/******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ 54:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.colorpicker-widget {
	height: 190px;
	user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}

/* Decoration */

.colorpicker-color-decoration,
.hc-light .colorpicker-color-decoration {
	border: solid 0.1em #000;
	box-sizing: border-box;
	margin: 0.1em 0.2em 0 0.2em;
	width: 0.8em;
	height: 0.8em;
	line-height: 0.8em;
	display: inline-block;
	cursor: pointer;
}

.hc-black .colorpicker-color-decoration,
.vs-dark .colorpicker-color-decoration {
	border: solid 0.1em #eee;
}

/* Header */

.colorpicker-header {
	display: flex;
	height: 24px;
	position: relative;
	background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAAHUlEQVQYV2PYvXu3JAi7uLiAMaYAjAGTQBPYLQkAa/0Zef3qRswAAAAASUVORK5CYII=");
	background-size: 9px 9px;
	image-rendering: pixelated;
}

.colorpicker-header .picked-color {
	width: 216px;
	display: flex;
	align-items: center;
	justify-content: center;
	line-height: 24px;
	cursor: pointer;
	color: white;
	flex: 1;
}

.colorpicker-header .picked-color .codicon {
	color: inherit;
	font-size: 14px;
	position: absolute;
	left: 8px;
}

.colorpicker-header .picked-color.light {
	color: black;
}

.colorpicker-header .original-color {
	width: 74px;
	z-index: inherit;
	cursor: pointer;
}


/* Body */

.colorpicker-body {
	display: flex;
	padding: 8px;
	position: relative;
}

.colorpicker-body .saturation-wrap {
	overflow: hidden;
	height: 150px;
	position: relative;
	min-width: 220px;
	flex: 1;
}

.colorpicker-body .saturation-box {
	height: 150px;
	position: absolute;
}

.colorpicker-body .saturation-selection {
	width: 9px;
	height: 9px;
	margin: -5px 0 0 -5px;
	border: 1px solid rgb(255, 255, 255);
	border-radius: 100%;
	box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.8);
	position: absolute;
}

.colorpicker-body .strip {
	width: 25px;
	height: 150px;
}

.colorpicker-body .hue-strip {
	position: relative;
	margin-left: 8px;
	cursor: grab;
	background: linear-gradient(to bottom, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
}

.colorpicker-body .opacity-strip {
	position: relative;
	margin-left: 8px;
	cursor: grab;
	background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAAHUlEQVQYV2PYvXu3JAi7uLiAMaYAjAGTQBPYLQkAa/0Zef3qRswAAAAASUVORK5CYII=");
	background-size: 9px 9px;
	image-rendering: pixelated;
}

.colorpicker-body .strip.grabbing {
	cursor: grabbing;
}

.colorpicker-body .slider {
	position: absolute;
	top: 0;
	left: -2px;
	width: calc(100% + 4px);
	height: 4px;
	box-sizing: border-box;
	border: 1px solid rgba(255, 255, 255, 0.71);
	box-shadow: 0px 0px 1px rgba(0, 0, 0, 0.85);
}

.colorpicker-body .strip .overlay {
	height: 150px;
	pointer-events: none;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/colorPicker/browser/colorPicker.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,aAAa;CACb,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;AACtB;;AAEA,eAAe;;AAEf;;CAEC,wBAAwB;CACxB,sBAAsB;CACtB,2BAA2B;CAC3B,YAAY;CACZ,aAAa;CACb,kBAAkB;CAClB,qBAAqB;CACrB,eAAe;AAChB;;AAEA;;CAEC,wBAAwB;AACzB;;AAEA,WAAW;;AAEX;CACC,aAAa;CACb,YAAY;CACZ,kBAAkB;CAClB,iRAAiR;CACjR,wBAAwB;CACxB,0BAA0B;AAC3B;;AAEA;CACC,YAAY;CACZ,aAAa;CACb,mBAAmB;CACnB,uBAAuB;CACvB,iBAAiB;CACjB,eAAe;CACf,YAAY;CACZ,OAAO;AACR;;AAEA;CACC,cAAc;CACd,eAAe;CACf,kBAAkB;CAClB,SAAS;AACV;;AAEA;CACC,YAAY;AACb;;AAEA;CACC,WAAW;CACX,gBAAgB;CAChB,eAAe;AAChB;;;AAGA,SAAS;;AAET;CACC,aAAa;CACb,YAAY;CACZ,kBAAkB;AACnB;;AAEA;CACC,gBAAgB;CAChB,aAAa;CACb,kBAAkB;CAClB,gBAAgB;CAChB,OAAO;AACR;;AAEA;CACC,aAAa;CACb,kBAAkB;AACnB;;AAEA;CACC,UAAU;CACV,WAAW;CACX,qBAAqB;CACrB,oCAAoC;CACpC,mBAAmB;CACnB,0CAA0C;CAC1C,kBAAkB;AACnB;;AAEA;CACC,WAAW;CACX,aAAa;AACd;;AAEA;CACC,kBAAkB;CAClB,gBAAgB;CAChB,YAAY;CACZ,iIAAiI;AAClI;;AAEA;CACC,kBAAkB;CAClB,gBAAgB;CAChB,YAAY;CACZ,iRAAiR;CACjR,wBAAwB;CACxB,0BAA0B;AAC3B;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,kBAAkB;CAClB,MAAM;CACN,UAAU;CACV,uBAAuB;CACvB,WAAW;CACX,sBAAsB;CACtB,2CAA2C;CAC3C,2CAA2C;AAC5C;;AAEA;CACC,aAAa;CACb,oBAAoB;AACrB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.colorpicker-widget {\n\theight: 190px;\n\tuser-select: none;\n\t-webkit-user-select: none;\n\t-ms-user-select: none;\n}\n\n/* Decoration */\n\n.colorpicker-color-decoration,\n.hc-light .colorpicker-color-decoration {\n\tborder: solid 0.1em #000;\n\tbox-sizing: border-box;\n\tmargin: 0.1em 0.2em 0 0.2em;\n\twidth: 0.8em;\n\theight: 0.8em;\n\tline-height: 0.8em;\n\tdisplay: inline-block;\n\tcursor: pointer;\n}\n\n.hc-black .colorpicker-color-decoration,\n.vs-dark .colorpicker-color-decoration {\n\tborder: solid 0.1em #eee;\n}\n\n/* Header */\n\n.colorpicker-header {\n\tdisplay: flex;\n\theight: 24px;\n\tposition: relative;\n\tbackground: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAAHUlEQVQYV2PYvXu3JAi7uLiAMaYAjAGTQBPYLQkAa/0Zef3qRswAAAAASUVORK5CYII=\");\n\tbackground-size: 9px 9px;\n\timage-rendering: pixelated;\n}\n\n.colorpicker-header .picked-color {\n\twidth: 216px;\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n\tline-height: 24px;\n\tcursor: pointer;\n\tcolor: white;\n\tflex: 1;\n}\n\n.colorpicker-header .picked-color .codicon {\n\tcolor: inherit;\n\tfont-size: 14px;\n\tposition: absolute;\n\tleft: 8px;\n}\n\n.colorpicker-header .picked-color.light {\n\tcolor: black;\n}\n\n.colorpicker-header .original-color {\n\twidth: 74px;\n\tz-index: inherit;\n\tcursor: pointer;\n}\n\n\n/* Body */\n\n.colorpicker-body {\n\tdisplay: flex;\n\tpadding: 8px;\n\tposition: relative;\n}\n\n.colorpicker-body .saturation-wrap {\n\toverflow: hidden;\n\theight: 150px;\n\tposition: relative;\n\tmin-width: 220px;\n\tflex: 1;\n}\n\n.colorpicker-body .saturation-box {\n\theight: 150px;\n\tposition: absolute;\n}\n\n.colorpicker-body .saturation-selection {\n\twidth: 9px;\n\theight: 9px;\n\tmargin: -5px 0 0 -5px;\n\tborder: 1px solid rgb(255, 255, 255);\n\tborder-radius: 100%;\n\tbox-shadow: 0px 0px 2px rgba(0, 0, 0, 0.8);\n\tposition: absolute;\n}\n\n.colorpicker-body .strip {\n\twidth: 25px;\n\theight: 150px;\n}\n\n.colorpicker-body .hue-strip {\n\tposition: relative;\n\tmargin-left: 8px;\n\tcursor: grab;\n\tbackground: linear-gradient(to bottom, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);\n}\n\n.colorpicker-body .opacity-strip {\n\tposition: relative;\n\tmargin-left: 8px;\n\tcursor: grab;\n\tbackground: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAAHUlEQVQYV2PYvXu3JAi7uLiAMaYAjAGTQBPYLQkAa/0Zef3qRswAAAAASUVORK5CYII=\");\n\tbackground-size: 9px 9px;\n\timage-rendering: pixelated;\n}\n\n.colorpicker-body .strip.grabbing {\n\tcursor: grabbing;\n}\n\n.colorpicker-body .slider {\n\tposition: absolute;\n\ttop: 0;\n\tleft: -2px;\n\twidth: calc(100% + 4px);\n\theight: 4px;\n\tbox-sizing: border-box;\n\tborder: 1px solid rgba(255, 255, 255, 0.71);\n\tbox-shadow: 0px 0px 1px rgba(0, 0, 0, 0.85);\n}\n\n.colorpicker-body .strip .overlay {\n\theight: 150px;\n\tpointer-events: none;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 112:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgHorizontalSplit = function SvgHorizontalSplit(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.63672 5.51464V11.25H19.6367V5.51464H4.63672ZM19.6367 12.75H4.63672V18.4854H19.6367V12.75ZM3.13672 5.4224C3.13672 4.55548 3.90378 4.01464 4.63672 4.01464H19.6367C20.3697 4.01464 21.1367 4.55548 21.1367 5.4224V18.5776C21.1367 19.4445 20.3697 19.9854 19.6367 19.9854H4.63672C3.90378 19.9854 3.13672 19.4445 3.13672 18.5776V5.4224Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgHorizontalSplit);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "62374e2c59679f2eb437c87be8391638.svg");

/***/ }),

/***/ 227:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var View = __webpack_require__(92207),
  ConfirmModalTemplate = __webpack_require__(51766);

function ConfirmModal(args) {
  View.call(this);

  this.title = args.title || 'Confirm';
  this.message = args.message;
  this.confirmLabel = args.confirmLabel || 'Confirm';
  this.cancelLabel = args.cancelLabel || 'Cancel';

  this.onConfirm = args.onConfirm;
  this.onCancel = args.onCancel;
}

ConfirmModal.prototype = Object.create(View.prototype);

ConfirmModal.prototype.render = function () {
  var el = this.bindView($(ConfirmModalTemplate), this);
  if (this.el) this.el.append(el);
  else this.el = el;

  return this.el;
};

ConfirmModal.prototype.onConfirmClicked = function (scope, el, evt) {
  this.onConfirm && this.onConfirm();
  evt.stopPropagation();
};

ConfirmModal.prototype.onCancelClicked = function (scope, el, evt) {
  this.onCancel && this.onCancel();
  evt.stopPropagation();
};

module.exports = ConfirmModal;


/***/ }),

/***/ 368:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.EasyMode-module__Root--lSYH0{width:100%;height:100%;overflow-y:auto;padding:12px;background-color:var(--theme-color-bg-2);border-radius:4px;font-family:"Menlo","Monaco","Courier New",monospace;font-size:13px}.EasyMode-module__EmptyState--BkaCa{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:150px;padding:24px;text-align:center}.EasyMode-module__EmptyIcon--Ed1Hw{font-size:48px;margin-bottom:12px;opacity:.5}.EasyMode-module__EmptyText--kyC2q{font-size:13px;color:var(--theme-color-fg-muted)}.EasyMode-module__TreeNode--yltst{margin-bottom:4px}.EasyMode-module__NodeHeader--bnJTH{display:flex;align-items:center;gap:6px;padding:6px 8px;border-radius:3px;transition:background-color .15s ease}.EasyMode-module__NodeHeader--bnJTH:hover{background-color:var(--theme-color-bg-3)}.EasyMode-module__Key--dBLMv{color:var(--theme-color-primary);font-weight:500}.EasyMode-module__Index--DJ8tg{color:var(--theme-color-fg-muted);font-weight:500}.EasyMode-module__Colon--al1u3{color:var(--theme-color-fg-muted)}.EasyMode-module__TypeBadge--rfJRz{display:inline-block;padding:2px 6px;font-size:10px;font-weight:600;text-transform:uppercase;border-radius:3px;letter-spacing:.5px;background-color:var(--theme-color-bg-3);color:var(--theme-color-fg-muted);border:1px solid var(--theme-color-border-default)}.EasyMode-module__TypeBadge--rfJRz[data-type=string]{background-color:rgba(59,130,246,.1019607843);color:#3b82f6;border-color:rgba(59,130,246,.3019607843)}.EasyMode-module__TypeBadge--rfJRz[data-type=number]{background-color:rgba(16,185,129,.1019607843);color:#10b981;border-color:rgba(16,185,129,.3019607843)}.EasyMode-module__TypeBadge--rfJRz[data-type=boolean]{background-color:rgba(245,158,11,.1019607843);color:#f59e0b;border-color:rgba(245,158,11,.3019607843)}.EasyMode-module__TypeBadge--rfJRz[data-type=null]{background-color:rgba(107,114,128,.1019607843);color:#6b7280;border-color:rgba(107,114,128,.3019607843)}.EasyMode-module__TypeBadge--rfJRz[data-type=array]{background-color:rgba(139,92,246,.1019607843);color:#8b5cf6;border-color:rgba(139,92,246,.3019607843)}.EasyMode-module__TypeBadge--rfJRz[data-type=object]{background-color:rgba(236,72,153,.1019607843);color:#ec4899;border-color:rgba(236,72,153,.3019607843)}.EasyMode-module__Value--ab72b{color:var(--theme-color-fg-default);font-family:inherit}.EasyMode-module__Value--ab72b[data-type=string]{color:#3b82f6}.EasyMode-module__Value--ab72b[data-type=number]{color:#10b981}.EasyMode-module__Value--ab72b[data-type=boolean]{color:#f59e0b}.EasyMode-module__Value--ab72b[data-type=null]{color:#6b7280;font-style:italic}.EasyMode-module__Count--S2G58{font-size:11px;color:var(--theme-color-fg-muted);font-weight:400}.EasyMode-module__Children--WcqOk{margin-left:0;border-left:1px solid var(--theme-color-border-default);padding-left:8px;margin-top:2px}.EasyMode-module__EditButton--yFyYy,.EasyMode-module__AddButton--hTtxC,.EasyMode-module__DeleteButton--yAqlm{padding:2px 8px;font-size:12px;font-weight:500;border:none;border-radius:3px;cursor:pointer;transition:all .15s ease;margin-left:6px}.EasyMode-module__EditButton--yFyYy{background-color:var(--theme-color-bg-3);color:var(--theme-color-primary)}.EasyMode-module__EditButton--yFyYy:hover{background-color:var(--theme-color-primary);color:#fff}.EasyMode-module__AddButton--hTtxC{background-color:var(--theme-color-primary);color:#fff;font-size:11px}.EasyMode-module__AddButton--hTtxC:hover{opacity:.9}.EasyMode-module__DeleteButton--yAqlm{background-color:#dc2626;color:#fff;font-size:14px;font-weight:bold;line-height:1}.EasyMode-module__DeleteButton--yAqlm:hover{background-color:#b91c1c}.EasyMode-module__AddItemForm--cgivw{display:flex;align-items:center;gap:8px;padding:8px;margin:4px 0;background-color:var(--theme-color-bg-3);border-radius:4px;border:1px solid var(--theme-color-border-default)}.EasyMode-module__AddItemForm--cgivw input[type=text]{flex:1;padding:4px 8px;font-size:13px;background-color:var(--theme-color-bg-1);border:1px solid var(--theme-color-border-default);border-radius:3px;color:var(--theme-color-fg-default)}.EasyMode-module__AddItemForm--cgivw input[type=text]::placeholder{color:var(--theme-color-fg-muted)}.EasyMode-module__AddItemForm--cgivw select{padding:4px 8px;font-size:13px;background-color:var(--theme-color-bg-1);border:1px solid var(--theme-color-border-default);border-radius:3px;color:var(--theme-color-fg-default);cursor:pointer}.EasyMode-module__AddItemForm--cgivw button{padding:4px 12px;font-size:12px;font-weight:500;border:none;border-radius:3px;cursor:pointer;transition:all .15s ease}.EasyMode-module__AddItemForm--cgivw button:first-of-type{background-color:var(--theme-color-primary);color:#fff}.EasyMode-module__AddItemForm--cgivw button:first-of-type:hover:not(:disabled){opacity:.9}.EasyMode-module__AddItemForm--cgivw button:first-of-type:disabled{opacity:.5;cursor:not-allowed}.EasyMode-module__AddItemForm--cgivw button:last-of-type{background-color:var(--theme-color-bg-2);color:var(--theme-color-fg-default);border:1px solid var(--theme-color-border-default)}.EasyMode-module__AddItemForm--cgivw button:last-of-type:hover{background-color:var(--theme-color-bg-1)}.EasyMode-module__Value--ab72b{cursor:pointer}.EasyMode-module__Value--ab72b:hover{text-decoration:underline}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/json-editor/modes/EasyMode/EasyMode.module.scss"],"names":[],"mappings":"AAKA,8BACE,UAAA,CACA,WAAA,CACA,eAAA,CACA,YAAA,CACA,wCAAA,CACA,iBAAA,CACA,oDAAA,CACA,cAAA,CAIF,oCACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,gBAAA,CACA,YAAA,CACA,iBAAA,CAGF,mCACE,cAAA,CACA,kBAAA,CACA,UAAA,CAGF,mCACE,cAAA,CACA,iCAAA,CAIF,kCACE,iBAAA,CAGF,oCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,eAAA,CACA,iBAAA,CACA,qCAAA,CAEA,0CACE,wCAAA,CAKJ,6BACE,gCAAA,CACA,eAAA,CAGF,+BACE,iCAAA,CACA,eAAA,CAGF,+BACE,iCAAA,CAIF,mCACE,oBAAA,CACA,eAAA,CACA,cAAA,CACA,eAAA,CACA,wBAAA,CACA,iBAAA,CACA,mBAAA,CACA,wCAAA,CACA,iCAAA,CACA,kDAAA,CAEA,qDACE,6CAAA,CACA,aAAA,CACA,yCAAA,CAGF,qDACE,6CAAA,CACA,aAAA,CACA,yCAAA,CAGF,sDACE,6CAAA,CACA,aAAA,CACA,yCAAA,CAGF,mDACE,8CAAA,CACA,aAAA,CACA,0CAAA,CAGF,oDACE,6CAAA,CACA,aAAA,CACA,yCAAA,CAGF,qDACE,6CAAA,CACA,aAAA,CACA,yCAAA,CAKJ,+BACE,mCAAA,CACA,mBAAA,CAEA,iDACE,aAAA,CAGF,iDACE,aAAA,CAGF,kDACE,aAAA,CAGF,+CACE,aAAA,CACA,iBAAA,CAKJ,+BACE,cAAA,CACA,iCAAA,CACA,eAAA,CAIF,kCACE,aAAA,CACA,uDAAA,CACA,gBAAA,CACA,cAAA,CAIF,6GAGE,eAAA,CACA,cAAA,CACA,eAAA,CACA,WAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CACA,eAAA,CAGF,oCACE,wCAAA,CACA,gCAAA,CAEA,0CACE,2CAAA,CACA,UAAA,CAIJ,mCACE,2CAAA,CACA,UAAA,CACA,cAAA,CAEA,yCACE,UAAA,CAIJ,sCACE,wBAAA,CACA,UAAA,CACA,cAAA,CACA,gBAAA,CACA,aAAA,CAEA,4CACE,wBAAA,CAKJ,qCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,WAAA,CACA,YAAA,CACA,wCAAA,CACA,iBAAA,CACA,kDAAA,CAEA,sDACE,MAAA,CACA,eAAA,CACA,cAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CAEA,mEACE,iCAAA,CAIJ,4CACE,eAAA,CACA,cAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CAGF,4CACE,gBAAA,CACA,cAAA,CACA,eAAA,CACA,WAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CAEA,0DACE,2CAAA,CACA,UAAA,CAEA,+EACE,UAAA,CAGF,mEACE,UAAA,CACA,kBAAA,CAIJ,yDACE,wCAAA,CACA,mCAAA,CACA,kDAAA,CAEA,+DACE,wCAAA,CAOR,+BACE,cAAA,CAEA,qCACE,yBAAA","sourcesContent":["/**\n * Easy Mode Styles\n * Uses design tokens for consistency with OpenNoodl design system\n */\n\n.Root {\n  width: 100%;\n  height: 100%;\n  overflow-y: auto;\n  padding: 12px;\n  background-color: var(--theme-color-bg-2);\n  border-radius: 4px;\n  font-family: 'Menlo', 'Monaco', 'Courier New', monospace;\n  font-size: 13px;\n}\n\n/* Empty State */\n.EmptyState {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  min-height: 150px;\n  padding: 24px;\n  text-align: center;\n}\n\n.EmptyIcon {\n  font-size: 48px;\n  margin-bottom: 12px;\n  opacity: 0.5;\n}\n\n.EmptyText {\n  font-size: 13px;\n  color: var(--theme-color-fg-muted);\n}\n\n/* Tree Node */\n.TreeNode {\n  margin-bottom: 4px;\n}\n\n.NodeHeader {\n  display: flex;\n  align-items: center;\n  gap: 6px;\n  padding: 6px 8px;\n  border-radius: 3px;\n  transition: background-color 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n/* Node Labels */\n.Key {\n  color: var(--theme-color-primary);\n  font-weight: 500;\n}\n\n.Index {\n  color: var(--theme-color-fg-muted);\n  font-weight: 500;\n}\n\n.Colon {\n  color: var(--theme-color-fg-muted);\n}\n\n/* Type Badge */\n.TypeBadge {\n  display: inline-block;\n  padding: 2px 6px;\n  font-size: 10px;\n  font-weight: 600;\n  text-transform: uppercase;\n  border-radius: 3px;\n  letter-spacing: 0.5px;\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-muted);\n  border: 1px solid var(--theme-color-border-default);\n\n  &[data-type='string'] {\n    background-color: #3b82f61a;\n    color: #3b82f6;\n    border-color: #3b82f64d;\n  }\n\n  &[data-type='number'] {\n    background-color: #10b9811a;\n    color: #10b981;\n    border-color: #10b9814d;\n  }\n\n  &[data-type='boolean'] {\n    background-color: #f59e0b1a;\n    color: #f59e0b;\n    border-color: #f59e0b4d;\n  }\n\n  &[data-type='null'] {\n    background-color: #6b72801a;\n    color: #6b7280;\n    border-color: #6b72804d;\n  }\n\n  &[data-type='array'] {\n    background-color: #8b5cf61a;\n    color: #8b5cf6;\n    border-color: #8b5cf64d;\n  }\n\n  &[data-type='object'] {\n    background-color: #ec48991a;\n    color: #ec4899;\n    border-color: #ec48994d;\n  }\n}\n\n/* Value Display */\n.Value {\n  color: var(--theme-color-fg-default);\n  font-family: inherit;\n\n  &[data-type='string'] {\n    color: #3b82f6;\n  }\n\n  &[data-type='number'] {\n    color: #10b981;\n  }\n\n  &[data-type='boolean'] {\n    color: #f59e0b;\n  }\n\n  &[data-type='null'] {\n    color: #6b7280;\n    font-style: italic;\n  }\n}\n\n/* Count Badge */\n.Count {\n  font-size: 11px;\n  color: var(--theme-color-fg-muted);\n  font-weight: 400;\n}\n\n/* Children Container */\n.Children {\n  margin-left: 0;\n  border-left: 1px solid var(--theme-color-border-default);\n  padding-left: 8px;\n  margin-top: 2px;\n}\n\n/* Action Buttons */\n.EditButton,\n.AddButton,\n.DeleteButton {\n  padding: 2px 8px;\n  font-size: 12px;\n  font-weight: 500;\n  border: none;\n  border-radius: 3px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n  margin-left: 6px;\n}\n\n.EditButton {\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-primary);\n\n  &:hover {\n    background-color: var(--theme-color-primary);\n    color: white;\n  }\n}\n\n.AddButton {\n  background-color: var(--theme-color-primary);\n  color: white;\n  font-size: 11px;\n\n  &:hover {\n    opacity: 0.9;\n  }\n}\n\n.DeleteButton {\n  background-color: #dc2626;\n  color: white;\n  font-size: 14px;\n  font-weight: bold;\n  line-height: 1;\n\n  &:hover {\n    background-color: #b91c1c;\n  }\n}\n\n/* Add Item Form */\n.AddItemForm {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 8px;\n  margin: 4px 0;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 4px;\n  border: 1px solid var(--theme-color-border-default);\n\n  input[type='text'] {\n    flex: 1;\n    padding: 4px 8px;\n    font-size: 13px;\n    background-color: var(--theme-color-bg-1);\n    border: 1px solid var(--theme-color-border-default);\n    border-radius: 3px;\n    color: var(--theme-color-fg-default);\n\n    &::placeholder {\n      color: var(--theme-color-fg-muted);\n    }\n  }\n\n  select {\n    padding: 4px 8px;\n    font-size: 13px;\n    background-color: var(--theme-color-bg-1);\n    border: 1px solid var(--theme-color-border-default);\n    border-radius: 3px;\n    color: var(--theme-color-fg-default);\n    cursor: pointer;\n  }\n\n  button {\n    padding: 4px 12px;\n    font-size: 12px;\n    font-weight: 500;\n    border: none;\n    border-radius: 3px;\n    cursor: pointer;\n    transition: all 0.15s ease;\n\n    &:first-of-type {\n      background-color: var(--theme-color-primary);\n      color: white;\n\n      &:hover:not(:disabled) {\n        opacity: 0.9;\n      }\n\n      &:disabled {\n        opacity: 0.5;\n        cursor: not-allowed;\n      }\n    }\n\n    &:last-of-type {\n      background-color: var(--theme-color-bg-2);\n      color: var(--theme-color-fg-default);\n      border: 1px solid var(--theme-color-border-default);\n\n      &:hover {\n        background-color: var(--theme-color-bg-1);\n      }\n    }\n  }\n}\n\n/* Clickable value for editing */\n.Value {\n  cursor: pointer;\n\n  &:hover {\n    text-decoration: underline;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `EasyMode-module__Root--lSYH0`,
	"EmptyState": `EasyMode-module__EmptyState--BkaCa`,
	"EmptyIcon": `EasyMode-module__EmptyIcon--Ed1Hw`,
	"EmptyText": `EasyMode-module__EmptyText--kyC2q`,
	"TreeNode": `EasyMode-module__TreeNode--yltst`,
	"NodeHeader": `EasyMode-module__NodeHeader--bnJTH`,
	"Key": `EasyMode-module__Key--dBLMv`,
	"Index": `EasyMode-module__Index--DJ8tg`,
	"Colon": `EasyMode-module__Colon--al1u3`,
	"TypeBadge": `EasyMode-module__TypeBadge--rfJRz`,
	"Value": `EasyMode-module__Value--ab72b`,
	"Count": `EasyMode-module__Count--S2G58`,
	"Children": `EasyMode-module__Children--WcqOk`,
	"EditButton": `EasyMode-module__EditButton--yFyYy`,
	"AddButton": `EasyMode-module__AddButton--hTtxC`,
	"DeleteButton": `EasyMode-module__DeleteButton--yAqlm`,
	"AddItemForm": `EasyMode-module__AddItemForm--cgivw`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 563:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.lessonlayerview {
  background-color: var(--theme-color-bg-2);
}

.lesson-layer-progressbar {
  margin-top: 2px;
  height: 4px;
}

.lesson-layer-progressbar-fill {
  background-color: var(--theme-color-primary);
  height: 100%;
  /* width is being calculated as a percentage based on how many steps are completed */
  transition: width 500ms;
}

.lesson-bottombar {
}

.lesson-steps {
  height: 80px;
  display: flex;
  overflow-x: auto;
}

.lesson-steps::-webkit-scrollbar {
  display: none;
}

.lesson-item {
  box-sizing: border-box;
  width: 230px;
  padding: 8px 16px;
  color: rgba(240, 247, 249, 0.5);
  border-left: 1px solid var(--theme-color-bg-1);
  flex-shrink: 0;
  overflow: hidden;
  background-color: var(--theme-color-secondary-dim);
  cursor: pointer;
  transition: background-color 200ms, opacity 200ms;
}

.lesson-item:not(.selected):not(.completed) {
  /* background-color: #2D5F6C; */
  color: var(--theme-color-fg-muted);
  background-color: var(--theme-color-bg-3);
  pointer-events: none;
}

.lesson-item.selected {
  background-color: var(--theme-color-bg-4);
  color: var(--theme-color-fg-highlight);
  opacity: 1;
  transition: background-color 200ms, opacity 200ms;
}

.lesson-item.selected:hover {
  color: var(--theme-color-secondary-bright);
}

.lesson-item .lesson-checkmark {
  content: url('../assets/icons/lesson-check-incomplete.svg');
  margin-left: auto;
  height: 16px;
}

.lesson-item:not(.completed):not(.selected) .lesson-checkmark {
  height: 16px;
}

.lesson-item:not(.completed) .lesson-checkmark {
  height: 21px;
}

.lesson-item:not(.completed).selected header {
  margin-top: -3px;
}

.lesson-item.completed .lesson-checkmark {
  content: url('../assets/icons/lesson-check-complete.svg');
}

.lesson-item.selected .lesson-checkmark {
  content: url('../assets/icons/lesson-check-incomplete-selected.svg');
}

.lesson-item.selected:hover .lesson-checkmark {
  content: url('../assets/icons/lesson-check-incomplete-selected-hover.svg');
}

.lesson-item header {
  margin-bottom: 6px;
  display: flex;
  flex-direction: row;
  align-items: center;
  font-weight: 600;
}

.lesson-item h2,
.lesson-item h3 {
  margin: 0;
  line-height: 1.2;
}

.lesson-item h2 strong,
.lesson-item h3 strong {
  font-weight: var(--font-weight-bold);
}

.lesson-item h2 i,
.lesson-item h3 i {
  font-style: italic;
}

.lesson-item h2 {
  font-size: 18px;
  margin-top: -2px;
  font-weight: var(--font-weight-medium);
}

.lesson-item h3 {
  font-size: 14px;
  font-weight: var(--font-weight-medium);
}

.lesson-item p {
  margin: 0;
}

.lesson-item-popup {
  background-color: var(--theme-color-bg-3);
  width: 512px;
  color: var(--theme-color-fg-highlight);
  padding: 8px;
}

.lesson-item-popup img,
.lesson-item-popup video {
  width: 100%;
  display: block;
}

.lesson-item-popup video::-webkit-media-controls-fullscreen-button,
.lesson-item-popup video::-webkit-media-controls-mute-button {
  display: none;
}

.lesson-item-popup h2,
.lesson-item-popup h3,
.lesson-item-popup p {
  margin-left: 24px;
  margin-right: 24px;
}

.lesson-item-popup h2 {
  font-weight: var(--font-weight-semibold);
  font-size: 21px;
  margin-top: 24px;
}

.lesson-item-popup p {
  font-weight: var(--font-weight-light);
  color: var(--theme-color-fg-highlight);
  font-size: 14px;
  line-height: 21px;
}

.lesson-item-popup p strong {
  font-weight: var(--font-weight-semibold);
}

.lesson-item-popup p i {
  font-style: italic;
}

.lesson-item-popup button {
  margin-right: 24px;
  background-color: var(--theme-color-primary);
  border: none;
  height: 26px;
  width: 90px;
  float: right;
  font-weight: bold;
  font-size: 11px;
  margin-top: 24px;
  margin-bottom: 16px;
  color: var(--theme-color-on-primary);
}

.lesson-item-popup button:hover {
  background-color: var(--theme-color-primary-highlight);
}

.lesson-item-popup {
  width: auto;
}

.lesson-item-popup [data-template='popup'] {
  display: flex;
}

.lesson-item-popup .popup-media video,
.lesson-item-popup .popup-media img {
  width: 720px;
}

.lesson-item-popup .popup-content-wrapper {
  width: 300px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/views/lessons/LessonLayerView.css"],"names":[],"mappings":"AAAA;EACE,yCAAyC;AAC3C;;AAEA;EACE,eAAe;EACf,WAAW;AACb;;AAEA;EACE,4CAA4C;EAC5C,YAAY;EACZ,oFAAoF;EACpF,uBAAuB;AACzB;;AAEA;AACA;;AAEA;EACE,YAAY;EACZ,aAAa;EACb,gBAAgB;AAClB;;AAEA;EACE,aAAa;AACf;;AAEA;EACE,sBAAsB;EACtB,YAAY;EACZ,iBAAiB;EACjB,+BAA+B;EAC/B,8CAA8C;EAC9C,cAAc;EACd,gBAAgB;EAChB,kDAAkD;EAClD,eAAe;EACf,iDAAiD;AACnD;;AAEA;EACE,+BAA+B;EAC/B,kCAAkC;EAClC,yCAAyC;EACzC,oBAAoB;AACtB;;AAEA;EACE,yCAAyC;EACzC,sCAAsC;EACtC,UAAU;EACV,iDAAiD;AACnD;;AAEA;EACE,0CAA0C;AAC5C;;AAEA;EACE,2DAA2D;EAC3D,iBAAiB;EACjB,YAAY;AACd;;AAEA;EACE,YAAY;AACd;;AAEA;EACE,YAAY;AACd;;AAEA;EACE,gBAAgB;AAClB;;AAEA;EACE,yDAAyD;AAC3D;;AAEA;EACE,oEAAoE;AACtE;;AAEA;EACE,0EAA0E;AAC5E;;AAEA;EACE,kBAAkB;EAClB,aAAa;EACb,mBAAmB;EACnB,mBAAmB;EACnB,gBAAgB;AAClB;;AAEA;;EAEE,SAAS;EACT,gBAAgB;AAClB;;AAEA;;EAEE,oCAAoC;AACtC;;AAEA;;EAEE,kBAAkB;AACpB;;AAEA;EACE,eAAe;EACf,gBAAgB;EAChB,sCAAsC;AACxC;;AAEA;EACE,eAAe;EACf,sCAAsC;AACxC;;AAEA;EACE,SAAS;AACX;;AAEA;EACE,yCAAyC;EACzC,YAAY;EACZ,sCAAsC;EACtC,YAAY;AACd;;AAEA;;EAEE,WAAW;EACX,cAAc;AAChB;;AAEA;;EAEE,aAAa;AACf;;AAEA;;;EAGE,iBAAiB;EACjB,kBAAkB;AACpB;;AAEA;EACE,wCAAwC;EACxC,eAAe;EACf,gBAAgB;AAClB;;AAEA;EACE,qCAAqC;EACrC,sCAAsC;EACtC,eAAe;EACf,iBAAiB;AACnB;;AAEA;EACE,wCAAwC;AAC1C;;AAEA;EACE,kBAAkB;AACpB;;AAEA;EACE,kBAAkB;EAClB,4CAA4C;EAC5C,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,iBAAiB;EACjB,eAAe;EACf,gBAAgB;EAChB,mBAAmB;EACnB,oCAAoC;AACtC;;AAEA;EACE,sDAAsD;AACxD;;AAEA;EACE,WAAW;AACb;;AAEA;EACE,aAAa;AACf;;AAEA;;EAEE,YAAY;AACd;;AAEA;EACE,YAAY;EACZ,aAAa;EACb,sBAAsB;EACtB,8BAA8B;AAChC","sourcesContent":[".lessonlayerview {\n  background-color: var(--theme-color-bg-2);\n}\n\n.lesson-layer-progressbar {\n  margin-top: 2px;\n  height: 4px;\n}\n\n.lesson-layer-progressbar-fill {\n  background-color: var(--theme-color-primary);\n  height: 100%;\n  /* width is being calculated as a percentage based on how many steps are completed */\n  transition: width 500ms;\n}\n\n.lesson-bottombar {\n}\n\n.lesson-steps {\n  height: 80px;\n  display: flex;\n  overflow-x: auto;\n}\n\n.lesson-steps::-webkit-scrollbar {\n  display: none;\n}\n\n.lesson-item {\n  box-sizing: border-box;\n  width: 230px;\n  padding: 8px 16px;\n  color: rgba(240, 247, 249, 0.5);\n  border-left: 1px solid var(--theme-color-bg-1);\n  flex-shrink: 0;\n  overflow: hidden;\n  background-color: var(--theme-color-secondary-dim);\n  cursor: pointer;\n  transition: background-color 200ms, opacity 200ms;\n}\n\n.lesson-item:not(.selected):not(.completed) {\n  /* background-color: #2D5F6C; */\n  color: var(--theme-color-fg-muted);\n  background-color: var(--theme-color-bg-3);\n  pointer-events: none;\n}\n\n.lesson-item.selected {\n  background-color: var(--theme-color-bg-4);\n  color: var(--theme-color-fg-highlight);\n  opacity: 1;\n  transition: background-color 200ms, opacity 200ms;\n}\n\n.lesson-item.selected:hover {\n  color: var(--theme-color-secondary-bright);\n}\n\n.lesson-item .lesson-checkmark {\n  content: url('../assets/icons/lesson-check-incomplete.svg');\n  margin-left: auto;\n  height: 16px;\n}\n\n.lesson-item:not(.completed):not(.selected) .lesson-checkmark {\n  height: 16px;\n}\n\n.lesson-item:not(.completed) .lesson-checkmark {\n  height: 21px;\n}\n\n.lesson-item:not(.completed).selected header {\n  margin-top: -3px;\n}\n\n.lesson-item.completed .lesson-checkmark {\n  content: url('../assets/icons/lesson-check-complete.svg');\n}\n\n.lesson-item.selected .lesson-checkmark {\n  content: url('../assets/icons/lesson-check-incomplete-selected.svg');\n}\n\n.lesson-item.selected:hover .lesson-checkmark {\n  content: url('../assets/icons/lesson-check-incomplete-selected-hover.svg');\n}\n\n.lesson-item header {\n  margin-bottom: 6px;\n  display: flex;\n  flex-direction: row;\n  align-items: center;\n  font-weight: 600;\n}\n\n.lesson-item h2,\n.lesson-item h3 {\n  margin: 0;\n  line-height: 1.2;\n}\n\n.lesson-item h2 strong,\n.lesson-item h3 strong {\n  font-weight: var(--font-weight-bold);\n}\n\n.lesson-item h2 i,\n.lesson-item h3 i {\n  font-style: italic;\n}\n\n.lesson-item h2 {\n  font-size: 18px;\n  margin-top: -2px;\n  font-weight: var(--font-weight-medium);\n}\n\n.lesson-item h3 {\n  font-size: 14px;\n  font-weight: var(--font-weight-medium);\n}\n\n.lesson-item p {\n  margin: 0;\n}\n\n.lesson-item-popup {\n  background-color: var(--theme-color-bg-3);\n  width: 512px;\n  color: var(--theme-color-fg-highlight);\n  padding: 8px;\n}\n\n.lesson-item-popup img,\n.lesson-item-popup video {\n  width: 100%;\n  display: block;\n}\n\n.lesson-item-popup video::-webkit-media-controls-fullscreen-button,\n.lesson-item-popup video::-webkit-media-controls-mute-button {\n  display: none;\n}\n\n.lesson-item-popup h2,\n.lesson-item-popup h3,\n.lesson-item-popup p {\n  margin-left: 24px;\n  margin-right: 24px;\n}\n\n.lesson-item-popup h2 {\n  font-weight: var(--font-weight-semibold);\n  font-size: 21px;\n  margin-top: 24px;\n}\n\n.lesson-item-popup p {\n  font-weight: var(--font-weight-light);\n  color: var(--theme-color-fg-highlight);\n  font-size: 14px;\n  line-height: 21px;\n}\n\n.lesson-item-popup p strong {\n  font-weight: var(--font-weight-semibold);\n}\n\n.lesson-item-popup p i {\n  font-style: italic;\n}\n\n.lesson-item-popup button {\n  margin-right: 24px;\n  background-color: var(--theme-color-primary);\n  border: none;\n  height: 26px;\n  width: 90px;\n  float: right;\n  font-weight: bold;\n  font-size: 11px;\n  margin-top: 24px;\n  margin-bottom: 16px;\n  color: var(--theme-color-on-primary);\n}\n\n.lesson-item-popup button:hover {\n  background-color: var(--theme-color-primary-highlight);\n}\n\n.lesson-item-popup {\n  width: auto;\n}\n\n.lesson-item-popup [data-template='popup'] {\n  display: flex;\n}\n\n.lesson-item-popup .popup-media video,\n.lesson-item-popup .popup-media img {\n  width: 720px;\n}\n\n.lesson-item-popup .popup-content-wrapper {\n  width: 300px;\n  display: flex;\n  flex-direction: column;\n  justify-content: space-between;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 667:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.context-view {
	position: absolute;
}

.context-view.fixed {
	all: initial;
	font-family: inherit;
	font-size: 13px;
	position: fixed;
	color: inherit;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/contextview/contextview.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kBAAkB;AACnB;;AAEA;CACC,YAAY;CACZ,oBAAoB;CACpB,eAAe;CACf,eAAe;CACf,cAAc;AACf","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.context-view {\n\tposition: absolute;\n}\n\n.context-view.fixed {\n\tall: initial;\n\tfont-family: inherit;\n\tfont-size: 13px;\n\tposition: fixed;\n\tcolor: inherit;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 1082:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* unused harmony export ReactComponent */
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = (/* unused pure expression or super */ null && (["title", "titleId"]));
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgComponentNodegraph = function SvgComponentNodegraph(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/React.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/React.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/React.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.73087 13.2163C4.05911 12.5445 4.05911 11.4554 4.73087 10.7837L10.7835 4.73102C11.4553 4.05926 12.5444 4.05927 13.2161 4.73102L19.2688 10.7837C19.9405 11.4554 19.9405 12.5445 19.2688 13.2163L13.2161 19.2689C12.5444 19.9407 11.4553 19.9407 10.7835 19.2689L4.73087 13.2163ZM5.77342 11.8262C5.67746 11.9222 5.67746 12.0778 5.77342 12.1737L11.8261 18.2264C11.922 18.3224 12.0776 18.3224 12.1736 18.2264L18.2262 12.1737C18.3222 12.0778 18.3222 11.9222 18.2262 11.8262L12.1736 5.77358C12.0776 5.67761 11.922 5.67761 11.8261 5.77358L5.77342 11.8262Z",
    fill: "#cfd5de"
  })));
};
var ForwardRef = /*#__PURE__*/(/* unused pure expression or super */ null && (forwardRef(SvgComponentNodegraph)));

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "8e4265f13ba3ce875545f42df9c69dee.svg");

/***/ }),

/***/ 1197:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Container-module__Root--kNExX{display:flex}.Container-module__Root--kNExX.Container-module__is-direction-horizontal--FIsJq{flex-direction:row;align-items:center}.Container-module__Root--kNExX.Container-module__is-direction-vertical--vnCrJ{flex-direction:column}.Container-module__Root--kNExX.Container-module__is-fill--i7BP_{width:100%;height:100%}.Container-module__Root--kNExX.Container-module__has-left-spacing--nI5Wo{margin-left:15px}.Container-module__Root--kNExX.Container-module__has-right-spacing--w9qsr{margin-right:15px}.Container-module__Root--kNExX.Container-module__has-top-spacing--mU1oT{margin-top:15px}.Container-module__Root--kNExX.Container-module__has-bottom-spacing--R5Gjc{margin-bottom:15px}.Container-module__Root--kNExX.Container-module__has-space-between--ORfwA{justify-content:space-between}.Container-module__Root--kNExX.Container-module__has-space-between--ORfwA.Container-module__is-direction-vertical--vnCrJ{height:100%}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/Container/Container.module.scss"],"names":[],"mappings":"AAAA,+BACE,YAAA,CAEA,gFACE,kBAAA,CACA,kBAAA,CAGF,8EACE,qBAAA,CAGF,gEACE,UAAA,CACA,WAAA,CAGF,yEACE,gBAAA,CAGF,0EACE,iBAAA,CAGF,wEACE,eAAA,CAGF,2EACE,kBAAA,CAGF,0EACE,6BAAA,CAGF,yHACE,WAAA","sourcesContent":[".Root {\n  display: flex;\n\n  &.is-direction-horizontal {\n    flex-direction: row;\n    align-items: center;\n  }\n\n  &.is-direction-vertical {\n    flex-direction: column;\n  }\n\n  &.is-fill {\n    width: 100%;\n    height: 100%;\n  }\n\n  &.has-left-spacing {\n    margin-left: 15px;\n  }\n\n  &.has-right-spacing {\n    margin-right: 15px;\n  }\n\n  &.has-top-spacing {\n    margin-top: 15px;\n  }\n\n  &.has-bottom-spacing {\n    margin-bottom: 15px;\n  }\n\n  &.has-space-between {\n    justify-content: space-between;\n  }\n\n  &.has-space-between.is-direction-vertical {\n    height: 100%;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Container-module__Root--kNExX`,
	"is-direction-horizontal": `Container-module__is-direction-horizontal--FIsJq`,
	"is-direction-vertical": `Container-module__is-direction-vertical--vnCrJ`,
	"is-fill": `Container-module__is-fill--i7BP_`,
	"has-left-spacing": `Container-module__has-left-spacing--nI5Wo`,
	"has-right-spacing": `Container-module__has-right-spacing--w9qsr`,
	"has-top-spacing": `Container-module__has-top-spacing--mU1oT`,
	"has-bottom-spacing": `Container-module__has-bottom-spacing--R5Gjc`,
	"has-space-between": `Container-module__has-space-between--ORfwA`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 1407:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

!function(e,t){ true?module.exports=t(__webpack_require__(54953)):0}(this,(e=>(()=>{var t={9735:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"apathy",author:"jannik siebert (https://github.com/janniks)",base00:"#031A16",base01:"#0B342D",base02:"#184E45",base03:"#2B685E",base04:"#5F9C92",base05:"#81B5AC",base06:"#A7CEC8",base07:"#D2E7E4",base08:"#3E9688",base09:"#3E7996",base0A:"#3E4C96",base0B:"#883E96",base0C:"#963E4C",base0D:"#96883E",base0E:"#4C963E",base0F:"#3E965B"},e.exports=t.default},294:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"ashes",author:"jannik siebert (https://github.com/janniks)",base00:"#1C2023",base01:"#393F45",base02:"#565E65",base03:"#747C84",base04:"#ADB3BA",base05:"#C7CCD1",base06:"#DFE2E5",base07:"#F3F4F5",base08:"#C7AE95",base09:"#C7C795",base0A:"#AEC795",base0B:"#95C7AE",base0C:"#95AEC7",base0D:"#AE95C7",base0E:"#C795AE",base0F:"#C79595"},e.exports=t.default},1733:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"atelier dune",author:"bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/dune)",base00:"#20201d",base01:"#292824",base02:"#6e6b5e",base03:"#7d7a68",base04:"#999580",base05:"#a6a28c",base06:"#e8e4cf",base07:"#fefbec",base08:"#d73737",base09:"#b65611",base0A:"#cfb017",base0B:"#60ac39",base0C:"#1fad83",base0D:"#6684e1",base0E:"#b854d4",base0F:"#d43552"},e.exports=t.default},8974:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"atelier forest",author:"bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/forest)",base00:"#1b1918",base01:"#2c2421",base02:"#68615e",base03:"#766e6b",base04:"#9c9491",base05:"#a8a19f",base06:"#e6e2e0",base07:"#f1efee",base08:"#f22c40",base09:"#df5320",base0A:"#d5911a",base0B:"#5ab738",base0C:"#00ad9c",base0D:"#407ee7",base0E:"#6666ea",base0F:"#c33ff3"},e.exports=t.default},6933:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"atelier heath",author:"bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/heath)",base00:"#1b181b",base01:"#292329",base02:"#695d69",base03:"#776977",base04:"#9e8f9e",base05:"#ab9bab",base06:"#d8cad8",base07:"#f7f3f7",base08:"#ca402b",base09:"#a65926",base0A:"#bb8a35",base0B:"#379a37",base0C:"#159393",base0D:"#516aec",base0E:"#7b59c0",base0F:"#cc33cc"},e.exports=t.default},523:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"atelier lakeside",author:"bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/lakeside/)",base00:"#161b1d",base01:"#1f292e",base02:"#516d7b",base03:"#5a7b8c",base04:"#7195a8",base05:"#7ea2b4",base06:"#c1e4f6",base07:"#ebf8ff",base08:"#d22d72",base09:"#935c25",base0A:"#8a8a0f",base0B:"#568c3b",base0C:"#2d8f6f",base0D:"#257fad",base0E:"#5d5db1",base0F:"#b72dd2"},e.exports=t.default},1223:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"atelier seaside",author:"bram de haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/seaside/)",base00:"#131513",base01:"#242924",base02:"#5e6e5e",base03:"#687d68",base04:"#809980",base05:"#8ca68c",base06:"#cfe8cf",base07:"#f0fff0",base08:"#e6193c",base09:"#87711d",base0A:"#c3c322",base0B:"#29a329",base0C:"#1999b3",base0D:"#3d62f5",base0E:"#ad2bee",base0F:"#e619c3"},e.exports=t.default},1233:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"bespin",author:"jan t. sott",base00:"#28211c",base01:"#36312e",base02:"#5e5d5c",base03:"#666666",base04:"#797977",base05:"#8a8986",base06:"#9d9b97",base07:"#baae9e",base08:"#cf6a4c",base09:"#cf7d34",base0A:"#f9ee98",base0B:"#54be0d",base0C:"#afc4db",base0D:"#5ea6ea",base0E:"#9b859d",base0F:"#937121"},e.exports=t.default},2847:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"brewer",author:"timothée poisot (http://github.com/tpoisot)",base00:"#0c0d0e",base01:"#2e2f30",base02:"#515253",base03:"#737475",base04:"#959697",base05:"#b7b8b9",base06:"#dadbdc",base07:"#fcfdfe",base08:"#e31a1c",base09:"#e6550d",base0A:"#dca060",base0B:"#31a354",base0C:"#80b1d3",base0D:"#3182bd",base0E:"#756bb1",base0F:"#b15928"},e.exports=t.default},8120:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"bright",author:"chris kempson (http://chriskempson.com)",base00:"#000000",base01:"#303030",base02:"#505050",base03:"#b0b0b0",base04:"#d0d0d0",base05:"#e0e0e0",base06:"#f5f5f5",base07:"#ffffff",base08:"#fb0120",base09:"#fc6d24",base0A:"#fda331",base0B:"#a1c659",base0C:"#76c7b7",base0D:"#6fb3d2",base0E:"#d381c3",base0F:"#be643c"},e.exports=t.default},6305:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"chalk",author:"chris kempson (http://chriskempson.com)",base00:"#151515",base01:"#202020",base02:"#303030",base03:"#505050",base04:"#b0b0b0",base05:"#d0d0d0",base06:"#e0e0e0",base07:"#f5f5f5",base08:"#fb9fb1",base09:"#eda987",base0A:"#ddb26f",base0B:"#acc267",base0C:"#12cfc0",base0D:"#6fc2ef",base0E:"#e1a3ee",base0F:"#deaf8f"},e.exports=t.default},525:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"codeschool",author:"brettof86",base00:"#232c31",base01:"#1c3657",base02:"#2a343a",base03:"#3f4944",base04:"#84898c",base05:"#9ea7a6",base06:"#a7cfa3",base07:"#b5d8f6",base08:"#2a5491",base09:"#43820d",base0A:"#a03b1e",base0B:"#237986",base0C:"#b02f30",base0D:"#484d79",base0E:"#c59820",base0F:"#c98344"},e.exports=t.default},4124:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"colors",author:"mrmrs (http://clrs.cc)",base00:"#111111",base01:"#333333",base02:"#555555",base03:"#777777",base04:"#999999",base05:"#bbbbbb",base06:"#dddddd",base07:"#ffffff",base08:"#ff4136",base09:"#ff851b",base0A:"#ffdc00",base0B:"#2ecc40",base0C:"#7fdbff",base0D:"#0074d9",base0E:"#b10dc9",base0F:"#85144b"},e.exports=t.default},7167:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"default",author:"chris kempson (http://chriskempson.com)",base00:"#181818",base01:"#282828",base02:"#383838",base03:"#585858",base04:"#b8b8b8",base05:"#d8d8d8",base06:"#e8e8e8",base07:"#f8f8f8",base08:"#ab4642",base09:"#dc9656",base0A:"#f7ca88",base0B:"#a1b56c",base0C:"#86c1b9",base0D:"#7cafc2",base0E:"#ba8baf",base0F:"#a16946"},e.exports=t.default},4582:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"eighties",author:"chris kempson (http://chriskempson.com)",base00:"#2d2d2d",base01:"#393939",base02:"#515151",base03:"#747369",base04:"#a09f93",base05:"#d3d0c8",base06:"#e8e6df",base07:"#f2f0ec",base08:"#f2777a",base09:"#f99157",base0A:"#ffcc66",base0B:"#99cc99",base0C:"#66cccc",base0D:"#6699cc",base0E:"#cc99cc",base0F:"#d27b53"},e.exports=t.default},7096:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"embers",author:"jannik siebert (https://github.com/janniks)",base00:"#16130F",base01:"#2C2620",base02:"#433B32",base03:"#5A5047",base04:"#8A8075",base05:"#A39A90",base06:"#BEB6AE",base07:"#DBD6D1",base08:"#826D57",base09:"#828257",base0A:"#6D8257",base0B:"#57826D",base0C:"#576D82",base0D:"#6D5782",base0E:"#82576D",base0F:"#825757"},e.exports=t.default},9887:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"flat",author:"chris kempson (http://chriskempson.com)",base00:"#2C3E50",base01:"#34495E",base02:"#7F8C8D",base03:"#95A5A6",base04:"#BDC3C7",base05:"#e0e0e0",base06:"#f5f5f5",base07:"#ECF0F1",base08:"#E74C3C",base09:"#E67E22",base0A:"#F1C40F",base0B:"#2ECC71",base0C:"#1ABC9C",base0D:"#3498DB",base0E:"#9B59B6",base0F:"#be643c"},e.exports=t.default},7199:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"google",author:"seth wright (http://sethawright.com)",base00:"#1d1f21",base01:"#282a2e",base02:"#373b41",base03:"#969896",base04:"#b4b7b4",base05:"#c5c8c6",base06:"#e0e0e0",base07:"#ffffff",base08:"#CC342B",base09:"#F96A38",base0A:"#FBA922",base0B:"#198844",base0C:"#3971ED",base0D:"#3971ED",base0E:"#A36AC7",base0F:"#3971ED"},e.exports=t.default},1985:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"grayscale",author:"alexandre gavioli (https://github.com/alexx2/)",base00:"#101010",base01:"#252525",base02:"#464646",base03:"#525252",base04:"#ababab",base05:"#b9b9b9",base06:"#e3e3e3",base07:"#f7f7f7",base08:"#7c7c7c",base09:"#999999",base0A:"#a0a0a0",base0B:"#8e8e8e",base0C:"#868686",base0D:"#686868",base0E:"#747474",base0F:"#5e5e5e"},e.exports=t.default},8093:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"green screen",author:"chris kempson (http://chriskempson.com)",base00:"#001100",base01:"#003300",base02:"#005500",base03:"#007700",base04:"#009900",base05:"#00bb00",base06:"#00dd00",base07:"#00ff00",base08:"#007700",base09:"#009900",base0A:"#007700",base0B:"#00bb00",base0C:"#005500",base0D:"#009900",base0E:"#00bb00",base0F:"#005500"},e.exports=t.default},1615:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"harmonic16",author:"jannik siebert (https://github.com/janniks)",base00:"#0b1c2c",base01:"#223b54",base02:"#405c79",base03:"#627e99",base04:"#aabcce",base05:"#cbd6e2",base06:"#e5ebf1",base07:"#f7f9fb",base08:"#bf8b56",base09:"#bfbf56",base0A:"#8bbf56",base0B:"#56bf8b",base0C:"#568bbf",base0D:"#8b56bf",base0E:"#bf568b",base0F:"#bf5656"},e.exports=t.default},9063:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"hopscotch",author:"jan t. sott",base00:"#322931",base01:"#433b42",base02:"#5c545b",base03:"#797379",base04:"#989498",base05:"#b9b5b8",base06:"#d5d3d5",base07:"#ffffff",base08:"#dd464c",base09:"#fd8b19",base0A:"#fdcc59",base0B:"#8fc13e",base0C:"#149b93",base0D:"#1290bf",base0E:"#c85e7c",base0F:"#b33508"},e.exports=t.default},9446:(e,t,a)=>{"use strict";function r(e){return e&&e.__esModule?e.default:e}t.__esModule=!0;var n=a(1308);t.threezerotwofour=r(n);var o=a(9735);t.apathy=r(o);var s=a(294);t.ashes=r(s);var i=a(1733);t.atelierDune=r(i);var l=a(8974);t.atelierForest=r(l);var c=a(6933);t.atelierHeath=r(c);var u=a(523);t.atelierLakeside=r(u);var d=a(1223);t.atelierSeaside=r(d);var b=a(1233);t.bespin=r(b);var p=a(2847);t.brewer=r(p);var f=a(8120);t.bright=r(f);var h=a(6305);t.chalk=r(h);var m=a(525);t.codeschool=r(m);var v=a(4124);t.colors=r(v);var g=a(7167);t.default=r(g);var y=a(4582);t.eighties=r(y);var k=a(7096);t.embers=r(k);var E=a(9887);t.flat=r(E);var w=a(7199);t.google=r(w);var j=a(1985);t.grayscale=r(j);var x=a(8093);t.greenscreen=r(x);var C=a(1615);t.harmonic=r(C);var O=a(9063);t.hopscotch=r(O);var M=a(9033);t.isotope=r(M);var S=a(4112);t.marrakesh=r(S);var _=a(9600);t.mocha=r(_);var A=a(1240);t.monokai=r(A);var F=a(9768);t.ocean=r(F);var P=a(8293);t.paraiso=r(P);var R=a(3093);t.pop=r(R);var D=a(1951);t.railscasts=r(D);var I=a(6368);t.shapeshifter=r(I);var z=a(2317);t.solarized=r(z);var B=a(1091);t.summerfruit=r(B);var N=a(6943);t.tomorrow=r(N);var L=a(5670);t.tube=r(L);var q=a(2536);t.twilight=r(q)},9033:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"isotope",author:"jan t. sott",base00:"#000000",base01:"#404040",base02:"#606060",base03:"#808080",base04:"#c0c0c0",base05:"#d0d0d0",base06:"#e0e0e0",base07:"#ffffff",base08:"#ff0000",base09:"#ff9900",base0A:"#ff0099",base0B:"#33ff00",base0C:"#00ffff",base0D:"#0066ff",base0E:"#cc00ff",base0F:"#3300ff"},e.exports=t.default},4112:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"marrakesh",author:"alexandre gavioli (http://github.com/alexx2/)",base00:"#201602",base01:"#302e00",base02:"#5f5b17",base03:"#6c6823",base04:"#86813b",base05:"#948e48",base06:"#ccc37a",base07:"#faf0a5",base08:"#c35359",base09:"#b36144",base0A:"#a88339",base0B:"#18974e",base0C:"#75a738",base0D:"#477ca1",base0E:"#8868b3",base0F:"#b3588e"},e.exports=t.default},9600:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"mocha",author:"chris kempson (http://chriskempson.com)",base00:"#3B3228",base01:"#534636",base02:"#645240",base03:"#7e705a",base04:"#b8afad",base05:"#d0c8c6",base06:"#e9e1dd",base07:"#f5eeeb",base08:"#cb6077",base09:"#d28b71",base0A:"#f4bc87",base0B:"#beb55b",base0C:"#7bbda4",base0D:"#8ab3b5",base0E:"#a89bb9",base0F:"#bb9584"},e.exports=t.default},1240:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"monokai",author:"wimer hazenberg (http://www.monokai.nl)",base00:"#272822",base01:"#383830",base02:"#49483e",base03:"#75715e",base04:"#a59f85",base05:"#f8f8f2",base06:"#f5f4f1",base07:"#f9f8f5",base08:"#f92672",base09:"#fd971f",base0A:"#f4bf75",base0B:"#a6e22e",base0C:"#a1efe4",base0D:"#66d9ef",base0E:"#ae81ff",base0F:"#cc6633"},e.exports=t.default},9768:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"ocean",author:"chris kempson (http://chriskempson.com)",base00:"#2b303b",base01:"#343d46",base02:"#4f5b66",base03:"#65737e",base04:"#a7adba",base05:"#c0c5ce",base06:"#dfe1e8",base07:"#eff1f5",base08:"#bf616a",base09:"#d08770",base0A:"#ebcb8b",base0B:"#a3be8c",base0C:"#96b5b4",base0D:"#8fa1b3",base0E:"#b48ead",base0F:"#ab7967"},e.exports=t.default},8293:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"paraiso",author:"jan t. sott",base00:"#2f1e2e",base01:"#41323f",base02:"#4f424c",base03:"#776e71",base04:"#8d8687",base05:"#a39e9b",base06:"#b9b6b0",base07:"#e7e9db",base08:"#ef6155",base09:"#f99b15",base0A:"#fec418",base0B:"#48b685",base0C:"#5bc4bf",base0D:"#06b6ef",base0E:"#815ba4",base0F:"#e96ba8"},e.exports=t.default},3093:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"pop",author:"chris kempson (http://chriskempson.com)",base00:"#000000",base01:"#202020",base02:"#303030",base03:"#505050",base04:"#b0b0b0",base05:"#d0d0d0",base06:"#e0e0e0",base07:"#ffffff",base08:"#eb008a",base09:"#f29333",base0A:"#f8ca12",base0B:"#37b349",base0C:"#00aabb",base0D:"#0e5a94",base0E:"#b31e8d",base0F:"#7a2d00"},e.exports=t.default},1951:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"railscasts",author:"ryan bates (http://railscasts.com)",base00:"#2b2b2b",base01:"#272935",base02:"#3a4055",base03:"#5a647e",base04:"#d4cfc9",base05:"#e6e1dc",base06:"#f4f1ed",base07:"#f9f7f3",base08:"#da4939",base09:"#cc7833",base0A:"#ffc66d",base0B:"#a5c261",base0C:"#519f50",base0D:"#6d9cbe",base0E:"#b6b3eb",base0F:"#bc9458"},e.exports=t.default},6368:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"shapeshifter",author:"tyler benziger (http://tybenz.com)",base00:"#000000",base01:"#040404",base02:"#102015",base03:"#343434",base04:"#555555",base05:"#ababab",base06:"#e0e0e0",base07:"#f9f9f9",base08:"#e92f2f",base09:"#e09448",base0A:"#dddd13",base0B:"#0ed839",base0C:"#23edda",base0D:"#3b48e3",base0E:"#f996e2",base0F:"#69542d"},e.exports=t.default},2317:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"solarized",author:"ethan schoonover (http://ethanschoonover.com/solarized)",base00:"#002b36",base01:"#073642",base02:"#586e75",base03:"#657b83",base04:"#839496",base05:"#93a1a1",base06:"#eee8d5",base07:"#fdf6e3",base08:"#dc322f",base09:"#cb4b16",base0A:"#b58900",base0B:"#859900",base0C:"#2aa198",base0D:"#268bd2",base0E:"#6c71c4",base0F:"#d33682"},e.exports=t.default},1091:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"summerfruit",author:"christopher corley (http://cscorley.github.io/)",base00:"#151515",base01:"#202020",base02:"#303030",base03:"#505050",base04:"#B0B0B0",base05:"#D0D0D0",base06:"#E0E0E0",base07:"#FFFFFF",base08:"#FF0086",base09:"#FD8900",base0A:"#ABA800",base0B:"#00C918",base0C:"#1faaaa",base0D:"#3777E6",base0E:"#AD00A1",base0F:"#cc6633"},e.exports=t.default},1308:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"threezerotwofour",author:"jan t. sott (http://github.com/idleberg)",base00:"#090300",base01:"#3a3432",base02:"#4a4543",base03:"#5c5855",base04:"#807d7c",base05:"#a5a2a2",base06:"#d6d5d4",base07:"#f7f7f7",base08:"#db2d20",base09:"#e8bbd0",base0A:"#fded02",base0B:"#01a252",base0C:"#b5e4f4",base0D:"#01a0e4",base0E:"#a16a94",base0F:"#cdab53"},e.exports=t.default},6943:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"tomorrow",author:"chris kempson (http://chriskempson.com)",base00:"#1d1f21",base01:"#282a2e",base02:"#373b41",base03:"#969896",base04:"#b4b7b4",base05:"#c5c8c6",base06:"#e0e0e0",base07:"#ffffff",base08:"#cc6666",base09:"#de935f",base0A:"#f0c674",base0B:"#b5bd68",base0C:"#8abeb7",base0D:"#81a2be",base0E:"#b294bb",base0F:"#a3685a"},e.exports=t.default},5670:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"london tube",author:"jan t. sott",base00:"#231f20",base01:"#1c3f95",base02:"#5a5758",base03:"#737171",base04:"#959ca1",base05:"#d9d8d8",base06:"#e7e7e8",base07:"#ffffff",base08:"#ee2e24",base09:"#f386a1",base0A:"#ffd204",base0B:"#00853e",base0C:"#85cebc",base0D:"#009ddc",base0E:"#98005d",base0F:"#b06110"},e.exports=t.default},2536:(e,t)=>{"use strict";t.__esModule=!0,t.default={scheme:"twilight",author:"david hart (http://hart-dev.com)",base00:"#1e1e1e",base01:"#323537",base02:"#464b50",base03:"#5f5a60",base04:"#838184",base05:"#a7a7a7",base06:"#c3c3c3",base07:"#ffffff",base08:"#cf6a4c",base09:"#cda869",base0A:"#f9ee98",base0B:"#8f9d6a",base0C:"#afc4db",base0D:"#7587a6",base0E:"#9b859d",base0F:"#9b703f"},e.exports=t.default},6481:(e,t,a)=>{var r=a(4176),n={};for(var o in r)r.hasOwnProperty(o)&&(n[r[o]]=o);var s=e.exports={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};for(var i in s)if(s.hasOwnProperty(i)){if(!("channels"in s[i]))throw new Error("missing channels property: "+i);if(!("labels"in s[i]))throw new Error("missing channel labels property: "+i);if(s[i].labels.length!==s[i].channels)throw new Error("channel and label counts mismatch: "+i);var l=s[i].channels,c=s[i].labels;delete s[i].channels,delete s[i].labels,Object.defineProperty(s[i],"channels",{value:l}),Object.defineProperty(s[i],"labels",{value:c})}s.rgb.hsl=function(e){var t,a,r=e[0]/255,n=e[1]/255,o=e[2]/255,s=Math.min(r,n,o),i=Math.max(r,n,o),l=i-s;return i===s?t=0:r===i?t=(n-o)/l:n===i?t=2+(o-r)/l:o===i&&(t=4+(r-n)/l),(t=Math.min(60*t,360))<0&&(t+=360),a=(s+i)/2,[t,100*(i===s?0:a<=.5?l/(i+s):l/(2-i-s)),100*a]},s.rgb.hsv=function(e){var t,a,r,n,o,s=e[0]/255,i=e[1]/255,l=e[2]/255,c=Math.max(s,i,l),u=c-Math.min(s,i,l),d=function(e){return(c-e)/6/u+.5};return 0===u?n=o=0:(o=u/c,t=d(s),a=d(i),r=d(l),s===c?n=r-a:i===c?n=1/3+t-r:l===c&&(n=2/3+a-t),n<0?n+=1:n>1&&(n-=1)),[360*n,100*o,100*c]},s.rgb.hwb=function(e){var t=e[0],a=e[1],r=e[2];return[s.rgb.hsl(e)[0],100*(1/255*Math.min(t,Math.min(a,r))),100*(r=1-1/255*Math.max(t,Math.max(a,r)))]},s.rgb.cmyk=function(e){var t,a=e[0]/255,r=e[1]/255,n=e[2]/255;return[100*((1-a-(t=Math.min(1-a,1-r,1-n)))/(1-t)||0),100*((1-r-t)/(1-t)||0),100*((1-n-t)/(1-t)||0),100*t]},s.rgb.keyword=function(e){var t=n[e];if(t)return t;var a,o,s,i=1/0;for(var l in r)if(r.hasOwnProperty(l)){var c=r[l],u=(o=e,s=c,Math.pow(o[0]-s[0],2)+Math.pow(o[1]-s[1],2)+Math.pow(o[2]-s[2],2));u<i&&(i=u,a=l)}return a},s.keyword.rgb=function(e){return r[e]},s.rgb.xyz=function(e){var t=e[0]/255,a=e[1]/255,r=e[2]/255;return[100*(.4124*(t=t>.04045?Math.pow((t+.055)/1.055,2.4):t/12.92)+.3576*(a=a>.04045?Math.pow((a+.055)/1.055,2.4):a/12.92)+.1805*(r=r>.04045?Math.pow((r+.055)/1.055,2.4):r/12.92)),100*(.2126*t+.7152*a+.0722*r),100*(.0193*t+.1192*a+.9505*r)]},s.rgb.lab=function(e){var t=s.rgb.xyz(e),a=t[0],r=t[1],n=t[2];return r/=100,n/=108.883,a=(a/=95.047)>.008856?Math.pow(a,1/3):7.787*a+16/116,[116*(r=r>.008856?Math.pow(r,1/3):7.787*r+16/116)-16,500*(a-r),200*(r-(n=n>.008856?Math.pow(n,1/3):7.787*n+16/116))]},s.hsl.rgb=function(e){var t,a,r,n,o,s=e[0]/360,i=e[1]/100,l=e[2]/100;if(0===i)return[o=255*l,o,o];t=2*l-(a=l<.5?l*(1+i):l+i-l*i),n=[0,0,0];for(var c=0;c<3;c++)(r=s+1/3*-(c-1))<0&&r++,r>1&&r--,o=6*r<1?t+6*(a-t)*r:2*r<1?a:3*r<2?t+(a-t)*(2/3-r)*6:t,n[c]=255*o;return n},s.hsl.hsv=function(e){var t=e[0],a=e[1]/100,r=e[2]/100,n=a,o=Math.max(r,.01);return a*=(r*=2)<=1?r:2-r,n*=o<=1?o:2-o,[t,100*(0===r?2*n/(o+n):2*a/(r+a)),100*((r+a)/2)]},s.hsv.rgb=function(e){var t=e[0]/60,a=e[1]/100,r=e[2]/100,n=Math.floor(t)%6,o=t-Math.floor(t),s=255*r*(1-a),i=255*r*(1-a*o),l=255*r*(1-a*(1-o));switch(r*=255,n){case 0:return[r,l,s];case 1:return[i,r,s];case 2:return[s,r,l];case 3:return[s,i,r];case 4:return[l,s,r];case 5:return[r,s,i]}},s.hsv.hsl=function(e){var t,a,r,n=e[0],o=e[1]/100,s=e[2]/100,i=Math.max(s,.01);return r=(2-o)*s,a=o*i,[n,100*(a=(a/=(t=(2-o)*i)<=1?t:2-t)||0),100*(r/=2)]},s.hwb.rgb=function(e){var t,a,r,n,o,s,i,l=e[0]/360,c=e[1]/100,u=e[2]/100,d=c+u;switch(d>1&&(c/=d,u/=d),r=6*l-(t=Math.floor(6*l)),1&t&&(r=1-r),n=c+r*((a=1-u)-c),t){default:case 6:case 0:o=a,s=n,i=c;break;case 1:o=n,s=a,i=c;break;case 2:o=c,s=a,i=n;break;case 3:o=c,s=n,i=a;break;case 4:o=n,s=c,i=a;break;case 5:o=a,s=c,i=n}return[255*o,255*s,255*i]},s.cmyk.rgb=function(e){var t=e[0]/100,a=e[1]/100,r=e[2]/100,n=e[3]/100;return[255*(1-Math.min(1,t*(1-n)+n)),255*(1-Math.min(1,a*(1-n)+n)),255*(1-Math.min(1,r*(1-n)+n))]},s.xyz.rgb=function(e){var t,a,r,n=e[0]/100,o=e[1]/100,s=e[2]/100;return a=-.9689*n+1.8758*o+.0415*s,r=.0557*n+-.204*o+1.057*s,t=(t=3.2406*n+-1.5372*o+-.4986*s)>.0031308?1.055*Math.pow(t,1/2.4)-.055:12.92*t,a=a>.0031308?1.055*Math.pow(a,1/2.4)-.055:12.92*a,r=r>.0031308?1.055*Math.pow(r,1/2.4)-.055:12.92*r,[255*(t=Math.min(Math.max(0,t),1)),255*(a=Math.min(Math.max(0,a),1)),255*(r=Math.min(Math.max(0,r),1))]},s.xyz.lab=function(e){var t=e[0],a=e[1],r=e[2];return a/=100,r/=108.883,t=(t/=95.047)>.008856?Math.pow(t,1/3):7.787*t+16/116,[116*(a=a>.008856?Math.pow(a,1/3):7.787*a+16/116)-16,500*(t-a),200*(a-(r=r>.008856?Math.pow(r,1/3):7.787*r+16/116))]},s.lab.xyz=function(e){var t,a,r,n=e[0];t=e[1]/500+(a=(n+16)/116),r=a-e[2]/200;var o=Math.pow(a,3),s=Math.pow(t,3),i=Math.pow(r,3);return a=o>.008856?o:(a-16/116)/7.787,t=s>.008856?s:(t-16/116)/7.787,r=i>.008856?i:(r-16/116)/7.787,[t*=95.047,a*=100,r*=108.883]},s.lab.lch=function(e){var t,a=e[0],r=e[1],n=e[2];return(t=360*Math.atan2(n,r)/2/Math.PI)<0&&(t+=360),[a,Math.sqrt(r*r+n*n),t]},s.lch.lab=function(e){var t,a=e[0],r=e[1];return t=e[2]/360*2*Math.PI,[a,r*Math.cos(t),r*Math.sin(t)]},s.rgb.ansi16=function(e){var t=e[0],a=e[1],r=e[2],n=1 in arguments?arguments[1]:s.rgb.hsv(e)[2];if(0===(n=Math.round(n/50)))return 30;var o=30+(Math.round(r/255)<<2|Math.round(a/255)<<1|Math.round(t/255));return 2===n&&(o+=60),o},s.hsv.ansi16=function(e){return s.rgb.ansi16(s.hsv.rgb(e),e[2])},s.rgb.ansi256=function(e){var t=e[0],a=e[1],r=e[2];return t===a&&a===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(a/255*5)+Math.round(r/255*5)},s.ansi16.rgb=function(e){var t=e%10;if(0===t||7===t)return e>50&&(t+=3.5),[t=t/10.5*255,t,t];var a=.5*(1+~~(e>50));return[(1&t)*a*255,(t>>1&1)*a*255,(t>>2&1)*a*255]},s.ansi256.rgb=function(e){if(e>=232){var t=10*(e-232)+8;return[t,t,t]}var a;return e-=16,[Math.floor(e/36)/5*255,Math.floor((a=e%36)/6)/5*255,a%6/5*255]},s.rgb.hex=function(e){var t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"000000".substring(t.length)+t},s.hex.rgb=function(e){var t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];var a=t[0];3===t[0].length&&(a=a.split("").map((function(e){return e+e})).join(""));var r=parseInt(a,16);return[r>>16&255,r>>8&255,255&r]},s.rgb.hcg=function(e){var t,a=e[0]/255,r=e[1]/255,n=e[2]/255,o=Math.max(Math.max(a,r),n),s=Math.min(Math.min(a,r),n),i=o-s;return t=i<=0?0:o===a?(r-n)/i%6:o===r?2+(n-a)/i:4+(a-r)/i+4,t/=6,[360*(t%=1),100*i,100*(i<1?s/(1-i):0)]},s.hsl.hcg=function(e){var t=e[1]/100,a=e[2]/100,r=1,n=0;return(r=a<.5?2*t*a:2*t*(1-a))<1&&(n=(a-.5*r)/(1-r)),[e[0],100*r,100*n]},s.hsv.hcg=function(e){var t=e[1]/100,a=e[2]/100,r=t*a,n=0;return r<1&&(n=(a-r)/(1-r)),[e[0],100*r,100*n]},s.hcg.rgb=function(e){var t=e[0]/360,a=e[1]/100,r=e[2]/100;if(0===a)return[255*r,255*r,255*r];var n,o=[0,0,0],s=t%1*6,i=s%1,l=1-i;switch(Math.floor(s)){case 0:o[0]=1,o[1]=i,o[2]=0;break;case 1:o[0]=l,o[1]=1,o[2]=0;break;case 2:o[0]=0,o[1]=1,o[2]=i;break;case 3:o[0]=0,o[1]=l,o[2]=1;break;case 4:o[0]=i,o[1]=0,o[2]=1;break;default:o[0]=1,o[1]=0,o[2]=l}return n=(1-a)*r,[255*(a*o[0]+n),255*(a*o[1]+n),255*(a*o[2]+n)]},s.hcg.hsv=function(e){var t=e[1]/100,a=t+e[2]/100*(1-t),r=0;return a>0&&(r=t/a),[e[0],100*r,100*a]},s.hcg.hsl=function(e){var t=e[1]/100,a=e[2]/100*(1-t)+.5*t,r=0;return a>0&&a<.5?r=t/(2*a):a>=.5&&a<1&&(r=t/(2*(1-a))),[e[0],100*r,100*a]},s.hcg.hwb=function(e){var t=e[1]/100,a=t+e[2]/100*(1-t);return[e[0],100*(a-t),100*(1-a)]},s.hwb.hcg=function(e){var t=e[1]/100,a=1-e[2]/100,r=a-t,n=0;return r<1&&(n=(a-r)/(1-r)),[e[0],100*r,100*n]},s.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},s.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},s.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},s.gray.hsl=s.gray.hsv=function(e){return[0,0,e[0]]},s.gray.hwb=function(e){return[0,100,e[0]]},s.gray.cmyk=function(e){return[0,0,0,e[0]]},s.gray.lab=function(e){return[e[0],0,0]},s.gray.hex=function(e){var t=255&Math.round(e[0]/100*255),a=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(a.length)+a},s.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]}},4732:(e,t,a)=>{var r=a(6481),n=a(1157),o={};Object.keys(r).forEach((function(e){o[e]={},Object.defineProperty(o[e],"channels",{value:r[e].channels}),Object.defineProperty(o[e],"labels",{value:r[e].labels});var t=n(e);Object.keys(t).forEach((function(a){var r=t[a];o[e][a]=function(e){var t=function(t){if(null==t)return t;arguments.length>1&&(t=Array.prototype.slice.call(arguments));var a=e(t);if("object"==typeof a)for(var r=a.length,n=0;n<r;n++)a[n]=Math.round(a[n]);return a};return"conversion"in e&&(t.conversion=e.conversion),t}(r),o[e][a].raw=function(e){var t=function(t){return null==t?t:(arguments.length>1&&(t=Array.prototype.slice.call(arguments)),e(t))};return"conversion"in e&&(t.conversion=e.conversion),t}(r)}))})),e.exports=o},1157:(e,t,a)=>{var r=a(6481);function n(e){var t=function(){for(var e={},t=Object.keys(r),a=t.length,n=0;n<a;n++)e[t[n]]={distance:-1,parent:null};return e}(),a=[e];for(t[e].distance=0;a.length;)for(var n=a.pop(),o=Object.keys(r[n]),s=o.length,i=0;i<s;i++){var l=o[i],c=t[l];-1===c.distance&&(c.distance=t[n].distance+1,c.parent=n,a.unshift(l))}return t}function o(e,t){return function(a){return t(e(a))}}function s(e,t){for(var a=[t[e].parent,e],n=r[t[e].parent][e],s=t[e].parent;t[s].parent;)a.unshift(t[s].parent),n=o(r[t[s].parent][s],n),s=t[s].parent;return n.conversion=a,n}e.exports=function(e){for(var t=n(e),a={},r=Object.keys(t),o=r.length,i=0;i<o;i++){var l=r[i];null!==t[l].parent&&(a[l]=s(l,t))}return a}},4176:e=>{"use strict";e.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}},4877:e=>{"use strict";e.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}},6138:(e,t,a)=>{var r=a(4877),n=a(301),o=Object.hasOwnProperty,s=Object.create(null);for(var i in r)o.call(r,i)&&(s[r[i]]=i);var l=e.exports={to:{},get:{}};function c(e,t,a){return Math.min(Math.max(t,e),a)}function u(e){var t=Math.round(e).toString(16).toUpperCase();return t.length<2?"0"+t:t}l.get=function(e){var t,a;switch(e.substring(0,3).toLowerCase()){case"hsl":t=l.get.hsl(e),a="hsl";break;case"hwb":t=l.get.hwb(e),a="hwb";break;default:t=l.get.rgb(e),a="rgb"}return t?{model:a,value:t}:null},l.get.rgb=function(e){if(!e)return null;var t,a,n,s=[0,0,0,1];if(t=e.match(/^#([a-f0-9]{6})([a-f0-9]{2})?$/i)){for(n=t[2],t=t[1],a=0;a<3;a++){var i=2*a;s[a]=parseInt(t.slice(i,i+2),16)}n&&(s[3]=parseInt(n,16)/255)}else if(t=e.match(/^#([a-f0-9]{3,4})$/i)){for(n=(t=t[1])[3],a=0;a<3;a++)s[a]=parseInt(t[a]+t[a],16);n&&(s[3]=parseInt(n+n,16)/255)}else if(t=e.match(/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/)){for(a=0;a<3;a++)s[a]=parseInt(t[a+1],0);t[4]&&(t[5]?s[3]=.01*parseFloat(t[4]):s[3]=parseFloat(t[4]))}else{if(!(t=e.match(/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/)))return(t=e.match(/^(\w+)$/))?"transparent"===t[1]?[0,0,0,0]:o.call(r,t[1])?((s=r[t[1]])[3]=1,s):null:null;for(a=0;a<3;a++)s[a]=Math.round(2.55*parseFloat(t[a+1]));t[4]&&(t[5]?s[3]=.01*parseFloat(t[4]):s[3]=parseFloat(t[4]))}for(a=0;a<3;a++)s[a]=c(s[a],0,255);return s[3]=c(s[3],0,1),s},l.get.hsl=function(e){if(!e)return null;var t=e.match(/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/);if(t){var a=parseFloat(t[4]);return[(parseFloat(t[1])%360+360)%360,c(parseFloat(t[2]),0,100),c(parseFloat(t[3]),0,100),c(isNaN(a)?1:a,0,1)]}return null},l.get.hwb=function(e){if(!e)return null;var t=e.match(/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/);if(t){var a=parseFloat(t[4]);return[(parseFloat(t[1])%360+360)%360,c(parseFloat(t[2]),0,100),c(parseFloat(t[3]),0,100),c(isNaN(a)?1:a,0,1)]}return null},l.to.hex=function(){var e=n(arguments);return"#"+u(e[0])+u(e[1])+u(e[2])+(e[3]<1?u(Math.round(255*e[3])):"")},l.to.rgb=function(){var e=n(arguments);return e.length<4||1===e[3]?"rgb("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+")":"rgba("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+", "+e[3]+")"},l.to.rgb.percent=function(){var e=n(arguments),t=Math.round(e[0]/255*100),a=Math.round(e[1]/255*100),r=Math.round(e[2]/255*100);return e.length<4||1===e[3]?"rgb("+t+"%, "+a+"%, "+r+"%)":"rgba("+t+"%, "+a+"%, "+r+"%, "+e[3]+")"},l.to.hsl=function(){var e=n(arguments);return e.length<4||1===e[3]?"hsl("+e[0]+", "+e[1]+"%, "+e[2]+"%)":"hsla("+e[0]+", "+e[1]+"%, "+e[2]+"%, "+e[3]+")"},l.to.hwb=function(){var e=n(arguments),t="";return e.length>=4&&1!==e[3]&&(t=", "+e[3]),"hwb("+e[0]+", "+e[1]+"%, "+e[2]+"%"+t+")"},l.to.keyword=function(e){return s[e.slice(0,3)]}},3639:(e,t,a)=>{"use strict";var r=a(6138),n=a(4732),o=[].slice,s=["keyword","gray","hex"],i={};Object.keys(n).forEach((function(e){i[o.call(n[e].labels).sort().join("")]=e}));var l={};function c(e,t){if(!(this instanceof c))return new c(e,t);if(t&&t in s&&(t=null),t&&!(t in n))throw new Error("Unknown model: "+t);var a,u;if(null==e)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(e instanceof c)this.model=e.model,this.color=e.color.slice(),this.valpha=e.valpha;else if("string"==typeof e){var d=r.get(e);if(null===d)throw new Error("Unable to parse color from string: "+e);this.model=d.model,u=n[this.model].channels,this.color=d.value.slice(0,u),this.valpha="number"==typeof d.value[u]?d.value[u]:1}else if(e.length){this.model=t||"rgb",u=n[this.model].channels;var p=o.call(e,0,u);this.color=b(p,u),this.valpha="number"==typeof e[u]?e[u]:1}else if("number"==typeof e)e&=16777215,this.model="rgb",this.color=[e>>16&255,e>>8&255,255&e],this.valpha=1;else{this.valpha=1;var f=Object.keys(e);"alpha"in e&&(f.splice(f.indexOf("alpha"),1),this.valpha="number"==typeof e.alpha?e.alpha:0);var h=f.sort().join("");if(!(h in i))throw new Error("Unable to parse color from object: "+JSON.stringify(e));this.model=i[h];var m=n[this.model].labels,v=[];for(a=0;a<m.length;a++)v.push(e[m[a]]);this.color=b(v)}if(l[this.model])for(u=n[this.model].channels,a=0;a<u;a++){var g=l[this.model][a];g&&(this.color[a]=g(this.color[a]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}function u(e,t,a){return(e=Array.isArray(e)?e:[e]).forEach((function(e){(l[e]||(l[e]=[]))[t]=a})),e=e[0],function(r){var n;return arguments.length?(a&&(r=a(r)),(n=this[e]()).color[t]=r,n):(n=this[e]().color[t],a&&(n=a(n)),n)}}function d(e){return function(t){return Math.max(0,Math.min(e,t))}}function b(e,t){for(var a=0;a<t;a++)"number"!=typeof e[a]&&(e[a]=0);return e}c.prototype={toString:function(){return this.string()},toJSON:function(){return this[this.model]()},string:function(e){var t=this.model in r.to?this:this.rgb(),a=1===(t=t.round("number"==typeof e?e:1)).valpha?t.color:t.color.concat(this.valpha);return r.to[t.model](a)},percentString:function(e){var t=this.rgb().round("number"==typeof e?e:1),a=1===t.valpha?t.color:t.color.concat(this.valpha);return r.to.rgb.percent(a)},array:function(){return 1===this.valpha?this.color.slice():this.color.concat(this.valpha)},object:function(){for(var e={},t=n[this.model].channels,a=n[this.model].labels,r=0;r<t;r++)e[a[r]]=this.color[r];return 1!==this.valpha&&(e.alpha=this.valpha),e},unitArray:function(){var e=this.rgb().color;return e[0]/=255,e[1]/=255,e[2]/=255,1!==this.valpha&&e.push(this.valpha),e},unitObject:function(){var e=this.rgb().object();return e.r/=255,e.g/=255,e.b/=255,1!==this.valpha&&(e.alpha=this.valpha),e},round:function(e){return e=Math.max(e||0,0),new c(this.color.map(function(e){return function(t){return function(e,t){return Number(e.toFixed(t))}(t,e)}}(e)).concat(this.valpha),this.model)},alpha:function(e){return arguments.length?new c(this.color.concat(Math.max(0,Math.min(1,e))),this.model):this.valpha},red:u("rgb",0,d(255)),green:u("rgb",1,d(255)),blue:u("rgb",2,d(255)),hue:u(["hsl","hsv","hsl","hwb","hcg"],0,(function(e){return(e%360+360)%360})),saturationl:u("hsl",1,d(100)),lightness:u("hsl",2,d(100)),saturationv:u("hsv",1,d(100)),value:u("hsv",2,d(100)),chroma:u("hcg",1,d(100)),gray:u("hcg",2,d(100)),white:u("hwb",1,d(100)),wblack:u("hwb",2,d(100)),cyan:u("cmyk",0,d(100)),magenta:u("cmyk",1,d(100)),yellow:u("cmyk",2,d(100)),black:u("cmyk",3,d(100)),x:u("xyz",0,d(100)),y:u("xyz",1,d(100)),z:u("xyz",2,d(100)),l:u("lab",0,d(100)),a:u("lab",1),b:u("lab",2),keyword:function(e){return arguments.length?new c(e):n[this.model].keyword(this.color)},hex:function(e){return arguments.length?new c(e):r.to.hex(this.rgb().round().color)},rgbNumber:function(){var e=this.rgb().color;return(255&e[0])<<16|(255&e[1])<<8|255&e[2]},luminosity:function(){for(var e=this.rgb().color,t=[],a=0;a<e.length;a++){var r=e[a]/255;t[a]=r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)}return.2126*t[0]+.7152*t[1]+.0722*t[2]},contrast:function(e){var t=this.luminosity(),a=e.luminosity();return t>a?(t+.05)/(a+.05):(a+.05)/(t+.05)},level:function(e){var t=this.contrast(e);return t>=7.1?"AAA":t>=4.5?"AA":""},isDark:function(){var e=this.rgb().color;return(299*e[0]+587*e[1]+114*e[2])/1e3<128},isLight:function(){return!this.isDark()},negate:function(){for(var e=this.rgb(),t=0;t<3;t++)e.color[t]=255-e.color[t];return e},lighten:function(e){var t=this.hsl();return t.color[2]+=t.color[2]*e,t},darken:function(e){var t=this.hsl();return t.color[2]-=t.color[2]*e,t},saturate:function(e){var t=this.hsl();return t.color[1]+=t.color[1]*e,t},desaturate:function(e){var t=this.hsl();return t.color[1]-=t.color[1]*e,t},whiten:function(e){var t=this.hwb();return t.color[1]+=t.color[1]*e,t},blacken:function(e){var t=this.hwb();return t.color[2]+=t.color[2]*e,t},grayscale:function(){var e=this.rgb().color,t=.3*e[0]+.59*e[1]+.11*e[2];return c.rgb(t,t,t)},fade:function(e){return this.alpha(this.valpha-this.valpha*e)},opaquer:function(e){return this.alpha(this.valpha+this.valpha*e)},rotate:function(e){var t=this.hsl(),a=t.color[0];return a=(a=(a+e)%360)<0?360+a:a,t.color[0]=a,t},mix:function(e,t){if(!e||!e.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof e);var a=e.rgb(),r=this.rgb(),n=void 0===t?.5:t,o=2*n-1,s=a.alpha()-r.alpha(),i=((o*s==-1?o:(o+s)/(1+o*s))+1)/2,l=1-i;return c.rgb(i*a.red()+l*r.red(),i*a.green()+l*r.green(),i*a.blue()+l*r.blue(),a.alpha()*n+r.alpha()*(1-n))}},Object.keys(n).forEach((function(e){if(-1===s.indexOf(e)){var t=n[e].channels;c.prototype[e]=function(){if(this.model===e)return new c(this);if(arguments.length)return new c(arguments,e);var a,r="number"==typeof arguments[t]?t:this.valpha;return new c((a=n[this.model][e].raw(this.color),Array.isArray(a)?a:[a]).concat(r),e)},c[e]=function(a){return"number"==typeof a&&(a=b(o.call(arguments),t)),new c(a,e)}}})),e.exports=c},9784:e=>{"use strict";var t,a="object"==typeof Reflect?Reflect:null,r=a&&"function"==typeof a.apply?a.apply:function(e,t,a){return Function.prototype.apply.call(e,t,a)};t=a&&"function"==typeof a.ownKeys?a.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise((function(a,r){function n(a){e.removeListener(t,o),r(a)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",n),a([].slice.call(arguments))}h(e,t,o,{once:!0}),"error"!==t&&function(e,t,a){"function"==typeof e.on&&h(e,"error",t,a)}(e,n,{once:!0})}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function i(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function c(e,t,a,r){var n,o,s,c;if(i(a),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,a.listener?a.listener:a),o=e._events),s=o[t]),void 0===s)s=o[t]=a,++e._eventsCount;else if("function"==typeof s?s=o[t]=r?[a,s]:[s,a]:r?s.unshift(a):s.push(a),(n=l(e))>0&&s.length>n&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,c=u,console&&console.warn&&console.warn(c)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,a){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:a},n=u.bind(r);return n.listener=a,r.wrapFn=n,n}function b(e,t,a){var r=e._events;if(void 0===r)return[];var n=r[t];return void 0===n?[]:"function"==typeof n?a?[n.listener||n]:[n]:a?function(e){for(var t=new Array(e.length),a=0;a<t.length;++a)t[a]=e[a].listener||e[a];return t}(n):f(n,n.length)}function p(e){var t=this._events;if(void 0!==t){var a=t[e];if("function"==typeof a)return 1;if(void 0!==a)return a.length}return 0}function f(e,t){for(var a=new Array(t),r=0;r<t;++r)a[r]=e[r];return a}function h(e,t,a,r){if("function"==typeof e.on)r.once?e.once(t,a):e.on(t,a);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function n(o){r.once&&e.removeEventListener(t,n),a(o)}))}}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");s=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return l(this)},o.prototype.emit=function(e){for(var t=[],a=1;a<arguments.length;a++)t.push(arguments[a]);var n="error"===e,o=this._events;if(void 0!==o)n=n&&void 0===o.error;else if(!n)return!1;if(n){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var i=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw i.context=s,i}var l=o[e];if(void 0===l)return!1;if("function"==typeof l)r(l,this,t);else{var c=l.length,u=f(l,c);for(a=0;a<c;++a)r(u[a],this,t)}return!0},o.prototype.addListener=function(e,t){return c(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return c(this,e,t,!0)},o.prototype.once=function(e,t){return i(t),this.on(e,d(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return i(t),this.prependListener(e,d(this,e,t)),this},o.prototype.removeListener=function(e,t){var a,r,n,o,s;if(i(t),void 0===(r=this._events))return this;if(void 0===(a=r[e]))return this;if(a===t||a.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,a.listener||t));else if("function"!=typeof a){for(n=-1,o=a.length-1;o>=0;o--)if(a[o]===t||a[o].listener===t){s=a[o].listener,n=o;break}if(n<0)return this;0===n?a.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(a,n),1===a.length&&(r[e]=a[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,a,r;if(void 0===(a=this._events))return this;if(void 0===a.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==a[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete a[e]),this;if(0===arguments.length){var n,o=Object.keys(a);for(r=0;r<o.length;++r)"removeListener"!==(n=o[r])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=a[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},o.prototype.listeners=function(e){return b(this,e,!0)},o.prototype.rawListeners=function(e){return b(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},o.prototype.listenerCount=p,o.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},8336:e=>{e.exports=function(e){return!(!e||"string"==typeof e)&&(e instanceof Array||Array.isArray(e)||e.length>=0&&(e.splice instanceof Function||Object.getOwnPropertyDescriptor(e,e.length-1)&&"String"!==e.constructor.name))}},3989:e=>{var t="__lodash_placeholder__",a=32,r=1/0,n=NaN,o=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",a],["partialRight",64],["rearg",256]],s="[object Function]",i="[object GeneratorFunction]",l=/^\s+|\s+$/g,c=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,u=/\{\n\/\* \[wrapped with (.+)\] \*/,d=/,? & /,b=/^[-+]0x[0-9a-f]+$/i,p=/^0b[01]+$/i,f=/^\[object .+?Constructor\]$/,h=/^0o[0-7]+$/i,m=/^(?:0|[1-9]\d*)$/,v=parseInt,g="object"==typeof global&&global&&global.Object===Object&&global,y="object"==typeof self&&self&&self.Object===Object&&self,k=g||y||Function("return this")();function E(e,t,a){switch(a.length){case 0:return e.call(t);case 1:return e.call(t,a[0]);case 2:return e.call(t,a[0],a[1]);case 3:return e.call(t,a[0],a[1],a[2])}return e.apply(t,a)}function w(e,t){return!!(e?e.length:0)&&function(e,t,a){if(t!=t)return function(e,t,a,r){var n=e.length,o=a+(r?1:-1);for(;r?o--:++o<n;)if(t(e[o],o,e))return o;return-1}(e,j,a);var r=a-1,n=e.length;for(;++r<n;)if(e[r]===t)return r;return-1}(e,t,0)>-1}function j(e){return e!=e}function x(e,a){for(var r=-1,n=e.length,o=0,s=[];++r<n;){var i=e[r];i!==a&&i!==t||(e[r]=t,s[o++]=r)}return s}var C,O,M,S=Function.prototype,_=Object.prototype,A=k["__core-js_shared__"],F=(C=/[^.]+$/.exec(A&&A.keys&&A.keys.IE_PROTO||""))?"Symbol(src)_1."+C:"",P=S.toString,R=_.hasOwnProperty,D=_.toString,I=RegExp("^"+P.call(R).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),z=Object.create,B=Math.max,N=Math.min,L=(O=H(Object,"defineProperty"),(M=H.name)&&M.length>2?O:void 0);function q(e){if(!X(e)||function(e){return!!F&&F in e}(e))return!1;var t=function(e){var t=X(e)?D.call(e):"";return t==s||t==i}(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?I:f;return t.test(function(e){if(null!=e){try{return P.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function V(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var a,r=X(a=e.prototype)?z(a):{},n=e.apply(r,t);return X(n)?n:r}}function T(e,t,a,r,n,o,s,i,l,c){var u=128&t,d=1&t,b=2&t,p=24&t,f=512&t,h=b?void 0:V(e);return function m(){for(var v=arguments.length,g=Array(v),y=v;y--;)g[y]=arguments[y];if(p)var E=U(m),w=function(e,t){for(var a=e.length,r=0;a--;)e[a]===t&&r++;return r}(g,E);if(r&&(g=function(e,t,a,r){for(var n=-1,o=e.length,s=a.length,i=-1,l=t.length,c=B(o-s,0),u=Array(l+c),d=!r;++i<l;)u[i]=t[i];for(;++n<s;)(d||n<o)&&(u[a[n]]=e[n]);for(;c--;)u[i++]=e[n++];return u}(g,r,n,p)),o&&(g=function(e,t,a,r){for(var n=-1,o=e.length,s=-1,i=a.length,l=-1,c=t.length,u=B(o-i,0),d=Array(u+c),b=!r;++n<u;)d[n]=e[n];for(var p=n;++l<c;)d[p+l]=t[l];for(;++s<i;)(b||n<o)&&(d[p+a[s]]=e[n++]);return d}(g,o,s,p)),v-=w,p&&v<c){var j=x(g,E);return K(e,t,T,m.placeholder,a,g,j,i,l,c-v)}var C=d?a:this,O=b?C[e]:e;return v=g.length,i?g=function(e,t){var a=e.length,r=N(t.length,a),n=function(e,t){var a=-1,r=e.length;for(t||(t=Array(r));++a<r;)t[a]=e[a];return t}(e);for(;r--;){var o=t[r];e[r]=J(o,a)?n[o]:void 0}return e}(g,i):f&&v>1&&g.reverse(),u&&l<v&&(g.length=l),this&&this!==k&&this instanceof m&&(O=h||V(O)),O.apply(C,g)}}function K(e,t,r,n,o,s,i,l,c,u){var d=8&t;t|=d?a:64,4&(t&=~(d?64:a))||(t&=-4);var b=r(e,t,o,d?s:void 0,d?i:void 0,d?void 0:s,d?void 0:i,l,c,u);return b.placeholder=n,G(b,e,t)}function W(e,t,r,n,o,s,i,l){var c=2&t;if(!c&&"function"!=typeof e)throw new TypeError("Expected a function");var u=n?n.length:0;if(u||(t&=-97,n=o=void 0),i=void 0===i?i:B(te(i),0),l=void 0===l?l:te(l),u-=o?o.length:0,64&t){var d=n,b=o;n=o=void 0}var p=[e,t,r,n,o,d,b,s,i,l];if(e=p[0],t=p[1],r=p[2],n=p[3],o=p[4],!(l=p[9]=null==p[9]?c?0:e.length:B(p[9]-u,0))&&24&t&&(t&=-25),t&&1!=t)f=8==t||16==t?function(e,t,a){var r=V(e);return function n(){for(var o=arguments.length,s=Array(o),i=o,l=U(n);i--;)s[i]=arguments[i];var c=o<3&&s[0]!==l&&s[o-1]!==l?[]:x(s,l);return(o-=c.length)<a?K(e,t,T,n.placeholder,void 0,s,c,void 0,void 0,a-o):E(this&&this!==k&&this instanceof n?r:e,this,s)}}(e,t,l):t!=a&&33!=t||o.length?T.apply(void 0,p):function(e,t,a,r){var n=1&t,o=V(e);return function t(){for(var s=-1,i=arguments.length,l=-1,c=r.length,u=Array(c+i),d=this&&this!==k&&this instanceof t?o:e;++l<c;)u[l]=r[l];for(;i--;)u[l++]=arguments[++s];return E(d,n?a:this,u)}}(e,t,r,n);else var f=function(e,t,a){var r=1&t,n=V(e);return function t(){return(this&&this!==k&&this instanceof t?n:e).apply(r?a:this,arguments)}}(e,t,r);return G(f,e,t)}function U(e){return e.placeholder}function H(e,t){var a=function(e,t){return null==e?void 0:e[t]}(e,t);return q(a)?a:void 0}function $(e){var t=e.match(u);return t?t[1].split(d):[]}function Y(e,t){var a=t.length,r=a-1;return t[r]=(a>1?"& ":"")+t[r],t=t.join(a>2?", ":" "),e.replace(c,"{\n/* [wrapped with "+t+"] */\n")}function J(e,t){return!!(t=null==t?9007199254740991:t)&&("number"==typeof e||m.test(e))&&e>-1&&e%1==0&&e<t}var G=L?function(e,t,a){var r,n=t+"";return L(e,"toString",{configurable:!0,enumerable:!1,value:(r=Y(n,Q($(n),a)),function(){return r})})}:function(e){return e};function Q(e,t){return function(e,t){for(var a=-1,r=e?e.length:0;++a<r&&!1!==t(e[a],a,e););}(o,(function(a){var r="_."+a[0];t&a[1]&&!w(e,r)&&e.push(r)})),e.sort()}function Z(e,t,a){var r=W(e,8,void 0,void 0,void 0,void 0,void 0,t=a?void 0:t);return r.placeholder=Z.placeholder,r}function X(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ee(e){return e?(e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==D.call(e)}(e))return n;if(X(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=X(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(l,"");var a=p.test(e);return a||h.test(e)?v(e.slice(2),a?2:8):b.test(e)?n:+e}(e))===r||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function te(e){var t=ee(e),a=t%1;return t==t?a?t-a:t:0}Z.placeholder={},e.exports=Z},301:(e,t,a)=>{"use strict";var r=a(8336),n=Array.prototype.concat,o=Array.prototype.slice,s=e.exports=function(e){for(var t=[],a=0,s=e.length;a<s;a++){var i=e[a];r(i)?t=n.call(t,o.call(i)):t.push(i)}return t};s.wrap=function(e){return function(){return e(s(arguments))}}},4119:t=>{"use strict";t.exports=e}},a={};function r(e){var n=a[e];if(void 0!==n)return n.exports;var o=a[e]={exports:{}};return t[e](o,o.exports,r),o.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var a in t)r.o(t,a)&&!r.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:t[a]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{"use strict";function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}function t(t){var a=function(t,a){if("object"!=e(t)||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,a||"default");if("object"!=e(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===a?String:Number)(t)}(t,"string");return"symbol"==e(a)?a:a+""}function a(e,a,r){return(a=t(a))in e?Object.defineProperty(e,a,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[a]=r,e}function o(e,t){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),a.push.apply(a,r)}return a}function s(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?o(Object(r),!0).forEach((function(t){a(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):o(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,a){for(var r=0;r<a.length;r++){var n=a[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,t(n.key),n)}}function c(e,t,a){return t&&l(e.prototype,t),a&&l(e,a),Object.defineProperty(e,"prototype",{writable:!1}),e}function u(e){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},u(e)}function d(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(d=function(){return!!e})()}function b(t,a){if(a&&("object"==e(a)||"function"==typeof a))return a;if(void 0!==a)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(t)}function p(e,t,a){return t=u(t),b(e,d()?Reflect.construct(t,a||[],u(e).constructor):t.apply(e,a))}function f(e,t){return f=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},f(e,t)}function h(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&f(e,t)}r.r(n),r.d(n,{default:()=>Et});var m=r(4119),v=r.n(m);function g(){var e=this.constructor.getDerivedStateFromProps(this.props,this.state);null!=e&&this.setState(e)}function y(e){this.setState(function(t){var a=this.constructor.getDerivedStateFromProps(e,t);return null!=a?a:null}.bind(this))}function k(e,t){try{var a=this.props,r=this.state;this.props=e,this.state=t,this.__reactInternalSnapshotFlag=!0,this.__reactInternalSnapshot=this.getSnapshotBeforeUpdate(a,r)}finally{this.props=a,this.state=r}}function E(e){var t=e.prototype;if(!t||!t.isReactComponent)throw new Error("Can only polyfill class components");if("function"!=typeof e.getDerivedStateFromProps&&"function"!=typeof t.getSnapshotBeforeUpdate)return e;var a=null,r=null,n=null;if("function"==typeof t.componentWillMount?a="componentWillMount":"function"==typeof t.UNSAFE_componentWillMount&&(a="UNSAFE_componentWillMount"),"function"==typeof t.componentWillReceiveProps?r="componentWillReceiveProps":"function"==typeof t.UNSAFE_componentWillReceiveProps&&(r="UNSAFE_componentWillReceiveProps"),"function"==typeof t.componentWillUpdate?n="componentWillUpdate":"function"==typeof t.UNSAFE_componentWillUpdate&&(n="UNSAFE_componentWillUpdate"),null!==a||null!==r||null!==n){var o=e.displayName||e.name,s="function"==typeof e.getDerivedStateFromProps?"getDerivedStateFromProps()":"getSnapshotBeforeUpdate()";throw Error("Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n"+o+" uses "+s+" but also contains the following legacy lifecycles:"+(null!==a?"\n  "+a:"")+(null!==r?"\n  "+r:"")+(null!==n?"\n  "+n:"")+"\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://fb.me/react-async-component-lifecycle-hooks")}if("function"==typeof e.getDerivedStateFromProps&&(t.componentWillMount=g,t.componentWillReceiveProps=y),"function"==typeof t.getSnapshotBeforeUpdate){if("function"!=typeof t.componentDidUpdate)throw new Error("Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype");t.componentWillUpdate=k;var i=t.componentDidUpdate;t.componentDidUpdate=function(e,t,a){var r=this.__reactInternalSnapshotFlag?this.__reactInternalSnapshot:a;i.call(this,e,t,r)}}return e}function w(e,t){if(null==e)return{};var a={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.includes(r))continue;a[r]=e[r]}return a}function j(e,t){if(null==e)return{};var a,r,n=w(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)a=o[r],t.includes(a)||{}.propertyIsEnumerable.call(e,a)&&(n[a]=e[a])}return n}function x(e,t){if(t&&(null==e?void 0:e.constructor)===t)return"bigNumber";var a=function(e){return{}.toString.call(e).match(/\s([a-zA-Z]+)/)[1].toLowerCase()}(e);return"number"===a&&(a=isNaN(e)?"nan":(0|e)!=e?"float":"integer"),a}function C(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\r/g,"\\r").replace(/\f/g,"\\f")}g.__suppressDeprecationWarning=!0,y.__suppressDeprecationWarning=!0,k.__suppressDeprecationWarning=!0;var O={scheme:"rjv-default",author:"mac gainor",base00:"rgba(0, 0, 0, 0)",base01:"rgb(245, 245, 245)",base02:"rgb(235, 235, 235)",base03:"#93a1a1",base04:"rgba(0, 0, 0, 0.3)",base05:"#586e75",base06:"#073642",base07:"#002b36",base08:"#d33682",base09:"#cb4b16",base0A:"#dc322f",base0B:"#859900",base0C:"#6c71c4",base0D:"#586e75",base0E:"#2aa198",base0F:"#268bd2"},M={scheme:"rjv-grey",author:"mac gainor",base00:"rgba(1, 1, 1, 0)",base01:"rgba(1, 1, 1, 0.1)",base02:"rgba(0, 0, 0, 0.2)",base03:"rgba(1, 1, 1, 0.3)",base04:"rgba(0, 0, 0, 0.4)",base05:"rgba(1, 1, 1, 0.5)",base06:"rgba(1, 1, 1, 0.6)",base07:"rgba(1, 1, 1, 0.7)",base08:"rgba(1, 1, 1, 0.8)",base09:"rgba(1, 1, 1, 0.8)",base0A:"rgba(1, 1, 1, 0.8)",base0B:"rgba(1, 1, 1, 0.8)",base0C:"rgba(1, 1, 1, 0.8)",base0D:"rgba(1, 1, 1, 0.8)",base0E:"rgba(1, 1, 1, 0.8)",base0F:"rgba(1, 1, 1, 0.8)"};const S={white:"#fff",black:"#000",transparent:"rgba(1, 1, 1, 0)",globalFontFamily:"monospace",globalCursor:"default",indentBlockWidth:"5px",braceFontWeight:"bold",braceCursor:"pointer",ellipsisFontSize:"18px",ellipsisLineHeight:"10px",ellipsisCursor:"pointer",keyMargin:"0px 5px",keyLetterSpacing:"0.5px",keyFontStyle:"none",keyBorderRadius:"3px",keyColonWeight:"bold",keyVerticalAlign:"top",keyOpacity:"0.85",keyOpacityHover:"1",keyValPaddingTop:"3px",keyValPaddingBottom:"3px",keyValPaddingRight:"5px",keyValBorderLeft:"1px solid",keyValBorderHover:"2px solid",keyValPaddingHover:"3px 5px 3px 4px",pushedContentMarginLeft:"6px",variableValuePaddingRight:"6px",nullFontSize:"11px",nullFontWeight:"bold",nullPadding:"1px 2px",nullBorderRadius:"3px",nanFontSize:"11px",nanFontWeight:"bold",nanPadding:"1px 2px",nanBorderRadius:"3px",undefinedFontSize:"11px",undefinedFontWeight:"bold",undefinedPadding:"1px 2px",undefinedBorderRadius:"3px",dataTypeFontSize:"11px",dataTypeMarginRight:"4px",datatypeOpacity:"0.8",objectSizeBorderRadius:"3px",objectSizeFontStyle:"italic",objectSizeMargin:"0px 6px 0px 0px",clipboardCursor:"pointer",clipboardCheckMarginLeft:"-12px",metaDataPadding:"0px 0px 0px 10px",arrayGroupMetaPadding:"0px 0px 0px 4px",iconContainerWidth:"17px",tooltipPadding:"4px",editInputMinWidth:"130px",editInputBorderRadius:"2px",editInputPadding:"5px",editInputMarginRight:"4px",editInputFontFamily:"monospace",iconCursor:"pointer",iconFontSize:"15px",iconPaddingRight:"1px",dateValueMarginLeft:"2px",iconMarginRight:"3px",detectedRowPaddingTop:"3px",addKeyCoverBackground:"rgba(255, 255, 255, 0.3)",addKeyCoverPosition:"absolute",addKeyCoverPositionPx:"0px",addKeyModalWidth:"200px",addKeyModalMargin:"auto",addKeyModalPadding:"10px",addKeyModalRadius:"3px",commaColor:"#666",commaFontSize:"12px",commaMarginRight:"4px"};function _(e,t){(null==t||t>e.length)&&(t=e.length);for(var a=0,r=Array(t);a<t;a++)r[a]=e[a];return r}function A(e,t){if(e){if("string"==typeof e)return _(e,t);var a={}.toString.call(e).slice(8,-1);return"Object"===a&&e.constructor&&(a=e.constructor.name),"Map"===a||"Set"===a?Array.from(e):"Arguments"===a||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a)?_(e,t):void 0}}function F(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var a=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=a){var r,n,o,s,i=[],l=!0,c=!1;try{if(o=(a=a.call(e)).next,0===t){if(Object(a)!==a)return;l=!1}else for(;!(l=(r=o.call(a)).done)&&(i.push(r.value),i.length!==t);l=!0);}catch(e){c=!0,n=e}finally{try{if(!l&&null!=a.return&&(s=a.return(),Object(s)!==s))return}finally{if(c)throw n}}return i}}(e,t)||A(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var P=r(9446),R=r(3639),D=r.n(R),I=r(3989),z=r.n(I);function B(e,t){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),a.push.apply(a,r)}return a}function N(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?B(Object(r),!0).forEach((function(t){a(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):B(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var L=P.default,q=Object.keys(L),V=function(e){var t,a=function(e){var t=e[0]/255,a=e[1]/255,r=e[2]/255;return[.299*t+.587*a+.114*r,-.14713*t+-.28886*a+.436*r,.615*t+-.51499*a+-.10001*r]}(D()(e).array()),r=F(a,3),n=r[0],o=r[1],s=r[2],i=function(e){var t,a,r,n=e[0],o=e[1],s=e[2];return t=1*n+0*o+1.13983*s,a=1*n+-.39465*o+-.5806*s,r=1*n+2.02311*o+0*s,[255*(t=Math.min(Math.max(0,t),1)),255*(a=Math.min(Math.max(0,a),1)),255*(r=Math.min(Math.max(0,r),1))]}([(t=n,t<.25?1:t<.5?.9-t:1.1-t),o,s]);return D().rgb(i).hex()},T=function(e){return function(t){return{className:[t.className,e.className].filter(Boolean).join(" "),style:N(N({},t.style||{}),e.style||{})}}},K=function(t,a){var r=Object.keys(a);for(var n in t)-1===r.indexOf(n)&&r.push(n);return r.reduce((function(r,n){return r[n]=function(t,a){if(void 0===t)return a;if(void 0===a)return t;var r=e(t),n=e(a);switch(r){case"string":switch(n){case"string":return[a,t].filter(Boolean).join(" ");case"object":return T({className:t,style:a});case"function":return function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return T({className:t})(a.apply(void 0,[e].concat(n)))}}break;case"object":switch(n){case"string":return T({className:a,style:t});case"object":return N(N({},a),t);case"function":return function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return T({style:t})(a.apply(void 0,[e].concat(n)))}}break;case"function":switch(n){case"string":return function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return t.apply(void 0,[T(e)({className:a})].concat(n))};case"object":return function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return t.apply(void 0,[T(e)({style:a})].concat(n))};case"function":return function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return t.apply(void 0,[a.apply(void 0,[e].concat(n))].concat(n))}}}}(t[n],a[n]),r}),{})},W=function(t,a){for(var r=arguments.length,n=new Array(r>2?r-2:0),o=2;o<r;o++)n[o-2]=arguments[o];if(null===a)return t;Array.isArray(a)||(a=[a]);var s=a.map((function(e){return t[e]})).filter(Boolean).reduce((function(t,a){return"string"==typeof a?t.className=[t.className,a].filter(Boolean).join(" "):"object"===e(a)?t.style=N(N({},t.style),a):"function"==typeof a&&(t=N(N({},t),a.apply(void 0,[t].concat(n)))),t}),{className:"",style:{}});return s.className||delete s.className,0===Object.keys(s.style).length&&delete s.style,s},U=function(e){return Object.keys(e).reduce((function(t,a){return t[a]=/^base/.test(a)?V(e[a]):"scheme"===a?e[a]+":inverted":e[a],t}),{})},H=z()((function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=t.defaultBase16,n=void 0===r?L:r,o=t.base16Themes,s=Y(a,void 0===o?null:o);s&&(a=N(N({},s),a));for(var i=q.reduce((function(e,t){return e[t]=a[t]||n[t],e}),{}),l=Object.keys(a).reduce((function(e,t){return-1===q.indexOf(t)?(e[t]=a[t],e):e}),{}),c=e(i),u=K(l,c),d=arguments.length,b=new Array(d>3?d-3:0),p=3;p<d;p++)b[p-3]=arguments[p];return z()(W,2).apply(void 0,[u].concat(b))}),3),$=function(e){return!!e.extend},Y=function(e,t){if(e&&$(e)&&e.extend&&(e=e.extend),"string"==typeof e){var a=F(e.split(":"),2),r=a[0],n=a[1];e=t?t[r]:P[r],"inverted"===n&&(e=U(e))}return e&&Object.prototype.hasOwnProperty.call(e,"base00")?e:void 0},J=function(e){var t=function(e){return{backgroundColor:e.base00,ellipsisColor:e.base09,braceColor:e.base07,expandedIcon:e.base0D,collapsedIcon:e.base0E,keyColor:e.base07,arrayKeyColor:e.base0C,objectSize:e.base04,copyToClipboard:e.base0F,copyToClipboardCheck:e.base0D,objectBorder:e.base02,dataTypes:{boolean:e.base0E,date:e.base0D,float:e.base0B,function:e.base0D,integer:e.base0F,string:e.base09,nan:e.base08,null:e.base0A,undefined:e.base05,regexp:e.base0A,background:e.base02,bigNumber:e.base09},editVariable:{editIcon:e.base0E,cancelIcon:e.base09,removeIcon:e.base09,addIcon:e.base0E,checkIcon:e.base0E,background:e.base01,color:e.base0A,border:e.base07},addKeyModal:{background:e.base05,border:e.base04,color:e.base0A,labelColor:e.base01},validationFailure:{background:e.base09,iconColor:e.base01,fontColor:e.base01}}}(e);return{"app-container":{fontFamily:S.globalFontFamily,cursor:S.globalCursor,backgroundColor:t.backgroundColor,position:"relative"},ellipsis:{display:"inline-block",color:t.ellipsisColor,fontSize:S.ellipsisFontSize,lineHeight:S.ellipsisLineHeight,cursor:S.ellipsisCursor},"brace-row":{display:"inline-block",cursor:"pointer"},brace:{display:"inline-block",cursor:S.braceCursor,fontWeight:S.braceFontWeight,color:t.braceColor},"expanded-icon":{color:t.expandedIcon},"collapsed-icon":{color:t.collapsedIcon},colon:{display:"inline-block",margin:S.keyMargin,color:t.keyColor,verticalAlign:"top"},objectKeyVal:function(e,a){return{style:s({paddingTop:S.keyValPaddingTop,paddingRight:S.keyValPaddingRight,paddingBottom:S.keyValPaddingBottom,borderLeft:S.keyValBorderLeft+" "+t.objectBorder,":hover":{paddingLeft:a.paddingLeft-1+"px",borderLeft:S.keyValBorderHover+" "+t.objectBorder}},a)}},"object-key-val-no-border":{padding:S.keyValPadding},"pushed-content":{marginLeft:S.pushedContentMarginLeft},variableValue:function(e,t){return{style:s({display:"inline-block",paddingRight:S.variableValuePaddingRight,position:"relative"},t)}},"object-name":{display:"inline-block",color:t.keyColor,letterSpacing:S.keyLetterSpacing,fontStyle:S.keyFontStyle,verticalAlign:S.keyVerticalAlign,opacity:S.keyOpacity,":hover":{opacity:S.keyOpacityHover}},"array-key":{display:"inline-block",color:t.arrayKeyColor,letterSpacing:S.keyLetterSpacing,fontStyle:S.keyFontStyle,verticalAlign:S.keyVerticalAlign,opacity:S.keyOpacity,":hover":{opacity:S.keyOpacityHover}},"object-size":{color:t.objectSize,borderRadius:S.objectSizeBorderRadius,fontStyle:S.objectSizeFontStyle,margin:S.objectSizeMargin,cursor:"default"},"data-type-label":{fontSize:S.dataTypeFontSize,marginRight:S.dataTypeMarginRight,opacity:S.datatypeOpacity},boolean:{display:"inline-block",color:t.dataTypes.boolean},date:{display:"inline-block",color:t.dataTypes.date},"date-value":{marginLeft:S.dateValueMarginLeft},float:{display:"inline-block",color:t.dataTypes.float},function:{display:"inline-block",color:t.dataTypes.function,cursor:"pointer",whiteSpace:"pre-line"},"function-value":{fontStyle:"italic"},integer:{display:"inline-block",color:t.dataTypes.integer},bigNumber:{display:"inline-block",color:t.dataTypes.bigNumber},string:{display:"inline-block",color:t.dataTypes.string},nan:{display:"inline-block",color:t.dataTypes.nan,fontSize:S.nanFontSize,fontWeight:S.nanFontWeight,backgroundColor:t.dataTypes.background,padding:S.nanPadding,borderRadius:S.nanBorderRadius},null:{display:"inline-block",color:t.dataTypes.null,fontSize:S.nullFontSize,fontWeight:S.nullFontWeight,backgroundColor:t.dataTypes.background,padding:S.nullPadding,borderRadius:S.nullBorderRadius},undefined:{display:"inline-block",color:t.dataTypes.undefined,fontSize:S.undefinedFontSize,padding:S.undefinedPadding,borderRadius:S.undefinedBorderRadius,backgroundColor:t.dataTypes.background},regexp:{display:"inline-block",color:t.dataTypes.regexp},"copy-to-clipboard":{cursor:S.clipboardCursor},"copy-icon":{color:t.copyToClipboard,fontSize:S.iconFontSize,marginRight:S.iconMarginRight,verticalAlign:"top"},"copy-icon-copied":{color:t.copyToClipboardCheck,marginLeft:S.clipboardCheckMarginLeft},"array-group-meta-data":{display:"inline-block",padding:S.arrayGroupMetaPadding},"object-meta-data":{display:"inline-block",padding:S.metaDataPadding},"icon-container":{display:"inline-block",width:S.iconContainerWidth},tooltip:{padding:S.tooltipPadding},removeVarIcon:{verticalAlign:"top",display:"inline-block",color:t.editVariable.removeIcon,cursor:S.iconCursor,fontSize:S.iconFontSize,marginRight:S.iconMarginRight},addVarIcon:{verticalAlign:"top",display:"inline-block",color:t.editVariable.addIcon,cursor:S.iconCursor,fontSize:S.iconFontSize,marginRight:S.iconMarginRight},editVarIcon:{verticalAlign:"top",display:"inline-block",color:t.editVariable.editIcon,cursor:S.iconCursor,fontSize:S.iconFontSize,marginRight:S.iconMarginRight},"edit-icon-container":{display:"inline-block",verticalAlign:"top"},"check-icon":{display:"inline-block",cursor:S.iconCursor,color:t.editVariable.checkIcon,fontSize:S.iconFontSize,paddingRight:S.iconPaddingRight},"cancel-icon":{display:"inline-block",cursor:S.iconCursor,color:t.editVariable.cancelIcon,fontSize:S.iconFontSize,paddingRight:S.iconPaddingRight},"edit-input":{display:"inline-block",minWidth:S.editInputMinWidth,borderRadius:S.editInputBorderRadius,backgroundColor:t.editVariable.background,color:t.editVariable.color,padding:S.editInputPadding,marginRight:S.editInputMarginRight,fontFamily:S.editInputFontFamily},"detected-row":{paddingTop:S.detectedRowPaddingTop},"key-modal-request":{position:S.addKeyCoverPosition,top:S.addKeyCoverPositionPx,left:S.addKeyCoverPositionPx,right:S.addKeyCoverPositionPx,bottom:S.addKeyCoverPositionPx,backgroundColor:S.addKeyCoverBackground},"key-modal":{width:S.addKeyModalWidth,backgroundColor:t.addKeyModal.background,marginLeft:S.addKeyModalMargin,marginRight:S.addKeyModalMargin,padding:S.addKeyModalPadding,borderRadius:S.addKeyModalRadius,marginTop:"15px",position:"relative"},"key-modal-label":{color:t.addKeyModal.labelColor,marginLeft:"2px",marginBottom:"5px",fontSize:"11px"},"key-modal-input-container":{overflow:"hidden"},"key-modal-input":{width:"100%",padding:"3px 6px",fontFamily:"monospace",color:t.addKeyModal.color,border:"none",boxSizing:"border-box",borderRadius:"2px"},"key-modal-cancel":{backgroundColor:t.editVariable.removeIcon,position:"absolute",top:"0px",right:"0px",borderRadius:"0px 3px 0px 3px",cursor:"pointer"},"key-modal-cancel-icon":{color:t.addKeyModal.labelColor,fontSize:S.iconFontSize,transform:"rotate(45deg)"},"key-modal-submit":{color:t.editVariable.addIcon,fontSize:S.iconFontSize,position:"absolute",right:"2px",top:"3px",cursor:"pointer"},"function-ellipsis":{display:"inline-block",color:t.ellipsisColor,fontSize:S.ellipsisFontSize,lineHeight:S.ellipsisLineHeight,cursor:S.ellipsisCursor},"validation-failure":{float:"right",padding:"3px 6px",borderRadius:"2px",cursor:"pointer",color:t.validationFailure.fontColor,backgroundColor:t.validationFailure.background},"validation-failure-label":{marginRight:"6px"},"validation-failure-clear":{position:"relative",verticalAlign:"top",cursor:"pointer",color:t.validationFailure.iconColor,fontSize:S.iconFontSize,transform:"rotate(45deg)"},comma:{display:"inline-block",color:S.commaColor,fontSize:S.commaFontSize,marginRight:S.commaMarginRight,cursor:"default"}}};function G(e,t,a){return e||console.error("theme has not been set"),function(e){var t=O;return!1!==e&&"none"!==e||(t=M),H(J,{defaultBase16:t})(e)}(e)(t,a)}var Q=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=(e.rjvId,e.type_name),a=e.displayDataTypes,r=e.theme;return a?v().createElement("span",Object.assign({className:"data-type-label"},G(r,"data-type-label")),t):null}}])}(v().PureComponent),Z=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props;return v().createElement("div",G(e.theme,"boolean"),v().createElement(Q,Object.assign({type_name:"bool"},e)),e.value?"true":"false")}}])}(v().PureComponent),X=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props;return v().createElement("div",G(e.theme,"date"),v().createElement(Q,Object.assign({type_name:"date"},e)),v().createElement("span",Object.assign({className:"date-value"},G(e.theme,"date-value")),e.value.toLocaleTimeString("en-us",{weekday:"short",year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})))}}])}(v().PureComponent),ee=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props;return v().createElement("div",G(e.theme,"float"),v().createElement(Q,Object.assign({type_name:"float"},e)),this.props.value)}}])}(v().PureComponent);function te(e){return function(e){if(Array.isArray(e))return _(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||A(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var ae=r(9784),re=function(){return c((function e(){i(this,e),this.handler=function(){}}),[{key:"register",value:function(e){this.handler=e}},{key:"dispatch",value:function(e){var t;null===(t=this.handler)||void 0===t||t.call(this,e)}}])}();globalThis.__globalDispatcherInstance||(globalThis.__globalDispatcherInstance=new re);const ne=globalThis.__globalDispatcherInstance;var oe=new(function(e){function t(){var e;i(this,t);for(var a=arguments.length,r=new Array(a),n=0;n<a;n++)r[n]=arguments[n];return(e=p(this,t,[].concat(r))).objects={},e.set=function(t,a,r,n){void 0===e.objects[t]&&(e.objects[t]={}),void 0===e.objects[t][a]&&(e.objects[t][a]={}),e.objects[t][a][r]=n},e.get=function(t,a,r,n){return void 0===e.objects[t]||void 0===e.objects[t][a]||null==e.objects[t][a][r]?n:e.objects[t][a][r]},e.handleAction=function(t){var a=t.rjvId,r=t.data;switch(t.name){case"RESET":e.emit("reset-"+a);break;case"VARIABLE_UPDATED":t.data.updated_src=e.updateSrc(a,r),e.set(a,"action","variable-update",s(s({},r),{},{type:"variable-edited"})),e.emit("variable-update-"+a);break;case"VARIABLE_REMOVED":t.data.updated_src=e.updateSrc(a,r),e.set(a,"action","variable-update",s(s({},r),{},{type:"variable-removed"})),e.emit("variable-update-"+a);break;case"VARIABLE_ADDED":t.data.updated_src=e.updateSrc(a,r),e.set(a,"action","variable-update",s(s({},r),{},{type:"variable-added"})),e.emit("variable-update-"+a);break;case"ADD_VARIABLE_KEY_REQUEST":e.set(a,"action","new-key-request",r),e.emit("add-key-request-"+a)}},e.updateSrc=function(t,a){var r=a.name,n=a.namespace,o=a.new_value,s=(a.existing_value,a.variable_removed);n.shift();var i,l=e.get(t,"global","src"),c=e.deepCopy(l,te(n)),u=c,d=function(e,t){var a="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!a){if(Array.isArray(e)||(a=A(e))||t&&e&&"number"==typeof e.length){a&&(e=a);var r=0,n=function(){};return{s:n,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,s=!0,i=!1;return{s:function(){a=a.call(e)},n:function(){var e=a.next();return s=e.done,e},e:function(e){i=!0,o=e},f:function(){try{s||null==a.return||a.return()}finally{if(i)throw o}}}}(n);try{for(d.s();!(i=d.n()).done;){u=u[i.value]}}catch(e){d.e(e)}finally{d.f()}return s?"array"==x(u)?u.splice(r,1):delete u[r]:null!==r?u[r]=o:c=o,e.set(t,"global","src",c),c},e.deepCopy=function(t,a){var r,n=x(t),o=a.shift();return"array"==n?r=te(t):"object"==n&&(r=s({},t)),void 0!==o&&(r[o]=e.deepCopy(t[o],a)),r},e}return h(t,e),c(t)}(ae.EventEmitter));ne.register(oe.handleAction.bind(oe));const se=oe;var ie=function(e){function t(e){var a;return i(this,t),(a=p(this,t,[e])).toggleCollapsed=function(){a.setState({collapsed:!a.state.collapsed},(function(){se.set(a.props.rjvId,a.props.namespace,"collapsed",a.state.collapsed)}))},a.getFunctionDisplay=function(e){var t=a.props;return e?v().createElement("span",null,a.props.value.toString().slice(9,-1).replace(/\{[\s\S]+/,""),v().createElement("span",{className:"function-collapsed",style:{fontWeight:"bold"}},v().createElement("span",null,"{"),v().createElement("span",G(t.theme,"ellipsis"),"..."),v().createElement("span",null,"}"))):a.props.value.toString().slice(9,-1)},a.state={collapsed:se.get(e.rjvId,e.namespace,"collapsed",!0)},a}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=this.state.collapsed;return v().createElement("div",G(e.theme,"function"),v().createElement(Q,Object.assign({type_name:"function"},e)),v().createElement("span",Object.assign({},G(e.theme,"function-value"),{className:"rjv-function-container",onClick:this.toggleCollapsed}),this.getFunctionDisplay(t)))}}])}(v().PureComponent),le=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){return v().createElement("div",G(this.props.theme,"nan"),"NaN")}}])}(v().PureComponent),ce=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){return v().createElement("div",G(this.props.theme,"null"),"NULL")}}])}(v().PureComponent),ue=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props;return v().createElement("div",G(e.theme,"integer"),v().createElement(Q,Object.assign({type_name:"int"},e)),this.props.value)}}])}(v().PureComponent),de=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props;return v().createElement("div",G(e.theme,"regexp"),v().createElement(Q,Object.assign({type_name:"regexp"},e)),this.props.value.toString())}}])}(v().PureComponent),be=function(e){function t(e){var a;return i(this,t),(a=p(this,t,[e])).toggleCollapsed=function(){a.setState({collapsed:!a.state.collapsed},(function(){se.set(a.props.rjvId,a.props.namespace,"collapsed",a.state.collapsed)}))},a.state={collapsed:se.get(e.rjvId,e.namespace,"collapsed",!0)},a}return h(t,e),c(t,[{key:"render",value:function(){var e=this.state.collapsed,t=this.props,a=t.collapseStringsAfterLength,r=t.theme,n=t.escapeStrings,o=t.value,s="integer"===x(a),i={style:{cursor:"default",wordBreak:"break-all"}};return n&&(o=C(o)),s&&o.length>a&&(i.style.cursor="pointer",e&&(o=v().createElement("span",null,o.substring(0,a),v().createElement("span",G(r,"ellipsis")," ...")))),v().createElement("div",G(r,"string"),v().createElement(Q,Object.assign({type_name:"string"},t)),v().createElement("span",Object.assign({className:"string-value"},i,{onClick:this.toggleCollapsed}),'"',o,'"'))}}])}(v().PureComponent),pe=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){return v().createElement("div",G(this.props.theme,"undefined"),"undefined")}}])}(v().PureComponent),fe=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props;return v().createElement("div",G(e.theme,"bigNumber"),v().createElement(Q,Object.assign({type_name:"bigNumber"},e)),this.props.value.toString())}}])}(v().PureComponent);function he(){return he=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)({}).hasOwnProperty.call(a,r)&&(e[r]=a[r])}return e},he.apply(null,arguments)}const me=m.useLayoutEffect;var ve=function(e,t){"function"!=typeof e?e.current=t:e(t)};const ge=function(e,t){var a=(0,m.useRef)();return(0,m.useCallback)((function(r){e.current=r,a.current&&ve(a.current,null),a.current=t,t&&ve(t,r)}),[t])};var ye={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},ke=function(e){Object.keys(ye).forEach((function(t){e.style.setProperty(t,ye[t],"important")}))},Ee=null,we=function(e,t){var a=e.scrollHeight;return"border-box"===t.sizingStyle.boxSizing?a+t.borderSize:a-t.paddingSize};var je=function(){},xe=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],Ce=!!document.documentElement.currentStyle,Oe=function(e){var t=window.getComputedStyle(e);if(null===t)return null;var a,r=(a=t,xe.reduce((function(e,t){return e[t]=a[t],e}),{})),n=r.boxSizing;return""===n?null:(Ce&&"border-box"===n&&(r.width=parseFloat(r.width)+parseFloat(r.borderRightWidth)+parseFloat(r.borderLeftWidth)+parseFloat(r.paddingRight)+parseFloat(r.paddingLeft)+"px"),{sizingStyle:r,paddingSize:parseFloat(r.paddingBottom)+parseFloat(r.paddingTop),borderSize:parseFloat(r.borderBottomWidth)+parseFloat(r.borderTopWidth)})};function Me(e,t,a){var r,n,o=(r=a,n=m.useRef(r),me((function(){n.current=r})),n);m.useLayoutEffect((function(){var a=function(e){return o.current(e)};if(e)return e.addEventListener(t,a),function(){return e.removeEventListener(t,a)}}),[])}var Se=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],_e=function(e,t){var a=e.cacheMeasurements,r=e.maxRows,n=e.minRows,o=e.onChange,s=void 0===o?je:o,i=e.onHeightChange,l=void 0===i?je:i,c=w(e,Se),u=void 0!==c.value,d=m.useRef(null),b=ge(d,t),p=m.useRef(0),f=m.useRef(),h=function(){var e=d.current,t=a&&f.current?f.current:Oe(e);if(t){f.current=t;var o=function(e,t,a,r){void 0===a&&(a=1),void 0===r&&(r=1/0),Ee||((Ee=document.createElement("textarea")).setAttribute("tabindex","-1"),Ee.setAttribute("aria-hidden","true"),ke(Ee)),null===Ee.parentNode&&document.body.appendChild(Ee);var n=e.paddingSize,o=e.borderSize,s=e.sizingStyle,i=s.boxSizing;Object.keys(s).forEach((function(e){var t=e;Ee.style[t]=s[t]})),ke(Ee),Ee.value=t;var l=we(Ee,e);Ee.value=t,l=we(Ee,e),Ee.value="x";var c=Ee.scrollHeight-n,u=c*a;"border-box"===i&&(u=u+n+o),l=Math.max(u,l);var d=c*r;return"border-box"===i&&(d=d+n+o),[l=Math.min(d,l),c]}(t,e.value||e.placeholder||"x",n,r),s=o[0],i=o[1];p.current!==s&&(p.current=s,e.style.setProperty("height",s+"px","important"),l(s,{rowHeight:i}))}};return m.useLayoutEffect(h),function(e,t){Me(document.body,"reset",(function(a){e.current.form===a.target&&t(a)}))}(d,(function(){if(!u){var e=d.current.value;requestAnimationFrame((function(){var t=d.current;t&&e!==t.value&&h()}))}})),Me(window,"resize",h),function(e){Me(document.fonts,"loadingdone",e)}(h),m.createElement("textarea",he({},c,{onChange:function(e){u||h(),s(e)},ref:b}))},Ae=m.forwardRef(_e);function Fe(e,t){e=e.trim();try{if("["===(e=structuredClone(e))[0])return Pe("array",JSON.parse(e));if("{"===e[0])return Pe("object",JSON.parse(e));if(e.match(/\-?\d+\.\d+/)&&e.match(/\-?\d+\.\d+/)[0]===e)return t&&parseFloat(e).toString()!==e?Pe("bigNumber",e):Pe("float",parseFloat(e));if(e.match(/\-?\d+e-\d+/)&&e.match(/\-?\d+e-\d+/)[0]===e)return Pe("float",Number(e));if(e.match(/\-?\d+/)&&e.match(/\-?\d+/)[0]===e)return t&&parseInt(e).toString()!==e?Pe("bigNumber",e):Pe("integer",parseInt(e));if(e.match(/\-?\d+e\+\d+/)&&e.match(/\-?\d+e\+\d+/)[0]===e)return Pe("integer",Number(e))}catch(e){}switch(e=e.toLowerCase()){case"undefined":return Pe("undefined",void 0);case"nan":return Pe("nan",NaN);case"null":return Pe("null",null);case"true":return Pe("boolean",!0);case"false":return Pe("boolean",!1);default:if(e=Date.parse(e))return Pe("date",new Date(e))}return Pe(!1,null)}function Pe(e,t){return{type:e,value:t}}var Re=["style"],De=["style"],Ie=["style"],ze=["style"],Be=["style"],Ne=["style"],Le=["style"],qe=["style"],Ve=["style"],Te=["style"],Ke=["style"],We=["style"],Ue=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,Re);return v().createElement("span",a,v().createElement("svg",Object.assign({},rt(t),{viewBox:"0 0 24 24",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),v().createElement("path",{d:"M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M7,13H17V11H7"})))}}])}(v().PureComponent),He=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,De);return v().createElement("span",a,v().createElement("svg",Object.assign({},rt(t),{viewBox:"0 0 24 24",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),v().createElement("path",{d:"M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M13,7H11V11H7V13H11V17H13V13H17V11H13V7Z"})))}}])}(v().PureComponent),$e=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,Ie),r=rt(t).style;return v().createElement("span",a,v().createElement("svg",{fill:r.color,width:r.height,height:r.width,style:r,viewBox:"0 0 1792 1792"},v().createElement("path",{d:"M1344 800v64q0 14-9 23t-23 9h-832q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h832q14 0 23 9t9 23zm128 448v-832q0-66-47-113t-113-47h-832q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113zm128-832v832q0 119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119 84.5-203.5t203.5-84.5h832q119 0 203.5 84.5t84.5 203.5z"})))}}])}(v().PureComponent),Ye=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,ze),r=rt(t).style;return v().createElement("span",a,v().createElement("svg",{fill:r.color,width:r.height,height:r.width,style:r,viewBox:"0 0 1792 1792"},v().createElement("path",{d:"M1344 800v64q0 14-9 23t-23 9h-352v352q0 14-9 23t-23 9h-64q-14 0-23-9t-9-23v-352h-352q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h352v-352q0-14 9-23t23-9h64q14 0 23 9t9 23v352h352q14 0 23 9t9 23zm128 448v-832q0-66-47-113t-113-47h-832q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113zm128-832v832q0 119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119 84.5-203.5t203.5-84.5h832q119 0 203.5 84.5t84.5 203.5z"})))}}])}(v().PureComponent),Je=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,Be);return v().createElement("span",a,v().createElement("svg",{style:s(s({},rt(t).style),{},{paddingLeft:"2px",verticalAlign:"top"}),viewBox:"0 0 15 15",fill:"currentColor"},v().createElement("path",{d:"M0 14l6-6-6-6z"})))}}])}(v().PureComponent),Ge=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,Ne);return v().createElement("span",a,v().createElement("svg",{style:s(s({},rt(t).style),{},{paddingLeft:"2px",verticalAlign:"top"}),viewBox:"0 0 15 15",fill:"currentColor"},v().createElement("path",{d:"M0 5l6 6 6-6z"})))}}])}(v().PureComponent),Qe=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,Le);return v().createElement("span",a,v().createElement("svg",Object.assign({},rt(t),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),v().createElement("g",null,v().createElement("path",{d:"m30 35h-25v-22.5h25v7.5h2.5v-12.5c0-1.4-1.1-2.5-2.5-2.5h-7.5c0-2.8-2.2-5-5-5s-5 2.2-5 5h-7.5c-1.4 0-2.5 1.1-2.5 2.5v27.5c0 1.4 1.1 2.5 2.5 2.5h25c1.4 0 2.5-1.1 2.5-2.5v-5h-2.5v5z m-20-27.5h2.5s2.5-1.1 2.5-2.5 1.1-2.5 2.5-2.5 2.5 1.1 2.5 2.5 1.3 2.5 2.5 2.5h2.5s2.5 1.1 2.5 2.5h-20c0-1.5 1.1-2.5 2.5-2.5z m-2.5 20h5v-2.5h-5v2.5z m17.5-5v-5l-10 7.5 10 7.5v-5h12.5v-5h-12.5z m-17.5 10h7.5v-2.5h-7.5v2.5z m12.5-17.5h-12.5v2.5h12.5v-2.5z m-7.5 5h-5v2.5h5v-2.5z"}))))}}])}(v().PureComponent),Ze=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,qe);return v().createElement("span",a,v().createElement("svg",Object.assign({},rt(t),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),v().createElement("g",null,v().createElement("path",{d:"m28.6 25q0-0.5-0.4-1l-4-4 4-4q0.4-0.5 0.4-1 0-0.6-0.4-1.1l-2-2q-0.4-0.4-1-0.4-0.6 0-1 0.4l-4.1 4.1-4-4.1q-0.4-0.4-1-0.4-0.6 0-1 0.4l-2 2q-0.5 0.5-0.5 1.1 0 0.5 0.5 1l4 4-4 4q-0.5 0.5-0.5 1 0 0.7 0.5 1.1l2 2q0.4 0.4 1 0.4 0.6 0 1-0.4l4-4.1 4.1 4.1q0.4 0.4 1 0.4 0.6 0 1-0.4l2-2q0.4-0.4 0.4-1z m8.7-5q0 4.7-2.3 8.6t-6.3 6.2-8.6 2.3-8.6-2.3-6.2-6.2-2.3-8.6 2.3-8.6 6.2-6.2 8.6-2.3 8.6 2.3 6.3 6.2 2.3 8.6z"}))))}}])}(v().PureComponent),Xe=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,Ve);return v().createElement("span",a,v().createElement("svg",Object.assign({},rt(t),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),v().createElement("g",null,v().createElement("path",{d:"m30.1 21.4v-2.8q0-0.6-0.4-1t-1-0.5h-5.7v-5.7q0-0.6-0.4-1t-1-0.4h-2.9q-0.6 0-1 0.4t-0.4 1v5.7h-5.7q-0.6 0-1 0.5t-0.5 1v2.8q0 0.6 0.5 1t1 0.5h5.7v5.7q0 0.5 0.4 1t1 0.4h2.9q0.6 0 1-0.4t0.4-1v-5.7h5.7q0.6 0 1-0.5t0.4-1z m7.2-1.4q0 4.7-2.3 8.6t-6.3 6.2-8.6 2.3-8.6-2.3-6.2-6.2-2.3-8.6 2.3-8.6 6.2-6.2 8.6-2.3 8.6 2.3 6.3 6.2 2.3 8.6z"}))))}}])}(v().PureComponent),et=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,Te);return v().createElement("span",a,v().createElement("svg",Object.assign({},rt(t),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),v().createElement("g",null,v().createElement("path",{d:"m31.6 21.6h-10v10h-3.2v-10h-10v-3.2h10v-10h3.2v10h10v3.2z"}))))}}])}(v().PureComponent),tt=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,Ke);return v().createElement("span",a,v().createElement("svg",Object.assign({},rt(t),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),v().createElement("g",null,v().createElement("path",{d:"m19.8 26.4l2.6-2.6-3.4-3.4-2.6 2.6v1.3h2.2v2.1h1.2z m9.8-16q-0.3-0.4-0.7 0l-7.8 7.8q-0.4 0.4 0 0.7t0.7 0l7.8-7.8q0.4-0.4 0-0.7z m1.8 13.2v4.3q0 2.6-1.9 4.5t-4.5 1.9h-18.6q-2.6 0-4.5-1.9t-1.9-4.5v-18.6q0-2.7 1.9-4.6t4.5-1.8h18.6q1.4 0 2.6 0.5 0.3 0.2 0.4 0.5 0.1 0.4-0.2 0.7l-1.1 1.1q-0.3 0.3-0.7 0.1-0.5-0.1-1-0.1h-18.6q-1.4 0-2.5 1.1t-1 2.5v18.6q0 1.4 1 2.5t2.5 1h18.6q1.5 0 2.5-1t1.1-2.5v-2.9q0-0.2 0.2-0.4l1.4-1.5q0.3-0.3 0.8-0.1t0.4 0.6z m-2.1-16.5l6.4 6.5-15 15h-6.4v-6.5z m9.9 3l-2.1 2-6.4-6.4 2.1-2q0.6-0.7 1.5-0.7t1.5 0.7l3.4 3.4q0.6 0.6 0.6 1.5t-0.6 1.5z"}))))}}])}(v().PureComponent),at=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.style,a=j(e,We);return v().createElement("span",a,v().createElement("svg",Object.assign({},rt(t),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),v().createElement("g",null,v().createElement("path",{d:"m31.7 16.4q0-0.6-0.4-1l-2.1-2.1q-0.4-0.4-1-0.4t-1 0.4l-9.1 9.1-5-5q-0.5-0.4-1-0.4t-1 0.4l-2.1 2q-0.4 0.4-0.4 1 0 0.6 0.4 1l8.1 8.1q0.4 0.4 1 0.4 0.6 0 1-0.4l12.2-12.1q0.4-0.4 0.4-1z m5.6 3.6q0 4.7-2.3 8.6t-6.3 6.2-8.6 2.3-8.6-2.3-6.2-6.2-2.3-8.6 2.3-8.6 6.2-6.2 8.6-2.3 8.6 2.3 6.3 6.2 2.3 8.6z"}))))}}])}(v().PureComponent);function rt(e){return e||(e={}),{style:s(s({verticalAlign:"middle"},e),{},{color:e.color?e.color:"#000000",height:"1em",width:"1em"})}}var nt=function(e){function t(e){var a;return i(this,t),(a=p(this,t,[e])).copiedTimer=null,a.copyToClipboardFallback=function(e){var t=document.createElement("textarea");t.value=e,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)},a.handleCopy=function(){var e=a.props,t=e.clickCallback,r=e.src,n=e.namespace,o=JSON.stringify(a.clipboardValue(r),null,"  ");navigator.clipboard?navigator.clipboard.writeText(o).catch((function(){a.copyToClipboardFallback(o)})):a.copyToClipboardFallback(o),a.copiedTimer=setTimeout((function(){a.setState({copied:!1})}),5500),a.setState({copied:!0},(function(){"function"==typeof t&&t({src:r,namespace:n,name:n[n.length-1]})}))},a.getClippyIcon=function(){var e=a.props.theme;return a.state.copied?v().createElement("span",null,v().createElement(Qe,Object.assign({className:"copy-icon"},G(e,"copy-icon"))),v().createElement("span",G(e,"copy-icon-copied"),"✔")):v().createElement(Qe,Object.assign({className:"copy-icon"},G(e,"copy-icon")))},a.clipboardValue=function(e){switch(x(e)){case"function":case"regexp":return e.toString();default:return e}},a.state={copied:!1},a}return h(t,e),c(t,[{key:"componentWillUnmount",value:function(){this.copiedTimer&&(clearTimeout(this.copiedTimer),this.copiedTimer=null)}},{key:"render",value:function(){var e=this.props,t=(e.src,e.theme),a=e.hidden,r=e.rowHovered,n=G(t,"copy-to-clipboard").style,o="inline";return a&&(o="none"),v().createElement("span",{className:"copy-to-clipboard-container",title:"Copy to clipboard",style:{verticalAlign:"top",display:r?"inline-block":"none"}},v().createElement("span",{style:s(s({},n),{},{display:o}),onClick:this.handleCopy},this.getClippyIcon()))}}])}(v().PureComponent);const ot=function(e){function t(e){var a;return i(this,t),(a=p(this,t,[e])).getEditIcon=function(){var e=a.props,t=e.variable,r=e.theme;return v().createElement("div",{className:"click-to-edit",style:{verticalAlign:"top",display:a.state.hovered?"inline-block":"none"}},v().createElement(tt,Object.assign({className:"click-to-edit-icon"},G(r,"editVarIcon"),{onClick:function(){a.prepopInput(t)}})))},a.prepopInput=function(e){if(!1!==a.props.onEdit){var t=function(e,t){var a;switch(x(e,t)){case"undefined":a="undefined";break;case"nan":a="NaN";break;case"string":a=e;break;case"bigNumber":case"date":case"function":case"regexp":a=e.toString();break;default:try{a=JSON.stringify(e,null,"  ")}catch(e){a=""}}return a}(e.value,a.props.bigNumber),r=Fe(t,a.props.bigNumber);a.setState({editMode:!0,editValue:t,parsedInput:{type:r.type,value:r.value}})}},a.getRemoveIcon=function(){var e=a.props,t=e.variable,r=e.namespace,n=e.theme,o=e.rjvId;return v().createElement("div",{className:"click-to-remove",style:{verticalAlign:"top",display:a.state.hovered?"inline-block":"none"}},v().createElement(Ze,Object.assign({className:"click-to-remove-icon"},G(n,"removeVarIcon"),{onClick:function(){ne.dispatch({name:"VARIABLE_REMOVED",rjvId:o,data:{name:t.name,namespace:r,existing_value:t.value,variable_removed:!0}})}})))},a.getValue=function(e,t){var r=!t&&e.type,n=a.props;switch(r){case!1:return a.getEditInput();case"string":return v().createElement(be,Object.assign({value:e.value},n));case"integer":return v().createElement(ue,Object.assign({value:e.value},n));case"float":return v().createElement(ee,Object.assign({value:e.value},n));case"boolean":return v().createElement(Z,Object.assign({value:e.value},n));case"function":return v().createElement(ie,Object.assign({value:e.value},n));case"null":return v().createElement(ce,n);case"nan":return v().createElement(le,n);case"undefined":return v().createElement(pe,n);case"date":return v().createElement(X,Object.assign({value:e.value},n));case"regexp":return v().createElement(de,Object.assign({value:e.value},n));case"bigNumber":return v().createElement(fe,Object.assign({value:e.value},n));default:return v().createElement("div",{className:"object-value"},JSON.stringify(e.value))}},a.getEditInput=function(){var e=a.props,t=e.keyModifier,r=e.selectOnFocus,n=e.theme,o=a.state.editValue;return v().createElement("div",null,v().createElement(Ae,Object.assign({type:"text",ref:function(e){e&&e[r?"select":"focus"]()},value:o,className:"variable-editor",onChange:function(e){var t=e.target.value,r=Fe(t,a.props.bigNumber);a.setState({editValue:t,parsedInput:{type:r.type,value:r.value}})},onKeyDown:function(e){switch(e.key){case"Escape":a.setState({editMode:!1,editValue:""});break;case"Enter":t(e,"submit")&&a.submitEdit(!0)}e.stopPropagation()},placeholder:"update this value",minRows:2},G(n,"edit-input"))),v().createElement("div",G(n,"edit-icon-container"),v().createElement(Ze,Object.assign({className:"edit-cancel"},G(n,"cancel-icon"),{onClick:function(e){e&&e.stopPropagation(),a.setState({editMode:!1,editValue:""})}})),v().createElement(at,Object.assign({className:"edit-check string-value"},G(n,"check-icon"),{onClick:function(e){e&&e.stopPropagation(),a.submitEdit()}})),v().createElement("div",null,a.showDetected())))},a.submitEdit=function(e){var t=a.props,r=t.variable,n=t.namespace,o=t.rjvId,s=t.bigNumber,i=a.state,l=i.editValue,c=i.parsedInput,u=l;e&&c.type&&(u=c.value,s&&"bigNumber"===c.type&&(u=new s(u))),a.setState({editMode:!1}),ne.dispatch({name:"VARIABLE_UPDATED",rjvId:o,data:{name:r.name,namespace:n,existing_value:r.value,new_value:u,variable_removed:!1}})},a.showDetected=function(){var e=a.props,t=e.theme,r=(e.variable,e.namespace,e.rjvId,a.state.parsedInput),n=(r.type,r.value,a.getDetectedInput());if(n)return v().createElement("div",null,v().createElement("div",G(t,"detected-row"),n,v().createElement(at,{className:"edit-check detected",style:s({verticalAlign:"top",paddingLeft:"3px"},G(t,"check-icon").style),onClick:function(e){e&&e.stopPropagation(),a.submitEdit(!0)}})))},a.getDetectedInput=function(){var e=a.state.parsedInput,t=e.type,r=e.value,n=a.props,o=n.theme;if(!1!==t)switch(t.toLowerCase()){case"object":return v().createElement("span",null,v().createElement("span",{style:s(s({},G(o,"brace").style),{},{cursor:"default"})},"{"),v().createElement("span",{style:s(s({},G(o,"ellipsis").style),{},{cursor:"default"})},"..."),v().createElement("span",{style:s(s({},G(o,"brace").style),{},{cursor:"default"})},"}"));case"array":return v().createElement("span",null,v().createElement("span",{style:s(s({},G(o,"brace").style),{},{cursor:"default"})},"["),v().createElement("span",{style:s(s({},G(o,"ellipsis").style),{},{cursor:"default"})},"..."),v().createElement("span",{style:s(s({},G(o,"brace").style),{},{cursor:"default"})},"]"));case"string":return v().createElement(be,Object.assign({value:r},n));case"integer":return v().createElement(ue,Object.assign({value:r},n));case"float":return v().createElement(ee,Object.assign({value:r},n));case"boolean":return v().createElement(Z,Object.assign({value:r},n));case"function":return v().createElement(ie,Object.assign({value:r},n));case"null":return v().createElement(ce,n);case"nan":return v().createElement(le,n);case"undefined":return v().createElement(pe,n);case"date":return v().createElement(X,Object.assign({value:new Date(r)},n));case"bignumber":return v().createElement(fe,Object.assign({value:r},n))}},a.state={editMode:!1,editValue:"",hovered:!1,renameKey:!1,parsedInput:{type:!1,value:null}},a}return h(t,e),c(t,[{key:"render",value:function(){var e=this,t=this.props,a=t.variable,r=t.singleIndent,n=t.type,o=t.theme,i=t.namespace,l=t.indentWidth,c=t.enableClipboard,u=t.onEdit,d=t.onDelete,b=t.onSelect,p=t.displayArrayKey,f=t.quotesOnKeys,h=t.keyModifier,m=t.showComma,g=t.isLast,y=this.state.editMode;return v().createElement("div",Object.assign({},G(o,"objectKeyVal",{paddingLeft:l*r}),{onMouseEnter:function(){return e.setState(s(s({},e.state),{},{hovered:!0}))},onMouseLeave:function(){return e.setState(s(s({},e.state),{},{hovered:!1}))},className:"variable-row",key:a.name}),"array"==n?p?v().createElement("span",Object.assign({},G(o,"array-key"),{key:a.name+"_"+i}),a.name,v().createElement("div",G(o,"colon"),":")):null:v().createElement("span",null,v().createElement("span",Object.assign({},G(o,"object-name"),{className:"object-key",key:a.name+"_"+i}),!!f&&v().createElement("span",{style:{verticalAlign:"top"}},'"'),v().createElement("span",{style:{display:"inline-block"}},C(a.name)),!!f&&v().createElement("span",{style:{verticalAlign:"top"}},'"')),v().createElement("span",G(o,"colon"),":")),v().createElement("div",Object.assign({className:"variable-value",onClick:!1===b&&!1===u?null:function(t){var r=te(i);h(t,"edit")&&!1!==u?e.prepopInput(a):!1!==b&&(r.shift(),b(s(s({},a),{},{namespace:r})))}},G(o,"variableValue",{cursor:!1===b?"default":"pointer"})),this.getValue(a,y)),m&&!g&&v().createElement("span",G(o,"comma"),","),c?v().createElement(nt,{rowHovered:this.state.hovered,hidden:y,src:a.value,clickCallback:c,theme:o,namespace:[].concat(te(i),[a.name])}):null,!1!==u&&0==y?this.getEditIcon():null,!1!==d&&0==y?this.getRemoveIcon():null)}}])}(v().PureComponent);var st=function(e){function t(){var e;i(this,t);for(var a=arguments.length,r=new Array(a),n=0;n<a;n++)r[n]=arguments[n];return(e=p(this,t,[].concat(r))).getObjectSize=function(){var t=e.props,a=t.size,r=t.theme;if(t.displayObjectSize)return v().createElement("span",Object.assign({className:"object-size"},G(r,"object-size")),a," item",1===a?"":"s")},e.getAddAttribute=function(t){var a=e.props,r=a.theme,n=a.namespace,o=a.name,i=a.src,l=a.rjvId,c=a.depth;return v().createElement("span",{className:"click-to-add",style:{verticalAlign:"top",display:t?"inline-block":"none"}},v().createElement(Xe,Object.assign({className:"click-to-add-icon"},G(r,"addVarIcon"),{onClick:function(){var e={name:c>0?o:null,namespace:n.splice(0,n.length-1),existing_value:i,variable_removed:!1,key_name:null};"object"===x(i)?ne.dispatch({name:"ADD_VARIABLE_KEY_REQUEST",rjvId:l,data:e}):ne.dispatch({name:"VARIABLE_ADDED",rjvId:l,data:s(s({},e),{},{new_value:[].concat(te(i),[null])})})}})))},e.getRemoveObject=function(t){var a=e.props,r=a.theme,n=(a.hover,a.namespace),o=a.name,s=a.src,i=a.rjvId;if(1!==n.length)return v().createElement("span",{className:"click-to-remove",style:{display:t?"inline-block":"none"}},v().createElement(Ze,Object.assign({className:"click-to-remove-icon"},G(r,"removeVarIcon"),{onClick:function(){ne.dispatch({name:"VARIABLE_REMOVED",rjvId:i,data:{name:o,namespace:n.splice(0,n.length-1),existing_value:s,variable_removed:!0}})}})))},e.render=function(){var t=e.props,a=t.theme,r=t.onDelete,n=t.onAdd,o=t.enableClipboard,s=t.src,i=t.namespace,l=t.rowHovered;return v().createElement("div",Object.assign({},G(a,"object-meta-data"),{className:"object-meta-data",onClick:function(e){e.stopPropagation()}}),e.getObjectSize(),o?v().createElement(nt,{rowHovered:l,clickCallback:o,src:s,theme:a,namespace:i}):null,!1!==n?e.getAddAttribute(l):null,!1!==r?e.getRemoveObject(l):null)},e}return h(t,e),c(t)}(v().PureComponent);function it(e){var t=e.parent_type,a=e.namespace,r=e.quotesOnKeys,n=e.theme,o=e.jsvRoot,s=e.name,i=e.displayArrayKey,l=e.name?e.name:"";return!o||!1!==s&&null!==s?"array"==t?i?v().createElement("span",Object.assign({},G(n,"array-key"),{key:a}),v().createElement("span",{className:"array-key"},l),v().createElement("span",G(n,"colon"),":")):v().createElement("span",null):v().createElement("span",Object.assign({},G(n,"object-name"),{key:a}),v().createElement("span",{className:"object-key"},r&&v().createElement("span",{style:{verticalAlign:"top"}},'"'),v().createElement("span",null,l),r&&v().createElement("span",{style:{verticalAlign:"top"}},'"')),v().createElement("span",G(n,"colon"),":")):v().createElement("span",null)}function lt(e){var t=e.theme;switch(e.iconStyle){case"triangle":return v().createElement(Ge,Object.assign({},G(t,"expanded-icon"),{className:"expanded-icon"}));case"square":return v().createElement($e,Object.assign({},G(t,"expanded-icon"),{className:"expanded-icon"}));default:return v().createElement(Ue,Object.assign({},G(t,"expanded-icon"),{className:"expanded-icon"}))}}function ct(e){var t=e.theme;switch(e.iconStyle){case"triangle":return v().createElement(Je,Object.assign({},G(t,"collapsed-icon"),{className:"collapsed-icon"}));case"square":return v().createElement(Ye,Object.assign({},G(t,"collapsed-icon"),{className:"collapsed-icon"}));default:return v().createElement(He,Object.assign({},G(t,"collapsed-icon"),{className:"collapsed-icon"}))}}var ut=["src","groupArraysAfterLength","depth","name","theme","jsvRoot","namespace","parent_type"],dt=function(e){function t(e){var a;return i(this,t),(a=p(this,t,[e])).toggleCollapsed=function(e){var t=[];for(var r in a.state.expanded)t.push(a.state.expanded[r]);t[e]=!t[e],a.setState({expanded:t})},a.state={expanded:[]},a}return h(t,e),c(t,[{key:"getExpandedIcon",value:function(e){var t=this.props,a=t.theme,r=t.iconStyle;return this.state.expanded[e]?v().createElement(lt,{theme:a,iconStyle:r}):v().createElement(ct,{theme:a,iconStyle:r})}},{key:"render",value:function(){var e=this,t=this.props,a=t.src,r=t.groupArraysAfterLength,n=(t.depth,t.name),o=t.theme,s=t.jsvRoot,i=t.namespace,l=(t.parent_type,j(t,ut)),c=0,u=5*this.props.indentWidth;s||(c=5*this.props.indentWidth);var d=r,b=Math.ceil(a.length/d);return v().createElement("div",Object.assign({className:"object-key-val"},G(o,s?"jsv-root":"objectKeyVal",{paddingLeft:c})),v().createElement(it,this.props),v().createElement("span",null,v().createElement(st,Object.assign({size:a.length},this.props))),te(Array(b)).map((function(t,r){return v().createElement("div",Object.assign({key:r,className:"object-key-val array-group"},G(o,"objectKeyVal",{marginLeft:6,paddingLeft:u})),v().createElement("span",G(o,"brace-row"),v().createElement("div",Object.assign({className:"icon-container"},G(o,"icon-container"),{onClick:function(t){e.toggleCollapsed(r)}}),e.getExpandedIcon(r)),e.state.expanded[r]?v().createElement(ht,Object.assign({key:n+r,depth:0,name:!1,collapsed:!1,groupArraysAfterLength:d,index_offset:r*d,src:a.slice(r*d,r*d+d),namespace:i,type:"array",parent_type:"array_group",theme:o,showComma:e.props.showComma,isLast:r===b-1},l)):v().createElement("span",Object.assign({},G(o,"brace"),{onClick:function(t){e.toggleCollapsed(r)},className:"array-group-brace"}),"[",v().createElement("div",Object.assign({},G(o,"array-group-meta-data"),{className:"array-group-meta-data"}),v().createElement("span",Object.assign({className:"object-size"},G(o,"object-size")),r*d," - ",r*d+d>a.length?a.length:r*d+d)),"]")))})))}}])}(v().PureComponent),bt=["depth","src","namespace","name","type","parent_type","theme","jsvRoot","iconStyle","showComma","isLast"],pt=function(e){function t(e){var a;i(this,t),(a=p(this,t,[e])).toggleCollapsed=function(){a.setState({expanded:!a.state.expanded},(function(){se.set(a.props.rjvId,a.props.namespace,"expanded",a.state.expanded)}))},a.getObjectContent=function(e,t,r){return v().createElement("div",{className:"pushed-content object-container"},v().createElement("div",Object.assign({className:"object-content"},G(a.props.theme,"pushed-content")),a.renderObjectContents(t,r)))},a.getEllipsis=function(){return 0===a.state.size?null:v().createElement("div",Object.assign({},G(a.props.theme,"ellipsis"),{className:"node-ellipsis",onClick:a.toggleCollapsed}),"...")},a.getObjectMetaData=function(e){var t=a.props,r=(t.rjvId,t.theme,a.state),n=r.size,o=r.hovered;return v().createElement(st,Object.assign({rowHovered:o,size:n},a.props))},a.renderObjectContents=function(e,t){var r,n=a.props,o=n.depth,s=n.parent_type,i=n.index_offset,l=n.groupArraysAfterLength,c=n.namespace,u=n.showComma,d=a.state.object_type,b=[],p=Object.keys(e||{});return a.props.sortKeys&&"array"!==d&&(p=p.sort()),p.forEach((function(n,f){r=new ft(n,e[n],t.bigNumber);var h=f===p.length-1;if("array_group"===s&&i&&(r.name=parseInt(r.name)+i),Object.prototype.hasOwnProperty.call(e,n))if("object"===r.type)b.push(v().createElement(ht,Object.assign({key:r.name,depth:o+1,name:r.name,src:r.value,namespace:c.concat(r.name),parent_type:d,isLast:h,showComma:u},t)));else if("array"===r.type){var m=ht;l&&r.value.length>l&&(m=dt),b.push(v().createElement(m,Object.assign({key:r.name,depth:o+1,name:r.name,src:r.value,namespace:c.concat(r.name),type:"array",parent_type:d,isLast:h,showComma:u},t)))}else b.push(v().createElement(ot,Object.assign({key:r.name+"_"+c,variable:r,singleIndent:5,namespace:c,type:a.props.type,isLast:h,showComma:u},t)));else;})),b};var r=t.getState(e);return a.state=s(s({},r),{},{prevProps:{}}),a}return h(t,e),c(t,[{key:"getBraceStart",value:function(e,t){var a=this,r=this.props,n=(r.src,r.theme),o=r.iconStyle;if("array_group"===r.parent_type)return v().createElement("span",null,v().createElement("span",G(n,"brace"),"array"===e?"[":"{"));var s=t?lt:ct;return v().createElement("span",null,v().createElement("span",Object.assign({onClick:function(e){a.toggleCollapsed()}},G(n,"brace-row")),v().createElement("div",Object.assign({className:"icon-container"},G(n,"icon-container")),v().createElement(s,{theme:n,iconStyle:o})),v().createElement(it,this.props),v().createElement("span",G(n,"brace"),"array"===e?"[":"{")))}},{key:"render",value:function(){var e=this,t=this.props,a=t.depth,r=t.src,n=(t.namespace,t.name,t.type,t.parent_type),o=t.theme,i=t.jsvRoot,l=t.iconStyle,c=t.showComma,u=t.isLast,d=j(t,bt),b=this.state,p=b.object_type,f=b.expanded,h={};return i||"array_group"===n?"array_group"===n&&(h.borderLeft=0,h.display="inline"):h.paddingLeft=5*this.props.indentWidth,v().createElement("div",Object.assign({className:"object-key-val",onMouseEnter:function(){return e.setState(s(s({},e.state),{},{hovered:!0}))},onMouseLeave:function(){return e.setState(s(s({},e.state),{},{hovered:!1}))}},G(o,i?"jsv-root":"objectKeyVal",h)),this.getBraceStart(p,f),f?this.getObjectContent(a,r,s({theme:o,iconStyle:l},d)):this.getEllipsis(),v().createElement("span",{className:"brace-row"},v().createElement("span",{style:s(s({},G(o,"brace").style),{},{paddingLeft:f?"3px":"0px"})},"array"===p?"]":"}")),c&&!u&&!i&&v().createElement("span",G(o,"comma"),","),this.getObjectMetaData(r))}}],[{key:"getDerivedStateFromProps",value:function(e,a){var r=a.prevProps;return e.src!==r.src||e.collapsed!==r.collapsed||e.name!==r.name||e.namespace!==r.namespace||e.rjvId!==r.rjvId?s(s({},t.getState(e)),{},{prevProps:e}):null}}])}(v().PureComponent);pt.getState=function(e){var t=Object.keys(e.src).length,a=(!1===e.collapsed||!0!==e.collapsed&&e.collapsed>e.depth)&&(!e.shouldCollapse||!1===e.shouldCollapse({name:e.name,src:e.src,type:x(e.src),namespace:e.namespace}))&&0!==t;return{expanded:se.get(e.rjvId,e.namespace,"expanded",a),object_type:"array"===e.type?"array":"object",parent_type:"array"===e.type?"array":"object",size:t,hovered:!1}};var ft=c((function e(t,a,r){i(this,e),this.name=t,this.value=a,this.type=x(a,r)}));E(pt);const ht=pt;var mt=function(e){function t(){var e;i(this,t);for(var a=arguments.length,r=new Array(a),n=0;n<a;n++)r[n]=arguments[n];return(e=p(this,t,[].concat(r))).render=function(){var t,a,r,n,o=e.props,s=[o.name],i=ht;"object"!=typeof o.name||Array.isArray(o.name)||(s=[(null===(t=o.name)||void 0===t?void 0:t.displayName)||(null===(a=o.name)||void 0===a?void 0:a.name)||(null===(r=o.name)||void 0===r||null===(n=r.type)||void 0===n?void 0:n.name)||"Anonymous"]);return Array.isArray(o.src)&&o.groupArraysAfterLength&&o.src.length>o.groupArraysAfterLength&&(i=dt),v().createElement("div",{className:"pretty-json-container object-container"},v().createElement("div",{className:"object-content"},v().createElement(i,Object.assign({namespace:s,depth:0,jsvRoot:!0},o))))},e}return h(t,e),c(t)}(v().PureComponent),vt=function(e){function t(e){var a;return i(this,t),(a=p(this,t,[e])).closeModal=function(){ne.dispatch({rjvId:a.props.rjvId,name:"RESET"})},a.submit=function(){a.props.submit(a.state.input)},a.state={input:e.input?e.input:""},a}return h(t,e),c(t,[{key:"render",value:function(){var e=this,t=this.props,a=t.theme,r=t.rjvId,n=t.isValid,o=this.state.input,s=n(o);return v().createElement("div",Object.assign({className:"key-modal-request"},G(a,"key-modal-request"),{onClick:this.closeModal}),v().createElement("div",Object.assign({},G(a,"key-modal"),{onClick:function(e){e.stopPropagation()}}),v().createElement("div",G(a,"key-modal-label"),"Key Name:"),v().createElement("div",{style:{position:"relative"}},v().createElement("input",Object.assign({},G(a,"key-modal-input"),{className:"key-modal-input",ref:function(e){return e&&e.focus()},spellCheck:!1,value:o,placeholder:"...",onChange:function(t){e.setState({input:t.target.value})},onKeyPress:function(t){s&&"Enter"===t.key?e.submit():"Escape"===t.key&&e.closeModal()}})),s?v().createElement(at,Object.assign({},G(a,"key-modal-submit"),{className:"key-modal-submit",onClick:function(t){return e.submit()}})):null),v().createElement("span",G(a,"key-modal-cancel"),v().createElement(et,Object.assign({},G(a,"key-modal-cancel-icon"),{className:"key-modal-cancel",onClick:function(){ne.dispatch({rjvId:r,name:"RESET"})}})))))}}])}(v().PureComponent),gt=function(e){function t(){var e;i(this,t);for(var a=arguments.length,r=new Array(a),n=0;n<a;n++)r[n]=arguments[n];return(e=p(this,t,[].concat(r))).isValid=function(t){var a=e.props.rjvId,r=se.get(a,"action","new-key-request");return""!=t&&-1===Object.keys(r.existing_value).indexOf(t)},e.submit=function(t){var a=e.props.rjvId,r=se.get(a,"action","new-key-request");r.new_value=s({},r.existing_value),r.new_value[t]=e.props.defaultValue,ne.dispatch({name:"VARIABLE_ADDED",rjvId:a,data:r})},e}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.active,a=e.theme,r=e.rjvId;return t?v().createElement(vt,{rjvId:r,theme:a,isValid:this.isValid,submit:this.submit}):null}}])}(v().PureComponent),yt=function(e){function t(){return i(this,t),p(this,t,arguments)}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.message,a=e.active,r=e.theme,n=e.rjvId;return a?v().createElement("div",Object.assign({className:"validation-failure"},G(r,"validation-failure"),{onClick:function(){ne.dispatch({rjvId:n,name:"RESET"})}}),v().createElement("span",G(r,"validation-failure-label"),t),v().createElement(et,G(r,"validation-failure-clear"))):null}}])}(v().PureComponent),kt=function(e){function t(e){var a;return i(this,t),(a=p(this,t,[e])).rjvId=Date.now().toString()+Math.random().toString(36).slice(2),a.getListeners=function(){return{reset:a.resetState,"variable-update":a.updateSrc,"add-key-request":a.addKeyRequest}},a.updateSrc=function(){var e,t=se.get(a.rjvId,"action","variable-update"),r=t.name,n=t.namespace,o=t.new_value,s=t.existing_value,i=t.updated_src,l=t.type,c=a.props,u=c.onEdit,d=c.onDelete,b=c.onAdd,p={existing_src:a.state.src,new_value:o,updated_src:i,name:r,namespace:n,existing_value:s};switch(l){case"variable-added":e=b(p);break;case"variable-edited":e=u(p);break;case"variable-removed":e=d(p)}!1!==e?(se.set(a.rjvId,"global","src",i),a.setState({src:i})):a.setState({validationFailure:!0})},a.addKeyRequest=function(){a.setState({addKeyRequest:!0})},a.resetState=function(){a.setState({validationFailure:!1,addKeyRequest:!1})},a.state={addKeyRequest:!1,editKeyRequest:!1,validationFailure:!1,src:t.defaultProps.src,name:t.defaultProps.name,theme:t.defaultProps.theme,validationMessage:t.defaultProps.validationMessage,prevSrc:t.defaultProps.src,prevName:t.defaultProps.name,prevTheme:t.defaultProps.theme},a}return h(t,e),c(t,[{key:"componentDidMount",value:function(){se.set(this.rjvId,"global","src",this.state.src);var e=this.getListeners();for(var t in e)se.on(t+"-"+this.rjvId,e[t]);this.setState({addKeyRequest:!1,editKeyRequest:!1})}},{key:"componentDidUpdate",value:function(e,t){!1!==t.addKeyRequest&&this.setState({addKeyRequest:!1}),!1!==t.editKeyRequest&&this.setState({editKeyRequest:!1}),e.src!==this.state.src&&se.set(this.rjvId,"global","src",this.state.src)}},{key:"componentWillUnmount",value:function(){var e=this.getListeners();for(var t in e)se.removeListener(t+"-"+this.rjvId,e[t])}},{key:"render",value:function(){var e=this.state,t=e.validationFailure,a=e.validationMessage,r=e.addKeyRequest,n=e.theme,o=e.src,i=e.name,l=this.props,c=l.style,u=l.defaultValue;return v().createElement("div",{className:"react-json-view",style:s(s({},G(n,"app-container").style),c)},v().createElement(yt,{message:a,active:t,theme:n,rjvId:this.rjvId}),v().createElement(mt,Object.assign({},this.props,{src:o,name:i,theme:n,type:x(o),rjvId:this.rjvId})),v().createElement(gt,{active:r,theme:n,rjvId:this.rjvId,defaultValue:u}))}}],[{key:"getDerivedStateFromProps",value:function(e,a){if(e.src!==a.prevSrc||e.name!==a.prevName||e.theme!==a.prevTheme){var r={src:e.src,name:e.name,theme:e.theme,validationMessage:e.validationMessage,prevSrc:e.src,prevName:e.name,prevTheme:e.theme};return t.validateState(r)}return null}}])}(v().PureComponent);kt.defaultProps={src:{},name:"root",theme:"rjv-default",collapsed:!1,collapseStringsAfterLength:!1,shouldCollapse:!1,sortKeys:!1,quotesOnKeys:!0,groupArraysAfterLength:100,indentWidth:4,enableClipboard:!0,escapeStrings:!0,displayObjectSize:!0,displayDataTypes:!0,onEdit:!1,onDelete:!1,onAdd:!1,onSelect:!1,iconStyle:"triangle",style:{},validationMessage:"Validation Error",defaultValue:null,displayArrayKey:!0,selectOnFocus:!1,keyModifier:function(e){return e.metaKey||e.ctrlKey},bigNumber:null,showComma:!0},kt.validateState=function(e){var t={};return"object"!==x(e.theme)||function(e){var t=["base00","base01","base02","base03","base04","base05","base06","base07","base08","base09","base0A","base0B","base0C","base0D","base0E","base0F"];if("object"===x(e)){for(var a=0;a<t.length;a++)if(!(t[a]in e))return!1;return!0}return!1}(e.theme)||(console.error("react-json-view error:","theme prop must be a theme name or valid base-16 theme object.",'defaulting to "rjv-default" theme'),t.theme="rjv-default"),"object"!==x(e.src)&&"array"!==x(e.src)&&(console.error("react-json-view error:","src property must be a valid json object"),t.name="ERROR",t.src={message:"src property must be a valid json object"}),s(s({},e),t)},E(kt);const Et=kt})(),n})()));

/***/ }),

/***/ 1644:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgImportSlanted = function SvgImportSlanted(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.57606 4.04646C3.85736 3.76515 4.23889 3.60712 4.63672 3.60712H12.8867C13.3009 3.60712 13.6367 3.9429 13.6367 4.35712C13.6367 4.77133 13.3009 5.10712 12.8867 5.10712L4.63672 5.10712L4.63672 20.1071H19.6367V11.8571C19.6367 11.4429 19.9725 11.1071 20.3867 11.1071C20.8009 11.1071 21.1367 11.4429 21.1367 11.8571V20.1071C21.1367 20.5049 20.9787 20.8865 20.6974 21.1678C20.4161 21.4491 20.0345 21.6071 19.6367 21.6071H4.63672C4.2389 21.6071 3.85736 21.4491 3.57606 21.1678C3.29475 20.8865 3.13672 20.5049 3.13672 20.1071V5.10712C3.13672 4.70929 3.29475 4.32776 3.57606 4.04646Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M18.7134 7.1069C19.0063 6.81401 19.0063 6.33913 18.7134 6.04624C18.4205 5.75335 17.9457 5.75335 17.6528 6.04624L11.5083 12.1907L11.5083 8.43274C11.5083 8.01853 11.1725 7.68274 10.7583 7.68274C10.3441 7.68274 10.0083 8.01853 10.0083 8.43274V14.0012C10.0083 14.4154 10.3441 14.7512 10.7583 14.7512L16.3268 14.7512C16.741 14.7512 17.0768 14.4154 17.0768 14.0012C17.0768 13.587 16.741 13.2512 16.3268 13.2512L12.5691 13.2512L18.7134 7.1069Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgImportSlanted);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "a6157f94762b11bb35a5b0a8d859a12a.svg");

/***/ }),

/***/ 1647:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.TreeView-module__Root--VXBM9{width:100%;display:flex;flex-direction:column}.TreeView-module__TreeViewItemDraggable--V1X1a{user-select:none;cursor:pointer}.TreeView-module__TreeViewItemDraggable--V1X1a *{pointer-events:none}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/tree-view/TreeView/TreeView.module.scss"],"names":[],"mappings":"AAAA,8BACE,UAAA,CACA,YAAA,CACA,qBAAA,CAGF,+CACE,gBAAA,CACA,cAAA,CAEA,iDACE,mBAAA","sourcesContent":[".Root {\n  width: 100%;\n  display: flex;\n  flex-direction: column;\n}\n\n.TreeViewItemDraggable {\n  user-select: none;\n  cursor: pointer;\n  \n  & * {\n    pointer-events: none;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `TreeView-module__Root--VXBM9`,
	"TreeViewItemDraggable": `TreeView-module__TreeViewItemDraggable--V1X1a`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 1696:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ErrorBoundary-module__Root--PUW0Y{position:relative;width:100%;height:100%}.ErrorBoundary-module__Center--IIT9O{height:60%;display:flex;justify-content:center;align-items:center;flex-direction:column}.ErrorBoundary-module__Container--UuTfp{padding:8px 16px;width:100%;max-width:600px;box-sizing:border-box}.ErrorBoundary-module__Container--UuTfp pre{overflow-x:auto;padding:16px 0;margin:16px 0;background:var(--theme-color-bg-3);color:var(--theme-color-fg-default);border-radius:4px;user-select:text}.ErrorBoundary-module__Container--UuTfp pre .ErrorBoundary-module__Error--FsZSl{display:block;padding:0 16px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/common/ErrorBoundary/ErrorBoundary.module.scss"],"names":[],"mappings":"AAAA,mCACE,iBAAA,CACA,UAAA,CACA,WAAA,CAGF,qCACE,UAAA,CACA,YAAA,CACA,sBAAA,CACA,kBAAA,CACA,qBAAA,CAGF,wCACE,gBAAA,CACA,UAAA,CACA,eAAA,CACA,qBAAA,CAEA,4CACE,eAAA,CACA,cAAA,CACA,aAAA,CACA,kCAAA,CACA,mCAAA,CACA,iBAAA,CACA,gBAAA,CAEA,gFACE,aAAA,CACA,cAAA","sourcesContent":[".Root {\n  position: relative;\n  width: 100%;\n  height: 100%;\n}\n\n.Center {\n  height: 60%;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  flex-direction: column;\n}\n\n.Container {\n  padding: 8px 16px;\n  width: 100%;\n  max-width: 600px;\n  box-sizing: border-box;\n\n  pre {\n    overflow-x: auto;\n    padding: 16px 0;\n    margin: 16px 0;\n    background: var(--theme-color-bg-3);\n    color: var(--theme-color-fg-default);\n    border-radius: 4px;\n    user-select: text;\n\n    .Error {\n      display: block;\n      padding: 0 16px;\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ErrorBoundary-module__Root--PUW0Y`,
	"Center": `ErrorBoundary-module__Center--IIT9O`,
	"Container": `ErrorBoundary-module__Container--UuTfp`,
	"Error": `ErrorBoundary-module__Error--FsZSl`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 1740:
/***/ ((module) => {

"use strict";


/* istanbul ignore next  */
function apply(styleElement, options, obj) {
  var css = "";
  if (obj.supports) {
    css += "@supports (".concat(obj.supports, ") {");
  }
  if (obj.media) {
    css += "@media ".concat(obj.media, " {");
  }
  var needLayer = typeof obj.layer !== "undefined";
  if (needLayer) {
    css += "@layer".concat(obj.layer.length > 0 ? " ".concat(obj.layer) : "", " {");
  }
  css += obj.css;
  if (needLayer) {
    css += "}";
  }
  if (obj.media) {
    css += "}";
  }
  if (obj.supports) {
    css += "}";
  }
  var sourceMap = obj.sourceMap;
  if (sourceMap && typeof btoa !== "undefined") {
    css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */");
  }

  // For old IE
  /* istanbul ignore if  */
  options.styleTagTransform(css, styleElement, options.options);
}
function removeStyleElement(styleElement) {
  // istanbul ignore if
  if (styleElement.parentNode === null) {
    return false;
  }
  styleElement.parentNode.removeChild(styleElement);
}

/* istanbul ignore next  */
function domAPI(options) {
  if (typeof document === "undefined") {
    return {
      update: function update() {},
      remove: function remove() {}
    };
  }
  var styleElement = options.insertStyleElement(options);
  return {
    update: function update(obj) {
      apply(styleElement, options, obj);
    },
    remove: function remove() {
      removeStyleElement(styleElement);
    }
  };
}
module.exports = domAPI;

/***/ }),

/***/ 1943:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-inputbox {
	position: relative;
	display: block;
	padding: 0;
	box-sizing:	border-box;

	/* Customizable */
	font-size: inherit;
}

.monaco-inputbox.idle {
	border: 1px solid transparent;
}

.monaco-inputbox > .ibwrapper > .input,
.monaco-inputbox > .ibwrapper > .mirror {

	/* Customizable */
	padding: 4px;
}

.monaco-inputbox > .ibwrapper {
	position: relative;
	width: 100%;
	height: 100%;
}

.monaco-inputbox > .ibwrapper > .input {
	display: inline-block;
	box-sizing:	border-box;
	width: 100%;
	height: 100%;
	line-height: inherit;
	border: none;
	font-family: inherit;
	font-size: inherit;
	resize: none;
	color: inherit;
}

.monaco-inputbox > .ibwrapper > input {
	text-overflow: ellipsis;
}

.monaco-inputbox > .ibwrapper > textarea.input {
	display: block;
	-ms-overflow-style: none; /* IE 10+: hide scrollbars */
	scrollbar-width: none; /* Firefox: hide scrollbars */
	outline: none;
}

.monaco-inputbox > .ibwrapper > textarea.input::-webkit-scrollbar {
	display: none; /* Chrome + Safari: hide scrollbar */
}

.monaco-inputbox > .ibwrapper > textarea.input.empty {
	white-space: nowrap;
}

.monaco-inputbox > .ibwrapper > .mirror {
	position: absolute;
	display: inline-block;
	width: 100%;
	top: 0;
	left: 0;
	box-sizing: border-box;
	white-space: pre-wrap;
	visibility: hidden;
	word-wrap: break-word;
}

/* Context view */

.monaco-inputbox-container {
	text-align: right;
}

.monaco-inputbox-container .monaco-inputbox-message {
	display: inline-block;
	overflow: hidden;
	text-align: left;
	width: 100%;
	box-sizing:	border-box;
	padding: 0.4em;
	font-size: 12px;
	line-height: 17px;
	margin-top: -1px;
	word-wrap: break-word;
}

/* Action bar support */
.monaco-inputbox .monaco-action-bar {
	position: absolute;
	right: 2px;
	top: 4px;
}

.monaco-inputbox .monaco-action-bar .action-item {
	margin-left: 2px;
}

.monaco-inputbox .monaco-action-bar .action-item .codicon {
	background-repeat: no-repeat;
	width: 16px;
	height: 16px;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/inputbox/inputBox.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kBAAkB;CAClB,cAAc;CACd,UAAU;CACV,sBAAsB;;CAEtB,iBAAiB;CACjB,kBAAkB;AACnB;;AAEA;CACC,6BAA6B;AAC9B;;AAEA;;;CAGC,iBAAiB;CACjB,YAAY;AACb;;AAEA;CACC,kBAAkB;CAClB,WAAW;CACX,YAAY;AACb;;AAEA;CACC,qBAAqB;CACrB,sBAAsB;CACtB,WAAW;CACX,YAAY;CACZ,oBAAoB;CACpB,YAAY;CACZ,oBAAoB;CACpB,kBAAkB;CAClB,YAAY;CACZ,cAAc;AACf;;AAEA;CACC,uBAAuB;AACxB;;AAEA;CACC,cAAc;CACd,wBAAwB,EAAE,4BAA4B;CACtD,qBAAqB,EAAE,6BAA6B;CACpD,aAAa;AACd;;AAEA;CACC,aAAa,EAAE,oCAAoC;AACpD;;AAEA;CACC,mBAAmB;AACpB;;AAEA;CACC,kBAAkB;CAClB,qBAAqB;CACrB,WAAW;CACX,MAAM;CACN,OAAO;CACP,sBAAsB;CACtB,qBAAqB;CACrB,kBAAkB;CAClB,qBAAqB;AACtB;;AAEA,iBAAiB;;AAEjB;CACC,iBAAiB;AAClB;;AAEA;CACC,qBAAqB;CACrB,gBAAgB;CAChB,gBAAgB;CAChB,WAAW;CACX,sBAAsB;CACtB,cAAc;CACd,eAAe;CACf,iBAAiB;CACjB,gBAAgB;CAChB,qBAAqB;AACtB;;AAEA,uBAAuB;AACvB;CACC,kBAAkB;CAClB,UAAU;CACV,QAAQ;AACT;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,4BAA4B;CAC5B,WAAW;CACX,YAAY;AACb","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-inputbox {\n\tposition: relative;\n\tdisplay: block;\n\tpadding: 0;\n\tbox-sizing:\tborder-box;\n\n\t/* Customizable */\n\tfont-size: inherit;\n}\n\n.monaco-inputbox.idle {\n\tborder: 1px solid transparent;\n}\n\n.monaco-inputbox > .ibwrapper > .input,\n.monaco-inputbox > .ibwrapper > .mirror {\n\n\t/* Customizable */\n\tpadding: 4px;\n}\n\n.monaco-inputbox > .ibwrapper {\n\tposition: relative;\n\twidth: 100%;\n\theight: 100%;\n}\n\n.monaco-inputbox > .ibwrapper > .input {\n\tdisplay: inline-block;\n\tbox-sizing:\tborder-box;\n\twidth: 100%;\n\theight: 100%;\n\tline-height: inherit;\n\tborder: none;\n\tfont-family: inherit;\n\tfont-size: inherit;\n\tresize: none;\n\tcolor: inherit;\n}\n\n.monaco-inputbox > .ibwrapper > input {\n\ttext-overflow: ellipsis;\n}\n\n.monaco-inputbox > .ibwrapper > textarea.input {\n\tdisplay: block;\n\t-ms-overflow-style: none; /* IE 10+: hide scrollbars */\n\tscrollbar-width: none; /* Firefox: hide scrollbars */\n\toutline: none;\n}\n\n.monaco-inputbox > .ibwrapper > textarea.input::-webkit-scrollbar {\n\tdisplay: none; /* Chrome + Safari: hide scrollbar */\n}\n\n.monaco-inputbox > .ibwrapper > textarea.input.empty {\n\twhite-space: nowrap;\n}\n\n.monaco-inputbox > .ibwrapper > .mirror {\n\tposition: absolute;\n\tdisplay: inline-block;\n\twidth: 100%;\n\ttop: 0;\n\tleft: 0;\n\tbox-sizing: border-box;\n\twhite-space: pre-wrap;\n\tvisibility: hidden;\n\tword-wrap: break-word;\n}\n\n/* Context view */\n\n.monaco-inputbox-container {\n\ttext-align: right;\n}\n\n.monaco-inputbox-container .monaco-inputbox-message {\n\tdisplay: inline-block;\n\toverflow: hidden;\n\ttext-align: left;\n\twidth: 100%;\n\tbox-sizing:\tborder-box;\n\tpadding: 0.4em;\n\tfont-size: 12px;\n\tline-height: 17px;\n\tmargin-top: -1px;\n\tword-wrap: break-word;\n}\n\n/* Action bar support */\n.monaco-inputbox .monaco-action-bar {\n\tposition: absolute;\n\tright: 2px;\n\ttop: 4px;\n}\n\n.monaco-inputbox .monaco-action-bar .action-item {\n\tmargin-left: 2px;\n}\n\n.monaco-inputbox .monaco-action-bar .action-item .codicon {\n\tbackground-repeat: no-repeat;\n\twidth: 16px;\n\theight: 16px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 1950:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgVideo = function SvgVideo(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M10.3037 25.8395C10.3037 25.2872 10.7514 24.8395 11.3037 24.8395H18.8037C19.356 24.8395 19.8037 25.2872 19.8037 25.8395C19.8037 26.3918 19.356 26.8395 18.8037 26.8395H11.3037C10.7514 26.8395 10.3037 26.3918 10.3037 25.8395Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M24.8454 21.7025H5.26204C4.18049 21.7025 3.30371 20.8257 3.30371 19.7442V6.03585C3.30371 4.95429 4.18049 4.07751 5.26204 4.07751H24.8454C25.9269 4.07751 26.8037 4.95429 26.8037 6.03585V19.7442C26.8037 20.8257 25.9269 21.7025 24.8454 21.7025ZM18.6841 13.4171C19.0468 13.1828 19.0468 12.5972 18.6841 12.3629L13.2641 8.86159C12.9015 8.62732 12.4482 8.92016 12.4482 9.3887V16.3913C12.4482 16.8598 12.9015 17.1527 13.2641 16.9184L18.6841 13.4171Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgVideo);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "e934bdec5ec9cba3d4949d4961b3f2d8.svg");

/***/ }),

/***/ 2258:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgFileFilled = function SvgFileFilled(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 25,
    viewBox: "0 0 24 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M14 2.80719L5.7 2.80721V3.55721L5.7 2.80721C5.29808 2.80722 4.92403 2.97875 4.65673 3.26515C4.39107 3.54979 4.25 3.92545 4.25 4.30721V20.8072C4.25 21.189 4.39107 21.5646 4.65673 21.8493C4.92404 22.1357 5.29809 22.3072 5.7 22.3072H18.3C18.7019 22.3072 19.076 22.1357 19.3433 21.8493C19.6089 21.5646 19.75 21.189 19.75 20.8072V8.55721C19.75 8.3583 19.671 8.16754 19.5303 8.02689L14.5303 3.02686C14.3897 2.88621 14.1989 2.80719 14 2.80719ZM8.32324 11.5701C8.32324 11.1007 8.7038 10.7201 9.17324 10.7201H14.8271C15.2965 10.7201 15.6771 11.1007 15.6771 11.5701C15.6771 12.0395 15.2965 12.4201 14.8271 12.4201H9.17324C8.7038 12.4201 8.32324 12.0395 8.32324 11.5701ZM8.32324 15.5701C8.32324 15.1007 8.7038 14.7201 9.17324 14.7201H14.8271C15.2965 14.7201 15.6771 15.1007 15.6771 15.5701C15.6771 16.0395 15.2965 16.4201 14.8271 16.4201H9.17324C8.7038 16.4201 8.32324 16.0395 8.32324 15.5701Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgFileFilled);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "6f923ecd985dfa730d4fc609d6d3b10c.svg");

/***/ }),

/***/ 2506:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDevicePhone = function SvgDevicePhone(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M16.3574 4.97807C16.3574 4.68717 16.1216 4.45135 15.8307 4.45135L8.17042 4.45135C7.87952 4.45135 7.64371 4.68717 7.64371 4.97807L7.64371 19.0219C7.64371 19.3128 7.87952 19.5486 8.17042 19.5486H15.8307C16.1216 19.5486 16.3574 19.3128 16.3574 19.0219V4.97807ZM15.8307 2.95135C16.95 2.95135 17.8574 3.85875 17.8574 4.97807V19.0219C17.8574 20.1413 16.95 21.0486 15.8307 21.0486H8.17042C7.0511 21.0486 6.14371 20.1413 6.14371 19.0219L6.14371 4.97807C6.14371 3.85875 7.0511 2.95135 8.17042 2.95135L15.8307 2.95135Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M9.69727 6.78748C9.69727 6.37326 10.0331 6.03748 10.4473 6.03748H13.5526C13.9668 6.03748 14.3026 6.37326 14.3026 6.78748C14.3026 7.20169 13.9668 7.53748 13.5526 7.53748H10.4473C10.0331 7.53748 9.69727 7.20169 9.69727 6.78748Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDevicePhone);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "51c417e0555a074f1915d320b9b71413.svg");

/***/ }),

/***/ 2680:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.DialogLayerContainer-module__Root--Efeqw{position:absolute;z-index:666;inset:0}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/DialogLayer/DialogLayerContainer.module.scss"],"names":[],"mappings":"AAAA,0CACE,iBAAA,CACA,WAAA,CACA,OAAA","sourcesContent":[".Root {\n  position: absolute;\n  z-index: 666;\n  inset: 0;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `DialogLayerContainer-module__Root--Efeqw`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 2730:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRestApi = function SvgRestApi(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.49204 3.54434C6.0493 3.24636 6.73631 3.10577 7.55784 3.10577C7.97205 3.10577 8.30784 3.44156 8.30784 3.85577C8.30784 4.26999 7.97205 4.60577 7.55784 4.60577C6.89859 4.60577 6.47503 4.71969 6.19936 4.8671C5.9363 5.00777 5.76448 5.20157 5.64135 5.45551C5.36201 6.03166 5.3463 6.85399 5.3463 7.92789L5.34633 8.02C5.34682 8.96663 5.34742 10.1339 4.90097 11.0547C4.72843 11.4105 4.48938 11.7337 4.16677 12C4.48938 12.2663 4.72843 12.5895 4.90097 12.9453C5.34742 13.8661 5.34682 15.0334 5.34633 15.98L5.3463 16.0721C5.3463 17.146 5.36201 17.9683 5.64135 18.5445C5.76448 18.7984 5.9363 18.9922 6.19936 19.1329C6.47503 19.2803 6.89859 19.3942 7.55784 19.3942C7.97205 19.3942 8.30784 19.73 8.30784 20.1442C8.30784 20.5584 7.97205 20.8942 7.55784 20.8942C6.73631 20.8942 6.0493 20.7536 5.49204 20.4557C4.92217 20.1509 4.5387 19.7085 4.29163 19.1989C3.84519 18.2781 3.84578 17.1109 3.84627 16.1642L3.8463 16.0721C3.8463 14.9982 3.83059 14.1759 3.55125 13.5997C3.42813 13.3458 3.2563 13.152 2.99325 13.0113C2.71757 12.8639 2.29401 12.75 1.63477 12.75C1.22055 12.75 0.884766 12.4142 0.884766 12C0.884766 11.5858 1.22055 11.25 1.63477 11.25C2.29401 11.25 2.71757 11.1361 2.99325 10.9887C3.2563 10.848 3.42813 10.6542 3.55125 10.4003C3.83059 9.82411 3.8463 9.00178 3.8463 7.92789L3.84627 7.83578C3.84578 6.88915 3.84519 5.7219 4.29163 4.8011C4.5387 4.29152 4.92217 3.84906 5.49204 3.54434ZM15.6924 3.85577C15.6924 3.44156 16.0282 3.10577 16.4424 3.10577C17.2639 3.10577 17.9509 3.24636 18.5082 3.54434C19.0781 3.84906 19.4615 4.29152 19.7086 4.8011C20.155 5.7219 20.1544 6.88915 20.1539 7.83578L20.1539 7.92789C20.1539 9.00178 20.1696 9.82411 20.449 10.4003C20.5721 10.6542 20.7439 10.848 21.007 10.9887C21.2827 11.1361 21.7062 11.25 22.3655 11.25C22.7797 11.25 23.1155 11.5858 23.1155 12C23.1155 12.4142 22.7797 12.75 22.3655 12.75C21.7062 12.75 21.2827 12.8639 21.007 13.0113C20.7439 13.152 20.5721 13.3458 20.449 13.5997C20.1696 14.1759 20.1539 14.9982 20.1539 16.0721L20.1539 16.1642C20.1544 17.1109 20.155 18.2781 19.7086 19.1989C19.4615 19.7085 19.0781 20.1509 18.5082 20.4557C17.9509 20.7536 17.2639 20.8942 16.4424 20.8942C16.0282 20.8942 15.6924 20.5584 15.6924 20.1442C15.6924 19.73 16.0282 19.3942 16.4424 19.3942C17.1016 19.3942 17.5252 19.2803 17.8009 19.1329C18.0639 18.9922 18.2357 18.7984 18.3589 18.5445C18.6382 17.9683 18.6539 17.146 18.6539 16.0721L18.6539 15.98C18.6534 15.0334 18.6528 13.8661 19.0993 12.9453C19.2718 12.5895 19.5108 12.2663 19.8334 12C19.5108 11.7337 19.2718 11.4105 19.0993 11.0547C18.6528 10.1339 18.6534 8.96663 18.6539 8.02L18.6539 7.92789C18.6539 6.85399 18.6382 6.03166 18.3589 5.45551C18.2357 5.20157 18.0639 5.00777 17.8009 4.8671C17.5252 4.71969 17.1016 4.60577 16.4424 4.60577C16.0282 4.60577 15.6924 4.26999 15.6924 3.85577ZM12.9001 12C12.9001 12.4971 12.4972 12.9 12.0001 12.9C11.503 12.9 11.1001 12.4971 11.1001 12C11.1001 11.5029 11.503 11.1 12.0001 11.1C12.4972 11.1 12.9001 11.5029 12.9001 12ZM7.92783 12.9C8.42489 12.9 8.82783 12.4971 8.82783 12C8.82783 11.5029 8.42489 11.1 7.92783 11.1C7.43078 11.1 7.02783 11.5029 7.02783 12C7.02783 12.4971 7.43078 12.9 7.92783 12.9ZM16.9724 12C16.9724 12.4971 16.5694 12.9 16.0724 12.9C15.5753 12.9 15.1724 12.4971 15.1724 12C15.1724 11.5029 15.5753 11.1 16.0724 11.1C16.5694 11.1 16.9724 11.5029 16.9724 12Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRestApi);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "613f05a18538ddea4f6c9e04cd125275.svg");

/***/ }),

/***/ 2904:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .blockDecorations-container {
	position: absolute;
	top: 0;
}

.monaco-editor .blockDecorations-block {
	position: absolute;
	box-sizing: border-box;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/blockDecorations/blockDecorations.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kBAAkB;CAClB,MAAM;AACP;;AAEA;CACC,kBAAkB;CAClB,sBAAsB;AACvB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .blockDecorations-container {\n\tposition: absolute;\n\ttop: 0;\n}\n\n.monaco-editor .blockDecorations-block {\n\tposition: absolute;\n\tbox-sizing: border-box;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 2911:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgClose = function SvgClose(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M17.6245 7.57283C17.9174 7.27994 17.9174 6.80507 17.6245 6.51217C17.3316 6.21928 16.8567 6.21928 16.5638 6.51217L12.1367 10.9393L7.70953 6.51217C7.41664 6.21928 6.94176 6.21928 6.64887 6.51217C6.35598 6.80507 6.35598 7.27994 6.64887 7.57283L11.076 12L6.64887 16.4272C6.35598 16.72 6.35598 17.1949 6.64887 17.4878C6.94176 17.7807 7.41664 17.7807 7.70953 17.4878L12.1367 13.0607L16.5638 17.4878C16.8567 17.7807 17.3316 17.7807 17.6245 17.4878C17.9174 17.1949 17.9174 16.72 17.6245 16.4272L13.1973 12L17.6245 7.57283Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgClose);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "cd82254f82cc3db2d211e83cea280cb3.svg");

/***/ }),

/***/ 3191:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const React = __webpack_require__(54953);
const Styles = {
  curveIcon: {
    backgroundColor: '#222',
    width: '40px',
    height: '40px',
    display: 'flex',
    justifyContent: 'center',
    padding: '2px'
  },
  curveIconImage: {
    opacity: 0.7,
    ':hover': {
      opacity: 1
    }
  },
  animationPlup: {
    height: '21px',
    width: '21px',
    borderRadius: '15px',
    backgroundColor: '#999',
    position: 'relative',
    top: '2px',
    left: '2px'
  }
};
class CurveEditor extends React.Component {
  _curtop = 0;
  constructor(props) {
    super(props);
    this.value = props.value || props.default;
    this.default = props.default;
    this.state = {
      duration: this.value.dur,
      isDurationDefault: this.value === undefined,
      delay: this.value.delay,
      isDelayDefault: this.value === undefined,
      cssBezierValues: this.value.curve
    };
    this.onUpdate = props.onUpdate;
  }
  getDevicePixelRatio(ctx) {
    var dpr = window.devicePixelRatio || 1;
    var bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
    var r = dpr / bsr;
    return r;
  }
  componentDidMount() {
    const canvas = this.refs.canvas;
    const ctx = canvas.getContext('2d');
    canvas.ratio = this.getDevicePixelRatio(ctx);
    //console.log(this.canvas.ratio);

    var oldWidth = canvas.width;
    var oldHeight = canvas.height;
    canvas.width = oldWidth * canvas.ratio;
    canvas.height = oldHeight * canvas.ratio;
    canvas.width = canvas.width;
    canvas.height = canvas.height;
    canvas.style.width = oldWidth + 'px';
    canvas.style.height = oldHeight + 'px';
    this.canvas = canvas;
    this.endPoints = [{
      x: 20,
      y: 180
    }, {
      x: 180,
      y: 20
    }];
    this.controlPoints = [{
      x: 0,
      y: 0
    }, {
      x: 0,
      y: 0
    }];
    this.presetTo(this.value.curve);
    this.setState({
      cssBezierValues: this.value.curve
    });
    this.paint();
    this._mouseMoveListener = this.onMouseMove.bind(this);
    document.addEventListener('mousemove', this._mouseMoveListener);
    this._mouseUpListener = this.onMouseUp.bind(this);
    document.addEventListener('mouseup', this._mouseUpListener);
  }
  canvasTopLeft() {
    var obj = this.canvas;
    var curleft = this._curtop = 0;
    if (obj.offsetParent) {
      do {
        curleft += obj.offsetLeft;
        this._curtop += obj.offsetTop;
      } while (obj = obj.offsetParent);
    }
    return [curleft, this._curtop];
  }
  isCloseTo(x, y, pnt) {
    return x >= pnt.x - 10 && x <= pnt.x + 10 && y >= pnt.y - 10 && y <= pnt.y + 10;
  }
  componentWillReceiveProps(props) {
    this.value = props.value || props.default;
    this.default = props.default;
    this.setState({
      duration: this.value.dur,
      isDurationDefault: this.value === undefined,
      delay: this.value.delay,
      isDelayDefault: this.value === undefined,
      cssBezierValues: this.value.curve
    });
    this.onUpdate = props.onUpdate;
    this.presetTo(this.value.curve);
    this.paint();
  }
  onMouseMove(evt) {
    if (this.trackMove) {
      var tl = this.canvasTopLeft();
      var x = evt.pageX - tl[0];
      var y = evt.pageY - tl[1];
      this.trackMove.x = x;
      this.trackMove.y = y;
      this.paint();
      this.setState({
        cssBezierValues: this.getCssBezierValues()
      });
      this.updateValues(true);
    }

    //    console.log(evt);
  }
  onMouseDown(evt) {
    var tl = this.canvasTopLeft();
    var x = evt.pageX - tl[0];
    var y = evt.pageY - tl[1];
    this.trackMove = undefined;
    if (this.isCloseTo(x, y, this.controlPoints[0]) || this.isCloseTo(x, y, this.endPoints[0])) {
      this.trackMove = this.controlPoints[0];
    }
    if (this.isCloseTo(x, y, this.controlPoints[1]) || this.isCloseTo(x, y, this.endPoints[1])) {
      this.trackMove = this.controlPoints[1];
    }

    //   console.log('down',evt)
  }
  onMouseUp(evt) {
    if (this.trackMove) {
      this.updateValues();
      this.testTiming();
    }
    this.trackMove = false;
  }
  componentWillUnmount() {
    document.removeEventListener('mousemove', this._mouseMoveListener);
    document.removeEventListener('mouseup', this._mouseUpListener);
  }
  presetTo(p) {
    const presets = {
      linear: [0.0, 0.0, 1.0, 1.0],
      'ease-in': [0.42, 0.0, 1.0, 1.0],
      'ease-out': [0.0, 0.0, 0.58, 1.0],
      'ease-in-out': [0.42, 0.0, 0.58, 1.0]
    };
    if (typeof p === 'string') p = presets[p];
    var size = 160;
    this.controlPoints[0].x = p[0] * size + this.endPoints[0].x;
    this.controlPoints[0].y = -(p[1] * size) + this.endPoints[0].y;
    this.controlPoints[1].x = p[2] * size + this.endPoints[0].x;
    this.controlPoints[1].y = -(p[3] * size) + this.endPoints[0].y;
    this.setState({
      cssBezierValues: p
    });
    this.paint();
  }
  updateValues(drag) {
    var curve = this.getCssBezierValues();
    var dur = parseFloat(this.state.duration);
    var delay = parseFloat(this.state.delay);
    this.onUpdate && this.onUpdate({
      curve: curve,
      dur: isNaN(dur) ? this.default.dur : dur,
      delay: isNaN(delay) ? this.default.delay : delay
    }, drag);
  }
  getCssBezierValues() {
    var size = 160;
    function round(num) {
      return Math.round((num + Number.EPSILON) * 100) / 100;
    }
    return [round((this.controlPoints[0].x - this.endPoints[0].x) / size), round(-(this.controlPoints[0].y - this.endPoints[0].y) / size), round((this.controlPoints[1].x - this.endPoints[0].x) / size), round(-(this.controlPoints[1].y - this.endPoints[0].y) / size)];
  }
  onDurationChange(evt) {
    const v = evt.target.value;
    this.setState({
      duration: v,
      isDurationDefault: false
    });
  }
  onDurationBlur(evt) {
    const v = evt.target.value;
    this.setState({
      duration: v == undefined || v === '' ? this.default.dur : v,
      isDurationDefault: v == undefined || v === ''
    });
    this.updateValues();
    this.testTiming();
  }
  onDelayChange(evt) {
    const v = evt.target.value;
    this.setState({
      delay: v,
      isDelayDefault: false
    });
  }
  onDelayBlur(evt) {
    const v = evt.target.value;
    this.setState({
      delay: v == undefined || v === '' ? this.default.delay : v,
      isDelayDefault: v == undefined || v === ''
    });
    this.updateValues();
    this.testTiming();
  }
  testTiming() {
    this.refs.animationPlup.style.transition = 'none';
    this.refs.animationPlup.style.transform = 'translate(30px)';
    void this.refs.animationPlup.offsetWidth;
    this.refs.animationPlup.style.transition = 'transform';
    this.refs.animationPlup.style.transitionDuration = this.state.duration + 'ms';
    this.refs.animationPlup.style.transitionDelay = this.state.delay + 'ms';
    this.refs.animationPlup.style.transitionTimingFunction = 'cubic-bezier(' + this.getCssBezierValues().join(',') + ')';
    void this.refs.animationPlup.offsetWidth;
    this.refs.animationPlup.style.transform = 'translate(180px)';
  }
  paint() {
    const canvas = this.refs.canvas;
    const ctx = canvas.getContext('2d');
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.scale(canvas.ratio, canvas.ratio);
    const w = 200,
      h = 200;
    const m = 20;
    var cps = this.controlPoints;

    // Background
    ctx.fillStyle = '#222222';
    ctx.fillRect(0, 0, w, h);

    // Control lines
    ctx.strokeStyle = '#444444';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.moveTo(m, h - m);
    ctx.lineTo(cps[0].x, cps[0].y);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(w - m, m);
    ctx.lineTo(cps[1].x, cps[1].y);
    ctx.stroke();

    // Curve
    ctx.strokeStyle = '#555555';
    ctx.lineWidth = 3;
    ctx.beginPath();
    ctx.moveTo(m, h - m);
    ctx.bezierCurveTo(cps[0].x, cps[0].y, cps[1].x, cps[1].y, w - m, m);
    ctx.stroke();

    // End points
    ctx.fillStyle = '#777777';
    ctx.beginPath();
    ctx.arc(m, h - m, 7, 0, 2 * Math.PI);
    ctx.fill();
    ctx.beginPath();
    ctx.arc(w - m, m, 7, 0, 2 * Math.PI);
    ctx.fill();

    // Control points
    ctx.fillStyle = '#dddddd';
    ctx.beginPath();
    ctx.arc(cps[0].x, cps[0].y, 7, 0, 2 * Math.PI);
    ctx.fill();
    ctx.beginPath();
    ctx.arc(cps[1].x, cps[1].y, 7, 0, 2 * Math.PI);
    ctx.fill();
  }
  onCurveInputChanged(index, evt) {
    const v = evt.target.value;
    this.state.cssBezierValues[index] = v;
    this.setState({
      cssBezierValues: this.state.cssBezierValues
    });
  }
  onCurveInputBlur(index, evt) {
    this.presetTo(this.state.cssBezierValues);
    this.testTiming();
    this.updateValues();
  }
  renderCurveInputs() {
    return this.state.cssBezierValues.map((c, index) => {
      return /*#__PURE__*/React.createElement("div", {
        style: {
          width: '59px',
          height: '35px',
          position: 'relative',
          marginRight: '5px'
        }
      }, /*#__PURE__*/React.createElement("input", {
        type: "string",
        style: {
          position: 'absolute',
          width: '100%',
          height: '100%',
          textAlign: 'right',
          paddingRight: '10px'
        },
        className: 'sidebar-panel-dark-input' + (this.state.isDurationDefault ? ' property-input-default' : ''),
        value: c,
        onChange: this.onCurveInputChanged.bind(this, index),
        onBlur: this.onCurveInputBlur.bind(this, index),
        onKeyDown: e => e.keyCode === 13 && e.target.blur()
      }));
    });
  }
  render() {
    return /*#__PURE__*/React.createElement("div", {
      style: {
        width: '270px',
        height: '370px'
      }
    }, /*#__PURE__*/React.createElement("canvas", {
      style: {
        position: 'relative',
        marginLeft: '10px',
        marginTop: '10px'
      },
      ref: "canvas",
      width: "200",
      height: "200",
      onMouseDown: this.onMouseDown.bind(this)
    }), /*#__PURE__*/React.createElement("div", {
      style: {
        position: 'absolute',
        top: '10px',
        right: '10px',
        ...Styles.curveIcon
      },
      onClick: () => {
        this.presetTo('ease-in');
        this.updateValues();
      }
    }, /*#__PURE__*/React.createElement("img", {
      key: "ease-in-icon",
      src: "../assets/icons/curve-ease-in.svg",
      style: Styles.curveIconImage
    })), /*#__PURE__*/React.createElement("div", {
      style: {
        position: 'absolute',
        top: '62px',
        right: '10px',
        ...Styles.curveIcon
      },
      onClick: () => {
        this.presetTo('ease-out');
        this.updateValues();
      }
    }, /*#__PURE__*/React.createElement("img", {
      key: "ease-out-icon",
      src: "../assets/icons/curve-ease-out.svg",
      style: Styles.curveIconImage
    })), /*#__PURE__*/React.createElement("div", {
      style: {
        position: 'absolute',
        top: '113px',
        right: '10px',
        ...Styles.curveIcon
      },
      onClick: () => {
        this.presetTo('ease-in-out');
        this.updateValues();
      }
    }, /*#__PURE__*/React.createElement("img", {
      key: "ease-in-out-icon",
      src: "../assets/icons/curve-ease-in-out.svg",
      style: Styles.curveIconImage
    })), /*#__PURE__*/React.createElement("div", {
      style: {
        position: 'absolute',
        top: '165px',
        right: '10px',
        ...Styles.curveIcon
      },
      onClick: () => {
        this.presetTo('linear');
        this.updateValues();
      }
    }, /*#__PURE__*/React.createElement("img", {
      key: "ease-linear-icon",
      src: "../assets/icons/curve-linear.svg",
      style: Styles.curveIconImage
    })), /*#__PURE__*/React.createElement("div", {
      style: {
        position: 'relative',
        height: '35px',
        display: 'flex',
        marginLeft: '10px',
        marginBottom: '5px'
      }
    }, this.renderCurveInputs()), /*#__PURE__*/React.createElement("div", {
      style: {
        height: '35px',
        position: 'relative'
      }
    }, /*#__PURE__*/React.createElement("label", {
      className: "property-label"
    }, "Duration (ms)"), /*#__PURE__*/React.createElement("div", {
      className: "property-value"
    }, /*#__PURE__*/React.createElement("input", {
      type: "string",
      className: 'sidebar-panel-dark-input' + (this.state.isDurationDefault ? ' property-input-default' : ''),
      style: {
        position: 'absolute',
        width: '100%',
        height: '100%'
      },
      value: this.state.duration,
      onChange: this.onDurationChange.bind(this),
      onBlur: this.onDurationBlur.bind(this),
      onKeyDown: e => e.keyCode === 13 && e.target.blur()
    }))), /*#__PURE__*/React.createElement("div", {
      style: {
        height: '35px',
        position: 'relative'
      }
    }, /*#__PURE__*/React.createElement("label", {
      className: "property-label"
    }, "Delay (ms)"), /*#__PURE__*/React.createElement("div", {
      className: "property-value"
    }, /*#__PURE__*/React.createElement("input", {
      type: "string",
      className: 'sidebar-panel-dark-input' + (this.state.isDelayDefault ? ' property-input-default' : ''),
      style: {
        position: 'absolute',
        width: '100%',
        height: '100%'
      },
      value: this.state.delay,
      onChange: this.onDelayChange.bind(this),
      onBlur: this.onDelayBlur.bind(this),
      onKeyDown: e => e.keyCode === 13 && e.target.blur()
    }))), /*#__PURE__*/React.createElement("div", {
      style: {
        height: '25px',
        position: 'relative',
        backgroundColor: '#222',
        marginTop: '5px',
        marginLeft: '10px',
        marginRight: '10px',
        borderRadius: '15px'
      },
      onClick: this.testTiming.bind(this)
    }, /*#__PURE__*/React.createElement("div", {
      ref: "animationPlup",
      style: {
        ...Styles.animationPlup,
        transform: 'translate(30px)'
      }
    })));
  }
}
module.exports = CurveEditor;

/***/ }),

/***/ 3348:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.NotificationFeedbackDisplay-module__Root--FRfrO{position:absolute;top:0;left:0;right:0;bottom:0;border:1px solid;pointer-events:none}.NotificationFeedbackDisplay-module__Root--FRfrO.NotificationFeedbackDisplay-module__is-type-success--Fk69e{border-color:var(--theme-color-success)}.NotificationFeedbackDisplay-module__Root--FRfrO.NotificationFeedbackDisplay-module__is-type-danger--GeEfL{border-color:var(--theme-color-danger)}.NotificationFeedbackDisplay-module__Root--FRfrO.NotificationFeedbackDisplay-module__is-type-notice--MyiyC{border-color:var(--theme-color-notice)}.NotificationFeedbackDisplay-module__Root--FRfrO.NotificationFeedbackDisplay-module__is-display-mode-fade-quick--Hw4Ei{opacity:1;animation:NotificationFeedbackDisplay-module__fade--VawTk 2000ms 200ms forwards}.NotificationFeedbackDisplay-module__Root--FRfrO.NotificationFeedbackDisplay-module__is-display-mode-fade-slow--aHXpD{opacity:1;animation:NotificationFeedbackDisplay-module__fade--VawTk 2000ms 3000ms forwards}@keyframes NotificationFeedbackDisplay-module__fade--VawTk{0%{opacity:1}100%{opacity:0}}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/NotificationFeedbackDisplay/NotificationFeedbackDisplay.module.scss"],"names":[],"mappings":"AAAA,iDACE,iBAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,gBAAA,CACA,mBAAA,CAGE,4GACE,uCAAA,CAGF,2GACE,sCAAA,CAGF,2GACE,sCAAA,CAKF,uHACE,SAAA,CACA,+EAAA,CAGF,sHACE,SAAA,CACA,gFAAA,CAKN,2DACE,GACE,SAAA,CAEF,KACE,SAAA,CAAA","sourcesContent":[".Root {\r\n  position: absolute;\r\n  top: 0;\r\n  left: 0;\r\n  right: 0;\r\n  bottom: 0;\r\n  border: 1px solid;\r\n  pointer-events: none;\r\n\r\n  &.is-type {\r\n    &-success {\r\n      border-color: var(--theme-color-success);\r\n    }\r\n\r\n    &-danger {\r\n      border-color: var(--theme-color-danger);\r\n    }\r\n\r\n    &-notice {\r\n      border-color: var(--theme-color-notice);\r\n    }\r\n  }\r\n\r\n  &.is-display-mode {\r\n    &-fade-quick {\r\n      opacity: 1;\r\n      animation: fade 2000ms 200ms forwards;\r\n    }\r\n\r\n    &-fade-slow {\r\n      opacity: 1;\r\n      animation: fade 2000ms 3000ms forwards;\r\n    }\r\n  }\r\n}\r\n\r\n@keyframes fade {\r\n  0% {\r\n    opacity: 1;\r\n  }\r\n  100% {\r\n    opacity: 0;\r\n  }\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `NotificationFeedbackDisplay-module__Root--FRfrO`,
	"is-type-success": `NotificationFeedbackDisplay-module__is-type-success--Fk69e`,
	"is-type-danger": `NotificationFeedbackDisplay-module__is-type-danger--GeEfL`,
	"is-type-notice": `NotificationFeedbackDisplay-module__is-type-notice--MyiyC`,
	"is-display-mode-fade-quick": `NotificationFeedbackDisplay-module__is-display-mode-fade-quick--Hw4Ei`,
	"fade": `NotificationFeedbackDisplay-module__fade--VawTk`,
	"is-display-mode-fade-slow": `NotificationFeedbackDisplay-module__is-display-mode-fade-slow--aHXpD`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 3386:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCards = function SvgCards(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M2.25 7.75C2.25 6.92157 2.92157 6.25 3.75 6.25H17.25C18.0784 6.25 18.75 6.92157 18.75 7.75V18.25C18.75 19.0784 18.0784 19.75 17.25 19.75H3.75C2.92157 19.75 2.25 19.0784 2.25 18.25V7.75ZM17.25 7.75H3.75V18.25H17.25V7.75Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.25 4C5.25 3.58579 5.58579 3.25 6 3.25H20.25C20.6478 3.25 21.0294 3.40804 21.3107 3.68934C21.592 3.97065 21.75 4.35218 21.75 4.75V16C21.75 16.4142 21.4142 16.75 21 16.75C20.5858 16.75 20.25 16.4142 20.25 16L20.25 4.75L6 4.75C5.58579 4.75 5.25 4.41421 5.25 4Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCards);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "1e1bb6d5619d230af4f4ec41e8df30f1.svg");

/***/ }),

/***/ 3567:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  g: () => (/* binding */ getIndexedPages),
  w: () => (/* binding */ getPageRoutes)
});

// EXTERNAL MODULE: ./src/editor/src/utils/node-graph-traverser.ts
var node_graph_traverser = __webpack_require__(6056);
// EXTERNAL MODULE: ./src/editor/src/utils/compilation/build-context.ts
var build_context = __webpack_require__(34120);
;// ./src/editor/src/utils/compilation/context/pages-helper.ts
/**
 * Returns the Page Title from the Page node.
 *
 * @param node The Page node.
 * @returns The Page title.
 */
function getPageTitle(node) {
    if (node.parameters.urlPath) {
        return String(node.parameters.urlPath);
    }
    // @ts-ignore node.owner...
    const titleParts = node.owner.owner.name.split('/');
    return titleParts[titleParts.length - 1];
}
/**
 * Returns the Page URL from the Page node.
 *
 * @param node The Page node.
 * @returns The Page URL.
 */
function getPageUrl(node) {
    if (node.parameters.urlPath) {
        return String(node.parameters.urlPath);
    }
    // @ts-ignore node.owner...
    const titleParts = node.owner.owner.name.split('/');
    const title = node.parameters['title'] || titleParts[titleParts.length - 1];
    return title.replace(/\s+/g, '-').toLowerCase();
}
/**
 * Returns a all the variables from the URL path.
 *
 * @param path The page path.
 * @returns The variables.
 */
function getPathVariables(path) {
    const match = path.match(/\{([^}]+)\}/g);
    if (match) {
        return match.map((m) => ({ query: m, name: m.replace('{', '').replace('}', '') }));
    }
    return [];
}

;// ./src/editor/src/utils/compilation/context/pages.ts



class RouteNode {
    constructor(args) {
        this.title = args.title;
        this.componentName = args.componentName;
        this.routerName = args.routerName;
        this.current = args.current;
        this.previous = args.previous;
    }
    _getExpanded(dynamicHash) {
        const previousUrl = this.previous.map((x) => x.path).join('/');
        // Create a pretty url with absolute path
        function createUrl(subpath) {
            const fullPath = subpath.startsWith('/') ? previousUrl + subpath : previousUrl + '/' + subpath;
            return fullPath.startsWith('/') ? fullPath : '/' + fullPath;
        }
        const map = (routes) => {
            return routes.map((route) => {
                var _a;
                return ({
                    kind: route.kind,
                    componentName: this.componentName,
                    title: route.title || this.title,
                    path: createUrl(route.path || ((_a = route.current) === null || _a === void 0 ? void 0 : _a.path)),
                    meta: route.meta || {}
                });
            });
        };
        if (this.current.variables) {
            const dynamicRoutes = dynamicHash[this.current.id];
            if (Array.isArray(dynamicRoutes) && dynamicRoutes.length > 0) {
                return map(dynamicRoutes);
            }
        }
        return map([
            {
                kind: build_context/* PageType */.g.Static,
                componentName: this.componentName,
                title: this.title,
                path: this.current.path,
                meta: {}
            }
        ]);
    }
}
function getRoutePages(x) {
    var _a, _b;
    const typename = x.node.typename;
    const urlPath = typename === 'Page' ? getPageUrl(x.node) : x.node.parameters.urlPath;
    // Router can have no path, this will be ignored later.
    if (!urlPath) {
        return null;
    }
    // Get all the variables from the URL path
    const variables = getPathVariables(urlPath);
    // Read all the path variables from the page inputs node
    // NOTE: The tag might not always be there.
    // @ts-expect-error TODO: Solve tag type
    const pathParams = (_b = (_a = x.tag) === null || _a === void 0 ? void 0 : _a.pageInputs) === null || _b === void 0 ? void 0 : _b.parameters.pathParams;
    if (pathParams) {
        const pathParamsArray = pathParams.split(',');
        pathParamsArray.forEach((x) => {
            // Remove all the variables that are already added
            if (variables.findIndex((b) => b.name == x) !== -1) {
                return;
            }
            variables.push({
                query: `{${x}}`,
                name: x
            });
        });
    }
    const componentName = x.node.owner.owner.fullName; // node -> graph -> component
    return {
        id: x.node.id,
        componentName,
        path: urlPath,
        variables
    };
}
async function getIndexedPages(project, options) {
    const { pages } = await getPageRoutes(project, options);
    return pages;
}
async function getPageRoutes(project, options) {
    // Traverse the node grah looking for all the "Router" and "Page" nodes.
    const traverser = new node_graph_traverser/* NodeGraphTraverser */.r(project, (node) => node.typename === 'Router' || node.typename === 'Page', {
        // Select the "Page Inputs" node which is used with a page.
        tagSelector: (node) => {
            if (node.typename === 'Page') {
                return {
                    // @ts-ignore node.owner
                    pageInputs: node.owner.roots.find((x) => x.typename === 'PageInputs'),
                    // @ts-ignore node.owner
                    componentName: node.owner.owner.name
                };
            }
            return null;
        }
    });
    // Fetch all the Page nodes.
    const pages = traverser.filter((node) => node.node.typename === 'Page');
    // Create a RoutePath class for each possible route.
    const routes = pages.map((node) => {
        const title = getPageTitle(node.node);
        const parentsAndSelf = node.parents(traverser.selector).reverse();
        parentsAndSelf.push(node);
        // urlPath is the same on both Page and Router
        const routes = parentsAndSelf.map(getRoutePages).filter((x) => !!x);
        // Find the router this in placed inside.
        const parentRouters = node.parents((x) => x.typename === 'Router');
        const routerName = parentRouters.length > 0 ? parentRouters[0].node.parameters.name : undefined;
        return new RouteNode({
            title,
            // @ts-expect-error node.tag
            componentName: node.tag.componentName,
            routerName,
            current: routes[routes.length - 1],
            previous: routes.slice(0, routes.length - 1)
        });
    });
    // Ask the user for the dynamic routes.
    const dynamicHash = {};
    await Promise.all(routes.map((x) => {
        if (x.current.variables.length === 0) {
            return Promise.resolve([]);
        }
        else if (!dynamicHash[x.current.id]) {
            return (async function () {
                const expandedPaths = options.expandPaths ? await options.expandPaths(x) : [x];
                dynamicHash[x.current.id] = expandedPaths.map((x) => ({
                    kind: build_context/* PageType */.g.Dynamic,
                    // This is filled in by _getExpanded later
                    componentName: undefined,
                    ...x
                }));
                return dynamicHash[x.current.id];
            })();
        }
        else {
            return Promise.resolve(dynamicHash[x.current.id]);
        }
    }));
    // Create the final list of pages.
    const indexedPages = routes.map((node) => node._getExpanded(dynamicHash)).flat();
    return { routes, pages: indexedPages, dynamicHash };
}


/***/ }),

/***/ 3702:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  $: () => (/* binding */ AiQuery)
});

;// ./src/editor/src/models/AiAssistant/_backend/commandLexer.ts
class ReActCommand {
    constructor(type, args) {
        this.type = type;
        this.args = args;
    }
}
class ReActCommandLexer {
    constructor() {
        this._position = 0;
        this._commands = [];
        this._buffer = '';
    }
    get commands() {
        return this._commands;
    }
    peek(input) {
        if (this._position < input.length) {
            return input[this._position];
        }
        return '';
    }
    next(input) {
        const ch = input[this._position];
        this._position++;
        return ch;
    }
    readUntil(input, stopChars) {
        let value = '';
        let escaped = false;
        while (this._position < input.length) {
            const ch = this.peek(input);
            if (ch === '\n') {
                value += ch;
                this.next(input);
            }
            else if (stopChars.includes(ch) && !escaped) {
                break;
            }
            else if (ch === '\\' && !escaped) {
                escaped = true;
                this.next(input);
            }
            else {
                escaped = false;
                value += this.next(input);
            }
        }
        return value.trim();
    }
    append(ch) {
        this._buffer += ch;
        const commandCount = this.commands.length;
        this.tokenize(this._buffer);
        // TODO: Check if any of the command content changed
        if (this.commands.length > commandCount) {
            return this.commands.slice(commandCount - 1);
        }
        return [];
    }
    tokenize(input) {
        this._position = 0;
        this._commands = [];
        while (this._position < input.length) {
            const uppercaseRegex = /[A-Z]/;
            while (this._position < input.length && !uppercaseRegex.test(this.peek(input))) {
                this.next(input);
            }
            const value = this.readUntil(input, ['[']);
            const commandType = value.trim();
            const args = [];
            if (this.peek(input) === '[') {
                this.next(input);
            }
            while (this.peek(input) !== ']') {
                if (this._position >= input.length) {
                    break;
                }
                if (this.peek(input) === '"') {
                    this.next(input);
                    const arg = this.readUntil(input, ['"']);
                    args.push(arg);
                    this.next(input);
                }
                else {
                    this.next(input);
                }
            }
            if (this.peek(input) === ']') {
                this.next(input);
                if (commandType !== '' && /^[A-Z]/.test(commandType)) {
                    this._commands.push(new ReActCommand(commandType, args));
                }
            }
            else {
                if (this._commands.length > 0) {
                    const lastCommand = this._commands[this._commands.length - 1];
                    lastCommand.type = commandType;
                    lastCommand.args = args;
                }
            }
        }
        return this._commands;
    }
}

;// ./src/editor/src/models/AiAssistant/_backend/lexer.ts
var TokenTypes;
(function (TokenTypes) {
    TokenTypes["OPEN_TAG"] = "OPEN_TAG";
    TokenTypes["CLOSE_TAG"] = "CLOSE_TAG";
    TokenTypes["SELF_CLOSING_TAG"] = "SELF_CLOSING_TAG";
    TokenTypes["TEXT"] = "TEXT";
})(TokenTypes || (TokenTypes = {}));
class Token {
    constructor(type, value, attributes = {}) {
        this.type = type;
        this.value = value;
        this.attributes = attributes;
    }
}
class Lexer {
    constructor() {
        this._position = 0;
        this._tokens = [];
        this._buffer = '';
    }
    get tokens() {
        return this._tokens;
    }
    peek(input) {
        if (this._position < input.length) {
            return input[this._position];
        }
        return '';
    }
    next(input) {
        const ch = input[this._position];
        this._position++;
        return ch;
    }
    readUntil(input, stopChar) {
        let value = '';
        while (this._position < input.length) {
            const ch = this.peek(input);
            if (ch === stopChar) {
                break;
            }
            value += this.next(input);
        }
        return value;
    }
    tokenizeTag(input) {
        var _a;
        const parts = input.trim().split(/(?=\s\w+=)/);
        const tagName = ((_a = parts.shift()) === null || _a === void 0 ? void 0 : _a.trim()) || '';
        const attributes = {};
        for (const part of parts) {
            const [key, value] = part.trim().split('=');
            if (value) {
                attributes[key] = value.replace(/^"(.*)"$/, '$1');
            }
        }
        return { tagName, attributes };
    }
    tokenize(input) {
        const _tokens = [];
        this._position = 0;
        while (this._position < input.length) {
            const ch = this.peek(input);
            if (ch === '<') {
                this.next(input);
                const value = this.readUntil(input, '>');
                // If there is no closing '>' for an OPEN_TAG, return an empty array and store it in the _buffer
                if (this._position >= input.length) {
                    this._buffer = '<' + value;
                    return [];
                }
                this.next(input);
                if (value.startsWith('/')) {
                    _tokens.push(new Token(TokenTypes.CLOSE_TAG, value.slice(1)));
                }
                else if (value.endsWith('/')) {
                    const { tagName, attributes } = this.tokenizeTag(value.slice(0, -1));
                    _tokens.push(new Token(TokenTypes.SELF_CLOSING_TAG, tagName, attributes));
                }
                else {
                    const { tagName, attributes } = this.tokenizeTag(value);
                    _tokens.push(new Token(TokenTypes.OPEN_TAG, tagName, attributes));
                }
            }
            else {
                // handle tag values
                let value = '';
                while (this._position < input.length) {
                    const nextChar = this.peek(input);
                    if (nextChar === '<') {
                        break;
                    }
                    value += this.next(input);
                }
                if (value) {
                    _tokens.push(new Token(TokenTypes.TEXT, value));
                }
            }
        }
        return _tokens;
    }
    append(input) {
        // If there is a _buffer, prepend it to the input and clear the _buffer
        if (this._buffer) {
            input = this._buffer + input;
            this._buffer = '';
        }
        // Tokenize the new input
        const new_tokens = this.tokenize(input);
        const updated_tokens = [];
        // If the last token is TEXT and the first new token is not an OPEN_TAG, merge them
        if (this._tokens.length > 0 && new_tokens.length > 0) {
            const lastToken = this._tokens[this._tokens.length - 1];
            const firstNewToken = new_tokens[0];
            if (lastToken.type === TokenTypes.TEXT &&
                ![TokenTypes.OPEN_TAG, TokenTypes.CLOSE_TAG, TokenTypes.SELF_CLOSING_TAG].includes(firstNewToken.type)) {
                lastToken.value += firstNewToken.value;
                new_tokens.shift();
                updated_tokens.push(lastToken);
            }
        }
        this._tokens = this._tokens.concat(new_tokens);
        return [...new_tokens, ...updated_tokens];
    }
    getTokenIndex() {
        return this._tokens.length - 1;
    }
    getTextBetween(start, end) {
        return _tokensToText(this._tokens.slice(start, end));
    }
    getLastToken() {
        if (this._tokens.length > 0) {
            return this._tokens[this._tokens.length - 1];
        }
        return null;
    }
    getFullText() {
        return _tokensToText(this._tokens);
    }
}
function _tokensToText(_tokens) {
    return _tokens.reduce((text, token) => {
        if (token.type === TokenTypes.TEXT) {
            return text + token.value;
        }
        else if (token.type === TokenTypes.OPEN_TAG) {
            const attributes = Object.keys(token.attributes).map((x) => `${x}="${token.attributes[x]}"`);
            return attributes.length > 0
                ? text + '<' + token.value + ' ' + attributes.join(' ') + '>'
                : text + '<' + token.value + '>';
        }
        else if (token.type === TokenTypes.CLOSE_TAG) {
            return text + '</' + token.value + '>';
        }
        else if (token.type === TokenTypes.SELF_CLOSING_TAG) {
            const attributes = Object.keys(token.attributes).map((x) => `${x}="${token.attributes[x]}"`);
            return attributes.length > 0
                ? text + '<' + token.value + ' ' + attributes.join(' ') + ' />'
                : text + '<' + token.value + '/>';
        }
        return text;
    }, '');
}

;// ./src/editor/src/models/AiAssistant/_backend/parser.ts

class Parser extends Lexer {
    constructor(callback, openTagCallback, closeTagCallback) {
        super();
        this.openTagStack = [];
        this.lastTextToken = null;
        this.callback = callback;
        this.openTagCallback = openTagCallback;
        this.closeTagCallback = closeTagCallback;
    }
    append(input) {
        var _a;
        const newTokens = super.append(input);
        for (const token of newTokens) {
            if (token.type === TokenTypes.OPEN_TAG) {
                this.openTagStack.push(token);
                this.openTagCallback(token.value, token.attributes);
            }
            else if (token.type === TokenTypes.CLOSE_TAG) {
                const openTagIndex = this.openTagStack.findIndex((t) => t.value === token.value);
                if (openTagIndex !== -1) {
                    this.openTagStack.splice(openTagIndex, 1);
                    const lastToken = this.getLastToken();
                    if (lastToken && lastToken.type === TokenTypes.TEXT && this.openTagStack.length === 0) {
                        this.callback(token.value, lastToken.value);
                    }
                    this.closeTagCallback(token.value, ((_a = this.lastTextToken) === null || _a === void 0 ? void 0 : _a.value) || '');
                }
            }
            else if (token.type === TokenTypes.SELF_CLOSING_TAG) {
                this.openTagCallback(token.value, token.attributes);
                this.closeTagCallback(token.value, '');
            }
            else if (token.type === TokenTypes.TEXT) {
                this.lastTextToken = token;
                if (this.openTagStack.length > 0) {
                    const currentOpenTag = this.openTagStack[this.openTagStack.length - 1];
                    if (currentOpenTag.type === TokenTypes.OPEN_TAG) {
                        this.callback(currentOpenTag.value, token.value);
                    }
                }
            }
        }
        return newTokens;
    }
    getCurrentOpenTag() {
        if (this.openTagStack.length > 0) {
            return this.openTagStack[this.openTagStack.length - 1];
        }
        return null;
    }
    getLastTextToken() {
        return this.lastTextToken;
    }
}

// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/context/ai-api.ts + 2 modules
var ai_api = __webpack_require__(51917);
;// ./src/editor/src/models/AiAssistant/context/ai-query.ts



var AiQuery;
(function (AiQuery) {
    async function chatReAct({ messages, provider, abortController }) {
        const parser = new ReActCommandLexer();
        let fullText = '';
        await ai_api.Ai.chatStream({
            provider,
            messages,
            abortController,
            onStream: (_, text) => {
                if (text) {
                    fullText += text;
                    parser.append(text);
                }
            }
        });
        return {
            commands: parser.commands,
            fullText
        };
    }
    AiQuery.chatReAct = chatReAct;
    async function chatStreamXml({ messages, provider, abortController, onEnd, onStream, onTagOpen, onTagEnd }) {
        const parser = new Parser((tagName, text) => {
            console.debug(tagName, text);
            onStream && onStream(tagName, text);
        }, (tagName, attributes) => {
            onTagOpen && onTagOpen(tagName, attributes);
        }, (tagName, fullText) => {
            onTagEnd && onTagEnd(tagName, fullText);
        });
        await ai_api.Ai.chatStream({
            provider,
            messages,
            abortController,
            onEnd,
            onStream: (_, text) => {
                if (text) {
                    parser.append(text);
                }
            }
        });
        return parser.getFullText();
    }
    AiQuery.chatStreamXml = chatStreamXml;
})(AiQuery || (AiQuery = {}));


/***/ }),

/***/ 3762:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.CellEditor-module__CellEditor--jfSUx{position:relative}.CellEditor-module__Input--G9zFY,.CellEditor-module__DateInput--jlcO8{width:100%;padding:4px 8px;border:1px solid var(--theme-color-primary);border-radius:4px;background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-default);font-size:12px}.CellEditor-module__Input--G9zFY:focus,.CellEditor-module__DateInput--jlcO8:focus{outline:none;border-color:var(--theme-color-primary);box-shadow:0 0 0 2px var(--theme-color-primary-muted)}.CellEditor-module__JsonEditor--K8fuJ{width:250px;min-height:100px;padding:8px;border:1px solid var(--theme-color-primary);border-radius:4px;background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-default);font-family:monospace;font-size:11px;resize:vertical}.CellEditor-module__JsonEditor--K8fuJ:focus{outline:none;border-color:var(--theme-color-primary);box-shadow:0 0 0 2px var(--theme-color-primary-muted)}.CellEditor-module__JsonActions--n9ipT{display:flex;gap:8px;margin-top:8px}.CellEditor-module__SaveButton--phxrP,.CellEditor-module__CancelButton--QNz4Z{padding:4px 12px;border-radius:4px;font-size:11px;cursor:pointer}.CellEditor-module__SaveButton--phxrP{background-color:var(--theme-color-primary);color:var(--theme-color-fg-on-primary);border:none}.CellEditor-module__SaveButton--phxrP:hover{opacity:.9}.CellEditor-module__CancelButton--QNz4Z{background-color:var(--theme-color-bg-3);color:var(--theme-color-fg-default);border:1px solid var(--theme-color-border-default)}.CellEditor-module__CancelButton--QNz4Z:hover{background-color:var(--theme-color-bg-2)}.CellEditor-module__Error--g4xg2{position:absolute;top:100%;left:0;margin-top:4px;padding:4px 8px;background-color:var(--theme-color-danger);color:#fff;font-size:10px;border-radius:4px;z-index:10;white-space:nowrap}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/databrowser/CellEditor.module.scss"],"names":[],"mappings":"AAIA,sCACE,iBAAA,CAGF,sEAEE,UAAA,CACA,eAAA,CACA,2CAAA,CACA,iBAAA,CACA,wCAAA,CACA,mCAAA,CACA,cAAA,CAEA,kFACE,YAAA,CACA,uCAAA,CACA,qDAAA,CAIJ,sCACE,WAAA,CACA,gBAAA,CACA,WAAA,CACA,2CAAA,CACA,iBAAA,CACA,wCAAA,CACA,mCAAA,CACA,qBAAA,CACA,cAAA,CACA,eAAA,CAEA,4CACE,YAAA,CACA,uCAAA,CACA,qDAAA,CAIJ,uCACE,YAAA,CACA,OAAA,CACA,cAAA,CAGF,8EAEE,gBAAA,CACA,iBAAA,CACA,cAAA,CACA,cAAA,CAGF,sCACE,2CAAA,CACA,sCAAA,CACA,WAAA,CAEA,4CACE,UAAA,CAIJ,wCACE,wCAAA,CACA,mCAAA,CACA,kDAAA,CAEA,8CACE,wCAAA,CAIJ,iCACE,iBAAA,CACA,QAAA,CACA,MAAA,CACA,cAAA,CACA,eAAA,CACA,0CAAA,CACA,UAAA,CACA,cAAA,CACA,iBAAA,CACA,UAAA,CACA,kBAAA","sourcesContent":["/**\n * CellEditor styles\n */\n\n.CellEditor {\n  position: relative;\n}\n\n.Input,\n.DateInput {\n  width: 100%;\n  padding: 4px 8px;\n  border: 1px solid var(--theme-color-primary);\n  border-radius: 4px;\n  background-color: var(--theme-color-bg-1);\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n    box-shadow: 0 0 0 2px var(--theme-color-primary-muted);\n  }\n}\n\n.JsonEditor {\n  width: 250px;\n  min-height: 100px;\n  padding: 8px;\n  border: 1px solid var(--theme-color-primary);\n  border-radius: 4px;\n  background-color: var(--theme-color-bg-1);\n  color: var(--theme-color-fg-default);\n  font-family: monospace;\n  font-size: 11px;\n  resize: vertical;\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n    box-shadow: 0 0 0 2px var(--theme-color-primary-muted);\n  }\n}\n\n.JsonActions {\n  display: flex;\n  gap: 8px;\n  margin-top: 8px;\n}\n\n.SaveButton,\n.CancelButton {\n  padding: 4px 12px;\n  border-radius: 4px;\n  font-size: 11px;\n  cursor: pointer;\n}\n\n.SaveButton {\n  background-color: var(--theme-color-primary);\n  color: var(--theme-color-fg-on-primary);\n  border: none;\n\n  &:hover {\n    opacity: 0.9;\n  }\n}\n\n.CancelButton {\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-default);\n  border: 1px solid var(--theme-color-border-default);\n\n  &:hover {\n    background-color: var(--theme-color-bg-2);\n  }\n}\n\n.Error {\n  position: absolute;\n  top: 100%;\n  left: 0;\n  margin-top: 4px;\n  padding: 4px 8px;\n  background-color: var(--theme-color-danger);\n  color: white;\n  font-size: 10px;\n  border-radius: 4px;\n  z-index: 10;\n  white-space: nowrap;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"CellEditor": `CellEditor-module__CellEditor--jfSUx`,
	"Input": `CellEditor-module__Input--G9zFY`,
	"DateInput": `CellEditor-module__DateInput--jlcO8`,
	"JsonEditor": `CellEditor-module__JsonEditor--K8fuJ`,
	"JsonActions": `CellEditor-module__JsonActions--n9ipT`,
	"SaveButton": `CellEditor-module__SaveButton--phxrP`,
	"CancelButton": `CellEditor-module__CancelButton--QNz4Z`,
	"Error": `CellEditor-module__Error--g4xg2`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 3966:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.InspectPopup-module__Root--ZH7Cs{background-color:var(--theme-color-bg-4);max-height:300px;max-width:500px;display:flex;gap:5px;padding:5px;border:1px solid var(--theme-color-border-default)}.InspectPopup-module__ValueContainer--RCZaY{overflow:auto;gap:5px;display:flex;flex-direction:column;padding-right:16px}.InspectPopup-module__ValueContainer--RCZaY span,.InspectPopup-module__ValueContainer--RCZaY div{font-family:var(--font-family-code)}.InspectPopup-module__ValueContainer--RCZaY .collapsed-icon svg,.InspectPopup-module__ValueContainer--RCZaY .expanded-icon svg{width:.8em !important;height:.8em !important;padding-top:.1em}.InspectPopup-module__ValueContainer--RCZaY .collapsed-icon svg,.InspectPopup-module__ValueContainer--RCZaY .collapsed-icon path,.InspectPopup-module__ValueContainer--RCZaY .expanded-icon svg,.InspectPopup-module__ValueContainer--RCZaY .expanded-icon path{color:var(--theme-color-fg-default-shy) !important;fill:var(--theme-color-fg-default-shy) !important}.InspectPopup-module__ValueContainer--RCZaY .object-key span{color:var(--theme-color-fg-highlight)}.InspectPopup-module__ValueContainer--RCZaY .node-ellipsis{font-size:1em !important}.InspectPopup-module__ValueInspector--epmsZ{font-family:monospace;color:var(--theme-color-fg-highlight);white-space:pre;cursor:text;user-select:text;display:flex}.InspectPopup-module__ValueInspector--epmsZ img{margin:0 auto;max-width:100px;max-height:50px}.InspectPopup-module__PinButton--XvpzO{-webkit-mask:url(../assets/icons/editor/push_pin_black_24dp-outline.svg);-webkit-mask-size:14px 14px;width:14px;height:14px;margin:0;padding:0;border:none;background:var(--theme-color-fg-default);flex-shrink:0}.InspectPopup-module__PinButton--XvpzO.InspectPopup-module__is-pinned--ZxYhd{-webkit-mask:url(../assets/icons/editor/push_pin_black_24dp-filled.svg);-webkit-mask-size:14px 14px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/nodegrapheditor/InspectJSONView/InspectPopup.module.scss"],"names":[],"mappings":"AAEA,kCACE,wCAAA,CACA,gBAAA,CACA,eAAA,CACA,YAAA,CACA,OAAA,CACA,WAAA,CACA,kDAAA,CAGF,4CACE,aAAA,CACA,OAAA,CACA,YAAA,CACA,qBAAA,CACA,kBAAA,CAEA,iGAEE,mCAAA,CAKA,+HACE,qBAAA,CACA,sBAAA,CACA,gBAAA,CAGF,gQAEE,kDAAA,CACA,iDAAA,CAKF,6DACE,qCAAA,CAIJ,2DACE,wBAAA,CAIJ,4CACE,qBAAA,CACA,qCAAA,CACA,eAAA,CACA,WAAA,CACA,gBAAA,CACA,YAAA,CAEA,gDACE,aAAA,CACA,eAAA,CACA,eAAA,CAIJ,uCACE,wEAAA,CACA,2BAAA,CACA,UApEc,CAqEd,WArEc,CAsEd,QAAA,CACA,SAAA,CACA,WAAA,CACA,wCAAA,CACA,aAAA,CAEA,6EACE,uEAAA,CACA,2BAAA","sourcesContent":["$pin-icon-size: 14px;\n\n.Root {\n  background-color: var(--theme-color-bg-4);\n  max-height: 300px;\n  max-width: 500px;\n  display: flex;\n  gap: 5px;\n  padding: 5px;\n  border: 1px solid var(--theme-color-border-default);\n}\n\n.ValueContainer {\n  overflow: auto;\n  gap: 5px;\n  display: flex;\n  flex-direction: column;\n  padding-right: 16px; /* Give some space for the copy icon */\n\n  span,\n  div {\n    font-family: var(--font-family-code);\n  }\n\n  :global(.collapsed-icon),\n  :global(.expanded-icon) {\n    svg {\n      width: 0.8em !important;\n      height: 0.8em !important;\n      padding-top: 0.1em;\n    }\n\n    svg,\n    path {\n      color: var(--theme-color-fg-default-shy) !important;\n      fill: var(--theme-color-fg-default-shy) !important;\n    }\n  }\n\n  :global(.object-key) {\n    span {\n      color: var(--theme-color-fg-highlight);\n    }\n  }\n\n  :global(.node-ellipsis) {\n    font-size: 1em !important;\n  }\n}\n\n.ValueInspector {\n  font-family: monospace;\n  color: var(--theme-color-fg-highlight);\n  white-space: pre;\n  cursor: text;\n  user-select: text;\n  display: flex;\n\n  img {\n    margin: 0 auto;\n    max-width: 100px;\n    max-height: 50px;\n  }\n}\n\n.PinButton {\n  -webkit-mask: url(../assets/icons/editor/push_pin_black_24dp-outline.svg);\n  -webkit-mask-size: $pin-icon-size $pin-icon-size;\n  width: $pin-icon-size;\n  height: $pin-icon-size;\n  margin: 0;\n  padding: 0;\n  border: none;\n  background: var(--theme-color-fg-default);\n  flex-shrink: 0;\n\n  &.is-pinned {\n    -webkit-mask: url(../assets/icons/editor/push_pin_black_24dp-filled.svg);\n    -webkit-mask-size: $pin-icon-size $pin-icon-size;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `InspectPopup-module__Root--ZH7Cs`,
	"ValueContainer": `InspectPopup-module__ValueContainer--RCZaY`,
	"ValueInspector": `InspectPopup-module__ValueInspector--epmsZ`,
	"PinButton": `InspectPopup-module__PinButton--XvpzO`,
	"is-pinned": `InspectPopup-module__is-pinned--ZxYhd`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 4073:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  m: () => (/* binding */ createIndexPage),
  H: () => (/* binding */ deployToFolder)
});

// EXTERNAL MODULE: ../noodl-platform/src/index.ts + 10 modules
var src = __webpack_require__(37218);
// EXTERNAL MODULE: ./src/editor/src/utils/exporter/index.ts + 4 modules
var exporter = __webpack_require__(87144);
;// ./src/editor/src/utils/compilation/build/cleanup.ts

async function clearFolders({ projectPath, outputPath, files }) {
    const topLevelFolders = [];
    // Collect toplevel folders
    for (const i in files) {
        const file = files[i];
        const localPath = file.fullPath.substring(projectPath.length + 1);
        // File is in a subfolder of the project directory, delete it
        // but make sure to never delete .git
        if (localPath.indexOf('/') !== -1 && localPath.substring(0, 4) !== '.git') {
            const comps = localPath.split('/');
            const topFolderName = comps[0];
            if (topLevelFolders.indexOf(topFolderName) === -1) {
                topLevelFolders.push(topFolderName);
            }
        }
    }
    // No folders to clear
    if (topLevelFolders.length === 0) {
        return;
    }
    let foldersToClear = topLevelFolders.length;
    for (const i in topLevelFolders) {
        const t = topLevelFolders[i];
        await src.filesystem.removeDirRecursive(outputPath + '/' + t);
        foldersToClear--;
        if (foldersToClear === 0)
            return;
    }
}

;// ./src/editor/src/utils/compilation/build/copy.ts


async function copyProjectFilesToFolder(projectPath, direntry) {
    // TODO: Load something like .noodlignore file list
    const ignoreFiles = ['.DS_Store', '.gitignore', '.gitattributes', 'project.json', 'Dockerfile'];
    // Copy everything from the project folder
    if (!projectPath) {
        throw new Error('Couldnt open project folder.');
    }
    await src.filesystem.makeDirectory(direntry);
    let files = await src.filesystem.listDirectoryFiles(projectPath);
    files = files.filter((f) => {
        if (ignoreFiles.indexOf(f.name) !== -1)
            return false;
        // TODO: Make this easier to access
        if (f.fullPath.indexOf('.git') !== -1)
            return false; // Ignore git files
        if (f.fullPath.indexOf('.noodl') !== -1)
            return false; // Ignore noodl files
        return true;
    });
    // First clear all folders, will be recreated later
    await clearFolders({
        projectPath,
        outputPath: direntry,
        files
    });
    let filesLeftToCopy = 0;
    let totalSuccess = true;
    function fileCompleted(success) {
        filesLeftToCopy--;
        totalSuccess = totalSuccess && success;
    }
    async function makeDirectoryAndCopyFile(f) {
        // TODO: This requires that the project path is looking nice
        // Example:
        // C:\\Users\\Eric\\AppData\\Roaming\\Noodl\\projects\\9acdd495-3d92-4490-ae0a-44f17bf47dca
        // C:\Users\Eric\AppData\Roaming\Noodl\projects\9acdd495-3d92-4490-ae0a-44f17bf47dca\noodl_modules\
        //                                                                       it will cut here ^
        const folderPath = f.fullPath.substring(projectPath.length, f.fullPath.length - f.name.length - 1);
        const localPath = f.fullPath.substring(projectPath.length);
        filesLeftToCopy++;
        const targetDir = src.filesystem.join(direntry, folderPath);
        await src.filesystem.makeDirectory(targetDir);
        try {
            await src.filesystem.copyFile(f.fullPath, direntry + '/' + localPath);
            fileCompleted(true);
        }
        catch (error) {
            console.error(error);
            fileCompleted(false);
        }
    }
    const tasks = files.map(makeDirectoryAndCopyFile);
    await Promise.all(tasks);
    if (!totalSuccess) {
        throw new Error('Failed to copy project files.');
    }
}

// EXTERNAL MODULE: ./src/editor/src/utils/compilation/build/deploy-index.ts
var deploy_index = __webpack_require__(71287);
// EXTERNAL MODULE: ./src/editor/src/utils/compilation/build/processors/html-processor.ts
var html_processor = __webpack_require__(62111);
;// ./src/editor/src/utils/compilation/build/deployer.ts





/**
 * Deployer is handling all the project deploy to a folder logic.
 *
 * This is also used when deploying to the Cloud
 * where it just copies over the built files.
 */
async function deployToFolder({ project, direntry, environment, baseUrl, envVariables, runtimeType = 'deploy' }) {
    // Check if this is a project folder
    try {
        const projectContent = await src.filesystem.readJson(direntry + '/project.json');
        if (projectContent) {
            return Promise.reject({ result: 'failure', message: 'Cannot deploy to a project folder.' });
        }
        // There is no project.json, this is not a project folder, good continue with the deploy
    }
    catch (error) {
        // noop; file doesn't exist
    }
    // Start by copying all files from the project folder to the deploy directory
    await copyProjectFilesToFolder(project._retainedProjectDirectory, direntry);
    // Export project
    const exportJson = exporter.exportToJSON(project, {
        useBundles: true,
        useBundleHashes: true,
        environment,
        // Remove all the cloud function components
        ignoreComponentFilter: (component) => !component.name.startsWith('/#__cloud__/')
    });
    if (!exportJson) {
        return Promise.reject({ result: 'failure', message: 'Failed to export project.' });
    }
    // Remove all keys from config that require master key
    const configSchema = exportJson.metadata['dbConfigSchema'];
    for (const key in configSchema) {
        if (configSchema[key].masterKeyOnly)
            delete configSchema[key];
    }
    // Read deploy description
    const index = await (0,deploy_index/* loadDeployIndex */.e1)(`${runtimeType}/index.json`);
    // Copy all deploy files
    await (0,deploy_index/* copyDeployFilesToFolder */.B3)({
        project,
        direntry,
        files: index,
        exportJson,
        baseUrl,
        envVariables,
        runtimeType
    });
    //then the export component bundles
    const dir = direntry + '/noodl_bundles/';
    for (const bundleId in exportJson.componentIndex) {
        if (bundleId !== 'root') {
            const json = JSON.stringify(exporter.exportComponentBundle(project, bundleId, exportJson.componentIndex));
            if (!src.filesystem.exists(dir)) {
                await src.filesystem.makeDirectory(dir);
            }
            await src.filesystem.writeFile(dir + bundleId + '.json', json);
        }
    }
}
async function createIndexPage(project, parameters) {
    // Read deploy description
    const index = await (0,deploy_index/* loadDeployIndex */.e1)('deploy/index.json');
    // Find the "index.html" file
    const indexFile = index.find((entry) => entry.url === 'index.html');
    if (!indexFile) {
        throw new Error('Could not find index.html in deploy index.');
    }
    // Read the index.html file
    const indexFilePath = src.filesystem.join((0,deploy_index/* getExternalFolderPath */.Pw)(), 'deploy', indexFile.url);
    const indexContent = await src.filesystem.readFile(indexFilePath);
    const htmlProcessor = new html_processor/* HtmlProcessor */.G(project);
    const content = await htmlProcessor.process(indexContent, parameters);
    return content;
}


/***/ }),

/***/ 4102:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_TextStylePicker_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(8580);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_TextStylePicker_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_TextStylePicker_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_TextStylePicker_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_TextStylePicker_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 4205:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgImportDown = function SvgImportDown(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.88672 13.8511C4.30093 13.8511 4.63672 14.1869 4.63672 14.6011V19.8511H19.6367V14.6011C19.6367 14.1869 19.9725 13.8511 20.3867 13.8511C20.8009 13.8511 21.1367 14.1869 21.1367 14.6011V19.8511C21.1367 20.2489 20.9787 20.6304 20.6974 20.9117C20.4161 21.193 20.0345 21.3511 19.6367 21.3511H4.63672C4.2389 21.3511 3.85736 21.193 3.57606 20.9117C3.29475 20.6304 3.13672 20.2489 3.13672 19.8511V14.6011C3.13672 14.1869 3.47251 13.8511 3.88672 13.8511Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M16.6165 10.1311C16.3265 9.84107 15.8465 9.84107 15.5565 10.1311L12.8965 12.7911V4.10107C12.8965 3.69107 12.5565 3.35107 12.1465 3.35107C11.7365 3.35107 11.3965 3.69107 11.3965 4.10107V12.7911L8.73648 10.1311C8.44648 9.84107 7.96648 9.84107 7.67648 10.1311C7.38648 10.4211 7.38648 10.9011 7.67648 11.1911L11.6165 15.1311C11.6865 15.2011 11.7665 15.2511 11.8565 15.2911C12.0365 15.3711 12.2465 15.3711 12.4265 15.2911C12.5165 15.2511 12.5965 15.2011 12.6665 15.1311L16.6065 11.1911C16.8965 10.9011 16.8965 10.4211 16.6065 10.1311H16.6165Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgImportDown);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "a82e2e464c2cbb19886784088ac375a1.svg");

/***/ }),

/***/ 4273:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-list {
	position: relative;
	height: 100%;
	width: 100%;
	white-space: nowrap;
}

.monaco-list.mouse-support {
	user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}

.monaco-list > .monaco-scrollable-element {
	height: 100%;
}

.monaco-list-rows {
	position: relative;
	width: 100%;
	height: 100%;
}

.monaco-list.horizontal-scrolling .monaco-list-rows {
	width: auto;
	min-width: 100%;
}

.monaco-list-row {
	position: absolute;
	box-sizing: border-box;
	overflow: hidden;
	width: 100%;
}

.monaco-list.mouse-support .monaco-list-row {
	cursor: pointer;
	touch-action: none;
}

/* for OS X ballistic scrolling */
.monaco-list-row.scrolling {
	display: none !important;
}

/* Focus */
.monaco-list.element-focused,
.monaco-list.selection-single,
.monaco-list.selection-multiple {
	outline: 0 !important;
}

/* Dnd */
.monaco-drag-image {
	display: inline-block;
	padding: 1px 7px;
	border-radius: 10px;
	font-size: 12px;
	position: absolute;
	z-index: 1000;
}

/* Filter */

.monaco-list-type-filter-message {
	position: absolute;
	box-sizing: border-box;
	width: 100%;
	height: 100%;
	top: 0;
	left: 0;
	padding: 40px 1em 1em 1em;
	text-align: center;
	white-space: normal;
	opacity: 0.7;
	pointer-events: none;
}

.monaco-list-type-filter-message:empty {
	display: none;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/list/list.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kBAAkB;CAClB,YAAY;CACZ,WAAW;CACX,mBAAmB;AACpB;;AAEA;CACC,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;AACtB;;AAEA;CACC,YAAY;AACb;;AAEA;CACC,kBAAkB;CAClB,WAAW;CACX,YAAY;AACb;;AAEA;CACC,WAAW;CACX,eAAe;AAChB;;AAEA;CACC,kBAAkB;CAClB,sBAAsB;CACtB,gBAAgB;CAChB,WAAW;AACZ;;AAEA;CACC,eAAe;CACf,kBAAkB;AACnB;;AAEA,iCAAiC;AACjC;CACC,wBAAwB;AACzB;;AAEA,UAAU;AACV;;;CAGC,qBAAqB;AACtB;;AAEA,QAAQ;AACR;CACC,qBAAqB;CACrB,gBAAgB;CAChB,mBAAmB;CACnB,eAAe;CACf,kBAAkB;CAClB,aAAa;AACd;;AAEA,WAAW;;AAEX;CACC,kBAAkB;CAClB,sBAAsB;CACtB,WAAW;CACX,YAAY;CACZ,MAAM;CACN,OAAO;CACP,yBAAyB;CACzB,kBAAkB;CAClB,mBAAmB;CACnB,YAAY;CACZ,oBAAoB;AACrB;;AAEA;CACC,aAAa;AACd","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-list {\n\tposition: relative;\n\theight: 100%;\n\twidth: 100%;\n\twhite-space: nowrap;\n}\n\n.monaco-list.mouse-support {\n\tuser-select: none;\n\t-webkit-user-select: none;\n\t-ms-user-select: none;\n}\n\n.monaco-list > .monaco-scrollable-element {\n\theight: 100%;\n}\n\n.monaco-list-rows {\n\tposition: relative;\n\twidth: 100%;\n\theight: 100%;\n}\n\n.monaco-list.horizontal-scrolling .monaco-list-rows {\n\twidth: auto;\n\tmin-width: 100%;\n}\n\n.monaco-list-row {\n\tposition: absolute;\n\tbox-sizing: border-box;\n\toverflow: hidden;\n\twidth: 100%;\n}\n\n.monaco-list.mouse-support .monaco-list-row {\n\tcursor: pointer;\n\ttouch-action: none;\n}\n\n/* for OS X ballistic scrolling */\n.monaco-list-row.scrolling {\n\tdisplay: none !important;\n}\n\n/* Focus */\n.monaco-list.element-focused,\n.monaco-list.selection-single,\n.monaco-list.selection-multiple {\n\toutline: 0 !important;\n}\n\n/* Dnd */\n.monaco-drag-image {\n\tdisplay: inline-block;\n\tpadding: 1px 7px;\n\tborder-radius: 10px;\n\tfont-size: 12px;\n\tposition: absolute;\n\tz-index: 1000;\n}\n\n/* Filter */\n\n.monaco-list-type-filter-message {\n\tposition: absolute;\n\tbox-sizing: border-box;\n\twidth: 100%;\n\theight: 100%;\n\ttop: 0;\n\tleft: 0;\n\tpadding: 40px 1em 1em 1em;\n\ttext-align: center;\n\twhite-space: normal;\n\topacity: 0.7;\n\tpointer-events: none;\n}\n\n.monaco-list-type-filter-message:empty {\n\tdisplay: none;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 4346:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCheckbox = function SvgCheckbox(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.6523 11.5636C22.0335 11.9632 22.0186 12.5962 21.619 12.9775L13.7812 20.4547C13.3946 20.8236 12.7863 20.8233 12.4 20.4541L8.48783 16.7155C8.08854 16.3339 8.07418 15.7009 8.45575 15.3017C8.83732 14.9024 9.47032 14.888 9.8696 15.2696L13.0915 18.3485L20.2384 11.5304C20.638 11.1491 21.271 11.164 21.6523 11.5636Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.37189 4.4585C4.19617 4.4585 4.05371 4.60095 4.05371 4.77668V26.1403C4.05371 26.316 4.19617 26.4585 4.37189 26.4585H25.7355C25.9113 26.4585 26.0537 26.316 26.0537 26.1403V4.77668C26.0537 4.60095 25.9113 4.4585 25.7355 4.4585H4.37189ZM2.55371 4.77668C2.55371 3.77252 3.36774 2.9585 4.37189 2.9585H25.7355C26.7397 2.9585 27.5537 3.77252 27.5537 4.77668V26.1403C27.5537 27.1445 26.7397 27.9585 25.7355 27.9585H4.37189C3.36774 27.9585 2.55371 27.1445 2.55371 26.1403V4.77668Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCheckbox);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "b709ab9c1f940e84f61a858361d67c5f.svg");

/***/ }),

/***/ 4480:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgArrowLineDown = function SvgArrowLineDown(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.1367 21.7009C21.1367 22.1151 20.8009 22.4509 20.3867 22.4509L3.88672 22.4509C3.47251 22.4509 3.13672 22.1151 3.13672 21.7009C3.13672 21.2867 3.47251 20.9509 3.88672 20.9509L20.3867 20.9509C20.8009 20.9509 21.1367 21.2867 21.1367 21.7009Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.421 18.9382C12.5105 18.9016 12.5944 18.8469 12.6671 18.7742L16.3648 15.0765C16.6577 14.7836 16.6577 14.3088 16.3648 14.0159C16.0719 13.723 15.597 13.723 15.3041 14.0159L12.8868 16.4332L12.8868 4.17548C12.8868 3.76127 12.551 3.42548 12.1368 3.42548C11.7226 3.42548 11.3868 3.76127 11.3868 4.17548L11.3868 16.4332L8.96943 14.0159C8.67654 13.723 8.20167 13.723 7.90877 14.0159C7.61588 14.3088 7.61588 14.7836 7.90877 15.0765L11.6044 18.7721C11.6111 18.7789 11.6179 18.7855 11.6248 18.792C11.7589 18.9172 11.9389 18.9939 12.1368 18.9939C12.2374 18.9939 12.3334 18.9741 12.421 18.9382Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgArrowLineDown);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "e3ab9fa9b4bf1ee2bff5badf86a4c833.svg");

/***/ }),

/***/ 4628:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.TextButton-module__Root--AjUVO{background-color:rgba(0,0,0,0);border:none;padding:0;height:20px;display:flex;align-items:center;cursor:pointer;padding:0 4px;transition:box-shadow var(--speed-turbo) var(--easing-base),background-color var(--speed-turbo) var(--easing-base)}.TextButton-module__Root--AjUVO:hover{box-shadow:0 0 0 4px var(--theme-color-fg-transparent);background-color:var(--theme-color-fg-transparent)}.TextButton-module__Root--AjUVO p{transition:color var(--speed-turbo)}.TextButton-module__Root--AjUVO path{transition:fill var(--speed-turbo)}.TextButton-module__Root--AjUVO.TextButton-module__is-size-default--KH40k p{font-size:14px}.TextButton-module__Root--AjUVO.TextButton-module__is-size-small--MJDnZ p{font-size:12px}.TextButton-module__Root--AjUVO.TextButton-module__has-left-spacing--RQ0An{margin-left:15px}.TextButton-module__Root--AjUVO.TextButton-module__has-right-spacing--JFxdI{margin-right:15px}.TextButton-module__Root--AjUVO.TextButton-module__is-variant-default--ZRenq path{fill:var(--theme-color-fg-default)}.TextButton-module__Root--AjUVO.TextButton-module__is-variant-default-contrast--I7pVO path{fill:var(--theme-color-fg-default-contrast)}.TextButton-module__Root--AjUVO.TextButton-module__is-variant-proud--z2j8i path{fill:var(--theme-color-fg-highlight)}.TextButton-module__Root--AjUVO.TextButton-module__is-variant-shy--sTfAo path{fill:var(--theme-color-fg-muted)}.TextButton-module__Root--AjUVO.TextButton-module__is-variant-success--_AShW path{fill:var(--theme-color-success)}.TextButton-module__Root--AjUVO.TextButton-module__is-variant-notice--lV2_d path{fill:var(--theme-color-notice)}.TextButton-module__Root--AjUVO.TextButton-module__is-variant-danger--SxNOY path{fill:var(--theme-color-danger)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/TextButton/TextButton.module.scss"],"names":[],"mappings":"AAAA,gCACE,8BAAA,CACA,WAAA,CACA,SAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,cAAA,CACA,aAAA,CACA,kHAAA,CAEA,sCACE,sDAAA,CACA,kDAAA,CAGF,kCACE,mCAAA,CAGF,qCACE,kCAAA,CAGF,4EACE,cAAA,CAGF,0EACE,cAAA,CAGF,2EACE,gBAAA,CAGF,4EACE,iBAAA,CAIA,kFACE,kCAAA,CAGF,2FACE,2CAAA,CAGF,gFACE,oCAAA,CAGF,8EACE,gCAAA,CAGF,kFACE,+BAAA,CAGF,iFACE,8BAAA,CAGF,iFACE,8BAAA","sourcesContent":[".Root {\n  background-color: transparent;\n  border: none;\n  padding: 0;\n  height: 20px;\n  display: flex;\n  align-items: center;\n  cursor: pointer;\n  padding: 0 4px;\n  transition: box-shadow var(--speed-turbo) var(--easing-base), background-color var(--speed-turbo) var(--easing-base);\n\n  &:hover {\n    box-shadow: 0 0 0 4px var(--theme-color-fg-transparent);\n    background-color: var(--theme-color-fg-transparent);\n  }\n\n  p {\n    transition: color var(--speed-turbo);\n  }\n\n  path {\n    transition: fill var(--speed-turbo);\n  }\n\n  &.is-size-default p {\n    font-size: 14px;\n  }\n\n  &.is-size-small p {\n    font-size: 12px;\n  }\n\n  &.has-left-spacing {\n    margin-left: 15px;\n  }\n\n  &.has-right-spacing {\n    margin-right: 15px;\n  }\n\n  &.is-variant {\n    &-default path {\n      fill: var(--theme-color-fg-default);\n    }\n\n    &-default-contrast path {\n      fill: var(--theme-color-fg-default-contrast);\n    }\n\n    &-proud path {\n      fill: var(--theme-color-fg-highlight);\n    }\n\n    &-shy path {\n      fill: var(--theme-color-fg-muted);\n    }\n\n    &-success path {\n      fill: var(--theme-color-success);\n    }\n\n    &-notice path {\n      fill: var(--theme-color-notice);\n    }\n\n    &-danger path {\n      fill: var(--theme-color-danger);\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `TextButton-module__Root--AjUVO`,
	"is-size-default": `TextButton-module__is-size-default--KH40k`,
	"is-size-small": `TextButton-module__is-size-small--MJDnZ`,
	"has-left-spacing": `TextButton-module__has-left-spacing--RQ0An`,
	"has-right-spacing": `TextButton-module__has-right-spacing--JFxdI`,
	"is-variant-default": `TextButton-module__is-variant-default--ZRenq`,
	"is-variant-default-contrast": `TextButton-module__is-variant-default-contrast--I7pVO`,
	"is-variant-proud": `TextButton-module__is-variant-proud--z2j8i`,
	"is-variant-shy": `TextButton-module__is-variant-shy--sTfAo`,
	"is-variant-success": `TextButton-module__is-variant-success--_AShW`,
	"is-variant-notice": `TextButton-module__is-variant-notice--lV2_d`,
	"is-variant-danger": `TextButton-module__is-variant-danger--SxNOY`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 4851:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

:root {
	--sash-size: 4px;
}

.monaco-sash {
	position: absolute;
	z-index: 35;
	touch-action: none;
}

.monaco-sash.disabled {
	pointer-events: none;
}

.monaco-sash.mac.vertical {
	cursor: col-resize;
}

.monaco-sash.vertical.minimum {
	cursor: e-resize;
}

.monaco-sash.vertical.maximum {
	cursor: w-resize;
}

.monaco-sash.mac.horizontal {
	cursor: row-resize;
}

.monaco-sash.horizontal.minimum {
	cursor: s-resize;
}

.monaco-sash.horizontal.maximum {
	cursor: n-resize;
}

.monaco-sash.disabled {
	cursor: default !important;
	pointer-events: none !important;
}

.monaco-sash.vertical {
	cursor: ew-resize;
	top: 0;
	width: var(--sash-size);
	height: 100%;
}

.monaco-sash.horizontal {
	cursor: ns-resize;
	left: 0;
	width: 100%;
	height: var(--sash-size);
}

.monaco-sash:not(.disabled) > .orthogonal-drag-handle {
	content: " ";
	height: calc(var(--sash-size) * 2);
	width: calc(var(--sash-size) * 2);
	z-index: 100;
	display: block;
	cursor: all-scroll;
	position: absolute;
}

.monaco-sash.horizontal.orthogonal-edge-north:not(.disabled)
	> .orthogonal-drag-handle.start,
.monaco-sash.horizontal.orthogonal-edge-south:not(.disabled)
	> .orthogonal-drag-handle.end {
	cursor: nwse-resize;
}

.monaco-sash.horizontal.orthogonal-edge-north:not(.disabled)
	> .orthogonal-drag-handle.end,
.monaco-sash.horizontal.orthogonal-edge-south:not(.disabled)
	> .orthogonal-drag-handle.start {
	cursor: nesw-resize;
}

.monaco-sash.vertical > .orthogonal-drag-handle.start {
	left: calc(var(--sash-size) * -0.5);
	top: calc(var(--sash-size) * -1);
}
.monaco-sash.vertical > .orthogonal-drag-handle.end {
	left: calc(var(--sash-size) * -0.5);
	bottom: calc(var(--sash-size) * -1);
}
.monaco-sash.horizontal > .orthogonal-drag-handle.start {
	top: calc(var(--sash-size) * -0.5);
	left: calc(var(--sash-size) * -1);
}
.monaco-sash.horizontal > .orthogonal-drag-handle.end {
	top: calc(var(--sash-size) * -0.5);
	right: calc(var(--sash-size) * -1);
}

.monaco-sash:before {
	content: '';
	pointer-events: none;
	position: absolute;
	width: 100%;
	height: 100%;
	transition: background-color 0.1s ease-out;
	background: transparent;
}

.monaco-sash.vertical:before {
	width: var(--sash-hover-size);
	left: calc(50% - (var(--sash-hover-size) / 2));
}

.monaco-sash.horizontal:before {
	height: var(--sash-hover-size);
	top: calc(50% - (var(--sash-hover-size) / 2));
}

.pointer-events-disabled {
	pointer-events: none !important;
}

/** Debug **/

.monaco-sash.debug {
	background: cyan;
}

.monaco-sash.debug.disabled {
	background: rgba(0, 255, 255, 0.2);
}

.monaco-sash.debug:not(.disabled) > .orthogonal-drag-handle {
	background: red;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/sash/sash.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,gBAAgB;AACjB;;AAEA;CACC,kBAAkB;CAClB,WAAW;CACX,kBAAkB;AACnB;;AAEA;CACC,oBAAoB;AACrB;;AAEA;CACC,kBAAkB;AACnB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,kBAAkB;AACnB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,0BAA0B;CAC1B,+BAA+B;AAChC;;AAEA;CACC,iBAAiB;CACjB,MAAM;CACN,uBAAuB;CACvB,YAAY;AACb;;AAEA;CACC,iBAAiB;CACjB,OAAO;CACP,WAAW;CACX,wBAAwB;AACzB;;AAEA;CACC,YAAY;CACZ,kCAAkC;CAClC,iCAAiC;CACjC,YAAY;CACZ,cAAc;CACd,kBAAkB;CAClB,kBAAkB;AACnB;;AAEA;;;;CAIC,mBAAmB;AACpB;;AAEA;;;;CAIC,mBAAmB;AACpB;;AAEA;CACC,mCAAmC;CACnC,gCAAgC;AACjC;AACA;CACC,mCAAmC;CACnC,mCAAmC;AACpC;AACA;CACC,kCAAkC;CAClC,iCAAiC;AAClC;AACA;CACC,kCAAkC;CAClC,kCAAkC;AACnC;;AAEA;CACC,WAAW;CACX,oBAAoB;CACpB,kBAAkB;CAClB,WAAW;CACX,YAAY;CACZ,0CAA0C;CAC1C,uBAAuB;AACxB;;AAEA;CACC,6BAA6B;CAC7B,8CAA8C;AAC/C;;AAEA;CACC,8BAA8B;CAC9B,6CAA6C;AAC9C;;AAEA;CACC,+BAA+B;AAChC;;AAEA,YAAY;;AAEZ;CACC,gBAAgB;AACjB;;AAEA;CACC,kCAAkC;AACnC;;AAEA;CACC,eAAe;AAChB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n:root {\n\t--sash-size: 4px;\n}\n\n.monaco-sash {\n\tposition: absolute;\n\tz-index: 35;\n\ttouch-action: none;\n}\n\n.monaco-sash.disabled {\n\tpointer-events: none;\n}\n\n.monaco-sash.mac.vertical {\n\tcursor: col-resize;\n}\n\n.monaco-sash.vertical.minimum {\n\tcursor: e-resize;\n}\n\n.monaco-sash.vertical.maximum {\n\tcursor: w-resize;\n}\n\n.monaco-sash.mac.horizontal {\n\tcursor: row-resize;\n}\n\n.monaco-sash.horizontal.minimum {\n\tcursor: s-resize;\n}\n\n.monaco-sash.horizontal.maximum {\n\tcursor: n-resize;\n}\n\n.monaco-sash.disabled {\n\tcursor: default !important;\n\tpointer-events: none !important;\n}\n\n.monaco-sash.vertical {\n\tcursor: ew-resize;\n\ttop: 0;\n\twidth: var(--sash-size);\n\theight: 100%;\n}\n\n.monaco-sash.horizontal {\n\tcursor: ns-resize;\n\tleft: 0;\n\twidth: 100%;\n\theight: var(--sash-size);\n}\n\n.monaco-sash:not(.disabled) > .orthogonal-drag-handle {\n\tcontent: \" \";\n\theight: calc(var(--sash-size) * 2);\n\twidth: calc(var(--sash-size) * 2);\n\tz-index: 100;\n\tdisplay: block;\n\tcursor: all-scroll;\n\tposition: absolute;\n}\n\n.monaco-sash.horizontal.orthogonal-edge-north:not(.disabled)\n\t> .orthogonal-drag-handle.start,\n.monaco-sash.horizontal.orthogonal-edge-south:not(.disabled)\n\t> .orthogonal-drag-handle.end {\n\tcursor: nwse-resize;\n}\n\n.monaco-sash.horizontal.orthogonal-edge-north:not(.disabled)\n\t> .orthogonal-drag-handle.end,\n.monaco-sash.horizontal.orthogonal-edge-south:not(.disabled)\n\t> .orthogonal-drag-handle.start {\n\tcursor: nesw-resize;\n}\n\n.monaco-sash.vertical > .orthogonal-drag-handle.start {\n\tleft: calc(var(--sash-size) * -0.5);\n\ttop: calc(var(--sash-size) * -1);\n}\n.monaco-sash.vertical > .orthogonal-drag-handle.end {\n\tleft: calc(var(--sash-size) * -0.5);\n\tbottom: calc(var(--sash-size) * -1);\n}\n.monaco-sash.horizontal > .orthogonal-drag-handle.start {\n\ttop: calc(var(--sash-size) * -0.5);\n\tleft: calc(var(--sash-size) * -1);\n}\n.monaco-sash.horizontal > .orthogonal-drag-handle.end {\n\ttop: calc(var(--sash-size) * -0.5);\n\tright: calc(var(--sash-size) * -1);\n}\n\n.monaco-sash:before {\n\tcontent: '';\n\tpointer-events: none;\n\tposition: absolute;\n\twidth: 100%;\n\theight: 100%;\n\ttransition: background-color 0.1s ease-out;\n\tbackground: transparent;\n}\n\n.monaco-sash.vertical:before {\n\twidth: var(--sash-hover-size);\n\tleft: calc(50% - (var(--sash-hover-size) / 2));\n}\n\n.monaco-sash.horizontal:before {\n\theight: var(--sash-hover-size);\n\ttop: calc(50% - (var(--sash-hover-size) / 2));\n}\n\n.pointer-events-disabled {\n\tpointer-events: none !important;\n}\n\n/** Debug **/\n\n.monaco-sash.debug {\n\tbackground: cyan;\n}\n\n.monaco-sash.debug.disabled {\n\tbackground: rgba(0, 255, 255, 0.2);\n}\n\n.monaco-sash.debug:not(.disabled) > .orthogonal-drag-handle {\n\tbackground: red;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 5049:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgQuestion = function SvgQuestion(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.1366 3.76872C7.59056 3.76872 3.90529 7.45399 3.90529 12C3.90529 16.546 7.59056 20.2313 12.1366 20.2313C16.6826 20.2313 20.3679 16.546 20.3679 12C20.3679 7.45399 16.6826 3.76872 12.1366 3.76872ZM2.40869 12C2.40869 6.62744 6.76401 2.27212 12.1366 2.27212C17.5091 2.27212 21.8645 6.62744 21.8645 12C21.8645 17.3726 17.5091 21.7279 12.1366 21.7279C6.76401 21.7279 2.40869 17.3726 2.40869 12Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.1366 18.1304C12.7565 18.1304 13.2591 17.6279 13.2591 17.008C13.2591 16.3881 12.7565 15.8855 12.1366 15.8855C11.5167 15.8855 11.0142 16.3881 11.0142 17.008C11.0142 17.6279 11.5167 18.1304 12.1366 18.1304Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M10.8482 6.65384C11.4636 6.39897 12.1406 6.33229 12.7938 6.46222C13.447 6.59215 14.047 6.91286 14.5179 7.38379C14.9889 7.85472 15.3096 8.45472 15.4395 9.10792C15.5694 9.76113 15.5028 10.4382 15.2479 11.0535C14.993 11.6688 14.5614 12.1947 14.0077 12.5647C13.6644 12.7941 13.2837 12.9572 12.8852 13.048V14.1205C12.8852 14.5338 12.5501 14.8688 12.1369 14.8688C11.7236 14.8688 11.3886 14.5338 11.3886 14.1205V12.3839C11.3886 12.1854 11.4674 11.9951 11.6077 11.8548C11.7481 11.7144 11.9384 11.6356 12.1369 11.6356C12.5069 11.6356 12.8686 11.5259 13.1762 11.3203C13.4838 11.1148 13.7236 10.8226 13.8652 10.4808C14.0068 10.1389 14.0439 9.76278 13.9717 9.3999C13.8995 9.03701 13.7213 8.70367 13.4597 8.44204C13.1981 8.18041 12.8647 8.00224 12.5018 7.93006C12.139 7.85788 11.7628 7.89492 11.421 8.03651C11.0791 8.17811 10.787 8.41789 10.5814 8.72553C10.3758 9.03317 10.2661 9.39486 10.2661 9.76486C10.2661 10.1781 9.9311 10.5132 9.51783 10.5132C9.10456 10.5132 8.76953 10.1781 8.76953 9.76486C8.76953 9.09886 8.96702 8.44782 9.33703 7.89406C9.70704 7.34031 10.2329 6.90871 10.8482 6.65384Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgQuestion);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "920954536fa3d8b341989e0b763aee10.svg");

/***/ }),

/***/ 5270:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PopupSection-module__Root--a7VC6{background-color:var(--theme-color-bg-4)}.PopupSection-module__Root--a7VC6.PopupSection-module__has-bottom-border--TuDLA{border-bottom:1px solid var(--theme-color-bg-4)}.PopupSection-module__Header--R7qUu{padding:8px 10px;background-color:var(--theme-color-bg-3)}.PopupSection-module__Content--CmQVq{padding:10px;display:flex;flex-direction:column}.PopupSection-module__Content--CmQVq.PopupSection-module__has-y-padding--C4j4g{padding-top:65px;padding-bottom:65px}.PopupSection-module__Content--CmQVq.PopupSection-module__is-centering-children--ix8QP{align-items:center}.PopupSection-module__Title--fS5uE{color:var(--theme-color-fg-default-shy);font-size:11px;text-transform:uppercase;margin:0;padding:0;font-family:var(--font-family);font-weight:var(--font-weight-semibold)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/popups/PopupSection/PopupSection.module.scss"],"names":[],"mappings":"AAAA,kCACE,wCAAA,CAEA,gFACE,+CAAA,CAIJ,oCACE,gBAAA,CACA,wCAAA,CAGF,qCACE,YAAA,CACA,YAAA,CACA,qBAAA,CAEA,+EACE,gBAAA,CACA,mBAAA,CAGF,uFACE,kBAAA,CAIJ,mCACE,uCAAA,CACA,cAAA,CACA,wBAAA,CACA,QAAA,CACA,SAAA,CACA,8BAAA,CACA,uCAAA","sourcesContent":[".Root {\n  background-color: var(--theme-color-bg-4);\n\n  &.has-bottom-border {\n    border-bottom: 1px solid var(--theme-color-bg-4);\n  }\n}\n\n.Header {\n  padding: 8px 10px;\n  background-color: var(--theme-color-bg-3);\n}\n\n.Content {\n  padding: 10px;\n  display: flex;\n  flex-direction: column;\n\n  &.has-y-padding {\n    padding-top: 65px;\n    padding-bottom: 65px;\n  }\n\n  &.is-centering-children {\n    align-items: center;\n  }\n}\n\n.Title {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 11px;\n  text-transform: uppercase;\n  margin: 0;\n  padding: 0;\n  font-family: var(--font-family);\n  font-weight: var(--font-weight-semibold);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PopupSection-module__Root--a7VC6`,
	"has-bottom-border": `PopupSection-module__has-bottom-border--TuDLA`,
	"Header": `PopupSection-module__Header--R7qUu`,
	"Content": `PopupSection-module__Content--CmQVq`,
	"has-y-padding": `PopupSection-module__has-y-padding--C4j4g`,
	"is-centering-children": `PopupSection-module__is-centering-children--ix8QP`,
	"Title": `PopupSection-module__Title--fS5uE`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 5376:
/***/ ((module) => {

// Module
var code = "<div> <div class=\"property-group\" data-template=\"group\"> <div style=\"display:inline-flex\" data-click=\"onGroupClicked\"> <div class=\"property-group-label\" style=\"height:30px;position:relative;flex-shrink:1\"> <label style=\"margin-left:10px;line-height:30px\" data-text=\"name\"></label> </div> </div> <div class=\"properties\" data-class=\"!isExpanded:hidden\" style=\"padding-bottom:10px\"> </div> </div> <div class=\"property-tab\" data-template=\"tab-group-tab\" data-click=\"onTabClicked\"> <div class=\"property-tab-icon\"></div> </div> <div class=\"property-tab-group\" data-template=\"tab-group\"> <div style=\"display:flex;flex-direction:row;justify-content:flex-end;align-items:center;margin-bottom:4px;margin-right:6px\" class=\"tabs\"> </div> <div class=\"properties\"> </div> </div> <div class=\"property-popout-group\" data-template=\"popout-group\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"label\"></label> <div class=\"property-value\"> <button type=\"button\" data-identifier=\"\" style=\"width:100%;height:100%\" class=\"property-codeeditor-button\" data-click=\"onPopoutClicked\">Edit</button> </div> </div> <div data-template=\"variable-type\" style=\"height:35px;position:relative\"> <div class=\"property-view\" style=\"position:absolute;width:100%;height:100%\"> </div> <div class=\"sidebar-panel-dark-input property-number-units\" style=\"position:absolute;left:25px;width:33px;top:1px;bottom:1px;padding:0\" data-click=\"onTypeDropDownClicked\" tabindex=\"1\"> <span data-class=\"isFocused:property-input-focused,isDefault:property-input-default\" style=\"line-height:35px\" data-text=\"propertyType\"></span> <div style=\"position:absolute;top:35px;left:0;width:100%;display:none\" class=\"property-input-dropdown\" style=\"display:none\"> </div> </div> </div> <div data-template=\"number\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-value\"> <input type=\"string\" data-identifier=\"\" class=\"sidebar-panel-dark-input\" style=\"position:absolute;width:100%;height:100%\" data-class=\"isConnected:property-input-connected,isFocused:property-input-focused,isDefault:property-input-default\" data-val=\"value\" data-change=\"onPropertyChanged\"> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"number-units\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-value\" style=\"right:45px\"> <input type=\"string\" class=\"sidebar-panel-dark-input\" style=\"position:absolute;width:100%;height:100%\" data-class=\"isConnected:property-input-connected,isFocused:property-input-focused,isDefault:property-input-default\" data-val=\"value\" data-change=\"onPropertyChanged\"> </div> <div class=\"sidebar-panel-dark-input property-number-units\" style=\"position:absolute;right:10px;width:33px;top:1px;bottom:1px;padding:0\" data-click=\"onDropDownClicked\" tabindex=\"1\"> <span data-class=\"isFocused:property-input-focused,isDefault:property-input-default\" style=\"line-height:35px\" data-text=\"unit\"></span> <div style=\"position:absolute;top:35px;left:0;width:100%;display:none\" class=\"property-input-dropdown\" style=\"display:none\"> </div> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"dimension\" style=\"height:35px;position:relative;display:flex;padding-right:10px;padding-top:1px;padding-bottom:1px\"> <div style=\"display:flex;flex:10000 0 80px;max-width:150px;margin-right:10px\"> <label class=\"property-label\" style=\"width:auto;position:relative;flex-grow:1;padding:0\" data-text=\"displayName\" data-tooltip=\"path:tooltip.dimension\"></label> </div> <div class=\"property-value\" style=\"position:relative;left:unset;right:unset;top:unset;bottom:unset;flex:1;min-width:45px\"> <input type=\"string\" class=\"sidebar-panel-dark-input\" style=\"width:100%;height:100%\" data-class=\"isConnected:property-input-connected,isFocused:property-input-focused,isDefault:property-input-default\" data-val=\"value\" data-change=\"onPropertyChanged\"> </div> <div class=\"sidebar-panel-dark-input property-number-units\" style=\"position:relative;width:33px;margin-left:1px;padding:0;flex-shrink:0\" data-click=\"onDropDownClicked\" tabindex=\"1\"> <span data-class=\"isFocused:property-input-focused,isDefault:property-input-default\" style=\"line-height:35px\" data-text=\"unit\"></span> <div style=\"position:absolute;top:35px;left:0;width:100%;display:none\" class=\"property-input-dropdown\" style=\"display:none\"> </div> </div> <div style=\"display:flex;flex:0 0 auto\" data-class=\"!isPercent:property-dimension-fixed-disabled\"> <label class=\"property-label\" style=\"position:relative;width:auto;margin-left:10px\" data-tooltip=\"path:tooltip.fixed\">Fixed</label> <div class=\"sidebar-panel-dark-input property-value\" style=\"width:33px;position:relative;left:unset;right:unset;top:unset;bottom:unset\" data-click=\"onBoxClicked\"> <i class=\"fa fa-check\" data-class=\"!isFixed:hidden\" style=\"position:absolute;left:10px;top:10px\"></i> </div> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"string\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-value\"> <input type=\"string\" data-identifier=\"\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"isDefault:property-input-default,isConnected:property-input-connected\" data-val=\"value\" data-change=\"onPropertyChanged\"> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"sizemode\" style=\"height:50px;position:relative;display:flex;justify-content:center\"> <div style=\"display:flex;position:relative;top:2px\"> <div class=\"size-icon\" data-tooltip=\"path:tooltip.explicit\" data-value=\"explicit\"> <div class=\"resizing-border\" style=\"width:30px;height:30px;position:relative\"> <div class=\"resizing-top resizing-bottom resizing-vline\" style=\"position:absolute;top:2px;left:10px;width:10px;height:22px\"></div> <div class=\"resizing-left resizing-right resizing-hline\" style=\"position:absolute;top:10px;left:2px;width:22px;height:10px\"></div> </div> </div> <div class=\"size-icon\" data-tooltip=\"path:tooltip.contentHeight\" data-value=\"contentHeight\"> <div class=\"resizing-border\" style=\"width:30px;height:30px;position:relative\"> <div class=\"resizing-left resizing-right resizing-hline\" style=\"position:absolute;top:10px;left:2px;width:22px;height:10px\"></div> </div> </div> <div class=\"size-icon\" data-tooltip=\"path:tooltip.contentWidth\" data-value=\"contentWidth\"> <div class=\"resizing-border\" style=\"width:30px;height:30px;position:relative\"> <div class=\"resizing-top resizing-bottom resizing-vline\" style=\"position:absolute;top:2px;left:10px;width:10px;height:22px\"></div> </div> </div> <div class=\"size-icon\" data-tooltip=\"path:tooltip.contentSize\" data-value=\"contentSize\"> <div class=\"resizing-border\" style=\"width:30px;height:30px;position:relative\"> </div> </div> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\" style=\"top:12px\"></span> </div> <div data-template=\"enum\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"sidebar-panel-dark-input property-value\" data-click=\"onDropDownClicked\"> <div style=\"position:absolute;left:0;right:0;top:0;bottom:0\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"isDefault:property-input-default,isConnected:property-input-connected\" data-val=\"value\" readonly=\"readonly\"> </div> <i class=\"property-input-dropdown-arrow fa fa-caret-down\" style=\"position:absolute;right:10px;top:10px\"></i> <div style=\"position:absolute;top:35px;left:0;width:100%;display:none\" class=\"property-input-dropdown\" style=\"display:none\"> </div> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"boolean\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"sidebar-panel-dark-input property-value\" style=\"width:33px\" data-class=\"isConnected:property-input-connected\" data-click=\"onBoxClicked\"> <i class=\"fa fa-check\" data-class=\"!value:hidden,isDefault:property-input-default\" style=\"position:absolute;left:10px;top:10px\"></i> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"image\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-value\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"isDefault:property-input-default,isConnected:property-input-connected\" data-val=\"value\" data-change=\"onPropertyChanged\"> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"icon\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-value\" style=\"right:45px\"> <div class=\"sidebar-panel-dark-input\" style=\"position:relative;height:32px;width:33px;top:1px;bottom:1px;padding:0;display:flex;align-items:center;justify-content:center\" data-click=\"onLaunchClicked\"> <span id=\"iconThumbnail\" style=\"color:#fff;font-size:20px;display:inline-block\"></span> </div> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"font\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-value\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"isDefault:property-input-default,isConnected:property-input-connected\" data-val=\"value\" data-change=\"onPropertyChanged\"> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"textStyle\" style=\"height:35px;position:relative;margin-bottom:10px\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-value\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"isDefault:property-input-default,isConnected:property-input-connected\" data-val=\"value\" data-change=\"onPropertyChanged\"> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"component\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-value\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"isDefault:property-input-default,isConnected:property-input-connected\" data-val=\"value\" data-change=\"onPropertyChanged\"> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"identifier\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-value\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"isDefault:property-input-default,isConnected:property-input-connected\" data-val=\"value\" data-change=\"onPropertyChanged\"> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"source\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-value\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"isDefault:property-input-default,isConnected:property-input-connected\" data-val=\"value\" data-change=\"onPropertyChanged\"> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"vec2\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\"></label> <div class=\"property-value\" style=\"right:0;top:0;height:35px\"> <div style=\"position:absolute;width:50%;height:100%;left:0\"> <label style=\"position:absolute;left:0;width:10px\" class=\"property-label\" data-text=\"comps.0.displayName\"></label> <div style=\"position:absolute;left:20px;right:5px;top:1px;bottom:1px\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"comps.0.isConnected:property-input-connected,comps.0.isDefault:property-input-default\" data-veccomp=\"0\" data-val=\"comps.0.value\" data-change=\"onPropertyChanged\"> </div> </div> <div style=\"position:absolute;width:50%;height:100%;left:50%\"> <label style=\"position:absolute;left:0;width:10px\" class=\"property-label\" data-text=\"comps.1.displayName\"></label> <div style=\"position:absolute;left:20px;right:10px;top:1px;bottom:1px\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"comps.1.isConnected:property-input-connected,comps.1.isDefault:property-input-default\" data-veccomp=\"1\" data-val=\"comps.1.value\" data-change=\"onPropertyChanged\"> </div> </div> </div> </div> <div data-template=\"vec3\" style=\"height:70px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\"></label> <div class=\"property-value\" style=\"right:0;top:0;height:35px\"> <div style=\"position:absolute;width:50%;height:100%;left:0\"> <label style=\"position:absolute;left:0;width:10px\" class=\"property-label\" data-text=\"comps.0.displayName\"></label> <div style=\"position:absolute;left:20px;right:5px;top:1px;bottom:1px\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"comps.0.isConnected:property-input-connected,comps.0.isDefault:property-input-default\" data-veccomp=\"0\" data-val=\"comps.0.value\" data-change=\"onPropertyChanged\"> </div> </div> <div style=\"position:absolute;width:50%;height:100%;left:50%\"> <label style=\"position:absolute;left:0;width:10px\" class=\"property-label\" data-text=\"comps.1.displayName\"></label> <div style=\"position:absolute;left:20px;right:10px;top:1px;bottom:1px\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"comps.1.isConnected:property-input-connected,comps.1.isDefault:property-input-default\" data-veccomp=\"1\" data-val=\"comps.1.value\" data-change=\"onPropertyChanged\"> </div> </div> </div> <div class=\"property-value\" style=\"right:0;bottom:0;top:35px\"> <div style=\"position:absolute;width:50%;height:100%;left:0\"> <label style=\"position:absolute;left:0;width:10px\" class=\"property-label\" data-text=\"comps.2.displayName\"></label> <div style=\"position:absolute;left:20px;right:5px;top:1px;bottom:1px\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"comps.2.isConnected:property-input-connected,comps.2.isDefault:property-input-default\" data-veccomp=\"2\" data-val=\"comps.2.value\" data-change=\"onPropertyChanged\"> </div> </div> </div> </div> <div data-template=\"vec4\" style=\"height:70px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\"></label> <div class=\"property-value\" style=\"right:0;top:0;height:35px\"> <div style=\"position:absolute;width:50%;height:100%;left:0\"> <label style=\"position:absolute;left:0;width:10px\" class=\"property-label\" data-text=\"comps.0.displayName\"></label> <div style=\"position:absolute;left:20px;right:5px;top:1px;bottom:1px\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"comps.0.isConnected:property-input-connected,comps.0.isDefault:property-input-default\" data-veccomp=\"0\" data-val=\"comps.0.value\" data-change=\"onPropertyChanged\"> </div> </div> <div style=\"position:absolute;width:50%;height:100%;left:50%\"> <label style=\"position:absolute;left:0;width:10px\" class=\"property-label\" data-text=\"comps.1.displayName\"></label> <div style=\"position:absolute;left:20px;right:10px;top:1px;bottom:1px\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"comps.1.isConnected:property-input-connected,comps.1.isDefault:property-input-default\" data-veccomp=\"1\" data-val=\"comps.1.value\" data-change=\"onPropertyChanged\"> </div> </div> </div> <div class=\"property-value\" style=\"right:0;bottom:0;top:35px\"> <div style=\"position:absolute;width:50%;height:100%;left:0\"> <label style=\"position:absolute;left:0;width:10px\" class=\"property-label\" data-text=\"comps.2.displayName\"></label> <div style=\"position:absolute;left:20px;right:5px;top:1px;bottom:1px\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"comps.2.isConnected:property-input-connected,comps.2.isDefault:property-input-default\" data-veccomp=\"2\" data-val=\"comps.2.value\" data-change=\"onPropertyChanged\"> </div> </div> <div style=\"position:absolute;width:50%;height:100%;left:50%\"> <label style=\"position:absolute;left:0;width:10px\" class=\"property-label\" data-text=\"comps.3.displayName\"></label> <div style=\"position:absolute;left:20px;right:10px;top:1px;bottom:1px\"> <input type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"comps.3.isConnected:property-input-connected,comps.3.isDefault:property-input-default\" data-veccomp=\"3\" data-val=\"comps.3.value\" data-change=\"onPropertyChanged\"> </div> </div> </div> </div> <div data-template=\"color\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-value\" style=\"right:45px\"> <input id=\"stringInput\" data-identifier=\"\" data-type=\"color\" type=\"string\" style=\"position:absolute;width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-class=\"isConnected:property-input-connected,isFocused:property-input-focused,isDefault:property-input-default\" data-val=\"value\" data-change=\"onStringInputChanged\"> </div> <div class=\"color-thumbnail\" style=\"position:absolute;right:10px;top:1px;bottom:1px;padding:0\" data-click=\"onLaunchClicked\"> <div class=\"color-thumbnail-content\"></div> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"textarea\" style=\"position:relative;display:flex\"> <label class=\"property-label\" data-text=\"displayName\" style=\"position:relative;flex-grow:0\" data-tooltip=\"path:tooltip\"></label> <div class=\"property-input-textarea-bg\" style=\"\"> <textarea style=\"width:100%\" data-identifier=\"\" class=\"sidebar-panel-dark-input property-input-textarea\" data-class=\"isConnected:property-input-connected,isFocused:property-input-focused,isDefault:property-input-default\" data-val=\"value\" data-change=\"onPropertyChanged\"></textarea> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"curve\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\"></label> <div class=\"property-value\"> <button type=\"button\" data-interaction=\"\" data-identifier=\"\" style=\"width:100%;height:100%\" class=\"property-codeeditor-button\" data-click=\"onEditClicked\">Edit</button> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"query\" style=\"height:35px;position:relative\"> <label class=\"property-label\" data-text=\"displayName\"></label> <div class=\"property-value\"> <button type=\"button\" style=\"width:100%;height:100%\" data-identifier=\"\" class=\"property-codeeditor-button\" data-click=\"onEditClicked\">Edit</button> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div> <div data-template=\"proplist\" style=\"position:relative\"> <div class=\"props\"></div> </div> <div class=\"groups\"> </div> </div> ";
// Exports
module.exports = code;

/***/ }),

/***/ 5435:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @file Blockly core module wrapper for node.js.  This module loads
 * blockly_compressed.js and jsdom, then calls
 * Blockly.utils.xml.injectDependencies to supply needed XML-handling
 * functions to Blocky.
 *
 * Note that, unlike index.js, this file does not get a UMD wrapper.
 * This is because it is only used in node.js environments and so is
 * guaranteed to be loaded as a CJS module.
 */

/* eslint-disable */


const Blockly = __webpack_require__(15811);
const {JSDOM} = __webpack_require__(7987);

// Override textToDomDocument and provide node.js alternatives to
// DOMParser and XMLSerializer.
if (typeof globalThis.document !== 'object') {
  const {window} = new JSDOM(`<!DOCTYPE html>`);
  Blockly.utils.xml.injectDependencies(window);
}

module.exports = Blockly;


/***/ }),

/***/ 5576:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   W: () => (/* binding */ GitHubOAuthService)
/* harmony export */ });
/* harmony import */ var electron__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(91288);
/* harmony import */ var electron__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(electron__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11138);
/**
 * GitHubOAuthService
 *
 * Manages GitHub OAuth authentication via IPC with the main process.
 * The main process handles the OAuth flow and protocol callbacks,
 * this service coordinates with it and manages state in the renderer.
 *
 * @module noodl-editor/services
 */


/**
 * Service for managing GitHub OAuth authentication
 *
 * This service coordinates with the main process which handles:
 * - State generation and validation
 * - Protocol callback handling (noodl://github-callback)
 * - Token exchange with GitHub
 *
 * The renderer process handles:
 * - Opening the auth URL in the browser
 * - Storing tokens securely
 * - Managing user state
 */
class GitHubOAuthService extends _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_1__.EventDispatcher {
    constructor() {
        super();
        this.currentUser = null;
        this.accessToken = null;
        this.isAuthenticating = false;
        console.log('🔧 [GitHubOAuthService] Constructor called - setting up IPC listeners');
        this.setupIPCListeners();
    }
    static get instance() {
        if (!GitHubOAuthService._instance) {
            GitHubOAuthService._instance = new GitHubOAuthService();
        }
        return GitHubOAuthService._instance;
    }
    /**
     * Set up IPC listeners for OAuth callbacks from main process
     */
    setupIPCListeners() {
        console.log('🔌 [GitHubOAuthService] Setting up IPC listeners for github-oauth-complete and github-oauth-error');
        // Listen for successful OAuth completion
        electron__WEBPACK_IMPORTED_MODULE_0__.ipcRenderer.on('github-oauth-complete', (_event, result) => {
            console.log('✅ [GitHubOAuthService] IPC RECEIVED: github-oauth-complete');
            console.log('✅ [GitHubOAuthService] Result:', result);
            this.handleOAuthComplete(result);
        });
        // Listen for OAuth errors
        electron__WEBPACK_IMPORTED_MODULE_0__.ipcRenderer.on('github-oauth-error', (_event, error) => {
            console.error('❌ [GitHubOAuthService] IPC RECEIVED: github-oauth-error');
            console.error('❌ [GitHubOAuthService] Error:', error);
            this.handleOAuthError(error);
        });
        console.log('✅ [GitHubOAuthService] IPC listeners registered');
    }
    /**
     * Handle successful OAuth completion from main process
     */
    async handleOAuthComplete(result) {
        try {
            console.log('🔄 [GitHub OAuth] Processing OAuth result for user:', result.user.login);
            // Store the token
            this.accessToken = result.token.access_token;
            this.currentUser = result.user;
            // Persist token securely
            await this.saveToken(result.token.access_token);
            console.log('✅ [GitHub OAuth] Authentication successful');
            // Notify listeners
            this.isAuthenticating = false;
            this.notifyListeners('oauth-success', { user: this.currentUser });
            this.notifyListeners('auth-state-changed', { authenticated: true });
        }
        catch (error) {
            console.error('❌ [GitHub OAuth] Failed to process OAuth result:', error);
            this.handleOAuthError({
                error: 'processing_failed',
                message: error instanceof Error ? error.message : 'Failed to process OAuth result'
            });
        }
    }
    /**
     * Handle OAuth error from main process
     */
    handleOAuthError(error) {
        console.error('❌ [GitHub OAuth] OAuth error:', error.error, error.message);
        this.isAuthenticating = false;
        this.notifyListeners('oauth-error', { error: error.message });
    }
    /**
     * Initiate OAuth flow by requesting auth URL from main process
     * and opening it in the system browser
     */
    async initiateOAuth() {
        if (this.isAuthenticating) {
            console.warn('[GitHub OAuth] OAuth flow already in progress');
            return;
        }
        console.log('🔐 [GitHub OAuth] Initiating OAuth flow');
        this.isAuthenticating = true;
        try {
            // Request auth URL from main process
            // Main process generates the state and stores it for validation
            const result = await electron__WEBPACK_IMPORTED_MODULE_0__.ipcRenderer.invoke('github-oauth-start');
            if (!result.success) {
                throw new Error(result.error || 'Failed to start OAuth flow');
            }
            console.log('🌐 [GitHub OAuth] Opening auth URL in browser');
            // Open the auth URL in the system browser
            await electron__WEBPACK_IMPORTED_MODULE_0__.shell.openExternal(result.authUrl);
            // Notify listeners that OAuth flow started
            this.notifyListeners('oauth-started');
            // The main process will handle the callback and send us the result
            // via 'github-oauth-complete' or 'github-oauth-error' IPC events
        }
        catch (error) {
            console.error('❌ [GitHub OAuth] Failed to initiate OAuth:', error);
            this.isAuthenticating = false;
            this.notifyListeners('oauth-error', {
                error: error instanceof Error ? error.message : 'Failed to start OAuth'
            });
            throw error;
        }
    }
    /**
     * Cancel any pending OAuth flow
     */
    async cancelOAuth() {
        if (this.isAuthenticating) {
            console.log('🚫 [GitHub OAuth] Cancelling OAuth flow');
            await electron__WEBPACK_IMPORTED_MODULE_0__.ipcRenderer.invoke('github-oauth-stop');
            this.isAuthenticating = false;
            this.notifyListeners('oauth-cancelled');
        }
    }
    /**
     * Get organizations for current user
     */
    async getOrganizations() {
        if (!this.accessToken) {
            throw new Error('Not authenticated');
        }
        const response = await fetch('https://api.github.com/user/orgs', {
            headers: {
                Authorization: `Bearer ${this.accessToken}`,
                Accept: 'application/vnd.github.v3+json'
            }
        });
        if (!response.ok) {
            throw new Error(`Failed to fetch organizations: ${response.status}`);
        }
        return await response.json();
    }
    /**
     * Get current access token
     */
    async getToken() {
        if (!this.accessToken) {
            // Try to load from storage
            await this.loadToken();
        }
        return this.accessToken;
    }
    /**
     * Get current authenticated user
     */
    getCurrentUser() {
        return this.currentUser;
    }
    /**
     * Check if user is authenticated
     */
    isAuthenticated() {
        return this.accessToken !== null && this.currentUser !== null;
    }
    /**
     * Check if OAuth flow is in progress
     */
    isOAuthInProgress() {
        return this.isAuthenticating;
    }
    /**
     * Revoke token and disconnect
     */
    async disconnect() {
        console.log('🔌 [GitHub OAuth] Disconnecting GitHub account');
        this.accessToken = null;
        this.currentUser = null;
        // Clear stored token
        await this.clearToken();
        // Notify listeners
        this.notifyListeners('auth-state-changed', { authenticated: false });
        this.notifyListeners('disconnected');
    }
    /**
     * Save token securely using Electron's safeStorage via IPC
     */
    async saveToken(token) {
        try {
            await electron__WEBPACK_IMPORTED_MODULE_0__.ipcRenderer.invoke('github-save-token', token);
            console.log('💾 [GitHub OAuth] Token saved');
        }
        catch (error) {
            console.error('❌ [GitHub OAuth] Failed to save token:', error);
            // Token is still in memory, just not persisted
        }
    }
    /**
     * Load token from secure storage
     */
    async loadToken() {
        var _a;
        try {
            const token = await electron__WEBPACK_IMPORTED_MODULE_0__.ipcRenderer.invoke('github-load-token');
            if (token) {
                console.log('🔑 [GitHub OAuth] Token loaded from storage, verifying...');
                this.accessToken = token;
                // Fetch user info to verify token is still valid
                await this.fetchCurrentUser();
                this.notifyListeners('auth-state-changed', { authenticated: true });
                console.log('✅ [GitHub OAuth] Token verified, user:', (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.login);
            }
        }
        catch (error) {
            console.error('❌ [GitHub OAuth] Failed to load/verify token:', error);
            // Token may be invalid, clear it
            this.accessToken = null;
            this.currentUser = null;
            await this.clearToken();
        }
    }
    /**
     * Fetch current user information from GitHub API
     */
    async fetchCurrentUser() {
        if (!this.accessToken) {
            throw new Error('No access token available');
        }
        const response = await fetch('https://api.github.com/user', {
            headers: {
                Authorization: `Bearer ${this.accessToken}`,
                Accept: 'application/vnd.github.v3+json'
            }
        });
        if (!response.ok) {
            throw new Error(`Failed to fetch user info: ${response.status}`);
        }
        this.currentUser = await response.json();
    }
    /**
     * Clear stored token
     */
    async clearToken() {
        try {
            await electron__WEBPACK_IMPORTED_MODULE_0__.ipcRenderer.invoke('github-clear-token');
        }
        catch (error) {
            console.error('❌ [GitHub OAuth] Failed to clear token:', error);
        }
    }
    /**
     * Initialize service and restore session if available
     */
    async initialize() {
        console.log('🔧 [GitHub OAuth] Initializing GitHubOAuthService');
        await this.loadToken();
    }
}


/***/ }),

/***/ 5604:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   F: () => (/* binding */ RouterAdapter)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(93015);
/* harmony import */ var _componentmodel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16163);
/* harmony import */ var _nodegraphmodel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(87844);
/* harmony import */ var _projectmodel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6203);
/* harmony import */ var _NodeTypeAdapter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(35715);





class RouterAdapter extends _NodeTypeAdapter__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .A {
    constructor() {
        super('Router');
        this.events = {
            componentRemoved: this.componentRemoved.bind(this),
            componentRenamed: this.componentRenamed.bind(this),
            componentDuplicated: this.componentDuplicated.bind(this),
            projectLoaded: this.evaluateRoutersHelath.bind(this),
            'nodeAdded:Router': this.evaluateRoutersHelath.bind(this),
            'parametersChanged:Router': this.parametersChanged.bind(this)
        };
    }
    componentRemoved(e) {
        const componentName = e.model.fullName;
        const routers = this.findAllNodes();
        routers.forEach((r) => {
            const pages = r.parameters['pages'];
            if (pages !== undefined && pages.routes !== undefined) {
                const idx = pages.routes.indexOf(componentName);
                if (idx !== -1) {
                    const _pages = JSON.parse(JSON.stringify(pages));
                    _pages.routes.splice(idx, 1);
                    if (_pages.startPage === componentName)
                        _pages.startPage = undefined;
                    r.setParameter('pages', _pages, { undo: e.undo });
                }
            }
        });
    }
    componentRenamed(e) {
        const before = e.oldName;
        const after = e.model.fullName;
        // Note: No need to handle undo here as it will simply revert back to a new renamne
        // Find all routers that have this component in it's routes and rename
        const routers = this.findAllNodes();
        routers.forEach((r) => {
            const pages = r.parameters['pages'];
            if (pages !== undefined && pages.routes !== undefined) {
                const idx = pages.routes.indexOf(before);
                if (idx !== -1) {
                    const _pages = JSON.parse(JSON.stringify(pages));
                    _pages.routes[idx] = after;
                    if (_pages.startPage === before)
                        _pages.startPage = after;
                    r.setParameter('pages', _pages);
                }
            }
        });
    }
    componentDuplicated(e) {
        // Is the duplicate a page
        const pages = e.duplicate.getNodesWithType('Page');
        if (pages !== undefined && pages.length > 0) {
            // Find all routers that have the original page and
            // add the duplicate to them
            const source = e.source.fullName;
            const duplicate = e.duplicate.fullName;
            const routers = this.findAllNodes();
            routers.forEach((r) => {
                const pages = r.parameters['pages'];
                if (pages !== undefined && pages.routes !== undefined) {
                    const idx = pages.routes.indexOf(source);
                    if (idx !== -1) {
                        const _pages = JSON.parse(JSON.stringify(pages));
                        _pages.routes.push(duplicate);
                        r.setParameter('pages', _pages, { undo: e.undo });
                    }
                }
            });
        }
    }
    evaluateRoutersHelath() {
        const routers = this.findAllNodes();
        // Check routers for name, and assign them one if they don't have one
        routers.forEach((r) => {
            if (r.parameters['name'] === undefined || r.parameters['name'] === '') {
                const routerNames = routers.map((r) => r.parameters.name);
                let name;
                //Check if the name "Main" is free
                if (routerNames.includes('Main') === false) {
                    name = 'Main';
                }
                else {
                    //Assign a name like "Router X"
                    let i = 0;
                    do {
                        name = 'Router ' + i;
                        i++;
                    } while (routerNames.includes(name));
                }
                r.setParameter('name', name);
            }
        });
    }
    parametersChanged(e) {
        const node = e.model;
        if (e.args.name === 'pages') {
            const pages = node.parameters['pages'];
            if (pages !== undefined) {
                if (pages.startPage === undefined) {
                    e.args.undo !== undefined &&
                        e.args.undo.pushAndDo({
                            do: () => {
                                pages.startPage = pages.routes[0];
                            },
                            undo: () => {
                                pages.startPage = undefined;
                            }
                        });
                }
            }
        }
        this.evaluateRoutersHelath();
    }
    static getPageInfoForComponents(components) {
        const pageInfo = [];
        components.forEach((c) => {
            const _c = _projectmodel__WEBPACK_IMPORTED_MODULE_3__.ProjectModel.instance.getComponentWithName(c);
            if (_c === undefined)
                return;
            const pages = _c.getNodesWithType('Page');
            if (pages === undefined || pages.length === 0)
                return;
            const page = pages[0];
            let title = page.parameters['title'];
            if (title === undefined) {
                const titleParts = c.split('/');
                title = titleParts[titleParts.length - 1];
            }
            let urlPath = page.parameters['urlPath'] || title.replace(/\s+/g, '-').toLowerCase();
            const pageInputs = _c.getNodesWithType('PageInputs');
            const pathParams = [];
            pageInputs.forEach((pi) => {
                if (pi.parameters['pathParams'])
                    pi.parameters['pathParams'].split(',').forEach((p) => pathParams.indexOf(p) === -1 && pathParams.push(p));
            });
            pathParams.forEach((p) => {
                if (urlPath.indexOf('{' + p + '}') === -1)
                    urlPath = urlPath + '/{' + p + '}';
            });
            pageInfo.push({
                path: urlPath,
                title: title,
                component: c
            });
        });
        return pageInfo;
    }
    static addPageToRouters(routerName, pageName, args) {
        const routers = _projectmodel__WEBPACK_IMPORTED_MODULE_3__.ProjectModel.instance.getNodesWithType('Router');
        routers.forEach((r) => {
            if ((r.parameters['name'] || 'Main') === (routerName || 'Main')) {
                // Add this page to the router
                const pages = JSON.parse(JSON.stringify(r.getParameter('pages') || {}));
                if (pages.routes === undefined)
                    pages.routes = [];
                pages.routes.push(pageName);
                r.setParameter('pages', pages, { undo: args.undo });
            }
        });
    }
    static getRouterNames() {
        const routers = _projectmodel__WEBPACK_IMPORTED_MODULE_3__.ProjectModel.instance.getNodesWithType('Router');
        const _routers = [];
        routers.forEach((r) => {
            if (_routers.indexOf(r.parameters['name'] || 'Main') === -1)
                _routers.push(r.parameters['name'] || 'Main');
        });
        return _routers;
    }
    static getPageComponents() {
        const pages = _projectmodel__WEBPACK_IMPORTED_MODULE_3__.ProjectModel.instance.getNodesWithType('Page');
        return pages.map((p) => p.owner.owner.name);
    }
    static createPageComponent(componentName) {
        const component = new _componentmodel__WEBPACK_IMPORTED_MODULE_1__/* .ComponentModel */ .j({
            name: componentName,
            graph: _nodegraphmodel__WEBPACK_IMPORTED_MODULE_2__/* .NodeGraphModel */ .W2.fromJSON(JSON.parse(JSON.stringify(_pageTemplate))),
            id: _utils_utils__WEBPACK_IMPORTED_MODULE_0__["default"].guid()
        });
        component.rekeyAllIds();
        return component;
    }
}
const _pageTemplate = {
    connections: [],
    roots: [
        {
            id: 'xxx',
            type: 'Page',
            x: 0,
            y: 0,
            parameters: {},
            ports: [],
            dynamicports: [],
            children: []
        },
        {
            id: 'yyy',
            type: 'PageInputs',
            x: -100,
            y: -50,
            parameters: {},
            ports: [],
            dynamicports: [],
            children: []
        }
    ]
};


/***/ }),

/***/ 5731:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.GitHubPanel-module__GitHubPanel--CIcbU{display:flex;flex-direction:column;height:100%;background-color:var(--theme-color-bg-2)}.GitHubPanel-module__Header--GUnHu{display:flex;flex-direction:column;border-bottom:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-2)}.GitHubPanel-module__Tabs--IZu2N{display:flex;gap:0;padding:0 12px}.GitHubPanel-module__Tab--mKxrc{padding:12px 16px;background:none;border:none;color:var(--theme-color-fg-default-shy);font-size:13px;font-weight:500;cursor:pointer;border-bottom:2px solid rgba(0,0,0,0);transition:all .2s ease}.GitHubPanel-module__Tab--mKxrc:hover{color:var(--theme-color-fg-default);background-color:var(--theme-color-bg-3)}.GitHubPanel-module__Tab--mKxrc.GitHubPanel-module__TabActive--Ka6sb{color:var(--theme-color-primary);border-bottom-color:var(--theme-color-primary)}.GitHubPanel-module__Content--zGwGd{flex:1;overflow:hidden;display:flex;flex-direction:column}.GitHubPanel-module__IssuesTab--VTFgp{display:flex;flex-direction:column;height:100%}.GitHubPanel-module__Filters--aygwL{padding:12px;border-bottom:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-2)}.GitHubPanel-module__SearchInput--CX96C{width:100%;padding:8px 12px;background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:4px;color:var(--theme-color-fg-default);font-size:13px}.GitHubPanel-module__SearchInput--CX96C::placeholder{color:var(--theme-color-fg-default-shy)}.GitHubPanel-module__SearchInput--CX96C:focus{outline:none;border-color:var(--theme-color-primary)}.GitHubPanel-module__IssuesList--CMm0m{flex:1;overflow-y:auto;padding:8px}.GitHubPanel-module__EmptyState--yNeZc{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:48px 24px;text-align:center;color:var(--theme-color-fg-default-shy)}.GitHubPanel-module__EmptyState--yNeZc h3{margin:12px 0 8px;color:var(--theme-color-fg-default);font-size:16px;font-weight:600}.GitHubPanel-module__EmptyState--yNeZc p{margin:0 0 20px;font-size:13px;line-height:1.5}.GitHubPanel-module__EmptyStateIcon--NpzNY{font-size:48px;opacity:.5}.GitHubPanel-module__ConnectButton--kwVBi{padding:10px 20px;background-color:var(--theme-color-primary);color:#fff;border:none;border-radius:4px;font-size:13px;font-weight:500;cursor:pointer;transition:opacity .2s ease}.GitHubPanel-module__ConnectButton--kwVBi:hover{opacity:.9}.GitHubPanel-module__ConnectButton--kwVBi:active{opacity:.8}.GitHubPanel-module__ComingSoon--ZdMpP{display:flex;align-items:center;justify-content:center;padding:48px 24px;color:var(--theme-color-fg-default-shy);font-size:13px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/GitHubPanel/GitHubPanel.module.scss"],"names":[],"mappings":"AAKA,wCACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,wCAAA,CAGF,mCACE,YAAA,CACA,qBAAA,CACA,yDAAA,CACA,wCAAA,CAGF,iCACE,YAAA,CACA,KAAA,CACA,cAAA,CAGF,gCACE,iBAAA,CACA,eAAA,CACA,WAAA,CACA,uCAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,qCAAA,CACA,uBAAA,CAEA,sCACE,mCAAA,CACA,wCAAA,CAGF,qEACE,gCAAA,CACA,8CAAA,CAIJ,oCACE,MAAA,CACA,eAAA,CACA,YAAA,CACA,qBAAA,CAGF,sCACE,YAAA,CACA,qBAAA,CACA,WAAA,CAGF,oCACE,YAAA,CACA,yDAAA,CACA,wCAAA,CAGF,wCACE,UAAA,CACA,gBAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CAEA,qDACE,uCAAA,CAGF,8CACE,YAAA,CACA,uCAAA,CAIJ,uCACE,MAAA,CACA,eAAA,CACA,WAAA,CAGF,uCACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,iBAAA,CACA,uCAAA,CAEA,0CACE,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CAGF,yCACE,eAAA,CACA,cAAA,CACA,eAAA,CAIJ,2CACE,cAAA,CACA,UAAA,CAGF,0CACE,iBAAA,CACA,2CAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,2BAAA,CAEA,gDACE,UAAA,CAGF,iDACE,UAAA,CAIJ,uCACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,uCAAA,CACA,cAAA","sourcesContent":["/**\n * GitHubPanel styles\n * Uses design tokens for theming\n */\n\n.GitHubPanel {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  background-color: var(--theme-color-bg-2);\n}\n\n.Header {\n  display: flex;\n  flex-direction: column;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-2);\n}\n\n.Tabs {\n  display: flex;\n  gap: 0;\n  padding: 0 12px;\n}\n\n.Tab {\n  padding: 12px 16px;\n  background: none;\n  border: none;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 13px;\n  font-weight: 500;\n  cursor: pointer;\n  border-bottom: 2px solid transparent;\n  transition: all 0.2s ease;\n\n  &:hover {\n    color: var(--theme-color-fg-default);\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.TabActive {\n    color: var(--theme-color-primary);\n    border-bottom-color: var(--theme-color-primary);\n  }\n}\n\n.Content {\n  flex: 1;\n  overflow: hidden;\n  display: flex;\n  flex-direction: column;\n}\n\n.IssuesTab {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n}\n\n.Filters {\n  padding: 12px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-2);\n}\n\n.SearchInput {\n  width: 100%;\n  padding: 8px 12px;\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  color: var(--theme-color-fg-default);\n  font-size: 13px;\n\n  &::placeholder {\n    color: var(--theme-color-fg-default-shy);\n  }\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.IssuesList {\n  flex: 1;\n  overflow-y: auto;\n  padding: 8px;\n}\n\n.EmptyState {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  padding: 48px 24px;\n  text-align: center;\n  color: var(--theme-color-fg-default-shy);\n\n  h3 {\n    margin: 12px 0 8px;\n    color: var(--theme-color-fg-default);\n    font-size: 16px;\n    font-weight: 600;\n  }\n\n  p {\n    margin: 0 0 20px;\n    font-size: 13px;\n    line-height: 1.5;\n  }\n}\n\n.EmptyStateIcon {\n  font-size: 48px;\n  opacity: 0.5;\n}\n\n.ConnectButton {\n  padding: 10px 20px;\n  background-color: var(--theme-color-primary);\n  color: white;\n  border: none;\n  border-radius: 4px;\n  font-size: 13px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: opacity 0.2s ease;\n\n  &:hover {\n    opacity: 0.9;\n  }\n\n  &:active {\n    opacity: 0.8;\n  }\n}\n\n.ComingSoon {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  padding: 48px 24px;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 13px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"GitHubPanel": `GitHubPanel-module__GitHubPanel--CIcbU`,
	"Header": `GitHubPanel-module__Header--GUnHu`,
	"Tabs": `GitHubPanel-module__Tabs--IZu2N`,
	"Tab": `GitHubPanel-module__Tab--mKxrc`,
	"TabActive": `GitHubPanel-module__TabActive--Ka6sb`,
	"Content": `GitHubPanel-module__Content--zGwGd`,
	"IssuesTab": `GitHubPanel-module__IssuesTab--VTFgp`,
	"Filters": `GitHubPanel-module__Filters--aygwL`,
	"SearchInput": `GitHubPanel-module__SearchInput--CX96C`,
	"IssuesList": `GitHubPanel-module__IssuesList--CMm0m`,
	"EmptyState": `GitHubPanel-module__EmptyState--yNeZc`,
	"EmptyStateIcon": `GitHubPanel-module__EmptyStateIcon--NpzNY`,
	"ConnectButton": `GitHubPanel-module__ConnectButton--kwVBi`,
	"ComingSoon": `GitHubPanel-module__ComingSoon--ZdMpP`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 6014:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.CloudServiceCard-module__Root--lJM3w{position:relative;transition:background-color var(--speed-turbo) var(--easing-base);border:1px solid rgba(0,0,0,0);border-bottom:1px solid var(--theme-color-bg-1)}.CloudServiceCard-module__Root--lJM3w:hover:not(.CloudServiceCard-module__is-open--aEFxm){background-color:var(--theme-color-bg-3)}.CloudServiceCard-module__Root--lJM3w.CloudServiceCard-module__is-alerting--p6N5u{animation:CloudServiceCard-module__border-alert--_CRCz 3000ms var(--easing-base) both}.CloudServiceCard-module__Root--lJM3w:not(.CloudServiceCard-module__is-editor-environment--uXIDw){order:1}.CloudServiceCard-module__Root--lJM3w.CloudServiceCard-module__is-editor-environment--uXIDw{order:0}.CloudServiceCard-module__Inner--xNvdY{padding:8px 16px 14px}.CloudServiceCard-module__Inner--xNvdY:not(.CloudServiceCard-module__is-always-open--QxBD0){cursor:pointer}@keyframes CloudServiceCard-module__border-alert--_CRCz{15%,45%,75%{border-top:1px solid var(--theme-color-notice);border-bottom:1px solid var(--theme-color-notice);border-right:1px solid var(--theme-color-notice);border-left:1px solid var(--theme-color-notice)}0%,30%,60%,90%,100%{border-top:1px solid var(--theme-color-bg-2);border-bottom:1px solid var(--theme-color-bg-1);border-right:1px solid var(--theme-color-bg-2);border-left:1px solid var(--theme-color-bg-2)}}.CloudServiceCard-module__MetaBar--lLWLE{display:flex;align-items:center;justify-content:space-between;padding-bottom:8px}.CloudServiceCard-module__ToggleContainer--zAJWV{transform:translateX(8px)}.CloudServiceCard-module__TypeDisplay--D9kDQ{color:var(--theme-color-fg-muted);font-weight:var(--font-weight-semibold);font-size:10px;text-transform:uppercase;display:flex;align-items:center}.CloudServiceCard-module__TypeDisplay--D9kDQ path{fill:var(--theme-color-fg-muted)}.CloudServiceCard-module__ActiveIndicator--AJai8{display:inline-block;margin-left:5px;color:var(--theme-color-notice);text-transform:none}.CloudServiceCard-module__ArchivedDisplay--yAq_M,.CloudServiceCard-module__UsedInEditorDisplay--S4GuA{display:inline-block;margin-left:8px}.CloudServiceCard-module__ArchivedDisplay--yAq_M{color:var(--theme-color-danger)}.CloudServiceCard-module__UsedInEditorDisplay--S4GuA{color:var(--theme-color-success)}.CloudServiceCard-module__CloudIcon--ME3ud{margin-right:8px}.CloudServiceCard-module__Header--_XJ9P{display:flex;flex-direction:column}.CloudServiceCard-module__Drawer--AHCA3{padding:14px 16px 16px;display:flex;flex-direction:column}.CloudServiceCard-module__Drawer--AHCA3.CloudServiceCard-module__has-no-top-padding--NrErP{padding-top:0}.CloudServiceCard-module__AdjacentInputs--duxCi{margin-left:-16px;display:flex}.CloudServiceCard-module__AdjacentInputs--duxCi>*{margin-left:16px;width:50%}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/CloudServicePanel/CloudServiceCard/CloudServiceCard.module.scss"],"names":[],"mappings":"AAEA,sCACE,iBAAA,CACA,iEAAA,CACA,8BAAA,CACA,+CAAA,CAEA,0FACE,wCAAA,CAGF,kFACE,qFAAA,CAGF,kGACE,OAAA,CAEF,4FACE,OAAA,CAIJ,uCACE,qBAAA,CAEA,4FACE,cAAA,CAIJ,wDACE,YAGE,8CAAA,CACA,iDAAA,CACA,gDAAA,CACA,+CAAA,CAGF,oBAKE,4CAAA,CACA,+CAAA,CACA,8CAAA,CACA,6CAAA,CAAA,CAIJ,yCACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,kBAAA,CAGF,iDACE,yBAAA,CAGF,6CACE,iCAAA,CACA,uCAAA,CACA,cAAA,CACA,wBAAA,CACA,YAAA,CACA,kBAAA,CAEA,kDACE,gCAAA,CAIJ,iDACE,oBAAA,CACA,eAAA,CACA,+BAAA,CACA,mBAAA,CAGF,sGAEE,oBAAA,CACA,eAAA,CAGF,iDACE,+BAAA,CAGF,qDACE,gCAAA,CAGF,2CACE,gBAAA,CAGF,wCACE,YAAA,CACA,qBAAA,CAGF,wCACE,sBAAA,CACA,YAAA,CACA,qBAAA,CAEA,2FACE,aAAA,CAIJ,gDACE,iBAAA,CACA,YAAA,CAEA,kDACE,gBAAA,CACA,SAAA","sourcesContent":["@use '@scss-variables/animation';\n\n.Root {\n  position: relative;\n  transition: background-color var(--speed-turbo) var(--easing-base);\n  border: 1px solid transparent;\n  border-bottom: 1px solid var(--theme-color-bg-1);\n\n  &:hover:not(.is-open) {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.is-alerting {\n    animation: border-alert 3000ms animation.$easing-base both;\n  }\n\n  &:not(.is-editor-environment) {\n    order: 1;\n  }\n  &.is-editor-environment {\n    order: 0;\n  }\n}\n\n.Inner {\n  padding: 8px 16px 14px;\n\n  &:not(.is-always-open) {\n    cursor: pointer;\n  }\n}\n\n@keyframes border-alert {\n  15%,\n  45%,\n  75% {\n    border-top: 1px solid var(--theme-color-notice);\n    border-bottom: 1px solid var(--theme-color-notice);\n    border-right: 1px solid var(--theme-color-notice);\n    border-left: 1px solid var(--theme-color-notice);\n  }\n\n  0%,\n  30%,\n  60%,\n  90%,\n  100% {\n    border-top: 1px solid var(--theme-color-bg-2);\n    border-bottom: 1px solid var(--theme-color-bg-1);\n    border-right: 1px solid var(--theme-color-bg-2);\n    border-left: 1px solid var(--theme-color-bg-2);\n  }\n}\n\n.MetaBar {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding-bottom: 8px;\n}\n\n.ToggleContainer {\n  transform: translateX(8px);\n}\n\n.TypeDisplay {\n  color: var(--theme-color-fg-muted);\n  font-weight: var(--font-weight-semibold);\n  font-size: 10px;\n  text-transform: uppercase;\n  display: flex;\n  align-items: center;\n\n  path {\n    fill: var(--theme-color-fg-muted);\n  }\n}\n\n.ActiveIndicator {\n  display: inline-block;\n  margin-left: 5px;\n  color: var(--theme-color-notice);\n  text-transform: none;\n}\n\n.ArchivedDisplay,\n.UsedInEditorDisplay {\n  display: inline-block;\n  margin-left: 8px;\n}\n\n.ArchivedDisplay {\n  color: var(--theme-color-danger);\n}\n\n.UsedInEditorDisplay {\n  color: var(--theme-color-success);\n}\n\n.CloudIcon {\n  margin-right: 8px;\n}\n\n.Header {\n  display: flex;\n  flex-direction: column;\n}\n\n.Drawer {\n  padding: 14px 16px 16px;\n  display: flex;\n  flex-direction: column;\n\n  &.has-no-top-padding {\n    padding-top: 0;\n  }\n}\n\n.AdjacentInputs {\n  margin-left: -16px;\n  display: flex;\n\n  & > * {\n    margin-left: 16px;\n    width: 50%;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `CloudServiceCard-module__Root--lJM3w`,
	"is-open": `CloudServiceCard-module__is-open--aEFxm`,
	"is-alerting": `CloudServiceCard-module__is-alerting--p6N5u`,
	"border-alert": `CloudServiceCard-module__border-alert--_CRCz`,
	"is-editor-environment": `CloudServiceCard-module__is-editor-environment--uXIDw`,
	"Inner": `CloudServiceCard-module__Inner--xNvdY`,
	"is-always-open": `CloudServiceCard-module__is-always-open--QxBD0`,
	"MetaBar": `CloudServiceCard-module__MetaBar--lLWLE`,
	"ToggleContainer": `CloudServiceCard-module__ToggleContainer--zAJWV`,
	"TypeDisplay": `CloudServiceCard-module__TypeDisplay--D9kDQ`,
	"ActiveIndicator": `CloudServiceCard-module__ActiveIndicator--AJai8`,
	"ArchivedDisplay": `CloudServiceCard-module__ArchivedDisplay--yAq_M`,
	"UsedInEditorDisplay": `CloudServiceCard-module__UsedInEditorDisplay--S4GuA`,
	"CloudIcon": `CloudServiceCard-module__CloudIcon--ME3ud`,
	"Header": `CloudServiceCard-module__Header--_XJ9P`,
	"Drawer": `CloudServiceCard-module__Drawer--AHCA3`,
	"has-no-top-padding": `CloudServiceCard-module__has-no-top-padding--NrErP`,
	"AdjacentInputs": `CloudServiceCard-module__AdjacentInputs--duxCi`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 6056:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   r: () => (/* binding */ NodeGraphTraverser)
/* harmony export */ });
/* unused harmony export TraverseNode */
/* harmony import */ var _noodl_models_componentmodel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16163);

/**
 * NodeGraphTraverser is a class that can be used to traverse a graph of nodes.
 *
 * @example
 * ```typescript
 * // This will traverse all the nodes in the project and branch on the router nodes.
 * const traverser = new NodeGraphTraverser(project, node => node.type === 'Router');
 * ```
 *
 * @example
 * ```typescript
 * // This will traverse all the nodes in the project and branch on the page nodes.
 * //
 * // It will also find all the Page Input nodes relative to
 * // the pages and add them as tags to the node.
 * //
 * // This makes it easy to handle paired nodes.
 * const traverser = new NodeGraphTraverser(project, node => node.type === 'Page', {
 *   tagSelector: node => node.owner.roots.find((x) => x.typename === 'PageInputs')
 * });
 * ```
 */
class NodeGraphTraverser {
    constructor(project, selector, options = {}, targetNode = undefined) {
        this.project = project;
        this.selector = selector;
        this.visitedNodeIds = [];
        this.traverseRouter = typeof options.traverseRouter === 'boolean' ? options.traverseRouter : true;
        this.traverseComponentStacks =
            typeof options.traverseComponentStacks === 'boolean' ? options.traverseComponentStacks : false;
        this.traverseComponent = typeof options.traverseComponent === 'boolean' ? options.traverseComponent : true;
        this.tagSelector = typeof options.tagSelector === 'function' ? options.tagSelector : null;
        this.root = new TraverseNode(this, null, targetNode || project.getRootNode(), null);
    }
    forEach(callback) {
        this.root.forEach(callback);
    }
    map(callback) {
        const items = [];
        this.forEach((node) => {
            const result = callback(node);
            if (result)
                items.push(result);
        });
        return items;
    }
    filter(callback) {
        const items = [];
        this.forEach((node) => {
            if (callback(node))
                items.push(node);
        });
        return items;
    }
}
class TraverseNode {
    constructor(root, parent, node, tag) {
        this.root = root;
        this.parent = parent;
        this.node = node;
        this.tag = tag;
        this.children = [];
        this.traverse(node);
    }
    forEach(callback) {
        callback(this);
        this.children.forEach((child) => {
            child.forEach(callback);
        });
    }
    parents(filter) {
        const parents = [];
        function traverse(parent) {
            if (parent.parent) {
                if (filter) {
                    if (filter(parent.parent.node)) {
                        parents.push(parent.parent);
                    }
                }
                else {
                    parents.push(parent.parent);
                }
                traverse(parent.parent);
            }
        }
        if (this.parent) {
            parents.push(this.parent);
            traverse(this.parent);
        }
        return parents;
    }
    traverse(node) {
        var _a, _b;
        const nodeId = node.id;
        const typename = node.typename;
        if (node.id !== this.node.id && this.root.selector(node)) {
            // Only visit a node once, this is important since
            // we are traversing the components and routers too.
            // Which can lead to infinite loops.
            if (!this.root.visitedNodeIds.includes(nodeId)) {
                this.root.visitedNodeIds.push(nodeId);
                const tag = this.root.tagSelector ? this.root.tagSelector(node) : null;
                this.children.push(new TraverseNode(this.root, this, node, tag));
            }
        }
        // Traverse the parameter routes in a Router node
        if (this.root.traverseRouter && typename === 'Router') {
            // Can be undefined when there are no pages
            (_a = node.parameters.pages) === null || _a === void 0 ? void 0 : _a.routes.forEach((componentName) => {
                const component = this.root.project.getComponentWithName(componentName);
                if (component) {
                    // NOTE: Root is always "Page"
                    component.graph.roots.forEach((child) => {
                        this.traverse(child);
                    });
                }
            });
        }
        //Traverse the pages in a Component Stack
        if (this.root.traverseComponentStacks && typename === 'Page Stack') {
            // Can be undefined when there are no pages
            (_b = node.parameters.pages) === null || _b === void 0 ? void 0 : _b.forEach(({ id }) => {
                const componentName = node.parameters['pageComp-' + id];
                const pagePath = node.parameters['pagePath-' + id];
                if (componentName) {
                    const component = this.root.project.getComponentWithName(componentName);
                    if (component) {
                        if (node.parameters.useRoutes && pagePath) {
                            const pathProxyNode = {
                                id: node.id + '-' + id,
                                typename: 'Page Stack Proxy Path',
                                type: null,
                                parameters: { route: pagePath && pagePath[0] === '/' ? pagePath.substring(1) : pagePath },
                                children: component.graph.roots
                            };
                            // HACK: Fake the NodeGraphNode type
                            this.traverse(pathProxyNode);
                        }
                        else {
                            component.graph.roots.forEach((child) => {
                                this.traverse(child);
                            });
                        }
                    }
                }
            });
        }
        // Traverse the component
        if (this.root.traverseComponent && node.type instanceof _noodl_models_componentmodel__WEBPACK_IMPORTED_MODULE_0__/* .ComponentModel */ .j) {
            const component = this.root.project.getComponentWithName(node.type.name);
            if (component) {
                component.graph.roots.forEach((child) => {
                    this.traverse(child);
                });
            }
        }
        // Traverse all the children
        if (node.children && node.children.length > 0) {
            node.children.forEach((child) => {
                this.traverse(child);
            });
        }
    }
}


/***/ }),

/***/ 6068:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.BoundaryIndicator-module__boundaryIndicator--PdDCL{position:absolute;pointer-events:auto;z-index:1001;transform:translate(-50%, -50%);animation:BoundaryIndicator-module__fade-in--cwp1d .3s ease-out}.BoundaryIndicator-module__content--RDdE5{display:flex;align-items:center;gap:var(--theme-spacing-2);padding:var(--theme-spacing-2) var(--theme-spacing-3);background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.3);transition:all .2s ease}.BoundaryIndicator-module__content--RDdE5:hover{transform:scale(1.02);box-shadow:0 6px 16px rgba(0,0,0,.4)}.BoundaryIndicator-module__icon--OPgwt{font-size:16px;font-weight:bold;color:var(--theme-color-fg-highlight);min-width:16px;text-align:center}.BoundaryIndicator-module__label--YiIp4{display:flex;flex-direction:column;gap:2px}.BoundaryIndicator-module__text--VR659{font-size:11px;color:var(--theme-color-fg-default-shy);font-weight:500;text-transform:uppercase;letter-spacing:.5px}.BoundaryIndicator-module__componentName--csgTm{font-size:13px;color:var(--theme-color-fg-default);font-weight:600}.BoundaryIndicator-module__navigateButton--cCa2v{padding:var(--theme-spacing-1) var(--theme-spacing-2);background-color:var(--theme-color-primary);color:#fff;border:none;border-radius:4px;font-size:14px;font-weight:bold;cursor:pointer;transition:all .2s ease}.BoundaryIndicator-module__navigateButton--cCa2v:hover{background-color:var(--theme-color-primary-hover);transform:scale(1.1)}.BoundaryIndicator-module__navigateButton--cCa2v:active{transform:scale(0.95)}.BoundaryIndicator-module__directionUp--Petz5 .BoundaryIndicator-module__icon--OPgwt{color:var(--theme-color-accent-blue)}.BoundaryIndicator-module__directionDown--cqA4k .BoundaryIndicator-module__icon--OPgwt{color:var(--theme-color-accent-orange)}@keyframes BoundaryIndicator-module__fade-in--cwp1d{from{opacity:0;transform:translate(-50%, -50%) scale(0.9)}to{opacity:1;transform:translate(-50%, -50%) scale(1)}}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/CanvasOverlays/HighlightOverlay/BoundaryIndicator.module.scss"],"names":[],"mappings":"AAOA,oDACE,iBAAA,CACA,mBAAA,CACA,YAAA,CACA,+BAAA,CAGA,+DAAA,CAGF,0CACE,YAAA,CACA,kBAAA,CACA,0BAAA,CACA,qDAAA,CAEA,wCAAA,CACA,kDAAA,CACA,iBAAA,CAEA,oCAAA,CAGA,uBAAA,CAEA,gDACE,qBAAA,CACA,oCAAA,CAIJ,uCACE,cAAA,CACA,gBAAA,CACA,qCAAA,CACA,cAAA,CACA,iBAAA,CAGF,wCACE,YAAA,CACA,qBAAA,CACA,OAAA,CAGF,uCACE,cAAA,CACA,uCAAA,CACA,eAAA,CACA,wBAAA,CACA,mBAAA,CAGF,gDACE,cAAA,CACA,mCAAA,CACA,eAAA,CAGF,iDACE,qDAAA,CACA,2CAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,cAAA,CACA,gBAAA,CACA,cAAA,CACA,uBAAA,CAEA,uDACE,iDAAA,CACA,oBAAA,CAGF,wDACE,qBAAA,CAMF,qFACE,oCAAA,CAKF,uFACE,sCAAA,CAKJ,oDACE,KACE,SAAA,CACA,0CAAA,CAEF,GACE,SAAA,CACA,wCAAA,CAAA","sourcesContent":["/**\n * BoundaryIndicator component styles\n *\n * Floating badge showing where cross-component paths continue.\n * Uses design tokens for consistency.\n */\n\n.boundaryIndicator {\n  position: absolute;\n  pointer-events: auto;\n  z-index: 1001; /* Above highlighted nodes */\n  transform: translate(-50%, -50%); /* Center on position */\n\n  /* Animation */\n  animation: fade-in 0.3s ease-out;\n}\n\n.content {\n  display: flex;\n  align-items: center;\n  gap: var(--theme-spacing-2);\n  padding: var(--theme-spacing-2) var(--theme-spacing-3);\n\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 8px;\n\n  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);\n\n  /* Smooth hover transition */\n  transition: all 0.2s ease;\n\n  &:hover {\n    transform: scale(1.02);\n    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);\n  }\n}\n\n.icon {\n  font-size: 16px;\n  font-weight: bold;\n  color: var(--theme-color-fg-highlight);\n  min-width: 16px;\n  text-align: center;\n}\n\n.label {\n  display: flex;\n  flex-direction: column;\n  gap: 2px;\n}\n\n.text {\n  font-size: 11px;\n  color: var(--theme-color-fg-default-shy);\n  font-weight: 500;\n  text-transform: uppercase;\n  letter-spacing: 0.5px;\n}\n\n.componentName {\n  font-size: 13px;\n  color: var(--theme-color-fg-default);\n  font-weight: 600;\n}\n\n.navigateButton {\n  padding: var(--theme-spacing-1) var(--theme-spacing-2);\n  background-color: var(--theme-color-primary);\n  color: white;\n  border: none;\n  border-radius: 4px;\n  font-size: 14px;\n  font-weight: bold;\n  cursor: pointer;\n  transition: all 0.2s ease;\n\n  &:hover {\n    background-color: var(--theme-color-primary-hover);\n    transform: scale(1.1);\n  }\n\n  &:active {\n    transform: scale(0.95);\n  }\n}\n\n/* Direction-specific styling */\n.directionUp {\n  .icon {\n    color: var(--theme-color-accent-blue);\n  }\n}\n\n.directionDown {\n  .icon {\n    color: var(--theme-color-accent-orange);\n  }\n}\n\n/* Animations */\n@keyframes fade-in {\n  from {\n    opacity: 0;\n    transform: translate(-50%, -50%) scale(0.9);\n  }\n  to {\n    opacity: 1;\n    transform: translate(-50%, -50%) scale(1);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"boundaryIndicator": `BoundaryIndicator-module__boundaryIndicator--PdDCL`,
	"fade-in": `BoundaryIndicator-module__fade-in--cwp1d`,
	"content": `BoundaryIndicator-module__content--RDdE5`,
	"icon": `BoundaryIndicator-module__icon--OPgwt`,
	"label": `BoundaryIndicator-module__label--YiIp4`,
	"text": `BoundaryIndicator-module__text--VR659`,
	"componentName": `BoundaryIndicator-module__componentName--csgTm`,
	"navigateButton": `BoundaryIndicator-module__navigateButton--cCa2v`,
	"directionUp": `BoundaryIndicator-module__directionUp--Petz5`,
	"directionDown": `BoundaryIndicator-module__directionDown--cqA4k`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 6202:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPlayCircle = function SvgPlayCircle(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 25,
    viewBox: "0 0 24 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.0002 5.54709C7.93344 5.54709 4.63672 8.84381 4.63672 12.9105C4.63672 16.9772 7.93344 20.274 12.0002 20.274C16.0669 20.274 19.3636 16.9772 19.3636 12.9105C19.3636 8.84381 16.0669 5.54709 12.0002 5.54709ZM3.13672 12.9105C3.13672 8.01538 7.10501 4.04709 12.0002 4.04709C16.8953 4.04709 20.8636 8.01538 20.8636 12.9105C20.8636 17.8057 16.8953 21.774 12.0002 21.774C7.10501 21.774 3.13672 17.8057 3.13672 12.9105Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M15.1647 13.3266C15.4616 13.1287 15.4616 12.6924 15.1647 12.4945L10.4951 9.38148C10.1628 9.15996 9.71777 9.39815 9.71777 9.7975V16.0236C9.71777 16.4229 10.1628 16.6611 10.4951 16.4396L15.1647 13.3266Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPlayCircle);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "c00744e192077f2c7f1577b2015b513a.svg");

/***/ }),

/***/ 6203:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  ProjectModel: () => (/* binding */ ProjectModel)
});

// EXTERNAL MODULE: external "underscore"
var external_underscore_ = __webpack_require__(80002);
var external_underscore_default = /*#__PURE__*/__webpack_require__.n(external_underscore_);
// EXTERNAL MODULE: ../noodl-platform/src/index.ts + 10 modules
var src = __webpack_require__(37218);
// EXTERNAL MODULE: ./src/editor/src/models/undo-queue-model.ts
var undo_queue_model = __webpack_require__(50867);
// EXTERNAL MODULE: ./src/editor/src/models/warningsmodel.ts
var warningsmodel = __webpack_require__(86105);
;// external "node:child_process"
const external_node_child_process_namespaceObject = require("node:child_process");
// EXTERNAL MODULE: external "node:path"
var external_node_path_ = __webpack_require__(76760);
var external_node_path_default = /*#__PURE__*/__webpack_require__.n(external_node_path_);
;// ./src/editor/src/utils/verifyJson.ts



function verifyJsonFile(filePath) {
    const verifyJsonIndexFilePath = external_node_path_default().join(src.platform.getAppPath(), 'src/editor/verify-json-index.js');
    const child = (0,external_node_child_process_namespaceObject.fork)(verifyJsonIndexFilePath, [filePath]);
    return new Promise((resolve, reject) => {
        child.on('close', (code) => {
            resolve(code === 0);
        });
        child.on('error', (e) => {
            reject(e);
        });
    });
}

// EXTERNAL MODULE: ./src/shared/model.js
var model = __webpack_require__(47821);
var model_default = /*#__PURE__*/__webpack_require__.n(model);
// EXTERNAL MODULE: ./src/shared/utils/EventDispatcher.ts
var EventDispatcher = __webpack_require__(11138);
// EXTERNAL MODULE: ./src/editor/src/utils/utils.ts
var utils = __webpack_require__(93015);
// EXTERNAL MODULE: ./src/editor/src/models/componentmodel.ts
var componentmodel = __webpack_require__(16163);
// EXTERNAL MODULE: ./src/editor/src/models/lessonmodel.js
var lessonmodel = __webpack_require__(13185);
var lessonmodel_default = /*#__PURE__*/__webpack_require__.n(lessonmodel);
// EXTERNAL MODULE: ./src/editor/src/models/nodegraphmodel/index.ts + 4 modules
var nodegraphmodel = __webpack_require__(87844);
// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/index.ts
var nodelibrary = __webpack_require__(68091);
// EXTERNAL MODULE: ./src/editor/src/utils/bugtracker.ts
var bugtracker = __webpack_require__(90962);
;// ./src/editor/src/models/projectmodel.modules.ts


async function listProjectModules(project /* ProjectModel */) {
    var modules = [];
    const modulesPath = project._retainedProjectDirectory + '/noodl_modules';
    const files = await src.filesystem.listDirectory(modulesPath);
    await Promise.all(files.map(async (file) => {
        if (file.isDirectory) {
            const manifestPath = src.filesystem.join(modulesPath, file.name, 'manifest.json');
            const manifest = await src.filesystem.readJson(manifestPath);
            modules.push({
                name: file.name,
                manifest
            });
        }
    }));
    return modules;
}
async function readProjectModules(project /* ProjectModel */) {
    bugtracker/* bugtracker */.$.debug('ProjectModel.readModules');
    const modulesPath = project._retainedProjectDirectory + '/noodl_modules';
    const files = await src.filesystem.listDirectory(modulesPath);
    project.modules = [];
    project.previews = [];
    project.componentAnnotations = {};
    await Promise.all(files.map(async (file) => {
        if (file.isDirectory) {
            const manifestPath = src.filesystem.join(modulesPath, file.name, 'manifest.json');
            const manifest = await src.filesystem.readJson(manifestPath);
            if (manifest) {
                manifest.name = file.name;
                project.modules.push(manifest);
                if (manifest.componentAnnotations) {
                    for (var comp in manifest.componentAnnotations) {
                        var ca = manifest.componentAnnotations[comp];
                        if (!project.componentAnnotations[comp])
                            project.componentAnnotations[comp] = {};
                        for (var key in ca)
                            project.componentAnnotations[comp][key] = ca[key];
                    }
                }
                if (manifest.previews) {
                    project.previews = manifest.previews.concat(project.previews);
                }
            }
        }
    }));
    console.log(`Loaded ${project.modules.length} modules`);
    return project.modules;
}

;// ./src/editor/src/models/VariantModel.ts





function _merge(dst, src) {
    for (const key in src) {
        if (src[key] !== undefined) {
            dst[key] = JSON.parse(JSON.stringify(src[key]));
        }
    }
}
class VariantModel extends (model_default()) {
    constructor(args) {
        super();
        this.name = args.name;
        this.typename = args.typename;
        this.parameters = {};
        this.stateParameters = {};
        this.stateTransitions = {};
    }
    // This will copy the parameter values from the node and merge with
    // existing values (keeping old values in the variant)
    updateFromNode(node) {
        _merge(this.parameters, node.parameters);
        // Merge state parameters
        if (node.stateParameters) {
            if (this.stateParameters === undefined)
                this.stateParameters = {};
            for (var state in node.stateParameters) {
                if (this.stateParameters[state] === undefined)
                    this.stateParameters[state] = {};
                _merge(this.stateParameters[state], node.stateParameters[state]);
            }
        }
        // Merge state transitions
        if (node.stateTransitions) {
            if (this.stateTransitions === undefined)
                this.stateTransitions = {};
            for (var state in node.stateTransitions) {
                if (this.stateTransitions[state] === undefined)
                    this.stateTransitions[state] = {};
                _merge(this.stateTransitions[state], node.stateTransitions[state]);
            }
        }
        // Merge state transitions
        if (node.defaultStateTransitions) {
            if (this.defaultStateTransitions === undefined)
                this.defaultStateTransitions = {};
            _merge(this.defaultStateTransitions, node.defaultStateTransitions);
        }
        this.notifyListeners('variantParametersChanged');
    }
    // This will update the parameters but from an other variant
    updateFromVariant(variant) {
        _merge(this.parameters, variant.parameters);
        // Merge state parameters
        if (variant.stateParameters) {
            if (this.stateParameters === undefined)
                this.stateParameters = {};
            for (var state in variant.stateParameters) {
                if (this.stateParameters[state] === undefined)
                    this.stateParameters[state] = {};
                _merge(this.stateParameters[state], variant.stateParameters[state]);
            }
        }
        // Merge state transitions
        if (variant.stateTransitions) {
            if (this.stateTransitions === undefined)
                this.stateTransitions = {};
            for (var state in variant.stateTransitions) {
                if (this.stateTransitions[state] === undefined)
                    this.stateTransitions[state] = {};
                _merge(this.stateTransitions[state], variant.stateTransitions[state]);
            }
        }
        // Merge state transitions
        if (variant.defaultStateTransitions) {
            if (this.defaultStateTransitions === undefined)
                this.defaultStateTransitions = {};
            _merge(this.defaultStateTransitions, variant.defaultStateTransitions);
        }
        this.notifyListeners('variantParametersChanged');
    }
    setParameters(args) {
        this.parameters = args.parameters;
        this.stateParameters = args.stateParamaters;
        this.stateTransitions = args.stateTransitions;
        this.defaultStateTransitions = args.defaultStateTransitions;
        this.notifyListeners('variantParametersChanged');
    }
    hasParameter(name, args) {
        if (args && args.state !== undefined && args.state !== 'neutral') {
            if (this.stateParameters !== undefined && this.stateParameters[args.state] !== undefined)
                return this.stateParameters[args.state][name] !== undefined;
        }
        else
            return this.parameters[name] !== undefined;
        return false;
    }
    getPort(portname, filter) {
        const ports = this.getPorts(filter);
        for (const i in ports)
            if (ports[i].name === portname)
                return ports[i];
    }
    getPorts(filter) {
        var ports;
        if (!this._ports) {
            // Start with type ports
            const type = this.getType();
            if (type === undefined)
                return [];
            var ports = type.ports ? type.ports : [];
            // Sort on index (assign index in order if not present)
            ports.sort(function (a, b) {
                return a.index > b.index ? 1 : -1;
            });
            this._ports = ports;
        }
        else
            ports = this._ports;
        return filter
            ? external_underscore_default().filter(ports, function (p) {
                return p.plug && p.plug.indexOf(filter) !== -1;
            })
            : ports;
    }
    getType() {
        if (this._type)
            return this._type;
        this._type = nodelibrary/* NodeLibrary */.m.instance.getNodeTypeWithName(this.typename);
        return this._type;
    }
    getParameter(name, args) {
        let value;
        if (args && args.state !== undefined && args.state !== 'neutral') {
            // Look for the parameter value in the state parameters
            if (this.stateParameters !== undefined && this.stateParameters[args.state] !== undefined)
                value = this.stateParameters[args.state][name];
            // No value in state parameters, try neutral state
            if (value === undefined)
                value = this.parameters[name];
        }
        else {
            // Look for the value in the neutral state / base parameters
            value = this.parameters[name];
        }
        if (value !== undefined)
            return value;
        // Get the default value from the port default
        const port = this.getPort(name, 'input');
        return port ? port.default : undefined;
    }
    setParameter(name, value, args) {
        if (args && args.state !== undefined && args.state !== 'neutral') {
            // Set the parameter for a specific interaction state
            if (this.stateParameters === undefined)
                this.stateParameters = {};
            if (this.stateParameters[args.state] === undefined)
                this.stateParameters[args.state] = {};
            var oldValue = this.stateParameters[args.state][name];
            if (value === undefined) {
                delete this.stateParameters[args.state][name];
            }
            else {
                this.stateParameters[args.state][name] = value;
            }
            this.notifyListeners('variantParametersChanged', { name: name, value: value, state: args.state });
        }
        else {
            var oldValue = this.parameters[name];
            if (value === undefined) {
                delete this.parameters[name];
            }
            else {
                this.parameters[name] = value;
            }
            this.notifyListeners('variantParametersChanged', { name: name, value: value });
        }
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            if (args.oldValue) {
                oldValue = args.oldValue;
            }
            undo.push({
                label: args.label,
                do: () => {
                    this.setParameter(name, value);
                },
                undo: () => {
                    this.setParameter(name, oldValue);
                }
            });
        }
    }
    getPossibleTransitionsForState(state) {
        const _this = this;
        const transitions = {};
        function _addTransitions(stateParameters) {
            for (const parameterName in stateParameters) {
                const port = _this.getPort(parameterName);
                if (nodelibrary/* NodeLibrary */.m.instance.canPortHaveTransition(port))
                    transitions[parameterName] = {
                        name: parameterName,
                        displayName: port ? port.displayName : undefined,
                        group: port ? port.group : undefined
                    };
            }
        }
        if (this.stateParameters === undefined)
            return [];
        if (state !== undefined && state !== 'neutral') {
            // Find all properties that have a value set for this state
            if (this.stateParameters && this.stateParameters[state])
                _addTransitions(this.stateParameters[state]);
            return Object.keys(transitions).map((t) => transitions[t]);
        }
        else {
            // This is the neutral state, it should contain all properties for all states
            const type = this.getType();
            if (type === undefined)
                return [];
            type.visualStates &&
                type.visualStates.forEach((state) => {
                    // Add state parameters from this node
                    if (this.stateParameters && this.stateParameters[state.name])
                        _addTransitions(this.stateParameters[state.name]);
                });
            return Object.keys(transitions).map((t) => transitions[t]);
        }
    }
    getStateTransition(state = 'neutral', parameterName) {
        if (this.stateTransitions !== undefined && this.stateTransitions[state] !== undefined)
            return this.stateTransitions[state][parameterName];
    }
    setStateTransition(state = 'neutral', parameterName, curve, args) {
        if (this.stateTransitions === undefined)
            this.stateTransitions = {};
        if (this.stateTransitions[state] === undefined)
            this.stateTransitions[state] = {};
        const _oldStateTransition = this.stateTransitions[state][parameterName];
        this.stateTransitions[state][parameterName] = curve;
        this.notifyListeners('variantStateTransitionsChanged', {
            state: state,
            parameterName: parameterName,
            curve: curve
        });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: 'set variant state transition',
                do: () => {
                    this.setStateTransition(state, parameterName, curve, args);
                },
                undo: () => {
                    this.stateTransitions[state][parameterName] = _oldStateTransition;
                    this.notifyListeners('variantStateTransitionsChanged', {
                        state: state,
                        parameterName: parameterName,
                        curve: _oldStateTransition
                    });
                }
            });
        }
    }
    getDefaultStateTransition(state = 'neutral') {
        if (this.defaultStateTransitions !== undefined)
            return this.defaultStateTransitions[state];
    }
    setDefaultStateTransition(state = 'neutral', curve, args) {
        if (this.defaultStateTransitions === undefined)
            this.defaultStateTransitions = {};
        const _oldDefaultStateTransition = this.defaultStateTransitions[state];
        this.defaultStateTransitions[state] = curve;
        this.notifyListeners('variantDefaultStateTransitionChanged', { state, curve });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: 'set variant default state transition',
                do: () => {
                    this.setDefaultStateTransition(state, curve, args);
                },
                undo: () => {
                    this.defaultStateTransitions[state] = _oldDefaultStateTransition;
                    this.notifyListeners('variantDefaultStateTransitionChanged', { state, curve: _oldDefaultStateTransition });
                }
            });
        }
    }
    evaluateHealth() {
        const clearConflict = (c) => {
            const idx = this.conflicts.indexOf(c);
            idx !== -1 && this.conflicts.splice(idx, 1);
            let key;
            if (c.type === 'parameter')
                key = 'variant-param-conflict-' + this.name + '-' + this.getType().fullName + '-' + c.name;
            else if (c.type === 'stateParameter')
                key =
                    'variant-state-param-conflict-' + this.name + '-' + this.getType().fullName + '-' + c.state + '-' + c.name;
            else if (c.type === 'stateTransition')
                key =
                    'variant-state-trans-conflict-' + this.name + '-' + this.getType().fullName + '-' + c.state + '-' + c.name;
            else if (c.type === 'defaultStateTransition')
                key = 'variant-dst-conflict-' + this.name + '-' + this.getType().fullName + '-' + c.state;
            warningsmodel/* WarningsModel */.l.instance.setWarning({ key }, undefined);
        };
        if (this.conflicts)
            this.conflicts.forEach((c) => {
                if (c.type === 'parameter') {
                    var port = this.getPort(c.name);
                    var ourValue = nodelibrary/* NodeLibrary */.m.instance.formatParameterValue(c.oursDisplayName || c.ours, port);
                    var theirValue = nodelibrary/* NodeLibrary */.m.instance.formatParameterValue(c.theirsDisplayName || c.theirs, port);
                    var portName = port !== undefined && port.displayName ? port.displayName : c.name;
                    warningsmodel/* WarningsModel */.l.instance.setWarning({ key: 'variant-param-conflict-' + this.name + '-' + this.getType().fullName + '-' + c.name }, {
                        type: 'conflict',
                        conflictMetadata: {
                            parameter: portName,
                            ours: ourValue,
                            theirs: theirValue
                        },
                        message: `Merge conflict in variant ${this.name} for type ${this.getType().displayName}`,
                        showGlobally: true,
                        onDismiss: () => {
                            clearConflict(c);
                        },
                        onUseTheirs: () => {
                            clearConflict(c);
                            this.setParameter(c.name, c.theirs);
                        }
                    });
                }
                else if (c.type === 'stateParameter') {
                    var state = this.getType().visualStates !== undefined
                        ? this.getType().visualStates.find((s) => s.name === c.state)
                        : undefined;
                    var stateName = state !== undefined ? state.label : c.state;
                    var port = this.getPort(c.name);
                    var ourValue = nodelibrary/* NodeLibrary */.m.instance.formatParameterValue(c.oursDisplayName || c.ours, port);
                    var theirValue = nodelibrary/* NodeLibrary */.m.instance.formatParameterValue(c.theirsDisplayName || c.theirs, port);
                    var portName = port !== undefined && port.displayName ? port.displayName : c.name;
                    warningsmodel/* WarningsModel */.l.instance.setWarning({
                        key: 'variant-state-param-conflict-' +
                            this.name +
                            '-' +
                            this.getType().fullName +
                            '-' +
                            c.state +
                            '-' +
                            c.name
                    }, {
                        type: 'conflict',
                        conflictMetadata: {
                            parameter: portName,
                            ours: ourValue,
                            theirs: theirValue
                        },
                        message: `Merge conflict in variant ${this.name} for type ${this.getType().displayName} in visual state parameter for state ${stateName}`,
                        showGlobally: true,
                        onDismiss: () => {
                            clearConflict(c);
                        },
                        onUseTheirs: () => {
                            clearConflict(c);
                            this.setParameter(c.name, c.theirs, { state: c.state });
                        }
                    });
                }
                else if (c.type === 'stateTransition') {
                    var state = this.getType().visualStates !== undefined
                        ? this.getType().visualStates.find((s) => s.name === c.state)
                        : undefined;
                    var stateName = state !== undefined ? state.label : c.state;
                    var port = this.getPort(c.name);
                    var portName = port !== undefined && port.displayName ? port.displayName : c.name;
                    warningsmodel/* WarningsModel */.l.instance.setWarning({
                        key: 'variant-state-trans-conflict-' +
                            this.name +
                            '-' +
                            this.getType().fullName +
                            '-' +
                            c.state +
                            '-' +
                            c.name
                    }, {
                        type: 'conflict',
                        conflictMetadata: {
                            parameter: portName,
                            ours: ourValue,
                            theirs: theirValue
                        },
                        message: `Merge conflict in variant ${this.name} for type ${this.getType().displayName} in visual state transition ${portName} for state ${stateName}`,
                        showGlobally: true,
                        onDismiss: () => {
                            clearConflict(c);
                        },
                        onUseTheirs: () => {
                            clearConflict(c);
                            this.setStateTransition(c.state, c.name, c.theirs);
                        }
                    });
                }
                else if (c.type === 'defaultStateTransition') {
                    var state = this.getType().visualStates !== undefined
                        ? this.getType().visualStates.find((s) => s.name === c.state)
                        : undefined;
                    var stateName = state !== undefined ? state.label : c.state;
                    warningsmodel/* WarningsModel */.l.instance.setWarning({ key: 'variant-dst-conflict-' + this.name + '-' + this.getType().fullName + '-' + c.state }, {
                        type: 'conflict',
                        conflictMetadata: {
                            parameter: portName,
                            ours: ourValue,
                            theirs: theirValue
                        },
                        message: `Merge conflict in variant ${this.name} for type ${this.getType().displayName} in default visual state transition ${portName} for state ${stateName}`,
                        level: 'error',
                        showGlobally: true,
                        onDismiss: () => {
                            clearConflict(c);
                        },
                        onUseTheirs: () => {
                            clearConflict(c);
                            this.setDefaultStateTransition(c.state, c.theirs);
                        }
                    });
                }
            });
    }
    toJSON() {
        const json = {
            name: this.name,
            typename: this.typename,
            parameters: this.parameters,
            stateParamaters: this.stateParameters,
            stateTransitions: this.stateTransitions,
            defaultStateTransitions: this.defaultStateTransitions,
            conflicts: this.conflicts ? JSON.parse(JSON.stringify(this.conflicts)) : undefined
        };
        return json;
    }
    static fromJSON(json) {
        const _this = new VariantModel({
            name: json.name,
            typename: json.typename
        });
        _this.parameters = json.parameters;
        _this.stateParameters = json.stateParamaters;
        _this.stateTransitions = json.stateTransitions;
        _this.defaultStateTransitions = json.defaultStateTransitions;
        _this.conflicts = json.conflicts;
        return _this;
    }
}

;// ./src/editor/src/models/projectmodel.ts














class ProjectModel extends (model_default()) {
    static get instance() {
        return ProjectModel._instance;
    }
    static set instance(project) {
        if (ProjectModel._instance !== project) {
            //unload old project
            if (ProjectModel._instance) {
                EventDispatcher.EventDispatcher.instance.notifyListeners('ProjectModel.instanceWillChange');
                nodelibrary/* NodeLibrary */.m.instance.unregisterModule(ProjectModel._instance);
            }
            //and load new one, if any
            project !== undefined && nodelibrary/* NodeLibrary */.m.instance.registerModule(project);
            const _oldInstance = ProjectModel._instance;
            ProjectModel._instance = project;
            EventDispatcher.EventDispatcher.instance.notifyListeners('ProjectModel.instanceHasChanged', {
                oldInstance: _oldInstance
            });
        }
    }
    constructor(args) {
        super();
        this.modules = [];
        this.components = [];
        this.variants = [];
        this.settings = {};
        if (args) {
            this.name = args.name;
            this.settings = args.settings;
            // this.thumbnailURI = args.thumbnailURI;
            this.version = args.version;
            this.runtimeVersion = args.runtimeVersion;
            this.metadata = args.metadata;
            // this.deviceSettings = args.deviceSettings;
        }
        // NOTE: runtimeVersion is NOT auto-defaulted here!
        // - New projects: Explicitly set to 'react19' in LocalProjectsModel.newProject()
        // - Old projects: Left undefined, detected by runtime scanner
        // - This prevents corrupting legacy projects when they're loaded
        nodelibrary/* NodeLibrary */.m.instance.on(['moduleRegistered', 'moduleUnregistered', 'libraryUpdated'], () => {
            this.scheduleEvaluateHealth();
        }, this);
    }
    // Load project json from directory
    static readJSONFromDirectory(retainedProjectDirectory, callback) {
        src.filesystem
            .readJson(retainedProjectDirectory + '/project.json')
            .then(callback)
            .catch((error) => {
            console.error(error);
            callback();
        });
    }
    // From local storage
    static fromLocalStorage() {
        let _this;
        const json = localStorage['project'];
        if (json)
            _this = ProjectModel.fromJSON(JSON.parse(json));
        else
            _this = new ProjectModel();
        return _this;
    }
    static fromJSON(json) {
        const _this = new ProjectModel(json);
        if (json.lesson)
            _this.lesson = lessonmodel_default().fromJSON(json.lesson);
        for (const i in json.components) {
            _this.addComponent(componentmodel/* ComponentModel */.j.fromJSON(json.components[i]));
        }
        if (json.variants !== undefined)
            _this.variants = json.variants.map((v) => VariantModel.fromJSON(v));
        if (json.rootNodeId)
            _this.rootNode = _this.findNodeWithId(json.rootNodeId);
        // Upgrade project if necessary
        ProjectModel.upgrade(_this);
        return _this;
    }
    static setSaveOnModelChange(enabled) {
        saveOnModelChange = enabled;
        if (!saveOnModelChange) {
            clearTimeout(saveTimeout);
        }
    }
    static upgrade(project) {
        if (!project.version)
            project.version = '0';
        let upgrader;
        while ((upgrader = ProjectModel.Upgraders[project.version])) {
            upgrader(project);
        }
    }
    dispose() {
        for (const c in this.components)
            this.components[c].dispose();
        nodelibrary/* NodeLibrary */.m.instance.off(this);
    }
    // Sets the root
    setRootNode(node) {
        this.rootNode = node;
        this.notifyListeners('rootNodeChanged', {
            model: node
        });
    }
    setRootComponent(component) {
        // First first node that can be export root
        const root = external_underscore_default().find(component.graph.roots, function (n) {
            return n.type.allowAsExportRoot;
        });
        if (root)
            this.setRootNode(root);
    }
    // Returns root
    getRootNode() {
        return this.rootNode;
    }
    getRootComponent() {
        var _a;
        const root = this.getRootNode();
        if (!root) {
            return;
        }
        return (_a = root.owner) === null || _a === void 0 ? void 0 : _a.owner;
    }
    // Returns all components of the project
    getComponents() {
        return this.components;
    }
    // Add a component to this project
    addComponent(component, args) {
        const _this = this;
        component.owner = this;
        if (args && args.undo && typeof args.undo !== 'object')
            var undoGroup = (args.undo = new undo_queue_model/* UndoActionGroup */.C({
                label: args.label || 'add component'
            }));
        this.components.push(component);
        this.notifyListeners('componentAdded', {
            model: component,
            undo: args ? args.undo : undefined
        });
        nodelibrary/* NodeLibrary */.m.instance.notifyListeners('typeAdded', {
            model: component
        });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: args.label,
                do: function () {
                    _this.addComponent(component);
                },
                undo: function () {
                    _this.removeComponent(component);
                }
            });
            undoGroup && undo_queue_model/* UndoQueue */.g.instance.push(undoGroup); // Push undo group if it was created
        }
    }
    duplicateComponent(component, newComponentName, args) {
        if (args && args.undo && typeof args.undo !== 'object')
            var undoGroup = (args.undo = new undo_queue_model/* UndoActionGroup */.C({
                label: args.label || 'duplicate component'
            }));
        const newComponent = new componentmodel/* ComponentModel */.j({
            name: newComponentName,
            graph: nodegraphmodel/* NodeGraphModel */.W2.fromJSON(JSON.parse(JSON.stringify(component.graph.toJSON()))),
            id: utils["default"].guid()
        });
        newComponent.rekeyAllIds();
        if (args.rerouteComponentRefs) {
            newComponent.rerouteComponentRefs(args.rerouteComponentRefs.oldPathPrefix, args.rerouteComponentRefs.newPathPrefix);
        }
        this.addComponent(newComponent, args);
        this.notifyListeners('componentDuplicated', {
            source: component,
            duplicate: newComponent,
            undo: args ? args.undo : undefined
        });
        undoGroup && undo_queue_model/* UndoQueue */.g.instance.push(undoGroup); // Push undo group if it was created
    }
    // Remove a component from this project
    removeComponent(component, args) {
        var _a, _b;
        const _this = this;
        const idx = this.components.indexOf(component);
        if (idx !== -1) {
            if (args && args.undo && typeof args.undo !== 'object')
                // Create undo group if none is provided already
                var undoGroup = (args.undo = new undo_queue_model/* UndoActionGroup */.C({
                    label: args.label || 'remove component'
                }));
            warningsmodel/* WarningsModel */.l.instance.clearAllWarningsForComponent(component);
            component.owner = undefined;
            this.components.splice(idx, 1);
            //reset the root node if we're deleting the root component
            if (((_b = (_a = this.rootNode) === null || _a === void 0 ? void 0 : _a.owner) === null || _b === void 0 ? void 0 : _b.owner) === component) {
                this.setRootNode(null);
            }
            this.notifyListeners('componentRemoved', {
                model: component,
                undo: args ? args.undo : undefined
            });
            nodelibrary/* NodeLibrary */.m.instance.notifyListeners('typeRemoved', {
                model: component
            });
            component.off(this);
            // Undo
            if (args && args.undo) {
                const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
                undo.push({
                    label: args.label,
                    do: function () {
                        _this.removeComponent(component);
                    },
                    undo: function () {
                        _this.addComponent(component);
                    }
                });
                undoGroup && undo_queue_model/* UndoQueue */.g.instance.push(undoGroup); // Push undo group if it was created
            }
            return true;
        }
    }
    /**
     * Returns a component with a specific name
     * @param name
     * @returns
     */
    getComponentWithName(name) {
        for (const i in this.components) {
            const c = this.components[i];
            if (c.name === name)
                return c;
        }
        return undefined;
    }
    forEachComponent(callback) {
        for (const i in this.components)
            callback(this.components[i]);
    }
    findNodeWithId(id) {
        for (const i in this.components) {
            const c = this.components[i];
            const node = c.graph.findNodeWithId(id);
            if (node)
                return node;
        }
    }
    getNodesWithType(typename) {
        const nodes = [];
        this.forEachComponent((c) => {
            c.forEachNode((n) => {
                if (n.typename === typename)
                    nodes.push(n);
            });
        });
        return nodes;
    }
    // Rename a component of the project
    renameComponent(component, newname, args) {
        const oldName = component.name;
        component.rename(newname);
        this.notifyListeners('componentRenamed', {
            model: component,
            oldName: oldName
        });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            const _this = this;
            undo.push({
                label: args.label,
                do: function () {
                    _this.renameComponent(component, newname);
                },
                undo: function () {
                    _this.renameComponent(component, oldName);
                }
            });
        }
    }
    // Rename a component with a given name
    renameComponentWithName(oldname, newname, args) {
        if (this.getComponentWithName(newname))
            return false;
        const c = this.getComponentWithName(oldname);
        this.renameComponent(c, newname, args);
        return true;
    }
    // Returns all components that start with the specified path
    getComponentsWithPath(path) {
        return external_underscore_default().filter(this.components, function (c) {
            return c.name.indexOf(path) === 0;
        });
    }
    // Moves all components that start with the specified path oldpath to
    // the new path
    moveComponentsToNewPath(oldpath, newpath, args) {
        const _this = this;
        external_underscore_default().each(this.getComponentsWithPath(oldpath), function (c) {
            const newname = newpath + c.name.substring(oldpath.length);
            _this.renameComponent(c, newname, args);
        });
    }
    applySettingsPatch(p) {
        const settings = this.getSettings();
        for (const name in p) {
            const value = p[name];
            if (value === null)
                settings[name] = undefined;
            else
                settings[name] = value;
        }
        this.setSettings(settings);
    }
    // Applies a patch to the project, optionally asks user for permission
    // or notifies user
    /* applyPatch(patch) {
      var _this = this;
  
      function applyPatch(confirmed) {
        // Apply the regular or dismiss patches depending on if the user confirmed or not
        var patches = confirmed ? patch.nodePatches : patch.dismissPatches;
        for (var i in patches) {
          var p = patches[i];
          var node = _this.findNodeWithId(p.nodeId);
          node && node.applyPatch(p);
        }
  
        if (patch.settingsPatch) _this.applySettingsPatch(patch.settingsPatch);
      }
  
      if (patch.notifyUser) {
        // Apply the patch but and notify the user
        applyPatch(true);
        WarningsModel.instance.setWarning(
          {
            key: 'patch-' + patch.key
          },
          {
            type: 'patch-notify',
            title: 'The project has been patched',
            message: patch.message,
            onPatch: function () {
              WarningsModel.instance.setWarning(
                {
                  key: 'patch-' + patch.key
                },
                undefined
              );
              applyPatch(true);
            }
          }
        );
      } else if (patch.askPermission) {
        // Ask permission, if the user declines then the dismiss patches will be applied
        // instead
        WarningsModel.instance.setWarning(
          {
            key: 'patch-' + patch.key
          },
          {
            type: 'patch-confirm',
            title: 'The project has been patched',
            message: patch.message,
            onPatch: function () {
              WarningsModel.instance.setWarning(
                {
                  key: 'patch-' + patch.key
                },
                undefined
              );
              applyPatch(true);
            },
            onDismiss: function () {
              WarningsModel.instance.setWarning(
                {
                  key: 'patch-' + patch.key
                },
                undefined
              );
              applyPatch(false);
            }
          }
        );
      } else {
        // Simply apply the patches
        applyPatch(true);
      }
    }*/
    // Settings
    getSettings() {
        return this.settings ? this.settings : {};
    }
    setSettings(settings) {
        this.settings = settings;
        this.notifyListeners('settingsChanged');
    }
    setSetting(name, value) {
        if (this.settings[name] === value) {
            return;
        }
        if (value === undefined) {
            delete this.settings[name];
        }
        else {
            this.settings[name] = value;
        }
        this.notifyListeners('settingsChanged');
    }
    resolveColor(color) {
        const styles = this.getMetaData('styles');
        return styles && styles.colors && styles.colors[color] ? styles.colors[color] : color;
    }
    // Name
    rename(name) {
        this.name = name;
        this.notifyListeners('renamed', {
            oldName: name
        });
    }
    // Thumbnail URI
    getThumbnailURI() {
        return this.thumbnailURI;
    }
    setThumbnailFromDataURI(uri) {
        this.thumbnailURI = uri;
        this.notifyListeners('thumbnailChanged');
    }
    // Save to directory
    toDirectory(retainedProjectDirectory, callback) {
        // This function stores the project in project json
        // First it writes to a tmp file, make sure it is correctly written and then moves it to project.json
        // This is to avoid project files becomming corrupted in the case of a process exit
        const projectJson = this.toJSON();
        //optimize the file by removing child x,y since they're calculated from the root positions during layout
        //reduces the amount of differences between versions _alot_ as well
        stripNodeChildPositions(projectJson);
        const tmpProjectPath = retainedProjectDirectory + '/project-tmp.json';
        src.filesystem
            .writeJson(tmpProjectPath, projectJson)
            // Make sure tmp file was written correctly
            .then(() => verifyJsonFile(tmpProjectPath))
            .then((validJson) => {
            if (!validJson) {
                callback &&
                    callback({
                        result: 'failure',
                        message: 'Error writing project file.'
                    });
                src.filesystem.removeFile(tmpProjectPath);
                return;
            }
            // Move tmp file to project.json
            src.filesystem
                .renameFile(tmpProjectPath, retainedProjectDirectory + '/project.json')
                .then(() => {
                callback &&
                    callback({
                        result: 'success'
                    });
            })
                .catch(() => {
                callback &&
                    callback({
                        result: 'failure',
                        message: 'Error writing project file.'
                    });
            });
        })
            .catch(() => {
            callback &&
                callback({
                    result: 'failure',
                    message: 'Error writing project file.'
                });
        });
    }
    // Project lessons
    isLesson() {
        return this.lesson !== undefined;
    }
    getLessonModel() {
        return this.lesson;
    }
    // Copy to folder
    copyFileToProjectDirectory(file, callback) {
        if (this._retainedProjectDirectory === undefined)
            return;
        const target = this._retainedProjectDirectory + '/' + file.name;
        src.filesystem
            .makeDirectory(src.filesystem.dirname(target))
            .then(() => {
            src.filesystem
                .copyFile(file.fullPath, target)
                .then(() => {
                callback &&
                    callback({
                        result: 'success'
                    }); // Write ended with success
            })
                .catch(() => {
                callback &&
                    callback({
                        result: 'failure',
                        message: 'Error copying file to project directory.'
                    });
            });
        })
            .catch(() => {
            callback &&
                callback({
                    result: 'failure',
                    message: 'Error copying file to project directory.'
                });
        });
    }
    // For each file in folder
    /*  ProjectModel.prototype._forEachFileInDirectory = function(dirEntry,callback,types) {
      var _this = this;
  
      var reader = dirEntry.createReader();
      reader.readEntries(function(results) {
        for(var i in results) {
          var fileEntry = results[i];
  
          if(fileEntry.isDirectory) {
            // Recurse into directory
            _this._forEachFileInDirectory(fileEntry,callback,types);
          }
          else {
            // Check the file ending then return the entry
            var parts = fileEntry.name.split('.');
            if(parts.length>0&&(types===undefined||types.indexOf(parts[parts.length-1].toLowerCase())!==-1)) {
              callback&&callback(fileEntry);
            }
          }
        }
  
      },function() {
        callback&&callback({result:'failure',message:'Failed to read project directory'});
      });
    }
  
    ProjectModel.prototype.forEachFileInProjectDirectory = function(callback,types) {
      var _this = this;
  
      if(this._retainedProjectDirectory === undefined) return;
  
      FileSystem.instance.restoreEntry(this._retainedProjectDirectory,function(projectDirectoryEntry) {
        _this._forEachFileInDirectory(projectDirectoryEntry,callback,types);
      });
    }*/
    _listFilesInDirectory(dirEntry, callback, args, _files) {
        const _this = this;
        let files = _files ? _files : [];
        src.filesystem
            .listDirectory(dirEntry)
            .then((results) => {
            let dirs = 0;
            for (const i in results) {
                const fileEntry = results[i];
                if (args && args.ignoreFullPath && args.ignoreFullPath.indexOf(fileEntry.fullPath) !== -1)
                    continue; // Ignore files if specifed
                if (fileEntry.isDirectory) {
                    // Recurse into directory
                    dirs++;
                    _this._listFilesInDirectory(fileEntry.fullPath, function (directoryFiles) {
                        if (directoryFiles)
                            files = files.concat(directoryFiles);
                        dirs--;
                        if (dirs === 0)
                            callback(files);
                    }, args);
                }
                else {
                    // Check the file ending then return the entry
                    const parts = fileEntry.name.split('.');
                    if (parts.length > 0 &&
                        (args === undefined ||
                            args.types === undefined ||
                            args.types.indexOf(parts[parts.length - 1].toLowerCase()) !== -1)) {
                        files.push(fileEntry);
                    }
                }
            }
            if (dirs === 0)
                callback(files);
        })
            .catch(() => callback());
    }
    listFilesInProjectDirectory(callback, types, ignoreFullPath) {
        const _this = this;
        if (this._retainedProjectDirectory === undefined)
            return;
        _this._listFilesInDirectory(this._retainedProjectDirectory, callback, {
            types,
            ignoreFullPath
        });
    }
    listModules(callback) {
        listProjectModules(this)
            .then(callback)
            .catch((error) => {
            console.error(error);
            callback();
        });
    }
    readModules(callback) {
        readProjectModules(this)
            .then(callback)
            .catch((error) => {
            console.error(error);
            callback();
        });
    }
    getModuleAnnotationsForComponentWithName(name) {
        if (!this.componentAnnotations)
            return;
        return this.componentAnnotations[name];
    }
    /** TODO: Delete me? */
    getModulePreviews() {
        return this.previews && this.previews.length > 0 ? this.previews : undefined;
    }
    deleteComponentAllowed(component) {
        const annotationDoesntAllow = this.componentAnnotations &&
            this.componentAnnotations[component.fullName] &&
            this.componentAnnotations[component.fullName].deleteAllowed === false;
        if (annotationDoesntAllow) {
            return {
                canBeDelete: false,
                reason: "This component can't be deleted"
            };
        }
        const isRootComponent = this.getRootComponent() === component;
        if (isRootComponent) {
            return {
                canBeDelete: false,
                reason: "Home component can't be deleted"
            };
        }
        return {
            canBeDelete: true
        };
    }
    renameComponentAllowed(name) {
        if (this.componentAnnotations &&
            this.componentAnnotations[name] &&
            this.componentAnnotations[name].renameAllowed === false) {
            return false;
        }
        return true;
    }
    isComponentHidden(name) {
        if (this.componentAnnotations &&
            this.componentAnnotations[name] &&
            this.componentAnnotations[name].hidden === true) {
            return true;
        }
        return false;
    }
    setMetaData(key, data) {
        if (!this.metadata)
            this.metadata = {};
        this.metadata[key] = data;
        EventDispatcher.EventDispatcher.instance.notifyListeners('ProjectModel.metadataChanged', {
            key,
            data
        });
    }
    getMetaData(key) {
        if (!this.metadata)
            this.metadata = {};
        return this.metadata[key];
    }
    mergeMetadata(newData) {
        if (!this.metadata)
            this.metadata = {};
        const merge = (target, source) => {
            // Iterate through `source` properties and if an `Object` set property to merge of `target` and `source` properties
            for (const key of Object.keys(source)) {
                if (source[key] instanceof Object && key in target)
                    Object.assign(source[key], merge(target[key], source[key]));
            }
            // Join `target` and modified `source`
            Object.assign(target || {}, source);
            return target;
        };
        merge(this.metadata, newData);
        for (const key in newData) {
            EventDispatcher.EventDispatcher.instance.notifyListeners('ProjectModel.metadataChanged', {
                key,
                data: this.metadata[key]
            });
        }
    }
    // App Configuration Methods
    /**
     * Gets the app configuration from project metadata.
     * @returns The app config object
     */
    getAppConfig() {
        // Import types dynamically to avoid circular dependencies
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const { DEFAULT_APP_CONFIG } = __webpack_require__(54743);
        return this.getMetaData('appConfig') || DEFAULT_APP_CONFIG;
    }
    /**
     * Sets the app configuration in project metadata.
     * @param config - The app config to save
     */
    setAppConfig(config) {
        this.setMetaData('appConfig', config);
    }
    /**
     * Updates the app configuration with partial values.
     * @param updates - Partial app config updates
     */
    updateAppConfig(updates) {
        const current = this.getAppConfig();
        this.setAppConfig({
            ...current,
            ...updates,
            identity: {
                ...current.identity,
                ...(updates.identity || {})
            },
            seo: {
                ...current.seo,
                ...(updates.seo || {})
            },
            pwa: updates.pwa ? { ...current.pwa, ...updates.pwa } : current.pwa
        });
    }
    /**
     * Gets all config variables.
     * @returns Array of config variables
     */
    getConfigVariables() {
        return this.getAppConfig().variables || [];
    }
    /**
     * Sets or updates a config variable.
     * @param variable - The config variable to set
     */
    setConfigVariable(variable) {
        const config = this.getAppConfig();
        const index = config.variables.findIndex((v) => v.key === variable.key);
        if (index >= 0) {
            config.variables[index] = variable;
        }
        else {
            config.variables.push(variable);
        }
        this.setAppConfig(config);
    }
    /**
     * Removes a config variable by key.
     * @param key - The variable key to remove
     */
    removeConfigVariable(key) {
        const config = this.getAppConfig();
        config.variables = config.variables.filter((v) => v.key !== key);
        this.setAppConfig(config);
    }
    createNewVariant(name, node) {
        let variant = this.variants.find((v) => v.name === name && v.typename === node.type.localName);
        if (variant !== undefined)
            return; // Variant already exists
        variant = new VariantModel({
            name: name,
            typename: node.type.localName
        });
        if (node.variant !== undefined) {
            // Node has a variant already, copy params
            variant.updateFromVariant(node.variant);
        }
        variant.updateFromNode(node);
        this.variants.push(variant);
        this.notifyListeners('variantCreated', {
            variant: variant
        });
        return variant;
    }
    updateVariant(name, node) {
        const variant = this.variants.find((v) => v.name === name && v.typename === node.type.localName);
        if (variant === undefined)
            return false; // Variant does not exist
        variant.updateFromNode(node);
        this.notifyListeners('variantUpdated', {
            variant: variant
        });
        return variant;
    }
    isVariantUsed(variant) {
        let isUsed = false;
        this.forEachComponent((c) => {
            c.forEachNode((n) => {
                if (n.variant === variant)
                    isUsed = true;
            });
        });
        return isUsed;
    }
    addVariant(variant, args) {
        const _v = this.variants.find((v) => v.name === variant.name && v.typename === variant.typename);
        if (_v !== undefined)
            return false; // Variant already exists
        this.variants.push(variant);
        this.notifyListeners('variantAdded', {
            variant: variant
        });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: 'add variant',
                do: () => {
                    this.addVariant(variant);
                },
                undo: () => {
                    const idx = this.variants.indexOf(variant);
                    this.variants.splice(idx, 1);
                    this.notifyListeners('variantDeleted', {
                        variant: variant
                    });
                }
            });
        }
        return true;
    }
    deleteVariant(variant, args) {
        const variantIdx = this.variants.findIndex((v) => v === variant);
        if (variantIdx !== -1) {
            this.variants.splice(variantIdx, 1);
            this.notifyListeners('variantDeleted', {
                variant: variant
            });
            // Undo
            if (args && args.undo) {
                const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
                undo.push({
                    label: 'rename variant',
                    do: () => {
                        this.deleteVariant(variant);
                    },
                    undo: () => {
                        this.variants.push(variant);
                        this.notifyListeners('variantCreated', {
                            variant: variant
                        });
                    }
                });
            }
        }
    }
    renameVariant(variant, newName, args) {
        const oldName = variant.name;
        variant.name = newName;
        this.notifyListeners('variantRenamed', {
            variant: variant,
            oldName: oldName
        });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: 'rename variant',
                do: () => {
                    this.renameVariant(variant, newName);
                },
                undo: () => {
                    this.renameVariant(variant, oldName);
                }
            });
        }
    }
    findVariant(name, nodetype) {
        return this.variants.find((v) => v.name === name && v.typename === nodetype.localName);
    }
    findVariantsForNodeType(nodetype) {
        return this.variants.filter((v) => v.typename === nodetype.localName && v.name !== undefined);
    }
    getAllVariants() {
        return this.variants;
    }
    scheduleEvaluateHealth() {
        const _this = this;
        if (this.evaluatehealthScheduled)
            return;
        this.evaluatehealthScheduled = true;
        setTimeout(function () {
            _this.evaluatehealthScheduled && _this.evaluateHealth();
            _this.evaluatehealthScheduled = false;
        }, 2000);
    }
    evaluateHealth() {
        if (!nodelibrary/* NodeLibrary */.m.instance.isLoaded())
            return;
        if (this !== ProjectModel.instance)
            return; // Only evaluate health for main project
        //  if (!NodeLibrary.instance.isModuleRegistered(this)) return; // This module is not registered in the node library, no need to eval health
        if (this.variants !== undefined)
            this.variants.forEach((v) => v.evaluateHealth());
        //Check for duplicate IDs
        //Note: can happen in older projects where a component might be missing an id and it's renamed and later merged with version control
        const allNodesIds = new Set();
        const duplicates = [];
        for (const component of this.getComponents()) {
            component.forEachNode((node) => {
                if (allNodesIds.has(node.id)) {
                    duplicates.push([component, node]);
                }
                else {
                    allNodesIds.add(node.id);
                }
            });
        }
        if (duplicates.length) {
            console.group('WARNING: The project has nodes that share the same ID, which will cause severe issues. Duplicates:');
            for (const [component, node] of duplicates) {
                console.log(`Node Id: ${node.id}. Component: ${component.fullName}`);
            }
            console.groupEnd();
        }
    }
    // to - from JSON
    toJSON() {
        const json = {
            name: this.name,
            components: [],
            settings: this.settings,
            rootNodeId: this.rootNode ? this.rootNode.id : undefined,
            // thumbnailURI:this.thumbnailURI,
            version: this.version,
            runtimeVersion: this.runtimeVersion,
            lesson: this.lesson ? this.lesson.toJSON() : undefined,
            metadata: this.metadata,
            variants: this.variants.map((v) => v.toJSON())
            //   deviceSettings:this.deviceSettings,
        };
        for (const i in this.components) {
            json.components.push(this.components[i].toJSON());
        }
        //sort so the git diff is as small as possible (sometimes components get re-arranged in the array)
        json.components.sort((a, b) => a.name.localeCompare(b.name));
        return json;
    }
}
ProjectModel.version = '1';
ProjectModel.Upgraders = {
    0: function (project) {
        // Upgrade project from 0 to 1, inferred types are removed and = should become * on
        // node instance ports
        project.forEachComponent(function (c) {
            c.forEachNode(function (n) {
                external_underscore_default().each(n.ports, function (p) {
                    if (p.type === '=')
                        p.type = '*';
                    else if (p.type.name === '=')
                        p.type.name = '*';
                });
            });
        });
        // Project upgraded to version 1
        project.version = '1';
    },
    1: function (project) {
        // Upgrade to version 2 (support for variants, state parameters and transitions)
        project.version = '2';
    },
    2: function (project) {
        // Upgrade to version 2 (support for comments)
        project.version = '3';
    },
    3: function (project) {
        // Upgrade event senders to use string lists instead of PortEditor
        project.version = '4';
    }
};
// Track when the current project instance is changed, keep track of changes on the instance
ProjectModel._instance = undefined;
// Watch if the project root is removed
EventDispatcher.EventDispatcher.instance.on('Model.nodeRemoved', function (e) {
    if (ProjectModel.instance && ProjectModel.instance.getRootNode() === e.args.model) {
        ProjectModel.instance.setRootNode(undefined);
    }
}, null);
function stripNodeChildPositions(json) {
    function recurse(node) {
        if (!node.children)
            return;
        for (const child of node.children) {
            delete child.x;
            delete child.y;
            recurse(child);
        }
    }
    if (!json)
        return;
    json.components &&
        json.components.forEach((comp) => {
            comp.graph &&
                comp.graph.roots &&
                comp.graph.roots.forEach((root) => {
                    recurse(root);
                });
        });
}
// Project saver, saves current project when a change to a model occurs
let saveOnModelChange = true;
let saveTimeout;
const ignoreEvents = [
    'Model.thumbnailChanged',
    'Model.inspectorAdded',
    'Model.inspectorRemoved',
    'Model.itemsChanged',
    'Model.activeChanged',
    'Model.warningsChanged',
    'Model.GetCurrentFrontends',
    'Model.GetAllEnvironments',
    'Model.myProjectsChanged',
    'Model.moduleRegistered',
    'Model.libraryUpdated',
    'Model.documentChanged',
    'Model.nodeSelected',
    'Model.selectNode',
    'Model.moduleUnregistered',
    'Model.exitEditor',
    'Model.lessonProgressChanged',
    'Model.instancePortsChanged',
    'Model.0',
    'Model.1',
    'Model.2'
];
EventDispatcher.EventDispatcher.instance.on('Model.*', function (event, eventName) {
    if (ignoreEvents.indexOf(eventName) !== -1)
        return;
    if (!saveOnModelChange)
        return;
    clearTimeout(saveTimeout);
    saveTimeout = setTimeout(saveProject, 1000);
}, null);
function saveProject() {
    if (!ProjectModel.instance)
        return;
    // CRITICAL: Do not save read-only projects (e.g., legacy projects opened for inspection)
    if (ProjectModel.instance._isReadOnly) {
        console.log('⚠️  Skipping auto-save: Project is in read-only mode');
        return;
    }
    if (ProjectModel.instance._retainedProjectDirectory) {
        // Project is loaded from directory, save it
        ProjectModel.instance.toDirectory(ProjectModel.instance._retainedProjectDirectory, function (r) {
            if (r.result !== 'success') {
                console.log(r.message);
                //retry in 3 seconds
                clearTimeout(saveTimeout);
                saveTimeout = setTimeout(saveProject, 3000);
                EventDispatcher.EventDispatcher.instance.emit('ProjectModel.saveFailedRetryScheduled');
            }
            else {
                console.log('Project saved ' + new Date()); // Project is saved to disk, start the watch timer
                EventDispatcher.EventDispatcher.instance.emit('ProjectModel.projectSavedToDisk');
                //startWatchTimeOut();
            }
        });
    }
    else {
        // The project is not loaded from a directory, store to local store
        localStorage['project'] = JSON.stringify(ProjectModel.instance.toJSON(), null, 3);
        console.log('Project stored to local storage ' + new Date());
    }
}


/***/ }),

/***/ 6386:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPalette = function SvgPalette(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M8.05486 12.9785C8.05486 13.5307 7.60721 13.9784 7.05502 13.9784C6.50282 13.9784 6.05518 13.5307 6.05518 12.9785C6.05518 12.4263 6.50282 11.9787 7.05502 11.9787C7.60721 11.9787 8.05486 12.4263 8.05486 12.9785Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M9.69043 8.8385C9.69043 9.39079 9.24271 9.8385 8.69043 9.8385C8.13814 9.8385 7.69043 9.39079 7.69043 8.8385C7.69043 8.28622 8.13814 7.8385 8.69043 7.8385C9.24271 7.8385 9.69043 8.28622 9.69043 8.8385Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M13.9253 7.36934C13.9253 7.92162 13.4776 8.36934 12.9253 8.36934C12.373 8.36934 11.9253 7.92162 11.9253 7.36934C11.9253 6.81705 12.373 6.36934 12.9253 6.36934C13.4776 6.36934 13.9253 6.81705 13.9253 7.36934Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.7762 10.1072C17.7762 10.6582 17.3295 11.1049 16.7785 11.1049C16.2274 11.1049 15.7808 10.6582 15.7808 10.1072C15.7808 9.55621 16.2274 9.10953 16.7785 9.10953C17.3295 9.10953 17.7762 9.55621 17.7762 10.1072Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.0613 21.936C9.66129 21.936 9.27129 21.866 8.89129 21.736C6.73129 20.976 4.89129 19.466 3.72129 17.496C2.56129 15.526 2.13129 13.186 2.50129 10.926C2.88129 8.66604 4.04129 6.59604 5.78129 5.10604C7.53129 3.61604 9.75129 2.77604 12.0413 2.75604H12.1513C14.7213 2.75604 17.1513 3.75604 18.9813 5.56604C19.9013 6.45604 20.6313 7.51604 21.1313 8.70604C21.6413 9.89604 21.9013 11.156 21.9013 12.446C21.9013 13.206 21.8313 13.966 21.6513 14.696C21.4813 15.466 21.0413 16.176 20.4213 16.676C19.8013 17.176 18.9713 17.426 18.2113 17.436H14.2113C14.0413 17.436 13.8813 17.506 13.7613 17.626C13.6413 17.746 13.5713 17.906 13.5713 18.076V18.416C13.5713 18.976 13.4313 19.536 13.1813 20.036C12.9213 20.536 12.5513 20.966 12.0913 21.296C11.6313 21.626 11.1013 21.836 10.5413 21.916C10.3813 21.936 10.2113 21.946 10.0513 21.946L10.0613 21.936ZM12.0513 4.25604C10.1213 4.27604 8.24129 4.97604 6.76129 6.24604C5.29129 7.50604 4.30129 9.25604 3.98129 11.176C3.66129 13.086 4.03129 15.066 5.02129 16.736C6.01129 18.406 7.56129 19.686 9.39129 20.326C9.69129 20.436 10.0213 20.466 10.3413 20.416C10.6613 20.376 10.9713 20.246 11.2313 20.066C11.4913 19.876 11.7113 19.626 11.8613 19.346C12.0113 19.056 12.0913 18.736 12.0913 18.416V18.076C12.0913 17.506 12.3113 16.966 12.7213 16.566C13.1213 16.166 13.6713 15.936 14.2313 15.936H18.2413C18.6913 15.956 19.1513 15.786 19.5113 15.496C19.8713 15.206 20.1213 14.806 20.2213 14.366C20.3713 13.736 20.4313 13.096 20.4313 12.456C20.4313 11.366 20.2013 10.296 19.7813 9.29604C19.3513 8.29604 18.7413 7.39604 17.9613 6.63604C16.4113 5.09604 14.3513 4.25604 12.1813 4.25604H12.0813H12.0513Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPalette);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "eb18d176b55ea3c40261cb3a4efaebb8.svg");

/***/ }),

/***/ 6554:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/*
	Keeping name short for faster parsing.
	cslr = core selections layer rendering (div)
*/
.monaco-editor .lines-content .cslr {
	position: absolute;
}

.monaco-editor			.top-left-radius		{ border-top-left-radius: 3px; }
.monaco-editor			.bottom-left-radius		{ border-bottom-left-radius: 3px; }
.monaco-editor			.top-right-radius		{ border-top-right-radius: 3px; }
.monaco-editor			.bottom-right-radius	{ border-bottom-right-radius: 3px; }

.monaco-editor.hc-black .top-left-radius		{ border-top-left-radius: 0; }
.monaco-editor.hc-black .bottom-left-radius		{ border-bottom-left-radius: 0; }
.monaco-editor.hc-black .top-right-radius		{ border-top-right-radius: 0; }
.monaco-editor.hc-black .bottom-right-radius	{ border-bottom-right-radius: 0; }

.monaco-editor.hc-light .top-left-radius		{ border-top-left-radius: 0; }
.monaco-editor.hc-light .bottom-left-radius		{ border-bottom-left-radius: 0; }
.monaco-editor.hc-light .top-right-radius		{ border-top-right-radius: 0; }
.monaco-editor.hc-light .bottom-right-radius	{ border-bottom-right-radius: 0; }
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/selections/selections.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;;;CAGC;AACD;CACC,kBAAkB;AACnB;;AAEA,qCAAqC,2BAA2B,EAAE;AAClE,wCAAwC,8BAA8B,EAAE;AACxE,sCAAsC,4BAA4B,EAAE;AACpE,wCAAwC,+BAA+B,EAAE;;AAEzE,4CAA4C,yBAAyB,EAAE;AACvE,+CAA+C,4BAA4B,EAAE;AAC7E,6CAA6C,0BAA0B,EAAE;AACzE,+CAA+C,6BAA6B,EAAE;;AAE9E,4CAA4C,yBAAyB,EAAE;AACvE,+CAA+C,4BAA4B,EAAE;AAC7E,6CAA6C,0BAA0B,EAAE;AACzE,+CAA+C,6BAA6B,EAAE","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/*\n\tKeeping name short for faster parsing.\n\tcslr = core selections layer rendering (div)\n*/\n.monaco-editor .lines-content .cslr {\n\tposition: absolute;\n}\n\n.monaco-editor\t\t\t.top-left-radius\t\t{ border-top-left-radius: 3px; }\n.monaco-editor\t\t\t.bottom-left-radius\t\t{ border-bottom-left-radius: 3px; }\n.monaco-editor\t\t\t.top-right-radius\t\t{ border-top-right-radius: 3px; }\n.monaco-editor\t\t\t.bottom-right-radius\t{ border-bottom-right-radius: 3px; }\n\n.monaco-editor.hc-black .top-left-radius\t\t{ border-top-left-radius: 0; }\n.monaco-editor.hc-black .bottom-left-radius\t\t{ border-bottom-left-radius: 0; }\n.monaco-editor.hc-black .top-right-radius\t\t{ border-top-right-radius: 0; }\n.monaco-editor.hc-black .bottom-right-radius\t{ border-bottom-right-radius: 0; }\n\n.monaco-editor.hc-light .top-left-radius\t\t{ border-top-left-radius: 0; }\n.monaco-editor.hc-light .bottom-left-radius\t\t{ border-bottom-left-radius: 0; }\n.monaco-editor.hc-light .top-right-radius\t\t{ border-top-right-radius: 0; }\n.monaco-editor.hc-light .bottom-right-radius\t{ border-bottom-right-radius: 0; }\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 6875:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   V: () => (/* binding */ push),
/* harmony export */   Y: () => (/* binding */ pushDelete)
/* harmony export */ });
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81882);
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(dugite__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(85869);
/* harmony import */ var _git_error__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(55952);
/* harmony import */ var _progress__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(51436);
/* harmony import */ var _authentication__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(38495);





async function pushDelete(repositoryDir, remoteName, branchName) {
    const networkArguments = await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .gitNetworkArguments */ .X)(repositoryDir);
    const args = [
        ...networkArguments,
        "push",
        remoteName,
        "--delete",
        branchName,
    ];
    const expectedErrors = new Set(_authentication__WEBPACK_IMPORTED_MODULE_4__/* .AuthenticationErrors */ .A);
    expectedErrors.add(dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.ProtectedBranchForcePush);
    let opts = {
        expectedErrors,
    };
    const result = await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(args, repositoryDir, "push", opts);
    if (result.gitErrorDescription) {
        throw new _git_error__WEBPACK_IMPORTED_MODULE_2__/* .GitError */ .XS(result, args);
    }
}
/**
 * Push from the remote to the branch, optionally setting the upstream.
 *
 * @param repository - The repository from which to push
 *
 * @param remote - The remote to push the specified branch to
 *
 * @param localBranch - The local branch to push
 *
 * @param remoteBranch - The remote branch to push to
 *
 * @param tagsToPush - The tags to push along with the branch.
 *
 * @param options - Optional customizations for the push execution.
 *                  see PushOptions for more information.
 *
 * @param progressCallback - An optional function which will be invoked
 *                           with information about the current progress
 *                           of the push operation. When provided this enables
 *                           the '--progress' command line flag for
 *                           'git push'.
 */
async function push(repositoryDir, remote, localBranch, remoteBranch, tagsToPush, options = {
    forceWithLease: false,
}, progressCallback) {
    const networkArguments = await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .gitNetworkArguments */ .X)(repositoryDir);
    const args = [
        ...networkArguments,
        "push",
        remote.name,
        remoteBranch ? `${localBranch}:${remoteBranch}` : localBranch,
    ];
    if (tagsToPush !== null) {
        args.push(...tagsToPush);
    }
    if (!remoteBranch) {
        args.push("--set-upstream");
    }
    else if (options.forceWithLease === true) {
        args.push("--force-with-lease");
    }
    const expectedErrors = new Set(_authentication__WEBPACK_IMPORTED_MODULE_4__/* .AuthenticationErrors */ .A);
    expectedErrors.add(dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.ProtectedBranchForcePush);
    let opts = {
        expectedErrors,
    };
    if (progressCallback) {
        args.push("--progress");
        const title = `Pushing to ${remote.name}`;
        const kind = "push";
        opts = await (0,_progress__WEBPACK_IMPORTED_MODULE_3__/* .executionOptionsWithProgress */ .s_)({ ...opts }, new _progress__WEBPACK_IMPORTED_MODULE_3__/* .PushProgressParser */ .LP(), (progress) => {
            const description = progress.kind === "progress" ? progress.details.text : progress.text;
            const value = progress.percent;
            progressCallback({
                kind,
                title,
                description,
                value,
                remote: remote.name,
                branch: localBranch,
            });
        });
        // Initial progress
        progressCallback({
            kind: "push",
            title,
            value: 0,
            remote: remote.name,
            branch: localBranch,
        });
    }
    const result = await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(args, repositoryDir, "push", opts);
    if (result.gitErrorDescription) {
        throw new _git_error__WEBPACK_IMPORTED_MODULE_2__/* .GitError */ .XS(result, args);
    }
    return true;
}


/***/ }),

/***/ 6951:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.quick-input-widget {
	font-size: 13px;
}

.quick-input-widget .monaco-highlighted-label .highlight,
.quick-input-widget .monaco-highlighted-label .highlight {
	color: #0066BF;
}

.vs .quick-input-widget .monaco-list-row.focused .monaco-highlighted-label .highlight,
.vs .quick-input-widget .monaco-list-row.focused .monaco-highlighted-label .highlight {
	color: #9DDDFF;
}

.vs-dark .quick-input-widget .monaco-highlighted-label .highlight,
.vs-dark .quick-input-widget .monaco-highlighted-label .highlight {
	color: #0097fb;
}

.hc-black .quick-input-widget .monaco-highlighted-label .highlight,
.hc-black .quick-input-widget .monaco-highlighted-label .highlight {
	color: #F38518;
}

.hc-light .quick-input-widget .monaco-highlighted-label .highlight,
.hc-light .quick-input-widget .monaco-highlighted-label .highlight {
	color: #0F4A85;
}

.monaco-keybinding > .monaco-keybinding-key {
	background-color: rgba(221, 221, 221, 0.4);
	border: solid 1px rgba(204, 204, 204, 0.4);
	border-bottom-color: rgba(187, 187, 187, 0.4);
	box-shadow: inset 0 -1px 0 rgba(187, 187, 187, 0.4);
	color: #555;
}

.hc-black .monaco-keybinding > .monaco-keybinding-key {
	background-color: transparent;
	border: solid 1px rgb(111, 195, 223);
	box-shadow: none;
	color: #fff;
}

.hc-light .monaco-keybinding > .monaco-keybinding-key {
	background-color: transparent;
	border: solid 1px #0F4A85;
	box-shadow: none;
	color: #292929;
}

.vs-dark .monaco-keybinding > .monaco-keybinding-key {
	background-color: rgba(128, 128, 128, 0.17);
	border: solid 1px rgba(51, 51, 51, 0.6);
	border-bottom-color: rgba(68, 68, 68, 0.6);
	box-shadow: inset 0 -1px 0 rgba(68, 68, 68, 0.6);
	color: #ccc;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickInput/standaloneQuickInput.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,eAAe;AAChB;;AAEA;;CAEC,cAAc;AACf;;AAEA;;CAEC,cAAc;AACf;;AAEA;;CAEC,cAAc;AACf;;AAEA;;CAEC,cAAc;AACf;;AAEA;;CAEC,cAAc;AACf;;AAEA;CACC,0CAA0C;CAC1C,0CAA0C;CAC1C,6CAA6C;CAC7C,mDAAmD;CACnD,WAAW;AACZ;;AAEA;CACC,6BAA6B;CAC7B,oCAAoC;CACpC,gBAAgB;CAChB,WAAW;AACZ;;AAEA;CACC,6BAA6B;CAC7B,yBAAyB;CACzB,gBAAgB;CAChB,cAAc;AACf;;AAEA;CACC,2CAA2C;CAC3C,uCAAuC;CACvC,0CAA0C;CAC1C,gDAAgD;CAChD,WAAW;AACZ","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.quick-input-widget {\n\tfont-size: 13px;\n}\n\n.quick-input-widget .monaco-highlighted-label .highlight,\n.quick-input-widget .monaco-highlighted-label .highlight {\n\tcolor: #0066BF;\n}\n\n.vs .quick-input-widget .monaco-list-row.focused .monaco-highlighted-label .highlight,\n.vs .quick-input-widget .monaco-list-row.focused .monaco-highlighted-label .highlight {\n\tcolor: #9DDDFF;\n}\n\n.vs-dark .quick-input-widget .monaco-highlighted-label .highlight,\n.vs-dark .quick-input-widget .monaco-highlighted-label .highlight {\n\tcolor: #0097fb;\n}\n\n.hc-black .quick-input-widget .monaco-highlighted-label .highlight,\n.hc-black .quick-input-widget .monaco-highlighted-label .highlight {\n\tcolor: #F38518;\n}\n\n.hc-light .quick-input-widget .monaco-highlighted-label .highlight,\n.hc-light .quick-input-widget .monaco-highlighted-label .highlight {\n\tcolor: #0F4A85;\n}\n\n.monaco-keybinding > .monaco-keybinding-key {\n\tbackground-color: rgba(221, 221, 221, 0.4);\n\tborder: solid 1px rgba(204, 204, 204, 0.4);\n\tborder-bottom-color: rgba(187, 187, 187, 0.4);\n\tbox-shadow: inset 0 -1px 0 rgba(187, 187, 187, 0.4);\n\tcolor: #555;\n}\n\n.hc-black .monaco-keybinding > .monaco-keybinding-key {\n\tbackground-color: transparent;\n\tborder: solid 1px rgb(111, 195, 223);\n\tbox-shadow: none;\n\tcolor: #fff;\n}\n\n.hc-light .monaco-keybinding > .monaco-keybinding-key {\n\tbackground-color: transparent;\n\tborder: solid 1px #0F4A85;\n\tbox-shadow: none;\n\tcolor: #292929;\n}\n\n.vs-dark .monaco-keybinding > .monaco-keybinding-key {\n\tbackground-color: rgba(128, 128, 128, 0.17);\n\tborder: solid 1px rgba(51, 51, 51, 0.6);\n\tborder-bottom-color: rgba(68, 68, 68, 0.6);\n\tbox-shadow: inset 0 -1px 0 rgba(68, 68, 68, 0.6);\n\tcolor: #ccc;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 7349:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Section-module__Root--gIgyK{display:flex;flex-direction:column;overflow:hidden}.Section-module__Root--gIgyK.Section-module__has-visible-overflow--FvS74{overflow:visible}.Section-module__Root--gIgyK.Section-module__is-variant-default--MUDJD{background-color:var(--theme-color-bg-2)}.Section-module__Root--gIgyK.Section-module__is-variant-default--MUDJD:not(:last-child){border-bottom:1px solid var(--theme-color-bg-1)}.Section-module__Root--gIgyK.Section-module__is-variant-default--MUDJD.Section-module__has-top-divider--b_YSG{border-top:1px solid var(--theme-color-bg-1)}.Section-module__Root--gIgyK.Section-module__is-variant-panel--FfnSD,.Section-module__Root--gIgyK.Section-module__is-variant-panel-shy--kenT2{background-color:var(--theme-color-bg-2)}.Section-module__Root--gIgyK.Section-module__is-variant-panel-shy--kenT2:not(:first-child),.Section-module__Root--gIgyK.Section-module__is-variant-panel-shy--kenT2.Section-module__has-top-divider--b_YSG{border-top:1px solid var(--theme-color-bg-1)}.Section-module__Root--gIgyK.Section-module__is-variant-in-modal--KISsi{background-color:var(--theme-color-bg-4)}.Section-module__Header--G63VE{display:flex;align-items:center;justify-content:space-between;flex:0 0 36px;min-height:36px;padding:0 var(--spacing-2-5) 0 var(--spacing-4);user-select:none}.Section-module__Header--G63VE.Section-module__is-variant-panel--FfnSD{background-color:var(--theme-color-bg-3)}.Section-module__Header--G63VE.Section-module__is-variant-panel-shy--kenT2{background-color:rgba(0,0,0,0)}.Section-module__Header--G63VE.Section-module__is-variant-in-modal--KISsi{background-color:var(--theme-color-bg-3)}.Section-module__Header--G63VE.Section-module__is-collapsable--EEP8c{padding-right:0;cursor:pointer}.Section-module__Header--G63VE.Section-module__is-collapsable--EEP8c:hover{background-color:var(--theme-color-bg-hover)}.Section-module__Body--j7pP9{overflow:hidden overlay;padding-top:var(--spacing-2)}.Section-module__Body--j7pP9.Section-module__is-variant-in-modal--KISsi{padding:0}.Section-module__Body--j7pP9.Section-module__has-visible-overflow--FvS74{overflow:visible}.Section-module__Body--j7pP9.Section-module__has-bottom-spacing--UNJ4y{padding-bottom:var(--spacing-3)}.Section-module__Body--j7pP9.Section-module__has-gutter--BYt1h{padding:var(--spacing-section-padding)}.Section-module__Body--j7pP9::-webkit-scrollbar{width:8px}.Section-module__Body--j7pP9::-webkit-scrollbar-track{background:var(--theme-color-bg-3)}.Section-module__Body--j7pP9::-webkit-scrollbar-thumb{background:var(--theme-color-bg-5);border-radius:var(--radius-full)}.Section-module__Body--j7pP9::-webkit-scrollbar-thumb:hover{background:var(--theme-color-fg-muted)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/sidebar/Section/Section.module.scss"],"names":[],"mappings":"AAAA,6BACE,YAAA,CACA,qBAAA,CACA,eAAA,CAEA,yEACE,gBAAA,CAGF,uEACE,wCAAA,CAEA,wFACE,+CAAA,CAGF,8GACE,4CAAA,CAIJ,8IAEE,wCAAA,CAIA,2MAEE,4CAAA,CAIJ,wEACE,wCAAA,CAIJ,+BACE,YAAA,CACA,kBAAA,CACA,6BAAA,CAGA,aAAA,CACA,eAAA,CACA,+CAAA,CAEA,gBAAA,CAEA,uEACE,wCAAA,CAGF,2EACE,8BAAA,CAGF,0EACE,wCAAA,CAGF,qEACE,eAAA,CACA,cAAA,CAEA,2EACE,4CAAA,CAKN,6BAEE,uBAAA,CACA,4BAAA,CAEA,wEACE,SAAA,CAGF,yEACE,gBAAA,CAGF,uEACE,+BAAA,CAGF,+DACE,sCAAA,CAIF,gDACE,SAAA,CAGF,sDACE,kCAAA,CAGF,sDACE,kCAAA,CACA,gCAAA,CAEA,4DACE,sCAAA","sourcesContent":[".Root {\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n\n  &.has-visible-overflow {\n    overflow: visible;\n  }\n\n  &.is-variant-default {\n    background-color: var(--theme-color-bg-2);\n\n    &:not(:last-child) {\n      border-bottom: 1px solid var(--theme-color-bg-1);\n    }\n\n    &.has-top-divider {\n      border-top: 1px solid var(--theme-color-bg-1);\n    }\n  }\n\n  &.is-variant-panel,\n  &.is-variant-panel-shy {\n    background-color: var(--theme-color-bg-2);\n  }\n\n  &.is-variant-panel-shy {\n    &:not(:first-child),\n    &.has-top-divider {\n      border-top: 1px solid var(--theme-color-bg-1);\n    }\n  }\n\n  &.is-variant-in-modal {\n    background-color: var(--theme-color-bg-4);\n  }\n}\n\n.Header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n\n  /* consistency */\n  flex: 0 0 36px;\n  min-height: 36px;\n  padding: 0 var(--spacing-2-5) 0 var(--spacing-4);\n\n  user-select: none;\n\n  &.is-variant-panel {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.is-variant-panel-shy {\n    background-color: transparent;\n  }\n\n  &.is-variant-in-modal {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.is-collapsable {\n    padding-right: 0;\n    cursor: pointer;\n\n    &:hover {\n      background-color: var(--theme-color-bg-hover);\n    }\n  }\n}\n\n.Body {\n  /* allow scrolling */\n  overflow: hidden overlay;\n  padding-top: var(--spacing-2);\n\n  &.is-variant-in-modal {\n    padding: 0;\n  }\n\n  &.has-visible-overflow {\n    overflow: visible;\n  }\n\n  &.has-bottom-spacing {\n    padding-bottom: var(--spacing-3);\n  }\n\n  &.has-gutter {\n    padding: var(--spacing-section-padding);\n  }\n\n  /* Custom scrollbar styling */\n  &::-webkit-scrollbar {\n    width: 8px;\n  }\n\n  &::-webkit-scrollbar-track {\n    background: var(--theme-color-bg-3);\n  }\n\n  &::-webkit-scrollbar-thumb {\n    background: var(--theme-color-bg-5);\n    border-radius: var(--radius-full);\n\n    &:hover {\n      background: var(--theme-color-fg-muted);\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Section-module__Root--gIgyK`,
	"has-visible-overflow": `Section-module__has-visible-overflow--FvS74`,
	"is-variant-default": `Section-module__is-variant-default--MUDJD`,
	"has-top-divider": `Section-module__has-top-divider--b_YSG`,
	"is-variant-panel": `Section-module__is-variant-panel--FfnSD`,
	"is-variant-panel-shy": `Section-module__is-variant-panel-shy--kenT2`,
	"is-variant-in-modal": `Section-module__is-variant-in-modal--KISsi`,
	"Header": `Section-module__Header--G63VE`,
	"is-collapsable": `Section-module__is-collapsable--EEP8c`,
	"Body": `Section-module__Body--j7pP9`,
	"has-bottom-spacing": `Section-module__has-bottom-spacing--UNJ4y`,
	"has-gutter": `Section-module__has-gutter--BYt1h`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 7412:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgJustifyContentSpaceEvenly = function SvgJustifyContentSpaceEvenly(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.6643 5.92615H8.06277C7.68401 5.92615 7.37695 6.18198 7.37695 6.49758V9.35472C7.37695 9.67031 7.68401 9.92615 8.06277 9.92615H17.6643C18.043 9.92615 18.3501 9.67031 18.3501 9.35472V6.49758C18.3501 6.18198 18.043 5.92615 17.6643 5.92615Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M8.06231 19.4261L17.6638 19.4261C18.0426 19.4261 18.3496 19.1703 18.3496 18.8547L18.3496 15.9976C18.3496 15.682 18.0426 15.4261 17.6638 15.4261L8.06231 15.4261C7.68354 15.4261 7.37649 15.682 7.37649 15.9976L7.37649 18.8547C7.37649 19.1703 7.68354 19.4261 8.06231 19.4261Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.86328 3.17615C3.86328 2.76193 4.22146 2.42615 4.6633 2.42615H21.0633C21.5051 2.42615 21.8633 2.76193 21.8633 3.17615C21.8633 3.59036 21.5051 3.92615 21.0633 3.92615H4.6633C4.22146 3.92615 3.86328 3.59036 3.86328 3.17615Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.86328 12.6761C3.86328 12.2619 4.22146 11.9261 4.6633 11.9261H21.0633C21.5051 11.9261 21.8633 12.2619 21.8633 12.6761C21.8633 13.0904 21.5051 13.4261 21.0633 13.4261H4.6633C4.22146 13.4261 3.86328 13.0904 3.86328 12.6761Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.8633 22.1761C21.8633 22.5904 21.5051 22.9261 21.0633 22.9261L4.66331 22.9261C4.22146 22.9261 3.86328 22.5904 3.86328 22.1761C3.86328 21.7619 4.22146 21.4261 4.66331 21.4261L21.0633 21.4261C21.5051 21.4261 21.8633 21.7619 21.8633 22.1761Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgJustifyContentSpaceEvenly);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "f0c55a9365384e8d4a6737957c3ae258.svg");

/***/ }),

/***/ 7444:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   KeyCode: () => (/* binding */ KeyCode),
/* harmony export */   KeyMod: () => (/* binding */ KeyMod)
/* harmony export */ });
var KeyCode;
(function (KeyCode) {
    KeyCode[KeyCode["DependsOnKbLayout"] = -1] = "DependsOnKbLayout";
    /**
     * Placed first to cover the 0 value of the enum.
     */
    KeyCode[KeyCode["Unknown"] = 0] = "Unknown";
    KeyCode[KeyCode["Backspace"] = 1] = "Backspace";
    KeyCode[KeyCode["Tab"] = 2] = "Tab";
    KeyCode[KeyCode["Enter"] = 3] = "Enter";
    KeyCode[KeyCode["Shift"] = 4] = "Shift";
    KeyCode[KeyCode["Ctrl"] = 5] = "Ctrl";
    KeyCode[KeyCode["Alt"] = 6] = "Alt";
    KeyCode[KeyCode["PauseBreak"] = 7] = "PauseBreak";
    KeyCode[KeyCode["CapsLock"] = 8] = "CapsLock";
    KeyCode[KeyCode["Escape"] = 9] = "Escape";
    KeyCode[KeyCode["Space"] = 10] = "Space";
    KeyCode[KeyCode["PageUp"] = 11] = "PageUp";
    KeyCode[KeyCode["PageDown"] = 12] = "PageDown";
    KeyCode[KeyCode["End"] = 13] = "End";
    KeyCode[KeyCode["Home"] = 14] = "Home";
    KeyCode[KeyCode["LeftArrow"] = 15] = "LeftArrow";
    KeyCode[KeyCode["UpArrow"] = 16] = "UpArrow";
    KeyCode[KeyCode["RightArrow"] = 17] = "RightArrow";
    KeyCode[KeyCode["DownArrow"] = 18] = "DownArrow";
    KeyCode[KeyCode["Insert"] = 19] = "Insert";
    KeyCode[KeyCode["Delete"] = 20] = "Delete";
    KeyCode[KeyCode["KEY_0"] = 21] = "KEY_0";
    KeyCode[KeyCode["KEY_1"] = 22] = "KEY_1";
    KeyCode[KeyCode["KEY_2"] = 23] = "KEY_2";
    KeyCode[KeyCode["KEY_3"] = 24] = "KEY_3";
    KeyCode[KeyCode["KEY_4"] = 25] = "KEY_4";
    KeyCode[KeyCode["KEY_5"] = 26] = "KEY_5";
    KeyCode[KeyCode["KEY_6"] = 27] = "KEY_6";
    KeyCode[KeyCode["KEY_7"] = 28] = "KEY_7";
    KeyCode[KeyCode["KEY_8"] = 29] = "KEY_8";
    KeyCode[KeyCode["KEY_9"] = 30] = "KEY_9";
    KeyCode[KeyCode["KEY_A"] = 31] = "KEY_A";
    KeyCode[KeyCode["KEY_B"] = 32] = "KEY_B";
    KeyCode[KeyCode["KEY_C"] = 33] = "KEY_C";
    KeyCode[KeyCode["KEY_D"] = 34] = "KEY_D";
    KeyCode[KeyCode["KEY_E"] = 35] = "KEY_E";
    KeyCode[KeyCode["KEY_F"] = 36] = "KEY_F";
    KeyCode[KeyCode["KEY_G"] = 37] = "KEY_G";
    KeyCode[KeyCode["KEY_H"] = 38] = "KEY_H";
    KeyCode[KeyCode["KEY_I"] = 39] = "KEY_I";
    KeyCode[KeyCode["KEY_J"] = 40] = "KEY_J";
    KeyCode[KeyCode["KEY_K"] = 41] = "KEY_K";
    KeyCode[KeyCode["KEY_L"] = 42] = "KEY_L";
    KeyCode[KeyCode["KEY_M"] = 43] = "KEY_M";
    KeyCode[KeyCode["KEY_N"] = 44] = "KEY_N";
    KeyCode[KeyCode["KEY_O"] = 45] = "KEY_O";
    KeyCode[KeyCode["KEY_P"] = 46] = "KEY_P";
    KeyCode[KeyCode["KEY_Q"] = 47] = "KEY_Q";
    KeyCode[KeyCode["KEY_R"] = 48] = "KEY_R";
    KeyCode[KeyCode["KEY_S"] = 49] = "KEY_S";
    KeyCode[KeyCode["KEY_T"] = 50] = "KEY_T";
    KeyCode[KeyCode["KEY_U"] = 51] = "KEY_U";
    KeyCode[KeyCode["KEY_V"] = 52] = "KEY_V";
    KeyCode[KeyCode["KEY_W"] = 53] = "KEY_W";
    KeyCode[KeyCode["KEY_X"] = 54] = "KEY_X";
    KeyCode[KeyCode["KEY_Y"] = 55] = "KEY_Y";
    KeyCode[KeyCode["KEY_Z"] = 56] = "KEY_Z";
    KeyCode[KeyCode["Meta"] = 57] = "Meta";
    KeyCode[KeyCode["ContextMenu"] = 58] = "ContextMenu";
    KeyCode[KeyCode["F1"] = 59] = "F1";
    KeyCode[KeyCode["F2"] = 60] = "F2";
    KeyCode[KeyCode["F3"] = 61] = "F3";
    KeyCode[KeyCode["F4"] = 62] = "F4";
    KeyCode[KeyCode["F5"] = 63] = "F5";
    KeyCode[KeyCode["F6"] = 64] = "F6";
    KeyCode[KeyCode["F7"] = 65] = "F7";
    KeyCode[KeyCode["F8"] = 66] = "F8";
    KeyCode[KeyCode["F9"] = 67] = "F9";
    KeyCode[KeyCode["F10"] = 68] = "F10";
    KeyCode[KeyCode["F11"] = 69] = "F11";
    KeyCode[KeyCode["F12"] = 70] = "F12";
    KeyCode[KeyCode["F13"] = 71] = "F13";
    KeyCode[KeyCode["F14"] = 72] = "F14";
    KeyCode[KeyCode["F15"] = 73] = "F15";
    KeyCode[KeyCode["F16"] = 74] = "F16";
    KeyCode[KeyCode["F17"] = 75] = "F17";
    KeyCode[KeyCode["F18"] = 76] = "F18";
    KeyCode[KeyCode["F19"] = 77] = "F19";
    KeyCode[KeyCode["NumLock"] = 78] = "NumLock";
    KeyCode[KeyCode["ScrollLock"] = 79] = "ScrollLock";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the ';:' key
     */
    KeyCode[KeyCode["US_SEMICOLON"] = 80] = "US_SEMICOLON";
    /**
     * For any country/region, the '+' key
     * For the US standard keyboard, the '=+' key
     */
    KeyCode[KeyCode["US_EQUAL"] = 81] = "US_EQUAL";
    /**
     * For any country/region, the ',' key
     * For the US standard keyboard, the ',<' key
     */
    KeyCode[KeyCode["US_COMMA"] = 82] = "US_COMMA";
    /**
     * For any country/region, the '-' key
     * For the US standard keyboard, the '-_' key
     */
    KeyCode[KeyCode["US_MINUS"] = 83] = "US_MINUS";
    /**
     * For any country/region, the '.' key
     * For the US standard keyboard, the '.>' key
     */
    KeyCode[KeyCode["US_DOT"] = 84] = "US_DOT";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the '/?' key
     */
    KeyCode[KeyCode["US_SLASH"] = 85] = "US_SLASH";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the '`~' key
     */
    KeyCode[KeyCode["US_BACKTICK"] = 86] = "US_BACKTICK";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the '[{' key
     */
    KeyCode[KeyCode["US_OPEN_SQUARE_BRACKET"] = 87] = "US_OPEN_SQUARE_BRACKET";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the '\|' key
     */
    KeyCode[KeyCode["US_BACKSLASH"] = 88] = "US_BACKSLASH";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the ']}' key
     */
    KeyCode[KeyCode["US_CLOSE_SQUARE_BRACKET"] = 89] = "US_CLOSE_SQUARE_BRACKET";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the ''"' key
     */
    KeyCode[KeyCode["US_QUOTE"] = 90] = "US_QUOTE";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     */
    KeyCode[KeyCode["OEM_8"] = 91] = "OEM_8";
    /**
     * Either the angle bracket key or the backslash key on the RT 102-key keyboard.
     */
    KeyCode[KeyCode["OEM_102"] = 92] = "OEM_102";
    KeyCode[KeyCode["NUMPAD_0"] = 93] = "NUMPAD_0";
    KeyCode[KeyCode["NUMPAD_1"] = 94] = "NUMPAD_1";
    KeyCode[KeyCode["NUMPAD_2"] = 95] = "NUMPAD_2";
    KeyCode[KeyCode["NUMPAD_3"] = 96] = "NUMPAD_3";
    KeyCode[KeyCode["NUMPAD_4"] = 97] = "NUMPAD_4";
    KeyCode[KeyCode["NUMPAD_5"] = 98] = "NUMPAD_5";
    KeyCode[KeyCode["NUMPAD_6"] = 99] = "NUMPAD_6";
    KeyCode[KeyCode["NUMPAD_7"] = 100] = "NUMPAD_7";
    KeyCode[KeyCode["NUMPAD_8"] = 101] = "NUMPAD_8";
    KeyCode[KeyCode["NUMPAD_9"] = 102] = "NUMPAD_9";
    KeyCode[KeyCode["NUMPAD_MULTIPLY"] = 103] = "NUMPAD_MULTIPLY";
    KeyCode[KeyCode["NUMPAD_ADD"] = 104] = "NUMPAD_ADD";
    KeyCode[KeyCode["NUMPAD_SEPARATOR"] = 105] = "NUMPAD_SEPARATOR";
    KeyCode[KeyCode["NUMPAD_SUBTRACT"] = 106] = "NUMPAD_SUBTRACT";
    KeyCode[KeyCode["NUMPAD_DECIMAL"] = 107] = "NUMPAD_DECIMAL";
    KeyCode[KeyCode["NUMPAD_DIVIDE"] = 108] = "NUMPAD_DIVIDE";
    /**
     * Cover all key codes when IME is processing input.
     */
    KeyCode[KeyCode["KEY_IN_COMPOSITION"] = 109] = "KEY_IN_COMPOSITION";
    KeyCode[KeyCode["ABNT_C1"] = 110] = "ABNT_C1";
    KeyCode[KeyCode["ABNT_C2"] = 111] = "ABNT_C2";
    /**
     * Placed last to cover the length of the enum.
     * Please do not depend on this value!
     */
    KeyCode[KeyCode["MAX_VALUE"] = 112] = "MAX_VALUE";
})(KeyCode || (KeyCode = {}));
var KeyMod;
(function (KeyMod) {
    KeyMod[KeyMod["CtrlCmd"] = 2048] = "CtrlCmd";
    KeyMod[KeyMod["Shift"] = 1024] = "Shift";
    KeyMod[KeyMod["Alt"] = 512] = "Alt";
    KeyMod[KeyMod["WinCtrl"] = 256] = "WinCtrl";
})(KeyMod || (KeyMod = {}));


/***/ }),

/***/ 7457:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  gf: () => (/* reexport */ actions/* CommitHistory */.gf),
  s9: () => (/* reexport */ actions/* CommitHistoryEntry */.s9),
  TU: () => (/* reexport */ Git),
  v7: () => (/* reexport */ actions/* GitActionError */.v7),
  I7: () => (/* reexport */ actions/* GitActionErrorCode */.I7),
  PR: () => (/* reexport */ actions/* deleteLocalBranch */.PR),
  SE: () => (/* reexport */ actions/* deleteRemoteBranch */.SE),
  p9: () => (/* reexport */ actions/* getBranches */.p9),
  Bo: () => (/* reexport */ actions/* getRemote */.Bo),
  a$: () => (/* reexport */ actions/* pull */.a$),
  VC: () => (/* reexport */ actions/* push */.VC)
});

// UNUSED EXPORTS: CommitState, ConvertStatusKindToGitStatus, GitEmptyRepositoryError, createErrorFromMessage, createMergeMessage, createSquashMessage, fetch, setRemoteURL, setRequestGitAccount

// EXTERNAL MODULE: ../noodl-git/src/core/models/status.ts
var models_status = __webpack_require__(45226);
;// ../noodl-git/src/models.ts

function ConvertStatusKindToGitStatus(x) {
    switch (x) {
        case models_status/* FileStatusKind */.Jb.New:
            return "new";
        case models_status/* FileStatusKind */.Jb.Modified:
            return "modified";
        case models_status/* FileStatusKind */.Jb.Deleted:
            return "deleted";
        case models_status/* FileStatusKind */.Jb.Copied:
            return "modified";
        case models_status/* FileStatusKind */.Jb.Renamed:
            return "modified";
        case models_status/* FileStatusKind */.Jb.Conflicted:
            return "conflicted";
        case models_status/* FileStatusKind */.Jb.Untracked:
            return "new";
    }
}
class GitEmptyRepositoryError extends Error {
    constructor() {
        super("The repository you're trying to clone is empty.");
    }
}

// EXTERNAL MODULE: external "fs-extra"
var external_fs_extra_ = __webpack_require__(59638);
// EXTERNAL MODULE: external "underscore"
var external_underscore_ = __webpack_require__(80002);
// EXTERNAL MODULE: ../noodl-git/src/actions/index.ts + 7 modules
var actions = __webpack_require__(11058);
// EXTERNAL MODULE: ../noodl-git/src/actions/remote.ts
var actions_remote = __webpack_require__(93125);
// EXTERNAL MODULE: ../noodl-git/src/constants.ts
var constants = __webpack_require__(25758);
// EXTERNAL MODULE: ../noodl-git/src/core/client.ts + 14 modules
var client = __webpack_require__(85869);
;// ../noodl-git/src/core/add.ts

async function addAll(basePath) {
    await (0,client/* git */.$)(['add', '-A'], basePath, 'addAll');
}

// EXTERNAL MODULE: external "path"
var external_path_ = __webpack_require__(16928);
var external_path_default = /*#__PURE__*/__webpack_require__.n(external_path_);
// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(79896);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
;// ../noodl-git/src/core/attributes.ts


async function appendGitAttributes(repositoryDir, newItems) {
    const gitAttributesPath = external_path_default().join(repositoryDir, '.gitattributes');
    const content = external_fs_default().existsSync(gitAttributesPath)
        ? await external_fs_default().promises.readFile(gitAttributesPath, { encoding: 'utf-8' })
        : '';
    const lineByLine = content.split('\n').map((x) => x.trim());
    const newContent = [];
    newItems.forEach((text) => {
        if (!lineByLine.includes(text)) {
            newContent.push(text);
        }
    });
    if (newContent.length > 0) {
        await external_fs_default().promises.appendFile(gitAttributesPath, newContent.join('\r\n') + '\r\n');
    }
}

;// ../noodl-git/src/core/branch.ts

/**
 * Returns the current branch name.
 *
 * For example: 'main'
 */
async function currentBranchName(repositoryDir) {
    // Used 'rev-parse' before, but
    const args = ['rev-parse', '--abbrev-ref', 'HEAD'];
    try {
        const { output } = await (0,client/* git */.$)(args, repositoryDir, 'currentBranchName');
        return output.toString().trim();
    }
    catch {
        // This will happen when there is no commit
        return 'null';
    }
}
async function createBranch(basePath, name, startPoint, noTrack) {
    const args = startPoint !== null ? ['branch', name, startPoint] : ['branch', name];
    // if we're branching directly from a remote branch, we don't want to track it
    // tracking it will make the rest of desktop think we want to push to that
    // remote branch's upstream (which would likely be the upstream of the fork)
    if (noTrack) {
        args.push('--no-track');
    }
    await (0,client/* git */.$)(args, basePath, 'createBranch');
}
/** Rename the given branch to a new name. */
async function renameBranch(repositoryDir, branch, newName) {
    await git(['branch', '-m', branch.nameWithoutRemote, newName], repositoryDir, 'renameBranch');
}
/**
 * Delete the branch locally.
 */
async function deleteLocalBranch(repositoryDir, branchName) {
    await git(['branch', '-D', branchName], repositoryDir, 'deleteLocalBranch');
    return true;
}

// EXTERNAL MODULE: ../noodl-git/src/core/checkout.ts
var checkout = __webpack_require__(36479);
;// ../noodl-git/src/core/clean.ts

/**
 * Delete all the untracked files.
 *
 * @param repositoryDir
 * @returns
 */
function cleanUntrackedFiles(repositoryDir) {
    return (0,client/* git */.$)(['clean', '-f', '-d'], repositoryDir, 'cleanUntrackedFiles');
}

// EXTERNAL MODULE: ../noodl-git/src/core/clone.ts
var clone = __webpack_require__(29902);
// EXTERNAL MODULE: ../noodl-git/src/core/git-error.ts
var git_error = __webpack_require__(55952);
;// ../noodl-git/src/core/commit.ts


/**
 * @param repositoryDir repository directory
 * @param message commit message
 * @param amend amend the commit
 * @returns the commit long SHA
 */
async function createCommit(repositoryDir, message, amend = false) {
    const args = ["-F", "-", "--allow-empty-message"];
    if (amend) {
        args.push("--amend");
    }
    // Create the commit
    const result = await (0,client/* git */.$)(["commit", ...args], repositoryDir, "createCommit", {
        stdin: message,
        spawn: false,
    });
    // Parse the result where we want to get the short SHA
    const shortSha = (0,git_error/* parseCommitSHA */.Bi)(result);
    // Try to get the long sha
    // Problem here is that we might get something like "(root-commit)"
    // in shortSha where we actually expect a short sha.
    //
    // This will occur on the first commit in the repository.
    try {
        // Retrieve the long sha since it's more reliable.
        const longShaResult = await (0,client/* git */.$)(["rev-parse", shortSha], repositoryDir, "createCommit");
        const longSha = longShaResult.output.toString().trim();
        return longSha;
    }
    catch (_e) { }
    // If the previous call failed then we probably don't care about getting the
    // long sha anyways. To feel better we should probably check this properly and
    // actually return the correct value always.
    return null;
}

// EXTERNAL MODULE: ../../node_modules/@electron/remote/renderer/index.js
var renderer = __webpack_require__(52391);
;// ../noodl-git/src/core/config.ts




function appDir() {
    return (0,external_path_.join)(renderer.app.getAppPath(), '..');
}
/**
 * Look up a config value by name in the repository.
 *
 * @param onlyLocal Whether or not the value to be retrieved should stick to
 *                  the local repository settings. It is false by default. This
 *                  is equivalent to using the `--local` argument in the
 *                  `git config` invocation.
 */
function getConfigValue(baseDir, name, onlyLocal = false) {
    return getConfigValueInPath(name, baseDir, onlyLocal);
}
/** Look up a global config value by name. */
function getGlobalConfigValue(name, env) {
    return getConfigValueInPath(name, null, false, undefined, env);
}
/**
 * Look up a global config value by name.
 *
 * Treats the returned value as a boolean as per Git's
 * own definition of a boolean configuration value (i.e.
 * 0 -> false, "off" -> false, "yes" -> true etc)
 */
async function getGlobalBooleanConfigValue(name, env) {
    const value = await getConfigValueInPath(name, null, false, 'bool', env);
    return value === null ? null : value !== 'false';
}
/**
 * Look up a config value by name
 *
 * @param path      The path to execute the `git` command in. If null
 *                  we'll use the global configuration (i.e. --global)
 *                  and execute the Git call from the same location that
 *                  GitHub Desktop is installed in.
 * @param onlyLocal Whether or not the value to be retrieved should stick to
 *                  the local repository settings (if a path is specified). It
 *                  is false by default. It is equivalent to using the `--local`
 *                  argument in the `git config` invocation.
 * @param type      Canonicalize configuration values according to the
 *                  expected type (i.e. 0 -> false, "on" -> true etc).
 *                  See `--type` documentation in `git config`
 */
async function getConfigValueInPath(name, path, onlyLocal = false, type, env) {
    const flags = ['config', '-z'];
    if (!path) {
        flags.push('--global');
    }
    else if (onlyLocal) {
        flags.push('--local');
    }
    if (type !== undefined) {
        flags.push('--type', type);
    }
    flags.push(name);
    const result = await (0,client/* git */.$)(flags, path || appDir(), 'getConfigValueInPath', {
        successExitCodes: new Set([0, 1]),
        env
    });
    // Git exits with 1 if the value isn't found. That's OK.
    if (result.exitCode === 1) {
        return null;
    }
    const output = result.output.toString();
    const pieces = output.split('\0');
    return pieces[0];
}
/** Get the path to the global git config. */
async function getGlobalConfigPath(env) {
    const options = env ? { env } : undefined;
    const result = await git(['config', '--global', '--list', '--show-origin', '--name-only', '-z'], appDir(), 'getGlobalConfigPath', options);
    const segments = result.output.toString().split('\0');
    if (segments.length < 1) {
        return null;
    }
    const pathSegment = segments[0];
    if (!pathSegment.length) {
        return null;
    }
    const path = pathSegment.match(/file:(.+)/i);
    if (!path || path.length < 2) {
        return null;
    }
    return normalize(path[1]);
}
/** Set the local config value by name. */
function setConfigValue(baseDir, name, value, env) {
    return setConfigValueInPath(name, value, baseDir, env);
}
/** Set the global config value by name. */
async function setGlobalConfigValue(name, value, env) {
    return setConfigValueInPath(name, value, null, env);
}
/**
 * Set config value by name
 *
 * @param path The path to execute the `git` command in. If null
 *             we'll use the global configuration (i.e. --global)
 *             and execute the Git call from the same location that
 *             GitHub Desktop is installed in.
 */
async function setConfigValueInPath(name, value, path, env) {
    const options = env ? { env } : undefined;
    const flags = ['config'];
    if (!path) {
        flags.push('--global');
    }
    flags.push('--replace-all', name, value);
    await (0,client/* git */.$)(flags, path || appDir(), 'setConfigValueInPath', options);
}
/** Remove the local config value by name. */
async function removeConfigValue(filePath, name, env) {
    return removeConfigValueInPath(name, filePath, env);
}
/** Remove the global config value by name. */
async function removeGlobalConfigValue(name, env) {
    return removeConfigValueInPath(name, null, env);
}
/**
 * Remove config value by name
 *
 * @param path The path to execute the `git` command in. If null
 *             we'll use the global configuration (i.e. --global)
 *             and execute the Git call from the same location that
 *             GitHub Desktop is installed in.
 */
async function removeConfigValueInPath(name, path, env) {
    const options = env ? { env } : undefined;
    const flags = ['config'];
    if (!path) {
        flags.push('--global');
    }
    flags.push('--unset-all', name);
    await git(flags, path || appDir(), 'removeConfigValueInPath', options);
}

// EXTERNAL MODULE: ../noodl-git/src/core/for-each-ref.ts
var for_each_ref = __webpack_require__(38332);
;// ../noodl-git/src/core/ignore.ts


async function appendGitIgnore(repositoryDir, newItems) {
    const gitIgnorePath = external_path_default().join(repositoryDir, '.gitignore');
    const content = external_fs_default().existsSync(gitIgnorePath) ? await external_fs_default().promises.readFile(gitIgnorePath, { encoding: 'utf-8' }) : '';
    const lineByLine = content.split('\n').map((x) => x.trim());
    const newContent = [];
    newItems.forEach((text) => {
        if (!lineByLine.includes(text)) {
            newContent.push(text);
        }
    });
    if (newContent.length > 0) {
        await external_fs_default().promises.appendFile(gitIgnorePath, newContent.join('\r\n') + '\r\n');
    }
}

;// ../noodl-git/src/core/init.ts




async function installMergeDriver(repositoryDir) {
    const driverPath = process.env.devMode
        ? `"${external_path_default().join(process.cwd(), 'electron')}"` + ' ' + `"${process.cwd()}"`
        : `"${process.env.exePath}"`;
    const driver = `${driverPath} --merge %O %A %B %L`;
    await setConfigValue(repositoryDir, 'merge.noodl.name', 'Merge driver installed by Noodl to handle merge conflicts in project.json file.');
    await setConfigValue(repositoryDir, 'merge.noodl.driver', driver);
}
async function init(repositoryDir, options) {
    const args = ['-c', `init.defaultBranch=${constants/* DEFAULT_BRANCH */.nU}`, 'init'];
    if (options === null || options === void 0 ? void 0 : options.bare) {
        args.push('--bare');
    }
    await (0,client/* git */.$)(args, repositoryDir, 'init');
    return repositoryDir;
}

// EXTERNAL MODULE: ../noodl-git/src/core/logs.ts
var logs = __webpack_require__(41176);
// EXTERNAL MODULE: ../noodl-git/src/core/merge.ts + 1 modules
var merge = __webpack_require__(73622);
// EXTERNAL MODULE: ../noodl-git/src/core/models/branch.ts + 1 modules
var models_branch = __webpack_require__(16279);
// EXTERNAL MODULE: ../noodl-git/src/core/models/computed-action.ts
var computed_action = __webpack_require__(89642);
// EXTERNAL MODULE: ../noodl-git/src/core/models/snapshot.ts + 1 modules
var snapshot = __webpack_require__(60629);
// EXTERNAL MODULE: ../noodl-git/src/core/open.ts
var core_open = __webpack_require__(89523);
// EXTERNAL MODULE: ../noodl-git/src/core/push.ts
var push = __webpack_require__(6875);
;// ../noodl-git/src/core/refs.ts

async function refhead(basePath) {
    const { output } = await (0,client/* git */.$)(['rev-parse', 'HEAD'], basePath, 'refhead');
    return output.toString().replace(/[\r\n]/g, '');
}

// EXTERNAL MODULE: ../noodl-git/src/core/remotes.ts
var core_remotes = __webpack_require__(57992);
// EXTERNAL MODULE: ../noodl-git/src/core/reset.ts
var core_reset = __webpack_require__(33532);
// EXTERNAL MODULE: ../noodl-git/src/core/rev-list.ts
var rev_list = __webpack_require__(65079);
;// ../noodl-git/src/core/show-ref.ts

async function getRefHeads(repositoryDir) {
    const args = ['show-ref', '--heads', '-d'];
    const tags = await git(args, repositoryDir, 'getRefHeads', {
        successExitCodes: new Set([0, 1]) // when there are no tags, git exits with 1.
    });
    const tagsArray = tags.output
        .toString()
        .split('\n')
        .filter((line) => line !== '')
        .map((line) => {
        const [commitSha, rawTagName] = line.split(' ');
        // Normalize tag names by removing the leading ref/tags/ and the trailing ^{}.
        //
        // git show-ref returns two entries for annotated tags:
        // deadbeef refs/tags/annotated-tag
        // de510b99 refs/tags/annotated-tag^{}
        //
        // The first entry sha correspond to the blob object of the annotation, while the second
        // entry corresponds to the actual commit where the tag was created.
        // By normalizing the tag name we can make sure that the commit sha gets stored in the returned
        // Map of commits (since git will always print the entry with the commit sha at the end).
        const headName = rawTagName.replace(/^refs\/heads\//, '').replace(/\^\{\}$/, '');
        return [headName, commitSha];
    });
    return new Map(tagsArray);
}
async function getAllTags(repositoryDir) {
    const args = ['show-ref', '-d'];
    const tags = await (0,client/* git */.$)(args, repositoryDir, 'getAllTags', {
        successExitCodes: new Set([0, 1]) // when there are no tags, git exits with 1.
    });
    const tagsArray = tags.output
        .toString()
        .split('\n')
        .filter((line) => line !== '')
        .map((line) => {
        const [commitSha, rawTagName] = line.split(' ');
        return [rawTagName, commitSha];
    });
    return new Map(tagsArray);
}

// EXTERNAL MODULE: ../noodl-git/src/core/stash.ts
var core_stash = __webpack_require__(55654);
// EXTERNAL MODULE: ../noodl-git/src/core/status.ts + 5 modules
var core_status = __webpack_require__(99918);
// EXTERNAL MODULE: ../noodl-git/src/core/update-ref.ts
var update_ref = __webpack_require__(99474);
// EXTERNAL MODULE: ../noodl-git/src/merge-driver.js
var merge_driver = __webpack_require__(77649);
;// ../noodl-git/src/core/cat-file.ts

async function getFileContents(repositoryDir, blobSha) {
    const args = ['cat-file', '-p', blobSha];
    const opts = {
        successExitCodes: new Set([0, 1]),
        spawn: false,
        processCallback: (cb) => {
            // If Node.js encounters a synchronous runtime error while spawning
            // `stdout` will be undefined and the error will be emitted asynchronously
            if (cb.stdout) {
                cb.stdout.setEncoding('binary');
            }
        }
    };
    const { output } = await (0,client/* git */.$)(args, repositoryDir, 'getFileContents', opts);
    return output;
}

;// ../noodl-git/src/merge-strategy.ts




function tryParseJson(str) {
    try {
        return JSON.parse(str);
    }
    catch {
        return null;
    }
}
/**
 * Defines the Noodl custom merge strategy.
 */
class MergeStrategy {
    constructor(repositoryDir, mergeProject, strategy = 'our') {
        this.repositoryDir = repositoryDir;
        this.mergeProject = mergeProject;
        this.strategy = strategy;
    }
    async solveConflicts(tree) {
        const projectJsonFiles = new Set(); //handle repos with multiple noodl projects
        const otherFiles = new Set();
        for (const entry of tree.conflictedEntries) {
            if (entry.hasConflicts) {
                const parent = entry.base || entry.our || entry.their;
                if (parent.path === 'project.json' || parent.path.slice(-13) === '/project.json') {
                    projectJsonFiles.add(entry);
                }
                else {
                    otherFiles.add(entry);
                }
            }
        }
        // Resolve conflicts
        const projectPromises = Array.from(projectJsonFiles).map((x) => this.resolveProjectJsonConflict(x));
        const otherFilePromises = Array.from(otherFiles).map((x) => this.resolveFileConflict(x));
        const allPromises = [...projectPromises, ...otherFilePromises];
        await Promise.all(allPromises);
        // Mark all the file as resolved resolution
        await addAll(this.repositoryDir);
        // Return all files that were resolved
        return [...projectJsonFiles, ...otherFiles];
    }
    async resolveFileConflict(entry) {
        const parent = entry.base || entry.our || entry.their;
        console.log('resolveFileConflict', parent.path);
        const targetEntry = entry[this.strategy];
        console.log('vcs: resolving file conflict', targetEntry.path, 'using', this.strategy);
        const ourBlob = await getFileContents(this.repositoryDir, targetEntry.sha);
        const absolutePath = external_path_default().join(this.repositoryDir, parent.path);
        // Write our version of the file
        await external_fs_default().promises.writeFile(absolutePath, ourBlob);
    }
    async resolveProjectJsonConflict(entry) {
        const parent = entry.base || entry.our || entry.their;
        console.log('resolveProjectJsonConflict', parent.path);
        const results = await Promise.all([
            entry.base ? getFileContents(this.repositoryDir, entry.base.sha) : Promise.resolve('{}'),
            entry.our ? getFileContents(this.repositoryDir, entry.our.sha) : Promise.resolve('{}'),
            entry.their ? getFileContents(this.repositoryDir, entry.their.sha) : Promise.resolve('{}')
        ]);
        const ancestor = tryParseJson(results[0].toString());
        const ours = tryParseJson(results[1].toString());
        const theirs = tryParseJson(results[2].toString());
        if (!ancestor) {
            throw new Error("Failed to solve project.json conflict. Couldn't parse ancestor: " + results[0].toString());
        }
        if (!ours) {
            throw new Error("Failed to solve project.json conflict. Couldn't parse ours: " + results[1].toString());
        }
        else if (!theirs) {
            throw new Error("Failed to solve project.json conflict. Couldn't parse theirs: " + results[2].toString());
        }
        const mergedResult = this.mergeProject(ancestor, ours, theirs);
        const absolutePath = external_path_default().join(this.repositoryDir, parent.path);
        await external_fs_default().promises.writeFile(absolutePath, JSON.stringify(mergedResult));
    }
}

;// ../noodl-git/src/git.ts



































var CommitState;
(function (CommitState) {
    CommitState[CommitState["NONE"] = 0] = "NONE";
    CommitState[CommitState["LOCAL"] = 1] = "LOCAL";
    CommitState[CommitState["REMOTE"] = 2] = "REMOTE";
})(CommitState || (CommitState = {}));
function createSquashMessage(branchName) {
    return `Squashed commit from branch '${branchName}'`;
}
function createMergeMessage(theirsBranchName, oursBranchName) {
    return `Merge ${theirsBranchName} into ${oursBranchName}`;
}
/**
 * NOTE: Don't change the methods here, they are the same as in Noodl Editor right now!
 * NOTE: I have added some return values in some places where there were none before.
 */
class Git {
    get repositoryPath() {
        return this.baseDir;
    }
    get Provider() {
        return this.originProvider;
    }
    get OriginUrl() {
        return this.originUrl;
    }
    constructor(mergeProject) {
        this.mergeProject = mergeProject;
        this.baseDir = null;
        this.originProvider = null;
        this.originUrl = null;
    }
    /**
     * Initialize a new git repository in the given path.
     *
     * @param baseDir
     */
    async initNewRepo(baseDir, options) {
        if (this.baseDir)
            return;
        this.baseDir = await init(baseDir, options);
        await this._setupRepository();
    }
    /**
     * Open a git repository in the given path.
     *
     * @param baseDir
     * @throws Error if the path is not a git repository
     */
    async openRepository(baseDir) {
        if (this.baseDir)
            return;
        const repositoryPath = await (0,core_open/* open */.ho)(baseDir);
        if (!repositoryPath) {
            throw new Error(`Not a git repository: ${baseDir}`);
        }
        this.baseDir = repositoryPath;
        await this._setupRepository();
    }
    /**
     * Clone a new repository.
     *
     * @param options
     */
    async clone({ url, directory, singleBranch, onProgress }) {
        if (this.baseDir)
            return;
        async function _clone() {
            try {
                return await (0,clone/* clone */.o)(url, directory, { branch: 'main', singleBranch }, (progress) => {
                    onProgress && onProgress(progress);
                });
            }
            catch (exc) {
                try {
                    return await (0,clone/* clone */.o)(url, directory, { branch: 'master', singleBranch }, (progress) => {
                        onProgress && onProgress(progress);
                    });
                }
                catch (exc) {
                    throw 'warning: You appear to have cloned an empty repository.';
                }
            }
        }
        try {
            await _clone();
            this.baseDir = directory;
            await this._setupRepository();
        }
        catch (exc) {
            if (exc && exc.toString().includes('warning: You appear to have cloned an empty repository.')) {
                // Remove the directory when it fails
                (0,external_fs_extra_.removeSync)(directory);
                throw new GitEmptyRepositoryError();
            }
        }
    }
    /**
     * List the remotes, sorted alphabetically by `name`, for a repository.
     *
     * @returns
     */
    async getRemoteName() {
        const remotes = await (0,core_remotes/* getRemotes */.K7)(this.baseDir);
        return remotes.length ? remotes[0].name : undefined;
    }
    /**
     * Add a new remote with the given URL.
     *
     * @param remoteURL
     */
    async addRemote(remoteURL) {
        await (0,core_remotes/* addRemote */.Uu)(this.baseDir, 'origin', remoteURL);
    }
    /**
     *
     * @param message
     * @returns Commit SHA
     */
    async commit(message) {
        // Cannot commit when there are no changes
        const status = await this.status();
        if (status.length === 0)
            throw new Error('Cannot commit without any local changes.');
        // Stage all changes, and untracked files
        // NOTE: This can be done with the commit command
        await addAll(this.baseDir);
        // Commit the changes
        return await createCommit(this.baseDir, message);
    }
    /**
     * Returns the status of the current git state.
     *
     * @returns
     */
    async status() {
        const statusList = await (0,core_status/* getStatus */.B)(this.baseDir);
        return statusList.files.map((x) => ({
            status: ConvertStatusKindToGitStatus(x.status.kind),
            path: x.path
        }));
    }
    /**
     * Stash the local changes.
     *
     * NOTE: This doesn't check if there are any changes.
     */
    async stashPushChanges(branchName) {
        const useBranchName = branchName !== null && branchName !== void 0 ? branchName : (await currentBranchName(this.baseDir));
        const stashMarker = `!!Noodl<${useBranchName}>`;
        return await (0,core_stash/* createStashEntry */.OT)(this.baseDir, stashMarker);
    }
    /**
     * Pop the stash.
     */
    async stashPopChanges(branchName) {
        const useBranchName = branchName !== null && branchName !== void 0 ? branchName : (await currentBranchName(this.baseDir));
        const stashMarker = `!!Noodl<${useBranchName}>`;
        const stashes = await (0,core_stash/* getStashes */.At)(this.baseDir);
        const stash = stashes.entries.find((x) => x.message === stashMarker);
        if (!stash) {
            return false;
        }
        await (0,merge_driver.writeMergeDriverOptions)({
            reversed: true
        });
        try {
            // Pop and then we do the merge check
            await (0,core_stash/* popStashEntry */.$S)(this.baseDir, stash.name);
        }
        catch (err) {
            // Run merge on untracked files, we are not able to pop the stash when there are untracked files.
            // The solution to this is to pop the stash to a new branch, which is done via "git stash branch".
            //
            // This means that we can handle it as 2 different branches making it easier to merge.
            //
            // OKAY, GOOD LUCK! BE READY!
            //
            // So here is a story all about how I screwed up git for a very long time.
            // Lets start with a stash and then pull in some changes.
            // Then we pop our stash, but its all about untracked changes.
            // So we created a branch called !!Noodl-Stash-... with all has our (local) changes
            // Then we merge in the remote changes to our new branch without any problems
            // So I checked out the branch we are working on
            // And the squash merge all the files from without a commit in our new !!Noodl-Stash
            //
            // Yeah it doesn't really work in the end, but maybe it helps a little? Maybe makes you happy?
            //
            if (err.toString().includes('could not restore untracked files from stash')) {
                const previousBranch = await this.getCurrentBranchName();
                const stashBranchName = `!!Noodl-Stash-${stash.branchName}`;
                // Create a new branch from the stash
                // this will also checkout the branch
                await (0,core_stash/* popStashEntryToBranch */.yT)(this.baseDir, stash.name, stashBranchName);
                // Merge our working branch into the stash branch
                await this._merge({
                    theirsBranchName: previousBranch,
                    oursBranchName: stashBranchName,
                    isSquash: false,
                    message: undefined,
                    allowFastForward: false
                });
                const changes = await this.status();
                if (changes.length > 0) {
                    await this.commit('Merge stash');
                }
                // TODO: Should we make sure there are no issues?
                // Checkout the working branch
                await this.checkoutBranch(previousBranch);
                // Squash merge our stash branch into the working branch without making any commits.
                await (0,merge/* merge */.h1)(this.baseDir, stashBranchName, {
                    strategy: 'recursive',
                    strategyOption: 'theirs',
                    isSquash: true,
                    squashNoCommit: true,
                    message: undefined,
                    noFastForward: true
                });
                // Delete the stash branch
                await this.deleteBranch(stashBranchName);
                // And what should be left on the working branch is our stash, that we love so much!
            }
            else {
                // We failed to pop the stash, this shouldn't happen, but we just log the error and return false.
                console.error(err);
                return false;
            }
        }
        finally {
            (0,merge_driver.cleanMergeDriverOptionsSync)();
        }
        // Get merge information
        const headCommitish = await this.getHeadCommitId();
        const tree = await (0,merge/* mergeTreeCommit */.sw)(this.baseDir, stash.sha, headCommitish);
        // Check if there is a merge conflict
        if (tree.kind === computed_action/* ComputedAction */.Y.Conflicts) {
            // Solve any conflicts if there are any after reapplying the stash
            // NOTE(?): "ours" and "theirs" are reveresed, since our changes are the incoming one from the stash
            const solver = new MergeStrategy(this.baseDir, this.mergeProject);
            await solver.solveConflicts(tree);
        }
        else if (tree.kind !== computed_action/* ComputedAction */.Y.Clean) {
            throw new Error('Failed to merge stash, ' + tree.kind);
        }
        return true;
    }
    /**
     *
     * @param options
     */
    async mergeToCurrentBranch(theirsBranchName, squash = true, message = undefined) {
        return this._mergeToCurrentBranch({
            theirsBranchName,
            squash,
            message
        });
    }
    /**
     * Reset the current branch to HEAD.
     *
     * This will delete all local changes and
     * checkout the HEAD branch if it exists.
     */
    async resetToHead() {
        // Get the current branch
        const branchName = await currentBranchName(this.baseDir);
        const branches = await (0,for_each_ref/* getBranchesOld */.W)(this.baseDir, branchName);
        const branch = branches.find((x) => x.name === branchName);
        // Delete all the untracked files
        await cleanUntrackedFiles(this.baseDir);
        // Delete all local changes
        await (0,core_reset/* reset */.c)(this.baseDir, 0 /* GitResetMode.Hard */, 'HEAD');
        // NOTE: Only checkout the branch if it exists
        if (branch) {
            await (0,checkout/* checkoutBranch */.n)(this.baseDir, branch, { force: true });
        }
    }
    async resetToCommitWithId(id) {
        await (0,core_reset/* reset */.c)(this.baseDir, 0 /* GitResetMode.Hard */, id);
        await cleanUntrackedFiles(this.baseDir);
    }
    async resetToMergeBase() {
        const headCommitId = await this.getHeadCommitId();
        const remoteHeadCommitId = await this.getRemoteHeadCommitId();
        if (!remoteHeadCommitId) {
            throw new Error('No remote commit to base from');
        }
        const mergeBaseId = await this.getMergeBaseCommitId(headCommitId, remoteHeadCommitId);
        await this.resetToCommitWithId(mergeBaseId);
        await cleanUntrackedFiles(this.baseDir);
    }
    /**
     *
     * @deprecated This is only used in old git panel
     *
     * @param options
     * @returns
     */
    async push(options) {
        const currentBranchName = await this.getCurrentBranchName();
        const remoteBranchName = currentBranchName;
        const remote = await (0,actions_remote/* getRemote */.B)(this.baseDir);
        try {
            return await (0,push/* push */.V)(this.baseDir, remote, currentBranchName, remoteBranchName, [], undefined, (progress) => {
                if (options === null || options === void 0 ? void 0 : options.onProgress) {
                    options.onProgress({
                        percent: progress.value
                    });
                }
            });
        }
        catch (error) {
            const message = error.toString();
            if (message.includes('Updates were rejected because the remote contains work that you do')) {
                throw new Error('Updates were rejected because there are new changes that you do not have locally. Pull to get the latest changes.');
            }
            throw (0,actions/* createErrorFromMessage */.gR)(message);
        }
    }
    async fetch({ onProgress }) {
        // Check remote origin where it is hosted
        const remoteName = await this.getRemoteName();
        const remoteUrl = await (0,core_remotes/* getRemoteURL */.EY)(this.repositoryPath, remoteName);
        this.originUrl = remoteUrl === null || remoteUrl === void 0 ? void 0 : remoteUrl.trim();
        this.originProvider = this.getProviderForRemote(remoteUrl);
        if (!remoteUrl) {
            throw new actions/* GitActionError */.v7(actions/* GitActionErrorCode */.I7.LocalRepository);
        }
        // Fetch
        const remote = await (0,actions_remote/* getRemote */.B)(this.baseDir);
        await (0,actions/* fetch */.hd)(this.baseDir, remote, onProgress);
    }
    /**
     *
     * @returns
     */
    async hasRemoteCommits() {
        const remoteName = await this.getRemoteName();
        const tags = await getAllTags(this.baseDir);
        const refDefault = `refs/remotes/${remoteName}/${constants/* DEFAULT_BRANCH */.nU}`;
        // Backwards compatability
        const ref_master = `refs/remotes/${remoteName}/master`;
        return tags.has(refDefault) || tags.has(ref_master);
    }
    /**
     * Returns a list of all commits.
     */
    async getCommitsCurrentBranch() {
        const limit = 100;
        const localGitCommits = await this.getCommits(undefined, limit);
        let commits = localGitCommits.map(this.mapCommit);
        const remoteHeadId = await this.getRemoteHeadCommitId();
        if (remoteHeadId) {
            const currentBranchName = await this.getCurrentBranchName();
            const remoteGitCommits = await (0,logs/* getCommits */.JR)(this.baseDir, `origin/${currentBranchName}`, limit, undefined);
            if (commits.length > 0 && remoteGitCommits.length > 0) {
                const aheadBehind = await this.aheadBehind(commits[0].sha, remoteHeadId);
                //note: aheadBehind.ahead can be more than commits.length, primarily after merging a branch with lots of commits
                for (let i = 0; i < Math.min(commits.length, aheadBehind.ahead); i++) {
                    commits[i].isLocalAhead = true;
                }
            }
            const remoteOnlyCommits = remoteGitCommits
                .filter((x) => localGitCommits.findIndex((c) => c.sha === x.sha) === -1)
                .map((x) => ({ ...this.mapCommit(x), isRemoteAhead: true }));
            commits = remoteOnlyCommits.concat(commits);
        }
        else {
            // there is no remote, it's a local branch
            // flag all the commits as being "ahead" of
            // the remote (even the commit that was the branching points, and commits before it)
            commits.forEach((c) => (c.isLocalAhead = true));
        }
        return commits;
    }
    /**
     * Returns the commits between the two commits excluding the base commit.
     *
     * NOTE: It's very important that the commit sha's are in the right order.
     *
     * @param baseCommitId
     * @param targetCommitId
     * @returns
     */
    async getCommitsBetween(baseCommitId, targetCommitId) {
        return (await this.getCommits((0,rev_list/* revSymmetricDifference */.QU)(baseCommitId, targetCommitId), 100)).map(this.mapCommit);
    }
    async getCommitFromId(id) {
        const commits = await this.getCommits(id, 1);
        const commit = commits.length > 0 ? commits[0] : null;
        return new snapshot/* Commit */.gn(this.baseDir, commit.sha, commit.shortSha, commit.summary, commit.body, commit.author, commit.committer, commit.parentSHAs, commit.tags);
    }
    async getMergeBaseCommitId(id1, id2) {
        return await (0,merge/* getMergeBase */.sT)(this.baseDir, id1, id2);
    }
    /**
     * Returns the HEAD SHA of the current branch.
     *
     * @returns
     */
    async getHeadCommitId() {
        const commit = await refhead(this.baseDir);
        return commit ? commit : null;
    }
    /**
     * Returns the remote latest SHA of the current branch.
     *
     * TODO: This is not a HEAD
     */
    async getRemoteHeadCommitId() {
        const remoteName = await this.getRemoteName();
        const branchName = await this.getCurrentBranchName();
        const tags = await getAllTags(this.baseDir);
        const ref = `refs/remotes/${remoteName}/${branchName}`;
        return tags.has(ref) ? tags.get(ref) : null;
    }
    /**
     *
     * @param branchName
     */
    async getHeadCommitOnBranch(branchName) {
        var _a;
        const branches = await (0,for_each_ref/* getBranchesOld */.W)(this.baseDir);
        const branch = branches.find((x) => x.name === branchName);
        return (_a = branch === null || branch === void 0 ? void 0 : branch.tip) === null || _a === void 0 ? void 0 : _a.sha;
    }
    async currentAheadBehind() {
        const currentLocalCommitId = await this.getHeadCommitId();
        const currentRemoteCommitId = await this.getRemoteHeadCommitId();
        return await this.aheadBehind(currentLocalCommitId, currentRemoteCommitId);
    }
    async aheadBehind(localCommitId, upstreamCommitId) {
        if (upstreamCommitId) {
            const { ahead, behind } = await (0,rev_list/* getAheadBehind */.ID)(this.baseDir, (0,rev_list/* revSymmetricDifference */.QU)(localCommitId, upstreamCommitId));
            return { ahead, behind };
        }
        else {
            const { ahead, behind } = await (0,rev_list/* getAheadBehind */.ID)(this.baseDir, localCommitId);
            return { ahead, behind };
        }
    }
    async getFileDiff(baseCommitId, targetCommitId) {
        const changes = await (0,logs/* getChangedFiles */.cL)(this.baseDir, (0,rev_list/* revRange */.zg)(baseCommitId, targetCommitId));
        return changes.files.map((x) => ({
            status: ConvertStatusKindToGitStatus(x.status.kind),
            path: x.path
        }));
    }
    /**
     * Create a new branch from the HEAD branch.
     *
     * @param name
     */
    async createBranchFromHead(name) {
        const headCommitId = await this.getHeadCommitId();
        await createBranch(this.baseDir, name, headCommitId);
    }
    /**
     * This will:
     * 1. Create a new branch
     * 2. Stash the current changes
     * 3. Checkout the new branch
     * 4. Pop the stash changes
     *
     * @param branchName
     */
    async createAndCheckoutBranch(branchName) {
        const currentBranchName = await this.getCurrentBranchName();
        // Check if branch already exists
        const branches = await (0,for_each_ref/* getBranchesOld */.W)(this.baseDir);
        if (branches.find((x) => x.name === branchName))
            throw new Error('Branch already exists');
        // The branch name can be invalid
        try {
            await this.createBranchFromHead(branchName);
        }
        catch (err) {
            const message = err.toString();
            if (message.includes('fatal: cannot lock ref') || message.includes('is not a valid branch name')) {
                throw new actions/* GitActionError */.v7(actions/* GitActionErrorCode */.I7.InvalidBranchName);
            }
            throw err;
        }
        // Stash changes if there are any local changes
        const status = await this.status();
        const needsStash = status.length > 0;
        if (needsStash) {
            await this.stashPushChanges(currentBranchName);
        }
        try {
            await this.checkoutBranch(branchName);
        }
        catch (err) {
            throw err;
        }
        finally {
            if (needsStash) {
                await this.stashPopChanges(currentBranchName);
            }
        }
    }
    /**
     *
     * @param name
     */
    async checkoutRemoteBranch(name) {
        const remoteName = await this.getRemoteName();
        const refName = `refs/remotes/${remoteName}/${name}`;
        const branches = await (0,for_each_ref/* getBranchesOld */.W)(this.baseDir);
        const remoteRef = branches.find((x) => x.ref === refName);
        await this.checkoutBranch(remoteRef.name);
    }
    /**
     * This will:
     * 1. Stash changes
     * 2. Checkout the branch
     * 3. Pop the stash changes (from the new branch; if there are any)
     *
     * @param name
     */
    async checkoutBranch(name, commitish) {
        // Find the branch we want to checkout
        const branches = await (0,for_each_ref/* getBranchesOld */.W)(this.baseDir);
        const branch = branches.find((x) => x.name === name);
        if (!branch)
            throw new Error('Branch not found');
        // 1. Stash changes if there are any local changes
        const status = await this.status();
        if (status.length > 0) {
            await this.stashPushChanges();
        }
        // 2. Checkout the branch
        await (0,checkout/* checkoutBranch */.n)(this.baseDir, branch, {
            force: false,
            commitish
        });
        // 3.
        try {
            await this.stashPopChanges();
        }
        catch {
            // if there is no stash the we don't care.
        }
    }
    /**
     * Returns the current branch name.
     */
    async getCurrentBranchName() {
        const branchName = await currentBranchName(this.baseDir);
        return branchName.trim();
    }
    /**
     * Returns all the branches.
     *
     * Technical: This merges all the branches (local/remote) into one list.
     *
     * @deprecated This is only used in old git panel
     */
    async getBranches() {
        const branches = await (0,for_each_ref/* getBranchesOld */.W)(this.baseDir);
        const allBranches = branches
            .filter((x) => x.type === models_branch/* BranchType */.Rk.Local)
            .map((x) => {
            return {
                name: x.name,
                local: true,
                remote: false
            };
        });
        // Update all the branches with the remote branches
        // There can be cases where you have 2 branches with the same name, just one is on a different remote.
        // Could also be cases where there are even more than just 2... Take care!
        branches
            .filter((x) => x.type === models_branch/* BranchType */.Rk.Remote)
            .forEach((x) => {
            // For example: "origin/A"
            // In the UI we just want to display the branch name, not the remote.
            let split = x.name.split('/');
            if (split.length > 1) {
                split = split.slice(1);
            }
            const branchName = split.join('/');
            const hitIndex = allBranches.findIndex((x) => x.name === branchName);
            if (hitIndex !== -1) {
                allBranches[hitIndex].remote = true;
            }
            else {
                allBranches.push({
                    name: branchName,
                    local: false,
                    remote: true
                });
            }
        });
        return (0,external_underscore_.sortBy)(allBranches, (x) => x.name);
    }
    /**
     * Deletes a specific branch.
     *
     * @param name
     */
    async deleteBranch(name) {
        const branches = await (0,for_each_ref/* getBranchesOld */.W)(this.baseDir);
        const branch = branches.find((x) => x.name === name && x.type === models_branch/* BranchType */.Rk.Local);
        if (!branch)
            throw new Error(`Branch doesn't exist`);
        await (0,update_ref/* deleteRef */.j)(this.baseDir, branch.ref);
    }
    /**
     *
     * @param name
     */
    async deleteRemoteBranch(name) {
        const remote = await (0,actions_remote/* getRemote */.B)(this.baseDir);
        const refName = `refs/remotes/${remote.name}/${name}`;
        const branches = await (0,for_each_ref/* getBranchesOld */.W)(this.baseDir);
        const branch = branches.find((x) => x.ref === refName && x.type === models_branch/* BranchType */.Rk.Remote);
        if (!branch)
            throw new Error('Remote Branch not found');
        await (0,push/* pushDelete */.Y)(this.baseDir, remote.name, name);
    }
    mapCommit(x) {
        return {
            sha: x.sha,
            shortSha: x.shortSha,
            message: x.summary,
            date: x.author.date,
            parentCount: x.parentSHAs.length,
            author: {
                name: x.author.name,
                email: x.author.email
            },
            isLocalAhead: false,
            isRemoteAhead: false
        };
    }
    async getCommits(revisionRange, limit) {
        return await (0,logs/* getCommits */.JR)(this.baseDir, revisionRange, limit);
    }
    /**
     * Setup the common git rules for it to work with Noodl.
     */
    async _setupRepository() {
        await setConfigValue(this.baseDir, 'core.precomposeUnicode', 'true');
        await setConfigValue(this.baseDir, 'core.protectNTFS', 'false');
        await setConfigValue(this.baseDir, 'core.longpaths', 'true');
        await installMergeDriver(this.baseDir);
        // Ignore these files (these rules are just saved in memory, not to .gitignore)
        await appendGitIgnore(this.baseDir, ['project-tmp.json*', '.DS_Store', '__MACOSX']);
        // Create or append the .gitattributes file
        await appendGitAttributes(this.baseDir, ['project.json merge=noodl']);
        const remoteName = await this.getRemoteName();
        if (remoteName) {
            const remoteUrl = await (0,core_remotes/* getRemoteURL */.EY)(this.repositoryPath, remoteName);
            this.originUrl = remoteUrl === null || remoteUrl === void 0 ? void 0 : remoteUrl.trim();
        }
        this.originProvider = this.getProviderForRemote(this.originUrl);
    }
    async _mergeToCurrentBranch(options) {
        // Get the target merge branch name
        const oursBranchName = await currentBranchName(this.baseDir);
        // Stash changes if there are any local changes
        const status = await this.status();
        const needsStash = status.length > 0;
        if (needsStash) {
            await this.stashPushChanges(oursBranchName);
        }
        // Do the merge
        try {
            await this._merge({
                theirsBranchName: options.theirsBranchName,
                oursBranchName,
                isSquash: options.squash,
                message: options.message,
                allowFastForward: options.allowFastForward || true
            });
        }
        finally {
            // Reapply local changes
            if (needsStash) {
                await this.stashPopChanges(oursBranchName);
            }
        }
    }
    async _merge(options) {
        const branches = await (0,for_each_ref/* getBranchesOld */.W)(this.baseDir);
        const ours = branches.find((x) => x.name === options.oursBranchName);
        const theirs = branches.find((x) => x.name === options.theirsBranchName);
        if (!ours)
            throw new Error(`Branch '${options.oursBranchName}' not found.`);
        if (!theirs)
            throw new Error(`Branch '${options.theirsBranchName}' not found.`);
        const message = options.message ||
            (options.isSquash
                ? createSquashMessage(options.theirsBranchName)
                : createMergeMessage(options.theirsBranchName, options.oursBranchName));
        try {
            // NOTE: We got a merge conflict, somewhere, somehow.
            //       Issue: project.json file to added to Unmerged paths.
            //       Solution: "git add/rm <file>" aka stage files
            await addAll(this.baseDir);
            await (0,merge/* merge */.h1)(this.baseDir, options.theirsBranchName, {
                strategy: undefined,
                isSquash: options.isSquash,
                squashNoCommit: !!options.squashNoCommit,
                message,
                noFastForward: !options.allowFastForward
            });
        }
        catch (err) {
            console.info('there are merge conflicts that have to be resolved, so we will resolve them just after this.');
            console.info(err);
        }
        // Our custom strategy
        const tree = await (0,merge/* mergeTree */.pR)(this.baseDir, ours, theirs);
        if (tree.kind === computed_action/* ComputedAction */.Y.Conflicts) {
            // Run our solve strategy
            const solver = new MergeStrategy(this.baseDir, this.mergeProject);
            await solver.solveConflicts(tree);
            // Create a merge commit
            await createCommit(this.baseDir, message);
        }
        else if (tree.kind !== computed_action/* ComputedAction */.Y.Clean) {
            throw new Error('Failed to merge, ' + tree.kind);
        }
    }
    async getConfigValue(name) {
        return getConfigValue(this.baseDir, name);
    }
    async setConfigValue(name, value) {
        return setConfigValue(this.baseDir, name, value);
    }
    getProviderForRemote(remoteUrl) {
        if (!remoteUrl) {
            return 'none';
        }
        else if (remoteUrl.includes('noodlapp.com')) {
            return 'noodl';
        }
        else if (remoteUrl.includes('github.com')) {
            return 'github';
        }
        else {
            return 'unknown';
        }
    }
    async setRemoteURL(remoteUrl) {
        const remoteName = await this.getRemoteName();
        const url = remoteUrl === null || remoteUrl === void 0 ? void 0 : remoteUrl.trim();
        //if there's no existing remote, add one called origin
        if (!remoteName) {
            await (0,core_remotes/* addRemote */.Uu)(this.repositoryPath, 'origin', url);
            return;
        }
        this.originUrl = url;
        this.originProvider = this.getProviderForRemote(url);
        await (0,actions_remote/* setRemoteURL */.g)(this.repositoryPath, remoteName, url);
    }
    async tryHandleRebaseState() {
        const status = await this.status();
        const conflicts = status.filter((s) => s.status === 'conflicted').map((s) => s.path);
        //check if the only issue is .gitignore and handle it
        if (conflicts.length === 1 && conflicts.includes('.gitignore')) {
            //resolve it with ours, just overwrite the remote
            //note that "ours" is reversed here since we're rebasing
            await (0,client/* git */.$)(['checkout', '--theirs', '.gitignore'], this.repositoryPath, 'pick-our-gitignore');
            await (0,client/* git */.$)(['add', '.gitignore'], this.repositoryPath, 'add-gitignore');
            await (0,client/* git */.$)(['rebase', '--continue'], this.repositoryPath, 'continue-rebase', {
                env: {
                    GIT_EDITOR: 'true' //make sure the commit message editor doesn't pop up
                }
            });
        }
        else {
            throw new Error('Repository is in a rebase state. Please handle manually through a git client.');
        }
    }
    async isRebaseInProgress() {
        try {
            //this will return the SHA of the commit that is being rebased, or throw if there's no rebase in progress
            await (0,client/* git */.$)(['rev-parse', '--verify', 'REBASE_HEAD'], this.repositoryPath, 'check-rebase');
            return true;
        }
        catch (e) {
            return false;
        }
    }
}

// EXTERNAL MODULE: ../noodl-git/src/core/trampoline/trampoline-askpass-handler.ts
var trampoline_askpass_handler = __webpack_require__(58848);
;// ../noodl-git/src/index.ts






/***/ }),

/***/ 7603:
/***/ ((module) => {

"use strict";
module.exports = require("scheduler");

/***/ }),

/***/ 7615:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCloudDownload = function SvgCloudDownload(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M16.5434 6.17798C15.234 5.91753 13.8769 6.0512 12.6434 6.5621C11.41 7.07299 10.3558 7.93815 9.61414 9.04818C8.87244 10.1582 8.47656 11.4633 8.47656 12.7983C8.47656 13.2125 8.14078 13.5483 7.72656 13.5483C7.31235 13.5483 6.97656 13.2125 6.97656 12.7983C6.97656 12.0369 7.08192 11.2835 7.28642 10.5585C7.18344 10.5517 7.0802 10.5482 6.97684 10.5483H6.97656C5.78309 10.5483 4.6385 11.0224 3.79458 11.8663C2.95067 12.7102 2.47656 13.8548 2.47656 15.0483C2.47656 16.2418 2.95067 17.3863 3.79458 18.2303C4.6385 19.0742 5.78309 19.5483 6.97656 19.5483H15.2266C16.5616 19.5483 17.8666 19.1524 18.9767 18.4107C20.0867 17.669 20.9519 16.6148 21.4627 15.3814C21.9736 14.148 22.1073 12.7908 21.8469 11.4814C21.5864 10.1721 20.9435 8.96932 19.9995 8.02531C19.0555 7.08131 17.8528 6.43843 16.5434 6.17798ZM7.84692 9.10999C8.00079 8.80213 8.17432 8.5031 8.36694 8.21483C9.27346 6.85812 10.5619 5.8007 12.0694 5.17628C13.5769 4.55185 15.2357 4.38848 16.8361 4.7068C18.4364 5.02513 19.9064 5.81087 21.0602 6.96465C22.214 8.11843 22.9997 9.58844 23.318 11.1888C23.6364 12.7891 23.473 14.4479 22.8486 15.9554C22.2241 17.4629 21.1667 18.7514 19.81 19.6579C18.4533 20.5644 16.8583 21.0483 15.2266 21.0483H6.97656C5.38526 21.0483 3.85914 20.4161 2.73392 19.2909C1.6087 18.1657 0.976562 16.6396 0.976562 15.0483C0.976562 13.457 1.6087 11.9309 2.73392 10.8056C3.85907 9.68049 5.38508 9.04836 6.97628 9.04828M7.84692 9.10999C7.55889 9.06885 7.26804 9.04819 6.97656 9.04828L7.84692 9.10999Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M11.8824 12.8036C11.5895 12.5107 11.1146 12.5107 10.8217 12.8036C10.5288 13.0965 10.5288 13.5714 10.8217 13.8643L13.7985 16.8411C13.9019 16.9445 14.0279 17.0113 14.1607 17.0417C14.1881 17.048 14.2161 17.0528 14.2446 17.056C14.2806 17.0601 14.317 17.0615 14.3532 17.0604C14.5563 17.0539 14.739 16.9668 14.8703 16.83L17.836 13.8643C18.1289 13.5714 18.1289 13.0965 17.836 12.8036C17.5431 12.5107 17.0682 12.5107 16.7753 12.8036L15.0791 14.4998L15.0791 9.28581C15.0791 8.87159 14.7433 8.53581 14.3291 8.53581C13.9149 8.53581 13.5791 8.87159 13.5791 9.28581L13.5791 14.5003L11.8824 12.8036Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCloudDownload);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "1f7c1b4c456e3ea55851000cb420a2aa.svg");

/***/ }),

/***/ 7943:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPlay = function SvgPlay(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M8 4.14062V18.1406L19 11.1406L8 4.14062Z",
    fill: "#9F9F9F"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPlay);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "0ac681b1a161ed001fb287a5e273bf44.svg");

/***/ }),

/***/ 7987:
/***/ ((module) => {

"use strict";
module.exports = require("jsdom");

/***/ }),

/***/ 8263:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  InspectPopup: () => (/* binding */ InspectPopup)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/@microlink/react-json-view/dist/main.js
var main = __webpack_require__(1407);
var main_default = /*#__PURE__*/__webpack_require__.n(main);
// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.ts + 4 modules
var projectmodel = __webpack_require__(6203);
// EXTERNAL MODULE: ./src/editor/src/views/ToastLayer/ToastLayer.tsx
var ToastLayer = __webpack_require__(80424);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/nodegrapheditor/InspectJSONView/InspectPopup.module.scss
var InspectPopup_module = __webpack_require__(3966);
;// ./src/editor/src/views/nodegrapheditor/InspectJSONView/InspectPopup.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(InspectPopup_module/* default */.A, options);




       /* harmony default export */ const InspectJSONView_InspectPopup_module = (InspectPopup_module/* default */.A && InspectPopup_module/* default */.A.locals ? InspectPopup_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/nodegrapheditor/InspectJSONView/InspectPopup.tsx






function InspectPopup({ debugValue, onPinClicked, pinned }) {
    if (debugValue === undefined) {
        return null;
    }
    if (typeof debugValue === 'string') {
        debugValue = { type: 'value', value: debugValue };
    }
    if (!Array.isArray(debugValue)) {
        debugValue = [debugValue];
    }
    const hasValuesToShow = debugValue.some((v) => v.value !== undefined);
    if (!hasValuesToShow) {
        return null;
    }
    return (external_react_default().createElement("div", { className: InspectJSONView_InspectPopup_module.Root },
        external_react_default().createElement("button", { onClick: onPinClicked, className: external_classnames_default()(InspectJSONView_InspectPopup_module.PinButton, pinned && InspectJSONView_InspectPopup_module['is-pinned']) }),
        external_react_default().createElement("div", { className: InspectJSONView_InspectPopup_module.ValueContainer }, debugValue.map((value, i) => {
            if (value.type === 'image') {
                return external_react_default().createElement(ImageInspector, { source: value.value, key: i });
            }
            else if (value.type === 'color') {
                return external_react_default().createElement(ColorInspector, { color: value.value, key: i });
            }
            else {
                return typeof value.value === 'object' && value.value !== null ? (external_react_default().createElement(ObjectInspector, { value: value.value, key: i })) : (external_react_default().createElement(ValueInspector, { value: value.value, key: i }));
            }
        }))));
}
function ObjectInspector({ value }) {
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        Array.isArray(value) ? external_react_default().createElement(ValueInspector, { value: 'Count: ' + value.length }) : null,
        external_react_default().createElement((main_default()), { src: value, theme: {
                base00: '#eaeaea',
                base01: '#eaeaea',
                base02: '#575757',
                base03: '#8b877f',
                base04: '#eaeaea',
                base05: '#eaeaea',
                base06: '#a0a0a0',
                base07: '#a0a0a0',
                base08: '#eaeaea',
                base09: '#f7c967',
                base0A: '#bcaffb',
                base0B: '#77C9D4',
                base0C: '#a0a0a0',
                base0D: '#a0a0a0',
                base0E: '#e5ae32', // copyToClipboardCheck (--base-color-yellow-300)
                base0F: '#b8b8b8' // copyToClipboard (--base-color-grey-300)
            }, enableClipboard: () => {
                ToastLayer.ToastLayer.showInteraction('Copied');
            }, style: { backgroundColor: 'transparent' }, name: false, indentWidth: 2, displayObjectSize: false, displayDataTypes: false, quotesOnKeys: false, collapsed: 1 })));
}
function ValueInspector({ value }) {
    return external_react_default().createElement("div", { className: InspectJSONView_InspectPopup_module.ValueInspector }, String(value));
}
function ColorInspector({ color }) {
    const c = projectmodel.ProjectModel.instance.resolveColor(color);
    return (external_react_default().createElement("div", { className: InspectJSONView_InspectPopup_module.ValueInspector, style: { display: 'flex', alignItems: 'center', gap: '5px' } },
        external_react_default().createElement("div", { style: { backgroundColor: c, width: '20px', height: '20px' } }),
        color));
}
function ImageInspector({ source }) {
    let src;
    if (source.startsWith('http')) {
        src = source;
    }
    else {
        const protocol = process.env.ssl ? 'https' : 'http';
        const port = process.env.NOODLPORT || 8574;
        src = `${protocol}://localhost:${port}/${source}`;
    }
    return (external_react_default().createElement("div", { className: InspectJSONView_InspectPopup_module.ValueInspector },
        external_react_default().createElement("img", { src: src })));
}


/***/ }),

/***/ 8580:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.textstyles-edit-style {
  width: 33px;
  height: 33px;
  flex-shrink: 0;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  border-left: 1px solid var(--theme-color-bg-4);
}

.textstyles-edit-style::before {
  content: url('../assets/icons/editor/edit-controls.svg');
  opacity: 0.6;
  line-height: 0;
}

.textstyles-edit-style:hover::before {
  opacity: 1;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/views/TextStylePicker/TextStylePicker.css"],"names":[],"mappings":"AAAA;EACE,WAAW;EACX,YAAY;EACZ,cAAc;EACd,kBAAkB;EAClB,aAAa;EACb,uBAAuB;EACvB,mBAAmB;EACnB,8CAA8C;AAChD;;AAEA;EACE,wDAAwD;EACxD,YAAY;EACZ,cAAc;AAChB;;AAEA;EACE,UAAU;AACZ","sourcesContent":[".textstyles-edit-style {\n  width: 33px;\n  height: 33px;\n  flex-shrink: 0;\n  position: relative;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  border-left: 1px solid var(--theme-color-bg-4);\n}\n\n.textstyles-edit-style::before {\n  content: url('../assets/icons/editor/edit-controls.svg');\n  opacity: 0.6;\n  line-height: 0;\n}\n\n.textstyles-edit-style:hover::before {\n  opacity: 1;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 8593:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.StringInputDialog-module__Root--ogXFs{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;z-index:10000}.StringInputDialog-module__Dialog--ZnGlx{background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:8px;padding:24px;min-width:400px;max-width:500px;box-shadow:0 8px 32px rgba(0,0,0,.3)}.StringInputDialog-module__Title--RDuT3{margin:0 0 20px 0;font-size:16px;font-weight:600;color:var(--theme-color-fg-default)}.StringInputDialog-module__Input--eeBl0{width:100%;padding:8px 12px;font-size:14px;border:1px solid var(--theme-color-border-default);border-radius:4px;background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-default);margin-bottom:20px;font-family:inherit}.StringInputDialog-module__Input--eeBl0:focus{outline:none;border-color:var(--theme-color-primary)}.StringInputDialog-module__Actions--VC8MR{display:flex;justify-content:flex-end;gap:10px}.StringInputDialog-module__ButtonCancel--YF2sW,.StringInputDialog-module__ButtonConfirm--KF5Rk{padding:8px 16px;border-radius:4px;font-size:14px;font-weight:500;cursor:pointer;font-family:inherit;transition:background-color .15s ease}.StringInputDialog-module__ButtonCancel--YF2sW:disabled,.StringInputDialog-module__ButtonConfirm--KF5Rk:disabled{opacity:.5;cursor:not-allowed}.StringInputDialog-module__ButtonCancel--YF2sW{background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);color:var(--theme-color-fg-default)}.StringInputDialog-module__ButtonCancel--YF2sW:hover:not(:disabled){background-color:var(--theme-color-bg-4)}.StringInputDialog-module__ButtonConfirm--KF5Rk{background-color:var(--theme-color-primary);border:none;color:#fff}.StringInputDialog-module__ButtonConfirm--KF5Rk:hover:not(:disabled){opacity:.9}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/ComponentsPanelNew/components/StringInputDialog.module.scss"],"names":[],"mappings":"AAKA,uCACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,+BAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,aAAA,CAGF,yCACE,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,YAAA,CACA,eAAA,CACA,eAAA,CACA,oCAAA,CAGF,wCACE,iBAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,wCACE,UAAA,CACA,gBAAA,CACA,cAAA,CACA,kDAAA,CACA,iBAAA,CACA,wCAAA,CACA,mCAAA,CACA,kBAAA,CACA,mBAAA,CAEA,8CACE,YAAA,CACA,uCAAA,CAIJ,0CACE,YAAA,CACA,wBAAA,CACA,QAAA,CAGF,+FAEE,gBAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,mBAAA,CACA,qCAAA,CAEA,iHACE,UAAA,CACA,kBAAA,CAIJ,+CACE,wCAAA,CACA,kDAAA,CACA,mCAAA,CAEA,oEACE,wCAAA,CAIJ,gDACE,2CAAA,CACA,WAAA,CACA,UAAA,CAEA,qEACE,UAAA","sourcesContent":["/**\n * StringInputDialog styles\n * Uses proper CSS classes for Electron compatibility\n */\n\n.Root {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.5);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 10000;\n}\n\n.Dialog {\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 8px;\n  padding: 24px;\n  min-width: 400px;\n  max-width: 500px;\n  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);\n}\n\n.Title {\n  margin: 0 0 20px 0;\n  font-size: 16px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n}\n\n.Input {\n  width: 100%;\n  padding: 8px 12px;\n  font-size: 14px;\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  background-color: var(--theme-color-bg-1);\n  color: var(--theme-color-fg-default);\n  margin-bottom: 20px;\n  font-family: inherit;\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.Actions {\n  display: flex;\n  justify-content: flex-end;\n  gap: 10px;\n}\n\n.ButtonCancel,\n.ButtonConfirm {\n  padding: 8px 16px;\n  border-radius: 4px;\n  font-size: 14px;\n  font-weight: 500;\n  cursor: pointer;\n  font-family: inherit;\n  transition: background-color 0.15s ease;\n\n  &:disabled {\n    opacity: 0.5;\n    cursor: not-allowed;\n  }\n}\n\n.ButtonCancel {\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  color: var(--theme-color-fg-default);\n\n  &:hover:not(:disabled) {\n    background-color: var(--theme-color-bg-4);\n  }\n}\n\n.ButtonConfirm {\n  background-color: var(--theme-color-primary);\n  border: none;\n  color: white;\n\n  &:hover:not(:disabled) {\n    opacity: 0.9;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `StringInputDialog-module__Root--ogXFs`,
	"Dialog": `StringInputDialog-module__Dialog--ZnGlx`,
	"Title": `StringInputDialog-module__Title--RDuT3`,
	"Input": `StringInputDialog-module__Input--eeBl0`,
	"Actions": `StringInputDialog-module__Actions--VC8MR`,
	"ButtonCancel": `StringInputDialog-module__ButtonCancel--YF2sW`,
	"ButtonConfirm": `StringInputDialog-module__ButtonConfirm--KF5Rk`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 8636:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.SidePanel-model__PanelItem--CjV9A{position:relative;width:100%;height:100%}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/SidePanel/SidePanel.model.scss"],"names":[],"mappings":"AAAA,mCACE,iBAAA,CACA,UAAA,CACA,WAAA","sourcesContent":[".PanelItem {\n  position: relative;\n  width: 100%;\n  height: 100%;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"PanelItem": `SidePanel-model__PanelItem--CjV9A`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 8717:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_LessonLayerView_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(563);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_LessonLayerView_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_LessonLayerView_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_LessonLayerView_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_LessonLayerView_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 9621:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PropertyPanelInput-module__Root--mggXO{display:flex;margin-bottom:8px;align-items:center;user-select:none}.PropertyPanelInput-module__Label--abxD5{font-family:var(--font-family);color:var(--theme-color-fg-default);padding-right:8px;font-size:12px;width:37%;flex-grow:0;flex-shrink:0;text-overflow:ellipsis;max-height:28px;line-clamp:2}.PropertyPanelInput-module__Label--abxD5.PropertyPanelInput-module__is-changed--_7dNF{color:var(--theme-color-secondary-as-fg)}.PropertyPanelInput-module__InputContainer--D0fgA{flex:1 1 auto;min-width:0;overflow:hidden}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/property-panel/PropertyPanelInput/PropertyPanelInput.module.scss"],"names":[],"mappings":"AAAA,wCACE,YAAA,CACA,iBAAA,CACA,kBAAA,CACA,gBAAA,CAGF,yCACE,8BAAA,CACA,mCAAA,CACA,iBAAA,CACA,cAAA,CACA,SAAA,CACA,WAAA,CACA,aAAA,CACA,sBAAA,CACA,eAAA,CACA,YAAA,CAEA,sFACE,wCAAA,CAIJ,kDACE,aAAA,CACA,WAAA,CACA,eAAA","sourcesContent":[".Root {\n  display: flex;\n  margin-bottom: 8px;\n  align-items: center;\n  user-select: none;\n}\n\n.Label {\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-default);\n  padding-right: 8px;\n  font-size: 12px;\n  width: 37%;\n  flex-grow: 0;\n  flex-shrink: 0;\n  text-overflow: ellipsis;\n  max-height: 28px;\n  line-clamp: 2;\n\n  &.is-changed {\n    color: var(--theme-color-secondary-as-fg);\n  }\n}\n\n.InputContainer {\n  flex: 1 1 auto;\n  min-width: 0; // Allow flex item to shrink below content size\n  overflow: hidden; // Prevent content overflow\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PropertyPanelInput-module__Root--mggXO`,
	"Label": `PropertyPanelInput-module__Label--abxD5`,
	"is-changed": `PropertyPanelInput-module__is-changed--_7dNF`,
	"InputContainer": `PropertyPanelInput-module__InputContainer--D0fgA`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 9638:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getPlatformHeaders = exports.isRunningInBrowser = void 0;
const version_1 = __webpack_require__(36377);
const isRunningInBrowser = () => {
    return (
    // @ts-ignore
    typeof window !== 'undefined' &&
        // @ts-ignore
        typeof window.document !== 'undefined' &&
        // @ts-ignore
        typeof navigator !== 'undefined');
};
exports.isRunningInBrowser = isRunningInBrowser;
/**
 * Note this does not detect 'browser'; for that, use getBrowserInfo().
 */
function getDetectedPlatform() {
    if (typeof Deno !== 'undefined' && Deno.build != null) {
        return 'deno';
    }
    if (typeof EdgeRuntime !== 'undefined') {
        return 'edge';
    }
    if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') {
        return 'node';
    }
    return 'unknown';
}
const getPlatformProperties = () => {
    const detectedPlatform = getDetectedPlatform();
    if (detectedPlatform === 'deno') {
        return {
            'X-Stainless-Lang': 'js',
            'X-Stainless-Package-Version': version_1.VERSION,
            'X-Stainless-OS': normalizePlatform(Deno.build.os),
            'X-Stainless-Arch': normalizeArch(Deno.build.arch),
            'X-Stainless-Runtime': 'deno',
            'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',
        };
    }
    if (typeof EdgeRuntime !== 'undefined') {
        return {
            'X-Stainless-Lang': 'js',
            'X-Stainless-Package-Version': version_1.VERSION,
            'X-Stainless-OS': 'Unknown',
            'X-Stainless-Arch': `other:${EdgeRuntime}`,
            'X-Stainless-Runtime': 'edge',
            'X-Stainless-Runtime-Version': globalThis.process.version,
        };
    }
    // Check if Node.js
    if (detectedPlatform === 'node') {
        return {
            'X-Stainless-Lang': 'js',
            'X-Stainless-Package-Version': version_1.VERSION,
            'X-Stainless-OS': normalizePlatform(globalThis.process.platform ?? 'unknown'),
            'X-Stainless-Arch': normalizeArch(globalThis.process.arch ?? 'unknown'),
            'X-Stainless-Runtime': 'node',
            'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown',
        };
    }
    const browserInfo = getBrowserInfo();
    if (browserInfo) {
        return {
            'X-Stainless-Lang': 'js',
            'X-Stainless-Package-Version': version_1.VERSION,
            'X-Stainless-OS': 'Unknown',
            'X-Stainless-Arch': 'unknown',
            'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
            'X-Stainless-Runtime-Version': browserInfo.version,
        };
    }
    // TODO add support for Cloudflare workers, etc.
    return {
        'X-Stainless-Lang': 'js',
        'X-Stainless-Package-Version': version_1.VERSION,
        'X-Stainless-OS': 'Unknown',
        'X-Stainless-Arch': 'unknown',
        'X-Stainless-Runtime': 'unknown',
        'X-Stainless-Runtime-Version': 'unknown',
    };
};
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
function getBrowserInfo() {
    if (typeof navigator === 'undefined' || !navigator) {
        return null;
    }
    // NOTE: The order matters here!
    const browserPatterns = [
        { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
        { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
        { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
        { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
        { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
        { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
    ];
    // Find the FIRST matching browser
    for (const { key, pattern } of browserPatterns) {
        const match = pattern.exec(navigator.userAgent);
        if (match) {
            const major = match[1] || 0;
            const minor = match[2] || 0;
            const patch = match[3] || 0;
            return { browser: key, version: `${major}.${minor}.${patch}` };
        }
    }
    return null;
}
const normalizeArch = (arch) => {
    // Node docs:
    // - https://nodejs.org/api/process.html#processarch
    // Deno docs:
    // - https://doc.deno.land/deno/stable/~/Deno.build
    if (arch === 'x32')
        return 'x32';
    if (arch === 'x86_64' || arch === 'x64')
        return 'x64';
    if (arch === 'arm')
        return 'arm';
    if (arch === 'aarch64' || arch === 'arm64')
        return 'arm64';
    if (arch)
        return `other:${arch}`;
    return 'unknown';
};
const normalizePlatform = (platform) => {
    // Node platforms:
    // - https://nodejs.org/api/process.html#processplatform
    // Deno platforms:
    // - https://doc.deno.land/deno/stable/~/Deno.build
    // - https://github.com/denoland/deno/issues/14799
    platform = platform.toLowerCase();
    // NOTE: this iOS check is untested and may not work
    // Node does not work natively on IOS, there is a fork at
    // https://github.com/nodejs-mobile/nodejs-mobile
    // however it is unknown at the time of writing how to detect if it is running
    if (platform.includes('ios'))
        return 'iOS';
    if (platform === 'android')
        return 'Android';
    if (platform === 'darwin')
        return 'MacOS';
    if (platform === 'win32')
        return 'Windows';
    if (platform === 'freebsd')
        return 'FreeBSD';
    if (platform === 'openbsd')
        return 'OpenBSD';
    if (platform === 'linux')
        return 'Linux';
    if (platform)
        return `Other:${platform}`;
    return 'Unknown';
};
let _platformHeaders;
const getPlatformHeaders = () => {
    return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));
};
exports.getPlatformHeaders = getPlatformHeaders;
//# sourceMappingURL=detect-platform.js.map

/***/ }),

/***/ 10014:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.editor-banner {
	box-sizing: border-box;
	cursor: default;
	width: 100%;
	font-size: 12px;
	display: flex;
	overflow: visible;

	height: 26px;

	background: var(--vscode-banner-background);
}


.editor-banner .icon-container {
	display: flex;
	flex-shrink: 0;
	align-items: center;
	padding: 0 6px 0 10px;
}

.editor-banner .icon-container.custom-icon {
	background-repeat: no-repeat;
	background-position: center center;
	background-size: 16px;
	width: 16px;
	padding: 0;
	margin: 0 6px 0 10px;
}

.editor-banner .message-container {
	display: flex;
	align-items: center;
	line-height: 26px;
	text-overflow: ellipsis;
	white-space: nowrap;
	overflow: hidden;
}

.editor-banner .message-container p {
	margin-block-start: 0;
	margin-block-end: 0;
}

.editor-banner .message-actions-container {
	flex-grow: 1;
	flex-shrink: 0;
	line-height: 26px;
	margin: 0 4px;
}

.editor-banner .message-actions-container a.monaco-button {
	width: inherit;
	margin: 2px 8px;
	padding: 0px 12px;
}

.editor-banner .message-actions-container a {
	padding: 3px;
	margin-left: 12px;
	text-decoration: underline;
}

.editor-banner .action-container {
	padding: 0 10px 0 6px;
}

.editor-banner {
	background-color: var(--vscode-banner-background);
}

.editor-banner,
.editor-banner .action-container .codicon,
.editor-banner .message-actions-container .monaco-link {
	color: var(--vscode-banner-foreground);
}

.editor-banner .icon-container .codicon {
	color: var(--vscode-banner-iconForeground);
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/unicodeHighlighter/browser/bannerController.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,sBAAsB;CACtB,eAAe;CACf,WAAW;CACX,eAAe;CACf,aAAa;CACb,iBAAiB;;CAEjB,YAAY;;CAEZ,2CAA2C;AAC5C;;;AAGA;CACC,aAAa;CACb,cAAc;CACd,mBAAmB;CACnB,qBAAqB;AACtB;;AAEA;CACC,4BAA4B;CAC5B,kCAAkC;CAClC,qBAAqB;CACrB,WAAW;CACX,UAAU;CACV,oBAAoB;AACrB;;AAEA;CACC,aAAa;CACb,mBAAmB;CACnB,iBAAiB;CACjB,uBAAuB;CACvB,mBAAmB;CACnB,gBAAgB;AACjB;;AAEA;CACC,qBAAqB;CACrB,mBAAmB;AACpB;;AAEA;CACC,YAAY;CACZ,cAAc;CACd,iBAAiB;CACjB,aAAa;AACd;;AAEA;CACC,cAAc;CACd,eAAe;CACf,iBAAiB;AAClB;;AAEA;CACC,YAAY;CACZ,iBAAiB;CACjB,0BAA0B;AAC3B;;AAEA;CACC,qBAAqB;AACtB;;AAEA;CACC,iDAAiD;AAClD;;AAEA;;;CAGC,sCAAsC;AACvC;;AAEA;CACC,0CAA0C;AAC3C","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.editor-banner {\n\tbox-sizing: border-box;\n\tcursor: default;\n\twidth: 100%;\n\tfont-size: 12px;\n\tdisplay: flex;\n\toverflow: visible;\n\n\theight: 26px;\n\n\tbackground: var(--vscode-banner-background);\n}\n\n\n.editor-banner .icon-container {\n\tdisplay: flex;\n\tflex-shrink: 0;\n\talign-items: center;\n\tpadding: 0 6px 0 10px;\n}\n\n.editor-banner .icon-container.custom-icon {\n\tbackground-repeat: no-repeat;\n\tbackground-position: center center;\n\tbackground-size: 16px;\n\twidth: 16px;\n\tpadding: 0;\n\tmargin: 0 6px 0 10px;\n}\n\n.editor-banner .message-container {\n\tdisplay: flex;\n\talign-items: center;\n\tline-height: 26px;\n\ttext-overflow: ellipsis;\n\twhite-space: nowrap;\n\toverflow: hidden;\n}\n\n.editor-banner .message-container p {\n\tmargin-block-start: 0;\n\tmargin-block-end: 0;\n}\n\n.editor-banner .message-actions-container {\n\tflex-grow: 1;\n\tflex-shrink: 0;\n\tline-height: 26px;\n\tmargin: 0 4px;\n}\n\n.editor-banner .message-actions-container a.monaco-button {\n\twidth: inherit;\n\tmargin: 2px 8px;\n\tpadding: 0px 12px;\n}\n\n.editor-banner .message-actions-container a {\n\tpadding: 3px;\n\tmargin-left: 12px;\n\ttext-decoration: underline;\n}\n\n.editor-banner .action-container {\n\tpadding: 0 10px 0 6px;\n}\n\n.editor-banner {\n\tbackground-color: var(--vscode-banner-background);\n}\n\n.editor-banner,\n.editor-banner .action-container .codicon,\n.editor-banner .message-actions-container .monaco-link {\n\tcolor: var(--vscode-banner-foreground);\n}\n\n.editor-banner .icon-container .codicon {\n\tcolor: var(--vscode-banner-iconForeground);\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 10142:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   g: () => (/* reexport safe */ _AiAssistantModel__WEBPACK_IMPORTED_MODULE_0__.g)
/* harmony export */ });
/* harmony import */ var _AiAssistantModel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77510);



/***/ }),

/***/ 10267:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.EditorTopbar-module__Root--IgH_V{container-name:editortopbar;height:36px;background-color:var(--theme-color-bg-2);border-bottom:2px solid var(--theme-color-bg-1);display:flex;align-items:stretch;justify-content:space-between}.EditorTopbar-module__LeftSide--IzwGV,.EditorTopbar-module__RightSide--Iop9k{display:flex;align-items:stretch}.EditorTopbar-module__LeftSide--IzwGV>div,.EditorTopbar-module__RightSide--Iop9k>div{display:flex;align-items:center}.EditorTopbar-module__LeftSide--IzwGV{flex-grow:1}.EditorTopbar-module__is-padded-s--SQT9A{padding:0 4px}.EditorTopbar-module__is-padded--Teyr4{padding:0 8px}.EditorTopbar-module__is-padded-l--_P74d{padding:0 16px}.EditorTopbar-module__LeftSide--IzwGV>div:not(:last-child){border-right:1px solid var(--theme-color-bg-1)}.EditorTopbar-module__RightSide--Iop9k>div:not(:first-child){border-left:1px solid var(--theme-color-bg-1)}.EditorTopbar-module__UrlBarWrapper--i6WJf{flex-grow:1;min-width:150px;max-width:500px;margin-right:-1px}.EditorTopbar-module__UrlBarTextInput--nPr24{width:100%}.EditorTopbar-module__UrlBarTextInput--nPr24 svg{cursor:pointer}.EditorTopbar-module__UrlBarTextInput--nPr24 svg:hover path{fill:var(--theme-color-fg-highlight)}.EditorTopbar-module__TooltipPositioner--NyL3r{height:32px;padding-bottom:1px;display:flex !important;flex-direction:column;justify-content:center}.EditorTopbar-module__TopbarSelect--_IqpF{display:flex;align-items:center;cursor:pointer}.EditorTopbar-module__TopbarSelect--_IqpF *{color:var(--theme-color-fg-highlight);fill:var(--theme-color-fg-highlight)}.EditorTopbar-module__TopbarSelect--_IqpF:hover *{color:var(--theme-color-fg-highlight);fill:var(--theme-color-fg-highlight);opacity:.8}.EditorTopbar-module__ZoomSelect--nRCBy{padding-right:4px;padding-left:8px}.EditorTopbar-module__DesignPreviewModeButton--rLP9T{cursor:pointer;pointer-events:all}.EditorTopbar-module__Root--IgH_V.EditorTopbar-module__is-small--oc68N .EditorTopbar-module__DeployButton--Ukpdr{padding:0 4px 0 8px;min-width:0}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/EditorTopbar/EditorTopbar.module.scss"],"names":[],"mappings":"AAAA,kCACE,2BAAA,CACA,WAAA,CACA,wCAAA,CACA,+CAAA,CACA,YAAA,CACA,mBAAA,CACA,6BAAA,CAGF,6EAEE,YAAA,CACA,mBAAA,CAGA,qFACE,YAAA,CACA,kBAAA,CAIJ,sCACE,WAAA,CAGF,yCACE,aAAA,CAGF,uCACE,aAAA,CAGF,yCACE,cAAA,CAIA,2DACE,8CAAA,CAKF,6DACE,6CAAA,CAIJ,2CACE,WAAA,CACA,eAAA,CACA,eAAA,CACA,iBAAA,CAGF,6CACE,UAAA,CAEA,iDACE,cAAA,CAGE,4DACE,oCAAA,CAMR,+CACE,WAAA,CACA,kBAAA,CACA,uBAAA,CACA,qBAAA,CACA,sBAAA,CAGF,0CACE,YAAA,CACA,kBAAA,CACA,cAAA,CAEA,4CACE,qCAAA,CACA,oCAAA,CAGF,kDACE,qCAAA,CACA,oCAAA,CACA,UAAA,CAIJ,wCACE,iBAAA,CACA,gBAAA,CAGF,qDACE,cAAA,CACA,kBAAA,CAIA,iHACE,mBAAA,CACA,WAAA","sourcesContent":[".Root {\n  container-name: editortopbar;\n  height: 36px;\n  background-color: var(--theme-color-bg-2);\n  border-bottom: 2px solid var(--theme-color-bg-1);\n  display: flex;\n  align-items: stretch;\n  justify-content: space-between;\n}\n\n.LeftSide,\n.RightSide {\n  display: flex;\n  align-items: stretch;\n\n  // please use these general selectors with great caution\n  > div {\n    display: flex;\n    align-items: center;\n  }\n}\n\n.LeftSide {\n  flex-grow: 1;\n}\n\n.is-padded-s {\n  padding: 0 4px;\n}\n\n.is-padded {\n  padding: 0 8px;\n}\n\n.is-padded-l {\n  padding: 0 16px;\n}\n\n.LeftSide {\n  > div:not(:last-child) {\n    border-right: 1px solid var(--theme-color-bg-1);\n  }\n}\n\n.RightSide {\n  > div:not(:first-child) {\n    border-left: 1px solid var(--theme-color-bg-1);\n  }\n}\n\n.UrlBarWrapper {\n  flex-grow: 1;\n  min-width: 150px;\n  max-width: 500px;\n  margin-right: -1px;\n}\n\n.UrlBarTextInput {\n  width: 100%;\n\n  svg {\n    cursor: pointer;\n\n    &:hover {\n      path {\n        fill: var(--theme-color-fg-highlight);\n      }\n    }\n  }\n}\n\n.TooltipPositioner {\n  height: 32px;\n  padding-bottom: 1px;\n  display: flex !important;\n  flex-direction: column;\n  justify-content: center;\n}\n\n.TopbarSelect {\n  display: flex;\n  align-items: center;\n  cursor: pointer;\n\n  * {\n    color: var(--theme-color-fg-highlight);\n    fill: var(--theme-color-fg-highlight);\n  }\n\n  &:hover * {\n    color: var(--theme-color-fg-highlight);\n    fill: var(--theme-color-fg-highlight);\n    opacity: 0.8;\n  }\n}\n\n.ZoomSelect {\n  padding-right: 4px;\n  padding-left: 8px;\n}\n\n.DesignPreviewModeButton {\n  cursor: pointer;\n  pointer-events: all;\n}\n\n.DeployButton {\n  .Root.is-small & {\n    padding: 0 4px 0 8px;\n    min-width: 0;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `EditorTopbar-module__Root--IgH_V`,
	"LeftSide": `EditorTopbar-module__LeftSide--IzwGV`,
	"RightSide": `EditorTopbar-module__RightSide--Iop9k`,
	"is-padded-s": `EditorTopbar-module__is-padded-s--SQT9A`,
	"is-padded": `EditorTopbar-module__is-padded--Teyr4`,
	"is-padded-l": `EditorTopbar-module__is-padded-l--_P74d`,
	"UrlBarWrapper": `EditorTopbar-module__UrlBarWrapper--i6WJf`,
	"UrlBarTextInput": `EditorTopbar-module__UrlBarTextInput--nPr24`,
	"TooltipPositioner": `EditorTopbar-module__TooltipPositioner--NyL3r`,
	"TopbarSelect": `EditorTopbar-module__TopbarSelect--_IqpF`,
	"ZoomSelect": `EditorTopbar-module__ZoomSelect--nRCBy`,
	"DesignPreviewModeButton": `EditorTopbar-module__DesignPreviewModeButton--rLP9T`,
	"is-small": `EditorTopbar-module__is-small--oc68N`,
	"DeployButton": `EditorTopbar-module__DeployButton--Ukpdr`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 10268:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.TitleBar-module__Root--p6TPZ{height:30px;flex-basis:30px;flex-shrink:0;flex-grow:0;width:100%;-webkit-app-region:drag;display:flex;justify-content:flex-end;align-items:center;border-bottom:2px solid var(--theme-color-bg-1);background-color:var(--theme-color-bg-2);box-sizing:border-box;user-select:none}.TitleBar-module__Root--p6TPZ.TitleBar-module__is-variant-shallow--wzN6R{background-color:var(--theme-color-bg-1);border-bottom:0}.TitleBar-module__Title--PT6zf{font-family:var(--font-family);color:var(--theme-color-fg-muted);font-size:12px;position:absolute;left:50%;transform:translateX(-50%)}.TitleBar-module__Version--pp1bB{font-family:var(--font-family);color:var(--theme-color-fg-default-shy);font-size:11px;margin-right:10px}.TitleBar-module__OSWindows--EiV0z{display:flex;height:100%}.TitleBar-module__OSWindowsIcon--FWlBQ{-webkit-app-region:no-drag;width:46px;height:100%;position:relative;display:flex;align-items:center;justify-content:center;opacity:.7;cursor:pointer}.TitleBar-module__OSWindowsIcon--FWlBQ:hover{background:hsla(0,0%,100%,.1);opacity:1}.TitleBar-module__OSWindowsIcon__Minimize--OlZRJ:before{position:absolute;width:10px;height:1px;border-bottom:1px solid var(--theme-color-bg-1);border-color:var(--theme-color-fg-highlight);content:"";box-sizing:border-box}.TitleBar-module__OSWindowsIcon__Maximize--cFVPM:before{content:"";width:10px;height:10px;border:1px solid var(--theme-color-fg-highlight);box-sizing:border-box}.TitleBar-module__OSWindowsIcon__Close--QsII8:before,.TitleBar-module__OSWindowsIcon__Close--QsII8:after{position:absolute;content:"";height:14px;width:1px;background-color:var(--theme-color-fg-highlight);box-sizing:border-box}.TitleBar-module__OSWindowsIcon__Close--QsII8:before{transform:rotate(45deg)}.TitleBar-module__OSWindowsIcon__Close--QsII8:after{transform:rotate(-45deg)}.TitleBar-module__OSWindowsIcon__Close--QsII8:hover{background:var(--theme-color-danger)}.TitleBar-module__OSWindowsIcon__Close--QsII8:hover:before,.TitleBar-module__OSWindowsIcon__Close--QsII8:hover:after{background-color:var(--theme-color-fg-highlight)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/app/TitleBar/TitleBar.module.scss"],"names":[],"mappings":"AAAA,8BACE,WAAA,CACA,eAAA,CACA,aAAA,CACA,WAAA,CAEA,UAAA,CACA,uBAAA,CACA,YAAA,CACA,wBAAA,CACA,kBAAA,CACA,+CAAA,CACA,wCAAA,CACA,qBAAA,CACA,gBAAA,CAEA,yEACE,wCAAA,CACA,eAAA,CAIJ,+BACE,8BAAA,CACA,iCAAA,CACA,cAAA,CACA,iBAAA,CACA,QAAA,CACA,0BAAA,CAGF,iCACE,8BAAA,CACA,uCAAA,CACA,cAAA,CACA,iBAAA,CAGF,mCACE,YAAA,CACA,WAAA,CAGF,uCACE,0BAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CAEA,cAAA,CAEA,6CACE,6BAAA,CACA,SAAA,CAIJ,wDACE,iBAAA,CACA,UAAA,CACA,UAAA,CACA,+CAAA,CACA,4CAAA,CACA,UAAA,CACA,qBAAA,CAGF,wDACE,UAAA,CACA,UAAA,CACA,WAAA,CACA,gDAAA,CACA,qBAAA,CAIA,yGAEE,iBAAA,CACA,UAAA,CACA,WAAA,CACA,SAAA,CACA,gDAAA,CACA,qBAAA,CAGF,qDACE,uBAAA,CAGF,oDACE,wBAAA,CAGF,oDACE,oCAAA,CAEA,qHAEE,gDAAA","sourcesContent":[".Root {\n  height: 30px;\n  flex-basis: 30px;\n  flex-shrink: 0;\n  flex-grow: 0;\n\n  width: 100%;\n  -webkit-app-region: drag;\n  display: flex;\n  justify-content: flex-end;\n  align-items: center;\n  border-bottom: 2px solid var(--theme-color-bg-1);\n  background-color: var(--theme-color-bg-2);\n  box-sizing: border-box;\n  user-select: none;\n\n  &.is-variant-shallow {\n    background-color: var(--theme-color-bg-1);\n    border-bottom: 0;\n  }\n}\n\n.Title {\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-muted);\n  font-size: 12px;\n  position: absolute;\n  left: 50%;\n  transform: translateX(-50%);\n}\n\n.Version {\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-default-shy);\n  font-size: 11px;\n  margin-right: 10px;\n}\n\n.OSWindows {\n  display: flex;\n  height: 100%;\n}\n\n.OSWindowsIcon {\n  -webkit-app-region: no-drag;\n  width: 46px;\n  height: 100%;\n  position: relative;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  opacity: 0.7;\n\n  cursor: pointer;\n\n  &:hover {\n    background: rgba(255, 255, 255, 0.1);\n    opacity: 1;\n  }\n}\n\n.OSWindowsIcon__Minimize:before {\n  position: absolute;\n  width: 10px;\n  height: 1px;\n  border-bottom: 1px solid var(--theme-color-bg-1);\n  border-color: var(--theme-color-fg-highlight);\n  content: '';\n  box-sizing: border-box;\n}\n\n.OSWindowsIcon__Maximize:before {\n  content: '';\n  width: 10px;\n  height: 10px;\n  border: 1px solid var(--theme-color-fg-highlight);\n  box-sizing: border-box;\n}\n\n.OSWindowsIcon__Close {\n  &:before,\n  &:after {\n    position: absolute;\n    content: '';\n    height: 14px;\n    width: 1px;\n    background-color: var(--theme-color-fg-highlight);\n    box-sizing: border-box;\n  }\n\n  &:before {\n    transform: rotate(45deg);\n  }\n\n  &:after {\n    transform: rotate(-45deg);\n  }\n\n  &:hover {\n    background: var(--theme-color-danger);\n\n    &:before,\n    &:after {\n      background-color: var(--theme-color-fg-highlight);\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `TitleBar-module__Root--p6TPZ`,
	"is-variant-shallow": `TitleBar-module__is-variant-shallow--wzN6R`,
	"Title": `TitleBar-module__Title--PT6zf`,
	"Version": `TitleBar-module__Version--pp1bB`,
	"OSWindows": `TitleBar-module__OSWindows--EiV0z`,
	"OSWindowsIcon": `TitleBar-module__OSWindowsIcon--FWlBQ`,
	"OSWindowsIcon__Minimize": `TitleBar-module__OSWindowsIcon__Minimize--OlZRJ`,
	"OSWindowsIcon__Maximize": `TitleBar-module__OSWindowsIcon__Maximize--cFVPM`,
	"OSWindowsIcon__Close": `TitleBar-module__OSWindowsIcon__Close--QsII8`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 10310:
/***/ ((module) => {

// Module
var code = "<div class=\"content-picker\"> <div data-template=\"item\" class=\"content-picker-list-item file-picker-list-item\" data-click=\"itemClicked\"> <div class=\"content-picker-item\" data-text=\"name\"> </div> </div> <label class=\"content-picker-header-label\">Choose file</label> <div class=\"items content-picker-items\"> </div> </div>";
// Exports
module.exports = code;

/***/ }),

/***/ 10651:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.DataLineagePanel-module__DataLineagePanel--yE0Q8{display:flex;flex-direction:column;height:100%;padding:var(--theme-spacing-2);overflow-y:auto;background-color:var(--theme-color-bg-1)}.DataLineagePanel-module__EmptyState--w7tP7{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;color:var(--theme-color-fg-default-shy)}.DataLineagePanel-module__EmptyState-icon--I9sjY{font-size:48px;margin-bottom:var(--theme-spacing-3);opacity:.5}.DataLineagePanel-module__EmptyState-title--IuZwM{font-size:16px;font-weight:600;margin-bottom:var(--theme-spacing-2)}.DataLineagePanel-module__EmptyState-description--O0aQK{font-size:14px;text-align:center;max-width:300px}.DataLineagePanel-module__Header--Bcgq4{display:flex;justify-content:space-between;align-items:center;padding-bottom:var(--theme-spacing-2);border-bottom:1px solid var(--theme-color-border-default);margin-bottom:var(--theme-spacing-3)}.DataLineagePanel-module__Header-title--NTMQp{display:flex;align-items:center;gap:var(--theme-spacing-2);font-weight:600;font-size:16px}.DataLineagePanel-module__Header-icon--ZzkUL{font-size:20px}.DataLineagePanel-module__Header-actions--ZBR2H{display:flex;gap:var(--theme-spacing-2)}.DataLineagePanel-module__Button--B2j76{padding:var(--theme-spacing-1) var(--theme-spacing-3);background-color:var(--theme-color-primary);color:var(--theme-color-bg-1);border:none;border-radius:var(--theme-border-radius-1);cursor:pointer;font-size:13px;font-weight:500}.DataLineagePanel-module__Button--B2j76:hover{background-color:var(--theme-color-primary-hover)}.DataLineagePanel-module__SelectedNode--FMPuA{padding:var(--theme-spacing-2);background-color:var(--theme-color-bg-2);border-radius:var(--theme-border-radius-1);margin-bottom:var(--theme-spacing-3)}.DataLineagePanel-module__SelectedNode-label--AINOF{font-size:15px;margin-bottom:var(--theme-spacing-1)}.DataLineagePanel-module__SelectedNode-meta--KE2zQ{font-size:13px;color:var(--theme-color-fg-default-shy);margin-bottom:var(--theme-spacing-1)}.DataLineagePanel-module__SelectedNode-component--RWQAc{font-size:12px;color:var(--theme-color-fg-default-shy);font-family:monospace}.DataLineagePanel-module__Section--kGdQG{margin-bottom:var(--theme-spacing-3)}.DataLineagePanel-module__Section-header--JXrES{display:flex;align-items:center;gap:var(--theme-spacing-2);padding:var(--theme-spacing-2);background-color:var(--theme-color-bg-2);border-radius:var(--theme-border-radius-1);cursor:pointer;user-select:none}.DataLineagePanel-module__Section-header--JXrES:hover{background-color:var(--theme-color-bg-3)}.DataLineagePanel-module__Section-toggle--oWgA8{font-size:12px;color:var(--theme-color-fg-default-shy)}.DataLineagePanel-module__Section-title--Rv0TO{display:flex;align-items:center;gap:var(--theme-spacing-1);font-weight:600;font-size:14px}.DataLineagePanel-module__Section-icon--wFXID{font-size:14px}.DataLineagePanel-module__Section-subtitle--XYbAk{font-size:12px;color:var(--theme-color-fg-default-shy);margin-left:auto}.DataLineagePanel-module__Section-content--jNcKW{margin-top:var(--theme-spacing-2);padding-left:var(--theme-spacing-2)}.DataLineagePanel-module__EmptyPath--ovsHt{display:flex;flex-direction:column;align-items:center;padding:var(--theme-spacing-4) var(--theme-spacing-2);color:var(--theme-color-fg-default-shy)}.DataLineagePanel-module__EmptyPath-icon--UyRRY{font-size:32px;margin-bottom:var(--theme-spacing-2);opacity:.5}.DataLineagePanel-module__EmptyPath-text--l65mK{font-size:14px;margin-bottom:var(--theme-spacing-1)}.DataLineagePanel-module__EmptyPath-hint--eW76f{font-size:12px;opacity:.7}.DataLineagePanel-module__DownstreamPath--HJWWr{margin-bottom:var(--theme-spacing-2)}.DataLineagePanel-module__DownstreamPath--HJWWr:last-child{margin-bottom:0}.DataLineagePanel-module__PathBranch--RL0bM{font-size:12px;font-weight:600;color:var(--theme-color-primary);margin-bottom:var(--theme-spacing-1)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/DataLineagePanel/DataLineagePanel.module.scss"],"names":[],"mappings":"AAEA,kDACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,8BAAA,CACA,eAAA,CACA,wCAAA,CAGF,4CACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,WAAA,CACA,uCAAA,CAEA,iDACE,cAAA,CACA,oCAAA,CACA,UAAA,CAGF,kDACE,cAAA,CACA,eAAA,CACA,oCAAA,CAGF,wDACE,cAAA,CACA,iBAAA,CACA,eAAA,CAIJ,wCACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,qCAAA,CACA,yDAAA,CACA,oCAAA,CAEA,8CACE,YAAA,CACA,kBAAA,CACA,0BAAA,CACA,eAAA,CACA,cAAA,CAGF,6CACE,cAAA,CAGF,gDACE,YAAA,CACA,0BAAA,CAIJ,wCACE,qDAAA,CACA,2CAAA,CACA,6BAAA,CACA,WAAA,CACA,0CAAA,CACA,cAAA,CACA,cAAA,CACA,eAAA,CAEA,8CACE,iDAAA,CAIJ,8CACE,8BAAA,CACA,wCAAA,CACA,0CAAA,CACA,oCAAA,CAEA,oDACE,cAAA,CACA,oCAAA,CAGF,mDACE,cAAA,CACA,uCAAA,CACA,oCAAA,CAGF,wDACE,cAAA,CACA,uCAAA,CACA,qBAAA,CAIJ,yCACE,oCAAA,CAEA,gDACE,YAAA,CACA,kBAAA,CACA,0BAAA,CACA,8BAAA,CACA,wCAAA,CACA,0CAAA,CACA,cAAA,CACA,gBAAA,CAEA,sDACE,wCAAA,CAIJ,gDACE,cAAA,CACA,uCAAA,CAGF,+CACE,YAAA,CACA,kBAAA,CACA,0BAAA,CACA,eAAA,CACA,cAAA,CAGF,8CACE,cAAA,CAGF,kDACE,cAAA,CACA,uCAAA,CACA,gBAAA,CAGF,iDACE,iCAAA,CACA,mCAAA,CAIJ,2CACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,qDAAA,CACA,uCAAA,CAEA,gDACE,cAAA,CACA,oCAAA,CACA,UAAA,CAGF,gDACE,cAAA,CACA,oCAAA,CAGF,gDACE,cAAA,CACA,UAAA,CAIJ,gDACE,oCAAA,CAEA,2DACE,eAAA,CAIJ,4CACE,cAAA,CACA,eAAA,CACA,gCAAA,CACA,oCAAA","sourcesContent":["// Data Lineage Panel Styles\n\n.DataLineagePanel {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  padding: var(--theme-spacing-2);\n  overflow-y: auto;\n  background-color: var(--theme-color-bg-1);\n}\n\n.EmptyState {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  height: 100%;\n  color: var(--theme-color-fg-default-shy);\n\n  &-icon {\n    font-size: 48px;\n    margin-bottom: var(--theme-spacing-3);\n    opacity: 0.5;\n  }\n\n  &-title {\n    font-size: 16px;\n    font-weight: 600;\n    margin-bottom: var(--theme-spacing-2);\n  }\n\n  &-description {\n    font-size: 14px;\n    text-align: center;\n    max-width: 300px;\n  }\n}\n\n.Header {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding-bottom: var(--theme-spacing-2);\n  border-bottom: 1px solid var(--theme-color-border-default);\n  margin-bottom: var(--theme-spacing-3);\n\n  &-title {\n    display: flex;\n    align-items: center;\n    gap: var(--theme-spacing-2);\n    font-weight: 600;\n    font-size: 16px;\n  }\n\n  &-icon {\n    font-size: 20px;\n  }\n\n  &-actions {\n    display: flex;\n    gap: var(--theme-spacing-2);\n  }\n}\n\n.Button {\n  padding: var(--theme-spacing-1) var(--theme-spacing-3);\n  background-color: var(--theme-color-primary);\n  color: var(--theme-color-bg-1);\n  border: none;\n  border-radius: var(--theme-border-radius-1);\n  cursor: pointer;\n  font-size: 13px;\n  font-weight: 500;\n\n  &:hover {\n    background-color: var(--theme-color-primary-hover);\n  }\n}\n\n.SelectedNode {\n  padding: var(--theme-spacing-2);\n  background-color: var(--theme-color-bg-2);\n  border-radius: var(--theme-border-radius-1);\n  margin-bottom: var(--theme-spacing-3);\n\n  &-label {\n    font-size: 15px;\n    margin-bottom: var(--theme-spacing-1);\n  }\n\n  &-meta {\n    font-size: 13px;\n    color: var(--theme-color-fg-default-shy);\n    margin-bottom: var(--theme-spacing-1);\n  }\n\n  &-component {\n    font-size: 12px;\n    color: var(--theme-color-fg-default-shy);\n    font-family: monospace;\n  }\n}\n\n.Section {\n  margin-bottom: var(--theme-spacing-3);\n\n  &-header {\n    display: flex;\n    align-items: center;\n    gap: var(--theme-spacing-2);\n    padding: var(--theme-spacing-2);\n    background-color: var(--theme-color-bg-2);\n    border-radius: var(--theme-border-radius-1);\n    cursor: pointer;\n    user-select: none;\n\n    &:hover {\n      background-color: var(--theme-color-bg-3);\n    }\n  }\n\n  &-toggle {\n    font-size: 12px;\n    color: var(--theme-color-fg-default-shy);\n  }\n\n  &-title {\n    display: flex;\n    align-items: center;\n    gap: var(--theme-spacing-1);\n    font-weight: 600;\n    font-size: 14px;\n  }\n\n  &-icon {\n    font-size: 14px;\n  }\n\n  &-subtitle {\n    font-size: 12px;\n    color: var(--theme-color-fg-default-shy);\n    margin-left: auto;\n  }\n\n  &-content {\n    margin-top: var(--theme-spacing-2);\n    padding-left: var(--theme-spacing-2);\n  }\n}\n\n.EmptyPath {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  padding: var(--theme-spacing-4) var(--theme-spacing-2);\n  color: var(--theme-color-fg-default-shy);\n\n  &-icon {\n    font-size: 32px;\n    margin-bottom: var(--theme-spacing-2);\n    opacity: 0.5;\n  }\n\n  &-text {\n    font-size: 14px;\n    margin-bottom: var(--theme-spacing-1);\n  }\n\n  &-hint {\n    font-size: 12px;\n    opacity: 0.7;\n  }\n}\n\n.DownstreamPath {\n  margin-bottom: var(--theme-spacing-2);\n\n  &:last-child {\n    margin-bottom: 0;\n  }\n}\n\n.PathBranch {\n  font-size: 12px;\n  font-weight: 600;\n  color: var(--theme-color-primary);\n  margin-bottom: var(--theme-spacing-1);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"DataLineagePanel": `DataLineagePanel-module__DataLineagePanel--yE0Q8`,
	"EmptyState": `DataLineagePanel-module__EmptyState--w7tP7`,
	"EmptyState-icon": `DataLineagePanel-module__EmptyState-icon--I9sjY`,
	"EmptyState-title": `DataLineagePanel-module__EmptyState-title--IuZwM`,
	"EmptyState-description": `DataLineagePanel-module__EmptyState-description--O0aQK`,
	"Header": `DataLineagePanel-module__Header--Bcgq4`,
	"Header-title": `DataLineagePanel-module__Header-title--NTMQp`,
	"Header-icon": `DataLineagePanel-module__Header-icon--ZzkUL`,
	"Header-actions": `DataLineagePanel-module__Header-actions--ZBR2H`,
	"Button": `DataLineagePanel-module__Button--B2j76`,
	"SelectedNode": `DataLineagePanel-module__SelectedNode--FMPuA`,
	"SelectedNode-label": `DataLineagePanel-module__SelectedNode-label--AINOF`,
	"SelectedNode-meta": `DataLineagePanel-module__SelectedNode-meta--KE2zQ`,
	"SelectedNode-component": `DataLineagePanel-module__SelectedNode-component--RWQAc`,
	"Section": `DataLineagePanel-module__Section--kGdQG`,
	"Section-header": `DataLineagePanel-module__Section-header--JXrES`,
	"Section-toggle": `DataLineagePanel-module__Section-toggle--oWgA8`,
	"Section-title": `DataLineagePanel-module__Section-title--Rv0TO`,
	"Section-icon": `DataLineagePanel-module__Section-icon--wFXID`,
	"Section-subtitle": `DataLineagePanel-module__Section-subtitle--XYbAk`,
	"Section-content": `DataLineagePanel-module__Section-content--jNcKW`,
	"EmptyPath": `DataLineagePanel-module__EmptyPath--ovsHt`,
	"EmptyPath-icon": `DataLineagePanel-module__EmptyPath-icon--UyRRY`,
	"EmptyPath-text": `DataLineagePanel-module__EmptyPath-text--l65mK`,
	"EmptyPath-hint": `DataLineagePanel-module__EmptyPath-hint--eW76f`,
	"DownstreamPath": `DataLineagePanel-module__DownstreamPath--HJWWr`,
	"PathBranch": `DataLineagePanel-module__PathBranch--RL0bM`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 10660:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .iPadShowKeyboard {
	width: 58px;
	min-width: 0;
	height: 36px;
	min-height: 0;
	margin: 0;
	padding: 0;
	position: absolute;
	resize: none;
	overflow: hidden;
	background: url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIHZpZXdCb3g9IjAgMCA1MyAzNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAwKSI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNDguMDM2NCA0LjAxMDQySDQuMDA3NzlMNC4wMDc3OSAzMi4wMjg2SDQ4LjAzNjRWNC4wMTA0MlpNNC4wMDc3OSAwLjAwNzgxMjVDMS43OTcyMSAwLjAwNzgxMjUgMC4wMDUxODc5OSAxLjc5OTg0IDAuMDA1MTg3OTkgNC4wMTA0MlYzMi4wMjg2QzAuMDA1MTg3OTkgMzQuMjM5MiAxLjc5NzIxIDM2LjAzMTIgNC4wMDc3OSAzNi4wMzEySDQ4LjAzNjRDNTAuMjQ3IDM2LjAzMTIgNTIuMDM5IDM0LjIzOTIgNTIuMDM5IDMyLjAyODZWNC4wMTA0MkM1Mi4wMzkgMS43OTk4NCA1MC4yNDcgMC4wMDc4MTI1IDQ4LjAzNjQgMC4wMDc4MTI1SDQuMDA3NzlaTTguMDEwNDIgOC4wMTMwMkgxMi4wMTNWMTIuMDE1Nkg4LjAxMDQyVjguMDEzMDJaTTIwLjAxODIgOC4wMTMwMkgxNi4wMTU2VjEyLjAxNTZIMjAuMDE4MlY4LjAxMzAyWk0yNC4wMjA4IDguMDEzMDJIMjguMDIzNFYxMi4wMTU2SDI0LjAyMDhWOC4wMTMwMlpNMzYuMDI4NiA4LjAxMzAySDMyLjAyNlYxMi4wMTU2SDM2LjAyODZWOC4wMTMwMlpNNDAuMDMxMiA4LjAxMzAySDQ0LjAzMzlWMTIuMDE1Nkg0MC4wMzEyVjguMDEzMDJaTTE2LjAxNTYgMTYuMDE4Mkg4LjAxMDQyVjIwLjAyMDhIMTYuMDE1NlYxNi4wMTgyWk0yMC4wMTgyIDE2LjAxODJIMjQuMDIwOFYyMC4wMjA4SDIwLjAxODJWMTYuMDE4MlpNMzIuMDI2IDE2LjAxODJIMjguMDIzNFYyMC4wMjA4SDMyLjAyNlYxNi4wMTgyWk00NC4wMzM5IDE2LjAxODJWMjAuMDIwOEgzNi4wMjg2VjE2LjAxODJINDQuMDMzOVpNMTIuMDEzIDI0LjAyMzRIOC4wMTA0MlYyOC4wMjZIMTIuMDEzVjI0LjAyMzRaTTE2LjAxNTYgMjQuMDIzNEgzNi4wMjg2VjI4LjAyNkgxNi4wMTU2VjI0LjAyMzRaTTQ0LjAzMzkgMjQuMDIzNEg0MC4wMzEyVjI4LjAyNkg0NC4wMzM5VjI0LjAyMzRaIiBmaWxsPSIjNDI0MjQyIi8+CjwvZz4KPGRlZnM+CjxjbGlwUGF0aCBpZD0iY2xpcDAiPgo8cmVjdCB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==") center center no-repeat;
	border: 4px solid #F6F6F6;
	border-radius: 4px;
}

.monaco-editor.vs-dark .iPadShowKeyboard {
	background: url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIHZpZXdCb3g9IjAgMCA1MyAzNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAwKSI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNDguMDM2NCA0LjAxMDQySDQuMDA3NzlMNC4wMDc3OSAzMi4wMjg2SDQ4LjAzNjRWNC4wMTA0MlpNNC4wMDc3OSAwLjAwNzgxMjVDMS43OTcyMSAwLjAwNzgxMjUgMC4wMDUxODc5OSAxLjc5OTg0IDAuMDA1MTg3OTkgNC4wMTA0MlYzMi4wMjg2QzAuMDA1MTg3OTkgMzQuMjM5MiAxLjc5NzIxIDM2LjAzMTIgNC4wMDc3OSAzNi4wMzEySDQ4LjAzNjRDNTAuMjQ3IDM2LjAzMTIgNTIuMDM5IDM0LjIzOTIgNTIuMDM5IDMyLjAyODZWNC4wMTA0MkM1Mi4wMzkgMS43OTk4NCA1MC4yNDcgMC4wMDc4MTI1IDQ4LjAzNjQgMC4wMDc4MTI1SDQuMDA3NzlaTTguMDEwNDIgOC4wMTMwMkgxMi4wMTNWMTIuMDE1Nkg4LjAxMDQyVjguMDEzMDJaTTIwLjAxODIgOC4wMTMwMkgxNi4wMTU2VjEyLjAxNTZIMjAuMDE4MlY4LjAxMzAyWk0yNC4wMjA4IDguMDEzMDJIMjguMDIzNFYxMi4wMTU2SDI0LjAyMDhWOC4wMTMwMlpNMzYuMDI4NiA4LjAxMzAySDMyLjAyNlYxMi4wMTU2SDM2LjAyODZWOC4wMTMwMlpNNDAuMDMxMiA4LjAxMzAySDQ0LjAzMzlWMTIuMDE1Nkg0MC4wMzEyVjguMDEzMDJaTTE2LjAxNTYgMTYuMDE4Mkg4LjAxMDQyVjIwLjAyMDhIMTYuMDE1NlYxNi4wMTgyWk0yMC4wMTgyIDE2LjAxODJIMjQuMDIwOFYyMC4wMjA4SDIwLjAxODJWMTYuMDE4MlpNMzIuMDI2IDE2LjAxODJIMjguMDIzNFYyMC4wMjA4SDMyLjAyNlYxNi4wMTgyWk00NC4wMzM5IDE2LjAxODJWMjAuMDIwOEgzNi4wMjg2VjE2LjAxODJINDQuMDMzOVpNMTIuMDEzIDI0LjAyMzRIOC4wMTA0MlYyOC4wMjZIMTIuMDEzVjI0LjAyMzRaTTE2LjAxNTYgMjQuMDIzNEgzNi4wMjg2VjI4LjAyNkgxNi4wMTU2VjI0LjAyMzRaTTQ0LjAzMzkgMjQuMDIzNEg0MC4wMzEyVjI4LjAyNkg0NC4wMzM5VjI0LjAyMzRaIiBmaWxsPSIjQzVDNUM1Ii8+CjwvZz4KPGRlZnM+CjxjbGlwUGF0aCBpZD0iY2xpcDAiPgo8cmVjdCB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==") center center no-repeat;
	border: 4px solid #252526;
}`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,WAAW;CACX,YAAY;CACZ,YAAY;CACZ,aAAa;CACb,SAAS;CACT,UAAU;CACV,kBAAkB;CAClB,YAAY;CACZ,gBAAgB;CAChB,qnDAAqnD;CACrnD,yBAAyB;CACzB,kBAAkB;AACnB;;AAEA;CACC,qnDAAqnD;CACrnD,yBAAyB;AAC1B","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .iPadShowKeyboard {\n\twidth: 58px;\n\tmin-width: 0;\n\theight: 36px;\n\tmin-height: 0;\n\tmargin: 0;\n\tpadding: 0;\n\tposition: absolute;\n\tresize: none;\n\toverflow: hidden;\n\tbackground: url(\"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIHZpZXdCb3g9IjAgMCA1MyAzNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAwKSI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNDguMDM2NCA0LjAxMDQySDQuMDA3NzlMNC4wMDc3OSAzMi4wMjg2SDQ4LjAzNjRWNC4wMTA0MlpNNC4wMDc3OSAwLjAwNzgxMjVDMS43OTcyMSAwLjAwNzgxMjUgMC4wMDUxODc5OSAxLjc5OTg0IDAuMDA1MTg3OTkgNC4wMTA0MlYzMi4wMjg2QzAuMDA1MTg3OTkgMzQuMjM5MiAxLjc5NzIxIDM2LjAzMTIgNC4wMDc3OSAzNi4wMzEySDQ4LjAzNjRDNTAuMjQ3IDM2LjAzMTIgNTIuMDM5IDM0LjIzOTIgNTIuMDM5IDMyLjAyODZWNC4wMTA0MkM1Mi4wMzkgMS43OTk4NCA1MC4yNDcgMC4wMDc4MTI1IDQ4LjAzNjQgMC4wMDc4MTI1SDQuMDA3NzlaTTguMDEwNDIgOC4wMTMwMkgxMi4wMTNWMTIuMDE1Nkg4LjAxMDQyVjguMDEzMDJaTTIwLjAxODIgOC4wMTMwMkgxNi4wMTU2VjEyLjAxNTZIMjAuMDE4MlY4LjAxMzAyWk0yNC4wMjA4IDguMDEzMDJIMjguMDIzNFYxMi4wMTU2SDI0LjAyMDhWOC4wMTMwMlpNMzYuMDI4NiA4LjAxMzAySDMyLjAyNlYxMi4wMTU2SDM2LjAyODZWOC4wMTMwMlpNNDAuMDMxMiA4LjAxMzAySDQ0LjAzMzlWMTIuMDE1Nkg0MC4wMzEyVjguMDEzMDJaTTE2LjAxNTYgMTYuMDE4Mkg4LjAxMDQyVjIwLjAyMDhIMTYuMDE1NlYxNi4wMTgyWk0yMC4wMTgyIDE2LjAxODJIMjQuMDIwOFYyMC4wMjA4SDIwLjAxODJWMTYuMDE4MlpNMzIuMDI2IDE2LjAxODJIMjguMDIzNFYyMC4wMjA4SDMyLjAyNlYxNi4wMTgyWk00NC4wMzM5IDE2LjAxODJWMjAuMDIwOEgzNi4wMjg2VjE2LjAxODJINDQuMDMzOVpNMTIuMDEzIDI0LjAyMzRIOC4wMTA0MlYyOC4wMjZIMTIuMDEzVjI0LjAyMzRaTTE2LjAxNTYgMjQuMDIzNEgzNi4wMjg2VjI4LjAyNkgxNi4wMTU2VjI0LjAyMzRaTTQ0LjAzMzkgMjQuMDIzNEg0MC4wMzEyVjI4LjAyNkg0NC4wMzM5VjI0LjAyMzRaIiBmaWxsPSIjNDI0MjQyIi8+CjwvZz4KPGRlZnM+CjxjbGlwUGF0aCBpZD0iY2xpcDAiPgo8cmVjdCB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==\") center center no-repeat;\n\tborder: 4px solid #F6F6F6;\n\tborder-radius: 4px;\n}\n\n.monaco-editor.vs-dark .iPadShowKeyboard {\n\tbackground: url(\"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIHZpZXdCb3g9IjAgMCA1MyAzNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAwKSI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNDguMDM2NCA0LjAxMDQySDQuMDA3NzlMNC4wMDc3OSAzMi4wMjg2SDQ4LjAzNjRWNC4wMTA0MlpNNC4wMDc3OSAwLjAwNzgxMjVDMS43OTcyMSAwLjAwNzgxMjUgMC4wMDUxODc5OSAxLjc5OTg0IDAuMDA1MTg3OTkgNC4wMTA0MlYzMi4wMjg2QzAuMDA1MTg3OTkgMzQuMjM5MiAxLjc5NzIxIDM2LjAzMTIgNC4wMDc3OSAzNi4wMzEySDQ4LjAzNjRDNTAuMjQ3IDM2LjAzMTIgNTIuMDM5IDM0LjIzOTIgNTIuMDM5IDMyLjAyODZWNC4wMTA0MkM1Mi4wMzkgMS43OTk4NCA1MC4yNDcgMC4wMDc4MTI1IDQ4LjAzNjQgMC4wMDc4MTI1SDQuMDA3NzlaTTguMDEwNDIgOC4wMTMwMkgxMi4wMTNWMTIuMDE1Nkg4LjAxMDQyVjguMDEzMDJaTTIwLjAxODIgOC4wMTMwMkgxNi4wMTU2VjEyLjAxNTZIMjAuMDE4MlY4LjAxMzAyWk0yNC4wMjA4IDguMDEzMDJIMjguMDIzNFYxMi4wMTU2SDI0LjAyMDhWOC4wMTMwMlpNMzYuMDI4NiA4LjAxMzAySDMyLjAyNlYxMi4wMTU2SDM2LjAyODZWOC4wMTMwMlpNNDAuMDMxMiA4LjAxMzAySDQ0LjAzMzlWMTIuMDE1Nkg0MC4wMzEyVjguMDEzMDJaTTE2LjAxNTYgMTYuMDE4Mkg4LjAxMDQyVjIwLjAyMDhIMTYuMDE1NlYxNi4wMTgyWk0yMC4wMTgyIDE2LjAxODJIMjQuMDIwOFYyMC4wMjA4SDIwLjAxODJWMTYuMDE4MlpNMzIuMDI2IDE2LjAxODJIMjguMDIzNFYyMC4wMjA4SDMyLjAyNlYxNi4wMTgyWk00NC4wMzM5IDE2LjAxODJWMjAuMDIwOEgzNi4wMjg2VjE2LjAxODJINDQuMDMzOVpNMTIuMDEzIDI0LjAyMzRIOC4wMTA0MlYyOC4wMjZIMTIuMDEzVjI0LjAyMzRaTTE2LjAxNTYgMjQuMDIzNEgzNi4wMjg2VjI4LjAyNkgxNi4wMTU2VjI0LjAyMzRaTTQ0LjAzMzkgMjQuMDIzNEg0MC4wMzEyVjI4LjAyNkg0NC4wMzM5VjI0LjAyMzRaIiBmaWxsPSIjQzVDNUM1Ii8+CjwvZz4KPGRlZnM+CjxjbGlwUGF0aCBpZD0iY2xpcDAiPgo8cmVjdCB3aWR0aD0iNTMiIGhlaWdodD0iMzYiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==\") center center no-repeat;\n\tborder: 4px solid #252526;\n}"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 10774:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgViewportVerticalArrow = function SvgViewportVerticalArrow(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M19.9019 1.97154C20.8684 1.97154 21.6519 2.75505 21.6519 3.72154V22.1014C21.6519 23.0679 20.8684 23.8514 19.9019 23.8514H5.11816C4.15166 23.8514 3.36816 23.0679 3.36816 22.1014L3.36816 3.72154C3.36816 2.75504 4.15167 1.97154 5.11816 1.97154L19.9019 1.97154ZM20.1519 3.72154C20.1519 3.58347 20.04 3.47154 19.9019 3.47154L5.11816 3.47154C4.98009 3.47154 4.86816 3.58347 4.86816 3.72154L4.86816 22.1014C4.86816 22.2395 4.98009 22.3514 5.11816 22.3514H19.9019C20.04 22.3514 20.1519 22.2395 20.1519 22.1014V3.72154Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.51 20.1947C12.0958 20.1947 11.76 19.8589 11.76 19.4447L11.76 6.37279C11.76 5.95857 12.0958 5.62279 12.51 5.62279C12.9242 5.62279 13.26 5.95857 13.26 6.37279L13.26 19.4447C13.26 19.8589 12.9242 20.1947 12.51 20.1947Z",
    fill: "#B8B8B8"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M13.0404 19.975C12.7475 20.2679 12.2726 20.2679 11.9797 19.975L8.9797 16.975C8.68681 16.6821 8.68681 16.2072 8.9797 15.9144C9.2726 15.6215 9.74747 15.6215 10.0404 15.9144L12.51 18.384L14.9797 15.9144C15.2726 15.6215 15.7475 15.6215 16.0404 15.9144C16.3333 16.2073 16.3333 16.6821 16.0404 16.975L13.0404 19.975Z",
    fill: "#B8B8B8"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M13.0404 5.84209C12.7475 5.5492 12.2726 5.5492 11.9797 5.84209L8.9797 8.84209C8.68681 9.13498 8.68681 9.60986 8.9797 9.90275C9.27259 10.1956 9.74747 10.1956 10.0404 9.90275L12.51 7.43308L14.9797 9.90275C15.2726 10.1956 15.7475 10.1956 16.0404 9.90275C16.3333 9.60986 16.3333 9.13498 16.0404 8.84209L13.0404 5.84209Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgViewportVerticalArrow);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "dd5ba222372b752a3a887f15ff75a845.svg");

/***/ }),

/***/ 10785:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgStar = function SvgStar(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M15.4777 21.8874L20.3339 24.9707C20.9602 25.3658 21.7311 24.778 21.548 24.0554L20.1412 18.5247C20.1032 18.3714 20.1092 18.2104 20.1587 18.0604C20.2081 17.9104 20.2989 17.7774 20.4207 17.6768L24.7758 14.0442C25.3443 13.5721 25.0553 12.6182 24.3133 12.57L18.6285 12.2039C18.4734 12.1948 18.3242 12.1408 18.1993 12.0484C18.0744 11.956 17.9791 11.8292 17.9251 11.6836L15.8053 6.34557C15.7492 6.19131 15.647 6.05805 15.5125 5.96389C15.3781 5.86972 15.2179 5.81921 15.0538 5.81921C14.8896 5.81921 14.7294 5.86972 14.595 5.96389C14.4605 6.05805 14.3583 6.19131 14.3022 6.34557L12.1824 11.6836C12.1284 11.8292 12.0331 11.956 11.9082 12.0484C11.7833 12.1408 11.6341 12.1948 11.479 12.2039L5.79417 12.57C5.05225 12.6182 4.76318 13.5721 5.33167 14.0442L9.68686 17.6768C9.80859 17.7774 9.8994 17.9104 9.94884 18.0604C9.99827 18.2104 10.0043 18.3714 9.96628 18.5247L8.66551 23.6507C8.4439 24.5179 9.36889 25.2212 10.1108 24.7491L14.6298 21.8874C14.7565 21.8068 14.9036 21.764 15.0538 21.764C15.2039 21.764 15.351 21.8068 15.4777 21.8874Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgStar);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "72af6578dbb25c4953ba82a646a4b8ce.svg");

/***/ }),

/***/ 10800:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

@font-face {
	font-family: "codicon";
	font-display: block;
	src: url(./codicon.ttf) format("truetype");
}

.codicon[class*='codicon-'] {
	font: normal normal normal 16px/1 codicon;
	display: inline-block;
	text-decoration: none;
	text-rendering: auto;
	text-align: center;
	text-transform: none;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}

/* icon rules are dynamically created by the platform theme service (see iconsStyleSheet.ts) */
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/codicons/codicon/codicon.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,sBAAsB;CACtB,mBAAmB;CACnB,0CAA0C;AAC3C;;AAEA;CACC,yCAAyC;CACzC,qBAAqB;CACrB,qBAAqB;CACrB,oBAAoB;CACpB,kBAAkB;CAClB,oBAAoB;CACpB,mCAAmC;CACnC,kCAAkC;CAClC,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;AACtB;;AAEA,8FAA8F","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n@font-face {\n\tfont-family: \"codicon\";\n\tfont-display: block;\n\tsrc: url(./codicon.ttf) format(\"truetype\");\n}\n\n.codicon[class*='codicon-'] {\n\tfont: normal normal normal 16px/1 codicon;\n\tdisplay: inline-block;\n\ttext-decoration: none;\n\ttext-rendering: auto;\n\ttext-align: center;\n\ttext-transform: none;\n\t-webkit-font-smoothing: antialiased;\n\t-moz-osx-font-smoothing: grayscale;\n\tuser-select: none;\n\t-webkit-user-select: none;\n\t-ms-user-select: none;\n}\n\n/* icon rules are dynamically created by the platform theme service (see iconsStyleSheet.ts) */\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 10835:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/* Suggest widget*/

.monaco-editor .suggest-widget {
	width: 430px;
	z-index: 40;
	display: flex;
	flex-direction: column;
}

.monaco-editor .suggest-widget.message {
	flex-direction: row;
	align-items: center;
}

.monaco-editor .suggest-widget,
.monaco-editor .suggest-details {
	flex: 0 1 auto;
	width: 100%;
	border-style: solid;
	border-width: 1px;
	border-color: var(--vscode-editorSuggestWidget-border);
	background-color: var(--vscode-editorSuggestWidget-background);
}

.monaco-editor.hc-black .suggest-widget,
.monaco-editor.hc-black .suggest-details,
.monaco-editor.hc-light .suggest-widget,
.monaco-editor.hc-light .suggest-details {
	border-width: 2px;
}

/* Styles for status bar part */


.monaco-editor .suggest-widget .suggest-status-bar {
	box-sizing: border-box;
	display: none;
	flex-flow: row nowrap;
	justify-content: space-between;
	width: 100%;
	font-size: 80%;
	padding: 0 4px 0 4px;
	border-top: 1px solid var(--vscode-editorSuggestWidget-border);
	overflow: hidden;
}

.monaco-editor .suggest-widget.with-status-bar .suggest-status-bar {
	display: flex;
}

.monaco-editor .suggest-widget .suggest-status-bar .left {
	padding-right: 8px;
}

.monaco-editor .suggest-widget.with-status-bar .suggest-status-bar .action-label {
	color: var(--vscode-editorSuggestWidgetStatus-foreground);
}

.monaco-editor .suggest-widget.with-status-bar .suggest-status-bar .action-item:not(:last-of-type) .action-label {
	margin-right: 0;
}

.monaco-editor .suggest-widget.with-status-bar .suggest-status-bar .action-item:not(:last-of-type) .action-label::after {
	content: ', ';
	margin-right: 0.3em;
}

.monaco-editor .suggest-widget.with-status-bar .monaco-list .monaco-list-row>.contents>.main>.right>.readMore,
.monaco-editor .suggest-widget.with-status-bar .monaco-list .monaco-list-row.focused.string-label>.contents>.main>.right>.readMore {
	display: none;
}

.monaco-editor .suggest-widget.with-status-bar:not(.docs-side) .monaco-list .monaco-list-row:hover>.contents>.main>.right.can-expand-details>.details-label {
	width: 100%;
}

/* Styles for Message element for when widget is loading or is empty */

.monaco-editor .suggest-widget>.message {
	padding-left: 22px;
}

/** Styles for the list element **/

.monaco-editor .suggest-widget>.tree {
	height: 100%;
	width: 100%;
}

.monaco-editor .suggest-widget .monaco-list {
	user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}

/** Styles for each row in the list element **/

.monaco-editor .suggest-widget .monaco-list .monaco-list-row {
	display: flex;
	-mox-box-sizing: border-box;
	box-sizing: border-box;
	padding-right: 10px;
	background-repeat: no-repeat;
	background-position: 2px 2px;
	white-space: nowrap;
	cursor: pointer;
	touch-action: none;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused {
	color: var(--vscode-editorSuggestWidget-selectedForeground);
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused .codicon {
	color: var(--vscode-editorSuggestWidget-selectedIconForeground);
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents {
	flex: 1;
	height: 100%;
	overflow: hidden;
	padding-left: 2px;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main {
	display: flex;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: pre;
	justify-content: space-between;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.left,
.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right {
	display: flex;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row:not(.focused)>.contents>.main .monaco-icon-label {
	color: var(--vscode-editorSuggestWidget-foreground);
}

.monaco-editor .suggest-widget:not(.frozen) .monaco-highlighted-label .highlight {
	font-weight: bold;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main .monaco-highlighted-label .highlight {
	color: var(--vscode-editorSuggestWidget-highlightForeground);
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused>.contents>.main .monaco-highlighted-label .highlight {
	color: var(--vscode-editorSuggestWidget-focusHighlightForeground);
}

/** ReadMore Icon styles **/

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.header>.codicon-close,
.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.readMore::before {
	color: inherit;
	opacity: 1;
	font-size: 14px;
	cursor: pointer;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.header>.codicon-close {
	position: absolute;
	top: 6px;
	right: 2px;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.header>.codicon-close:hover,
.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.readMore:hover {
	opacity: 1;
}

/** signature, qualifier, type/details opacity **/

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.details-label {
	opacity: 0.7;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.left>.signature-label {
	overflow: hidden;
	text-overflow: ellipsis;
	opacity: 0.6;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.left>.qualifier-label {
	margin-left: 12px;
	opacity: 0.4;
	font-size: 85%;
	line-height: initial;
	text-overflow: ellipsis;
	overflow: hidden;
	align-self: center;
}

/** Type Info and icon next to the label in the focused completion item **/

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.details-label {
	font-size: 85%;
	margin-left: 1.1em;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.details-label>.monaco-tokenized-source {
	display: inline;
}

/** Details: if using CompletionItem#details, show on focus **/

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.details-label {
	display: none;
}

.monaco-editor .suggest-widget:not(.shows-details) .monaco-list .monaco-list-row.focused>.contents>.main>.right>.details-label {
	display: inline;
}

/** Details: if using CompletionItemLabel#details, always show **/

.monaco-editor .suggest-widget .monaco-list .monaco-list-row:not(.string-label)>.contents>.main>.right>.details-label,
.monaco-editor .suggest-widget.docs-side .monaco-list .monaco-list-row.focused:not(.string-label)>.contents>.main>.right>.details-label {
	display: inline;
}

/** Ellipsis on hover **/

.monaco-editor .suggest-widget:not(.docs-side) .monaco-list .monaco-list-row.focused:hover>.contents>.main>.right.can-expand-details>.details-label {
	width: calc(100% - 26px);
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.left {
	flex-shrink: 1;
	flex-grow: 1;
	overflow: hidden;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.left>.monaco-icon-label {
	flex-shrink: 0;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row:not(.string-label)>.contents>.main>.left>.monaco-icon-label {
	max-width: 100%;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row.string-label>.contents>.main>.left>.monaco-icon-label {
	flex-shrink: 1;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right {
	overflow: hidden;
	flex-shrink: 4;
	max-width: 70%;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.readMore {
	display: inline-block;
	position: absolute;
	right: 10px;
	width: 18px;
	height: 18px;
	visibility: hidden;
}

/** Do NOT display ReadMore when docs is side/below **/

.monaco-editor .suggest-widget.docs-side .monaco-list .monaco-list-row>.contents>.main>.right>.readMore {
	display: none !important;
}

/** Do NOT display ReadMore when using plain CompletionItemLabel (details/documentation might not be resolved) **/

.monaco-editor .suggest-widget .monaco-list .monaco-list-row.string-label>.contents>.main>.right>.readMore {
	display: none;
}

/** Focused item can show ReadMore, but can't when docs is side/below **/

.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused.string-label>.contents>.main>.right>.readMore {
	display: inline-block;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused:hover>.contents>.main>.right>.readMore {
	visibility: visible;
}

/** Styles for each row in the list **/

.monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-icon-label.deprecated {
	opacity: 0.66;
	text-decoration: unset;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-icon-label.deprecated>.monaco-icon-label-container>.monaco-icon-name-container {
	text-decoration: line-through;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-icon-label::before {
	height: 100%;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row .icon {
	display: block;
	height: 16px;
	width: 16px;
	margin-left: 2px;
	background-repeat: no-repeat;
	background-size: 80%;
	background-position: center;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row .icon.hide {
	display: none;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon {
	display: flex;
	align-items: center;
	margin-right: 4px;
}

.monaco-editor .suggest-widget.no-icons .monaco-list .monaco-list-row .icon,
.monaco-editor .suggest-widget.no-icons .monaco-list .monaco-list-row .suggest-icon::before {
	display: none;
}

.monaco-editor .suggest-widget .monaco-list .monaco-list-row .icon.customcolor .colorspan {
	margin: 0 0 0 0.3em;
	border: 0.1em solid #000;
	width: 0.7em;
	height: 0.7em;
	display: inline-block;
}

/** Styles for the docs of the completion item in focus **/

.monaco-editor .suggest-details-container {
	z-index: 41;
}

.monaco-editor .suggest-details {
	display: flex;
	flex-direction: column;
	cursor: default;
	color: var(--vscode-editorSuggestWidget-foreground);
}

.monaco-editor .suggest-details.focused {
	border-color: var(--vscode-focusBorder);
}

.monaco-editor .suggest-details a {
	color: var(--vscode-textLink-foreground);
}

.monaco-editor .suggest-details a:hover {
	color: var(--vscode-textLink-activeForeground);
}

.monaco-editor .suggest-details code {
	background-color: var(--vscode-textCodeBlock-background);
}

.monaco-editor .suggest-details.no-docs {
	display: none;
}

.monaco-editor .suggest-details>.monaco-scrollable-element {
	flex: 1;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body {
	box-sizing: border-box;
	height: 100%;
	width: 100%;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.header>.type {
	flex: 2;
	overflow: hidden;
	text-overflow: ellipsis;
	opacity: 0.7;
	white-space: pre;
	margin: 0 24px 0 0;
	padding: 4px 0 12px 5px;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.header>.type.auto-wrap {
	white-space: normal;
	word-break: break-all;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs {
	margin: 0;
	padding: 4px 5px;
	white-space: pre-wrap;
}

.monaco-editor .suggest-details.no-type>.monaco-scrollable-element>.body>.docs {
	margin-right: 24px;
	overflow: hidden;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs {
	padding: 0;
	white-space: initial;
	min-height: calc(1rem + 8px);
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs>div,
.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs>span:not(:empty) {
	padding: 4px 5px;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs>div>p:first-child {
	margin-top: 0;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs>div>p:last-child {
	margin-bottom: 0;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs .monaco-tokenized-source {
	white-space: pre;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs .code {
	white-space: pre-wrap;
	word-wrap: break-word;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs .codicon {
	vertical-align: sub;
}

.monaco-editor .suggest-details>.monaco-scrollable-element>.body>p:empty {
	display: none;
}

.monaco-editor .suggest-details code {
	border-radius: 3px;
	padding: 0 0.4em;
}

.monaco-editor .suggest-details ul {
	padding-left: 20px;
}

.monaco-editor .suggest-details ol {
	padding-left: 20px;
}

.monaco-editor .suggest-details p code {
	font-family: var(--monaco-monospace-font);
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/media/suggest.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F,kBAAkB;;AAElB;CACC,YAAY;CACZ,WAAW;CACX,aAAa;CACb,sBAAsB;AACvB;;AAEA;CACC,mBAAmB;CACnB,mBAAmB;AACpB;;AAEA;;CAEC,cAAc;CACd,WAAW;CACX,mBAAmB;CACnB,iBAAiB;CACjB,sDAAsD;CACtD,8DAA8D;AAC/D;;AAEA;;;;CAIC,iBAAiB;AAClB;;AAEA,+BAA+B;;;AAG/B;CACC,sBAAsB;CACtB,aAAa;CACb,qBAAqB;CACrB,8BAA8B;CAC9B,WAAW;CACX,cAAc;CACd,oBAAoB;CACpB,8DAA8D;CAC9D,gBAAgB;AACjB;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,kBAAkB;AACnB;;AAEA;CACC,yDAAyD;AAC1D;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,aAAa;CACb,mBAAmB;AACpB;;AAEA;;CAEC,aAAa;AACd;;AAEA;CACC,WAAW;AACZ;;AAEA,sEAAsE;;AAEtE;CACC,kBAAkB;AACnB;;AAEA,kCAAkC;;AAElC;CACC,YAAY;CACZ,WAAW;AACZ;;AAEA;CACC,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;AACtB;;AAEA,8CAA8C;;AAE9C;CACC,aAAa;CACb,2BAA2B;CAC3B,sBAAsB;CACtB,mBAAmB;CACnB,4BAA4B;CAC5B,4BAA4B;CAC5B,mBAAmB;CACnB,eAAe;CACf,kBAAkB;AACnB;;AAEA;CACC,2DAA2D;AAC5D;;AAEA;CACC,+DAA+D;AAChE;;AAEA;CACC,OAAO;CACP,YAAY;CACZ,gBAAgB;CAChB,iBAAiB;AAClB;;AAEA;CACC,aAAa;CACb,gBAAgB;CAChB,uBAAuB;CACvB,gBAAgB;CAChB,8BAA8B;AAC/B;;AAEA;;CAEC,aAAa;AACd;;AAEA;CACC,mDAAmD;AACpD;;AAEA;CACC,iBAAiB;AAClB;;AAEA;CACC,4DAA4D;AAC7D;;AAEA;CACC,iEAAiE;AAClE;;AAEA,2BAA2B;;AAE3B;;CAEC,cAAc;CACd,UAAU;CACV,eAAe;CACf,eAAe;AAChB;;AAEA;CACC,kBAAkB;CAClB,QAAQ;CACR,UAAU;AACX;;AAEA;;CAEC,UAAU;AACX;;AAEA,iDAAiD;;AAEjD;CACC,YAAY;AACb;;AAEA;CACC,gBAAgB;CAChB,uBAAuB;CACvB,YAAY;AACb;;AAEA;CACC,iBAAiB;CACjB,YAAY;CACZ,cAAc;CACd,oBAAoB;CACpB,uBAAuB;CACvB,gBAAgB;CAChB,kBAAkB;AACnB;;AAEA,0EAA0E;;AAE1E;CACC,cAAc;CACd,kBAAkB;CAClB,gBAAgB;CAChB,uBAAuB;CACvB,mBAAmB;AACpB;;AAEA;CACC,eAAe;AAChB;;AAEA,8DAA8D;;AAE9D;CACC,aAAa;AACd;;AAEA;CACC,eAAe;AAChB;;AAEA,iEAAiE;;AAEjE;;CAEC,eAAe;AAChB;;AAEA,wBAAwB;;AAExB;CACC,wBAAwB;AACzB;;AAEA;CACC,cAAc;CACd,YAAY;CACZ,gBAAgB;AACjB;;AAEA;CACC,cAAc;AACf;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,cAAc;AACf;;AAEA;CACC,gBAAgB;CAChB,cAAc;CACd,cAAc;AACf;;AAEA;CACC,qBAAqB;CACrB,kBAAkB;CAClB,WAAW;CACX,WAAW;CACX,YAAY;CACZ,kBAAkB;AACnB;;AAEA,sDAAsD;;AAEtD;CACC,wBAAwB;AACzB;;AAEA,iHAAiH;;AAEjH;CACC,aAAa;AACd;;AAEA,wEAAwE;;AAExE;CACC,qBAAqB;AACtB;;AAEA;CACC,mBAAmB;AACpB;;AAEA,sCAAsC;;AAEtC;CACC,aAAa;CACb,sBAAsB;AACvB;;AAEA;CACC,6BAA6B;AAC9B;;AAEA;CACC,YAAY;AACb;;AAEA;CACC,cAAc;CACd,YAAY;CACZ,WAAW;CACX,gBAAgB;CAChB,4BAA4B;CAC5B,oBAAoB;CACpB,2BAA2B;AAC5B;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,aAAa;CACb,mBAAmB;CACnB,iBAAiB;AAClB;;AAEA;;CAEC,aAAa;AACd;;AAEA;CACC,mBAAmB;CACnB,wBAAwB;CACxB,YAAY;CACZ,aAAa;CACb,qBAAqB;AACtB;;AAEA,0DAA0D;;AAE1D;CACC,WAAW;AACZ;;AAEA;CACC,aAAa;CACb,sBAAsB;CACtB,eAAe;CACf,mDAAmD;AACpD;;AAEA;CACC,uCAAuC;AACxC;;AAEA;CACC,wCAAwC;AACzC;;AAEA;CACC,8CAA8C;AAC/C;;AAEA;CACC,wDAAwD;AACzD;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,OAAO;AACR;;AAEA;CACC,sBAAsB;CACtB,YAAY;CACZ,WAAW;AACZ;;AAEA;CACC,OAAO;CACP,gBAAgB;CAChB,uBAAuB;CACvB,YAAY;CACZ,gBAAgB;CAChB,kBAAkB;CAClB,uBAAuB;AACxB;;AAEA;CACC,mBAAmB;CACnB,qBAAqB;AACtB;;AAEA;CACC,SAAS;CACT,gBAAgB;CAChB,qBAAqB;AACtB;;AAEA;CACC,kBAAkB;CAClB,gBAAgB;AACjB;;AAEA;CACC,UAAU;CACV,oBAAoB;CACpB,4BAA4B;AAC7B;;AAEA;;CAEC,gBAAgB;AACjB;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,qBAAqB;CACrB,qBAAqB;AACtB;;AAEA;CACC,mBAAmB;AACpB;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,kBAAkB;CAClB,gBAAgB;AACjB;;AAEA;CACC,kBAAkB;AACnB;;AAEA;CACC,kBAAkB;AACnB;;AAEA;CACC,yCAAyC;AAC1C","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/* Suggest widget*/\n\n.monaco-editor .suggest-widget {\n\twidth: 430px;\n\tz-index: 40;\n\tdisplay: flex;\n\tflex-direction: column;\n}\n\n.monaco-editor .suggest-widget.message {\n\tflex-direction: row;\n\talign-items: center;\n}\n\n.monaco-editor .suggest-widget,\n.monaco-editor .suggest-details {\n\tflex: 0 1 auto;\n\twidth: 100%;\n\tborder-style: solid;\n\tborder-width: 1px;\n\tborder-color: var(--vscode-editorSuggestWidget-border);\n\tbackground-color: var(--vscode-editorSuggestWidget-background);\n}\n\n.monaco-editor.hc-black .suggest-widget,\n.monaco-editor.hc-black .suggest-details,\n.monaco-editor.hc-light .suggest-widget,\n.monaco-editor.hc-light .suggest-details {\n\tborder-width: 2px;\n}\n\n/* Styles for status bar part */\n\n\n.monaco-editor .suggest-widget .suggest-status-bar {\n\tbox-sizing: border-box;\n\tdisplay: none;\n\tflex-flow: row nowrap;\n\tjustify-content: space-between;\n\twidth: 100%;\n\tfont-size: 80%;\n\tpadding: 0 4px 0 4px;\n\tborder-top: 1px solid var(--vscode-editorSuggestWidget-border);\n\toverflow: hidden;\n}\n\n.monaco-editor .suggest-widget.with-status-bar .suggest-status-bar {\n\tdisplay: flex;\n}\n\n.monaco-editor .suggest-widget .suggest-status-bar .left {\n\tpadding-right: 8px;\n}\n\n.monaco-editor .suggest-widget.with-status-bar .suggest-status-bar .action-label {\n\tcolor: var(--vscode-editorSuggestWidgetStatus-foreground);\n}\n\n.monaco-editor .suggest-widget.with-status-bar .suggest-status-bar .action-item:not(:last-of-type) .action-label {\n\tmargin-right: 0;\n}\n\n.monaco-editor .suggest-widget.with-status-bar .suggest-status-bar .action-item:not(:last-of-type) .action-label::after {\n\tcontent: ', ';\n\tmargin-right: 0.3em;\n}\n\n.monaco-editor .suggest-widget.with-status-bar .monaco-list .monaco-list-row>.contents>.main>.right>.readMore,\n.monaco-editor .suggest-widget.with-status-bar .monaco-list .monaco-list-row.focused.string-label>.contents>.main>.right>.readMore {\n\tdisplay: none;\n}\n\n.monaco-editor .suggest-widget.with-status-bar:not(.docs-side) .monaco-list .monaco-list-row:hover>.contents>.main>.right.can-expand-details>.details-label {\n\twidth: 100%;\n}\n\n/* Styles for Message element for when widget is loading or is empty */\n\n.monaco-editor .suggest-widget>.message {\n\tpadding-left: 22px;\n}\n\n/** Styles for the list element **/\n\n.monaco-editor .suggest-widget>.tree {\n\theight: 100%;\n\twidth: 100%;\n}\n\n.monaco-editor .suggest-widget .monaco-list {\n\tuser-select: none;\n\t-webkit-user-select: none;\n\t-ms-user-select: none;\n}\n\n/** Styles for each row in the list element **/\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row {\n\tdisplay: flex;\n\t-mox-box-sizing: border-box;\n\tbox-sizing: border-box;\n\tpadding-right: 10px;\n\tbackground-repeat: no-repeat;\n\tbackground-position: 2px 2px;\n\twhite-space: nowrap;\n\tcursor: pointer;\n\ttouch-action: none;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused {\n\tcolor: var(--vscode-editorSuggestWidget-selectedForeground);\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused .codicon {\n\tcolor: var(--vscode-editorSuggestWidget-selectedIconForeground);\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents {\n\tflex: 1;\n\theight: 100%;\n\toverflow: hidden;\n\tpadding-left: 2px;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main {\n\tdisplay: flex;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\twhite-space: pre;\n\tjustify-content: space-between;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.left,\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right {\n\tdisplay: flex;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row:not(.focused)>.contents>.main .monaco-icon-label {\n\tcolor: var(--vscode-editorSuggestWidget-foreground);\n}\n\n.monaco-editor .suggest-widget:not(.frozen) .monaco-highlighted-label .highlight {\n\tfont-weight: bold;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main .monaco-highlighted-label .highlight {\n\tcolor: var(--vscode-editorSuggestWidget-highlightForeground);\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused>.contents>.main .monaco-highlighted-label .highlight {\n\tcolor: var(--vscode-editorSuggestWidget-focusHighlightForeground);\n}\n\n/** ReadMore Icon styles **/\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.header>.codicon-close,\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.readMore::before {\n\tcolor: inherit;\n\topacity: 1;\n\tfont-size: 14px;\n\tcursor: pointer;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.header>.codicon-close {\n\tposition: absolute;\n\ttop: 6px;\n\tright: 2px;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.header>.codicon-close:hover,\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.readMore:hover {\n\topacity: 1;\n}\n\n/** signature, qualifier, type/details opacity **/\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.details-label {\n\topacity: 0.7;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.left>.signature-label {\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\topacity: 0.6;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.left>.qualifier-label {\n\tmargin-left: 12px;\n\topacity: 0.4;\n\tfont-size: 85%;\n\tline-height: initial;\n\ttext-overflow: ellipsis;\n\toverflow: hidden;\n\talign-self: center;\n}\n\n/** Type Info and icon next to the label in the focused completion item **/\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.details-label {\n\tfont-size: 85%;\n\tmargin-left: 1.1em;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\twhite-space: nowrap;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.details-label>.monaco-tokenized-source {\n\tdisplay: inline;\n}\n\n/** Details: if using CompletionItem#details, show on focus **/\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.details-label {\n\tdisplay: none;\n}\n\n.monaco-editor .suggest-widget:not(.shows-details) .monaco-list .monaco-list-row.focused>.contents>.main>.right>.details-label {\n\tdisplay: inline;\n}\n\n/** Details: if using CompletionItemLabel#details, always show **/\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row:not(.string-label)>.contents>.main>.right>.details-label,\n.monaco-editor .suggest-widget.docs-side .monaco-list .monaco-list-row.focused:not(.string-label)>.contents>.main>.right>.details-label {\n\tdisplay: inline;\n}\n\n/** Ellipsis on hover **/\n\n.monaco-editor .suggest-widget:not(.docs-side) .monaco-list .monaco-list-row.focused:hover>.contents>.main>.right.can-expand-details>.details-label {\n\twidth: calc(100% - 26px);\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.left {\n\tflex-shrink: 1;\n\tflex-grow: 1;\n\toverflow: hidden;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.left>.monaco-icon-label {\n\tflex-shrink: 0;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row:not(.string-label)>.contents>.main>.left>.monaco-icon-label {\n\tmax-width: 100%;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row.string-label>.contents>.main>.left>.monaco-icon-label {\n\tflex-shrink: 1;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right {\n\toverflow: hidden;\n\tflex-shrink: 4;\n\tmax-width: 70%;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row>.contents>.main>.right>.readMore {\n\tdisplay: inline-block;\n\tposition: absolute;\n\tright: 10px;\n\twidth: 18px;\n\theight: 18px;\n\tvisibility: hidden;\n}\n\n/** Do NOT display ReadMore when docs is side/below **/\n\n.monaco-editor .suggest-widget.docs-side .monaco-list .monaco-list-row>.contents>.main>.right>.readMore {\n\tdisplay: none !important;\n}\n\n/** Do NOT display ReadMore when using plain CompletionItemLabel (details/documentation might not be resolved) **/\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row.string-label>.contents>.main>.right>.readMore {\n\tdisplay: none;\n}\n\n/** Focused item can show ReadMore, but can't when docs is side/below **/\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused.string-label>.contents>.main>.right>.readMore {\n\tdisplay: inline-block;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row.focused:hover>.contents>.main>.right>.readMore {\n\tvisibility: visible;\n}\n\n/** Styles for each row in the list **/\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-icon-label.deprecated {\n\topacity: 0.66;\n\ttext-decoration: unset;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-icon-label.deprecated>.monaco-icon-label-container>.monaco-icon-name-container {\n\ttext-decoration: line-through;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row .monaco-icon-label::before {\n\theight: 100%;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row .icon {\n\tdisplay: block;\n\theight: 16px;\n\twidth: 16px;\n\tmargin-left: 2px;\n\tbackground-repeat: no-repeat;\n\tbackground-size: 80%;\n\tbackground-position: center;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row .icon.hide {\n\tdisplay: none;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row .suggest-icon {\n\tdisplay: flex;\n\talign-items: center;\n\tmargin-right: 4px;\n}\n\n.monaco-editor .suggest-widget.no-icons .monaco-list .monaco-list-row .icon,\n.monaco-editor .suggest-widget.no-icons .monaco-list .monaco-list-row .suggest-icon::before {\n\tdisplay: none;\n}\n\n.monaco-editor .suggest-widget .monaco-list .monaco-list-row .icon.customcolor .colorspan {\n\tmargin: 0 0 0 0.3em;\n\tborder: 0.1em solid #000;\n\twidth: 0.7em;\n\theight: 0.7em;\n\tdisplay: inline-block;\n}\n\n/** Styles for the docs of the completion item in focus **/\n\n.monaco-editor .suggest-details-container {\n\tz-index: 41;\n}\n\n.monaco-editor .suggest-details {\n\tdisplay: flex;\n\tflex-direction: column;\n\tcursor: default;\n\tcolor: var(--vscode-editorSuggestWidget-foreground);\n}\n\n.monaco-editor .suggest-details.focused {\n\tborder-color: var(--vscode-focusBorder);\n}\n\n.monaco-editor .suggest-details a {\n\tcolor: var(--vscode-textLink-foreground);\n}\n\n.monaco-editor .suggest-details a:hover {\n\tcolor: var(--vscode-textLink-activeForeground);\n}\n\n.monaco-editor .suggest-details code {\n\tbackground-color: var(--vscode-textCodeBlock-background);\n}\n\n.monaco-editor .suggest-details.no-docs {\n\tdisplay: none;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element {\n\tflex: 1;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body {\n\tbox-sizing: border-box;\n\theight: 100%;\n\twidth: 100%;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.header>.type {\n\tflex: 2;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\topacity: 0.7;\n\twhite-space: pre;\n\tmargin: 0 24px 0 0;\n\tpadding: 4px 0 12px 5px;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.header>.type.auto-wrap {\n\twhite-space: normal;\n\tword-break: break-all;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs {\n\tmargin: 0;\n\tpadding: 4px 5px;\n\twhite-space: pre-wrap;\n}\n\n.monaco-editor .suggest-details.no-type>.monaco-scrollable-element>.body>.docs {\n\tmargin-right: 24px;\n\toverflow: hidden;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs {\n\tpadding: 0;\n\twhite-space: initial;\n\tmin-height: calc(1rem + 8px);\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs>div,\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs>span:not(:empty) {\n\tpadding: 4px 5px;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs>div>p:first-child {\n\tmargin-top: 0;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs>div>p:last-child {\n\tmargin-bottom: 0;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs .monaco-tokenized-source {\n\twhite-space: pre;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs .code {\n\twhite-space: pre-wrap;\n\tword-wrap: break-word;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>.docs.markdown-docs .codicon {\n\tvertical-align: sub;\n}\n\n.monaco-editor .suggest-details>.monaco-scrollable-element>.body>p:empty {\n\tdisplay: none;\n}\n\n.monaco-editor .suggest-details code {\n\tborder-radius: 3px;\n\tpadding: 0 0.4em;\n}\n\n.monaco-editor .suggest-details ul {\n\tpadding-left: 20px;\n}\n\n.monaco-editor .suggest-details ol {\n\tpadding-left: 20px;\n}\n\n.monaco-editor .suggest-details p code {\n\tfont-family: var(--monaco-monospace-font);\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 11058:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  gf: () => (/* reexport */ CommitHistory),
  s9: () => (/* reexport */ CommitHistoryEntry),
  v7: () => (/* reexport */ git_action_error/* GitActionError */.v7),
  I7: () => (/* reexport */ git_action_error/* GitActionErrorCode */.I7),
  gR: () => (/* reexport */ git_action_error/* createErrorFromMessage */.gR),
  PR: () => (/* reexport */ deleteLocalBranch),
  SE: () => (/* reexport */ deleteRemoteBranch),
  hd: () => (/* reexport */ fetch_fetch),
  p9: () => (/* reexport */ getBranches),
  Bo: () => (/* reexport */ actions_remote/* getRemote */.B),
  a$: () => (/* reexport */ pull_pull),
  VC: () => (/* reexport */ push_push)
});

// UNUSED EXPORTS: setRemoteURL

// EXTERNAL MODULE: ../noodl-git/src/core/for-each-ref.ts
var for_each_ref = __webpack_require__(38332);
// EXTERNAL MODULE: external "underscore"
var external_underscore_ = __webpack_require__(80002);
// EXTERNAL MODULE: ../noodl-git/src/core/update-ref.ts
var update_ref = __webpack_require__(99474);
// EXTERNAL MODULE: ../noodl-git/src/core/push.ts
var push = __webpack_require__(6875);
// EXTERNAL MODULE: ../noodl-git/src/actions/git-action-error.ts
var git_action_error = __webpack_require__(55861);
;// ../noodl-git/src/actions/branch.ts





async function getBranches(repositoryDir) {
    const branches = await (0,for_each_ref/* getBranches */.p9)(repositoryDir);
    const groupped = (0,external_underscore_.groupBy)(branches, (x) => x.type);
    Object.keys(groupped).forEach((key) => (0,external_underscore_.sortBy)(groupped[key], (x) => x.name));
    return Object.keys(groupped).flatMap((key) => groupped[key]);
}
/**
 * Delete a local branch, this will leave the remote branch intact if there is one.
 *
 * @param repositoryDir
 * @param branch
 */
async function deleteLocalBranch(repositoryDir, branch) {
    await (0,update_ref/* deleteRef */.j)(repositoryDir, branch.ref);
}
/**
 * Delete a remote branch.
 *
 * @param repositoryDir
 * @param branch
 */
async function deleteRemoteBranch(repositoryDir, branch) {
    if (!branch.upstream) {
        throw new Error("Branch is not remote.");
    }
    try {
        await (0,push/* pushDelete */.Y)(repositoryDir, branch.upstreamRemoteName, branch.nameWithoutRemote);
    }
    catch (error) {
        const message = error.toString();
        if (message.includes("remote ref does not exist")) {
            throw new git_action_error/* GitActionError */.v7(git_action_error/* GitActionErrorCode */.I7.BranchNotExisting);
        }
        else {
            throw error;
        }
    }
}

// EXTERNAL MODULE: ../noodl-git/src/core/logs.ts
var logs = __webpack_require__(41176);
// EXTERNAL MODULE: ../noodl-git/src/core/models/snapshot.ts + 1 modules
var snapshot = __webpack_require__(60629);
;// ../noodl-git/src/actions/history.ts


class CommitHistoryEntry extends snapshot/* Commit */.gn {
    constructor(commit, isLocalAhead, isRemoteAhead) {
        super(commit.repositoryDir, commit.sha, commit.shortSha, commit.summary, commit.body, commit.author, commit.committer, commit.parentSHAs, commit.tags);
        this.isLocalAhead = isLocalAhead;
        this.isRemoteAhead = isRemoteAhead;
    }
}
/**
 * Class designed to handle history between multiple branches.
 */
class CommitHistory {
    constructor(repositoryDir, branch) {
        this.repositoryDir = repositoryDir;
        this.branch = branch;
    }
    async fetch(count) {
        const localGitCommits = await (0,logs/* getCommits */.JR)(this.repositoryDir, undefined, count);
        let commits = localGitCommits.map((x) => new CommitHistoryEntry(x, false, false));
        if (this.branch.remote) {
            const remoteAheadGitCommits = await (0,logs/* getCommits */.JR)(this.repositoryDir, `${this.branch.nameWithoutRemote}..${this.branch.remote.name}`, count);
            const remoteOnlyCommits = remoteAheadGitCommits.map((x) => new CommitHistoryEntry(x, false, true));
            //get commits that aren't pushed
            const localAheadGitCommits = await (0,logs/* getCommits */.JR)(this.repositoryDir, `${this.branch.remote.name}..${this.branch.nameWithoutRemote}`, count);
            localAheadGitCommits.forEach((aheadCommit) => {
                const c = commits.find((c) => c.sha === aheadCommit.sha);
                if (c) {
                    c.isLocalAhead = true;
                }
            });
            commits = remoteOnlyCommits.concat(commits);
        }
        else {
            // there is no remote, it's a local branch
            // flag all the commits as being "ahead" of
            // the remote (even the commit that was the branching points, and commits before it)
            commits.forEach((c) => (c.isLocalAhead = true));
        }
        return commits;
    }
}

// EXTERNAL MODULE: ../noodl-git/src/actions/remote.ts
var actions_remote = __webpack_require__(93125);
;// ../noodl-git/src/actions/push.ts



async function push_push({ baseDir, currentBranch, onProgress }) {
    const remote = await (0,actions_remote/* getRemote */.B)(baseDir);
    try {
        return await (0,push/* push */.V)(baseDir, remote, currentBranch.nameWithoutRemote, currentBranch.upstreamWithoutRemote, [], undefined, onProgress);
    }
    catch (error) {
        const message = error.toString();
        if (message.includes('Updates were rejected because the remote contains work that you do')) {
            throw new Error('Updates were rejected because there are new changes that you do not have locally. Pull to get the latest changes.');
        }
        throw (0,git_action_error/* createErrorFromMessage */.gR)(error.toString());
    }
}

// EXTERNAL MODULE: ../noodl-git/src/core/authentication.ts
var authentication = __webpack_require__(38495);
// EXTERNAL MODULE: ../noodl-git/src/core/client.ts + 14 modules
var client = __webpack_require__(85869);
// EXTERNAL MODULE: ../noodl-git/src/core/git-error.ts
var git_error = __webpack_require__(55952);
// EXTERNAL MODULE: ../noodl-git/src/core/progress/index.ts + 8 modules
var progress = __webpack_require__(51436);
;// ../noodl-git/src/core/pull.ts




/**
 * Returns the arguments to use on any git operation that can end up
 * triggering a rebase.
 */
function gitRebaseArguments() {
    return [
        // Explicitly set the rebase backend to merge.
        // We need to force this option to be sure that Desktop
        // uses the merge backend even if the user has the apply backend
        // configured, since this is the only one supported.
        // This can go away once git deprecates the apply backend.
        '-c',
        'rebase.backend=merge'
    ];
}
async function getPullArgs(repositoryDir, remote, branch, progressCallback) {
    const networkArguments = await (0,client/* gitNetworkArguments */.X)(repositoryDir);
    const args = [...networkArguments, ...gitRebaseArguments(), 'pull'];
    if (progressCallback != null) {
        args.push('--progress');
    }
    args.push(remote);
    args.push(branch);
    args.push('--rebase'); //this is used to reconcile the divergent branches so git doesn't complain, and to prevent merge commits when you have local changes
    return args;
}
/**
 * Pull from the specified remote.
 *
 * @param repository - The repository in which the pull should take place
 *
 * @param remote     - The name of the remote that should be pulled from
 *
 * @param branch
 *
 * @param progressCallback - An optional function which will be invoked
 *                           with information about the current progress
 *                           of the pull operation. When provided this enables
 *                           the '--progress' command line flag for
 *                           'git pull'.
 */
async function pull(repositoryDir, remote, branch, progressCallback) {
    let opts = {
        expectedErrors: authentication/* AuthenticationErrors */.A
    };
    if (progressCallback) {
        const title = `Pulling ${remote.name}`;
        const kind = 'pull';
        opts = await (0,progress/* executionOptionsWithProgress */.s_)({ ...opts }, new progress/* PullProgressParser */.I8(), (progress) => {
            // In addition to progress output from the remote end and from
            // git itself, the stderr output from pull contains information
            // about ref updates. We don't need to bring those into the progress
            // stream so we'll just punt on anything we don't know about for now.
            if (progress.kind === 'context') {
                if (!progress.text.startsWith('remote: Counting objects')) {
                    return;
                }
            }
            const description = progress.kind === 'progress' ? progress.details.text : progress.text;
            const value = progress.percent;
            progressCallback({
                kind,
                title,
                description,
                value,
                remote: remote.name
            });
        });
        // Initial progress
        progressCallback({ kind, title, value: 0, remote: remote.name });
    }
    const args = await getPullArgs(repositoryDir, remote.name, typeof branch === 'object' ? branch.name : branch, progressCallback);
    const result = await (0,client/* git */.$)(args, repositoryDir, 'pull', opts);
    if (result.gitErrorDescription) {
        throw new git_error/* GitError */.XS(result, args);
    }
}

;// ../noodl-git/src/actions/pull.ts


async function pull_pull(repositoryDir, remote, branch, progressCallback) {
    try {
        return await pull(repositoryDir, remote, branch, progressCallback);
    }
    catch (error) {
        throw (0,git_action_error/* createErrorFromMessage */.gR)(error.toString());
    }
}

;// ../noodl-git/src/core/fetch.ts


async function getFetchArgs(repositoryDir, remote, progressCallback) {
    const networkArguments = await (0,client/* gitNetworkArguments */.X)(repositoryDir);
    return progressCallback != null
        ? [...networkArguments, "fetch", "--progress", "--prune", remote]
        : [...networkArguments, "fetch", "--prune", remote];
}
/**
 * Fetch from the given remote.
 *
 * @param repository - The repository to fetch into
 *
 * @param remote     - The remote to fetch from
 *
 * @param progressCallback - An optional function which will be invoked
 *                           with information about the current progress
 *                           of the fetch operation. When provided this enables
 *                           the '--progress' command line flag for
 *                           'git fetch'.
 */
async function fetch(repositoryDir, remote, progressCallback) {
    let opts = {
        successExitCodes: new Set([0]),
    };
    if (progressCallback) {
        const title = `Fetching ${remote.name}`;
        const kind = "fetch";
        opts = await (0,progress/* executionOptionsWithProgress */.s_)({ ...opts }, new progress/* FetchProgressParser */.Pm(), (progress) => {
            // In addition to progress output from the remote end and from
            // git itself, the stderr output from pull contains information
            // about ref updates. We don't need to bring those into the progress
            // stream so we'll just punt on anything we don't know about for now.
            if (progress.kind === "context") {
                if (!progress.text.startsWith("remote: Counting objects")) {
                    return;
                }
            }
            const description = progress.kind === "progress" ? progress.details.text : progress.text;
            const value = progress.percent;
            progressCallback({
                kind,
                title,
                description,
                value,
                remote: remote.name,
            });
        });
    }
    const args = await getFetchArgs(repositoryDir, remote.name, progressCallback);
    return await (0,client/* git */.$)(args, repositoryDir, "fetch", opts);
}
/** Fetch a given refspec from the given remote. */
async function fetchRefspec(repositoryDir, remote, refspec) {
    const options = {
        successExitCodes: new Set([0, 128]),
        env: {},
    };
    const networkArguments = await gitNetworkArguments(repositoryDir);
    const args = [...networkArguments, "fetch", remote.name, refspec];
    await git(args, repositoryDir, "fetchRefspec", options);
}
async function fastForwardBranches(repositoryDir, branches) {
    if (branches.length === 0) {
        return;
    }
    const refPairs = branches.map((branch) => `${branch.upstreamRef}:${branch.ref}`);
    const opts = {
        // Fetch exits with an exit code of 1 if one or more refs failed to update
        // which is what we expect will happen
        successExitCodes: new Set([0, 1]),
        env: {
            // This will make sure the reflog entries are correct after
            // fast-forwarding the branches.
            GIT_REFLOG_ACTION: "pull",
        },
        stdin: refPairs.join("\n"),
    };
    await git([
        "fetch",
        ".",
        // Make sure we don't try to update branches that can't be fast-forwarded
        // even if the user disabled this via the git config option
        // `fetch.showForcedUpdates`
        "--show-forced-updates",
        // Prevent `git fetch` from touching the `FETCH_HEAD`
        "--no-write-fetch-head",
        // Take branch refs from stdin to circumvent shell max line length
        // limitations (mainly on Windows)
        "--stdin",
    ], repositoryDir, "fastForwardBranches", opts);
}

;// ../noodl-git/src/actions/fetch.ts


async function fetch_fetch(repositoryDir, remote, progressCallback) {
    try {
        return await fetch(repositoryDir, remote, progressCallback);
    }
    catch (error) {
        throw (0,git_action_error/* createErrorFromMessage */.gR)(error.toString());
    }
}

;// ../noodl-git/src/actions/index.ts









/***/ }),

/***/ 11138:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   EventDispatcher: () => (/* binding */ EventDispatcher)
/* harmony export */ });
class EventDispatcher {
    constructor() {
        this.listeners = [];
    }
    on(event, listener, group) {
        this.listeners.push({ event: event, listener: listener, group: group });
    }
    notifyListeners(event, args) {
        const testForComps = event.split('.');
        function notify(event, listener, eventName) {
            const comps = event.split('.');
            if (comps[0] === testForComps[0] && (comps[1] === '*' || comps[1] === testForComps[1]))
                listener(args, eventName);
        }
        for (const i in this.listeners) {
            if (this.listeners[i].event instanceof Array) {
                for (const j in this.listeners[i].event)
                    notify(this.listeners[i].event[j], this.listeners[i].listener, event);
            }
            else {
                notify(this.listeners[i].event, this.listeners[i].listener, event);
            }
        }
    }
    emit(event, args) {
        this.notifyListeners(event, args);
    }
    off(group) {
        if (group === undefined)
            return;
        for (let i = 0; i < this.listeners.length; i++) {
            if (this.listeners[i].group === group) {
                this.listeners.splice(i, 1);
                i--;
            }
        }
    }
}
EventDispatcher.instance = new EventDispatcher();


/***/ }),

/***/ 11166:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .margin-view-overlays .line-numbers {
	font-variant-numeric: tabular-nums;
	position: absolute;
	text-align: right;
	display: inline-block;
	vertical-align: middle;
	box-sizing: border-box;
	cursor: default;
	height: 100%;
}

.monaco-editor .relative-current-line-number {
	text-align: left;
	display: inline-block;
	width: 100%;
}

.monaco-editor .margin-view-overlays .line-numbers.lh-odd {
	margin-top: 1px;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/lineNumbers/lineNumbers.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kCAAkC;CAClC,kBAAkB;CAClB,iBAAiB;CACjB,qBAAqB;CACrB,sBAAsB;CACtB,sBAAsB;CACtB,eAAe;CACf,YAAY;AACb;;AAEA;CACC,gBAAgB;CAChB,qBAAqB;CACrB,WAAW;AACZ;;AAEA;CACC,eAAe;AAChB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .margin-view-overlays .line-numbers {\n\tfont-variant-numeric: tabular-nums;\n\tposition: absolute;\n\ttext-align: right;\n\tdisplay: inline-block;\n\tvertical-align: middle;\n\tbox-sizing: border-box;\n\tcursor: default;\n\theight: 100%;\n}\n\n.monaco-editor .relative-current-line-number {\n\ttext-align: left;\n\tdisplay: inline-block;\n\twidth: 100%;\n}\n\n.monaco-editor .margin-view-overlays .line-numbers.lh-odd {\n\tmargin-top: 1px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 11244:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.IconButton-module__Root--hfD5F{padding:4px;border:0;border-radius:2px;display:inline-flex;align-items:center;cursor:pointer;transition:background-color var(--speed-turbo) var(--easing-base)}.IconButton-module__Root--hfD5F path{transition:fill var(--speed-turbo) var(--easing-base)}.IconButton-module__Root--hfD5F:disabled{background-color:var(--theme-color-bg-2)}.IconButton-module__Root--hfD5F:disabled path{fill:var(--theme-color-fg-default-shy)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-default--lIlIL{background-color:var(--theme-color-bg-3)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-default--lIlIL path{fill:var(--theme-color-fg-default)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-default--lIlIL.IconButton-module__is-state-active--AjUki,.IconButton-module__Root--hfD5F.IconButton-module__is-variant-default--lIlIL:not(:disabled):hover{background-color:var(--theme-color-bg-1)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-default--lIlIL.IconButton-module__is-state-active--AjUki path,.IconButton-module__Root--hfD5F.IconButton-module__is-variant-default--lIlIL:not(:disabled):hover path{fill:var(--theme-color-fg-highlight)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-semi-transparent--nc6rH{background-color:var(--theme-color-fg-transparent)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-semi-transparent--nc6rH path{fill:var(--theme-color-fg-highlight)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-semi-transparent--nc6rH.IconButton-module__is-state-active--AjUki,.IconButton-module__Root--hfD5F.IconButton-module__is-variant-semi-transparent--nc6rH:not(:disabled):hover{background-color:var(--theme-color-bg-1-transparent)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-semi-transparent--nc6rH.IconButton-module__is-state-active--AjUki path,.IconButton-module__Root--hfD5F.IconButton-module__is-variant-semi-transparent--nc6rH:not(:disabled):hover path{fill:var(--theme-color-fg-highlight)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-transparent--Pb06x{background-color:rgba(0,0,0,0) !important}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-transparent--Pb06x path{fill:var(--theme-color-fg-default)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-transparent--Pb06x:disabled path{fill:var(--theme-color-bg-4)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-transparent--Pb06x.IconButton-module__is-state-active--AjUki,.IconButton-module__Root--hfD5F.IconButton-module__is-variant-transparent--Pb06x:not(:disabled):hover{background-color:var(--theme-color-bg-1-transparent)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-transparent--Pb06x.IconButton-module__is-state-active--AjUki path,.IconButton-module__Root--hfD5F.IconButton-module__is-variant-transparent--Pb06x:not(:disabled):hover path{fill:var(--theme-color-fg-highlight)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-opaque-on-hover--uxvFi{background-color:rgba(0,0,0,0)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-opaque-on-hover--uxvFi path{fill:var(--theme-color-fg-default)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-opaque-on-hover--uxvFi:not(:disabled):hover{background-color:var(--theme-color-bg-3)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-opaque-on-hover--uxvFi:not(:disabled):hover path{fill:var(--theme-color-fg-highlight)}.IconButton-module__Root--hfD5F.IconButton-module__is-variant-opaque-on-hover--uxvFi:disabled path{fill:var(--theme-color-bg-4)}.IconButton-module__Root--hfD5F.IconButton-module__is-button-size-bigger--Yp4aW{padding:6px}.IconButton-module__Icon--I3M7K{transition:transform var(--speed-quick) var(--easing-base)}.IconButton-module__Root--hfD5F.IconButton-module__is-state-rotated--YsNWi .IconButton-module__Icon--I3M7K{transform:rotate(180deg)}.IconButton-module__Root--hfD5F.IconButton-module__is-icon-variant-notice--CYW0N:hover .IconButton-module__Icon--I3M7K path{fill:var(--theme-color-primary-highlight) !important}.IconButton-module__Label--OaTdr{margin-left:4px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/IconButton/IconButton.module.scss"],"names":[],"mappings":"AAAA,gCACE,WAAA,CACA,QAAA,CACA,iBAAA,CACA,mBAAA,CACA,kBAAA,CACA,cAAA,CACA,iEAAA,CAEA,qCACE,qDAAA,CAGF,yCACE,wCAAA,CAEA,8CACE,sCAAA,CAIJ,6EACE,wCAAA,CAEA,kFACE,kCAAA,CAGF,yNAEE,wCAAA,CAEA,mOACE,oCAAA,CAKN,sFACE,kDAAA,CAEA,2FACE,oCAAA,CAGF,2OAEE,oDAAA,CAEA,qPACE,oCAAA,CAKN,iFACE,yCAAA,CAEA,sFACE,kCAAA,CAIA,+FACE,4BAAA,CAIJ,iOAEE,oDAAA,CAEA,2OACE,oCAAA,CAKN,qFACE,8BAAA,CAEA,0FACE,kCAAA,CAGF,0GACE,wCAAA,CAEA,+GACE,oCAAA,CAKF,mGACE,4BAAA,CAKN,gFACE,WAAA,CAIJ,gCACE,0DAAA,CAEA,2GACE,wBAAA,CAIA,4HACE,oDAAA,CAKN,iCACE,eAAA","sourcesContent":[".Root {\n  padding: 4px;\n  border: 0;\n  border-radius: 2px;\n  display: inline-flex;\n  align-items: center;\n  cursor: pointer;\n  transition: background-color var(--speed-turbo) var(--easing-base);\n\n  path {\n    transition: fill var(--speed-turbo) var(--easing-base);\n  }\n\n  &:disabled {\n    background-color: var(--theme-color-bg-2);\n\n    path {\n      fill: var(--theme-color-fg-default-shy);\n    }\n  }\n\n  &.is-variant-default {\n    background-color: var(--theme-color-bg-3);\n\n    path {\n      fill: var(--theme-color-fg-default);\n    }\n\n    &.is-state-active,\n    &:not(:disabled):hover {\n      background-color: var(--theme-color-bg-1);\n\n      path {\n        fill: var(--theme-color-fg-highlight);\n      }\n    }\n  }\n\n  &.is-variant-semi-transparent {\n    background-color: var(--theme-color-fg-transparent);\n\n    path {\n      fill: var(--theme-color-fg-highlight);\n    }\n\n    &.is-state-active,\n    &:not(:disabled):hover {\n      background-color: var(--theme-color-bg-1-transparent);\n\n      path {\n        fill: var(--theme-color-fg-highlight);\n      }\n    }\n  }\n\n  &.is-variant-transparent {\n    background-color: transparent !important;\n\n    path {\n      fill: var(--theme-color-fg-default);\n    }\n\n    &:disabled {\n      path {\n        fill: var(--theme-color-bg-4);\n      }\n    }\n\n    &.is-state-active,\n    &:not(:disabled):hover {\n      background-color: var(--theme-color-bg-1-transparent);\n\n      path {\n        fill: var(--theme-color-fg-highlight);\n      }\n    }\n  }\n\n  &.is-variant-opaque-on-hover {\n    background-color: transparent;\n\n    path {\n      fill: var(--theme-color-fg-default);\n    }\n\n    &:not(:disabled):hover {\n      background-color: var(--theme-color-bg-3);\n\n      path {\n        fill: var(--theme-color-fg-highlight);\n      }\n    }\n\n    &:disabled {\n      path {\n        fill: var(--theme-color-bg-4);\n      }\n    }\n  }\n\n  &.is-button-size-bigger {\n    padding: 6px;\n  }\n}\n\n.Icon {\n  transition: transform var(--speed-quick) var(--easing-base);\n\n  .Root.is-state-rotated & {\n    transform: rotate(180deg);\n  }\n\n  .Root.is-icon-variant-notice:hover & {\n    path {\n      fill: var(--theme-color-primary-highlight) !important;\n    }\n  }\n}\n\n.Label {\n  margin-left: 4px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `IconButton-module__Root--hfD5F`,
	"is-variant-default": `IconButton-module__is-variant-default--lIlIL`,
	"is-state-active": `IconButton-module__is-state-active--AjUki`,
	"is-variant-semi-transparent": `IconButton-module__is-variant-semi-transparent--nc6rH`,
	"is-variant-transparent": `IconButton-module__is-variant-transparent--Pb06x`,
	"is-variant-opaque-on-hover": `IconButton-module__is-variant-opaque-on-hover--uxvFi`,
	"is-button-size-bigger": `IconButton-module__is-button-size-bigger--Yp4aW`,
	"Icon": `IconButton-module__Icon--I3M7K`,
	"is-state-rotated": `IconButton-module__is-state-rotated--YsNWi`,
	"is-icon-variant-notice": `IconButton-module__is-icon-variant-notice--CYW0N`,
	"Label": `IconButton-module__Label--OaTdr`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 11530:
/***/ ((module) => {

"use strict";
module.exports = require("diff3");

/***/ }),

/***/ 11603:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  M: () => (/* reexport */ CollapsableSection)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/inputs/IconButton/index.ts + 2 modules
var IconButton = __webpack_require__(28208);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Collapsible/index.ts + 2 modules
var Collapsible = __webpack_require__(20014);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/sidebar/Section/index.ts + 2 modules
var Section = __webpack_require__(60028);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Label/index.ts + 2 modules
var Label = __webpack_require__(91629);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/index.ts
var Text = __webpack_require__(93834);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/sidebar/CollapsableSection/CollapsableSection.module.scss
var CollapsableSection_module = __webpack_require__(27781);
;// ../noodl-core-ui/src/components/sidebar/CollapsableSection/CollapsableSection.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(CollapsableSection_module/* default */.A, options);




       /* harmony default export */ const CollapsableSection_CollapsableSection_module = (CollapsableSection_module/* default */.A && CollapsableSection_module/* default */.A.locals ? CollapsableSection_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/sidebar/CollapsableSection/CollapsableSection.tsx









function CollapsableSection({ variant = Section/* SectionVariant */.$.Default, title, isClosed, hasGutter, hasBottomSpacing, hasVisibleOverflow, hasTopDivider, actions, children, UNSAFE_className, UNSAFE_style }) {
    const [isCollapsed, setIsCollapsed] = (0,external_react_.useState)(!!isClosed);
    return (external_react_default().createElement("section", { className: external_classnames_default()([
            CollapsableSection_CollapsableSection_module['Root'],
            CollapsableSection_CollapsableSection_module[`is-variant-${variant}`],
            hasVisibleOverflow && CollapsableSection_CollapsableSection_module['has-visible-overflow'],
            hasTopDivider && CollapsableSection_CollapsableSection_module['has-top-divider'],
            UNSAFE_className
        ]), style: UNSAFE_style },
        (Boolean(title) || Boolean(actions)) && (external_react_default().createElement("div", { onClick: () => setIsCollapsed((prev) => !prev), className: external_classnames_default()([CollapsableSection_CollapsableSection_module['Header'], CollapsableSection_CollapsableSection_module[`is-variant-${variant}`], CollapsableSection_CollapsableSection_module['is-collapsable']]) },
            external_react_default().createElement(Label/* Label */.JU, { variant: Text/* TextType */.M2.Proud, size: Label/* LabelSize */.IV.Medium }, title),
            Boolean(actions) && external_react_default().createElement("div", null, actions),
            external_react_default().createElement(IconButton/* IconButton */.K0, { icon: Icon/* IconName */.$M.CaretUp, variant: IconButton/* IconButtonVariant */.nl.Transparent, state: isCollapsed ? IconButton/* IconButtonState */.Df.Rotated : null }))),
        external_react_default().createElement(Collapsible/* Collapsible */.N, { isCollapsed: isCollapsed },
            external_react_default().createElement("div", { className: external_classnames_default()([
                    CollapsableSection_CollapsableSection_module['Body'],
                    CollapsableSection_CollapsableSection_module[`is-variant-${variant}`],
                    hasGutter && CollapsableSection_CollapsableSection_module['has-gutter'],
                    hasBottomSpacing && CollapsableSection_CollapsableSection_module['has-bottom-spacing'],
                    hasVisibleOverflow && CollapsableSection_CollapsableSection_module['has-visible-overflow']
                ]) }, Boolean(children) && children))));
}

;// ../noodl-core-ui/src/components/sidebar/CollapsableSection/index.ts



/***/ }),

/***/ 11684:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const _ = __webpack_require__(80002);
const { ProjectModel } = __webpack_require__(6203);
const { projectFromDirectory } = __webpack_require__(46998);
const FileSystem = __webpack_require__(38656);

var ProjectImporter = function () {};

// This function lists all components, resources, modules, styles and variants
// And figure out dependencies for component and variants
ProjectImporter.prototype.listComponentsAndDependencies = function (direntry, callback) {
  projectFromDirectory(direntry, function (importProject) {
    if (!importProject) {
      callback();
      return;
    }

    // Collect all component dependencies for this component
    function collectDependencies(c) {
      var deps = [];
      c.forEachNode(function (n) {
        if (n.type.fullName.indexOf('/') === 0) {
          deps.push(n.type.fullName);
        }
      });
      return deps;
    }

    // Collect all file dependencies for a component
    var filePathMap = {};
    function _collectFileDependencies(parameters, deps) {
      for (var i in parameters) {
        var value = parameters[i];
        if (typeof value === 'string' && filePathMap[value]) {
          // We have a possible match, add as file dependency
          deps[value] = true;
        }
      }
    }

    function collectFileDependencies(c) {
      var deps = {};
      c.forEachNode(function (n) {
        // Check if any of the parameters contain file references
        _collectFileDependencies(n.parameters, deps);
        if (n.stateParameters)
          for (let state in n.stateParameters) {
            _collectFileDependencies(n.stateParameters[state], deps);
          }
      });
      return Object.keys(deps);
    }

    // Collect all variant dependencies for a component
    function collectVariantDependencies(c) {
      var deps = {};
      c.forEachNode(function (n) {
        if (n.variantName) {
          deps[n.type.localName + '/' + n.variantName] = { typename: n.type.localName, name: n.variantName };
        }
      });
      return Object.keys(deps).map((dep) => deps[dep]);
    }

    // Collect all style dependencies
    function _getColorStyle(name) {
      if (
        importProject.metadata !== undefined &&
        importProject.metadata.styles !== undefined &&
        importProject.metadata.styles.colors !== undefined
      )
        return importProject.metadata.styles.colors[name];
    }

    function _getTextStyle(name) {
      if (
        importProject.metadata !== undefined &&
        importProject.metadata.styles !== undefined &&
        importProject.metadata.styles.text !== undefined
      )
        return importProject.metadata.styles.text[name];
    }

    function _collectStyleDependencies(parameters, deps) {
      for (var key in parameters) {
        const value = parameters[key];
        if (typeof value === 'string') {
          if (_getColorStyle(value) !== undefined) {
            // This is a color style reference
            deps.colors[value] = true;
          } else if (_getTextStyle(value) !== undefined) {
            deps.text[value] = true;
          }
        }
      }
    }

    function collectStyleDependencies(c) {
      var deps = { text: {}, colors: {} };
      c.forEachNode(function (n) {
        _collectStyleDependencies(n.parameters, deps);
        if (n.stateParameters)
          for (let state in n.stateParameters) {
            _collectStyleDependencies(n.stateParameters[state], deps);
          }
      });
      return { colors: Object.keys(deps.colors), text: Object.keys(deps.text) };
    }

    // Collect file dependencies for a variant
    function collectVariantFileDependencies(v) {
      var deps = {};

      _collectFileDependencies(v.parameters, deps);
      if (v.stateParameters)
        for (let state in v.stateParameters) {
          _collectFileDependencies(v.stateParameters[state], deps);
        }

      return Object.keys(deps);
    }

    // Collect style dependencies for a variant
    function collectVariantStyleDependencies(v) {
      var deps = { text: {}, colors: {} };

      _collectStyleDependencies(v.parameters, deps);
      if (v.stateParameters)
        for (let state in v.stateParameters) {
          _collectStyleDependencies(v.stateParameters[state], deps);
        }

      return { colors: Object.keys(deps.colors), text: Object.keys(deps.text) };
    }

    // Collect style file dependencies
    function collectStyleFileDependencies(s) {
      var deps = {};

      _collectFileDependencies(s, deps);

      return Object.keys(deps);
    }

    // List all resources in project folder for import
    const ignoreFullPath = [
      `${importProject._retainedProjectDirectory}/.git`,
      `${importProject._retainedProjectDirectory}/__MACOSX`
    ];

    importProject.listFilesInProjectDirectory(
      function (entries) {
        // Create a map of all filenames, and create the resources
        // list
        var resources = [];
        var ignore = ['project.json', '.ds_store', '.gitignore', '.gitattributes', 'readme.md'];
        entries.forEach((e) => {
          if (ignore.indexOf(e.name.toLowerCase()) !== -1) return;
          // Skip all ignore files
          else if (e.fullPath.indexOf('.git') === 0) return;
          // Skip .git
          else if (e.fullPath.startsWith(importProject._retainedProjectDirectory + '/noodl_modules')) return; // Ignore modules

          var localPath = e.fullPath.substring(direntry.length + 1);
          filePathMap[localPath] = true;

          resources.push({ name: localPath });
        });

        // Collect modules
        let modules = [];
        try {
          const _modules = FileSystem.instance.readDirectorySync(direntry + '/noodl_modules');
          modules = _modules
            .filter((m) => FileSystem.instance.fileExistsSync(m.fullPath + '/manifest.json'))
            .map((m) => ({ name: m.name }));
        } catch (e) {}

        // Return array with components and dependencies
        var componentsToImport = [];
        importProject.forEachComponent(function (importComponent) {
          componentsToImport.push({
            name: importComponent.fullName,
            dependencies: collectDependencies(importComponent),
            fileDependencies: collectFileDependencies(importComponent),
            variantDependencies: collectVariantDependencies(importComponent),
            styleDependencies: collectStyleDependencies(importComponent)
          });
        });

        // List all styles
        var styles = { colors: [], text: [] };
        if (importProject.metadata !== undefined && importProject.metadata.styles !== undefined) {
          if (importProject.metadata.styles.colors !== undefined) {
            styles.colors = Object.keys(importProject.metadata.styles.colors).map((s) => ({
              name: s
            }));
          }

          if (importProject.metadata.styles.text !== undefined) {
            styles.text = Object.keys(importProject.metadata.styles.text).map((s) => ({
              name: s,
              fileDependencies: collectStyleFileDependencies(importProject.metadata.styles.text[s])
            }));
          }
        }

        // List all variants
        var variants = [];
        if (importProject.variants !== undefined) {
          importProject.variants.forEach((v) => {
            if (v.name !== undefined) {
              variants.push({
                name: v.name,
                typename: v.typename,
                fileDependencies: collectVariantFileDependencies(v),
                styleDependencies: collectVariantStyleDependencies(v)
              });
            }
          });
        }

        callback({ components: componentsToImport, resources, modules, styles, variants });
      },
      undefined,
      ignoreFullPath
    );
  });
};

ProjectImporter.prototype.hasCollisions = function (c) {
  return (
    (c.resources !== undefined && c.resources.length > 0) ||
    (c.components !== undefined && c.components.length > 0) ||
    (c.variants !== undefined && c.variants.length > 0) ||
    (c.modules !== undefined && c.modules.length > 0) ||
    (c.styles !== undefined && c.styles.colors !== undefined && c.styles.colors.length > 0) ||
    (c.styles !== undefined && c.styles.text !== undefined && c.styles.text.length > 0)
  );
};

// This function checks for collisions with the current project model instance
ProjectImporter.prototype.checkForCollisions = function (imports, callback) {
  if (!ProjectModel.instance) {
    callback({ result: 'failure', message: 'No project loaded, cannot import.' });
    return;
  }

  // Check for component collisions
  var collisions = { resources: [], components: [], styles: { text: [], colors: [] }, variants: [], modules: [] };
  imports.components &&
    _.each(imports.components, function (c) {
      var component = ProjectModel.instance.getComponentWithName(c.name);
      if (component) collisions.components.push(c);
    });

  // Check style collisions
  const styles = ProjectModel.instance.getMetaData('styles');
  if (styles !== undefined) {
    // Check color styles
    if (styles.colors !== undefined && imports.styles.colors !== undefined) {
      imports.styles.colors.forEach((c) => {
        if (styles.colors[c.name] !== undefined) collisions.styles.colors.push(c);
      });
    }

    // Check text styles
    if (styles.text !== undefined && imports.styles.text !== undefined) {
      imports.styles.text.forEach((t) => {
        if (styles.text[t.name] !== undefined) collisions.styles.text.push(t);
      });
    }
  }

  // Check variant collisions
  if (imports.variants !== undefined) {
    imports.variants.forEach((v) => {
      if (ProjectModel.instance.findVariant(v.name, { localName: v.typename }) !== undefined) {
        collisions.variants.push(v);
      }
    });
  }

  // No resources of modules to import, return now
  if (
    (imports.resources === undefined || imports.resources.length === 0) &&
    (imports.modules === undefined || imports.modules.length === 0)
  ) {
    callback(this.hasCollisions(collisions) ? collisions : undefined);
    return;
  }

  ProjectModel.instance.listFilesInProjectDirectory((projectFiles) => {
    // Create map of all project files
    var filePathMap = {};
    projectFiles.forEach((e) => {
      var localPath = e.fullPath.substring(ProjectModel.instance._retainedProjectDirectory.length + 1);
      filePathMap[localPath] = true;
    });

    // Check for collisions and return result
    imports.resources.forEach((f) => {
      if (filePathMap[f.name]) collisions.resources.push(f);
    });

    // Check for module collisions
    let modules = [];
    try {
      const _modules = FileSystem.instance.readDirectorySync(
        ProjectModel.instance._retainedProjectDirectory + '/noodl_modules'
      );
      modules = _modules
        .filter((m) => FileSystem.instance.fileExistsSync(m.fullPath + '/manifest.json'))
        .map((m) => ({ name: m.name }));
    } catch (e) {}

    if (modules.length > 0) {
      imports.modules.forEach((m) => {
        if (modules.find((_m) => _m.name === m.name) !== undefined) {
          collisions.modules.push(m);
        }
      });
    }

    callback(this.hasCollisions(collisions) ? collisions : undefined);
  });
};

ProjectImporter.prototype.importResources = function (direntry, imports, callback, options) {
  const project = options && options.importIntoProject ? options.importIntoProject : ProjectModel.instance;

  // Callback when a file is processed
  var resourcesLeft = 0;
  var failedFiles = 0;
  function fileCompleted(success) {
    if (!success) failedFiles++;

    resourcesLeft--;
    if (resourcesLeft === 0) {
      if (failedFiles) callback({ result: 'failure', message: 'Not all files could be copied' });
      else callback({ result: 'success' });
    }
  }

  if (imports.resources.length === 0) {
    callback({ result: 'success' });
    return;
  }

  // Loop over all resources and copy them, create folders
  // if necessary
  _.each(imports.resources, function (r) {
    resourcesLeft++;
    var folders = r.name.split('/');
    folders.pop(); // Remove last entry (filename)
    FileSystem.instance.makeDirectory(project._retainedProjectDirectory + '/' + folders.join('/'), function (res) {
      if (res.result === 'failure') fileCompleted(false);
      else {
        project.copyFileToProjectDirectory({ fullPath: direntry + '/' + r.name, name: r.name }, function (res) {
          fileCompleted(res.result === 'success');
        });
      }
    });
  });
};

ProjectImporter.prototype.import = function (direntry, imports, callback, options) {
  var _this = this;

  const project = options && options.importIntoProject ? options.importIntoProject : ProjectModel.instance;

  if (!project) {
    callback({ result: 'failure', message: 'No project loaded, cannot import.' });
    return;
  }

  projectFromDirectory(direntry, function (importProject) {
    if (!importProject) {
      callback({ result: 'failure', message: 'Could not open project to import' });
      return;
    }

    // Add components to import to project
    imports.components &&
      _.each(imports.components, function (c) {
        var importComponent = importProject.getComponentWithName(c.name);
        importProject.removeComponent(importComponent);

        delete importComponent.id; // re-key below will create a new id
        importComponent.rekeyAllIds();

        var component = project.getComponentWithName(c.name);
        if(component) {
          project.removeComponent(component)
          // Component exist in project, it should be overwritten
          importComponent.id = component.id;
        }

        project.addComponent(importComponent);
      });

    // Merge styles
    if (imports.styles !== undefined) {
      const importStyles = importProject.getMetaData('styles');
      const styles = { text: {}, colors: {} };

      if (imports.styles.colors !== undefined) {
        imports.styles.colors.forEach((c) => {
          styles.colors[c.name] = importStyles.colors[c.name];
        });
      }

      if (imports.styles.text !== undefined) {
        imports.styles.text.forEach((c) => {
          styles.text[c.name] = importStyles.text[c.name];
        });
      }
      project.mergeMetadata({ styles });
    }

    // Add variants
    if (imports.variants !== undefined) {
      imports.variants.forEach((v) => {
        const importVariant = importProject.findVariant(v.name, { localName: v.typename });
        importProject.deleteVariant(importVariant);

        const variant = project.findVariant(v.name, { localName: v.typename });
        if (variant !== undefined) project.deleteVariant(variant);
        project.addVariant(importVariant);
      });
    }

    // If no resources or packages to import, we are done
    if ((!imports.resources || imports.resources.length === 0) && (!imports.modules || imports.modules.length === 0)) {
      callback({ result: 'success' });
      return;
    }

    // Import resources
    _this.importResources(
      direntry,
      imports,
      function (r) {
        if (r.result !== 'success') {
          callback(r);
          return;
        }

        // Import modules
        if (imports.modules !== undefined) {
          imports.modules.forEach((m) => {
            FileSystem.instance.copyRecursiveSync(
              importProject._retainedProjectDirectory + '/noodl_modules/' + m.name,
              project._retainedProjectDirectory + '/noodl_modules/' + m.name
            );
          });
        }

        callback({ result: 'success' });
      },
      options
    );
  });
};

ProjectImporter.prototype.filterImports = function (imports, filter) {
  if (filter.remove) {
    if (filter.remove.components !== undefined && filter.remove.components.length > 0)
      imports.components = imports.components.filter((c) => !filter.remove.components.find((_c) => _c.name == c.name));

    if (filter.remove.resources !== undefined && filter.remove.resources.length > 0)
      imports.resources = imports.resources.filter((c) => !filter.remove.resources.find((_c) => _c.name == c.name));

    if (filter.remove.modules !== undefined && filter.remove.modules.length > 0)
      imports.modules = imports.modules.filter((c) => !filter.remove.modules.find((_c) => _c.name == c.name));

    if (filter.remove.variants !== undefined && filter.remove.variants.length > 0)
      imports.variants = imports.variants.filter(
        (c) => !filter.remove.variants.find((_c) => _c.name == c.name && _c.typename === c.typename)
      );

    if (
      filter.remove.styles !== undefined &&
      filter.remove.styles.colors !== undefined &&
      filter.remove.styles.colors.length > 0
    )
      imports.styles.colors = imports.styles.colors.filter(
        (c) => !filter.remove.styles.colors.find((_c) => _c.name == c.name)
      );

    if (
      filter.remove.styles !== undefined &&
      filter.remove.styles.text !== undefined &&
      filter.remove.styles.text.length > 0
    )
      imports.styles.text = imports.styles.text.filter(
        (c) => !filter.remove.styles.text.find((_c) => _c.name == c.name)
      );
  }
};

ProjectImporter.instance = new ProjectImporter();

module.exports = ProjectImporter;


/***/ }),

/***/ 11793:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
const React = __webpack_require__(54953);
const {
  useState,
  useEffect,
  useRef
} = __webpack_require__(54953);
const ColorPicker = (__webpack_require__(45330)/* ["default"] */ .A);
const FontPicker = (__webpack_require__(63544)/* ["default"] */ .A);
const PopupLayer = __webpack_require__(45653);
__webpack_require__(75851);
const GenericInputProperty = React.forwardRef((props, ref) => {
  const [inputValue, setInputValue] = useState(props.value || '');
  useEffect(() => {
    setInputValue(props.value);
  }, [props.value]);
  function onChange(newValue) {
    const changed = props.value !== newValue;
    changed && props.onChange && props.onChange(newValue);
  }
  return /*#__PURE__*/React.createElement("div", {
    className: "propertyeditor-item",
    style: props.style,
    onClick: props.onClick,
    ref: ref
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      width: '120px',
      flexShrink: 0,
      textAlign: 'right'
    }
  }, props.label), /*#__PURE__*/React.createElement("input", {
    className: "propertyeditor-item-input",
    type: props.type || 'string',
    value: inputValue,
    style: {
      flexGrow: 1,
      flexShrink: 1
    },
    onChange: e => {
      setInputValue(e.target.value);
      const changed = props.value !== e.target.value;
      changed && props.onEditChange && props.onEditChange(e.target.value);
    },
    onFocus: props.onFocus,
    onBlur: e => {
      onChange(e.target.value);
      props.onBlur && props.onBlur(e);
    },
    onKeyUp: e => {
      if (e.key === 'Enter') {
        e.target.blur();
      }
    }
  }));
});
function UnitDropdown(props) {
  const [open, setOpen] = useState(false);
  function onChange(newValue) {
    const changed = props.value !== newValue;
    changed && props.onChange && props.onChange(newValue);
  }
  return /*#__PURE__*/React.createElement("div", {
    className: "sidebar-panel-dark-input propertyeditor-unit-dropdown",
    tabIndex: "1" //hack to make onBlur trigger
    ,
    onBlur: () => setOpen(false),
    onClick: () => setOpen(!open)
  }, /*#__PURE__*/React.createElement("div", null, props.value), open ? /*#__PURE__*/React.createElement("div", {
    className: "property-input-dropdown propertyeditor-unit-dropdown-list"
  }, props.units.map(unit => /*#__PURE__*/React.createElement("div", {
    className: "property-input-enum",
    key: unit,
    onClick: () => onChange(unit)
  }, unit))) : null);
}

// props.value: an object with type {value, unit}
function GenericPropertyWithUnits(props) {
  const value = typeof props.value === 'object' ? props.value.value : undefined;
  const unit = typeof props.value === 'object' ? props.value.unit : props.units[0];
  return /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'flex'
    }
  }, /*#__PURE__*/React.createElement(GenericInputProperty, {
    key: value,
    value: value,
    type: "string",
    onChange: newValue => props.onChange && props.onChange({
      value: newValue,
      unit
    }),
    label: props.label
  }), /*#__PURE__*/React.createElement(UnitDropdown, {
    value: unit,
    units: props.units,
    onChange: newUnit => props.onChange({
      value,
      unit: newUnit
    })
  }));
}
function ColorProperty(props) {
  const popupAnchor = useRef(null);
  const [showColorPicker, setShowColorPicker] = useState(false);
  const [color, setColor] = useState(props.value);
  useEffect(() => {
    if (!showColorPicker) return;
    const colorPicker = new ColorPicker();
    colorPicker.render();
    colorPicker.setColor(color);
    colorPicker.setColorChangedListener((color, commitChange) => {
      setColor(color);
      if (commitChange) {
        props.onChange && props.onChange(color);
      }
    });
    const popout = PopupLayer.instance.showPopout({
      content: colorPicker,
      attachTo: $(popupAnchor.current),
      position: 'right',
      onClose: () => {
        colorPicker.dispose();
      }
    });
    return () => {
      PopupLayer.instance.hidePopout(popout);
    };
  }, [showColorPicker]);
  function onChange(newValue) {
    setColor(newValue);
    props.onChange && props.onChange(newValue);
  }
  return /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'flex'
    },
    tabIndex: "1",
    onBlur: () => setShowColorPicker(false)
  }, /*#__PURE__*/React.createElement(GenericInputProperty, {
    value: color,
    type: "string",
    onChange: onChange,
    label: props.label
  }), /*#__PURE__*/React.createElement("div", {
    className: "color-thumbnail",
    style: {
      marginTop: '1px',
      marginLeft: '2px'
    },
    onClick: () => setShowColorPicker(s => !s)
  }, /*#__PURE__*/React.createElement("div", {
    ref: popupAnchor,
    className: "color-thumbnail-content",
    style: {
      backgroundColor: color
    }
  })));
}
function FontProperty(props) {
  const ref = useRef(null);
  const [showFontPicker, setShowFontPicker] = useState(false);
  const fontPickerRef = useRef(null);
  const [value, setValue] = useState(props.value);
  function onChange(newValue) {
    setValue(newValue);
    setShowFontPicker(false);
    const changed = newValue !== props.value;
    changed && props.onChange && props.onChange(newValue);
  }
  useEffect(() => {
    if (!showFontPicker) return;
    const fontPicker = new FontPicker({
      onItemSelected: onChange
    });
    fontPicker.render();
    fontPickerRef.current = fontPicker;
    const popout = PopupLayer.instance.showPopout({
      content: fontPicker,
      attachTo: $(ref.current),
      position: 'right'
    });
    return () => {
      PopupLayer.instance.hidePopout(popout);
      fontPickerRef.current = null;
    };
  }, [showFontPicker, onChange]);
  function onClick(e) {
    setShowFontPicker(true);
  }
  return /*#__PURE__*/React.createElement(GenericInputProperty, {
    ref: ref,
    key: value,
    value: value,
    type: "string",
    onClick: onClick,
    onEditChange: value => {
      setValue(value);
      fontPickerRef.current && fontPickerRef.current.setFilter(value);
    },
    onChange: onChange,
    label: props.label
  });
}
function EnumProperty(props) {
  const [value, setValue] = useState(props.value);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  function onChange(newValue) {
    setValue(newValue);
    const changed = props.value !== newValue;
    changed && props.onChange && props.onChange(newValue);
  }
  const enums = props.enums || [];
  let dropdown = null;
  if (dropdownOpen) {
    dropdown = /*#__PURE__*/React.createElement("div", {
      className: "property-input-dropdown propertyeditor-enums-dropdown"
    }, enums.map(({
      label,
      value
    }) => /*#__PURE__*/React.createElement("div", {
      key: value,
      className: "property-input-enum",
      onClick: () => {
        onChange(value);
      }
    }, label)));
  }
  const selectedItem = enums.find(e => e.value === value);
  const labelForCurrentValue = selectedItem ? selectedItem.label : value;
  return /*#__PURE__*/React.createElement("div", {
    className: "propertyeditor-item",
    style: {
      display: 'flex',
      ...props.style
    },
    tabIndex: "1" //hack to get the onBlur event
    ,
    onBlur: () => setDropdownOpen(false),
    onClick: () => setDropdownOpen(open => !open)
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      width: '120px',
      flexShrink: 0,
      textAlign: 'right'
    }
  }, props.label), /*#__PURE__*/React.createElement("div", {
    className: "propertyeditor-item-input",
    style: {
      display: 'flex',
      alignItems: 'center',
      flexGrow: 1,
      position: 'relative'
    }
  }, labelForCurrentValue, /*#__PURE__*/React.createElement("i", {
    className: "property-input-dropdown-arrow fa fa-caret-down",
    style: {
      position: 'absolute',
      right: '10px'
    }
  }), dropdown));
}
function propertyFromPort(port, value, onChange) {
  const type = port.type;
  const typeName = port.type.name ? port.type.name : port.type;
  const props = {
    value,
    label: port.displayName,
    onChange
  };
  switch (typeName) {
    case 'font':
      return /*#__PURE__*/React.createElement(FontProperty, _extends({
        key: port.name
      }, props));
    case 'color':
      return /*#__PURE__*/React.createElement(ColorProperty, _extends({
        key: port.name
      }, props));
    case 'enum':
      return /*#__PURE__*/React.createElement(EnumProperty, _extends({
        key: port.name
      }, props, {
        enums: type.enums
      }));
  }
  if (type.units) {
    return /*#__PURE__*/React.createElement(GenericPropertyWithUnits, _extends({
      key: port.name
    }, props, {
      units: type.units
    }));
  }
  return /*#__PURE__*/React.createElement(GenericInputProperty, _extends({
    key: port.name
  }, props));
}
module.exports = {
  ColorProperty,
  FontProperty,
  GenericInputProperty,
  GenericPropertyWithUnits,
  EnumProperty,
  propertyFromPort
};

/***/ }),

/***/ 12055:
/***/ ((module) => {

"use strict";
module.exports = require("mkdirp");

/***/ }),

/***/ 12093:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  $$: () => (/* reexport */ ActivityIndicator),
  Iz: () => (/* reexport */ ActivityIndicatorColor)
});

// UNUSED EXPORTS: ActivityIndicatorSize

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/common/ActivityIndicator/ActivityIndicator.module.scss
var ActivityIndicator_module = __webpack_require__(63520);
;// ../noodl-core-ui/src/components/common/ActivityIndicator/ActivityIndicator.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(ActivityIndicator_module/* default */.A, options);




       /* harmony default export */ const ActivityIndicator_ActivityIndicator_module = (ActivityIndicator_module/* default */.A && ActivityIndicator_module/* default */.A.locals ? ActivityIndicator_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/common/ActivityIndicator/ActivityIndicator.tsx



var ActivityIndicatorColor;
(function (ActivityIndicatorColor) {
    ActivityIndicatorColor["Light"] = "light";
    ActivityIndicatorColor["Dark"] = "dark";
})(ActivityIndicatorColor || (ActivityIndicatorColor = {}));
var ActivityIndicatorSize;
(function (ActivityIndicatorSize) {
    ActivityIndicatorSize["Default"] = "default";
    ActivityIndicatorSize["Small"] = "small";
})(ActivityIndicatorSize || (ActivityIndicatorSize = {}));
function ActivityIndicator({ text, color = ActivityIndicatorColor.Light, size = ActivityIndicatorSize.Default, isOverlay }) {
    return (external_react_default().createElement("div", { className: external_classnames_default()([ActivityIndicator_ActivityIndicator_module['Root'], isOverlay && ActivityIndicator_ActivityIndicator_module['is-overlay']]) },
        external_react_default().createElement("div", { className: external_classnames_default()(ActivityIndicator_ActivityIndicator_module['Inner'], ActivityIndicator_ActivityIndicator_module[`is-size-${size}`]) },
            Boolean(text) && external_react_default().createElement("p", null, text),
            external_react_default().createElement("div", { className: external_classnames_default()([ActivityIndicator_ActivityIndicator_module['FirstDot'], ActivityIndicator_ActivityIndicator_module[`is-color-${color}`]]) }),
            external_react_default().createElement("div", { className: external_classnames_default()([ActivityIndicator_ActivityIndicator_module['SecondDot'], ActivityIndicator_ActivityIndicator_module[`is-color-${color}`]]) }),
            external_react_default().createElement("div", { className: external_classnames_default()([ActivityIndicator_ActivityIndicator_module['ThirdDot'], ActivityIndicator_ActivityIndicator_module[`is-color-${color}`]]) }))));
}

;// ../noodl-core-ui/src/components/common/ActivityIndicator/index.ts



/***/ }),

/***/ 12265:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgAlignItemRight = function SvgAlignItemRight(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.4805 7.92615H8.29297C7.93053 7.92615 7.63672 8.18198 7.63672 8.49758V11.3547C7.63672 11.6703 7.93053 11.9261 8.29297 11.9261H17.4805C17.8429 11.9261 18.1367 11.6703 18.1367 11.3547V8.49758C18.1367 8.18198 17.8429 7.92615 17.4805 7.92615Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.5742 13.4261H9.69922C9.38856 13.4261 9.13672 13.682 9.13672 13.9976V16.8547C9.13672 17.1703 9.38856 17.4261 9.69922 17.4261H17.5742C17.8849 17.4261 18.1367 17.1703 18.1367 16.8547V13.9976C18.1367 13.682 17.8849 13.4261 17.5742 13.4261Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M20.3867 3.67615C20.8009 3.67615 21.1367 4.03433 21.1367 4.47617L21.1367 20.8761C21.1367 21.318 20.8009 21.6761 20.3867 21.6761C19.9725 21.6761 19.6367 21.318 19.6367 20.8761L19.6367 4.47617C19.6367 4.03433 19.9725 3.67615 20.3867 3.67615Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgAlignItemRight);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "d5cce59464364db18dd4ee622e248319.svg");

/***/ }),

/***/ 12678:
/***/ ((module) => {

"use strict";
module.exports = require("classnames");

/***/ }),

/***/ 13185:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const Model = __webpack_require__(47821);
const { tracker } = __webpack_require__(38986);

var LessonModel = function (args) {
  Model.call(this);

  this.index = args.index;
  this.url = args.url;
  this.name = args.name;
  this.header = args.header;
  this.title = args.title;
  this.completionBadge = args.completionBadge;

  this.numberOfLessons = args.numberOfLessons;
  this.baseURL = args.baseURL;
  this.absoluteURL = this.url.startsWith('http') ? this.url : this.baseURL + this.url;
};
LessonModel.prototype = Object.create(Model.prototype);

LessonModel.prototype.fetch = function (callback) {
  var _this = this;

  var url = this.url.startsWith('http') ? this.url : this.baseURL + this.url;

  function extractAnnotations() {
    _this.annotations = [];

    for (var j in _this.lessons) {
      var annotations = _this.lessons[j].match(/data-[^=]+="[^"]+"/g);
      if (annotations) {
        var _a = {};
        for (var i in annotations) {
          var a = annotations[i];
          var name = a.substring(0, a.indexOf('='));
          var value = a.substring(a.indexOf('=') + 2, a.length - 1);
          _a[name] = value;
        }
        _this.annotations.push(_a);
      }
    }
  }

  $.ajax({
    url: url,
    cache: false,
    headers: {
      Accept: 'text/html'
    },
    success: function (html) {
      _this.lessons = html
        .split('<!-- # -->')
        .map((step) => step.trim())
        .filter((step) => step.length > 0);
      _this.numberOfLessons = _this.lessons.length;
      extractAnnotations();
      callback && callback();
    },
    error: function (err) {
      _this.lessons = undefined;
      callback && callback();
    }
  });
};

LessonModel.prototype.start = function () {
  this.fetch(() => {
    if (this.lessons) {
      if (this.index === 0) {
        // Track the the lesson is started
        tracker.track('Lesson started', {
          url: this.absoluteURL,
          name: this.name
        });
      }

      this.notifyListeners('instructionsFetched');
    }
  });
};

LessonModel.prototype.reportChanged = function () {
  if (this.index >= this.lessons.length - 1) {
    tracker.track('Lesson completed', {
      // Track that lesson is completed
      url: this.absoluteURL,
      name: this.name
    });
  } else if (this.index > 0) {
    tracker.track('Lesson next', {
      // Track that user moves to next lesson
      index: this.index,
      url: this.absoluteURL,
      name: this.name
    });
    tracker.increment('TotalLessonPartsCompleted', 1);
  }

  this.notifyListeners('instructionsChanged');
};

LessonModel.prototype.next = function () {
  if (this.index >= this.numberOfLessons - 1) {
    return;
  }

  this.index++;
  this.reportChanged();
};

LessonModel.prototype.getInstructions = function (step) {
  if (!this.lessons) return;
  if (step === undefined) step = 0;

  return this.lessons[step];
};

LessonModel.prototype.getAnnotations = function (step) {
  if (!this.annotations) return;
  if (step === undefined) step = 0;

  return this.annotations[step];
};

LessonModel.prototype.getCurrentSuggestedNodes = function () {
  if (!this.annotations) return;

  for (var i = this.index; i >= 0; i--) {
    var nodes = this.annotations[i]['data-suggested-nodes'];
    if (nodes) return nodes.split(',');
  }
};

LessonModel.prototype.getCurrentIconsDisabled = function () {
  let disabledIcons = [];

  if (this.annotations) {
    for (var i = this.index; i >= 0; i--) {
      const icons = this.annotations[i]['data-disable-icons'];
      if (icons) {
        disabledIcons = icons.split(',');
        break;
      }
    }
  }

  return disabledIcons.concat(['deploy', 'cloudServices']); //always disable deploy and cloudServices
};

LessonModel.prototype.getLength = function () {
  if (!this.lessons) return 0;
  return this.lessons.length;
};

LessonModel.prototype.getProgress = function () {
  if (!this.numberOfLessons || !this.index) return 0;

  var progress = Math.min(Math.round((this.index / this.numberOfLessons) * 100), 100);
  return progress;
};

LessonModel.prototype.toJSON = function () {
  return {
    index: this.index,
    numberOfLessons: this.numberOfLessons,
    url: this.url,
    name: this.name,
    header: this.header,
    title: this.title,
    baseURL: this.baseURL,
    completionBadge: this.completionBadge
  };
};

LessonModel.fromJSON = function (json) {
  return new LessonModel(json);
};

module.exports = LessonModel;


/***/ }),

/***/ 13484:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (/* binding */ useOnMount)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

function useOnMount(onMount) {
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(onMount, []);
}


/***/ }),

/***/ 13614:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDeviceTablet = function SvgDeviceTablet(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M18.1381 5.56425C18.1381 5.32927 17.9137 5.0271 17.4962 5.0271L6.50331 5.0271C6.08583 5.0271 5.86142 5.32927 5.86142 5.56425L5.86142 18.4358C5.86142 18.6707 6.08583 18.9729 6.50331 18.9729H17.4962C17.9137 18.9729 18.1381 18.6707 18.1381 18.4358V5.56425ZM17.4962 3.5271C18.5965 3.5271 19.6025 4.37748 19.6025 5.56425V18.4358C19.6025 19.6225 18.5965 20.4729 17.4962 20.4729H6.50331C5.40298 20.4729 4.39697 19.6225 4.39697 18.4358L4.39697 5.56425C4.39697 4.37748 5.40298 3.5271 6.50331 3.5271L17.4962 3.5271Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M11.8152 7.97765C12.2595 7.97765 12.6197 7.61748 12.6197 7.17318C12.6197 6.72889 12.2595 6.36871 11.8152 6.36871C11.3709 6.36871 11.0107 6.72889 11.0107 7.17318C11.0107 7.61748 11.3709 7.97765 11.8152 7.97765Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDeviceTablet);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "f097c0608735b826527200dac39afae1.svg");

/***/ }),

/***/ 13615:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-action-bar {
	white-space: nowrap;
	height: 100%;
}

.monaco-action-bar .actions-container {
	display: flex;
	margin: 0 auto;
	padding: 0;
	height: 100%;
	width: 100%;
	align-items: center;
}

.monaco-action-bar.vertical .actions-container {
	display: inline-block;
}

.monaco-action-bar .action-item {
	display: block;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	position: relative;  /* DO NOT REMOVE - this is the key to preventing the ghosting icon bug in Chrome 42 */
}

.monaco-action-bar .action-item.disabled {
	cursor: default;
}

.monaco-action-bar .action-item .icon,
.monaco-action-bar .action-item .codicon {
	display: block;
}

.monaco-action-bar .action-item .codicon {
	display: flex;
	align-items: center;
	width: 16px;
	height: 16px;
}

.monaco-action-bar .action-label {
	font-size: 11px;
	padding: 3px;
	border-radius: 5px;
}

.monaco-action-bar .action-item.disabled .action-label,
.monaco-action-bar .action-item.disabled .action-label::before,
.monaco-action-bar .action-item.disabled .action-label:hover {
	opacity: 0.6;
}

/* Vertical actions */

.monaco-action-bar.vertical {
	text-align: left;
}

.monaco-action-bar.vertical .action-item {
	display: block;
}

.monaco-action-bar.vertical .action-label.separator {
	display: block;
	border-bottom: 1px solid #bbb;
	padding-top: 1px;
	margin-left: .8em;
	margin-right: .8em;
}

.monaco-action-bar .action-item .action-label.separator {
	width: 1px;
	height: 16px;
	margin: 5px 4px !important;
	cursor: default;
	min-width: 1px;
	padding: 0;
	background-color: #bbb;
}

.secondary-actions .monaco-action-bar .action-label {
	margin-left: 6px;
}

/* Action Items */
.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-action-bar .action-item.action-dropdown-item {
	display: flex;
}

.monaco-action-bar .action-item.action-dropdown-item > .action-label {
	margin-right: 1px;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/actionbar/actionbar.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,mBAAmB;CACnB,YAAY;AACb;;AAEA;CACC,aAAa;CACb,cAAc;CACd,UAAU;CACV,YAAY;CACZ,WAAW;CACX,mBAAmB;AACpB;;AAEA;CACC,qBAAqB;AACtB;;AAEA;CACC,cAAc;CACd,mBAAmB;CACnB,uBAAuB;CACvB,eAAe;CACf,kBAAkB,GAAG,qFAAqF;AAC3G;;AAEA;CACC,eAAe;AAChB;;AAEA;;CAEC,cAAc;AACf;;AAEA;CACC,aAAa;CACb,mBAAmB;CACnB,WAAW;CACX,YAAY;AACb;;AAEA;CACC,eAAe;CACf,YAAY;CACZ,kBAAkB;AACnB;;AAEA;;;CAGC,YAAY;AACb;;AAEA,qBAAqB;;AAErB;CACC,gBAAgB;AACjB;;AAEA;CACC,cAAc;AACf;;AAEA;CACC,cAAc;CACd,6BAA6B;CAC7B,gBAAgB;CAChB,iBAAiB;CACjB,kBAAkB;AACnB;;AAEA;CACC,UAAU;CACV,YAAY;CACZ,0BAA0B;CAC1B,eAAe;CACf,cAAc;CACd,UAAU;CACV,sBAAsB;AACvB;;AAEA;CACC,gBAAgB;AACjB;;AAEA,iBAAiB;AACjB;CACC,gBAAgB,EAAE,iFAAiF;CACnG,OAAO;CACP,gBAAgB;CAChB,eAAe;CACf,aAAa;CACb,mBAAmB;CACnB,uBAAuB;CACvB,kBAAkB;AACnB;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,iBAAiB;AAClB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-action-bar {\n\twhite-space: nowrap;\n\theight: 100%;\n}\n\n.monaco-action-bar .actions-container {\n\tdisplay: flex;\n\tmargin: 0 auto;\n\tpadding: 0;\n\theight: 100%;\n\twidth: 100%;\n\talign-items: center;\n}\n\n.monaco-action-bar.vertical .actions-container {\n\tdisplay: inline-block;\n}\n\n.monaco-action-bar .action-item {\n\tdisplay: block;\n\talign-items: center;\n\tjustify-content: center;\n\tcursor: pointer;\n\tposition: relative;  /* DO NOT REMOVE - this is the key to preventing the ghosting icon bug in Chrome 42 */\n}\n\n.monaco-action-bar .action-item.disabled {\n\tcursor: default;\n}\n\n.monaco-action-bar .action-item .icon,\n.monaco-action-bar .action-item .codicon {\n\tdisplay: block;\n}\n\n.monaco-action-bar .action-item .codicon {\n\tdisplay: flex;\n\talign-items: center;\n\twidth: 16px;\n\theight: 16px;\n}\n\n.monaco-action-bar .action-label {\n\tfont-size: 11px;\n\tpadding: 3px;\n\tborder-radius: 5px;\n}\n\n.monaco-action-bar .action-item.disabled .action-label,\n.monaco-action-bar .action-item.disabled .action-label::before,\n.monaco-action-bar .action-item.disabled .action-label:hover {\n\topacity: 0.6;\n}\n\n/* Vertical actions */\n\n.monaco-action-bar.vertical {\n\ttext-align: left;\n}\n\n.monaco-action-bar.vertical .action-item {\n\tdisplay: block;\n}\n\n.monaco-action-bar.vertical .action-label.separator {\n\tdisplay: block;\n\tborder-bottom: 1px solid #bbb;\n\tpadding-top: 1px;\n\tmargin-left: .8em;\n\tmargin-right: .8em;\n}\n\n.monaco-action-bar .action-item .action-label.separator {\n\twidth: 1px;\n\theight: 16px;\n\tmargin: 5px 4px !important;\n\tcursor: default;\n\tmin-width: 1px;\n\tpadding: 0;\n\tbackground-color: #bbb;\n}\n\n.secondary-actions .monaco-action-bar .action-label {\n\tmargin-left: 6px;\n}\n\n/* Action Items */\n.monaco-action-bar .action-item.select-container {\n\toverflow: hidden; /* somehow the dropdown overflows its container, we prevent it here to not push */\n\tflex: 1;\n\tmax-width: 170px;\n\tmin-width: 60px;\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n\tmargin-right: 10px;\n}\n\n.monaco-action-bar .action-item.action-dropdown-item {\n\tdisplay: flex;\n}\n\n.monaco-action-bar .action-item.action-dropdown-item > .action-label {\n\tmargin-right: 1px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 13773:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRocket = function SvgRocket(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M20.5342 3.2098C20.295 2.97056 19.98 2.82211 19.6434 2.78974C18.4809 2.66128 15.7953 2.55045 13.0376 3.76524C12.0841 4.18522 11.1314 4.75974 10.2357 5.5349L6.06373 5.90977C5.83629 5.92817 5.61647 6.0004 5.42241 6.12053C5.2304 6.2394 5.06912 6.40175 4.95155 6.59441L2.17477 10.9451L2.17348 10.9472C2.03955 11.1585 1.96158 11.4004 1.94688 11.6501C1.93219 11.8999 1.98126 12.1493 2.08948 12.3749C2.1977 12.6004 2.36152 12.7948 2.56552 12.9396C2.76953 13.0844 3.00747 13.175 3.25611 13.2028L6.45582 13.5584L7.79038 14.8929L5.49925 17.184C5.20636 17.4769 5.20635 17.9518 5.49924 18.2447C5.79213 18.5376 6.26701 18.5376 6.5599 18.2447L8.85104 15.9536L10.1858 17.2884L10.5414 20.4881C10.5691 20.7367 10.6597 20.9742 10.8045 21.1782C10.9494 21.3822 11.1437 21.5461 11.3693 21.6543C11.5948 21.7625 11.8442 21.8116 12.094 21.7969C12.3437 21.7822 12.5857 21.7042 12.797 21.5703L12.799 21.569L17.1497 18.7922C17.3424 18.6746 17.5047 18.5134 17.6236 18.3214C17.7437 18.1274 17.8159 17.9078 17.8343 17.6805L18.2217 13.4195C18.9711 12.5403 19.531 11.6097 19.9442 10.6798C21.1661 7.92991 21.073 5.26147 20.9546 4.10421C20.923 3.76626 20.7743 3.44989 20.5342 3.2098ZM16.9828 12.559C16.9508 12.5891 16.9215 12.622 16.8951 12.6574C15.6493 14.0372 13.8166 15.2826 11.1189 16.1001L7.64083 12.622C8.43399 9.91919 9.66156 8.0833 11.0297 6.83572C11.0452 6.8228 11.0601 6.80928 11.0744 6.7952C11.9019 6.05008 12.7793 5.51807 13.6422 5.13796C16.0474 4.07852 18.4212 4.16537 19.4647 4.27913C19.569 5.32291 19.6373 7.67631 18.5734 10.0707C18.2027 10.9049 17.6907 11.7535 16.9828 12.559ZM16.5713 15.0056L16.342 17.5283L12.0277 20.2818L11.717 17.4854C13.7272 16.8567 15.3177 15.9965 16.5713 15.0056ZM6.21548 7.40218L8.6782 7.18089C7.70337 8.43429 6.86187 10.0223 6.2532 12.0266L3.46194 11.7165L6.21548 7.40218Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M14.5241 9.21963C14.8781 9.5736 15.452 9.5736 15.806 9.21963C16.1599 8.86566 16.1599 8.29176 15.806 7.93779C15.452 7.58382 14.8781 7.58382 14.5241 7.93779C14.1702 8.29176 14.1702 8.86566 14.5241 9.21963Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M11.6711 12.0729C12.0251 12.4269 12.599 12.4269 12.9529 12.0729C13.3069 11.7189 13.3069 11.145 12.9529 10.7911C12.599 10.4371 12.0251 10.4371 11.6711 10.7911C11.3171 11.145 11.3171 11.7189 11.6711 12.0729Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRocket);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "fbc7103e79b2d0a073a4e9207abca8d8.svg");

/***/ }),

/***/ 13777:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.iconpicker-bg {
  background-color: var(--theme-color-bg-2);
}

.iconpicker-header {
  background-color: var(--theme-color-bg-4);
  flex: 0 0 26px;
  line-height: 30px;
  padding-left: 10px;
}

.iconpicker-search-header {
  background-color: var(--theme-color-bg-4);
}

.iconpicker-iconset-header {
  background-color: var(--theme-color-bg-4);
  flex: 0 0 26px;
  line-height: 30px;
  padding-left: 10px;
}

.iconpicker-label {
  color: var(--theme-color-fg-muted);
}

.iconpicker-search-input {
  background-color: var(--theme-color-bg-5);
  color: var(--theme-color-fg-default-contrast);
  border: none;
  display: block;
  padding: 0 0 0 10px;
  box-sizing: border-box;
  font: 12px var(--font-family-regular);
}

.iconpicker-icon {
  color: var(--theme-color-fg-highlight);
  width: 24px;
  height: 24px;
  padding: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/propertyeditor/iconpicker.css"],"names":[],"mappings":"AAAA;EACE,yCAAyC;AAC3C;;AAEA;EACE,yCAAyC;EACzC,cAAc;EACd,iBAAiB;EACjB,kBAAkB;AACpB;;AAEA;EACE,yCAAyC;AAC3C;;AAEA;EACE,yCAAyC;EACzC,cAAc;EACd,iBAAiB;EACjB,kBAAkB;AACpB;;AAEA;EACE,kCAAkC;AACpC;;AAEA;EACE,yCAAyC;EACzC,6CAA6C;EAC7C,YAAY;EACZ,cAAc;EACd,mBAAmB;EACnB,sBAAsB;EACtB,qCAAqC;AACvC;;AAEA;EACE,sCAAsC;EACtC,WAAW;EACX,YAAY;EACZ,YAAY;EACZ,aAAa;EACb,uBAAuB;EACvB,mBAAmB;EACnB,eAAe;AACjB","sourcesContent":[".iconpicker-bg {\n  background-color: var(--theme-color-bg-2);\n}\n\n.iconpicker-header {\n  background-color: var(--theme-color-bg-4);\n  flex: 0 0 26px;\n  line-height: 30px;\n  padding-left: 10px;\n}\n\n.iconpicker-search-header {\n  background-color: var(--theme-color-bg-4);\n}\n\n.iconpicker-iconset-header {\n  background-color: var(--theme-color-bg-4);\n  flex: 0 0 26px;\n  line-height: 30px;\n  padding-left: 10px;\n}\n\n.iconpicker-label {\n  color: var(--theme-color-fg-muted);\n}\n\n.iconpicker-search-input {\n  background-color: var(--theme-color-bg-5);\n  color: var(--theme-color-fg-default-contrast);\n  border: none;\n  display: block;\n  padding: 0 0 0 10px;\n  box-sizing: border-box;\n  font: 12px var(--font-family-regular);\n}\n\n.iconpicker-icon {\n  color: var(--theme-color-fg-highlight);\n  width: 24px;\n  height: 24px;\n  padding: 5px;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  cursor: pointer;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 13837:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCaretRight = function SvgCaretRight(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M8.60639 18.5303C8.3135 18.2374 8.3135 17.7626 8.60639 17.4697L14.0761 12L8.60639 6.53033C8.3135 6.23744 8.3135 5.76256 8.60639 5.46967C8.89928 5.17678 9.37416 5.17678 9.66705 5.46967L15.667 11.4697C15.9599 11.7626 15.9599 12.2374 15.667 12.5303L9.66705 18.5303C9.37416 18.8232 8.89928 18.8232 8.60639 18.5303Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCaretRight);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "ec5f4bc7ca029ff654e786cabb4ecb1c.svg");

/***/ }),

/***/ 14061:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCircleDot = function SvgCircleDot(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M18.0412 5.92932C17.9447 6.41692 17.4712 6.73398 16.9836 6.63748C15.0511 6.25504 13.0459 6.54499 11.3009 7.4592C9.55589 8.3734 8.17599 9.85688 7.39027 11.6634C6.60454 13.4699 6.46024 15.4908 6.98132 17.3906C7.5024 19.2904 8.65751 20.9549 10.2549 22.1078C11.8523 23.2607 13.796 23.8326 15.7632 23.7286C17.7305 23.6246 19.603 22.851 21.07 21.5362C22.537 20.2213 23.5102 18.4443 23.8281 16.5002C23.9957 15.4749 23.9758 14.4356 23.777 13.4308C23.6805 12.9432 23.9975 12.4697 24.4851 12.3733C24.9727 12.2768 25.4462 12.5938 25.5427 13.0814C25.783 14.2956 25.8071 15.5516 25.6045 16.7907C25.2203 19.1401 24.0442 21.2876 22.2713 22.8766C20.4985 24.4655 18.2356 25.4004 15.8582 25.5261C13.4808 25.6517 11.132 24.9606 9.20153 23.5674C7.27108 22.1741 5.87514 20.1626 5.24543 17.8667C4.61572 15.5708 4.7901 13.1286 5.73964 10.9455C6.68918 8.76233 8.35676 6.96956 10.4656 5.86476C12.5744 4.75995 14.9976 4.40955 17.333 4.87173C17.8206 4.96822 18.1377 5.44172 18.0412 5.92932Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M20.2192 6.98721C20.5159 6.58847 21.0797 6.5058 21.4785 6.80256C22.3278 7.43465 23.0759 8.19262 23.6969 9.05028C23.9884 9.45288 23.8983 10.0156 23.4957 10.3071C23.0931 10.5986 22.5304 10.5085 22.2389 10.1059C21.7252 9.39644 21.1064 8.76942 20.4038 8.24654C20.0051 7.94978 19.9224 7.38596 20.2192 6.98721Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCircleDot);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "3a431bc30b11bc079f5dbceca8cfaa2a.svg");

/***/ }),

/***/ 14264:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRoundedCornerAll = function SvgRoundedCornerAll(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.45898 10.8704L5.45898 13.1204C5.45898 13.5346 5.1232 13.8704 4.70898 13.8704C4.29477 13.8704 3.95898 13.5346 3.95898 13.1204L3.95898 10.8704C3.95898 7.14244 6.98106 4.12036 10.709 4.12036L12.959 4.12036C13.3732 4.12036 13.709 4.45615 13.709 4.87036C13.709 5.28457 13.3732 5.62036 12.959 5.62036L10.709 5.62036C7.80949 5.62036 5.45898 7.97087 5.45898 10.8704Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M24.8145 10.8703L24.8145 13.1165C24.8145 13.5307 25.1502 13.8665 25.5645 13.8665C25.9787 13.8665 26.3145 13.5307 26.3145 13.1165L26.3145 10.8703C26.3145 7.14239 23.2924 4.12031 19.5645 4.12031L17.3183 4.12031C16.9041 4.12031 16.5683 4.4561 16.5683 4.87031C16.5683 5.28453 16.9041 5.62031 17.3183 5.62031L19.5645 5.62031C22.4639 5.62031 24.8145 7.97082 24.8145 10.8703Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.45898 19.7258L5.45898 17.4758C5.45898 17.0616 5.1232 16.7258 4.70898 16.7258C4.29477 16.7258 3.95898 17.0616 3.95898 17.4758L3.95898 19.7258C3.95898 23.4538 6.98106 26.4758 10.709 26.4758L12.959 26.4758C13.3732 26.4758 13.709 26.14 13.709 25.7258C13.709 25.3116 13.3732 24.9758 12.959 24.9758L10.709 24.9758C7.80949 24.9758 5.45898 22.6253 5.45898 19.7258Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M24.8145 19.7259L24.8145 17.4797C24.8145 17.0655 25.1502 16.7297 25.5645 16.7297C25.9787 16.7297 26.3145 17.0655 26.3145 17.4797L26.3145 19.7259C26.3145 23.4538 23.2924 26.4759 19.5645 26.4759L17.3183 26.4759C16.9041 26.4759 16.5683 26.1401 16.5683 25.7259C16.5683 25.3117 16.9041 24.9759 17.3183 24.9759L19.5645 24.9759C22.4639 24.9759 24.8145 22.6254 24.8145 19.7259Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRoundedCornerAll);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "b40dce4895dcabad421c0e84010d2cbc.svg");

/***/ }),

/***/ 14596:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.CreateTableModal-module__Overlay--IZAZ0{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;z-index:1000}.CreateTableModal-module__Modal--ltHfm{background:var(--theme-color-bg-2);border-radius:8px;width:640px;max-width:90vw;max-height:80vh;display:flex;flex-direction:column;box-shadow:0 8px 32px rgba(0,0,0,.4)}.CreateTableModal-module__Header--jEi6l{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--theme-color-border-default)}.CreateTableModal-module__Content--qPa_5{flex:1;overflow-y:auto;padding:20px}.CreateTableModal-module__Section--oEPwF{margin-bottom:20px}.CreateTableModal-module__Section--oEPwF:last-child{margin-bottom:0}.CreateTableModal-module__Input--HPFbh{width:100%;padding:8px 12px;margin-top:8px;background:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:4px;color:var(--theme-color-fg-default);font-size:13px}.CreateTableModal-module__Input--HPFbh::placeholder{color:var(--theme-color-fg-default-shy)}.CreateTableModal-module__Input--HPFbh:focus{outline:none;border-color:var(--theme-color-primary)}.CreateTableModal-module__ColumnsTable--baEMl{margin-top:12px;border:1px solid var(--theme-color-border-default);border-radius:4px;overflow:hidden}.CreateTableModal-module__ColumnRow--V3NER{display:grid;grid-template-columns:2fr 1.2fr .8fr 1.5fr 40px;gap:8px;padding:8px 12px;background:var(--theme-color-bg-3);border-bottom:1px solid var(--theme-color-border-default);align-items:center}.CreateTableModal-module__ColumnRow--V3NER:first-child{background:var(--theme-color-bg-2);font-size:11px;color:var(--theme-color-fg-default-shy);text-transform:uppercase;letter-spacing:.5px}.CreateTableModal-module__ColumnRow--V3NER:last-child{border-bottom:none}.CreateTableModal-module__ColumnRow--V3NER[data-system=true]{background:var(--theme-color-bg-2);opacity:.7}.CreateTableModal-module__ColName--KbcOp,.CreateTableModal-module__ColType--bahMw,.CreateTableModal-module__ColRequired--zo0oP,.CreateTableModal-module__ColDefault--srx2X,.CreateTableModal-module__ColActions--p021a{display:flex;align-items:center}.CreateTableModal-module__ColRequired--zo0oP{justify-content:center}.CreateTableModal-module__ColActions--p021a{justify-content:flex-end}.CreateTableModal-module__ColumnInput--rpyPi{width:100%;padding:6px 8px;background:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:3px;color:var(--theme-color-fg-default);font-size:12px}.CreateTableModal-module__ColumnInput--rpyPi::placeholder{color:var(--theme-color-fg-default-shy)}.CreateTableModal-module__ColumnInput--rpyPi:focus{outline:none;border-color:var(--theme-color-primary)}.CreateTableModal-module__TypeSelect--ZC5I2{width:100%;padding:6px 8px;background:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:3px;color:var(--theme-color-fg-default);font-size:12px;cursor:pointer}.CreateTableModal-module__TypeSelect--ZC5I2:focus{outline:none;border-color:var(--theme-color-primary)}.CreateTableModal-module__Error--tPIGs{display:flex;align-items:center;gap:8px;padding:10px 12px;background:var(--theme-color-danger-transparent);border-radius:4px;color:var(--theme-color-danger);margin-top:12px}.CreateTableModal-module__Footer--EbHS1{display:flex;align-items:center;justify-content:flex-end;gap:8px;padding:16px 20px;border-top:1px solid var(--theme-color-border-default)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/schemamanager/CreateTableModal.module.scss"],"names":[],"mappings":"AAIA,yCACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,yBAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,YAAA,CAGF,uCACE,kCAAA,CACA,iBAAA,CACA,WAAA,CACA,cAAA,CACA,eAAA,CACA,YAAA,CACA,qBAAA,CACA,oCAAA,CAGF,wCACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,iBAAA,CACA,yDAAA,CAGF,yCACE,MAAA,CACA,eAAA,CACA,YAAA,CAGF,yCACE,kBAAA,CAEA,oDACE,eAAA,CAIJ,uCACE,UAAA,CACA,gBAAA,CACA,cAAA,CACA,kCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CAEA,oDACE,uCAAA,CAGF,6CACE,YAAA,CACA,uCAAA,CAIJ,8CACE,eAAA,CACA,kDAAA,CACA,iBAAA,CACA,eAAA,CAGF,2CACE,YAAA,CACA,+CAAA,CACA,OAAA,CACA,gBAAA,CACA,kCAAA,CACA,yDAAA,CACA,kBAAA,CAEA,uDACE,kCAAA,CACA,cAAA,CACA,uCAAA,CACA,wBAAA,CACA,mBAAA,CAGF,sDACE,kBAAA,CAGF,6DACE,kCAAA,CACA,UAAA,CAIJ,uNAKE,YAAA,CACA,kBAAA,CAGF,6CACE,sBAAA,CAGF,4CACE,wBAAA,CAGF,6CACE,UAAA,CACA,eAAA,CACA,kCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CAEA,0DACE,uCAAA,CAGF,mDACE,YAAA,CACA,uCAAA,CAIJ,4CACE,UAAA,CACA,eAAA,CACA,kCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,cAAA,CAEA,kDACE,YAAA,CACA,uCAAA,CAIJ,uCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,iBAAA,CACA,gDAAA,CACA,iBAAA,CACA,+BAAA,CACA,eAAA,CAGF,wCACE,YAAA,CACA,kBAAA,CACA,wBAAA,CACA,OAAA,CACA,iBAAA,CACA,sDAAA","sourcesContent":["/**\n * CreateTableModal styles\n */\n\n.Overlay {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background: rgba(0, 0, 0, 0.5);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 1000;\n}\n\n.Modal {\n  background: var(--theme-color-bg-2);\n  border-radius: 8px;\n  width: 640px;\n  max-width: 90vw;\n  max-height: 80vh;\n  display: flex;\n  flex-direction: column;\n  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);\n}\n\n.Header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 16px 20px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.Content {\n  flex: 1;\n  overflow-y: auto;\n  padding: 20px;\n}\n\n.Section {\n  margin-bottom: 20px;\n\n  &:last-child {\n    margin-bottom: 0;\n  }\n}\n\n.Input {\n  width: 100%;\n  padding: 8px 12px;\n  margin-top: 8px;\n  background: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  color: var(--theme-color-fg-default);\n  font-size: 13px;\n\n  &::placeholder {\n    color: var(--theme-color-fg-default-shy);\n  }\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.ColumnsTable {\n  margin-top: 12px;\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  overflow: hidden;\n}\n\n.ColumnRow {\n  display: grid;\n  grid-template-columns: 2fr 1.2fr 0.8fr 1.5fr 40px;\n  gap: 8px;\n  padding: 8px 12px;\n  background: var(--theme-color-bg-3);\n  border-bottom: 1px solid var(--theme-color-border-default);\n  align-items: center;\n\n  &:first-child {\n    background: var(--theme-color-bg-2);\n    font-size: 11px;\n    color: var(--theme-color-fg-default-shy);\n    text-transform: uppercase;\n    letter-spacing: 0.5px;\n  }\n\n  &:last-child {\n    border-bottom: none;\n  }\n\n  &[data-system='true'] {\n    background: var(--theme-color-bg-2);\n    opacity: 0.7;\n  }\n}\n\n.ColName,\n.ColType,\n.ColRequired,\n.ColDefault,\n.ColActions {\n  display: flex;\n  align-items: center;\n}\n\n.ColRequired {\n  justify-content: center;\n}\n\n.ColActions {\n  justify-content: flex-end;\n}\n\n.ColumnInput {\n  width: 100%;\n  padding: 6px 8px;\n  background: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 3px;\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n\n  &::placeholder {\n    color: var(--theme-color-fg-default-shy);\n  }\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.TypeSelect {\n  width: 100%;\n  padding: 6px 8px;\n  background: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 3px;\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n  cursor: pointer;\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.Error {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 10px 12px;\n  background: var(--theme-color-danger-transparent);\n  border-radius: 4px;\n  color: var(--theme-color-danger);\n  margin-top: 12px;\n}\n\n.Footer {\n  display: flex;\n  align-items: center;\n  justify-content: flex-end;\n  gap: 8px;\n  padding: 16px 20px;\n  border-top: 1px solid var(--theme-color-border-default);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Overlay": `CreateTableModal-module__Overlay--IZAZ0`,
	"Modal": `CreateTableModal-module__Modal--ltHfm`,
	"Header": `CreateTableModal-module__Header--jEi6l`,
	"Content": `CreateTableModal-module__Content--qPa_5`,
	"Section": `CreateTableModal-module__Section--oEPwF`,
	"Input": `CreateTableModal-module__Input--HPFbh`,
	"ColumnsTable": `CreateTableModal-module__ColumnsTable--baEMl`,
	"ColumnRow": `CreateTableModal-module__ColumnRow--V3NER`,
	"ColName": `CreateTableModal-module__ColName--KbcOp`,
	"ColType": `CreateTableModal-module__ColType--bahMw`,
	"ColRequired": `CreateTableModal-module__ColRequired--zo0oP`,
	"ColDefault": `CreateTableModal-module__ColDefault--srx2X`,
	"ColActions": `CreateTableModal-module__ColActions--p021a`,
	"ColumnInput": `CreateTableModal-module__ColumnInput--rpyPi`,
	"TypeSelect": `CreateTableModal-module__TypeSelect--ZC5I2`,
	"Error": `CreateTableModal-module__Error--tPIGs`,
	"Footer": `CreateTableModal-module__Footer--EbHS1`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 14764:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5, _path6, _path7, _path8, _path9;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDimensionWidthHeight = function SvgDimensionWidthHeight(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 30,
    viewBox: "0 0 31 30",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M18.4189 11.2185C18.6951 11.2185 18.9189 11.4424 18.9189 11.7185L18.9189 18.2821C18.9189 18.5582 18.6951 18.7821 18.4189 18.7821L11.8554 18.7821C11.5792 18.7821 11.3554 18.5582 11.3554 18.2821L11.3554 11.7185C11.3554 11.4424 11.5792 11.2185 11.8554 11.2185L18.4189 11.2185Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M24.7803 12.0027C25.0732 12.2956 25.0732 12.7705 24.7803 13.0634L22.8437 15L24.7803 16.9366C25.0732 17.2295 25.0732 17.7044 24.7803 17.9973C24.4874 18.2902 24.0126 18.2902 23.7197 17.9973L21.2527 15.5303C20.9598 15.2374 20.9598 14.7626 21.2527 14.4697L23.7197 12.0027C24.0126 11.7098 24.4874 11.7098 24.7803 12.0027Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M28.8096 15.0002C28.8096 15.4145 28.4738 15.7502 28.0596 15.7502L21.7832 15.7502C21.369 15.7502 21.0332 15.4145 21.0332 15.0002C21.0332 14.586 21.369 14.2502 21.7832 14.2502L28.0596 14.2502C28.4738 14.2502 28.8096 14.586 28.8096 15.0002Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.94623 12.0027C4.65334 12.2956 4.65334 12.7705 4.94623 13.0634L6.88287 15L4.94623 16.9366C4.65334 17.2295 4.65334 17.7044 4.94623 17.9973C5.23913 18.2902 5.714 18.2902 6.00689 17.9973L8.47386 15.5303C8.76676 15.2374 8.76676 14.7626 8.47386 14.4697L6.00689 12.0027C5.714 11.7098 5.23913 11.7098 4.94623 12.0027Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M0.916992 15.0002C0.916992 15.4145 1.25278 15.7502 1.66699 15.7502L7.94339 15.7502C8.3576 15.7502 8.69339 15.4145 8.69339 15.0002C8.69339 14.586 8.3576 14.2502 7.94339 14.2502L1.66699 14.2502C1.25278 14.2502 0.916992 14.586 0.916992 15.0002Z",
    fill: "#F5F5F5"
  })), _path6 || (_path6 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M17.8604 24.917C17.5675 25.2099 17.0926 25.2099 16.7997 24.917L14.8631 22.9803L12.9265 24.917C12.6336 25.2099 12.1587 25.2099 11.8658 24.917C11.5729 24.6241 11.5729 24.1492 11.8658 23.8563L14.3328 21.3894C14.6257 21.0965 15.1005 21.0965 15.3934 21.3894L17.8604 23.8563C18.1533 24.1492 18.1533 24.6241 17.8604 24.917Z",
    fill: "#F5F5F5"
  })), _path7 || (_path7 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M14.8633 28.9459C14.4491 28.9459 14.1133 28.6101 14.1133 28.1959L14.1133 21.9195C14.1133 21.5053 14.4491 21.1695 14.8633 21.1695C15.2775 21.1695 15.6133 21.5053 15.6133 21.9195L15.6133 28.1959C15.6133 28.6101 15.2775 28.9459 14.8633 28.9459Z",
    fill: "#F5F5F5"
  })), _path8 || (_path8 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M17.8604 5.08326C17.5675 4.79036 17.0926 4.79036 16.7997 5.08326L14.8631 7.0199L12.9265 5.08326C12.6336 4.79036 12.1587 4.79036 11.8658 5.08326C11.5729 5.37615 11.5729 5.85102 11.8658 6.14392L14.3328 8.61089C14.6257 8.90378 15.1005 8.90378 15.3934 8.61089L17.8604 6.14392C18.1533 5.85102 18.1533 5.37615 17.8604 5.08326Z",
    fill: "#F5F5F5"
  })), _path9 || (_path9 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M14.8633 1.05414C14.4491 1.05414 14.1133 1.38992 14.1133 1.80414L14.1133 8.08053C14.1133 8.49475 14.4491 8.83053 14.8633 8.83053C15.2775 8.83053 15.6133 8.49475 15.6133 8.08053L15.6133 1.80414C15.6133 1.38992 15.2775 1.05414 14.8633 1.05414Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDimensionWidthHeight);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "515d58d605bb2b403b0cf3337a31f980.svg");

/***/ }),

/***/ 15204:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  m: () => (/* binding */ NodeLibrary)
});

// EXTERNAL MODULE: external "underscore"
var external_underscore_ = __webpack_require__(80002);
var external_underscore_default = /*#__PURE__*/__webpack_require__.n(external_underscore_);
// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/BasicNodeType.ts
var BasicNodeType = __webpack_require__(28593);
// EXTERNAL MODULE: ./src/shared/model.js
var model = __webpack_require__(47821);
var model_default = /*#__PURE__*/__webpack_require__.n(model);
;// ./src/editor/src/models/nodelibrary/UnknownNodeType.ts

class UnknownNodeType extends (model_default()) {
    get localName() {
        const path = this.name.split('/');
        return path[path.length - 1];
    }
    get fullName() {
        return this.name;
    }
    get displayName() {
        return this.localName;
    }
    constructor(typename) {
        super();
        this.name = typename;
        return this;
    }
    labelForNode(node) {
        return this.localName;
    }
    /**
     * Module is undefined for basic types
     */
    getModule() { }
}

;// ./src/editor/src/models/nodelibrary/nodelibrary.ts




const _condFuncCache = {};
function evaluateDynamicPortsCondition(cond, node) {
    if (cond.startsWith('#js')) {
        // This is a JS expression
        if (_condFuncCache[cond] === undefined)
            _condFuncCache[cond] = new Function('params', 'return ' + cond.substring('#js'.length));
        return !!_condFuncCache[cond](new Proxy(node.parameters, {
            get: (target, prop, receiver) => {
                return node.getParameter(prop);
            }
        }));
    }
    const tokens = cond.match(/(?:[^\s']+|'[^']*')+/g); // Split on whitespace but respect single qoutes
    function evalCond(i) {
        if (tokens.length < i + 3)
            return true;
        const paramName = tokens[i + 0].replace(/'/g, ''); // Trim any quotes
        const op = tokens[i + 1];
        const value = tokens[i + 2].replace(/'/g, '');
        let res;
        switch (op) {
            case '=':
                res = '' + node.getParameter(paramName) === value;
                break;
            case '!=':
                res = '' + node.getParameter(paramName) !== value;
                break;
            case 'NOT':
                res = node.getParameter(paramName) === undefined;
                break;
        }
        if (tokens.length > i + 3) {
            const logic = tokens[i + 3];
            switch (logic) {
                case 'AND':
                    return res && evalCond(i + 4);
                case 'OR':
                    return res || evalCond(i + 4);
            }
        }
        return res;
    }
    return evalCond(0);
}
class NodeLibrary extends (model_default()) {
    constructor() {
        super();
        this.modules = [];
        //have all types available in a name => type map to improve performance
        //of getNodeTypeWithName which is a major hotspot
        this.typeCache = new Map();
        this.loadLibrary();
        return this;
    }
    /** Returns the name for a port type */
    static nameForPortType(type) {
        if (!type)
            return;
        return typeof type === 'string' ? type : type.name;
    }
    loadLibrary() {
        this.types = [];
        this.typeCache.clear();
        this.unkownNodeTypes = {};
        // @ts-expect-error window be scary!
        this.library = (typeof window !== 'undefined' ? window.NodeLibraryData : {}) || {};
        // Register basic types from the node library
        for (const i in this.library.nodetypes) {
            const type = this.library.nodetypes[i];
            this.registerType(new BasicNodeType/* BasicNodeType */.F(type));
        }
        // Dynamic port managers
        // this.dynamicPortManagers = [];
        /*  var dynamicPortManagerTypes = {
          'numbered':NodeLibrary.DynamicPortNumbered,
          'portchannel':NodeLibrary.DynamicPortChannel,
          'conditionalports':NodeLibrary.DynamicPortConditional,
          'expand':NodeLibrary.DynamicPortExpand,
        };*/
        /*  for(var i in this.library.dynamicports) {
          var type = this.library.dynamicports[i].type;
      
          if(type && dynamicPortManagerTypes[type])
            this.dynamicPortManagers.push(new dynamicPortManagerTypes[type](this.library.dynamicports[i]));
        }*/
        // Make sure the default color scheme is present
        if (!this.library.colors)
            this.library.colors = { nodes: {}, connections: {} };
        if (!this.library.colors.nodes.default) {
            this.library.colors.nodes.default = {
                base: '#485e65',
                text: '#93a1a1'
            };
        }
        if (!this.library.colors.connections.default) {
            this.library.colors.connections.default = {
                normal: '#916311',
                highlighted: '#ffa300'
            };
        }
    }
    reload() {
        this.loadLibrary();
        this.notifyListeners('libraryUpdated');
    }
    isLoaded() {
        return this.types.length > 0;
    }
    registerModule(module) {
        this.modules.push(module);
        module._registered = true;
        //keep this.typeCache in sync by removing components that are removed from registered modules
        //no need to listen for new components since getNodeTypeWithName handles types that arent in the typeCache
        module.on('componentRemoved', ({ model }) => {
            this.typeCache.delete(model.name);
        }, this);
        this.notifyListeners('moduleRegistered', { model: module });
    }
    unregisterModule(module) {
        module.off(this);
        const idx = this.modules.indexOf(module);
        idx !== -1 && this.modules.splice(idx, 1);
        module._registered = false;
        this.typeCache.clear();
        this.notifyListeners('moduleUnregistered', { model: module });
    }
    isModuleRegistered(module) {
        return module._registered;
    }
    _getNodeTypeWithName(typename) {
        const types = this.types.concat(this.getComponents());
        return external_underscore_default().find(types, function (type) {
            return type.name === typename;
        });
    }
    getNodeTypeWithName(typename) {
        const hasLoadedNodeLib = this.types.length;
        if (hasLoadedNodeLib && !this.typeCache.has(typename)) {
            const types = this.types.concat(this.getComponents());
            types.forEach((type) => this.typeCache.set(type.name, type));
        }
        return this.typeCache.get(typename);
    }
    getNodeTypes() {
        return this.types;
    }
    getComponents() {
        let components = [];
        for (const i in this.modules) {
            const m = this.modules[i];
            components = components.concat(m.getComponents());
        }
        return components;
    }
    registerType(type) {
        this.types.push(type);
    }
    getUnknownNodeType(typename) {
        if (!this.unkownNodeTypes[typename])
            this.unkownNodeTypes[typename] = new UnknownNodeType(typename);
        return this.unkownNodeTypes[typename];
    }
    typeIsMissing(type) {
        if (!type ||
            type instanceof UnknownNodeType || // Type has not been resolved
            (type.graph && !type.owner)) {
            // Type is component but not part of a project
            return true;
        }
        return false;
    }
    colorSchemeForNodeColorName(name) {
        return this.library.colors.nodes[name] || this.library.colors.nodes.default;
    }
    colorSchemeForNodeType(type) {
        if (!type.color)
            return this.library.colors.nodes.default;
        return this.library.colors.nodes[type.color];
    }
    colorSchemeForConnectionType(type) {
        if (!this.library.colors.connections[type])
            return this.library.colors.connections.default;
        return this.library.colors.connections[type];
    }
    // This function returns the annotated name for a port this is generally the
    // display name for the port plus any annotations such as the unit for numbers
    getAnnotatedPortName(node, port) {
        const displayName = (port.displayName ? port.displayName : port.name) +
            (port.tab && port.tab.label ? ' (' + port.tab.label + ')' : '');
        // Annotate an number port with units with the current unit
        if (NodeLibrary.nameForPortType(port.type) === 'number' && port.type.units !== undefined) {
            const haveUnit = node.parameters[port.name] !== undefined && node.parameters[port.name].unit !== undefined;
            return (displayName +
                '<span class="portname-annotation-unit">&nbsp;(' +
                (haveUnit ? node.parameters[port.name].unit : port.type.defaultUnit) +
                ')<span>');
        }
        return displayName;
    }
    formatParameterValue(value, port) {
        if (!port)
            return value;
        if (value === undefined)
            return;
        // If it's an enum node, it must return the label
        if (NodeLibrary.nameForPortType(port.type) === 'enum') {
            if (value === undefined)
                return 'none';
            const e = external_underscore_default().find(port.type.enums, function (e) {
                return e === value || e.value === value;
            });
            if (e === undefined)
                return;
            return e.label ? e.label : e;
        }
        // If the value has a unit, format it
        else if (NodeLibrary.nameForPortType(port.type) === 'number' && port.type.units !== undefined) {
            if (value.unit !== undefined)
                return value.value + '' + value.unit;
            else
                return value + '' + port.type.units[0];
        }
        return value;
    }
    typeRenamed(model, oldName) {
        this.typeCache.delete(oldName);
        this.typeCache.set(model.name, model);
        this.notifyListeners('typeRenamed', { model, oldName });
    }
    findVariant(variantName, nodeType) {
        let variant = null;
        for (const m of this.modules) {
            if (m.findVariant)
                variant = m.findVariant(variantName, nodeType);
            if (variant !== undefined)
                return variant;
        }
        return variant;
    }
    getStyles(styleType) {
        for (const m of this.modules) {
            if (m.getMetaData) {
                const styles = m.getMetaData('styles');
                if (styles && styles[styleType]) {
                    return styles[styleType];
                }
            }
        }
        return {};
    }
    // Return true if a type can be casted to
    canCastPortTypes(from, to) {
        const _from = NodeLibrary.nameForPortType(from);
        const _to = NodeLibrary.nameForPortType(to);
        if (_from === '*' || _to === '*')
            return true; // All types
        if (_from === _to)
            return true; // Same type
        // Not same type, look in cast list
        const cast = external_underscore_default().find(this.library.typecasts, function (c) {
            return c.from === _from;
        });
        if (!cast)
            return false;
        return cast.to.indexOf(_to) !== -1;
    }
    // This function attempts to find a type that is compatible with all connections
    // in the supplied array. The connections array should be on the form
    // [{direction:'to',type: 'number'},
    //  {direction:'from',type: 'boolean'}, ...]
    // The direction is the direction which the compatible type should be able to cast to
    // the supplied type. In the example above the function will attempt to find a type
    // that can cast to a number, and that can be casted to from a boolean.
    findCompatiblePortType(connections) {
        const _this = this;
        // Returns true if all types are castable in the
        // correct direction
        function isCompatible(type) {
            for (const i in connections) {
                const c = connections[i];
                const from = c.direction === 'from' ? c.type : type;
                const to = c.direction === 'to' ? c.type : type;
                if (!_this.canCastPortTypes(from, to))
                    return false;
            }
            return true;
        }
        // Merges modifiers for all types
        function mergeModifiers(types) {
            const merged = {};
            // Merge enums
            let enums = [];
            external_underscore_default().each(types, function (t) {
                if (t.enums)
                    enums = external_underscore_default().union(enums, t.enums);
            });
            merged.enums = enums.length > 0 ? enums : undefined;
            // Merge other modifiers
            external_underscore_default().each(types, function (t) {
                merged.multiline = merged.multiline || t.multiline;
                merged.allowConnectionsOnly = merged.allowConnectionsOnly || t.allowConnectionsOnly;
                merged.allowEditOnly = merged.allowEditOnly || t.allowEditOnly;
            });
            for (const i in merged)
                if (merged[i] === undefined)
                    delete merged[i]; // Delete undefined
            return merged;
        }
        if (external_underscore_default().every(connections, function (c) {
            return NodeLibrary.nameForPortType(c.type) === NodeLibrary.nameForPortType(connections[0].type);
        })) {
            // All ports have the same type, return a merged type
            return external_underscore_default().extend({ name: NodeLibrary.nameForPortType(connections[0].type) }, mergeModifiers(external_underscore_default().pluck(connections, 'type')));
        }
        else {
            const explicitTypeConnections = connections.filter(function (c) {
                return NodeLibrary.nameForPortType(c.type) !== '*';
            });
            if (explicitTypeConnections.length === 1)
                return explicitTypeConnections[0].type;
            // Iterate over all possible typecasts until a match that
            // supports all connections are found
            for (const i in this.library.typecasts) {
                const type = this.library.typecasts[i].from;
                if (isCompatible(type))
                    return external_underscore_default().extend({ name: type }, mergeModifiers(external_underscore_default().pluck(connections, 'type')));
            }
        }
    }
    // Project settings template from node library
    getProjectSettingsPorts() {
        return this.library.projectsettings || {};
    }
    applyPortConditionsFilterForNode(node, modes) {
        if (!node.type.dynamicports)
            return [];
        // Allow dynamic ports to be used in multiple conditions
        const ports = {};
        for (const i in node.type.dynamicports) {
            const ref = node.type.dynamicports[i];
            if (ref.name.startsWith('conditionalports/') &&
                (modes === undefined || modes.indexOf(ref.name.split('/')[1]) !== -1)) {
                if (!evaluateDynamicPortsCondition(ref.condition, node)) {
                    // Condition failed, these ports should be removed
                    ref.ports.forEach((p) => {
                        if (ports[p.name] === undefined) {
                            ports[p.name] = true;
                        }
                    });
                }
                else {
                    ref.ports.forEach((p) => {
                        ports[p.name] = false;
                    });
                }
            }
        }
        return Object.keys(ports).filter((key) => ports[key]);
    }
    isConditionalPortValid(node, portname, modes) {
        if (!node.type.dynamicports)
            return true;
        for (const i in node.type.dynamicports) {
            const ref = node.type.dynamicports[i];
            if (ref.name.startsWith('conditionalports/') &&
                (modes === undefined || modes.indexOf(ref.name.split('/')[1]) !== -1)) {
                if (ref.ports.find((p) => p.name === portname) !== undefined) {
                    return evaluateDynamicPortsCondition(ref.condition, node);
                }
            }
        }
        return true;
    }
    canPortHaveTransition(port) {
        function _typename() {
            return typeof port.type === 'object' ? port.type.name : port.type;
        }
        if (port === undefined)
            return false;
        return _typename() === 'color' || _typename() === 'number' || _typename() === 'dimension';
    }
}
NodeLibrary.instance = new NodeLibrary();


/***/ }),

/***/ 15601:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   T: () => (/* binding */ extractNumber)
/* harmony export */ });
function extractNumber(string) {
    return parseFloat(string.replace(/[^\d.-]/g, ''));
}


/***/ }),

/***/ 15618:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  CancellationTokenSource: () => (/* reexport */ editor_api_CancellationTokenSource),
  Emitter: () => (/* reexport */ editor_api_Emitter),
  KeyCode: () => (/* reexport */ editor_api_KeyCode),
  KeyMod: () => (/* reexport */ editor_api_KeyMod),
  MarkerSeverity: () => (/* reexport */ editor_api_MarkerSeverity),
  MarkerTag: () => (/* reexport */ editor_api_MarkerTag),
  Position: () => (/* reexport */ editor_api_Position),
  Range: () => (/* reexport */ editor_api_Range),
  Selection: () => (/* reexport */ editor_api_Selection),
  SelectionDirection: () => (/* reexport */ editor_api_SelectionDirection),
  Token: () => (/* reexport */ editor_api_Token),
  Uri: () => (/* reexport */ editor_api_Uri),
  "default": () => (/* binding */ editor_api),
  editor: () => (/* reexport */ editor_api_editor),
  languages: () => (/* reexport */ languages)
});

// NAMESPACE OBJECT: ../../node_modules/monaco-editor/esm/vs/base/browser/browser.js
var browser_namespaceObject = {};
__webpack_require__.r(browser_namespaceObject);
__webpack_require__.d(browser_namespaceObject, {
  PixelRatio: () => (PixelRatio),
  addMatchMediaChangeListener: () => (addMatchMediaChangeListener),
  getZoomFactor: () => (getZoomFactor),
  isAndroid: () => (browser_isAndroid),
  isChrome: () => (browser_isChrome),
  isElectron: () => (isElectron),
  isFirefox: () => (browser_isFirefox),
  isSafari: () => (browser_isSafari),
  isStandalone: () => (isStandalone),
  isWebKit: () => (isWebKit),
  isWebkitWebView: () => (isWebkitWebView)
});

// NAMESPACE OBJECT: ../../node_modules/monaco-editor/esm/vs/editor/editor.api.js
var editor_api_namespaceObject = {};
__webpack_require__.r(editor_api_namespaceObject);
__webpack_require__.d(editor_api_namespaceObject, {
  CancellationTokenSource: () => (editor_api_CancellationTokenSource),
  Emitter: () => (editor_api_Emitter),
  KeyCode: () => (editor_api_KeyCode),
  KeyMod: () => (editor_api_KeyMod),
  MarkerSeverity: () => (editor_api_MarkerSeverity),
  MarkerTag: () => (editor_api_MarkerTag),
  Position: () => (editor_api_Position),
  Range: () => (editor_api_Range),
  Selection: () => (editor_api_Selection),
  SelectionDirection: () => (editor_api_SelectionDirection),
  Token: () => (editor_api_Token),
  Uri: () => (editor_api_Uri),
  editor: () => (editor_api_editor),
  languages: () => (languages)
});

// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp.css
var accessibilityHelp = __webpack_require__(90006);
;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp.css

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(accessibilityHelp/* default */.A, options);




       /* harmony default export */ const accessibilityHelp_accessibilityHelp = (accessibilityHelp/* default */.A && accessibilityHelp/* default */.A.locals ? accessibilityHelp/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/common/errors.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
// Avoid circular dependency on EventEmitter by implementing a subset of the interface.
class ErrorHandler {
    constructor() {
        this.listeners = [];
        this.unexpectedErrorHandler = function (e) {
            setTimeout(() => {
                if (e.stack) {
                    if (ErrorNoTelemetry.isErrorNoTelemetry(e)) {
                        throw new ErrorNoTelemetry(e.message + '\n\n' + e.stack);
                    }
                    throw new Error(e.message + '\n\n' + e.stack);
                }
                throw e;
            }, 0);
        };
    }
    emit(e) {
        this.listeners.forEach((listener) => {
            listener(e);
        });
    }
    onUnexpectedError(e) {
        this.unexpectedErrorHandler(e);
        this.emit(e);
    }
    // For external errors, we don't want the listeners to be called
    onUnexpectedExternalError(e) {
        this.unexpectedErrorHandler(e);
    }
}
const errorHandler = new ErrorHandler();
function onUnexpectedError(e) {
    // ignore errors from cancelled promises
    if (!isCancellationError(e)) {
        errorHandler.onUnexpectedError(e);
    }
    return undefined;
}
function onUnexpectedExternalError(e) {
    // ignore errors from cancelled promises
    if (!isCancellationError(e)) {
        errorHandler.onUnexpectedExternalError(e);
    }
    return undefined;
}
function transformErrorForSerialization(error) {
    if (error instanceof Error) {
        const { name, message } = error;
        const stack = error.stacktrace || error.stack;
        return {
            $isError: true,
            name,
            message,
            stack,
            noTelemetry: ErrorNoTelemetry.isErrorNoTelemetry(error)
        };
    }
    // return as is
    return error;
}
const canceledName = 'Canceled';
/**
 * Checks if the given error is a promise in canceled state
 */
function isCancellationError(error) {
    if (error instanceof CancellationError) {
        return true;
    }
    return error instanceof Error && error.name === canceledName && error.message === canceledName;
}
// !!!IMPORTANT!!!
// Do NOT change this class because it is also used as an API-type.
class CancellationError extends Error {
    constructor() {
        super(canceledName);
        this.name = this.message;
    }
}
/**
 * @deprecated use {@link CancellationError `new CancellationError()`} instead
 */
function canceled() {
    const error = new Error(canceledName);
    error.name = error.message;
    return error;
}
function illegalArgument(name) {
    if (name) {
        return new Error(`Illegal argument: ${name}`);
    }
    else {
        return new Error('Illegal argument');
    }
}
function illegalState(name) {
    if (name) {
        return new Error(`Illegal state: ${name}`);
    }
    else {
        return new Error('Illegal state');
    }
}
class NotSupportedError extends Error {
    constructor(message) {
        super('NotSupported');
        if (message) {
            this.message = message;
        }
    }
}
/**
 * Error that when thrown won't be logged in telemetry as an unhandled error.
 */
class ErrorNoTelemetry extends Error {
    constructor(msg) {
        super(msg);
        this.name = 'ErrorNoTelemetry';
    }
    static fromError(err) {
        if (err instanceof ErrorNoTelemetry) {
            return err;
        }
        const result = new ErrorNoTelemetry();
        result.message = err.message;
        result.stack = err.stack;
        return result;
    }
    static isErrorNoTelemetry(err) {
        return err.name === 'ErrorNoTelemetry';
    }
}
/**
 * This error indicates a bug.
 * Do not throw this for invalid user input.
 * Only catch this error to recover gracefully from bugs.
 */
class BugIndicatingError extends Error {
    constructor(message) {
        super(message || 'An unexpected bug occurred.');
        Object.setPrototypeOf(this, BugIndicatingError.prototype);
        // Because we know for sure only buggy code throws this,
        // we definitely want to break here and fix the bug.
        // eslint-disable-next-line no-debugger
        debugger;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/functional.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
function once(fn) {
    const _this = this;
    let didCall = false;
    let result;
    return function () {
        if (didCall) {
            return result;
        }
        didCall = true;
        result = fn.apply(_this, arguments);
        return result;
    };
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/iterator.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var Iterable;
(function (Iterable) {
    function is(thing) {
        return thing && typeof thing === 'object' && typeof thing[Symbol.iterator] === 'function';
    }
    Iterable.is = is;
    const _empty = Object.freeze([]);
    function empty() {
        return _empty;
    }
    Iterable.empty = empty;
    function* single(element) {
        yield element;
    }
    Iterable.single = single;
    function from(iterable) {
        return iterable || _empty;
    }
    Iterable.from = from;
    function isEmpty(iterable) {
        return !iterable || iterable[Symbol.iterator]().next().done === true;
    }
    Iterable.isEmpty = isEmpty;
    function first(iterable) {
        return iterable[Symbol.iterator]().next().value;
    }
    Iterable.first = first;
    function some(iterable, predicate) {
        for (const element of iterable) {
            if (predicate(element)) {
                return true;
            }
        }
        return false;
    }
    Iterable.some = some;
    function find(iterable, predicate) {
        for (const element of iterable) {
            if (predicate(element)) {
                return element;
            }
        }
        return undefined;
    }
    Iterable.find = find;
    function* filter(iterable, predicate) {
        for (const element of iterable) {
            if (predicate(element)) {
                yield element;
            }
        }
    }
    Iterable.filter = filter;
    function* map(iterable, fn) {
        let index = 0;
        for (const element of iterable) {
            yield fn(element, index++);
        }
    }
    Iterable.map = map;
    function* concat(...iterables) {
        for (const iterable of iterables) {
            for (const element of iterable) {
                yield element;
            }
        }
    }
    Iterable.concat = concat;
    function* concatNested(iterables) {
        for (const iterable of iterables) {
            for (const element of iterable) {
                yield element;
            }
        }
    }
    Iterable.concatNested = concatNested;
    function reduce(iterable, reducer, initialValue) {
        let value = initialValue;
        for (const element of iterable) {
            value = reducer(value, element);
        }
        return value;
    }
    Iterable.reduce = reduce;
    function forEach(iterable, fn) {
        let index = 0;
        for (const element of iterable) {
            fn(element, index++);
        }
    }
    Iterable.forEach = forEach;
    /**
     * Returns an iterable slice of the array, with the same semantics as `array.slice()`.
     */
    function* slice(arr, from, to = arr.length) {
        if (from < 0) {
            from += arr.length;
        }
        if (to < 0) {
            to += arr.length;
        }
        else if (to > arr.length) {
            to = arr.length;
        }
        for (; from < to; from++) {
            yield arr[from];
        }
    }
    Iterable.slice = slice;
    /**
     * Consumes `atMost` elements from iterable and returns the consumed elements,
     * and an iterable for the rest of the elements.
     */
    function consume(iterable, atMost = Number.POSITIVE_INFINITY) {
        const consumed = [];
        if (atMost === 0) {
            return [consumed, iterable];
        }
        const iterator = iterable[Symbol.iterator]();
        for (let i = 0; i < atMost; i++) {
            const next = iterator.next();
            if (next.done) {
                return [consumed, Iterable.empty()];
            }
            consumed.push(next.value);
        }
        return [consumed, { [Symbol.iterator]() { return iterator; } }];
    }
    Iterable.consume = consume;
    /**
     * Consumes `atMost` elements from iterable and returns the consumed elements,
     * and an iterable for the rest of the elements.
     */
    function collect(iterable) {
        return consume(iterable)[0];
    }
    Iterable.collect = collect;
    /**
     * Returns whether the iterables are the same length and all items are
     * equal using the comparator function.
     */
    function equals(a, b, comparator = (at, bt) => at === bt) {
        const ai = a[Symbol.iterator]();
        const bi = b[Symbol.iterator]();
        while (true) {
            const an = ai.next();
            const bn = bi.next();
            if (an.done !== bn.done) {
                return false;
            }
            else if (an.done) {
                return true;
            }
            else if (!comparator(an.value, bn.value)) {
                return false;
            }
        }
    }
    Iterable.equals = equals;
})(Iterable || (Iterable = {}));

;// ../../node_modules/monaco-editor/esm/vs/base/common/lifecycle.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


/**
 * Enables logging of potentially leaked disposables.
 *
 * A disposable is considered leaked if it is not disposed or not registered as the child of
 * another disposable. This tracking is very simple an only works for classes that either
 * extend Disposable or use a DisposableStore. This means there are a lot of false positives.
 */
const TRACK_DISPOSABLES = false;
let disposableTracker = null;
function setDisposableTracker(tracker) {
    disposableTracker = tracker;
}
if (TRACK_DISPOSABLES) {
    const __is_disposable_tracked__ = '__is_disposable_tracked__';
    setDisposableTracker(new class {
        trackDisposable(x) {
            const stack = new Error('Potentially leaked disposable').stack;
            setTimeout(() => {
                if (!x[__is_disposable_tracked__]) {
                    console.log(stack);
                }
            }, 3000);
        }
        setParent(child, parent) {
            if (child && child !== Disposable.None) {
                try {
                    child[__is_disposable_tracked__] = true;
                }
                catch (_a) {
                    // noop
                }
            }
        }
        markAsDisposed(disposable) {
            if (disposable && disposable !== Disposable.None) {
                try {
                    disposable[__is_disposable_tracked__] = true;
                }
                catch (_a) {
                    // noop
                }
            }
        }
        markAsSingleton(disposable) { }
    });
}
function trackDisposable(x) {
    disposableTracker === null || disposableTracker === void 0 ? void 0 : disposableTracker.trackDisposable(x);
    return x;
}
function markAsDisposed(disposable) {
    disposableTracker === null || disposableTracker === void 0 ? void 0 : disposableTracker.markAsDisposed(disposable);
}
function setParentOfDisposable(child, parent) {
    disposableTracker === null || disposableTracker === void 0 ? void 0 : disposableTracker.setParent(child, parent);
}
function setParentOfDisposables(children, parent) {
    if (!disposableTracker) {
        return;
    }
    for (const child of children) {
        disposableTracker.setParent(child, parent);
    }
}
/**
 * Indicates that the given object is a singleton which does not need to be disposed.
*/
function markAsSingleton(singleton) {
    disposableTracker === null || disposableTracker === void 0 ? void 0 : disposableTracker.markAsSingleton(singleton);
    return singleton;
}
class MultiDisposeError extends Error {
    constructor(errors) {
        super(`Encountered errors while disposing of store. Errors: [${errors.join(', ')}]`);
        this.errors = errors;
    }
}
function isDisposable(thing) {
    return typeof thing.dispose === 'function' && thing.dispose.length === 0;
}
function dispose(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 MultiDisposeError(errors);
        }
        return Array.isArray(arg) ? [] : arg;
    }
    else if (arg) {
        arg.dispose();
        return arg;
    }
}
function combinedDisposable(...disposables) {
    const parent = toDisposable(() => dispose(disposables));
    setParentOfDisposables(disposables, parent);
    return parent;
}
function toDisposable(fn) {
    const self = trackDisposable({
        dispose: once(() => {
            markAsDisposed(self);
            fn();
        })
    });
    return self;
}
class DisposableStore {
    constructor() {
        this._toDispose = new Set();
        this._isDisposed = false;
        trackDisposable(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._isDisposed) {
            return;
        }
        markAsDisposed(this);
        this._isDisposed = true;
        this.clear();
    }
    /**
     * Returns `true` if this object has been disposed
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of all registered disposables but do not mark this object as disposed.
     */
    clear() {
        try {
            dispose(this._toDispose.values());
        }
        finally {
            this._toDispose.clear();
        }
    }
    add(o) {
        if (!o) {
            return o;
        }
        if (o === this) {
            throw new Error('Cannot register a disposable on itself!');
        }
        setParentOfDisposable(o, this);
        if (this._isDisposed) {
            if (!DisposableStore.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._toDispose.add(o);
        }
        return o;
    }
}
DisposableStore.DISABLE_DISPOSED_WARNING = false;
class Disposable {
    constructor() {
        this._store = new DisposableStore();
        trackDisposable(this);
        setParentOfDisposable(this._store, this);
    }
    dispose() {
        markAsDisposed(this);
        this._store.dispose();
    }
    _register(o) {
        if (o === this) {
            throw new Error('Cannot register a disposable on itself!');
        }
        return this._store.add(o);
    }
}
Disposable.None = Object.freeze({ dispose() { } });
/**
 * Manages the lifecycle of a disposable value that may be changed.
 *
 * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can
 * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up.
 */
class MutableDisposable {
    constructor() {
        this._isDisposed = false;
        trackDisposable(this);
    }
    get value() {
        return this._isDisposed ? undefined : this._value;
    }
    set value(value) {
        var _a;
        if (this._isDisposed || value === this._value) {
            return;
        }
        (_a = this._value) === null || _a === void 0 ? void 0 : _a.dispose();
        if (value) {
            setParentOfDisposable(value, this);
        }
        this._value = value;
    }
    clear() {
        this.value = undefined;
    }
    dispose() {
        var _a;
        this._isDisposed = true;
        markAsDisposed(this);
        (_a = this._value) === null || _a === void 0 ? void 0 : _a.dispose();
        this._value = undefined;
    }
    /**
     * Clears the value, but does not dispose it.
     * The old value is returned.
    */
    clearAndLeak() {
        const oldValue = this._value;
        this._value = undefined;
        if (oldValue) {
            setParentOfDisposable(oldValue, null);
        }
        return oldValue;
    }
}
class RefCountedDisposable {
    constructor(_disposable) {
        this._disposable = _disposable;
        this._counter = 1;
    }
    acquire() {
        this._counter++;
        return this;
    }
    release() {
        if (--this._counter === 0) {
            this._disposable.dispose();
        }
        return this;
    }
}
/**
 * A safe disposable can be `unset` so that a leaked reference (listener)
 * can be cut-off.
 */
class SafeDisposable {
    constructor() {
        this.dispose = () => { };
        this.unset = () => { };
        this.isset = () => false;
        trackDisposable(this);
    }
    set(fn) {
        let callback = fn;
        this.unset = () => callback = undefined;
        this.isset = () => callback !== undefined;
        this.dispose = () => {
            if (callback) {
                callback();
                callback = undefined;
                markAsDisposed(this);
            }
        };
        return this;
    }
}
class ImmortalReference {
    constructor(object) {
        this.object = object;
    }
    dispose() { }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/linkedList.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class linkedList_Node {
    constructor(element) {
        this.element = element;
        this.next = linkedList_Node.Undefined;
        this.prev = linkedList_Node.Undefined;
    }
}
linkedList_Node.Undefined = new linkedList_Node(undefined);
class LinkedList {
    constructor() {
        this._first = linkedList_Node.Undefined;
        this._last = linkedList_Node.Undefined;
        this._size = 0;
    }
    get size() {
        return this._size;
    }
    isEmpty() {
        return this._first === linkedList_Node.Undefined;
    }
    clear() {
        let node = this._first;
        while (node !== linkedList_Node.Undefined) {
            const next = node.next;
            node.prev = linkedList_Node.Undefined;
            node.next = linkedList_Node.Undefined;
            node = next;
        }
        this._first = linkedList_Node.Undefined;
        this._last = linkedList_Node.Undefined;
        this._size = 0;
    }
    unshift(element) {
        return this._insert(element, false);
    }
    push(element) {
        return this._insert(element, true);
    }
    _insert(element, atTheEnd) {
        const newNode = new linkedList_Node(element);
        if (this._first === linkedList_Node.Undefined) {
            this._first = newNode;
            this._last = newNode;
        }
        else if (atTheEnd) {
            // push
            const oldLast = this._last;
            this._last = newNode;
            newNode.prev = oldLast;
            oldLast.next = newNode;
        }
        else {
            // unshift
            const oldFirst = this._first;
            this._first = newNode;
            newNode.next = oldFirst;
            oldFirst.prev = newNode;
        }
        this._size += 1;
        let didRemove = false;
        return () => {
            if (!didRemove) {
                didRemove = true;
                this._remove(newNode);
            }
        };
    }
    shift() {
        if (this._first === linkedList_Node.Undefined) {
            return undefined;
        }
        else {
            const res = this._first.element;
            this._remove(this._first);
            return res;
        }
    }
    pop() {
        if (this._last === linkedList_Node.Undefined) {
            return undefined;
        }
        else {
            const res = this._last.element;
            this._remove(this._last);
            return res;
        }
    }
    _remove(node) {
        if (node.prev !== linkedList_Node.Undefined && node.next !== linkedList_Node.Undefined) {
            // middle
            const anchor = node.prev;
            anchor.next = node.next;
            node.next.prev = anchor;
        }
        else if (node.prev === linkedList_Node.Undefined && node.next === linkedList_Node.Undefined) {
            // only node
            this._first = linkedList_Node.Undefined;
            this._last = linkedList_Node.Undefined;
        }
        else if (node.next === linkedList_Node.Undefined) {
            // last
            this._last = this._last.prev;
            this._last.next = linkedList_Node.Undefined;
        }
        else if (node.prev === linkedList_Node.Undefined) {
            // first
            this._first = this._first.next;
            this._first.prev = linkedList_Node.Undefined;
        }
        // done
        this._size -= 1;
    }
    *[Symbol.iterator]() {
        let node = this._first;
        while (node !== linkedList_Node.Undefined) {
            yield node.element;
            node = node.next;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/nls.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var __awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
let isPseudo = (typeof document !== 'undefined' && document.location && document.location.hash.indexOf('pseudo=true') >= 0);
const DEFAULT_TAG = 'i-default';
function _format(message, args) {
    let result;
    if (args.length === 0) {
        result = message;
    }
    else {
        result = message.replace(/\{(\d+)\}/g, (match, rest) => {
            const index = rest[0];
            const arg = args[index];
            let result = match;
            if (typeof arg === 'string') {
                result = arg;
            }
            else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) {
                result = String(arg);
            }
            return result;
        });
    }
    if (isPseudo) {
        // FF3B and FF3D is the Unicode zenkaku representation for [ and ]
        result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D';
    }
    return result;
}
function findLanguageForModule(config, name) {
    let result = config[name];
    if (result) {
        return result;
    }
    result = config['*'];
    if (result) {
        return result;
    }
    return null;
}
function endWithSlash(path) {
    if (path.charAt(path.length - 1) === '/') {
        return path;
    }
    return path + '/';
}
function getMessagesFromTranslationsService(translationServiceUrl, language, name) {
    return __awaiter(this, void 0, void 0, function* () {
        const url = endWithSlash(translationServiceUrl) + endWithSlash(language) + 'vscode/' + endWithSlash(name);
        const res = yield fetch(url);
        if (res.ok) {
            const messages = yield res.json();
            return messages;
        }
        throw new Error(`${res.status} - ${res.statusText}`);
    });
}
function createScopedLocalize(scope) {
    return function (idx, defaultValue) {
        const restArgs = Array.prototype.slice.call(arguments, 2);
        return _format(scope[idx], restArgs);
    };
}
function localize(data, message, ...args) {
    return _format(message, args);
}
function getConfiguredDefaultLocale(_) {
    // This returns undefined because this implementation isn't used and is overwritten by the loader
    // when loaded.
    return undefined;
}
function setPseudoTranslation(value) {
    isPseudo = value;
}
/**
 * Invoked in a built product at run-time
 */
function create(key, data) {
    var _a;
    return {
        localize: createScopedLocalize(data[key]),
        getConfiguredDefaultLocale: (_a = data.getConfiguredDefaultLocale) !== null && _a !== void 0 ? _a : ((_) => undefined)
    };
}
/**
 * Invoked by the loader at run-time
 */
function load(name, req, load, config) {
    var _a;
    const pluginConfig = (_a = config['vs/nls']) !== null && _a !== void 0 ? _a : {};
    if (!name || name.length === 0) {
        return load({
            localize: localize,
            getConfiguredDefaultLocale: () => { var _a; return (_a = pluginConfig.availableLanguages) === null || _a === void 0 ? void 0 : _a['*']; }
        });
    }
    const language = pluginConfig.availableLanguages ? findLanguageForModule(pluginConfig.availableLanguages, name) : null;
    const useDefaultLanguage = language === null || language === DEFAULT_TAG;
    let suffix = '.nls';
    if (!useDefaultLanguage) {
        suffix = suffix + '.' + language;
    }
    const messagesLoaded = (messages) => {
        if (Array.isArray(messages)) {
            messages.localize = createScopedLocalize(messages);
        }
        else {
            messages.localize = createScopedLocalize(messages[name]);
        }
        messages.getConfiguredDefaultLocale = () => { var _a; return (_a = pluginConfig.availableLanguages) === null || _a === void 0 ? void 0 : _a['*']; };
        load(messages);
    };
    if (typeof pluginConfig.loadBundle === 'function') {
        pluginConfig.loadBundle(name, language, (err, messages) => {
            // We have an error. Load the English default strings to not fail
            if (err) {
                req([name + '.nls'], messagesLoaded);
            }
            else {
                messagesLoaded(messages);
            }
        });
    }
    else if (pluginConfig.translationServiceUrl && !useDefaultLanguage) {
        (() => __awaiter(this, void 0, void 0, function* () {
            var _b;
            try {
                const messages = yield getMessagesFromTranslationsService(pluginConfig.translationServiceUrl, language, name);
                return messagesLoaded(messages);
            }
            catch (err) {
                // Language is already as generic as it gets, so require default messages
                if (!language.includes('-')) {
                    console.error(err);
                    return req([name + '.nls'], messagesLoaded);
                }
                try {
                    // Since there is a dash, the language configured is a specific sub-language of the same generic language.
                    // Since we were unable to load the specific language, try to load the generic language. Ex. we failed to find a
                    // Swiss German (de-CH), so try to load the generic German (de) messages instead.
                    const genericLanguage = language.split('-')[0];
                    const messages = yield getMessagesFromTranslationsService(pluginConfig.translationServiceUrl, genericLanguage, name);
                    // We got some messages, so we configure the configuration to use the generic language for this session.
                    (_b = pluginConfig.availableLanguages) !== null && _b !== void 0 ? _b : (pluginConfig.availableLanguages = {});
                    pluginConfig.availableLanguages['*'] = genericLanguage;
                    return messagesLoaded(messages);
                }
                catch (err) {
                    console.error(err);
                    return req([name + '.nls'], messagesLoaded);
                }
            }
        }))();
    }
    else {
        req([name + suffix], messagesLoaded, (err) => {
            if (suffix === '.nls') {
                console.error('Failed trying to load default language strings', err);
                return;
            }
            console.error(`Failed to load message bundle for language ${language}. Falling back to the default language:`, err);
            req([name + '.nls'], messagesLoaded);
        });
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/platform.js
var _a;
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const LANGUAGE_DEFAULT = 'en';
let _isWindows = false;
let _isMacintosh = false;
let _isLinux = false;
let _isLinuxSnap = false;
let _isNative = false;
let _isWeb = false;
let _isElectron = false;
let _isIOS = false;
let _isCI = false;
let _locale = undefined;
let _language = LANGUAGE_DEFAULT;
let _translationsConfigFile = (/* unused pure expression or super */ null && (undefined));
let _userAgent = undefined;
const platform_globals = (typeof self === 'object' ? self : typeof global === 'object' ? global : {});
let nodeProcess = undefined;
if (typeof platform_globals.vscode !== 'undefined' && typeof platform_globals.vscode.process !== 'undefined') {
    // Native environment (sandboxed)
    nodeProcess = platform_globals.vscode.process;
}
else if (typeof process !== 'undefined') {
    // Native environment (non-sandboxed)
    nodeProcess = process;
}
const isElectronProcess = typeof ((_a = nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.versions) === null || _a === void 0 ? void 0 : _a.electron) === 'string';
const isElectronRenderer = isElectronProcess && (nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.type) === 'renderer';
// Web environment
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;
    _isWeb = true;
    const configuredLocale = getConfiguredDefaultLocale(
    // This call _must_ be done in the file that calls `nls.getConfiguredDefaultLocale`
    // to ensure that the NLS AMD Loader plugin has been loaded and configured.
    // This is because the loader plugin decides what the default locale is based on
    // how it's able to resolve the strings.
    localize({ key: 'ensureLoaderPluginIsLoaded', comment: ['{Locked}'] }, '_'));
    _locale = configuredLocale || LANGUAGE_DEFAULT;
    _language = _locale;
}
// Native environment
else 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 = LANGUAGE_DEFAULT;
    _language = LANGUAGE_DEFAULT;
    const rawNlsConfig = nodeProcess.env['VSCODE_NLS_CONFIG'];
    if (rawNlsConfig) {
        try {
            const nlsConfig = JSON.parse(rawNlsConfig);
            const resolved = nlsConfig.availableLanguages['*'];
            _locale = nlsConfig.locale;
            // VSCode's default language is 'en'
            _language = resolved ? resolved : LANGUAGE_DEFAULT;
            _translationsConfigFile = nlsConfig._translationsConfigFile;
        }
        catch (e) {
        }
    }
    _isNative = true;
}
// Unknown environment
else {
    console.error('Unable to resolve platform.');
}
let _platform = 0 /* Platform.Web */;
if (_isMacintosh) {
    _platform = 1 /* Platform.Mac */;
}
else if (_isWindows) {
    _platform = 3 /* Platform.Windows */;
}
else if (_isLinux) {
    _platform = 2 /* Platform.Linux */;
}
const isWindows = _isWindows;
const isMacintosh = _isMacintosh;
const isLinux = _isLinux;
const isNative = _isNative;
const isWeb = _isWeb;
const isWebWorker = (_isWeb && typeof platform_globals.importScripts === 'function');
const isIOS = _isIOS;
const userAgent = _userAgent;
/**
 * The language used for the user interface. The format of
 * the string is all lower case (e.g. zh-tw for Traditional
 * Chinese)
 */
const language = _language;
const setTimeout0IsFaster = (typeof platform_globals.postMessage === 'function' && !platform_globals.importScripts);
/**
 * See https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#:~:text=than%204%2C%20then-,set%20timeout%20to%204,-.
 *
 * Works similarly to `setTimeout(0)` but doesn't suffer from the 4ms artificial delay
 * that browsers set when the nesting level is > 5.
 */
const setTimeout0 = (() => {
    if (setTimeout0IsFaster) {
        const pending = [];
        platform_globals.addEventListener('message', (e) => {
            if (e.data && e.data.vscodeScheduleAsyncWork) {
                for (let i = 0, len = pending.length; i < len; i++) {
                    const candidate = pending[i];
                    if (candidate.id === e.data.vscodeScheduleAsyncWork) {
                        pending.splice(i, 1);
                        candidate.callback();
                        return;
                    }
                }
            }
        });
        let lastId = 0;
        return (callback) => {
            const myId = ++lastId;
            pending.push({
                id: myId,
                callback: callback
            });
            platform_globals.postMessage({ vscodeScheduleAsyncWork: myId }, '*');
        };
    }
    return (callback) => setTimeout(callback);
})();
const OS = (_isMacintosh || _isIOS ? 2 /* OperatingSystem.Macintosh */ : (_isWindows ? 1 /* OperatingSystem.Windows */ : 3 /* OperatingSystem.Linux */));
let _isLittleEndian = true;
let _isLittleEndianComputed = false;
function isLittleEndian() {
    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;
}
const isChrome = !!(userAgent && userAgent.indexOf('Chrome') >= 0);
const isFirefox = !!(userAgent && userAgent.indexOf('Firefox') >= 0);
const isSafari = !!(!isChrome && (userAgent && userAgent.indexOf('Safari') >= 0));
const isEdge = !!(userAgent && userAgent.indexOf('Edg/') >= 0);
const isAndroid = !!(userAgent && userAgent.indexOf('Android') >= 0);

;// ../../node_modules/monaco-editor/esm/vs/base/common/stopwatch.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const hasPerformanceNow = (platform_globals.performance && typeof platform_globals.performance.now === 'function');
class StopWatch {
    constructor(highResolution) {
        this._highResolution = hasPerformanceNow && highResolution;
        this._startTime = this._now();
        this._stopTime = -1;
    }
    static create(highResolution = true) {
        return new StopWatch(highResolution);
    }
    stop() {
        this._stopTime = this._now();
    }
    elapsed() {
        if (this._stopTime !== -1) {
            return this._stopTime - this._startTime;
        }
        return this._now() - this._startTime;
    }
    _now() {
        return this._highResolution ? platform_globals.performance.now() : Date.now();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/event.js




// -----------------------------------------------------------------------------------------------------------------------
// Uncomment the next line to print warnings whenever an emitter with listeners is disposed. That is a sign of code smell.
// -----------------------------------------------------------------------------------------------------------------------
const _enableDisposeWithListenerWarning = false;
// _enableDisposeWithListenerWarning = Boolean("TRUE"); // causes a linter warning so that it cannot be pushed
// -----------------------------------------------------------------------------------------------------------------------
// Uncomment the next line to print warnings whenever a snapshotted event is used repeatedly without cleanup.
// See https://github.com/microsoft/vscode/issues/142851
// -----------------------------------------------------------------------------------------------------------------------
const _enableSnapshotPotentialLeakWarning = false;
var Event;
(function (Event) {
    Event.None = () => Disposable.None;
    function _addLeakageTraceLogic(options) {
        if (_enableSnapshotPotentialLeakWarning) {
            const { onListenerDidAdd: origListenerDidAdd } = options;
            const stack = Stacktrace.create();
            let count = 0;
            options.onListenerDidAdd = () => {
                if (++count === 2) {
                    console.warn('snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here');
                    stack.print();
                }
                origListenerDidAdd === null || origListenerDidAdd === void 0 ? void 0 : origListenerDidAdd();
            };
        }
    }
    /**
     * Given an event, returns another event which only fires once.
     */
    function once(event) {
        return (listener, thisArgs = null, disposables) => {
            // we need this, in case the event fires during the listener call
            let didFire = false;
            let result = undefined;
            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;
        };
    }
    Event.once = once;
    /**
     * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
     * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
     * returned event causes this utility to leak a listener on the original event.
     */
    function map(event, map, disposable) {
        return snapshot((listener, thisArgs = null, disposables) => event(i => listener.call(thisArgs, map(i)), null, disposables), disposable);
    }
    Event.map = map;
    /**
     * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
     * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
     * returned event causes this utility to leak a listener on the original event.
     */
    function forEach(event, each, disposable) {
        return snapshot((listener, thisArgs = null, disposables) => event(i => { each(i); listener.call(thisArgs, i); }, null, disposables), disposable);
    }
    Event.forEach = forEach;
    function filter(event, filter, disposable) {
        return snapshot((listener, thisArgs = null, disposables) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables), disposable);
    }
    Event.filter = filter;
    /**
     * Given an event, returns the same event but typed as `Event<void>`.
     */
    function signal(event) {
        return event;
    }
    Event.signal = signal;
    function any(...events) {
        return (listener, thisArgs = null, disposables) => combinedDisposable(...events.map(event => event(e => listener.call(thisArgs, e), null, disposables)));
    }
    Event.any = any;
    /**
     * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
     * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
     * returned event causes this utility to leak a listener on the original event.
     */
    function reduce(event, merge, initial, disposable) {
        let output = initial;
        return map(event, e => {
            output = merge(output, e);
            return output;
        }, disposable);
    }
    Event.reduce = reduce;
    function snapshot(event, disposable) {
        let listener;
        const options = {
            onFirstListenerAdd() {
                listener = event(emitter.fire, emitter);
            },
            onLastListenerRemove() {
                listener === null || listener === void 0 ? void 0 : listener.dispose();
            }
        };
        if (!disposable) {
            _addLeakageTraceLogic(options);
        }
        const emitter = new Emitter(options);
        disposable === null || disposable === void 0 ? void 0 : disposable.add(emitter);
        return emitter.event;
    }
    function debounce(event, merge, delay = 100, leading = false, leakWarningThreshold, disposable) {
        let subscription;
        let output = undefined;
        let handle = undefined;
        let numDebouncedCalls = 0;
        const options = {
            leakWarningThreshold,
            onFirstListenerAdd() {
                subscription = event(cur => {
                    numDebouncedCalls++;
                    output = merge(output, cur);
                    if (leading && !handle) {
                        emitter.fire(output);
                        output = undefined;
                    }
                    clearTimeout(handle);
                    handle = setTimeout(() => {
                        const _output = output;
                        output = undefined;
                        handle = undefined;
                        if (!leading || numDebouncedCalls > 1) {
                            emitter.fire(_output);
                        }
                        numDebouncedCalls = 0;
                    }, delay);
                });
            },
            onLastListenerRemove() {
                subscription.dispose();
            }
        };
        if (!disposable) {
            _addLeakageTraceLogic(options);
        }
        const emitter = new Emitter(options);
        disposable === null || disposable === void 0 ? void 0 : disposable.add(emitter);
        return emitter.event;
    }
    Event.debounce = debounce;
    /**
     * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
     * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
     * returned event causes this utility to leak a listener on the original event.
     */
    function latch(event, equals = (a, b) => a === b, disposable) {
        let firstCall = true;
        let cache;
        return filter(event, value => {
            const shouldEmit = firstCall || !equals(value, cache);
            firstCall = false;
            cache = value;
            return shouldEmit;
        }, disposable);
    }
    Event.latch = latch;
    /**
     * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
     * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
     * returned event causes this utility to leak a listener on the original event.
     */
    function split(event, isT, disposable) {
        return [
            Event.filter(event, isT, disposable),
            Event.filter(event, e => !isT(e), disposable),
        ];
    }
    Event.split = split;
    /**
     * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
     * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
     * returned event causes this utility to leak a listener on the original event.
     */
    function buffer(event, flushAfterTimeout = false, _buffer = []) {
        let buffer = _buffer.slice();
        let listener = event(e => {
            if (buffer) {
                buffer.push(e);
            }
            else {
                emitter.fire(e);
            }
        });
        const flush = () => {
            buffer === null || buffer === void 0 ? void 0 : buffer.forEach(e => emitter.fire(e));
            buffer = null;
        };
        const emitter = new Emitter({
            onFirstListenerAdd() {
                if (!listener) {
                    listener = event(e => emitter.fire(e));
                }
            },
            onFirstListenerDidAdd() {
                if (buffer) {
                    if (flushAfterTimeout) {
                        setTimeout(flush);
                    }
                    else {
                        flush();
                    }
                }
            },
            onLastListenerRemove() {
                if (listener) {
                    listener.dispose();
                }
                listener = null;
            }
        });
        return emitter.event;
    }
    Event.buffer = buffer;
    class ChainableEvent {
        constructor(event) {
            this.event = event;
            this.disposables = new DisposableStore();
        }
        map(fn) {
            return new ChainableEvent(map(this.event, fn, this.disposables));
        }
        forEach(fn) {
            return new ChainableEvent(forEach(this.event, fn, this.disposables));
        }
        filter(fn) {
            return new ChainableEvent(filter(this.event, fn, this.disposables));
        }
        reduce(merge, initial) {
            return new ChainableEvent(reduce(this.event, merge, initial, this.disposables));
        }
        latch() {
            return new ChainableEvent(latch(this.event, undefined, this.disposables));
        }
        debounce(merge, delay = 100, leading = false, leakWarningThreshold) {
            return new ChainableEvent(debounce(this.event, merge, delay, leading, leakWarningThreshold, this.disposables));
        }
        on(listener, thisArgs, disposables) {
            return this.event(listener, thisArgs, disposables);
        }
        once(listener, thisArgs, disposables) {
            return once(this.event)(listener, thisArgs, disposables);
        }
        dispose() {
            this.disposables.dispose();
        }
    }
    function chain(event) {
        return new ChainableEvent(event);
    }
    Event.chain = chain;
    function fromNodeEventEmitter(emitter, eventName, map = id => id) {
        const fn = (...args) => result.fire(map(...args));
        const onFirstListenerAdd = () => emitter.on(eventName, fn);
        const onLastListenerRemove = () => emitter.removeListener(eventName, fn);
        const result = new Emitter({ onFirstListenerAdd, onLastListenerRemove });
        return result.event;
    }
    Event.fromNodeEventEmitter = fromNodeEventEmitter;
    function fromDOMEventEmitter(emitter, eventName, map = id => id) {
        const fn = (...args) => result.fire(map(...args));
        const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);
        const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn);
        const result = new Emitter({ onFirstListenerAdd, onLastListenerRemove });
        return result.event;
    }
    Event.fromDOMEventEmitter = fromDOMEventEmitter;
    function toPromise(event) {
        return new Promise(resolve => once(event)(resolve));
    }
    Event.toPromise = toPromise;
    function runAndSubscribe(event, handler) {
        handler(undefined);
        return event(e => handler(e));
    }
    Event.runAndSubscribe = runAndSubscribe;
    function runAndSubscribeWithStore(event, handler) {
        let store = null;
        function run(e) {
            store === null || store === void 0 ? void 0 : store.dispose();
            store = new DisposableStore();
            handler(e, store);
        }
        run(undefined);
        const disposable = event(e => run(e));
        return toDisposable(() => {
            disposable.dispose();
            store === null || store === void 0 ? void 0 : store.dispose();
        });
    }
    Event.runAndSubscribeWithStore = runAndSubscribeWithStore;
    class EmitterObserver {
        constructor(obs, store) {
            this.obs = obs;
            this._counter = 0;
            this._hasChanged = false;
            const options = {
                onFirstListenerAdd: () => {
                    obs.addObserver(this);
                },
                onLastListenerRemove: () => {
                    obs.removeObserver(this);
                }
            };
            if (!store) {
                _addLeakageTraceLogic(options);
            }
            this.emitter = new Emitter(options);
            if (store) {
                store.add(this.emitter);
            }
        }
        beginUpdate(_observable) {
            // console.assert(_observable === this.obs);
            this._counter++;
        }
        handleChange(_observable, _change) {
            this._hasChanged = true;
        }
        endUpdate(_observable) {
            if (--this._counter === 0) {
                if (this._hasChanged) {
                    this._hasChanged = false;
                    this.emitter.fire(this.obs.get());
                }
            }
        }
    }
    function fromObservable(obs, store) {
        const observer = new EmitterObserver(obs, store);
        return observer.emitter.event;
    }
    Event.fromObservable = fromObservable;
})(Event || (Event = {}));
class EventProfiling {
    constructor(name) {
        this._listenerCount = 0;
        this._invocationCount = 0;
        this._elapsedOverall = 0;
        this._name = `${name}_${EventProfiling._idPool++}`;
    }
    start(listenerCount) {
        this._stopWatch = new StopWatch(true);
        this._listenerCount = listenerCount;
    }
    stop() {
        if (this._stopWatch) {
            const elapsed = this._stopWatch.elapsed();
            this._elapsedOverall += elapsed;
            this._invocationCount += 1;
            console.info(`did FIRE ${this._name}: elapsed_ms: ${elapsed.toFixed(5)}, listener: ${this._listenerCount} (elapsed_overall: ${this._elapsedOverall.toFixed(2)}, invocations: ${this._invocationCount})`);
            this._stopWatch = undefined;
        }
    }
}
EventProfiling._idPool = 0;
let _globalLeakWarningThreshold = -1;
class LeakageMonitor {
    constructor(customThreshold, name = Math.random().toString(18).slice(2, 5)) {
        this.customThreshold = customThreshold;
        this.name = name;
        this._warnCountdown = 0;
    }
    dispose() {
        if (this._stacks) {
            this._stacks.clear();
        }
    }
    check(stack, listenerCount) {
        let threshold = _globalLeakWarningThreshold;
        if (typeof this.customThreshold === 'number') {
            threshold = this.customThreshold;
        }
        if (threshold <= 0 || listenerCount < threshold) {
            return undefined;
        }
        if (!this._stacks) {
            this._stacks = new Map();
        }
        const count = (this._stacks.get(stack.value) || 0);
        this._stacks.set(stack.value, count + 1);
        this._warnCountdown -= 1;
        if (this._warnCountdown <= 0) {
            // only warn on first exceed and then every time the limit
            // is exceeded by 50% again
            this._warnCountdown = threshold * 0.5;
            // find most frequent listener and print warning
            let topStack;
            let topCount = 0;
            for (const [stack, count] of this._stacks) {
                if (!topStack || topCount < count) {
                    topStack = stack;
                    topCount = count;
                }
            }
            console.warn(`[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`);
            console.warn(topStack);
        }
        return () => {
            const count = (this._stacks.get(stack.value) || 0);
            this._stacks.set(stack.value, count - 1);
        };
    }
}
class Stacktrace {
    constructor(value) {
        this.value = value;
    }
    static create() {
        var _a;
        return new Stacktrace((_a = new Error().stack) !== null && _a !== void 0 ? _a : '');
    }
    print() {
        console.warn(this.value.split('\n').slice(2).join('\n'));
    }
}
class Listener {
    constructor(callback, callbackThis, stack) {
        this.callback = callback;
        this.callbackThis = callbackThis;
        this.stack = stack;
        this.subscription = new SafeDisposable();
    }
    invoke(e) {
        this.callback.call(this.callbackThis, e);
    }
}
/**
 * The Emitter can be used to expose an Event to the public
 * to fire it from the insides.
 * Sample:
    class Document {

        private readonly _onDidChange = new Emitter<(value:string)=>any>();

        public onDidChange = this._onDidChange.event;

        // getter-style
        // get onDidChange(): Event<(value:string)=>any> {
        // 	return this._onDidChange.event;
        // }

        private _doIt() {
            //...
            this._onDidChange.fire(value);
        }
    }
 */
class Emitter {
    constructor(options) {
        var _a, _b;
        this._disposed = false;
        this._options = options;
        this._leakageMon = _globalLeakWarningThreshold > 0 ? new LeakageMonitor(this._options && this._options.leakWarningThreshold) : undefined;
        this._perfMon = ((_a = this._options) === null || _a === void 0 ? void 0 : _a._profName) ? new EventProfiling(this._options._profName) : undefined;
        this._deliveryQueue = (_b = this._options) === null || _b === void 0 ? void 0 : _b.deliveryQueue;
    }
    dispose() {
        var _a, _b, _c, _d;
        if (!this._disposed) {
            this._disposed = true;
            // It is bad to have listeners at the time of disposing an emitter, it is worst to have listeners keep the emitter
            // alive via the reference that's embedded in their disposables. Therefore we loop over all remaining listeners and
            // unset their subscriptions/disposables. Looping and blaming remaining listeners is done on next tick because the
            // the following programming pattern is very popular:
            //
            // const someModel = this._disposables.add(new ModelObject()); // (1) create and register model
            // this._disposables.add(someModel.onDidChange(() => { ... }); // (2) subscribe and register model-event listener
            // ...later...
            // this._disposables.dispose(); disposes (1) then (2): don't warn after (1) but after the "overall dispose" is done
            if (this._listeners) {
                if (_enableDisposeWithListenerWarning) {
                    const listeners = Array.from(this._listeners);
                    queueMicrotask(() => {
                        var _a;
                        for (const listener of listeners) {
                            if (listener.subscription.isset()) {
                                listener.subscription.unset();
                                (_a = listener.stack) === null || _a === void 0 ? void 0 : _a.print();
                            }
                        }
                    });
                }
                this._listeners.clear();
            }
            (_a = this._deliveryQueue) === null || _a === void 0 ? void 0 : _a.clear(this);
            (_c = (_b = this._options) === null || _b === void 0 ? void 0 : _b.onLastListenerRemove) === null || _c === void 0 ? void 0 : _c.call(_b);
            (_d = this._leakageMon) === null || _d === void 0 ? void 0 : _d.dispose();
        }
    }
    /**
     * For the public to allow to subscribe
     * to events from this Emitter
     */
    get event() {
        if (!this._event) {
            this._event = (callback, thisArgs, disposables) => {
                var _a, _b, _c;
                if (!this._listeners) {
                    this._listeners = new LinkedList();
                }
                const firstListener = this._listeners.isEmpty();
                if (firstListener && ((_a = this._options) === null || _a === void 0 ? void 0 : _a.onFirstListenerAdd)) {
                    this._options.onFirstListenerAdd(this);
                }
                let removeMonitor;
                let stack;
                if (this._leakageMon && this._listeners.size >= 30) {
                    // check and record this emitter for potential leakage
                    stack = Stacktrace.create();
                    removeMonitor = this._leakageMon.check(stack, this._listeners.size + 1);
                }
                if (_enableDisposeWithListenerWarning) {
                    stack = stack !== null && stack !== void 0 ? stack : Stacktrace.create();
                }
                const listener = new Listener(callback, thisArgs, stack);
                const removeListener = this._listeners.push(listener);
                if (firstListener && ((_b = this._options) === null || _b === void 0 ? void 0 : _b.onFirstListenerDidAdd)) {
                    this._options.onFirstListenerDidAdd(this);
                }
                if ((_c = this._options) === null || _c === void 0 ? void 0 : _c.onListenerDidAdd) {
                    this._options.onListenerDidAdd(this, callback, thisArgs);
                }
                const result = listener.subscription.set(() => {
                    removeMonitor === null || removeMonitor === void 0 ? void 0 : removeMonitor();
                    if (!this._disposed) {
                        removeListener();
                        if (this._options && this._options.onLastListenerRemove) {
                            const hasListeners = (this._listeners && !this._listeners.isEmpty());
                            if (!hasListeners) {
                                this._options.onLastListenerRemove(this);
                            }
                        }
                    }
                });
                if (disposables instanceof DisposableStore) {
                    disposables.add(result);
                }
                else if (Array.isArray(disposables)) {
                    disposables.push(result);
                }
                return result;
            };
        }
        return this._event;
    }
    /**
     * To be kept private to fire an event to
     * subscribers
     */
    fire(event) {
        var _a, _b;
        if (this._listeners) {
            // put all [listener,event]-pairs into delivery queue
            // then emit all event. an inner/nested event might be
            // the driver of this
            if (!this._deliveryQueue) {
                this._deliveryQueue = new PrivateEventDeliveryQueue();
            }
            for (const listener of this._listeners) {
                this._deliveryQueue.push(this, listener, event);
            }
            // start/stop performance insight collection
            (_a = this._perfMon) === null || _a === void 0 ? void 0 : _a.start(this._deliveryQueue.size);
            this._deliveryQueue.deliver();
            (_b = this._perfMon) === null || _b === void 0 ? void 0 : _b.stop();
        }
    }
}
class EventDeliveryQueue {
    constructor() {
        this._queue = new LinkedList();
    }
    get size() {
        return this._queue.size;
    }
    push(emitter, listener, event) {
        this._queue.push(new EventDeliveryQueueElement(emitter, listener, event));
    }
    clear(emitter) {
        const newQueue = new LinkedList();
        for (const element of this._queue) {
            if (element.emitter !== emitter) {
                newQueue.push(element);
            }
        }
        this._queue = newQueue;
    }
    deliver() {
        while (this._queue.size > 0) {
            const element = this._queue.shift();
            try {
                element.listener.invoke(element.event);
            }
            catch (e) {
                onUnexpectedError(e);
            }
        }
    }
}
/**
 * An `EventDeliveryQueue` that is guaranteed to be used by a single `Emitter`.
 */
class PrivateEventDeliveryQueue extends EventDeliveryQueue {
    clear(emitter) {
        // Here we can just clear the entire linked list because
        // all elements are guaranteed to belong to this emitter
        this._queue.clear();
    }
}
class EventDeliveryQueueElement {
    constructor(emitter, listener, event) {
        this.emitter = emitter;
        this.listener = listener;
        this.event = event;
    }
}
class PauseableEmitter extends Emitter {
    constructor(options) {
        super(options);
        this._isPaused = 0;
        this._eventQueue = new LinkedList();
        this._mergeFn = options === null || options === void 0 ? void 0 : options.merge;
    }
    pause() {
        this._isPaused++;
    }
    resume() {
        if (this._isPaused !== 0 && --this._isPaused === 0) {
            if (this._mergeFn) {
                // use the merge function to create a single composite
                // event. make a copy in case firing pauses this emitter
                const events = Array.from(this._eventQueue);
                this._eventQueue.clear();
                super.fire(this._mergeFn(events));
            }
            else {
                // no merging, fire each event individually and test
                // that this emitter isn't paused halfway through
                while (!this._isPaused && this._eventQueue.size !== 0) {
                    super.fire(this._eventQueue.shift());
                }
            }
        }
    }
    fire(event) {
        if (this._listeners) {
            if (this._isPaused !== 0) {
                this._eventQueue.push(event);
            }
            else {
                super.fire(event);
            }
        }
    }
}
class DebounceEmitter extends PauseableEmitter {
    constructor(options) {
        var _a;
        super(options);
        this._delay = (_a = options.delay) !== null && _a !== void 0 ? _a : 100;
    }
    fire(event) {
        if (!this._handle) {
            this.pause();
            this._handle = setTimeout(() => {
                this._handle = undefined;
                this.resume();
            }, this._delay);
        }
        super.fire(event);
    }
}
/**
 * The EventBufferer is useful in situations in which you want
 * to delay firing your events during some code.
 * You can wrap that code and be sure that the event will not
 * be fired during that wrap.
 *
 * ```
 * const emitter: Emitter;
 * const delayer = new EventDelayer();
 * const delayedEvent = delayer.wrapEvent(emitter.event);
 *
 * delayedEvent(console.log);
 *
 * delayer.bufferEvents(() => {
 *   emitter.fire(); // event will not be fired yet
 * });
 *
 * // event will only be fired at this point
 * ```
 */
class EventBufferer {
    constructor() {
        this.buffers = [];
    }
    wrapEvent(event) {
        return (listener, thisArgs, disposables) => {
            return event(i => {
                const buffer = this.buffers[this.buffers.length - 1];
                if (buffer) {
                    buffer.push(() => listener.call(thisArgs, i));
                }
                else {
                    listener.call(thisArgs, i);
                }
            }, undefined, disposables);
        };
    }
    bufferEvents(fn) {
        const buffer = [];
        this.buffers.push(buffer);
        const r = fn();
        this.buffers.pop();
        buffer.forEach(flush => flush());
        return r;
    }
}
/**
 * A Relay is an event forwarder which functions as a replugabble event pipe.
 * Once created, you can connect an input event to it and it will simply forward
 * events from that input event through its own `event` property. The `input`
 * can be changed at any point in time.
 */
class Relay {
    constructor() {
        this.listening = false;
        this.inputEvent = Event.None;
        this.inputEventListener = Disposable.None;
        this.emitter = new Emitter({
            onFirstListenerDidAdd: () => {
                this.listening = true;
                this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter);
            },
            onLastListenerRemove: () => {
                this.listening = false;
                this.inputEventListener.dispose();
            }
        });
        this.event = this.emitter.event;
    }
    set input(event) {
        this.inputEvent = event;
        if (this.listening) {
            this.inputEventListener.dispose();
            this.inputEventListener = event(this.emitter.fire, this.emitter);
        }
    }
    dispose() {
        this.inputEventListener.dispose();
        this.emitter.dispose();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/browser.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class WindowManager {
    constructor() {
        // --- Zoom Factor
        this._zoomFactor = 1;
    }
    getZoomFactor() {
        return this._zoomFactor;
    }
}
WindowManager.INSTANCE = new WindowManager();
/**
 * See https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#monitoring_screen_resolution_or_zoom_level_changes
 */
class DevicePixelRatioMonitor extends Disposable {
    constructor() {
        super();
        this._onDidChange = this._register(new Emitter());
        this.onDidChange = this._onDidChange.event;
        this._listener = () => this._handleChange(true);
        this._mediaQueryList = null;
        this._handleChange(false);
    }
    _handleChange(fireEvent) {
        var _a;
        (_a = this._mediaQueryList) === null || _a === void 0 ? void 0 : _a.removeEventListener('change', this._listener);
        this._mediaQueryList = matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
        this._mediaQueryList.addEventListener('change', this._listener);
        if (fireEvent) {
            this._onDidChange.fire();
        }
    }
}
class PixelRatioImpl extends Disposable {
    constructor() {
        super();
        this._onDidChange = this._register(new Emitter());
        this.onDidChange = this._onDidChange.event;
        this._value = this._getPixelRatio();
        const dprMonitor = this._register(new DevicePixelRatioMonitor());
        this._register(dprMonitor.onDidChange(() => {
            this._value = this._getPixelRatio();
            this._onDidChange.fire(this._value);
        }));
    }
    get value() {
        return this._value;
    }
    _getPixelRatio() {
        const ctx = document.createElement('canvas').getContext('2d');
        const dpr = window.devicePixelRatio || 1;
        const bsr = ctx.webkitBackingStorePixelRatio ||
            ctx.mozBackingStorePixelRatio ||
            ctx.msBackingStorePixelRatio ||
            ctx.oBackingStorePixelRatio ||
            ctx.backingStorePixelRatio || 1;
        return dpr / bsr;
    }
}
class PixelRatioFacade {
    constructor() {
        this._pixelRatioMonitor = null;
    }
    _getOrCreatePixelRatioMonitor() {
        if (!this._pixelRatioMonitor) {
            this._pixelRatioMonitor = markAsSingleton(new PixelRatioImpl());
        }
        return this._pixelRatioMonitor;
    }
    /**
     * Get the current value.
     */
    get value() {
        return this._getOrCreatePixelRatioMonitor().value;
    }
    /**
     * Listen for changes.
     */
    get onDidChange() {
        return this._getOrCreatePixelRatioMonitor().onDidChange;
    }
}
function addMatchMediaChangeListener(query, callback) {
    if (typeof query === 'string') {
        query = window.matchMedia(query);
    }
    query.addEventListener('change', callback);
}
/**
 * Returns the pixel ratio.
 *
 * This is useful for rendering <canvas> elements at native screen resolution or for being used as
 * a cache key when storing font measurements. Fonts might render differently depending on resolution
 * and any measurements need to be discarded for example when a window is moved from a monitor to another.
 */
const PixelRatio = new PixelRatioFacade();
/** The zoom scale for an index, e.g. 1, 1.2, 1.4 */
function getZoomFactor() {
    return WindowManager.INSTANCE.getZoomFactor();
}
const browser_userAgent = navigator.userAgent;
const browser_isFirefox = (browser_userAgent.indexOf('Firefox') >= 0);
const isWebKit = (browser_userAgent.indexOf('AppleWebKit') >= 0);
const browser_isChrome = (browser_userAgent.indexOf('Chrome') >= 0);
const browser_isSafari = (!browser_isChrome && (browser_userAgent.indexOf('Safari') >= 0));
const isWebkitWebView = (!browser_isChrome && !browser_isSafari && isWebKit);
const isElectron = (browser_userAgent.indexOf('Electron/') >= 0);
const browser_isAndroid = (browser_userAgent.indexOf('Android') >= 0);
let standalone = false;
if (window.matchMedia) {
    const matchMedia = window.matchMedia('(display-mode: standalone)');
    standalone = matchMedia.matches;
    addMatchMediaChangeListener(matchMedia, ({ matches }) => {
        standalone = matches;
    });
}
function isStandalone() {
    return standalone;
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/canIUse.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


/**
 * Browser feature we can support in current platform, browser and environment.
 */
const canIUse_BrowserFeatures = {
    clipboard: {
        writeText: (isNative
            || (document.queryCommandSupported && document.queryCommandSupported('copy'))
            || !!(navigator && navigator.clipboard && navigator.clipboard.writeText)),
        readText: (isNative
            || !!(navigator && navigator.clipboard && navigator.clipboard.readText))
    },
    keyboard: (() => {
        if (isNative || isStandalone()) {
            return 0 /* KeyboardSupport.Always */;
        }
        if (navigator.keyboard || browser_isSafari) {
            return 1 /* KeyboardSupport.FullScreen */;
        }
        return 2 /* KeyboardSupport.None */;
    })(),
    // '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 window || navigator.maxTouchPoints > 0,
    pointerEvents: window.PointerEvent && ('ontouchstart' in window || window.navigator.maxTouchPoints > 0 || navigator.maxTouchPoints > 0)
};

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

;// ../../node_modules/monaco-editor/esm/vs/base/common/keybindings.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

function createKeybinding(keybinding, OS) {
    if (keybinding === 0) {
        return null;
    }
    const firstPart = (keybinding & 0x0000FFFF) >>> 0;
    const chordPart = (keybinding & 0xFFFF0000) >>> 16;
    if (chordPart !== 0) {
        return new ChordKeybinding([
            createSimpleKeybinding(firstPart, OS),
            createSimpleKeybinding(chordPart, OS)
        ]);
    }
    return new ChordKeybinding([createSimpleKeybinding(firstPart, OS)]);
}
function createSimpleKeybinding(keybinding, OS) {
    const ctrlCmd = (keybinding & 2048 /* BinaryKeybindingsMask.CtrlCmd */ ? true : false);
    const winCtrl = (keybinding & 256 /* BinaryKeybindingsMask.WinCtrl */ ? true : false);
    const ctrlKey = (OS === 2 /* OperatingSystem.Macintosh */ ? winCtrl : ctrlCmd);
    const shiftKey = (keybinding & 1024 /* BinaryKeybindingsMask.Shift */ ? true : false);
    const altKey = (keybinding & 512 /* BinaryKeybindingsMask.Alt */ ? true : false);
    const metaKey = (OS === 2 /* OperatingSystem.Macintosh */ ? ctrlCmd : winCtrl);
    const keyCode = (keybinding & 255 /* BinaryKeybindingsMask.KeyCode */);
    return new SimpleKeybinding(ctrlKey, shiftKey, altKey, metaKey, keyCode);
}
class SimpleKeybinding {
    constructor(ctrlKey, shiftKey, altKey, metaKey, keyCode) {
        this.ctrlKey = ctrlKey;
        this.shiftKey = shiftKey;
        this.altKey = altKey;
        this.metaKey = metaKey;
        this.keyCode = keyCode;
    }
    equals(other) {
        return (this.ctrlKey === other.ctrlKey
            && this.shiftKey === other.shiftKey
            && this.altKey === other.altKey
            && this.metaKey === other.metaKey
            && this.keyCode === other.keyCode);
    }
    isModifierKey() {
        return (this.keyCode === 0 /* KeyCode.Unknown */
            || this.keyCode === 5 /* KeyCode.Ctrl */
            || this.keyCode === 57 /* KeyCode.Meta */
            || this.keyCode === 6 /* KeyCode.Alt */
            || this.keyCode === 4 /* KeyCode.Shift */);
    }
    toChord() {
        return new ChordKeybinding([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 /* KeyCode.Ctrl */)
            || (this.shiftKey && this.keyCode === 4 /* KeyCode.Shift */)
            || (this.altKey && this.keyCode === 6 /* KeyCode.Alt */)
            || (this.metaKey && this.keyCode === 57 /* KeyCode.Meta */));
    }
}
class ChordKeybinding {
    constructor(parts) {
        if (parts.length === 0) {
            throw illegalArgument(`parts`);
        }
        this.parts = parts;
    }
}
class ScanCodeBinding {
    constructor(ctrlKey, shiftKey, altKey, metaKey, scanCode) {
        this.ctrlKey = ctrlKey;
        this.shiftKey = shiftKey;
        this.altKey = altKey;
        this.metaKey = metaKey;
        this.scanCode = 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 /* ScanCode.ControlLeft */ || this.scanCode === 161 /* ScanCode.ControlRight */))
            || (this.shiftKey && (this.scanCode === 158 /* ScanCode.ShiftLeft */ || this.scanCode === 162 /* ScanCode.ShiftRight */))
            || (this.altKey && (this.scanCode === 159 /* ScanCode.AltLeft */ || this.scanCode === 163 /* ScanCode.AltRight */))
            || (this.metaKey && (this.scanCode === 160 /* ScanCode.MetaLeft */ || this.scanCode === 164 /* ScanCode.MetaRight */)));
    }
}
class ResolvedKeybindingPart {
    constructor(ctrlKey, shiftKey, altKey, metaKey, kbLabel, kbAriaLabel) {
        this.ctrlKey = ctrlKey;
        this.shiftKey = shiftKey;
        this.altKey = altKey;
        this.metaKey = metaKey;
        this.keyLabel = kbLabel;
        this.keyAriaLabel = kbAriaLabel;
    }
}
/**
 * A resolved keybinding. Can be a simple keybinding or a chord keybinding.
 */
class ResolvedKeybinding {
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/keyboardEvent.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




function extractKeyCode(e) {
    if (e.charCode) {
        // "keypress" events mostly
        const char = String.fromCharCode(e.charCode).toUpperCase();
        return KeyCodeUtils.fromString(char);
    }
    const keyCode = e.keyCode;
    // browser quirks
    if (keyCode === 3) {
        return 7 /* KeyCode.PauseBreak */;
    }
    else if (browser_isFirefox) {
        if (keyCode === 59) {
            return 80 /* KeyCode.Semicolon */;
        }
        else if (keyCode === 107) {
            return 81 /* KeyCode.Equal */;
        }
        else if (keyCode === 109) {
            return 83 /* KeyCode.Minus */;
        }
        else if (isMacintosh && keyCode === 224) {
            return 57 /* KeyCode.Meta */;
        }
    }
    else if (isWebKit) {
        if (keyCode === 91) {
            return 57 /* KeyCode.Meta */;
        }
        else if (isMacintosh && keyCode === 93) {
            // the two meta keys in the Mac have different key codes (91 and 93)
            return 57 /* KeyCode.Meta */;
        }
        else if (!isMacintosh && keyCode === 92) {
            return 57 /* KeyCode.Meta */;
        }
    }
    // cross browser keycodes:
    return EVENT_KEY_CODE_MAP[keyCode] || 0 /* KeyCode.Unknown */;
}
const ctrlKeyMod = (isMacintosh ? 256 /* KeyMod.WinCtrl */ : 2048 /* KeyMod.CtrlCmd */);
const altKeyMod = 512 /* KeyMod.Alt */;
const shiftKeyMod = 1024 /* KeyMod.Shift */;
const metaKeyMod = (isMacintosh ? 2048 /* KeyMod.CtrlCmd */ : 256 /* KeyMod.WinCtrl */);
class StandardKeyboardEvent {
    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.keyCode = extractKeyCode(e);
        this.code = e.code;
        // console.info(e.type + ": keyCode: " + e.keyCode + ", which: " + e.which + ", charCode: " + e.charCode + ", detail: " + e.detail + " ====> " + this.keyCode + ' -- ' + KeyCode[this.keyCode]);
        this.ctrlKey = this.ctrlKey || this.keyCode === 5 /* KeyCode.Ctrl */;
        this.altKey = this.altKey || this.keyCode === 6 /* KeyCode.Alt */;
        this.shiftKey = this.shiftKey || this.keyCode === 4 /* KeyCode.Shift */;
        this.metaKey = this.metaKey || this.keyCode === 57 /* KeyCode.Meta */;
        this._asKeybinding = this._computeKeybinding();
        this._asRuntimeKeybinding = this._computeRuntimeKeybinding();
        // console.log(`code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`);
    }
    preventDefault() {
        if (this.browserEvent && this.browserEvent.preventDefault) {
            this.browserEvent.preventDefault();
        }
    }
    stopPropagation() {
        if (this.browserEvent && this.browserEvent.stopPropagation) {
            this.browserEvent.stopPropagation();
        }
    }
    toKeybinding() {
        return this._asRuntimeKeybinding;
    }
    equals(other) {
        return this._asKeybinding === other;
    }
    _computeKeybinding() {
        let key = 0 /* KeyCode.Unknown */;
        if (this.keyCode !== 5 /* KeyCode.Ctrl */ && this.keyCode !== 4 /* KeyCode.Shift */ && this.keyCode !== 6 /* KeyCode.Alt */ && this.keyCode !== 57 /* KeyCode.Meta */) {
            key = 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 |= key;
        return result;
    }
    _computeRuntimeKeybinding() {
        let key = 0 /* KeyCode.Unknown */;
        if (this.keyCode !== 5 /* KeyCode.Ctrl */ && this.keyCode !== 4 /* KeyCode.Shift */ && this.keyCode !== 6 /* KeyCode.Alt */ && this.keyCode !== 57 /* KeyCode.Meta */) {
            key = this.keyCode;
        }
        return new SimpleKeybinding(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/iframe.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
let hasDifferentOriginAncestorFlag = false;
let sameOriginWindowChainCache = null;
function getParentWindowIfSameOrigin(w) {
    if (!w.parent || w.parent === w) {
        return null;
    }
    // Cannot really tell if we have access to the parent window unless we try to access something in it
    try {
        const location = w.location;
        const parentLocation = w.parent.location;
        if (location.origin !== 'null' && parentLocation.origin !== 'null' && location.origin !== parentLocation.origin) {
            hasDifferentOriginAncestorFlag = true;
            return null;
        }
    }
    catch (e) {
        hasDifferentOriginAncestorFlag = true;
        return null;
    }
    return w.parent;
}
class IframeUtils {
    /**
     * 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.
     * To distinguish if at one point the current execution environment is running inside a window with a different origin, see hasDifferentOriginAncestor()
     */
    static getSameOriginWindowChain() {
        if (!sameOriginWindowChainCache) {
            sameOriginWindowChainCache = [];
            let w = window;
            let parent;
            do {
                parent = getParentWindowIfSameOrigin(w);
                if (parent) {
                    sameOriginWindowChainCache.push({
                        window: w,
                        iframeElement: w.frameElement || null
                    });
                }
                else {
                    sameOriginWindowChainCache.push({
                        window: w,
                        iframeElement: null
                    });
                }
                w = parent;
            } while (w);
        }
        return sameOriginWindowChainCache.slice(0);
    }
    /**
     * Returns the position of `childWindow` relative to `ancestorWindow`
     */
    static getPositionOfChildWindowRelativeToAncestorWindow(childWindow, ancestorWindow) {
        if (!ancestorWindow || childWindow === ancestorWindow) {
            return {
                top: 0,
                left: 0
            };
        }
        let top = 0, left = 0;
        const windowChain = this.getSameOriginWindowChain();
        for (const windowChainEl of windowChain) {
            top += windowChainEl.window.scrollY;
            left += windowChainEl.window.scrollX;
            if (windowChainEl.window === ancestorWindow) {
                break;
            }
            if (!windowChainEl.iframeElement) {
                break;
            }
            const boundingRect = windowChainEl.iframeElement.getBoundingClientRect();
            top += boundingRect.top;
            left += boundingRect.left;
        }
        return {
            top: top,
            left: left
        };
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/mouseEvent.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class StandardMouseEvent {
    constructor(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 {
            // Probably hit by MSGestureEvent
            this.posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            this.posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
        // Find the position of the iframe this code is executing in relative to the iframe where the event was captured.
        const iframeOffsets = IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(self, e.view);
        this.posx -= iframeOffsets.left;
        this.posy -= iframeOffsets.top;
    }
    preventDefault() {
        this.browserEvent.preventDefault();
    }
    stopPropagation() {
        this.browserEvent.stopPropagation();
    }
}
class StandardWheelEvent {
    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;
        if (e) {
            // Old (deprecated) wheel events
            const e1 = e;
            const e2 = e;
            // vertical delta scroll
            if (typeof e1.wheelDeltaY !== 'undefined') {
                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') {
                // Modern wheel event
                // https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent
                const ev = e;
                if (ev.deltaMode === ev.DOM_DELTA_LINE) {
                    // the deltas are expressed in lines
                    if (browser_isFirefox && !isMacintosh) {
                        this.deltaY = -e.deltaY / 3;
                    }
                    else {
                        this.deltaY = -e.deltaY;
                    }
                }
                else {
                    this.deltaY = -e.deltaY / 40;
                }
            }
            // horizontal delta scroll
            if (typeof e1.wheelDeltaX !== 'undefined') {
                if (browser_isSafari && isWindows) {
                    this.deltaX = -(e1.wheelDeltaX / 120);
                }
                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') {
                // Modern wheel event
                // https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent
                const ev = e;
                if (ev.deltaMode === ev.DOM_DELTA_LINE) {
                    // the deltas are expressed in lines
                    if (browser_isFirefox && !isMacintosh) {
                        this.deltaX = -e.deltaX / 3;
                    }
                    else {
                        this.deltaX = -e.deltaX;
                    }
                }
                else {
                    this.deltaX = -e.deltaX / 40;
                }
            }
            // Assume a vertical scroll if nothing else worked
            if (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) {
                this.deltaY = e.wheelDelta / 120;
            }
        }
    }
    preventDefault() {
        if (this.browserEvent) {
            this.browserEvent.preventDefault();
        }
    }
    stopPropagation() {
        if (this.browserEvent) {
            this.browserEvent.stopPropagation();
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/dompurify/dompurify.js
/*! @license DOMPurify 2.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.1/LICENSE */

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var dompurify_hasOwnProperty = Object.hasOwnProperty,
    setPrototypeOf = Object.setPrototypeOf,
    isFrozen = Object.isFrozen,
    getPrototypeOf = Object.getPrototypeOf,
    getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var freeze = Object.freeze,
    seal = Object.seal,
    dompurify_create = Object.create; // eslint-disable-line import/no-mutable-exports

var _ref = typeof Reflect !== 'undefined' && Reflect,
    apply = _ref.apply,
    construct = _ref.construct;

if (!apply) {
  apply = function apply(fun, thisValue, args) {
    return fun.apply(thisValue, args);
  };
}

if (!freeze) {
  freeze = function freeze(x) {
    return x;
  };
}

if (!seal) {
  seal = function seal(x) {
    return x;
  };
}

if (!construct) {
  construct = function construct(Func, args) {
    return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))();
  };
}

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 stringMatch = unapply(String.prototype.match);
var stringReplace = unapply(String.prototype.replace);
var stringIndexOf = unapply(String.prototype.indexOf);
var stringTrim = unapply(String.prototype.trim);

var regExpTest = unapply(RegExp.prototype.test);

var typeErrorCreate = unconstruct(TypeError);

function unapply(func) {
  return function (thisArg) {
    for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }

    return apply(func, thisArg, args);
  };
}

function unconstruct(func) {
  return function () {
    for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }

    return construct(func, args);
  };
}

/* Add properties to a lookup table */
function addToSet(set, array) {
  if (setPrototypeOf) {
    // Make 'in' and truthy checks like Boolean(set.constructor)
    // independent of any properties defined on Object.prototype.
    // Prevent prototype setters from intercepting set as a this value.
    setPrototypeOf(set, null);
  }

  var l = array.length;
  while (l--) {
    var element = array[l];
    if (typeof element === 'string') {
      var lcElement = stringToLowerCase(element);
      if (lcElement !== element) {
        // Config presets (e.g. tags.js, attrs.js) are immutable.
        if (!isFrozen(array)) {
          array[l] = lcElement;
        }

        element = lcElement;
      }
    }

    set[element] = true;
  }

  return set;
}

/* Shallow clone an object */
function clone(object) {
  var newObject = dompurify_create(null);

  var property = void 0;
  for (property in object) {
    if (apply(dompurify_hasOwnProperty, object, [property])) {
      newObject[property] = object[property];
    }
  }

  return newObject;
}

/* IE10 doesn't support __lookupGetter__ so lets'
 * simulate it. It also automatically checks
 * if the prop is function or getter and behaves
 * accordingly. */
function lookupGetter(object, prop) {
  while (object !== null) {
    var 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(element) {
    console.warn('fallback value for', element);
    return null;
  }

  return fallbackValue;
}

var html = 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']);

// SVG
var svg = 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', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);

// List of SVG elements that are disallowed by default.
// We still need to know them so that we can do namespace
// checks properly in case one wants to add them to
// allow-list.
var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'feimage', '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 = 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']);

// Similarly to SVG, we want to know all MathML elements,
// even those that we disallow by default.
var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);

var dompurify_text = freeze(['#text']);

var html$1 = 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', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', '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', 'xmlns', 'slot']);

var svg$1 = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', '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', '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', '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', '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', 'targetx', 'targety', 'transform', '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$1 = 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']);

// eslint-disable-next-line unicorn/better-regex
var MUSTACHE_EXPR = seal(/\{\{[\s\S]*|[\s\S]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
var ERB_EXPR = seal(/<%[\s\S]*|[\s\S]*%>/gm);
var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape
var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|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 _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

function _toConsumableArray$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var getGlobal = function getGlobal() {
  return typeof window === 'undefined' ? null : window;
};

/**
 * Creates a no-op policy for internal use only.
 * Don't export this function outside this module!
 * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
 * @param {Document} document The document object (to determine policy name suffix)
 * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
 * are not supported).
 */
var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
  if ((typeof trustedTypes === 'undefined' ? 'undefined' : _typeof(trustedTypes)) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
    return null;
  }

  // Allow the callers to control the unique policy name
  // by adding a data-tt-policy-suffix to the script element with the DOMPurify.
  // Policy creation with duplicate names throws in Trusted Types.
  var suffix = null;
  var ATTR_NAME = 'data-tt-policy-suffix';
  if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
    suffix = document.currentScript.getAttribute(ATTR_NAME);
  }

  var policyName = 'dompurify' + (suffix ? '#' + suffix : '');

  try {
    return trustedTypes.createPolicy(policyName, {
      createHTML: function createHTML(html$$1) {
        return html$$1;
      }
    });
  } catch (_) {
    // Policy creation failed (most likely another DOMPurify script has
    // already run). Skip creating the policy, as this will only cause errors
    // if TT are enforced.
    console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
    return null;
  }
};

function createDOMPurify() {
  var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();

  var DOMPurify = function DOMPurify(root) {
    return createDOMPurify(root);
  };

  /**
   * Version label, exposed for easier checks
   * if DOMPurify is up to date or not
   */
  DOMPurify.version = '2.3.1';

  /**
   * Array of elements that DOMPurify removed during sanitation.
   * Empty if nothing was removed.
   */
  DOMPurify.removed = [];

  if (!window || !window.document || window.document.nodeType !== 9) {
    // Not running in a browser, provide a factory function
    // so that you can pass your own Window
    DOMPurify.isSupported = false;

    return DOMPurify;
  }

  var originalDocument = window.document;

  var document = window.document;
  var DocumentFragment = window.DocumentFragment,
      HTMLTemplateElement = window.HTMLTemplateElement,
      Node = window.Node,
      Element = window.Element,
      NodeFilter = window.NodeFilter,
      _window$NamedNodeMap = window.NamedNodeMap,
      NamedNodeMap = _window$NamedNodeMap === undefined ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
      Text = window.Text,
      Comment = window.Comment,
      DOMParser = window.DOMParser,
      trustedTypes = window.trustedTypes;


  var ElementPrototype = Element.prototype;

  var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
  var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
  var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
  var getParentNode = lookupGetter(ElementPrototype, 'parentNode');

  // As per issue #47, the web-components registry is inherited by a
  // new document created via createHTMLDocument. As per the spec
  // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
  // a new empty registry is used when creating a template contents owner
  // document, so we use that as our parent document to ensure nothing
  // is inherited.
  if (typeof HTMLTemplateElement === 'function') {
    var template = document.createElement('template');
    if (template.content && template.content.ownerDocument) {
      document = template.content.ownerDocument;
    }
  }

  var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
  var emptyHTML = trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML('') : '';

  var _document = document,
      implementation = _document.implementation,
      createNodeIterator = _document.createNodeIterator,
      createDocumentFragment = _document.createDocumentFragment,
      getElementsByTagName = _document.getElementsByTagName;
  var importNode = originalDocument.importNode;


  var documentMode = {};
  try {
    documentMode = clone(document).documentMode ? document.documentMode : {};
  } catch (_) {}

  var hooks = {};

  /**
   * Expose whether this browser supports running the full DOMPurify.
   */
  DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;

  var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR,
      ERB_EXPR$$1 = ERB_EXPR,
      DATA_ATTR$$1 = DATA_ATTR,
      ARIA_ATTR$$1 = ARIA_ATTR,
      IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA,
      ATTR_WHITESPACE$$1 = ATTR_WHITESPACE;
  var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI;

  /**
   * We consider the elements and attributes below to be safe. Ideally
   * don't add any new ones but feel free to remove unwanted ones.
   */

  /* allowed element names */

  var ALLOWED_TAGS = null;
  var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(html), _toConsumableArray$1(svg), _toConsumableArray$1(svgFilters), _toConsumableArray$1(mathMl), _toConsumableArray$1(dompurify_text)));

  /* Allowed attribute names */
  var ALLOWED_ATTR = null;
  var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray$1(html$1), _toConsumableArray$1(svg$1), _toConsumableArray$1(mathMl$1), _toConsumableArray$1(xml)));

  /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
  var FORBID_TAGS = null;

  /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
  var FORBID_ATTR = null;

  /* Decide if ARIA attributes are okay */
  var ALLOW_ARIA_ATTR = true;

  /* Decide if custom data attributes are okay */
  var ALLOW_DATA_ATTR = true;

  /* Decide if unknown protocols are okay */
  var ALLOW_UNKNOWN_PROTOCOLS = false;

  /* Output should be safe for common template engines.
   * This means, DOMPurify removes data attributes, mustaches and ERB
   */
  var SAFE_FOR_TEMPLATES = false;

  /* Decide if document with <html>... should be returned */
  var WHOLE_DOCUMENT = false;

  /* Track whether config is already set on this instance of DOMPurify. */
  var SET_CONFIG = false;

  /* Decide if all elements (e.g. style, script) must be children of
   * document.body. By default, browsers might move them to document.head */
  var FORCE_BODY = false;

  /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
   * string (or a TrustedHTML object if Trusted Types are supported).
   * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
   */
  var RETURN_DOM = false;

  /* Decide if a DOM `DocumentFragment` should be returned, instead of a html
   * string  (or a TrustedHTML object if Trusted Types are supported) */
  var RETURN_DOM_FRAGMENT = false;

  /* If `RETURN_DOM` or `RETURN_DOM_FRAGMENT` is enabled, decide if the returned DOM
   * `Node` is imported into the current `Document`. If this flag is not enabled the
   * `Node` will belong (its ownerDocument) to a fresh `HTMLDocument`, created by
   * DOMPurify.
   *
   * This defaults to `true` starting DOMPurify 2.2.0. Note that setting it to `false`
   * might cause XSS from attacks hidden in closed shadowroots in case the browser
   * supports Declarative Shadow: DOM https://web.dev/declarative-shadow-dom/
   */
  var RETURN_DOM_IMPORT = true;

  /* Try to return a Trusted Type object instead of a string, return a string in
   * case Trusted Types are not supported  */
  var RETURN_TRUSTED_TYPE = false;

  /* Output should be free from DOM clobbering attacks? */
  var SANITIZE_DOM = true;

  /* Keep element content when removing element? */
  var KEEP_CONTENT = true;

  /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
   * of importing it into a new Document and returning a sanitized copy */
  var IN_PLACE = false;

  /* Allow usage of profiles like html, svg and mathMl */
  var USE_PROFILES = {};

  /* Tags to ignore content of when KEEP_CONTENT is true */
  var FORBID_CONTENTS = null;
  var 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']);

  /* Tags that are safe for data: URIs */
  var DATA_URI_TAGS = null;
  var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);

  /* Attributes safe for values like "javascript:" */
  var URI_SAFE_ATTRIBUTES = null;
  var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);

  var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
  var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
  var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
  /* Document namespace */
  var NAMESPACE = HTML_NAMESPACE;
  var IS_EMPTY_INPUT = false;

  /* Keep a reference to config to pass to hooks */
  var CONFIG = null;

  /* Ideally, do not touch anything below this line */
  /* ______________________________________________ */

  var formElement = document.createElement('form');

  /**
   * _parseConfig
   *
   * @param  {Object} cfg optional config literal
   */
  // eslint-disable-next-line complexity
  var _parseConfig = function _parseConfig(cfg) {
    if (CONFIG && CONFIG === cfg) {
      return;
    }

    /* Shield configuration object from tampering */
    if (!cfg || (typeof cfg === 'undefined' ? 'undefined' : _typeof(cfg)) !== 'object') {
      cfg = {};
    }

    /* Shield configuration object from prototype pollution */
    cfg = clone(cfg);

    /* Set configuration parameters */
    ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
    ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
    URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
    DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
    FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
    FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
    FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
    USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
    ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
    ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
    ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
    SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
    WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
    RETURN_DOM = cfg.RETURN_DOM || false; // Default false
    RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
    RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT !== false; // Default true
    RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
    FORCE_BODY = cfg.FORCE_BODY || false; // Default false
    SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
    KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
    IN_PLACE = cfg.IN_PLACE || false; // Default false
    IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1;
    NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
    if (SAFE_FOR_TEMPLATES) {
      ALLOW_DATA_ATTR = false;
    }

    if (RETURN_DOM_FRAGMENT) {
      RETURN_DOM = true;
    }

    /* Parse profile info */
    if (USE_PROFILES) {
      ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(dompurify_text)));
      ALLOWED_ATTR = [];
      if (USE_PROFILES.html === true) {
        addToSet(ALLOWED_TAGS, html);
        addToSet(ALLOWED_ATTR, html$1);
      }

      if (USE_PROFILES.svg === true) {
        addToSet(ALLOWED_TAGS, svg);
        addToSet(ALLOWED_ATTR, svg$1);
        addToSet(ALLOWED_ATTR, xml);
      }

      if (USE_PROFILES.svgFilters === true) {
        addToSet(ALLOWED_TAGS, svgFilters);
        addToSet(ALLOWED_ATTR, svg$1);
        addToSet(ALLOWED_ATTR, xml);
      }

      if (USE_PROFILES.mathMl === true) {
        addToSet(ALLOWED_TAGS, mathMl);
        addToSet(ALLOWED_ATTR, mathMl$1);
        addToSet(ALLOWED_ATTR, xml);
      }
    }

    /* Merge configuration parameters */
    if (cfg.ADD_TAGS) {
      if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
        ALLOWED_TAGS = clone(ALLOWED_TAGS);
      }

      addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
    }

    if (cfg.ADD_ATTR) {
      if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
        ALLOWED_ATTR = clone(ALLOWED_ATTR);
      }

      addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
    }

    if (cfg.ADD_URI_SAFE_ATTR) {
      addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
    }

    if (cfg.FORBID_CONTENTS) {
      if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
        FORBID_CONTENTS = clone(FORBID_CONTENTS);
      }

      addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
    }

    /* Add #text in case KEEP_CONTENT is set to true */
    if (KEEP_CONTENT) {
      ALLOWED_TAGS['#text'] = true;
    }

    /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
    if (WHOLE_DOCUMENT) {
      addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
    }

    /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
    if (ALLOWED_TAGS.table) {
      addToSet(ALLOWED_TAGS, ['tbody']);
      delete FORBID_TAGS.tbody;
    }

    // Prevent further manipulation of configuration.
    // Not available in IE8, Safari 5, etc.
    if (freeze) {
      freeze(cfg);
    }

    CONFIG = cfg;
  };

  var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);

  var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']);

  /* Keep track of all possible SVG and MathML tags
   * so that we can perform the namespace checks
   * correctly. */
  var ALL_SVG_TAGS = addToSet({}, svg);
  addToSet(ALL_SVG_TAGS, svgFilters);
  addToSet(ALL_SVG_TAGS, svgDisallowed);

  var ALL_MATHML_TAGS = addToSet({}, mathMl);
  addToSet(ALL_MATHML_TAGS, mathMlDisallowed);

  /**
   *
   *
   * @param  {Element} element a DOM element whose namespace is being checked
   * @returns {boolean} Return false if the element has a
   *  namespace that a spec-compliant parser would never
   *  return. Return true otherwise.
   */
  var _checkValidNamespace = function _checkValidNamespace(element) {
    var parent = getParentNode(element);

    // In JSDOM, if we're inside shadow DOM, then parentNode
    // can be null. We just simulate parent in this case.
    if (!parent || !parent.tagName) {
      parent = {
        namespaceURI: HTML_NAMESPACE,
        tagName: 'template'
      };
    }

    var tagName = stringToLowerCase(element.tagName);
    var parentTagName = stringToLowerCase(parent.tagName);

    if (element.namespaceURI === SVG_NAMESPACE) {
      // The only way to switch from HTML namespace to SVG
      // is via <svg>. If it happens via any other tag, then
      // it should be killed.
      if (parent.namespaceURI === HTML_NAMESPACE) {
        return tagName === 'svg';
      }

      // The only way to switch from MathML to SVG is via
      // svg if parent is either <annotation-xml> or MathML
      // text integration points.
      if (parent.namespaceURI === MATHML_NAMESPACE) {
        return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
      }

      // We only allow elements that are defined in SVG
      // spec. All others are disallowed in SVG namespace.
      return Boolean(ALL_SVG_TAGS[tagName]);
    }

    if (element.namespaceURI === MATHML_NAMESPACE) {
      // The only way to switch from HTML namespace to MathML
      // is via <math>. If it happens via any other tag, then
      // it should be killed.
      if (parent.namespaceURI === HTML_NAMESPACE) {
        return tagName === 'math';
      }

      // The only way to switch from SVG to MathML is via
      // <math> and HTML integration points
      if (parent.namespaceURI === SVG_NAMESPACE) {
        return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
      }

      // We only allow elements that are defined in MathML
      // spec. All others are disallowed in MathML namespace.
      return Boolean(ALL_MATHML_TAGS[tagName]);
    }

    if (element.namespaceURI === HTML_NAMESPACE) {
      // The only way to switch from SVG to HTML is via
      // HTML integration points, and from MathML to HTML
      // is via MathML text integration points
      if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }

      if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }

      // Certain elements are allowed in both SVG and HTML
      // namespace. We need to specify them explicitly
      // so that they don't get erronously deleted from
      // HTML namespace.
      var commonSvgAndHTMLElements = addToSet({}, ['title', 'style', 'font', 'a', 'script']);

      // We disallow tags that are specific for MathML
      // or SVG and should never appear in HTML namespace
      return !ALL_MATHML_TAGS[tagName] && (commonSvgAndHTMLElements[tagName] || !ALL_SVG_TAGS[tagName]);
    }

    // The code should never reach this place (this means
    // that the element somehow got namespace that is not
    // HTML, SVG or MathML). Return false just in case.
    return false;
  };

  /**
   * _forceRemove
   *
   * @param  {Node} node a DOM node
   */
  var _forceRemove = function _forceRemove(node) {
    arrayPush(DOMPurify.removed, { element: node });
    try {
      // eslint-disable-next-line unicorn/prefer-dom-node-remove
      node.parentNode.removeChild(node);
    } catch (_) {
      try {
        node.outerHTML = emptyHTML;
      } catch (_) {
        node.remove();
      }
    }
  };

  /**
   * _removeAttribute
   *
   * @param  {String} name an Attribute name
   * @param  {Node} node a DOM node
   */
  var _removeAttribute = function _removeAttribute(name, node) {
    try {
      arrayPush(DOMPurify.removed, {
        attribute: node.getAttributeNode(name),
        from: node
      });
    } catch (_) {
      arrayPush(DOMPurify.removed, {
        attribute: null,
        from: node
      });
    }

    node.removeAttribute(name);

    // We void attribute values for unremovable "is"" attributes
    if (name === 'is' && !ALLOWED_ATTR[name]) {
      if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
        try {
          _forceRemove(node);
        } catch (_) {}
      } else {
        try {
          node.setAttribute(name, '');
        } catch (_) {}
      }
    }
  };

  /**
   * _initDocument
   *
   * @param  {String} dirty a string of dirty markup
   * @return {Document} a DOM, filled with the dirty markup
   */
  var _initDocument = function _initDocument(dirty) {
    /* Create a HTML document */
    var doc = void 0;
    var leadingWhitespace = void 0;

    if (FORCE_BODY) {
      dirty = '<remove></remove>' + dirty;
    } else {
      /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
      var matches = stringMatch(dirty, /^[\r\n\t ]+/);
      leadingWhitespace = matches && matches[0];
    }

    var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
    /*
     * Use the DOMParser API by default, fallback later if needs be
     * DOMParser not work for svg when has multiple root element.
     */
    if (NAMESPACE === HTML_NAMESPACE) {
      try {
        doc = new DOMParser().parseFromString(dirtyPayload, 'text/html');
      } catch (_) {}
    }

    /* Use createHTMLDocument in case DOMParser is not available */
    if (!doc || !doc.documentElement) {
      doc = implementation.createDocument(NAMESPACE, 'template', null);
      try {
        doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload;
      } catch (_) {
        // Syntax error if dirtyPayload is invalid xml
      }
    }

    var body = doc.body || doc.documentElement;

    if (dirty && leadingWhitespace) {
      body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
    }

    /* Work on whole document or just its body */
    if (NAMESPACE === HTML_NAMESPACE) {
      return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
    }

    return WHOLE_DOCUMENT ? doc.documentElement : body;
  };

  /**
   * _createIterator
   *
   * @param  {Document} root document/fragment to create iterator for
   * @return {Iterator} iterator instance
   */
  var _createIterator = function _createIterator(root) {
    return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
  };

  /**
   * _isClobbered
   *
   * @param  {Node} elm element to check for clobbering attacks
   * @return {Boolean} true if clobbered, false if safe
   */
  var _isClobbered = function _isClobbered(elm) {
    if (elm instanceof Text || elm instanceof Comment) {
      return false;
    }

    if (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') {
      return true;
    }

    return false;
  };

  /**
   * _isNode
   *
   * @param  {Node} obj object to check whether it's a DOM node
   * @return {Boolean} true is object is a DOM node
   */
  var _isNode = function _isNode(object) {
    return (typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? object instanceof Node : object && (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
  };

  /**
   * _executeHook
   * Execute user configurable hooks
   *
   * @param  {String} entryPoint  Name of the hook's entry point
   * @param  {Node} currentNode node to work on with the hook
   * @param  {Object} data additional hook parameters
   */
  var _executeHook = function _executeHook(entryPoint, currentNode, data) {
    if (!hooks[entryPoint]) {
      return;
    }

    arrayForEach(hooks[entryPoint], function (hook) {
      hook.call(DOMPurify, currentNode, data, CONFIG);
    });
  };

  /**
   * _sanitizeElements
   *
   * @protect nodeName
   * @protect textContent
   * @protect removeChild
   *
   * @param   {Node} currentNode to check for permission to exist
   * @return  {Boolean} true if node was killed, false if left alive
   */
  var _sanitizeElements = function _sanitizeElements(currentNode) {
    var content = void 0;

    /* Execute a hook if present */
    _executeHook('beforeSanitizeElements', currentNode, null);

    /* Check if element is clobbered or can clobber */
    if (_isClobbered(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }

    /* Check if tagname contains Unicode */
    if (stringMatch(currentNode.nodeName, /[\u0080-\uFFFF]/)) {
      _forceRemove(currentNode);
      return true;
    }

    /* Now let's check the element's type and name */
    var tagName = stringToLowerCase(currentNode.nodeName);

    /* Execute a hook if present */
    _executeHook('uponSanitizeElement', currentNode, {
      tagName: tagName,
      allowedTags: ALLOWED_TAGS
    });

    /* Detect mXSS attempts abusing namespace confusion */
    if (!_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
      _forceRemove(currentNode);
      return true;
    }

    /* Mitigate a problem with templates inside select */
    if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
      _forceRemove(currentNode);
      return true;
    }

    /* Remove element if anything forbids its presence */
    if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
      /* Keep content except for bad-listed elements */
      if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
        var parentNode = getParentNode(currentNode) || currentNode.parentNode;
        var childNodes = getChildNodes(currentNode) || currentNode.childNodes;

        if (childNodes && parentNode) {
          var childCount = childNodes.length;

          for (var i = childCount - 1; i >= 0; --i) {
            parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
          }
        }
      }

      _forceRemove(currentNode);
      return true;
    }

    /* Check whether element has a valid namespace */
    if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }

    if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
      _forceRemove(currentNode);
      return true;
    }

    /* Sanitize element content to be template-safe */
    if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
      /* Get the element's text content */
      content = currentNode.textContent;
      content = stringReplace(content, MUSTACHE_EXPR$$1, ' ');
      content = stringReplace(content, ERB_EXPR$$1, ' ');
      if (currentNode.textContent !== content) {
        arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
        currentNode.textContent = content;
      }
    }

    /* Execute a hook if present */
    _executeHook('afterSanitizeElements', currentNode, null);

    return false;
  };

  /**
   * _isValidAttribute
   *
   * @param  {string} lcTag Lowercase tag name of containing element.
   * @param  {string} lcName Lowercase attribute name.
   * @param  {string} value Attribute value.
   * @return {Boolean} Returns true if `value` is valid, otherwise false.
   */
  // eslint-disable-next-line complexity
  var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
    /* Make sure attribute cannot clobber */
    if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
      return false;
    }

    /* Allow valid data-* attributes: At least one character after "-"
        (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
        XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
        We don't need to check the value; it's always URI safe. */
    if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$$1, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
      return false;

      /* Check value is safe. First, is attr inert? If so, is safe */
    } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$$1, stringReplace(value, ATTR_WHITESPACE$$1, ''))) ; 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_DATA$$1, stringReplace(value, ATTR_WHITESPACE$$1, ''))) ; else if (!value) ; else {
      return false;
    }

    return true;
  };

  /**
   * _sanitizeAttributes
   *
   * @protect attributes
   * @protect nodeName
   * @protect removeAttribute
   * @protect setAttribute
   *
   * @param  {Node} currentNode to sanitize
   */
  var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
    var attr = void 0;
    var value = void 0;
    var lcName = void 0;
    var l = void 0;
    /* Execute a hook if present */
    _executeHook('beforeSanitizeAttributes', currentNode, null);

    var attributes = currentNode.attributes;

    /* Check if we have attributes; if not we might have a text node */

    if (!attributes) {
      return;
    }

    var hookEvent = {
      attrName: '',
      attrValue: '',
      keepAttr: true,
      allowedAttributes: ALLOWED_ATTR
    };
    l = attributes.length;

    /* Go backwards over all attributes; safely remove bad ones */
    while (l--) {
      attr = attributes[l];
      var _attr = attr,
          name = _attr.name,
          namespaceURI = _attr.namespaceURI;

      value = stringTrim(attr.value);
      lcName = stringToLowerCase(name);

      /* Execute a hook if present */
      hookEvent.attrName = lcName;
      hookEvent.attrValue = value;
      hookEvent.keepAttr = true;
      hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
      _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
      value = hookEvent.attrValue;
      /* Did the hooks approve of the attribute? */
      if (hookEvent.forceKeepAttr) {
        continue;
      }

      /* Remove attribute */
      _removeAttribute(name, currentNode);

      /* Did the hooks approve of the attribute? */
      if (!hookEvent.keepAttr) {
        continue;
      }

      /* Work around a security issue in jQuery 3.0 */
      if (regExpTest(/\/>/i, value)) {
        _removeAttribute(name, currentNode);
        continue;
      }

      /* Sanitize attribute content to be template-safe */
      if (SAFE_FOR_TEMPLATES) {
        value = stringReplace(value, MUSTACHE_EXPR$$1, ' ');
        value = stringReplace(value, ERB_EXPR$$1, ' ');
      }

      /* Is `value` valid for this attribute? */
      var lcTag = currentNode.nodeName.toLowerCase();
      if (!_isValidAttribute(lcTag, lcName, value)) {
        continue;
      }

      /* Handle invalid data-* attribute set by try-catching it */
      try {
        if (namespaceURI) {
          currentNode.setAttributeNS(namespaceURI, name, value);
        } else {
          /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
          currentNode.setAttribute(name, value);
        }

        arrayPop(DOMPurify.removed);
      } catch (_) {}
    }

    /* Execute a hook if present */
    _executeHook('afterSanitizeAttributes', currentNode, null);
  };

  /**
   * _sanitizeShadowDOM
   *
   * @param  {DocumentFragment} fragment to iterate over recursively
   */
  var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
    var shadowNode = void 0;
    var shadowIterator = _createIterator(fragment);

    /* Execute a hook if present */
    _executeHook('beforeSanitizeShadowDOM', fragment, null);

    while (shadowNode = shadowIterator.nextNode()) {
      /* Execute a hook if present */
      _executeHook('uponSanitizeShadowNode', shadowNode, null);

      /* Sanitize tags and elements */
      if (_sanitizeElements(shadowNode)) {
        continue;
      }

      /* Deep shadow DOM detected */
      if (shadowNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM(shadowNode.content);
      }

      /* Check attributes, sanitize if necessary */
      _sanitizeAttributes(shadowNode);
    }

    /* Execute a hook if present */
    _executeHook('afterSanitizeShadowDOM', fragment, null);
  };

  /**
   * Sanitize
   * Public method providing core sanitation functionality
   *
   * @param {String|Node} dirty string or DOM node
   * @param {Object} configuration object
   */
  // eslint-disable-next-line complexity
  DOMPurify.sanitize = function (dirty, cfg) {
    var body = void 0;
    var importedNode = void 0;
    var currentNode = void 0;
    var oldNode = void 0;
    var returnNode = void 0;
    /* Make sure we have a string to sanitize.
      DO NOT return early, as this will return the wrong type if
      the user has requested a DOM object rather than a string */
    IS_EMPTY_INPUT = !dirty;
    if (IS_EMPTY_INPUT) {
      dirty = '<!-->';
    }

    /* Stringify, in case dirty is an object */
    if (typeof dirty !== 'string' && !_isNode(dirty)) {
      // eslint-disable-next-line no-negated-condition
      if (typeof dirty.toString !== 'function') {
        throw typeErrorCreate('toString is not a function');
      } else {
        dirty = dirty.toString();
        if (typeof dirty !== 'string') {
          throw typeErrorCreate('dirty is not a string, aborting');
        }
      }
    }

    /* Check we can run. Otherwise fall back or ignore */
    if (!DOMPurify.isSupported) {
      if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
        if (typeof dirty === 'string') {
          return window.toStaticHTML(dirty);
        }

        if (_isNode(dirty)) {
          return window.toStaticHTML(dirty.outerHTML);
        }
      }

      return dirty;
    }

    /* Assign config vars */
    if (!SET_CONFIG) {
      _parseConfig(cfg);
    }

    /* Clean up removed elements */
    DOMPurify.removed = [];

    /* Check if dirty is correctly typed for IN_PLACE */
    if (typeof dirty === 'string') {
      IN_PLACE = false;
    }

    if (IN_PLACE) ; else if (dirty instanceof Node) {
      /* If dirty is a DOM element, append to an empty document to avoid
         elements being stripped by the parser */
      body = _initDocument('<!---->');
      importedNode = body.ownerDocument.importNode(dirty, true);
      if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
        /* Node is already a body, use as is */
        body = importedNode;
      } else if (importedNode.nodeName === 'HTML') {
        body = importedNode;
      } else {
        // eslint-disable-next-line unicorn/prefer-dom-node-append
        body.appendChild(importedNode);
      }
    } else {
      /* Exit directly if we have nothing to do */
      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;
      }

      /* Initialize the document to work on */
      body = _initDocument(dirty);

      /* Check we have a DOM node from the data */
      if (!body) {
        return RETURN_DOM ? null : emptyHTML;
      }
    }

    /* Remove first element node (ours) if FORCE_BODY is set */
    if (body && FORCE_BODY) {
      _forceRemove(body.firstChild);
    }

    /* Get node iterator */
    var nodeIterator = _createIterator(IN_PLACE ? dirty : body);

    /* Now start iterating over the created document */
    while (currentNode = nodeIterator.nextNode()) {
      /* Fix IE's strange behavior with manipulated textNodes #89 */
      if (currentNode.nodeType === 3 && currentNode === oldNode) {
        continue;
      }

      /* Sanitize tags and elements */
      if (_sanitizeElements(currentNode)) {
        continue;
      }

      /* Shadow DOM detected, sanitize it */
      if (currentNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM(currentNode.content);
      }

      /* Check attributes, sanitize if necessary */
      _sanitizeAttributes(currentNode);

      oldNode = currentNode;
    }

    oldNode = null;

    /* If we sanitized `dirty` in-place, return it. */
    if (IN_PLACE) {
      return dirty;
    }

    /* Return sanitized string or DOM */
    if (RETURN_DOM) {
      if (RETURN_DOM_FRAGMENT) {
        returnNode = createDocumentFragment.call(body.ownerDocument);

        while (body.firstChild) {
          // eslint-disable-next-line unicorn/prefer-dom-node-append
          returnNode.appendChild(body.firstChild);
        }
      } else {
        returnNode = body;
      }

      if (RETURN_DOM_IMPORT) {
        /*
          AdoptNode() is not used because internal state is not reset
          (e.g. the past names map of a HTMLFormElement), this is safe
          in theory but we would rather not risk another attack vector.
          The state that is cloned by importNode() is explicitly defined
          by the specs.
        */
        returnNode = importNode.call(originalDocument, returnNode, true);
      }

      return returnNode;
    }

    var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;

    /* Sanitize final string template-safe */
    if (SAFE_FOR_TEMPLATES) {
      serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$$1, ' ');
      serializedHTML = stringReplace(serializedHTML, ERB_EXPR$$1, ' ');
    }

    return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  };

  /**
   * Public method to set the configuration once
   * setConfig
   *
   * @param {Object} cfg configuration object
   */
  DOMPurify.setConfig = function (cfg) {
    _parseConfig(cfg);
    SET_CONFIG = true;
  };

  /**
   * Public method to remove the configuration
   * clearConfig
   *
   */
  DOMPurify.clearConfig = function () {
    CONFIG = null;
    SET_CONFIG = false;
  };

  /**
   * Public method to check if an attribute value is valid.
   * Uses last set config, if any. Otherwise, uses config defaults.
   * isValidAttribute
   *
   * @param  {string} tag Tag name of containing element.
   * @param  {string} attr Attribute name.
   * @param  {string} value Attribute value.
   * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
   */
  DOMPurify.isValidAttribute = function (tag, attr, value) {
    /* Initialize shared config vars if necessary. */
    if (!CONFIG) {
      _parseConfig({});
    }

    var lcTag = stringToLowerCase(tag);
    var lcName = stringToLowerCase(attr);
    return _isValidAttribute(lcTag, lcName, value);
  };

  /**
   * AddHook
   * Public method to add DOMPurify hooks
   *
   * @param {String} entryPoint entry point for the hook to add
   * @param {Function} hookFunction function to execute
   */
  DOMPurify.addHook = function (entryPoint, hookFunction) {
    if (typeof hookFunction !== 'function') {
      return;
    }

    hooks[entryPoint] = hooks[entryPoint] || [];
    arrayPush(hooks[entryPoint], hookFunction);
  };

  /**
   * RemoveHook
   * Public method to remove a DOMPurify hook at a given entryPoint
   * (pops it from the stack of hooks if more are present)
   *
   * @param {String} entryPoint entry point for the hook to remove
   */
  DOMPurify.removeHook = function (entryPoint) {
    if (hooks[entryPoint]) {
      arrayPop(hooks[entryPoint]);
    }
  };

  /**
   * RemoveHooks
   * Public method to remove all DOMPurify hooks at a given entryPoint
   *
   * @param  {String} entryPoint entry point for the hooks to remove
   */
  DOMPurify.removeHooks = function (entryPoint) {
    if (hooks[entryPoint]) {
      hooks[entryPoint] = [];
    }
  };

  /**
   * RemoveAllHooks
   * Public method to remove all DOMPurify hooks
   *
   */
  DOMPurify.removeAllHooks = function () {
    hooks = {};
  };

  return DOMPurify;
}

var purify = createDOMPurify();

// ESM-comment-begin
// define(function () { return purify; });
// ESM-comment-end

// ESM-uncomment-begin
/* harmony default export */ const dompurify = ((/* unused pure expression or super */ null && (purify)));
const version = purify.version;
const isSupported = purify.isSupported;
const sanitize = purify.sanitize;
const setConfig = purify.setConfig;
const clearConfig = purify.clearConfig;
const isValidAttribute = purify.isValidAttribute;
const addHook = purify.addHook;
const removeHook = purify.removeHook;
const removeHooks = purify.removeHooks;
const removeAllHooks = purify.removeAllHooks;
// ESM-uncomment-end

;// ../../node_modules/monaco-editor/esm/vs/base/common/process.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

let safeProcess;
// Native sandbox environment
if (typeof platform_globals.vscode !== 'undefined' && typeof platform_globals.vscode.process !== 'undefined') {
    const sandboxProcess = platform_globals.vscode.process;
    safeProcess = {
        get platform() { return sandboxProcess.platform; },
        get arch() { return sandboxProcess.arch; },
        get env() { return sandboxProcess.env; },
        cwd() { return sandboxProcess.cwd(); }
    };
}
// Native node.js environment
else if (typeof process !== 'undefined') {
    safeProcess = {
        get platform() { return process.platform; },
        get arch() { return process.arch; },
        get env() { return process.env; },
        cwd() { return process.env['VSCODE_CWD'] || process.cwd(); }
    };
}
// Web environment
else {
    safeProcess = {
        // Supported
        get platform() { return isWindows ? 'win32' : isMacintosh ? 'darwin' : 'linux'; },
        get arch() { return undefined; /* arch is undefined in web */ },
        // Unsupported
        get env() { return {}; },
        cwd() { return '/'; }
    };
}
/**
 * Provides safe access to the `cwd` property in node.js, sandboxed or web
 * environments.
 *
 * Note: in web, this property is hardcoded to be `/`.
 */
const cwd = safeProcess.cwd;
/**
 * Provides safe access to the `env` property in node.js, sandboxed or web
 * environments.
 *
 * Note: in web, this property is hardcoded to be `{}`.
 */
const env = safeProcess.env;
/**
 * Provides safe access to the `platform` property in node.js, sandboxed or web
 * environments.
 */
const process_platform = safeProcess.platform;

;// ../../node_modules/monaco-editor/esm/vs/base/common/path.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
// NOTE: VSCode's copy of nodejs path library to be usable in common (non-node) namespace
// Copied from: https://github.com/nodejs/node/blob/v14.16.0/lib/path.js
/**
 * Copyright Joyent, Inc. and other Node contributors.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the
 * following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
 * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

const CHAR_UPPERCASE_A = 65; /* A */
const CHAR_LOWERCASE_A = 97; /* a */
const CHAR_UPPERCASE_Z = 90; /* Z */
const CHAR_LOWERCASE_Z = 122; /* z */
const CHAR_DOT = 46; /* . */
const CHAR_FORWARD_SLASH = 47; /* / */
const CHAR_BACKWARD_SLASH = 92; /* \ */
const CHAR_COLON = 58; /* : */
const CHAR_QUESTION_MARK = 63; /* ? */
class ErrorInvalidArgType extends Error {
    constructor(name, expected, actual) {
        // determiner: 'must be' or 'must not be'
        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 validateString(value, name) {
    if (typeof value !== 'string') {
        throw new ErrorInvalidArgType(name, 'string', value);
    }
}
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);
}
// Resolves . and .. elements in a path with directory names
function normalizeString(path, allowAboveRoot, separator, isPathSeparator) {
    let res = '';
    let lastSegmentLength = 0;
    let lastSlash = -1;
    let dots = 0;
    let code = 0;
    for (let i = 0; i <= path.length; ++i) {
        if (i < path.length) {
            code = path.charCodeAt(i);
        }
        else if (isPathSeparator(code)) {
            break;
        }
        else {
            code = CHAR_FORWARD_SLASH;
        }
        if (isPathSeparator(code)) {
            if (lastSlash === i - 1 || dots === 1) {
                // NOOP
            }
            else if (dots === 2) {
                if (res.length < 2 || lastSegmentLength !== 2 ||
                    res.charCodeAt(res.length - 1) !== CHAR_DOT ||
                    res.charCodeAt(res.length - 2) !== CHAR_DOT) {
                    if (res.length > 2) {
                        const lastSlashIndex = res.lastIndexOf(separator);
                        if (lastSlashIndex === -1) {
                            res = '';
                            lastSegmentLength = 0;
                        }
                        else {
                            res = res.slice(0, lastSlashIndex);
                            lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
                        }
                        lastSlash = i;
                        dots = 0;
                        continue;
                    }
                    else if (res.length !== 0) {
                        res = '';
                        lastSegmentLength = 0;
                        lastSlash = i;
                        dots = 0;
                        continue;
                    }
                }
                if (allowAboveRoot) {
                    res += res.length > 0 ? `${separator}..` : '..';
                    lastSegmentLength = 2;
                }
            }
            else {
                if (res.length > 0) {
                    res += `${separator}${path.slice(lastSlash + 1, i)}`;
                }
                else {
                    res = path.slice(lastSlash + 1, i);
                }
                lastSegmentLength = i - lastSlash - 1;
            }
            lastSlash = i;
            dots = 0;
        }
        else if (code === CHAR_DOT && dots !== -1) {
            ++dots;
        }
        else {
            dots = -1;
        }
    }
    return res;
}
function path_format(sep, pathObject) {
    if (pathObject === null || typeof pathObject !== 'object') {
        throw new ErrorInvalidArgType('pathObject', 'Object', pathObject);
    }
    const dir = pathObject.dir || pathObject.root;
    const base = pathObject.base ||
        `${pathObject.name || ''}${pathObject.ext || ''}`;
    if (!dir) {
        return base;
    }
    return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep}${base}`;
}
const win32 = {
    // path.resolve([from ...], to)
    resolve(...pathSegments) {
        let resolvedDevice = '';
        let resolvedTail = '';
        let resolvedAbsolute = false;
        for (let i = pathSegments.length - 1; i >= -1; i--) {
            let path;
            if (i >= 0) {
                path = pathSegments[i];
                validateString(path, 'path');
                // Skip empty entries
                if (path.length === 0) {
                    continue;
                }
            }
            else if (resolvedDevice.length === 0) {
                path = cwd();
            }
            else {
                // Windows has the concept of drive-specific current working
                // directories. If we've resolved a drive letter but not yet an
                // absolute path, get cwd for that drive, or the process cwd if
                // the drive cwd is not available. We're sure the device is not
                // a UNC path at this points, because UNC paths are always absolute.
                path = env[`=${resolvedDevice}`] || cwd();
                // Verify that a cwd was found and that it actually points
                // to our drive. If not, default to the drive's root.
                if (path === undefined ||
                    (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);
            // Try to match a root
            if (len === 1) {
                if (isPathSeparator(code)) {
                    // `path` contains just a path separator
                    rootEnd = 1;
                    isAbsolute = true;
                }
            }
            else if (isPathSeparator(code)) {
                // Possible UNC root
                // If we started with a separator, we know we at least have an
                // absolute path of some kind (UNC or otherwise)
                isAbsolute = true;
                if (isPathSeparator(path.charCodeAt(1))) {
                    // Matched double path separator at beginning
                    let j = 2;
                    let last = j;
                    // Match 1 or more non-path separators
                    while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                        j++;
                    }
                    if (j < len && j !== last) {
                        const firstPart = path.slice(last, j);
                        // Matched!
                        last = j;
                        // Match 1 or more path separators
                        while (j < len && isPathSeparator(path.charCodeAt(j))) {
                            j++;
                        }
                        if (j < len && j !== last) {
                            // Matched!
                            last = j;
                            // Match 1 or more non-path separators
                            while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                                j++;
                            }
                            if (j === len || j !== last) {
                                // We matched a UNC root
                                device = `\\\\${firstPart}\\${path.slice(last, j)}`;
                                rootEnd = j;
                            }
                        }
                    }
                }
                else {
                    rootEnd = 1;
                }
            }
            else if (isWindowsDeviceRoot(code) &&
                path.charCodeAt(1) === CHAR_COLON) {
                // Possible device root
                device = path.slice(0, 2);
                rootEnd = 2;
                if (len > 2 && isPathSeparator(path.charCodeAt(2))) {
                    // Treat separator following drive name as an absolute path
                    // indicator
                    isAbsolute = true;
                    rootEnd = 3;
                }
            }
            if (device.length > 0) {
                if (resolvedDevice.length > 0) {
                    if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
                        // This path points to another device so it is not applicable
                        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;
                }
            }
        }
        // At this point the path should be resolved to a full absolute path,
        // but handle relative paths to be safe (might happen when process.cwd()
        // fails)
        // Normalize the tail path
        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);
        // Try to match a root
        if (len === 1) {
            // `path` contains just a single char, exit early to avoid
            // unnecessary work
            return isPosixPathSeparator(code) ? '\\' : path;
        }
        if (isPathSeparator(code)) {
            // Possible UNC root
            // If we started with a separator, we know we at least have an absolute
            // path of some kind (UNC or otherwise)
            isAbsolute = true;
            if (isPathSeparator(path.charCodeAt(1))) {
                // Matched double path separator at beginning
                let j = 2;
                let last = j;
                // Match 1 or more non-path separators
                while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                    j++;
                }
                if (j < len && j !== last) {
                    const firstPart = path.slice(last, j);
                    // Matched!
                    last = j;
                    // Match 1 or more path separators
                    while (j < len && isPathSeparator(path.charCodeAt(j))) {
                        j++;
                    }
                    if (j < len && j !== last) {
                        // Matched!
                        last = j;
                        // Match 1 or more non-path separators
                        while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                            j++;
                        }
                        if (j === len) {
                            // We matched a UNC root only
                            // Return the normalized version of the UNC root since there
                            // is nothing left to process
                            return `\\\\${firstPart}\\${path.slice(last)}\\`;
                        }
                        if (j !== last) {
                            // We matched a UNC root with leftovers
                            device = `\\\\${firstPart}\\${path.slice(last, j)}`;
                            rootEnd = j;
                        }
                    }
                }
            }
            else {
                rootEnd = 1;
            }
        }
        else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
            // Possible device root
            device = path.slice(0, 2);
            rootEnd = 2;
            if (len > 2 && isPathSeparator(path.charCodeAt(2))) {
                // Treat separator following drive name as an absolute path
                // indicator
                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 === undefined) {
            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 i = 0; i < paths.length; ++i) {
            const arg = paths[i];
            validateString(arg, 'path');
            if (arg.length > 0) {
                if (joined === undefined) {
                    joined = firstPart = arg;
                }
                else {
                    joined += `\\${arg}`;
                }
            }
        }
        if (joined === undefined) {
            return '.';
        }
        // Make sure that the joined path doesn't start with two slashes, because
        // normalize() will mistake it for a UNC path then.
        //
        // This step is skipped when it is very clear that the user actually
        // intended to point at a UNC path. This is assumed when the first
        // non-empty string arguments starts with exactly two slashes followed by
        // at least one more non-slash character.
        //
        // Note that for normalize() to treat a path as a UNC path it needs to
        // have at least 2 components, so we don't filter for that here.
        // This means that the user can use join to construct UNC paths from
        // a server name and a share name; for example:
        //   path.join('//server', 'share') -> '\\\\server\\share\\')
        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 {
                        // We matched a UNC path in the first part
                        needsReplace = false;
                    }
                }
            }
        }
        if (needsReplace) {
            // Find any more consecutive slashes we need to replace
            while (slashCount < joined.length &&
                isPathSeparator(joined.charCodeAt(slashCount))) {
                slashCount++;
            }
            // Replace the slashes if needed
            if (slashCount >= 2) {
                joined = `\\${joined.slice(slashCount)}`;
            }
        }
        return win32.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 = win32.resolve(from);
        const toOrig = win32.resolve(to);
        if (fromOrig === toOrig) {
            return '';
        }
        from = fromOrig.toLowerCase();
        to = toOrig.toLowerCase();
        if (from === to) {
            return '';
        }
        // Trim any leading backslashes
        let fromStart = 0;
        while (fromStart < from.length &&
            from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
            fromStart++;
        }
        // Trim trailing backslashes (applicable to UNC paths only)
        let fromEnd = from.length;
        while (fromEnd - 1 > fromStart &&
            from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
            fromEnd--;
        }
        const fromLen = fromEnd - fromStart;
        // Trim any leading backslashes
        let toStart = 0;
        while (toStart < to.length &&
            to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
            toStart++;
        }
        // Trim trailing backslashes (applicable to UNC paths only)
        let toEnd = to.length;
        while (toEnd - 1 > toStart &&
            to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
            toEnd--;
        }
        const toLen = toEnd - toStart;
        // Compare paths to find the longest common path from root
        const length = fromLen < toLen ? fromLen : toLen;
        let lastCommonSep = -1;
        let i = 0;
        for (; i < length; i++) {
            const fromCode = from.charCodeAt(fromStart + i);
            if (fromCode !== to.charCodeAt(toStart + i)) {
                break;
            }
            else if (fromCode === CHAR_BACKWARD_SLASH) {
                lastCommonSep = i;
            }
        }
        // We found a mismatch before the first common path separator was seen, so
        // return the original `to`.
        if (i !== length) {
            if (lastCommonSep === -1) {
                return toOrig;
            }
        }
        else {
            if (toLen > length) {
                if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
                    // We get here if `from` is the exact base path for `to`.
                    // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz'
                    return toOrig.slice(toStart + i + 1);
                }
                if (i === 2) {
                    // We get here if `from` is the device root.
                    // For example: from='C:\\'; to='C:\\foo'
                    return toOrig.slice(toStart + i);
                }
            }
            if (fromLen > length) {
                if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
                    // We get here if `to` is the exact base path for `from`.
                    // For example: from='C:\\foo\\bar'; to='C:\\foo'
                    lastCommonSep = i;
                }
                else if (i === 2) {
                    // We get here if `to` is the device root.
                    // For example: from='C:\\foo\\bar'; to='C:\\'
                    lastCommonSep = 3;
                }
            }
            if (lastCommonSep === -1) {
                lastCommonSep = 0;
            }
        }
        let out = '';
        // Generate the relative path based on the path difference between `to` and
        // `from`
        for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
            if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
                out += out.length === 0 ? '..' : '\\..';
            }
        }
        toStart += lastCommonSep;
        // Lastly, append the rest of the destination (`to`) path that comes after
        // the common path parts
        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) {
        // Note: this will *probably* throw somewhere.
        if (typeof path !== 'string') {
            return path;
        }
        if (path.length === 0) {
            return '';
        }
        const resolvedPath = win32.resolve(path);
        if (resolvedPath.length <= 2) {
            return path;
        }
        if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
            // Possible UNC root
            if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
                const code = resolvedPath.charCodeAt(2);
                if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
                    // Matched non-long UNC root, convert the path to a long UNC path
                    return `\\\\?\\UNC\\${resolvedPath.slice(2)}`;
                }
            }
        }
        else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
            resolvedPath.charCodeAt(1) === CHAR_COLON &&
            resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
            // Matched device root, convert the path to a long UNC path
            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) {
            // `path` contains just a path separator, exit early to avoid
            // unnecessary work or a dot.
            return isPathSeparator(code) ? path : '.';
        }
        // Try to match a root
        if (isPathSeparator(code)) {
            // Possible UNC root
            rootEnd = offset = 1;
            if (isPathSeparator(path.charCodeAt(1))) {
                // Matched double path separator at beginning
                let j = 2;
                let last = j;
                // Match 1 or more non-path separators
                while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                    j++;
                }
                if (j < len && j !== last) {
                    // Matched!
                    last = j;
                    // Match 1 or more path separators
                    while (j < len && isPathSeparator(path.charCodeAt(j))) {
                        j++;
                    }
                    if (j < len && j !== last) {
                        // Matched!
                        last = j;
                        // Match 1 or more non-path separators
                        while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                            j++;
                        }
                        if (j === len) {
                            // We matched a UNC root only
                            return path;
                        }
                        if (j !== last) {
                            // We matched a UNC root with leftovers
                            // Offset by 1 to include the separator after the UNC root to
                            // treat it as a "normal root" on top of a (UNC) root
                            rootEnd = offset = j + 1;
                        }
                    }
                }
            }
            // Possible device root
        }
        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 i = len - 1; i >= offset; --i) {
            if (isPathSeparator(path.charCodeAt(i))) {
                if (!matchedSlash) {
                    end = i;
                    break;
                }
            }
            else {
                // We saw the first non-path separator
                matchedSlash = false;
            }
        }
        if (end === -1) {
            if (rootEnd === -1) {
                return '.';
            }
            end = rootEnd;
        }
        return path.slice(0, end);
    },
    basename(path, ext) {
        if (ext !== undefined) {
            validateString(ext, 'ext');
        }
        validateString(path, 'path');
        let start = 0;
        let end = -1;
        let matchedSlash = true;
        let i;
        // Check for a drive letter prefix so as not to mistake the following
        // path separator as an extra separator at the end of the path that can be
        // disregarded
        if (path.length >= 2 &&
            isWindowsDeviceRoot(path.charCodeAt(0)) &&
            path.charCodeAt(1) === CHAR_COLON) {
            start = 2;
        }
        if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
            if (ext === path) {
                return '';
            }
            let extIdx = ext.length - 1;
            let firstNonSlashEnd = -1;
            for (i = path.length - 1; i >= start; --i) {
                const code = path.charCodeAt(i);
                if (isPathSeparator(code)) {
                    // If we reached a path separator that was not part of a set of path
                    // separators at the end of the string, stop now
                    if (!matchedSlash) {
                        start = i + 1;
                        break;
                    }
                }
                else {
                    if (firstNonSlashEnd === -1) {
                        // We saw the first non-path separator, remember this index in case
                        // we need it if the extension ends up not matching
                        matchedSlash = false;
                        firstNonSlashEnd = i + 1;
                    }
                    if (extIdx >= 0) {
                        // Try to match the explicit extension
                        if (code === ext.charCodeAt(extIdx)) {
                            if (--extIdx === -1) {
                                // We matched the extension, so mark this as the end of our path
                                // component
                                end = i;
                            }
                        }
                        else {
                            // Extension does not match, so our result is the entire path
                            // component
                            extIdx = -1;
                            end = firstNonSlashEnd;
                        }
                    }
                }
            }
            if (start === end) {
                end = firstNonSlashEnd;
            }
            else if (end === -1) {
                end = path.length;
            }
            return path.slice(start, end);
        }
        for (i = path.length - 1; i >= start; --i) {
            if (isPathSeparator(path.charCodeAt(i))) {
                // If we reached a path separator that was not part of a set of path
                // separators at the end of the string, stop now
                if (!matchedSlash) {
                    start = i + 1;
                    break;
                }
            }
            else if (end === -1) {
                // We saw the first non-path separator, mark this as the end of our
                // path component
                matchedSlash = false;
                end = i + 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;
        // Track the state of characters (if any) we see before our first dot and
        // after any path separator we find
        let preDotState = 0;
        // Check for a drive letter prefix so as not to mistake the following
        // path separator as an extra separator at the end of the path that can be
        // disregarded
        if (path.length >= 2 &&
            path.charCodeAt(1) === CHAR_COLON &&
            isWindowsDeviceRoot(path.charCodeAt(0))) {
            start = startPart = 2;
        }
        for (let i = path.length - 1; i >= start; --i) {
            const code = path.charCodeAt(i);
            if (isPathSeparator(code)) {
                // If we reached a path separator that was not part of a set of path
                // separators at the end of the string, stop now
                if (!matchedSlash) {
                    startPart = i + 1;
                    break;
                }
                continue;
            }
            if (end === -1) {
                // We saw the first non-path separator, mark this as the end of our
                // extension
                matchedSlash = false;
                end = i + 1;
            }
            if (code === CHAR_DOT) {
                // If this is our first dot, mark it as the start of our extension
                if (startDot === -1) {
                    startDot = i;
                }
                else if (preDotState !== 1) {
                    preDotState = 1;
                }
            }
            else if (startDot !== -1) {
                // We saw a non-dot and non-path separator before our dot, so we should
                // have a good chance at having a non-empty extension
                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: path_format.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)) {
                // `path` contains just a path separator, exit early to avoid
                // unnecessary work
                ret.root = ret.dir = path;
                return ret;
            }
            ret.base = ret.name = path;
            return ret;
        }
        // Try to match a root
        if (isPathSeparator(code)) {
            // Possible UNC root
            rootEnd = 1;
            if (isPathSeparator(path.charCodeAt(1))) {
                // Matched double path separator at beginning
                let j = 2;
                let last = j;
                // Match 1 or more non-path separators
                while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                    j++;
                }
                if (j < len && j !== last) {
                    // Matched!
                    last = j;
                    // Match 1 or more path separators
                    while (j < len && isPathSeparator(path.charCodeAt(j))) {
                        j++;
                    }
                    if (j < len && j !== last) {
                        // Matched!
                        last = j;
                        // Match 1 or more non-path separators
                        while (j < len && !isPathSeparator(path.charCodeAt(j))) {
                            j++;
                        }
                        if (j === len) {
                            // We matched a UNC root only
                            rootEnd = j;
                        }
                        else if (j !== last) {
                            // We matched a UNC root with leftovers
                            rootEnd = j + 1;
                        }
                    }
                }
            }
        }
        else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
            // Possible device root
            if (len <= 2) {
                // `path` contains just a drive root, exit early to avoid
                // unnecessary work
                ret.root = ret.dir = path;
                return ret;
            }
            rootEnd = 2;
            if (isPathSeparator(path.charCodeAt(2))) {
                if (len === 3) {
                    // `path` contains just a drive root, exit early to avoid
                    // unnecessary work
                    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 i = path.length - 1;
        // Track the state of characters (if any) we see before our first dot and
        // after any path separator we find
        let preDotState = 0;
        // Get non-dir info
        for (; i >= rootEnd; --i) {
            code = path.charCodeAt(i);
            if (isPathSeparator(code)) {
                // If we reached a path separator that was not part of a set of path
                // separators at the end of the string, stop now
                if (!matchedSlash) {
                    startPart = i + 1;
                    break;
                }
                continue;
            }
            if (end === -1) {
                // We saw the first non-path separator, mark this as the end of our
                // extension
                matchedSlash = false;
                end = i + 1;
            }
            if (code === CHAR_DOT) {
                // If this is our first dot, mark it as the start of our extension
                if (startDot === -1) {
                    startDot = i;
                }
                else if (preDotState !== 1) {
                    preDotState = 1;
                }
            }
            else if (startDot !== -1) {
                // We saw a non-dot and non-path separator before our dot, so we should
                // have a good chance at having a non-empty extension
                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 the directory is the root, use the entire root as the `dir` including
        // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the
        // trailing slash (`C:\abc\def` -> `C:\abc`).
        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
};
const posix = {
    // path.resolve([from ...], to)
    resolve(...pathSegments) {
        let resolvedPath = '';
        let resolvedAbsolute = false;
        for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
            const path = i >= 0 ? pathSegments[i] : cwd();
            validateString(path, 'path');
            // Skip empty entries
            if (path.length === 0) {
                continue;
            }
            resolvedPath = `${path}/${resolvedPath}`;
            resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
        }
        // At this point the path should be resolved to a full absolute path, but
        // handle relative paths to be safe (might happen when process.cwd() fails)
        // Normalize the path
        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;
        // Normalize the path
        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 i = 0; i < paths.length; ++i) {
            const arg = paths[i];
            validateString(arg, 'path');
            if (arg.length > 0) {
                if (joined === undefined) {
                    joined = arg;
                }
                else {
                    joined += `/${arg}`;
                }
            }
        }
        if (joined === undefined) {
            return '.';
        }
        return posix.normalize(joined);
    },
    relative(from, to) {
        validateString(from, 'from');
        validateString(to, 'to');
        if (from === to) {
            return '';
        }
        // Trim leading forward slashes.
        from = posix.resolve(from);
        to = posix.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;
        // Compare paths to find the longest common path from root
        const length = (fromLen < toLen ? fromLen : toLen);
        let lastCommonSep = -1;
        let i = 0;
        for (; i < length; i++) {
            const fromCode = from.charCodeAt(fromStart + i);
            if (fromCode !== to.charCodeAt(toStart + i)) {
                break;
            }
            else if (fromCode === CHAR_FORWARD_SLASH) {
                lastCommonSep = i;
            }
        }
        if (i === length) {
            if (toLen > length) {
                if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
                    // We get here if `from` is the exact base path for `to`.
                    // For example: from='/foo/bar'; to='/foo/bar/baz'
                    return to.slice(toStart + i + 1);
                }
                if (i === 0) {
                    // We get here if `from` is the root
                    // For example: from='/'; to='/foo'
                    return to.slice(toStart + i);
                }
            }
            else if (fromLen > length) {
                if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
                    // We get here if `to` is the exact base path for `from`.
                    // For example: from='/foo/bar/baz'; to='/foo/bar'
                    lastCommonSep = i;
                }
                else if (i === 0) {
                    // We get here if `to` is the root.
                    // For example: from='/foo/bar'; to='/'
                    lastCommonSep = 0;
                }
            }
        }
        let out = '';
        // Generate the relative path based on the path difference between `to`
        // and `from`.
        for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
            if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
                out += out.length === 0 ? '..' : '/..';
            }
        }
        // Lastly, append the rest of the destination (`to`) path that comes after
        // the common path parts.
        return `${out}${to.slice(toStart + lastCommonSep)}`;
    },
    toNamespacedPath(path) {
        // Non-op on posix systems
        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 i = path.length - 1; i >= 1; --i) {
            if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
                if (!matchedSlash) {
                    end = i;
                    break;
                }
            }
            else {
                // We saw the first non-path separator
                matchedSlash = false;
            }
        }
        if (end === -1) {
            return hasRoot ? '/' : '.';
        }
        if (hasRoot && end === 1) {
            return '//';
        }
        return path.slice(0, end);
    },
    basename(path, ext) {
        if (ext !== undefined) {
            validateString(ext, 'ext');
        }
        validateString(path, 'path');
        let start = 0;
        let end = -1;
        let matchedSlash = true;
        let i;
        if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
            if (ext === path) {
                return '';
            }
            let extIdx = ext.length - 1;
            let firstNonSlashEnd = -1;
            for (i = path.length - 1; i >= 0; --i) {
                const code = path.charCodeAt(i);
                if (code === CHAR_FORWARD_SLASH) {
                    // If we reached a path separator that was not part of a set of path
                    // separators at the end of the string, stop now
                    if (!matchedSlash) {
                        start = i + 1;
                        break;
                    }
                }
                else {
                    if (firstNonSlashEnd === -1) {
                        // We saw the first non-path separator, remember this index in case
                        // we need it if the extension ends up not matching
                        matchedSlash = false;
                        firstNonSlashEnd = i + 1;
                    }
                    if (extIdx >= 0) {
                        // Try to match the explicit extension
                        if (code === ext.charCodeAt(extIdx)) {
                            if (--extIdx === -1) {
                                // We matched the extension, so mark this as the end of our path
                                // component
                                end = i;
                            }
                        }
                        else {
                            // Extension does not match, so our result is the entire path
                            // component
                            extIdx = -1;
                            end = firstNonSlashEnd;
                        }
                    }
                }
            }
            if (start === end) {
                end = firstNonSlashEnd;
            }
            else if (end === -1) {
                end = path.length;
            }
            return path.slice(start, end);
        }
        for (i = path.length - 1; i >= 0; --i) {
            if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
                // If we reached a path separator that was not part of a set of path
                // separators at the end of the string, stop now
                if (!matchedSlash) {
                    start = i + 1;
                    break;
                }
            }
            else if (end === -1) {
                // We saw the first non-path separator, mark this as the end of our
                // path component
                matchedSlash = false;
                end = i + 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;
        // Track the state of characters (if any) we see before our first dot and
        // after any path separator we find
        let preDotState = 0;
        for (let i = path.length - 1; i >= 0; --i) {
            const code = path.charCodeAt(i);
            if (code === CHAR_FORWARD_SLASH) {
                // If we reached a path separator that was not part of a set of path
                // separators at the end of the string, stop now
                if (!matchedSlash) {
                    startPart = i + 1;
                    break;
                }
                continue;
            }
            if (end === -1) {
                // We saw the first non-path separator, mark this as the end of our
                // extension
                matchedSlash = false;
                end = i + 1;
            }
            if (code === CHAR_DOT) {
                // If this is our first dot, mark it as the start of our extension
                if (startDot === -1) {
                    startDot = i;
                }
                else if (preDotState !== 1) {
                    preDotState = 1;
                }
            }
            else if (startDot !== -1) {
                // We saw a non-dot and non-path separator before our dot, so we should
                // have a good chance at having a non-empty extension
                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: path_format.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 i = path.length - 1;
        // Track the state of characters (if any) we see before our first dot and
        // after any path separator we find
        let preDotState = 0;
        // Get non-dir info
        for (; i >= start; --i) {
            const code = path.charCodeAt(i);
            if (code === CHAR_FORWARD_SLASH) {
                // If we reached a path separator that was not part of a set of path
                // separators at the end of the string, stop now
                if (!matchedSlash) {
                    startPart = i + 1;
                    break;
                }
                continue;
            }
            if (end === -1) {
                // We saw the first non-path separator, mark this as the end of our
                // extension
                matchedSlash = false;
                end = i + 1;
            }
            if (code === CHAR_DOT) {
                // If this is our first dot, mark it as the start of our extension
                if (startDot === -1) {
                    startDot = i;
                }
                else if (preDotState !== 1) {
                    preDotState = 1;
                }
            }
            else if (startDot !== -1) {
                // We saw a non-dot and non-path separator before our dot, so we should
                // have a good chance at having a non-empty extension
                preDotState = -1;
            }
        }
        if (end !== -1) {
            const start = 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(start, end);
            }
            else {
                ret.name = path.slice(start, startDot);
                ret.base = path.slice(start, 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
};
posix.win32 = win32.win32 = win32;
posix.posix = win32.posix = posix;
const normalize = (process_platform === 'win32' ? win32.normalize : posix.normalize);
const resolve = (process_platform === 'win32' ? win32.resolve : posix.resolve);
const relative = (process_platform === 'win32' ? win32.relative : posix.relative);
const path_dirname = (process_platform === 'win32' ? win32.dirname : posix.dirname);
const basename = (process_platform === 'win32' ? win32.basename : posix.basename);
const extname = (process_platform === 'win32' ? win32.extname : posix.extname);
const path_sep = (process_platform === 'win32' ? win32.sep : posix.sep);

;// ../../node_modules/monaco-editor/esm/vs/base/common/uri.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


const _schemePattern = /^\w[\w\d+.-]*$/;
const _singleSlashStart = /^\//;
const _doubleSlashStart = /^\/\//;
function _validateUri(ret, _strict) {
    // scheme, must be set
    if (!ret.scheme && _strict) {
        throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`);
    }
    // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
    // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
    if (ret.scheme && !_schemePattern.test(ret.scheme)) {
        throw new Error('[UriError]: Scheme contains illegal characters.');
    }
    // path, http://tools.ietf.org/html/rfc3986#section-3.3
    // If a URI contains an authority component, then the path component
    // must either be empty or begin with a slash ("/") character.  If a URI
    // does not contain an authority component, then the path cannot begin
    // with two slash 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 ("//")');
            }
        }
    }
}
// for a while we allowed uris *without* schemes and this is the migration
// for them, e.g. an uri without scheme and without strict-mode warns and falls
// back to the file-scheme. that should cause the least carnage and still be a
// clear warning
function _schemeFix(scheme, _strict) {
    if (!scheme && !_strict) {
        return 'file';
    }
    return scheme;
}
// implements a bit of https://tools.ietf.org/html/rfc3986#section-5
function _referenceResolution(scheme, path) {
    // the slash-character is our 'default base' as we don't
    // support constructing URIs relative to other URIs. This
    // also means that we alter and potentially break paths.
    // see https://tools.ietf.org/html/rfc3986#section-5.1.4
    switch (scheme) {
        case 'https':
        case 'http':
        case 'file':
            if (!path) {
                path = _slash;
            }
            else if (path[0] !== _slash) {
                path = _slash + path;
            }
            break;
    }
    return path;
}
const _empty = '';
const _slash = '/';
const _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
/**
 * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
 * This class is a simple parser which creates the basic component parts
 * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
 * and encoding.
 *
 * ```txt
 *       foo://example.com:8042/over/there?name=ferret#nose
 *       \_/   \______________/\_________/ \_________/ \__/
 *        |           |            |            |        |
 *     scheme     authority       path        query   fragment
 *        |   _____________________|__
 *       / \ /                        \
 *       urn:example:animal:ferret:nose
 * ```
 */
class URI {
    /**
     * @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;
            // no validation because it's this URI
            // that creates uri components.
            // _validateUri(this);
        }
        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);
        }
    }
    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';
    }
    // ---- 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() {
        // if (this.scheme !== 'file') {
        // 	console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
        // }
        return uriToFsPath(this, false);
    }
    // ---- modify to new -------------------------
    with(change) {
        if (!change) {
            return this;
        }
        let { scheme, authority, path, query, fragment } = change;
        if (scheme === undefined) {
            scheme = this.scheme;
        }
        else if (scheme === null) {
            scheme = _empty;
        }
        if (authority === undefined) {
            authority = this.authority;
        }
        else if (authority === null) {
            authority = _empty;
        }
        if (path === undefined) {
            path = this.path;
        }
        else if (path === null) {
            path = _empty;
        }
        if (query === undefined) {
            query = this.query;
        }
        else if (query === null) {
            query = _empty;
        }
        if (fragment === undefined) {
            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;
        // normalize to fwd-slashes on windows,
        // on other systems bwd-slashes are valid
        // filename character, eg /f\oo/ba\r.txt
        if (isWindows) {
            path = path.replace(/\\/g, _slash);
        }
        // check for authority as used in UNC shares
        // or use the path as given
        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);
    }
    static from(components) {
        const result = new Uri(components.scheme, components.authority, components.path, components.query, components.fragment);
        _validateUri(result, true);
        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 (isWindows && uri.scheme === 'file') {
            newPath = URI.file(win32.join(uriToFsPath(uri, true), ...pathFragment)).path;
        }
        else {
            newPath = posix.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;
            result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null;
            return result;
        }
    }
}
const _pathSepMarker = isWindows ? 1 : undefined;
// This class exists so that URI is compatible with vscode.Uri (API).
class Uri extends URI {
    constructor() {
        super(...arguments);
        this._formatted = null;
        this._fsPath = null;
    }
    get fsPath() {
        if (!this._fsPath) {
            this._fsPath = uriToFsPath(this, false);
        }
        return this._fsPath;
    }
    toString(skipEncoding = false) {
        if (!skipEncoding) {
            if (!this._formatted) {
                this._formatted = _asFormatted(this, false);
            }
            return this._formatted;
        }
        else {
            // we don't cache that
            return _asFormatted(this, true);
        }
    }
    toJSON() {
        const res = {
            $mid: 1 /* MarshalledId.Uri */
        };
        // cached state
        if (this._fsPath) {
            res.fsPath = this._fsPath;
            res._sep = _pathSepMarker;
        }
        if (this._formatted) {
            res.external = this._formatted;
        }
        // uri components
        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;
    }
}
// reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
const encodeTable = {
    [58 /* CharCode.Colon */]: '%3A',
    [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',
    [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, allowSlash) {
    let res = undefined;
    let nativeEncodePos = -1;
    for (let pos = 0; pos < uriComponent.length; pos++) {
        const code = uriComponent.charCodeAt(pos);
        // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
        if ((code >= 97 /* CharCode.a */ && code <= 122 /* CharCode.z */)
            || (code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */)
            || (code >= 48 /* CharCode.Digit0 */ && code <= 57 /* CharCode.Digit9 */)
            || code === 45 /* CharCode.Dash */
            || code === 46 /* CharCode.Period */
            || code === 95 /* CharCode.Underline */
            || code === 126 /* CharCode.Tilde */
            || (allowSlash && code === 47 /* CharCode.Slash */)) {
            // check if we are delaying native encode
            if (nativeEncodePos !== -1) {
                res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
                nativeEncodePos = -1;
            }
            // check if we write into a new string (by default we try to return the param)
            if (res !== undefined) {
                res += uriComponent.charAt(pos);
            }
        }
        else {
            // encoding needed, we need to allocate a new string
            if (res === undefined) {
                res = uriComponent.substr(0, pos);
            }
            // check with default table first
            const escaped = encodeTable[code];
            if (escaped !== undefined) {
                // check if we are delaying native encode
                if (nativeEncodePos !== -1) {
                    res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
                    nativeEncodePos = -1;
                }
                // append escaped variant to result
                res += escaped;
            }
            else if (nativeEncodePos === -1) {
                // use native encode only when needed
                nativeEncodePos = pos;
            }
        }
    }
    if (nativeEncodePos !== -1) {
        res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
    }
    return res !== undefined ? res : uriComponent;
}
function encodeURIComponentMinimal(path) {
    let res = undefined;
    for (let pos = 0; pos < path.length; pos++) {
        const code = path.charCodeAt(pos);
        if (code === 35 /* CharCode.Hash */ || code === 63 /* CharCode.QuestionMark */) {
            if (res === undefined) {
                res = path.substr(0, pos);
            }
            res += encodeTable[code];
        }
        else {
            if (res !== undefined) {
                res += path[pos];
            }
        }
    }
    return res !== undefined ? res : path;
}
/**
 * Compute `fsPath` for the given uri
 */
function uriToFsPath(uri, keepDriveLetterCasing) {
    let value;
    if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
        // unc path: file://shares/c$/far/boo
        value = `//${uri.authority}${uri.path}`;
    }
    else if (uri.path.charCodeAt(0) === 47 /* CharCode.Slash */
        && (uri.path.charCodeAt(1) >= 65 /* CharCode.A */ && uri.path.charCodeAt(1) <= 90 /* CharCode.Z */ || uri.path.charCodeAt(1) >= 97 /* CharCode.a */ && uri.path.charCodeAt(1) <= 122 /* CharCode.z */)
        && uri.path.charCodeAt(2) === 58 /* CharCode.Colon */) {
        if (!keepDriveLetterCasing) {
            // windows drive letter: file:///c:/far/boo
            value = uri.path[1].toLowerCase() + uri.path.substr(2);
        }
        else {
            value = uri.path.substr(1);
        }
    }
    else {
        // other path
        value = uri.path;
    }
    if (isWindows) {
        value = value.replace(/\//g, '\\');
    }
    return value;
}
/**
 * Create the external version of a uri
 */
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) {
            // <user>@<auth>
            const userinfo = authority.substr(0, idx);
            authority = authority.substr(idx + 1);
            idx = userinfo.indexOf(':');
            if (idx === -1) {
                res += encoder(userinfo, false);
            }
            else {
                // <user>:<pass>@<auth>
                res += encoder(userinfo.substr(0, idx), false);
                res += ':';
                res += encoder(userinfo.substr(idx + 1), false);
            }
            res += '@';
        }
        authority = authority.toLowerCase();
        idx = authority.indexOf(':');
        if (idx === -1) {
            res += encoder(authority, false);
        }
        else {
            // <auth>:<port>
            res += encoder(authority.substr(0, idx), false);
            res += authority.substr(idx);
        }
    }
    if (path) {
        // lower-case windows drive letters in /C:/fff or C:/fff
        if (path.length >= 3 && path.charCodeAt(0) === 47 /* CharCode.Slash */ && path.charCodeAt(2) === 58 /* CharCode.Colon */) {
            const code = path.charCodeAt(1);
            if (code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */) {
                path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; // "/c:".length === 3
            }
        }
        else if (path.length >= 2 && path.charCodeAt(1) === 58 /* CharCode.Colon */) {
            const code = path.charCodeAt(0);
            if (code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */) {
                path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`; // "/c:".length === 3
            }
        }
        // encode the rest of the path
        res += encoder(path, true);
    }
    if (query) {
        res += '?';
        res += encoder(query, false);
    }
    if (fragment) {
        res += '#';
        res += !skipEncoding ? encodeURIComponentFast(fragment, false) : fragment;
    }
    return res;
}
// --- decode
function decodeURIComponentGraceful(str) {
    try {
        return decodeURIComponent(str);
    }
    catch (_a) {
        if (str.length > 3) {
            return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3));
        }
        else {
            return str;
        }
    }
}
const _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));
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/network.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


var Schemas;
(function (Schemas) {
    /**
     * A schema that is used for models that exist in memory
     * only and that have no correspondence on a server or such.
     */
    Schemas.inMemory = 'inmemory';
    /**
     * A schema that is used for setting files
     */
    Schemas.vscode = 'vscode';
    /**
     * A schema that is used for internal private files
     */
    Schemas.internal = 'private';
    /**
     * A walk-through document.
     */
    Schemas.walkThrough = 'walkThrough';
    /**
     * An embedded code snippet.
     */
    Schemas.walkThroughSnippet = 'walkThroughSnippet';
    Schemas.http = 'http';
    Schemas.https = 'https';
    Schemas.file = 'file';
    Schemas.mailto = 'mailto';
    Schemas.untitled = 'untitled';
    Schemas.data = 'data';
    Schemas.command = 'command';
    Schemas.vscodeRemote = 'vscode-remote';
    Schemas.vscodeRemoteResource = 'vscode-remote-resource';
    Schemas.vscodeUserData = 'vscode-userdata';
    Schemas.vscodeCustomEditor = 'vscode-custom-editor';
    Schemas.vscodeNotebook = 'vscode-notebook';
    Schemas.vscodeNotebookCell = 'vscode-notebook-cell';
    Schemas.vscodeNotebookCellMetadata = 'vscode-notebook-cell-metadata';
    Schemas.vscodeNotebookCellOutput = 'vscode-notebook-cell-output';
    Schemas.vscodeInteractive = 'vscode-interactive';
    Schemas.vscodeInteractiveInput = 'vscode-interactive-input';
    Schemas.vscodeSettings = 'vscode-settings';
    Schemas.vscodeWorkspaceTrust = 'vscode-workspace-trust';
    Schemas.vscodeTerminal = 'vscode-terminal';
    /**
     * Scheme used internally for webviews that aren't linked to a resource (i.e. not custom editors)
     */
    Schemas.webviewPanel = 'webview-panel';
    /**
     * Scheme used for loading the wrapper html and script in webviews.
     */
    Schemas.vscodeWebview = 'vscode-webview';
    /**
     * Scheme used for extension pages
     */
    Schemas.extension = 'extension';
    /**
     * Scheme used as a replacement of `file` scheme to load
     * files with our custom protocol handler (desktop only).
     */
    Schemas.vscodeFileResource = 'vscode-file';
    /**
     * Scheme used for temporary resources
     */
    Schemas.tmp = 'tmp';
    /**
     * Scheme used vs live share
     */
    Schemas.vsls = 'vsls';
    /**
     * Scheme used for the Source Control commit input's text document
     */
    Schemas.vscodeSourceControl = 'vscode-scm';
})(Schemas || (Schemas = {}));
const connectionTokenQueryName = 'tkn';
class RemoteAuthoritiesImpl {
    constructor() {
        this._hosts = Object.create(null);
        this._ports = Object.create(null);
        this._connectionTokens = Object.create(null);
        this._preferredWebSchema = 'http';
        this._delegate = null;
        this._remoteResourcesPath = `/${Schemas.vscodeRemoteResource}`;
    }
    setPreferredWebSchema(schema) {
        this._preferredWebSchema = schema;
    }
    rewrite(uri) {
        if (this._delegate) {
            return this._delegate(uri);
        }
        const authority = uri.authority;
        let host = this._hosts[authority];
        if (host && host.indexOf(':') !== -1) {
            host = `[${host}]`;
        }
        const port = this._ports[authority];
        const connectionToken = this._connectionTokens[authority];
        let query = `path=${encodeURIComponent(uri.path)}`;
        if (typeof connectionToken === 'string') {
            query += `&${connectionTokenQueryName}=${encodeURIComponent(connectionToken)}`;
        }
        return URI.from({
            scheme: isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource,
            authority: `${host}:${port}`,
            path: this._remoteResourcesPath,
            query
        });
    }
}
const RemoteAuthorities = new RemoteAuthoritiesImpl();
class FileAccessImpl {
    asBrowserUri(uriOrModule, moduleIdToUrl) {
        const uri = this.toUri(uriOrModule, moduleIdToUrl);
        // Handle remote URIs via `RemoteAuthorities`
        if (uri.scheme === Schemas.vscodeRemote) {
            return RemoteAuthorities.rewrite(uri);
        }
        // Convert to `vscode-file` resource..
        if (
        // ...only ever for `file` resources
        uri.scheme === Schemas.file &&
            (
            // ...and we run in native environments
            isNative ||
                // ...or web worker extensions on desktop
                (isWebWorker && platform_globals.origin === `${Schemas.vscodeFileResource}://${FileAccessImpl.FALLBACK_AUTHORITY}`))) {
            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.FALLBACK_AUTHORITY,
                query: null,
                fragment: null
            });
        }
        return uri;
    }
    toUri(uriOrModule, moduleIdToUrl) {
        if (URI.isUri(uriOrModule)) {
            return uriOrModule;
        }
        return URI.parse(moduleIdToUrl.toUrl(uriOrModule));
    }
}
FileAccessImpl.FALLBACK_AUTHORITY = 'vscode-app';
const FileAccess = new FileAccessImpl();

;// ../../node_modules/monaco-editor/esm/vs/base/browser/dom.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/










function clearNode(node) {
    while (node.firstChild) {
        node.firstChild.remove();
    }
}
/**
 * @deprecated Use node.isConnected directly
 */
function isInDOM(node) {
    var _a;
    return (_a = node === null || node === void 0 ? void 0 : node.isConnected) !== null && _a !== void 0 ? _a : false;
}
class DomListener {
    constructor(node, type, handler, options) {
        this._node = node;
        this._type = type;
        this._handler = handler;
        this._options = (options || false);
        this._node.addEventListener(this._type, this._handler, this._options);
    }
    dispose() {
        if (!this._handler) {
            // Already disposed
            return;
        }
        this._node.removeEventListener(this._type, this._handler, this._options);
        // Prevent leakers from holding on to the dom or handler func
        this._node = null;
        this._handler = null;
    }
}
function addDisposableListener(node, type, handler, useCaptureOrOptions) {
    return new DomListener(node, type, handler, useCaptureOrOptions);
}
function _wrapAsStandardMouseEvent(handler) {
    return function (e) {
        return handler(new StandardMouseEvent(e));
    };
}
function _wrapAsStandardKeyboardEvent(handler) {
    return function (e) {
        return handler(new StandardKeyboardEvent(e));
    };
}
const addStandardDisposableListener = function addStandardDisposableListener(node, type, handler, useCapture) {
    let wrapHandler = handler;
    if (type === 'click' || type === 'mousedown') {
        wrapHandler = _wrapAsStandardMouseEvent(handler);
    }
    else if (type === 'keydown' || type === 'keypress' || type === 'keyup') {
        wrapHandler = _wrapAsStandardKeyboardEvent(handler);
    }
    return addDisposableListener(node, type, wrapHandler, useCapture);
};
const addStandardDisposableGenericMouseDownListener = function addStandardDisposableListener(node, handler, useCapture) {
    const wrapHandler = _wrapAsStandardMouseEvent(handler);
    return addDisposableGenericMouseDownListener(node, wrapHandler, useCapture);
};
const addStandardDisposableGenericMouseUpListener = function addStandardDisposableListener(node, handler, useCapture) {
    const wrapHandler = _wrapAsStandardMouseEvent(handler);
    return addDisposableGenericMouseUpListener(node, wrapHandler, useCapture);
};
function addDisposableGenericMouseDownListener(node, handler, useCapture) {
    return addDisposableListener(node, isIOS && canIUse_BrowserFeatures.pointerEvents ? EventType.POINTER_DOWN : EventType.MOUSE_DOWN, handler, useCapture);
}
function addDisposableGenericMouseUpListener(node, handler, useCapture) {
    return addDisposableListener(node, platform.isIOS && BrowserFeatures.pointerEvents ? EventType.POINTER_UP : EventType.MOUSE_UP, handler, useCapture);
}
function createEventEmitter(target, type, options) {
    let domListener = null;
    const handler = (e) => result.fire(e);
    const onFirstListenerAdd = () => {
        if (!domListener) {
            domListener = new DomListener(target, type, handler, options);
        }
    };
    const onLastListenerRemove = () => {
        if (domListener) {
            domListener.dispose();
            domListener = null;
        }
    };
    const result = new Emitter({ onFirstListenerAdd, onLastListenerRemove });
    return result;
}
let _animationFrame = null;
function doRequestAnimationFrame(callback) {
    if (!_animationFrame) {
        const emulatedRequestAnimationFrame = (callback) => {
            return setTimeout(() => callback(new Date().getTime()), 0);
        };
        _animationFrame = (self.requestAnimationFrame
            || self.msRequestAnimationFrame
            || self.webkitRequestAnimationFrame
            || self.mozRequestAnimationFrame
            || self.oRequestAnimationFrame
            || emulatedRequestAnimationFrame);
    }
    return _animationFrame.call(self, callback);
}
/**
 * Schedule a callback to be run at the next animation frame.
 * This allows multiple parties to register callbacks that should run at the next animation frame.
 * If currently in an animation frame, `runner` will be executed immediately.
 * @return token that can be used to cancel the scheduled runner (only if `runner` was not executed immediately).
 */
let runAtThisOrScheduleAtNextAnimationFrame;
/**
 * Schedule a callback to be run at the next animation frame.
 * This allows multiple parties to register callbacks that should run at the next animation frame.
 * If currently in an animation frame, `runner` will be executed at the next animation frame.
 * @return token that can be used to cancel the scheduled runner.
 */
let scheduleAtNextAnimationFrame;
class AnimationFrameQueueItem {
    constructor(runner, priority = 0) {
        this._runner = runner;
        this.priority = priority;
        this._canceled = false;
    }
    dispose() {
        this._canceled = true;
    }
    execute() {
        if (this._canceled) {
            return;
        }
        try {
            this._runner();
        }
        catch (e) {
            onUnexpectedError(e);
        }
    }
    // Sort by priority (largest to lowest)
    static sort(a, b) {
        return b.priority - a.priority;
    }
}
(function () {
    /**
     * The runners scheduled at the next animation frame
     */
    let NEXT_QUEUE = [];
    /**
     * The runners scheduled at the current animation frame
     */
    let CURRENT_QUEUE = null;
    /**
     * A flag to keep track if the native requestAnimationFrame was already called
     */
    let animFrameRequested = false;
    /**
     * A flag to indicate if currently handling a native requestAnimationFrame callback
     */
    let inAnimationFrameRunner = false;
    const animationFrameRunner = () => {
        animFrameRequested = false;
        CURRENT_QUEUE = NEXT_QUEUE;
        NEXT_QUEUE = [];
        inAnimationFrameRunner = true;
        while (CURRENT_QUEUE.length > 0) {
            CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort);
            const top = CURRENT_QUEUE.shift();
            top.execute();
        }
        inAnimationFrameRunner = false;
    };
    scheduleAtNextAnimationFrame = (runner, priority = 0) => {
        const item = new AnimationFrameQueueItem(runner, priority);
        NEXT_QUEUE.push(item);
        if (!animFrameRequested) {
            animFrameRequested = true;
            doRequestAnimationFrame(animationFrameRunner);
        }
        return item;
    };
    runAtThisOrScheduleAtNextAnimationFrame = (runner, priority) => {
        if (inAnimationFrameRunner) {
            const item = new AnimationFrameQueueItem(runner, priority);
            CURRENT_QUEUE.push(item);
            return item;
        }
        else {
            return scheduleAtNextAnimationFrame(runner, priority);
        }
    };
})();
function dom_getComputedStyle(el) {
    return document.defaultView.getComputedStyle(el, null);
}
function getClientArea(element) {
    // Try with DOM clientWidth / clientHeight
    if (element !== document.body) {
        return new Dimension(element.clientWidth, element.clientHeight);
    }
    // If visual view port exits and it's on mobile, it should be used instead of window innerWidth / innerHeight, or document.body.clientWidth / document.body.clientHeight
    if (isIOS && window.visualViewport) {
        return new Dimension(window.visualViewport.width, window.visualViewport.height);
    }
    // Try innerWidth / innerHeight
    if (window.innerWidth && window.innerHeight) {
        return new Dimension(window.innerWidth, window.innerHeight);
    }
    // Try with document.body.clientWidth / document.body.clientHeight
    if (document.body && document.body.clientWidth && document.body.clientHeight) {
        return new Dimension(document.body.clientWidth, document.body.clientHeight);
    }
    // Try with document.documentElement.clientWidth / document.documentElement.clientHeight
    if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) {
        return new Dimension(document.documentElement.clientWidth, document.documentElement.clientHeight);
    }
    throw new Error('Unable to figure out browser width and height');
}
class SizeUtils {
    // Adapted from WinJS
    // Converts a CSS positioning string for the specified element to pixels.
    static convertToPixels(element, value) {
        return parseFloat(value) || 0;
    }
    static getDimension(element, cssPropertyName, jsPropertyName) {
        const computedStyle = dom_getComputedStyle(element);
        let value = '0';
        if (computedStyle) {
            if (computedStyle.getPropertyValue) {
                value = computedStyle.getPropertyValue(cssPropertyName);
            }
            else {
                // IE8
                value = computedStyle.getAttribute(jsPropertyName);
            }
        }
        return SizeUtils.convertToPixels(element, value);
    }
    static getBorderLeftWidth(element) {
        return SizeUtils.getDimension(element, 'border-left-width', 'borderLeftWidth');
    }
    static getBorderRightWidth(element) {
        return SizeUtils.getDimension(element, 'border-right-width', 'borderRightWidth');
    }
    static getBorderTopWidth(element) {
        return SizeUtils.getDimension(element, 'border-top-width', 'borderTopWidth');
    }
    static getBorderBottomWidth(element) {
        return SizeUtils.getDimension(element, 'border-bottom-width', 'borderBottomWidth');
    }
    static getPaddingLeft(element) {
        return SizeUtils.getDimension(element, 'padding-left', 'paddingLeft');
    }
    static getPaddingRight(element) {
        return SizeUtils.getDimension(element, 'padding-right', 'paddingRight');
    }
    static getPaddingTop(element) {
        return SizeUtils.getDimension(element, 'padding-top', 'paddingTop');
    }
    static getPaddingBottom(element) {
        return SizeUtils.getDimension(element, 'padding-bottom', 'paddingBottom');
    }
    static getMarginLeft(element) {
        return SizeUtils.getDimension(element, 'margin-left', 'marginLeft');
    }
    static getMarginTop(element) {
        return SizeUtils.getDimension(element, 'margin-top', 'marginTop');
    }
    static getMarginRight(element) {
        return SizeUtils.getDimension(element, 'margin-right', 'marginRight');
    }
    static getMarginBottom(element) {
        return SizeUtils.getDimension(element, 'margin-bottom', 'marginBottom');
    }
}
class Dimension {
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }
    with(width = this.width, height = this.height) {
        if (width !== this.width || height !== this.height) {
            return new Dimension(width, 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 Dimension) {
            return obj;
        }
        else {
            return new Dimension(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;
    }
}
Dimension.None = new Dimension(0, 0);
function getTopLeftOffset(element) {
    // Adapted from WinJS.Utilities.getPosition
    // and added borders to the mix
    let offsetParent = element.offsetParent;
    let top = element.offsetTop;
    let left = element.offsetLeft;
    while ((element = element.parentNode) !== null
        && element !== document.body
        && element !== document.documentElement) {
        top -= element.scrollTop;
        const c = isShadowRoot(element) ? null : dom_getComputedStyle(element);
        if (c) {
            left -= c.direction !== 'rtl' ? element.scrollLeft : -element.scrollLeft;
        }
        if (element === offsetParent) {
            left += SizeUtils.getBorderLeftWidth(element);
            top += SizeUtils.getBorderTopWidth(element);
            top += element.offsetTop;
            left += element.offsetLeft;
            offsetParent = element.offsetParent;
        }
    }
    return {
        left: left,
        top: top
    };
}
function size(element, width, height) {
    if (typeof width === 'number') {
        element.style.width = `${width}px`;
    }
    if (typeof height === 'number') {
        element.style.height = `${height}px`;
    }
}
/**
 * Returns the position of a dom node relative to the entire page.
 */
function getDomNodePagePosition(domNode) {
    const bb = domNode.getBoundingClientRect();
    return {
        left: bb.left + StandardWindow.scrollX,
        top: bb.top + StandardWindow.scrollY,
        width: bb.width,
        height: bb.height
    };
}
/**
 * Returns the effective zoom on a given element before window zoom level is applied
 */
function getDomNodeZoomLevel(domNode) {
    let testElement = domNode;
    let zoom = 1.0;
    do {
        const elementZoomLevel = dom_getComputedStyle(testElement).zoom;
        if (elementZoomLevel !== null && elementZoomLevel !== undefined && elementZoomLevel !== '1') {
            zoom *= elementZoomLevel;
        }
        testElement = testElement.parentElement;
    } while (testElement !== null && testElement !== document.documentElement);
    return zoom;
}
const StandardWindow = new class {
    get scrollX() {
        if (typeof window.scrollX === 'number') {
            // modern browsers
            return window.scrollX;
        }
        else {
            return document.body.scrollLeft + document.documentElement.scrollLeft;
        }
    }
    get scrollY() {
        if (typeof window.scrollY === 'number') {
            // modern browsers
            return window.scrollY;
        }
        else {
            return document.body.scrollTop + document.documentElement.scrollTop;
        }
    }
};
// Adapted from WinJS
// Gets the width of the element, including margins.
function getTotalWidth(element) {
    const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
    return element.offsetWidth + margin;
}
function getContentWidth(element) {
    const border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);
    const padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);
    return element.offsetWidth - border - padding;
}
// Adapted from WinJS
// Gets the height of the content of the specified element. The content height does not include borders or padding.
function getContentHeight(element) {
    const border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);
    const padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);
    return element.offsetHeight - border - padding;
}
// Adapted from WinJS
// Gets the height of the element, including its margins.
function getTotalHeight(element) {
    const margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);
    return element.offsetHeight + margin;
}
// ----------------------------------------------------------------------------------------
function isAncestor(testChild, testAncestor) {
    while (testChild) {
        if (testChild === testAncestor) {
            return true;
        }
        testChild = testChild.parentNode;
    }
    return false;
}
function findParentWithClass(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 hasParentWithClass(node, clazz, stopAtClazzOrNode) {
    return !!findParentWithClass(node, clazz, stopAtClazzOrNode);
}
function isShadowRoot(node) {
    return (node && !!node.host && !!node.mode);
}
function isInShadowDOM(domNode) {
    return !!getShadowRoot(domNode);
}
function getShadowRoot(domNode) {
    while (domNode.parentNode) {
        if (domNode === document.body) {
            // reached the body
            return null;
        }
        domNode = domNode.parentNode;
    }
    return isShadowRoot(domNode) ? domNode : null;
}
function getActiveElement() {
    let result = document.activeElement;
    while (result === null || result === void 0 ? void 0 : result.shadowRoot) {
        result = result.shadowRoot.activeElement;
    }
    return result;
}
function createStyleSheet(container = document.getElementsByTagName('head')[0]) {
    const style = document.createElement('style');
    style.type = 'text/css';
    style.media = 'screen';
    container.appendChild(style);
    return style;
}
let _sharedStyleSheet = null;
function getSharedStyleSheet() {
    if (!_sharedStyleSheet) {
        _sharedStyleSheet = createStyleSheet();
    }
    return _sharedStyleSheet;
}
function getDynamicStyleSheetRules(style) {
    var _a, _b;
    if ((_a = style === null || style === void 0 ? void 0 : style.sheet) === null || _a === void 0 ? void 0 : _a.rules) {
        // Chrome, IE
        return style.sheet.rules;
    }
    if ((_b = style === null || style === void 0 ? void 0 : style.sheet) === null || _b === void 0 ? void 0 : _b.cssRules) {
        // FF
        return style.sheet.cssRules;
    }
    return [];
}
function createCSSRule(selector, cssText, style = getSharedStyleSheet()) {
    if (!style || !cssText) {
        return;
    }
    style.sheet.insertRule(selector + '{' + cssText + '}', 0);
}
function removeCSSRulesContainingSelector(ruleName, style = getSharedStyleSheet()) {
    if (!style) {
        return;
    }
    const rules = getDynamicStyleSheetRules(style);
    const toDelete = [];
    for (let i = 0; i < rules.length; i++) {
        const rule = rules[i];
        if (rule.selectorText.indexOf(ruleName) !== -1) {
            toDelete.push(i);
        }
    }
    for (let i = toDelete.length - 1; i >= 0; i--) {
        style.sheet.deleteRule(toDelete[i]);
    }
}
function isHTMLElement(o) {
    if (typeof HTMLElement === 'object') {
        return o instanceof HTMLElement;
    }
    return o && typeof o === 'object' && o.nodeType === 1 && typeof o.nodeName === 'string';
}
const EventType = {
    // 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',
    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: isWebKit ? 'webkitAnimationStart' : 'animationstart',
    ANIMATION_END: isWebKit ? 'webkitAnimationEnd' : 'animationend',
    ANIMATION_ITERATION: isWebKit ? 'webkitAnimationIteration' : 'animationiteration'
};
const EventHelper = {
    stop: function (e, cancelBubble) {
        if (e.preventDefault) {
            e.preventDefault();
        }
        else {
            // IE8
            e.returnValue = false;
        }
        if (cancelBubble) {
            if (e.stopPropagation) {
                e.stopPropagation();
            }
            else {
                // IE8
                e.cancelBubble = true;
            }
        }
    }
};
function saveParentsScrollTop(node) {
    const r = [];
    for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
        r[i] = node.scrollTop;
        node = node.parentNode;
    }
    return r;
}
function restoreParentsScrollTop(node, state) {
    for (let i = 0; node && node.nodeType === node.ELEMENT_NODE; i++) {
        if (node.scrollTop !== state[i]) {
            node.scrollTop = state[i];
        }
        node = node.parentNode;
    }
}
class FocusTracker extends Disposable {
    constructor(element) {
        super();
        this._onDidFocus = this._register(new Emitter());
        this.onDidFocus = this._onDidFocus.event;
        this._onDidBlur = this._register(new Emitter());
        this.onDidBlur = this._onDidBlur.event;
        let hasFocus = FocusTracker.hasFocusWithin(element);
        let loosingFocus = false;
        const onFocus = () => {
            loosingFocus = false;
            if (!hasFocus) {
                hasFocus = true;
                this._onDidFocus.fire();
            }
        };
        const onBlur = () => {
            if (hasFocus) {
                loosingFocus = true;
                window.setTimeout(() => {
                    if (loosingFocus) {
                        loosingFocus = false;
                        hasFocus = false;
                        this._onDidBlur.fire();
                    }
                }, 0);
            }
        };
        this._refreshStateHandler = () => {
            const currentNodeHasFocus = FocusTracker.hasFocusWithin(element);
            if (currentNodeHasFocus !== hasFocus) {
                if (hasFocus) {
                    onBlur();
                }
                else {
                    onFocus();
                }
            }
        };
        this._register(addDisposableListener(element, EventType.FOCUS, onFocus, true));
        this._register(addDisposableListener(element, EventType.BLUR, onBlur, true));
        this._register(addDisposableListener(element, EventType.FOCUS_IN, () => this._refreshStateHandler()));
        this._register(addDisposableListener(element, EventType.FOCUS_OUT, () => this._refreshStateHandler()));
    }
    static hasFocusWithin(element) {
        const shadowRoot = getShadowRoot(element);
        const activeElement = (shadowRoot ? shadowRoot.activeElement : document.activeElement);
        return isAncestor(activeElement, element);
    }
}
function trackFocus(element) {
    return new FocusTracker(element);
}
function append(parent, ...children) {
    parent.append(...children);
    if (children.length === 1 && typeof children[0] !== 'string') {
        return children[0];
    }
}
function prepend(parent, child) {
    parent.insertBefore(child, parent.firstChild);
    return child;
}
/**
 * Removes all children from `parent` and appends `children`
 */
function dom_reset(parent, ...children) {
    parent.innerText = '';
    append(parent, ...children);
}
const SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;
var Namespace;
(function (Namespace) {
    Namespace["HTML"] = "http://www.w3.org/1999/xhtml";
    Namespace["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');
    }
    attrs = Object.assign({}, (attrs || {}));
    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();
    }
    Object.keys(attrs).forEach(name => {
        const value = attrs[name];
        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 dom_$(description, attrs, ...children) {
    return _$(Namespace.HTML, description, attrs, ...children);
}
dom_$.SVG = function (description, attrs, ...children) {
    return _$(Namespace.SVG, description, attrs, ...children);
};
function show(...elements) {
    for (const element of elements) {
        element.style.display = '';
        element.removeAttribute('aria-hidden');
    }
}
function hide(...elements) {
    for (const element of elements) {
        element.style.display = 'none';
        element.setAttribute('aria-hidden', 'true');
    }
}
function getElementsByTagName(tag) {
    return Array.prototype.slice.call(document.getElementsByTagName(tag), 0);
}
/**
 * Find a value usable for a dom node size such that the likelihood that it would be
 * displayed with constant screen pixels size is as high as possible.
 *
 * e.g. We would desire for the cursors to be 2px (CSS px) wide. Under a devicePixelRatio
 * of 1.25, the cursor will be 2.5 screen pixels wide. Depending on how the dom node aligns/"snaps"
 * with the screen pixels, it will sometimes be rendered with 2 screen pixels, and sometimes with 3 screen pixels.
 */
function computeScreenAwareSize(cssPx) {
    const screenPx = window.devicePixelRatio * cssPx;
    return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio;
}
/**
 * Open safely a new window. This is the best way to do so, but you cannot tell
 * if the window was opened or if it was blocked by the browser's popup blocker.
 * If you want to tell if the browser blocked the new window, use {@link windowOpenWithSuccess}.
 *
 * See https://github.com/microsoft/monaco-editor/issues/601
 * To protect against malicious code in the linked site, particularly phishing attempts,
 * the window.opener should be set to null to prevent the linked site from having access
 * to change the location of the current page.
 * See https://mathiasbynens.github.io/rel-noopener/
 */
function windowOpenNoOpener(url) {
    // By using 'noopener' in the `windowFeatures` argument, the newly created window will
    // not be able to use `window.opener` to reach back to the current page.
    // See https://stackoverflow.com/a/46958731
    // See https://developer.mozilla.org/en-US/docs/Web/API/Window/open#noopener
    // However, this also doesn't allow us to realize if the browser blocked
    // the creation of the window.
    window.open(url, '_blank', 'noopener');
}
function animate(fn) {
    const step = () => {
        fn();
        stepDisposable = scheduleAtNextAnimationFrame(step);
    };
    let stepDisposable = scheduleAtNextAnimationFrame(step);
    return toDisposable(() => stepDisposable.dispose());
}
RemoteAuthorities.setPreferredWebSchema(/^https:/.test(window.location.href) ? 'https' : 'http');
/**
 * returns url('...')
 */
function asCSSUrl(uri) {
    if (!uri) {
        return `url('')`;
    }
    return `url('${FileAccess.asBrowserUri(uri).toString(true).replace(/'/g, '%27')}')`;
}
function asCSSPropertyValue(value) {
    return `'${value.replace(/'/g, '%27')}'`;
}
// -- sanitize and trusted html
/**
 * Hooks dompurify using `afterSanitizeAttributes` to check that all `href` and `src`
 * attributes are valid.
 */
function hookDomPurifyHrefAndSrcSanitizer(allowedProtocols, allowDataImages = false) {
    // https://github.com/cure53/DOMPurify/blob/main/demos/hooks-scheme-allowlist.html
    // build an anchor to map URLs to
    const anchor = document.createElement('a');
    addHook('afterSanitizeAttributes', (node) => {
        // check all href/src attributes for validity
        for (const attr of ['href', 'src']) {
            if (node.hasAttribute(attr)) {
                const attrValue = node.getAttribute(attr);
                if (attr === 'href' && attrValue.startsWith('#')) {
                    // Allow fragment links
                    continue;
                }
                anchor.href = attrValue;
                if (!allowedProtocols.includes(anchor.protocol.replace(/:$/, ''))) {
                    if (allowDataImages && attr === 'src' && anchor.href.startsWith('data:')) {
                        continue;
                    }
                    node.removeAttribute(attr);
                }
            }
        }
    });
    return toDisposable(() => {
        removeHook('afterSanitizeAttributes');
    });
}
class ModifierKeyEmitter extends Emitter {
    constructor() {
        super();
        this._subscriptions = new DisposableStore();
        this._keyStatus = {
            altKey: false,
            shiftKey: false,
            ctrlKey: false,
            metaKey: false
        };
        this._subscriptions.add(addDisposableListener(window, 'keydown', e => {
            if (e.defaultPrevented) {
                return;
            }
            const event = new StandardKeyboardEvent(e);
            // If Alt-key keydown event is repeated, ignore it #112347
            // Only known to be necessary for Alt-Key at the moment #115810
            if (event.keyCode === 6 /* KeyCode.Alt */ && e.repeat) {
                return;
            }
            if (e.altKey && !this._keyStatus.altKey) {
                this._keyStatus.lastKeyPressed = 'alt';
            }
            else if (e.ctrlKey && !this._keyStatus.ctrlKey) {
                this._keyStatus.lastKeyPressed = 'ctrl';
            }
            else if (e.metaKey && !this._keyStatus.metaKey) {
                this._keyStatus.lastKeyPressed = 'meta';
            }
            else if (e.shiftKey && !this._keyStatus.shiftKey) {
                this._keyStatus.lastKeyPressed = 'shift';
            }
            else if (event.keyCode !== 6 /* KeyCode.Alt */) {
                this._keyStatus.lastKeyPressed = undefined;
            }
            else {
                return;
            }
            this._keyStatus.altKey = e.altKey;
            this._keyStatus.ctrlKey = e.ctrlKey;
            this._keyStatus.metaKey = e.metaKey;
            this._keyStatus.shiftKey = e.shiftKey;
            if (this._keyStatus.lastKeyPressed) {
                this._keyStatus.event = e;
                this.fire(this._keyStatus);
            }
        }, true));
        this._subscriptions.add(addDisposableListener(window, 'keyup', e => {
            if (e.defaultPrevented) {
                return;
            }
            if (!e.altKey && this._keyStatus.altKey) {
                this._keyStatus.lastKeyReleased = 'alt';
            }
            else if (!e.ctrlKey && this._keyStatus.ctrlKey) {
                this._keyStatus.lastKeyReleased = 'ctrl';
            }
            else if (!e.metaKey && this._keyStatus.metaKey) {
                this._keyStatus.lastKeyReleased = 'meta';
            }
            else if (!e.shiftKey && this._keyStatus.shiftKey) {
                this._keyStatus.lastKeyReleased = 'shift';
            }
            else {
                this._keyStatus.lastKeyReleased = undefined;
            }
            if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) {
                this._keyStatus.lastKeyPressed = undefined;
            }
            this._keyStatus.altKey = e.altKey;
            this._keyStatus.ctrlKey = e.ctrlKey;
            this._keyStatus.metaKey = e.metaKey;
            this._keyStatus.shiftKey = e.shiftKey;
            if (this._keyStatus.lastKeyReleased) {
                this._keyStatus.event = e;
                this.fire(this._keyStatus);
            }
        }, true));
        this._subscriptions.add(addDisposableListener(document.body, 'mousedown', () => {
            this._keyStatus.lastKeyPressed = undefined;
        }, true));
        this._subscriptions.add(addDisposableListener(document.body, 'mouseup', () => {
            this._keyStatus.lastKeyPressed = undefined;
        }, true));
        this._subscriptions.add(addDisposableListener(document.body, 'mousemove', e => {
            if (e.buttons) {
                this._keyStatus.lastKeyPressed = undefined;
            }
        }, true));
        this._subscriptions.add(addDisposableListener(window, 'blur', () => {
            this.resetKeyStatus();
        }));
    }
    get keyStatus() {
        return this._keyStatus;
    }
    /**
     * Allows to explicitly reset the key status based on more knowledge (#109062)
     */
    resetKeyStatus() {
        this.doResetKeyStatus();
        this.fire(this._keyStatus);
    }
    doResetKeyStatus() {
        this._keyStatus = {
            altKey: false,
            shiftKey: false,
            ctrlKey: false,
            metaKey: false
        };
    }
    static getInstance() {
        if (!ModifierKeyEmitter.instance) {
            ModifierKeyEmitter.instance = new ModifierKeyEmitter();
        }
        return ModifierKeyEmitter.instance;
    }
    dispose() {
        super.dispose();
        this._subscriptions.dispose();
    }
}
class DragAndDropObserver extends Disposable {
    constructor(element, callbacks) {
        super();
        this.element = element;
        this.callbacks = callbacks;
        // A helper to fix issues with repeated DRAG_ENTER / DRAG_LEAVE
        // calls see https://github.com/microsoft/vscode/issues/14470
        // when the element has child elements where the events are fired
        // repeadedly.
        this.counter = 0;
        // Allows to measure the duration of the drag operation.
        this.dragStartTime = 0;
        this.registerListeners();
    }
    registerListeners() {
        this._register(addDisposableListener(this.element, EventType.DRAG_ENTER, (e) => {
            this.counter++;
            this.dragStartTime = e.timeStamp;
            this.callbacks.onDragEnter(e);
        }));
        this._register(addDisposableListener(this.element, EventType.DRAG_OVER, (e) => {
            var _a, _b;
            e.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
            (_b = (_a = this.callbacks).onDragOver) === null || _b === void 0 ? void 0 : _b.call(_a, e, e.timeStamp - this.dragStartTime);
        }));
        this._register(addDisposableListener(this.element, EventType.DRAG_LEAVE, (e) => {
            this.counter--;
            if (this.counter === 0) {
                this.dragStartTime = 0;
                this.callbacks.onDragLeave(e);
            }
        }));
        this._register(addDisposableListener(this.element, EventType.DRAG_END, (e) => {
            this.counter = 0;
            this.dragStartTime = 0;
            this.callbacks.onDragEnd(e);
        }));
        this._register(addDisposableListener(this.element, EventType.DROP, (e) => {
            this.counter = 0;
            this.dragStartTime = 0;
            this.callbacks.onDrop(e);
        }));
    }
}
const H_REGEX = /(?<tag>[\w\-]+)?(?:#(?<id>[\w\-]+))?(?<class>(?:\.(?:[\w\-]+))*)(?:@(?<name>(?:[\w\_])+))?/;
function h(tag, ...args) {
    let attributes;
    let children;
    if (Array.isArray(args[0])) {
        attributes = {};
        children = args[0];
    }
    else {
        attributes = args[0] || {};
        children = args[1];
    }
    const match = H_REGEX.exec(tag);
    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'];
    }
    if (match.groups['class']) {
        el.className = match.groups['class'].replace(/\./g, ' ').trim();
    }
    const result = {};
    if (match.groups['name']) {
        result[match.groups['name']] = el;
    }
    if (children) {
        for (const c of children) {
            if (c instanceof HTMLElement) {
                el.appendChild(c);
            }
            else if (typeof c === 'string') {
                el.append(c);
            }
            else {
                Object.assign(result, c);
                el.appendChild(c.root);
            }
        }
    }
    for (const [key, value] of Object.entries(attributes)) {
        if (key === 'style') {
            for (const [cssKey, cssValue] of Object.entries(value)) {
                el.style.setProperty(camelCaseToHyphenCase(cssKey), typeof cssValue === 'number' ? cssValue + 'px' : '' + cssValue);
            }
        }
        else if (key === 'tabIndex') {
            el.tabIndex = value;
        }
        else {
            el.setAttribute(camelCaseToHyphenCase(key), value.toString());
        }
    }
    result['root'] = el;
    return result;
}
function camelCaseToHyphenCase(str) {
    return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/fastDomNode.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class FastDomNode {
    constructor(domNode) {
        this.domNode = domNode;
        this._maxWidth = '';
        this._width = '';
        this._height = '';
        this._top = '';
        this._left = '';
        this._bottom = '';
        this._right = '';
        this._fontFamily = '';
        this._fontWeight = '';
        this._fontSize = '';
        this._fontStyle = '';
        this._fontFeatureSettings = '';
        this._textDecoration = '';
        this._lineHeight = '';
        this._letterSpacing = '';
        this._className = '';
        this._display = '';
        this._position = '';
        this._visibility = '';
        this._color = '';
        this._backgroundColor = '';
        this._layerHint = false;
        this._contain = 'none';
        this._boxShadow = '';
    }
    setMaxWidth(_maxWidth) {
        const maxWidth = numberAsPixels(_maxWidth);
        if (this._maxWidth === maxWidth) {
            return;
        }
        this._maxWidth = maxWidth;
        this.domNode.style.maxWidth = this._maxWidth;
    }
    setWidth(_width) {
        const width = numberAsPixels(_width);
        if (this._width === width) {
            return;
        }
        this._width = width;
        this.domNode.style.width = this._width;
    }
    setHeight(_height) {
        const height = numberAsPixels(_height);
        if (this._height === height) {
            return;
        }
        this._height = height;
        this.domNode.style.height = this._height;
    }
    setTop(_top) {
        const top = numberAsPixels(_top);
        if (this._top === top) {
            return;
        }
        this._top = top;
        this.domNode.style.top = this._top;
    }
    setLeft(_left) {
        const left = numberAsPixels(_left);
        if (this._left === left) {
            return;
        }
        this._left = left;
        this.domNode.style.left = this._left;
    }
    setBottom(_bottom) {
        const bottom = numberAsPixels(_bottom);
        if (this._bottom === bottom) {
            return;
        }
        this._bottom = bottom;
        this.domNode.style.bottom = this._bottom;
    }
    setRight(_right) {
        const right = numberAsPixels(_right);
        if (this._right === right) {
            return;
        }
        this._right = right;
        this.domNode.style.right = this._right;
    }
    setFontFamily(fontFamily) {
        if (this._fontFamily === fontFamily) {
            return;
        }
        this._fontFamily = fontFamily;
        this.domNode.style.fontFamily = this._fontFamily;
    }
    setFontWeight(fontWeight) {
        if (this._fontWeight === fontWeight) {
            return;
        }
        this._fontWeight = fontWeight;
        this.domNode.style.fontWeight = this._fontWeight;
    }
    setFontSize(_fontSize) {
        const fontSize = numberAsPixels(_fontSize);
        if (this._fontSize === fontSize) {
            return;
        }
        this._fontSize = fontSize;
        this.domNode.style.fontSize = this._fontSize;
    }
    setFontStyle(fontStyle) {
        if (this._fontStyle === fontStyle) {
            return;
        }
        this._fontStyle = fontStyle;
        this.domNode.style.fontStyle = this._fontStyle;
    }
    setFontFeatureSettings(fontFeatureSettings) {
        if (this._fontFeatureSettings === fontFeatureSettings) {
            return;
        }
        this._fontFeatureSettings = fontFeatureSettings;
        this.domNode.style.fontFeatureSettings = this._fontFeatureSettings;
    }
    setTextDecoration(textDecoration) {
        if (this._textDecoration === textDecoration) {
            return;
        }
        this._textDecoration = textDecoration;
        this.domNode.style.textDecoration = this._textDecoration;
    }
    setLineHeight(_lineHeight) {
        const lineHeight = numberAsPixels(_lineHeight);
        if (this._lineHeight === lineHeight) {
            return;
        }
        this._lineHeight = lineHeight;
        this.domNode.style.lineHeight = this._lineHeight;
    }
    setLetterSpacing(_letterSpacing) {
        const letterSpacing = numberAsPixels(_letterSpacing);
        if (this._letterSpacing === letterSpacing) {
            return;
        }
        this._letterSpacing = letterSpacing;
        this.domNode.style.letterSpacing = this._letterSpacing;
    }
    setClassName(className) {
        if (this._className === className) {
            return;
        }
        this._className = className;
        this.domNode.className = this._className;
    }
    toggleClassName(className, shouldHaveIt) {
        this.domNode.classList.toggle(className, shouldHaveIt);
        this._className = this.domNode.className;
    }
    setDisplay(display) {
        if (this._display === display) {
            return;
        }
        this._display = display;
        this.domNode.style.display = this._display;
    }
    setPosition(position) {
        if (this._position === position) {
            return;
        }
        this._position = position;
        this.domNode.style.position = this._position;
    }
    setVisibility(visibility) {
        if (this._visibility === visibility) {
            return;
        }
        this._visibility = visibility;
        this.domNode.style.visibility = this._visibility;
    }
    setColor(color) {
        if (this._color === color) {
            return;
        }
        this._color = color;
        this.domNode.style.color = this._color;
    }
    setBackgroundColor(backgroundColor) {
        if (this._backgroundColor === backgroundColor) {
            return;
        }
        this._backgroundColor = backgroundColor;
        this.domNode.style.backgroundColor = this._backgroundColor;
    }
    setLayerHinting(layerHint) {
        if (this._layerHint === layerHint) {
            return;
        }
        this._layerHint = layerHint;
        this.domNode.style.transform = this._layerHint ? 'translate3d(0px, 0px, 0px)' : '';
    }
    setBoxShadow(boxShadow) {
        if (this._boxShadow === boxShadow) {
            return;
        }
        this._boxShadow = boxShadow;
        this.domNode.style.boxShadow = boxShadow;
    }
    setContain(contain) {
        if (this._contain === contain) {
            return;
        }
        this._contain = contain;
        this.domNode.style.contain = this._contain;
    }
    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 createFastDomNode(domNode) {
    return new FastDomNode(domNode);
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/formattedTextRenderer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

function renderText(text, options = {}) {
    const element = createElement(options);
    element.textContent = text;
    return element;
}
function renderFormattedText(formattedText, options = {}) {
    const element = createElement(options);
    _renderFormattedText(element, parseFormattedText(formattedText, !!options.renderCodeSegments), options.actionHandler, options.renderCodeSegments);
    return element;
}
function createElement(options) {
    const tagName = options.inline ? 'span' : 'div';
    const element = document.createElement(tagName);
    if (options.className) {
        element.className = options.className;
    }
    return element;
}
class StringStream {
    constructor(source) {
        this.source = source;
        this.index = 0;
    }
    eos() {
        return this.index >= this.source.length;
    }
    next() {
        const next = this.peek();
        this.advance();
        return next;
    }
    peek() {
        return this.source[this.index];
    }
    advance() {
        this.index++;
    }
}
function _renderFormattedText(element, treeNode, actionHandler, renderCodeSegments) {
    let child;
    if (treeNode.type === 2 /* FormatType.Text */) {
        child = document.createTextNode(treeNode.content || '');
    }
    else if (treeNode.type === 3 /* FormatType.Bold */) {
        child = document.createElement('b');
    }
    else if (treeNode.type === 4 /* FormatType.Italics */) {
        child = document.createElement('i');
    }
    else if (treeNode.type === 7 /* FormatType.Code */ && renderCodeSegments) {
        child = document.createElement('code');
    }
    else if (treeNode.type === 5 /* FormatType.Action */ && actionHandler) {
        const a = document.createElement('a');
        actionHandler.disposables.add(addStandardDisposableListener(a, 'click', (event) => {
            actionHandler.callback(String(treeNode.index), event);
        }));
        child = a;
    }
    else if (treeNode.type === 8 /* FormatType.NewLine */) {
        child = document.createElement('br');
    }
    else if (treeNode.type === 1 /* FormatType.Root */) {
        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 /* FormatType.Root */,
        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 /* FormatType.Invalid */);
        if (isEscapedFormatType) {
            next = stream.next(); // unread the backslash if it escapes a format tag type
        }
        if (!isEscapedFormatType && isFormatTag(next, parseCodeSegments) && next === stream.peek()) {
            stream.advance();
            if (current.type === 2 /* FormatType.Text */) {
                current = stack.pop();
            }
            const type = formatTagType(next, parseCodeSegments);
            if (current.type === type || (current.type === 5 /* FormatType.Action */ && type === 6 /* FormatType.ActionClose */)) {
                current = stack.pop();
            }
            else {
                const newCurrent = {
                    type: type,
                    children: []
                };
                if (type === 5 /* FormatType.Action */) {
                    newCurrent.index = actionViewItemIndex;
                    actionViewItemIndex++;
                }
                current.children.push(newCurrent);
                stack.push(current);
                current = newCurrent;
            }
        }
        else if (next === '\n') {
            if (current.type === 2 /* FormatType.Text */) {
                current = stack.pop();
            }
            current.children.push({
                type: 8 /* FormatType.NewLine */
            });
        }
        else {
            if (current.type !== 2 /* FormatType.Text */) {
                const textCurrent = {
                    type: 2 /* FormatType.Text */,
                    content: next
                };
                current.children.push(textCurrent);
                stack.push(current);
                current = textCurrent;
            }
            else {
                current.content += next;
            }
        }
    }
    if (current.type === 2 /* FormatType.Text */) {
        current = stack.pop();
    }
    if (stack.length) {
        // incorrectly formatted string literal
    }
    return root;
}
function isFormatTag(char, supportCodeSegments) {
    return formatTagType(char, supportCodeSegments) !== 0 /* FormatType.Invalid */;
}
function formatTagType(char, supportCodeSegments) {
    switch (char) {
        case '*':
            return 3 /* FormatType.Bold */;
        case '_':
            return 4 /* FormatType.Italics */;
        case '[':
            return 5 /* FormatType.Action */;
        case ']':
            return 6 /* FormatType.ActionClose */;
        case '`':
            return supportCodeSegments ? 7 /* FormatType.Code */ : 0 /* FormatType.Invalid */;
        default:
            return 0 /* FormatType.Invalid */;
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/aria/aria.css
var aria = __webpack_require__(52767);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/aria/aria.css

      
      
      
      
      
      
      
      
      

var aria_options = {};

aria_options.styleTagTransform = (styleTagTransform_default());
aria_options.setAttributes = (setAttributesWithoutAttributes_default());

      aria_options.insert = insertBySelector_default().bind(null, "head");
    
aria_options.domAPI = (styleDomAPI_default());
aria_options.insertStyleElement = (insertStyleElement_default());

var aria_update = injectStylesIntoStyleTag_default()(aria/* default */.A, aria_options);




       /* harmony default export */ const aria_aria = (aria/* default */.A && aria/* default */.A.locals ? aria/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/aria/aria.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



// Use a max length since we are inserting the whole msg in the DOM and that can cause browsers to freeze for long messages #94233
const MAX_MESSAGE_LENGTH = 20000;
let ariaContainer;
let alertContainer;
let alertContainer2;
let statusContainer;
let statusContainer2;
function setARIAContainer(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('role', 'complementary');
        element.setAttribute('aria-live', 'polite');
        element.setAttribute('aria-atomic', 'true');
        ariaContainer.appendChild(element);
        return element;
    };
    statusContainer = createStatusContainer();
    statusContainer2 = createStatusContainer();
    parent.appendChild(ariaContainer);
}
/**
 * Given the provided message, will make sure that it is read as alert to screen readers.
 */
function aria_alert(msg) {
    if (!ariaContainer) {
        return;
    }
    // Use alternate containers such that duplicated messages get read out by screen readers #99466
    if (alertContainer.textContent !== msg) {
        clearNode(alertContainer2);
        insertMessage(alertContainer, msg);
    }
    else {
        clearNode(alertContainer);
        insertMessage(alertContainer2, msg);
    }
}
/**
 * Given the provided message, will make sure that it is read as status to screen readers.
 */
function aria_status(msg) {
    if (!ariaContainer) {
        return;
    }
    if (isMacintosh) {
        aria_alert(msg); // VoiceOver does not seem to support status role
    }
    else {
        if (statusContainer.textContent !== msg) {
            clearNode(statusContainer2);
            insertMessage(statusContainer, msg);
        }
        else {
            clearNode(statusContainer);
            insertMessage(statusContainer2, msg);
        }
    }
}
function insertMessage(target, msg) {
    clearNode(target);
    if (msg.length > MAX_MESSAGE_LENGTH) {
        msg = msg.substr(0, MAX_MESSAGE_LENGTH);
    }
    target.textContent = msg;
    // See https://www.paciellogroup.com/blog/2012/06/html5-accessibility-chops-aria-rolealert-browser-support/
    target.style.visibility = 'hidden';
    target.style.visibility = 'visible';
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/arrays.js
/**
 * Returns the last element of an array.
 * @param array The array.
 * @param n Which element from the end (default is zero).
 */
function tail(array, n = 0) {
    return array[array.length - (1 + n)];
}
function tail2(arr) {
    if (arr.length === 0) {
        throw new Error('Invalid tail call');
    }
    return [arr.slice(0, arr.length - 1), arr[arr.length - 1]];
}
function equals(one, other, itemEquals = (a, b) => a === b) {
    if (one === other) {
        return true;
    }
    if (!one || !other) {
        return false;
    }
    if (one.length !== other.length) {
        return false;
    }
    for (let i = 0, len = one.length; i < len; i++) {
        if (!itemEquals(one[i], other[i])) {
            return false;
        }
    }
    return true;
}
/**
 * Remove the element at `index` by replacing it with the last element. This is faster than `splice`
 * but changes the order of the array
 */
function removeFastWithoutKeepingOrder(array, index) {
    const last = array.length - 1;
    if (index < last) {
        array[index] = array[last];
    }
    array.pop();
}
/**
 * Performs a binary search algorithm over a sorted array.
 *
 * @param array The array being searched.
 * @param key The value we search for.
 * @param comparator A function that takes two array elements and returns zero
 *   if they are equal, a negative number if the first element precedes the
 *   second one in the sorting order, or a positive number if the second element
 *   precedes the first one.
 * @return See {@link binarySearch2}
 */
function binarySearch(array, key, comparator) {
    return binarySearch2(array.length, i => comparator(array[i], key));
}
/**
 * Performs a binary search algorithm over a sorted collection. Useful for cases
 * when we need to perform a binary search over something that isn't actually an
 * array, and converting data to an array would defeat the use of binary search
 * in the first place.
 *
 * @param length The collection length.
 * @param compareToKey A function that takes an index of an element in the
 *   collection and returns zero if the value at this index is equal to the
 *   search key, a negative number if the value precedes the search key in the
 *   sorting order, or a positive number if the search key precedes the value.
 * @return A non-negative index of an element, if found. If not found, the
 *   result is -(n+1) (or ~n, using bitwise notation), where n is the index
 *   where the key should be inserted to maintain the sorting order.
 */
function binarySearch2(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);
}
/**
 * Takes a sorted array and a function p. The array is sorted in such a way that all elements where p(x) is false
 * are located before all elements where p(x) is true.
 * @returns the least x for which p(x) is true or array.length if no element fullfills the given function.
 */
function findFirstInSorted(array, p) {
    let low = 0, high = array.length;
    if (high === 0) {
        return 0; // no children
    }
    while (low < high) {
        const mid = Math.floor((low + high) / 2);
        if (p(array[mid])) {
            high = mid;
        }
        else {
            low = mid + 1;
        }
    }
    return low;
}
function quickSelect(nth, data, compare) {
    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 = compare(value, pivotValue);
        if (val < 0) {
            lower.push(value);
        }
        else if (val > 0) {
            higher.push(value);
        }
        else {
            pivots.push(value);
        }
    }
    if (nth < lower.length) {
        return quickSelect(nth, lower, compare);
    }
    else if (nth < lower.length + pivots.length) {
        return pivots[0];
    }
    else {
        return quickSelect(nth - (lower.length + pivots.length), higher, compare);
    }
}
function groupBy(data, compare) {
    const result = [];
    let currentGroup = undefined;
    for (const element of data.slice(0).sort(compare)) {
        if (!currentGroup || compare(currentGroup[0], element) !== 0) {
            currentGroup = [element];
            result.push(currentGroup);
        }
        else {
            currentGroup.push(element);
        }
    }
    return result;
}
/**
 * @returns New array with all falsy values removed. The original array IS NOT modified.
 */
function coalesce(array) {
    return array.filter(e => !!e);
}
/**
 * @returns false if the provided object is an array and not empty.
 */
function isFalsyOrEmpty(obj) {
    return !Array.isArray(obj) || obj.length === 0;
}
function isNonEmptyArray(obj) {
    return Array.isArray(obj) && obj.length > 0;
}
/**
 * Removes duplicates from the given array. The optional keyFn allows to specify
 * how elements are checked for equality by returning an alternate value for each.
 */
function distinct(array, keyFn = value => value) {
    const seen = new Set();
    return array.filter(element => {
        const key = keyFn(element);
        if (seen.has(key)) {
            return false;
        }
        seen.add(key);
        return true;
    });
}
function findLast(arr, predicate) {
    const idx = lastIndex(arr, predicate);
    if (idx === -1) {
        return undefined;
    }
    return arr[idx];
}
function lastIndex(array, fn) {
    for (let i = array.length - 1; i >= 0; i--) {
        const element = array[i];
        if (fn(element)) {
            return i;
        }
    }
    return -1;
}
function firstOrDefault(array, notFoundValue) {
    return array.length > 0 ? array[0] : notFoundValue;
}
function range(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 i = from; i < to; i++) {
            result.push(i);
        }
    }
    else {
        for (let i = from; i > to; i--) {
            result.push(i);
        }
    }
    return result;
}
/**
 * Insert `insertArr` inside `target` at `insertIndex`.
 * Please don't touch unless you understand https://jsperf.com/inserting-an-array-within-an-array
 */
function arrayInsert(target, insertIndex, insertArr) {
    const before = target.slice(0, insertIndex);
    const after = target.slice(insertIndex);
    return before.concat(insertArr, after);
}
/**
 * Pushes an element to the start of the array, if found.
 */
function pushToStart(arr, value) {
    const index = arr.indexOf(value);
    if (index > -1) {
        arr.splice(index, 1);
        arr.unshift(value);
    }
}
/**
 * Pushes an element to the end of the array, if found.
 */
function pushToEnd(arr, value) {
    const index = arr.indexOf(value);
    if (index > -1) {
        arr.splice(index, 1);
        arr.push(value);
    }
}
function pushMany(arr, items) {
    for (const item of items) {
        arr.push(item);
    }
}
function asArray(x) {
    return Array.isArray(x) ? x : [x];
}
/**
 * Insert the new items in the array.
 * @param array The original array.
 * @param start The zero-based location in the array from which to start inserting elements.
 * @param newItems The items to be inserted
 */
function insertInto(array, start, newItems) {
    const startIdx = getActualStartIndex(array, start);
    const originalLength = array.length;
    const newItemsLength = newItems.length;
    array.length = originalLength + newItemsLength;
    // Move the items after the start index, start from the end so that we don't overwrite any value.
    for (let i = originalLength - 1; i >= startIdx; i--) {
        array[i + newItemsLength] = array[i];
    }
    for (let i = 0; i < newItemsLength; i++) {
        array[i + startIdx] = newItems[i];
    }
}
/**
 * Removes elements from an array and inserts new elements in their place, returning the deleted elements. Alternative to the native Array.splice method, it
 * can only support limited number of items due to the maximum call stack size limit.
 * @param array The original array.
 * @param start The zero-based location in the array from which to start removing elements.
 * @param deleteCount The number of elements to remove.
 * @returns An array containing the elements that were deleted.
 */
function splice(array, start, deleteCount, newItems) {
    const index = getActualStartIndex(array, start);
    const result = array.splice(index, deleteCount);
    insertInto(array, index, newItems);
    return result;
}
/**
 * Determine the actual start index (same logic as the native splice() or slice())
 * If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided.
 * If negative, it will begin that many elements from the end of the array. (In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of array.length - n.) If array.length + start is less than 0, it will begin from index 0.
 * @param array The target array.
 * @param start The operation index.
 */
function getActualStartIndex(array, start) {
    return start < 0 ? Math.max(start + array.length, 0) : Math.min(start, array.length);
}
var CompareResult;
(function (CompareResult) {
    function isLessThan(result) {
        return result < 0;
    }
    CompareResult.isLessThan = isLessThan;
    function isGreaterThan(result) {
        return result > 0;
    }
    CompareResult.isGreaterThan = isGreaterThan;
    function isNeitherLessOrGreaterThan(result) {
        return result === 0;
    }
    CompareResult.isNeitherLessOrGreaterThan = isNeitherLessOrGreaterThan;
    CompareResult.greaterThan = 1;
    CompareResult.lessThan = -1;
    CompareResult.neitherLessOrGreaterThan = 0;
})(CompareResult || (CompareResult = {}));
function compareBy(selector, comparator) {
    return (a, b) => comparator(selector(a), selector(b));
}
/**
 * The natural order on numbers.
*/
const numberComparator = (a, b) => a - b;
/**
 * Returns the first item that is equal to or greater than every other item.
*/
function findMaxBy(items, comparator) {
    if (items.length === 0) {
        return undefined;
    }
    let max = items[0];
    for (let i = 1; i < items.length; i++) {
        const item = items[i];
        if (comparator(item, max) > 0) {
            max = item;
        }
    }
    return max;
}
/**
 * Returns the last item that is equal to or greater than every other item.
*/
function findLastMaxBy(items, comparator) {
    if (items.length === 0) {
        return undefined;
    }
    let max = items[0];
    for (let i = 1; i < items.length; i++) {
        const item = items[i];
        if (comparator(item, max) >= 0) {
            max = item;
        }
    }
    return max;
}
/**
 * Returns the first item that is equal to or less than every other item.
*/
function findMinBy(items, comparator) {
    return findMaxBy(items, (a, b) => -comparator(a, b));
}
class ArrayQueue {
    /**
     * Constructs a queue that is backed by the given array. Runtime is O(1).
    */
    constructor(items) {
        this.items = items;
        this.firstIdx = 0;
        this.lastIdx = this.items.length - 1;
    }
    get length() {
        return this.lastIdx - this.firstIdx + 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) {
        // P(k) := k <= this.lastIdx && predicate(this.items[k])
        // Find s := min { k | k >= this.firstIdx && !P(k) } and return this.data[this.firstIdx...s)
        let startIdx = this.firstIdx;
        while (startIdx < this.items.length && predicate(this.items[startIdx])) {
            startIdx++;
        }
        const result = startIdx === this.firstIdx ? null : this.items.slice(this.firstIdx, startIdx);
        this.firstIdx = 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) {
        // P(k) := this.firstIdx >= k && predicate(this.items[k])
        // Find s := max { k | k <= this.lastIdx && !P(k) } and return this.data(s...this.lastIdx]
        let endIdx = this.lastIdx;
        while (endIdx >= 0 && predicate(this.items[endIdx])) {
            endIdx--;
        }
        const result = endIdx === this.lastIdx ? null : this.items.slice(endIdx + 1, this.lastIdx + 1);
        this.lastIdx = endIdx;
        return result;
    }
    peek() {
        if (this.length === 0) {
            return undefined;
        }
        return this.items[this.firstIdx];
    }
    dequeue() {
        const result = this.items[this.firstIdx];
        this.firstIdx++;
        return result;
    }
    takeCount(count) {
        const result = this.items.slice(this.firstIdx, this.firstIdx + count);
        this.firstIdx += count;
        return result;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/decorators.js
function memoize(_target, key, descriptor) {
    let fnKey = null;
    let fn = null;
    if (typeof descriptor.value === 'function') {
        fnKey = 'value';
        fn = descriptor.value;
        if (fn.length !== 0) {
            console.warn('Memoize should only be used in functions with zero parameters');
        }
    }
    else if (typeof descriptor.get === 'function') {
        fnKey = 'get';
        fn = descriptor.get;
    }
    if (!fn) {
        throw new Error('not supported');
    }
    const memoizeKey = `$memoize$${key}`;
    descriptor[fnKey] = function (...args) {
        if (!this.hasOwnProperty(memoizeKey)) {
            Object.defineProperty(this, memoizeKey, {
                configurable: false,
                enumerable: false,
                writable: false,
                value: fn.apply(this, args)
            });
        }
        return this[memoizeKey];
    };
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/touch.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};




var touch_EventType;
(function (EventType) {
    EventType.Tap = '-monaco-gesturetap';
    EventType.Change = '-monaco-gesturechange';
    EventType.Start = '-monaco-gesturestart';
    EventType.End = '-monaco-gesturesend';
    EventType.Contextmenu = '-monaco-gesturecontextmenu';
})(touch_EventType || (touch_EventType = {}));
class Gesture extends Disposable {
    constructor() {
        super();
        this.dispatched = false;
        this.activeTouches = {};
        this.handle = null;
        this.targets = [];
        this.ignoreTargets = [];
        this._lastSetTapCountTime = 0;
        this._register(addDisposableListener(document, 'touchstart', (e) => this.onTouchStart(e), { passive: false }));
        this._register(addDisposableListener(document, 'touchend', (e) => this.onTouchEnd(e)));
        this._register(addDisposableListener(document, 'touchmove', (e) => this.onTouchMove(e), { passive: false }));
    }
    static addTarget(element) {
        if (!Gesture.isTouchDevice()) {
            return Disposable.None;
        }
        if (!Gesture.INSTANCE) {
            Gesture.INSTANCE = new Gesture();
        }
        Gesture.INSTANCE.targets.push(element);
        return {
            dispose: () => {
                Gesture.INSTANCE.targets = Gesture.INSTANCE.targets.filter(t => t !== element);
            }
        };
    }
    static ignoreTarget(element) {
        if (!Gesture.isTouchDevice()) {
            return Disposable.None;
        }
        if (!Gesture.INSTANCE) {
            Gesture.INSTANCE = new Gesture();
        }
        Gesture.INSTANCE.ignoreTargets.push(element);
        return {
            dispose: () => {
                Gesture.INSTANCE.ignoreTargets = Gesture.INSTANCE.ignoreTargets.filter(t => t !== element);
            }
        };
    }
    static isTouchDevice() {
        // `'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
        return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
    }
    dispose() {
        if (this.handle) {
            this.handle.dispose();
            this.handle = null;
        }
        super.dispose();
    }
    onTouchStart(e) {
        const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
        if (this.handle) {
            this.handle.dispose();
            this.handle = null;
        }
        for (let i = 0, len = e.targetTouches.length; i < len; i++) {
            const touch = e.targetTouches.item(i);
            this.activeTouches[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.newGestureEvent(touch_EventType.Start, touch.target);
            evt.pageX = touch.pageX;
            evt.pageY = touch.pageY;
            this.dispatchEvent(evt);
        }
        if (this.dispatched) {
            e.preventDefault();
            e.stopPropagation();
            this.dispatched = false;
        }
    }
    onTouchEnd(e) {
        const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
        const activeTouchCount = Object.keys(this.activeTouches).length;
        for (let i = 0, len = e.changedTouches.length; i < len; i++) {
            const touch = e.changedTouches.item(i);
            if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
                console.warn('move of an UNKNOWN touch', touch);
                continue;
            }
            const data = this.activeTouches[touch.identifier], holdTime = Date.now() - data.initialTimeStamp;
            if (holdTime < Gesture.HOLD_DELAY
                && Math.abs(data.initialPageX - tail(data.rollingPageX)) < 30
                && Math.abs(data.initialPageY - tail(data.rollingPageY)) < 30) {
                const evt = this.newGestureEvent(touch_EventType.Tap, data.initialTarget);
                evt.pageX = tail(data.rollingPageX);
                evt.pageY = tail(data.rollingPageY);
                this.dispatchEvent(evt);
            }
            else if (holdTime >= Gesture.HOLD_DELAY
                && Math.abs(data.initialPageX - tail(data.rollingPageX)) < 30
                && Math.abs(data.initialPageY - tail(data.rollingPageY)) < 30) {
                const evt = this.newGestureEvent(touch_EventType.Contextmenu, data.initialTarget);
                evt.pageX = tail(data.rollingPageX);
                evt.pageY = tail(data.rollingPageY);
                this.dispatchEvent(evt);
            }
            else if (activeTouchCount === 1) {
                const finalX = tail(data.rollingPageX);
                const finalY = tail(data.rollingPageY);
                const deltaT = tail(data.rollingTimestamps) - data.rollingTimestamps[0];
                const deltaX = finalX - data.rollingPageX[0];
                const deltaY = finalY - data.rollingPageY[0];
                // We need to get all the dispatch targets on the start of the inertia event
                const dispatchTo = this.targets.filter(t => data.initialTarget instanceof Node && t.contains(data.initialTarget));
                this.inertia(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.dispatchEvent(this.newGestureEvent(touch_EventType.End, data.initialTarget));
            // forget about this touch
            delete this.activeTouches[touch.identifier];
        }
        if (this.dispatched) {
            e.preventDefault();
            e.stopPropagation();
            this.dispatched = false;
        }
    }
    newGestureEvent(type, initialTarget) {
        const event = document.createEvent('CustomEvent');
        event.initEvent(type, false, true);
        event.initialTarget = initialTarget;
        event.tapCount = 0;
        return event;
    }
    dispatchEvent(event) {
        if (event.type === touch_EventType.Tap) {
            const currentTime = (new Date()).getTime();
            let setTapCount = 0;
            if (currentTime - this._lastSetTapCountTime > Gesture.CLEAR_TAP_COUNT_TIME) {
                setTapCount = 1;
            }
            else {
                setTapCount = 2;
            }
            this._lastSetTapCountTime = currentTime;
            event.tapCount = setTapCount;
        }
        else if (event.type === touch_EventType.Change || event.type === touch_EventType.Contextmenu) {
            // tap is canceled by scrolling or context menu
            this._lastSetTapCountTime = 0;
        }
        for (let i = 0; i < this.ignoreTargets.length; i++) {
            if (event.initialTarget instanceof Node && this.ignoreTargets[i].contains(event.initialTarget)) {
                return;
            }
        }
        this.targets.forEach(target => {
            if (event.initialTarget instanceof Node && target.contains(event.initialTarget)) {
                target.dispatchEvent(event);
                this.dispatched = true;
            }
        });
    }
    inertia(dispatchTo, t1, vX, dirX, x, vY, dirY, y) {
        this.handle = scheduleAtNextAnimationFrame(() => {
            const now = Date.now();
            // velocity: old speed + accel_over_time
            const deltaT = now - t1;
            let delta_pos_x = 0, delta_pos_y = 0;
            let stopped = true;
            vX += Gesture.SCROLL_FRICTION * deltaT;
            vY += Gesture.SCROLL_FRICTION * deltaT;
            if (vX > 0) {
                stopped = false;
                delta_pos_x = dirX * vX * deltaT;
            }
            if (vY > 0) {
                stopped = false;
                delta_pos_y = dirY * vY * deltaT;
            }
            // dispatch translation event
            const evt = this.newGestureEvent(touch_EventType.Change);
            evt.translationX = delta_pos_x;
            evt.translationY = delta_pos_y;
            dispatchTo.forEach(d => d.dispatchEvent(evt));
            if (!stopped) {
                this.inertia(dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y);
            }
        });
    }
    onTouchMove(e) {
        const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
        for (let i = 0, len = e.changedTouches.length; i < len; i++) {
            const touch = e.changedTouches.item(i);
            if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
                console.warn('end of an UNKNOWN touch', touch);
                continue;
            }
            const data = this.activeTouches[touch.identifier];
            const evt = this.newGestureEvent(touch_EventType.Change, data.initialTarget);
            evt.translationX = touch.pageX - tail(data.rollingPageX);
            evt.translationY = touch.pageY - tail(data.rollingPageY);
            evt.pageX = touch.pageX;
            evt.pageY = touch.pageY;
            this.dispatchEvent(evt);
            // only keep a few data points, to average the final speed
            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.dispatched) {
            e.preventDefault();
            e.stopPropagation();
            this.dispatched = false;
        }
    }
}
Gesture.SCROLL_FRICTION = -0.005;
Gesture.HOLD_DELAY = 700;
Gesture.CLEAR_TAP_COUNT_TIME = 400; // ms
__decorate([
    memoize
], Gesture, "isTouchDevice", null);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/widget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class Widget extends Disposable {
    onclick(domNode, listener) {
        this._register(addDisposableListener(domNode, EventType.CLICK, (e) => listener(new StandardMouseEvent(e))));
    }
    onmousedown(domNode, listener) {
        this._register(addDisposableListener(domNode, EventType.MOUSE_DOWN, (e) => listener(new StandardMouseEvent(e))));
    }
    onmouseover(domNode, listener) {
        this._register(addDisposableListener(domNode, EventType.MOUSE_OVER, (e) => listener(new StandardMouseEvent(e))));
    }
    onmouseleave(domNode, listener) {
        this._register(addDisposableListener(domNode, EventType.MOUSE_LEAVE, (e) => listener(new StandardMouseEvent(e))));
    }
    onkeydown(domNode, listener) {
        this._register(addDisposableListener(domNode, EventType.KEY_DOWN, (e) => listener(new StandardKeyboardEvent(e))));
    }
    onkeyup(domNode, listener) {
        this._register(addDisposableListener(domNode, EventType.KEY_UP, (e) => listener(new StandardKeyboardEvent(e))));
    }
    oninput(domNode, listener) {
        this._register(addDisposableListener(domNode, EventType.INPUT, listener));
    }
    onblur(domNode, listener) {
        this._register(addDisposableListener(domNode, EventType.BLUR, listener));
    }
    onfocus(domNode, listener) {
        this._register(addDisposableListener(domNode, EventType.FOCUS, listener));
    }
    ignoreGesture(domNode) {
        Gesture.ignoreTarget(domNode);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/cache.js
/**
 * Uses a LRU cache to make a given parametrized function cached.
 * Caches just the last value.
 * The key must be JSON serializable.
*/
class LRUCachedFunction {
    constructor(fn) {
        this.fn = fn;
        this.lastCache = undefined;
        this.lastArgKey = undefined;
    }
    get(arg) {
        const key = JSON.stringify(arg);
        if (this.lastArgKey !== key) {
            this.lastArgKey = key;
            this.lastCache = this.fn(arg);
        }
        return this.lastCache;
    }
}
/**
 * Uses an unbounded cache (referential equality) to memoize the results of the given function.
*/
class CachedFunction {
    constructor(fn) {
        this.fn = fn;
        this._map = new Map();
    }
    get cachedValues() {
        return this._map;
    }
    get(arg) {
        if (this._map.has(arg)) {
            return this._map.get(arg);
        }
        const value = this.fn(arg);
        this._map.set(arg, value);
        return value;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/lazy.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class Lazy {
    constructor(executor) {
        this.executor = executor;
        this._didRun = false;
    }
    /**
     * True if the lazy value has been resolved.
     */
    hasValue() { return this._didRun; }
    /**
     * 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
     */
    getValue() {
        if (!this._didRun) {
            try {
                this._value = this.executor();
            }
            catch (err) {
                this._error = err;
            }
            finally {
                this._didRun = true;
            }
        }
        if (this._error) {
            throw this._error;
        }
        return this._value;
    }
    /**
     * Get the wrapped value without forcing evaluation.
     */
    get rawValue() { return this._value; }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/strings.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var strings_a;


function isFalsyOrWhitespace(str) {
    if (!str || typeof str !== 'string') {
        return true;
    }
    return str.trim().length === 0;
}
const _formatRegexp = /{(\d+)}/g;
/**
 * Helper to produce a string with a variable number of arguments. Insert variable segments
 * into the string using the {n} notation where N is the index of the argument following the string.
 * @param value string to which formatting is applied
 * @param args replacements for {n}-entries
 */
function format(value, ...args) {
    if (args.length === 0) {
        return value;
    }
    return value.replace(_formatRegexp, function (match, group) {
        const idx = parseInt(group, 10);
        return isNaN(idx) || idx < 0 || idx >= args.length ?
            match :
            args[idx];
    });
}
/**
 * Converts HTML characters inside the string to use entities instead. Makes the string safe from
 * being used e.g. in HTMLElement.innerHTML.
 */
function strings_escape(html) {
    return html.replace(/[<>&]/g, function (match) {
        switch (match) {
            case '<': return '&lt;';
            case '>': return '&gt;';
            case '&': return '&amp;';
            default: return match;
        }
    });
}
/**
 * Escapes regular expression characters in a given string
 */
function escapeRegExpCharacters(value) {
    return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, '\\$&');
}
/**
 * Removes all occurrences of needle from the beginning and end of haystack.
 * @param haystack string to trim
 * @param needle the thing to trim (default is a blank)
 */
function trim(haystack, needle = ' ') {
    const trimmed = ltrim(haystack, needle);
    return rtrim(trimmed, needle);
}
/**
 * Removes all occurrences of needle from the beginning of haystack.
 * @param haystack string to trim
 * @param needle the thing to trim
 */
function ltrim(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);
}
/**
 * Removes all occurrences of needle from the end of haystack.
 * @param haystack string to trim
 * @param needle the thing to trim
 */
function rtrim(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 convertSimple2RegExpPattern(pattern) {
    return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
}
function stripWildcards(pattern) {
    return pattern.replace(/\*/g, '');
}
function createRegExp(searchString, isRegex, options = {}) {
    if (!searchString) {
        throw new Error('Cannot create regex from empty string');
    }
    if (!isRegex) {
        searchString = escapeRegExpCharacters(searchString);
    }
    if (options.wholeWord) {
        if (!/\B/.test(searchString.charAt(0))) {
            searchString = '\\b' + searchString;
        }
        if (!/\B/.test(searchString.charAt(searchString.length - 1))) {
            searchString = searchString + '\\b';
        }
    }
    let modifiers = '';
    if (options.global) {
        modifiers += 'g';
    }
    if (!options.matchCase) {
        modifiers += 'i';
    }
    if (options.multiline) {
        modifiers += 'm';
    }
    if (options.unicode) {
        modifiers += 'u';
    }
    return new RegExp(searchString, modifiers);
}
function regExpLeadsToEndlessLoop(regexp) {
    // Exit early if it's one of these special cases which are meant to match
    // against an empty string
    if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$' || regexp.source === '^\\s*$') {
        return false;
    }
    // We check against an empty string. If the regular expression doesn't advance
    // (e.g. ends in an endless loop) it will match an empty string.
    const match = regexp.exec('');
    return !!(match && regexp.lastIndex === 0);
}
function regExpFlags(regexp) {
    return (regexp.global ? 'g' : '')
        + (regexp.ignoreCase ? 'i' : '')
        + (regexp.multiline ? 'm' : '')
        + (regexp /* standalone editor compilation */.unicode ? 'u' : '');
}
function splitLines(str) {
    return str.split(/\r\n|\r|\n/);
}
/**
 * Returns first index of the string that is not whitespace.
 * If string is empty or contains only whitespaces, returns -1
 */
function strings_firstNonWhitespaceIndex(str) {
    for (let i = 0, len = str.length; i < len; i++) {
        const chCode = str.charCodeAt(i);
        if (chCode !== 32 /* CharCode.Space */ && chCode !== 9 /* CharCode.Tab */) {
            return i;
        }
    }
    return -1;
}
/**
 * Returns the leading whitespace of the string.
 * If the string contains only whitespaces, returns entire string
 */
function getLeadingWhitespace(str, start = 0, end = str.length) {
    for (let i = start; i < end; i++) {
        const chCode = str.charCodeAt(i);
        if (chCode !== 32 /* CharCode.Space */ && chCode !== 9 /* CharCode.Tab */) {
            return str.substring(start, i);
        }
    }
    return str.substring(start, end);
}
/**
 * Returns last index of the string that is not whitespace.
 * If string is empty or contains only whitespaces, returns -1
 */
function strings_lastNonWhitespaceIndex(str, startIndex = str.length - 1) {
    for (let i = startIndex; i >= 0; i--) {
        const chCode = str.charCodeAt(i);
        if (chCode !== 32 /* CharCode.Space */ && chCode !== 9 /* CharCode.Tab */) {
            return i;
        }
    }
    return -1;
}
function compare(a, b) {
    if (a < b) {
        return -1;
    }
    else if (a > b) {
        return 1;
    }
    else {
        return 0;
    }
}
function compareSubstring(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 compareIgnoreCase(a, b) {
    return compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length);
}
function compareSubstringIgnoreCase(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) {
            // equal
            continue;
        }
        if (codeA >= 128 || codeB >= 128) {
            // not ASCII letters -> fallback to lower-casing strings
            return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd);
        }
        // mapper lower-case ascii letter onto upper-case varinats
        // [97-122] (lower ascii) --> [65-90] (upper ascii)
        if (isLowerAsciiLetter(codeA)) {
            codeA -= 32;
        }
        if (isLowerAsciiLetter(codeB)) {
            codeB -= 32;
        }
        // compare both code points
        const diff = codeA - codeB;
        if (diff === 0) {
            continue;
        }
        return diff;
    }
    const aLen = aEnd - aStart;
    const bLen = bEnd - bStart;
    if (aLen < bLen) {
        return -1;
    }
    else if (aLen > bLen) {
        return 1;
    }
    return 0;
}
function isAsciiDigit(code) {
    return code >= 48 /* CharCode.Digit0 */ && code <= 57 /* CharCode.Digit9 */;
}
function isLowerAsciiLetter(code) {
    return code >= 97 /* CharCode.a */ && code <= 122 /* CharCode.z */;
}
function isUpperAsciiLetter(code) {
    return code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */;
}
function equalsIgnoreCase(a, b) {
    return a.length === b.length && compareSubstringIgnoreCase(a, b) === 0;
}
function startsWithIgnoreCase(str, candidate) {
    const candidateLength = candidate.length;
    if (candidate.length > str.length) {
        return false;
    }
    return compareSubstringIgnoreCase(str, candidate, 0, candidateLength) === 0;
}
/**
 * @returns the length of the common prefix of the two strings.
 */
function strings_commonPrefixLength(a, b) {
    const len = Math.min(a.length, b.length);
    let i;
    for (i = 0; i < len; i++) {
        if (a.charCodeAt(i) !== b.charCodeAt(i)) {
            return i;
        }
    }
    return len;
}
/**
 * @returns the length of the common suffix of the two strings.
 */
function strings_commonSuffixLength(a, b) {
    const len = Math.min(a.length, b.length);
    let i;
    const aLastIndex = a.length - 1;
    const bLastIndex = b.length - 1;
    for (i = 0; i < len; i++) {
        if (a.charCodeAt(aLastIndex - i) !== b.charCodeAt(bLastIndex - i)) {
            return i;
        }
    }
    return len;
}
/**
 * See http://en.wikipedia.org/wiki/Surrogate_pair
 */
function isHighSurrogate(charCode) {
    return (0xD800 <= charCode && charCode <= 0xDBFF);
}
/**
 * See http://en.wikipedia.org/wiki/Surrogate_pair
 */
function isLowSurrogate(charCode) {
    return (0xDC00 <= charCode && charCode <= 0xDFFF);
}
/**
 * See http://en.wikipedia.org/wiki/Surrogate_pair
 */
function computeCodePoint(highSurrogate, lowSurrogate) {
    return ((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000;
}
/**
 * get the code point that begins at offset `offset`
 */
function getNextCodePoint(str, len, offset) {
    const charCode = str.charCodeAt(offset);
    if (isHighSurrogate(charCode) && offset + 1 < len) {
        const nextCharCode = str.charCodeAt(offset + 1);
        if (isLowSurrogate(nextCharCode)) {
            return computeCodePoint(charCode, nextCharCode);
        }
    }
    return charCode;
}
/**
 * get the code point that ends right before offset `offset`
 */
function getPrevCodePoint(str, offset) {
    const charCode = str.charCodeAt(offset - 1);
    if (isLowSurrogate(charCode) && offset > 1) {
        const prevCharCode = str.charCodeAt(offset - 2);
        if (isHighSurrogate(prevCharCode)) {
            return computeCodePoint(prevCharCode, charCode);
        }
    }
    return charCode;
}
class CodePointIterator {
    constructor(str, offset = 0) {
        this._str = str;
        this._len = str.length;
        this._offset = offset;
    }
    get offset() {
        return this._offset;
    }
    setOffset(offset) {
        this._offset = offset;
    }
    prevCodePoint() {
        const codePoint = getPrevCodePoint(this._str, this._offset);
        this._offset -= (codePoint >= 65536 /* Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
        return codePoint;
    }
    nextCodePoint() {
        const codePoint = getNextCodePoint(this._str, this._len, this._offset);
        this._offset += (codePoint >= 65536 /* Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1);
        return codePoint;
    }
    eol() {
        return (this._offset >= this._len);
    }
}
class GraphemeIterator {
    constructor(str, offset = 0) {
        this._iterator = new CodePointIterator(str, offset);
    }
    get offset() {
        return this._iterator.offset;
    }
    nextGraphemeLength() {
        const graphemeBreakTree = GraphemeBreakTree.getInstance();
        const iterator = this._iterator;
        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)) {
                // move iterator back
                iterator.setOffset(offset);
                break;
            }
            graphemeBreakType = nextGraphemeBreakType;
        }
        return (iterator.offset - initialOffset);
    }
    prevGraphemeLength() {
        const graphemeBreakTree = GraphemeBreakTree.getInstance();
        const iterator = this._iterator;
        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)) {
                // move iterator back
                iterator.setOffset(offset);
                break;
            }
            graphemeBreakType = prevGraphemeBreakType;
        }
        return (initialOffset - iterator.offset);
    }
    eol() {
        return this._iterator.eol();
    }
}
function nextCharLength(str, initialOffset) {
    const iterator = new GraphemeIterator(str, initialOffset);
    return iterator.nextGraphemeLength();
}
function prevCharLength(str, initialOffset) {
    const iterator = new GraphemeIterator(str, initialOffset);
    return iterator.prevGraphemeLength();
}
function getCharContainingOffset(str, offset) {
    if (offset > 0 && isLowSurrogate(str.charCodeAt(offset))) {
        offset--;
    }
    const endOffset = offset + nextCharLength(str, offset);
    const startOffset = endOffset - prevCharLength(str, endOffset);
    return [startOffset, endOffset];
}
/**
 * Generated using https://github.com/alexdima/unicode-utils/blob/main/rtl-test.js
 */
const CONTAINS_RTL = /(?:[\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])/;
/**
 * Returns true if `str` contains any Unicode character that is classified as "R" or "AL".
 */
function strings_containsRTL(str) {
    return CONTAINS_RTL.test(str);
}
const IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/;
/**
 * Returns true if `str` contains only basic ASCII characters in the range 32 - 126 (including 32 and 126) or \n, \r, \t
 */
function strings_isBasicASCII(str) {
    return IS_BASIC_ASCII.test(str);
}
const UNUSUAL_LINE_TERMINATORS = /[\u2028\u2029]/; // LINE SEPARATOR (LS) or PARAGRAPH SEPARATOR (PS)
/**
 * Returns true if `str` contains unusual line terminators, like LS or PS
 */
function containsUnusualLineTerminators(str) {
    return UNUSUAL_LINE_TERMINATORS.test(str);
}
function isFullWidthCharacter(charCode) {
    // Do a cheap trick to better support wrapping of wide characters, treat them as 2 columns
    // http://jrgraphix.net/research/unicode_blocks.php
    //          2E80 - 2EFF   CJK Radicals Supplement
    //          2F00 - 2FDF   Kangxi Radicals
    //          2FF0 - 2FFF   Ideographic Description Characters
    //          3000 - 303F   CJK Symbols and Punctuation
    //          3040 - 309F   Hiragana
    //          30A0 - 30FF   Katakana
    //          3100 - 312F   Bopomofo
    //          3130 - 318F   Hangul Compatibility Jamo
    //          3190 - 319F   Kanbun
    //          31A0 - 31BF   Bopomofo Extended
    //          31F0 - 31FF   Katakana Phonetic Extensions
    //          3200 - 32FF   Enclosed CJK Letters and Months
    //          3300 - 33FF   CJK Compatibility
    //          3400 - 4DBF   CJK Unified Ideographs Extension A
    //          4DC0 - 4DFF   Yijing Hexagram Symbols
    //          4E00 - 9FFF   CJK Unified Ideographs
    //          A000 - A48F   Yi Syllables
    //          A490 - A4CF   Yi Radicals
    //          AC00 - D7AF   Hangul Syllables
    // [IGNORE] D800 - DB7F   High Surrogates
    // [IGNORE] DB80 - DBFF   High Private Use Surrogates
    // [IGNORE] DC00 - DFFF   Low Surrogates
    // [IGNORE] E000 - F8FF   Private Use Area
    //          F900 - FAFF   CJK Compatibility Ideographs
    // [IGNORE] FB00 - FB4F   Alphabetic Presentation Forms
    // [IGNORE] FB50 - FDFF   Arabic Presentation Forms-A
    // [IGNORE] FE00 - FE0F   Variation Selectors
    // [IGNORE] FE20 - FE2F   Combining Half Marks
    // [IGNORE] FE30 - FE4F   CJK Compatibility Forms
    // [IGNORE] FE50 - FE6F   Small Form Variants
    // [IGNORE] FE70 - FEFF   Arabic Presentation Forms-B
    //          FF00 - FFEF   Halfwidth and Fullwidth Forms
    //               [https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms]
    //               of which FF01 - FF5E fullwidth ASCII of 21 to 7E
    // [IGNORE]    and FF65 - FFDC halfwidth of Katakana and Hangul
    // [IGNORE] FFF0 - FFFF   Specials
    return ((charCode >= 0x2E80 && charCode <= 0xD7AF)
        || (charCode >= 0xF900 && charCode <= 0xFAFF)
        || (charCode >= 0xFF01 && charCode <= 0xFF5E));
}
/**
 * A fast function (therefore imprecise) to check if code points are emojis.
 * Generated using https://github.com/alexdima/unicode-utils/blob/main/emoji-test.js
 */
function isEmojiImprecise(x) {
    return ((x >= 0x1F1E6 && x <= 0x1F1FF) || (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));
}
// -- UTF-8 BOM
const UTF8_BOM_CHARACTER = String.fromCharCode(65279 /* CharCode.UTF8_BOM */);
function startsWithUTF8BOM(str) {
    return !!(str && str.length > 0 && str.charCodeAt(0) === 65279 /* CharCode.UTF8_BOM */);
}
function containsUppercaseCharacter(target, ignoreEscapedChars = false) {
    if (!target) {
        return false;
    }
    if (ignoreEscapedChars) {
        target = target.replace(/\\./g, '');
    }
    return target.toLowerCase() !== target;
}
/**
 * Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc.
 */
function singleLetterHash(n) {
    const LETTERS_CNT = (90 /* CharCode.Z */ - 65 /* CharCode.A */ + 1);
    n = n % (2 * LETTERS_CNT);
    if (n < LETTERS_CNT) {
        return String.fromCharCode(97 /* CharCode.a */ + n);
    }
    return String.fromCharCode(65 /* CharCode.A */ + n - LETTERS_CNT);
}
function breakBetweenGraphemeBreakType(breakTypeA, breakTypeB) {
    // http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules
    // !!! Let's make the common case a bit faster
    if (breakTypeA === 0 /* GraphemeBreakType.Other */) {
        // see https://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakTest-13.0.0d10.html#table
        return (breakTypeB !== 5 /* GraphemeBreakType.Extend */ && breakTypeB !== 7 /* GraphemeBreakType.SpacingMark */);
    }
    // Do not break between a CR and LF. Otherwise, break before and after controls.
    // GB3                                        CR × LF
    // GB4                       (Control | CR | LF) ÷
    // GB5                                           ÷ (Control | CR | LF)
    if (breakTypeA === 2 /* GraphemeBreakType.CR */) {
        if (breakTypeB === 3 /* GraphemeBreakType.LF */) {
            return false; // GB3
        }
    }
    if (breakTypeA === 4 /* GraphemeBreakType.Control */ || breakTypeA === 2 /* GraphemeBreakType.CR */ || breakTypeA === 3 /* GraphemeBreakType.LF */) {
        return true; // GB4
    }
    if (breakTypeB === 4 /* GraphemeBreakType.Control */ || breakTypeB === 2 /* GraphemeBreakType.CR */ || breakTypeB === 3 /* GraphemeBreakType.LF */) {
        return true; // GB5
    }
    // Do not break Hangul syllable sequences.
    // GB6                                         L × (L | V | LV | LVT)
    // GB7                                  (LV | V) × (V | T)
    // GB8                                 (LVT | T) × T
    if (breakTypeA === 8 /* GraphemeBreakType.L */) {
        if (breakTypeB === 8 /* GraphemeBreakType.L */ || breakTypeB === 9 /* GraphemeBreakType.V */ || breakTypeB === 11 /* GraphemeBreakType.LV */ || breakTypeB === 12 /* GraphemeBreakType.LVT */) {
            return false; // GB6
        }
    }
    if (breakTypeA === 11 /* GraphemeBreakType.LV */ || breakTypeA === 9 /* GraphemeBreakType.V */) {
        if (breakTypeB === 9 /* GraphemeBreakType.V */ || breakTypeB === 10 /* GraphemeBreakType.T */) {
            return false; // GB7
        }
    }
    if (breakTypeA === 12 /* GraphemeBreakType.LVT */ || breakTypeA === 10 /* GraphemeBreakType.T */) {
        if (breakTypeB === 10 /* GraphemeBreakType.T */) {
            return false; // GB8
        }
    }
    // Do not break before extending characters or ZWJ.
    // GB9                                           × (Extend | ZWJ)
    if (breakTypeB === 5 /* GraphemeBreakType.Extend */ || breakTypeB === 13 /* GraphemeBreakType.ZWJ */) {
        return false; // GB9
    }
    // The GB9a and GB9b rules only apply to extended grapheme clusters:
    // Do not break before SpacingMarks, or after Prepend characters.
    // GB9a                                          × SpacingMark
    // GB9b                                  Prepend ×
    if (breakTypeB === 7 /* GraphemeBreakType.SpacingMark */) {
        return false; // GB9a
    }
    if (breakTypeA === 1 /* GraphemeBreakType.Prepend */) {
        return false; // GB9b
    }
    // Do not break within emoji modifier sequences or emoji zwj sequences.
    // GB11    \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic}
    if (breakTypeA === 13 /* GraphemeBreakType.ZWJ */ && breakTypeB === 14 /* GraphemeBreakType.Extended_Pictographic */) {
        // Note: we are not implementing the rule entirely here to avoid introducing states
        return false; // GB11
    }
    // GB12                          sot (RI RI)* RI × RI
    // GB13                        [^RI] (RI RI)* RI × RI
    if (breakTypeA === 6 /* GraphemeBreakType.Regional_Indicator */ && breakTypeB === 6 /* GraphemeBreakType.Regional_Indicator */) {
        // Note: we are not implementing the rule entirely here to avoid introducing states
        return false; // GB12 & GB13
    }
    // GB999                                     Any ÷ Any
    return true;
}
class GraphemeBreakTree {
    constructor() {
        this._data = getGraphemeBreakRawData();
    }
    static getInstance() {
        if (!GraphemeBreakTree._INSTANCE) {
            GraphemeBreakTree._INSTANCE = new GraphemeBreakTree();
        }
        return GraphemeBreakTree._INSTANCE;
    }
    getGraphemeBreakType(codePoint) {
        // !!! Let's make 7bit ASCII a bit faster: 0..31
        if (codePoint < 32) {
            if (codePoint === 10 /* CharCode.LineFeed */) {
                return 3 /* GraphemeBreakType.LF */;
            }
            if (codePoint === 13 /* CharCode.CarriageReturn */) {
                return 2 /* GraphemeBreakType.CR */;
            }
            return 4 /* GraphemeBreakType.Control */;
        }
        // !!! Let's make 7bit ASCII a bit faster: 32..126
        if (codePoint < 127) {
            return 0 /* GraphemeBreakType.Other */;
        }
        const data = this._data;
        const nodeCount = data.length / 3;
        let nodeIndex = 1;
        while (nodeIndex <= nodeCount) {
            if (codePoint < data[3 * nodeIndex]) {
                // go left
                nodeIndex = 2 * nodeIndex;
            }
            else if (codePoint > data[3 * nodeIndex + 1]) {
                // go right
                nodeIndex = 2 * nodeIndex + 1;
            }
            else {
                // hit
                return data[3 * nodeIndex + 2];
            }
        }
        return 0 /* GraphemeBreakType.Other */;
    }
}
GraphemeBreakTree._INSTANCE = null;
function getGraphemeBreakRawData() {
    // generated using https://github.com/alexdima/unicode-utils/blob/main/grapheme-break.js
    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]');
}
//#endregion
/**
 * Computes the offset after performing a left delete on the given string,
 * while considering unicode grapheme/emoji rules.
*/
function getLeftDeleteOffset(offset, str) {
    if (offset === 0) {
        return 0;
    }
    // Try to delete emoji part.
    const emojiOffset = getOffsetBeforeLastEmojiComponent(offset, str);
    if (emojiOffset !== undefined) {
        return emojiOffset;
    }
    // Otherwise, just skip a single code point.
    const iterator = new CodePointIterator(str, offset);
    iterator.prevCodePoint();
    return iterator.offset;
}
function getOffsetBeforeLastEmojiComponent(initialOffset, str) {
    // See https://www.unicode.org/reports/tr51/tr51-14.html#EBNF_and_Regex for the
    // structure of emojis.
    const iterator = new CodePointIterator(str, initialOffset);
    let codePoint = iterator.prevCodePoint();
    // Skip modifiers
    while ((isEmojiModifier(codePoint) || codePoint === 65039 /* CodePoint.emojiVariantSelector */ || codePoint === 8419 /* CodePoint.enclosingKeyCap */)) {
        if (iterator.offset === 0) {
            // Cannot skip modifier, no preceding emoji base.
            return undefined;
        }
        codePoint = iterator.prevCodePoint();
    }
    // Expect base emoji
    if (!isEmojiImprecise(codePoint)) {
        // Unexpected code point, not a valid emoji.
        return undefined;
    }
    let resultOffset = iterator.offset;
    if (resultOffset > 0) {
        // Skip optional ZWJ code points that combine multiple emojis.
        // In theory, we should check if that ZWJ actually combines multiple emojis
        // to prevent deleting ZWJs in situations we didn't account for.
        const optionalZwjCodePoint = iterator.prevCodePoint();
        if (optionalZwjCodePoint === 8205 /* CodePoint.zwj */) {
            resultOffset = iterator.offset;
        }
    }
    return resultOffset;
}
function isEmojiModifier(codePoint) {
    return 0x1F3FB <= codePoint && codePoint <= 0x1F3FF;
}
const noBreakWhitespace = '\xa0';
class AmbiguousCharacters {
    constructor(confusableDictionary) {
        this.confusableDictionary = confusableDictionary;
    }
    static getInstance(locales) {
        return AmbiguousCharacters.cache.get(Array.from(locales));
    }
    static getLocales() {
        return AmbiguousCharacters._locales.getValue();
    }
    isAmbiguous(codePoint) {
        return this.confusableDictionary.has(codePoint);
    }
    /**
     * 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.confusableDictionary.get(codePoint);
    }
    getConfusableCodePoints() {
        return new Set(this.confusableDictionary.keys());
    }
}
strings_a = AmbiguousCharacters;
AmbiguousCharacters.ambiguousCharacterData = new Lazy(() => {
    // Generated using https://github.com/hediet/vscode-unicode-data
    // Stored as key1, value1, key2, value2, ...
    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],\"_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]}');
});
AmbiguousCharacters.cache = new LRUCachedFunction((locales) => {
    function arrayToMap(arr) {
        const result = new Map();
        for (let i = 0; i < arr.length; i += 2) {
            result.set(arr[i], arr[i + 1]);
        }
        return result;
    }
    function mergeMaps(map1, map2) {
        const result = new Map(map1);
        for (const [key, value] of map2) {
            result.set(key, value);
        }
        return result;
    }
    function intersectMaps(map1, map2) {
        if (!map1) {
            return map2;
        }
        const result = new Map();
        for (const [key, value] of map1) {
            if (map2.has(key)) {
                result.set(key, value);
            }
        }
        return result;
    }
    const data = strings_a.ambiguousCharacterData.getValue();
    let filteredLocales = locales.filter((l) => !l.startsWith('_') && l in data);
    if (filteredLocales.length === 0) {
        filteredLocales = ['_default'];
    }
    let languageSpecificMap = undefined;
    for (const locale of filteredLocales) {
        const map = arrayToMap(data[locale]);
        languageSpecificMap = intersectMaps(languageSpecificMap, map);
    }
    const commonMap = arrayToMap(data['_common']);
    const map = mergeMaps(commonMap, languageSpecificMap);
    return new AmbiguousCharacters(map);
});
AmbiguousCharacters._locales = new Lazy(() => Object.keys(AmbiguousCharacters.ambiguousCharacterData.getValue()).filter((k) => !k.startsWith('_')));
class InvisibleCharacters {
    static getRawData() {
        // Generated using https://github.com/hediet/vscode-unicode-data
        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 getData() {
        if (!this._data) {
            this._data = new Set(InvisibleCharacters.getRawData());
        }
        return this._data;
    }
    static isInvisibleCharacter(codePoint) {
        return InvisibleCharacters.getData().has(codePoint);
    }
    static get codePoints() {
        return InvisibleCharacters.getData();
    }
}
InvisibleCharacters._data = undefined;

;// ../../node_modules/monaco-editor/esm/vs/platform/instantiation/common/instantiation.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
// ------ internal util
var _util;
(function (_util) {
    _util.serviceIds = new Map();
    _util.DI_TARGET = '$di$target';
    _util.DI_DEPENDENCIES = '$di$dependencies';
    function getServiceDependencies(ctor) {
        return ctor[_util.DI_DEPENDENCIES] || [];
    }
    _util.getServiceDependencies = getServiceDependencies;
})(_util || (_util = {}));
const IInstantiationService = createDecorator('instantiationService');
function storeServiceDependency(id, target, index) {
    if (target[_util.DI_TARGET] === target) {
        target[_util.DI_DEPENDENCIES].push({ id, index });
    }
    else {
        target[_util.DI_DEPENDENCIES] = [{ id, index }];
        target[_util.DI_TARGET] = target;
    }
}
/**
 * The *only* valid way to create a {{ServiceIdentifier}}.
 */
function createDecorator(serviceId) {
    if (_util.serviceIds.has(serviceId)) {
        return _util.serviceIds.get(serviceId);
    }
    const id = function (target, key, index) {
        if (arguments.length !== 3) {
            throw new Error('@IServiceName-decorator can only be used to decorate a parameter');
        }
        storeServiceDependency(id, target, index);
    };
    id.toString = () => serviceId;
    _util.serviceIds.set(serviceId, id);
    return id;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/services/codeEditorService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const ICodeEditorService = createDecorator('codeEditorService');

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/position.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/**
 * A position in the editor.
 */
class Position {
    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 Position(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 Position.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 Position.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 Position.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 Position(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 Position(pos.lineNumber, pos.column);
    }
    /**
     * Test if `obj` is an `IPosition`.
     */
    static isIPosition(obj) {
        return (obj
            && (typeof obj.lineNumber === 'number')
            && (typeof obj.column === 'number'));
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/model.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const IModelService = createDecorator('modelService');

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/resolverService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const ITextModelService = createDecorator('textModelService');

;// ../../node_modules/monaco-editor/esm/vs/base/common/actions.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var actions_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};



class Action extends Disposable {
    constructor(id, label = '', cssClass = '', enabled = true, actionCallback) {
        super();
        this._onDidChange = this._register(new Emitter());
        this.onDidChange = this._onDidChange.event;
        this._enabled = true;
        this._id = id;
        this._label = label;
        this._cssClass = cssClass;
        this._enabled = enabled;
        this._actionCallback = actionCallback;
    }
    get id() {
        return this._id;
    }
    get label() {
        return this._label;
    }
    set label(value) {
        this._setLabel(value);
    }
    _setLabel(value) {
        if (this._label !== value) {
            this._label = value;
            this._onDidChange.fire({ label: value });
        }
    }
    get tooltip() {
        return this._tooltip || '';
    }
    set tooltip(value) {
        this._setTooltip(value);
    }
    _setTooltip(value) {
        if (this._tooltip !== value) {
            this._tooltip = value;
            this._onDidChange.fire({ tooltip: value });
        }
    }
    get class() {
        return this._cssClass;
    }
    set class(value) {
        this._setClass(value);
    }
    _setClass(value) {
        if (this._cssClass !== value) {
            this._cssClass = value;
            this._onDidChange.fire({ class: value });
        }
    }
    get enabled() {
        return this._enabled;
    }
    set enabled(value) {
        this._setEnabled(value);
    }
    _setEnabled(value) {
        if (this._enabled !== value) {
            this._enabled = value;
            this._onDidChange.fire({ enabled: value });
        }
    }
    get checked() {
        return this._checked;
    }
    set checked(value) {
        this._setChecked(value);
    }
    _setChecked(value) {
        if (this._checked !== value) {
            this._checked = value;
            this._onDidChange.fire({ checked: value });
        }
    }
    run(event, data) {
        return actions_awaiter(this, void 0, void 0, function* () {
            if (this._actionCallback) {
                yield this._actionCallback(event);
            }
        });
    }
}
class ActionRunner extends Disposable {
    constructor() {
        super(...arguments);
        this._onBeforeRun = this._register(new Emitter());
        this.onBeforeRun = this._onBeforeRun.event;
        this._onDidRun = this._register(new Emitter());
        this.onDidRun = this._onDidRun.event;
    }
    run(action, context) {
        return actions_awaiter(this, void 0, void 0, function* () {
            if (!action.enabled) {
                return;
            }
            this._onBeforeRun.fire({ action });
            let error = undefined;
            try {
                yield this.runAction(action, context);
            }
            catch (e) {
                error = e;
            }
            this._onDidRun.fire({ action, error });
        });
    }
    runAction(action, context) {
        return actions_awaiter(this, void 0, void 0, function* () {
            yield action.run(context);
        });
    }
}
class Separator extends Action {
    constructor(label) {
        super(Separator.ID, label, label ? 'separator text' : 'separator');
        this.checked = false;
        this.enabled = false;
    }
}
Separator.ID = 'vs.actions.separator';
class SubmenuAction {
    constructor(id, label, actions, cssClass) {
        this.tooltip = '';
        this.enabled = true;
        this.checked = undefined;
        this.id = id;
        this.label = label;
        this.class = cssClass;
        this._actions = actions;
    }
    get actions() { return this._actions; }
    dispose() {
        // there is NOTHING to dispose and the SubmenuAction should
        // never have anything to dispose as it is a convenience type
        // to bridge into the rendering world.
    }
    run() {
        return actions_awaiter(this, void 0, void 0, function* () { });
    }
}
class EmptySubmenuAction extends Action {
    constructor() {
        super(EmptySubmenuAction.ID, localize('submenu.empty', '(empty)'), undefined, false);
    }
}
EmptySubmenuAction.ID = 'vs.actions.empty';
function toAction(props) {
    var _a, _b;
    return {
        id: props.id,
        label: props.label,
        class: undefined,
        enabled: (_a = props.enabled) !== null && _a !== void 0 ? _a : true,
        checked: (_b = props.checked) !== null && _b !== void 0 ? _b : false,
        run: () => actions_awaiter(this, void 0, void 0, function* () { return props.run(); }),
        tooltip: props.label,
        dispose: () => { }
    };
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/codicons.js
// Selects all codicon names encapsulated in the `$()` syntax and wraps the
// results with spaces so that screen readers can read the text better.
function getCodiconAriaLabel(text) {
    if (!text) {
        return '';
    }
    return text.replace(/\$\((.*?)\)/g, (_match, codiconName) => ` ${codiconName} `).trim();
}
/**
 * The Codicon library is a set of default icons that are built-in in VS Code.
 *
 * In the product (outside of base) Codicons should only be used as defaults. In order to have all icons in VS Code
 * themeable, component should define new, UI component specific icons using `iconRegistry.registerIcon`.
 * In that call a Codicon can be named as default.
 */
class Codicon {
    constructor(id, definition, description) {
        this.id = id;
        this.definition = definition;
        this.description = description;
        Codicon._allCodicons.push(this);
    }
    get classNames() { return 'codicon codicon-' + this.id; }
    // classNamesArray is useful for migrating to ES6 classlist
    get classNamesArray() { return ['codicon', 'codicon-' + this.id]; }
    get cssSelector() { return '.codicon.codicon-' + this.id; }
    /**
     * @returns Returns all default icons covered by the codicon font. Only to be used by the icon registry in platform.
     */
    static getAll() {
        return Codicon._allCodicons;
    }
}
// registry
Codicon._allCodicons = [];
// built-in icons, with image name
Codicon.add = new Codicon('add', { fontCharacter: '\\ea60' });
Codicon.plus = new Codicon('plus', Codicon.add.definition);
Codicon.gistNew = new Codicon('gist-new', Codicon.add.definition);
Codicon.repoCreate = new Codicon('repo-create', Codicon.add.definition);
Codicon.lightbulb = new Codicon('lightbulb', { fontCharacter: '\\ea61' });
Codicon.lightBulb = new Codicon('light-bulb', { fontCharacter: '\\ea61' });
Codicon.repo = new Codicon('repo', { fontCharacter: '\\ea62' });
Codicon.repoDelete = new Codicon('repo-delete', { fontCharacter: '\\ea62' });
Codicon.gistFork = new Codicon('gist-fork', { fontCharacter: '\\ea63' });
Codicon.repoForked = new Codicon('repo-forked', { fontCharacter: '\\ea63' });
Codicon.gitPullRequest = new Codicon('git-pull-request', { fontCharacter: '\\ea64' });
Codicon.gitPullRequestAbandoned = new Codicon('git-pull-request-abandoned', { fontCharacter: '\\ea64' });
Codicon.recordKeys = new Codicon('record-keys', { fontCharacter: '\\ea65' });
Codicon.keyboard = new Codicon('keyboard', { fontCharacter: '\\ea65' });
Codicon.tag = new Codicon('tag', { fontCharacter: '\\ea66' });
Codicon.tagAdd = new Codicon('tag-add', { fontCharacter: '\\ea66' });
Codicon.tagRemove = new Codicon('tag-remove', { fontCharacter: '\\ea66' });
Codicon.person = new Codicon('person', { fontCharacter: '\\ea67' });
Codicon.personFollow = new Codicon('person-follow', { fontCharacter: '\\ea67' });
Codicon.personOutline = new Codicon('person-outline', { fontCharacter: '\\ea67' });
Codicon.personFilled = new Codicon('person-filled', { fontCharacter: '\\ea67' });
Codicon.gitBranch = new Codicon('git-branch', { fontCharacter: '\\ea68' });
Codicon.gitBranchCreate = new Codicon('git-branch-create', { fontCharacter: '\\ea68' });
Codicon.gitBranchDelete = new Codicon('git-branch-delete', { fontCharacter: '\\ea68' });
Codicon.sourceControl = new Codicon('source-control', { fontCharacter: '\\ea68' });
Codicon.mirror = new Codicon('mirror', { fontCharacter: '\\ea69' });
Codicon.mirrorPublic = new Codicon('mirror-public', { fontCharacter: '\\ea69' });
Codicon.star = new Codicon('star', { fontCharacter: '\\ea6a' });
Codicon.starAdd = new Codicon('star-add', { fontCharacter: '\\ea6a' });
Codicon.starDelete = new Codicon('star-delete', { fontCharacter: '\\ea6a' });
Codicon.starEmpty = new Codicon('star-empty', { fontCharacter: '\\ea6a' });
Codicon.comment = new Codicon('comment', { fontCharacter: '\\ea6b' });
Codicon.commentAdd = new Codicon('comment-add', { fontCharacter: '\\ea6b' });
Codicon.alert = new Codicon('alert', { fontCharacter: '\\ea6c' });
Codicon.warning = new Codicon('warning', { fontCharacter: '\\ea6c' });
Codicon.search = new Codicon('search', { fontCharacter: '\\ea6d' });
Codicon.searchSave = new Codicon('search-save', { fontCharacter: '\\ea6d' });
Codicon.logOut = new Codicon('log-out', { fontCharacter: '\\ea6e' });
Codicon.signOut = new Codicon('sign-out', { fontCharacter: '\\ea6e' });
Codicon.logIn = new Codicon('log-in', { fontCharacter: '\\ea6f' });
Codicon.signIn = new Codicon('sign-in', { fontCharacter: '\\ea6f' });
Codicon.eye = new Codicon('eye', { fontCharacter: '\\ea70' });
Codicon.eyeUnwatch = new Codicon('eye-unwatch', { fontCharacter: '\\ea70' });
Codicon.eyeWatch = new Codicon('eye-watch', { fontCharacter: '\\ea70' });
Codicon.circleFilled = new Codicon('circle-filled', { fontCharacter: '\\ea71' });
Codicon.primitiveDot = new Codicon('primitive-dot', { fontCharacter: '\\ea71' });
Codicon.closeDirty = new Codicon('close-dirty', { fontCharacter: '\\ea71' });
Codicon.debugBreakpoint = new Codicon('debug-breakpoint', { fontCharacter: '\\ea71' });
Codicon.debugBreakpointDisabled = new Codicon('debug-breakpoint-disabled', { fontCharacter: '\\ea71' });
Codicon.debugHint = new Codicon('debug-hint', { fontCharacter: '\\ea71' });
Codicon.primitiveSquare = new Codicon('primitive-square', { fontCharacter: '\\ea72' });
Codicon.edit = new Codicon('edit', { fontCharacter: '\\ea73' });
Codicon.pencil = new Codicon('pencil', { fontCharacter: '\\ea73' });
Codicon.info = new Codicon('info', { fontCharacter: '\\ea74' });
Codicon.issueOpened = new Codicon('issue-opened', { fontCharacter: '\\ea74' });
Codicon.gistPrivate = new Codicon('gist-private', { fontCharacter: '\\ea75' });
Codicon.gitForkPrivate = new Codicon('git-fork-private', { fontCharacter: '\\ea75' });
Codicon.lock = new Codicon('lock', { fontCharacter: '\\ea75' });
Codicon.mirrorPrivate = new Codicon('mirror-private', { fontCharacter: '\\ea75' });
Codicon.close = new Codicon('close', { fontCharacter: '\\ea76' });
Codicon.removeClose = new Codicon('remove-close', { fontCharacter: '\\ea76' });
Codicon.x = new Codicon('x', { fontCharacter: '\\ea76' });
Codicon.repoSync = new Codicon('repo-sync', { fontCharacter: '\\ea77' });
Codicon.sync = new Codicon('sync', { fontCharacter: '\\ea77' });
Codicon.clone = new Codicon('clone', { fontCharacter: '\\ea78' });
Codicon.desktopDownload = new Codicon('desktop-download', { fontCharacter: '\\ea78' });
Codicon.beaker = new Codicon('beaker', { fontCharacter: '\\ea79' });
Codicon.microscope = new Codicon('microscope', { fontCharacter: '\\ea79' });
Codicon.vm = new Codicon('vm', { fontCharacter: '\\ea7a' });
Codicon.deviceDesktop = new Codicon('device-desktop', { fontCharacter: '\\ea7a' });
Codicon.file = new Codicon('file', { fontCharacter: '\\ea7b' });
Codicon.fileText = new Codicon('file-text', { fontCharacter: '\\ea7b' });
Codicon.more = new Codicon('more', { fontCharacter: '\\ea7c' });
Codicon.ellipsis = new Codicon('ellipsis', { fontCharacter: '\\ea7c' });
Codicon.kebabHorizontal = new Codicon('kebab-horizontal', { fontCharacter: '\\ea7c' });
Codicon.mailReply = new Codicon('mail-reply', { fontCharacter: '\\ea7d' });
Codicon.reply = new Codicon('reply', { fontCharacter: '\\ea7d' });
Codicon.organization = new Codicon('organization', { fontCharacter: '\\ea7e' });
Codicon.organizationFilled = new Codicon('organization-filled', { fontCharacter: '\\ea7e' });
Codicon.organizationOutline = new Codicon('organization-outline', { fontCharacter: '\\ea7e' });
Codicon.newFile = new Codicon('new-file', { fontCharacter: '\\ea7f' });
Codicon.fileAdd = new Codicon('file-add', { fontCharacter: '\\ea7f' });
Codicon.newFolder = new Codicon('new-folder', { fontCharacter: '\\ea80' });
Codicon.fileDirectoryCreate = new Codicon('file-directory-create', { fontCharacter: '\\ea80' });
Codicon.trash = new Codicon('trash', { fontCharacter: '\\ea81' });
Codicon.trashcan = new Codicon('trashcan', { fontCharacter: '\\ea81' });
Codicon.history = new Codicon('history', { fontCharacter: '\\ea82' });
Codicon.clock = new Codicon('clock', { fontCharacter: '\\ea82' });
Codicon.folder = new Codicon('folder', { fontCharacter: '\\ea83' });
Codicon.fileDirectory = new Codicon('file-directory', { fontCharacter: '\\ea83' });
Codicon.symbolFolder = new Codicon('symbol-folder', { fontCharacter: '\\ea83' });
Codicon.logoGithub = new Codicon('logo-github', { fontCharacter: '\\ea84' });
Codicon.markGithub = new Codicon('mark-github', { fontCharacter: '\\ea84' });
Codicon.github = new Codicon('github', { fontCharacter: '\\ea84' });
Codicon.terminal = new Codicon('terminal', { fontCharacter: '\\ea85' });
Codicon.console = new Codicon('console', { fontCharacter: '\\ea85' });
Codicon.repl = new Codicon('repl', { fontCharacter: '\\ea85' });
Codicon.zap = new Codicon('zap', { fontCharacter: '\\ea86' });
Codicon.symbolEvent = new Codicon('symbol-event', { fontCharacter: '\\ea86' });
Codicon.error = new Codicon('error', { fontCharacter: '\\ea87' });
Codicon.stop = new Codicon('stop', { fontCharacter: '\\ea87' });
Codicon.variable = new Codicon('variable', { fontCharacter: '\\ea88' });
Codicon.symbolVariable = new Codicon('symbol-variable', { fontCharacter: '\\ea88' });
Codicon.array = new Codicon('array', { fontCharacter: '\\ea8a' });
Codicon.symbolArray = new Codicon('symbol-array', { fontCharacter: '\\ea8a' });
Codicon.symbolModule = new Codicon('symbol-module', { fontCharacter: '\\ea8b' });
Codicon.symbolPackage = new Codicon('symbol-package', { fontCharacter: '\\ea8b' });
Codicon.symbolNamespace = new Codicon('symbol-namespace', { fontCharacter: '\\ea8b' });
Codicon.symbolObject = new Codicon('symbol-object', { fontCharacter: '\\ea8b' });
Codicon.symbolMethod = new Codicon('symbol-method', { fontCharacter: '\\ea8c' });
Codicon.symbolFunction = new Codicon('symbol-function', { fontCharacter: '\\ea8c' });
Codicon.symbolConstructor = new Codicon('symbol-constructor', { fontCharacter: '\\ea8c' });
Codicon.symbolBoolean = new Codicon('symbol-boolean', { fontCharacter: '\\ea8f' });
Codicon.symbolNull = new Codicon('symbol-null', { fontCharacter: '\\ea8f' });
Codicon.symbolNumeric = new Codicon('symbol-numeric', { fontCharacter: '\\ea90' });
Codicon.symbolNumber = new Codicon('symbol-number', { fontCharacter: '\\ea90' });
Codicon.symbolStructure = new Codicon('symbol-structure', { fontCharacter: '\\ea91' });
Codicon.symbolStruct = new Codicon('symbol-struct', { fontCharacter: '\\ea91' });
Codicon.symbolParameter = new Codicon('symbol-parameter', { fontCharacter: '\\ea92' });
Codicon.symbolTypeParameter = new Codicon('symbol-type-parameter', { fontCharacter: '\\ea92' });
Codicon.symbolKey = new Codicon('symbol-key', { fontCharacter: '\\ea93' });
Codicon.symbolText = new Codicon('symbol-text', { fontCharacter: '\\ea93' });
Codicon.symbolReference = new Codicon('symbol-reference', { fontCharacter: '\\ea94' });
Codicon.goToFile = new Codicon('go-to-file', { fontCharacter: '\\ea94' });
Codicon.symbolEnum = new Codicon('symbol-enum', { fontCharacter: '\\ea95' });
Codicon.symbolValue = new Codicon('symbol-value', { fontCharacter: '\\ea95' });
Codicon.symbolRuler = new Codicon('symbol-ruler', { fontCharacter: '\\ea96' });
Codicon.symbolUnit = new Codicon('symbol-unit', { fontCharacter: '\\ea96' });
Codicon.activateBreakpoints = new Codicon('activate-breakpoints', { fontCharacter: '\\ea97' });
Codicon.archive = new Codicon('archive', { fontCharacter: '\\ea98' });
Codicon.arrowBoth = new Codicon('arrow-both', { fontCharacter: '\\ea99' });
Codicon.arrowDown = new Codicon('arrow-down', { fontCharacter: '\\ea9a' });
Codicon.arrowLeft = new Codicon('arrow-left', { fontCharacter: '\\ea9b' });
Codicon.arrowRight = new Codicon('arrow-right', { fontCharacter: '\\ea9c' });
Codicon.arrowSmallDown = new Codicon('arrow-small-down', { fontCharacter: '\\ea9d' });
Codicon.arrowSmallLeft = new Codicon('arrow-small-left', { fontCharacter: '\\ea9e' });
Codicon.arrowSmallRight = new Codicon('arrow-small-right', { fontCharacter: '\\ea9f' });
Codicon.arrowSmallUp = new Codicon('arrow-small-up', { fontCharacter: '\\eaa0' });
Codicon.arrowUp = new Codicon('arrow-up', { fontCharacter: '\\eaa1' });
Codicon.bell = new Codicon('bell', { fontCharacter: '\\eaa2' });
Codicon.bold = new Codicon('bold', { fontCharacter: '\\eaa3' });
Codicon.book = new Codicon('book', { fontCharacter: '\\eaa4' });
Codicon.bookmark = new Codicon('bookmark', { fontCharacter: '\\eaa5' });
Codicon.debugBreakpointConditionalUnverified = new Codicon('debug-breakpoint-conditional-unverified', { fontCharacter: '\\eaa6' });
Codicon.debugBreakpointConditional = new Codicon('debug-breakpoint-conditional', { fontCharacter: '\\eaa7' });
Codicon.debugBreakpointConditionalDisabled = new Codicon('debug-breakpoint-conditional-disabled', { fontCharacter: '\\eaa7' });
Codicon.debugBreakpointDataUnverified = new Codicon('debug-breakpoint-data-unverified', { fontCharacter: '\\eaa8' });
Codicon.debugBreakpointData = new Codicon('debug-breakpoint-data', { fontCharacter: '\\eaa9' });
Codicon.debugBreakpointDataDisabled = new Codicon('debug-breakpoint-data-disabled', { fontCharacter: '\\eaa9' });
Codicon.debugBreakpointLogUnverified = new Codicon('debug-breakpoint-log-unverified', { fontCharacter: '\\eaaa' });
Codicon.debugBreakpointLog = new Codicon('debug-breakpoint-log', { fontCharacter: '\\eaab' });
Codicon.debugBreakpointLogDisabled = new Codicon('debug-breakpoint-log-disabled', { fontCharacter: '\\eaab' });
Codicon.briefcase = new Codicon('briefcase', { fontCharacter: '\\eaac' });
Codicon.broadcast = new Codicon('broadcast', { fontCharacter: '\\eaad' });
Codicon.browser = new Codicon('browser', { fontCharacter: '\\eaae' });
Codicon.bug = new Codicon('bug', { fontCharacter: '\\eaaf' });
Codicon.calendar = new Codicon('calendar', { fontCharacter: '\\eab0' });
Codicon.caseSensitive = new Codicon('case-sensitive', { fontCharacter: '\\eab1' });
Codicon.check = new Codicon('check', { fontCharacter: '\\eab2' });
Codicon.checklist = new Codicon('checklist', { fontCharacter: '\\eab3' });
Codicon.chevronDown = new Codicon('chevron-down', { fontCharacter: '\\eab4' });
Codicon.dropDownButton = new Codicon('drop-down-button', Codicon.chevronDown.definition);
Codicon.chevronLeft = new Codicon('chevron-left', { fontCharacter: '\\eab5' });
Codicon.chevronRight = new Codicon('chevron-right', { fontCharacter: '\\eab6' });
Codicon.chevronUp = new Codicon('chevron-up', { fontCharacter: '\\eab7' });
Codicon.chromeClose = new Codicon('chrome-close', { fontCharacter: '\\eab8' });
Codicon.chromeMaximize = new Codicon('chrome-maximize', { fontCharacter: '\\eab9' });
Codicon.chromeMinimize = new Codicon('chrome-minimize', { fontCharacter: '\\eaba' });
Codicon.chromeRestore = new Codicon('chrome-restore', { fontCharacter: '\\eabb' });
Codicon.circleOutline = new Codicon('circle-outline', { fontCharacter: '\\eabc' });
Codicon.debugBreakpointUnverified = new Codicon('debug-breakpoint-unverified', { fontCharacter: '\\eabc' });
Codicon.circleSlash = new Codicon('circle-slash', { fontCharacter: '\\eabd' });
Codicon.circuitBoard = new Codicon('circuit-board', { fontCharacter: '\\eabe' });
Codicon.clearAll = new Codicon('clear-all', { fontCharacter: '\\eabf' });
Codicon.clippy = new Codicon('clippy', { fontCharacter: '\\eac0' });
Codicon.closeAll = new Codicon('close-all', { fontCharacter: '\\eac1' });
Codicon.cloudDownload = new Codicon('cloud-download', { fontCharacter: '\\eac2' });
Codicon.cloudUpload = new Codicon('cloud-upload', { fontCharacter: '\\eac3' });
Codicon.code = new Codicon('code', { fontCharacter: '\\eac4' });
Codicon.collapseAll = new Codicon('collapse-all', { fontCharacter: '\\eac5' });
Codicon.colorMode = new Codicon('color-mode', { fontCharacter: '\\eac6' });
Codicon.commentDiscussion = new Codicon('comment-discussion', { fontCharacter: '\\eac7' });
Codicon.compareChanges = new Codicon('compare-changes', { fontCharacter: '\\eafd' });
Codicon.creditCard = new Codicon('credit-card', { fontCharacter: '\\eac9' });
Codicon.dash = new Codicon('dash', { fontCharacter: '\\eacc' });
Codicon.dashboard = new Codicon('dashboard', { fontCharacter: '\\eacd' });
Codicon.database = new Codicon('database', { fontCharacter: '\\eace' });
Codicon.debugContinue = new Codicon('debug-continue', { fontCharacter: '\\eacf' });
Codicon.debugDisconnect = new Codicon('debug-disconnect', { fontCharacter: '\\ead0' });
Codicon.debugPause = new Codicon('debug-pause', { fontCharacter: '\\ead1' });
Codicon.debugRestart = new Codicon('debug-restart', { fontCharacter: '\\ead2' });
Codicon.debugStart = new Codicon('debug-start', { fontCharacter: '\\ead3' });
Codicon.debugStepInto = new Codicon('debug-step-into', { fontCharacter: '\\ead4' });
Codicon.debugStepOut = new Codicon('debug-step-out', { fontCharacter: '\\ead5' });
Codicon.debugStepOver = new Codicon('debug-step-over', { fontCharacter: '\\ead6' });
Codicon.debugStop = new Codicon('debug-stop', { fontCharacter: '\\ead7' });
Codicon.debug = new Codicon('debug', { fontCharacter: '\\ead8' });
Codicon.deviceCameraVideo = new Codicon('device-camera-video', { fontCharacter: '\\ead9' });
Codicon.deviceCamera = new Codicon('device-camera', { fontCharacter: '\\eada' });
Codicon.deviceMobile = new Codicon('device-mobile', { fontCharacter: '\\eadb' });
Codicon.diffAdded = new Codicon('diff-added', { fontCharacter: '\\eadc' });
Codicon.diffIgnored = new Codicon('diff-ignored', { fontCharacter: '\\eadd' });
Codicon.diffModified = new Codicon('diff-modified', { fontCharacter: '\\eade' });
Codicon.diffRemoved = new Codicon('diff-removed', { fontCharacter: '\\eadf' });
Codicon.diffRenamed = new Codicon('diff-renamed', { fontCharacter: '\\eae0' });
Codicon.diff = new Codicon('diff', { fontCharacter: '\\eae1' });
Codicon.discard = new Codicon('discard', { fontCharacter: '\\eae2' });
Codicon.editorLayout = new Codicon('editor-layout', { fontCharacter: '\\eae3' });
Codicon.emptyWindow = new Codicon('empty-window', { fontCharacter: '\\eae4' });
Codicon.exclude = new Codicon('exclude', { fontCharacter: '\\eae5' });
Codicon.extensions = new Codicon('extensions', { fontCharacter: '\\eae6' });
Codicon.eyeClosed = new Codicon('eye-closed', { fontCharacter: '\\eae7' });
Codicon.fileBinary = new Codicon('file-binary', { fontCharacter: '\\eae8' });
Codicon.fileCode = new Codicon('file-code', { fontCharacter: '\\eae9' });
Codicon.fileMedia = new Codicon('file-media', { fontCharacter: '\\eaea' });
Codicon.filePdf = new Codicon('file-pdf', { fontCharacter: '\\eaeb' });
Codicon.fileSubmodule = new Codicon('file-submodule', { fontCharacter: '\\eaec' });
Codicon.fileSymlinkDirectory = new Codicon('file-symlink-directory', { fontCharacter: '\\eaed' });
Codicon.fileSymlinkFile = new Codicon('file-symlink-file', { fontCharacter: '\\eaee' });
Codicon.fileZip = new Codicon('file-zip', { fontCharacter: '\\eaef' });
Codicon.files = new Codicon('files', { fontCharacter: '\\eaf0' });
Codicon.filter = new Codicon('filter', { fontCharacter: '\\eaf1' });
Codicon.flame = new Codicon('flame', { fontCharacter: '\\eaf2' });
Codicon.foldDown = new Codicon('fold-down', { fontCharacter: '\\eaf3' });
Codicon.foldUp = new Codicon('fold-up', { fontCharacter: '\\eaf4' });
Codicon.fold = new Codicon('fold', { fontCharacter: '\\eaf5' });
Codicon.folderActive = new Codicon('folder-active', { fontCharacter: '\\eaf6' });
Codicon.folderOpened = new Codicon('folder-opened', { fontCharacter: '\\eaf7' });
Codicon.gear = new Codicon('gear', { fontCharacter: '\\eaf8' });
Codicon.gift = new Codicon('gift', { fontCharacter: '\\eaf9' });
Codicon.gistSecret = new Codicon('gist-secret', { fontCharacter: '\\eafa' });
Codicon.gist = new Codicon('gist', { fontCharacter: '\\eafb' });
Codicon.gitCommit = new Codicon('git-commit', { fontCharacter: '\\eafc' });
Codicon.gitCompare = new Codicon('git-compare', { fontCharacter: '\\eafd' });
Codicon.gitMerge = new Codicon('git-merge', { fontCharacter: '\\eafe' });
Codicon.githubAction = new Codicon('github-action', { fontCharacter: '\\eaff' });
Codicon.githubAlt = new Codicon('github-alt', { fontCharacter: '\\eb00' });
Codicon.globe = new Codicon('globe', { fontCharacter: '\\eb01' });
Codicon.grabber = new Codicon('grabber', { fontCharacter: '\\eb02' });
Codicon.graph = new Codicon('graph', { fontCharacter: '\\eb03' });
Codicon.gripper = new Codicon('gripper', { fontCharacter: '\\eb04' });
Codicon.heart = new Codicon('heart', { fontCharacter: '\\eb05' });
Codicon.home = new Codicon('home', { fontCharacter: '\\eb06' });
Codicon.horizontalRule = new Codicon('horizontal-rule', { fontCharacter: '\\eb07' });
Codicon.hubot = new Codicon('hubot', { fontCharacter: '\\eb08' });
Codicon.inbox = new Codicon('inbox', { fontCharacter: '\\eb09' });
Codicon.issueClosed = new Codicon('issue-closed', { fontCharacter: '\\eba4' });
Codicon.issueReopened = new Codicon('issue-reopened', { fontCharacter: '\\eb0b' });
Codicon.issues = new Codicon('issues', { fontCharacter: '\\eb0c' });
Codicon.italic = new Codicon('italic', { fontCharacter: '\\eb0d' });
Codicon.jersey = new Codicon('jersey', { fontCharacter: '\\eb0e' });
Codicon.json = new Codicon('json', { fontCharacter: '\\eb0f' });
Codicon.kebabVertical = new Codicon('kebab-vertical', { fontCharacter: '\\eb10' });
Codicon.key = new Codicon('key', { fontCharacter: '\\eb11' });
Codicon.law = new Codicon('law', { fontCharacter: '\\eb12' });
Codicon.lightbulbAutofix = new Codicon('lightbulb-autofix', { fontCharacter: '\\eb13' });
Codicon.linkExternal = new Codicon('link-external', { fontCharacter: '\\eb14' });
Codicon.link = new Codicon('link', { fontCharacter: '\\eb15' });
Codicon.listOrdered = new Codicon('list-ordered', { fontCharacter: '\\eb16' });
Codicon.listUnordered = new Codicon('list-unordered', { fontCharacter: '\\eb17' });
Codicon.liveShare = new Codicon('live-share', { fontCharacter: '\\eb18' });
Codicon.loading = new Codicon('loading', { fontCharacter: '\\eb19' });
Codicon.location = new Codicon('location', { fontCharacter: '\\eb1a' });
Codicon.mailRead = new Codicon('mail-read', { fontCharacter: '\\eb1b' });
Codicon.mail = new Codicon('mail', { fontCharacter: '\\eb1c' });
Codicon.markdown = new Codicon('markdown', { fontCharacter: '\\eb1d' });
Codicon.megaphone = new Codicon('megaphone', { fontCharacter: '\\eb1e' });
Codicon.mention = new Codicon('mention', { fontCharacter: '\\eb1f' });
Codicon.milestone = new Codicon('milestone', { fontCharacter: '\\eb20' });
Codicon.mortarBoard = new Codicon('mortar-board', { fontCharacter: '\\eb21' });
Codicon.move = new Codicon('move', { fontCharacter: '\\eb22' });
Codicon.multipleWindows = new Codicon('multiple-windows', { fontCharacter: '\\eb23' });
Codicon.mute = new Codicon('mute', { fontCharacter: '\\eb24' });
Codicon.noNewline = new Codicon('no-newline', { fontCharacter: '\\eb25' });
Codicon.note = new Codicon('note', { fontCharacter: '\\eb26' });
Codicon.octoface = new Codicon('octoface', { fontCharacter: '\\eb27' });
Codicon.openPreview = new Codicon('open-preview', { fontCharacter: '\\eb28' });
Codicon.package_ = new Codicon('package', { fontCharacter: '\\eb29' });
Codicon.paintcan = new Codicon('paintcan', { fontCharacter: '\\eb2a' });
Codicon.pin = new Codicon('pin', { fontCharacter: '\\eb2b' });
Codicon.play = new Codicon('play', { fontCharacter: '\\eb2c' });
Codicon.run = new Codicon('run', { fontCharacter: '\\eb2c' });
Codicon.plug = new Codicon('plug', { fontCharacter: '\\eb2d' });
Codicon.preserveCase = new Codicon('preserve-case', { fontCharacter: '\\eb2e' });
Codicon.preview = new Codicon('preview', { fontCharacter: '\\eb2f' });
Codicon.project = new Codicon('project', { fontCharacter: '\\eb30' });
Codicon.pulse = new Codicon('pulse', { fontCharacter: '\\eb31' });
Codicon.question = new Codicon('question', { fontCharacter: '\\eb32' });
Codicon.quote = new Codicon('quote', { fontCharacter: '\\eb33' });
Codicon.radioTower = new Codicon('radio-tower', { fontCharacter: '\\eb34' });
Codicon.reactions = new Codicon('reactions', { fontCharacter: '\\eb35' });
Codicon.references = new Codicon('references', { fontCharacter: '\\eb36' });
Codicon.refresh = new Codicon('refresh', { fontCharacter: '\\eb37' });
Codicon.regex = new Codicon('regex', { fontCharacter: '\\eb38' });
Codicon.remoteExplorer = new Codicon('remote-explorer', { fontCharacter: '\\eb39' });
Codicon.remote = new Codicon('remote', { fontCharacter: '\\eb3a' });
Codicon.remove = new Codicon('remove', { fontCharacter: '\\eb3b' });
Codicon.replaceAll = new Codicon('replace-all', { fontCharacter: '\\eb3c' });
Codicon.replace = new Codicon('replace', { fontCharacter: '\\eb3d' });
Codicon.repoClone = new Codicon('repo-clone', { fontCharacter: '\\eb3e' });
Codicon.repoForcePush = new Codicon('repo-force-push', { fontCharacter: '\\eb3f' });
Codicon.repoPull = new Codicon('repo-pull', { fontCharacter: '\\eb40' });
Codicon.repoPush = new Codicon('repo-push', { fontCharacter: '\\eb41' });
Codicon.report = new Codicon('report', { fontCharacter: '\\eb42' });
Codicon.requestChanges = new Codicon('request-changes', { fontCharacter: '\\eb43' });
Codicon.rocket = new Codicon('rocket', { fontCharacter: '\\eb44' });
Codicon.rootFolderOpened = new Codicon('root-folder-opened', { fontCharacter: '\\eb45' });
Codicon.rootFolder = new Codicon('root-folder', { fontCharacter: '\\eb46' });
Codicon.rss = new Codicon('rss', { fontCharacter: '\\eb47' });
Codicon.ruby = new Codicon('ruby', { fontCharacter: '\\eb48' });
Codicon.saveAll = new Codicon('save-all', { fontCharacter: '\\eb49' });
Codicon.saveAs = new Codicon('save-as', { fontCharacter: '\\eb4a' });
Codicon.save = new Codicon('save', { fontCharacter: '\\eb4b' });
Codicon.screenFull = new Codicon('screen-full', { fontCharacter: '\\eb4c' });
Codicon.screenNormal = new Codicon('screen-normal', { fontCharacter: '\\eb4d' });
Codicon.searchStop = new Codicon('search-stop', { fontCharacter: '\\eb4e' });
Codicon.server = new Codicon('server', { fontCharacter: '\\eb50' });
Codicon.settingsGear = new Codicon('settings-gear', { fontCharacter: '\\eb51' });
Codicon.settings = new Codicon('settings', { fontCharacter: '\\eb52' });
Codicon.shield = new Codicon('shield', { fontCharacter: '\\eb53' });
Codicon.smiley = new Codicon('smiley', { fontCharacter: '\\eb54' });
Codicon.sortPrecedence = new Codicon('sort-precedence', { fontCharacter: '\\eb55' });
Codicon.splitHorizontal = new Codicon('split-horizontal', { fontCharacter: '\\eb56' });
Codicon.splitVertical = new Codicon('split-vertical', { fontCharacter: '\\eb57' });
Codicon.squirrel = new Codicon('squirrel', { fontCharacter: '\\eb58' });
Codicon.starFull = new Codicon('star-full', { fontCharacter: '\\eb59' });
Codicon.starHalf = new Codicon('star-half', { fontCharacter: '\\eb5a' });
Codicon.symbolClass = new Codicon('symbol-class', { fontCharacter: '\\eb5b' });
Codicon.symbolColor = new Codicon('symbol-color', { fontCharacter: '\\eb5c' });
Codicon.symbolCustomColor = new Codicon('symbol-customcolor', { fontCharacter: '\\eb5c' });
Codicon.symbolConstant = new Codicon('symbol-constant', { fontCharacter: '\\eb5d' });
Codicon.symbolEnumMember = new Codicon('symbol-enum-member', { fontCharacter: '\\eb5e' });
Codicon.symbolField = new Codicon('symbol-field', { fontCharacter: '\\eb5f' });
Codicon.symbolFile = new Codicon('symbol-file', { fontCharacter: '\\eb60' });
Codicon.symbolInterface = new Codicon('symbol-interface', { fontCharacter: '\\eb61' });
Codicon.symbolKeyword = new Codicon('symbol-keyword', { fontCharacter: '\\eb62' });
Codicon.symbolMisc = new Codicon('symbol-misc', { fontCharacter: '\\eb63' });
Codicon.symbolOperator = new Codicon('symbol-operator', { fontCharacter: '\\eb64' });
Codicon.symbolProperty = new Codicon('symbol-property', { fontCharacter: '\\eb65' });
Codicon.wrench = new Codicon('wrench', { fontCharacter: '\\eb65' });
Codicon.wrenchSubaction = new Codicon('wrench-subaction', { fontCharacter: '\\eb65' });
Codicon.symbolSnippet = new Codicon('symbol-snippet', { fontCharacter: '\\eb66' });
Codicon.tasklist = new Codicon('tasklist', { fontCharacter: '\\eb67' });
Codicon.telescope = new Codicon('telescope', { fontCharacter: '\\eb68' });
Codicon.textSize = new Codicon('text-size', { fontCharacter: '\\eb69' });
Codicon.threeBars = new Codicon('three-bars', { fontCharacter: '\\eb6a' });
Codicon.thumbsdown = new Codicon('thumbsdown', { fontCharacter: '\\eb6b' });
Codicon.thumbsup = new Codicon('thumbsup', { fontCharacter: '\\eb6c' });
Codicon.tools = new Codicon('tools', { fontCharacter: '\\eb6d' });
Codicon.triangleDown = new Codicon('triangle-down', { fontCharacter: '\\eb6e' });
Codicon.triangleLeft = new Codicon('triangle-left', { fontCharacter: '\\eb6f' });
Codicon.triangleRight = new Codicon('triangle-right', { fontCharacter: '\\eb70' });
Codicon.triangleUp = new Codicon('triangle-up', { fontCharacter: '\\eb71' });
Codicon.twitter = new Codicon('twitter', { fontCharacter: '\\eb72' });
Codicon.unfold = new Codicon('unfold', { fontCharacter: '\\eb73' });
Codicon.unlock = new Codicon('unlock', { fontCharacter: '\\eb74' });
Codicon.unmute = new Codicon('unmute', { fontCharacter: '\\eb75' });
Codicon.unverified = new Codicon('unverified', { fontCharacter: '\\eb76' });
Codicon.verified = new Codicon('verified', { fontCharacter: '\\eb77' });
Codicon.versions = new Codicon('versions', { fontCharacter: '\\eb78' });
Codicon.vmActive = new Codicon('vm-active', { fontCharacter: '\\eb79' });
Codicon.vmOutline = new Codicon('vm-outline', { fontCharacter: '\\eb7a' });
Codicon.vmRunning = new Codicon('vm-running', { fontCharacter: '\\eb7b' });
Codicon.watch = new Codicon('watch', { fontCharacter: '\\eb7c' });
Codicon.whitespace = new Codicon('whitespace', { fontCharacter: '\\eb7d' });
Codicon.wholeWord = new Codicon('whole-word', { fontCharacter: '\\eb7e' });
Codicon.window = new Codicon('window', { fontCharacter: '\\eb7f' });
Codicon.wordWrap = new Codicon('word-wrap', { fontCharacter: '\\eb80' });
Codicon.zoomIn = new Codicon('zoom-in', { fontCharacter: '\\eb81' });
Codicon.zoomOut = new Codicon('zoom-out', { fontCharacter: '\\eb82' });
Codicon.listFilter = new Codicon('list-filter', { fontCharacter: '\\eb83' });
Codicon.listFlat = new Codicon('list-flat', { fontCharacter: '\\eb84' });
Codicon.listSelection = new Codicon('list-selection', { fontCharacter: '\\eb85' });
Codicon.selection = new Codicon('selection', { fontCharacter: '\\eb85' });
Codicon.listTree = new Codicon('list-tree', { fontCharacter: '\\eb86' });
Codicon.debugBreakpointFunctionUnverified = new Codicon('debug-breakpoint-function-unverified', { fontCharacter: '\\eb87' });
Codicon.debugBreakpointFunction = new Codicon('debug-breakpoint-function', { fontCharacter: '\\eb88' });
Codicon.debugBreakpointFunctionDisabled = new Codicon('debug-breakpoint-function-disabled', { fontCharacter: '\\eb88' });
Codicon.debugStackframeActive = new Codicon('debug-stackframe-active', { fontCharacter: '\\eb89' });
Codicon.circleSmallFilled = new Codicon('circle-small-filled', { fontCharacter: '\\eb8a' });
Codicon.debugStackframeDot = new Codicon('debug-stackframe-dot', Codicon.circleSmallFilled.definition);
Codicon.debugStackframe = new Codicon('debug-stackframe', { fontCharacter: '\\eb8b' });
Codicon.debugStackframeFocused = new Codicon('debug-stackframe-focused', { fontCharacter: '\\eb8b' });
Codicon.debugBreakpointUnsupported = new Codicon('debug-breakpoint-unsupported', { fontCharacter: '\\eb8c' });
Codicon.symbolString = new Codicon('symbol-string', { fontCharacter: '\\eb8d' });
Codicon.debugReverseContinue = new Codicon('debug-reverse-continue', { fontCharacter: '\\eb8e' });
Codicon.debugStepBack = new Codicon('debug-step-back', { fontCharacter: '\\eb8f' });
Codicon.debugRestartFrame = new Codicon('debug-restart-frame', { fontCharacter: '\\eb90' });
Codicon.callIncoming = new Codicon('call-incoming', { fontCharacter: '\\eb92' });
Codicon.callOutgoing = new Codicon('call-outgoing', { fontCharacter: '\\eb93' });
Codicon.menu = new Codicon('menu', { fontCharacter: '\\eb94' });
Codicon.expandAll = new Codicon('expand-all', { fontCharacter: '\\eb95' });
Codicon.feedback = new Codicon('feedback', { fontCharacter: '\\eb96' });
Codicon.groupByRefType = new Codicon('group-by-ref-type', { fontCharacter: '\\eb97' });
Codicon.ungroupByRefType = new Codicon('ungroup-by-ref-type', { fontCharacter: '\\eb98' });
Codicon.account = new Codicon('account', { fontCharacter: '\\eb99' });
Codicon.bellDot = new Codicon('bell-dot', { fontCharacter: '\\eb9a' });
Codicon.debugConsole = new Codicon('debug-console', { fontCharacter: '\\eb9b' });
Codicon.library = new Codicon('library', { fontCharacter: '\\eb9c' });
Codicon.output = new Codicon('output', { fontCharacter: '\\eb9d' });
Codicon.runAll = new Codicon('run-all', { fontCharacter: '\\eb9e' });
Codicon.syncIgnored = new Codicon('sync-ignored', { fontCharacter: '\\eb9f' });
Codicon.pinned = new Codicon('pinned', { fontCharacter: '\\eba0' });
Codicon.githubInverted = new Codicon('github-inverted', { fontCharacter: '\\eba1' });
Codicon.debugAlt = new Codicon('debug-alt', { fontCharacter: '\\eb91' });
Codicon.serverProcess = new Codicon('server-process', { fontCharacter: '\\eba2' });
Codicon.serverEnvironment = new Codicon('server-environment', { fontCharacter: '\\eba3' });
Codicon.pass = new Codicon('pass', { fontCharacter: '\\eba4' });
Codicon.stopCircle = new Codicon('stop-circle', { fontCharacter: '\\eba5' });
Codicon.playCircle = new Codicon('play-circle', { fontCharacter: '\\eba6' });
Codicon.record = new Codicon('record', { fontCharacter: '\\eba7' });
Codicon.debugAltSmall = new Codicon('debug-alt-small', { fontCharacter: '\\eba8' });
Codicon.vmConnect = new Codicon('vm-connect', { fontCharacter: '\\eba9' });
Codicon.cloud = new Codicon('cloud', { fontCharacter: '\\ebaa' });
Codicon.merge = new Codicon('merge', { fontCharacter: '\\ebab' });
Codicon.exportIcon = new Codicon('export', { fontCharacter: '\\ebac' });
Codicon.graphLeft = new Codicon('graph-left', { fontCharacter: '\\ebad' });
Codicon.magnet = new Codicon('magnet', { fontCharacter: '\\ebae' });
Codicon.notebook = new Codicon('notebook', { fontCharacter: '\\ebaf' });
Codicon.redo = new Codicon('redo', { fontCharacter: '\\ebb0' });
Codicon.checkAll = new Codicon('check-all', { fontCharacter: '\\ebb1' });
Codicon.pinnedDirty = new Codicon('pinned-dirty', { fontCharacter: '\\ebb2' });
Codicon.passFilled = new Codicon('pass-filled', { fontCharacter: '\\ebb3' });
Codicon.circleLargeFilled = new Codicon('circle-large-filled', { fontCharacter: '\\ebb4' });
Codicon.circleLargeOutline = new Codicon('circle-large-outline', { fontCharacter: '\\ebb5' });
Codicon.combine = new Codicon('combine', { fontCharacter: '\\ebb6' });
Codicon.gather = new Codicon('gather', { fontCharacter: '\\ebb6' });
Codicon.table = new Codicon('table', { fontCharacter: '\\ebb7' });
Codicon.variableGroup = new Codicon('variable-group', { fontCharacter: '\\ebb8' });
Codicon.typeHierarchy = new Codicon('type-hierarchy', { fontCharacter: '\\ebb9' });
Codicon.typeHierarchySub = new Codicon('type-hierarchy-sub', { fontCharacter: '\\ebba' });
Codicon.typeHierarchySuper = new Codicon('type-hierarchy-super', { fontCharacter: '\\ebbb' });
Codicon.gitPullRequestCreate = new Codicon('git-pull-request-create', { fontCharacter: '\\ebbc' });
Codicon.runAbove = new Codicon('run-above', { fontCharacter: '\\ebbd' });
Codicon.runBelow = new Codicon('run-below', { fontCharacter: '\\ebbe' });
Codicon.notebookTemplate = new Codicon('notebook-template', { fontCharacter: '\\ebbf' });
Codicon.debugRerun = new Codicon('debug-rerun', { fontCharacter: '\\ebc0' });
Codicon.workspaceTrusted = new Codicon('workspace-trusted', { fontCharacter: '\\ebc1' });
Codicon.workspaceUntrusted = new Codicon('workspace-untrusted', { fontCharacter: '\\ebc2' });
Codicon.workspaceUnspecified = new Codicon('workspace-unspecified', { fontCharacter: '\\ebc3' });
Codicon.terminalCmd = new Codicon('terminal-cmd', { fontCharacter: '\\ebc4' });
Codicon.terminalDebian = new Codicon('terminal-debian', { fontCharacter: '\\ebc5' });
Codicon.terminalLinux = new Codicon('terminal-linux', { fontCharacter: '\\ebc6' });
Codicon.terminalPowershell = new Codicon('terminal-powershell', { fontCharacter: '\\ebc7' });
Codicon.terminalTmux = new Codicon('terminal-tmux', { fontCharacter: '\\ebc8' });
Codicon.terminalUbuntu = new Codicon('terminal-ubuntu', { fontCharacter: '\\ebc9' });
Codicon.terminalBash = new Codicon('terminal-bash', { fontCharacter: '\\ebca' });
Codicon.arrowSwap = new Codicon('arrow-swap', { fontCharacter: '\\ebcb' });
Codicon.copy = new Codicon('copy', { fontCharacter: '\\ebcc' });
Codicon.personAdd = new Codicon('person-add', { fontCharacter: '\\ebcd' });
Codicon.filterFilled = new Codicon('filter-filled', { fontCharacter: '\\ebce' });
Codicon.wand = new Codicon('wand', { fontCharacter: '\\ebcf' });
Codicon.debugLineByLine = new Codicon('debug-line-by-line', { fontCharacter: '\\ebd0' });
Codicon.inspect = new Codicon('inspect', { fontCharacter: '\\ebd1' });
Codicon.layers = new Codicon('layers', { fontCharacter: '\\ebd2' });
Codicon.layersDot = new Codicon('layers-dot', { fontCharacter: '\\ebd3' });
Codicon.layersActive = new Codicon('layers-active', { fontCharacter: '\\ebd4' });
Codicon.compass = new Codicon('compass', { fontCharacter: '\\ebd5' });
Codicon.compassDot = new Codicon('compass-dot', { fontCharacter: '\\ebd6' });
Codicon.compassActive = new Codicon('compass-active', { fontCharacter: '\\ebd7' });
Codicon.azure = new Codicon('azure', { fontCharacter: '\\ebd8' });
Codicon.issueDraft = new Codicon('issue-draft', { fontCharacter: '\\ebd9' });
Codicon.gitPullRequestClosed = new Codicon('git-pull-request-closed', { fontCharacter: '\\ebda' });
Codicon.gitPullRequestDraft = new Codicon('git-pull-request-draft', { fontCharacter: '\\ebdb' });
Codicon.debugAll = new Codicon('debug-all', { fontCharacter: '\\ebdc' });
Codicon.debugCoverage = new Codicon('debug-coverage', { fontCharacter: '\\ebdd' });
Codicon.runErrors = new Codicon('run-errors', { fontCharacter: '\\ebde' });
Codicon.folderLibrary = new Codicon('folder-library', { fontCharacter: '\\ebdf' });
Codicon.debugContinueSmall = new Codicon('debug-continue-small', { fontCharacter: '\\ebe0' });
Codicon.beakerStop = new Codicon('beaker-stop', { fontCharacter: '\\ebe1' });
Codicon.graphLine = new Codicon('graph-line', { fontCharacter: '\\ebe2' });
Codicon.graphScatter = new Codicon('graph-scatter', { fontCharacter: '\\ebe3' });
Codicon.pieChart = new Codicon('pie-chart', { fontCharacter: '\\ebe4' });
Codicon.bracket = new Codicon('bracket', Codicon.json.definition);
Codicon.bracketDot = new Codicon('bracket-dot', { fontCharacter: '\\ebe5' });
Codicon.bracketError = new Codicon('bracket-error', { fontCharacter: '\\ebe6' });
Codicon.lockSmall = new Codicon('lock-small', { fontCharacter: '\\ebe7' });
Codicon.azureDevops = new Codicon('azure-devops', { fontCharacter: '\\ebe8' });
Codicon.verifiedFilled = new Codicon('verified-filled', { fontCharacter: '\\ebe9' });
Codicon.newLine = new Codicon('newline', { fontCharacter: '\\ebea' });
Codicon.layout = new Codicon('layout', { fontCharacter: '\\ebeb' });
Codicon.layoutActivitybarLeft = new Codicon('layout-activitybar-left', { fontCharacter: '\\ebec' });
Codicon.layoutActivitybarRight = new Codicon('layout-activitybar-right', { fontCharacter: '\\ebed' });
Codicon.layoutPanelLeft = new Codicon('layout-panel-left', { fontCharacter: '\\ebee' });
Codicon.layoutPanelCenter = new Codicon('layout-panel-center', { fontCharacter: '\\ebef' });
Codicon.layoutPanelJustify = new Codicon('layout-panel-justify', { fontCharacter: '\\ebf0' });
Codicon.layoutPanelRight = new Codicon('layout-panel-right', { fontCharacter: '\\ebf1' });
Codicon.layoutPanel = new Codicon('layout-panel', { fontCharacter: '\\ebf2' });
Codicon.layoutSidebarLeft = new Codicon('layout-sidebar-left', { fontCharacter: '\\ebf3' });
Codicon.layoutSidebarRight = new Codicon('layout-sidebar-right', { fontCharacter: '\\ebf4' });
Codicon.layoutStatusbar = new Codicon('layout-statusbar', { fontCharacter: '\\ebf5' });
Codicon.layoutMenubar = new Codicon('layout-menubar', { fontCharacter: '\\ebf6' });
Codicon.layoutCentered = new Codicon('layout-centered', { fontCharacter: '\\ebf7' });
Codicon.layoutSidebarRightOff = new Codicon('layout-sidebar-right-off', { fontCharacter: '\\ec00' });
Codicon.layoutPanelOff = new Codicon('layout-panel-off', { fontCharacter: '\\ec01' });
Codicon.layoutSidebarLeftOff = new Codicon('layout-sidebar-left-off', { fontCharacter: '\\ec02' });
Codicon.target = new Codicon('target', { fontCharacter: '\\ebf8' });
Codicon.indent = new Codicon('indent', { fontCharacter: '\\ebf9' });
Codicon.recordSmall = new Codicon('record-small', { fontCharacter: '\\ebfa' });
Codicon.errorSmall = new Codicon('error-small', { fontCharacter: '\\ebfb' });
Codicon.arrowCircleDown = new Codicon('arrow-circle-down', { fontCharacter: '\\ebfc' });
Codicon.arrowCircleLeft = new Codicon('arrow-circle-left', { fontCharacter: '\\ebfd' });
Codicon.arrowCircleRight = new Codicon('arrow-circle-right', { fontCharacter: '\\ebfe' });
Codicon.arrowCircleUp = new Codicon('arrow-circle-up', { fontCharacter: '\\ebff' });
Codicon.heartFilled = new Codicon('heart-filled', { fontCharacter: '\\ec04' });
Codicon.map = new Codicon('map', { fontCharacter: '\\ec05' });
Codicon.mapFilled = new Codicon('map-filled', { fontCharacter: '\\ec06' });
Codicon.circleSmall = new Codicon('circle-small', { fontCharacter: '\\ec07' });
Codicon.bellSlash = new Codicon('bell-slash', { fontCharacter: '\\ec08' });
Codicon.bellSlashDot = new Codicon('bell-slash-dot', { fontCharacter: '\\ec09' });
Codicon.commentUnresolved = new Codicon('comment-unresolved', { fontCharacter: '\\ec0a' });
Codicon.gitPullRequestGoToChanges = new Codicon('git-pull-request-go-to-changes', { fontCharacter: '\\ec0b' });
Codicon.gitPullRequestNewChanges = new Codicon('git-pull-request-new-changes', { fontCharacter: '\\ec0c' });
// derived icons, that could become separate icons
Codicon.dialogError = new Codicon('dialog-error', Codicon.error.definition);
Codicon.dialogWarning = new Codicon('dialog-warning', Codicon.warning.definition);
Codicon.dialogInfo = new Codicon('dialog-info', Codicon.info.definition);
Codicon.dialogClose = new Codicon('dialog-close', Codicon.close.definition);
Codicon.treeItemExpanded = new Codicon('tree-item-expanded', Codicon.chevronDown.definition); // collapsed is done with rotation
Codicon.treeFilterOnTypeOn = new Codicon('tree-filter-on-type-on', Codicon.listFilter.definition);
Codicon.treeFilterOnTypeOff = new Codicon('tree-filter-on-type-off', Codicon.listSelection.definition);
Codicon.treeFilterClear = new Codicon('tree-filter-clear', Codicon.close.definition);
Codicon.treeItemLoading = new Codicon('tree-item-loading', Codicon.loading.definition);
Codicon.menuSelection = new Codicon('menu-selection', Codicon.check.definition);
Codicon.menuSubmenu = new Codicon('menu-submenu', Codicon.chevronRight.definition);
Codicon.menuBarMore = new Codicon('menubar-more', Codicon.more.definition);
Codicon.scrollbarButtonLeft = new Codicon('scrollbar-button-left', Codicon.triangleLeft.definition);
Codicon.scrollbarButtonRight = new Codicon('scrollbar-button-right', Codicon.triangleRight.definition);
Codicon.scrollbarButtonUp = new Codicon('scrollbar-button-up', Codicon.triangleUp.definition);
Codicon.scrollbarButtonDown = new Codicon('scrollbar-button-down', Codicon.triangleDown.definition);
Codicon.toolBarMore = new Codicon('toolbar-more', Codicon.more.definition);
Codicon.quickInputBack = new Codicon('quick-input-back', Codicon.arrowLeft.definition);
var CSSIcon;
(function (CSSIcon) {
    CSSIcon.iconNameSegment = '[A-Za-z0-9]+';
    CSSIcon.iconNameExpression = '[A-Za-z0-9-]+';
    CSSIcon.iconModifierExpression = '~[A-Za-z]+';
    CSSIcon.iconNameCharacter = '[A-Za-z0-9~-]';
    const cssIconIdRegex = new RegExp(`^(${CSSIcon.iconNameExpression})(${CSSIcon.iconModifierExpression})?$`);
    function asClassNameArray(icon) {
        if (icon instanceof Codicon) {
            return ['codicon', 'codicon-' + icon.id];
        }
        const match = cssIconIdRegex.exec(icon.id);
        if (!match) {
            return asClassNameArray(Codicon.error);
        }
        const [, id, modifier] = match;
        const classNames = ['codicon', 'codicon-' + id];
        if (modifier) {
            classNames.push('codicon-modifier-' + modifier.substr(1));
        }
        return classNames;
    }
    CSSIcon.asClassNameArray = asClassNameArray;
    function asClassName(icon) {
        return asClassNameArray(icon).join(' ');
    }
    CSSIcon.asClassName = asClassName;
    function asCSSSelector(icon) {
        return '.' + asClassNameArray(icon).join('.');
    }
    CSSIcon.asCSSSelector = asCSSSelector;
})(CSSIcon || (CSSIcon = {}));

;// ../../node_modules/monaco-editor/esm/vs/base/common/types.js
/**
 * @returns whether the provided parameter is a JavaScript Array or not.
 */
function isArray(array) {
    return Array.isArray(array);
}
/**
 * @returns whether the provided parameter is a JavaScript String or not.
 */
function isString(str) {
    return (typeof str === 'string');
}
/**
 *
 * @returns whether the provided parameter is of type `object` but **not**
 *	`null`, an `array`, a `regexp`, nor a `date`.
 */
function isObject(obj) {
    // The method can't do a type cast since there are type (like strings) which
    // are subclasses of any put not positvely matched by the function. Hence type
    // narrowing results in wrong results.
    return typeof obj === 'object'
        && obj !== null
        && !Array.isArray(obj)
        && !(obj instanceof RegExp)
        && !(obj instanceof Date);
}
/**
 *
 * @returns whether the provided parameter is of type `Buffer` or Uint8Array dervived type
 */
function isTypedArray(obj) {
    const TypedArray = Object.getPrototypeOf(Uint8Array);
    return typeof obj === 'object'
        && obj instanceof TypedArray;
}
/**
 * In **contrast** to just checking `typeof` this will return `false` for `NaN`.
 * @returns whether the provided parameter is a JavaScript Number or not.
 */
function isNumber(obj) {
    return (typeof obj === 'number' && !isNaN(obj));
}
/**
 * @returns whether the provided parameter is an Iterable, casting to the given generic
 */
function isIterable(obj) {
    return !!obj && typeof obj[Symbol.iterator] === 'function';
}
/**
 * @returns whether the provided parameter is a JavaScript Boolean or not.
 */
function isBoolean(obj) {
    return (obj === true || obj === false);
}
/**
 * @returns whether the provided parameter is undefined.
 */
function isUndefined(obj) {
    return (typeof obj === 'undefined');
}
/**
 * @returns whether the provided parameter is defined.
 */
function isDefined(arg) {
    return !isUndefinedOrNull(arg);
}
/**
 * @returns whether the provided parameter is undefined or null.
 */
function isUndefinedOrNull(obj) {
    return (isUndefined(obj) || obj === null);
}
function assertType(condition, type) {
    if (!condition) {
        throw new Error(type ? `Unexpected type, expected '${type}'` : 'Unexpected type');
    }
}
/**
 * Asserts that the argument passed in is neither undefined nor null.
 */
function assertIsDefined(arg) {
    if (isUndefinedOrNull(arg)) {
        throw new Error('Assertion Failed: argument is undefined or null');
    }
    return arg;
}
/**
 * @returns whether the provided parameter is a JavaScript Function or not.
 */
function isFunction(obj) {
    return (typeof obj === 'function');
}
function validateConstraints(args, constraints) {
    const len = Math.min(args.length, constraints.length);
    for (let i = 0; i < len; i++) {
        validateConstraint(args[i], constraints[i]);
    }
}
function validateConstraint(arg, constraint) {
    if (isString(constraint)) {
        if (typeof arg !== constraint) {
            throw new Error(`argument does not match constraint: typeof ${constraint}`);
        }
    }
    else if (isFunction(constraint)) {
        try {
            if (arg instanceof constraint) {
                return;
            }
        }
        catch (_a) {
            // ignore
        }
        if (!isUndefinedOrNull(arg) && arg.constructor === constraint) {
            return;
        }
        if (constraint.length === 1 && constraint.call(undefined, 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 getAllPropertyNames(obj) {
    let res = [];
    let proto = Object.getPrototypeOf(obj);
    while (Object.prototype !== proto) {
        res = res.concat(Object.getOwnPropertyNames(proto));
        proto = Object.getPrototypeOf(proto);
    }
    return res;
}
function getAllMethodNames(obj) {
    const methods = [];
    for (const prop of getAllPropertyNames(obj)) {
        if (typeof obj[prop] === 'function') {
            methods.push(prop);
        }
    }
    return methods;
}
function createProxyObject(methodNames, invoke) {
    const createProxyMethod = (method) => {
        return function () {
            const args = Array.prototype.slice.call(arguments, 0);
            return invoke(method, args);
        };
    };
    const result = {};
    for (const methodName of methodNames) {
        result[methodName] = createProxyMethod(methodName);
    }
    return result;
}
/**
 * Converts null to undefined, passes all other values through.
 */
function withNullAsUndefined(x) {
    return x === null ? undefined : x;
}
function assertNever(value, message = 'Unreachable') {
    throw new Error(message);
}

;// ../../node_modules/monaco-editor/esm/vs/platform/commands/common/commands.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






const ICommandService = createDecorator('commandService');
const CommandsRegistry = new class {
    constructor() {
        this._commands = new Map();
        this._onDidRegisterCommand = new Emitter();
        this.onDidRegisterCommand = this._onDidRegisterCommand.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 });
        }
        // add argument validation if rich command metadata is provided
        if (idOrCommand.description) {
            const constraints = [];
            for (const arg of idOrCommand.description.args) {
                constraints.push(arg.constraint);
            }
            const actualHandler = idOrCommand.handler;
            idOrCommand.handler = function (accessor, ...args) {
                validateConstraints(args, constraints);
                return actualHandler(accessor, ...args);
            };
        }
        // find a place to store the command
        const { id } = idOrCommand;
        let commands = this._commands.get(id);
        if (!commands) {
            commands = new LinkedList();
            this._commands.set(id, commands);
        }
        const removeFn = commands.unshift(idOrCommand);
        const ret = toDisposable(() => {
            removeFn();
            const command = this._commands.get(id);
            if (command === null || command === void 0 ? void 0 : command.isEmpty()) {
                this._commands.delete(id);
            }
        });
        // tell the world about this command
        this._onDidRegisterCommand.fire(id);
        return ret;
    }
    registerCommandAlias(oldId, newId) {
        return CommandsRegistry.registerCommand(oldId, (accessor, ...args) => accessor.get(ICommandService).executeCommand(newId, ...args));
    }
    getCommand(id) {
        const list = this._commands.get(id);
        if (!list || list.isEmpty()) {
            return undefined;
        }
        return Iterable.first(list);
    }
    getCommands() {
        const result = new Map();
        for (const key of this._commands.keys()) {
            const command = this.getCommand(key);
            if (command) {
                result.set(key, command);
            }
        }
        return result;
    }
};
const NullCommandService = {
    _serviceBrand: undefined,
    onWillExecuteCommand: () => Disposable.None,
    onDidExecuteCommand: () => Disposable.None,
    executeCommand() {
        return Promise.resolve(undefined);
    }
};
CommandsRegistry.registerCommand('noop', () => { });

;// ../../node_modules/monaco-editor/esm/vs/platform/contextkey/common/contextkey.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



const CONSTANT_VALUES = new Map();
CONSTANT_VALUES.set('false', false);
CONSTANT_VALUES.set('true', true);
CONSTANT_VALUES.set('isMac', isMacintosh);
CONSTANT_VALUES.set('isLinux', isLinux);
CONSTANT_VALUES.set('isWindows', isWindows);
CONSTANT_VALUES.set('isWeb', isWeb);
CONSTANT_VALUES.set('isMacNative', isMacintosh && !isWeb);
CONSTANT_VALUES.set('isEdge', isEdge);
CONSTANT_VALUES.set('isFirefox', isFirefox);
CONSTANT_VALUES.set('isChrome', isChrome);
CONSTANT_VALUES.set('isSafari', isSafari);
const contextkey_hasOwnProperty = Object.prototype.hasOwnProperty;
class ContextKeyExpr {
    static has(key) {
        return ContextKeyDefinedExpr.create(key);
    }
    static equals(key, value) {
        return ContextKeyEqualsExpr.create(key, value);
    }
    static regex(key, value) {
        return ContextKeyRegexExpr.create(key, value);
    }
    static not(key) {
        return ContextKeyNotExpr.create(key);
    }
    static and(...expr) {
        return ContextKeyAndExpr.create(expr, null);
    }
    static or(...expr) {
        return ContextKeyOrExpr.create(expr, null, true);
    }
    static deserialize(serialized, strict = false) {
        if (!serialized) {
            return undefined;
        }
        return this._deserializeOrExpression(serialized, strict);
    }
    static _deserializeOrExpression(serialized, strict) {
        const pieces = serialized.split('||');
        return ContextKeyOrExpr.create(pieces.map(p => this._deserializeAndExpression(p, strict)), null, true);
    }
    static _deserializeAndExpression(serialized, strict) {
        const pieces = serialized.split('&&');
        return ContextKeyAndExpr.create(pieces.map(p => this._deserializeOne(p, strict)), null);
    }
    static _deserializeOne(serializedOne, strict) {
        serializedOne = serializedOne.trim();
        if (serializedOne.indexOf('!=') >= 0) {
            const pieces = serializedOne.split('!=');
            return ContextKeyNotEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict));
        }
        if (serializedOne.indexOf('==') >= 0) {
            const pieces = serializedOne.split('==');
            return ContextKeyEqualsExpr.create(pieces[0].trim(), this._deserializeValue(pieces[1], strict));
        }
        if (serializedOne.indexOf('=~') >= 0) {
            const pieces = serializedOne.split('=~');
            return ContextKeyRegexExpr.create(pieces[0].trim(), this._deserializeRegexValue(pieces[1], strict));
        }
        if (serializedOne.indexOf(' not in ') >= 0) {
            const pieces = serializedOne.split(' not in ');
            return ContextKeyNotInExpr.create(pieces[0].trim(), pieces[1].trim());
        }
        if (serializedOne.indexOf(' in ') >= 0) {
            const pieces = serializedOne.split(' in ');
            return ContextKeyInExpr.create(pieces[0].trim(), pieces[1].trim());
        }
        if (/^[^<=>]+>=[^<=>]+$/.test(serializedOne)) {
            const pieces = serializedOne.split('>=');
            return ContextKeyGreaterEqualsExpr.create(pieces[0].trim(), pieces[1].trim());
        }
        if (/^[^<=>]+>[^<=>]+$/.test(serializedOne)) {
            const pieces = serializedOne.split('>');
            return ContextKeyGreaterExpr.create(pieces[0].trim(), pieces[1].trim());
        }
        if (/^[^<=>]+<=[^<=>]+$/.test(serializedOne)) {
            const pieces = serializedOne.split('<=');
            return ContextKeySmallerEqualsExpr.create(pieces[0].trim(), pieces[1].trim());
        }
        if (/^[^<=>]+<[^<=>]+$/.test(serializedOne)) {
            const pieces = serializedOne.split('<');
            return ContextKeySmallerExpr.create(pieces[0].trim(), pieces[1].trim());
        }
        if (/^\!\s*/.test(serializedOne)) {
            return ContextKeyNotExpr.create(serializedOne.substr(1).trim());
        }
        return ContextKeyDefinedExpr.create(serializedOne);
    }
    static _deserializeValue(serializedValue, strict) {
        serializedValue = serializedValue.trim();
        if (serializedValue === 'true') {
            return true;
        }
        if (serializedValue === 'false') {
            return false;
        }
        const m = /^'([^']*)'$/.exec(serializedValue);
        if (m) {
            return m[1].trim();
        }
        return serializedValue;
    }
    static _deserializeRegexValue(serializedValue, strict) {
        if (isFalsyOrWhitespace(serializedValue)) {
            if (strict) {
                throw new Error('missing regexp-value for =~-expression');
            }
            else {
                console.warn('missing regexp-value for =~-expression');
            }
            return null;
        }
        const start = serializedValue.indexOf('/');
        const end = serializedValue.lastIndexOf('/');
        if (start === end || start < 0 /* || to < 0 */) {
            if (strict) {
                throw new Error(`bad regexp-value '${serializedValue}', missing /-enclosure`);
            }
            else {
                console.warn(`bad regexp-value '${serializedValue}', missing /-enclosure`);
            }
            return null;
        }
        const value = serializedValue.slice(start + 1, end);
        const caseIgnoreFlag = serializedValue[end + 1] === 'i' ? 'i' : '';
        try {
            return new RegExp(value, caseIgnoreFlag);
        }
        catch (e) {
            if (strict) {
                throw new Error(`bad regexp-value '${serializedValue}', parse error: ${e}`);
            }
            else {
                console.warn(`bad regexp-value '${serializedValue}', parse error: ${e}`);
            }
            return null;
        }
    }
}
function expressionsAreEqualWithConstantSubstitution(a, b) {
    const aExpr = a ? a.substituteConstants() : undefined;
    const bExpr = b ? b.substituteConstants() : undefined;
    if (!aExpr && !bExpr) {
        return true;
    }
    if (!aExpr || !bExpr) {
        return false;
    }
    return aExpr.equals(bExpr);
}
function cmp(a, b) {
    return a.cmp(b);
}
class ContextKeyFalseExpr {
    constructor() {
        this.type = 0 /* ContextKeyExprType.False */;
    }
    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 [];
    }
    negate() {
        return ContextKeyTrueExpr.INSTANCE;
    }
}
ContextKeyFalseExpr.INSTANCE = new ContextKeyFalseExpr();
class ContextKeyTrueExpr {
    constructor() {
        this.type = 1 /* ContextKeyExprType.True */;
    }
    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 [];
    }
    negate() {
        return ContextKeyFalseExpr.INSTANCE;
    }
}
ContextKeyTrueExpr.INSTANCE = new ContextKeyTrueExpr();
class ContextKeyDefinedExpr {
    constructor(key, negated) {
        this.key = key;
        this.negated = negated;
        this.type = 2 /* ContextKeyExprType.Defined */;
    }
    static create(key, negated = null) {
        const constantValue = CONSTANT_VALUES.get(key);
        if (typeof constantValue === 'boolean') {
            return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
        }
        return new ContextKeyDefinedExpr(key, negated);
    }
    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 ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
        }
        return this;
    }
    evaluate(context) {
        return (!!context.getValue(this.key));
    }
    serialize() {
        return this.key;
    }
    keys() {
        return [this.key];
    }
    negate() {
        if (!this.negated) {
            this.negated = ContextKeyNotExpr.create(this.key, this);
        }
        return this.negated;
    }
}
class ContextKeyEqualsExpr {
    constructor(key, value, negated) {
        this.key = key;
        this.value = value;
        this.negated = negated;
        this.type = 4 /* ContextKeyExprType.Equals */;
    }
    static create(key, value, negated = null) {
        if (typeof value === 'boolean') {
            return (value ? ContextKeyDefinedExpr.create(key, negated) : ContextKeyNotExpr.create(key, negated));
        }
        const constantValue = CONSTANT_VALUES.get(key);
        if (typeof constantValue === 'boolean') {
            const trueValue = constantValue ? 'true' : 'false';
            return (value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE);
        }
        return new ContextKeyEqualsExpr(key, value, negated);
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        return cmp2(this.key, this.value, other.key, other.value);
    }
    equals(other) {
        if (other.type === this.type) {
            return (this.key === other.key && this.value === other.value);
        }
        return false;
    }
    substituteConstants() {
        const constantValue = CONSTANT_VALUES.get(this.key);
        if (typeof constantValue === 'boolean') {
            const trueValue = constantValue ? 'true' : 'false';
            return (this.value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE);
        }
        return this;
    }
    evaluate(context) {
        // Intentional ==
        // eslint-disable-next-line eqeqeq
        return (context.getValue(this.key) == this.value);
    }
    serialize() {
        return `${this.key} == '${this.value}'`;
    }
    keys() {
        return [this.key];
    }
    negate() {
        if (!this.negated) {
            this.negated = ContextKeyNotEqualsExpr.create(this.key, this.value, this);
        }
        return this.negated;
    }
}
class ContextKeyInExpr {
    constructor(key, valueKey) {
        this.key = key;
        this.valueKey = valueKey;
        this.type = 10 /* ContextKeyExprType.In */;
        this.negated = null;
    }
    static create(key, valueKey) {
        return new ContextKeyInExpr(key, valueKey);
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        return cmp2(this.key, this.valueKey, other.key, other.valueKey);
    }
    equals(other) {
        if (other.type === this.type) {
            return (this.key === other.key && this.valueKey === other.valueKey);
        }
        return false;
    }
    substituteConstants() {
        return this;
    }
    evaluate(context) {
        const source = context.getValue(this.valueKey);
        const item = context.getValue(this.key);
        if (Array.isArray(source)) {
            return source.includes(item);
        }
        if (typeof item === 'string' && typeof source === 'object' && source !== null) {
            return contextkey_hasOwnProperty.call(source, item);
        }
        return false;
    }
    serialize() {
        return `${this.key} in '${this.valueKey}'`;
    }
    keys() {
        return [this.key, this.valueKey];
    }
    negate() {
        if (!this.negated) {
            this.negated = ContextKeyNotInExpr.create(this.key, this.valueKey);
        }
        return this.negated;
    }
}
class ContextKeyNotInExpr {
    constructor(key, valueKey) {
        this.key = key;
        this.valueKey = valueKey;
        this.type = 11 /* ContextKeyExprType.NotIn */;
        this._negated = ContextKeyInExpr.create(key, valueKey);
    }
    static create(key, valueKey) {
        return new ContextKeyNotInExpr(key, valueKey);
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        return this._negated.cmp(other._negated);
    }
    equals(other) {
        if (other.type === this.type) {
            return this._negated.equals(other._negated);
        }
        return false;
    }
    substituteConstants() {
        return this;
    }
    evaluate(context) {
        return !this._negated.evaluate(context);
    }
    serialize() {
        return `${this.key} not in '${this.valueKey}'`;
    }
    keys() {
        return this._negated.keys();
    }
    negate() {
        return this._negated;
    }
}
class ContextKeyNotEqualsExpr {
    constructor(key, value, negated) {
        this.key = key;
        this.value = value;
        this.negated = negated;
        this.type = 5 /* ContextKeyExprType.NotEquals */;
    }
    static create(key, value, negated = null) {
        if (typeof value === 'boolean') {
            if (value) {
                return ContextKeyNotExpr.create(key, negated);
            }
            return ContextKeyDefinedExpr.create(key, negated);
        }
        const constantValue = CONSTANT_VALUES.get(key);
        if (typeof constantValue === 'boolean') {
            const falseValue = constantValue ? 'true' : 'false';
            return (value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE);
        }
        return new ContextKeyNotEqualsExpr(key, value, negated);
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        return cmp2(this.key, this.value, other.key, other.value);
    }
    equals(other) {
        if (other.type === this.type) {
            return (this.key === other.key && this.value === other.value);
        }
        return false;
    }
    substituteConstants() {
        const constantValue = CONSTANT_VALUES.get(this.key);
        if (typeof constantValue === 'boolean') {
            const falseValue = constantValue ? 'true' : 'false';
            return (this.value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE);
        }
        return this;
    }
    evaluate(context) {
        // Intentional !=
        // eslint-disable-next-line eqeqeq
        return (context.getValue(this.key) != this.value);
    }
    serialize() {
        return `${this.key} != '${this.value}'`;
    }
    keys() {
        return [this.key];
    }
    negate() {
        if (!this.negated) {
            this.negated = ContextKeyEqualsExpr.create(this.key, this.value, this);
        }
        return this.negated;
    }
}
class ContextKeyNotExpr {
    constructor(key, negated) {
        this.key = key;
        this.negated = negated;
        this.type = 3 /* ContextKeyExprType.Not */;
    }
    static create(key, negated = null) {
        const constantValue = CONSTANT_VALUES.get(key);
        if (typeof constantValue === 'boolean') {
            return (constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE);
        }
        return new ContextKeyNotExpr(key, negated);
    }
    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 ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE);
        }
        return this;
    }
    evaluate(context) {
        return (!context.getValue(this.key));
    }
    serialize() {
        return `!${this.key}`;
    }
    keys() {
        return [this.key];
    }
    negate() {
        if (!this.negated) {
            this.negated = ContextKeyDefinedExpr.create(this.key, this);
        }
        return this.negated;
    }
}
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 ContextKeyFalseExpr.INSTANCE;
}
class ContextKeyGreaterExpr {
    constructor(key, value, negated) {
        this.key = key;
        this.value = value;
        this.negated = negated;
        this.type = 12 /* ContextKeyExprType.Greater */;
    }
    static create(key, _value, negated = null) {
        return withFloatOrStr(_value, (value) => new ContextKeyGreaterExpr(key, value, negated));
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        return cmp2(this.key, this.value, other.key, other.value);
    }
    equals(other) {
        if (other.type === this.type) {
            return (this.key === other.key && this.value === other.value);
        }
        return false;
    }
    substituteConstants() {
        return this;
    }
    evaluate(context) {
        if (typeof this.value === 'string') {
            return false;
        }
        return (parseFloat(context.getValue(this.key)) > this.value);
    }
    serialize() {
        return `${this.key} > ${this.value}`;
    }
    keys() {
        return [this.key];
    }
    negate() {
        if (!this.negated) {
            this.negated = ContextKeySmallerEqualsExpr.create(this.key, this.value, this);
        }
        return this.negated;
    }
}
class ContextKeyGreaterEqualsExpr {
    constructor(key, value, negated) {
        this.key = key;
        this.value = value;
        this.negated = negated;
        this.type = 13 /* ContextKeyExprType.GreaterEquals */;
    }
    static create(key, _value, negated = null) {
        return withFloatOrStr(_value, (value) => new ContextKeyGreaterEqualsExpr(key, value, negated));
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        return cmp2(this.key, this.value, other.key, other.value);
    }
    equals(other) {
        if (other.type === this.type) {
            return (this.key === other.key && this.value === other.value);
        }
        return false;
    }
    substituteConstants() {
        return this;
    }
    evaluate(context) {
        if (typeof this.value === 'string') {
            return false;
        }
        return (parseFloat(context.getValue(this.key)) >= this.value);
    }
    serialize() {
        return `${this.key} >= ${this.value}`;
    }
    keys() {
        return [this.key];
    }
    negate() {
        if (!this.negated) {
            this.negated = ContextKeySmallerExpr.create(this.key, this.value, this);
        }
        return this.negated;
    }
}
class ContextKeySmallerExpr {
    constructor(key, value, negated) {
        this.key = key;
        this.value = value;
        this.negated = negated;
        this.type = 14 /* ContextKeyExprType.Smaller */;
    }
    static create(key, _value, negated = null) {
        return withFloatOrStr(_value, (value) => new ContextKeySmallerExpr(key, value, negated));
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        return cmp2(this.key, this.value, other.key, other.value);
    }
    equals(other) {
        if (other.type === this.type) {
            return (this.key === other.key && this.value === other.value);
        }
        return false;
    }
    substituteConstants() {
        return this;
    }
    evaluate(context) {
        if (typeof this.value === 'string') {
            return false;
        }
        return (parseFloat(context.getValue(this.key)) < this.value);
    }
    serialize() {
        return `${this.key} < ${this.value}`;
    }
    keys() {
        return [this.key];
    }
    negate() {
        if (!this.negated) {
            this.negated = ContextKeyGreaterEqualsExpr.create(this.key, this.value, this);
        }
        return this.negated;
    }
}
class ContextKeySmallerEqualsExpr {
    constructor(key, value, negated) {
        this.key = key;
        this.value = value;
        this.negated = negated;
        this.type = 15 /* ContextKeyExprType.SmallerEquals */;
    }
    static create(key, _value, negated = null) {
        return withFloatOrStr(_value, (value) => new ContextKeySmallerEqualsExpr(key, value, negated));
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        return cmp2(this.key, this.value, other.key, other.value);
    }
    equals(other) {
        if (other.type === this.type) {
            return (this.key === other.key && this.value === other.value);
        }
        return false;
    }
    substituteConstants() {
        return this;
    }
    evaluate(context) {
        if (typeof this.value === 'string') {
            return false;
        }
        return (parseFloat(context.getValue(this.key)) <= this.value);
    }
    serialize() {
        return `${this.key} <= ${this.value}`;
    }
    keys() {
        return [this.key];
    }
    negate() {
        if (!this.negated) {
            this.negated = ContextKeyGreaterExpr.create(this.key, this.value, this);
        }
        return this.negated;
    }
}
class ContextKeyRegexExpr {
    constructor(key, regexp) {
        this.key = key;
        this.regexp = regexp;
        this.type = 7 /* ContextKeyExprType.Regex */;
        this.negated = null;
        //
    }
    static create(key, regexp) {
        return new ContextKeyRegexExpr(key, regexp);
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        if (this.key < other.key) {
            return -1;
        }
        if (this.key > other.key) {
            return 1;
        }
        const thisSource = this.regexp ? this.regexp.source : '';
        const otherSource = other.regexp ? other.regexp.source : '';
        if (thisSource < otherSource) {
            return -1;
        }
        if (thisSource > otherSource) {
            return 1;
        }
        return 0;
    }
    equals(other) {
        if (other.type === this.type) {
            const thisSource = this.regexp ? this.regexp.source : '';
            const otherSource = other.regexp ? other.regexp.source : '';
            return (this.key === other.key && thisSource === otherSource);
        }
        return false;
    }
    substituteConstants() {
        return this;
    }
    evaluate(context) {
        const value = context.getValue(this.key);
        return this.regexp ? this.regexp.test(value) : false;
    }
    serialize() {
        const value = this.regexp
            ? `/${this.regexp.source}/${this.regexp.ignoreCase ? 'i' : ''}`
            : '/invalid/';
        return `${this.key} =~ ${value}`;
    }
    keys() {
        return [this.key];
    }
    negate() {
        if (!this.negated) {
            this.negated = ContextKeyNotRegexExpr.create(this);
        }
        return this.negated;
    }
}
class ContextKeyNotRegexExpr {
    constructor(_actual) {
        this._actual = _actual;
        this.type = 8 /* ContextKeyExprType.NotRegex */;
        //
    }
    static create(actual) {
        return new ContextKeyNotRegexExpr(actual);
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        return this._actual.cmp(other._actual);
    }
    equals(other) {
        if (other.type === this.type) {
            return this._actual.equals(other._actual);
        }
        return false;
    }
    substituteConstants() {
        return this;
    }
    evaluate(context) {
        return !this._actual.evaluate(context);
    }
    serialize() {
        throw new Error('Method not implemented.');
    }
    keys() {
        return this._actual.keys();
    }
    negate() {
        return this._actual;
    }
}
/**
 * @returns the same instance if nothing changed.
 */
function eliminateConstantsInArray(arr) {
    // Allocate array only if there is a difference
    let newArr = null;
    for (let i = 0, len = arr.length; i < len; i++) {
        const newExpr = arr[i].substituteConstants();
        if (arr[i] !== newExpr) {
            // something has changed!
            // allocate array on first difference
            if (newArr === null) {
                newArr = [];
                for (let j = 0; j < i; j++) {
                    newArr[j] = arr[j];
                }
            }
        }
        if (newArr !== null) {
            newArr[i] = newExpr;
        }
    }
    if (newArr === null) {
        return arr;
    }
    return newArr;
}
class ContextKeyAndExpr {
    constructor(expr, negated) {
        this.expr = expr;
        this.negated = negated;
        this.type = 6 /* ContextKeyExprType.And */;
    }
    static create(_expr, negated) {
        return ContextKeyAndExpr._normalizeArr(_expr, negated);
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        if (this.expr.length < other.expr.length) {
            return -1;
        }
        if (this.expr.length > other.expr.length) {
            return 1;
        }
        for (let i = 0, len = this.expr.length; i < len; i++) {
            const r = cmp(this.expr[i], other.expr[i]);
            if (r !== 0) {
                return r;
            }
        }
        return 0;
    }
    equals(other) {
        if (other.type === this.type) {
            if (this.expr.length !== other.expr.length) {
                return false;
            }
            for (let i = 0, len = this.expr.length; i < len; i++) {
                if (!this.expr[i].equals(other.expr[i])) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
    substituteConstants() {
        const exprArr = eliminateConstantsInArray(this.expr);
        if (exprArr === this.expr) {
            // no change
            return this;
        }
        return ContextKeyAndExpr.create(exprArr, this.negated);
    }
    evaluate(context) {
        for (let i = 0, len = this.expr.length; i < len; i++) {
            if (!this.expr[i].evaluate(context)) {
                return false;
            }
        }
        return true;
    }
    static _normalizeArr(arr, negated) {
        const expr = [];
        let hasTrue = false;
        for (const e of arr) {
            if (!e) {
                continue;
            }
            if (e.type === 1 /* ContextKeyExprType.True */) {
                // anything && true ==> anything
                hasTrue = true;
                continue;
            }
            if (e.type === 0 /* ContextKeyExprType.False */) {
                // anything && false ==> false
                return ContextKeyFalseExpr.INSTANCE;
            }
            if (e.type === 6 /* ContextKeyExprType.And */) {
                expr.push(...e.expr);
                continue;
            }
            expr.push(e);
        }
        if (expr.length === 0 && hasTrue) {
            return ContextKeyTrueExpr.INSTANCE;
        }
        if (expr.length === 0) {
            return undefined;
        }
        if (expr.length === 1) {
            return expr[0];
        }
        expr.sort(cmp);
        // eliminate duplicate terms
        for (let i = 1; i < expr.length; i++) {
            if (expr[i - 1].equals(expr[i])) {
                expr.splice(i, 1);
                i--;
            }
        }
        if (expr.length === 1) {
            return expr[0];
        }
        // We must distribute any OR expression because we don't support parens
        // OR extensions will be at the end (due to sorting rules)
        while (expr.length > 1) {
            const lastElement = expr[expr.length - 1];
            if (lastElement.type !== 9 /* ContextKeyExprType.Or */) {
                break;
            }
            // pop the last element
            expr.pop();
            // pop the second to last element
            const secondToLastElement = expr.pop();
            const isFinished = (expr.length === 0);
            // distribute `lastElement` over `secondToLastElement`
            const resultElement = ContextKeyOrExpr.create(lastElement.expr.map(el => ContextKeyAndExpr.create([el, secondToLastElement], null)), null, isFinished);
            if (resultElement) {
                expr.push(resultElement);
                expr.sort(cmp);
            }
        }
        if (expr.length === 1) {
            return expr[0];
        }
        return new ContextKeyAndExpr(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;
    }
    negate() {
        if (!this.negated) {
            const result = [];
            for (const expr of this.expr) {
                result.push(expr.negate());
            }
            this.negated = ContextKeyOrExpr.create(result, this, true);
        }
        return this.negated;
    }
}
class ContextKeyOrExpr {
    constructor(expr, negated) {
        this.expr = expr;
        this.negated = negated;
        this.type = 9 /* ContextKeyExprType.Or */;
    }
    static create(_expr, negated, extraRedundantCheck) {
        return ContextKeyOrExpr._normalizeArr(_expr, negated, extraRedundantCheck);
    }
    cmp(other) {
        if (other.type !== this.type) {
            return this.type - other.type;
        }
        if (this.expr.length < other.expr.length) {
            return -1;
        }
        if (this.expr.length > other.expr.length) {
            return 1;
        }
        for (let i = 0, len = this.expr.length; i < len; i++) {
            const r = cmp(this.expr[i], other.expr[i]);
            if (r !== 0) {
                return r;
            }
        }
        return 0;
    }
    equals(other) {
        if (other.type === this.type) {
            if (this.expr.length !== other.expr.length) {
                return false;
            }
            for (let i = 0, len = this.expr.length; i < len; i++) {
                if (!this.expr[i].equals(other.expr[i])) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
    substituteConstants() {
        const exprArr = eliminateConstantsInArray(this.expr);
        if (exprArr === this.expr) {
            // no change
            return this;
        }
        return ContextKeyOrExpr.create(exprArr, this.negated, false);
    }
    evaluate(context) {
        for (let i = 0, len = this.expr.length; i < len; i++) {
            if (this.expr[i].evaluate(context)) {
                return true;
            }
        }
        return false;
    }
    static _normalizeArr(arr, negated, extraRedundantCheck) {
        let expr = [];
        let hasFalse = false;
        if (arr) {
            for (let i = 0, len = arr.length; i < len; i++) {
                const e = arr[i];
                if (!e) {
                    continue;
                }
                if (e.type === 0 /* ContextKeyExprType.False */) {
                    // anything || false ==> anything
                    hasFalse = true;
                    continue;
                }
                if (e.type === 1 /* ContextKeyExprType.True */) {
                    // anything || true ==> true
                    return ContextKeyTrueExpr.INSTANCE;
                }
                if (e.type === 9 /* ContextKeyExprType.Or */) {
                    expr = expr.concat(e.expr);
                    continue;
                }
                expr.push(e);
            }
            if (expr.length === 0 && hasFalse) {
                return ContextKeyFalseExpr.INSTANCE;
            }
            expr.sort(cmp);
        }
        if (expr.length === 0) {
            return undefined;
        }
        if (expr.length === 1) {
            return expr[0];
        }
        // eliminate duplicate terms
        for (let i = 1; i < expr.length; i++) {
            if (expr[i - 1].equals(expr[i])) {
                expr.splice(i, 1);
                i--;
            }
        }
        if (expr.length === 1) {
            return expr[0];
        }
        // eliminate redundant terms
        if (extraRedundantCheck) {
            for (let i = 0; i < expr.length; i++) {
                for (let j = i + 1; j < expr.length; j++) {
                    if (implies(expr[i], expr[j])) {
                        expr.splice(j, 1);
                        j--;
                    }
                }
            }
            if (expr.length === 1) {
                return expr[0];
            }
        }
        return new ContextKeyOrExpr(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;
    }
    negate() {
        if (!this.negated) {
            const result = [];
            for (const expr of this.expr) {
                result.push(expr.negate());
            }
            // We don't support parens, so here we distribute the AND over the OR terminals
            // We always take the first 2 AND pairs and distribute them
            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(ContextKeyAndExpr.create([left, right], null));
                    }
                }
                const isFinished = (result.length === 0);
                result.unshift(ContextKeyOrExpr.create(all, null, isFinished));
            }
            this.negated = result[0];
        }
        return this.negated;
    }
}
class RawContextKey extends ContextKeyDefinedExpr {
    constructor(key, defaultValue, metaOrHide) {
        super(key, null);
        this._defaultValue = defaultValue;
        // collect all context keys into a central place
        if (typeof metaOrHide === 'object') {
            RawContextKey._info.push(Object.assign(Object.assign({}, metaOrHide), { key }));
        }
        else if (metaOrHide !== true) {
            RawContextKey._info.push({ key, description: metaOrHide, type: defaultValue !== null && defaultValue !== undefined ? typeof defaultValue : undefined });
        }
    }
    static all() {
        return RawContextKey._info.values();
    }
    bindTo(target) {
        return target.createKey(this.key, this._defaultValue);
    }
    getValue(target) {
        return target.getContextKeyValue(this.key);
    }
    toNegated() {
        return this.negate();
    }
    isEqualTo(value) {
        return ContextKeyEqualsExpr.create(this.key, value);
    }
}
RawContextKey._info = [];
const IContextKeyService = createDecorator('contextKeyService');
const SET_CONTEXT_COMMAND_ID = 'setContext';
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;
}
/**
 * Returns true if it is provable `p` implies `q`.
 */
function implies(p, q) {
    if (q.type === 6 /* ContextKeyExprType.And */ && (p.type !== 9 /* ContextKeyExprType.Or */ && p.type !== 6 /* ContextKeyExprType.And */)) {
        // covers the case: A implies A && B
        for (const qTerm of q.expr) {
            if (p.equals(qTerm)) {
                return true;
            }
        }
    }
    const notP = p.negate();
    const expr = getTerminals(notP).concat(getTerminals(q));
    expr.sort(cmp);
    for (let i = 0; i < expr.length; i++) {
        const a = expr[i];
        const notA = a.negate();
        for (let j = i + 1; j < expr.length; j++) {
            const b = expr[j];
            if (notA.equals(b)) {
                return true;
            }
        }
    }
    return false;
}
function getTerminals(node) {
    if (node.type === 9 /* ContextKeyExprType.Or */) {
        return node.expr;
    }
    return [node];
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/assert.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/**
 * Throws an error with the provided message if the provided value does not evaluate to a true Javascript value.
 */
function ok(value, message) {
    if (!value) {
        throw new Error(message ? `Assertion failed (${message})` : 'Assertion Failed');
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/registry/common/platform.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class RegistryImpl {
    constructor() {
        this.data = new Map();
    }
    add(id, data) {
        ok(isString(id));
        ok(isObject(data));
        ok(!this.data.has(id), 'There is already an extension with this id');
        this.data.set(id, data);
    }
    as(id) {
        return this.data.get(id) || null;
    }
}
const Registry = new RegistryImpl();

;// ../../node_modules/monaco-editor/esm/vs/platform/theme/common/theme.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/**
 * Color scheme used by the OS and by color themes.
 */
var ColorScheme;
(function (ColorScheme) {
    ColorScheme["DARK"] = "dark";
    ColorScheme["LIGHT"] = "light";
    ColorScheme["HIGH_CONTRAST_DARK"] = "hcDark";
    ColorScheme["HIGH_CONTRAST_LIGHT"] = "hcLight";
})(ColorScheme || (ColorScheme = {}));
function isHighContrast(scheme) {
    return scheme === ColorScheme.HIGH_CONTRAST_DARK || scheme === ColorScheme.HIGH_CONTRAST_LIGHT;
}
function isDark(scheme) {
    return scheme === ColorScheme.DARK || scheme === ColorScheme.HIGH_CONTRAST_DARK;
}

;// ../../node_modules/monaco-editor/esm/vs/platform/theme/common/themeService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






const IThemeService = createDecorator('themeService');
var ThemeColor;
(function (ThemeColor) {
    function isThemeColor(obj) {
        return obj && typeof obj === 'object' && typeof obj.id === 'string';
    }
    ThemeColor.isThemeColor = isThemeColor;
})(ThemeColor || (ThemeColor = {}));
function themeColorFromId(id) {
    return { id };
}
var ThemeIcon;
(function (ThemeIcon) {
    function isThemeIcon(obj) {
        return obj && typeof obj === 'object' && typeof obj.id === 'string' && (typeof obj.color === 'undefined' || ThemeColor.isThemeColor(obj.color));
    }
    ThemeIcon.isThemeIcon = isThemeIcon;
    const _regexFromString = new RegExp(`^\\$\\((${CSSIcon.iconNameExpression}(?:${CSSIcon.iconModifierExpression})?)\\)$`);
    function fromString(str) {
        const match = _regexFromString.exec(str);
        if (!match) {
            return undefined;
        }
        const [, name] = match;
        return { id: name };
    }
    ThemeIcon.fromString = fromString;
    function fromId(id) {
        return { id };
    }
    ThemeIcon.fromId = fromId;
    function modify(icon, modifier) {
        let id = icon.id;
        const tildeIndex = id.lastIndexOf('~');
        if (tildeIndex !== -1) {
            id = id.substring(0, tildeIndex);
        }
        if (modifier) {
            id = `${id}~${modifier}`;
        }
        return { id };
    }
    ThemeIcon.modify = modify;
    function getModifier(icon) {
        const tildeIndex = icon.id.lastIndexOf('~');
        if (tildeIndex !== -1) {
            return icon.id.substring(tildeIndex + 1);
        }
        return undefined;
    }
    ThemeIcon.getModifier = getModifier;
    function isEqual(ti1, ti2) {
        var _a, _b;
        return ti1.id === ti2.id && ((_a = ti1.color) === null || _a === void 0 ? void 0 : _a.id) === ((_b = ti2.color) === null || _b === void 0 ? void 0 : _b.id);
    }
    ThemeIcon.isEqual = isEqual;
    function asThemeIcon(codicon, color) {
        return { id: codicon.id, color: color ? themeColorFromId(color) : undefined };
    }
    ThemeIcon.asThemeIcon = asThemeIcon;
    ThemeIcon.asClassNameArray = CSSIcon.asClassNameArray;
    ThemeIcon.asClassName = CSSIcon.asClassName;
    ThemeIcon.asCSSSelector = CSSIcon.asCSSSelector;
})(ThemeIcon || (ThemeIcon = {}));
function getThemeTypeSelector(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';
    }
}
// static theming participant
const Extensions = {
    ThemingContribution: 'base.contributions.theming'
};
class ThemingRegistry {
    constructor() {
        this.themingParticipants = [];
        this.themingParticipants = [];
        this.onThemingParticipantAddedEmitter = new Emitter();
    }
    onColorThemeChange(participant) {
        this.themingParticipants.push(participant);
        this.onThemingParticipantAddedEmitter.fire(participant);
        return toDisposable(() => {
            const idx = this.themingParticipants.indexOf(participant);
            this.themingParticipants.splice(idx, 1);
        });
    }
    getThemingParticipants() {
        return this.themingParticipants;
    }
}
const themingRegistry = new ThemingRegistry();
Registry.add(Extensions.ThemingContribution, themingRegistry);
function registerThemingParticipant(participant) {
    return themingRegistry.onColorThemeChange(participant);
}
/**
 * Utility base class for all themable components.
 */
class Themable extends Disposable {
    constructor(themeService) {
        super();
        this.themeService = themeService;
        this.theme = themeService.getColorTheme();
        // Hook up to theme changes
        this._register(this.themeService.onDidColorThemeChange(theme => this.onThemeChange(theme)));
    }
    onThemeChange(theme) {
        this.theme = theme;
        this.updateStyles();
    }
    updateStyles() {
        // Subclasses to override
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/actions/common/actions.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var actions_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};










function isIMenuItem(item) {
    return item.command !== undefined;
}
class MenuId {
    /**
     * 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(identifier) {
        if (MenuId._instances.has(identifier)) {
            throw new TypeError(`MenuId with identifier '${identifier}' already exists. Use MenuId.for(ident) or a unique identifier`);
        }
        MenuId._instances.set(identifier, this);
        this.id = identifier;
    }
}
MenuId._instances = new Map();
MenuId.CommandPalette = new MenuId('CommandPalette');
MenuId.DebugBreakpointsContext = new MenuId('DebugBreakpointsContext');
MenuId.DebugCallStackContext = new MenuId('DebugCallStackContext');
MenuId.DebugConsoleContext = new MenuId('DebugConsoleContext');
MenuId.DebugVariablesContext = new MenuId('DebugVariablesContext');
MenuId.DebugWatchContext = new MenuId('DebugWatchContext');
MenuId.DebugToolBar = new MenuId('DebugToolBar');
MenuId.DebugToolBarStop = new MenuId('DebugToolBarStop');
MenuId.EditorContext = new MenuId('EditorContext');
MenuId.SimpleEditorContext = new MenuId('SimpleEditorContext');
MenuId.EditorContextCopy = new MenuId('EditorContextCopy');
MenuId.EditorContextPeek = new MenuId('EditorContextPeek');
MenuId.EditorContextShare = new MenuId('EditorContextShare');
MenuId.EditorTitle = new MenuId('EditorTitle');
MenuId.EditorTitleRun = new MenuId('EditorTitleRun');
MenuId.EditorTitleContext = new MenuId('EditorTitleContext');
MenuId.EmptyEditorGroup = new MenuId('EmptyEditorGroup');
MenuId.EmptyEditorGroupContext = new MenuId('EmptyEditorGroupContext');
MenuId.ExplorerContext = new MenuId('ExplorerContext');
MenuId.ExtensionContext = new MenuId('ExtensionContext');
MenuId.GlobalActivity = new MenuId('GlobalActivity');
MenuId.CommandCenter = new MenuId('CommandCenter');
MenuId.LayoutControlMenuSubmenu = new MenuId('LayoutControlMenuSubmenu');
MenuId.LayoutControlMenu = new MenuId('LayoutControlMenu');
MenuId.MenubarMainMenu = new MenuId('MenubarMainMenu');
MenuId.MenubarAppearanceMenu = new MenuId('MenubarAppearanceMenu');
MenuId.MenubarDebugMenu = new MenuId('MenubarDebugMenu');
MenuId.MenubarEditMenu = new MenuId('MenubarEditMenu');
MenuId.MenubarCopy = new MenuId('MenubarCopy');
MenuId.MenubarFileMenu = new MenuId('MenubarFileMenu');
MenuId.MenubarGoMenu = new MenuId('MenubarGoMenu');
MenuId.MenubarHelpMenu = new MenuId('MenubarHelpMenu');
MenuId.MenubarLayoutMenu = new MenuId('MenubarLayoutMenu');
MenuId.MenubarNewBreakpointMenu = new MenuId('MenubarNewBreakpointMenu');
MenuId.MenubarPanelAlignmentMenu = new MenuId('MenubarPanelAlignmentMenu');
MenuId.MenubarPanelPositionMenu = new MenuId('MenubarPanelPositionMenu');
MenuId.MenubarPreferencesMenu = new MenuId('MenubarPreferencesMenu');
MenuId.MenubarRecentMenu = new MenuId('MenubarRecentMenu');
MenuId.MenubarSelectionMenu = new MenuId('MenubarSelectionMenu');
MenuId.MenubarShare = new MenuId('MenubarShare');
MenuId.MenubarSwitchEditorMenu = new MenuId('MenubarSwitchEditorMenu');
MenuId.MenubarSwitchGroupMenu = new MenuId('MenubarSwitchGroupMenu');
MenuId.MenubarTerminalMenu = new MenuId('MenubarTerminalMenu');
MenuId.MenubarViewMenu = new MenuId('MenubarViewMenu');
MenuId.MenubarHomeMenu = new MenuId('MenubarHomeMenu');
MenuId.OpenEditorsContext = new MenuId('OpenEditorsContext');
MenuId.ProblemsPanelContext = new MenuId('ProblemsPanelContext');
MenuId.SCMChangeContext = new MenuId('SCMChangeContext');
MenuId.SCMResourceContext = new MenuId('SCMResourceContext');
MenuId.SCMResourceFolderContext = new MenuId('SCMResourceFolderContext');
MenuId.SCMResourceGroupContext = new MenuId('SCMResourceGroupContext');
MenuId.SCMSourceControl = new MenuId('SCMSourceControl');
MenuId.SCMTitle = new MenuId('SCMTitle');
MenuId.SearchContext = new MenuId('SearchContext');
MenuId.StatusBarWindowIndicatorMenu = new MenuId('StatusBarWindowIndicatorMenu');
MenuId.StatusBarRemoteIndicatorMenu = new MenuId('StatusBarRemoteIndicatorMenu');
MenuId.TestItem = new MenuId('TestItem');
MenuId.TestItemGutter = new MenuId('TestItemGutter');
MenuId.TestPeekElement = new MenuId('TestPeekElement');
MenuId.TestPeekTitle = new MenuId('TestPeekTitle');
MenuId.TouchBarContext = new MenuId('TouchBarContext');
MenuId.TitleBarContext = new MenuId('TitleBarContext');
MenuId.TitleBarTitleContext = new MenuId('TitleBarTitleContext');
MenuId.TunnelContext = new MenuId('TunnelContext');
MenuId.TunnelPrivacy = new MenuId('TunnelPrivacy');
MenuId.TunnelProtocol = new MenuId('TunnelProtocol');
MenuId.TunnelPortInline = new MenuId('TunnelInline');
MenuId.TunnelTitle = new MenuId('TunnelTitle');
MenuId.TunnelLocalAddressInline = new MenuId('TunnelLocalAddressInline');
MenuId.TunnelOriginInline = new MenuId('TunnelOriginInline');
MenuId.ViewItemContext = new MenuId('ViewItemContext');
MenuId.ViewContainerTitle = new MenuId('ViewContainerTitle');
MenuId.ViewContainerTitleContext = new MenuId('ViewContainerTitleContext');
MenuId.ViewTitle = new MenuId('ViewTitle');
MenuId.ViewTitleContext = new MenuId('ViewTitleContext');
MenuId.CommentThreadTitle = new MenuId('CommentThreadTitle');
MenuId.CommentThreadActions = new MenuId('CommentThreadActions');
MenuId.CommentTitle = new MenuId('CommentTitle');
MenuId.CommentActions = new MenuId('CommentActions');
MenuId.InteractiveToolbar = new MenuId('InteractiveToolbar');
MenuId.InteractiveCellTitle = new MenuId('InteractiveCellTitle');
MenuId.InteractiveCellDelete = new MenuId('InteractiveCellDelete');
MenuId.InteractiveCellExecute = new MenuId('InteractiveCellExecute');
MenuId.InteractiveInputExecute = new MenuId('InteractiveInputExecute');
MenuId.NotebookToolbar = new MenuId('NotebookToolbar');
MenuId.NotebookCellTitle = new MenuId('NotebookCellTitle');
MenuId.NotebookCellDelete = new MenuId('NotebookCellDelete');
MenuId.NotebookCellInsert = new MenuId('NotebookCellInsert');
MenuId.NotebookCellBetween = new MenuId('NotebookCellBetween');
MenuId.NotebookCellListTop = new MenuId('NotebookCellTop');
MenuId.NotebookCellExecute = new MenuId('NotebookCellExecute');
MenuId.NotebookCellExecutePrimary = new MenuId('NotebookCellExecutePrimary');
MenuId.NotebookDiffCellInputTitle = new MenuId('NotebookDiffCellInputTitle');
MenuId.NotebookDiffCellMetadataTitle = new MenuId('NotebookDiffCellMetadataTitle');
MenuId.NotebookDiffCellOutputsTitle = new MenuId('NotebookDiffCellOutputsTitle');
MenuId.NotebookOutputToolbar = new MenuId('NotebookOutputToolbar');
MenuId.NotebookEditorLayoutConfigure = new MenuId('NotebookEditorLayoutConfigure');
MenuId.NotebookKernelSource = new MenuId('NotebookKernelSource');
MenuId.BulkEditTitle = new MenuId('BulkEditTitle');
MenuId.BulkEditContext = new MenuId('BulkEditContext');
MenuId.TimelineItemContext = new MenuId('TimelineItemContext');
MenuId.TimelineTitle = new MenuId('TimelineTitle');
MenuId.TimelineTitleContext = new MenuId('TimelineTitleContext');
MenuId.TimelineFilterSubMenu = new MenuId('TimelineFilterSubMenu');
MenuId.AccountsContext = new MenuId('AccountsContext');
MenuId.PanelTitle = new MenuId('PanelTitle');
MenuId.AuxiliaryBarTitle = new MenuId('AuxiliaryBarTitle');
MenuId.TerminalInstanceContext = new MenuId('TerminalInstanceContext');
MenuId.TerminalEditorInstanceContext = new MenuId('TerminalEditorInstanceContext');
MenuId.TerminalNewDropdownContext = new MenuId('TerminalNewDropdownContext');
MenuId.TerminalTabContext = new MenuId('TerminalTabContext');
MenuId.TerminalTabEmptyAreaContext = new MenuId('TerminalTabEmptyAreaContext');
MenuId.TerminalInlineTabContext = new MenuId('TerminalInlineTabContext');
MenuId.WebviewContext = new MenuId('WebviewContext');
MenuId.InlineCompletionsActions = new MenuId('InlineCompletionsActions');
MenuId.NewFile = new MenuId('NewFile');
MenuId.MergeToolbar = new MenuId('MergeToolbar');
MenuId.MergeInput1Toolbar = new MenuId('MergeToolbar1Toolbar');
MenuId.MergeInput2Toolbar = new MenuId('MergeToolbar2Toolbar');
const IMenuService = createDecorator('menuService');
const MenuRegistry = new class {
    constructor() {
        this._commands = new Map();
        this._menuItems = new Map();
        this._onDidChangeMenu = new Emitter();
        this.onDidChangeMenu = this._onDidChangeMenu.event;
        this._commandPaletteChangeEvent = {
            has: id => id === MenuId.CommandPalette
        };
    }
    addCommand(command) {
        return this.addCommands(Iterable.single(command));
    }
    addCommands(commands) {
        for (const command of commands) {
            this._commands.set(command.id, command);
        }
        this._onDidChangeMenu.fire(this._commandPaletteChangeEvent);
        return toDisposable(() => {
            let didChange = false;
            for (const command of commands) {
                didChange = this._commands.delete(command.id) || didChange;
            }
            if (didChange) {
                this._onDidChangeMenu.fire(this._commandPaletteChangeEvent);
            }
        });
    }
    getCommand(id) {
        return this._commands.get(id);
    }
    getCommands() {
        const map = new Map();
        this._commands.forEach((value, key) => map.set(key, value));
        return map;
    }
    appendMenuItem(id, item) {
        return this.appendMenuItems(Iterable.single({ id, item }));
    }
    appendMenuItems(items) {
        const changedIds = new Set();
        const toRemove = new LinkedList();
        for (const { id, item } of items) {
            let list = this._menuItems.get(id);
            if (!list) {
                list = new LinkedList();
                this._menuItems.set(id, list);
            }
            toRemove.push(list.push(item));
            changedIds.add(id);
        }
        this._onDidChangeMenu.fire(changedIds);
        return toDisposable(() => {
            if (toRemove.size > 0) {
                for (const fn of toRemove) {
                    fn();
                }
                this._onDidChangeMenu.fire(changedIds);
                toRemove.clear();
            }
        });
    }
    getMenuItems(id) {
        let result;
        if (this._menuItems.has(id)) {
            result = [...this._menuItems.get(id)];
        }
        else {
            result = [];
        }
        if (id === MenuId.CommandPalette) {
            // CommandPalette is special because it shows
            // all commands by default
            this._appendImplicitItems(result);
        }
        return result;
    }
    _appendImplicitItems(result) {
        const set = new Set();
        for (const item of result) {
            if (isIMenuItem(item)) {
                set.add(item.command.id);
                if (item.alt) {
                    set.add(item.alt.id);
                }
            }
        }
        this._commands.forEach((command, id) => {
            if (!set.has(id)) {
                result.push({ command });
            }
        });
    }
};
class SubmenuItemAction extends SubmenuAction {
    constructor(item, _menuService, _contextKeyService, _options) {
        super(`submenuitem.${item.submenu.id}`, typeof item.title === 'string' ? item.title : item.title.value, [], 'submenu');
        this.item = item;
        this._menuService = _menuService;
        this._contextKeyService = _contextKeyService;
        this._options = _options;
    }
    get actions() {
        const result = [];
        const menu = this._menuService.createMenu(this.item.submenu, this._contextKeyService);
        const groups = menu.getActions(this._options);
        menu.dispose();
        for (const [, actions] of groups) {
            if (actions.length > 0) {
                result.push(...actions);
                result.push(new Separator());
            }
        }
        if (result.length) {
            result.pop(); // remove last separator
        }
        return result;
    }
}
// implements IAction, does NOT extend Action, so that no one
// subscribes to events of Action or modified properties
let MenuItemAction = class MenuItemAction {
    constructor(item, alt, options, hideActions, contextKeyService, _commandService) {
        var _a, _b;
        this.hideActions = hideActions;
        this._commandService = _commandService;
        this.id = item.id;
        this.label = (options === null || options === void 0 ? void 0 : options.renderShortTitle) && item.shortTitle
            ? (typeof item.shortTitle === 'string' ? item.shortTitle : item.shortTitle.value)
            : (typeof item.title === 'string' ? item.title : item.title.value);
        this.tooltip = (_b = (typeof item.tooltip === 'string' ? item.tooltip : (_a = item.tooltip) === null || _a === void 0 ? void 0 : _a.value)) !== null && _b !== void 0 ? _b : '';
        this.enabled = !item.precondition || contextKeyService.contextMatchesRules(item.precondition);
        this.checked = undefined;
        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 (toggled.title) {
                this.label = typeof toggled.title === 'string' ? toggled.title : toggled.title.value;
            }
        }
        this.item = item;
        this.alt = alt ? new MenuItemAction(alt, undefined, options, hideActions, contextKeyService, _commandService) : undefined;
        this._options = options;
        if (ThemeIcon.isThemeIcon(item.icon)) {
            this.class = CSSIcon.asClassName(item.icon);
        }
    }
    dispose() {
        // there is NOTHING to dispose and the MenuItemAction should
        // never have anything to dispose as it is a convenience type
        // to bridge into the rendering world.
    }
    run(...args) {
        var _a, _b;
        let runArgs = [];
        if ((_a = this._options) === null || _a === void 0 ? void 0 : _a.arg) {
            runArgs = [...runArgs, this._options.arg];
        }
        if ((_b = this._options) === null || _b === void 0 ? void 0 : _b.shouldForwardArgs) {
            runArgs = [...runArgs, ...args];
        }
        return this._commandService.executeCommand(this.id, ...runArgs);
    }
};
MenuItemAction = actions_decorate([
    __param(4, IContextKeyService),
    __param(5, ICommandService)
], MenuItemAction);

//#endregion

;// ../../node_modules/monaco-editor/esm/vs/platform/keybinding/common/keybindingsRegistry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class KeybindingsRegistryImpl {
    constructor() {
        this._coreKeybindings = [];
        this._extensionKeybindings = [];
        this._cachedMergedKeybindings = null;
    }
    /**
     * Take current platform into account and reduce to primary & secondary.
     */
    static bindToCurrentPlatform(kb) {
        if (OS === 1 /* OperatingSystem.Windows */) {
            if (kb && kb.win) {
                return kb.win;
            }
        }
        else if (OS === 2 /* OperatingSystem.Macintosh */) {
            if (kb && kb.mac) {
                return kb.mac;
            }
        }
        else {
            if (kb && kb.linux) {
                return kb.linux;
            }
        }
        return kb;
    }
    registerKeybindingRule(rule) {
        const actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule);
        if (actualKb && actualKb.primary) {
            const kk = createKeybinding(actualKb.primary, OS);
            if (kk) {
                this._registerDefaultKeybinding(kk, rule.id, rule.args, rule.weight, 0, rule.when);
            }
        }
        if (actualKb && Array.isArray(actualKb.secondary)) {
            for (let i = 0, len = actualKb.secondary.length; i < len; i++) {
                const k = actualKb.secondary[i];
                const kk = createKeybinding(k, OS);
                if (kk) {
                    this._registerDefaultKeybinding(kk, rule.id, rule.args, rule.weight, -i - 1, rule.when);
                }
            }
        }
    }
    registerCommandAndKeybindingRule(desc) {
        this.registerKeybindingRule(desc);
        CommandsRegistry.registerCommand(desc);
    }
    static _mightProduceChar(keyCode) {
        if (keyCode >= 21 /* KeyCode.Digit0 */ && keyCode <= 30 /* KeyCode.Digit9 */) {
            return true;
        }
        if (keyCode >= 31 /* KeyCode.KeyA */ && keyCode <= 56 /* KeyCode.KeyZ */) {
            return true;
        }
        return (keyCode === 80 /* KeyCode.Semicolon */
            || keyCode === 81 /* KeyCode.Equal */
            || keyCode === 82 /* KeyCode.Comma */
            || keyCode === 83 /* KeyCode.Minus */
            || keyCode === 84 /* KeyCode.Period */
            || keyCode === 85 /* KeyCode.Slash */
            || keyCode === 86 /* KeyCode.Backquote */
            || keyCode === 110 /* KeyCode.ABNT_C1 */
            || keyCode === 111 /* KeyCode.ABNT_C2 */
            || keyCode === 87 /* KeyCode.BracketLeft */
            || keyCode === 88 /* KeyCode.Backslash */
            || keyCode === 89 /* KeyCode.BracketRight */
            || keyCode === 90 /* KeyCode.Quote */
            || keyCode === 91 /* KeyCode.OEM_8 */
            || keyCode === 92 /* KeyCode.IntlBackslash */);
    }
    _assertNoCtrlAlt(keybinding, commandId) {
        if (keybinding.ctrlKey && keybinding.altKey && !keybinding.metaKey) {
            if (KeybindingsRegistryImpl._mightProduceChar(keybinding.keyCode)) {
                console.warn('Ctrl+Alt+ keybindings should not be used by default under Windows. Offender: ', keybinding, ' for ', commandId);
            }
        }
    }
    _registerDefaultKeybinding(keybinding, commandId, commandArgs, weight1, weight2, when) {
        if (OS === 1 /* OperatingSystem.Windows */) {
            this._assertNoCtrlAlt(keybinding.parts[0], commandId);
        }
        this._coreKeybindings.push({
            keybinding: keybinding.parts,
            command: commandId,
            commandArgs: commandArgs,
            when: when,
            weight1: weight1,
            weight2: weight2,
            extensionId: null,
            isBuiltinExtension: false
        });
        this._cachedMergedKeybindings = null;
    }
    getDefaultKeybindings() {
        if (!this._cachedMergedKeybindings) {
            this._cachedMergedKeybindings = [].concat(this._coreKeybindings).concat(this._extensionKeybindings);
            this._cachedMergedKeybindings.sort(sorter);
        }
        return this._cachedMergedKeybindings.slice(0);
    }
}
const KeybindingsRegistry = new KeybindingsRegistryImpl();
// Define extension point ids
const keybindingsRegistry_Extensions = {
    EditorModes: 'platform.keybindingsRegistry'
};
Registry.add(keybindingsRegistry_Extensions.EditorModes, KeybindingsRegistry);
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;
}

;// ../../node_modules/monaco-editor/esm/vs/platform/telemetry/common/telemetry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const ITelemetryService = createDecorator('telemetryService');

;// ../../node_modules/monaco-editor/esm/vs/platform/log/common/log.js



const ILogService = createDecorator('logService');
var LogLevel;
(function (LogLevel) {
    LogLevel[LogLevel["Trace"] = 0] = "Trace";
    LogLevel[LogLevel["Debug"] = 1] = "Debug";
    LogLevel[LogLevel["Info"] = 2] = "Info";
    LogLevel[LogLevel["Warning"] = 3] = "Warning";
    LogLevel[LogLevel["Error"] = 4] = "Error";
    LogLevel[LogLevel["Critical"] = 5] = "Critical";
    LogLevel[LogLevel["Off"] = 6] = "Off";
})(LogLevel || (LogLevel = {}));
const DEFAULT_LOG_LEVEL = LogLevel.Info;
class AbstractLogger extends Disposable {
    constructor() {
        super(...arguments);
        this.level = DEFAULT_LOG_LEVEL;
        this._onDidChangeLogLevel = this._register(new Emitter());
    }
    setLevel(level) {
        if (this.level !== level) {
            this.level = level;
            this._onDidChangeLogLevel.fire(this.level);
        }
    }
    getLevel() {
        return this.level;
    }
}
class ConsoleLogger extends AbstractLogger {
    constructor(logLevel = DEFAULT_LOG_LEVEL) {
        super();
        this.setLevel(logLevel);
    }
    trace(message, ...args) {
        if (this.getLevel() <= LogLevel.Trace) {
            console.log('%cTRACE', 'color: #888', message, ...args);
        }
    }
    debug(message, ...args) {
        if (this.getLevel() <= LogLevel.Debug) {
            console.log('%cDEBUG', 'background: #eee; color: #888', message, ...args);
        }
    }
    info(message, ...args) {
        if (this.getLevel() <= LogLevel.Info) {
            console.log('%c INFO', 'color: #33f', message, ...args);
        }
    }
    error(message, ...args) {
        if (this.getLevel() <= LogLevel.Error) {
            console.log('%c  ERR', 'color: #f33', message, ...args);
        }
    }
    dispose() {
        // noop
    }
}
class LogService extends Disposable {
    constructor(logger) {
        super();
        this.logger = logger;
        this._register(logger);
    }
    getLevel() {
        return this.logger.getLevel();
    }
    trace(message, ...args) {
        this.logger.trace(message, ...args);
    }
    debug(message, ...args) {
        this.logger.debug(message, ...args);
    }
    info(message, ...args) {
        this.logger.info(message, ...args);
    }
    error(message, ...args) {
        this.logger.error(message, ...args);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/editorExtensions.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/















class Command {
    constructor(opts) {
        this.id = opts.id;
        this.precondition = opts.precondition;
        this._kbOpts = opts.kbOpts;
        this._menuOpts = opts.menuOpts;
        this._description = opts.description;
    }
    register() {
        if (Array.isArray(this._menuOpts)) {
            this._menuOpts.forEach(this._registerMenuItem, this);
        }
        else if (this._menuOpts) {
            this._registerMenuItem(this._menuOpts);
        }
        if (this._kbOpts) {
            const kbOptsArr = Array.isArray(this._kbOpts) ? this._kbOpts : [this._kbOpts];
            for (const kbOpts of kbOptsArr) {
                let kbWhen = kbOpts.kbExpr;
                if (this.precondition) {
                    if (kbWhen) {
                        kbWhen = ContextKeyExpr.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,
                };
                KeybindingsRegistry.registerKeybindingRule(desc);
            }
        }
        CommandsRegistry.registerCommand({
            id: this.id,
            handler: (accessor, args) => this.runCommand(accessor, args),
            description: this._description
        });
    }
    _registerMenuItem(item) {
        MenuRegistry.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
        });
    }
}
class MultiCommand extends Command {
    constructor() {
        super(...arguments);
        this._implementations = [];
    }
    /**
     * A higher priority gets to be looked at first
     */
    addImplementation(priority, name, implementation) {
        this._implementations.push({ priority, name, implementation });
        this._implementations.sort((a, b) => b.priority - a.priority);
        return {
            dispose: () => {
                for (let i = 0; i < this._implementations.length; i++) {
                    if (this._implementations[i].implementation === implementation) {
                        this._implementations.splice(i, 1);
                        return;
                    }
                }
            }
        };
    }
    runCommand(accessor, args) {
        const logService = accessor.get(ILogService);
        logService.trace(`Executing Command '${this.id}' which has ${this._implementations.length} bound.`);
        for (const impl of this._implementations) {
            const result = impl.implementation(accessor, args);
            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.`);
    }
}
//#endregion
/**
 * A command that delegates to another command's implementation.
 *
 * This lets different commands be registered but share the same implementation
 */
class ProxyCommand extends Command {
    constructor(command, opts) {
        super(opts);
        this.command = command;
    }
    runCommand(accessor, args) {
        return this.command.runCommand(accessor, args);
    }
}
class EditorCommand extends Command {
    /**
     * Create a command class that is bound to a certain editor contribution.
     */
    static bindToContribution(controllerGetter) {
        return class EditorControllerCommandImpl extends EditorCommand {
            constructor(opts) {
                super(opts);
                this._callback = opts.handler;
            }
            runEditorCommand(accessor, editor, args) {
                const controller = controllerGetter(editor);
                if (controller) {
                    this._callback(controller, args);
                }
            }
        };
    }
    static runEditorCommand(accessor, args, precondition, runner) {
        const codeEditorService = accessor.get(ICodeEditorService);
        // Find the editor with text focus or active
        const editor = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
        if (!editor) {
            // well, at least we tried...
            return;
        }
        return editor.invokeWithinContext((editorAccessor) => {
            const kbService = editorAccessor.get(IContextKeyService);
            if (!kbService.contextMatchesRules(withNullAsUndefined(precondition))) {
                // precondition does not hold
                return;
            }
            return runner(editorAccessor, editor, args);
        });
    }
    runCommand(accessor, args) {
        return EditorCommand.runEditorCommand(accessor, args, this.precondition, (accessor, editor, args) => this.runEditorCommand(accessor, editor, args));
    }
}
class EditorAction extends EditorCommand {
    constructor(opts) {
        super(EditorAction.convertOptions(opts));
        this.label = opts.label;
        this.alias = opts.alias;
    }
    static convertOptions(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 = MenuId.EditorContext;
            }
            if (!item.title) {
                item.title = opts.label;
            }
            item.when = ContextKeyExpr.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;
    }
    runEditorCommand(accessor, editor, args) {
        this.reportTelemetry(accessor, editor);
        return this.run(accessor, editor, args || {});
    }
    reportTelemetry(accessor, editor) {
        accessor.get(ITelemetryService).publicLog2('editorActionInvoked', { name: this.label, id: this.id });
    }
}
class MultiEditorAction extends EditorAction {
    constructor() {
        super(...arguments);
        this._implementations = [];
    }
    /**
     * A higher priority gets to be looked at first
     */
    addImplementation(priority, implementation) {
        this._implementations.push([priority, implementation]);
        this._implementations.sort((a, b) => b[0] - a[0]);
        return {
            dispose: () => {
                for (let i = 0; i < this._implementations.length; i++) {
                    if (this._implementations[i][1] === implementation) {
                        this._implementations.splice(i, 1);
                        return;
                    }
                }
            }
        };
    }
    run(accessor, editor, args) {
        for (const impl of this._implementations) {
            const result = impl[1](accessor, editor, args);
            if (result) {
                if (typeof result === 'boolean') {
                    return;
                }
                return result;
            }
        }
    }
}
//#endregion
// --- Registration of commands and actions
function registerModelAndPositionCommand(id, handler) {
    CommandsRegistry.registerCommand(id, function (accessor, ...args) {
        const instaService = accessor.get(IInstantiationService);
        const [resource, position] = args;
        assertType(URI.isUri(resource));
        assertType(Position.isIPosition(position));
        const model = accessor.get(IModelService).getModel(resource);
        if (model) {
            const editorPosition = Position.lift(position);
            return instaService.invokeFunction(handler, model, editorPosition, ...args.slice(2));
        }
        return accessor.get(ITextModelService).createModelReference(resource).then(reference => {
            return new Promise((resolve, reject) => {
                try {
                    const result = instaService.invokeFunction(handler, reference.object.textEditorModel, Position.lift(position), args.slice(2));
                    resolve(result);
                }
                catch (err) {
                    reject(err);
                }
            }).finally(() => {
                reference.dispose();
            });
        });
    });
}
function registerEditorCommand(editorCommand) {
    EditorContributionRegistry.INSTANCE.registerEditorCommand(editorCommand);
    return editorCommand;
}
function registerEditorAction(ctor) {
    const action = new ctor();
    EditorContributionRegistry.INSTANCE.registerEditorAction(action);
    return action;
}
function registerMultiEditorAction(action) {
    EditorContributionRegistry.INSTANCE.registerEditorAction(action);
    return action;
}
function registerInstantiatedEditorAction(editorAction) {
    EditorContributionRegistry.INSTANCE.registerEditorAction(editorAction);
}
function registerEditorContribution(id, ctor) {
    EditorContributionRegistry.INSTANCE.registerEditorContribution(id, ctor);
}
var EditorExtensionsRegistry;
(function (EditorExtensionsRegistry) {
    function getEditorCommand(commandId) {
        return EditorContributionRegistry.INSTANCE.getEditorCommand(commandId);
    }
    EditorExtensionsRegistry.getEditorCommand = getEditorCommand;
    function getEditorActions() {
        return EditorContributionRegistry.INSTANCE.getEditorActions();
    }
    EditorExtensionsRegistry.getEditorActions = getEditorActions;
    function getEditorContributions() {
        return EditorContributionRegistry.INSTANCE.getEditorContributions();
    }
    EditorExtensionsRegistry.getEditorContributions = getEditorContributions;
    function getSomeEditorContributions(ids) {
        return EditorContributionRegistry.INSTANCE.getEditorContributions().filter(c => ids.indexOf(c.id) >= 0);
    }
    EditorExtensionsRegistry.getSomeEditorContributions = getSomeEditorContributions;
    function getDiffEditorContributions() {
        return EditorContributionRegistry.INSTANCE.getDiffEditorContributions();
    }
    EditorExtensionsRegistry.getDiffEditorContributions = getDiffEditorContributions;
})(EditorExtensionsRegistry || (EditorExtensionsRegistry = {}));
// Editor extension points
const editorExtensions_Extensions = {
    EditorCommonContributions: 'editor.contributions'
};
class EditorContributionRegistry {
    constructor() {
        this.editorContributions = [];
        this.diffEditorContributions = [];
        this.editorActions = [];
        this.editorCommands = Object.create(null);
    }
    registerEditorContribution(id, ctor) {
        this.editorContributions.push({ id, ctor: ctor });
    }
    getEditorContributions() {
        return this.editorContributions.slice(0);
    }
    getDiffEditorContributions() {
        return this.diffEditorContributions.slice(0);
    }
    registerEditorAction(action) {
        action.register();
        this.editorActions.push(action);
    }
    getEditorActions() {
        return this.editorActions.slice(0);
    }
    registerEditorCommand(editorCommand) {
        editorCommand.register();
        this.editorCommands[editorCommand.id] = editorCommand;
    }
    getEditorCommand(commandId) {
        return (this.editorCommands[commandId] || null);
    }
}
EditorContributionRegistry.INSTANCE = new EditorContributionRegistry();
Registry.add(editorExtensions_Extensions.EditorCommonContributions, EditorContributionRegistry.INSTANCE);
function registerCommand(command) {
    command.register();
    return command;
}
const UndoCommand = registerCommand(new MultiCommand({
    id: 'undo',
    precondition: undefined,
    kbOpts: {
        weight: 0 /* KeybindingWeight.EditorCore */,
        primary: 2048 /* KeyMod.CtrlCmd */ | 56 /* KeyCode.KeyZ */
    },
    menuOpts: [{
            menuId: MenuId.MenubarEditMenu,
            group: '1_do',
            title: localize({ key: 'miUndo', comment: ['&& denotes a mnemonic'] }, "&&Undo"),
            order: 1
        }, {
            menuId: MenuId.CommandPalette,
            group: '',
            title: localize('undo', "Undo"),
            order: 1
        }]
}));
registerCommand(new ProxyCommand(UndoCommand, { id: 'default:undo', precondition: undefined }));
const RedoCommand = registerCommand(new MultiCommand({
    id: 'redo',
    precondition: undefined,
    kbOpts: {
        weight: 0 /* KeybindingWeight.EditorCore */,
        primary: 2048 /* KeyMod.CtrlCmd */ | 55 /* KeyCode.KeyY */,
        secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 56 /* KeyCode.KeyZ */],
        mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 56 /* KeyCode.KeyZ */ }
    },
    menuOpts: [{
            menuId: MenuId.MenubarEditMenu,
            group: '1_do',
            title: localize({ key: 'miRedo', comment: ['&& denotes a mnemonic'] }, "&&Redo"),
            order: 2
        }, {
            menuId: MenuId.CommandPalette,
            group: '',
            title: localize('redo', "Redo"),
            order: 1
        }]
}));
registerCommand(new ProxyCommand(RedoCommand, { id: 'default:redo', precondition: undefined }));
const SelectAllCommand = registerCommand(new MultiCommand({
    id: 'editor.action.selectAll',
    precondition: undefined,
    kbOpts: {
        weight: 0 /* KeybindingWeight.EditorCore */,
        kbExpr: null,
        primary: 2048 /* KeyMod.CtrlCmd */ | 31 /* KeyCode.KeyA */
    },
    menuOpts: [{
            menuId: MenuId.MenubarSelectionMenu,
            group: '1_basic',
            title: localize({ key: 'miSelectAll', comment: ['&& denotes a mnemonic'] }, "&&Select All"),
            order: 1
        }, {
            menuId: MenuId.CommandPalette,
            group: '',
            title: localize('selectAll', "Select All"),
            order: 1
        }]
}));

;// ../../node_modules/monaco-editor/esm/vs/editor/common/editorContextKeys.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


var EditorContextKeys;
(function (EditorContextKeys) {
    EditorContextKeys.editorSimpleInput = new RawContextKey('editorSimpleInput', false, true);
    /**
     * A context key that is set when the editor's text has focus (cursor is blinking).
     * Is false when focus is in simple editor widgets (repl input, scm commit input).
     */
    EditorContextKeys.editorTextFocus = new RawContextKey('editorTextFocus', false, localize('editorTextFocus', "Whether the editor text has focus (cursor is blinking)"));
    /**
     * A context key that is set when the editor's text or an editor's widget has focus.
     */
    EditorContextKeys.focus = new RawContextKey('editorFocus', false, localize('editorFocus', "Whether the editor or an editor widget has focus (e.g. focus is in the find widget)"));
    /**
     * A context key that is set when any editor input has focus (regular editor, repl input...).
     */
    EditorContextKeys.textInputFocus = new RawContextKey('textInputFocus', false, localize('textInputFocus', "Whether an editor or a rich text input has focus (cursor is blinking)"));
    EditorContextKeys.readOnly = new RawContextKey('editorReadonly', false, localize('editorReadonly', "Whether the editor is read only"));
    EditorContextKeys.inDiffEditor = new RawContextKey('inDiffEditor', false, localize('inDiffEditor', "Whether the context is a diff editor"));
    EditorContextKeys.columnSelection = new RawContextKey('editorColumnSelection', false, localize('editorColumnSelection', "Whether `editor.columnSelection` is enabled"));
    EditorContextKeys.writable = EditorContextKeys.readOnly.toNegated();
    EditorContextKeys.hasNonEmptySelection = new RawContextKey('editorHasSelection', false, localize('editorHasSelection', "Whether the editor has text selected"));
    EditorContextKeys.hasOnlyEmptySelection = EditorContextKeys.hasNonEmptySelection.toNegated();
    EditorContextKeys.hasMultipleSelections = new RawContextKey('editorHasMultipleSelections', false, localize('editorHasMultipleSelections', "Whether the editor has multiple selections"));
    EditorContextKeys.hasSingleSelection = EditorContextKeys.hasMultipleSelections.toNegated();
    EditorContextKeys.tabMovesFocus = new RawContextKey('editorTabMovesFocus', false, localize('editorTabMovesFocus', "Whether `Tab` will move focus out of the editor"));
    EditorContextKeys.tabDoesNotMoveFocus = EditorContextKeys.tabMovesFocus.toNegated();
    EditorContextKeys.isInWalkThroughSnippet = new RawContextKey('isInEmbeddedEditor', false, true);
    EditorContextKeys.canUndo = new RawContextKey('canUndo', false, true);
    EditorContextKeys.canRedo = new RawContextKey('canRedo', false, true);
    EditorContextKeys.hoverVisible = new RawContextKey('editorHoverVisible', false, localize('editorHoverVisible', "Whether the editor hover is visible"));
    /**
     * A context key that is set when an editor is part of a larger editor, like notebooks or
     * (future) a diff editor
     */
    EditorContextKeys.inCompositeEditor = new RawContextKey('inCompositeEditor', undefined, localize('inCompositeEditor', "Whether the editor is part of a larger editor (e.g. notebooks)"));
    EditorContextKeys.notInCompositeEditor = EditorContextKeys.inCompositeEditor.toNegated();
    // -- mode context keys
    EditorContextKeys.languageId = new RawContextKey('editorLangId', '', localize('editorLangId', "The language identifier of the editor"));
    EditorContextKeys.hasCompletionItemProvider = new RawContextKey('editorHasCompletionItemProvider', false, localize('editorHasCompletionItemProvider', "Whether the editor has a completion item provider"));
    EditorContextKeys.hasCodeActionsProvider = new RawContextKey('editorHasCodeActionsProvider', false, localize('editorHasCodeActionsProvider', "Whether the editor has a code actions provider"));
    EditorContextKeys.hasCodeLensProvider = new RawContextKey('editorHasCodeLensProvider', false, localize('editorHasCodeLensProvider', "Whether the editor has a code lens provider"));
    EditorContextKeys.hasDefinitionProvider = new RawContextKey('editorHasDefinitionProvider', false, localize('editorHasDefinitionProvider', "Whether the editor has a definition provider"));
    EditorContextKeys.hasDeclarationProvider = new RawContextKey('editorHasDeclarationProvider', false, localize('editorHasDeclarationProvider', "Whether the editor has a declaration provider"));
    EditorContextKeys.hasImplementationProvider = new RawContextKey('editorHasImplementationProvider', false, localize('editorHasImplementationProvider', "Whether the editor has an implementation provider"));
    EditorContextKeys.hasTypeDefinitionProvider = new RawContextKey('editorHasTypeDefinitionProvider', false, localize('editorHasTypeDefinitionProvider', "Whether the editor has a type definition provider"));
    EditorContextKeys.hasHoverProvider = new RawContextKey('editorHasHoverProvider', false, localize('editorHasHoverProvider', "Whether the editor has a hover provider"));
    EditorContextKeys.hasDocumentHighlightProvider = new RawContextKey('editorHasDocumentHighlightProvider', false, localize('editorHasDocumentHighlightProvider', "Whether the editor has a document highlight provider"));
    EditorContextKeys.hasDocumentSymbolProvider = new RawContextKey('editorHasDocumentSymbolProvider', false, localize('editorHasDocumentSymbolProvider', "Whether the editor has a document symbol provider"));
    EditorContextKeys.hasReferenceProvider = new RawContextKey('editorHasReferenceProvider', false, localize('editorHasReferenceProvider', "Whether the editor has a reference provider"));
    EditorContextKeys.hasRenameProvider = new RawContextKey('editorHasRenameProvider', false, localize('editorHasRenameProvider', "Whether the editor has a rename provider"));
    EditorContextKeys.hasSignatureHelpProvider = new RawContextKey('editorHasSignatureHelpProvider', false, localize('editorHasSignatureHelpProvider', "Whether the editor has a signature help provider"));
    EditorContextKeys.hasInlayHintsProvider = new RawContextKey('editorHasInlayHintsProvider', false, localize('editorHasInlayHintsProvider', "Whether the editor has an inline hints provider"));
    // -- mode context keys: formatting
    EditorContextKeys.hasDocumentFormattingProvider = new RawContextKey('editorHasDocumentFormattingProvider', false, localize('editorHasDocumentFormattingProvider', "Whether the editor has a document formatting provider"));
    EditorContextKeys.hasDocumentSelectionFormattingProvider = new RawContextKey('editorHasDocumentSelectionFormattingProvider', false, localize('editorHasDocumentSelectionFormattingProvider', "Whether the editor has a document selection formatting provider"));
    EditorContextKeys.hasMultipleDocumentFormattingProvider = new RawContextKey('editorHasMultipleDocumentFormattingProvider', false, localize('editorHasMultipleDocumentFormattingProvider', "Whether the editor has multiple document formatting providers"));
    EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider = new RawContextKey('editorHasMultipleDocumentSelectionFormattingProvider', false, localize('editorHasMultipleDocumentSelectionFormattingProvider', "Whether the editor has multiple document selection formatting providers"));
})(EditorContextKeys || (EditorContextKeys = {}));

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/config/tabFocus.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class TabFocusImpl {
    constructor() {
        this._tabFocus = false;
        this._onDidChangeTabFocus = new Emitter();
        this.onDidChangeTabFocus = this._onDidChangeTabFocus.event;
    }
    getTabFocusMode() {
        return this._tabFocus;
    }
    setTabFocusMode(tabFocusMode) {
        if (this._tabFocus === tabFocusMode) {
            return;
        }
        this._tabFocus = tabFocusMode;
        this._onDidChangeTabFocus.fire(this._tabFocus);
    }
}
/**
 * Control what pressing Tab does.
 * If it is false, pressing Tab or Shift-Tab will be handled by the editor.
 * If it is true, pressing Tab or Shift-Tab will move the browser focus.
 * Defaults to false.
 */
const TabFocus = new TabFocusImpl();

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/toggleTabFocusMode/browser/toggleTabFocusMode.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class ToggleTabFocusModeAction extends EditorAction {
    constructor() {
        super({
            id: ToggleTabFocusModeAction.ID,
            label: localize({ key: 'toggle.tabMovesFocus', comment: ['Turn on/off use of tab key for moving focus around VS Code'] }, "Toggle Tab Key Moves Focus"),
            alias: 'Toggle Tab Key Moves Focus',
            precondition: undefined,
            kbOpts: {
                kbExpr: null,
                primary: 2048 /* KeyMod.CtrlCmd */ | 43 /* KeyCode.KeyM */,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 43 /* KeyCode.KeyM */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        const oldValue = TabFocus.getTabFocusMode();
        const newValue = !oldValue;
        TabFocus.setTabFocusMode(newValue);
        if (newValue) {
            aria_alert(localize('toggle.tabMovesFocus.on', "Pressing Tab will now move focus to the next focusable element"));
        }
        else {
            aria_alert(localize('toggle.tabMovesFocus.off', "Pressing Tab will now insert the tab character"));
        }
    }
}
ToggleTabFocusModeAction.ID = 'editor.action.toggleTabFocusMode';
registerEditorAction(ToggleTabFocusModeAction);

;// ../../node_modules/monaco-editor/esm/vs/platform/keybinding/common/keybinding.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const IKeybindingService = createDecorator('keybindingService');

;// ../../node_modules/monaco-editor/esm/vs/platform/opener/common/opener.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var opener_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};




const IOpenerService = createDecorator('openerService');
const NullOpenerService = Object.freeze({
    _serviceBrand: undefined,
    registerOpener() { return Disposable.None; },
    registerValidator() { return Disposable.None; },
    registerExternalUriResolver() { return Disposable.None; },
    setDefaultExternalOpener() { },
    registerExternalOpener() { return Disposable.None; },
    open() {
        return opener_awaiter(this, void 0, void 0, function* () { return false; });
    },
    resolveExternalUri(uri) {
        return opener_awaiter(this, void 0, void 0, function* () { return { resolved: uri, dispose() { } }; });
    },
});
function matchesScheme(target, scheme) {
    if (URI.isUri(target)) {
        return equalsIgnoreCase(target.scheme, scheme);
    }
    else {
        return startsWithIgnoreCase(target, scheme + ':');
    }
}
function matchesSomeScheme(target, ...schemes) {
    return schemes.some(scheme => matchesScheme(target, scheme));
}
/**
 * file:///some/file.js#73
 * file:///some/file.js#L73
 * file:///some/file.js#73,84
 * file:///some/file.js#L73,84
 * file:///some/file.js#73-83
 * file:///some/file.js#L73-L83
 * file:///some/file.js#73,84-83,52
 * file:///some/file.js#L73,84-L83,52
 */
function extractSelection(uri) {
    let selection = undefined;
    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]) : undefined,
            endColumn: match[4] ? (match[5] ? parseInt(match[5]) : 1) : undefined
        };
        uri = uri.with({ fragment: '' });
    }
    return { selection, uri };
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/cancellation.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const shortcutEvent = Object.freeze(function (callback, context) {
    const handle = setTimeout(callback.bind(context), 0);
    return { dispose() { clearTimeout(handle); } };
});
var CancellationToken;
(function (CancellationToken) {
    function isCancellationToken(thing) {
        if (thing === CancellationToken.None || thing === CancellationToken.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';
    }
    CancellationToken.isCancellationToken = isCancellationToken;
    CancellationToken.None = Object.freeze({
        isCancellationRequested: false,
        onCancellationRequested: Event.None
    });
    CancellationToken.Cancelled = Object.freeze({
        isCancellationRequested: true,
        onCancellationRequested: shortcutEvent
    });
})(CancellationToken || (CancellationToken = {}));
class MutableToken {
    constructor() {
        this._isCancelled = false;
        this._emitter = null;
    }
    cancel() {
        if (!this._isCancelled) {
            this._isCancelled = true;
            if (this._emitter) {
                this._emitter.fire(undefined);
                this.dispose();
            }
        }
    }
    get isCancellationRequested() {
        return this._isCancelled;
    }
    get onCancellationRequested() {
        if (this._isCancelled) {
            return shortcutEvent;
        }
        if (!this._emitter) {
            this._emitter = new Emitter();
        }
        return this._emitter.event;
    }
    dispose() {
        if (this._emitter) {
            this._emitter.dispose();
            this._emitter = null;
        }
    }
}
class CancellationTokenSource {
    constructor(parent) {
        this._token = undefined;
        this._parentListener = undefined;
        this._parentListener = parent && parent.onCancellationRequested(this.cancel, this);
    }
    get token() {
        if (!this._token) {
            // be lazy and create the token only when
            // actually needed
            this._token = new MutableToken();
        }
        return this._token;
    }
    cancel() {
        if (!this._token) {
            // save an object by returning the default
            // cancelled token when cancellation happens
            // before someone asks for the token
            this._token = CancellationToken.Cancelled;
        }
        else if (this._token instanceof MutableToken) {
            // actually cancel
            this._token.cancel();
        }
    }
    dispose(cancel = false) {
        if (cancel) {
            this.cancel();
        }
        if (this._parentListener) {
            this._parentListener.dispose();
        }
        if (!this._token) {
            // ensure to initialize with an empty token if we had none
            this._token = CancellationToken.None;
        }
        else if (this._token instanceof MutableToken) {
            // actually dispose
            this._token.dispose();
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/async.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var async_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
var __asyncValues = (undefined && undefined.__asyncValues) || function (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); }
};





function isThenable(obj) {
    return !!obj && typeof obj.then === 'function';
}
function createCancelablePromise(callback) {
    const source = new CancellationTokenSource();
    const thenable = callback(source.token);
    const promise = new Promise((resolve, reject) => {
        const subscription = source.token.onCancellationRequested(() => {
            subscription.dispose();
            source.dispose();
            reject(new CancellationError());
        });
        Promise.resolve(thenable).then(value => {
            subscription.dispose();
            source.dispose();
            resolve(value);
        }, err => {
            subscription.dispose();
            source.dispose();
            reject(err);
        });
    });
    return new class {
        cancel() {
            source.cancel();
        }
        then(resolve, reject) {
            return promise.then(resolve, reject);
        }
        catch(reject) {
            return this.then(undefined, reject);
        }
        finally(onfinally) {
            return promise.finally(onfinally);
        }
    };
}
function raceCancellation(promise, token, defaultValue) {
    return new Promise((resolve, reject) => {
        const ref = token.onCancellationRequested(() => {
            ref.dispose();
            resolve(defaultValue);
        });
        promise.then(resolve, reject).finally(() => ref.dispose());
    });
}
/**
 * A helper to prevent accumulation of sequential async tasks.
 *
 * Imagine a mail man with the sole task of delivering letters. As soon as
 * a letter submitted for delivery, he drives to the destination, delivers it
 * and returns to his base. Imagine that during the trip, N more letters were submitted.
 * When the mail man returns, he picks those N letters and delivers them all in a
 * single trip. Even though N+1 submissions occurred, only 2 deliveries were made.
 *
 * The throttler implements this via the queue() method, by providing it a task
 * factory. Following the example:
 *
 * 		const throttler = new Throttler();
 * 		const letters = [];
 *
 * 		function deliver() {
 * 			const lettersToDeliver = letters;
 * 			letters = [];
 * 			return makeTheTrip(lettersToDeliver);
 * 		}
 *
 * 		function onLetterReceived(l) {
 * 			letters.push(l);
 * 			throttler.queue(deliver);
 * 		}
 */
class Throttler {
    constructor() {
        this.activePromise = null;
        this.queuedPromise = null;
        this.queuedPromiseFactory = null;
    }
    queue(promiseFactory) {
        if (this.activePromise) {
            this.queuedPromiseFactory = promiseFactory;
            if (!this.queuedPromise) {
                const onComplete = () => {
                    this.queuedPromise = null;
                    const result = this.queue(this.queuedPromiseFactory);
                    this.queuedPromiseFactory = null;
                    return result;
                };
                this.queuedPromise = new Promise(resolve => {
                    this.activePromise.then(onComplete, onComplete).then(resolve);
                });
            }
            return new Promise((resolve, reject) => {
                this.queuedPromise.then(resolve, reject);
            });
        }
        this.activePromise = promiseFactory();
        return new Promise((resolve, reject) => {
            this.activePromise.then((result) => {
                this.activePromise = null;
                resolve(result);
            }, (err) => {
                this.activePromise = null;
                reject(err);
            });
        });
    }
}
const timeoutDeferred = (timeout, fn) => {
    let scheduled = true;
    const handle = setTimeout(() => {
        scheduled = false;
        fn();
    }, timeout);
    return {
        isTriggered: () => scheduled,
        dispose: () => {
            clearTimeout(handle);
            scheduled = false;
        },
    };
};
const microtaskDeferred = (fn) => {
    let scheduled = true;
    queueMicrotask(() => {
        if (scheduled) {
            scheduled = false;
            fn();
        }
    });
    return {
        isTriggered: () => scheduled,
        dispose: () => { scheduled = false; },
    };
};
/** Can be passed into the Delayed to defer using a microtask */
const MicrotaskDelay = Symbol('MicrotaskDelay');
/**
 * A helper to delay (debounce) execution of a task that is being requested often.
 *
 * Following the throttler, now imagine the mail man wants to optimize the number of
 * trips proactively. The trip itself can be long, so he decides not to make the trip
 * as soon as a letter is submitted. Instead he waits a while, in case more
 * letters are submitted. After said waiting period, if no letters were submitted, he
 * decides to make the trip. Imagine that N more letters were submitted after the first
 * one, all within a short period of time between each other. Even though N+1
 * submissions occurred, only 1 delivery was made.
 *
 * The delayer offers this behavior via the trigger() method, into which both the task
 * to be executed and the waiting period (delay) must be passed in as arguments. Following
 * the example:
 *
 * 		const delayer = new Delayer(WAITING_PERIOD);
 * 		const letters = [];
 *
 * 		function letterReceived(l) {
 * 			letters.push(l);
 * 			delayer.trigger(() => { return makeTheTrip(); });
 * 		}
 */
class Delayer {
    constructor(defaultDelay) {
        this.defaultDelay = defaultDelay;
        this.deferred = null;
        this.completionPromise = null;
        this.doResolve = null;
        this.doReject = null;
        this.task = null;
    }
    trigger(task, delay = this.defaultDelay) {
        this.task = task;
        this.cancelTimeout();
        if (!this.completionPromise) {
            this.completionPromise = new Promise((resolve, reject) => {
                this.doResolve = resolve;
                this.doReject = reject;
            }).then(() => {
                this.completionPromise = null;
                this.doResolve = null;
                if (this.task) {
                    const task = this.task;
                    this.task = null;
                    return task();
                }
                return undefined;
            });
        }
        const fn = () => {
            var _a;
            this.deferred = null;
            (_a = this.doResolve) === null || _a === void 0 ? void 0 : _a.call(this, null);
        };
        this.deferred = delay === MicrotaskDelay ? microtaskDeferred(fn) : timeoutDeferred(delay, fn);
        return this.completionPromise;
    }
    isTriggered() {
        var _a;
        return !!((_a = this.deferred) === null || _a === void 0 ? void 0 : _a.isTriggered());
    }
    cancel() {
        var _a;
        this.cancelTimeout();
        if (this.completionPromise) {
            (_a = this.doReject) === null || _a === void 0 ? void 0 : _a.call(this, new CancellationError());
            this.completionPromise = null;
        }
    }
    cancelTimeout() {
        var _a;
        (_a = this.deferred) === null || _a === void 0 ? void 0 : _a.dispose();
        this.deferred = null;
    }
    dispose() {
        this.cancel();
    }
}
/**
 * A helper to delay execution of a task that is being requested often, while
 * preventing accumulation of consecutive executions, while the task runs.
 *
 * The mail man is clever and waits for a certain amount of time, before going
 * out to deliver letters. While the mail man is going out, more letters arrive
 * and can only be delivered once he is back. Once he is back the mail man will
 * do one more trip to deliver the letters that have accumulated while he was out.
 */
class ThrottledDelayer {
    constructor(defaultDelay) {
        this.delayer = new Delayer(defaultDelay);
        this.throttler = new Throttler();
    }
    trigger(promiseFactory, delay) {
        return this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay);
    }
    dispose() {
        this.delayer.dispose();
    }
}
function timeout(millis, token) {
    if (!token) {
        return createCancelablePromise(token => timeout(millis, token));
    }
    return new Promise((resolve, reject) => {
        const handle = setTimeout(() => {
            disposable.dispose();
            resolve();
        }, millis);
        const disposable = token.onCancellationRequested(() => {
            clearTimeout(handle);
            disposable.dispose();
            reject(new CancellationError());
        });
    });
}
function disposableTimeout(handler, timeout = 0) {
    const timer = setTimeout(handler, timeout);
    return toDisposable(() => clearTimeout(timer));
}
function first(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();
}
class TimeoutTimer {
    constructor(runner, timeout) {
        this._token = -1;
        if (typeof runner === 'function' && typeof timeout === 'number') {
            this.setIfNotSet(runner, timeout);
        }
    }
    dispose() {
        this.cancel();
    }
    cancel() {
        if (this._token !== -1) {
            clearTimeout(this._token);
            this._token = -1;
        }
    }
    cancelAndSet(runner, timeout) {
        this.cancel();
        this._token = setTimeout(() => {
            this._token = -1;
            runner();
        }, timeout);
    }
    setIfNotSet(runner, timeout) {
        if (this._token !== -1) {
            // timer is already set
            return;
        }
        this._token = setTimeout(() => {
            this._token = -1;
            runner();
        }, timeout);
    }
}
class IntervalTimer {
    constructor() {
        this._token = -1;
    }
    dispose() {
        this.cancel();
    }
    cancel() {
        if (this._token !== -1) {
            clearInterval(this._token);
            this._token = -1;
        }
    }
    cancelAndSet(runner, interval) {
        this.cancel();
        this._token = setInterval(() => {
            runner();
        }, interval);
    }
}
class RunOnceScheduler {
    constructor(runner, delay) {
        this.timeoutToken = -1;
        this.runner = runner;
        this.timeout = delay;
        this.timeoutHandler = this.onTimeout.bind(this);
    }
    /**
     * Dispose RunOnceScheduler
     */
    dispose() {
        this.cancel();
        this.runner = null;
    }
    /**
     * Cancel current scheduled runner (if any).
     */
    cancel() {
        if (this.isScheduled()) {
            clearTimeout(this.timeoutToken);
            this.timeoutToken = -1;
        }
    }
    /**
     * Cancel previous runner (if any) & schedule a new runner.
     */
    schedule(delay = this.timeout) {
        this.cancel();
        this.timeoutToken = setTimeout(this.timeoutHandler, delay);
    }
    get delay() {
        return this.timeout;
    }
    set delay(value) {
        this.timeout = value;
    }
    /**
     * Returns true if scheduled.
     */
    isScheduled() {
        return this.timeoutToken !== -1;
    }
    onTimeout() {
        this.timeoutToken = -1;
        if (this.runner) {
            this.doRun();
        }
    }
    doRun() {
        var _a;
        (_a = this.runner) === null || _a === void 0 ? void 0 : _a.call(this);
    }
}
/**
 * Execute the callback the next time the browser is idle
 */
let runWhenIdle;
(function () {
    if (typeof requestIdleCallback !== 'function' || typeof cancelIdleCallback !== 'function') {
        runWhenIdle = (runner) => {
            setTimeout0(() => {
                if (disposed) {
                    return;
                }
                const end = Date.now() + 15; // one frame at 64fps
                runner(Object.freeze({
                    didTimeout: true,
                    timeRemaining() {
                        return Math.max(0, end - Date.now());
                    }
                }));
            });
            let disposed = false;
            return {
                dispose() {
                    if (disposed) {
                        return;
                    }
                    disposed = true;
                }
            };
        };
    }
    else {
        runWhenIdle = (runner, timeout) => {
            const handle = requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined);
            let disposed = false;
            return {
                dispose() {
                    if (disposed) {
                        return;
                    }
                    disposed = true;
                    cancelIdleCallback(handle);
                }
            };
        };
    }
})();
/**
 * An implementation of the "idle-until-urgent"-strategy as introduced
 * here: https://philipwalton.com/articles/idle-until-urgent/
 */
class IdleValue {
    constructor(executor) {
        this._didRun = false;
        this._executor = () => {
            try {
                this._value = executor();
            }
            catch (err) {
                this._error = err;
            }
            finally {
                this._didRun = true;
            }
        };
        this._handle = runWhenIdle(() => this._executor());
    }
    dispose() {
        this._handle.dispose();
    }
    get value() {
        if (!this._didRun) {
            this._handle.dispose();
            this._executor();
        }
        if (this._error) {
            throw this._error;
        }
        return this._value;
    }
    get isInitialized() {
        return this._didRun;
    }
}
/**
 * Creates a promise whose resolution or rejection can be controlled imperatively.
 */
class DeferredPromise {
    constructor() {
        this.rejected = false;
        this.resolved = false;
        this.p = new Promise((c, e) => {
            this.completeCallback = c;
            this.errorCallback = e;
        });
    }
    get isRejected() {
        return this.rejected;
    }
    get isSettled() {
        return this.rejected || this.resolved;
    }
    complete(value) {
        return new Promise(resolve => {
            this.completeCallback(value);
            this.resolved = true;
            resolve();
        });
    }
    cancel() {
        new Promise(resolve => {
            this.errorCallback(new CancellationError());
            this.rejected = true;
            resolve();
        });
    }
}
//#endregion
//#region Promises
var Promises;
(function (Promises) {
    /**
     * A drop-in replacement for `Promise.all` with the only difference
     * that the method awaits every promise to either fulfill or reject.
     *
     * Similar to `Promise.all`, only the first error will be returned
     * if any.
     */
    function settled(promises) {
        return async_awaiter(this, void 0, void 0, function* () {
            let firstError = undefined;
            const result = yield Promise.all(promises.map(promise => promise.then(value => value, error => {
                if (!firstError) {
                    firstError = error;
                }
                return undefined; // do not rethrow so that other promises can settle
            })));
            if (typeof firstError !== 'undefined') {
                throw firstError;
            }
            return result; // cast is needed and protected by the `throw` above
        });
    }
    Promises.settled = settled;
    /**
     * A helper to create a new `Promise<T>` with a body that is a promise
     * itself. By default, an error that raises from the async body will
     * end up as a unhandled rejection, so this utility properly awaits the
     * body and rejects the promise as a normal promise does without async
     * body.
     *
     * This method should only be used in rare cases where otherwise `async`
     * cannot be used (e.g. when callbacks are involved that require this).
     */
    function withAsyncBody(bodyFn) {
        // eslint-disable-next-line no-async-promise-executor
        return new Promise((resolve, reject) => async_awaiter(this, void 0, void 0, function* () {
            try {
                yield bodyFn(resolve, reject);
            }
            catch (error) {
                reject(error);
            }
        }));
    }
    Promises.withAsyncBody = withAsyncBody;
})(Promises || (Promises = {}));
/**
 * A rich implementation for an `AsyncIterable<T>`.
 */
class AsyncIterableObject {
    constructor(executor) {
        this._state = 0 /* AsyncIterableSourceState.Initial */;
        this._results = [];
        this._error = null;
        this._onStateChanged = new Emitter();
        queueMicrotask(() => async_awaiter(this, void 0, void 0, function* () {
            const writer = {
                emitOne: (item) => this.emitOne(item),
                emitMany: (items) => this.emitMany(items),
                reject: (error) => this.reject(error)
            };
            try {
                yield Promise.resolve(executor(writer));
                this.resolve();
            }
            catch (err) {
                this.reject(err);
            }
            finally {
                writer.emitOne = undefined;
                writer.emitMany = undefined;
                writer.reject = undefined;
            }
        }));
    }
    static fromArray(items) {
        return new AsyncIterableObject((writer) => {
            writer.emitMany(items);
        });
    }
    static fromPromise(promise) {
        return new AsyncIterableObject((emitter) => async_awaiter(this, void 0, void 0, function* () {
            emitter.emitMany(yield promise);
        }));
    }
    static fromPromises(promises) {
        return new AsyncIterableObject((emitter) => async_awaiter(this, void 0, void 0, function* () {
            yield Promise.all(promises.map((p) => async_awaiter(this, void 0, void 0, function* () { return emitter.emitOne(yield p); })));
        }));
    }
    static merge(iterables) {
        return new AsyncIterableObject((emitter) => async_awaiter(this, void 0, void 0, function* () {
            yield Promise.all(iterables.map((iterable) => { var iterable_1, iterable_1_1; return async_awaiter(this, void 0, void 0, function* () {
                var e_1, _a;
                try {
                    for (iterable_1 = __asyncValues(iterable); iterable_1_1 = yield iterable_1.next(), !iterable_1_1.done;) {
                        const item = iterable_1_1.value;
                        emitter.emitOne(item);
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) yield _a.call(iterable_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            }); }));
        }));
    }
    [Symbol.asyncIterator]() {
        let i = 0;
        return {
            next: () => async_awaiter(this, void 0, void 0, function* () {
                do {
                    if (this._state === 2 /* AsyncIterableSourceState.DoneError */) {
                        throw this._error;
                    }
                    if (i < this._results.length) {
                        return { done: false, value: this._results[i++] };
                    }
                    if (this._state === 1 /* AsyncIterableSourceState.DoneOK */) {
                        return { done: true, value: undefined };
                    }
                    yield Event.toPromise(this._onStateChanged.event);
                } while (true);
            })
        };
    }
    static map(iterable, mapFn) {
        return new AsyncIterableObject((emitter) => async_awaiter(this, void 0, void 0, function* () {
            var e_2, _a;
            try {
                for (var iterable_2 = __asyncValues(iterable), iterable_2_1; iterable_2_1 = yield iterable_2.next(), !iterable_2_1.done;) {
                    const item = iterable_2_1.value;
                    emitter.emitOne(mapFn(item));
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (iterable_2_1 && !iterable_2_1.done && (_a = iterable_2.return)) yield _a.call(iterable_2);
                }
                finally { if (e_2) throw e_2.error; }
            }
        }));
    }
    map(mapFn) {
        return AsyncIterableObject.map(this, mapFn);
    }
    static filter(iterable, filterFn) {
        return new AsyncIterableObject((emitter) => async_awaiter(this, void 0, void 0, function* () {
            var e_3, _a;
            try {
                for (var iterable_3 = __asyncValues(iterable), iterable_3_1; iterable_3_1 = yield iterable_3.next(), !iterable_3_1.done;) {
                    const item = iterable_3_1.value;
                    if (filterFn(item)) {
                        emitter.emitOne(item);
                    }
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (iterable_3_1 && !iterable_3_1.done && (_a = iterable_3.return)) yield _a.call(iterable_3);
                }
                finally { if (e_3) throw e_3.error; }
            }
        }));
    }
    filter(filterFn) {
        return AsyncIterableObject.filter(this, filterFn);
    }
    static coalesce(iterable) {
        return AsyncIterableObject.filter(iterable, item => !!item);
    }
    coalesce() {
        return AsyncIterableObject.coalesce(this);
    }
    static toPromise(iterable) {
        var iterable_4, iterable_4_1;
        var e_4, _a;
        return async_awaiter(this, void 0, void 0, function* () {
            const result = [];
            try {
                for (iterable_4 = __asyncValues(iterable); iterable_4_1 = yield iterable_4.next(), !iterable_4_1.done;) {
                    const item = iterable_4_1.value;
                    result.push(item);
                }
            }
            catch (e_4_1) { e_4 = { error: e_4_1 }; }
            finally {
                try {
                    if (iterable_4_1 && !iterable_4_1.done && (_a = iterable_4.return)) yield _a.call(iterable_4);
                }
                finally { if (e_4) throw e_4.error; }
            }
            return result;
        });
    }
    toPromise() {
        return AsyncIterableObject.toPromise(this);
    }
    /**
     * The value will be appended at the end.
     *
     * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
     */
    emitOne(value) {
        if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
            return;
        }
        // it is important to add new values at the end,
        // as we may have iterators already running on the array
        this._results.push(value);
        this._onStateChanged.fire();
    }
    /**
     * The values will be appended at the end.
     *
     * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
     */
    emitMany(values) {
        if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
            return;
        }
        // it is important to add new values at the end,
        // as we may have iterators already running on the array
        this._results = this._results.concat(values);
        this._onStateChanged.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.
     */
    resolve() {
        if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
            return;
        }
        this._state = 1 /* AsyncIterableSourceState.DoneOK */;
        this._onStateChanged.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.
     */
    reject(error) {
        if (this._state !== 0 /* AsyncIterableSourceState.Initial */) {
            return;
        }
        this._state = 2 /* AsyncIterableSourceState.DoneError */;
        this._error = error;
        this._onStateChanged.fire();
    }
}
AsyncIterableObject.EMPTY = AsyncIterableObject.fromArray([]);
class CancelableAsyncIterableObject extends AsyncIterableObject {
    constructor(_source, executor) {
        super(executor);
        this._source = _source;
    }
    cancel() {
        this._source.cancel();
    }
}
function createCancelableAsyncIterable(callback) {
    const source = new CancellationTokenSource();
    const innerIterable = callback(source.token);
    return new CancelableAsyncIterableObject(source, (emitter) => async_awaiter(this, void 0, void 0, function* () {
        var e_5, _a;
        const subscription = source.token.onCancellationRequested(() => {
            subscription.dispose();
            source.dispose();
            emitter.reject(new CancellationError());
        });
        try {
            try {
                for (var innerIterable_1 = __asyncValues(innerIterable), innerIterable_1_1; innerIterable_1_1 = yield innerIterable_1.next(), !innerIterable_1_1.done;) {
                    const item = innerIterable_1_1.value;
                    if (source.token.isCancellationRequested) {
                        // canceled in the meantime
                        return;
                    }
                    emitter.emitOne(item);
                }
            }
            catch (e_5_1) { e_5 = { error: e_5_1 }; }
            finally {
                try {
                    if (innerIterable_1_1 && !innerIterable_1_1.done && (_a = innerIterable_1.return)) yield _a.call(innerIterable_1);
                }
                finally { if (e_5) throw e_5.error; }
            }
            subscription.dispose();
            source.dispose();
        }
        catch (err) {
            subscription.dispose();
            source.dispose();
            emitter.reject(err);
        }
    }));
}
//#endregion

;// ../../node_modules/monaco-editor/esm/vs/base/common/color.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
function roundFloat(number, decimalPoints) {
    const decimal = Math.pow(10, decimalPoints);
    return Math.round(number * decimal) / decimal;
}
class RGBA {
    constructor(r, g, b, a = 1) {
        this._rgbaBrand = undefined;
        this.r = Math.min(255, Math.max(0, r)) | 0;
        this.g = Math.min(255, Math.max(0, g)) | 0;
        this.b = Math.min(255, Math.max(0, b)) | 0;
        this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
    }
    static equals(a, b) {
        return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
    }
}
class HSLA {
    constructor(h, s, l, a) {
        this._hslaBrand = undefined;
        this.h = Math.max(Math.min(360, h), 0) | 0;
        this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
        this.l = roundFloat(Math.max(Math.min(1, l), 0), 3);
        this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
    }
    static equals(a, b) {
        return a.h === b.h && a.s === b.s && a.l === b.l && a.a === b.a;
    }
    /**
     * Converts an RGB color value to HSL. Conversion formula
     * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
     * Assumes r, g, and b are contained in the set [0, 255] and
     * returns h in the set [0, 360], s, and l in the set [0, 1].
     */
    static fromRGBA(rgba) {
        const r = rgba.r / 255;
        const g = rgba.g / 255;
        const b = rgba.b / 255;
        const a = rgba.a;
        const max = Math.max(r, g, b);
        const min = Math.min(r, g, b);
        let h = 0;
        let s = 0;
        const l = (min + max) / 2;
        const chroma = max - min;
        if (chroma > 0) {
            s = Math.min((l <= 0.5 ? chroma / (2 * l) : chroma / (2 - (2 * l))), 1);
            switch (max) {
                case r:
                    h = (g - b) / chroma + (g < b ? 6 : 0);
                    break;
                case g:
                    h = (b - r) / chroma + 2;
                    break;
                case b:
                    h = (r - g) / chroma + 4;
                    break;
            }
            h *= 60;
            h = Math.round(h);
        }
        return new HSLA(h, s, l, a);
    }
    static _hue2rgb(p, q, t) {
        if (t < 0) {
            t += 1;
        }
        if (t > 1) {
            t -= 1;
        }
        if (t < 1 / 6) {
            return p + (q - p) * 6 * t;
        }
        if (t < 1 / 2) {
            return q;
        }
        if (t < 2 / 3) {
            return p + (q - p) * (2 / 3 - t) * 6;
        }
        return p;
    }
    /**
     * Converts an HSL color value to RGB. Conversion formula
     * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
     * Assumes h in the set [0, 360] s, and l are contained in the set [0, 1] and
     * returns r, g, and b in the set [0, 255].
     */
    static toRGBA(hsla) {
        const h = hsla.h / 360;
        const { s, l, a } = hsla;
        let r, g, b;
        if (s === 0) {
            r = g = b = l; // achromatic
        }
        else {
            const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            const p = 2 * l - q;
            r = HSLA._hue2rgb(p, q, h + 1 / 3);
            g = HSLA._hue2rgb(p, q, h);
            b = HSLA._hue2rgb(p, q, h - 1 / 3);
        }
        return new RGBA(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
    }
}
class HSVA {
    constructor(h, s, v, a) {
        this._hsvaBrand = undefined;
        this.h = Math.max(Math.min(360, h), 0) | 0;
        this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
        this.v = roundFloat(Math.max(Math.min(1, v), 0), 3);
        this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
    }
    static equals(a, b) {
        return a.h === b.h && a.s === b.s && a.v === b.v && a.a === b.a;
    }
    // from http://www.rapidtables.com/convert/color/rgb-to-hsv.htm
    static fromRGBA(rgba) {
        const r = rgba.r / 255;
        const g = rgba.g / 255;
        const b = rgba.b / 255;
        const cmax = Math.max(r, g, b);
        const cmin = Math.min(r, g, b);
        const delta = cmax - cmin;
        const s = cmax === 0 ? 0 : (delta / cmax);
        let m;
        if (delta === 0) {
            m = 0;
        }
        else if (cmax === r) {
            m = ((((g - b) / delta) % 6) + 6) % 6;
        }
        else if (cmax === g) {
            m = ((b - r) / delta) + 2;
        }
        else {
            m = ((r - g) / delta) + 4;
        }
        return new HSVA(Math.round(m * 60), s, cmax, rgba.a);
    }
    // from http://www.rapidtables.com/convert/color/hsv-to-rgb.htm
    static toRGBA(hsva) {
        const { h, s, v, a } = hsva;
        const c = v * s;
        const x = c * (1 - Math.abs((h / 60) % 2 - 1));
        const m = v - c;
        let [r, g, b] = [0, 0, 0];
        if (h < 60) {
            r = c;
            g = x;
        }
        else if (h < 120) {
            r = x;
            g = c;
        }
        else if (h < 180) {
            g = c;
            b = x;
        }
        else if (h < 240) {
            g = x;
            b = c;
        }
        else if (h < 300) {
            r = x;
            b = c;
        }
        else if (h <= 360) {
            r = c;
            b = x;
        }
        r = Math.round((r + m) * 255);
        g = Math.round((g + m) * 255);
        b = Math.round((b + m) * 255);
        return new RGBA(r, g, b, a);
    }
}
class Color {
    constructor(arg) {
        if (!arg) {
            throw new Error('Color needs a value');
        }
        else if (arg instanceof RGBA) {
            this.rgba = arg;
        }
        else if (arg instanceof HSLA) {
            this._hsla = arg;
            this.rgba = HSLA.toRGBA(arg);
        }
        else if (arg instanceof HSVA) {
            this._hsva = arg;
            this.rgba = HSVA.toRGBA(arg);
        }
        else {
            throw new Error('Invalid color ctor argument');
        }
    }
    static fromHex(hex) {
        return Color.Format.CSS.parseHex(hex) || Color.red;
    }
    get hsla() {
        if (this._hsla) {
            return this._hsla;
        }
        else {
            return HSLA.fromRGBA(this.rgba);
        }
    }
    get hsva() {
        if (this._hsva) {
            return this._hsva;
        }
        return HSVA.fromRGBA(this.rgba);
    }
    equals(other) {
        return !!other && RGBA.equals(this.rgba, other.rgba) && HSLA.equals(this.hsla, other.hsla) && HSVA.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 = Color._relativeLuminanceForComponent(this.rgba.r);
        const G = Color._relativeLuminanceForComponent(this.rgba.g);
        const B = Color._relativeLuminanceForComponent(this.rgba.b);
        const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B;
        return roundFloat(luminance, 4);
    }
    static _relativeLuminanceForComponent(color) {
        const c = color / 255;
        return (c <= 0.03928) ? c / 12.92 : Math.pow(((c + 0.055) / 1.055), 2.4);
    }
    /**
     *	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) / 1000;
        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;
    }
    lighten(factor) {
        return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l + this.hsla.l * factor, this.hsla.a));
    }
    darken(factor) {
        return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l - this.hsla.l * factor, this.hsla.a));
    }
    transparent(factor) {
        const { r, g, b, a } = this.rgba;
        return new Color(new RGBA(r, g, b, a * factor));
    }
    isTransparent() {
        return this.rgba.a === 0;
    }
    isOpaque() {
        return this.rgba.a === 1;
    }
    opposite() {
        return new Color(new RGBA(255 - this.rgba.r, 255 - this.rgba.g, 255 - this.rgba.b, this.rgba.a));
    }
    toString() {
        if (!this._toString) {
            this._toString = Color.Format.CSS.format(this);
        }
        return this._toString;
    }
    static getLighterColor(of, relative, factor) {
        if (of.isLighterThan(relative)) {
            return of;
        }
        factor = factor ? factor : 0.5;
        const lum1 = of.getRelativeLuminance();
        const lum2 = relative.getRelativeLuminance();
        factor = factor * (lum2 - lum1) / lum2;
        return of.lighten(factor);
    }
    static getDarkerColor(of, relative, factor) {
        if (of.isDarkerThan(relative)) {
            return of;
        }
        factor = factor ? factor : 0.5;
        const lum1 = of.getRelativeLuminance();
        const lum2 = relative.getRelativeLuminance();
        factor = factor * (lum1 - lum2) / lum1;
        return of.darken(factor);
    }
}
Color.white = new Color(new RGBA(255, 255, 255, 1));
Color.black = new Color(new RGBA(0, 0, 0, 1));
Color.red = new Color(new RGBA(255, 0, 0, 1));
Color.blue = new Color(new RGBA(0, 0, 255, 1));
Color.green = new Color(new RGBA(0, 255, 0, 1));
Color.cyan = new Color(new RGBA(0, 255, 255, 1));
Color.lightgrey = new Color(new RGBA(211, 211, 211, 1));
Color.transparent = new Color(new RGBA(0, 0, 0, 0));
(function (Color) {
    let Format;
    (function (Format) {
        let CSS;
        (function (CSS) {
            function formatRGB(color) {
                if (color.rgba.a === 1) {
                    return `rgb(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b})`;
                }
                return Color.Format.CSS.formatRGBA(color);
            }
            CSS.formatRGB = formatRGB;
            function formatRGBA(color) {
                return `rgba(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b}, ${+(color.rgba.a).toFixed(2)})`;
            }
            CSS.formatRGBA = formatRGBA;
            function formatHSL(color) {
                if (color.hsla.a === 1) {
                    return `hsl(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed(2)}%)`;
                }
                return Color.Format.CSS.formatHSLA(color);
            }
            CSS.formatHSL = formatHSL;
            function formatHSLA(color) {
                return `hsla(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed(2)}%, ${color.hsla.a.toFixed(2)})`;
            }
            CSS.formatHSLA = formatHSLA;
            function _toTwoDigitHex(n) {
                const r = n.toString(16);
                return r.length !== 2 ? '0' + r : r;
            }
            /**
             * Formats the color as #RRGGBB
             */
            function formatHex(color) {
                return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}`;
            }
            CSS.formatHex = formatHex;
            /**
             * Formats the color as #RRGGBBAA
             * If 'compact' is set, colors without transparancy will be printed as #RRGGBB
             */
            function formatHexA(color, compact = false) {
                if (compact && color.rgba.a === 1) {
                    return Color.Format.CSS.formatHex(color);
                }
                return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}${_toTwoDigitHex(Math.round(color.rgba.a * 255))}`;
            }
            CSS.formatHexA = formatHexA;
            /**
             * The default format will use HEX if opaque and RGBA otherwise.
             */
            function format(color) {
                if (color.isOpaque()) {
                    return Color.Format.CSS.formatHex(color);
                }
                return Color.Format.CSS.formatRGBA(color);
            }
            CSS.format = format;
            /**
             * Converts an Hex color value to a Color.
             * returns r, g, and b are contained in the set [0, 255]
             * @param hex string (#RGB, #RGBA, #RRGGBB or #RRGGBBAA).
             */
            function parseHex(hex) {
                const length = hex.length;
                if (length === 0) {
                    // Invalid color
                    return null;
                }
                if (hex.charCodeAt(0) !== 35 /* CharCode.Hash */) {
                    // Does not begin with a #
                    return null;
                }
                if (length === 7) {
                    // #RRGGBB format
                    const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
                    const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
                    const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
                    return new Color(new RGBA(r, g, b, 1));
                }
                if (length === 9) {
                    // #RRGGBBAA format
                    const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
                    const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
                    const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
                    const a = 16 * _parseHexDigit(hex.charCodeAt(7)) + _parseHexDigit(hex.charCodeAt(8));
                    return new Color(new RGBA(r, g, b, a / 255));
                }
                if (length === 4) {
                    // #RGB format
                    const r = _parseHexDigit(hex.charCodeAt(1));
                    const g = _parseHexDigit(hex.charCodeAt(2));
                    const b = _parseHexDigit(hex.charCodeAt(3));
                    return new Color(new RGBA(16 * r + r, 16 * g + g, 16 * b + b));
                }
                if (length === 5) {
                    // #RGBA format
                    const r = _parseHexDigit(hex.charCodeAt(1));
                    const g = _parseHexDigit(hex.charCodeAt(2));
                    const b = _parseHexDigit(hex.charCodeAt(3));
                    const a = _parseHexDigit(hex.charCodeAt(4));
                    return new Color(new RGBA(16 * r + r, 16 * g + g, 16 * b + b, (16 * a + a) / 255));
                }
                // Invalid color
                return null;
            }
            CSS.parseHex = parseHex;
            function _parseHexDigit(charCode) {
                switch (charCode) {
                    case 48 /* CharCode.Digit0 */: return 0;
                    case 49 /* CharCode.Digit1 */: return 1;
                    case 50 /* CharCode.Digit2 */: return 2;
                    case 51 /* CharCode.Digit3 */: return 3;
                    case 52 /* CharCode.Digit4 */: return 4;
                    case 53 /* CharCode.Digit5 */: return 5;
                    case 54 /* CharCode.Digit6 */: return 6;
                    case 55 /* CharCode.Digit7 */: return 7;
                    case 56 /* CharCode.Digit8 */: return 8;
                    case 57 /* CharCode.Digit9 */: return 9;
                    case 97 /* CharCode.a */: return 10;
                    case 65 /* CharCode.A */: return 10;
                    case 98 /* CharCode.b */: return 11;
                    case 66 /* CharCode.B */: return 11;
                    case 99 /* CharCode.c */: return 12;
                    case 67 /* CharCode.C */: return 12;
                    case 100 /* CharCode.d */: return 13;
                    case 68 /* CharCode.D */: return 13;
                    case 101 /* CharCode.e */: return 14;
                    case 69 /* CharCode.E */: return 14;
                    case 102 /* CharCode.f */: return 15;
                    case 70 /* CharCode.F */: return 15;
                }
                return 0;
            }
        })(CSS = Format.CSS || (Format.CSS = {}));
    })(Format = Color.Format || (Color.Format = {}));
})(Color || (Color = {}));

;// ../../node_modules/monaco-editor/esm/vs/platform/jsonschemas/common/jsonContributionRegistry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


const jsonContributionRegistry_Extensions = {
    JSONContribution: 'base.contributions.json'
};
function normalizeId(id) {
    if (id.length > 0 && id.charAt(id.length - 1) === '#') {
        return id.substring(0, id.length - 1);
    }
    return id;
}
class JSONContributionRegistry {
    constructor() {
        this._onDidChangeSchema = new Emitter();
        this.schemasById = {};
    }
    registerSchema(uri, unresolvedSchemaContent) {
        this.schemasById[normalizeId(uri)] = unresolvedSchemaContent;
        this._onDidChangeSchema.fire(uri);
    }
    notifySchemaChanged(uri) {
        this._onDidChangeSchema.fire(uri);
    }
}
const jsonContributionRegistry = new JSONContributionRegistry();
Registry.add(jsonContributionRegistry_Extensions.JSONContribution, jsonContributionRegistry);

;// ../../node_modules/monaco-editor/esm/vs/platform/theme/common/colorRegistry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







/**
 * Returns the css variable name for the given color identifier. Dots (`.`) are replaced with hyphens (`-`) and
 * everything is prefixed with `--vscode-`.
 *
 * @sample `editorSuggestWidget.background` is `--vscode-editorSuggestWidget-background`.
 */
function asCssVariableName(colorIdent) {
    return `--vscode-${colorIdent.replace(/\./g, '-')}`;
}
// color registry
const colorRegistry_Extensions = {
    ColorContribution: 'base.contributions.colors'
};
class ColorRegistry {
    constructor() {
        this._onDidChangeSchema = new Emitter();
        this.onDidChangeSchema = this._onDidChangeSchema.event;
        this.colorSchema = { type: 'object', properties: {} };
        this.colorReferenceSchema = { type: 'string', enum: [], enumDescriptions: [] };
        this.colorsById = {};
    }
    registerColor(id, defaults, description, needsTransparency = false, deprecationMessage) {
        const colorContribution = { id, description, defaults, needsTransparency, deprecationMessage };
        this.colorsById[id] = colorContribution;
        const propertySchema = { type: 'string', description, format: 'color-hex', defaultSnippets: [{ body: '${1:#ff0000}' }] };
        if (deprecationMessage) {
            propertySchema.deprecationMessage = deprecationMessage;
        }
        this.colorSchema.properties[id] = propertySchema;
        this.colorReferenceSchema.enum.push(id);
        this.colorReferenceSchema.enumDescriptions.push(description);
        this._onDidChangeSchema.fire();
        return id;
    }
    getColors() {
        return Object.keys(this.colorsById).map(id => this.colorsById[id]);
    }
    resolveDefaultColor(id, theme) {
        const colorDesc = this.colorsById[id];
        if (colorDesc && colorDesc.defaults) {
            const colorValue = colorDesc.defaults[theme.type];
            return resolveColorValue(colorValue, theme);
        }
        return undefined;
    }
    getColorSchema() {
        return this.colorSchema;
    }
    toString() {
        const sorter = (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.colorsById).sort(sorter).map(k => `- \`${k}\`: ${this.colorsById[k].description}`).join('\n');
    }
}
const colorRegistry = new ColorRegistry();
Registry.add(colorRegistry_Extensions.ColorContribution, colorRegistry);
function migrateColorDefaults(o) {
    if (o === null) {
        return o;
    }
    if (typeof o.hcLight === 'undefined') {
        if (o.hcDark === null || typeof o.hcDark === 'string') {
            o.hcLight = o.hcDark;
        }
        else {
            o.hcLight = o.light;
        }
    }
    return o;
}
function registerColor(id, defaults, description, needsTransparency, deprecationMessage) {
    return colorRegistry.registerColor(id, migrateColorDefaults(defaults), description, needsTransparency, deprecationMessage);
}
// ----- base colors
const foreground = registerColor('foreground', { dark: '#CCCCCC', light: '#616161', hcDark: '#FFFFFF', hcLight: '#292929' }, localize('foreground', "Overall foreground color. This color is only used if not overridden by a component."));
const disabledForeground = registerColor('disabledForeground', { dark: '#CCCCCC80', light: '#61616180', hcDark: '#A5A5A5', hcLight: '#7F7F7F' }, localize('disabledForeground', "Overall foreground for disabled elements. This color is only used if not overridden by a component."));
const errorForeground = registerColor('errorForeground', { dark: '#F48771', light: '#A1260D', hcDark: '#F48771', hcLight: '#B5200D' }, localize('errorForeground', "Overall foreground color for error messages. This color is only used if not overridden by a component."));
const descriptionForeground = registerColor('descriptionForeground', { light: '#717171', dark: transparent(foreground, 0.7), hcDark: transparent(foreground, 0.7), hcLight: transparent(foreground, 0.7) }, localize('descriptionForeground', "Foreground color for description text providing additional information, for example for a label."));
const iconForeground = registerColor('icon.foreground', { dark: '#C5C5C5', light: '#424242', hcDark: '#FFFFFF', hcLight: '#292929' }, localize('iconForeground', "The default color for icons in the workbench."));
const focusBorder = registerColor('focusBorder', { dark: '#007FD4', light: '#0090F1', hcDark: '#F38518', hcLight: '#0F4A85' }, localize('focusBorder', "Overall border color for focused elements. This color is only used if not overridden by a component."));
const contrastBorder = registerColor('contrastBorder', { light: null, dark: null, hcDark: '#6FC3DF', hcLight: '#0F4A85' }, localize('contrastBorder', "An extra border around elements to separate them from others for greater contrast."));
const activeContrastBorder = registerColor('contrastActiveBorder', { light: null, dark: null, hcDark: focusBorder, hcLight: focusBorder }, localize('activeContrastBorder', "An extra border around active elements to separate them from others for greater contrast."));
const selectionBackground = registerColor('selection.background', { light: null, dark: null, hcDark: null, hcLight: null }, localize('selectionBackground', "The background color of text selections in the workbench (e.g. for input fields or text areas). Note that this does not apply to selections within the editor."));
// ------ text colors
const textSeparatorForeground = registerColor('textSeparator.foreground', { light: '#0000002e', dark: '#ffffff2e', hcDark: Color.black, hcLight: '#292929' }, localize('textSeparatorForeground', "Color for text separators."));
const textLinkForeground = registerColor('textLink.foreground', { light: '#006AB1', dark: '#3794FF', hcDark: '#3794FF', hcLight: '#0F4A85' }, localize('textLinkForeground', "Foreground color for links in text."));
const textLinkActiveForeground = registerColor('textLink.activeForeground', { light: '#006AB1', dark: '#3794FF', hcDark: '#3794FF', hcLight: '#0F4A85' }, localize('textLinkActiveForeground', "Foreground color for links in text when clicked on and on mouse hover."));
const textPreformatForeground = registerColor('textPreformat.foreground', { light: '#A31515', dark: '#D7BA7D', hcDark: '#D7BA7D', hcLight: '#292929' }, localize('textPreformatForeground', "Foreground color for preformatted text segments."));
const textBlockQuoteBackground = registerColor('textBlockQuote.background', { light: '#7f7f7f1a', dark: '#7f7f7f1a', hcDark: null, hcLight: '#F2F2F2' }, localize('textBlockQuoteBackground', "Background color for block quotes in text."));
const textBlockQuoteBorder = registerColor('textBlockQuote.border', { light: '#007acc80', dark: '#007acc80', hcDark: Color.white, hcLight: '#292929' }, localize('textBlockQuoteBorder', "Border color for block quotes in text."));
const textCodeBlockBackground = registerColor('textCodeBlock.background', { light: '#dcdcdc66', dark: '#0a0a0a66', hcDark: Color.black, hcLight: '#F2F2F2' }, localize('textCodeBlockBackground', "Background color for code blocks in text."));
// ----- widgets
const widgetShadow = registerColor('widget.shadow', { dark: transparent(Color.black, .36), light: transparent(Color.black, .16), hcDark: null, hcLight: null }, localize('widgetShadow', 'Shadow color of widgets such as find/replace inside the editor.'));
const inputBackground = registerColor('input.background', { dark: '#3C3C3C', light: Color.white, hcDark: Color.black, hcLight: Color.white }, localize('inputBoxBackground', "Input box background."));
const inputForeground = registerColor('input.foreground', { dark: foreground, light: foreground, hcDark: foreground, hcLight: foreground }, localize('inputBoxForeground', "Input box foreground."));
const inputBorder = registerColor('input.border', { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize('inputBoxBorder', "Input box border."));
const inputActiveOptionBorder = registerColor('inputOption.activeBorder', { dark: '#007ACC00', light: '#007ACC00', hcDark: contrastBorder, hcLight: contrastBorder }, localize('inputBoxActiveOptionBorder', "Border color of activated options in input fields."));
const inputActiveOptionHoverBackground = registerColor('inputOption.hoverBackground', { dark: '#5a5d5e80', light: '#b8b8b850', hcDark: null, hcLight: null }, localize('inputOption.hoverBackground', "Background color of activated options in input fields."));
const inputActiveOptionBackground = registerColor('inputOption.activeBackground', { dark: transparent(focusBorder, 0.4), light: transparent(focusBorder, 0.2), hcDark: Color.transparent, hcLight: Color.transparent }, localize('inputOption.activeBackground', "Background hover color of options in input fields."));
const inputActiveOptionForeground = registerColor('inputOption.activeForeground', { dark: Color.white, light: Color.black, hcDark: null, hcLight: foreground }, localize('inputOption.activeForeground', "Foreground color of activated options in input fields."));
const inputPlaceholderForeground = registerColor('input.placeholderForeground', { light: transparent(foreground, 0.5), dark: transparent(foreground, 0.5), hcDark: transparent(foreground, 0.7), hcLight: transparent(foreground, 0.7) }, localize('inputPlaceholderForeground', "Input box foreground color for placeholder text."));
const inputValidationInfoBackground = registerColor('inputValidation.infoBackground', { dark: '#063B49', light: '#D6ECF2', hcDark: Color.black, hcLight: Color.white }, localize('inputValidationInfoBackground', "Input validation background color for information severity."));
const inputValidationInfoForeground = registerColor('inputValidation.infoForeground', { dark: null, light: null, hcDark: null, hcLight: foreground }, localize('inputValidationInfoForeground', "Input validation foreground color for information severity."));
const inputValidationInfoBorder = registerColor('inputValidation.infoBorder', { dark: '#007acc', light: '#007acc', hcDark: contrastBorder, hcLight: contrastBorder }, localize('inputValidationInfoBorder', "Input validation border color for information severity."));
const inputValidationWarningBackground = registerColor('inputValidation.warningBackground', { dark: '#352A05', light: '#F6F5D2', hcDark: Color.black, hcLight: Color.white }, localize('inputValidationWarningBackground', "Input validation background color for warning severity."));
const inputValidationWarningForeground = registerColor('inputValidation.warningForeground', { dark: null, light: null, hcDark: null, hcLight: foreground }, localize('inputValidationWarningForeground', "Input validation foreground color for warning severity."));
const inputValidationWarningBorder = registerColor('inputValidation.warningBorder', { dark: '#B89500', light: '#B89500', hcDark: contrastBorder, hcLight: contrastBorder }, localize('inputValidationWarningBorder', "Input validation border color for warning severity."));
const inputValidationErrorBackground = registerColor('inputValidation.errorBackground', { dark: '#5A1D1D', light: '#F2DEDE', hcDark: Color.black, hcLight: Color.white }, localize('inputValidationErrorBackground', "Input validation background color for error severity."));
const inputValidationErrorForeground = registerColor('inputValidation.errorForeground', { dark: null, light: null, hcDark: null, hcLight: foreground }, localize('inputValidationErrorForeground', "Input validation foreground color for error severity."));
const inputValidationErrorBorder = registerColor('inputValidation.errorBorder', { dark: '#BE1100', light: '#BE1100', hcDark: contrastBorder, hcLight: contrastBorder }, localize('inputValidationErrorBorder', "Input validation border color for error severity."));
const selectBackground = registerColor('dropdown.background', { dark: '#3C3C3C', light: Color.white, hcDark: Color.black, hcLight: Color.white }, localize('dropdownBackground', "Dropdown background."));
const selectListBackground = registerColor('dropdown.listBackground', { dark: null, light: null, hcDark: Color.black, hcLight: Color.white }, localize('dropdownListBackground', "Dropdown list background."));
const selectForeground = registerColor('dropdown.foreground', { dark: '#F0F0F0', light: null, hcDark: Color.white, hcLight: foreground }, localize('dropdownForeground', "Dropdown foreground."));
const selectBorder = registerColor('dropdown.border', { dark: selectBackground, light: '#CECECE', hcDark: contrastBorder, hcLight: contrastBorder }, localize('dropdownBorder', "Dropdown border."));
const checkboxBackground = registerColor('checkbox.background', { dark: selectBackground, light: selectBackground, hcDark: selectBackground, hcLight: selectBackground }, localize('checkbox.background', "Background color of checkbox widget."));
const checkboxForeground = registerColor('checkbox.foreground', { dark: selectForeground, light: selectForeground, hcDark: selectForeground, hcLight: selectForeground }, localize('checkbox.foreground', "Foreground color of checkbox widget."));
const checkboxBorder = registerColor('checkbox.border', { dark: selectBorder, light: selectBorder, hcDark: selectBorder, hcLight: selectBorder }, localize('checkbox.border', "Border color of checkbox widget."));
const buttonForeground = registerColor('button.foreground', { dark: Color.white, light: Color.white, hcDark: Color.white, hcLight: Color.white }, localize('buttonForeground', "Button foreground color."));
const buttonSeparator = registerColor('button.separator', { dark: transparent(buttonForeground, .4), light: transparent(buttonForeground, .4), hcDark: transparent(buttonForeground, .4), hcLight: transparent(buttonForeground, .4) }, localize('buttonSeparator', "Button separator color."));
const buttonBackground = registerColor('button.background', { dark: '#0E639C', light: '#007ACC', hcDark: null, hcLight: '#0F4A85' }, localize('buttonBackground', "Button background color."));
const buttonHoverBackground = registerColor('button.hoverBackground', { dark: lighten(buttonBackground, 0.2), light: darken(buttonBackground, 0.2), hcDark: null, hcLight: null }, localize('buttonHoverBackground', "Button background color when hovering."));
const buttonBorder = registerColor('button.border', { dark: contrastBorder, light: contrastBorder, hcDark: contrastBorder, hcLight: contrastBorder }, localize('buttonBorder', "Button border color."));
const buttonSecondaryForeground = registerColor('button.secondaryForeground', { dark: Color.white, light: Color.white, hcDark: Color.white, hcLight: foreground }, localize('buttonSecondaryForeground', "Secondary button foreground color."));
const buttonSecondaryBackground = registerColor('button.secondaryBackground', { dark: '#3A3D41', light: '#5F6A79', hcDark: null, hcLight: Color.white }, localize('buttonSecondaryBackground', "Secondary button background color."));
const buttonSecondaryHoverBackground = registerColor('button.secondaryHoverBackground', { dark: lighten(buttonSecondaryBackground, 0.2), light: darken(buttonSecondaryBackground, 0.2), hcDark: null, hcLight: null }, localize('buttonSecondaryHoverBackground', "Secondary button background color when hovering."));
const badgeBackground = registerColor('badge.background', { dark: '#4D4D4D', light: '#C4C4C4', hcDark: Color.black, hcLight: '#0F4A85' }, localize('badgeBackground', "Badge background color. Badges are small information labels, e.g. for search results count."));
const badgeForeground = registerColor('badge.foreground', { dark: Color.white, light: '#333', hcDark: Color.white, hcLight: Color.white }, localize('badgeForeground', "Badge foreground color. Badges are small information labels, e.g. for search results count."));
const scrollbarShadow = registerColor('scrollbar.shadow', { dark: '#000000', light: '#DDDDDD', hcDark: null, hcLight: null }, localize('scrollbarShadow', "Scrollbar shadow to indicate that the view is scrolled."));
const scrollbarSliderBackground = registerColor('scrollbarSlider.background', { dark: Color.fromHex('#797979').transparent(0.4), light: Color.fromHex('#646464').transparent(0.4), hcDark: transparent(contrastBorder, 0.6), hcLight: transparent(contrastBorder, 0.4) }, localize('scrollbarSliderBackground', "Scrollbar slider background color."));
const scrollbarSliderHoverBackground = registerColor('scrollbarSlider.hoverBackground', { dark: Color.fromHex('#646464').transparent(0.7), light: Color.fromHex('#646464').transparent(0.7), hcDark: transparent(contrastBorder, 0.8), hcLight: transparent(contrastBorder, 0.8) }, localize('scrollbarSliderHoverBackground', "Scrollbar slider background color when hovering."));
const scrollbarSliderActiveBackground = registerColor('scrollbarSlider.activeBackground', { dark: Color.fromHex('#BFBFBF').transparent(0.4), light: Color.fromHex('#000000').transparent(0.6), hcDark: contrastBorder, hcLight: contrastBorder }, localize('scrollbarSliderActiveBackground', "Scrollbar slider background color when clicked on."));
const progressBarBackground = registerColor('progressBar.background', { dark: Color.fromHex('#0E70C0'), light: Color.fromHex('#0E70C0'), hcDark: contrastBorder, hcLight: contrastBorder }, localize('progressBarBackground', "Background color of the progress bar that can show for long running operations."));
const editorErrorBackground = registerColor('editorError.background', { dark: null, light: null, hcDark: null, hcLight: null }, localize('editorError.background', 'Background color of error text in the editor. The color must not be opaque so as not to hide underlying decorations.'), true);
const editorErrorForeground = registerColor('editorError.foreground', { dark: '#F14C4C', light: '#E51400', hcDark: '#F48771', hcLight: '#B5200D' }, localize('editorError.foreground', 'Foreground color of error squigglies in the editor.'));
const editorErrorBorder = registerColor('editorError.border', { dark: null, light: null, hcDark: Color.fromHex('#E47777').transparent(0.8), hcLight: '#B5200D' }, localize('errorBorder', 'Border color of error boxes in the editor.'));
const editorWarningBackground = registerColor('editorWarning.background', { dark: null, light: null, hcDark: null, hcLight: null }, localize('editorWarning.background', 'Background color of warning text in the editor. The color must not be opaque so as not to hide underlying decorations.'), true);
const editorWarningForeground = registerColor('editorWarning.foreground', { dark: '#CCA700', light: '#BF8803', hcDark: '#FFD37', hcLight: '#895503' }, localize('editorWarning.foreground', 'Foreground color of warning squigglies in the editor.'));
const editorWarningBorder = registerColor('editorWarning.border', { dark: null, light: null, hcDark: Color.fromHex('#FFCC00').transparent(0.8), hcLight: '#' }, localize('warningBorder', 'Border color of warning boxes in the editor.'));
const editorInfoBackground = registerColor('editorInfo.background', { dark: null, light: null, hcDark: null, hcLight: null }, localize('editorInfo.background', 'Background color of info text in the editor. The color must not be opaque so as not to hide underlying decorations.'), true);
const editorInfoForeground = registerColor('editorInfo.foreground', { dark: '#3794FF', light: '#1a85ff', hcDark: '#3794FF', hcLight: '#1a85ff' }, localize('editorInfo.foreground', 'Foreground color of info squigglies in the editor.'));
const editorInfoBorder = registerColor('editorInfo.border', { dark: null, light: null, hcDark: Color.fromHex('#3794FF').transparent(0.8), hcLight: '#292929' }, localize('infoBorder', 'Border color of info boxes in the editor.'));
const editorHintForeground = registerColor('editorHint.foreground', { dark: Color.fromHex('#eeeeee').transparent(0.7), light: '#6c6c6c', hcDark: null, hcLight: null }, localize('editorHint.foreground', 'Foreground color of hint squigglies in the editor.'));
const editorHintBorder = registerColor('editorHint.border', { dark: null, light: null, hcDark: Color.fromHex('#eeeeee').transparent(0.8), hcLight: '#292929' }, localize('hintBorder', 'Border color of hint boxes in the editor.'));
const sashHoverBorder = registerColor('sash.hoverBorder', { dark: focusBorder, light: focusBorder, hcDark: focusBorder, hcLight: focusBorder }, localize('sashActiveBorder', "Border color of active sashes."));
/**
 * Editor background color.
 */
const editorBackground = registerColor('editor.background', { light: '#ffffff', dark: '#1E1E1E', hcDark: Color.black, hcLight: Color.white }, localize('editorBackground', "Editor background color."));
/**
 * Editor foreground color.
 */
const editorForeground = registerColor('editor.foreground', { light: '#333333', dark: '#BBBBBB', hcDark: Color.white, hcLight: foreground }, localize('editorForeground', "Editor default foreground color."));
/**
 * Sticky scroll
 */
const editorStickyScrollBackground = registerColor('editorStickyScroll.background', { light: editorBackground, dark: editorBackground, hcDark: editorBackground, hcLight: editorBackground }, localize('editorStickyScrollBackground', "Sticky scroll background color for the editor"));
const editorStickyScrollHoverBackground = registerColor('editorStickyScrollHover.background', { dark: '#2A2D2E', light: '#F0F0F0', hcDark: null, hcLight: Color.fromHex('#0F4A85').transparent(0.1) }, localize('editorStickyScrollHoverBackground', "Sticky scroll on hover background color for the editor"));
/**
 * Editor widgets
 */
const editorWidgetBackground = registerColor('editorWidget.background', { dark: '#252526', light: '#F3F3F3', hcDark: '#0C141F', hcLight: Color.white }, localize('editorWidgetBackground', 'Background color of editor widgets, such as find/replace.'));
const editorWidgetForeground = registerColor('editorWidget.foreground', { dark: foreground, light: foreground, hcDark: foreground, hcLight: foreground }, localize('editorWidgetForeground', 'Foreground color of editor widgets, such as find/replace.'));
const editorWidgetBorder = registerColor('editorWidget.border', { dark: '#454545', light: '#C8C8C8', hcDark: contrastBorder, hcLight: contrastBorder }, localize('editorWidgetBorder', 'Border color of editor widgets. The color is only used if the widget chooses to have a border and if the color is not overridden by a widget.'));
const editorWidgetResizeBorder = registerColor('editorWidget.resizeBorder', { light: null, dark: null, hcDark: null, hcLight: null }, localize('editorWidgetResizeBorder', "Border color of the resize bar of editor widgets. The color is only used if the widget chooses to have a resize border and if the color is not overridden by a widget."));
/**
 * Quick pick widget
 */
const quickInputBackground = registerColor('quickInput.background', { dark: editorWidgetBackground, light: editorWidgetBackground, hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize('pickerBackground', "Quick picker background color. The quick picker widget is the container for pickers like the command palette."));
const quickInputForeground = registerColor('quickInput.foreground', { dark: editorWidgetForeground, light: editorWidgetForeground, hcDark: editorWidgetForeground, hcLight: editorWidgetForeground }, localize('pickerForeground', "Quick picker foreground color. The quick picker widget is the container for pickers like the command palette."));
const quickInputTitleBackground = registerColor('quickInputTitle.background', { dark: new Color(new RGBA(255, 255, 255, 0.105)), light: new Color(new RGBA(0, 0, 0, 0.06)), hcDark: '#000000', hcLight: Color.white }, localize('pickerTitleBackground', "Quick picker title background color. The quick picker widget is the container for pickers like the command palette."));
const pickerGroupForeground = registerColor('pickerGroup.foreground', { dark: '#3794FF', light: '#0066BF', hcDark: Color.white, hcLight: '#0F4A85' }, localize('pickerGroupForeground', "Quick picker color for grouping labels."));
const pickerGroupBorder = registerColor('pickerGroup.border', { dark: '#3F3F46', light: '#CCCEDB', hcDark: Color.white, hcLight: '#0F4A85' }, localize('pickerGroupBorder', "Quick picker color for grouping borders."));
/**
 * Keybinding label
 */
const keybindingLabelBackground = registerColor('keybindingLabel.background', { dark: new Color(new RGBA(128, 128, 128, 0.17)), light: new Color(new RGBA(221, 221, 221, 0.4)), hcDark: Color.transparent, hcLight: Color.transparent }, localize('keybindingLabelBackground', "Keybinding label background color. The keybinding label is used to represent a keyboard shortcut."));
const keybindingLabelForeground = registerColor('keybindingLabel.foreground', { dark: Color.fromHex('#CCCCCC'), light: Color.fromHex('#555555'), hcDark: Color.white, hcLight: foreground }, localize('keybindingLabelForeground', "Keybinding label foreground color. The keybinding label is used to represent a keyboard shortcut."));
const keybindingLabelBorder = registerColor('keybindingLabel.border', { dark: new Color(new RGBA(51, 51, 51, 0.6)), light: new Color(new RGBA(204, 204, 204, 0.4)), hcDark: new Color(new RGBA(111, 195, 223)), hcLight: contrastBorder }, localize('keybindingLabelBorder', "Keybinding label border color. The keybinding label is used to represent a keyboard shortcut."));
const keybindingLabelBottomBorder = registerColor('keybindingLabel.bottomBorder', { dark: new Color(new RGBA(68, 68, 68, 0.6)), light: new Color(new RGBA(187, 187, 187, 0.4)), hcDark: new Color(new RGBA(111, 195, 223)), hcLight: foreground }, localize('keybindingLabelBottomBorder', "Keybinding label border bottom color. The keybinding label is used to represent a keyboard shortcut."));
/**
 * Editor selection colors.
 */
const editorSelectionBackground = registerColor('editor.selectionBackground', { light: '#ADD6FF', dark: '#264F78', hcDark: '#f3f518', hcLight: '#0F4A85' }, localize('editorSelectionBackground', "Color of the editor selection."));
const editorSelectionForeground = registerColor('editor.selectionForeground', { light: null, dark: null, hcDark: '#000000', hcLight: Color.white }, localize('editorSelectionForeground', "Color of the selected text for high contrast."));
const editorInactiveSelection = registerColor('editor.inactiveSelectionBackground', { light: transparent(editorSelectionBackground, 0.5), dark: transparent(editorSelectionBackground, 0.5), hcDark: transparent(editorSelectionBackground, 0.7), hcLight: transparent(editorSelectionBackground, 0.5) }, localize('editorInactiveSelection', "Color of the selection in an inactive editor. The color must not be opaque so as not to hide underlying decorations."), true);
const editorSelectionHighlight = registerColor('editor.selectionHighlightBackground', { light: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), dark: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), hcDark: null, hcLight: null }, localize('editorSelectionHighlight', 'Color for regions with the same content as the selection. The color must not be opaque so as not to hide underlying decorations.'), true);
const editorSelectionHighlightBorder = registerColor('editor.selectionHighlightBorder', { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('editorSelectionHighlightBorder', "Border color for regions with the same content as the selection."));
/**
 * Editor find match colors.
 */
const editorFindMatch = registerColor('editor.findMatchBackground', { light: '#A8AC94', dark: '#515C6A', hcDark: null, hcLight: null }, localize('editorFindMatch', "Color of the current search match."));
const editorFindMatchHighlight = registerColor('editor.findMatchHighlightBackground', { light: '#EA5C0055', dark: '#EA5C0055', hcDark: null, hcLight: null }, localize('findMatchHighlight', "Color of the other search matches. The color must not be opaque so as not to hide underlying decorations."), true);
const editorFindRangeHighlight = registerColor('editor.findRangeHighlightBackground', { dark: '#3a3d4166', light: '#b4b4b44d', hcDark: null, hcLight: null }, localize('findRangeHighlight', "Color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true);
const editorFindMatchBorder = registerColor('editor.findMatchBorder', { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('editorFindMatchBorder', "Border color of the current search match."));
const editorFindMatchHighlightBorder = registerColor('editor.findMatchHighlightBorder', { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('findMatchHighlightBorder', "Border color of the other search matches."));
const editorFindRangeHighlightBorder = registerColor('editor.findRangeHighlightBorder', { dark: null, light: null, hcDark: transparent(activeContrastBorder, 0.4), hcLight: transparent(activeContrastBorder, 0.4) }, localize('findRangeHighlightBorder', "Border color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true);
/**
 * Search Editor query match colors.
 *
 * Distinct from normal editor find match to allow for better differentiation
 */
const searchEditorFindMatch = registerColor('searchEditor.findMatchBackground', { light: transparent(editorFindMatchHighlight, 0.66), dark: transparent(editorFindMatchHighlight, 0.66), hcDark: editorFindMatchHighlight, hcLight: editorFindMatchHighlight }, localize('searchEditor.queryMatch', "Color of the Search Editor query matches."));
const searchEditorFindMatchBorder = registerColor('searchEditor.findMatchBorder', { light: transparent(editorFindMatchHighlightBorder, 0.66), dark: transparent(editorFindMatchHighlightBorder, 0.66), hcDark: editorFindMatchHighlightBorder, hcLight: editorFindMatchHighlightBorder }, localize('searchEditor.editorFindMatchBorder', "Border color of the Search Editor query matches."));
/**
 * Editor hover
 */
const editorHoverHighlight = registerColor('editor.hoverHighlightBackground', { light: '#ADD6FF26', dark: '#264f7840', hcDark: '#ADD6FF26', hcLight: null }, localize('hoverHighlight', 'Highlight below the word for which a hover is shown. The color must not be opaque so as not to hide underlying decorations.'), true);
const editorHoverBackground = registerColor('editorHoverWidget.background', { light: editorWidgetBackground, dark: editorWidgetBackground, hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize('hoverBackground', 'Background color of the editor hover.'));
const editorHoverForeground = registerColor('editorHoverWidget.foreground', { light: editorWidgetForeground, dark: editorWidgetForeground, hcDark: editorWidgetForeground, hcLight: editorWidgetForeground }, localize('hoverForeground', 'Foreground color of the editor hover.'));
const editorHoverBorder = registerColor('editorHoverWidget.border', { light: editorWidgetBorder, dark: editorWidgetBorder, hcDark: editorWidgetBorder, hcLight: editorWidgetBorder }, localize('hoverBorder', 'Border color of the editor hover.'));
const editorHoverStatusBarBackground = registerColor('editorHoverWidget.statusBarBackground', { dark: lighten(editorHoverBackground, 0.2), light: darken(editorHoverBackground, 0.05), hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize('statusBarBackground', "Background color of the editor hover status bar."));
/**
 * Editor link colors
 */
const editorActiveLinkForeground = registerColor('editorLink.activeForeground', { dark: '#4E94CE', light: Color.blue, hcDark: Color.cyan, hcLight: '#292929' }, localize('activeLinkForeground', 'Color of active links.'));
/**
 * Inline hints
 */
const editorInlayHintForeground = registerColor('editorInlayHint.foreground', { dark: transparent(badgeForeground, .8), light: transparent(badgeForeground, .8), hcDark: badgeForeground, hcLight: badgeForeground }, localize('editorInlayHintForeground', 'Foreground color of inline hints'));
const editorInlayHintBackground = registerColor('editorInlayHint.background', { dark: transparent(badgeBackground, .6), light: transparent(badgeBackground, .3), hcDark: badgeBackground, hcLight: badgeBackground }, localize('editorInlayHintBackground', 'Background color of inline hints'));
const editorInlayHintTypeForeground = registerColor('editorInlayHint.typeForeground', { dark: editorInlayHintForeground, light: editorInlayHintForeground, hcDark: editorInlayHintForeground, hcLight: editorInlayHintForeground }, localize('editorInlayHintForegroundTypes', 'Foreground color of inline hints for types'));
const editorInlayHintTypeBackground = registerColor('editorInlayHint.typeBackground', { dark: editorInlayHintBackground, light: editorInlayHintBackground, hcDark: editorInlayHintBackground, hcLight: editorInlayHintBackground }, localize('editorInlayHintBackgroundTypes', 'Background color of inline hints for types'));
const editorInlayHintParameterForeground = registerColor('editorInlayHint.parameterForeground', { dark: editorInlayHintForeground, light: editorInlayHintForeground, hcDark: editorInlayHintForeground, hcLight: editorInlayHintForeground }, localize('editorInlayHintForegroundParameter', 'Foreground color of inline hints for parameters'));
const editorInlayHintParameterBackground = registerColor('editorInlayHint.parameterBackground', { dark: editorInlayHintBackground, light: editorInlayHintBackground, hcDark: editorInlayHintBackground, hcLight: editorInlayHintBackground }, localize('editorInlayHintBackgroundParameter', 'Background color of inline hints for parameters'));
/**
 * Editor lighbulb icon colors
 */
const editorLightBulbForeground = registerColor('editorLightBulb.foreground', { dark: '#FFCC00', light: '#DDB100', hcDark: '#FFCC00', hcLight: '#007ACC' }, localize('editorLightBulbForeground', "The color used for the lightbulb actions icon."));
const editorLightBulbAutoFixForeground = registerColor('editorLightBulbAutoFix.foreground', { dark: '#75BEFF', light: '#007ACC', hcDark: '#75BEFF', hcLight: '#007ACC' }, localize('editorLightBulbAutoFixForeground', "The color used for the lightbulb auto fix actions icon."));
/**
 * Diff Editor Colors
 */
const defaultInsertColor = new Color(new RGBA(155, 185, 85, .2));
const defaultRemoveColor = new Color(new RGBA(255, 0, 0, .2));
const diffInserted = registerColor('diffEditor.insertedTextBackground', { dark: '#9ccc2c33', light: '#9ccc2c66', hcDark: null, hcLight: null }, localize('diffEditorInserted', 'Background color for text that got inserted. The color must not be opaque so as not to hide underlying decorations.'), true);
const diffRemoved = registerColor('diffEditor.removedTextBackground', { dark: '#ff000066', light: '#ff00004d', hcDark: null, hcLight: null }, localize('diffEditorRemoved', 'Background color for text that got removed. The color must not be opaque so as not to hide underlying decorations.'), true);
const diffInsertedLine = registerColor('diffEditor.insertedLineBackground', { dark: defaultInsertColor, light: defaultInsertColor, hcDark: null, hcLight: null }, localize('diffEditorInsertedLines', 'Background color for lines that got inserted. The color must not be opaque so as not to hide underlying decorations.'), true);
const diffRemovedLine = registerColor('diffEditor.removedLineBackground', { dark: defaultRemoveColor, light: defaultRemoveColor, hcDark: null, hcLight: null }, localize('diffEditorRemovedLines', 'Background color for lines that got removed. The color must not be opaque so as not to hide underlying decorations.'), true);
const diffInsertedLineGutter = registerColor('diffEditorGutter.insertedLineBackground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('diffEditorInsertedLineGutter', 'Background color for the margin where lines got inserted.'));
const diffRemovedLineGutter = registerColor('diffEditorGutter.removedLineBackground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('diffEditorRemovedLineGutter', 'Background color for the margin where lines got removed.'));
const diffOverviewRulerInserted = registerColor('diffEditorOverview.insertedForeground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('diffEditorOverviewInserted', 'Diff overview ruler foreground for inserted content.'));
const diffOverviewRulerRemoved = registerColor('diffEditorOverview.removedForeground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('diffEditorOverviewRemoved', 'Diff overview ruler foreground for removed content.'));
const diffInsertedOutline = registerColor('diffEditor.insertedTextBorder', { dark: null, light: null, hcDark: '#33ff2eff', hcLight: '#374E06' }, localize('diffEditorInsertedOutline', 'Outline color for the text that got inserted.'));
const diffRemovedOutline = registerColor('diffEditor.removedTextBorder', { dark: null, light: null, hcDark: '#FF008F', hcLight: '#AD0707' }, localize('diffEditorRemovedOutline', 'Outline color for text that got removed.'));
const diffBorder = registerColor('diffEditor.border', { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize('diffEditorBorder', 'Border color between the two text editors.'));
const diffDiagonalFill = registerColor('diffEditor.diagonalFill', { dark: '#cccccc33', light: '#22222233', hcDark: null, hcLight: null }, localize('diffDiagonalFill', "Color of the diff editor's diagonal fill. The diagonal fill is used in side-by-side diff views."));
/**
 * List and tree colors
 */
const listFocusBackground = registerColor('list.focusBackground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('listFocusBackground', "List/Tree background color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listFocusForeground = registerColor('list.focusForeground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('listFocusForeground', "List/Tree foreground color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listFocusOutline = registerColor('list.focusOutline', { dark: focusBorder, light: focusBorder, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('listFocusOutline', "List/Tree outline color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listFocusAndSelectionOutline = registerColor('list.focusAndSelectionOutline', { dark: null, light: null, hcDark: null, hcLight: null }, localize('listFocusAndSelectionOutline', "List/Tree outline color for the focused item when the list/tree is active and selected. An active list/tree has keyboard focus, an inactive does not."));
const listActiveSelectionBackground = registerColor('list.activeSelectionBackground', { dark: '#04395E', light: '#0060C0', hcDark: null, hcLight: Color.fromHex('#0F4A85').transparent(0.1) }, localize('listActiveSelectionBackground', "List/Tree background color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listActiveSelectionForeground = registerColor('list.activeSelectionForeground', { dark: Color.white, light: Color.white, hcDark: null, hcLight: null }, localize('listActiveSelectionForeground', "List/Tree foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listActiveSelectionIconForeground = registerColor('list.activeSelectionIconForeground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('listActiveSelectionIconForeground', "List/Tree icon foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listInactiveSelectionBackground = registerColor('list.inactiveSelectionBackground', { dark: '#37373D', light: '#E4E6F1', hcDark: null, hcLight: Color.fromHex('#0F4A85').transparent(0.1) }, localize('listInactiveSelectionBackground', "List/Tree background color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
const listInactiveSelectionForeground = registerColor('list.inactiveSelectionForeground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('listInactiveSelectionForeground', "List/Tree foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
const listInactiveSelectionIconForeground = registerColor('list.inactiveSelectionIconForeground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('listInactiveSelectionIconForeground', "List/Tree icon foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
const listInactiveFocusBackground = registerColor('list.inactiveFocusBackground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('listInactiveFocusBackground', "List/Tree background color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
const listInactiveFocusOutline = registerColor('list.inactiveFocusOutline', { dark: null, light: null, hcDark: null, hcLight: null }, localize('listInactiveFocusOutline', "List/Tree outline color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
const listHoverBackground = registerColor('list.hoverBackground', { dark: '#2A2D2E', light: '#F0F0F0', hcDark: null, hcLight: Color.fromHex('#0F4A85').transparent(0.1) }, localize('listHoverBackground', "List/Tree background when hovering over items using the mouse."));
const listHoverForeground = registerColor('list.hoverForeground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('listHoverForeground', "List/Tree foreground when hovering over items using the mouse."));
const listDropBackground = registerColor('list.dropBackground', { dark: '#062F4A', light: '#D6EBFF', hcDark: null, hcLight: null }, localize('listDropBackground', "List/Tree drag and drop background when moving items around using the mouse."));
const listHighlightForeground = registerColor('list.highlightForeground', { dark: '#2AAAFF', light: '#0066BF', hcDark: focusBorder, hcLight: focusBorder }, localize('highlight', 'List/Tree foreground color of the match highlights when searching inside the list/tree.'));
const listFocusHighlightForeground = registerColor('list.focusHighlightForeground', { dark: listHighlightForeground, light: ifDefinedThenElse(listActiveSelectionBackground, listHighlightForeground, '#BBE7FF'), hcDark: listHighlightForeground, hcLight: listHighlightForeground }, localize('listFocusHighlightForeground', 'List/Tree foreground color of the match highlights on actively focused items when searching inside the list/tree.'));
const listInvalidItemForeground = registerColor('list.invalidItemForeground', { dark: '#B89500', light: '#B89500', hcDark: '#B89500', hcLight: '#B5200D' }, localize('invalidItemForeground', 'List/Tree foreground color for invalid items, for example an unresolved root in explorer.'));
const listErrorForeground = registerColor('list.errorForeground', { dark: '#F88070', light: '#B01011', hcDark: null, hcLight: null }, localize('listErrorForeground', 'Foreground color of list items containing errors.'));
const listWarningForeground = registerColor('list.warningForeground', { dark: '#CCA700', light: '#855F00', hcDark: null, hcLight: null }, localize('listWarningForeground', 'Foreground color of list items containing warnings.'));
const listFilterWidgetBackground = registerColor('listFilterWidget.background', { light: darken(editorWidgetBackground, 0), dark: lighten(editorWidgetBackground, 0), hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize('listFilterWidgetBackground', 'Background color of the type filter widget in lists and trees.'));
const listFilterWidgetOutline = registerColor('listFilterWidget.outline', { dark: Color.transparent, light: Color.transparent, hcDark: '#f38518', hcLight: '#007ACC' }, localize('listFilterWidgetOutline', 'Outline color of the type filter widget in lists and trees.'));
const listFilterWidgetNoMatchesOutline = registerColor('listFilterWidget.noMatchesOutline', { dark: '#BE1100', light: '#BE1100', hcDark: contrastBorder, hcLight: contrastBorder }, localize('listFilterWidgetNoMatchesOutline', 'Outline color of the type filter widget in lists and trees, when there are no matches.'));
const listFilterWidgetShadow = registerColor('listFilterWidget.shadow', { dark: widgetShadow, light: widgetShadow, hcDark: widgetShadow, hcLight: widgetShadow }, localize('listFilterWidgetShadow', 'Shadown color of the type filter widget in lists and trees.'));
const listFilterMatchHighlight = registerColor('list.filterMatchBackground', { dark: editorFindMatchHighlight, light: editorFindMatchHighlight, hcDark: null, hcLight: null }, localize('listFilterMatchHighlight', 'Background color of the filtered match.'));
const listFilterMatchHighlightBorder = registerColor('list.filterMatchBorder', { dark: editorFindMatchHighlightBorder, light: editorFindMatchHighlightBorder, hcDark: contrastBorder, hcLight: activeContrastBorder }, localize('listFilterMatchHighlightBorder', 'Border color of the filtered match.'));
const treeIndentGuidesStroke = registerColor('tree.indentGuidesStroke', { dark: '#585858', light: '#a9a9a9', hcDark: '#a9a9a9', hcLight: '#a5a5a5' }, localize('treeIndentGuidesStroke', "Tree stroke color for the indentation guides."));
const tableColumnsBorder = registerColor('tree.tableColumnsBorder', { dark: '#CCCCCC20', light: '#61616120', hcDark: null, hcLight: null }, localize('tableColumnsBorder', "Table border color between columns."));
const tableOddRowsBackgroundColor = registerColor('tree.tableOddRowsBackground', { dark: transparent(foreground, 0.04), light: transparent(foreground, 0.04), hcDark: null, hcLight: null }, localize('tableOddRowsBackgroundColor', "Background color for odd table rows."));
const listDeemphasizedForeground = registerColor('list.deemphasizedForeground', { dark: '#8C8C8C', light: '#8E8E90', hcDark: '#A7A8A9', hcLight: '#666666' }, localize('listDeemphasizedForeground', "List/Tree foreground color for items that are deemphasized. "));
/**
 * Quick pick widget (dependent on List and tree colors)
 */
const _deprecatedQuickInputListFocusBackground = registerColor('quickInput.list.focusBackground', { dark: null, light: null, hcDark: null, hcLight: null }, '', undefined, localize('quickInput.list.focusBackground deprecation', "Please use quickInputList.focusBackground instead"));
const quickInputListFocusForeground = registerColor('quickInputList.focusForeground', { dark: listActiveSelectionForeground, light: listActiveSelectionForeground, hcDark: listActiveSelectionForeground, hcLight: listActiveSelectionForeground }, localize('quickInput.listFocusForeground', "Quick picker foreground color for the focused item."));
const quickInputListFocusIconForeground = registerColor('quickInputList.focusIconForeground', { dark: listActiveSelectionIconForeground, light: listActiveSelectionIconForeground, hcDark: listActiveSelectionIconForeground, hcLight: listActiveSelectionIconForeground }, localize('quickInput.listFocusIconForeground', "Quick picker icon foreground color for the focused item."));
const quickInputListFocusBackground = registerColor('quickInputList.focusBackground', { dark: oneOf(_deprecatedQuickInputListFocusBackground, listActiveSelectionBackground), light: oneOf(_deprecatedQuickInputListFocusBackground, listActiveSelectionBackground), hcDark: null, hcLight: null }, localize('quickInput.listFocusBackground', "Quick picker background color for the focused item."));
/**
 * Menu colors
 */
const menuBorder = registerColor('menu.border', { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize('menuBorder', "Border color of menus."));
const menuForeground = registerColor('menu.foreground', { dark: selectForeground, light: foreground, hcDark: selectForeground, hcLight: selectForeground }, localize('menuForeground', "Foreground color of menu items."));
const menuBackground = registerColor('menu.background', { dark: selectBackground, light: selectBackground, hcDark: selectBackground, hcLight: selectBackground }, localize('menuBackground', "Background color of menu items."));
const menuSelectionForeground = registerColor('menu.selectionForeground', { dark: listActiveSelectionForeground, light: listActiveSelectionForeground, hcDark: listActiveSelectionForeground, hcLight: listActiveSelectionForeground }, localize('menuSelectionForeground', "Foreground color of the selected menu item in menus."));
const menuSelectionBackground = registerColor('menu.selectionBackground', { dark: listActiveSelectionBackground, light: listActiveSelectionBackground, hcDark: listActiveSelectionBackground, hcLight: listActiveSelectionBackground }, localize('menuSelectionBackground', "Background color of the selected menu item in menus."));
const menuSelectionBorder = registerColor('menu.selectionBorder', { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('menuSelectionBorder', "Border color of the selected menu item in menus."));
const menuSeparatorBackground = registerColor('menu.separatorBackground', { dark: '#606060', light: '#D4D4D4', hcDark: contrastBorder, hcLight: contrastBorder }, localize('menuSeparatorBackground', "Color of a separator menu item in menus."));
/**
 * Toolbar colors
 */
const toolbarHoverBackground = registerColor('toolbar.hoverBackground', { dark: '#5a5d5e50', light: '#b8b8b850', hcDark: null, hcLight: null }, localize('toolbarHoverBackground', "Toolbar background when hovering over actions using the mouse"));
const toolbarHoverOutline = registerColor('toolbar.hoverOutline', { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('toolbarHoverOutline', "Toolbar outline when hovering over actions using the mouse"));
const toolbarActiveBackground = registerColor('toolbar.activeBackground', { dark: lighten(toolbarHoverBackground, 0.1), light: darken(toolbarHoverBackground, 0.1), hcDark: null, hcLight: null }, localize('toolbarActiveBackground', "Toolbar background when holding the mouse over actions"));
/**
 * Snippet placeholder colors
 */
const snippetTabstopHighlightBackground = registerColor('editor.snippetTabstopHighlightBackground', { dark: new Color(new RGBA(124, 124, 124, 0.3)), light: new Color(new RGBA(10, 50, 100, 0.2)), hcDark: new Color(new RGBA(124, 124, 124, 0.3)), hcLight: new Color(new RGBA(10, 50, 100, 0.2)) }, localize('snippetTabstopHighlightBackground', "Highlight background color of a snippet tabstop."));
const snippetTabstopHighlightBorder = registerColor('editor.snippetTabstopHighlightBorder', { dark: null, light: null, hcDark: null, hcLight: null }, localize('snippetTabstopHighlightBorder', "Highlight border color of a snippet tabstop."));
const snippetFinalTabstopHighlightBackground = registerColor('editor.snippetFinalTabstopHighlightBackground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('snippetFinalTabstopHighlightBackground', "Highlight background color of the final tabstop of a snippet."));
const snippetFinalTabstopHighlightBorder = registerColor('editor.snippetFinalTabstopHighlightBorder', { dark: '#525252', light: new Color(new RGBA(10, 50, 100, 0.5)), hcDark: '#525252', hcLight: '#292929' }, localize('snippetFinalTabstopHighlightBorder', "Highlight border color of the final tabstop of a snippet."));
/**
 * Breadcrumb colors
 */
const breadcrumbsForeground = registerColor('breadcrumb.foreground', { light: transparent(foreground, 0.8), dark: transparent(foreground, 0.8), hcDark: transparent(foreground, 0.8), hcLight: transparent(foreground, 0.8) }, localize('breadcrumbsFocusForeground', "Color of focused breadcrumb items."));
const breadcrumbsBackground = registerColor('breadcrumb.background', { light: editorBackground, dark: editorBackground, hcDark: editorBackground, hcLight: editorBackground }, localize('breadcrumbsBackground', "Background color of breadcrumb items."));
const breadcrumbsFocusForeground = registerColor('breadcrumb.focusForeground', { light: darken(foreground, 0.2), dark: lighten(foreground, 0.1), hcDark: lighten(foreground, 0.1), hcLight: lighten(foreground, 0.1) }, localize('breadcrumbsFocusForeground', "Color of focused breadcrumb items."));
const breadcrumbsActiveSelectionForeground = registerColor('breadcrumb.activeSelectionForeground', { light: darken(foreground, 0.2), dark: lighten(foreground, 0.1), hcDark: lighten(foreground, 0.1), hcLight: lighten(foreground, 0.1) }, localize('breadcrumbsSelectedForeground', "Color of selected breadcrumb items."));
const breadcrumbsPickerBackground = registerColor('breadcrumbPicker.background', { light: editorWidgetBackground, dark: editorWidgetBackground, hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize('breadcrumbsSelectedBackground', "Background color of breadcrumb item picker."));
/**
 * Merge-conflict colors
 */
const headerTransparency = 0.5;
const currentBaseColor = Color.fromHex('#40C8AE').transparent(headerTransparency);
const incomingBaseColor = Color.fromHex('#40A6FF').transparent(headerTransparency);
const commonBaseColor = Color.fromHex('#606060').transparent(0.4);
const contentTransparency = 0.4;
const rulerTransparency = 1;
const mergeCurrentHeaderBackground = registerColor('merge.currentHeaderBackground', { dark: currentBaseColor, light: currentBaseColor, hcDark: null, hcLight: null }, localize('mergeCurrentHeaderBackground', 'Current header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
const mergeCurrentContentBackground = registerColor('merge.currentContentBackground', { dark: transparent(mergeCurrentHeaderBackground, contentTransparency), light: transparent(mergeCurrentHeaderBackground, contentTransparency), hcDark: transparent(mergeCurrentHeaderBackground, contentTransparency), hcLight: transparent(mergeCurrentHeaderBackground, contentTransparency) }, localize('mergeCurrentContentBackground', 'Current content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
const mergeIncomingHeaderBackground = registerColor('merge.incomingHeaderBackground', { dark: incomingBaseColor, light: incomingBaseColor, hcDark: null, hcLight: null }, localize('mergeIncomingHeaderBackground', 'Incoming header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
const mergeIncomingContentBackground = registerColor('merge.incomingContentBackground', { dark: transparent(mergeIncomingHeaderBackground, contentTransparency), light: transparent(mergeIncomingHeaderBackground, contentTransparency), hcDark: transparent(mergeIncomingHeaderBackground, contentTransparency), hcLight: transparent(mergeIncomingHeaderBackground, contentTransparency) }, localize('mergeIncomingContentBackground', 'Incoming content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
const mergeCommonHeaderBackground = registerColor('merge.commonHeaderBackground', { dark: commonBaseColor, light: commonBaseColor, hcDark: null, hcLight: null }, localize('mergeCommonHeaderBackground', 'Common ancestor header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
const mergeCommonContentBackground = registerColor('merge.commonContentBackground', { dark: transparent(mergeCommonHeaderBackground, contentTransparency), light: transparent(mergeCommonHeaderBackground, contentTransparency), hcDark: transparent(mergeCommonHeaderBackground, contentTransparency), hcLight: transparent(mergeCommonHeaderBackground, contentTransparency) }, localize('mergeCommonContentBackground', 'Common ancestor content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations.'), true);
const mergeBorder = registerColor('merge.border', { dark: null, light: null, hcDark: '#C3DF6F', hcLight: '#007ACC' }, localize('mergeBorder', 'Border color on headers and the splitter in inline merge-conflicts.'));
const overviewRulerCurrentContentForeground = registerColor('editorOverviewRuler.currentContentForeground', { dark: transparent(mergeCurrentHeaderBackground, rulerTransparency), light: transparent(mergeCurrentHeaderBackground, rulerTransparency), hcDark: mergeBorder, hcLight: mergeBorder }, localize('overviewRulerCurrentContentForeground', 'Current overview ruler foreground for inline merge-conflicts.'));
const overviewRulerIncomingContentForeground = registerColor('editorOverviewRuler.incomingContentForeground', { dark: transparent(mergeIncomingHeaderBackground, rulerTransparency), light: transparent(mergeIncomingHeaderBackground, rulerTransparency), hcDark: mergeBorder, hcLight: mergeBorder }, localize('overviewRulerIncomingContentForeground', 'Incoming overview ruler foreground for inline merge-conflicts.'));
const overviewRulerCommonContentForeground = registerColor('editorOverviewRuler.commonContentForeground', { dark: transparent(mergeCommonHeaderBackground, rulerTransparency), light: transparent(mergeCommonHeaderBackground, rulerTransparency), hcDark: mergeBorder, hcLight: mergeBorder }, localize('overviewRulerCommonContentForeground', 'Common ancestor overview ruler foreground for inline merge-conflicts.'));
const overviewRulerFindMatchForeground = registerColor('editorOverviewRuler.findMatchForeground', { dark: '#d186167e', light: '#d186167e', hcDark: '#AB5A00', hcLight: '' }, localize('overviewRulerFindMatchForeground', 'Overview ruler marker color for find matches. The color must not be opaque so as not to hide underlying decorations.'), true);
const overviewRulerSelectionHighlightForeground = registerColor('editorOverviewRuler.selectionHighlightForeground', { dark: '#A0A0A0CC', light: '#A0A0A0CC', hcDark: '#A0A0A0CC', hcLight: '#A0A0A0CC' }, localize('overviewRulerSelectionHighlightForeground', 'Overview ruler marker color for selection highlights. The color must not be opaque so as not to hide underlying decorations.'), true);
const minimapFindMatch = registerColor('minimap.findMatchHighlight', { light: '#d18616', dark: '#d18616', hcDark: '#AB5A00', hcLight: '#0F4A85' }, localize('minimapFindMatchHighlight', 'Minimap marker color for find matches.'), true);
const minimapSelectionOccurrenceHighlight = registerColor('minimap.selectionOccurrenceHighlight', { light: '#c9c9c9', dark: '#676767', hcDark: '#ffffff', hcLight: '#0F4A85' }, localize('minimapSelectionOccurrenceHighlight', 'Minimap marker color for repeating editor selections.'), true);
const minimapSelection = registerColor('minimap.selectionHighlight', { light: '#ADD6FF', dark: '#264F78', hcDark: '#ffffff', hcLight: '#0F4A85' }, localize('minimapSelectionHighlight', 'Minimap marker color for the editor selection.'), true);
const minimapError = registerColor('minimap.errorHighlight', { dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hcDark: new Color(new RGBA(255, 50, 50, 1)), hcLight: '#B5200D' }, localize('minimapError', 'Minimap marker color for errors.'));
const minimapWarning = registerColor('minimap.warningHighlight', { dark: editorWarningForeground, light: editorWarningForeground, hcDark: editorWarningBorder, hcLight: editorWarningBorder }, localize('overviewRuleWarning', 'Minimap marker color for warnings.'));
const minimapBackground = registerColor('minimap.background', { dark: null, light: null, hcDark: null, hcLight: null }, localize('minimapBackground', "Minimap background color."));
const minimapForegroundOpacity = registerColor('minimap.foregroundOpacity', { dark: Color.fromHex('#000f'), light: Color.fromHex('#000f'), hcDark: Color.fromHex('#000f'), hcLight: Color.fromHex('#000f') }, localize('minimapForegroundOpacity', 'Opacity of foreground elements rendered in the minimap. For example, "#000000c0" will render the elements with 75% opacity.'));
const minimapSliderBackground = registerColor('minimapSlider.background', { light: transparent(scrollbarSliderBackground, 0.5), dark: transparent(scrollbarSliderBackground, 0.5), hcDark: transparent(scrollbarSliderBackground, 0.5), hcLight: transparent(scrollbarSliderBackground, 0.5) }, localize('minimapSliderBackground', "Minimap slider background color."));
const minimapSliderHoverBackground = registerColor('minimapSlider.hoverBackground', { light: transparent(scrollbarSliderHoverBackground, 0.5), dark: transparent(scrollbarSliderHoverBackground, 0.5), hcDark: transparent(scrollbarSliderHoverBackground, 0.5), hcLight: transparent(scrollbarSliderHoverBackground, 0.5) }, localize('minimapSliderHoverBackground', "Minimap slider background color when hovering."));
const minimapSliderActiveBackground = registerColor('minimapSlider.activeBackground', { light: transparent(scrollbarSliderActiveBackground, 0.5), dark: transparent(scrollbarSliderActiveBackground, 0.5), hcDark: transparent(scrollbarSliderActiveBackground, 0.5), hcLight: transparent(scrollbarSliderActiveBackground, 0.5) }, localize('minimapSliderActiveBackground', "Minimap slider background color when clicked on."));
const problemsErrorIconForeground = registerColor('problemsErrorIcon.foreground', { dark: editorErrorForeground, light: editorErrorForeground, hcDark: editorErrorForeground, hcLight: editorErrorForeground }, localize('problemsErrorIconForeground', "The color used for the problems error icon."));
const problemsWarningIconForeground = registerColor('problemsWarningIcon.foreground', { dark: editorWarningForeground, light: editorWarningForeground, hcDark: editorWarningForeground, hcLight: editorWarningForeground }, localize('problemsWarningIconForeground', "The color used for the problems warning icon."));
const problemsInfoIconForeground = registerColor('problemsInfoIcon.foreground', { dark: editorInfoForeground, light: editorInfoForeground, hcDark: editorInfoForeground, hcLight: editorInfoForeground }, localize('problemsInfoIconForeground', "The color used for the problems info icon."));
/**
 * Chart colors
 */
const chartsForeground = registerColor('charts.foreground', { dark: foreground, light: foreground, hcDark: foreground, hcLight: foreground }, localize('chartsForeground', "The foreground color used in charts."));
const chartsLines = registerColor('charts.lines', { dark: transparent(foreground, .5), light: transparent(foreground, .5), hcDark: transparent(foreground, .5), hcLight: transparent(foreground, .5) }, localize('chartsLines', "The color used for horizontal lines in charts."));
const chartsRed = registerColor('charts.red', { dark: editorErrorForeground, light: editorErrorForeground, hcDark: editorErrorForeground, hcLight: editorErrorForeground }, localize('chartsRed', "The red color used in chart visualizations."));
const chartsBlue = registerColor('charts.blue', { dark: editorInfoForeground, light: editorInfoForeground, hcDark: editorInfoForeground, hcLight: editorInfoForeground }, localize('chartsBlue', "The blue color used in chart visualizations."));
const chartsYellow = registerColor('charts.yellow', { dark: editorWarningForeground, light: editorWarningForeground, hcDark: editorWarningForeground, hcLight: editorWarningForeground }, localize('chartsYellow', "The yellow color used in chart visualizations."));
const chartsOrange = registerColor('charts.orange', { dark: minimapFindMatch, light: minimapFindMatch, hcDark: minimapFindMatch, hcLight: minimapFindMatch }, localize('chartsOrange', "The orange color used in chart visualizations."));
const chartsGreen = registerColor('charts.green', { dark: '#89D185', light: '#388A34', hcDark: '#89D185', hcLight: '#374e06' }, localize('chartsGreen', "The green color used in chart visualizations."));
const chartsPurple = registerColor('charts.purple', { dark: '#B180D7', light: '#652D90', hcDark: '#B180D7', hcLight: '#652D90' }, localize('chartsPurple', "The purple color used in chart visualizations."));
// ----- color functions
function executeTransform(transform, theme) {
    var _a, _b, _c;
    switch (transform.op) {
        case 0 /* ColorTransformType.Darken */:
            return (_a = resolveColorValue(transform.value, theme)) === null || _a === void 0 ? void 0 : _a.darken(transform.factor);
        case 1 /* ColorTransformType.Lighten */:
            return (_b = resolveColorValue(transform.value, theme)) === null || _b === void 0 ? void 0 : _b.lighten(transform.factor);
        case 2 /* ColorTransformType.Transparent */:
            return (_c = resolveColorValue(transform.value, theme)) === null || _c === void 0 ? void 0 : _c.transparent(transform.factor);
        case 3 /* ColorTransformType.OneOf */:
            for (const candidate of transform.values) {
                const color = resolveColorValue(candidate, theme);
                if (color) {
                    return color;
                }
            }
            return undefined;
        case 5 /* ColorTransformType.IfDefinedThenElse */:
            return resolveColorValue(theme.defines(transform.if) ? transform.then : transform.else, theme);
        case 4 /* ColorTransformType.LessProminent */: {
            const from = resolveColorValue(transform.value, theme);
            if (!from) {
                return undefined;
            }
            const backgroundColor = resolveColorValue(transform.background, theme);
            if (!backgroundColor) {
                return from.transparent(transform.factor * transform.transparency);
            }
            return from.isDarkerThan(backgroundColor)
                ? Color.getLighterColor(from, backgroundColor, transform.factor).transparent(transform.transparency)
                : Color.getDarkerColor(from, backgroundColor, transform.factor).transparent(transform.transparency);
        }
        default:
            throw assertNever(transform);
    }
}
function darken(colorValue, factor) {
    return { op: 0 /* ColorTransformType.Darken */, value: colorValue, factor };
}
function lighten(colorValue, factor) {
    return { op: 1 /* ColorTransformType.Lighten */, value: colorValue, factor };
}
function transparent(colorValue, factor) {
    return { op: 2 /* ColorTransformType.Transparent */, value: colorValue, factor };
}
function oneOf(...colorValues) {
    return { op: 3 /* ColorTransformType.OneOf */, values: colorValues };
}
function ifDefinedThenElse(ifArg, thenArg, elseArg) {
    return { op: 5 /* ColorTransformType.IfDefinedThenElse */, if: ifArg, then: thenArg, else: elseArg };
}
function lessProminent(colorValue, backgroundColorValue, factor, transparency) {
    return { op: 4 /* ColorTransformType.LessProminent */, value: colorValue, background: backgroundColorValue, factor, transparency };
}
// ----- implementation
/**
 * @param colorValue Resolve a color value in the context of a theme
 */
function resolveColorValue(colorValue, theme) {
    if (colorValue === null) {
        return undefined;
    }
    else if (typeof colorValue === 'string') {
        if (colorValue[0] === '#') {
            return Color.fromHex(colorValue);
        }
        return theme.getColor(colorValue);
    }
    else if (colorValue instanceof Color) {
        return colorValue;
    }
    else if (typeof colorValue === 'object') {
        return executeTransform(colorValue, theme);
    }
    return undefined;
}
const workbenchColorsSchemaId = 'vscode://schemas/workbench-colors';
const schemaRegistry = Registry.as(jsonContributionRegistry_Extensions.JSONContribution);
schemaRegistry.registerSchema(workbenchColorsSchemaId, colorRegistry.getColorSchema());
const delayer = new RunOnceScheduler(() => schemaRegistry.notifySchemaChanged(workbenchColorsSchemaId), 200);
colorRegistry.onDidChangeSchema(() => {
    if (!delayer.isScheduled()) {
        delayer.schedule();
    }
});
// setTimeout(_ => console.log(colorRegistry.toString()), 5000);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/standaloneStrings.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

var AccessibilityHelpNLS;
(function (AccessibilityHelpNLS) {
    AccessibilityHelpNLS.noSelection = localize("noSelection", "No selection");
    AccessibilityHelpNLS.singleSelectionRange = localize("singleSelectionRange", "Line {0}, Column {1} ({2} selected)");
    AccessibilityHelpNLS.singleSelection = localize("singleSelection", "Line {0}, Column {1}");
    AccessibilityHelpNLS.multiSelectionRange = localize("multiSelectionRange", "{0} selections ({1} characters selected)");
    AccessibilityHelpNLS.multiSelection = localize("multiSelection", "{0} selections");
    AccessibilityHelpNLS.emergencyConfOn = localize("emergencyConfOn", "Now changing the setting `accessibilitySupport` to 'on'.");
    AccessibilityHelpNLS.openingDocs = localize("openingDocs", "Now opening the Editor Accessibility documentation page.");
    AccessibilityHelpNLS.readonlyDiffEditor = localize("readonlyDiffEditor", " in a read-only pane of a diff editor.");
    AccessibilityHelpNLS.editableDiffEditor = localize("editableDiffEditor", " in a pane of a diff editor.");
    AccessibilityHelpNLS.readonlyEditor = localize("readonlyEditor", " in a read-only code editor");
    AccessibilityHelpNLS.editableEditor = localize("editableEditor", " in a code editor");
    AccessibilityHelpNLS.changeConfigToOnMac = localize("changeConfigToOnMac", "To configure the editor to be optimized for usage with a Screen Reader press Command+E now.");
    AccessibilityHelpNLS.changeConfigToOnWinLinux = localize("changeConfigToOnWinLinux", "To configure the editor to be optimized for usage with a Screen Reader press Control+E now.");
    AccessibilityHelpNLS.auto_on = localize("auto_on", "The editor is configured to be optimized for usage with a Screen Reader.");
    AccessibilityHelpNLS.auto_off = localize("auto_off", "The editor is configured to never be optimized for usage with a Screen Reader, which is not the case at this time.");
    AccessibilityHelpNLS.tabFocusModeOnMsg = localize("tabFocusModeOnMsg", "Pressing Tab in the current editor will move focus to the next focusable element. Toggle this behavior by pressing {0}.");
    AccessibilityHelpNLS.tabFocusModeOnMsgNoKb = localize("tabFocusModeOnMsgNoKb", "Pressing Tab in the current editor will move focus to the next focusable element. The command {0} is currently not triggerable by a keybinding.");
    AccessibilityHelpNLS.tabFocusModeOffMsg = localize("tabFocusModeOffMsg", "Pressing Tab in the current editor will insert the tab character. Toggle this behavior by pressing {0}.");
    AccessibilityHelpNLS.tabFocusModeOffMsgNoKb = localize("tabFocusModeOffMsgNoKb", "Pressing Tab in the current editor will insert the tab character. The command {0} is currently not triggerable by a keybinding.");
    AccessibilityHelpNLS.openDocMac = localize("openDocMac", "Press Command+H now to open a browser window with more information related to editor accessibility.");
    AccessibilityHelpNLS.openDocWinLinux = localize("openDocWinLinux", "Press Control+H now to open a browser window with more information related to editor accessibility.");
    AccessibilityHelpNLS.outroMsg = localize("outroMsg", "You can dismiss this tooltip and return to the editor by pressing Escape or Shift+Escape.");
    AccessibilityHelpNLS.showAccessibilityHelpAction = localize("showAccessibilityHelpAction", "Show Accessibility Help");
})(AccessibilityHelpNLS || (AccessibilityHelpNLS = {}));
var InspectTokensNLS;
(function (InspectTokensNLS) {
    InspectTokensNLS.inspectTokensAction = localize('inspectTokens', "Developer: Inspect Tokens");
})(InspectTokensNLS || (InspectTokensNLS = {}));
var GoToLineNLS;
(function (GoToLineNLS) {
    GoToLineNLS.gotoLineActionLabel = localize('gotoLineActionLabel', "Go to Line/Column...");
})(GoToLineNLS || (GoToLineNLS = {}));
var QuickHelpNLS;
(function (QuickHelpNLS) {
    QuickHelpNLS.helpQuickAccessActionLabel = localize('helpQuickAccess', "Show all Quick Access Providers");
})(QuickHelpNLS || (QuickHelpNLS = {}));
var QuickCommandNLS;
(function (QuickCommandNLS) {
    QuickCommandNLS.quickCommandActionLabel = localize('quickCommandActionLabel', "Command Palette");
    QuickCommandNLS.quickCommandHelp = localize('quickCommandActionHelp', "Show And Run Commands");
})(QuickCommandNLS || (QuickCommandNLS = {}));
var QuickOutlineNLS;
(function (QuickOutlineNLS) {
    QuickOutlineNLS.quickOutlineActionLabel = localize('quickOutlineActionLabel', "Go to Symbol...");
    QuickOutlineNLS.quickOutlineByCategoryActionLabel = localize('quickOutlineByCategoryActionLabel', "Go to Symbol by Category...");
})(QuickOutlineNLS || (QuickOutlineNLS = {}));
var StandaloneCodeEditorNLS;
(function (StandaloneCodeEditorNLS) {
    StandaloneCodeEditorNLS.editorViewAccessibleLabel = localize('editorViewAccessibleLabel', "Editor content");
    StandaloneCodeEditorNLS.accessibilityHelpMessage = localize('accessibilityHelpMessage', "Press Alt+F1 for Accessibility Options.");
})(StandaloneCodeEditorNLS || (StandaloneCodeEditorNLS = {}));
var ToggleHighContrastNLS;
(function (ToggleHighContrastNLS) {
    ToggleHighContrastNLS.toggleHighContrast = localize('toggleHighContrast', "Toggle High Contrast Theme");
})(ToggleHighContrastNLS || (ToggleHighContrastNLS = {}));
var StandaloneServicesNLS;
(function (StandaloneServicesNLS) {
    StandaloneServicesNLS.bulkEditServiceSummary = localize('bulkEditServiceSummary', "Made {0} edits in {1} files");
})(StandaloneServicesNLS || (StandaloneServicesNLS = {}));

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var accessibilityHelp_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var accessibilityHelp_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};




















const CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE = new RawContextKey('accessibilityHelpWidgetVisible', false);
let AccessibilityHelpController = class AccessibilityHelpController extends Disposable {
    constructor(editor, instantiationService) {
        super();
        this._editor = editor;
        this._widget = this._register(instantiationService.createInstance(AccessibilityHelpWidget, this._editor));
    }
    static get(editor) {
        return editor.getContribution(AccessibilityHelpController.ID);
    }
    show() {
        this._widget.show();
    }
    hide() {
        this._widget.hide();
    }
};
AccessibilityHelpController.ID = 'editor.contrib.accessibilityHelpController';
AccessibilityHelpController = accessibilityHelp_decorate([
    accessibilityHelp_param(1, IInstantiationService)
], AccessibilityHelpController);
function getSelectionLabel(selections, charactersSelected) {
    if (!selections || selections.length === 0) {
        return AccessibilityHelpNLS.noSelection;
    }
    if (selections.length === 1) {
        if (charactersSelected) {
            return format(AccessibilityHelpNLS.singleSelectionRange, selections[0].positionLineNumber, selections[0].positionColumn, charactersSelected);
        }
        return format(AccessibilityHelpNLS.singleSelection, selections[0].positionLineNumber, selections[0].positionColumn);
    }
    if (charactersSelected) {
        return format(AccessibilityHelpNLS.multiSelectionRange, selections.length, charactersSelected);
    }
    if (selections.length > 0) {
        return format(AccessibilityHelpNLS.multiSelection, selections.length);
    }
    return '';
}
let AccessibilityHelpWidget = class AccessibilityHelpWidget extends Widget {
    constructor(editor, _contextKeyService, _keybindingService, _openerService) {
        super();
        this._contextKeyService = _contextKeyService;
        this._keybindingService = _keybindingService;
        this._openerService = _openerService;
        this._editor = editor;
        this._isVisibleKey = CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE.bindTo(this._contextKeyService);
        this._domNode = createFastDomNode(document.createElement('div'));
        this._domNode.setClassName('accessibilityHelpWidget');
        this._domNode.setDisplay('none');
        this._domNode.setAttribute('role', 'dialog');
        this._domNode.setAttribute('aria-hidden', 'true');
        this._contentDomNode = createFastDomNode(document.createElement('div'));
        this._contentDomNode.setAttribute('role', 'document');
        this._domNode.appendChild(this._contentDomNode);
        this._isVisible = false;
        this._register(this._editor.onDidLayoutChange(() => {
            if (this._isVisible) {
                this._layout();
            }
        }));
        // Intentionally not configurable!
        this._register(addStandardDisposableListener(this._contentDomNode.domNode, 'keydown', (e) => {
            if (!this._isVisible) {
                return;
            }
            if (e.equals(2048 /* KeyMod.CtrlCmd */ | 35 /* KeyCode.KeyE */)) {
                aria_alert(AccessibilityHelpNLS.emergencyConfOn);
                this._editor.updateOptions({
                    accessibilitySupport: 'on'
                });
                clearNode(this._contentDomNode.domNode);
                this._buildContent();
                this._contentDomNode.domNode.focus();
                e.preventDefault();
                e.stopPropagation();
            }
            if (e.equals(2048 /* KeyMod.CtrlCmd */ | 38 /* KeyCode.KeyH */)) {
                aria_alert(AccessibilityHelpNLS.openingDocs);
                let url = this._editor.getRawOptions().accessibilityHelpUrl;
                if (typeof url === 'undefined') {
                    url = 'https://go.microsoft.com/fwlink/?linkid=852450';
                }
                this._openerService.open(URI.parse(url));
                e.preventDefault();
                e.stopPropagation();
            }
        }));
        this.onblur(this._contentDomNode.domNode, () => {
            this.hide();
        });
        this._editor.addOverlayWidget(this);
    }
    dispose() {
        this._editor.removeOverlayWidget(this);
        super.dispose();
    }
    getId() {
        return AccessibilityHelpWidget.ID;
    }
    getDomNode() {
        return this._domNode.domNode;
    }
    getPosition() {
        return {
            preference: null
        };
    }
    show() {
        if (this._isVisible) {
            return;
        }
        this._isVisible = true;
        this._isVisibleKey.set(true);
        this._layout();
        this._domNode.setDisplay('block');
        this._domNode.setAttribute('aria-hidden', 'false');
        this._contentDomNode.domNode.tabIndex = 0;
        this._buildContent();
        this._contentDomNode.domNode.focus();
    }
    _descriptionForCommand(commandId, msg, noKbMsg) {
        const kb = this._keybindingService.lookupKeybinding(commandId);
        if (kb) {
            return format(msg, kb.getAriaLabel());
        }
        return format(noKbMsg, commandId);
    }
    _buildContent() {
        const options = this._editor.getOptions();
        const selections = this._editor.getSelections();
        let charactersSelected = 0;
        if (selections) {
            const model = this._editor.getModel();
            if (model) {
                selections.forEach((selection) => {
                    charactersSelected += model.getValueLengthInRange(selection);
                });
            }
        }
        let text = getSelectionLabel(selections, charactersSelected);
        if (options.get(56 /* EditorOption.inDiffEditor */)) {
            if (options.get(83 /* EditorOption.readOnly */)) {
                text += AccessibilityHelpNLS.readonlyDiffEditor;
            }
            else {
                text += AccessibilityHelpNLS.editableDiffEditor;
            }
        }
        else {
            if (options.get(83 /* EditorOption.readOnly */)) {
                text += AccessibilityHelpNLS.readonlyEditor;
            }
            else {
                text += AccessibilityHelpNLS.editableEditor;
            }
        }
        const turnOnMessage = (isMacintosh
            ? AccessibilityHelpNLS.changeConfigToOnMac
            : AccessibilityHelpNLS.changeConfigToOnWinLinux);
        switch (options.get(2 /* EditorOption.accessibilitySupport */)) {
            case 0 /* AccessibilitySupport.Unknown */:
                text += '\n\n - ' + turnOnMessage;
                break;
            case 2 /* AccessibilitySupport.Enabled */:
                text += '\n\n - ' + AccessibilityHelpNLS.auto_on;
                break;
            case 1 /* AccessibilitySupport.Disabled */:
                text += '\n\n - ' + AccessibilityHelpNLS.auto_off;
                text += ' ' + turnOnMessage;
                break;
        }
        if (options.get(132 /* EditorOption.tabFocusMode */)) {
            text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, AccessibilityHelpNLS.tabFocusModeOnMsg, AccessibilityHelpNLS.tabFocusModeOnMsgNoKb);
        }
        else {
            text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, AccessibilityHelpNLS.tabFocusModeOffMsg, AccessibilityHelpNLS.tabFocusModeOffMsgNoKb);
        }
        const openDocMessage = (isMacintosh
            ? AccessibilityHelpNLS.openDocMac
            : AccessibilityHelpNLS.openDocWinLinux);
        text += '\n\n - ' + openDocMessage;
        text += '\n\n' + AccessibilityHelpNLS.outroMsg;
        this._contentDomNode.domNode.appendChild(renderFormattedText(text));
        // Per https://www.w3.org/TR/wai-aria/roles#document, Authors SHOULD provide a title or label for documents
        this._contentDomNode.domNode.setAttribute('aria-label', text);
    }
    hide() {
        if (!this._isVisible) {
            return;
        }
        this._isVisible = false;
        this._isVisibleKey.reset();
        this._domNode.setDisplay('none');
        this._domNode.setAttribute('aria-hidden', 'true');
        this._contentDomNode.domNode.tabIndex = -1;
        clearNode(this._contentDomNode.domNode);
        this._editor.focus();
    }
    _layout() {
        const editorLayout = this._editor.getLayoutInfo();
        const w = Math.max(5, Math.min(AccessibilityHelpWidget.WIDTH, editorLayout.width - 40));
        const h = Math.max(5, Math.min(AccessibilityHelpWidget.HEIGHT, editorLayout.height - 40));
        this._domNode.setWidth(w);
        this._domNode.setHeight(h);
        const top = Math.round((editorLayout.height - h) / 2);
        this._domNode.setTop(top);
        const left = Math.round((editorLayout.width - w) / 2);
        this._domNode.setLeft(left);
    }
};
AccessibilityHelpWidget.ID = 'editor.contrib.accessibilityHelpWidget';
AccessibilityHelpWidget.WIDTH = 500;
AccessibilityHelpWidget.HEIGHT = 300;
AccessibilityHelpWidget = accessibilityHelp_decorate([
    accessibilityHelp_param(1, IContextKeyService),
    accessibilityHelp_param(2, IKeybindingService),
    accessibilityHelp_param(3, IOpenerService)
], AccessibilityHelpWidget);
class ShowAccessibilityHelpAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.showAccessibilityHelp',
            label: AccessibilityHelpNLS.showAccessibilityHelpAction,
            alias: 'Show Accessibility Help',
            precondition: undefined,
            kbOpts: {
                primary: 512 /* KeyMod.Alt */ | 59 /* KeyCode.F1 */,
                weight: 100 /* KeybindingWeight.EditorContrib */,
                linux: {
                    primary: 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 59 /* KeyCode.F1 */,
                    secondary: [512 /* KeyMod.Alt */ | 59 /* KeyCode.F1 */]
                }
            }
        });
    }
    run(accessor, editor) {
        const controller = AccessibilityHelpController.get(editor);
        if (controller) {
            controller.show();
        }
    }
}
registerEditorContribution(AccessibilityHelpController.ID, AccessibilityHelpController);
registerEditorAction(ShowAccessibilityHelpAction);
const AccessibilityHelpCommand = EditorCommand.bindToContribution(AccessibilityHelpController.get);
registerEditorCommand(new AccessibilityHelpCommand({
    id: 'closeAccessibilityHelp',
    precondition: CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE,
    handler: x => x.hide(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 100,
        kbExpr: EditorContextKeys.focus,
        primary: 9 /* KeyCode.Escape */,
        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
    }
}));
registerThemingParticipant((theme, collector) => {
    const widgetBackground = theme.getColor(editorWidgetBackground);
    if (widgetBackground) {
        collector.addRule(`.monaco-editor .accessibilityHelpWidget { background-color: ${widgetBackground}; }`);
    }
    const widgetForeground = theme.getColor(editorWidgetForeground);
    if (widgetForeground) {
        collector.addRule(`.monaco-editor .accessibilityHelpWidget { color: ${widgetForeground}; }`);
    }
    const widgetShadowColor = theme.getColor(widgetShadow);
    if (widgetShadowColor) {
        collector.addRule(`.monaco-editor .accessibilityHelpWidget { box-shadow: 0 2px 8px ${widgetShadowColor}; }`);
    }
    const hcBorder = theme.getColor(contrastBorder);
    if (hcBorder) {
        collector.addRule(`.monaco-editor .accessibilityHelpWidget { border: 2px solid ${hcBorder}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/base/common/map.js
var map_a, _b;

class StringIterator {
    constructor() {
        this._value = '';
        this._pos = 0;
    }
    reset(key) {
        this._value = key;
        this._pos = 0;
        return this;
    }
    next() {
        this._pos += 1;
        return this;
    }
    hasNext() {
        return this._pos < this._value.length - 1;
    }
    cmp(a) {
        const aCode = a.charCodeAt(0);
        const thisCode = this._value.charCodeAt(this._pos);
        return aCode - thisCode;
    }
    value() {
        return this._value[this._pos];
    }
}
class ConfigKeysIterator {
    constructor(_caseSensitive = true) {
        this._caseSensitive = _caseSensitive;
    }
    reset(key) {
        this._value = key;
        this._from = 0;
        this._to = 0;
        return this.next();
    }
    hasNext() {
        return this._to < this._value.length;
    }
    next() {
        // this._data = key.split(/[\\/]/).filter(s => !!s);
        this._from = this._to;
        let justSeps = true;
        for (; this._to < this._value.length; this._to++) {
            const ch = this._value.charCodeAt(this._to);
            if (ch === 46 /* CharCode.Period */) {
                if (justSeps) {
                    this._from++;
                }
                else {
                    break;
                }
            }
            else {
                justSeps = false;
            }
        }
        return this;
    }
    cmp(a) {
        return this._caseSensitive
            ? compareSubstring(a, this._value, 0, a.length, this._from, this._to)
            : compareSubstringIgnoreCase(a, this._value, 0, a.length, this._from, this._to);
    }
    value() {
        return this._value.substring(this._from, this._to);
    }
}
class PathIterator {
    constructor(_splitOnBackslash = true, _caseSensitive = true) {
        this._splitOnBackslash = _splitOnBackslash;
        this._caseSensitive = _caseSensitive;
    }
    reset(key) {
        this._from = 0;
        this._to = 0;
        this._value = key;
        this._valueLen = key.length;
        for (let pos = key.length - 1; pos >= 0; pos--, this._valueLen--) {
            const ch = this._value.charCodeAt(pos);
            if (!(ch === 47 /* CharCode.Slash */ || this._splitOnBackslash && ch === 92 /* CharCode.Backslash */)) {
                break;
            }
        }
        return this.next();
    }
    hasNext() {
        return this._to < this._valueLen;
    }
    next() {
        // this._data = key.split(/[\\/]/).filter(s => !!s);
        this._from = this._to;
        let justSeps = true;
        for (; this._to < this._valueLen; this._to++) {
            const ch = this._value.charCodeAt(this._to);
            if (ch === 47 /* CharCode.Slash */ || this._splitOnBackslash && ch === 92 /* CharCode.Backslash */) {
                if (justSeps) {
                    this._from++;
                }
                else {
                    break;
                }
            }
            else {
                justSeps = false;
            }
        }
        return this;
    }
    cmp(a) {
        return this._caseSensitive
            ? compareSubstring(a, this._value, 0, a.length, this._from, this._to)
            : compareSubstringIgnoreCase(a, this._value, 0, a.length, this._from, this._to);
    }
    value() {
        return this._value.substring(this._from, this._to);
    }
}
class UriIterator {
    constructor(_ignorePathCasing, _ignoreQueryAndFragment) {
        this._ignorePathCasing = _ignorePathCasing;
        this._ignoreQueryAndFragment = _ignoreQueryAndFragment;
        this._states = [];
        this._stateIdx = 0;
    }
    reset(key) {
        this._value = key;
        this._states = [];
        if (this._value.scheme) {
            this._states.push(1 /* UriIteratorState.Scheme */);
        }
        if (this._value.authority) {
            this._states.push(2 /* UriIteratorState.Authority */);
        }
        if (this._value.path) {
            this._pathIterator = new PathIterator(false, !this._ignorePathCasing(key));
            this._pathIterator.reset(key.path);
            if (this._pathIterator.value()) {
                this._states.push(3 /* UriIteratorState.Path */);
            }
        }
        if (!this._ignoreQueryAndFragment(key)) {
            if (this._value.query) {
                this._states.push(4 /* UriIteratorState.Query */);
            }
            if (this._value.fragment) {
                this._states.push(5 /* UriIteratorState.Fragment */);
            }
        }
        this._stateIdx = 0;
        return this;
    }
    next() {
        if (this._states[this._stateIdx] === 3 /* UriIteratorState.Path */ && this._pathIterator.hasNext()) {
            this._pathIterator.next();
        }
        else {
            this._stateIdx += 1;
        }
        return this;
    }
    hasNext() {
        return (this._states[this._stateIdx] === 3 /* UriIteratorState.Path */ && this._pathIterator.hasNext())
            || this._stateIdx < this._states.length - 1;
    }
    cmp(a) {
        if (this._states[this._stateIdx] === 1 /* UriIteratorState.Scheme */) {
            return compareIgnoreCase(a, this._value.scheme);
        }
        else if (this._states[this._stateIdx] === 2 /* UriIteratorState.Authority */) {
            return compareIgnoreCase(a, this._value.authority);
        }
        else if (this._states[this._stateIdx] === 3 /* UriIteratorState.Path */) {
            return this._pathIterator.cmp(a);
        }
        else if (this._states[this._stateIdx] === 4 /* UriIteratorState.Query */) {
            return compare(a, this._value.query);
        }
        else if (this._states[this._stateIdx] === 5 /* UriIteratorState.Fragment */) {
            return compare(a, this._value.fragment);
        }
        throw new Error();
    }
    value() {
        if (this._states[this._stateIdx] === 1 /* UriIteratorState.Scheme */) {
            return this._value.scheme;
        }
        else if (this._states[this._stateIdx] === 2 /* UriIteratorState.Authority */) {
            return this._value.authority;
        }
        else if (this._states[this._stateIdx] === 3 /* UriIteratorState.Path */) {
            return this._pathIterator.value();
        }
        else if (this._states[this._stateIdx] === 4 /* UriIteratorState.Query */) {
            return this._value.query;
        }
        else if (this._states[this._stateIdx] === 5 /* UriIteratorState.Fragment */) {
            return this._value.fragment;
        }
        throw new Error();
    }
}
class TernarySearchTreeNode {
    constructor() {
        this.height = 1;
    }
    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() {
        var _c, _d;
        return (_d = (_c = this.left) === null || _c === void 0 ? void 0 : _c.height) !== null && _d !== void 0 ? _d : 0;
    }
    get heightRight() {
        var _c, _d;
        return (_d = (_c = this.right) === null || _c === void 0 ? void 0 : _c.height) !== null && _d !== void 0 ? _d : 0;
    }
}
class map_TernarySearchTree {
    constructor(segments) {
        this._iter = segments;
    }
    static forUris(ignorePathCasing = () => false, ignoreQueryAndFragment = () => false) {
        return new map_TernarySearchTree(new UriIterator(ignorePathCasing, ignoreQueryAndFragment));
    }
    static forStrings() {
        return new map_TernarySearchTree(new StringIterator());
    }
    static forConfigKeys() {
        return new map_TernarySearchTree(new ConfigKeysIterator());
    }
    clear() {
        this._root = undefined;
    }
    set(key, element) {
        const iter = this._iter.reset(key);
        let node;
        if (!this._root) {
            this._root = new TernarySearchTreeNode();
            this._root.segment = iter.value();
        }
        const stack = [];
        // find insert_node
        node = this._root;
        while (true) {
            const val = iter.cmp(node.segment);
            if (val > 0) {
                // left
                if (!node.left) {
                    node.left = new TernarySearchTreeNode();
                    node.left.segment = iter.value();
                }
                stack.push([-1 /* Dir.Left */, node]);
                node = node.left;
            }
            else if (val < 0) {
                // right
                if (!node.right) {
                    node.right = new TernarySearchTreeNode();
                    node.right.segment = iter.value();
                }
                stack.push([1 /* Dir.Right */, node]);
                node = node.right;
            }
            else if (iter.hasNext()) {
                // mid
                iter.next();
                if (!node.mid) {
                    node.mid = new TernarySearchTreeNode();
                    node.mid.segment = iter.value();
                }
                stack.push([0 /* Dir.Mid */, node]);
                node = node.mid;
            }
            else {
                break;
            }
        }
        // set value
        const oldElement = node.value;
        node.value = element;
        node.key = key;
        // balance
        for (let i = stack.length - 1; i >= 0; i--) {
            const node = stack[i][1];
            node.updateHeight();
            const bf = node.balanceFactor();
            if (bf < -1 || bf > 1) {
                // needs rotate
                const d1 = stack[i][0];
                const d2 = stack[i + 1][0];
                if (d1 === 1 /* Dir.Right */ && d2 === 1 /* Dir.Right */) {
                    //right, right -> rotate left
                    stack[i][1] = node.rotateLeft();
                }
                else if (d1 === -1 /* Dir.Left */ && d2 === -1 /* Dir.Left */) {
                    // left, left -> rotate right
                    stack[i][1] = node.rotateRight();
                }
                else if (d1 === 1 /* Dir.Right */ && d2 === -1 /* Dir.Left */) {
                    // right, left -> double rotate right, left
                    node.right = stack[i + 1][1] = stack[i + 1][1].rotateRight();
                    stack[i][1] = node.rotateLeft();
                }
                else if (d1 === -1 /* Dir.Left */ && d2 === 1 /* Dir.Right */) {
                    // left, right -> double rotate left, right
                    node.left = stack[i + 1][1] = stack[i + 1][1].rotateLeft();
                    stack[i][1] = node.rotateRight();
                }
                else {
                    throw new Error();
                }
                // patch path to parent
                if (i > 0) {
                    switch (stack[i - 1][0]) {
                        case -1 /* Dir.Left */:
                            stack[i - 1][1].left = stack[i][1];
                            break;
                        case 1 /* Dir.Right */:
                            stack[i - 1][1].right = stack[i][1];
                            break;
                        case 0 /* Dir.Mid */:
                            stack[i - 1][1].mid = stack[i][1];
                            break;
                    }
                }
                else {
                    this._root = stack[0][1];
                }
            }
        }
        return oldElement;
    }
    get(key) {
        var _c;
        return (_c = this._getNode(key)) === null || _c === void 0 ? void 0 : _c.value;
    }
    _getNode(key) {
        const iter = this._iter.reset(key);
        let node = this._root;
        while (node) {
            const val = iter.cmp(node.segment);
            if (val > 0) {
                // left
                node = node.left;
            }
            else if (val < 0) {
                // right
                node = node.right;
            }
            else if (iter.hasNext()) {
                // mid
                iter.next();
                node = node.mid;
            }
            else {
                break;
            }
        }
        return node;
    }
    has(key) {
        const node = this._getNode(key);
        return !((node === null || node === void 0 ? void 0 : node.value) === undefined && (node === null || node === void 0 ? void 0 : node.mid) === undefined);
    }
    delete(key) {
        return this._delete(key, false);
    }
    deleteSuperstr(key) {
        return this._delete(key, true);
    }
    _delete(key, superStr) {
        var _c;
        const iter = this._iter.reset(key);
        const stack = [];
        let node = this._root;
        // find node
        while (node) {
            const val = iter.cmp(node.segment);
            if (val > 0) {
                // left
                stack.push([-1 /* Dir.Left */, node]);
                node = node.left;
            }
            else if (val < 0) {
                // right
                stack.push([1 /* Dir.Right */, node]);
                node = node.right;
            }
            else if (iter.hasNext()) {
                // mid
                iter.next();
                stack.push([0 /* Dir.Mid */, node]);
                node = node.mid;
            }
            else {
                break;
            }
        }
        if (!node) {
            // node not found
            return;
        }
        if (superStr) {
            // removing children, reset height
            node.left = undefined;
            node.mid = undefined;
            node.right = undefined;
            node.height = 1;
        }
        else {
            // removing element
            node.key = undefined;
            node.value = undefined;
        }
        // BST node removal
        if (!node.mid && !node.value) {
            if (node.left && node.right) {
                // full node
                const min = this._min(node.right);
                const { key, value, segment } = min;
                this._delete(min.key, false);
                node.key = key;
                node.value = value;
                node.segment = segment;
            }
            else {
                // empty or half empty
                const newChild = (_c = node.left) !== null && _c !== void 0 ? _c : node.right;
                if (stack.length > 0) {
                    const [dir, parent] = stack[stack.length - 1];
                    switch (dir) {
                        case -1 /* Dir.Left */:
                            parent.left = newChild;
                            break;
                        case 0 /* Dir.Mid */:
                            parent.mid = newChild;
                            break;
                        case 1 /* Dir.Right */:
                            parent.right = newChild;
                            break;
                    }
                }
                else {
                    this._root = newChild;
                }
            }
        }
        // AVL balance
        for (let i = stack.length - 1; i >= 0; i--) {
            const node = stack[i][1];
            node.updateHeight();
            const bf = node.balanceFactor();
            if (bf > 1) {
                // right heavy
                if (node.right.balanceFactor() >= 0) {
                    // right, right -> rotate left
                    stack[i][1] = node.rotateLeft();
                }
                else {
                    // right, left -> double rotate
                    node.right = node.right.rotateRight();
                    stack[i][1] = node.rotateLeft();
                }
            }
            else if (bf < -1) {
                // left heavy
                if (node.left.balanceFactor() <= 0) {
                    // left, left -> rotate right
                    stack[i][1] = node.rotateRight();
                }
                else {
                    // left, right -> double rotate
                    node.left = node.left.rotateLeft();
                    stack[i][1] = node.rotateRight();
                }
            }
            // patch path to parent
            if (i > 0) {
                switch (stack[i - 1][0]) {
                    case -1 /* Dir.Left */:
                        stack[i - 1][1].left = stack[i][1];
                        break;
                    case 1 /* Dir.Right */:
                        stack[i - 1][1].right = stack[i][1];
                        break;
                    case 0 /* Dir.Mid */:
                        stack[i - 1][1].mid = stack[i][1];
                        break;
                }
            }
            else {
                this._root = stack[0][1];
            }
        }
    }
    _min(node) {
        while (node.left) {
            node = node.left;
        }
        return node;
    }
    findSubstr(key) {
        const iter = this._iter.reset(key);
        let node = this._root;
        let candidate = undefined;
        while (node) {
            const val = iter.cmp(node.segment);
            if (val > 0) {
                // left
                node = node.left;
            }
            else if (val < 0) {
                // right
                node = node.right;
            }
            else if (iter.hasNext()) {
                // mid
                iter.next();
                candidate = node.value || candidate;
                node = node.mid;
            }
            else {
                break;
            }
        }
        return node && node.value || candidate;
    }
    findSuperstr(key) {
        const iter = this._iter.reset(key);
        let node = this._root;
        while (node) {
            const val = iter.cmp(node.segment);
            if (val > 0) {
                // left
                node = node.left;
            }
            else if (val < 0) {
                // right
                node = node.right;
            }
            else if (iter.hasNext()) {
                // mid
                iter.next();
                node = node.mid;
            }
            else {
                // collect
                if (!node.mid) {
                    return undefined;
                }
                else {
                    return this._entries(node.mid);
                }
            }
        }
        return undefined;
    }
    forEach(callback) {
        for (const [key, value] of this) {
            callback(value, key);
        }
    }
    *[Symbol.iterator]() {
        yield* this._entries(this._root);
    }
    _entries(node) {
        const result = [];
        this._dfsEntries(node, result);
        return result[Symbol.iterator]();
    }
    _dfsEntries(node, bucket) {
        // DFS
        if (!node) {
            return;
        }
        if (node.left) {
            this._dfsEntries(node.left, bucket);
        }
        if (node.value) {
            bucket.push([node.key, node.value]);
        }
        if (node.mid) {
            this._dfsEntries(node.mid, bucket);
        }
        if (node.right) {
            this._dfsEntries(node.right, bucket);
        }
    }
}
class ResourceMapEntry {
    constructor(uri, value) {
        this.uri = uri;
        this.value = value;
    }
}
class ResourceMap {
    constructor(mapOrKeyFn, toKey) {
        this[map_a] = 'ResourceMap';
        if (mapOrKeyFn instanceof ResourceMap) {
            this.map = new Map(mapOrKeyFn.map);
            this.toKey = toKey !== null && toKey !== void 0 ? toKey : ResourceMap.defaultToKey;
        }
        else {
            this.map = new Map();
            this.toKey = mapOrKeyFn !== null && mapOrKeyFn !== void 0 ? mapOrKeyFn : ResourceMap.defaultToKey;
        }
    }
    set(resource, value) {
        this.map.set(this.toKey(resource), new ResourceMapEntry(resource, value));
        return this;
    }
    get(resource) {
        var _c;
        return (_c = this.map.get(this.toKey(resource))) === null || _c === void 0 ? void 0 : _c.value;
    }
    has(resource) {
        return this.map.has(this.toKey(resource));
    }
    get size() {
        return this.map.size;
    }
    clear() {
        this.map.clear();
    }
    delete(resource) {
        return this.map.delete(this.toKey(resource));
    }
    forEach(clb, thisArg) {
        if (typeof thisArg !== 'undefined') {
            clb = clb.bind(thisArg);
        }
        for (const [_, entry] of this.map) {
            clb(entry.value, entry.uri, this);
        }
    }
    *values() {
        for (const entry of this.map.values()) {
            yield entry.value;
        }
    }
    *keys() {
        for (const entry of this.map.values()) {
            yield entry.uri;
        }
    }
    *entries() {
        for (const entry of this.map.values()) {
            yield [entry.uri, entry.value];
        }
    }
    *[(map_a = Symbol.toStringTag, Symbol.iterator)]() {
        for (const [, entry] of this.map) {
            yield [entry.uri, entry.value];
        }
    }
}
ResourceMap.defaultToKey = (resource) => resource.toString();
class LinkedMap {
    constructor() {
        this[_b] = 'LinkedMap';
        this._map = new Map();
        this._head = undefined;
        this._tail = undefined;
        this._size = 0;
        this._state = 0;
    }
    clear() {
        this._map.clear();
        this._head = undefined;
        this._tail = undefined;
        this._size = 0;
        this._state++;
    }
    isEmpty() {
        return !this._head && !this._tail;
    }
    get size() {
        return this._size;
    }
    get first() {
        var _c;
        return (_c = this._head) === null || _c === void 0 ? void 0 : _c.value;
    }
    get last() {
        var _c;
        return (_c = this._tail) === null || _c === void 0 ? void 0 : _c.value;
    }
    has(key) {
        return this._map.has(key);
    }
    get(key, touch = 0 /* Touch.None */) {
        const item = this._map.get(key);
        if (!item) {
            return undefined;
        }
        if (touch !== 0 /* Touch.None */) {
            this.touch(item, touch);
        }
        return item.value;
    }
    set(key, value, touch = 0 /* Touch.None */) {
        let item = this._map.get(key);
        if (item) {
            item.value = value;
            if (touch !== 0 /* Touch.None */) {
                this.touch(item, touch);
            }
        }
        else {
            item = { key, value, next: undefined, previous: undefined };
            switch (touch) {
                case 0 /* Touch.None */:
                    this.addItemLast(item);
                    break;
                case 1 /* Touch.AsOld */:
                    this.addItemFirst(item);
                    break;
                case 2 /* Touch.AsNew */:
                    this.addItemLast(item);
                    break;
                default:
                    this.addItemLast(item);
                    break;
            }
            this._map.set(key, item);
            this._size++;
        }
        return this;
    }
    delete(key) {
        return !!this.remove(key);
    }
    remove(key) {
        const item = this._map.get(key);
        if (!item) {
            return undefined;
        }
        this._map.delete(key);
        this.removeItem(item);
        this._size--;
        return item.value;
    }
    shift() {
        if (!this._head && !this._tail) {
            return undefined;
        }
        if (!this._head || !this._tail) {
            throw new Error('Invalid list');
        }
        const item = this._head;
        this._map.delete(item.key);
        this.removeItem(item);
        this._size--;
        return item.value;
    }
    forEach(callbackfn, thisArg) {
        const state = this._state;
        let current = this._head;
        while (current) {
            if (thisArg) {
                callbackfn.bind(thisArg)(current.value, current.key, this);
            }
            else {
                callbackfn(current.value, current.key, this);
            }
            if (this._state !== state) {
                throw new Error(`LinkedMap got modified during iteration.`);
            }
            current = current.next;
        }
    }
    keys() {
        const map = this;
        const state = this._state;
        let current = this._head;
        const iterator = {
            [Symbol.iterator]() {
                return iterator;
            },
            next() {
                if (map._state !== 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: undefined, done: true };
                }
            }
        };
        return iterator;
    }
    values() {
        const map = this;
        const state = this._state;
        let current = this._head;
        const iterator = {
            [Symbol.iterator]() {
                return iterator;
            },
            next() {
                if (map._state !== 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: undefined, done: true };
                }
            }
        };
        return iterator;
    }
    entries() {
        const map = this;
        const state = this._state;
        let current = this._head;
        const iterator = {
            [Symbol.iterator]() {
                return iterator;
            },
            next() {
                if (map._state !== 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: undefined, done: true };
                }
            }
        };
        return iterator;
    }
    [(_b = Symbol.toStringTag, Symbol.iterator)]() {
        return this.entries();
    }
    trimOld(newSize) {
        if (newSize >= this.size) {
            return;
        }
        if (newSize === 0) {
            this.clear();
            return;
        }
        let current = this._head;
        let currentSize = this.size;
        while (current && currentSize > newSize) {
            this._map.delete(current.key);
            current = current.next;
            currentSize--;
        }
        this._head = current;
        this._size = currentSize;
        if (current) {
            current.previous = undefined;
        }
        this._state++;
    }
    addItemFirst(item) {
        // First time Insert
        if (!this._head && !this._tail) {
            this._tail = item;
        }
        else if (!this._head) {
            throw new Error('Invalid list');
        }
        else {
            item.next = this._head;
            this._head.previous = item;
        }
        this._head = item;
        this._state++;
    }
    addItemLast(item) {
        // First time Insert
        if (!this._head && !this._tail) {
            this._head = item;
        }
        else if (!this._tail) {
            throw new Error('Invalid list');
        }
        else {
            item.previous = this._tail;
            this._tail.next = item;
        }
        this._tail = item;
        this._state++;
    }
    removeItem(item) {
        if (item === this._head && item === this._tail) {
            this._head = undefined;
            this._tail = undefined;
        }
        else if (item === this._head) {
            // This can only happen if size === 1 which is handled
            // by the case above.
            if (!item.next) {
                throw new Error('Invalid list');
            }
            item.next.previous = undefined;
            this._head = item.next;
        }
        else if (item === this._tail) {
            // This can only happen if size === 1 which is handled
            // by the case above.
            if (!item.previous) {
                throw new Error('Invalid list');
            }
            item.previous.next = undefined;
            this._tail = 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 = undefined;
        item.previous = undefined;
        this._state++;
    }
    touch(item, touch) {
        if (!this._head || !this._tail) {
            throw new Error('Invalid list');
        }
        if ((touch !== 1 /* Touch.AsOld */ && touch !== 2 /* Touch.AsNew */)) {
            return;
        }
        if (touch === 1 /* Touch.AsOld */) {
            if (item === this._head) {
                return;
            }
            const next = item.next;
            const previous = item.previous;
            // Unlink the item
            if (item === this._tail) {
                // previous must be defined since item was not head but is tail
                // So there are more than on item in the map
                previous.next = undefined;
                this._tail = previous;
            }
            else {
                // Both next and previous are not undefined since item was neither head nor tail.
                next.previous = previous;
                previous.next = next;
            }
            // Insert the node at head
            item.previous = undefined;
            item.next = this._head;
            this._head.previous = item;
            this._head = item;
            this._state++;
        }
        else if (touch === 2 /* Touch.AsNew */) {
            if (item === this._tail) {
                return;
            }
            const next = item.next;
            const previous = item.previous;
            // Unlink the item.
            if (item === this._head) {
                // next must be defined since item was not tail but is head
                // So there are more than on item in the map
                next.previous = undefined;
                this._head = next;
            }
            else {
                // Both next and previous are not undefined since item was neither head nor tail.
                next.previous = previous;
                previous.next = next;
            }
            item.next = undefined;
            item.previous = this._tail;
            this._tail.next = item;
            this._tail = item;
            this._state++;
        }
    }
    toJSON() {
        const data = [];
        this.forEach((value, key) => {
            data.push([key, value]);
        });
        return data;
    }
    fromJSON(data) {
        this.clear();
        for (const [key, value] of data) {
            this.set(key, value);
        }
    }
}
class LRUCache extends LinkedMap {
    constructor(limit, ratio = 1) {
        super();
        this._limit = limit;
        this._ratio = Math.min(Math.max(0, ratio), 1);
    }
    get limit() {
        return this._limit;
    }
    set limit(limit) {
        this._limit = limit;
        this.checkTrim();
    }
    get(key, touch = 2 /* Touch.AsNew */) {
        return super.get(key, touch);
    }
    peek(key) {
        return super.get(key, 0 /* Touch.None */);
    }
    set(key, value) {
        super.set(key, value, 2 /* Touch.AsNew */);
        this.checkTrim();
        return this;
    }
    checkTrim() {
        if (this.size > this._limit) {
            this.trimOld(Math.round(this._limit * this._ratio));
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/filters.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


// Combined filters
/**
 * @returns A filter which combines the provided set
 * of filters with an or. The *first* filters that
 * matches defined the return value of the returned
 * filter.
 */
function or(...filter) {
    return function (word, wordToMatchAgainst) {
        for (let i = 0, len = filter.length; i < len; i++) {
            const match = filter[i](word, wordToMatchAgainst);
            if (match) {
                return match;
            }
        }
        return null;
    };
}
// Prefix
const matchesStrictPrefix = _matchesPrefix.bind(undefined, false);
const matchesPrefix = _matchesPrefix.bind(undefined, true);
function _matchesPrefix(ignoreCase, word, wordToMatchAgainst) {
    if (!wordToMatchAgainst || wordToMatchAgainst.length < word.length) {
        return null;
    }
    let matches;
    if (ignoreCase) {
        matches = startsWithIgnoreCase(wordToMatchAgainst, word);
    }
    else {
        matches = wordToMatchAgainst.indexOf(word) === 0;
    }
    if (!matches) {
        return null;
    }
    return word.length > 0 ? [{ start: 0, end: word.length }] : [];
}
// Contiguous Substring
function matchesContiguousSubString(word, wordToMatchAgainst) {
    const index = wordToMatchAgainst.toLowerCase().indexOf(word.toLowerCase());
    if (index === -1) {
        return null;
    }
    return [{ start: index, end: index + word.length }];
}
// Substring
function matchesSubString(word, wordToMatchAgainst) {
    return _matchesSubString(word.toLowerCase(), wordToMatchAgainst.toLowerCase(), 0, 0);
}
function _matchesSubString(word, wordToMatchAgainst, i, j) {
    if (i === word.length) {
        return [];
    }
    else if (j === wordToMatchAgainst.length) {
        return null;
    }
    else {
        if (word[i] === wordToMatchAgainst[j]) {
            let result = null;
            if (result = _matchesSubString(word, wordToMatchAgainst, i + 1, j + 1)) {
                return join({ start: j, end: j + 1 }, result);
            }
            return null;
        }
        return _matchesSubString(word, wordToMatchAgainst, i, j + 1);
    }
}
// CamelCase
function isLower(code) {
    return 97 /* CharCode.a */ <= code && code <= 122 /* CharCode.z */;
}
function isUpper(code) {
    return 65 /* CharCode.A */ <= code && code <= 90 /* CharCode.Z */;
}
function filters_isNumber(code) {
    return 48 /* CharCode.Digit0 */ <= code && code <= 57 /* CharCode.Digit9 */;
}
function isWhitespace(code) {
    return (code === 32 /* CharCode.Space */
        || code === 9 /* CharCode.Tab */
        || code === 10 /* CharCode.LineFeed */
        || code === 13 /* CharCode.CarriageReturn */);
}
const wordSeparators = new Set();
// These are chosen as natural word separators based on writen text.
// It is a subset of the word separators used by the monaco editor.
'()[]{}<>`\'"-/;:,.?!'
    .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));
}
function isAlphanumeric(code) {
    return isLower(code) || isUpper(code) || filters_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 i = start; i < camelCaseWord.length; i++) {
        const c = camelCaseWord.charCodeAt(i);
        if (isUpper(c) || filters_isNumber(c) || (i > 0 && !isAlphanumeric(camelCaseWord.charCodeAt(i - 1)))) {
            return i;
        }
    }
    return camelCaseWord.length;
}
function _matchesCamelCase(word, camelCaseWord, i, j) {
    if (i === word.length) {
        return [];
    }
    else if (j === camelCaseWord.length) {
        return null;
    }
    else if (word[i] !== camelCaseWord[j].toLowerCase()) {
        return null;
    }
    else {
        let result = null;
        let nextUpperIndex = j + 1;
        result = _matchesCamelCase(word, camelCaseWord, i + 1, j + 1);
        while (!result && (nextUpperIndex = nextAnchor(camelCaseWord, nextUpperIndex)) < camelCaseWord.length) {
            result = _matchesCamelCase(word, camelCaseWord, i + 1, nextUpperIndex);
            nextUpperIndex++;
        }
        return result === null ? null : join({ start: j, end: j + 1 }, result);
    }
}
// Heuristic to avoid computing camel case matcher for words that don't
// look like camelCaseWords.
function analyzeCamelCaseWord(word) {
    let upper = 0, lower = 0, alpha = 0, numeric = 0, code = 0;
    for (let i = 0; i < word.length; i++) {
        code = word.charCodeAt(i);
        if (isUpper(code)) {
            upper++;
        }
        if (isLower(code)) {
            lower++;
        }
        if (isAlphanumeric(code)) {
            alpha++;
        }
        if (filters_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;
}
// Heuristic to avoid computing camel case matcher for words that don't
// look like camel case patterns.
function isCamelCasePattern(word) {
    let upper = 0, lower = 0, code = 0, whitespace = 0;
    for (let i = 0; i < word.length; i++) {
        code = word.charCodeAt(i);
        if (isUpper(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 matchesCamelCase(word, camelCaseWord) {
    if (!camelCaseWord) {
        return null;
    }
    camelCaseWord = camelCaseWord.trim();
    if (camelCaseWord.length === 0) {
        return null;
    }
    if (!isCamelCasePattern(word)) {
        return null;
    }
    if (camelCaseWord.length > 60) {
        return null;
    }
    const analysis = analyzeCamelCaseWord(camelCaseWord);
    if (!isCamelCaseWord(analysis)) {
        if (!isUpperCaseWord(analysis)) {
            return null;
        }
        camelCaseWord = camelCaseWord.toLowerCase();
    }
    let result = null;
    let i = 0;
    word = word.toLowerCase();
    while (i < camelCaseWord.length && (result = _matchesCamelCase(word, camelCaseWord, 0, i)) === null) {
        i = nextAnchor(camelCaseWord, i + 1);
    }
    return result;
}
// Matches beginning of words supporting non-ASCII languages
// If `contiguous` is true then matches word with beginnings of the words in the target. E.g. "pul" will match "Git: Pull"
// Otherwise also matches sub string of the word with beginnings of the words in the target. E.g. "gp" or "g p" will match "Git: Pull"
// Useful in cases where the target is words (e.g. command labels)
function matchesWords(word, target, contiguous = false) {
    if (!target || target.length === 0) {
        return null;
    }
    let result = null;
    let i = 0;
    word = word.toLowerCase();
    target = target.toLowerCase();
    while (i < target.length && (result = _matchesWords(word, target, 0, i, contiguous)) === null) {
        i = nextWord(target, i + 1);
    }
    return result;
}
function _matchesWords(word, target, i, j, contiguous) {
    if (i === word.length) {
        return [];
    }
    else if (j === target.length) {
        return null;
    }
    else if (!charactersMatch(word.charCodeAt(i), target.charCodeAt(j))) {
        return null;
    }
    else {
        let result = null;
        let nextWordIndex = j + 1;
        result = _matchesWords(word, target, i + 1, j + 1, contiguous);
        if (!contiguous) {
            while (!result && (nextWordIndex = nextWord(target, nextWordIndex)) < target.length) {
                result = _matchesWords(word, target, i + 1, nextWordIndex, contiguous);
                nextWordIndex++;
            }
        }
        return result === null ? null : join({ start: j, end: j + 1 }, result);
    }
}
function nextWord(word, start) {
    for (let i = start; i < word.length; i++) {
        if (isWordSeparator(word.charCodeAt(i)) ||
            (i > 0 && isWordSeparator(word.charCodeAt(i - 1)))) {
            return i;
        }
    }
    return word.length;
}
// Fuzzy
const fuzzyContiguousFilter = or(matchesPrefix, matchesCamelCase, matchesContiguousSubString);
const fuzzySeparateFilter = or(matchesPrefix, matchesCamelCase, matchesSubString);
const fuzzyRegExpCache = new LRUCache(10000); // bounded to 10000 elements
function matchesFuzzy(word, wordToMatchAgainst, enableSeparateSubstringMatching = false) {
    if (typeof word !== 'string' || typeof wordToMatchAgainst !== 'string') {
        return null; // return early for invalid input
    }
    // Form RegExp for wildcard matches
    let regexp = fuzzyRegExpCache.get(word);
    if (!regexp) {
        regexp = new RegExp(convertSimple2RegExpPattern(word), 'i');
        fuzzyRegExpCache.set(word, regexp);
    }
    // RegExp Filter
    const match = regexp.exec(wordToMatchAgainst);
    if (match) {
        return [{ start: match.index, end: match.index + match[0].length }];
    }
    // Default Filter
    return enableSeparateSubstringMatching ? fuzzySeparateFilter(word, wordToMatchAgainst) : fuzzyContiguousFilter(word, wordToMatchAgainst);
}
function anyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos) {
    const max = Math.min(13, pattern.length);
    for (; patternPos < max; patternPos++) {
        const result = fuzzyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos, { firstMatchCanBeWeak: false, boostFullMatch: true });
        if (result) {
            return result;
        }
    }
    return [0, wordPos];
}
//#region --- fuzzyScore ---
function createMatches(score) {
    if (typeof score === 'undefined') {
        return [];
    }
    const res = [];
    const wordPos = score[1];
    for (let i = score.length - 1; i > 1; i--) {
        const pos = score[i] + 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;
}
const _maxLen = 128;
function initTable() {
    const table = [];
    const row = [];
    for (let i = 0; i <= _maxLen; i++) {
        row[i] = 0;
    }
    for (let i = 0; i <= _maxLen; i++) {
        table.push(row.slice(0));
    }
    return table;
}
function initArr(maxLen) {
    const row = [];
    for (let i = 0; i <= maxLen; i++) {
        row[i] = 0;
    }
    return row;
}
const _minWordMatchPos = initArr(2 * _maxLen); // min word position for a certain pattern position
const _maxWordMatchPos = initArr(2 * _maxLen); // max word position for a certain pattern position
const _diag = initTable(); // the length of a contiguous diagonal match
const _table = initTable();
const _arrows = initTable();
const _debug = false;
function printTable(table, pattern, patternLen, word, wordLen) {
    function pad(s, n, pad = ' ') {
        while (s.length < n) {
            s = pad + s;
        }
        return s;
    }
    let ret = ` |   |${word.split('').map(c => pad(c, 3)).join('|')}\n`;
    for (let i = 0; i <= patternLen; i++) {
        if (i === 0) {
            ret += ' |';
        }
        else {
            ret += `${pattern[i - 1]}|`;
        }
        ret += table[i].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 /* CharCode.Underline */:
        case 45 /* CharCode.Dash */:
        case 46 /* CharCode.Period */:
        case 32 /* CharCode.Space */:
        case 47 /* CharCode.Slash */:
        case 92 /* CharCode.Backslash */:
        case 39 /* CharCode.SingleQuote */:
        case 34 /* CharCode.DoubleQuote */:
        case 58 /* CharCode.Colon */:
        case 36 /* CharCode.DollarSign */:
        case 60 /* CharCode.LessThan */:
        case 62 /* CharCode.GreaterThan */:
        case 40 /* CharCode.OpenParen */:
        case 41 /* CharCode.CloseParen */:
        case 91 /* CharCode.OpenSquareBracket */:
        case 93 /* CharCode.CloseSquareBracket */:
        case 123 /* CharCode.OpenCurlyBrace */:
        case 125 /* CharCode.CloseCurlyBrace */:
            return true;
        case undefined:
            return false;
        default:
            if (isEmojiImprecise(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 /* CharCode.Space */:
        case 9 /* CharCode.Tab */:
            return true;
        default:
            return false;
    }
}
function isUpperCaseAtPos(pos, word, wordLow) {
    return word[pos] !== wordLow[pos];
}
function isPatternInWord(patternLow, patternPos, patternLen, wordLow, wordPos, wordLen, fillMinWordPosArr = false) {
    while (patternPos < patternLen && wordPos < wordLen) {
        if (patternLow[patternPos] === wordLow[wordPos]) {
            if (fillMinWordPosArr) {
                // Remember the min word position for each pattern position
                _minWordMatchPos[patternPos] = wordPos;
            }
            patternPos += 1;
        }
        wordPos += 1;
    }
    return patternPos === patternLen; // pattern must be exhausted
}
var FuzzyScore;
(function (FuzzyScore) {
    /**
     * No matches and value `-100`
     */
    FuzzyScore.Default = ([-100, 0]);
    function isDefault(score) {
        return !score || (score.length === 2 && score[0] === -100 && score[1] === 0);
    }
    FuzzyScore.isDefault = isDefault;
})(FuzzyScore || (FuzzyScore = {}));
class FuzzyScoreOptions {
    constructor(firstMatchCanBeWeak, boostFullMatch) {
        this.firstMatchCanBeWeak = firstMatchCanBeWeak;
        this.boostFullMatch = boostFullMatch;
    }
}
FuzzyScoreOptions.default = { boostFullMatch: true, firstMatchCanBeWeak: false };
function fuzzyScore(pattern, patternLow, patternStart, word, wordLow, wordStart, options = FuzzyScoreOptions.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 undefined;
    }
    // Run a simple check if the characters of pattern occur
    // (in order) at all in word. If that isn't the case we
    // stop because no match will be possible
    if (!isPatternInWord(patternLow, patternStart, patternLen, wordLow, wordStart, wordLen, true)) {
        return undefined;
    }
    // Find the max matching word position for each pattern position
    // NOTE: the min matching word position was filled in above, in the `isPatternInWord` call
    _fillInMaxWordMatchPos(patternLen, wordLen, patternStart, wordStart, patternLow, wordLow);
    let row = 1;
    let column = 1;
    let patternPos = patternStart;
    let wordPos = wordStart;
    const hasStrongFirstMatch = [false];
    // There will be a match, fill in tables
    for (row = 1, patternPos = patternStart; patternPos < patternLen; row++, patternPos++) {
        // Reduce search space to possible matching word positions and to possible access from next row
        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 score = Number.MIN_SAFE_INTEGER;
            let canComeDiag = false;
            if (wordPos <= maxWordMatchPos) {
                score = _doScore(pattern, patternLow, patternPos, patternStart, word, wordLow, wordPos, wordLen, wordStart, _diag[row - 1][column - 1] === 0, hasStrongFirstMatch);
            }
            let diagScore = 0;
            if (score !== Number.MAX_SAFE_INTEGER) {
                canComeDiag = true;
                diagScore = score + _table[row - 1][column - 1];
            }
            const canComeLeft = wordPos > minWordMatchPos;
            const leftScore = canComeLeft ? _table[row][column - 1] + (_diag[row][column - 1] > 0 ? -5 : 0) : 0; // penalty for a gap start
            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; // penalty for a gap start
            if (canComeLeftLeft && (!canComeLeft || leftLeftScore >= leftScore) && (!canComeDiag || leftLeftScore >= diagScore)) {
                // always prefer choosing left left to jump over a diagonal because that means a match is earlier in the word
                _table[row][column] = leftLeftScore;
                _arrows[row][column] = 3 /* Arrow.LeftLeft */;
                _diag[row][column] = 0;
            }
            else if (canComeLeft && (!canComeDiag || leftScore >= diagScore)) {
                // always prefer choosing left since that means a match is earlier in the word
                _table[row][column] = leftScore;
                _arrows[row][column] = 2 /* Arrow.Left */;
                _diag[row][column] = 0;
            }
            else if (canComeDiag) {
                _table[row][column] = diagScore;
                _arrows[row][column] = 1 /* Arrow.Diag */;
                _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] && !options.firstMatchCanBeWeak) {
        return undefined;
    }
    row--;
    column--;
    const result = [_table[row][column], wordStart];
    let backwardsDiagLength = 0;
    let maxMatchColumn = 0;
    while (row >= 1) {
        // Find the column where we go diagonally up
        let diagColumn = column;
        do {
            const arrow = _arrows[row][diagColumn];
            if (arrow === 3 /* Arrow.LeftLeft */) {
                diagColumn = diagColumn - 2;
            }
            else if (arrow === 2 /* Arrow.Left */) {
                diagColumn = diagColumn - 1;
            }
            else {
                // found the diagonal
                break;
            }
        } while (diagColumn >= 1);
        // Overturn the "forwards" decision if keeping the "backwards" diagonal would give a better match
        if (backwardsDiagLength > 1 // only if we would have a contiguous match of 3 characters
            && patternLow[patternStart + row - 1] === wordLow[wordStart + column - 1] // only if we can do a contiguous match diagonally
            && !isUpperCaseAtPos(diagColumn + wordStart - 1, word, wordLow) // only if the forwards chose diagonal is not an uppercase
            && backwardsDiagLength + 1 > _diag[row][diagColumn] // only if our contiguous match would be longer than the "forwards" contiguous match
        ) {
            diagColumn = column;
        }
        if (diagColumn === column) {
            // this is a contiguous match
            backwardsDiagLength++;
        }
        else {
            backwardsDiagLength = 1;
        }
        if (!maxMatchColumn) {
            // remember the last matched column
            maxMatchColumn = diagColumn;
        }
        row--;
        column = diagColumn - 1;
        result.push(column);
    }
    if (wordLen === patternLen && options.boostFullMatch) {
        // the word matches the pattern with all characters!
        // giving the score a total match boost (to come up ahead other words)
        result[0] += 2;
    }
    // Add 1 penalty for each skipped character in the word
    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 score = 1;
    let isGapLocation = false;
    if (wordPos === (patternPos - patternStart)) {
        // common prefix: `foobar <-> foobaz`
        //                            ^^^^^
        score = pattern[patternPos] === word[wordPos] ? 7 : 5;
    }
    else if (isUpperCaseAtPos(wordPos, word, wordLow) && (wordPos === 0 || !isUpperCaseAtPos(wordPos - 1, word, wordLow))) {
        // hitting upper-case: `foo <-> forOthers`
        //                              ^^ ^
        score = pattern[patternPos] === word[wordPos] ? 7 : 5;
        isGapLocation = true;
    }
    else if (isSeparatorAtPos(wordLow, wordPos) && (wordPos === 0 || !isSeparatorAtPos(wordLow, wordPos - 1))) {
        // hitting a separator: `. <-> foo.bar`
        //                                ^
        score = 5;
    }
    else if (isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1)) {
        // post separator: `foo <-> bar_foo`
        //                              ^^^
        score = 5;
        isGapLocation = true;
    }
    if (score > 1 && patternPos === patternStart) {
        outFirstMatchStrong[0] = true;
    }
    if (!isGapLocation) {
        isGapLocation = isUpperCaseAtPos(wordPos, word, wordLow) || isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1);
    }
    //
    if (patternPos === patternStart) { // first character in pattern
        if (wordPos > wordStart) {
            // the first pattern character would match a word character that is not at the word start
            // so introduce a penalty to account for the gap preceding this match
            score -= isGapLocation ? 3 : 5;
        }
    }
    else {
        if (newMatchStart) {
            // this would be the beginning of a new match (i.e. there would be a gap before this location)
            score += isGapLocation ? 2 : 0;
        }
        else {
            // this is part of a contiguous match, so give it a slight bonus, but do so only if it would not be a preferred gap location
            score += isGapLocation ? 0 : 1;
        }
    }
    if (wordPos + 1 === wordLen) {
        // we always penalize gaps, but this gives unfair advantages to a match that would match the last character in the word
        // so pretend there is a gap after the last character in the word to normalize things
        score -= isGapLocation ? 3 : 5;
    }
    return score;
}
//#endregion
//#region --- graceful ---
function fuzzyScoreGracefulAggressive(pattern, lowPattern, patternPos, word, lowWord, wordPos, options) {
    return fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, true, options);
}
function fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word, lowWord, wordPos, aggressive, options) {
    let top = fuzzyScore(pattern, lowPattern, patternPos, word, lowWord, wordPos, options);
    if (top && !aggressive) {
        // when using the original pattern yield a result we`
        // return it unless we are aggressive and try to find
        // a better alignment, e.g. `cno` -> `^co^ns^ole` or `^c^o^nsole`.
        return top;
    }
    if (pattern.length >= 3) {
        // When the pattern is long enough then try a few (max 7)
        // permutations of the pattern to find a better match. The
        // permutations only swap neighbouring characters, e.g
        // `cnoso` becomes `conso`, `cnsoo`, `cnoos`.
        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 = fuzzyScore(newPattern, newPattern.toLowerCase(), patternPos, word, lowWord, wordPos, options);
                if (candidate) {
                    candidate[0] -= 3; // permutation penalty
                    if (!top || candidate[0] > top[0]) {
                        top = candidate;
                    }
                }
            }
        }
    }
    return top;
}
function nextTypoPermutation(pattern, patternPos) {
    if (patternPos + 1 >= pattern.length) {
        return undefined;
    }
    const swap1 = pattern[patternPos];
    const swap2 = pattern[patternPos + 1];
    if (swap1 === swap2) {
        return undefined;
    }
    return pattern.slice(0, patternPos)
        + swap2
        + swap1
        + pattern.slice(patternPos + 2);
}
//#endregion

;// ../../node_modules/monaco-editor/esm/vs/base/common/iconLabels.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



const iconStartMarker = '$(';
const iconsRegex = new RegExp(`\\$\\(${CSSIcon.iconNameExpression}(?:${CSSIcon.iconModifierExpression})?\\)`, 'g'); // no capturing groups
const iconNameCharacterRegexp = new RegExp(CSSIcon.iconNameCharacter);
const escapeIconsRegex = new RegExp(`(\\\\)?${iconsRegex.source}`, 'g');
function escapeIcons(text) {
    return text.replace(escapeIconsRegex, (match, escaped) => escaped ? match : `\\${match}`);
}
const markdownEscapedIconsRegex = new RegExp(`\\\\${iconsRegex.source}`, 'g');
function markdownEscapeEscapedIcons(text) {
    // Need to add an extra \ for escaping in markdown
    return text.replace(markdownEscapedIconsRegex, match => `\\${match}`);
}
const stripIconsRegex = new RegExp(`(\\s)?(\\\\)?${iconsRegex.source}(\\s)?`, 'g');
function stripIcons(text) {
    if (text.indexOf(iconStartMarker) === -1) {
        return text;
    }
    return text.replace(stripIconsRegex, (match, preWhitespace, escaped, postWhitespace) => escaped ? match : preWhitespace || postWhitespace || '');
}
function parseLabelWithIcons(text) {
    const firstIconIndex = text.indexOf(iconStartMarker);
    if (firstIconIndex === -1) {
        return { text }; // return early if the word does not include an icon
    }
    return doParseLabelWithIcons(text, firstIconIndex);
}
function doParseLabelWithIcons(text, firstIconIndex) {
    const iconOffsets = [];
    let textWithoutIcons = '';
    function appendChars(chars) {
        if (chars) {
            textWithoutIcons += chars;
            for (const _ of chars) {
                iconOffsets.push(iconsOffset); // make sure to fill in icon offsets
            }
        }
    }
    let currentIconStart = -1;
    let currentIconValue = '';
    let iconsOffset = 0;
    let char;
    let nextChar;
    let offset = firstIconIndex;
    const length = text.length;
    // Append all characters until the first icon
    appendChars(text.substr(0, firstIconIndex));
    // example: $(file-symlink-file) my cool $(other-icon) entry
    while (offset < length) {
        char = text[offset];
        nextChar = text[offset + 1];
        // beginning of icon: some value $( <--
        if (char === iconStartMarker[0] && nextChar === iconStartMarker[1]) {
            currentIconStart = offset;
            // if we had a previous potential icon value without
            // the closing ')', it was actually not an icon and
            // so we have to add it to the actual value
            appendChars(currentIconValue);
            currentIconValue = iconStartMarker;
            offset++; // jump over '('
        }
        // end of icon: some value $(some-icon) <--
        else if (char === ')' && currentIconStart !== -1) {
            const currentIconLength = offset - currentIconStart + 1; // +1 to include the closing ')'
            iconsOffset += currentIconLength;
            currentIconStart = -1;
            currentIconValue = '';
        }
        // within icon
        else if (currentIconStart !== -1) {
            // Make sure this is a real icon name
            if (iconNameCharacterRegexp.test(char)) {
                currentIconValue += char;
            }
            else {
                // This is not a real icon, treat it as text
                appendChars(currentIconValue);
                currentIconStart = -1;
                currentIconValue = '';
            }
        }
        // any value outside of icon
        else {
            appendChars(char);
        }
        offset++;
    }
    // if we had a previous potential icon value without
    // the closing ')', it was actually not an icon and
    // so we have to add it to the actual value
    appendChars(currentIconValue);
    return { text: textWithoutIcons, iconOffsets };
}
function matchesFuzzyIconAware(query, target, enableSeparateSubstringMatching = false) {
    const { text, iconOffsets } = target;
    // Return early if there are no icon markers in the word to match against
    if (!iconOffsets || iconOffsets.length === 0) {
        return matchesFuzzy(query, text, enableSeparateSubstringMatching);
    }
    // Trim the word to match against because it could have leading
    // whitespace now if the word started with an icon
    const wordToMatchAgainstWithoutIconsTrimmed = ltrim(text, ' ');
    const leadingWhitespaceOffset = text.length - wordToMatchAgainstWithoutIconsTrimmed.length;
    // match on value without icon
    const matches = matchesFuzzy(query, wordToMatchAgainstWithoutIconsTrimmed, enableSeparateSubstringMatching);
    // Map matches back to offsets with icon and trimming
    if (matches) {
        for (const match of matches) {
            const iconOffset = iconOffsets[match.start + leadingWhitespaceOffset] /* icon offsets at index */ + leadingWhitespaceOffset /* overall leading whitespace offset */;
            match.start += iconOffset;
            match.end += iconOffset;
        }
    }
    return matches;
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/htmlContent.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class MarkdownString {
    constructor(value = '', isTrustedOrOptions = false) {
        var _a, _b, _c;
        this.value = value;
        if (typeof this.value !== 'string') {
            throw illegalArgument('value');
        }
        if (typeof isTrustedOrOptions === 'boolean') {
            this.isTrusted = isTrustedOrOptions;
            this.supportThemeIcons = false;
            this.supportHtml = false;
        }
        else {
            this.isTrusted = (_a = isTrustedOrOptions.isTrusted) !== null && _a !== void 0 ? _a : undefined;
            this.supportThemeIcons = (_b = isTrustedOrOptions.supportThemeIcons) !== null && _b !== void 0 ? _b : false;
            this.supportHtml = (_c = isTrustedOrOptions.supportHtml) !== null && _c !== void 0 ? _c : false;
        }
    }
    appendText(value, newlineStyle = 0 /* MarkdownStringTextNewlineStyle.Paragraph */) {
        this.value += escapeMarkdownSyntaxTokens(this.supportThemeIcons ? escapeIcons(value) : value)
            .replace(/([ \t]+)/g, (_match, g1) => '&nbsp;'.repeat(g1.length))
            .replace(/\>/gm, '\\>')
            .replace(/\n/g, newlineStyle === 1 /* MarkdownStringTextNewlineStyle.Break */ ? '\\\n' : '\n\n');
        return this;
    }
    appendMarkdown(value) {
        this.value += value;
        return this;
    }
    appendCodeblock(langId, code) {
        this.value += '\n```';
        this.value += langId;
        this.value += '\n';
        this.value += code;
        this.value += '\n```\n';
        return this;
    }
    appendLink(target, label, title) {
        this.value += '[';
        this.value += this._escape(label, ']');
        this.value += '](';
        this.value += this._escape(String(target), ')');
        if (title) {
            this.value += ` "${this._escape(this._escape(title, '"'), ')')}"`;
        }
        this.value += ')';
        return this;
    }
    _escape(value, ch) {
        const r = new RegExp(escapeRegExpCharacters(ch), 'g');
        return value.replace(r, (match, offset) => {
            if (value.charAt(offset - 1) !== '\\') {
                return `\\${match}`;
            }
            else {
                return match;
            }
        });
    }
}
function isEmptyMarkdownString(oneOrMany) {
    if (isMarkdownString(oneOrMany)) {
        return !oneOrMany.value;
    }
    else if (Array.isArray(oneOrMany)) {
        return oneOrMany.every(isEmptyMarkdownString);
    }
    else {
        return true;
    }
}
function isMarkdownString(thing) {
    if (thing instanceof MarkdownString) {
        return true;
    }
    else if (thing && typeof thing === 'object') {
        return typeof thing.value === 'string'
            && (typeof thing.isTrusted === 'boolean' || thing.isTrusted === undefined)
            && (typeof thing.supportThemeIcons === 'boolean' || thing.supportThemeIcons === undefined);
    }
    return false;
}
function escapeMarkdownSyntaxTokens(text) {
    // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
    return text.replace(/[\\`*_{}[\]()#+\-!]/g, '\\$&');
}
function escapeDoubleQuotes(input) {
    return input.replace(/"/g, '&quot;');
}
function removeMarkdownEscapes(text) {
    if (!text) {
        return text;
    }
    return text.replace(/\\([\\`*_{}[\]()#+\-.!])/g, '$1');
}
function parseHrefAndDimensions(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 width = widthFromParams ? widthFromParams[1] : '';
        const widthIsFinite = isFinite(parseInt(width));
        const heightIsFinite = isFinite(parseInt(height));
        if (widthIsFinite) {
            dimensions.push(`width="${width}"`);
        }
        if (heightIsFinite) {
            dimensions.push(`height="${height}"`);
        }
    }
    return { href, dimensions };
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/anchorSelect/browser/anchorSelect.css
var anchorSelect = __webpack_require__(31020);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/anchorSelect/browser/anchorSelect.css

      
      
      
      
      
      
      
      
      

var anchorSelect_options = {};

anchorSelect_options.styleTagTransform = (styleTagTransform_default());
anchorSelect_options.setAttributes = (setAttributesWithoutAttributes_default());

      anchorSelect_options.insert = insertBySelector_default().bind(null, "head");
    
anchorSelect_options.domAPI = (styleDomAPI_default());
anchorSelect_options.insertStyleElement = (insertStyleElement_default());

var anchorSelect_update = injectStylesIntoStyleTag_default()(anchorSelect/* default */.A, anchorSelect_options);




       /* harmony default export */ const browser_anchorSelect = (anchorSelect/* default */.A && anchorSelect/* default */.A.locals ? anchorSelect/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/range.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/**
 * A range in the editor. (startLineNumber,startColumn) is <= (endLineNumber,endColumn)
 */
class Range {
    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 Range.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 Range.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 Range.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 Range.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 Range.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 Range(startLineNumber, startColumn, endLineNumber, endColumn);
    }
    /**
     * A intersection of the two ranges.
     */
    intersectRanges(range) {
        return Range.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);
        }
        // Check if selection is now empty
        if (resultStartLineNumber > resultEndLineNumber) {
            return null;
        }
        if (resultStartLineNumber === resultEndLineNumber && resultStartColumn > resultEndColumn) {
            return null;
        }
        return new Range(resultStartLineNumber, resultStartColumn, resultEndLineNumber, resultEndColumn);
    }
    /**
     * Test if this range equals other.
     */
    equalsRange(other) {
        return Range.equalsRange(this, other);
    }
    /**
     * Test if range `a` equals `b`.
     */
    static equalsRange(a, b) {
        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 Range.getEndPosition(this);
    }
    /**
     * Return the end position (which will be after or equal to the start position)
     */
    static getEndPosition(range) {
        return new Position(range.endLineNumber, range.endColumn);
    }
    /**
     * Return the start position (which will be before or equal to the end position)
     */
    getStartPosition() {
        return Range.getStartPosition(this);
    }
    /**
     * Return the start position (which will be before or equal to the end position)
     */
    static getStartPosition(range) {
        return new Position(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 Range(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 Range(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
    }
    /**
     * Create a new empty range using this range's start position.
     */
    collapseToStart() {
        return Range.collapseToStart(this);
    }
    /**
     * Create a new empty range using this range's start position.
     */
    static collapseToStart(range) {
        return new Range(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn);
    }
    // ---
    static fromPositions(start, end = start) {
        return new Range(start.lineNumber, start.column, end.lineNumber, end.column);
    }
    static lift(range) {
        if (!range) {
            return null;
        }
        return new Range(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) {
        // Check if `a` is before `b`
        if (a.endLineNumber < b.startLineNumber || (a.endLineNumber === b.startLineNumber && a.endColumn < b.startColumn)) {
            return false;
        }
        // Check if `b` is before `a`
        if (b.endLineNumber < a.startLineNumber || (b.endLineNumber === a.startLineNumber && b.endColumn < a.startColumn)) {
            return false;
        }
        // These ranges must intersect
        return true;
    }
    /**
     * Test if the two ranges are intersecting. If the ranges are touching it returns true.
     */
    static areIntersecting(a, b) {
        // Check if `a` is before `b`
        if (a.endLineNumber < b.startLineNumber || (a.endLineNumber === b.startLineNumber && a.endColumn <= b.startColumn)) {
            return false;
        }
        // Check if `b` is before `a`
        if (b.endLineNumber < a.startLineNumber || (b.endLineNumber === a.startLineNumber && b.endColumn <= a.startColumn)) {
            return false;
        }
        // These ranges must intersect
        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;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/selection.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


/**
 * A selection in the editor.
 * The selection is a range that has an orientation.
 */
class Selection extends Range {
    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 (Selection.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 /* SelectionDirection.LTR */;
        }
        return 1 /* SelectionDirection.RTL */;
    }
    /**
     * Create a new selection with a different `positionLineNumber` and `positionColumn`.
     */
    setEndPosition(endLineNumber, endColumn) {
        if (this.getDirection() === 0 /* SelectionDirection.LTR */) {
            return new Selection(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
        }
        return new Selection(endLineNumber, endColumn, this.startLineNumber, this.startColumn);
    }
    /**
     * Get the position at `positionLineNumber` and `positionColumn`.
     */
    getPosition() {
        return new Position(this.positionLineNumber, this.positionColumn);
    }
    /**
     * Get the position at the start of the selection.
    */
    getSelectionStart() {
        return new Position(this.selectionStartLineNumber, this.selectionStartColumn);
    }
    /**
     * Create a new selection with a different `selectionStartLineNumber` and `selectionStartColumn`.
     */
    setStartPosition(startLineNumber, startColumn) {
        if (this.getDirection() === 0 /* SelectionDirection.LTR */) {
            return new Selection(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
        }
        return new Selection(this.endLineNumber, this.endColumn, startLineNumber, startColumn);
    }
    // ----
    /**
     * Create a `Selection` from one or two positions
     */
    static fromPositions(start, end = start) {
        return new Selection(start.lineNumber, start.column, end.lineNumber, end.column);
    }
    /**
     * Creates a `Selection` from a range, given a direction.
     */
    static fromRange(range, direction) {
        if (direction === 0 /* SelectionDirection.LTR */) {
            return new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
        }
        else {
            return new Selection(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn);
        }
    }
    /**
     * Create a `Selection` from an `ISelection`.
     */
    static liftSelection(sel) {
        return new Selection(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 i = 0, len = a.length; i < len; i++) {
            if (!this.selectionsEqual(a[i], b[i])) {
                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 /* SelectionDirection.LTR */) {
            return new Selection(startLineNumber, startColumn, endLineNumber, endColumn);
        }
        return new Selection(endLineNumber, endColumn, startLineNumber, startColumn);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/anchorSelect/browser/anchorSelect.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var anchorSelect_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var anchorSelect_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var anchorSelect_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};









const SelectionAnchorSet = new RawContextKey('selectionAnchorSet', false);
let SelectionAnchorController = class SelectionAnchorController {
    constructor(editor, contextKeyService) {
        this.editor = editor;
        this.selectionAnchorSetContextKey = SelectionAnchorSet.bindTo(contextKeyService);
        this.modelChangeListener = editor.onDidChangeModel(() => this.selectionAnchorSetContextKey.reset());
    }
    static get(editor) {
        return editor.getContribution(SelectionAnchorController.ID);
    }
    setSelectionAnchor() {
        if (this.editor.hasModel()) {
            const position = this.editor.getPosition();
            this.editor.changeDecorations((accessor) => {
                if (this.decorationId) {
                    accessor.removeDecoration(this.decorationId);
                }
                this.decorationId = accessor.addDecoration(Selection.fromPositions(position, position), {
                    description: 'selection-anchor',
                    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
                    hoverMessage: new MarkdownString().appendText(localize('selectionAnchor', "Selection Anchor")),
                    className: 'selection-anchor'
                });
            });
            this.selectionAnchorSetContextKey.set(!!this.decorationId);
            aria_alert(localize('anchorSet', "Anchor set at {0}:{1}", position.lineNumber, position.column));
        }
    }
    goToSelectionAnchor() {
        if (this.editor.hasModel() && this.decorationId) {
            const anchorPosition = this.editor.getModel().getDecorationRange(this.decorationId);
            if (anchorPosition) {
                this.editor.setPosition(anchorPosition.getStartPosition());
            }
        }
    }
    selectFromAnchorToCursor() {
        if (this.editor.hasModel() && this.decorationId) {
            const start = this.editor.getModel().getDecorationRange(this.decorationId);
            if (start) {
                const end = this.editor.getPosition();
                this.editor.setSelection(Selection.fromPositions(start.getStartPosition(), end));
                this.cancelSelectionAnchor();
            }
        }
    }
    cancelSelectionAnchor() {
        if (this.decorationId) {
            const decorationId = this.decorationId;
            this.editor.changeDecorations((accessor) => {
                accessor.removeDecoration(decorationId);
                this.decorationId = undefined;
            });
            this.selectionAnchorSetContextKey.set(false);
        }
    }
    dispose() {
        this.cancelSelectionAnchor();
        this.modelChangeListener.dispose();
    }
};
SelectionAnchorController.ID = 'editor.contrib.selectionAnchorController';
SelectionAnchorController = anchorSelect_decorate([
    anchorSelect_param(1, IContextKeyService)
], SelectionAnchorController);
class SetSelectionAnchor extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.setSelectionAnchor',
            label: localize('setSelectionAnchor', "Set Selection Anchor"),
            alias: 'Set Selection Anchor',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 32 /* KeyCode.KeyB */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor) {
        var _a;
        return anchorSelect_awaiter(this, void 0, void 0, function* () {
            (_a = SelectionAnchorController.get(editor)) === null || _a === void 0 ? void 0 : _a.setSelectionAnchor();
        });
    }
}
class GoToSelectionAnchor extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.goToSelectionAnchor',
            label: localize('goToSelectionAnchor', "Go to Selection Anchor"),
            alias: 'Go to Selection Anchor',
            precondition: SelectionAnchorSet,
        });
    }
    run(_accessor, editor) {
        var _a;
        return anchorSelect_awaiter(this, void 0, void 0, function* () {
            (_a = SelectionAnchorController.get(editor)) === null || _a === void 0 ? void 0 : _a.goToSelectionAnchor();
        });
    }
}
class SelectFromAnchorToCursor extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.selectFromAnchorToCursor',
            label: localize('selectFromAnchorToCursor', "Select from Anchor to Cursor"),
            alias: 'Select from Anchor to Cursor',
            precondition: SelectionAnchorSet,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor) {
        var _a;
        return anchorSelect_awaiter(this, void 0, void 0, function* () {
            (_a = SelectionAnchorController.get(editor)) === null || _a === void 0 ? void 0 : _a.selectFromAnchorToCursor();
        });
    }
}
class CancelSelectionAnchor extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.cancelSelectionAnchor',
            label: localize('cancelSelectionAnchor', "Cancel Selection Anchor"),
            alias: 'Cancel Selection Anchor',
            precondition: SelectionAnchorSet,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 9 /* KeyCode.Escape */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor) {
        var _a;
        return anchorSelect_awaiter(this, void 0, void 0, function* () {
            (_a = SelectionAnchorController.get(editor)) === null || _a === void 0 ? void 0 : _a.cancelSelectionAnchor();
        });
    }
}
registerEditorContribution(SelectionAnchorController.ID, SelectionAnchorController);
registerEditorAction(SetSelectionAnchor);
registerEditorAction(GoToSelectionAnchor);
registerEditorAction(SelectFromAnchorToCursor);
registerEditorAction(CancelSelectionAnchor);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/bracketMatching/browser/bracketMatching.css
var bracketMatching = __webpack_require__(93938);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/bracketMatching/browser/bracketMatching.css

      
      
      
      
      
      
      
      
      

var bracketMatching_options = {};

bracketMatching_options.styleTagTransform = (styleTagTransform_default());
bracketMatching_options.setAttributes = (setAttributesWithoutAttributes_default());

      bracketMatching_options.insert = insertBySelector_default().bind(null, "head");
    
bracketMatching_options.domAPI = (styleDomAPI_default());
bracketMatching_options.insertStyleElement = (insertStyleElement_default());

var bracketMatching_update = injectStylesIntoStyleTag_default()(bracketMatching/* default */.A, bracketMatching_options);




       /* harmony default export */ const browser_bracketMatching = (bracketMatching/* default */.A && bracketMatching/* default */.A.locals ? bracketMatching/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/common/objects.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

function deepClone(obj) {
    if (!obj || typeof obj !== 'object') {
        return obj;
    }
    if (obj instanceof RegExp) {
        // See https://github.com/microsoft/TypeScript/issues/10990
        return obj;
    }
    const result = Array.isArray(obj) ? [] : {};
    Object.keys(obj).forEach((key) => {
        if (obj[key] && typeof obj[key] === 'object') {
            result[key] = deepClone(obj[key]);
        }
        else {
            result[key] = obj[key];
        }
    });
    return result;
}
function deepFreeze(obj) {
    if (!obj || typeof obj !== 'object') {
        return obj;
    }
    const stack = [obj];
    while (stack.length > 0) {
        const obj = stack.shift();
        Object.freeze(obj);
        for (const key in obj) {
            if (_hasOwnProperty.call(obj, key)) {
                const prop = obj[key];
                if (typeof prop === 'object' && !Object.isFrozen(prop) && !isTypedArray(prop)) {
                    stack.push(prop);
                }
            }
        }
    }
    return obj;
}
const _hasOwnProperty = Object.prototype.hasOwnProperty;
function cloneAndChange(obj, changer) {
    return _cloneAndChange(obj, changer, new Set());
}
function _cloneAndChange(obj, changer, seen) {
    if (isUndefinedOrNull(obj)) {
        return obj;
    }
    const changed = changer(obj);
    if (typeof changed !== 'undefined') {
        return changed;
    }
    if (isArray(obj)) {
        const r1 = [];
        for (const e of obj) {
            r1.push(_cloneAndChange(e, changer, seen));
        }
        return r1;
    }
    if (isObject(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;
}
/**
 * Copies all properties of source into destination. The optional parameter "overwrite" allows to control
 * if existing properties on the destination should be overwritten or not. Defaults to true (overwrite).
 */
function mixin(destination, source, overwrite = true) {
    if (!isObject(destination)) {
        return source;
    }
    if (isObject(source)) {
        Object.keys(source).forEach(key => {
            if (key in destination) {
                if (overwrite) {
                    if (isObject(destination[key]) && isObject(source[key])) {
                        mixin(destination[key], source[key], overwrite);
                    }
                    else {
                        destination[key] = source[key];
                    }
                }
            }
            else {
                destination[key] = source[key];
            }
        });
    }
    return destination;
}
function objects_equals(one, other) {
    if (one === other) {
        return true;
    }
    if (one === null || one === undefined || other === null || other === undefined) {
        return false;
    }
    if (typeof one !== typeof other) {
        return false;
    }
    if (typeof one !== 'object') {
        return false;
    }
    if ((Array.isArray(one)) !== (Array.isArray(other))) {
        return false;
    }
    let i;
    let key;
    if (Array.isArray(one)) {
        if (one.length !== other.length) {
            return false;
        }
        for (i = 0; i < one.length; i++) {
            if (!objects_equals(one[i], other[i])) {
                return false;
            }
        }
    }
    else {
        const oneKeys = [];
        for (key in one) {
            oneKeys.push(key);
        }
        oneKeys.sort();
        const otherKeys = [];
        for (key in other) {
            otherKeys.push(key);
        }
        otherKeys.sort();
        if (!objects_equals(oneKeys, otherKeys)) {
            return false;
        }
        for (i = 0; i < oneKeys.length; i++) {
            if (!objects_equals(one[oneKeys[i]], other[oneKeys[i]])) {
                return false;
            }
        }
    }
    return true;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/**
 * Vertical Lane in the overview ruler of the editor.
 */
var OverviewRulerLane;
(function (OverviewRulerLane) {
    OverviewRulerLane[OverviewRulerLane["Left"] = 1] = "Left";
    OverviewRulerLane[OverviewRulerLane["Center"] = 2] = "Center";
    OverviewRulerLane[OverviewRulerLane["Right"] = 4] = "Right";
    OverviewRulerLane[OverviewRulerLane["Full"] = 7] = "Full";
})(OverviewRulerLane || (OverviewRulerLane = {}));
/**
 * Position in the minimap to render the decoration.
 */
var MinimapPosition;
(function (MinimapPosition) {
    MinimapPosition[MinimapPosition["Inline"] = 1] = "Inline";
    MinimapPosition[MinimapPosition["Gutter"] = 2] = "Gutter";
})(MinimapPosition || (MinimapPosition = {}));
var InjectedTextCursorStops;
(function (InjectedTextCursorStops) {
    InjectedTextCursorStops[InjectedTextCursorStops["Both"] = 0] = "Both";
    InjectedTextCursorStops[InjectedTextCursorStops["Right"] = 1] = "Right";
    InjectedTextCursorStops[InjectedTextCursorStops["Left"] = 2] = "Left";
    InjectedTextCursorStops[InjectedTextCursorStops["None"] = 3] = "None";
})(InjectedTextCursorStops || (InjectedTextCursorStops = {}));
class TextModelResolvedOptions {
    /**
     * @internal
     */
    constructor(src) {
        this._textModelResolvedOptionsBrand = undefined;
        this.tabSize = Math.max(1, src.tabSize | 0);
        this.indentSize = src.tabSize | 0;
        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.indentSize === other.indentSize
            && this.insertSpaces === other.insertSpaces
            && this.defaultEOL === other.defaultEOL
            && this.trimAutoWhitespace === other.trimAutoWhitespace
            && objects_equals(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,
        };
    }
}
class FindMatch {
    /**
     * @internal
     */
    constructor(range, matches) {
        this._findMatchBrand = undefined;
        this.range = range;
        this.matches = matches;
    }
}
/**
 * @internal
 */
function isITextSnapshot(obj) {
    return (obj && typeof obj.read === 'function');
}
/**
 * @internal
 */
class ValidAnnotatedEditOperation {
    constructor(identifier, range, text, forceMoveMarkers, isAutoWhitespaceEdit, _isTracked) {
        this.identifier = identifier;
        this.range = range;
        this.text = text;
        this.forceMoveMarkers = forceMoveMarkers;
        this.isAutoWhitespaceEdit = isAutoWhitespaceEdit;
        this._isTracked = _isTracked;
    }
}
/**
 * @internal
 */
class SearchData {
    constructor(regex, wordSeparators, simpleSearch) {
        this.regex = regex;
        this.wordSeparators = wordSeparators;
        this.simpleSearch = simpleSearch;
    }
}
/**
 * @internal
 */
class ApplyEditsResult {
    constructor(reverseEdits, changes, trimAutoWhitespaceLineNumbers) {
        this.reverseEdits = reverseEdits;
        this.changes = changes;
        this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers;
    }
}
/**
 * @internal
 */
function shouldSynchronizeModel(model) {
    return (!model.isTooLargeForSyncing() && !model.isForSimpleWidget);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/eolCounter.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
function countEOL(text) {
    let eolCount = 0;
    let firstLineLength = 0;
    let lastLineStart = 0;
    let eol = 0 /* StringEOL.Unknown */;
    for (let i = 0, len = text.length; i < len; i++) {
        const chr = text.charCodeAt(i);
        if (chr === 13 /* CharCode.CarriageReturn */) {
            if (eolCount === 0) {
                firstLineLength = i;
            }
            eolCount++;
            if (i + 1 < len && text.charCodeAt(i + 1) === 10 /* CharCode.LineFeed */) {
                // \r\n... case
                eol |= 2 /* StringEOL.CRLF */;
                i++; // skip \n
            }
            else {
                // \r... case
                eol |= 3 /* StringEOL.Invalid */;
            }
            lastLineStart = i + 1;
        }
        else if (chr === 10 /* CharCode.LineFeed */) {
            // \n... case
            eol |= 1 /* StringEOL.LF */;
            if (eolCount === 0) {
                firstLineLength = i;
            }
            eolCount++;
            lastLineStart = i + 1;
        }
    }
    if (eolCount === 0) {
        firstLineLength = text.length;
    }
    return [eolCount, firstLineLength, text.length - lastLineStart, eol];
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/cursorColumns.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/**
 * A column in a position is the gap between two adjacent characters. The methods here
 * work with a concept called "visible column". A visible column is a very rough approximation
 * of the horizontal screen position of a column. For example, using a tab size of 4:
 * ```txt
 * |<TAB>|<TAB>|T|ext
 * |     |     | \---- column = 4, visible column = 9
 * |     |     \------ column = 3, visible column = 8
 * |     \------------ column = 2, visible column = 4
 * \------------------ column = 1, visible column = 0
 * ```
 *
 * **NOTE**: Visual columns do not work well for RTL text or variable-width fonts or characters.
 *
 * **NOTE**: These methods work and make sense both on the model and on the view model.
 */
class CursorColumns {
    static _nextVisibleColumn(codePoint, visibleColumn, tabSize) {
        if (codePoint === 9 /* CharCode.Tab */) {
            return CursorColumns.nextRenderTabStop(visibleColumn, tabSize);
        }
        if (isFullWidthCharacter(codePoint) || isEmojiImprecise(codePoint)) {
            return visibleColumn + 2;
        }
        return visibleColumn + 1;
    }
    /**
     * Returns a visible column from a column.
     * @see {@link CursorColumns}
     */
    static visibleColumnFromColumn(lineContent, column, tabSize) {
        const textLen = Math.min(column - 1, lineContent.length);
        const text = lineContent.substring(0, textLen);
        const iterator = new GraphemeIterator(text);
        let result = 0;
        while (!iterator.eol()) {
            const codePoint = getNextCodePoint(text, textLen, iterator.offset);
            iterator.nextGraphemeLength();
            result = this._nextVisibleColumn(codePoint, result, tabSize);
        }
        return result;
    }
    /**
     * Returns a column from a visible column.
     * @see {@link CursorColumns}
     */
    static columnFromVisibleColumn(lineContent, visibleColumn, tabSize) {
        if (visibleColumn <= 0) {
            return 1;
        }
        const lineContentLength = lineContent.length;
        const iterator = new GraphemeIterator(lineContent);
        let beforeVisibleColumn = 0;
        let beforeColumn = 1;
        while (!iterator.eol()) {
            const codePoint = getNextCodePoint(lineContent, lineContentLength, iterator.offset);
            iterator.nextGraphemeLength();
            const afterVisibleColumn = this._nextVisibleColumn(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;
        }
        // walked the entire string
        return lineContentLength + 1;
    }
    /**
     * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)
     * @see {@link CursorColumns}
     */
    static nextRenderTabStop(visibleColumn, tabSize) {
        return visibleColumn + tabSize - visibleColumn % tabSize;
    }
    /**
     * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns)
     * @see {@link CursorColumns}
     */
    static nextIndentTabStop(visibleColumn, indentSize) {
        return visibleColumn + indentSize - visibleColumn % indentSize;
    }
    /**
     * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
     * @see {@link CursorColumns}
     */
    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 CursorColumns}
     */
    static prevIndentTabStop(column, indentSize) {
        return Math.max(0, column - 1 - (column - 1) % indentSize);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/indentation.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


function _normalizeIndentationFromWhitespace(str, indentSize, insertSpaces) {
    let spacesCnt = 0;
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) === '\t') {
            spacesCnt = CursorColumns.nextIndentTabStop(spacesCnt, indentSize);
        }
        else {
            spacesCnt++;
        }
    }
    let result = '';
    if (!insertSpaces) {
        const tabsCnt = Math.floor(spacesCnt / indentSize);
        spacesCnt = spacesCnt % indentSize;
        for (let i = 0; i < tabsCnt; i++) {
            result += '\t';
        }
    }
    for (let i = 0; i < spacesCnt; i++) {
        result += ' ';
    }
    return result;
}
function normalizeIndentation(str, indentSize, insertSpaces) {
    let firstNonWhitespaceIndex = strings_firstNonWhitespaceIndex(str);
    if (firstNonWhitespaceIndex === -1) {
        firstNonWhitespaceIndex = str.length;
    }
    return _normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex), indentSize, insertSpaces) + str.substring(firstNonWhitespaceIndex);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/textModelDefaults.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
const EDITOR_MODEL_DEFAULTS = {
    tabSize: 4,
    indentSize: 4,
    insertSpaces: true,
    detectIndentation: true,
    trimAutoWhitespace: true,
    largeFileOptimizations: true,
    bracketPairColorizationOptions: {
        enabled: true,
        independentColorPoolPerBracketType: false,
    },
};

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/language.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const ILanguageService = createDecorator('languageService');

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/wordHelper.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


const USUAL_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:\'",.<>/?';
/**
 * Create a word definition regular expression based on default word separators.
 * Optionally provide allowed separators that should be included in words.
 *
 * The default would look like this:
 * /(-?\d*\.\d\w*)|([^\`\~\!\@\#\$\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g
 */
function createWordRegExp(allowInWords = '') {
    let source = '(-?\\d*\\.\\d\\w*)|([^';
    for (const sep of USUAL_WORD_SEPARATORS) {
        if (allowInWords.indexOf(sep) >= 0) {
            continue;
        }
        source += '\\' + sep;
    }
    source += '\\s]+)';
    return new RegExp(source, 'g');
}
// catches numbers (including floating numbers) in the first group, and alphanum in the second
const DEFAULT_WORD_REGEXP = createWordRegExp();
function ensureValidWordDefinition(wordDefinition) {
    let result = DEFAULT_WORD_REGEXP;
    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;
}
const _defaultConfig = new LinkedList();
_defaultConfig.unshift({
    maxLen: 1000,
    windowSize: 15,
    timeBudget: 150
});
function getWordAtText(column, wordDefinition, text, textOffset, config) {
    if (!config) {
        config = Iterable.first(_defaultConfig);
    }
    if (text.length > config.maxLen) {
        // don't throw strings that long at the regexp
        // but use a sub-string in which a word must occur
        let start = column - config.maxLen / 2;
        if (start < 0) {
            start = 0;
        }
        else {
            textOffset += start;
        }
        text = text.substring(start, column + config.maxLen / 2);
        return getWordAtText(column, wordDefinition, text, textOffset, config);
    }
    const t1 = Date.now();
    const pos = column - 1 - textOffset;
    let prevRegexIndex = -1;
    let match = null;
    for (let i = 1;; i++) {
        // check time budget
        if (Date.now() - t1 >= config.timeBudget) {
            break;
        }
        // reset the index at which the regexp should start matching, also know where it
        // should stop so that subsequent search don't repeat previous searches
        const regexIndex = pos - config.windowSize * i;
        wordDefinition.lastIndex = Math.max(0, regexIndex);
        const thisMatch = _findRegexMatchEnclosingPosition(wordDefinition, text, pos, prevRegexIndex);
        if (!thisMatch && match) {
            // stop: we have something
            break;
        }
        match = thisMatch;
        // stop: searched at start
        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, text, pos, stopPos) {
    let match;
    while (match = wordDefinition.exec(text)) {
        const matchIndex = match.index || 0;
        if (matchIndex <= pos && wordDefinition.lastIndex >= pos) {
            return match;
        }
        else if (stopPos > 0 && matchIndex > stopPos) {
            return null;
        }
    }
    return null;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/languageConfiguration.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/**
 * Describes what to do with the indentation when pressing Enter.
 */
var IndentAction;
(function (IndentAction) {
    /**
     * Insert new line and copy the previous line's indentation.
     */
    IndentAction[IndentAction["None"] = 0] = "None";
    /**
     * Insert new line and indent once (relative to the previous line's indentation).
     */
    IndentAction[IndentAction["Indent"] = 1] = "Indent";
    /**
     * Insert two new lines:
     *  - the first one indented which will hold the cursor
     *  - the second one at the same indentation level
     */
    IndentAction[IndentAction["IndentOutdent"] = 2] = "IndentOutdent";
    /**
     * Insert new line and outdent once (relative to the previous line's indentation).
     */
    IndentAction[IndentAction["Outdent"] = 3] = "Outdent";
})(IndentAction || (IndentAction = {}));
/**
 * @internal
 */
class StandardAutoClosingPairConditional {
    constructor(source) {
        this._neutralCharacter = null;
        this._neutralCharacterSearched = false;
        this.open = source.open;
        this.close = source.close;
        // initially allowed in all tokens
        this._inString = true;
        this._inComment = true;
        this._inRegEx = true;
        if (Array.isArray(source.notIn)) {
            for (let i = 0, len = source.notIn.length; i < len; i++) {
                const notIn = source.notIn[i];
                switch (notIn) {
                    case 'string':
                        this._inString = false;
                        break;
                    case 'comment':
                        this._inComment = false;
                        break;
                    case 'regex':
                        this._inRegEx = false;
                        break;
                }
            }
        }
    }
    isOK(standardToken) {
        switch (standardToken) {
            case 0 /* StandardTokenType.Other */:
                return true;
            case 1 /* StandardTokenType.Comment */:
                return this._inComment;
            case 2 /* StandardTokenType.String */:
                return this._inString;
            case 3 /* StandardTokenType.RegEx */:
                return this._inRegEx;
        }
    }
    shouldAutoClose(context, column) {
        // Always complete on empty line
        if (context.getTokenCount() === 0) {
            return true;
        }
        const tokenIndex = context.findTokenIndexAtOffset(column - 2);
        const standardTokenType = context.getStandardTokenType(tokenIndex);
        return this.isOK(standardTokenType);
    }
    _findNeutralCharacterInRange(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._neutralCharacterSearched) {
            this._neutralCharacterSearched = true;
            if (!this._neutralCharacter) {
                this._neutralCharacter = this._findNeutralCharacterInRange(48 /* CharCode.Digit0 */, 57 /* CharCode.Digit9 */);
            }
            if (!this._neutralCharacter) {
                this._neutralCharacter = this._findNeutralCharacterInRange(97 /* CharCode.a */, 122 /* CharCode.z */);
            }
            if (!this._neutralCharacter) {
                this._neutralCharacter = this._findNeutralCharacterInRange(65 /* CharCode.A */, 90 /* CharCode.Z */);
            }
        }
        return this._neutralCharacter;
    }
}
/**
 * @internal
 */
class AutoClosingPairs {
    constructor(autoClosingPairs) {
        this.autoClosingPairsOpenByStart = new Map();
        this.autoClosingPairsOpenByEnd = new Map();
        this.autoClosingPairsCloseByStart = new Map();
        this.autoClosingPairsCloseByEnd = new Map();
        this.autoClosingPairsCloseSingleChar = 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, key, value) {
    if (target.has(key)) {
        target.get(key).push(value);
    }
    else {
        target.set(key, [value]);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/supports.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
function createScopedLineTokens(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 ScopedLineTokens(context, desiredLanguageId, firstTokenIndex, lastTokenIndex + 1, context.getStartOffset(firstTokenIndex), context.getEndOffset(lastTokenIndex));
}
class ScopedLineTokens {
    constructor(actual, languageId, firstTokenIndex, lastTokenIndex, firstCharOffset, lastCharOffset) {
        this._scopedLineTokensBrand = undefined;
        this._actual = actual;
        this.languageId = languageId;
        this._firstTokenIndex = firstTokenIndex;
        this._lastTokenIndex = lastTokenIndex;
        this.firstCharOffset = firstCharOffset;
        this._lastCharOffset = lastCharOffset;
    }
    getLineContent() {
        const actualLineContent = this._actual.getLineContent();
        return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset);
    }
    getActualLineContentBefore(offset) {
        const actualLineContent = this._actual.getLineContent();
        return actualLineContent.substring(0, this.firstCharOffset + offset);
    }
    getTokenCount() {
        return this._lastTokenIndex - this._firstTokenIndex;
    }
    findTokenIndexAtOffset(offset) {
        return this._actual.findTokenIndexAtOffset(offset + this.firstCharOffset) - this._firstTokenIndex;
    }
    getStandardTokenType(tokenIndex) {
        return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex);
    }
}
function ignoreBracketsInToken(standardTokenType) {
    return (standardTokenType & 3 /* IgnoreBracketsInTokens.value */) !== 0;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/supports/characterPair.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class CharacterPairSupport {
    constructor(config) {
        if (config.autoClosingPairs) {
            this._autoClosingPairs = config.autoClosingPairs.map(el => new StandardAutoClosingPairConditional(el));
        }
        else if (config.brackets) {
            this._autoClosingPairs = config.brackets.map(b => new StandardAutoClosingPairConditional({ open: b[0], close: b[1] }));
        }
        else {
            this._autoClosingPairs = [];
        }
        if (config.__electricCharacterSupport && config.__electricCharacterSupport.docComment) {
            const docComment = config.__electricCharacterSupport.docComment;
            // IDocComment is legacy, only partially supported
            this._autoClosingPairs.push(new StandardAutoClosingPairConditional({ open: docComment.open, close: docComment.close || '' }));
        }
        this._autoCloseBefore = typeof config.autoCloseBefore === 'string' ? config.autoCloseBefore : CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED;
        this._surroundingPairs = config.surroundingPairs || this._autoClosingPairs;
    }
    getAutoClosingPairs() {
        return this._autoClosingPairs;
    }
    getAutoCloseBeforeSet() {
        return this._autoCloseBefore;
    }
    getSurroundingPairs() {
        return this._surroundingPairs;
    }
}
CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED = ';:.,=}])> \n\t';

;// ../../node_modules/monaco-editor/esm/vs/base/common/buffer.js
const hasBuffer = (typeof Buffer !== 'undefined');
let textDecoder;
class VSBuffer {
    constructor(buffer) {
        this.buffer = buffer;
        this.byteLength = this.buffer.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))) {
            // https://nodejs.org/dist/latest-v10.x/docs/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
            // Create a zero-copy Buffer wrapper around the ArrayBuffer pointed to by the Uint8Array
            actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength);
        }
        return new VSBuffer(actual);
    }
    toString() {
        if (hasBuffer) {
            return this.buffer.toString();
        }
        else {
            if (!textDecoder) {
                textDecoder = new TextDecoder();
            }
            return textDecoder.decode(this.buffer);
        }
    }
}
function readUInt16LE(source, offset) {
    return (((source[offset + 0] << 0) >>> 0) |
        ((source[offset + 1] << 8) >>> 0));
}
function writeUInt16LE(destination, value, offset) {
    destination[offset + 0] = (value & 0b11111111);
    value = value >>> 8;
    destination[offset + 1] = (value & 0b11111111);
}
function readUInt32BE(source, offset) {
    return (source[offset] * Math.pow(2, 24)
        + source[offset + 1] * Math.pow(2, 16)
        + source[offset + 2] * Math.pow(2, 8)
        + source[offset + 3]);
}
function writeUInt32BE(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 readUInt8(source, offset) {
    return source[offset];
}
function writeUInt8(destination, value, offset) {
    destination[offset] = value;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/stringBuilder.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



let _utf16LE_TextDecoder;
function getUTF16LE_TextDecoder() {
    if (!_utf16LE_TextDecoder) {
        _utf16LE_TextDecoder = new TextDecoder('UTF-16LE');
    }
    return _utf16LE_TextDecoder;
}
let _utf16BE_TextDecoder;
function getUTF16BE_TextDecoder() {
    if (!_utf16BE_TextDecoder) {
        _utf16BE_TextDecoder = new TextDecoder('UTF-16BE');
    }
    return _utf16BE_TextDecoder;
}
let _platformTextDecoder;
function getPlatformTextDecoder() {
    if (!_platformTextDecoder) {
        _platformTextDecoder = isLittleEndian() ? getUTF16LE_TextDecoder() : getUTF16BE_TextDecoder();
    }
    return _platformTextDecoder;
}
const hasTextDecoder = (typeof TextDecoder !== 'undefined');
let createStringBuilder;
let decodeUTF16LE;
if (hasTextDecoder) {
    createStringBuilder = (capacity) => new StringBuilder(capacity);
    decodeUTF16LE = standardDecodeUTF16LE;
}
else {
    createStringBuilder = (capacity) => new CompatStringBuilder();
    decodeUTF16LE = compatDecodeUTF16LE;
}
function standardDecodeUTF16LE(source, offset, len) {
    const view = new Uint16Array(source.buffer, offset, len);
    if (len > 0 && (view[0] === 0xFEFF || view[0] === 0xFFFE)) {
        // UTF16 sometimes starts with a BOM https://de.wikipedia.org/wiki/Byte_Order_Mark
        // It looks like TextDecoder.decode will eat up a leading BOM (0xFEFF or 0xFFFE)
        // We don't want that behavior because we know the string is UTF16LE and the BOM should be maintained
        // So we use the manual decoder
        return compatDecodeUTF16LE(source, offset, len);
    }
    return getUTF16LE_TextDecoder().decode(view);
}
function compatDecodeUTF16LE(source, offset, len) {
    const result = [];
    let resultLen = 0;
    for (let i = 0; i < len; i++) {
        const charCode = readUInt16LE(source, offset);
        offset += 2;
        result[resultLen++] = String.fromCharCode(charCode);
    }
    return result.join('');
}
class StringBuilder {
    constructor(capacity) {
        this._capacity = capacity | 0;
        this._buffer = new Uint16Array(this._capacity);
        this._completedStrings = null;
        this._bufferLength = 0;
    }
    reset() {
        this._completedStrings = null;
        this._bufferLength = 0;
    }
    build() {
        if (this._completedStrings !== null) {
            this._flushBuffer();
            return this._completedStrings.join('');
        }
        return this._buildBuffer();
    }
    _buildBuffer() {
        if (this._bufferLength === 0) {
            return '';
        }
        const view = new Uint16Array(this._buffer.buffer, 0, this._bufferLength);
        return getPlatformTextDecoder().decode(view);
    }
    _flushBuffer() {
        const bufferString = this._buildBuffer();
        this._bufferLength = 0;
        if (this._completedStrings === null) {
            this._completedStrings = [bufferString];
        }
        else {
            this._completedStrings[this._completedStrings.length] = bufferString;
        }
    }
    write1(charCode) {
        const remainingSpace = this._capacity - this._bufferLength;
        if (remainingSpace <= 1) {
            if (remainingSpace === 0 || isHighSurrogate(charCode)) {
                this._flushBuffer();
            }
        }
        this._buffer[this._bufferLength++] = charCode;
    }
    appendASCII(charCode) {
        if (this._bufferLength === this._capacity) {
            // buffer is full
            this._flushBuffer();
        }
        this._buffer[this._bufferLength++] = charCode;
    }
    appendASCIIString(str) {
        const strLen = str.length;
        if (this._bufferLength + strLen >= this._capacity) {
            // This string does not fit in the remaining buffer space
            this._flushBuffer();
            this._completedStrings[this._completedStrings.length] = str;
            return;
        }
        for (let i = 0; i < strLen; i++) {
            this._buffer[this._bufferLength++] = str.charCodeAt(i);
        }
    }
}
class CompatStringBuilder {
    constructor() {
        this._pieces = [];
        this._piecesLen = 0;
    }
    reset() {
        this._pieces = [];
        this._piecesLen = 0;
    }
    build() {
        return this._pieces.join('');
    }
    write1(charCode) {
        this._pieces[this._piecesLen++] = String.fromCharCode(charCode);
    }
    appendASCII(charCode) {
        this._pieces[this._piecesLen++] = String.fromCharCode(charCode);
    }
    appendASCIIString(str) {
        this._pieces[this._piecesLen++] = str;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/supports/richEditBrackets.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



/**
 * Represents a grouping of colliding bracket pairs.
 *
 * Most of the times this contains a single bracket pair,
 * but sometimes this contains multiple bracket pairs in cases
 * where the same string appears as a closing bracket for multiple
 * bracket pairs, or the same string appears an opening bracket for
 * multiple bracket pairs.
 *
 * e.g. of a group containing a single pair:
 *   open: ['{'], close: ['}']
 *
 * e.g. of a group containing multiple pairs:
 *   open: ['if', 'for'], close: ['end', 'end']
 */
class RichEditBracket {
    constructor(languageId, index, open, close, forwardRegex, reversedRegex) {
        this._richEditBracketBrand = undefined;
        this.languageId = languageId;
        this.index = index;
        this.open = open;
        this.close = close;
        this.forwardRegex = forwardRegex;
        this.reversedRegex = reversedRegex;
        this._openSet = RichEditBracket._toSet(this.open);
        this._closeSet = RichEditBracket._toSet(this.close);
    }
    /**
     * Check if the provided `text` is an open bracket in this group.
     */
    isOpen(text) {
        return this._openSet.has(text);
    }
    /**
     * Check if the provided `text` is a close bracket in this group.
     */
    isClose(text) {
        return this._closeSet.has(text);
    }
    static _toSet(arr) {
        const result = new Set();
        for (const element of arr) {
            result.add(element);
        }
        return result;
    }
}
/**
 * Groups together brackets that have equal open or close sequences.
 *
 * For example, if the following brackets are defined:
 *   ['IF','END']
 *   ['for','end']
 *   ['{','}']
 *
 * Then the grouped brackets would be:
 *   { open: ['if', 'for'], close: ['end', 'end'] }
 *   { open: ['{'], close: ['}'] }
 *
 */
function groupFuzzyBrackets(brackets) {
    const N = brackets.length;
    brackets = brackets.map(b => [b[0].toLowerCase(), b[1].toLowerCase()]);
    const group = [];
    for (let i = 0; i < N; i++) {
        group[i] = i;
    }
    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 i = 0; i < N; i++) {
            if (group[i] === oldG) {
                group[i] = newG;
            }
        }
    };
    // group together brackets that have the same open or the same close sequence
    for (let i = 0; i < N; i++) {
        const a = brackets[i];
        for (let j = i + 1; j < N; j++) {
            const b = brackets[j];
            if (areOverlapping(a, b)) {
                mergeGroups(group[i], group[j]);
            }
        }
    }
    const result = [];
    for (let g = 0; g < N; g++) {
        const currentOpen = [];
        const currentClose = [];
        for (let i = 0; i < N; i++) {
            if (group[i] === g) {
                const [open, close] = brackets[i];
                currentOpen.push(open);
                currentClose.push(close);
            }
        }
        if (currentOpen.length > 0) {
            result.push({
                open: currentOpen,
                close: currentClose
            });
        }
    }
    return result;
}
class RichEditBrackets {
    constructor(languageId, _brackets) {
        this._richEditBracketsBrand = undefined;
        const brackets = groupFuzzyBrackets(_brackets);
        this.brackets = brackets.map((b, index) => {
            return new RichEditBracket(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 open of bracket.open) {
                this.textIsBracket[open] = bracket;
                this.textIsOpenBracket[open] = true;
                this.maxBracketLength = Math.max(this.maxBracketLength, open.length);
            }
            for (const close of bracket.close) {
                this.textIsBracket[close] = bracket;
                this.textIsOpenBracket[close] = false;
                this.maxBracketLength = Math.max(this.maxBracketLength, close.length);
            }
        }
    }
}
function collectSuperstrings(str, brackets, currentIndex, dest) {
    for (let i = 0, len = brackets.length; i < len; i++) {
        if (i === currentIndex) {
            continue;
        }
        const bracket = brackets[i];
        for (const open of bracket.open) {
            if (open.indexOf(str) >= 0) {
                dest.push(open);
            }
        }
        for (const close of bracket.close) {
            if (close.indexOf(str) >= 0) {
                dest.push(close);
            }
        }
    }
}
function lengthcmp(a, b) {
    return a.length - b.length;
}
function unique(arr) {
    if (arr.length <= 1) {
        return arr;
    }
    const result = [];
    const seen = new Set();
    for (const element of arr) {
        if (seen.has(element)) {
            continue;
        }
        result.push(element);
        seen.add(element);
    }
    return result;
}
/**
 * Create a regular expression that can be used to search forward in a piece of text
 * for a group of bracket pairs. But this regex must be built in a way in which
 * it is aware of the other bracket pairs defined for the language.
 *
 * For example, if a language contains the following bracket pairs:
 *   ['begin', 'end']
 *   ['if', 'end if']
 * The two bracket pairs do not collide because no open or close brackets are equal.
 * So the function getRegexForBracketPair is called twice, once with
 * the ['begin'], ['end'] group consisting of one bracket pair, and once with
 * the ['if'], ['end if'] group consiting of the other bracket pair.
 *
 * But there could be a situation where an occurrence of 'end if' is mistaken
 * for an occurrence of 'end'.
 *
 * Therefore, for the bracket pair ['begin', 'end'], the regex will also
 * target 'end if'. The regex will be something like:
 *   /(\bend if\b)|(\bend\b)|(\bif\b)/
 *
 * The regex also searches for "superstrings" (other brackets that might be mistaken with the current bracket).
 *
 */
function getRegexForBracketPair(open, close, brackets, currentIndex) {
    // search in all brackets for other brackets that are a superstring of these brackets
    let pieces = [];
    pieces = pieces.concat(open);
    pieces = pieces.concat(close);
    for (let i = 0, len = pieces.length; i < len; i++) {
        collectSuperstrings(pieces[i], brackets, currentIndex, pieces);
    }
    pieces = unique(pieces);
    pieces.sort(lengthcmp);
    pieces.reverse();
    return createBracketOrRegExp(pieces);
}
/**
 * Matching a regular expression in JS can only be done "forwards". So JS offers natively only
 * methods to find the first match of a regex in a string. But sometimes, it is useful to
 * find the last match of a regex in a string. For such a situation, a nice solution is to
 * simply reverse the string and then search for a reversed regex.
 *
 * This function also has the fine details of `getRegexForBracketPair`. For the same example
 * given above, the regex produced here would look like:
 *   /(\bfi dne\b)|(\bdne\b)|(\bfi\b)/
 */
function getReversedRegexForBracketPair(open, close, brackets, currentIndex) {
    // search in all brackets for other brackets that are a superstring of these brackets
    let pieces = [];
    pieces = pieces.concat(open);
    pieces = pieces.concat(close);
    for (let i = 0, len = pieces.length; i < len; i++) {
        collectSuperstrings(pieces[i], brackets, currentIndex, pieces);
    }
    pieces = unique(pieces);
    pieces.sort(lengthcmp);
    pieces.reverse();
    return createBracketOrRegExp(pieces.map(toReversedString));
}
/**
 * Creates a regular expression that targets all bracket pairs.
 *
 * e.g. for the bracket pairs:
 *  ['{','}']
 *  ['begin,'end']
 *  ['for','end']
 * the regex would look like:
 *  /(\{)|(\})|(\bbegin\b)|(\bend\b)|(\bfor\b)/
 */
function getRegexForBrackets(brackets) {
    let pieces = [];
    for (const bracket of brackets) {
        for (const open of bracket.open) {
            pieces.push(open);
        }
        for (const close of bracket.close) {
            pieces.push(close);
        }
    }
    pieces = unique(pieces);
    return createBracketOrRegExp(pieces);
}
/**
 * Matching a regular expression in JS can only be done "forwards". So JS offers natively only
 * methods to find the first match of a regex in a string. But sometimes, it is useful to
 * find the last match of a regex in a string. For such a situation, a nice solution is to
 * simply reverse the string and then search for a reversed regex.
 *
 * e.g. for the bracket pairs:
 *  ['{','}']
 *  ['begin,'end']
 *  ['for','end']
 * the regex would look like:
 *  /(\{)|(\})|(\bnigeb\b)|(\bdne\b)|(\brof\b)/
 */
function getReversedRegexForBrackets(brackets) {
    let pieces = [];
    for (const bracket of brackets) {
        for (const open of bracket.open) {
            pieces.push(open);
        }
        for (const close of bracket.close) {
            pieces.push(close);
        }
    }
    pieces = unique(pieces);
    return createBracketOrRegExp(pieces.map(toReversedString));
}
function prepareBracketForRegExp(str) {
    // This bracket pair uses letters like e.g. "begin" - "end"
    const insertWordBoundaries = (/^[\w ]+$/.test(str));
    str = escapeRegExpCharacters(str);
    return (insertWordBoundaries ? `\\b${str}\\b` : str);
}
function createBracketOrRegExp(pieces) {
    const regexStr = `(${pieces.map(prepareBracketForRegExp).join(')|(')})`;
    return createRegExp(regexStr, true);
}
const toReversedString = (function () {
    function reverse(str) {
        if (hasTextDecoder) {
            // create a Uint16Array and then use a TextDecoder to create a string
            const arr = new Uint16Array(str.length);
            let offset = 0;
            for (let i = str.length - 1; i >= 0; i--) {
                arr[offset++] = str.charCodeAt(i);
            }
            return getPlatformTextDecoder().decode(arr);
        }
        else {
            const result = [];
            let resultLen = 0;
            for (let i = str.length - 1; i >= 0; i--) {
                result[resultLen++] = str.charAt(i);
            }
            return result.join('');
        }
    }
    let lastInput = null;
    let lastOutput = null;
    return function toReversedString(str) {
        if (lastInput !== str) {
            lastInput = str;
            lastOutput = reverse(lastInput);
        }
        return lastOutput;
    };
})();
class BracketsUtils {
    static _findPrevBracketInText(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 Range(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1);
    }
    static findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, startOffset, endOffset) {
        // Because JS does not support backwards regex search, we search forwards in a reversed string with a reversed regex ;)
        const reversedLineText = toReversedString(lineText);
        const reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset);
        return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedSubstr, startOffset);
    }
    static findNextBracketInText(bracketRegex, lineNumber, text, offset) {
        const m = text.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 Range(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);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/supports/electricCharacter.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class BracketElectricCharacterSupport {
    constructor(richEditBrackets) {
        this._richEditBrackets = richEditBrackets;
    }
    getElectricCharacters() {
        const result = [];
        if (this._richEditBrackets) {
            for (const bracket of this._richEditBrackets.brackets) {
                for (const close of bracket.close) {
                    const lastChar = close.charAt(close.length - 1);
                    result.push(lastChar);
                }
            }
        }
        return distinct(result);
    }
    onElectricCharacter(character, context, column) {
        if (!this._richEditBrackets || this._richEditBrackets.brackets.length === 0) {
            return null;
        }
        const tokenIndex = context.findTokenIndexAtOffset(column - 1);
        if (ignoreBracketsInToken(context.getStandardTokenType(tokenIndex))) {
            return null;
        }
        const reversedBracketRegex = this._richEditBrackets.reversedRegex;
        const text = context.getLineContent().substring(0, column - 1) + character;
        const r = BracketsUtils.findPrevBracketInRange(reversedBracketRegex, 1, text, 0, text.length);
        if (!r) {
            return null;
        }
        const bracketText = text.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
        const isOpen = this._richEditBrackets.textIsOpenBracket[bracketText];
        if (isOpen) {
            return null;
        }
        const textBeforeBracket = context.getActualLineContentBefore(r.startColumn - 1);
        if (!/^\s*$/.test(textBeforeBracket)) {
            // There is other text on the line before the bracket
            return null;
        }
        return {
            matchOpenBracket: bracketText
        };
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/supports/indentRules.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
function resetGlobalRegex(reg) {
    if (reg.global) {
        reg.lastIndex = 0;
    }
    return true;
}
class IndentRulesSupport {
    constructor(indentationRules) {
        this._indentationRules = indentationRules;
    }
    shouldIncrease(text) {
        if (this._indentationRules) {
            if (this._indentationRules.increaseIndentPattern && resetGlobalRegex(this._indentationRules.increaseIndentPattern) && this._indentationRules.increaseIndentPattern.test(text)) {
                return true;
            }
            // if (this._indentationRules.indentNextLinePattern && this._indentationRules.indentNextLinePattern.test(text)) {
            // 	return true;
            // }
        }
        return false;
    }
    shouldDecrease(text) {
        if (this._indentationRules && this._indentationRules.decreaseIndentPattern && resetGlobalRegex(this._indentationRules.decreaseIndentPattern) && this._indentationRules.decreaseIndentPattern.test(text)) {
            return true;
        }
        return false;
    }
    shouldIndentNextLine(text) {
        if (this._indentationRules && this._indentationRules.indentNextLinePattern && resetGlobalRegex(this._indentationRules.indentNextLinePattern) && this._indentationRules.indentNextLinePattern.test(text)) {
            return true;
        }
        return false;
    }
    shouldIgnore(text) {
        // the text matches `unIndentedLinePattern`
        if (this._indentationRules && this._indentationRules.unIndentedLinePattern && resetGlobalRegex(this._indentationRules.unIndentedLinePattern) && this._indentationRules.unIndentedLinePattern.test(text)) {
            return true;
        }
        return false;
    }
    getIndentMetadata(text) {
        let ret = 0;
        if (this.shouldIncrease(text)) {
            ret += 1 /* IndentConsts.INCREASE_MASK */;
        }
        if (this.shouldDecrease(text)) {
            ret += 2 /* IndentConsts.DECREASE_MASK */;
        }
        if (this.shouldIndentNextLine(text)) {
            ret += 4 /* IndentConsts.INDENT_NEXTLINE_MASK */;
        }
        if (this.shouldIgnore(text)) {
            ret += 8 /* IndentConsts.UNINDENT_MASK */;
        }
        return ret;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/supports/onEnter.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class OnEnterSupport {
    constructor(opts) {
        opts = opts || {};
        opts.brackets = opts.brackets || [
            ['(', ')'],
            ['{', '}'],
            ['[', ']']
        ];
        this._brackets = [];
        opts.brackets.forEach((bracket) => {
            const openRegExp = OnEnterSupport._createOpenBracketRegExp(bracket[0]);
            const closeRegExp = OnEnterSupport._createCloseBracketRegExp(bracket[1]);
            if (openRegExp && closeRegExp) {
                this._brackets.push({
                    open: bracket[0],
                    openRegExp: openRegExp,
                    close: bracket[1],
                    closeRegExp: closeRegExp,
                });
            }
        });
        this._regExpRules = opts.onEnterRules || [];
    }
    onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) {
        // (1): `regExpRules`
        if (autoIndent >= 3 /* EditorAutoIndentStrategy.Advanced */) {
            for (let i = 0, len = this._regExpRules.length; i < len; i++) {
                const rule = this._regExpRules[i];
                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; // To disable the effect of the "g" flag.
                    return obj.reg.test(obj.text);
                });
                if (regResult) {
                    return rule.action;
                }
            }
        }
        // (2): Special indent-outdent
        if (autoIndent >= 2 /* EditorAutoIndentStrategy.Brackets */) {
            if (beforeEnterText.length > 0 && afterEnterText.length > 0) {
                for (let i = 0, len = this._brackets.length; i < len; i++) {
                    const bracket = this._brackets[i];
                    if (bracket.openRegExp.test(beforeEnterText) && bracket.closeRegExp.test(afterEnterText)) {
                        return { indentAction: IndentAction.IndentOutdent };
                    }
                }
            }
        }
        // (4): Open bracket based logic
        if (autoIndent >= 2 /* EditorAutoIndentStrategy.Brackets */) {
            if (beforeEnterText.length > 0) {
                for (let i = 0, len = this._brackets.length; i < len; i++) {
                    const bracket = this._brackets[i];
                    if (bracket.openRegExp.test(beforeEnterText)) {
                        return { indentAction: IndentAction.Indent };
                    }
                }
            }
        }
        return null;
    }
    static _createOpenBracketRegExp(bracket) {
        let str = escapeRegExpCharacters(bracket);
        if (!/\B/.test(str.charAt(0))) {
            str = '\\b' + str;
        }
        str += '\\s*$';
        return OnEnterSupport._safeRegExp(str);
    }
    static _createCloseBracketRegExp(bracket) {
        let str = escapeRegExpCharacters(bracket);
        if (!/\B/.test(str.charAt(str.length - 1))) {
            str = str + '\\b';
        }
        str = '^\\s*' + str;
        return OnEnterSupport._safeRegExp(str);
    }
    static _safeRegExp(def) {
        try {
            return new RegExp(def);
        }
        catch (err) {
            onUnexpectedError(err);
            return null;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/configuration/common/configuration.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const IConfigurationService = createDecorator('configurationService');
function toValuesTree(properties, conflictReporter) {
    const root = Object.create(null);
    for (const key in properties) {
        addToValueTree(root, key, properties[key], conflictReporter);
    }
    return root;
}
function addToValueTree(settingsTreeRoot, key, value, conflictReporter) {
    const segments = key.split('.');
    const last = segments.pop();
    let curr = settingsTreeRoot;
    for (let i = 0; i < segments.length; i++) {
        const s = segments[i];
        let obj = curr[s];
        switch (typeof obj) {
            case 'undefined':
                obj = curr[s] = Object.create(null);
                break;
            case 'object':
                break;
            default:
                conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join('.')} is ${JSON.stringify(obj)}`);
                return;
        }
        curr = obj;
    }
    if (typeof curr === 'object' && curr !== null) {
        try {
            curr[last] = value; // workaround https://github.com/microsoft/vscode/issues/13606
        }
        catch (e) {
            conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`);
        }
    }
    else {
        conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`);
    }
}
function removeFromValueTree(valueTree, key) {
    const segments = key.split('.');
    doRemoveFromValueTree(valueTree, segments);
}
function doRemoveFromValueTree(valueTree, segments) {
    const first = segments.shift();
    if (segments.length === 0) {
        // Reached last segment
        delete valueTree[first];
        return;
    }
    if (Object.keys(valueTree).indexOf(first) !== -1) {
        const value = valueTree[first];
        if (typeof value === 'object' && !Array.isArray(value)) {
            doRemoveFromValueTree(value, segments);
            if (Object.keys(value).length === 0) {
                delete valueTree[first];
            }
        }
    }
}
/**
 * A helper function to get the configuration value with a specific settings path (e.g. config.some.setting)
 */
function getConfigurationValue(config, settingPath, defaultValue) {
    function accessSetting(config, path) {
        let current = config;
        for (const component of path) {
            if (typeof current !== 'object' || current === null) {
                return undefined;
            }
            current = current[component];
        }
        return current;
    }
    const path = settingPath.split('.');
    const result = accessSetting(config, path);
    return typeof result === 'undefined' ? defaultValue : result;
}
function getLanguageTagSettingPlainKey(settingKey) {
    return settingKey.replace(/[\[\]]/g, '');
}

;// ../../node_modules/monaco-editor/esm/vs/platform/instantiation/common/descriptors.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class SyncDescriptor {
    constructor(ctor, staticArguments = [], supportsDelayedInstantiation = false) {
        this.ctor = ctor;
        this.staticArguments = staticArguments;
        this.supportsDelayedInstantiation = supportsDelayedInstantiation;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/instantiation/common/extensions.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const _registry = [];
function registerSingleton(id, ctorOrDescriptor, supportsDelayedInstantiation) {
    if (!(ctorOrDescriptor instanceof SyncDescriptor)) {
        ctorOrDescriptor = new SyncDescriptor(ctorOrDescriptor, [], supportsDelayedInstantiation);
    }
    _registry.push([id, ctorOrDescriptor]);
}
function getSingletonServiceDescriptors() {
    return _registry;
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/mime.js
const Mimes = Object.freeze({
    text: 'text/plain',
    binary: 'application/octet-stream',
    unknown: 'application/unknown',
    markdown: 'text/markdown',
    latex: 'text/latex',
    uriList: 'text/uri-list',
});

;// ../../node_modules/monaco-editor/esm/vs/platform/configuration/common/configurationRegistry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







const configurationRegistry_Extensions = {
    Configuration: 'base.contributions.configuration'
};
const allSettings = { properties: {}, patternProperties: {} };
const applicationSettings = { properties: {}, patternProperties: {} };
const machineSettings = { properties: {}, patternProperties: {} };
const machineOverridableSettings = { properties: {}, patternProperties: {} };
const windowSettings = { properties: {}, patternProperties: {} };
const resourceSettings = { properties: {}, patternProperties: {} };
const resourceLanguageSettingsSchemaId = 'vscode://schemas/settings/resourceLanguage';
const contributionRegistry = Registry.as(jsonContributionRegistry_Extensions.JSONContribution);
class ConfigurationRegistry {
    constructor() {
        this.overrideIdentifiers = new Set();
        this._onDidSchemaChange = new Emitter();
        this._onDidUpdateConfiguration = new Emitter();
        this.configurationDefaultsOverrides = new Map();
        this.defaultLanguageConfigurationOverridesNode = {
            id: 'defaultOverrides',
            title: localize('defaultLanguageConfigurationOverrides.title', "Default Language Configuration Overrides"),
            properties: {}
        };
        this.configurationContributors = [this.defaultLanguageConfigurationOverridesNode];
        this.resourceLanguageSettingsSchema = { properties: {}, patternProperties: {}, additionalProperties: false, errorMessage: 'Unknown editor configuration setting', allowTrailingCommas: true, allowComments: true };
        this.configurationProperties = {};
        this.policyConfigurations = new Map();
        this.excludedConfigurationProperties = {};
        contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
        this.registerOverridePropertyPatternKey();
    }
    registerConfiguration(configuration, validate = true) {
        this.registerConfigurations([configuration], validate);
    }
    registerConfigurations(configurations, validate = true) {
        const properties = this.doRegisterConfigurations(configurations, validate);
        contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
        this._onDidSchemaChange.fire();
        this._onDidUpdateConfiguration.fire({ properties });
    }
    registerDefaultConfigurations(configurationDefaults) {
        var _a;
        const properties = [];
        const overrideIdentifiers = [];
        for (const { overrides, source } of configurationDefaults) {
            for (const key in overrides) {
                properties.push(key);
                if (OVERRIDE_PROPERTY_REGEX.test(key)) {
                    const configurationDefaultOverride = this.configurationDefaultsOverrides.get(key);
                    const valuesSources = (_a = configurationDefaultOverride === null || configurationDefaultOverride === void 0 ? void 0 : configurationDefaultOverride.valuesSources) !== null && _a !== void 0 ? _a : new Map();
                    if (source) {
                        for (const configuration of Object.keys(overrides[key])) {
                            valuesSources.set(configuration, source);
                        }
                    }
                    const defaultValue = Object.assign(Object.assign({}, ((configurationDefaultOverride === null || configurationDefaultOverride === void 0 ? void 0 : configurationDefaultOverride.value) || {})), overrides[key]);
                    this.configurationDefaultsOverrides.set(key, { source, value: defaultValue, valuesSources });
                    const plainKey = getLanguageTagSettingPlainKey(key);
                    const property = {
                        type: 'object',
                        default: defaultValue,
                        description: localize('defaultLanguageConfiguration.description', "Configure settings to be overridden for the {0} language.", plainKey),
                        $ref: resourceLanguageSettingsSchemaId,
                        defaultDefaultValue: defaultValue,
                        source: isString(source) ? undefined : source,
                        defaultValueSource: source
                    };
                    overrideIdentifiers.push(...overrideIdentifiersFromKey(key));
                    this.configurationProperties[key] = property;
                    this.defaultLanguageConfigurationOverridesNode.properties[key] = property;
                }
                else {
                    this.configurationDefaultsOverrides.set(key, { value: overrides[key], source });
                    const property = this.configurationProperties[key];
                    if (property) {
                        this.updatePropertyDefaultValue(key, property);
                        this.updateSchema(key, property);
                    }
                }
            }
        }
        this.registerOverrideIdentifiers(overrideIdentifiers);
        this._onDidSchemaChange.fire();
        this._onDidUpdateConfiguration.fire({ properties, defaultsOverrides: true });
    }
    registerOverrideIdentifiers(overrideIdentifiers) {
        for (const overrideIdentifier of overrideIdentifiers) {
            this.overrideIdentifiers.add(overrideIdentifier);
        }
        this.updateOverridePropertyPatternKey();
    }
    doRegisterConfigurations(configurations, validate) {
        const properties = [];
        configurations.forEach(configuration => {
            properties.push(...this.validateAndRegisterProperties(configuration, validate, configuration.extensionInfo, configuration.restrictedProperties)); // fills in defaults
            this.configurationContributors.push(configuration);
            this.registerJSONConfiguration(configuration);
        });
        return properties;
    }
    validateAndRegisterProperties(configuration, validate = true, extensionInfo, restrictedProperties, scope = 3 /* ConfigurationScope.WINDOW */) {
        var _a;
        scope = isUndefinedOrNull(configuration.scope) ? scope : configuration.scope;
        const propertyKeys = [];
        const properties = configuration.properties;
        if (properties) {
            for (const key in properties) {
                const property = properties[key];
                if (validate && validateProperty(key, property)) {
                    delete properties[key];
                    continue;
                }
                property.source = extensionInfo;
                // update default value
                property.defaultDefaultValue = properties[key].default;
                this.updatePropertyDefaultValue(key, property);
                // update scope
                if (OVERRIDE_PROPERTY_REGEX.test(key)) {
                    property.scope = undefined; // No scope for overridable properties `[${identifier}]`
                }
                else {
                    property.scope = isUndefinedOrNull(property.scope) ? scope : property.scope;
                    property.restricted = isUndefinedOrNull(property.restricted) ? !!(restrictedProperties === null || restrictedProperties === void 0 ? void 0 : restrictedProperties.includes(key)) : property.restricted;
                }
                // Add to properties maps
                // Property is included by default if 'included' is unspecified
                if (properties[key].hasOwnProperty('included') && !properties[key].included) {
                    this.excludedConfigurationProperties[key] = properties[key];
                    delete properties[key];
                    continue;
                }
                else {
                    this.configurationProperties[key] = properties[key];
                    if ((_a = properties[key].policy) === null || _a === void 0 ? void 0 : _a.name) {
                        this.policyConfigurations.set(properties[key].policy.name, key);
                    }
                }
                if (!properties[key].deprecationMessage && properties[key].markdownDeprecationMessage) {
                    // If not set, default deprecationMessage to the markdown source
                    properties[key].deprecationMessage = properties[key].markdownDeprecationMessage;
                }
                propertyKeys.push(key);
            }
        }
        const subNodes = configuration.allOf;
        if (subNodes) {
            for (const node of subNodes) {
                propertyKeys.push(...this.validateAndRegisterProperties(node, validate, extensionInfo, restrictedProperties, scope));
            }
        }
        return propertyKeys;
    }
    getConfigurationProperties() {
        return this.configurationProperties;
    }
    getPolicyConfigurations() {
        return this.policyConfigurations;
    }
    registerJSONConfiguration(configuration) {
        const register = (configuration) => {
            const properties = configuration.properties;
            if (properties) {
                for (const key in properties) {
                    this.updateSchema(key, properties[key]);
                }
            }
            const subNodes = configuration.allOf;
            subNodes === null || subNodes === void 0 ? void 0 : subNodes.forEach(register);
        };
        register(configuration);
    }
    updateSchema(key, property) {
        allSettings.properties[key] = property;
        switch (property.scope) {
            case 1 /* ConfigurationScope.APPLICATION */:
                applicationSettings.properties[key] = property;
                break;
            case 2 /* ConfigurationScope.MACHINE */:
                machineSettings.properties[key] = property;
                break;
            case 6 /* ConfigurationScope.MACHINE_OVERRIDABLE */:
                machineOverridableSettings.properties[key] = property;
                break;
            case 3 /* ConfigurationScope.WINDOW */:
                windowSettings.properties[key] = property;
                break;
            case 4 /* ConfigurationScope.RESOURCE */:
                resourceSettings.properties[key] = property;
                break;
            case 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */:
                resourceSettings.properties[key] = property;
                this.resourceLanguageSettingsSchema.properties[key] = property;
                break;
        }
    }
    updateOverridePropertyPatternKey() {
        for (const overrideIdentifier of this.overrideIdentifiers.values()) {
            const overrideIdentifierProperty = `[${overrideIdentifier}]`;
            const resourceLanguagePropertiesSchema = {
                type: 'object',
                description: localize('overrideSettings.defaultDescription', "Configure editor settings to be overridden for a language."),
                errorMessage: localize('overrideSettings.errorMessage', "This setting does not support per-language configuration."),
                $ref: resourceLanguageSettingsSchemaId,
            };
            this.updatePropertyDefaultValue(overrideIdentifierProperty, resourceLanguagePropertiesSchema);
            allSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
            applicationSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
            machineSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
            machineOverridableSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
            windowSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
            resourceSettings.properties[overrideIdentifierProperty] = resourceLanguagePropertiesSchema;
        }
        this._onDidSchemaChange.fire();
    }
    registerOverridePropertyPatternKey() {
        const resourceLanguagePropertiesSchema = {
            type: 'object',
            description: localize('overrideSettings.defaultDescription', "Configure editor settings to be overridden for a language."),
            errorMessage: localize('overrideSettings.errorMessage', "This setting does not support per-language configuration."),
            $ref: resourceLanguageSettingsSchemaId,
        };
        allSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
        applicationSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
        machineSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
        machineOverridableSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
        windowSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
        resourceSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
        this._onDidSchemaChange.fire();
    }
    updatePropertyDefaultValue(key, property) {
        const configurationdefaultOverride = this.configurationDefaultsOverrides.get(key);
        let defaultValue = configurationdefaultOverride === null || configurationdefaultOverride === void 0 ? void 0 : configurationdefaultOverride.value;
        let defaultSource = configurationdefaultOverride === null || configurationdefaultOverride === void 0 ? void 0 : configurationdefaultOverride.source;
        if (isUndefined(defaultValue)) {
            defaultValue = property.defaultDefaultValue;
            defaultSource = undefined;
        }
        if (isUndefined(defaultValue)) {
            defaultValue = getDefaultValue(property.type);
        }
        property.default = defaultValue;
        property.defaultValueSource = defaultSource;
    }
}
const OVERRIDE_IDENTIFIER_PATTERN = `\\[([^\\]]+)\\]`;
const OVERRIDE_IDENTIFIER_REGEX = new RegExp(OVERRIDE_IDENTIFIER_PATTERN, 'g');
const OVERRIDE_PROPERTY_PATTERN = `^(${OVERRIDE_IDENTIFIER_PATTERN})+$`;
const OVERRIDE_PROPERTY_REGEX = new RegExp(OVERRIDE_PROPERTY_PATTERN);
function overrideIdentifiersFromKey(key) {
    const identifiers = [];
    if (OVERRIDE_PROPERTY_REGEX.test(key)) {
        let matches = OVERRIDE_IDENTIFIER_REGEX.exec(key);
        while (matches === null || matches === void 0 ? void 0 : matches.length) {
            const identifier = matches[1].trim();
            if (identifier) {
                identifiers.push(identifier);
            }
            matches = OVERRIDE_IDENTIFIER_REGEX.exec(key);
        }
    }
    return distinct(identifiers);
}
function getDefaultValue(type) {
    const t = Array.isArray(type) ? type[0] : type;
    switch (t) {
        case 'boolean':
            return false;
        case 'integer':
        case 'number':
            return 0;
        case 'string':
            return '';
        case 'array':
            return [];
        case 'object':
            return {};
        default:
            return null;
    }
}
const configurationRegistry = new ConfigurationRegistry();
Registry.add(configurationRegistry_Extensions.Configuration, configurationRegistry);
function validateProperty(property, schema) {
    var _a, _b, _c, _d;
    if (!property.trim()) {
        return localize('config.property.empty', "Cannot register an empty property");
    }
    if (OVERRIDE_PROPERTY_REGEX.test(property)) {
        return localize('config.property.languageDefault', "Cannot register '{0}'. This matches property pattern '\\\\[.*\\\\]$' for describing language specific editor settings. Use 'configurationDefaults' contribution.", property);
    }
    if (configurationRegistry.getConfigurationProperties()[property] !== undefined) {
        return localize('config.property.duplicate', "Cannot register '{0}'. This property is already registered.", property);
    }
    if (((_a = schema.policy) === null || _a === void 0 ? void 0 : _a.name) && configurationRegistry.getPolicyConfigurations().get((_b = schema.policy) === null || _b === void 0 ? void 0 : _b.name) !== undefined) {
        return localize('config.policy.duplicate', "Cannot register '{0}'. The associated policy {1} is already registered with {2}.", property, (_c = schema.policy) === null || _c === void 0 ? void 0 : _c.name, configurationRegistry.getPolicyConfigurations().get((_d = schema.policy) === null || _d === void 0 ? void 0 : _d.name));
    }
    return null;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/modesRegistry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





// Define extension point ids
const modesRegistry_Extensions = {
    ModesRegistry: 'editor.modesRegistry'
};
class EditorModesRegistry {
    constructor() {
        this._onDidChangeLanguages = new Emitter();
        this.onDidChangeLanguages = this._onDidChangeLanguages.event;
        this._languages = [];
    }
    registerLanguage(def) {
        this._languages.push(def);
        this._onDidChangeLanguages.fire(undefined);
        return {
            dispose: () => {
                for (let i = 0, len = this._languages.length; i < len; i++) {
                    if (this._languages[i] === def) {
                        this._languages.splice(i, 1);
                        return;
                    }
                }
            }
        };
    }
    getLanguages() {
        return this._languages;
    }
}
const ModesRegistry = new EditorModesRegistry();
Registry.add(modesRegistry_Extensions.ModesRegistry, ModesRegistry);
const PLAINTEXT_LANGUAGE_ID = 'plaintext';
const PLAINTEXT_EXTENSION = '.txt';
ModesRegistry.registerLanguage({
    id: PLAINTEXT_LANGUAGE_ID,
    extensions: [PLAINTEXT_EXTENSION],
    aliases: [localize('plainText.alias', "Plain Text"), 'text'],
    mimetypes: [Mimes.text]
});
Registry.as(configurationRegistry_Extensions.Configuration)
    .registerDefaultConfigurations([{
        overrides: {
            '[plaintext]': {
                'editor.unicodeHighlight.ambiguousCharacters': false,
                'editor.unicodeHighlight.invisibleCharacters': false
            }
        }
    }]);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/supports/languageBracketsConfiguration.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


/**
 * Captures all bracket related configurations for a single language.
 * Immutable.
*/
class LanguageBracketsConfiguration {
    constructor(languageId, config) {
        this.languageId = languageId;
        let brackets;
        // Prefer colorized bracket pairs, as they are more accurate.
        // TODO@hediet: Deprecate `colorizedBracketPairs` and increase accuracy for brackets.
        if (config.colorizedBracketPairs) {
            brackets = filterValidBrackets(config.colorizedBracketPairs.map(b => [b[0], b[1]]));
        }
        else if (config.brackets) {
            brackets = filterValidBrackets(config.brackets
                .map((b) => [b[0], b[1]])
                // Many languages set < ... > as bracket pair, even though they also use it as comparison operator.
                // This leads to problems when colorizing this bracket, so we exclude it by default.
                // Languages can still override this by configuring `colorizedBracketPairs`
                // https://github.com/microsoft/vscode/issues/132476
                .filter((p) => !(p[0] === '<' && p[1] === '>')));
        }
        else {
            brackets = [];
        }
        const openingBracketInfos = new CachedFunction((bracket) => {
            const closing = new Set();
            return {
                info: new OpeningBracketKind(this, bracket, closing),
                closing,
            };
        });
        const closingBracketInfos = new CachedFunction((bracket) => {
            const opening = new Set();
            return {
                info: new ClosingBracketKind(this, bracket, opening),
                opening,
            };
        });
        for (const [open, close] of brackets) {
            const opening = openingBracketInfos.get(open);
            const closing = closingBracketInfos.get(close);
            opening.closing.add(closing.info);
            closing.opening.add(opening.info);
        }
        this._openingBrackets = new Map([...openingBracketInfos.cachedValues].map(([k, v]) => [k, v.info]));
        this._closingBrackets = new Map([...closingBracketInfos.cachedValues].map(([k, v]) => [k, v.info]));
    }
    /**
     * No two brackets have the same bracket text.
    */
    get openingBrackets() {
        return [...this._openingBrackets.values()];
    }
    /**
     * No two brackets have the same bracket text.
    */
    get closingBrackets() {
        return [...this._closingBrackets.values()];
    }
    getOpeningBracketInfo(bracketText) {
        return this._openingBrackets.get(bracketText);
    }
    getClosingBracketInfo(bracketText) {
        return this._closingBrackets.get(bracketText);
    }
    getBracketInfo(bracketText) {
        return this.getOpeningBracketInfo(bracketText) || this.getClosingBracketInfo(bracketText);
    }
}
function filterValidBrackets(bracketPairs) {
    return bracketPairs.filter(([open, close]) => open !== '' && close !== '');
}
class BracketKindBase {
    constructor(config, bracketText) {
        this.config = config;
        this.bracketText = bracketText;
    }
    get languageId() {
        return this.config.languageId;
    }
}
class OpeningBracketKind extends BracketKindBase {
    constructor(config, bracketText, openedBrackets) {
        super(config, bracketText);
        this.openedBrackets = openedBrackets;
        this.isOpeningBracket = true;
    }
}
class ClosingBracketKind extends BracketKindBase {
    constructor(config, bracketText, 
    /**
     * Non empty array of all opening brackets this bracket closes.
    */
    closedBrackets) {
        super(config, bracketText);
        this.closedBrackets = closedBrackets;
        this.isOpeningBracket = false;
    }
    /**
     * Checks if this bracket closes the given other bracket.
     * Brackets from other language configuration can be used (they will always return false).
     * If other is a bracket with the same language id, they have to be from the same configuration.
    */
    closes(other) {
        if (other.languageId === this.languageId) {
            if (other['config'] !== this.config) {
                throw new BugIndicatingError('Brackets from different language configuration cannot be used.');
            }
        }
        return this.closedBrackets.has(other);
    }
    getClosedBrackets() {
        return [...this.closedBrackets];
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/languageConfigurationRegistry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var languageConfigurationRegistry_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var languageConfigurationRegistry_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};

















class LanguageConfigurationServiceChangeEvent {
    constructor(languageId) {
        this.languageId = languageId;
    }
    affects(languageId) {
        return !this.languageId ? true : this.languageId === languageId;
    }
}
const ILanguageConfigurationService = createDecorator('languageConfigurationService');
let LanguageConfigurationService = class LanguageConfigurationService extends Disposable {
    constructor(configurationService, languageService) {
        super();
        this.configurationService = configurationService;
        this.languageService = languageService;
        this._registry = this._register(new LanguageConfigurationRegistry());
        this.onDidChangeEmitter = this._register(new Emitter());
        this.onDidChange = this.onDidChangeEmitter.event;
        this.configurations = new Map();
        const languageConfigKeys = new Set(Object.values(customizedLanguageConfigKeys));
        this._register(this.configurationService.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.configurations.clear();
                this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(undefined));
            }
            else {
                for (const languageId of localConfigChanged) {
                    if (this.languageService.isRegisteredLanguageId(languageId)) {
                        this.configurations.delete(languageId);
                        this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(languageId));
                    }
                }
            }
        }));
        this._register(this._registry.onDidChange((e) => {
            this.configurations.delete(e.languageId);
            this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(e.languageId));
        }));
    }
    register(languageId, configuration, priority) {
        return this._registry.register(languageId, configuration, priority);
    }
    getLanguageConfiguration(languageId) {
        let result = this.configurations.get(languageId);
        if (!result) {
            result = computeConfig(languageId, this._registry, this.configurationService, this.languageService);
            this.configurations.set(languageId, result);
        }
        return result;
    }
};
LanguageConfigurationService = languageConfigurationRegistry_decorate([
    languageConfigurationRegistry_param(0, IConfigurationService),
    languageConfigurationRegistry_param(1, ILanguageService)
], LanguageConfigurationService);

function computeConfig(languageId, registry, configurationService, languageService) {
    let languageConfig = registry.getLanguageConfiguration(languageId);
    if (!languageConfig) {
        if (!languageService.isRegisteredLanguageId(languageId)) {
            throw new Error(`Language id "${languageId}" is not configured nor known`);
        }
        languageConfig = new ResolvedLanguageConfiguration(languageId, {});
    }
    const customizedConfig = getCustomizedLanguageConfig(languageConfig.languageId, configurationService);
    const data = combineLanguageConfigurations([languageConfig.underlyingConfig, customizedConfig]);
    const config = new ResolvedLanguageConfiguration(languageConfig.languageId, data);
    return config;
}
const 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 undefined;
    }
    return data.map(pair => {
        if (!Array.isArray(pair) || pair.length !== 2) {
            return undefined;
        }
        return [pair[0], pair[1]];
    }).filter((p) => !!p);
}
function getIndentationAtPosition(model, lineNumber, column) {
    const lineText = model.getLineContent(lineNumber);
    let indentation = getLeadingWhitespace(lineText);
    if (indentation.length > column - 1) {
        indentation = indentation.substring(0, column - 1);
    }
    return indentation;
}
function getScopedLineTokens(model, lineNumber, columnNumber) {
    model.tokenization.forceTokenization(lineNumber);
    const lineTokens = model.tokenization.getLineTokens(lineNumber);
    const column = (typeof columnNumber === 'undefined' ? model.getLineMaxColumn(lineNumber) - 1 : columnNumber - 1);
    return createScopedLineTokens(lineTokens, column);
}
class ComposedLanguageConfiguration {
    constructor(languageId) {
        this.languageId = languageId;
        this._resolved = null;
        this._entries = [];
        this._order = 0;
        this._resolved = null;
    }
    register(configuration, priority) {
        const entry = new LanguageConfigurationContribution(configuration, priority, ++this._order);
        this._entries.push(entry);
        this._resolved = null;
        return toDisposable(() => {
            for (let i = 0; i < this._entries.length; i++) {
                if (this._entries[i] === entry) {
                    this._entries.splice(i, 1);
                    this._resolved = null;
                    break;
                }
            }
        });
    }
    getResolvedConfiguration() {
        if (!this._resolved) {
            const config = this._resolve();
            if (config) {
                this._resolved = new ResolvedLanguageConfiguration(this.languageId, config);
            }
        }
        return this._resolved;
    }
    _resolve() {
        if (this._entries.length === 0) {
            return null;
        }
        this._entries.sort(LanguageConfigurationContribution.cmp);
        return combineLanguageConfigurations(this._entries.map(e => e.configuration));
    }
}
function combineLanguageConfigurations(configs) {
    let result = {
        comments: undefined,
        brackets: undefined,
        wordPattern: undefined,
        indentationRules: undefined,
        onEnterRules: undefined,
        autoClosingPairs: undefined,
        surroundingPairs: undefined,
        autoCloseBefore: undefined,
        folding: undefined,
        colorizedBracketPairs: undefined,
        __electricCharacterSupport: undefined,
    };
    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;
}
class LanguageConfigurationContribution {
    constructor(configuration, priority, order) {
        this.configuration = configuration;
        this.priority = priority;
        this.order = order;
    }
    static cmp(a, b) {
        if (a.priority === b.priority) {
            // higher order last
            return a.order - b.order;
        }
        // higher priority last
        return a.priority - b.priority;
    }
}
class LanguageConfigurationChangeEvent {
    constructor(languageId) {
        this.languageId = languageId;
    }
}
class LanguageConfigurationRegistry extends Disposable {
    constructor() {
        super();
        this._entries = new Map();
        this._onDidChange = this._register(new Emitter());
        this.onDidChange = this._onDidChange.event;
        this._register(this.register(PLAINTEXT_LANGUAGE_ID, {
            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, configuration, priority = 0) {
        let entries = this._entries.get(languageId);
        if (!entries) {
            entries = new ComposedLanguageConfiguration(languageId);
            this._entries.set(languageId, entries);
        }
        const disposable = entries.register(configuration, priority);
        this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId));
        return toDisposable(() => {
            disposable.dispose();
            this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId));
        });
    }
    getLanguageConfiguration(languageId) {
        const entries = this._entries.get(languageId);
        return (entries === null || entries === void 0 ? void 0 : entries.getResolvedConfiguration()) || null;
    }
}
/**
 * Immutable.
*/
class ResolvedLanguageConfiguration {
    constructor(languageId, underlyingConfig) {
        this.languageId = languageId;
        this.underlyingConfig = underlyingConfig;
        this._brackets = null;
        this._electricCharacter = null;
        this._onEnterSupport =
            this.underlyingConfig.brackets ||
                this.underlyingConfig.indentationRules ||
                this.underlyingConfig.onEnterRules
                ? new OnEnterSupport(this.underlyingConfig)
                : null;
        this.comments = ResolvedLanguageConfiguration._handleComments(this.underlyingConfig);
        this.characterPair = new CharacterPairSupport(this.underlyingConfig);
        this.wordDefinition = this.underlyingConfig.wordPattern || DEFAULT_WORD_REGEXP;
        this.indentationRules = this.underlyingConfig.indentationRules;
        if (this.underlyingConfig.indentationRules) {
            this.indentRulesSupport = new IndentRulesSupport(this.underlyingConfig.indentationRules);
        }
        else {
            this.indentRulesSupport = null;
        }
        this.foldingRules = this.underlyingConfig.folding || {};
        this.bracketsNew = new LanguageBracketsConfiguration(languageId, this.underlyingConfig);
    }
    getWordDefinition() {
        return ensureValidWordDefinition(this.wordDefinition);
    }
    get brackets() {
        if (!this._brackets && this.underlyingConfig.brackets) {
            this._brackets = new RichEditBrackets(this.languageId, this.underlyingConfig.brackets);
        }
        return this._brackets;
    }
    get electricCharacter() {
        if (!this._electricCharacter) {
            this._electricCharacter = new BracketElectricCharacterSupport(this.brackets);
        }
        return this._electricCharacter;
    }
    onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) {
        if (!this._onEnterSupport) {
            return null;
        }
        return this._onEnterSupport.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText);
    }
    getAutoClosingPairs() {
        return new AutoClosingPairs(this.characterPair.getAutoClosingPairs());
    }
    getAutoCloseBeforeSet() {
        return this.characterPair.getAutoCloseBeforeSet();
    }
    getSurroundingPairs() {
        return this.characterPair.getSurroundingPairs();
    }
    static _handleComments(conf) {
        const commentRule = conf.comments;
        if (!commentRule) {
            return null;
        }
        // comment configuration
        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;
    }
}
registerSingleton(ILanguageConfigurationService, LanguageConfigurationService);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/textModelBracketPairs.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class BracketInfo {
    constructor(range, 
    /** 0-based level */
    nestingLevel, nestingLevelOfEqualBracketType, isInvalid) {
        this.range = range;
        this.nestingLevel = nestingLevel;
        this.nestingLevelOfEqualBracketType = nestingLevelOfEqualBracketType;
        this.isInvalid = isInvalid;
    }
}
class BracketPairInfo {
    constructor(range, openingBracketRange, closingBracketRange, 
    /** 0-based */
    nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode) {
        this.range = range;
        this.openingBracketRange = openingBracketRange;
        this.closingBracketRange = closingBracketRange;
        this.nestingLevel = nestingLevel;
        this.nestingLevelOfEqualBracketType = nestingLevelOfEqualBracketType;
        this.bracketPairNode = bracketPairNode;
    }
    get openingBracketInfo() {
        return this.bracketPairNode.openingBracket.bracketInfo;
    }
}
class BracketPairWithMinIndentationInfo extends BracketPairInfo {
    constructor(range, openingBracketRange, closingBracketRange, 
    /**
     * 0-based
    */
    nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode, 
    /**
     * -1 if not requested, otherwise the size of the minimum indentation in the bracket pair in terms of visible columns.
    */
    minVisibleColumnIndentation) {
        super(range, openingBracketRange, closingBracketRange, nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode);
        this.minVisibleColumnIndentation = minVisibleColumnIndentation;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/length.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


/**
 * Represents a non-negative length in terms of line and column count.
 * Prefer using {@link Length} for performance reasons.
*/
class LengthObj {
    constructor(lineCount, columnCount) {
        this.lineCount = lineCount;
        this.columnCount = columnCount;
    }
    toString() {
        return `${this.lineCount},${this.columnCount}`;
    }
}
LengthObj.zero = new LengthObj(0, 0);
/**
 * The end must be greater than or equal to the start.
*/
function lengthDiff(startLineCount, startColumnCount, endLineCount, endColumnCount) {
    return (startLineCount !== endLineCount)
        ? toLength(endLineCount - startLineCount, endColumnCount)
        : toLength(0, endColumnCount - startColumnCount);
}
const lengthZero = 0;
function lengthIsZero(length) {
    return length === 0;
}
/*
 * We have 52 bits available in a JS number.
 * We use the upper 26 bits to store the line and the lower 26 bits to store the column.
 *
 * Set boolean to `true` when debugging, so that debugging is easier.
 */
const factor = /* is debug: */  false ? 0 : Math.pow(2, 26);
function toLength(lineCount, columnCount) {
    // llllllllllllllllllllllllllcccccccccccccccccccccccccc (52 bits)
    //       line count (26 bits)    column count (26 bits)
    // If there is no overflow (all values/sums below 2^26 = 67108864),
    // we have `toLength(lns1, cols1) + toLength(lns2, cols2) = toLength(lns1 + lns2, cols1 + cols2)`.
    return (lineCount * factor + columnCount);
}
function lengthToObj(length) {
    const l = length;
    const lineCount = Math.floor(l / factor);
    const columnCount = l - lineCount * factor;
    return new LengthObj(lineCount, columnCount);
}
function lengthGetLineCount(length) {
    return Math.floor(length / factor);
}
/**
 * Returns the amount of columns of the given length, assuming that it does not span any line.
*/
function lengthGetColumnCountIfZeroLineCount(length) {
    return length;
}
function lengthAdd(l1, l2) {
    return ((l2 < factor)
        ? (l1 + l2) // l2 is the amount of columns (zero line count). Keep the column count from l1.
        : (l1 - (l1 % factor) + l2)); // l1 - (l1 % factor) equals toLength(l1.lineCount, 0)
}
/**
 * Returns a non negative length `result` such that `lengthAdd(length1, result) = length2`, or zero if such length does not exist.
 */
function lengthDiffNonNegative(length1, length2) {
    const l1 = length1;
    const l2 = length2;
    const diff = l2 - l1;
    if (diff <= 0) {
        // line-count of length1 is higher than line-count of length2
        // or they are equal and column-count of length1 is higher than column-count of length2
        return lengthZero;
    }
    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 toLength(0, colCount2 - colCount1);
    }
    else {
        return toLength(lineCount2 - lineCount1, colCount2);
    }
}
function lengthLessThan(length1, length2) {
    // First, compare line counts, then column counts.
    return length1 < length2;
}
function lengthLessThanEqual(length1, length2) {
    return length1 <= length2;
}
function lengthGreaterThanEqual(length1, length2) {
    return length1 >= length2;
}
function positionToLength(position) {
    return toLength(position.lineNumber - 1, position.column - 1);
}
function lengthsToRange(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 Range(lineCount + 1, colCount + 1, lineCount2 + 1, colCount2 + 1);
}
function lengthOfString(str) {
    const lines = splitLines(str);
    return toLength(lines.length - 1, lines[lines.length - 1].length);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/beforeEditPositionMapper.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class TextEditInfo {
    constructor(startOffset, endOffset, newLength) {
        this.startOffset = startOffset;
        this.endOffset = endOffset;
        this.newLength = newLength;
    }
}
class BeforeEditPositionMapper {
    /**
     * @param edits Must be sorted by offset in ascending order.
    */
    constructor(edits, documentLength) {
        this.documentLength = documentLength;
        this.nextEditIdx = 0;
        this.deltaOldToNewLineCount = 0;
        this.deltaOldToNewColumnCount = 0;
        this.deltaLineIdxInOld = -1;
        this.edits = edits.map(edit => TextEditInfoCache.from(edit));
    }
    /**
     * @param offset Must be equal to or greater than the last offset this method has been called with.
    */
    getOffsetBeforeChange(offset) {
        this.adjustNextEdit(offset);
        return this.translateCurToOld(offset);
    }
    /**
     * @param offset Must be equal to or greater than the last offset this method has been called with.
    */
    getDistanceToNextChange(offset) {
        this.adjustNextEdit(offset);
        const nextEdit = this.edits[this.nextEditIdx];
        const nextChangeOffset = nextEdit ? this.translateOldToCur(nextEdit.offsetObj) : this.documentLength;
        return lengthDiffNonNegative(offset, nextChangeOffset);
    }
    translateOldToCur(oldOffsetObj) {
        if (oldOffsetObj.lineCount === this.deltaLineIdxInOld) {
            return toLength(oldOffsetObj.lineCount + this.deltaOldToNewLineCount, oldOffsetObj.columnCount + this.deltaOldToNewColumnCount);
        }
        else {
            return toLength(oldOffsetObj.lineCount + this.deltaOldToNewLineCount, oldOffsetObj.columnCount);
        }
    }
    translateCurToOld(newOffset) {
        const offsetObj = lengthToObj(newOffset);
        if (offsetObj.lineCount - this.deltaOldToNewLineCount === this.deltaLineIdxInOld) {
            return toLength(offsetObj.lineCount - this.deltaOldToNewLineCount, offsetObj.columnCount - this.deltaOldToNewColumnCount);
        }
        else {
            return toLength(offsetObj.lineCount - this.deltaOldToNewLineCount, offsetObj.columnCount);
        }
    }
    adjustNextEdit(offset) {
        while (this.nextEditIdx < this.edits.length) {
            const nextEdit = this.edits[this.nextEditIdx];
            // After applying the edit, what is its end offset (considering all previous edits)?
            const nextEditEndOffsetInCur = this.translateOldToCur(nextEdit.endOffsetAfterObj);
            if (lengthLessThanEqual(nextEditEndOffsetInCur, offset)) {
                // We are after the edit, skip it
                this.nextEditIdx++;
                const nextEditEndOffsetInCurObj = lengthToObj(nextEditEndOffsetInCur);
                // Before applying the edit, what is its end offset (considering all previous edits)?
                const nextEditEndOffsetBeforeInCurObj = lengthToObj(this.translateOldToCur(nextEdit.endOffsetBeforeObj));
                const lineDelta = nextEditEndOffsetInCurObj.lineCount - nextEditEndOffsetBeforeInCurObj.lineCount;
                this.deltaOldToNewLineCount += lineDelta;
                const previousColumnDelta = this.deltaLineIdxInOld === nextEdit.endOffsetBeforeObj.lineCount ? this.deltaOldToNewColumnCount : 0;
                const columnDelta = nextEditEndOffsetInCurObj.columnCount - nextEditEndOffsetBeforeInCurObj.columnCount;
                this.deltaOldToNewColumnCount = previousColumnDelta + columnDelta;
                this.deltaLineIdxInOld = nextEdit.endOffsetBeforeObj.lineCount;
            }
            else {
                // We are in or before the edit.
                break;
            }
        }
    }
}
class TextEditInfoCache {
    constructor(startOffset, endOffset, textLength) {
        this.endOffsetBeforeObj = lengthToObj(endOffset);
        this.endOffsetAfterObj = lengthToObj(lengthAdd(startOffset, textLength));
        this.offsetObj = lengthToObj(startOffset);
    }
    static from(edit) {
        return new TextEditInfoCache(edit.startOffset, edit.endOffset, edit.newLength);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/smallImmutableSet.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
const emptyArr = new Array();
/**
 * Represents an immutable set that works best for a small number of elements (less than 32).
 * It uses bits to encode element membership efficiently.
*/
class SmallImmutableSet {
    constructor(items, additionalItems) {
        this.items = items;
        this.additionalItems = additionalItems;
    }
    static create(items, additionalItems) {
        if (items <= 128 && additionalItems.length === 0) {
            // We create a cache of 128=2^7 elements to cover all sets with up to 7 (dense) elements.
            let cached = SmallImmutableSet.cache[items];
            if (!cached) {
                cached = new SmallImmutableSet(items, additionalItems);
                SmallImmutableSet.cache[items] = cached;
            }
            return cached;
        }
        return new SmallImmutableSet(items, additionalItems);
    }
    static getEmpty() {
        return this.empty;
    }
    add(value, keyProvider) {
        const key = keyProvider.getKey(value);
        let idx = key >> 5; // divided by 32
        if (idx === 0) {
            // fast path
            const newItem = (1 << key) | this.items;
            if (newItem === this.items) {
                return this;
            }
            return SmallImmutableSet.create(newItem, this.additionalItems);
        }
        idx--;
        const newItems = this.additionalItems.slice(0);
        while (newItems.length < idx) {
            newItems.push(0);
        }
        newItems[idx] |= 1 << (key & 31);
        return SmallImmutableSet.create(this.items, newItems);
    }
    merge(other) {
        const merged = this.items | other.items;
        if (this.additionalItems === emptyArr && other.additionalItems === emptyArr) {
            // fast path
            if (merged === this.items) {
                return this;
            }
            if (merged === other.items) {
                return other;
            }
            return SmallImmutableSet.create(merged, emptyArr);
        }
        // This can be optimized, but it's not a common case
        const newItems = new Array();
        for (let i = 0; i < Math.max(this.additionalItems.length, other.additionalItems.length); i++) {
            const item1 = this.additionalItems[i] || 0;
            const item2 = other.additionalItems[i] || 0;
            newItems.push(item1 | item2);
        }
        return SmallImmutableSet.create(merged, newItems);
    }
    intersects(other) {
        if ((this.items & other.items) !== 0) {
            return true;
        }
        for (let i = 0; i < Math.min(this.additionalItems.length, other.additionalItems.length); i++) {
            if ((this.additionalItems[i] & other.additionalItems[i]) !== 0) {
                return true;
            }
        }
        return false;
    }
}
SmallImmutableSet.cache = new Array(129);
SmallImmutableSet.empty = SmallImmutableSet.create(0, emptyArr);
const identityKeyProvider = {
    getKey(value) {
        return value;
    }
};
/**
 * Assigns values a unique incrementing key.
*/
class DenseKeyProvider {
    constructor() {
        this.items = new Map();
    }
    getKey(value) {
        let existing = this.items.get(value);
        if (existing === undefined) {
            existing = this.items.size;
            this.items.set(value, existing);
        }
        return existing;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/ast.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



/**
 * The base implementation for all AST nodes.
*/
class BaseAstNode {
    constructor(length) {
        this._length = length;
    }
    /**
     * The length of the entire node, which should equal the sum of lengths of all children.
    */
    get length() {
        return this._length;
    }
}
/**
 * Represents a bracket pair including its child (e.g. `{ ... }`).
 * Might be unclosed.
 * Immutable, if all children are immutable.
*/
class PairAstNode extends BaseAstNode {
    constructor(length, openingBracket, child, closingBracket, missingOpeningBracketIds) {
        super(length);
        this.openingBracket = openingBracket;
        this.child = child;
        this.closingBracket = closingBracket;
        this.missingOpeningBracketIds = missingOpeningBracketIds;
    }
    static create(openingBracket, child, closingBracket) {
        let length = openingBracket.length;
        if (child) {
            length = lengthAdd(length, child.length);
        }
        if (closingBracket) {
            length = lengthAdd(length, closingBracket.length);
        }
        return new PairAstNode(length, openingBracket, child, closingBracket, child ? child.missingOpeningBracketIds : SmallImmutableSet.getEmpty());
    }
    get kind() {
        return 2 /* AstNodeKind.Pair */;
    }
    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 = new Array();
        result.push(this.openingBracket);
        if (this.child) {
            result.push(this.child);
        }
        if (this.closingBracket) {
            result.push(this.closingBracket);
        }
        return result;
    }
    canBeReused(openBracketIds) {
        if (this.closingBracket === null) {
            // Unclosed pair ast nodes only
            // end at the end of the document
            // or when a parent node is closed.
            // This could be improved:
            // Only return false if some next token is neither "undefined" nor a bracket that closes a parent.
            return false;
        }
        if (openBracketIds.intersects(this.missingOpeningBracketIds)) {
            return false;
        }
        return true;
    }
    deepClone() {
        return new PairAstNode(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(lengthAdd(offset, this.openingBracket.length), textModel) : Number.MAX_SAFE_INTEGER;
    }
}
class ListAstNode extends BaseAstNode {
    /**
     * Use ListAstNode.create.
    */
    constructor(length, listHeight, _missingOpeningBracketIds) {
        super(length);
        this.listHeight = listHeight;
        this._missingOpeningBracketIds = _missingOpeningBracketIds;
        this.cachedMinIndentation = -1;
    }
    /**
     * 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 = lengthAdd(length, item2.length);
        missingBracketIds = missingBracketIds.merge(item2.missingOpeningBracketIds);
        if (item3) {
            if (item1.listHeight !== item3.listHeight) {
                throw new Error('Invalid list heights');
            }
            length = lengthAdd(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 getEmpty() {
        return new ImmutableArrayListAstNode(lengthZero, 0, [], SmallImmutableSet.getEmpty());
    }
    get kind() {
        return 4 /* AstNodeKind.List */;
    }
    get missingOpeningBracketIds() {
        return this._missingOpeningBracketIds;
    }
    throwIfImmutable() {
        // NOOP
    }
    makeLastElementMutable() {
        this.throwIfImmutable();
        const childCount = this.childrenLength;
        if (childCount === 0) {
            return undefined;
        }
        const lastChild = this.getChild(childCount - 1);
        const mutable = lastChild.kind === 4 /* AstNodeKind.List */ ? lastChild.toMutable() : lastChild;
        if (lastChild !== mutable) {
            this.setChild(childCount - 1, mutable);
        }
        return mutable;
    }
    makeFirstElementMutable() {
        this.throwIfImmutable();
        const childCount = this.childrenLength;
        if (childCount === 0) {
            return undefined;
        }
        const firstChild = this.getChild(0);
        const mutable = firstChild.kind === 4 /* AstNodeKind.List */ ? firstChild.toMutable() : firstChild;
        if (firstChild !== mutable) {
            this.setChild(0, mutable);
        }
        return mutable;
    }
    canBeReused(openBracketIds) {
        if (openBracketIds.intersects(this.missingOpeningBracketIds)) {
            return false;
        }
        let lastChild = this;
        let lastLength;
        while (lastChild.kind === 4 /* AstNodeKind.List */ && (lastLength = lastChild.childrenLength) > 0) {
            lastChild = lastChild.getChild(lastLength - 1);
        }
        return lastChild.canBeReused(openBracketIds);
    }
    handleChildrenChanged() {
        this.throwIfImmutable();
        const count = this.childrenLength;
        let length = this.getChild(0).length;
        let unopenedBrackets = this.getChild(0).missingOpeningBracketIds;
        for (let i = 1; i < count; i++) {
            const child = this.getChild(i);
            length = lengthAdd(length, child.length);
            unopenedBrackets = unopenedBrackets.merge(child.missingOpeningBracketIds);
        }
        this._length = length;
        this._missingOpeningBracketIds = unopenedBrackets;
        this.cachedMinIndentation = -1;
    }
    computeMinIndentation(offset, textModel) {
        if (this.cachedMinIndentation !== -1) {
            return this.cachedMinIndentation;
        }
        let minIndentation = Number.MAX_SAFE_INTEGER;
        let childOffset = offset;
        for (let i = 0; i < this.childrenLength; i++) {
            const child = this.getChild(i);
            if (child) {
                minIndentation = Math.min(minIndentation, child.computeMinIndentation(childOffset, textModel));
                childOffset = lengthAdd(childOffset, child.length);
            }
        }
        this.cachedMinIndentation = minIndentation;
        return minIndentation;
    }
}
class TwoThreeListAstNode extends ListAstNode {
    constructor(length, listHeight, _item1, _item2, _item3, missingOpeningBracketIds) {
        super(length, listHeight, missingOpeningBracketIds);
        this._item1 = _item1;
        this._item2 = _item2;
        this._item3 = _item3;
    }
    get childrenLength() {
        return this._item3 !== null ? 3 : 2;
    }
    getChild(idx) {
        switch (idx) {
            case 0: return this._item1;
            case 1: return this._item2;
            case 2: return this._item3;
        }
        throw new Error('Invalid child index');
    }
    setChild(idx, node) {
        switch (idx) {
            case 0:
                this._item1 = node;
                return;
            case 1:
                this._item2 = node;
                return;
            case 2:
                this._item3 = node;
                return;
        }
        throw new Error('Invalid child index');
    }
    get children() {
        return this._item3 ? [this._item1, this._item2, this._item3] : [this._item1, this._item2];
    }
    get item1() {
        return this._item1;
    }
    get item2() {
        return this._item2;
    }
    get item3() {
        return this._item3;
    }
    deepClone() {
        return new TwoThreeListAstNode(this.length, this.listHeight, this._item1.deepClone(), this._item2.deepClone(), this._item3 ? this._item3.deepClone() : null, this.missingOpeningBracketIds);
    }
    appendChildOfSameHeight(node) {
        if (this._item3) {
            throw new Error('Cannot append to a full (2,3) tree node');
        }
        this.throwIfImmutable();
        this._item3 = node;
        this.handleChildrenChanged();
    }
    unappendChild() {
        if (!this._item3) {
            throw new Error('Cannot remove from a non-full (2,3) tree node');
        }
        this.throwIfImmutable();
        const result = this._item3;
        this._item3 = null;
        this.handleChildrenChanged();
        return result;
    }
    prependChildOfSameHeight(node) {
        if (this._item3) {
            throw new Error('Cannot prepend to a full (2,3) tree node');
        }
        this.throwIfImmutable();
        this._item3 = this._item2;
        this._item2 = this._item1;
        this._item1 = node;
        this.handleChildrenChanged();
    }
    unprependChild() {
        if (!this._item3) {
            throw new Error('Cannot remove from a non-full (2,3) tree node');
        }
        this.throwIfImmutable();
        const result = this._item1;
        this._item1 = this._item2;
        this._item2 = this._item3;
        this._item3 = null;
        this.handleChildrenChanged();
        return result;
    }
    toMutable() {
        return this;
    }
}
/**
 * Immutable, if all children are immutable.
*/
class Immutable23ListAstNode extends TwoThreeListAstNode {
    toMutable() {
        return new TwoThreeListAstNode(this.length, this.listHeight, this.item1, this.item2, this.item3, this.missingOpeningBracketIds);
    }
    throwIfImmutable() {
        throw new Error('this instance is immutable');
    }
}
/**
 * For debugging.
*/
class ArrayListAstNode extends ListAstNode {
    constructor(length, listHeight, _children, missingOpeningBracketIds) {
        super(length, listHeight, missingOpeningBracketIds);
        this._children = _children;
    }
    get childrenLength() {
        return this._children.length;
    }
    getChild(idx) {
        return this._children[idx];
    }
    setChild(idx, child) {
        this._children[idx] = child;
    }
    get children() {
        return this._children;
    }
    deepClone() {
        const children = new Array(this._children.length);
        for (let i = 0; i < this._children.length; i++) {
            children[i] = this._children[i].deepClone();
        }
        return new ArrayListAstNode(this.length, this.listHeight, children, this.missingOpeningBracketIds);
    }
    appendChildOfSameHeight(node) {
        this.throwIfImmutable();
        this._children.push(node);
        this.handleChildrenChanged();
    }
    unappendChild() {
        this.throwIfImmutable();
        const item = this._children.pop();
        this.handleChildrenChanged();
        return item;
    }
    prependChildOfSameHeight(node) {
        this.throwIfImmutable();
        this._children.unshift(node);
        this.handleChildrenChanged();
    }
    unprependChild() {
        this.throwIfImmutable();
        const item = this._children.shift();
        this.handleChildrenChanged();
        return item;
    }
    toMutable() {
        return this;
    }
}
/**
 * Immutable, if all children are immutable.
*/
class ImmutableArrayListAstNode extends ArrayListAstNode {
    toMutable() {
        return new ArrayListAstNode(this.length, this.listHeight, [...this.children], this.missingOpeningBracketIds);
    }
    throwIfImmutable() {
        throw new Error('this instance is immutable');
    }
}
const emptyArray = [];
class ImmutableLeafAstNode extends BaseAstNode {
    get listHeight() {
        return 0;
    }
    get childrenLength() {
        return 0;
    }
    getChild(idx) {
        return null;
    }
    get children() {
        return emptyArray;
    }
    deepClone() {
        return this;
    }
}
class TextAstNode extends ImmutableLeafAstNode {
    get kind() {
        return 0 /* AstNodeKind.Text */;
    }
    get missingOpeningBracketIds() {
        return SmallImmutableSet.getEmpty();
    }
    canBeReused(_openedBracketIds) {
        return true;
    }
    computeMinIndentation(offset, textModel) {
        const start = lengthToObj(offset);
        // Text ast nodes don't have partial indentation (ensured by the tokenizer).
        // Thus, if this text node does not start at column 0, the first line cannot have any indentation at all.
        const startLineNumber = (start.columnCount === 0 ? start.lineCount : start.lineCount + 1) + 1;
        const endLineNumber = lengthGetLineCount(lengthAdd(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 = CursorColumns.visibleColumnFromColumn(lineContent, firstNonWsColumn, textModel.getOptions().tabSize);
            result = Math.min(result, visibleColumn);
        }
        return result;
    }
}
class BracketAstNode extends ImmutableLeafAstNode {
    constructor(length, bracketInfo, 
    /**
     * In case of a opening bracket, this is the id of the opening bracket.
     * In case of a closing bracket, this contains the ids of all opening brackets it can close.
    */
    bracketIds) {
        super(length);
        this.bracketInfo = bracketInfo;
        this.bracketIds = bracketIds;
    }
    static create(length, bracketInfo, bracketIds) {
        const node = new BracketAstNode(length, bracketInfo, bracketIds);
        return node;
    }
    get kind() {
        return 1 /* AstNodeKind.Bracket */;
    }
    get missingOpeningBracketIds() {
        return SmallImmutableSet.getEmpty();
    }
    get text() {
        return this.bracketInfo.bracketText;
    }
    get languageId() {
        return this.bracketInfo.languageId;
    }
    canBeReused(_openedBracketIds) {
        // These nodes could be reused,
        // but not in a general way.
        // Their parent may be reused.
        return false;
    }
    computeMinIndentation(offset, textModel) {
        return Number.MAX_SAFE_INTEGER;
    }
}
class InvalidBracketAstNode extends ImmutableLeafAstNode {
    constructor(closingBrackets, length) {
        super(length);
        this.missingOpeningBracketIds = closingBrackets;
    }
    get kind() {
        return 3 /* AstNodeKind.UnexpectedClosingBracket */;
    }
    canBeReused(openedBracketIds) {
        return !openedBracketIds.intersects(this.missingOpeningBracketIds);
    }
    computeMinIndentation(offset, textModel) {
        return Number.MAX_SAFE_INTEGER;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/encodedTokenAttributes.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/**
 */
class TokenMetadata {
    static getLanguageId(metadata) {
        return (metadata & 255 /* MetadataConsts.LANGUAGEID_MASK */) >>> 0 /* MetadataConsts.LANGUAGEID_OFFSET */;
    }
    static getTokenType(metadata) {
        return (metadata & 768 /* MetadataConsts.TOKEN_TYPE_MASK */) >>> 8 /* MetadataConsts.TOKEN_TYPE_OFFSET */;
    }
    static containsBalancedBrackets(metadata) {
        return (metadata & 1024 /* MetadataConsts.BALANCED_BRACKETS_MASK */) !== 0;
    }
    static getFontStyle(metadata) {
        return (metadata & 30720 /* MetadataConsts.FONT_STYLE_MASK */) >>> 11 /* MetadataConsts.FONT_STYLE_OFFSET */;
    }
    static getForeground(metadata) {
        return (metadata & 16744448 /* MetadataConsts.FOREGROUND_MASK */) >>> 15 /* MetadataConsts.FOREGROUND_OFFSET */;
    }
    static getBackground(metadata) {
        return (metadata & 4278190080 /* MetadataConsts.BACKGROUND_MASK */) >>> 24 /* MetadataConsts.BACKGROUND_OFFSET */;
    }
    static getClassNameFromMetadata(metadata) {
        const foreground = this.getForeground(metadata);
        let className = 'mtk' + foreground;
        const fontStyle = this.getFontStyle(metadata);
        if (fontStyle & 1 /* FontStyle.Italic */) {
            className += ' mtki';
        }
        if (fontStyle & 2 /* FontStyle.Bold */) {
            className += ' mtkb';
        }
        if (fontStyle & 4 /* FontStyle.Underline */) {
            className += ' mtku';
        }
        if (fontStyle & 8 /* FontStyle.Strikethrough */) {
            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 /* FontStyle.Italic */) {
            result += 'font-style: italic;';
        }
        if (fontStyle & 2 /* FontStyle.Bold */) {
            result += 'font-weight: bold;';
        }
        let textDecoration = '';
        if (fontStyle & 4 /* FontStyle.Underline */) {
            textDecoration += ' underline';
        }
        if (fontStyle & 8 /* FontStyle.Strikethrough */) {
            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: 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 */),
        };
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/tokenizer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class Token {
    constructor(length, kind, 
    /**
     * If this token is an opening bracket, this is the id of the opening bracket.
     * If this token is a closing bracket, this is the id of the first opening bracket that is closed by this bracket.
     * Otherwise, it is -1.
     */
    bracketId, 
    /**
     * If this token is an opening bracket, this just contains `bracketId`.
     * If this token is a closing bracket, this lists all opening bracket ids, that it closes.
     * Otherwise, it is empty.
     */
    bracketIds, astNode) {
        this.length = length;
        this.kind = kind;
        this.bracketId = bracketId;
        this.bracketIds = bracketIds;
        this.astNode = astNode;
    }
}
class TextBufferTokenizer {
    constructor(textModel, bracketTokens) {
        this.textModel = textModel;
        this.bracketTokens = bracketTokens;
        this.reader = new NonPeekableTextBufferTokenizer(this.textModel, this.bracketTokens);
        this._offset = lengthZero;
        this.didPeek = false;
        this.peeked = null;
        this.textBufferLineCount = textModel.getLineCount();
        this.textBufferLastLineLength = textModel.getLineLength(this.textBufferLineCount);
    }
    get offset() {
        return this._offset;
    }
    get length() {
        return toLength(this.textBufferLineCount, this.textBufferLastLineLength);
    }
    skip(length) {
        this.didPeek = false;
        this._offset = lengthAdd(this._offset, length);
        const obj = lengthToObj(this._offset);
        this.reader.setPosition(obj.lineCount, obj.columnCount);
    }
    read() {
        let token;
        if (this.peeked) {
            this.didPeek = false;
            token = this.peeked;
        }
        else {
            token = this.reader.read();
        }
        if (token) {
            this._offset = lengthAdd(this._offset, token.length);
        }
        return token;
    }
    peek() {
        if (!this.didPeek) {
            this.peeked = this.reader.read();
            this.didPeek = true;
        }
        return this.peeked;
    }
}
/**
 * Does not support peek.
*/
class NonPeekableTextBufferTokenizer {
    constructor(textModel, bracketTokens) {
        this.textModel = textModel;
        this.bracketTokens = bracketTokens;
        this.lineIdx = 0;
        this.line = null;
        this.lineCharOffset = 0;
        this.lineTokens = null;
        this.lineTokenOffset = 0;
        /** Must be a zero line token. The end of the document cannot be peeked. */
        this.peekedToken = null;
        this.textBufferLineCount = textModel.getLineCount();
        this.textBufferLastLineLength = textModel.getLineLength(this.textBufferLineCount);
    }
    setPosition(lineIdx, column) {
        // We must not jump into a token!
        if (lineIdx === this.lineIdx) {
            this.lineCharOffset = column;
            this.lineTokenOffset = this.lineCharOffset === 0 ? 0 : this.lineTokens.findTokenIndexAtOffset(this.lineCharOffset);
        }
        else {
            this.lineIdx = lineIdx;
            this.lineCharOffset = column;
            this.line = null;
        }
        this.peekedToken = null;
    }
    read() {
        if (this.peekedToken) {
            const token = this.peekedToken;
            this.peekedToken = null;
            this.lineCharOffset += lengthGetColumnCountIfZeroLineCount(token.length);
            return token;
        }
        if (this.lineIdx > this.textBufferLineCount - 1 || (this.lineIdx === this.textBufferLineCount - 1 && this.lineCharOffset >= this.textBufferLastLineLength)) {
            // We are after the end
            return null;
        }
        if (this.line === null) {
            this.lineTokens = this.textModel.tokenization.getLineTokens(this.lineIdx + 1);
            this.line = this.lineTokens.getLineContent();
            this.lineTokenOffset = this.lineCharOffset === 0 ? 0 : this.lineTokens.findTokenIndexAtOffset(this.lineCharOffset);
        }
        const startLineIdx = this.lineIdx;
        const startLineCharOffset = this.lineCharOffset;
        // limits the length of text tokens.
        // If text tokens get too long, incremental updates will be slow
        let lengthHeuristic = 0;
        while (true) {
            const lineTokens = this.lineTokens;
            const tokenCount = lineTokens.getCount();
            let peekedBracketToken = null;
            if (this.lineTokenOffset < tokenCount) {
                const tokenMetadata = lineTokens.getMetadata(this.lineTokenOffset);
                while (this.lineTokenOffset + 1 < tokenCount && tokenMetadata === lineTokens.getMetadata(this.lineTokenOffset + 1)) {
                    // Skip tokens that are identical.
                    // Sometimes, (bracket) identifiers are split up into multiple tokens.
                    this.lineTokenOffset++;
                }
                const isOther = TokenMetadata.getTokenType(tokenMetadata) === 0 /* StandardTokenType.Other */;
                const containsBracketType = TokenMetadata.containsBalancedBrackets(tokenMetadata);
                const endOffset = lineTokens.getEndOffset(this.lineTokenOffset);
                // Is there a bracket token next? Only consume text.
                if (containsBracketType && isOther && this.lineCharOffset < endOffset) {
                    const languageId = lineTokens.getLanguageId(this.lineTokenOffset);
                    const text = this.line.substring(this.lineCharOffset, endOffset);
                    const brackets = this.bracketTokens.getSingleLanguageBracketTokens(languageId);
                    const regexp = brackets.regExpGlobal;
                    if (regexp) {
                        regexp.lastIndex = 0;
                        const match = regexp.exec(text);
                        if (match) {
                            peekedBracketToken = brackets.getToken(match[0]);
                            if (peekedBracketToken) {
                                // Consume leading text of the token
                                this.lineCharOffset += match.index;
                            }
                        }
                    }
                }
                lengthHeuristic += endOffset - this.lineCharOffset;
                if (peekedBracketToken) {
                    // Don't skip the entire token, as a single token could contain multiple brackets.
                    if (startLineIdx !== this.lineIdx || startLineCharOffset !== this.lineCharOffset) {
                        // There is text before the bracket
                        this.peekedToken = peekedBracketToken;
                        break;
                    }
                    else {
                        // Consume the peeked token
                        this.lineCharOffset += lengthGetColumnCountIfZeroLineCount(peekedBracketToken.length);
                        return peekedBracketToken;
                    }
                }
                else {
                    // Skip the entire token, as the token contains no brackets at all.
                    this.lineTokenOffset++;
                    this.lineCharOffset = endOffset;
                }
            }
            else {
                if (this.lineIdx === this.textBufferLineCount - 1) {
                    break;
                }
                this.lineIdx++;
                this.lineTokens = this.textModel.tokenization.getLineTokens(this.lineIdx + 1);
                this.lineTokenOffset = 0;
                this.line = this.lineTokens.getLineContent();
                this.lineCharOffset = 0;
                lengthHeuristic += 33; // max 1000/33 = 30 lines
                // This limits the amount of work to recompute min-indentation
                if (lengthHeuristic > 1000) {
                    // only break (automatically) at the end of line.
                    break;
                }
            }
            if (lengthHeuristic > 1500) {
                // Eventually break regardless of the line length so that
                // very long lines do not cause bad performance.
                // This effective limits max indentation to 500, as
                // indentation is not computed across multiple text nodes.
                break;
            }
        }
        // If a token contains some proper indentation, it also contains \n{INDENTATION+}(?!{INDENTATION}),
        // unless the line is too long.
        // Thus, the min indentation of the document is the minimum min indentation of every text node.
        const length = lengthDiff(startLineIdx, startLineCharOffset, this.lineIdx, this.lineCharOffset);
        return new Token(length, 0 /* TokenKind.Text */, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length));
    }
}
class FastTokenizer {
    constructor(text, brackets) {
        this.text = text;
        this._offset = lengthZero;
        this.idx = 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 = new Array();
        for (let i = 0; i < 60; i++) {
            smallTextTokens0Line.push(new Token(toLength(0, i), 0 /* TokenKind.Text */, -1, SmallImmutableSet.getEmpty(), new TextAstNode(toLength(0, i))));
        }
        const smallTextTokens1Line = new Array();
        for (let i = 0; i < 60; i++) {
            smallTextTokens1Line.push(new Token(toLength(1, i), 0 /* TokenKind.Text */, -1, SmallImmutableSet.getEmpty(), new TextAstNode(toLength(1, i))));
        }
        if (regexp) {
            regexp.lastIndex = 0;
            // If a token contains indentation, it also contains \n{INDENTATION+}(?!{INDENTATION})
            while ((match = regexp.exec(text)) !== 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 = toLength(0, colCount);
                                token = new Token(length, 0 /* TokenKind.Text */, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length));
                            }
                        }
                        else {
                            const lineCount = curLineCount - lastTokenEndLine;
                            const colCount = curOffset - lastLineBreakOffset;
                            if (lineCount === 1 && colCount < smallTextTokens1Line.length) {
                                token = smallTextTokens1Line[colCount];
                            }
                            else {
                                const length = toLength(lineCount, colCount);
                                token = new Token(length, 0 /* TokenKind.Text */, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length));
                            }
                        }
                        tokens.push(token);
                    }
                    // value is matched by regexp, so the token must exist
                    tokens.push(brackets.getToken(value));
                    lastTokenEndOffset = curOffset + value.length;
                    lastTokenEndLine = curLineCount;
                }
            }
        }
        const offset = text.length;
        if (lastTokenEndOffset !== offset) {
            const length = (lastTokenEndLine === curLineCount)
                ? toLength(0, offset - lastTokenEndOffset)
                : toLength(curLineCount - lastTokenEndLine, offset - lastLineBreakOffset);
            tokens.push(new Token(length, 0 /* TokenKind.Text */, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length)));
        }
        this.length = toLength(curLineCount, offset - lastLineBreakOffset);
        this.tokens = tokens;
    }
    get offset() {
        return this._offset;
    }
    read() {
        return this.tokens[this.idx++] || null;
    }
    peek() {
        return this.tokens[this.idx] || null;
    }
    skip(length) {
        throw new NotSupportedError();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/brackets.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class BracketTokens {
    constructor(map) {
        this.map = map;
        this.hasRegExp = false;
        this._regExpGlobal = null;
    }
    static createFromLanguage(configuration, denseKeyProvider) {
        function getId(bracketInfo) {
            return denseKeyProvider.getKey(`${bracketInfo.languageId}:::${bracketInfo.bracketText}`);
        }
        const map = new Map();
        for (const openingBracket of configuration.bracketsNew.openingBrackets) {
            const length = toLength(0, openingBracket.bracketText.length);
            const openingTextId = getId(openingBracket);
            const bracketIds = SmallImmutableSet.getEmpty().add(openingTextId, identityKeyProvider);
            map.set(openingBracket.bracketText, new Token(length, 1 /* TokenKind.OpeningBracket */, openingTextId, bracketIds, BracketAstNode.create(length, openingBracket, bracketIds)));
        }
        for (const closingBracket of configuration.bracketsNew.closingBrackets) {
            const length = toLength(0, closingBracket.bracketText.length);
            let bracketIds = SmallImmutableSet.getEmpty();
            const closingBrackets = closingBracket.getClosedBrackets();
            for (const bracket of closingBrackets) {
                bracketIds = bracketIds.add(getId(bracket), identityKeyProvider);
            }
            map.set(closingBracket.bracketText, new Token(length, 2 /* TokenKind.ClosingBracket */, getId(closingBrackets[0]), bracketIds, BracketAstNode.create(length, closingBracket, bracketIds)));
        }
        return new BracketTokens(map);
    }
    getRegExpStr() {
        if (this.isEmpty) {
            return null;
        }
        else {
            const keys = [...this.map.keys()];
            keys.sort();
            keys.reverse();
            return keys.map(k => brackets_prepareBracketForRegExp(k)).join('|');
        }
    }
    /**
     * Returns null if there is no such regexp (because there are no brackets).
    */
    get regExpGlobal() {
        if (!this.hasRegExp) {
            const regExpStr = this.getRegExpStr();
            this._regExpGlobal = regExpStr ? new RegExp(regExpStr, 'gi') : null;
            this.hasRegExp = true;
        }
        return this._regExpGlobal;
    }
    getToken(value) {
        return this.map.get(value.toLowerCase());
    }
    findClosingTokenText(openingBracketIds) {
        for (const [closingText, info] of this.map) {
            if (info.kind === 2 /* TokenKind.ClosingBracket */ && info.bracketIds.intersects(openingBracketIds)) {
                return closingText;
            }
        }
        return undefined;
    }
    get isEmpty() {
        return this.map.size === 0;
    }
}
function brackets_prepareBracketForRegExp(str) {
    let escaped = escapeRegExpCharacters(str);
    // These bracket pair delimiters start or end with letters
    // see https://github.com/microsoft/vscode/issues/132162 https://github.com/microsoft/vscode/issues/150440
    if (/^[\w ]+/.test(str)) {
        escaped = `\\b${escaped}`;
    }
    if (/[\w ]+$/.test(str)) {
        escaped = `${escaped}\\b`;
    }
    return escaped;
}
class LanguageAgnosticBracketTokens {
    constructor(denseKeyProvider, getLanguageConfiguration) {
        this.denseKeyProvider = denseKeyProvider;
        this.getLanguageConfiguration = getLanguageConfiguration;
        this.languageIdToBracketTokens = new Map();
    }
    didLanguageChange(languageId) {
        // Report a change whenever the language configuration updates.
        return this.languageIdToBracketTokens.has(languageId);
    }
    getSingleLanguageBracketTokens(languageId) {
        let singleLanguageBracketTokens = this.languageIdToBracketTokens.get(languageId);
        if (!singleLanguageBracketTokens) {
            singleLanguageBracketTokens = BracketTokens.createFromLanguage(this.getLanguageConfiguration(languageId), this.denseKeyProvider);
            this.languageIdToBracketTokens.set(languageId, singleLanguageBracketTokens);
        }
        return singleLanguageBracketTokens;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/concat23Trees.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/**
 * Concatenates a list of (2,3) AstNode's into a single (2,3) AstNode.
 * This mutates the items of the input array!
 * If all items have the same height, this method has runtime O(items.length).
 * Otherwise, it has runtime O(items.length * max(log(items.length), items.max(i => i.height))).
*/
function concat23Trees(items) {
    if (items.length === 0) {
        return null;
    }
    if (items.length === 1) {
        return items[0];
    }
    let i = 0;
    /**
     * Reads nodes of same height and concatenates them to a single node.
    */
    function readNode() {
        if (i >= items.length) {
            return null;
        }
        const start = i;
        const height = items[start].listHeight;
        i++;
        while (i < items.length && items[i].listHeight === height) {
            i++;
        }
        if (i - start >= 2) {
            return concat23TreesOfSameHeight(start === 0 && i === items.length ? items : items.slice(start, i), false);
        }
        else {
            return items[start];
        }
    }
    // The items might not have the same height.
    // We merge all items by using a binary concat operator.
    let first = readNode(); // There must be a first item
    let second = readNode();
    if (!second) {
        return first;
    }
    for (let item = readNode(); item; item = readNode()) {
        // Prefer concatenating smaller trees, as the runtime of concat depends on the tree height.
        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 concat23TreesOfSameHeight(items, createImmutableLists = false) {
    if (items.length === 0) {
        return null;
    }
    if (items.length === 1) {
        return items[0];
    }
    let length = items.length;
    // All trees have same height, just create parent nodes.
    while (length > 3) {
        const newLength = length >> 1;
        for (let i = 0; i < newLength; i++) {
            const j = i << 1;
            items[i] = ListAstNode.create23(items[j], items[j + 1], j + 3 === length ? items[j + 2] : null, createImmutableLists);
        }
        length = newLength;
    }
    return ListAstNode.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 ListAstNode.create23(node1, node2, null, false);
    }
    else if (node1.listHeight > node2.listHeight) {
        // node1 is the tree we want to insert into
        return concat23Trees_append(node1, node2);
    }
    else {
        return concat23Trees_prepend(node2, node1);
    }
}
/**
 * Appends the given node to the end of this (2,3) tree.
 * Returns the new root.
*/
function concat23Trees_append(list, nodeToAppend) {
    list = list.toMutable();
    let curNode = list;
    const parents = new Array();
    let nodeToAppendOfCorrectHeight;
    while (true) {
        // assert nodeToInsert.listHeight <= curNode.listHeight
        if (nodeToAppend.listHeight === curNode.listHeight) {
            nodeToAppendOfCorrectHeight = nodeToAppend;
            break;
        }
        // assert 0 <= nodeToInsert.listHeight < curNode.listHeight
        if (curNode.kind !== 4 /* AstNodeKind.List */) {
            throw new Error('unexpected');
        }
        parents.push(curNode);
        // assert 2 <= curNode.childrenLength <= 3
        curNode = curNode.makeLastElementMutable();
    }
    // assert nodeToAppendOfCorrectHeight!.listHeight === curNode.listHeight
    for (let i = parents.length - 1; i >= 0; i--) {
        const parent = parents[i];
        if (nodeToAppendOfCorrectHeight) {
            // Can we take the element?
            if (parent.childrenLength >= 3) {
                // assert parent.childrenLength === 3 && parent.listHeight === nodeToAppendOfCorrectHeight.listHeight + 1
                // we need to split to maintain (2,3)-tree property.
                // Send the third element + the new element to the parent.
                nodeToAppendOfCorrectHeight = ListAstNode.create23(parent.unappendChild(), nodeToAppendOfCorrectHeight, null, false);
            }
            else {
                parent.appendChildOfSameHeight(nodeToAppendOfCorrectHeight);
                nodeToAppendOfCorrectHeight = undefined;
            }
        }
        else {
            parent.handleChildrenChanged();
        }
    }
    if (nodeToAppendOfCorrectHeight) {
        return ListAstNode.create23(list, nodeToAppendOfCorrectHeight, null, false);
    }
    else {
        return list;
    }
}
/**
 * Prepends the given node to the end of this (2,3) tree.
 * Returns the new root.
*/
function concat23Trees_prepend(list, nodeToAppend) {
    list = list.toMutable();
    let curNode = list;
    const parents = new Array();
    // assert nodeToInsert.listHeight <= curNode.listHeight
    while (nodeToAppend.listHeight !== curNode.listHeight) {
        // assert 0 <= nodeToInsert.listHeight < curNode.listHeight
        if (curNode.kind !== 4 /* AstNodeKind.List */) {
            throw new Error('unexpected');
        }
        parents.push(curNode);
        // assert 2 <= curNode.childrenFast.length <= 3
        curNode = curNode.makeFirstElementMutable();
    }
    let nodeToPrependOfCorrectHeight = nodeToAppend;
    // assert nodeToAppendOfCorrectHeight!.listHeight === curNode.listHeight
    for (let i = parents.length - 1; i >= 0; i--) {
        const parent = parents[i];
        if (nodeToPrependOfCorrectHeight) {
            // Can we take the element?
            if (parent.childrenLength >= 3) {
                // assert parent.childrenLength === 3 && parent.listHeight === nodeToAppendOfCorrectHeight.listHeight + 1
                // we need to split to maintain (2,3)-tree property.
                // Send the third element + the new element to the parent.
                nodeToPrependOfCorrectHeight = ListAstNode.create23(nodeToPrependOfCorrectHeight, parent.unprependChild(), null, false);
            }
            else {
                parent.prependChildOfSameHeight(nodeToPrependOfCorrectHeight);
                nodeToPrependOfCorrectHeight = undefined;
            }
        }
        else {
            parent.handleChildrenChanged();
        }
    }
    if (nodeToPrependOfCorrectHeight) {
        return ListAstNode.create23(nodeToPrependOfCorrectHeight, list, null, false);
    }
    else {
        return list;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/nodeReader.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/**
 * Allows to efficiently find a longest child at a given offset in a fixed node.
 * The requested offsets must increase monotonously.
*/
class NodeReader {
    constructor(node) {
        this.lastOffset = lengthZero;
        this.nextNodes = [node];
        this.offsets = [lengthZero];
        this.idxs = [];
    }
    /**
     * 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 (lengthLessThan(offset, this.lastOffset)) {
            throw new Error('Invalid offset');
        }
        this.lastOffset = offset;
        // Find the longest node of all those that are closest to the current offset.
        while (true) {
            const curNode = lastOrUndefined(this.nextNodes);
            if (!curNode) {
                return undefined;
            }
            const curNodeOffset = lastOrUndefined(this.offsets);
            if (lengthLessThan(offset, curNodeOffset)) {
                // The next best node is not here yet.
                // The reader must advance before a cached node is hit.
                return undefined;
            }
            if (lengthLessThan(curNodeOffset, offset)) {
                // The reader is ahead of the current node.
                if (lengthAdd(curNodeOffset, curNode.length) <= offset) {
                    // The reader is after the end of the current node.
                    this.nextNodeAfterCurrent();
                }
                else {
                    // The reader is somewhere in the current node.
                    const nextChildIdx = getNextChildIdx(curNode);
                    if (nextChildIdx !== -1) {
                        // Go to the first child and repeat.
                        this.nextNodes.push(curNode.getChild(nextChildIdx));
                        this.offsets.push(curNodeOffset);
                        this.idxs.push(nextChildIdx);
                    }
                    else {
                        // We don't have children
                        this.nextNodeAfterCurrent();
                    }
                }
            }
            else {
                // readerOffsetBeforeChange === curNodeOffset
                if (predicate(curNode)) {
                    this.nextNodeAfterCurrent();
                    return curNode;
                }
                else {
                    const nextChildIdx = getNextChildIdx(curNode);
                    // look for shorter node
                    if (nextChildIdx === -1) {
                        // There is no shorter node.
                        this.nextNodeAfterCurrent();
                        return undefined;
                    }
                    else {
                        // Descend into first child & repeat.
                        this.nextNodes.push(curNode.getChild(nextChildIdx));
                        this.offsets.push(curNodeOffset);
                        this.idxs.push(nextChildIdx);
                    }
                }
            }
        }
    }
    // Navigates to the longest node that continues after the current node.
    nextNodeAfterCurrent() {
        while (true) {
            const currentOffset = lastOrUndefined(this.offsets);
            const currentNode = lastOrUndefined(this.nextNodes);
            this.nextNodes.pop();
            this.offsets.pop();
            if (this.idxs.length === 0) {
                // We just popped the root node, there is no next node.
                break;
            }
            // Parent is not undefined, because idxs is not empty
            const parent = lastOrUndefined(this.nextNodes);
            const nextChildIdx = getNextChildIdx(parent, this.idxs[this.idxs.length - 1]);
            if (nextChildIdx !== -1) {
                this.nextNodes.push(parent.getChild(nextChildIdx));
                this.offsets.push(lengthAdd(currentOffset, currentNode.length));
                this.idxs[this.idxs.length - 1] = nextChildIdx;
                break;
            }
            else {
                this.idxs.pop();
            }
            // We fully consumed the parent.
            // Current node is now parent, so call nextNodeAfterCurrent again
        }
    }
}
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] : undefined;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/parser.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






/**
 * Non incrementally built ASTs are immutable.
*/
function parseDocument(tokenizer, edits, oldNode, createImmutableLists) {
    const parser = new Parser(tokenizer, edits, oldNode, createImmutableLists);
    return parser.parseDocument();
}
/**
 * Non incrementally built ASTs are immutable.
*/
class Parser {
    constructor(tokenizer, edits, oldNode, createImmutableLists) {
        this.tokenizer = tokenizer;
        this.createImmutableLists = createImmutableLists;
        this._itemsConstructed = 0;
        this._itemsFromCache = 0;
        if (oldNode && createImmutableLists) {
            throw new Error('Not supported');
        }
        this.oldNodeReader = oldNode ? new NodeReader(oldNode) : undefined;
        this.positionMapper = new BeforeEditPositionMapper(edits, tokenizer.length);
    }
    parseDocument() {
        this._itemsConstructed = 0;
        this._itemsFromCache = 0;
        let result = this.parseList(SmallImmutableSet.getEmpty());
        if (!result) {
            result = ListAstNode.getEmpty();
        }
        return result;
    }
    parseList(openedBracketIds) {
        const items = new Array();
        while (true) {
            const token = this.tokenizer.peek();
            if (!token ||
                (token.kind === 2 /* TokenKind.ClosingBracket */ &&
                    token.bracketIds.intersects(openedBracketIds))) {
                break;
            }
            const child = this.parseChild(openedBracketIds);
            if (child.kind === 4 /* AstNodeKind.List */ && child.childrenLength === 0) {
                continue;
            }
            items.push(child);
        }
        // When there is no oldNodeReader, all items are created from scratch and must have the same height.
        const result = this.oldNodeReader ? concat23Trees(items) : concat23TreesOfSameHeight(items, this.createImmutableLists);
        return result;
    }
    parseChild(openedBracketIds) {
        if (this.oldNodeReader) {
            const maxCacheableLength = this.positionMapper.getDistanceToNextChange(this.tokenizer.offset);
            if (!lengthIsZero(maxCacheableLength)) {
                const cachedNode = this.oldNodeReader.readLongestNodeAt(this.positionMapper.getOffsetBeforeChange(this.tokenizer.offset), curNode => {
                    if (!lengthLessThan(curNode.length, maxCacheableLength)) {
                        // Either the node contains edited text or touches edited text.
                        // In the latter case, brackets might have been extended (`end` -> `ending`), so even touching nodes cannot be reused.
                        return false;
                    }
                    const canBeReused = curNode.canBeReused(openedBracketIds);
                    return canBeReused;
                });
                if (cachedNode) {
                    this._itemsFromCache++;
                    this.tokenizer.skip(cachedNode.length);
                    return cachedNode;
                }
            }
        }
        this._itemsConstructed++;
        const token = this.tokenizer.read();
        switch (token.kind) {
            case 2 /* TokenKind.ClosingBracket */:
                return new InvalidBracketAstNode(token.bracketIds, token.length);
            case 0 /* TokenKind.Text */:
                return token.astNode;
            case 1 /* TokenKind.OpeningBracket */: {
                const set = openedBracketIds.merge(token.bracketIds);
                const child = this.parseList(set);
                const nextToken = this.tokenizer.peek();
                if (nextToken &&
                    nextToken.kind === 2 /* TokenKind.ClosingBracket */ &&
                    (nextToken.bracketId === token.bracketId || nextToken.bracketIds.intersects(token.bracketIds))) {
                    this.tokenizer.read();
                    return PairAstNode.create(token.astNode, child, nextToken.astNode);
                }
                else {
                    return PairAstNode.create(token.astNode, child, null);
                }
            }
            default:
                throw new Error('unexpected');
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsTree/bracketPairsTree.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/










class BracketPairsTree extends Disposable {
    constructor(textModel, getLanguageConfiguration) {
        super();
        this.textModel = textModel;
        this.getLanguageConfiguration = getLanguageConfiguration;
        this.didChangeEmitter = new Emitter();
        this.denseKeyProvider = new DenseKeyProvider();
        this.brackets = new LanguageAgnosticBracketTokens(this.denseKeyProvider, this.getLanguageConfiguration);
        this.onDidChange = this.didChangeEmitter.event;
        if (textModel.tokenization.backgroundTokenizationState === 0 /* BackgroundTokenizationState.Uninitialized */) {
            // There are no token information yet
            const brackets = this.brackets.getSingleLanguageBracketTokens(this.textModel.getLanguageId());
            const tokenizer = new FastTokenizer(this.textModel.getValue(), brackets);
            this.initialAstWithoutTokens = parseDocument(tokenizer, [], undefined, true);
            this.astWithTokens = this.initialAstWithoutTokens;
        }
        else if (textModel.tokenization.backgroundTokenizationState === 2 /* BackgroundTokenizationState.Completed */) {
            // Skip the initial ast, as there is no flickering.
            // Directly create the tree with token information.
            this.initialAstWithoutTokens = undefined;
            this.astWithTokens = this.parseDocumentFromTextBuffer([], undefined, false);
        }
        else if (textModel.tokenization.backgroundTokenizationState === 1 /* BackgroundTokenizationState.InProgress */) {
            this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer([], undefined, true);
            this.astWithTokens = this.initialAstWithoutTokens;
        }
    }
    didLanguageChange(languageId) {
        return this.brackets.didLanguageChange(languageId);
    }
    //#region TextModel events
    handleDidChangeBackgroundTokenizationState() {
        if (this.textModel.tokenization.backgroundTokenizationState === 2 /* BackgroundTokenizationState.Completed */) {
            const wasUndefined = this.initialAstWithoutTokens === undefined;
            // Clear the initial tree as we can use the tree with token information now.
            this.initialAstWithoutTokens = undefined;
            if (!wasUndefined) {
                this.didChangeEmitter.fire();
            }
        }
    }
    handleDidChangeTokens({ ranges }) {
        const edits = ranges.map(r => new TextEditInfo(toLength(r.fromLineNumber - 1, 0), toLength(r.toLineNumber, 0), toLength(r.toLineNumber - r.fromLineNumber + 1, 0)));
        this.astWithTokens = this.parseDocumentFromTextBuffer(edits, this.astWithTokens, false);
        if (!this.initialAstWithoutTokens) {
            this.didChangeEmitter.fire();
        }
    }
    handleContentChanged(change) {
        const edits = change.changes.map(c => {
            const range = Range.lift(c.range);
            return new TextEditInfo(positionToLength(range.getStartPosition()), positionToLength(range.getEndPosition()), lengthOfString(c.text));
        }).reverse();
        this.astWithTokens = this.parseDocumentFromTextBuffer(edits, this.astWithTokens, false);
        if (this.initialAstWithoutTokens) {
            this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer(edits, this.initialAstWithoutTokens, false);
        }
    }
    //#endregion
    /**
     * @pure (only if isPure = true)
    */
    parseDocumentFromTextBuffer(edits, previousAst, immutable) {
        // Is much faster if `isPure = false`.
        const isPure = false;
        const previousAstClone = isPure ? previousAst === null || previousAst === void 0 ? void 0 : previousAst.deepClone() : previousAst;
        const tokenizer = new TextBufferTokenizer(this.textModel, this.brackets);
        const result = parseDocument(tokenizer, edits, previousAstClone, immutable);
        return result;
    }
    getBracketsInRange(range) {
        const startOffset = toLength(range.startLineNumber - 1, range.startColumn - 1);
        const endOffset = toLength(range.endLineNumber - 1, range.endColumn - 1);
        const result = new Array();
        const node = this.initialAstWithoutTokens || this.astWithTokens;
        collectBrackets(node, lengthZero, node.length, startOffset, endOffset, result, 0, new Map());
        return result;
    }
    getBracketPairsInRange(range, includeMinIndentation) {
        const result = new Array();
        const startLength = positionToLength(range.getStartPosition());
        const endLength = positionToLength(range.getEndPosition());
        const node = this.initialAstWithoutTokens || this.astWithTokens;
        const context = new CollectBracketPairsContext(result, includeMinIndentation, this.textModel);
        collectBracketPairs(node, lengthZero, node.length, startLength, endLength, context, 0, new Map());
        return result;
    }
    getFirstBracketAfter(position) {
        const node = this.initialAstWithoutTokens || this.astWithTokens;
        return getFirstBracketAfter(node, lengthZero, node.length, positionToLength(position));
    }
    getFirstBracketBefore(position) {
        const node = this.initialAstWithoutTokens || this.astWithTokens;
        return getFirstBracketBefore(node, lengthZero, node.length, positionToLength(position));
    }
}
function getFirstBracketBefore(node, nodeOffsetStart, nodeOffsetEnd, position) {
    if (node.kind === 4 /* AstNodeKind.List */ || node.kind === 2 /* AstNodeKind.Pair */) {
        const lengths = [];
        for (const child of node.children) {
            nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
            lengths.push({ nodeOffsetStart, nodeOffsetEnd });
            nodeOffsetStart = nodeOffsetEnd;
        }
        for (let i = lengths.length - 1; i >= 0; i--) {
            const { nodeOffsetStart, nodeOffsetEnd } = lengths[i];
            if (lengthLessThan(nodeOffsetStart, position)) {
                const result = getFirstBracketBefore(node.children[i], nodeOffsetStart, nodeOffsetEnd, position);
                if (result) {
                    return result;
                }
            }
        }
        return null;
    }
    else if (node.kind === 3 /* AstNodeKind.UnexpectedClosingBracket */) {
        return null;
    }
    else if (node.kind === 1 /* AstNodeKind.Bracket */) {
        const range = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
        return {
            bracketInfo: node.bracketInfo,
            range
        };
    }
    return null;
}
function getFirstBracketAfter(node, nodeOffsetStart, nodeOffsetEnd, position) {
    if (node.kind === 4 /* AstNodeKind.List */ || node.kind === 2 /* AstNodeKind.Pair */) {
        for (const child of node.children) {
            nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
            if (lengthLessThan(position, nodeOffsetEnd)) {
                const result = getFirstBracketAfter(child, nodeOffsetStart, nodeOffsetEnd, position);
                if (result) {
                    return result;
                }
            }
            nodeOffsetStart = nodeOffsetEnd;
        }
        return null;
    }
    else if (node.kind === 3 /* AstNodeKind.UnexpectedClosingBracket */) {
        return null;
    }
    else if (node.kind === 1 /* AstNodeKind.Bracket */) {
        const range = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
        return {
            bracketInfo: node.bracketInfo,
            range
        };
    }
    return null;
}
function collectBrackets(node, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, result, level, levelPerBracketType) {
    if (level > 200) {
        return;
    }
    if (node.kind === 4 /* AstNodeKind.List */) {
        for (const child of node.children) {
            nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
            if (lengthLessThanEqual(nodeOffsetStart, endOffset) &&
                lengthGreaterThanEqual(nodeOffsetEnd, startOffset)) {
                collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, result, level, levelPerBracketType);
            }
            nodeOffsetStart = nodeOffsetEnd;
        }
    }
    else if (node.kind === 2 /* AstNodeKind.Pair */) {
        let levelPerBracket = 0;
        if (levelPerBracketType) {
            let existing = levelPerBracketType.get(node.openingBracket.text);
            if (existing === undefined) {
                existing = 0;
            }
            levelPerBracket = existing;
            existing++;
            levelPerBracketType.set(node.openingBracket.text, existing);
        }
        // Don't use node.children here to improve performance
        {
            const child = node.openingBracket;
            nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
            if (lengthLessThanEqual(nodeOffsetStart, endOffset) &&
                lengthGreaterThanEqual(nodeOffsetEnd, startOffset)) {
                const range = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
                result.push(new BracketInfo(range, level, levelPerBracket, !node.closingBracket));
            }
            nodeOffsetStart = nodeOffsetEnd;
        }
        if (node.child) {
            const child = node.child;
            nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
            if (lengthLessThanEqual(nodeOffsetStart, endOffset) &&
                lengthGreaterThanEqual(nodeOffsetEnd, startOffset)) {
                collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, result, level + 1, levelPerBracketType);
            }
            nodeOffsetStart = nodeOffsetEnd;
        }
        if (node.closingBracket) {
            const child = node.closingBracket;
            nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
            if (lengthLessThanEqual(nodeOffsetStart, endOffset) &&
                lengthGreaterThanEqual(nodeOffsetEnd, startOffset)) {
                const range = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
                result.push(new BracketInfo(range, level, levelPerBracket, false));
            }
            nodeOffsetStart = nodeOffsetEnd;
        }
        levelPerBracketType === null || levelPerBracketType === void 0 ? void 0 : levelPerBracketType.set(node.openingBracket.text, levelPerBracket);
    }
    else if (node.kind === 3 /* AstNodeKind.UnexpectedClosingBracket */) {
        const range = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
        result.push(new BracketInfo(range, level - 1, 0, true));
    }
    else if (node.kind === 1 /* AstNodeKind.Bracket */) {
        const range = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
        result.push(new BracketInfo(range, level - 1, 0, false));
    }
}
class CollectBracketPairsContext {
    constructor(result, includeMinIndentation, textModel) {
        this.result = result;
        this.includeMinIndentation = includeMinIndentation;
        this.textModel = textModel;
    }
}
function collectBracketPairs(node, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, context, level, levelPerBracketType) {
    var _a;
    if (level > 200) {
        return;
    }
    if (node.kind === 2 /* AstNodeKind.Pair */) {
        let levelPerBracket = 0;
        if (levelPerBracketType) {
            let existing = levelPerBracketType.get(node.openingBracket.text);
            if (existing === undefined) {
                existing = 0;
            }
            levelPerBracket = existing;
            existing++;
            levelPerBracketType.set(node.openingBracket.text, existing);
        }
        const openingBracketEnd = lengthAdd(nodeOffsetStart, node.openingBracket.length);
        let minIndentation = -1;
        if (context.includeMinIndentation) {
            minIndentation = node.computeMinIndentation(nodeOffsetStart, context.textModel);
        }
        context.result.push(new BracketPairWithMinIndentationInfo(lengthsToRange(nodeOffsetStart, nodeOffsetEnd), lengthsToRange(nodeOffsetStart, openingBracketEnd), node.closingBracket
            ? lengthsToRange(lengthAdd(openingBracketEnd, ((_a = node.child) === null || _a === void 0 ? void 0 : _a.length) || lengthZero), nodeOffsetEnd)
            : undefined, level, levelPerBracket, node, minIndentation));
        nodeOffsetStart = openingBracketEnd;
        if (node.child) {
            const child = node.child;
            nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
            if (lengthLessThanEqual(nodeOffsetStart, endOffset) &&
                lengthGreaterThanEqual(nodeOffsetEnd, startOffset)) {
                collectBracketPairs(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, context, level + 1, levelPerBracketType);
            }
        }
        levelPerBracketType === null || levelPerBracketType === void 0 ? void 0 : levelPerBracketType.set(node.openingBracket.text, levelPerBracket);
    }
    else {
        let curOffset = nodeOffsetStart;
        for (const child of node.children) {
            const childOffset = curOffset;
            curOffset = lengthAdd(curOffset, child.length);
            if (lengthLessThanEqual(childOffset, endOffset) &&
                lengthLessThanEqual(startOffset, curOffset)) {
                collectBracketPairs(child, childOffset, curOffset, startOffset, endOffset, context, level, levelPerBracketType);
            }
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/bracketPairsImpl.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







class BracketPairsTextModelPart extends Disposable {
    constructor(textModel, languageConfigurationService) {
        super();
        this.textModel = textModel;
        this.languageConfigurationService = languageConfigurationService;
        this.bracketPairsTree = this._register(new MutableDisposable());
        this.onDidChangeEmitter = new Emitter();
        this.onDidChange = this.onDidChangeEmitter.event;
        this.bracketsRequested = false;
        this._register(this.languageConfigurationService.onDidChange(e => {
            var _a;
            if (!e.languageId || ((_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.didLanguageChange(e.languageId))) {
                this.bracketPairsTree.clear();
                this.updateBracketPairsTree();
            }
        }));
    }
    get canBuildAST() {
        const maxSupportedDocumentLength = /* max lines */ 50000 * /* average column count */ 100;
        return this.textModel.getValueLength() <= maxSupportedDocumentLength;
    }
    //#region TextModel events
    handleDidChangeOptions(e) {
        this.bracketPairsTree.clear();
        this.updateBracketPairsTree();
    }
    handleDidChangeLanguage(e) {
        this.bracketPairsTree.clear();
        this.updateBracketPairsTree();
    }
    handleDidChangeContent(change) {
        var _a;
        (_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.handleContentChanged(change);
    }
    handleDidChangeBackgroundTokenizationState() {
        var _a;
        (_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.handleDidChangeBackgroundTokenizationState();
    }
    handleDidChangeTokens(e) {
        var _a;
        (_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.handleDidChangeTokens(e);
    }
    //#endregion
    updateBracketPairsTree() {
        if (this.bracketsRequested && this.canBuildAST) {
            if (!this.bracketPairsTree.value) {
                const store = new DisposableStore();
                this.bracketPairsTree.value = createDisposableRef(store.add(new BracketPairsTree(this.textModel, (languageId) => {
                    return this.languageConfigurationService.getLanguageConfiguration(languageId);
                })), store);
                store.add(this.bracketPairsTree.value.object.onDidChange(e => this.onDidChangeEmitter.fire(e)));
                this.onDidChangeEmitter.fire();
            }
        }
        else {
            if (this.bracketPairsTree.value) {
                this.bracketPairsTree.clear();
                // Important: Don't call fire if there was no change!
                this.onDidChangeEmitter.fire();
            }
        }
    }
    /**
     * Returns all bracket pairs that intersect the given range.
     * The result is sorted by the start position.
    */
    getBracketPairsInRange(range) {
        var _a;
        this.bracketsRequested = true;
        this.updateBracketPairsTree();
        return ((_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.getBracketPairsInRange(range, false)) || [];
    }
    getBracketPairsInRangeWithMinIndentation(range) {
        var _a;
        this.bracketsRequested = true;
        this.updateBracketPairsTree();
        return ((_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.getBracketPairsInRange(range, true)) || [];
    }
    getBracketsInRange(range) {
        var _a;
        this.bracketsRequested = true;
        this.updateBracketPairsTree();
        return ((_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.getBracketsInRange(range)) || [];
    }
    findMatchingBracketUp(_bracket, _position, maxDuration) {
        const position = this.textModel.validatePosition(_position);
        const languageId = this.textModel.getLanguageIdAtPosition(position.lineNumber, position.column);
        if (this.canBuildAST) {
            const closingBracketInfo = this.languageConfigurationService
                .getLanguageConfiguration(languageId)
                .bracketsNew.getClosingBracketInfo(_bracket);
            if (!closingBracketInfo) {
                return null;
            }
            const bracketPair = findLast(this.getBracketPairsInRange(Range.fromPositions(_position, _position)) || [], (b) => closingBracketInfo.closes(b.openingBracketInfo));
            if (bracketPair) {
                return bracketPair.openingBracketRange;
            }
            return null;
        }
        else {
            // Fallback to old bracket matching code:
            const bracket = _bracket.toLowerCase();
            const bracketsSupport = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
            if (!bracketsSupport) {
                return null;
            }
            const data = bracketsSupport.textIsBracket[bracket];
            if (!data) {
                return null;
            }
            return stripBracketSearchCanceled(this._findMatchingBracketUp(data, position, createTimeBasedContinueBracketSearchPredicate(maxDuration)));
        }
    }
    matchBracket(position, maxDuration) {
        if (this.canBuildAST) {
            const bracketPair = findLastMaxBy(this.getBracketPairsInRange(Range.fromPositions(position, position)).filter((item) => item.closingBracketRange !== undefined &&
                (item.openingBracketRange.containsPosition(position) ||
                    item.closingBracketRange.containsPosition(position))), compareBy((item) => item.openingBracketRange.containsPosition(position)
                ? item.openingBracketRange
                : item.closingBracketRange, Range.compareRangesUsingStarts));
            if (bracketPair) {
                return [bracketPair.openingBracketRange, bracketPair.closingBracketRange];
            }
            return null;
        }
        else {
            // Fallback to old bracket matching code:
            const continueSearchPredicate = createTimeBasedContinueBracketSearchPredicate(maxDuration);
            return this._matchBracket(this.textModel.validatePosition(position), continueSearchPredicate);
        }
    }
    _establishBracketSearchOffsets(position, lineTokens, modeBrackets, tokenIndex) {
        const tokenCount = lineTokens.getCount();
        const currentLanguageId = lineTokens.getLanguageId(tokenIndex);
        // limit search to not go before `maxBracketLength`
        let searchStartOffset = Math.max(0, position.column - 1 - modeBrackets.maxBracketLength);
        for (let i = tokenIndex - 1; i >= 0; i--) {
            const tokenEndOffset = lineTokens.getEndOffset(i);
            if (tokenEndOffset <= searchStartOffset) {
                break;
            }
            if (ignoreBracketsInToken(lineTokens.getStandardTokenType(i)) || lineTokens.getLanguageId(i) !== currentLanguageId) {
                searchStartOffset = tokenEndOffset;
                break;
            }
        }
        // limit search to not go after `maxBracketLength`
        let searchEndOffset = Math.min(lineTokens.getLineContent().length, position.column - 1 + modeBrackets.maxBracketLength);
        for (let i = tokenIndex + 1; i < tokenCount; i++) {
            const tokenStartOffset = lineTokens.getStartOffset(i);
            if (tokenStartOffset >= searchEndOffset) {
                break;
            }
            if (ignoreBracketsInToken(lineTokens.getStandardTokenType(i)) || lineTokens.getLanguageId(i) !== currentLanguageId) {
                searchEndOffset = tokenStartOffset;
                break;
            }
        }
        return { searchStartOffset, searchEndOffset };
    }
    _matchBracket(position, continueSearchPredicate) {
        const lineNumber = position.lineNumber;
        const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
        const lineText = this.textModel.getLineContent(lineNumber);
        const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        if (tokenIndex < 0) {
            return null;
        }
        const currentModeBrackets = this.languageConfigurationService.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex)).brackets;
        // check that the token is not to be ignored
        if (currentModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex))) {
            let { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, currentModeBrackets, tokenIndex);
            // it might be the case that [currentTokenStart -> currentTokenEnd] contains multiple brackets
            // `bestResult` will contain the most right-side result
            let bestResult = null;
            while (true) {
                const foundBracket = BracketsUtils.findNextBracketInRange(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                if (!foundBracket) {
                    // there are no more brackets in this text
                    break;
                }
                // check that we didn't hit a bracket too far away from position
                if (foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
                    const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
                    const r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText], continueSearchPredicate);
                    if (r) {
                        if (r instanceof BracketSearchCanceled) {
                            return null;
                        }
                        bestResult = r;
                    }
                }
                searchStartOffset = foundBracket.endColumn - 1;
            }
            if (bestResult) {
                return bestResult;
            }
        }
        // If position is in between two tokens, try also looking in the previous token
        if (tokenIndex > 0 && lineTokens.getStartOffset(tokenIndex) === position.column - 1) {
            const prevTokenIndex = tokenIndex - 1;
            const prevModeBrackets = this.languageConfigurationService.getLanguageConfiguration(lineTokens.getLanguageId(prevTokenIndex)).brackets;
            // check that previous token is not to be ignored
            if (prevModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(prevTokenIndex))) {
                const { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, prevModeBrackets, prevTokenIndex);
                const foundBracket = BracketsUtils.findPrevBracketInRange(prevModeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                // check that we didn't hit a bracket too far away from position
                if (foundBracket && foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
                    const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
                    const r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText], continueSearchPredicate);
                    if (r) {
                        if (r instanceof BracketSearchCanceled) {
                            return null;
                        }
                        return r;
                    }
                }
            }
        }
        return null;
    }
    _matchFoundBracket(foundBracket, data, isOpen, continueSearchPredicate) {
        if (!data) {
            return null;
        }
        const matched = (isOpen
            ? this._findMatchingBracketDown(data, foundBracket.getEndPosition(), continueSearchPredicate)
            : this._findMatchingBracketUp(data, foundBracket.getStartPosition(), continueSearchPredicate));
        if (!matched) {
            return null;
        }
        if (matched instanceof BracketSearchCanceled) {
            return matched;
        }
        return [foundBracket, matched];
    }
    _findMatchingBracketUp(bracket, position, continueSearchPredicate) {
        // console.log('_findMatchingBracketUp: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));
        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 r = BracketsUtils.findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                if (!r) {
                    break;
                }
                const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
                if (bracket.isOpen(hitText)) {
                    count++;
                }
                else if (bracket.isClose(hitText)) {
                    count--;
                }
                if (count === 0) {
                    return r;
                }
                searchEndOffset = r.startColumn - 1;
            }
            return null;
        };
        for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
            const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
            const tokenCount = lineTokens.getCount();
            const lineText = this.textModel.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 && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
                if (searchInToken) {
                    // this token should be searched
                    if (prevSearchInToken) {
                        // the previous token should be searched, simply extend searchStartOffset
                        searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                    }
                    else {
                        // the previous token should not be searched
                        searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                        searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                    }
                }
                else {
                    // this token should not be searched
                    if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
                        const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
                        if (r) {
                            return r;
                        }
                    }
                }
                prevSearchInToken = searchInToken;
            }
            if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
                const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
                if (r) {
                    return r;
                }
            }
        }
        return null;
    }
    _findMatchingBracketDown(bracket, position, continueSearchPredicate) {
        // console.log('_findMatchingBracketDown: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));
        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 r = BracketsUtils.findNextBracketInRange(bracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                if (!r) {
                    break;
                }
                const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
                if (bracket.isOpen(hitText)) {
                    count++;
                }
                else if (bracket.isClose(hitText)) {
                    count--;
                }
                if (count === 0) {
                    return r;
                }
                searchStartOffset = r.endColumn - 1;
            }
            return null;
        };
        const lineCount = this.textModel.getLineCount();
        for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
            const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
            const tokenCount = lineTokens.getCount();
            const lineText = this.textModel.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 && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
                if (searchInToken) {
                    // this token should be searched
                    if (prevSearchInToken) {
                        // the previous token should be searched, simply extend searchEndOffset
                        searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                    }
                    else {
                        // the previous token should not be searched
                        searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                        searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                    }
                }
                else {
                    // this token should not be searched
                    if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
                        const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
                        if (r) {
                            return r;
                        }
                    }
                }
                prevSearchInToken = searchInToken;
            }
            if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
                const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
                if (r) {
                    return r;
                }
            }
        }
        return null;
    }
    findPrevBracket(_position) {
        var _a;
        const position = this.textModel.validatePosition(_position);
        if (this.canBuildAST) {
            this.bracketsRequested = true;
            this.updateBracketPairsTree();
            return ((_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.getFirstBracketBefore(position)) || null;
        }
        let languageId = null;
        let modeBrackets = null;
        let bracketConfig = null;
        for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
            const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
            const tokenCount = lineTokens.getCount();
            const lineText = this.textModel.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.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                    bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
                }
            }
            let prevSearchInToken = true;
            for (; tokenIndex >= 0; tokenIndex--) {
                const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
                if (languageId !== tokenLanguageId) {
                    // language id change!
                    if (modeBrackets && bracketConfig && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                        const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                        if (r) {
                            return this._toFoundBracket(bracketConfig, r);
                        }
                        prevSearchInToken = false;
                    }
                    languageId = tokenLanguageId;
                    modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                    bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
                }
                const searchInToken = (!!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
                if (searchInToken) {
                    // this token should be searched
                    if (prevSearchInToken) {
                        // the previous token should be searched, simply extend searchStartOffset
                        searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                    }
                    else {
                        // the previous token should not be searched
                        searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                        searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                    }
                }
                else {
                    // this token should not be searched
                    if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                        const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                        if (r) {
                            return this._toFoundBracket(bracketConfig, r);
                        }
                    }
                }
                prevSearchInToken = searchInToken;
            }
            if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                if (r) {
                    return this._toFoundBracket(bracketConfig, r);
                }
            }
        }
        return null;
    }
    findNextBracket(_position) {
        var _a;
        const position = this.textModel.validatePosition(_position);
        if (this.canBuildAST) {
            this.bracketsRequested = true;
            this.updateBracketPairsTree();
            return ((_a = this.bracketPairsTree.value) === null || _a === void 0 ? void 0 : _a.object.getFirstBracketAfter(position)) || null;
        }
        const lineCount = this.textModel.getLineCount();
        let languageId = null;
        let modeBrackets = null;
        let bracketConfig = null;
        for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
            const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
            const tokenCount = lineTokens.getCount();
            const lineText = this.textModel.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.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                    bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
                }
            }
            let prevSearchInToken = true;
            for (; tokenIndex < tokenCount; tokenIndex++) {
                const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
                if (languageId !== tokenLanguageId) {
                    // language id change!
                    if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                        const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                        if (r) {
                            return this._toFoundBracket(bracketConfig, r);
                        }
                        prevSearchInToken = false;
                    }
                    languageId = tokenLanguageId;
                    modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                    bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
                }
                const searchInToken = (!!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
                if (searchInToken) {
                    // this token should be searched
                    if (prevSearchInToken) {
                        // the previous token should be searched, simply extend searchEndOffset
                        searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                    }
                    else {
                        // the previous token should not be searched
                        searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                        searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                    }
                }
                else {
                    // this token should not be searched
                    if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                        const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                        if (r) {
                            return this._toFoundBracket(bracketConfig, r);
                        }
                    }
                }
                prevSearchInToken = searchInToken;
            }
            if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                if (r) {
                    return this._toFoundBracket(bracketConfig, r);
                }
            }
        }
        return null;
    }
    findEnclosingBrackets(_position, maxDuration) {
        const position = this.textModel.validatePosition(_position);
        if (this.canBuildAST) {
            const range = Range.fromPositions(position);
            const bracketPair = findLast(this.getBracketPairsInRange(Range.fromPositions(position, position)), (item) => item.closingBracketRange !== undefined && item.range.strictContainsRange(range));
            if (bracketPair) {
                return [bracketPair.openingBracketRange, bracketPair.closingBracketRange];
            }
            return null;
        }
        const continueSearchPredicate = createTimeBasedContinueBracketSearchPredicate(maxDuration);
        const lineCount = this.textModel.getLineCount();
        const savedCounts = new Map();
        let counts = [];
        const resetCounts = (languageId, modeBrackets) => {
            if (!savedCounts.has(languageId)) {
                const tmp = [];
                for (let i = 0, len = modeBrackets ? modeBrackets.brackets.length : 0; i < len; i++) {
                    tmp[i] = 0;
                }
                savedCounts.set(languageId, tmp);
            }
            counts = savedCounts.get(languageId);
        };
        let totalCallCount = 0;
        const searchInRange = (modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset) => {
            while (true) {
                if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) {
                    return BracketSearchCanceled.INSTANCE;
                }
                const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
                if (!r) {
                    break;
                }
                const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
                const bracket = modeBrackets.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._matchFoundBracket(r, bracket, false, continueSearchPredicate);
                    }
                }
                searchStartOffset = r.endColumn - 1;
            }
            return null;
        };
        let languageId = null;
        let modeBrackets = null;
        for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
            const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
            const tokenCount = lineTokens.getCount();
            const lineText = this.textModel.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.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                    resetCounts(languageId, modeBrackets);
                }
            }
            let prevSearchInToken = true;
            for (; tokenIndex < tokenCount; tokenIndex++) {
                const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
                if (languageId !== tokenLanguageId) {
                    // language id change!
                    if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                        const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
                        if (r) {
                            return stripBracketSearchCanceled(r);
                        }
                        prevSearchInToken = false;
                    }
                    languageId = tokenLanguageId;
                    modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
                    resetCounts(languageId, modeBrackets);
                }
                const searchInToken = (!!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
                if (searchInToken) {
                    // this token should be searched
                    if (prevSearchInToken) {
                        // the previous token should be searched, simply extend searchEndOffset
                        searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                    }
                    else {
                        // the previous token should not be searched
                        searchStartOffset = lineTokens.getStartOffset(tokenIndex);
                        searchEndOffset = lineTokens.getEndOffset(tokenIndex);
                    }
                }
                else {
                    // this token should not be searched
                    if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                        const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
                        if (r) {
                            return stripBracketSearchCanceled(r);
                        }
                    }
                }
                prevSearchInToken = searchInToken;
            }
            if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
                const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
                if (r) {
                    return stripBracketSearchCanceled(r);
                }
            }
        }
        return null;
    }
    _toFoundBracket(bracketConfig, r) {
        if (!r) {
            return null;
        }
        let text = this.textModel.getValueInRange(r);
        text = text.toLowerCase();
        const bracketInfo = bracketConfig.getBracketInfo(text);
        if (!bracketInfo) {
            return null;
        }
        return {
            range: r,
            bracketInfo
        };
    }
}
function createDisposableRef(object, disposable) {
    return {
        object,
        dispose: () => disposable === null || disposable === void 0 ? void 0 : disposable.dispose(),
    };
}
function createTimeBasedContinueBracketSearchPredicate(maxDuration) {
    if (typeof maxDuration === 'undefined') {
        return () => true;
    }
    else {
        const startTime = Date.now();
        return () => {
            return (Date.now() - startTime <= maxDuration);
        };
    }
}
class BracketSearchCanceled {
    constructor() {
        this._searchCanceledBrand = undefined;
    }
}
BracketSearchCanceled.INSTANCE = new BracketSearchCanceled();
function stripBracketSearchCanceled(result) {
    if (result instanceof BracketSearchCanceled) {
        return null;
    }
    return result;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/editorColorRegistry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





/**
 * Definition of the editor colors
 */
const editorLineHighlight = registerColor('editor.lineHighlightBackground', { dark: null, light: null, hcDark: null, hcLight: null }, localize('lineHighlight', 'Background color for the highlight of line at the cursor position.'));
const editorLineHighlightBorder = registerColor('editor.lineHighlightBorder', { dark: '#282828', light: '#eeeeee', hcDark: '#f38518', hcLight: contrastBorder }, localize('lineHighlightBorderBox', 'Background color for the border around the line at the cursor position.'));
const editorRangeHighlight = registerColor('editor.rangeHighlightBackground', { dark: '#ffffff0b', light: '#fdff0033', hcDark: null, hcLight: null }, localize('rangeHighlight', 'Background color of highlighted ranges, like by quick open and find features. The color must not be opaque so as not to hide underlying decorations.'), true);
const editorRangeHighlightBorder = registerColor('editor.rangeHighlightBorder', { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('rangeHighlightBorder', 'Background color of the border around highlighted ranges.'), true);
const editorSymbolHighlight = registerColor('editor.symbolHighlightBackground', { dark: editorFindMatchHighlight, light: editorFindMatchHighlight, hcDark: null, hcLight: null }, localize('symbolHighlight', 'Background color of highlighted symbol, like for go to definition or go next/previous symbol. The color must not be opaque so as not to hide underlying decorations.'), true);
const editorSymbolHighlightBorder = registerColor('editor.symbolHighlightBorder', { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('symbolHighlightBorder', 'Background color of the border around highlighted symbols.'), true);
const editorCursorForeground = registerColor('editorCursor.foreground', { dark: '#AEAFAD', light: Color.black, hcDark: Color.white, hcLight: '#0F4A85' }, localize('caret', 'Color of the editor cursor.'));
const editorCursorBackground = registerColor('editorCursor.background', null, localize('editorCursorBackground', 'The background color of the editor cursor. Allows customizing the color of a character overlapped by a block cursor.'));
const editorWhitespaces = registerColor('editorWhitespace.foreground', { dark: '#e3e4e229', light: '#33333333', hcDark: '#e3e4e229', hcLight: '#CCCCCC' }, localize('editorWhitespaces', 'Color of whitespace characters in the editor.'));
const editorIndentGuides = registerColor('editorIndentGuide.background', { dark: editorWhitespaces, light: editorWhitespaces, hcDark: editorWhitespaces, hcLight: editorWhitespaces }, localize('editorIndentGuides', 'Color of the editor indentation guides.'));
const editorActiveIndentGuides = registerColor('editorIndentGuide.activeBackground', { dark: editorWhitespaces, light: editorWhitespaces, hcDark: editorWhitespaces, hcLight: editorWhitespaces }, localize('editorActiveIndentGuide', 'Color of the active editor indentation guides.'));
const editorLineNumbers = registerColor('editorLineNumber.foreground', { dark: '#858585', light: '#237893', hcDark: Color.white, hcLight: '#292929' }, localize('editorLineNumbers', 'Color of editor line numbers.'));
const deprecatedEditorActiveLineNumber = registerColor('editorActiveLineNumber.foreground', { dark: '#c6c6c6', light: '#0B216F', hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('editorActiveLineNumber', 'Color of editor active line number'), false, localize('deprecatedEditorActiveLineNumber', 'Id is deprecated. Use \'editorLineNumber.activeForeground\' instead.'));
const editorActiveLineNumber = registerColor('editorLineNumber.activeForeground', { dark: deprecatedEditorActiveLineNumber, light: deprecatedEditorActiveLineNumber, hcDark: deprecatedEditorActiveLineNumber, hcLight: deprecatedEditorActiveLineNumber }, localize('editorActiveLineNumber', 'Color of editor active line number'));
const editorRuler = registerColor('editorRuler.foreground', { dark: '#5A5A5A', light: Color.lightgrey, hcDark: Color.white, hcLight: '#292929' }, localize('editorRuler', 'Color of the editor rulers.'));
const editorCodeLensForeground = registerColor('editorCodeLens.foreground', { dark: '#999999', light: '#919191', hcDark: '#999999', hcLight: '#292929' }, localize('editorCodeLensForeground', 'Foreground color of editor CodeLens'));
const editorBracketMatchBackground = registerColor('editorBracketMatch.background', { dark: '#0064001a', light: '#0064001a', hcDark: '#0064001a', hcLight: '#0000' }, localize('editorBracketMatchBackground', 'Background color behind matching brackets'));
const editorBracketMatchBorder = registerColor('editorBracketMatch.border', { dark: '#888', light: '#B9B9B9', hcDark: contrastBorder, hcLight: contrastBorder }, localize('editorBracketMatchBorder', 'Color for matching brackets boxes'));
const editorOverviewRulerBorder = registerColor('editorOverviewRuler.border', { dark: '#7f7f7f4d', light: '#7f7f7f4d', hcDark: '#7f7f7f4d', hcLight: '#666666' }, localize('editorOverviewRulerBorder', 'Color of the overview ruler border.'));
const editorOverviewRulerBackground = registerColor('editorOverviewRuler.background', null, localize('editorOverviewRulerBackground', 'Background color of the editor overview ruler. Only used when the minimap is enabled and placed on the right side of the editor.'));
const editorGutter = registerColor('editorGutter.background', { dark: editorBackground, light: editorBackground, hcDark: editorBackground, hcLight: editorBackground }, localize('editorGutter', 'Background color of the editor gutter. The gutter contains the glyph margins and the line numbers.'));
const editorUnnecessaryCodeBorder = registerColor('editorUnnecessaryCode.border', { dark: null, light: null, hcDark: Color.fromHex('#fff').transparent(0.8), hcLight: contrastBorder }, localize('unnecessaryCodeBorder', 'Border color of unnecessary (unused) source code in the editor.'));
const editorUnnecessaryCodeOpacity = registerColor('editorUnnecessaryCode.opacity', { dark: Color.fromHex('#000a'), light: Color.fromHex('#0007'), hcDark: null, hcLight: null }, localize('unnecessaryCodeOpacity', 'Opacity of unnecessary (unused) source code in the editor. For example, "#000000c0" will render the code with 75% opacity. For high contrast themes, use the  \'editorUnnecessaryCode.border\' theme color to underline unnecessary code instead of fading it out.'));
const ghostTextBorder = registerColor('editorGhostText.border', { dark: null, light: null, hcDark: Color.fromHex('#fff').transparent(0.8), hcLight: Color.fromHex('#292929').transparent(0.8) }, localize('editorGhostTextBorder', 'Border color of ghost text in the editor.'));
const ghostTextForeground = registerColor('editorGhostText.foreground', { dark: Color.fromHex('#ffffff56'), light: Color.fromHex('#0007'), hcDark: null, hcLight: null }, localize('editorGhostTextForeground', 'Foreground color of the ghost text in the editor.'));
const ghostTextBackground = registerColor('editorGhostText.background', { dark: null, light: null, hcDark: null, hcLight: null }, localize('editorGhostTextBackground', 'Background color of the ghost text in the editor.'));
const rulerRangeDefault = new Color(new RGBA(0, 122, 204, 0.6));
const overviewRulerRangeHighlight = registerColor('editorOverviewRuler.rangeHighlightForeground', { dark: rulerRangeDefault, light: rulerRangeDefault, hcDark: rulerRangeDefault, hcLight: rulerRangeDefault }, localize('overviewRulerRangeHighlight', 'Overview ruler marker color for range highlights. The color must not be opaque so as not to hide underlying decorations.'), true);
const overviewRulerError = registerColor('editorOverviewRuler.errorForeground', { dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hcDark: new Color(new RGBA(255, 50, 50, 1)), hcLight: '#B5200D' }, localize('overviewRuleError', 'Overview ruler marker color for errors.'));
const overviewRulerWarning = registerColor('editorOverviewRuler.warningForeground', { dark: editorWarningForeground, light: editorWarningForeground, hcDark: editorWarningBorder, hcLight: editorWarningBorder }, localize('overviewRuleWarning', 'Overview ruler marker color for warnings.'));
const overviewRulerInfo = registerColor('editorOverviewRuler.infoForeground', { dark: editorInfoForeground, light: editorInfoForeground, hcDark: editorInfoBorder, hcLight: editorInfoBorder }, localize('overviewRuleInfo', 'Overview ruler marker color for infos.'));
const editorBracketHighlightingForeground1 = registerColor('editorBracketHighlight.foreground1', { dark: '#FFD700', light: '#0431FAFF', hcDark: '#FFD700', hcLight: '#0431FAFF' }, localize('editorBracketHighlightForeground1', 'Foreground color of brackets (1). Requires enabling bracket pair colorization.'));
const editorBracketHighlightingForeground2 = registerColor('editorBracketHighlight.foreground2', { dark: '#DA70D6', light: '#319331FF', hcDark: '#DA70D6', hcLight: '#319331FF' }, localize('editorBracketHighlightForeground2', 'Foreground color of brackets (2). Requires enabling bracket pair colorization.'));
const editorBracketHighlightingForeground3 = registerColor('editorBracketHighlight.foreground3', { dark: '#179FFF', light: '#7B3814FF', hcDark: '#87CEFA', hcLight: '#7B3814FF' }, localize('editorBracketHighlightForeground3', 'Foreground color of brackets (3). Requires enabling bracket pair colorization.'));
const editorBracketHighlightingForeground4 = registerColor('editorBracketHighlight.foreground4', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketHighlightForeground4', 'Foreground color of brackets (4). Requires enabling bracket pair colorization.'));
const editorBracketHighlightingForeground5 = registerColor('editorBracketHighlight.foreground5', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketHighlightForeground5', 'Foreground color of brackets (5). Requires enabling bracket pair colorization.'));
const editorBracketHighlightingForeground6 = registerColor('editorBracketHighlight.foreground6', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketHighlightForeground6', 'Foreground color of brackets (6). Requires enabling bracket pair colorization.'));
const editorBracketHighlightingUnexpectedBracketForeground = registerColor('editorBracketHighlight.unexpectedBracket.foreground', { dark: new Color(new RGBA(255, 18, 18, 0.8)), light: new Color(new RGBA(255, 18, 18, 0.8)), hcDark: new Color(new RGBA(255, 50, 50, 1)), hcLight: '' }, localize('editorBracketHighlightUnexpectedBracketForeground', 'Foreground color of unexpected brackets.'));
const editorBracketPairGuideBackground1 = registerColor('editorBracketPairGuide.background1', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.background1', 'Background color of inactive bracket pair guides (1). Requires enabling bracket pair guides.'));
const editorBracketPairGuideBackground2 = registerColor('editorBracketPairGuide.background2', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.background2', 'Background color of inactive bracket pair guides (2). Requires enabling bracket pair guides.'));
const editorBracketPairGuideBackground3 = registerColor('editorBracketPairGuide.background3', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.background3', 'Background color of inactive bracket pair guides (3). Requires enabling bracket pair guides.'));
const editorBracketPairGuideBackground4 = registerColor('editorBracketPairGuide.background4', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.background4', 'Background color of inactive bracket pair guides (4). Requires enabling bracket pair guides.'));
const editorBracketPairGuideBackground5 = registerColor('editorBracketPairGuide.background5', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.background5', 'Background color of inactive bracket pair guides (5). Requires enabling bracket pair guides.'));
const editorBracketPairGuideBackground6 = registerColor('editorBracketPairGuide.background6', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.background6', 'Background color of inactive bracket pair guides (6). Requires enabling bracket pair guides.'));
const editorBracketPairGuideActiveBackground1 = registerColor('editorBracketPairGuide.activeBackground1', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.activeBackground1', 'Background color of active bracket pair guides (1). Requires enabling bracket pair guides.'));
const editorBracketPairGuideActiveBackground2 = registerColor('editorBracketPairGuide.activeBackground2', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.activeBackground2', 'Background color of active bracket pair guides (2). Requires enabling bracket pair guides.'));
const editorBracketPairGuideActiveBackground3 = registerColor('editorBracketPairGuide.activeBackground3', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.activeBackground3', 'Background color of active bracket pair guides (3). Requires enabling bracket pair guides.'));
const editorBracketPairGuideActiveBackground4 = registerColor('editorBracketPairGuide.activeBackground4', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.activeBackground4', 'Background color of active bracket pair guides (4). Requires enabling bracket pair guides.'));
const editorBracketPairGuideActiveBackground5 = registerColor('editorBracketPairGuide.activeBackground5', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.activeBackground5', 'Background color of active bracket pair guides (5). Requires enabling bracket pair guides.'));
const editorBracketPairGuideActiveBackground6 = registerColor('editorBracketPairGuide.activeBackground6', { dark: '#00000000', light: '#00000000', hcDark: '#00000000', hcLight: '#00000000' }, localize('editorBracketPairGuide.activeBackground6', 'Background color of active bracket pair guides (6). Requires enabling bracket pair guides.'));
const editorUnicodeHighlightBorder = registerColor('editorUnicodeHighlight.border', { dark: '#BD9B03', light: '#CEA33D', hcDark: '#ff0000', hcLight: '' }, localize('editorUnicodeHighlight.border', 'Border color used to highlight unicode characters.'));
const editorUnicodeHighlightBackground = registerColor('editorUnicodeHighlight.background', { dark: '#bd9b0326', light: '#cea33d14', hcDark: '#00000000', hcLight: '' }, localize('editorUnicodeHighlight.background', 'Background color used to highlight unicode characters.'));
// contains all color rules that used to defined in editor/browser/widget/editor.css
registerThemingParticipant((theme, collector) => {
    const background = theme.getColor(editorBackground);
    if (background) {
        collector.addRule(`.monaco-editor, .monaco-editor-background { background-color: ${background}; }`);
    }
    const lineHighlight = theme.getColor(editorLineHighlight);
    const imeBackground = (lineHighlight && !lineHighlight.isTransparent() ? lineHighlight : background);
    if (imeBackground) {
        collector.addRule(`.monaco-editor .inputarea.ime-input { background-color: ${imeBackground}; }`);
    }
    const foreground = theme.getColor(editorForeground);
    if (foreground) {
        collector.addRule(`.monaco-editor, .monaco-editor .inputarea.ime-input { color: ${foreground}; }`);
    }
    const gutter = theme.getColor(editorGutter);
    if (gutter) {
        collector.addRule(`.monaco-editor .margin { background-color: ${gutter}; }`);
    }
    const rangeHighlight = theme.getColor(editorRangeHighlight);
    if (rangeHighlight) {
        collector.addRule(`.monaco-editor .rangeHighlight { background-color: ${rangeHighlight}; }`);
    }
    const rangeHighlightBorder = theme.getColor(editorRangeHighlightBorder);
    if (rangeHighlightBorder) {
        collector.addRule(`.monaco-editor .rangeHighlight { border: 1px ${isHighContrast(theme.type) ? 'dotted' : 'solid'} ${rangeHighlightBorder}; }`);
    }
    const symbolHighlight = theme.getColor(editorSymbolHighlight);
    if (symbolHighlight) {
        collector.addRule(`.monaco-editor .symbolHighlight { background-color: ${symbolHighlight}; }`);
    }
    const symbolHighlightBorder = theme.getColor(editorSymbolHighlightBorder);
    if (symbolHighlightBorder) {
        collector.addRule(`.monaco-editor .symbolHighlight { border: 1px ${isHighContrast(theme.type) ? 'dotted' : 'solid'} ${symbolHighlightBorder}; }`);
    }
    const invisibles = theme.getColor(editorWhitespaces);
    if (invisibles) {
        collector.addRule(`.monaco-editor .mtkw { color: ${invisibles} !important; }`);
        collector.addRule(`.monaco-editor .mtkz { color: ${invisibles} !important; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/colorizedBracketPairsDecorationProvider.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class ColorizedBracketPairsDecorationProvider extends Disposable {
    constructor(textModel) {
        super();
        this.textModel = textModel;
        this.colorProvider = new ColorProvider();
        this.onDidChangeEmitter = new Emitter();
        this.onDidChange = this.onDidChangeEmitter.event;
        this.colorizationOptions = textModel.getOptions().bracketPairColorizationOptions;
        this._register(textModel.bracketPairs.onDidChange(e => {
            this.onDidChangeEmitter.fire();
        }));
    }
    //#region TextModel events
    handleDidChangeOptions(e) {
        this.colorizationOptions = this.textModel.getOptions().bracketPairColorizationOptions;
    }
    //#endregion
    getDecorationsInRange(range, ownerId, filterOutValidation) {
        if (ownerId === undefined) {
            return [];
        }
        if (!this.colorizationOptions.enabled) {
            return [];
        }
        const result = new Array();
        const bracketsInRange = this.textModel.bracketPairs.getBracketsInRange(range);
        for (const bracket of bracketsInRange) {
            result.push({
                id: `bracket${bracket.range.toString()}-${bracket.nestingLevel}`,
                options: {
                    description: 'BracketPairColorization',
                    inlineClassName: this.colorProvider.getInlineClassName(bracket, this.colorizationOptions.independentColorPoolPerBracketType),
                },
                ownerId: 0,
                range: bracket.range,
            });
        }
        return result;
    }
    getAllDecorations(ownerId, filterOutValidation) {
        if (ownerId === undefined) {
            return [];
        }
        if (!this.colorizationOptions.enabled) {
            return [];
        }
        return this.getDecorationsInRange(new Range(1, 1, this.textModel.getLineCount(), 1), ownerId, filterOutValidation);
    }
}
class ColorProvider {
    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) {
        // To support a dynamic amount of colors up to 6 colors,
        // we use a number that is a lcm of all numbers from 1 to 6.
        return `bracket-highlighting-${level % 30}`;
    }
}
registerThemingParticipant((theme, collector) => {
    const colors = [
        editorBracketHighlightingForeground1,
        editorBracketHighlightingForeground2,
        editorBracketHighlightingForeground3,
        editorBracketHighlightingForeground4,
        editorBracketHighlightingForeground5,
        editorBracketHighlightingForeground6
    ];
    const colorProvider = new ColorProvider();
    collector.addRule(`.monaco-editor .${colorProvider.unexpectedClosingBracketClassName} { color: ${theme.getColor(editorBracketHighlightingUnexpectedBracketForeground)}; }`);
    const colorValues = colors
        .map(c => theme.getColor(c))
        .filter((c) => !!c)
        .filter(c => !c.isTransparent());
    for (let level = 0; level < 30; level++) {
        const color = colorValues[level % colorValues.length];
        collector.addRule(`.monaco-editor .${colorProvider.getInlineClassNameOfLevel(level)} { color: ${color}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/textChange.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


function escapeNewLine(str) {
    return (str
        .replace(/\n/g, '\\n')
        .replace(/\r/g, '\\r'));
}
class TextChange {
    constructor(oldPosition, oldText, newPosition, newText) {
        this.oldPosition = oldPosition;
        this.oldText = oldText;
        this.newPosition = newPosition;
        this.newText = newText;
    }
    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;
    }
    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 _writeStringSize(str) {
        return (4 + 2 * str.length);
    }
    static _writeString(b, str, offset) {
        const len = str.length;
        writeUInt32BE(b, len, offset);
        offset += 4;
        for (let i = 0; i < len; i++) {
            writeUInt16LE(b, str.charCodeAt(i), offset);
            offset += 2;
        }
        return offset;
    }
    static _readString(b, offset) {
        const len = readUInt32BE(b, offset);
        offset += 4;
        return decodeUTF16LE(b, offset, len);
    }
    writeSize() {
        return (+4 // oldPosition
            + 4 // newPosition
            + TextChange._writeStringSize(this.oldText)
            + TextChange._writeStringSize(this.newText));
    }
    write(b, offset) {
        writeUInt32BE(b, this.oldPosition, offset);
        offset += 4;
        writeUInt32BE(b, this.newPosition, offset);
        offset += 4;
        offset = TextChange._writeString(b, this.oldText, offset);
        offset = TextChange._writeString(b, this.newText, offset);
        return offset;
    }
    static read(b, offset, dest) {
        const oldPosition = readUInt32BE(b, offset);
        offset += 4;
        const newPosition = readUInt32BE(b, offset);
        offset += 4;
        const oldText = TextChange._readString(b, offset);
        offset += TextChange._writeStringSize(oldText);
        const newText = TextChange._readString(b, offset);
        offset += TextChange._writeStringSize(newText);
        dest.push(new TextChange(oldPosition, oldText, newPosition, newText));
        return offset;
    }
}
function compressConsecutiveTextChanges(prevEdits, currEdits) {
    if (prevEdits === null || prevEdits.length === 0) {
        return currEdits;
    }
    const compressor = new TextChangeCompressor(prevEdits, currEdits);
    return compressor.compress();
}
class TextChangeCompressor {
    constructor(prevEdits, currEdits) {
        this._prevEdits = prevEdits;
        this._currEdits = currEdits;
        this._result = [];
        this._resultLen = 0;
        this._prevLen = this._prevEdits.length;
        this._prevDeltaOffset = 0;
        this._currLen = this._currEdits.length;
        this._currDeltaOffset = 0;
    }
    compress() {
        let prevIndex = 0;
        let currIndex = 0;
        let prevEdit = this._getPrev(prevIndex);
        let currEdit = this._getCurr(currIndex);
        while (prevIndex < this._prevLen || currIndex < this._currLen) {
            if (prevEdit === null) {
                this._acceptCurr(currEdit);
                currEdit = this._getCurr(++currIndex);
                continue;
            }
            if (currEdit === null) {
                this._acceptPrev(prevEdit);
                prevEdit = this._getPrev(++prevIndex);
                continue;
            }
            if (currEdit.oldEnd <= prevEdit.newPosition) {
                this._acceptCurr(currEdit);
                currEdit = this._getCurr(++currIndex);
                continue;
            }
            if (prevEdit.newEnd <= currEdit.oldPosition) {
                this._acceptPrev(prevEdit);
                prevEdit = this._getPrev(++prevIndex);
                continue;
            }
            if (currEdit.oldPosition < prevEdit.newPosition) {
                const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newPosition - currEdit.oldPosition);
                this._acceptCurr(e1);
                currEdit = e2;
                continue;
            }
            if (prevEdit.newPosition < currEdit.oldPosition) {
                const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldPosition - prevEdit.newPosition);
                this._acceptPrev(e1);
                prevEdit = e2;
                continue;
            }
            // At this point, currEdit.oldPosition === prevEdit.newPosition
            let mergePrev;
            let mergeCurr;
            if (currEdit.oldEnd === prevEdit.newEnd) {
                mergePrev = prevEdit;
                mergeCurr = currEdit;
                prevEdit = this._getPrev(++prevIndex);
                currEdit = this._getCurr(++currIndex);
            }
            else if (currEdit.oldEnd < prevEdit.newEnd) {
                const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldLength);
                mergePrev = e1;
                mergeCurr = currEdit;
                prevEdit = e2;
                currEdit = this._getCurr(++currIndex);
            }
            else {
                const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newLength);
                mergePrev = prevEdit;
                mergeCurr = e1;
                prevEdit = this._getPrev(++prevIndex);
                currEdit = e2;
            }
            this._result[this._resultLen++] = new TextChange(mergePrev.oldPosition, mergePrev.oldText, mergeCurr.newPosition, mergeCurr.newText);
            this._prevDeltaOffset += mergePrev.newLength - mergePrev.oldLength;
            this._currDeltaOffset += mergeCurr.newLength - mergeCurr.oldLength;
        }
        const merged = TextChangeCompressor._merge(this._result);
        const cleaned = TextChangeCompressor._removeNoOps(merged);
        return cleaned;
    }
    _acceptCurr(currEdit) {
        this._result[this._resultLen++] = TextChangeCompressor._rebaseCurr(this._prevDeltaOffset, currEdit);
        this._currDeltaOffset += currEdit.newLength - currEdit.oldLength;
    }
    _getCurr(currIndex) {
        return (currIndex < this._currLen ? this._currEdits[currIndex] : null);
    }
    _acceptPrev(prevEdit) {
        this._result[this._resultLen++] = TextChangeCompressor._rebasePrev(this._currDeltaOffset, prevEdit);
        this._prevDeltaOffset += prevEdit.newLength - prevEdit.oldLength;
    }
    _getPrev(prevIndex) {
        return (prevIndex < this._prevLen ? this._prevEdits[prevIndex] : null);
    }
    static _rebaseCurr(prevDeltaOffset, currEdit) {
        return new TextChange(currEdit.oldPosition - prevDeltaOffset, currEdit.oldText, currEdit.newPosition, currEdit.newText);
    }
    static _rebasePrev(currDeltaOffset, prevEdit) {
        return new TextChange(prevEdit.oldPosition, prevEdit.oldText, prevEdit.newPosition + currDeltaOffset, prevEdit.newText);
    }
    static _splitPrev(edit, offset) {
        const preText = edit.newText.substr(0, offset);
        const postText = edit.newText.substr(offset);
        return [
            new TextChange(edit.oldPosition, edit.oldText, edit.newPosition, preText),
            new TextChange(edit.oldEnd, '', edit.newPosition + offset, postText)
        ];
    }
    static _splitCurr(edit, offset) {
        const preText = edit.oldText.substr(0, offset);
        const postText = edit.oldText.substr(offset);
        return [
            new TextChange(edit.oldPosition, preText, edit.newPosition, edit.newText),
            new TextChange(edit.oldPosition + offset, postText, edit.newEnd, '')
        ];
    }
    static _merge(edits) {
        if (edits.length === 0) {
            return edits;
        }
        const result = [];
        let resultLen = 0;
        let prev = edits[0];
        for (let i = 1; i < edits.length; i++) {
            const curr = edits[i];
            if (prev.oldEnd === curr.oldPosition) {
                // Merge into `prev`
                prev = new TextChange(prev.oldPosition, prev.oldText + curr.oldText, prev.newPosition, prev.newText + curr.newText);
            }
            else {
                result[resultLen++] = prev;
                prev = curr;
            }
        }
        result[resultLen++] = prev;
        return result;
    }
    static _removeNoOps(edits) {
        if (edits.length === 0) {
            return edits;
        }
        const result = [];
        let resultLen = 0;
        for (let i = 0; i < edits.length; i++) {
            const edit = edits[i];
            if (edit.oldText === edit.newText) {
                continue;
            }
            result[resultLen++] = edit;
        }
        return result;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/extpath.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



function extpath_isPathSeparator(code) {
    return code === 47 /* CharCode.Slash */ || code === 92 /* CharCode.Backslash */;
}
/**
 * Takes a Windows OS path and changes backward slashes to forward slashes.
 * This should only be done for OS paths from Windows (or user provided paths potentially from Windows).
 * Using it on a Linux or MaxOS path might change it.
 */
function toSlashes(osPath) {
    return osPath.replace(/[\\/]/g, posix.sep);
}
/**
 * Takes a Windows OS path (using backward or forward slashes) and turns it into a posix path:
 * - turns backward slashes into forward slashes
 * - makes it absolute if it starts with a drive letter
 * This should only be done for OS paths from Windows (or user provided paths potentially from Windows).
 * Using it on a Linux or MaxOS path might change it.
 */
function toPosixPath(osPath) {
    if (osPath.indexOf('/') === -1) {
        osPath = toSlashes(osPath);
    }
    if (/^[a-zA-Z]:(\/|$)/.test(osPath)) { // starts with a drive letter
        osPath = '/' + osPath;
    }
    return osPath;
}
/**
 * Computes the _root_ this path, like `getRoot('c:\files') === c:\`,
 * `getRoot('files:///files/path') === files:///`,
 * or `getRoot('\\server\shares\path') === \\server\shares\`
 */
function getRoot(path, sep = posix.sep) {
    if (!path) {
        return '';
    }
    const len = path.length;
    const firstLetter = path.charCodeAt(0);
    if (extpath_isPathSeparator(firstLetter)) {
        if (extpath_isPathSeparator(path.charCodeAt(1))) {
            // UNC candidate \\localhost\shares\ddd
            //               ^^^^^^^^^^^^^^^^^^^
            if (!extpath_isPathSeparator(path.charCodeAt(2))) {
                let pos = 3;
                const start = pos;
                for (; pos < len; pos++) {
                    if (extpath_isPathSeparator(path.charCodeAt(pos))) {
                        break;
                    }
                }
                if (start !== pos && !extpath_isPathSeparator(path.charCodeAt(pos + 1))) {
                    pos += 1;
                    for (; pos < len; pos++) {
                        if (extpath_isPathSeparator(path.charCodeAt(pos))) {
                            return path.slice(0, pos + 1) // consume this separator
                                .replace(/[\\/]/g, sep);
                        }
                    }
                }
            }
        }
        // /user/far
        // ^
        return sep;
    }
    else if (isWindowsDriveLetter(firstLetter)) {
        // check for windows drive letter c:\ or c:
        if (path.charCodeAt(1) === 58 /* CharCode.Colon */) {
            if (extpath_isPathSeparator(path.charCodeAt(2))) {
                // C:\fff
                // ^^^
                return path.slice(0, 2) + sep;
            }
            else {
                // C:
                // ^^
                return path.slice(0, 2);
            }
        }
    }
    // check for URI
    // scheme://authority/path
    // ^^^^^^^^^^^^^^^^^^^
    let pos = path.indexOf('://');
    if (pos !== -1) {
        pos += 3; // 3 -> "://".length
        for (; pos < len; pos++) {
            if (extpath_isPathSeparator(path.charCodeAt(pos))) {
                return path.slice(0, pos + 1); // consume this separator
            }
        }
    }
    return '';
}
/**
 * @deprecated please use `IUriIdentityService.extUri.isEqualOrParent` instead. If
 * you are in a context without services, consider to pass down the `extUri` from the
 * outside, or use `extUriBiasedIgnorePathCase` if you know what you are doing.
 */
function isEqualOrParent(base, parentCandidate, ignoreCase, separator = path_sep) {
    if (base === parentCandidate) {
        return true;
    }
    if (!base || !parentCandidate) {
        return false;
    }
    if (parentCandidate.length > base.length) {
        return false;
    }
    if (ignoreCase) {
        const beginsWith = startsWithIgnoreCase(base, parentCandidate);
        if (!beginsWith) {
            return false;
        }
        if (parentCandidate.length === base.length) {
            return true; // same path, different casing
        }
        let sepOffset = parentCandidate.length;
        if (parentCandidate.charAt(parentCandidate.length - 1) === separator) {
            sepOffset--; // adjust the expected sep offset in case our candidate already ends in separator character
        }
        return base.charAt(sepOffset) === separator;
    }
    if (parentCandidate.charAt(parentCandidate.length - 1) !== separator) {
        parentCandidate += separator;
    }
    return base.indexOf(parentCandidate) === 0;
}
function isWindowsDriveLetter(char0) {
    return char0 >= 65 /* CharCode.A */ && char0 <= 90 /* CharCode.Z */ || char0 >= 97 /* CharCode.a */ && char0 <= 122 /* CharCode.z */;
}
function hasDriveLetter(path, isWindowsOS = isWindows) {
    if (isWindowsOS) {
        return isWindowsDriveLetter(path.charCodeAt(0)) && path.charCodeAt(1) === 58 /* CharCode.Colon */;
    }
    return false;
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/resources.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






function originalFSPath(uri) {
    return uriToFsPath(uri, true);
}
class ExtUri {
    constructor(_ignorePathCasing) {
        this._ignorePathCasing = _ignorePathCasing;
    }
    compare(uri1, uri2, ignoreFragment = false) {
        if (uri1 === uri2) {
            return 0;
        }
        return compare(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._ignorePathCasing(uri) ? uri.path.toLowerCase() : undefined,
            fragment: ignoreFragment ? null : undefined
        }).toString();
    }
    isEqualOrParent(base, parentCandidate, ignoreFragment = false) {
        if (base.scheme === parentCandidate.scheme) {
            if (base.scheme === Schemas.file) {
                return isEqualOrParent(originalFSPath(base), originalFSPath(parentCandidate), this._ignorePathCasing(base)) && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment);
            }
            if (isEqualAuthority(base.authority, parentCandidate.authority)) {
                return isEqualOrParent(base.path, parentCandidate.path, this._ignorePathCasing(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 resources_basename(resource) || resource.authority;
    }
    basename(resource) {
        return posix.basename(resource.path);
    }
    extname(resource) {
        return posix.extname(resource.path);
    }
    dirname(resource) {
        if (resource.path.length === 0) {
            return resource;
        }
        let dirname;
        if (resource.scheme === Schemas.file) {
            dirname = URI.file(path_dirname(originalFSPath(resource))).path;
        }
        else {
            dirname = posix.dirname(resource.path);
            if (resource.authority && dirname.length && dirname.charCodeAt(0) !== 47 /* CharCode.Slash */) {
                console.error(`dirname("${resource.toString})) resulted in a relative path`);
                dirname = '/'; // If a URI contains an authority component, then the path component must either be empty or begin with a CharCode.Slash ("/") character
            }
        }
        return resource.with({
            path: dirname
        });
    }
    normalizePath(resource) {
        if (!resource.path.length) {
            return resource;
        }
        let normalizedPath;
        if (resource.scheme === Schemas.file) {
            normalizedPath = URI.file(normalize(originalFSPath(resource))).path;
        }
        else {
            normalizedPath = posix.normalize(resource.path);
        }
        return resource.with({
            path: normalizedPath
        });
    }
    relativePath(from, to) {
        if (from.scheme !== to.scheme || !isEqualAuthority(from.authority, to.authority)) {
            return undefined;
        }
        if (from.scheme === Schemas.file) {
            const relativePath = relative(originalFSPath(from), originalFSPath(to));
            return isWindows ? toSlashes(relativePath) : relativePath;
        }
        let fromPath = from.path || '/';
        const toPath = to.path || '/';
        if (this._ignorePathCasing(from)) {
            // make casing of fromPath match toPath
            let i = 0;
            for (const len = Math.min(fromPath.length, toPath.length); i < len; i++) {
                if (fromPath.charCodeAt(i) !== toPath.charCodeAt(i)) {
                    if (fromPath.charAt(i).toLowerCase() !== toPath.charAt(i).toLowerCase()) {
                        break;
                    }
                }
            }
            fromPath = toPath.substr(0, i) + fromPath.substr(i);
        }
        return posix.relative(fromPath, toPath);
    }
    resolvePath(base, path) {
        if (base.scheme === Schemas.file) {
            const newURI = URI.file(resolve(originalFSPath(base), path));
            return base.with({
                authority: newURI.authority,
                path: newURI.path
            });
        }
        path = toPosixPath(path); // we allow path to be a windows path
        return base.with({
            path: posix.resolve(base.path, path)
        });
    }
    // --- misc
    isAbsolutePath(resource) {
        return !!resource.path && resource.path[0] === '/';
    }
    isEqualAuthority(a1, a2) {
        return a1 === a2 || (a1 !== undefined && a2 !== undefined && equalsIgnoreCase(a1, a2));
    }
    hasTrailingPathSeparator(resource, sep = path_sep) {
        if (resource.scheme === Schemas.file) {
            const fsp = originalFSPath(resource);
            return fsp.length > getRoot(fsp).length && fsp[fsp.length - 1] === sep;
        }
        else {
            const p = resource.path;
            return (p.length > 1 && p.charCodeAt(p.length - 1) === 47 /* CharCode.Slash */) && !(/^[a-zA-Z]:(\/$|\\$)/.test(resource.fsPath)); // ignore the slash at offset 0
        }
    }
    removeTrailingPathSeparator(resource, sep = path_sep) {
        // Make sure that the path isn't a drive letter. A trailing separator there is not removable.
        if (hasTrailingPathSeparator(resource, sep)) {
            return resource.with({ path: resource.path.substr(0, resource.path.length - 1) });
        }
        return resource;
    }
    addTrailingPathSeparator(resource, sep = path_sep) {
        let isRootSep = false;
        if (resource.scheme === Schemas.file) {
            const fsp = originalFSPath(resource);
            isRootSep = ((fsp !== undefined) && (fsp.length === getRoot(fsp).length) && (fsp[fsp.length - 1] === sep));
        }
        else {
            sep = '/';
            const p = resource.path;
            isRootSep = p.length === 1 && p.charCodeAt(p.length - 1) === 47 /* CharCode.Slash */;
        }
        if (!isRootSep && !hasTrailingPathSeparator(resource, sep)) {
            return resource.with({ path: resource.path + '/' });
        }
        return resource;
    }
}
/**
 * Unbiased utility that takes uris "as they are". This means it can be interchanged with
 * uri#toString() usages. The following is true
 * ```
 * assertEqual(aUri.toString() === bUri.toString(), exturi.isEqual(aUri, bUri))
 * ```
 */
const extUri = new ExtUri(() => false);
/**
 * BIASED utility that _mostly_ ignored the case of urs paths. ONLY use this util if you
 * understand what you are doing.
 *
 * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged.
 *
 * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient
 * because those uris come from a "trustworthy source". When creating unknown uris it's always
 * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path
 * casing matters.
 */
const extUriBiasedIgnorePathCase = new ExtUri(uri => {
    // A file scheme resource is in the same platform as code, so ignore case for non linux platforms
    // Resource can be from another platform. Lowering the case as an hack. Should come from File system provider
    return uri.scheme === Schemas.file ? !isLinux : true;
});
/**
 * BIASED utility that always ignores the casing of uris paths. ONLY use this util if you
 * understand what you are doing.
 *
 * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged.
 *
 * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient
 * because those uris come from a "trustworthy source". When creating unknown uris it's always
 * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path
 * casing matters.
 */
const extUriIgnorePathCase = new ExtUri(_ => true);
const isEqual = extUri.isEqual.bind(extUri);
const resources_isEqualOrParent = extUri.isEqualOrParent.bind(extUri);
const getComparisonKey = extUri.getComparisonKey.bind(extUri);
const basenameOrAuthority = extUri.basenameOrAuthority.bind(extUri);
const resources_basename = extUri.basename.bind(extUri);
const resources_extname = extUri.extname.bind(extUri);
const dirname = extUri.dirname.bind(extUri);
const joinPath = extUri.joinPath.bind(extUri);
const normalizePath = extUri.normalizePath.bind(extUri);
const relativePath = extUri.relativePath.bind(extUri);
const resolvePath = extUri.resolvePath.bind(extUri);
const isAbsolutePath = extUri.isAbsolutePath.bind(extUri);
const isEqualAuthority = extUri.isEqualAuthority.bind(extUri);
const hasTrailingPathSeparator = extUri.hasTrailingPathSeparator.bind(extUri);
const removeTrailingPathSeparator = extUri.removeTrailingPathSeparator.bind(extUri);
const addTrailingPathSeparator = extUri.addTrailingPathSeparator.bind(extUri);
/**
 * Data URI related helpers.
 */
var DataUri;
(function (DataUri) {
    DataUri.META_DATA_LABEL = 'label';
    DataUri.META_DATA_DESCRIPTION = 'description';
    DataUri.META_DATA_SIZE = 'size';
    DataUri.META_DATA_MIME = 'mime';
    function parseMetaData(dataUri) {
        const metadata = new Map();
        // Given a URI of:  data:image/png;size:2313;label:SomeLabel;description:SomeDescription;base64,77+9UE5...
        // the metadata is: size:2313;label:SomeLabel;description:SomeDescription
        const meta = dataUri.path.substring(dataUri.path.indexOf(';') + 1, dataUri.path.lastIndexOf(';'));
        meta.split(';').forEach(property => {
            const [key, value] = property.split(':');
            if (key && value) {
                metadata.set(key, value);
            }
        });
        // Given a URI of:  data:image/png;size:2313;label:SomeLabel;description:SomeDescription;base64,77+9UE5...
        // the mime is: image/png
        const mime = dataUri.path.substring(0, dataUri.path.indexOf(';'));
        if (mime) {
            metadata.set(DataUri.META_DATA_MIME, mime);
        }
        return metadata;
    }
    DataUri.parseMetaData = parseMetaData;
})(DataUri || (DataUri = {}));

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/editStack.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







function uriGetComparisonKey(resource) {
    return resource.toString();
}
class SingleModelEditStackData {
    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;
    }
    static create(model, beforeCursorState) {
        const alternativeVersionId = model.getAlternativeVersionId();
        const eol = getModelEOL(model);
        return new SingleModelEditStackData(alternativeVersionId, alternativeVersionId, eol, eol, beforeCursorState, beforeCursorState, []);
    }
    append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
        if (textChanges.length > 0) {
            this.changes = compressConsecutiveTextChanges(this.changes, textChanges);
        }
        this.afterEOL = afterEOL;
        this.afterVersionId = afterVersionId;
        this.afterCursorState = afterCursorState;
    }
    static _writeSelectionsSize(selections) {
        return 4 + 4 * 4 * (selections ? selections.length : 0);
    }
    static _writeSelections(b, selections, offset) {
        writeUInt32BE(b, (selections ? selections.length : 0), offset);
        offset += 4;
        if (selections) {
            for (const selection of selections) {
                writeUInt32BE(b, selection.selectionStartLineNumber, offset);
                offset += 4;
                writeUInt32BE(b, selection.selectionStartColumn, offset);
                offset += 4;
                writeUInt32BE(b, selection.positionLineNumber, offset);
                offset += 4;
                writeUInt32BE(b, selection.positionColumn, offset);
                offset += 4;
            }
        }
        return offset;
    }
    static _readSelections(b, offset, dest) {
        const count = readUInt32BE(b, offset);
        offset += 4;
        for (let i = 0; i < count; i++) {
            const selectionStartLineNumber = readUInt32BE(b, offset);
            offset += 4;
            const selectionStartColumn = readUInt32BE(b, offset);
            offset += 4;
            const positionLineNumber = readUInt32BE(b, offset);
            offset += 4;
            const positionColumn = readUInt32BE(b, offset);
            offset += 4;
            dest.push(new Selection(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn));
        }
        return offset;
    }
    serialize() {
        let necessarySize = (+4 // beforeVersionId
            + 4 // afterVersionId
            + 1 // beforeEOL
            + 1 // afterEOL
            + SingleModelEditStackData._writeSelectionsSize(this.beforeCursorState)
            + SingleModelEditStackData._writeSelectionsSize(this.afterCursorState)
            + 4 // change count
        );
        for (const change of this.changes) {
            necessarySize += change.writeSize();
        }
        const b = new Uint8Array(necessarySize);
        let offset = 0;
        writeUInt32BE(b, this.beforeVersionId, offset);
        offset += 4;
        writeUInt32BE(b, this.afterVersionId, offset);
        offset += 4;
        writeUInt8(b, this.beforeEOL, offset);
        offset += 1;
        writeUInt8(b, this.afterEOL, offset);
        offset += 1;
        offset = SingleModelEditStackData._writeSelections(b, this.beforeCursorState, offset);
        offset = SingleModelEditStackData._writeSelections(b, this.afterCursorState, offset);
        writeUInt32BE(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 = readUInt32BE(b, offset);
        offset += 4;
        const afterVersionId = readUInt32BE(b, offset);
        offset += 4;
        const beforeEOL = readUInt8(b, offset);
        offset += 1;
        const afterEOL = readUInt8(b, offset);
        offset += 1;
        const beforeCursorState = [];
        offset = SingleModelEditStackData._readSelections(b, offset, beforeCursorState);
        const afterCursorState = [];
        offset = SingleModelEditStackData._readSelections(b, offset, afterCursorState);
        const changeCount = readUInt32BE(b, offset);
        offset += 4;
        const changes = [];
        for (let i = 0; i < changeCount; i++) {
            offset = TextChange.read(b, offset, changes);
        }
        return new SingleModelEditStackData(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes);
    }
}
class SingleModelEditStackElement {
    constructor(label, code, model, beforeCursorState) {
        this.label = label;
        this.code = code;
        this.model = model;
        this._data = SingleModelEditStackData.create(model, beforeCursorState);
    }
    get type() {
        return 0 /* UndoRedoElementType.Resource */;
    }
    get resource() {
        if (URI.isUri(this.model)) {
            return this.model;
        }
        return this.model.uri;
    }
    toString() {
        const data = (this._data instanceof SingleModelEditStackData ? this._data : SingleModelEditStackData.deserialize(this._data));
        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._data instanceof SingleModelEditStackData);
    }
    append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
        if (this._data instanceof SingleModelEditStackData) {
            this._data.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
        }
    }
    close() {
        if (this._data instanceof SingleModelEditStackData) {
            this._data = this._data.serialize();
        }
    }
    open() {
        if (!(this._data instanceof SingleModelEditStackData)) {
            this._data = SingleModelEditStackData.deserialize(this._data);
        }
    }
    undo() {
        if (URI.isUri(this.model)) {
            // don't have a model
            throw new Error(`Invalid SingleModelEditStackElement`);
        }
        if (this._data instanceof SingleModelEditStackData) {
            this._data = this._data.serialize();
        }
        const data = SingleModelEditStackData.deserialize(this._data);
        this.model._applyUndo(data.changes, data.beforeEOL, data.beforeVersionId, data.beforeCursorState);
    }
    redo() {
        if (URI.isUri(this.model)) {
            // don't have a model
            throw new Error(`Invalid SingleModelEditStackElement`);
        }
        if (this._data instanceof SingleModelEditStackData) {
            this._data = this._data.serialize();
        }
        const data = SingleModelEditStackData.deserialize(this._data);
        this.model._applyRedo(data.changes, data.afterEOL, data.afterVersionId, data.afterCursorState);
    }
    heapSize() {
        if (this._data instanceof SingleModelEditStackData) {
            this._data = this._data.serialize();
        }
        return this._data.byteLength + 168 /*heap overhead*/;
    }
}
class MultiModelEditStackElement {
    constructor(label, code, editStackElements) {
        this.label = label;
        this.code = code;
        this.type = 1 /* UndoRedoElementType.Workspace */;
        this._isOpen = true;
        this._editStackElementsArr = editStackElements.slice(0);
        this._editStackElementsMap = new Map();
        for (const editStackElement of this._editStackElementsArr) {
            const key = uriGetComparisonKey(editStackElement.resource);
            this._editStackElementsMap.set(key, editStackElement);
        }
        this._delegate = null;
    }
    get resources() {
        return this._editStackElementsArr.map(editStackElement => editStackElement.resource);
    }
    prepareUndoRedo() {
        if (this._delegate) {
            return this._delegate.prepareUndoRedo(this);
        }
    }
    matchesResource(resource) {
        const key = uriGetComparisonKey(resource);
        return (this._editStackElementsMap.has(key));
    }
    setModel(model) {
        const key = uriGetComparisonKey(URI.isUri(model) ? model : model.uri);
        if (this._editStackElementsMap.has(key)) {
            this._editStackElementsMap.get(key).setModel(model);
        }
    }
    canAppend(model) {
        if (!this._isOpen) {
            return false;
        }
        const key = uriGetComparisonKey(model.uri);
        if (this._editStackElementsMap.has(key)) {
            const editStackElement = this._editStackElementsMap.get(key);
            return editStackElement.canAppend(model);
        }
        return false;
    }
    append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
        const key = uriGetComparisonKey(model.uri);
        const editStackElement = this._editStackElementsMap.get(key);
        editStackElement.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
    }
    close() {
        this._isOpen = false;
    }
    open() {
        // cannot reopen
    }
    undo() {
        this._isOpen = false;
        for (const editStackElement of this._editStackElementsArr) {
            editStackElement.undo();
        }
    }
    redo() {
        for (const editStackElement of this._editStackElementsArr) {
            editStackElement.redo();
        }
    }
    heapSize(resource) {
        const key = uriGetComparisonKey(resource);
        if (this._editStackElementsMap.has(key)) {
            const editStackElement = this._editStackElementsMap.get(key);
            return editStackElement.heapSize();
        }
        return 0;
    }
    split() {
        return this._editStackElementsArr;
    }
    toString() {
        const result = [];
        for (const editStackElement of this._editStackElementsArr) {
            result.push(`${resources_basename(editStackElement.resource)}: ${editStackElement}`);
        }
        return `{${result.join(', ')}}`;
    }
}
function getModelEOL(model) {
    const eol = model.getEOL();
    if (eol === '\n') {
        return 0 /* EndOfLineSequence.LF */;
    }
    else {
        return 1 /* EndOfLineSequence.CRLF */;
    }
}
function isEditStackElement(element) {
    if (!element) {
        return false;
    }
    return ((element instanceof SingleModelEditStackElement) || (element instanceof MultiModelEditStackElement));
}
class EditStack {
    constructor(model, undoRedoService) {
        this._model = model;
        this._undoRedoService = undoRedoService;
    }
    pushStackElement() {
        const lastElement = this._undoRedoService.getLastElement(this._model.uri);
        if (isEditStackElement(lastElement)) {
            lastElement.close();
        }
    }
    popStackElement() {
        const lastElement = this._undoRedoService.getLastElement(this._model.uri);
        if (isEditStackElement(lastElement)) {
            lastElement.open();
        }
    }
    clear() {
        this._undoRedoService.removeElements(this._model.uri);
    }
    _getOrCreateEditStackElement(beforeCursorState) {
        const lastElement = this._undoRedoService.getLastElement(this._model.uri);
        if (isEditStackElement(lastElement) && lastElement.canAppend(this._model)) {
            return lastElement;
        }
        const newElement = new SingleModelEditStackElement(localize('edit', "Typing"), 'undoredo.textBufferEdit', this._model, beforeCursorState);
        this._undoRedoService.pushElement(newElement);
        return newElement;
    }
    pushEOL(eol) {
        const editStackElement = this._getOrCreateEditStackElement(null);
        this._model.setEOL(eol);
        editStackElement.append(this._model, [], getModelEOL(this._model), this._model.getAlternativeVersionId(), null);
    }
    pushEditOperation(beforeCursorState, editOperations, cursorStateComputer) {
        const editStackElement = this._getOrCreateEditStackElement(beforeCursorState);
        const inverseEditOperations = this._model.applyEdits(editOperations, true);
        const afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperations);
        const textChanges = inverseEditOperations.map((op, index) => ({ 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._model, textChanges.map(op => op.textChange), getModelEOL(this._model), this._model.getAlternativeVersionId(), afterCursorState);
        return afterCursorState;
    }
    static _computeCursorState(cursorStateComputer, inverseEditOperations) {
        try {
            return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null;
        }
        catch (e) {
            onUnexpectedError(e);
            return null;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/textModelPart.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class TextModelPart extends Disposable {
    constructor() {
        super(...arguments);
        this._isDisposed = false;
    }
    dispose() {
        super.dispose();
        this._isDisposed = true;
    }
    assertNotDisposed() {
        if (this._isDisposed) {
            throw new Error('TextModelPart is disposed!');
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/utils.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/**
 * Returns:
 *  - -1 => the line consists of whitespace
 *  - otherwise => the indent level is returned value
 */
function computeIndentLevel(line, tabSize) {
    let indent = 0;
    let i = 0;
    const len = line.length;
    while (i < len) {
        const chCode = line.charCodeAt(i);
        if (chCode === 32 /* CharCode.Space */) {
            indent++;
        }
        else if (chCode === 9 /* CharCode.Tab */) {
            indent = indent - indent % tabSize + tabSize;
        }
        else {
            break;
        }
        i++;
    }
    if (i === len) {
        return -1; // line only consists of whitespace
    }
    return indent;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/textModelGuides.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var HorizontalGuidesState;
(function (HorizontalGuidesState) {
    HorizontalGuidesState[HorizontalGuidesState["Disabled"] = 0] = "Disabled";
    HorizontalGuidesState[HorizontalGuidesState["EnabledForActive"] = 1] = "EnabledForActive";
    HorizontalGuidesState[HorizontalGuidesState["Enabled"] = 2] = "Enabled";
})(HorizontalGuidesState || (HorizontalGuidesState = {}));
class IndentGuide {
    constructor(visibleColumn, column, className, 
    /**
     * If set, this indent guide is a horizontal guide (no vertical part).
     * It starts at visibleColumn and continues until endColumn.
    */
    horizontalLine, 
    /**
     * If set (!= -1), only show this guide for wrapped lines that don't contain this model column, but are after it.
    */
    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();
        }
    }
}
class IndentGuideHorizontalLine {
    constructor(top, endColumn) {
        this.top = top;
        this.endColumn = endColumn;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/guidesTextModelPart.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







class GuidesTextModelPart extends TextModelPart {
    constructor(textModel, languageConfigurationService) {
        super();
        this.textModel = textModel;
        this.languageConfigurationService = languageConfigurationService;
    }
    getLanguageConfiguration(languageId) {
        return this.languageConfigurationService.getLanguageConfiguration(languageId);
    }
    _computeIndentLevel(lineIndex) {
        return computeIndentLevel(this.textModel.getLineContent(lineIndex + 1), this.textModel.getOptions().tabSize);
    }
    getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
        this.assertNotDisposed();
        const lineCount = this.textModel.getLineCount();
        if (lineNumber < 1 || lineNumber > lineCount) {
            throw new Error('Illegal value for lineNumber');
        }
        const foldingRules = this.getLanguageConfiguration(this.textModel.getLanguageId()).foldingRules;
        const offSide = Boolean(foldingRules && foldingRules.offSide);
        let up_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
        let up_aboveContentLineIndent = -1;
        let up_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
        let up_belowContentLineIndent = -1;
        const up_resolveIndents = (lineNumber) => {
            if (up_aboveContentLineIndex !== -1 &&
                (up_aboveContentLineIndex === -2 ||
                    up_aboveContentLineIndex > lineNumber - 1)) {
                up_aboveContentLineIndex = -1;
                up_aboveContentLineIndent = -1;
                // must find previous line with content
                for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
                    const indent = this._computeIndentLevel(lineIndex);
                    if (indent >= 0) {
                        up_aboveContentLineIndex = lineIndex;
                        up_aboveContentLineIndent = indent;
                        break;
                    }
                }
            }
            if (up_belowContentLineIndex === -2) {
                up_belowContentLineIndex = -1;
                up_belowContentLineIndent = -1;
                // must find next line with content
                for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
                    const indent = this._computeIndentLevel(lineIndex);
                    if (indent >= 0) {
                        up_belowContentLineIndex = lineIndex;
                        up_belowContentLineIndent = indent;
                        break;
                    }
                }
            }
        };
        let down_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
        let down_aboveContentLineIndent = -1;
        let down_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
        let down_belowContentLineIndent = -1;
        const down_resolveIndents = (lineNumber) => {
            if (down_aboveContentLineIndex === -2) {
                down_aboveContentLineIndex = -1;
                down_aboveContentLineIndent = -1;
                // must find previous line with content
                for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
                    const indent = this._computeIndentLevel(lineIndex);
                    if (indent >= 0) {
                        down_aboveContentLineIndex = lineIndex;
                        down_aboveContentLineIndent = indent;
                        break;
                    }
                }
            }
            if (down_belowContentLineIndex !== -1 &&
                (down_belowContentLineIndex === -2 ||
                    down_belowContentLineIndex < lineNumber - 1)) {
                down_belowContentLineIndex = -1;
                down_belowContentLineIndent = -1;
                // must find next line with content
                for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
                    const indent = this._computeIndentLevel(lineIndex);
                    if (indent >= 0) {
                        down_belowContentLineIndex = lineIndex;
                        down_belowContentLineIndent = indent;
                        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 > 50000) {
                // stop processing
                goUp = false;
                goDown = false;
            }
            let upLineIndentLevel = -1;
            if (goUp && upLineNumber >= 1) {
                // compute indent level going up
                const currentIndent = this._computeIndentLevel(upLineNumber - 1);
                if (currentIndent >= 0) {
                    // This line has content (besides whitespace)
                    // Use the line's indent
                    up_belowContentLineIndex = upLineNumber - 1;
                    up_belowContentLineIndent = currentIndent;
                    upLineIndentLevel = Math.ceil(currentIndent / this.textModel.getOptions().indentSize);
                }
                else {
                    up_resolveIndents(upLineNumber);
                    upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent);
                }
            }
            let downLineIndentLevel = -1;
            if (goDown && downLineNumber <= lineCount) {
                // compute indent level going down
                const currentIndent = this._computeIndentLevel(downLineNumber - 1);
                if (currentIndent >= 0) {
                    // This line has content (besides whitespace)
                    // Use the line's indent
                    down_aboveContentLineIndex = downLineNumber - 1;
                    down_aboveContentLineIndent = currentIndent;
                    downLineIndentLevel = Math.ceil(currentIndent / this.textModel.getOptions().indentSize);
                }
                else {
                    down_resolveIndents(downLineNumber);
                    downLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, down_aboveContentLineIndent, down_belowContentLineIndent);
                }
            }
            if (distance === 0) {
                initialIndent = upLineIndentLevel;
                continue;
            }
            if (distance === 1) {
                if (downLineNumber <= lineCount &&
                    downLineIndentLevel >= 0 &&
                    initialIndent + 1 === downLineIndentLevel) {
                    // This is the beginning of a scope, we have special handling here, since we want the
                    // child scope indent to be active, not the parent scope
                    goUp = false;
                    startLineNumber = downLineNumber;
                    endLineNumber = downLineNumber;
                    indent = downLineIndentLevel;
                    continue;
                }
                if (upLineNumber >= 1 &&
                    upLineIndentLevel >= 0 &&
                    upLineIndentLevel - 1 === initialIndent) {
                    // This is the end of a scope, just like above
                    goDown = false;
                    startLineNumber = upLineNumber;
                    endLineNumber = upLineNumber;
                    indent = upLineIndentLevel;
                    continue;
                }
                startLineNumber = lineNumber;
                endLineNumber = lineNumber;
                indent = initialIndent;
                if (indent === 0) {
                    // No need to continue
                    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, options) {
        var _a;
        const result = [];
        for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
            result.push([]);
        }
        // If requested, this could be made configurable.
        const includeSingleLinePairs = true;
        const bracketPairs = this.textModel.bracketPairs.getBracketPairsInRangeWithMinIndentation(new Range(startLineNumber, 1, endLineNumber, this.textModel.getLineMaxColumn(endLineNumber)));
        let activeBracketPairRange = undefined;
        if (activePosition && bracketPairs.length > 0) {
            const bracketsContainingActivePosition = (startLineNumber <= activePosition.lineNumber &&
                activePosition.lineNumber <= endLineNumber
                // We don't need to query the brackets again if the cursor is in the viewport
                ? bracketPairs
                : this.textModel.bracketPairs.getBracketPairsInRange(Range.fromPositions(activePosition))).filter((bp) => Range.strictContainsPosition(bp.range, activePosition));
            activeBracketPairRange = (_a = findLast(bracketsContainingActivePosition, (i) => includeSingleLinePairs || i.range.startLineNumber !== i.range.endLineNumber)) === null || _a === void 0 ? void 0 : _a.range;
        }
        const independentColorPoolPerBracketType = this.textModel.getOptions().bracketPairColorizationOptions.independentColorPoolPerBracketType;
        const colorProvider = new BracketPairGuidesClassNames();
        for (const pair of bracketPairs) {
            /*


                    {
                    |
                    }

                    {
                    |
                    ----}

                ____{
                |test
                ----}

                renderHorizontalEndLineAtTheBottom:
                    {
                    |
                    |x}
                    --
                renderHorizontalEndLineAtTheBottom:
                ____{
                |test
                | x }
                ----
            */
            if (!pair.closingBracketRange) {
                continue;
            }
            const isActive = activeBracketPairRange && pair.range.equalsRange(activeBracketPairRange);
            if (!isActive && !options.includeInactive) {
                continue;
            }
            const className = colorProvider.getInlineClassName(pair.nestingLevel, pair.nestingLevelOfEqualBracketType, independentColorPoolPerBracketType) +
                (options.highlightActive && isActive
                    ? ' ' + colorProvider.activeClassName
                    : '');
            const start = pair.openingBracketRange.getStartPosition();
            const end = pair.closingBracketRange.getStartPosition();
            const horizontalGuides = options.horizontalGuides === HorizontalGuidesState.Enabled || (options.horizontalGuides === HorizontalGuidesState.EnabledForActive && isActive);
            if (pair.range.startLineNumber === pair.range.endLineNumber) {
                if (includeSingleLinePairs && horizontalGuides) {
                    result[pair.range.startLineNumber - startLineNumber].push(new IndentGuide(-1, pair.openingBracketRange.getEndPosition().column, className, new IndentGuideHorizontalLine(false, end.column), -1, -1));
                }
                continue;
            }
            const endVisibleColumn = this.getVisibleColumnFromPosition(end);
            const startVisibleColumn = this.getVisibleColumnFromPosition(pair.openingBracketRange.getStartPosition());
            const guideVisibleColumn = Math.min(startVisibleColumn, endVisibleColumn, pair.minVisibleColumnIndentation + 1);
            let renderHorizontalEndLineAtTheBottom = false;
            const firstNonWsIndex = strings_firstNonWhitespaceIndex(this.textModel.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 IndentGuide(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 IndentGuide(guideVisibleColumn, -1, className, new IndentGuideHorizontalLine(false, start.column), -1, -1));
                }
                if (end.lineNumber <= endLineNumber && endVisibleColumn > guideVisibleColumn) {
                    result[end.lineNumber - startLineNumber].push(new IndentGuide(guideVisibleColumn, -1, className, new IndentGuideHorizontalLine(!renderHorizontalEndLineAtTheBottom, end.column), -1, -1));
                }
            }
        }
        for (const guides of result) {
            guides.sort((a, b) => a.visibleColumn - b.visibleColumn);
        }
        return result;
    }
    getVisibleColumnFromPosition(position) {
        return (CursorColumns.visibleColumnFromColumn(this.textModel.getLineContent(position.lineNumber), position.column, this.textModel.getOptions().tabSize) + 1);
    }
    getLinesIndentGuides(startLineNumber, endLineNumber) {
        this.assertNotDisposed();
        const lineCount = this.textModel.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 options = this.textModel.getOptions();
        const foldingRules = this.getLanguageConfiguration(this.textModel.getLanguageId()).foldingRules;
        const offSide = Boolean(foldingRules && foldingRules.offSide);
        const result = new Array(endLineNumber - startLineNumber + 1);
        let aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
        let aboveContentLineIndent = -1;
        let belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
        let belowContentLineIndent = -1;
        for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
            const resultIndex = lineNumber - startLineNumber;
            const currentIndent = this._computeIndentLevel(lineNumber - 1);
            if (currentIndent >= 0) {
                // This line has content (besides whitespace)
                // Use the line's indent
                aboveContentLineIndex = lineNumber - 1;
                aboveContentLineIndent = currentIndent;
                result[resultIndex] = Math.ceil(currentIndent / options.indentSize);
                continue;
            }
            if (aboveContentLineIndex === -2) {
                aboveContentLineIndex = -1;
                aboveContentLineIndent = -1;
                // must find previous line with content
                for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
                    const indent = this._computeIndentLevel(lineIndex);
                    if (indent >= 0) {
                        aboveContentLineIndex = lineIndex;
                        aboveContentLineIndent = indent;
                        break;
                    }
                }
            }
            if (belowContentLineIndex !== -1 &&
                (belowContentLineIndex === -2 || belowContentLineIndex < lineNumber - 1)) {
                belowContentLineIndex = -1;
                belowContentLineIndent = -1;
                // must find next line with content
                for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
                    const indent = this._computeIndentLevel(lineIndex);
                    if (indent >= 0) {
                        belowContentLineIndex = lineIndex;
                        belowContentLineIndent = indent;
                        break;
                    }
                }
            }
            result[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent);
        }
        return result;
    }
    _getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent) {
        const options = this.textModel.getOptions();
        if (aboveContentLineIndent === -1 || belowContentLineIndent === -1) {
            // At the top or bottom of the file
            return 0;
        }
        else if (aboveContentLineIndent < belowContentLineIndent) {
            // we are inside the region above
            return 1 + Math.floor(aboveContentLineIndent / options.indentSize);
        }
        else if (aboveContentLineIndent === belowContentLineIndent) {
            // we are in between two regions
            return Math.ceil(belowContentLineIndent / options.indentSize);
        }
        else {
            if (offSide) {
                // same level as region below
                return Math.ceil(belowContentLineIndent / options.indentSize);
            }
            else {
                // we are inside the region that ends below
                return 1 + Math.floor(belowContentLineIndent / options.indentSize);
            }
        }
    }
}
class BracketPairGuidesClassNames {
    constructor() {
        this.activeClassName = 'indent-active';
    }
    getInlineClassName(nestingLevel, nestingLevelOfEqualBracketType, independentColorPoolPerBracketType) {
        return this.getInlineClassNameOfLevel(independentColorPoolPerBracketType ? nestingLevelOfEqualBracketType : nestingLevel);
    }
    getInlineClassNameOfLevel(level) {
        // To support a dynamic amount of colors up to 6 colors,
        // we use a number that is a lcm of all numbers from 1 to 6.
        return `bracket-indent-guide lvl-${level % 30}`;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/indentationGuesser.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class SpacesDiffResult {
    constructor() {
        this.spacesDiff = 0;
        this.looksLikeAlignment = false;
    }
}
/**
 * Compute the diff in spaces between two line's indentation.
 */
function spacesDiff(a, aLength, b, bLength, result) {
    result.spacesDiff = 0;
    result.looksLikeAlignment = false;
    // This can go both ways (e.g.):
    //  - a: "\t"
    //  - b: "\t    "
    //  => This should count 1 tab and 4 spaces
    let i;
    for (i = 0; i < aLength && i < bLength; i++) {
        const aCharCode = a.charCodeAt(i);
        const bCharCode = b.charCodeAt(i);
        if (aCharCode !== bCharCode) {
            break;
        }
    }
    let aSpacesCnt = 0, aTabsCount = 0;
    for (let j = i; j < aLength; j++) {
        const aCharCode = a.charCodeAt(j);
        if (aCharCode === 32 /* CharCode.Space */) {
            aSpacesCnt++;
        }
        else {
            aTabsCount++;
        }
    }
    let bSpacesCnt = 0, bTabsCount = 0;
    for (let j = i; j < bLength; j++) {
        const bCharCode = b.charCodeAt(j);
        if (bCharCode === 32 /* CharCode.Space */) {
            bSpacesCnt++;
        }
        else {
            bTabsCount++;
        }
    }
    if (aSpacesCnt > 0 && aTabsCount > 0) {
        return;
    }
    if (bSpacesCnt > 0 && bTabsCount > 0) {
        return;
    }
    const tabsDiff = Math.abs(aTabsCount - bTabsCount);
    const spacesDiff = Math.abs(aSpacesCnt - bSpacesCnt);
    if (tabsDiff === 0) {
        // check if the indentation difference might be caused by alignment reasons
        // sometime folks like to align their code, but this should not be used as a hint
        result.spacesDiff = spacesDiff;
        if (spacesDiff > 0 && 0 <= bSpacesCnt - 1 && bSpacesCnt - 1 < a.length && bSpacesCnt < b.length) {
            if (b.charCodeAt(bSpacesCnt) !== 32 /* CharCode.Space */ && a.charCodeAt(bSpacesCnt - 1) === 32 /* CharCode.Space */) {
                if (a.charCodeAt(a.length - 1) === 44 /* CharCode.Comma */) {
                    // This looks like an alignment desire: e.g.
                    // const a = b + c,
                    //       d = b - c;
                    result.looksLikeAlignment = true;
                }
            }
        }
        return;
    }
    if (spacesDiff % tabsDiff === 0) {
        result.spacesDiff = spacesDiff / tabsDiff;
        return;
    }
}
function guessIndentation(source, defaultTabSize, defaultInsertSpaces) {
    // Look at most at the first 10k lines
    const linesCount = Math.min(source.getLineCount(), 10000);
    let linesIndentedWithTabsCount = 0; // number of lines that contain at least one tab in indentation
    let linesIndentedWithSpacesCount = 0; // number of lines that contain only spaces in indentation
    let previousLineText = ''; // content of latest line that contained non-whitespace chars
    let previousLineIndentation = 0; // index at which latest line contained the first non-whitespace char
    const ALLOWED_TAB_SIZE_GUESSES = [2, 4, 6, 8, 3, 5, 7]; // prefer even guesses for `tabSize`, limit to [2, 8].
    const MAX_ALLOWED_TAB_SIZE_GUESS = 8; // max(ALLOWED_TAB_SIZE_GUESSES) = 8
    const spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0]; // `tabSize` scores
    const tmp = new SpacesDiffResult();
    for (let lineNumber = 1; lineNumber <= linesCount; lineNumber++) {
        const currentLineLength = source.getLineLength(lineNumber);
        const currentLineText = source.getLineContent(lineNumber);
        // if the text buffer is chunk based, so long lines are cons-string, v8 will flattern the string when we check charCode.
        // checking charCode on chunks directly is cheaper.
        const useCurrentLineText = (currentLineLength <= 65536);
        let currentLineHasContent = false; // does `currentLineText` contain non-whitespace chars
        let currentLineIndentation = 0; // index at which `currentLineText` contains the first non-whitespace char
        let currentLineSpacesCount = 0; // count of spaces found in `currentLineText` indentation
        let currentLineTabsCount = 0; // count of tabs found in `currentLineText` indentation
        for (let j = 0, lenJ = currentLineLength; j < lenJ; j++) {
            const charCode = (useCurrentLineText ? currentLineText.charCodeAt(j) : source.getLineCharCode(lineNumber, j));
            if (charCode === 9 /* CharCode.Tab */) {
                currentLineTabsCount++;
            }
            else if (charCode === 32 /* CharCode.Space */) {
                currentLineSpacesCount++;
            }
            else {
                // Hit non whitespace character on this line
                currentLineHasContent = true;
                currentLineIndentation = j;
                break;
            }
        }
        // Ignore empty or only whitespace lines
        if (!currentLineHasContent) {
            continue;
        }
        if (currentLineTabsCount > 0) {
            linesIndentedWithTabsCount++;
        }
        else if (currentLineSpacesCount > 1) {
            linesIndentedWithSpacesCount++;
        }
        spacesDiff(previousLineText, previousLineIndentation, currentLineText, currentLineIndentation, tmp);
        if (tmp.looksLikeAlignment) {
            // if defaultInsertSpaces === true && the spaces count == tabSize, we may want to count it as valid indentation
            //
            // - item1
            //   - item2
            //
            // otherwise skip this line entirely
            //
            // const a = 1,
            //       b = 2;
            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;
    // Guess tabSize only if inserting spaces...
    if (insertSpaces) {
        let tabSizeScore = (insertSpaces ? 0 : 0.1 * linesCount);
        // console.log("score threshold: " + tabSizeScore);
        ALLOWED_TAB_SIZE_GUESSES.forEach((possibleTabSize) => {
            const possibleTabSizeScore = spacesDiffCount[possibleTabSize];
            if (possibleTabSizeScore > tabSizeScore) {
                tabSizeScore = possibleTabSizeScore;
                tabSize = possibleTabSize;
            }
        });
        // Let a tabSize of 2 win even if it is not the maximum
        // (only in case 4 was guessed)
        if (tabSize === 4 && spacesDiffCount[4] > 0 && spacesDiffCount[2] > 0 && spacesDiffCount[2] >= spacesDiffCount[4] / 2) {
            tabSize = 2;
        }
    }
    // console.log('--------------------------');
    // console.log('linesIndentedWithTabsCount: ' + linesIndentedWithTabsCount + ', linesIndentedWithSpacesCount: ' + linesIndentedWithSpacesCount);
    // console.log('spacesDiffCount: ' + spacesDiffCount);
    // console.log('tabSize: ' + tabSize + ', tabSizeScore: ' + tabSizeScore);
    return {
        insertSpaces: insertSpaces,
        tabSize: tabSize
    };
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/intervalTree.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
function getNodeColor(node) {
    return ((node.metadata & 1 /* Constants.ColorMask */) >>> 0 /* Constants.ColorOffset */);
}
function setNodeColor(node, color) {
    node.metadata = ((node.metadata & 254 /* Constants.ColorMaskInverse */) | (color << 0 /* Constants.ColorOffset */));
}
function getNodeIsVisited(node) {
    return ((node.metadata & 2 /* Constants.IsVisitedMask */) >>> 1 /* Constants.IsVisitedOffset */) === 1;
}
function setNodeIsVisited(node, value) {
    node.metadata = ((node.metadata & 253 /* Constants.IsVisitedMaskInverse */) | ((value ? 1 : 0) << 1 /* Constants.IsVisitedOffset */));
}
function getNodeIsForValidation(node) {
    return ((node.metadata & 4 /* Constants.IsForValidationMask */) >>> 2 /* Constants.IsForValidationOffset */) === 1;
}
function setNodeIsForValidation(node, value) {
    node.metadata = ((node.metadata & 251 /* Constants.IsForValidationMaskInverse */) | ((value ? 1 : 0) << 2 /* Constants.IsForValidationOffset */));
}
function getNodeStickiness(node) {
    return ((node.metadata & 24 /* Constants.StickinessMask */) >>> 3 /* Constants.StickinessOffset */);
}
function _setNodeStickiness(node, stickiness) {
    node.metadata = ((node.metadata & 231 /* Constants.StickinessMaskInverse */) | (stickiness << 3 /* Constants.StickinessOffset */));
}
function getCollapseOnReplaceEdit(node) {
    return ((node.metadata & 32 /* Constants.CollapseOnReplaceEditMask */) >>> 5 /* Constants.CollapseOnReplaceEditOffset */) === 1;
}
function setCollapseOnReplaceEdit(node, value) {
    node.metadata = ((node.metadata & 223 /* Constants.CollapseOnReplaceEditMaskInverse */) | ((value ? 1 : 0) << 5 /* Constants.CollapseOnReplaceEditOffset */));
}
class IntervalNode {
    constructor(id, 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;
        // FORCE_OVERFLOWING_TEST: this.delta = start;
        this.delta = 0;
        this.maxEnd = end;
        this.id = id;
        this.ownerId = 0;
        this.options = null;
        setNodeIsForValidation(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(options) {
        this.options = options;
        const className = this.options.className;
        setNodeIsForValidation(this, (className === "squiggly-error" /* ClassName.EditorErrorDecoration */
            || className === "squiggly-warning" /* ClassName.EditorWarningDecoration */
            || className === "squiggly-info" /* ClassName.EditorInfoDecoration */));
        _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;
    }
}
const SENTINEL = new IntervalNode(null, 0, 0);
SENTINEL.parent = SENTINEL;
SENTINEL.left = SENTINEL;
SENTINEL.right = SENTINEL;
setNodeColor(SENTINEL, 0 /* NodeColor.Black */);
class IntervalTree {
    constructor() {
        this.root = SENTINEL;
        this.requestNormalizeDelta = false;
    }
    intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId) {
        if (this.root === SENTINEL) {
            return [];
        }
        return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, cachedVersionId);
    }
    search(filterOwnerId, filterOutValidation, cachedVersionId) {
        if (this.root === SENTINEL) {
            return [];
        }
        return search(this, filterOwnerId, filterOutValidation, cachedVersionId);
    }
    /**
     * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
     */
    collectNodesFromOwner(ownerId) {
        return collectNodesFromOwner(this, ownerId);
    }
    /**
     * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
     */
    collectNodesPostOrder() {
        return collectNodesPostOrder(this);
    }
    insert(node) {
        rbTreeInsert(this, node);
        this._normalizeDeltaIfNecessary();
    }
    delete(node) {
        rbTreeDelete(this, node);
        this._normalizeDeltaIfNecessary();
    }
    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) {
        // Our strategy is to remove all directly impacted nodes, and then add them back to the tree.
        // (1) collect all nodes that are intersecting this edit as nodes of interest
        const nodesOfInterest = searchForEditing(this, offset, offset + length);
        // (2) remove all nodes that are intersecting this edit
        for (let i = 0, len = nodesOfInterest.length; i < len; i++) {
            const node = nodesOfInterest[i];
            rbTreeDelete(this, node);
        }
        this._normalizeDeltaIfNecessary();
        // (3) edit all tree nodes except the nodes of interest
        noOverlapReplace(this, offset, offset + length, textLength);
        this._normalizeDeltaIfNecessary();
        // (4) edit the nodes of interest and insert them back in the tree
        for (let i = 0, len = nodesOfInterest.length; i < len; i++) {
            const node = nodesOfInterest[i];
            node.start = node.cachedAbsoluteStart;
            node.end = node.cachedAbsoluteEnd;
            nodeAcceptEdit(node, offset, (offset + length), textLength, forceMoveMarkers);
            node.maxEnd = node.end;
            rbTreeInsert(this, node);
        }
        this._normalizeDeltaIfNecessary();
    }
    _normalizeDeltaIfNecessary() {
        if (!this.requestNormalizeDelta) {
            return;
        }
        this.requestNormalizeDelta = false;
        normalizeDelta(this);
    }
}
//#region Delta Normalization
function normalizeDelta(T) {
    let node = T.root;
    let delta = 0;
    while (node !== SENTINEL) {
        if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {
            // go left
            node = node.left;
            continue;
        }
        if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
            // go right
            delta += node.delta;
            node = node.right;
            continue;
        }
        // handle current node
        node.start = delta + node.start;
        node.end = delta + node.end;
        node.delta = 0;
        recomputeMaxEnd(node);
        setNodeIsVisited(node, true);
        // going up from this node
        setNodeIsVisited(node.left, false);
        setNodeIsVisited(node.right, false);
        if (node === node.parent.right) {
            delta -= node.parent.delta;
        }
        node = node.parent;
    }
    setNodeIsVisited(T.root, false);
}
function adjustMarkerBeforeColumn(markerOffset, markerStickToPreviousCharacter, checkOffset, moveSemantics) {
    if (markerOffset < checkOffset) {
        return true;
    }
    if (markerOffset > checkOffset) {
        return false;
    }
    if (moveSemantics === 1 /* MarkerMoveSemantics.ForceMove */) {
        return false;
    }
    if (moveSemantics === 2 /* MarkerMoveSemantics.ForceStay */) {
        return true;
    }
    return markerStickToPreviousCharacter;
}
/**
 * This is a lot more complicated than strictly necessary to maintain the same behaviour
 * as when decorations were implemented using two markers.
 */
function nodeAcceptEdit(node, start, end, textLength, forceMoveMarkers) {
    const nodeStickiness = getNodeStickiness(node);
    const startStickToPreviousCharacter = (nodeStickiness === 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
        || nodeStickiness === 2 /* TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */);
    const endStickToPreviousCharacter = (nodeStickiness === 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
        || nodeStickiness === 2 /* TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */);
    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)) {
        // This edit encompasses the entire decoration range
        // and the decoration has asked to become collapsed
        node.start = start;
        startDone = true;
        node.end = start;
        endDone = true;
    }
    {
        const moveSemantics = forceMoveMarkers ? 1 /* MarkerMoveSemantics.ForceMove */ : (deletingCnt > 0 ? 2 /* MarkerMoveSemantics.ForceStay */ : 0 /* MarkerMoveSemantics.MarkerDefined */);
        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 /* MarkerMoveSemantics.ForceStay */ : 0 /* MarkerMoveSemantics.MarkerDefined */);
        if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start + commonLength, moveSemantics)) {
            startDone = true;
        }
        if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start + commonLength, moveSemantics)) {
            endDone = true;
        }
    }
    {
        const moveSemantics = forceMoveMarkers ? 1 /* MarkerMoveSemantics.ForceMove */ : 0 /* MarkerMoveSemantics.MarkerDefined */;
        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;
        }
    }
    // Finish
    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) {
    // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
    // Now, it is known that two intervals A and B overlap only when both
    // A.low <= B.high and A.high >= B.low. When searching the trees for
    // nodes overlapping with a given interval, you can immediately skip:
    //  a) all nodes to the right of nodes whose low value is past the end of the given interval.
    //  b) all nodes that have their maximum 'high' value below the start of the given interval.
    let node = T.root;
    let delta = 0;
    let nodeMaxEnd = 0;
    let nodeStart = 0;
    let nodeEnd = 0;
    const result = [];
    let resultLen = 0;
    while (node !== SENTINEL) {
        if (getNodeIsVisited(node)) {
            // going up from this 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)) {
            // first time seeing this node
            nodeMaxEnd = delta + node.maxEnd;
            if (nodeMaxEnd < start) {
                // cover case b) from above
                // there is no need to search this node or its children
                setNodeIsVisited(node, true);
                continue;
            }
            if (node.left !== SENTINEL) {
                // go left
                node = node.left;
                continue;
            }
        }
        // handle current node
        nodeStart = delta + node.start;
        if (nodeStart > end) {
            // cover case a) from above
            // there is no need to search this node or its right subtree
            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 !== SENTINEL && !getNodeIsVisited(node.right)) {
            // go right
            delta += node.delta;
            node = node.right;
            continue;
        }
    }
    setNodeIsVisited(T.root, false);
    return result;
}
function noOverlapReplace(T, start, end, textLength) {
    // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
    // Now, it is known that two intervals A and B overlap only when both
    // A.low <= B.high and A.high >= B.low. When searching the trees for
    // nodes overlapping with a given interval, you can immediately skip:
    //  a) all nodes to the right of nodes whose low value is past the end of the given interval.
    //  b) all nodes that have their maximum 'high' value below the start of the given interval.
    let node = T.root;
    let delta = 0;
    let nodeMaxEnd = 0;
    let nodeStart = 0;
    const editDelta = (textLength - (end - start));
    while (node !== SENTINEL) {
        if (getNodeIsVisited(node)) {
            // going up from this node
            setNodeIsVisited(node.left, false);
            setNodeIsVisited(node.right, false);
            if (node === node.parent.right) {
                delta -= node.parent.delta;
            }
            recomputeMaxEnd(node);
            node = node.parent;
            continue;
        }
        if (!getNodeIsVisited(node.left)) {
            // first time seeing this node
            nodeMaxEnd = delta + node.maxEnd;
            if (nodeMaxEnd < start) {
                // cover case b) from above
                // there is no need to search this node or its children
                setNodeIsVisited(node, true);
                continue;
            }
            if (node.left !== SENTINEL) {
                // go left
                node = node.left;
                continue;
            }
        }
        // handle current node
        nodeStart = delta + node.start;
        if (nodeStart > end) {
            node.start += editDelta;
            node.end += editDelta;
            node.delta += editDelta;
            if (node.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || node.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
                T.requestNormalizeDelta = true;
            }
            // cover case a) from above
            // there is no need to search this node or its right subtree
            setNodeIsVisited(node, true);
            continue;
        }
        setNodeIsVisited(node, true);
        if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
            // go right
            delta += node.delta;
            node = node.right;
            continue;
        }
    }
    setNodeIsVisited(T.root, false);
}
//#endregion
//#region Searching
function collectNodesFromOwner(T, ownerId) {
    let node = T.root;
    const result = [];
    let resultLen = 0;
    while (node !== SENTINEL) {
        if (getNodeIsVisited(node)) {
            // going up from this node
            setNodeIsVisited(node.left, false);
            setNodeIsVisited(node.right, false);
            node = node.parent;
            continue;
        }
        if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {
            // go left
            node = node.left;
            continue;
        }
        // handle current node
        if (node.ownerId === ownerId) {
            result[resultLen++] = node;
        }
        setNodeIsVisited(node, true);
        if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
            // go 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 !== SENTINEL) {
        if (getNodeIsVisited(node)) {
            // going up from this node
            setNodeIsVisited(node.left, false);
            setNodeIsVisited(node.right, false);
            node = node.parent;
            continue;
        }
        if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {
            // go left
            node = node.left;
            continue;
        }
        if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
            // go right
            node = node.right;
            continue;
        }
        // handle current node
        result[resultLen++] = node;
        setNodeIsVisited(node, true);
    }
    setNodeIsVisited(T.root, false);
    return result;
}
function search(T, filterOwnerId, filterOutValidation, cachedVersionId) {
    let node = T.root;
    let delta = 0;
    let nodeStart = 0;
    let nodeEnd = 0;
    const result = [];
    let resultLen = 0;
    while (node !== SENTINEL) {
        if (getNodeIsVisited(node)) {
            // going up from this 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 !== SENTINEL && !getNodeIsVisited(node.left)) {
            // go left
            node = node.left;
            continue;
        }
        // handle current node
        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 (include) {
            result[resultLen++] = node;
        }
        setNodeIsVisited(node, true);
        if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
            // go right
            delta += node.delta;
            node = node.right;
            continue;
        }
    }
    setNodeIsVisited(T.root, false);
    return result;
}
function intervalSearch(T, intervalStart, intervalEnd, filterOwnerId, filterOutValidation, cachedVersionId) {
    // https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
    // Now, it is known that two intervals A and B overlap only when both
    // A.low <= B.high and A.high >= B.low. When searching the trees for
    // nodes overlapping with a given interval, you can immediately skip:
    //  a) all nodes to the right of nodes whose low value is past the end of the given interval.
    //  b) all nodes that have their maximum 'high' value below the start of the given interval.
    let node = T.root;
    let delta = 0;
    let nodeMaxEnd = 0;
    let nodeStart = 0;
    let nodeEnd = 0;
    const result = [];
    let resultLen = 0;
    while (node !== SENTINEL) {
        if (getNodeIsVisited(node)) {
            // going up from this 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)) {
            // first time seeing this node
            nodeMaxEnd = delta + node.maxEnd;
            if (nodeMaxEnd < intervalStart) {
                // cover case b) from above
                // there is no need to search this node or its children
                setNodeIsVisited(node, true);
                continue;
            }
            if (node.left !== SENTINEL) {
                // go left
                node = node.left;
                continue;
            }
        }
        // handle current node
        nodeStart = delta + node.start;
        if (nodeStart > intervalEnd) {
            // cover case a) from above
            // there is no need to search this node or its right subtree
            setNodeIsVisited(node, true);
            continue;
        }
        nodeEnd = delta + node.end;
        if (nodeEnd >= intervalStart) {
            // There is overlap
            node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
            let include = true;
            if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
                include = false;
            }
            if (filterOutValidation && getNodeIsForValidation(node)) {
                include = false;
            }
            if (include) {
                result[resultLen++] = node;
            }
        }
        setNodeIsVisited(node, true);
        if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
            // go right
            delta += node.delta;
            node = node.right;
            continue;
        }
    }
    setNodeIsVisited(T.root, false);
    return result;
}
//#endregion
//#region Insertion
function rbTreeInsert(T, newNode) {
    if (T.root === SENTINEL) {
        newNode.parent = SENTINEL;
        newNode.left = SENTINEL;
        newNode.right = SENTINEL;
        setNodeColor(newNode, 0 /* NodeColor.Black */);
        T.root = newNode;
        return T.root;
    }
    treeInsert(T, newNode);
    recomputeMaxEndWalkToRoot(newNode.parent);
    // repair tree
    let x = newNode;
    while (x !== T.root && getNodeColor(x.parent) === 1 /* NodeColor.Red */) {
        if (x.parent === x.parent.parent.left) {
            const y = x.parent.parent.right;
            if (getNodeColor(y) === 1 /* NodeColor.Red */) {
                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;
                    leftRotate(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 (getNodeColor(y) === 1 /* NodeColor.Red */) {
                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 */);
                leftRotate(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 cmp = intervalCompare(zAbsoluteStart, zAbsoluteEnd, x.start + delta, x.end + delta);
        if (cmp < 0) {
            // this node should be inserted to the left
            // => it is not affected by the node's delta
            if (x.left === SENTINEL) {
                z.start -= delta;
                z.end -= delta;
                z.maxEnd -= delta;
                x.left = z;
                break;
            }
            else {
                x = x.left;
            }
        }
        else {
            // this node should be inserted to the right
            // => it is not affected by the node's delta
            if (x.right === SENTINEL) {
                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 = SENTINEL;
    z.right = SENTINEL;
    setNodeColor(z, 1 /* NodeColor.Red */);
}
//#endregion
//#region Deletion
function rbTreeDelete(T, z) {
    let x;
    let y;
    // RB-DELETE except we don't swap z and y in case c)
    // i.e. we always delete what's pointed at by z.
    if (z.left === SENTINEL) {
        x = z.right;
        y = z;
        // x's delta is no longer influenced by z's delta
        x.delta += z.delta;
        if (x.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || x.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
            T.requestNormalizeDelta = true;
        }
        x.start += z.delta;
        x.end += z.delta;
    }
    else if (z.right === SENTINEL) {
        x = z.left;
        y = z;
    }
    else {
        y = leftest(z.right);
        x = y.right;
        // y's delta is no longer influenced by z's delta,
        // but we don't want to walk the entire right-hand-side subtree of x.
        // we therefore maintain z's delta in y, and adjust only x
        x.start += y.delta;
        x.end += y.delta;
        x.delta += y.delta;
        if (x.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || x.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
            T.requestNormalizeDelta = true;
        }
        y.start += z.delta;
        y.end += z.delta;
        y.delta = z.delta;
        if (y.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || y.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
            T.requestNormalizeDelta = true;
        }
    }
    if (y === T.root) {
        T.root = x;
        setNodeColor(x, 0 /* NodeColor.Black */);
        z.detach();
        resetSentinel();
        recomputeMaxEnd(x);
        T.root.parent = SENTINEL;
        return;
    }
    const yWasRed = (getNodeColor(y) === 1 /* NodeColor.Red */);
    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, getNodeColor(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 !== SENTINEL) {
            y.left.parent = y;
        }
        if (y.right !== SENTINEL) {
            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);
    }
    // RB-DELETE-FIXUP
    let w;
    while (x !== T.root && getNodeColor(x) === 0 /* NodeColor.Black */) {
        if (x === x.parent.left) {
            w = x.parent.right;
            if (getNodeColor(w) === 1 /* NodeColor.Red */) {
                setNodeColor(w, 0 /* NodeColor.Black */);
                setNodeColor(x.parent, 1 /* NodeColor.Red */);
                leftRotate(T, x.parent);
                w = x.parent.right;
            }
            if (getNodeColor(w.left) === 0 /* NodeColor.Black */ && getNodeColor(w.right) === 0 /* NodeColor.Black */) {
                setNodeColor(w, 1 /* NodeColor.Red */);
                x = x.parent;
            }
            else {
                if (getNodeColor(w.right) === 0 /* NodeColor.Black */) {
                    setNodeColor(w.left, 0 /* NodeColor.Black */);
                    setNodeColor(w, 1 /* NodeColor.Red */);
                    rightRotate(T, w);
                    w = x.parent.right;
                }
                setNodeColor(w, getNodeColor(x.parent));
                setNodeColor(x.parent, 0 /* NodeColor.Black */);
                setNodeColor(w.right, 0 /* NodeColor.Black */);
                leftRotate(T, x.parent);
                x = T.root;
            }
        }
        else {
            w = x.parent.left;
            if (getNodeColor(w) === 1 /* NodeColor.Red */) {
                setNodeColor(w, 0 /* NodeColor.Black */);
                setNodeColor(x.parent, 1 /* NodeColor.Red */);
                rightRotate(T, x.parent);
                w = x.parent.left;
            }
            if (getNodeColor(w.left) === 0 /* NodeColor.Black */ && getNodeColor(w.right) === 0 /* NodeColor.Black */) {
                setNodeColor(w, 1 /* NodeColor.Red */);
                x = x.parent;
            }
            else {
                if (getNodeColor(w.left) === 0 /* NodeColor.Black */) {
                    setNodeColor(w.right, 0 /* NodeColor.Black */);
                    setNodeColor(w, 1 /* NodeColor.Red */);
                    leftRotate(T, w);
                    w = x.parent.left;
                }
                setNodeColor(w, getNodeColor(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 !== SENTINEL) {
        node = node.left;
    }
    return node;
}
function resetSentinel() {
    SENTINEL.parent = SENTINEL;
    SENTINEL.delta = 0; // optional
    SENTINEL.start = 0; // optional
    SENTINEL.end = 0; // optional
}
//#endregion
//#region Rotations
function leftRotate(T, x) {
    const y = x.right; // set y.
    y.delta += x.delta; // y's delta is no longer influenced by x's delta
    if (y.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || y.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
        T.requestNormalizeDelta = true;
    }
    y.start += x.delta;
    y.end += x.delta;
    x.right = y.left; // turn y's left subtree into x's right subtree.
    if (y.left !== SENTINEL) {
        y.left.parent = x;
    }
    y.parent = x.parent; // link x's parent to y.
    if (x.parent === SENTINEL) {
        T.root = y;
    }
    else if (x === x.parent.left) {
        x.parent.left = y;
    }
    else {
        x.parent.right = y;
    }
    y.left = x; // put x on y's left.
    x.parent = y;
    recomputeMaxEnd(x);
    recomputeMaxEnd(y);
}
function rightRotate(T, y) {
    const x = y.left;
    y.delta -= x.delta;
    if (y.delta < -1073741824 /* Constants.MIN_SAFE_DELTA */ || y.delta > 1073741824 /* Constants.MAX_SAFE_DELTA */) {
        T.requestNormalizeDelta = true;
    }
    y.start -= x.delta;
    y.end -= x.delta;
    y.left = x.right;
    if (x.right !== SENTINEL) {
        x.right.parent = y;
    }
    x.parent = y.parent;
    if (y.parent === SENTINEL) {
        T.root = x;
    }
    else if (y === y.parent.right) {
        y.parent.right = x;
    }
    else {
        y.parent.left = x;
    }
    x.right = y;
    y.parent = x;
    recomputeMaxEnd(y);
    recomputeMaxEnd(x);
}
//#endregion
//#region max end computation
function computeMaxEnd(node) {
    let maxEnd = node.end;
    if (node.left !== SENTINEL) {
        const leftMaxEnd = node.left.maxEnd;
        if (leftMaxEnd > maxEnd) {
            maxEnd = leftMaxEnd;
        }
    }
    if (node.right !== SENTINEL) {
        const rightMaxEnd = node.right.maxEnd + node.delta;
        if (rightMaxEnd > maxEnd) {
            maxEnd = rightMaxEnd;
        }
    }
    return maxEnd;
}
function recomputeMaxEnd(node) {
    node.maxEnd = computeMaxEnd(node);
}
function recomputeMaxEndWalkToRoot(node) {
    while (node !== SENTINEL) {
        const maxEnd = computeMaxEnd(node);
        if (node.maxEnd === maxEnd) {
            // no need to go further
            return;
        }
        node.maxEnd = maxEnd;
        node = node.parent;
    }
}
//#endregion
//#region utils
function intervalCompare(aStart, aEnd, bStart, bEnd) {
    if (aStart === bStart) {
        return aEnd - bEnd;
    }
    return aStart - bStart;
}
//#endregion

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class TreeNode {
    constructor(piece, color) {
        this.piece = piece;
        this.color = color;
        this.size_left = 0;
        this.lf_left = 0;
        this.parent = this;
        this.left = this;
        this.right = this;
    }
    next() {
        if (this.right !== rbTreeBase_SENTINEL) {
            return rbTreeBase_leftest(this.right);
        }
        let node = this;
        while (node.parent !== rbTreeBase_SENTINEL) {
            if (node.parent.left === node) {
                break;
            }
            node = node.parent;
        }
        if (node.parent === rbTreeBase_SENTINEL) {
            return rbTreeBase_SENTINEL;
        }
        else {
            return node.parent;
        }
    }
    prev() {
        if (this.left !== rbTreeBase_SENTINEL) {
            return righttest(this.left);
        }
        let node = this;
        while (node.parent !== rbTreeBase_SENTINEL) {
            if (node.parent.right === node) {
                break;
            }
            node = node.parent;
        }
        if (node.parent === rbTreeBase_SENTINEL) {
            return rbTreeBase_SENTINEL;
        }
        else {
            return node.parent;
        }
    }
    detach() {
        this.parent = null;
        this.left = null;
        this.right = null;
    }
}
const rbTreeBase_SENTINEL = new TreeNode(null, 0 /* NodeColor.Black */);
rbTreeBase_SENTINEL.parent = rbTreeBase_SENTINEL;
rbTreeBase_SENTINEL.left = rbTreeBase_SENTINEL;
rbTreeBase_SENTINEL.right = rbTreeBase_SENTINEL;
rbTreeBase_SENTINEL.color = 0 /* NodeColor.Black */;
function rbTreeBase_leftest(node) {
    while (node.left !== rbTreeBase_SENTINEL) {
        node = node.left;
    }
    return node;
}
function righttest(node) {
    while (node.right !== rbTreeBase_SENTINEL) {
        node = node.right;
    }
    return node;
}
function calculateSize(node) {
    if (node === rbTreeBase_SENTINEL) {
        return 0;
    }
    return node.size_left + node.piece.length + calculateSize(node.right);
}
function calculateLF(node) {
    if (node === rbTreeBase_SENTINEL) {
        return 0;
    }
    return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right);
}
function rbTreeBase_resetSentinel() {
    rbTreeBase_SENTINEL.parent = rbTreeBase_SENTINEL;
}
function rbTreeBase_leftRotate(tree, x) {
    const y = x.right;
    // fix size_left
    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 !== rbTreeBase_SENTINEL) {
        y.left.parent = x;
    }
    y.parent = x.parent;
    if (x.parent === rbTreeBase_SENTINEL) {
        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 rbTreeBase_rightRotate(tree, y) {
    const x = y.left;
    y.left = x.right;
    if (x.right !== rbTreeBase_SENTINEL) {
        x.right.parent = y;
    }
    x.parent = y.parent;
    // fix size_left
    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 === rbTreeBase_SENTINEL) {
        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 rbDelete(tree, z) {
    let x;
    let y;
    if (z.left === rbTreeBase_SENTINEL) {
        y = z;
        x = y.right;
    }
    else if (z.right === rbTreeBase_SENTINEL) {
        y = z;
        x = y.left;
    }
    else {
        y = rbTreeBase_leftest(z.right);
        x = y.right;
    }
    if (y === tree.root) {
        tree.root = x;
        // if x is null, we are removing the only node
        x.color = 0 /* NodeColor.Black */;
        z.detach();
        rbTreeBase_resetSentinel();
        tree.root.parent = rbTreeBase_SENTINEL;
        return;
    }
    const yWasRed = (y.color === 1 /* NodeColor.Red */);
    if (y === y.parent.left) {
        y.parent.left = x;
    }
    else {
        y.parent.right = x;
    }
    if (y === z) {
        x.parent = y.parent;
        recomputeTreeMetadata(tree, x);
    }
    else {
        if (y.parent === z) {
            x.parent = y;
        }
        else {
            x.parent = y.parent;
        }
        // as we make changes to x's hierarchy, update size_left of subtree first
        recomputeTreeMetadata(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 !== rbTreeBase_SENTINEL) {
            y.left.parent = y;
        }
        if (y.right !== rbTreeBase_SENTINEL) {
            y.right.parent = y;
        }
        // update metadata
        // we replace z with y, so in this sub tree, the length change is z.item.length
        y.size_left = z.size_left;
        y.lf_left = z.lf_left;
        recomputeTreeMetadata(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;
            updateTreeMetadata(tree, x.parent, delta, lf_delta);
        }
    }
    recomputeTreeMetadata(tree, x.parent);
    if (yWasRed) {
        rbTreeBase_resetSentinel();
        return;
    }
    // RB-DELETE-FIXUP
    let w;
    while (x !== tree.root && x.color === 0 /* NodeColor.Black */) {
        if (x === x.parent.left) {
            w = x.parent.right;
            if (w.color === 1 /* NodeColor.Red */) {
                w.color = 0 /* NodeColor.Black */;
                x.parent.color = 1 /* NodeColor.Red */;
                rbTreeBase_leftRotate(tree, x.parent);
                w = x.parent.right;
            }
            if (w.left.color === 0 /* NodeColor.Black */ && w.right.color === 0 /* NodeColor.Black */) {
                w.color = 1 /* NodeColor.Red */;
                x = x.parent;
            }
            else {
                if (w.right.color === 0 /* NodeColor.Black */) {
                    w.left.color = 0 /* NodeColor.Black */;
                    w.color = 1 /* NodeColor.Red */;
                    rbTreeBase_rightRotate(tree, w);
                    w = x.parent.right;
                }
                w.color = x.parent.color;
                x.parent.color = 0 /* NodeColor.Black */;
                w.right.color = 0 /* NodeColor.Black */;
                rbTreeBase_leftRotate(tree, x.parent);
                x = tree.root;
            }
        }
        else {
            w = x.parent.left;
            if (w.color === 1 /* NodeColor.Red */) {
                w.color = 0 /* NodeColor.Black */;
                x.parent.color = 1 /* NodeColor.Red */;
                rbTreeBase_rightRotate(tree, x.parent);
                w = x.parent.left;
            }
            if (w.left.color === 0 /* NodeColor.Black */ && w.right.color === 0 /* NodeColor.Black */) {
                w.color = 1 /* NodeColor.Red */;
                x = x.parent;
            }
            else {
                if (w.left.color === 0 /* NodeColor.Black */) {
                    w.right.color = 0 /* NodeColor.Black */;
                    w.color = 1 /* NodeColor.Red */;
                    rbTreeBase_leftRotate(tree, w);
                    w = x.parent.left;
                }
                w.color = x.parent.color;
                x.parent.color = 0 /* NodeColor.Black */;
                w.left.color = 0 /* NodeColor.Black */;
                rbTreeBase_rightRotate(tree, x.parent);
                x = tree.root;
            }
        }
    }
    x.color = 0 /* NodeColor.Black */;
    rbTreeBase_resetSentinel();
}
function fixInsert(tree, x) {
    recomputeTreeMetadata(tree, x);
    while (x !== tree.root && x.parent.color === 1 /* NodeColor.Red */) {
        if (x.parent === x.parent.parent.left) {
            const y = x.parent.parent.right;
            if (y.color === 1 /* NodeColor.Red */) {
                x.parent.color = 0 /* NodeColor.Black */;
                y.color = 0 /* NodeColor.Black */;
                x.parent.parent.color = 1 /* NodeColor.Red */;
                x = x.parent.parent;
            }
            else {
                if (x === x.parent.right) {
                    x = x.parent;
                    rbTreeBase_leftRotate(tree, x);
                }
                x.parent.color = 0 /* NodeColor.Black */;
                x.parent.parent.color = 1 /* NodeColor.Red */;
                rbTreeBase_rightRotate(tree, x.parent.parent);
            }
        }
        else {
            const y = x.parent.parent.left;
            if (y.color === 1 /* NodeColor.Red */) {
                x.parent.color = 0 /* NodeColor.Black */;
                y.color = 0 /* NodeColor.Black */;
                x.parent.parent.color = 1 /* NodeColor.Red */;
                x = x.parent.parent;
            }
            else {
                if (x === x.parent.left) {
                    x = x.parent;
                    rbTreeBase_rightRotate(tree, x);
                }
                x.parent.color = 0 /* NodeColor.Black */;
                x.parent.parent.color = 1 /* NodeColor.Red */;
                rbTreeBase_leftRotate(tree, x.parent.parent);
            }
        }
    }
    tree.root.color = 0 /* NodeColor.Black */;
}
function updateTreeMetadata(tree, x, delta, lineFeedCntDelta) {
    // node length change or line feed count change
    while (x !== tree.root && x !== rbTreeBase_SENTINEL) {
        if (x.parent.left === x) {
            x.parent.size_left += delta;
            x.parent.lf_left += lineFeedCntDelta;
        }
        x = x.parent;
    }
}
function recomputeTreeMetadata(tree, x) {
    let delta = 0;
    let lf_delta = 0;
    if (x === tree.root) {
        return;
    }
    // go upwards till the node whose left subtree is changed.
    while (x !== tree.root && x === x.parent.right) {
        x = x.parent;
    }
    if (x === tree.root) {
        // well, it means we add a node to the end (inorder)
        return;
    }
    // x is the node whose right subtree is changed.
    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;
    // go upwards till root. O(logN)
    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;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/uint.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
function toUint8(v) {
    if (v < 0) {
        return 0;
    }
    if (v > 255 /* Constants.MAX_UINT_8 */) {
        return 255 /* Constants.MAX_UINT_8 */;
    }
    return v | 0;
}
function toUint32(v) {
    if (v < 0) {
        return 0;
    }
    if (v > 4294967295 /* Constants.MAX_UINT_32 */) {
        return 4294967295 /* Constants.MAX_UINT_32 */;
    }
    return v | 0;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/characterClassifier.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/**
 * A fast character classifier that uses a compact array for ASCII values.
 */
class CharacterClassifier {
    constructor(_defaultValue) {
        const defaultValue = toUint8(_defaultValue);
        this._defaultValue = defaultValue;
        this._asciiMap = CharacterClassifier._createAsciiMap(defaultValue);
        this._map = new Map();
    }
    static _createAsciiMap(defaultValue) {
        const asciiMap = new Uint8Array(256);
        for (let i = 0; i < 256; i++) {
            asciiMap[i] = defaultValue;
        }
        return asciiMap;
    }
    set(charCode, _value) {
        const value = toUint8(_value);
        if (charCode >= 0 && charCode < 256) {
            this._asciiMap[charCode] = value;
        }
        else {
            this._map.set(charCode, value);
        }
    }
    get(charCode) {
        if (charCode >= 0 && charCode < 256) {
            return this._asciiMap[charCode];
        }
        else {
            return (this._map.get(charCode) || this._defaultValue);
        }
    }
}
class CharacterSet {
    constructor() {
        this._actual = new CharacterClassifier(0 /* Boolean.False */);
    }
    add(charCode) {
        this._actual.set(charCode, 1 /* Boolean.True */);
    }
    has(charCode) {
        return (this._actual.get(charCode) === 1 /* Boolean.True */);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/wordCharacterClassifier.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class WordCharacterClassifier extends CharacterClassifier {
    constructor(wordSeparators) {
        super(0 /* WordCharacterClass.Regular */);
        for (let i = 0, len = wordSeparators.length; i < len; i++) {
            this.set(wordSeparators.charCodeAt(i), 2 /* WordCharacterClass.WordSeparator */);
        }
        this.set(32 /* CharCode.Space */, 1 /* WordCharacterClass.Whitespace */);
        this.set(9 /* CharCode.Tab */, 1 /* WordCharacterClass.Whitespace */);
    }
}
function wordCharacterClassifier_once(computeFn) {
    const cache = {}; // TODO@Alex unbounded cache
    return (input) => {
        if (!cache.hasOwnProperty(input)) {
            cache[input] = computeFn(input);
        }
        return cache[input];
    };
}
const getMapForWordSeparators = wordCharacterClassifier_once((input) => new WordCharacterClassifier(input));

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/textModelSearch.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





const LIMIT_FIND_COUNT = 999;
class SearchParams {
    constructor(searchString, isRegex, matchCase, wordSeparators) {
        this.searchString = searchString;
        this.isRegex = isRegex;
        this.matchCase = matchCase;
        this.wordSeparators = wordSeparators;
    }
    parseSearchRequest() {
        if (this.searchString === '') {
            return null;
        }
        // Try to create a RegExp out of the params
        let multiline;
        if (this.isRegex) {
            multiline = isMultilineRegexSource(this.searchString);
        }
        else {
            multiline = (this.searchString.indexOf('\n') >= 0);
        }
        let regex = null;
        try {
            regex = createRegExp(this.searchString, this.isRegex, {
                matchCase: this.matchCase,
                wholeWord: false,
                multiline: 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()) {
            // casing might make a difference
            canUseSimpleSearch = this.matchCase;
        }
        return new SearchData(regex, this.wordSeparators ? getMapForWordSeparators(this.wordSeparators) : null, canUseSimpleSearch ? this.searchString : null);
    }
}
function isMultilineRegexSource(searchString) {
    if (!searchString || searchString.length === 0) {
        return false;
    }
    for (let i = 0, len = searchString.length; i < len; i++) {
        const chCode = searchString.charCodeAt(i);
        if (chCode === 10 /* CharCode.LineFeed */) {
            return true;
        }
        if (chCode === 92 /* CharCode.Backslash */) {
            // move to next char
            i++;
            if (i >= len) {
                // string ends with a \
                break;
            }
            const nextChCode = searchString.charCodeAt(i);
            if (nextChCode === 110 /* CharCode.n */ || nextChCode === 114 /* CharCode.r */ || nextChCode === 87 /* CharCode.W */) {
                return true;
            }
        }
    }
    return false;
}
function createFindMatch(range, rawMatches, captureMatches) {
    if (!captureMatches) {
        return new FindMatch(range, null);
    }
    const matches = [];
    for (let i = 0, len = rawMatches.length; i < len; i++) {
        matches[i] = rawMatches[i];
    }
    return new FindMatch(range, matches);
}
class LineFeedCounter {
    constructor(text) {
        const lineFeedsOffsets = [];
        let lineFeedsOffsetsLen = 0;
        for (let i = 0, textLen = text.length; i < textLen; i++) {
            if (text.charCodeAt(i) === 10 /* CharCode.LineFeed */) {
                lineFeedsOffsets[lineFeedsOffsetsLen++] = i;
            }
        }
        this._lineFeedsOffsets = lineFeedsOffsets;
    }
    findLineFeedCountBeforeOffset(offset) {
        const lineFeedsOffsets = this._lineFeedsOffsets;
        let min = 0;
        let max = lineFeedsOffsets.length - 1;
        if (max === -1) {
            // no line feeds
            return 0;
        }
        if (offset <= lineFeedsOffsets[0]) {
            // before first line feed
            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) {
                    // bingo!
                    min = mid;
                    max = mid;
                }
                else {
                    min = mid + 1;
                }
            }
        }
        return min + 1;
    }
}
class TextModelSearch {
    static findMatches(model, searchParams, searchRange, captureMatches, limitResultCount) {
        const searchData = searchParams.parseSearchRequest();
        if (!searchData) {
            return [];
        }
        if (searchData.regex.multiline) {
            return this._doFindMatchesMultiline(model, searchRange, new Searcher(searchData.wordSeparators, searchData.regex), captureMatches, limitResultCount);
        }
        return this._doFindMatchesLineByLine(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 _getMultilineMatchRange(model, deltaOffset, text, lfCounter, matchIndex, match0) {
        let startOffset;
        let lineFeedCountBeforeMatch = 0;
        if (lfCounter) {
            lineFeedCountBeforeMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex);
            startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch /* add as many \r as there were \n */;
        }
        else {
            startOffset = deltaOffset + matchIndex;
        }
        let endOffset;
        if (lfCounter) {
            const lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length);
            const lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch;
            endOffset = startOffset + match0.length + lineFeedCountInMatch /* add as many \r as there were \n */;
        }
        else {
            endOffset = startOffset + match0.length;
        }
        const startPosition = model.getPositionAt(startOffset);
        const endPosition = model.getPositionAt(endOffset);
        return new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
    }
    static _doFindMatchesMultiline(model, searchRange, searcher, captureMatches, limitResultCount) {
        const deltaOffset = model.getOffsetAt(searchRange.getStartPosition());
        // We always execute multiline search over the lines joined with \n
        // This makes it that \n will match the EOL for both CRLF and LF models
        // We compensate for offset errors in `_getMultilineMatchRange`
        const text = model.getValueInRange(searchRange, 1 /* EndOfLinePreference.LF */);
        const lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null);
        const result = [];
        let counter = 0;
        let m;
        searcher.reset(0);
        while ((m = searcher.next(text))) {
            result[counter++] = createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m.index, m[0]), m, captureMatches);
            if (counter >= limitResultCount) {
                return result;
            }
        }
        return result;
    }
    static _doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount) {
        const result = [];
        let resultLen = 0;
        // Early case for a search range that starts & stops on the same line number
        if (searchRange.startLineNumber === searchRange.endLineNumber) {
            const text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1);
            resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
            return result;
        }
        // Collect results from first line
        const text = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1);
        resultLen = this._findMatchesInLine(searchData, text, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result, captureMatches, limitResultCount);
        // Collect results from middle lines
        for (let lineNumber = searchRange.startLineNumber + 1; lineNumber < searchRange.endLineNumber && resultLen < limitResultCount; lineNumber++) {
            resultLen = this._findMatchesInLine(searchData, model.getLineContent(lineNumber), lineNumber, 0, resultLen, result, captureMatches, limitResultCount);
        }
        // Collect results from last line
        if (resultLen < limitResultCount) {
            const text = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1);
            resultLen = this._findMatchesInLine(searchData, text, searchRange.endLineNumber, 0, resultLen, result, captureMatches, limitResultCount);
        }
        return result;
    }
    static _findMatchesInLine(searchData, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
        const wordSeparators = searchData.wordSeparators;
        if (!captureMatches && searchData.simpleSearch) {
            const searchString = searchData.simpleSearch;
            const searchStringLen = searchString.length;
            const textLength = text.length;
            let lastMatchIndex = -searchStringLen;
            while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
                if (!wordSeparators || isValidMatch(wordSeparators, text, textLength, lastMatchIndex, searchStringLen)) {
                    result[resultLen++] = new FindMatch(new Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
                    if (resultLen >= limitResultCount) {
                        return resultLen;
                    }
                }
            }
            return resultLen;
        }
        const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
        let m;
        // Reset regex to search from the beginning
        searcher.reset(0);
        do {
            m = searcher.next(text);
            if (m) {
                result[resultLen++] = createFindMatch(new Range(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 Searcher(searchData.wordSeparators, searchData.regex);
        if (searchData.regex.multiline) {
            return this._doFindNextMatchMultiline(model, searchStart, searcher, captureMatches);
        }
        return this._doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches);
    }
    static _doFindNextMatchMultiline(model, searchStart, searcher, captureMatches) {
        const searchTextStart = new Position(searchStart.lineNumber, 1);
        const deltaOffset = model.getOffsetAt(searchTextStart);
        const lineCount = model.getLineCount();
        // We always execute multiline search over the lines joined with \n
        // This makes it that \n will match the EOL for both CRLF and LF models
        // We compensate for offset errors in `_getMultilineMatchRange`
        const text = model.getValueInRange(new Range(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)), 1 /* EndOfLinePreference.LF */);
        const lfCounter = (model.getEOL() === '\r\n' ? new LineFeedCounter(text) : null);
        searcher.reset(searchStart.column - 1);
        const m = searcher.next(text);
        if (m) {
            return createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text, lfCounter, m.index, m[0]), m, captureMatches);
        }
        if (searchStart.lineNumber !== 1 || searchStart.column !== 1) {
            // Try again from the top
            return this._doFindNextMatchMultiline(model, new Position(1, 1), searcher, captureMatches);
        }
        return null;
    }
    static _doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches) {
        const lineCount = model.getLineCount();
        const startLineNumber = searchStart.lineNumber;
        // Look in first line
        const text = model.getLineContent(startLineNumber);
        const r = this._findFirstMatchInLine(searcher, text, startLineNumber, searchStart.column, captureMatches);
        if (r) {
            return r;
        }
        for (let i = 1; i <= lineCount; i++) {
            const lineIndex = (startLineNumber + i - 1) % lineCount;
            const text = model.getLineContent(lineIndex + 1);
            const r = this._findFirstMatchInLine(searcher, text, lineIndex + 1, 1, captureMatches);
            if (r) {
                return r;
            }
        }
        return null;
    }
    static _findFirstMatchInLine(searcher, text, lineNumber, fromColumn, captureMatches) {
        // Set regex to search from column
        searcher.reset(fromColumn - 1);
        const m = searcher.next(text);
        if (m) {
            return createFindMatch(new Range(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 Searcher(searchData.wordSeparators, searchData.regex);
        if (searchData.regex.multiline) {
            return this._doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches);
        }
        return this._doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches);
    }
    static _doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches) {
        const matches = this._doFindMatchesMultiline(model, new Range(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)) {
            // Try again with all content
            return this._doFindPreviousMatchMultiline(model, new Position(lineCount, model.getLineMaxColumn(lineCount)), searcher, captureMatches);
        }
        return null;
    }
    static _doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches) {
        const lineCount = model.getLineCount();
        const startLineNumber = searchStart.lineNumber;
        // Look in first line
        const text = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1);
        const r = this._findLastMatchInLine(searcher, text, startLineNumber, captureMatches);
        if (r) {
            return r;
        }
        for (let i = 1; i <= lineCount; i++) {
            const lineIndex = (lineCount + startLineNumber - i - 1) % lineCount;
            const text = model.getLineContent(lineIndex + 1);
            const r = this._findLastMatchInLine(searcher, text, lineIndex + 1, captureMatches);
            if (r) {
                return r;
            }
        }
        return null;
    }
    static _findLastMatchInLine(searcher, text, lineNumber, captureMatches) {
        let bestResult = null;
        let m;
        searcher.reset(0);
        while ((m = searcher.next(text))) {
            bestResult = createFindMatch(new Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);
        }
        return bestResult;
    }
}
function leftIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) {
    if (matchStartIndex === 0) {
        // Match starts at start of string
        return true;
    }
    const charBefore = text.charCodeAt(matchStartIndex - 1);
    if (wordSeparators.get(charBefore) !== 0 /* WordCharacterClass.Regular */) {
        // The character before the match is a word separator
        return true;
    }
    if (charBefore === 13 /* CharCode.CarriageReturn */ || charBefore === 10 /* CharCode.LineFeed */) {
        // The character before the match is line break or carriage return.
        return true;
    }
    if (matchLength > 0) {
        const firstCharInMatch = text.charCodeAt(matchStartIndex);
        if (wordSeparators.get(firstCharInMatch) !== 0 /* WordCharacterClass.Regular */) {
            // The first character inside the match is a word separator
            return true;
        }
    }
    return false;
}
function rightIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength) {
    if (matchStartIndex + matchLength === textLength) {
        // Match ends at end of string
        return true;
    }
    const charAfter = text.charCodeAt(matchStartIndex + matchLength);
    if (wordSeparators.get(charAfter) !== 0 /* WordCharacterClass.Regular */) {
        // The character after the match is a word separator
        return true;
    }
    if (charAfter === 13 /* CharCode.CarriageReturn */ || charAfter === 10 /* CharCode.LineFeed */) {
        // The character after the match is line break or carriage return.
        return true;
    }
    if (matchLength > 0) {
        const lastCharInMatch = text.charCodeAt(matchStartIndex + matchLength - 1);
        if (wordSeparators.get(lastCharInMatch) !== 0 /* WordCharacterClass.Regular */) {
            // The last character in the match is a word separator
            return true;
        }
    }
    return false;
}
function isValidMatch(wordSeparators, text, textLength, matchStartIndex, matchLength) {
    return (leftIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength)
        && rightIsWordBounday(wordSeparators, text, textLength, matchStartIndex, matchLength));
}
class Searcher {
    constructor(wordSeparators, searchRegex) {
        this._wordSeparators = wordSeparators;
        this._searchRegex = searchRegex;
        this._prevMatchStartIndex = -1;
        this._prevMatchLength = 0;
    }
    reset(lastIndex) {
        this._searchRegex.lastIndex = lastIndex;
        this._prevMatchStartIndex = -1;
        this._prevMatchLength = 0;
    }
    next(text) {
        const textLength = text.length;
        let m;
        do {
            if (this._prevMatchStartIndex + this._prevMatchLength === textLength) {
                // Reached the end of the line
                return null;
            }
            m = this._searchRegex.exec(text);
            if (!m) {
                return null;
            }
            const matchStartIndex = m.index;
            const matchLength = m[0].length;
            if (matchStartIndex === this._prevMatchStartIndex && matchLength === this._prevMatchLength) {
                if (matchLength === 0) {
                    // the search result is an empty string and won't advance `regex.lastIndex`, so `regex.exec` will stuck here
                    // we attempt to recover from that by advancing by two if surrogate pair found and by one otherwise
                    if (getNextCodePoint(text, textLength, this._searchRegex.lastIndex) > 0xFFFF) {
                        this._searchRegex.lastIndex += 2;
                    }
                    else {
                        this._searchRegex.lastIndex += 1;
                    }
                    continue;
                }
                // Exit early if the regex matches the same range twice
                return null;
            }
            this._prevMatchStartIndex = matchStartIndex;
            this._prevMatchLength = matchLength;
            if (!this._wordSeparators || isValidMatch(this._wordSeparators, text, textLength, matchStartIndex, matchLength)) {
                return m;
            }
        } while (m);
        return null;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





// const lfRegex = new RegExp(/\r\n|\r|\n/g);
const AverageBufferSize = 65535;
function createUintArray(arr) {
    let r;
    if (arr[arr.length - 1] < 65536) {
        r = new Uint16Array(arr.length);
    }
    else {
        r = new Uint32Array(arr.length);
    }
    r.set(arr, 0);
    return r;
}
class LineStarts {
    constructor(lineStarts, cr, lf, crlf, isBasicASCII) {
        this.lineStarts = lineStarts;
        this.cr = cr;
        this.lf = lf;
        this.crlf = crlf;
        this.isBasicASCII = isBasicASCII;
    }
}
function createLineStartsFast(str, readonly = true) {
    const r = [0];
    let rLength = 1;
    for (let i = 0, len = str.length; i < len; i++) {
        const chr = str.charCodeAt(i);
        if (chr === 13 /* CharCode.CarriageReturn */) {
            if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* CharCode.LineFeed */) {
                // \r\n... case
                r[rLength++] = i + 2;
                i++; // skip \n
            }
            else {
                // \r... case
                r[rLength++] = i + 1;
            }
        }
        else if (chr === 10 /* CharCode.LineFeed */) {
            r[rLength++] = i + 1;
        }
    }
    if (readonly) {
        return createUintArray(r);
    }
    else {
        return r;
    }
}
function createLineStarts(r, str) {
    r.length = 0;
    r[0] = 0;
    let rLength = 1;
    let cr = 0, lf = 0, crlf = 0;
    let isBasicASCII = true;
    for (let i = 0, len = str.length; i < len; i++) {
        const chr = str.charCodeAt(i);
        if (chr === 13 /* CharCode.CarriageReturn */) {
            if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* CharCode.LineFeed */) {
                // \r\n... case
                crlf++;
                r[rLength++] = i + 2;
                i++; // skip \n
            }
            else {
                cr++;
                // \r... case
                r[rLength++] = i + 1;
            }
        }
        else if (chr === 10 /* CharCode.LineFeed */) {
            lf++;
            r[rLength++] = i + 1;
        }
        else {
            if (isBasicASCII) {
                if (chr !== 9 /* CharCode.Tab */ && (chr < 32 || chr > 126)) {
                    isBasicASCII = false;
                }
            }
        }
    }
    const result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII);
    r.length = 0;
    return result;
}
class Piece {
    constructor(bufferIndex, start, end, lineFeedCnt, length) {
        this.bufferIndex = bufferIndex;
        this.start = start;
        this.end = end;
        this.lineFeedCnt = lineFeedCnt;
        this.length = length;
    }
}
class StringBuffer {
    constructor(buffer, lineStarts) {
        this.buffer = buffer;
        this.lineStarts = lineStarts;
    }
}
/**
 * Readonly snapshot for piece tree.
 * In a real multiple thread environment, to make snapshot reading always work correctly, we need to
 * 1. Make TreeNode.piece immutable, then reading and writing can run in parallel.
 * 2. TreeNode/Buffers normalization should not happen during snapshot reading.
 */
class PieceTreeSnapshot {
    constructor(tree, BOM) {
        this._pieces = [];
        this._tree = tree;
        this._BOM = BOM;
        this._index = 0;
        if (tree.root !== rbTreeBase_SENTINEL) {
            tree.iterate(tree.root, node => {
                if (node !== rbTreeBase_SENTINEL) {
                    this._pieces.push(node.piece);
                }
                return true;
            });
        }
    }
    read() {
        if (this._pieces.length === 0) {
            if (this._index === 0) {
                this._index++;
                return this._BOM;
            }
            else {
                return null;
            }
        }
        if (this._index > this._pieces.length - 1) {
            return null;
        }
        if (this._index === 0) {
            return this._BOM + this._tree.getPieceContent(this._pieces[this._index++]);
        }
        return this._tree.getPieceContent(this._pieces[this._index++]);
    }
}
class PieceTreeSearchCache {
    constructor(limit) {
        this._limit = limit;
        this._cache = [];
    }
    get(offset) {
        for (let i = this._cache.length - 1; i >= 0; i--) {
            const nodePos = this._cache[i];
            if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) {
                return nodePos;
            }
        }
        return null;
    }
    get2(lineNumber) {
        for (let i = this._cache.length - 1; i >= 0; i--) {
            const nodePos = this._cache[i];
            if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) {
                return nodePos;
            }
        }
        return null;
    }
    set(nodePosition) {
        if (this._cache.length >= this._limit) {
            this._cache.shift();
        }
        this._cache.push(nodePosition);
    }
    validate(offset) {
        let hasInvalidVal = false;
        const tmp = this._cache;
        for (let i = 0; i < tmp.length; i++) {
            const nodePos = tmp[i];
            if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) {
                tmp[i] = null;
                hasInvalidVal = true;
                continue;
            }
        }
        if (hasInvalidVal) {
            const newArr = [];
            for (const entry of tmp) {
                if (entry !== null) {
                    newArr.push(entry);
                }
            }
            this._cache = newArr;
        }
    }
}
class PieceTreeBase {
    constructor(chunks, eol, eolNormalized) {
        this.create(chunks, eol, eolNormalized);
    }
    create(chunks, eol, eolNormalized) {
        this._buffers = [
            new StringBuffer('', [0])
        ];
        this._lastChangeBufferPos = { line: 0, column: 0 };
        this.root = rbTreeBase_SENTINEL;
        this._lineCnt = 1;
        this._length = 0;
        this._EOL = eol;
        this._EOLLength = eol.length;
        this._EOLNormalized = eolNormalized;
        let lastNode = null;
        for (let i = 0, len = chunks.length; i < len; i++) {
            if (chunks[i].buffer.length > 0) {
                if (!chunks[i].lineStarts) {
                    chunks[i].lineStarts = createLineStartsFast(chunks[i].buffer);
                }
                const piece = new Piece(i + 1, { line: 0, column: 0 }, { line: chunks[i].lineStarts.length - 1, column: chunks[i].buffer.length - chunks[i].lineStarts[chunks[i].lineStarts.length - 1] }, chunks[i].lineStarts.length - 1, chunks[i].buffer.length);
                this._buffers.push(chunks[i]);
                lastNode = this.rbInsertRight(lastNode, piece);
            }
        }
        this._searchCache = new PieceTreeSearchCache(1);
        this._lastVisitedLine = { lineNumber: 0, value: '' };
        this.computeBufferMetadata();
    }
    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.getNodeContent(node);
            const len = str.length;
            if (tempChunkLen <= min || tempChunkLen + len < max) {
                tempChunk += str;
                tempChunkLen += len;
                return true;
            }
            // flush anyways
            const text = tempChunk.replace(/\r\n|\r|\n/g, eol);
            chunks.push(new StringBuffer(text, createLineStartsFast(text)));
            tempChunk = str;
            tempChunkLen = len;
            return true;
        });
        if (tempChunkLen > 0) {
            const text = tempChunk.replace(/\r\n|\r|\n/g, eol);
            chunks.push(new StringBuffer(text, createLineStartsFast(text)));
        }
        this.create(chunks, eol, true);
    }
    // #region Buffer API
    getEOL() {
        return this._EOL;
    }
    setEOL(newEOL) {
        this._EOL = newEOL;
        this._EOLLength = this._EOL.length;
        this.normalizeEOL(newEOL);
    }
    createSnapshot(BOM) {
        return new PieceTreeSnapshot(this, BOM);
    }
    getOffsetAt(lineNumber, column) {
        let leftLen = 0; // inorder
        let x = this.root;
        while (x !== rbTreeBase_SENTINEL) {
            if (x.left !== rbTreeBase_SENTINEL && x.lf_left + 1 >= lineNumber) {
                x = x.left;
            }
            else if (x.lf_left + x.piece.lineFeedCnt + 1 >= lineNumber) {
                leftLen += x.size_left;
                // lineNumber >= 2
                const accumualtedValInCurrentIndex = this.getAccumulatedValue(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 !== rbTreeBase_SENTINEL) {
            if (x.size_left !== 0 && x.size_left >= offset) {
                x = x.left;
            }
            else if (x.size_left + x.piece.length >= offset) {
                const out = this.getIndexOf(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 Position(lfCnt + 1, column + 1);
                }
                return new Position(lfCnt + 1, out.remainder + 1);
            }
            else {
                offset -= x.size_left + x.piece.length;
                lfCnt += x.lf_left + x.piece.lineFeedCnt;
                if (x.right === rbTreeBase_SENTINEL) {
                    // last node
                    const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
                    const column = originalOffset - offset - lineStartOffset;
                    return new Position(lfCnt + 1, column + 1);
                }
                else {
                    x = x.right;
                }
            }
        }
        return new Position(1, 1);
    }
    getValueInRange(range, eol) {
        if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
            return '';
        }
        const startPosition = this.nodeAt2(range.startLineNumber, range.startColumn);
        const endPosition = this.nodeAt2(range.endLineNumber, range.endColumn);
        const value = this.getValueInRange2(startPosition, endPosition);
        if (eol) {
            if (eol !== this._EOL || !this._EOLNormalized) {
                return value.replace(/\r\n|\r|\n/g, eol);
            }
            if (eol === this.getEOL() && this._EOLNormalized) {
                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 buffer = this._buffers[node.piece.bufferIndex].buffer;
            const startOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
            return buffer.substring(startOffset + startPosition.remainder, startOffset + endPosition.remainder);
        }
        let x = startPosition.node;
        const buffer = this._buffers[x.piece.bufferIndex].buffer;
        const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
        let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length);
        x = x.next();
        while (x !== rbTreeBase_SENTINEL) {
            const buffer = this._buffers[x.piece.bufferIndex].buffer;
            const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
            if (x === endPosition.node) {
                ret += buffer.substring(startOffset, startOffset + endPosition.remainder);
                break;
            }
            else {
                ret += buffer.substr(startOffset, 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 === rbTreeBase_SENTINEL) {
                return true;
            }
            const piece = node.piece;
            let pieceLength = piece.length;
            if (pieceLength === 0) {
                return true;
            }
            const buffer = this._buffers[piece.bufferIndex].buffer;
            const lineStarts = this._buffers[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 /* CharCode.LineFeed */) {
                    // pretend the \n was in the previous piece..
                    pieceStartOffset++;
                    pieceLength--;
                }
                lines[linesLength++] = currentLine;
                currentLine = '';
                danglingCR = false;
                if (pieceLength === 0) {
                    return true;
                }
            }
            if (pieceStartLine === pieceEndLine) {
                // this piece has no new lines
                if (!this._EOLNormalized && buffer.charCodeAt(pieceStartOffset + pieceLength - 1) === 13 /* CharCode.CarriageReturn */) {
                    danglingCR = true;
                    currentLine += buffer.substr(pieceStartOffset, pieceLength - 1);
                }
                else {
                    currentLine += buffer.substr(pieceStartOffset, pieceLength);
                }
                return true;
            }
            // add the text before the first line start in this piece
            currentLine += (this._EOLNormalized
                ? buffer.substring(pieceStartOffset, Math.max(pieceStartOffset, lineStarts[pieceStartLine + 1] - this._EOLLength))
                : buffer.substring(pieceStartOffset, lineStarts[pieceStartLine + 1]).replace(/(\r\n|\r|\n)$/, ''));
            lines[linesLength++] = currentLine;
            for (let line = pieceStartLine + 1; line < pieceEndLine; line++) {
                currentLine = (this._EOLNormalized
                    ? buffer.substring(lineStarts[line], lineStarts[line + 1] - this._EOLLength)
                    : buffer.substring(lineStarts[line], lineStarts[line + 1]).replace(/(\r\n|\r|\n)$/, ''));
                lines[linesLength++] = currentLine;
            }
            if (!this._EOLNormalized && buffer.charCodeAt(lineStarts[pieceEndLine] + piece.end.column - 1) === 13 /* CharCode.CarriageReturn */) {
                danglingCR = true;
                if (piece.end.column === 0) {
                    // The last line ended with a \r, let's undo the push, it will be pushed by next iteration
                    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._length;
    }
    getLineCount() {
        return this._lineCnt;
    }
    getLineContent(lineNumber) {
        if (this._lastVisitedLine.lineNumber === lineNumber) {
            return this._lastVisitedLine.value;
        }
        this._lastVisitedLine.lineNumber = lineNumber;
        if (lineNumber === this._lineCnt) {
            this._lastVisitedLine.value = this.getLineRawContent(lineNumber);
        }
        else if (this._EOLNormalized) {
            this._lastVisitedLine.value = this.getLineRawContent(lineNumber, this._EOLLength);
        }
        else {
            this._lastVisitedLine.value = this.getLineRawContent(lineNumber).replace(/(\r\n|\r|\n)$/, '');
        }
        return this._lastVisitedLine.value;
    }
    _getCharCode(nodePos) {
        if (nodePos.remainder === nodePos.node.piece.length) {
            // the char we want to fetch is at the head of next node.
            const matchingNode = nodePos.node.next();
            if (!matchingNode) {
                return 0;
            }
            const buffer = this._buffers[matchingNode.piece.bufferIndex];
            const startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
            return buffer.buffer.charCodeAt(startOffset);
        }
        else {
            const buffer = this._buffers[nodePos.node.piece.bufferIndex];
            const startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
            const targetOffset = startOffset + nodePos.remainder;
            return buffer.buffer.charCodeAt(targetOffset);
        }
    }
    getLineCharCode(lineNumber, index) {
        const nodePos = this.nodeAt2(lineNumber, index + 1);
        return this._getCharCode(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._EOLLength;
    }
    findMatchesInNode(node, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result) {
        const buffer = this._buffers[node.piece.bufferIndex];
        const startOffsetInBuffer = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
        const start = this.offsetInBuffer(node.piece.bufferIndex, startCursor);
        const end = this.offsetInBuffer(node.piece.bufferIndex, endCursor);
        let m;
        // Reset regex to search from the beginning
        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.positionInBuffer(node, offsetInBuffer(m.index) - startOffsetInBuffer, ret);
                const lineFeedCnt = this.getLineFeedCnt(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++] = createFindMatch(new Range(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 Searcher(searchData.wordSeparators, searchData.regex);
        let startPosition = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn);
        if (startPosition === null) {
            return [];
        }
        const endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn);
        if (endPosition === null) {
            return [];
        }
        let start = this.positionInBuffer(startPosition.node, startPosition.remainder);
        const end = this.positionInBuffer(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.getLineFeedCnt(currentNode.piece.bufferIndex, start, currentNode.piece.end);
            if (lineBreakCnt >= 1) {
                // last line break position
                const lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts;
                const startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start);
                const nextLineStartOffset = lineStarts[start.line + lineBreakCnt];
                const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
                resultLen = this.findMatchesInNode(currentNode, searcher, startLineNumber, startColumn, start, this.positionInBuffer(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result);
                if (resultLen >= limitResultCount) {
                    return result;
                }
                startLineNumber += lineBreakCnt;
            }
            const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
            // search for the remaining content
            if (startLineNumber === searchRange.endLineNumber) {
                const text = this.getLineContent(startLineNumber).substring(startColumn, searchRange.endColumn - 1);
                resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn, resultLen, result, captureMatches, limitResultCount);
                return result;
            }
            resultLen = this._findMatchesInLine(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn), startLineNumber, startColumn, resultLen, result, captureMatches, limitResultCount);
            if (resultLen >= limitResultCount) {
                return result;
            }
            startLineNumber++;
            startPosition = this.nodeAt2(startLineNumber, 1);
            currentNode = startPosition.node;
            start = this.positionInBuffer(startPosition.node, startPosition.remainder);
        }
        if (startLineNumber === searchRange.endLineNumber) {
            const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
            const text = this.getLineContent(startLineNumber).substring(startColumn, searchRange.endColumn - 1);
            resultLen = this._findMatchesInLine(searchData, searcher, text, searchRange.endLineNumber, startColumn, 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;
    }
    _findMatchesInLine(searchData, searcher, text, lineNumber, deltaOffset, resultLen, result, captureMatches, limitResultCount) {
        const wordSeparators = searchData.wordSeparators;
        if (!captureMatches && searchData.simpleSearch) {
            const searchString = searchData.simpleSearch;
            const searchStringLen = searchString.length;
            const textLength = text.length;
            let lastMatchIndex = -searchStringLen;
            while ((lastMatchIndex = text.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
                if (!wordSeparators || isValidMatch(wordSeparators, text, textLength, lastMatchIndex, searchStringLen)) {
                    result[resultLen++] = new FindMatch(new Range(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
                    if (resultLen >= limitResultCount) {
                        return resultLen;
                    }
                }
            }
            return resultLen;
        }
        let m;
        // Reset regex to search from the beginning
        searcher.reset(0);
        do {
            m = searcher.next(text);
            if (m) {
                result[resultLen++] = createFindMatch(new Range(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._EOLNormalized = this._EOLNormalized && eolNormalized;
        this._lastVisitedLine.lineNumber = 0;
        this._lastVisitedLine.value = '';
        if (this.root !== rbTreeBase_SENTINEL) {
            const { node, remainder, nodeStartOffset } = this.nodeAt(offset);
            const piece = node.piece;
            const bufferIndex = piece.bufferIndex;
            const insertPosInBuffer = this.positionInBuffer(node, remainder);
            if (node.piece.bufferIndex === 0 &&
                piece.end.line === this._lastChangeBufferPos.line &&
                piece.end.column === this._lastChangeBufferPos.column &&
                (nodeStartOffset + piece.length === offset) &&
                value.length < AverageBufferSize) {
                // changed buffer
                this.appendToNode(node, value);
                this.computeBufferMetadata();
                return;
            }
            if (nodeStartOffset === offset) {
                this.insertContentToNodeLeft(value, node);
                this._searchCache.validate(offset);
            }
            else if (nodeStartOffset + node.piece.length > offset) {
                // we are inserting into the middle of a node.
                const nodesToDel = [];
                let newRightPiece = new Piece(piece.bufferIndex, insertPosInBuffer, piece.end, this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end), this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer));
                if (this.shouldCheckCRLF() && this.endWithCR(value)) {
                    const headOfRight = this.nodeCharCodeAt(node, remainder);
                    if (headOfRight === 10 /** \n */) {
                        const newStart = { line: newRightPiece.start.line + 1, column: 0 };
                        newRightPiece = new Piece(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.getLineFeedCnt(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1);
                        value += '\n';
                    }
                }
                // reuse node for content before insertion point.
                if (this.shouldCheckCRLF() && this.startWithLF(value)) {
                    const tailOfLeft = this.nodeCharCodeAt(node, remainder - 1);
                    if (tailOfLeft === 13 /** \r */) {
                        const previousPos = this.positionInBuffer(node, remainder - 1);
                        this.deleteNodeTail(node, previousPos);
                        value = '\r' + value;
                        if (node.piece.length === 0) {
                            nodesToDel.push(node);
                        }
                    }
                    else {
                        this.deleteNodeTail(node, insertPosInBuffer);
                    }
                }
                else {
                    this.deleteNodeTail(node, insertPosInBuffer);
                }
                const newPieces = this.createNewPieces(value);
                if (newRightPiece.length > 0) {
                    this.rbInsertRight(node, newRightPiece);
                }
                let tmpNode = node;
                for (let k = 0; k < newPieces.length; k++) {
                    tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
                }
                this.deleteNodes(nodesToDel);
            }
            else {
                this.insertContentToNodeRight(value, node);
            }
        }
        else {
            // insert new node
            const pieces = this.createNewPieces(value);
            let node = this.rbInsertLeft(null, pieces[0]);
            for (let k = 1; k < pieces.length; k++) {
                node = this.rbInsertRight(node, pieces[k]);
            }
        }
        // todo, this is too brutal. Total line feed count should be updated the same way as lf_left.
        this.computeBufferMetadata();
    }
    delete(offset, cnt) {
        this._lastVisitedLine.lineNumber = 0;
        this._lastVisitedLine.value = '';
        if (cnt <= 0 || this.root === rbTreeBase_SENTINEL) {
            return;
        }
        const startPosition = this.nodeAt(offset);
        const endPosition = this.nodeAt(offset + cnt);
        const startNode = startPosition.node;
        const endNode = endPosition.node;
        if (startNode === endNode) {
            const startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
            const endSplitPosInBuffer = this.positionInBuffer(startNode, endPosition.remainder);
            if (startPosition.nodeStartOffset === offset) {
                if (cnt === startNode.piece.length) { // delete node
                    const next = startNode.next();
                    rbDelete(this, startNode);
                    this.validateCRLFWithPrevNode(next);
                    this.computeBufferMetadata();
                    return;
                }
                this.deleteNodeHead(startNode, endSplitPosInBuffer);
                this._searchCache.validate(offset);
                this.validateCRLFWithPrevNode(startNode);
                this.computeBufferMetadata();
                return;
            }
            if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) {
                this.deleteNodeTail(startNode, startSplitPosInBuffer);
                this.validateCRLFWithNextNode(startNode);
                this.computeBufferMetadata();
                return;
            }
            // delete content in the middle, this node will be splitted to nodes
            this.shrinkNode(startNode, startSplitPosInBuffer, endSplitPosInBuffer);
            this.computeBufferMetadata();
            return;
        }
        const nodesToDel = [];
        const startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
        this.deleteNodeTail(startNode, startSplitPosInBuffer);
        this._searchCache.validate(offset);
        if (startNode.piece.length === 0) {
            nodesToDel.push(startNode);
        }
        // update last touched node
        const endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder);
        this.deleteNodeHead(endNode, endSplitPosInBuffer);
        if (endNode.piece.length === 0) {
            nodesToDel.push(endNode);
        }
        // delete nodes in between
        const secondNode = startNode.next();
        for (let node = secondNode; node !== rbTreeBase_SENTINEL && node !== endNode; node = node.next()) {
            nodesToDel.push(node);
        }
        const prev = startNode.piece.length === 0 ? startNode.prev() : startNode;
        this.deleteNodes(nodesToDel);
        this.validateCRLFWithNextNode(prev);
        this.computeBufferMetadata();
    }
    insertContentToNodeLeft(value, node) {
        // we are inserting content to the beginning of node
        const nodesToDel = [];
        if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) {
            // move `\n` to new node.
            const piece = node.piece;
            const newStart = { line: piece.start.line + 1, column: 0 };
            const nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1);
            node.piece = nPiece;
            value += '\n';
            updateTreeMetadata(this, node, -1, -1);
            if (node.piece.length === 0) {
                nodesToDel.push(node);
            }
        }
        const newPieces = this.createNewPieces(value);
        let newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]);
        for (let k = newPieces.length - 2; k >= 0; k--) {
            newNode = this.rbInsertLeft(newNode, newPieces[k]);
        }
        this.validateCRLFWithPrevNode(newNode);
        this.deleteNodes(nodesToDel);
    }
    insertContentToNodeRight(value, node) {
        // we are inserting to the right of this node.
        if (this.adjustCarriageReturnFromNext(value, node)) {
            // move \n to the new node.
            value += '\n';
        }
        const newPieces = this.createNewPieces(value);
        const newNode = this.rbInsertRight(node, newPieces[0]);
        let tmpNode = newNode;
        for (let k = 1; k < newPieces.length; k++) {
            tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
        }
        this.validateCRLFWithPrevNode(newNode);
    }
    positionInBuffer(node, remainder, ret) {
        const piece = node.piece;
        const bufferIndex = node.piece.bufferIndex;
        const lineStarts = this._buffers[bufferIndex].lineStarts;
        const startOffset = lineStarts[piece.start.line] + piece.start.column;
        const offset = startOffset + remainder;
        // binary search offset between startOffset and endOffset
        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
        };
    }
    getLineFeedCnt(bufferIndex, start, end) {
        // we don't need to worry about start: abc\r|\n, or abc|\r, or abc|\n, or abc|\r\n doesn't change the fact that, there is one line break after start.
        // now let's take care of end: abc\r|\n, if end is in between \r and \n, we need to add line feed count by 1
        if (end.column === 0) {
            return end.line - start.line;
        }
        const lineStarts = this._buffers[bufferIndex].lineStarts;
        if (end.line === lineStarts.length - 1) { // it means, there is no \n after end, otherwise, there will be one more lineStart.
            return end.line - start.line;
        }
        const nextLineStartOffset = lineStarts[end.line + 1];
        const endOffset = lineStarts[end.line] + end.column;
        if (nextLineStartOffset > endOffset + 1) { // there are more than 1 character after end, which means it can't be \n
            return end.line - start.line;
        }
        // endOffset + 1 === nextLineStartOffset
        // character at endOffset is \n, so we check the character before first
        // if character at endOffset is \r, end.column is 0 and we can't get here.
        const previousCharOffset = endOffset - 1; // end.column > 0 so it's okay.
        const buffer = this._buffers[bufferIndex].buffer;
        if (buffer.charCodeAt(previousCharOffset) === 13) {
            return end.line - start.line + 1;
        }
        else {
            return end.line - start.line;
        }
    }
    offsetInBuffer(bufferIndex, cursor) {
        const lineStarts = this._buffers[bufferIndex].lineStarts;
        return lineStarts[cursor.line] + cursor.column;
    }
    deleteNodes(nodes) {
        for (let i = 0; i < nodes.length; i++) {
            rbDelete(this, nodes[i]);
        }
    }
    createNewPieces(text) {
        if (text.length > AverageBufferSize) {
            // the content is large, operations like substring, charCode becomes slow
            // so here we split it into smaller chunks, just like what we did for CR/LF normalization
            const newPieces = [];
            while (text.length > AverageBufferSize) {
                const lastChar = text.charCodeAt(AverageBufferSize - 1);
                let splitText;
                if (lastChar === 13 /* CharCode.CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
                    // last character is \r or a high surrogate => keep it back
                    splitText = text.substring(0, AverageBufferSize - 1);
                    text = text.substring(AverageBufferSize - 1);
                }
                else {
                    splitText = text.substring(0, AverageBufferSize);
                    text = text.substring(AverageBufferSize);
                }
                const lineStarts = createLineStartsFast(splitText);
                newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: splitText.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, splitText.length));
                this._buffers.push(new StringBuffer(splitText, lineStarts));
            }
            const lineStarts = createLineStartsFast(text);
            newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: text.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, text.length));
            this._buffers.push(new StringBuffer(text, lineStarts));
            return newPieces;
        }
        let startOffset = this._buffers[0].buffer.length;
        const lineStarts = createLineStartsFast(text, false);
        let start = this._lastChangeBufferPos;
        if (this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 1] === startOffset
            && startOffset !== 0
            && this.startWithLF(text)
            && this.endWithCR(this._buffers[0].buffer) // todo, we can check this._lastChangeBufferPos's column as it's the last one
        ) {
            this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line, column: this._lastChangeBufferPos.column + 1 };
            start = this._lastChangeBufferPos;
            for (let i = 0; i < lineStarts.length; i++) {
                lineStarts[i] += startOffset + 1;
            }
            this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
            this._buffers[0].buffer += '_' + text;
            startOffset += 1;
        }
        else {
            if (startOffset !== 0) {
                for (let i = 0; i < lineStarts.length; i++) {
                    lineStarts[i] += startOffset;
                }
            }
            this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
            this._buffers[0].buffer += text;
        }
        const endOffset = this._buffers[0].buffer.length;
        const endIndex = this._buffers[0].lineStarts.length - 1;
        const endColumn = endOffset - this._buffers[0].lineStarts[endIndex];
        const endPos = { line: endIndex, column: endColumn };
        const newPiece = new Piece(0, /** todo@peng */ start, endPos, this.getLineFeedCnt(0, start, endPos), endOffset - startOffset);
        this._lastChangeBufferPos = endPos;
        return [newPiece];
    }
    getLineRawContent(lineNumber, endOffset = 0) {
        let x = this.root;
        let ret = '';
        const cache = this._searchCache.get2(lineNumber);
        if (cache) {
            x = cache.node;
            const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1);
            const buffer = this._buffers[x.piece.bufferIndex].buffer;
            const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
            if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) {
                ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
            }
            else {
                const accumulatedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber);
                return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
            }
        }
        else {
            let nodeStartOffset = 0;
            const originalLineNumber = lineNumber;
            while (x !== rbTreeBase_SENTINEL) {
                if (x.left !== rbTreeBase_SENTINEL && x.lf_left >= lineNumber - 1) {
                    x = x.left;
                }
                else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
                    const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
                    const accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
                    const buffer = this._buffers[x.piece.bufferIndex].buffer;
                    const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
                    nodeStartOffset += x.size_left;
                    this._searchCache.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.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
                    const buffer = this._buffers[x.piece.bufferIndex].buffer;
                    const startOffset = this.offsetInBuffer(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;
                }
            }
        }
        // search in order, to find the node contains end column
        x = x.next();
        while (x !== rbTreeBase_SENTINEL) {
            const buffer = this._buffers[x.piece.bufferIndex].buffer;
            if (x.piece.lineFeedCnt > 0) {
                const accumulatedValue = this.getAccumulatedValue(x, 0);
                const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
                ret += buffer.substring(startOffset, startOffset + accumulatedValue - endOffset);
                return ret;
            }
            else {
                const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
                ret += buffer.substr(startOffset, x.piece.length);
            }
            x = x.next();
        }
        return ret;
    }
    computeBufferMetadata() {
        let x = this.root;
        let lfCnt = 1;
        let len = 0;
        while (x !== rbTreeBase_SENTINEL) {
            lfCnt += x.lf_left + x.piece.lineFeedCnt;
            len += x.size_left + x.piece.length;
            x = x.right;
        }
        this._lineCnt = lfCnt;
        this._length = len;
        this._searchCache.validate(this._length);
    }
    // #region node operations
    getIndexOf(node, accumulatedValue) {
        const piece = node.piece;
        const pos = this.positionInBuffer(node, accumulatedValue);
        const lineCnt = pos.line - piece.start.line;
        if (this.offsetInBuffer(piece.bufferIndex, piece.end) - this.offsetInBuffer(piece.bufferIndex, piece.start) === accumulatedValue) {
            // we are checking the end of this node, so a CRLF check is necessary.
            const realLineCnt = this.getLineFeedCnt(node.piece.bufferIndex, piece.start, pos);
            if (realLineCnt !== lineCnt) {
                // aha yes, CRLF
                return { index: realLineCnt, remainder: 0 };
            }
        }
        return { index: lineCnt, remainder: pos.column };
    }
    getAccumulatedValue(node, index) {
        if (index < 0) {
            return 0;
        }
        const piece = node.piece;
        const lineStarts = this._buffers[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;
        }
    }
    deleteNodeTail(node, pos) {
        const piece = node.piece;
        const originalLFCnt = piece.lineFeedCnt;
        const originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
        const newEnd = pos;
        const newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd);
        const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
        const lf_delta = newLineFeedCnt - originalLFCnt;
        const size_delta = newEndOffset - originalEndOffset;
        const newLength = piece.length + size_delta;
        node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
        updateTreeMetadata(this, node, size_delta, lf_delta);
    }
    deleteNodeHead(node, pos) {
        const piece = node.piece;
        const originalLFCnt = piece.lineFeedCnt;
        const originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
        const newStart = pos;
        const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
        const newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart);
        const lf_delta = newLineFeedCnt - originalLFCnt;
        const size_delta = originalStartOffset - newStartOffset;
        const newLength = piece.length + size_delta;
        node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
        updateTreeMetadata(this, node, size_delta, lf_delta);
    }
    shrinkNode(node, start, end) {
        const piece = node.piece;
        const originalStartPos = piece.start;
        const originalEndPos = piece.end;
        // old piece, originalStartPos, start
        const oldLength = piece.length;
        const oldLFCnt = piece.lineFeedCnt;
        const newEnd = start;
        const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
        const newLength = this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos);
        node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
        updateTreeMetadata(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt);
        // new right piece, end, originalEndPos
        const newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end));
        const newNode = this.rbInsertRight(node, newPiece);
        this.validateCRLFWithPrevNode(newNode);
    }
    appendToNode(node, value) {
        if (this.adjustCarriageReturnFromNext(value, node)) {
            value += '\n';
        }
        const hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node);
        const startOffset = this._buffers[0].buffer.length;
        this._buffers[0].buffer += value;
        const lineStarts = createLineStartsFast(value, false);
        for (let i = 0; i < lineStarts.length; i++) {
            lineStarts[i] += startOffset;
        }
        if (hitCRLF) {
            const prevStartOffset = this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 2];
            this._buffers[0].lineStarts.pop();
            // _lastChangeBufferPos is already wrong
            this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line - 1, column: startOffset - prevStartOffset };
        }
        this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
        const endIndex = this._buffers[0].lineStarts.length - 1;
        const endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex];
        const newEnd = { line: endIndex, column: endColumn };
        const newLength = node.piece.length + value.length;
        const oldLineFeedCnt = node.piece.lineFeedCnt;
        const newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd);
        const lf_delta = newLineFeedCnt - oldLineFeedCnt;
        node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength);
        this._lastChangeBufferPos = newEnd;
        updateTreeMetadata(this, node, value.length, lf_delta);
    }
    nodeAt(offset) {
        let x = this.root;
        const cache = this._searchCache.get(offset);
        if (cache) {
            return {
                node: cache.node,
                nodeStartOffset: cache.nodeStartOffset,
                remainder: offset - cache.nodeStartOffset
            };
        }
        let nodeStartOffset = 0;
        while (x !== rbTreeBase_SENTINEL) {
            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._searchCache.set(ret);
                return ret;
            }
            else {
                offset -= x.size_left + x.piece.length;
                nodeStartOffset += x.size_left + x.piece.length;
                x = x.right;
            }
        }
        return null;
    }
    nodeAt2(lineNumber, column) {
        let x = this.root;
        let nodeStartOffset = 0;
        while (x !== rbTreeBase_SENTINEL) {
            if (x.left !== rbTreeBase_SENTINEL && x.lf_left >= lineNumber - 1) {
                x = x.left;
            }
            else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
                const prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
                const accumulatedValue = this.getAccumulatedValue(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.getAccumulatedValue(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;
            }
        }
        // search in order, to find the node contains position.column
        x = x.next();
        while (x !== rbTreeBase_SENTINEL) {
            if (x.piece.lineFeedCnt > 0) {
                const accumulatedValue = this.getAccumulatedValue(x, 0);
                const nodeStartOffset = this.offsetOfNode(x);
                return {
                    node: x,
                    remainder: Math.min(column - 1, accumulatedValue),
                    nodeStartOffset
                };
            }
            else {
                if (x.piece.length >= column - 1) {
                    const nodeStartOffset = this.offsetOfNode(x);
                    return {
                        node: x,
                        remainder: column - 1,
                        nodeStartOffset
                    };
                }
                else {
                    column -= x.piece.length;
                }
            }
            x = x.next();
        }
        return null;
    }
    nodeCharCodeAt(node, offset) {
        if (node.piece.lineFeedCnt < 1) {
            return -1;
        }
        const buffer = this._buffers[node.piece.bufferIndex];
        const newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset;
        return buffer.buffer.charCodeAt(newOffset);
    }
    offsetOfNode(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
    shouldCheckCRLF() {
        return !(this._EOLNormalized && this._EOL === '\n');
    }
    startWithLF(val) {
        if (typeof val === 'string') {
            return val.charCodeAt(0) === 10;
        }
        if (val === rbTreeBase_SENTINEL || val.piece.lineFeedCnt === 0) {
            return false;
        }
        const piece = val.piece;
        const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
        const line = piece.start.line;
        const startOffset = lineStarts[line] + piece.start.column;
        if (line === lineStarts.length - 1) {
            // last line, so there is no line feed at the end of this line
            return false;
        }
        const nextLineOffset = lineStarts[line + 1];
        if (nextLineOffset > startOffset + 1) {
            return false;
        }
        return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;
    }
    endWithCR(val) {
        if (typeof val === 'string') {
            return val.charCodeAt(val.length - 1) === 13;
        }
        if (val === rbTreeBase_SENTINEL || val.piece.lineFeedCnt === 0) {
            return false;
        }
        return this.nodeCharCodeAt(val, val.piece.length - 1) === 13;
    }
    validateCRLFWithPrevNode(nextNode) {
        if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) {
            const node = nextNode.prev();
            if (this.endWithCR(node)) {
                this.fixCRLF(node, nextNode);
            }
        }
    }
    validateCRLFWithNextNode(node) {
        if (this.shouldCheckCRLF() && this.endWithCR(node)) {
            const nextNode = node.next();
            if (this.startWithLF(nextNode)) {
                this.fixCRLF(node, nextNode);
            }
        }
    }
    fixCRLF(prev, next) {
        const nodesToDel = [];
        // update node
        const lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts;
        let newEnd;
        if (prev.piece.end.column === 0) {
            // it means, last line ends with \r, not \r\n
            newEnd = { line: prev.piece.end.line - 1, column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1 };
        }
        else {
            // \r\n
            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 Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);
        updateTreeMetadata(this, prev, -1, -1);
        if (prev.piece.length === 0) {
            nodesToDel.push(prev);
        }
        // update nextNode
        const newStart = { line: next.piece.start.line + 1, column: 0 };
        const newLength = next.piece.length - 1;
        const newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end);
        next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);
        updateTreeMetadata(this, next, -1, -1);
        if (next.piece.length === 0) {
            nodesToDel.push(next);
        }
        // create new piece which contains \r\n
        const pieces = this.createNewPieces('\r\n');
        this.rbInsertRight(prev, pieces[0]);
        // delete empty nodes
        for (let i = 0; i < nodesToDel.length; i++) {
            rbDelete(this, nodesToDel[i]);
        }
    }
    adjustCarriageReturnFromNext(value, node) {
        if (this.shouldCheckCRLF() && this.endWithCR(value)) {
            const nextNode = node.next();
            if (this.startWithLF(nextNode)) {
                // move `\n` forward
                value += '\n';
                if (nextNode.piece.length === 1) {
                    rbDelete(this, nextNode);
                }
                else {
                    const piece = nextNode.piece;
                    const newStart = { line: piece.start.line + 1, column: 0 };
                    const newLength = piece.length - 1;
                    const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
                    nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
                    updateTreeMetadata(this, nextNode, -1, -1);
                }
                return true;
            }
        }
        return false;
    }
    // #endregion
    // #endregion
    // #region Tree operations
    iterate(node, callback) {
        if (node === rbTreeBase_SENTINEL) {
            return callback(rbTreeBase_SENTINEL);
        }
        const leftRet = this.iterate(node.left, callback);
        if (!leftRet) {
            return leftRet;
        }
        return callback(node) && this.iterate(node.right, callback);
    }
    getNodeContent(node) {
        if (node === rbTreeBase_SENTINEL) {
            return '';
        }
        const buffer = this._buffers[node.piece.bufferIndex];
        const piece = node.piece;
        const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
        const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
        const currentContent = buffer.buffer.substring(startOffset, endOffset);
        return currentContent;
    }
    getPieceContent(piece) {
        const buffer = this._buffers[piece.bufferIndex];
        const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
        const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
        const currentContent = buffer.buffer.substring(startOffset, endOffset);
        return currentContent;
    }
    /**
     *      node              node
     *     /  \              /  \
     *    a   b    <----   a    b
     *                         /
     *                        z
     */
    rbInsertRight(node, p) {
        const z = new TreeNode(p, 1 /* NodeColor.Red */);
        z.left = rbTreeBase_SENTINEL;
        z.right = rbTreeBase_SENTINEL;
        z.parent = rbTreeBase_SENTINEL;
        z.size_left = 0;
        z.lf_left = 0;
        const x = this.root;
        if (x === rbTreeBase_SENTINEL) {
            this.root = z;
            z.color = 0 /* NodeColor.Black */;
        }
        else if (node.right === rbTreeBase_SENTINEL) {
            node.right = z;
            z.parent = node;
        }
        else {
            const nextNode = rbTreeBase_leftest(node.right);
            nextNode.left = z;
            z.parent = nextNode;
        }
        fixInsert(this, z);
        return z;
    }
    /**
     *      node              node
     *     /  \              /  \
     *    a   b     ---->   a    b
     *                       \
     *                        z
     */
    rbInsertLeft(node, p) {
        const z = new TreeNode(p, 1 /* NodeColor.Red */);
        z.left = rbTreeBase_SENTINEL;
        z.right = rbTreeBase_SENTINEL;
        z.parent = rbTreeBase_SENTINEL;
        z.size_left = 0;
        z.lf_left = 0;
        if (this.root === rbTreeBase_SENTINEL) {
            this.root = z;
            z.color = 0 /* NodeColor.Black */;
        }
        else if (node.left === rbTreeBase_SENTINEL) {
            node.left = z;
            z.parent = node;
        }
        else {
            const prevNode = righttest(node.left); // a
            prevNode.right = z;
            z.parent = prevNode;
        }
        fixInsert(this, z);
        return z;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBuffer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/








class PieceTreeTextBuffer extends Disposable {
    constructor(chunks, BOM, eol, containsRTL, containsUnusualLineTerminators, isBasicASCII, eolNormalized) {
        super();
        this._onDidChangeContent = this._register(new Emitter());
        this._BOM = BOM;
        this._mightContainNonBasicASCII = !isBasicASCII;
        this._mightContainRTL = containsRTL;
        this._mightContainUnusualLineTerminators = containsUnusualLineTerminators;
        this._pieceTree = new PieceTreeBase(chunks, eol, eolNormalized);
    }
    mightContainRTL() {
        return this._mightContainRTL;
    }
    mightContainUnusualLineTerminators() {
        return this._mightContainUnusualLineTerminators;
    }
    resetMightContainUnusualLineTerminators() {
        this._mightContainUnusualLineTerminators = false;
    }
    mightContainNonBasicASCII() {
        return this._mightContainNonBasicASCII;
    }
    getBOM() {
        return this._BOM;
    }
    getEOL() {
        return this._pieceTree.getEOL();
    }
    createSnapshot(preserveBOM) {
        return this._pieceTree.createSnapshot(preserveBOM ? this._BOM : '');
    }
    getOffsetAt(lineNumber, column) {
        return this._pieceTree.getOffsetAt(lineNumber, column);
    }
    getPositionAt(offset) {
        return this._pieceTree.getPositionAt(offset);
    }
    getRangeAt(start, length) {
        const end = start + length;
        const startPosition = this.getPositionAt(start);
        const endPosition = this.getPositionAt(end);
        return new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
    }
    getValueInRange(range, eol = 0 /* EndOfLinePreference.TextDefined */) {
        if (range.isEmpty()) {
            return '';
        }
        const lineEnding = this._getEndOfLine(eol);
        return this._pieceTree.getValueInRange(range, lineEnding);
    }
    getValueLengthInRange(range, eol = 0 /* EndOfLinePreference.TextDefined */) {
        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);
        return endOffset - startOffset;
    }
    getCharacterCountInRange(range, eol = 0 /* EndOfLinePreference.TextDefined */) {
        if (this._mightContainNonBasicASCII) {
            // we must count by iterating
            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 (isHighSurrogate(lineContent.charCodeAt(offset))) {
                        result = result + 1;
                        offset = offset + 1;
                    }
                    else {
                        result = result + 1;
                    }
                }
            }
            result += this._getEndOfLine(eol).length * (toLineNumber - fromLineNumber);
            return result;
        }
        return this.getValueLengthInRange(range, eol);
    }
    getLength() {
        return this._pieceTree.getLength();
    }
    getLineCount() {
        return this._pieceTree.getLineCount();
    }
    getLinesContent() {
        return this._pieceTree.getLinesContent();
    }
    getLineContent(lineNumber) {
        return this._pieceTree.getLineContent(lineNumber);
    }
    getLineCharCode(lineNumber, index) {
        return this._pieceTree.getLineCharCode(lineNumber, index);
    }
    getLineLength(lineNumber) {
        return this._pieceTree.getLineLength(lineNumber);
    }
    getLineFirstNonWhitespaceColumn(lineNumber) {
        const result = strings_firstNonWhitespaceIndex(this.getLineContent(lineNumber));
        if (result === -1) {
            return 0;
        }
        return result + 1;
    }
    getLineLastNonWhitespaceColumn(lineNumber) {
        const result = strings_lastNonWhitespaceIndex(this.getLineContent(lineNumber));
        if (result === -1) {
            return 0;
        }
        return result + 2;
    }
    _getEndOfLine(eol) {
        switch (eol) {
            case 1 /* EndOfLinePreference.LF */:
                return '\n';
            case 2 /* EndOfLinePreference.CRLF */:
                return '\r\n';
            case 0 /* EndOfLinePreference.TextDefined */:
                return this.getEOL();
            default:
                throw new Error('Unknown EOL preference');
        }
    }
    setEOL(newEOL) {
        this._pieceTree.setEOL(newEOL);
    }
    applyEdits(rawOperations, recordTrimAutoWhitespace, computeUndoEdits) {
        let mightContainRTL = this._mightContainRTL;
        let mightContainUnusualLineTerminators = this._mightContainUnusualLineTerminators;
        let mightContainNonBasicASCII = this._mightContainNonBasicASCII;
        let canReduceOperations = true;
        let operations = [];
        for (let i = 0; i < rawOperations.length; i++) {
            const op = rawOperations[i];
            if (canReduceOperations && op._isTracked) {
                canReduceOperations = false;
            }
            const validatedRange = op.range;
            if (op.text) {
                let textMightContainNonBasicASCII = true;
                if (!mightContainNonBasicASCII) {
                    textMightContainNonBasicASCII = !strings_isBasicASCII(op.text);
                    mightContainNonBasicASCII = textMightContainNonBasicASCII;
                }
                if (!mightContainRTL && textMightContainNonBasicASCII) {
                    // check if the new inserted text contains RTL
                    mightContainRTL = strings_containsRTL(op.text);
                }
                if (!mightContainUnusualLineTerminators && textMightContainNonBasicASCII) {
                    // check if the new inserted text contains unusual line terminators
                    mightContainUnusualLineTerminators = containsUnusualLineTerminators(op.text);
                }
            }
            let validText = '';
            let eolCount = 0;
            let firstLineLength = 0;
            let lastLineLength = 0;
            if (op.text) {
                let strEOL;
                [eolCount, firstLineLength, lastLineLength, strEOL] = countEOL(op.text);
                const bufferEOL = this.getEOL();
                const expectedStrEOL = (bufferEOL === '\r\n' ? 2 /* StringEOL.CRLF */ : 1 /* StringEOL.LF */);
                if (strEOL === 0 /* StringEOL.Unknown */ || strEOL === expectedStrEOL) {
                    validText = op.text;
                }
                else {
                    validText = op.text.replace(/\r\n|\r|\n/g, bufferEOL);
                }
            }
            operations[i] = {
                sortIndex: i,
                identifier: op.identifier || null,
                range: validatedRange,
                rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn),
                rangeLength: this.getValueLengthInRange(validatedRange),
                text: validText,
                eolCount: eolCount,
                firstLineLength: firstLineLength,
                lastLineLength: lastLineLength,
                forceMoveMarkers: Boolean(op.forceMoveMarkers),
                isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false
            };
        }
        // Sort operations ascending
        operations.sort(PieceTreeTextBuffer._sortOpsAscending);
        let hasTouchingRanges = false;
        for (let i = 0, count = operations.length - 1; i < count; i++) {
            const rangeEnd = operations[i].range.getEndPosition();
            const nextRangeStart = operations[i + 1].range.getStartPosition();
            if (nextRangeStart.isBeforeOrEqual(rangeEnd)) {
                if (nextRangeStart.isBefore(rangeEnd)) {
                    // overlapping ranges
                    throw new Error('Overlapping ranges are not allowed!');
                }
                hasTouchingRanges = true;
            }
        }
        if (canReduceOperations) {
            operations = this._reduceOperations(operations);
        }
        // Delta encode operations
        const reverseRanges = (computeUndoEdits || recordTrimAutoWhitespace ? PieceTreeTextBuffer._getInverseEditRanges(operations) : []);
        const newTrimAutoWhitespaceCandidates = [];
        if (recordTrimAutoWhitespace) {
            for (let i = 0; i < operations.length; i++) {
                const op = operations[i];
                const reverseRange = reverseRanges[i];
                if (op.isAutoWhitespaceEdit && op.range.isEmpty()) {
                    // Record already the future line numbers that might be auto whitespace removal candidates on next edit
                    for (let lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) {
                        let currentLineContent = '';
                        if (lineNumber === reverseRange.startLineNumber) {
                            currentLineContent = this.getLineContent(op.range.startLineNumber);
                            if (strings_firstNonWhitespaceIndex(currentLineContent) !== -1) {
                                continue;
                            }
                        }
                        newTrimAutoWhitespaceCandidates.push({ lineNumber: lineNumber, oldContent: currentLineContent });
                    }
                }
            }
        }
        let reverseOperations = null;
        if (computeUndoEdits) {
            let reverseRangeDeltaOffset = 0;
            reverseOperations = [];
            for (let i = 0; i < operations.length; i++) {
                const op = operations[i];
                const reverseRange = reverseRanges[i];
                const bufferText = this.getValueInRange(op.range);
                const reverseRangeOffset = op.rangeOffset + reverseRangeDeltaOffset;
                reverseRangeDeltaOffset += (op.text.length - bufferText.length);
                reverseOperations[i] = {
                    sortIndex: op.sortIndex,
                    identifier: op.identifier,
                    range: reverseRange,
                    text: bufferText,
                    textChange: new TextChange(op.rangeOffset, bufferText, reverseRangeOffset, op.text)
                };
            }
            // Can only sort reverse operations when the order is not significant
            if (!hasTouchingRanges) {
                reverseOperations.sort((a, b) => a.sortIndex - b.sortIndex);
            }
        }
        this._mightContainRTL = mightContainRTL;
        this._mightContainUnusualLineTerminators = mightContainUnusualLineTerminators;
        this._mightContainNonBasicASCII = mightContainNonBasicASCII;
        const contentChanges = this._doApplyEdits(operations);
        let trimAutoWhitespaceLineNumbers = null;
        if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) {
            // sort line numbers auto whitespace removal candidates for next edit descending
            newTrimAutoWhitespaceCandidates.sort((a, b) => b.lineNumber - a.lineNumber);
            trimAutoWhitespaceLineNumbers = [];
            for (let i = 0, len = newTrimAutoWhitespaceCandidates.length; i < len; i++) {
                const lineNumber = newTrimAutoWhitespaceCandidates[i].lineNumber;
                if (i > 0 && newTrimAutoWhitespaceCandidates[i - 1].lineNumber === lineNumber) {
                    // Do not have the same line number twice
                    continue;
                }
                const prevContent = newTrimAutoWhitespaceCandidates[i].oldContent;
                const lineContent = this.getLineContent(lineNumber);
                if (lineContent.length === 0 || lineContent === prevContent || strings_firstNonWhitespaceIndex(lineContent) !== -1) {
                    continue;
                }
                trimAutoWhitespaceLineNumbers.push(lineNumber);
            }
        }
        this._onDidChangeContent.fire();
        return new ApplyEditsResult(reverseOperations, contentChanges, trimAutoWhitespaceLineNumbers);
    }
    /**
     * Transform operations such that they represent the same logic edit,
     * but that they also do not cause OOM crashes.
     */
    _reduceOperations(operations) {
        if (operations.length < 1000) {
            // We know from empirical testing that a thousand edits work fine regardless of their shape.
            return operations;
        }
        // At one point, due to how events are emitted and how each operation is handled,
        // some operations can trigger a high amount of temporary string allocations,
        // that will immediately get edited again.
        // e.g. a formatter inserting ridiculous ammounts of \n on a model with a single line
        // Therefore, the strategy is to collapse all the operations into a huge single edit operation
        return [this._toSingleEditOperation(operations)];
    }
    _toSingleEditOperation(operations) {
        let forceMoveMarkers = false;
        const firstEditRange = operations[0].range;
        const lastEditRange = operations[operations.length - 1].range;
        const entireEditRange = new Range(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn);
        let lastEndLineNumber = firstEditRange.startLineNumber;
        let lastEndColumn = firstEditRange.startColumn;
        const result = [];
        for (let i = 0, len = operations.length; i < len; i++) {
            const operation = operations[i];
            const range = operation.range;
            forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers;
            // (1) -- Push old text
            result.push(this.getValueInRange(new Range(lastEndLineNumber, lastEndColumn, range.startLineNumber, range.startColumn)));
            // (2) -- Push new text
            if (operation.text.length > 0) {
                result.push(operation.text);
            }
            lastEndLineNumber = range.endLineNumber;
            lastEndColumn = range.endColumn;
        }
        const text = result.join('');
        const [eolCount, firstLineLength, lastLineLength] = countEOL(text);
        return {
            sortIndex: 0,
            identifier: operations[0].identifier,
            range: entireEditRange,
            rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn),
            rangeLength: this.getValueLengthInRange(entireEditRange, 0 /* EndOfLinePreference.TextDefined */),
            text: text,
            eolCount: eolCount,
            firstLineLength: firstLineLength,
            lastLineLength: lastLineLength,
            forceMoveMarkers: forceMoveMarkers,
            isAutoWhitespaceEdit: false
        };
    }
    _doApplyEdits(operations) {
        operations.sort(PieceTreeTextBuffer._sortOpsDescending);
        const contentChanges = [];
        // operations are from bottom to top
        for (let i = 0; i < operations.length; i++) {
            const op = operations[i];
            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) {
                // no-op
                continue;
            }
            if (op.text) {
                // replacement
                this._pieceTree.delete(op.rangeOffset, op.rangeLength);
                this._pieceTree.insert(op.rangeOffset, op.text, true);
            }
            else {
                // deletion
                this._pieceTree.delete(op.rangeOffset, op.rangeLength);
            }
            const contentChangeRange = new Range(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._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
    }
    /**
     * Assumes `operations` are validated and sorted ascending
     */
    static _getInverseEditRanges(operations) {
        const result = [];
        let prevOpEndLineNumber = 0;
        let prevOpEndColumn = 0;
        let prevOp = null;
        for (let i = 0, len = operations.length; i < len; i++) {
            const op = operations[i];
            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) {
                // the operation inserts something
                const lineCount = op.eolCount + 1;
                if (lineCount === 1) {
                    // single line insert
                    resultRange = new Range(startLineNumber, startColumn, startLineNumber, startColumn + op.firstLineLength);
                }
                else {
                    // multi line insert
                    resultRange = new Range(startLineNumber, startColumn, startLineNumber + lineCount - 1, op.lastLineLength + 1);
                }
            }
            else {
                // There is nothing to insert
                resultRange = new Range(startLineNumber, startColumn, startLineNumber, startColumn);
            }
            prevOpEndLineNumber = resultRange.endLineNumber;
            prevOpEndColumn = resultRange.endColumn;
            result.push(resultRange);
            prevOp = op;
        }
        return result;
    }
    static _sortOpsAscending(a, b) {
        const r = Range.compareRangesUsingEnds(a.range, b.range);
        if (r === 0) {
            return a.sortIndex - b.sortIndex;
        }
        return r;
    }
    static _sortOpsDescending(a, b) {
        const r = Range.compareRangesUsingEnds(a.range, b.range);
        if (r === 0) {
            return b.sortIndex - a.sortIndex;
        }
        return -r;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class PieceTreeTextBufferFactory {
    constructor(_chunks, _bom, _cr, _lf, _crlf, _containsRTL, _containsUnusualLineTerminators, _isBasicASCII, _normalizeEOL) {
        this._chunks = _chunks;
        this._bom = _bom;
        this._cr = _cr;
        this._lf = _lf;
        this._crlf = _crlf;
        this._containsRTL = _containsRTL;
        this._containsUnusualLineTerminators = _containsUnusualLineTerminators;
        this._isBasicASCII = _isBasicASCII;
        this._normalizeEOL = _normalizeEOL;
    }
    _getEOL(defaultEOL) {
        const totalEOLCount = this._cr + this._lf + this._crlf;
        const totalCRCount = this._cr + this._crlf;
        if (totalEOLCount === 0) {
            // This is an empty file or a file with precisely one line
            return (defaultEOL === 1 /* DefaultEndOfLine.LF */ ? '\n' : '\r\n');
        }
        if (totalCRCount > totalEOLCount / 2) {
            // More than half of the file contains \r\n ending lines
            return '\r\n';
        }
        // At least one line more ends in \n
        return '\n';
    }
    create(defaultEOL) {
        const eol = this._getEOL(defaultEOL);
        const chunks = this._chunks;
        if (this._normalizeEOL &&
            ((eol === '\r\n' && (this._cr > 0 || this._lf > 0))
                || (eol === '\n' && (this._cr > 0 || this._crlf > 0)))) {
            // Normalize pieces
            for (let i = 0, len = chunks.length; i < len; i++) {
                const str = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol);
                const newLineStart = createLineStartsFast(str);
                chunks[i] = new StringBuffer(str, newLineStart);
            }
        }
        const textBuffer = new PieceTreeTextBuffer(chunks, this._bom, eol, this._containsRTL, this._containsUnusualLineTerminators, this._isBasicASCII, this._normalizeEOL);
        return { textBuffer: textBuffer, disposable: textBuffer };
    }
}
class PieceTreeTextBufferBuilder {
    constructor() {
        this.chunks = [];
        this.BOM = '';
        this._hasPreviousChar = false;
        this._previousChar = 0;
        this._tmpLineStarts = [];
        this.cr = 0;
        this.lf = 0;
        this.crlf = 0;
        this.containsRTL = false;
        this.containsUnusualLineTerminators = false;
        this.isBasicASCII = true;
    }
    acceptChunk(chunk) {
        if (chunk.length === 0) {
            return;
        }
        if (this.chunks.length === 0) {
            if (startsWithUTF8BOM(chunk)) {
                this.BOM = UTF8_BOM_CHARACTER;
                chunk = chunk.substr(1);
            }
        }
        const lastChar = chunk.charCodeAt(chunk.length - 1);
        if (lastChar === 13 /* CharCode.CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
            // last character is \r or a high surrogate => keep it back
            this._acceptChunk1(chunk.substr(0, chunk.length - 1), false);
            this._hasPreviousChar = true;
            this._previousChar = lastChar;
        }
        else {
            this._acceptChunk1(chunk, false);
            this._hasPreviousChar = false;
            this._previousChar = lastChar;
        }
    }
    _acceptChunk1(chunk, allowEmptyStrings) {
        if (!allowEmptyStrings && chunk.length === 0) {
            // Nothing to do
            return;
        }
        if (this._hasPreviousChar) {
            this._acceptChunk2(String.fromCharCode(this._previousChar) + chunk);
        }
        else {
            this._acceptChunk2(chunk);
        }
    }
    _acceptChunk2(chunk) {
        const lineStarts = createLineStarts(this._tmpLineStarts, chunk);
        this.chunks.push(new StringBuffer(chunk, lineStarts.lineStarts));
        this.cr += lineStarts.cr;
        this.lf += lineStarts.lf;
        this.crlf += lineStarts.crlf;
        if (this.isBasicASCII) {
            this.isBasicASCII = lineStarts.isBasicASCII;
        }
        if (!this.isBasicASCII && !this.containsRTL) {
            // No need to check if it is basic ASCII
            this.containsRTL = strings_containsRTL(chunk);
        }
        if (!this.isBasicASCII && !this.containsUnusualLineTerminators) {
            // No need to check if it is basic ASCII
            this.containsUnusualLineTerminators = containsUnusualLineTerminators(chunk);
        }
    }
    finish(normalizeEOL = true) {
        this._finish();
        return new PieceTreeTextBufferFactory(this.chunks, this.BOM, this.cr, this.lf, this.crlf, this.containsRTL, this.containsUnusualLineTerminators, this.isBasicASCII, normalizeEOL);
    }
    _finish() {
        if (this.chunks.length === 0) {
            this._acceptChunk1('', true);
        }
        if (this._hasPreviousChar) {
            this._hasPreviousChar = false;
            // recreate last chunk
            const lastChunk = this.chunks[this.chunks.length - 1];
            lastChunk.buffer += String.fromCharCode(this._previousChar);
            const newLineStarts = createLineStartsFast(lastChunk.buffer);
            lastChunk.lineStarts = newLineStarts;
            if (this._previousChar === 13 /* CharCode.CarriageReturn */) {
                this.cr++;
            }
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/tokens/lineTokens.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class LineTokens {
    constructor(tokens, text, decoder) {
        this._lineTokensBrand = undefined;
        this._tokens = tokens;
        this._tokensCount = (this._tokens.length >>> 1);
        this._text = text;
        this._languageIdCodec = decoder;
    }
    static createEmpty(lineContent, decoder) {
        const defaultMetadata = LineTokens.defaultTokenMetadata;
        const tokens = new Uint32Array(2);
        tokens[0] = lineContent.length;
        tokens[1] = defaultMetadata;
        return new LineTokens(tokens, lineContent, decoder);
    }
    equals(other) {
        if (other instanceof LineTokens) {
            return this.slicedEquals(other, 0, this._tokensCount);
        }
        return false;
    }
    slicedEquals(other, sliceFromTokenIndex, sliceTokenCount) {
        if (this._text !== other._text) {
            return false;
        }
        if (this._tokensCount !== other._tokensCount) {
            return false;
        }
        const from = (sliceFromTokenIndex << 1);
        const to = from + (sliceTokenCount << 1);
        for (let i = from; i < to; i++) {
            if (this._tokens[i] !== other._tokens[i]) {
                return false;
            }
        }
        return true;
    }
    getLineContent() {
        return this._text;
    }
    getCount() {
        return this._tokensCount;
    }
    getStartOffset(tokenIndex) {
        if (tokenIndex > 0) {
            return this._tokens[(tokenIndex - 1) << 1];
        }
        return 0;
    }
    getMetadata(tokenIndex) {
        const metadata = this._tokens[(tokenIndex << 1) + 1];
        return metadata;
    }
    getLanguageId(tokenIndex) {
        const metadata = this._tokens[(tokenIndex << 1) + 1];
        const languageId = TokenMetadata.getLanguageId(metadata);
        return this._languageIdCodec.decodeLanguageId(languageId);
    }
    getStandardTokenType(tokenIndex) {
        const metadata = this._tokens[(tokenIndex << 1) + 1];
        return TokenMetadata.getTokenType(metadata);
    }
    getForeground(tokenIndex) {
        const metadata = this._tokens[(tokenIndex << 1) + 1];
        return TokenMetadata.getForeground(metadata);
    }
    getClassName(tokenIndex) {
        const metadata = this._tokens[(tokenIndex << 1) + 1];
        return TokenMetadata.getClassNameFromMetadata(metadata);
    }
    getInlineStyle(tokenIndex, colorMap) {
        const metadata = this._tokens[(tokenIndex << 1) + 1];
        return TokenMetadata.getInlineStyleFromMetadata(metadata, colorMap);
    }
    getPresentation(tokenIndex) {
        const metadata = this._tokens[(tokenIndex << 1) + 1];
        return TokenMetadata.getPresentationFromMetadata(metadata);
    }
    getEndOffset(tokenIndex) {
        return this._tokens[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 LineTokens.findIndexInTokensArray(this._tokens, offset);
    }
    inflate() {
        return this;
    }
    sliceAndInflate(startOffset, endOffset, deltaOffset) {
        return new SliceLineTokens(this, startOffset, endOffset, deltaOffset);
    }
    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;
    }
    /**
     * @pure
     * @param insertTokens Must be sorted by offset.
    */
    withInserted(insertTokens) {
        if (insertTokens.length === 0) {
            return this;
        }
        let nextOriginalTokenIdx = 0;
        let nextInsertTokenIdx = 0;
        let text = '';
        const newTokens = new Array();
        let originalEndOffset = 0;
        while (true) {
            const nextOriginalTokenEndOffset = nextOriginalTokenIdx < this._tokensCount ? this._tokens[nextOriginalTokenIdx << 1] : -1;
            const nextInsertToken = nextInsertTokenIdx < insertTokens.length ? insertTokens[nextInsertTokenIdx] : null;
            if (nextOriginalTokenEndOffset !== -1 && (nextInsertToken === null || nextOriginalTokenEndOffset <= nextInsertToken.offset)) {
                // original token ends before next insert token
                text += this._text.substring(originalEndOffset, nextOriginalTokenEndOffset);
                const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1];
                newTokens.push(text.length, metadata);
                nextOriginalTokenIdx++;
                originalEndOffset = nextOriginalTokenEndOffset;
            }
            else if (nextInsertToken) {
                if (nextInsertToken.offset > originalEndOffset) {
                    // insert token is in the middle of the next token.
                    text += this._text.substring(originalEndOffset, nextInsertToken.offset);
                    const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1];
                    newTokens.push(text.length, metadata);
                    originalEndOffset = nextInsertToken.offset;
                }
                text += nextInsertToken.text;
                newTokens.push(text.length, nextInsertToken.tokenMetadata);
                nextInsertTokenIdx++;
            }
            else {
                break;
            }
        }
        return new LineTokens(new Uint32Array(newTokens), text, this._languageIdCodec);
    }
}
LineTokens.defaultTokenMetadata = ((0 /* FontStyle.None */ << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
    | (1 /* ColorId.DefaultForeground */ << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
    | (2 /* ColorId.DefaultBackground */ << 24 /* MetadataConsts.BACKGROUND_OFFSET */)) >>> 0;
class SliceLineTokens {
    constructor(source, startOffset, endOffset, deltaOffset) {
        this._source = source;
        this._startOffset = startOffset;
        this._endOffset = endOffset;
        this._deltaOffset = deltaOffset;
        this._firstTokenIndex = source.findTokenIndexAtOffset(startOffset);
        this._tokensCount = 0;
        for (let i = this._firstTokenIndex, len = source.getCount(); i < len; i++) {
            const tokenStartOffset = source.getStartOffset(i);
            if (tokenStartOffset >= endOffset) {
                break;
            }
            this._tokensCount++;
        }
    }
    getMetadata(tokenIndex) {
        return this._source.getMetadata(this._firstTokenIndex + tokenIndex);
    }
    getLanguageId(tokenIndex) {
        return this._source.getLanguageId(this._firstTokenIndex + tokenIndex);
    }
    getLineContent() {
        return this._source.getLineContent().substring(this._startOffset, this._endOffset);
    }
    equals(other) {
        if (other instanceof SliceLineTokens) {
            return (this._startOffset === other._startOffset
                && this._endOffset === other._endOffset
                && this._deltaOffset === other._deltaOffset
                && this._source.slicedEquals(other._source, this._firstTokenIndex, this._tokensCount));
        }
        return false;
    }
    getCount() {
        return this._tokensCount;
    }
    getForeground(tokenIndex) {
        return this._source.getForeground(this._firstTokenIndex + tokenIndex);
    }
    getEndOffset(tokenIndex) {
        const tokenEndOffset = this._source.getEndOffset(this._firstTokenIndex + tokenIndex);
        return Math.min(this._endOffset, tokenEndOffset) - this._startOffset + this._deltaOffset;
    }
    getClassName(tokenIndex) {
        return this._source.getClassName(this._firstTokenIndex + tokenIndex);
    }
    getInlineStyle(tokenIndex, colorMap) {
        return this._source.getInlineStyle(this._firstTokenIndex + tokenIndex, colorMap);
    }
    getPresentation(tokenIndex) {
        return this._source.getPresentation(this._firstTokenIndex + tokenIndex);
    }
    findTokenIndexAtOffset(offset) {
        return this._source.findTokenIndexAtOffset(offset + this._startOffset - this._deltaOffset) - this._firstTokenIndex;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/tokenizationRegistry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var tokenizationRegistry_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};


class TokenizationRegistry {
    constructor() {
        this._map = new Map();
        this._factories = new Map();
        this._onDidChange = new Emitter();
        this.onDidChange = this._onDidChange.event;
        this._colorMap = null;
    }
    fire(languages) {
        this._onDidChange.fire({
            changedLanguages: languages,
            changedColorMap: false
        });
    }
    register(language, support) {
        this._map.set(language, support);
        this.fire([language]);
        return toDisposable(() => {
            if (this._map.get(language) !== support) {
                return;
            }
            this._map.delete(language);
            this.fire([language]);
        });
    }
    registerFactory(languageId, factory) {
        var _a;
        (_a = this._factories.get(languageId)) === null || _a === void 0 ? void 0 : _a.dispose();
        const myData = new TokenizationSupportFactoryData(this, languageId, factory);
        this._factories.set(languageId, myData);
        return toDisposable(() => {
            const v = this._factories.get(languageId);
            if (!v || v !== myData) {
                return;
            }
            this._factories.delete(languageId);
            v.dispose();
        });
    }
    getOrCreate(languageId) {
        return tokenizationRegistry_awaiter(this, void 0, void 0, function* () {
            // check first if the support is already set
            const tokenizationSupport = this.get(languageId);
            if (tokenizationSupport) {
                return tokenizationSupport;
            }
            const factory = this._factories.get(languageId);
            if (!factory || factory.isResolved) {
                // no factory or factory.resolve already finished
                return null;
            }
            yield factory.resolve();
            return this.get(languageId);
        });
    }
    get(language) {
        return (this._map.get(language) || null);
    }
    isResolved(languageId) {
        const tokenizationSupport = this.get(languageId);
        if (tokenizationSupport) {
            return true;
        }
        const factory = this._factories.get(languageId);
        if (!factory || factory.isResolved) {
            return true;
        }
        return false;
    }
    setColorMap(colorMap) {
        this._colorMap = colorMap;
        this._onDidChange.fire({
            changedLanguages: Array.from(this._map.keys()),
            changedColorMap: true
        });
    }
    getColorMap() {
        return this._colorMap;
    }
    getDefaultBackground() {
        if (this._colorMap && this._colorMap.length > 2 /* ColorId.DefaultBackground */) {
            return this._colorMap[2 /* ColorId.DefaultBackground */];
        }
        return null;
    }
}
class TokenizationSupportFactoryData extends Disposable {
    constructor(_registry, _languageId, _factory) {
        super();
        this._registry = _registry;
        this._languageId = _languageId;
        this._factory = _factory;
        this._isDisposed = false;
        this._resolvePromise = null;
        this._isResolved = false;
    }
    get isResolved() {
        return this._isResolved;
    }
    dispose() {
        this._isDisposed = true;
        super.dispose();
    }
    resolve() {
        return tokenizationRegistry_awaiter(this, void 0, void 0, function* () {
            if (!this._resolvePromise) {
                this._resolvePromise = this._create();
            }
            return this._resolvePromise;
        });
    }
    _create() {
        return tokenizationRegistry_awaiter(this, void 0, void 0, function* () {
            const value = yield Promise.resolve(this._factory.createTokenizationSupport());
            this._isResolved = true;
            if (value && !this._isDisposed) {
                this._register(this._registry.register(this._languageId, value));
            }
        });
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class languages_Token {
    constructor(offset, type, language) {
        this._tokenBrand = undefined;
        this.offset = offset;
        this.type = type;
        this.language = language;
    }
    toString() {
        return '(' + this.offset + ', ' + this.type + ')';
    }
}
/**
 * @internal
 */
class TokenizationResult {
    constructor(tokens, endState) {
        this._tokenizationResultBrand = undefined;
        this.tokens = tokens;
        this.endState = endState;
    }
}
/**
 * @internal
 */
class EncodedTokenizationResult {
    constructor(tokens, endState) {
        this._encodedTokenizationResultBrand = undefined;
        this.tokens = tokens;
        this.endState = endState;
    }
}
/**
 * @internal
 */
var CompletionItemKinds;
(function (CompletionItemKinds) {
    const byKind = new Map();
    byKind.set(0 /* CompletionItemKind.Method */, Codicon.symbolMethod);
    byKind.set(1 /* CompletionItemKind.Function */, Codicon.symbolFunction);
    byKind.set(2 /* CompletionItemKind.Constructor */, Codicon.symbolConstructor);
    byKind.set(3 /* CompletionItemKind.Field */, Codicon.symbolField);
    byKind.set(4 /* CompletionItemKind.Variable */, Codicon.symbolVariable);
    byKind.set(5 /* CompletionItemKind.Class */, Codicon.symbolClass);
    byKind.set(6 /* CompletionItemKind.Struct */, Codicon.symbolStruct);
    byKind.set(7 /* CompletionItemKind.Interface */, Codicon.symbolInterface);
    byKind.set(8 /* CompletionItemKind.Module */, Codicon.symbolModule);
    byKind.set(9 /* CompletionItemKind.Property */, Codicon.symbolProperty);
    byKind.set(10 /* CompletionItemKind.Event */, Codicon.symbolEvent);
    byKind.set(11 /* CompletionItemKind.Operator */, Codicon.symbolOperator);
    byKind.set(12 /* CompletionItemKind.Unit */, Codicon.symbolUnit);
    byKind.set(13 /* CompletionItemKind.Value */, Codicon.symbolValue);
    byKind.set(15 /* CompletionItemKind.Enum */, Codicon.symbolEnum);
    byKind.set(14 /* CompletionItemKind.Constant */, Codicon.symbolConstant);
    byKind.set(15 /* CompletionItemKind.Enum */, Codicon.symbolEnum);
    byKind.set(16 /* CompletionItemKind.EnumMember */, Codicon.symbolEnumMember);
    byKind.set(17 /* CompletionItemKind.Keyword */, Codicon.symbolKeyword);
    byKind.set(27 /* CompletionItemKind.Snippet */, Codicon.symbolSnippet);
    byKind.set(18 /* CompletionItemKind.Text */, Codicon.symbolText);
    byKind.set(19 /* CompletionItemKind.Color */, Codicon.symbolColor);
    byKind.set(20 /* CompletionItemKind.File */, Codicon.symbolFile);
    byKind.set(21 /* CompletionItemKind.Reference */, Codicon.symbolReference);
    byKind.set(22 /* CompletionItemKind.Customcolor */, Codicon.symbolCustomColor);
    byKind.set(23 /* CompletionItemKind.Folder */, Codicon.symbolFolder);
    byKind.set(24 /* CompletionItemKind.TypeParameter */, Codicon.symbolTypeParameter);
    byKind.set(25 /* CompletionItemKind.User */, Codicon.account);
    byKind.set(26 /* CompletionItemKind.Issue */, Codicon.issues);
    /**
     * @internal
     */
    function toIcon(kind) {
        let codicon = byKind.get(kind);
        if (!codicon) {
            console.info('No codicon found for CompletionItemKind ' + kind);
            codicon = Codicon.symbolProperty;
        }
        return codicon;
    }
    CompletionItemKinds.toIcon = toIcon;
    const data = 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 */);
    /**
     * @internal
     */
    function fromString(value, strict) {
        let res = data.get(value);
        if (typeof res === 'undefined' && !strict) {
            res = 9 /* CompletionItemKind.Property */;
        }
        return res;
    }
    CompletionItemKinds.fromString = fromString;
})(CompletionItemKinds || (CompletionItemKinds = {}));
/**
 * How an {@link InlineCompletionsProvider inline completion provider} was triggered.
 */
var InlineCompletionTriggerKind;
(function (InlineCompletionTriggerKind) {
    /**
     * Completion was triggered automatically while editing.
     * It is sufficient to return a single completion item in this case.
     */
    InlineCompletionTriggerKind[InlineCompletionTriggerKind["Automatic"] = 0] = "Automatic";
    /**
     * Completion was triggered explicitly by a user gesture.
     * Return multiple completion items to enable cycling through them.
     */
    InlineCompletionTriggerKind[InlineCompletionTriggerKind["Explicit"] = 1] = "Explicit";
})(InlineCompletionTriggerKind || (InlineCompletionTriggerKind = {}));
var SignatureHelpTriggerKind;
(function (SignatureHelpTriggerKind) {
    SignatureHelpTriggerKind[SignatureHelpTriggerKind["Invoke"] = 1] = "Invoke";
    SignatureHelpTriggerKind[SignatureHelpTriggerKind["TriggerCharacter"] = 2] = "TriggerCharacter";
    SignatureHelpTriggerKind[SignatureHelpTriggerKind["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind || (SignatureHelpTriggerKind = {}));
/**
 * A document highlight kind.
 */
var DocumentHighlightKind;
(function (DocumentHighlightKind) {
    /**
     * A textual occurrence.
     */
    DocumentHighlightKind[DocumentHighlightKind["Text"] = 0] = "Text";
    /**
     * Read-access of a symbol, like reading a variable.
     */
    DocumentHighlightKind[DocumentHighlightKind["Read"] = 1] = "Read";
    /**
     * Write-access of a symbol, like writing to a variable.
     */
    DocumentHighlightKind[DocumentHighlightKind["Write"] = 2] = "Write";
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
/**
 * @internal
 */
function isLocationLink(thing) {
    return thing
        && URI.isUri(thing.uri)
        && Range.isIRange(thing.range)
        && (Range.isIRange(thing.originSelectionRange) || Range.isIRange(thing.targetSelectionRange));
}
/**
 * @internal
 */
var SymbolKinds;
(function (SymbolKinds) {
    const byKind = new Map();
    byKind.set(0 /* SymbolKind.File */, Codicon.symbolFile);
    byKind.set(1 /* SymbolKind.Module */, Codicon.symbolModule);
    byKind.set(2 /* SymbolKind.Namespace */, Codicon.symbolNamespace);
    byKind.set(3 /* SymbolKind.Package */, Codicon.symbolPackage);
    byKind.set(4 /* SymbolKind.Class */, Codicon.symbolClass);
    byKind.set(5 /* SymbolKind.Method */, Codicon.symbolMethod);
    byKind.set(6 /* SymbolKind.Property */, Codicon.symbolProperty);
    byKind.set(7 /* SymbolKind.Field */, Codicon.symbolField);
    byKind.set(8 /* SymbolKind.Constructor */, Codicon.symbolConstructor);
    byKind.set(9 /* SymbolKind.Enum */, Codicon.symbolEnum);
    byKind.set(10 /* SymbolKind.Interface */, Codicon.symbolInterface);
    byKind.set(11 /* SymbolKind.Function */, Codicon.symbolFunction);
    byKind.set(12 /* SymbolKind.Variable */, Codicon.symbolVariable);
    byKind.set(13 /* SymbolKind.Constant */, Codicon.symbolConstant);
    byKind.set(14 /* SymbolKind.String */, Codicon.symbolString);
    byKind.set(15 /* SymbolKind.Number */, Codicon.symbolNumber);
    byKind.set(16 /* SymbolKind.Boolean */, Codicon.symbolBoolean);
    byKind.set(17 /* SymbolKind.Array */, Codicon.symbolArray);
    byKind.set(18 /* SymbolKind.Object */, Codicon.symbolObject);
    byKind.set(19 /* SymbolKind.Key */, Codicon.symbolKey);
    byKind.set(20 /* SymbolKind.Null */, Codicon.symbolNull);
    byKind.set(21 /* SymbolKind.EnumMember */, Codicon.symbolEnumMember);
    byKind.set(22 /* SymbolKind.Struct */, Codicon.symbolStruct);
    byKind.set(23 /* SymbolKind.Event */, Codicon.symbolEvent);
    byKind.set(24 /* SymbolKind.Operator */, Codicon.symbolOperator);
    byKind.set(25 /* SymbolKind.TypeParameter */, Codicon.symbolTypeParameter);
    /**
     * @internal
     */
    function toIcon(kind) {
        let icon = byKind.get(kind);
        if (!icon) {
            console.info('No codicon found for SymbolKind ' + kind);
            icon = Codicon.symbolProperty;
        }
        return icon;
    }
    SymbolKinds.toIcon = toIcon;
})(SymbolKinds || (SymbolKinds = {}));
class FoldingRangeKind {
    /**
     * Creates a new {@link FoldingRangeKind}.
     *
     * @param value of the kind.
     */
    constructor(value) {
        this.value = value;
    }
}
/**
 * Kind for folding range representing a comment. The value of the kind is 'comment'.
 */
FoldingRangeKind.Comment = new FoldingRangeKind('comment');
/**
 * Kind for folding range representing a import. The value of the kind is 'imports'.
 */
FoldingRangeKind.Imports = new FoldingRangeKind('imports');
/**
 * Kind for folding range representing regions (for example marked by `#region`, `#endregion`).
 * The value of the kind is 'region'.
 */
FoldingRangeKind.Region = new FoldingRangeKind('region');
/**
 * @internal
 */
var languages_Command;
(function (Command) {
    /**
     * @internal
     */
    function is(obj) {
        if (!obj || typeof obj !== 'object') {
            return false;
        }
        return typeof obj.id === 'string' &&
            typeof obj.title === 'string';
    }
    Command.is = is;
})(languages_Command || (languages_Command = {}));
var InlayHintKind;
(function (InlayHintKind) {
    InlayHintKind[InlayHintKind["Type"] = 1] = "Type";
    InlayHintKind[InlayHintKind["Parameter"] = 2] = "Parameter";
})(InlayHintKind || (InlayHintKind = {}));
/**
 * @internal
 */
const languages_TokenizationRegistry = new TokenizationRegistry();

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/nullTokenize.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const NullState = new class {
    clone() {
        return this;
    }
    equals(other) {
        return (this === other);
    }
};
function nullTokenize(languageId, state) {
    return new TokenizationResult([new languages_Token(0, '', languageId)], state);
}
function nullTokenizeEncoded(languageId, state) {
    const tokens = new Uint32Array(2);
    tokens[0] = 0;
    tokens[1] = ((languageId << 0 /* MetadataConsts.LANGUAGEID_OFFSET */)
        | (0 /* StandardTokenType.Other */ << 8 /* MetadataConsts.TOKEN_TYPE_OFFSET */)
        | (0 /* FontStyle.None */ << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
        | (1 /* ColorId.DefaultForeground */ << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
        | (2 /* ColorId.DefaultBackground */ << 24 /* MetadataConsts.BACKGROUND_OFFSET */)) >>> 0;
    return new EncodedTokenizationResult(tokens, state === null ? NullState : state);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/tokens/contiguousMultilineTokens.js
/**
 * Represents contiguous tokens over a contiguous range of lines.
 */
class ContiguousMultilineTokens {
    constructor(startLineNumber, tokens) {
        this._startLineNumber = startLineNumber;
        this._tokens = tokens;
    }
    /**
     * (Inclusive) start line number for these tokens.
     */
    get startLineNumber() {
        return this._startLineNumber;
    }
    /**
     * (Inclusive) end line number for these tokens.
     */
    get endLineNumber() {
        return this._startLineNumber + this._tokens.length - 1;
    }
    /**
     * @see {@link _tokens}
     */
    getLineTokens(lineNumber) {
        return this._tokens[lineNumber - this._startLineNumber];
    }
    appendLineTokens(lineTokens) {
        this._tokens.push(lineTokens);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/tokens/contiguousMultilineTokensBuilder.js

class ContiguousMultilineTokensBuilder {
    constructor() {
        this._tokens = [];
    }
    add(lineNumber, lineTokens) {
        if (this._tokens.length > 0) {
            const last = this._tokens[this._tokens.length - 1];
            if (last.endLineNumber + 1 === lineNumber) {
                // append
                last.appendLineTokens(lineTokens);
                return;
            }
        }
        this._tokens.push(new ContiguousMultilineTokens(lineNumber, [lineTokens]));
    }
    finalize() {
        return this._tokens;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/textModelTokens.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/











/**
 * An array that avoids being sparse by always
 * filling up unused indices with a default value.
 */
class ContiguousGrowingArray {
    constructor(_default) {
        this._default = _default;
        this._store = [];
    }
    get(index) {
        if (index < this._store.length) {
            return this._store[index];
        }
        return this._default;
    }
    set(index, value) {
        while (index >= this._store.length) {
            this._store[this._store.length] = this._default;
        }
        this._store[index] = value;
    }
    delete(deleteIndex, deleteCount) {
        if (deleteCount === 0 || deleteIndex >= this._store.length) {
            return;
        }
        this._store.splice(deleteIndex, deleteCount);
    }
    insert(insertIndex, insertCount) {
        if (insertCount === 0 || insertIndex >= this._store.length) {
            return;
        }
        const arr = [];
        for (let i = 0; i < insertCount; i++) {
            arr[i] = this._default;
        }
        this._store = arrayInsert(this._store, insertIndex, arr);
    }
}
/**
 * Stores the states at the start of each line and keeps track of which lines
 * must be retokenized. Also uses state equality to quickly validate lines
 * that don't need to be retokenized.
 *
 * For example, when typing on a line, the line gets marked as needing to be tokenized.
 * Once the line is tokenized, the end state is checked for equality against the begin
 * state of the next line. If the states are equal, tokenization doesn't need to run
 * again over the rest of the file. If the states are not equal, the next line gets marked
 * as needing to be tokenized.
 */
class TokenizationStateStore {
    constructor(tokenizationSupport, initialState) {
        this.tokenizationSupport = tokenizationSupport;
        this.initialState = initialState;
        /**
         * `lineBeginState[i]` contains the begin state used to tokenize line number `i + 1`.
         */
        this._lineBeginState = new ContiguousGrowingArray(null);
        /**
         * `lineNeedsTokenization[i]` describes if line number `i + 1` needs to be tokenized.
         */
        this._lineNeedsTokenization = new ContiguousGrowingArray(true);
        this._firstLineNeedsTokenization = 0;
        this._lineBeginState.set(0, this.initialState);
    }
    get invalidLineStartIndex() {
        return this._firstLineNeedsTokenization;
    }
    markMustBeTokenized(lineIndex) {
        this._lineNeedsTokenization.set(lineIndex, true);
        this._firstLineNeedsTokenization = Math.min(this._firstLineNeedsTokenization, lineIndex);
    }
    getBeginState(lineIndex) {
        return this._lineBeginState.get(lineIndex);
    }
    setEndState(linesLength, lineIndex, endState) {
        this._lineNeedsTokenization.set(lineIndex, false);
        this._firstLineNeedsTokenization = lineIndex + 1;
        // Check if this was the last line
        if (lineIndex === linesLength - 1) {
            return;
        }
        // Check if the end state has changed
        const previousEndState = this._lineBeginState.get(lineIndex + 1);
        if (previousEndState === null || !endState.equals(previousEndState)) {
            this._lineBeginState.set(lineIndex + 1, endState);
            this.markMustBeTokenized(lineIndex + 1);
            return;
        }
        // Perhaps we can skip tokenizing some lines...
        let i = lineIndex + 1;
        while (i < linesLength) {
            if (this._lineNeedsTokenization.get(i)) {
                break;
            }
            i++;
        }
        this._firstLineNeedsTokenization = i;
    }
    //#region Editing
    applyEdits(range, eolCount) {
        this.markMustBeTokenized(range.startLineNumber - 1);
        this._lineBeginState.delete(range.startLineNumber, range.endLineNumber - range.startLineNumber);
        this._lineNeedsTokenization.delete(range.startLineNumber, range.endLineNumber - range.startLineNumber);
        this._lineBeginState.insert(range.startLineNumber, eolCount);
        this._lineNeedsTokenization.insert(range.startLineNumber, eolCount);
    }
}
class TextModelTokenization extends Disposable {
    constructor(_textModel, _tokenizationPart, _languageIdCodec) {
        super();
        this._textModel = _textModel;
        this._tokenizationPart = _tokenizationPart;
        this._languageIdCodec = _languageIdCodec;
        this._isScheduled = false;
        this._isDisposed = false;
        this._tokenizationStateStore = null;
        this._register(languages_TokenizationRegistry.onDidChange((e) => {
            const languageId = this._textModel.getLanguageId();
            if (e.changedLanguages.indexOf(languageId) === -1) {
                return;
            }
            this._resetTokenizationState();
            this._tokenizationPart.clearTokens();
        }));
        this._resetTokenizationState();
    }
    dispose() {
        this._isDisposed = true;
        super.dispose();
    }
    //#region TextModel events
    handleDidChangeContent(e) {
        if (e.isFlush) {
            this._resetTokenizationState();
            return;
        }
        if (this._tokenizationStateStore) {
            for (let i = 0, len = e.changes.length; i < len; i++) {
                const change = e.changes[i];
                const [eolCount] = countEOL(change.text);
                this._tokenizationStateStore.applyEdits(change.range, eolCount);
            }
        }
        this._beginBackgroundTokenization();
    }
    handleDidChangeAttached() {
        this._beginBackgroundTokenization();
    }
    handleDidChangeLanguage(e) {
        this._resetTokenizationState();
        this._tokenizationPart.clearTokens();
    }
    //#endregion
    _resetTokenizationState() {
        const [tokenizationSupport, initialState] = initializeTokenization(this._textModel, this._tokenizationPart);
        if (tokenizationSupport && initialState) {
            this._tokenizationStateStore = new TokenizationStateStore(tokenizationSupport, initialState);
        }
        else {
            this._tokenizationStateStore = null;
        }
        this._beginBackgroundTokenization();
    }
    _beginBackgroundTokenization() {
        if (this._isScheduled || !this._textModel.isAttachedToEditor() || !this._hasLinesToTokenize()) {
            return;
        }
        this._isScheduled = true;
        runWhenIdle((deadline) => {
            this._isScheduled = false;
            this._backgroundTokenizeWithDeadline(deadline);
        });
    }
    /**
     * Tokenize until the deadline occurs, but try to yield every 1-2ms.
     */
    _backgroundTokenizeWithDeadline(deadline) {
        // Read the time remaining from the `deadline` immediately because it is unclear
        // if the `deadline` object will be valid after execution leaves this function.
        const endTime = Date.now() + deadline.timeRemaining();
        const execute = () => {
            if (this._isDisposed || !this._textModel.isAttachedToEditor() || !this._hasLinesToTokenize()) {
                // disposed in the meantime or detached or finished
                return;
            }
            this._backgroundTokenizeForAtLeast1ms();
            if (Date.now() < endTime) {
                // There is still time before reaching the deadline, so yield to the browser and then
                // continue execution
                setTimeout0(execute);
            }
            else {
                // The deadline has been reached, so schedule a new idle callback if necessary
                this._beginBackgroundTokenization();
            }
        };
        execute();
    }
    /**
     * Tokenize for at least 1ms.
     */
    _backgroundTokenizeForAtLeast1ms() {
        const lineCount = this._textModel.getLineCount();
        const builder = new ContiguousMultilineTokensBuilder();
        const sw = StopWatch.create(false);
        do {
            if (sw.elapsed() > 1) {
                // the comparison is intentionally > 1 and not >= 1 to ensure that
                // a full millisecond has elapsed, given how microseconds are rounded
                // to milliseconds
                break;
            }
            const tokenizedLineNumber = this._tokenizeOneInvalidLine(builder);
            if (tokenizedLineNumber >= lineCount) {
                break;
            }
        } while (this._hasLinesToTokenize());
        this._tokenizationPart.setTokens(builder.finalize(), this._isTokenizationComplete());
    }
    tokenizeViewport(startLineNumber, endLineNumber) {
        const builder = new ContiguousMultilineTokensBuilder();
        this._tokenizeViewport(builder, startLineNumber, endLineNumber);
        this._tokenizationPart.setTokens(builder.finalize(), this._isTokenizationComplete());
    }
    reset() {
        this._resetTokenizationState();
        this._tokenizationPart.clearTokens();
    }
    forceTokenization(lineNumber) {
        const builder = new ContiguousMultilineTokensBuilder();
        this._updateTokensUntilLine(builder, lineNumber);
        this._tokenizationPart.setTokens(builder.finalize(), this._isTokenizationComplete());
    }
    getTokenTypeIfInsertingCharacter(position, character) {
        if (!this._tokenizationStateStore) {
            return 0 /* StandardTokenType.Other */;
        }
        this.forceTokenization(position.lineNumber);
        const lineStartState = this._tokenizationStateStore.getBeginState(position.lineNumber - 1);
        if (!lineStartState) {
            return 0 /* StandardTokenType.Other */;
        }
        const languageId = this._textModel.getLanguageId();
        const lineContent = this._textModel.getLineContent(position.lineNumber);
        // Create the text as if `character` was inserted
        const text = (lineContent.substring(0, position.column - 1)
            + character
            + lineContent.substring(position.column - 1));
        const r = safeTokenize(this._languageIdCodec, languageId, this._tokenizationStateStore.tokenizationSupport, text, true, lineStartState);
        const lineTokens = new LineTokens(r.tokens, text, this._languageIdCodec);
        if (lineTokens.getCount() === 0) {
            return 0 /* StandardTokenType.Other */;
        }
        const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        return lineTokens.getStandardTokenType(tokenIndex);
    }
    tokenizeLineWithEdit(position, length, newText) {
        const lineNumber = position.lineNumber;
        const column = position.column;
        if (!this._tokenizationStateStore) {
            return null;
        }
        this.forceTokenization(lineNumber);
        const lineStartState = this._tokenizationStateStore.getBeginState(lineNumber - 1);
        if (!lineStartState) {
            return null;
        }
        const curLineContent = this._textModel.getLineContent(lineNumber);
        const newLineContent = curLineContent.substring(0, column - 1)
            + newText + curLineContent.substring(column - 1 + length);
        const languageId = this._textModel.getLanguageIdAtPosition(lineNumber, 0);
        const result = safeTokenize(this._languageIdCodec, languageId, this._tokenizationStateStore.tokenizationSupport, newLineContent, true, lineStartState);
        const lineTokens = new LineTokens(result.tokens, newLineContent, this._languageIdCodec);
        return lineTokens;
    }
    isCheapToTokenize(lineNumber) {
        if (!this._tokenizationStateStore) {
            return true;
        }
        const firstInvalidLineNumber = this._tokenizationStateStore.invalidLineStartIndex + 1;
        if (lineNumber > firstInvalidLineNumber) {
            return false;
        }
        if (lineNumber < firstInvalidLineNumber) {
            return true;
        }
        if (this._textModel.getLineLength(lineNumber) < 2048 /* Constants.CHEAP_TOKENIZATION_LENGTH_LIMIT */) {
            return true;
        }
        return false;
    }
    _hasLinesToTokenize() {
        if (!this._tokenizationStateStore) {
            return false;
        }
        return (this._tokenizationStateStore.invalidLineStartIndex < this._textModel.getLineCount());
    }
    _isTokenizationComplete() {
        if (!this._tokenizationStateStore) {
            return false;
        }
        return (this._tokenizationStateStore.invalidLineStartIndex >= this._textModel.getLineCount());
    }
    _tokenizeOneInvalidLine(builder) {
        if (!this._tokenizationStateStore || !this._hasLinesToTokenize()) {
            return this._textModel.getLineCount() + 1;
        }
        const lineNumber = this._tokenizationStateStore.invalidLineStartIndex + 1;
        this._updateTokensUntilLine(builder, lineNumber);
        return lineNumber;
    }
    _updateTokensUntilLine(builder, lineNumber) {
        if (!this._tokenizationStateStore) {
            return;
        }
        const languageId = this._textModel.getLanguageId();
        const linesLength = this._textModel.getLineCount();
        const endLineIndex = lineNumber - 1;
        // Validate all states up to and including endLineIndex
        for (let lineIndex = this._tokenizationStateStore.invalidLineStartIndex; lineIndex <= endLineIndex; lineIndex++) {
            const text = this._textModel.getLineContent(lineIndex + 1);
            const lineStartState = this._tokenizationStateStore.getBeginState(lineIndex);
            const r = safeTokenize(this._languageIdCodec, languageId, this._tokenizationStateStore.tokenizationSupport, text, true, lineStartState);
            builder.add(lineIndex + 1, r.tokens);
            this._tokenizationStateStore.setEndState(linesLength, lineIndex, r.endState);
            lineIndex = this._tokenizationStateStore.invalidLineStartIndex - 1; // -1 because the outer loop increments it
        }
    }
    _tokenizeViewport(builder, startLineNumber, endLineNumber) {
        if (!this._tokenizationStateStore) {
            // nothing to do
            return;
        }
        if (endLineNumber <= this._tokenizationStateStore.invalidLineStartIndex) {
            // nothing to do
            return;
        }
        if (startLineNumber <= this._tokenizationStateStore.invalidLineStartIndex) {
            // tokenization has reached the viewport start...
            this._updateTokensUntilLine(builder, endLineNumber);
            return;
        }
        let nonWhitespaceColumn = this._textModel.getLineFirstNonWhitespaceColumn(startLineNumber);
        const fakeLines = [];
        let initialState = null;
        for (let i = startLineNumber - 1; nonWhitespaceColumn > 1 && i >= 1; i--) {
            const newNonWhitespaceIndex = this._textModel.getLineFirstNonWhitespaceColumn(i);
            if (newNonWhitespaceIndex === 0) {
                continue;
            }
            if (newNonWhitespaceIndex < nonWhitespaceColumn) {
                fakeLines.push(this._textModel.getLineContent(i));
                nonWhitespaceColumn = newNonWhitespaceIndex;
                initialState = this._tokenizationStateStore.getBeginState(i - 1);
                if (initialState) {
                    break;
                }
            }
        }
        if (!initialState) {
            initialState = this._tokenizationStateStore.initialState;
        }
        const languageId = this._textModel.getLanguageId();
        let state = initialState;
        for (let i = fakeLines.length - 1; i >= 0; i--) {
            const r = safeTokenize(this._languageIdCodec, languageId, this._tokenizationStateStore.tokenizationSupport, fakeLines[i], false, state);
            state = r.endState;
        }
        for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
            const text = this._textModel.getLineContent(lineNumber);
            const r = safeTokenize(this._languageIdCodec, languageId, this._tokenizationStateStore.tokenizationSupport, text, true, state);
            builder.add(lineNumber, r.tokens);
            this._tokenizationStateStore.markMustBeTokenized(lineNumber - 1);
            state = r.endState;
        }
    }
}
function initializeTokenization(textModel, tokenizationPart) {
    if (textModel.isTooLargeForTokenization()) {
        return [null, null];
    }
    const tokenizationSupport = languages_TokenizationRegistry.get(tokenizationPart.getLanguageId());
    if (!tokenizationSupport) {
        return [null, null];
    }
    let initialState;
    try {
        initialState = tokenizationSupport.getInitialState();
    }
    catch (e) {
        onUnexpectedError(e);
        return [null, null];
    }
    return [tokenizationSupport, initialState];
}
function safeTokenize(languageIdCodec, languageId, tokenizationSupport, text, hasEOL, state) {
    let r = null;
    if (tokenizationSupport) {
        try {
            r = tokenizationSupport.tokenizeEncoded(text, hasEOL, state.clone());
        }
        catch (e) {
            onUnexpectedError(e);
        }
    }
    if (!r) {
        r = nullTokenizeEncoded(languageIdCodec.encodeLanguageId(languageId), state);
    }
    LineTokens.convertToEndOffset(r.tokens, text.length);
    return r;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/tokens/contiguousTokensEditing.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const EMPTY_LINE_TOKENS = (new Uint32Array(0)).buffer;
class ContiguousTokensEditing {
    static deleteBeginning(lineTokens, toChIndex) {
        if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
            return lineTokens;
        }
        return ContiguousTokensEditing.delete(lineTokens, 0, toChIndex);
    }
    static deleteEnding(lineTokens, fromChIndex) {
        if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
            return lineTokens;
        }
        const tokens = toUint32Array(lineTokens);
        const lineTextLength = tokens[tokens.length - 2];
        return ContiguousTokensEditing.delete(lineTokens, fromChIndex, lineTextLength);
    }
    static delete(lineTokens, fromChIndex, toChIndex) {
        if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS || fromChIndex === toChIndex) {
            return lineTokens;
        }
        const tokens = toUint32Array(lineTokens);
        const tokensCount = (tokens.length >>> 1);
        // special case: deleting everything
        if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) {
            return EMPTY_LINE_TOKENS;
        }
        const fromTokenIndex = LineTokens.findIndexInTokensArray(tokens, fromChIndex);
        const fromTokenStartOffset = (fromTokenIndex > 0 ? tokens[(fromTokenIndex - 1) << 1] : 0);
        const fromTokenEndOffset = tokens[fromTokenIndex << 1];
        if (toChIndex < fromTokenEndOffset) {
            // the delete range is inside a single token
            const delta = (toChIndex - fromChIndex);
            for (let i = fromTokenIndex; i < tokensCount; i++) {
                tokens[i << 1] -= delta;
            }
            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) {
            // nothing to trim
            return lineTokens;
        }
        const tmp = new Uint32Array(dest);
        tmp.set(tokens.subarray(0, dest), 0);
        return tmp.buffer;
    }
    static append(lineTokens, _otherTokens) {
        if (_otherTokens === EMPTY_LINE_TOKENS) {
            return lineTokens;
        }
        if (lineTokens === EMPTY_LINE_TOKENS) {
            return _otherTokens;
        }
        if (lineTokens === null) {
            return lineTokens;
        }
        if (_otherTokens === null) {
            // cannot determine combined line length...
            return null;
        }
        const myTokens = toUint32Array(lineTokens);
        const otherTokens = toUint32Array(_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 i = 0; i < otherTokensCount; i++) {
            result[dest++] = otherTokens[(i << 1)] + delta;
            result[dest++] = otherTokens[(i << 1) + 1];
        }
        return result.buffer;
    }
    static insert(lineTokens, chIndex, textLength) {
        if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
            // nothing to do
            return lineTokens;
        }
        const tokens = toUint32Array(lineTokens);
        const tokensCount = (tokens.length >>> 1);
        let fromTokenIndex = LineTokens.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 toUint32Array(arr) {
    if (arr instanceof Uint32Array) {
        return arr;
    }
    else {
        return new Uint32Array(arr);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/tokens/contiguousTokensStore.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





/**
 * Represents contiguous tokens in a text model.
 */
class ContiguousTokensStore {
    constructor(languageIdCodec) {
        this._lineTokens = [];
        this._len = 0;
        this._languageIdCodec = languageIdCodec;
    }
    flush() {
        this._lineTokens = [];
        this._len = 0;
    }
    getTokens(topLevelLanguageId, lineIndex, lineText) {
        let rawLineTokens = null;
        if (lineIndex < this._len) {
            rawLineTokens = this._lineTokens[lineIndex];
        }
        if (rawLineTokens !== null && rawLineTokens !== EMPTY_LINE_TOKENS) {
            return new LineTokens(toUint32Array(rawLineTokens), lineText, this._languageIdCodec);
        }
        const lineTokens = new Uint32Array(2);
        lineTokens[0] = lineText.length;
        lineTokens[1] = getDefaultMetadata(this._languageIdCodec.encodeLanguageId(topLevelLanguageId));
        return new LineTokens(lineTokens, lineText, this._languageIdCodec);
    }
    static _massageTokens(topLevelLanguageId, lineTextLength, _tokens) {
        const tokens = _tokens ? toUint32Array(_tokens) : null;
        if (lineTextLength === 0) {
            let hasDifferentLanguageId = false;
            if (tokens && tokens.length > 1) {
                hasDifferentLanguageId = (TokenMetadata.getLanguageId(tokens[1]) !== topLevelLanguageId);
            }
            if (!hasDifferentLanguageId) {
                return EMPTY_LINE_TOKENS;
            }
        }
        if (!tokens || tokens.length === 0) {
            const tokens = new Uint32Array(2);
            tokens[0] = lineTextLength;
            tokens[1] = getDefaultMetadata(topLevelLanguageId);
            return tokens.buffer;
        }
        // Ensure the last token covers the end of the text
        tokens[tokens.length - 2] = lineTextLength;
        if (tokens.byteOffset === 0 && tokens.byteLength === tokens.buffer.byteLength) {
            // Store directly the ArrayBuffer pointer to save an object
            return tokens.buffer;
        }
        return tokens;
    }
    _ensureLine(lineIndex) {
        while (lineIndex >= this._len) {
            this._lineTokens[this._len] = null;
            this._len++;
        }
    }
    _deleteLines(start, deleteCount) {
        if (deleteCount === 0) {
            return;
        }
        if (start + deleteCount > this._len) {
            deleteCount = this._len - start;
        }
        this._lineTokens.splice(start, deleteCount);
        this._len -= deleteCount;
    }
    _insertLines(insertIndex, insertCount) {
        if (insertCount === 0) {
            return;
        }
        const lineTokens = [];
        for (let i = 0; i < insertCount; i++) {
            lineTokens[i] = null;
        }
        this._lineTokens = arrayInsert(this._lineTokens, insertIndex, lineTokens);
        this._len += insertCount;
    }
    setTokens(topLevelLanguageId, lineIndex, lineTextLength, _tokens, checkEquality) {
        const tokens = ContiguousTokensStore._massageTokens(this._languageIdCodec.encodeLanguageId(topLevelLanguageId), lineTextLength, _tokens);
        this._ensureLine(lineIndex);
        const oldTokens = this._lineTokens[lineIndex];
        this._lineTokens[lineIndex] = tokens;
        if (checkEquality) {
            return !ContiguousTokensStore._equals(oldTokens, tokens);
        }
        return false;
    }
    static _equals(_a, _b) {
        if (!_a || !_b) {
            return !_a && !_b;
        }
        const a = toUint32Array(_a);
        const b = toUint32Array(_b);
        if (a.length !== b.length) {
            return false;
        }
        for (let i = 0, len = a.length; i < len; i++) {
            if (a[i] !== b[i]) {
                return false;
            }
        }
        return true;
    }
    //#region Editing
    acceptEdit(range, eolCount, firstLineLength) {
        this._acceptDeleteRange(range);
        this._acceptInsertText(new Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength);
    }
    _acceptDeleteRange(range) {
        const firstLineIndex = range.startLineNumber - 1;
        if (firstLineIndex >= this._len) {
            return;
        }
        if (range.startLineNumber === range.endLineNumber) {
            if (range.startColumn === range.endColumn) {
                // Nothing to delete
                return;
            }
            this._lineTokens[firstLineIndex] = ContiguousTokensEditing.delete(this._lineTokens[firstLineIndex], range.startColumn - 1, range.endColumn - 1);
            return;
        }
        this._lineTokens[firstLineIndex] = ContiguousTokensEditing.deleteEnding(this._lineTokens[firstLineIndex], range.startColumn - 1);
        const lastLineIndex = range.endLineNumber - 1;
        let lastLineTokens = null;
        if (lastLineIndex < this._len) {
            lastLineTokens = ContiguousTokensEditing.deleteBeginning(this._lineTokens[lastLineIndex], range.endColumn - 1);
        }
        // Take remaining text on last line and append it to remaining text on first line
        this._lineTokens[firstLineIndex] = ContiguousTokensEditing.append(this._lineTokens[firstLineIndex], lastLineTokens);
        // Delete middle lines
        this._deleteLines(range.startLineNumber, range.endLineNumber - range.startLineNumber);
    }
    _acceptInsertText(position, eolCount, firstLineLength) {
        if (eolCount === 0 && firstLineLength === 0) {
            // Nothing to insert
            return;
        }
        const lineIndex = position.lineNumber - 1;
        if (lineIndex >= this._len) {
            return;
        }
        if (eolCount === 0) {
            // Inserting text on one line
            this._lineTokens[lineIndex] = ContiguousTokensEditing.insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
            return;
        }
        this._lineTokens[lineIndex] = ContiguousTokensEditing.deleteEnding(this._lineTokens[lineIndex], position.column - 1);
        this._lineTokens[lineIndex] = ContiguousTokensEditing.insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
        this._insertLines(position.lineNumber, eolCount);
    }
}
function getDefaultMetadata(topLevelLanguageId) {
    return ((topLevelLanguageId << 0 /* MetadataConsts.LANGUAGEID_OFFSET */)
        | (0 /* StandardTokenType.Other */ << 8 /* MetadataConsts.TOKEN_TYPE_OFFSET */)
        | (0 /* FontStyle.None */ << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
        | (1 /* ColorId.DefaultForeground */ << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
        | (2 /* ColorId.DefaultBackground */ << 24 /* MetadataConsts.BACKGROUND_OFFSET */)
        // If there is no grammar, we just take a guess and try to match brackets.
        | (1024 /* MetadataConsts.BALANCED_BRACKETS_MASK */)) >>> 0;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/tokens/sparseTokensStore.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


/**
 * Represents sparse tokens in a text model.
 */
class SparseTokensStore {
    constructor(languageIdCodec) {
        this._pieces = [];
        this._isComplete = false;
        this._languageIdCodec = languageIdCodec;
    }
    flush() {
        this._pieces = [];
        this._isComplete = false;
    }
    isEmpty() {
        return (this._pieces.length === 0);
    }
    set(pieces, isComplete) {
        this._pieces = pieces || [];
        this._isComplete = isComplete;
    }
    setPartial(_range, pieces) {
        // console.log(`setPartial ${_range} ${pieces.map(p => p.toString()).join(', ')}`);
        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 i = 0, len = this._pieces.length; i < len; i++) {
            const piece = this._pieces[i];
            if (piece.endLineNumber < range.startLineNumber) {
                // this piece is before the range
                continue;
            }
            if (piece.startLineNumber > range.endLineNumber) {
                // this piece is after the range, so mark the spot before this piece
                // as a good insertion position and stop looping
                insertPosition = insertPosition || { index: i };
                break;
            }
            // this piece might intersect with the range
            piece.removeTokens(range);
            if (piece.isEmpty()) {
                // remove the piece if it became empty
                this._pieces.splice(i, 1);
                i--;
                len--;
                continue;
            }
            if (piece.endLineNumber < range.startLineNumber) {
                // after removal, this piece is before the range
                continue;
            }
            if (piece.startLineNumber > range.endLineNumber) {
                // after removal, this piece is after the range
                insertPosition = insertPosition || { index: i };
                continue;
            }
            // after removal, this piece contains the range
            const [a, b] = piece.split(range);
            if (a.isEmpty()) {
                // this piece is actually after the range
                insertPosition = insertPosition || { index: i };
                continue;
            }
            if (b.isEmpty()) {
                // this piece is actually before the range
                continue;
            }
            this._pieces.splice(i, 1, a, b);
            i++;
            len++;
            insertPosition = insertPosition || { index: i };
        }
        insertPosition = insertPosition || { index: this._pieces.length };
        if (pieces.length > 0) {
            this._pieces = arrayInsert(this._pieces, insertPosition.index, pieces);
        }
        // console.log(`I HAVE ${this._pieces.length} pieces`);
        // console.log(`${this._pieces.map(p => p.toString()).join('\n')}`);
        return range;
    }
    isComplete() {
        return this._isComplete;
    }
    addSparseTokens(lineNumber, aTokens) {
        if (aTokens.getLineContent().length === 0) {
            // Don't do anything for empty lines
            return aTokens;
        }
        const pieces = this._pieces;
        if (pieces.length === 0) {
            return aTokens;
        }
        const pieceIndex = SparseTokensStore._findFirstPieceWithLine(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 /* MetadataConsts.SEMANTIC_USE_ITALIC */) ? 2048 /* MetadataConsts.ITALIC_MASK */ : 0)
                | ((bMetadata & 2 /* MetadataConsts.SEMANTIC_USE_BOLD */) ? 4096 /* MetadataConsts.BOLD_MASK */ : 0)
                | ((bMetadata & 4 /* MetadataConsts.SEMANTIC_USE_UNDERLINE */) ? 8192 /* MetadataConsts.UNDERLINE_MASK */ : 0)
                | ((bMetadata & 8 /* MetadataConsts.SEMANTIC_USE_STRIKETHROUGH */) ? 16384 /* MetadataConsts.STRIKETHROUGH_MASK */ : 0)
                | ((bMetadata & 16 /* MetadataConsts.SEMANTIC_USE_FOREGROUND */) ? 16744448 /* MetadataConsts.FOREGROUND_MASK */ : 0)
                | ((bMetadata & 32 /* MetadataConsts.SEMANTIC_USE_BACKGROUND */) ? 4278190080 /* MetadataConsts.BACKGROUND_MASK */ : 0)) >>> 0;
            const aMask = (~bMask) >>> 0;
            // push any token from `a` that is before `b`
            while (aIndex < aLen && aTokens.getEndOffset(aIndex) <= bStartCharacter) {
                emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
                aIndex++;
            }
            // push the token from `a` if it intersects the token from `b`
            if (aIndex < aLen && aTokens.getStartOffset(aIndex) < bStartCharacter) {
                emitToken(bStartCharacter, aTokens.getMetadata(aIndex));
            }
            // skip any tokens from `a` that are contained inside `b`
            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) {
                    // `a` ends exactly at the same spot as `b`!
                    aIndex++;
                }
            }
            else {
                const aMergeIndex = Math.min(Math.max(0, aIndex - 1), aLen - 1);
                // push the token from `b`
                emitToken(bEndCharacter, (aTokens.getMetadata(aMergeIndex) & aMask) | (bMetadata & bMask));
            }
        }
        // push the remaining tokens from `a`
        while (aIndex < aLen) {
            emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
            aIndex++;
        }
        return new LineTokens(new Uint32Array(result), aTokens.getLineContent(), this._languageIdCodec);
    }
    static _findFirstPieceWithLine(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._pieces) {
            piece.acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode);
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/tokenizationTextModelPart.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







class TokenizationTextModelPart extends TextModelPart {
    constructor(_languageService, _languageConfigurationService, _textModel, bracketPairsTextModelPart, _languageId) {
        super();
        this._languageService = _languageService;
        this._languageConfigurationService = _languageConfigurationService;
        this._textModel = _textModel;
        this.bracketPairsTextModelPart = bracketPairsTextModelPart;
        this._languageId = _languageId;
        this._onDidChangeLanguage = this._register(new Emitter());
        this.onDidChangeLanguage = this._onDidChangeLanguage.event;
        this._onDidChangeLanguageConfiguration = this._register(new Emitter());
        this.onDidChangeLanguageConfiguration = this._onDidChangeLanguageConfiguration.event;
        this._onDidChangeTokens = this._register(new Emitter());
        this.onDidChangeTokens = this._onDidChangeTokens.event;
        this._backgroundTokenizationState = 0 /* BackgroundTokenizationState.Uninitialized */;
        this._onBackgroundTokenizationStateChanged = this._register(new Emitter());
        this._tokens = new ContiguousTokensStore(this._languageService.languageIdCodec);
        this._semanticTokens = new SparseTokensStore(this._languageService.languageIdCodec);
        this._tokenization = new TextModelTokenization(_textModel, this, this._languageService.languageIdCodec);
        this._languageRegistryListener = this._languageConfigurationService.onDidChange(e => {
            if (e.affects(this._languageId)) {
                this._onDidChangeLanguageConfiguration.fire({});
            }
        });
    }
    acceptEdit(range, text, eolCount, firstLineLength, lastLineLength) {
        this._tokens.acceptEdit(range, eolCount, firstLineLength);
        this._semanticTokens.acceptEdit(range, eolCount, firstLineLength, lastLineLength, text.length > 0 ? text.charCodeAt(0) : 0 /* CharCode.Null */);
    }
    handleDidChangeAttached() {
        this._tokenization.handleDidChangeAttached();
    }
    flush() {
        this._tokens.flush();
        this._semanticTokens.flush();
    }
    handleDidChangeContent(change) {
        this._tokenization.handleDidChangeContent(change);
    }
    dispose() {
        this._languageRegistryListener.dispose();
        this._tokenization.dispose();
        super.dispose();
    }
    get backgroundTokenizationState() {
        return this._backgroundTokenizationState;
    }
    handleTokenizationProgress(completed) {
        if (this._backgroundTokenizationState === 2 /* BackgroundTokenizationState.Completed */) {
            // We already did a full tokenization and don't go back to progressing.
            return;
        }
        const newState = completed ? 2 /* BackgroundTokenizationState.Completed */ : 1 /* BackgroundTokenizationState.InProgress */;
        if (this._backgroundTokenizationState !== newState) {
            this._backgroundTokenizationState = newState;
            this.bracketPairsTextModelPart.handleDidChangeBackgroundTokenizationState();
            this._onBackgroundTokenizationStateChanged.fire();
        }
    }
    setTokens(tokens, backgroundTokenizationCompleted = false) {
        if (tokens.length !== 0) {
            const ranges = [];
            for (let i = 0, len = tokens.length; i < len; i++) {
                const element = tokens[i];
                let minChangedLineNumber = 0;
                let maxChangedLineNumber = 0;
                let hasChange = false;
                for (let lineNumber = element.startLineNumber; lineNumber <= element.endLineNumber; lineNumber++) {
                    if (hasChange) {
                        this._tokens.setTokens(this._languageId, lineNumber - 1, this._textModel.getLineLength(lineNumber), element.getLineTokens(lineNumber), false);
                        maxChangedLineNumber = lineNumber;
                    }
                    else {
                        const lineHasChange = this._tokens.setTokens(this._languageId, lineNumber - 1, this._textModel.getLineLength(lineNumber), element.getLineTokens(lineNumber), true);
                        if (lineHasChange) {
                            hasChange = true;
                            minChangedLineNumber = lineNumber;
                            maxChangedLineNumber = lineNumber;
                        }
                    }
                }
                if (hasChange) {
                    ranges.push({
                        fromLineNumber: minChangedLineNumber,
                        toLineNumber: maxChangedLineNumber,
                    });
                }
            }
            if (ranges.length > 0) {
                this._emitModelTokensChangedEvent({
                    tokenizationSupportChanged: false,
                    semanticTokensApplied: false,
                    ranges: ranges,
                });
            }
        }
        this.handleTokenizationProgress(backgroundTokenizationCompleted);
    }
    setSemanticTokens(tokens, isComplete) {
        this._semanticTokens.set(tokens, isComplete);
        this._emitModelTokensChangedEvent({
            tokenizationSupportChanged: false,
            semanticTokensApplied: tokens !== null,
            ranges: [{ fromLineNumber: 1, toLineNumber: this._textModel.getLineCount() }],
        });
    }
    hasCompleteSemanticTokens() {
        return this._semanticTokens.isComplete();
    }
    hasSomeSemanticTokens() {
        return !this._semanticTokens.isEmpty();
    }
    setPartialSemanticTokens(range, tokens) {
        if (this.hasCompleteSemanticTokens()) {
            return;
        }
        const changedRange = this._textModel.validateRange(this._semanticTokens.setPartial(range, tokens));
        this._emitModelTokensChangedEvent({
            tokenizationSupportChanged: false,
            semanticTokensApplied: true,
            ranges: [
                {
                    fromLineNumber: changedRange.startLineNumber,
                    toLineNumber: changedRange.endLineNumber,
                },
            ],
        });
    }
    tokenizeViewport(startLineNumber, endLineNumber) {
        startLineNumber = Math.max(1, startLineNumber);
        endLineNumber = Math.min(this._textModel.getLineCount(), endLineNumber);
        this._tokenization.tokenizeViewport(startLineNumber, endLineNumber);
    }
    clearTokens() {
        this._tokens.flush();
        this._emitModelTokensChangedEvent({
            tokenizationSupportChanged: true,
            semanticTokensApplied: false,
            ranges: [
                {
                    fromLineNumber: 1,
                    toLineNumber: this._textModel.getLineCount(),
                },
            ],
        });
    }
    _emitModelTokensChangedEvent(e) {
        if (!this._textModel._isDisposing()) {
            this.bracketPairsTextModelPart.handleDidChangeTokens(e);
            this._onDidChangeTokens.fire(e);
        }
    }
    resetTokenization() {
        this._tokenization.reset();
    }
    forceTokenization(lineNumber) {
        if (lineNumber < 1 || lineNumber > this._textModel.getLineCount()) {
            throw new Error('Illegal value for lineNumber');
        }
        this._tokenization.forceTokenization(lineNumber);
    }
    isCheapToTokenize(lineNumber) {
        return this._tokenization.isCheapToTokenize(lineNumber);
    }
    tokenizeIfCheap(lineNumber) {
        if (this.isCheapToTokenize(lineNumber)) {
            this.forceTokenization(lineNumber);
        }
    }
    getLineTokens(lineNumber) {
        if (lineNumber < 1 || lineNumber > this._textModel.getLineCount()) {
            throw new Error('Illegal value for lineNumber');
        }
        return this._getLineTokens(lineNumber);
    }
    _getLineTokens(lineNumber) {
        const lineText = this._textModel.getLineContent(lineNumber);
        const syntacticTokens = this._tokens.getTokens(this._languageId, lineNumber - 1, lineText);
        return this._semanticTokens.addSparseTokens(lineNumber, syntacticTokens);
    }
    getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
        const position = this._textModel.validatePosition(new Position(lineNumber, column));
        return this._tokenization.getTokenTypeIfInsertingCharacter(position, character);
    }
    tokenizeLineWithEdit(position, length, newText) {
        const validatedPosition = this._textModel.validatePosition(position);
        return this._tokenization.tokenizeLineWithEdit(validatedPosition, length, newText);
    }
    getLanguageConfiguration(languageId) {
        return this._languageConfigurationService.getLanguageConfiguration(languageId);
    }
    // Having tokens allows implementing additional helper methods
    getWordAtPosition(_position) {
        this.assertNotDisposed();
        const position = this._textModel.validatePosition(_position);
        const lineContent = this._textModel.getLineContent(position.lineNumber);
        const lineTokens = this._getLineTokens(position.lineNumber);
        const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        // (1). First try checking right biased word
        const [rbStartOffset, rbEndOffset] = TokenizationTextModelPart._findLanguageBoundaries(lineTokens, tokenIndex);
        const rightBiasedWord = getWordAtText(position.column, this.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex)).getWordDefinition(), lineContent.substring(rbStartOffset, rbEndOffset), rbStartOffset);
        // Make sure the result touches the original passed in position
        if (rightBiasedWord &&
            rightBiasedWord.startColumn <= _position.column &&
            _position.column <= rightBiasedWord.endColumn) {
            return rightBiasedWord;
        }
        // (2). Else, if we were at a language boundary, check the left biased word
        if (tokenIndex > 0 && rbStartOffset === position.column - 1) {
            // edge case, where `position` sits between two tokens belonging to two different languages
            const [lbStartOffset, lbEndOffset] = TokenizationTextModelPart._findLanguageBoundaries(lineTokens, tokenIndex - 1);
            const leftBiasedWord = getWordAtText(position.column, this.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex - 1)).getWordDefinition(), lineContent.substring(lbStartOffset, lbEndOffset), lbStartOffset);
            // Make sure the result touches the original passed in position
            if (leftBiasedWord &&
                leftBiasedWord.startColumn <= _position.column &&
                _position.column <= leftBiasedWord.endColumn) {
                return leftBiasedWord;
            }
        }
        return null;
    }
    static _findLanguageBoundaries(lineTokens, tokenIndex) {
        const languageId = lineTokens.getLanguageId(tokenIndex);
        // go left until a different language is hit
        let startOffset = 0;
        for (let i = tokenIndex; i >= 0 && lineTokens.getLanguageId(i) === languageId; i--) {
            startOffset = lineTokens.getStartOffset(i);
        }
        // go right until a different language is hit
        let endOffset = lineTokens.getLineContent().length;
        for (let i = tokenIndex, tokenCount = lineTokens.getCount(); i < tokenCount && lineTokens.getLanguageId(i) === languageId; i++) {
            endOffset = lineTokens.getEndOffset(i);
        }
        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,
        };
    }
    getLanguageId() {
        return this._languageId;
    }
    getLanguageIdAtPosition(lineNumber, column) {
        const position = this._textModel.validatePosition(new Position(lineNumber, column));
        const lineTokens = this.getLineTokens(position.lineNumber);
        return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));
    }
    setLanguageId(languageId) {
        if (this._languageId === languageId) {
            // There's nothing to do
            return;
        }
        const e = {
            oldLanguage: this._languageId,
            newLanguage: languageId
        };
        this._languageId = languageId;
        this.bracketPairsTextModelPart.handleDidChangeLanguage(e);
        this._tokenization.handleDidChangeLanguage(e);
        this._onDidChangeLanguage.fire(e);
        this._onDidChangeLanguageConfiguration.fire({});
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/textModelEvents.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/**
 * An event describing that a model has been reset to a new value.
 * @internal
 */
class ModelRawFlush {
    constructor() {
        this.changeType = 1 /* RawContentChangedType.Flush */;
    }
}
/**
 * Represents text injected on a line
 * @internal
 */
class LineInjectedText {
    constructor(ownerId, lineNumber, column, options, order) {
        this.ownerId = ownerId;
        this.lineNumber = lineNumber;
        this.column = column;
        this.options = options;
        this.order = order;
    }
    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 decoration of decorations) {
            if (decoration.options.before && decoration.options.before.content.length > 0) {
                result.push(new LineInjectedText(decoration.ownerId, decoration.range.startLineNumber, decoration.range.startColumn, decoration.options.before, 0));
            }
            if (decoration.options.after && decoration.options.after.content.length > 0) {
                result.push(new LineInjectedText(decoration.ownerId, decoration.range.endLineNumber, decoration.range.endColumn, decoration.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;
    }
}
/**
 * An event describing that a line has changed in a model.
 * @internal
 */
class ModelRawLineChanged {
    constructor(lineNumber, detail, injectedText) {
        this.changeType = 2 /* RawContentChangedType.LineChanged */;
        this.lineNumber = lineNumber;
        this.detail = detail;
        this.injectedText = injectedText;
    }
}
/**
 * An event describing that line(s) have been deleted in a model.
 * @internal
 */
class ModelRawLinesDeleted {
    constructor(fromLineNumber, toLineNumber) {
        this.changeType = 3 /* RawContentChangedType.LinesDeleted */;
        this.fromLineNumber = fromLineNumber;
        this.toLineNumber = toLineNumber;
    }
}
/**
 * An event describing that line(s) have been inserted in a model.
 * @internal
 */
class ModelRawLinesInserted {
    constructor(fromLineNumber, toLineNumber, detail, injectedTexts) {
        this.changeType = 4 /* RawContentChangedType.LinesInserted */;
        this.injectedTexts = injectedTexts;
        this.fromLineNumber = fromLineNumber;
        this.toLineNumber = toLineNumber;
        this.detail = detail;
    }
}
/**
 * An event describing that a model has had its EOL changed.
 * @internal
 */
class ModelRawEOLChanged {
    constructor() {
        this.changeType = 5 /* RawContentChangedType.EOLChanged */;
    }
}
/**
 * An event describing a change in the text of a model.
 * @internal
 */
class ModelRawContentChangedEvent {
    constructor(changes, versionId, isUndoing, isRedoing) {
        this.changes = changes;
        this.versionId = versionId;
        this.isUndoing = isUndoing;
        this.isRedoing = isRedoing;
        this.resultingSelection = null;
    }
    containsEvent(type) {
        for (let i = 0, len = this.changes.length; i < len; i++) {
            const change = this.changes[i];
            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 ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing);
    }
}
/**
 * An event describing a change in injected text.
 * @internal
 */
class ModelInjectedTextChangedEvent {
    constructor(changes) {
        this.changes = changes;
    }
}
/**
 * @internal
 */
class InternalModelContentChangeEvent {
    constructor(rawContentChangedEvent, contentChangedEvent) {
        this.rawContentChangedEvent = rawContentChangedEvent;
        this.contentChangedEvent = contentChangedEvent;
    }
    merge(other) {
        const rawContentChangedEvent = ModelRawContentChangedEvent.merge(this.rawContentChangedEvent, other.rawContentChangedEvent);
        const contentChangedEvent = InternalModelContentChangeEvent._mergeChangeEvents(this.contentChangedEvent, other.contentChangedEvent);
        return new InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent);
    }
    static _mergeChangeEvents(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);
        return {
            changes: changes,
            eol: eol,
            versionId: versionId,
            isUndoing: isUndoing,
            isRedoing: isRedoing,
            isFlush: isFlush
        };
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/undoRedo/common/undoRedo.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const IUndoRedoService = createDecorator('undoRedoService');
class ResourceEditStackSnapshot {
    constructor(resource, elements) {
        this.resource = resource;
        this.elements = elements;
    }
}
class UndoRedoGroup {
    constructor() {
        this.id = UndoRedoGroup._ID++;
        this.order = 1;
    }
    nextOrder() {
        if (this.id === 0) {
            return 0;
        }
        return this.order++;
    }
}
UndoRedoGroup._ID = 0;
UndoRedoGroup.None = new UndoRedoGroup();
class UndoRedoSource {
    constructor() {
        this.id = UndoRedoSource._ID++;
        this.order = 1;
    }
    nextOrder() {
        if (this.id === 0) {
            return 0;
        }
        return this.order++;
    }
}
UndoRedoSource._ID = 0;
UndoRedoSource.None = new UndoRedoSource();

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/textModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var textModel_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var textModel_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};




























function createTextBufferFactory(text) {
    const builder = new PieceTreeTextBufferBuilder();
    builder.acceptChunk(text);
    return builder.finish();
}
function createTextBufferFactoryFromSnapshot(snapshot) {
    const builder = new PieceTreeTextBufferBuilder();
    let chunk;
    while (typeof (chunk = snapshot.read()) === 'string') {
        builder.acceptChunk(chunk);
    }
    return builder.finish();
}
function createTextBuffer(value, defaultEOL) {
    let factory;
    if (typeof value === 'string') {
        factory = createTextBufferFactory(value);
    }
    else if (isITextSnapshot(value)) {
        factory = createTextBufferFactoryFromSnapshot(value);
    }
    else {
        factory = value;
    }
    return factory.create(defaultEOL);
}
let MODEL_ID = 0;
const textModel_LIMIT_FIND_COUNT = 999;
const LONG_LINE_BOUNDARY = 10000;
class TextModelSnapshot {
    constructor(source) {
        this._source = source;
        this._eos = false;
    }
    read() {
        if (this._eos) {
            return null;
        }
        const result = [];
        let resultCnt = 0;
        let resultLength = 0;
        do {
            const tmp = this._source.read();
            if (tmp === null) {
                // end-of-stream
                this._eos = 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);
    }
}
const invalidFunc = () => { throw new Error(`Invalid change accessor`); };
let TextModel = class TextModel extends Disposable {
    constructor(source, languageId, creationOptions, associatedResource = null, _undoRedoService, _languageService, _languageConfigurationService) {
        super();
        this._undoRedoService = _undoRedoService;
        this._languageService = _languageService;
        this._languageConfigurationService = _languageConfigurationService;
        //#region Events
        this._onWillDispose = this._register(new Emitter());
        this.onWillDispose = this._onWillDispose.event;
        this._onDidChangeDecorations = this._register(new DidChangeDecorationsEmitter(affectedInjectedTextLines => this.handleBeforeFireDecorationsChangedEvent(affectedInjectedTextLines)));
        this.onDidChangeDecorations = this._onDidChangeDecorations.event;
        this._onDidChangeOptions = this._register(new Emitter());
        this.onDidChangeOptions = this._onDidChangeOptions.event;
        this._onDidChangeAttached = this._register(new Emitter());
        this.onDidChangeAttached = this._onDidChangeAttached.event;
        this._onDidChangeInjectedText = this._register(new Emitter());
        this._eventEmitter = this._register(new DidChangeContentEmitter());
        this._deltaDecorationCallCnt = 0;
        // Generate a new unique model id
        MODEL_ID++;
        this.id = '$model' + MODEL_ID;
        this.isForSimpleWidget = creationOptions.isForSimpleWidget;
        if (typeof associatedResource === 'undefined' || associatedResource === null) {
            this._associatedResource = URI.parse('inmemory://model/' + MODEL_ID);
        }
        else {
            this._associatedResource = associatedResource;
        }
        this._attachedEditorCount = 0;
        const { textBuffer, disposable } = createTextBuffer(source, creationOptions.defaultEOL);
        this._buffer = textBuffer;
        this._bufferDisposable = disposable;
        this._options = TextModel.resolveOptions(this._buffer, creationOptions);
        this._bracketPairs = this._register(new BracketPairsTextModelPart(this, this._languageConfigurationService));
        this._guidesTextModelPart = this._register(new GuidesTextModelPart(this, this._languageConfigurationService));
        this._decorationProvider = this._register(new ColorizedBracketPairsDecorationProvider(this));
        this._tokenizationTextModelPart = new TokenizationTextModelPart(this._languageService, this._languageConfigurationService, this, this._bracketPairs, languageId);
        const bufferLineCount = this._buffer.getLineCount();
        const bufferTextLength = this._buffer.getValueLengthInRange(new Range(1, 1, bufferLineCount, this._buffer.getLineLength(bufferLineCount) + 1), 0 /* model.EndOfLinePreference.TextDefined */);
        // !!! Make a decision in the ctor and permanently respect this decision !!!
        // If a model is too large at construction time, it will never get tokenized,
        // under no circumstances.
        if (creationOptions.largeFileOptimizations) {
            this._isTooLargeForTokenization = ((bufferTextLength > TextModel.LARGE_FILE_SIZE_THRESHOLD)
                || (bufferLineCount > TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD));
        }
        else {
            this._isTooLargeForTokenization = false;
        }
        this._isTooLargeForSyncing = (bufferTextLength > TextModel.MODEL_SYNC_LIMIT);
        this._versionId = 1;
        this._alternativeVersionId = 1;
        this._initialUndoRedoSnapshot = null;
        this._isDisposed = false;
        this.__isDisposing = false;
        this._instanceId = singleLetterHash(MODEL_ID);
        this._lastDecorationId = 0;
        this._decorations = Object.create(null);
        this._decorationsTree = new DecorationsTrees();
        this._commandManager = new EditStack(this, this._undoRedoService);
        this._isUndoing = false;
        this._isRedoing = false;
        this._trimAutoWhitespaceLines = null;
        this._register(this._decorationProvider.onDidChange(() => {
            this._onDidChangeDecorations.beginDeferredEmit();
            this._onDidChangeDecorations.fire();
            this._onDidChangeDecorations.endDeferredEmit();
        }));
    }
    static resolveOptions(textBuffer, options) {
        if (options.detectIndentation) {
            const guessedIndentation = guessIndentation(textBuffer, options.tabSize, options.insertSpaces);
            return new TextModelResolvedOptions({
                tabSize: guessedIndentation.tabSize,
                indentSize: guessedIndentation.tabSize,
                insertSpaces: guessedIndentation.insertSpaces,
                trimAutoWhitespace: options.trimAutoWhitespace,
                defaultEOL: options.defaultEOL,
                bracketPairColorizationOptions: options.bracketPairColorizationOptions,
            });
        }
        return new TextModelResolvedOptions({
            tabSize: options.tabSize,
            indentSize: options.indentSize,
            insertSpaces: options.insertSpaces,
            trimAutoWhitespace: options.trimAutoWhitespace,
            defaultEOL: options.defaultEOL,
            bracketPairColorizationOptions: options.bracketPairColorizationOptions,
        });
    }
    get onDidChangeLanguage() { return this._tokenizationTextModelPart.onDidChangeLanguage; }
    get onDidChangeLanguageConfiguration() { return this._tokenizationTextModelPart.onDidChangeLanguageConfiguration; }
    get onDidChangeTokens() { return this._tokenizationTextModelPart.onDidChangeTokens; }
    onDidChangeContent(listener) {
        return this._eventEmitter.slowEvent((e) => listener(e.contentChangedEvent));
    }
    onDidChangeContentOrInjectedText(listener) {
        return combinedDisposable(this._eventEmitter.fastEvent(e => listener(e)), this._onDidChangeInjectedText.event(e => listener(e)));
    }
    _isDisposing() { return this.__isDisposing; }
    get tokenization() { return this._tokenizationTextModelPart; }
    get bracketPairs() { return this._bracketPairs; }
    get guides() { return this._guidesTextModelPart; }
    dispose() {
        this.__isDisposing = true;
        this._onWillDispose.fire();
        this._tokenizationTextModelPart.dispose();
        this._isDisposed = true;
        super.dispose();
        this._bufferDisposable.dispose();
        this.__isDisposing = false;
        // Manually release reference to previous text buffer to avoid large leaks
        // in case someone leaks a TextModel reference
        const emptyDisposedTextBuffer = new PieceTreeTextBuffer([], '', '\n', false, false, true, true);
        emptyDisposedTextBuffer.dispose();
        this._buffer = emptyDisposedTextBuffer;
        this._bufferDisposable = Disposable.None;
    }
    _assertNotDisposed() {
        if (this._isDisposed) {
            throw new Error('Model is disposed!');
        }
    }
    _emitContentChangedEvent(rawChange, change) {
        if (this.__isDisposing) {
            // Do not confuse listeners by emitting any event after disposing
            return;
        }
        this._tokenizationTextModelPart.handleDidChangeContent(change);
        this._bracketPairs.handleDidChangeContent(change);
        this._eventEmitter.fire(new InternalModelContentChangeEvent(rawChange, change));
    }
    setValue(value) {
        this._assertNotDisposed();
        if (value === null) {
            // There's nothing to do
            return;
        }
        const { textBuffer, disposable } = createTextBuffer(value, this._options.defaultEOL);
        this._setValueFromTextBuffer(textBuffer, disposable);
    }
    _createContentChanged2(range, rangeOffset, rangeLength, text, isUndoing, isRedoing, isFlush) {
        return {
            changes: [{
                    range: range,
                    rangeOffset: rangeOffset,
                    rangeLength: rangeLength,
                    text: text,
                }],
            eol: this._buffer.getEOL(),
            versionId: this.getVersionId(),
            isUndoing: isUndoing,
            isRedoing: isRedoing,
            isFlush: isFlush
        };
    }
    _setValueFromTextBuffer(textBuffer, textBufferDisposable) {
        this._assertNotDisposed();
        const oldFullModelRange = this.getFullModelRange();
        const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
        const endLineNumber = this.getLineCount();
        const endColumn = this.getLineMaxColumn(endLineNumber);
        this._buffer = textBuffer;
        this._bufferDisposable.dispose();
        this._bufferDisposable = textBufferDisposable;
        this._increaseVersionId();
        // Flush all tokens
        this._tokenizationTextModelPart.flush();
        // Destroy all my decorations
        this._decorations = Object.create(null);
        this._decorationsTree = new DecorationsTrees();
        // Destroy my edit history and settings
        this._commandManager.clear();
        this._trimAutoWhitespaceLines = null;
        this._emitContentChangedEvent(new ModelRawContentChangedEvent([
            new ModelRawFlush()
        ], this._versionId, false, false), this._createContentChanged2(new Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, true));
    }
    setEOL(eol) {
        this._assertNotDisposed();
        const newEOL = (eol === 1 /* model.EndOfLineSequence.CRLF */ ? '\r\n' : '\n');
        if (this._buffer.getEOL() === newEOL) {
            // Nothing to do
            return;
        }
        const oldFullModelRange = this.getFullModelRange();
        const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
        const endLineNumber = this.getLineCount();
        const endColumn = this.getLineMaxColumn(endLineNumber);
        this._onBeforeEOLChange();
        this._buffer.setEOL(newEOL);
        this._increaseVersionId();
        this._onAfterEOLChange();
        this._emitContentChangedEvent(new ModelRawContentChangedEvent([
            new ModelRawEOLChanged()
        ], this._versionId, false, false), this._createContentChanged2(new Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, false));
    }
    _onBeforeEOLChange() {
        // Ensure all decorations get their `range` set.
        this._decorationsTree.ensureAllNodesHaveRanges(this);
    }
    _onAfterEOLChange() {
        // Transform back `range` to offsets
        const versionId = this.getVersionId();
        const allDecorations = this._decorationsTree.collectNodesPostOrder();
        for (let i = 0, len = allDecorations.length; i < len; i++) {
            const node = allDecorations[i];
            const range = node.range; // the range is defined due to `_onBeforeEOLChange`
            const delta = node.cachedAbsoluteStart - node.start;
            const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
            const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
            node.cachedAbsoluteStart = startOffset;
            node.cachedAbsoluteEnd = endOffset;
            node.cachedVersionId = versionId;
            node.start = startOffset - delta;
            node.end = endOffset - delta;
            recomputeMaxEnd(node);
        }
    }
    onBeforeAttached() {
        this._attachedEditorCount++;
        if (this._attachedEditorCount === 1) {
            this._tokenizationTextModelPart.handleDidChangeAttached();
            this._onDidChangeAttached.fire(undefined);
        }
    }
    onBeforeDetached() {
        this._attachedEditorCount--;
        if (this._attachedEditorCount === 0) {
            this._tokenizationTextModelPart.handleDidChangeAttached();
            this._onDidChangeAttached.fire(undefined);
        }
    }
    isAttachedToEditor() {
        return this._attachedEditorCount > 0;
    }
    getAttachedEditorCount() {
        return this._attachedEditorCount;
    }
    isTooLargeForSyncing() {
        return this._isTooLargeForSyncing;
    }
    isTooLargeForTokenization() {
        return this._isTooLargeForTokenization;
    }
    isDisposed() {
        return this._isDisposed;
    }
    isDominatedByLongLines() {
        this._assertNotDisposed();
        if (this.isTooLargeForTokenization()) {
            // Cannot word wrap huge files anyways, so it doesn't really matter
            return false;
        }
        let smallLineCharCount = 0;
        let longLineCharCount = 0;
        const lineCount = this._buffer.getLineCount();
        for (let lineNumber = 1; lineNumber <= lineCount; lineNumber++) {
            const lineLength = this._buffer.getLineLength(lineNumber);
            if (lineLength >= LONG_LINE_BOUNDARY) {
                longLineCharCount += lineLength;
            }
            else {
                smallLineCharCount += lineLength;
            }
        }
        return (longLineCharCount > smallLineCharCount);
    }
    get uri() {
        return this._associatedResource;
    }
    //#region Options
    getOptions() {
        this._assertNotDisposed();
        return this._options;
    }
    getFormattingOptions() {
        return {
            tabSize: this._options.indentSize,
            insertSpaces: this._options.insertSpaces
        };
    }
    updateOptions(_newOpts) {
        this._assertNotDisposed();
        const tabSize = (typeof _newOpts.tabSize !== 'undefined') ? _newOpts.tabSize : this._options.tabSize;
        const indentSize = (typeof _newOpts.indentSize !== 'undefined') ? _newOpts.indentSize : this._options.indentSize;
        const insertSpaces = (typeof _newOpts.insertSpaces !== 'undefined') ? _newOpts.insertSpaces : this._options.insertSpaces;
        const trimAutoWhitespace = (typeof _newOpts.trimAutoWhitespace !== 'undefined') ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace;
        const bracketPairColorizationOptions = (typeof _newOpts.bracketColorizationOptions !== 'undefined') ? _newOpts.bracketColorizationOptions : this._options.bracketPairColorizationOptions;
        const newOpts = new TextModelResolvedOptions({
            tabSize: tabSize,
            indentSize: indentSize,
            insertSpaces: insertSpaces,
            defaultEOL: this._options.defaultEOL,
            trimAutoWhitespace: trimAutoWhitespace,
            bracketPairColorizationOptions,
        });
        if (this._options.equals(newOpts)) {
            return;
        }
        const e = this._options.createChangeEvent(newOpts);
        this._options = newOpts;
        this._bracketPairs.handleDidChangeOptions(e);
        this._decorationProvider.handleDidChangeOptions(e);
        this._onDidChangeOptions.fire(e);
    }
    detectIndentation(defaultInsertSpaces, defaultTabSize) {
        this._assertNotDisposed();
        const guessedIndentation = guessIndentation(this._buffer, defaultTabSize, defaultInsertSpaces);
        this.updateOptions({
            insertSpaces: guessedIndentation.insertSpaces,
            tabSize: guessedIndentation.tabSize,
            indentSize: guessedIndentation.tabSize, // TODO@Alex: guess indentSize independent of tabSize
        });
    }
    normalizeIndentation(str) {
        this._assertNotDisposed();
        return normalizeIndentation(str, this._options.indentSize, this._options.insertSpaces);
    }
    //#endregion
    //#region Reading
    getVersionId() {
        this._assertNotDisposed();
        return this._versionId;
    }
    mightContainRTL() {
        return this._buffer.mightContainRTL();
    }
    mightContainUnusualLineTerminators() {
        return this._buffer.mightContainUnusualLineTerminators();
    }
    removeUnusualLineTerminators(selections = null) {
        const matches = this.findMatches(UNUSUAL_LINE_TERMINATORS.source, false, true, false, null, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
        this._buffer.resetMightContainUnusualLineTerminators();
        this.pushEditOperations(selections, matches.map(m => ({ range: m.range, text: null })), () => null);
    }
    mightContainNonBasicASCII() {
        return this._buffer.mightContainNonBasicASCII();
    }
    getAlternativeVersionId() {
        this._assertNotDisposed();
        return this._alternativeVersionId;
    }
    getInitialUndoRedoSnapshot() {
        this._assertNotDisposed();
        return this._initialUndoRedoSnapshot;
    }
    getOffsetAt(rawPosition) {
        this._assertNotDisposed();
        const position = this._validatePosition(rawPosition.lineNumber, rawPosition.column, 0 /* StringOffsetValidationType.Relaxed */);
        return this._buffer.getOffsetAt(position.lineNumber, position.column);
    }
    getPositionAt(rawOffset) {
        this._assertNotDisposed();
        const offset = (Math.min(this._buffer.getLength(), Math.max(0, rawOffset)));
        return this._buffer.getPositionAt(offset);
    }
    _increaseVersionId() {
        this._versionId = this._versionId + 1;
        this._alternativeVersionId = this._versionId;
    }
    _overwriteVersionId(versionId) {
        this._versionId = versionId;
    }
    _overwriteAlternativeVersionId(newAlternativeVersionId) {
        this._alternativeVersionId = newAlternativeVersionId;
    }
    _overwriteInitialUndoRedoSnapshot(newInitialUndoRedoSnapshot) {
        this._initialUndoRedoSnapshot = newInitialUndoRedoSnapshot;
    }
    getValue(eol, preserveBOM = false) {
        this._assertNotDisposed();
        const fullModelRange = this.getFullModelRange();
        const fullModelValue = this.getValueInRange(fullModelRange, eol);
        if (preserveBOM) {
            return this._buffer.getBOM() + fullModelValue;
        }
        return fullModelValue;
    }
    createSnapshot(preserveBOM = false) {
        return new TextModelSnapshot(this._buffer.createSnapshot(preserveBOM));
    }
    getValueLength(eol, preserveBOM = false) {
        this._assertNotDisposed();
        const fullModelRange = this.getFullModelRange();
        const fullModelValue = this.getValueLengthInRange(fullModelRange, eol);
        if (preserveBOM) {
            return this._buffer.getBOM().length + fullModelValue;
        }
        return fullModelValue;
    }
    getValueInRange(rawRange, eol = 0 /* model.EndOfLinePreference.TextDefined */) {
        this._assertNotDisposed();
        return this._buffer.getValueInRange(this.validateRange(rawRange), eol);
    }
    getValueLengthInRange(rawRange, eol = 0 /* model.EndOfLinePreference.TextDefined */) {
        this._assertNotDisposed();
        return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol);
    }
    getCharacterCountInRange(rawRange, eol = 0 /* model.EndOfLinePreference.TextDefined */) {
        this._assertNotDisposed();
        return this._buffer.getCharacterCountInRange(this.validateRange(rawRange), eol);
    }
    getLineCount() {
        this._assertNotDisposed();
        return this._buffer.getLineCount();
    }
    getLineContent(lineNumber) {
        this._assertNotDisposed();
        if (lineNumber < 1 || lineNumber > this.getLineCount()) {
            throw new Error('Illegal value for lineNumber');
        }
        return this._buffer.getLineContent(lineNumber);
    }
    getLineLength(lineNumber) {
        this._assertNotDisposed();
        if (lineNumber < 1 || lineNumber > this.getLineCount()) {
            throw new Error('Illegal value for lineNumber');
        }
        return this._buffer.getLineLength(lineNumber);
    }
    getLinesContent() {
        this._assertNotDisposed();
        return this._buffer.getLinesContent();
    }
    getEOL() {
        this._assertNotDisposed();
        return this._buffer.getEOL();
    }
    getEndOfLineSequence() {
        this._assertNotDisposed();
        return (this._buffer.getEOL() === '\n'
            ? 0 /* model.EndOfLineSequence.LF */
            : 1 /* model.EndOfLineSequence.CRLF */);
    }
    getLineMinColumn(lineNumber) {
        this._assertNotDisposed();
        return 1;
    }
    getLineMaxColumn(lineNumber) {
        this._assertNotDisposed();
        if (lineNumber < 1 || lineNumber > this.getLineCount()) {
            throw new Error('Illegal value for lineNumber');
        }
        return this._buffer.getLineLength(lineNumber) + 1;
    }
    getLineFirstNonWhitespaceColumn(lineNumber) {
        this._assertNotDisposed();
        if (lineNumber < 1 || lineNumber > this.getLineCount()) {
            throw new Error('Illegal value for lineNumber');
        }
        return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber);
    }
    getLineLastNonWhitespaceColumn(lineNumber) {
        this._assertNotDisposed();
        if (lineNumber < 1 || lineNumber > this.getLineCount()) {
            throw new Error('Illegal value for lineNumber');
        }
        return this._buffer.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._buffer.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 Range
            && !(range instanceof Selection)) {
            return range;
        }
        return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
    }
    _isValidPosition(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._buffer.getLineCount();
        if (lineNumber > lineCount) {
            return false;
        }
        if (column === 1) {
            return true;
        }
        const maxColumn = this.getLineMaxColumn(lineNumber);
        if (column > maxColumn) {
            return false;
        }
        if (validationType === 1 /* StringOffsetValidationType.SurrogatePairs */) {
            // !!At this point, column > 1
            const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
            if (isHighSurrogate(charCodeBefore)) {
                return false;
            }
        }
        return true;
    }
    _validatePosition(_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._buffer.getLineCount();
        if (lineNumber < 1) {
            return new Position(1, 1);
        }
        if (lineNumber > lineCount) {
            return new Position(lineCount, this.getLineMaxColumn(lineCount));
        }
        if (column <= 1) {
            return new Position(lineNumber, 1);
        }
        const maxColumn = this.getLineMaxColumn(lineNumber);
        if (column >= maxColumn) {
            return new Position(lineNumber, maxColumn);
        }
        if (validationType === 1 /* StringOffsetValidationType.SurrogatePairs */) {
            // If the position would end up in the middle of a high-low surrogate pair,
            // we move it to before the pair
            // !!At this point, column > 1
            const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
            if (isHighSurrogate(charCodeBefore)) {
                return new Position(lineNumber, column - 1);
            }
        }
        return new Position(lineNumber, column);
    }
    validatePosition(position) {
        const validationType = 1 /* StringOffsetValidationType.SurrogatePairs */;
        this._assertNotDisposed();
        // Avoid object allocation and cover most likely case
        if (position instanceof Position) {
            if (this._isValidPosition(position.lineNumber, position.column, validationType)) {
                return position;
            }
        }
        return this._validatePosition(position.lineNumber, position.column, validationType);
    }
    _isValidRange(range, validationType) {
        const startLineNumber = range.startLineNumber;
        const startColumn = range.startColumn;
        const endLineNumber = range.endLineNumber;
        const endColumn = range.endColumn;
        if (!this._isValidPosition(startLineNumber, startColumn, 0 /* StringOffsetValidationType.Relaxed */)) {
            return false;
        }
        if (!this._isValidPosition(endLineNumber, endColumn, 0 /* StringOffsetValidationType.Relaxed */)) {
            return false;
        }
        if (validationType === 1 /* StringOffsetValidationType.SurrogatePairs */) {
            const charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0);
            const charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0);
            const startInsideSurrogatePair = isHighSurrogate(charCodeBeforeStart);
            const endInsideSurrogatePair = isHighSurrogate(charCodeBeforeEnd);
            if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
                return true;
            }
            return false;
        }
        return true;
    }
    validateRange(_range) {
        const validationType = 1 /* StringOffsetValidationType.SurrogatePairs */;
        this._assertNotDisposed();
        // Avoid object allocation and cover most likely case
        if ((_range instanceof Range) && !(_range instanceof Selection)) {
            if (this._isValidRange(_range, validationType)) {
                return _range;
            }
        }
        const start = this._validatePosition(_range.startLineNumber, _range.startColumn, 0 /* StringOffsetValidationType.Relaxed */);
        const end = this._validatePosition(_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 /* StringOffsetValidationType.SurrogatePairs */) {
            const charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0);
            const charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0);
            const startInsideSurrogatePair = isHighSurrogate(charCodeBeforeStart);
            const endInsideSurrogatePair = isHighSurrogate(charCodeBeforeEnd);
            if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
                return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
            }
            if (startLineNumber === endLineNumber && startColumn === endColumn) {
                // do not expand a collapsed range, simply move it to a valid location
                return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn - 1);
            }
            if (startInsideSurrogatePair && endInsideSurrogatePair) {
                // expand range at both ends
                return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn + 1);
            }
            if (startInsideSurrogatePair) {
                // only expand range at the start
                return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn);
            }
            // only expand range at the end
            return new Range(startLineNumber, startColumn, endLineNumber, endColumn + 1);
        }
        return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
    }
    modifyPosition(rawPosition, offset) {
        this._assertNotDisposed();
        const candidate = this.getOffsetAt(rawPosition) + offset;
        return this.getPositionAt(Math.min(this._buffer.getLength(), Math.max(0, candidate)));
    }
    getFullModelRange() {
        this._assertNotDisposed();
        const lineCount = this.getLineCount();
        return new Range(1, 1, lineCount, this.getLineMaxColumn(lineCount));
    }
    findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
        return this._buffer.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
    }
    findMatches(searchString, rawSearchScope, isRegex, matchCase, wordSeparators, captureMatches, limitResultCount = textModel_LIMIT_FIND_COUNT) {
        this._assertNotDisposed();
        let searchRanges = null;
        if (rawSearchScope !== null) {
            if (!Array.isArray(rawSearchScope)) {
                rawSearchScope = [rawSearchScope];
            }
            if (rawSearchScope.every((searchScope) => Range.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 (Range.areIntersecting(prev, curr)) {
                return prev.plusRange(curr);
            }
            uniqueSearchRanges.push(prev);
            return curr;
        }));
        let matchMapper;
        if (!isRegex && searchString.indexOf('\n') < 0) {
            // not regex, not multi line
            const searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators);
            const searchData = searchParams.parseSearchRequest();
            if (!searchData) {
                return [];
            }
            matchMapper = (searchRange) => this.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
        }
        else {
            matchMapper = (searchRange) => TextModelSearch.findMatches(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchRange, captureMatches, limitResultCount);
        }
        return uniqueSearchRanges.map(matchMapper).reduce((arr, matches) => arr.concat(matches), []);
    }
    findNextMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) {
        this._assertNotDisposed();
        const searchStart = this.validatePosition(rawSearchStart);
        if (!isRegex && searchString.indexOf('\n') < 0) {
            const searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators);
            const searchData = searchParams.parseSearchRequest();
            if (!searchData) {
                return null;
            }
            const lineCount = this.getLineCount();
            let searchRange = new Range(searchStart.lineNumber, searchStart.column, lineCount, this.getLineMaxColumn(lineCount));
            let ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
            TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
            if (ret.length > 0) {
                return ret[0];
            }
            searchRange = new Range(1, 1, searchStart.lineNumber, this.getLineMaxColumn(searchStart.lineNumber));
            ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
            if (ret.length > 0) {
                return ret[0];
            }
            return null;
        }
        return TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
    }
    findPreviousMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators, captureMatches) {
        this._assertNotDisposed();
        const searchStart = this.validatePosition(rawSearchStart);
        return TextModelSearch.findPreviousMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
    }
    //#endregion
    //#region Editing
    pushStackElement() {
        this._commandManager.pushStackElement();
    }
    popStackElement() {
        this._commandManager.popStackElement();
    }
    pushEOL(eol) {
        const currentEOL = (this.getEOL() === '\n' ? 0 /* model.EndOfLineSequence.LF */ : 1 /* model.EndOfLineSequence.CRLF */);
        if (currentEOL === eol) {
            return;
        }
        try {
            this._onDidChangeDecorations.beginDeferredEmit();
            this._eventEmitter.beginDeferredEmit();
            if (this._initialUndoRedoSnapshot === null) {
                this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
            }
            this._commandManager.pushEOL(eol);
        }
        finally {
            this._eventEmitter.endDeferredEmit();
            this._onDidChangeDecorations.endDeferredEmit();
        }
    }
    _validateEditOperation(rawOperation) {
        if (rawOperation instanceof ValidAnnotatedEditOperation) {
            return rawOperation;
        }
        return new ValidAnnotatedEditOperation(rawOperation.identifier || null, this.validateRange(rawOperation.range), rawOperation.text, rawOperation.forceMoveMarkers || false, rawOperation.isAutoWhitespaceEdit || false, rawOperation._isTracked || false);
    }
    _validateEditOperations(rawOperations) {
        const result = [];
        for (let i = 0, len = rawOperations.length; i < len; i++) {
            result[i] = this._validateEditOperation(rawOperations[i]);
        }
        return result;
    }
    pushEditOperations(beforeCursorState, editOperations, cursorStateComputer) {
        try {
            this._onDidChangeDecorations.beginDeferredEmit();
            this._eventEmitter.beginDeferredEmit();
            return this._pushEditOperations(beforeCursorState, this._validateEditOperations(editOperations), cursorStateComputer);
        }
        finally {
            this._eventEmitter.endDeferredEmit();
            this._onDidChangeDecorations.endDeferredEmit();
        }
    }
    _pushEditOperations(beforeCursorState, editOperations, cursorStateComputer) {
        if (this._options.trimAutoWhitespace && this._trimAutoWhitespaceLines) {
            // Go through each saved line number and insert a trim whitespace edit
            // if it is safe to do so (no conflicts with other edits).
            const incomingEdits = editOperations.map((op) => {
                return {
                    range: this.validateRange(op.range),
                    text: op.text
                };
            });
            // Sometimes, auto-formatters change ranges automatically which can cause undesired auto whitespace trimming near the cursor
            // We'll use the following heuristic: if the edits occur near the cursor, then it's ok to trim auto whitespace
            let editsAreNearCursors = true;
            if (beforeCursorState) {
                for (let i = 0, len = beforeCursorState.length; i < len; i++) {
                    const sel = beforeCursorState[i];
                    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 i = 0, len = this._trimAutoWhitespaceLines.length; i < len; i++) {
                    const trimLineNumber = this._trimAutoWhitespaceLines[i];
                    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) {
                            // `trimLine` is completely outside this edit
                            continue;
                        }
                        // At this point:
                        //   editRange.startLineNumber <= trimLine <= editRange.endLineNumber
                        if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === maxLineColumn
                            && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(0) === '\n') {
                            // This edit inserts a new line (and maybe other text) after `trimLine`
                            continue;
                        }
                        if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === 1
                            && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(editText.length - 1) === '\n') {
                            // This edit inserts a new line (and maybe other text) before `trimLine`
                            continue;
                        }
                        // Looks like we can't trim this line as it would interfere with an incoming edit
                        allowTrimLine = false;
                        break;
                    }
                    if (allowTrimLine) {
                        const trimRange = new Range(trimLineNumber, 1, trimLineNumber, maxLineColumn);
                        editOperations.push(new ValidAnnotatedEditOperation(null, trimRange, null, false, false, false));
                    }
                }
            }
            this._trimAutoWhitespaceLines = null;
        }
        if (this._initialUndoRedoSnapshot === null) {
            this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
        }
        return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer);
    }
    _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 Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
                text: change.oldText
            };
        });
        this._applyUndoRedoEdits(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 Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
                text: change.newText
            };
        });
        this._applyUndoRedoEdits(edits, eol, false, true, resultingAlternativeVersionId, resultingSelection);
    }
    _applyUndoRedoEdits(edits, eol, isUndoing, isRedoing, resultingAlternativeVersionId, resultingSelection) {
        try {
            this._onDidChangeDecorations.beginDeferredEmit();
            this._eventEmitter.beginDeferredEmit();
            this._isUndoing = isUndoing;
            this._isRedoing = isRedoing;
            this.applyEdits(edits, false);
            this.setEOL(eol);
            this._overwriteAlternativeVersionId(resultingAlternativeVersionId);
        }
        finally {
            this._isUndoing = false;
            this._isRedoing = false;
            this._eventEmitter.endDeferredEmit(resultingSelection);
            this._onDidChangeDecorations.endDeferredEmit();
        }
    }
    applyEdits(rawOperations, computeUndoEdits = false) {
        try {
            this._onDidChangeDecorations.beginDeferredEmit();
            this._eventEmitter.beginDeferredEmit();
            const operations = this._validateEditOperations(rawOperations);
            return this._doApplyEdits(operations, computeUndoEdits);
        }
        finally {
            this._eventEmitter.endDeferredEmit();
            this._onDidChangeDecorations.endDeferredEmit();
        }
    }
    _doApplyEdits(rawOperations, computeUndoEdits) {
        const oldLineCount = this._buffer.getLineCount();
        const result = this._buffer.applyEdits(rawOperations, this._options.trimAutoWhitespace, computeUndoEdits);
        const newLineCount = this._buffer.getLineCount();
        const contentChanges = result.changes;
        this._trimAutoWhitespaceLines = result.trimAutoWhitespaceLineNumbers;
        if (contentChanges.length !== 0) {
            // We do a first pass to update tokens and decorations
            // because we want to read decorations in the second pass
            // where we will emit content change events
            // and we want to read the final decorations
            for (let i = 0, len = contentChanges.length; i < len; i++) {
                const change = contentChanges[i];
                const [eolCount, firstLineLength, lastLineLength] = countEOL(change.text);
                this._tokenizationTextModelPart.acceptEdit(change.range, change.text, eolCount, firstLineLength, lastLineLength);
                this._decorationsTree.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers);
            }
            const rawContentChanges = [];
            this._increaseVersionId();
            let lineCount = oldLineCount;
            for (let i = 0, len = contentChanges.length; i < len; i++) {
                const change = contentChanges[i];
                const [eolCount] = countEOL(change.text);
                this._onDidChangeDecorations.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._decorationsTree.getInjectedTextInInterval(this, this.getOffsetAt(new Position(firstEditLineNumber, 1)), this.getOffsetAt(new Position(lastInsertedLineNumber, this.getLineMaxColumn(lastInsertedLineNumber))), 0);
                const injectedTextInEditedRange = LineInjectedText.fromDecorations(decorationsWithInjectedTextInEditedRange);
                const injectedTextInEditedRangeQueue = new ArrayQueue(injectedTextInEditedRange);
                for (let j = editingLinesCnt; j >= 0; j--) {
                    const editLineNumber = startLineNumber + j;
                    const currentEditLineNumber = currentEditStartLineNumber + j;
                    injectedTextInEditedRangeQueue.takeFromEndWhile(r => r.lineNumber > currentEditLineNumber);
                    const decorationsInCurrentLine = injectedTextInEditedRangeQueue.takeFromEndWhile(r => r.lineNumber === currentEditLineNumber);
                    rawContentChanges.push(new ModelRawLineChanged(editLineNumber, this.getLineContent(currentEditLineNumber), decorationsInCurrentLine));
                }
                if (editingLinesCnt < deletingLinesCnt) {
                    // Must delete some lines
                    const spliceStartLineNumber = startLineNumber + editingLinesCnt;
                    rawContentChanges.push(new ModelRawLinesDeleted(spliceStartLineNumber + 1, endLineNumber));
                }
                if (editingLinesCnt < insertingLinesCnt) {
                    const injectedTextInEditedRangeQueue = new ArrayQueue(injectedTextInEditedRange);
                    // Must insert some lines
                    const spliceLineNumber = startLineNumber + editingLinesCnt;
                    const cnt = insertingLinesCnt - editingLinesCnt;
                    const fromLineNumber = newLineCount - lineCount - cnt + spliceLineNumber + 1;
                    const injectedTexts = [];
                    const newLines = [];
                    for (let i = 0; i < cnt; i++) {
                        const lineNumber = fromLineNumber + i;
                        newLines[i] = this.getLineContent(lineNumber);
                        injectedTextInEditedRangeQueue.takeWhile(r => r.lineNumber < lineNumber);
                        injectedTexts[i] = injectedTextInEditedRangeQueue.takeWhile(r => r.lineNumber === lineNumber);
                    }
                    rawContentChanges.push(new ModelRawLinesInserted(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLines, injectedTexts));
                }
                lineCount += changeLineCountDelta;
            }
            this._emitContentChangedEvent(new ModelRawContentChangedEvent(rawContentChanges, this.getVersionId(), this._isUndoing, this._isRedoing), {
                changes: contentChanges,
                eol: this._buffer.getEOL(),
                versionId: this.getVersionId(),
                isUndoing: this._isUndoing,
                isRedoing: this._isRedoing,
                isFlush: false
            });
        }
        return (result.reverseEdits === null ? undefined : result.reverseEdits);
    }
    undo() {
        return this._undoRedoService.undo(this.uri);
    }
    canUndo() {
        return this._undoRedoService.canUndo(this.uri);
    }
    redo() {
        return this._undoRedoService.redo(this.uri);
    }
    canRedo() {
        return this._undoRedoService.canRedo(this.uri);
    }
    //#endregion
    //#region Decorations
    handleBeforeFireDecorationsChangedEvent(affectedInjectedTextLines) {
        // This is called before the decoration changed event is fired.
        if (affectedInjectedTextLines === null || affectedInjectedTextLines.size === 0) {
            return;
        }
        const affectedLines = Array.from(affectedInjectedTextLines);
        const lineChangeEvents = affectedLines.map(lineNumber => new ModelRawLineChanged(lineNumber, this.getLineContent(lineNumber), this._getInjectedTextInLine(lineNumber)));
        this._onDidChangeInjectedText.fire(new ModelInjectedTextChangedEvent(lineChangeEvents));
    }
    changeDecorations(callback, ownerId = 0) {
        this._assertNotDisposed();
        try {
            this._onDidChangeDecorations.beginDeferredEmit();
            return this._changeDecorations(ownerId, callback);
        }
        finally {
            this._onDidChangeDecorations.endDeferredEmit();
        }
    }
    _changeDecorations(ownerId, callback) {
        const changeAccessor = {
            addDecoration: (range, options) => {
                return this._deltaDecorationsImpl(ownerId, [], [{ range: range, options: options }])[0];
            },
            changeDecoration: (id, newRange) => {
                this._changeDecorationImpl(id, newRange);
            },
            changeDecorationOptions: (id, options) => {
                this._changeDecorationOptionsImpl(id, _normalizeOptions(options));
            },
            removeDecoration: (id) => {
                this._deltaDecorationsImpl(ownerId, [id], []);
            },
            deltaDecorations: (oldDecorations, newDecorations) => {
                if (oldDecorations.length === 0 && newDecorations.length === 0) {
                    // nothing to do
                    return [];
                }
                return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
            }
        };
        let result = null;
        try {
            result = callback(changeAccessor);
        }
        catch (e) {
            onUnexpectedError(e);
        }
        // Invalidate change accessor
        changeAccessor.addDecoration = invalidFunc;
        changeAccessor.changeDecoration = invalidFunc;
        changeAccessor.changeDecorationOptions = invalidFunc;
        changeAccessor.removeDecoration = invalidFunc;
        changeAccessor.deltaDecorations = invalidFunc;
        return result;
    }
    deltaDecorations(oldDecorations, newDecorations, ownerId = 0) {
        this._assertNotDisposed();
        if (!oldDecorations) {
            oldDecorations = [];
        }
        if (oldDecorations.length === 0 && newDecorations.length === 0) {
            // nothing to do
            return [];
        }
        try {
            this._deltaDecorationCallCnt++;
            if (this._deltaDecorationCallCnt > 1) {
                console.warn(`Invoking deltaDecorations recursively could lead to leaking decorations.`);
                onUnexpectedError(new Error(`Invoking deltaDecorations recursively could lead to leaking decorations.`));
            }
            this._onDidChangeDecorations.beginDeferredEmit();
            return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
        }
        finally {
            this._onDidChangeDecorations.endDeferredEmit();
            this._deltaDecorationCallCnt--;
        }
    }
    _getTrackedRange(id) {
        return this.getDecorationRange(id);
    }
    _setTrackedRange(id, newRange, newStickiness) {
        const node = (id ? this._decorations[id] : null);
        if (!node) {
            if (!newRange) {
                // node doesn't exist, the request is to delete => nothing to do
                return null;
            }
            // node doesn't exist, the request is to set => add the tracked range
            return this._deltaDecorationsImpl(0, [], [{ range: newRange, options: TRACKED_RANGE_OPTIONS[newStickiness] }])[0];
        }
        if (!newRange) {
            // node exists, the request is to delete => delete node
            this._decorationsTree.delete(node);
            delete this._decorations[node.id];
            return null;
        }
        // node exists, the request is to set => change the tracked range and its options
        const range = this._validateRangeRelaxedNoAllocations(newRange);
        const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
        const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
        this._decorationsTree.delete(node);
        node.reset(this.getVersionId(), startOffset, endOffset, range);
        node.setOptions(TRACKED_RANGE_OPTIONS[newStickiness]);
        this._decorationsTree.insert(node);
        return node.id;
    }
    removeAllDecorationsWithOwnerId(ownerId) {
        if (this._isDisposed) {
            return;
        }
        const nodes = this._decorationsTree.collectNodesFromOwner(ownerId);
        for (let i = 0, len = nodes.length; i < len; i++) {
            const node = nodes[i];
            this._decorationsTree.delete(node);
            delete this._decorations[node.id];
        }
    }
    getDecorationOptions(decorationId) {
        const node = this._decorations[decorationId];
        if (!node) {
            return null;
        }
        return node.options;
    }
    getDecorationRange(decorationId) {
        const node = this._decorations[decorationId];
        if (!node) {
            return null;
        }
        return this._decorationsTree.getNodeRange(this, node);
    }
    getLineDecorations(lineNumber, ownerId = 0, filterOutValidation = false) {
        if (lineNumber < 1 || lineNumber > this.getLineCount()) {
            return [];
        }
        return this.getLinesDecorations(lineNumber, lineNumber, ownerId, filterOutValidation);
    }
    getLinesDecorations(_startLineNumber, _endLineNumber, ownerId = 0, filterOutValidation = 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 Range(startLineNumber, 1, endLineNumber, endColumn);
        const decorations = this._getDecorationsInRange(range, ownerId, filterOutValidation);
        pushMany(decorations, this._decorationProvider.getDecorationsInRange(range, ownerId, filterOutValidation));
        return decorations;
    }
    getDecorationsInRange(range, ownerId = 0, filterOutValidation = false) {
        const validatedRange = this.validateRange(range);
        const decorations = this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation);
        pushMany(decorations, this._decorationProvider.getDecorationsInRange(validatedRange, ownerId, filterOutValidation));
        return decorations;
    }
    getOverviewRulerDecorations(ownerId = 0, filterOutValidation = false) {
        return this._decorationsTree.getAll(this, ownerId, filterOutValidation, true);
    }
    getInjectedTextDecorations(ownerId = 0) {
        return this._decorationsTree.getAllInjectedText(this, ownerId);
    }
    _getInjectedTextInLine(lineNumber) {
        const startOffset = this._buffer.getOffsetAt(lineNumber, 1);
        const endOffset = startOffset + this._buffer.getLineLength(lineNumber);
        const result = this._decorationsTree.getInjectedTextInInterval(this, startOffset, endOffset, 0);
        return LineInjectedText.fromDecorations(result).filter(t => t.lineNumber === lineNumber);
    }
    getAllDecorations(ownerId = 0, filterOutValidation = false) {
        let result = this._decorationsTree.getAll(this, ownerId, filterOutValidation, false);
        result = result.concat(this._decorationProvider.getAllDecorations(ownerId, filterOutValidation));
        return result;
    }
    _getDecorationsInRange(filterRange, filterOwnerId, filterOutValidation) {
        const startOffset = this._buffer.getOffsetAt(filterRange.startLineNumber, filterRange.startColumn);
        const endOffset = this._buffer.getOffsetAt(filterRange.endLineNumber, filterRange.endColumn);
        return this._decorationsTree.getAllInInterval(this, startOffset, endOffset, filterOwnerId, filterOutValidation);
    }
    getRangeAt(start, end) {
        return this._buffer.getRangeAt(start, end - start);
    }
    _changeDecorationImpl(decorationId, _range) {
        const node = this._decorations[decorationId];
        if (!node) {
            return;
        }
        if (node.options.after) {
            const oldRange = this.getDecorationRange(decorationId);
            this._onDidChangeDecorations.recordLineAffectedByInjectedText(oldRange.endLineNumber);
        }
        if (node.options.before) {
            const oldRange = this.getDecorationRange(decorationId);
            this._onDidChangeDecorations.recordLineAffectedByInjectedText(oldRange.startLineNumber);
        }
        const range = this._validateRangeRelaxedNoAllocations(_range);
        const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
        const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
        this._decorationsTree.delete(node);
        node.reset(this.getVersionId(), startOffset, endOffset, range);
        this._decorationsTree.insert(node);
        this._onDidChangeDecorations.checkAffectedAndFire(node.options);
        if (node.options.after) {
            this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.endLineNumber);
        }
        if (node.options.before) {
            this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.startLineNumber);
        }
    }
    _changeDecorationOptionsImpl(decorationId, options) {
        const node = this._decorations[decorationId];
        if (!node) {
            return;
        }
        const nodeWasInOverviewRuler = (node.options.overviewRuler && node.options.overviewRuler.color ? true : false);
        const nodeIsInOverviewRuler = (options.overviewRuler && options.overviewRuler.color ? true : false);
        this._onDidChangeDecorations.checkAffectedAndFire(node.options);
        this._onDidChangeDecorations.checkAffectedAndFire(options);
        if (node.options.after || options.after) {
            const nodeRange = this._decorationsTree.getNodeRange(this, node);
            this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.endLineNumber);
        }
        if (node.options.before || options.before) {
            const nodeRange = this._decorationsTree.getNodeRange(this, node);
            this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.startLineNumber);
        }
        if (nodeWasInOverviewRuler !== nodeIsInOverviewRuler) {
            // Delete + Insert due to an overview ruler status change
            this._decorationsTree.delete(node);
            node.setOptions(options);
            this._decorationsTree.insert(node);
        }
        else {
            node.setOptions(options);
        }
    }
    _deltaDecorationsImpl(ownerId, 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) {
                // (1) get ourselves an old node
                do {
                    node = this._decorations[oldDecorationsIds[oldDecorationIndex++]];
                } while (!node && oldDecorationIndex < oldDecorationsLen);
                // (2) remove the node from the tree (if it exists)
                if (node) {
                    if (node.options.after) {
                        const nodeRange = this._decorationsTree.getNodeRange(this, node);
                        this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.endLineNumber);
                    }
                    if (node.options.before) {
                        const nodeRange = this._decorationsTree.getNodeRange(this, node);
                        this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.startLineNumber);
                    }
                    this._decorationsTree.delete(node);
                    this._onDidChangeDecorations.checkAffectedAndFire(node.options);
                }
            }
            if (newDecorationIndex < newDecorationsLen) {
                // (3) create a new node if necessary
                if (!node) {
                    const internalDecorationId = (++this._lastDecorationId);
                    const decorationId = `${this._instanceId};${internalDecorationId}`;
                    node = new IntervalNode(decorationId, 0, 0);
                    this._decorations[decorationId] = node;
                }
                // (4) initialize node
                const newDecoration = newDecorations[newDecorationIndex];
                const range = this._validateRangeRelaxedNoAllocations(newDecoration.range);
                const options = _normalizeOptions(newDecoration.options);
                const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
                const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
                node.ownerId = ownerId;
                node.reset(versionId, startOffset, endOffset, range);
                node.setOptions(options);
                if (node.options.after) {
                    this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.endLineNumber);
                }
                if (node.options.before) {
                    this._onDidChangeDecorations.recordLineAffectedByInjectedText(range.startLineNumber);
                }
                this._onDidChangeDecorations.checkAffectedAndFire(options);
                this._decorationsTree.insert(node);
                result[newDecorationIndex] = node.id;
                newDecorationIndex++;
            }
            else {
                if (node) {
                    delete this._decorations[node.id];
                }
            }
        }
        return result;
    }
    //#endregion
    //#region Tokenization
    // TODO move them to the tokenization part.
    getLanguageId() {
        return this.tokenization.getLanguageId();
    }
    setMode(languageId) {
        this.tokenization.setLanguageId(languageId);
    }
    getLanguageIdAtPosition(lineNumber, column) {
        return this.tokenization.getLanguageIdAtPosition(lineNumber, column);
    }
    getWordAtPosition(position) {
        return this._tokenizationTextModelPart.getWordAtPosition(position);
    }
    getWordUntilPosition(position) {
        return this._tokenizationTextModelPart.getWordUntilPosition(position);
    }
    //#endregion
    normalizePosition(position, affinity) {
        return position;
    }
    /**
     * Gets the column at which indentation stops at a given line.
     * @internal
    */
    getLineIndentColumn(lineNumber) {
        // Columns start with 1.
        return indentOfLine(this.getLineContent(lineNumber)) + 1;
    }
};
TextModel.MODEL_SYNC_LIMIT = 50 * 1024 * 1024; // 50 MB
TextModel.LARGE_FILE_SIZE_THRESHOLD = 20 * 1024 * 1024; // 20 MB;
TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD = 300 * 1000; // 300K lines
TextModel.DEFAULT_CREATION_OPTIONS = {
    isForSimpleWidget: false,
    tabSize: EDITOR_MODEL_DEFAULTS.tabSize,
    indentSize: EDITOR_MODEL_DEFAULTS.indentSize,
    insertSpaces: EDITOR_MODEL_DEFAULTS.insertSpaces,
    detectIndentation: false,
    defaultEOL: 1 /* model.DefaultEndOfLine.LF */,
    trimAutoWhitespace: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
    largeFileOptimizations: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
    bracketPairColorizationOptions: EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions,
};
TextModel = textModel_decorate([
    textModel_param(4, IUndoRedoService),
    textModel_param(5, ILanguageService),
    textModel_param(6, ILanguageConfigurationService)
], TextModel);

function indentOfLine(line) {
    let indent = 0;
    for (const c of line) {
        if (c === ' ' || c === '\t') {
            indent++;
        }
        else {
            break;
        }
    }
    return indent;
}
//#region Decorations
function isNodeInOverviewRuler(node) {
    return (node.options.overviewRuler && node.options.overviewRuler.color ? true : false);
}
function isNodeInjectedText(node) {
    return !!node.options.after || !!node.options.before;
}
class DecorationsTrees {
    constructor() {
        this._decorationsTree0 = new IntervalTree();
        this._decorationsTree1 = new IntervalTree();
        this._injectedTextDecorationsTree = new IntervalTree();
    }
    ensureAllNodesHaveRanges(host) {
        this.getAll(host, 0, false, false);
    }
    _ensureNodesHaveRanges(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) {
        const versionId = host.getVersionId();
        const result = this._intervalSearch(start, end, filterOwnerId, filterOutValidation, versionId);
        return this._ensureNodesHaveRanges(host, result);
    }
    _intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId) {
        const r0 = this._decorationsTree0.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);
        const r1 = this._decorationsTree1.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);
        const r2 = this._injectedTextDecorationsTree.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);
        return r0.concat(r1).concat(r2);
    }
    getInjectedTextInInterval(host, start, end, filterOwnerId) {
        const versionId = host.getVersionId();
        const result = this._injectedTextDecorationsTree.intervalSearch(start, end, filterOwnerId, false, versionId);
        return this._ensureNodesHaveRanges(host, result).filter((i) => i.options.showIfCollapsed || !i.range.isEmpty());
    }
    getAllInjectedText(host, filterOwnerId) {
        const versionId = host.getVersionId();
        const result = this._injectedTextDecorationsTree.search(filterOwnerId, false, versionId);
        return this._ensureNodesHaveRanges(host, result).filter((i) => i.options.showIfCollapsed || !i.range.isEmpty());
    }
    getAll(host, filterOwnerId, filterOutValidation, overviewRulerOnly) {
        const versionId = host.getVersionId();
        const result = this._search(filterOwnerId, filterOutValidation, overviewRulerOnly, versionId);
        return this._ensureNodesHaveRanges(host, result);
    }
    _search(filterOwnerId, filterOutValidation, overviewRulerOnly, cachedVersionId) {
        if (overviewRulerOnly) {
            return this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);
        }
        else {
            const r0 = this._decorationsTree0.search(filterOwnerId, filterOutValidation, cachedVersionId);
            const r1 = this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);
            const r2 = this._injectedTextDecorationsTree.search(filterOwnerId, filterOutValidation, cachedVersionId);
            return r0.concat(r1).concat(r2);
        }
    }
    collectNodesFromOwner(ownerId) {
        const r0 = this._decorationsTree0.collectNodesFromOwner(ownerId);
        const r1 = this._decorationsTree1.collectNodesFromOwner(ownerId);
        const r2 = this._injectedTextDecorationsTree.collectNodesFromOwner(ownerId);
        return r0.concat(r1).concat(r2);
    }
    collectNodesPostOrder() {
        const r0 = this._decorationsTree0.collectNodesPostOrder();
        const r1 = this._decorationsTree1.collectNodesPostOrder();
        const r2 = this._injectedTextDecorationsTree.collectNodesPostOrder();
        return r0.concat(r1).concat(r2);
    }
    insert(node) {
        if (isNodeInjectedText(node)) {
            this._injectedTextDecorationsTree.insert(node);
        }
        else if (isNodeInOverviewRuler(node)) {
            this._decorationsTree1.insert(node);
        }
        else {
            this._decorationsTree0.insert(node);
        }
    }
    delete(node) {
        if (isNodeInjectedText(node)) {
            this._injectedTextDecorationsTree.delete(node);
        }
        else if (isNodeInOverviewRuler(node)) {
            this._decorationsTree1.delete(node);
        }
        else {
            this._decorationsTree0.delete(node);
        }
    }
    getNodeRange(host, node) {
        const versionId = host.getVersionId();
        if (node.cachedVersionId !== versionId) {
            this._resolveNode(node, versionId);
        }
        if (node.range === null) {
            node.range = host.getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
        }
        return node.range;
    }
    _resolveNode(node, cachedVersionId) {
        if (isNodeInjectedText(node)) {
            this._injectedTextDecorationsTree.resolveNode(node, cachedVersionId);
        }
        else if (isNodeInOverviewRuler(node)) {
            this._decorationsTree1.resolveNode(node, cachedVersionId);
        }
        else {
            this._decorationsTree0.resolveNode(node, cachedVersionId);
        }
    }
    acceptReplace(offset, length, textLength, forceMoveMarkers) {
        this._decorationsTree0.acceptReplace(offset, length, textLength, forceMoveMarkers);
        this._decorationsTree1.acceptReplace(offset, length, textLength, forceMoveMarkers);
        this._injectedTextDecorationsTree.acceptReplace(offset, length, textLength, forceMoveMarkers);
    }
}
function cleanClassName(className) {
    return className.replace(/[^a-z0-9\-_]/gi, ' ');
}
class DecorationOptions {
    constructor(options) {
        this.color = options.color || '';
        this.darkColor = options.darkColor || '';
    }
}
class ModelDecorationOverviewRulerOptions extends DecorationOptions {
    constructor(options) {
        super(options);
        this._resolvedColor = null;
        this.position = (typeof options.position === 'number' ? options.position : OverviewRulerLane.Center);
    }
    getColor(theme) {
        if (!this._resolvedColor) {
            if (theme.type !== 'light' && this.darkColor) {
                this._resolvedColor = this._resolveColor(this.darkColor, theme);
            }
            else {
                this._resolvedColor = this._resolveColor(this.color, theme);
            }
        }
        return this._resolvedColor;
    }
    invalidateCachedColor() {
        this._resolvedColor = null;
    }
    _resolveColor(color, theme) {
        if (typeof color === 'string') {
            return color;
        }
        const c = color ? theme.getColor(color.id) : null;
        if (!c) {
            return '';
        }
        return c.toString();
    }
}
class ModelDecorationMinimapOptions extends DecorationOptions {
    constructor(options) {
        super(options);
        this.position = options.position;
    }
    getColor(theme) {
        if (!this._resolvedColor) {
            if (theme.type !== 'light' && this.darkColor) {
                this._resolvedColor = this._resolveColor(this.darkColor, theme);
            }
            else {
                this._resolvedColor = this._resolveColor(this.color, theme);
            }
        }
        return this._resolvedColor;
    }
    invalidateCachedColor() {
        this._resolvedColor = undefined;
    }
    _resolveColor(color, theme) {
        if (typeof color === 'string') {
            return Color.fromHex(color);
        }
        return theme.getColor(color.id);
    }
}
class ModelDecorationInjectedTextOptions {
    constructor(options) {
        this.content = options.content || '';
        this.inlineClassName = options.inlineClassName || null;
        this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
        this.attachedData = options.attachedData || null;
        this.cursorStops = options.cursorStops || null;
    }
    static from(options) {
        if (options instanceof ModelDecorationInjectedTextOptions) {
            return options;
        }
        return new ModelDecorationInjectedTextOptions(options);
    }
}
class ModelDecorationOptions {
    constructor(options) {
        var _a, _b;
        this.description = options.description;
        this.blockClassName = options.blockClassName ? cleanClassName(options.blockClassName) : null;
        this.stickiness = options.stickiness || 0 /* model.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */;
        this.zIndex = options.zIndex || 0;
        this.className = options.className ? cleanClassName(options.className) : null;
        this.hoverMessage = options.hoverMessage || null;
        this.glyphMarginHoverMessage = options.glyphMarginHoverMessage || null;
        this.isWholeLine = options.isWholeLine || false;
        this.showIfCollapsed = options.showIfCollapsed || false;
        this.collapseOnReplaceEdit = options.collapseOnReplaceEdit || false;
        this.overviewRuler = options.overviewRuler ? new ModelDecorationOverviewRulerOptions(options.overviewRuler) : null;
        this.minimap = options.minimap ? new ModelDecorationMinimapOptions(options.minimap) : null;
        this.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : null;
        this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : null;
        this.firstLineDecorationClassName = options.firstLineDecorationClassName ? cleanClassName(options.firstLineDecorationClassName) : null;
        this.marginClassName = options.marginClassName ? cleanClassName(options.marginClassName) : null;
        this.inlineClassName = options.inlineClassName ? cleanClassName(options.inlineClassName) : null;
        this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
        this.beforeContentClassName = options.beforeContentClassName ? cleanClassName(options.beforeContentClassName) : null;
        this.afterContentClassName = options.afterContentClassName ? cleanClassName(options.afterContentClassName) : null;
        this.after = options.after ? ModelDecorationInjectedTextOptions.from(options.after) : null;
        this.before = options.before ? ModelDecorationInjectedTextOptions.from(options.before) : null;
        this.hideInCommentTokens = (_a = options.hideInCommentTokens) !== null && _a !== void 0 ? _a : false;
        this.hideInStringTokens = (_b = options.hideInStringTokens) !== null && _b !== void 0 ? _b : false;
    }
    static register(options) {
        return new ModelDecorationOptions(options);
    }
    static createDynamic(options) {
        return new ModelDecorationOptions(options);
    }
}
ModelDecorationOptions.EMPTY = ModelDecorationOptions.register({ description: 'empty' });
/**
 * The order carefully matches the values of the enum.
 */
const TRACKED_RANGE_OPTIONS = [
    ModelDecorationOptions.register({ description: 'tracked-range-always-grows-when-typing-at-edges', stickiness: 0 /* model.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */ }),
    ModelDecorationOptions.register({ description: 'tracked-range-never-grows-when-typing-at-edges', stickiness: 1 /* model.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */ }),
    ModelDecorationOptions.register({ description: 'tracked-range-grows-only-when-typing-before', stickiness: 2 /* model.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */ }),
    ModelDecorationOptions.register({ description: 'tracked-range-grows-only-when-typing-after', stickiness: 3 /* model.TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */ }),
];
function _normalizeOptions(options) {
    if (options instanceof ModelDecorationOptions) {
        return options;
    }
    return ModelDecorationOptions.createDynamic(options);
}
class DidChangeDecorationsEmitter extends Disposable {
    constructor(handleBeforeFire) {
        super();
        this.handleBeforeFire = handleBeforeFire;
        this._actual = this._register(new Emitter());
        this.event = this._actual.event;
        this._affectedInjectedTextLines = null;
        this._deferredCnt = 0;
        this._shouldFire = false;
        this._affectsMinimap = false;
        this._affectsOverviewRuler = false;
    }
    beginDeferredEmit() {
        this._deferredCnt++;
    }
    endDeferredEmit() {
        var _a;
        this._deferredCnt--;
        if (this._deferredCnt === 0) {
            if (this._shouldFire) {
                this.handleBeforeFire(this._affectedInjectedTextLines);
                const event = {
                    affectsMinimap: this._affectsMinimap,
                    affectsOverviewRuler: this._affectsOverviewRuler
                };
                this._shouldFire = false;
                this._affectsMinimap = false;
                this._affectsOverviewRuler = false;
                this._actual.fire(event);
            }
            (_a = this._affectedInjectedTextLines) === null || _a === void 0 ? void 0 : _a.clear();
            this._affectedInjectedTextLines = null;
        }
    }
    recordLineAffectedByInjectedText(lineNumber) {
        if (!this._affectedInjectedTextLines) {
            this._affectedInjectedTextLines = new Set();
        }
        this._affectedInjectedTextLines.add(lineNumber);
    }
    checkAffectedAndFire(options) {
        if (!this._affectsMinimap) {
            this._affectsMinimap = options.minimap && options.minimap.position ? true : false;
        }
        if (!this._affectsOverviewRuler) {
            this._affectsOverviewRuler = options.overviewRuler && options.overviewRuler.color ? true : false;
        }
        this._shouldFire = true;
    }
    fire() {
        this._affectsMinimap = true;
        this._affectsOverviewRuler = true;
        this._shouldFire = true;
    }
}
//#endregion
class DidChangeContentEmitter extends Disposable {
    constructor() {
        super();
        /**
         * Both `fastEvent` and `slowEvent` work the same way and contain the same events, but first we invoke `fastEvent` and then `slowEvent`.
         */
        this._fastEmitter = this._register(new Emitter());
        this.fastEvent = this._fastEmitter.event;
        this._slowEmitter = this._register(new Emitter());
        this.slowEvent = this._slowEmitter.event;
        this._deferredCnt = 0;
        this._deferredEvent = null;
    }
    beginDeferredEmit() {
        this._deferredCnt++;
    }
    endDeferredEmit(resultingSelection = null) {
        this._deferredCnt--;
        if (this._deferredCnt === 0) {
            if (this._deferredEvent !== null) {
                this._deferredEvent.rawContentChangedEvent.resultingSelection = resultingSelection;
                const e = this._deferredEvent;
                this._deferredEvent = null;
                this._fastEmitter.fire(e);
                this._slowEmitter.fire(e);
            }
        }
    }
    fire(e) {
        if (this._deferredCnt > 0) {
            if (this._deferredEvent) {
                this._deferredEvent = this._deferredEvent.merge(e);
            }
            else {
                this._deferredEvent = e;
            }
            return;
        }
        this._fastEmitter.fire(e);
        this._slowEmitter.fire(e);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/bracketMatching/browser/bracketMatching.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/















const overviewRulerBracketMatchForeground = registerColor('editorOverviewRuler.bracketMatchForeground', { dark: '#A0A0A0', light: '#A0A0A0', hcDark: '#A0A0A0', hcLight: '#A0A0A0' }, localize('overviewRulerBracketMatchForeground', 'Overview ruler marker color for matching brackets.'));
class JumpToBracketAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.jumpToBracket',
            label: localize('smartSelect.jumpBracket', "Go to Bracket"),
            alias: 'Go to Bracket',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 88 /* KeyCode.Backslash */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        var _a;
        (_a = BracketMatchingController.get(editor)) === null || _a === void 0 ? void 0 : _a.jumpToBracket();
    }
}
class SelectToBracketAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.selectToBracket',
            label: localize('smartSelect.selectToBracket', "Select to Bracket"),
            alias: 'Select to Bracket',
            precondition: undefined,
            description: {
                description: `Select to Bracket`,
                args: [{
                        name: 'args',
                        schema: {
                            type: 'object',
                            properties: {
                                'selectBrackets': {
                                    type: 'boolean',
                                    default: true
                                }
                            },
                        }
                    }]
            }
        });
    }
    run(accessor, editor, args) {
        var _a;
        let selectBrackets = true;
        if (args && args.selectBrackets === false) {
            selectBrackets = false;
        }
        (_a = BracketMatchingController.get(editor)) === null || _a === void 0 ? void 0 : _a.selectToBracket(selectBrackets);
    }
}
class BracketsData {
    constructor(position, brackets, options) {
        this.position = position;
        this.brackets = brackets;
        this.options = options;
    }
}
class BracketMatchingController extends Disposable {
    constructor(editor) {
        super();
        this._editor = editor;
        this._lastBracketsData = [];
        this._lastVersionId = 0;
        this._decorations = this._editor.createDecorationsCollection();
        this._updateBracketsSoon = this._register(new RunOnceScheduler(() => this._updateBrackets(), 50));
        this._matchBrackets = this._editor.getOption(66 /* EditorOption.matchBrackets */);
        this._updateBracketsSoon.schedule();
        this._register(editor.onDidChangeCursorPosition((e) => {
            if (this._matchBrackets === 'never') {
                // Early exit if nothing needs to be done!
                // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;)
                return;
            }
            this._updateBracketsSoon.schedule();
        }));
        this._register(editor.onDidChangeModelContent((e) => {
            this._updateBracketsSoon.schedule();
        }));
        this._register(editor.onDidChangeModel((e) => {
            this._lastBracketsData = [];
            this._updateBracketsSoon.schedule();
        }));
        this._register(editor.onDidChangeModelLanguageConfiguration((e) => {
            this._lastBracketsData = [];
            this._updateBracketsSoon.schedule();
        }));
        this._register(editor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(66 /* EditorOption.matchBrackets */)) {
                this._matchBrackets = this._editor.getOption(66 /* EditorOption.matchBrackets */);
                this._decorations.clear();
                this._lastBracketsData = [];
                this._lastVersionId = 0;
                this._updateBracketsSoon.schedule();
            }
        }));
        this._register(editor.onDidBlurEditorWidget(() => {
            this._updateBracketsSoon.schedule();
        }));
        this._register(editor.onDidFocusEditorWidget(() => {
            this._updateBracketsSoon.schedule();
        }));
    }
    static get(editor) {
        return editor.getContribution(BracketMatchingController.ID);
    }
    jumpToBracket() {
        if (!this._editor.hasModel()) {
            return;
        }
        const model = this._editor.getModel();
        const newSelections = this._editor.getSelections().map(selection => {
            const position = selection.getStartPosition();
            // find matching brackets if position is on a bracket
            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 {
                // find the enclosing brackets if the position isn't on a matching bracket
                const enclosingBrackets = model.bracketPairs.findEnclosingBrackets(position);
                if (enclosingBrackets) {
                    newCursorPosition = enclosingBrackets[1].getStartPosition();
                }
                else {
                    // no enclosing brackets, try the very first next bracket
                    const nextBracket = model.bracketPairs.findNextBracket(position);
                    if (nextBracket && nextBracket.range) {
                        newCursorPosition = nextBracket.range.getStartPosition();
                    }
                }
            }
            if (newCursorPosition) {
                return new Selection(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
            }
            return new Selection(position.lineNumber, position.column, position.lineNumber, position.column);
        });
        this._editor.setSelections(newSelections);
        this._editor.revealRange(newSelections[0]);
    }
    selectToBracket(selectBrackets) {
        if (!this._editor.hasModel()) {
            return;
        }
        const model = this._editor.getModel();
        const newSelections = [];
        this._editor.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(Range.compareRangesUsingStarts);
                const [open, close] = brackets;
                selectFrom = selectBrackets ? open.getStartPosition() : open.getEndPosition();
                selectTo = selectBrackets ? close.getEndPosition() : close.getStartPosition();
                if (close.containsPosition(position)) {
                    // select backwards if the cursor was on the closing bracket
                    const tmp = selectFrom;
                    selectFrom = selectTo;
                    selectTo = tmp;
                }
            }
            if (selectFrom && selectTo) {
                newSelections.push(new Selection(selectFrom.lineNumber, selectFrom.column, selectTo.lineNumber, selectTo.column));
            }
        });
        if (newSelections.length > 0) {
            this._editor.setSelections(newSelections);
            this._editor.revealRange(newSelections[0]);
        }
    }
    _updateBrackets() {
        if (this._matchBrackets === 'never') {
            return;
        }
        this._recomputeBrackets();
        const newDecorations = [];
        let newDecorationsLen = 0;
        for (const bracketData of this._lastBracketsData) {
            const brackets = bracketData.brackets;
            if (brackets) {
                newDecorations[newDecorationsLen++] = { range: brackets[0], options: bracketData.options };
                newDecorations[newDecorationsLen++] = { range: brackets[1], options: bracketData.options };
            }
        }
        this._decorations.set(newDecorations);
    }
    _recomputeBrackets() {
        if (!this._editor.hasModel() || !this._editor.hasWidgetFocus()) {
            // no model or no focus => no brackets!
            this._lastBracketsData = [];
            this._lastVersionId = 0;
            return;
        }
        const selections = this._editor.getSelections();
        if (selections.length > 100) {
            // no bracket matching for high numbers of selections
            this._lastBracketsData = [];
            this._lastVersionId = 0;
            return;
        }
        const model = this._editor.getModel();
        const versionId = model.getVersionId();
        let previousData = [];
        if (this._lastVersionId === versionId) {
            // use the previous data only if the model is at the same version id
            previousData = this._lastBracketsData;
        }
        const positions = [];
        let positionsLen = 0;
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            if (selection.isEmpty()) {
                // will bracket match a cursor only if the selection is collapsed
                positions[positionsLen++] = selection.getStartPosition();
            }
        }
        // sort positions for `previousData` cache hits
        if (positions.length > 1) {
            positions.sort(Position.compare);
        }
        const newData = [];
        let newDataLen = 0;
        let previousIndex = 0;
        const previousLen = previousData.length;
        for (let i = 0, len = positions.length; i < len; i++) {
            const position = positions[i];
            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 options = BracketMatchingController._DECORATION_OPTIONS_WITH_OVERVIEW_RULER;
                if (!brackets && this._matchBrackets === 'always') {
                    brackets = model.bracketPairs.findEnclosingBrackets(position, 20 /* give at most 20ms to compute */);
                    options = BracketMatchingController._DECORATION_OPTIONS_WITHOUT_OVERVIEW_RULER;
                }
                newData[newDataLen++] = new BracketsData(position, brackets, options);
            }
        }
        this._lastBracketsData = newData;
        this._lastVersionId = versionId;
    }
}
BracketMatchingController.ID = 'editor.contrib.bracketMatchingController';
BracketMatchingController._DECORATION_OPTIONS_WITH_OVERVIEW_RULER = ModelDecorationOptions.register({
    description: 'bracket-match-overview',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    className: 'bracket-match',
    overviewRuler: {
        color: themeColorFromId(overviewRulerBracketMatchForeground),
        position: OverviewRulerLane.Center
    }
});
BracketMatchingController._DECORATION_OPTIONS_WITHOUT_OVERVIEW_RULER = ModelDecorationOptions.register({
    description: 'bracket-match-no-overview',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    className: 'bracket-match'
});
registerEditorContribution(BracketMatchingController.ID, BracketMatchingController);
registerEditorAction(SelectToBracketAction);
registerEditorAction(JumpToBracketAction);
registerThemingParticipant((theme, collector) => {
    const bracketMatchBackground = theme.getColor(editorBracketMatchBackground);
    if (bracketMatchBackground) {
        collector.addRule(`.monaco-editor .bracket-match { background-color: ${bracketMatchBackground}; }`);
    }
    const bracketMatchBorder = theme.getColor(editorBracketMatchBorder);
    if (bracketMatchBorder) {
        collector.addRule(`.monaco-editor .bracket-match { border: 1px solid ${bracketMatchBorder}; }`);
    }
});
// Go to menu
MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, {
    group: '5_infile_nav',
    command: {
        id: 'editor.action.jumpToBracket',
        title: localize({ key: 'miGoToBracket', comment: ['&& denotes a mnemonic'] }, "Go to &&Bracket")
    },
    order: 2
});

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursorCommon.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






const autoCloseAlways = () => true;
const autoCloseNever = () => false;
const autoCloseBeforeWhitespace = (chr) => (chr === ' ' || chr === '\t');
class CursorConfiguration {
    constructor(languageId, modelOptions, configuration, languageConfigurationService) {
        this.languageConfigurationService = languageConfigurationService;
        this._cursorMoveConfigurationBrand = undefined;
        this._languageId = languageId;
        const options = configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this.readOnly = options.get(83 /* EditorOption.readOnly */);
        this.tabSize = modelOptions.tabSize;
        this.indentSize = modelOptions.indentSize;
        this.insertSpaces = modelOptions.insertSpaces;
        this.stickyTabStops = options.get(106 /* EditorOption.stickyTabStops */);
        this.lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2);
        this.useTabStops = options.get(118 /* EditorOption.useTabStops */);
        this.wordSeparators = options.get(119 /* EditorOption.wordSeparators */);
        this.emptySelectionClipboard = options.get(33 /* EditorOption.emptySelectionClipboard */);
        this.copyWithSyntaxHighlighting = options.get(21 /* EditorOption.copyWithSyntaxHighlighting */);
        this.multiCursorMergeOverlapping = options.get(71 /* EditorOption.multiCursorMergeOverlapping */);
        this.multiCursorPaste = options.get(73 /* EditorOption.multiCursorPaste */);
        this.autoClosingBrackets = options.get(5 /* EditorOption.autoClosingBrackets */);
        this.autoClosingQuotes = options.get(8 /* EditorOption.autoClosingQuotes */);
        this.autoClosingDelete = options.get(6 /* EditorOption.autoClosingDelete */);
        this.autoClosingOvertype = options.get(7 /* EditorOption.autoClosingOvertype */);
        this.autoSurround = options.get(11 /* EditorOption.autoSurround */);
        this.autoIndent = options.get(9 /* EditorOption.autoIndent */);
        this.surroundingPairs = {};
        this._electricChars = null;
        this.shouldAutoCloseBefore = {
            quote: this._getShouldAutoClose(languageId, this.autoClosingQuotes),
            bracket: this._getShouldAutoClose(languageId, this.autoClosingBrackets)
        };
        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;
            }
        }
    }
    static shouldRecreate(e) {
        return (e.hasChanged(133 /* EditorOption.layoutInfo */)
            || e.hasChanged(119 /* EditorOption.wordSeparators */)
            || e.hasChanged(33 /* EditorOption.emptySelectionClipboard */)
            || e.hasChanged(71 /* EditorOption.multiCursorMergeOverlapping */)
            || e.hasChanged(73 /* EditorOption.multiCursorPaste */)
            || e.hasChanged(5 /* EditorOption.autoClosingBrackets */)
            || e.hasChanged(8 /* EditorOption.autoClosingQuotes */)
            || e.hasChanged(6 /* EditorOption.autoClosingDelete */)
            || e.hasChanged(7 /* EditorOption.autoClosingOvertype */)
            || e.hasChanged(11 /* EditorOption.autoSurround */)
            || e.hasChanged(118 /* EditorOption.useTabStops */)
            || e.hasChanged(61 /* EditorOption.lineHeight */)
            || e.hasChanged(83 /* EditorOption.readOnly */));
    }
    get electricChars() {
        var _a;
        if (!this._electricChars) {
            this._electricChars = {};
            const electricChars = (_a = this.languageConfigurationService.getLanguageConfiguration(this._languageId).electricCharacter) === null || _a === void 0 ? void 0 : _a.getElectricCharacters();
            if (electricChars) {
                for (const char of electricChars) {
                    this._electricChars[char] = true;
                }
            }
        }
        return this._electricChars;
    }
    /**
     * Should return opening bracket type to match indentation with
     */
    onElectricCharacter(character, context, column) {
        const scopedLineTokens = createScopedLineTokens(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 normalizeIndentation(str, this.indentSize, this.insertSpaces);
    }
    _getShouldAutoClose(languageId, autoCloseConfig) {
        switch (autoCloseConfig) {
            case 'beforeWhitespace':
                return autoCloseBeforeWhitespace;
            case 'languageDefined':
                return this._getLanguageDefinedShouldAutoClose(languageId);
            case 'always':
                return autoCloseAlways;
            case 'never':
                return autoCloseNever;
        }
    }
    _getLanguageDefinedShouldAutoClose(languageId) {
        const autoCloseBeforeSet = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoCloseBeforeSet();
        return c => autoCloseBeforeSet.indexOf(c) !== -1;
    }
    /**
     * Returns a visible column from a column.
     * @see {@link CursorColumns}
     */
    visibleColumnFromColumn(model, position) {
        return CursorColumns.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, this.tabSize);
    }
    /**
     * Returns a visible column from a column.
     * @see {@link CursorColumns}
     */
    columnFromVisibleColumn(model, lineNumber, visibleColumn) {
        const result = CursorColumns.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;
    }
}
class CursorState {
    constructor(modelState, viewState) {
        this._cursorStateBrand = undefined;
        this.modelState = modelState;
        this.viewState = viewState;
    }
    static fromModelState(modelState) {
        return new PartialModelCursorState(modelState);
    }
    static fromViewState(viewState) {
        return new PartialViewCursorState(viewState);
    }
    static fromModelSelection(modelSelection) {
        const selection = Selection.liftSelection(modelSelection);
        const modelState = new SingleCursorState(Range.fromPositions(selection.getSelectionStart()), 0, selection.getPosition(), 0);
        return CursorState.fromModelState(modelState);
    }
    static fromModelSelections(modelSelections) {
        const states = [];
        for (let i = 0, len = modelSelections.length; i < len; i++) {
            states[i] = this.fromModelSelection(modelSelections[i]);
        }
        return states;
    }
    equals(other) {
        return (this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState));
    }
}
class PartialModelCursorState {
    constructor(modelState) {
        this.modelState = modelState;
        this.viewState = null;
    }
}
class PartialViewCursorState {
    constructor(viewState) {
        this.modelState = null;
        this.viewState = viewState;
    }
}
/**
 * Represents the cursor state on either the model or on the view model.
 */
class SingleCursorState {
    constructor(selectionStart, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns) {
        this._singleCursorStateBrand = undefined;
        this.selectionStart = selectionStart;
        this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns;
        this.position = position;
        this.leftoverVisibleColumns = leftoverVisibleColumns;
        this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position);
    }
    equals(other) {
        return (this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns
            && this.leftoverVisibleColumns === other.leftoverVisibleColumns
            && 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) {
            // move just position
            return new SingleCursorState(this.selectionStart, this.selectionStartLeftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns);
        }
        else {
            // move everything
            return new SingleCursorState(new Range(lineNumber, column, lineNumber, column), leftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns);
        }
    }
    static _computeSelection(selectionStart, position) {
        if (selectionStart.isEmpty() || !position.isBeforeOrEqual(selectionStart.getStartPosition())) {
            return Selection.fromPositions(selectionStart.getStartPosition(), position);
        }
        else {
            return Selection.fromPositions(selectionStart.getEndPosition(), position);
        }
    }
}
class EditOperationResult {
    constructor(type, commands, opts) {
        this._editOperationResultBrand = undefined;
        this.type = type;
        this.commands = commands;
        this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore;
        this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter;
    }
}
function isQuote(ch) {
    return (ch === '\'' || ch === '"' || ch === '`');
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursor/cursorColumnSelection.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class ColumnSelection {
    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 = [];
        // console.log(`fromVisibleColumn: ${fromVisibleColumn}, toVisibleColumn: ${toVisibleColumn}`);
        for (let i = 0; i < lineCount; i++) {
            const lineNumber = fromLineNumber + (reversed ? -i : i);
            const startColumn = config.columnFromVisibleColumn(model, lineNumber, fromVisibleColumn);
            const endColumn = config.columnFromVisibleColumn(model, lineNumber, toVisibleColumn);
            const visibleStartColumn = config.visibleColumnFromColumn(model, new Position(lineNumber, startColumn));
            const visibleEndColumn = config.visibleColumnFromColumn(model, new Position(lineNumber, endColumn));
            // console.log(`lineNumber: ${lineNumber}: visibleStartColumn: ${visibleStartColumn}, visibleEndColumn: ${visibleEndColumn}`);
            if (isLTR) {
                if (visibleStartColumn > toVisibleColumn) {
                    continue;
                }
                if (visibleEndColumn < fromVisibleColumn) {
                    continue;
                }
            }
            if (isRTL) {
                if (visibleEndColumn > fromVisibleColumn) {
                    continue;
                }
                if (visibleStartColumn < toVisibleColumn) {
                    continue;
                }
            }
            result.push(new SingleCursorState(new Range(lineNumber, startColumn, lineNumber, startColumn), 0, new Position(lineNumber, endColumn), 0));
        }
        if (result.length === 0) {
            // We are after all the lines, so add cursor at the end of each line
            for (let i = 0; i < lineCount; i++) {
                const lineNumber = fromLineNumber + (reversed ? -i : i);
                const maxColumn = model.getLineMaxColumn(lineNumber);
                result.push(new SingleCursorState(new Range(lineNumber, maxColumn, lineNumber, maxColumn), 0, new Position(lineNumber, maxColumn), 0));
            }
        }
        return {
            viewStates: result,
            reversed: reversed,
            fromLineNumber: fromLineNumber,
            fromVisualColumn: fromVisibleColumn,
            toLineNumber: toLineNumber,
            toVisualColumn: toVisibleColumn
        };
    }
    static columnSelectLeft(config, model, prevColumnSelectData) {
        let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn;
        if (toViewVisualColumn > 0) {
            toViewVisualColumn--;
        }
        return ColumnSelection.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 Position(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);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/commands/replaceCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class ReplaceCommand {
    constructor(range, text, insertsAutoWhitespace = false) {
        this._range = range;
        this._text = text;
        this.insertsAutoWhitespace = insertsAutoWhitespace;
    }
    getEditOperations(model, builder) {
        builder.addTrackedEditOperation(this._range, this._text);
    }
    computeCursorState(model, helper) {
        const inverseEditOperations = helper.getInverseEditOperations();
        const srcRange = inverseEditOperations[0].range;
        return Selection.fromPositions(srcRange.getEndPosition());
    }
}
class ReplaceCommandThatSelectsText {
    constructor(range, text) {
        this._range = range;
        this._text = text;
    }
    getEditOperations(model, builder) {
        builder.addTrackedEditOperation(this._range, this._text);
    }
    computeCursorState(model, helper) {
        const inverseEditOperations = helper.getInverseEditOperations();
        const srcRange = inverseEditOperations[0].range;
        return Selection.fromRange(srcRange, 0 /* SelectionDirection.LTR */);
    }
}
class ReplaceCommandWithoutChangingPosition {
    constructor(range, text, insertsAutoWhitespace = false) {
        this._range = range;
        this._text = text;
        this.insertsAutoWhitespace = insertsAutoWhitespace;
    }
    getEditOperations(model, builder) {
        builder.addTrackedEditOperation(this._range, this._text);
    }
    computeCursorState(model, helper) {
        const inverseEditOperations = helper.getInverseEditOperations();
        const srcRange = inverseEditOperations[0].range;
        return Selection.fromPositions(srcRange.getStartPosition());
    }
}
class ReplaceCommandWithOffsetCursorState {
    constructor(range, text, lineNumberDeltaOffset, columnDeltaOffset, insertsAutoWhitespace = false) {
        this._range = range;
        this._text = text;
        this._columnDeltaOffset = columnDeltaOffset;
        this._lineNumberDeltaOffset = lineNumberDeltaOffset;
        this.insertsAutoWhitespace = insertsAutoWhitespace;
    }
    getEditOperations(model, builder) {
        builder.addTrackedEditOperation(this._range, this._text);
    }
    computeCursorState(model, helper) {
        const inverseEditOperations = helper.getInverseEditOperations();
        const srcRange = inverseEditOperations[0].range;
        return Selection.fromPositions(srcRange.getEndPosition().delta(this._lineNumberDeltaOffset, this._columnDeltaOffset));
    }
}
class ReplaceCommandThatPreservesSelection {
    constructor(editRange, text, initialSelection, forceMoveMarkers = false) {
        this._range = editRange;
        this._text = text;
        this._initialSelection = initialSelection;
        this._forceMoveMarkers = forceMoveMarkers;
        this._selectionId = null;
    }
    getEditOperations(model, builder) {
        builder.addTrackedEditOperation(this._range, this._text, this._forceMoveMarkers);
        this._selectionId = builder.trackSelection(this._initialSelection);
    }
    computeCursorState(model, helper) {
        return helper.getTrackedSelection(this._selectionId);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursor/cursorAtomicMoveOperations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class AtomicTabMoveOperations {
    /**
     * 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 i = 0; i < lineLength; i++) {
            if (i === position) {
                return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn];
            }
            if (visibleColumn % tabSize === 0) {
                prevTabStopPosition = i;
                prevTabStopVisibleColumn = visibleColumn;
            }
            const chCode = lineContent.charCodeAt(i);
            switch (chCode) {
                case 32 /* CharCode.Space */:
                    visibleColumn += 1;
                    break;
                case 9 /* CharCode.Tab */:
                    // Skip to the next multiple of tabSize.
                    visibleColumn = CursorColumns.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;
        // Get the 0-based visible column corresponding to the position, or return
        // -1 if it is not in the initial whitespace.
        const [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn] = AtomicTabMoveOperations.whitespaceVisibleColumn(lineContent, position, tabSize);
        if (visibleColumn === -1) {
            return -1;
        }
        // Is the output left or right of the current position. The case for nearest
        // where it is the same as the current position is handled in the switch.
        let left;
        switch (direction) {
            case 0 /* Direction.Left */:
                left = true;
                break;
            case 1 /* Direction.Right */:
                left = false;
                break;
            case 2 /* Direction.Nearest */:
                // The code below assumes the output position is either left or right
                // of the input position. If it is the same, return immediately.
                if (visibleColumn % tabSize === 0) {
                    return position;
                }
                // Go to the nearest indentation.
                left = visibleColumn % tabSize <= (tabSize / 2);
                break;
        }
        // If going left, we can just use the info about the last tab stop position and
        // last tab stop visible column that we computed in the first walk over the whitespace.
        if (left) {
            if (prevTabStopPosition === -1) {
                return -1;
            }
            // If the direction is left, we need to keep scanning right to ensure
            // that targetVisibleColumn + tabSize is before non-whitespace.
            // This is so that when we press left at the end of a partial
            // indentation it only goes one character. For example '      foo' with
            // tabSize 4, should jump from position 6 to position 5, not 4.
            let currentVisibleColumn = prevTabStopVisibleColumn;
            for (let i = prevTabStopPosition; i < lineLength; ++i) {
                if (currentVisibleColumn === prevTabStopVisibleColumn + tabSize) {
                    // It is a full indentation.
                    return prevTabStopPosition;
                }
                const chCode = lineContent.charCodeAt(i);
                switch (chCode) {
                    case 32 /* CharCode.Space */:
                        currentVisibleColumn += 1;
                        break;
                    case 9 /* CharCode.Tab */:
                        currentVisibleColumn = CursorColumns.nextRenderTabStop(currentVisibleColumn, tabSize);
                        break;
                    default:
                        return -1;
                }
            }
            if (currentVisibleColumn === prevTabStopVisibleColumn + tabSize) {
                return prevTabStopPosition;
            }
            // It must have been a partial indentation.
            return -1;
        }
        // We are going right.
        const targetVisibleColumn = CursorColumns.nextRenderTabStop(visibleColumn, tabSize);
        // We can just continue from where whitespaceVisibleColumn got to.
        let currentVisibleColumn = visibleColumn;
        for (let i = position; i < lineLength; i++) {
            if (currentVisibleColumn === targetVisibleColumn) {
                return i;
            }
            const chCode = lineContent.charCodeAt(i);
            switch (chCode) {
                case 32 /* CharCode.Space */:
                    currentVisibleColumn += 1;
                    break;
                case 9 /* CharCode.Tab */:
                    currentVisibleColumn = CursorColumns.nextRenderTabStop(currentVisibleColumn, tabSize);
                    break;
                default:
                    return -1;
            }
        }
        // This condition handles when the target column is at the end of the line.
        if (currentVisibleColumn === targetVisibleColumn) {
            return lineLength;
        }
        return -1;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursor/cursorMoveOperations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class CursorPosition {
    constructor(lineNumber, column, leftoverVisibleColumns) {
        this._cursorPositionBrand = undefined;
        this.lineNumber = lineNumber;
        this.column = column;
        this.leftoverVisibleColumns = leftoverVisibleColumns;
    }
}
class MoveOperations {
    static leftPosition(model, position) {
        if (position.column > model.getLineMinColumn(position.lineNumber)) {
            return position.delta(undefined, -prevCharLength(model.getLineContent(position.lineNumber), position.column - 1));
        }
        else if (position.lineNumber > 1) {
            const newLineNumber = position.lineNumber - 1;
            return new Position(newLineNumber, model.getLineMaxColumn(newLineNumber));
        }
        else {
            return position;
        }
    }
    static leftPositionAtomicSoftTabs(model, position, tabSize) {
        if (position.column <= model.getLineIndentColumn(position.lineNumber)) {
            const minColumn = model.getLineMinColumn(position.lineNumber);
            const lineContent = model.getLineContent(position.lineNumber);
            const newPosition = AtomicTabMoveOperations.atomicPosition(lineContent, position.column - 1, tabSize, 0 /* Direction.Left */);
            if (newPosition !== -1 && newPosition + 1 >= minColumn) {
                return new Position(position.lineNumber, newPosition + 1);
            }
        }
        return this.leftPosition(model, position);
    }
    static left(config, model, position) {
        const pos = config.stickyTabStops
            ? MoveOperations.leftPositionAtomicSoftTabs(model, position, config.tabSize)
            : MoveOperations.leftPosition(model, position);
        return new CursorPosition(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) {
            // If the user has a selection and does not want to extend it,
            // put the cursor at the beginning of the selection.
            lineNumber = cursor.selection.startLineNumber;
            column = cursor.selection.startColumn;
        }
        else {
            // This has no effect if noOfColumns === 1.
            // It is ok to do so in the half-line scenario.
            const pos = cursor.position.delta(undefined, -(noOfColumns - 1));
            // We clip the position before normalization, as normalization is not defined
            // for possibly negative columns.
            const normalizedPos = model.normalizePosition(MoveOperations.clipPositionColumn(pos, model), 0 /* PositionAffinity.Left */);
            const p = MoveOperations.left(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 clipPositionColumn(position, model) {
        return new Position(position.lineNumber, MoveOperations.clipRange(position.column, model.getLineMinColumn(position.lineNumber), model.getLineMaxColumn(position.lineNumber)));
    }
    static clipRange(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 + nextCharLength(model.getLineContent(lineNumber), column - 1);
        }
        else if (lineNumber < model.getLineCount()) {
            lineNumber = lineNumber + 1;
            column = model.getLineMinColumn(lineNumber);
        }
        return new Position(lineNumber, column);
    }
    static rightPositionAtomicSoftTabs(model, lineNumber, column, tabSize, indentSize) {
        if (column < model.getLineIndentColumn(lineNumber)) {
            const lineContent = model.getLineContent(lineNumber);
            const newPosition = AtomicTabMoveOperations.atomicPosition(lineContent, column - 1, tabSize, 1 /* Direction.Right */);
            if (newPosition !== -1) {
                return new Position(lineNumber, newPosition + 1);
            }
        }
        return this.rightPosition(model, lineNumber, column);
    }
    static right(config, model, position) {
        const pos = config.stickyTabStops
            ? MoveOperations.rightPositionAtomicSoftTabs(model, position.lineNumber, position.column, config.tabSize, config.indentSize)
            : MoveOperations.rightPosition(model, position.lineNumber, position.column);
        return new CursorPosition(pos.lineNumber, pos.column, 0);
    }
    static moveRight(config, model, cursor, inSelectionMode, noOfColumns) {
        let lineNumber, column;
        if (cursor.hasSelection() && !inSelectionMode) {
            // If we are in selection mode, move right without selection cancels selection and puts cursor at the end of the selection
            lineNumber = cursor.selection.endLineNumber;
            column = cursor.selection.endColumn;
        }
        else {
            const pos = cursor.position.delta(undefined, noOfColumns - 1);
            const normalizedPos = model.normalizePosition(MoveOperations.clipPositionColumn(pos, model), 1 /* PositionAffinity.Right */);
            const r = MoveOperations.right(config, model, normalizedPos);
            lineNumber = r.lineNumber;
            column = r.column;
        }
        return cursor.move(inSelectionMode, lineNumber, column, 0);
    }
    static vertical(config, model, lineNumber, column, leftoverVisibleColumns, newLineNumber, allowMoveOnEdgeLine, normalizationAffinity) {
        const currentVisibleColumn = CursorColumns.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 - CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize);
        }
        if (normalizationAffinity !== undefined) {
            const position = new Position(lineNumber, column);
            const newPosition = model.normalizePosition(position, normalizationAffinity);
            leftoverVisibleColumns = leftoverVisibleColumns + (column - newPosition.column);
            lineNumber = newPosition.lineNumber;
            column = newPosition.column;
        }
        return new CursorPosition(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) {
            // If we are in selection mode, move down acts relative to the end of selection
            lineNumber = cursor.selection.endLineNumber;
            column = cursor.selection.endColumn;
        }
        else {
            lineNumber = cursor.position.lineNumber;
            column = cursor.position.column;
        }
        const r = MoveOperations.down(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);
        return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns);
    }
    static translateDown(config, model, cursor) {
        const selection = cursor.selection;
        const selectionStart = MoveOperations.down(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
        const position = MoveOperations.down(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);
        return new SingleCursorState(new Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new Position(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) {
            // If we are in selection mode, move up acts relative to the beginning of selection
            lineNumber = cursor.selection.startLineNumber;
            column = cursor.selection.startColumn;
        }
        else {
            lineNumber = cursor.position.lineNumber;
            column = cursor.position.column;
        }
        const r = MoveOperations.up(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);
        return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns);
    }
    static translateUp(config, model, cursor) {
        const selection = cursor.selection;
        const selectionStart = MoveOperations.up(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
        const position = MoveOperations.up(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);
        return new SingleCursorState(new Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new Position(position.lineNumber, position.column), position.leftoverVisibleColumns);
    }
    static _isBlankLine(model, lineNumber) {
        if (model.getLineFirstNonWhitespaceColumn(lineNumber) === 0) {
            // empty or contains only whitespace
            return true;
        }
        return false;
    }
    static moveToPrevBlankLine(config, model, cursor, inSelectionMode) {
        let lineNumber = cursor.position.lineNumber;
        // If our current line is blank, move to the previous non-blank line
        while (lineNumber > 1 && this._isBlankLine(model, lineNumber)) {
            lineNumber--;
        }
        // Find the previous blank line
        while (lineNumber > 1 && !this._isBlankLine(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;
        // If our current line is blank, move to the next non-blank line
        while (lineNumber < lineCount && this._isBlankLine(model, lineNumber)) {
            lineNumber++;
        }
        // Find the next blank line
        while (lineNumber < lineCount && !this._isBlankLine(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 /* Constants.MAX_SAFE_SMALL_INTEGER */ - 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);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursor/cursorDeleteOperations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







class DeleteOperations {
    static deleteRight(prevEditOperationType, config, model, selections) {
        const commands = [];
        let shouldPushStackElementBefore = (prevEditOperationType !== 3 /* EditOperationType.DeletingRight */);
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            let deleteSelection = selection;
            if (deleteSelection.isEmpty()) {
                const position = selection.getPosition();
                const rightOfPosition = MoveOperations.right(config, model, position);
                deleteSelection = new Range(rightOfPosition.lineNumber, rightOfPosition.column, position.lineNumber, position.column);
            }
            if (deleteSelection.isEmpty()) {
                // Probably at end of file => ignore
                commands[i] = null;
                continue;
            }
            if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) {
                shouldPushStackElementBefore = true;
            }
            commands[i] = new ReplaceCommand(deleteSelection, '');
        }
        return [shouldPushStackElementBefore, commands];
    }
    static isAutoClosingPairDelete(autoClosingDelete, autoClosingBrackets, autoClosingQuotes, autoClosingPairsOpen, model, selections, autoClosedCharacters) {
        if (autoClosingBrackets === 'never' && autoClosingQuotes === 'never') {
            return false;
        }
        if (autoClosingDelete === 'never') {
            return false;
        }
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            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 (isQuote(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;
            }
            // Must delete the pair only if it was automatically inserted by the editor
            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 _runAutoClosingPairDelete(config, model, selections) {
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            const position = selections[i].getPosition();
            const deleteSelection = new Range(position.lineNumber, position.column - 1, position.lineNumber, position.column + 1);
            commands[i] = new ReplaceCommand(deleteSelection, '');
        }
        return [true, commands];
    }
    static deleteLeft(prevEditOperationType, config, model, selections, autoClosedCharacters) {
        if (this.isAutoClosingPairDelete(config.autoClosingDelete, config.autoClosingBrackets, config.autoClosingQuotes, config.autoClosingPairs.autoClosingPairsOpenByEnd, model, selections, autoClosedCharacters)) {
            return this._runAutoClosingPairDelete(config, model, selections);
        }
        const commands = [];
        let shouldPushStackElementBefore = (prevEditOperationType !== 2 /* EditOperationType.DeletingLeft */);
        for (let i = 0, len = selections.length; i < len; i++) {
            const deleteRange = DeleteOperations.getDeleteRange(selections[i], model, config);
            // Ignore empty delete ranges, as they have no effect
            // They happen if the cursor is at the beginning of the file.
            if (deleteRange.isEmpty()) {
                commands[i] = null;
                continue;
            }
            if (deleteRange.startLineNumber !== deleteRange.endLineNumber) {
                shouldPushStackElementBefore = true;
            }
            commands[i] = new ReplaceCommand(deleteRange, '');
        }
        return [shouldPushStackElementBefore, commands];
    }
    static getDeleteRange(selection, model, config) {
        if (!selection.isEmpty()) {
            return selection;
        }
        const position = selection.getPosition();
        // Unintend when using tab stops and cursor is within indentation
        if (config.useTabStops && position.column > 1) {
            const lineContent = model.getLineContent(position.lineNumber);
            const firstNonWhitespaceIndex = strings_firstNonWhitespaceIndex(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 = CursorColumns.prevIndentTabStop(fromVisibleColumn, config.indentSize);
                const toColumn = config.columnFromVisibleColumn(model, position.lineNumber, toVisibleColumn);
                return new Range(position.lineNumber, toColumn, position.lineNumber, position.column);
            }
        }
        return Range.fromPositions(DeleteOperations.getPositionAfterDeleteLeft(position, model), position);
    }
    static getPositionAfterDeleteLeft(position, model) {
        if (position.column > 1) {
            // Convert 1-based columns to 0-based offsets and back.
            const idx = getLeftDeleteOffset(position.column - 1, model.getLineContent(position.lineNumber));
            return position.with(undefined, idx + 1);
        }
        else if (position.lineNumber > 1) {
            const newLine = position.lineNumber - 1;
            return new Position(newLine, model.getLineMaxColumn(newLine));
        }
        else {
            return position;
        }
    }
    static cut(config, model, selections) {
        const commands = [];
        let lastCutRange = null;
        selections.sort((a, b) => Position.compare(a.getStartPosition(), b.getEndPosition()));
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            if (selection.isEmpty()) {
                if (config.emptySelectionClipboard) {
                    // This is a full line cut
                    const position = selection.getPosition();
                    let startLineNumber, startColumn, endLineNumber, endColumn;
                    if (position.lineNumber < model.getLineCount()) {
                        // Cutting a line in the middle of the model
                        startLineNumber = position.lineNumber;
                        startColumn = 1;
                        endLineNumber = position.lineNumber + 1;
                        endColumn = 1;
                    }
                    else if (position.lineNumber > 1 && (lastCutRange === null || lastCutRange === void 0 ? void 0 : lastCutRange.endLineNumber) !== position.lineNumber) {
                        // Cutting the last line & there are more than 1 lines in the model & a previous cut operation does not touch the current cut operation
                        startLineNumber = position.lineNumber - 1;
                        startColumn = model.getLineMaxColumn(position.lineNumber - 1);
                        endLineNumber = position.lineNumber;
                        endColumn = model.getLineMaxColumn(position.lineNumber);
                    }
                    else {
                        // Cutting the single line that the model contains
                        startLineNumber = position.lineNumber;
                        startColumn = 1;
                        endLineNumber = position.lineNumber;
                        endColumn = model.getLineMaxColumn(position.lineNumber);
                    }
                    const deleteSelection = new Range(startLineNumber, startColumn, endLineNumber, endColumn);
                    lastCutRange = deleteSelection;
                    if (!deleteSelection.isEmpty()) {
                        commands[i] = new ReplaceCommand(deleteSelection, '');
                    }
                    else {
                        commands[i] = null;
                    }
                }
                else {
                    // Cannot cut empty selection
                    commands[i] = null;
                }
            }
            else {
                commands[i] = new ReplaceCommand(selection, '');
            }
        }
        return new EditOperationResult(0 /* EditOperationType.Other */, commands, {
            shouldPushStackElementBefore: true,
            shouldPushStackElementAfter: true
        });
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursor/cursorWordOperations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class WordOperations {
    static _createWord(lineContent, wordType, nextCharClass, start, end) {
        // console.log('WORD ==> ' + start + ' => ' + end + ':::: <<<' + lineContent.substring(start, end) + '>>>');
        return { start: start, end: end, wordType: wordType, nextCharClass: nextCharClass };
    }
    static _findPreviousWordOnLine(wordSeparators, model, position) {
        const lineContent = model.getLineContent(position.lineNumber);
        return this._doFindPreviousWordOnLine(lineContent, wordSeparators, position);
    }
    static _doFindPreviousWordOnLine(lineContent, wordSeparators, position) {
        let wordType = 0 /* WordType.None */;
        for (let chIndex = position.column - 2; chIndex >= 0; chIndex--) {
            const chCode = lineContent.charCodeAt(chIndex);
            const chClass = wordSeparators.get(chCode);
            if (chClass === 0 /* WordCharacterClass.Regular */) {
                if (wordType === 2 /* WordType.Separator */) {
                    return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
                }
                wordType = 1 /* WordType.Regular */;
            }
            else if (chClass === 2 /* WordCharacterClass.WordSeparator */) {
                if (wordType === 1 /* WordType.Regular */) {
                    return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
                }
                wordType = 2 /* WordType.Separator */;
            }
            else if (chClass === 1 /* WordCharacterClass.Whitespace */) {
                if (wordType !== 0 /* WordType.None */) {
                    return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators, wordType, chIndex + 1));
                }
            }
        }
        if (wordType !== 0 /* WordType.None */) {
            return this._createWord(lineContent, wordType, 1 /* WordCharacterClass.Whitespace */, 0, this._findEndOfWord(lineContent, wordSeparators, wordType, 0));
        }
        return null;
    }
    static _findEndOfWord(lineContent, wordSeparators, wordType, startIndex) {
        const len = lineContent.length;
        for (let chIndex = startIndex; chIndex < len; chIndex++) {
            const chCode = lineContent.charCodeAt(chIndex);
            const chClass = wordSeparators.get(chCode);
            if (chClass === 1 /* WordCharacterClass.Whitespace */) {
                return chIndex;
            }
            if (wordType === 1 /* WordType.Regular */ && chClass === 2 /* WordCharacterClass.WordSeparator */) {
                return chIndex;
            }
            if (wordType === 2 /* WordType.Separator */ && chClass === 0 /* WordCharacterClass.Regular */) {
                return chIndex;
            }
        }
        return len;
    }
    static _findNextWordOnLine(wordSeparators, model, position) {
        const lineContent = model.getLineContent(position.lineNumber);
        return this._doFindNextWordOnLine(lineContent, wordSeparators, position);
    }
    static _doFindNextWordOnLine(lineContent, wordSeparators, position) {
        let wordType = 0 /* WordType.None */;
        const len = lineContent.length;
        for (let chIndex = position.column - 1; chIndex < len; chIndex++) {
            const chCode = lineContent.charCodeAt(chIndex);
            const chClass = wordSeparators.get(chCode);
            if (chClass === 0 /* WordCharacterClass.Regular */) {
                if (wordType === 2 /* WordType.Separator */) {
                    return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
                }
                wordType = 1 /* WordType.Regular */;
            }
            else if (chClass === 2 /* WordCharacterClass.WordSeparator */) {
                if (wordType === 1 /* WordType.Regular */) {
                    return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
                }
                wordType = 2 /* WordType.Separator */;
            }
            else if (chClass === 1 /* WordCharacterClass.Whitespace */) {
                if (wordType !== 0 /* WordType.None */) {
                    return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators, wordType, chIndex - 1), chIndex);
                }
            }
        }
        if (wordType !== 0 /* WordType.None */) {
            return this._createWord(lineContent, wordType, 1 /* WordCharacterClass.Whitespace */, this._findStartOfWord(lineContent, wordSeparators, wordType, len - 1), len);
        }
        return null;
    }
    static _findStartOfWord(lineContent, wordSeparators, wordType, startIndex) {
        for (let chIndex = startIndex; chIndex >= 0; chIndex--) {
            const chCode = lineContent.charCodeAt(chIndex);
            const chClass = wordSeparators.get(chCode);
            if (chClass === 1 /* WordCharacterClass.Whitespace */) {
                return chIndex + 1;
            }
            if (wordType === 1 /* WordType.Regular */ && chClass === 2 /* WordCharacterClass.WordSeparator */) {
                return chIndex + 1;
            }
            if (wordType === 2 /* WordType.Separator */ && chClass === 0 /* WordCharacterClass.Regular */) {
                return chIndex + 1;
            }
        }
        return 0;
    }
    static moveWordLeft(wordSeparators, model, position, wordNavigationType) {
        let lineNumber = position.lineNumber;
        let column = position.column;
        if (column === 1) {
            if (lineNumber > 1) {
                lineNumber = lineNumber - 1;
                column = model.getLineMaxColumn(lineNumber);
            }
        }
        let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new Position(lineNumber, column));
        if (wordNavigationType === 0 /* WordNavigationType.WordStart */) {
            return new Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
        }
        if (wordNavigationType === 1 /* WordNavigationType.WordStartFast */) {
            if (prevWordOnLine
                && prevWordOnLine.wordType === 2 /* WordType.Separator */
                && prevWordOnLine.end - prevWordOnLine.start === 1
                && prevWordOnLine.nextCharClass === 0 /* WordCharacterClass.Regular */) {
                // Skip over a word made up of one single separator and followed by a regular character
                prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new Position(lineNumber, prevWordOnLine.start + 1));
            }
            return new Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
        }
        if (wordNavigationType === 3 /* WordNavigationType.WordAccessibility */) {
            while (prevWordOnLine
                && prevWordOnLine.wordType === 2 /* WordType.Separator */) {
                // Skip over words made up of only separators
                prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new Position(lineNumber, prevWordOnLine.start + 1));
            }
            return new Position(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
        }
        // We are stopping at the ending of words
        if (prevWordOnLine && column <= prevWordOnLine.end + 1) {
            prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, new Position(lineNumber, prevWordOnLine.start + 1));
        }
        return new Position(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 Position(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 /* CharCode.Underline */ && right !== 95 /* CharCode.Underline */) {
                // snake_case_variables
                return new Position(lineNumber, column);
            }
            if ((isLowerAsciiLetter(left) || isAsciiDigit(left)) && isUpperAsciiLetter(right)) {
                // camelCaseVariables
                return new Position(lineNumber, column);
            }
            if (isUpperAsciiLetter(left) && isUpperAsciiLetter(right)) {
                // thisIsACamelCaseWithOneLetterWords
                if (column + 1 < maxColumn) {
                    const rightRight = lineContent.charCodeAt(column);
                    if (isLowerAsciiLetter(rightRight) || isAsciiDigit(rightRight)) {
                        return new Position(lineNumber, column);
                    }
                }
            }
        }
        return new Position(lineNumber, 1);
    }
    static moveWordRight(wordSeparators, 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 = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, column));
        if (wordNavigationType === 2 /* WordNavigationType.WordEnd */) {
            if (nextWordOnLine && nextWordOnLine.wordType === 2 /* WordType.Separator */) {
                if (nextWordOnLine.end - nextWordOnLine.start === 1 && nextWordOnLine.nextCharClass === 0 /* WordCharacterClass.Regular */) {
                    // Skip over a word made up of one single separator and followed by a regular character
                    nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, nextWordOnLine.end + 1));
                }
            }
            if (nextWordOnLine) {
                column = nextWordOnLine.end + 1;
            }
            else {
                column = model.getLineMaxColumn(lineNumber);
            }
        }
        else if (wordNavigationType === 3 /* WordNavigationType.WordAccessibility */) {
            if (movedDown) {
                // If we move to the next line, pretend that the cursor is right before the first character.
                // This is needed when the first word starts right at the first character - and in order not to miss it,
                // we need to start before.
                column = 0;
            }
            while (nextWordOnLine
                && (nextWordOnLine.wordType === 2 /* WordType.Separator */
                    || nextWordOnLine.start + 1 <= column)) {
                // Skip over a word made up of one single separator
                // Also skip over word if it begins before current cursor position to ascertain we're moving forward at least 1 character.
                nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, nextWordOnLine.end + 1));
            }
            if (nextWordOnLine) {
                column = nextWordOnLine.start + 1;
            }
            else {
                column = model.getLineMaxColumn(lineNumber);
            }
        }
        else {
            if (nextWordOnLine && !movedDown && column >= nextWordOnLine.start + 1) {
                nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, nextWordOnLine.end + 1));
            }
            if (nextWordOnLine) {
                column = nextWordOnLine.start + 1;
            }
            else {
                column = model.getLineMaxColumn(lineNumber);
            }
        }
        return new Position(lineNumber, column);
    }
    static _moveWordPartRight(model, position) {
        const lineNumber = position.lineNumber;
        const maxColumn = model.getLineMaxColumn(lineNumber);
        if (position.column === maxColumn) {
            return (lineNumber < model.getLineCount() ? new Position(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 /* CharCode.Underline */ && right === 95 /* CharCode.Underline */) {
                // snake_case_variables
                return new Position(lineNumber, column);
            }
            if ((isLowerAsciiLetter(left) || isAsciiDigit(left)) && isUpperAsciiLetter(right)) {
                // camelCaseVariables
                return new Position(lineNumber, column);
            }
            if (isUpperAsciiLetter(left) && isUpperAsciiLetter(right)) {
                // thisIsACamelCaseWithOneLetterWords
                if (column + 1 < maxColumn) {
                    const rightRight = lineContent.charCodeAt(column);
                    if (isLowerAsciiLetter(rightRight) || isAsciiDigit(rightRight)) {
                        return new Position(lineNumber, column);
                    }
                }
            }
        }
        return new Position(lineNumber, maxColumn);
    }
    static _deleteWordLeftWhitespace(model, position) {
        const lineContent = model.getLineContent(position.lineNumber);
        const startIndex = position.column - 2;
        const lastNonWhitespace = strings_lastNonWhitespaceIndex(lineContent, startIndex);
        if (lastNonWhitespace + 1 < startIndex) {
            return new Range(position.lineNumber, lastNonWhitespace + 2, position.lineNumber, position.column);
        }
        return null;
    }
    static deleteWordLeft(ctx, wordNavigationType) {
        const wordSeparators = ctx.wordSeparators;
        const model = ctx.model;
        const selection = ctx.selection;
        const whitespaceHeuristics = ctx.whitespaceHeuristics;
        if (!selection.isEmpty()) {
            return selection;
        }
        if (DeleteOperations.isAutoClosingPairDelete(ctx.autoClosingDelete, ctx.autoClosingBrackets, ctx.autoClosingQuotes, ctx.autoClosingPairs.autoClosingPairsOpenByEnd, ctx.model, [ctx.selection], ctx.autoClosedCharacters)) {
            const position = ctx.selection.getPosition();
            return new Range(position.lineNumber, position.column - 1, position.lineNumber, position.column + 1);
        }
        const position = new Position(selection.positionLineNumber, selection.positionColumn);
        let lineNumber = position.lineNumber;
        let column = position.column;
        if (lineNumber === 1 && column === 1) {
            // Ignore deleting at beginning of file
            return null;
        }
        if (whitespaceHeuristics) {
            const r = this._deleteWordLeftWhitespace(model, position);
            if (r) {
                return r;
            }
        }
        let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
        if (wordNavigationType === 0 /* WordNavigationType.WordStart */) {
            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 = WordOperations._findPreviousWordOnLine(wordSeparators, model, new Position(lineNumber, prevWordOnLine.start + 1));
            }
            if (prevWordOnLine) {
                column = prevWordOnLine.end + 1;
            }
            else {
                if (column > 1) {
                    column = 1;
                }
                else {
                    lineNumber--;
                    column = model.getLineMaxColumn(lineNumber);
                }
            }
        }
        return new Range(lineNumber, column, position.lineNumber, position.column);
    }
    static deleteInsideWord(wordSeparators, model, selection) {
        if (!selection.isEmpty()) {
            return selection;
        }
        const position = new Position(selection.positionLineNumber, selection.positionColumn);
        const r = this._deleteInsideWordWhitespace(model, position);
        if (r) {
            return r;
        }
        return this._deleteInsideWordDetermineDeleteRange(wordSeparators, model, position);
    }
    static _charAtIsWhitespace(str, index) {
        const charCode = str.charCodeAt(index);
        return (charCode === 32 /* CharCode.Space */ || charCode === 9 /* CharCode.Tab */);
    }
    static _deleteInsideWordWhitespace(model, position) {
        const lineContent = model.getLineContent(position.lineNumber);
        const lineContentLength = lineContent.length;
        if (lineContentLength === 0) {
            // empty line
            return null;
        }
        let leftIndex = Math.max(position.column - 2, 0);
        if (!this._charAtIsWhitespace(lineContent, leftIndex)) {
            // touches a non-whitespace character to the left
            return null;
        }
        let rightIndex = Math.min(position.column - 1, lineContentLength - 1);
        if (!this._charAtIsWhitespace(lineContent, rightIndex)) {
            // touches a non-whitespace character to the right
            return null;
        }
        // walk over whitespace to the left
        while (leftIndex > 0 && this._charAtIsWhitespace(lineContent, leftIndex - 1)) {
            leftIndex--;
        }
        // walk over whitespace to the right
        while (rightIndex + 1 < lineContentLength && this._charAtIsWhitespace(lineContent, rightIndex + 1)) {
            rightIndex++;
        }
        return new Range(position.lineNumber, leftIndex + 1, position.lineNumber, rightIndex + 2);
    }
    static _deleteInsideWordDetermineDeleteRange(wordSeparators, model, position) {
        const lineContent = model.getLineContent(position.lineNumber);
        const lineLength = lineContent.length;
        if (lineLength === 0) {
            // empty line
            if (position.lineNumber > 1) {
                return new Range(position.lineNumber - 1, model.getLineMaxColumn(position.lineNumber - 1), position.lineNumber, 1);
            }
            else {
                if (position.lineNumber < model.getLineCount()) {
                    return new Range(position.lineNumber, 1, position.lineNumber + 1, 1);
                }
                else {
                    // empty model
                    return new Range(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 Range(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._charAtIsWhitespace(lineContent, endColumn - 1)) {
                expandedToTheRight = true;
                endColumn++;
            }
            if (!expandedToTheRight) {
                while (startColumn > 1 && this._charAtIsWhitespace(lineContent, startColumn - 2)) {
                    startColumn--;
                }
            }
            return createRangeWithPosition(startColumn, endColumn);
        };
        const prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
        if (prevWordOnLine && touchesWord(prevWordOnLine)) {
            return deleteWordAndAdjacentWhitespace(prevWordOnLine);
        }
        const nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, 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 = WordOperations._moveWordPartLeft(model, pos);
        return new Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
    }
    static _findFirstNonWhitespaceChar(str, startIndex) {
        const len = str.length;
        for (let chIndex = startIndex; chIndex < len; chIndex++) {
            const ch = str.charAt(chIndex);
            if (ch !== ' ' && ch !== '\t') {
                return chIndex;
            }
        }
        return len;
    }
    static _deleteWordRightWhitespace(model, position) {
        const lineContent = model.getLineContent(position.lineNumber);
        const startIndex = position.column - 1;
        const firstNonWhitespace = this._findFirstNonWhitespaceChar(lineContent, startIndex);
        if (startIndex + 1 < firstNonWhitespace) {
            // bingo
            return new Range(position.lineNumber, position.column, position.lineNumber, firstNonWhitespace + 1);
        }
        return null;
    }
    static deleteWordRight(ctx, wordNavigationType) {
        const wordSeparators = ctx.wordSeparators;
        const model = ctx.model;
        const selection = ctx.selection;
        const whitespaceHeuristics = ctx.whitespaceHeuristics;
        if (!selection.isEmpty()) {
            return selection;
        }
        const position = new Position(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) {
            // Ignore deleting at end of file
            return null;
        }
        if (whitespaceHeuristics) {
            const r = this._deleteWordRightWhitespace(model, position);
            if (r) {
                return r;
            }
        }
        let nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, position);
        if (wordNavigationType === 2 /* WordNavigationType.WordEnd */) {
            if (nextWordOnLine) {
                column = nextWordOnLine.end + 1;
            }
            else {
                if (column < maxColumn || lineNumber === lineCount) {
                    column = maxColumn;
                }
                else {
                    lineNumber++;
                    nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, 1));
                    if (nextWordOnLine) {
                        column = nextWordOnLine.start + 1;
                    }
                    else {
                        column = model.getLineMaxColumn(lineNumber);
                    }
                }
            }
        }
        else {
            if (nextWordOnLine && column >= nextWordOnLine.start + 1) {
                nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, nextWordOnLine.end + 1));
            }
            if (nextWordOnLine) {
                column = nextWordOnLine.start + 1;
            }
            else {
                if (column < maxColumn || lineNumber === lineCount) {
                    column = maxColumn;
                }
                else {
                    lineNumber++;
                    nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators, model, new Position(lineNumber, 1));
                    if (nextWordOnLine) {
                        column = nextWordOnLine.start + 1;
                    }
                    else {
                        column = model.getLineMaxColumn(lineNumber);
                    }
                }
            }
        }
        return new Range(lineNumber, column, position.lineNumber, position.column);
    }
    static _deleteWordPartRight(model, selection) {
        if (!selection.isEmpty()) {
            return selection;
        }
        const pos = selection.getPosition();
        const toPosition = WordOperations._moveWordPartRight(model, pos);
        return new Range(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
    }
    static _createWordAtPosition(model, lineNumber, word) {
        const range = new Range(lineNumber, word.start + 1, lineNumber, word.end + 1);
        return {
            word: model.getValueInRange(range),
            startColumn: range.startColumn,
            endColumn: range.endColumn
        };
    }
    static getWordAtPosition(model, _wordSeparators, position) {
        const wordSeparators = getMapForWordSeparators(_wordSeparators);
        const prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
        if (prevWord && prevWord.wordType === 1 /* WordType.Regular */ && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) {
            return WordOperations._createWordAtPosition(model, position.lineNumber, prevWord);
        }
        const nextWord = WordOperations._findNextWordOnLine(wordSeparators, model, position);
        if (nextWord && nextWord.wordType === 1 /* WordType.Regular */ && nextWord.start <= position.column - 1 && position.column - 1 <= nextWord.end) {
            return WordOperations._createWordAtPosition(model, position.lineNumber, nextWord);
        }
        return null;
    }
    static word(config, model, cursor, inSelectionMode, position) {
        const wordSeparators = getMapForWordSeparators(config.wordSeparators);
        const prevWord = WordOperations._findPreviousWordOnLine(wordSeparators, model, position);
        const nextWord = WordOperations._findNextWordOnLine(wordSeparators, model, position);
        if (!inSelectionMode) {
            // Entering word selection for the first time
            let startColumn;
            let endColumn;
            if (prevWord && prevWord.wordType === 1 /* WordType.Regular */ && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) {
                // isTouchingPrevWord
                startColumn = prevWord.start + 1;
                endColumn = prevWord.end + 1;
            }
            else if (nextWord && nextWord.wordType === 1 /* WordType.Regular */ && nextWord.start <= position.column - 1 && position.column - 1 <= nextWord.end) {
                // isTouchingNextWord
                startColumn = nextWord.start + 1;
                endColumn = nextWord.end + 1;
            }
            else {
                if (prevWord) {
                    startColumn = prevWord.end + 1;
                }
                else {
                    startColumn = 1;
                }
                if (nextWord) {
                    endColumn = nextWord.start + 1;
                }
                else {
                    endColumn = model.getLineMaxColumn(position.lineNumber);
                }
            }
            return new SingleCursorState(new Range(position.lineNumber, startColumn, position.lineNumber, endColumn), 0, new Position(position.lineNumber, endColumn), 0);
        }
        let startColumn;
        let endColumn;
        if (prevWord && prevWord.wordType === 1 /* WordType.Regular */ && prevWord.start < position.column - 1 && position.column - 1 < prevWord.end) {
            // isInsidePrevWord
            startColumn = prevWord.start + 1;
            endColumn = prevWord.end + 1;
        }
        else if (nextWord && nextWord.wordType === 1 /* WordType.Regular */ && nextWord.start < position.column - 1 && position.column - 1 < nextWord.end) {
            // isInsideNextWord
            startColumn = nextWord.start + 1;
            endColumn = nextWord.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 Position(lineNumber, column);
            if (cursor.selectionStart.containsPosition(possiblePosition)) {
                column = cursor.selectionStart.endColumn;
            }
        }
        else {
            column = endColumn;
            const possiblePosition = new Position(lineNumber, column);
            if (cursor.selectionStart.containsPosition(possiblePosition)) {
                column = cursor.selectionStart.startColumn;
            }
        }
        return cursor.move(true, lineNumber, column, 0);
    }
}
class WordPartOperations extends WordOperations {
    static deleteWordPartLeft(ctx) {
        const candidates = enforceDefined([
            WordOperations.deleteWordLeft(ctx, 0 /* WordNavigationType.WordStart */),
            WordOperations.deleteWordLeft(ctx, 2 /* WordNavigationType.WordEnd */),
            WordOperations._deleteWordPartLeft(ctx.model, ctx.selection)
        ]);
        candidates.sort(Range.compareRangesUsingEnds);
        return candidates[2];
    }
    static deleteWordPartRight(ctx) {
        const candidates = enforceDefined([
            WordOperations.deleteWordRight(ctx, 0 /* WordNavigationType.WordStart */),
            WordOperations.deleteWordRight(ctx, 2 /* WordNavigationType.WordEnd */),
            WordOperations._deleteWordPartRight(ctx.model, ctx.selection)
        ]);
        candidates.sort(Range.compareRangesUsingStarts);
        return candidates[0];
    }
    static moveWordPartLeft(wordSeparators, model, position) {
        const candidates = enforceDefined([
            WordOperations.moveWordLeft(wordSeparators, model, position, 0 /* WordNavigationType.WordStart */),
            WordOperations.moveWordLeft(wordSeparators, model, position, 2 /* WordNavigationType.WordEnd */),
            WordOperations._moveWordPartLeft(model, position)
        ]);
        candidates.sort(Position.compare);
        return candidates[2];
    }
    static moveWordPartRight(wordSeparators, model, position) {
        const candidates = enforceDefined([
            WordOperations.moveWordRight(wordSeparators, model, position, 0 /* WordNavigationType.WordStart */),
            WordOperations.moveWordRight(wordSeparators, model, position, 2 /* WordNavigationType.WordEnd */),
            WordOperations._moveWordPartRight(model, position)
        ]);
        candidates.sort(Position.compare);
        return candidates[0];
    }
}
function enforceDefined(arr) {
    return arr.filter(el => Boolean(el));
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursor/cursorMoveCommands.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class CursorMoveCommands {
    static addCursorDown(viewModel, cursors, useLogicalLine) {
        const result = [];
        let resultLen = 0;
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            result[resultLen++] = new CursorState(cursor.modelState, cursor.viewState);
            if (useLogicalLine) {
                result[resultLen++] = CursorState.fromModelState(MoveOperations.translateDown(viewModel.cursorConfig, viewModel.model, cursor.modelState));
            }
            else {
                result[resultLen++] = CursorState.fromViewState(MoveOperations.translateDown(viewModel.cursorConfig, viewModel, cursor.viewState));
            }
        }
        return result;
    }
    static addCursorUp(viewModel, cursors, useLogicalLine) {
        const result = [];
        let resultLen = 0;
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            result[resultLen++] = new CursorState(cursor.modelState, cursor.viewState);
            if (useLogicalLine) {
                result[resultLen++] = CursorState.fromModelState(MoveOperations.translateUp(viewModel.cursorConfig, viewModel.model, cursor.modelState));
            }
            else {
                result[resultLen++] = CursorState.fromViewState(MoveOperations.translateUp(viewModel.cursorConfig, viewModel, cursor.viewState));
            }
        }
        return result;
    }
    static moveToBeginningOfLine(viewModel, cursors, inSelectionMode) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            result[i] = this._moveToLineStart(viewModel, cursor, inSelectionMode);
        }
        return result;
    }
    static _moveToLineStart(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._moveToLineStartByView(viewModel, cursor, inSelectionMode);
        }
        else {
            return this._moveToLineStartByModel(viewModel, cursor, inSelectionMode);
        }
    }
    static _moveToLineStartByView(viewModel, cursor, inSelectionMode) {
        return CursorState.fromViewState(MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode));
    }
    static _moveToLineStartByModel(viewModel, cursor, inSelectionMode) {
        return CursorState.fromModelState(MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
    }
    static moveToEndOfLine(viewModel, cursors, inSelectionMode, sticky) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            result[i] = this._moveToLineEnd(viewModel, cursor, inSelectionMode, sticky);
        }
        return result;
    }
    static _moveToLineEnd(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._moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky);
        }
        else {
            return this._moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky);
        }
    }
    static _moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky) {
        return CursorState.fromViewState(MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, sticky));
    }
    static _moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky) {
        return CursorState.fromModelState(MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, sticky));
    }
    static expandLineSelection(viewModel, cursors) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            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[i] = CursorState.fromModelState(new SingleCursorState(new Range(startLineNumber, 1, startLineNumber, 1), 0, new Position(endLineNumber, endColumn), 0));
        }
        return result;
    }
    static moveToBeginningOfBuffer(viewModel, cursors, inSelectionMode) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            result[i] = CursorState.fromModelState(MoveOperations.moveToBeginningOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
        }
        return result;
    }
    static moveToEndOfBuffer(viewModel, cursors, inSelectionMode) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            result[i] = CursorState.fromModelState(MoveOperations.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 CursorState.fromModelState(new SingleCursorState(new Range(1, 1, 1, 1), 0, new Position(lineCount, maxColumn), 0));
    }
    static line(viewModel, cursor, inSelectionMode, _position, _viewPosition) {
        const position = viewModel.model.validatePosition(_position);
        const viewPosition = (_viewPosition
            ? viewModel.coordinatesConverter.validateViewPosition(new Position(_viewPosition.lineNumber, _viewPosition.column), position)
            : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position));
        if (!inSelectionMode || !cursor.modelState.hasSelection()) {
            // Entering line selection for the first time
            const lineCount = viewModel.model.getLineCount();
            let selectToLineNumber = position.lineNumber + 1;
            let selectToColumn = 1;
            if (selectToLineNumber > lineCount) {
                selectToLineNumber = lineCount;
                selectToColumn = viewModel.model.getLineMaxColumn(selectToLineNumber);
            }
            return CursorState.fromModelState(new SingleCursorState(new Range(position.lineNumber, 1, selectToLineNumber, selectToColumn), 0, new Position(selectToLineNumber, selectToColumn), 0));
        }
        // Continuing line selection
        const enteringLineNumber = cursor.modelState.selectionStart.getStartPosition().lineNumber;
        if (position.lineNumber < enteringLineNumber) {
            return CursorState.fromViewState(cursor.viewState.move(cursor.modelState.hasSelection(), 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 CursorState.fromViewState(cursor.viewState.move(cursor.modelState.hasSelection(), selectToViewLineNumber, selectToViewColumn, 0));
        }
        else {
            const endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition();
            return CursorState.fromModelState(cursor.modelState.move(cursor.modelState.hasSelection(), endPositionOfSelectionStart.lineNumber, endPositionOfSelectionStart.column, 0));
        }
    }
    static word(viewModel, cursor, inSelectionMode, _position) {
        const position = viewModel.model.validatePosition(_position);
        return CursorState.fromModelState(WordOperations.word(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, position));
    }
    static cancelSelection(viewModel, cursor) {
        if (!cursor.modelState.hasSelection()) {
            return new CursorState(cursor.modelState, cursor.viewState);
        }
        const lineNumber = cursor.viewState.position.lineNumber;
        const column = cursor.viewState.position.column;
        return CursorState.fromViewState(new SingleCursorState(new Range(lineNumber, column, lineNumber, column), 0, new Position(lineNumber, column), 0));
    }
    static moveTo(viewModel, cursor, inSelectionMode, _position, _viewPosition) {
        const position = viewModel.model.validatePosition(_position);
        const viewPosition = (_viewPosition
            ? viewModel.coordinatesConverter.validateViewPosition(new Position(_viewPosition.lineNumber, _viewPosition.column), position)
            : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position));
        return CursorState.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0));
    }
    static simpleMove(viewModel, cursors, direction, inSelectionMode, value, unit) {
        switch (direction) {
            case 0 /* CursorMove.Direction.Left */: {
                if (unit === 4 /* CursorMove.Unit.HalfLine */) {
                    // Move left by half the current line length
                    return this._moveHalfLineLeft(viewModel, cursors, inSelectionMode);
                }
                else {
                    // Move left by `moveParams.value` columns
                    return this._moveLeft(viewModel, cursors, inSelectionMode, value);
                }
            }
            case 1 /* CursorMove.Direction.Right */: {
                if (unit === 4 /* CursorMove.Unit.HalfLine */) {
                    // Move right by half the current line length
                    return this._moveHalfLineRight(viewModel, cursors, inSelectionMode);
                }
                else {
                    // Move right by `moveParams.value` columns
                    return this._moveRight(viewModel, cursors, inSelectionMode, value);
                }
            }
            case 2 /* CursorMove.Direction.Up */: {
                if (unit === 2 /* CursorMove.Unit.WrappedLine */) {
                    // Move up by view lines
                    return this._moveUpByViewLines(viewModel, cursors, inSelectionMode, value);
                }
                else {
                    // Move up by model lines
                    return this._moveUpByModelLines(viewModel, cursors, inSelectionMode, value);
                }
            }
            case 3 /* CursorMove.Direction.Down */: {
                if (unit === 2 /* CursorMove.Unit.WrappedLine */) {
                    // Move down by view lines
                    return this._moveDownByViewLines(viewModel, cursors, inSelectionMode, value);
                }
                else {
                    // Move down by model lines
                    return this._moveDownByModelLines(viewModel, cursors, inSelectionMode, value);
                }
            }
            case 4 /* CursorMove.Direction.PrevBlankLine */: {
                if (unit === 2 /* CursorMove.Unit.WrappedLine */) {
                    return cursors.map(cursor => CursorState.fromViewState(MoveOperations.moveToPrevBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode)));
                }
                else {
                    return cursors.map(cursor => CursorState.fromModelState(MoveOperations.moveToPrevBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)));
                }
            }
            case 5 /* CursorMove.Direction.NextBlankLine */: {
                if (unit === 2 /* CursorMove.Unit.WrappedLine */) {
                    return cursors.map(cursor => CursorState.fromViewState(MoveOperations.moveToNextBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode)));
                }
                else {
                    return cursors.map(cursor => CursorState.fromModelState(MoveOperations.moveToNextBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)));
                }
            }
            case 6 /* CursorMove.Direction.WrappedLineStart */: {
                // Move to the beginning of the current view line
                return this._moveToViewMinColumn(viewModel, cursors, inSelectionMode);
            }
            case 7 /* CursorMove.Direction.WrappedLineFirstNonWhitespaceCharacter */: {
                // Move to the first non-whitespace column of the current view line
                return this._moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode);
            }
            case 8 /* CursorMove.Direction.WrappedLineColumnCenter */: {
                // Move to the "center" of the current view line
                return this._moveToViewCenterColumn(viewModel, cursors, inSelectionMode);
            }
            case 9 /* CursorMove.Direction.WrappedLineEnd */: {
                // Move to the end of the current view line
                return this._moveToViewMaxColumn(viewModel, cursors, inSelectionMode);
            }
            case 10 /* CursorMove.Direction.WrappedLineLastNonWhitespaceCharacter */: {
                // Move to the last non-whitespace column of the current view line
                return this._moveToViewLastNonWhitespaceColumn(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 /* CursorMove.Direction.ViewPortTop */: {
                // Move to the nth line start in the viewport (from the top)
                const modelLineNumber = this._firstLineNumberInRange(viewModel.model, visibleModelRange, value);
                const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
                return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
            }
            case 13 /* CursorMove.Direction.ViewPortBottom */: {
                // Move to the nth line start in the viewport (from the bottom)
                const modelLineNumber = this._lastLineNumberInRange(viewModel.model, visibleModelRange, value);
                const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
                return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
            }
            case 12 /* CursorMove.Direction.ViewPortCenter */: {
                // Move to the line start in the viewport center
                const modelLineNumber = Math.round((visibleModelRange.startLineNumber + visibleModelRange.endLineNumber) / 2);
                const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
                return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
            }
            case 14 /* CursorMove.Direction.ViewPortIfOutside */: {
                // Move to a position inside the viewport
                const result = [];
                for (let i = 0, len = cursors.length; i < len; i++) {
                    const cursor = cursors[i];
                    result[i] = 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) {
            // Nothing to do, cursor is in viewport
            return new CursorState(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 = MoveOperations.vertical(viewModel.cursorConfig, viewModel, viewLineNumber, cursor.viewState.position.column, cursor.viewState.leftoverVisibleColumns, newViewLineNumber, false);
            return CursorState.fromViewState(cursor.viewState.move(inSelectionMode, position.lineNumber, position.column, position.leftoverVisibleColumns));
        }
    }
    /**
     * Find the nth line start included in the range (from the start).
     */
    static _firstLineNumberInRange(model, range, count) {
        let startLineNumber = range.startLineNumber;
        if (range.startColumn !== model.getLineMinColumn(startLineNumber)) {
            // Move on to the second line if the first line start is not included in the range
            startLineNumber++;
        }
        return Math.min(range.endLineNumber, startLineNumber + count - 1);
    }
    /**
     * Find the nth line start included in the range (from the end).
     */
    static _lastLineNumberInRange(model, range, count) {
        let startLineNumber = range.startLineNumber;
        if (range.startColumn !== model.getLineMinColumn(startLineNumber)) {
            // Move on to the second line if the first line start is not included in the range
            startLineNumber++;
        }
        return Math.max(startLineNumber, range.endLineNumber - count + 1);
    }
    static _moveLeft(viewModel, cursors, inSelectionMode, noOfColumns) {
        return cursors.map(cursor => CursorState.fromViewState(MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns)));
    }
    static _moveHalfLineLeft(viewModel, cursors, inSelectionMode) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            const viewLineNumber = cursor.viewState.position.lineNumber;
            const halfLine = Math.round(viewModel.getLineContent(viewLineNumber).length / 2);
            result[i] = CursorState.fromViewState(MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine));
        }
        return result;
    }
    static _moveRight(viewModel, cursors, inSelectionMode, noOfColumns) {
        return cursors.map(cursor => CursorState.fromViewState(MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns)));
    }
    static _moveHalfLineRight(viewModel, cursors, inSelectionMode) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            const viewLineNumber = cursor.viewState.position.lineNumber;
            const halfLine = Math.round(viewModel.getLineContent(viewLineNumber).length / 2);
            result[i] = CursorState.fromViewState(MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine));
        }
        return result;
    }
    static _moveDownByViewLines(viewModel, cursors, inSelectionMode, linesCount) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            result[i] = CursorState.fromViewState(MoveOperations.moveDown(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount));
        }
        return result;
    }
    static _moveDownByModelLines(viewModel, cursors, inSelectionMode, linesCount) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            result[i] = CursorState.fromModelState(MoveOperations.moveDown(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount));
        }
        return result;
    }
    static _moveUpByViewLines(viewModel, cursors, inSelectionMode, linesCount) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            result[i] = CursorState.fromViewState(MoveOperations.moveUp(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount));
        }
        return result;
    }
    static _moveUpByModelLines(viewModel, cursors, inSelectionMode, linesCount) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            result[i] = CursorState.fromModelState(MoveOperations.moveUp(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount));
        }
        return result;
    }
    static _moveToViewPosition(viewModel, cursor, inSelectionMode, toViewLineNumber, toViewColumn) {
        return CursorState.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0));
    }
    static _moveToModelPosition(viewModel, cursor, inSelectionMode, toModelLineNumber, toModelColumn) {
        return CursorState.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0));
    }
    static _moveToViewMinColumn(viewModel, cursors, inSelectionMode) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            const viewLineNumber = cursor.viewState.position.lineNumber;
            const viewColumn = viewModel.getLineMinColumn(viewLineNumber);
            result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
        }
        return result;
    }
    static _moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            const viewLineNumber = cursor.viewState.position.lineNumber;
            const viewColumn = viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber);
            result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
        }
        return result;
    }
    static _moveToViewCenterColumn(viewModel, cursors, inSelectionMode) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            const viewLineNumber = cursor.viewState.position.lineNumber;
            const viewColumn = Math.round((viewModel.getLineMaxColumn(viewLineNumber) + viewModel.getLineMinColumn(viewLineNumber)) / 2);
            result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
        }
        return result;
    }
    static _moveToViewMaxColumn(viewModel, cursors, inSelectionMode) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            const viewLineNumber = cursor.viewState.position.lineNumber;
            const viewColumn = viewModel.getLineMaxColumn(viewLineNumber);
            result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
        }
        return result;
    }
    static _moveToViewLastNonWhitespaceColumn(viewModel, cursors, inSelectionMode) {
        const result = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            const cursor = cursors[i];
            const viewLineNumber = cursor.viewState.position.lineNumber;
            const viewColumn = viewModel.getLineLastNonWhitespaceColumn(viewLineNumber);
            result[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
        }
        return result;
    }
}
var CursorMove;
(function (CursorMove) {
    const isCursorMoveArgs = function (arg) {
        if (!isObject(arg)) {
            return false;
        }
        const cursorMoveArg = arg;
        if (!isString(cursorMoveArg.to)) {
            return false;
        }
        if (!isUndefined(cursorMoveArg.select) && !isBoolean(cursorMoveArg.select)) {
            return false;
        }
        if (!isUndefined(cursorMoveArg.by) && !isString(cursorMoveArg.by)) {
            return false;
        }
        if (!isUndefined(cursorMoveArg.value) && !isNumber(cursorMoveArg.value)) {
            return false;
        }
        return true;
    };
    CursorMove.description = {
        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
                        }
                    }
                }
            }
        ]
    };
    /**
     * Positions in the view for cursor move command.
     */
    CursorMove.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'
    };
    /**
     * Units for Cursor move 'by' argument
     */
    CursorMove.RawUnit = {
        Line: 'line',
        WrappedLine: 'wrappedLine',
        Character: 'character',
        HalfLine: 'halfLine'
    };
    function parse(args) {
        if (!args.to) {
            // illegal arguments
            return null;
        }
        let direction;
        switch (args.to) {
            case CursorMove.RawDirection.Left:
                direction = 0 /* Direction.Left */;
                break;
            case CursorMove.RawDirection.Right:
                direction = 1 /* Direction.Right */;
                break;
            case CursorMove.RawDirection.Up:
                direction = 2 /* Direction.Up */;
                break;
            case CursorMove.RawDirection.Down:
                direction = 3 /* Direction.Down */;
                break;
            case CursorMove.RawDirection.PrevBlankLine:
                direction = 4 /* Direction.PrevBlankLine */;
                break;
            case CursorMove.RawDirection.NextBlankLine:
                direction = 5 /* Direction.NextBlankLine */;
                break;
            case CursorMove.RawDirection.WrappedLineStart:
                direction = 6 /* Direction.WrappedLineStart */;
                break;
            case CursorMove.RawDirection.WrappedLineFirstNonWhitespaceCharacter:
                direction = 7 /* Direction.WrappedLineFirstNonWhitespaceCharacter */;
                break;
            case CursorMove.RawDirection.WrappedLineColumnCenter:
                direction = 8 /* Direction.WrappedLineColumnCenter */;
                break;
            case CursorMove.RawDirection.WrappedLineEnd:
                direction = 9 /* Direction.WrappedLineEnd */;
                break;
            case CursorMove.RawDirection.WrappedLineLastNonWhitespaceCharacter:
                direction = 10 /* Direction.WrappedLineLastNonWhitespaceCharacter */;
                break;
            case CursorMove.RawDirection.ViewPortTop:
                direction = 11 /* Direction.ViewPortTop */;
                break;
            case CursorMove.RawDirection.ViewPortBottom:
                direction = 13 /* Direction.ViewPortBottom */;
                break;
            case CursorMove.RawDirection.ViewPortCenter:
                direction = 12 /* Direction.ViewPortCenter */;
                break;
            case CursorMove.RawDirection.ViewPortIfOutside:
                direction = 14 /* Direction.ViewPortIfOutside */;
                break;
            default:
                // illegal arguments
                return null;
        }
        let unit = 0 /* Unit.None */;
        switch (args.by) {
            case CursorMove.RawUnit.Line:
                unit = 1 /* Unit.Line */;
                break;
            case CursorMove.RawUnit.WrappedLine:
                unit = 2 /* Unit.WrappedLine */;
                break;
            case CursorMove.RawUnit.Character:
                unit = 3 /* Unit.Character */;
                break;
            case CursorMove.RawUnit.HalfLine:
                unit = 4 /* Unit.HalfLine */;
                break;
        }
        return {
            direction: direction,
            unit: unit,
            select: (!!args.select),
            value: (args.value || 1)
        };
    }
    CursorMove.parse = parse;
})(CursorMove || (CursorMove = {}));

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/enterAction.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


function getEnterAction(autoIndent, model, range, languageConfigurationService) {
    const scopedLineTokens = getScopedLineTokens(model, range.startLineNumber, range.startColumn);
    const richEditSupport = languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId);
    if (!richEditSupport) {
        return null;
    }
    const scopedLineText = scopedLineTokens.getLineContent();
    const beforeEnterText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset);
    // selection support
    let afterEnterText;
    if (range.isEmpty()) {
        afterEnterText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset);
    }
    else {
        const endScopedLineTokens = getScopedLineTokens(model, range.endLineNumber, range.endColumn);
        afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset);
    }
    let previousLineText = '';
    if (range.startLineNumber > 1 && scopedLineTokens.firstCharOffset === 0) {
        // This is not the first line and the entire line belongs to this mode
        const oneLineAboveScopedLineTokens = getScopedLineTokens(model, range.startLineNumber - 1);
        if (oneLineAboveScopedLineTokens.languageId === scopedLineTokens.languageId) {
            // The line above ends with text belonging to the same mode
            previousLineText = oneLineAboveScopedLineTokens.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;
    // Here we add `\t` to appendText first because enterAction is leveraging appendText and removeText to change indentation.
    if (!appendText) {
        if ((indentAction === IndentAction.Indent) ||
            (indentAction === IndentAction.IndentOutdent)) {
            appendText = '\t';
        }
        else {
            appendText = '';
        }
    }
    else if (indentAction === IndentAction.Indent) {
        appendText = '\t' + appendText;
    }
    let indentation = getIndentationAtPosition(model, range.startLineNumber, range.startColumn);
    if (removeText) {
        indentation = indentation.substring(0, indentation.length - removeText);
    }
    return {
        indentAction: indentAction,
        appendText: appendText,
        removeText: removeText,
        indentation: indentation
    };
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/commands/shiftCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var shiftCommand_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var shiftCommand_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};






const repeatCache = Object.create(null);
function cachedStringRepeat(str, count) {
    if (count <= 0) {
        return '';
    }
    if (!repeatCache[str]) {
        repeatCache[str] = ['', str];
    }
    const cache = repeatCache[str];
    for (let i = cache.length; i <= count; i++) {
        cache[i] = cache[i - 1] + str;
    }
    return cache[count];
}
let ShiftCommand = class ShiftCommand {
    constructor(range, opts, _languageConfigurationService) {
        this._languageConfigurationService = _languageConfigurationService;
        this._opts = opts;
        this._selection = range;
        this._selectionId = null;
        this._useLastEditRangeForCursorEndPosition = false;
        this._selectionStartColumnStaysPut = false;
    }
    static unshiftIndent(line, column, tabSize, indentSize, insertSpaces) {
        // Determine the visible column where the content starts
        const contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(line, column, tabSize);
        if (insertSpaces) {
            const indent = cachedStringRepeat(' ', indentSize);
            const desiredTabStop = CursorColumns.prevIndentTabStop(contentStartVisibleColumn, indentSize);
            const indentCount = desiredTabStop / indentSize; // will be an integer
            return cachedStringRepeat(indent, indentCount);
        }
        else {
            const indent = '\t';
            const desiredTabStop = CursorColumns.prevRenderTabStop(contentStartVisibleColumn, tabSize);
            const indentCount = desiredTabStop / tabSize; // will be an integer
            return cachedStringRepeat(indent, indentCount);
        }
    }
    static shiftIndent(line, column, tabSize, indentSize, insertSpaces) {
        // Determine the visible column where the content starts
        const contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(line, column, tabSize);
        if (insertSpaces) {
            const indent = cachedStringRepeat(' ', indentSize);
            const desiredTabStop = CursorColumns.nextIndentTabStop(contentStartVisibleColumn, indentSize);
            const indentCount = desiredTabStop / indentSize; // will be an integer
            return cachedStringRepeat(indent, indentCount);
        }
        else {
            const indent = '\t';
            const desiredTabStop = CursorColumns.nextRenderTabStop(contentStartVisibleColumn, tabSize);
            const indentCount = desiredTabStop / tabSize; // will be an integer
            return cachedStringRepeat(indent, indentCount);
        }
    }
    _addEditOperation(builder, range, text) {
        if (this._useLastEditRangeForCursorEndPosition) {
            builder.addTrackedEditOperation(range, text);
        }
        else {
            builder.addEditOperation(range, text);
        }
    }
    getEditOperations(model, builder) {
        const startLine = this._selection.startLineNumber;
        let endLine = this._selection.endLineNumber;
        if (this._selection.endColumn === 1 && startLine !== endLine) {
            endLine = endLine - 1;
        }
        const { tabSize, indentSize, insertSpaces } = this._opts;
        const shouldIndentEmptyLines = (startLine === endLine);
        if (this._opts.useTabStops) {
            // if indenting or outdenting on a whitespace only line
            if (this._selection.isEmpty()) {
                if (/^\s*$/.test(model.getLineContent(startLine))) {
                    this._useLastEditRangeForCursorEndPosition = true;
                }
            }
            // keep track of previous line's "miss-alignment"
            let previousLineExtraSpaces = 0, extraSpaces = 0;
            for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) {
                extraSpaces = 0;
                const lineText = model.getLineContent(lineNumber);
                let indentationEndIndex = strings_firstNonWhitespaceIndex(lineText);
                if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
                    // empty line or line with no leading whitespace => nothing to do
                    continue;
                }
                if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {
                    // do not indent empty lines => nothing to do
                    continue;
                }
                if (indentationEndIndex === -1) {
                    // the entire line is whitespace
                    indentationEndIndex = lineText.length;
                }
                if (lineNumber > 1) {
                    const contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(lineText, indentationEndIndex + 1, tabSize);
                    if (contentStartVisibleColumn % indentSize !== 0) {
                        // The current line is "miss-aligned", so let's see if this is expected...
                        // This can only happen when it has trailing commas in the indent
                        if (model.tokenization.isCheapToTokenize(lineNumber - 1)) {
                            const enterAction = getEnterAction(this._opts.autoIndent, model, new Range(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1), lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)), this._languageConfigurationService);
                            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 /* CharCode.Space */) {
                                            extraSpaces++;
                                        }
                                        else {
                                            break;
                                        }
                                    }
                                }
                                if (enterAction.removeText) {
                                    extraSpaces = Math.max(0, extraSpaces - enterAction.removeText);
                                }
                                // Act as if `prefixSpaces` is not part of the indentation
                                for (let j = 0; j < extraSpaces; j++) {
                                    if (indentationEndIndex === 0 || lineText.charCodeAt(indentationEndIndex - 1) !== 32 /* CharCode.Space */) {
                                        break;
                                    }
                                    indentationEndIndex--;
                                }
                            }
                        }
                    }
                }
                if (this._opts.isUnshift && indentationEndIndex === 0) {
                    // line with no leading whitespace => nothing to do
                    continue;
                }
                let desiredIndent;
                if (this._opts.isUnshift) {
                    desiredIndent = ShiftCommand.unshiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
                }
                else {
                    desiredIndent = ShiftCommand.shiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
                }
                this._addEditOperation(builder, new Range(lineNumber, 1, lineNumber, indentationEndIndex + 1), desiredIndent);
                if (lineNumber === startLine && !this._selection.isEmpty()) {
                    // Force the startColumn to stay put because we're inserting after it
                    this._selectionStartColumnStaysPut = (this._selection.startColumn <= indentationEndIndex + 1);
                }
            }
        }
        else {
            // if indenting or outdenting on a whitespace only line
            if (!this._opts.isUnshift && this._selection.isEmpty() && model.getLineLength(startLine) === 0) {
                this._useLastEditRangeForCursorEndPosition = true;
            }
            const oneIndent = (insertSpaces ? cachedStringRepeat(' ', indentSize) : '\t');
            for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++) {
                const lineText = model.getLineContent(lineNumber);
                let indentationEndIndex = strings_firstNonWhitespaceIndex(lineText);
                if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
                    // empty line or line with no leading whitespace => nothing to do
                    continue;
                }
                if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {
                    // do not indent empty lines => nothing to do
                    continue;
                }
                if (indentationEndIndex === -1) {
                    // the entire line is whitespace
                    indentationEndIndex = lineText.length;
                }
                if (this._opts.isUnshift && indentationEndIndex === 0) {
                    // line with no leading whitespace => nothing to do
                    continue;
                }
                if (this._opts.isUnshift) {
                    indentationEndIndex = Math.min(indentationEndIndex, indentSize);
                    for (let i = 0; i < indentationEndIndex; i++) {
                        const chr = lineText.charCodeAt(i);
                        if (chr === 9 /* CharCode.Tab */) {
                            indentationEndIndex = i + 1;
                            break;
                        }
                    }
                    this._addEditOperation(builder, new Range(lineNumber, 1, lineNumber, indentationEndIndex + 1), '');
                }
                else {
                    this._addEditOperation(builder, new Range(lineNumber, 1, lineNumber, 1), oneIndent);
                    if (lineNumber === startLine && !this._selection.isEmpty()) {
                        // Force the startColumn to stay put because we're inserting after it
                        this._selectionStartColumnStaysPut = (this._selection.startColumn === 1);
                    }
                }
            }
        }
        this._selectionId = builder.trackSelection(this._selection);
    }
    computeCursorState(model, helper) {
        if (this._useLastEditRangeForCursorEndPosition) {
            const lastOp = helper.getInverseEditOperations()[0];
            return new Selection(lastOp.range.endLineNumber, lastOp.range.endColumn, lastOp.range.endLineNumber, lastOp.range.endColumn);
        }
        const result = helper.getTrackedSelection(this._selectionId);
        if (this._selectionStartColumnStaysPut) {
            // The selection start should not move
            const initialStartColumn = this._selection.startColumn;
            const resultStartColumn = result.startColumn;
            if (resultStartColumn <= initialStartColumn) {
                return result;
            }
            if (result.getDirection() === 0 /* SelectionDirection.LTR */) {
                return new Selection(result.startLineNumber, initialStartColumn, result.endLineNumber, result.endColumn);
            }
            return new Selection(result.endLineNumber, result.endColumn, result.startLineNumber, initialStartColumn);
        }
        return result;
    }
};
ShiftCommand = shiftCommand_decorate([
    shiftCommand_param(2, ILanguageConfigurationService)
], ShiftCommand);


;// ../../node_modules/monaco-editor/esm/vs/editor/common/commands/surroundSelectionCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class SurroundSelectionCommand {
    constructor(range, charBeforeSelection, charAfterSelection) {
        this._range = range;
        this._charBeforeSelection = charBeforeSelection;
        this._charAfterSelection = charAfterSelection;
    }
    getEditOperations(model, builder) {
        builder.addTrackedEditOperation(new Range(this._range.startLineNumber, this._range.startColumn, this._range.startLineNumber, this._range.startColumn), this._charBeforeSelection);
        builder.addTrackedEditOperation(new Range(this._range.endLineNumber, this._range.endColumn, this._range.endLineNumber, this._range.endColumn), this._charAfterSelection);
    }
    computeCursorState(model, helper) {
        const inverseEditOperations = helper.getInverseEditOperations();
        const firstOperationRange = inverseEditOperations[0].range;
        const secondOperationRange = inverseEditOperations[1].range;
        return new Selection(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this._charAfterSelection.length);
    }
}
/**
 * A surround selection command that runs after composition finished.
 */
class CompositionSurroundSelectionCommand {
    constructor(_position, _text, _charAfter) {
        this._position = _position;
        this._text = _text;
        this._charAfter = _charAfter;
    }
    getEditOperations(model, builder) {
        builder.addTrackedEditOperation(new Range(this._position.lineNumber, this._position.column, this._position.lineNumber, this._position.column), this._text + this._charAfter);
    }
    computeCursorState(model, helper) {
        const inverseEditOperations = helper.getInverseEditOperations();
        const opRange = inverseEditOperations[0].range;
        return new Selection(opRange.endLineNumber, opRange.startColumn, opRange.endLineNumber, opRange.endColumn - this._charAfter.length);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/autoIndent.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




/**
 * Get nearest preceding line which doesn't match unIndentPattern or contains all whitespace.
 * Result:
 * -1: run into the boundary of embedded languages
 * 0: every line above are invalid
 * else: nearest preceding line of the same language
 */
function getPrecedingValidLine(model, lineNumber, indentRulesSupport) {
    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 text = model.getLineContent(lastLineNumber);
            if (indentRulesSupport.shouldIgnore(text) || /^\s+$/.test(text) || text === '') {
                resultLineNumber = lastLineNumber;
                continue;
            }
            return lastLineNumber;
        }
    }
    return -1;
}
/**
 * Get inherited indentation from above lines.
 * 1. Find the nearest preceding line which doesn't match unIndentedLinePattern.
 * 2. If this line matches indentNextLinePattern or increaseIndentPattern, it means that the indent level of `lineNumber` should be 1 greater than this line.
 * 3. If this line doesn't match any indent rules
 *   a. check whether the line above it matches indentNextLinePattern
 *   b. If not, the indent level of this line is the result
 *   c. If so, it means the indent of this line is *temporary*, go upward utill we find a line whose indent is not temporary (the same workflow a -> b -> c).
 * 4. Otherwise, we fail to get an inherited indent from aboves. Return null and we should not touch the indent of `lineNumber`
 *
 * This function only return the inherited indent based on above lines, it doesn't check whether current line should decrease or not.
 */
function getInheritIndentForLine(autoIndent, model, lineNumber, honorIntentialIndent = true, languageConfigurationService) {
    if (autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
        return null;
    }
    const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(model.tokenization.getLanguageId()).indentRulesSupport;
    if (!indentRulesSupport) {
        return null;
    }
    if (lineNumber <= 1) {
        return {
            indentation: '',
            action: null
        };
    }
    const precedingUnIgnoredLine = getPrecedingValidLine(model, lineNumber, indentRulesSupport);
    if (precedingUnIgnoredLine < 0) {
        return null;
    }
    else if (precedingUnIgnoredLine < 1) {
        return {
            indentation: '',
            action: null
        };
    }
    const precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine);
    if (indentRulesSupport.shouldIncrease(precedingUnIgnoredLineContent) || indentRulesSupport.shouldIndentNextLine(precedingUnIgnoredLineContent)) {
        return {
            indentation: getLeadingWhitespace(precedingUnIgnoredLineContent),
            action: IndentAction.Indent,
            line: precedingUnIgnoredLine
        };
    }
    else if (indentRulesSupport.shouldDecrease(precedingUnIgnoredLineContent)) {
        return {
            indentation: getLeadingWhitespace(precedingUnIgnoredLineContent),
            action: null,
            line: precedingUnIgnoredLine
        };
    }
    else {
        // precedingUnIgnoredLine can not be ignored.
        // it doesn't increase indent of following lines
        // it doesn't increase just next line
        // so current line is not affect by precedingUnIgnoredLine
        // and then we should get a correct inheritted indentation from above lines
        if (precedingUnIgnoredLine === 1) {
            return {
                indentation: getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
                action: null,
                line: precedingUnIgnoredLine
            };
        }
        const previousLine = precedingUnIgnoredLine - 1;
        const previousLineIndentMetadata = indentRulesSupport.getIndentMetadata(model.getLineContent(previousLine));
        if (!(previousLineIndentMetadata & (1 /* IndentConsts.INCREASE_MASK */ | 2 /* IndentConsts.DECREASE_MASK */)) &&
            (previousLineIndentMetadata & 4 /* IndentConsts.INDENT_NEXTLINE_MASK */)) {
            let stopLine = 0;
            for (let i = previousLine - 1; i > 0; i--) {
                if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(i))) {
                    continue;
                }
                stopLine = i;
                break;
            }
            return {
                indentation: getLeadingWhitespace(model.getLineContent(stopLine + 1)),
                action: null,
                line: stopLine + 1
            };
        }
        if (honorIntentialIndent) {
            return {
                indentation: getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
                action: null,
                line: precedingUnIgnoredLine
            };
        }
        else {
            // search from precedingUnIgnoredLine until we find one whose indent is not temporary
            for (let i = precedingUnIgnoredLine; i > 0; i--) {
                const lineContent = model.getLineContent(i);
                if (indentRulesSupport.shouldIncrease(lineContent)) {
                    return {
                        indentation: getLeadingWhitespace(lineContent),
                        action: IndentAction.Indent,
                        line: i
                    };
                }
                else if (indentRulesSupport.shouldIndentNextLine(lineContent)) {
                    let stopLine = 0;
                    for (let j = i - 1; j > 0; j--) {
                        if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(i))) {
                            continue;
                        }
                        stopLine = j;
                        break;
                    }
                    return {
                        indentation: getLeadingWhitespace(model.getLineContent(stopLine + 1)),
                        action: null,
                        line: stopLine + 1
                    };
                }
                else if (indentRulesSupport.shouldDecrease(lineContent)) {
                    return {
                        indentation: getLeadingWhitespace(lineContent),
                        action: null,
                        line: i
                    };
                }
            }
            return {
                indentation: getLeadingWhitespace(model.getLineContent(1)),
                action: null,
                line: 1
            };
        }
    }
}
function getGoodIndentForLine(autoIndent, virtualModel, languageId, lineNumber, indentConverter, languageConfigurationService) {
    if (autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
        return null;
    }
    const richEditSupport = languageConfigurationService.getLanguageConfiguration(languageId);
    if (!richEditSupport) {
        return null;
    }
    const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport;
    if (!indentRulesSupport) {
        return null;
    }
    const indent = getInheritIndentForLine(autoIndent, virtualModel, lineNumber, undefined, languageConfigurationService);
    const lineContent = virtualModel.getLineContent(lineNumber);
    if (indent) {
        const inheritLine = indent.line;
        if (inheritLine !== undefined) {
            const enterResult = richEditSupport.onEnter(autoIndent, '', virtualModel.getLineContent(inheritLine), '');
            if (enterResult) {
                let indentation = getLeadingWhitespace(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 (indentRulesSupport.shouldDecrease(lineContent)) {
                    indentation = indentConverter.unshiftIndent(indentation);
                }
                if (enterResult.appendText) {
                    indentation += enterResult.appendText;
                }
                return getLeadingWhitespace(indentation);
            }
        }
        if (indentRulesSupport.shouldDecrease(lineContent)) {
            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 getIndentForEnter(autoIndent, model, range, indentConverter, languageConfigurationService) {
    if (autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
        return null;
    }
    model.tokenization.forceTokenization(range.startLineNumber);
    const lineTokens = model.tokenization.getLineTokens(range.startLineNumber);
    const scopedLineTokens = createScopedLineTokens(lineTokens, range.startColumn - 1);
    const scopedLineText = scopedLineTokens.getLineContent();
    let embeddedLanguage = false;
    let beforeEnterText;
    if (scopedLineTokens.firstCharOffset > 0 && lineTokens.getLanguageId(0) !== scopedLineTokens.languageId) {
        // we are in the embeded language content
        embeddedLanguage = true; // if embeddedLanguage is true, then we don't touch the indentation of current line
        beforeEnterText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset);
    }
    else {
        beforeEnterText = lineTokens.getLineContent().substring(0, range.startColumn - 1);
    }
    let afterEnterText;
    if (range.isEmpty()) {
        afterEnterText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset);
    }
    else {
        const endScopedLineTokens = getScopedLineTokens(model, range.endLineNumber, range.endColumn);
        afterEnterText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset);
    }
    const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).indentRulesSupport;
    if (!indentRulesSupport) {
        return null;
    }
    const beforeEnterResult = beforeEnterText;
    const beforeEnterIndent = getLeadingWhitespace(beforeEnterText);
    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 === range.startLineNumber) {
                return beforeEnterResult;
            }
            else {
                return model.getLineContent(lineNumber);
            }
        }
    };
    const currentLineIndent = getLeadingWhitespace(lineTokens.getLineContent());
    const afterEnterAction = getInheritIndentForLine(autoIndent, virtualModel, range.startLineNumber + 1, undefined, languageConfigurationService);
    if (!afterEnterAction) {
        const beforeEnter = embeddedLanguage ? currentLineIndent : beforeEnterIndent;
        return {
            beforeEnter: beforeEnter,
            afterEnter: beforeEnter
        };
    }
    let afterEnterIndent = embeddedLanguage ? currentLineIndent : afterEnterAction.indentation;
    if (afterEnterAction.action === IndentAction.Indent) {
        afterEnterIndent = indentConverter.shiftIndent(afterEnterIndent);
    }
    if (indentRulesSupport.shouldDecrease(afterEnterText)) {
        afterEnterIndent = indentConverter.unshiftIndent(afterEnterIndent);
    }
    return {
        beforeEnter: embeddedLanguage ? currentLineIndent : beforeEnterIndent,
        afterEnter: afterEnterIndent
    };
}
/**
 * We should always allow intentional indentation. It means, if users change the indentation of `lineNumber` and the content of
 * this line doesn't match decreaseIndentPattern, we should not adjust the indentation.
 */
function getIndentActionForType(autoIndent, model, range, ch, indentConverter, languageConfigurationService) {
    if (autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
        return null;
    }
    const scopedLineTokens = getScopedLineTokens(model, range.startLineNumber, range.startColumn);
    if (scopedLineTokens.firstCharOffset) {
        // this line has mixed languages and indentation rules will not work
        return null;
    }
    const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).indentRulesSupport;
    if (!indentRulesSupport) {
        return null;
    }
    const scopedLineText = scopedLineTokens.getLineContent();
    const beforeTypeText = scopedLineText.substr(0, range.startColumn - 1 - scopedLineTokens.firstCharOffset);
    // selection support
    let afterTypeText;
    if (range.isEmpty()) {
        afterTypeText = scopedLineText.substr(range.startColumn - 1 - scopedLineTokens.firstCharOffset);
    }
    else {
        const endScopedLineTokens = getScopedLineTokens(model, range.endLineNumber, range.endColumn);
        afterTypeText = endScopedLineTokens.getLineContent().substr(range.endColumn - 1 - scopedLineTokens.firstCharOffset);
    }
    // If previous content already matches decreaseIndentPattern, it means indentation of this line should already be adjusted
    // Users might change the indentation by purpose and we should honor that instead of readjusting.
    if (!indentRulesSupport.shouldDecrease(beforeTypeText + afterTypeText) && indentRulesSupport.shouldDecrease(beforeTypeText + ch + afterTypeText)) {
        // after typing `ch`, the content matches decreaseIndentPattern, we should adjust the indent to a good manner.
        // 1. Get inherited indent action
        const r = getInheritIndentForLine(autoIndent, model, range.startLineNumber, false, languageConfigurationService);
        if (!r) {
            return null;
        }
        let indentation = r.indentation;
        if (r.action !== IndentAction.Indent) {
            indentation = indentConverter.unshiftIndent(indentation);
        }
        return indentation;
    }
    return null;
}
function getIndentMetadata(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));
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursor/cursorTypeOperations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/














class TypeOperations {
    static indent(config, model, selections) {
        if (model === null || selections === null) {
            return [];
        }
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            commands[i] = new ShiftCommand(selections[i], {
                isUnshift: false,
                tabSize: config.tabSize,
                indentSize: config.indentSize,
                insertSpaces: config.insertSpaces,
                useTabStops: config.useTabStops,
                autoIndent: config.autoIndent
            }, config.languageConfigurationService);
        }
        return commands;
    }
    static outdent(config, model, selections) {
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            commands[i] = new ShiftCommand(selections[i], {
                isUnshift: true,
                tabSize: config.tabSize,
                indentSize: config.indentSize,
                insertSpaces: config.insertSpaces,
                useTabStops: config.useTabStops,
                autoIndent: config.autoIndent
            }, config.languageConfigurationService);
        }
        return commands;
    }
    static shiftIndent(config, indentation, count) {
        count = count || 1;
        return ShiftCommand.shiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);
    }
    static unshiftIndent(config, indentation, count) {
        count = count || 1;
        return ShiftCommand.unshiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces);
    }
    static _distributedPaste(config, model, selections, text) {
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            commands[i] = new ReplaceCommand(selections[i], text[i]);
        }
        return new EditOperationResult(0 /* EditOperationType.Other */, commands, {
            shouldPushStackElementBefore: true,
            shouldPushStackElementAfter: true
        });
    }
    static _simplePaste(config, model, selections, text, pasteOnNewLine) {
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            const position = selection.getPosition();
            if (pasteOnNewLine && !selection.isEmpty()) {
                pasteOnNewLine = false;
            }
            if (pasteOnNewLine && text.indexOf('\n') !== text.length - 1) {
                pasteOnNewLine = false;
            }
            if (pasteOnNewLine) {
                // Paste entire line at the beginning of line
                const typeSelection = new Range(position.lineNumber, 1, position.lineNumber, 1);
                commands[i] = new ReplaceCommandThatPreservesSelection(typeSelection, text, selection, true);
            }
            else {
                commands[i] = new ReplaceCommand(selection, text);
            }
        }
        return new EditOperationResult(0 /* EditOperationType.Other */, commands, {
            shouldPushStackElementBefore: true,
            shouldPushStackElementAfter: true
        });
    }
    static _distributePasteToCursors(config, selections, text, pasteOnNewLine, multicursorText) {
        if (pasteOnNewLine) {
            return null;
        }
        if (selections.length === 1) {
            return null;
        }
        if (multicursorText && multicursorText.length === selections.length) {
            return multicursorText;
        }
        if (config.multiCursorPaste === 'spread') {
            // Try to spread the pasted text in case the line count matches the cursor count
            // Remove trailing \n if present
            if (text.charCodeAt(text.length - 1) === 10 /* CharCode.LineFeed */) {
                text = text.substr(0, text.length - 1);
            }
            // Remove trailing \r if present
            if (text.charCodeAt(text.length - 1) === 13 /* CharCode.CarriageReturn */) {
                text = text.substr(0, text.length - 1);
            }
            const lines = splitLines(text);
            if (lines.length === selections.length) {
                return lines;
            }
        }
        return null;
    }
    static paste(config, model, selections, text, pasteOnNewLine, multicursorText) {
        const distributedPaste = this._distributePasteToCursors(config, selections, text, pasteOnNewLine, multicursorText);
        if (distributedPaste) {
            selections = selections.sort(Range.compareRangesUsingStarts);
            return this._distributedPaste(config, model, selections, distributedPaste);
        }
        else {
            return this._simplePaste(config, model, selections, text, pasteOnNewLine);
        }
    }
    static _goodIndentForLine(config, model, lineNumber) {
        let action = null;
        let indentation = '';
        const expectedIndentAction = getInheritIndentForLine(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 = strings_lastNonWhitespaceIndex(lineText);
                if (nonWhitespaceIdx >= 0) {
                    break;
                }
            }
            if (lastLineNumber < 1) {
                // No previous line with content found
                return null;
            }
            const maxColumn = model.getLineMaxColumn(lastLineNumber);
            const expectedEnterAction = getEnterAction(config.autoIndent, model, new Range(lastLineNumber, maxColumn, lastLineNumber, maxColumn), config.languageConfigurationService);
            if (expectedEnterAction) {
                indentation = expectedEnterAction.indentation + expectedEnterAction.appendText;
            }
        }
        if (action) {
            if (action === IndentAction.Indent) {
                indentation = TypeOperations.shiftIndent(config, indentation);
            }
            if (action === IndentAction.Outdent) {
                indentation = TypeOperations.unshiftIndent(config, indentation);
            }
            indentation = config.normalizeIndentation(indentation);
        }
        if (!indentation) {
            return null;
        }
        return indentation;
    }
    static _replaceJumpToNextIndent(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 i = 0; i < spacesCnt; i++) {
                typeText += ' ';
            }
        }
        else {
            typeText = '\t';
        }
        return new ReplaceCommand(selection, typeText, insertsAutoWhitespace);
    }
    static tab(config, model, selections) {
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            if (selection.isEmpty()) {
                const lineText = model.getLineContent(selection.startLineNumber);
                if (/^\s*$/.test(lineText) && model.tokenization.isCheapToTokenize(selection.startLineNumber)) {
                    let goodIndent = this._goodIndentForLine(config, model, selection.startLineNumber);
                    goodIndent = goodIndent || '\t';
                    const possibleTypeText = config.normalizeIndentation(goodIndent);
                    if (!lineText.startsWith(possibleTypeText)) {
                        commands[i] = new ReplaceCommand(new Range(selection.startLineNumber, 1, selection.startLineNumber, lineText.length + 1), possibleTypeText, true);
                        continue;
                    }
                }
                commands[i] = this._replaceJumpToNextIndent(config, model, selection, true);
            }
            else {
                if (selection.startLineNumber === selection.endLineNumber) {
                    const lineMaxColumn = model.getLineMaxColumn(selection.startLineNumber);
                    if (selection.startColumn !== 1 || selection.endColumn !== lineMaxColumn) {
                        // This is a single line selection that is not the entire line
                        commands[i] = this._replaceJumpToNextIndent(config, model, selection, false);
                        continue;
                    }
                }
                commands[i] = new ShiftCommand(selection, {
                    isUnshift: false,
                    tabSize: config.tabSize,
                    indentSize: config.indentSize,
                    insertSpaces: config.insertSpaces,
                    useTabStops: config.useTabStops,
                    autoIndent: config.autoIndent
                }, config.languageConfigurationService);
            }
        }
        return commands;
    }
    static compositionType(prevEditOperationType, config, model, selections, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
        const commands = selections.map(selection => this._compositionType(model, selection, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta));
        return new EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
            shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, 4 /* EditOperationType.TypingOther */),
            shouldPushStackElementAfter: false
        });
    }
    static _compositionType(model, selection, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
        if (!selection.isEmpty()) {
            // looks like https://github.com/microsoft/vscode/issues/2773
            // where a cursor operation occurred before a canceled composition
            // => ignore composition
            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 Range(pos.lineNumber, startColumn, pos.lineNumber, endColumn);
        const oldText = model.getValueInRange(range);
        if (oldText === text && positionDelta === 0) {
            // => ignore composition that doesn't do anything
            return null;
        }
        return new ReplaceCommandWithOffsetCursorState(range, text, 0, positionDelta);
    }
    static _typeCommand(range, text, keepPosition) {
        if (keepPosition) {
            return new ReplaceCommandWithoutChangingPosition(range, text, true);
        }
        else {
            return new ReplaceCommand(range, text, true);
        }
    }
    static _enter(config, model, keepPosition, range) {
        if (config.autoIndent === 0 /* EditorAutoIndentStrategy.None */) {
            return TypeOperations._typeCommand(range, '\n', keepPosition);
        }
        if (!model.tokenization.isCheapToTokenize(range.getStartPosition().lineNumber) || config.autoIndent === 1 /* EditorAutoIndentStrategy.Keep */) {
            const lineText = model.getLineContent(range.startLineNumber);
            const indentation = getLeadingWhitespace(lineText).substring(0, range.startColumn - 1);
            return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation), keepPosition);
        }
        const r = getEnterAction(config.autoIndent, model, range, config.languageConfigurationService);
        if (r) {
            if (r.indentAction === IndentAction.None) {
                // Nothing special
                return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(r.indentation + r.appendText), keepPosition);
            }
            else if (r.indentAction === IndentAction.Indent) {
                // Indent once
                return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(r.indentation + r.appendText), keepPosition);
            }
            else if (r.indentAction === IndentAction.IndentOutdent) {
                // Ultra special
                const normalIndent = config.normalizeIndentation(r.indentation);
                const increasedIndent = config.normalizeIndentation(r.indentation + r.appendText);
                const typeText = '\n' + increasedIndent + '\n' + normalIndent;
                if (keepPosition) {
                    return new ReplaceCommandWithoutChangingPosition(range, typeText, true);
                }
                else {
                    return new ReplaceCommandWithOffsetCursorState(range, typeText, -1, increasedIndent.length - normalIndent.length, true);
                }
            }
            else if (r.indentAction === IndentAction.Outdent) {
                const actualIndentation = TypeOperations.unshiftIndent(config, r.indentation);
                return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(actualIndentation + r.appendText), keepPosition);
            }
        }
        const lineText = model.getLineContent(range.startLineNumber);
        const indentation = getLeadingWhitespace(lineText).substring(0, range.startColumn - 1);
        if (config.autoIndent >= 4 /* EditorAutoIndentStrategy.Full */) {
            const ir = getIndentForEnter(config.autoIndent, model, range, {
                unshiftIndent: (indent) => {
                    return TypeOperations.unshiftIndent(config, indent);
                },
                shiftIndent: (indent) => {
                    return TypeOperations.shiftIndent(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 = strings_firstNonWhitespaceIndex(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 ReplaceCommandWithoutChangingPosition(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 ReplaceCommandWithOffsetCursorState(range, '\n' + config.normalizeIndentation(ir.afterEnter), 0, offset, true);
                }
            }
        }
        return TypeOperations._typeCommand(range, '\n' + config.normalizeIndentation(indentation), keepPosition);
    }
    static _isAutoIndentType(config, model, selections) {
        if (config.autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
            return false;
        }
        for (let i = 0, len = selections.length; i < len; i++) {
            if (!model.tokenization.isCheapToTokenize(selections[i].getEndPosition().lineNumber)) {
                return false;
            }
        }
        return true;
    }
    static _runAutoIndentType(config, model, range, ch) {
        const currentIndentation = getIndentationAtPosition(model, range.startLineNumber, range.startColumn);
        const actualIndentation = getIndentActionForType(config.autoIndent, model, range, ch, {
            shiftIndent: (indentation) => {
                return TypeOperations.shiftIndent(config, indentation);
            },
            unshiftIndent: (indentation) => {
                return TypeOperations.unshiftIndent(config, indentation);
            },
        }, config.languageConfigurationService);
        if (actualIndentation === null) {
            return null;
        }
        if (actualIndentation !== config.normalizeIndentation(currentIndentation)) {
            const firstNonWhitespace = model.getLineFirstNonWhitespaceColumn(range.startLineNumber);
            if (firstNonWhitespace === 0) {
                return TypeOperations._typeCommand(new Range(range.startLineNumber, 1, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) + ch, false);
            }
            else {
                return TypeOperations._typeCommand(new Range(range.startLineNumber, 1, range.endLineNumber, range.endColumn), config.normalizeIndentation(actualIndentation) +
                    model.getLineContent(range.startLineNumber).substring(firstNonWhitespace - 1, range.startColumn - 1) + ch, false);
            }
        }
        return null;
    }
    static _isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch) {
        if (config.autoClosingOvertype === 'never') {
            return false;
        }
        if (!config.autoClosingPairs.autoClosingPairsCloseSingleChar.has(ch)) {
            return false;
        }
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            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;
            }
            // Do not over-type quotes after a backslash
            const chIsQuote = isQuote(ch);
            const beforeCharacter = position.column > 2 ? lineText.charCodeAt(position.column - 2) : 0 /* CharCode.Null */;
            if (beforeCharacter === 92 /* CharCode.Backslash */ && chIsQuote) {
                return false;
            }
            // Must over-type a closing character typed by the editor
            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;
    }
    static _runAutoClosingOvertype(prevEditOperationType, config, model, selections, ch) {
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            const position = selection.getPosition();
            const typeSelection = new Range(position.lineNumber, position.column, position.lineNumber, position.column + 1);
            commands[i] = new ReplaceCommand(typeSelection, ch);
        }
        return new EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
            shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, 4 /* EditOperationType.TypingOther */),
            shouldPushStackElementAfter: false
        });
    }
    static _isBeforeClosingBrace(config, lineAfter) {
        // If the start of lineAfter can be interpretted as both a starting or ending brace, default to returning false
        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;
    }
    /**
     * 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 _findAutoClosingPairOpen(config, model, positions, ch) {
        const candidates = config.autoClosingPairs.autoClosingPairsOpenByEnd.get(ch);
        if (!candidates) {
            return null;
        }
        // Determine which auto-closing pair it is
        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 Range(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;
    }
    /**
     * 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 _findContainedAutoClosingPair(config, pair) {
        if (pair.open.length <= 1) {
            return null;
        }
        const lastChar = pair.close.charAt(pair.close.length - 1);
        // get candidates with the same last character as close
        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;
    }
    static _getAutoClosingPairClose(config, model, selections, ch, chIsAlreadyTyped) {
        const chIsQuote = isQuote(ch);
        const autoCloseConfig = (chIsQuote ? config.autoClosingQuotes : config.autoClosingBrackets);
        const shouldAutoCloseBefore = (chIsQuote ? config.shouldAutoCloseBefore.quote : config.shouldAutoCloseBefore.bracket);
        if (autoCloseConfig === 'never') {
            return null;
        }
        for (const selection of selections) {
            if (!selection.isEmpty()) {
                return null;
            }
        }
        // This method is called both when typing (regularly) and when composition ends
        // This means that we need to work with a text buffer where sometimes `ch` is not
        // there (it is being typed right now) or with a text buffer where `ch` has already been typed
        //
        // In order to avoid adding checks for `chIsAlreadyTyped` in all places, we will work
        // with two conceptual positions, the position before `ch` and the position after `ch`
        //
        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 };
            }
        });
        // Find the longest auto-closing open pair in case of multiple ending in `ch`
        // e.g. when having [f","] and [","], it picks [f","] if the character before is f
        const pair = this._findAutoClosingPairOpen(config, model, positions.map(p => new Position(p.lineNumber, p.beforeColumn)), ch);
        if (!pair) {
            return null;
        }
        // Sometimes, it is possible to have two auto-closing pairs that have a containment relationship
        // e.g. when having [(,)] and [(*,*)]
        // - when typing (, the resulting state is (|)
        // - when typing *, the desired resulting state is (*|*), not (*|*))
        const containedPair = this._findContainedAutoClosingPair(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;
            }
            // Only consider auto closing the pair if an allowed character follows or if another autoclosed pair closing brace follows
            if (lineAfter.length > 0) {
                const characterAfter = lineAfter.charAt(0);
                const isBeforeCloseBrace = TypeOperations._isBeforeClosingBrace(config, lineAfter);
                if (!isBeforeCloseBrace && !shouldAutoCloseBefore(characterAfter)) {
                    return null;
                }
            }
            // Do not auto-close ' or " after a word character
            if (pair.open.length === 1 && (ch === '\'' || ch === '"') && autoCloseConfig !== 'always') {
                const wordSeparators = getMapForWordSeparators(config.wordSeparators);
                if (lineBefore.length > 0) {
                    const characterBefore = lineBefore.charCodeAt(lineBefore.length - 1);
                    if (wordSeparators.get(characterBefore) === 0 /* WordCharacterClass.Regular */) {
                        return null;
                    }
                }
            }
            if (!model.tokenization.isCheapToTokenize(lineNumber)) {
                // Do not force tokenization
                return null;
            }
            model.tokenization.forceTokenization(lineNumber);
            const lineTokens = model.tokenization.getLineTokens(lineNumber);
            const scopedLineTokens = createScopedLineTokens(lineTokens, beforeColumn - 1);
            if (!pair.shouldAutoClose(scopedLineTokens, beforeColumn - scopedLineTokens.firstCharOffset)) {
                return null;
            }
            // Typing for example a quote could either start a new string, in which case auto-closing is desirable
            // or it could end a previously started string, in which case auto-closing is not desirable
            //
            // In certain cases, it is really not possible to look at the previous token to determine
            // what would happen. That's why we do something really unusual, we pretend to type a different
            // character and ask the tokenizer what the outcome of doing that is: after typing a neutral
            // character, are we in a string (i.e. the quote would most likely end a string) or not?
            //
            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;
        }
    }
    static _runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, chIsAlreadyTyped, autoClosingPairClose) {
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            commands[i] = new TypeWithAutoClosingCommand(selection, ch, !chIsAlreadyTyped, autoClosingPairClose);
        }
        return new EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
            shouldPushStackElementBefore: true,
            shouldPushStackElementAfter: false
        });
    }
    static _shouldSurroundChar(config, ch) {
        if (isQuote(ch)) {
            return (config.autoSurround === 'quotes' || config.autoSurround === 'languageDefined');
        }
        else {
            // Character is a bracket
            return (config.autoSurround === 'brackets' || config.autoSurround === 'languageDefined');
        }
    }
    static _isSurroundSelectionType(config, model, selections, ch) {
        if (!TypeOperations._shouldSurroundChar(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) {
            return false;
        }
        const isTypingAQuoteCharacter = isQuote(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)) {
                    // this selected text contains something other than whitespace
                    selectionContainsOnlyWhitespace = false;
                    break;
                }
            }
            if (selectionContainsOnlyWhitespace) {
                return false;
            }
            if (isTypingAQuoteCharacter && selection.startLineNumber === selection.endLineNumber && selection.startColumn + 1 === selection.endColumn) {
                const selectionText = model.getValueInRange(selection);
                if (isQuote(selectionText)) {
                    // Typing a quote character on top of another quote character
                    // => disable surround selection type
                    return false;
                }
            }
        }
        return true;
    }
    static _runSurroundSelectionType(prevEditOperationType, config, model, selections, ch) {
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            const closeCharacter = config.surroundingPairs[ch];
            commands[i] = new SurroundSelectionCommand(selection, ch, closeCharacter);
        }
        return new EditOperationResult(0 /* EditOperationType.Other */, commands, {
            shouldPushStackElementBefore: true,
            shouldPushStackElementAfter: true
        });
    }
    static _isTypeInterceptorElectricChar(config, model, selections) {
        if (selections.length === 1 && model.tokenization.isCheapToTokenize(selections[0].getEndPosition().lineNumber)) {
            return true;
        }
        return false;
    }
    static _typeInterceptorElectricChar(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) {
            onUnexpectedError(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) {
                    // matched something on the same line => no change in indentation
                    return null;
                }
                const matchLine = model.getLineContent(match.startLineNumber);
                const matchLineIndentation = getLeadingWhitespace(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 Range(position.lineNumber, 1, position.lineNumber, position.column);
                const command = new ReplaceCommand(typeSelection, typeText);
                return new EditOperationResult(getTypingOperation(typeText, prevEditOperationType), [command], {
                    shouldPushStackElementBefore: false,
                    shouldPushStackElementAfter: true
                });
            }
        }
        return null;
    }
    /**
     * 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) {
            // could not deduce what the composition did
            return null;
        }
        let insertedText = null;
        for (const composition of compositions) {
            if (insertedText === null) {
                insertedText = composition.insertedText;
            }
            else if (insertedText !== composition.insertedText) {
                // not all selections agree on what was typed
                return null;
            }
        }
        if (!insertedText || insertedText.length !== 1) {
            // we're only interested in the case where a single character was inserted
            return null;
        }
        const ch = insertedText;
        let hasDeletion = false;
        for (const composition of compositions) {
            if (composition.deletedText.length !== 0) {
                hasDeletion = true;
                break;
            }
        }
        if (hasDeletion) {
            // Check if this could have been a surround selection
            if (!TypeOperations._shouldSurroundChar(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) {
                return null;
            }
            const isTypingAQuoteCharacter = isQuote(ch);
            for (const composition of compositions) {
                if (composition.deletedSelectionStart !== 0 || composition.deletedSelectionEnd !== composition.deletedText.length) {
                    // more text was deleted than was selected, so this could not have been a surround selection
                    return null;
                }
                if (/^[ \t]+$/.test(composition.deletedText)) {
                    // deleted text was only whitespace
                    return null;
                }
                if (isTypingAQuoteCharacter && isQuote(composition.deletedText)) {
                    // deleted text was a quote
                    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 commands = [];
            for (let i = 0, len = positions.length; i < len; i++) {
                commands.push(new CompositionSurroundSelectionCommand(positions[i], compositions[i].deletedText, ch));
            }
            return new EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: false
            });
        }
        if (this._isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) {
            // Unfortunately, the close character is at this point "doubled", so we need to delete it...
            const commands = selections.map(s => new ReplaceCommand(new Range(s.positionLineNumber, s.positionColumn, s.positionLineNumber, s.positionColumn + 1), '', false));
            return new EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: false
            });
        }
        const autoClosingPairClose = this._getAutoClosingPairClose(config, model, selections, ch, true);
        if (autoClosingPairClose !== null) {
            return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, true, autoClosingPairClose);
        }
        return null;
    }
    static typeWithInterceptors(isDoingComposition, prevEditOperationType, config, model, selections, autoClosedCharacters, ch) {
        if (!isDoingComposition && ch === '\n') {
            const commands = [];
            for (let i = 0, len = selections.length; i < len; i++) {
                commands[i] = TypeOperations._enter(config, model, false, selections[i]);
            }
            return new EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
                shouldPushStackElementBefore: true,
                shouldPushStackElementAfter: false,
            });
        }
        if (!isDoingComposition && this._isAutoIndentType(config, model, selections)) {
            const commands = [];
            let autoIndentFails = false;
            for (let i = 0, len = selections.length; i < len; i++) {
                commands[i] = this._runAutoIndentType(config, model, selections[i], ch);
                if (!commands[i]) {
                    autoIndentFails = true;
                    break;
                }
            }
            if (!autoIndentFails) {
                return new EditOperationResult(4 /* EditOperationType.TypingOther */, commands, {
                    shouldPushStackElementBefore: true,
                    shouldPushStackElementAfter: false,
                });
            }
        }
        if (this._isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) {
            return this._runAutoClosingOvertype(prevEditOperationType, config, model, selections, ch);
        }
        if (!isDoingComposition) {
            const autoClosingPairClose = this._getAutoClosingPairClose(config, model, selections, ch, false);
            if (autoClosingPairClose) {
                return this._runAutoClosingOpenCharType(prevEditOperationType, config, model, selections, ch, false, autoClosingPairClose);
            }
        }
        if (!isDoingComposition && this._isSurroundSelectionType(config, model, selections, ch)) {
            return this._runSurroundSelectionType(prevEditOperationType, config, model, selections, ch);
        }
        // Electric characters make sense only when dealing with a single cursor,
        // as multiple cursors typing brackets for example would interfer with bracket matching
        if (!isDoingComposition && this._isTypeInterceptorElectricChar(config, model, selections)) {
            const r = this._typeInterceptorElectricChar(prevEditOperationType, config, model, selections[0], ch);
            if (r) {
                return r;
            }
        }
        // A simple character type
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            commands[i] = new ReplaceCommand(selections[i], ch);
        }
        const opType = getTypingOperation(ch, prevEditOperationType);
        return new EditOperationResult(opType, commands, {
            shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType),
            shouldPushStackElementAfter: false
        });
    }
    static typeWithoutInterceptors(prevEditOperationType, config, model, selections, str) {
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            commands[i] = new ReplaceCommand(selections[i], str);
        }
        const opType = getTypingOperation(str, prevEditOperationType);
        return new EditOperationResult(opType, commands, {
            shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType),
            shouldPushStackElementAfter: false
        });
    }
    static lineInsertBefore(config, model, selections) {
        if (model === null || selections === null) {
            return [];
        }
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            let lineNumber = selections[i].positionLineNumber;
            if (lineNumber === 1) {
                commands[i] = new ReplaceCommandWithoutChangingPosition(new Range(1, 1, 1, 1), '\n');
            }
            else {
                lineNumber--;
                const column = model.getLineMaxColumn(lineNumber);
                commands[i] = this._enter(config, model, false, new Range(lineNumber, column, lineNumber, column));
            }
        }
        return commands;
    }
    static lineInsertAfter(config, model, selections) {
        if (model === null || selections === null) {
            return [];
        }
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            const lineNumber = selections[i].positionLineNumber;
            const column = model.getLineMaxColumn(lineNumber);
            commands[i] = this._enter(config, model, false, new Range(lineNumber, column, lineNumber, column));
        }
        return commands;
    }
    static lineBreakInsert(config, model, selections) {
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            commands[i] = this._enter(config, model, true, selections[i]);
        }
        return commands;
    }
}
class TypeWithAutoClosingCommand extends ReplaceCommandWithOffsetCursorState {
    constructor(selection, openCharacter, insertOpenCharacter, closeCharacter) {
        super(selection, (insertOpenCharacter ? openCharacter : '') + closeCharacter, 0, -closeCharacter.length);
        this._openCharacter = openCharacter;
        this._closeCharacter = closeCharacter;
        this.closeCharacterRange = null;
        this.enclosingRange = null;
    }
    computeCursorState(model, helper) {
        const inverseEditOperations = helper.getInverseEditOperations();
        const range = inverseEditOperations[0].range;
        this.closeCharacterRange = new Range(range.startLineNumber, range.endColumn - this._closeCharacter.length, range.endLineNumber, range.endColumn);
        this.enclosingRange = new Range(range.startLineNumber, range.endColumn - this._openCharacter.length - this._closeCharacter.length, range.endLineNumber, range.endColumn);
        return super.computeCursorState(model, helper);
    }
}
class CompositionOutcome {
    constructor(deletedText, deletedSelectionStart, deletedSelectionEnd, insertedText, insertedSelectionStart, insertedSelectionEnd) {
        this.deletedText = deletedText;
        this.deletedSelectionStart = deletedSelectionStart;
        this.deletedSelectionEnd = deletedSelectionEnd;
        this.insertedText = insertedText;
        this.insertedSelectionStart = insertedSelectionStart;
        this.insertedSelectionEnd = insertedSelectionEnd;
    }
}
function getTypingOperation(typedText, previousTypingOperation) {
    if (typedText === ' ') {
        return previousTypingOperation === 5 /* EditOperationType.TypingFirstSpace */
            || previousTypingOperation === 6 /* EditOperationType.TypingConsecutiveSpace */
            ? 6 /* EditOperationType.TypingConsecutiveSpace */
            : 5 /* EditOperationType.TypingFirstSpace */;
    }
    return 4 /* EditOperationType.TypingOther */;
}
function shouldPushStackElementBetween(previousTypingOperation, typingOperation) {
    if (isTypingOperation(previousTypingOperation) && !isTypingOperation(typingOperation)) {
        // Always set an undo stop before non-type operations
        return true;
    }
    if (previousTypingOperation === 5 /* EditOperationType.TypingFirstSpace */) {
        // `abc |d`: No undo stop
        // `abc  |d`: Undo stop
        return false;
    }
    // Insert undo stop between different operation types
    return normalizeOperationType(previousTypingOperation) !== normalizeOperationType(typingOperation);
}
function normalizeOperationType(type) {
    return (type === 6 /* EditOperationType.TypingConsecutiveSpace */ || type === 5 /* EditOperationType.TypingFirstSpace */)
        ? 'space'
        : type;
}
function isTypingOperation(type) {
    return type === 4 /* EditOperationType.TypingOther */
        || type === 5 /* EditOperationType.TypingFirstSpace */
        || type === 6 /* EditOperationType.TypingConsecutiveSpace */;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/coreCommands.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
















const CORE_WEIGHT = 0 /* KeybindingWeight.EditorCore */;
class CoreEditorCommand extends EditorCommand {
    runEditorCommand(accessor, editor, args) {
        const viewModel = editor._getViewModel();
        if (!viewModel) {
            // the editor has no view => has no cursors
            return;
        }
        this.runCoreEditorCommand(viewModel, args || {});
    }
}
var EditorScroll_;
(function (EditorScroll_) {
    const isEditorScrollArgs = function (arg) {
        if (!isObject(arg)) {
            return false;
        }
        const scrollArg = arg;
        if (!isString(scrollArg.to)) {
            return false;
        }
        if (!isUndefined(scrollArg.by) && !isString(scrollArg.by)) {
            return false;
        }
        if (!isUndefined(scrollArg.value) && !isNumber(scrollArg.value)) {
            return false;
        }
        if (!isUndefined(scrollArg.revealCursor) && !isBoolean(scrollArg.revealCursor)) {
            return false;
        }
        return true;
    };
    EditorScroll_.description = {
        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',
                        }
                    }
                }
            }
        ]
    };
    /**
     * Directions in the view for editor scroll command.
     */
    EditorScroll_.RawDirection = {
        Up: 'up',
        Down: 'down',
    };
    /**
     * Units for editor scroll 'by' argument
     */
    EditorScroll_.RawUnit = {
        Line: 'line',
        WrappedLine: 'wrappedLine',
        Page: 'page',
        HalfPage: 'halfPage',
        Editor: 'editor'
    };
    function parse(args) {
        let direction;
        switch (args.to) {
            case EditorScroll_.RawDirection.Up:
                direction = 1 /* Direction.Up */;
                break;
            case EditorScroll_.RawDirection.Down:
                direction = 2 /* Direction.Down */;
                break;
            default:
                // Illegal arguments
                return null;
        }
        let unit;
        switch (args.by) {
            case EditorScroll_.RawUnit.Line:
                unit = 1 /* Unit.Line */;
                break;
            case EditorScroll_.RawUnit.WrappedLine:
                unit = 2 /* Unit.WrappedLine */;
                break;
            case EditorScroll_.RawUnit.Page:
                unit = 3 /* Unit.Page */;
                break;
            case EditorScroll_.RawUnit.HalfPage:
                unit = 4 /* Unit.HalfPage */;
                break;
            case EditorScroll_.RawUnit.Editor:
                unit = 5 /* Unit.Editor */;
                break;
            default:
                unit = 2 /* Unit.WrappedLine */;
        }
        const value = Math.floor(args.value || 1);
        const revealCursor = !!args.revealCursor;
        return {
            direction: direction,
            unit: unit,
            value: value,
            revealCursor: revealCursor,
            select: (!!args.select)
        };
    }
    EditorScroll_.parse = parse;
})(EditorScroll_ || (EditorScroll_ = {}));
var RevealLine_;
(function (RevealLine_) {
    const isRevealLineArgs = function (arg) {
        if (!isObject(arg)) {
            return false;
        }
        const reveaLineArg = arg;
        if (!isNumber(reveaLineArg.lineNumber) && !isString(reveaLineArg.lineNumber)) {
            return false;
        }
        if (!isUndefined(reveaLineArg.at) && !isString(reveaLineArg.at)) {
            return false;
        }
        return true;
    };
    RevealLine_.description = {
        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']
                        }
                    }
                }
            }
        ]
    };
    /**
     * Values for reveal line 'at' argument
     */
    RevealLine_.RawAtArgument = {
        Top: 'top',
        Center: 'center',
        Bottom: 'bottom'
    };
})(RevealLine_ || (RevealLine_ = {}));
class EditorOrNativeTextInputCommand {
    constructor(target) {
        // 1. handle case when focus is in editor.
        target.addImplementation(10000, 'code-editor', (accessor, args) => {
            // Only if editor text focus (i.e. not if editor has widget focus).
            const focusedEditor = accessor.get(ICodeEditorService).getFocusedCodeEditor();
            if (focusedEditor && focusedEditor.hasTextFocus()) {
                return this._runEditorCommand(accessor, focusedEditor, args);
            }
            return false;
        });
        // 2. handle case when focus is in some other `input` / `textarea`.
        target.addImplementation(1000, 'generic-dom-input-textarea', (accessor, args) => {
            // Only if focused on an element that allows for entering text
            const activeElement = document.activeElement;
            if (activeElement && ['input', 'textarea'].indexOf(activeElement.tagName.toLowerCase()) >= 0) {
                this.runDOMCommand();
                return true;
            }
            return false;
        });
        // 3. (default) handle case when focus is somewhere else.
        target.addImplementation(0, 'generic-dom', (accessor, args) => {
            // Redirecting to active editor
            const activeEditor = accessor.get(ICodeEditorService).getActiveCodeEditor();
            if (activeEditor) {
                activeEditor.focus();
                return this._runEditorCommand(accessor, activeEditor, args);
            }
            return false;
        });
    }
    _runEditorCommand(accessor, editor, args) {
        const result = this.runEditorCommand(accessor, editor, args);
        if (result) {
            return result;
        }
        return true;
    }
}
var CoreNavigationCommands;
(function (CoreNavigationCommands) {
    class BaseMoveToCommand extends CoreEditorCommand {
        constructor(opts) {
            super(opts);
            this._minimalReveal = opts.minimalReveal;
            this._inSelectionMode = opts.inSelectionMode;
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            const cursorStateChanged = viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                CursorMoveCommands.moveTo(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition)
            ]);
            if (cursorStateChanged) {
                viewModel.revealPrimaryCursor(args.source, true, this._minimalReveal);
            }
        }
    }
    CoreNavigationCommands.MoveTo = registerEditorCommand(new BaseMoveToCommand({
        id: '_moveTo',
        minimalReveal: true,
        inSelectionMode: false,
        precondition: undefined
    }));
    CoreNavigationCommands.MoveToSelect = registerEditorCommand(new BaseMoveToCommand({
        id: '_moveToSelect',
        minimalReveal: false,
        inSelectionMode: true,
        precondition: undefined
    }));
    class ColumnSelectCommand extends CoreEditorCommand {
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            const result = this._getColumnSelectResult(viewModel, viewModel.getPrimaryCursorState(), viewModel.getCursorColumnSelectData(), args);
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, result.viewStates.map((viewState) => CursorState.fromViewState(viewState)));
            viewModel.setCursorColumnSelectData({
                isReal: true,
                fromViewLineNumber: result.fromLineNumber,
                fromViewVisualColumn: result.fromVisualColumn,
                toViewLineNumber: result.toLineNumber,
                toViewVisualColumn: result.toVisualColumn
            });
            if (result.reversed) {
                viewModel.revealTopMostCursor(args.source);
            }
            else {
                viewModel.revealBottomMostCursor(args.source);
            }
        }
    }
    CoreNavigationCommands.ColumnSelect = registerEditorCommand(new class extends ColumnSelectCommand {
        constructor() {
            super({
                id: 'columnSelect',
                precondition: undefined
            });
        }
        _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
            // validate `args`
            const validatedPosition = viewModel.model.validatePosition(args.position);
            const validatedViewPosition = viewModel.coordinatesConverter.validateViewPosition(new Position(args.viewPosition.lineNumber, args.viewPosition.column), validatedPosition);
            const fromViewLineNumber = args.doColumnSelect ? prevColumnSelectData.fromViewLineNumber : validatedViewPosition.lineNumber;
            const fromViewVisualColumn = args.doColumnSelect ? prevColumnSelectData.fromViewVisualColumn : args.mouseColumn - 1;
            return ColumnSelection.columnSelect(viewModel.cursorConfig, viewModel, fromViewLineNumber, fromViewVisualColumn, validatedViewPosition.lineNumber, args.mouseColumn - 1);
        }
    });
    CoreNavigationCommands.CursorColumnSelectLeft = registerEditorCommand(new class extends ColumnSelectCommand {
        constructor() {
            super({
                id: 'cursorColumnSelectLeft',
                precondition: undefined,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 15 /* KeyCode.LeftArrow */,
                    linux: { primary: 0 }
                }
            });
        }
        _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
            return ColumnSelection.columnSelectLeft(viewModel.cursorConfig, viewModel, prevColumnSelectData);
        }
    });
    CoreNavigationCommands.CursorColumnSelectRight = registerEditorCommand(new class extends ColumnSelectCommand {
        constructor() {
            super({
                id: 'cursorColumnSelectRight',
                precondition: undefined,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 17 /* KeyCode.RightArrow */,
                    linux: { primary: 0 }
                }
            });
        }
        _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
            return ColumnSelection.columnSelectRight(viewModel.cursorConfig, viewModel, prevColumnSelectData);
        }
    });
    class ColumnSelectUpCommand extends ColumnSelectCommand {
        constructor(opts) {
            super(opts);
            this._isPaged = opts.isPaged;
        }
        _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
            return ColumnSelection.columnSelectUp(viewModel.cursorConfig, viewModel, prevColumnSelectData, this._isPaged);
        }
    }
    CoreNavigationCommands.CursorColumnSelectUp = registerEditorCommand(new ColumnSelectUpCommand({
        isPaged: false,
        id: 'cursorColumnSelectUp',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */,
            linux: { primary: 0 }
        }
    }));
    CoreNavigationCommands.CursorColumnSelectPageUp = registerEditorCommand(new ColumnSelectUpCommand({
        isPaged: true,
        id: 'cursorColumnSelectPageUp',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 11 /* KeyCode.PageUp */,
            linux: { primary: 0 }
        }
    }));
    class ColumnSelectDownCommand extends ColumnSelectCommand {
        constructor(opts) {
            super(opts);
            this._isPaged = opts.isPaged;
        }
        _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
            return ColumnSelection.columnSelectDown(viewModel.cursorConfig, viewModel, prevColumnSelectData, this._isPaged);
        }
    }
    CoreNavigationCommands.CursorColumnSelectDown = registerEditorCommand(new ColumnSelectDownCommand({
        isPaged: false,
        id: 'cursorColumnSelectDown',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */,
            linux: { primary: 0 }
        }
    }));
    CoreNavigationCommands.CursorColumnSelectPageDown = registerEditorCommand(new ColumnSelectDownCommand({
        isPaged: true,
        id: 'cursorColumnSelectPageDown',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 12 /* KeyCode.PageDown */,
            linux: { primary: 0 }
        }
    }));
    class CursorMoveImpl extends CoreEditorCommand {
        constructor() {
            super({
                id: 'cursorMove',
                precondition: undefined,
                description: CursorMove.description
            });
        }
        runCoreEditorCommand(viewModel, args) {
            const parsed = CursorMove.parse(args);
            if (!parsed) {
                // illegal arguments
                return;
            }
            this._runCursorMove(viewModel, args.source, parsed);
        }
        _runCursorMove(viewModel, source, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(source, 3 /* CursorChangeReason.Explicit */, CursorMoveImpl._move(viewModel, viewModel.getCursorStates(), args));
            viewModel.revealPrimaryCursor(source, true);
        }
        static _move(viewModel, cursors, args) {
            const inSelectionMode = args.select;
            const value = args.value;
            switch (args.direction) {
                case 0 /* CursorMove_.Direction.Left */:
                case 1 /* CursorMove_.Direction.Right */:
                case 2 /* CursorMove_.Direction.Up */:
                case 3 /* CursorMove_.Direction.Down */:
                case 4 /* CursorMove_.Direction.PrevBlankLine */:
                case 5 /* CursorMove_.Direction.NextBlankLine */:
                case 6 /* CursorMove_.Direction.WrappedLineStart */:
                case 7 /* CursorMove_.Direction.WrappedLineFirstNonWhitespaceCharacter */:
                case 8 /* CursorMove_.Direction.WrappedLineColumnCenter */:
                case 9 /* CursorMove_.Direction.WrappedLineEnd */:
                case 10 /* CursorMove_.Direction.WrappedLineLastNonWhitespaceCharacter */:
                    return CursorMoveCommands.simpleMove(viewModel, cursors, args.direction, inSelectionMode, value, args.unit);
                case 11 /* CursorMove_.Direction.ViewPortTop */:
                case 13 /* CursorMove_.Direction.ViewPortBottom */:
                case 12 /* CursorMove_.Direction.ViewPortCenter */:
                case 14 /* CursorMove_.Direction.ViewPortIfOutside */:
                    return CursorMoveCommands.viewportMove(viewModel, cursors, args.direction, inSelectionMode, value);
                default:
                    return null;
            }
        }
    }
    CoreNavigationCommands.CursorMoveImpl = CursorMoveImpl;
    CoreNavigationCommands.CursorMove = registerEditorCommand(new CursorMoveImpl());
    class CursorMoveBasedCommand extends CoreEditorCommand {
        constructor(opts) {
            super(opts);
            this._staticArgs = opts.args;
        }
        runCoreEditorCommand(viewModel, dynamicArgs) {
            let args = this._staticArgs;
            if (this._staticArgs.value === -1 /* Constants.PAGE_SIZE_MARKER */) {
                // -1 is a marker for page size
                args = {
                    direction: this._staticArgs.direction,
                    unit: this._staticArgs.unit,
                    select: this._staticArgs.select,
                    value: dynamicArgs.pageSize || viewModel.cursorConfig.pageSize
                };
            }
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(dynamicArgs.source, 3 /* CursorChangeReason.Explicit */, CursorMoveCommands.simpleMove(viewModel, viewModel.getCursorStates(), args.direction, args.select, args.value, args.unit));
            viewModel.revealPrimaryCursor(dynamicArgs.source, true);
        }
    }
    CoreNavigationCommands.CursorLeft = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 0 /* CursorMove_.Direction.Left */,
            unit: 0 /* CursorMove_.Unit.None */,
            select: false,
            value: 1
        },
        id: 'cursorLeft',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 15 /* KeyCode.LeftArrow */,
            mac: { primary: 15 /* KeyCode.LeftArrow */, secondary: [256 /* KeyMod.WinCtrl */ | 32 /* KeyCode.KeyB */] }
        }
    }));
    CoreNavigationCommands.CursorLeftSelect = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 0 /* CursorMove_.Direction.Left */,
            unit: 0 /* CursorMove_.Unit.None */,
            select: true,
            value: 1
        },
        id: 'cursorLeftSelect',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */
        }
    }));
    CoreNavigationCommands.CursorRight = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 1 /* CursorMove_.Direction.Right */,
            unit: 0 /* CursorMove_.Unit.None */,
            select: false,
            value: 1
        },
        id: 'cursorRight',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 17 /* KeyCode.RightArrow */,
            mac: { primary: 17 /* KeyCode.RightArrow */, secondary: [256 /* KeyMod.WinCtrl */ | 36 /* KeyCode.KeyF */] }
        }
    }));
    CoreNavigationCommands.CursorRightSelect = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 1 /* CursorMove_.Direction.Right */,
            unit: 0 /* CursorMove_.Unit.None */,
            select: true,
            value: 1
        },
        id: 'cursorRightSelect',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */
        }
    }));
    CoreNavigationCommands.CursorUp = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 2 /* CursorMove_.Direction.Up */,
            unit: 2 /* CursorMove_.Unit.WrappedLine */,
            select: false,
            value: 1
        },
        id: 'cursorUp',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 16 /* KeyCode.UpArrow */,
            mac: { primary: 16 /* KeyCode.UpArrow */, secondary: [256 /* KeyMod.WinCtrl */ | 46 /* KeyCode.KeyP */] }
        }
    }));
    CoreNavigationCommands.CursorUpSelect = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 2 /* CursorMove_.Direction.Up */,
            unit: 2 /* CursorMove_.Unit.WrappedLine */,
            select: true,
            value: 1
        },
        id: 'cursorUpSelect',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */,
            secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */],
            mac: { primary: 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */ },
            linux: { primary: 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */ }
        }
    }));
    CoreNavigationCommands.CursorPageUp = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 2 /* CursorMove_.Direction.Up */,
            unit: 2 /* CursorMove_.Unit.WrappedLine */,
            select: false,
            value: -1 /* Constants.PAGE_SIZE_MARKER */
        },
        id: 'cursorPageUp',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 11 /* KeyCode.PageUp */
        }
    }));
    CoreNavigationCommands.CursorPageUpSelect = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 2 /* CursorMove_.Direction.Up */,
            unit: 2 /* CursorMove_.Unit.WrappedLine */,
            select: true,
            value: -1 /* Constants.PAGE_SIZE_MARKER */
        },
        id: 'cursorPageUpSelect',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 1024 /* KeyMod.Shift */ | 11 /* KeyCode.PageUp */
        }
    }));
    CoreNavigationCommands.CursorDown = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 3 /* CursorMove_.Direction.Down */,
            unit: 2 /* CursorMove_.Unit.WrappedLine */,
            select: false,
            value: 1
        },
        id: 'cursorDown',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 18 /* KeyCode.DownArrow */,
            mac: { primary: 18 /* KeyCode.DownArrow */, secondary: [256 /* KeyMod.WinCtrl */ | 44 /* KeyCode.KeyN */] }
        }
    }));
    CoreNavigationCommands.CursorDownSelect = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 3 /* CursorMove_.Direction.Down */,
            unit: 2 /* CursorMove_.Unit.WrappedLine */,
            select: true,
            value: 1
        },
        id: 'cursorDownSelect',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */,
            secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */],
            mac: { primary: 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */ },
            linux: { primary: 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */ }
        }
    }));
    CoreNavigationCommands.CursorPageDown = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 3 /* CursorMove_.Direction.Down */,
            unit: 2 /* CursorMove_.Unit.WrappedLine */,
            select: false,
            value: -1 /* Constants.PAGE_SIZE_MARKER */
        },
        id: 'cursorPageDown',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 12 /* KeyCode.PageDown */
        }
    }));
    CoreNavigationCommands.CursorPageDownSelect = registerEditorCommand(new CursorMoveBasedCommand({
        args: {
            direction: 3 /* CursorMove_.Direction.Down */,
            unit: 2 /* CursorMove_.Unit.WrappedLine */,
            select: true,
            value: -1 /* Constants.PAGE_SIZE_MARKER */
        },
        id: 'cursorPageDownSelect',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 1024 /* KeyMod.Shift */ | 12 /* KeyCode.PageDown */
        }
    }));
    CoreNavigationCommands.CreateCursor = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'createCursor',
                precondition: undefined
            });
        }
        runCoreEditorCommand(viewModel, args) {
            let newState;
            if (args.wholeLine) {
                newState = CursorMoveCommands.line(viewModel, viewModel.getPrimaryCursorState(), false, args.position, args.viewPosition);
            }
            else {
                newState = CursorMoveCommands.moveTo(viewModel, viewModel.getPrimaryCursorState(), false, args.position, args.viewPosition);
            }
            const states = viewModel.getCursorStates();
            // Check if we should remove a cursor (sort of like a toggle)
            if (states.length > 1) {
                const newModelPosition = (newState.modelState ? newState.modelState.position : null);
                const newViewPosition = (newState.viewState ? newState.viewState.position : null);
                for (let i = 0, len = states.length; i < len; i++) {
                    const state = states[i];
                    if (newModelPosition && !state.modelState.selection.containsPosition(newModelPosition)) {
                        continue;
                    }
                    if (newViewPosition && !state.viewState.selection.containsPosition(newViewPosition)) {
                        continue;
                    }
                    // => Remove the cursor
                    states.splice(i, 1);
                    viewModel.model.pushStackElement();
                    viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, states);
                    return;
                }
            }
            // => Add the new cursor
            states.push(newState);
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, states);
        }
    });
    CoreNavigationCommands.LastCursorMoveToSelect = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: '_lastCursorMoveToSelect',
                precondition: undefined
            });
        }
        runCoreEditorCommand(viewModel, args) {
            const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
            const states = viewModel.getCursorStates();
            const newStates = states.slice(0);
            newStates[lastAddedCursorIndex] = CursorMoveCommands.moveTo(viewModel, states[lastAddedCursorIndex], true, args.position, args.viewPosition);
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, newStates);
        }
    });
    class HomeCommand extends CoreEditorCommand {
        constructor(opts) {
            super(opts);
            this._inSelectionMode = opts.inSelectionMode;
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, CursorMoveCommands.moveToBeginningOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
            viewModel.revealPrimaryCursor(args.source, true);
        }
    }
    CoreNavigationCommands.CursorHome = registerEditorCommand(new HomeCommand({
        inSelectionMode: false,
        id: 'cursorHome',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 14 /* KeyCode.Home */,
            mac: { primary: 14 /* KeyCode.Home */, secondary: [2048 /* KeyMod.CtrlCmd */ | 15 /* KeyCode.LeftArrow */] }
        }
    }));
    CoreNavigationCommands.CursorHomeSelect = registerEditorCommand(new HomeCommand({
        inSelectionMode: true,
        id: 'cursorHomeSelect',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 1024 /* KeyMod.Shift */ | 14 /* KeyCode.Home */,
            mac: { primary: 1024 /* KeyMod.Shift */ | 14 /* KeyCode.Home */, secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */] }
        }
    }));
    class LineStartCommand extends CoreEditorCommand {
        constructor(opts) {
            super(opts);
            this._inSelectionMode = opts.inSelectionMode;
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, this._exec(viewModel.getCursorStates()));
            viewModel.revealPrimaryCursor(args.source, true);
        }
        _exec(cursors) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                const lineNumber = cursor.modelState.position.lineNumber;
                result[i] = CursorState.fromModelState(cursor.modelState.move(this._inSelectionMode, lineNumber, 1, 0));
            }
            return result;
        }
    }
    CoreNavigationCommands.CursorLineStart = registerEditorCommand(new LineStartCommand({
        inSelectionMode: false,
        id: 'cursorLineStart',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 0,
            mac: { primary: 256 /* KeyMod.WinCtrl */ | 31 /* KeyCode.KeyA */ }
        }
    }));
    CoreNavigationCommands.CursorLineStartSelect = registerEditorCommand(new LineStartCommand({
        inSelectionMode: true,
        id: 'cursorLineStartSelect',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 0,
            mac: { primary: 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 31 /* KeyCode.KeyA */ }
        }
    }));
    class EndCommand extends CoreEditorCommand {
        constructor(opts) {
            super(opts);
            this._inSelectionMode = opts.inSelectionMode;
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, CursorMoveCommands.moveToEndOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode, args.sticky || false));
            viewModel.revealPrimaryCursor(args.source, true);
        }
    }
    CoreNavigationCommands.CursorEnd = registerEditorCommand(new EndCommand({
        inSelectionMode: false,
        id: 'cursorEnd',
        precondition: undefined,
        kbOpts: {
            args: { sticky: false },
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 13 /* KeyCode.End */,
            mac: { primary: 13 /* KeyCode.End */, secondary: [2048 /* KeyMod.CtrlCmd */ | 17 /* KeyCode.RightArrow */] }
        },
        description: {
            description: `Go to End`,
            args: [{
                    name: 'args',
                    schema: {
                        type: 'object',
                        properties: {
                            'sticky': {
                                description: localize('stickydesc', "Stick to the end even when going to longer lines"),
                                type: 'boolean',
                                default: false
                            }
                        }
                    }
                }]
        }
    }));
    CoreNavigationCommands.CursorEndSelect = registerEditorCommand(new EndCommand({
        inSelectionMode: true,
        id: 'cursorEndSelect',
        precondition: undefined,
        kbOpts: {
            args: { sticky: false },
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 1024 /* KeyMod.Shift */ | 13 /* KeyCode.End */,
            mac: { primary: 1024 /* KeyMod.Shift */ | 13 /* KeyCode.End */, secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */] }
        },
        description: {
            description: `Select to End`,
            args: [{
                    name: 'args',
                    schema: {
                        type: 'object',
                        properties: {
                            'sticky': {
                                description: localize('stickydesc', "Stick to the end even when going to longer lines"),
                                type: 'boolean',
                                default: false
                            }
                        }
                    }
                }]
        }
    }));
    class LineEndCommand extends CoreEditorCommand {
        constructor(opts) {
            super(opts);
            this._inSelectionMode = opts.inSelectionMode;
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, this._exec(viewModel, viewModel.getCursorStates()));
            viewModel.revealPrimaryCursor(args.source, true);
        }
        _exec(viewModel, cursors) {
            const result = [];
            for (let i = 0, len = cursors.length; i < len; i++) {
                const cursor = cursors[i];
                const lineNumber = cursor.modelState.position.lineNumber;
                const maxColumn = viewModel.model.getLineMaxColumn(lineNumber);
                result[i] = CursorState.fromModelState(cursor.modelState.move(this._inSelectionMode, lineNumber, maxColumn, 0));
            }
            return result;
        }
    }
    CoreNavigationCommands.CursorLineEnd = registerEditorCommand(new LineEndCommand({
        inSelectionMode: false,
        id: 'cursorLineEnd',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 0,
            mac: { primary: 256 /* KeyMod.WinCtrl */ | 35 /* KeyCode.KeyE */ }
        }
    }));
    CoreNavigationCommands.CursorLineEndSelect = registerEditorCommand(new LineEndCommand({
        inSelectionMode: true,
        id: 'cursorLineEndSelect',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 0,
            mac: { primary: 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 35 /* KeyCode.KeyE */ }
        }
    }));
    class TopCommand extends CoreEditorCommand {
        constructor(opts) {
            super(opts);
            this._inSelectionMode = opts.inSelectionMode;
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, CursorMoveCommands.moveToBeginningOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
            viewModel.revealPrimaryCursor(args.source, true);
        }
    }
    CoreNavigationCommands.CursorTop = registerEditorCommand(new TopCommand({
        inSelectionMode: false,
        id: 'cursorTop',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 14 /* KeyCode.Home */,
            mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */ }
        }
    }));
    CoreNavigationCommands.CursorTopSelect = registerEditorCommand(new TopCommand({
        inSelectionMode: true,
        id: 'cursorTopSelect',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 14 /* KeyCode.Home */,
            mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */ }
        }
    }));
    class BottomCommand extends CoreEditorCommand {
        constructor(opts) {
            super(opts);
            this._inSelectionMode = opts.inSelectionMode;
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, CursorMoveCommands.moveToEndOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
            viewModel.revealPrimaryCursor(args.source, true);
        }
    }
    CoreNavigationCommands.CursorBottom = registerEditorCommand(new BottomCommand({
        inSelectionMode: false,
        id: 'cursorBottom',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 13 /* KeyCode.End */,
            mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */ }
        }
    }));
    CoreNavigationCommands.CursorBottomSelect = registerEditorCommand(new BottomCommand({
        inSelectionMode: true,
        id: 'cursorBottomSelect',
        precondition: undefined,
        kbOpts: {
            weight: CORE_WEIGHT,
            kbExpr: EditorContextKeys.textInputFocus,
            primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 13 /* KeyCode.End */,
            mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */ }
        }
    }));
    class EditorScrollImpl extends CoreEditorCommand {
        constructor() {
            super({
                id: 'editorScroll',
                precondition: undefined,
                description: EditorScroll_.description
            });
        }
        runCoreEditorCommand(viewModel, args) {
            const parsed = EditorScroll_.parse(args);
            if (!parsed) {
                // illegal arguments
                return;
            }
            this._runEditorScroll(viewModel, args.source, parsed);
        }
        _runEditorScroll(viewModel, source, args) {
            const desiredScrollTop = this._computeDesiredScrollTop(viewModel, args);
            if (args.revealCursor) {
                // must ensure cursor is in new visible range
                const desiredVisibleViewRange = viewModel.getCompletelyVisibleViewRangeAtScrollTop(desiredScrollTop);
                viewModel.setCursorStates(source, 3 /* CursorChangeReason.Explicit */, [
                    CursorMoveCommands.findPositionInViewportIfOutside(viewModel, viewModel.getPrimaryCursorState(), desiredVisibleViewRange, args.select)
                ]);
            }
            viewModel.viewLayout.setScrollPosition({ scrollTop: desiredScrollTop }, 0 /* ScrollType.Smooth */);
        }
        _computeDesiredScrollTop(viewModel, args) {
            if (args.unit === 1 /* EditorScroll_.Unit.Line */) {
                // scrolling by model lines
                const visibleViewRange = viewModel.getCompletelyVisibleViewRange();
                const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
                let desiredTopModelLineNumber;
                if (args.direction === 1 /* EditorScroll_.Direction.Up */) {
                    // must go x model lines up
                    desiredTopModelLineNumber = Math.max(1, visibleModelRange.startLineNumber - args.value);
                }
                else {
                    // must go x model lines down
                    desiredTopModelLineNumber = Math.min(viewModel.model.getLineCount(), visibleModelRange.startLineNumber + args.value);
                }
                const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(new Position(desiredTopModelLineNumber, 1));
                return viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
            }
            if (args.unit === 5 /* EditorScroll_.Unit.Editor */) {
                let desiredTopModelLineNumber = 0;
                if (args.direction === 2 /* EditorScroll_.Direction.Down */) {
                    desiredTopModelLineNumber = viewModel.model.getLineCount() - viewModel.cursorConfig.pageSize;
                }
                return viewModel.viewLayout.getVerticalOffsetForLineNumber(desiredTopModelLineNumber);
            }
            let noOfLines;
            if (args.unit === 3 /* EditorScroll_.Unit.Page */) {
                noOfLines = viewModel.cursorConfig.pageSize * args.value;
            }
            else if (args.unit === 4 /* EditorScroll_.Unit.HalfPage */) {
                noOfLines = Math.round(viewModel.cursorConfig.pageSize / 2) * args.value;
            }
            else {
                noOfLines = args.value;
            }
            const deltaLines = (args.direction === 1 /* EditorScroll_.Direction.Up */ ? -1 : 1) * noOfLines;
            return viewModel.viewLayout.getCurrentScrollTop() + deltaLines * viewModel.cursorConfig.lineHeight;
        }
    }
    CoreNavigationCommands.EditorScrollImpl = EditorScrollImpl;
    CoreNavigationCommands.EditorScroll = registerEditorCommand(new EditorScrollImpl());
    CoreNavigationCommands.ScrollLineUp = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'scrollLineUp',
                precondition: undefined,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 11 /* KeyCode.PageUp */ }
                }
            });
        }
        runCoreEditorCommand(viewModel, args) {
            CoreNavigationCommands.EditorScroll._runEditorScroll(viewModel, args.source, {
                direction: 1 /* EditorScroll_.Direction.Up */,
                unit: 2 /* EditorScroll_.Unit.WrappedLine */,
                value: 1,
                revealCursor: false,
                select: false
            });
        }
    });
    CoreNavigationCommands.ScrollPageUp = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'scrollPageUp',
                precondition: undefined,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 11 /* KeyCode.PageUp */,
                    win: { primary: 512 /* KeyMod.Alt */ | 11 /* KeyCode.PageUp */ },
                    linux: { primary: 512 /* KeyMod.Alt */ | 11 /* KeyCode.PageUp */ }
                }
            });
        }
        runCoreEditorCommand(viewModel, args) {
            CoreNavigationCommands.EditorScroll._runEditorScroll(viewModel, args.source, {
                direction: 1 /* EditorScroll_.Direction.Up */,
                unit: 3 /* EditorScroll_.Unit.Page */,
                value: 1,
                revealCursor: false,
                select: false
            });
        }
    });
    CoreNavigationCommands.ScrollEditorTop = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'scrollEditorTop',
                precondition: undefined,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                }
            });
        }
        runCoreEditorCommand(viewModel, args) {
            CoreNavigationCommands.EditorScroll._runEditorScroll(viewModel, args.source, {
                direction: 1 /* EditorScroll_.Direction.Up */,
                unit: 5 /* EditorScroll_.Unit.Editor */,
                value: 1,
                revealCursor: false,
                select: false
            });
        }
    });
    CoreNavigationCommands.ScrollLineDown = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'scrollLineDown',
                precondition: undefined,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 12 /* KeyCode.PageDown */ }
                }
            });
        }
        runCoreEditorCommand(viewModel, args) {
            CoreNavigationCommands.EditorScroll._runEditorScroll(viewModel, args.source, {
                direction: 2 /* EditorScroll_.Direction.Down */,
                unit: 2 /* EditorScroll_.Unit.WrappedLine */,
                value: 1,
                revealCursor: false,
                select: false
            });
        }
    });
    CoreNavigationCommands.ScrollPageDown = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'scrollPageDown',
                precondition: undefined,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 12 /* KeyCode.PageDown */,
                    win: { primary: 512 /* KeyMod.Alt */ | 12 /* KeyCode.PageDown */ },
                    linux: { primary: 512 /* KeyMod.Alt */ | 12 /* KeyCode.PageDown */ }
                }
            });
        }
        runCoreEditorCommand(viewModel, args) {
            CoreNavigationCommands.EditorScroll._runEditorScroll(viewModel, args.source, {
                direction: 2 /* EditorScroll_.Direction.Down */,
                unit: 3 /* EditorScroll_.Unit.Page */,
                value: 1,
                revealCursor: false,
                select: false
            });
        }
    });
    CoreNavigationCommands.ScrollEditorBottom = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'scrollEditorBottom',
                precondition: undefined,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                }
            });
        }
        runCoreEditorCommand(viewModel, args) {
            CoreNavigationCommands.EditorScroll._runEditorScroll(viewModel, args.source, {
                direction: 2 /* EditorScroll_.Direction.Down */,
                unit: 5 /* EditorScroll_.Unit.Editor */,
                value: 1,
                revealCursor: false,
                select: false
            });
        }
    });
    class WordCommand extends CoreEditorCommand {
        constructor(opts) {
            super(opts);
            this._inSelectionMode = opts.inSelectionMode;
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                CursorMoveCommands.word(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position)
            ]);
            viewModel.revealPrimaryCursor(args.source, true);
        }
    }
    CoreNavigationCommands.WordSelect = registerEditorCommand(new WordCommand({
        inSelectionMode: false,
        id: '_wordSelect',
        precondition: undefined
    }));
    CoreNavigationCommands.WordSelectDrag = registerEditorCommand(new WordCommand({
        inSelectionMode: true,
        id: '_wordSelectDrag',
        precondition: undefined
    }));
    CoreNavigationCommands.LastCursorWordSelect = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'lastCursorWordSelect',
                precondition: undefined
            });
        }
        runCoreEditorCommand(viewModel, args) {
            const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
            const states = viewModel.getCursorStates();
            const newStates = states.slice(0);
            const lastAddedState = states[lastAddedCursorIndex];
            newStates[lastAddedCursorIndex] = CursorMoveCommands.word(viewModel, lastAddedState, lastAddedState.modelState.hasSelection(), args.position);
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, newStates);
        }
    });
    class LineCommand extends CoreEditorCommand {
        constructor(opts) {
            super(opts);
            this._inSelectionMode = opts.inSelectionMode;
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                CursorMoveCommands.line(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition)
            ]);
            viewModel.revealPrimaryCursor(args.source, false);
        }
    }
    CoreNavigationCommands.LineSelect = registerEditorCommand(new LineCommand({
        inSelectionMode: false,
        id: '_lineSelect',
        precondition: undefined
    }));
    CoreNavigationCommands.LineSelectDrag = registerEditorCommand(new LineCommand({
        inSelectionMode: true,
        id: '_lineSelectDrag',
        precondition: undefined
    }));
    class LastCursorLineCommand extends CoreEditorCommand {
        constructor(opts) {
            super(opts);
            this._inSelectionMode = opts.inSelectionMode;
        }
        runCoreEditorCommand(viewModel, args) {
            const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
            const states = viewModel.getCursorStates();
            const newStates = states.slice(0);
            newStates[lastAddedCursorIndex] = CursorMoveCommands.line(viewModel, states[lastAddedCursorIndex], this._inSelectionMode, args.position, args.viewPosition);
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, newStates);
        }
    }
    CoreNavigationCommands.LastCursorLineSelect = registerEditorCommand(new LastCursorLineCommand({
        inSelectionMode: false,
        id: 'lastCursorLineSelect',
        precondition: undefined
    }));
    CoreNavigationCommands.LastCursorLineSelectDrag = registerEditorCommand(new LastCursorLineCommand({
        inSelectionMode: true,
        id: 'lastCursorLineSelectDrag',
        precondition: undefined
    }));
    CoreNavigationCommands.CancelSelection = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'cancelSelection',
                precondition: EditorContextKeys.hasNonEmptySelection,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                    primary: 9 /* KeyCode.Escape */,
                    secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
                }
            });
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                CursorMoveCommands.cancelSelection(viewModel, viewModel.getPrimaryCursorState())
            ]);
            viewModel.revealPrimaryCursor(args.source, true);
        }
    });
    CoreNavigationCommands.RemoveSecondaryCursors = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'removeSecondaryCursors',
                precondition: EditorContextKeys.hasMultipleSelections,
                kbOpts: {
                    weight: CORE_WEIGHT + 1,
                    kbExpr: EditorContextKeys.textInputFocus,
                    primary: 9 /* KeyCode.Escape */,
                    secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
                }
            });
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                viewModel.getPrimaryCursorState()
            ]);
            viewModel.revealPrimaryCursor(args.source, true);
            aria_status(localize('removedCursor', "Removed secondary cursors"));
        }
    });
    CoreNavigationCommands.RevealLine = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'revealLine',
                precondition: undefined,
                description: RevealLine_.description
            });
        }
        runCoreEditorCommand(viewModel, args) {
            const revealLineArg = args;
            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 Range(lineNumber, 1, lineNumber, viewModel.model.getLineMaxColumn(lineNumber));
            let revealAt = 0 /* VerticalRevealType.Simple */;
            if (revealLineArg.at) {
                switch (revealLineArg.at) {
                    case RevealLine_.RawAtArgument.Top:
                        revealAt = 3 /* VerticalRevealType.Top */;
                        break;
                    case RevealLine_.RawAtArgument.Center:
                        revealAt = 1 /* VerticalRevealType.Center */;
                        break;
                    case RevealLine_.RawAtArgument.Bottom:
                        revealAt = 4 /* VerticalRevealType.Bottom */;
                        break;
                    default:
                        break;
                }
            }
            const viewRange = viewModel.coordinatesConverter.convertModelRangeToViewRange(range);
            viewModel.revealRange(args.source, false, viewRange, revealAt, 0 /* ScrollType.Smooth */);
        }
    });
    CoreNavigationCommands.SelectAll = new class extends EditorOrNativeTextInputCommand {
        constructor() {
            super(SelectAllCommand);
        }
        runDOMCommand() {
            if (browser_isFirefox) {
                document.activeElement.focus();
                document.activeElement.select();
            }
            document.execCommand('selectAll');
        }
        runEditorCommand(accessor, editor, args) {
            const viewModel = editor._getViewModel();
            if (!viewModel) {
                // the editor has no view => has no cursors
                return;
            }
            this.runCoreEditorCommand(viewModel, args);
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates('keyboard', 3 /* CursorChangeReason.Explicit */, [
                CursorMoveCommands.selectAll(viewModel, viewModel.getPrimaryCursorState())
            ]);
        }
    }();
    CoreNavigationCommands.SetSelection = registerEditorCommand(new class extends CoreEditorCommand {
        constructor() {
            super({
                id: 'setSelection',
                precondition: undefined
            });
        }
        runCoreEditorCommand(viewModel, args) {
            viewModel.model.pushStackElement();
            viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, [
                CursorState.fromModelSelection(args.selection)
            ]);
        }
    });
})(CoreNavigationCommands || (CoreNavigationCommands = {}));
const columnSelectionCondition = ContextKeyExpr.and(EditorContextKeys.textInputFocus, EditorContextKeys.columnSelection);
function registerColumnSelection(id, keybinding) {
    KeybindingsRegistry.registerKeybindingRule({
        id: id,
        primary: keybinding,
        when: columnSelectionCondition,
        weight: CORE_WEIGHT + 1
    });
}
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectLeft.id, 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectRight.id, 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectUp.id, 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectPageUp.id, 1024 /* KeyMod.Shift */ | 11 /* KeyCode.PageUp */);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectDown.id, 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */);
registerColumnSelection(CoreNavigationCommands.CursorColumnSelectPageDown.id, 1024 /* KeyMod.Shift */ | 12 /* KeyCode.PageDown */);
function coreCommands_registerCommand(command) {
    command.register();
    return command;
}
var CoreEditingCommands;
(function (CoreEditingCommands) {
    class CoreEditingCommand extends EditorCommand {
        runEditorCommand(accessor, editor, args) {
            const viewModel = editor._getViewModel();
            if (!viewModel) {
                // the editor has no view => has no cursors
                return;
            }
            this.runCoreEditingCommand(editor, viewModel, args || {});
        }
    }
    CoreEditingCommands.CoreEditingCommand = CoreEditingCommand;
    CoreEditingCommands.LineBreakInsert = registerEditorCommand(new class extends CoreEditingCommand {
        constructor() {
            super({
                id: 'lineBreakInsert',
                precondition: EditorContextKeys.writable,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                    primary: 0,
                    mac: { primary: 256 /* KeyMod.WinCtrl */ | 45 /* KeyCode.KeyO */ }
                }
            });
        }
        runCoreEditingCommand(editor, viewModel, args) {
            editor.pushUndoStop();
            editor.executeCommands(this.id, TypeOperations.lineBreakInsert(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map(s => s.modelState.selection)));
        }
    });
    CoreEditingCommands.Outdent = registerEditorCommand(new class extends CoreEditingCommand {
        constructor() {
            super({
                id: 'outdent',
                precondition: EditorContextKeys.writable,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus),
                    primary: 1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */
                }
            });
        }
        runCoreEditingCommand(editor, viewModel, args) {
            editor.pushUndoStop();
            editor.executeCommands(this.id, TypeOperations.outdent(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map(s => s.modelState.selection)));
            editor.pushUndoStop();
        }
    });
    CoreEditingCommands.Tab = registerEditorCommand(new class extends CoreEditingCommand {
        constructor() {
            super({
                id: 'tab',
                precondition: EditorContextKeys.writable,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus),
                    primary: 2 /* KeyCode.Tab */
                }
            });
        }
        runCoreEditingCommand(editor, viewModel, args) {
            editor.pushUndoStop();
            editor.executeCommands(this.id, TypeOperations.tab(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map(s => s.modelState.selection)));
            editor.pushUndoStop();
        }
    });
    CoreEditingCommands.DeleteLeft = registerEditorCommand(new class extends CoreEditingCommand {
        constructor() {
            super({
                id: 'deleteLeft',
                precondition: undefined,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                    primary: 1 /* KeyCode.Backspace */,
                    secondary: [1024 /* KeyMod.Shift */ | 1 /* KeyCode.Backspace */],
                    mac: { primary: 1 /* KeyCode.Backspace */, secondary: [1024 /* KeyMod.Shift */ | 1 /* KeyCode.Backspace */, 256 /* KeyMod.WinCtrl */ | 38 /* KeyCode.KeyH */, 256 /* KeyMod.WinCtrl */ | 1 /* KeyCode.Backspace */] }
                }
            });
        }
        runCoreEditingCommand(editor, viewModel, args) {
            const [shouldPushStackElementBefore, commands] = DeleteOperations.deleteLeft(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map(s => s.modelState.selection), viewModel.getCursorAutoClosedCharacters());
            if (shouldPushStackElementBefore) {
                editor.pushUndoStop();
            }
            editor.executeCommands(this.id, commands);
            viewModel.setPrevEditOperationType(2 /* EditOperationType.DeletingLeft */);
        }
    });
    CoreEditingCommands.DeleteRight = registerEditorCommand(new class extends CoreEditingCommand {
        constructor() {
            super({
                id: 'deleteRight',
                precondition: undefined,
                kbOpts: {
                    weight: CORE_WEIGHT,
                    kbExpr: EditorContextKeys.textInputFocus,
                    primary: 20 /* KeyCode.Delete */,
                    mac: { primary: 20 /* KeyCode.Delete */, secondary: [256 /* KeyMod.WinCtrl */ | 34 /* KeyCode.KeyD */, 256 /* KeyMod.WinCtrl */ | 20 /* KeyCode.Delete */] }
                }
            });
        }
        runCoreEditingCommand(editor, viewModel, args) {
            const [shouldPushStackElementBefore, commands] = DeleteOperations.deleteRight(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map(s => s.modelState.selection));
            if (shouldPushStackElementBefore) {
                editor.pushUndoStop();
            }
            editor.executeCommands(this.id, commands);
            viewModel.setPrevEditOperationType(3 /* EditOperationType.DeletingRight */);
        }
    });
    CoreEditingCommands.Undo = new class extends EditorOrNativeTextInputCommand {
        constructor() {
            super(UndoCommand);
        }
        runDOMCommand() {
            document.execCommand('undo');
        }
        runEditorCommand(accessor, editor, args) {
            if (!editor.hasModel() || editor.getOption(83 /* EditorOption.readOnly */) === true) {
                return;
            }
            return editor.getModel().undo();
        }
    }();
    CoreEditingCommands.Redo = new class extends EditorOrNativeTextInputCommand {
        constructor() {
            super(RedoCommand);
        }
        runDOMCommand() {
            document.execCommand('redo');
        }
        runEditorCommand(accessor, editor, args) {
            if (!editor.hasModel() || editor.getOption(83 /* EditorOption.readOnly */) === true) {
                return;
            }
            return editor.getModel().redo();
        }
    }();
})(CoreEditingCommands || (CoreEditingCommands = {}));
/**
 * A command that will invoke a command on the focused editor.
 */
class EditorHandlerCommand extends Command {
    constructor(id, handlerId, description) {
        super({
            id: id,
            precondition: undefined,
            description: description
        });
        this._handlerId = handlerId;
    }
    runCommand(accessor, args) {
        const editor = accessor.get(ICodeEditorService).getFocusedCodeEditor();
        if (!editor) {
            return;
        }
        editor.trigger('keyboard', this._handlerId, args);
    }
}
function registerOverwritableCommand(handlerId, description) {
    coreCommands_registerCommand(new EditorHandlerCommand('default:' + handlerId, handlerId));
    coreCommands_registerCommand(new EditorHandlerCommand(handlerId, handlerId, description));
}
registerOverwritableCommand("type" /* Handler.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 */);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/caretOperations/browser/moveCaretCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class MoveCaretCommand {
    constructor(selection, isMovingLeft) {
        this._selection = selection;
        this._isMovingLeft = isMovingLeft;
    }
    getEditOperations(model, builder) {
        if (this._selection.startLineNumber !== this._selection.endLineNumber || this._selection.isEmpty()) {
            return;
        }
        const lineNumber = this._selection.startLineNumber;
        const startColumn = this._selection.startColumn;
        const endColumn = this._selection.endColumn;
        if (this._isMovingLeft && startColumn === 1) {
            return;
        }
        if (!this._isMovingLeft && endColumn === model.getLineMaxColumn(lineNumber)) {
            return;
        }
        if (this._isMovingLeft) {
            const rangeBefore = new Range(lineNumber, startColumn - 1, lineNumber, startColumn);
            const charBefore = model.getValueInRange(rangeBefore);
            builder.addEditOperation(rangeBefore, null);
            builder.addEditOperation(new Range(lineNumber, endColumn, lineNumber, endColumn), charBefore);
        }
        else {
            const rangeAfter = new Range(lineNumber, endColumn, lineNumber, endColumn + 1);
            const charAfter = model.getValueInRange(rangeAfter);
            builder.addEditOperation(rangeAfter, null);
            builder.addEditOperation(new Range(lineNumber, startColumn, lineNumber, startColumn), charAfter);
        }
    }
    computeCursorState(model, helper) {
        if (this._isMovingLeft) {
            return new Selection(this._selection.startLineNumber, this._selection.startColumn - 1, this._selection.endLineNumber, this._selection.endColumn - 1);
        }
        else {
            return new Selection(this._selection.startLineNumber, this._selection.startColumn + 1, this._selection.endLineNumber, this._selection.endColumn + 1);
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/caretOperations/browser/caretOperations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class MoveCaretAction extends EditorAction {
    constructor(left, opts) {
        super(opts);
        this.left = left;
    }
    run(accessor, editor) {
        if (!editor.hasModel()) {
            return;
        }
        const commands = [];
        const selections = editor.getSelections();
        for (const selection of selections) {
            commands.push(new MoveCaretCommand(selection, this.left));
        }
        editor.pushUndoStop();
        editor.executeCommands(this.id, commands);
        editor.pushUndoStop();
    }
}
class MoveCaretLeftAction extends MoveCaretAction {
    constructor() {
        super(true, {
            id: 'editor.action.moveCarretLeftAction',
            label: localize('caret.moveLeft', "Move Selected Text Left"),
            alias: 'Move Selected Text Left',
            precondition: EditorContextKeys.writable
        });
    }
}
class MoveCaretRightAction extends MoveCaretAction {
    constructor() {
        super(false, {
            id: 'editor.action.moveCarretRightAction',
            label: localize('caret.moveRight', "Move Selected Text Right"),
            alias: 'Move Selected Text Right',
            precondition: EditorContextKeys.writable
        });
    }
}
registerEditorAction(MoveCaretLeftAction);
registerEditorAction(MoveCaretRightAction);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/caretOperations/browser/transpose.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class TransposeLettersAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.transposeLetters',
            label: localize('transposeLetters.label', "Transpose Letters"),
            alias: 'Transpose Letters',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 0,
                mac: {
                    primary: 256 /* KeyMod.WinCtrl */ | 50 /* KeyCode.KeyT */
                },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        if (!editor.hasModel()) {
            return;
        }
        const model = editor.getModel();
        const commands = [];
        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))) {
                // at beginning of file, nothing to do
                continue;
            }
            // handle special case: when at end of line, transpose left two chars
            // otherwise, transpose left and right chars
            const endPosition = (column === lastColumn) ?
                selection.getPosition() :
                MoveOperations.rightPosition(model, selection.getPosition().lineNumber, selection.getPosition().column);
            const middlePosition = MoveOperations.leftPosition(model, endPosition);
            const beginPosition = MoveOperations.leftPosition(model, middlePosition);
            const leftChar = model.getValueInRange(Range.fromPositions(beginPosition, middlePosition));
            const rightChar = model.getValueInRange(Range.fromPositions(middlePosition, endPosition));
            const replaceRange = Range.fromPositions(beginPosition, endPosition);
            commands.push(new ReplaceCommand(replaceRange, rightChar + leftChar));
        }
        if (commands.length > 0) {
            editor.pushUndoStop();
            editor.executeCommands(this.id, commands);
            editor.pushUndoStop();
        }
    }
}
registerEditorAction(TransposeLettersAction);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/controller/textAreaState.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



const _debugComposition = false;
class TextAreaState {
    constructor(value, selectionStart, selectionEnd, selectionStartPosition, selectionEndPosition) {
        this.value = value;
        this.selectionStart = selectionStart;
        this.selectionEnd = selectionEnd;
        this.selectionStartPosition = selectionStartPosition;
        this.selectionEndPosition = selectionEndPosition;
    }
    toString() {
        return `[ <${this.value}>, selectionStart: ${this.selectionStart}, selectionEnd: ${this.selectionEnd}]`;
    }
    static readFromTextArea(textArea) {
        return new TextAreaState(textArea.getValue(), textArea.getSelectionStart(), textArea.getSelectionEnd(), null, null);
    }
    collapseSelection() {
        return new TextAreaState(this.value, this.value.length, this.value.length, null, null);
    }
    writeToTextArea(reason, textArea, select) {
        if (_debugComposition) {
            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._finishDeduceEditorPosition(this.selectionStartPosition, str, -1);
        }
        if (offset >= this.selectionEnd) {
            const str = this.value.substring(this.selectionEnd, offset);
            return this._finishDeduceEditorPosition(this.selectionEndPosition, str, 1);
        }
        const str1 = this.value.substring(this.selectionStart, offset);
        if (str1.indexOf(String.fromCharCode(8230)) === -1) {
            return this._finishDeduceEditorPosition(this.selectionStartPosition, str1, 1);
        }
        const str2 = this.value.substring(offset, this.selectionEnd);
        return this._finishDeduceEditorPosition(this.selectionEndPosition, str2, -1);
    }
    _finishDeduceEditorPosition(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) {
            // This is the EMPTY state
            return {
                text: '',
                replacePrevCharCnt: 0,
                replaceNextCharCnt: 0,
                positionDelta: 0
            };
        }
        if (_debugComposition) {
            console.log('------------------------deduceInput');
            console.log(`PREVIOUS STATE: ${previousState.toString()}`);
            console.log(`CURRENT STATE: ${currentState.toString()}`);
        }
        const prefixLength = Math.min(strings_commonPrefixLength(previousState.value, currentState.value), previousState.selectionStart, currentState.selectionStart);
        const suffixLength = Math.min(strings_commonSuffixLength(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 (_debugComposition) {
            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) {
            // no current selection
            const replacePreviousCharacters = (previousState.selectionStart - prefixLength);
            if (_debugComposition) {
                console.log(`REMOVE PREVIOUS: ${replacePreviousCharacters} chars`);
            }
            return {
                text: currentValue,
                replacePrevCharCnt: replacePreviousCharacters,
                replaceNextCharCnt: 0,
                positionDelta: 0
            };
        }
        // there is a current selection => composition case
        const replacePreviousCharacters = previousSelectionEnd - previousSelectionStart;
        return {
            text: currentValue,
            replacePrevCharCnt: replacePreviousCharacters,
            replaceNextCharCnt: 0,
            positionDelta: 0
        };
    }
    static deduceAndroidCompositionInput(previousState, currentState) {
        if (!previousState) {
            // This is the EMPTY state
            return {
                text: '',
                replacePrevCharCnt: 0,
                replaceNextCharCnt: 0,
                positionDelta: 0
            };
        }
        if (_debugComposition) {
            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(strings_commonPrefixLength(previousState.value, currentState.value), previousState.selectionEnd);
        const suffixLength = Math.min(strings_commonSuffixLength(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 (_debugComposition) {
            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
        };
    }
}
TextAreaState.EMPTY = new TextAreaState('', 0, 0, null, null);
class PagedScreenReaderStrategy {
    static _getPageOfLine(lineNumber, linesPerPage) {
        return Math.floor((lineNumber - 1) / linesPerPage);
    }
    static _getRangeForPage(page, linesPerPage) {
        const offset = page * linesPerPage;
        const startLineNumber = offset + 1;
        const endLineNumber = offset + linesPerPage;
        return new Range(startLineNumber, 1, endLineNumber + 1, 1);
    }
    static fromEditorSelection(previousState, model, selection, linesPerPage, trimLongText) {
        const selectionStartPage = PagedScreenReaderStrategy._getPageOfLine(selection.startLineNumber, linesPerPage);
        const selectionStartPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionStartPage, linesPerPage);
        const selectionEndPage = PagedScreenReaderStrategy._getPageOfLine(selection.endLineNumber, linesPerPage);
        const selectionEndPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionEndPage, linesPerPage);
        const pretextRange = selectionStartPageRange.intersectRanges(new Range(1, 1, selection.startLineNumber, selection.startColumn));
        let pretext = model.getValueInRange(pretextRange, 1 /* EndOfLinePreference.LF */);
        const lastLine = model.getLineCount();
        const lastLineMaxColumn = model.getLineMaxColumn(lastLine);
        const posttextRange = selectionEndPageRange.intersectRanges(new Range(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn));
        let posttext = model.getValueInRange(posttextRange, 1 /* EndOfLinePreference.LF */);
        let text;
        if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) {
            // take full selection
            text = model.getValueInRange(selection, 1 /* EndOfLinePreference.LF */);
        }
        else {
            const selectionRange1 = selectionStartPageRange.intersectRanges(selection);
            const selectionRange2 = selectionEndPageRange.intersectRanges(selection);
            text = (model.getValueInRange(selectionRange1, 1 /* EndOfLinePreference.LF */)
                + String.fromCharCode(8230)
                + model.getValueInRange(selectionRange2, 1 /* EndOfLinePreference.LF */));
        }
        // Chromium handles very poorly text even of a few thousand chars
        // Cut text to avoid stalling the entire UI
        if (trimLongText) {
            const LIMIT_CHARS = 500;
            if (pretext.length > LIMIT_CHARS) {
                pretext = pretext.substring(pretext.length - LIMIT_CHARS, pretext.length);
            }
            if (posttext.length > LIMIT_CHARS) {
                posttext = posttext.substring(0, LIMIT_CHARS);
            }
            if (text.length > 2 * LIMIT_CHARS) {
                text = text.substring(0, LIMIT_CHARS) + String.fromCharCode(8230) + text.substring(text.length - LIMIT_CHARS, text.length);
            }
        }
        return new TextAreaState(pretext + text + posttext, pretext.length, pretext.length + text.length, new Position(selection.startLineNumber, selection.startColumn), new Position(selection.endLineNumber, selection.endColumn));
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/controller/textAreaInput.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/










var TextAreaSyntethicEvents;
(function (TextAreaSyntethicEvents) {
    TextAreaSyntethicEvents.Tap = '-monaco-textarea-synthetic-tap';
})(TextAreaSyntethicEvents || (TextAreaSyntethicEvents = {}));
const CopyOptions = {
    forceCopyWithSyntaxHighlighting: false
};
/**
 * Every time we write to the clipboard, we record a bit of extra metadata here.
 * Every time we read from the cipboard, if the text matches our last written text,
 * we can fetch the previous metadata.
 */
class InMemoryClipboardMetadataManager {
    constructor() {
        this._lastState = null;
    }
    set(lastCopiedValue, data) {
        this._lastState = { lastCopiedValue, data };
    }
    get(pastedText) {
        if (this._lastState && this._lastState.lastCopiedValue === pastedText) {
            // match!
            return this._lastState.data;
        }
        this._lastState = null;
        return null;
    }
}
InMemoryClipboardMetadataManager.INSTANCE = new InMemoryClipboardMetadataManager();
class CompositionContext {
    constructor() {
        this._lastTypeTextLength = 0;
    }
    handleCompositionUpdate(text) {
        text = text || '';
        const typeInput = {
            text: text,
            replacePrevCharCnt: this._lastTypeTextLength,
            replaceNextCharCnt: 0,
            positionDelta: 0
        };
        this._lastTypeTextLength = text.length;
        return typeInput;
    }
}
/**
 * Writes screen reader content to the textarea and is able to analyze its input events to generate:
 *  - onCut
 *  - onPaste
 *  - onType
 *
 * Composition events are generated for presentation purposes (composition input is reflected in onType).
 */
class TextAreaInput extends Disposable {
    constructor(_host, _textArea, _OS, _browser) {
        super();
        this._host = _host;
        this._textArea = _textArea;
        this._OS = _OS;
        this._browser = _browser;
        this._onFocus = this._register(new Emitter());
        this.onFocus = this._onFocus.event;
        this._onBlur = this._register(new Emitter());
        this.onBlur = this._onBlur.event;
        this._onKeyDown = this._register(new Emitter());
        this.onKeyDown = this._onKeyDown.event;
        this._onKeyUp = this._register(new Emitter());
        this.onKeyUp = this._onKeyUp.event;
        this._onCut = this._register(new Emitter());
        this.onCut = this._onCut.event;
        this._onPaste = this._register(new Emitter());
        this.onPaste = this._onPaste.event;
        this._onType = this._register(new Emitter());
        this.onType = this._onType.event;
        this._onCompositionStart = this._register(new Emitter());
        this.onCompositionStart = this._onCompositionStart.event;
        this._onCompositionUpdate = this._register(new Emitter());
        this.onCompositionUpdate = this._onCompositionUpdate.event;
        this._onCompositionEnd = this._register(new Emitter());
        this.onCompositionEnd = this._onCompositionEnd.event;
        this._onSelectionChangeRequest = this._register(new Emitter());
        this.onSelectionChangeRequest = this._onSelectionChangeRequest.event;
        this._asyncTriggerCut = this._register(new RunOnceScheduler(() => this._onCut.fire(), 0));
        this._asyncFocusGainWriteScreenReaderContent = this._register(new RunOnceScheduler(() => this.writeScreenReaderContent('asyncFocusGain'), 0));
        this._textAreaState = TextAreaState.EMPTY;
        this._selectionChangeListener = null;
        this.writeScreenReaderContent('ctor');
        this._hasFocus = false;
        this._currentComposition = null;
        let lastKeyDown = null;
        this._register(this._textArea.onKeyDown((_e) => {
            const e = new StandardKeyboardEvent(_e);
            if (e.keyCode === 109 /* KeyCode.KEY_IN_COMPOSITION */
                || (this._currentComposition && e.keyCode === 1 /* KeyCode.Backspace */)) {
                // Stop propagation for keyDown events if the IME is processing key input
                e.stopPropagation();
            }
            if (e.equals(9 /* KeyCode.Escape */)) {
                // Prevent default always for `Esc`, otherwise it will generate a keypress
                // See https://msdn.microsoft.com/en-us/library/ie/ms536939(v=vs.85).aspx
                e.preventDefault();
            }
            lastKeyDown = e;
            this._onKeyDown.fire(e);
        }));
        this._register(this._textArea.onKeyUp((_e) => {
            const e = new StandardKeyboardEvent(_e);
            this._onKeyUp.fire(e);
        }));
        this._register(this._textArea.onCompositionStart((e) => {
            if (_debugComposition) {
                console.log(`[compositionstart]`, e);
            }
            const currentComposition = new CompositionContext();
            if (this._currentComposition) {
                // simply reset the composition context
                this._currentComposition = currentComposition;
                return;
            }
            this._currentComposition = currentComposition;
            if (this._OS === 2 /* OperatingSystem.Macintosh */
                && lastKeyDown
                && lastKeyDown.equals(109 /* KeyCode.KEY_IN_COMPOSITION */)
                && this._textAreaState.selectionStart === this._textAreaState.selectionEnd
                && this._textAreaState.selectionStart > 0
                && this._textAreaState.value.substr(this._textAreaState.selectionStart - 1, 1) === e.data
                && (lastKeyDown.code === 'ArrowRight' || lastKeyDown.code === 'ArrowLeft')) {
                // Handling long press case on Chromium/Safari macOS + arrow key => pretend the character was selected
                if (_debugComposition) {
                    console.log(`[compositionstart] Handling long press case on macOS + arrow key`, e);
                }
                // Pretend the previous character was composed (in order to get it removed by subsequent compositionupdate events)
                currentComposition.handleCompositionUpdate('x');
                this._onCompositionStart.fire({ data: e.data });
                return;
            }
            if (this._browser.isAndroid) {
                // when tapping on the editor, Android enters composition mode to edit the current word
                // so we cannot clear the textarea on Android and we must pretend the current word was selected
                this._onCompositionStart.fire({ data: e.data });
                return;
            }
            this._onCompositionStart.fire({ data: e.data });
        }));
        this._register(this._textArea.onCompositionUpdate((e) => {
            if (_debugComposition) {
                console.log(`[compositionupdate]`, e);
            }
            const currentComposition = this._currentComposition;
            if (!currentComposition) {
                // should not be possible to receive a 'compositionupdate' without a 'compositionstart'
                return;
            }
            if (this._browser.isAndroid) {
                // On Android, the data sent with the composition update event is unusable.
                // For example, if the cursor is in the middle of a word like Mic|osoft
                // and Microsoft is chosen from the keyboard's suggestions, the e.data will contain "Microsoft".
                // This is not really usable because it doesn't tell us where the edit began and where it ended.
                const newState = TextAreaState.readFromTextArea(this._textArea);
                const typeInput = TextAreaState.deduceAndroidCompositionInput(this._textAreaState, newState);
                this._textAreaState = newState;
                this._onType.fire(typeInput);
                this._onCompositionUpdate.fire(e);
                return;
            }
            const typeInput = currentComposition.handleCompositionUpdate(e.data);
            this._textAreaState = TextAreaState.readFromTextArea(this._textArea);
            this._onType.fire(typeInput);
            this._onCompositionUpdate.fire(e);
        }));
        this._register(this._textArea.onCompositionEnd((e) => {
            if (_debugComposition) {
                console.log(`[compositionend]`, e);
            }
            const currentComposition = this._currentComposition;
            if (!currentComposition) {
                // https://github.com/microsoft/monaco-editor/issues/1663
                // On iOS 13.2, Chinese system IME randomly trigger an additional compositionend event with empty data
                return;
            }
            this._currentComposition = null;
            if (this._browser.isAndroid) {
                // On Android, the data sent with the composition update event is unusable.
                // For example, if the cursor is in the middle of a word like Mic|osoft
                // and Microsoft is chosen from the keyboard's suggestions, the e.data will contain "Microsoft".
                // This is not really usable because it doesn't tell us where the edit began and where it ended.
                const newState = TextAreaState.readFromTextArea(this._textArea);
                const typeInput = TextAreaState.deduceAndroidCompositionInput(this._textAreaState, newState);
                this._textAreaState = newState;
                this._onType.fire(typeInput);
                this._onCompositionEnd.fire();
                return;
            }
            const typeInput = currentComposition.handleCompositionUpdate(e.data);
            this._textAreaState = TextAreaState.readFromTextArea(this._textArea);
            this._onType.fire(typeInput);
            this._onCompositionEnd.fire();
        }));
        this._register(this._textArea.onInput((e) => {
            if (_debugComposition) {
                console.log(`[input]`, e);
            }
            // Pretend here we touched the text area, as the `input` event will most likely
            // result in a `selectionchange` event which we want to ignore
            this._textArea.setIgnoreSelectionChangeTime('received input event');
            if (this._currentComposition) {
                return;
            }
            const newState = TextAreaState.readFromTextArea(this._textArea);
            const typeInput = TextAreaState.deduceInput(this._textAreaState, newState, /*couldBeEmojiInput*/ this._OS === 2 /* OperatingSystem.Macintosh */);
            if (typeInput.replacePrevCharCnt === 0 && typeInput.text.length === 1 && isHighSurrogate(typeInput.text.charCodeAt(0))) {
                // Ignore invalid input but keep it around for next time
                return;
            }
            this._textAreaState = newState;
            if (typeInput.text !== ''
                || typeInput.replacePrevCharCnt !== 0
                || typeInput.replaceNextCharCnt !== 0
                || typeInput.positionDelta !== 0) {
                this._onType.fire(typeInput);
            }
        }));
        // --- Clipboard operations
        this._register(this._textArea.onCut((e) => {
            // Pretend here we touched the text area, as the `cut` event will most likely
            // result in a `selectionchange` event which we want to ignore
            this._textArea.setIgnoreSelectionChangeTime('received cut event');
            this._ensureClipboardGetsEditorSelection(e);
            this._asyncTriggerCut.schedule();
        }));
        this._register(this._textArea.onCopy((e) => {
            this._ensureClipboardGetsEditorSelection(e);
        }));
        this._register(this._textArea.onPaste((e) => {
            // Pretend here we touched the text area, as the `paste` event will most likely
            // result in a `selectionchange` event which we want to ignore
            this._textArea.setIgnoreSelectionChangeTime('received paste event');
            e.preventDefault();
            if (!e.clipboardData) {
                return;
            }
            let [text, metadata] = ClipboardEventUtils.getTextData(e.clipboardData);
            if (!text) {
                return;
            }
            // try the in-memory store
            metadata = metadata || InMemoryClipboardMetadataManager.INSTANCE.get(text);
            this._onPaste.fire({
                text: text,
                metadata: metadata
            });
        }));
        this._register(this._textArea.onFocus(() => {
            const hadFocus = this._hasFocus;
            this._setHasFocus(true);
            if (this._browser.isSafari && !hadFocus && this._hasFocus) {
                // When "tabbing into" the textarea, immediately after dispatching the 'focus' event,
                // Safari will always move the selection at offset 0 in the textarea
                this._asyncFocusGainWriteScreenReaderContent.schedule();
            }
        }));
        this._register(this._textArea.onBlur(() => {
            if (this._currentComposition) {
                // See https://github.com/microsoft/vscode/issues/112621
                // where compositionend is not triggered when the editor
                // is taken off-dom during a composition
                // Clear the flag to be able to write to the textarea
                this._currentComposition = null;
                // Clear the textarea to avoid an unwanted cursor type
                this.writeScreenReaderContent('blurWithoutCompositionEnd');
                // Fire artificial composition end
                this._onCompositionEnd.fire();
            }
            this._setHasFocus(false);
        }));
        this._register(this._textArea.onSyntheticTap(() => {
            if (this._browser.isAndroid && this._currentComposition) {
                // on Android, tapping does not cancel the current composition, so the
                // textarea is stuck showing the old composition
                // Clear the flag to be able to write to the textarea
                this._currentComposition = null;
                // Clear the textarea to avoid an unwanted cursor type
                this.writeScreenReaderContent('tapWithoutCompositionEnd');
                // Fire artificial composition end
                this._onCompositionEnd.fire();
            }
        }));
    }
    _installSelectionChangeListener() {
        // See https://github.com/microsoft/vscode/issues/27216 and https://github.com/microsoft/vscode/issues/98256
        // When using a Braille display, it is possible for users to reposition the
        // system caret. This is reflected in Chrome as a `selectionchange` event.
        //
        // The `selectionchange` event appears to be emitted under numerous other circumstances,
        // so it is quite a challenge to distinguish a `selectionchange` coming in from a user
        // using a Braille display from all the other cases.
        //
        // The problems with the `selectionchange` event are:
        //  * the event is emitted when the textarea is focused programmatically -- textarea.focus()
        //  * the event is emitted when the selection is changed in the textarea programmatically -- textarea.setSelectionRange(...)
        //  * the event is emitted when the value of the textarea is changed programmatically -- textarea.value = '...'
        //  * the event is emitted when tabbing into the textarea
        //  * the event is emitted asynchronously (sometimes with a delay as high as a few tens of ms)
        //  * the event sometimes comes in bursts for a single logical textarea operation
        // `selectionchange` events often come multiple times for a single logical change
        // so throttle multiple `selectionchange` events that burst in a short period of time.
        let previousSelectionChangeEventTime = 0;
        return addDisposableListener(document, 'selectionchange', (e) => {
            if (!this._hasFocus) {
                return;
            }
            if (this._currentComposition) {
                return;
            }
            if (!this._browser.isChrome) {
                // Support only for Chrome until testing happens on other browsers
                return;
            }
            const now = Date.now();
            const delta1 = now - previousSelectionChangeEventTime;
            previousSelectionChangeEventTime = now;
            if (delta1 < 5) {
                // received another `selectionchange` event within 5ms of the previous `selectionchange` event
                // => ignore it
                return;
            }
            const delta2 = now - this._textArea.getIgnoreSelectionChangeTime();
            this._textArea.resetSelectionChangeTime();
            if (delta2 < 100) {
                // received a `selectionchange` event within 100ms since we touched the textarea
                // => ignore it, since we caused it
                return;
            }
            if (!this._textAreaState.selectionStartPosition || !this._textAreaState.selectionEndPosition) {
                // Cannot correlate a position in the textarea with a position in the editor...
                return;
            }
            const newValue = this._textArea.getValue();
            if (this._textAreaState.value !== newValue) {
                // Cannot correlate a position in the textarea with a position in the editor...
                return;
            }
            const newSelectionStart = this._textArea.getSelectionStart();
            const newSelectionEnd = this._textArea.getSelectionEnd();
            if (this._textAreaState.selectionStart === newSelectionStart && this._textAreaState.selectionEnd === newSelectionEnd) {
                // Nothing to do...
                return;
            }
            const _newSelectionStartPosition = this._textAreaState.deduceEditorPosition(newSelectionStart);
            const newSelectionStartPosition = this._host.deduceModelPosition(_newSelectionStartPosition[0], _newSelectionStartPosition[1], _newSelectionStartPosition[2]);
            const _newSelectionEndPosition = this._textAreaState.deduceEditorPosition(newSelectionEnd);
            const newSelectionEndPosition = this._host.deduceModelPosition(_newSelectionEndPosition[0], _newSelectionEndPosition[1], _newSelectionEndPosition[2]);
            const newSelection = new Selection(newSelectionStartPosition.lineNumber, newSelectionStartPosition.column, newSelectionEndPosition.lineNumber, newSelectionEndPosition.column);
            this._onSelectionChangeRequest.fire(newSelection);
        });
    }
    dispose() {
        super.dispose();
        if (this._selectionChangeListener) {
            this._selectionChangeListener.dispose();
            this._selectionChangeListener = null;
        }
    }
    focusTextArea() {
        // Setting this._hasFocus and writing the screen reader content
        // will result in a focus() and setSelectionRange() in the textarea
        this._setHasFocus(true);
        // If the editor is off DOM, focus cannot be really set, so let's double check that we have managed to set the focus
        this.refreshFocusState();
    }
    isFocused() {
        return this._hasFocus;
    }
    refreshFocusState() {
        this._setHasFocus(this._textArea.hasFocus());
    }
    _setHasFocus(newHasFocus) {
        if (this._hasFocus === newHasFocus) {
            // no change
            return;
        }
        this._hasFocus = newHasFocus;
        if (this._selectionChangeListener) {
            this._selectionChangeListener.dispose();
            this._selectionChangeListener = null;
        }
        if (this._hasFocus) {
            this._selectionChangeListener = this._installSelectionChangeListener();
        }
        if (this._hasFocus) {
            this.writeScreenReaderContent('focusgain');
        }
        if (this._hasFocus) {
            this._onFocus.fire();
        }
        else {
            this._onBlur.fire();
        }
    }
    _setAndWriteTextAreaState(reason, textAreaState) {
        if (!this._hasFocus) {
            textAreaState = textAreaState.collapseSelection();
        }
        textAreaState.writeToTextArea(reason, this._textArea, this._hasFocus);
        this._textAreaState = textAreaState;
    }
    writeScreenReaderContent(reason) {
        if (this._currentComposition) {
            // Do not write to the text area when doing composition
            return;
        }
        this._setAndWriteTextAreaState(reason, this._host.getScreenReaderContent(this._textAreaState));
    }
    _ensureClipboardGetsEditorSelection(e) {
        const dataToCopy = this._host.getDataToCopy();
        const storedMetadata = {
            version: 1,
            isFromEmptySelection: dataToCopy.isFromEmptySelection,
            multicursorText: dataToCopy.multicursorText,
            mode: dataToCopy.mode
        };
        InMemoryClipboardMetadataManager.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._browser.isFirefox ? dataToCopy.text.replace(/\r\n/g, '\n') : dataToCopy.text), storedMetadata);
        e.preventDefault();
        if (e.clipboardData) {
            ClipboardEventUtils.setTextData(e.clipboardData, dataToCopy.text, dataToCopy.html, storedMetadata);
        }
    }
}
class ClipboardEventUtils {
    static getTextData(clipboardData) {
        const text = clipboardData.getData(Mimes.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) {
                // no problem!
            }
        }
        if (text.length === 0 && metadata === null && clipboardData.files.length > 0) {
            // no textual data pasted, generate text from file names
            const files = Array.prototype.slice.call(clipboardData.files, 0);
            return [files.map(file => file.name).join('\n'), null];
        }
        return [text, metadata];
    }
    static setTextData(clipboardData, text, html, metadata) {
        clipboardData.setData(Mimes.text, text);
        if (typeof html === 'string') {
            clipboardData.setData('text/html', html);
        }
        clipboardData.setData('vscode-editor-data', JSON.stringify(metadata));
    }
}
class TextAreaWrapper extends Disposable {
    constructor(_actual) {
        super();
        this._actual = _actual;
        this.onKeyDown = this._register(createEventEmitter(this._actual, 'keydown')).event;
        this.onKeyUp = this._register(createEventEmitter(this._actual, 'keyup')).event;
        this.onCompositionStart = this._register(createEventEmitter(this._actual, 'compositionstart')).event;
        this.onCompositionUpdate = this._register(createEventEmitter(this._actual, 'compositionupdate')).event;
        this.onCompositionEnd = this._register(createEventEmitter(this._actual, 'compositionend')).event;
        this.onInput = this._register(createEventEmitter(this._actual, 'input')).event;
        this.onCut = this._register(createEventEmitter(this._actual, 'cut')).event;
        this.onCopy = this._register(createEventEmitter(this._actual, 'copy')).event;
        this.onPaste = this._register(createEventEmitter(this._actual, 'paste')).event;
        this.onFocus = this._register(createEventEmitter(this._actual, 'focus')).event;
        this.onBlur = this._register(createEventEmitter(this._actual, 'blur')).event;
        this._onSyntheticTap = this._register(new Emitter());
        this.onSyntheticTap = this._onSyntheticTap.event;
        this._ignoreSelectionChangeTime = 0;
        this._register(addDisposableListener(this._actual, TextAreaSyntethicEvents.Tap, () => this._onSyntheticTap.fire()));
    }
    hasFocus() {
        const shadowRoot = getShadowRoot(this._actual);
        if (shadowRoot) {
            return shadowRoot.activeElement === this._actual;
        }
        else if (isInDOM(this._actual)) {
            return document.activeElement === this._actual;
        }
        else {
            return false;
        }
    }
    setIgnoreSelectionChangeTime(reason) {
        this._ignoreSelectionChangeTime = Date.now();
    }
    getIgnoreSelectionChangeTime() {
        return this._ignoreSelectionChangeTime;
    }
    resetSelectionChangeTime() {
        this._ignoreSelectionChangeTime = 0;
    }
    getValue() {
        // console.log('current value: ' + this._textArea.value);
        return this._actual.value;
    }
    setValue(reason, value) {
        const textArea = this._actual;
        if (textArea.value === value) {
            // No change
            return;
        }
        // console.log('reason: ' + reason + ', current value: ' + textArea.value + ' => new value: ' + value);
        this.setIgnoreSelectionChangeTime('setValue');
        textArea.value = value;
    }
    getSelectionStart() {
        return this._actual.selectionDirection === 'backward' ? this._actual.selectionEnd : this._actual.selectionStart;
    }
    getSelectionEnd() {
        return this._actual.selectionDirection === 'backward' ? this._actual.selectionStart : this._actual.selectionEnd;
    }
    setSelectionRange(reason, selectionStart, selectionEnd) {
        const textArea = this._actual;
        let activeElement = null;
        const shadowRoot = getShadowRoot(textArea);
        if (shadowRoot) {
            activeElement = shadowRoot.activeElement;
        }
        else {
            activeElement = document.activeElement;
        }
        const currentIsFocused = (activeElement === textArea);
        const currentSelectionStart = textArea.selectionStart;
        const currentSelectionEnd = textArea.selectionEnd;
        if (currentIsFocused && currentSelectionStart === selectionStart && currentSelectionEnd === selectionEnd) {
            // No change
            // Firefox iframe bug https://github.com/microsoft/monaco-editor/issues/643#issuecomment-367871377
            if (browser_isFirefox && window.parent !== window) {
                textArea.focus();
            }
            return;
        }
        // console.log('reason: ' + reason + ', setSelectionRange: ' + selectionStart + ' -> ' + selectionEnd);
        if (currentIsFocused) {
            // No need to focus, only need to change the selection range
            this.setIgnoreSelectionChangeTime('setSelectionRange');
            textArea.setSelectionRange(selectionStart, selectionEnd);
            if (browser_isFirefox && window.parent !== window) {
                textArea.focus();
            }
            return;
        }
        // If the focus is outside the textarea, browsers will try really hard to reveal the textarea.
        // Here, we try to undo the browser's desperate reveal.
        try {
            const scrollState = saveParentsScrollTop(textArea);
            this.setIgnoreSelectionChangeTime('setSelectionRange');
            textArea.focus();
            textArea.setSelectionRange(selectionStart, selectionEnd);
            restoreParentsScrollTop(textArea, scrollState);
        }
        catch (e) {
            // Sometimes IE throws when setting selection (e.g. textarea is off-DOM)
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/clipboard/common/clipboardService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const IClipboardService = createDecorator('clipboardService');

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/clipboard/browser/clipboard.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var clipboard_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};









const CLIPBOARD_CONTEXT_MENU_GROUP = '9_cutcopypaste';
const supportsCut = (isNative || document.queryCommandSupported('cut'));
const supportsCopy = (isNative || document.queryCommandSupported('copy'));
// Firefox only supports navigator.clipboard.readText() in browser extensions.
// See https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/readText#Browser_compatibility
// When loading over http, navigator.clipboard can be undefined. See https://github.com/microsoft/monaco-editor/issues/2313
const supportsPaste = (typeof navigator.clipboard === 'undefined' || browser_isFirefox) ? document.queryCommandSupported('paste') : true;
function clipboard_registerCommand(command) {
    command.register();
    return command;
}
const CutAction = supportsCut ? clipboard_registerCommand(new MultiCommand({
    id: 'editor.action.clipboardCutAction',
    precondition: undefined,
    kbOpts: (
    // Do not bind cut keybindings in the browser,
    // since browsers do that for us and it avoids security prompts
    isNative ? {
        primary: 2048 /* KeyMod.CtrlCmd */ | 54 /* KeyCode.KeyX */,
        win: { primary: 2048 /* KeyMod.CtrlCmd */ | 54 /* KeyCode.KeyX */, secondary: [1024 /* KeyMod.Shift */ | 20 /* KeyCode.Delete */] },
        weight: 100 /* KeybindingWeight.EditorContrib */
    } : undefined),
    menuOpts: [{
            menuId: MenuId.MenubarEditMenu,
            group: '2_ccp',
            title: localize({ key: 'miCut', comment: ['&& denotes a mnemonic'] }, "Cu&&t"),
            order: 1
        }, {
            menuId: MenuId.EditorContext,
            group: CLIPBOARD_CONTEXT_MENU_GROUP,
            title: localize('actions.clipboard.cutLabel', "Cut"),
            when: EditorContextKeys.writable,
            order: 1,
        }, {
            menuId: MenuId.CommandPalette,
            group: '',
            title: localize('actions.clipboard.cutLabel', "Cut"),
            order: 1
        }, {
            menuId: MenuId.SimpleEditorContext,
            group: CLIPBOARD_CONTEXT_MENU_GROUP,
            title: localize('actions.clipboard.cutLabel', "Cut"),
            when: EditorContextKeys.writable,
            order: 1,
        }]
})) : undefined;
const CopyAction = supportsCopy ? clipboard_registerCommand(new MultiCommand({
    id: 'editor.action.clipboardCopyAction',
    precondition: undefined,
    kbOpts: (
    // Do not bind copy keybindings in the browser,
    // since browsers do that for us and it avoids security prompts
    isNative ? {
        primary: 2048 /* KeyMod.CtrlCmd */ | 33 /* KeyCode.KeyC */,
        win: { primary: 2048 /* KeyMod.CtrlCmd */ | 33 /* KeyCode.KeyC */, secondary: [2048 /* KeyMod.CtrlCmd */ | 19 /* KeyCode.Insert */] },
        weight: 100 /* KeybindingWeight.EditorContrib */
    } : undefined),
    menuOpts: [{
            menuId: MenuId.MenubarEditMenu,
            group: '2_ccp',
            title: localize({ key: 'miCopy', comment: ['&& denotes a mnemonic'] }, "&&Copy"),
            order: 2
        }, {
            menuId: MenuId.EditorContext,
            group: CLIPBOARD_CONTEXT_MENU_GROUP,
            title: localize('actions.clipboard.copyLabel', "Copy"),
            order: 2,
        }, {
            menuId: MenuId.CommandPalette,
            group: '',
            title: localize('actions.clipboard.copyLabel', "Copy"),
            order: 1
        }, {
            menuId: MenuId.SimpleEditorContext,
            group: CLIPBOARD_CONTEXT_MENU_GROUP,
            title: localize('actions.clipboard.copyLabel', "Copy"),
            order: 2,
        }]
})) : undefined;
MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { submenu: MenuId.MenubarCopy, title: { value: localize('copy as', "Copy As"), original: 'Copy As', }, group: '2_ccp', order: 3 });
MenuRegistry.appendMenuItem(MenuId.EditorContext, { submenu: MenuId.EditorContextCopy, title: { value: localize('copy as', "Copy As"), original: 'Copy As', }, group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 3 });
MenuRegistry.appendMenuItem(MenuId.EditorContext, { submenu: MenuId.EditorContextShare, title: { value: localize('share', "Share"), original: 'Share', }, group: '11_share', order: -1 });
const PasteAction = supportsPaste ? clipboard_registerCommand(new MultiCommand({
    id: 'editor.action.clipboardPasteAction',
    precondition: undefined,
    kbOpts: (
    // Do not bind paste keybindings in the browser,
    // since browsers do that for us and it avoids security prompts
    isNative ? {
        primary: 2048 /* KeyMod.CtrlCmd */ | 52 /* KeyCode.KeyV */,
        win: { primary: 2048 /* KeyMod.CtrlCmd */ | 52 /* KeyCode.KeyV */, secondary: [1024 /* KeyMod.Shift */ | 19 /* KeyCode.Insert */] },
        linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 52 /* KeyCode.KeyV */, secondary: [1024 /* KeyMod.Shift */ | 19 /* KeyCode.Insert */] },
        weight: 100 /* KeybindingWeight.EditorContrib */
    } : undefined),
    menuOpts: [{
            menuId: MenuId.MenubarEditMenu,
            group: '2_ccp',
            title: localize({ key: 'miPaste', comment: ['&& denotes a mnemonic'] }, "&&Paste"),
            order: 4
        }, {
            menuId: MenuId.EditorContext,
            group: CLIPBOARD_CONTEXT_MENU_GROUP,
            title: localize('actions.clipboard.pasteLabel', "Paste"),
            when: EditorContextKeys.writable,
            order: 4,
        }, {
            menuId: MenuId.CommandPalette,
            group: '',
            title: localize('actions.clipboard.pasteLabel', "Paste"),
            order: 1
        }, {
            menuId: MenuId.SimpleEditorContext,
            group: CLIPBOARD_CONTEXT_MENU_GROUP,
            title: localize('actions.clipboard.pasteLabel', "Paste"),
            when: EditorContextKeys.writable,
            order: 4,
        }]
})) : undefined;
class ExecCommandCopyWithSyntaxHighlightingAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.clipboardCopyWithSyntaxHighlightingAction',
            label: localize('actions.clipboard.copyWithSyntaxHighlightingLabel', "Copy With Syntax Highlighting"),
            alias: 'Copy With Syntax Highlighting',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 0,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        if (!editor.hasModel()) {
            return;
        }
        const emptySelectionClipboard = editor.getOption(33 /* EditorOption.emptySelectionClipboard */);
        if (!emptySelectionClipboard && editor.getSelection().isEmpty()) {
            return;
        }
        CopyOptions.forceCopyWithSyntaxHighlighting = true;
        editor.focus();
        document.execCommand('copy');
        CopyOptions.forceCopyWithSyntaxHighlighting = false;
    }
}
function registerExecCommandImpl(target, browserCommand) {
    if (!target) {
        return;
    }
    // 1. handle case when focus is in editor.
    target.addImplementation(10000, 'code-editor', (accessor, args) => {
        // Only if editor text focus (i.e. not if editor has widget focus).
        const focusedEditor = accessor.get(ICodeEditorService).getFocusedCodeEditor();
        if (focusedEditor && focusedEditor.hasTextFocus()) {
            // Do not execute if there is no selection and empty selection clipboard is off
            const emptySelectionClipboard = focusedEditor.getOption(33 /* EditorOption.emptySelectionClipboard */);
            const selection = focusedEditor.getSelection();
            if (selection && selection.isEmpty() && !emptySelectionClipboard) {
                return true;
            }
            document.execCommand(browserCommand);
            return true;
        }
        return false;
    });
    // 2. (default) handle case when focus is somewhere else.
    target.addImplementation(0, 'generic-dom', (accessor, args) => {
        document.execCommand(browserCommand);
        return true;
    });
}
registerExecCommandImpl(CutAction, 'cut');
registerExecCommandImpl(CopyAction, 'copy');
if (PasteAction) {
    // 1. Paste: handle case when focus is in editor.
    PasteAction.addImplementation(10000, 'code-editor', (accessor, args) => {
        const codeEditorService = accessor.get(ICodeEditorService);
        const clipboardService = accessor.get(IClipboardService);
        // Only if editor text focus (i.e. not if editor has widget focus).
        const focusedEditor = codeEditorService.getFocusedCodeEditor();
        if (focusedEditor && focusedEditor.hasTextFocus()) {
            const result = document.execCommand('paste');
            // Use the clipboard service if document.execCommand('paste') was not successful
            if (!result && isWeb) {
                return (() => clipboard_awaiter(void 0, void 0, void 0, function* () {
                    const clipboardText = yield clipboardService.readText();
                    if (clipboardText !== '') {
                        const metadata = InMemoryClipboardMetadataManager.INSTANCE.get(clipboardText);
                        let pasteOnNewLine = false;
                        let multicursorText = null;
                        let mode = null;
                        if (metadata) {
                            pasteOnNewLine = (focusedEditor.getOption(33 /* EditorOption.emptySelectionClipboard */) && !!metadata.isFromEmptySelection);
                            multicursorText = (typeof metadata.multicursorText !== 'undefined' ? metadata.multicursorText : null);
                            mode = metadata.mode;
                        }
                        focusedEditor.trigger('keyboard', "paste" /* Handler.Paste */, {
                            text: clipboardText,
                            pasteOnNewLine,
                            multicursorText,
                            mode
                        });
                    }
                }))();
            }
            return true;
        }
        return false;
    });
    // 2. Paste: (default) handle case when focus is somewhere else.
    PasteAction.addImplementation(0, 'generic-dom', (accessor, args) => {
        document.execCommand('paste');
        return true;
    });
}
if (supportsCopy) {
    registerEditorAction(ExecCommandCopyWithSyntaxHighlightingAction);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/services/bulkEditService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



const IBulkEditService = createDecorator('IWorkspaceEditService');
class ResourceEdit {
    constructor(metadata) {
        this.metadata = metadata;
    }
    static convert(edit) {
        return edit.edits.map(edit => {
            if (ResourceTextEdit.is(edit)) {
                return ResourceTextEdit.lift(edit);
            }
            if (ResourceFileEdit.is(edit)) {
                return ResourceFileEdit.lift(edit);
            }
            throw new Error('Unsupported edit');
        });
    }
}
class ResourceTextEdit extends ResourceEdit {
    constructor(resource, textEdit, versionId = undefined, metadata) {
        super(metadata);
        this.resource = resource;
        this.textEdit = textEdit;
        this.versionId = versionId;
    }
    static is(candidate) {
        if (candidate instanceof ResourceTextEdit) {
            return true;
        }
        return isObject(candidate)
            && URI.isUri(candidate.resource)
            && isObject(candidate.textEdit);
    }
    static lift(edit) {
        if (edit instanceof ResourceTextEdit) {
            return edit;
        }
        else {
            return new ResourceTextEdit(edit.resource, edit.textEdit, edit.versionId, edit.metadata);
        }
    }
}
class ResourceFileEdit extends ResourceEdit {
    constructor(oldResource, newResource, options = {}, metadata) {
        super(metadata);
        this.oldResource = oldResource;
        this.newResource = newResource;
        this.options = options;
    }
    static is(candidate) {
        if (candidate instanceof ResourceFileEdit) {
            return true;
        }
        else {
            return isObject(candidate)
                && (Boolean(candidate.newResource) || Boolean(candidate.oldResource));
        }
    }
    static lift(edit) {
        if (edit instanceof ResourceFileEdit) {
            return edit;
        }
        else {
            return new ResourceFileEdit(edit.oldResource, edit.newResource, edit.options, edit.metadata);
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/languageFeatures.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const ILanguageFeaturesService = createDecorator('ILanguageFeaturesService');

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/editorState/browser/keybindingCancellation.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







const IEditorCancellationTokens = createDecorator('IEditorCancelService');
const ctxCancellableOperation = new RawContextKey('cancellableOperation', false, localize('cancellableOperation', 'Whether the editor runs a cancellable operation, e.g. like \'Peek References\''));
registerSingleton(IEditorCancellationTokens, class {
    constructor() {
        this._tokens = new WeakMap();
    }
    add(editor, cts) {
        let data = this._tokens.get(editor);
        if (!data) {
            data = editor.invokeWithinContext(accessor => {
                const key = ctxCancellableOperation.bindTo(accessor.get(IContextKeyService));
                const tokens = new LinkedList();
                return { key, tokens };
            });
            this._tokens.set(editor, data);
        }
        let removeFn;
        data.key.set(true);
        removeFn = data.tokens.push(cts);
        return () => {
            // remove w/o cancellation
            if (removeFn) {
                removeFn();
                data.key.set(!data.tokens.isEmpty());
                removeFn = undefined;
            }
        };
    }
    cancel(editor) {
        const data = this._tokens.get(editor);
        if (!data) {
            return;
        }
        // remove with cancellation
        const cts = data.tokens.pop();
        if (cts) {
            cts.cancel();
            data.key.set(!data.tokens.isEmpty());
        }
    }
}, true);
class EditorKeybindingCancellationTokenSource extends CancellationTokenSource {
    constructor(editor, parent) {
        super(parent);
        this.editor = editor;
        this._unregister = editor.invokeWithinContext(accessor => accessor.get(IEditorCancellationTokens).add(editor, this));
    }
    dispose() {
        this._unregister();
        super.dispose();
    }
}
registerEditorCommand(new class extends EditorCommand {
    constructor() {
        super({
            id: 'editor.cancelOperation',
            kbOpts: {
                weight: 100 /* KeybindingWeight.EditorContrib */,
                primary: 9 /* KeyCode.Escape */
            },
            precondition: ctxCancellableOperation
        });
    }
    runEditorCommand(accessor, editor) {
        accessor.get(IEditorCancellationTokens).cancel(editor);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/editorState/browser/editorState.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class EditorState {
    constructor(editor, flags) {
        this.flags = flags;
        if ((this.flags & 1 /* CodeEditorStateFlag.Value */) !== 0) {
            const model = editor.getModel();
            this.modelVersionId = model ? format('{0}#{1}', model.uri.toString(), model.getVersionId()) : null;
        }
        else {
            this.modelVersionId = null;
        }
        if ((this.flags & 4 /* CodeEditorStateFlag.Position */) !== 0) {
            this.position = editor.getPosition();
        }
        else {
            this.position = null;
        }
        if ((this.flags & 2 /* CodeEditorStateFlag.Selection */) !== 0) {
            this.selection = editor.getSelection();
        }
        else {
            this.selection = null;
        }
        if ((this.flags & 8 /* CodeEditorStateFlag.Scroll */) !== 0) {
            this.scrollLeft = editor.getScrollLeft();
            this.scrollTop = editor.getScrollTop();
        }
        else {
            this.scrollLeft = -1;
            this.scrollTop = -1;
        }
    }
    _equals(other) {
        if (!(other instanceof EditorState)) {
            return false;
        }
        const state = other;
        if (this.modelVersionId !== state.modelVersionId) {
            return false;
        }
        if (this.scrollLeft !== state.scrollLeft || this.scrollTop !== state.scrollTop) {
            return false;
        }
        if (!this.position && state.position || this.position && !state.position || this.position && state.position && !this.position.equals(state.position)) {
            return false;
        }
        if (!this.selection && state.selection || this.selection && !state.selection || this.selection && state.selection && !this.selection.equalsRange(state.selection)) {
            return false;
        }
        return true;
    }
    validate(editor) {
        return this._equals(new EditorState(editor, this.flags));
    }
}
/**
 * A cancellation token source that cancels when the editor changes as expressed
 * by the provided flags
 * @param range If provided, changes in position and selection within this range will not trigger cancellation
 */
class EditorStateCancellationTokenSource extends EditorKeybindingCancellationTokenSource {
    constructor(editor, flags, range, parent) {
        super(editor, parent);
        this._listener = new DisposableStore();
        if (flags & 4 /* CodeEditorStateFlag.Position */) {
            this._listener.add(editor.onDidChangeCursorPosition(e => {
                if (!range || !Range.containsPosition(range, e.position)) {
                    this.cancel();
                }
            }));
        }
        if (flags & 2 /* CodeEditorStateFlag.Selection */) {
            this._listener.add(editor.onDidChangeCursorSelection(e => {
                if (!range || !Range.containsRange(range, e.selection)) {
                    this.cancel();
                }
            }));
        }
        if (flags & 8 /* CodeEditorStateFlag.Scroll */) {
            this._listener.add(editor.onDidScrollChange(_ => this.cancel()));
        }
        if (flags & 1 /* CodeEditorStateFlag.Value */) {
            this._listener.add(editor.onDidChangeModel(_ => this.cancel()));
            this._listener.add(editor.onDidChangeModelContent(_ => this.cancel()));
        }
    }
    dispose() {
        this._listener.dispose();
        super.dispose();
    }
}
/**
 * A cancellation token source that cancels when the provided model changes
 */
class TextModelCancellationTokenSource extends CancellationTokenSource {
    constructor(model, parent) {
        super(parent);
        this._listener = model.onDidChangeContent(() => this.cancel());
    }
    dispose() {
        this._listener.dispose();
        super.dispose();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/progress/common/progress.js

const IProgressService = createDecorator('progressService');
const emptyProgressRunner = Object.freeze({
    total() { },
    worked() { },
    done() { }
});
class Progress {
    constructor(callback) {
        this.callback = callback;
    }
    report(item) {
        this._value = item;
        this.callback(this._value);
    }
}
Progress.None = Object.freeze({ report() { } });
const IEditorProgressService = createDecorator('editorProgressService');

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/types.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class CodeActionKind {
    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 + CodeActionKind.sep);
    }
    intersects(other) {
        return this.contains(other) || other.contains(this);
    }
    append(part) {
        return new CodeActionKind(this.value + CodeActionKind.sep + part);
    }
}
CodeActionKind.sep = '.';
CodeActionKind.None = new CodeActionKind('@@none@@'); // Special code action that contains nothing
CodeActionKind.Empty = new CodeActionKind('');
CodeActionKind.QuickFix = new CodeActionKind('quickfix');
CodeActionKind.Refactor = new CodeActionKind('refactor');
CodeActionKind.Source = new CodeActionKind('source');
CodeActionKind.SourceOrganizeImports = CodeActionKind.Source.append('organizeImports');
CodeActionKind.SourceFixAll = CodeActionKind.Source.append('fixAll');
var CodeActionTriggerSource;
(function (CodeActionTriggerSource) {
    CodeActionTriggerSource["Refactor"] = "refactor";
    CodeActionTriggerSource["RefactorPreview"] = "refactor preview";
    CodeActionTriggerSource["Lightbulb"] = "lightbulb";
    CodeActionTriggerSource["Default"] = "other (default)";
    CodeActionTriggerSource["SourceAction"] = "source action";
    CodeActionTriggerSource["QuickFix"] = "quick fix action";
    CodeActionTriggerSource["FixAll"] = "fix all";
    CodeActionTriggerSource["OrganizeImports"] = "organize imports";
    CodeActionTriggerSource["AutoFix"] = "auto fix";
    CodeActionTriggerSource["QuickFixHover"] = "quick fix hover window";
    CodeActionTriggerSource["OnSave"] = "save participants";
    CodeActionTriggerSource["ProblemsView"] = "problems view";
})(CodeActionTriggerSource || (CodeActionTriggerSource = {}));
function mayIncludeActionsOfKind(filter, providedKind) {
    // A provided kind may be a subset or superset of our filtered kind.
    if (filter.include && !filter.include.intersects(providedKind)) {
        return false;
    }
    if (filter.excludes) {
        if (filter.excludes.some(exclude => excludesAction(providedKind, exclude, filter.include))) {
            return false;
        }
    }
    // Don't return source actions unless they are explicitly requested
    if (!filter.includeSourceActions && CodeActionKind.Source.contains(providedKind)) {
        return false;
    }
    return true;
}
function filtersAction(filter, action) {
    const actionKind = action.kind ? new CodeActionKind(action.kind) : undefined;
    // Filter out actions by kind
    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;
        }
    }
    // Don't return source actions unless they are explicitly requested
    if (!filter.includeSourceActions) {
        if (actionKind && CodeActionKind.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)) {
        // The include is more specific, don't filter out
        return false;
    }
    return true;
}
class CodeActionCommandArgs {
    constructor(kind, apply, preferred) {
        this.kind = kind;
        this.apply = apply;
        this.preferred = preferred;
    }
    static fromUser(arg, defaults) {
        if (!arg || typeof arg !== 'object') {
            return new CodeActionCommandArgs(defaults.kind, defaults.apply, false);
        }
        return new CodeActionCommandArgs(CodeActionCommandArgs.getKindFromUser(arg, defaults.kind), CodeActionCommandArgs.getApplyFromUser(arg, defaults.apply), CodeActionCommandArgs.getPreferredUser(arg));
    }
    static getApplyFromUser(arg, defaultAutoApply) {
        switch (typeof arg.apply === 'string' ? arg.apply.toLowerCase() : '') {
            case 'first': return "first" /* CodeActionAutoApply.First */;
            case 'never': return "never" /* CodeActionAutoApply.Never */;
            case 'ifsingle': return "ifSingle" /* CodeActionAutoApply.IfSingle */;
            default: return defaultAutoApply;
        }
    }
    static getKindFromUser(arg, defaultKind) {
        return typeof arg.kind === 'string'
            ? new CodeActionKind(arg.kind)
            : defaultKind;
    }
    static getPreferredUser(arg) {
        return typeof arg.preferred === 'boolean'
            ? arg.preferred
            : false;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/codeAction.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var codeAction_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};













const codeActionCommandId = 'editor.action.codeAction';
const refactorCommandId = 'editor.action.refactor';
const refactorPreviewCommandId = 'editor.action.refactor.preview';
const sourceActionCommandId = 'editor.action.sourceAction';
const organizeImportsCommandId = 'editor.action.organizeImports';
const fixAllCommandId = 'editor.action.fixAll';
class CodeActionItem {
    constructor(action, provider) {
        this.action = action;
        this.provider = provider;
    }
    resolve(token) {
        var _a;
        return codeAction_awaiter(this, void 0, void 0, function* () {
            if (((_a = this.provider) === null || _a === void 0 ? void 0 : _a.resolveCodeAction) && !this.action.edit) {
                let action;
                try {
                    action = yield this.provider.resolveCodeAction(this.action, token);
                }
                catch (err) {
                    onUnexpectedExternalError(err);
                }
                if (action) {
                    this.action.edit = action.edit;
                }
            }
            return this;
        });
    }
}
class ManagedCodeActionSet extends Disposable {
    constructor(actions, documentation, disposables) {
        super();
        this.documentation = documentation;
        this._register(disposables);
        this.allActions = [...actions].sort(ManagedCodeActionSet.codeActionsComparator);
        this.validActions = this.allActions.filter(({ action }) => !action.disabled);
    }
    static codeActionsComparator({ action: a }, { action: b }) {
        if (a.isPreferred && !b.isPreferred) {
            return -1;
        }
        else if (!a.isPreferred && b.isPreferred) {
            return 1;
        }
        if (isNonEmptyArray(a.diagnostics)) {
            if (isNonEmptyArray(b.diagnostics)) {
                return a.diagnostics[0].message.localeCompare(b.diagnostics[0].message);
            }
            else {
                return -1;
            }
        }
        else if (isNonEmptyArray(b.diagnostics)) {
            return 1;
        }
        else {
            return 0; // both have no diagnostics
        }
    }
    get hasAutoFix() {
        return this.validActions.some(({ action: fix }) => !!fix.kind && CodeActionKind.QuickFix.contains(new CodeActionKind(fix.kind)) && !!fix.isPreferred);
    }
}
const emptyCodeActionsResponse = { actions: [], documentation: undefined };
function getCodeActions(registry, model, rangeOrSelection, trigger, progress, token) {
    var _a;
    const filter = trigger.filter || {};
    const codeActionContext = {
        only: (_a = filter.include) === null || _a === void 0 ? void 0 : _a.value,
        trigger: trigger.type,
    };
    const cts = new TextModelCancellationTokenSource(model, token);
    const providers = getCodeActionProviders(registry, model, filter);
    const disposables = new DisposableStore();
    const promises = providers.map((provider) => codeAction_awaiter(this, void 0, void 0, function* () {
        try {
            progress.report(provider);
            const providedCodeActions = yield provider.provideCodeActions(model, rangeOrSelection, codeActionContext, cts.token);
            if (providedCodeActions) {
                disposables.add(providedCodeActions);
            }
            if (cts.token.isCancellationRequested) {
                return emptyCodeActionsResponse;
            }
            const filteredActions = ((providedCodeActions === null || providedCodeActions === void 0 ? void 0 : providedCodeActions.actions) || []).filter(action => action && filtersAction(filter, action));
            const documentation = getDocumentation(provider, filteredActions, filter.include);
            return {
                actions: filteredActions.map(action => new CodeActionItem(action, provider)),
                documentation
            };
        }
        catch (err) {
            if (isCancellationError(err)) {
                throw err;
            }
            onUnexpectedExternalError(err);
            return emptyCodeActionsResponse;
        }
    }));
    const listener = registry.onDidChange(() => {
        const newProviders = registry.all(model);
        if (!equals(newProviders, providers)) {
            cts.cancel();
        }
    });
    return Promise.all(promises).then(actions => {
        const allActions = actions.map(x => x.actions).flat();
        const allDocumentation = coalesce(actions.map(x => x.documentation));
        return new ManagedCodeActionSet(allActions, allDocumentation, disposables);
    })
        .finally(() => {
        listener.dispose();
        cts.dispose();
    });
}
function getCodeActionProviders(registry, model, filter) {
    return registry.all(model)
        // Don't include providers that we know will not return code actions of interest
        .filter(provider => {
        if (!provider.providedCodeActionKinds) {
            // We don't know what type of actions this provider will return.
            return true;
        }
        return provider.providedCodeActionKinds.some(kind => mayIncludeActionsOfKind(filter, new CodeActionKind(kind)));
    });
}
function getDocumentation(provider, providedCodeActions, only) {
    if (!provider.documentation) {
        return undefined;
    }
    const documentation = provider.documentation.map(entry => ({ kind: new CodeActionKind(entry.kind), command: entry.command }));
    if (only) {
        let currentBest;
        for (const entry of documentation) {
            if (entry.kind.contains(only)) {
                if (!currentBest) {
                    currentBest = entry;
                }
                else {
                    // Take best match
                    if (currentBest.kind.contains(entry.kind)) {
                        currentBest = entry;
                    }
                }
            }
        }
        if (currentBest) {
            return currentBest === null || currentBest === void 0 ? void 0 : currentBest.command;
        }
    }
    // Otherwise, check to see if any of the provided actions match.
    for (const action of providedCodeActions) {
        if (!action.kind) {
            continue;
        }
        for (const entry of documentation) {
            if (entry.kind.contains(new CodeActionKind(action.kind))) {
                return entry.command;
            }
        }
    }
    return undefined;
}
CommandsRegistry.registerCommand('_executeCodeActionProvider', function (accessor, resource, rangeOrSelection, kind, itemResolveCount) {
    return codeAction_awaiter(this, void 0, void 0, function* () {
        if (!(resource instanceof URI)) {
            throw illegalArgument();
        }
        const { codeActionProvider } = accessor.get(ILanguageFeaturesService);
        const model = accessor.get(IModelService).getModel(resource);
        if (!model) {
            throw illegalArgument();
        }
        const validatedRangeOrSelection = Selection.isISelection(rangeOrSelection)
            ? Selection.liftSelection(rangeOrSelection)
            : Range.isIRange(rangeOrSelection)
                ? model.validateRange(rangeOrSelection)
                : undefined;
        if (!validatedRangeOrSelection) {
            throw illegalArgument();
        }
        const include = typeof kind === 'string' ? new CodeActionKind(kind) : undefined;
        const codeActionSet = yield getCodeActions(codeActionProvider, model, validatedRangeOrSelection, { type: 1 /* languages.CodeActionTriggerType.Invoke */, triggerAction: CodeActionTriggerSource.Default, filter: { includeSourceActions: true, include } }, Progress.None, CancellationToken.None);
        const resolving = [];
        const resolveCount = Math.min(codeActionSet.validActions.length, typeof itemResolveCount === 'number' ? itemResolveCount : 0);
        for (let i = 0; i < resolveCount; i++) {
            resolving.push(codeActionSet.validActions[i].resolve(CancellationToken.None));
        }
        try {
            yield Promise.all(resolving);
            return codeActionSet.validActions.map(item => item.action);
        }
        finally {
            setTimeout(() => codeActionSet.dispose(), 100);
        }
    });
});

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/message/browser/messageController.css
var messageController = __webpack_require__(72618);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/message/browser/messageController.css

      
      
      
      
      
      
      
      
      

var messageController_options = {};

messageController_options.styleTagTransform = (styleTagTransform_default());
messageController_options.setAttributes = (setAttributesWithoutAttributes_default());

      messageController_options.insert = insertBySelector_default().bind(null, "head");
    
messageController_options.domAPI = (styleDomAPI_default());
messageController_options.insertStyleElement = (insertStyleElement_default());

var messageController_update = injectStylesIntoStyleTag_default()(messageController/* default */.A, messageController_options);




       /* harmony default export */ const browser_messageController = (messageController/* default */.A && messageController/* default */.A.locals ? messageController/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/message/browser/messageController.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var messageController_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var messageController_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};








let MessageController = class MessageController {
    constructor(editor, contextKeyService) {
        this._messageWidget = new MutableDisposable();
        this._messageListeners = new DisposableStore();
        this._editor = editor;
        this._visible = MessageController.MESSAGE_VISIBLE.bindTo(contextKeyService);
    }
    static get(editor) {
        return editor.getContribution(MessageController.ID);
    }
    dispose() {
        this._messageListeners.dispose();
        this._messageWidget.dispose();
        this._visible.reset();
    }
    showMessage(message, position) {
        aria_alert(message);
        this._visible.set(true);
        this._messageWidget.clear();
        this._messageListeners.clear();
        this._messageWidget.value = new MessageWidget(this._editor, position, message);
        // close on blur, cursor, model change, dispose
        this._messageListeners.add(this._editor.onDidBlurEditorText(() => this.closeMessage()));
        this._messageListeners.add(this._editor.onDidChangeCursorPosition(() => this.closeMessage()));
        this._messageListeners.add(this._editor.onDidDispose(() => this.closeMessage()));
        this._messageListeners.add(this._editor.onDidChangeModel(() => this.closeMessage()));
        // 3sec
        this._messageListeners.add(new TimeoutTimer(() => this.closeMessage(), 3000));
        // close on mouse move
        let bounds;
        this._messageListeners.add(this._editor.onMouseMove(e => {
            // outside the text area
            if (!e.target.position) {
                return;
            }
            if (!bounds) {
                // define bounding box around position and first mouse occurance
                bounds = new Range(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1);
            }
            else if (!bounds.containsPosition(e.target.position)) {
                // check if position is still in bounds
                this.closeMessage();
            }
        }));
    }
    closeMessage() {
        this._visible.reset();
        this._messageListeners.clear();
        if (this._messageWidget.value) {
            this._messageListeners.add(MessageWidget.fadeOut(this._messageWidget.value));
        }
    }
};
MessageController.ID = 'editor.contrib.messageController';
MessageController.MESSAGE_VISIBLE = new RawContextKey('messageVisible', false, localize('messageVisible', 'Whether the editor is currently showing an inline message'));
MessageController = messageController_decorate([
    messageController_param(1, IContextKeyService)
], MessageController);

const MessageCommand = EditorCommand.bindToContribution(MessageController.get);
registerEditorCommand(new MessageCommand({
    id: 'leaveEditorMessage',
    precondition: MessageController.MESSAGE_VISIBLE,
    handler: c => c.closeMessage(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 30,
        primary: 9 /* KeyCode.Escape */
    }
}));
class MessageWidget {
    constructor(editor, { lineNumber, column }, text) {
        // Editor.IContentWidget.allowEditorOverflow
        this.allowEditorOverflow = true;
        this.suppressMouseDown = false;
        this._editor = editor;
        this._editor.revealLinesInCenterIfOutsideViewport(lineNumber, lineNumber, 0 /* ScrollType.Smooth */);
        this._position = { lineNumber, column };
        this._domNode = document.createElement('div');
        this._domNode.classList.add('monaco-editor-overlaymessage');
        this._domNode.style.marginLeft = '-6px';
        const anchorTop = document.createElement('div');
        anchorTop.classList.add('anchor', 'top');
        this._domNode.appendChild(anchorTop);
        const message = document.createElement('div');
        message.classList.add('message');
        message.textContent = text;
        this._domNode.appendChild(message);
        const anchorBottom = document.createElement('div');
        anchorBottom.classList.add('anchor', 'below');
        this._domNode.appendChild(anchorBottom);
        this._editor.addContentWidget(this);
        this._domNode.classList.add('fadeIn');
    }
    static fadeOut(messageWidget) {
        const dispose = () => {
            messageWidget.dispose();
            clearTimeout(handle);
            messageWidget.getDomNode().removeEventListener('animationend', dispose);
        };
        const handle = setTimeout(dispose, 110);
        messageWidget.getDomNode().addEventListener('animationend', dispose);
        messageWidget.getDomNode().classList.add('fadeOut');
        return { dispose };
    }
    dispose() {
        this._editor.removeContentWidget(this);
    }
    getId() {
        return 'messageoverlay';
    }
    getDomNode() {
        return this._domNode;
    }
    getPosition() {
        return {
            position: this._position,
            preference: [
                1 /* ContentWidgetPositionPreference.ABOVE */,
                2 /* ContentWidgetPositionPreference.BELOW */,
            ],
            positionAffinity: 1 /* PositionAffinity.Right */,
        };
    }
    afterRender(position) {
        this._domNode.classList.toggle('below', position === 2 /* ContentWidgetPositionPreference.BELOW */);
    }
}
registerEditorContribution(MessageController.ID, MessageController);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/event.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class DomEmitter {
    constructor(element, type, useCapture) {
        const fn = (e) => this.emitter.fire(e);
        this.emitter = new Emitter({
            onFirstListenerAdd: () => element.addEventListener(type, fn, useCapture),
            onLastListenerRemove: () => element.removeEventListener(type, fn, useCapture)
        });
    }
    get event() {
        return this.emitter.event;
    }
    dispose() {
        this.emitter.dispose();
    }
}
function stopEvent(event) {
    event.preventDefault();
    event.stopPropagation();
    return event;
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/list/splice.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class CombinedSpliceable {
    constructor(spliceables) {
        this.spliceables = spliceables;
    }
    splice(start, deleteCount, elements) {
        this.spliceables.forEach(s => s.splice(start, deleteCount, elements));
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/numbers.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
function clamp(value, min, max) {
    return Math.min(Math.max(value, min), max);
}
class MovingAverage {
    constructor() {
        this._n = 1;
        this._val = 0;
    }
    update(value) {
        this._val = this._val + (value - this._val) / this._n;
        this._n += 1;
        return this._val;
    }
    get value() {
        return this._val;
    }
}
class SlidingWindowAverage {
    constructor(size) {
        this._n = 0;
        this._val = 0;
        this._values = [];
        this._index = 0;
        this._sum = 0;
        this._values = new Array(size);
        this._values.fill(0, 0, size);
    }
    update(value) {
        const oldValue = this._values[this._index];
        this._values[this._index] = value;
        this._index = (this._index + 1) % this._values.length;
        this._sum -= oldValue;
        this._sum += value;
        if (this._n < this._values.length) {
            this._n += 1;
        }
        this._val = this._sum / this._n;
        return this._val;
    }
    get value() {
        return this._val;
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/list/list.css
var list = __webpack_require__(4273);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/list/list.css

      
      
      
      
      
      
      
      
      

var list_options = {};

list_options.styleTagTransform = (styleTagTransform_default());
list_options.setAttributes = (setAttributesWithoutAttributes_default());

      list_options.insert = insertBySelector_default().bind(null, "head");
    
list_options.domAPI = (styleDomAPI_default());
list_options.insertStyleElement = (insertStyleElement_default());

var list_update = injectStylesIntoStyleTag_default()(list/* default */.A, list_options);




       /* harmony default export */ const list_list = (list/* default */.A && list/* default */.A.locals ? list/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/list/list.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class ListError extends Error {
    constructor(user, message) {
        super(`ListError [${user}] ${message}`);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/dnd.js

// Common data transfers
const DataTransfers = {
    /**
     * 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: Mimes.text
};
const StaticDND = {
    CurrentDragAndDropData: undefined
};

;// ../../node_modules/monaco-editor/esm/vs/base/browser/globalPointerMoveMonitor.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class GlobalPointerMoveMonitor {
    constructor() {
        this._hooks = new DisposableStore();
        this._pointerMoveCallback = null;
        this._onStopCallback = null;
    }
    dispose() {
        this.stopMonitoring(false);
        this._hooks.dispose();
    }
    stopMonitoring(invokeStopCallback, browserEvent) {
        if (!this.isMonitoring()) {
            // Not monitoring
            return;
        }
        // Unhook
        this._hooks.clear();
        this._pointerMoveCallback = null;
        const onStopCallback = this._onStopCallback;
        this._onStopCallback = null;
        if (invokeStopCallback && onStopCallback) {
            onStopCallback(browserEvent);
        }
    }
    isMonitoring() {
        return !!this._pointerMoveCallback;
    }
    startMonitoring(initialElement, pointerId, initialButtons, pointerMoveCallback, onStopCallback) {
        if (this.isMonitoring()) {
            this.stopMonitoring(false);
        }
        this._pointerMoveCallback = pointerMoveCallback;
        this._onStopCallback = onStopCallback;
        let eventSource = initialElement;
        try {
            initialElement.setPointerCapture(pointerId);
            this._hooks.add(toDisposable(() => {
                initialElement.releasePointerCapture(pointerId);
            }));
        }
        catch (err) {
            // See https://github.com/microsoft/vscode/issues/144584
            // See https://github.com/microsoft/vscode/issues/146947
            // `setPointerCapture` sometimes fails when being invoked
            // from a `mousedown` listener on macOS and Windows
            // and it always fails on Linux with the exception:
            //     DOMException: Failed to execute 'setPointerCapture' on 'Element':
            //     No active pointer with the given id is found.
            // In case of failure, we bind the listeners on the window
            eventSource = window;
        }
        this._hooks.add(addDisposableListener(eventSource, EventType.POINTER_MOVE, (e) => {
            if (e.buttons !== initialButtons) {
                // Buttons state has changed in the meantime
                this.stopMonitoring(true);
                return;
            }
            e.preventDefault();
            this._pointerMoveCallback(e);
        }));
        this._hooks.add(addDisposableListener(eventSource, EventType.POINTER_UP, (e) => this.stopMonitoring(true)));
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/scrollbar/scrollbarArrow.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




/**
 * The arrow image size.
 */
const ARROW_IMG_SIZE = 11;
class ScrollbarArrow extends Widget {
    constructor(opts) {
        super();
        this._onActivate = 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(...opts.icon.classNamesArray);
        this.domNode.style.position = 'absolute';
        this.domNode.style.width = ARROW_IMG_SIZE + 'px';
        this.domNode.style.height = ARROW_IMG_SIZE + '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._pointerMoveMonitor = this._register(new GlobalPointerMoveMonitor());
        this._register(addStandardDisposableListener(this.bgDomNode, EventType.POINTER_DOWN, (e) => this._arrowPointerDown(e)));
        this._register(addStandardDisposableListener(this.domNode, EventType.POINTER_DOWN, (e) => this._arrowPointerDown(e)));
        this._pointerdownRepeatTimer = this._register(new IntervalTimer());
        this._pointerdownScheduleRepeatTimer = this._register(new TimeoutTimer());
    }
    _arrowPointerDown(e) {
        if (!e.target || !(e.target instanceof Element)) {
            return;
        }
        const scheduleRepeater = () => {
            this._pointerdownRepeatTimer.cancelAndSet(() => this._onActivate(), 1000 / 24);
        };
        this._onActivate();
        this._pointerdownRepeatTimer.cancel();
        this._pointerdownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200);
        this._pointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => { }, () => {
            this._pointerdownRepeatTimer.cancel();
            this._pointerdownScheduleRepeatTimer.cancel();
        });
        e.preventDefault();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/scrollbar/scrollbarVisibilityController.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class ScrollbarVisibilityController extends Disposable {
    constructor(visibility, visibleClassName, invisibleClassName) {
        super();
        this._visibility = visibility;
        this._visibleClassName = visibleClassName;
        this._invisibleClassName = invisibleClassName;
        this._domNode = null;
        this._isVisible = false;
        this._isNeeded = false;
        this._rawShouldBeVisible = false;
        this._shouldBeVisible = false;
        this._revealTimer = this._register(new TimeoutTimer());
    }
    setVisibility(visibility) {
        if (this._visibility !== visibility) {
            this._visibility = visibility;
            this._updateShouldBeVisible();
        }
    }
    // ----------------- Hide / Reveal
    setShouldBeVisible(rawShouldBeVisible) {
        this._rawShouldBeVisible = rawShouldBeVisible;
        this._updateShouldBeVisible();
    }
    _applyVisibilitySetting() {
        if (this._visibility === 2 /* ScrollbarVisibility.Hidden */) {
            return false;
        }
        if (this._visibility === 3 /* ScrollbarVisibility.Visible */) {
            return true;
        }
        return this._rawShouldBeVisible;
    }
    _updateShouldBeVisible() {
        const shouldBeVisible = this._applyVisibilitySetting();
        if (this._shouldBeVisible !== shouldBeVisible) {
            this._shouldBeVisible = shouldBeVisible;
            this.ensureVisibility();
        }
    }
    setIsNeeded(isNeeded) {
        if (this._isNeeded !== isNeeded) {
            this._isNeeded = isNeeded;
            this.ensureVisibility();
        }
    }
    setDomNode(domNode) {
        this._domNode = domNode;
        this._domNode.setClassName(this._invisibleClassName);
        // Now that the flags & the dom node are in a consistent state, ensure the Hidden/Visible configuration
        this.setShouldBeVisible(false);
    }
    ensureVisibility() {
        if (!this._isNeeded) {
            // Nothing to be rendered
            this._hide(false);
            return;
        }
        if (this._shouldBeVisible) {
            this._reveal();
        }
        else {
            this._hide(true);
        }
    }
    _reveal() {
        if (this._isVisible) {
            return;
        }
        this._isVisible = true;
        // The CSS animation doesn't play otherwise
        this._revealTimer.setIfNotSet(() => {
            var _a;
            (_a = this._domNode) === null || _a === void 0 ? void 0 : _a.setClassName(this._visibleClassName);
        }, 0);
    }
    _hide(withFadeAway) {
        var _a;
        this._revealTimer.cancel();
        if (!this._isVisible) {
            return;
        }
        this._isVisible = false;
        (_a = this._domNode) === null || _a === void 0 ? void 0 : _a.setClassName(this._invisibleClassName + (withFadeAway ? ' fade' : ''));
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/scrollbar/abstractScrollbar.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







/**
 * The orthogonal distance to the slider at which dragging "resets". This implements "snapping"
 */
const POINTER_DRAG_RESET_DISTANCE = 140;
class AbstractScrollbar extends Widget {
    constructor(opts) {
        super();
        this._lazyRender = opts.lazyRender;
        this._host = opts.host;
        this._scrollable = opts.scrollable;
        this._scrollByPage = opts.scrollByPage;
        this._scrollbarState = opts.scrollbarState;
        this._visibilityController = this._register(new ScrollbarVisibilityController(opts.visibility, 'visible scrollbar ' + opts.extraScrollbarClassName, 'invisible scrollbar ' + opts.extraScrollbarClassName));
        this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
        this._pointerMoveMonitor = this._register(new GlobalPointerMoveMonitor());
        this._shouldRender = true;
        this.domNode = createFastDomNode(document.createElement('div'));
        this.domNode.setAttribute('role', 'presentation');
        this.domNode.setAttribute('aria-hidden', 'true');
        this._visibilityController.setDomNode(this.domNode);
        this.domNode.setPosition('absolute');
        this._register(addDisposableListener(this.domNode.domNode, EventType.POINTER_DOWN, (e) => this._domNodePointerDown(e)));
    }
    // ----------------- creation
    /**
     * Creates the dom node for an arrow & adds it to the container
     */
    _createArrow(opts) {
        const arrow = this._register(new ScrollbarArrow(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
     */
    _createSlider(top, left, width, height) {
        this.slider = createFastDomNode(document.createElement('div'));
        this.slider.setClassName('slider');
        this.slider.setPosition('absolute');
        this.slider.setTop(top);
        this.slider.setLeft(left);
        if (typeof width === 'number') {
            this.slider.setWidth(width);
        }
        if (typeof height === 'number') {
            this.slider.setHeight(height);
        }
        this.slider.setLayerHinting(true);
        this.slider.setContain('strict');
        this.domNode.domNode.appendChild(this.slider.domNode);
        this._register(addDisposableListener(this.slider.domNode, EventType.POINTER_DOWN, (e) => {
            if (e.button === 0) {
                e.preventDefault();
                this._sliderPointerDown(e);
            }
        }));
        this.onclick(this.slider.domNode, e => {
            if (e.leftButton) {
                e.stopPropagation();
            }
        });
    }
    // ----------------- Update state
    _onElementSize(visibleSize) {
        if (this._scrollbarState.setVisibleSize(visibleSize)) {
            this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
            this._shouldRender = true;
            if (!this._lazyRender) {
                this.render();
            }
        }
        return this._shouldRender;
    }
    _onElementScrollSize(elementScrollSize) {
        if (this._scrollbarState.setScrollSize(elementScrollSize)) {
            this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
            this._shouldRender = true;
            if (!this._lazyRender) {
                this.render();
            }
        }
        return this._shouldRender;
    }
    _onElementScrollPosition(elementScrollPosition) {
        if (this._scrollbarState.setScrollPosition(elementScrollPosition)) {
            this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
            this._shouldRender = true;
            if (!this._lazyRender) {
                this.render();
            }
        }
        return this._shouldRender;
    }
    // ----------------- rendering
    beginReveal() {
        this._visibilityController.setShouldBeVisible(true);
    }
    beginHide() {
        this._visibilityController.setShouldBeVisible(false);
    }
    render() {
        if (!this._shouldRender) {
            return;
        }
        this._shouldRender = false;
        this._renderDomNode(this._scrollbarState.getRectangleLargeSize(), this._scrollbarState.getRectangleSmallSize());
        this._updateSlider(this._scrollbarState.getSliderSize(), this._scrollbarState.getArrowSize() + this._scrollbarState.getSliderPosition());
    }
    // ----------------- DOM events
    _domNodePointerDown(e) {
        if (e.target !== this.domNode.domNode) {
            return;
        }
        this._onPointerDown(e);
    }
    delegatePointerDown(e) {
        const domTop = this.domNode.domNode.getClientRects()[0].top;
        const sliderStart = domTop + this._scrollbarState.getSliderPosition();
        const sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize();
        const pointerPos = this._sliderPointerPosition(e);
        if (sliderStart <= pointerPos && pointerPos <= sliderStop) {
            // Act as if it was a pointer down on the slider
            if (e.button === 0) {
                e.preventDefault();
                this._sliderPointerDown(e);
            }
        }
        else {
            // Act as if it was a pointer down on the scrollbar
            this._onPointerDown(e);
        }
    }
    _onPointerDown(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 = getDomNodePagePosition(this.domNode.domNode);
            offsetX = e.pageX - domNodePosition.left;
            offsetY = e.pageY - domNodePosition.top;
        }
        const offset = this._pointerDownRelativePosition(offsetX, offsetY);
        this._setDesiredScrollPositionNow(this._scrollByPage
            ? this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(offset)
            : this._scrollbarState.getDesiredScrollPositionFromOffset(offset));
        if (e.button === 0) {
            // left button
            e.preventDefault();
            this._sliderPointerDown(e);
        }
    }
    _sliderPointerDown(e) {
        if (!e.target || !(e.target instanceof Element)) {
            return;
        }
        const initialPointerPosition = this._sliderPointerPosition(e);
        const initialPointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(e);
        const initialScrollbarState = this._scrollbarState.clone();
        this.slider.toggleClassName('active', true);
        this._pointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => {
            const pointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(pointerMoveData);
            const pointerOrthogonalDelta = Math.abs(pointerOrthogonalPosition - initialPointerOrthogonalPosition);
            if (isWindows && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE) {
                // The pointer has wondered away from the scrollbar => reset dragging
                this._setDesiredScrollPositionNow(initialScrollbarState.getScrollPosition());
                return;
            }
            const pointerPosition = this._sliderPointerPosition(pointerMoveData);
            const pointerDelta = pointerPosition - initialPointerPosition;
            this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(pointerDelta));
        }, () => {
            this.slider.toggleClassName('active', false);
            this._host.onDragEnd();
        });
        this._host.onDragStart();
    }
    _setDesiredScrollPositionNow(_desiredScrollPosition) {
        const desiredScrollPosition = {};
        this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition);
        this._scrollable.setScrollPositionNow(desiredScrollPosition);
    }
    updateScrollbarSize(scrollbarSize) {
        this._updateScrollbarSize(scrollbarSize);
        this._scrollbarState.setScrollbarSize(scrollbarSize);
        this._shouldRender = true;
        if (!this._lazyRender) {
            this.render();
        }
    }
    isNeeded() {
        return this._scrollbarState.isNeeded();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/scrollbar/scrollbarState.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/**
 * The minimal size of the slider (such that it can still be clickable) -- it is artificially enlarged.
 */
const MINIMUM_SLIDER_SIZE = 20;
class ScrollbarState {
    constructor(arrowSize, scrollbarSize, oppositeScrollbarSize, visibleSize, scrollSize, scrollPosition) {
        this._scrollbarSize = Math.round(scrollbarSize);
        this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);
        this._arrowSize = Math.round(arrowSize);
        this._visibleSize = visibleSize;
        this._scrollSize = scrollSize;
        this._scrollPosition = scrollPosition;
        this._computedAvailableSize = 0;
        this._computedIsNeeded = false;
        this._computedSliderSize = 0;
        this._computedSliderRatio = 0;
        this._computedSliderPosition = 0;
        this._refreshComputedValues();
    }
    clone() {
        return new ScrollbarState(this._arrowSize, this._scrollbarSize, this._oppositeScrollbarSize, this._visibleSize, this._scrollSize, this._scrollPosition);
    }
    setVisibleSize(visibleSize) {
        const iVisibleSize = Math.round(visibleSize);
        if (this._visibleSize !== iVisibleSize) {
            this._visibleSize = iVisibleSize;
            this._refreshComputedValues();
            return true;
        }
        return false;
    }
    setScrollSize(scrollSize) {
        const iScrollSize = Math.round(scrollSize);
        if (this._scrollSize !== iScrollSize) {
            this._scrollSize = iScrollSize;
            this._refreshComputedValues();
            return true;
        }
        return false;
    }
    setScrollPosition(scrollPosition) {
        const iScrollPosition = Math.round(scrollPosition);
        if (this._scrollPosition !== iScrollPosition) {
            this._scrollPosition = iScrollPosition;
            this._refreshComputedValues();
            return true;
        }
        return false;
    }
    setScrollbarSize(scrollbarSize) {
        this._scrollbarSize = Math.round(scrollbarSize);
    }
    setOppositeScrollbarSize(oppositeScrollbarSize) {
        this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);
    }
    static _computeValues(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) {
            // There is no need for a slider
            return {
                computedAvailableSize: Math.round(computedAvailableSize),
                computedIsNeeded: computedIsNeeded,
                computedSliderSize: Math.round(computedRepresentableSize),
                computedSliderRatio: 0,
                computedSliderPosition: 0,
            };
        }
        // We must artificially increase the size of the slider if needed, since the slider would be too small to grab with the mouse otherwise
        const computedSliderSize = Math.round(Math.max(MINIMUM_SLIDER_SIZE, Math.floor(visibleSize * computedRepresentableSize / scrollSize)));
        // The slider can move from 0 to `computedRepresentableSize` - `computedSliderSize`
        // in the same way `scrollPosition` can move from 0 to `scrollSize` - `visibleSize`.
        const computedSliderRatio = (computedRepresentableSize - computedSliderSize) / (scrollSize - visibleSize);
        const computedSliderPosition = (scrollPosition * computedSliderRatio);
        return {
            computedAvailableSize: Math.round(computedAvailableSize),
            computedIsNeeded: computedIsNeeded,
            computedSliderSize: Math.round(computedSliderSize),
            computedSliderRatio: computedSliderRatio,
            computedSliderPosition: Math.round(computedSliderPosition),
        };
    }
    _refreshComputedValues() {
        const r = ScrollbarState._computeValues(this._oppositeScrollbarSize, this._arrowSize, this._visibleSize, this._scrollSize, this._scrollPosition);
        this._computedAvailableSize = r.computedAvailableSize;
        this._computedIsNeeded = r.computedIsNeeded;
        this._computedSliderSize = r.computedSliderSize;
        this._computedSliderRatio = r.computedSliderRatio;
        this._computedSliderPosition = r.computedSliderPosition;
    }
    getArrowSize() {
        return this._arrowSize;
    }
    getScrollPosition() {
        return this._scrollPosition;
    }
    getRectangleLargeSize() {
        return this._computedAvailableSize;
    }
    getRectangleSmallSize() {
        return this._scrollbarSize;
    }
    isNeeded() {
        return this._computedIsNeeded;
    }
    getSliderSize() {
        return this._computedSliderSize;
    }
    getSliderPosition() {
        return this._computedSliderPosition;
    }
    /**
     * 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._computedIsNeeded) {
            // no need for a slider
            return 0;
        }
        const desiredSliderPosition = offset - this._arrowSize - this._computedSliderSize / 2;
        return Math.round(desiredSliderPosition / this._computedSliderRatio);
    }
    /**
     * 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._computedIsNeeded) {
            // no need for a slider
            return 0;
        }
        const correctedOffset = offset - this._arrowSize; // compensate if has arrows
        let desiredScrollPosition = this._scrollPosition;
        if (correctedOffset < this._computedSliderPosition) {
            desiredScrollPosition -= this._visibleSize; // page up/left
        }
        else {
            desiredScrollPosition += this._visibleSize; // page down/right
        }
        return desiredScrollPosition;
    }
    /**
     * Compute a desired `scrollPosition` such that the slider moves by `delta`.
     */
    getDesiredScrollPositionFromDelta(delta) {
        if (!this._computedIsNeeded) {
            // no need for a slider
            return 0;
        }
        const desiredSliderPosition = this._computedSliderPosition + delta;
        return Math.round(desiredSliderPosition / this._computedSliderRatio);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/scrollbar/horizontalScrollbar.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class HorizontalScrollbar extends AbstractScrollbar {
    constructor(scrollable, options, host) {
        const scrollDimensions = scrollable.getScrollDimensions();
        const scrollPosition = scrollable.getCurrentScrollPosition();
        super({
            lazyRender: options.lazyRender,
            host: host,
            scrollbarState: new ScrollbarState((options.horizontalHasArrows ? options.arrowSize : 0), (options.horizontal === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.horizontalScrollbarSize), (options.vertical === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.verticalScrollbarSize), scrollDimensions.width, scrollDimensions.scrollWidth, scrollPosition.scrollLeft),
            visibility: options.horizontal,
            extraScrollbarClassName: 'horizontal',
            scrollable: scrollable,
            scrollByPage: options.scrollByPage
        });
        if (options.horizontalHasArrows) {
            const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;
            const scrollbarDelta = (options.horizontalScrollbarSize - ARROW_IMG_SIZE) / 2;
            this._createArrow({
                className: 'scra',
                icon: Codicon.scrollbarButtonLeft,
                top: scrollbarDelta,
                left: arrowDelta,
                bottom: undefined,
                right: undefined,
                bgWidth: options.arrowSize,
                bgHeight: options.horizontalScrollbarSize,
                onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 1, 0)),
            });
            this._createArrow({
                className: 'scra',
                icon: Codicon.scrollbarButtonRight,
                top: scrollbarDelta,
                left: undefined,
                bottom: undefined,
                right: arrowDelta,
                bgWidth: options.arrowSize,
                bgHeight: options.horizontalScrollbarSize,
                onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, -1, 0)),
            });
        }
        this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, undefined, options.horizontalSliderSize);
    }
    _updateSlider(sliderSize, sliderPosition) {
        this.slider.setWidth(sliderSize);
        this.slider.setLeft(sliderPosition);
    }
    _renderDomNode(largeSize, smallSize) {
        this.domNode.setWidth(largeSize);
        this.domNode.setHeight(smallSize);
        this.domNode.setLeft(0);
        this.domNode.setBottom(0);
    }
    onDidScroll(e) {
        this._shouldRender = this._onElementScrollSize(e.scrollWidth) || this._shouldRender;
        this._shouldRender = this._onElementScrollPosition(e.scrollLeft) || this._shouldRender;
        this._shouldRender = this._onElementSize(e.width) || this._shouldRender;
        return this._shouldRender;
    }
    _pointerDownRelativePosition(offsetX, offsetY) {
        return offsetX;
    }
    _sliderPointerPosition(e) {
        return e.pageX;
    }
    _sliderOrthogonalPointerPosition(e) {
        return e.pageY;
    }
    _updateScrollbarSize(size) {
        this.slider.setHeight(size);
    }
    writeScrollPosition(target, scrollPosition) {
        target.scrollLeft = scrollPosition;
    }
    updateOptions(options) {
        this.updateScrollbarSize(options.horizontal === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.horizontalScrollbarSize);
        this._scrollbarState.setOppositeScrollbarSize(options.vertical === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.verticalScrollbarSize);
        this._visibilityController.setVisibility(options.horizontal);
        this._scrollByPage = options.scrollByPage;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/scrollbar/verticalScrollbar.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class VerticalScrollbar extends AbstractScrollbar {
    constructor(scrollable, options, host) {
        const scrollDimensions = scrollable.getScrollDimensions();
        const scrollPosition = scrollable.getCurrentScrollPosition();
        super({
            lazyRender: options.lazyRender,
            host: host,
            scrollbarState: new ScrollbarState((options.verticalHasArrows ? options.arrowSize : 0), (options.vertical === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.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: options.vertical,
            extraScrollbarClassName: 'vertical',
            scrollable: scrollable,
            scrollByPage: options.scrollByPage
        });
        if (options.verticalHasArrows) {
            const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;
            const scrollbarDelta = (options.verticalScrollbarSize - ARROW_IMG_SIZE) / 2;
            this._createArrow({
                className: 'scra',
                icon: Codicon.scrollbarButtonUp,
                top: arrowDelta,
                left: scrollbarDelta,
                bottom: undefined,
                right: undefined,
                bgWidth: options.verticalScrollbarSize,
                bgHeight: options.arrowSize,
                onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, 1)),
            });
            this._createArrow({
                className: 'scra',
                icon: Codicon.scrollbarButtonDown,
                top: undefined,
                left: scrollbarDelta,
                bottom: arrowDelta,
                right: undefined,
                bgWidth: options.verticalScrollbarSize,
                bgHeight: options.arrowSize,
                onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, -1)),
            });
        }
        this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, undefined);
    }
    _updateSlider(sliderSize, sliderPosition) {
        this.slider.setHeight(sliderSize);
        this.slider.setTop(sliderPosition);
    }
    _renderDomNode(largeSize, smallSize) {
        this.domNode.setWidth(smallSize);
        this.domNode.setHeight(largeSize);
        this.domNode.setRight(0);
        this.domNode.setTop(0);
    }
    onDidScroll(e) {
        this._shouldRender = this._onElementScrollSize(e.scrollHeight) || this._shouldRender;
        this._shouldRender = this._onElementScrollPosition(e.scrollTop) || this._shouldRender;
        this._shouldRender = this._onElementSize(e.height) || this._shouldRender;
        return this._shouldRender;
    }
    _pointerDownRelativePosition(offsetX, offsetY) {
        return offsetY;
    }
    _sliderPointerPosition(e) {
        return e.pageY;
    }
    _sliderOrthogonalPointerPosition(e) {
        return e.pageX;
    }
    _updateScrollbarSize(size) {
        this.slider.setWidth(size);
    }
    writeScrollPosition(target, scrollPosition) {
        target.scrollTop = scrollPosition;
    }
    updateOptions(options) {
        this.updateScrollbarSize(options.vertical === 2 /* ScrollbarVisibility.Hidden */ ? 0 : options.verticalScrollbarSize);
        // give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom
        this._scrollbarState.setOppositeScrollbarSize(0);
        this._visibilityController.setVisibility(options.vertical);
        this._scrollByPage = options.scrollByPage;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/scrollable.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class ScrollState {
    constructor(_forceIntegerValues, width, scrollWidth, scrollLeft, height, scrollHeight, scrollTop) {
        this._forceIntegerValues = _forceIntegerValues;
        this._scrollStateBrand = undefined;
        if (this._forceIntegerValues) {
            width = width | 0;
            scrollWidth = scrollWidth | 0;
            scrollLeft = scrollLeft | 0;
            height = height | 0;
            scrollHeight = scrollHeight | 0;
            scrollTop = scrollTop | 0;
        }
        this.rawScrollLeft = scrollLeft; // before validation
        this.rawScrollTop = scrollTop; // before validation
        if (width < 0) {
            width = 0;
        }
        if (scrollLeft + width > scrollWidth) {
            scrollLeft = scrollWidth - width;
        }
        if (scrollLeft < 0) {
            scrollLeft = 0;
        }
        if (height < 0) {
            height = 0;
        }
        if (scrollTop + height > scrollHeight) {
            scrollTop = scrollHeight - height;
        }
        if (scrollTop < 0) {
            scrollTop = 0;
        }
        this.width = width;
        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 ScrollState(this._forceIntegerValues, (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 ScrollState(this._forceIntegerValues, 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: 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: widthChanged,
            scrollWidthChanged: scrollWidthChanged,
            scrollLeftChanged: scrollLeftChanged,
            heightChanged: heightChanged,
            scrollHeightChanged: scrollHeightChanged,
            scrollTopChanged: scrollTopChanged,
        };
    }
}
class Scrollable extends Disposable {
    constructor(options) {
        super();
        this._scrollableBrand = undefined;
        this._onScroll = this._register(new Emitter());
        this.onScroll = this._onScroll.event;
        this._smoothScrollDuration = options.smoothScrollDuration;
        this._scheduleAtNextAnimationFrame = options.scheduleAtNextAnimationFrame;
        this._state = new ScrollState(options.forceIntegerValues, 0, 0, 0, 0, 0, 0);
        this._smoothScrolling = null;
    }
    dispose() {
        if (this._smoothScrolling) {
            this._smoothScrolling.dispose();
            this._smoothScrolling = null;
        }
        super.dispose();
    }
    setSmoothScrollDuration(smoothScrollDuration) {
        this._smoothScrollDuration = smoothScrollDuration;
    }
    validateScrollPosition(scrollPosition) {
        return this._state.withScrollPosition(scrollPosition);
    }
    getScrollDimensions() {
        return this._state;
    }
    setScrollDimensions(dimensions, useRawScrollPositions) {
        var _a;
        const newState = this._state.withScrollDimensions(dimensions, useRawScrollPositions);
        this._setState(newState, Boolean(this._smoothScrolling));
        // Validate outstanding animated scroll position target
        (_a = this._smoothScrolling) === null || _a === void 0 ? void 0 : _a.acceptScrollDimensions(this._state);
    }
    /**
     * 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._smoothScrolling) {
            return this._smoothScrolling.to;
        }
        return this._state;
    }
    /**
     * 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._state;
    }
    setScrollPositionNow(update) {
        // no smooth scrolling requested
        const newState = this._state.withScrollPosition(update);
        // Terminate any outstanding smooth scrolling
        if (this._smoothScrolling) {
            this._smoothScrolling.dispose();
            this._smoothScrolling = null;
        }
        this._setState(newState, false);
    }
    setScrollPositionSmooth(update, reuseAnimation) {
        if (this._smoothScrollDuration === 0) {
            // Smooth scrolling not supported.
            return this.setScrollPositionNow(update);
        }
        if (this._smoothScrolling) {
            // Combine our pending scrollLeft/scrollTop with incoming scrollLeft/scrollTop
            update = {
                scrollLeft: (typeof update.scrollLeft === 'undefined' ? this._smoothScrolling.to.scrollLeft : update.scrollLeft),
                scrollTop: (typeof update.scrollTop === 'undefined' ? this._smoothScrolling.to.scrollTop : update.scrollTop)
            };
            // Validate `update`
            const validTarget = this._state.withScrollPosition(update);
            if (this._smoothScrolling.to.scrollLeft === validTarget.scrollLeft && this._smoothScrolling.to.scrollTop === validTarget.scrollTop) {
                // No need to interrupt or extend the current animation since we're going to the same place
                return;
            }
            let newSmoothScrolling;
            if (reuseAnimation) {
                newSmoothScrolling = new SmoothScrollingOperation(this._smoothScrolling.from, validTarget, this._smoothScrolling.startTime, this._smoothScrolling.duration);
            }
            else {
                newSmoothScrolling = this._smoothScrolling.combine(this._state, validTarget, this._smoothScrollDuration);
            }
            this._smoothScrolling.dispose();
            this._smoothScrolling = newSmoothScrolling;
        }
        else {
            // Validate `update`
            const validTarget = this._state.withScrollPosition(update);
            this._smoothScrolling = SmoothScrollingOperation.start(this._state, validTarget, this._smoothScrollDuration);
        }
        // Begin smooth scrolling animation
        this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {
            if (!this._smoothScrolling) {
                return;
            }
            this._smoothScrolling.animationFrameDisposable = null;
            this._performSmoothScrolling();
        });
    }
    _performSmoothScrolling() {
        if (!this._smoothScrolling) {
            return;
        }
        const update = this._smoothScrolling.tick();
        const newState = this._state.withScrollPosition(update);
        this._setState(newState, true);
        if (!this._smoothScrolling) {
            // Looks like someone canceled the smooth scrolling
            // from the scroll event handler
            return;
        }
        if (update.isDone) {
            this._smoothScrolling.dispose();
            this._smoothScrolling = null;
            return;
        }
        // Continue smooth scrolling animation
        this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {
            if (!this._smoothScrolling) {
                return;
            }
            this._smoothScrolling.animationFrameDisposable = null;
            this._performSmoothScrolling();
        });
    }
    _setState(newState, inSmoothScrolling) {
        const oldState = this._state;
        if (oldState.equals(newState)) {
            // no change
            return;
        }
        this._state = newState;
        this._onScroll.fire(this._state.createScrollEvent(oldState, inSmoothScrolling));
    }
}
class SmoothScrollingUpdate {
    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));
    };
}
class SmoothScrollingOperation {
    constructor(from, to, startTime, duration) {
        this.from = from;
        this.to = to;
        this.duration = duration;
        this.startTime = startTime;
        this.animationFrameDisposable = null;
        this._initAnimations();
    }
    _initAnimations() {
        this.scrollLeft = this._initAnimation(this.from.scrollLeft, this.to.scrollLeft, this.to.width);
        this.scrollTop = this._initAnimation(this.from.scrollTop, this.to.scrollTop, this.to.height);
    }
    _initAnimation(from, to, viewportSize) {
        const delta = Math.abs(from - to);
        if (delta > 2.5 * viewportSize) {
            let stop1, stop2;
            if (from < to) {
                // scroll to 75% of the viewportSize
                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._initAnimations();
    }
    tick() {
        return this._tick(Date.now());
    }
    _tick(now) {
        const completion = (now - this.startTime) / this.duration;
        if (completion < 1) {
            const newScrollLeft = this.scrollLeft(completion);
            const newScrollTop = this.scrollTop(completion);
            return new SmoothScrollingUpdate(newScrollLeft, newScrollTop, false);
        }
        return new SmoothScrollingUpdate(this.to.scrollLeft, this.to.scrollTop, true);
    }
    combine(from, to, duration) {
        return SmoothScrollingOperation.start(from, to, duration);
    }
    static start(from, to, duration) {
        // +10 / -10 : pretend the animation already started for a quicker response to a scroll request
        duration = duration + 10;
        const startTime = Date.now() - 10;
        return new SmoothScrollingOperation(from, to, startTime, duration);
    }
}
function easeInCubic(t) {
    return Math.pow(t, 3);
}
function easeOutCubic(t) {
    return 1 - easeInCubic(1 - t);
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/scrollbar/media/scrollbars.css
var scrollbars = __webpack_require__(72915);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/scrollbar/media/scrollbars.css

      
      
      
      
      
      
      
      
      

var scrollbars_options = {};

scrollbars_options.styleTagTransform = (styleTagTransform_default());
scrollbars_options.setAttributes = (setAttributesWithoutAttributes_default());

      scrollbars_options.insert = insertBySelector_default().bind(null, "head");
    
scrollbars_options.domAPI = (styleDomAPI_default());
scrollbars_options.insertStyleElement = (insertStyleElement_default());

var scrollbars_update = injectStylesIntoStyleTag_default()(scrollbars/* default */.A, scrollbars_options);




       /* harmony default export */ const media_scrollbars = (scrollbars/* default */.A && scrollbars/* default */.A.locals ? scrollbars/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/scrollbar/scrollableElement.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/













const HIDE_TIMEOUT = 500;
const SCROLL_WHEEL_SENSITIVITY = 50;
const SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED = true;
class MouseWheelClassifierItem {
    constructor(timestamp, deltaX, deltaY) {
        this.timestamp = timestamp;
        this.deltaX = deltaX;
        this.deltaY = deltaY;
        this.score = 0;
    }
}
class MouseWheelClassifier {
    constructor() {
        this._capacity = 5;
        this._memory = [];
        this._front = -1;
        this._rear = -1;
    }
    isPhysicalMouseWheel() {
        if (this._front === -1 && this._rear === -1) {
            // no elements
            return false;
        }
        // 0.5 * last + 0.25 * 2nd last + 0.125 * 3rd last + ...
        let remainingInfluence = 1;
        let score = 0;
        let iteration = 1;
        let index = this._rear;
        do {
            const influence = (index === this._front ? remainingInfluence : Math.pow(2, -iteration));
            remainingInfluence -= influence;
            score += this._memory[index].score * influence;
            if (index === this._front) {
                break;
            }
            index = (this._capacity + index - 1) % this._capacity;
            iteration++;
        } while (true);
        return (score <= 0.5);
    }
    accept(timestamp, deltaX, deltaY) {
        const item = new MouseWheelClassifierItem(timestamp, deltaX, deltaY);
        item.score = this._computeScore(item);
        if (this._front === -1 && this._rear === -1) {
            this._memory[0] = item;
            this._front = 0;
            this._rear = 0;
        }
        else {
            this._rear = (this._rear + 1) % this._capacity;
            if (this._rear === this._front) {
                // Drop oldest
                this._front = (this._front + 1) % this._capacity;
            }
            this._memory[this._rear] = item;
        }
    }
    /**
     * 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.
     */
    _computeScore(item) {
        if (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) {
            // both axes exercised => definitely not a physical mouse wheel
            return 1;
        }
        let score = 0.5;
        const prev = (this._front === -1 && this._rear === -1 ? null : this._memory[this._rear]);
        if (prev) {
            // const deltaT = item.timestamp - prev.timestamp;
            // if (deltaT < 1000 / 30) {
            // 	// sooner than X times per second => indicator that this is not a physical mouse wheel
            // 	score += 0.25;
            // }
            // if (item.deltaX === prev.deltaX && item.deltaY === prev.deltaY) {
            // 	// equal amplitude => indicator that this is a physical mouse wheel
            // 	score -= 0.25;
            // }
        }
        if (!this._isAlmostInt(item.deltaX) || !this._isAlmostInt(item.deltaY)) {
            // non-integer deltas => indicator that this is not a physical mouse wheel
            score += 0.25;
        }
        return Math.min(Math.max(score, 0), 1);
    }
    _isAlmostInt(value) {
        const delta = Math.abs(Math.round(value) - value);
        return (delta < 0.01);
    }
}
MouseWheelClassifier.INSTANCE = new MouseWheelClassifier();
class AbstractScrollableElement extends Widget {
    constructor(element, options, scrollable) {
        super();
        this._onScroll = this._register(new Emitter());
        this.onScroll = this._onScroll.event;
        this._onWillScroll = this._register(new Emitter());
        element.style.overflow = 'hidden';
        this._options = resolveOptions(options);
        this._scrollable = scrollable;
        this._register(this._scrollable.onScroll((e) => {
            this._onWillScroll.fire(e);
            this._onDidScroll(e);
            this._onScroll.fire(e);
        }));
        const scrollbarHost = {
            onMouseWheel: (mouseWheelEvent) => this._onMouseWheel(mouseWheelEvent),
            onDragStart: () => this._onDragStart(),
            onDragEnd: () => this._onDragEnd(),
        };
        this._verticalScrollbar = this._register(new VerticalScrollbar(this._scrollable, this._options, scrollbarHost));
        this._horizontalScrollbar = this._register(new HorizontalScrollbar(this._scrollable, this._options, scrollbarHost));
        this._domNode = document.createElement('div');
        this._domNode.className = 'monaco-scrollable-element ' + this._options.className;
        this._domNode.setAttribute('role', 'presentation');
        this._domNode.style.position = 'relative';
        this._domNode.style.overflow = 'hidden';
        this._domNode.appendChild(element);
        this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode);
        this._domNode.appendChild(this._verticalScrollbar.domNode.domNode);
        if (this._options.useShadows) {
            this._leftShadowDomNode = createFastDomNode(document.createElement('div'));
            this._leftShadowDomNode.setClassName('shadow');
            this._domNode.appendChild(this._leftShadowDomNode.domNode);
            this._topShadowDomNode = createFastDomNode(document.createElement('div'));
            this._topShadowDomNode.setClassName('shadow');
            this._domNode.appendChild(this._topShadowDomNode.domNode);
            this._topLeftShadowDomNode = createFastDomNode(document.createElement('div'));
            this._topLeftShadowDomNode.setClassName('shadow');
            this._domNode.appendChild(this._topLeftShadowDomNode.domNode);
        }
        else {
            this._leftShadowDomNode = null;
            this._topShadowDomNode = null;
            this._topLeftShadowDomNode = null;
        }
        this._listenOnDomNode = this._options.listenOnDomNode || this._domNode;
        this._mouseWheelToDispose = [];
        this._setListeningToMouseWheel(this._options.handleMouseWheel);
        this.onmouseover(this._listenOnDomNode, (e) => this._onMouseOver(e));
        this.onmouseleave(this._listenOnDomNode, (e) => this._onMouseLeave(e));
        this._hideTimeout = this._register(new TimeoutTimer());
        this._isDragging = false;
        this._mouseIsOver = false;
        this._shouldRender = true;
        this._revealOnScroll = true;
    }
    get options() {
        return this._options;
    }
    dispose() {
        this._mouseWheelToDispose = dispose(this._mouseWheelToDispose);
        super.dispose();
    }
    /**
     * Get the generated 'scrollable' dom node
     */
    getDomNode() {
        return this._domNode;
    }
    getOverviewRulerLayoutInfo() {
        return {
            parent: this._domNode,
            insertBefore: this._verticalScrollbar.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._verticalScrollbar.delegatePointerDown(browserEvent);
    }
    getScrollDimensions() {
        return this._scrollable.getScrollDimensions();
    }
    setScrollDimensions(dimensions) {
        this._scrollable.setScrollDimensions(dimensions, false);
    }
    /**
     * Update the class name of the scrollable element.
     */
    updateClassName(newClassName) {
        this._options.className = newClassName;
        // Defaults are different on Macs
        if (isMacintosh) {
            this._options.className += ' mac';
        }
        this._domNode.className = 'monaco-scrollable-element ' + this._options.className;
    }
    /**
     * Update configuration options for the scrollbar.
     */
    updateOptions(newOptions) {
        if (typeof newOptions.handleMouseWheel !== 'undefined') {
            this._options.handleMouseWheel = newOptions.handleMouseWheel;
            this._setListeningToMouseWheel(this._options.handleMouseWheel);
        }
        if (typeof newOptions.mouseWheelScrollSensitivity !== 'undefined') {
            this._options.mouseWheelScrollSensitivity = newOptions.mouseWheelScrollSensitivity;
        }
        if (typeof newOptions.fastScrollSensitivity !== 'undefined') {
            this._options.fastScrollSensitivity = newOptions.fastScrollSensitivity;
        }
        if (typeof newOptions.scrollPredominantAxis !== 'undefined') {
            this._options.scrollPredominantAxis = newOptions.scrollPredominantAxis;
        }
        if (typeof newOptions.horizontal !== 'undefined') {
            this._options.horizontal = newOptions.horizontal;
        }
        if (typeof newOptions.vertical !== 'undefined') {
            this._options.vertical = newOptions.vertical;
        }
        if (typeof newOptions.horizontalScrollbarSize !== 'undefined') {
            this._options.horizontalScrollbarSize = newOptions.horizontalScrollbarSize;
        }
        if (typeof newOptions.verticalScrollbarSize !== 'undefined') {
            this._options.verticalScrollbarSize = newOptions.verticalScrollbarSize;
        }
        if (typeof newOptions.scrollByPage !== 'undefined') {
            this._options.scrollByPage = newOptions.scrollByPage;
        }
        this._horizontalScrollbar.updateOptions(this._options);
        this._verticalScrollbar.updateOptions(this._options);
        if (!this._options.lazyRender) {
            this._render();
        }
    }
    // -------------------- mouse wheel scrolling --------------------
    _setListeningToMouseWheel(shouldListen) {
        const isListening = (this._mouseWheelToDispose.length > 0);
        if (isListening === shouldListen) {
            // No change
            return;
        }
        // Stop listening (if necessary)
        this._mouseWheelToDispose = dispose(this._mouseWheelToDispose);
        // Start listening (if necessary)
        if (shouldListen) {
            const onMouseWheel = (browserEvent) => {
                this._onMouseWheel(new StandardWheelEvent(browserEvent));
            };
            this._mouseWheelToDispose.push(addDisposableListener(this._listenOnDomNode, EventType.MOUSE_WHEEL, onMouseWheel, { passive: false }));
        }
    }
    _onMouseWheel(e) {
        const classifier = MouseWheelClassifier.INSTANCE;
        if (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED) {
            const osZoomFactor = window.devicePixelRatio / getZoomFactor();
            if (isWindows || isLinux) {
                // On Windows and Linux, the incoming delta events are multiplied with the OS zoom factor.
                // The OS zoom factor can be reverse engineered by using the device pixel ratio and the configured zoom factor into account.
                classifier.accept(Date.now(), e.deltaX / osZoomFactor, e.deltaY / osZoomFactor);
            }
            else {
                classifier.accept(Date.now(), e.deltaX, e.deltaY);
            }
        }
        // console.log(`${Date.now()}, ${e.deltaY}, ${e.deltaX}`);
        let didScroll = false;
        if (e.deltaY || e.deltaX) {
            let deltaY = e.deltaY * this._options.mouseWheelScrollSensitivity;
            let deltaX = e.deltaX * this._options.mouseWheelScrollSensitivity;
            if (this._options.scrollPredominantAxis) {
                if (Math.abs(deltaY) >= Math.abs(deltaX)) {
                    deltaX = 0;
                }
                else {
                    deltaY = 0;
                }
            }
            if (this._options.flipAxes) {
                [deltaY, deltaX] = [deltaX, deltaY];
            }
            // Convert vertical scrolling to horizontal if shift is held, this
            // is handled at a higher level on Mac
            const shiftConvert = !isMacintosh && e.browserEvent && e.browserEvent.shiftKey;
            if ((this._options.scrollYToX || shiftConvert) && !deltaX) {
                deltaX = deltaY;
                deltaY = 0;
            }
            if (e.browserEvent && e.browserEvent.altKey) {
                // fastScrolling
                deltaX = deltaX * this._options.fastScrollSensitivity;
                deltaY = deltaY * this._options.fastScrollSensitivity;
            }
            const futureScrollPosition = this._scrollable.getFutureScrollPosition();
            let desiredScrollPosition = {};
            if (deltaY) {
                const deltaScrollTop = SCROLL_WHEEL_SENSITIVITY * deltaY;
                // Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll
                const desiredScrollTop = futureScrollPosition.scrollTop - (deltaScrollTop < 0 ? Math.floor(deltaScrollTop) : Math.ceil(deltaScrollTop));
                this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop);
            }
            if (deltaX) {
                const deltaScrollLeft = SCROLL_WHEEL_SENSITIVITY * deltaX;
                // Here we convert values such as -0.3 to -1 or 0.3 to 1, otherwise low speed scrolling will never scroll
                const desiredScrollLeft = futureScrollPosition.scrollLeft - (deltaScrollLeft < 0 ? Math.floor(deltaScrollLeft) : Math.ceil(deltaScrollLeft));
                this._horizontalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollLeft);
            }
            // Check that we are scrolling towards a location which is valid
            desiredScrollPosition = this._scrollable.validateScrollPosition(desiredScrollPosition);
            if (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) {
                const canPerformSmoothScroll = (SCROLL_WHEEL_SMOOTH_SCROLL_ENABLED
                    && this._options.mouseWheelSmoothScroll
                    && classifier.isPhysicalMouseWheel());
                if (canPerformSmoothScroll) {
                    this._scrollable.setScrollPositionSmooth(desiredScrollPosition);
                }
                else {
                    this._scrollable.setScrollPositionNow(desiredScrollPosition);
                }
                didScroll = true;
            }
        }
        let consumeMouseWheel = didScroll;
        if (!consumeMouseWheel && this._options.alwaysConsumeMouseWheel) {
            consumeMouseWheel = true;
        }
        if (!consumeMouseWheel && this._options.consumeMouseWheelIfScrollbarIsNeeded && (this._verticalScrollbar.isNeeded() || this._horizontalScrollbar.isNeeded())) {
            consumeMouseWheel = true;
        }
        if (consumeMouseWheel) {
            e.preventDefault();
            e.stopPropagation();
        }
    }
    _onDidScroll(e) {
        this._shouldRender = this._horizontalScrollbar.onDidScroll(e) || this._shouldRender;
        this._shouldRender = this._verticalScrollbar.onDidScroll(e) || this._shouldRender;
        if (this._options.useShadows) {
            this._shouldRender = true;
        }
        if (this._revealOnScroll) {
            this._reveal();
        }
        if (!this._options.lazyRender) {
            this._render();
        }
    }
    /**
     * Render / mutate the DOM now.
     * Should be used together with the ctor option `lazyRender`.
     */
    renderNow() {
        if (!this._options.lazyRender) {
            throw new Error('Please use `lazyRender` together with `renderNow`!');
        }
        this._render();
    }
    _render() {
        if (!this._shouldRender) {
            return;
        }
        this._shouldRender = false;
        this._horizontalScrollbar.render();
        this._verticalScrollbar.render();
        if (this._options.useShadows) {
            const scrollState = this._scrollable.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._leftShadowDomNode.setClassName(`shadow${leftClassName}`);
            this._topShadowDomNode.setClassName(`shadow${topClassName}`);
            this._topLeftShadowDomNode.setClassName(`shadow${topLeftClassName}${topClassName}${leftClassName}`);
        }
    }
    // -------------------- fade in / fade out --------------------
    _onDragStart() {
        this._isDragging = true;
        this._reveal();
    }
    _onDragEnd() {
        this._isDragging = false;
        this._hide();
    }
    _onMouseLeave(e) {
        this._mouseIsOver = false;
        this._hide();
    }
    _onMouseOver(e) {
        this._mouseIsOver = true;
        this._reveal();
    }
    _reveal() {
        this._verticalScrollbar.beginReveal();
        this._horizontalScrollbar.beginReveal();
        this._scheduleHide();
    }
    _hide() {
        if (!this._mouseIsOver && !this._isDragging) {
            this._verticalScrollbar.beginHide();
            this._horizontalScrollbar.beginHide();
        }
    }
    _scheduleHide() {
        if (!this._mouseIsOver && !this._isDragging) {
            this._hideTimeout.cancelAndSet(() => this._hide(), HIDE_TIMEOUT);
        }
    }
}
class ScrollableElement extends AbstractScrollableElement {
    constructor(element, options) {
        options = options || {};
        options.mouseWheelSmoothScroll = false;
        const scrollable = new Scrollable({
            forceIntegerValues: true,
            smoothScrollDuration: 0,
            scheduleAtNextAnimationFrame: (callback) => scheduleAtNextAnimationFrame(callback)
        });
        super(element, options, scrollable);
        this._register(scrollable);
    }
    setScrollPosition(update) {
        this._scrollable.setScrollPositionNow(update);
    }
}
class SmoothScrollableElement extends AbstractScrollableElement {
    constructor(element, options, scrollable) {
        super(element, options, scrollable);
    }
    setScrollPosition(update) {
        if (update.reuseAnimation) {
            this._scrollable.setScrollPositionSmooth(update, update.reuseAnimation);
        }
        else {
            this._scrollable.setScrollPositionNow(update);
        }
    }
    getScrollPosition() {
        return this._scrollable.getCurrentScrollPosition();
    }
}
class DomScrollableElement extends AbstractScrollableElement {
    constructor(element, options) {
        options = options || {};
        options.mouseWheelSmoothScroll = false;
        const scrollable = new Scrollable({
            forceIntegerValues: false,
            smoothScrollDuration: 0,
            scheduleAtNextAnimationFrame: (callback) => scheduleAtNextAnimationFrame(callback)
        });
        super(element, options, scrollable);
        this._register(scrollable);
        this._element = element;
        this.onScroll((e) => {
            if (e.scrollTopChanged) {
                this._element.scrollTop = e.scrollTop;
            }
            if (e.scrollLeftChanged) {
                this._element.scrollLeft = e.scrollLeft;
            }
        });
        this.scanDomNode();
    }
    setScrollPosition(update) {
        this._scrollable.setScrollPositionNow(update);
    }
    getScrollPosition() {
        return this._scrollable.getCurrentScrollPosition();
    }
    scanDomNode() {
        // width, scrollLeft, scrollWidth, height, scrollTop, scrollHeight
        this.setScrollDimensions({
            width: this._element.clientWidth,
            scrollWidth: this._element.scrollWidth,
            height: this._element.clientHeight,
            scrollHeight: this._element.scrollHeight
        });
        this.setScrollPosition({
            scrollLeft: this._element.scrollLeft,
            scrollTop: this._element.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 /* ScrollbarVisibility.Auto */),
        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 /* ScrollbarVisibility.Auto */),
        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);
    // Defaults are different on Macs
    if (isMacintosh) {
        result.className += ' mac';
    }
    return result;
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/range.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var range_Range;
(function (Range) {
    /**
     * Returns the intersection between two ranges as a range itself.
     * Returns `{ start: 0, end: 0 }` if the intersection is empty.
     */
    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 };
    }
    Range.intersect = intersect;
    function isEmpty(range) {
        return range.end - range.start <= 0;
    }
    Range.isEmpty = isEmpty;
    function intersects(one, other) {
        return !isEmpty(intersect(one, other));
    }
    Range.intersects = intersects;
    function relativeComplement(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;
    }
    Range.relativeComplement = relativeComplement;
})(range_Range || (range_Range = {}));

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/list/rangeMap.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/**
 * Returns the intersection between a ranged group and a range.
 * Returns `[]` if the intersection is empty.
 */
function groupIntersect(range, groups) {
    const result = [];
    for (const r of groups) {
        if (range.start >= r.range.end) {
            continue;
        }
        if (range.end < r.range.start) {
            break;
        }
        const intersection = range_Range.intersect(range, r.range);
        if (range_Range.isEmpty(intersection)) {
            continue;
        }
        result.push({
            range: intersection,
            size: r.size
        });
    }
    return result;
}
/**
 * Shifts a range by that `much`.
 */
function shift({ start, end }, much) {
    return { start: start + much, end: end + much };
}
/**
 * Consolidates a collection of ranged groups.
 *
 * Consolidation is the process of merging consecutive ranged groups
 * that share the same `size`.
 */
function consolidate(groups) {
    const result = [];
    let previousGroup = null;
    for (const group of groups) {
        const start = group.range.start;
        const end = group.range.end;
        const size = group.size;
        if (previousGroup && size === previousGroup.size) {
            previousGroup.range.end = end;
            continue;
        }
        previousGroup = { range: { start, end }, size };
        result.push(previousGroup);
    }
    return result;
}
/**
 * Concatenates several collections of ranged groups into a single
 * collection.
 */
function rangeMap_concat(...groups) {
    return consolidate(groups.reduce((r, g) => r.concat(g), []));
}
class RangeMap {
    constructor() {
        this.groups = [];
        this._size = 0;
    }
    splice(index, deleteCount, items = []) {
        const diff = items.length - deleteCount;
        const before = groupIntersect({ start: 0, end: index }, this.groups);
        const after = groupIntersect({ start: index + deleteCount, end: Number.POSITIVE_INFINITY }, this.groups)
            .map(g => ({ range: shift(g.range, diff), size: g.size }));
        const middle = items.map((item, i) => ({
            range: { start: index + i, end: index + i + 1 },
            size: item.size
        }));
        this.groups = rangeMap_concat(before, middle, after);
        this._size = this.groups.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.groups.length;
        if (!len) {
            return 0;
        }
        return this.groups[len - 1].range.end;
    }
    /**
     * Returns the sum of the sizes of all items in the range map.
     */
    get size() {
        return this._size;
    }
    /**
     * Returns the index of the item at the given position.
     */
    indexAt(position) {
        if (position < 0) {
            return -1;
        }
        let index = 0;
        let size = 0;
        for (const group of this.groups) {
            const count = group.range.end - group.range.start;
            const newSize = size + (count * group.size);
            if (position < newSize) {
                return index + Math.floor((position - size) / group.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 group of this.groups) {
            const groupCount = group.range.end - group.range.start;
            const newCount = count + groupCount;
            if (index < newCount) {
                return position + ((index - count) * group.size);
            }
            position += groupCount * group.size;
            count = newCount;
        }
        return -1;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/list/rowCache.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

function removeFromParent(element) {
    var _a;
    try {
        (_a = element.parentElement) === null || _a === void 0 ? void 0 : _a.removeChild(element);
    }
    catch (e) {
        // this will throw if this happens due to a blur event, nasty business
    }
}
class RowCache {
    constructor(renderers) {
        this.renderers = renderers;
        this.cache = new Map();
    }
    /**
     * Returns a row either by creating a new one or reusing
     * a previously released row which shares the same templateId.
     */
    alloc(templateId) {
        let result = this.getTemplateCache(templateId).pop();
        if (!result) {
            const domNode = dom_$('.monaco-list-row');
            const renderer = this.getRenderer(templateId);
            const templateData = renderer.renderTemplate(domNode);
            result = { domNode, templateId, templateData };
        }
        return result;
    }
    /**
     * Releases the row for eventual reuse.
     */
    release(row) {
        if (!row) {
            return;
        }
        this.releaseRow(row);
    }
    releaseRow(row) {
        const { domNode, templateId } = row;
        if (domNode) {
            domNode.classList.remove('scrolling');
            removeFromParent(domNode);
        }
        const cache = this.getTemplateCache(templateId);
        cache.push(row);
    }
    getTemplateCache(templateId) {
        let result = this.cache.get(templateId);
        if (!result) {
            result = [];
            this.cache.set(templateId, result);
        }
        return result;
    }
    dispose() {
        this.cache.forEach((cachedRows, templateId) => {
            for (const cachedRow of cachedRows) {
                const renderer = this.getRenderer(templateId);
                renderer.disposeTemplate(cachedRow.templateData);
                cachedRow.templateData = null;
            }
        });
        this.cache.clear();
    }
    getRenderer(templateId) {
        const renderer = this.renderers.get(templateId);
        if (!renderer) {
            throw new Error(`No renderer found for ${templateId}`);
        }
        return renderer;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/list/listView.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var listView_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};















const DefaultOptions = {
    useShadows: true,
    verticalScrollMode: 1 /* ScrollbarVisibility.Auto */,
    setRowLineHeight: true,
    setRowHeight: true,
    supportDynamicHeights: false,
    dnd: {
        getDragElements(e) { return [e]; },
        getDragURI() { return null; },
        onDragStart() { },
        onDragOver() { return false; },
        drop() { }
    },
    horizontalScrolling: false,
    transformOptimization: true,
    alwaysConsumeMouseWheel: true,
};
class ElementsDragAndDropData {
    constructor(elements) {
        this.elements = elements;
    }
    update() { }
    getData() {
        return this.elements;
    }
}
class ExternalElementsDragAndDropData {
    constructor(elements) {
        this.elements = elements;
    }
    update() { }
    getData() {
        return this.elements;
    }
}
class NativeDragAndDropData {
    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 i = 0; i < dataTransfer.files.length; i++) {
                const file = dataTransfer.files.item(i);
                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 equals(f1, f2);
    }
    return f1 === f2;
}
class ListViewAccessibilityProvider {
    constructor(accessibilityProvider) {
        if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getSetSize) {
            this.getSetSize = accessibilityProvider.getSetSize.bind(accessibilityProvider);
        }
        else {
            this.getSetSize = (e, i, l) => l;
        }
        if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getPosInSet) {
            this.getPosInSet = accessibilityProvider.getPosInSet.bind(accessibilityProvider);
        }
        else {
            this.getPosInSet = (e, i) => i + 1;
        }
        if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getRole) {
            this.getRole = accessibilityProvider.getRole.bind(accessibilityProvider);
        }
        else {
            this.getRole = _ => 'listitem';
        }
        if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.isChecked) {
            this.isChecked = accessibilityProvider.isChecked.bind(accessibilityProvider);
        }
        else {
            this.isChecked = _ => undefined;
        }
    }
}
/**
 * The {@link ListView} is a virtual scrolling engine.
 *
 * Given that it only renders elements within its viewport, it can hold large
 * collections of elements and stay very performant. The performance bottleneck
 * usually lies within the user's rendering code for each element.
 *
 * @remarks It is a low-level widget, not meant to be used directly. Refer to the
 * List widget instead.
 */
class ListView {
    constructor(container, virtualDelegate, renderers, options = DefaultOptions) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
        this.virtualDelegate = virtualDelegate;
        this.domId = `list_id_${++ListView.InstanceCount}`;
        this.renderers = new Map();
        this.renderWidth = 0;
        this._scrollHeight = 0;
        this.scrollableElementUpdateDisposable = null;
        this.scrollableElementWidthDelayer = new Delayer(50);
        this.splicing = false;
        this.dragOverAnimationStopDisposable = Disposable.None;
        this.dragOverMouseY = 0;
        this.canDrop = false;
        this.currentDragFeedbackDisposable = Disposable.None;
        this.onDragLeaveTimeout = Disposable.None;
        this.disposables = new DisposableStore();
        this._onDidChangeContentHeight = new Emitter();
        this._horizontalScrolling = false;
        if (options.horizontalScrolling && options.supportDynamicHeights) {
            throw new Error('Horizontal scrolling and dynamic heights not supported simultaneously');
        }
        this.items = [];
        this.itemId = 0;
        this.rangeMap = new RangeMap();
        for (const renderer of renderers) {
            this.renderers.set(renderer.templateId, renderer);
        }
        this.cache = this.disposables.add(new RowCache(this.renderers));
        this.lastRenderTop = 0;
        this.lastRenderHeight = 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 options.mouseSupport === 'boolean' ? options.mouseSupport : true);
        this._horizontalScrolling = (_a = options.horizontalScrolling) !== null && _a !== void 0 ? _a : DefaultOptions.horizontalScrolling;
        this.domNode.classList.toggle('horizontal-scrolling', this._horizontalScrolling);
        this.additionalScrollHeight = typeof options.additionalScrollHeight === 'undefined' ? 0 : options.additionalScrollHeight;
        this.accessibilityProvider = new ListViewAccessibilityProvider(options.accessibilityProvider);
        this.rowsContainer = document.createElement('div');
        this.rowsContainer.className = 'monaco-list-rows';
        const transformOptimization = (_b = options.transformOptimization) !== null && _b !== void 0 ? _b : DefaultOptions.transformOptimization;
        if (transformOptimization) {
            this.rowsContainer.style.transform = 'translate3d(0px, 0px, 0px)';
        }
        this.disposables.add(Gesture.addTarget(this.rowsContainer));
        this.scrollable = new Scrollable({
            forceIntegerValues: true,
            smoothScrollDuration: ((_c = options.smoothScrolling) !== null && _c !== void 0 ? _c : false) ? 125 : 0,
            scheduleAtNextAnimationFrame: cb => scheduleAtNextAnimationFrame(cb)
        });
        this.scrollableElement = this.disposables.add(new SmoothScrollableElement(this.rowsContainer, {
            alwaysConsumeMouseWheel: (_d = options.alwaysConsumeMouseWheel) !== null && _d !== void 0 ? _d : DefaultOptions.alwaysConsumeMouseWheel,
            horizontal: 1 /* ScrollbarVisibility.Auto */,
            vertical: (_e = options.verticalScrollMode) !== null && _e !== void 0 ? _e : DefaultOptions.verticalScrollMode,
            useShadows: (_f = options.useShadows) !== null && _f !== void 0 ? _f : DefaultOptions.useShadows,
            mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity,
            fastScrollSensitivity: options.fastScrollSensitivity
        }, this.scrollable));
        this.domNode.appendChild(this.scrollableElement.getDomNode());
        container.appendChild(this.domNode);
        this.scrollableElement.onScroll(this.onScroll, this, this.disposables);
        this.disposables.add(addDisposableListener(this.rowsContainer, touch_EventType.Change, e => this.onTouchChange(e)));
        // Prevent the monaco-scrollable-element from scrolling
        // https://github.com/microsoft/vscode/issues/44181
        this.disposables.add(addDisposableListener(this.scrollableElement.getDomNode(), 'scroll', e => e.target.scrollTop = 0));
        this.disposables.add(addDisposableListener(this.domNode, 'dragover', e => this.onDragOver(this.toDragEvent(e))));
        this.disposables.add(addDisposableListener(this.domNode, 'drop', e => this.onDrop(this.toDragEvent(e))));
        this.disposables.add(addDisposableListener(this.domNode, 'dragleave', e => this.onDragLeave(this.toDragEvent(e))));
        this.disposables.add(addDisposableListener(this.domNode, 'dragend', e => this.onDragEnd(e)));
        this.setRowLineHeight = (_g = options.setRowLineHeight) !== null && _g !== void 0 ? _g : DefaultOptions.setRowLineHeight;
        this.setRowHeight = (_h = options.setRowHeight) !== null && _h !== void 0 ? _h : DefaultOptions.setRowHeight;
        this.supportDynamicHeights = (_j = options.supportDynamicHeights) !== null && _j !== void 0 ? _j : DefaultOptions.supportDynamicHeights;
        this.dnd = (_k = options.dnd) !== null && _k !== void 0 ? _k : DefaultOptions.dnd;
        this.layout();
    }
    get contentHeight() { return this.rangeMap.size; }
    get horizontalScrolling() { return this._horizontalScrolling; }
    set horizontalScrolling(value) {
        if (value === this._horizontalScrolling) {
            return;
        }
        if (value && this.supportDynamicHeights) {
            throw new Error('Horizontal scrolling and dynamic heights not supported simultaneously');
        }
        this._horizontalScrolling = value;
        this.domNode.classList.toggle('horizontal-scrolling', this._horizontalScrolling);
        if (this._horizontalScrolling) {
            for (const item of this.items) {
                this.measureItemWidth(item);
            }
            this.updateScrollWidth();
            this.scrollableElement.setScrollDimensions({ width: getContentWidth(this.domNode) });
            this.rowsContainer.style.width = `${Math.max(this.scrollWidth || 0, this.renderWidth)}px`;
        }
        else {
            this.scrollableElementWidthDelayer.cancel();
            this.scrollableElement.setScrollDimensions({ width: this.renderWidth, scrollWidth: this.renderWidth });
            this.rowsContainer.style.width = '';
        }
    }
    updateOptions(options) {
        if (options.additionalScrollHeight !== undefined) {
            this.additionalScrollHeight = options.additionalScrollHeight;
            this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
        }
        if (options.smoothScrolling !== undefined) {
            this.scrollable.setSmoothScrollDuration(options.smoothScrolling ? 125 : 0);
        }
        if (options.horizontalScrolling !== undefined) {
            this.horizontalScrolling = options.horizontalScrolling;
        }
        if (options.mouseWheelScrollSensitivity !== undefined) {
            this.scrollableElement.updateOptions({ mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity });
        }
        if (options.fastScrollSensitivity !== undefined) {
            this.scrollableElement.updateOptions({ fastScrollSensitivity: options.fastScrollSensitivity });
        }
    }
    splice(start, deleteCount, elements = []) {
        if (this.splicing) {
            throw new Error('Can\'t run recursive splices.');
        }
        this.splicing = true;
        try {
            return this._splice(start, deleteCount, elements);
        }
        finally {
            this.splicing = false;
            this._onDidChangeContentHeight.fire(this.contentHeight);
        }
    }
    _splice(start, deleteCount, elements = []) {
        const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
        const deleteRange = { start, end: start + deleteCount };
        const removeRange = range_Range.intersect(previousRenderRange, deleteRange);
        // try to reuse rows, avoid removing them from DOM
        const rowsToDispose = new Map();
        for (let i = removeRange.end - 1; i >= removeRange.start; i--) {
            const item = this.items[i];
            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.renderers.get(item.templateId);
                if (renderer && renderer.disposeElement) {
                    renderer.disposeElement(item.element, i, item.row.templateData, item.size);
                }
                rows.push(item.row);
            }
            item.row = null;
        }
        const previousRestRange = { start: start + deleteCount, end: this.items.length };
        const previousRenderedRestRange = range_Range.intersect(previousRestRange, previousRenderRange);
        const previousUnrenderedRestRanges = range_Range.relativeComplement(previousRestRange, previousRenderRange);
        const inserted = elements.map(element => ({
            id: String(this.itemId++),
            element,
            templateId: this.virtualDelegate.getTemplateId(element),
            size: this.virtualDelegate.getHeight(element),
            width: undefined,
            hasDynamicHeight: !!this.virtualDelegate.hasDynamicHeight && this.virtualDelegate.hasDynamicHeight(element),
            lastDynamicHeightWidth: undefined,
            row: null,
            uri: undefined,
            dropTarget: false,
            dragStartDisposable: Disposable.None,
            checkedDisposable: Disposable.None
        }));
        let deleted;
        // TODO@joao: improve this optimization to catch even more cases
        if (start === 0 && deleteCount >= this.items.length) {
            this.rangeMap = new RangeMap();
            this.rangeMap.splice(0, 0, inserted);
            deleted = this.items;
            this.items = inserted;
        }
        else {
            this.rangeMap.splice(start, deleteCount, inserted);
            deleted = this.items.splice(start, deleteCount, ...inserted);
        }
        const delta = elements.length - deleteCount;
        const renderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
        const renderedRestRange = shift(previousRenderedRestRange, delta);
        const updateRange = range_Range.intersect(renderRange, renderedRestRange);
        for (let i = updateRange.start; i < updateRange.end; i++) {
            this.updateItemInDOM(this.items[i], i);
        }
        const removeRanges = range_Range.relativeComplement(renderedRestRange, renderRange);
        for (const range of removeRanges) {
            for (let i = range.start; i < range.end; i++) {
                this.removeItemFromDOM(i);
            }
        }
        const unrenderedRestRanges = previousUnrenderedRestRanges.map(r => shift(r, delta));
        const elementsRange = { start, end: start + elements.length };
        const insertRanges = [elementsRange, ...unrenderedRestRanges].map(r => range_Range.intersect(renderRange, r));
        const beforeElement = this.getNextToLastElement(insertRanges);
        for (const range of insertRanges) {
            for (let i = range.start; i < range.end; i++) {
                const item = this.items[i];
                const rows = rowsToDispose.get(item.templateId);
                const row = rows === null || rows === void 0 ? void 0 : rows.pop();
                this.insertItemInDOM(i, beforeElement, row);
            }
        }
        for (const rows of rowsToDispose.values()) {
            for (const row of rows) {
                this.cache.release(row);
            }
        }
        this.eventuallyUpdateScrollDimensions();
        if (this.supportDynamicHeights) {
            this._rerender(this.scrollTop, this.renderHeight);
        }
        return deleted.map(i => i.element);
    }
    eventuallyUpdateScrollDimensions() {
        this._scrollHeight = this.contentHeight;
        this.rowsContainer.style.height = `${this._scrollHeight}px`;
        if (!this.scrollableElementUpdateDisposable) {
            this.scrollableElementUpdateDisposable = scheduleAtNextAnimationFrame(() => {
                this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
                this.updateScrollWidth();
                this.scrollableElementUpdateDisposable = null;
            });
        }
    }
    eventuallyUpdateScrollWidth() {
        if (!this.horizontalScrolling) {
            this.scrollableElementWidthDelayer.cancel();
            return;
        }
        this.scrollableElementWidthDelayer.trigger(() => this.updateScrollWidth());
    }
    updateScrollWidth() {
        if (!this.horizontalScrolling) {
            return;
        }
        let scrollWidth = 0;
        for (const item of this.items) {
            if (typeof item.width !== 'undefined') {
                scrollWidth = Math.max(scrollWidth, item.width);
            }
        }
        this.scrollWidth = scrollWidth;
        this.scrollableElement.setScrollDimensions({ scrollWidth: scrollWidth === 0 ? 0 : (scrollWidth + 10) });
    }
    rerender() {
        if (!this.supportDynamicHeights) {
            return;
        }
        for (const item of this.items) {
            item.lastDynamicHeightWidth = undefined;
        }
        this._rerender(this.lastRenderTop, this.lastRenderHeight);
    }
    get length() {
        return this.items.length;
    }
    get renderHeight() {
        const scrollDimensions = this.scrollableElement.getScrollDimensions();
        return scrollDimensions.height;
    }
    element(index) {
        return this.items[index].element;
    }
    domElement(index) {
        const row = this.items[index].row;
        return row && row.domNode;
    }
    elementHeight(index) {
        return this.items[index].size;
    }
    elementTop(index) {
        return this.rangeMap.positionAt(index);
    }
    indexAt(position) {
        return this.rangeMap.indexAt(position);
    }
    indexAfter(position) {
        return this.rangeMap.indexAfter(position);
    }
    layout(height, width) {
        const scrollDimensions = {
            height: typeof height === 'number' ? height : getContentHeight(this.domNode)
        };
        if (this.scrollableElementUpdateDisposable) {
            this.scrollableElementUpdateDisposable.dispose();
            this.scrollableElementUpdateDisposable = null;
            scrollDimensions.scrollHeight = this.scrollHeight;
        }
        this.scrollableElement.setScrollDimensions(scrollDimensions);
        if (typeof width !== 'undefined') {
            this.renderWidth = width;
            if (this.supportDynamicHeights) {
                this._rerender(this.scrollTop, this.renderHeight);
            }
        }
        if (this.horizontalScrolling) {
            this.scrollableElement.setScrollDimensions({
                width: typeof width === 'number' ? width : getContentWidth(this.domNode)
            });
        }
    }
    // Render
    render(previousRenderRange, renderTop, renderHeight, renderLeft, scrollWidth, updateItemsInDOM = false) {
        const renderRange = this.getRenderRange(renderTop, renderHeight);
        const rangesToInsert = range_Range.relativeComplement(renderRange, previousRenderRange);
        const rangesToRemove = range_Range.relativeComplement(previousRenderRange, renderRange);
        const beforeElement = this.getNextToLastElement(rangesToInsert);
        if (updateItemsInDOM) {
            const rangesToUpdate = range_Range.intersect(previousRenderRange, renderRange);
            for (let i = rangesToUpdate.start; i < rangesToUpdate.end; i++) {
                this.updateItemInDOM(this.items[i], i);
            }
        }
        for (const range of rangesToInsert) {
            for (let i = range.start; i < range.end; i++) {
                this.insertItemInDOM(i, beforeElement);
            }
        }
        for (const range of rangesToRemove) {
            for (let i = range.start; i < range.end; i++) {
                this.removeItemFromDOM(i);
            }
        }
        if (renderLeft !== undefined) {
            this.rowsContainer.style.left = `-${renderLeft}px`;
        }
        this.rowsContainer.style.top = `-${renderTop}px`;
        if (this.horizontalScrolling && scrollWidth !== undefined) {
            this.rowsContainer.style.width = `${Math.max(scrollWidth, this.renderWidth)}px`;
        }
        this.lastRenderTop = renderTop;
        this.lastRenderHeight = renderHeight;
    }
    // DOM operations
    insertItemInDOM(index, beforeElement, row) {
        const item = this.items[index];
        if (!item.row) {
            item.row = row !== null && row !== void 0 ? row : this.cache.alloc(item.templateId);
        }
        const role = this.accessibilityProvider.getRole(item.element) || 'listitem';
        item.row.domNode.setAttribute('role', role);
        const checked = this.accessibilityProvider.isChecked(item.element);
        if (typeof checked === 'boolean') {
            item.row.domNode.setAttribute('aria-checked', String(!!checked));
        }
        else if (checked) {
            const update = (checked) => item.row.domNode.setAttribute('aria-checked', String(!!checked));
            update(checked.value);
            item.checkedDisposable = checked.onDidChange(update);
        }
        if (!item.row.domNode.parentElement) {
            if (beforeElement) {
                this.rowsContainer.insertBefore(item.row.domNode, beforeElement);
            }
            else {
                this.rowsContainer.appendChild(item.row.domNode);
            }
        }
        this.updateItemInDOM(item, index);
        const renderer = this.renderers.get(item.templateId);
        if (!renderer) {
            throw new Error(`No renderer found for template id ${item.templateId}`);
        }
        renderer === null || renderer === void 0 ? void 0 : renderer.renderElement(item.element, index, item.row.templateData, item.size);
        const uri = this.dnd.getDragURI(item.element);
        item.dragStartDisposable.dispose();
        item.row.domNode.draggable = !!uri;
        if (uri) {
            item.dragStartDisposable = addDisposableListener(item.row.domNode, 'dragstart', event => this.onDragStart(item.element, uri, event));
        }
        if (this.horizontalScrolling) {
            this.measureItemWidth(item);
            this.eventuallyUpdateScrollWidth();
        }
    }
    measureItemWidth(item) {
        if (!item.row || !item.row.domNode) {
            return;
        }
        item.row.domNode.style.width = browser_isFirefox ? '-moz-fit-content' : 'fit-content';
        item.width = getContentWidth(item.row.domNode);
        const style = window.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 = '';
    }
    updateItemInDOM(item, index) {
        item.row.domNode.style.top = `${this.elementTop(index)}px`;
        if (this.setRowHeight) {
            item.row.domNode.style.height = `${item.size}px`;
        }
        if (this.setRowLineHeight) {
            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.accessibilityProvider.getSetSize(item.element, index, this.length)));
        item.row.domNode.setAttribute('aria-posinset', String(this.accessibilityProvider.getPosInSet(item.element, index)));
        item.row.domNode.setAttribute('id', this.getElementDomId(index));
        item.row.domNode.classList.toggle('drop-target', item.dropTarget);
    }
    removeItemFromDOM(index) {
        const item = this.items[index];
        item.dragStartDisposable.dispose();
        item.checkedDisposable.dispose();
        if (item.row) {
            const renderer = this.renderers.get(item.templateId);
            if (renderer && renderer.disposeElement) {
                renderer.disposeElement(item.element, index, item.row.templateData, item.size);
            }
            this.cache.release(item.row);
            item.row = null;
        }
        if (this.horizontalScrolling) {
            this.eventuallyUpdateScrollWidth();
        }
    }
    getScrollTop() {
        const scrollPosition = this.scrollableElement.getScrollPosition();
        return scrollPosition.scrollTop;
    }
    setScrollTop(scrollTop, reuseAnimation) {
        if (this.scrollableElementUpdateDisposable) {
            this.scrollableElementUpdateDisposable.dispose();
            this.scrollableElementUpdateDisposable = null;
            this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
        }
        this.scrollableElement.setScrollPosition({ scrollTop, reuseAnimation });
    }
    get scrollTop() {
        return this.getScrollTop();
    }
    set scrollTop(scrollTop) {
        this.setScrollTop(scrollTop);
    }
    get scrollHeight() {
        return this._scrollHeight + (this.horizontalScrolling ? 10 : 0) + this.additionalScrollHeight;
    }
    // Events
    get onMouseClick() { return Event.map(this.disposables.add(new DomEmitter(this.domNode, 'click')).event, e => this.toMouseEvent(e), this.disposables); }
    get onMouseDblClick() { return Event.map(this.disposables.add(new DomEmitter(this.domNode, 'dblclick')).event, e => this.toMouseEvent(e), this.disposables); }
    get onMouseMiddleClick() { return Event.filter(Event.map(this.disposables.add(new DomEmitter(this.domNode, 'auxclick')).event, e => this.toMouseEvent(e), this.disposables), e => e.browserEvent.button === 1, this.disposables); }
    get onMouseDown() { return Event.map(this.disposables.add(new DomEmitter(this.domNode, 'mousedown')).event, e => this.toMouseEvent(e), this.disposables); }
    get onMouseOver() { return Event.map(this.disposables.add(new DomEmitter(this.domNode, 'mouseover')).event, e => this.toMouseEvent(e), this.disposables); }
    get onContextMenu() { return Event.any(Event.map(this.disposables.add(new DomEmitter(this.domNode, 'contextmenu')).event, e => this.toMouseEvent(e), this.disposables), Event.map(this.disposables.add(new DomEmitter(this.domNode, touch_EventType.Contextmenu)).event, e => this.toGestureEvent(e), this.disposables)); }
    get onTouchStart() { return Event.map(this.disposables.add(new DomEmitter(this.domNode, 'touchstart')).event, e => this.toTouchEvent(e), this.disposables); }
    get onTap() { return Event.map(this.disposables.add(new DomEmitter(this.rowsContainer, touch_EventType.Tap)).event, e => this.toGestureEvent(e), this.disposables); }
    toMouseEvent(browserEvent) {
        const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
        const item = typeof index === 'undefined' ? undefined : this.items[index];
        const element = item && item.element;
        return { browserEvent, index, element };
    }
    toTouchEvent(browserEvent) {
        const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
        const item = typeof index === 'undefined' ? undefined : this.items[index];
        const element = item && item.element;
        return { browserEvent, index, element };
    }
    toGestureEvent(browserEvent) {
        const index = this.getItemIndexFromEventTarget(browserEvent.initialTarget || null);
        const item = typeof index === 'undefined' ? undefined : this.items[index];
        const element = item && item.element;
        return { browserEvent, index, element };
    }
    toDragEvent(browserEvent) {
        const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
        const item = typeof index === 'undefined' ? undefined : this.items[index];
        const element = item && item.element;
        return { browserEvent, index, element };
    }
    onScroll(e) {
        try {
            const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
            this.render(previousRenderRange, e.scrollTop, e.height, e.scrollLeft, e.scrollWidth);
            if (this.supportDynamicHeights) {
                this._rerender(e.scrollTop, e.height, e.inSmoothScrolling);
            }
        }
        catch (err) {
            console.error('Got bad scroll event:', e);
            throw err;
        }
    }
    onTouchChange(event) {
        event.preventDefault();
        event.stopPropagation();
        this.scrollTop -= event.translationY;
    }
    // DND
    onDragStart(element, uri, event) {
        var _a, _b;
        if (!event.dataTransfer) {
            return;
        }
        const elements = this.dnd.getDragElements(element);
        event.dataTransfer.effectAllowed = 'copyMove';
        event.dataTransfer.setData(DataTransfers.TEXT, uri);
        if (event.dataTransfer.setDragImage) {
            let label;
            if (this.dnd.getDragLabel) {
                label = this.dnd.getDragLabel(elements, event);
            }
            if (typeof label === 'undefined') {
                label = String(elements.length);
            }
            const dragImage = dom_$('.monaco-drag-image');
            dragImage.textContent = label;
            document.body.appendChild(dragImage);
            event.dataTransfer.setDragImage(dragImage, -10, -10);
            setTimeout(() => document.body.removeChild(dragImage), 0);
        }
        this.currentDragData = new ElementsDragAndDropData(elements);
        StaticDND.CurrentDragAndDropData = new ExternalElementsDragAndDropData(elements);
        (_b = (_a = this.dnd).onDragStart) === null || _b === void 0 ? void 0 : _b.call(_a, this.currentDragData, event);
    }
    onDragOver(event) {
        var _a;
        event.browserEvent.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome)
        this.onDragLeaveTimeout.dispose();
        if (StaticDND.CurrentDragAndDropData && StaticDND.CurrentDragAndDropData.getData() === 'vscode-ui') {
            return false;
        }
        this.setupDragAndDropScrollTopAnimation(event.browserEvent);
        if (!event.browserEvent.dataTransfer) {
            return false;
        }
        // Drag over from outside
        if (!this.currentDragData) {
            if (StaticDND.CurrentDragAndDropData) {
                // Drag over from another list
                this.currentDragData = StaticDND.CurrentDragAndDropData;
            }
            else {
                // Drag over from the desktop
                if (!event.browserEvent.dataTransfer.types) {
                    return false;
                }
                this.currentDragData = new NativeDragAndDropData();
            }
        }
        const result = this.dnd.onDragOver(this.currentDragData, event.element, event.index, event.browserEvent);
        this.canDrop = typeof result === 'boolean' ? result : result.accept;
        if (!this.canDrop) {
            this.currentDragFeedback = undefined;
            this.currentDragFeedbackDisposable.dispose();
            return false;
        }
        event.browserEvent.dataTransfer.dropEffect = (typeof result !== 'boolean' && result.effect === 0 /* ListDragOverEffect.Copy */) ? '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];
            }
        }
        // sanitize feedback list
        feedback = distinct(feedback).filter(i => i >= -1 && i < this.length).sort((a, b) => a - b);
        feedback = feedback[0] === -1 ? [-1] : feedback;
        if (equalsDragFeedback(this.currentDragFeedback, feedback)) {
            return true;
        }
        this.currentDragFeedback = feedback;
        this.currentDragFeedbackDisposable.dispose();
        if (feedback[0] === -1) { // entire list feedback
            this.domNode.classList.add('drop-target');
            this.rowsContainer.classList.add('drop-target');
            this.currentDragFeedbackDisposable = toDisposable(() => {
                this.domNode.classList.remove('drop-target');
                this.rowsContainer.classList.remove('drop-target');
            });
        }
        else {
            for (const index of feedback) {
                const item = this.items[index];
                item.dropTarget = true;
                (_a = item.row) === null || _a === void 0 ? void 0 : _a.domNode.classList.add('drop-target');
            }
            this.currentDragFeedbackDisposable = toDisposable(() => {
                var _a;
                for (const index of feedback) {
                    const item = this.items[index];
                    item.dropTarget = false;
                    (_a = item.row) === null || _a === void 0 ? void 0 : _a.domNode.classList.remove('drop-target');
                }
            });
        }
        return true;
    }
    onDragLeave(event) {
        var _a, _b;
        this.onDragLeaveTimeout.dispose();
        this.onDragLeaveTimeout = disposableTimeout(() => this.clearDragOverFeedback(), 100);
        if (this.currentDragData) {
            (_b = (_a = this.dnd).onDragLeave) === null || _b === void 0 ? void 0 : _b.call(_a, this.currentDragData, event.element, event.index, event.browserEvent);
        }
    }
    onDrop(event) {
        if (!this.canDrop) {
            return;
        }
        const dragData = this.currentDragData;
        this.teardownDragAndDropScrollTopAnimation();
        this.clearDragOverFeedback();
        this.currentDragData = undefined;
        StaticDND.CurrentDragAndDropData = undefined;
        if (!dragData || !event.browserEvent.dataTransfer) {
            return;
        }
        event.browserEvent.preventDefault();
        dragData.update(event.browserEvent.dataTransfer);
        this.dnd.drop(dragData, event.element, event.index, event.browserEvent);
    }
    onDragEnd(event) {
        var _a, _b;
        this.canDrop = false;
        this.teardownDragAndDropScrollTopAnimation();
        this.clearDragOverFeedback();
        this.currentDragData = undefined;
        StaticDND.CurrentDragAndDropData = undefined;
        (_b = (_a = this.dnd).onDragEnd) === null || _b === void 0 ? void 0 : _b.call(_a, event);
    }
    clearDragOverFeedback() {
        this.currentDragFeedback = undefined;
        this.currentDragFeedbackDisposable.dispose();
        this.currentDragFeedbackDisposable = Disposable.None;
    }
    // DND scroll top animation
    setupDragAndDropScrollTopAnimation(event) {
        if (!this.dragOverAnimationDisposable) {
            const viewTop = getTopLeftOffset(this.domNode).top;
            this.dragOverAnimationDisposable = animate(this.animateDragAndDropScrollTop.bind(this, viewTop));
        }
        this.dragOverAnimationStopDisposable.dispose();
        this.dragOverAnimationStopDisposable = disposableTimeout(() => {
            if (this.dragOverAnimationDisposable) {
                this.dragOverAnimationDisposable.dispose();
                this.dragOverAnimationDisposable = undefined;
            }
        }, 1000);
        this.dragOverMouseY = event.pageY;
    }
    animateDragAndDropScrollTop(viewTop) {
        if (this.dragOverMouseY === undefined) {
            return;
        }
        const diff = this.dragOverMouseY - viewTop;
        const upperLimit = this.renderHeight - 35;
        if (diff < 35) {
            this.scrollTop += Math.max(-14, Math.floor(0.3 * (diff - 35)));
        }
        else if (diff > upperLimit) {
            this.scrollTop += Math.min(14, Math.floor(0.3 * (diff - upperLimit)));
        }
    }
    teardownDragAndDropScrollTopAnimation() {
        this.dragOverAnimationStopDisposable.dispose();
        if (this.dragOverAnimationDisposable) {
            this.dragOverAnimationDisposable.dispose();
            this.dragOverAnimationDisposable = undefined;
        }
    }
    // Util
    getItemIndexFromEventTarget(target) {
        const scrollableElement = this.scrollableElement.getDomNode();
        let element = target;
        while (element instanceof HTMLElement && element !== this.rowsContainer && scrollableElement.contains(element)) {
            const rawIndex = element.getAttribute('data-index');
            if (rawIndex) {
                const index = Number(rawIndex);
                if (!isNaN(index)) {
                    return index;
                }
            }
            element = element.parentElement;
        }
        return undefined;
    }
    getRenderRange(renderTop, renderHeight) {
        return {
            start: this.rangeMap.indexAt(renderTop),
            end: this.rangeMap.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.
     */
    _rerender(renderTop, renderHeight, inSmoothScrolling) {
        const previousRenderRange = this.getRenderRange(renderTop, renderHeight);
        // Let's remember the second element's position, this helps in scrolling up
        // and preserving a linear upwards scroll movement
        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 heightDiff = 0;
        while (true) {
            const renderRange = this.getRenderRange(renderTop, renderHeight);
            let didChange = false;
            for (let i = renderRange.start; i < renderRange.end; i++) {
                const diff = this.probeDynamicHeight(i);
                if (diff !== 0) {
                    this.rangeMap.splice(i, 1, [this.items[i]]);
                }
                heightDiff += diff;
                didChange = didChange || diff !== 0;
            }
            if (!didChange) {
                if (heightDiff !== 0) {
                    this.eventuallyUpdateScrollDimensions();
                }
                const unrenderRanges = range_Range.relativeComplement(previousRenderRange, renderRange);
                for (const range of unrenderRanges) {
                    for (let i = range.start; i < range.end; i++) {
                        if (this.items[i].row) {
                            this.removeItemFromDOM(i);
                        }
                    }
                }
                const renderRanges = range_Range.relativeComplement(renderRange, previousRenderRange);
                for (const range of renderRanges) {
                    for (let i = range.start; i < range.end; i++) {
                        const afterIndex = i + 1;
                        const beforeRow = afterIndex < this.items.length ? this.items[afterIndex].row : null;
                        const beforeElement = beforeRow ? beforeRow.domNode : null;
                        this.insertItemInDOM(i, beforeElement);
                    }
                }
                for (let i = renderRange.start; i < renderRange.end; i++) {
                    if (this.items[i].row) {
                        this.updateItemInDOM(this.items[i], i);
                    }
                }
                if (typeof anchorElementIndex === 'number') {
                    // To compute a destination scroll top, we need to take into account the current smooth scrolling
                    // animation, and then reuse it with a new target (to avoid prolonging the scroll)
                    // See https://github.com/microsoft/vscode/issues/104144
                    // See https://github.com/microsoft/vscode/pull/104284
                    // See https://github.com/microsoft/vscode/issues/107704
                    const deltaScrollTop = this.scrollable.getFutureScrollPosition().scrollTop - renderTop;
                    const newScrollTop = this.elementTop(anchorElementIndex) - anchorElementTopDelta + deltaScrollTop;
                    this.setScrollTop(newScrollTop, inSmoothScrolling);
                }
                this._onDidChangeContentHeight.fire(this.contentHeight);
                return;
            }
        }
    }
    probeDynamicHeight(index) {
        var _a, _b, _c;
        const item = this.items[index];
        if (!!this.virtualDelegate.getDynamicHeight) {
            const newSize = this.virtualDelegate.getDynamicHeight(item.element);
            if (newSize !== null) {
                const size = item.size;
                item.size = newSize;
                item.lastDynamicHeightWidth = this.renderWidth;
                return newSize - size;
            }
        }
        if (!item.hasDynamicHeight || item.lastDynamicHeightWidth === this.renderWidth) {
            return 0;
        }
        if (!!this.virtualDelegate.hasDynamicHeight && !this.virtualDelegate.hasDynamicHeight(item.element)) {
            return 0;
        }
        const size = item.size;
        if (!this.setRowHeight && item.row) {
            const newSize = item.row.domNode.offsetHeight;
            item.size = newSize;
            item.lastDynamicHeightWidth = this.renderWidth;
            return newSize - size;
        }
        const row = this.cache.alloc(item.templateId);
        row.domNode.style.height = '';
        this.rowsContainer.appendChild(row.domNode);
        const renderer = this.renderers.get(item.templateId);
        if (renderer) {
            renderer.renderElement(item.element, index, row.templateData, undefined);
            (_a = renderer.disposeElement) === null || _a === void 0 ? void 0 : _a.call(renderer, item.element, index, row.templateData, undefined);
        }
        item.size = row.domNode.offsetHeight;
        (_c = (_b = this.virtualDelegate).setDynamicHeight) === null || _c === void 0 ? void 0 : _c.call(_b, item.element, item.size);
        item.lastDynamicHeightWidth = this.renderWidth;
        this.rowsContainer.removeChild(row.domNode);
        this.cache.release(row);
        return item.size - size;
    }
    getNextToLastElement(ranges) {
        const lastRange = ranges[ranges.length - 1];
        if (!lastRange) {
            return null;
        }
        const nextToLastItem = this.items[lastRange.end];
        if (!nextToLastItem) {
            return null;
        }
        if (!nextToLastItem.row) {
            return null;
        }
        return nextToLastItem.row.domNode;
    }
    getElementDomId(index) {
        return `${this.domId}_${index}`;
    }
    // Dispose
    dispose() {
        var _a;
        if (this.items) {
            for (const item of this.items) {
                if (item.row) {
                    const renderer = this.renderers.get(item.row.templateId);
                    if (renderer) {
                        (_a = renderer.disposeElement) === null || _a === void 0 ? void 0 : _a.call(renderer, item.element, -1, item.row.templateData, undefined);
                        renderer.disposeTemplate(item.row.templateData);
                    }
                }
            }
            this.items = [];
        }
        if (this.domNode && this.domNode.parentNode) {
            this.domNode.parentNode.removeChild(this.domNode);
        }
        dispose(this.disposables);
    }
}
ListView.InstanceCount = 0;
listView_decorate([
    memoize
], ListView.prototype, "onMouseClick", null);
listView_decorate([
    memoize
], ListView.prototype, "onMouseDblClick", null);
listView_decorate([
    memoize
], ListView.prototype, "onMouseMiddleClick", null);
listView_decorate([
    memoize
], ListView.prototype, "onMouseDown", null);
listView_decorate([
    memoize
], ListView.prototype, "onMouseOver", null);
listView_decorate([
    memoize
], ListView.prototype, "onContextMenu", null);
listView_decorate([
    memoize
], ListView.prototype, "onTouchStart", null);
listView_decorate([
    memoize
], ListView.prototype, "onTap", null);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/list/listWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var listWidget_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var listWidget_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};




















class TraitRenderer {
    constructor(trait) {
        this.trait = trait;
        this.renderedElements = [];
    }
    get templateId() {
        return `template:${this.trait.name}`;
    }
    renderTemplate(container) {
        return container;
    }
    renderElement(element, index, templateData) {
        const renderedElementIndex = this.renderedElements.findIndex(el => el.templateData === templateData);
        if (renderedElementIndex >= 0) {
            const rendered = this.renderedElements[renderedElementIndex];
            this.trait.unrender(templateData);
            rendered.index = index;
        }
        else {
            const rendered = { index, templateData };
            this.renderedElements.push(rendered);
        }
        this.trait.renderIndex(index, templateData);
    }
    splice(start, deleteCount, insertCount) {
        const rendered = [];
        for (const renderedElement of this.renderedElements) {
            if (renderedElement.index < start) {
                rendered.push(renderedElement);
            }
            else if (renderedElement.index >= start + deleteCount) {
                rendered.push({
                    index: renderedElement.index + insertCount - deleteCount,
                    templateData: renderedElement.templateData
                });
            }
        }
        this.renderedElements = rendered;
    }
    renderIndexes(indexes) {
        for (const { index, templateData } of this.renderedElements) {
            if (indexes.indexOf(index) > -1) {
                this.trait.renderIndex(index, templateData);
            }
        }
    }
    disposeTemplate(templateData) {
        const index = this.renderedElements.findIndex(el => el.templateData === templateData);
        if (index < 0) {
            return;
        }
        this.renderedElements.splice(index, 1);
    }
}
class Trait {
    constructor(_trait) {
        this._trait = _trait;
        this.length = 0;
        this.indexes = [];
        this.sortedIndexes = [];
        this._onChange = new Emitter();
        this.onChange = this._onChange.event;
    }
    get name() { return this._trait; }
    get renderer() {
        return new TraitRenderer(this);
    }
    splice(start, deleteCount, elements) {
        var _a;
        deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));
        const diff = elements.length - deleteCount;
        const end = start + deleteCount;
        const sortedIndexes = [
            ...this.sortedIndexes.filter(i => i < start),
            ...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1),
            ...this.sortedIndexes.filter(i => i >= end).map(i => i + diff)
        ];
        const length = this.length + diff;
        if (this.sortedIndexes.length > 0 && sortedIndexes.length === 0 && length > 0) {
            const first = (_a = this.sortedIndexes.find(index => index >= start)) !== null && _a !== void 0 ? _a : length - 1;
            sortedIndexes.push(Math.min(first, length - 1));
        }
        this.renderer.splice(start, deleteCount, elements.length);
        this._set(sortedIndexes, sortedIndexes);
        this.length = length;
    }
    renderIndex(index, container) {
        container.classList.toggle(this._trait, this.contains(index));
    }
    unrender(container) {
        container.classList.remove(this._trait);
    }
    /**
     * 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._set(indexes, [...indexes].sort(numericSort), browserEvent);
    }
    _set(indexes, sortedIndexes, browserEvent) {
        const result = this.indexes;
        const sortedResult = this.sortedIndexes;
        this.indexes = indexes;
        this.sortedIndexes = sortedIndexes;
        const toRender = disjunction(sortedResult, indexes);
        this.renderer.renderIndexes(toRender);
        this._onChange.fire({ indexes, browserEvent });
        return result;
    }
    get() {
        return this.indexes;
    }
    contains(index) {
        return binarySearch(this.sortedIndexes, index, numericSort) >= 0;
    }
    dispose() {
        dispose(this._onChange);
    }
}
listWidget_decorate([
    memoize
], Trait.prototype, "renderer", null);
class SelectionTrait extends Trait {
    constructor(setAriaSelected) {
        super('selected');
        this.setAriaSelected = setAriaSelected;
    }
    renderIndex(index, container) {
        super.renderIndex(index, container);
        if (this.setAriaSelected) {
            if (this.contains(index)) {
                container.setAttribute('aria-selected', 'true');
            }
            else {
                container.setAttribute('aria-selected', 'false');
            }
        }
    }
}
/**
 * The TraitSpliceable is used as a util class to be able
 * to preserve traits across splice calls, given an identity
 * provider.
 */
class TraitSpliceable {
    constructor(trait, view, identityProvider) {
        this.trait = trait;
        this.view = view;
        this.identityProvider = identityProvider;
    }
    splice(start, deleteCount, elements) {
        if (!this.identityProvider) {
            return this.trait.splice(start, deleteCount, elements.map(() => false));
        }
        const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider.getId(this.view.element(i)).toString());
        const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider.getId(e).toString()) > -1);
        this.trait.splice(start, deleteCount, elementsWithTrait);
    }
}
function isInputElement(e) {
    return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA';
}
function isMonacoEditor(e) {
    if (e.classList.contains('monaco-editor')) {
        return true;
    }
    if (e.classList.contains('monaco-list')) {
        return false;
    }
    if (!e.parentElement) {
        return false;
    }
    return isMonacoEditor(e.parentElement);
}
function isButton(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 isButton(e.parentElement);
}
class KeyboardController {
    constructor(list, view, options) {
        this.list = list;
        this.view = view;
        this.disposables = new DisposableStore();
        this.multipleSelectionDisposables = new DisposableStore();
        this.onKeyDown.filter(e => e.keyCode === 3 /* KeyCode.Enter */).on(this.onEnter, this, this.disposables);
        this.onKeyDown.filter(e => e.keyCode === 16 /* KeyCode.UpArrow */).on(this.onUpArrow, this, this.disposables);
        this.onKeyDown.filter(e => e.keyCode === 18 /* KeyCode.DownArrow */).on(this.onDownArrow, this, this.disposables);
        this.onKeyDown.filter(e => e.keyCode === 11 /* KeyCode.PageUp */).on(this.onPageUpArrow, this, this.disposables);
        this.onKeyDown.filter(e => e.keyCode === 12 /* KeyCode.PageDown */).on(this.onPageDownArrow, this, this.disposables);
        this.onKeyDown.filter(e => e.keyCode === 9 /* KeyCode.Escape */).on(this.onEscape, this, this.disposables);
        if (options.multipleSelectionSupport !== false) {
            this.onKeyDown.filter(e => (isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === 31 /* KeyCode.KeyA */).on(this.onCtrlA, this, this.multipleSelectionDisposables);
        }
    }
    get onKeyDown() {
        return this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event)
            .filter(e => !isInputElement(e.target))
            .map(e => new StandardKeyboardEvent(e)));
    }
    updateOptions(optionsUpdate) {
        if (optionsUpdate.multipleSelectionSupport !== undefined) {
            this.multipleSelectionDisposables.clear();
            if (optionsUpdate.multipleSelectionSupport) {
                this.onKeyDown.filter(e => (isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === 31 /* KeyCode.KeyA */).on(this.onCtrlA, this, this.multipleSelectionDisposables);
            }
        }
    }
    onEnter(e) {
        e.preventDefault();
        e.stopPropagation();
        this.list.setSelection(this.list.getFocus(), e.browserEvent);
    }
    onUpArrow(e) {
        e.preventDefault();
        e.stopPropagation();
        this.list.focusPrevious(1, false, e.browserEvent);
        const el = this.list.getFocus()[0];
        this.list.setAnchor(el);
        this.list.reveal(el);
        this.view.domNode.focus();
    }
    onDownArrow(e) {
        e.preventDefault();
        e.stopPropagation();
        this.list.focusNext(1, false, e.browserEvent);
        const el = this.list.getFocus()[0];
        this.list.setAnchor(el);
        this.list.reveal(el);
        this.view.domNode.focus();
    }
    onPageUpArrow(e) {
        e.preventDefault();
        e.stopPropagation();
        this.list.focusPreviousPage(e.browserEvent);
        const el = this.list.getFocus()[0];
        this.list.setAnchor(el);
        this.list.reveal(el);
        this.view.domNode.focus();
    }
    onPageDownArrow(e) {
        e.preventDefault();
        e.stopPropagation();
        this.list.focusNextPage(e.browserEvent);
        const el = this.list.getFocus()[0];
        this.list.setAnchor(el);
        this.list.reveal(el);
        this.view.domNode.focus();
    }
    onCtrlA(e) {
        e.preventDefault();
        e.stopPropagation();
        this.list.setSelection(range(this.list.length), e.browserEvent);
        this.list.setAnchor(undefined);
        this.view.domNode.focus();
    }
    onEscape(e) {
        if (this.list.getSelection().length) {
            e.preventDefault();
            e.stopPropagation();
            this.list.setSelection([], e.browserEvent);
            this.list.setAnchor(undefined);
            this.view.domNode.focus();
        }
    }
    dispose() {
        this.disposables.dispose();
        this.multipleSelectionDisposables.dispose();
    }
}
listWidget_decorate([
    memoize
], KeyboardController.prototype, "onKeyDown", null);
var TypeNavigationMode;
(function (TypeNavigationMode) {
    TypeNavigationMode[TypeNavigationMode["Automatic"] = 0] = "Automatic";
    TypeNavigationMode[TypeNavigationMode["Trigger"] = 1] = "Trigger";
})(TypeNavigationMode || (TypeNavigationMode = {}));
var TypeNavigationControllerState;
(function (TypeNavigationControllerState) {
    TypeNavigationControllerState[TypeNavigationControllerState["Idle"] = 0] = "Idle";
    TypeNavigationControllerState[TypeNavigationControllerState["Typing"] = 1] = "Typing";
})(TypeNavigationControllerState || (TypeNavigationControllerState = {}));
const DefaultKeyboardNavigationDelegate = new class {
    mightProducePrintableCharacter(event) {
        if (event.ctrlKey || event.metaKey || event.altKey) {
            return false;
        }
        return (event.keyCode >= 31 /* KeyCode.KeyA */ && event.keyCode <= 56 /* KeyCode.KeyZ */)
            || (event.keyCode >= 21 /* KeyCode.Digit0 */ && event.keyCode <= 30 /* KeyCode.Digit9 */)
            || (event.keyCode >= 93 /* KeyCode.Numpad0 */ && event.keyCode <= 102 /* KeyCode.Numpad9 */)
            || (event.keyCode >= 80 /* KeyCode.Semicolon */ && event.keyCode <= 90 /* KeyCode.Quote */);
    }
};
class TypeNavigationController {
    constructor(list, view, keyboardNavigationLabelProvider, keyboardNavigationEventFilter, delegate) {
        this.list = list;
        this.view = view;
        this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
        this.keyboardNavigationEventFilter = keyboardNavigationEventFilter;
        this.delegate = delegate;
        this.enabled = false;
        this.state = TypeNavigationControllerState.Idle;
        this.mode = TypeNavigationMode.Automatic;
        this.triggered = false;
        this.previouslyFocused = -1;
        this.enabledDisposables = new DisposableStore();
        this.disposables = new DisposableStore();
        this.updateOptions(list.options);
    }
    updateOptions(options) {
        var _a, _b;
        if ((_a = options.typeNavigationEnabled) !== null && _a !== void 0 ? _a : true) {
            this.enable();
        }
        else {
            this.disable();
        }
        this.mode = (_b = options.typeNavigationMode) !== null && _b !== void 0 ? _b : TypeNavigationMode.Automatic;
    }
    enable() {
        if (this.enabled) {
            return;
        }
        let typing = false;
        const onChar = this.enabledDisposables.add(Event.chain(this.enabledDisposables.add(new DomEmitter(this.view.domNode, 'keydown')).event))
            .filter(e => !isInputElement(e.target))
            .filter(() => this.mode === TypeNavigationMode.Automatic || this.triggered)
            .map(event => new StandardKeyboardEvent(event))
            .filter(e => typing || this.keyboardNavigationEventFilter(e))
            .filter(e => this.delegate.mightProducePrintableCharacter(e))
            .forEach(stopEvent)
            .map(event => event.browserEvent.key)
            .event;
        const onClear = Event.debounce(onChar, () => null, 800, undefined, undefined, this.enabledDisposables);
        const onInput = Event.reduce(Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i), undefined, this.enabledDisposables);
        onInput(this.onInput, this, this.enabledDisposables);
        onClear(this.onClear, this, this.enabledDisposables);
        onChar(() => typing = true, undefined, this.enabledDisposables);
        onClear(() => typing = false, undefined, this.enabledDisposables);
        this.enabled = true;
        this.triggered = false;
    }
    disable() {
        if (!this.enabled) {
            return;
        }
        this.enabledDisposables.clear();
        this.enabled = false;
        this.triggered = false;
    }
    onClear() {
        var _a;
        const focus = this.list.getFocus();
        if (focus.length > 0 && focus[0] === this.previouslyFocused) {
            // List: re-announce element on typing end since typed keys will interrupt aria label of focused element
            // Do not announce if there was a focus change at the end to prevent duplication https://github.com/microsoft/vscode/issues/95961
            const ariaLabel = (_a = this.list.options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.getAriaLabel(this.list.element(focus[0]));
            if (ariaLabel) {
                aria_alert(ariaLabel);
            }
        }
        this.previouslyFocused = -1;
    }
    onInput(word) {
        if (!word) {
            this.state = TypeNavigationControllerState.Idle;
            this.triggered = false;
            return;
        }
        const focus = this.list.getFocus();
        const start = focus.length > 0 ? focus[0] : 0;
        const delta = this.state === TypeNavigationControllerState.Idle ? 1 : 0;
        this.state = TypeNavigationControllerState.Typing;
        for (let i = 0; i < this.list.length; i++) {
            const index = (start + i + delta) % this.list.length;
            const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index));
            const labelStr = label && label.toString();
            if (typeof labelStr === 'undefined' || matchesPrefix(word, labelStr)) {
                this.previouslyFocused = start;
                this.list.setFocus([index]);
                this.list.reveal(index);
                return;
            }
        }
    }
    dispose() {
        this.disable();
        this.enabledDisposables.dispose();
        this.disposables.dispose();
    }
}
class DOMFocusController {
    constructor(list, view) {
        this.list = list;
        this.view = view;
        this.disposables = new DisposableStore();
        const onKeyDown = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(view.domNode, 'keydown')).event))
            .filter(e => !isInputElement(e.target))
            .map(e => new StandardKeyboardEvent(e));
        onKeyDown.filter(e => e.keyCode === 2 /* KeyCode.Tab */ && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey)
            .on(this.onTab, this, this.disposables);
    }
    onTab(e) {
        if (e.target !== this.view.domNode) {
            return;
        }
        const focus = this.list.getFocus();
        if (focus.length === 0) {
            return;
        }
        const focusedDomElement = this.view.domElement(focus[0]);
        if (!focusedDomElement) {
            return;
        }
        const tabIndexElement = focusedDomElement.querySelector('[tabIndex]');
        if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) {
            return;
        }
        const style = window.getComputedStyle(tabIndexElement);
        if (style.visibility === 'hidden' || style.display === 'none') {
            return;
        }
        e.preventDefault();
        e.stopPropagation();
        tabIndexElement.focus();
    }
    dispose() {
        this.disposables.dispose();
    }
}
function isSelectionSingleChangeEvent(event) {
    return isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey;
}
function isSelectionRangeChangeEvent(event) {
    return event.browserEvent.shiftKey;
}
function isMouseRightClick(event) {
    return event instanceof MouseEvent && event.button === 2;
}
const DefaultMultipleSelectionController = {
    isSelectionSingleChangeEvent,
    isSelectionRangeChangeEvent
};
class MouseController {
    constructor(list) {
        this.list = list;
        this.disposables = new DisposableStore();
        this._onPointer = new Emitter();
        this.onPointer = this._onPointer.event;
        if (list.options.multipleSelectionSupport !== false) {
            this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController;
        }
        this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport;
        if (this.mouseSupport) {
            list.onMouseDown(this.onMouseDown, this, this.disposables);
            list.onContextMenu(this.onContextMenu, this, this.disposables);
            list.onMouseDblClick(this.onDoubleClick, this, this.disposables);
            list.onTouchStart(this.onMouseDown, this, this.disposables);
            this.disposables.add(Gesture.addTarget(list.getHTMLElement()));
        }
        Event.any(list.onMouseClick, list.onMouseMiddleClick, list.onTap)(this.onViewPointer, this, this.disposables);
    }
    updateOptions(optionsUpdate) {
        if (optionsUpdate.multipleSelectionSupport !== undefined) {
            this.multipleSelectionController = undefined;
            if (optionsUpdate.multipleSelectionSupport) {
                this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController;
            }
        }
    }
    isSelectionSingleChangeEvent(event) {
        if (!this.multipleSelectionController) {
            return false;
        }
        return this.multipleSelectionController.isSelectionSingleChangeEvent(event);
    }
    isSelectionRangeChangeEvent(event) {
        if (!this.multipleSelectionController) {
            return false;
        }
        return this.multipleSelectionController.isSelectionRangeChangeEvent(event);
    }
    isSelectionChangeEvent(event) {
        return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event);
    }
    onMouseDown(e) {
        if (isMonacoEditor(e.browserEvent.target)) {
            return;
        }
        if (document.activeElement !== e.browserEvent.target) {
            this.list.domFocus();
        }
    }
    onContextMenu(e) {
        if (isMonacoEditor(e.browserEvent.target)) {
            return;
        }
        const focus = typeof e.index === 'undefined' ? [] : [e.index];
        this.list.setFocus(focus, e.browserEvent);
    }
    onViewPointer(e) {
        if (!this.mouseSupport) {
            return;
        }
        if (isInputElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
            return;
        }
        const focus = e.index;
        if (typeof focus === 'undefined') {
            this.list.setFocus([], e.browserEvent);
            this.list.setSelection([], e.browserEvent);
            this.list.setAnchor(undefined);
            return;
        }
        if (this.isSelectionRangeChangeEvent(e)) {
            return this.changeSelection(e);
        }
        if (this.isSelectionChangeEvent(e)) {
            return this.changeSelection(e);
        }
        this.list.setFocus([focus], e.browserEvent);
        this.list.setAnchor(focus);
        if (!isMouseRightClick(e.browserEvent)) {
            this.list.setSelection([focus], e.browserEvent);
        }
        this._onPointer.fire(e);
    }
    onDoubleClick(e) {
        if (isInputElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
            return;
        }
        if (this.isSelectionChangeEvent(e)) {
            return;
        }
        const focus = this.list.getFocus();
        this.list.setSelection(focus, e.browserEvent);
    }
    changeSelection(e) {
        const focus = e.index;
        let anchor = this.list.getAnchor();
        if (this.isSelectionRangeChangeEvent(e)) {
            if (typeof anchor === 'undefined') {
                const currentFocus = this.list.getFocus()[0];
                anchor = currentFocus !== null && currentFocus !== void 0 ? currentFocus : focus;
                this.list.setAnchor(anchor);
            }
            const min = Math.min(anchor, focus);
            const max = Math.max(anchor, focus);
            const rangeSelection = range(min, max + 1);
            const selection = this.list.getSelection();
            const contiguousRange = getContiguousRangeContaining(disjunction(selection, [anchor]), anchor);
            if (contiguousRange.length === 0) {
                return;
            }
            const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange));
            this.list.setSelection(newSelection, e.browserEvent);
            this.list.setFocus([focus], e.browserEvent);
        }
        else if (this.isSelectionSingleChangeEvent(e)) {
            const selection = this.list.getSelection();
            const newSelection = selection.filter(i => i !== focus);
            this.list.setFocus([focus]);
            this.list.setAnchor(focus);
            if (selection.length === newSelection.length) {
                this.list.setSelection([...newSelection, focus], e.browserEvent);
            }
            else {
                this.list.setSelection(newSelection, e.browserEvent);
            }
        }
    }
    dispose() {
        this.disposables.dispose();
    }
}
class DefaultStyleController {
    constructor(styleElement, selectorSuffix) {
        this.styleElement = styleElement;
        this.selectorSuffix = selectorSuffix;
    }
    style(styles) {
        const suffix = this.selectorSuffix && `.${this.selectorSuffix}`;
        const content = [];
        if (styles.listBackground) {
            if (styles.listBackground.isOpaque()) {
                content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`);
            }
            else if (!isMacintosh) { // subpixel AA doesn't exist in macOS
                console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`);
            }
        }
        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}; }`); // overwrite :hover style in this case!
        }
        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}; }`); // overwrite :hover style in this case!
        }
        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.listFocusAndSelectionOutline) {
            content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { outline-color: ${styles.listFocusAndSelectionOutline} !important; }`);
        }
        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}; }`); // overwrite :hover style in this case!
        }
        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}; }`); // overwrite :hover style in this case!
        }
        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}; }`); // overwrite :hover style in this case!
        }
        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) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`);
        }
        if (styles.listHoverForeground) {
            content.push(`.monaco-list${suffix} .monaco-list-row:hover:not(.selected):not(.focused) { color:  ${styles.listHoverForeground}; }`);
        }
        if (styles.listSelectionOutline) {
            content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; 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; }
			`);
        }
        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.listDropBackground) {
            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.listDropBackground} !important; color: inherit !important; }
			`);
        }
        if (styles.tableColumnsBorder) {
            content.push(`
				.monaco-table:hover > .monaco-split-view2,
				.monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before {
					border-color: ${styles.tableColumnsBorder};
			}`);
        }
        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.styleElement.textContent = content.join('\n');
    }
}
const defaultStyles = {
    listFocusBackground: Color.fromHex('#7FB0D0'),
    listActiveSelectionBackground: Color.fromHex('#0E639C'),
    listActiveSelectionForeground: Color.fromHex('#FFFFFF'),
    listActiveSelectionIconForeground: Color.fromHex('#FFFFFF'),
    listFocusAndSelectionOutline: Color.fromHex('#90C2F9'),
    listFocusAndSelectionBackground: Color.fromHex('#094771'),
    listFocusAndSelectionForeground: Color.fromHex('#FFFFFF'),
    listInactiveSelectionBackground: Color.fromHex('#3F3F46'),
    listInactiveSelectionIconForeground: Color.fromHex('#FFFFFF'),
    listHoverBackground: Color.fromHex('#2A2D2E'),
    listDropBackground: Color.fromHex('#383B3D'),
    treeIndentGuidesStroke: Color.fromHex('#a9a9a9'),
    tableColumnsBorder: Color.fromHex('#cccccc').transparent(0.2),
    tableOddRowsBackgroundColor: Color.fromHex('#cccccc').transparent(0.04)
};
const listWidget_DefaultOptions = {
    keyboardSupport: true,
    mouseSupport: true,
    multipleSelectionSupport: true,
    dnd: {
        getDragURI() { return null; },
        onDragStart() { },
        onDragOver() { return false; },
        drop() { }
    }
};
// TODO@Joao: move these utils into a SortedArray class
function getContiguousRangeContaining(range, value) {
    const index = range.indexOf(value);
    if (index === -1) {
        return [];
    }
    const result = [];
    let i = index - 1;
    while (i >= 0 && range[i] === value - (index - i)) {
        result.push(range[i--]);
    }
    result.reverse();
    i = index;
    while (i < range.length && range[i] === value + (i - index)) {
        result.push(range[i++]);
    }
    return result;
}
/**
 * Given two sorted collections of numbers, returns the intersection
 * between them (OR).
 */
function disjunction(one, other) {
    const result = [];
    let i = 0, j = 0;
    while (i < one.length || j < other.length) {
        if (i >= one.length) {
            result.push(other[j++]);
        }
        else if (j >= other.length) {
            result.push(one[i++]);
        }
        else if (one[i] === other[j]) {
            result.push(one[i]);
            i++;
            j++;
            continue;
        }
        else if (one[i] < other[j]) {
            result.push(one[i++]);
        }
        else {
            result.push(other[j++]);
        }
    }
    return result;
}
/**
 * Given two sorted collections of numbers, returns the relative
 * complement between them (XOR).
 */
function relativeComplement(one, other) {
    const result = [];
    let i = 0, j = 0;
    while (i < one.length || j < other.length) {
        if (i >= one.length) {
            result.push(other[j++]);
        }
        else if (j >= other.length) {
            result.push(one[i++]);
        }
        else if (one[i] === other[j]) {
            i++;
            j++;
            continue;
        }
        else if (one[i] < other[j]) {
            result.push(one[i++]);
        }
        else {
            j++;
        }
    }
    return result;
}
const numericSort = (a, b) => a - b;
class PipelineRenderer {
    constructor(_templateId, renderers) {
        this._templateId = _templateId;
        this.renderers = renderers;
    }
    get templateId() {
        return this._templateId;
    }
    renderTemplate(container) {
        return this.renderers.map(r => r.renderTemplate(container));
    }
    renderElement(element, index, templateData, height) {
        let i = 0;
        for (const renderer of this.renderers) {
            renderer.renderElement(element, index, templateData[i++], height);
        }
    }
    disposeElement(element, index, templateData, height) {
        var _a;
        let i = 0;
        for (const renderer of this.renderers) {
            (_a = renderer.disposeElement) === null || _a === void 0 ? void 0 : _a.call(renderer, element, index, templateData[i], height);
            i += 1;
        }
    }
    disposeTemplate(templateData) {
        let i = 0;
        for (const renderer of this.renderers) {
            renderer.disposeTemplate(templateData[i++]);
        }
    }
}
class AccessibiltyRenderer {
    constructor(accessibilityProvider) {
        this.accessibilityProvider = accessibilityProvider;
        this.templateId = 'a18n';
    }
    renderTemplate(container) {
        return container;
    }
    renderElement(element, index, container) {
        const ariaLabel = this.accessibilityProvider.getAriaLabel(element);
        if (ariaLabel) {
            container.setAttribute('aria-label', ariaLabel);
        }
        else {
            container.removeAttribute('aria-label');
        }
        const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element);
        if (typeof ariaLevel === 'number') {
            container.setAttribute('aria-level', `${ariaLevel}`);
        }
        else {
            container.removeAttribute('aria-level');
        }
    }
    disposeTemplate(templateData) {
        // noop
    }
}
class ListViewDragAndDrop {
    constructor(list, dnd) {
        this.list = list;
        this.dnd = dnd;
    }
    getDragElements(element) {
        const selection = this.list.getSelectedElements();
        const elements = selection.indexOf(element) > -1 ? selection : [element];
        return elements;
    }
    getDragURI(element) {
        return this.dnd.getDragURI(element);
    }
    getDragLabel(elements, originalEvent) {
        if (this.dnd.getDragLabel) {
            return this.dnd.getDragLabel(elements, originalEvent);
        }
        return undefined;
    }
    onDragStart(data, originalEvent) {
        var _a, _b;
        (_b = (_a = this.dnd).onDragStart) === null || _b === void 0 ? void 0 : _b.call(_a, data, originalEvent);
    }
    onDragOver(data, targetElement, targetIndex, originalEvent) {
        return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent);
    }
    onDragLeave(data, targetElement, targetIndex, originalEvent) {
        var _a, _b;
        (_b = (_a = this.dnd).onDragLeave) === null || _b === void 0 ? void 0 : _b.call(_a, data, targetElement, targetIndex, originalEvent);
    }
    onDragEnd(originalEvent) {
        var _a, _b;
        (_b = (_a = this.dnd).onDragEnd) === null || _b === void 0 ? void 0 : _b.call(_a, originalEvent);
    }
    drop(data, targetElement, targetIndex, originalEvent) {
        this.dnd.drop(data, targetElement, targetIndex, originalEvent);
    }
}
/**
 * The {@link List} is a virtual scrolling widget, built on top of the {@link ListView}
 * widget.
 *
 * Features:
 * - Customizable keyboard and mouse support
 * - Element traits: focus, selection, achor
 * - Accessibility support
 * - Touch support
 * - Performant template-based rendering
 * - Horizontal scrolling
 * - Variable element height support
 * - Dynamic element height support
 * - Drag-and-drop support
 */
class List {
    constructor(user, container, virtualDelegate, renderers, _options = listWidget_DefaultOptions) {
        var _a, _b, _c, _d;
        this.user = user;
        this._options = _options;
        this.focus = new Trait('focused');
        this.anchor = new Trait('anchor');
        this.eventBufferer = new EventBufferer();
        this._ariaLabel = '';
        this.disposables = new DisposableStore();
        this._onDidDispose = new Emitter();
        this.onDidDispose = this._onDidDispose.event;
        const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? (_a = this._options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.getWidgetRole() : 'list';
        this.selection = new SelectionTrait(role !== 'listbox');
        mixin(_options, defaultStyles, false);
        const baseRenderers = [this.focus.renderer, this.selection.renderer];
        this.accessibilityProvider = _options.accessibilityProvider;
        if (this.accessibilityProvider) {
            baseRenderers.push(new AccessibiltyRenderer(this.accessibilityProvider));
            (_c = (_b = this.accessibilityProvider).onDidChangeActiveDescendant) === null || _c === void 0 ? void 0 : _c.call(_b, this.onDidChangeActiveDescendant, this, this.disposables);
        }
        renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r]));
        const viewOptions = Object.assign(Object.assign({}, _options), { dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) });
        this.view = new ListView(container, virtualDelegate, renderers, viewOptions);
        this.view.domNode.setAttribute('role', role);
        if (_options.styleController) {
            this.styleController = _options.styleController(this.view.domId);
        }
        else {
            const styleElement = createStyleSheet(this.view.domNode);
            this.styleController = new DefaultStyleController(styleElement, this.view.domId);
        }
        this.spliceable = new CombinedSpliceable([
            new TraitSpliceable(this.focus, this.view, _options.identityProvider),
            new TraitSpliceable(this.selection, this.view, _options.identityProvider),
            new TraitSpliceable(this.anchor, this.view, _options.identityProvider),
            this.view
        ]);
        this.disposables.add(this.focus);
        this.disposables.add(this.selection);
        this.disposables.add(this.anchor);
        this.disposables.add(this.view);
        this.disposables.add(this._onDidDispose);
        this.disposables.add(new DOMFocusController(this, this.view));
        if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) {
            this.keyboardController = new KeyboardController(this, this.view, _options);
            this.disposables.add(this.keyboardController);
        }
        if (_options.keyboardNavigationLabelProvider) {
            const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate;
            this.typeNavigationController = new TypeNavigationController(this, this.view, _options.keyboardNavigationLabelProvider, (_d = _options.keyboardNavigationEventFilter) !== null && _d !== void 0 ? _d : (() => true), delegate);
            this.disposables.add(this.typeNavigationController);
        }
        this.mouseController = this.createMouseController(_options);
        this.disposables.add(this.mouseController);
        this.onDidChangeFocus(this._onFocusChange, this, this.disposables);
        this.onDidChangeSelection(this._onSelectionChange, this, this.disposables);
        if (this.accessibilityProvider) {
            this.ariaLabel = this.accessibilityProvider.getWidgetAriaLabel();
        }
        if (this._options.multipleSelectionSupport !== false) {
            this.view.domNode.setAttribute('aria-multiselectable', 'true');
        }
    }
    get onDidChangeFocus() {
        return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e), this.disposables);
    }
    get onDidChangeSelection() {
        return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e), this.disposables);
    }
    get domId() { return this.view.domId; }
    get onMouseClick() { return this.view.onMouseClick; }
    get onMouseDblClick() { return this.view.onMouseDblClick; }
    get onMouseMiddleClick() { return this.view.onMouseMiddleClick; }
    get onPointer() { return this.mouseController.onPointer; }
    get onMouseDown() { return this.view.onMouseDown; }
    get onMouseOver() { return this.view.onMouseOver; }
    get onTouchStart() { return this.view.onTouchStart; }
    get onTap() { return this.view.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 = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event))
            .map(e => new StandardKeyboardEvent(e))
            .filter(e => didJustPressContextMenuKey = e.keyCode === 58 /* KeyCode.ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* KeyCode.F10 */))
            .map(stopEvent)
            .filter(() => false)
            .event;
        const fromKeyUp = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keyup')).event))
            .forEach(() => didJustPressContextMenuKey = false)
            .map(e => new StandardKeyboardEvent(e))
            .filter(e => e.keyCode === 58 /* KeyCode.ContextMenu */ || (e.shiftKey && e.keyCode === 68 /* KeyCode.F10 */))
            .map(stopEvent)
            .map(({ browserEvent }) => {
            const focus = this.getFocus();
            const index = focus.length ? focus[0] : undefined;
            const element = typeof index !== 'undefined' ? this.view.element(index) : undefined;
            const anchor = typeof index !== 'undefined' ? this.view.domElement(index) : this.view.domNode;
            return { index, element, anchor, browserEvent };
        })
            .event;
        const fromMouse = this.disposables.add(Event.chain(this.view.onContextMenu))
            .filter(_ => !didJustPressContextMenuKey)
            .map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.pageX + 1, y: browserEvent.pageY }, browserEvent }))
            .event;
        return Event.any(fromKeyDown, fromKeyUp, fromMouse);
    }
    get onKeyDown() { return this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event; }
    get onDidFocus() { return Event.signal(this.disposables.add(new DomEmitter(this.view.domNode, 'focus', true)).event); }
    createMouseController(options) {
        return new MouseController(this);
    }
    updateOptions(optionsUpdate = {}) {
        var _a, _b;
        this._options = Object.assign(Object.assign({}, this._options), optionsUpdate);
        (_a = this.typeNavigationController) === null || _a === void 0 ? void 0 : _a.updateOptions(this._options);
        if (this._options.multipleSelectionController !== undefined) {
            if (this._options.multipleSelectionSupport) {
                this.view.domNode.setAttribute('aria-multiselectable', 'true');
            }
            else {
                this.view.domNode.removeAttribute('aria-multiselectable');
            }
        }
        this.mouseController.updateOptions(optionsUpdate);
        (_b = this.keyboardController) === null || _b === void 0 ? void 0 : _b.updateOptions(optionsUpdate);
        this.view.updateOptions(optionsUpdate);
    }
    get options() {
        return this._options;
    }
    splice(start, deleteCount, elements = []) {
        if (start < 0 || start > this.view.length) {
            throw new ListError(this.user, `Invalid start index: ${start}`);
        }
        if (deleteCount < 0) {
            throw new ListError(this.user, `Invalid delete count: ${deleteCount}`);
        }
        if (deleteCount === 0 && elements.length === 0) {
            return;
        }
        this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements));
    }
    rerender() {
        this.view.rerender();
    }
    element(index) {
        return this.view.element(index);
    }
    get length() {
        return this.view.length;
    }
    get contentHeight() {
        return this.view.contentHeight;
    }
    get scrollTop() {
        return this.view.getScrollTop();
    }
    set scrollTop(scrollTop) {
        this.view.setScrollTop(scrollTop);
    }
    get ariaLabel() {
        return this._ariaLabel;
    }
    set ariaLabel(value) {
        this._ariaLabel = value;
        this.view.domNode.setAttribute('aria-label', value);
    }
    domFocus() {
        this.view.domNode.focus({ preventScroll: true });
    }
    layout(height, width) {
        this.view.layout(height, width);
    }
    setSelection(indexes, browserEvent) {
        for (const index of indexes) {
            if (index < 0 || index >= this.length) {
                throw new ListError(this.user, `Invalid index ${index}`);
            }
        }
        this.selection.set(indexes, browserEvent);
    }
    getSelection() {
        return this.selection.get();
    }
    getSelectedElements() {
        return this.getSelection().map(i => this.view.element(i));
    }
    setAnchor(index) {
        if (typeof index === 'undefined') {
            this.anchor.set([]);
            return;
        }
        if (index < 0 || index >= this.length) {
            throw new ListError(this.user, `Invalid index ${index}`);
        }
        this.anchor.set([index]);
    }
    getAnchor() {
        return firstOrDefault(this.anchor.get(), undefined);
    }
    getAnchorElement() {
        const anchor = this.getAnchor();
        return typeof anchor === 'undefined' ? undefined : this.element(anchor);
    }
    setFocus(indexes, browserEvent) {
        for (const index of indexes) {
            if (index < 0 || index >= this.length) {
                throw new ListError(this.user, `Invalid index ${index}`);
            }
        }
        this.focus.set(indexes, browserEvent);
    }
    focusNext(n = 1, loop = false, browserEvent, filter) {
        if (this.length === 0) {
            return;
        }
        const focus = this.focus.get();
        const index = this.findNextIndex(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.focus.get();
        const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter);
        if (index > -1) {
            this.setFocus([index], browserEvent);
        }
    }
    focusNextPage(browserEvent, filter) {
        return listWidget_awaiter(this, void 0, void 0, function* () {
            let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight);
            lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
            const currentlyFocusedElementIndex = this.getFocus()[0];
            if (currentlyFocusedElementIndex !== lastPageIndex && (currentlyFocusedElementIndex === undefined || lastPageIndex > currentlyFocusedElementIndex)) {
                const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter);
                if (lastGoodPageIndex > -1 && currentlyFocusedElementIndex !== lastGoodPageIndex) {
                    this.setFocus([lastGoodPageIndex], browserEvent);
                }
                else {
                    this.setFocus([lastPageIndex], browserEvent);
                }
            }
            else {
                const previousScrollTop = this.view.getScrollTop();
                let nextpageScrollTop = previousScrollTop + this.view.renderHeight;
                if (lastPageIndex > currentlyFocusedElementIndex) {
                    // scroll last page element to the top only if the last page element is below the focused element
                    nextpageScrollTop -= this.view.elementHeight(lastPageIndex);
                }
                this.view.setScrollTop(nextpageScrollTop);
                if (this.view.getScrollTop() !== previousScrollTop) {
                    this.setFocus([]);
                    // Let the scroll event listener run
                    yield timeout(0);
                    yield this.focusNextPage(browserEvent, filter);
                }
            }
        });
    }
    focusPreviousPage(browserEvent, filter) {
        return listWidget_awaiter(this, void 0, void 0, function* () {
            let firstPageIndex;
            const scrollTop = this.view.getScrollTop();
            if (scrollTop === 0) {
                firstPageIndex = this.view.indexAt(scrollTop);
            }
            else {
                firstPageIndex = this.view.indexAfter(scrollTop - 1);
            }
            const currentlyFocusedElementIndex = this.getFocus()[0];
            if (currentlyFocusedElementIndex !== firstPageIndex && (currentlyFocusedElementIndex === undefined || currentlyFocusedElementIndex >= firstPageIndex)) {
                const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter);
                if (firstGoodPageIndex > -1 && currentlyFocusedElementIndex !== firstGoodPageIndex) {
                    this.setFocus([firstGoodPageIndex], browserEvent);
                }
                else {
                    this.setFocus([firstPageIndex], browserEvent);
                }
            }
            else {
                const previousScrollTop = scrollTop;
                this.view.setScrollTop(scrollTop - this.view.renderHeight);
                if (this.view.getScrollTop() !== previousScrollTop) {
                    this.setFocus([]);
                    // Let the scroll event listener run
                    yield timeout(0);
                    yield this.focusPreviousPage(browserEvent, filter);
                }
            }
        });
    }
    focusLast(browserEvent, filter) {
        if (this.length === 0) {
            return;
        }
        const index = this.findPreviousIndex(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.findNextIndex(n, false, filter);
        if (index > -1) {
            this.setFocus([index], browserEvent);
        }
    }
    findNextIndex(index, loop = false, filter) {
        for (let i = 0; i < this.length; i++) {
            if (index >= this.length && !loop) {
                return -1;
            }
            index = index % this.length;
            if (!filter || filter(this.element(index))) {
                return index;
            }
            index++;
        }
        return -1;
    }
    findPreviousIndex(index, loop = false, filter) {
        for (let i = 0; i < this.length; i++) {
            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.focus.get();
    }
    getFocusedElements() {
        return this.getFocus().map(i => this.view.element(i));
    }
    reveal(index, relativeTop) {
        if (index < 0 || index >= this.length) {
            throw new ListError(this.user, `Invalid index ${index}`);
        }
        const scrollTop = this.view.getScrollTop();
        const elementTop = this.view.elementTop(index);
        const elementHeight = this.view.elementHeight(index);
        if (isNumber(relativeTop)) {
            // y = mx + b
            const m = elementHeight - this.view.renderHeight;
            this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop);
        }
        else {
            const viewItemBottom = elementTop + elementHeight;
            const scrollBottom = scrollTop + this.view.renderHeight;
            if (elementTop < scrollTop && viewItemBottom >= scrollBottom) {
                // The element is already overflowing the viewport, no-op
            }
            else if (elementTop < scrollTop || (viewItemBottom >= scrollBottom && elementHeight >= this.view.renderHeight)) {
                this.view.setScrollTop(elementTop);
            }
            else if (viewItemBottom >= scrollBottom) {
                this.view.setScrollTop(viewItemBottom - this.view.renderHeight);
            }
        }
    }
    getHTMLElement() {
        return this.view.domNode;
    }
    getElementID(index) {
        return this.view.getElementDomId(index);
    }
    style(styles) {
        this.styleController.style(styles);
    }
    toListEvent({ indexes, browserEvent }) {
        return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent };
    }
    _onFocusChange() {
        const focus = this.focus.get();
        this.view.domNode.classList.toggle('element-focused', focus.length > 0);
        this.onDidChangeActiveDescendant();
    }
    onDidChangeActiveDescendant() {
        var _a;
        const focus = this.focus.get();
        if (focus.length > 0) {
            let id;
            if ((_a = this.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.getActiveDescendantId) {
                id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0]));
            }
            this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0]));
        }
        else {
            this.view.domNode.removeAttribute('aria-activedescendant');
        }
    }
    _onSelectionChange() {
        const selection = this.selection.get();
        this.view.domNode.classList.toggle('selection-none', selection.length === 0);
        this.view.domNode.classList.toggle('selection-single', selection.length === 1);
        this.view.domNode.classList.toggle('selection-multiple', selection.length > 1);
    }
    dispose() {
        this._onDidDispose.fire();
        this.disposables.dispose();
        this._onDidDispose.dispose();
    }
}
listWidget_decorate([
    memoize
], List.prototype, "onDidChangeFocus", null);
listWidget_decorate([
    memoize
], List.prototype, "onDidChangeSelection", null);
listWidget_decorate([
    memoize
], List.prototype, "onContextMenu", null);
listWidget_decorate([
    memoize
], List.prototype, "onKeyDown", null);
listWidget_decorate([
    memoize
], List.prototype, "onDidFocus", null);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/media/action.css
var action = __webpack_require__(33252);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/media/action.css

      
      
      
      
      
      
      
      
      

var action_options = {};

action_options.styleTagTransform = (styleTagTransform_default());
action_options.setAttributes = (setAttributesWithoutAttributes_default());

      action_options.insert = insertBySelector_default().bind(null, "head");
    
action_options.domAPI = (styleDomAPI_default());
action_options.insertStyleElement = (insertStyleElement_default());

var action_update = injectStylesIntoStyleTag_default()(action/* default */.A, action_options);




       /* harmony default export */ const media_action = (action/* default */.A && action/* default */.A.locals ? action/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/platform/contextview/browser/contextView.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const IContextViewService = createDecorator('contextViewService');
const IContextMenuService = createDecorator('contextMenuService');

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/codeActionMenu.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var codeActionMenu_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var codeActionMenu_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var codeActionMenu_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};


















const Context = {
    Visible: new RawContextKey('CodeActionMenuVisible', false, localize('CodeActionMenuVisible', "Whether the code action list widget is visible"))
};
class CodeActionAction extends Action {
    constructor(action, callback) {
        super(action.command ? action.command.id : action.title, stripNewlines(action.title), undefined, !action.disabled, callback);
        this.action = action;
    }
}
function stripNewlines(str) {
    return str.replace(/\r\n|\r|\n/g, ' ');
}
const TEMPLATE_ID = 'codeActionWidget';
const codeActionLineHeight = 26;
let CodeMenuRenderer = class CodeMenuRenderer {
    constructor(acceptKeybindings, keybindingService) {
        this.acceptKeybindings = acceptKeybindings;
        this.keybindingService = keybindingService;
    }
    get templateId() { return TEMPLATE_ID; }
    renderTemplate(container) {
        const data = Object.create(null);
        data.disposables = [];
        data.root = container;
        data.text = document.createElement('span');
        // data.detail = document.createElement('');
        container.append(data.text);
        // container.append(data.detail);
        return data;
    }
    renderElement(element, index, templateData) {
        const data = templateData;
        const text = element.title;
        // const detail = element.detail;
        const isEnabled = element.isEnabled;
        const isSeparator = element.isSeparator;
        const isDocumentation = element.isDocumentation;
        data.text.textContent = text;
        // data.detail.textContent = detail;
        if (!isEnabled) {
            data.root.classList.add('option-disabled');
            data.root.style.backgroundColor = 'transparent !important';
        }
        else {
            data.root.classList.remove('option-disabled');
        }
        if (isSeparator) {
            data.root.classList.add('separator');
            data.root.style.height = '10px';
        }
        if (!isDocumentation) {
            const updateLabel = () => {
                var _a, _b;
                const [accept, preview] = this.acceptKeybindings;
                data.root.title = localize({ key: 'label', comment: ['placeholders are keybindings, e.g "F2 to Refactor, Shift+F2 to Preview"'] }, "{0} to Refactor, {1} to Preview", (_a = this.keybindingService.lookupKeybinding(accept)) === null || _a === void 0 ? void 0 : _a.getLabel(), (_b = this.keybindingService.lookupKeybinding(preview)) === null || _b === void 0 ? void 0 : _b.getLabel());
                // data.root.title = this.keybindingService.lookupKeybinding(accept)?.getLabel() + ' to Refactor, ' + this.keybindingService.lookupKeybinding(preview)?.getLabel() + ' to Preview';
            };
            updateLabel();
        }
    }
    disposeTemplate(templateData) {
        templateData.disposables = dispose(templateData.disposables);
    }
};
CodeMenuRenderer = codeActionMenu_decorate([
    codeActionMenu_param(1, IKeybindingService)
], CodeMenuRenderer);
let CodeActionMenu = class CodeActionMenu extends Disposable {
    constructor(_editor, _delegate, _contextMenuService, keybindingService, _languageFeaturesService, _telemetryService, _themeService, _configurationService, _contextViewService, _contextKeyService) {
        super();
        this._editor = _editor;
        this._delegate = _delegate;
        this._contextMenuService = _contextMenuService;
        this._languageFeaturesService = _languageFeaturesService;
        this._telemetryService = _telemetryService;
        this._configurationService = _configurationService;
        this._contextViewService = _contextViewService;
        this._contextKeyService = _contextKeyService;
        this._showingActions = this._register(new MutableDisposable());
        this.codeActionList = this._register(new MutableDisposable());
        this.options = [];
        this._visible = false;
        this.viewItems = [];
        this.hasSeperator = false;
        this._keybindingResolver = new CodeActionKeybindingResolver({
            getKeybindings: () => keybindingService.getKeybindings()
        });
        this._ctxMenuWidgetVisible = Context.Visible.bindTo(this._contextKeyService);
        this.listRenderer = new CodeMenuRenderer([`onEnterSelectCodeAction`, `onEnterSelectCodeActionWithPreview`], keybindingService);
    }
    get isVisible() {
        return this._visible;
    }
    isCodeActionWidgetEnabled(model) {
        return this._configurationService.getValue('editor.experimental.useCustomCodeActionMenu', {
            resource: model.uri
        });
    }
    _onListSelection(e) {
        if (e.elements.length) {
            e.elements.forEach(element => {
                if (element.isEnabled) {
                    element.action.run();
                    this.hideCodeActionWidget();
                }
            });
        }
    }
    _onListHover(e) {
        var _a, _b, _c, _d;
        if (!e.element) {
            this.currSelectedItem = undefined;
            (_a = this.codeActionList.value) === null || _a === void 0 ? void 0 : _a.setFocus([]);
        }
        else {
            if ((_b = e.element) === null || _b === void 0 ? void 0 : _b.isEnabled) {
                (_c = this.codeActionList.value) === null || _c === void 0 ? void 0 : _c.setFocus([e.element.index]);
                this.focusedEnabledItem = this.viewItems.indexOf(e.element);
                this.currSelectedItem = e.element.index;
            }
            else {
                this.currSelectedItem = undefined;
                (_d = this.codeActionList.value) === null || _d === void 0 ? void 0 : _d.setFocus([e.element.index]);
            }
        }
    }
    renderCodeActionMenuList(element, inputArray) {
        var _a;
        const renderDisposables = new DisposableStore();
        const renderMenu = document.createElement('div');
        // Render invisible div to block mouse interaction in the rest of the UI
        const menuBlock = document.createElement('div');
        this.block = element.appendChild(menuBlock);
        this.block.classList.add('context-view-block');
        this.block.style.position = 'fixed';
        this.block.style.cursor = 'initial';
        this.block.style.left = '0';
        this.block.style.top = '0';
        this.block.style.width = '100%';
        this.block.style.height = '100%';
        this.block.style.zIndex = '-1';
        renderDisposables.add(addDisposableListener(this.block, EventType.MOUSE_DOWN, e => e.stopPropagation()));
        renderMenu.id = 'codeActionMenuWidget';
        renderMenu.classList.add('codeActionMenuWidget');
        element.appendChild(renderMenu);
        this.codeActionList.value = new List('codeActionWidget', renderMenu, {
            getHeight(element) {
                if (element.isSeparator) {
                    return 10;
                }
                return codeActionLineHeight;
            },
            getTemplateId(element) {
                return 'codeActionWidget';
            }
        }, [this.listRenderer], { keyboardSupport: false });
        renderDisposables.add(this.codeActionList.value.onMouseOver(e => this._onListHover(e)));
        renderDisposables.add(this.codeActionList.value.onDidChangeFocus(e => { var _a; return (_a = this.codeActionList.value) === null || _a === void 0 ? void 0 : _a.domFocus(); }));
        renderDisposables.add(this.codeActionList.value.onDidChangeSelection(e => this._onListSelection(e)));
        renderDisposables.add(this._editor.onDidLayoutChange(e => this.hideCodeActionWidget()));
        // Populating the list widget and tracking enabled options.
        inputArray.forEach((item, index) => {
            const currIsSeparator = item.class === 'separator';
            let isDocumentation = false;
            if (item instanceof CodeActionAction) {
                isDocumentation = item.action.kind === CodeActionMenu.documentationID;
            }
            if (currIsSeparator) {
                // set to true forever
                this.hasSeperator = true;
            }
            const menuItem = { title: item.label, detail: item.tooltip, action: inputArray[index], isEnabled: item.enabled, isSeparator: currIsSeparator, index, isDocumentation };
            if (item.enabled) {
                this.viewItems.push(menuItem);
            }
            this.options.push(menuItem);
        });
        this.codeActionList.value.splice(0, this.codeActionList.value.length, this.options);
        const height = this.hasSeperator ? (inputArray.length - 1) * codeActionLineHeight + 10 : inputArray.length * codeActionLineHeight;
        renderMenu.style.height = String(height) + 'px';
        this.codeActionList.value.layout(height);
        // For finding width dynamically (not using resize observer)
        const arr = [];
        this.options.forEach((item, index) => {
            var _a, _b;
            if (!this.codeActionList.value) {
                return;
            }
            const element = (_b = document.getElementById((_a = this.codeActionList.value) === null || _a === void 0 ? void 0 : _a.getElementID(index))) === null || _b === void 0 ? void 0 : _b.getElementsByTagName('span')[0].offsetWidth;
            arr.push(Number(element));
        });
        // resize observer - can be used in the future since list widget supports dynamic height but not width
        const maxWidth = Math.max(...arr);
        // 40 is the additional padding for the list widget (20 left, 20 right)
        renderMenu.style.width = maxWidth + 52 + 'px';
        (_a = this.codeActionList.value) === null || _a === void 0 ? void 0 : _a.layout(height, maxWidth);
        // List selection
        if (this.viewItems.length < 1 || this.viewItems.every(item => item.isDocumentation)) {
            this.currSelectedItem = undefined;
        }
        else {
            this.focusedEnabledItem = 0;
            this.currSelectedItem = this.viewItems[0].index;
            this.codeActionList.value.setFocus([this.currSelectedItem]);
        }
        // List Focus
        this.codeActionList.value.domFocus();
        const focusTracker = trackFocus(element);
        const blurListener = focusTracker.onDidBlur(() => {
            this.hideCodeActionWidget();
            // this._contextViewService.hideContextView({ source: this });
        });
        renderDisposables.add(blurListener);
        renderDisposables.add(focusTracker);
        this._ctxMenuWidgetVisible.set(true);
        return renderDisposables;
    }
    focusPrevious() {
        var _a;
        if (typeof this.focusedEnabledItem === 'undefined') {
            this.focusedEnabledItem = this.viewItems[0].index;
        }
        else if (this.viewItems.length < 1) {
            return false;
        }
        const startIndex = this.focusedEnabledItem;
        let item;
        do {
            this.focusedEnabledItem = this.focusedEnabledItem - 1;
            if (this.focusedEnabledItem < 0) {
                this.focusedEnabledItem = this.viewItems.length - 1;
            }
            item = this.viewItems[this.focusedEnabledItem];
            (_a = this.codeActionList.value) === null || _a === void 0 ? void 0 : _a.setFocus([item.index]);
            this.currSelectedItem = item.index;
        } while (this.focusedEnabledItem !== startIndex && ((!item.isEnabled) || item.action.id === Separator.ID));
        return true;
    }
    focusNext() {
        var _a;
        if (typeof this.focusedEnabledItem === 'undefined') {
            this.focusedEnabledItem = this.viewItems.length - 1;
        }
        else if (this.viewItems.length < 1) {
            return false;
        }
        const startIndex = this.focusedEnabledItem;
        let item;
        do {
            this.focusedEnabledItem = (this.focusedEnabledItem + 1) % this.viewItems.length;
            item = this.viewItems[this.focusedEnabledItem];
            (_a = this.codeActionList.value) === null || _a === void 0 ? void 0 : _a.setFocus([item.index]);
            this.currSelectedItem = item.index;
        } while (this.focusedEnabledItem !== startIndex && ((!item.isEnabled) || item.action.id === Separator.ID));
        return true;
    }
    navigateListWithKeysUp() {
        this.focusPrevious();
    }
    navigateListWithKeysDown() {
        this.focusNext();
    }
    onEnterSet() {
        var _a;
        if (typeof this.currSelectedItem === 'number') {
            (_a = this.codeActionList.value) === null || _a === void 0 ? void 0 : _a.setSelection([this.currSelectedItem]);
        }
    }
    dispose() {
        super.dispose();
    }
    hideCodeActionWidget() {
        this._ctxMenuWidgetVisible.reset();
        this.options = [];
        this.viewItems = [];
        this.focusedEnabledItem = 0;
        this.currSelectedItem = undefined;
        this.hasSeperator = false;
        this._contextViewService.hideContextView({ source: this });
    }
    codeActionTelemetry(openedFromString, didCancel, CodeActions) {
        this._telemetryService.publicLog2('codeAction.applyCodeAction', {
            codeActionFrom: openedFromString,
            validCodeActions: CodeActions.validActions.length,
            cancelled: didCancel,
        });
    }
    show(trigger, codeActions, at, options) {
        return codeActionMenu_awaiter(this, void 0, void 0, function* () {
            const model = this._editor.getModel();
            if (!model) {
                return;
            }
            const actionsToShow = options.includeDisabledActions ? codeActions.allActions : codeActions.validActions;
            if (!actionsToShow.length) {
                this._visible = false;
                return;
            }
            if (!this._editor.getDomNode()) {
                // cancel when editor went off-dom
                this._visible = false;
                throw canceled();
            }
            this._visible = true;
            this._showingActions.value = codeActions;
            const menuActions = this.getMenuActions(trigger, actionsToShow, codeActions.documentation);
            const anchor = Position.isIPosition(at) ? this._toCoords(at) : at || { x: 0, y: 0 };
            const resolver = this._keybindingResolver.getResolver();
            const useShadowDOM = this._editor.getOption(117 /* EditorOption.useShadowDOM */);
            if (this.isCodeActionWidgetEnabled(model)) {
                this._contextViewService.showContextView({
                    getAnchor: () => anchor,
                    render: (container) => this.renderCodeActionMenuList(container, menuActions),
                    onHide: (didCancel) => {
                        const openedFromString = (options.fromLightbulb) ? CodeActionTriggerSource.Lightbulb : trigger.triggerAction;
                        this.codeActionTelemetry(openedFromString, didCancel, codeActions);
                        this._visible = false;
                        this._editor.focus();
                    },
                }, this._editor.getDomNode(), false);
            }
            else {
                this._contextMenuService.showContextMenu({
                    domForShadowRoot: useShadowDOM ? this._editor.getDomNode() : undefined,
                    getAnchor: () => anchor,
                    getActions: () => menuActions,
                    onHide: (didCancel) => {
                        const openedFromString = (options.fromLightbulb) ? CodeActionTriggerSource.Lightbulb : trigger.triggerAction;
                        this.codeActionTelemetry(openedFromString, didCancel, codeActions);
                        this._visible = false;
                        this._editor.focus();
                    },
                    autoSelectFirstItem: true,
                    getKeyBinding: action => action instanceof CodeActionAction ? resolver(action.action) : undefined,
                });
            }
        });
    }
    getMenuActions(trigger, actionsToShow, documentation) {
        var _a, _b;
        const toCodeActionAction = (item) => new CodeActionAction(item.action, () => this._delegate.onSelectCodeAction(item, trigger));
        const result = actionsToShow
            .map(toCodeActionAction);
        const allDocumentation = [...documentation];
        const model = this._editor.getModel();
        if (model && result.length) {
            for (const provider of this._languageFeaturesService.codeActionProvider.all(model)) {
                if (provider._getAdditionalMenuItems) {
                    allDocumentation.push(...provider._getAdditionalMenuItems({ trigger: trigger.type, only: (_b = (_a = trigger.filter) === null || _a === void 0 ? void 0 : _a.include) === null || _b === void 0 ? void 0 : _b.value }, actionsToShow.map(item => item.action)));
                }
            }
        }
        if (allDocumentation.length) {
            result.push(new Separator(), ...allDocumentation.map(command => toCodeActionAction(new CodeActionItem({
                title: command.title,
                command: command,
                kind: CodeActionMenu.documentationID
            }, undefined))));
        }
        return result;
    }
    _toCoords(position) {
        if (!this._editor.hasModel()) {
            return { x: 0, y: 0 };
        }
        this._editor.revealPosition(position, 1 /* ScrollType.Immediate */);
        this._editor.render();
        // Translate to absolute editor position
        const cursorCoords = this._editor.getScrolledVisiblePosition(position);
        const editorCoords = getDomNodePagePosition(this._editor.getDomNode());
        const x = editorCoords.left + cursorCoords.left;
        const y = editorCoords.top + cursorCoords.top + cursorCoords.height;
        return { x, y };
    }
};
CodeActionMenu.documentationID = '_documentation';
CodeActionMenu = codeActionMenu_decorate([
    codeActionMenu_param(2, IContextMenuService),
    codeActionMenu_param(3, IKeybindingService),
    codeActionMenu_param(4, ILanguageFeaturesService),
    codeActionMenu_param(5, ITelemetryService),
    codeActionMenu_param(6, IThemeService),
    codeActionMenu_param(7, IConfigurationService),
    codeActionMenu_param(8, IContextViewService),
    codeActionMenu_param(9, IContextKeyService)
], CodeActionMenu);

class CodeActionKeybindingResolver {
    constructor(_keybindingProvider) {
        this._keybindingProvider = _keybindingProvider;
    }
    getResolver() {
        // Lazy since we may not actually ever read the value
        const allCodeActionBindings = new Lazy(() => this._keybindingProvider.getKeybindings()
            .filter(item => CodeActionKeybindingResolver.codeActionCommands.indexOf(item.command) >= 0)
            .filter(item => item.resolvedKeybinding)
            .map((item) => {
            // Special case these commands since they come built-in with VS Code and don't use 'commandArgs'
            let commandArgs = item.commandArgs;
            if (item.command === organizeImportsCommandId) {
                commandArgs = { kind: CodeActionKind.SourceOrganizeImports.value };
            }
            else if (item.command === fixAllCommandId) {
                commandArgs = { kind: CodeActionKind.SourceFixAll.value };
            }
            return Object.assign({ resolvedKeybinding: item.resolvedKeybinding }, CodeActionCommandArgs.fromUser(commandArgs, {
                kind: CodeActionKind.None,
                apply: "never" /* CodeActionAutoApply.Never */
            }));
        }));
        return (action) => {
            if (action.kind) {
                const binding = this.bestKeybindingForCodeAction(action, allCodeActionBindings.getValue());
                return binding === null || binding === void 0 ? void 0 : binding.resolvedKeybinding;
            }
            return undefined;
        };
    }
    bestKeybindingForCodeAction(action, candidates) {
        if (!action.kind) {
            return undefined;
        }
        const kind = new CodeActionKind(action.kind);
        return candidates
            .filter(candidate => candidate.kind.contains(kind))
            .filter(candidate => {
            if (candidate.preferred) {
                // If the candidate keybinding only applies to preferred actions, the this action must also be preferred
                return action.isPreferred;
            }
            return true;
        })
            .reduceRight((currentBest, candidate) => {
            if (!currentBest) {
                return candidate;
            }
            // Select the more specific binding
            return currentBest.kind.contains(candidate.kind) ? candidate : currentBest;
        }, undefined);
    }
}
CodeActionKeybindingResolver.codeActionCommands = [
    refactorCommandId,
    codeActionCommandId,
    sourceActionCommandId,
    organizeImportsCommandId,
    fixAllCommandId
];

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/lightBulbWidget.css
var lightBulbWidget = __webpack_require__(32383);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/lightBulbWidget.css

      
      
      
      
      
      
      
      
      

var lightBulbWidget_options = {};

lightBulbWidget_options.styleTagTransform = (styleTagTransform_default());
lightBulbWidget_options.setAttributes = (setAttributesWithoutAttributes_default());

      lightBulbWidget_options.insert = insertBySelector_default().bind(null, "head");
    
lightBulbWidget_options.domAPI = (styleDomAPI_default());
lightBulbWidget_options.insertStyleElement = (insertStyleElement_default());

var lightBulbWidget_update = injectStylesIntoStyleTag_default()(lightBulbWidget/* default */.A, lightBulbWidget_options);




       /* harmony default export */ const browser_lightBulbWidget = (lightBulbWidget/* default */.A && lightBulbWidget/* default */.A.locals ? lightBulbWidget/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/lightBulbWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var lightBulbWidget_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var lightBulbWidget_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};











var LightBulbState;
(function (LightBulbState) {
    LightBulbState.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 /* Type.Showing */;
        }
    }
    LightBulbState.Showing = Showing;
})(LightBulbState || (LightBulbState = {}));
let LightBulbWidget = class LightBulbWidget extends Disposable {
    constructor(_editor, _quickFixActionId, _preferredFixActionId, _keybindingService) {
        super();
        this._editor = _editor;
        this._quickFixActionId = _quickFixActionId;
        this._preferredFixActionId = _preferredFixActionId;
        this._keybindingService = _keybindingService;
        this._onClick = this._register(new Emitter());
        this.onClick = this._onClick.event;
        this._state = LightBulbState.Hidden;
        this._domNode = document.createElement('div');
        this._domNode.className = Codicon.lightBulb.classNames;
        this._editor.addContentWidget(this);
        this._register(this._editor.onDidChangeModelContent(_ => {
            // cancel when the line in question has been removed
            const editorModel = this._editor.getModel();
            if (this.state.type !== 1 /* LightBulbState.Type.Showing */ || !editorModel || this.state.editorPosition.lineNumber >= editorModel.getLineCount()) {
                this.hide();
            }
        }));
        Gesture.ignoreTarget(this._domNode);
        this._register(addStandardDisposableGenericMouseDownListener(this._domNode, e => {
            if (this.state.type !== 1 /* LightBulbState.Type.Showing */) {
                return;
            }
            // Make sure that focus / cursor location is not lost when clicking widget icon
            this._editor.focus();
            e.preventDefault();
            // a bit of extra work to make sure the menu
            // doesn't cover the line-text
            const { top, height } = getDomNodePagePosition(this._domNode);
            const lineHeight = this._editor.getOption(61 /* EditorOption.lineHeight */);
            let pad = Math.floor(lineHeight / 3);
            if (this.state.widgetPosition.position !== null && this.state.widgetPosition.position.lineNumber < this.state.editorPosition.lineNumber) {
                pad += lineHeight;
            }
            this._onClick.fire({
                x: e.posx,
                y: top + height + pad,
                actions: this.state.actions,
                trigger: this.state.trigger,
            });
        }));
        this._register(addDisposableListener(this._domNode, 'mouseenter', (e) => {
            if ((e.buttons & 1) !== 1) {
                return;
            }
            // mouse enters lightbulb while the primary/left button
            // is being pressed -> hide the lightbulb
            this.hide();
        }));
        this._register(this._editor.onDidChangeConfiguration(e => {
            // hide when told to do so
            if (e.hasChanged(59 /* EditorOption.lightbulb */) && !this._editor.getOption(59 /* EditorOption.lightbulb */).enabled) {
                this.hide();
            }
        }));
        this._updateLightBulbTitleAndIcon();
        this._register(this._keybindingService.onDidUpdateKeybindings(this._updateLightBulbTitleAndIcon, this));
    }
    dispose() {
        super.dispose();
        this._editor.removeContentWidget(this);
    }
    getId() {
        return 'LightBulbWidget';
    }
    getDomNode() {
        return this._domNode;
    }
    getPosition() {
        return this._state.type === 1 /* LightBulbState.Type.Showing */ ? this._state.widgetPosition : null;
    }
    update(actions, trigger, atPosition) {
        if (actions.validActions.length <= 0) {
            return this.hide();
        }
        const options = this._editor.getOptions();
        if (!options.get(59 /* EditorOption.lightbulb */).enabled) {
            return this.hide();
        }
        const model = this._editor.getModel();
        if (!model) {
            return this.hide();
        }
        const { lineNumber, column } = model.validatePosition(atPosition);
        const tabSize = model.getOptions().tabSize;
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        const lineContent = model.getLineContent(lineNumber);
        const indent = computeIndentLevel(lineContent, tabSize);
        const lineHasSpace = fontInfo.spaceWidth * indent > 22;
        const isFolded = (lineNumber) => {
            return lineNumber > 2 && this._editor.getTopForLineNumber(lineNumber) === this._editor.getTopForLineNumber(lineNumber - 1);
        };
        let effectiveLineNumber = lineNumber;
        if (!lineHasSpace) {
            if (lineNumber > 1 && !isFolded(lineNumber - 1)) {
                effectiveLineNumber -= 1;
            }
            else if (!isFolded(lineNumber + 1)) {
                effectiveLineNumber += 1;
            }
            else if (column * fontInfo.spaceWidth < 22) {
                // cannot show lightbulb above/below and showing
                // it inline would overlay the cursor...
                return this.hide();
            }
        }
        this.state = new LightBulbState.Showing(actions, trigger, atPosition, {
            position: { lineNumber: effectiveLineNumber, column: 1 },
            preference: LightBulbWidget._posPref
        });
        this._editor.layoutContentWidget(this);
    }
    hide() {
        this.state = LightBulbState.Hidden;
        this._editor.layoutContentWidget(this);
    }
    get state() { return this._state; }
    set state(value) {
        this._state = value;
        this._updateLightBulbTitleAndIcon();
    }
    _updateLightBulbTitleAndIcon() {
        if (this.state.type === 1 /* LightBulbState.Type.Showing */ && this.state.actions.hasAutoFix) {
            // update icon
            this._domNode.classList.remove(...Codicon.lightBulb.classNamesArray);
            this._domNode.classList.add(...Codicon.lightbulbAutofix.classNamesArray);
            const preferredKb = this._keybindingService.lookupKeybinding(this._preferredFixActionId);
            if (preferredKb) {
                this.title = localize('preferredcodeActionWithKb', "Show Code Actions. Preferred Quick Fix Available ({0})", preferredKb.getLabel());
                return;
            }
        }
        // update icon
        this._domNode.classList.remove(...Codicon.lightbulbAutofix.classNamesArray);
        this._domNode.classList.add(...Codicon.lightBulb.classNamesArray);
        const kb = this._keybindingService.lookupKeybinding(this._quickFixActionId);
        if (kb) {
            this.title = localize('codeActionWithKb', "Show Code Actions ({0})", kb.getLabel());
        }
        else {
            this.title = localize('codeAction', "Show Code Actions");
        }
    }
    set title(value) {
        this._domNode.title = value;
    }
};
LightBulbWidget._posPref = [0 /* ContentWidgetPositionPreference.EXACT */];
LightBulbWidget = lightBulbWidget_decorate([
    lightBulbWidget_param(3, IKeybindingService)
], LightBulbWidget);

registerThemingParticipant((theme, collector) => {
    var _a;
    const editorBackgroundColor = (_a = theme.getColor(editorBackground)) === null || _a === void 0 ? void 0 : _a.transparent(0.7);
    // Lightbulb Icon
    const editorLightBulbForegroundColor = theme.getColor(editorLightBulbForeground);
    if (editorLightBulbForegroundColor) {
        collector.addRule(`
		.monaco-editor .contentWidgets ${Codicon.lightBulb.cssSelector} {
			color: ${editorLightBulbForegroundColor};
			background-color: ${editorBackgroundColor};
		}`);
    }
    // Lightbulb Auto Fix Icon
    const editorLightBulbAutoFixForegroundColor = theme.getColor(editorLightBulbAutoFixForeground);
    if (editorLightBulbAutoFixForegroundColor) {
        collector.addRule(`
		.monaco-editor .contentWidgets ${Codicon.lightbulbAutofix.cssSelector} {
			color: ${editorLightBulbAutoFixForegroundColor};
			background-color: ${editorBackgroundColor};
		}`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/codeActionUi.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var codeActionUi_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var codeActionUi_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var codeActionUi_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (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;
};
var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (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);
};
var _CodeActionUi_disposed;







let CodeActionUi = class CodeActionUi extends Disposable {
    constructor(_editor, quickFixActionId, preferredFixActionId, delegate, instantiationService) {
        super();
        this._editor = _editor;
        this.delegate = delegate;
        this._activeCodeActions = this._register(new MutableDisposable());
        this.previewOn = false;
        _CodeActionUi_disposed.set(this, false);
        this._codeActionWidget = new Lazy(() => {
            return this._register(instantiationService.createInstance(CodeActionMenu, this._editor, {
                onSelectCodeAction: (action, trigger) => codeActionUi_awaiter(this, void 0, void 0, function* () {
                    if (this.previewOn) {
                        this.delegate.applyCodeAction(action, /* retrigger */ true, Boolean(this.previewOn));
                    }
                    else {
                        this.delegate.applyCodeAction(action, /* retrigger */ true, Boolean(trigger.preview));
                    }
                    this.previewOn = false;
                })
            }));
        });
        this._lightBulbWidget = new Lazy(() => {
            const widget = this._register(instantiationService.createInstance(LightBulbWidget, this._editor, quickFixActionId, preferredFixActionId));
            this._register(widget.onClick(e => this.showCodeActionList(e.trigger, e.actions, e, { includeDisabledActions: false, fromLightbulb: true })));
            return widget;
        });
    }
    dispose() {
        __classPrivateFieldSet(this, _CodeActionUi_disposed, true, "f");
        super.dispose();
    }
    hideCodeActionWidget() {
        if (this._codeActionWidget.hasValue()) {
            this._codeActionWidget.getValue().hideCodeActionWidget();
        }
    }
    onEnter() {
        if (this._codeActionWidget.hasValue()) {
            this._codeActionWidget.getValue().onEnterSet();
        }
    }
    onPreviewEnter() {
        this.previewOn = true;
        this.onEnter();
    }
    navigateList(navUp) {
        if (this._codeActionWidget.hasValue()) {
            if (navUp) {
                this._codeActionWidget.getValue().navigateListWithKeysUp();
            }
            else {
                this._codeActionWidget.getValue().navigateListWithKeysDown();
            }
        }
    }
    update(newState) {
        var _a, _b, _c, _d, _e;
        return codeActionUi_awaiter(this, void 0, void 0, function* () {
            if (newState.type !== 1 /* CodeActionsState.Type.Triggered */) {
                (_a = this._lightBulbWidget.rawValue) === null || _a === void 0 ? void 0 : _a.hide();
                return;
            }
            let actions;
            try {
                actions = yield newState.actions;
            }
            catch (e) {
                onUnexpectedError(e);
                return;
            }
            if (__classPrivateFieldGet(this, _CodeActionUi_disposed, "f")) {
                return;
            }
            this._lightBulbWidget.getValue().update(actions, newState.trigger, newState.position);
            if (newState.trigger.type === 1 /* CodeActionTriggerType.Invoke */) {
                if ((_b = newState.trigger.filter) === null || _b === void 0 ? void 0 : _b.include) { // Triggered for specific scope
                    // Check to see if we want to auto apply.
                    const validActionToApply = this.tryGetValidActionToApply(newState.trigger, actions);
                    if (validActionToApply) {
                        try {
                            this._lightBulbWidget.getValue().hide();
                            yield this.delegate.applyCodeAction(validActionToApply, false, false);
                        }
                        finally {
                            actions.dispose();
                        }
                        return;
                    }
                    // Check to see if there is an action that we would have applied were it not invalid
                    if (newState.trigger.context) {
                        const invalidAction = this.getInvalidActionThatWouldHaveBeenApplied(newState.trigger, actions);
                        if (invalidAction && invalidAction.action.disabled) {
                            (_c = MessageController.get(this._editor)) === null || _c === void 0 ? void 0 : _c.showMessage(invalidAction.action.disabled, newState.trigger.context.position);
                            actions.dispose();
                            return;
                        }
                    }
                }
                const includeDisabledActions = !!((_d = newState.trigger.filter) === null || _d === void 0 ? void 0 : _d.include);
                if (newState.trigger.context) {
                    if (!actions.allActions.length || !includeDisabledActions && !actions.validActions.length) {
                        (_e = MessageController.get(this._editor)) === null || _e === void 0 ? void 0 : _e.showMessage(newState.trigger.context.notAvailableMessage, newState.trigger.context.position);
                        this._activeCodeActions.value = actions;
                        actions.dispose();
                        return;
                    }
                }
                this._activeCodeActions.value = actions;
                this._codeActionWidget.getValue().show(newState.trigger, actions, newState.position, { includeDisabledActions, fromLightbulb: false });
            }
            else {
                // auto magically triggered
                if (this._codeActionWidget.getValue().isVisible) {
                    // TODO: Figure out if we should update the showing menu?
                    actions.dispose();
                }
                else {
                    this._activeCodeActions.value = actions;
                }
            }
        });
    }
    getInvalidActionThatWouldHaveBeenApplied(trigger, actions) {
        if (!actions.allActions.length) {
            return undefined;
        }
        if ((trigger.autoApply === "first" /* CodeActionAutoApply.First */ && actions.validActions.length === 0)
            || (trigger.autoApply === "ifSingle" /* CodeActionAutoApply.IfSingle */ && actions.allActions.length === 1)) {
            return actions.allActions.find(({ action }) => action.disabled);
        }
        return undefined;
    }
    tryGetValidActionToApply(trigger, actions) {
        if (!actions.validActions.length) {
            return undefined;
        }
        if ((trigger.autoApply === "first" /* CodeActionAutoApply.First */ && actions.validActions.length > 0)
            || (trigger.autoApply === "ifSingle" /* CodeActionAutoApply.IfSingle */ && actions.validActions.length === 1)) {
            return actions.validActions[0];
        }
        return undefined;
    }
    showCodeActionList(trigger, actions, at, options) {
        return codeActionUi_awaiter(this, void 0, void 0, function* () {
            this._codeActionWidget.getValue().show(trigger, actions, at, options);
        });
    }
};
_CodeActionUi_disposed = new WeakMap();
CodeActionUi = codeActionUi_decorate([
    codeActionUi_param(4, IInstantiationService)
], CodeActionUi);


;// ../../node_modules/monaco-editor/esm/vs/base/common/severity.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

var Severity;
(function (Severity) {
    Severity[Severity["Ignore"] = 0] = "Ignore";
    Severity[Severity["Info"] = 1] = "Info";
    Severity[Severity["Warning"] = 2] = "Warning";
    Severity[Severity["Error"] = 3] = "Error";
})(Severity || (Severity = {}));
(function (Severity) {
    const _error = 'error';
    const _warning = 'warning';
    const _warn = 'warn';
    const _info = 'info';
    const _ignore = 'ignore';
    /**
     * Parses 'error', 'warning', 'warn', 'info' in call casings
     * and falls back to ignore.
     */
    function fromValue(value) {
        if (!value) {
            return Severity.Ignore;
        }
        if (equalsIgnoreCase(_error, value)) {
            return Severity.Error;
        }
        if (equalsIgnoreCase(_warning, value) || equalsIgnoreCase(_warn, value)) {
            return Severity.Warning;
        }
        if (equalsIgnoreCase(_info, value)) {
            return Severity.Info;
        }
        return Severity.Ignore;
    }
    Severity.fromValue = fromValue;
    function toString(severity) {
        switch (severity) {
            case Severity.Error: return _error;
            case Severity.Warning: return _warning;
            case Severity.Info: return _info;
            default: return _ignore;
        }
    }
    Severity.toString = toString;
})(Severity || (Severity = {}));
/* harmony default export */ const common_severity = (Severity);

;// ../../node_modules/monaco-editor/esm/vs/platform/markers/common/markers.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



var MarkerSeverity;
(function (MarkerSeverity) {
    MarkerSeverity[MarkerSeverity["Hint"] = 1] = "Hint";
    MarkerSeverity[MarkerSeverity["Info"] = 2] = "Info";
    MarkerSeverity[MarkerSeverity["Warning"] = 4] = "Warning";
    MarkerSeverity[MarkerSeverity["Error"] = 8] = "Error";
})(MarkerSeverity || (MarkerSeverity = {}));
(function (MarkerSeverity) {
    function compare(a, b) {
        return b - a;
    }
    MarkerSeverity.compare = compare;
    const _displayStrings = Object.create(null);
    _displayStrings[MarkerSeverity.Error] = localize('sev.error', "Error");
    _displayStrings[MarkerSeverity.Warning] = localize('sev.warning', "Warning");
    _displayStrings[MarkerSeverity.Info] = localize('sev.info', "Info");
    function toString(a) {
        return _displayStrings[a] || '';
    }
    MarkerSeverity.toString = toString;
    function fromSeverity(severity) {
        switch (severity) {
            case common_severity.Error: return MarkerSeverity.Error;
            case common_severity.Warning: return MarkerSeverity.Warning;
            case common_severity.Info: return MarkerSeverity.Info;
            case common_severity.Ignore: return MarkerSeverity.Hint;
        }
    }
    MarkerSeverity.fromSeverity = fromSeverity;
    function toSeverity(severity) {
        switch (severity) {
            case MarkerSeverity.Error: return common_severity.Error;
            case MarkerSeverity.Warning: return common_severity.Warning;
            case MarkerSeverity.Info: return common_severity.Info;
            case MarkerSeverity.Hint: return common_severity.Ignore;
        }
    }
    MarkerSeverity.toSeverity = toSeverity;
})(MarkerSeverity || (MarkerSeverity = {}));
var IMarkerData;
(function (IMarkerData) {
    const emptyString = '';
    function makeKey(markerData) {
        return makeKeyOptionalMessage(markerData, true);
    }
    IMarkerData.makeKey = makeKey;
    function makeKeyOptionalMessage(markerData, useMessage) {
        const result = [emptyString];
        if (markerData.source) {
            result.push(markerData.source.replace('¦', '\\¦'));
        }
        else {
            result.push(emptyString);
        }
        if (markerData.code) {
            if (typeof markerData.code === 'string') {
                result.push(markerData.code.replace('¦', '\\¦'));
            }
            else {
                result.push(markerData.code.value.replace('¦', '\\¦'));
            }
        }
        else {
            result.push(emptyString);
        }
        if (markerData.severity !== undefined && markerData.severity !== null) {
            result.push(MarkerSeverity.toString(markerData.severity));
        }
        else {
            result.push(emptyString);
        }
        // Modifed to not include the message as part of the marker key to work around
        // https://github.com/microsoft/vscode/issues/77475
        if (markerData.message && useMessage) {
            result.push(markerData.message.replace('¦', '\\¦'));
        }
        else {
            result.push(emptyString);
        }
        if (markerData.startLineNumber !== undefined && markerData.startLineNumber !== null) {
            result.push(markerData.startLineNumber.toString());
        }
        else {
            result.push(emptyString);
        }
        if (markerData.startColumn !== undefined && markerData.startColumn !== null) {
            result.push(markerData.startColumn.toString());
        }
        else {
            result.push(emptyString);
        }
        if (markerData.endLineNumber !== undefined && markerData.endLineNumber !== null) {
            result.push(markerData.endLineNumber.toString());
        }
        else {
            result.push(emptyString);
        }
        if (markerData.endColumn !== undefined && markerData.endColumn !== null) {
            result.push(markerData.endColumn.toString());
        }
        else {
            result.push(emptyString);
        }
        result.push(emptyString);
        return result.join('¦');
    }
    IMarkerData.makeKeyOptionalMessage = makeKeyOptionalMessage;
})(IMarkerData || (IMarkerData = {}));
const IMarkerService = createDecorator('markerService');

;// ../../node_modules/monaco-editor/esm/vs/platform/notification/common/notification.js


var notification_Severity = common_severity;
const INotificationService = createDecorator('notificationService');
class NoOpNotification {
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/codeActionModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var codeActionModel_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (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);
};
var codeActionModel_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (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;
};
var _CodeActionModel_isDisposed;










const SUPPORTED_CODE_ACTIONS = new RawContextKey('supportedCodeAction', '');
class CodeActionOracle extends Disposable {
    constructor(_editor, _markerService, _signalChange, _delay = 250) {
        super();
        this._editor = _editor;
        this._markerService = _markerService;
        this._signalChange = _signalChange;
        this._delay = _delay;
        this._autoTriggerTimer = this._register(new TimeoutTimer());
        this._register(this._markerService.onMarkerChanged(e => this._onMarkerChanges(e)));
        this._register(this._editor.onDidChangeCursorPosition(() => this._onCursorChange()));
    }
    trigger(trigger) {
        const selection = this._getRangeOfSelectionUnlessWhitespaceEnclosed(trigger);
        return this._createEventAndSignalChange(trigger, selection);
    }
    _onMarkerChanges(resources) {
        const model = this._editor.getModel();
        if (!model) {
            return;
        }
        if (resources.some(resource => isEqual(resource, model.uri))) {
            this._autoTriggerTimer.cancelAndSet(() => {
                this.trigger({ type: 2 /* CodeActionTriggerType.Auto */, triggerAction: CodeActionTriggerSource.Default });
            }, this._delay);
        }
    }
    _onCursorChange() {
        this._autoTriggerTimer.cancelAndSet(() => {
            this.trigger({ type: 2 /* CodeActionTriggerType.Auto */, triggerAction: CodeActionTriggerSource.Default });
        }, this._delay);
    }
    _getRangeOfMarker(selection) {
        const model = this._editor.getModel();
        if (!model) {
            return undefined;
        }
        for (const marker of this._markerService.read({ resource: model.uri })) {
            const markerRange = model.validateRange(marker);
            if (Range.intersectRanges(markerRange, selection)) {
                return Range.lift(markerRange);
            }
        }
        return undefined;
    }
    _getRangeOfSelectionUnlessWhitespaceEnclosed(trigger) {
        if (!this._editor.hasModel()) {
            return undefined;
        }
        const model = this._editor.getModel();
        const selection = this._editor.getSelection();
        if (selection.isEmpty() && trigger.type === 2 /* CodeActionTriggerType.Auto */) {
            const { lineNumber, column } = selection.getPosition();
            const line = model.getLineContent(lineNumber);
            if (line.length === 0) {
                // empty line
                return undefined;
            }
            else if (column === 1) {
                // look only right
                if (/\s/.test(line[0])) {
                    return undefined;
                }
            }
            else if (column === model.getLineMaxColumn(lineNumber)) {
                // look only left
                if (/\s/.test(line[line.length - 1])) {
                    return undefined;
                }
            }
            else {
                // look left and right
                if (/\s/.test(line[column - 2]) && /\s/.test(line[column - 1])) {
                    return undefined;
                }
            }
        }
        return selection;
    }
    _createEventAndSignalChange(trigger, selection) {
        const model = this._editor.getModel();
        if (!selection || !model) {
            // cancel
            this._signalChange(undefined);
            return undefined;
        }
        const markerRange = this._getRangeOfMarker(selection);
        const position = markerRange ? markerRange.getStartPosition() : selection.getStartPosition();
        const e = {
            trigger,
            selection,
            position
        };
        this._signalChange(e);
        return e;
    }
}
var CodeActionsState;
(function (CodeActionsState) {
    CodeActionsState.Empty = { type: 0 /* Type.Empty */ };
    class Triggered {
        constructor(trigger, rangeOrSelection, position, _cancellablePromise) {
            this.trigger = trigger;
            this.rangeOrSelection = rangeOrSelection;
            this.position = position;
            this._cancellablePromise = _cancellablePromise;
            this.type = 1 /* Type.Triggered */;
            this.actions = _cancellablePromise.catch((e) => {
                if (isCancellationError(e)) {
                    return emptyCodeActionSet;
                }
                throw e;
            });
        }
        cancel() {
            this._cancellablePromise.cancel();
        }
    }
    CodeActionsState.Triggered = Triggered;
})(CodeActionsState || (CodeActionsState = {}));
const emptyCodeActionSet = {
    allActions: [],
    validActions: [],
    dispose: () => { },
    documentation: [],
    hasAutoFix: false
};
class CodeActionModel extends Disposable {
    constructor(_editor, _registry, _markerService, contextKeyService, _progressService) {
        super();
        this._editor = _editor;
        this._registry = _registry;
        this._markerService = _markerService;
        this._progressService = _progressService;
        this._codeActionOracle = this._register(new MutableDisposable());
        this._state = CodeActionsState.Empty;
        this._onDidChangeState = this._register(new Emitter());
        this.onDidChangeState = this._onDidChangeState.event;
        _CodeActionModel_isDisposed.set(this, false);
        this._supportedCodeActions = SUPPORTED_CODE_ACTIONS.bindTo(contextKeyService);
        this._register(this._editor.onDidChangeModel(() => this._update()));
        this._register(this._editor.onDidChangeModelLanguage(() => this._update()));
        this._register(this._registry.onDidChange(() => this._update()));
        this._update();
    }
    dispose() {
        if (codeActionModel_classPrivateFieldGet(this, _CodeActionModel_isDisposed, "f")) {
            return;
        }
        codeActionModel_classPrivateFieldSet(this, _CodeActionModel_isDisposed, true, "f");
        super.dispose();
        this.setState(CodeActionsState.Empty, true);
    }
    _update() {
        if (codeActionModel_classPrivateFieldGet(this, _CodeActionModel_isDisposed, "f")) {
            return;
        }
        this._codeActionOracle.value = undefined;
        this.setState(CodeActionsState.Empty);
        const model = this._editor.getModel();
        if (model
            && this._registry.has(model)
            && !this._editor.getOption(83 /* EditorOption.readOnly */)) {
            const supportedActions = [];
            for (const provider of this._registry.all(model)) {
                if (Array.isArray(provider.providedCodeActionKinds)) {
                    supportedActions.push(...provider.providedCodeActionKinds);
                }
            }
            this._supportedCodeActions.set(supportedActions.join(' '));
            this._codeActionOracle.value = new CodeActionOracle(this._editor, this._markerService, trigger => {
                var _a;
                if (!trigger) {
                    this.setState(CodeActionsState.Empty);
                    return;
                }
                const actions = createCancelablePromise(token => getCodeActions(this._registry, model, trigger.selection, trigger.trigger, Progress.None, token));
                if (trigger.trigger.type === 1 /* CodeActionTriggerType.Invoke */) {
                    (_a = this._progressService) === null || _a === void 0 ? void 0 : _a.showWhile(actions, 250);
                }
                this.setState(new CodeActionsState.Triggered(trigger.trigger, trigger.selection, trigger.position, actions));
            }, undefined);
            this._codeActionOracle.value.trigger({ type: 2 /* CodeActionTriggerType.Auto */, triggerAction: CodeActionTriggerSource.Default });
        }
        else {
            this._supportedCodeActions.reset();
        }
    }
    trigger(trigger) {
        var _a;
        (_a = this._codeActionOracle.value) === null || _a === void 0 ? void 0 : _a.trigger(trigger);
    }
    setState(newState, skipNotify) {
        if (newState === this._state) {
            return;
        }
        // Cancel old request
        if (this._state.type === 1 /* CodeActionsState.Type.Triggered */) {
            this._state.cancel();
        }
        this._state = newState;
        if (!skipNotify && !codeActionModel_classPrivateFieldGet(this, _CodeActionModel_isDisposed, "f")) {
            this._onDidChangeState.fire(newState);
        }
    }
}
_CodeActionModel_isDisposed = new WeakMap();

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/codeActionCommands.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var codeActionCommands_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var codeActionCommands_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var codeActionCommands_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};






















function contextKeyForSupportedActions(kind) {
    return ContextKeyExpr.regex(SUPPORTED_CODE_ACTIONS.keys()[0], new RegExp('(\\s|^)' + escapeRegExpCharacters(kind.value) + '\\b'));
}
function refactorTrigger(editor, userArgs, preview, codeActionFrom) {
    const args = CodeActionCommandArgs.fromUser(userArgs, {
        kind: CodeActionKind.Refactor,
        apply: "never" /* CodeActionAutoApply.Never */
    });
    return triggerCodeActionsForEditorSelection(editor, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === 'string'
        ? args.preferred
            ? localize('editor.action.refactor.noneMessage.preferred.kind', "No preferred refactorings for '{0}' available", userArgs.kind)
            : localize('editor.action.refactor.noneMessage.kind', "No refactorings for '{0}' available", userArgs.kind)
        : args.preferred
            ? localize('editor.action.refactor.noneMessage.preferred', "No preferred refactorings available")
            : localize('editor.action.refactor.noneMessage', "No refactorings available"), {
        include: CodeActionKind.Refactor.contains(args.kind) ? args.kind : CodeActionKind.None,
        onlyIncludePreferredActions: args.preferred
    }, args.apply, preview, codeActionFrom);
}
const argsSchema = {
    type: 'object',
    defaultSnippets: [{ body: { kind: '' } }],
    properties: {
        'kind': {
            type: 'string',
            description: localize('args.schema.kind', "Kind of the code action to run."),
        },
        'apply': {
            type: 'string',
            description: localize('args.schema.apply', "Controls when the returned actions are applied."),
            default: "ifSingle" /* CodeActionAutoApply.IfSingle */,
            enum: ["first" /* CodeActionAutoApply.First */, "ifSingle" /* CodeActionAutoApply.IfSingle */, "never" /* CodeActionAutoApply.Never */],
            enumDescriptions: [
                localize('args.schema.apply.first', "Always apply the first returned code action."),
                localize('args.schema.apply.ifSingle', "Apply the first returned code action if it is the only one."),
                localize('args.schema.apply.never', "Do not apply the returned code actions."),
            ]
        },
        'preferred': {
            type: 'boolean',
            default: false,
            description: localize('args.schema.preferred', "Controls if only preferred code actions should be returned."),
        }
    }
};
let QuickFixController = class QuickFixController extends Disposable {
    constructor(editor, markerService, contextKeyService, progressService, _instantiationService, languageFeaturesService) {
        super();
        this._instantiationService = _instantiationService;
        this._editor = editor;
        this._model = this._register(new CodeActionModel(this._editor, languageFeaturesService.codeActionProvider, markerService, contextKeyService, progressService));
        this._register(this._model.onDidChangeState(newState => this.update(newState)));
        this._ui = new Lazy(() => this._register(new CodeActionUi(editor, QuickFixAction.Id, AutoFixAction.Id, {
            applyCodeAction: (action, retrigger, preview) => codeActionCommands_awaiter(this, void 0, void 0, function* () {
                try {
                    yield this._applyCodeAction(action, preview);
                }
                finally {
                    if (retrigger) {
                        this._trigger({ type: 2 /* CodeActionTriggerType.Auto */, triggerAction: CodeActionTriggerSource.QuickFix, filter: {} });
                    }
                }
            })
        }, this._instantiationService)));
    }
    static get(editor) {
        return editor.getContribution(QuickFixController.ID);
    }
    update(newState) {
        this._ui.getValue().update(newState);
    }
    hideCodeActionMenu() {
        if (this._ui.hasValue()) {
            this._ui.getValue().hideCodeActionWidget();
        }
    }
    navigateCodeActionList(navUp) {
        if (this._ui.hasValue()) {
            this._ui.getValue().navigateList(navUp);
        }
    }
    selectedOption() {
        if (this._ui.hasValue()) {
            this._ui.getValue().onEnter();
        }
    }
    selectedOptionWithPreview() {
        if (this._ui.hasValue()) {
            this._ui.getValue().onPreviewEnter();
        }
    }
    showCodeActions(trigger, actions, at) {
        return this._ui.getValue().showCodeActionList(trigger, actions, at, { includeDisabledActions: false, fromLightbulb: false });
    }
    manualTriggerAtCurrentPosition(notAvailableMessage, triggerAction, filter, autoApply, preview) {
        var _a;
        if (!this._editor.hasModel()) {
            return;
        }
        (_a = MessageController.get(this._editor)) === null || _a === void 0 ? void 0 : _a.closeMessage();
        const triggerPosition = this._editor.getPosition();
        this._trigger({ type: 1 /* CodeActionTriggerType.Invoke */, triggerAction, filter, autoApply, context: { notAvailableMessage, position: triggerPosition }, preview });
    }
    _trigger(trigger) {
        return this._model.trigger(trigger);
    }
    _applyCodeAction(action, preview) {
        return this._instantiationService.invokeFunction(applyCodeAction, action, ApplyCodeActionReason.FromCodeActions, { preview, editor: this._editor });
    }
};
QuickFixController.ID = 'editor.contrib.quickFixController';
QuickFixController = codeActionCommands_decorate([
    codeActionCommands_param(1, IMarkerService),
    codeActionCommands_param(2, IContextKeyService),
    codeActionCommands_param(3, IEditorProgressService),
    codeActionCommands_param(4, IInstantiationService),
    codeActionCommands_param(5, ILanguageFeaturesService)
], QuickFixController);

var ApplyCodeActionReason;
(function (ApplyCodeActionReason) {
    ApplyCodeActionReason["OnSave"] = "onSave";
    ApplyCodeActionReason["FromProblemsView"] = "fromProblemsView";
    ApplyCodeActionReason["FromCodeActions"] = "fromCodeActions";
})(ApplyCodeActionReason || (ApplyCodeActionReason = {}));
function applyCodeAction(accessor, item, codeActionReason, options) {
    return codeActionCommands_awaiter(this, void 0, void 0, function* () {
        const bulkEditService = accessor.get(IBulkEditService);
        const commandService = accessor.get(ICommandService);
        const telemetryService = accessor.get(ITelemetryService);
        const notificationService = accessor.get(INotificationService);
        telemetryService.publicLog2('codeAction.applyCodeAction', {
            codeActionTitle: item.action.title,
            codeActionKind: item.action.kind,
            codeActionIsPreferred: !!item.action.isPreferred,
            reason: codeActionReason,
        });
        yield item.resolve(CancellationToken.None);
        if (item.action.edit) {
            yield bulkEditService.apply(ResourceEdit.convert(item.action.edit), {
                editor: options === null || options === void 0 ? void 0 : options.editor,
                label: item.action.title,
                quotableLabel: item.action.title,
                code: 'undoredo.codeAction',
                respectAutoSaveConfig: true,
                showPreview: options === null || options === void 0 ? void 0 : options.preview,
            });
        }
        if (item.action.command) {
            try {
                yield commandService.executeCommand(item.action.command.id, ...(item.action.command.arguments || []));
            }
            catch (err) {
                const message = asMessage(err);
                notificationService.error(typeof message === 'string'
                    ? message
                    : localize('applyCodeActionFailed', "An unknown error occurred while applying the code action"));
            }
        }
    });
}
function asMessage(err) {
    if (typeof err === 'string') {
        return err;
    }
    else if (err instanceof Error && typeof err.message === 'string') {
        return err.message;
    }
    else {
        return undefined;
    }
}
function triggerCodeActionsForEditorSelection(editor, notAvailableMessage, filter, autoApply, preview = false, triggerAction = CodeActionTriggerSource.Default) {
    if (editor.hasModel()) {
        const controller = QuickFixController.get(editor);
        controller === null || controller === void 0 ? void 0 : controller.manualTriggerAtCurrentPosition(notAvailableMessage, triggerAction, filter, autoApply, preview);
    }
}
class QuickFixAction extends EditorAction {
    constructor() {
        super({
            id: QuickFixAction.Id,
            label: localize('quickfix.trigger.label', "Quick Fix..."),
            alias: 'Quick Fix...',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 84 /* KeyCode.Period */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor) {
        return triggerCodeActionsForEditorSelection(editor, localize('editor.action.quickFix.noneMessage', "No code actions available"), undefined, undefined, false, CodeActionTriggerSource.QuickFix);
    }
}
QuickFixAction.Id = 'editor.action.quickFix';
class CodeActionCommand extends EditorCommand {
    constructor() {
        super({
            id: codeActionCommandId,
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
            description: {
                description: 'Trigger a code action',
                args: [{ name: 'args', schema: argsSchema, }]
            }
        });
    }
    runEditorCommand(_accessor, editor, userArgs) {
        const args = CodeActionCommandArgs.fromUser(userArgs, {
            kind: CodeActionKind.Empty,
            apply: "ifSingle" /* CodeActionAutoApply.IfSingle */,
        });
        return triggerCodeActionsForEditorSelection(editor, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === 'string'
            ? args.preferred
                ? localize('editor.action.codeAction.noneMessage.preferred.kind', "No preferred code actions for '{0}' available", userArgs.kind)
                : localize('editor.action.codeAction.noneMessage.kind', "No code actions for '{0}' available", userArgs.kind)
            : args.preferred
                ? localize('editor.action.codeAction.noneMessage.preferred', "No preferred code actions available")
                : localize('editor.action.codeAction.noneMessage', "No code actions available"), {
            include: args.kind,
            includeSourceActions: true,
            onlyIncludePreferredActions: args.preferred,
        }, args.apply);
    }
}
class RefactorAction extends EditorAction {
    constructor() {
        super({
            id: refactorCommandId,
            label: localize('refactor.label', "Refactor..."),
            alias: 'Refactor...',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 48 /* KeyCode.KeyR */,
                mac: {
                    primary: 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 48 /* KeyCode.KeyR */
                },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            contextMenuOpts: {
                group: '1_modification',
                order: 2,
                when: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.Refactor)),
            },
            description: {
                description: 'Refactor...',
                args: [{ name: 'args', schema: argsSchema }]
            }
        });
    }
    run(_accessor, editor, userArgs) {
        return refactorTrigger(editor, userArgs, false, CodeActionTriggerSource.Refactor);
    }
}
class RefactorPreview extends EditorAction {
    constructor() {
        super({
            id: refactorPreviewCommandId,
            label: localize('refactor.preview.label', "Refactor with Preview..."),
            alias: 'Refactor Preview...',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
            description: {
                description: 'Refactor Preview...',
                args: [{ name: 'args', schema: argsSchema }]
            }
        });
    }
    run(_accessor, editor, userArgs) {
        return refactorTrigger(editor, userArgs, true, CodeActionTriggerSource.RefactorPreview);
    }
}
class SourceAction extends EditorAction {
    constructor() {
        super({
            id: sourceActionCommandId,
            label: localize('source.label', "Source Action..."),
            alias: 'Source Action...',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
            contextMenuOpts: {
                group: '1_modification',
                order: 2.1,
                when: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.Source)),
            },
            description: {
                description: 'Source Action...',
                args: [{ name: 'args', schema: argsSchema }]
            }
        });
    }
    run(_accessor, editor, userArgs) {
        const args = CodeActionCommandArgs.fromUser(userArgs, {
            kind: CodeActionKind.Source,
            apply: "never" /* CodeActionAutoApply.Never */
        });
        return triggerCodeActionsForEditorSelection(editor, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === 'string'
            ? args.preferred
                ? localize('editor.action.source.noneMessage.preferred.kind', "No preferred source actions for '{0}' available", userArgs.kind)
                : localize('editor.action.source.noneMessage.kind', "No source actions for '{0}' available", userArgs.kind)
            : args.preferred
                ? localize('editor.action.source.noneMessage.preferred', "No preferred source actions available")
                : localize('editor.action.source.noneMessage', "No source actions available"), {
            include: CodeActionKind.Source.contains(args.kind) ? args.kind : CodeActionKind.None,
            includeSourceActions: true,
            onlyIncludePreferredActions: args.preferred,
        }, args.apply, undefined, CodeActionTriggerSource.SourceAction);
    }
}
class OrganizeImportsAction extends EditorAction {
    constructor() {
        super({
            id: organizeImportsCommandId,
            label: localize('organizeImports.label', "Organize Imports"),
            alias: 'Organize Imports',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.SourceOrganizeImports)),
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 45 /* KeyCode.KeyO */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
        });
    }
    run(_accessor, editor) {
        return triggerCodeActionsForEditorSelection(editor, localize('editor.action.organize.noneMessage', "No organize imports action available"), { include: CodeActionKind.SourceOrganizeImports, includeSourceActions: true }, "ifSingle" /* CodeActionAutoApply.IfSingle */, undefined, CodeActionTriggerSource.OrganizeImports);
    }
}
class FixAllAction extends EditorAction {
    constructor() {
        super({
            id: fixAllCommandId,
            label: localize('fixAll.label', "Fix All"),
            alias: 'Fix All',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.SourceFixAll))
        });
    }
    run(_accessor, editor) {
        return triggerCodeActionsForEditorSelection(editor, localize('fixAll.noneMessage', "No fix all action available"), { include: CodeActionKind.SourceFixAll, includeSourceActions: true }, "ifSingle" /* CodeActionAutoApply.IfSingle */, undefined, CodeActionTriggerSource.FixAll);
    }
}
class AutoFixAction extends EditorAction {
    constructor() {
        super({
            id: AutoFixAction.Id,
            label: localize('autoFix.label', "Auto Fix..."),
            alias: 'Auto Fix...',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.QuickFix)),
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 84 /* KeyCode.Period */,
                mac: {
                    primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 84 /* KeyCode.Period */
                },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor) {
        return triggerCodeActionsForEditorSelection(editor, localize('editor.action.autoFix.noneMessage', "No auto fixes available"), {
            include: CodeActionKind.QuickFix,
            onlyIncludePreferredActions: true
        }, "ifSingle" /* CodeActionAutoApply.IfSingle */, undefined, CodeActionTriggerSource.AutoFix);
    }
}
AutoFixAction.Id = 'editor.action.autoFix';
const CodeActionContribution = EditorCommand.bindToContribution(QuickFixController.get);
const weight = 100 /* KeybindingWeight.EditorContrib */ + 90;
registerEditorCommand(new CodeActionContribution({
    id: 'hideCodeActionMenuWidget',
    precondition: Context.Visible,
    handler(x) {
        x.hideCodeActionMenu();
    },
    kbOpts: {
        weight: weight,
        primary: 9 /* KeyCode.Escape */,
        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
    }
}));
registerEditorCommand(new CodeActionContribution({
    id: 'focusPreviousCodeAction',
    precondition: Context.Visible,
    handler(x) {
        x.navigateCodeActionList(true);
    },
    kbOpts: {
        weight: weight + 100000,
        primary: 16 /* KeyCode.UpArrow */,
        secondary: [2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */],
    }
}));
registerEditorCommand(new CodeActionContribution({
    id: 'focusNextCodeAction',
    precondition: Context.Visible,
    handler(x) {
        x.navigateCodeActionList(false);
    },
    kbOpts: {
        weight: weight + 100000,
        primary: 18 /* KeyCode.DownArrow */,
        secondary: [2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */],
    }
}));
registerEditorCommand(new CodeActionContribution({
    id: 'onEnterSelectCodeAction',
    precondition: Context.Visible,
    handler(x) {
        x.selectedOption();
    },
    kbOpts: {
        weight: weight + 100000,
        primary: 3 /* KeyCode.Enter */,
        secondary: [1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */],
    }
}));
registerEditorCommand(new CodeActionContribution({
    id: 'onEnterSelectCodeActionWithPreview',
    precondition: Context.Visible,
    handler(x) {
        x.selectedOptionWithPreview();
    },
    kbOpts: {
        weight: weight + 100000,
        primary: 2048 /* KeyMod.CtrlCmd */ | 3 /* KeyCode.Enter */,
    }
}));

;// ../../node_modules/monaco-editor/esm/vs/editor/common/config/editorOptions.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






/**
 * @internal
 * The width of the minimap gutter, in pixels.
 */
const MINIMAP_GUTTER_WIDTH = 8;
//#endregion
/**
 * An event describing that the configuration of the editor has changed.
 */
class ConfigurationChangedEvent {
    /**
     * @internal
     */
    constructor(values) {
        this._values = values;
    }
    hasChanged(id) {
        return this._values[id];
    }
}
/**
 * @internal
 */
class ComputeOptionsMemory {
    constructor() {
        this.stableMinimapLayoutInput = null;
        this.stableFitMaxMinimapScale = 0;
        this.stableFitRemainingWidth = 0;
    }
}
/**
 * @internal
 */
class BaseEditorOption {
    constructor(id, name, defaultValue, schema) {
        this.id = id;
        this.name = name;
        this.defaultValue = defaultValue;
        this.schema = schema;
    }
    applyUpdate(value, update) {
        return applyUpdate(value, update);
    }
    compute(env, options, value) {
        return value;
    }
}
class ApplyUpdateResult {
    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) && equals(value, update);
        return new ApplyUpdateResult(update, !arrayEquals);
    }
    let didChange = false;
    for (const key in update) {
        if (update.hasOwnProperty(key)) {
            const result = applyUpdate(value[key], update[key]);
            if (result.didChange) {
                value[key] = result.newValue;
                didChange = true;
            }
        }
    }
    return new ApplyUpdateResult(value, didChange);
}
/**
 * @internal
 */
class ComputedEditorOption {
    constructor(id) {
        this.schema = undefined;
        this.id = id;
        this.name = '_never_';
        this.defaultValue = undefined;
    }
    applyUpdate(value, update) {
        return applyUpdate(value, update);
    }
    validate(input) {
        return this.defaultValue;
    }
}
class SimpleEditorOption {
    constructor(id, name, defaultValue, schema) {
        this.id = id;
        this.name = name;
        this.defaultValue = defaultValue;
        this.schema = schema;
    }
    applyUpdate(value, update) {
        return applyUpdate(value, update);
    }
    validate(input) {
        if (typeof input === 'undefined') {
            return this.defaultValue;
        }
        return input;
    }
    compute(env, options, value) {
        return value;
    }
}
/**
 * @internal
 */
function editorOptions_boolean(value, defaultValue) {
    if (typeof value === 'undefined') {
        return defaultValue;
    }
    if (value === 'false') {
        // treat the string 'false' as false
        return false;
    }
    return Boolean(value);
}
class EditorBooleanOption extends SimpleEditorOption {
    constructor(id, name, defaultValue, schema = undefined) {
        if (typeof schema !== 'undefined') {
            schema.type = 'boolean';
            schema.default = defaultValue;
        }
        super(id, name, defaultValue, schema);
    }
    validate(input) {
        return editorOptions_boolean(input, this.defaultValue);
    }
}
/**
 * @internal
 */
function clampedInt(value, defaultValue, minimum, maximum) {
    if (typeof value === 'undefined') {
        return defaultValue;
    }
    let r = parseInt(value, 10);
    if (isNaN(r)) {
        return defaultValue;
    }
    r = Math.max(minimum, r);
    r = Math.min(maximum, r);
    return r | 0;
}
class EditorIntOption extends SimpleEditorOption {
    constructor(id, name, defaultValue, minimum, maximum, schema = undefined) {
        if (typeof schema !== 'undefined') {
            schema.type = 'integer';
            schema.default = defaultValue;
            schema.minimum = minimum;
            schema.maximum = maximum;
        }
        super(id, name, defaultValue, schema);
        this.minimum = minimum;
        this.maximum = maximum;
    }
    static clampedInt(value, defaultValue, minimum, maximum) {
        return clampedInt(value, defaultValue, minimum, maximum);
    }
    validate(input) {
        return EditorIntOption.clampedInt(input, this.defaultValue, this.minimum, this.maximum);
    }
}
class EditorFloatOption extends SimpleEditorOption {
    constructor(id, name, defaultValue, validationFn, schema) {
        if (typeof schema !== 'undefined') {
            schema.type = 'number';
            schema.default = defaultValue;
        }
        super(id, name, defaultValue, schema);
        this.validationFn = validationFn;
    }
    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 r = parseFloat(value);
        return (isNaN(r) ? defaultValue : r);
    }
    validate(input) {
        return this.validationFn(EditorFloatOption.float(input, this.defaultValue));
    }
}
class EditorStringOption extends SimpleEditorOption {
    static string(value, defaultValue) {
        if (typeof value !== 'string') {
            return defaultValue;
        }
        return value;
    }
    constructor(id, name, defaultValue, schema = undefined) {
        if (typeof schema !== 'undefined') {
            schema.type = 'string';
            schema.default = defaultValue;
        }
        super(id, name, defaultValue, schema);
    }
    validate(input) {
        return EditorStringOption.string(input, this.defaultValue);
    }
}
/**
 * @internal
 */
function stringSet(value, defaultValue, allowedValues) {
    if (typeof value !== 'string') {
        return defaultValue;
    }
    if (allowedValues.indexOf(value) === -1) {
        return defaultValue;
    }
    return value;
}
class EditorStringEnumOption extends SimpleEditorOption {
    constructor(id, name, defaultValue, allowedValues, schema = undefined) {
        if (typeof schema !== 'undefined') {
            schema.type = 'string';
            schema.enum = allowedValues;
            schema.default = defaultValue;
        }
        super(id, name, defaultValue, schema);
        this._allowedValues = allowedValues;
    }
    validate(input) {
        return stringSet(input, this.defaultValue, this._allowedValues);
    }
}
class EditorEnumOption extends BaseEditorOption {
    constructor(id, name, defaultValue, defaultStringValue, allowedValues, convert, schema = undefined) {
        if (typeof schema !== 'undefined') {
            schema.type = 'string';
            schema.enum = allowedValues;
            schema.default = defaultStringValue;
        }
        super(id, name, defaultValue, schema);
        this._allowedValues = allowedValues;
        this._convert = convert;
    }
    validate(input) {
        if (typeof input !== 'string') {
            return this.defaultValue;
        }
        if (this._allowedValues.indexOf(input) === -1) {
            return this.defaultValue;
        }
        return this._convert(input);
    }
}
//#endregion
//#region autoIndent
function _autoIndentFromString(autoIndent) {
    switch (autoIndent) {
        case 'none': return 0 /* EditorAutoIndentStrategy.None */;
        case 'keep': return 1 /* EditorAutoIndentStrategy.Keep */;
        case 'brackets': return 2 /* EditorAutoIndentStrategy.Brackets */;
        case 'advanced': return 3 /* EditorAutoIndentStrategy.Advanced */;
        case 'full': return 4 /* EditorAutoIndentStrategy.Full */;
    }
}
//#endregion
//#region accessibilitySupport
class EditorAccessibilitySupport extends BaseEditorOption {
    constructor() {
        super(2 /* EditorOption.accessibilitySupport */, 'accessibilitySupport', 0 /* AccessibilitySupport.Unknown */, {
            type: 'string',
            enum: ['auto', 'on', 'off'],
            enumDescriptions: [
                localize('accessibilitySupport.auto', "The editor will use platform APIs to detect when a Screen Reader is attached."),
                localize('accessibilitySupport.on', "The editor will be permanently optimized for usage with a Screen Reader. Word wrapping will be disabled."),
                localize('accessibilitySupport.off', "The editor will never be optimized for usage with a Screen Reader."),
            ],
            default: 'auto',
            description: localize('accessibilitySupport', "Controls whether the editor should run in a mode where it is optimized for screen readers. Setting to on will disable word wrapping.")
        });
    }
    validate(input) {
        switch (input) {
            case 'auto': return 0 /* AccessibilitySupport.Unknown */;
            case 'off': return 1 /* AccessibilitySupport.Disabled */;
            case 'on': return 2 /* AccessibilitySupport.Enabled */;
        }
        return this.defaultValue;
    }
    compute(env, options, value) {
        if (value === 0 /* AccessibilitySupport.Unknown */) {
            // The editor reads the `accessibilitySupport` from the environment
            return env.accessibilitySupport;
        }
        return value;
    }
}
class EditorComments extends BaseEditorOption {
    constructor() {
        const defaults = {
            insertSpace: true,
            ignoreEmptyLines: true,
        };
        super(19 /* EditorOption.comments */, 'comments', defaults, {
            'editor.comments.insertSpace': {
                type: 'boolean',
                default: defaults.insertSpace,
                description: localize('comments.insertSpace', "Controls whether a space character is inserted when commenting.")
            },
            'editor.comments.ignoreEmptyLines': {
                type: 'boolean',
                default: defaults.ignoreEmptyLines,
                description: localize('comments.ignoreEmptyLines', 'Controls if empty lines should be ignored with toggle, add or remove actions for line comments.')
            },
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            insertSpace: editorOptions_boolean(input.insertSpace, this.defaultValue.insertSpace),
            ignoreEmptyLines: editorOptions_boolean(input.ignoreEmptyLines, this.defaultValue.ignoreEmptyLines),
        };
    }
}
function _cursorBlinkingStyleFromString(cursorBlinkingStyle) {
    switch (cursorBlinkingStyle) {
        case 'blink': return 1 /* TextEditorCursorBlinkingStyle.Blink */;
        case 'smooth': return 2 /* TextEditorCursorBlinkingStyle.Smooth */;
        case 'phase': return 3 /* TextEditorCursorBlinkingStyle.Phase */;
        case 'expand': return 4 /* TextEditorCursorBlinkingStyle.Expand */;
        case 'solid': return 5 /* TextEditorCursorBlinkingStyle.Solid */;
    }
}
//#endregion
//#region cursorStyle
/**
 * The style in which the editor's cursor should be rendered.
 */
var TextEditorCursorStyle;
(function (TextEditorCursorStyle) {
    /**
     * As a vertical line (sitting between two characters).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["Line"] = 1] = "Line";
    /**
     * As a block (sitting on top of a character).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["Block"] = 2] = "Block";
    /**
     * As a horizontal line (sitting under a character).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["Underline"] = 3] = "Underline";
    /**
     * As a thin vertical line (sitting between two characters).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["LineThin"] = 4] = "LineThin";
    /**
     * As an outlined block (sitting on top of a character).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["BlockOutline"] = 5] = "BlockOutline";
    /**
     * As a thin horizontal line (sitting under a character).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["UnderlineThin"] = 6] = "UnderlineThin";
})(TextEditorCursorStyle || (TextEditorCursorStyle = {}));
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;
    }
}
//#endregion
//#region editorClassName
class EditorClassName extends ComputedEditorOption {
    constructor() {
        super(130 /* EditorOption.editorClassName */);
    }
    compute(env, options, _) {
        const classNames = ['monaco-editor'];
        if (options.get(35 /* EditorOption.extraEditorClassName */)) {
            classNames.push(options.get(35 /* EditorOption.extraEditorClassName */));
        }
        if (env.extraEditorClassName) {
            classNames.push(env.extraEditorClassName);
        }
        if (options.get(68 /* EditorOption.mouseStyle */) === 'default') {
            classNames.push('mouse-default');
        }
        else if (options.get(68 /* EditorOption.mouseStyle */) === 'copy') {
            classNames.push('mouse-copy');
        }
        if (options.get(102 /* EditorOption.showUnused */)) {
            classNames.push('showUnused');
        }
        if (options.get(128 /* EditorOption.showDeprecated */)) {
            classNames.push('showDeprecated');
        }
        return classNames.join(' ');
    }
}
//#endregion
//#region emptySelectionClipboard
class EditorEmptySelectionClipboard extends EditorBooleanOption {
    constructor() {
        super(33 /* EditorOption.emptySelectionClipboard */, 'emptySelectionClipboard', true, { description: localize('emptySelectionClipboard', "Controls whether copying without a selection copies the current line.") });
    }
    compute(env, options, value) {
        return value && env.emptySelectionClipboard;
    }
}
class EditorFind extends BaseEditorOption {
    constructor() {
        const defaults = {
            cursorMoveOnType: true,
            seedSearchStringFromSelection: 'always',
            autoFindInSelection: 'never',
            globalFindClipboard: false,
            addExtraSpaceOnTop: true,
            loop: true
        };
        super(37 /* EditorOption.find */, 'find', defaults, {
            'editor.find.cursorMoveOnType': {
                type: 'boolean',
                default: defaults.cursorMoveOnType,
                description: localize('find.cursorMoveOnType', "Controls whether the cursor should jump to find matches while typing.")
            },
            'editor.find.seedSearchStringFromSelection': {
                type: 'string',
                enum: ['never', 'always', 'selection'],
                default: defaults.seedSearchStringFromSelection,
                enumDescriptions: [
                    localize('editor.find.seedSearchStringFromSelection.never', 'Never seed search string from the editor selection.'),
                    localize('editor.find.seedSearchStringFromSelection.always', 'Always seed search string from the editor selection, including word at cursor position.'),
                    localize('editor.find.seedSearchStringFromSelection.selection', 'Only seed search string from the editor selection.')
                ],
                description: localize('find.seedSearchStringFromSelection', "Controls whether the search string in the Find Widget is seeded from the editor selection.")
            },
            'editor.find.autoFindInSelection': {
                type: 'string',
                enum: ['never', 'always', 'multiline'],
                default: defaults.autoFindInSelection,
                enumDescriptions: [
                    localize('editor.find.autoFindInSelection.never', 'Never turn on Find in Selection automatically (default).'),
                    localize('editor.find.autoFindInSelection.always', 'Always turn on Find in Selection automatically.'),
                    localize('editor.find.autoFindInSelection.multiline', 'Turn on Find in Selection automatically when multiple lines of content are selected.')
                ],
                description: localize('find.autoFindInSelection', "Controls the condition for turning on Find in Selection automatically.")
            },
            'editor.find.globalFindClipboard': {
                type: 'boolean',
                default: defaults.globalFindClipboard,
                description: localize('find.globalFindClipboard', "Controls whether the Find Widget should read or modify the shared find clipboard on macOS."),
                included: isMacintosh
            },
            'editor.find.addExtraSpaceOnTop': {
                type: 'boolean',
                default: defaults.addExtraSpaceOnTop,
                description: localize('find.addExtraSpaceOnTop', "Controls whether the Find Widget should add extra lines on top of the editor. When true, you can scroll beyond the first line when the Find Widget is visible.")
            },
            'editor.find.loop': {
                type: 'boolean',
                default: defaults.loop,
                description: localize('find.loop', "Controls whether the search automatically restarts from the beginning (or the end) when no further matches can be found.")
            },
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            cursorMoveOnType: editorOptions_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: editorOptions_boolean(input.globalFindClipboard, this.defaultValue.globalFindClipboard),
            addExtraSpaceOnTop: editorOptions_boolean(input.addExtraSpaceOnTop, this.defaultValue.addExtraSpaceOnTop),
            loop: editorOptions_boolean(input.loop, this.defaultValue.loop),
        };
    }
}
//#endregion
//#region fontLigatures
/**
 * @internal
 */
class EditorFontLigatures extends BaseEditorOption {
    constructor() {
        super(47 /* EditorOption.fontLigatures */, 'fontLigatures', EditorFontLigatures.OFF, {
            anyOf: [
                {
                    type: 'boolean',
                    description: localize('fontLigatures', "Enables/Disables font ligatures ('calt' and 'liga' font features). Change this to a string for fine-grained control of the 'font-feature-settings' CSS property."),
                },
                {
                    type: 'string',
                    description: localize('fontFeatureSettings', "Explicit 'font-feature-settings' CSS property. A boolean can be passed instead if one only needs to turn on/off ligatures.")
                }
            ],
            description: localize('fontLigaturesGeneral', "Configures font ligatures or font features. Can be either a boolean to enable/disable ligatures or a string for the value of the CSS 'font-feature-settings' property."),
            default: false
        });
    }
    validate(input) {
        if (typeof input === 'undefined') {
            return this.defaultValue;
        }
        if (typeof input === 'string') {
            if (input === 'false') {
                return EditorFontLigatures.OFF;
            }
            if (input === 'true') {
                return EditorFontLigatures.ON;
            }
            return input;
        }
        if (Boolean(input)) {
            return EditorFontLigatures.ON;
        }
        return EditorFontLigatures.OFF;
    }
}
EditorFontLigatures.OFF = '"liga" off, "calt" off';
EditorFontLigatures.ON = '"liga" on, "calt" on';
//#endregion
//#region fontInfo
class EditorFontInfo extends ComputedEditorOption {
    constructor() {
        super(46 /* EditorOption.fontInfo */);
    }
    compute(env, options, _) {
        return env.fontInfo;
    }
}
//#endregion
//#region fontSize
class EditorFontSize extends SimpleEditorOption {
    constructor() {
        super(48 /* EditorOption.fontSize */, 'fontSize', EDITOR_FONT_DEFAULTS.fontSize, {
            type: 'number',
            minimum: 6,
            maximum: 100,
            default: EDITOR_FONT_DEFAULTS.fontSize,
            description: localize('fontSize', "Controls the font size in pixels.")
        });
    }
    validate(input) {
        const r = EditorFloatOption.float(input, this.defaultValue);
        if (r === 0) {
            return EDITOR_FONT_DEFAULTS.fontSize;
        }
        return EditorFloatOption.clamp(r, 6, 100);
    }
    compute(env, options, value) {
        // The final fontSize respects the editor zoom level.
        // So take the result from env.fontInfo
        return env.fontInfo.fontSize;
    }
}
//#endregion
//#region fontWeight
class EditorFontWeight extends BaseEditorOption {
    constructor() {
        super(49 /* EditorOption.fontWeight */, 'fontWeight', EDITOR_FONT_DEFAULTS.fontWeight, {
            anyOf: [
                {
                    type: 'number',
                    minimum: EditorFontWeight.MINIMUM_VALUE,
                    maximum: EditorFontWeight.MAXIMUM_VALUE,
                    errorMessage: localize('fontWeightErrorMessage', "Only \"normal\" and \"bold\" keywords or numbers between 1 and 1000 are allowed.")
                },
                {
                    type: 'string',
                    pattern: '^(normal|bold|1000|[1-9][0-9]{0,2})$'
                },
                {
                    enum: EditorFontWeight.SUGGESTION_VALUES
                }
            ],
            default: EDITOR_FONT_DEFAULTS.fontWeight,
            description: localize('fontWeight', "Controls the font weight. Accepts \"normal\" and \"bold\" keywords or numbers between 1 and 1000.")
        });
    }
    validate(input) {
        if (input === 'normal' || input === 'bold') {
            return input;
        }
        return String(EditorIntOption.clampedInt(input, EDITOR_FONT_DEFAULTS.fontWeight, EditorFontWeight.MINIMUM_VALUE, EditorFontWeight.MAXIMUM_VALUE));
    }
}
EditorFontWeight.SUGGESTION_VALUES = ['normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900'];
EditorFontWeight.MINIMUM_VALUE = 1;
EditorFontWeight.MAXIMUM_VALUE = 1000;
class EditorGoToLocation extends BaseEditorOption {
    constructor() {
        const defaults = {
            multiple: 'peek',
            multipleDefinitions: 'peek',
            multipleTypeDefinitions: 'peek',
            multipleDeclarations: 'peek',
            multipleImplementations: 'peek',
            multipleReferences: 'peek',
            alternativeDefinitionCommand: 'editor.action.goToReferences',
            alternativeTypeDefinitionCommand: 'editor.action.goToReferences',
            alternativeDeclarationCommand: 'editor.action.goToReferences',
            alternativeImplementationCommand: '',
            alternativeReferenceCommand: '',
        };
        const jsonSubset = {
            type: 'string',
            enum: ['peek', 'gotoAndPeek', 'goto'],
            default: defaults.multiple,
            enumDescriptions: [
                localize('editor.gotoLocation.multiple.peek', 'Show peek view of the results (default)'),
                localize('editor.gotoLocation.multiple.gotoAndPeek', 'Go to the primary result and show a peek view'),
                localize('editor.gotoLocation.multiple.goto', 'Go to the primary result and enable peek-less navigation to others')
            ]
        };
        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(53 /* EditorOption.gotoLocation */, 'gotoLocation', defaults, {
            'editor.gotoLocation.multiple': {
                deprecationMessage: localize('editor.gotoLocation.multiple.deprecated', "This setting is deprecated, please use separate settings like 'editor.editor.gotoLocation.multipleDefinitions' or 'editor.editor.gotoLocation.multipleImplementations' instead."),
            },
            'editor.gotoLocation.multipleDefinitions': Object.assign({ description: localize('editor.editor.gotoLocation.multipleDefinitions', "Controls the behavior the 'Go to Definition'-command when multiple target locations exist.") }, jsonSubset),
            'editor.gotoLocation.multipleTypeDefinitions': Object.assign({ description: localize('editor.editor.gotoLocation.multipleTypeDefinitions', "Controls the behavior the 'Go to Type Definition'-command when multiple target locations exist.") }, jsonSubset),
            'editor.gotoLocation.multipleDeclarations': Object.assign({ description: localize('editor.editor.gotoLocation.multipleDeclarations', "Controls the behavior the 'Go to Declaration'-command when multiple target locations exist.") }, jsonSubset),
            'editor.gotoLocation.multipleImplementations': Object.assign({ description: localize('editor.editor.gotoLocation.multipleImplemenattions', "Controls the behavior the 'Go to Implementations'-command when multiple target locations exist.") }, jsonSubset),
            'editor.gotoLocation.multipleReferences': Object.assign({ description: localize('editor.editor.gotoLocation.multipleReferences', "Controls the behavior the 'Go to References'-command when multiple target locations exist.") }, jsonSubset),
            'editor.gotoLocation.alternativeDefinitionCommand': {
                type: 'string',
                default: defaults.alternativeDefinitionCommand,
                enum: alternativeCommandOptions,
                description: localize('alternativeDefinitionCommand', "Alternative command id that is being executed when the result of 'Go to Definition' is the current location.")
            },
            'editor.gotoLocation.alternativeTypeDefinitionCommand': {
                type: 'string',
                default: defaults.alternativeTypeDefinitionCommand,
                enum: alternativeCommandOptions,
                description: localize('alternativeTypeDefinitionCommand', "Alternative command id that is being executed when the result of 'Go to Type Definition' is the current location.")
            },
            'editor.gotoLocation.alternativeDeclarationCommand': {
                type: 'string',
                default: defaults.alternativeDeclarationCommand,
                enum: alternativeCommandOptions,
                description: localize('alternativeDeclarationCommand', "Alternative command id that is being executed when the result of 'Go to Declaration' is the current location.")
            },
            'editor.gotoLocation.alternativeImplementationCommand': {
                type: 'string',
                default: defaults.alternativeImplementationCommand,
                enum: alternativeCommandOptions,
                description: localize('alternativeImplementationCommand', "Alternative command id that is being executed when the result of 'Go to Implementation' is the current location.")
            },
            'editor.gotoLocation.alternativeReferenceCommand': {
                type: 'string',
                default: defaults.alternativeReferenceCommand,
                enum: alternativeCommandOptions,
                description: localize('alternativeReferenceCommand', "Alternative command id that is being executed when the result of 'Go to Reference' is the current location.")
            },
        });
    }
    validate(_input) {
        var _a, _b, _c, _d, _e;
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            multiple: stringSet(input.multiple, this.defaultValue.multiple, ['peek', 'gotoAndPeek', 'goto']),
            multipleDefinitions: (_a = input.multipleDefinitions) !== null && _a !== void 0 ? _a : stringSet(input.multipleDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']),
            multipleTypeDefinitions: (_b = input.multipleTypeDefinitions) !== null && _b !== void 0 ? _b : stringSet(input.multipleTypeDefinitions, 'peek', ['peek', 'gotoAndPeek', 'goto']),
            multipleDeclarations: (_c = input.multipleDeclarations) !== null && _c !== void 0 ? _c : stringSet(input.multipleDeclarations, 'peek', ['peek', 'gotoAndPeek', 'goto']),
            multipleImplementations: (_d = input.multipleImplementations) !== null && _d !== void 0 ? _d : stringSet(input.multipleImplementations, 'peek', ['peek', 'gotoAndPeek', 'goto']),
            multipleReferences: (_e = input.multipleReferences) !== null && _e !== void 0 ? _e : stringSet(input.multipleReferences, '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),
        };
    }
}
class EditorHover extends BaseEditorOption {
    constructor() {
        const defaults = {
            enabled: true,
            delay: 300,
            sticky: true,
            above: true,
        };
        super(55 /* EditorOption.hover */, 'hover', defaults, {
            'editor.hover.enabled': {
                type: 'boolean',
                default: defaults.enabled,
                description: localize('hover.enabled', "Controls whether the hover is shown.")
            },
            'editor.hover.delay': {
                type: 'number',
                default: defaults.delay,
                minimum: 0,
                maximum: 10000,
                description: localize('hover.delay', "Controls the delay in milliseconds after which the hover is shown.")
            },
            'editor.hover.sticky': {
                type: 'boolean',
                default: defaults.sticky,
                description: localize('hover.sticky', "Controls whether the hover should remain visible when mouse is moved over it.")
            },
            'editor.hover.above': {
                type: 'boolean',
                default: defaults.above,
                description: localize('hover.above', "Prefer showing hovers above the line, if there's space.")
            },
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            enabled: editorOptions_boolean(input.enabled, this.defaultValue.enabled),
            delay: EditorIntOption.clampedInt(input.delay, this.defaultValue.delay, 0, 10000),
            sticky: editorOptions_boolean(input.sticky, this.defaultValue.sticky),
            above: editorOptions_boolean(input.above, this.defaultValue.above),
        };
    }
}
/**
 * @internal
 */
class EditorLayoutInfoComputer extends ComputedEditorOption {
    constructor() {
        super(133 /* EditorOption.layoutInfo */);
    }
    compute(env, options, _) {
        return EditorLayoutInfoComputer.computeLayout(options, {
            memory: env.memory,
            outerWidth: env.outerWidth,
            outerHeight: env.outerHeight,
            isDominatedByLongLines: env.isDominatedByLongLines,
            lineHeight: env.fontInfo.lineHeight,
            viewLineCount: env.viewLineCount,
            lineNumbersDigitCount: env.lineNumbersDigitCount,
            typicalHalfwidthCharacterWidth: env.fontInfo.typicalHalfwidthCharacterWidth,
            maxDigitWidth: env.fontInfo.maxDigitWidth,
            pixelRatio: env.pixelRatio
        });
    }
    static computeContainedMinimapLineCount(input) {
        const typicalViewportLineCount = input.height / input.lineHeight;
        const extraLinesBeyondLastLine = input.scrollBeyondLastLine ? (typicalViewportLineCount - 1) : 0;
        const desiredRatio = (input.viewLineCount + extraLinesBeyondLastLine) / (input.pixelRatio * input.height);
        const minimapLineCount = Math.floor(input.viewLineCount / desiredRatio);
        return { typicalViewportLineCount, extraLinesBeyondLastLine, desiredRatio, minimapLineCount };
    }
    static _computeMinimapLayout(input, memory) {
        const outerWidth = input.outerWidth;
        const outerHeight = input.outerHeight;
        const pixelRatio = input.pixelRatio;
        if (!input.minimap.enabled) {
            return {
                renderMinimap: 0 /* RenderMinimap.None */,
                minimapLeft: 0,
                minimapWidth: 0,
                minimapHeightIsEditorHeight: false,
                minimapIsSampling: false,
                minimapScale: 1,
                minimapLineHeight: 1,
                minimapCanvasInnerWidth: 0,
                minimapCanvasInnerHeight: Math.floor(pixelRatio * outerHeight),
                minimapCanvasOuterWidth: 0,
                minimapCanvasOuterHeight: outerHeight,
            };
        }
        // Can use memory if only the `viewLineCount` and `remainingWidth` have changed
        const stableMinimapLayoutInput = memory.stableMinimapLayoutInput;
        const couldUseMemory = (stableMinimapLayoutInput
            // && input.outerWidth === lastMinimapLayoutInput.outerWidth !!! INTENTIONAL OMITTED
            && input.outerHeight === stableMinimapLayoutInput.outerHeight
            && input.lineHeight === stableMinimapLayoutInput.lineHeight
            && input.typicalHalfwidthCharacterWidth === stableMinimapLayoutInput.typicalHalfwidthCharacterWidth
            && input.pixelRatio === stableMinimapLayoutInput.pixelRatio
            && input.scrollBeyondLastLine === stableMinimapLayoutInput.scrollBeyondLastLine
            && 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.viewLineCount === lastMinimapLayoutInput.viewLineCount !!! INTENTIONAL OMITTED
            // && input.remainingWidth === lastMinimapLayoutInput.remainingWidth !!! INTENTIONAL OMITTED
            && 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, extraLinesBeyondLastLine, desiredRatio, minimapLineCount } = EditorLayoutInfoComputer.computeContainedMinimapLineCount({
                viewLineCount: viewLineCount,
                scrollBeyondLastLine: scrollBeyondLastLine,
                height: outerHeight,
                lineHeight: lineHeight,
                pixelRatio: pixelRatio
            });
            // ratio is intentionally not part of the layout to avoid the layout changing all the time
            // when doing sampling
            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((viewLineCount + extraLinesBeyondLastLine) * minimapLineHeight);
                    if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) {
                        // There is a loop when using `fit` and viewport wrapping:
                        // - view line count impacts minimap layout
                        // - minimap layout impacts viewport width
                        // - viewport width impacts view line count
                        // To break the loop, once we go to a smaller minimap scale, we try to stick with it.
                        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) {
                        // There is a loop when using `fill` and viewport wrapping:
                        // - view line count impacts minimap layout
                        // - minimap layout impacts viewport width
                        // - viewport width impacts view line count
                        // To break the loop, once we go to a smaller minimap scale, we try to stick with it.
                        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, viewLineCount + extraLinesBeyondLastLine)) * minimapLineHeight);
                    if (isViewportWrapping) {
                        // remember for next time
                        memory.stableMinimapLayoutInput = input;
                        memory.stableFitRemainingWidth = remainingWidth;
                        memory.stableFitMaxMinimapScale = minimapScale;
                    }
                    else {
                        memory.stableMinimapLayoutInput = null;
                        memory.stableFitRemainingWidth = 0;
                    }
                }
            }
        }
        // Given:
        // (leaving 2px for the cursor to have space after the last character)
        // viewportColumn = (contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth
        // minimapWidth = viewportColumn * minimapCharWidth
        // contentWidth = remainingWidth - minimapWidth
        // What are good values for contentWidth and minimapWidth ?
        // minimapWidth = ((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth) * minimapCharWidth
        // typicalHalfwidthCharacterWidth * minimapWidth = (contentWidth - verticalScrollbarWidth - 2) * minimapCharWidth
        // typicalHalfwidthCharacterWidth * minimapWidth = (remainingWidth - minimapWidth - verticalScrollbarWidth - 2) * minimapCharWidth
        // (typicalHalfwidthCharacterWidth + minimapCharWidth) * minimapWidth = (remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth
        // minimapWidth = ((remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth) / (typicalHalfwidthCharacterWidth + minimapCharWidth)
        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 /* RenderMinimap.Text */ : 2 /* RenderMinimap.Blocks */);
        const minimapLeft = (minimapSide === 'left' ? 0 : (outerWidth - minimapWidth - verticalScrollbarWidth));
        return {
            renderMinimap,
            minimapLeft,
            minimapWidth,
            minimapHeightIsEditorHeight,
            minimapIsSampling,
            minimapScale,
            minimapLineHeight,
            minimapCanvasInnerWidth,
            minimapCanvasInnerHeight,
            minimapCanvasOuterWidth,
            minimapCanvasOuterHeight,
        };
    }
    static computeLayout(options, env) {
        const outerWidth = env.outerWidth | 0;
        const outerHeight = env.outerHeight | 0;
        const lineHeight = env.lineHeight | 0;
        const lineNumbersDigitCount = env.lineNumbersDigitCount | 0;
        const typicalHalfwidthCharacterWidth = env.typicalHalfwidthCharacterWidth;
        const maxDigitWidth = env.maxDigitWidth;
        const pixelRatio = env.pixelRatio;
        const viewLineCount = env.viewLineCount;
        const wordWrapOverride2 = options.get(125 /* EditorOption.wordWrapOverride2 */);
        const wordWrapOverride1 = (wordWrapOverride2 === 'inherit' ? options.get(124 /* EditorOption.wordWrapOverride1 */) : wordWrapOverride2);
        const wordWrap = (wordWrapOverride1 === 'inherit' ? options.get(120 /* EditorOption.wordWrap */) : wordWrapOverride1);
        const wordWrapColumn = options.get(123 /* EditorOption.wordWrapColumn */);
        const accessibilitySupport = options.get(2 /* EditorOption.accessibilitySupport */);
        const isDominatedByLongLines = env.isDominatedByLongLines;
        const showGlyphMargin = options.get(52 /* EditorOption.glyphMargin */);
        const showLineNumbers = (options.get(62 /* EditorOption.lineNumbers */).renderType !== 0 /* RenderLineNumbersType.Off */);
        const lineNumbersMinChars = options.get(63 /* EditorOption.lineNumbersMinChars */);
        const scrollBeyondLastLine = options.get(96 /* EditorOption.scrollBeyondLastLine */);
        const minimap = options.get(67 /* EditorOption.minimap */);
        const scrollbar = options.get(94 /* EditorOption.scrollbar */);
        const verticalScrollbarWidth = scrollbar.verticalScrollbarSize;
        const verticalScrollbarHasArrows = scrollbar.verticalHasArrows;
        const scrollbarArrowSize = scrollbar.arrowSize;
        const horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize;
        const rawLineDecorationsWidth = options.get(60 /* EditorOption.lineDecorationsWidth */);
        const folding = options.get(39 /* EditorOption.folding */);
        const showFoldingDecoration = options.get(101 /* EditorOption.showFoldingControls */) !== 'never';
        let lineDecorationsWidth;
        if (typeof rawLineDecorationsWidth === 'string' && /^\d+(\.\d+)?ch$/.test(rawLineDecorationsWidth)) {
            const multiple = parseFloat(rawLineDecorationsWidth.substr(0, rawLineDecorationsWidth.length - 2));
            lineDecorationsWidth = EditorIntOption.clampedInt(multiple * typicalHalfwidthCharacterWidth, 0, 0, 1000);
        }
        else {
            lineDecorationsWidth = EditorIntOption.clampedInt(rawLineDecorationsWidth, 0, 0, 1000);
        }
        if (folding && showFoldingDecoration) {
            lineDecorationsWidth += 16;
        }
        let lineNumbersWidth = 0;
        if (showLineNumbers) {
            const digitCount = Math.max(lineNumbersDigitCount, lineNumbersMinChars);
            lineNumbersWidth = Math.round(digitCount * maxDigitWidth);
        }
        let glyphMarginWidth = 0;
        if (showGlyphMargin) {
            glyphMarginWidth = lineHeight;
        }
        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 (accessibilitySupport !== 2 /* AccessibilitySupport.Enabled */) {
            // See https://github.com/microsoft/vscode/issues/27766
            // Never enable wrapping when a screen reader is attached
            // because arrow down etc. will not move the cursor in the way
            // a screen reader expects.
            if (wordWrapOverride1 === 'inherit' && isDominatedByLongLines) {
                // Force viewport width wrapping if model is dominated by long lines
                isWordWrapMinified = true;
                isViewportWrapping = true;
            }
            else if (wordWrap === 'on' || wordWrap === 'bounded') {
                isViewportWrapping = true;
            }
            else if (wordWrap === 'wordWrapColumn') {
                wrappingColumn = wordWrapColumn;
            }
        }
        const minimapLayout = EditorLayoutInfoComputer._computeMinimapLayout({
            outerWidth: outerWidth,
            outerHeight: outerHeight,
            lineHeight: lineHeight,
            typicalHalfwidthCharacterWidth: typicalHalfwidthCharacterWidth,
            pixelRatio: pixelRatio,
            scrollBeyondLastLine: scrollBeyondLastLine,
            minimap: minimap,
            verticalScrollbarWidth: verticalScrollbarWidth,
            viewLineCount: viewLineCount,
            remainingWidth: remainingWidth,
            isViewportWrapping: isViewportWrapping,
        }, env.memory || new ComputeOptionsMemory());
        if (minimapLayout.renderMinimap !== 0 /* RenderMinimap.None */ && minimapLayout.minimapLeft === 0) {
            // the minimap is rendered to the left, so move everything to the right
            glyphMarginLeft += minimapLayout.minimapWidth;
            lineNumbersLeft += minimapLayout.minimapWidth;
            decorationsLeft += minimapLayout.minimapWidth;
            contentLeft += minimapLayout.minimapWidth;
        }
        const contentWidth = remainingWidth - minimapLayout.minimapWidth;
        // (leaving 2px for the cursor to have space after the last character)
        const viewportColumn = Math.max(1, Math.floor((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth));
        const verticalArrowSize = (verticalScrollbarHasArrows ? scrollbarArrowSize : 0);
        if (isViewportWrapping) {
            // compute the actual wrappingColumn
            wrappingColumn = Math.max(1, viewportColumn);
            if (wordWrap === 'bounded') {
                wrappingColumn = Math.min(wrappingColumn, wordWrapColumn);
            }
        }
        return {
            width: outerWidth,
            height: outerHeight,
            glyphMarginLeft: glyphMarginLeft,
            glyphMarginWidth: glyphMarginWidth,
            lineNumbersLeft: lineNumbersLeft,
            lineNumbersWidth: lineNumbersWidth,
            decorationsLeft: decorationsLeft,
            decorationsWidth: lineDecorationsWidth,
            contentLeft: contentLeft,
            contentWidth: contentWidth,
            minimap: minimapLayout,
            viewportColumn: viewportColumn,
            isWordWrapMinified: isWordWrapMinified,
            isViewportWrapping: isViewportWrapping,
            wrappingColumn: wrappingColumn,
            verticalScrollbarWidth: verticalScrollbarWidth,
            horizontalScrollbarHeight: horizontalScrollbarHeight,
            overviewRuler: {
                top: verticalArrowSize,
                width: verticalScrollbarWidth,
                height: (outerHeight - 2 * verticalArrowSize),
                right: 0
            }
        };
    }
}
class EditorLightbulb extends BaseEditorOption {
    constructor() {
        const defaults = { enabled: true };
        super(59 /* EditorOption.lightbulb */, 'lightbulb', defaults, {
            'editor.lightbulb.enabled': {
                type: 'boolean',
                default: defaults.enabled,
                description: localize('codeActions', "Enables the code action lightbulb in the editor.")
            },
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            enabled: editorOptions_boolean(input.enabled, this.defaultValue.enabled)
        };
    }
}
class EditorExperimental extends BaseEditorOption {
    constructor() {
        const defaults = { stickyScroll: { enabled: false } };
        super(34 /* EditorOption.experimental */, 'experimental', defaults, {
            'editor.experimental.stickyScroll.enabled': {
                type: 'boolean',
                default: defaults.stickyScroll.enabled,
                description: localize('editor.experimental.stickyScroll', "Shows the nested current scopes during the scroll at the top of the editor.")
            },
        });
    }
    validate(_input) {
        var _a;
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            stickyScroll: {
                enabled: editorOptions_boolean((_a = input.stickyScroll) === null || _a === void 0 ? void 0 : _a.enabled, this.defaultValue.stickyScroll.enabled)
            }
        };
    }
}
class EditorInlayHints extends BaseEditorOption {
    constructor() {
        const defaults = { enabled: 'on', fontSize: 0, fontFamily: '', padding: false };
        super(129 /* EditorOption.inlayHints */, 'inlayHints', defaults, {
            'editor.inlayHints.enabled': {
                type: 'string',
                default: defaults.enabled,
                description: localize('inlayHints.enable', "Enables the inlay hints in the editor."),
                enum: ['on', 'onUnlessPressed', 'offUnlessPressed', 'off'],
                markdownEnumDescriptions: [
                    localize('editor.inlayHints.on', "Inlay hints are enabled"),
                    localize('editor.inlayHints.onUnlessPressed', "Inlay hints are showing by default and hide when holding `Ctrl+Alt`"),
                    localize('editor.inlayHints.offUnlessPressed', "Inlay hints are hidden by default and show when holding `Ctrl+Alt`"),
                    localize('editor.inlayHints.off', "Inlay hints are disabled"),
                ],
            },
            'editor.inlayHints.fontSize': {
                type: 'number',
                default: defaults.fontSize,
                markdownDescription: localize('inlayHints.fontSize', "Controls font size of inlay hints in the editor. As default the {0} is used when the configured value is less than {1} or greater than the editor font size.", '`#editor.fontSize#`', '`5`')
            },
            'editor.inlayHints.fontFamily': {
                type: 'string',
                default: defaults.fontFamily,
                markdownDescription: localize('inlayHints.fontFamily', "Controls font family of inlay hints in the editor. When set to empty, the {0} is used.", '`#editor.fontFamily#`')
            },
            'editor.inlayHints.padding': {
                type: 'boolean',
                default: defaults.padding,
                description: localize('inlayHints.padding', "Enables the padding around the inlay hints in the editor.")
            }
        });
    }
    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: editorOptions_boolean(input.padding, this.defaultValue.padding)
        };
    }
}
//#endregion
//#region lineHeight
class EditorLineHeight extends EditorFloatOption {
    constructor() {
        super(61 /* EditorOption.lineHeight */, 'lineHeight', EDITOR_FONT_DEFAULTS.lineHeight, x => EditorFloatOption.clamp(x, 0, 150), { markdownDescription: localize('lineHeight', "Controls the line height. \n - Use 0 to automatically compute the line height from the font size.\n - Values between 0 and 8 will be used as a multiplier with the font size.\n - Values greater than or equal to 8 will be used as effective values.") });
    }
    compute(env, options, value) {
        // The lineHeight is computed from the fontSize if it is 0.
        // Moreover, the final lineHeight respects the editor zoom level.
        // So take the result from env.fontInfo
        return env.fontInfo.lineHeight;
    }
}
class EditorMinimap extends BaseEditorOption {
    constructor() {
        const defaults = {
            enabled: true,
            size: 'proportional',
            side: 'right',
            showSlider: 'mouseover',
            autohide: false,
            renderCharacters: true,
            maxColumn: 120,
            scale: 1,
        };
        super(67 /* EditorOption.minimap */, 'minimap', defaults, {
            'editor.minimap.enabled': {
                type: 'boolean',
                default: defaults.enabled,
                description: localize('minimap.enabled', "Controls whether the minimap is shown.")
            },
            'editor.minimap.autohide': {
                type: 'boolean',
                default: defaults.autohide,
                description: localize('minimap.autohide', "Controls whether the minimap is hidden automatically.")
            },
            'editor.minimap.size': {
                type: 'string',
                enum: ['proportional', 'fill', 'fit'],
                enumDescriptions: [
                    localize('minimap.size.proportional', "The minimap has the same size as the editor contents (and might scroll)."),
                    localize('minimap.size.fill', "The minimap will stretch or shrink as necessary to fill the height of the editor (no scrolling)."),
                    localize('minimap.size.fit', "The minimap will shrink as necessary to never be larger than the editor (no scrolling)."),
                ],
                default: defaults.size,
                description: localize('minimap.size', "Controls the size of the minimap.")
            },
            'editor.minimap.side': {
                type: 'string',
                enum: ['left', 'right'],
                default: defaults.side,
                description: localize('minimap.side', "Controls the side where to render the minimap.")
            },
            'editor.minimap.showSlider': {
                type: 'string',
                enum: ['always', 'mouseover'],
                default: defaults.showSlider,
                description: localize('minimap.showSlider', "Controls when the minimap slider is shown.")
            },
            'editor.minimap.scale': {
                type: 'number',
                default: defaults.scale,
                minimum: 1,
                maximum: 3,
                enum: [1, 2, 3],
                description: localize('minimap.scale', "Scale of content drawn in the minimap: 1, 2 or 3.")
            },
            'editor.minimap.renderCharacters': {
                type: 'boolean',
                default: defaults.renderCharacters,
                description: localize('minimap.renderCharacters', "Render the actual characters on a line as opposed to color blocks.")
            },
            'editor.minimap.maxColumn': {
                type: 'number',
                default: defaults.maxColumn,
                description: localize('minimap.maxColumn', "Limit the width of the minimap to render at most a certain number of columns.")
            }
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            enabled: editorOptions_boolean(input.enabled, this.defaultValue.enabled),
            autohide: editorOptions_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: editorOptions_boolean(input.renderCharacters, this.defaultValue.renderCharacters),
            scale: EditorIntOption.clampedInt(input.scale, 1, 1, 3),
            maxColumn: EditorIntOption.clampedInt(input.maxColumn, this.defaultValue.maxColumn, 1, 10000),
        };
    }
}
//#endregion
//#region multiCursorModifier
function _multiCursorModifierFromString(multiCursorModifier) {
    if (multiCursorModifier === 'ctrlCmd') {
        return (isMacintosh ? 'metaKey' : 'ctrlKey');
    }
    return 'altKey';
}
class EditorPadding extends BaseEditorOption {
    constructor() {
        super(77 /* EditorOption.padding */, 'padding', { top: 0, bottom: 0 }, {
            'editor.padding.top': {
                type: 'number',
                default: 0,
                minimum: 0,
                maximum: 1000,
                description: localize('padding.top', "Controls the amount of space between the top edge of the editor and the first line.")
            },
            'editor.padding.bottom': {
                type: 'number',
                default: 0,
                minimum: 0,
                maximum: 1000,
                description: localize('padding.bottom', "Controls the amount of space between the bottom edge of the editor and the last line.")
            }
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            top: EditorIntOption.clampedInt(input.top, 0, 0, 1000),
            bottom: EditorIntOption.clampedInt(input.bottom, 0, 0, 1000)
        };
    }
}
class EditorParameterHints extends BaseEditorOption {
    constructor() {
        const defaults = {
            enabled: true,
            cycle: false
        };
        super(78 /* EditorOption.parameterHints */, 'parameterHints', defaults, {
            'editor.parameterHints.enabled': {
                type: 'boolean',
                default: defaults.enabled,
                description: localize('parameterHints.enabled', "Enables a pop-up that shows parameter documentation and type information as you type.")
            },
            'editor.parameterHints.cycle': {
                type: 'boolean',
                default: defaults.cycle,
                description: localize('parameterHints.cycle', "Controls whether the parameter hints menu cycles or closes when reaching the end of the list.")
            },
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            enabled: editorOptions_boolean(input.enabled, this.defaultValue.enabled),
            cycle: editorOptions_boolean(input.cycle, this.defaultValue.cycle)
        };
    }
}
//#endregion
//#region pixelRatio
class EditorPixelRatio extends ComputedEditorOption {
    constructor() {
        super(131 /* EditorOption.pixelRatio */);
    }
    compute(env, options, _) {
        return env.pixelRatio;
    }
}
class EditorQuickSuggestions extends BaseEditorOption {
    constructor() {
        const defaults = {
            other: 'on',
            comments: 'off',
            strings: 'off'
        };
        const types = [
            { type: 'boolean' },
            {
                type: 'string',
                enum: ['on', 'inline', 'off'],
                enumDescriptions: [localize('on', "Quick suggestions show inside the suggest widget"), localize('inline', "Quick suggestions show as ghost text"), localize('off', "Quick suggestions are disabled")]
            }
        ];
        super(81 /* EditorOption.quickSuggestions */, 'quickSuggestions', defaults, {
            type: 'object',
            additionalProperties: false,
            properties: {
                strings: {
                    anyOf: types,
                    default: defaults.strings,
                    description: localize('quickSuggestions.strings', "Enable quick suggestions inside strings.")
                },
                comments: {
                    anyOf: types,
                    default: defaults.comments,
                    description: localize('quickSuggestions.comments', "Enable quick suggestions inside comments.")
                },
                other: {
                    anyOf: types,
                    default: defaults.other,
                    description: localize('quickSuggestions.other', "Enable quick suggestions outside of strings and comments.")
                },
            },
            default: defaults,
            markdownDescription: localize('quickSuggestions', "Controls whether suggestions should automatically show up while typing. This can be controlled for typing in comments, strings, and other code. Quick suggestion can be configured to show as ghost text or with the suggest widget. Also be aware of the '{0}'-setting which controls if suggestions are triggered by special characters.", `#editor.suggestOnTriggerCharacters#`)
        });
        this.defaultValue = defaults;
    }
    validate(input) {
        if (typeof input === 'boolean') {
            // boolean -> all on/off
            const value = input ? 'on' : 'off';
            return { comments: value, strings: value, other: value };
        }
        if (!input || typeof input !== 'object') {
            // invalid 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
        };
    }
}
class EditorRenderLineNumbersOption extends BaseEditorOption {
    constructor() {
        super(62 /* EditorOption.lineNumbers */, 'lineNumbers', { renderType: 1 /* RenderLineNumbersType.On */, renderFn: null }, {
            type: 'string',
            enum: ['off', 'on', 'relative', 'interval'],
            enumDescriptions: [
                localize('lineNumbers.off', "Line numbers are not rendered."),
                localize('lineNumbers.on', "Line numbers are rendered as absolute number."),
                localize('lineNumbers.relative', "Line numbers are rendered as distance in lines to cursor position."),
                localize('lineNumbers.interval', "Line numbers are rendered every 10 lines.")
            ],
            default: 'on',
            description: localize('lineNumbers', "Controls the display of line numbers.")
        });
    }
    validate(lineNumbers) {
        let renderType = this.defaultValue.renderType;
        let renderFn = this.defaultValue.renderFn;
        if (typeof lineNumbers !== 'undefined') {
            if (typeof lineNumbers === 'function') {
                renderType = 4 /* RenderLineNumbersType.Custom */;
                renderFn = lineNumbers;
            }
            else if (lineNumbers === 'interval') {
                renderType = 3 /* RenderLineNumbersType.Interval */;
            }
            else if (lineNumbers === 'relative') {
                renderType = 2 /* RenderLineNumbersType.Relative */;
            }
            else if (lineNumbers === 'on') {
                renderType = 1 /* RenderLineNumbersType.On */;
            }
            else {
                renderType = 0 /* RenderLineNumbersType.Off */;
            }
        }
        return {
            renderType,
            renderFn
        };
    }
}
//#endregion
//#region renderValidationDecorations
/**
 * @internal
 */
function filterValidationDecorations(options) {
    const renderValidationDecorations = options.get(89 /* EditorOption.renderValidationDecorations */);
    if (renderValidationDecorations === 'editable') {
        return options.get(83 /* EditorOption.readOnly */);
    }
    return renderValidationDecorations === 'on' ? false : true;
}
class EditorRulers extends BaseEditorOption {
    constructor() {
        const defaults = [];
        const columnSchema = { type: 'number', description: localize('rulers.size', "Number of monospace characters at which this editor ruler will render.") };
        super(93 /* EditorOption.rulers */, 'rulers', defaults, {
            type: 'array',
            items: {
                anyOf: [
                    columnSchema,
                    {
                        type: [
                            'object'
                        ],
                        properties: {
                            column: columnSchema,
                            color: {
                                type: 'string',
                                description: localize('rulers.color', "Color of this editor ruler."),
                                format: 'color-hex'
                            }
                        }
                    }
                ]
            },
            default: defaults,
            description: localize('rulers', "Render vertical rulers after a certain number of monospace characters. Use multiple values for multiple rulers. No rulers are drawn if array is empty.")
        });
    }
    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, 10000),
                        color: null
                    });
                }
                else if (_element && typeof _element === 'object') {
                    const element = _element;
                    rulers.push({
                        column: EditorIntOption.clampedInt(element.column, 0, 0, 10000),
                        color: element.color
                    });
                }
            }
            rulers.sort((a, b) => a.column - b.column);
            return rulers;
        }
        return this.defaultValue;
    }
}
function _scrollbarVisibilityFromString(visibility, defaultValue) {
    if (typeof visibility !== 'string') {
        return defaultValue;
    }
    switch (visibility) {
        case 'hidden': return 2 /* ScrollbarVisibility.Hidden */;
        case 'visible': return 3 /* ScrollbarVisibility.Visible */;
        default: return 1 /* ScrollbarVisibility.Auto */;
    }
}
class EditorScrollbar extends BaseEditorOption {
    constructor() {
        const defaults = {
            vertical: 1 /* ScrollbarVisibility.Auto */,
            horizontal: 1 /* ScrollbarVisibility.Auto */,
            arrowSize: 11,
            useShadows: true,
            verticalHasArrows: false,
            horizontalHasArrows: false,
            horizontalScrollbarSize: 12,
            horizontalSliderSize: 12,
            verticalScrollbarSize: 14,
            verticalSliderSize: 14,
            handleMouseWheel: true,
            alwaysConsumeMouseWheel: true,
            scrollByPage: false
        };
        super(94 /* EditorOption.scrollbar */, 'scrollbar', defaults, {
            'editor.scrollbar.vertical': {
                type: 'string',
                enum: ['auto', 'visible', 'hidden'],
                enumDescriptions: [
                    localize('scrollbar.vertical.auto', "The vertical scrollbar will be visible only when necessary."),
                    localize('scrollbar.vertical.visible', "The vertical scrollbar will always be visible."),
                    localize('scrollbar.vertical.fit', "The vertical scrollbar will always be hidden."),
                ],
                default: 'auto',
                description: localize('scrollbar.vertical', "Controls the visibility of the vertical scrollbar.")
            },
            'editor.scrollbar.horizontal': {
                type: 'string',
                enum: ['auto', 'visible', 'hidden'],
                enumDescriptions: [
                    localize('scrollbar.horizontal.auto', "The horizontal scrollbar will be visible only when necessary."),
                    localize('scrollbar.horizontal.visible', "The horizontal scrollbar will always be visible."),
                    localize('scrollbar.horizontal.fit', "The horizontal scrollbar will always be hidden."),
                ],
                default: 'auto',
                description: localize('scrollbar.horizontal', "Controls the visibility of the horizontal scrollbar.")
            },
            'editor.scrollbar.verticalScrollbarSize': {
                type: 'number',
                default: defaults.verticalScrollbarSize,
                description: localize('scrollbar.verticalScrollbarSize', "The width of the vertical scrollbar.")
            },
            'editor.scrollbar.horizontalScrollbarSize': {
                type: 'number',
                default: defaults.horizontalScrollbarSize,
                description: localize('scrollbar.horizontalScrollbarSize', "The height of the horizontal scrollbar.")
            },
            'editor.scrollbar.scrollByPage': {
                type: 'boolean',
                default: defaults.scrollByPage,
                description: localize('scrollbar.scrollByPage', "Controls whether clicks scroll by page or jump to click position.")
            }
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        const horizontalScrollbarSize = EditorIntOption.clampedInt(input.horizontalScrollbarSize, this.defaultValue.horizontalScrollbarSize, 0, 1000);
        const verticalScrollbarSize = EditorIntOption.clampedInt(input.verticalScrollbarSize, this.defaultValue.verticalScrollbarSize, 0, 1000);
        return {
            arrowSize: EditorIntOption.clampedInt(input.arrowSize, this.defaultValue.arrowSize, 0, 1000),
            vertical: _scrollbarVisibilityFromString(input.vertical, this.defaultValue.vertical),
            horizontal: _scrollbarVisibilityFromString(input.horizontal, this.defaultValue.horizontal),
            useShadows: editorOptions_boolean(input.useShadows, this.defaultValue.useShadows),
            verticalHasArrows: editorOptions_boolean(input.verticalHasArrows, this.defaultValue.verticalHasArrows),
            horizontalHasArrows: editorOptions_boolean(input.horizontalHasArrows, this.defaultValue.horizontalHasArrows),
            handleMouseWheel: editorOptions_boolean(input.handleMouseWheel, this.defaultValue.handleMouseWheel),
            alwaysConsumeMouseWheel: editorOptions_boolean(input.alwaysConsumeMouseWheel, this.defaultValue.alwaysConsumeMouseWheel),
            horizontalScrollbarSize: horizontalScrollbarSize,
            horizontalSliderSize: EditorIntOption.clampedInt(input.horizontalSliderSize, horizontalScrollbarSize, 0, 1000),
            verticalScrollbarSize: verticalScrollbarSize,
            verticalSliderSize: EditorIntOption.clampedInt(input.verticalSliderSize, verticalScrollbarSize, 0, 1000),
            scrollByPage: editorOptions_boolean(input.scrollByPage, this.defaultValue.scrollByPage),
        };
    }
}
/**
 * @internal
*/
const inUntrustedWorkspace = 'inUntrustedWorkspace';
/**
 * @internal
 */
const 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',
};
class UnicodeHighlight extends BaseEditorOption {
    constructor() {
        const defaults = {
            nonBasicASCII: inUntrustedWorkspace,
            invisibleCharacters: true,
            ambiguousCharacters: true,
            includeComments: inUntrustedWorkspace,
            includeStrings: true,
            allowedCharacters: {},
            allowedLocales: { _os: true, _vscode: true },
        };
        super(115 /* EditorOption.unicodeHighlighting */, 'unicodeHighlight', defaults, {
            [unicodeHighlightConfigKeys.nonBasicASCII]: {
                restricted: true,
                type: ['boolean', 'string'],
                enum: [true, false, inUntrustedWorkspace],
                default: defaults.nonBasicASCII,
                description: localize('unicodeHighlight.nonBasicASCII', "Controls whether all non-basic ASCII characters are highlighted. Only characters between U+0020 and U+007E, tab, line-feed and carriage-return are considered basic ASCII.")
            },
            [unicodeHighlightConfigKeys.invisibleCharacters]: {
                restricted: true,
                type: 'boolean',
                default: defaults.invisibleCharacters,
                description: localize('unicodeHighlight.invisibleCharacters', "Controls whether characters that just reserve space or have no width at all are highlighted.")
            },
            [unicodeHighlightConfigKeys.ambiguousCharacters]: {
                restricted: true,
                type: 'boolean',
                default: defaults.ambiguousCharacters,
                description: localize('unicodeHighlight.ambiguousCharacters', "Controls whether characters are highlighted that can be confused with basic ASCII characters, except those that are common in the current user locale.")
            },
            [unicodeHighlightConfigKeys.includeComments]: {
                restricted: true,
                type: ['boolean', 'string'],
                enum: [true, false, inUntrustedWorkspace],
                default: defaults.includeComments,
                description: localize('unicodeHighlight.includeComments', "Controls whether characters in comments should also be subject to unicode highlighting.")
            },
            [unicodeHighlightConfigKeys.includeStrings]: {
                restricted: true,
                type: ['boolean', 'string'],
                enum: [true, false, inUntrustedWorkspace],
                default: defaults.includeStrings,
                description: localize('unicodeHighlight.includeStrings', "Controls whether characters in strings should also be subject to unicode highlighting.")
            },
            [unicodeHighlightConfigKeys.allowedCharacters]: {
                restricted: true,
                type: 'object',
                default: defaults.allowedCharacters,
                description: localize('unicodeHighlight.allowedCharacters', "Defines allowed characters that are not being highlighted."),
                additionalProperties: {
                    type: 'boolean'
                }
            },
            [unicodeHighlightConfigKeys.allowedLocales]: {
                restricted: true,
                type: 'object',
                additionalProperties: {
                    type: 'boolean'
                },
                default: defaults.allowedLocales,
                description: localize('unicodeHighlight.allowedLocales', "Unicode characters that are common in allowed locales are not being highlighted.")
            },
        });
    }
    applyUpdate(value, update) {
        let didChange = false;
        if (update.allowedCharacters && value) {
            // Treat allowedCharacters atomically
            if (!objects_equals(value.allowedCharacters, update.allowedCharacters)) {
                value = Object.assign(Object.assign({}, value), { allowedCharacters: update.allowedCharacters });
                didChange = true;
            }
        }
        if (update.allowedLocales && value) {
            // Treat allowedLocales atomically
            if (!objects_equals(value.allowedLocales, update.allowedLocales)) {
                value = Object.assign(Object.assign({}, 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: editorOptions_boolean(input.invisibleCharacters, this.defaultValue.invisibleCharacters),
            ambiguousCharacters: editorOptions_boolean(input.ambiguousCharacters, this.defaultValue.ambiguousCharacters),
            includeComments: primitiveSet(input.includeComments, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
            includeStrings: primitiveSet(input.includeStrings, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
            allowedCharacters: this.validateBooleanMap(_input.allowedCharacters, this.defaultValue.allowedCharacters),
            allowedLocales: this.validateBooleanMap(_input.allowedLocales, this.defaultValue.allowedLocales),
        };
    }
    validateBooleanMap(map, defaultValue) {
        if ((typeof map !== 'object') || !map) {
            return defaultValue;
        }
        const result = {};
        for (const [key, value] of Object.entries(map)) {
            if (value === true) {
                result[key] = true;
            }
        }
        return result;
    }
}
/**
 * Configuration options for inline suggestions
 */
class InlineEditorSuggest extends BaseEditorOption {
    constructor() {
        const defaults = {
            enabled: true,
            mode: 'subwordSmart'
        };
        super(57 /* EditorOption.inlineSuggest */, 'inlineSuggest', defaults, {
            'editor.inlineSuggest.enabled': {
                type: 'boolean',
                default: defaults.enabled,
                description: localize('inlineSuggest.enabled', "Controls whether to automatically show inline suggestions in the editor.")
            }
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            enabled: editorOptions_boolean(input.enabled, this.defaultValue.enabled),
            mode: stringSet(input.mode, this.defaultValue.mode, ['prefix', 'subword', 'subwordSmart']),
        };
    }
}
/**
 * Configuration options for inline suggestions
 */
class BracketPairColorization extends BaseEditorOption {
    constructor() {
        const defaults = {
            enabled: EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions.enabled,
            independentColorPoolPerBracketType: EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions.independentColorPoolPerBracketType,
        };
        super(12 /* EditorOption.bracketPairColorization */, 'bracketPairColorization', defaults, {
            'editor.bracketPairColorization.enabled': {
                type: 'boolean',
                default: defaults.enabled,
                markdownDescription: localize('bracketPairColorization.enabled', "Controls whether bracket pair colorization is enabled or not. Use {0} to override the bracket highlight colors.", '`#workbench.colorCustomizations#`')
            },
            'editor.bracketPairColorization.independentColorPoolPerBracketType': {
                type: 'boolean',
                default: defaults.independentColorPoolPerBracketType,
                description: localize('bracketPairColorization.independentColorPoolPerBracketType', "Controls whether each bracket type has its own independent color pool.")
            },
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            enabled: editorOptions_boolean(input.enabled, this.defaultValue.enabled),
            independentColorPoolPerBracketType: editorOptions_boolean(input.independentColorPoolPerBracketType, this.defaultValue.independentColorPoolPerBracketType),
        };
    }
}
/**
 * Configuration options for inline suggestions
 */
class GuideOptions extends BaseEditorOption {
    constructor() {
        const defaults = {
            bracketPairs: false,
            bracketPairsHorizontal: 'active',
            highlightActiveBracketPair: true,
            indentation: true,
            highlightActiveIndentation: true
        };
        super(13 /* EditorOption.guides */, 'guides', defaults, {
            'editor.guides.bracketPairs': {
                type: ['boolean', 'string'],
                enum: [true, 'active', false],
                enumDescriptions: [
                    localize('editor.guides.bracketPairs.true', "Enables bracket pair guides."),
                    localize('editor.guides.bracketPairs.active', "Enables bracket pair guides only for the active bracket pair."),
                    localize('editor.guides.bracketPairs.false', "Disables bracket pair guides."),
                ],
                default: defaults.bracketPairs,
                description: localize('editor.guides.bracketPairs', "Controls whether bracket pair guides are enabled or not.")
            },
            'editor.guides.bracketPairsHorizontal': {
                type: ['boolean', 'string'],
                enum: [true, 'active', false],
                enumDescriptions: [
                    localize('editor.guides.bracketPairsHorizontal.true', "Enables horizontal guides as addition to vertical bracket pair guides."),
                    localize('editor.guides.bracketPairsHorizontal.active', "Enables horizontal guides only for the active bracket pair."),
                    localize('editor.guides.bracketPairsHorizontal.false', "Disables horizontal bracket pair guides."),
                ],
                default: defaults.bracketPairsHorizontal,
                description: localize('editor.guides.bracketPairsHorizontal', "Controls whether horizontal bracket pair guides are enabled or not.")
            },
            'editor.guides.highlightActiveBracketPair': {
                type: 'boolean',
                default: defaults.highlightActiveBracketPair,
                description: localize('editor.guides.highlightActiveBracketPair', "Controls whether the editor should highlight the active bracket pair.")
            },
            'editor.guides.indentation': {
                type: 'boolean',
                default: defaults.indentation,
                description: localize('editor.guides.indentation', "Controls whether the editor should render indent guides.")
            },
            'editor.guides.highlightActiveIndentation': {
                type: ['boolean', 'string'],
                enum: [true, 'always', false],
                enumDescriptions: [
                    localize('editor.guides.highlightActiveIndentation.true', "Highlights the active indent guide."),
                    localize('editor.guides.highlightActiveIndentation.always', "Highlights the active indent guide even if bracket guides are highlighted."),
                    localize('editor.guides.highlightActiveIndentation.false', "Do not highlight the active indent guide."),
                ],
                default: defaults.highlightActiveIndentation,
                description: localize('editor.guides.highlightActiveIndentation', "Controls whether the editor should highlight the active indent guide.")
            }
        });
    }
    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: editorOptions_boolean(input.highlightActiveBracketPair, this.defaultValue.highlightActiveBracketPair),
            indentation: editorOptions_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];
}
class EditorSuggest extends BaseEditorOption {
    constructor() {
        const defaults = {
            insertMode: 'insert',
            filterGraceful: true,
            snippetsPreventQuickSuggestions: true,
            localityBonus: false,
            shareSuggestSelections: false,
            showIcons: true,
            showStatusBar: false,
            preview: false,
            previewMode: 'subwordSmart',
            showInlineDetails: true,
            showMethods: true,
            showFunctions: true,
            showConstructors: true,
            showDeprecated: 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(108 /* EditorOption.suggest */, 'suggest', defaults, {
            'editor.suggest.insertMode': {
                type: 'string',
                enum: ['insert', 'replace'],
                enumDescriptions: [
                    localize('suggest.insertMode.insert', "Insert suggestion without overwriting text right of the cursor."),
                    localize('suggest.insertMode.replace', "Insert suggestion and overwrite text right of the cursor."),
                ],
                default: defaults.insertMode,
                description: localize('suggest.insertMode', "Controls whether words are overwritten when accepting completions. Note that this depends on extensions opting into this feature.")
            },
            'editor.suggest.filterGraceful': {
                type: 'boolean',
                default: defaults.filterGraceful,
                description: localize('suggest.filterGraceful', "Controls whether filtering and sorting suggestions accounts for small typos.")
            },
            'editor.suggest.localityBonus': {
                type: 'boolean',
                default: defaults.localityBonus,
                description: localize('suggest.localityBonus', "Controls whether sorting favors words that appear close to the cursor.")
            },
            'editor.suggest.shareSuggestSelections': {
                type: 'boolean',
                default: defaults.shareSuggestSelections,
                markdownDescription: localize('suggest.shareSuggestSelections', "Controls whether remembered suggestion selections are shared between multiple workspaces and windows (needs `#editor.suggestSelection#`).")
            },
            'editor.suggest.snippetsPreventQuickSuggestions': {
                type: 'boolean',
                default: defaults.snippetsPreventQuickSuggestions,
                description: localize('suggest.snippetsPreventQuickSuggestions', "Controls whether an active snippet prevents quick suggestions.")
            },
            'editor.suggest.showIcons': {
                type: 'boolean',
                default: defaults.showIcons,
                description: localize('suggest.showIcons', "Controls whether to show or hide icons in suggestions.")
            },
            'editor.suggest.showStatusBar': {
                type: 'boolean',
                default: defaults.showStatusBar,
                description: localize('suggest.showStatusBar', "Controls the visibility of the status bar at the bottom of the suggest widget.")
            },
            'editor.suggest.preview': {
                type: 'boolean',
                default: defaults.preview,
                description: localize('suggest.preview', "Controls whether to preview the suggestion outcome in the editor.")
            },
            'editor.suggest.showInlineDetails': {
                type: 'boolean',
                default: defaults.showInlineDetails,
                description: localize('suggest.showInlineDetails', "Controls whether suggest details show inline with the label or only in the details widget")
            },
            'editor.suggest.maxVisibleSuggestions': {
                type: 'number',
                deprecationMessage: localize('suggest.maxVisibleSuggestions.dep', "This setting is deprecated. The suggest widget can now be resized."),
            },
            'editor.suggest.filteredTypes': {
                type: 'object',
                deprecationMessage: localize('deprecated', "This setting is deprecated, please use separate settings like 'editor.suggest.showKeywords' or 'editor.suggest.showSnippets' instead.")
            },
            'editor.suggest.showMethods': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showMethods', "When enabled IntelliSense shows `method`-suggestions.")
            },
            'editor.suggest.showFunctions': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showFunctions', "When enabled IntelliSense shows `function`-suggestions.")
            },
            'editor.suggest.showConstructors': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showConstructors', "When enabled IntelliSense shows `constructor`-suggestions.")
            },
            'editor.suggest.showDeprecated': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showDeprecated', "When enabled IntelliSense shows `deprecated`-suggestions.")
            },
            'editor.suggest.showFields': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showFields', "When enabled IntelliSense shows `field`-suggestions.")
            },
            'editor.suggest.showVariables': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showVariables', "When enabled IntelliSense shows `variable`-suggestions.")
            },
            'editor.suggest.showClasses': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showClasss', "When enabled IntelliSense shows `class`-suggestions.")
            },
            'editor.suggest.showStructs': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showStructs', "When enabled IntelliSense shows `struct`-suggestions.")
            },
            'editor.suggest.showInterfaces': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showInterfaces', "When enabled IntelliSense shows `interface`-suggestions.")
            },
            'editor.suggest.showModules': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showModules', "When enabled IntelliSense shows `module`-suggestions.")
            },
            'editor.suggest.showProperties': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showPropertys', "When enabled IntelliSense shows `property`-suggestions.")
            },
            'editor.suggest.showEvents': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showEvents', "When enabled IntelliSense shows `event`-suggestions.")
            },
            'editor.suggest.showOperators': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showOperators', "When enabled IntelliSense shows `operator`-suggestions.")
            },
            'editor.suggest.showUnits': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showUnits', "When enabled IntelliSense shows `unit`-suggestions.")
            },
            'editor.suggest.showValues': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showValues', "When enabled IntelliSense shows `value`-suggestions.")
            },
            'editor.suggest.showConstants': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showConstants', "When enabled IntelliSense shows `constant`-suggestions.")
            },
            'editor.suggest.showEnums': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showEnums', "When enabled IntelliSense shows `enum`-suggestions.")
            },
            'editor.suggest.showEnumMembers': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showEnumMembers', "When enabled IntelliSense shows `enumMember`-suggestions.")
            },
            'editor.suggest.showKeywords': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showKeywords', "When enabled IntelliSense shows `keyword`-suggestions.")
            },
            'editor.suggest.showWords': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showTexts', "When enabled IntelliSense shows `text`-suggestions.")
            },
            'editor.suggest.showColors': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showColors', "When enabled IntelliSense shows `color`-suggestions.")
            },
            'editor.suggest.showFiles': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showFiles', "When enabled IntelliSense shows `file`-suggestions.")
            },
            'editor.suggest.showReferences': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showReferences', "When enabled IntelliSense shows `reference`-suggestions.")
            },
            'editor.suggest.showCustomcolors': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showCustomcolors', "When enabled IntelliSense shows `customcolor`-suggestions.")
            },
            'editor.suggest.showFolders': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showFolders', "When enabled IntelliSense shows `folder`-suggestions.")
            },
            'editor.suggest.showTypeParameters': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showTypeParameters', "When enabled IntelliSense shows `typeParameter`-suggestions.")
            },
            'editor.suggest.showSnippets': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showSnippets', "When enabled IntelliSense shows `snippet`-suggestions.")
            },
            'editor.suggest.showUsers': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showUsers', "When enabled IntelliSense shows `user`-suggestions.")
            },
            'editor.suggest.showIssues': {
                type: 'boolean',
                default: true,
                markdownDescription: localize('editor.suggest.showIssues', "When enabled IntelliSense shows `issues`-suggestions.")
            }
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            insertMode: stringSet(input.insertMode, this.defaultValue.insertMode, ['insert', 'replace']),
            filterGraceful: editorOptions_boolean(input.filterGraceful, this.defaultValue.filterGraceful),
            snippetsPreventQuickSuggestions: editorOptions_boolean(input.snippetsPreventQuickSuggestions, this.defaultValue.filterGraceful),
            localityBonus: editorOptions_boolean(input.localityBonus, this.defaultValue.localityBonus),
            shareSuggestSelections: editorOptions_boolean(input.shareSuggestSelections, this.defaultValue.shareSuggestSelections),
            showIcons: editorOptions_boolean(input.showIcons, this.defaultValue.showIcons),
            showStatusBar: editorOptions_boolean(input.showStatusBar, this.defaultValue.showStatusBar),
            preview: editorOptions_boolean(input.preview, this.defaultValue.preview),
            previewMode: stringSet(input.previewMode, this.defaultValue.previewMode, ['prefix', 'subword', 'subwordSmart']),
            showInlineDetails: editorOptions_boolean(input.showInlineDetails, this.defaultValue.showInlineDetails),
            showMethods: editorOptions_boolean(input.showMethods, this.defaultValue.showMethods),
            showFunctions: editorOptions_boolean(input.showFunctions, this.defaultValue.showFunctions),
            showConstructors: editorOptions_boolean(input.showConstructors, this.defaultValue.showConstructors),
            showDeprecated: editorOptions_boolean(input.showDeprecated, this.defaultValue.showDeprecated),
            showFields: editorOptions_boolean(input.showFields, this.defaultValue.showFields),
            showVariables: editorOptions_boolean(input.showVariables, this.defaultValue.showVariables),
            showClasses: editorOptions_boolean(input.showClasses, this.defaultValue.showClasses),
            showStructs: editorOptions_boolean(input.showStructs, this.defaultValue.showStructs),
            showInterfaces: editorOptions_boolean(input.showInterfaces, this.defaultValue.showInterfaces),
            showModules: editorOptions_boolean(input.showModules, this.defaultValue.showModules),
            showProperties: editorOptions_boolean(input.showProperties, this.defaultValue.showProperties),
            showEvents: editorOptions_boolean(input.showEvents, this.defaultValue.showEvents),
            showOperators: editorOptions_boolean(input.showOperators, this.defaultValue.showOperators),
            showUnits: editorOptions_boolean(input.showUnits, this.defaultValue.showUnits),
            showValues: editorOptions_boolean(input.showValues, this.defaultValue.showValues),
            showConstants: editorOptions_boolean(input.showConstants, this.defaultValue.showConstants),
            showEnums: editorOptions_boolean(input.showEnums, this.defaultValue.showEnums),
            showEnumMembers: editorOptions_boolean(input.showEnumMembers, this.defaultValue.showEnumMembers),
            showKeywords: editorOptions_boolean(input.showKeywords, this.defaultValue.showKeywords),
            showWords: editorOptions_boolean(input.showWords, this.defaultValue.showWords),
            showColors: editorOptions_boolean(input.showColors, this.defaultValue.showColors),
            showFiles: editorOptions_boolean(input.showFiles, this.defaultValue.showFiles),
            showReferences: editorOptions_boolean(input.showReferences, this.defaultValue.showReferences),
            showFolders: editorOptions_boolean(input.showFolders, this.defaultValue.showFolders),
            showTypeParameters: editorOptions_boolean(input.showTypeParameters, this.defaultValue.showTypeParameters),
            showSnippets: editorOptions_boolean(input.showSnippets, this.defaultValue.showSnippets),
            showUsers: editorOptions_boolean(input.showUsers, this.defaultValue.showUsers),
            showIssues: editorOptions_boolean(input.showIssues, this.defaultValue.showIssues),
        };
    }
}
class SmartSelect extends BaseEditorOption {
    constructor() {
        super(104 /* EditorOption.smartSelect */, 'smartSelect', {
            selectLeadingAndTrailingWhitespace: true
        }, {
            'editor.smartSelect.selectLeadingAndTrailingWhitespace': {
                description: localize('selectLeadingAndTrailingWhitespace', "Whether leading and trailing whitespace should always be selected."),
                default: true,
                type: 'boolean'
            }
        });
    }
    validate(input) {
        if (!input || typeof input !== 'object') {
            return this.defaultValue;
        }
        return {
            selectLeadingAndTrailingWhitespace: editorOptions_boolean(input.selectLeadingAndTrailingWhitespace, this.defaultValue.selectLeadingAndTrailingWhitespace)
        };
    }
}
//#endregion
//#region tabFocusMode
class EditorTabFocusMode extends ComputedEditorOption {
    constructor() {
        super(132 /* EditorOption.tabFocusMode */);
    }
    compute(env, options, _) {
        const readOnly = options.get(83 /* EditorOption.readOnly */);
        return (readOnly ? true : env.tabFocusMode);
    }
}
function _wrappingIndentFromString(wrappingIndent) {
    switch (wrappingIndent) {
        case 'none': return 0 /* WrappingIndent.None */;
        case 'same': return 1 /* WrappingIndent.Same */;
        case 'indent': return 2 /* WrappingIndent.Indent */;
        case 'deepIndent': return 3 /* WrappingIndent.DeepIndent */;
    }
}
class EditorWrappingInfoComputer extends ComputedEditorOption {
    constructor() {
        super(134 /* EditorOption.wrappingInfo */);
    }
    compute(env, options, _) {
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        return {
            isDominatedByLongLines: env.isDominatedByLongLines,
            isWordWrapMinified: layoutInfo.isWordWrapMinified,
            isViewportWrapping: layoutInfo.isViewportWrapping,
            wrappingColumn: layoutInfo.wrappingColumn,
        };
    }
}
class EditorDropIntoEditor extends BaseEditorOption {
    constructor() {
        const defaults = { enabled: true };
        super(32 /* EditorOption.dropIntoEditor */, 'dropIntoEditor', defaults, {
            'editor.dropIntoEditor.enabled': {
                type: 'boolean',
                default: defaults.enabled,
                markdownDescription: localize('dropIntoEditor.enabled', "Controls whether you can drag and drop a file into a text editor by holding down `shift` (instead of opening the file in an editor)."),
            },
        });
    }
    validate(_input) {
        if (!_input || typeof _input !== 'object') {
            return this.defaultValue;
        }
        const input = _input;
        return {
            enabled: editorOptions_boolean(input.enabled, this.defaultValue.enabled)
        };
    }
}
//#endregion
const DEFAULT_WINDOWS_FONT_FAMILY = 'Consolas, \'Courier New\', monospace';
const DEFAULT_MAC_FONT_FAMILY = 'Menlo, Monaco, \'Courier New\', monospace';
const DEFAULT_LINUX_FONT_FAMILY = '\'Droid Sans Mono\', \'monospace\', monospace';
/**
 * @internal
 */
const EDITOR_FONT_DEFAULTS = {
    fontFamily: (isMacintosh ? DEFAULT_MAC_FONT_FAMILY : (isLinux ? DEFAULT_LINUX_FONT_FAMILY : DEFAULT_WINDOWS_FONT_FAMILY)),
    fontWeight: 'normal',
    fontSize: (isMacintosh ? 12 : 14),
    lineHeight: 0,
    letterSpacing: 0,
};
/**
 * @internal
 */
const editorOptionsRegistry = [];
function register(option) {
    editorOptionsRegistry[option.id] = option;
    return option;
}
const EditorOptions = {
    acceptSuggestionOnCommitCharacter: register(new EditorBooleanOption(0 /* EditorOption.acceptSuggestionOnCommitCharacter */, 'acceptSuggestionOnCommitCharacter', true, { markdownDescription: localize('acceptSuggestionOnCommitCharacter', "Controls whether suggestions should be accepted on commit characters. For example, in JavaScript, the semi-colon (`; `) can be a commit character that accepts a suggestion and types that character.") })),
    acceptSuggestionOnEnter: register(new EditorStringEnumOption(1 /* EditorOption.acceptSuggestionOnEnter */, 'acceptSuggestionOnEnter', 'on', ['on', 'smart', 'off'], {
        markdownEnumDescriptions: [
            '',
            localize('acceptSuggestionOnEnterSmart', "Only accept a suggestion with `Enter` when it makes a textual change."),
            ''
        ],
        markdownDescription: localize('acceptSuggestionOnEnter', "Controls whether suggestions should be accepted on `Enter`, in addition to `Tab`. Helps to avoid ambiguity between inserting new lines or accepting suggestions.")
    })),
    accessibilitySupport: register(new EditorAccessibilitySupport()),
    accessibilityPageSize: register(new EditorIntOption(3 /* EditorOption.accessibilityPageSize */, 'accessibilityPageSize', 10, 1, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, {
        description: localize('accessibilityPageSize', "Controls the number of lines in the editor that can be read out by a screen reader at once. When we detect a screen reader we automatically set the default to be 500. Warning: this has a performance implication for numbers larger than the default.")
    })),
    ariaLabel: register(new EditorStringOption(4 /* EditorOption.ariaLabel */, 'ariaLabel', localize('editorViewAccessibleLabel', "Editor content"))),
    autoClosingBrackets: register(new EditorStringEnumOption(5 /* EditorOption.autoClosingBrackets */, 'autoClosingBrackets', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], {
        enumDescriptions: [
            '',
            localize('editor.autoClosingBrackets.languageDefined', "Use language configurations to determine when to autoclose brackets."),
            localize('editor.autoClosingBrackets.beforeWhitespace', "Autoclose brackets only when the cursor is to the left of whitespace."),
            '',
        ],
        description: localize('autoClosingBrackets', "Controls whether the editor should automatically close brackets after the user adds an opening bracket.")
    })),
    autoClosingDelete: register(new EditorStringEnumOption(6 /* EditorOption.autoClosingDelete */, 'autoClosingDelete', 'auto', ['always', 'auto', 'never'], {
        enumDescriptions: [
            '',
            localize('editor.autoClosingDelete.auto', "Remove adjacent closing quotes or brackets only if they were automatically inserted."),
            '',
        ],
        description: localize('autoClosingDelete', "Controls whether the editor should remove adjacent closing quotes or brackets when deleting.")
    })),
    autoClosingOvertype: register(new EditorStringEnumOption(7 /* EditorOption.autoClosingOvertype */, 'autoClosingOvertype', 'auto', ['always', 'auto', 'never'], {
        enumDescriptions: [
            '',
            localize('editor.autoClosingOvertype.auto', "Type over closing quotes or brackets only if they were automatically inserted."),
            '',
        ],
        description: localize('autoClosingOvertype', "Controls whether the editor should type over closing quotes or brackets.")
    })),
    autoClosingQuotes: register(new EditorStringEnumOption(8 /* EditorOption.autoClosingQuotes */, 'autoClosingQuotes', 'languageDefined', ['always', 'languageDefined', 'beforeWhitespace', 'never'], {
        enumDescriptions: [
            '',
            localize('editor.autoClosingQuotes.languageDefined', "Use language configurations to determine when to autoclose quotes."),
            localize('editor.autoClosingQuotes.beforeWhitespace', "Autoclose quotes only when the cursor is to the left of whitespace."),
            '',
        ],
        description: localize('autoClosingQuotes', "Controls whether the editor should automatically close quotes after the user adds an opening quote.")
    })),
    autoIndent: register(new EditorEnumOption(9 /* EditorOption.autoIndent */, 'autoIndent', 4 /* EditorAutoIndentStrategy.Full */, 'full', ['none', 'keep', 'brackets', 'advanced', 'full'], _autoIndentFromString, {
        enumDescriptions: [
            localize('editor.autoIndent.none', "The editor will not insert indentation automatically."),
            localize('editor.autoIndent.keep', "The editor will keep the current line's indentation."),
            localize('editor.autoIndent.brackets', "The editor will keep the current line's indentation and honor language defined brackets."),
            localize('editor.autoIndent.advanced', "The editor will keep the current line's indentation, honor language defined brackets and invoke special onEnterRules defined by languages."),
            localize('editor.autoIndent.full', "The editor will keep the current line's indentation, honor language defined brackets, invoke special onEnterRules defined by languages, and honor indentationRules defined by languages."),
        ],
        description: localize('autoIndent', "Controls whether the editor should automatically adjust the indentation when users type, paste, move or indent lines.")
    })),
    automaticLayout: register(new EditorBooleanOption(10 /* EditorOption.automaticLayout */, 'automaticLayout', false)),
    autoSurround: register(new EditorStringEnumOption(11 /* EditorOption.autoSurround */, 'autoSurround', 'languageDefined', ['languageDefined', 'quotes', 'brackets', 'never'], {
        enumDescriptions: [
            localize('editor.autoSurround.languageDefined', "Use language configurations to determine when to automatically surround selections."),
            localize('editor.autoSurround.quotes', "Surround with quotes but not brackets."),
            localize('editor.autoSurround.brackets', "Surround with brackets but not quotes."),
            ''
        ],
        description: localize('autoSurround', "Controls whether the editor should automatically surround selections when typing quotes or brackets.")
    })),
    bracketPairColorization: register(new BracketPairColorization()),
    bracketPairGuides: register(new GuideOptions()),
    stickyTabStops: register(new EditorBooleanOption(106 /* EditorOption.stickyTabStops */, 'stickyTabStops', false, { description: localize('stickyTabStops', "Emulate selection behavior of tab characters when using spaces for indentation. Selection will stick to tab stops.") })),
    codeLens: register(new EditorBooleanOption(14 /* EditorOption.codeLens */, 'codeLens', true, { description: localize('codeLens', "Controls whether the editor shows CodeLens.") })),
    codeLensFontFamily: register(new EditorStringOption(15 /* EditorOption.codeLensFontFamily */, 'codeLensFontFamily', '', { description: localize('codeLensFontFamily', "Controls the font family for CodeLens.") })),
    codeLensFontSize: register(new EditorIntOption(16 /* EditorOption.codeLensFontSize */, 'codeLensFontSize', 0, 0, 100, {
        type: 'number',
        default: 0,
        minimum: 0,
        maximum: 100,
        markdownDescription: localize('codeLensFontSize', "Controls the font size in pixels for CodeLens. When set to `0`, 90% of `#editor.fontSize#` is used.")
    })),
    colorDecorators: register(new EditorBooleanOption(17 /* EditorOption.colorDecorators */, 'colorDecorators', true, { description: localize('colorDecorators', "Controls whether the editor should render the inline color decorators and color picker.") })),
    columnSelection: register(new EditorBooleanOption(18 /* EditorOption.columnSelection */, 'columnSelection', false, { description: localize('columnSelection', "Enable that the selection with the mouse and keys is doing column selection.") })),
    comments: register(new EditorComments()),
    contextmenu: register(new EditorBooleanOption(20 /* EditorOption.contextmenu */, 'contextmenu', true)),
    copyWithSyntaxHighlighting: register(new EditorBooleanOption(21 /* EditorOption.copyWithSyntaxHighlighting */, 'copyWithSyntaxHighlighting', true, { description: localize('copyWithSyntaxHighlighting', "Controls whether syntax highlighting should be copied into the clipboard.") })),
    cursorBlinking: register(new EditorEnumOption(22 /* EditorOption.cursorBlinking */, 'cursorBlinking', 1 /* TextEditorCursorBlinkingStyle.Blink */, 'blink', ['blink', 'smooth', 'phase', 'expand', 'solid'], _cursorBlinkingStyleFromString, { description: localize('cursorBlinking', "Control the cursor animation style.") })),
    cursorSmoothCaretAnimation: register(new EditorBooleanOption(23 /* EditorOption.cursorSmoothCaretAnimation */, 'cursorSmoothCaretAnimation', false, { description: localize('cursorSmoothCaretAnimation', "Controls whether the smooth caret animation should be enabled.") })),
    cursorStyle: register(new EditorEnumOption(24 /* EditorOption.cursorStyle */, 'cursorStyle', TextEditorCursorStyle.Line, 'line', ['line', 'block', 'underline', 'line-thin', 'block-outline', 'underline-thin'], _cursorStyleFromString, { description: localize('cursorStyle', "Controls the cursor style.") })),
    cursorSurroundingLines: register(new EditorIntOption(25 /* EditorOption.cursorSurroundingLines */, 'cursorSurroundingLines', 0, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, { description: localize('cursorSurroundingLines', "Controls the minimal number of visible leading and trailing lines surrounding the cursor. Known as 'scrollOff' or 'scrollOffset' in some other editors.") })),
    cursorSurroundingLinesStyle: register(new EditorStringEnumOption(26 /* EditorOption.cursorSurroundingLinesStyle */, 'cursorSurroundingLinesStyle', 'default', ['default', 'all'], {
        enumDescriptions: [
            localize('cursorSurroundingLinesStyle.default', "`cursorSurroundingLines` is enforced only when triggered via the keyboard or API."),
            localize('cursorSurroundingLinesStyle.all', "`cursorSurroundingLines` is enforced always.")
        ],
        description: localize('cursorSurroundingLinesStyle', "Controls when `cursorSurroundingLines` should be enforced.")
    })),
    cursorWidth: register(new EditorIntOption(27 /* EditorOption.cursorWidth */, 'cursorWidth', 0, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, { markdownDescription: localize('cursorWidth', "Controls the width of the cursor when `#editor.cursorStyle#` is set to `line`.") })),
    disableLayerHinting: register(new EditorBooleanOption(28 /* EditorOption.disableLayerHinting */, 'disableLayerHinting', false)),
    disableMonospaceOptimizations: register(new EditorBooleanOption(29 /* EditorOption.disableMonospaceOptimizations */, 'disableMonospaceOptimizations', false)),
    domReadOnly: register(new EditorBooleanOption(30 /* EditorOption.domReadOnly */, 'domReadOnly', false)),
    dragAndDrop: register(new EditorBooleanOption(31 /* EditorOption.dragAndDrop */, 'dragAndDrop', true, { description: localize('dragAndDrop', "Controls whether the editor should allow moving selections via drag and drop.") })),
    emptySelectionClipboard: register(new EditorEmptySelectionClipboard()),
    dropIntoEditor: register(new EditorDropIntoEditor()),
    experimental: register(new EditorExperimental()),
    extraEditorClassName: register(new EditorStringOption(35 /* EditorOption.extraEditorClassName */, 'extraEditorClassName', '')),
    fastScrollSensitivity: register(new EditorFloatOption(36 /* EditorOption.fastScrollSensitivity */, 'fastScrollSensitivity', 5, x => (x <= 0 ? 5 : x), { markdownDescription: localize('fastScrollSensitivity', "Scrolling speed multiplier when pressing `Alt`.") })),
    find: register(new EditorFind()),
    fixedOverflowWidgets: register(new EditorBooleanOption(38 /* EditorOption.fixedOverflowWidgets */, 'fixedOverflowWidgets', false)),
    folding: register(new EditorBooleanOption(39 /* EditorOption.folding */, 'folding', true, { description: localize('folding', "Controls whether the editor has code folding enabled.") })),
    foldingStrategy: register(new EditorStringEnumOption(40 /* EditorOption.foldingStrategy */, 'foldingStrategy', 'auto', ['auto', 'indentation'], {
        enumDescriptions: [
            localize('foldingStrategy.auto', "Use a language-specific folding strategy if available, else the indentation-based one."),
            localize('foldingStrategy.indentation', "Use the indentation-based folding strategy."),
        ],
        description: localize('foldingStrategy', "Controls the strategy for computing folding ranges.")
    })),
    foldingHighlight: register(new EditorBooleanOption(41 /* EditorOption.foldingHighlight */, 'foldingHighlight', true, { description: localize('foldingHighlight', "Controls whether the editor should highlight folded ranges.") })),
    foldingImportsByDefault: register(new EditorBooleanOption(42 /* EditorOption.foldingImportsByDefault */, 'foldingImportsByDefault', false, { description: localize('foldingImportsByDefault', "Controls whether the editor automatically collapses import ranges.") })),
    foldingMaximumRegions: register(new EditorIntOption(43 /* EditorOption.foldingMaximumRegions */, 'foldingMaximumRegions', 5000, 10, 65000, // limit must be less than foldingRanges MAX_FOLDING_REGIONS
    { description: localize('foldingMaximumRegions', "The maximum number of foldable regions. Increasing this value may result in the editor becoming less responsive when the current source has a large number of foldable regions.") })),
    unfoldOnClickAfterEndOfLine: register(new EditorBooleanOption(44 /* EditorOption.unfoldOnClickAfterEndOfLine */, 'unfoldOnClickAfterEndOfLine', false, { description: localize('unfoldOnClickAfterEndOfLine', "Controls whether clicking on the empty content after a folded line will unfold the line.") })),
    fontFamily: register(new EditorStringOption(45 /* EditorOption.fontFamily */, 'fontFamily', EDITOR_FONT_DEFAULTS.fontFamily, { description: localize('fontFamily', "Controls the font family.") })),
    fontInfo: register(new EditorFontInfo()),
    fontLigatures2: register(new EditorFontLigatures()),
    fontSize: register(new EditorFontSize()),
    fontWeight: register(new EditorFontWeight()),
    formatOnPaste: register(new EditorBooleanOption(50 /* EditorOption.formatOnPaste */, 'formatOnPaste', false, { description: localize('formatOnPaste', "Controls whether the editor should automatically format the pasted content. A formatter must be available and the formatter should be able to format a range in a document.") })),
    formatOnType: register(new EditorBooleanOption(51 /* EditorOption.formatOnType */, 'formatOnType', false, { description: localize('formatOnType', "Controls whether the editor should automatically format the line after typing.") })),
    glyphMargin: register(new EditorBooleanOption(52 /* EditorOption.glyphMargin */, 'glyphMargin', true, { description: localize('glyphMargin', "Controls whether the editor should render the vertical glyph margin. Glyph margin is mostly used for debugging.") })),
    gotoLocation: register(new EditorGoToLocation()),
    hideCursorInOverviewRuler: register(new EditorBooleanOption(54 /* EditorOption.hideCursorInOverviewRuler */, 'hideCursorInOverviewRuler', false, { description: localize('hideCursorInOverviewRuler', "Controls whether the cursor should be hidden in the overview ruler.") })),
    hover: register(new EditorHover()),
    inDiffEditor: register(new EditorBooleanOption(56 /* EditorOption.inDiffEditor */, 'inDiffEditor', false)),
    letterSpacing: register(new EditorFloatOption(58 /* EditorOption.letterSpacing */, 'letterSpacing', EDITOR_FONT_DEFAULTS.letterSpacing, x => EditorFloatOption.clamp(x, -5, 20), { description: localize('letterSpacing', "Controls the letter spacing in pixels.") })),
    lightbulb: register(new EditorLightbulb()),
    lineDecorationsWidth: register(new SimpleEditorOption(60 /* EditorOption.lineDecorationsWidth */, 'lineDecorationsWidth', 10)),
    lineHeight: register(new EditorLineHeight()),
    lineNumbers: register(new EditorRenderLineNumbersOption()),
    lineNumbersMinChars: register(new EditorIntOption(63 /* EditorOption.lineNumbersMinChars */, 'lineNumbersMinChars', 5, 1, 300)),
    linkedEditing: register(new EditorBooleanOption(64 /* EditorOption.linkedEditing */, 'linkedEditing', false, { description: localize('linkedEditing', "Controls whether the editor has linked editing enabled. Depending on the language, related symbols, e.g. HTML tags, are updated while editing.") })),
    links: register(new EditorBooleanOption(65 /* EditorOption.links */, 'links', true, { description: localize('links', "Controls whether the editor should detect links and make them clickable.") })),
    matchBrackets: register(new EditorStringEnumOption(66 /* EditorOption.matchBrackets */, 'matchBrackets', 'always', ['always', 'near', 'never'], { description: localize('matchBrackets', "Highlight matching brackets.") })),
    minimap: register(new EditorMinimap()),
    mouseStyle: register(new EditorStringEnumOption(68 /* EditorOption.mouseStyle */, 'mouseStyle', 'text', ['text', 'default', 'copy'])),
    mouseWheelScrollSensitivity: register(new EditorFloatOption(69 /* EditorOption.mouseWheelScrollSensitivity */, 'mouseWheelScrollSensitivity', 1, x => (x === 0 ? 1 : x), { markdownDescription: localize('mouseWheelScrollSensitivity', "A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.") })),
    mouseWheelZoom: register(new EditorBooleanOption(70 /* EditorOption.mouseWheelZoom */, 'mouseWheelZoom', false, { markdownDescription: localize('mouseWheelZoom', "Zoom the font of the editor when using mouse wheel and holding `Ctrl`.") })),
    multiCursorMergeOverlapping: register(new EditorBooleanOption(71 /* EditorOption.multiCursorMergeOverlapping */, 'multiCursorMergeOverlapping', true, { description: localize('multiCursorMergeOverlapping', "Merge multiple cursors when they are overlapping.") })),
    multiCursorModifier: register(new EditorEnumOption(72 /* EditorOption.multiCursorModifier */, 'multiCursorModifier', 'altKey', 'alt', ['ctrlCmd', 'alt'], _multiCursorModifierFromString, {
        markdownEnumDescriptions: [
            localize('multiCursorModifier.ctrlCmd', "Maps to `Control` on Windows and Linux and to `Command` on macOS."),
            localize('multiCursorModifier.alt', "Maps to `Alt` on Windows and Linux and to `Option` on macOS.")
        ],
        markdownDescription: localize({
            key: 'multiCursorModifier',
            comment: [
                '- `ctrlCmd` refers to a value the setting can take and should not be localized.',
                '- `Control` and `Command` refer to the modifier keys Ctrl or Cmd on the keyboard and can be localized.'
            ]
        }, "The modifier to be used to add multiple cursors with the mouse. The Go to Definition and Open Link mouse gestures will adapt such that they do not conflict with the [multicursor modifier](https://code.visualstudio.com/docs/editor/codebasics#_multicursor-modifier).")
    })),
    multiCursorPaste: register(new EditorStringEnumOption(73 /* EditorOption.multiCursorPaste */, 'multiCursorPaste', 'spread', ['spread', 'full'], {
        markdownEnumDescriptions: [
            localize('multiCursorPaste.spread', "Each cursor pastes a single line of the text."),
            localize('multiCursorPaste.full', "Each cursor pastes the full text.")
        ],
        markdownDescription: localize('multiCursorPaste', "Controls pasting when the line count of the pasted text matches the cursor count.")
    })),
    occurrencesHighlight: register(new EditorBooleanOption(74 /* EditorOption.occurrencesHighlight */, 'occurrencesHighlight', true, { description: localize('occurrencesHighlight', "Controls whether the editor should highlight semantic symbol occurrences.") })),
    overviewRulerBorder: register(new EditorBooleanOption(75 /* EditorOption.overviewRulerBorder */, 'overviewRulerBorder', true, { description: localize('overviewRulerBorder', "Controls whether a border should be drawn around the overview ruler.") })),
    overviewRulerLanes: register(new EditorIntOption(76 /* EditorOption.overviewRulerLanes */, 'overviewRulerLanes', 3, 0, 3)),
    padding: register(new EditorPadding()),
    parameterHints: register(new EditorParameterHints()),
    peekWidgetDefaultFocus: register(new EditorStringEnumOption(79 /* EditorOption.peekWidgetDefaultFocus */, 'peekWidgetDefaultFocus', 'tree', ['tree', 'editor'], {
        enumDescriptions: [
            localize('peekWidgetDefaultFocus.tree', "Focus the tree when opening peek"),
            localize('peekWidgetDefaultFocus.editor', "Focus the editor when opening peek")
        ],
        description: localize('peekWidgetDefaultFocus', "Controls whether to focus the inline editor or the tree in the peek widget.")
    })),
    definitionLinkOpensInPeek: register(new EditorBooleanOption(80 /* EditorOption.definitionLinkOpensInPeek */, 'definitionLinkOpensInPeek', false, { description: localize('definitionLinkOpensInPeek', "Controls whether the Go to Definition mouse gesture always opens the peek widget.") })),
    quickSuggestions: register(new EditorQuickSuggestions()),
    quickSuggestionsDelay: register(new EditorIntOption(82 /* EditorOption.quickSuggestionsDelay */, 'quickSuggestionsDelay', 10, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, { description: localize('quickSuggestionsDelay', "Controls the delay in milliseconds after which quick suggestions will show up.") })),
    readOnly: register(new EditorBooleanOption(83 /* EditorOption.readOnly */, 'readOnly', false)),
    renameOnType: register(new EditorBooleanOption(84 /* EditorOption.renameOnType */, 'renameOnType', false, { description: localize('renameOnType', "Controls whether the editor auto renames on type."), markdownDeprecationMessage: localize('renameOnTypeDeprecate', "Deprecated, use `editor.linkedEditing` instead.") })),
    renderControlCharacters: register(new EditorBooleanOption(85 /* EditorOption.renderControlCharacters */, 'renderControlCharacters', true, { description: localize('renderControlCharacters', "Controls whether the editor should render control characters."), restricted: true })),
    renderFinalNewline: register(new EditorBooleanOption(86 /* EditorOption.renderFinalNewline */, 'renderFinalNewline', true, { description: localize('renderFinalNewline', "Render last line number when the file ends with a newline.") })),
    renderLineHighlight: register(new EditorStringEnumOption(87 /* EditorOption.renderLineHighlight */, 'renderLineHighlight', 'line', ['none', 'gutter', 'line', 'all'], {
        enumDescriptions: [
            '',
            '',
            '',
            localize('renderLineHighlight.all', "Highlights both the gutter and the current line."),
        ],
        description: localize('renderLineHighlight', "Controls how the editor should render the current line highlight.")
    })),
    renderLineHighlightOnlyWhenFocus: register(new EditorBooleanOption(88 /* EditorOption.renderLineHighlightOnlyWhenFocus */, 'renderLineHighlightOnlyWhenFocus', false, { description: localize('renderLineHighlightOnlyWhenFocus', "Controls if the editor should render the current line highlight only when the editor is focused.") })),
    renderValidationDecorations: register(new EditorStringEnumOption(89 /* EditorOption.renderValidationDecorations */, 'renderValidationDecorations', 'editable', ['editable', 'on', 'off'])),
    renderWhitespace: register(new EditorStringEnumOption(90 /* EditorOption.renderWhitespace */, 'renderWhitespace', 'selection', ['none', 'boundary', 'selection', 'trailing', 'all'], {
        enumDescriptions: [
            '',
            localize('renderWhitespace.boundary', "Render whitespace characters except for single spaces between words."),
            localize('renderWhitespace.selection', "Render whitespace characters only on selected text."),
            localize('renderWhitespace.trailing', "Render only trailing whitespace characters."),
            ''
        ],
        description: localize('renderWhitespace', "Controls how the editor should render whitespace characters.")
    })),
    revealHorizontalRightPadding: register(new EditorIntOption(91 /* EditorOption.revealHorizontalRightPadding */, 'revealHorizontalRightPadding', 30, 0, 1000)),
    roundedSelection: register(new EditorBooleanOption(92 /* EditorOption.roundedSelection */, 'roundedSelection', true, { description: localize('roundedSelection', "Controls whether selections should have rounded corners.") })),
    rulers: register(new EditorRulers()),
    scrollbar: register(new EditorScrollbar()),
    scrollBeyondLastColumn: register(new EditorIntOption(95 /* EditorOption.scrollBeyondLastColumn */, 'scrollBeyondLastColumn', 4, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, { description: localize('scrollBeyondLastColumn', "Controls the number of extra characters beyond which the editor will scroll horizontally.") })),
    scrollBeyondLastLine: register(new EditorBooleanOption(96 /* EditorOption.scrollBeyondLastLine */, 'scrollBeyondLastLine', true, { description: localize('scrollBeyondLastLine', "Controls whether the editor will scroll beyond the last line.") })),
    scrollPredominantAxis: register(new EditorBooleanOption(97 /* EditorOption.scrollPredominantAxis */, 'scrollPredominantAxis', true, { description: localize('scrollPredominantAxis', "Scroll only along the predominant axis when scrolling both vertically and horizontally at the same time. Prevents horizontal drift when scrolling vertically on a trackpad.") })),
    selectionClipboard: register(new EditorBooleanOption(98 /* EditorOption.selectionClipboard */, 'selectionClipboard', true, {
        description: localize('selectionClipboard', "Controls whether the Linux primary clipboard should be supported."),
        included: isLinux
    })),
    selectionHighlight: register(new EditorBooleanOption(99 /* EditorOption.selectionHighlight */, 'selectionHighlight', true, { description: localize('selectionHighlight', "Controls whether the editor should highlight matches similar to the selection.") })),
    selectOnLineNumbers: register(new EditorBooleanOption(100 /* EditorOption.selectOnLineNumbers */, 'selectOnLineNumbers', true)),
    showFoldingControls: register(new EditorStringEnumOption(101 /* EditorOption.showFoldingControls */, 'showFoldingControls', 'mouseover', ['always', 'never', 'mouseover'], {
        enumDescriptions: [
            localize('showFoldingControls.always', "Always show the folding controls."),
            localize('showFoldingControls.never', "Never show the folding controls and reduce the gutter size."),
            localize('showFoldingControls.mouseover', "Only show the folding controls when the mouse is over the gutter."),
        ],
        description: localize('showFoldingControls', "Controls when the folding controls on the gutter are shown.")
    })),
    showUnused: register(new EditorBooleanOption(102 /* EditorOption.showUnused */, 'showUnused', true, { description: localize('showUnused', "Controls fading out of unused code.") })),
    showDeprecated: register(new EditorBooleanOption(128 /* EditorOption.showDeprecated */, 'showDeprecated', true, { description: localize('showDeprecated', "Controls strikethrough deprecated variables.") })),
    inlayHints: register(new EditorInlayHints()),
    snippetSuggestions: register(new EditorStringEnumOption(103 /* EditorOption.snippetSuggestions */, 'snippetSuggestions', 'inline', ['top', 'bottom', 'inline', 'none'], {
        enumDescriptions: [
            localize('snippetSuggestions.top', "Show snippet suggestions on top of other suggestions."),
            localize('snippetSuggestions.bottom', "Show snippet suggestions below other suggestions."),
            localize('snippetSuggestions.inline', "Show snippets suggestions with other suggestions."),
            localize('snippetSuggestions.none', "Do not show snippet suggestions."),
        ],
        description: localize('snippetSuggestions', "Controls whether snippets are shown with other suggestions and how they are sorted.")
    })),
    smartSelect: register(new SmartSelect()),
    smoothScrolling: register(new EditorBooleanOption(105 /* EditorOption.smoothScrolling */, 'smoothScrolling', false, { description: localize('smoothScrolling', "Controls whether the editor will scroll using an animation.") })),
    stopRenderingLineAfter: register(new EditorIntOption(107 /* EditorOption.stopRenderingLineAfter */, 'stopRenderingLineAfter', 10000, -1, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */)),
    suggest: register(new EditorSuggest()),
    inlineSuggest: register(new InlineEditorSuggest()),
    suggestFontSize: register(new EditorIntOption(109 /* EditorOption.suggestFontSize */, 'suggestFontSize', 0, 0, 1000, { markdownDescription: localize('suggestFontSize', "Font size for the suggest widget. When set to {0}, the value of {1} is used.", '`0`', '`#editor.fontSize#`') })),
    suggestLineHeight: register(new EditorIntOption(110 /* EditorOption.suggestLineHeight */, 'suggestLineHeight', 0, 0, 1000, { markdownDescription: localize('suggestLineHeight', "Line height for the suggest widget. When set to {0}, the value of {1} is used. The minimum value is 8.", '`0`', '`#editor.lineHeight#`') })),
    suggestOnTriggerCharacters: register(new EditorBooleanOption(111 /* EditorOption.suggestOnTriggerCharacters */, 'suggestOnTriggerCharacters', true, { description: localize('suggestOnTriggerCharacters', "Controls whether suggestions should automatically show up when typing trigger characters.") })),
    suggestSelection: register(new EditorStringEnumOption(112 /* EditorOption.suggestSelection */, 'suggestSelection', 'first', ['first', 'recentlyUsed', 'recentlyUsedByPrefix'], {
        markdownEnumDescriptions: [
            localize('suggestSelection.first', "Always select the first suggestion."),
            localize('suggestSelection.recentlyUsed', "Select recent suggestions unless further typing selects one, e.g. `console.| -> console.log` because `log` has been completed recently."),
            localize('suggestSelection.recentlyUsedByPrefix', "Select suggestions based on previous prefixes that have completed those suggestions, e.g. `co -> console` and `con -> const`."),
        ],
        description: localize('suggestSelection', "Controls how suggestions are pre-selected when showing the suggest list.")
    })),
    tabCompletion: register(new EditorStringEnumOption(113 /* EditorOption.tabCompletion */, 'tabCompletion', 'off', ['on', 'off', 'onlySnippets'], {
        enumDescriptions: [
            localize('tabCompletion.on', "Tab complete will insert the best matching suggestion when pressing tab."),
            localize('tabCompletion.off', "Disable tab completions."),
            localize('tabCompletion.onlySnippets', "Tab complete snippets when their prefix match. Works best when 'quickSuggestions' aren't enabled."),
        ],
        description: localize('tabCompletion', "Enables tab completions.")
    })),
    tabIndex: register(new EditorIntOption(114 /* EditorOption.tabIndex */, 'tabIndex', 0, -1, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */)),
    unicodeHighlight: register(new UnicodeHighlight()),
    unusualLineTerminators: register(new EditorStringEnumOption(116 /* EditorOption.unusualLineTerminators */, 'unusualLineTerminators', 'prompt', ['auto', 'off', 'prompt'], {
        enumDescriptions: [
            localize('unusualLineTerminators.auto', "Unusual line terminators are automatically removed."),
            localize('unusualLineTerminators.off', "Unusual line terminators are ignored."),
            localize('unusualLineTerminators.prompt', "Unusual line terminators prompt to be removed."),
        ],
        description: localize('unusualLineTerminators', "Remove unusual line terminators that might cause problems.")
    })),
    useShadowDOM: register(new EditorBooleanOption(117 /* EditorOption.useShadowDOM */, 'useShadowDOM', true)),
    useTabStops: register(new EditorBooleanOption(118 /* EditorOption.useTabStops */, 'useTabStops', true, { description: localize('useTabStops', "Inserting and deleting whitespace follows tab stops.") })),
    wordSeparators: register(new EditorStringOption(119 /* EditorOption.wordSeparators */, 'wordSeparators', USUAL_WORD_SEPARATORS, { description: localize('wordSeparators', "Characters that will be used as word separators when doing word related navigations or operations.") })),
    wordWrap: register(new EditorStringEnumOption(120 /* EditorOption.wordWrap */, 'wordWrap', 'off', ['off', 'on', 'wordWrapColumn', 'bounded'], {
        markdownEnumDescriptions: [
            localize('wordWrap.off', "Lines will never wrap."),
            localize('wordWrap.on', "Lines will wrap at the viewport width."),
            localize({
                key: 'wordWrap.wordWrapColumn',
                comment: [
                    '- `editor.wordWrapColumn` refers to a different setting and should not be localized.'
                ]
            }, "Lines will wrap at `#editor.wordWrapColumn#`."),
            localize({
                key: 'wordWrap.bounded',
                comment: [
                    '- viewport means the edge of the visible window size.',
                    '- `editor.wordWrapColumn` refers to a different setting and should not be localized.'
                ]
            }, "Lines will wrap at the minimum of viewport and `#editor.wordWrapColumn#`."),
        ],
        description: localize({
            key: 'wordWrap',
            comment: [
                '- \'off\', \'on\', \'wordWrapColumn\' and \'bounded\' refer to values the setting can take and should not be localized.',
                '- `editor.wordWrapColumn` refers to a different setting and should not be localized.'
            ]
        }, "Controls how lines should wrap.")
    })),
    wordWrapBreakAfterCharacters: register(new EditorStringOption(121 /* EditorOption.wordWrapBreakAfterCharacters */, 'wordWrapBreakAfterCharacters', 
    // allow-any-unicode-next-line
    ' \t})]?|/&.,;¢°′″‰℃、。｡､￠，．：；？！％・･ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ｧｨｩｪｫｬｭｮｯｰ”〉》」』】〕）］｝｣')),
    wordWrapBreakBeforeCharacters: register(new EditorStringOption(122 /* EditorOption.wordWrapBreakBeforeCharacters */, 'wordWrapBreakBeforeCharacters', 
    // allow-any-unicode-next-line
    '([{‘“〈《「『【〔（［｛｢£¥＄￡￥+＋')),
    wordWrapColumn: register(new EditorIntOption(123 /* EditorOption.wordWrapColumn */, 'wordWrapColumn', 80, 1, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, {
        markdownDescription: localize({
            key: 'wordWrapColumn',
            comment: [
                '- `editor.wordWrap` refers to a different setting and should not be localized.',
                '- \'wordWrapColumn\' and \'bounded\' refer to values the different setting can take and should not be localized.'
            ]
        }, "Controls the wrapping column of the editor when `#editor.wordWrap#` is `wordWrapColumn` or `bounded`.")
    })),
    wordWrapOverride1: register(new EditorStringEnumOption(124 /* EditorOption.wordWrapOverride1 */, 'wordWrapOverride1', 'inherit', ['off', 'on', 'inherit'])),
    wordWrapOverride2: register(new EditorStringEnumOption(125 /* EditorOption.wordWrapOverride2 */, 'wordWrapOverride2', 'inherit', ['off', 'on', 'inherit'])),
    wrappingIndent: register(new EditorEnumOption(126 /* EditorOption.wrappingIndent */, 'wrappingIndent', 1 /* WrappingIndent.Same */, 'same', ['none', 'same', 'indent', 'deepIndent'], _wrappingIndentFromString, {
        enumDescriptions: [
            localize('wrappingIndent.none', "No indentation. Wrapped lines begin at column 1."),
            localize('wrappingIndent.same', "Wrapped lines get the same indentation as the parent."),
            localize('wrappingIndent.indent', "Wrapped lines get +1 indentation toward the parent."),
            localize('wrappingIndent.deepIndent', "Wrapped lines get +2 indentation toward the parent."),
        ],
        description: localize('wrappingIndent', "Controls the indentation of wrapped lines."),
    })),
    wrappingStrategy: register(new EditorStringEnumOption(127 /* EditorOption.wrappingStrategy */, 'wrappingStrategy', 'simple', ['simple', 'advanced'], {
        enumDescriptions: [
            localize('wrappingStrategy.simple', "Assumes that all characters are of the same width. This is a fast algorithm that works correctly for monospace fonts and certain scripts (like Latin characters) where glyphs are of equal width."),
            localize('wrappingStrategy.advanced', "Delegates wrapping points computation to the browser. This is a slow algorithm, that might cause freezes for large files, but it works correctly in all cases.")
        ],
        description: localize('wrappingStrategy', "Controls the algorithm that computes wrapping points.")
    })),
    // Leave these at the end (because they have dependencies!)
    editorClassName: register(new EditorClassName()),
    pixelRatio: register(new EditorPixelRatio()),
    tabFocusMode: register(new EditorTabFocusMode()),
    layoutInfo: register(new EditorLayoutInfoComputer()),
    wrappingInfo: register(new EditorWrappingInfoComputer())
};

;// ../../node_modules/monaco-editor/esm/vs/editor/common/config/editorConfigurationSchema.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





const editorConfigurationBaseNode = Object.freeze({
    id: 'editor',
    order: 5,
    type: 'object',
    title: localize('editorConfigurationTitle', "Editor"),
    scope: 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */,
});
const editorConfiguration = Object.assign(Object.assign({}, editorConfigurationBaseNode), { properties: {
        'editor.tabSize': {
            type: 'number',
            default: EDITOR_MODEL_DEFAULTS.tabSize,
            minimum: 1,
            markdownDescription: localize('tabSize', "The number of spaces a tab is equal to. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.")
        },
        // 'editor.indentSize': {
        // 	'anyOf': [
        // 		{
        // 			type: 'string',
        // 			enum: ['tabSize']
        // 		},
        // 		{
        // 			type: 'number',
        // 			minimum: 1
        // 		}
        // 	],
        // 	default: 'tabSize',
        // 	markdownDescription: nls.localize('indentSize', "The number of spaces used for indentation or 'tabSize' to use the value from `#editor.tabSize#`. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.")
        // },
        'editor.insertSpaces': {
            type: 'boolean',
            default: EDITOR_MODEL_DEFAULTS.insertSpaces,
            markdownDescription: localize('insertSpaces', "Insert spaces when pressing `Tab`. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.")
        },
        'editor.detectIndentation': {
            type: 'boolean',
            default: EDITOR_MODEL_DEFAULTS.detectIndentation,
            markdownDescription: localize('detectIndentation', "Controls whether `#editor.tabSize#` and `#editor.insertSpaces#` will be automatically detected when a file is opened based on the file contents.")
        },
        'editor.trimAutoWhitespace': {
            type: 'boolean',
            default: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
            description: localize('trimAutoWhitespace', "Remove trailing auto inserted whitespace.")
        },
        'editor.largeFileOptimizations': {
            type: 'boolean',
            default: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
            description: localize('largeFileOptimizations', "Special handling for large files to disable certain memory intensive features.")
        },
        'editor.wordBasedSuggestions': {
            type: 'boolean',
            default: true,
            description: localize('wordBasedSuggestions', "Controls whether completions should be computed based on words in the document.")
        },
        'editor.wordBasedSuggestionsMode': {
            enum: ['currentDocument', 'matchingDocuments', 'allDocuments'],
            default: 'matchingDocuments',
            enumDescriptions: [
                localize('wordBasedSuggestionsMode.currentDocument', 'Only suggest words from the active document.'),
                localize('wordBasedSuggestionsMode.matchingDocuments', 'Suggest words from all open documents of the same language.'),
                localize('wordBasedSuggestionsMode.allDocuments', 'Suggest words from all open documents.')
            ],
            description: localize('wordBasedSuggestionsMode', "Controls from which documents word based completions are computed.")
        },
        'editor.semanticHighlighting.enabled': {
            enum: [true, false, 'configuredByTheme'],
            enumDescriptions: [
                localize('semanticHighlighting.true', 'Semantic highlighting enabled for all color themes.'),
                localize('semanticHighlighting.false', 'Semantic highlighting disabled for all color themes.'),
                localize('semanticHighlighting.configuredByTheme', 'Semantic highlighting is configured by the current color theme\'s `semanticHighlighting` setting.')
            ],
            default: 'configuredByTheme',
            description: localize('semanticHighlighting.enabled', "Controls whether the semanticHighlighting is shown for the languages that support it.")
        },
        'editor.stablePeek': {
            type: 'boolean',
            default: false,
            markdownDescription: localize('stablePeek', "Keep peek editors open even when double clicking their content or when hitting `Escape`.")
        },
        'editor.maxTokenizationLineLength': {
            type: 'integer',
            default: 20000,
            description: localize('maxTokenizationLineLength', "Lines above this length will not be tokenized for performance reasons")
        },
        'editor.language.brackets': {
            type: ['array', 'null'],
            default: null,
            description: localize('schema.brackets', 'Defines the bracket symbols that increase or decrease the indentation.'),
            items: {
                type: 'array',
                items: [
                    {
                        type: 'string',
                        description: localize('schema.openBracket', 'The opening bracket character or string sequence.')
                    },
                    {
                        type: 'string',
                        description: localize('schema.closeBracket', 'The closing bracket character or string sequence.')
                    }
                ]
            }
        },
        'editor.language.colorizedBracketPairs': {
            type: ['array', 'null'],
            default: null,
            description: localize('schema.colorizedBracketPairs', 'Defines the bracket pairs that are colorized by their nesting level if bracket pair colorization is enabled.'),
            items: {
                type: 'array',
                items: [
                    {
                        type: 'string',
                        description: localize('schema.openBracket', 'The opening bracket character or string sequence.')
                    },
                    {
                        type: 'string',
                        description: localize('schema.closeBracket', 'The closing bracket character or string sequence.')
                    }
                ]
            }
        },
        'diffEditor.maxComputationTime': {
            type: 'number',
            default: 5000,
            description: localize('maxComputationTime', "Timeout in milliseconds after which diff computation is cancelled. Use 0 for no timeout.")
        },
        'diffEditor.maxFileSize': {
            type: 'number',
            default: 50,
            description: localize('maxFileSize', "Maximum file size in MB for which to compute diffs. Use 0 for no limit.")
        },
        'diffEditor.renderSideBySide': {
            type: 'boolean',
            default: true,
            description: localize('sideBySide', "Controls whether the diff editor shows the diff side by side or inline.")
        },
        'diffEditor.renderMarginRevertIcon': {
            type: 'boolean',
            default: true,
            description: localize('renderMarginRevertIcon', "When enabled, the diff editor shows arrows in its glyph margin to revert changes.")
        },
        'diffEditor.ignoreTrimWhitespace': {
            type: 'boolean',
            default: true,
            description: localize('ignoreTrimWhitespace', "When enabled, the diff editor ignores changes in leading or trailing whitespace.")
        },
        'diffEditor.renderIndicators': {
            type: 'boolean',
            default: true,
            description: localize('renderIndicators', "Controls whether the diff editor shows +/- indicators for added/removed changes.")
        },
        'diffEditor.codeLens': {
            type: 'boolean',
            default: false,
            description: localize('codeLens', "Controls whether the editor shows CodeLens.")
        },
        'diffEditor.wordWrap': {
            type: 'string',
            enum: ['off', 'on', 'inherit'],
            default: 'inherit',
            markdownEnumDescriptions: [
                localize('wordWrap.off', "Lines will never wrap."),
                localize('wordWrap.on', "Lines will wrap at the viewport width."),
                localize('wordWrap.inherit', "Lines will wrap according to the `#editor.wordWrap#` setting."),
            ]
        }
    } });
function isConfigurationPropertySchema(x) {
    return (typeof x.type !== 'undefined' || typeof x.anyOf !== 'undefined');
}
// Add properties from the Editor Option Registry
for (const editorOption of editorOptionsRegistry) {
    const schema = editorOption.schema;
    if (typeof schema !== 'undefined') {
        if (isConfigurationPropertySchema(schema)) {
            // This is a single schema contribution
            editorConfiguration.properties[`editor.${editorOption.name}`] = schema;
        }
        else {
            for (const key in schema) {
                if (Object.hasOwnProperty.call(schema, key)) {
                    editorConfiguration.properties[key] = schema[key];
                }
            }
        }
    }
}
let cachedEditorConfigurationKeys = null;
function getEditorConfigurationKeys() {
    if (cachedEditorConfigurationKeys === null) {
        cachedEditorConfigurationKeys = Object.create(null);
        Object.keys(editorConfiguration.properties).forEach((prop) => {
            cachedEditorConfigurationKeys[prop] = true;
        });
    }
    return cachedEditorConfigurationKeys;
}
function isEditorConfigurationKey(key) {
    const editorConfigurationKeys = getEditorConfigurationKeys();
    return (editorConfigurationKeys[`editor.${key}`] || false);
}
function isDiffEditorConfigurationKey(key) {
    const editorConfigurationKeys = getEditorConfigurationKeys();
    return (editorConfigurationKeys[`diffEditor.${key}`] || false);
}
const editorConfigurationSchema_configurationRegistry = Registry.as(configurationRegistry_Extensions.Configuration);
editorConfigurationSchema_configurationRegistry.registerConfiguration(editorConfiguration);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/codeActionWidgetContribution.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




Registry.as(configurationRegistry_Extensions.Configuration).registerConfiguration(Object.assign(Object.assign({}, editorConfigurationBaseNode), { properties: {
        'editor.experimental.useCustomCodeActionMenu': {
            type: 'boolean',
            tags: ['experimental'],
            scope: 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */,
            description: localize('codeActionWidget', "Enabling this adjusts how the code action menu is rendered."),
            default: false,
        },
    } }));

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/codeActionContributions.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



registerEditorContribution(QuickFixController.ID, QuickFixController);
registerEditorAction(QuickFixAction);
registerEditorAction(RefactorAction);
registerEditorAction(RefactorPreview);
registerEditorAction(SourceAction);
registerEditorAction(OrganizeImportsAction);
registerEditorAction(AutoFixAction);
registerEditorAction(FixAllAction);
registerEditorCommand(new CodeActionCommand());

;// ../../node_modules/monaco-editor/esm/vs/base/common/hash.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/**
 * Return a hash value for an object.
 */
function hash(obj) {
    return doHash(obj, 0);
}
function doHash(obj, hashVal) {
    switch (typeof obj) {
        case 'object':
            if (obj === null) {
                return numberHash(349, hashVal);
            }
            else if (Array.isArray(obj)) {
                return arrayHash(obj, hashVal);
            }
            return objectHash(obj, hashVal);
        case 'string':
            return stringHash(obj, hashVal);
        case 'boolean':
            return booleanHash(obj, hashVal);
        case 'number':
            return numberHash(obj, hashVal);
        case 'undefined':
            return numberHash(937, hashVal);
        default:
            return numberHash(617, hashVal);
    }
}
function numberHash(val, initialHashVal) {
    return (((initialHashVal << 5) - initialHashVal) + val) | 0; // hashVal * 31 + ch, keep as int32
}
function booleanHash(b, initialHashVal) {
    return numberHash(b ? 433 : 863, initialHashVal);
}
function stringHash(s, hashVal) {
    hashVal = numberHash(149417, hashVal);
    for (let i = 0, length = s.length; i < length; i++) {
        hashVal = numberHash(s.charCodeAt(i), hashVal);
    }
    return hashVal;
}
function arrayHash(arr, initialHashVal) {
    initialHashVal = numberHash(104579, initialHashVal);
    return arr.reduce((hashVal, item) => doHash(item, hashVal), initialHashVal);
}
function objectHash(obj, initialHashVal) {
    initialHashVal = numberHash(181387, initialHashVal);
    return Object.keys(obj).sort().reduce((hashVal, key) => {
        hashVal = stringHash(key, hashVal);
        return doHash(obj[key], hashVal);
    }, initialHashVal);
}
function hash_leftRotate(value, bits, totalBits = 32) {
    // delta + bits = totalBits
    const delta = totalBits - bits;
    // All ones, expect `delta` zeros aligned to the right
    const mask = ~((1 << delta) - 1);
    // Join (value left-shifted `bits` bits) with (masked value right-shifted `delta` bits)
    return ((value << bits) | ((mask & value) >>> delta)) >>> 0;
}
function fill(dest, index = 0, count = dest.byteLength, value = 0) {
    for (let i = 0; i < count; i++) {
        dest[index + i] = value;
    }
}
function leftPad(value, length, char = '0') {
    while (value.length < length) {
        value = char + value;
    }
    return value;
}
function toHexString(bufferOrValue, bitsize = 32) {
    if (bufferOrValue instanceof ArrayBuffer) {
        return Array.from(new Uint8Array(bufferOrValue)).map(b => b.toString(16).padStart(2, '0')).join('');
    }
    return leftPad((bufferOrValue >>> 0).toString(16), bitsize / 4);
}
/**
 * A SHA1 implementation that works with strings and does not allocate.
 */
class StringSHA1 {
    constructor() {
        this._h0 = 0x67452301;
        this._h1 = 0xEFCDAB89;
        this._h2 = 0x98BADCFE;
        this._h3 = 0x10325476;
        this._h4 = 0xC3D2E1F0;
        this._buff = new Uint8Array(64 /* SHA1Constant.BLOCK_SIZE */ + 3 /* to fit any utf-8 */);
        this._buffDV = new DataView(this._buff.buffer);
        this._buffLen = 0;
        this._totalLen = 0;
        this._leftoverHighSurrogate = 0;
        this._finished = false;
    }
    update(str) {
        const strLen = str.length;
        if (strLen === 0) {
            return;
        }
        const buff = this._buff;
        let buffLen = this._buffLen;
        let leftoverHighSurrogate = this._leftoverHighSurrogate;
        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 (isHighSurrogate(charCode)) {
                if (offset + 1 < strLen) {
                    const nextCharCode = str.charCodeAt(offset + 1);
                    if (isLowSurrogate(nextCharCode)) {
                        offset++;
                        codePoint = computeCodePoint(charCode, nextCharCode);
                    }
                    else {
                        // illegal => unicode replacement character
                        codePoint = 65533 /* SHA1Constant.UNICODE_REPLACEMENT */;
                    }
                }
                else {
                    // last character is a surrogate pair
                    leftoverHighSurrogate = charCode;
                    break;
                }
            }
            else if (isLowSurrogate(charCode)) {
                // illegal => unicode replacement character
                codePoint = 65533 /* SHA1Constant.UNICODE_REPLACEMENT */;
            }
            buffLen = this._push(buff, buffLen, codePoint);
            offset++;
            if (offset < strLen) {
                charCode = str.charCodeAt(offset);
            }
            else {
                break;
            }
        }
        this._buffLen = buffLen;
        this._leftoverHighSurrogate = leftoverHighSurrogate;
    }
    _push(buff, buffLen, codePoint) {
        if (codePoint < 0x0080) {
            buff[buffLen++] = codePoint;
        }
        else if (codePoint < 0x0800) {
            buff[buffLen++] = 0b11000000 | ((codePoint & 0b00000000000000000000011111000000) >>> 6);
            buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
        }
        else if (codePoint < 0x10000) {
            buff[buffLen++] = 0b11100000 | ((codePoint & 0b00000000000000001111000000000000) >>> 12);
            buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);
            buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
        }
        else {
            buff[buffLen++] = 0b11110000 | ((codePoint & 0b00000000000111000000000000000000) >>> 18);
            buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000111111000000000000) >>> 12);
            buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);
            buff[buffLen++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
        }
        if (buffLen >= 64 /* SHA1Constant.BLOCK_SIZE */) {
            this._step();
            buffLen -= 64 /* SHA1Constant.BLOCK_SIZE */;
            this._totalLen += 64 /* SHA1Constant.BLOCK_SIZE */;
            // take last 3 in case of UTF8 overflow
            buff[0] = buff[64 /* SHA1Constant.BLOCK_SIZE */ + 0];
            buff[1] = buff[64 /* SHA1Constant.BLOCK_SIZE */ + 1];
            buff[2] = buff[64 /* SHA1Constant.BLOCK_SIZE */ + 2];
        }
        return buffLen;
    }
    digest() {
        if (!this._finished) {
            this._finished = true;
            if (this._leftoverHighSurrogate) {
                // illegal => unicode replacement character
                this._leftoverHighSurrogate = 0;
                this._buffLen = this._push(this._buff, this._buffLen, 65533 /* SHA1Constant.UNICODE_REPLACEMENT */);
            }
            this._totalLen += this._buffLen;
            this._wrapUp();
        }
        return toHexString(this._h0) + toHexString(this._h1) + toHexString(this._h2) + toHexString(this._h3) + toHexString(this._h4);
    }
    _wrapUp() {
        this._buff[this._buffLen++] = 0x80;
        fill(this._buff, this._buffLen);
        if (this._buffLen > 56) {
            this._step();
            fill(this._buff);
        }
        // this will fit because the mantissa can cover up to 52 bits
        const ml = 8 * this._totalLen;
        this._buffDV.setUint32(56, Math.floor(ml / 4294967296), false);
        this._buffDV.setUint32(60, ml % 4294967296, false);
        this._step();
    }
    _step() {
        const bigBlock32 = StringSHA1._bigBlock32;
        const data = this._buffDV;
        for (let j = 0; j < 64 /* 16*4 */; j += 4) {
            bigBlock32.setUint32(j, data.getUint32(j, false), false);
        }
        for (let j = 64; j < 320 /* 80*4 */; j += 4) {
            bigBlock32.setUint32(j, hash_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._h0;
        let b = this._h1;
        let c = this._h2;
        let d = this._h3;
        let e = this._h4;
        let f, k;
        let temp;
        for (let j = 0; j < 80; j++) {
            if (j < 20) {
                f = (b & c) | ((~b) & d);
                k = 0x5A827999;
            }
            else if (j < 40) {
                f = b ^ c ^ d;
                k = 0x6ED9EBA1;
            }
            else if (j < 60) {
                f = (b & c) | (b & d) | (c & d);
                k = 0x8F1BBCDC;
            }
            else {
                f = b ^ c ^ d;
                k = 0xCA62C1D6;
            }
            temp = (hash_leftRotate(a, 5) + f + e + k + bigBlock32.getUint32(j * 4, false)) & 0xffffffff;
            e = d;
            d = c;
            c = hash_leftRotate(b, 30);
            b = a;
            a = temp;
        }
        this._h0 = (this._h0 + a) & 0xffffffff;
        this._h1 = (this._h1 + b) & 0xffffffff;
        this._h2 = (this._h2 + c) & 0xffffffff;
        this._h3 = (this._h3 + d) & 0xffffffff;
        this._h4 = (this._h4 + e) & 0xffffffff;
    }
}
StringSHA1._bigBlock32 = new DataView(new ArrayBuffer(320)); // 80 * 4 = 320

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/stableEditorScroll.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class StableEditorScrollState {
    constructor(_visiblePosition, _visiblePositionScrollDelta, _cursorPosition) {
        this._visiblePosition = _visiblePosition;
        this._visiblePositionScrollDelta = _visiblePositionScrollDelta;
        this._cursorPosition = _cursorPosition;
    }
    static capture(editor) {
        let visiblePosition = null;
        let visiblePositionScrollDelta = 0;
        if (editor.getScrollTop() !== 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 StableEditorScrollState(visiblePosition, visiblePositionScrollDelta, editor.getPosition());
    }
    restore(editor) {
        if (this._visiblePosition) {
            const visiblePositionScrollTop = editor.getTopForPosition(this._visiblePosition.lineNumber, this._visiblePosition.column);
            editor.setScrollTop(visiblePositionScrollTop + this._visiblePositionScrollDelta);
        }
    }
    restoreRelativeVerticalPositionOfCursor(editor) {
        const currentCursorPosition = editor.getPosition();
        if (!this._cursorPosition || !currentCursorPosition) {
            return;
        }
        const offset = editor.getTopForLineNumber(currentCursorPosition.lineNumber) - editor.getTopForLineNumber(this._cursorPosition.lineNumber);
        editor.setScrollTop(editor.getScrollTop() + offset);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codelens/browser/codelens.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var codelens_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};








class CodeLensModel {
    constructor() {
        this.lenses = [];
        this._disposables = new DisposableStore();
    }
    dispose() {
        this._disposables.dispose();
    }
    get isDisposed() {
        return this._disposables.isDisposed;
    }
    add(list, provider) {
        this._disposables.add(list);
        for (const symbol of list.lenses) {
            this.lenses.push({ symbol, provider });
        }
    }
}
function getCodeLensModel(registry, model, token) {
    return codelens_awaiter(this, void 0, void 0, function* () {
        const provider = registry.ordered(model);
        const providerRanks = new Map();
        const result = new CodeLensModel();
        const promises = provider.map((provider, i) => codelens_awaiter(this, void 0, void 0, function* () {
            providerRanks.set(provider, i);
            try {
                const list = yield Promise.resolve(provider.provideCodeLenses(model, token));
                if (list) {
                    result.add(list, provider);
                }
            }
            catch (err) {
                onUnexpectedExternalError(err);
            }
        }));
        yield Promise.all(promises);
        result.lenses = result.lenses.sort((a, b) => {
            // sort by lineNumber, provider-rank, and column
            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;
    });
}
CommandsRegistry.registerCommand('_executeCodeLensProvider', function (accessor, ...args) {
    let [uri, itemResolveCount] = args;
    assertType(URI.isUri(uri));
    assertType(typeof itemResolveCount === 'number' || !itemResolveCount);
    const { codeLensProvider } = accessor.get(ILanguageFeaturesService);
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
        throw illegalArgument();
    }
    const result = [];
    const disposables = new DisposableStore();
    return getCodeLensModel(codeLensProvider, model, CancellationToken.None).then(value => {
        disposables.add(value);
        const resolve = [];
        for (const item of value.lenses) {
            if (itemResolveCount === undefined || 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(() => {
        // make sure to return results, then (on next tick)
        // dispose the results
        setTimeout(() => disposables.dispose(), 100);
    });
});

;// ../../node_modules/monaco-editor/esm/vs/base/parts/storage/common/storage.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var storage_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};




var StorageState;
(function (StorageState) {
    StorageState[StorageState["None"] = 0] = "None";
    StorageState[StorageState["Initialized"] = 1] = "Initialized";
    StorageState[StorageState["Closed"] = 2] = "Closed";
})(StorageState || (StorageState = {}));
class Storage extends Disposable {
    constructor(database, options = Object.create(null)) {
        super();
        this.database = database;
        this.options = options;
        this._onDidChangeStorage = this._register(new Emitter());
        this.onDidChangeStorage = this._onDidChangeStorage.event;
        this.state = StorageState.None;
        this.cache = new Map();
        this.flushDelayer = new ThrottledDelayer(Storage.DEFAULT_FLUSH_DELAY);
        this.pendingDeletes = new Set();
        this.pendingInserts = new Map();
        this.whenFlushedCallbacks = [];
        this.registerListeners();
    }
    registerListeners() {
        this._register(this.database.onDidChangeItemsExternal(e => this.onDidChangeItemsExternal(e)));
    }
    onDidChangeItemsExternal(e) {
        var _a, _b;
        // items that change external require us to update our
        // caches with the values. we just accept the value and
        // emit an event if there is a change.
        (_a = e.changed) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => this.accept(key, value));
        (_b = e.deleted) === null || _b === void 0 ? void 0 : _b.forEach(key => this.accept(key, undefined));
    }
    accept(key, value) {
        if (this.state === StorageState.Closed) {
            return; // Return early if we are already closed
        }
        let changed = false;
        // Item got removed, check for deletion
        if (isUndefinedOrNull(value)) {
            changed = this.cache.delete(key);
        }
        // Item got updated, check for change
        else {
            const currentValue = this.cache.get(key);
            if (currentValue !== value) {
                this.cache.set(key, value);
                changed = true;
            }
        }
        // Signal to outside listeners
        if (changed) {
            this._onDidChangeStorage.fire(key);
        }
    }
    get(key, fallbackValue) {
        const value = this.cache.get(key);
        if (isUndefinedOrNull(value)) {
            return fallbackValue;
        }
        return value;
    }
    getBoolean(key, fallbackValue) {
        const value = this.get(key);
        if (isUndefinedOrNull(value)) {
            return fallbackValue;
        }
        return value === 'true';
    }
    getNumber(key, fallbackValue) {
        const value = this.get(key);
        if (isUndefinedOrNull(value)) {
            return fallbackValue;
        }
        return parseInt(value, 10);
    }
    set(key, value) {
        return storage_awaiter(this, void 0, void 0, function* () {
            if (this.state === StorageState.Closed) {
                return; // Return early if we are already closed
            }
            // We remove the key for undefined/null values
            if (isUndefinedOrNull(value)) {
                return this.delete(key);
            }
            // Otherwise, convert to String and store
            const valueStr = String(value);
            // Return early if value already set
            const currentValue = this.cache.get(key);
            if (currentValue === valueStr) {
                return;
            }
            // Update in cache and pending
            this.cache.set(key, valueStr);
            this.pendingInserts.set(key, valueStr);
            this.pendingDeletes.delete(key);
            // Event
            this._onDidChangeStorage.fire(key);
            // Accumulate work by scheduling after timeout
            return this.doFlush();
        });
    }
    delete(key) {
        return storage_awaiter(this, void 0, void 0, function* () {
            if (this.state === StorageState.Closed) {
                return; // Return early if we are already closed
            }
            // Remove from cache and add to pending
            const wasDeleted = this.cache.delete(key);
            if (!wasDeleted) {
                return; // Return early if value already deleted
            }
            if (!this.pendingDeletes.has(key)) {
                this.pendingDeletes.add(key);
            }
            this.pendingInserts.delete(key);
            // Event
            this._onDidChangeStorage.fire(key);
            // Accumulate work by scheduling after timeout
            return this.doFlush();
        });
    }
    get hasPending() {
        return this.pendingInserts.size > 0 || this.pendingDeletes.size > 0;
    }
    flushPending() {
        return storage_awaiter(this, void 0, void 0, function* () {
            if (!this.hasPending) {
                return; // return early if nothing to do
            }
            // Get pending data
            const updateRequest = { insert: this.pendingInserts, delete: this.pendingDeletes };
            // Reset pending data for next run
            this.pendingDeletes = new Set();
            this.pendingInserts = new Map();
            // Update in storage and release any
            // waiters we have once done
            return this.database.updateItems(updateRequest).finally(() => {
                var _a;
                if (!this.hasPending) {
                    while (this.whenFlushedCallbacks.length) {
                        (_a = this.whenFlushedCallbacks.pop()) === null || _a === void 0 ? void 0 : _a();
                    }
                }
            });
        });
    }
    doFlush(delay) {
        return storage_awaiter(this, void 0, void 0, function* () {
            return this.flushDelayer.trigger(() => this.flushPending(), delay);
        });
    }
    dispose() {
        this.flushDelayer.dispose();
        super.dispose();
    }
}
Storage.DEFAULT_FLUSH_DELAY = 100;
class InMemoryStorageDatabase {
    constructor() {
        this.onDidChangeItemsExternal = Event.None;
        this.items = new Map();
    }
    updateItems(request) {
        var _a, _b;
        return storage_awaiter(this, void 0, void 0, function* () {
            (_a = request.insert) === null || _a === void 0 ? void 0 : _a.forEach((value, key) => this.items.set(key, value));
            (_b = request.delete) === null || _b === void 0 ? void 0 : _b.forEach(key => this.items.delete(key));
        });
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/storage/common/storage.js





const TARGET_KEY = '__$__targetStorageMarker';
const IStorageService = createDecorator('storageService');
var WillSaveStateReason;
(function (WillSaveStateReason) {
    /**
     * No specific reason to save state.
     */
    WillSaveStateReason[WillSaveStateReason["NONE"] = 0] = "NONE";
    /**
     * A hint that the workbench is about to shutdown.
     */
    WillSaveStateReason[WillSaveStateReason["SHUTDOWN"] = 1] = "SHUTDOWN";
})(WillSaveStateReason || (WillSaveStateReason = {}));
class AbstractStorageService extends Disposable {
    constructor(options = { flushInterval: AbstractStorageService.DEFAULT_FLUSH_INTERVAL }) {
        super();
        this.options = options;
        this._onDidChangeValue = this._register(new PauseableEmitter());
        this.onDidChangeValue = this._onDidChangeValue.event;
        this._onDidChangeTarget = this._register(new PauseableEmitter());
        this._onWillSaveState = this._register(new Emitter());
        this.onWillSaveState = this._onWillSaveState.event;
        this._workspaceKeyTargets = undefined;
        this._profileKeyTargets = undefined;
        this._applicationKeyTargets = undefined;
    }
    emitDidChangeValue(scope, key) {
        // Specially handle `TARGET_KEY`
        if (key === TARGET_KEY) {
            // Clear our cached version which is now out of date
            switch (scope) {
                case -1 /* StorageScope.APPLICATION */:
                    this._applicationKeyTargets = undefined;
                    break;
                case 0 /* StorageScope.PROFILE */:
                    this._profileKeyTargets = undefined;
                    break;
                case 1 /* StorageScope.WORKSPACE */:
                    this._workspaceKeyTargets = undefined;
                    break;
            }
            // Emit as `didChangeTarget` event
            this._onDidChangeTarget.fire({ scope });
        }
        // Emit any other key to outside
        else {
            this._onDidChangeValue.fire({ scope, key, target: this.getKeyTargets(scope)[key] });
        }
    }
    get(key, scope, fallbackValue) {
        var _a;
        return (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.get(key, fallbackValue);
    }
    getBoolean(key, scope, fallbackValue) {
        var _a;
        return (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.getBoolean(key, fallbackValue);
    }
    getNumber(key, scope, fallbackValue) {
        var _a;
        return (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.getNumber(key, fallbackValue);
    }
    store(key, value, scope, target) {
        // We remove the key for undefined/null values
        if (isUndefinedOrNull(value)) {
            this.remove(key, scope);
            return;
        }
        // Update our datastructures but send events only after
        this.withPausedEmitters(() => {
            var _a;
            // Update key-target map
            this.updateKeyTarget(key, scope, target);
            // Store actual value
            (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.set(key, value);
        });
    }
    remove(key, scope) {
        // Update our datastructures but send events only after
        this.withPausedEmitters(() => {
            var _a;
            // Update key-target map
            this.updateKeyTarget(key, scope, undefined);
            // Remove actual key
            (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.delete(key);
        });
    }
    withPausedEmitters(fn) {
        // Pause emitters
        this._onDidChangeValue.pause();
        this._onDidChangeTarget.pause();
        try {
            fn();
        }
        finally {
            // Resume emitters
            this._onDidChangeValue.resume();
            this._onDidChangeTarget.resume();
        }
    }
    updateKeyTarget(key, scope, target) {
        var _a, _b;
        // Add
        const keyTargets = this.getKeyTargets(scope);
        if (typeof target === 'number') {
            if (keyTargets[key] !== target) {
                keyTargets[key] = target;
                (_a = this.getStorage(scope)) === null || _a === void 0 ? void 0 : _a.set(TARGET_KEY, JSON.stringify(keyTargets));
            }
        }
        // Remove
        else {
            if (typeof keyTargets[key] === 'number') {
                delete keyTargets[key];
                (_b = this.getStorage(scope)) === null || _b === void 0 ? void 0 : _b.set(TARGET_KEY, JSON.stringify(keyTargets));
            }
        }
    }
    get workspaceKeyTargets() {
        if (!this._workspaceKeyTargets) {
            this._workspaceKeyTargets = this.loadKeyTargets(1 /* StorageScope.WORKSPACE */);
        }
        return this._workspaceKeyTargets;
    }
    get profileKeyTargets() {
        if (!this._profileKeyTargets) {
            this._profileKeyTargets = this.loadKeyTargets(0 /* StorageScope.PROFILE */);
        }
        return this._profileKeyTargets;
    }
    get applicationKeyTargets() {
        if (!this._applicationKeyTargets) {
            this._applicationKeyTargets = this.loadKeyTargets(-1 /* StorageScope.APPLICATION */);
        }
        return this._applicationKeyTargets;
    }
    getKeyTargets(scope) {
        switch (scope) {
            case -1 /* StorageScope.APPLICATION */:
                return this.applicationKeyTargets;
            case 0 /* StorageScope.PROFILE */:
                return this.profileKeyTargets;
            default:
                return this.workspaceKeyTargets;
        }
    }
    loadKeyTargets(scope) {
        const keysRaw = this.get(TARGET_KEY, scope);
        if (keysRaw) {
            try {
                return JSON.parse(keysRaw);
            }
            catch (error) {
                // Fail gracefully
            }
        }
        return Object.create(null);
    }
}
AbstractStorageService.DEFAULT_FLUSH_INTERVAL = 60 * 1000; // every minute
class InMemoryStorageService extends AbstractStorageService {
    constructor() {
        super();
        this.applicationStorage = this._register(new Storage(new InMemoryStorageDatabase()));
        this.profileStorage = this._register(new Storage(new InMemoryStorageDatabase()));
        this.workspaceStorage = this._register(new Storage(new InMemoryStorageDatabase()));
        this._register(this.workspaceStorage.onDidChangeStorage(key => this.emitDidChangeValue(1 /* StorageScope.WORKSPACE */, key)));
        this._register(this.profileStorage.onDidChangeStorage(key => this.emitDidChangeValue(0 /* StorageScope.PROFILE */, key)));
        this._register(this.applicationStorage.onDidChangeStorage(key => this.emitDidChangeValue(-1 /* StorageScope.APPLICATION */, key)));
    }
    getStorage(scope) {
        switch (scope) {
            case -1 /* StorageScope.APPLICATION */:
                return this.applicationStorage;
            case 0 /* StorageScope.PROFILE */:
                return this.profileStorage;
            default:
                return this.workspaceStorage;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codelens/browser/codeLensCache.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var codeLensCache_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var codeLensCache_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};








const ICodeLensCache = createDecorator('ICodeLensCache');
class CacheItem {
    constructor(lineCount, data) {
        this.lineCount = lineCount;
        this.data = data;
    }
}
let CodeLensCache = class CodeLensCache {
    constructor(storageService) {
        this._fakeProvider = new class {
            provideCodeLenses() {
                throw new Error('not supported');
            }
        };
        this._cache = new LRUCache(20, 0.75);
        // remove old data
        const oldkey = 'codelens/cache';
        runWhenIdle(() => storageService.remove(oldkey, 1 /* StorageScope.WORKSPACE */));
        // restore lens data on start
        const key = 'codelens/cache2';
        const raw = storageService.get(key, 1 /* StorageScope.WORKSPACE */, '{}');
        this._deserialize(raw);
        // store lens data on shutdown
        once(storageService.onWillSaveState)(e => {
            if (e.reason === WillSaveStateReason.SHUTDOWN) {
                storageService.store(key, this._serialize(), 1 /* StorageScope.WORKSPACE */, 1 /* StorageTarget.MACHINE */);
            }
        });
    }
    put(model, data) {
        // create a copy of the model that is without command-ids
        // but with comand-labels
        const copyItems = data.lenses.map(item => {
            var _a;
            return {
                range: item.symbol.range,
                command: item.symbol.command && { id: '', title: (_a = item.symbol.command) === null || _a === void 0 ? void 0 : _a.title },
            };
        });
        const copyModel = new CodeLensModel();
        copyModel.add({ lenses: copyItems, dispose: () => { } }, this._fakeProvider);
        const item = new CacheItem(model.getLineCount(), copyModel);
        this._cache.set(model.uri.toString(), item);
    }
    get(model) {
        const item = this._cache.get(model.uri.toString());
        return item && item.lineCount === model.getLineCount() ? item.data : undefined;
    }
    delete(model) {
        this._cache.delete(model.uri.toString());
    }
    // --- persistence
    _serialize() {
        const data = Object.create(null);
        for (const [key, value] of this._cache) {
            const lines = new Set();
            for (const d of value.data.lenses) {
                lines.add(d.symbol.range.startLineNumber);
            }
            data[key] = {
                lineCount: value.lineCount,
                lines: [...lines.values()]
            };
        }
        return JSON.stringify(data);
    }
    _deserialize(raw) {
        try {
            const data = JSON.parse(raw);
            for (const key in data) {
                const element = data[key];
                const lenses = [];
                for (const line of element.lines) {
                    lenses.push({ range: new Range(line, 1, line, 11) });
                }
                const model = new CodeLensModel();
                model.add({ lenses, dispose() { } }, this._fakeProvider);
                this._cache.set(key, new CacheItem(element.lineCount, model));
            }
        }
        catch (_a) {
            // ignore...
        }
    }
};
CodeLensCache = codeLensCache_decorate([
    codeLensCache_param(0, IStorageService)
], CodeLensCache);

registerSingleton(ICodeLensCache, CodeLensCache);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/iconLabel/iconLabels.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


const labelWithIconsRegex = new RegExp(`(\\\\)?\\$\\((${CSSIcon.iconNameExpression}(?:${CSSIcon.iconModifierExpression})?)\\)`, 'g');
function renderLabelWithIcons(text) {
    const elements = new Array();
    let match;
    let textStart = 0, textStop = 0;
    while ((match = labelWithIconsRegex.exec(text)) !== null) {
        textStop = match.index || 0;
        elements.push(text.substring(textStart, textStop));
        textStart = (match.index || 0) + match[0].length;
        const [, escaped, codicon] = match;
        elements.push(escaped ? `$(${codicon})` : renderIcon({ id: codicon }));
    }
    if (textStart < text.length) {
        elements.push(text.substring(textStart));
    }
    return elements;
}
function renderIcon(icon) {
    const node = dom_$(`span`);
    node.classList.add(...CSSIcon.asClassNameArray(icon));
    return node;
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/codelens/browser/codelensWidget.css
var codelensWidget = __webpack_require__(46172);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codelens/browser/codelensWidget.css

      
      
      
      
      
      
      
      
      

var codelensWidget_options = {};

codelensWidget_options.styleTagTransform = (styleTagTransform_default());
codelensWidget_options.setAttributes = (setAttributesWithoutAttributes_default());

      codelensWidget_options.insert = insertBySelector_default().bind(null, "head");
    
codelensWidget_options.domAPI = (styleDomAPI_default());
codelensWidget_options.insertStyleElement = (insertStyleElement_default());

var codelensWidget_update = injectStylesIntoStyleTag_default()(codelensWidget/* default */.A, codelensWidget_options);




       /* harmony default export */ const browser_codelensWidget = (codelensWidget/* default */.A && codelensWidget/* default */.A.locals ? codelensWidget/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codelens/browser/codelensWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class CodeLensViewZone {
    constructor(afterLineNumber, heightInPx, onHeight) {
        /**
         * We want that this view zone, which reserves space for a code lens appears
         * as close as possible to the next line, so we use a very large value here.
         */
        this.afterColumn = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
        this.afterLineNumber = afterLineNumber;
        this.heightInPx = heightInPx;
        this._onHeight = onHeight;
        this.suppressMouseDown = true;
        this.domNode = document.createElement('div');
    }
    onComputedHeight(height) {
        if (this._lastHeight === undefined) {
            this._lastHeight = height;
        }
        else if (this._lastHeight !== height) {
            this._lastHeight = height;
            this._onHeight();
        }
    }
    isVisible() {
        return this._lastHeight !== 0
            && this.domNode.hasAttribute('monaco-visible-view-zone');
    }
}
class CodeLensContentWidget {
    constructor(editor, className, line) {
        // Editor.IContentWidget.allowEditorOverflow
        this.allowEditorOverflow = false;
        this.suppressMouseDown = true;
        this._commands = new Map();
        this._isEmpty = true;
        this._editor = editor;
        this._id = `codelens.widget-${(CodeLensContentWidget._idPool++)}`;
        this.updatePosition(line);
        this._domNode = document.createElement('span');
        this._domNode.className = `codelens-decoration ${className}`;
    }
    withCommands(lenses, animate) {
        this._commands.clear();
        const children = [];
        let hasSymbol = false;
        for (let i = 0; i < lenses.length; i++) {
            const lens = lenses[i];
            if (!lens) {
                continue;
            }
            hasSymbol = true;
            if (lens.command) {
                const title = renderLabelWithIcons(lens.command.title.trim());
                if (lens.command.id) {
                    children.push(dom_$('a', { id: String(i), title: lens.command.tooltip, role: 'button' }, ...title));
                    this._commands.set(String(i), lens.command);
                }
                else {
                    children.push(dom_$('span', { title: lens.command.tooltip }, ...title));
                }
                if (i + 1 < lenses.length) {
                    children.push(dom_$('span', undefined, '\u00a0|\u00a0'));
                }
            }
        }
        if (!hasSymbol) {
            // symbols but no commands
            dom_reset(this._domNode, dom_$('span', undefined, 'no commands'));
        }
        else {
            // symbols and commands
            dom_reset(this._domNode, ...children);
            if (this._isEmpty && animate) {
                this._domNode.classList.add('fadein');
            }
            this._isEmpty = false;
        }
    }
    getCommand(link) {
        return link.parentElement === this._domNode
            ? this._commands.get(link.id)
            : undefined;
    }
    getId() {
        return this._id;
    }
    getDomNode() {
        return this._domNode;
    }
    updatePosition(line) {
        const column = this._editor.getModel().getLineFirstNonWhitespaceColumn(line);
        this._widgetPosition = {
            position: { lineNumber: line, column: column },
            preference: [1 /* ContentWidgetPositionPreference.ABOVE */]
        };
    }
    getPosition() {
        return this._widgetPosition || null;
    }
}
CodeLensContentWidget._idPool = 0;
class CodeLensHelper {
    constructor() {
        this._removeDecorations = [];
        this._addDecorations = [];
        this._addDecorationsCallbacks = [];
    }
    addDecoration(decoration, callback) {
        this._addDecorations.push(decoration);
        this._addDecorationsCallbacks.push(callback);
    }
    removeDecoration(decorationId) {
        this._removeDecorations.push(decorationId);
    }
    commit(changeAccessor) {
        const resultingDecorations = changeAccessor.deltaDecorations(this._removeDecorations, this._addDecorations);
        for (let i = 0, len = resultingDecorations.length; i < len; i++) {
            this._addDecorationsCallbacks[i](resultingDecorations[i]);
        }
    }
}
class CodeLensWidget {
    constructor(data, editor, className, helper, viewZoneChangeAccessor, heightInPx, updateCallback) {
        this._isDisposed = false;
        this._editor = editor;
        this._className = className;
        this._data = data;
        // create combined range, track all ranges with decorations,
        // check if there is already something to render
        this._decorationIds = [];
        let range;
        const lenses = [];
        this._data.forEach((codeLensData, i) => {
            if (codeLensData.symbol.command) {
                lenses.push(codeLensData.symbol);
            }
            helper.addDecoration({
                range: codeLensData.symbol.range,
                options: ModelDecorationOptions.EMPTY
            }, id => this._decorationIds[i] = id);
            // the range contains all lenses on this line
            if (!range) {
                range = Range.lift(codeLensData.symbol.range);
            }
            else {
                range = Range.plusRange(range, codeLensData.symbol.range);
            }
        });
        this._viewZone = new CodeLensViewZone(range.startLineNumber - 1, heightInPx, updateCallback);
        this._viewZoneId = viewZoneChangeAccessor.addZone(this._viewZone);
        if (lenses.length > 0) {
            this._createContentWidgetIfNecessary();
            this._contentWidget.withCommands(lenses, false);
        }
    }
    _createContentWidgetIfNecessary() {
        if (!this._contentWidget) {
            this._contentWidget = new CodeLensContentWidget(this._editor, this._className, this._viewZone.afterLineNumber + 1);
            this._editor.addContentWidget(this._contentWidget);
        }
        else {
            this._editor.layoutContentWidget(this._contentWidget);
        }
    }
    dispose(helper, viewZoneChangeAccessor) {
        this._decorationIds.forEach(helper.removeDecoration, helper);
        this._decorationIds = [];
        viewZoneChangeAccessor === null || viewZoneChangeAccessor === void 0 ? void 0 : viewZoneChangeAccessor.removeZone(this._viewZoneId);
        if (this._contentWidget) {
            this._editor.removeContentWidget(this._contentWidget);
            this._contentWidget = undefined;
        }
        this._isDisposed = true;
    }
    isDisposed() {
        return this._isDisposed;
    }
    isValid() {
        return this._decorationIds.some((id, i) => {
            const range = this._editor.getModel().getDecorationRange(id);
            const symbol = this._data[i].symbol;
            return !!(range && Range.isEmpty(symbol.range) === range.isEmpty());
        });
    }
    updateCodeLensSymbols(data, helper) {
        this._decorationIds.forEach(helper.removeDecoration, helper);
        this._decorationIds = [];
        this._data = data;
        this._data.forEach((codeLensData, i) => {
            helper.addDecoration({
                range: codeLensData.symbol.range,
                options: ModelDecorationOptions.EMPTY
            }, id => this._decorationIds[i] = id);
        });
    }
    updateHeight(height, viewZoneChangeAccessor) {
        this._viewZone.heightInPx = height;
        viewZoneChangeAccessor.layoutZone(this._viewZoneId);
        if (this._contentWidget) {
            this._editor.layoutContentWidget(this._contentWidget);
        }
    }
    computeIfNecessary(model) {
        if (!this._viewZone.isVisible()) {
            return null;
        }
        // Read editor current state
        for (let i = 0; i < this._decorationIds.length; i++) {
            const range = model.getDecorationRange(this._decorationIds[i]);
            if (range) {
                this._data[i].symbol.range = range;
            }
        }
        return this._data;
    }
    updateCommands(symbols) {
        this._createContentWidgetIfNecessary();
        this._contentWidget.withCommands(symbols, true);
        for (let i = 0; i < this._data.length; i++) {
            const resolved = symbols[i];
            if (resolved) {
                const { symbol } = this._data[i];
                symbol.command = resolved.command || symbol.command;
            }
        }
    }
    getCommand(link) {
        var _a;
        return (_a = this._contentWidget) === null || _a === void 0 ? void 0 : _a.getCommand(link);
    }
    getLineNumber() {
        const range = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
        if (range) {
            return range.startLineNumber;
        }
        return -1;
    }
    update(viewZoneChangeAccessor) {
        if (this.isValid()) {
            const range = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
            if (range) {
                this._viewZone.afterLineNumber = range.startLineNumber - 1;
                viewZoneChangeAccessor.layoutZone(this._viewZoneId);
                if (this._contentWidget) {
                    this._contentWidget.updatePosition(range.startLineNumber);
                    this._editor.layoutContentWidget(this._contentWidget);
                }
            }
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/parts/quickinput/common/quickInput.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
const NO_KEY_MODS = { ctrlCmd: false, alt: false };
var QuickInputHideReason;
(function (QuickInputHideReason) {
    /**
     * Focus moved away from the quick input.
     */
    QuickInputHideReason[QuickInputHideReason["Blur"] = 1] = "Blur";
    /**
     * An explicit user gesture, e.g. pressing Escape key.
     */
    QuickInputHideReason[QuickInputHideReason["Gesture"] = 2] = "Gesture";
    /**
     * Anything else.
     */
    QuickInputHideReason[QuickInputHideReason["Other"] = 3] = "Other";
})(QuickInputHideReason || (QuickInputHideReason = {}));
var ItemActivation;
(function (ItemActivation) {
    ItemActivation[ItemActivation["NONE"] = 0] = "NONE";
    ItemActivation[ItemActivation["FIRST"] = 1] = "FIRST";
    ItemActivation[ItemActivation["SECOND"] = 2] = "SECOND";
    ItemActivation[ItemActivation["LAST"] = 3] = "LAST";
})(ItemActivation || (ItemActivation = {}));
class QuickPickItemScorerAccessor {
    constructor(options) {
        this.options = options;
    }
}
const quickPickItemScorerAccessor = new QuickPickItemScorerAccessor();
//#endregion

;// ../../node_modules/monaco-editor/esm/vs/platform/quickinput/common/quickInput.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


const IQuickInputService = createDecorator('quickInputService');

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/languageFeatureDebounce.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var languageFeatureDebounce_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var languageFeatureDebounce_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};







const ILanguageFeatureDebounceService = createDecorator('ILanguageFeatureDebounceService');
var IdentityHash;
(function (IdentityHash) {
    const _hashes = new WeakMap();
    let pool = 0;
    function of(obj) {
        let value = _hashes.get(obj);
        if (value === undefined) {
            value = ++pool;
            _hashes.set(obj, value);
        }
        return value;
    }
    IdentityHash.of = of;
})(IdentityHash || (IdentityHash = {}));
class FeatureDebounceInformation {
    constructor(_logService, _name, _registry, _default, _min, _max) {
        this._logService = _logService;
        this._name = _name;
        this._registry = _registry;
        this._default = _default;
        this._min = _min;
        this._max = _max;
        this._cache = new LRUCache(50, 0.7);
    }
    _key(model) {
        return model.id + this._registry.all(model).reduce((hashVal, obj) => doHash(IdentityHash.of(obj), hashVal), 0);
    }
    get(model) {
        const key = this._key(model);
        const avg = this._cache.get(key);
        return avg
            ? clamp(avg.value, this._min, this._max)
            : this.default();
    }
    update(model, value) {
        const key = this._key(model);
        let avg = this._cache.get(key);
        if (!avg) {
            avg = new SlidingWindowAverage(6);
            this._cache.set(key, avg);
        }
        const newValue = clamp(avg.update(value), this._min, this._max);
        if (!matchesScheme(model.uri, 'output')) {
            this._logService.trace(`[DEBOUNCE: ${this._name}] for ${model.uri.toString()} is ${newValue}ms`);
        }
        return newValue;
    }
    _overall() {
        const result = new MovingAverage();
        for (const [, avg] of this._cache) {
            result.update(avg.value);
        }
        return result.value;
    }
    default() {
        const value = (this._overall() | 0) || this._default;
        return clamp(value, this._min, this._max);
    }
}
let LanguageFeatureDebounceService = class LanguageFeatureDebounceService {
    constructor(_logService) {
        this._logService = _logService;
        this._data = new Map();
    }
    for(feature, name, config) {
        var _a, _b, _c;
        const min = (_a = config === null || config === void 0 ? void 0 : config.min) !== null && _a !== void 0 ? _a : 50;
        const max = (_b = config === null || config === void 0 ? void 0 : config.max) !== null && _b !== void 0 ? _b : Math.pow(min, 2);
        const extra = (_c = config === null || config === void 0 ? void 0 : config.key) !== null && _c !== void 0 ? _c : undefined;
        const key = `${IdentityHash.of(feature)},${min}${extra ? ',' + extra : ''}`;
        let info = this._data.get(key);
        if (!info) {
            info = new FeatureDebounceInformation(this._logService, name, feature, (this._overallAverage() | 0) || (min * 1.5), // default is overall default or derived from min-value
            min, max);
            this._data.set(key, info);
        }
        return info;
    }
    _overallAverage() {
        // Average of all language features. Not a great value but an approximation
        const result = new MovingAverage();
        for (const info of this._data.values()) {
            result.update(info.default());
        }
        return result.value;
    }
};
LanguageFeatureDebounceService = languageFeatureDebounce_decorate([
    languageFeatureDebounce_param(0, ILogService)
], LanguageFeatureDebounceService);

registerSingleton(ILanguageFeatureDebounceService, LanguageFeatureDebounceService, true);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/codelens/browser/codelensController.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var codelensController_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var codelensController_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var codelensController_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};


















let CodeLensContribution = class CodeLensContribution {
    constructor(_editor, _languageFeaturesService, debounceService, _commandService, _notificationService, _codeLensCache) {
        this._editor = _editor;
        this._languageFeaturesService = _languageFeaturesService;
        this._commandService = _commandService;
        this._notificationService = _notificationService;
        this._codeLensCache = _codeLensCache;
        this._disposables = new DisposableStore();
        this._localToDispose = new DisposableStore();
        this._lenses = [];
        this._oldCodeLensModels = new DisposableStore();
        this._provideCodeLensDebounce = debounceService.for(_languageFeaturesService.codeLensProvider, 'CodeLensProvide', { min: 250 });
        this._resolveCodeLensesDebounce = debounceService.for(_languageFeaturesService.codeLensProvider, 'CodeLensResolve', { min: 250, salt: 'resolve' });
        this._resolveCodeLensesScheduler = new RunOnceScheduler(() => this._resolveCodeLensesInViewport(), this._resolveCodeLensesDebounce.default());
        this._disposables.add(this._editor.onDidChangeModel(() => this._onModelChange()));
        this._disposables.add(this._editor.onDidChangeModelLanguage(() => this._onModelChange()));
        this._disposables.add(this._editor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(46 /* EditorOption.fontInfo */) || e.hasChanged(16 /* EditorOption.codeLensFontSize */) || e.hasChanged(15 /* EditorOption.codeLensFontFamily */)) {
                this._updateLensStyle();
            }
            if (e.hasChanged(14 /* EditorOption.codeLens */)) {
                this._onModelChange();
            }
        }));
        this._disposables.add(_languageFeaturesService.codeLensProvider.onDidChange(this._onModelChange, this));
        this._onModelChange();
        this._styleClassName = '_' + hash(this._editor.getId()).toString(16);
        this._styleElement = createStyleSheet(isInShadowDOM(this._editor.getContainerDomNode())
            ? this._editor.getContainerDomNode()
            : undefined);
        this._updateLensStyle();
    }
    dispose() {
        var _a;
        this._localDispose();
        this._disposables.dispose();
        this._oldCodeLensModels.dispose();
        (_a = this._currentCodeLensModel) === null || _a === void 0 ? void 0 : _a.dispose();
        this._styleElement.remove();
    }
    _getLayoutInfo() {
        const lineHeightFactor = Math.max(1.3, this._editor.getOption(61 /* EditorOption.lineHeight */) / this._editor.getOption(48 /* EditorOption.fontSize */));
        let fontSize = this._editor.getOption(16 /* EditorOption.codeLensFontSize */);
        if (!fontSize || fontSize < 5) {
            fontSize = (this._editor.getOption(48 /* EditorOption.fontSize */) * .9) | 0;
        }
        return {
            fontSize,
            codeLensHeight: (fontSize * lineHeightFactor) | 0,
        };
    }
    _updateLensStyle() {
        const { codeLensHeight, fontSize } = this._getLayoutInfo();
        const fontFamily = this._editor.getOption(15 /* EditorOption.codeLensFontFamily */);
        const editorFontInfo = this._editor.getOption(46 /* EditorOption.fontInfo */);
        const fontFamilyVar = `--codelens-font-family${this._styleClassName}`;
        const fontFeaturesVar = `--codelens-font-features${this._styleClassName}`;
        let newStyle = `
		.monaco-editor .codelens-decoration.${this._styleClassName} { line-height: ${codeLensHeight}px; font-size: ${fontSize}px; padding-right: ${Math.round(fontSize * 0.5)}px; font-feature-settings: var(${fontFeaturesVar}) }
		.monaco-editor .codelens-decoration.${this._styleClassName} span.codicon { line-height: ${codeLensHeight}px; font-size: ${fontSize}px; }
		`;
        if (fontFamily) {
            newStyle += `.monaco-editor .codelens-decoration.${this._styleClassName} { font-family: var(${fontFamilyVar}), ${EDITOR_FONT_DEFAULTS.fontFamily}}`;
        }
        this._styleElement.textContent = newStyle;
        this._editor.getContainerDomNode().style.setProperty(fontFamilyVar, fontFamily !== null && fontFamily !== void 0 ? fontFamily : 'inherit');
        this._editor.getContainerDomNode().style.setProperty(fontFeaturesVar, editorFontInfo.fontFeatureSettings);
        //
        this._editor.changeViewZones(accessor => {
            for (const lens of this._lenses) {
                lens.updateHeight(codeLensHeight, accessor);
            }
        });
    }
    _localDispose() {
        var _a, _b, _c;
        (_a = this._getCodeLensModelPromise) === null || _a === void 0 ? void 0 : _a.cancel();
        this._getCodeLensModelPromise = undefined;
        (_b = this._resolveCodeLensesPromise) === null || _b === void 0 ? void 0 : _b.cancel();
        this._resolveCodeLensesPromise = undefined;
        this._localToDispose.clear();
        this._oldCodeLensModels.clear();
        (_c = this._currentCodeLensModel) === null || _c === void 0 ? void 0 : _c.dispose();
    }
    _onModelChange() {
        this._localDispose();
        const model = this._editor.getModel();
        if (!model) {
            return;
        }
        if (!this._editor.getOption(14 /* EditorOption.codeLens */)) {
            return;
        }
        const cachedLenses = this._codeLensCache.get(model);
        if (cachedLenses) {
            this._renderCodeLensSymbols(cachedLenses);
        }
        if (!this._languageFeaturesService.codeLensProvider.has(model)) {
            // no provider -> return but check with
            // cached lenses. they expire after 30 seconds
            if (cachedLenses) {
                this._localToDispose.add(disposableTimeout(() => {
                    const cachedLensesNow = this._codeLensCache.get(model);
                    if (cachedLenses === cachedLensesNow) {
                        this._codeLensCache.delete(model);
                        this._onModelChange();
                    }
                }, 30 * 1000));
            }
            return;
        }
        for (const provider of this._languageFeaturesService.codeLensProvider.all(model)) {
            if (typeof provider.onDidChange === 'function') {
                const registration = provider.onDidChange(() => scheduler.schedule());
                this._localToDispose.add(registration);
            }
        }
        const scheduler = new RunOnceScheduler(() => {
            var _a;
            const t1 = Date.now();
            (_a = this._getCodeLensModelPromise) === null || _a === void 0 ? void 0 : _a.cancel();
            this._getCodeLensModelPromise = createCancelablePromise(token => getCodeLensModel(this._languageFeaturesService.codeLensProvider, model, token));
            this._getCodeLensModelPromise.then(result => {
                if (this._currentCodeLensModel) {
                    this._oldCodeLensModels.add(this._currentCodeLensModel);
                }
                this._currentCodeLensModel = result;
                // cache model to reduce flicker
                this._codeLensCache.put(model, result);
                // update moving average
                const newDelay = this._provideCodeLensDebounce.update(model, Date.now() - t1);
                scheduler.delay = newDelay;
                // render lenses
                this._renderCodeLensSymbols(result);
                // dom.scheduleAtNextAnimationFrame(() => this._resolveCodeLensesInViewport());
                this._resolveCodeLensesInViewportSoon();
            }, onUnexpectedError);
        }, this._provideCodeLensDebounce.get(model));
        this._localToDispose.add(scheduler);
        this._localToDispose.add(toDisposable(() => this._resolveCodeLensesScheduler.cancel()));
        this._localToDispose.add(this._editor.onDidChangeModelContent(() => {
            this._editor.changeDecorations(decorationsAccessor => {
                this._editor.changeViewZones(viewZonesAccessor => {
                    const toDispose = [];
                    let lastLensLineNumber = -1;
                    this._lenses.forEach((lens) => {
                        if (!lens.isValid() || lastLensLineNumber === lens.getLineNumber()) {
                            // invalid -> lens collapsed, attach range doesn't exist anymore
                            // line_number -> lenses should never be on the same line
                            toDispose.push(lens);
                        }
                        else {
                            lens.update(viewZonesAccessor);
                            lastLensLineNumber = lens.getLineNumber();
                        }
                    });
                    const helper = new CodeLensHelper();
                    toDispose.forEach((l) => {
                        l.dispose(helper, viewZonesAccessor);
                        this._lenses.splice(this._lenses.indexOf(l), 1);
                    });
                    helper.commit(decorationsAccessor);
                });
            });
            // Ask for all references again
            scheduler.schedule();
        }));
        this._localToDispose.add(this._editor.onDidFocusEditorWidget(() => {
            scheduler.schedule();
        }));
        this._localToDispose.add(this._editor.onDidScrollChange(e => {
            if (e.scrollTopChanged && this._lenses.length > 0) {
                this._resolveCodeLensesInViewportSoon();
            }
        }));
        this._localToDispose.add(this._editor.onDidLayoutChange(() => {
            this._resolveCodeLensesInViewportSoon();
        }));
        this._localToDispose.add(toDisposable(() => {
            if (this._editor.getModel()) {
                const scrollState = StableEditorScrollState.capture(this._editor);
                this._editor.changeDecorations(decorationsAccessor => {
                    this._editor.changeViewZones(viewZonesAccessor => {
                        this._disposeAllLenses(decorationsAccessor, viewZonesAccessor);
                    });
                });
                scrollState.restore(this._editor);
            }
            else {
                // No accessors available
                this._disposeAllLenses(undefined, undefined);
            }
        }));
        this._localToDispose.add(this._editor.onMouseDown(e => {
            if (e.target.type !== 9 /* MouseTargetType.CONTENT_WIDGET */) {
                return;
            }
            let target = e.target.element;
            if ((target === null || target === void 0 ? void 0 : target.tagName) === 'SPAN') {
                target = target.parentElement;
            }
            if ((target === null || target === void 0 ? void 0 : target.tagName) === 'A') {
                for (const lens of this._lenses) {
                    const command = lens.getCommand(target);
                    if (command) {
                        this._commandService.executeCommand(command.id, ...(command.arguments || [])).catch(err => this._notificationService.error(err));
                        break;
                    }
                }
            }
        }));
        scheduler.schedule();
    }
    _disposeAllLenses(decChangeAccessor, viewZoneChangeAccessor) {
        const helper = new CodeLensHelper();
        for (const lens of this._lenses) {
            lens.dispose(helper, viewZoneChangeAccessor);
        }
        if (decChangeAccessor) {
            helper.commit(decChangeAccessor);
        }
        this._lenses.length = 0;
    }
    _renderCodeLensSymbols(symbols) {
        if (!this._editor.hasModel()) {
            return;
        }
        const maxLineNumber = this._editor.getModel().getLineCount();
        const groups = [];
        let lastGroup;
        for (const symbol of symbols.lenses) {
            const line = symbol.symbol.range.startLineNumber;
            if (line < 1 || line > maxLineNumber) {
                // invalid code lens
                continue;
            }
            else if (lastGroup && lastGroup[lastGroup.length - 1].symbol.range.startLineNumber === line) {
                // on same line as previous
                lastGroup.push(symbol);
            }
            else {
                // on later line as previous
                lastGroup = [symbol];
                groups.push(lastGroup);
            }
        }
        const scrollState = StableEditorScrollState.capture(this._editor);
        const layoutInfo = this._getLayoutInfo();
        this._editor.changeDecorations(decorationsAccessor => {
            this._editor.changeViewZones(viewZoneAccessor => {
                const helper = new CodeLensHelper();
                let codeLensIndex = 0;
                let groupsIndex = 0;
                while (groupsIndex < groups.length && codeLensIndex < this._lenses.length) {
                    const symbolsLineNumber = groups[groupsIndex][0].symbol.range.startLineNumber;
                    const codeLensLineNumber = this._lenses[codeLensIndex].getLineNumber();
                    if (codeLensLineNumber < symbolsLineNumber) {
                        this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor);
                        this._lenses.splice(codeLensIndex, 1);
                    }
                    else if (codeLensLineNumber === symbolsLineNumber) {
                        this._lenses[codeLensIndex].updateCodeLensSymbols(groups[groupsIndex], helper);
                        groupsIndex++;
                        codeLensIndex++;
                    }
                    else {
                        this._lenses.splice(codeLensIndex, 0, new CodeLensWidget(groups[groupsIndex], this._editor, this._styleClassName, helper, viewZoneAccessor, layoutInfo.codeLensHeight, () => this._resolveCodeLensesInViewportSoon()));
                        codeLensIndex++;
                        groupsIndex++;
                    }
                }
                // Delete extra code lenses
                while (codeLensIndex < this._lenses.length) {
                    this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor);
                    this._lenses.splice(codeLensIndex, 1);
                }
                // Create extra symbols
                while (groupsIndex < groups.length) {
                    this._lenses.push(new CodeLensWidget(groups[groupsIndex], this._editor, this._styleClassName, helper, viewZoneAccessor, layoutInfo.codeLensHeight, () => this._resolveCodeLensesInViewportSoon()));
                    groupsIndex++;
                }
                helper.commit(decorationsAccessor);
            });
        });
        scrollState.restore(this._editor);
    }
    _resolveCodeLensesInViewportSoon() {
        const model = this._editor.getModel();
        if (model) {
            this._resolveCodeLensesScheduler.schedule();
        }
    }
    _resolveCodeLensesInViewport() {
        var _a;
        (_a = this._resolveCodeLensesPromise) === null || _a === void 0 ? void 0 : _a.cancel();
        this._resolveCodeLensesPromise = undefined;
        const model = this._editor.getModel();
        if (!model) {
            return;
        }
        const toResolve = [];
        const lenses = [];
        this._lenses.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 = createCancelablePromise(token => {
            const promises = toResolve.map((request, i) => {
                const resolvedSymbols = new Array(request.length);
                const promises = request.map((request, i) => {
                    if (!request.symbol.command && typeof request.provider.resolveCodeLens === 'function') {
                        return Promise.resolve(request.provider.resolveCodeLens(model, request.symbol, token)).then(symbol => {
                            resolvedSymbols[i] = symbol;
                        }, onUnexpectedExternalError);
                    }
                    else {
                        resolvedSymbols[i] = request.symbol;
                        return Promise.resolve(undefined);
                    }
                });
                return Promise.all(promises).then(() => {
                    if (!token.isCancellationRequested && !lenses[i].isDisposed()) {
                        lenses[i].updateCommands(resolvedSymbols);
                    }
                });
            });
            return Promise.all(promises);
        });
        this._resolveCodeLensesPromise = resolvePromise;
        this._resolveCodeLensesPromise.then(() => {
            // update moving average
            const newDelay = this._resolveCodeLensesDebounce.update(model, Date.now() - t1);
            this._resolveCodeLensesScheduler.delay = newDelay;
            if (this._currentCodeLensModel) { // update the cached state with new resolved items
                this._codeLensCache.put(model, this._currentCodeLensModel);
            }
            this._oldCodeLensModels.clear(); // dispose old models once we have updated the UI with the current model
            if (resolvePromise === this._resolveCodeLensesPromise) {
                this._resolveCodeLensesPromise = undefined;
            }
        }, err => {
            onUnexpectedError(err); // can also be cancellation!
            if (resolvePromise === this._resolveCodeLensesPromise) {
                this._resolveCodeLensesPromise = undefined;
            }
        });
    }
    getModel() {
        return this._currentCodeLensModel;
    }
};
CodeLensContribution.ID = 'css.editor.codeLens';
CodeLensContribution = codelensController_decorate([
    codelensController_param(1, ILanguageFeaturesService),
    codelensController_param(2, ILanguageFeatureDebounceService),
    codelensController_param(3, ICommandService),
    codelensController_param(4, INotificationService),
    codelensController_param(5, ICodeLensCache)
], CodeLensContribution);

registerEditorContribution(CodeLensContribution.ID, CodeLensContribution);
registerEditorAction(class ShowLensesInCurrentLine extends EditorAction {
    constructor() {
        super({
            id: 'codelens.showLensesInCurrentLine',
            precondition: EditorContextKeys.hasCodeLensProvider,
            label: localize('showLensOnLine', "Show CodeLens Commands For Current Line"),
            alias: 'Show CodeLens Commands For Current Line',
        });
    }
    run(accessor, editor) {
        return codelensController_awaiter(this, void 0, void 0, function* () {
            if (!editor.hasModel()) {
                return;
            }
            const quickInputService = accessor.get(IQuickInputService);
            const commandService = accessor.get(ICommandService);
            const notificationService = accessor.get(INotificationService);
            const lineNumber = editor.getSelection().positionLineNumber;
            const codelensController = editor.getContribution(CodeLensContribution.ID);
            if (!codelensController) {
                return;
            }
            const model = codelensController.getModel();
            if (!model) {
                // nothing
                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) {
                // We dont want an empty picker
                return;
            }
            const item = yield quickInputService.pick(items, { canPickMany: false });
            if (!item) {
                // Nothing picked
                return;
            }
            if (model.isDisposed) {
                // retry whenever the model has been disposed
                return yield commandService.executeCommand(this.id);
            }
            try {
                yield commandService.executeCommand(item.command.id, ...(item.command.arguments || []));
            }
            catch (err) {
                notificationService.error(err);
            }
        });
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/editorDom.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






/**
 * Coordinates relative to the whole document (e.g. mouse event's pageX and pageY)
 */
class PageCoordinates {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this._pageCoordinatesBrand = undefined;
    }
    toClientCoordinates() {
        return new ClientCoordinates(this.x - StandardWindow.scrollX, this.y - StandardWindow.scrollY);
    }
}
/**
 * Coordinates within the application's client area (i.e. origin is document's scroll position).
 *
 * For example, clicking in the top-left corner of the client area will
 * always result in a mouse event with a client.x value of 0, regardless
 * of whether the page is scrolled horizontally.
 */
class ClientCoordinates {
    constructor(clientX, clientY) {
        this.clientX = clientX;
        this.clientY = clientY;
        this._clientCoordinatesBrand = undefined;
    }
    toPageCoordinates() {
        return new PageCoordinates(this.clientX + StandardWindow.scrollX, this.clientY + StandardWindow.scrollY);
    }
}
/**
 * The position of the editor in the page.
 */
class EditorPagePosition {
    constructor(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this._editorPagePositionBrand = undefined;
    }
}
/**
 * Coordinates relative to the the (top;left) of the editor that can be used safely with other internal editor metrics.
 * **NOTE**: This position is obtained by taking page coordinates and transforming them relative to the
 * editor's (top;left) position in a way in which scale transformations are taken into account.
 * **NOTE**: These coordinates could be negative if the mouse position is outside the editor.
 */
class CoordinatesRelativeToEditor {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this._positionRelativeToEditorBrand = undefined;
    }
}
function createEditorPagePosition(editorViewDomNode) {
    const editorPos = getDomNodePagePosition(editorViewDomNode);
    return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height);
}
function createCoordinatesRelativeToEditor(editorViewDomNode, editorPagePosition, pos) {
    // The editor's page position is read from the DOM using getBoundingClientRect().
    //
    // getBoundingClientRect() returns the actual dimensions, while offsetWidth and offsetHeight
    // reflect the unscaled size. We can use this difference to detect a transform:scale()
    // and we will apply the transformation in inverse to get mouse coordinates that make sense inside the editor.
    //
    // This could be expanded to cover rotation as well maybe by walking the DOM up from `editorViewDomNode`
    // and computing the effective transformation matrix using getComputedStyle(element).transform.
    //
    const scaleX = editorPagePosition.width / editorViewDomNode.offsetWidth;
    const scaleY = editorPagePosition.height / editorViewDomNode.offsetHeight;
    // Adjust mouse offsets if editor appears to be scaled via transforms
    const relativeX = (pos.x - editorPagePosition.x) / scaleX;
    const relativeY = (pos.y - editorPagePosition.y) / scaleY;
    return new CoordinatesRelativeToEditor(relativeX, relativeY);
}
class EditorMouseEvent extends StandardMouseEvent {
    constructor(e, isFromPointerCapture, editorViewDomNode) {
        super(e);
        this._editorMouseEventBrand = undefined;
        this.isFromPointerCapture = isFromPointerCapture;
        this.pos = new PageCoordinates(this.posx, this.posy);
        this.editorPos = createEditorPagePosition(editorViewDomNode);
        this.relativePos = createCoordinatesRelativeToEditor(editorViewDomNode, this.editorPos, this.pos);
    }
}
class EditorMouseEventFactory {
    constructor(editorViewDomNode) {
        this._editorViewDomNode = editorViewDomNode;
    }
    _create(e) {
        return new EditorMouseEvent(e, false, this._editorViewDomNode);
    }
    onContextMenu(target, callback) {
        return addDisposableListener(target, 'contextmenu', (e) => {
            callback(this._create(e));
        });
    }
    onMouseUp(target, callback) {
        return addDisposableListener(target, 'mouseup', (e) => {
            callback(this._create(e));
        });
    }
    onMouseDown(target, callback) {
        return addDisposableListener(target, EventType.MOUSE_DOWN, (e) => {
            callback(this._create(e));
        });
    }
    onPointerDown(target, callback) {
        return addDisposableListener(target, EventType.POINTER_DOWN, (e) => {
            callback(this._create(e), e.pointerId);
        });
    }
    onMouseLeave(target, callback) {
        return addDisposableListener(target, EventType.MOUSE_LEAVE, (e) => {
            callback(this._create(e));
        });
    }
    onMouseMove(target, callback) {
        return addDisposableListener(target, 'mousemove', (e) => callback(this._create(e)));
    }
}
class EditorPointerEventFactory {
    constructor(editorViewDomNode) {
        this._editorViewDomNode = editorViewDomNode;
    }
    _create(e) {
        return new EditorMouseEvent(e, false, this._editorViewDomNode);
    }
    onPointerUp(target, callback) {
        return addDisposableListener(target, 'pointerup', (e) => {
            callback(this._create(e));
        });
    }
    onPointerDown(target, callback) {
        return addDisposableListener(target, EventType.POINTER_DOWN, (e) => {
            callback(this._create(e), e.pointerId);
        });
    }
    onPointerLeave(target, callback) {
        return addDisposableListener(target, EventType.POINTER_LEAVE, (e) => {
            callback(this._create(e));
        });
    }
    onPointerMove(target, callback) {
        return addDisposableListener(target, 'pointermove', (e) => callback(this._create(e)));
    }
}
class GlobalEditorPointerMoveMonitor extends Disposable {
    constructor(editorViewDomNode) {
        super();
        this._editorViewDomNode = editorViewDomNode;
        this._globalPointerMoveMonitor = this._register(new GlobalPointerMoveMonitor());
        this._keydownListener = null;
    }
    startMonitoring(initialElement, pointerId, initialButtons, pointerMoveCallback, onStopCallback) {
        // Add a <<capture>> keydown event listener that will cancel the monitoring
        // if something other than a modifier key is pressed
        this._keydownListener = addStandardDisposableListener(document, 'keydown', (e) => {
            const kb = e.toKeybinding();
            if (kb.isModifierKey()) {
                // Allow modifier keys
                return;
            }
            this._globalPointerMoveMonitor.stopMonitoring(true, e.browserEvent);
        }, true);
        this._globalPointerMoveMonitor.startMonitoring(initialElement, pointerId, initialButtons, (e) => {
            pointerMoveCallback(new EditorMouseEvent(e, true, this._editorViewDomNode));
        }, (e) => {
            this._keydownListener.dispose();
            onStopCallback(e);
        });
    }
    stopMonitoring() {
        this._globalPointerMoveMonitor.stopMonitoring(true);
    }
}
/**
 * A helper to create dynamic css rules, bound to a class name.
 * Rules are reused.
 * Reference counting and delayed garbage collection ensure that no rules leak.
*/
class DynamicCssRules {
    constructor(_editor) {
        this._editor = _editor;
        this._instanceId = ++DynamicCssRules._idPool;
        this._counter = 0;
        this._rules = new Map();
        // We delay garbage collection so that hanging rules can be reused.
        this._garbageCollectionScheduler = new RunOnceScheduler(() => this.garbageCollect(), 1000);
    }
    createClassNameRef(options) {
        const rule = this.getOrCreateRule(options);
        rule.increaseRefCount();
        return {
            className: rule.className,
            dispose: () => {
                rule.decreaseRefCount();
                this._garbageCollectionScheduler.schedule();
            }
        };
    }
    getOrCreateRule(properties) {
        const key = this.computeUniqueKey(properties);
        let existingRule = this._rules.get(key);
        if (!existingRule) {
            const counter = this._counter++;
            existingRule = new RefCountedCssRule(key, `dyn-rule-${this._instanceId}-${counter}`, isInShadowDOM(this._editor.getContainerDomNode())
                ? this._editor.getContainerDomNode()
                : undefined, properties);
            this._rules.set(key, existingRule);
        }
        return existingRule;
    }
    computeUniqueKey(properties) {
        return JSON.stringify(properties);
    }
    garbageCollect() {
        for (const rule of this._rules.values()) {
            if (!rule.hasReferences()) {
                this._rules.delete(rule.key);
                rule.dispose();
            }
        }
    }
}
DynamicCssRules._idPool = 0;
class RefCountedCssRule {
    constructor(key, className, _containerElement, properties) {
        this.key = key;
        this.className = className;
        this.properties = properties;
        this._referenceCount = 0;
        this._styleElement = createStyleSheet(_containerElement);
        this._styleElement.textContent = this.getCssText(this.className, this.properties);
    }
    getCssText(className, properties) {
        let str = `.${className} {`;
        for (const prop in properties) {
            const value = properties[prop];
            let cssValue;
            if (typeof value === 'object') {
                cssValue = `var(${asCssVariableName(value.id)})`;
            }
            else {
                cssValue = value;
            }
            const cssPropName = camelToDashes(prop);
            str += `\n\t${cssPropName}: ${cssValue};`;
        }
        str += `\n}`;
        return str;
    }
    dispose() {
        this._styleElement.remove();
    }
    increaseRefCount() {
        this._referenceCount++;
    }
    decreaseRefCount() {
        this._referenceCount--;
    }
    hasReferences() {
        return this._referenceCount > 0;
    }
}
function camelToDashes(str) {
    return str.replace(/(^[A-Z])/, ([first]) => first.toLowerCase())
        .replace(/([A-Z])/g, ([letter]) => `-${letter.toLowerCase()}`);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/colorPicker/browser/color.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







function getColors(registry, model, token) {
    const colors = [];
    const providers = registry.ordered(model).reverse();
    const promises = providers.map(provider => Promise.resolve(provider.provideDocumentColors(model, token)).then(result => {
        if (Array.isArray(result)) {
            for (const colorInfo of result) {
                colors.push({ colorInfo, provider });
            }
        }
    }));
    return Promise.all(promises).then(() => colors);
}
function getColorPresentations(model, colorInfo, provider, token) {
    return Promise.resolve(provider.provideColorPresentations(model, colorInfo, token));
}
CommandsRegistry.registerCommand('_executeDocumentColorProvider', function (accessor, ...args) {
    const [resource] = args;
    if (!(resource instanceof URI)) {
        throw illegalArgument();
    }
    const { colorProvider: colorProviderRegistry } = accessor.get(ILanguageFeaturesService);
    const model = accessor.get(IModelService).getModel(resource);
    if (!model) {
        throw illegalArgument();
    }
    const rawCIs = [];
    const providers = colorProviderRegistry.ordered(model).reverse();
    const promises = providers.map(provider => Promise.resolve(provider.provideDocumentColors(model, CancellationToken.None)).then(result => {
        if (Array.isArray(result)) {
            for (const ci of result) {
                rawCIs.push({ range: ci.range, color: [ci.color.red, ci.color.green, ci.color.blue, ci.color.alpha] });
            }
        }
    }));
    return Promise.all(promises).then(() => rawCIs);
});
CommandsRegistry.registerCommand('_executeColorPresentationProvider', function (accessor, ...args) {
    const [color, context] = args;
    const { uri, range } = context;
    if (!(uri instanceof URI) || !Array.isArray(color) || color.length !== 4 || !Range.isIRange(range)) {
        throw illegalArgument();
    }
    const [red, green, blue, alpha] = color;
    const { colorProvider: colorProviderRegistry } = accessor.get(ILanguageFeaturesService);
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
        throw illegalArgument();
    }
    const colorInfo = {
        range,
        color: { red, green, blue, alpha }
    };
    const presentations = [];
    const providers = colorProviderRegistry.ordered(model).reverse();
    const promises = providers.map(provider => Promise.resolve(provider.provideColorPresentations(model, colorInfo, CancellationToken.None)).then(result => {
        if (Array.isArray(result)) {
            presentations.push(...result);
        }
    }));
    return Promise.all(promises).then(() => presentations);
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/colorPicker/browser/colorDetector.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var colorDetector_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var colorDetector_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var colorDetector_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};














const ColorDecorationInjectedTextMarker = Object.create({});
const MAX_DECORATORS = 500;
let ColorDetector = class ColorDetector extends Disposable {
    constructor(_editor, _configurationService, _languageFeaturesService, languageFeatureDebounceService) {
        super();
        this._editor = _editor;
        this._configurationService = _configurationService;
        this._languageFeaturesService = _languageFeaturesService;
        this._localToDispose = this._register(new DisposableStore());
        this._decorationsIds = [];
        this._colorDatas = new Map();
        this._colorDecoratorIds = this._editor.createDecorationsCollection();
        this._ruleFactory = new DynamicCssRules(this._editor);
        this._colorDecorationClassRefs = this._register(new DisposableStore());
        this._debounceInformation = languageFeatureDebounceService.for(_languageFeaturesService.colorProvider, 'Document Colors', { min: ColorDetector.RECOMPUTE_TIME });
        this._register(_editor.onDidChangeModel(() => {
            this._isEnabled = this.isEnabled();
            this.onModelChanged();
        }));
        this._register(_editor.onDidChangeModelLanguage(() => this.onModelChanged()));
        this._register(_languageFeaturesService.colorProvider.onDidChange(() => this.onModelChanged()));
        this._register(_editor.onDidChangeConfiguration(() => {
            const prevIsEnabled = this._isEnabled;
            this._isEnabled = this.isEnabled();
            if (prevIsEnabled !== this._isEnabled) {
                if (this._isEnabled) {
                    this.onModelChanged();
                }
                else {
                    this.removeAllDecorations();
                }
            }
        }));
        this._timeoutTimer = null;
        this._computePromise = null;
        this._isEnabled = this.isEnabled();
        this.onModelChanged();
    }
    isEnabled() {
        const model = this._editor.getModel();
        if (!model) {
            return false;
        }
        const languageId = model.getLanguageId();
        // handle deprecated settings. [languageId].colorDecorators.enable
        const deprecatedConfig = this._configurationService.getValue(languageId);
        if (deprecatedConfig && typeof deprecatedConfig === 'object') {
            const colorDecorators = deprecatedConfig['colorDecorators']; // deprecatedConfig.valueOf('.colorDecorators.enable');
            if (colorDecorators && colorDecorators['enable'] !== undefined && !colorDecorators['enable']) {
                return colorDecorators['enable'];
            }
        }
        return this._editor.getOption(17 /* EditorOption.colorDecorators */);
    }
    static get(editor) {
        return editor.getContribution(this.ID);
    }
    dispose() {
        this.stop();
        this.removeAllDecorations();
        super.dispose();
    }
    onModelChanged() {
        this.stop();
        if (!this._isEnabled) {
            return;
        }
        const model = this._editor.getModel();
        if (!model || !this._languageFeaturesService.colorProvider.has(model)) {
            return;
        }
        this._localToDispose.add(this._editor.onDidChangeModelContent(() => {
            if (!this._timeoutTimer) {
                this._timeoutTimer = new TimeoutTimer();
                this._timeoutTimer.cancelAndSet(() => {
                    this._timeoutTimer = null;
                    this.beginCompute();
                }, this._debounceInformation.get(model));
            }
        }));
        this.beginCompute();
    }
    beginCompute() {
        this._computePromise = createCancelablePromise((token) => colorDetector_awaiter(this, void 0, void 0, function* () {
            const model = this._editor.getModel();
            if (!model) {
                return Promise.resolve([]);
            }
            const sw = new StopWatch(false);
            const colors = yield getColors(this._languageFeaturesService.colorProvider, model, token);
            this._debounceInformation.update(model, sw.elapsed());
            return colors;
        }));
        this._computePromise.then((colorInfos) => {
            this.updateDecorations(colorInfos);
            this.updateColorDecorators(colorInfos);
            this._computePromise = null;
        }, onUnexpectedError);
    }
    stop() {
        if (this._timeoutTimer) {
            this._timeoutTimer.cancel();
            this._timeoutTimer = null;
        }
        if (this._computePromise) {
            this._computePromise.cancel();
            this._computePromise = null;
        }
        this._localToDispose.clear();
    }
    updateDecorations(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: ModelDecorationOptions.EMPTY
        }));
        this._editor.changeDecorations((changeAccessor) => {
            this._decorationsIds = changeAccessor.deltaDecorations(this._decorationsIds, decorations);
            this._colorDatas = new Map();
            this._decorationsIds.forEach((id, i) => this._colorDatas.set(id, colorDatas[i]));
        });
    }
    updateColorDecorators(colorData) {
        this._colorDecorationClassRefs.clear();
        const decorations = [];
        for (let i = 0; i < colorData.length && decorations.length < MAX_DECORATORS; i++) {
            const { red, green, blue, alpha } = colorData[i].colorInfo.color;
            const rgba = new RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha);
            const color = `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
            const ref = this._colorDecorationClassRefs.add(this._ruleFactory.createClassNameRef({
                backgroundColor: color
            }));
            decorations.push({
                range: {
                    startLineNumber: colorData[i].colorInfo.range.startLineNumber,
                    startColumn: colorData[i].colorInfo.range.startColumn,
                    endLineNumber: colorData[i].colorInfo.range.endLineNumber,
                    endColumn: colorData[i].colorInfo.range.endColumn
                },
                options: {
                    description: 'colorDetector',
                    before: {
                        content: noBreakWhitespace,
                        inlineClassName: `${ref.className} colorpicker-color-decoration`,
                        inlineClassNameAffectsLetterSpacing: true,
                        attachedData: ColorDecorationInjectedTextMarker
                    }
                }
            });
        }
        this._colorDecoratorIds.set(decorations);
    }
    removeAllDecorations() {
        this._editor.removeDecorations(this._decorationsIds);
        this._decorationsIds = [];
        this._colorDecoratorIds.clear();
        this._colorDecorationClassRefs.clear();
    }
    getColorData(position) {
        const model = this._editor.getModel();
        if (!model) {
            return null;
        }
        const decorations = model
            .getDecorationsInRange(Range.fromPositions(position, position))
            .filter(d => this._colorDatas.has(d.id));
        if (decorations.length === 0) {
            return null;
        }
        return this._colorDatas.get(decorations[0].id);
    }
    isColorDecoration(decoration) {
        return this._colorDecoratorIds.has(decoration);
    }
};
ColorDetector.ID = 'editor.contrib.colorDetector';
ColorDetector.RECOMPUTE_TIME = 1000; // ms
ColorDetector = colorDetector_decorate([
    colorDetector_param(1, IConfigurationService),
    colorDetector_param(2, ILanguageFeaturesService),
    colorDetector_param(3, ILanguageFeatureDebounceService)
], ColorDetector);

registerEditorContribution(ColorDetector.ID, ColorDetector);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/colorPicker/browser/colorPickerModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class ColorPickerModel {
    constructor(color, availableColorPresentations, presentationIndex) {
        this.presentationIndex = presentationIndex;
        this._onColorFlushed = new Emitter();
        this.onColorFlushed = this._onColorFlushed.event;
        this._onDidChangeColor = new Emitter();
        this.onDidChangeColor = this._onDidChangeColor.event;
        this._onDidChangePresentation = new Emitter();
        this.onDidChangePresentation = this._onDidChangePresentation.event;
        this.originalColor = color;
        this._color = color;
        this._colorPresentations = availableColorPresentations;
    }
    get color() {
        return this._color;
    }
    set color(color) {
        if (this._color.equals(color)) {
            return;
        }
        this._color = color;
        this._onDidChangeColor.fire(color);
    }
    get presentation() { return this.colorPresentations[this.presentationIndex]; }
    get colorPresentations() {
        return this._colorPresentations;
    }
    set colorPresentations(colorPresentations) {
        this._colorPresentations = colorPresentations;
        if (this.presentationIndex > colorPresentations.length - 1) {
            this.presentationIndex = 0;
        }
        this._onDidChangePresentation.fire(this.presentation);
    }
    selectNextColorPresentation() {
        this.presentationIndex = (this.presentationIndex + 1) % this.colorPresentations.length;
        this.flushColor();
        this._onDidChangePresentation.fire(this.presentation);
    }
    guessColorPresentation(color, originalText) {
        for (let i = 0; i < this.colorPresentations.length; i++) {
            if (originalText.toLowerCase() === this.colorPresentations[i].label) {
                this.presentationIndex = i;
                this._onDidChangePresentation.fire(this.presentation);
                break;
            }
        }
    }
    flushColor() {
        this._onColorFlushed.fire(this._color);
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/colorPicker/browser/colorPicker.css
var colorPicker = __webpack_require__(54);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/colorPicker/browser/colorPicker.css

      
      
      
      
      
      
      
      
      

var colorPicker_options = {};

colorPicker_options.styleTagTransform = (styleTagTransform_default());
colorPicker_options.setAttributes = (setAttributesWithoutAttributes_default());

      colorPicker_options.insert = insertBySelector_default().bind(null, "head");
    
colorPicker_options.domAPI = (styleDomAPI_default());
colorPicker_options.insertStyleElement = (insertStyleElement_default());

var colorPicker_update = injectStylesIntoStyleTag_default()(colorPicker/* default */.A, colorPicker_options);




       /* harmony default export */ const browser_colorPicker = (colorPicker/* default */.A && colorPicker/* default */.A.locals ? colorPicker/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/colorPicker/browser/colorPickerWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/











const $ = dom_$;
class ColorPickerHeader extends Disposable {
    constructor(container, model, themeService) {
        super();
        this.model = model;
        this.domNode = $('.colorpicker-header');
        append(container, this.domNode);
        this.pickedColorNode = append(this.domNode, $('.picked-color'));
        const tooltip = localize('clickToToggleColorOptions', "Click to toggle color options (rgb/hsl/hex)");
        this.pickedColorNode.setAttribute('title', tooltip);
        const colorBox = append(this.domNode, $('.original-color'));
        colorBox.style.backgroundColor = Color.Format.CSS.format(this.model.originalColor) || '';
        this.backgroundColor = themeService.getColorTheme().getColor(editorHoverBackground) || Color.white;
        this._register(registerThemingParticipant((theme, collector) => {
            this.backgroundColor = theme.getColor(editorHoverBackground) || Color.white;
        }));
        this._register(addDisposableListener(this.pickedColorNode, EventType.CLICK, () => this.model.selectNextColorPresentation()));
        this._register(addDisposableListener(colorBox, EventType.CLICK, () => {
            this.model.color = this.model.originalColor;
            this.model.flushColor();
        }));
        this._register(model.onDidChangeColor(this.onDidChangeColor, this));
        this._register(model.onDidChangePresentation(this.onDidChangePresentation, this));
        this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(model.color) || '';
        this.pickedColorNode.classList.toggle('light', model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter());
        this.onDidChangeColor(this.model.color);
    }
    onDidChangeColor(color) {
        this.pickedColorNode.style.backgroundColor = Color.Format.CSS.format(color) || '';
        this.pickedColorNode.classList.toggle('light', color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter());
        this.onDidChangePresentation();
    }
    onDidChangePresentation() {
        this.pickedColorNode.textContent = this.model.presentation ? this.model.presentation.label : '';
        this.pickedColorNode.prepend($('.codicon.codicon-color-mode'));
    }
}
class ColorPickerBody extends Disposable {
    constructor(container, model, pixelRatio) {
        super();
        this.model = model;
        this.pixelRatio = pixelRatio;
        this.domNode = $('.colorpicker-body');
        append(container, this.domNode);
        this.saturationBox = new SaturationBox(this.domNode, this.model, this.pixelRatio);
        this._register(this.saturationBox);
        this._register(this.saturationBox.onDidChange(this.onDidSaturationValueChange, this));
        this._register(this.saturationBox.onColorFlushed(this.flushColor, this));
        this.opacityStrip = new OpacityStrip(this.domNode, this.model);
        this._register(this.opacityStrip);
        this._register(this.opacityStrip.onDidChange(this.onDidOpacityChange, this));
        this._register(this.opacityStrip.onColorFlushed(this.flushColor, this));
        this.hueStrip = new HueStrip(this.domNode, this.model);
        this._register(this.hueStrip);
        this._register(this.hueStrip.onDidChange(this.onDidHueChange, this));
        this._register(this.hueStrip.onColorFlushed(this.flushColor, this));
    }
    flushColor() {
        this.model.flushColor();
    }
    onDidSaturationValueChange({ s, v }) {
        const hsva = this.model.color.hsva;
        this.model.color = new Color(new HSVA(hsva.h, s, v, hsva.a));
    }
    onDidOpacityChange(a) {
        const hsva = this.model.color.hsva;
        this.model.color = new Color(new HSVA(hsva.h, hsva.s, hsva.v, a));
    }
    onDidHueChange(value) {
        const hsva = this.model.color.hsva;
        const h = (1 - value) * 360;
        this.model.color = new Color(new HSVA(h === 360 ? 0 : h, hsva.s, hsva.v, hsva.a));
    }
    layout() {
        this.saturationBox.layout();
        this.opacityStrip.layout();
        this.hueStrip.layout();
    }
}
class SaturationBox extends Disposable {
    constructor(container, model, pixelRatio) {
        super();
        this.model = model;
        this.pixelRatio = pixelRatio;
        this._onDidChange = new Emitter();
        this.onDidChange = this._onDidChange.event;
        this._onColorFlushed = new Emitter();
        this.onColorFlushed = this._onColorFlushed.event;
        this.domNode = $('.saturation-wrap');
        append(container, this.domNode);
        // Create canvas, draw selected color
        this.canvas = document.createElement('canvas');
        this.canvas.className = 'saturation-box';
        append(this.domNode, this.canvas);
        // Add selection circle
        this.selection = $('.saturation-selection');
        append(this.domNode, this.selection);
        this.layout();
        this._register(addDisposableListener(this.domNode, EventType.POINTER_DOWN, e => this.onPointerDown(e)));
        this._register(this.model.onDidChangeColor(this.onDidChangeColor, this));
        this.monitor = null;
    }
    onPointerDown(e) {
        if (!e.target || !(e.target instanceof Element)) {
            return;
        }
        this.monitor = this._register(new GlobalPointerMoveMonitor());
        const origin = getDomNodePagePosition(this.domNode);
        if (e.target !== this.selection) {
            this.onDidChangePosition(e.offsetX, e.offsetY);
        }
        this.monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangePosition(event.pageX - origin.left, event.pageY - origin.top), () => null);
        const pointerUpListener = addDisposableListener(document, EventType.POINTER_UP, () => {
            this._onColorFlushed.fire();
            pointerUpListener.dispose();
            if (this.monitor) {
                this.monitor.stopMonitoring(true);
                this.monitor = null;
            }
        }, true);
    }
    onDidChangePosition(left, top) {
        const s = Math.max(0, Math.min(1, left / this.width));
        const v = Math.max(0, Math.min(1, 1 - (top / this.height)));
        this.paintSelection(s, v);
        this._onDidChange.fire({ s, v });
    }
    layout() {
        this.width = this.domNode.offsetWidth;
        this.height = this.domNode.offsetHeight;
        this.canvas.width = this.width * this.pixelRatio;
        this.canvas.height = this.height * this.pixelRatio;
        this.paint();
        const hsva = this.model.color.hsva;
        this.paintSelection(hsva.s, hsva.v);
    }
    paint() {
        const hsva = this.model.color.hsva;
        const saturatedColor = new Color(new HSVA(hsva.h, 1, 1, 1));
        const ctx = this.canvas.getContext('2d');
        const whiteGradient = ctx.createLinearGradient(0, 0, this.canvas.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.canvas.height);
        blackGradient.addColorStop(0, 'rgba(0, 0, 0, 0)');
        blackGradient.addColorStop(1, 'rgba(0, 0, 0, 1)');
        ctx.rect(0, 0, this.canvas.width, this.canvas.height);
        ctx.fillStyle = Color.Format.CSS.format(saturatedColor);
        ctx.fill();
        ctx.fillStyle = whiteGradient;
        ctx.fill();
        ctx.fillStyle = blackGradient;
        ctx.fill();
    }
    paintSelection(s, v) {
        this.selection.style.left = `${s * this.width}px`;
        this.selection.style.top = `${this.height - v * this.height}px`;
    }
    onDidChangeColor() {
        if (this.monitor && this.monitor.isMonitoring()) {
            return;
        }
        this.paint();
    }
}
class Strip extends Disposable {
    constructor(container, model) {
        super();
        this.model = model;
        this._onDidChange = new Emitter();
        this.onDidChange = this._onDidChange.event;
        this._onColorFlushed = new Emitter();
        this.onColorFlushed = this._onColorFlushed.event;
        this.domNode = append(container, $('.strip'));
        this.overlay = append(this.domNode, $('.overlay'));
        this.slider = append(this.domNode, $('.slider'));
        this.slider.style.top = `0px`;
        this._register(addDisposableListener(this.domNode, EventType.POINTER_DOWN, e => this.onPointerDown(e)));
        this.layout();
    }
    layout() {
        this.height = this.domNode.offsetHeight - this.slider.offsetHeight;
        const value = this.getValue(this.model.color);
        this.updateSliderPosition(value);
    }
    onPointerDown(e) {
        if (!e.target || !(e.target instanceof Element)) {
            return;
        }
        const monitor = this._register(new GlobalPointerMoveMonitor());
        const origin = getDomNodePagePosition(this.domNode);
        this.domNode.classList.add('grabbing');
        if (e.target !== this.slider) {
            this.onDidChangeTop(e.offsetY);
        }
        monitor.startMonitoring(e.target, e.pointerId, e.buttons, event => this.onDidChangeTop(event.pageY - origin.top), () => null);
        const pointerUpListener = addDisposableListener(document, EventType.POINTER_UP, () => {
            this._onColorFlushed.fire();
            pointerUpListener.dispose();
            monitor.stopMonitoring(true);
            this.domNode.classList.remove('grabbing');
        }, true);
    }
    onDidChangeTop(top) {
        const value = Math.max(0, Math.min(1, 1 - (top / this.height)));
        this.updateSliderPosition(value);
        this._onDidChange.fire(value);
    }
    updateSliderPosition(value) {
        this.slider.style.top = `${(1 - value) * this.height}px`;
    }
}
class OpacityStrip extends Strip {
    constructor(container, model) {
        super(container, model);
        this.domNode.classList.add('opacity-strip');
        this._register(model.onDidChangeColor(this.onDidChangeColor, this));
        this.onDidChangeColor(this.model.color);
    }
    onDidChangeColor(color) {
        const { r, g, b } = color.rgba;
        const opaque = new Color(new RGBA(r, g, b, 1));
        const transparent = new Color(new RGBA(r, g, b, 0));
        this.overlay.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent} 100%)`;
    }
    getValue(color) {
        return color.hsva.a;
    }
}
class HueStrip extends Strip {
    constructor(container, model) {
        super(container, model);
        this.domNode.classList.add('hue-strip');
    }
    getValue(color) {
        return 1 - (color.hsva.h / 360);
    }
}
class ColorPickerWidget extends Widget {
    constructor(container, model, pixelRatio, themeService) {
        super();
        this.model = model;
        this.pixelRatio = pixelRatio;
        this._register(PixelRatio.onDidChange(() => this.layout()));
        const element = $('.colorpicker-widget');
        container.appendChild(element);
        const header = new ColorPickerHeader(element, this.model, themeService);
        this.body = new ColorPickerBody(element, this.model, this.pixelRatio);
        this._register(header);
        this._register(this.body);
    }
    layout() {
        this.body.layout();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/colorPicker/browser/colorHoverParticipant.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var colorHoverParticipant_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var colorHoverParticipant_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var colorHoverParticipant_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};










class ColorHover {
    constructor(owner, range, model, provider) {
        this.owner = owner;
        this.range = range;
        this.model = model;
        this.provider = provider;
        /**
         * Force the hover to always be rendered at this specific range,
         * even in the case of multiple hover parts.
         */
        this.forceShowAtRange = true;
    }
    isValidForHoverAnchor(anchor) {
        return (anchor.type === 1 /* HoverAnchorType.Range */
            && this.range.startColumn <= anchor.range.startColumn
            && this.range.endColumn >= anchor.range.endColumn);
    }
}
let ColorHoverParticipant = class ColorHoverParticipant {
    constructor(_editor, _themeService) {
        this._editor = _editor;
        this._themeService = _themeService;
        this.hoverOrdinal = 1;
    }
    computeSync(anchor, lineDecorations) {
        return [];
    }
    computeAsync(anchor, lineDecorations, token) {
        return AsyncIterableObject.fromPromise(this._computeAsync(anchor, lineDecorations, token));
    }
    _computeAsync(anchor, lineDecorations, token) {
        return colorHoverParticipant_awaiter(this, void 0, void 0, function* () {
            if (!this._editor.hasModel()) {
                return [];
            }
            const colorDetector = ColorDetector.get(this._editor);
            if (!colorDetector) {
                return [];
            }
            for (const d of lineDecorations) {
                if (!colorDetector.isColorDecoration(d)) {
                    continue;
                }
                const colorData = colorDetector.getColorData(d.range.getStartPosition());
                if (colorData) {
                    const colorHover = yield this._createColorHover(this._editor.getModel(), colorData.colorInfo, colorData.provider);
                    return [colorHover];
                }
            }
            return [];
        });
    }
    _createColorHover(editorModel, colorInfo, provider) {
        return colorHoverParticipant_awaiter(this, void 0, void 0, function* () {
            const originalText = editorModel.getValueInRange(colorInfo.range);
            const { red, green, blue, alpha } = colorInfo.color;
            const rgba = new RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha);
            const color = new Color(rgba);
            const colorPresentations = yield getColorPresentations(editorModel, colorInfo, provider, CancellationToken.None);
            const model = new ColorPickerModel(color, [], 0);
            model.colorPresentations = colorPresentations || [];
            model.guessColorPresentation(color, originalText);
            return new ColorHover(this, Range.lift(colorInfo.range), model, provider);
        });
    }
    renderHoverParts(context, hoverParts) {
        if (hoverParts.length === 0 || !this._editor.hasModel()) {
            return Disposable.None;
        }
        const disposables = new DisposableStore();
        const colorHover = hoverParts[0];
        const editorModel = this._editor.getModel();
        const model = colorHover.model;
        const widget = disposables.add(new ColorPickerWidget(context.fragment, model, this._editor.getOption(131 /* EditorOption.pixelRatio */), this._themeService));
        context.setColorPicker(widget);
        let range = new Range(colorHover.range.startLineNumber, colorHover.range.startColumn, colorHover.range.endLineNumber, colorHover.range.endColumn);
        const updateEditorModel = () => {
            let textEdits;
            let newRange;
            if (model.presentation.textEdit) {
                textEdits = [model.presentation.textEdit];
                newRange = new Range(model.presentation.textEdit.range.startLineNumber, model.presentation.textEdit.range.startColumn, model.presentation.textEdit.range.endLineNumber, model.presentation.textEdit.range.endColumn);
                const trackedRange = this._editor.getModel()._setTrackedRange(null, newRange, 3 /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */);
                this._editor.pushUndoStop();
                this._editor.executeEdits('colorpicker', textEdits);
                newRange = this._editor.getModel()._getTrackedRange(trackedRange) || newRange;
            }
            else {
                textEdits = [{ range, text: model.presentation.label, forceMoveMarkers: false }];
                newRange = range.setEndPosition(range.endLineNumber, range.startColumn + model.presentation.label.length);
                this._editor.pushUndoStop();
                this._editor.executeEdits('colorpicker', textEdits);
            }
            if (model.presentation.additionalTextEdits) {
                textEdits = [...model.presentation.additionalTextEdits];
                this._editor.executeEdits('colorpicker', textEdits);
                context.hide();
            }
            this._editor.pushUndoStop();
            range = newRange;
        };
        const updateColorPresentations = (color) => {
            return getColorPresentations(editorModel, {
                range: range,
                color: {
                    red: color.rgba.r / 255,
                    green: color.rgba.g / 255,
                    blue: color.rgba.b / 255,
                    alpha: color.rgba.a
                }
            }, colorHover.provider, CancellationToken.None).then((colorPresentations) => {
                model.colorPresentations = colorPresentations || [];
            });
        };
        disposables.add(model.onColorFlushed((color) => {
            updateColorPresentations(color).then(updateEditorModel);
        }));
        disposables.add(model.onDidChangeColor(updateColorPresentations));
        return disposables;
    }
};
ColorHoverParticipant = colorHoverParticipant_decorate([
    colorHoverParticipant_param(1, IThemeService)
], ColorHoverParticipant);


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition.css
var goToDefinitionAtPosition = __webpack_require__(66534);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition.css

      
      
      
      
      
      
      
      
      

var goToDefinitionAtPosition_options = {};

goToDefinitionAtPosition_options.styleTagTransform = (styleTagTransform_default());
goToDefinitionAtPosition_options.setAttributes = (setAttributesWithoutAttributes_default());

      goToDefinitionAtPosition_options.insert = insertBySelector_default().bind(null, "head");
    
goToDefinitionAtPosition_options.domAPI = (styleDomAPI_default());
goToDefinitionAtPosition_options.insertStyleElement = (insertStyleElement_default());

var goToDefinitionAtPosition_update = injectStylesIntoStyleTag_default()(goToDefinitionAtPosition/* default */.A, goToDefinitionAtPosition_options);




       /* harmony default export */ const link_goToDefinitionAtPosition = (goToDefinitionAtPosition/* default */.A && goToDefinitionAtPosition/* default */.A.locals ? goToDefinitionAtPosition/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/link/clickLinkGesture.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



function hasModifier(e, modifier) {
    return !!e[modifier];
}
/**
 * An event that encapsulates the various trigger modifiers logic needed for go to definition.
 */
class ClickLinkMouseEvent {
    constructor(source, opts) {
        this.target = source.target;
        this.hasTriggerModifier = hasModifier(source.event, opts.triggerModifier);
        this.hasSideBySideModifier = hasModifier(source.event, opts.triggerSideBySideModifier);
        this.isNoneOrSingleMouseDown = (source.event.detail <= 1);
    }
}
/**
 * An event that encapsulates the various trigger modifiers logic needed for go to definition.
 */
class ClickLinkKeyboardEvent {
    constructor(source, opts) {
        this.keyCodeIsTriggerKey = (source.keyCode === opts.triggerKey);
        this.keyCodeIsSideBySideKey = (source.keyCode === opts.triggerSideBySideKey);
        this.hasTriggerModifier = hasModifier(source, opts.triggerModifier);
    }
}
class ClickLinkOptions {
    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(multiCursorModifier) {
    if (multiCursorModifier === 'altKey') {
        if (isMacintosh) {
            return new ClickLinkOptions(57 /* KeyCode.Meta */, 'metaKey', 6 /* KeyCode.Alt */, 'altKey');
        }
        return new ClickLinkOptions(5 /* KeyCode.Ctrl */, 'ctrlKey', 6 /* KeyCode.Alt */, 'altKey');
    }
    if (isMacintosh) {
        return new ClickLinkOptions(6 /* KeyCode.Alt */, 'altKey', 57 /* KeyCode.Meta */, 'metaKey');
    }
    return new ClickLinkOptions(6 /* KeyCode.Alt */, 'altKey', 5 /* KeyCode.Ctrl */, 'ctrlKey');
}
class ClickLinkGesture extends Disposable {
    constructor(editor) {
        super();
        this._onMouseMoveOrRelevantKeyDown = this._register(new Emitter());
        this.onMouseMoveOrRelevantKeyDown = this._onMouseMoveOrRelevantKeyDown.event;
        this._onExecute = this._register(new Emitter());
        this.onExecute = this._onExecute.event;
        this._onCancel = this._register(new Emitter());
        this.onCancel = this._onCancel.event;
        this._editor = editor;
        this._opts = createOptions(this._editor.getOption(72 /* EditorOption.multiCursorModifier */));
        this._lastMouseMoveEvent = null;
        this._hasTriggerKeyOnMouseDown = false;
        this._lineNumberOnMouseDown = 0;
        this._register(this._editor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(72 /* EditorOption.multiCursorModifier */)) {
                const newOpts = createOptions(this._editor.getOption(72 /* EditorOption.multiCursorModifier */));
                if (this._opts.equals(newOpts)) {
                    return;
                }
                this._opts = newOpts;
                this._lastMouseMoveEvent = null;
                this._hasTriggerKeyOnMouseDown = false;
                this._lineNumberOnMouseDown = 0;
                this._onCancel.fire();
            }
        }));
        this._register(this._editor.onMouseMove((e) => this._onEditorMouseMove(new ClickLinkMouseEvent(e, this._opts))));
        this._register(this._editor.onMouseDown((e) => this._onEditorMouseDown(new ClickLinkMouseEvent(e, this._opts))));
        this._register(this._editor.onMouseUp((e) => this._onEditorMouseUp(new ClickLinkMouseEvent(e, this._opts))));
        this._register(this._editor.onKeyDown((e) => this._onEditorKeyDown(new ClickLinkKeyboardEvent(e, this._opts))));
        this._register(this._editor.onKeyUp((e) => this._onEditorKeyUp(new ClickLinkKeyboardEvent(e, this._opts))));
        this._register(this._editor.onMouseDrag(() => this._resetHandler()));
        this._register(this._editor.onDidChangeCursorSelection((e) => this._onDidChangeCursorSelection(e)));
        this._register(this._editor.onDidChangeModel((e) => this._resetHandler()));
        this._register(this._editor.onDidChangeModelContent(() => this._resetHandler()));
        this._register(this._editor.onDidScrollChange((e) => {
            if (e.scrollTopChanged || e.scrollLeftChanged) {
                this._resetHandler();
            }
        }));
    }
    _onDidChangeCursorSelection(e) {
        if (e.selection && e.selection.startColumn !== e.selection.endColumn) {
            this._resetHandler(); // immediately stop this feature if the user starts to select (https://github.com/microsoft/vscode/issues/7827)
        }
    }
    _onEditorMouseMove(mouseEvent) {
        this._lastMouseMoveEvent = mouseEvent;
        this._onMouseMoveOrRelevantKeyDown.fire([mouseEvent, null]);
    }
    _onEditorMouseDown(mouseEvent) {
        // We need to record if we had the trigger key on mouse down because someone might select something in the editor
        // holding the mouse down and then while mouse is down start to press Ctrl/Cmd to start a copy operation and then
        // release the mouse button without wanting to do the navigation.
        // With this flag we prevent goto definition if the mouse was down before the trigger key was pressed.
        this._hasTriggerKeyOnMouseDown = mouseEvent.hasTriggerModifier;
        this._lineNumberOnMouseDown = mouseEvent.target.position ? mouseEvent.target.position.lineNumber : 0;
    }
    _onEditorMouseUp(mouseEvent) {
        const currentLineNumber = mouseEvent.target.position ? mouseEvent.target.position.lineNumber : 0;
        if (this._hasTriggerKeyOnMouseDown && this._lineNumberOnMouseDown && this._lineNumberOnMouseDown === currentLineNumber) {
            this._onExecute.fire(mouseEvent);
        }
    }
    _onEditorKeyDown(e) {
        if (this._lastMouseMoveEvent
            && (e.keyCodeIsTriggerKey // User just pressed Ctrl/Cmd (normal goto definition)
                || (e.keyCodeIsSideBySideKey && e.hasTriggerModifier) // User pressed Ctrl/Cmd+Alt (goto definition to the side)
            )) {
            this._onMouseMoveOrRelevantKeyDown.fire([this._lastMouseMoveEvent, e]);
        }
        else if (e.hasTriggerModifier) {
            this._onCancel.fire(); // remove decorations if user holds another key with ctrl/cmd to prevent accident goto declaration
        }
    }
    _onEditorKeyUp(e) {
        if (e.keyCodeIsTriggerKey) {
            this._onCancel.fire();
        }
    }
    _resetHandler() {
        this._lastMouseMoveEvent = null;
        this._hasTriggerKeyOnMouseDown = false;
        this._onCancel.fire();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/iconLabel/iconLabelHover.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var iconLabelHover_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};








function setupNativeHover(htmlElement, tooltip) {
    if (isString(tooltip)) {
        // Icons don't render in the native hover so we strip them out
        htmlElement.title = stripIcons(tooltip);
    }
    else if (tooltip === null || tooltip === void 0 ? void 0 : tooltip.markdownNotSupportedFallback) {
        htmlElement.title = tooltip.markdownNotSupportedFallback;
    }
    else {
        htmlElement.removeAttribute('title');
    }
}
class UpdatableHoverWidget {
    constructor(hoverDelegate, target, fadeInAnimation) {
        this.hoverDelegate = hoverDelegate;
        this.target = target;
        this.fadeInAnimation = fadeInAnimation;
    }
    update(content, focus, options) {
        var _a;
        return iconLabelHover_awaiter(this, void 0, void 0, function* () {
            if (this._cancellationTokenSource) {
                // there's an computation ongoing, cancel it
                this._cancellationTokenSource.dispose(true);
                this._cancellationTokenSource = undefined;
            }
            if (this.isDisposed) {
                return;
            }
            let resolvedContent;
            if (content === undefined || isString(content) || content instanceof HTMLElement) {
                resolvedContent = content;
            }
            else if (!isFunction(content.markdown)) {
                resolvedContent = (_a = content.markdown) !== null && _a !== void 0 ? _a : content.markdownNotSupportedFallback;
            }
            else {
                // compute the content, potentially long-running
                // show 'Loading' if no hover is up yet
                if (!this._hoverWidget) {
                    this.show(localize('iconLabel.loading', "Loading..."), focus);
                }
                // compute the content
                this._cancellationTokenSource = new CancellationTokenSource();
                const token = this._cancellationTokenSource.token;
                resolvedContent = yield content.markdown(token);
                if (resolvedContent === undefined) {
                    resolvedContent = content.markdownNotSupportedFallback;
                }
                if (this.isDisposed || token.isCancellationRequested) {
                    // either the widget has been closed in the meantime
                    // or there has been a new call to `update`
                    return;
                }
            }
            this.show(resolvedContent, focus, options);
        });
    }
    show(content, focus, options) {
        const oldHoverWidget = this._hoverWidget;
        if (this.hasContent(content)) {
            const hoverOptions = Object.assign({ content, target: this.target, showPointer: this.hoverDelegate.placement === 'element', hoverPosition: 2 /* HoverPosition.BELOW */, skipFadeInAnimation: !this.fadeInAnimation || !!oldHoverWidget }, options);
            this._hoverWidget = this.hoverDelegate.showHover(hoverOptions, focus);
        }
        oldHoverWidget === null || oldHoverWidget === void 0 ? void 0 : oldHoverWidget.dispose();
    }
    hasContent(content) {
        if (!content) {
            return false;
        }
        if (isMarkdownString(content)) {
            return !!content.value;
        }
        return true;
    }
    get isDisposed() {
        var _a;
        return (_a = this._hoverWidget) === null || _a === void 0 ? void 0 : _a.isDisposed;
    }
    dispose() {
        var _a, _b;
        (_a = this._hoverWidget) === null || _a === void 0 ? void 0 : _a.dispose();
        (_b = this._cancellationTokenSource) === null || _b === void 0 ? void 0 : _b.dispose(true);
        this._cancellationTokenSource = undefined;
    }
}
function setupCustomHover(hoverDelegate, htmlElement, content, options) {
    let hoverPreparation;
    let hoverWidget;
    const hideHover = (disposeWidget, disposePreparation) => {
        var _a;
        if (disposeWidget) {
            hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.dispose();
            hoverWidget = undefined;
        }
        if (disposePreparation) {
            hoverPreparation === null || hoverPreparation === void 0 ? void 0 : hoverPreparation.dispose();
            hoverPreparation = undefined;
        }
        (_a = hoverDelegate.onDidHideHover) === null || _a === void 0 ? void 0 : _a.call(hoverDelegate);
    };
    const triggerShowHover = (delay, focus, target) => {
        return new TimeoutTimer(() => iconLabelHover_awaiter(this, void 0, void 0, function* () {
            if (!hoverWidget || hoverWidget.isDisposed) {
                hoverWidget = new UpdatableHoverWidget(hoverDelegate, target || htmlElement, delay > 0);
                yield hoverWidget.update(content, focus, options);
            }
        }), delay);
    };
    const onMouseOver = () => {
        if (hoverPreparation) {
            return;
        }
        const toDispose = new DisposableStore();
        const onMouseLeave = (e) => hideHover(false, e.fromElement === htmlElement);
        toDispose.add(addDisposableListener(htmlElement, EventType.MOUSE_LEAVE, onMouseLeave, true));
        const onMouseDown = () => hideHover(true, true);
        toDispose.add(addDisposableListener(htmlElement, EventType.MOUSE_DOWN, onMouseDown, true));
        const target = {
            targetElements: [htmlElement],
            dispose: () => { }
        };
        if (hoverDelegate.placement === undefined || hoverDelegate.placement === 'mouse') {
            // track the mouse position
            const onMouseMove = (e) => {
                target.x = e.x + 10;
                if ((e.target instanceof HTMLElement) && e.target.classList.contains('action-label')) {
                    hideHover(true, true);
                }
            };
            toDispose.add(addDisposableListener(htmlElement, EventType.MOUSE_MOVE, onMouseMove, true));
        }
        toDispose.add(triggerShowHover(hoverDelegate.delay, false, target));
        hoverPreparation = toDispose;
    };
    const mouseOverDomEmitter = addDisposableListener(htmlElement, EventType.MOUSE_OVER, onMouseOver, true);
    const hover = {
        show: focus => {
            hideHover(false, true); // terminate a ongoing mouse over preparation
            triggerShowHover(0, focus); // show hover immediately
        },
        hide: () => {
            hideHover(true, true);
        },
        update: (newContent, hoverOptions) => iconLabelHover_awaiter(this, void 0, void 0, function* () {
            content = newContent;
            yield (hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.update(content, undefined, hoverOptions));
        }),
        dispose: () => {
            mouseOverDomEmitter.dispose();
            hideHover(true, true);
        }
    };
    return hover;
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/actionbar/actionbar.css
var actionbar = __webpack_require__(13615);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/actionbar/actionbar.css

      
      
      
      
      
      
      
      
      

var actionbar_options = {};

actionbar_options.styleTagTransform = (styleTagTransform_default());
actionbar_options.setAttributes = (setAttributesWithoutAttributes_default());

      actionbar_options.insert = insertBySelector_default().bind(null, "head");
    
actionbar_options.domAPI = (styleDomAPI_default());
actionbar_options.insertStyleElement = (insertStyleElement_default());

var actionbar_update = injectStylesIntoStyleTag_default()(actionbar/* default */.A, actionbar_options);




       /* harmony default export */ const actionbar_actionbar = (actionbar/* default */.A && actionbar/* default */.A.locals ? actionbar/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/actionbar/actionViewItems.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/











class BaseActionViewItem extends Disposable {
    constructor(context, action, options = {}) {
        super();
        this.options = options;
        this._context = context || this;
        this._action = action;
        if (action instanceof Action) {
            this._register(action.onDidChange(event => {
                if (!this.element) {
                    // we have not been rendered yet, so there
                    // is no point in updating the UI
                    return;
                }
                this.handleActionChangeEvent(event);
            }));
        }
    }
    get action() {
        return this._action;
    }
    handleActionChangeEvent(event) {
        if (event.enabled !== undefined) {
            this.updateEnabled();
        }
        if (event.checked !== undefined) {
            this.updateChecked();
        }
        if (event.class !== undefined) {
            this.updateClass();
        }
        if (event.label !== undefined) {
            this.updateLabel();
            this.updateTooltip();
        }
        if (event.tooltip !== undefined) {
            this.updateTooltip();
        }
    }
    get actionRunner() {
        if (!this._actionRunner) {
            this._actionRunner = this._register(new ActionRunner());
        }
        return this._actionRunner;
    }
    set actionRunner(actionRunner) {
        this._actionRunner = actionRunner;
    }
    getAction() {
        return this._action;
    }
    isEnabled() {
        return this._action.enabled;
    }
    setActionContext(newContext) {
        this._context = newContext;
    }
    render(container) {
        const element = this.element = container;
        this._register(Gesture.addTarget(container));
        const enableDragging = this.options && this.options.draggable;
        if (enableDragging) {
            container.draggable = true;
            if (browser_isFirefox) {
                // Firefox: requires to set a text data transfer to get going
                this._register(addDisposableListener(container, EventType.DRAG_START, e => { var _a; return (_a = e.dataTransfer) === null || _a === void 0 ? void 0 : _a.setData(DataTransfers.TEXT, this._action.label); }));
            }
        }
        this._register(addDisposableListener(element, touch_EventType.Tap, e => this.onClick(e, true))); // Preserve focus on tap #125470
        this._register(addDisposableListener(element, EventType.MOUSE_DOWN, e => {
            if (!enableDragging) {
                EventHelper.stop(e, true); // do not run when dragging is on because that would disable it
            }
            if (this._action.enabled && e.button === 0) {
                element.classList.add('active');
            }
        }));
        if (isMacintosh) {
            // macOS: allow to trigger the button when holding Ctrl+key and pressing the
            // main mouse button. This is for scenarios where e.g. some interaction forces
            // the Ctrl+key to be pressed and hold but the user still wants to interact
            // with the actions (for example quick access in quick navigation mode).
            this._register(addDisposableListener(element, EventType.CONTEXT_MENU, e => {
                if (e.button === 0 && e.ctrlKey === true) {
                    this.onClick(e);
                }
            }));
        }
        this._register(addDisposableListener(element, EventType.CLICK, e => {
            EventHelper.stop(e, true);
            // menus do not use the click event
            if (!(this.options && this.options.isMenu)) {
                this.onClick(e);
            }
        }));
        this._register(addDisposableListener(element, EventType.DBLCLICK, e => {
            EventHelper.stop(e, true);
        }));
        [EventType.MOUSE_UP, EventType.MOUSE_OUT].forEach(event => {
            this._register(addDisposableListener(element, event, e => {
                EventHelper.stop(e);
                element.classList.remove('active');
            }));
        });
    }
    onClick(event, preserveFocus = false) {
        var _a;
        EventHelper.stop(event, true);
        const context = isUndefinedOrNull(this._context) ? ((_a = this.options) === null || _a === void 0 ? void 0 : _a.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');
        }
    }
    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;
    }
    updateEnabled() {
        // implement in subclass
    }
    updateLabel() {
        // implement in subclass
    }
    getTooltip() {
        return this.getAction().tooltip;
    }
    updateTooltip() {
        var _a;
        if (!this.element) {
            return;
        }
        const title = (_a = this.getTooltip()) !== null && _a !== void 0 ? _a : '';
        this.element.setAttribute('aria-label', title);
        if (!this.options.hoverDelegate) {
            this.element.title = title;
        }
        else {
            this.element.title = '';
            if (!this.customHover) {
                this.customHover = setupCustomHover(this.options.hoverDelegate, this.element, title);
                this._store.add(this.customHover);
            }
            else {
                this.customHover.update(title);
            }
        }
    }
    updateClass() {
        // implement in subclass
    }
    updateChecked() {
        // implement in subclass
    }
    dispose() {
        if (this.element) {
            this.element.remove();
            this.element = undefined;
        }
        super.dispose();
    }
}
class ActionViewItem extends BaseActionViewItem {
    constructor(context, action, options = {}) {
        super(context, action, options);
        this.options = options;
        this.options.icon = options.icon !== undefined ? options.icon : false;
        this.options.label = options.label !== undefined ? options.label : true;
        this.cssClass = '';
    }
    render(container) {
        super.render(container);
        if (this.element) {
            this.label = append(this.element, dom_$('a.action-label'));
        }
        if (this.label) {
            if (this._action.id === Separator.ID) {
                this.label.setAttribute('role', 'presentation'); // A separator is a presentation item
            }
            else {
                if (this.options.isMenu) {
                    this.label.setAttribute('role', 'menuitem');
                }
                else {
                    this.label.setAttribute('role', 'button');
                }
            }
        }
        if (this.options.label && this.options.keybinding && this.element) {
            append(this.element, dom_$('span.keybinding')).textContent = this.options.keybinding;
        }
        this.updateClass();
        this.updateLabel();
        this.updateTooltip();
        this.updateEnabled();
        this.updateChecked();
    }
    // 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.label) {
            this.label.tabIndex = 0;
            this.label.focus();
        }
    }
    blur() {
        if (this.label) {
            this.label.tabIndex = -1;
        }
    }
    setFocusable(focusable) {
        if (this.label) {
            this.label.tabIndex = focusable ? 0 : -1;
        }
    }
    updateLabel() {
        if (this.options.label && this.label) {
            this.label.textContent = this.getAction().label;
        }
    }
    getTooltip() {
        let title = null;
        if (this.getAction().tooltip) {
            title = this.getAction().tooltip;
        }
        else if (!this.options.label && this.getAction().label && this.options.icon) {
            title = this.getAction().label;
            if (this.options.keybinding) {
                title = localize({ key: 'titleLabel', comment: ['action title', 'action keybinding'] }, "{0} ({1})", title, this.options.keybinding);
            }
        }
        return title !== null && title !== void 0 ? title : undefined;
    }
    updateClass() {
        var _a;
        if (this.cssClass && this.label) {
            this.label.classList.remove(...this.cssClass.split(' '));
        }
        if (this.options.icon) {
            this.cssClass = this.getAction().class;
            if (this.label) {
                this.label.classList.add('codicon');
                if (this.cssClass) {
                    this.label.classList.add(...this.cssClass.split(' '));
                }
            }
            this.updateEnabled();
        }
        else {
            (_a = this.label) === null || _a === void 0 ? void 0 : _a.classList.remove('codicon');
        }
    }
    updateEnabled() {
        var _a, _b;
        if (this.getAction().enabled) {
            if (this.label) {
                this.label.removeAttribute('aria-disabled');
                this.label.classList.remove('disabled');
            }
            (_a = this.element) === null || _a === void 0 ? void 0 : _a.classList.remove('disabled');
        }
        else {
            if (this.label) {
                this.label.setAttribute('aria-disabled', 'true');
                this.label.classList.add('disabled');
            }
            (_b = this.element) === null || _b === void 0 ? void 0 : _b.classList.add('disabled');
        }
    }
    updateChecked() {
        if (this.label) {
            if (this.getAction().checked) {
                this.label.classList.add('checked');
            }
            else {
                this.label.classList.remove('checked');
            }
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/actionbar/actionbar.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var actionbar_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};








class ActionBar extends Disposable {
    constructor(container, options = {}) {
        var _a, _b, _c, _d, _e, _f;
        super();
        // Trigger Key Tracking
        this.triggerKeyDown = false;
        this.focusable = true;
        this._onDidBlur = this._register(new Emitter());
        this.onDidBlur = this._onDidBlur.event;
        this._onDidCancel = this._register(new Emitter({ onFirstListenerAdd: () => this.cancelHasListener = true }));
        this.onDidCancel = this._onDidCancel.event;
        this.cancelHasListener = false;
        this._onDidRun = this._register(new Emitter());
        this.onDidRun = this._onDidRun.event;
        this._onBeforeRun = this._register(new Emitter());
        this.onBeforeRun = this._onBeforeRun.event;
        this.options = options;
        this._context = (_a = options.context) !== null && _a !== void 0 ? _a : null;
        this._orientation = (_b = this.options.orientation) !== null && _b !== void 0 ? _b : 0 /* ActionsOrientation.HORIZONTAL */;
        this._triggerKeys = {
            keyDown: (_d = (_c = this.options.triggerKeys) === null || _c === void 0 ? void 0 : _c.keyDown) !== null && _d !== void 0 ? _d : false,
            keys: (_f = (_e = this.options.triggerKeys) === null || _e === void 0 ? void 0 : _e.keys) !== null && _f !== void 0 ? _f : [3 /* KeyCode.Enter */, 10 /* KeyCode.Space */]
        };
        if (this.options.actionRunner) {
            this._actionRunner = this.options.actionRunner;
        }
        else {
            this._actionRunner = new ActionRunner();
            this._register(this._actionRunner);
        }
        this._register(this._actionRunner.onDidRun(e => this._onDidRun.fire(e)));
        this._register(this._actionRunner.onBeforeRun(e => this._onBeforeRun.fire(e)));
        this._actionIds = [];
        this.viewItems = [];
        this.viewItemDisposables = new Map();
        this.focusedItem = undefined;
        this.domNode = document.createElement('div');
        this.domNode.className = 'monaco-action-bar';
        if (options.animated !== false) {
            this.domNode.classList.add('animated');
        }
        let previousKeys;
        let nextKeys;
        switch (this._orientation) {
            case 0 /* ActionsOrientation.HORIZONTAL */:
                previousKeys = [15 /* KeyCode.LeftArrow */];
                nextKeys = [17 /* KeyCode.RightArrow */];
                break;
            case 1 /* ActionsOrientation.VERTICAL */:
                previousKeys = [16 /* KeyCode.UpArrow */];
                nextKeys = [18 /* KeyCode.DownArrow */];
                this.domNode.className += ' vertical';
                break;
        }
        this._register(addDisposableListener(this.domNode, EventType.KEY_DOWN, e => {
            const event = new StandardKeyboardEvent(e);
            let eventHandled = true;
            const focusedItem = typeof this.focusedItem === 'number' ? this.viewItems[this.focusedItem] : undefined;
            if (previousKeys && (event.equals(previousKeys[0]) || event.equals(previousKeys[1]))) {
                eventHandled = this.focusPrevious();
            }
            else if (nextKeys && (event.equals(nextKeys[0]) || event.equals(nextKeys[1]))) {
                eventHandled = this.focusNext();
            }
            else if (event.equals(9 /* KeyCode.Escape */) && this.cancelHasListener) {
                this._onDidCancel.fire();
            }
            else if (event.equals(14 /* KeyCode.Home */)) {
                eventHandled = this.focusFirst();
            }
            else if (event.equals(13 /* KeyCode.End */)) {
                eventHandled = this.focusLast();
            }
            else if (event.equals(2 /* KeyCode.Tab */) && focusedItem instanceof BaseActionViewItem && focusedItem.trapsArrowNavigation) {
                eventHandled = this.focusNext();
            }
            else if (this.isTriggerKeyEvent(event)) {
                // Staying out of the else branch even if not triggered
                if (this._triggerKeys.keyDown) {
                    this.doTrigger(event);
                }
                else {
                    this.triggerKeyDown = true;
                }
            }
            else {
                eventHandled = false;
            }
            if (eventHandled) {
                event.preventDefault();
                event.stopPropagation();
            }
        }));
        this._register(addDisposableListener(this.domNode, EventType.KEY_UP, e => {
            const event = new StandardKeyboardEvent(e);
            // Run action on Enter/Space
            if (this.isTriggerKeyEvent(event)) {
                if (!this._triggerKeys.keyDown && this.triggerKeyDown) {
                    this.triggerKeyDown = false;
                    this.doTrigger(event);
                }
                event.preventDefault();
                event.stopPropagation();
            }
            // Recompute focused item
            else if (event.equals(2 /* KeyCode.Tab */) || event.equals(1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */)) {
                this.updateFocusedItem();
            }
        }));
        this.focusTracker = this._register(trackFocus(this.domNode));
        this._register(this.focusTracker.onDidBlur(() => {
            if (getActiveElement() === this.domNode || !isAncestor(getActiveElement(), this.domNode)) {
                this._onDidBlur.fire();
                this.focusedItem = undefined;
                this.previouslyFocusedItem = undefined;
                this.triggerKeyDown = false;
            }
        }));
        this._register(this.focusTracker.onDidFocus(() => this.updateFocusedItem()));
        this.actionsList = document.createElement('ul');
        this.actionsList.className = 'actions-container';
        this.actionsList.setAttribute('role', this.options.ariaRole || 'toolbar');
        if (this.options.ariaLabel) {
            this.actionsList.setAttribute('aria-label', this.options.ariaLabel);
        }
        this.domNode.appendChild(this.actionsList);
        container.appendChild(this.domNode);
    }
    refreshRole() {
        if (this.length() >= 2) {
            this.actionsList.setAttribute('role', this.options.ariaRole || 'toolbar');
        }
        else {
            this.actionsList.setAttribute('role', 'presentation');
        }
    }
    // 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.focusable = focusable;
        if (this.focusable) {
            const firstEnabled = this.viewItems.find(vi => vi instanceof BaseActionViewItem && vi.isEnabled());
            if (firstEnabled instanceof BaseActionViewItem) {
                firstEnabled.setFocusable(true);
            }
        }
        else {
            this.viewItems.forEach(vi => {
                if (vi instanceof BaseActionViewItem) {
                    vi.setFocusable(false);
                }
            });
        }
    }
    isTriggerKeyEvent(event) {
        let ret = false;
        this._triggerKeys.keys.forEach(keyCode => {
            ret = ret || event.equals(keyCode);
        });
        return ret;
    }
    updateFocusedItem() {
        for (let i = 0; i < this.actionsList.children.length; i++) {
            const elem = this.actionsList.children[i];
            if (isAncestor(getActiveElement(), elem)) {
                this.focusedItem = i;
                break;
            }
        }
    }
    get context() {
        return this._context;
    }
    set context(context) {
        this._context = context;
        this.viewItems.forEach(i => i.setActionContext(context));
    }
    get actionRunner() {
        return this._actionRunner;
    }
    set actionRunner(actionRunner) {
        if (actionRunner) {
            this._actionRunner = actionRunner;
            this.viewItems.forEach(item => item.actionRunner = actionRunner);
        }
    }
    getContainer() {
        return this.domNode;
    }
    push(arg, options = {}) {
        const actions = Array.isArray(arg) ? arg : [arg];
        let index = isNumber(options.index) ? options.index : null;
        actions.forEach((action) => {
            const actionViewItemElement = document.createElement('li');
            actionViewItemElement.className = 'action-item';
            actionViewItemElement.setAttribute('role', 'presentation');
            let item;
            if (this.options.actionViewItemProvider) {
                item = this.options.actionViewItemProvider(action);
            }
            if (!item) {
                item = new ActionViewItem(this.context, action, Object.assign({ hoverDelegate: this.options.hoverDelegate }, options));
            }
            // Prevent native context menu on actions
            if (!this.options.allowContextMenu) {
                this.viewItemDisposables.set(item, addDisposableListener(actionViewItemElement, EventType.CONTEXT_MENU, (e) => {
                    EventHelper.stop(e, true);
                }));
            }
            item.actionRunner = this._actionRunner;
            item.setActionContext(this.context);
            item.render(actionViewItemElement);
            if (this.focusable && item instanceof BaseActionViewItem && this.viewItems.length === 0) {
                // We need to allow for the first enabled item to be focused on using tab navigation #106441
                item.setFocusable(true);
            }
            if (index === null || index < 0 || index >= this.actionsList.children.length) {
                this.actionsList.appendChild(actionViewItemElement);
                this.viewItems.push(item);
                this._actionIds.push(action.id);
            }
            else {
                this.actionsList.insertBefore(actionViewItemElement, this.actionsList.children[index]);
                this.viewItems.splice(index, 0, item);
                this._actionIds.splice(index, 0, action.id);
                index++;
            }
        });
        if (typeof this.focusedItem === 'number') {
            // After a clear actions might be re-added to simply toggle some actions. We should preserve focus #97128
            this.focus(this.focusedItem);
        }
        this.refreshRole();
    }
    clear() {
        dispose(this.viewItems);
        this.viewItemDisposables.forEach(d => d.dispose());
        this.viewItemDisposables.clear();
        this.viewItems = [];
        this._actionIds = [];
        clearNode(this.actionsList);
        this.refreshRole();
    }
    length() {
        return this.viewItems.length;
    }
    focus(arg) {
        let selectFirst = false;
        let index = undefined;
        if (arg === undefined) {
            selectFirst = true;
        }
        else if (typeof arg === 'number') {
            index = arg;
        }
        else if (typeof arg === 'boolean') {
            selectFirst = arg;
        }
        if (selectFirst && typeof this.focusedItem === 'undefined') {
            const firstEnabled = this.viewItems.findIndex(item => item.isEnabled());
            // Focus the first enabled item
            this.focusedItem = firstEnabled === -1 ? undefined : firstEnabled;
            this.updateFocus(undefined, undefined, true);
        }
        else {
            if (index !== undefined) {
                this.focusedItem = index;
            }
            this.updateFocus(undefined, undefined, true);
        }
    }
    focusFirst() {
        this.focusedItem = this.length() - 1;
        return this.focusNext(true);
    }
    focusLast() {
        this.focusedItem = 0;
        return this.focusPrevious(true);
    }
    focusNext(forceLoop) {
        if (typeof this.focusedItem === 'undefined') {
            this.focusedItem = this.viewItems.length - 1;
        }
        else if (this.viewItems.length <= 1) {
            return false;
        }
        const startIndex = this.focusedItem;
        let item;
        do {
            if (!forceLoop && this.options.preventLoopNavigation && this.focusedItem + 1 >= this.viewItems.length) {
                this.focusedItem = startIndex;
                return false;
            }
            this.focusedItem = (this.focusedItem + 1) % this.viewItems.length;
            item = this.viewItems[this.focusedItem];
        } while (this.focusedItem !== startIndex && ((this.options.focusOnlyEnabledItems && !item.isEnabled()) || item.action.id === Separator.ID));
        this.updateFocus();
        return true;
    }
    focusPrevious(forceLoop) {
        if (typeof this.focusedItem === 'undefined') {
            this.focusedItem = 0;
        }
        else if (this.viewItems.length <= 1) {
            return false;
        }
        const startIndex = this.focusedItem;
        let item;
        do {
            this.focusedItem = this.focusedItem - 1;
            if (this.focusedItem < 0) {
                if (!forceLoop && this.options.preventLoopNavigation) {
                    this.focusedItem = startIndex;
                    return false;
                }
                this.focusedItem = this.viewItems.length - 1;
            }
            item = this.viewItems[this.focusedItem];
        } while (this.focusedItem !== startIndex && ((this.options.focusOnlyEnabledItems && !item.isEnabled()) || item.action.id === Separator.ID));
        this.updateFocus(true);
        return true;
    }
    updateFocus(fromRight, preventScroll, forceFocus = false) {
        var _a;
        if (typeof this.focusedItem === 'undefined') {
            this.actionsList.focus({ preventScroll });
        }
        if (this.previouslyFocusedItem !== undefined && this.previouslyFocusedItem !== this.focusedItem) {
            (_a = this.viewItems[this.previouslyFocusedItem]) === null || _a === void 0 ? void 0 : _a.blur();
        }
        const actionViewItem = this.focusedItem !== undefined && this.viewItems[this.focusedItem];
        if (actionViewItem) {
            let focusItem = true;
            if (!isFunction(actionViewItem.focus)) {
                focusItem = false;
            }
            if (this.options.focusOnlyEnabledItems && isFunction(actionViewItem.isEnabled) && !actionViewItem.isEnabled()) {
                focusItem = false;
            }
            if (actionViewItem.action.id === Separator.ID) {
                focusItem = false;
            }
            if (!focusItem) {
                this.actionsList.focus({ preventScroll });
                this.previouslyFocusedItem = undefined;
            }
            else if (forceFocus || this.previouslyFocusedItem !== this.focusedItem) {
                actionViewItem.focus(fromRight);
                this.previouslyFocusedItem = this.focusedItem;
            }
        }
    }
    doTrigger(event) {
        if (typeof this.focusedItem === 'undefined') {
            return; //nothing to focus
        }
        // trigger action
        const actionViewItem = this.viewItems[this.focusedItem];
        if (actionViewItem instanceof BaseActionViewItem) {
            const context = (actionViewItem._context === null || actionViewItem._context === undefined) ? event : actionViewItem._context;
            this.run(actionViewItem._action, context);
        }
    }
    run(action, context) {
        return actionbar_awaiter(this, void 0, void 0, function* () {
            yield this._actionRunner.run(action, context);
        });
    }
    dispose() {
        dispose(this.viewItems);
        this.viewItems = [];
        this._actionIds = [];
        this.getContainer().remove();
        super.dispose();
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/peekView/browser/media/peekViewWidget.css
var peekViewWidget = __webpack_require__(61385);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/peekView/browser/media/peekViewWidget.css

      
      
      
      
      
      
      
      
      

var peekViewWidget_options = {};

peekViewWidget_options.styleTagTransform = (styleTagTransform_default());
peekViewWidget_options.setAttributes = (setAttributesWithoutAttributes_default());

      peekViewWidget_options.insert = insertBySelector_default().bind(null, "head");
    
peekViewWidget_options.domAPI = (styleDomAPI_default());
peekViewWidget_options.insertStyleElement = (insertStyleElement_default());

var peekViewWidget_update = injectStylesIntoStyleTag_default()(peekViewWidget/* default */.A, peekViewWidget_options);




       /* harmony default export */ const media_peekViewWidget = (peekViewWidget/* default */.A && peekViewWidget/* default */.A.locals ? peekViewWidget/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/markerDecorations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const IMarkerDecorationsService = createDecorator('markerDecorationsService');

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/services/markerDecorations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var markerDecorations_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var markerDecorations_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};


let MarkerDecorationsContribution = class MarkerDecorationsContribution {
    constructor(_editor, _markerDecorationsService) {
        // Doesn't do anything, just requires `IMarkerDecorationsService` to make sure it gets instantiated
    }
    dispose() {
    }
};
MarkerDecorationsContribution.ID = 'editor.contrib.markerDecorations';
MarkerDecorationsContribution = markerDecorations_decorate([
    markerDecorations_param(1, IMarkerDecorationsService)
], MarkerDecorationsContribution);

registerEditorContribution(MarkerDecorationsContribution.ID, MarkerDecorationsContribution);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/widget/media/editor.css
var editor = __webpack_require__(89818);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/widget/media/editor.css

      
      
      
      
      
      
      
      
      

var editor_options = {};

editor_options.styleTagTransform = (styleTagTransform_default());
editor_options.setAttributes = (setAttributesWithoutAttributes_default());

      editor_options.insert = insertBySelector_default().bind(null, "head");
    
editor_options.domAPI = (styleDomAPI_default());
editor_options.insertStyleElement = (insertStyleElement_default());

var editor_update = injectStylesIntoStyleTag_default()(editor/* default */.A, editor_options);




       /* harmony default export */ const media_editor = (editor/* default */.A && editor/* default */.A.locals ? editor/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/config/elementSizeObserver.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class ElementSizeObserver extends Disposable {
    constructor(referenceDomElement, dimension) {
        super();
        this._onDidChange = this._register(new Emitter());
        this.onDidChange = this._onDidChange.event;
        this._referenceDomElement = referenceDomElement;
        this._width = -1;
        this._height = -1;
        this._resizeObserver = null;
        this.measureReferenceDomElement(false, dimension);
    }
    dispose() {
        this.stopObserving();
        super.dispose();
    }
    getWidth() {
        return this._width;
    }
    getHeight() {
        return this._height;
    }
    startObserving() {
        if (!this._resizeObserver && this._referenceDomElement) {
            this._resizeObserver = new ResizeObserver((entries) => {
                if (entries && entries[0] && entries[0].contentRect) {
                    this.observe({ width: entries[0].contentRect.width, height: entries[0].contentRect.height });
                }
                else {
                    this.observe();
                }
            });
            this._resizeObserver.observe(this._referenceDomElement);
        }
    }
    stopObserving() {
        if (this._resizeObserver) {
            this._resizeObserver.disconnect();
            this._resizeObserver = null;
        }
    }
    observe(dimension) {
        this.measureReferenceDomElement(true, dimension);
    }
    measureReferenceDomElement(emitEvent, dimension) {
        let observedWidth = 0;
        let observedHeight = 0;
        if (dimension) {
            observedWidth = dimension.width;
            observedHeight = dimension.height;
        }
        else if (this._referenceDomElement) {
            observedWidth = this._referenceDomElement.clientWidth;
            observedHeight = this._referenceDomElement.clientHeight;
        }
        observedWidth = Math.max(5, observedWidth);
        observedHeight = Math.max(5, observedHeight);
        if (this._width !== observedWidth || this._height !== observedHeight) {
            this._width = observedWidth;
            this._height = observedHeight;
            if (emitEvent) {
                this._onDidChange.fire();
            }
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/config/domFontInfo.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

function applyFontInfo(domNode, fontInfo) {
    if (domNode instanceof FastDomNode) {
        domNode.setFontFamily(fontInfo.getMassagedFontFamily());
        domNode.setFontWeight(fontInfo.fontWeight);
        domNode.setFontSize(fontInfo.fontSize);
        domNode.setFontFeatureSettings(fontInfo.fontFeatureSettings);
        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.lineHeight = fontInfo.lineHeight + 'px';
        domNode.style.letterSpacing = fontInfo.letterSpacing + 'px';
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/config/charWidthReader.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class CharWidthRequest {
    constructor(chr, type) {
        this.chr = chr;
        this.type = type;
        this.width = 0;
    }
    fulfill(width) {
        this.width = width;
    }
}
class DomCharWidthReader {
    constructor(bareFontInfo, requests) {
        this._bareFontInfo = bareFontInfo;
        this._requests = requests;
        this._container = null;
        this._testElements = null;
    }
    read() {
        // Create a test container with all these test elements
        this._createDomElements();
        // Add the container to the DOM
        document.body.appendChild(this._container);
        // Read character widths
        this._readFromDomElements();
        // Remove the container from the DOM
        document.body.removeChild(this._container);
        this._container = null;
        this._testElements = null;
    }
    _createDomElements() {
        const container = document.createElement('div');
        container.style.position = 'absolute';
        container.style.top = '-50000px';
        container.style.width = '50000px';
        const regularDomNode = document.createElement('div');
        applyFontInfo(regularDomNode, this._bareFontInfo);
        container.appendChild(regularDomNode);
        const boldDomNode = document.createElement('div');
        applyFontInfo(boldDomNode, this._bareFontInfo);
        boldDomNode.style.fontWeight = 'bold';
        container.appendChild(boldDomNode);
        const italicDomNode = document.createElement('div');
        applyFontInfo(italicDomNode, this._bareFontInfo);
        italicDomNode.style.fontStyle = 'italic';
        container.appendChild(italicDomNode);
        const testElements = [];
        for (const request of this._requests) {
            let parent;
            if (request.type === 0 /* CharWidthRequestType.Regular */) {
                parent = regularDomNode;
            }
            if (request.type === 2 /* CharWidthRequestType.Bold */) {
                parent = boldDomNode;
            }
            if (request.type === 1 /* CharWidthRequestType.Italic */) {
                parent = italicDomNode;
            }
            parent.appendChild(document.createElement('br'));
            const testElement = document.createElement('span');
            DomCharWidthReader._render(testElement, request);
            parent.appendChild(testElement);
            testElements.push(testElement);
        }
        this._container = container;
        this._testElements = testElements;
    }
    static _render(testElement, request) {
        if (request.chr === ' ') {
            let htmlString = '\u00a0';
            // Repeat character 256 (2^8) times
            for (let i = 0; i < 8; i++) {
                htmlString += htmlString;
            }
            testElement.innerText = htmlString;
        }
        else {
            let testString = request.chr;
            // Repeat character 256 (2^8) times
            for (let i = 0; i < 8; i++) {
                testString += testString;
            }
            testElement.textContent = testString;
        }
    }
    _readFromDomElements() {
        for (let i = 0, len = this._requests.length; i < len; i++) {
            const request = this._requests[i];
            const testElement = this._testElements[i];
            request.fulfill(testElement.offsetWidth / 256);
        }
    }
}
function readCharWidths(bareFontInfo, requests) {
    const reader = new DomCharWidthReader(bareFontInfo, requests);
    reader.read();
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/config/editorZoom.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const EditorZoom = new class {
    constructor() {
        this._zoomLevel = 0;
        this._onDidChangeZoomLevel = new Emitter();
        this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;
    }
    getZoomLevel() {
        return this._zoomLevel;
    }
    setZoomLevel(zoomLevel) {
        zoomLevel = Math.min(Math.max(-5, zoomLevel), 20);
        if (this._zoomLevel === zoomLevel) {
            return;
        }
        this._zoomLevel = zoomLevel;
        this._onDidChangeZoomLevel.fire(this._zoomLevel);
    }
};

;// ../../node_modules/monaco-editor/esm/vs/editor/common/config/fontInfo.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



/**
 * Determined from empirical observations.
 * @internal
 */
const GOLDEN_LINE_HEIGHT_RATIO = isMacintosh ? 1.5 : 1.35;
/**
 * @internal
 */
const MINIMUM_LINE_HEIGHT = 8;
class BareFontInfo {
    /**
     * @internal
     */
    constructor(opts) {
        this._bareFontInfoBrand = undefined;
        this.pixelRatio = opts.pixelRatio;
        this.fontFamily = String(opts.fontFamily);
        this.fontWeight = String(opts.fontWeight);
        this.fontSize = opts.fontSize;
        this.fontFeatureSettings = opts.fontFeatureSettings;
        this.lineHeight = opts.lineHeight | 0;
        this.letterSpacing = opts.letterSpacing;
    }
    /**
     * @internal
     */
    static createFromValidatedSettings(options, pixelRatio, ignoreEditorZoom) {
        const fontFamily = options.get(45 /* EditorOption.fontFamily */);
        const fontWeight = options.get(49 /* EditorOption.fontWeight */);
        const fontSize = options.get(48 /* EditorOption.fontSize */);
        const fontFeatureSettings = options.get(47 /* EditorOption.fontLigatures */);
        const lineHeight = options.get(61 /* EditorOption.lineHeight */);
        const letterSpacing = options.get(58 /* EditorOption.letterSpacing */);
        return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom);
    }
    /**
     * @internal
     */
    static _create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom) {
        if (lineHeight === 0) {
            lineHeight = GOLDEN_LINE_HEIGHT_RATIO * fontSize;
        }
        else if (lineHeight < MINIMUM_LINE_HEIGHT) {
            // Values too small to be line heights in pixels are in ems.
            lineHeight = lineHeight * fontSize;
        }
        // Enforce integer, minimum constraints
        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;
        return new BareFontInfo({
            pixelRatio: pixelRatio,
            fontFamily: fontFamily,
            fontWeight: fontWeight,
            fontSize: fontSize,
            fontFeatureSettings: fontFeatureSettings,
            lineHeight: lineHeight,
            letterSpacing: letterSpacing
        });
    }
    /**
     * @internal
     */
    getId() {
        return `${this.pixelRatio}-${this.fontFamily}-${this.fontWeight}-${this.fontSize}-${this.fontFeatureSettings}-${this.lineHeight}-${this.letterSpacing}`;
    }
    /**
     * @internal
     */
    getMassagedFontFamily() {
        const fallbackFontFamily = EDITOR_FONT_DEFAULTS.fontFamily;
        const fontFamily = BareFontInfo._wrapInQuotes(this.fontFamily);
        if (fallbackFontFamily && this.fontFamily !== fallbackFontFamily) {
            return `${fontFamily}, ${fallbackFontFamily}`;
        }
        return fontFamily;
    }
    static _wrapInQuotes(fontFamily) {
        if (/[,"']/.test(fontFamily)) {
            // Looks like the font family might be already escaped
            return fontFamily;
        }
        if (/[+ ]/.test(fontFamily)) {
            // Wrap a font family using + or <space> with quotes
            return `"${fontFamily}"`;
        }
        return fontFamily;
    }
}
// change this whenever `FontInfo` members are changed
const SERIALIZED_FONT_INFO_VERSION = 1;
class FontInfo extends BareFontInfo {
    /**
     * @internal
     */
    constructor(opts, isTrusted) {
        super(opts);
        this._editorStylingBrand = undefined;
        this.version = SERIALIZED_FONT_INFO_VERSION;
        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.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);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/config/fontMeasurements.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class FontMeasurementsImpl extends Disposable {
    constructor() {
        super();
        this._onDidChange = this._register(new Emitter());
        this.onDidChange = this._onDidChange.event;
        this._cache = new FontMeasurementsCache();
        this._evictUntrustedReadingsTimeout = -1;
    }
    dispose() {
        if (this._evictUntrustedReadingsTimeout !== -1) {
            window.clearTimeout(this._evictUntrustedReadingsTimeout);
            this._evictUntrustedReadingsTimeout = -1;
        }
        super.dispose();
    }
    /**
     * Clear all cached font information and trigger a change event.
     */
    clearAllFontInfos() {
        this._cache = new FontMeasurementsCache();
        this._onDidChange.fire();
    }
    _writeToCache(item, value) {
        this._cache.put(item, value);
        if (!value.isTrusted && this._evictUntrustedReadingsTimeout === -1) {
            // Try reading again after some time
            this._evictUntrustedReadingsTimeout = window.setTimeout(() => {
                this._evictUntrustedReadingsTimeout = -1;
                this._evictUntrustedReadings();
            }, 5000);
        }
    }
    _evictUntrustedReadings() {
        const values = this._cache.getValues();
        let somethingRemoved = false;
        for (const item of values) {
            if (!item.isTrusted) {
                somethingRemoved = true;
                this._cache.remove(item);
            }
        }
        if (somethingRemoved) {
            this._onDidChange.fire();
        }
    }
    /**
     * Read font information.
     */
    readFontInfo(bareFontInfo) {
        if (!this._cache.has(bareFontInfo)) {
            let readConfig = this._actualReadFontInfo(bareFontInfo);
            if (readConfig.typicalHalfwidthCharacterWidth <= 2 || readConfig.typicalFullwidthCharacterWidth <= 2 || readConfig.spaceWidth <= 2 || readConfig.maxDigitWidth <= 2) {
                // Hey, it's Bug 14341 ... we couldn't read
                readConfig = new FontInfo({
                    pixelRatio: PixelRatio.value,
                    fontFamily: readConfig.fontFamily,
                    fontWeight: readConfig.fontWeight,
                    fontSize: readConfig.fontSize,
                    fontFeatureSettings: readConfig.fontFeatureSettings,
                    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._writeToCache(bareFontInfo, readConfig);
        }
        return this._cache.get(bareFontInfo);
    }
    _createRequest(chr, type, all, monospace) {
        const result = new CharWidthRequest(chr, type);
        all.push(result);
        monospace === null || monospace === void 0 ? void 0 : monospace.push(result);
        return result;
    }
    _actualReadFontInfo(bareFontInfo) {
        const all = [];
        const monospace = [];
        const typicalHalfwidthCharacter = this._createRequest('n', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const typicalFullwidthCharacter = this._createRequest('\uff4d', 0 /* CharWidthRequestType.Regular */, all, null);
        const space = this._createRequest(' ', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const digit0 = this._createRequest('0', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const digit1 = this._createRequest('1', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const digit2 = this._createRequest('2', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const digit3 = this._createRequest('3', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const digit4 = this._createRequest('4', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const digit5 = this._createRequest('5', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const digit6 = this._createRequest('6', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const digit7 = this._createRequest('7', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const digit8 = this._createRequest('8', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const digit9 = this._createRequest('9', 0 /* CharWidthRequestType.Regular */, all, monospace);
        // monospace test: used for whitespace rendering
        const rightwardsArrow = this._createRequest('→', 0 /* CharWidthRequestType.Regular */, all, monospace);
        const halfwidthRightwardsArrow = this._createRequest('￫', 0 /* CharWidthRequestType.Regular */, all, null);
        // U+00B7 - MIDDLE DOT
        const middot = this._createRequest('·', 0 /* CharWidthRequestType.Regular */, all, monospace);
        // U+2E31 - WORD SEPARATOR MIDDLE DOT
        const wsmiddotWidth = this._createRequest(String.fromCharCode(0x2E31), 0 /* CharWidthRequestType.Regular */, all, null);
        // monospace test: some characters
        const monospaceTestChars = '|/-_ilm%';
        for (let i = 0, len = monospaceTestChars.length; i < len; i++) {
            this._createRequest(monospaceTestChars.charAt(i), 0 /* CharWidthRequestType.Regular */, all, monospace);
            this._createRequest(monospaceTestChars.charAt(i), 1 /* CharWidthRequestType.Italic */, all, monospace);
            this._createRequest(monospaceTestChars.charAt(i), 2 /* CharWidthRequestType.Bold */, all, monospace);
        }
        readCharWidths(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 i = 1, len = monospace.length; isMonospace && i < len; i++) {
            const diff = referenceWidth - monospace[i].width;
            if (diff < -0.001 || diff > 0.001) {
                isMonospace = false;
                break;
            }
        }
        let canUseHalfwidthRightwardsArrow = true;
        if (isMonospace && halfwidthRightwardsArrow.width !== referenceWidth) {
            // using a halfwidth rightwards arrow would break monospace...
            canUseHalfwidthRightwardsArrow = false;
        }
        if (halfwidthRightwardsArrow.width > rightwardsArrow.width) {
            // using a halfwidth rightwards arrow would paint a larger arrow than a regular rightwards arrow
            canUseHalfwidthRightwardsArrow = false;
        }
        return new FontInfo({
            pixelRatio: PixelRatio.value,
            fontFamily: bareFontInfo.fontFamily,
            fontWeight: bareFontInfo.fontWeight,
            fontSize: bareFontInfo.fontSize,
            fontFeatureSettings: bareFontInfo.fontFeatureSettings,
            lineHeight: bareFontInfo.lineHeight,
            letterSpacing: bareFontInfo.letterSpacing,
            isMonospace: isMonospace,
            typicalHalfwidthCharacterWidth: typicalHalfwidthCharacter.width,
            typicalFullwidthCharacterWidth: typicalFullwidthCharacter.width,
            canUseHalfwidthRightwardsArrow: canUseHalfwidthRightwardsArrow,
            spaceWidth: space.width,
            middotWidth: middot.width,
            wsmiddotWidth: wsmiddotWidth.width,
            maxDigitWidth: maxDigitWidth
        }, true);
    }
}
class FontMeasurementsCache {
    constructor() {
        this._keys = Object.create(null);
        this._values = Object.create(null);
    }
    has(item) {
        const itemId = item.getId();
        return !!this._values[itemId];
    }
    get(item) {
        const itemId = item.getId();
        return this._values[itemId];
    }
    put(item, value) {
        const itemId = item.getId();
        this._keys[itemId] = item;
        this._values[itemId] = value;
    }
    remove(item) {
        const itemId = item.getId();
        delete this._keys[itemId];
        delete this._values[itemId];
    }
    getValues() {
        return Object.keys(this._keys).map(id => this._values[id]);
    }
}
const FontMeasurements = new FontMeasurementsImpl();

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/config/migrateOptions.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class EditorSettingMigration {
    constructor(key, migrate) {
        this.key = key;
        this.migrate = migrate;
    }
    apply(options) {
        const value = EditorSettingMigration._read(options, this.key);
        const read = (key) => EditorSettingMigration._read(options, key);
        const write = (key, value) => EditorSettingMigration._write(options, key, value);
        this.migrate(value, read, write);
    }
    static _read(source, key) {
        if (typeof source === 'undefined') {
            return undefined;
        }
        const firstDotIndex = key.indexOf('.');
        if (firstDotIndex >= 0) {
            const firstSegment = key.substring(0, firstDotIndex);
            return this._read(source[firstSegment], key.substring(firstDotIndex + 1));
        }
        return source[key];
    }
    static _write(target, key, value) {
        const firstDotIndex = key.indexOf('.');
        if (firstDotIndex >= 0) {
            const firstSegment = key.substring(0, firstDotIndex);
            target[firstSegment] = target[firstSegment] || {};
            this._write(target[firstSegment], key.substring(firstDotIndex + 1), value);
            return;
        }
        target[key] = value;
    }
}
EditorSettingMigration.items = [];
function registerEditorSettingMigration(key, migrate) {
    EditorSettingMigration.items.push(new EditorSettingMigration(key, migrate));
}
function registerSimpleEditorSettingMigration(key, values) {
    registerEditorSettingMigration(key, (value, read, write) => {
        if (typeof value !== 'undefined') {
            for (const [oldValue, newValue] of values) {
                if (value === oldValue) {
                    write(key, newValue);
                    return;
                }
            }
        }
    });
}
/**
 * Compatibility with old options
 */
function migrateOptions(options) {
    EditorSettingMigration.items.forEach(migration => migration.apply(options));
}
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']]);
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', undefined);
        if (typeof read('guides.indentation') === 'undefined') {
            write('guides.indentation', !!value);
        }
    }
});
registerEditorSettingMigration('highlightActiveIndentGuide', (value, read, write) => {
    if (typeof value !== 'undefined') {
        write('highlightActiveIndentGuide', undefined);
        if (typeof read('guides.highlightActiveIndentation') === 'undefined') {
            write('guides.highlightActiveIndentation', !!value);
        }
    }
});
const 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', undefined);
    }
});
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);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/platform/accessibility/common/accessibility.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


const IAccessibilityService = createDecorator('accessibilityService');
const CONTEXT_ACCESSIBILITY_MODE_ENABLED = new RawContextKey('accessibilityModeEnabled', false);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/config/editorConfiguration.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var editorConfiguration_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var editorConfiguration_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};














let EditorConfiguration = class EditorConfiguration extends Disposable {
    constructor(isSimpleWidget, options, container, _accessibilityService) {
        super();
        this._accessibilityService = _accessibilityService;
        this._onDidChange = this._register(new Emitter());
        this.onDidChange = this._onDidChange.event;
        this._onDidChangeFast = this._register(new Emitter());
        this.onDidChangeFast = this._onDidChangeFast.event;
        this._isDominatedByLongLines = false;
        this._viewLineCount = 1;
        this._lineNumbersDigitCount = 1;
        this._reservedHeight = 0;
        this._computeOptionsMemory = new ComputeOptionsMemory();
        this.isSimpleWidget = isSimpleWidget;
        this._containerObserver = this._register(new ElementSizeObserver(container, options.dimension));
        this._rawOptions = deepCloneAndMigrateOptions(options);
        this._validatedOptions = EditorOptionsUtil.validateOptions(this._rawOptions);
        this.options = this._computeOptions();
        if (this.options.get(10 /* EditorOption.automaticLayout */)) {
            this._containerObserver.startObserving();
        }
        this._register(EditorZoom.onDidChangeZoomLevel(() => this._recomputeOptions()));
        this._register(TabFocus.onDidChangeTabFocus(() => this._recomputeOptions()));
        this._register(this._containerObserver.onDidChange(() => this._recomputeOptions()));
        this._register(FontMeasurements.onDidChange(() => this._recomputeOptions()));
        this._register(PixelRatio.onDidChange(() => this._recomputeOptions()));
        this._register(this._accessibilityService.onDidChangeScreenReaderOptimized(() => this._recomputeOptions()));
    }
    _recomputeOptions() {
        const newOptions = this._computeOptions();
        const changeEvent = EditorOptionsUtil.checkEquals(this.options, newOptions);
        if (changeEvent === null) {
            // nothing changed!
            return;
        }
        this.options = newOptions;
        this._onDidChangeFast.fire(changeEvent);
        this._onDidChange.fire(changeEvent);
    }
    _computeOptions() {
        const partialEnv = this._readEnvConfiguration();
        const bareFontInfo = BareFontInfo.createFromValidatedSettings(this._validatedOptions, partialEnv.pixelRatio, this.isSimpleWidget);
        const fontInfo = this._readFontInfo(bareFontInfo);
        const env = {
            memory: this._computeOptionsMemory,
            outerWidth: partialEnv.outerWidth,
            outerHeight: partialEnv.outerHeight - this._reservedHeight,
            fontInfo: fontInfo,
            extraEditorClassName: partialEnv.extraEditorClassName,
            isDominatedByLongLines: this._isDominatedByLongLines,
            viewLineCount: this._viewLineCount,
            lineNumbersDigitCount: this._lineNumbersDigitCount,
            emptySelectionClipboard: partialEnv.emptySelectionClipboard,
            pixelRatio: partialEnv.pixelRatio,
            tabFocusMode: TabFocus.getTabFocusMode(),
            accessibilitySupport: partialEnv.accessibilitySupport
        };
        return EditorOptionsUtil.computeOptions(this._validatedOptions, env);
    }
    _readEnvConfiguration() {
        return {
            extraEditorClassName: getExtraEditorClassName(),
            outerWidth: this._containerObserver.getWidth(),
            outerHeight: this._containerObserver.getHeight(),
            emptySelectionClipboard: isWebKit || browser_isFirefox,
            pixelRatio: PixelRatio.value,
            accessibilitySupport: (this._accessibilityService.isScreenReaderOptimized()
                ? 2 /* AccessibilitySupport.Enabled */
                : this._accessibilityService.getAccessibilitySupport())
        };
    }
    _readFontInfo(bareFontInfo) {
        return FontMeasurements.readFontInfo(bareFontInfo);
    }
    getRawOptions() {
        return this._rawOptions;
    }
    updateOptions(_newOptions) {
        const newOptions = deepCloneAndMigrateOptions(_newOptions);
        const didChange = EditorOptionsUtil.applyUpdate(this._rawOptions, newOptions);
        if (!didChange) {
            return;
        }
        this._validatedOptions = EditorOptionsUtil.validateOptions(this._rawOptions);
        this._recomputeOptions();
    }
    observeContainer(dimension) {
        this._containerObserver.observe(dimension);
    }
    setIsDominatedByLongLines(isDominatedByLongLines) {
        if (this._isDominatedByLongLines === isDominatedByLongLines) {
            return;
        }
        this._isDominatedByLongLines = isDominatedByLongLines;
        this._recomputeOptions();
    }
    setModelLineCount(modelLineCount) {
        const lineNumbersDigitCount = digitCount(modelLineCount);
        if (this._lineNumbersDigitCount === lineNumbersDigitCount) {
            return;
        }
        this._lineNumbersDigitCount = lineNumbersDigitCount;
        this._recomputeOptions();
    }
    setViewLineCount(viewLineCount) {
        if (this._viewLineCount === viewLineCount) {
            return;
        }
        this._viewLineCount = viewLineCount;
        this._recomputeOptions();
    }
    setReservedHeight(reservedHeight) {
        if (this._reservedHeight === reservedHeight) {
            return;
        }
        this._reservedHeight = reservedHeight;
        this._recomputeOptions();
    }
};
EditorConfiguration = editorConfiguration_decorate([
    editorConfiguration_param(3, IAccessibilityService)
], EditorConfiguration);

function digitCount(n) {
    let r = 0;
    while (n) {
        n = Math.floor(n / 10);
        r++;
    }
    return r ? r : 1;
}
function getExtraEditorClassName() {
    let extra = '';
    if (!browser_isSafari && !isWebkitWebView) {
        // Use user-select: none in all browsers except Safari and native macOS WebView
        extra += 'no-user-select ';
    }
    if (browser_isSafari) {
        // See https://github.com/microsoft/vscode/issues/108822
        extra += 'no-minimap-shadow ';
        extra += 'enable-user-select ';
    }
    if (isMacintosh) {
        extra += 'mac ';
    }
    return extra;
}
class ValidatedEditorOptions {
    constructor() {
        this._values = [];
    }
    _read(option) {
        return this._values[option];
    }
    get(id) {
        return this._values[id];
    }
    _write(option, value) {
        this._values[option] = value;
    }
}
class ComputedEditorOptions {
    constructor() {
        this._values = [];
    }
    _read(id) {
        if (id >= this._values.length) {
            throw new Error('Cannot read uninitialized value');
        }
        return this._values[id];
    }
    get(id) {
        return this._read(id);
    }
    _write(id, value) {
        this._values[id] = value;
    }
}
class EditorOptionsUtil {
    static validateOptions(options) {
        const result = new ValidatedEditorOptions();
        for (const editorOption of editorOptionsRegistry) {
            const value = (editorOption.name === '_never_' ? undefined : options[editorOption.name]);
            result._write(editorOption.id, editorOption.validate(value));
        }
        return result;
    }
    static computeOptions(options, env) {
        const result = new ComputedEditorOptions();
        for (const editorOption of editorOptionsRegistry) {
            result._write(editorOption.id, editorOption.compute(env, result, options._read(editorOption.id)));
        }
        return result;
    }
    static _deepEquals(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) ? equals(a, b) : false);
        }
        if (Object.keys(a).length !== Object.keys(b).length) {
            return false;
        }
        for (const key in a) {
            if (!EditorOptionsUtil._deepEquals(a[key], b[key])) {
                return false;
            }
        }
        return true;
    }
    static checkEquals(a, b) {
        const result = [];
        let somethingChanged = false;
        for (const editorOption of editorOptionsRegistry) {
            const changed = !EditorOptionsUtil._deepEquals(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(options, update) {
        let changed = false;
        for (const editorOption of editorOptionsRegistry) {
            if (update.hasOwnProperty(editorOption.name)) {
                const result = editorOption.applyUpdate(options[editorOption.name], update[editorOption.name]);
                options[editorOption.name] = result.newValue;
                changed = changed || result.didChange;
            }
        }
        return changed;
    }
}
function deepCloneAndMigrateOptions(_options) {
    const options = deepClone(_options);
    migrateOptions(options);
    return options;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewEventHandler.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class ViewEventHandler extends Disposable {
    constructor() {
        super();
        this._shouldRender = true;
    }
    shouldRender() {
        return this._shouldRender;
    }
    forceShouldRender() {
        this._shouldRender = true;
    }
    setShouldRender() {
        this._shouldRender = true;
    }
    onDidRender() {
        this._shouldRender = 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 i = 0, len = events.length; i < len; i++) {
            const e = events[i];
            switch (e.type) {
                case 0 /* viewEvents.ViewEventType.ViewCompositionStart */:
                    if (this.onCompositionStart(e)) {
                        shouldRender = true;
                    }
                    break;
                case 1 /* viewEvents.ViewEventType.ViewCompositionEnd */:
                    if (this.onCompositionEnd(e)) {
                        shouldRender = true;
                    }
                    break;
                case 2 /* viewEvents.ViewEventType.ViewConfigurationChanged */:
                    if (this.onConfigurationChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                case 3 /* viewEvents.ViewEventType.ViewCursorStateChanged */:
                    if (this.onCursorStateChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                case 4 /* viewEvents.ViewEventType.ViewDecorationsChanged */:
                    if (this.onDecorationsChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                case 5 /* viewEvents.ViewEventType.ViewFlushed */:
                    if (this.onFlushed(e)) {
                        shouldRender = true;
                    }
                    break;
                case 6 /* viewEvents.ViewEventType.ViewFocusChanged */:
                    if (this.onFocusChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                case 7 /* viewEvents.ViewEventType.ViewLanguageConfigurationChanged */:
                    if (this.onLanguageConfigurationChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                case 8 /* viewEvents.ViewEventType.ViewLineMappingChanged */:
                    if (this.onLineMappingChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                case 9 /* viewEvents.ViewEventType.ViewLinesChanged */:
                    if (this.onLinesChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                case 10 /* viewEvents.ViewEventType.ViewLinesDeleted */:
                    if (this.onLinesDeleted(e)) {
                        shouldRender = true;
                    }
                    break;
                case 11 /* viewEvents.ViewEventType.ViewLinesInserted */:
                    if (this.onLinesInserted(e)) {
                        shouldRender = true;
                    }
                    break;
                case 12 /* viewEvents.ViewEventType.ViewRevealRangeRequest */:
                    if (this.onRevealRangeRequest(e)) {
                        shouldRender = true;
                    }
                    break;
                case 13 /* viewEvents.ViewEventType.ViewScrollChanged */:
                    if (this.onScrollChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                case 15 /* viewEvents.ViewEventType.ViewTokensChanged */:
                    if (this.onTokensChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                case 14 /* viewEvents.ViewEventType.ViewThemeChanged */:
                    if (this.onThemeChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                case 16 /* viewEvents.ViewEventType.ViewTokensColorsChanged */:
                    if (this.onTokensColorsChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                case 17 /* viewEvents.ViewEventType.ViewZonesChanged */:
                    if (this.onZonesChanged(e)) {
                        shouldRender = true;
                    }
                    break;
                default:
                    console.info('View received unknown event: ');
                    console.info(e);
            }
        }
        if (shouldRender) {
            this._shouldRender = true;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/view/viewPart.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class ViewPart extends ViewEventHandler {
    constructor(context) {
        super();
        this._context = context;
        this._context.addEventHandler(this);
    }
    dispose() {
        this._context.removeEventHandler(this);
        super.dispose();
    }
}
class PartFingerprints {
    static write(target, partId) {
        target.setAttribute('data-mprt', String(partId));
    }
    static read(target) {
        const r = target.getAttribute('data-mprt');
        if (r === null) {
            return 0 /* PartFingerprint.None */;
        }
        return parseInt(r, 10);
    }
    static collect(child, stopAt) {
        const result = [];
        let resultLen = 0;
        while (child && child !== document.body) {
            if (child === stopAt) {
                break;
            }
            if (child.nodeType === child.ELEMENT_NODE) {
                result[resultLen++] = this.read(child);
            }
            child = child.parentElement;
        }
        const r = new Uint8Array(resultLen);
        for (let i = 0; i < resultLen; i++) {
            r[i] = result[resultLen - i - 1];
        }
        return r;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/view/renderingContext.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class RestrictedRenderingContext {
    constructor(viewLayout, viewportData) {
        this._restrictedRenderingContextBrand = undefined;
        this._viewLayout = viewLayout;
        this.viewportData = viewportData;
        this.scrollWidth = this._viewLayout.getScrollWidth();
        this.scrollHeight = this._viewLayout.getScrollHeight();
        this.visibleRange = this.viewportData.visibleRange;
        this.bigNumbersDelta = this.viewportData.bigNumbersDelta;
        const vInfo = this._viewLayout.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) {
        return this._viewLayout.getVerticalOffsetForLineNumber(lineNumber);
    }
    getDecorationsInViewport() {
        return this.viewportData.getDecorationsInViewport();
    }
}
class RenderingContext extends RestrictedRenderingContext {
    constructor(viewLayout, viewportData, viewLines) {
        super(viewLayout, viewportData);
        this._renderingContextBrand = undefined;
        this._viewLines = viewLines;
    }
    linesVisibleRangesForRange(range, includeNewLines) {
        return this._viewLines.linesVisibleRangesForRange(range, includeNewLines);
    }
    visibleRangeForPosition(position) {
        return this._viewLines.visibleRangeForPosition(position);
    }
}
class LineVisibleRanges {
    constructor(outsideRenderedLine, lineNumber, ranges) {
        this.outsideRenderedLine = outsideRenderedLine;
        this.lineNumber = lineNumber;
        this.ranges = ranges;
    }
}
class HorizontalRange {
    constructor(left, width) {
        this._horizontalRangeBrand = undefined;
        this.left = Math.round(left);
        this.width = Math.round(width);
    }
    static from(ranges) {
        const result = new Array(ranges.length);
        for (let i = 0, len = ranges.length; i < len; i++) {
            const range = ranges[i];
            result[i] = new HorizontalRange(range.left, range.width);
        }
        return result;
    }
    toString() {
        return `[${this.left},${this.width}]`;
    }
}
class FloatHorizontalRange {
    constructor(left, width) {
        this._floatHorizontalRangeBrand = undefined;
        this.left = left;
        this.width = width;
    }
    toString() {
        return `[${this.left},${this.width}]`;
    }
    static compare(a, b) {
        return a.left - b.left;
    }
}
class HorizontalPosition {
    constructor(outsideRenderedLine, left) {
        this.outsideRenderedLine = outsideRenderedLine;
        this.originalLeft = left;
        this.left = Math.round(this.originalLeft);
    }
}
class VisibleRanges {
    constructor(outsideRenderedLine, ranges) {
        this.outsideRenderedLine = outsideRenderedLine;
        this.ranges = ranges;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/lines/rangeUtil.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class RangeUtil {
    static _createRange() {
        if (!this._handyReadyRange) {
            this._handyReadyRange = document.createRange();
        }
        return this._handyReadyRange;
    }
    static _detachRange(range, endNode) {
        // Move range out of the span node, IE doesn't like having many ranges in
        // the same spot and will act badly for lines containing dashes ('-')
        range.selectNodeContents(endNode);
    }
    static _readClientRects(startElement, startOffset, endElement, endOffset, endNode) {
        const range = this._createRange();
        try {
            range.setStart(startElement, startOffset);
            range.setEnd(endElement, endOffset);
            return range.getClientRects();
        }
        catch (e) {
            // This is life ...
            return null;
        }
        finally {
            this._detachRange(range, endNode);
        }
    }
    static _mergeAdjacentRanges(ranges) {
        if (ranges.length === 1) {
            // There is nothing to merge
            return ranges;
        }
        ranges.sort(FloatHorizontalRange.compare);
        const result = [];
        let resultLen = 0;
        let prev = ranges[0];
        for (let i = 1, len = ranges.length; i < len; i++) {
            const range = ranges[i];
            if (prev.left + prev.width + 0.9 /* account for browser's rounding errors*/ >= 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 _createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft, clientRectScale) {
        if (!clientRects || clientRects.length === 0) {
            return null;
        }
        // We go through FloatHorizontalRange because it has been observed in bi-di text
        // that the clientRects are not coming in sorted from the browser
        const result = [];
        for (let i = 0, len = clientRects.length; i < len; i++) {
            const clientRect = clientRects[i];
            result[i] = new FloatHorizontalRange(Math.max(0, (clientRect.left - clientRectDeltaLeft) / clientRectScale), clientRect.width / clientRectScale);
        }
        return this._mergeAdjacentRanges(result);
    }
    static readHorizontalRanges(domNode, startChildIndex, startOffset, endChildIndex, endOffset, clientRectDeltaLeft, clientRectScale, endNode) {
        // Panic check
        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) {
            // We must find the position at the beginning of a <span>
            // To cover cases of empty <span>s, avoid using a range and use the <span>'s bounding box
            const clientRects = domNode.children[startChildIndex].getClientRects();
            return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft, clientRectScale);
        }
        // If crossing over to a span only to select offset 0, then use the previous span's maximum offset
        // Chrome is buggy and doesn't handle 0 offsets well sometimes.
        if (startChildIndex !== endChildIndex) {
            if (endChildIndex > 0 && endOffset === 0) {
                endChildIndex--;
                endOffset = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
            }
        }
        let startElement = domNode.children[startChildIndex].firstChild;
        let endElement = domNode.children[endChildIndex].firstChild;
        if (!startElement || !endElement) {
            // When having an empty <span> (without any text content), try to move to the previous <span>
            if (!startElement && startOffset === 0 && startChildIndex > 0) {
                startElement = domNode.children[startChildIndex - 1].firstChild;
                startOffset = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
            }
            if (!endElement && endOffset === 0 && endChildIndex > 0) {
                endElement = domNode.children[endChildIndex - 1].firstChild;
                endOffset = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
            }
        }
        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._readClientRects(startElement, startOffset, endElement, endOffset, endNode);
        return this._createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft, clientRectScale);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewLayout/lineDecorations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class LineDecoration {
    constructor(startColumn, endColumn, className, type) {
        this.startColumn = startColumn;
        this.endColumn = endColumn;
        this.className = className;
        this.type = type;
        this._lineDecorationBrand = undefined;
    }
    static _equals(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 i = 0; i < aLen; i++) {
            if (!LineDecoration._equals(a[i], b[i])) {
                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 r = [];
        let rLength = 0;
        for (const dec of arr) {
            if (dec.endColumn <= startColumn || dec.startColumn >= endColumn) {
                continue;
            }
            r[rLength++] = new LineDecoration(Math.max(1, dec.startColumn - startColumn + 1), Math.min(lineLength + 1, dec.endColumn - startColumn + 1), dec.className, dec.type);
        }
        return r;
    }
    static filter(lineDecorations, lineNumber, minLineColumn, maxLineColumn) {
        if (lineDecorations.length === 0) {
            return [];
        }
        const result = [];
        let resultLen = 0;
        for (let i = 0, len = lineDecorations.length; i < len; i++) {
            const d = lineDecorations[i];
            const range = d.range;
            if (range.endLineNumber < lineNumber || range.startLineNumber > lineNumber) {
                // Ignore decorations that sit outside this line
                continue;
            }
            if (range.isEmpty() && (d.type === 0 /* InlineDecorationType.Regular */ || d.type === 3 /* InlineDecorationType.RegularAffectingLetterSpacing */)) {
                // Ignore empty range decorations
                continue;
            }
            const startColumn = (range.startLineNumber === lineNumber ? range.startColumn : minLineColumn);
            const endColumn = (range.endLineNumber === lineNumber ? range.endColumn : maxLineColumn);
            result[resultLen++] = new LineDecoration(startColumn, endColumn, d.inlineClassName, d.type);
        }
        return result;
    }
    static _typeCompare(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 = LineDecoration._typeCompare(a.type, b.type);
        if (typeCmp !== 0) {
            return typeCmp;
        }
        if (a.className !== b.className) {
            return a.className < b.className ? -1 : 1;
        }
        return 0;
    }
}
class DecorationSegment {
    constructor(startOffset, endOffset, className, metadata) {
        this.startOffset = startOffset;
        this.endOffset = endOffset;
        this.className = className;
        this.metadata = metadata;
    }
}
class Stack {
    constructor() {
        this.stopOffsets = [];
        this.classNames = [];
        this.metadata = [];
        this.count = 0;
    }
    static _metadata(metadata) {
        let result = 0;
        for (let i = 0, len = metadata.length; i < len; i++) {
            result |= metadata[i];
        }
        return result;
    }
    consumeLowerThan(maxStopOffset, nextStartOffset, result) {
        while (this.count > 0 && this.stopOffsets[0] < maxStopOffset) {
            let i = 0;
            // Take all equal stopping offsets
            while (i + 1 < this.count && this.stopOffsets[i] === this.stopOffsets[i + 1]) {
                i++;
            }
            // Basically we are consuming the first i + 1 elements of the stack
            result.push(new DecorationSegment(nextStartOffset, this.stopOffsets[i], this.classNames.join(' '), Stack._metadata(this.metadata)));
            nextStartOffset = this.stopOffsets[i] + 1;
            // Consume them
            this.stopOffsets.splice(0, i + 1);
            this.classNames.splice(0, i + 1);
            this.metadata.splice(0, i + 1);
            this.count -= (i + 1);
        }
        if (this.count > 0 && nextStartOffset < maxStopOffset) {
            result.push(new DecorationSegment(nextStartOffset, maxStopOffset - 1, this.classNames.join(' '), Stack._metadata(this.metadata)));
            nextStartOffset = maxStopOffset;
        }
        return nextStartOffset;
    }
    insert(stopOffset, className, metadata) {
        if (this.count === 0 || this.stopOffsets[this.count - 1] <= stopOffset) {
            // Insert at the end
            this.stopOffsets.push(stopOffset);
            this.classNames.push(className);
            this.metadata.push(metadata);
        }
        else {
            // Find the insertion position for `stopOffset`
            for (let i = 0; i < this.count; i++) {
                if (this.stopOffsets[i] >= stopOffset) {
                    this.stopOffsets.splice(i, 0, stopOffset);
                    this.classNames.splice(i, 0, className);
                    this.metadata.splice(i, 0, metadata);
                    break;
                }
            }
        }
        this.count++;
        return;
    }
}
class LineDecorationsNormalizer {
    /**
     * 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 i = 0, len = lineDecorations.length; i < len; i++) {
            const d = lineDecorations[i];
            let startColumn = d.startColumn;
            let endColumn = d.endColumn;
            const className = d.className;
            const metadata = (d.type === 1 /* InlineDecorationType.Before */
                ? 2 /* LinePartMetadata.PSEUDO_BEFORE */
                : d.type === 2 /* InlineDecorationType.After */
                    ? 4 /* LinePartMetadata.PSEUDO_AFTER */
                    : 0);
            // If the position would end up in the middle of a high-low surrogate pair, we move it to before the pair
            if (startColumn > 1) {
                const charCodeBefore = lineContent.charCodeAt(startColumn - 2);
                if (isHighSurrogate(charCodeBefore)) {
                    startColumn--;
                }
            }
            if (endColumn > 1) {
                const charCodeBefore = lineContent.charCodeAt(endColumn - 2);
                if (isHighSurrogate(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 /* Constants.MAX_SAFE_SMALL_INTEGER */, nextStartOffset, result);
        return result;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewLayout/linePart.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class LinePart {
    constructor(
    /**
     * last char index of this token (not inclusive).
     */
    endIndex, type, metadata, containsRTL) {
        this.endIndex = endIndex;
        this.type = type;
        this.metadata = metadata;
        this.containsRTL = containsRTL;
        this._linePartBrand = undefined;
    }
    isWhitespace() {
        return (this.metadata & 1 /* LinePartMetadata.IS_WHITESPACE_MASK */ ? true : false);
    }
    isPseudoAfter() {
        return (this.metadata & 4 /* LinePartMetadata.PSEUDO_AFTER_MASK */ ? true : false);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewLayout/viewLineRenderer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class LineRange {
    constructor(startIndex, endIndex) {
        this.startOffset = startIndex;
        this.endOffset = endIndex;
    }
    equals(otherLineRange) {
        return this.startOffset === otherLineRange.startOffset
            && this.endOffset === otherLineRange.endOffset;
    }
}
class RenderLineInput {
    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(LineDecoration.compare);
        this.tabSize = tabSize;
        this.startVisibleColumn = startVisibleColumn;
        this.spaceWidth = spaceWidth;
        this.stopRenderingLineAfter = stopRenderingLineAfter;
        this.renderWhitespace = (renderWhitespace === 'all'
            ? 4 /* RenderWhitespace.All */
            : renderWhitespace === 'boundary'
                ? 1 /* RenderWhitespace.Boundary */
                : renderWhitespace === 'selection'
                    ? 2 /* RenderWhitespace.Selection */
                    : renderWhitespace === 'trailing'
                        ? 3 /* RenderWhitespace.Trailing */
                        : 0 /* RenderWhitespace.None */);
        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 = 0x2E31; // U+2E31 - WORD SEPARATOR MIDDLE DOT
        }
        else {
            this.renderSpaceWidth = middotWidth;
            this.renderSpaceCharCode = 0xB7; // U+00B7 - MIDDLE DOT
        }
    }
    sameSelection(otherSelections) {
        if (this.selectionsOnLine === null) {
            return otherSelections === null;
        }
        if (otherSelections === null) {
            return false;
        }
        if (otherSelections.length !== this.selectionsOnLine.length) {
            return false;
        }
        for (let i = 0; i < this.selectionsOnLine.length; i++) {
            if (!this.selectionsOnLine[i].equals(otherSelections[i])) {
                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
            && LineDecoration.equalsArr(this.lineDecorations, other.lineDecorations)
            && this.lineTokens.equals(other.lineTokens)
            && this.sameSelection(other.selectionsOnLine));
    }
}
class DomPosition {
    constructor(partIndex, charIndex) {
        this.partIndex = partIndex;
        this.charIndex = charIndex;
    }
}
/**
 * Provides a both direction mapping between a line's character and its rendered position.
 */
class CharacterMapping {
    constructor(length, partCount) {
        this.length = length;
        this._data = new Uint32Array(this.length);
        this._horizontalOffset = new Uint32Array(this.length);
    }
    static getPartIndex(partData) {
        return (partData & 4294901760 /* CharacterMappingConstants.PART_INDEX_MASK */) >>> 16 /* CharacterMappingConstants.PART_INDEX_OFFSET */;
    }
    static getCharIndex(partData) {
        return (partData & 65535 /* CharacterMappingConstants.CHAR_INDEX_MASK */) >>> 0 /* CharacterMappingConstants.CHAR_INDEX_OFFSET */;
    }
    setColumnInfo(column, partIndex, charIndex, horizontalOffset) {
        const partData = ((partIndex << 16 /* CharacterMappingConstants.PART_INDEX_OFFSET */)
            | (charIndex << 0 /* CharacterMappingConstants.CHAR_INDEX_OFFSET */)) >>> 0;
        this._data[column - 1] = partData;
        this._horizontalOffset[column - 1] = horizontalOffset;
    }
    getHorizontalOffset(column) {
        if (this._horizontalOffset.length === 0) {
            // No characters on this line
            return 0;
        }
        return this._horizontalOffset[column - 1];
    }
    charOffsetToPartData(charOffset) {
        if (this.length === 0) {
            return 0;
        }
        if (charOffset < 0) {
            return this._data[0];
        }
        if (charOffset >= this.length) {
            return this._data[this.length - 1];
        }
        return this._data[charOffset];
    }
    getDomPosition(column) {
        const partData = this.charOffsetToPartData(column - 1);
        const partIndex = CharacterMapping.getPartIndex(partData);
        const charIndex = CharacterMapping.getCharIndex(partData);
        return new DomPosition(partIndex, charIndex);
    }
    getColumn(domPosition, partLength) {
        const charOffset = this.partDataToCharOffset(domPosition.partIndex, partLength, domPosition.charIndex);
        return charOffset + 1;
    }
    partDataToCharOffset(partIndex, partLength, charIndex) {
        if (this.length === 0) {
            return 0;
        }
        const searchEntry = ((partIndex << 16 /* CharacterMappingConstants.PART_INDEX_OFFSET */)
            | (charIndex << 0 /* CharacterMappingConstants.CHAR_INDEX_OFFSET */)) >>> 0;
        let min = 0;
        let max = this.length - 1;
        while (min + 1 < max) {
            const mid = ((min + max) >>> 1);
            const midEntry = this._data[mid];
            if (midEntry === searchEntry) {
                return mid;
            }
            else if (midEntry > searchEntry) {
                max = mid;
            }
            else {
                min = mid;
            }
        }
        if (min === max) {
            return min;
        }
        const minEntry = this._data[min];
        const maxEntry = this._data[max];
        if (minEntry === searchEntry) {
            return min;
        }
        if (maxEntry === searchEntry) {
            return max;
        }
        const minPartIndex = CharacterMapping.getPartIndex(minEntry);
        const minCharIndex = CharacterMapping.getCharIndex(minEntry);
        const maxPartIndex = CharacterMapping.getPartIndex(maxEntry);
        let maxCharIndex;
        if (minPartIndex !== maxPartIndex) {
            // sitting between parts
            maxCharIndex = partLength;
        }
        else {
            maxCharIndex = CharacterMapping.getCharIndex(maxEntry);
        }
        const minEntryDistance = charIndex - minCharIndex;
        const maxEntryDistance = maxCharIndex - charIndex;
        if (minEntryDistance <= maxEntryDistance) {
            return min;
        }
        return max;
    }
}
class RenderLineOutput {
    constructor(characterMapping, containsRTL, containsForeignElements) {
        this._renderLineOutputBrand = undefined;
        this.characterMapping = characterMapping;
        this.containsRTL = containsRTL;
        this.containsForeignElements = containsForeignElements;
    }
}
function renderViewLine(input, sb) {
    if (input.lineContent.length === 0) {
        if (input.lineDecorations.length > 0) {
            // This line is empty, but it contains inline decorations
            sb.appendASCIIString(`<span>`);
            let beforeCount = 0;
            let afterCount = 0;
            let containsForeignElements = 0 /* ForeignElementType.None */;
            for (const lineDecoration of input.lineDecorations) {
                if (lineDecoration.type === 1 /* InlineDecorationType.Before */ || lineDecoration.type === 2 /* InlineDecorationType.After */) {
                    sb.appendASCIIString(`<span class="`);
                    sb.appendASCIIString(lineDecoration.className);
                    sb.appendASCIIString(`"></span>`);
                    if (lineDecoration.type === 1 /* InlineDecorationType.Before */) {
                        containsForeignElements |= 1 /* ForeignElementType.Before */;
                        beforeCount++;
                    }
                    if (lineDecoration.type === 2 /* InlineDecorationType.After */) {
                        containsForeignElements |= 2 /* ForeignElementType.After */;
                        afterCount++;
                    }
                }
            }
            sb.appendASCIIString(`</span>`);
            const characterMapping = new CharacterMapping(1, beforeCount + afterCount);
            characterMapping.setColumnInfo(1, beforeCount, 0, 0);
            return new RenderLineOutput(characterMapping, false, containsForeignElements);
        }
        // completely empty line
        sb.appendASCIIString('<span><span></span></span>');
        return new RenderLineOutput(new CharacterMapping(0, 0), false, 0 /* ForeignElementType.None */);
    }
    return _renderLine(resolveRenderLineInput(input), sb);
}
class RenderLineOutput2 {
    constructor(characterMapping, html, containsRTL, containsForeignElements) {
        this.characterMapping = characterMapping;
        this.html = html;
        this.containsRTL = containsRTL;
        this.containsForeignElements = containsForeignElements;
    }
}
function renderViewLine2(input) {
    const sb = createStringBuilder(10000);
    const out = renderViewLine(input, sb);
    return new RenderLineOutput2(out.characterMapping, sb.build(), out.containsRTL, out.containsForeignElements);
}
class ResolvedRenderLineInput {
    constructor(fontIsMonospace, canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, 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.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 len;
    if (input.stopRenderingLineAfter !== -1 && input.stopRenderingLineAfter < lineContent.length) {
        isOverflowing = true;
        len = input.stopRenderingLineAfter;
    }
    else {
        isOverflowing = false;
        len = lineContent.length;
    }
    let tokens = transformAndRemoveOverflowing(lineContent, input.containsRTL, input.lineTokens, input.fauxIndentLength, len);
    if (input.renderControlCharacters && !input.isBasicASCII) {
        // Calling `extractControlCharacters` before adding (possibly empty) line parts
        // for inline decorations. `extractControlCharacters` removes empty line parts.
        tokens = extractControlCharacters(lineContent, tokens);
    }
    if (input.renderWhitespace === 4 /* RenderWhitespace.All */ ||
        input.renderWhitespace === 1 /* RenderWhitespace.Boundary */ ||
        (input.renderWhitespace === 2 /* RenderWhitespace.Selection */ && !!input.selectionsOnLine) ||
        input.renderWhitespace === 3 /* RenderWhitespace.Trailing */) {
        tokens = _applyRenderWhitespace(input, lineContent, len, tokens);
    }
    let containsForeignElements = 0 /* ForeignElementType.None */;
    if (input.lineDecorations.length > 0) {
        for (let i = 0, len = input.lineDecorations.length; i < len; i++) {
            const lineDecoration = input.lineDecorations[i];
            if (lineDecoration.type === 3 /* InlineDecorationType.RegularAffectingLetterSpacing */) {
                // Pretend there are foreign elements... although not 100% accurate.
                containsForeignElements |= 1 /* ForeignElementType.Before */;
            }
            else if (lineDecoration.type === 1 /* InlineDecorationType.Before */) {
                containsForeignElements |= 1 /* ForeignElementType.Before */;
            }
            else if (lineDecoration.type === 2 /* InlineDecorationType.After */) {
                containsForeignElements |= 2 /* ForeignElementType.After */;
            }
        }
        tokens = _applyInlineDecorations(lineContent, len, tokens, input.lineDecorations);
    }
    if (!input.containsRTL) {
        // We can never split RTL text, as it ruins the rendering
        tokens = splitLargeTokens(lineContent, tokens, !input.isBasicASCII || input.fontLigatures);
    }
    return new ResolvedRenderLineInput(input.useMonospaceOptimizations, input.canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, tokens, containsForeignElements, input.fauxIndentLength, input.tabSize, input.startVisibleColumn, input.containsRTL, input.spaceWidth, input.renderSpaceCharCode, input.renderWhitespace, input.renderControlCharacters);
}
/**
 * In the rendering phase, characters are always looped until token.endIndex.
 * Ensure that all tokens end before `len` and the last one ends precisely at `len`.
 */
function transformAndRemoveOverflowing(lineContent, lineContainsRTL, tokens, fauxIndentLength, len) {
    const result = [];
    let resultLen = 0;
    // The faux indent part of the line should have no token type
    if (fauxIndentLength > 0) {
        result[resultLen++] = new LinePart(fauxIndentLength, '', 0, false);
    }
    let startOffset = fauxIndentLength;
    for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
        const endIndex = tokens.getEndOffset(tokenIndex);
        if (endIndex <= fauxIndentLength) {
            // The faux indent part of the line should have no token type
            continue;
        }
        const type = tokens.getClassName(tokenIndex);
        if (endIndex >= len) {
            const tokenContainsRTL = (lineContainsRTL ? strings_containsRTL(lineContent.substring(startOffset, len)) : false);
            result[resultLen++] = new LinePart(len, type, 0, tokenContainsRTL);
            break;
        }
        const tokenContainsRTL = (lineContainsRTL ? strings_containsRTL(lineContent.substring(startOffset, endIndex)) : false);
        result[resultLen++] = new LinePart(endIndex, type, 0, tokenContainsRTL);
        startOffset = endIndex;
    }
    return result;
}
/**
 * See https://github.com/microsoft/vscode/issues/6885.
 * It appears that having very large spans causes very slow reading of character positions.
 * So here we try to avoid that.
 */
function splitLargeTokens(lineContent, tokens, onlyAtSpaces) {
    let lastTokenEndIndex = 0;
    const result = [];
    let resultLen = 0;
    if (onlyAtSpaces) {
        // Split only at spaces => we need to walk each character
        for (let i = 0, len = tokens.length; i < len; i++) {
            const token = tokens[i];
            const tokenEndIndex = token.endIndex;
            if (lastTokenEndIndex + 50 /* Constants.LongToken */ < 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 /* CharCode.Space */) {
                        lastSpaceOffset = j;
                    }
                    if (lastSpaceOffset !== -1 && j - currTokenStart >= 50 /* Constants.LongToken */) {
                        // Split at `lastSpaceOffset` + 1
                        result[resultLen++] = new LinePart(lastSpaceOffset + 1, tokenType, tokenMetadata, tokenContainsRTL);
                        currTokenStart = lastSpaceOffset + 1;
                        lastSpaceOffset = -1;
                    }
                }
                if (currTokenStart !== tokenEndIndex) {
                    result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
                }
            }
            else {
                result[resultLen++] = token;
            }
            lastTokenEndIndex = tokenEndIndex;
        }
    }
    else {
        // Split anywhere => we don't need to walk each character
        for (let i = 0, len = tokens.length; i < len; i++) {
            const token = tokens[i];
            const tokenEndIndex = token.endIndex;
            const diff = (tokenEndIndex - lastTokenEndIndex);
            if (diff > 50 /* Constants.LongToken */) {
                const tokenType = token.type;
                const tokenMetadata = token.metadata;
                const tokenContainsRTL = token.containsRTL;
                const piecesCount = Math.ceil(diff / 50 /* Constants.LongToken */);
                for (let j = 1; j < piecesCount; j++) {
                    const pieceEndIndex = lastTokenEndIndex + (j * 50 /* Constants.LongToken */);
                    result[resultLen++] = new LinePart(pieceEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
                }
                result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
            }
            else {
                result[resultLen++] = token;
            }
            lastTokenEndIndex = tokenEndIndex;
        }
    }
    return result;
}
function isControlCharacter(charCode) {
    if (charCode < 32) {
        return (charCode !== 9 /* CharCode.Tab */);
    }
    if (charCode === 127) {
        // DEL
        return true;
    }
    if ((charCode >= 0x202A && charCode <= 0x202E)
        || (charCode >= 0x2066 && charCode <= 0x2069)
        || (charCode >= 0x200E && charCode <= 0x200F)
        || charCode === 0x061C) {
        // Unicode Directional Formatting Characters
        // LRE	U+202A	LEFT-TO-RIGHT EMBEDDING
        // RLE	U+202B	RIGHT-TO-LEFT EMBEDDING
        // PDF	U+202C	POP DIRECTIONAL FORMATTING
        // LRO	U+202D	LEFT-TO-RIGHT OVERRIDE
        // RLO	U+202E	RIGHT-TO-LEFT OVERRIDE
        // LRI	U+2066	LEFT-TO-RIGHT ISOLATE
        // RLI	U+2067	RIGHT-TO-LEFT ISOLATE
        // FSI	U+2068	FIRST STRONG ISOLATE
        // PDI	U+2069	POP DIRECTIONAL ISOLATE
        // LRM	U+200E	LEFT-TO-RIGHT MARK
        // RLM	U+200F	RIGHT-TO-LEFT MARK
        // ALM	U+061C	ARABIC LETTER MARK
        return true;
    }
    return false;
}
function extractControlCharacters(lineContent, tokens) {
    const result = [];
    let lastLinePart = new LinePart(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) {
                    // emit previous part if it has text
                    lastLinePart = new LinePart(charOffset, token.type, token.metadata, token.containsRTL);
                    result.push(lastLinePart);
                }
                lastLinePart = new LinePart(charOffset + 1, 'mtkcontrol', token.metadata, false);
                result.push(lastLinePart);
            }
        }
        if (charOffset > lastLinePart.endIndex) {
            // emit previous part if it has text
            lastLinePart = new LinePart(tokenEndIndex, token.type, token.metadata, token.containsRTL);
            result.push(lastLinePart);
        }
    }
    return result;
}
/**
 * Whitespace is rendered by "replacing" tokens with a special-purpose `mtkw` type that is later recognized in the rendering phase.
 * Moreover, a token is created for every visual indent because on some fonts the glyphs used for rendering whitespace (&rarr; or &middot;) do not have the same width as &nbsp;.
 * The rendering phase will generate `style="width:..."` for these tokens.
 */
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 /* RenderWhitespace.Boundary */);
    const onlyTrailing = (input.renderWhitespace === 3 /* RenderWhitespace.Trailing */);
    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 = strings_firstNonWhitespaceIndex(lineContent);
    let lastNonWhitespaceIndex;
    if (firstNonWhitespaceIndex === -1) {
        lineIsEmptyOrWhitespace = true;
        firstNonWhitespaceIndex = len;
        lastNonWhitespaceIndex = len;
    }
    else {
        lastNonWhitespaceIndex = strings_lastNonWhitespaceIndex(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) {
            // in leading or trailing whitespace
            isInWhitespace = true;
        }
        else if (chCode === 9 /* CharCode.Tab */) {
            // a tab character is rendered both in all and boundary cases
            isInWhitespace = true;
        }
        else if (chCode === 32 /* CharCode.Space */) {
            // hit a space character
            if (onlyBoundary) {
                // rendering only boundary whitespace
                if (wasInWhitespace) {
                    isInWhitespace = true;
                }
                else {
                    const nextChCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0 /* CharCode.Null */);
                    isInWhitespace = (nextChCode === 32 /* CharCode.Space */ || nextChCode === 9 /* CharCode.Tab */);
                }
            }
            else {
                isInWhitespace = true;
            }
        }
        else {
            isInWhitespace = false;
        }
        // If rendering whitespace on selection, check that the charIndex falls within a selection
        if (isInWhitespace && selections) {
            isInWhitespace = !!currentSelection && currentSelection.startOffset <= charIndex && currentSelection.endOffset > charIndex;
        }
        // If rendering only trailing whitespace, check that the charIndex points to trailing whitespace.
        if (isInWhitespace && onlyTrailing) {
            isInWhitespace = lineIsEmptyOrWhitespace || charIndex > lastNonWhitespaceIndex;
        }
        if (isInWhitespace && tokenContainsRTL) {
            // If the token contains RTL text, breaking it up into multiple line parts
            // to render whitespace might affect the browser's bidi layout.
            //
            // We render whitespace in such tokens only if the whitespace
            // is the leading or the trailing whitespace of the line,
            // which doesn't affect the browser's bidi layout.
            if (charIndex >= firstNonWhitespaceIndex && charIndex <= lastNonWhitespaceIndex) {
                isInWhitespace = false;
            }
        }
        if (wasInWhitespace) {
            // was in whitespace token
            if (!isInWhitespace || (!useMonospaceOptimizations && tmpIndent >= tabSize)) {
                // leaving whitespace token or entering a new indent
                if (generateLinePartForEachWhitespace) {
                    const lastEndIndex = (resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength);
                    for (let i = lastEndIndex + 1; i <= charIndex; i++) {
                        result[resultLen++] = new LinePart(i, 'mtkw', 1 /* LinePartMetadata.IS_WHITESPACE */, false);
                    }
                }
                else {
                    result[resultLen++] = new LinePart(charIndex, 'mtkw', 1 /* LinePartMetadata.IS_WHITESPACE */, false);
                }
                tmpIndent = tmpIndent % tabSize;
            }
        }
        else {
            // was in regular token
            if (charIndex === tokenEndIndex || (isInWhitespace && charIndex > fauxIndentLength)) {
                result[resultLen++] = new LinePart(charIndex, tokenType, 0, tokenContainsRTL);
                tmpIndent = tmpIndent % tabSize;
            }
        }
        if (chCode === 9 /* CharCode.Tab */) {
            tmpIndent = tabSize;
        }
        else if (isFullWidthCharacter(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) {
        // was in whitespace token
        if (continuesWithWrappedLine && onlyBoundary) {
            const lastCharCode = (len > 0 ? lineContent.charCodeAt(len - 1) : 0 /* CharCode.Null */);
            const prevCharCode = (len > 1 ? lineContent.charCodeAt(len - 2) : 0 /* CharCode.Null */);
            const isSingleTrailingSpace = (lastCharCode === 32 /* CharCode.Space */ && (prevCharCode !== 32 /* CharCode.Space */ && prevCharCode !== 9 /* CharCode.Tab */));
            if (!isSingleTrailingSpace) {
                generateWhitespace = true;
            }
        }
        else {
            generateWhitespace = true;
        }
    }
    if (generateWhitespace) {
        if (generateLinePartForEachWhitespace) {
            const lastEndIndex = (resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength);
            for (let i = lastEndIndex + 1; i <= len; i++) {
                result[resultLen++] = new LinePart(i, 'mtkw', 1 /* LinePartMetadata.IS_WHITESPACE */, false);
            }
        }
        else {
            result[resultLen++] = new LinePart(len, 'mtkw', 1 /* LinePartMetadata.IS_WHITESPACE */, false);
        }
    }
    else {
        result[resultLen++] = new LinePart(len, tokenType, 0, tokenContainsRTL);
    }
    return result;
}
/**
 * Inline decorations are "merged" on top of tokens.
 * Special care must be taken when multiple inline decorations are at play and they overlap.
 */
function _applyInlineDecorations(lineContent, len, tokens, _lineDecorations) {
    _lineDecorations.sort(LineDecoration.compare);
    const lineDecorations = LineDecorationsNormalizer.normalize(lineContent, _lineDecorations);
    const lineDecorationsLen = lineDecorations.length;
    let lineDecorationIndex = 0;
    const result = [];
    let resultLen = 0;
    let lastResultEndIndex = 0;
    for (let tokenIndex = 0, len = tokens.length; tokenIndex < len; 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 LinePart(lastResultEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
            }
            if (lineDecoration.endOffset + 1 <= tokenEndIndex) {
                // This line decoration ends before this token ends
                lastResultEndIndex = lineDecoration.endOffset + 1;
                result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className, tokenMetadata | lineDecoration.metadata, tokenContainsRTL);
                lineDecorationIndex++;
            }
            else {
                // This line decoration continues on to the next token
                lastResultEndIndex = tokenEndIndex;
                result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className, tokenMetadata | lineDecoration.metadata, tokenContainsRTL);
                break;
            }
        }
        if (tokenEndIndex > lastResultEndIndex) {
            lastResultEndIndex = tokenEndIndex;
            result[resultLen++] = new LinePart(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 LinePart(lastResultEndIndex, lineDecoration.className, lineDecoration.metadata, false);
            lineDecorationIndex++;
        }
    }
    return result;
}
/**
 * This function is on purpose not split up into multiple functions to allow runtime type inference (i.e. performance reasons).
 * Notice how all the needed data is fully resolved and passed in (i.e. no other calls).
 */
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 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 CharacterMapping(len + 1, parts.length);
    let lastCharacterMappingDefined = false;
    let charIndex = 0;
    let visibleColumn = startVisibleColumn;
    let charOffsetInPart = 0; // the character offset in the current part
    let charHorizontalOffset = 0; // the character horizontal position in terms of chars relative to line start
    let partDisplacement = 0;
    if (containsRTL) {
        sb.appendASCIIString('<span dir="ltr">');
    }
    else {
        sb.appendASCIIString('<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 /* RenderWhitespace.None */ && part.isWhitespace());
        const partRendersWhitespaceWithWidth = partRendersWhitespace && !fontIsMonospace && (partType === 'mtkw' /*only whitespace*/ || !containsForeignElements);
        const partIsEmptyAndHasPseudoAfter = (charIndex === partEndIndex && part.isPseudoAfter());
        charOffsetInPart = 0;
        sb.appendASCIIString('<span ');
        if (partContainsRTL) {
            sb.appendASCIIString('style="unicode-bidi:isolate" ');
        }
        sb.appendASCIIString('class="');
        sb.appendASCIIString(partRendersWhitespaceWithWidth ? 'mtkz' : partType);
        sb.appendASCII(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 /* CharCode.Tab */ ? (tabSize - (_visibleColumn % tabSize)) : 1) | 0;
                    partWidth += charWidth;
                    if (_charIndex >= fauxIndentLength) {
                        _visibleColumn += charWidth;
                    }
                }
            }
            if (partRendersWhitespaceWithWidth) {
                sb.appendASCIIString(' style="width:');
                sb.appendASCIIString(String(spaceWidth * partWidth));
                sb.appendASCIIString('px"');
            }
            sb.appendASCII(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 /* CharCode.Tab */) {
                    producedCharacters = (tabSize - (visibleColumn % tabSize)) | 0;
                    charWidth = producedCharacters;
                    if (!canUseHalfwidthRightwardsArrow || charWidth > 1) {
                        sb.write1(0x2192); // RIGHTWARDS ARROW
                    }
                    else {
                        sb.write1(0xFFEB); // HALFWIDTH RIGHTWARDS ARROW
                    }
                    for (let space = 2; space <= charWidth; space++) {
                        sb.write1(0xA0); // &nbsp;
                    }
                }
                else { // must be CharCode.Space
                    producedCharacters = 2;
                    charWidth = 1;
                    sb.write1(renderSpaceCharCode); // &middot; or word separator middle dot
                    sb.write1(0x200C); // ZERO WIDTH NON-JOINER
                }
                charOffsetInPart += producedCharacters;
                charHorizontalOffset += charWidth;
                if (charIndex >= fauxIndentLength) {
                    visibleColumn += charWidth;
                }
            }
        }
        else {
            sb.appendASCII(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 /* CharCode.Tab */:
                        producedCharacters = (tabSize - (visibleColumn % tabSize));
                        charWidth = producedCharacters;
                        for (let space = 1; space <= producedCharacters; space++) {
                            sb.write1(0xA0); // &nbsp;
                        }
                        break;
                    case 32 /* CharCode.Space */:
                        sb.write1(0xA0); // &nbsp;
                        break;
                    case 60 /* CharCode.LessThan */:
                        sb.appendASCIIString('&lt;');
                        break;
                    case 62 /* CharCode.GreaterThan */:
                        sb.appendASCIIString('&gt;');
                        break;
                    case 38 /* CharCode.Ampersand */:
                        sb.appendASCIIString('&amp;');
                        break;
                    case 0 /* CharCode.Null */:
                        if (renderControlCharacters) {
                            // See https://unicode-table.com/en/blocks/control-pictures/
                            sb.write1(9216);
                        }
                        else {
                            sb.appendASCIIString('&#00;');
                        }
                        break;
                    case 65279 /* CharCode.UTF8_BOM */:
                    case 8232 /* CharCode.LINE_SEPARATOR */:
                    case 8233 /* CharCode.PARAGRAPH_SEPARATOR */:
                    case 133 /* CharCode.NEXT_LINE */:
                        sb.write1(0xFFFD);
                        break;
                    default:
                        if (isFullWidthCharacter(charCode)) {
                            charWidth++;
                        }
                        // See https://unicode-table.com/en/blocks/control-pictures/
                        if (renderControlCharacters && charCode < 32) {
                            sb.write1(9216 + charCode);
                        }
                        else if (renderControlCharacters && charCode === 127) {
                            // DEL
                            sb.write1(9249);
                        }
                        else if (renderControlCharacters && isControlCharacter(charCode)) {
                            sb.appendASCIIString('[U+');
                            sb.appendASCIIString(to4CharHex(charCode));
                            sb.appendASCIIString(']');
                            producedCharacters = 8;
                            charWidth = producedCharacters;
                        }
                        else {
                            sb.write1(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.appendASCIIString('</span>');
    }
    if (!lastCharacterMappingDefined) {
        // When getting client rects for the last character, we will position the
        // text range at the end of the span, insteaf of at the beginning of next span
        characterMapping.setColumnInfo(len + 1, parts.length - 1, charOffsetInPart, charHorizontalOffset);
    }
    if (isOverflowing) {
        sb.appendASCIIString('<span>&hellip;</span>');
    }
    sb.appendASCIIString('</span>');
    return new RenderLineOutput(characterMapping, containsRTL, containsForeignElements);
}
function to4CharHex(n) {
    return n.toString(16).toUpperCase().padStart(4, '0');
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/lines/viewLine.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









const canUseFastRenderedViewLine = (function () {
    if (isNative) {
        // In VSCode we know very well when the zoom level changes
        return true;
    }
    if (isLinux || browser_isFirefox || browser_isSafari) {
        // On Linux, it appears that zooming affects char widths (in pixels), which is unexpected.
        // --
        // Even though we read character widths correctly, having read them at a specific zoom level
        // does not mean they are the same at the current zoom level.
        // --
        // This could be improved if we ever figure out how to get an event when browsers zoom,
        // but until then we have to stick with reading client rects.
        // --
        // The same has been observed with Firefox on Windows7
        // --
        // The same has been oversved with Safari
        return false;
    }
    return true;
})();
let monospaceAssumptionsAreValid = true;
class DomReadingContext {
    constructor(domNode, endNode) {
        this._domNode = domNode;
        this._clientRectDeltaLeft = 0;
        this._clientRectScale = 1;
        this._clientRectRead = false;
        this.endNode = endNode;
    }
    readClientRect() {
        if (!this._clientRectRead) {
            this._clientRectRead = true;
            const rect = this._domNode.getBoundingClientRect();
            this._clientRectDeltaLeft = rect.left;
            this._clientRectScale = rect.width / this._domNode.offsetWidth;
        }
    }
    get clientRectDeltaLeft() {
        if (!this._clientRectRead) {
            this.readClientRect();
        }
        return this._clientRectDeltaLeft;
    }
    get clientRectScale() {
        if (!this._clientRectRead) {
            this.readClientRect();
        }
        return this._clientRectScale;
    }
}
class ViewLineOptions {
    constructor(config, themeType) {
        this.themeType = themeType;
        const options = config.options;
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        this.renderWhitespace = options.get(90 /* EditorOption.renderWhitespace */);
        this.renderControlCharacters = options.get(85 /* EditorOption.renderControlCharacters */);
        this.spaceWidth = fontInfo.spaceWidth;
        this.middotWidth = fontInfo.middotWidth;
        this.wsmiddotWidth = fontInfo.wsmiddotWidth;
        this.useMonospaceOptimizations = (fontInfo.isMonospace
            && !options.get(29 /* EditorOption.disableMonospaceOptimizations */));
        this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow;
        this.lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this.stopRenderingLineAfter = options.get(107 /* EditorOption.stopRenderingLineAfter */);
        this.fontLigatures = options.get(47 /* EditorOption.fontLigatures */);
    }
    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);
    }
}
class ViewLine {
    constructor(options) {
        this._options = options;
        this._isMaybeInvalid = true;
        this._renderedViewLine = null;
    }
    // --- begin IVisibleLineData
    getDomNode() {
        if (this._renderedViewLine && this._renderedViewLine.domNode) {
            return this._renderedViewLine.domNode.domNode;
        }
        return null;
    }
    setDomNode(domNode) {
        if (this._renderedViewLine) {
            this._renderedViewLine.domNode = createFastDomNode(domNode);
        }
        else {
            throw new Error('I have no rendered view line to set the dom node to...');
        }
    }
    onContentChanged() {
        this._isMaybeInvalid = true;
    }
    onTokensChanged() {
        this._isMaybeInvalid = true;
    }
    onDecorationsChanged() {
        this._isMaybeInvalid = true;
    }
    onOptionsChanged(newOptions) {
        this._isMaybeInvalid = true;
        this._options = newOptions;
    }
    onSelectionChanged() {
        if (isHighContrast(this._options.themeType) || this._options.renderWhitespace === 'selection') {
            this._isMaybeInvalid = true;
            return true;
        }
        return false;
    }
    renderLine(lineNumber, deltaTop, viewportData, sb) {
        if (this._isMaybeInvalid === false) {
            // it appears that nothing relevant has changed
            return false;
        }
        this._isMaybeInvalid = false;
        const lineData = viewportData.getViewLineRenderingData(lineNumber);
        const options = this._options;
        const actualInlineDecorations = LineDecoration.filter(lineData.inlineDecorations, lineNumber, lineData.minColumn, lineData.maxColumn);
        // Only send selection information when needed for rendering whitespace
        let selectionsOnLine = null;
        if (isHighContrast(options.themeType) || this._options.renderWhitespace === 'selection') {
            const selections = viewportData.selections;
            for (const selection of selections) {
                if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) {
                    // Selection does not intersect line
                    continue;
                }
                const startColumn = (selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn);
                const endColumn = (selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn);
                if (startColumn < endColumn) {
                    if (isHighContrast(options.themeType) || this._options.renderWhitespace !== 'selection') {
                        actualInlineDecorations.push(new LineDecoration(startColumn, endColumn, 'inline-selected-text', 0 /* InlineDecorationType.Regular */));
                    }
                    else {
                        if (!selectionsOnLine) {
                            selectionsOnLine = [];
                        }
                        selectionsOnLine.push(new LineRange(startColumn - 1, endColumn - 1));
                    }
                }
            }
        }
        const renderLineInput = new RenderLineInput(options.useMonospaceOptimizations, options.canUseHalfwidthRightwardsArrow, lineData.content, lineData.continuesWithWrappedLine, lineData.isBasicASCII, lineData.containsRTL, lineData.minColumn - 1, lineData.tokens, actualInlineDecorations, lineData.tabSize, lineData.startVisibleColumn, options.spaceWidth, options.middotWidth, options.wsmiddotWidth, options.stopRenderingLineAfter, options.renderWhitespace, options.renderControlCharacters, options.fontLigatures !== EditorFontLigatures.OFF, selectionsOnLine);
        if (this._renderedViewLine && this._renderedViewLine.input.equals(renderLineInput)) {
            // no need to do anything, we have the same render input
            return false;
        }
        sb.appendASCIIString('<div style="top:');
        sb.appendASCIIString(String(deltaTop));
        sb.appendASCIIString('px;height:');
        sb.appendASCIIString(String(this._options.lineHeight));
        sb.appendASCIIString('px;" class="');
        sb.appendASCIIString(ViewLine.CLASS_NAME);
        sb.appendASCIIString('">');
        const output = renderViewLine(renderLineInput, sb);
        sb.appendASCIIString('</div>');
        let renderedViewLine = null;
        if (monospaceAssumptionsAreValid && canUseFastRenderedViewLine && lineData.isBasicASCII && options.useMonospaceOptimizations && output.containsForeignElements === 0 /* ForeignElementType.None */) {
            if (lineData.content.length < 300 && renderLineInput.lineTokens.getCount() < 100) {
                // Browser rounding errors have been observed in Chrome and IE, so using the fast
                // view line only for short lines. Please test before removing the length check...
                // ---
                // Another rounding error has been observed on Linux in VSCode, where <span> width
                // rounding errors add up to an observable large number...
                // ---
                // Also see another example of rounding errors on Windows in
                // https://github.com/microsoft/vscode/issues/33178
                renderedViewLine = new FastRenderedViewLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping);
            }
        }
        if (!renderedViewLine) {
            renderedViewLine = createRenderedLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping, output.containsRTL, output.containsForeignElements);
        }
        this._renderedViewLine = renderedViewLine;
        return true;
    }
    layoutLine(lineNumber, deltaTop) {
        if (this._renderedViewLine && this._renderedViewLine.domNode) {
            this._renderedViewLine.domNode.setTop(deltaTop);
            this._renderedViewLine.domNode.setHeight(this._options.lineHeight);
        }
    }
    // --- end IVisibleLineData
    getWidth() {
        if (!this._renderedViewLine) {
            return 0;
        }
        return this._renderedViewLine.getWidth();
    }
    getWidthIsFast() {
        if (!this._renderedViewLine) {
            return true;
        }
        return this._renderedViewLine.getWidthIsFast();
    }
    needsMonospaceFontCheck() {
        if (!this._renderedViewLine) {
            return false;
        }
        return (this._renderedViewLine instanceof FastRenderedViewLine);
    }
    monospaceAssumptionsAreValid() {
        if (!this._renderedViewLine) {
            return monospaceAssumptionsAreValid;
        }
        if (this._renderedViewLine instanceof FastRenderedViewLine) {
            return this._renderedViewLine.monospaceAssumptionsAreValid();
        }
        return monospaceAssumptionsAreValid;
    }
    onMonospaceAssumptionsInvalidated() {
        if (this._renderedViewLine && this._renderedViewLine instanceof FastRenderedViewLine) {
            this._renderedViewLine = this._renderedViewLine.toSlowRenderedLine();
        }
    }
    getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
        if (!this._renderedViewLine) {
            return null;
        }
        startColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, startColumn));
        endColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, endColumn));
        const stopRenderingLineAfter = this._renderedViewLine.input.stopRenderingLineAfter;
        let outsideRenderedLine = false;
        if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1 && endColumn > stopRenderingLineAfter + 1) {
            // This range is obviously not visible
            outsideRenderedLine = true;
        }
        if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1) {
            startColumn = stopRenderingLineAfter + 1;
        }
        if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter + 1) {
            endColumn = stopRenderingLineAfter + 1;
        }
        const horizontalRanges = this._renderedViewLine.getVisibleRangesForRange(lineNumber, startColumn, endColumn, context);
        if (horizontalRanges && horizontalRanges.length > 0) {
            return new VisibleRanges(outsideRenderedLine, horizontalRanges);
        }
        return null;
    }
    getColumnOfNodeOffset(lineNumber, spanNode, offset) {
        if (!this._renderedViewLine) {
            return 1;
        }
        return this._renderedViewLine.getColumnOfNodeOffset(lineNumber, spanNode, offset);
    }
}
ViewLine.CLASS_NAME = 'view-line';
/**
 * A rendered line which is guaranteed to contain only regular ASCII and is rendered with a monospace font.
 */
class FastRenderedViewLine {
    constructor(domNode, renderLineInput, characterMapping) {
        this.domNode = domNode;
        this.input = renderLineInput;
        this._characterMapping = characterMapping;
        this._charWidth = renderLineInput.spaceWidth;
    }
    getWidth() {
        return Math.round(this._getCharPosition(this._characterMapping.length));
    }
    getWidthIsFast() {
        return true;
    }
    monospaceAssumptionsAreValid() {
        if (!this.domNode) {
            return monospaceAssumptionsAreValid;
        }
        const expectedWidth = this.getWidth();
        const actualWidth = this.domNode.domNode.firstChild.offsetWidth;
        if (Math.abs(expectedWidth - actualWidth) >= 2) {
            // more than 2px off
            console.warn(`monospace assumptions have been violated, therefore disabling monospace optimizations!`);
            monospaceAssumptionsAreValid = false;
        }
        return monospaceAssumptionsAreValid;
    }
    toSlowRenderedLine() {
        return createRenderedLine(this.domNode, this.input, this._characterMapping, false, 0 /* ForeignElementType.None */);
    }
    getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
        const startPosition = this._getCharPosition(startColumn);
        const endPosition = this._getCharPosition(endColumn);
        return [new FloatHorizontalRange(startPosition, endPosition - startPosition)];
    }
    _getCharPosition(column) {
        const horizontalOffset = this._characterMapping.getHorizontalOffset(column);
        return this._charWidth * horizontalOffset;
    }
    getColumnOfNodeOffset(lineNumber, spanNode, offset) {
        const spanNodeTextContentLength = spanNode.textContent.length;
        let spanIndex = -1;
        while (spanNode) {
            spanNode = spanNode.previousSibling;
            spanIndex++;
        }
        return this._characterMapping.getColumn(new DomPosition(spanIndex, offset), spanNodeTextContentLength);
    }
}
/**
 * Every time we render a line, we save what we have rendered in an instance of this class.
 */
class RenderedViewLine {
    constructor(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements) {
        this.domNode = domNode;
        this.input = renderLineInput;
        this._characterMapping = characterMapping;
        this._isWhitespaceOnly = /^\s*$/.test(renderLineInput.lineContent);
        this._containsForeignElements = containsForeignElements;
        this._cachedWidth = -1;
        this._pixelOffsetCache = null;
        if (!containsRTL || this._characterMapping.length === 0 /* the line is empty */) {
            this._pixelOffsetCache = new Float32Array(Math.max(2, this._characterMapping.length + 1));
            for (let column = 0, len = this._characterMapping.length; column <= len; column++) {
                this._pixelOffsetCache[column] = -1;
            }
        }
    }
    // --- Reading from the DOM methods
    _getReadingTarget(myDomNode) {
        return myDomNode.domNode.firstChild;
    }
    /**
     * Width of the line in pixels
     */
    getWidth() {
        if (!this.domNode) {
            return 0;
        }
        if (this._cachedWidth === -1) {
            this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth;
        }
        return this._cachedWidth;
    }
    getWidthIsFast() {
        if (this._cachedWidth === -1) {
            return false;
        }
        return true;
    }
    /**
     * Visible ranges for a model range
     */
    getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
        if (!this.domNode) {
            return null;
        }
        if (this._pixelOffsetCache !== null) {
            // the text is LTR
            const startOffset = this._readPixelOffset(this.domNode, lineNumber, startColumn, context);
            if (startOffset === -1) {
                return null;
            }
            const endOffset = this._readPixelOffset(this.domNode, lineNumber, endColumn, context);
            if (endOffset === -1) {
                return null;
            }
            return [new FloatHorizontalRange(startOffset, endOffset - startOffset)];
        }
        return this._readVisibleRangesForRange(this.domNode, lineNumber, startColumn, endColumn, context);
    }
    _readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context) {
        if (startColumn === endColumn) {
            const pixelOffset = this._readPixelOffset(domNode, lineNumber, startColumn, context);
            if (pixelOffset === -1) {
                return null;
            }
            else {
                return [new FloatHorizontalRange(pixelOffset, 0)];
            }
        }
        else {
            return this._readRawVisibleRangesForRange(domNode, startColumn, endColumn, context);
        }
    }
    _readPixelOffset(domNode, lineNumber, column, context) {
        if (this._characterMapping.length === 0) {
            // This line has no content
            if (this._containsForeignElements === 0 /* ForeignElementType.None */) {
                // We can assume the line is really empty
                return 0;
            }
            if (this._containsForeignElements === 2 /* ForeignElementType.After */) {
                // We have foreign elements after the (empty) line
                return 0;
            }
            if (this._containsForeignElements === 1 /* ForeignElementType.Before */) {
                // We have foreign elements before the (empty) line
                return this.getWidth();
            }
            // We have foreign elements before & after the (empty) line
            const readingTarget = this._getReadingTarget(domNode);
            if (readingTarget.firstChild) {
                return readingTarget.firstChild.offsetWidth;
            }
            else {
                return 0;
            }
        }
        if (this._pixelOffsetCache !== null) {
            // the text is LTR
            const cachedPixelOffset = this._pixelOffsetCache[column];
            if (cachedPixelOffset !== -1) {
                return cachedPixelOffset;
            }
            const result = this._actualReadPixelOffset(domNode, lineNumber, column, context);
            this._pixelOffsetCache[column] = result;
            return result;
        }
        return this._actualReadPixelOffset(domNode, lineNumber, column, context);
    }
    _actualReadPixelOffset(domNode, lineNumber, column, context) {
        if (this._characterMapping.length === 0) {
            // This line has no content
            const r = RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), 0, 0, 0, 0, context.clientRectDeltaLeft, context.clientRectScale, context.endNode);
            if (!r || r.length === 0) {
                return -1;
            }
            return r[0].left;
        }
        if (column === this._characterMapping.length && this._isWhitespaceOnly && this._containsForeignElements === 0 /* ForeignElementType.None */) {
            // This branch helps in the case of whitespace only lines which have a width set
            return this.getWidth();
        }
        const domPosition = this._characterMapping.getDomPosition(column);
        const r = RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), domPosition.partIndex, domPosition.charIndex, domPosition.partIndex, domPosition.charIndex, context.clientRectDeltaLeft, context.clientRectScale, context.endNode);
        if (!r || r.length === 0) {
            return -1;
        }
        const result = r[0].left;
        if (this.input.isBasicASCII) {
            const horizontalOffset = this._characterMapping.getHorizontalOffset(column);
            const expectedResult = Math.round(this.input.spaceWidth * horizontalOffset);
            if (Math.abs(expectedResult - result) <= 1) {
                return expectedResult;
            }
        }
        return result;
    }
    _readRawVisibleRangesForRange(domNode, startColumn, endColumn, context) {
        if (startColumn === 1 && endColumn === this._characterMapping.length) {
            // This branch helps IE with bidi text & gives a performance boost to other browsers when reading visible ranges for an entire line
            return [new FloatHorizontalRange(0, this.getWidth())];
        }
        const startDomPosition = this._characterMapping.getDomPosition(startColumn);
        const endDomPosition = this._characterMapping.getDomPosition(endColumn);
        return RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), startDomPosition.partIndex, startDomPosition.charIndex, endDomPosition.partIndex, endDomPosition.charIndex, context.clientRectDeltaLeft, context.clientRectScale, context.endNode);
    }
    /**
     * Returns the column for the text found at a specific offset inside a rendered dom node
     */
    getColumnOfNodeOffset(lineNumber, spanNode, offset) {
        const spanNodeTextContentLength = spanNode.textContent.length;
        let spanIndex = -1;
        while (spanNode) {
            spanNode = spanNode.previousSibling;
            spanIndex++;
        }
        return this._characterMapping.getColumn(new DomPosition(spanIndex, offset), spanNodeTextContentLength);
    }
}
class WebKitRenderedViewLine extends RenderedViewLine {
    _readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context) {
        const output = super._readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context);
        if (!output || output.length === 0 || startColumn === endColumn || (startColumn === 1 && endColumn === this._characterMapping.length)) {
            return output;
        }
        // WebKit is buggy and returns an expanded range (to contain words in some cases)
        // The last client rect is enlarged (I think)
        if (!this.input.containsRTL) {
            // This is an attempt to patch things up
            // Find position of last column
            const endPixelOffset = this._readPixelOffset(domNode, lineNumber, endColumn, context);
            if (endPixelOffset !== -1) {
                const lastRange = output[output.length - 1];
                if (lastRange.left < endPixelOffset) {
                    // Trim down the width of the last visible range to not go after the last column's position
                    lastRange.width = endPixelOffset - lastRange.left;
                }
            }
        }
        return output;
    }
}
const createRenderedLine = (function () {
    if (isWebKit) {
        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);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/controller/mouseTarget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/








class UnknownHitTestResult {
    constructor(hitTarget = null) {
        this.hitTarget = hitTarget;
        this.type = 0 /* HitTestResultType.Unknown */;
    }
}
class ContentHitTestResult {
    constructor(position, spanNode, injectedText) {
        this.position = position;
        this.spanNode = spanNode;
        this.injectedText = injectedText;
        this.type = 1 /* HitTestResultType.Content */;
    }
}
var HitTestResult;
(function (HitTestResult) {
    function createFromDOMInfo(ctx, spanNode, offset) {
        const position = ctx.getPositionFromDOMInfo(spanNode, offset);
        if (position) {
            return new ContentHitTestResult(position, spanNode, null);
        }
        return new UnknownHitTestResult(spanNode);
    }
    HitTestResult.createFromDOMInfo = createFromDOMInfo;
})(HitTestResult || (HitTestResult = {}));
class PointerHandlerLastRenderData {
    constructor(lastViewCursorsRenderData, lastTextareaPosition) {
        this.lastViewCursorsRenderData = lastViewCursorsRenderData;
        this.lastTextareaPosition = lastTextareaPosition;
    }
}
class MouseTarget {
    static _deduceRage(position, range = null) {
        if (!range && position) {
            return new Range(position.lineNumber, position.column, position.lineNumber, position.column);
        }
        return range !== null && range !== void 0 ? range : null;
    }
    static createUnknown(element, mouseColumn, position) {
        return { type: 0 /* MouseTargetType.UNKNOWN */, element, mouseColumn, position, range: this._deduceRage(position) };
    }
    static createTextarea(element, mouseColumn) {
        return { type: 1 /* MouseTargetType.TEXTAREA */, element, mouseColumn, position: null, range: null };
    }
    static createMargin(type, element, mouseColumn, position, range, detail) {
        return { type, element, mouseColumn, position, range, detail };
    }
    static createViewZone(type, element, mouseColumn, position, detail) {
        return { type, element, mouseColumn, position, range: this._deduceRage(position), detail };
    }
    static createContentText(element, mouseColumn, position, range, detail) {
        return { type: 6 /* MouseTargetType.CONTENT_TEXT */, element, mouseColumn, position, range: this._deduceRage(position, range), detail };
    }
    static createContentEmpty(element, mouseColumn, position, detail) {
        return { type: 7 /* MouseTargetType.CONTENT_EMPTY */, element, mouseColumn, position, range: this._deduceRage(position), detail };
    }
    static createContentWidget(element, mouseColumn, detail) {
        return { type: 9 /* MouseTargetType.CONTENT_WIDGET */, element, mouseColumn, position: null, range: null, detail };
    }
    static createScrollbar(element, mouseColumn, position) {
        return { type: 11 /* MouseTargetType.SCROLLBAR */, element, mouseColumn, position, range: this._deduceRage(position) };
    }
    static createOverlayWidget(element, mouseColumn, detail) {
        return { type: 12 /* MouseTargetType.OVERLAY_WIDGET */, element, mouseColumn, position: null, range: null, detail };
    }
    static createOutsideEditor(mouseColumn, position) {
        return { type: 13 /* MouseTargetType.OUTSIDE_EDITOR */, element: null, mouseColumn, position, range: this._deduceRage(position) };
    }
    static _typeToString(type) {
        if (type === 1 /* MouseTargetType.TEXTAREA */) {
            return 'TEXTAREA';
        }
        if (type === 2 /* MouseTargetType.GUTTER_GLYPH_MARGIN */) {
            return 'GUTTER_GLYPH_MARGIN';
        }
        if (type === 3 /* MouseTargetType.GUTTER_LINE_NUMBERS */) {
            return 'GUTTER_LINE_NUMBERS';
        }
        if (type === 4 /* MouseTargetType.GUTTER_LINE_DECORATIONS */) {
            return 'GUTTER_LINE_DECORATIONS';
        }
        if (type === 5 /* MouseTargetType.GUTTER_VIEW_ZONE */) {
            return 'GUTTER_VIEW_ZONE';
        }
        if (type === 6 /* MouseTargetType.CONTENT_TEXT */) {
            return 'CONTENT_TEXT';
        }
        if (type === 7 /* MouseTargetType.CONTENT_EMPTY */) {
            return 'CONTENT_EMPTY';
        }
        if (type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */) {
            return 'CONTENT_VIEW_ZONE';
        }
        if (type === 9 /* MouseTargetType.CONTENT_WIDGET */) {
            return 'CONTENT_WIDGET';
        }
        if (type === 10 /* MouseTargetType.OVERVIEW_RULER */) {
            return 'OVERVIEW_RULER';
        }
        if (type === 11 /* MouseTargetType.SCROLLBAR */) {
            return 'SCROLLBAR';
        }
        if (type === 12 /* MouseTargetType.OVERLAY_WIDGET */) {
            return 'OVERLAY_WIDGET';
        }
        return 'UNKNOWN';
    }
    static toString(target) {
        return this._typeToString(target.type) + ': ' + target.position + ' - ' + target.range + ' - ' + JSON.stringify(target.detail);
    }
}
class ElementPath {
    static isTextArea(path) {
        return (path.length === 2
            && path[0] === 3 /* PartFingerprint.OverflowGuard */
            && path[1] === 6 /* PartFingerprint.TextArea */);
    }
    static isChildOfViewLines(path) {
        return (path.length >= 4
            && path[0] === 3 /* PartFingerprint.OverflowGuard */
            && path[3] === 7 /* PartFingerprint.ViewLines */);
    }
    static isStrictChildOfViewLines(path) {
        return (path.length > 4
            && path[0] === 3 /* PartFingerprint.OverflowGuard */
            && path[3] === 7 /* PartFingerprint.ViewLines */);
    }
    static isChildOfScrollableElement(path) {
        return (path.length >= 2
            && path[0] === 3 /* PartFingerprint.OverflowGuard */
            && path[1] === 5 /* PartFingerprint.ScrollableElement */);
    }
    static isChildOfMinimap(path) {
        return (path.length >= 2
            && path[0] === 3 /* PartFingerprint.OverflowGuard */
            && path[1] === 8 /* PartFingerprint.Minimap */);
    }
    static isChildOfContentWidgets(path) {
        return (path.length >= 4
            && path[0] === 3 /* PartFingerprint.OverflowGuard */
            && path[3] === 1 /* PartFingerprint.ContentWidgets */);
    }
    static isChildOfOverflowingContentWidgets(path) {
        return (path.length >= 1
            && path[0] === 2 /* PartFingerprint.OverflowingContentWidgets */);
    }
    static isChildOfOverlayWidgets(path) {
        return (path.length >= 2
            && path[0] === 3 /* PartFingerprint.OverflowGuard */
            && path[1] === 4 /* PartFingerprint.OverlayWidgets */);
    }
}
class HitTestContext {
    constructor(context, viewHelper, lastRenderData) {
        this.viewModel = context.viewModel;
        const options = context.configuration.options;
        this.layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this.viewDomNode = viewHelper.viewDomNode;
        this.lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this.stickyTabStops = options.get(106 /* EditorOption.stickyTabStops */);
        this.typicalHalfwidthCharacterWidth = options.get(46 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
        this.lastRenderData = lastRenderData;
        this._context = context;
        this._viewHelper = viewHelper;
    }
    getZoneAtCoord(mouseVerticalOffset) {
        return HitTestContext.getZoneAtCoord(this._context, mouseVerticalOffset);
    }
    static getZoneAtCoord(context, mouseVerticalOffset) {
        // The target is either a view zone or the empty space after the last view-line
        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) {
                // There are more lines after this view zone
                positionAfter = new Position(viewZoneWhitespace.afterLineNumber + 1, 1);
            }
            if (viewZoneWhitespace.afterLineNumber > 0) {
                // There are more lines above this view zone
                positionBefore = new Position(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: positionBefore,
                positionAfter: positionAfter,
                position: position
            };
        }
        return null;
    }
    getFullLineRangeAtCoord(mouseVerticalOffset) {
        if (this._context.viewLayout.isAfterLines(mouseVerticalOffset)) {
            // Below the last line
            const lineNumber = this._context.viewModel.getLineCount();
            const maxLineColumn = this._context.viewModel.getLineMaxColumn(lineNumber);
            return {
                range: new Range(lineNumber, maxLineColumn, lineNumber, maxLineColumn),
                isAfterLines: true
            };
        }
        const lineNumber = this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
        const maxLineColumn = this._context.viewModel.getLineMaxColumn(lineNumber);
        return {
            range: new Range(lineNumber, 1, lineNumber, maxLineColumn),
            isAfterLines: false
        };
    }
    getLineNumberAtVerticalOffset(mouseVerticalOffset) {
        return this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
    }
    isAfterLines(mouseVerticalOffset) {
        return this._context.viewLayout.isAfterLines(mouseVerticalOffset);
    }
    isInTopPadding(mouseVerticalOffset) {
        return this._context.viewLayout.isInTopPadding(mouseVerticalOffset);
    }
    isInBottomPadding(mouseVerticalOffset) {
        return this._context.viewLayout.isInBottomPadding(mouseVerticalOffset);
    }
    getVerticalOffsetForLineNumber(lineNumber) {
        return this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber);
    }
    findAttribute(element, attr) {
        return HitTestContext._findAttribute(element, attr, this._viewHelper.viewDomNode);
    }
    static _findAttribute(element, attr, stopAt) {
        while (element && element !== document.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._viewHelper.getLineWidth(lineNumber);
    }
    visibleRangeForPosition(lineNumber, column) {
        return this._viewHelper.visibleRangeForPosition(lineNumber, column);
    }
    getPositionFromDOMInfo(spanNode, offset) {
        return this._viewHelper.getPositionFromDOMInfo(spanNode, offset);
    }
    getCurrentScrollTop() {
        return this._context.viewLayout.getCurrentScrollTop();
    }
    getCurrentScrollLeft() {
        return this._context.viewLayout.getCurrentScrollLeft();
    }
}
class BareHitTestRequest {
    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.mouseColumn = Math.max(0, MouseTargetFactory._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth));
    }
}
class HitTestRequest extends BareHitTestRequest {
    constructor(ctx, editorPos, pos, relativePos, target) {
        super(ctx, editorPos, pos, relativePos);
        this._ctx = ctx;
        if (target) {
            this.target = target;
            this.targetPath = PartFingerprints.collect(target, ctx.viewDomNode);
        }
        else {
            this.target = null;
            this.targetPath = new Uint8Array(0);
        }
    }
    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}\n\ttarget: ${this.target ? this.target.outerHTML : null}`;
    }
    _getMouseColumn(position = null) {
        if (position && position.column < this._ctx.viewModel.getLineMaxColumn(position.lineNumber)) {
            // Most likely, the line contains foreign decorations...
            return CursorColumns.visibleColumnFromColumn(this._ctx.viewModel.getLineContent(position.lineNumber), position.column, this._ctx.viewModel.model.getOptions().tabSize) + 1;
        }
        return this.mouseColumn;
    }
    fulfillUnknown(position = null) {
        return MouseTarget.createUnknown(this.target, this._getMouseColumn(position), position);
    }
    fulfillTextarea() {
        return MouseTarget.createTextarea(this.target, this._getMouseColumn());
    }
    fulfillMargin(type, position, range, detail) {
        return MouseTarget.createMargin(type, this.target, this._getMouseColumn(position), position, range, detail);
    }
    fulfillViewZone(type, position, detail) {
        return MouseTarget.createViewZone(type, this.target, this._getMouseColumn(position), position, detail);
    }
    fulfillContentText(position, range, detail) {
        return MouseTarget.createContentText(this.target, this._getMouseColumn(position), position, range, detail);
    }
    fulfillContentEmpty(position, detail) {
        return MouseTarget.createContentEmpty(this.target, this._getMouseColumn(position), position, detail);
    }
    fulfillContentWidget(detail) {
        return MouseTarget.createContentWidget(this.target, this._getMouseColumn(), detail);
    }
    fulfillScrollbar(position) {
        return MouseTarget.createScrollbar(this.target, this._getMouseColumn(position), position);
    }
    fulfillOverlayWidget(detail) {
        return MouseTarget.createOverlayWidget(this.target, this._getMouseColumn(), detail);
    }
    withTarget(target) {
        return new HitTestRequest(this._ctx, this.editorPos, this.pos, this.relativePos, target);
    }
}
const EMPTY_CONTENT_AFTER_LINES = { isAfterLines: true };
function createEmptyContentDataInLines(horizontalDistanceToText) {
    return {
        isAfterLines: false,
        horizontalDistanceToText: horizontalDistanceToText
    };
}
class MouseTargetFactory {
    constructor(context, viewHelper) {
        this._context = context;
        this._viewHelper = viewHelper;
    }
    mouseTargetIsWidget(e) {
        const t = e.target;
        const path = PartFingerprints.collect(t, this._viewHelper.viewDomNode);
        // Is it a content widget?
        if (ElementPath.isChildOfContentWidgets(path) || ElementPath.isChildOfOverflowingContentWidgets(path)) {
            return true;
        }
        // Is it an overlay widget?
        if (ElementPath.isChildOfOverlayWidgets(path)) {
            return true;
        }
        return false;
    }
    createMouseTarget(lastRenderData, editorPos, pos, relativePos, target) {
        const ctx = new HitTestContext(this._context, this._viewHelper, lastRenderData);
        const request = new HitTestRequest(ctx, editorPos, pos, relativePos, target);
        try {
            const r = MouseTargetFactory._createMouseTarget(ctx, request, false);
            // console.log(MouseTarget.toString(r));
            return r;
        }
        catch (err) {
            // console.log(err);
            return request.fulfillUnknown();
        }
    }
    static _createMouseTarget(ctx, request, domHitTestExecuted) {
        // console.log(`${domHitTestExecuted ? '=>' : ''}CAME IN REQUEST: ${request}`);
        // First ensure the request has a target
        if (request.target === null) {
            if (domHitTestExecuted) {
                // Still no target... and we have already executed hit test...
                return request.fulfillUnknown();
            }
            const hitTestResult = MouseTargetFactory._doHitTest(ctx, request);
            if (hitTestResult.type === 1 /* HitTestResultType.Content */) {
                return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.spanNode, hitTestResult.position, hitTestResult.injectedText);
            }
            return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true);
        }
        // we know for a fact that request.target is not null
        const resolvedRequest = request;
        let result = null;
        result = result || MouseTargetFactory._hitTestContentWidget(ctx, resolvedRequest);
        result = result || MouseTargetFactory._hitTestOverlayWidget(ctx, resolvedRequest);
        result = result || MouseTargetFactory._hitTestMinimap(ctx, resolvedRequest);
        result = result || MouseTargetFactory._hitTestScrollbarSlider(ctx, resolvedRequest);
        result = result || MouseTargetFactory._hitTestViewZone(ctx, resolvedRequest);
        result = result || MouseTargetFactory._hitTestMargin(ctx, resolvedRequest);
        result = result || MouseTargetFactory._hitTestViewCursor(ctx, resolvedRequest);
        result = result || MouseTargetFactory._hitTestTextArea(ctx, resolvedRequest);
        result = result || MouseTargetFactory._hitTestViewLines(ctx, resolvedRequest, domHitTestExecuted);
        result = result || MouseTargetFactory._hitTestScrollbar(ctx, resolvedRequest);
        return (result || request.fulfillUnknown());
    }
    static _hitTestContentWidget(ctx, request) {
        // Is it a content widget?
        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 _hitTestOverlayWidget(ctx, request) {
        // Is it an overlay widget?
        if (ElementPath.isChildOfOverlayWidgets(request.targetPath)) {
            const widgetId = ctx.findAttribute(request.target, 'widgetId');
            if (widgetId) {
                return request.fulfillOverlayWidget(widgetId);
            }
            else {
                return request.fulfillUnknown();
            }
        }
        return null;
    }
    static _hitTestViewCursor(ctx, request) {
        if (request.target) {
            // Check if we've hit a painted cursor
            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) {
            // Edge has a bug when hit-testing the exact position of a cursor,
            // instead of returning the correct dom node, it returns the
            // first or last rendered view line dom node, therefore help it out
            // and first check if we are on top of a cursor
            const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData;
            const mouseContentHorizontalOffset = request.mouseContentHorizontalOffset;
            const mouseVerticalOffset = request.mouseVerticalOffset;
            for (const d of lastViewCursorsRenderData) {
                if (mouseContentHorizontalOffset < d.contentLeft) {
                    // mouse position is to the left of the cursor
                    continue;
                }
                if (mouseContentHorizontalOffset > d.contentLeft + d.width) {
                    // mouse position is to the right of the cursor
                    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 _hitTestViewZone(ctx, request) {
        const viewZoneData = ctx.getZoneAtCoord(request.mouseVerticalOffset);
        if (viewZoneData) {
            const mouseTargetType = (request.isInContentArea ? 8 /* MouseTargetType.CONTENT_VIEW_ZONE */ : 5 /* MouseTargetType.GUTTER_VIEW_ZONE */);
            return request.fulfillViewZone(mouseTargetType, viewZoneData.position, viewZoneData);
        }
        return null;
    }
    static _hitTestTextArea(ctx, request) {
        // Is it the textarea?
        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 _hitTestMargin(ctx, request) {
        if (request.isInMarginArea) {
            const res = ctx.getFullLineRangeAtCoord(request.mouseVerticalOffset);
            const pos = res.range.getStartPosition();
            let offset = Math.abs(request.relativePos.x);
            const detail = {
                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) {
                // On the glyph margin
                return request.fulfillMargin(2 /* MouseTargetType.GUTTER_GLYPH_MARGIN */, pos, res.range, detail);
            }
            offset -= ctx.layoutInfo.glyphMarginWidth;
            if (offset <= ctx.layoutInfo.lineNumbersWidth) {
                // On the line numbers
                return request.fulfillMargin(3 /* MouseTargetType.GUTTER_LINE_NUMBERS */, pos, res.range, detail);
            }
            offset -= ctx.layoutInfo.lineNumbersWidth;
            // On the line decorations
            return request.fulfillMargin(4 /* MouseTargetType.GUTTER_LINE_DECORATIONS */, pos, res.range, detail);
        }
        return null;
    }
    static _hitTestViewLines(ctx, request, domHitTestExecuted) {
        if (!ElementPath.isChildOfViewLines(request.targetPath)) {
            return null;
        }
        if (ctx.isInTopPadding(request.mouseVerticalOffset)) {
            return request.fulfillContentEmpty(new Position(1, 1), EMPTY_CONTENT_AFTER_LINES);
        }
        // Check if it is below any lines and any view zones
        if (ctx.isAfterLines(request.mouseVerticalOffset) || ctx.isInBottomPadding(request.mouseVerticalOffset)) {
            // This most likely indicates it happened after the last view-line
            const lineCount = ctx.viewModel.getLineCount();
            const maxLineColumn = ctx.viewModel.getLineMaxColumn(lineCount);
            return request.fulfillContentEmpty(new Position(lineCount, maxLineColumn), EMPTY_CONTENT_AFTER_LINES);
        }
        if (domHitTestExecuted) {
            // Check if we are hitting a view-line (can happen in the case of inline decorations on empty lines)
            // See https://github.com/microsoft/vscode/issues/46942
            if (ElementPath.isStrictChildOfViewLines(request.targetPath)) {
                const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
                if (ctx.viewModel.getLineLength(lineNumber) === 0) {
                    const lineWidth = ctx.getLineWidth(lineNumber);
                    const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
                    return request.fulfillContentEmpty(new Position(lineNumber, 1), detail);
                }
                const lineWidth = ctx.getLineWidth(lineNumber);
                if (request.mouseContentHorizontalOffset >= lineWidth) {
                    const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
                    const pos = new Position(lineNumber, ctx.viewModel.getLineMaxColumn(lineNumber));
                    return request.fulfillContentEmpty(pos, detail);
                }
            }
            // We have already executed hit test...
            return request.fulfillUnknown();
        }
        const hitTestResult = MouseTargetFactory._doHitTest(ctx, request);
        if (hitTestResult.type === 1 /* HitTestResultType.Content */) {
            return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.spanNode, hitTestResult.position, hitTestResult.injectedText);
        }
        return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true);
    }
    static _hitTestMinimap(ctx, request) {
        if (ElementPath.isChildOfMinimap(request.targetPath)) {
            const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
            const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
            return request.fulfillScrollbar(new Position(possibleLineNumber, maxColumn));
        }
        return null;
    }
    static _hitTestScrollbarSlider(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 Position(possibleLineNumber, maxColumn));
                }
            }
        }
        return null;
    }
    static _hitTestScrollbar(ctx, request) {
        // Is it the overview ruler?
        // Is it a child of the scrollable element?
        if (ElementPath.isChildOfScrollableElement(request.targetPath)) {
            const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
            const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
            return request.fulfillScrollbar(new Position(possibleLineNumber, maxColumn));
        }
        return null;
    }
    getMouseColumn(relativePos) {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        const mouseContentHorizontalOffset = this._context.viewLayout.getCurrentScrollLeft() + relativePos.x - layoutInfo.contentLeft;
        return MouseTargetFactory._getMouseColumn(mouseContentHorizontalOffset, options.get(46 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth);
    }
    static _getMouseColumn(mouseContentHorizontalOffset, typicalHalfwidthCharacterWidth) {
        if (mouseContentHorizontalOffset < 0) {
            return 1;
        }
        const chars = Math.round(mouseContentHorizontalOffset / typicalHalfwidthCharacterWidth);
        return (chars + 1);
    }
    static createMouseTargetFromHitTestPosition(ctx, request, spanNode, pos, injectedText) {
        const lineNumber = pos.lineNumber;
        const column = pos.column;
        const lineWidth = ctx.getLineWidth(lineNumber);
        if (request.mouseContentHorizontalOffset > lineWidth) {
            const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
            return request.fulfillContentEmpty(pos, detail);
        }
        const visibleRange = ctx.visibleRangeForPosition(lineNumber, column);
        if (!visibleRange) {
            return request.fulfillUnknown(pos);
        }
        const columnHorizontalOffset = visibleRange.left;
        if (request.mouseContentHorizontalOffset === columnHorizontalOffset) {
            return request.fulfillContentText(pos, null, { mightBeForeignElement: !!injectedText, injectedText });
        }
        const points = [];
        points.push({ offset: visibleRange.left, column: column });
        if (column > 1) {
            const visibleRange = ctx.visibleRangeForPosition(lineNumber, column - 1);
            if (visibleRange) {
                points.push({ offset: visibleRange.left, column: column - 1 });
            }
        }
        const lineMaxColumn = ctx.viewModel.getLineMaxColumn(lineNumber);
        if (column < lineMaxColumn) {
            const visibleRange = ctx.visibleRangeForPosition(lineNumber, column + 1);
            if (visibleRange) {
                points.push({ offset: visibleRange.left, column: column + 1 });
            }
        }
        points.sort((a, b) => a.offset - b.offset);
        const mouseCoordinates = request.pos.toClientCoordinates();
        const spanNodeClientRect = spanNode.getBoundingClientRect();
        const mouseIsOverSpanNode = (spanNodeClientRect.left <= mouseCoordinates.clientX && mouseCoordinates.clientX <= spanNodeClientRect.right);
        for (let i = 1; i < points.length; i++) {
            const prev = points[i - 1];
            const curr = points[i];
            if (prev.offset <= request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset <= curr.offset) {
                const rng = new Range(lineNumber, prev.column, lineNumber, curr.column);
                // See https://github.com/microsoft/vscode/issues/152819
                // Due to the use of zwj, the browser's hit test result is skewed towards the left
                // Here we try to correct that if the mouse horizontal offset is closer to the right than the left
                const prevDelta = Math.abs(prev.offset - request.mouseContentHorizontalOffset);
                const nextDelta = Math.abs(curr.offset - request.mouseContentHorizontalOffset);
                const resultPos = (prevDelta < nextDelta
                    ? new Position(lineNumber, prev.column)
                    : new Position(lineNumber, curr.column));
                return request.fulfillContentText(resultPos, rng, { mightBeForeignElement: !mouseIsOverSpanNode || !!injectedText, injectedText });
            }
        }
        return request.fulfillContentText(pos, null, { mightBeForeignElement: !mouseIsOverSpanNode || !!injectedText, injectedText });
    }
    /**
     * Most probably WebKit browsers and Edge
     */
    static _doHitTestWithCaretRangeFromPoint(ctx, request) {
        // In Chrome, especially on Linux it is possible to click between lines,
        // so try to adjust the `hity` below so that it lands in the center of a line
        const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
        const lineVerticalOffset = ctx.getVerticalOffsetForLineNumber(lineNumber);
        const lineCenteredVerticalOffset = lineVerticalOffset + Math.floor(ctx.lineHeight / 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 PageCoordinates(request.pos.x, adjustedPageY);
        const r = this._actualDoHitTestWithCaretRangeFromPoint(ctx, adjustedPage.toClientCoordinates());
        if (r.type === 1 /* HitTestResultType.Content */) {
            return r;
        }
        // Also try to hit test without the adjustment (for the edge cases that we are near the top or bottom)
        return this._actualDoHitTestWithCaretRangeFromPoint(ctx, request.pos.toClientCoordinates());
    }
    static _actualDoHitTestWithCaretRangeFromPoint(ctx, coords) {
        const shadowRoot = getShadowRoot(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 = document.caretRangeFromPoint(coords.clientX, coords.clientY);
        }
        if (!range || !range.startContainer) {
            return new UnknownHitTestResult();
        }
        // Chrome always hits a TEXT_NODE, while Edge sometimes hits a token span
        const startContainer = range.startContainer;
        if (startContainer.nodeType === startContainer.TEXT_NODE) {
            // startContainer is expected to be the token text
            const parent1 = startContainer.parentNode; // expected to be the token span
            const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line container span
            const parent3 = parent2 ? parent2.parentNode : null; // expected to be the view line div
            const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
            if (parent3ClassName === ViewLine.CLASS_NAME) {
                return HitTestResult.createFromDOMInfo(ctx, parent1, range.startOffset);
            }
            else {
                return new UnknownHitTestResult(startContainer.parentNode);
            }
        }
        else if (startContainer.nodeType === startContainer.ELEMENT_NODE) {
            // startContainer is expected to be the token span
            const parent1 = startContainer.parentNode; // expected to be the view line container span
            const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line div
            const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null;
            if (parent2ClassName === ViewLine.CLASS_NAME) {
                return HitTestResult.createFromDOMInfo(ctx, startContainer, startContainer.textContent.length);
            }
            else {
                return new UnknownHitTestResult(startContainer);
            }
        }
        return new UnknownHitTestResult();
    }
    /**
     * Most probably Gecko
     */
    static _doHitTestWithCaretPositionFromPoint(ctx, coords) {
        const hitResult = document.caretPositionFromPoint(coords.clientX, coords.clientY);
        if (hitResult.offsetNode.nodeType === hitResult.offsetNode.TEXT_NODE) {
            // offsetNode is expected to be the token text
            const parent1 = hitResult.offsetNode.parentNode; // expected to be the token span
            const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line container span
            const parent3 = parent2 ? parent2.parentNode : null; // expected to be the view line div
            const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
            if (parent3ClassName === ViewLine.CLASS_NAME) {
                return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode.parentNode, hitResult.offset);
            }
            else {
                return new UnknownHitTestResult(hitResult.offsetNode.parentNode);
            }
        }
        // For inline decorations, Gecko sometimes returns the `<span>` of the line and the offset is the `<span>` with the inline decoration
        // Some other times, it returns the `<span>` with the inline decoration
        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 === ViewLine.CLASS_NAME) {
                // it returned the `<span>` of the line and the offset is the `<span>` with the inline decoration
                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 === ViewLine.CLASS_NAME) {
                // it returned the `<span>` with the inline decoration
                return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode, 0);
            }
        }
        return new UnknownHitTestResult(hitResult.offsetNode);
    }
    static _snapToSoftTabBoundary(position, viewModel) {
        const lineContent = viewModel.getLineContent(position.lineNumber);
        const { tabSize } = viewModel.model.getOptions();
        const newPosition = AtomicTabMoveOperations.atomicPosition(lineContent, position.column - 1, tabSize, 2 /* Direction.Nearest */);
        if (newPosition !== -1) {
            return new Position(position.lineNumber, newPosition + 1);
        }
        return position;
    }
    static _doHitTest(ctx, request) {
        let result = new UnknownHitTestResult();
        if (typeof document.caretRangeFromPoint === 'function') {
            result = this._doHitTestWithCaretRangeFromPoint(ctx, request);
        }
        else if (document.caretPositionFromPoint) {
            result = this._doHitTestWithCaretPositionFromPoint(ctx, request.pos.toClientCoordinates());
        }
        if (result.type === 1 /* HitTestResultType.Content */) {
            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);
            }
        }
        // Snap to the nearest soft tab boundary if atomic soft tabs are enabled.
        if (result.type === 1 /* HitTestResultType.Content */ && ctx.stickyTabStops) {
            result = new ContentHitTestResult(this._snapToSoftTabBoundary(result.position, ctx.viewModel), result.spanNode, result.injectedText);
        }
        return result;
    }
}
function shadowCaretRangeFromPoint(shadowRoot, x, y) {
    const range = document.createRange();
    // Get the element under the point
    let el = shadowRoot.elementFromPoint(x, y);
    if (el !== null) {
        // Get the last child of the element until its firstChild is a text node
        // This assumes that the pointer is on the right of the line, out of the tokens
        // and that we want to get the offset of the last token of the line
        while (el && el.firstChild && el.firstChild.nodeType !== el.firstChild.TEXT_NODE && el.lastChild && el.lastChild.firstChild) {
            el = el.lastChild;
        }
        // Grab its rect
        const rect = el.getBoundingClientRect();
        // And its font
        const font = window.getComputedStyle(el, null).getPropertyValue('font');
        // And also its txt content
        const text = el.innerText;
        // Position the pixel cursor at the left of the element
        let pixelCursor = rect.left;
        let offset = 0;
        let step;
        // If the point is on the right of the box put the cursor after the last character
        if (x > rect.left + rect.width) {
            offset = text.length;
        }
        else {
            const charWidthReader = CharWidthReader.getInstance();
            // Goes through all the characters of the innerText, and checks if the x of the point
            // belongs to the character.
            for (let i = 0; i < text.length + 1; i++) {
                // The step is half the width of the character
                step = charWidthReader.getCharWidth(text.charAt(i), font) / 2;
                // Move to the center of the character
                pixelCursor += step;
                // If the x of the point is smaller that the position of the cursor, the point is over that character
                if (x < pixelCursor) {
                    offset = i;
                    break;
                }
                // Move between the current character and the next
                pixelCursor += step;
            }
        }
        // Creates a range with the text node of the element and set the offset found
        range.setStart(el.firstChild, offset);
        range.setEnd(el.firstChild, offset);
    }
    return range;
}
class CharWidthReader {
    constructor() {
        this._cache = {};
        this._canvas = document.createElement('canvas');
    }
    static getInstance() {
        if (!CharWidthReader._INSTANCE) {
            CharWidthReader._INSTANCE = new CharWidthReader();
        }
        return CharWidthReader._INSTANCE;
    }
    getCharWidth(char, font) {
        const cacheKey = char + font;
        if (this._cache[cacheKey]) {
            return this._cache[cacheKey];
        }
        const context = this._canvas.getContext('2d');
        context.font = font;
        const metrics = context.measureText(char);
        const width = metrics.width;
        this._cache[cacheKey] = width;
        return width;
    }
}
CharWidthReader._INSTANCE = null;

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/controller/mouseHandler.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/











class MouseHandler extends ViewEventHandler {
    constructor(context, viewController, viewHelper) {
        super();
        this._mouseLeaveMonitor = null;
        this._context = context;
        this.viewController = viewController;
        this.viewHelper = viewHelper;
        this.mouseTargetFactory = new MouseTargetFactory(this._context, viewHelper);
        this._mouseDownOperation = this._register(new MouseDownOperation(this._context, this.viewController, this.viewHelper, (e, testEventTarget) => this._createMouseTarget(e, testEventTarget), (e) => this._getMouseColumn(e)));
        this.lastMouseLeaveTime = -1;
        this._height = this._context.configuration.options.get(133 /* EditorOption.layoutInfo */).height;
        const mouseEvents = new EditorMouseEventFactory(this.viewHelper.viewDomNode);
        this._register(mouseEvents.onContextMenu(this.viewHelper.viewDomNode, (e) => this._onContextMenu(e, true)));
        this._register(mouseEvents.onMouseMove(this.viewHelper.viewDomNode, (e) => {
            this._onMouseMove(e);
            // See https://github.com/microsoft/vscode/issues/138789
            // When moving the mouse really quickly, the browser sometimes forgets to
            // send us a `mouseleave` or `mouseout` event. We therefore install here
            // a global `mousemove` listener to manually recover if the mouse goes outside
            // the editor. As soon as the mouse leaves outside of the editor, we
            // remove this listener
            if (!this._mouseLeaveMonitor) {
                this._mouseLeaveMonitor = addDisposableListener(document, 'mousemove', (e) => {
                    if (!this.viewHelper.viewDomNode.contains(e.target)) {
                        // went outside the editor!
                        this._onMouseLeave(new EditorMouseEvent(e, false, this.viewHelper.viewDomNode));
                    }
                });
            }
        }));
        this._register(mouseEvents.onMouseUp(this.viewHelper.viewDomNode, (e) => this._onMouseUp(e)));
        this._register(mouseEvents.onMouseLeave(this.viewHelper.viewDomNode, (e) => this._onMouseLeave(e)));
        // `pointerdown` events can't be used to determine if there's a double click, or triple click
        // because their `e.detail` is always 0.
        // We will therefore save the pointer id for the mouse and then reuse it in the `mousedown` event
        // for `element.setPointerCapture`.
        let capturePointerId = 0;
        this._register(mouseEvents.onPointerDown(this.viewHelper.viewDomNode, (e, pointerId) => {
            capturePointerId = pointerId;
        }));
        // The `pointerup` listener registered by `GlobalEditorPointerMoveMonitor` does not get invoked 100% of the times.
        // I speculate that this is because the `pointerup` listener is only registered during the `mousedown` event, and perhaps
        // the `pointerup` event is already queued for dispatching, which makes it that the new listener doesn't get fired.
        // See https://github.com/microsoft/vscode/issues/146486 for repro steps.
        // To compensate for that, we simply register here a `pointerup` listener and just communicate it.
        this._register(addDisposableListener(this.viewHelper.viewDomNode, EventType.POINTER_UP, (e) => {
            this._mouseDownOperation.onPointerUp();
        }));
        this._register(mouseEvents.onMouseDown(this.viewHelper.viewDomNode, (e) => this._onMouseDown(e, capturePointerId)));
        const onMouseWheel = (browserEvent) => {
            this.viewController.emitMouseWheel(browserEvent);
            if (!this._context.configuration.options.get(70 /* EditorOption.mouseWheelZoom */)) {
                return;
            }
            const e = new StandardWheelEvent(browserEvent);
            const doMouseWheelZoom = (isMacintosh
                // on macOS we support cmd + two fingers scroll (`metaKey` set)
                // and also the two fingers pinch gesture (`ctrKey` set)
                ? ((browserEvent.metaKey || browserEvent.ctrlKey) && !browserEvent.shiftKey && !browserEvent.altKey)
                : (browserEvent.ctrlKey && !browserEvent.metaKey && !browserEvent.shiftKey && !browserEvent.altKey));
            if (doMouseWheelZoom) {
                const zoomLevel = EditorZoom.getZoomLevel();
                const delta = e.deltaY > 0 ? 1 : -1;
                EditorZoom.setZoomLevel(zoomLevel + delta);
                e.preventDefault();
                e.stopPropagation();
            }
        };
        this._register(addDisposableListener(this.viewHelper.viewDomNode, EventType.MOUSE_WHEEL, onMouseWheel, { capture: true, passive: false }));
        this._context.addEventHandler(this);
    }
    dispose() {
        this._context.removeEventHandler(this);
        if (this._mouseLeaveMonitor) {
            this._mouseLeaveMonitor.dispose();
            this._mouseLeaveMonitor = null;
        }
        super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        if (e.hasChanged(133 /* EditorOption.layoutInfo */)) {
            // layout change
            const height = this._context.configuration.options.get(133 /* EditorOption.layoutInfo */).height;
            if (this._height !== height) {
                this._height = height;
                this._mouseDownOperation.onHeightChanged();
            }
        }
        return false;
    }
    onCursorStateChanged(e) {
        this._mouseDownOperation.onCursorStateChanged(e);
        return false;
    }
    onFocusChanged(e) {
        return false;
    }
    onScrollChanged(e) {
        this._mouseDownOperation.onScrollChanged();
        return false;
    }
    // --- end event handlers
    getTargetAtClientPoint(clientX, clientY) {
        const clientPos = new ClientCoordinates(clientX, clientY);
        const pos = clientPos.toPageCoordinates();
        const editorPos = createEditorPagePosition(this.viewHelper.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 = createCoordinatesRelativeToEditor(this.viewHelper.viewDomNode, editorPos, pos);
        return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), editorPos, pos, relativePos, null);
    }
    _createMouseTarget(e, testEventTarget) {
        let target = e.target;
        if (!this.viewHelper.viewDomNode.contains(target)) {
            const shadowRoot = getShadowRoot(this.viewHelper.viewDomNode);
            if (shadowRoot) {
                target = shadowRoot.elementsFromPoint(e.posx, e.posy).find((el) => this.viewHelper.viewDomNode.contains(el));
            }
        }
        return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), e.editorPos, e.pos, e.relativePos, testEventTarget ? target : null);
    }
    _getMouseColumn(e) {
        return this.mouseTargetFactory.getMouseColumn(e.relativePos);
    }
    _onContextMenu(e, testEventTarget) {
        this.viewController.emitContextMenu({
            event: e,
            target: this._createMouseTarget(e, testEventTarget)
        });
    }
    _onMouseMove(e) {
        const targetIsWidget = this.mouseTargetFactory.mouseTargetIsWidget(e);
        if (!targetIsWidget) {
            e.preventDefault();
        }
        if (this._mouseDownOperation.isActive()) {
            // In selection/drag operation
            return;
        }
        const actualMouseMoveTime = e.timestamp;
        if (actualMouseMoveTime < this.lastMouseLeaveTime) {
            // Due to throttling, this event occurred before the mouse left the editor, therefore ignore it.
            return;
        }
        this.viewController.emitMouseMove({
            event: e,
            target: this._createMouseTarget(e, true)
        });
    }
    _onMouseLeave(e) {
        if (this._mouseLeaveMonitor) {
            this._mouseLeaveMonitor.dispose();
            this._mouseLeaveMonitor = null;
        }
        this.lastMouseLeaveTime = (new Date()).getTime();
        this.viewController.emitMouseLeave({
            event: e,
            target: null
        });
    }
    _onMouseUp(e) {
        this.viewController.emitMouseUp({
            event: e,
            target: this._createMouseTarget(e, true)
        });
    }
    _onMouseDown(e, pointerId) {
        const t = this._createMouseTarget(e, true);
        const targetIsContent = (t.type === 6 /* MouseTargetType.CONTENT_TEXT */ || t.type === 7 /* MouseTargetType.CONTENT_EMPTY */);
        const targetIsGutter = (t.type === 2 /* MouseTargetType.GUTTER_GLYPH_MARGIN */ || t.type === 3 /* MouseTargetType.GUTTER_LINE_NUMBERS */ || t.type === 4 /* MouseTargetType.GUTTER_LINE_DECORATIONS */);
        const targetIsLineNumbers = (t.type === 3 /* MouseTargetType.GUTTER_LINE_NUMBERS */);
        const selectOnLineNumbers = this._context.configuration.options.get(100 /* EditorOption.selectOnLineNumbers */);
        const targetIsViewZone = (t.type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */ || t.type === 5 /* MouseTargetType.GUTTER_VIEW_ZONE */);
        const targetIsWidget = (t.type === 9 /* MouseTargetType.CONTENT_WIDGET */);
        let shouldHandle = e.leftButton || e.middleButton;
        if (isMacintosh && e.leftButton && e.ctrlKey) {
            shouldHandle = false;
        }
        const focus = () => {
            e.preventDefault();
            this.viewHelper.focusTextArea();
        };
        if (shouldHandle && (targetIsContent || (targetIsLineNumbers && selectOnLineNumbers))) {
            focus();
            this._mouseDownOperation.start(t.type, e, pointerId);
        }
        else if (targetIsGutter) {
            // Do not steal focus
            e.preventDefault();
        }
        else if (targetIsViewZone) {
            const viewZoneData = t.detail;
            if (shouldHandle && this.viewHelper.shouldSuppressMouseDownOnViewZone(viewZoneData.viewZoneId)) {
                focus();
                this._mouseDownOperation.start(t.type, e, pointerId);
                e.preventDefault();
            }
        }
        else if (targetIsWidget && this.viewHelper.shouldSuppressMouseDownOnWidget(t.detail)) {
            focus();
            e.preventDefault();
        }
        this.viewController.emitMouseDown({
            event: e,
            target: t
        });
    }
}
class MouseDownOperation extends Disposable {
    constructor(context, viewController, viewHelper, createMouseTarget, getMouseColumn) {
        super();
        this._context = context;
        this._viewController = viewController;
        this._viewHelper = viewHelper;
        this._createMouseTarget = createMouseTarget;
        this._getMouseColumn = getMouseColumn;
        this._mouseMoveMonitor = this._register(new GlobalEditorPointerMoveMonitor(this._viewHelper.viewDomNode));
        this._onScrollTimeout = this._register(new TimeoutTimer());
        this._mouseState = new MouseDownState();
        this._currentSelection = new Selection(1, 1, 1, 1);
        this._isActive = false;
        this._lastMouseEvent = null;
    }
    dispose() {
        super.dispose();
    }
    isActive() {
        return this._isActive;
    }
    _onMouseDownThenMove(e) {
        this._lastMouseEvent = e;
        this._mouseState.setModifiers(e);
        const position = this._findMousePosition(e, false);
        if (!position) {
            // Ignoring because position is unknown
            return;
        }
        if (this._mouseState.isDragAndDrop) {
            this._viewController.emitMouseDrag({
                event: e,
                target: position
            });
        }
        else {
            this._dispatchMouse(position, true);
        }
    }
    start(targetType, e, pointerId) {
        this._lastMouseEvent = e;
        this._mouseState.setStartedOnLineNumbers(targetType === 3 /* MouseTargetType.GUTTER_LINE_NUMBERS */);
        this._mouseState.setStartButtons(e);
        this._mouseState.setModifiers(e);
        const position = this._findMousePosition(e, true);
        if (!position || !position.position) {
            // Ignoring because position is unknown
            return;
        }
        this._mouseState.trySetCount(e.detail, position.position);
        // Overwrite the detail of the MouseEvent, as it will be sent out in an event and contributions might rely on it.
        e.detail = this._mouseState.count;
        const options = this._context.configuration.options;
        if (!options.get(83 /* EditorOption.readOnly */)
            && options.get(31 /* EditorOption.dragAndDrop */)
            && !options.get(18 /* EditorOption.columnSelection */)
            && !this._mouseState.altKey // we don't support multiple mouse
            && e.detail < 2 // only single click on a selection can work
            && !this._isActive // the mouse is not down yet
            && !this._currentSelection.isEmpty() // we don't drag single cursor
            && (position.type === 6 /* MouseTargetType.CONTENT_TEXT */) // single click on text
            && position.position && this._currentSelection.containsPosition(position.position) // single click on a selection
        ) {
            this._mouseState.isDragAndDrop = true;
            this._isActive = true;
            this._mouseMoveMonitor.startMonitoring(this._viewHelper.viewLinesDomNode, pointerId, e.buttons, (e) => this._onMouseDownThenMove(e), (browserEvent) => {
                const position = this._findMousePosition(this._lastMouseEvent, false);
                if (browserEvent && browserEvent instanceof KeyboardEvent) {
                    // cancel
                    this._viewController.emitMouseDropCanceled();
                }
                else {
                    this._viewController.emitMouseDrop({
                        event: this._lastMouseEvent,
                        target: (position ? this._createMouseTarget(this._lastMouseEvent, true) : null) // Ignoring because position is unknown, e.g., Content View Zone
                    });
                }
                this._stop();
            });
            return;
        }
        this._mouseState.isDragAndDrop = false;
        this._dispatchMouse(position, e.shiftKey);
        if (!this._isActive) {
            this._isActive = true;
            this._mouseMoveMonitor.startMonitoring(this._viewHelper.viewLinesDomNode, pointerId, e.buttons, (e) => this._onMouseDownThenMove(e), () => this._stop());
        }
    }
    _stop() {
        this._isActive = false;
        this._onScrollTimeout.cancel();
    }
    onHeightChanged() {
        this._mouseMoveMonitor.stopMonitoring();
    }
    onPointerUp() {
        this._mouseMoveMonitor.stopMonitoring();
    }
    onScrollChanged() {
        if (!this._isActive) {
            return;
        }
        this._onScrollTimeout.setIfNotSet(() => {
            if (!this._lastMouseEvent) {
                return;
            }
            const position = this._findMousePosition(this._lastMouseEvent, false);
            if (!position) {
                // Ignoring because position is unknown
                return;
            }
            if (this._mouseState.isDragAndDrop) {
                // Ignoring because users are dragging the text
                return;
            }
            this._dispatchMouse(position, true);
        }, 10);
    }
    onCursorStateChanged(e) {
        this._currentSelection = e.selections[0];
    }
    _getPositionOutsideEditor(e) {
        const editorContent = e.editorPos;
        const model = this._context.viewModel;
        const viewLayout = this._context.viewLayout;
        const mouseColumn = this._getMouseColumn(e);
        if (e.posy < editorContent.y) {
            const verticalOffset = Math.max(viewLayout.getCurrentScrollTop() - (editorContent.y - e.posy), 0);
            const viewZoneData = HitTestContext.getZoneAtCoord(this._context, verticalOffset);
            if (viewZoneData) {
                const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
                if (newPosition) {
                    return MouseTarget.createOutsideEditor(mouseColumn, newPosition);
                }
            }
            const aboveLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
            return MouseTarget.createOutsideEditor(mouseColumn, new Position(aboveLineNumber, 1));
        }
        if (e.posy > editorContent.y + editorContent.height) {
            const verticalOffset = viewLayout.getCurrentScrollTop() + e.relativePos.y;
            const viewZoneData = HitTestContext.getZoneAtCoord(this._context, verticalOffset);
            if (viewZoneData) {
                const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
                if (newPosition) {
                    return MouseTarget.createOutsideEditor(mouseColumn, newPosition);
                }
            }
            const belowLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
            return MouseTarget.createOutsideEditor(mouseColumn, new Position(belowLineNumber, model.getLineMaxColumn(belowLineNumber)));
        }
        const possibleLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getCurrentScrollTop() + e.relativePos.y);
        if (e.posx < editorContent.x) {
            return MouseTarget.createOutsideEditor(mouseColumn, new Position(possibleLineNumber, 1));
        }
        if (e.posx > editorContent.x + editorContent.width) {
            return MouseTarget.createOutsideEditor(mouseColumn, new Position(possibleLineNumber, model.getLineMaxColumn(possibleLineNumber)));
        }
        return null;
    }
    _findMousePosition(e, testEventTarget) {
        const positionOutsideEditor = this._getPositionOutsideEditor(e);
        if (positionOutsideEditor) {
            return positionOutsideEditor;
        }
        const t = this._createMouseTarget(e, testEventTarget);
        const hintedPosition = t.position;
        if (!hintedPosition) {
            return null;
        }
        if (t.type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */ || t.type === 5 /* MouseTargetType.GUTTER_VIEW_ZONE */) {
            const newPosition = this._helpPositionJumpOverViewZone(t.detail);
            if (newPosition) {
                return MouseTarget.createViewZone(t.type, t.element, t.mouseColumn, newPosition, t.detail);
            }
        }
        return t;
    }
    _helpPositionJumpOverViewZone(viewZoneData) {
        // Force position on view zones to go above or below depending on where selection started from
        const selectionStart = new Position(this._currentSelection.selectionStartLineNumber, this._currentSelection.selectionStartColumn);
        const positionBefore = viewZoneData.positionBefore;
        const positionAfter = viewZoneData.positionAfter;
        if (positionBefore && positionAfter) {
            if (positionBefore.isBefore(selectionStart)) {
                return positionBefore;
            }
            else {
                return positionAfter;
            }
        }
        return null;
    }
    _dispatchMouse(position, inSelectionMode) {
        if (!position.position) {
            return;
        }
        this._viewController.dispatchMouse({
            position: position.position,
            mouseColumn: position.mouseColumn,
            startedOnLineNumbers: this._mouseState.startedOnLineNumbers,
            inSelectionMode: inSelectionMode,
            mouseDownCount: this._mouseState.count,
            altKey: this._mouseState.altKey,
            ctrlKey: this._mouseState.ctrlKey,
            metaKey: this._mouseState.metaKey,
            shiftKey: this._mouseState.shiftKey,
            leftButton: this._mouseState.leftButton,
            middleButton: this._mouseState.middleButton,
            onInjectedText: position.type === 6 /* MouseTargetType.CONTENT_TEXT */ && position.detail.injectedText !== null
        });
    }
}
class MouseDownState {
    constructor() {
        this._altKey = false;
        this._ctrlKey = false;
        this._metaKey = false;
        this._shiftKey = false;
        this._leftButton = false;
        this._middleButton = false;
        this._startedOnLineNumbers = false;
        this._lastMouseDownPosition = null;
        this._lastMouseDownPositionEqualCount = 0;
        this._lastMouseDownCount = 0;
        this._lastSetMouseDownCountTime = 0;
        this.isDragAndDrop = false;
    }
    get altKey() { return this._altKey; }
    get ctrlKey() { return this._ctrlKey; }
    get metaKey() { return this._metaKey; }
    get shiftKey() { return this._shiftKey; }
    get leftButton() { return this._leftButton; }
    get middleButton() { return this._middleButton; }
    get startedOnLineNumbers() { return this._startedOnLineNumbers; }
    get count() {
        return this._lastMouseDownCount;
    }
    setModifiers(source) {
        this._altKey = source.altKey;
        this._ctrlKey = source.ctrlKey;
        this._metaKey = source.metaKey;
        this._shiftKey = source.shiftKey;
    }
    setStartButtons(source) {
        this._leftButton = source.leftButton;
        this._middleButton = source.middleButton;
    }
    setStartedOnLineNumbers(startedOnLineNumbers) {
        this._startedOnLineNumbers = startedOnLineNumbers;
    }
    trySetCount(setMouseDownCount, newMouseDownPosition) {
        // a. Invalidate multiple clicking if too much time has passed (will be hit by IE because the detail field of mouse events contains garbage in IE10)
        const currentTime = (new Date()).getTime();
        if (currentTime - this._lastSetMouseDownCountTime > MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME) {
            setMouseDownCount = 1;
        }
        this._lastSetMouseDownCountTime = currentTime;
        // b. Ensure that we don't jump from single click to triple click in one go (will be hit by IE because the detail field of mouse events contains garbage in IE10)
        if (setMouseDownCount > this._lastMouseDownCount + 1) {
            setMouseDownCount = this._lastMouseDownCount + 1;
        }
        // c. Invalidate multiple clicking if the logical position is different
        if (this._lastMouseDownPosition && this._lastMouseDownPosition.equals(newMouseDownPosition)) {
            this._lastMouseDownPositionEqualCount++;
        }
        else {
            this._lastMouseDownPositionEqualCount = 1;
        }
        this._lastMouseDownPosition = newMouseDownPosition;
        // Finally set the lastMouseDownCount
        this._lastMouseDownCount = Math.min(setMouseDownCount, this._lastMouseDownPositionEqualCount);
    }
}
MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME = 400; // ms

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/controller/pointerHandler.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/








/**
 * Currently only tested on iOS 13/ iPadOS.
 */
class PointerEventHandler extends MouseHandler {
    constructor(context, viewController, viewHelper) {
        super(context, viewController, viewHelper);
        this._register(Gesture.addTarget(this.viewHelper.linesContentDomNode));
        this._register(addDisposableListener(this.viewHelper.linesContentDomNode, touch_EventType.Tap, (e) => this.onTap(e)));
        this._register(addDisposableListener(this.viewHelper.linesContentDomNode, touch_EventType.Change, (e) => this.onChange(e)));
        this._register(addDisposableListener(this.viewHelper.linesContentDomNode, touch_EventType.Contextmenu, (e) => this._onContextMenu(new EditorMouseEvent(e, false, this.viewHelper.viewDomNode), false)));
        this._lastPointerType = 'mouse';
        this._register(addDisposableListener(this.viewHelper.linesContentDomNode, 'pointerdown', (e) => {
            const pointerType = e.pointerType;
            if (pointerType === 'mouse') {
                this._lastPointerType = 'mouse';
                return;
            }
            else if (pointerType === 'touch') {
                this._lastPointerType = 'touch';
            }
            else {
                this._lastPointerType = 'pen';
            }
        }));
        // PonterEvents
        const pointerEvents = new EditorPointerEventFactory(this.viewHelper.viewDomNode);
        this._register(pointerEvents.onPointerMove(this.viewHelper.viewDomNode, (e) => this._onMouseMove(e)));
        this._register(pointerEvents.onPointerUp(this.viewHelper.viewDomNode, (e) => this._onMouseUp(e)));
        this._register(pointerEvents.onPointerLeave(this.viewHelper.viewDomNode, (e) => this._onMouseLeave(e)));
        this._register(pointerEvents.onPointerDown(this.viewHelper.viewDomNode, (e, pointerId) => this._onMouseDown(e, pointerId)));
    }
    onTap(event) {
        if (!event.initialTarget || !this.viewHelper.linesContentDomNode.contains(event.initialTarget)) {
            return;
        }
        event.preventDefault();
        this.viewHelper.focusTextArea();
        const target = this._createMouseTarget(new EditorMouseEvent(event, false, this.viewHelper.viewDomNode), false);
        if (target.position) {
            // this.viewController.moveTo(target.position);
            this.viewController.dispatchMouse({
                position: target.position,
                mouseColumn: target.position.column,
                startedOnLineNumbers: false,
                mouseDownCount: event.tapCount,
                inSelectionMode: false,
                altKey: false,
                ctrlKey: false,
                metaKey: false,
                shiftKey: false,
                leftButton: false,
                middleButton: false,
                onInjectedText: target.type === 6 /* MouseTargetType.CONTENT_TEXT */ && target.detail.injectedText !== null
            });
        }
    }
    onChange(e) {
        if (this._lastPointerType === 'touch') {
            this._context.viewModel.viewLayout.deltaScrollNow(-e.translationX, -e.translationY);
        }
    }
    _onMouseDown(e, pointerId) {
        if (e.browserEvent.pointerType === 'touch') {
            return;
        }
        super._onMouseDown(e, pointerId);
    }
}
class TouchHandler extends MouseHandler {
    constructor(context, viewController, viewHelper) {
        super(context, viewController, viewHelper);
        this._register(Gesture.addTarget(this.viewHelper.linesContentDomNode));
        this._register(addDisposableListener(this.viewHelper.linesContentDomNode, touch_EventType.Tap, (e) => this.onTap(e)));
        this._register(addDisposableListener(this.viewHelper.linesContentDomNode, touch_EventType.Change, (e) => this.onChange(e)));
        this._register(addDisposableListener(this.viewHelper.linesContentDomNode, touch_EventType.Contextmenu, (e) => this._onContextMenu(new EditorMouseEvent(e, false, this.viewHelper.viewDomNode), false)));
    }
    onTap(event) {
        event.preventDefault();
        this.viewHelper.focusTextArea();
        const target = this._createMouseTarget(new EditorMouseEvent(event, false, this.viewHelper.viewDomNode), false);
        if (target.position) {
            // Send the tap event also to the <textarea> (for input purposes)
            const event = document.createEvent('CustomEvent');
            event.initEvent(TextAreaSyntethicEvents.Tap, false, true);
            this.viewHelper.dispatchTextAreaEvent(event);
            this.viewController.moveTo(target.position);
        }
    }
    onChange(e) {
        this._context.viewModel.viewLayout.deltaScrollNow(-e.translationX, -e.translationY);
    }
}
class PointerHandler extends Disposable {
    constructor(context, viewController, viewHelper) {
        super();
        if ((isIOS && canIUse_BrowserFeatures.pointerEvents)) {
            this.handler = this._register(new PointerEventHandler(context, viewController, viewHelper));
        }
        else if (window.TouchEvent) {
            this.handler = this._register(new TouchHandler(context, viewController, viewHelper));
        }
        else {
            this.handler = this._register(new MouseHandler(context, viewController, viewHelper));
        }
    }
    getTargetAtClientPoint(clientX, clientY) {
        return this.handler.getTargetAtClientPoint(clientX, clientY);
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/controller/textAreaHandler.css
var textAreaHandler = __webpack_require__(38770);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/controller/textAreaHandler.css

      
      
      
      
      
      
      
      
      

var textAreaHandler_options = {};

textAreaHandler_options.styleTagTransform = (styleTagTransform_default());
textAreaHandler_options.setAttributes = (setAttributesWithoutAttributes_default());

      textAreaHandler_options.insert = insertBySelector_default().bind(null, "head");
    
textAreaHandler_options.domAPI = (styleDomAPI_default());
textAreaHandler_options.insertStyleElement = (insertStyleElement_default());

var textAreaHandler_update = injectStylesIntoStyleTag_default()(textAreaHandler/* default */.A, textAreaHandler_options);




       /* harmony default export */ const controller_textAreaHandler = (textAreaHandler/* default */.A && textAreaHandler/* default */.A.locals ? textAreaHandler/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/lineNumbers/lineNumbers.css
var lineNumbers = __webpack_require__(11166);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/lineNumbers/lineNumbers.css

      
      
      
      
      
      
      
      
      

var lineNumbers_options = {};

lineNumbers_options.styleTagTransform = (styleTagTransform_default());
lineNumbers_options.setAttributes = (setAttributesWithoutAttributes_default());

      lineNumbers_options.insert = insertBySelector_default().bind(null, "head");
    
lineNumbers_options.domAPI = (styleDomAPI_default());
lineNumbers_options.insertStyleElement = (insertStyleElement_default());

var lineNumbers_update = injectStylesIntoStyleTag_default()(lineNumbers/* default */.A, lineNumbers_options);




       /* harmony default export */ const lineNumbers_lineNumbers = (lineNumbers/* default */.A && lineNumbers/* default */.A.locals ? lineNumbers/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/view/dynamicViewOverlay.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class DynamicViewOverlay extends ViewEventHandler {
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/lineNumbers/lineNumbers.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class LineNumbersOverlay extends DynamicViewOverlay {
    constructor(context) {
        super();
        this._context = context;
        this._readConfig();
        this._lastCursorModelPosition = new Position(1, 1);
        this._lastCursorViewPosition = new Position(1, 1);
        this._renderResult = null;
        this._activeLineNumber = 1;
        this._context.addEventHandler(this);
    }
    _readConfig() {
        const options = this._context.configuration.options;
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        const lineNumbers = options.get(62 /* EditorOption.lineNumbers */);
        this._renderLineNumbers = lineNumbers.renderType;
        this._renderCustomLineNumbers = lineNumbers.renderFn;
        this._renderFinalNewline = options.get(86 /* EditorOption.renderFinalNewline */);
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._lineNumbersLeft = layoutInfo.lineNumbersLeft;
        this._lineNumbersWidth = layoutInfo.lineNumbersWidth;
    }
    dispose() {
        this._context.removeEventHandler(this);
        this._renderResult = null;
        super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        this._readConfig();
        return true;
    }
    onCursorStateChanged(e) {
        const primaryViewPosition = e.selections[0].getPosition();
        this._lastCursorViewPosition = primaryViewPosition;
        this._lastCursorModelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(primaryViewPosition);
        let shouldRender = false;
        if (this._activeLineNumber !== primaryViewPosition.lineNumber) {
            this._activeLineNumber = primaryViewPosition.lineNumber;
            shouldRender = true;
        }
        if (this._renderLineNumbers === 2 /* RenderLineNumbersType.Relative */ || this._renderLineNumbers === 3 /* RenderLineNumbersType.Interval */) {
            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;
    }
    // --- end event handlers
    _getLineRenderLineNumber(viewLineNumber) {
        const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position(viewLineNumber, 1));
        if (modelPosition.column !== 1) {
            return '';
        }
        const modelLineNumber = modelPosition.lineNumber;
        if (this._renderCustomLineNumbers) {
            return this._renderCustomLineNumbers(modelLineNumber);
        }
        if (this._renderLineNumbers === 3 /* RenderLineNumbersType.Interval */) {
            if (this._lastCursorModelPosition.lineNumber === modelLineNumber) {
                return String(modelLineNumber);
            }
            if (modelLineNumber % 10 === 0) {
                return String(modelLineNumber);
            }
            return '';
        }
        return String(modelLineNumber);
    }
    prepareRender(ctx) {
        if (this._renderLineNumbers === 0 /* RenderLineNumbersType.Off */) {
            this._renderResult = null;
            return;
        }
        const lineHeightClassName = (isLinux ? (this._lineHeight % 2 === 0 ? ' lh-even' : ' lh-odd') : '');
        const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
        const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
        const common = '<div class="' + LineNumbersOverlay.CLASS_NAME + lineHeightClassName + '" style="left:' + this._lineNumbersLeft + 'px;width:' + this._lineNumbersWidth + 'px;">';
        let relativeLineNumbers = null;
        if (this._renderLineNumbers === 2 /* RenderLineNumbersType.Relative */) {
            relativeLineNumbers = new Array(visibleEndLineNumber - visibleStartLineNumber + 1);
            if (this._lastCursorViewPosition.lineNumber >= visibleStartLineNumber && this._lastCursorViewPosition.lineNumber <= visibleEndLineNumber) {
                relativeLineNumbers[this._lastCursorViewPosition.lineNumber - visibleStartLineNumber] = this._lastCursorModelPosition.lineNumber;
            }
            // Iterate up to compute relative line numbers
            {
                let value = 0;
                for (let lineNumber = this._lastCursorViewPosition.lineNumber + 1; lineNumber <= visibleEndLineNumber; lineNumber++) {
                    const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position(lineNumber, 1));
                    const isWrappedLine = (modelPosition.column !== 1);
                    if (!isWrappedLine) {
                        value++;
                    }
                    if (lineNumber >= visibleStartLineNumber) {
                        relativeLineNumbers[lineNumber - visibleStartLineNumber] = isWrappedLine ? 0 : value;
                    }
                }
            }
            // Iterate down to compute relative line numbers
            {
                let value = 0;
                for (let lineNumber = this._lastCursorViewPosition.lineNumber - 1; lineNumber >= visibleStartLineNumber; lineNumber--) {
                    const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position(lineNumber, 1));
                    const isWrappedLine = (modelPosition.column !== 1);
                    if (!isWrappedLine) {
                        value++;
                    }
                    if (lineNumber <= visibleEndLineNumber) {
                        relativeLineNumbers[lineNumber - visibleStartLineNumber] = isWrappedLine ? 0 : value;
                    }
                }
            }
        }
        const lineCount = this._context.viewModel.getLineCount();
        const output = [];
        for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
            const lineIndex = lineNumber - visibleStartLineNumber;
            if (!this._renderFinalNewline) {
                if (lineNumber === lineCount && this._context.viewModel.getLineLength(lineNumber) === 0) {
                    // Do not render last (empty) line
                    output[lineIndex] = '';
                    continue;
                }
            }
            let renderLineNumber;
            if (relativeLineNumbers) {
                const relativeLineNumber = relativeLineNumbers[lineIndex];
                if (this._lastCursorViewPosition.lineNumber === lineNumber) {
                    // current line!
                    renderLineNumber = `<span class="relative-current-line-number">${relativeLineNumber}</span>`;
                }
                else if (relativeLineNumber) {
                    renderLineNumber = String(relativeLineNumber);
                }
                else {
                    renderLineNumber = '';
                }
            }
            else {
                renderLineNumber = this._getLineRenderLineNumber(lineNumber);
            }
            if (renderLineNumber) {
                if (lineNumber === this._activeLineNumber) {
                    output[lineIndex] = ('<div class="active-line-number ' + LineNumbersOverlay.CLASS_NAME + lineHeightClassName + '" style="left:' + this._lineNumbersLeft + 'px;width:' + this._lineNumbersWidth + 'px;">'
                        + renderLineNumber
                        + '</div>');
                }
                else {
                    output[lineIndex] = (common
                        + renderLineNumber
                        + '</div>');
                }
            }
            else {
                output[lineIndex] = '';
            }
        }
        this._renderResult = output;
    }
    render(startLineNumber, lineNumber) {
        if (!this._renderResult) {
            return '';
        }
        const lineIndex = lineNumber - startLineNumber;
        if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
            return '';
        }
        return this._renderResult[lineIndex];
    }
}
LineNumbersOverlay.CLASS_NAME = 'line-numbers';
// theming
registerThemingParticipant((theme, collector) => {
    const lineNumbers = theme.getColor(editorLineNumbers);
    if (lineNumbers) {
        collector.addRule(`.monaco-editor .line-numbers { color: ${lineNumbers}; }`);
    }
    const activeLineNumber = theme.getColor(editorActiveLineNumber);
    if (activeLineNumber) {
        collector.addRule(`.monaco-editor .line-numbers.active-line-number { color: ${activeLineNumber}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/margin/margin.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class Margin extends ViewPart {
    constructor(context) {
        super(context);
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._canUseLayerHinting = !options.get(28 /* EditorOption.disableLayerHinting */);
        this._contentLeft = layoutInfo.contentLeft;
        this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
        this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
        this._domNode = createFastDomNode(document.createElement('div'));
        this._domNode.setClassName(Margin.OUTER_CLASS_NAME);
        this._domNode.setPosition('absolute');
        this._domNode.setAttribute('role', 'presentation');
        this._domNode.setAttribute('aria-hidden', 'true');
        this._glyphMarginBackgroundDomNode = createFastDomNode(document.createElement('div'));
        this._glyphMarginBackgroundDomNode.setClassName(Margin.CLASS_NAME);
        this._domNode.appendChild(this._glyphMarginBackgroundDomNode);
    }
    dispose() {
        super.dispose();
    }
    getDomNode() {
        return this._domNode;
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._canUseLayerHinting = !options.get(28 /* EditorOption.disableLayerHinting */);
        this._contentLeft = layoutInfo.contentLeft;
        this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
        this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
        return true;
    }
    onScrollChanged(e) {
        return super.onScrollChanged(e) || e.scrollTopChanged;
    }
    // --- end event handlers
    prepareRender(ctx) {
        // Nothing to read
    }
    render(ctx) {
        this._domNode.setLayerHinting(this._canUseLayerHinting);
        this._domNode.setContain('strict');
        const adjustedScrollTop = ctx.scrollTop - ctx.bigNumbersDelta;
        this._domNode.setTop(-adjustedScrollTop);
        const height = Math.min(ctx.scrollHeight, 1000000);
        this._domNode.setHeight(height);
        this._domNode.setWidth(this._contentLeft);
        this._glyphMarginBackgroundDomNode.setLeft(this._glyphMarginLeft);
        this._glyphMarginBackgroundDomNode.setWidth(this._glyphMarginWidth);
        this._glyphMarginBackgroundDomNode.setHeight(height);
    }
}
Margin.CLASS_NAME = 'glyph-margin';
Margin.OUTER_CLASS_NAME = 'margin';

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/mouseCursor/mouseCursor.css
var mouseCursor = __webpack_require__(96419);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/mouseCursor/mouseCursor.css

      
      
      
      
      
      
      
      
      

var mouseCursor_options = {};

mouseCursor_options.styleTagTransform = (styleTagTransform_default());
mouseCursor_options.setAttributes = (setAttributesWithoutAttributes_default());

      mouseCursor_options.insert = insertBySelector_default().bind(null, "head");
    
mouseCursor_options.domAPI = (styleDomAPI_default());
mouseCursor_options.insertStyleElement = (insertStyleElement_default());

var mouseCursor_update = injectStylesIntoStyleTag_default()(mouseCursor/* default */.A, mouseCursor_options);




       /* harmony default export */ const mouseCursor_mouseCursor = (mouseCursor/* default */.A && mouseCursor/* default */.A.locals ? mouseCursor/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/mouseCursor/mouseCursor.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const MOUSE_CURSOR_TEXT_CSS_CLASS_NAME = `monaco-mouse-cursor-text`;

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/controller/textAreaHandler.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




















class VisibleTextAreaData {
    constructor(_context, modelLineNumber, distanceToModelLineStart, widthOfHiddenLineTextBefore, distanceToModelLineEnd) {
        this._context = _context;
        this.modelLineNumber = modelLineNumber;
        this.distanceToModelLineStart = distanceToModelLineStart;
        this.widthOfHiddenLineTextBefore = widthOfHiddenLineTextBefore;
        this.distanceToModelLineEnd = distanceToModelLineEnd;
        this._visibleTextAreaBrand = undefined;
        this.startPosition = null;
        this.endPosition = null;
        this.visibleTextareaStart = null;
        this.visibleTextareaEnd = null;
        /**
         * When doing composition, the currently composed text might be split up into
         * multiple tokens, then merged again into a single token, etc. Here we attempt
         * to keep the presentation of the <textarea> stable by using the previous used
         * style if multiple tokens come into play. This avoids flickering.
         */
        this._previousPresentation = null;
    }
    prepareRender(visibleRangeProvider) {
        const startModelPosition = new Position(this.modelLineNumber, this.distanceToModelLineStart + 1);
        const endModelPosition = new Position(this.modelLineNumber, this._context.viewModel.model.getLineMaxColumn(this.modelLineNumber) - this.distanceToModelLineEnd);
        this.startPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(startModelPosition);
        this.endPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(endModelPosition);
        if (this.startPosition.lineNumber === this.endPosition.lineNumber) {
            this.visibleTextareaStart = visibleRangeProvider.visibleRangeForPosition(this.startPosition);
            this.visibleTextareaEnd = visibleRangeProvider.visibleRangeForPosition(this.endPosition);
        }
        else {
            // TODO: what if the view positions are not on the same line?
            this.visibleTextareaStart = null;
            this.visibleTextareaEnd = null;
        }
    }
    definePresentation(tokenPresentation) {
        if (!this._previousPresentation) {
            // To avoid flickering, once set, always reuse a presentation throughout the entire IME session
            if (tokenPresentation) {
                this._previousPresentation = tokenPresentation;
            }
            else {
                this._previousPresentation = {
                    foreground: 1 /* ColorId.DefaultForeground */,
                    italic: false,
                    bold: false,
                    underline: false,
                    strikethrough: false,
                };
            }
        }
        return this._previousPresentation;
    }
}
const canUseZeroSizeTextarea = (browser_isFirefox);
class TextAreaHandler extends ViewPart {
    constructor(context, viewController, visibleRangeProvider) {
        super(context);
        // --- end view API
        this._primaryCursorPosition = new Position(1, 1);
        this._primaryCursorVisibleRange = null;
        this._viewController = viewController;
        this._visibleRangeProvider = visibleRangeProvider;
        this._scrollLeft = 0;
        this._scrollTop = 0;
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._setAccessibilityOptions(options);
        this._contentLeft = layoutInfo.contentLeft;
        this._contentWidth = layoutInfo.contentWidth;
        this._contentHeight = layoutInfo.height;
        this._fontInfo = options.get(46 /* EditorOption.fontInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._emptySelectionClipboard = options.get(33 /* EditorOption.emptySelectionClipboard */);
        this._copyWithSyntaxHighlighting = options.get(21 /* EditorOption.copyWithSyntaxHighlighting */);
        this._visibleTextArea = null;
        this._selections = [new Selection(1, 1, 1, 1)];
        this._modelSelections = [new Selection(1, 1, 1, 1)];
        this._lastRenderPosition = null;
        // Text Area (The focus will always be in the textarea when the cursor is blinking)
        this.textArea = createFastDomNode(document.createElement('textarea'));
        PartFingerprints.write(this.textArea, 6 /* PartFingerprint.TextArea */);
        this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
        this.textArea.setAttribute('wrap', 'off');
        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', this._getAriaLabel(options));
        this.textArea.setAttribute('tabindex', String(options.get(114 /* EditorOption.tabIndex */)));
        this.textArea.setAttribute('role', 'textbox');
        this.textArea.setAttribute('aria-roledescription', localize('editor', "editor"));
        this.textArea.setAttribute('aria-multiline', 'true');
        this.textArea.setAttribute('aria-haspopup', 'false');
        this.textArea.setAttribute('aria-autocomplete', 'both');
        if (options.get(30 /* EditorOption.domReadOnly */) && options.get(83 /* EditorOption.readOnly */)) {
            this.textArea.setAttribute('readonly', 'true');
        }
        this.textAreaCover = createFastDomNode(document.createElement('div'));
        this.textAreaCover.setPosition('absolute');
        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);
            }
        };
        const textAreaInputHost = {
            getDataToCopy: () => {
                const rawTextToCopy = this._context.viewModel.getPlainTextToCopy(this._modelSelections, this._emptySelectionClipboard, isWindows);
                const newLineCharacter = this._context.viewModel.model.getEOL();
                const isFromEmptySelection = (this._emptySelectionClipboard && this._modelSelections.length === 1 && this._modelSelections[0].isEmpty());
                const multicursorText = (Array.isArray(rawTextToCopy) ? rawTextToCopy : null);
                const text = (Array.isArray(rawTextToCopy) ? rawTextToCopy.join(newLineCharacter) : rawTextToCopy);
                let html = undefined;
                let mode = null;
                if (CopyOptions.forceCopyWithSyntaxHighlighting || (this._copyWithSyntaxHighlighting && text.length < 65536)) {
                    const richText = this._context.viewModel.getRichTextToCopy(this._modelSelections, this._emptySelectionClipboard);
                    if (richText) {
                        html = richText.html;
                        mode = richText.mode;
                    }
                }
                return {
                    isFromEmptySelection,
                    multicursorText,
                    text,
                    html,
                    mode
                };
            },
            getScreenReaderContent: (currentState) => {
                if (this._accessibilitySupport === 1 /* AccessibilitySupport.Disabled */) {
                    // We know for a fact that a screen reader is not attached
                    // On OSX, we write the character before the cursor to allow for "long-press" composition
                    // Also on OSX, we write the word before the cursor to allow for the Accessibility Keyboard to give good hints
                    const selection = this._selections[0];
                    if (isMacintosh && selection.isEmpty()) {
                        const position = selection.getStartPosition();
                        let textBefore = this._getWordBeforePosition(position);
                        if (textBefore.length === 0) {
                            textBefore = this._getCharacterBeforePosition(position);
                        }
                        if (textBefore.length > 0) {
                            return new TextAreaState(textBefore, textBefore.length, textBefore.length, position, position);
                        }
                    }
                    // on Safari, document.execCommand('cut') and document.execCommand('copy') will just not work
                    // if the textarea has no content selected. So if there is an editor selection, ensure something
                    // is selected in the textarea.
                    if (browser_isSafari && !selection.isEmpty()) {
                        const placeholderText = 'vscode-placeholder';
                        return new TextAreaState(placeholderText, 0, placeholderText.length, null, null);
                    }
                    return TextAreaState.EMPTY;
                }
                if (browser_isAndroid) {
                    // when tapping in the editor on a word, Android enters composition mode.
                    // in the `compositionstart` event we cannot clear the textarea, because
                    // it then forgets to ever send a `compositionend`.
                    // we therefore only write the current word in the textarea
                    const selection = this._selections[0];
                    if (selection.isEmpty()) {
                        const position = selection.getStartPosition();
                        const [wordAtPosition, positionOffsetInWord] = this._getAndroidWordAtPosition(position);
                        if (wordAtPosition.length > 0) {
                            return new TextAreaState(wordAtPosition, positionOffsetInWord, positionOffsetInWord, position, position);
                        }
                    }
                    return TextAreaState.EMPTY;
                }
                return PagedScreenReaderStrategy.fromEditorSelection(currentState, simpleModel, this._selections[0], this._accessibilityPageSize, this._accessibilitySupport === 0 /* AccessibilitySupport.Unknown */);
            },
            deduceModelPosition: (viewAnchorPosition, deltaOffset, lineFeedCnt) => {
                return this._context.viewModel.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt);
            }
        };
        const textAreaWrapper = this._register(new TextAreaWrapper(this.textArea.domNode));
        this._textAreaInput = this._register(new TextAreaInput(textAreaInputHost, textAreaWrapper, OS, browser_namespaceObject));
        this._register(this._textAreaInput.onKeyDown((e) => {
            this._viewController.emitKeyDown(e);
        }));
        this._register(this._textAreaInput.onKeyUp((e) => {
            this._viewController.emitKeyUp(e);
        }));
        this._register(this._textAreaInput.onPaste((e) => {
            let pasteOnNewLine = false;
            let multicursorText = null;
            let mode = null;
            if (e.metadata) {
                pasteOnNewLine = (this._emptySelectionClipboard && !!e.metadata.isFromEmptySelection);
                multicursorText = (typeof e.metadata.multicursorText !== 'undefined' ? e.metadata.multicursorText : null);
                mode = e.metadata.mode;
            }
            this._viewController.paste(e.text, pasteOnNewLine, multicursorText, mode);
        }));
        this._register(this._textAreaInput.onCut(() => {
            this._viewController.cut();
        }));
        this._register(this._textAreaInput.onType((e) => {
            if (e.replacePrevCharCnt || e.replaceNextCharCnt || e.positionDelta) {
                // must be handled through the new command
                if (_debugComposition) {
                    console.log(` => compositionType: <<${e.text}>>, ${e.replacePrevCharCnt}, ${e.replaceNextCharCnt}, ${e.positionDelta}`);
                }
                this._viewController.compositionType(e.text, e.replacePrevCharCnt, e.replaceNextCharCnt, e.positionDelta);
            }
            else {
                if (_debugComposition) {
                    console.log(` => type: <<${e.text}>>`);
                }
                this._viewController.type(e.text);
            }
        }));
        this._register(this._textAreaInput.onSelectionChangeRequest((modelSelection) => {
            this._viewController.setSelection(modelSelection);
        }));
        this._register(this._textAreaInput.onCompositionStart((e) => {
            // The textarea might contain some content when composition starts.
            //
            // When we make the textarea visible, it always has a height of 1 line,
            // so we don't need to worry too much about content on lines above or below
            // the selection.
            //
            // However, the text on the current line needs to be made visible because
            // some IME methods allow to move to other glyphs on the current line
            // (by pressing arrow keys).
            //
            // (1) The textarea might contain only some parts of the current line,
            // like the word before the selection. Also, the content inside the textarea
            // can grow or shrink as composition occurs. We therefore anchor the textarea
            // in terms of distance to a certain line start and line end.
            //
            // (2) Also, we should not make \t characters visible, because their rendering
            // inside the <textarea> will not align nicely with our rendering. We therefore
            // will hide (if necessary) some of the leading text on the current line.
            const ta = this.textArea.domNode;
            const modelSelection = this._modelSelections[0];
            const { distanceToModelLineStart, widthOfHiddenTextBefore } = (() => {
                // Find the text that is on the current line before the selection
                const textBeforeSelection = ta.value.substring(0, Math.min(ta.selectionStart, ta.selectionEnd));
                const lineFeedOffset1 = textBeforeSelection.lastIndexOf('\n');
                const lineTextBeforeSelection = textBeforeSelection.substring(lineFeedOffset1 + 1);
                // We now search to see if we should hide some part of it (if it contains \t)
                const tabOffset1 = lineTextBeforeSelection.lastIndexOf('\t');
                const desiredVisibleBeforeCharCount = lineTextBeforeSelection.length - tabOffset1 - 1;
                const startModelPosition = modelSelection.getStartPosition();
                const visibleBeforeCharCount = Math.min(startModelPosition.column - 1, desiredVisibleBeforeCharCount);
                const distanceToModelLineStart = startModelPosition.column - 1 - visibleBeforeCharCount;
                const hiddenLineTextBefore = lineTextBeforeSelection.substring(0, lineTextBeforeSelection.length - visibleBeforeCharCount);
                const widthOfHiddenTextBefore = measureText(hiddenLineTextBefore, this._fontInfo);
                return { distanceToModelLineStart, widthOfHiddenTextBefore };
            })();
            const { distanceToModelLineEnd } = (() => {
                // Find the text that is on the current line after the selection
                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('\t');
                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 distanceToModelLineEnd = this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column - visibleAfterCharCount;
                return { distanceToModelLineEnd };
            })();
            // Scroll to reveal the location in the editor where composition occurs
            this._context.viewModel.revealRange('keyboard', true, Range.fromPositions(this._selections[0].getStartPosition()), 0 /* viewEvents.VerticalRevealType.Simple */, 1 /* ScrollType.Immediate */);
            this._visibleTextArea = new VisibleTextAreaData(this._context, modelSelection.startLineNumber, distanceToModelLineStart, widthOfHiddenTextBefore, distanceToModelLineEnd);
            this._visibleTextArea.prepareRender(this._visibleRangeProvider);
            this._render();
            // Show the textarea
            this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ime-input`);
            this._viewController.compositionStart();
            this._context.viewModel.onCompositionStart();
        }));
        this._register(this._textAreaInput.onCompositionUpdate((e) => {
            if (!this._visibleTextArea) {
                return;
            }
            this._visibleTextArea.prepareRender(this._visibleRangeProvider);
            this._render();
        }));
        this._register(this._textAreaInput.onCompositionEnd(() => {
            this._visibleTextArea = null;
            this._render();
            this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
            this._viewController.compositionEnd();
            this._context.viewModel.onCompositionEnd();
        }));
        this._register(this._textAreaInput.onFocus(() => {
            this._context.viewModel.setHasFocus(true);
        }));
        this._register(this._textAreaInput.onBlur(() => {
            this._context.viewModel.setHasFocus(false);
        }));
    }
    dispose() {
        super.dispose();
    }
    _getAndroidWordAtPosition(position) {
        const ANDROID_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:",.<>/?';
        const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
        const wordSeparators = getMapForWordSeparators(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 = wordSeparators.get(charCode);
                if (charClass !== 0 /* WordCharacterClass.Regular */) {
                    goingLeft = false;
                }
                else {
                    startColumn--;
                }
            }
            if (goingRight && endColumn > lineContent.length) {
                goingRight = false;
            }
            if (goingRight) {
                const charCode = lineContent.charCodeAt(endColumn - 1);
                const charClass = wordSeparators.get(charCode);
                if (charClass !== 0 /* WordCharacterClass.Regular */) {
                    goingRight = false;
                }
                else {
                    endColumn++;
                }
            }
            distance++;
        }
        return [lineContent.substring(startColumn - 1, endColumn - 1), position.column - startColumn];
    }
    _getWordBeforePosition(position) {
        const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
        const wordSeparators = getMapForWordSeparators(this._context.configuration.options.get(119 /* EditorOption.wordSeparators */));
        let column = position.column;
        let distance = 0;
        while (column > 1) {
            const charCode = lineContent.charCodeAt(column - 2);
            const charClass = wordSeparators.get(charCode);
            if (charClass !== 0 /* WordCharacterClass.Regular */ || distance > 50) {
                return lineContent.substring(column - 1, position.column - 1);
            }
            distance++;
            column--;
        }
        return lineContent.substring(0, position.column - 1);
    }
    _getCharacterBeforePosition(position) {
        if (position.column > 1) {
            const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
            const charBefore = lineContent.charAt(position.column - 2);
            if (!isHighSurrogate(charBefore.charCodeAt(0))) {
                return charBefore;
            }
        }
        return '';
    }
    _getAriaLabel(options) {
        const accessibilitySupport = options.get(2 /* EditorOption.accessibilitySupport */);
        if (accessibilitySupport === 1 /* AccessibilitySupport.Disabled */) {
            return localize('accessibilityOffAriaLabel', "The editor is not accessible at this time. Press {0} for options.", isLinux ? 'Shift+Alt+F1' : 'Alt+F1');
        }
        return options.get(4 /* EditorOption.ariaLabel */);
    }
    _setAccessibilityOptions(options) {
        this._accessibilitySupport = options.get(2 /* EditorOption.accessibilitySupport */);
        const accessibilityPageSize = options.get(3 /* EditorOption.accessibilityPageSize */);
        if (this._accessibilitySupport === 2 /* AccessibilitySupport.Enabled */ && accessibilityPageSize === EditorOptions.accessibilityPageSize.defaultValue) {
            // If a screen reader is attached and the default value is not set we should automatically increase the page size to 500 for a better experience
            this._accessibilityPageSize = 500;
        }
        else {
            this._accessibilityPageSize = accessibilityPageSize;
        }
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._setAccessibilityOptions(options);
        this._contentLeft = layoutInfo.contentLeft;
        this._contentWidth = layoutInfo.contentWidth;
        this._contentHeight = layoutInfo.height;
        this._fontInfo = options.get(46 /* EditorOption.fontInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._emptySelectionClipboard = options.get(33 /* EditorOption.emptySelectionClipboard */);
        this._copyWithSyntaxHighlighting = options.get(21 /* EditorOption.copyWithSyntaxHighlighting */);
        this.textArea.setAttribute('aria-label', this._getAriaLabel(options));
        this.textArea.setAttribute('tabindex', String(options.get(114 /* EditorOption.tabIndex */)));
        if (e.hasChanged(30 /* EditorOption.domReadOnly */) || e.hasChanged(83 /* EditorOption.readOnly */)) {
            if (options.get(30 /* EditorOption.domReadOnly */) && options.get(83 /* EditorOption.readOnly */)) {
                this.textArea.setAttribute('readonly', 'true');
            }
            else {
                this.textArea.removeAttribute('readonly');
            }
        }
        if (e.hasChanged(2 /* EditorOption.accessibilitySupport */)) {
            this._textAreaInput.writeScreenReaderContent('strategy changed');
        }
        return true;
    }
    onCursorStateChanged(e) {
        this._selections = e.selections.slice(0);
        this._modelSelections = e.modelSelections.slice(0);
        this._textAreaInput.writeScreenReaderContent('selection changed');
        return true;
    }
    onDecorationsChanged(e) {
        // true for inline decorations that can end up relayouting text
        return true;
    }
    onFlushed(e) {
        return true;
    }
    onLinesChanged(e) {
        return true;
    }
    onLinesDeleted(e) {
        return true;
    }
    onLinesInserted(e) {
        return true;
    }
    onScrollChanged(e) {
        this._scrollLeft = e.scrollLeft;
        this._scrollTop = e.scrollTop;
        return true;
    }
    onZonesChanged(e) {
        return true;
    }
    // --- end event handlers
    // --- begin view API
    isFocused() {
        return this._textAreaInput.isFocused();
    }
    focusTextArea() {
        this._textAreaInput.focusTextArea();
    }
    getLastRenderData() {
        return this._lastRenderPosition;
    }
    setAriaOptions(options) {
        if (options.activeDescendant) {
            this.textArea.setAttribute('aria-haspopup', 'true');
            this.textArea.setAttribute('aria-autocomplete', 'list');
            this.textArea.setAttribute('aria-activedescendant', options.activeDescendant);
        }
        else {
            this.textArea.setAttribute('aria-haspopup', 'false');
            this.textArea.setAttribute('aria-autocomplete', 'both');
            this.textArea.removeAttribute('aria-activedescendant');
        }
        if (options.role) {
            this.textArea.setAttribute('role', options.role);
        }
    }
    prepareRender(ctx) {
        var _a;
        this._primaryCursorPosition = new Position(this._selections[0].positionLineNumber, this._selections[0].positionColumn);
        this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(this._primaryCursorPosition);
        (_a = this._visibleTextArea) === null || _a === void 0 ? void 0 : _a.prepareRender(ctx);
    }
    render(ctx) {
        this._textAreaInput.writeScreenReaderContent('render');
        this._render();
    }
    _render() {
        if (this._visibleTextArea) {
            // The text area is visible for composition reasons
            const visibleStart = this._visibleTextArea.visibleTextareaStart;
            const visibleEnd = this._visibleTextArea.visibleTextareaEnd;
            const startPosition = this._visibleTextArea.startPosition;
            const endPosition = this._visibleTextArea.endPosition;
            if (startPosition && endPosition && visibleStart && visibleEnd && visibleEnd.left >= this._scrollLeft && visibleStart.left <= this._scrollLeft + this._contentWidth) {
                const top = (this._context.viewLayout.getVerticalOffsetForLineNumber(this._primaryCursorPosition.lineNumber) - this._scrollTop);
                const lineCount = this._newlinecount(this.textArea.domNode.value.substr(0, this.textArea.domNode.selectionStart));
                let scrollLeft = this._visibleTextArea.widthOfHiddenLineTextBefore;
                let left = (this._contentLeft + visibleStart.left - this._scrollLeft);
                // See https://github.com/microsoft/vscode/issues/141725#issuecomment-1050670841
                // Here we are adding +1 to avoid flickering that might be caused by having a width that is too small.
                // This could be caused by rounding errors that might only show up with certain font families.
                // In other words, a pixel might be lost when doing something like
                //      `Math.round(end) - Math.round(start)`
                // vs
                //      `Math.round(end - start)`
                let width = visibleEnd.left - visibleStart.left + 1;
                if (left < this._contentLeft) {
                    // the textarea would be rendered on top of the margin,
                    // so reduce its width. We use the same technique as
                    // for hiding text before
                    const delta = (this._contentLeft - left);
                    left += delta;
                    scrollLeft += delta;
                    width -= delta;
                }
                if (width > this._contentWidth) {
                    // the textarea would be wider than the content width,
                    // so reduce its width.
                    width = this._contentWidth;
                }
                // Try to render the textarea with the color/font style to match the text under it
                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 presentation = this._visibleTextArea.definePresentation((textareaSpansSingleToken ? viewLineData.tokens.getPresentation(startTokenIndex) : null));
                this.textArea.domNode.scrollTop = lineCount * this._lineHeight;
                this.textArea.domNode.scrollLeft = scrollLeft;
                this._doRender({
                    lastRenderPosition: null,
                    top: top,
                    left: left,
                    width: width,
                    height: this._lineHeight,
                    useCover: false,
                    color: (languages_TokenizationRegistry.getColorMap() || [])[presentation.foreground],
                    italic: presentation.italic,
                    bold: presentation.bold,
                    underline: presentation.underline,
                    strikethrough: presentation.strikethrough
                });
            }
            return;
        }
        if (!this._primaryCursorVisibleRange) {
            // The primary cursor is outside the viewport => place textarea to the top left
            this._renderAtTopLeft();
            return;
        }
        const left = this._contentLeft + this._primaryCursorVisibleRange.left - this._scrollLeft;
        if (left < this._contentLeft || left > this._contentLeft + this._contentWidth) {
            // cursor is outside the viewport
            this._renderAtTopLeft();
            return;
        }
        const top = this._context.viewLayout.getVerticalOffsetForLineNumber(this._selections[0].positionLineNumber) - this._scrollTop;
        if (top < 0 || top > this._contentHeight) {
            // cursor is outside the viewport
            this._renderAtTopLeft();
            return;
        }
        // The primary cursor is in the viewport (at least vertically) => place textarea on the cursor
        if (isMacintosh) {
            // For the popup emoji input, we will make the text area as high as the line height
            // We will also make the fontSize and lineHeight the correct dimensions to help with the placement of these pickers
            this._doRender({
                lastRenderPosition: this._primaryCursorPosition,
                top: top,
                left: left,
                width: (canUseZeroSizeTextarea ? 0 : 1),
                height: this._lineHeight,
                useCover: false
            });
            // In case the textarea contains a word, we're going to try to align the textarea's cursor
            // with our cursor by scrolling the textarea as much as possible
            this.textArea.domNode.scrollLeft = this._primaryCursorVisibleRange.left;
            const lineCount = this._newlinecount(this.textArea.domNode.value.substr(0, this.textArea.domNode.selectionStart));
            this.textArea.domNode.scrollTop = lineCount * this._lineHeight;
            return;
        }
        this._doRender({
            lastRenderPosition: this._primaryCursorPosition,
            top: top,
            left: left,
            width: (canUseZeroSizeTextarea ? 0 : 1),
            height: (canUseZeroSizeTextarea ? 0 : 1),
            useCover: false
        });
    }
    _newlinecount(text) {
        let result = 0;
        let startIndex = -1;
        do {
            startIndex = text.indexOf('\n', startIndex + 1);
            if (startIndex === -1) {
                break;
            }
            result++;
        } while (true);
        return result;
    }
    _renderAtTopLeft() {
        // (in WebKit the textarea is 1px by 1px because it cannot handle input to a 0x0 textarea)
        // specifically, when doing Korean IME, setting the textarea to 0x0 breaks IME badly.
        this._doRender({
            lastRenderPosition: null,
            top: 0,
            left: 0,
            width: (canUseZeroSizeTextarea ? 0 : 1),
            height: (canUseZeroSizeTextarea ? 0 : 1),
            useCover: true
        });
    }
    _doRender(renderData) {
        this._lastRenderPosition = renderData.lastRenderPosition;
        const ta = this.textArea;
        const tac = this.textAreaCover;
        applyFontInfo(ta, this._fontInfo);
        ta.setTop(renderData.top);
        ta.setLeft(renderData.left);
        ta.setWidth(renderData.width);
        ta.setHeight(renderData.height);
        ta.setColor(renderData.color ? Color.Format.CSS.formatHex(renderData.color) : '');
        ta.setFontStyle(renderData.italic ? 'italic' : '');
        if (renderData.bold) {
            // fontWeight is also set by `applyFontInfo`, so only overwrite it if necessary
            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 options = this._context.configuration.options;
        if (options.get(52 /* EditorOption.glyphMargin */)) {
            tac.setClassName('monaco-editor-background textAreaCover ' + Margin.OUTER_CLASS_NAME);
        }
        else {
            if (options.get(62 /* EditorOption.lineNumbers */).renderType !== 0 /* RenderLineNumbersType.Off */) {
                tac.setClassName('monaco-editor-background textAreaCover ' + LineNumbersOverlay.CLASS_NAME);
            }
            else {
                tac.setClassName('monaco-editor-background textAreaCover');
            }
        }
    }
}
function measureText(text, fontInfo) {
    if (text.length === 0) {
        return 0;
    }
    const container = document.createElement('div');
    container.style.position = 'absolute';
    container.style.top = '-50000px';
    container.style.width = '50000px';
    const regularDomNode = document.createElement('span');
    applyFontInfo(regularDomNode, fontInfo);
    regularDomNode.style.whiteSpace = 'pre'; // just like the textarea
    regularDomNode.append(text);
    container.appendChild(regularDomNode);
    document.body.appendChild(container);
    const res = regularDomNode.offsetWidth;
    document.body.removeChild(container);
    return res;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/view/viewController.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class ViewController {
    constructor(configuration, viewModel, userInputEvents, commandDelegate) {
        this.configuration = configuration;
        this.viewModel = viewModel;
        this.userInputEvents = userInputEvents;
        this.commandDelegate = commandDelegate;
    }
    paste(text, pasteOnNewLine, multicursorText, mode) {
        this.commandDelegate.paste(text, pasteOnNewLine, multicursorText, mode);
    }
    type(text) {
        this.commandDelegate.type(text);
    }
    compositionType(text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
        this.commandDelegate.compositionType(text, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
    }
    compositionStart() {
        this.commandDelegate.startComposition();
    }
    compositionEnd() {
        this.commandDelegate.endComposition();
    }
    cut() {
        this.commandDelegate.cut();
    }
    setSelection(modelSelection) {
        CoreNavigationCommands.SetSelection.runCoreEditorCommand(this.viewModel, {
            source: 'keyboard',
            selection: modelSelection
        });
    }
    _validateViewColumn(viewPosition) {
        const minColumn = this.viewModel.getLineMinColumn(viewPosition.lineNumber);
        if (viewPosition.column < minColumn) {
            return new Position(viewPosition.lineNumber, minColumn);
        }
        return viewPosition;
    }
    _hasMulticursorModifier(data) {
        switch (this.configuration.options.get(72 /* EditorOption.multiCursorModifier */)) {
            case 'altKey':
                return data.altKey;
            case 'ctrlKey':
                return data.ctrlKey;
            case 'metaKey':
                return data.metaKey;
            default:
                return false;
        }
    }
    _hasNonMulticursorModifier(data) {
        switch (this.configuration.options.get(72 /* 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 options = this.configuration.options;
        const selectionClipboardIsOn = (isLinux && options.get(98 /* EditorOption.selectionClipboard */));
        const columnSelection = options.get(18 /* EditorOption.columnSelection */);
        if (data.middleButton && !selectionClipboardIsOn) {
            this._columnSelect(data.position, data.mouseColumn, data.inSelectionMode);
        }
        else if (data.startedOnLineNumbers) {
            // If the dragging started on the gutter, then have operations work on the entire line
            if (this._hasMulticursorModifier(data)) {
                if (data.inSelectionMode) {
                    this._lastCursorLineSelect(data.position);
                }
                else {
                    this._createCursor(data.position, true);
                }
            }
            else {
                if (data.inSelectionMode) {
                    this._lineSelectDrag(data.position);
                }
                else {
                    this._lineSelect(data.position);
                }
            }
        }
        else if (data.mouseDownCount >= 4) {
            this._selectAll();
        }
        else if (data.mouseDownCount === 3) {
            if (this._hasMulticursorModifier(data)) {
                if (data.inSelectionMode) {
                    this._lastCursorLineSelectDrag(data.position);
                }
                else {
                    this._lastCursorLineSelect(data.position);
                }
            }
            else {
                if (data.inSelectionMode) {
                    this._lineSelectDrag(data.position);
                }
                else {
                    this._lineSelect(data.position);
                }
            }
        }
        else if (data.mouseDownCount === 2) {
            if (!data.onInjectedText) {
                if (this._hasMulticursorModifier(data)) {
                    this._lastCursorWordSelect(data.position);
                }
                else {
                    if (data.inSelectionMode) {
                        this._wordSelectDrag(data.position);
                    }
                    else {
                        this._wordSelect(data.position);
                    }
                }
            }
        }
        else {
            if (this._hasMulticursorModifier(data)) {
                if (!this._hasNonMulticursorModifier(data)) {
                    if (data.shiftKey) {
                        this._columnSelect(data.position, data.mouseColumn, true);
                    }
                    else {
                        // Do multi-cursor operations only when purely alt is pressed
                        if (data.inSelectionMode) {
                            this._lastCursorMoveToSelect(data.position);
                        }
                        else {
                            this._createCursor(data.position, false);
                        }
                    }
                }
            }
            else {
                if (data.inSelectionMode) {
                    if (data.altKey) {
                        this._columnSelect(data.position, data.mouseColumn, true);
                    }
                    else {
                        if (columnSelection) {
                            this._columnSelect(data.position, data.mouseColumn, true);
                        }
                        else {
                            this._moveToSelect(data.position);
                        }
                    }
                }
                else {
                    this.moveTo(data.position);
                }
            }
        }
    }
    _usualArgs(viewPosition) {
        viewPosition = this._validateViewColumn(viewPosition);
        return {
            source: 'mouse',
            position: this._convertViewToModelPosition(viewPosition),
            viewPosition: viewPosition
        };
    }
    moveTo(viewPosition) {
        CoreNavigationCommands.MoveTo.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
    }
    _moveToSelect(viewPosition) {
        CoreNavigationCommands.MoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
    }
    _columnSelect(viewPosition, mouseColumn, doColumnSelect) {
        viewPosition = this._validateViewColumn(viewPosition);
        CoreNavigationCommands.ColumnSelect.runCoreEditorCommand(this.viewModel, {
            source: 'mouse',
            position: this._convertViewToModelPosition(viewPosition),
            viewPosition: viewPosition,
            mouseColumn: mouseColumn,
            doColumnSelect: doColumnSelect
        });
    }
    _createCursor(viewPosition, wholeLine) {
        viewPosition = this._validateViewColumn(viewPosition);
        CoreNavigationCommands.CreateCursor.runCoreEditorCommand(this.viewModel, {
            source: 'mouse',
            position: this._convertViewToModelPosition(viewPosition),
            viewPosition: viewPosition,
            wholeLine: wholeLine
        });
    }
    _lastCursorMoveToSelect(viewPosition) {
        CoreNavigationCommands.LastCursorMoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
    }
    _wordSelect(viewPosition) {
        CoreNavigationCommands.WordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
    }
    _wordSelectDrag(viewPosition) {
        CoreNavigationCommands.WordSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
    }
    _lastCursorWordSelect(viewPosition) {
        CoreNavigationCommands.LastCursorWordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
    }
    _lineSelect(viewPosition) {
        CoreNavigationCommands.LineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
    }
    _lineSelectDrag(viewPosition) {
        CoreNavigationCommands.LineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
    }
    _lastCursorLineSelect(viewPosition) {
        CoreNavigationCommands.LastCursorLineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
    }
    _lastCursorLineSelectDrag(viewPosition) {
        CoreNavigationCommands.LastCursorLineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition));
    }
    _selectAll() {
        CoreNavigationCommands.SelectAll.runCoreEditorCommand(this.viewModel, { source: 'mouse' });
    }
    // ----------------------
    _convertViewToModelPosition(viewPosition) {
        return this.viewModel.coordinatesConverter.convertViewPositionToModelPosition(viewPosition);
    }
    emitKeyDown(e) {
        this.userInputEvents.emitKeyDown(e);
    }
    emitKeyUp(e) {
        this.userInputEvents.emitKeyUp(e);
    }
    emitContextMenu(e) {
        this.userInputEvents.emitContextMenu(e);
    }
    emitMouseMove(e) {
        this.userInputEvents.emitMouseMove(e);
    }
    emitMouseLeave(e) {
        this.userInputEvents.emitMouseLeave(e);
    }
    emitMouseUp(e) {
        this.userInputEvents.emitMouseUp(e);
    }
    emitMouseDown(e) {
        this.userInputEvents.emitMouseDown(e);
    }
    emitMouseDrag(e) {
        this.userInputEvents.emitMouseDrag(e);
    }
    emitMouseDrop(e) {
        this.userInputEvents.emitMouseDrop(e);
    }
    emitMouseDropCanceled() {
        this.userInputEvents.emitMouseDropCanceled();
    }
    emitMouseWheel(e) {
        this.userInputEvents.emitMouseWheel(e);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/view/viewUserInputEvents.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class ViewUserInputEvents {
    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._coordinatesConverter = coordinatesConverter;
    }
    emitKeyDown(e) {
        var _a;
        (_a = this.onKeyDown) === null || _a === void 0 ? void 0 : _a.call(this, e);
    }
    emitKeyUp(e) {
        var _a;
        (_a = this.onKeyUp) === null || _a === void 0 ? void 0 : _a.call(this, e);
    }
    emitContextMenu(e) {
        var _a;
        (_a = this.onContextMenu) === null || _a === void 0 ? void 0 : _a.call(this, this._convertViewToModelMouseEvent(e));
    }
    emitMouseMove(e) {
        var _a;
        (_a = this.onMouseMove) === null || _a === void 0 ? void 0 : _a.call(this, this._convertViewToModelMouseEvent(e));
    }
    emitMouseLeave(e) {
        var _a;
        (_a = this.onMouseLeave) === null || _a === void 0 ? void 0 : _a.call(this, this._convertViewToModelMouseEvent(e));
    }
    emitMouseDown(e) {
        var _a;
        (_a = this.onMouseDown) === null || _a === void 0 ? void 0 : _a.call(this, this._convertViewToModelMouseEvent(e));
    }
    emitMouseUp(e) {
        var _a;
        (_a = this.onMouseUp) === null || _a === void 0 ? void 0 : _a.call(this, this._convertViewToModelMouseEvent(e));
    }
    emitMouseDrag(e) {
        var _a;
        (_a = this.onMouseDrag) === null || _a === void 0 ? void 0 : _a.call(this, this._convertViewToModelMouseEvent(e));
    }
    emitMouseDrop(e) {
        var _a;
        (_a = this.onMouseDrop) === null || _a === void 0 ? void 0 : _a.call(this, this._convertViewToModelMouseEvent(e));
    }
    emitMouseDropCanceled() {
        var _a;
        (_a = this.onMouseDropCanceled) === null || _a === void 0 ? void 0 : _a.call(this);
    }
    emitMouseWheel(e) {
        var _a;
        (_a = this.onMouseWheel) === null || _a === void 0 ? void 0 : _a.call(this, e);
    }
    _convertViewToModelMouseEvent(e) {
        if (e.target) {
            return {
                event: e.event,
                target: this._convertViewToModelMouseTarget(e.target)
            };
        }
        return e;
    }
    _convertViewToModelMouseTarget(target) {
        return ViewUserInputEvents.convertViewToModelMouseTarget(target, this._coordinatesConverter);
    }
    static convertViewToModelMouseTarget(target, coordinatesConverter) {
        const result = Object.assign({}, target);
        if (result.position) {
            result.position = coordinatesConverter.convertViewPositionToModelPosition(result.position);
        }
        if (result.range) {
            result.range = coordinatesConverter.convertViewRangeToModelRange(result.range);
        }
        return result;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/view/viewLayer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var viewLayer_a;


class RenderedLinesCollection {
    constructor(createLine) {
        this._createLine = createLine;
        this._set(1, []);
    }
    flush() {
        this._set(1, []);
    }
    _set(rendLineNumberStart, lines) {
        this._lines = lines;
        this._rendLineNumberStart = rendLineNumberStart;
    }
    _get() {
        return {
            rendLineNumberStart: this._rendLineNumberStart,
            lines: this._lines
        };
    }
    /**
     * @returns Inclusive line number that is inside this collection
     */
    getStartLineNumber() {
        return this._rendLineNumberStart;
    }
    /**
     * @returns Inclusive line number that is inside this collection
     */
    getEndLineNumber() {
        return this._rendLineNumberStart + this._lines.length - 1;
    }
    getCount() {
        return this._lines.length;
    }
    getLine(lineNumber) {
        const lineIndex = lineNumber - this._rendLineNumberStart;
        if (lineIndex < 0 || lineIndex >= this._lines.length) {
            throw new Error('Illegal value for lineNumber');
        }
        return this._lines[lineIndex];
    }
    /**
     * @returns Lines that were removed from this collection
     */
    onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
        if (this.getCount() === 0) {
            // no lines
            return null;
        }
        const startLineNumber = this.getStartLineNumber();
        const endLineNumber = this.getEndLineNumber();
        if (deleteToLineNumber < startLineNumber) {
            // deleting above the viewport
            const deleteCnt = deleteToLineNumber - deleteFromLineNumber + 1;
            this._rendLineNumberStart -= deleteCnt;
            return null;
        }
        if (deleteFromLineNumber > endLineNumber) {
            // deleted below the viewport
            return null;
        }
        // Record what needs to be deleted
        let deleteStartIndex = 0;
        let deleteCount = 0;
        for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
            const lineIndex = lineNumber - this._rendLineNumberStart;
            if (deleteFromLineNumber <= lineNumber && lineNumber <= deleteToLineNumber) {
                // this is a line to be deleted
                if (deleteCount === 0) {
                    // this is the first line to be deleted
                    deleteStartIndex = lineIndex;
                    deleteCount = 1;
                }
                else {
                    deleteCount++;
                }
            }
        }
        // Adjust this._rendLineNumberStart for lines deleted above
        if (deleteFromLineNumber < startLineNumber) {
            // Something was deleted above
            let deleteAboveCount = 0;
            if (deleteToLineNumber < startLineNumber) {
                // the entire deleted lines are above
                deleteAboveCount = deleteToLineNumber - deleteFromLineNumber + 1;
            }
            else {
                deleteAboveCount = startLineNumber - deleteFromLineNumber;
            }
            this._rendLineNumberStart -= deleteAboveCount;
        }
        const deleted = this._lines.splice(deleteStartIndex, deleteCount);
        return deleted;
    }
    onLinesChanged(changeFromLineNumber, changeCount) {
        const changeToLineNumber = changeFromLineNumber + changeCount - 1;
        if (this.getCount() === 0) {
            // no lines
            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) {
                // Notify the line
                this._lines[changedLineNumber - this._rendLineNumberStart].onContentChanged();
                someoneNotified = true;
            }
        }
        return someoneNotified;
    }
    onLinesInserted(insertFromLineNumber, insertToLineNumber) {
        if (this.getCount() === 0) {
            // no lines
            return null;
        }
        const insertCnt = insertToLineNumber - insertFromLineNumber + 1;
        const startLineNumber = this.getStartLineNumber();
        const endLineNumber = this.getEndLineNumber();
        if (insertFromLineNumber <= startLineNumber) {
            // inserting above the viewport
            this._rendLineNumberStart += insertCnt;
            return null;
        }
        if (insertFromLineNumber > endLineNumber) {
            // inserting below the viewport
            return null;
        }
        if (insertCnt + insertFromLineNumber > endLineNumber) {
            // insert inside the viewport in such a way that all remaining lines are pushed outside
            const deleted = this._lines.splice(insertFromLineNumber - this._rendLineNumberStart, endLineNumber - insertFromLineNumber + 1);
            return deleted;
        }
        // insert inside the viewport, push out some lines, but not all remaining lines
        const newLines = [];
        for (let i = 0; i < insertCnt; i++) {
            newLines[i] = this._createLine();
        }
        const insertIndex = insertFromLineNumber - this._rendLineNumberStart;
        const beforeLines = this._lines.slice(0, insertIndex);
        const afterLines = this._lines.slice(insertIndex, this._lines.length - insertCnt);
        const deletedLines = this._lines.slice(this._lines.length - insertCnt, this._lines.length);
        this._lines = beforeLines.concat(newLines).concat(afterLines);
        return deletedLines;
    }
    onTokensChanged(ranges) {
        if (this.getCount() === 0) {
            // no lines
            return false;
        }
        const startLineNumber = this.getStartLineNumber();
        const endLineNumber = this.getEndLineNumber();
        let notifiedSomeone = false;
        for (let i = 0, len = ranges.length; i < len; i++) {
            const rng = ranges[i];
            if (rng.toLineNumber < startLineNumber || rng.fromLineNumber > endLineNumber) {
                // range outside viewport
                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._rendLineNumberStart;
                this._lines[lineIndex].onTokensChanged();
                notifiedSomeone = true;
            }
        }
        return notifiedSomeone;
    }
}
class VisibleLinesCollection {
    constructor(host) {
        this._host = host;
        this.domNode = this._createDomNode();
        this._linesCollection = new RenderedLinesCollection(() => this._host.createVisibleLine());
    }
    _createDomNode() {
        const domNode = createFastDomNode(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(133 /* EditorOption.layoutInfo */)) {
            return true;
        }
        return false;
    }
    onFlushed(e) {
        this._linesCollection.flush();
        // No need to clear the dom node because a full .innerHTML will occur in ViewLayerRenderer._render
        return true;
    }
    onLinesChanged(e) {
        return this._linesCollection.onLinesChanged(e.fromLineNumber, e.count);
    }
    onLinesDeleted(e) {
        const deleted = this._linesCollection.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
        if (deleted) {
            // Remove from DOM
            for (let i = 0, len = deleted.length; i < len; i++) {
                const lineDomNode = deleted[i].getDomNode();
                if (lineDomNode) {
                    this.domNode.domNode.removeChild(lineDomNode);
                }
            }
        }
        return true;
    }
    onLinesInserted(e) {
        const deleted = this._linesCollection.onLinesInserted(e.fromLineNumber, e.toLineNumber);
        if (deleted) {
            // Remove from DOM
            for (let i = 0, len = deleted.length; i < len; i++) {
                const lineDomNode = deleted[i].getDomNode();
                if (lineDomNode) {
                    this.domNode.domNode.removeChild(lineDomNode);
                }
            }
        }
        return true;
    }
    onScrollChanged(e) {
        return e.scrollTopChanged;
    }
    onTokensChanged(e) {
        return this._linesCollection.onTokensChanged(e.ranges);
    }
    onZonesChanged(e) {
        return true;
    }
    // ---- end view event handlers
    getStartLineNumber() {
        return this._linesCollection.getStartLineNumber();
    }
    getEndLineNumber() {
        return this._linesCollection.getEndLineNumber();
    }
    getVisibleLine(lineNumber) {
        return this._linesCollection.getLine(lineNumber);
    }
    renderLines(viewportData) {
        const inp = this._linesCollection._get();
        const renderer = new ViewLayerRenderer(this.domNode.domNode, this._host, viewportData);
        const ctx = {
            rendLineNumberStart: inp.rendLineNumberStart,
            lines: inp.lines,
            linesLength: inp.lines.length
        };
        // Decide if this render will do a single update (single large .innerHTML) or many updates (inserting/removing dom nodes)
        const resCtx = renderer.render(ctx, viewportData.startLineNumber, viewportData.endLineNumber, viewportData.relativeVerticalOffset);
        this._linesCollection._set(resCtx.rendLineNumberStart, resCtx.lines);
    }
}
class ViewLayerRenderer {
    constructor(domNode, host, viewportData) {
        this.domNode = domNode;
        this.host = host;
        this.viewportData = viewportData;
    }
    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)) {
            // There is no overlap whatsoever
            ctx.rendLineNumberStart = startLineNumber;
            ctx.linesLength = stopLineNumber - startLineNumber + 1;
            ctx.lines = [];
            for (let x = startLineNumber; x <= stopLineNumber; x++) {
                ctx.lines[x - startLineNumber] = this.host.createVisibleLine();
            }
            this._finishRendering(ctx, true, deltaTop);
            return ctx;
        }
        // Update lines which will remain untouched
        this._renderUntouchedLines(ctx, Math.max(startLineNumber - ctx.rendLineNumberStart, 0), Math.min(stopLineNumber - ctx.rendLineNumberStart, ctx.linesLength - 1), deltaTop, startLineNumber);
        if (ctx.rendLineNumberStart > startLineNumber) {
            // Insert lines before
            const fromLineNumber = startLineNumber;
            const toLineNumber = Math.min(stopLineNumber, ctx.rendLineNumberStart - 1);
            if (fromLineNumber <= toLineNumber) {
                this._insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
                ctx.linesLength += toLineNumber - fromLineNumber + 1;
            }
        }
        else if (ctx.rendLineNumberStart < startLineNumber) {
            // Remove lines before
            const removeCnt = Math.min(ctx.linesLength, startLineNumber - ctx.rendLineNumberStart);
            if (removeCnt > 0) {
                this._removeLinesBefore(ctx, removeCnt);
                ctx.linesLength -= removeCnt;
            }
        }
        ctx.rendLineNumberStart = startLineNumber;
        if (ctx.rendLineNumberStart + ctx.linesLength - 1 < stopLineNumber) {
            // Insert lines after
            const fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength;
            const toLineNumber = stopLineNumber;
            if (fromLineNumber <= toLineNumber) {
                this._insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
                ctx.linesLength += toLineNumber - fromLineNumber + 1;
            }
        }
        else if (ctx.rendLineNumberStart + ctx.linesLength - 1 > stopLineNumber) {
            // Remove lines after
            const fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1);
            const toLineNumber = ctx.linesLength - 1;
            const removeCnt = toLineNumber - fromLineNumber + 1;
            if (removeCnt > 0) {
                this._removeLinesAfter(ctx, removeCnt);
                ctx.linesLength -= removeCnt;
            }
        }
        this._finishRendering(ctx, false, deltaTop);
        return ctx;
    }
    _renderUntouchedLines(ctx, startIndex, endIndex, deltaTop, deltaLN) {
        const rendLineNumberStart = ctx.rendLineNumberStart;
        const lines = ctx.lines;
        for (let i = startIndex; i <= endIndex; i++) {
            const lineNumber = rendLineNumberStart + i;
            lines[i].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN]);
        }
    }
    _insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
        const newLines = [];
        let newLinesLen = 0;
        for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
            newLines[newLinesLen++] = this.host.createVisibleLine();
        }
        ctx.lines = newLines.concat(ctx.lines);
    }
    _removeLinesBefore(ctx, removeCount) {
        for (let i = 0; i < removeCount; i++) {
            const lineDomNode = ctx.lines[i].getDomNode();
            if (lineDomNode) {
                this.domNode.removeChild(lineDomNode);
            }
        }
        ctx.lines.splice(0, removeCount);
    }
    _insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
        const newLines = [];
        let newLinesLen = 0;
        for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
            newLines[newLinesLen++] = this.host.createVisibleLine();
        }
        ctx.lines = ctx.lines.concat(newLines);
    }
    _removeLinesAfter(ctx, removeCount) {
        const removeIndex = ctx.linesLength - removeCount;
        for (let i = 0; i < removeCount; i++) {
            const lineDomNode = ctx.lines[removeIndex + i].getDomNode();
            if (lineDomNode) {
                this.domNode.removeChild(lineDomNode);
            }
        }
        ctx.lines.splice(removeIndex, removeCount);
    }
    _finishRenderingNewLines(ctx, domNodeIsEmpty, newLinesHTML, wasNew) {
        if (ViewLayerRenderer._ttPolicy) {
            newLinesHTML = ViewLayerRenderer._ttPolicy.createHTML(newLinesHTML);
        }
        const lastChild = this.domNode.lastChild;
        if (domNodeIsEmpty || !lastChild) {
            this.domNode.innerHTML = newLinesHTML; // explains the ugly casts -> https://github.com/microsoft/vscode/issues/106396#issuecomment-692625393;
        }
        else {
            lastChild.insertAdjacentHTML('afterend', newLinesHTML);
        }
        let currChild = this.domNode.lastChild;
        for (let i = ctx.linesLength - 1; i >= 0; i--) {
            const line = ctx.lines[i];
            if (wasNew[i]) {
                line.setDomNode(currChild);
                currChild = currChild.previousSibling;
            }
        }
    }
    _finishRenderingInvalidLines(ctx, invalidLinesHTML, wasInvalid) {
        const hugeDomNode = document.createElement('div');
        if (ViewLayerRenderer._ttPolicy) {
            invalidLinesHTML = ViewLayerRenderer._ttPolicy.createHTML(invalidLinesHTML);
        }
        hugeDomNode.innerHTML = invalidLinesHTML;
        for (let i = 0; i < ctx.linesLength; i++) {
            const line = ctx.lines[i];
            if (wasInvalid[i]) {
                const source = hugeDomNode.firstChild;
                const lineDomNode = line.getDomNode();
                lineDomNode.parentNode.replaceChild(source, lineDomNode);
                line.setDomNode(source);
            }
        }
    }
    _finishRendering(ctx, domNodeIsEmpty, deltaTop) {
        const sb = ViewLayerRenderer._sb;
        const linesLength = ctx.linesLength;
        const lines = ctx.lines;
        const rendLineNumberStart = ctx.rendLineNumberStart;
        const wasNew = [];
        {
            sb.reset();
            let hadNewLine = false;
            for (let i = 0; i < linesLength; i++) {
                const line = lines[i];
                wasNew[i] = false;
                const lineDomNode = line.getDomNode();
                if (lineDomNode) {
                    // line is not new
                    continue;
                }
                const renderResult = line.renderLine(i + rendLineNumberStart, deltaTop[i], this.viewportData, sb);
                if (!renderResult) {
                    // line does not need rendering
                    continue;
                }
                wasNew[i] = true;
                hadNewLine = true;
            }
            if (hadNewLine) {
                this._finishRenderingNewLines(ctx, domNodeIsEmpty, sb.build(), wasNew);
            }
        }
        {
            sb.reset();
            let hadInvalidLine = false;
            const wasInvalid = [];
            for (let i = 0; i < linesLength; i++) {
                const line = lines[i];
                wasInvalid[i] = false;
                if (wasNew[i]) {
                    // line was new
                    continue;
                }
                const renderResult = line.renderLine(i + rendLineNumberStart, deltaTop[i], this.viewportData, sb);
                if (!renderResult) {
                    // line does not need rendering
                    continue;
                }
                wasInvalid[i] = true;
                hadInvalidLine = true;
            }
            if (hadInvalidLine) {
                this._finishRenderingInvalidLines(ctx, sb.build(), wasInvalid);
            }
        }
    }
}
ViewLayerRenderer._ttPolicy = (viewLayer_a = window.trustedTypes) === null || viewLayer_a === void 0 ? void 0 : viewLayer_a.createPolicy('editorViewLayer', { createHTML: value => value });
ViewLayerRenderer._sb = createStringBuilder(100000);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/view/viewOverlays.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class ViewOverlays extends ViewPart {
    constructor(context) {
        super(context);
        this._visibleLines = new VisibleLinesCollection(this);
        this.domNode = this._visibleLines.domNode;
        this._dynamicOverlays = [];
        this._isFocused = false;
        this.domNode.setClassName('view-overlays');
    }
    shouldRender() {
        if (super.shouldRender()) {
            return true;
        }
        for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) {
            const dynamicOverlay = this._dynamicOverlays[i];
            if (dynamicOverlay.shouldRender()) {
                return true;
            }
        }
        return false;
    }
    dispose() {
        super.dispose();
        for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) {
            const dynamicOverlay = this._dynamicOverlays[i];
            dynamicOverlay.dispose();
        }
        this._dynamicOverlays = [];
    }
    getDomNode() {
        return this.domNode;
    }
    // ---- begin IVisibleLinesHost
    createVisibleLine() {
        return new ViewOverlayLine(this._context.configuration, this._dynamicOverlays);
    }
    // ---- end IVisibleLinesHost
    addDynamicOverlay(overlay) {
        this._dynamicOverlays.push(overlay);
    }
    // ----- event handlers
    onConfigurationChanged(e) {
        this._visibleLines.onConfigurationChanged(e);
        const startLineNumber = this._visibleLines.getStartLineNumber();
        const endLineNumber = this._visibleLines.getEndLineNumber();
        for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
            const line = this._visibleLines.getVisibleLine(lineNumber);
            line.onConfigurationChanged(e);
        }
        return true;
    }
    onFlushed(e) {
        return this._visibleLines.onFlushed(e);
    }
    onFocusChanged(e) {
        this._isFocused = e.isFocused;
        return true;
    }
    onLinesChanged(e) {
        return this._visibleLines.onLinesChanged(e);
    }
    onLinesDeleted(e) {
        return this._visibleLines.onLinesDeleted(e);
    }
    onLinesInserted(e) {
        return this._visibleLines.onLinesInserted(e);
    }
    onScrollChanged(e) {
        return this._visibleLines.onScrollChanged(e) || true;
    }
    onTokensChanged(e) {
        return this._visibleLines.onTokensChanged(e);
    }
    onZonesChanged(e) {
        return this._visibleLines.onZonesChanged(e);
    }
    // ----- end event handlers
    prepareRender(ctx) {
        const toRender = this._dynamicOverlays.filter(overlay => overlay.shouldRender());
        for (let i = 0, len = toRender.length; i < len; i++) {
            const dynamicOverlay = toRender[i];
            dynamicOverlay.prepareRender(ctx);
            dynamicOverlay.onDidRender();
        }
    }
    render(ctx) {
        // Overwriting to bypass `shouldRender` flag
        this._viewOverlaysRender(ctx);
        this.domNode.toggleClassName('focused', this._isFocused);
    }
    _viewOverlaysRender(ctx) {
        this._visibleLines.renderLines(ctx.viewportData);
    }
}
class ViewOverlayLine {
    constructor(configuration, dynamicOverlays) {
        this._configuration = configuration;
        this._lineHeight = this._configuration.options.get(61 /* EditorOption.lineHeight */);
        this._dynamicOverlays = dynamicOverlays;
        this._domNode = null;
        this._renderedContent = null;
    }
    getDomNode() {
        if (!this._domNode) {
            return null;
        }
        return this._domNode.domNode;
    }
    setDomNode(domNode) {
        this._domNode = createFastDomNode(domNode);
    }
    onContentChanged() {
        // Nothing
    }
    onTokensChanged() {
        // Nothing
    }
    onConfigurationChanged(e) {
        this._lineHeight = this._configuration.options.get(61 /* EditorOption.lineHeight */);
    }
    renderLine(lineNumber, deltaTop, viewportData, sb) {
        let result = '';
        for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) {
            const dynamicOverlay = this._dynamicOverlays[i];
            result += dynamicOverlay.render(viewportData.startLineNumber, lineNumber);
        }
        if (this._renderedContent === result) {
            // No rendering needed
            return false;
        }
        this._renderedContent = result;
        sb.appendASCIIString('<div style="position:absolute;top:');
        sb.appendASCIIString(String(deltaTop));
        sb.appendASCIIString('px;width:100%;height:');
        sb.appendASCIIString(String(this._lineHeight));
        sb.appendASCIIString('px;">');
        sb.appendASCIIString(result);
        sb.appendASCIIString('</div>');
        return true;
    }
    layoutLine(lineNumber, deltaTop) {
        if (this._domNode) {
            this._domNode.setTop(deltaTop);
            this._domNode.setHeight(this._lineHeight);
        }
    }
}
class ContentViewOverlays extends ViewOverlays {
    constructor(context) {
        super(context);
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._contentWidth = layoutInfo.contentWidth;
        this.domNode.setHeight(0);
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._contentWidth = layoutInfo.contentWidth;
        return super.onConfigurationChanged(e) || true;
    }
    onScrollChanged(e) {
        return super.onScrollChanged(e) || e.scrollWidthChanged;
    }
    // --- end event handlers
    _viewOverlaysRender(ctx) {
        super._viewOverlaysRender(ctx);
        this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth));
    }
}
class MarginViewOverlays extends ViewOverlays {
    constructor(context) {
        super(context);
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._contentLeft = layoutInfo.contentLeft;
        this.domNode.setClassName('margin-view-overlays');
        this.domNode.setWidth(1);
        applyFontInfo(this.domNode, options.get(46 /* EditorOption.fontInfo */));
    }
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        applyFontInfo(this.domNode, options.get(46 /* EditorOption.fontInfo */));
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._contentLeft = 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, 1000000);
        this.domNode.setHeight(height);
        this.domNode.setWidth(this._contentLeft);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/contentWidgets/contentWidgets.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class Coordinate {
    constructor(top, left) {
        this._coordinateBrand = undefined;
        this.top = top;
        this.left = left;
    }
}
class ViewContentWidgets extends ViewPart {
    constructor(context, viewDomNode) {
        super(context);
        this._viewDomNode = viewDomNode;
        this._widgets = {};
        this.domNode = createFastDomNode(document.createElement('div'));
        PartFingerprints.write(this.domNode, 1 /* PartFingerprint.ContentWidgets */);
        this.domNode.setClassName('contentWidgets');
        this.domNode.setPosition('absolute');
        this.domNode.setTop(0);
        this.overflowingContentWidgetsDomNode = createFastDomNode(document.createElement('div'));
        PartFingerprints.write(this.overflowingContentWidgetsDomNode, 2 /* PartFingerprint.OverflowingContentWidgets */);
        this.overflowingContentWidgetsDomNode.setClassName('overflowingContentWidgets');
    }
    dispose() {
        super.dispose();
        this._widgets = {};
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        const keys = Object.keys(this._widgets);
        for (const widgetId of keys) {
            this._widgets[widgetId].onConfigurationChanged(e);
        }
        return true;
    }
    onDecorationsChanged(e) {
        // true for inline decorations that can end up relayouting text
        return true;
    }
    onFlushed(e) {
        return true;
    }
    onLineMappingChanged(e) {
        const keys = Object.keys(this._widgets);
        for (const widgetId of keys) {
            this._widgets[widgetId].onLineMappingChanged(e);
        }
        return true;
    }
    onLinesChanged(e) {
        return true;
    }
    onLinesDeleted(e) {
        return true;
    }
    onLinesInserted(e) {
        return true;
    }
    onScrollChanged(e) {
        return true;
    }
    onZonesChanged(e) {
        return true;
    }
    // ---- end view event handlers
    addWidget(_widget) {
        const myWidget = new contentWidgets_Widget(this._context, this._viewDomNode, _widget);
        this._widgets[myWidget.id] = myWidget;
        if (myWidget.allowEditorOverflow) {
            this.overflowingContentWidgetsDomNode.appendChild(myWidget.domNode);
        }
        else {
            this.domNode.appendChild(myWidget.domNode);
        }
        this.setShouldRender();
    }
    setWidgetPosition(widget, range, preference, affinity) {
        const myWidget = this._widgets[widget.getId()];
        myWidget.setPosition(range, preference, affinity);
        this.setShouldRender();
    }
    removeWidget(widget) {
        const widgetId = widget.getId();
        if (this._widgets.hasOwnProperty(widgetId)) {
            const myWidget = this._widgets[widgetId];
            delete this._widgets[widgetId];
            const domNode = myWidget.domNode.domNode;
            domNode.parentNode.removeChild(domNode);
            domNode.removeAttribute('monaco-visible-content-widget');
            this.setShouldRender();
        }
    }
    shouldSuppressMouseDownOnWidget(widgetId) {
        if (this._widgets.hasOwnProperty(widgetId)) {
            return this._widgets[widgetId].suppressMouseDown;
        }
        return false;
    }
    onBeforeRender(viewportData) {
        const keys = Object.keys(this._widgets);
        for (const widgetId of keys) {
            this._widgets[widgetId].onBeforeRender(viewportData);
        }
    }
    prepareRender(ctx) {
        const keys = Object.keys(this._widgets);
        for (const widgetId of keys) {
            this._widgets[widgetId].prepareRender(ctx);
        }
    }
    render(ctx) {
        const keys = Object.keys(this._widgets);
        for (const widgetId of keys) {
            this._widgets[widgetId].render(ctx);
        }
    }
}
class contentWidgets_Widget {
    constructor(context, viewDomNode, actual) {
        this._context = context;
        this._viewDomNode = viewDomNode;
        this._actual = actual;
        this.domNode = createFastDomNode(this._actual.getDomNode());
        this.id = this._actual.getId();
        this.allowEditorOverflow = this._actual.allowEditorOverflow || false;
        this.suppressMouseDown = this._actual.suppressMouseDown || false;
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._fixedOverflowWidgets = options.get(38 /* EditorOption.fixedOverflowWidgets */);
        this._contentWidth = layoutInfo.contentWidth;
        this._contentLeft = layoutInfo.contentLeft;
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._range = null;
        this._viewRange = null;
        this._affinity = null;
        this._preference = [];
        this._cachedDomNodeOffsetWidth = -1;
        this._cachedDomNodeOffsetHeight = -1;
        this._maxWidth = this._getMaxWidth();
        this._isVisible = false;
        this._renderData = null;
        this.domNode.setPosition((this._fixedOverflowWidgets && this.allowEditorOverflow) ? 'fixed' : 'absolute');
        this.domNode.setDisplay('none');
        this.domNode.setVisibility('hidden');
        this.domNode.setAttribute('widgetId', this.id);
        this.domNode.setMaxWidth(this._maxWidth);
    }
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        if (e.hasChanged(133 /* EditorOption.layoutInfo */)) {
            const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
            this._contentLeft = layoutInfo.contentLeft;
            this._contentWidth = layoutInfo.contentWidth;
            this._maxWidth = this._getMaxWidth();
        }
    }
    onLineMappingChanged(e) {
        this._setPosition(this._range, this._affinity);
    }
    _setPosition(range, affinity) {
        var _a;
        this._range = range;
        this._viewRange = null;
        this._affinity = affinity;
        if (this._range) {
            // Do not trust that widgets give a valid position
            const validModelRange = this._context.viewModel.model.validateRange(this._range);
            if (this._context.viewModel.coordinatesConverter.modelPositionIsVisible(validModelRange.getStartPosition()) || this._context.viewModel.coordinatesConverter.modelPositionIsVisible(validModelRange.getEndPosition())) {
                this._viewRange = this._context.viewModel.coordinatesConverter.convertModelRangeToViewRange(validModelRange, (_a = this._affinity) !== null && _a !== void 0 ? _a : undefined);
            }
        }
    }
    _getMaxWidth() {
        return (this.allowEditorOverflow
            ? window.innerWidth || document.documentElement.offsetWidth || document.body.offsetWidth
            : this._contentWidth);
    }
    setPosition(range, preference, affinity) {
        this._setPosition(range, affinity);
        this._preference = preference;
        if (this._viewRange && this._preference && this._preference.length > 0) {
            // this content widget would like to be visible if possible
            // we change it from `display:none` to `display:block` even if it
            // might be outside the viewport such that we can measure its size
            // in `prepareRender`
            this.domNode.setDisplay('block');
        }
        else {
            this.domNode.setDisplay('none');
        }
        this._cachedDomNodeOffsetWidth = -1;
        this._cachedDomNodeOffsetHeight = -1;
    }
    _layoutBoxInViewport(topLeft, bottomLeft, width, height, ctx) {
        // Our visible box is split horizontally by the current line => 2 boxes
        // a) the box above the line
        const aboveLineTop = topLeft.top;
        const heightAboveLine = aboveLineTop;
        // b) the box under the line
        const underLineTop = bottomLeft.top + this._lineHeight;
        const heightUnderLine = ctx.viewportHeight - underLineTop;
        const aboveTop = aboveLineTop - height;
        const fitsAbove = (heightAboveLine >= height);
        const belowTop = underLineTop;
        const fitsBelow = (heightUnderLine >= height);
        // And its left
        let actualAboveLeft = topLeft.left;
        let actualBelowLeft = bottomLeft.left;
        if (actualAboveLeft + width > ctx.scrollLeft + ctx.viewportWidth) {
            actualAboveLeft = ctx.scrollLeft + ctx.viewportWidth - width;
        }
        if (actualBelowLeft + width > ctx.scrollLeft + ctx.viewportWidth) {
            actualBelowLeft = ctx.scrollLeft + ctx.viewportWidth - width;
        }
        if (actualAboveLeft < ctx.scrollLeft) {
            actualAboveLeft = ctx.scrollLeft;
        }
        if (actualBelowLeft < ctx.scrollLeft) {
            actualBelowLeft = ctx.scrollLeft;
        }
        return {
            fitsAbove: fitsAbove,
            aboveTop: aboveTop,
            aboveLeft: actualAboveLeft,
            fitsBelow: fitsBelow,
            belowTop: belowTop,
            belowLeft: actualBelowLeft,
        };
    }
    _layoutHorizontalSegmentInPage(windowSize, domNodePosition, left, width) {
        // Initially, the limits are defined as the dom node limits
        const MIN_LIMIT = Math.max(0, domNodePosition.left - width);
        const MAX_LIMIT = Math.min(domNodePosition.left + domNodePosition.width + width, windowSize.width);
        let absoluteLeft = domNodePosition.left + left - StandardWindow.scrollX;
        if (absoluteLeft + width > MAX_LIMIT) {
            const delta = absoluteLeft - (MAX_LIMIT - width);
            absoluteLeft -= delta;
            left -= delta;
        }
        if (absoluteLeft < MIN_LIMIT) {
            const delta = absoluteLeft - MIN_LIMIT;
            absoluteLeft -= delta;
            left -= delta;
        }
        return [left, absoluteLeft];
    }
    _layoutBoxInPage(topLeft, bottomLeft, width, height, ctx) {
        const aboveTop = topLeft.top - height;
        const belowTop = bottomLeft.top + this._lineHeight;
        const domNodePosition = getDomNodePagePosition(this._viewDomNode.domNode);
        const absoluteAboveTop = domNodePosition.top + aboveTop - StandardWindow.scrollY;
        const absoluteBelowTop = domNodePosition.top + belowTop - StandardWindow.scrollY;
        const windowSize = getClientArea(document.body);
        const [aboveLeft, absoluteAboveLeft] = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, topLeft.left - ctx.scrollLeft + this._contentLeft, width);
        const [belowLeft, absoluteBelowLeft] = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, bottomLeft.left - ctx.scrollLeft + this._contentLeft, width);
        // Leave some clearance to the top/bottom
        const TOP_PADDING = 22;
        const BOTTOM_PADDING = 22;
        const fitsAbove = (absoluteAboveTop >= TOP_PADDING);
        const fitsBelow = (absoluteBelowTop + height <= windowSize.height - BOTTOM_PADDING);
        if (this._fixedOverflowWidgets) {
            return {
                fitsAbove,
                aboveTop: Math.max(absoluteAboveTop, TOP_PADDING),
                aboveLeft: absoluteAboveLeft,
                fitsBelow,
                belowTop: absoluteBelowTop,
                belowLeft: absoluteBelowLeft
            };
        }
        return {
            fitsAbove,
            aboveTop: aboveTop,
            aboveLeft,
            fitsBelow,
            belowTop,
            belowLeft
        };
    }
    _prepareRenderWidgetAtExactPositionOverflowing(topLeft) {
        return new Coordinate(topLeft.top, topLeft.left + this._contentLeft);
    }
    /**
     * Compute `this._topLeft`
     */
    _getTopAndBottomLeft(ctx) {
        if (!this._viewRange) {
            return [null, null];
        }
        const visibleRangesForRange = ctx.linesVisibleRangesForRange(this._viewRange, false);
        if (!visibleRangesForRange || visibleRangesForRange.length === 0) {
            return [null, null];
        }
        let firstLine = visibleRangesForRange[0];
        let lastLine = visibleRangesForRange[0];
        for (const visibleRangesForLine of visibleRangesForRange) {
            if (visibleRangesForLine.lineNumber < firstLine.lineNumber) {
                firstLine = visibleRangesForLine;
            }
            if (visibleRangesForLine.lineNumber > lastLine.lineNumber) {
                lastLine = visibleRangesForLine;
            }
        }
        let firstLineMinLeft = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */; //firstLine.Constants.MAX_SAFE_SMALL_INTEGER;
        for (const visibleRange of firstLine.ranges) {
            if (visibleRange.left < firstLineMinLeft) {
                firstLineMinLeft = visibleRange.left;
            }
        }
        let lastLineMinLeft = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */; //lastLine.Constants.MAX_SAFE_SMALL_INTEGER;
        for (const visibleRange of lastLine.ranges) {
            if (visibleRange.left < lastLineMinLeft) {
                lastLineMinLeft = visibleRange.left;
            }
        }
        const topForPosition = ctx.getVerticalOffsetForLineNumber(firstLine.lineNumber) - ctx.scrollTop;
        const topLeft = new Coordinate(topForPosition, firstLineMinLeft);
        const topForBottomLine = ctx.getVerticalOffsetForLineNumber(lastLine.lineNumber) - ctx.scrollTop;
        const bottomLeft = new Coordinate(topForBottomLine, lastLineMinLeft);
        return [topLeft, bottomLeft];
    }
    _prepareRenderWidget(ctx) {
        if (!this._preference || this._preference.length === 0) {
            return null;
        }
        const [topLeft, bottomLeft] = this._getTopAndBottomLeft(ctx);
        if (!topLeft || !bottomLeft) {
            return null;
        }
        if (this._cachedDomNodeOffsetWidth === -1 || this._cachedDomNodeOffsetHeight === -1) {
            let preferredDimensions = null;
            if (typeof this._actual.beforeRender === 'function') {
                preferredDimensions = safeInvoke(this._actual.beforeRender, this._actual);
            }
            if (preferredDimensions) {
                this._cachedDomNodeOffsetWidth = preferredDimensions.width;
                this._cachedDomNodeOffsetHeight = preferredDimensions.height;
            }
            else {
                const domNode = this.domNode.domNode;
                const clientRect = domNode.getBoundingClientRect();
                this._cachedDomNodeOffsetWidth = Math.round(clientRect.width);
                this._cachedDomNodeOffsetHeight = Math.round(clientRect.height);
            }
        }
        let placement;
        if (this.allowEditorOverflow) {
            placement = this._layoutBoxInPage(topLeft, bottomLeft, this._cachedDomNodeOffsetWidth, this._cachedDomNodeOffsetHeight, ctx);
        }
        else {
            placement = this._layoutBoxInViewport(topLeft, bottomLeft, this._cachedDomNodeOffsetWidth, this._cachedDomNodeOffsetHeight, ctx);
        }
        // Do two passes, first for perfect fit, second picks first option
        for (let pass = 1; pass <= 2; pass++) {
            for (const pref of this._preference) {
                // placement
                if (pref === 1 /* ContentWidgetPositionPreference.ABOVE */) {
                    if (!placement) {
                        // Widget outside of viewport
                        return null;
                    }
                    if (pass === 2 || placement.fitsAbove) {
                        return { coordinate: new Coordinate(placement.aboveTop, placement.aboveLeft), position: 1 /* ContentWidgetPositionPreference.ABOVE */ };
                    }
                }
                else if (pref === 2 /* ContentWidgetPositionPreference.BELOW */) {
                    if (!placement) {
                        // Widget outside of viewport
                        return null;
                    }
                    if (pass === 2 || placement.fitsBelow) {
                        return { coordinate: new Coordinate(placement.belowTop, placement.belowLeft), position: 2 /* ContentWidgetPositionPreference.BELOW */ };
                    }
                }
                else {
                    if (this.allowEditorOverflow) {
                        return { coordinate: this._prepareRenderWidgetAtExactPositionOverflowing(topLeft), position: 0 /* ContentWidgetPositionPreference.EXACT */ };
                    }
                    else {
                        return { coordinate: topLeft, 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._viewRange || !this._preference) {
            return;
        }
        if (this._viewRange.endLineNumber < viewportData.startLineNumber || this._viewRange.startLineNumber > viewportData.endLineNumber) {
            // Outside of viewport
            return;
        }
        this.domNode.setMaxWidth(this._maxWidth);
    }
    prepareRender(ctx) {
        this._renderData = this._prepareRenderWidget(ctx);
    }
    render(ctx) {
        if (!this._renderData) {
            // This widget should be invisible
            if (this._isVisible) {
                this.domNode.removeAttribute('monaco-visible-content-widget');
                this._isVisible = false;
                this.domNode.setVisibility('hidden');
            }
            if (typeof this._actual.afterRender === 'function') {
                safeInvoke(this._actual.afterRender, this._actual, null);
            }
            return;
        }
        // This widget should be visible
        if (this.allowEditorOverflow) {
            this.domNode.setTop(this._renderData.coordinate.top);
            this.domNode.setLeft(this._renderData.coordinate.left);
        }
        else {
            this.domNode.setTop(this._renderData.coordinate.top + ctx.scrollTop - ctx.bigNumbersDelta);
            this.domNode.setLeft(this._renderData.coordinate.left);
        }
        if (!this._isVisible) {
            this.domNode.setVisibility('inherit');
            this.domNode.setAttribute('monaco-visible-content-widget', 'true');
            this._isVisible = true;
        }
        if (typeof this._actual.afterRender === 'function') {
            safeInvoke(this._actual.afterRender, this._actual, this._renderData.position);
        }
    }
}
function safeInvoke(fn, thisArg, ...args) {
    try {
        return fn.call(thisArg, ...args);
    }
    catch (_a) {
        // ignore
        return null;
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight.css
var currentLineHighlight = __webpack_require__(30418);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight.css

      
      
      
      
      
      
      
      
      

var currentLineHighlight_options = {};

currentLineHighlight_options.styleTagTransform = (styleTagTransform_default());
currentLineHighlight_options.setAttributes = (setAttributesWithoutAttributes_default());

      currentLineHighlight_options.insert = insertBySelector_default().bind(null, "head");
    
currentLineHighlight_options.domAPI = (styleDomAPI_default());
currentLineHighlight_options.insertStyleElement = (insertStyleElement_default());

var currentLineHighlight_update = injectStylesIntoStyleTag_default()(currentLineHighlight/* default */.A, currentLineHighlight_options);




       /* harmony default export */ const currentLineHighlight_currentLineHighlight = (currentLineHighlight/* default */.A && currentLineHighlight/* default */.A.locals ? currentLineHighlight/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







class AbstractLineHighlightOverlay extends DynamicViewOverlay {
    constructor(context) {
        super();
        this._context = context;
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._renderLineHighlight = options.get(87 /* EditorOption.renderLineHighlight */);
        this._renderLineHighlightOnlyWhenFocus = options.get(88 /* EditorOption.renderLineHighlightOnlyWhenFocus */);
        this._contentLeft = layoutInfo.contentLeft;
        this._contentWidth = layoutInfo.contentWidth;
        this._selectionIsEmpty = true;
        this._focused = false;
        this._cursorLineNumbers = [1];
        this._selections = [new Selection(1, 1, 1, 1)];
        this._renderData = null;
        this._context.addEventHandler(this);
    }
    dispose() {
        this._context.removeEventHandler(this);
        super.dispose();
    }
    _readFromSelections() {
        let hasChanged = false;
        const cursorsLineNumbers = this._selections.map(s => s.positionLineNumber);
        cursorsLineNumbers.sort((a, b) => a - b);
        if (!equals(this._cursorLineNumbers, cursorsLineNumbers)) {
            this._cursorLineNumbers = cursorsLineNumbers;
            hasChanged = true;
        }
        const selectionIsEmpty = this._selections.every(s => s.isEmpty());
        if (this._selectionIsEmpty !== selectionIsEmpty) {
            this._selectionIsEmpty = selectionIsEmpty;
            hasChanged = true;
        }
        return hasChanged;
    }
    // --- begin event handlers
    onThemeChanged(e) {
        return this._readFromSelections();
    }
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._renderLineHighlight = options.get(87 /* EditorOption.renderLineHighlight */);
        this._renderLineHighlightOnlyWhenFocus = options.get(88 /* EditorOption.renderLineHighlightOnlyWhenFocus */);
        this._contentLeft = layoutInfo.contentLeft;
        this._contentWidth = layoutInfo.contentWidth;
        return true;
    }
    onCursorStateChanged(e) {
        this._selections = e.selections;
        return this._readFromSelections();
    }
    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._renderLineHighlightOnlyWhenFocus) {
            return false;
        }
        this._focused = e.isFocused;
        return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
        if (!this._shouldRenderThis()) {
            this._renderData = null;
            return;
        }
        const renderedLine = this._renderOne(ctx);
        const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
        const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
        const len = this._cursorLineNumbers.length;
        let index = 0;
        const renderData = [];
        for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
            const lineIndex = lineNumber - visibleStartLineNumber;
            while (index < len && this._cursorLineNumbers[index] < lineNumber) {
                index++;
            }
            if (index < len && this._cursorLineNumbers[index] === lineNumber) {
                renderData[lineIndex] = renderedLine;
            }
            else {
                renderData[lineIndex] = '';
            }
        }
        this._renderData = renderData;
    }
    render(startLineNumber, lineNumber) {
        if (!this._renderData) {
            return '';
        }
        const lineIndex = lineNumber - startLineNumber;
        if (lineIndex >= this._renderData.length) {
            return '';
        }
        return this._renderData[lineIndex];
    }
    _shouldRenderInMargin() {
        return ((this._renderLineHighlight === 'gutter' || this._renderLineHighlight === 'all')
            && (!this._renderLineHighlightOnlyWhenFocus || this._focused));
    }
    _shouldRenderInContent() {
        return ((this._renderLineHighlight === 'line' || this._renderLineHighlight === 'all')
            && this._selectionIsEmpty
            && (!this._renderLineHighlightOnlyWhenFocus || this._focused));
    }
}
class CurrentLineHighlightOverlay extends AbstractLineHighlightOverlay {
    _renderOne(ctx) {
        const className = 'current-line' + (this._shouldRenderOther() ? ' current-line-both' : '');
        return `<div class="${className}" style="width:${Math.max(ctx.scrollWidth, this._contentWidth)}px; height:${this._lineHeight}px;"></div>`;
    }
    _shouldRenderThis() {
        return this._shouldRenderInContent();
    }
    _shouldRenderOther() {
        return this._shouldRenderInMargin();
    }
}
class CurrentLineMarginHighlightOverlay extends AbstractLineHighlightOverlay {
    _renderOne(ctx) {
        const className = 'current-line' + (this._shouldRenderInMargin() ? ' current-line-margin' : '') + (this._shouldRenderOther() ? ' current-line-margin-both' : '');
        return `<div class="${className}" style="width:${this._contentLeft}px; height:${this._lineHeight}px;"></div>`;
    }
    _shouldRenderThis() {
        return true;
    }
    _shouldRenderOther() {
        return this._shouldRenderInContent();
    }
}
registerThemingParticipant((theme, collector) => {
    const lineHighlight = theme.getColor(editorLineHighlight);
    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(editorLineHighlightBorder)) {
        const lineHighlightBorder = theme.getColor(editorLineHighlightBorder);
        if (lineHighlightBorder) {
            collector.addRule(`.monaco-editor .view-overlays .current-line { border: 2px solid ${lineHighlightBorder}; }`);
            collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { border: 2px solid ${lineHighlightBorder}; }`);
            if (isHighContrast(theme.type)) {
                collector.addRule(`.monaco-editor .view-overlays .current-line { border-width: 1px; }`);
                collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { border-width: 1px; }`);
            }
        }
    }
});

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/decorations/decorations.css
var decorations = __webpack_require__(55274);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/decorations/decorations.css

      
      
      
      
      
      
      
      
      

var decorations_options = {};

decorations_options.styleTagTransform = (styleTagTransform_default());
decorations_options.setAttributes = (setAttributesWithoutAttributes_default());

      decorations_options.insert = insertBySelector_default().bind(null, "head");
    
decorations_options.domAPI = (styleDomAPI_default());
decorations_options.insertStyleElement = (insertStyleElement_default());

var decorations_update = injectStylesIntoStyleTag_default()(decorations/* default */.A, decorations_options);




       /* harmony default export */ const decorations_decorations = (decorations/* default */.A && decorations/* default */.A.locals ? decorations/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/decorations/decorations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class DecorationsOverlay extends DynamicViewOverlay {
    constructor(context) {
        super();
        this._context = context;
        const options = this._context.configuration.options;
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._typicalHalfwidthCharacterWidth = options.get(46 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
        this._renderResult = null;
        this._context.addEventHandler(this);
    }
    dispose() {
        this._context.removeEventHandler(this);
        this._renderResult = null;
        super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._typicalHalfwidthCharacterWidth = options.get(46 /* 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();
        // Keep only decorations with `className`
        let decorations = [];
        let decorationsLen = 0;
        for (let i = 0, len = _decorations.length; i < len; i++) {
            const d = _decorations[i];
            if (d.options.className) {
                decorations[decorationsLen++] = d;
            }
        }
        // Sort decorations for consistent render output
        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 Range.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] = '';
        }
        // Render first whole line decorations and then regular decorations
        this._renderWholeLineDecorations(ctx, decorations, output);
        this._renderNormalDecorations(ctx, decorations, output);
        this._renderResult = output;
    }
    _renderWholeLineDecorations(ctx, decorations, output) {
        const lineHeight = String(this._lineHeight);
        const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
        const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
        for (let i = 0, lenI = decorations.length; i < lenI; i++) {
            const d = decorations[i];
            if (!d.options.isWholeLine) {
                continue;
            }
            const decorationOutput = ('<div class="cdr '
                + d.options.className
                + '" style="left:0;width:100%;height:'
                + lineHeight
                + 'px;"></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;
            }
        }
    }
    _renderNormalDecorations(ctx, decorations, output) {
        const lineHeight = String(this._lineHeight);
        const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
        let prevClassName = null;
        let prevShowIfCollapsed = false;
        let prevRange = null;
        for (let i = 0, lenI = decorations.length; i < lenI; i++) {
            const d = decorations[i];
            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 Range(range.startLineNumber, range.startColumn, range.endLineNumber - 1, this._context.viewModel.getLineMaxColumn(range.endLineNumber - 1));
            }
            if (prevClassName === className && prevShowIfCollapsed === showIfCollapsed && Range.areIntersectingOrTouching(prevRange, range)) {
                // merge into previous decoration
                prevRange = Range.plusRange(prevRange, range);
                continue;
            }
            // flush previous decoration
            if (prevClassName !== null) {
                this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output);
            }
            prevClassName = className;
            prevShowIfCollapsed = showIfCollapsed;
            prevRange = range;
        }
        if (prevClassName !== null) {
            this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output);
        }
    }
    _renderNormalDecoration(ctx, range, className, showIfCollapsed, lineHeight, 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._typicalHalfwidthCharacterWidth) {
                    // collapsed/very small range case => make the decoration visible by expanding its width
                    // expand its size on both sides (both to the left and to the right, keeping it centered)
                    const center = Math.round(singleVisibleRange.left + singleVisibleRange.width / 2);
                    const left = Math.max(0, Math.round(center - this._typicalHalfwidthCharacterWidth / 2));
                    lineVisibleRanges.ranges[0] = new HorizontalRange(left, this._typicalHalfwidthCharacterWidth);
                }
            }
            for (let k = 0, lenK = lineVisibleRanges.ranges.length; k < lenK; k++) {
                const visibleRange = lineVisibleRanges.ranges[k];
                const decorationOutput = ('<div class="cdr '
                    + className
                    + '" style="left:'
                    + String(visibleRange.left)
                    + 'px;width:'
                    + String(visibleRange.width)
                    + 'px;height:'
                    + lineHeight
                    + 'px;"></div>');
                output[lineIndex] += decorationOutput;
            }
        }
    }
    render(startLineNumber, lineNumber) {
        if (!this._renderResult) {
            return '';
        }
        const lineIndex = lineNumber - startLineNumber;
        if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
            return '';
        }
        return this._renderResult[lineIndex];
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/editorScrollbar/editorScrollbar.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class editorScrollbar_EditorScrollbar extends ViewPart {
    constructor(context, linesContent, viewDomNode, overflowGuardDomNode) {
        super(context);
        const options = this._context.configuration.options;
        const scrollbar = options.get(94 /* EditorOption.scrollbar */);
        const mouseWheelScrollSensitivity = options.get(69 /* EditorOption.mouseWheelScrollSensitivity */);
        const fastScrollSensitivity = options.get(36 /* EditorOption.fastScrollSensitivity */);
        const scrollPredominantAxis = options.get(97 /* EditorOption.scrollPredominantAxis */);
        const scrollbarOptions = {
            listenOnDomNode: viewDomNode.domNode,
            className: 'editor-scrollable' + ' ' + getThemeTypeSelector(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: mouseWheelScrollSensitivity,
            fastScrollSensitivity: fastScrollSensitivity,
            scrollPredominantAxis: scrollPredominantAxis,
            scrollByPage: scrollbar.scrollByPage,
        };
        this.scrollbar = this._register(new SmoothScrollableElement(linesContent.domNode, scrollbarOptions, this._context.viewLayout.getScrollable()));
        PartFingerprints.write(this.scrollbar.getDomNode(), 5 /* PartFingerprint.ScrollableElement */);
        this.scrollbarDomNode = createFastDomNode(this.scrollbar.getDomNode());
        this.scrollbarDomNode.setPosition('absolute');
        this._setLayout();
        // When having a zone widget that calls .focus() on one of its dom elements,
        // the browser will try desperately to reveal that dom node, unexpectedly
        // changing the .scrollTop of this.linesContent
        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 */);
        };
        // I've seen this happen both on the view dom node & on the lines content dom node.
        this._register(addDisposableListener(viewDomNode.domNode, 'scroll', (e) => onBrowserDesperateReveal(viewDomNode.domNode, true, true)));
        this._register(addDisposableListener(linesContent.domNode, 'scroll', (e) => onBrowserDesperateReveal(linesContent.domNode, true, false)));
        this._register(addDisposableListener(overflowGuardDomNode.domNode, 'scroll', (e) => onBrowserDesperateReveal(overflowGuardDomNode.domNode, true, false)));
        this._register(addDisposableListener(this.scrollbarDomNode.domNode, 'scroll', (e) => onBrowserDesperateReveal(this.scrollbarDomNode.domNode, true, false)));
    }
    dispose() {
        super.dispose();
    }
    _setLayout() {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this.scrollbarDomNode.setLeft(layoutInfo.contentLeft);
        const minimap = options.get(67 /* EditorOption.minimap */);
        const side = minimap.side;
        if (side === 'right') {
            this.scrollbarDomNode.setWidth(layoutInfo.contentWidth + layoutInfo.minimap.minimapWidth);
        }
        else {
            this.scrollbarDomNode.setWidth(layoutInfo.contentWidth);
        }
        this.scrollbarDomNode.setHeight(layoutInfo.height);
    }
    getOverviewRulerLayoutInfo() {
        return this.scrollbar.getOverviewRulerLayoutInfo();
    }
    getDomNode() {
        return this.scrollbarDomNode;
    }
    delegateVerticalScrollbarPointerDown(browserEvent) {
        this.scrollbar.delegateVerticalScrollbarPointerDown(browserEvent);
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        if (e.hasChanged(94 /* EditorOption.scrollbar */)
            || e.hasChanged(69 /* EditorOption.mouseWheelScrollSensitivity */)
            || e.hasChanged(36 /* EditorOption.fastScrollSensitivity */)) {
            const options = this._context.configuration.options;
            const scrollbar = options.get(94 /* EditorOption.scrollbar */);
            const mouseWheelScrollSensitivity = options.get(69 /* EditorOption.mouseWheelScrollSensitivity */);
            const fastScrollSensitivity = options.get(36 /* EditorOption.fastScrollSensitivity */);
            const scrollPredominantAxis = options.get(97 /* EditorOption.scrollPredominantAxis */);
            const newOpts = {
                vertical: scrollbar.vertical,
                horizontal: scrollbar.horizontal,
                verticalScrollbarSize: scrollbar.verticalScrollbarSize,
                horizontalScrollbarSize: scrollbar.horizontalScrollbarSize,
                scrollByPage: scrollbar.scrollByPage,
                handleMouseWheel: scrollbar.handleMouseWheel,
                mouseWheelScrollSensitivity: mouseWheelScrollSensitivity,
                fastScrollSensitivity: fastScrollSensitivity,
                scrollPredominantAxis: scrollPredominantAxis
            };
            this.scrollbar.updateOptions(newOpts);
        }
        if (e.hasChanged(133 /* EditorOption.layoutInfo */)) {
            this._setLayout();
        }
        return true;
    }
    onScrollChanged(e) {
        return true;
    }
    onThemeChanged(e) {
        this.scrollbar.updateClassName('editor-scrollable' + ' ' + getThemeTypeSelector(this._context.theme.type));
        return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
        // Nothing to do
    }
    render(ctx) {
        this.scrollbar.renderNow();
    }
}
registerThemingParticipant((theme, collector) => {
    // Scrollbars
    const scrollbarShadowColor = theme.getColor(scrollbarShadow);
    if (scrollbarShadowColor) {
        collector.addRule(`
			.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 = theme.getColor(scrollbarSliderBackground);
    if (scrollbarSliderBackgroundColor) {
        collector.addRule(`
			.monaco-scrollable-element > .scrollbar > .slider {
				background: ${scrollbarSliderBackgroundColor};
			}
		`);
    }
    const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground);
    if (scrollbarSliderHoverBackgroundColor) {
        collector.addRule(`
			.monaco-scrollable-element > .scrollbar > .slider:hover {
				background: ${scrollbarSliderHoverBackgroundColor};
			}
		`);
    }
    const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground);
    if (scrollbarSliderActiveBackgroundColor) {
        collector.addRule(`
			.monaco-scrollable-element > .scrollbar > .slider.active {
				background: ${scrollbarSliderActiveBackgroundColor};
			}
		`);
    }
});

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/glyphMargin/glyphMargin.css
var glyphMargin = __webpack_require__(35062);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/glyphMargin/glyphMargin.css

      
      
      
      
      
      
      
      
      

var glyphMargin_options = {};

glyphMargin_options.styleTagTransform = (styleTagTransform_default());
glyphMargin_options.setAttributes = (setAttributesWithoutAttributes_default());

      glyphMargin_options.insert = insertBySelector_default().bind(null, "head");
    
glyphMargin_options.domAPI = (styleDomAPI_default());
glyphMargin_options.insertStyleElement = (insertStyleElement_default());

var glyphMargin_update = injectStylesIntoStyleTag_default()(glyphMargin/* default */.A, glyphMargin_options);




       /* harmony default export */ const glyphMargin_glyphMargin = (glyphMargin/* default */.A && glyphMargin/* default */.A.locals ? glyphMargin/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/glyphMargin/glyphMargin.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class DecorationToRender {
    constructor(startLineNumber, endLineNumber, className) {
        this._decorationToRenderBrand = undefined;
        this.startLineNumber = +startLineNumber;
        this.endLineNumber = +endLineNumber;
        this.className = String(className);
    }
}
class DedupOverlay extends DynamicViewOverlay {
    _render(visibleStartLineNumber, visibleEndLineNumber, decorations) {
        const output = [];
        for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
            const lineIndex = lineNumber - visibleStartLineNumber;
            output[lineIndex] = [];
        }
        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 i = 0, len = decorations.length; i < len; i++) {
            const d = decorations[i];
            const className = d.className;
            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 i = startLineIndex; i <= prevEndLineIndex; i++) {
                output[i].push(prevClassName);
            }
        }
        return output;
    }
}
class GlyphMarginOverlay extends DedupOverlay {
    constructor(context) {
        super();
        this._context = context;
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._glyphMargin = options.get(52 /* EditorOption.glyphMargin */);
        this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
        this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
        this._renderResult = null;
        this._context.addEventHandler(this);
    }
    dispose() {
        this._context.removeEventHandler(this);
        this._renderResult = null;
        super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._glyphMargin = options.get(52 /* EditorOption.glyphMargin */);
        this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
        this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
        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
    _getDecorations(ctx) {
        const decorations = ctx.getDecorationsInViewport();
        const r = [];
        let rLen = 0;
        for (let i = 0, len = decorations.length; i < len; i++) {
            const d = decorations[i];
            const glyphMarginClassName = d.options.glyphMarginClassName;
            if (glyphMarginClassName) {
                r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, glyphMarginClassName);
            }
        }
        return r;
    }
    prepareRender(ctx) {
        if (!this._glyphMargin) {
            this._renderResult = null;
            return;
        }
        const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
        const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
        const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
        const lineHeight = this._lineHeight.toString();
        const left = this._glyphMarginLeft.toString();
        const width = this._glyphMarginWidth.toString();
        const common = '" style="left:' + left + 'px;width:' + width + 'px' + ';height:' + lineHeight + 'px;"></div>';
        const output = [];
        for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
            const lineIndex = lineNumber - visibleStartLineNumber;
            const classNames = toRender[lineIndex];
            if (classNames.length === 0) {
                output[lineIndex] = '';
            }
            else {
                output[lineIndex] = ('<div class="cgmr codicon '
                    + classNames.join(' ')
                    + common);
            }
        }
        this._renderResult = output;
    }
    render(startLineNumber, lineNumber) {
        if (!this._renderResult) {
            return '';
        }
        const lineIndex = lineNumber - startLineNumber;
        if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
            return '';
        }
        return this._renderResult[lineIndex];
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/indentGuides/indentGuides.css
var indentGuides = __webpack_require__(87354);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/indentGuides/indentGuides.css

      
      
      
      
      
      
      
      
      

var indentGuides_options = {};

indentGuides_options.styleTagTransform = (styleTagTransform_default());
indentGuides_options.setAttributes = (setAttributesWithoutAttributes_default());

      indentGuides_options.insert = insertBySelector_default().bind(null, "head");
    
indentGuides_options.domAPI = (styleDomAPI_default());
indentGuides_options.insertStyleElement = (insertStyleElement_default());

var indentGuides_update = injectStylesIntoStyleTag_default()(indentGuides/* default */.A, indentGuides_options);




       /* harmony default export */ const indentGuides_indentGuides = (indentGuides/* default */.A && indentGuides/* default */.A.locals ? indentGuides/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/indentGuides/indentGuides.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









class IndentGuidesOverlay extends DynamicViewOverlay {
    constructor(context) {
        super();
        this._context = context;
        this._primaryPosition = null;
        const options = this._context.configuration.options;
        const wrappingInfo = options.get(134 /* EditorOption.wrappingInfo */);
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._spaceWidth = fontInfo.spaceWidth;
        this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : (wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth);
        this._bracketPairGuideOptions = options.get(13 /* EditorOption.guides */);
        this._renderResult = null;
        this._context.addEventHandler(this);
    }
    dispose() {
        this._context.removeEventHandler(this);
        this._renderResult = null;
        super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        const wrappingInfo = options.get(134 /* EditorOption.wrappingInfo */);
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._spaceWidth = fontInfo.spaceWidth;
        this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : (wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth);
        this._bracketPairGuideOptions = options.get(13 /* EditorOption.guides */);
        return true;
    }
    onCursorStateChanged(e) {
        var _a;
        const selection = e.selections[0];
        const newPosition = selection.getPosition();
        if (!((_a = this._primaryPosition) === null || _a === void 0 ? void 0 : _a.equals(newPosition))) {
            this._primaryPosition = newPosition;
            return true;
        }
        return false;
    }
    onDecorationsChanged(e) {
        // true for inline decorations
        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;
    }
    onLanguageConfigurationChanged(e) {
        return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
        var _a, _b, _c, _d;
        if (!this._bracketPairGuideOptions.indentation && this._bracketPairGuideOptions.bracketPairs === false) {
            this._renderResult = null;
            return;
        }
        const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
        const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
        const scrollWidth = ctx.scrollWidth;
        const lineHeight = this._lineHeight;
        const activeCursorPosition = this._primaryPosition;
        const indents = this.getGuidesByLine(visibleStartLineNumber, visibleEndLineNumber, activeCursorPosition);
        const output = [];
        for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
            const lineIndex = lineNumber - visibleStartLineNumber;
            const indent = indents[lineIndex];
            let result = '';
            const leftOffset = (_b = (_a = ctx.visibleRangeForPosition(new Position(lineNumber, 1))) === null || _a === void 0 ? void 0 : _a.left) !== null && _b !== void 0 ? _b : 0;
            for (const guide of indent) {
                const left = guide.column === -1
                    ? leftOffset + (guide.visibleColumn - 1) * this._spaceWidth
                    : ctx.visibleRangeForPosition(new Position(lineNumber, guide.column)).left;
                if (left > scrollWidth || (this._maxIndentLeft > 0 && left > this._maxIndentLeft)) {
                    break;
                }
                const className = guide.horizontalLine ? (guide.horizontalLine.top ? 'horizontal-top' : 'horizontal-bottom') : 'vertical';
                const width = guide.horizontalLine
                    ? ((_d = (_c = ctx.visibleRangeForPosition(new Position(lineNumber, guide.horizontalLine.endColumn))) === null || _c === void 0 ? void 0 : _c.left) !== null && _d !== void 0 ? _d : (left + this._spaceWidth)) - left
                    : this._spaceWidth;
                result += `<div class="core-guide ${guide.className} ${className}" style="left:${left}px;height:${lineHeight}px;width:${width}px"></div>`;
            }
            output[lineIndex] = result;
        }
        this._renderResult = output;
    }
    getGuidesByLine(visibleStartLineNumber, visibleEndLineNumber, activeCursorPosition) {
        const bracketGuides = this._bracketPairGuideOptions.bracketPairs !== false
            ? this._context.viewModel.getBracketGuidesInRangeByLine(visibleStartLineNumber, visibleEndLineNumber, activeCursorPosition, {
                highlightActive: this._bracketPairGuideOptions.highlightActiveBracketPair,
                horizontalGuides: this._bracketPairGuideOptions.bracketPairsHorizontal === true
                    ? HorizontalGuidesState.Enabled
                    : this._bracketPairGuideOptions.bracketPairsHorizontal === 'active'
                        ? HorizontalGuidesState.EnabledForActive
                        : HorizontalGuidesState.Disabled,
                includeInactive: this._bracketPairGuideOptions.bracketPairs === true,
            })
            : null;
        const indentGuides = this._bracketPairGuideOptions.indentation
            ? this._context.viewModel.getLinesIndentGuides(visibleStartLineNumber, visibleEndLineNumber)
            : null;
        let activeIndentStartLineNumber = 0;
        let activeIndentEndLineNumber = 0;
        let activeIndentLevel = 0;
        if (this._bracketPairGuideOptions.highlightActiveIndentation !== false && activeCursorPosition) {
            const activeIndentInfo = this._context.viewModel.getActiveIndentGuide(activeCursorPosition.lineNumber, visibleStartLineNumber, visibleEndLineNumber);
            activeIndentStartLineNumber = activeIndentInfo.startLineNumber;
            activeIndentEndLineNumber = activeIndentInfo.endLineNumber;
            activeIndentLevel = activeIndentInfo.indent;
        }
        const { indentSize } = this._context.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 ArrayQueue(bracketGuidesInLine);
            const indentGuidesInLine = indentGuides ? indentGuides[lineNumber - visibleStartLineNumber] : [];
            for (let indentLvl = 1; indentLvl <= indentGuidesInLine; indentLvl++) {
                const indentGuide = (indentLvl - 1) * indentSize + 1;
                const isActive = 
                // Disable active indent guide if there are bracket guides.
                (this._bracketPairGuideOptions.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 IndentGuide(indentGuide, -1, isActive ? 'core-guide-indent-active' : 'core-guide-indent', null, -1, -1));
                }
            }
            lineGuides.push(...bracketGuidesInLineQueue.takeWhile(g => true) || []);
        }
        return result;
    }
    render(startLineNumber, lineNumber) {
        if (!this._renderResult) {
            return '';
        }
        const lineIndex = lineNumber - startLineNumber;
        if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
            return '';
        }
        return this._renderResult[lineIndex];
    }
}
function transparentToUndefined(color) {
    if (color && color.isTransparent()) {
        return undefined;
    }
    return color;
}
registerThemingParticipant((theme, collector) => {
    const editorIndentGuidesColor = theme.getColor(editorIndentGuides);
    if (editorIndentGuidesColor) {
        collector.addRule(`.monaco-editor .lines-content .core-guide-indent { box-shadow: 1px 0 0 0 ${editorIndentGuidesColor} inset; }`);
    }
    const editorActiveIndentGuidesColor = theme.getColor(editorActiveIndentGuides) || editorIndentGuidesColor;
    if (editorActiveIndentGuidesColor) {
        collector.addRule(`.monaco-editor .lines-content .core-guide-indent-active { box-shadow: 1px 0 0 0 ${editorActiveIndentGuidesColor} inset; }`);
    }
    const colors = [
        { bracketColor: editorBracketHighlightingForeground1, guideColor: editorBracketPairGuideBackground1, guideColorActive: editorBracketPairGuideActiveBackground1 },
        { bracketColor: editorBracketHighlightingForeground2, guideColor: editorBracketPairGuideBackground2, guideColorActive: editorBracketPairGuideActiveBackground2 },
        { bracketColor: editorBracketHighlightingForeground3, guideColor: editorBracketPairGuideBackground3, guideColorActive: editorBracketPairGuideActiveBackground3 },
        { bracketColor: editorBracketHighlightingForeground4, guideColor: editorBracketPairGuideBackground4, guideColorActive: editorBracketPairGuideActiveBackground4 },
        { bracketColor: editorBracketHighlightingForeground5, guideColor: editorBracketPairGuideBackground5, guideColorActive: editorBracketPairGuideActiveBackground5 },
        { bracketColor: editorBracketHighlightingForeground6, guideColor: editorBracketPairGuideBackground6, guideColorActive: editorBracketPairGuideActiveBackground6 }
    ];
    const colorProvider = new BracketPairGuidesClassNames();
    const colorValues = colors
        .map(c => {
        var _a, _b;
        const bracketColor = theme.getColor(c.bracketColor);
        const guideColor = theme.getColor(c.guideColor);
        const guideColorActive = theme.getColor(c.guideColorActive);
        const effectiveGuideColor = transparentToUndefined((_a = transparentToUndefined(guideColor)) !== null && _a !== void 0 ? _a : bracketColor === null || bracketColor === void 0 ? void 0 : bracketColor.transparent(0.3));
        const effectiveGuideColorActive = transparentToUndefined((_b = transparentToUndefined(guideColorActive)) !== null && _b !== void 0 ? _b : bracketColor);
        if (!effectiveGuideColor || !effectiveGuideColorActive) {
            return undefined;
        }
        return {
            guideColor: effectiveGuideColor,
            guideColorActive: effectiveGuideColorActive,
        };
    })
        .filter(isDefined);
    if (colorValues.length > 0) {
        for (let level = 0; level < 30; level++) {
            const colors = colorValues[level % colorValues.length];
            collector.addRule(`.monaco-editor .${colorProvider.getInlineClassNameOfLevel(level).replace(/ /g, '.')} { --guide-color: ${colors.guideColor}; --guide-color-active: ${colors.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); }`);
    }
});

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/lines/viewLines.css
var viewLines = __webpack_require__(84607);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/lines/viewLines.css

      
      
      
      
      
      
      
      
      

var viewLines_options = {};

viewLines_options.styleTagTransform = (styleTagTransform_default());
viewLines_options.setAttributes = (setAttributesWithoutAttributes_default());

      viewLines_options.insert = insertBySelector_default().bind(null, "head");
    
viewLines_options.domAPI = (styleDomAPI_default());
viewLines_options.insertStyleElement = (insertStyleElement_default());

var viewLines_update = injectStylesIntoStyleTag_default()(viewLines/* default */.A, viewLines_options);




       /* harmony default export */ const lines_viewLines = (viewLines/* default */.A && viewLines/* default */.A.locals ? viewLines/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/lines/viewLines.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/











class LastRenderedData {
    constructor() {
        this._currentVisibleRange = new Range(1, 1, 1, 1);
    }
    getCurrentVisibleRange() {
        return this._currentVisibleRange;
    }
    setCurrentVisibleRange(currentVisibleRange) {
        this._currentVisibleRange = currentVisibleRange;
    }
}
class HorizontalRevealRangeRequest {
    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;
    }
}
class HorizontalRevealSelectionsRequest {
    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 i = 1, len = selections.length; i < len; i++) {
            const selection = selections[i];
            minLineNumber = Math.min(minLineNumber, selection.startLineNumber);
            maxLineNumber = Math.max(maxLineNumber, selection.endLineNumber);
        }
        this.minLineNumber = minLineNumber;
        this.maxLineNumber = maxLineNumber;
    }
}
class ViewLines extends ViewPart {
    constructor(context, linesContent) {
        super(context);
        this._linesContent = linesContent;
        this._textRangeRestingSpot = document.createElement('div');
        this._visibleLines = new VisibleLinesCollection(this);
        this.domNode = this._visibleLines.domNode;
        const conf = this._context.configuration;
        const options = this._context.configuration.options;
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        const wrappingInfo = options.get(134 /* EditorOption.wrappingInfo */);
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
        this._isViewportWrapping = wrappingInfo.isViewportWrapping;
        this._revealHorizontalRightPadding = options.get(91 /* EditorOption.revealHorizontalRightPadding */);
        this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
        this._cursorSurroundingLines = options.get(25 /* EditorOption.cursorSurroundingLines */);
        this._cursorSurroundingLinesStyle = options.get(26 /* EditorOption.cursorSurroundingLinesStyle */);
        this._canUseLayerHinting = !options.get(28 /* EditorOption.disableLayerHinting */);
        this._viewLineOptions = new ViewLineOptions(conf, this._context.theme.type);
        PartFingerprints.write(this.domNode, 7 /* PartFingerprint.ViewLines */);
        this.domNode.setClassName(`view-lines ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
        applyFontInfo(this.domNode, fontInfo);
        // --- width & height
        this._maxLineWidth = 0;
        this._asyncUpdateLineWidths = new RunOnceScheduler(() => {
            this._updateLineWidthsSlow();
        }, 200);
        this._asyncCheckMonospaceFontAssumptions = new RunOnceScheduler(() => {
            this._checkMonospaceFontAssumptions();
        }, 2000);
        this._lastRenderedData = new LastRenderedData();
        this._horizontalRevealRequest = null;
    }
    dispose() {
        this._asyncUpdateLineWidths.dispose();
        this._asyncCheckMonospaceFontAssumptions.dispose();
        super.dispose();
    }
    getDomNode() {
        return this.domNode;
    }
    // ---- begin IVisibleLinesHost
    createVisibleLine() {
        return new ViewLine(this._viewLineOptions);
    }
    // ---- end IVisibleLinesHost
    // ---- begin view event handlers
    onConfigurationChanged(e) {
        this._visibleLines.onConfigurationChanged(e);
        if (e.hasChanged(134 /* EditorOption.wrappingInfo */)) {
            this._maxLineWidth = 0;
        }
        const options = this._context.configuration.options;
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        const wrappingInfo = options.get(134 /* EditorOption.wrappingInfo */);
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
        this._isViewportWrapping = wrappingInfo.isViewportWrapping;
        this._revealHorizontalRightPadding = options.get(91 /* EditorOption.revealHorizontalRightPadding */);
        this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
        this._cursorSurroundingLines = options.get(25 /* EditorOption.cursorSurroundingLines */);
        this._cursorSurroundingLinesStyle = options.get(26 /* EditorOption.cursorSurroundingLinesStyle */);
        this._canUseLayerHinting = !options.get(28 /* EditorOption.disableLayerHinting */);
        applyFontInfo(this.domNode, fontInfo);
        this._onOptionsMaybeChanged();
        if (e.hasChanged(133 /* EditorOption.layoutInfo */)) {
            this._maxLineWidth = 0;
        }
        return true;
    }
    _onOptionsMaybeChanged() {
        const conf = this._context.configuration;
        const newViewLineOptions = new ViewLineOptions(conf, this._context.theme.type);
        if (!this._viewLineOptions.equals(newViewLineOptions)) {
            this._viewLineOptions = newViewLineOptions;
            const startLineNumber = this._visibleLines.getStartLineNumber();
            const endLineNumber = this._visibleLines.getEndLineNumber();
            for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
                const line = this._visibleLines.getVisibleLine(lineNumber);
                line.onOptionsChanged(this._viewLineOptions);
            }
            return true;
        }
        return false;
    }
    onCursorStateChanged(e) {
        const rendStartLineNumber = this._visibleLines.getStartLineNumber();
        const rendEndLineNumber = this._visibleLines.getEndLineNumber();
        let r = false;
        for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
            r = this._visibleLines.getVisibleLine(lineNumber).onSelectionChanged() || r;
        }
        return r;
    }
    onDecorationsChanged(e) {
        if (true /*e.inlineDecorationsChanged*/) {
            const rendStartLineNumber = this._visibleLines.getStartLineNumber();
            const rendEndLineNumber = this._visibleLines.getEndLineNumber();
            for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
                this._visibleLines.getVisibleLine(lineNumber).onDecorationsChanged();
            }
        }
        return true;
    }
    onFlushed(e) {
        const shouldRender = this._visibleLines.onFlushed(e);
        this._maxLineWidth = 0;
        return shouldRender;
    }
    onLinesChanged(e) {
        return this._visibleLines.onLinesChanged(e);
    }
    onLinesDeleted(e) {
        return this._visibleLines.onLinesDeleted(e);
    }
    onLinesInserted(e) {
        return this._visibleLines.onLinesInserted(e);
    }
    onRevealRangeRequest(e) {
        // Using the future viewport here in order to handle multiple
        // incoming reveal range requests that might all desire to be animated
        const desiredScrollTop = this._computeScrollTopToRevealRange(this._context.viewLayout.getFutureViewport(), e.source, e.minimalReveal, e.range, e.selections, e.verticalType);
        if (desiredScrollTop === -1) {
            // marker to abort the reveal range request
            return false;
        }
        // validate the new desired scroll top
        let newScrollPosition = this._context.viewLayout.validateScrollPosition({ scrollTop: desiredScrollTop });
        if (e.revealHorizontal) {
            if (e.range && e.range.startLineNumber !== e.range.endLineNumber) {
                // Two or more lines? => scroll to base (That's how you see most of the two lines)
                newScrollPosition = {
                    scrollTop: newScrollPosition.scrollTop,
                    scrollLeft: 0
                };
            }
            else if (e.range) {
                // We don't necessarily know the horizontal offset of this range since the line might not be in the view...
                this._horizontalRevealRequest = 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._horizontalRevealRequest = new HorizontalRevealSelectionsRequest(e.minimalReveal, e.selections, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e.scrollType);
            }
        }
        else {
            this._horizontalRevealRequest = null;
        }
        const scrollTopDelta = Math.abs(this._context.viewLayout.getCurrentScrollTop() - newScrollPosition.scrollTop);
        const scrollType = (scrollTopDelta <= this._lineHeight ? 1 /* ScrollType.Immediate */ : e.scrollType);
        this._context.viewModel.viewLayout.setScrollPosition(newScrollPosition, scrollType);
        return true;
    }
    onScrollChanged(e) {
        if (this._horizontalRevealRequest && e.scrollLeftChanged) {
            // cancel any outstanding horizontal reveal request if someone else scrolls horizontally.
            this._horizontalRevealRequest = null;
        }
        if (this._horizontalRevealRequest && e.scrollTopChanged) {
            const min = Math.min(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);
            const max = Math.max(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);
            if (e.scrollTop < min || e.scrollTop > max) {
                // cancel any outstanding horizontal reveal request if someone else scrolls vertically.
                this._horizontalRevealRequest = null;
            }
        }
        this.domNode.setWidth(e.scrollWidth);
        return this._visibleLines.onScrollChanged(e) || true;
    }
    onTokensChanged(e) {
        return this._visibleLines.onTokensChanged(e);
    }
    onZonesChanged(e) {
        this._context.viewModel.viewLayout.setMaxLineWidth(this._maxLineWidth);
        return this._visibleLines.onZonesChanged(e);
    }
    onThemeChanged(e) {
        return this._onOptionsMaybeChanged();
    }
    // ---- end view event handlers
    // ----------- HELPERS FOR OTHERS
    getPositionFromDOMInfo(spanNode, offset) {
        const viewLineDomNode = this._getViewLineDomNode(spanNode);
        if (viewLineDomNode === null) {
            // Couldn't find view line node
            return null;
        }
        const lineNumber = this._getLineNumberFor(viewLineDomNode);
        if (lineNumber === -1) {
            // Couldn't find view line node
            return null;
        }
        if (lineNumber < 1 || lineNumber > this._context.viewModel.getLineCount()) {
            // lineNumber is outside range
            return null;
        }
        if (this._context.viewModel.getLineMaxColumn(lineNumber) === 1) {
            // Line is empty
            return new Position(lineNumber, 1);
        }
        const rendStartLineNumber = this._visibleLines.getStartLineNumber();
        const rendEndLineNumber = this._visibleLines.getEndLineNumber();
        if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
            // Couldn't find line
            return null;
        }
        let column = this._visibleLines.getVisibleLine(lineNumber).getColumnOfNodeOffset(lineNumber, spanNode, offset);
        const minColumn = this._context.viewModel.getLineMinColumn(lineNumber);
        if (column < minColumn) {
            column = minColumn;
        }
        return new Position(lineNumber, column);
    }
    _getViewLineDomNode(node) {
        while (node && node.nodeType === 1) {
            if (node.className === ViewLine.CLASS_NAME) {
                return node;
            }
            node = node.parentElement;
        }
        return null;
    }
    /**
     * @returns the line number of this view line dom node.
     */
    _getLineNumberFor(domNode) {
        const startLineNumber = this._visibleLines.getStartLineNumber();
        const endLineNumber = this._visibleLines.getEndLineNumber();
        for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
            const line = this._visibleLines.getVisibleLine(lineNumber);
            if (domNode === line.getDomNode()) {
                return lineNumber;
            }
        }
        return -1;
    }
    getLineWidth(lineNumber) {
        const rendStartLineNumber = this._visibleLines.getStartLineNumber();
        const rendEndLineNumber = this._visibleLines.getEndLineNumber();
        if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
            // Couldn't find line
            return -1;
        }
        return this._visibleLines.getVisibleLine(lineNumber).getWidth();
    }
    linesVisibleRangesForRange(_range, includeNewLines) {
        if (this.shouldRender()) {
            // Cannot read from the DOM because it is dirty
            // i.e. the model & the dom are out of sync, so I'd be reading something stale
            return null;
        }
        const originalEndLineNumber = _range.endLineNumber;
        const range = Range.intersectRanges(_range, this._lastRenderedData.getCurrentVisibleRange());
        if (!range) {
            return null;
        }
        const visibleRanges = [];
        let visibleRangesLen = 0;
        const domReadingContext = new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
        let nextLineModelLineNumber = 0;
        if (includeNewLines) {
            nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position(range.startLineNumber, 1)).lineNumber;
        }
        const rendStartLineNumber = this._visibleLines.getStartLineNumber();
        const rendEndLineNumber = this._visibleLines.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 endColumn = lineNumber === range.endLineNumber ? range.endColumn : this._context.viewModel.getLineMaxColumn(lineNumber);
            const visibleRangesForLine = this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(lineNumber, startColumn, endColumn, domReadingContext);
            if (!visibleRangesForLine) {
                continue;
            }
            if (includeNewLines && lineNumber < originalEndLineNumber) {
                const currentLineModelLineNumber = nextLineModelLineNumber;
                nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position(lineNumber + 1, 1)).lineNumber;
                if (currentLineModelLineNumber !== nextLineModelLineNumber) {
                    visibleRangesForLine.ranges[visibleRangesForLine.ranges.length - 1].width += this._typicalHalfwidthCharacterWidth;
                }
            }
            visibleRanges[visibleRangesLen++] = new LineVisibleRanges(visibleRangesForLine.outsideRenderedLine, lineNumber, HorizontalRange.from(visibleRangesForLine.ranges));
        }
        if (visibleRangesLen === 0) {
            return null;
        }
        return visibleRanges;
    }
    _visibleRangesForLineRange(lineNumber, startColumn, endColumn) {
        if (this.shouldRender()) {
            // Cannot read from the DOM because it is dirty
            // i.e. the model & the dom are out of sync, so I'd be reading something stale
            return null;
        }
        if (lineNumber < this._visibleLines.getStartLineNumber() || lineNumber > this._visibleLines.getEndLineNumber()) {
            return null;
        }
        return this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(lineNumber, startColumn, endColumn, new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot));
    }
    visibleRangeForPosition(position) {
        const visibleRanges = this._visibleRangesForLineRange(position.lineNumber, position.column, position.column);
        if (!visibleRanges) {
            return null;
        }
        return new HorizontalPosition(visibleRanges.outsideRenderedLine, visibleRanges.ranges[0].left);
    }
    // --- implementation
    updateLineWidths() {
        this._updateLineWidths(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).
     */
    _updateLineWidthsFast() {
        return this._updateLineWidths(true);
    }
    _updateLineWidthsSlow() {
        this._updateLineWidths(false);
    }
    _updateLineWidths(fast) {
        const rendStartLineNumber = this._visibleLines.getStartLineNumber();
        const rendEndLineNumber = this._visibleLines.getEndLineNumber();
        let localMaxLineWidth = 1;
        let allWidthsComputed = true;
        for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
            const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
            if (fast && !visibleLine.getWidthIsFast()) {
                // Cannot compute width in a fast way for this line
                allWidthsComputed = false;
                continue;
            }
            localMaxLineWidth = Math.max(localMaxLineWidth, visibleLine.getWidth());
        }
        if (allWidthsComputed && rendStartLineNumber === 1 && rendEndLineNumber === this._context.viewModel.getLineCount()) {
            // we know the max line width for all the lines
            this._maxLineWidth = 0;
        }
        this._ensureMaxLineWidth(localMaxLineWidth);
        return allWidthsComputed;
    }
    _checkMonospaceFontAssumptions() {
        // Problems with monospace assumptions are more apparent for longer lines,
        // as small rounding errors start to sum up, so we will select the longest
        // line for a closer inspection
        let longestLineNumber = -1;
        let longestWidth = -1;
        const rendStartLineNumber = this._visibleLines.getStartLineNumber();
        const rendEndLineNumber = this._visibleLines.getEndLineNumber();
        for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
            const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
            if (visibleLine.needsMonospaceFontCheck()) {
                const lineWidth = visibleLine.getWidth();
                if (lineWidth > longestWidth) {
                    longestWidth = lineWidth;
                    longestLineNumber = lineNumber;
                }
            }
        }
        if (longestLineNumber === -1) {
            return;
        }
        if (!this._visibleLines.getVisibleLine(longestLineNumber).monospaceAssumptionsAreValid()) {
            for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
                const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
                visibleLine.onMonospaceAssumptionsInvalidated();
            }
        }
    }
    prepareRender() {
        throw new Error('Not supported');
    }
    render() {
        throw new Error('Not supported');
    }
    renderText(viewportData) {
        // (1) render lines - ensures lines are in the DOM
        this._visibleLines.renderLines(viewportData);
        this._lastRenderedData.setCurrentVisibleRange(viewportData.visibleRange);
        this.domNode.setWidth(this._context.viewLayout.getScrollWidth());
        this.domNode.setHeight(Math.min(this._context.viewLayout.getScrollHeight(), 1000000));
        // (2) compute horizontal scroll position:
        //  - this must happen after the lines are in the DOM since it might need a line that rendered just now
        //  - it might change `scrollWidth` and `scrollLeft`
        if (this._horizontalRevealRequest) {
            const horizontalRevealRequest = this._horizontalRevealRequest;
            // Check that we have the line that contains the horizontal range in the viewport
            if (viewportData.startLineNumber <= horizontalRevealRequest.minLineNumber && horizontalRevealRequest.maxLineNumber <= viewportData.endLineNumber) {
                this._horizontalRevealRequest = null;
                // allow `visibleRangesForRange2` to work
                this.onDidRender();
                // compute new scroll position
                const newScrollLeft = this._computeScrollLeftToReveal(horizontalRevealRequest);
                if (newScrollLeft) {
                    if (!this._isViewportWrapping) {
                        // ensure `scrollWidth` is large enough
                        this._ensureMaxLineWidth(newScrollLeft.maxHorizontalOffset);
                    }
                    // set `scrollLeft`
                    this._context.viewModel.viewLayout.setScrollPosition({
                        scrollLeft: newScrollLeft.scrollLeft
                    }, horizontalRevealRequest.scrollType);
                }
            }
        }
        // Update max line width (not so important, it is just so the horizontal scrollbar doesn't get too small)
        if (!this._updateLineWidthsFast()) {
            // Computing the width of some lines would be slow => delay it
            this._asyncUpdateLineWidths.schedule();
        }
        if (isLinux && !this._asyncCheckMonospaceFontAssumptions.isScheduled()) {
            const rendStartLineNumber = this._visibleLines.getStartLineNumber();
            const rendEndLineNumber = this._visibleLines.getEndLineNumber();
            for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
                const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
                if (visibleLine.needsMonospaceFontCheck()) {
                    this._asyncCheckMonospaceFontAssumptions.schedule();
                    break;
                }
            }
        }
        // (3) handle scrolling
        this._linesContent.setLayerHinting(this._canUseLayerHinting);
        this._linesContent.setContain('strict');
        const adjustedScrollTop = this._context.viewLayout.getCurrentScrollTop() - viewportData.bigNumbersDelta;
        this._linesContent.setTop(-adjustedScrollTop);
        this._linesContent.setLeft(-this._context.viewLayout.getCurrentScrollLeft());
    }
    // --- width
    _ensureMaxLineWidth(lineWidth) {
        const iLineWidth = Math.ceil(lineWidth);
        if (this._maxLineWidth < iLineWidth) {
            this._maxLineWidth = iLineWidth;
            this._context.viewModel.viewLayout.setMaxLineWidth(this._maxLineWidth);
        }
    }
    _computeScrollTopToRevealRange(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 i = 1, len = selections.length; i < len; i++) {
                const selection = selections[i];
                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._lineHeight;
        }
        else if (range) {
            boxIsSingleRange = true;
            boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(range.startLineNumber);
            boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(range.endLineNumber) + this._lineHeight;
        }
        else {
            return -1;
        }
        const shouldIgnoreScrollOff = (source === 'mouse' || minimalReveal) && this._cursorSurroundingLinesStyle === 'default';
        if (!shouldIgnoreScrollOff) {
            const context = Math.min((viewportHeight / this._lineHeight) / 2, this._cursorSurroundingLines);
            boxStartY -= context * this._lineHeight;
            boxEndY += Math.max(0, (context - 1)) * this._lineHeight;
        }
        else {
            if (!minimalReveal) {
                // Reveal one more line above (this case is hit when dragging)
                boxStartY -= this._lineHeight;
            }
        }
        if (verticalType === 0 /* viewEvents.VerticalRevealType.Simple */ || verticalType === 4 /* viewEvents.VerticalRevealType.Bottom */) {
            // Reveal one line more when the last line would be covered by the scrollbar - arrow down case or revealing a line explicitly at bottom
            boxEndY += (minimalReveal ? this._horizontalScrollbarHeight : this._lineHeight);
        }
        let newScrollTop;
        if (boxEndY - boxStartY > viewportHeight) {
            // the box is larger than the viewport ... scroll to its top
            if (!boxIsSingleRange) {
                // do not reveal multiple cursors if there are more than fit the viewport
                return -1;
            }
            newScrollTop = boxStartY;
        }
        else if (verticalType === 5 /* viewEvents.VerticalRevealType.NearTop */ || verticalType === 6 /* viewEvents.VerticalRevealType.NearTopIfOutsideViewport */) {
            if (verticalType === 6 /* viewEvents.VerticalRevealType.NearTopIfOutsideViewport */ && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
                // Box is already in the viewport... do nothing
                newScrollTop = viewportStartY;
            }
            else {
                // We want a gap that is 20% of the viewport, but with a minimum of 5 lines
                const desiredGapAbove = Math.max(5 * this._lineHeight, viewportHeight * 0.2);
                // Try to scroll just above the box with the desired gap
                const desiredScrollTop = boxStartY - desiredGapAbove;
                // But ensure that the box is not pushed out of viewport
                const minScrollTop = boxEndY - viewportHeight;
                newScrollTop = Math.max(minScrollTop, desiredScrollTop);
            }
        }
        else if (verticalType === 1 /* viewEvents.VerticalRevealType.Center */ || verticalType === 2 /* viewEvents.VerticalRevealType.CenterIfOutsideViewport */) {
            if (verticalType === 2 /* viewEvents.VerticalRevealType.CenterIfOutsideViewport */ && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
                // Box is already in the viewport... do nothing
                newScrollTop = viewportStartY;
            }
            else {
                // Box is outside the viewport... center it
                const boxMiddleY = (boxStartY + boxEndY) / 2;
                newScrollTop = Math.max(0, boxMiddleY - viewportHeight / 2);
            }
        }
        else {
            newScrollTop = this._computeMinimumScrolling(viewportStartY, viewportEndY, boxStartY, boxEndY, verticalType === 3 /* viewEvents.VerticalRevealType.Top */, verticalType === 4 /* viewEvents.VerticalRevealType.Bottom */);
        }
        return newScrollTop;
    }
    _computeScrollLeftToReveal(horizontalRevealRequest) {
        const viewport = this._context.viewLayout.getCurrentViewport();
        const viewportStartX = viewport.left;
        const viewportEndX = viewportStartX + viewport.width;
        let boxStartX = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
        let boxEndX = 0;
        if (horizontalRevealRequest.type === 'range') {
            const visibleRanges = this._visibleRangesForLineRange(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._visibleRangesForLineRange(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 - ViewLines.HORIZONTAL_EXTRA_PX);
            boxEndX += this._revealHorizontalRightPadding;
        }
        if (horizontalRevealRequest.type === 'selections' && boxEndX - boxStartX > viewport.width) {
            return null;
        }
        const newScrollLeft = this._computeMinimumScrolling(viewportStartX, viewportEndX, boxStartX, boxEndX);
        return {
            scrollLeft: newScrollLeft,
            maxHorizontalOffset: boxEndX
        };
    }
    _computeMinimumScrolling(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) {
            // The box would fit in the viewport
            if (revealAtStart) {
                return boxStart;
            }
            if (revealAtEnd) {
                return Math.max(0, boxEnd - viewportLength);
            }
            if (boxStart < viewportStart) {
                // The box is above the viewport
                return boxStart;
            }
            else if (boxEnd > viewportEnd) {
                // The box is below the viewport
                return Math.max(0, boxEnd - viewportLength);
            }
        }
        else {
            // The box would not fit in the viewport
            // Reveal the beginning of the box
            return boxStart;
        }
        return viewportStart;
    }
}
/**
 * Adds this amount of pixels to the right of lines (no-one wants to type near the edge of the viewport)
 */
ViewLines.HORIZONTAL_EXTRA_PX = 30;

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/linesDecorations/linesDecorations.css
var linesDecorations = __webpack_require__(82700);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/linesDecorations/linesDecorations.css

      
      
      
      
      
      
      
      
      

var linesDecorations_options = {};

linesDecorations_options.styleTagTransform = (styleTagTransform_default());
linesDecorations_options.setAttributes = (setAttributesWithoutAttributes_default());

      linesDecorations_options.insert = insertBySelector_default().bind(null, "head");
    
linesDecorations_options.domAPI = (styleDomAPI_default());
linesDecorations_options.insertStyleElement = (insertStyleElement_default());

var linesDecorations_update = injectStylesIntoStyleTag_default()(linesDecorations/* default */.A, linesDecorations_options);




       /* harmony default export */ const linesDecorations_linesDecorations = (linesDecorations/* default */.A && linesDecorations/* default */.A.locals ? linesDecorations/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/linesDecorations/linesDecorations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class LinesDecorationsOverlay extends DedupOverlay {
    constructor(context) {
        super();
        this._context = context;
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._decorationsLeft = layoutInfo.decorationsLeft;
        this._decorationsWidth = layoutInfo.decorationsWidth;
        this._renderResult = null;
        this._context.addEventHandler(this);
    }
    dispose() {
        this._context.removeEventHandler(this);
        this._renderResult = null;
        super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._decorationsLeft = layoutInfo.decorationsLeft;
        this._decorationsWidth = 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
    _getDecorations(ctx) {
        const decorations = ctx.getDecorationsInViewport();
        const r = [];
        let rLen = 0;
        for (let i = 0, len = decorations.length; i < len; i++) {
            const d = decorations[i];
            const linesDecorationsClassName = d.options.linesDecorationsClassName;
            if (linesDecorationsClassName) {
                r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, linesDecorationsClassName);
            }
            const firstLineDecorationClassName = d.options.firstLineDecorationClassName;
            if (firstLineDecorationClassName) {
                r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.startLineNumber, firstLineDecorationClassName);
            }
        }
        return r;
    }
    prepareRender(ctx) {
        const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
        const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
        const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
        const left = this._decorationsLeft.toString();
        const width = this._decorationsWidth.toString();
        const common = '" style="left:' + left + 'px;width:' + width + 'px;"></div>';
        const output = [];
        for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
            const lineIndex = lineNumber - visibleStartLineNumber;
            const classNames = toRender[lineIndex];
            let lineOutput = '';
            for (let i = 0, len = classNames.length; i < len; i++) {
                lineOutput += '<div class="cldr ' + classNames[i] + common;
            }
            output[lineIndex] = lineOutput;
        }
        this._renderResult = output;
    }
    render(startLineNumber, lineNumber) {
        if (!this._renderResult) {
            return '';
        }
        return this._renderResult[lineNumber - startLineNumber];
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/marginDecorations/marginDecorations.css
var marginDecorations = __webpack_require__(28046);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/marginDecorations/marginDecorations.css

      
      
      
      
      
      
      
      
      

var marginDecorations_options = {};

marginDecorations_options.styleTagTransform = (styleTagTransform_default());
marginDecorations_options.setAttributes = (setAttributesWithoutAttributes_default());

      marginDecorations_options.insert = insertBySelector_default().bind(null, "head");
    
marginDecorations_options.domAPI = (styleDomAPI_default());
marginDecorations_options.insertStyleElement = (insertStyleElement_default());

var marginDecorations_update = injectStylesIntoStyleTag_default()(marginDecorations/* default */.A, marginDecorations_options);




       /* harmony default export */ const marginDecorations_marginDecorations = (marginDecorations/* default */.A && marginDecorations/* default */.A.locals ? marginDecorations/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/marginDecorations/marginDecorations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class MarginViewLineDecorationsOverlay extends DedupOverlay {
    constructor(context) {
        super();
        this._context = context;
        this._renderResult = null;
        this._context.addEventHandler(this);
    }
    dispose() {
        this._context.removeEventHandler(this);
        this._renderResult = 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
    _getDecorations(ctx) {
        const decorations = ctx.getDecorationsInViewport();
        const r = [];
        let rLen = 0;
        for (let i = 0, len = decorations.length; i < len; i++) {
            const d = decorations[i];
            const marginClassName = d.options.marginClassName;
            if (marginClassName) {
                r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, marginClassName);
            }
        }
        return r;
    }
    prepareRender(ctx) {
        const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
        const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
        const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
        const output = [];
        for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
            const lineIndex = lineNumber - visibleStartLineNumber;
            const classNames = toRender[lineIndex];
            let lineOutput = '';
            for (let i = 0, len = classNames.length; i < len; i++) {
                lineOutput += '<div class="cmdr ' + classNames[i] + '" style=""></div>';
            }
            output[lineIndex] = lineOutput;
        }
        this._renderResult = output;
    }
    render(startLineNumber, lineNumber) {
        if (!this._renderResult) {
            return '';
        }
        return this._renderResult[lineNumber - startLineNumber];
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/minimap/minimap.css
var minimap = __webpack_require__(87082);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/minimap/minimap.css

      
      
      
      
      
      
      
      
      

var minimap_options = {};

minimap_options.styleTagTransform = (styleTagTransform_default());
minimap_options.setAttributes = (setAttributesWithoutAttributes_default());

      minimap_options.insert = insertBySelector_default().bind(null, "head");
    
minimap_options.domAPI = (styleDomAPI_default());
minimap_options.insertStyleElement = (insertStyleElement_default());

var minimap_update = injectStylesIntoStyleTag_default()(minimap/* default */.A, minimap_options);




       /* harmony default export */ const minimap_minimap = (minimap/* default */.A && minimap/* default */.A.locals ? minimap/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/rgba.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/**
 * A very VM friendly rgba datastructure.
 * Please don't touch unless you take a look at the IR.
 */
class RGBA8 {
    constructor(r, g, b, a) {
        this._rgba8Brand = undefined;
        this.r = RGBA8._clamp(r);
        this.g = RGBA8._clamp(g);
        this.b = RGBA8._clamp(b);
        this.a = RGBA8._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;
    }
}
RGBA8.Empty = new RGBA8(0, 0, 0, 0);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewModel/minimapTokensColorTracker.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class MinimapTokensColorTracker extends Disposable {
    constructor() {
        super();
        this._onDidChange = new Emitter();
        this.onDidChange = this._onDidChange.event;
        this._updateColorMap();
        this._register(languages_TokenizationRegistry.onDidChange(e => {
            if (e.changedColorMap) {
                this._updateColorMap();
            }
        }));
    }
    static getInstance() {
        if (!this._INSTANCE) {
            this._INSTANCE = markAsSingleton(new MinimapTokensColorTracker());
        }
        return this._INSTANCE;
    }
    _updateColorMap() {
        const colorMap = languages_TokenizationRegistry.getColorMap();
        if (!colorMap) {
            this._colors = [RGBA8.Empty];
            this._backgroundIsLight = true;
            return;
        }
        this._colors = [RGBA8.Empty];
        for (let colorId = 1; colorId < colorMap.length; colorId++) {
            const source = colorMap[colorId].rgba;
            // Use a VM friendly data-type
            this._colors[colorId] = new RGBA8(source.r, source.g, source.b, Math.round(source.a * 255));
        }
        const backgroundLuminosity = colorMap[2 /* ColorId.DefaultBackground */].getRelativeLuminance();
        this._backgroundIsLight = backgroundLuminosity >= 0.5;
        this._onDidChange.fire(undefined);
    }
    getColor(colorId) {
        if (colorId < 1 || colorId >= this._colors.length) {
            // background color (basically invisible)
            colorId = 2 /* ColorId.DefaultBackground */;
        }
        return this._colors[colorId];
    }
    backgroundIsLight() {
        return this._backgroundIsLight;
    }
}
MinimapTokensColorTracker._INSTANCE = null;

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class Viewport {
    constructor(top, left, width, height) {
        this._viewportBrand = undefined;
        this.top = top | 0;
        this.left = left | 0;
        this.width = width | 0;
        this.height = height | 0;
    }
}
class MinimapLinesRenderingData {
    constructor(tabSize, data) {
        this.tabSize = tabSize;
        this.data = data;
    }
}
class ViewLineData {
    constructor(content, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations) {
        this._viewLineDataBrand = undefined;
        this.content = content;
        this.continuesWithWrappedLine = continuesWithWrappedLine;
        this.minColumn = minColumn;
        this.maxColumn = maxColumn;
        this.startVisibleColumn = startVisibleColumn;
        this.tokens = tokens;
        this.inlineDecorations = inlineDecorations;
    }
}
class ViewLineRenderingData {
    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 = ViewLineRenderingData.isBasicASCII(content, mightContainNonBasicASCII);
        this.containsRTL = ViewLineRenderingData.containsRTL(content, this.isBasicASCII, mightContainRTL);
        this.tokens = tokens;
        this.inlineDecorations = inlineDecorations;
        this.tabSize = tabSize;
        this.startVisibleColumn = startVisibleColumn;
    }
    static isBasicASCII(lineContent, mightContainNonBasicASCII) {
        if (mightContainNonBasicASCII) {
            return strings_isBasicASCII(lineContent);
        }
        return true;
    }
    static containsRTL(lineContent, isBasicASCII, mightContainRTL) {
        if (!isBasicASCII && mightContainRTL) {
            return strings_containsRTL(lineContent);
        }
        return false;
    }
}
class InlineDecoration {
    constructor(range, inlineClassName, type) {
        this.range = range;
        this.inlineClassName = inlineClassName;
        this.type = type;
    }
}
class SingleLineInlineDecoration {
    constructor(startOffset, endOffset, inlineClassName, inlineClassNameAffectsLetterSpacing) {
        this.startOffset = startOffset;
        this.endOffset = endOffset;
        this.inlineClassName = inlineClassName;
        this.inlineClassNameAffectsLetterSpacing = inlineClassNameAffectsLetterSpacing;
    }
    toInlineDecoration(lineNumber) {
        return new InlineDecoration(new Range(lineNumber, this.startOffset + 1, lineNumber, this.endOffset + 1), this.inlineClassName, this.inlineClassNameAffectsLetterSpacing ? 3 /* InlineDecorationType.RegularAffectingLetterSpacing */ : 0 /* InlineDecorationType.Regular */);
    }
}
class ViewModelDecoration {
    constructor(range, options) {
        this._viewModelDecorationBrand = undefined;
        this.range = range;
        this.options = options;
    }
}
class OverviewRulerDecorationsGroup {
    constructor(color, zIndex, 
    /**
     * Decorations are encoded in a number array using the following scheme:
     *  - 3*i = lane
     *  - 3*i+1 = startLineNumber
     *  - 3*i+2 = endLineNumber
     */
    data) {
        this.color = color;
        this.zIndex = zIndex;
        this.data = data;
    }
    static cmp(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;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/minimap/minimapCharSheet.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
const allCharCodes = (() => {
    const v = [];
    for (let i = 32 /* Constants.START_CH_CODE */; i <= 126 /* Constants.END_CH_CODE */; i++) {
        v.push(i);
    }
    v.push(65533 /* Constants.UNKNOWN_CODE */);
    return v;
})();
const getCharIndex = (chCode, fontScale) => {
    chCode -= 32 /* Constants.START_CH_CODE */;
    if (chCode < 0 || chCode > 96 /* Constants.CHAR_COUNT */) {
        if (fontScale <= 2) {
            // for smaller scales, we can get away with using any ASCII character...
            return (chCode + 96 /* Constants.CHAR_COUNT */) % 96 /* Constants.CHAR_COUNT */;
        }
        return 96 /* Constants.CHAR_COUNT */ - 1; // unknown symbol
    }
    return chCode;
};

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/minimap/minimapCharRenderer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class MinimapCharRenderer {
    constructor(charData, scale) {
        this.scale = scale;
        this._minimapCharRendererBrand = undefined;
        this.charDataNormal = MinimapCharRenderer.soften(charData, 12 / 15);
        this.charDataLight = MinimapCharRenderer.soften(charData, 50 / 60);
    }
    static soften(input, ratio) {
        const result = new Uint8ClampedArray(input.length);
        for (let i = 0, len = input.length; i < len; i++) {
            result[i] = toUint8(input[i] * ratio);
        }
        return result;
    }
    renderChar(target, dx, dy, chCode, color, foregroundAlpha, backgroundColor, backgroundAlpha, fontScale, useLighterFont, force1pxHeight) {
        const charWidth = 1 /* Constants.BASE_CHAR_WIDTH */ * this.scale;
        const charHeight = 2 /* Constants.BASE_CHAR_HEIGHT */ * 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.charDataLight : this.charDataNormal;
        const charIndex = getCharIndex(chCode, fontScale);
        const destWidth = target.width * 4 /* Constants.RGBA_CHANNELS_CNT */;
        const backgroundR = backgroundColor.r;
        const backgroundG = backgroundColor.g;
        const backgroundB = backgroundColor.b;
        const deltaR = color.r - backgroundR;
        const deltaG = color.g - backgroundG;
        const deltaB = color.b - backgroundB;
        const destAlpha = Math.max(foregroundAlpha, backgroundAlpha);
        const dest = target.data;
        let sourceOffset = charIndex * charWidth * charHeight;
        let row = dy * destWidth + dx * 4 /* Constants.RGBA_CHANNELS_CNT */;
        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, color, foregroundAlpha, backgroundColor, backgroundAlpha, force1pxHeight) {
        const charWidth = 1 /* Constants.BASE_CHAR_WIDTH */ * this.scale;
        const charHeight = 2 /* Constants.BASE_CHAR_HEIGHT */ * 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 /* Constants.RGBA_CHANNELS_CNT */;
        const c = 0.5 * (foregroundAlpha / 255);
        const backgroundR = backgroundColor.r;
        const backgroundG = backgroundColor.g;
        const backgroundB = backgroundColor.b;
        const deltaR = color.r - backgroundR;
        const deltaG = color.g - backgroundG;
        const deltaB = color.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 /* Constants.RGBA_CHANNELS_CNT */;
        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;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/minimap/minimapPreBaked.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const 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
};
const decodeData = (str) => {
    const output = new Uint8ClampedArray(str.length / 2);
    for (let i = 0; i < str.length; i += 2) {
        output[i >> 1] = (charTable[str[i]] << 4) | (charTable[str[i + 1]] & 0xF);
    }
    return output;
};
/*
const encodeData = (data: Uint8ClampedArray, length: string) => {
    const chars = '0123456789ABCDEF';
    let output = '';
    for (let i = 0; i < data.length; i++) {
        output += chars[data[i] >> 4] + chars[data[i] & 0xf];
    }
    return output;
};
*/
/**
 * Map of minimap scales to prebaked sample data at those scales. We don't
 * sample much larger data, because then font family becomes visible, which
 * is use-configurable.
 */
const prebakedMiniMaps = {
    1: once(() => decodeData('0000511D6300CF609C709645A78432005642574171487021003C451900274D35D762755E8B629C5BA856AF57BA649530C167D1512A272A3F6038604460398526BCA2A968DB6F8957C768BE5FBE2FB467CF5D8D5B795DC7625B5DFF50DE64C466DB2FC47CD860A65E9A2EB96CB54CE06DA763AB2EA26860524D3763536601005116008177A8705E53AB738E6A982F88BAA35B5F5B626D9C636B449B737E5B7B678598869A662F6B5B8542706C704C80736A607578685B70594A49715A4522E792')),
    2: once(() => decodeData('000000000000000055394F383D2800008B8B1F210002000081B1CBCBCC820000847AAF6B9AAF2119BE08B8881AD60000A44FD07DCCF107015338130C00000000385972265F390B406E2437634B4B48031B12B8A0847000001E15B29A402F0000000000004B33460B00007A752C2A0000000000004D3900000084394B82013400ABA5CFC7AD9C0302A45A3E5A98AB000089A43382D97900008BA54AA087A70A0248A6A7AE6DBE0000BF6F94987EA40A01A06DCFA7A7A9030496C32F77891D0000A99FB1A0AFA80603B29AB9CA75930D010C0948354D3900000C0948354F37460D0028BE673D8400000000AF9D7B6E00002B007AA8933400007AA642675C2700007984CFB9C3985B768772A8A6B7B20000CAAECAAFC4B700009F94A6009F840009D09F9BA4CA9C0000CC8FC76DC87F0000C991C472A2000000A894A48CA7B501079BA2C9C69BA20000B19A5D3FA89000005CA6009DA2960901B0A7F0669FB200009D009E00B7890000DAD0F5D092820000D294D4C48BD10000B5A7A4A3B1A50402CAB6CBA6A2000000B5A7A4A3B1A8044FCDADD19D9CB00000B7778F7B8AAE0803C9AB5D3F5D3F00009EA09EA0BAB006039EA0989A8C7900009B9EF4D6B7C00000A9A7816CACA80000ABAC84705D3F000096DA635CDC8C00006F486F266F263D4784006124097B00374F6D2D6D2D6D4A3A95872322000000030000000000008D8939130000000000002E22A5C9CBC70600AB25C0B5C9B400061A2DB04CA67001082AA6BEBEBFC606002321DACBC19E03087AA08B6768380000282FBAC0B8CA7A88AD25BBA5A29900004C396C5894A6000040485A6E356E9442A32CD17EADA70000B4237923628600003E2DE9C1D7B500002F25BBA5A2990000231DB6AFB4A804023025C0B5CAB588062B2CBDBEC0C706882435A75CA20000002326BD6A82A908048B4B9A5A668000002423A09CB4BB060025259C9D8A7900001C1FCAB2C7C700002A2A9387ABA200002626A4A47D6E9D14333163A0C87500004B6F9C2D643A257049364936493647358A34438355497F1A0000A24C1D590000D38DFFBDD4CD3126'))
};

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/minimap/minimapCharRendererFactory.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




/**
 * Creates character renderers. It takes a 'scale' that determines how large
 * characters should be drawn. Using this, it draws data into a canvas and
 * then downsamples the characters as necessary for the current display.
 * This makes rendering more efficient, rather than drawing a full (tiny)
 * font, or downsampling in real-time.
 */
class MinimapCharRendererFactory {
    /**
     * Creates a new character renderer factory with the given scale.
     */
    static create(scale, fontFamily) {
        // renderers are immutable. By default we'll 'create' a new minimap
        // character renderer whenever we switch editors, no need to do extra work.
        if (this.lastCreated && scale === this.lastCreated.scale && fontFamily === this.lastFontFamily) {
            return this.lastCreated;
        }
        let factory;
        if (prebakedMiniMaps[scale]) {
            factory = new MinimapCharRenderer(prebakedMiniMaps[scale](), scale);
        }
        else {
            factory = MinimapCharRendererFactory.createFromSampleData(MinimapCharRendererFactory.createSampleData(fontFamily).data, scale);
        }
        this.lastFontFamily = fontFamily;
        this.lastCreated = 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 /* Constants.SAMPLED_CHAR_HEIGHT */}px`;
        canvas.height = 16 /* Constants.SAMPLED_CHAR_HEIGHT */;
        canvas.width = 96 /* Constants.CHAR_COUNT */ * 10 /* Constants.SAMPLED_CHAR_WIDTH */;
        canvas.style.width = 96 /* Constants.CHAR_COUNT */ * 10 /* Constants.SAMPLED_CHAR_WIDTH */ + 'px';
        ctx.fillStyle = '#ffffff';
        ctx.font = `bold ${16 /* Constants.SAMPLED_CHAR_HEIGHT */}px ${fontFamily}`;
        ctx.textBaseline = 'middle';
        let x = 0;
        for (const code of allCharCodes) {
            ctx.fillText(String.fromCharCode(code), x, 16 /* Constants.SAMPLED_CHAR_HEIGHT */ / 2);
            x += 10 /* Constants.SAMPLED_CHAR_WIDTH */;
        }
        return ctx.getImageData(0, 0, 96 /* Constants.CHAR_COUNT */ * 10 /* Constants.SAMPLED_CHAR_WIDTH */, 16 /* Constants.SAMPLED_CHAR_HEIGHT */);
    }
    /**
     * Creates a character renderer from the canvas sample data.
     */
    static createFromSampleData(source, scale) {
        const expectedLength = 16 /* Constants.SAMPLED_CHAR_HEIGHT */ * 10 /* Constants.SAMPLED_CHAR_WIDTH */ * 4 /* Constants.RGBA_CHANNELS_CNT */ * 96 /* Constants.CHAR_COUNT */;
        if (source.length !== expectedLength) {
            throw new Error('Unexpected source in MinimapCharRenderer');
        }
        const charData = MinimapCharRendererFactory._downsample(source, scale);
        return new MinimapCharRenderer(charData, scale);
    }
    static _downsampleChar(source, sourceOffset, dest, destOffset, scale) {
        const width = 1 /* Constants.BASE_CHAR_WIDTH */ * scale;
        const height = 2 /* Constants.BASE_CHAR_HEIGHT */ * scale;
        let targetIndex = destOffset;
        let brightest = 0;
        // This is essentially an ad-hoc rescaling algorithm. Standard approaches
        // like bicubic interpolation are awesome for scaling between image sizes,
        // but don't work so well when scaling to very small pixel values, we end
        // up with blurry, indistinct forms.
        //
        // The approach taken here is simply mapping each source pixel to the target
        // pixels, and taking the weighted values for all pixels in each, and then
        // averaging them out. Finally we apply an intensity boost in _downsample,
        // since when scaling to the smallest pixel sizes there's more black space
        // which causes characters to be much less distinct.
        for (let y = 0; y < height; y++) {
            // 1. For this destination pixel, get the source pixels we're sampling
            // from (x1, y1) to the next pixel (x2, y2)
            const sourceY1 = (y / height) * 16 /* Constants.SAMPLED_CHAR_HEIGHT */;
            const sourceY2 = ((y + 1) / height) * 16 /* Constants.SAMPLED_CHAR_HEIGHT */;
            for (let x = 0; x < width; x++) {
                const sourceX1 = (x / width) * 10 /* Constants.SAMPLED_CHAR_WIDTH */;
                const sourceX2 = ((x + 1) / width) * 10 /* Constants.SAMPLED_CHAR_WIDTH */;
                // 2. Sample all of them, summing them up and weighting them. Similar
                // to bilinear interpolation.
                let value = 0;
                let samples = 0;
                for (let sy = sourceY1; sy < sourceY2; sy++) {
                    const sourceRow = sourceOffset + Math.floor(sy) * 3840 /* Constants.RGBA_SAMPLED_ROW_WIDTH */;
                    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 /* Constants.RGBA_CHANNELS_CNT */;
                        const weight = xBalance * yBalance;
                        samples += weight;
                        value += ((source[sourceIndex] * source[sourceIndex + 3]) / 255) * weight;
                    }
                }
                const final = value / samples;
                brightest = Math.max(brightest, final);
                dest[targetIndex++] = toUint8(final);
            }
        }
        return brightest;
    }
    static _downsample(data, scale) {
        const pixelsPerCharacter = 2 /* Constants.BASE_CHAR_HEIGHT */ * scale * 1 /* Constants.BASE_CHAR_WIDTH */ * scale;
        const resultLen = pixelsPerCharacter * 96 /* Constants.CHAR_COUNT */;
        const result = new Uint8ClampedArray(resultLen);
        let resultOffset = 0;
        let sourceOffset = 0;
        let brightest = 0;
        for (let charIndex = 0; charIndex < 96 /* Constants.CHAR_COUNT */; charIndex++) {
            brightest = Math.max(brightest, this._downsampleChar(data, sourceOffset, result, resultOffset, scale));
            resultOffset += pixelsPerCharacter;
            sourceOffset += 10 /* Constants.SAMPLED_CHAR_WIDTH */ * 4 /* Constants.RGBA_CHANNELS_CNT */;
        }
        if (brightest > 0) {
            const adjust = 255 / brightest;
            for (let i = 0; i < resultLen; i++) {
                result[i] *= adjust;
            }
        }
        return result;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/minimap/minimap.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





















/**
 * The orthogonal distance to the slider at which dragging "resets". This implements "snapping"
 */
const minimap_POINTER_DRAG_RESET_DISTANCE = 140;
const GUTTER_DECORATION_WIDTH = 2;
class MinimapOptions {
    constructor(configuration, theme, tokensColorTracker) {
        const options = configuration.options;
        const pixelRatio = options.get(131 /* EditorOption.pixelRatio */);
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        const minimapLayout = layoutInfo.minimap;
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        const minimapOpts = options.get(67 /* EditorOption.minimap */);
        this.renderMinimap = minimapLayout.renderMinimap;
        this.size = minimapOpts.size;
        this.minimapHeightIsEditorHeight = minimapLayout.minimapHeightIsEditorHeight;
        this.scrollBeyondLastLine = options.get(96 /* EditorOption.scrollBeyondLastLine */);
        this.showSlider = minimapOpts.showSlider;
        this.autohide = minimapOpts.autohide;
        this.pixelRatio = pixelRatio;
        this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
        this.lineHeight = options.get(61 /* 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 /* Constants.BASE_CHAR_WIDTH */ * this.fontScale;
        this.charRenderer = once(() => MinimapCharRendererFactory.create(this.fontScale, fontInfo.fontFamily));
        this.defaultBackgroundColor = tokensColorTracker.getColor(2 /* ColorId.DefaultBackground */);
        this.backgroundColor = MinimapOptions._getMinimapBackground(theme, this.defaultBackgroundColor);
        this.foregroundAlpha = MinimapOptions._getMinimapForegroundOpacity(theme);
    }
    static _getMinimapBackground(theme, defaultBackgroundColor) {
        const themeColor = theme.getColor(minimapBackground);
        if (themeColor) {
            return new RGBA8(themeColor.rgba.r, themeColor.rgba.g, themeColor.rgba.b, Math.round(255 * themeColor.rgba.a));
        }
        return defaultBackgroundColor;
    }
    static _getMinimapForegroundOpacity(theme) {
        const themeColor = theme.getColor(minimapForegroundOpacity);
        if (themeColor) {
            return RGBA8._clamp(Math.round(255 * themeColor.rgba.a));
        }
        return 255;
    }
    equals(other) {
        return (this.renderMinimap === other.renderMinimap
            && this.size === other.size
            && this.minimapHeightIsEditorHeight === other.minimapHeightIsEditorHeight
            && this.scrollBeyondLastLine === other.scrollBeyondLastLine
            && 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.defaultBackgroundColor && this.defaultBackgroundColor.equals(other.defaultBackgroundColor)
            && this.backgroundColor && this.backgroundColor.equals(other.backgroundColor)
            && this.foregroundAlpha === other.foregroundAlpha);
    }
}
class MinimapLayout {
    constructor(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber) {
        this.scrollTop = scrollTop;
        this.scrollHeight = scrollHeight;
        this.sliderNeeded = sliderNeeded;
        this._computedSliderRatio = computedSliderRatio;
        this.sliderTop = sliderTop;
        this.sliderHeight = sliderHeight;
        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._computedSliderRatio);
    }
    getDesiredScrollTopFromTouchLocation(pageY) {
        return Math.round((pageY - this.sliderHeight / 2) / this._computedSliderRatio);
    }
    static create(options, viewportStartLineNumber, viewportEndLineNumber, viewportStartLineNumberVerticalOffset, viewportHeight, viewportContainsWhitespaceGaps, lineCount, realLineCount, scrollTop, scrollHeight, previousLayout) {
        const pixelRatio = options.pixelRatio;
        const minimapLineHeight = options.minimapLineHeight;
        const minimapLinesFitting = Math.floor(options.canvasInnerHeight / minimapLineHeight);
        const lineHeight = options.lineHeight;
        if (options.minimapHeightIsEditorHeight) {
            const logicalScrollHeight = (realLineCount * options.lineHeight
                + (options.scrollBeyondLastLine ? viewportHeight - options.lineHeight : 0));
            const sliderHeight = Math.max(1, Math.floor(viewportHeight * viewportHeight / logicalScrollHeight));
            const maxMinimapSliderTop = Math.max(0, options.minimapHeight - sliderHeight);
            // The slider can move from 0 to `maxMinimapSliderTop`
            // in the same way `scrollTop` can move from 0 to `scrollHeight` - `viewportHeight`.
            const computedSliderRatio = (maxMinimapSliderTop) / (scrollHeight - viewportHeight);
            const sliderTop = (scrollTop * computedSliderRatio);
            const sliderNeeded = (maxMinimapSliderTop > 0);
            const maxLinesFitting = Math.floor(options.canvasInnerHeight / options.minimapLineHeight);
            return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, 1, Math.min(lineCount, maxLinesFitting));
        }
        // The visible line count in a viewport can change due to a number of reasons:
        //  a) with the same viewport width, different scroll positions can result in partial lines being visible:
        //    e.g. for a line height of 20, and a viewport height of 600
        //          * scrollTop = 0  => visible lines are [1, 30]
        //          * scrollTop = 10 => visible lines are [1, 31] (with lines 1 and 31 partially visible)
        //          * scrollTop = 20 => visible lines are [2, 31]
        //  b) whitespace gaps might make their way in the viewport (which results in a decrease in the visible line count)
        //  c) we could be in the scroll beyond last line case (which also results in a decrease in the visible line count, down to possibly only one line being visible)
        // We must first establish a desirable slider height.
        let sliderHeight;
        if (viewportContainsWhitespaceGaps && viewportEndLineNumber !== lineCount) {
            // case b) from above: there are whitespace gaps in the viewport.
            // In this case, the height of the slider directly reflects the visible line count.
            const viewportLineCount = viewportEndLineNumber - viewportStartLineNumber + 1;
            sliderHeight = Math.floor(viewportLineCount * minimapLineHeight / pixelRatio);
        }
        else {
            // The slider has a stable height
            const expectedViewportLineCount = viewportHeight / lineHeight;
            sliderHeight = Math.floor(expectedViewportLineCount * minimapLineHeight / pixelRatio);
        }
        let maxMinimapSliderTop;
        if (options.scrollBeyondLastLine) {
            // The minimap slider, when dragged all the way down, will contain the last line at its top
            maxMinimapSliderTop = (lineCount - 1) * minimapLineHeight / pixelRatio;
        }
        else {
            // The minimap slider, when dragged all the way down, will contain the last line at its bottom
            maxMinimapSliderTop = Math.max(0, lineCount * minimapLineHeight / pixelRatio - sliderHeight);
        }
        maxMinimapSliderTop = Math.min(options.minimapHeight - sliderHeight, maxMinimapSliderTop);
        // The slider can move from 0 to `maxMinimapSliderTop`
        // in the same way `scrollTop` can move from 0 to `scrollHeight` - `viewportHeight`.
        const computedSliderRatio = (maxMinimapSliderTop) / (scrollHeight - viewportHeight);
        const sliderTop = (scrollTop * computedSliderRatio);
        let extraLinesAtTheBottom = 0;
        if (options.scrollBeyondLastLine) {
            const expectedViewportLineCount = viewportHeight / lineHeight;
            extraLinesAtTheBottom = expectedViewportLineCount - 1;
        }
        if (minimapLinesFitting >= lineCount + extraLinesAtTheBottom) {
            // All lines fit in the minimap
            const startLineNumber = 1;
            const endLineNumber = lineCount;
            const sliderNeeded = (maxMinimapSliderTop > 0);
            return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, startLineNumber, endLineNumber);
        }
        else {
            let startLineNumber = Math.max(1, Math.floor(viewportStartLineNumber - sliderTop * pixelRatio / minimapLineHeight));
            // Avoid flickering caused by a partial viewport start line
            // by being consistent w.r.t. the previous layout decision
            if (previousLayout && previousLayout.scrollHeight === scrollHeight) {
                if (previousLayout.scrollTop > scrollTop) {
                    // Scrolling up => never increase `startLineNumber`
                    startLineNumber = Math.min(startLineNumber, previousLayout.startLineNumber);
                }
                if (previousLayout.scrollTop < scrollTop) {
                    // Scrolling down => never decrease `startLineNumber`
                    startLineNumber = Math.max(startLineNumber, previousLayout.startLineNumber);
                }
            }
            const endLineNumber = Math.min(lineCount, startLineNumber + minimapLinesFitting - 1);
            const partialLine = (scrollTop - viewportStartLineNumberVerticalOffset) / lineHeight;
            const sliderTopAligned = (viewportStartLineNumber - startLineNumber + partialLine) * minimapLineHeight / pixelRatio;
            return new MinimapLayout(scrollTop, scrollHeight, true, computedSliderRatio, sliderTopAligned, sliderHeight, startLineNumber, endLineNumber);
        }
    }
}
class MinimapLine {
    constructor(dy) {
        this.dy = dy;
    }
    onContentChanged() {
        this.dy = -1;
    }
    onTokensChanged() {
        this.dy = -1;
    }
}
MinimapLine.INVALID = new MinimapLine(-1);
class RenderData {
    constructor(renderedLayout, imageData, lines) {
        this.renderedLayout = renderedLayout;
        this._imageData = imageData;
        this._renderedLines = new RenderedLinesCollection(() => MinimapLine.INVALID);
        this._renderedLines._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._renderedLines._get();
        const lines = tmp.lines;
        for (let i = 0, len = lines.length; i < len; i++) {
            if (lines[i].dy === -1) {
                // This line is invalid
                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._renderedLines._get();
        return {
            imageData: this._imageData,
            rendLineNumberStart: tmp.rendLineNumberStart,
            lines: tmp.lines
        };
    }
    onLinesChanged(changeFromLineNumber, changeCount) {
        return this._renderedLines.onLinesChanged(changeFromLineNumber, changeCount);
    }
    onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
        this._renderedLines.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
    }
    onLinesInserted(insertFromLineNumber, insertToLineNumber) {
        this._renderedLines.onLinesInserted(insertFromLineNumber, insertToLineNumber);
    }
    onTokensChanged(ranges) {
        return this._renderedLines.onTokensChanged(ranges);
    }
}
/**
 * Some sort of double buffering.
 *
 * Keeps two buffers around that will be rotated for painting.
 * Always gives a buffer that is filled with the background color.
 */
class MinimapBuffers {
    constructor(ctx, WIDTH, HEIGHT, background) {
        this._backgroundFillData = MinimapBuffers._createBackgroundFillData(WIDTH, HEIGHT, background);
        this._buffers = [
            ctx.createImageData(WIDTH, HEIGHT),
            ctx.createImageData(WIDTH, HEIGHT)
        ];
        this._lastUsedBuffer = 0;
    }
    getBuffer() {
        // rotate buffers
        this._lastUsedBuffer = 1 - this._lastUsedBuffer;
        const result = this._buffers[this._lastUsedBuffer];
        // fill with background color
        result.data.set(this._backgroundFillData);
        return result;
    }
    static _createBackgroundFillData(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 i = 0; i < HEIGHT; i++) {
            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;
    }
}
class MinimapSamplingState {
    constructor(samplingRatio, minimapLines) {
        this.samplingRatio = samplingRatio;
        this.minimapLines = minimapLines;
    }
    static compute(options, viewLineCount, oldSamplingState) {
        if (options.renderMinimap === 0 /* RenderMinimap.None */ || !options.isSampling) {
            return [null, []];
        }
        // ratio is intentionally not part of the layout to avoid the layout changing all the time
        // so we need to recompute it again...
        const pixelRatio = options.pixelRatio;
        const lineHeight = options.lineHeight;
        const scrollBeyondLastLine = options.scrollBeyondLastLine;
        const { minimapLineCount } = EditorLayoutInfoComputer.computeContainedMinimapLineCount({
            viewLineCount: viewLineCount,
            scrollBeyondLastLine: scrollBeyondLastLine,
            height: options.editorHeight,
            lineHeight: lineHeight,
            pixelRatio: pixelRatio
        });
        const ratio = viewLineCount / minimapLineCount;
        const halfRatio = ratio / 2;
        if (!oldSamplingState || oldSamplingState.minimapLines.length === 0) {
            const result = [];
            result[0] = 1;
            if (minimapLineCount > 1) {
                for (let i = 0, lastIndex = minimapLineCount - 1; i < lastIndex; i++) {
                    result[i] = Math.round(i * ratio + halfRatio);
                }
                result[minimapLineCount - 1] = viewLineCount;
            }
            return [new MinimapSamplingState(ratio, result), []];
        }
        const oldMinimapLines = oldSamplingState.minimapLines;
        const oldLength = oldMinimapLines.length;
        const result = [];
        let oldIndex = 0;
        let oldDeltaLineCount = 0;
        let minViewLineNumber = 1;
        const MAX_EVENT_COUNT = 10; // generate at most 10 events, if there are more than 10 changes, just flush all previous data
        let events = [];
        let lastEvent = null;
        for (let i = 0; i < minimapLineCount; i++) {
            const fromViewLineNumber = Math.max(minViewLineNumber, Math.round(i * ratio));
            const toViewLineNumber = Math.max(fromViewLineNumber, Math.round((i + 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) {
                // reuse the old sampled line
                selectedViewLineNumber = oldMinimapLines[oldIndex];
                oldIndex++;
            }
            else {
                if (i === 0) {
                    selectedViewLineNumber = 1;
                }
                else if (i + 1 === minimapLineCount) {
                    selectedViewLineNumber = viewLineCount;
                }
                else {
                    selectedViewLineNumber = Math.round(i * ratio + halfRatio);
                }
                if (events.length < MAX_EVENT_COUNT) {
                    const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
                    if (lastEvent && lastEvent.type === 'inserted' && lastEvent._i === i - 1) {
                        lastEvent.insertToLineNumber++;
                    }
                    else {
                        lastEvent = { type: 'inserted', _i: i, insertFromLineNumber: oldMinimapLineNumber, insertToLineNumber: oldMinimapLineNumber };
                        events.push(lastEvent);
                    }
                    oldDeltaLineCount++;
                }
            }
            result[i] = 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 {
            // too many events, just give up
            events = [{ type: 'flush' }];
        }
        return [new MinimapSamplingState(ratio, result), events];
    }
    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 toLineIndex = this.modelLineToMinimapLine(toLineNumber) - 1;
        while (toLineIndex + 1 < this.minimapLines.length && this.minimapLines[toLineIndex + 1] <= toLineNumber) {
            toLineIndex++;
        }
        if (fromLineIndex === toLineIndex) {
            const sampledLineNumber = this.minimapLines[fromLineIndex];
            if (sampledLineNumber < fromLineNumber || sampledLineNumber > toLineNumber) {
                // This line is not part of the sampled lines ==> nothing to do
                return null;
            }
        }
        return [fromLineIndex + 1, toLineIndex + 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) {
        // have the mapping be sticky
        const deletedLineCount = e.toLineNumber - e.fromLineNumber + 1;
        let changeStartIndex = this.minimapLines.length;
        let changeEndIndex = 0;
        for (let i = this.minimapLines.length - 1; i >= 0; i--) {
            if (this.minimapLines[i] < e.fromLineNumber) {
                break;
            }
            if (this.minimapLines[i] <= e.toLineNumber) {
                // this line got deleted => move to previous available
                this.minimapLines[i] = Math.max(1, e.fromLineNumber - 1);
                changeStartIndex = Math.min(changeStartIndex, i);
                changeEndIndex = Math.max(changeEndIndex, i);
            }
            else {
                this.minimapLines[i] -= deletedLineCount;
            }
        }
        return [changeStartIndex, changeEndIndex];
    }
    onLinesInserted(e) {
        // have the mapping be sticky
        const insertedLineCount = e.toLineNumber - e.fromLineNumber + 1;
        for (let i = this.minimapLines.length - 1; i >= 0; i--) {
            if (this.minimapLines[i] < e.fromLineNumber) {
                break;
            }
            this.minimapLines[i] += insertedLineCount;
        }
    }
}
class Minimap extends ViewPart {
    constructor(context) {
        super(context);
        this.tokensColorTracker = MinimapTokensColorTracker.getInstance();
        this._selections = [];
        this._minimapSelections = 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._samplingState = samplingState;
        this._shouldCheckSampling = false;
        this._actual = new InnerMinimap(context.theme, this);
    }
    dispose() {
        this._actual.dispose();
        super.dispose();
    }
    getDomNode() {
        return this._actual.getDomNode();
    }
    _onOptionsMaybeChanged() {
        const opts = new MinimapOptions(this._context.configuration, this._context.theme, this.tokensColorTracker);
        if (this.options.equals(opts)) {
            return false;
        }
        this.options = opts;
        this._recreateLineSampling();
        this._actual.onDidChangeOptions();
        return true;
    }
    // ---- begin view event handlers
    onConfigurationChanged(e) {
        return this._onOptionsMaybeChanged();
    }
    onCursorStateChanged(e) {
        this._selections = e.selections;
        this._minimapSelections = null;
        return this._actual.onSelectionChanged();
    }
    onDecorationsChanged(e) {
        if (e.affectsMinimap) {
            return this._actual.onDecorationsChanged();
        }
        return false;
    }
    onFlushed(e) {
        if (this._samplingState) {
            this._shouldCheckSampling = true;
        }
        return this._actual.onFlushed();
    }
    onLinesChanged(e) {
        if (this._samplingState) {
            const minimapLineRange = this._samplingState.modelLineRangeToMinimapLineRange(e.fromLineNumber, e.fromLineNumber + e.count - 1);
            if (minimapLineRange) {
                return this._actual.onLinesChanged(minimapLineRange[0], minimapLineRange[1] - minimapLineRange[0] + 1);
            }
            else {
                return false;
            }
        }
        else {
            return this._actual.onLinesChanged(e.fromLineNumber, e.count);
        }
    }
    onLinesDeleted(e) {
        if (this._samplingState) {
            const [changeStartIndex, changeEndIndex] = this._samplingState.onLinesDeleted(e);
            if (changeStartIndex <= changeEndIndex) {
                this._actual.onLinesChanged(changeStartIndex + 1, changeEndIndex - changeStartIndex + 1);
            }
            this._shouldCheckSampling = true;
            return true;
        }
        else {
            return this._actual.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
        }
    }
    onLinesInserted(e) {
        if (this._samplingState) {
            this._samplingState.onLinesInserted(e);
            this._shouldCheckSampling = true;
            return true;
        }
        else {
            return this._actual.onLinesInserted(e.fromLineNumber, e.toLineNumber);
        }
    }
    onScrollChanged(e) {
        return this._actual.onScrollChanged();
    }
    onThemeChanged(e) {
        this._actual.onThemeChanged();
        this._onOptionsMaybeChanged();
        return true;
    }
    onTokensChanged(e) {
        if (this._samplingState) {
            const ranges = [];
            for (const range of e.ranges) {
                const minimapLineRange = this._samplingState.modelLineRangeToMinimapLineRange(range.fromLineNumber, range.toLineNumber);
                if (minimapLineRange) {
                    ranges.push({ fromLineNumber: minimapLineRange[0], toLineNumber: minimapLineRange[1] });
                }
            }
            if (ranges.length) {
                return this._actual.onTokensChanged(ranges);
            }
            else {
                return false;
            }
        }
        else {
            return this._actual.onTokensChanged(e.ranges);
        }
    }
    onTokensColorsChanged(e) {
        this._onOptionsMaybeChanged();
        return this._actual.onTokensColorsChanged();
    }
    onZonesChanged(e) {
        return this._actual.onZonesChanged();
    }
    // --- end event handlers
    prepareRender(ctx) {
        if (this._shouldCheckSampling) {
            this._shouldCheckSampling = false;
            this._recreateLineSampling();
        }
    }
    render(ctx) {
        let viewportStartLineNumber = ctx.visibleRange.startLineNumber;
        let viewportEndLineNumber = ctx.visibleRange.endLineNumber;
        if (this._samplingState) {
            viewportStartLineNumber = this._samplingState.modelLineToMinimapLine(viewportStartLineNumber);
            viewportEndLineNumber = this._samplingState.modelLineToMinimapLine(viewportEndLineNumber);
        }
        const minimapCtx = {
            viewportContainsWhitespaceGaps: (ctx.viewportData.whitespaceViewportData.length > 0),
            scrollWidth: ctx.scrollWidth,
            scrollHeight: ctx.scrollHeight,
            viewportStartLineNumber: viewportStartLineNumber,
            viewportEndLineNumber: viewportEndLineNumber,
            viewportStartLineNumberVerticalOffset: ctx.getVerticalOffsetForLineNumber(viewportStartLineNumber),
            scrollTop: ctx.scrollTop,
            scrollLeft: ctx.scrollLeft,
            viewportWidth: ctx.viewportWidth,
            viewportHeight: ctx.viewportHeight,
        };
        this._actual.render(minimapCtx);
    }
    //#region IMinimapModel
    _recreateLineSampling() {
        this._minimapSelections = null;
        const wasSampling = Boolean(this._samplingState);
        const [samplingState, events] = MinimapSamplingState.compute(this.options, this._context.viewModel.getLineCount(), this._samplingState);
        this._samplingState = samplingState;
        if (wasSampling && this._samplingState) {
            // was sampling, is sampling
            for (const event of events) {
                switch (event.type) {
                    case 'deleted':
                        this._actual.onLinesDeleted(event.deleteFromLineNumber, event.deleteToLineNumber);
                        break;
                    case 'inserted':
                        this._actual.onLinesInserted(event.insertFromLineNumber, event.insertToLineNumber);
                        break;
                    case 'flush':
                        this._actual.onFlushed();
                        break;
                }
            }
        }
    }
    getLineCount() {
        if (this._samplingState) {
            return this._samplingState.minimapLines.length;
        }
        return this._context.viewModel.getLineCount();
    }
    getRealLineCount() {
        return this._context.viewModel.getLineCount();
    }
    getLineContent(lineNumber) {
        if (this._samplingState) {
            return this._context.viewModel.getLineContent(this._samplingState.minimapLines[lineNumber - 1]);
        }
        return this._context.viewModel.getLineContent(lineNumber);
    }
    getLineMaxColumn(lineNumber) {
        if (this._samplingState) {
            return this._context.viewModel.getLineMaxColumn(this._samplingState.minimapLines[lineNumber - 1]);
        }
        return this._context.viewModel.getLineMaxColumn(lineNumber);
    }
    getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
        if (this._samplingState) {
            const result = [];
            for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
                if (needed[lineIndex]) {
                    result[lineIndex] = this._context.viewModel.getViewLineData(this._samplingState.minimapLines[startLineNumber + lineIndex - 1]);
                }
                else {
                    result[lineIndex] = null;
                }
            }
            return result;
        }
        return this._context.viewModel.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed).data;
    }
    getSelections() {
        if (this._minimapSelections === null) {
            if (this._samplingState) {
                this._minimapSelections = [];
                for (const selection of this._selections) {
                    const [minimapLineStart, minimapLineEnd] = this._samplingState.decorationLineRangeToMinimapLineRange(selection.startLineNumber, selection.endLineNumber);
                    this._minimapSelections.push(new Selection(minimapLineStart, selection.startColumn, minimapLineEnd, selection.endColumn));
                }
            }
            else {
                this._minimapSelections = this._selections;
            }
        }
        return this._minimapSelections;
    }
    getMinimapDecorationsInViewport(startLineNumber, endLineNumber) {
        let visibleRange;
        if (this._samplingState) {
            const modelStartLineNumber = this._samplingState.minimapLines[startLineNumber - 1];
            const modelEndLineNumber = this._samplingState.minimapLines[endLineNumber - 1];
            visibleRange = new Range(modelStartLineNumber, 1, modelEndLineNumber, this._context.viewModel.getLineMaxColumn(modelEndLineNumber));
        }
        else {
            visibleRange = new Range(startLineNumber, 1, endLineNumber, this._context.viewModel.getLineMaxColumn(endLineNumber));
        }
        const decorations = this._context.viewModel.getDecorationsInViewport(visibleRange);
        if (this._samplingState) {
            const result = [];
            for (const decoration of decorations) {
                if (!decoration.options.minimap) {
                    continue;
                }
                const range = decoration.range;
                const minimapStartLineNumber = this._samplingState.modelLineToMinimapLine(range.startLineNumber);
                const minimapEndLineNumber = this._samplingState.modelLineToMinimapLine(range.endLineNumber);
                result.push(new ViewModelDecoration(new Range(minimapStartLineNumber, range.startColumn, minimapEndLineNumber, range.endColumn), decoration.options));
            }
            return result;
        }
        return decorations;
    }
    getOptions() {
        return this._context.viewModel.model.getOptions();
    }
    revealLineNumber(lineNumber) {
        if (this._samplingState) {
            lineNumber = this._samplingState.minimapLines[lineNumber - 1];
        }
        this._context.viewModel.revealRange('mouse', false, new Range(lineNumber, 1, lineNumber, 1), 1 /* viewEvents.VerticalRevealType.Center */, 0 /* ScrollType.Smooth */);
    }
    setScrollTop(scrollTop) {
        this._context.viewModel.viewLayout.setScrollPosition({
            scrollTop: scrollTop
        }, 1 /* ScrollType.Immediate */);
    }
}
class InnerMinimap extends Disposable {
    constructor(theme, model) {
        super();
        this._renderDecorations = false;
        this._gestureInProgress = false;
        this._theme = theme;
        this._model = model;
        this._lastRenderData = null;
        this._buffers = null;
        this._selectionColor = this._theme.getColor(minimapSelection);
        this._domNode = createFastDomNode(document.createElement('div'));
        PartFingerprints.write(this._domNode, 8 /* PartFingerprint.Minimap */);
        this._domNode.setClassName(this._getMinimapDomNodeClassName());
        this._domNode.setPosition('absolute');
        this._domNode.setAttribute('role', 'presentation');
        this._domNode.setAttribute('aria-hidden', 'true');
        this._shadow = createFastDomNode(document.createElement('div'));
        this._shadow.setClassName('minimap-shadow-hidden');
        this._domNode.appendChild(this._shadow);
        this._canvas = createFastDomNode(document.createElement('canvas'));
        this._canvas.setPosition('absolute');
        this._canvas.setLeft(0);
        this._domNode.appendChild(this._canvas);
        this._decorationsCanvas = createFastDomNode(document.createElement('canvas'));
        this._decorationsCanvas.setPosition('absolute');
        this._decorationsCanvas.setClassName('minimap-decorations-layer');
        this._decorationsCanvas.setLeft(0);
        this._domNode.appendChild(this._decorationsCanvas);
        this._slider = createFastDomNode(document.createElement('div'));
        this._slider.setPosition('absolute');
        this._slider.setClassName('minimap-slider');
        this._slider.setLayerHinting(true);
        this._slider.setContain('strict');
        this._domNode.appendChild(this._slider);
        this._sliderHorizontal = createFastDomNode(document.createElement('div'));
        this._sliderHorizontal.setPosition('absolute');
        this._sliderHorizontal.setClassName('minimap-slider-horizontal');
        this._slider.appendChild(this._sliderHorizontal);
        this._applyLayout();
        this._pointerDownListener = addStandardDisposableListener(this._domNode.domNode, EventType.POINTER_DOWN, (e) => {
            e.preventDefault();
            const renderMinimap = this._model.options.renderMinimap;
            if (renderMinimap === 0 /* RenderMinimap.None */) {
                return;
            }
            if (!this._lastRenderData) {
                return;
            }
            if (this._model.options.size !== 'proportional') {
                if (e.button === 0 && this._lastRenderData) {
                    // pretend the click occurred in the center of the slider
                    const position = getDomNodePagePosition(this._slider.domNode);
                    const initialPosY = position.top + position.height / 2;
                    this._startSliderDragging(e, initialPosY, this._lastRenderData.renderedLayout);
                }
                return;
            }
            const minimapLineHeight = this._model.options.minimapLineHeight;
            const internalOffsetY = (this._model.options.canvasInnerHeight / this._model.options.canvasOuterHeight) * e.offsetY;
            const lineIndex = Math.floor(internalOffsetY / minimapLineHeight);
            let lineNumber = lineIndex + this._lastRenderData.renderedLayout.startLineNumber;
            lineNumber = Math.min(lineNumber, this._model.getLineCount());
            this._model.revealLineNumber(lineNumber);
        });
        this._sliderPointerMoveMonitor = new GlobalPointerMoveMonitor();
        this._sliderPointerDownListener = addStandardDisposableListener(this._slider.domNode, EventType.POINTER_DOWN, (e) => {
            e.preventDefault();
            e.stopPropagation();
            if (e.button === 0 && this._lastRenderData) {
                this._startSliderDragging(e, e.pageY, this._lastRenderData.renderedLayout);
            }
        });
        this._gestureDisposable = Gesture.addTarget(this._domNode.domNode);
        this._sliderTouchStartListener = addDisposableListener(this._domNode.domNode, touch_EventType.Start, (e) => {
            e.preventDefault();
            e.stopPropagation();
            if (this._lastRenderData) {
                this._slider.toggleClassName('active', true);
                this._gestureInProgress = true;
                this.scrollDueToTouchEvent(e);
            }
        }, { passive: false });
        this._sliderTouchMoveListener = addDisposableListener(this._domNode.domNode, touch_EventType.Change, (e) => {
            e.preventDefault();
            e.stopPropagation();
            if (this._lastRenderData && this._gestureInProgress) {
                this.scrollDueToTouchEvent(e);
            }
        }, { passive: false });
        this._sliderTouchEndListener = addStandardDisposableListener(this._domNode.domNode, touch_EventType.End, (e) => {
            e.preventDefault();
            e.stopPropagation();
            this._gestureInProgress = false;
            this._slider.toggleClassName('active', false);
        });
    }
    _startSliderDragging(e, initialPosY, initialSliderState) {
        if (!e.target || !(e.target instanceof Element)) {
            return;
        }
        const initialPosX = e.pageX;
        this._slider.toggleClassName('active', true);
        const handlePointerMove = (posy, posx) => {
            const pointerOrthogonalDelta = Math.abs(posx - initialPosX);
            if (isWindows && pointerOrthogonalDelta > minimap_POINTER_DRAG_RESET_DISTANCE) {
                // The pointer has wondered away from the scrollbar => reset dragging
                this._model.setScrollTop(initialSliderState.scrollTop);
                return;
            }
            const pointerDelta = posy - initialPosY;
            this._model.setScrollTop(initialSliderState.getDesiredScrollTopFromDelta(pointerDelta));
        };
        if (e.pageY !== initialPosY) {
            handlePointerMove(e.pageY, initialPosX);
        }
        this._sliderPointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, pointerMoveData => handlePointerMove(pointerMoveData.pageY, pointerMoveData.pageX), () => {
            this._slider.toggleClassName('active', false);
        });
    }
    scrollDueToTouchEvent(touch) {
        const startY = this._domNode.domNode.getBoundingClientRect().top;
        const scrollTop = this._lastRenderData.renderedLayout.getDesiredScrollTopFromTouchLocation(touch.pageY - startY);
        this._model.setScrollTop(scrollTop);
    }
    dispose() {
        this._pointerDownListener.dispose();
        this._sliderPointerMoveMonitor.dispose();
        this._sliderPointerDownListener.dispose();
        this._gestureDisposable.dispose();
        this._sliderTouchStartListener.dispose();
        this._sliderTouchMoveListener.dispose();
        this._sliderTouchEndListener.dispose();
        super.dispose();
    }
    _getMinimapDomNodeClassName() {
        const class_ = ['minimap'];
        if (this._model.options.showSlider === 'always') {
            class_.push('slider-always');
        }
        else {
            class_.push('slider-mouseover');
        }
        if (this._model.options.autohide) {
            class_.push('autohide');
        }
        return class_.join(' ');
    }
    getDomNode() {
        return this._domNode;
    }
    _applyLayout() {
        this._domNode.setLeft(this._model.options.minimapLeft);
        this._domNode.setWidth(this._model.options.minimapWidth);
        this._domNode.setHeight(this._model.options.minimapHeight);
        this._shadow.setHeight(this._model.options.minimapHeight);
        this._canvas.setWidth(this._model.options.canvasOuterWidth);
        this._canvas.setHeight(this._model.options.canvasOuterHeight);
        this._canvas.domNode.width = this._model.options.canvasInnerWidth;
        this._canvas.domNode.height = this._model.options.canvasInnerHeight;
        this._decorationsCanvas.setWidth(this._model.options.canvasOuterWidth);
        this._decorationsCanvas.setHeight(this._model.options.canvasOuterHeight);
        this._decorationsCanvas.domNode.width = this._model.options.canvasInnerWidth;
        this._decorationsCanvas.domNode.height = this._model.options.canvasInnerHeight;
        this._slider.setWidth(this._model.options.minimapWidth);
    }
    _getBuffer() {
        if (!this._buffers) {
            if (this._model.options.canvasInnerWidth > 0 && this._model.options.canvasInnerHeight > 0) {
                this._buffers = new MinimapBuffers(this._canvas.domNode.getContext('2d'), this._model.options.canvasInnerWidth, this._model.options.canvasInnerHeight, this._model.options.backgroundColor);
            }
        }
        return this._buffers ? this._buffers.getBuffer() : null;
    }
    // ---- begin view event handlers
    onDidChangeOptions() {
        this._lastRenderData = null;
        this._buffers = null;
        this._applyLayout();
        this._domNode.setClassName(this._getMinimapDomNodeClassName());
    }
    onSelectionChanged() {
        this._renderDecorations = true;
        return true;
    }
    onDecorationsChanged() {
        this._renderDecorations = true;
        return true;
    }
    onFlushed() {
        this._lastRenderData = null;
        return true;
    }
    onLinesChanged(changeFromLineNumber, changeCount) {
        if (this._lastRenderData) {
            return this._lastRenderData.onLinesChanged(changeFromLineNumber, changeCount);
        }
        return false;
    }
    onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
        var _a;
        (_a = this._lastRenderData) === null || _a === void 0 ? void 0 : _a.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
        return true;
    }
    onLinesInserted(insertFromLineNumber, insertToLineNumber) {
        var _a;
        (_a = this._lastRenderData) === null || _a === void 0 ? void 0 : _a.onLinesInserted(insertFromLineNumber, insertToLineNumber);
        return true;
    }
    onScrollChanged() {
        this._renderDecorations = true;
        return true;
    }
    onThemeChanged() {
        this._selectionColor = this._theme.getColor(minimapSelection);
        this._renderDecorations = true;
        return true;
    }
    onTokensChanged(ranges) {
        if (this._lastRenderData) {
            return this._lastRenderData.onTokensChanged(ranges);
        }
        return false;
    }
    onTokensColorsChanged() {
        this._lastRenderData = null;
        this._buffers = null;
        return true;
    }
    onZonesChanged() {
        this._lastRenderData = null;
        return true;
    }
    // --- end event handlers
    render(renderingCtx) {
        const renderMinimap = this._model.options.renderMinimap;
        if (renderMinimap === 0 /* RenderMinimap.None */) {
            this._shadow.setClassName('minimap-shadow-hidden');
            this._sliderHorizontal.setWidth(0);
            this._sliderHorizontal.setHeight(0);
            return;
        }
        if (renderingCtx.scrollLeft + renderingCtx.viewportWidth >= renderingCtx.scrollWidth) {
            this._shadow.setClassName('minimap-shadow-hidden');
        }
        else {
            this._shadow.setClassName('minimap-shadow-visible');
        }
        const layout = MinimapLayout.create(this._model.options, renderingCtx.viewportStartLineNumber, renderingCtx.viewportEndLineNumber, renderingCtx.viewportStartLineNumberVerticalOffset, renderingCtx.viewportHeight, renderingCtx.viewportContainsWhitespaceGaps, this._model.getLineCount(), this._model.getRealLineCount(), renderingCtx.scrollTop, renderingCtx.scrollHeight, this._lastRenderData ? this._lastRenderData.renderedLayout : null);
        this._slider.setDisplay(layout.sliderNeeded ? 'block' : 'none');
        this._slider.setTop(layout.sliderTop);
        this._slider.setHeight(layout.sliderHeight);
        // Compute horizontal slider coordinates
        this._sliderHorizontal.setLeft(0);
        this._sliderHorizontal.setWidth(this._model.options.minimapWidth);
        this._sliderHorizontal.setTop(0);
        this._sliderHorizontal.setHeight(layout.sliderHeight);
        this.renderDecorations(layout);
        this._lastRenderData = this.renderLines(layout);
    }
    renderDecorations(layout) {
        if (this._renderDecorations) {
            this._renderDecorations = false;
            const selections = this._model.getSelections();
            selections.sort(Range.compareRangesUsingStarts);
            const decorations = this._model.getMinimapDecorationsInViewport(layout.startLineNumber, layout.endLineNumber);
            decorations.sort((a, b) => (a.options.zIndex || 0) - (b.options.zIndex || 0));
            const { canvasInnerWidth, canvasInnerHeight } = this._model.options;
            const lineHeight = this._model.options.minimapLineHeight;
            const characterWidth = this._model.options.minimapCharWidth;
            const tabSize = this._model.getOptions().tabSize;
            const canvasContext = this._decorationsCanvas.domNode.getContext('2d');
            canvasContext.clearRect(0, 0, canvasInnerWidth, canvasInnerHeight);
            // We first need to render line highlights and then render decorations on top of those.
            // But we need to pick a single color for each line, and use that as a line highlight.
            // This needs to be the color of the decoration with the highest `zIndex`, but priority
            // is given to the selection.
            const highlightedLines = new ContiguousLineMap(layout.startLineNumber, layout.endLineNumber, false);
            this._renderSelectionLineHighlights(canvasContext, selections, highlightedLines, layout, lineHeight);
            this._renderDecorationsLineHighlights(canvasContext, decorations, highlightedLines, layout, lineHeight);
            const lineOffsetMap = new ContiguousLineMap(layout.startLineNumber, layout.endLineNumber, null);
            this._renderSelectionsHighlights(canvasContext, selections, lineOffsetMap, layout, lineHeight, tabSize, characterWidth, canvasInnerWidth);
            this._renderDecorationsHighlights(canvasContext, decorations, lineOffsetMap, layout, lineHeight, tabSize, characterWidth, canvasInnerWidth);
        }
    }
    _renderSelectionLineHighlights(canvasContext, selections, highlightedLines, layout, lineHeight) {
        if (!this._selectionColor || this._selectionColor.isTransparent()) {
            return;
        }
        canvasContext.fillStyle = this._selectionColor.transparent(0.5).toString();
        let y1 = 0;
        let y2 = 0;
        for (const selection of selections) {
            const startLineNumber = Math.max(layout.startLineNumber, selection.startLineNumber);
            const endLineNumber = Math.min(layout.endLineNumber, selection.endLineNumber);
            if (startLineNumber > endLineNumber) {
                // entirely outside minimap's viewport
                continue;
            }
            for (let line = startLineNumber; line <= endLineNumber; line++) {
                highlightedLines.set(line, true);
            }
            const yy1 = (startLineNumber - layout.startLineNumber) * lineHeight;
            const yy2 = (endLineNumber - layout.startLineNumber) * lineHeight + lineHeight;
            if (y2 >= yy1) {
                // merge into previous
                y2 = yy2;
            }
            else {
                if (y2 > y1) {
                    // flush
                    canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y1, canvasContext.canvas.width, y2 - y1);
                }
                y1 = yy1;
                y2 = yy2;
            }
        }
        if (y2 > y1) {
            // flush
            canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y1, canvasContext.canvas.width, y2 - y1);
        }
    }
    _renderDecorationsLineHighlights(canvasContext, decorations, highlightedLines, layout, lineHeight) {
        const highlightColors = new Map();
        // Loop backwards to hit first decorations with higher `zIndex`
        for (let i = decorations.length - 1; i >= 0; i--) {
            const decoration = decorations[i];
            const minimapOptions = decoration.options.minimap;
            if (!minimapOptions || minimapOptions.position !== MinimapPosition.Inline) {
                continue;
            }
            const startLineNumber = Math.max(layout.startLineNumber, decoration.range.startLineNumber);
            const endLineNumber = Math.min(layout.endLineNumber, decoration.range.endLineNumber);
            if (startLineNumber > endLineNumber) {
                // entirely outside minimap's viewport
                continue;
            }
            const decorationColor = minimapOptions.getColor(this._theme.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 = (startLineNumber - layout.startLineNumber) * lineHeight;
                canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y, canvasContext.canvas.width, lineHeight);
            }
        }
    }
    _renderSelectionsHighlights(canvasContext, selections, lineOffsetMap, layout, lineHeight, tabSize, characterWidth, canvasInnerWidth) {
        if (!this._selectionColor || this._selectionColor.isTransparent()) {
            return;
        }
        for (const selection of selections) {
            const startLineNumber = Math.max(layout.startLineNumber, selection.startLineNumber);
            const endLineNumber = Math.min(layout.endLineNumber, selection.endLineNumber);
            if (startLineNumber > endLineNumber) {
                // entirely outside minimap's viewport
                continue;
            }
            for (let line = startLineNumber; line <= endLineNumber; line++) {
                this.renderDecorationOnLine(canvasContext, lineOffsetMap, selection, this._selectionColor, layout, line, lineHeight, lineHeight, tabSize, characterWidth, canvasInnerWidth);
            }
        }
    }
    _renderDecorationsHighlights(canvasContext, decorations, lineOffsetMap, layout, lineHeight, tabSize, characterWidth, canvasInnerWidth) {
        // Loop forwards to hit first decorations with lower `zIndex`
        for (const decoration of decorations) {
            const minimapOptions = decoration.options.minimap;
            if (!minimapOptions) {
                continue;
            }
            const startLineNumber = Math.max(layout.startLineNumber, decoration.range.startLineNumber);
            const endLineNumber = Math.min(layout.endLineNumber, decoration.range.endLineNumber);
            if (startLineNumber > endLineNumber) {
                // entirely outside minimap's viewport
                continue;
            }
            const decorationColor = minimapOptions.getColor(this._theme.value);
            if (!decorationColor || decorationColor.isTransparent()) {
                continue;
            }
            for (let line = startLineNumber; line <= endLineNumber; line++) {
                switch (minimapOptions.position) {
                    case MinimapPosition.Inline:
                        this.renderDecorationOnLine(canvasContext, lineOffsetMap, decoration.range, decorationColor, layout, line, lineHeight, lineHeight, tabSize, characterWidth, canvasInnerWidth);
                        continue;
                    case MinimapPosition.Gutter: {
                        const y = (line - layout.startLineNumber) * lineHeight;
                        const x = 2;
                        this.renderDecoration(canvasContext, decorationColor, x, y, GUTTER_DECORATION_WIDTH, lineHeight);
                        continue;
                    }
                }
            }
        }
    }
    renderDecorationOnLine(canvasContext, lineOffsetMap, decorationRange, decorationColor, layout, lineNumber, height, lineHeight, tabSize, charWidth, canvasInnerWidth) {
        const y = (lineNumber - layout.startLineNumber) * lineHeight;
        // Skip rendering the line if it's vertically outside our viewport
        if (y + height < 0 || y > this._model.options.canvasInnerHeight) {
            return;
        }
        const { startLineNumber, endLineNumber } = decorationRange;
        const startColumn = (startLineNumber === lineNumber ? decorationRange.startColumn : 1);
        const endColumn = (endLineNumber === lineNumber ? decorationRange.endColumn : this._model.getLineMaxColumn(lineNumber));
        const x1 = this.getXOffsetForPosition(lineOffsetMap, lineNumber, startColumn, tabSize, charWidth, canvasInnerWidth);
        const x2 = this.getXOffsetForPosition(lineOffsetMap, lineNumber, endColumn, tabSize, charWidth, canvasInnerWidth);
        this.renderDecoration(canvasContext, decorationColor, x1, y, x2 - x1, height);
    }
    getXOffsetForPosition(lineOffsetMap, lineNumber, column, tabSize, charWidth, canvasInnerWidth) {
        if (column === 1) {
            return MINIMAP_GUTTER_WIDTH;
        }
        const minimumXOffset = (column - 1) * charWidth;
        if (minimumXOffset >= canvasInnerWidth) {
            // there is no need to look at actual characters,
            // as this column is certainly after the minimap width
            return canvasInnerWidth;
        }
        // Cache line offset data so that it is only read once per line
        let lineIndexToXOffset = lineOffsetMap.get(lineNumber);
        if (!lineIndexToXOffset) {
            const lineData = this._model.getLineContent(lineNumber);
            lineIndexToXOffset = [MINIMAP_GUTTER_WIDTH];
            let prevx = MINIMAP_GUTTER_WIDTH;
            for (let i = 1; i < lineData.length + 1; i++) {
                const charCode = lineData.charCodeAt(i - 1);
                const dx = charCode === 9 /* CharCode.Tab */
                    ? tabSize * charWidth
                    : isFullWidthCharacter(charCode)
                        ? 2 * charWidth
                        : charWidth;
                const x = prevx + dx;
                if (x >= canvasInnerWidth) {
                    // no need to keep on going, as we've hit the canvas width
                    lineIndexToXOffset[i] = canvasInnerWidth;
                    break;
                }
                lineIndexToXOffset[i] = x;
                prevx = x;
            }
            lineOffsetMap.set(lineNumber, lineIndexToXOffset);
        }
        if (column - 1 < lineIndexToXOffset.length) {
            return lineIndexToXOffset[column - 1];
        }
        // goes over the canvas width
        return canvasInnerWidth;
    }
    renderDecoration(canvasContext, decorationColor, x, y, width, height) {
        canvasContext.fillStyle = decorationColor && decorationColor.toString() || '';
        canvasContext.fillRect(x, y, width, height);
    }
    renderLines(layout) {
        const startLineNumber = layout.startLineNumber;
        const endLineNumber = layout.endLineNumber;
        const minimapLineHeight = this._model.options.minimapLineHeight;
        // Check if nothing changed w.r.t. lines from last frame
        if (this._lastRenderData && this._lastRenderData.linesEquals(layout)) {
            const _lastData = this._lastRenderData._get();
            // Nice!! Nothing changed from last frame
            return new RenderData(layout, _lastData.imageData, _lastData.lines);
        }
        // Oh well!! We need to repaint some lines...
        const imageData = this._getBuffer();
        if (!imageData) {
            // 0 width or 0 height canvas, nothing to do
            return null;
        }
        // Render untouched lines by using last rendered data.
        const [_dirtyY1, _dirtyY2, needed] = InnerMinimap._renderUntouchedLines(imageData, startLineNumber, endLineNumber, minimapLineHeight, this._lastRenderData);
        // Fetch rendering info from view model for rest of lines that need rendering.
        const lineInfo = this._model.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed);
        const tabSize = this._model.getOptions().tabSize;
        const defaultBackground = this._model.options.defaultBackgroundColor;
        const background = this._model.options.backgroundColor;
        const foregroundAlpha = this._model.options.foregroundAlpha;
        const tokensColorTracker = this._model.tokensColorTracker;
        const useLighterFont = tokensColorTracker.backgroundIsLight();
        const renderMinimap = this._model.options.renderMinimap;
        const charRenderer = this._model.options.charRenderer();
        const fontScale = this._model.options.fontScale;
        const minimapCharWidth = this._model.options.minimapCharWidth;
        const baseCharHeight = (renderMinimap === 1 /* RenderMinimap.Text */ ? 2 /* Constants.BASE_CHAR_HEIGHT */ : 2 /* Constants.BASE_CHAR_HEIGHT */ + 1);
        const renderMinimapLineHeight = baseCharHeight * fontScale;
        const innerLinePadding = (minimapLineHeight > renderMinimapLineHeight ? Math.floor((minimapLineHeight - renderMinimapLineHeight) / 2) : 0);
        // Render the rest of lines
        const backgroundA = background.a / 255;
        const renderBackground = new RGBA8(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 = 0;
        const renderedLines = [];
        for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
            if (needed[lineIndex]) {
                InnerMinimap._renderLine(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;
        // Finally, paint to the canvas
        const ctx = this._canvas.domNode.getContext('2d');
        ctx.putImageData(imageData, 0, 0, 0, dirtyY1, imageData.width, dirtyHeight);
        // Save rendered data for reuse on next frame if possible
        return new RenderData(layout, imageData, renderedLines);
    }
    static _renderUntouchedLines(target, startLineNumber, endLineNumber, minimapLineHeight, lastRenderData) {
        const needed = [];
        if (!lastRenderData) {
            for (let i = 0, len = endLineNumber - startLineNumber + 1; i < len; i++) {
                needed[i] = 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; // the pixel offset up to which all the data is equal to the prev frame
        let dirtyPixel2 = -1; // the pixel offset after which all the data is equal to the prev frame
        let copySourceStart = -1;
        let copySourceEnd = -1;
        let copyDestStart = -1;
        let copyDestEnd = -1;
        let dest_dy = 0;
        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) {
                // contiguous zone => extend copy request
                copySourceEnd = sourceEnd;
                copyDestEnd = destEnd;
            }
            else {
                if (copySourceStart !== -1) {
                    // flush existing copy request
                    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) {
            // flush existing copy request
            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 _renderLine(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) {
                    // hit edge of minimap
                    return;
                }
                const charCode = content.charCodeAt(charIndex);
                if (charCode === 9 /* CharCode.Tab */) {
                    const insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
                    tabsCharDelta += insertSpacesCount - 1;
                    // No need to render anything since tab is invisible
                    dx += insertSpacesCount * charWidth;
                }
                else if (charCode === 32 /* CharCode.Space */) {
                    // No need to render anything since space is invisible
                    dx += charWidth;
                }
                else {
                    // Render twice for a full width character
                    const count = isFullWidthCharacter(charCode) ? 2 : 1;
                    for (let i = 0; i < count; i++) {
                        if (renderMinimap === 2 /* RenderMinimap.Blocks */) {
                            minimapCharRenderer.blockRenderChar(target, dx, dy + innerLinePadding, tokenColor, foregroundAlpha, backgroundColor, backgroundAlpha, force1pxHeight);
                        }
                        else { // RenderMinimap.Text
                            minimapCharRenderer.renderChar(target, dx, dy + innerLinePadding, charCode, tokenColor, foregroundAlpha, backgroundColor, backgroundAlpha, fontScale, useLighterFont, force1pxHeight);
                        }
                        dx += charWidth;
                        if (dx > maxDx) {
                            // hit edge of minimap
                            return;
                        }
                    }
                }
            }
        }
    }
}
class ContiguousLineMap {
    constructor(startLineNumber, endLineNumber, defaultValue) {
        this._startLineNumber = startLineNumber;
        this._endLineNumber = endLineNumber;
        this._defaultValue = defaultValue;
        this._values = [];
        for (let i = 0, count = this._endLineNumber - this._startLineNumber + 1; i < count; i++) {
            this._values[i] = defaultValue;
        }
    }
    has(lineNumber) {
        return (this.get(lineNumber) !== this._defaultValue);
    }
    set(lineNumber, value) {
        if (lineNumber < this._startLineNumber || lineNumber > this._endLineNumber) {
            return;
        }
        this._values[lineNumber - this._startLineNumber] = value;
    }
    get(lineNumber) {
        if (lineNumber < this._startLineNumber || lineNumber > this._endLineNumber) {
            return this._defaultValue;
        }
        return this._values[lineNumber - this._startLineNumber];
    }
}
registerThemingParticipant((theme, collector) => {
    const sliderBackground = theme.getColor(minimapSliderBackground);
    if (sliderBackground) {
        collector.addRule(`.monaco-editor .minimap-slider .minimap-slider-horizontal { background: ${sliderBackground}; }`);
    }
    const sliderHoverBackground = theme.getColor(minimapSliderHoverBackground);
    if (sliderHoverBackground) {
        collector.addRule(`.monaco-editor .minimap-slider:hover .minimap-slider-horizontal { background: ${sliderHoverBackground}; }`);
    }
    const sliderActiveBackground = theme.getColor(minimapSliderActiveBackground);
    if (sliderActiveBackground) {
        collector.addRule(`.monaco-editor .minimap-slider.active .minimap-slider-horizontal { background: ${sliderActiveBackground}; }`);
    }
    const shadow = theme.getColor(scrollbarShadow);
    if (shadow) {
        collector.addRule(`.monaco-editor .minimap-shadow-visible { box-shadow: ${shadow} -6px 0 6px -6px inset; }`);
    }
});

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/overlayWidgets/overlayWidgets.css
var overlayWidgets = __webpack_require__(51726);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/overlayWidgets/overlayWidgets.css

      
      
      
      
      
      
      
      
      

var overlayWidgets_options = {};

overlayWidgets_options.styleTagTransform = (styleTagTransform_default());
overlayWidgets_options.setAttributes = (setAttributesWithoutAttributes_default());

      overlayWidgets_options.insert = insertBySelector_default().bind(null, "head");
    
overlayWidgets_options.domAPI = (styleDomAPI_default());
overlayWidgets_options.insertStyleElement = (insertStyleElement_default());

var overlayWidgets_update = injectStylesIntoStyleTag_default()(overlayWidgets/* default */.A, overlayWidgets_options);




       /* harmony default export */ const overlayWidgets_overlayWidgets = (overlayWidgets/* default */.A && overlayWidgets/* default */.A.locals ? overlayWidgets/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/overlayWidgets/overlayWidgets.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class ViewOverlayWidgets extends ViewPart {
    constructor(context) {
        super(context);
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._widgets = {};
        this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
        this._minimapWidth = layoutInfo.minimap.minimapWidth;
        this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
        this._editorHeight = layoutInfo.height;
        this._editorWidth = layoutInfo.width;
        this._domNode = createFastDomNode(document.createElement('div'));
        PartFingerprints.write(this._domNode, 4 /* PartFingerprint.OverlayWidgets */);
        this._domNode.setClassName('overlayWidgets');
    }
    dispose() {
        super.dispose();
        this._widgets = {};
    }
    getDomNode() {
        return this._domNode;
    }
    // ---- begin view event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
        this._minimapWidth = layoutInfo.minimap.minimapWidth;
        this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
        this._editorHeight = layoutInfo.height;
        this._editorWidth = layoutInfo.width;
        return true;
    }
    // ---- end view event handlers
    addWidget(widget) {
        const domNode = createFastDomNode(widget.getDomNode());
        this._widgets[widget.getId()] = {
            widget: widget,
            preference: null,
            domNode: domNode
        };
        // This is sync because a widget wants to be in the dom
        domNode.setPosition('absolute');
        domNode.setAttribute('widgetId', widget.getId());
        this._domNode.appendChild(domNode);
        this.setShouldRender();
    }
    setWidgetPosition(widget, preference) {
        const widgetData = this._widgets[widget.getId()];
        if (widgetData.preference === preference) {
            return false;
        }
        widgetData.preference = preference;
        this.setShouldRender();
        return true;
    }
    removeWidget(widget) {
        const widgetId = widget.getId();
        if (this._widgets.hasOwnProperty(widgetId)) {
            const widgetData = this._widgets[widgetId];
            const domNode = widgetData.domNode.domNode;
            delete this._widgets[widgetId];
            domNode.parentNode.removeChild(domNode);
            this.setShouldRender();
        }
    }
    _renderWidget(widgetData) {
        const domNode = widgetData.domNode;
        if (widgetData.preference === null) {
            domNode.setTop('');
            return;
        }
        if (widgetData.preference === 0 /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */) {
            domNode.setTop(0);
            domNode.setRight((2 * this._verticalScrollbarWidth) + this._minimapWidth);
        }
        else if (widgetData.preference === 1 /* OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER */) {
            const widgetHeight = domNode.domNode.clientHeight;
            domNode.setTop((this._editorHeight - widgetHeight - 2 * this._horizontalScrollbarHeight));
            domNode.setRight((2 * this._verticalScrollbarWidth) + this._minimapWidth);
        }
        else if (widgetData.preference === 2 /* OverlayWidgetPositionPreference.TOP_CENTER */) {
            domNode.setTop(0);
            domNode.domNode.style.right = '50%';
        }
    }
    prepareRender(ctx) {
        // Nothing to read
    }
    render(ctx) {
        this._domNode.setWidth(this._editorWidth);
        const keys = Object.keys(this._widgets);
        for (let i = 0, len = keys.length; i < len; i++) {
            const widgetId = keys[i];
            this._renderWidget(this._widgets[widgetId]);
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







class Settings {
    constructor(config, theme) {
        const options = config.options;
        this.lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this.pixelRatio = options.get(131 /* EditorOption.pixelRatio */);
        this.overviewRulerLanes = options.get(76 /* EditorOption.overviewRulerLanes */);
        this.renderBorder = options.get(75 /* EditorOption.overviewRulerBorder */);
        const borderColor = theme.getColor(editorOverviewRulerBorder);
        this.borderColor = borderColor ? borderColor.toString() : null;
        this.hideCursor = options.get(54 /* EditorOption.hideCursorInOverviewRuler */);
        const cursorColor = theme.getColor(editorCursorForeground);
        this.cursorColor = cursorColor ? cursorColor.transparent(0.7).toString() : null;
        this.themeType = theme.type;
        const minimapOpts = options.get(67 /* EditorOption.minimap */);
        const minimapEnabled = minimapOpts.enabled;
        const minimapSide = minimapOpts.side;
        const themeColor = theme.getColor(editorOverviewRulerBackground);
        const defaultBackground = languages_TokenizationRegistry.getDefaultBackground();
        let backgroundColor = null;
        if (themeColor !== undefined) {
            backgroundColor = themeColor;
        }
        else if (minimapEnabled) {
            backgroundColor = defaultBackground;
        }
        if (backgroundColor === null || minimapSide === 'left') {
            this.backgroundColor = null;
        }
        else {
            this.backgroundColor = Color.Format.CSS.formatHex(backgroundColor);
        }
        const layoutInfo = options.get(133 /* 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) {
            // overview ruler is off
            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._initLanes(1, this.canvasWidth, this.overviewRulerLanes);
        this.x = x;
        this.w = w;
    }
    _initLanes(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,
                    centerOffset,
                    leftOffset,
                    rightOffset,
                    leftOffset,
                    centerOffset,
                    leftOffset, // Left | Center | Right
                ], [
                    0,
                    leftWidth,
                    centerWidth,
                    leftWidth + centerWidth,
                    rightWidth,
                    leftWidth + centerWidth + rightWidth,
                    centerWidth + rightWidth,
                    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,
                    leftOffset,
                    leftOffset,
                    rightOffset,
                    leftOffset,
                    leftOffset,
                    leftOffset, // Left | Center | Right
                ], [
                    0,
                    leftWidth,
                    leftWidth,
                    leftWidth,
                    rightWidth,
                    leftWidth + rightWidth,
                    leftWidth + rightWidth,
                    leftWidth + rightWidth, // Left | Center | Right
                ]
            ];
        }
        else {
            const offset = canvasLeftOffset;
            const width = remainingWidth;
            return [
                [
                    0,
                    offset,
                    offset,
                    offset,
                    offset,
                    offset,
                    offset,
                    offset, // Left | Center | Right
                ], [
                    0,
                    width,
                    width,
                    width,
                    width,
                    width,
                    width,
                    width, // 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.cursorColor === other.cursorColor
            && this.themeType === other.themeType
            && 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);
    }
}
class DecorationsOverviewRuler extends ViewPart {
    constructor(context) {
        super(context);
        this._domNode = createFastDomNode(document.createElement('canvas'));
        this._domNode.setClassName('decorationsOverviewRuler');
        this._domNode.setPosition('absolute');
        this._domNode.setLayerHinting(true);
        this._domNode.setContain('strict');
        this._domNode.setAttribute('aria-hidden', 'true');
        this._updateSettings(false);
        this._tokensColorTrackerListener = languages_TokenizationRegistry.onDidChange((e) => {
            if (e.changedColorMap) {
                this._updateSettings(true);
            }
        });
        this._cursorPositions = [];
    }
    dispose() {
        super.dispose();
        this._tokensColorTrackerListener.dispose();
    }
    _updateSettings(renderNow) {
        const newSettings = new Settings(this._context.configuration, this._context.theme);
        if (this._settings && this._settings.equals(newSettings)) {
            // nothing to do
            return false;
        }
        this._settings = newSettings;
        this._domNode.setTop(this._settings.top);
        this._domNode.setRight(this._settings.right);
        this._domNode.setWidth(this._settings.domWidth);
        this._domNode.setHeight(this._settings.domHeight);
        this._domNode.domNode.width = this._settings.canvasWidth;
        this._domNode.domNode.height = this._settings.canvasHeight;
        if (renderNow) {
            this._render();
        }
        return true;
    }
    // ---- begin view event handlers
    onConfigurationChanged(e) {
        return this._updateSettings(false);
    }
    onCursorStateChanged(e) {
        this._cursorPositions = [];
        for (let i = 0, len = e.selections.length; i < len; i++) {
            this._cursorPositions[i] = e.selections[i].getPosition();
        }
        this._cursorPositions.sort(Position.compare);
        return true;
    }
    onDecorationsChanged(e) {
        if (e.affectsOverviewRuler) {
            return true;
        }
        return false;
    }
    onFlushed(e) {
        return true;
    }
    onScrollChanged(e) {
        return e.scrollHeightChanged;
    }
    onZonesChanged(e) {
        return true;
    }
    onThemeChanged(e) {
        return this._updateSettings(false);
    }
    // ---- end view event handlers
    getDomNode() {
        return this._domNode.domNode;
    }
    prepareRender(ctx) {
        // Nothing to read
    }
    render(editorCtx) {
        this._render();
    }
    _render() {
        if (this._settings.overviewRulerLanes === 0) {
            // overview ruler is off
            this._domNode.setBackgroundColor(this._settings.backgroundColor ? this._settings.backgroundColor : '');
            this._domNode.setDisplay('none');
            return;
        }
        this._domNode.setDisplay('block');
        const canvasWidth = this._settings.canvasWidth;
        const canvasHeight = this._settings.canvasHeight;
        const lineHeight = this._settings.lineHeight;
        const viewLayout = this._context.viewLayout;
        const outerHeight = this._context.viewLayout.getScrollHeight();
        const heightRatio = canvasHeight / outerHeight;
        const decorations = this._context.viewModel.getAllOverviewRulerDecorations(this._context.theme);
        const minDecorationHeight = (6 /* Constants.MIN_DECORATION_HEIGHT */ * this._settings.pixelRatio) | 0;
        const halfMinDecorationHeight = (minDecorationHeight / 2) | 0;
        const canvasCtx = this._domNode.domNode.getContext('2d');
        if (this._settings.backgroundColor === null) {
            canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
        }
        else {
            canvasCtx.fillStyle = this._settings.backgroundColor;
            canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
        }
        const x = this._settings.x;
        const w = this._settings.w;
        decorations.sort(OverviewRulerDecorationsGroup.cmp);
        for (const decorationGroup of decorations) {
            const color = decorationGroup.color;
            const decorationGroupData = decorationGroup.data;
            canvasCtx.fillStyle = color;
            let prevLane = 0;
            let prevY1 = 0;
            let prevY2 = 0;
            for (let i = 0, len = decorationGroupData.length / 3; i < len; i++) {
                const lane = decorationGroupData[3 * i];
                const startLineNumber = decorationGroupData[3 * i + 1];
                const endLineNumber = decorationGroupData[3 * i + 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) {
                    // flush prev
                    if (i !== 0) {
                        canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
                    }
                    prevLane = lane;
                    prevY1 = y1;
                    prevY2 = y2;
                }
                else {
                    // merge into prev
                    if (y2 > prevY2) {
                        prevY2 = y2;
                    }
                }
            }
            canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
        }
        // Draw cursors
        if (!this._settings.hideCursor && this._settings.cursorColor) {
            const cursorHeight = (2 * this._settings.pixelRatio) | 0;
            const halfCursorHeight = (cursorHeight / 2) | 0;
            const cursorX = this._settings.x[7 /* OverviewRulerLane.Full */];
            const cursorW = this._settings.w[7 /* OverviewRulerLane.Full */];
            canvasCtx.fillStyle = this._settings.cursorColor;
            let prevY1 = -100;
            let prevY2 = -100;
            for (let i = 0, len = this._cursorPositions.length; i < len; i++) {
                const cursor = this._cursorPositions[i];
                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) {
                    // flush prev
                    if (i !== 0) {
                        canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
                    }
                    prevY1 = y1;
                    prevY2 = y2;
                }
                else {
                    // merge into prev
                    if (y2 > prevY2) {
                        prevY2 = y2;
                    }
                }
            }
            canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
        }
        if (this._settings.renderBorder && this._settings.borderColor && this._settings.overviewRulerLanes > 0) {
            canvasCtx.beginPath();
            canvasCtx.lineWidth = 1;
            canvasCtx.strokeStyle = this._settings.borderColor;
            canvasCtx.moveTo(0, 0);
            canvasCtx.lineTo(0, canvasHeight);
            canvasCtx.stroke();
            canvasCtx.moveTo(0, 0);
            canvasCtx.lineTo(canvasWidth, 0);
            canvasCtx.stroke();
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewModel/overviewZoneManager.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class ColorZone {
    constructor(from, to, colorId) {
        this._colorZoneBrand = undefined;
        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;
    }
}
/**
 * A zone in the overview ruler
 */
class OverviewRulerZone {
    constructor(startLineNumber, endLineNumber, heightInLines, color) {
        this._overviewRulerZoneBrand = undefined;
        this.startLineNumber = startLineNumber;
        this.endLineNumber = endLineNumber;
        this.heightInLines = heightInLines;
        this.color = color;
        this._colorZone = 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._colorZone = colorZone;
    }
    getColorZones() {
        return this._colorZone;
    }
}
class OverviewZoneManager {
    constructor(getVerticalOffsetForLine) {
        this._getVerticalOffsetForLine = getVerticalOffsetForLine;
        this._zones = [];
        this._colorZonesInvalid = false;
        this._lineHeight = 0;
        this._domWidth = 0;
        this._domHeight = 0;
        this._outerHeight = 0;
        this._pixelRatio = 1;
        this._lastAssignedId = 0;
        this._color2Id = Object.create(null);
        this._id2Color = [];
    }
    getId2Color() {
        return this._id2Color;
    }
    setZones(newZones) {
        this._zones = newZones;
        this._zones.sort(OverviewRulerZone.compare);
    }
    setLineHeight(lineHeight) {
        if (this._lineHeight === lineHeight) {
            return false;
        }
        this._lineHeight = lineHeight;
        this._colorZonesInvalid = true;
        return true;
    }
    setPixelRatio(pixelRatio) {
        this._pixelRatio = pixelRatio;
        this._colorZonesInvalid = true;
    }
    getDOMWidth() {
        return this._domWidth;
    }
    getCanvasWidth() {
        return this._domWidth * this._pixelRatio;
    }
    setDOMWidth(width) {
        if (this._domWidth === width) {
            return false;
        }
        this._domWidth = width;
        this._colorZonesInvalid = true;
        return true;
    }
    getDOMHeight() {
        return this._domHeight;
    }
    getCanvasHeight() {
        return this._domHeight * this._pixelRatio;
    }
    setDOMHeight(height) {
        if (this._domHeight === height) {
            return false;
        }
        this._domHeight = height;
        this._colorZonesInvalid = true;
        return true;
    }
    getOuterHeight() {
        return this._outerHeight;
    }
    setOuterHeight(outerHeight) {
        if (this._outerHeight === outerHeight) {
            return false;
        }
        this._outerHeight = outerHeight;
        this._colorZonesInvalid = true;
        return true;
    }
    resolveColorZones() {
        const colorZonesInvalid = this._colorZonesInvalid;
        const lineHeight = Math.floor(this._lineHeight);
        const totalHeight = Math.floor(this.getCanvasHeight());
        const outerHeight = Math.floor(this._outerHeight);
        const heightRatio = totalHeight / outerHeight;
        const halfMinimumHeight = Math.floor(4 /* Constants.MINIMUM_HEIGHT */ * this._pixelRatio / 2);
        const allColorZones = [];
        for (let i = 0, len = this._zones.length; i < len; i++) {
            const zone = this._zones[i];
            if (!colorZonesInvalid) {
                const colorZone = zone.getColorZones();
                if (colorZone) {
                    allColorZones.push(colorZone);
                    continue;
                }
            }
            const offset1 = this._getVerticalOffsetForLine(zone.startLineNumber);
            const offset2 = (zone.heightInLines === 0
                ? this._getVerticalOffsetForLine(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 color = zone.color;
            let colorId = this._color2Id[color];
            if (!colorId) {
                colorId = (++this._lastAssignedId);
                this._color2Id[color] = colorId;
                this._id2Color[colorId] = color;
            }
            const colorZone = new ColorZone(ycenter - halfHeight, ycenter + halfHeight, colorId);
            zone.setColorZone(colorZone);
            allColorZones.push(colorZone);
        }
        this._colorZonesInvalid = false;
        allColorZones.sort(ColorZone.compare);
        return allColorZones;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/overviewRuler/overviewRuler.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class OverviewRuler extends ViewEventHandler {
    constructor(context, cssClassName) {
        super();
        this._context = context;
        const options = this._context.configuration.options;
        this._domNode = createFastDomNode(document.createElement('canvas'));
        this._domNode.setClassName(cssClassName);
        this._domNode.setPosition('absolute');
        this._domNode.setLayerHinting(true);
        this._domNode.setContain('strict');
        this._zoneManager = new OverviewZoneManager((lineNumber) => this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber));
        this._zoneManager.setDOMWidth(0);
        this._zoneManager.setDOMHeight(0);
        this._zoneManager.setOuterHeight(this._context.viewLayout.getScrollHeight());
        this._zoneManager.setLineHeight(options.get(61 /* EditorOption.lineHeight */));
        this._zoneManager.setPixelRatio(options.get(131 /* EditorOption.pixelRatio */));
        this._context.addEventHandler(this);
    }
    dispose() {
        this._context.removeEventHandler(this);
        super.dispose();
    }
    // ---- begin view event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        if (e.hasChanged(61 /* EditorOption.lineHeight */)) {
            this._zoneManager.setLineHeight(options.get(61 /* EditorOption.lineHeight */));
            this._render();
        }
        if (e.hasChanged(131 /* EditorOption.pixelRatio */)) {
            this._zoneManager.setPixelRatio(options.get(131 /* EditorOption.pixelRatio */));
            this._domNode.setWidth(this._zoneManager.getDOMWidth());
            this._domNode.setHeight(this._zoneManager.getDOMHeight());
            this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
            this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
            this._render();
        }
        return true;
    }
    onFlushed(e) {
        this._render();
        return true;
    }
    onScrollChanged(e) {
        if (e.scrollHeightChanged) {
            this._zoneManager.setOuterHeight(e.scrollHeight);
            this._render();
        }
        return true;
    }
    onZonesChanged(e) {
        this._render();
        return true;
    }
    // ---- end view event handlers
    getDomNode() {
        return this._domNode.domNode;
    }
    setLayout(position) {
        this._domNode.setTop(position.top);
        this._domNode.setRight(position.right);
        let hasChanged = false;
        hasChanged = this._zoneManager.setDOMWidth(position.width) || hasChanged;
        hasChanged = this._zoneManager.setDOMHeight(position.height) || hasChanged;
        if (hasChanged) {
            this._domNode.setWidth(this._zoneManager.getDOMWidth());
            this._domNode.setHeight(this._zoneManager.getDOMHeight());
            this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
            this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
            this._render();
        }
    }
    setZones(zones) {
        this._zoneManager.setZones(zones);
        this._render();
    }
    _render() {
        if (this._zoneManager.getOuterHeight() === 0) {
            return false;
        }
        const width = this._zoneManager.getCanvasWidth();
        const height = this._zoneManager.getCanvasHeight();
        const colorZones = this._zoneManager.resolveColorZones();
        const id2Color = this._zoneManager.getId2Color();
        const ctx = this._domNode.domNode.getContext('2d');
        ctx.clearRect(0, 0, width, height);
        if (colorZones.length > 0) {
            this._renderOneLane(ctx, colorZones, id2Color, width);
        }
        return true;
    }
    _renderOneLane(ctx, colorZones, id2Color, width) {
        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, width, 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, width, currentTo - currentFrom);
                    currentFrom = zoneFrom;
                    currentTo = zoneTo;
                }
            }
        }
        ctx.fillRect(0, currentFrom, width, currentTo - currentFrom);
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/rulers/rulers.css
var rulers = __webpack_require__(33874);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/rulers/rulers.css

      
      
      
      
      
      
      
      
      

var rulers_options = {};

rulers_options.styleTagTransform = (styleTagTransform_default());
rulers_options.setAttributes = (setAttributesWithoutAttributes_default());

      rulers_options.insert = insertBySelector_default().bind(null, "head");
    
rulers_options.domAPI = (styleDomAPI_default());
rulers_options.insertStyleElement = (insertStyleElement_default());

var rulers_update = injectStylesIntoStyleTag_default()(rulers/* default */.A, rulers_options);




       /* harmony default export */ const rulers_rulers = (rulers/* default */.A && rulers/* default */.A.locals ? rulers/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/rulers/rulers.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class Rulers extends ViewPart {
    constructor(context) {
        super(context);
        this.domNode = createFastDomNode(document.createElement('div'));
        this.domNode.setAttribute('role', 'presentation');
        this.domNode.setAttribute('aria-hidden', 'true');
        this.domNode.setClassName('view-rulers');
        this._renderedRulers = [];
        const options = this._context.configuration.options;
        this._rulers = options.get(93 /* EditorOption.rulers */);
        this._typicalHalfwidthCharacterWidth = options.get(46 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
    }
    dispose() {
        super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        this._rulers = options.get(93 /* EditorOption.rulers */);
        this._typicalHalfwidthCharacterWidth = options.get(46 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
        return true;
    }
    onScrollChanged(e) {
        return e.scrollHeightChanged;
    }
    // --- end event handlers
    prepareRender(ctx) {
        // Nothing to read
    }
    _ensureRulersCount() {
        const currentCount = this._renderedRulers.length;
        const desiredCount = this._rulers.length;
        if (currentCount === desiredCount) {
            // Nothing to do
            return;
        }
        if (currentCount < desiredCount) {
            const { tabSize } = this._context.viewModel.model.getOptions();
            const rulerWidth = tabSize;
            let addCount = desiredCount - currentCount;
            while (addCount > 0) {
                const node = createFastDomNode(document.createElement('div'));
                node.setClassName('view-ruler');
                node.setWidth(rulerWidth);
                this.domNode.appendChild(node);
                this._renderedRulers.push(node);
                addCount--;
            }
            return;
        }
        let removeCount = currentCount - desiredCount;
        while (removeCount > 0) {
            const node = this._renderedRulers.pop();
            this.domNode.removeChild(node);
            removeCount--;
        }
    }
    render(ctx) {
        this._ensureRulersCount();
        for (let i = 0, len = this._rulers.length; i < len; i++) {
            const node = this._renderedRulers[i];
            const ruler = this._rulers[i];
            node.setBoxShadow(ruler.color ? `1px 0 0 0 ${ruler.color} inset` : ``);
            node.setHeight(Math.min(ctx.scrollHeight, 1000000));
            node.setLeft(ruler.column * this._typicalHalfwidthCharacterWidth);
        }
    }
}
registerThemingParticipant((theme, collector) => {
    const rulerColor = theme.getColor(editorRuler);
    if (rulerColor) {
        collector.addRule(`.monaco-editor .view-ruler { box-shadow: 1px 0 0 0 ${rulerColor} inset; }`);
    }
});

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/scrollDecoration/scrollDecoration.css
var scrollDecoration = __webpack_require__(36650);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/scrollDecoration/scrollDecoration.css

      
      
      
      
      
      
      
      
      

var scrollDecoration_options = {};

scrollDecoration_options.styleTagTransform = (styleTagTransform_default());
scrollDecoration_options.setAttributes = (setAttributesWithoutAttributes_default());

      scrollDecoration_options.insert = insertBySelector_default().bind(null, "head");
    
scrollDecoration_options.domAPI = (styleDomAPI_default());
scrollDecoration_options.insertStyleElement = (insertStyleElement_default());

var scrollDecoration_update = injectStylesIntoStyleTag_default()(scrollDecoration/* default */.A, scrollDecoration_options);




       /* harmony default export */ const scrollDecoration_scrollDecoration = (scrollDecoration/* default */.A && scrollDecoration/* default */.A.locals ? scrollDecoration/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/scrollDecoration/scrollDecoration.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class ScrollDecorationViewPart extends ViewPart {
    constructor(context) {
        super(context);
        this._scrollTop = 0;
        this._width = 0;
        this._updateWidth();
        this._shouldShow = false;
        const options = this._context.configuration.options;
        const scrollbar = options.get(94 /* EditorOption.scrollbar */);
        this._useShadows = scrollbar.useShadows;
        this._domNode = createFastDomNode(document.createElement('div'));
        this._domNode.setAttribute('role', 'presentation');
        this._domNode.setAttribute('aria-hidden', 'true');
    }
    dispose() {
        super.dispose();
    }
    _updateShouldShow() {
        const newShouldShow = (this._useShadows && this._scrollTop > 0);
        if (this._shouldShow !== newShouldShow) {
            this._shouldShow = newShouldShow;
            return true;
        }
        return false;
    }
    getDomNode() {
        return this._domNode;
    }
    _updateWidth() {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        if (layoutInfo.minimap.renderMinimap === 0 || (layoutInfo.minimap.minimapWidth > 0 && layoutInfo.minimap.minimapLeft === 0)) {
            this._width = layoutInfo.width;
        }
        else {
            this._width = layoutInfo.width - layoutInfo.verticalScrollbarWidth;
        }
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        const scrollbar = options.get(94 /* EditorOption.scrollbar */);
        this._useShadows = scrollbar.useShadows;
        this._updateWidth();
        this._updateShouldShow();
        return true;
    }
    onScrollChanged(e) {
        this._scrollTop = e.scrollTop;
        return this._updateShouldShow();
    }
    // --- end event handlers
    prepareRender(ctx) {
        // Nothing to read
    }
    render(ctx) {
        this._domNode.setWidth(this._width);
        this._domNode.setClassName(this._shouldShow ? 'scroll-decoration' : '');
    }
}
registerThemingParticipant((theme, collector) => {
    const shadow = theme.getColor(scrollbarShadow);
    if (shadow) {
        collector.addRule(`.monaco-editor .scroll-decoration { box-shadow: ${shadow} 0 6px 6px -6px inset; }`);
    }
});

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/selections/selections.css
var selections = __webpack_require__(6554);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/selections/selections.css

      
      
      
      
      
      
      
      
      

var selections_options = {};

selections_options.styleTagTransform = (styleTagTransform_default());
selections_options.setAttributes = (setAttributesWithoutAttributes_default());

      selections_options.insert = insertBySelector_default().bind(null, "head");
    
selections_options.domAPI = (styleDomAPI_default());
selections_options.insertStyleElement = (insertStyleElement_default());

var selections_update = injectStylesIntoStyleTag_default()(selections/* default */.A, selections_options);




       /* harmony default export */ const selections_selections = (selections/* default */.A && selections/* default */.A.locals ? selections/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/selections/selections.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class HorizontalRangeWithStyle {
    constructor(other) {
        this.left = other.left;
        this.width = other.width;
        this.startStyle = null;
        this.endStyle = null;
    }
}
class LineVisibleRangesWithStyle {
    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));
}
class SelectionsOverlay extends DynamicViewOverlay {
    constructor(context) {
        super();
        this._previousFrameVisibleRangesWithStyle = [];
        this._context = context;
        const options = this._context.configuration.options;
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._roundedSelection = options.get(92 /* EditorOption.roundedSelection */);
        this._typicalHalfwidthCharacterWidth = options.get(46 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
        this._selections = [];
        this._renderResult = null;
        this._context.addEventHandler(this);
    }
    dispose() {
        this._context.removeEventHandler(this);
        this._renderResult = null;
        super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._roundedSelection = options.get(92 /* EditorOption.roundedSelection */);
        this._typicalHalfwidthCharacterWidth = options.get(46 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth;
        return true;
    }
    onCursorStateChanged(e) {
        this._selections = e.selections.slice(0);
        return true;
    }
    onDecorationsChanged(e) {
        // true for inline decorations that can end up relayouting text
        return true; //e.inlineDecorationsChanged;
    }
    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
    _visibleRangesHaveGaps(linesVisibleRanges) {
        for (let i = 0, len = linesVisibleRanges.length; i < len; i++) {
            const lineVisibleRanges = linesVisibleRanges[i];
            if (lineVisibleRanges.ranges.length > 1) {
                // There are two ranges on the same line
                return true;
            }
        }
        return false;
    }
    _enrichVisibleRangesWithStyle(viewport, linesVisibleRanges, previousFrame) {
        const epsilon = this._typicalHalfwidthCharacterWidth / 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 i = 0; !previousFrameTop && i < previousFrame.length; i++) {
                    if (previousFrame[i].lineNumber === topLineNumber) {
                        previousFrameTop = previousFrame[i].ranges[0];
                    }
                }
            }
            const bottomLineNumber = linesVisibleRanges[linesVisibleRanges.length - 1].lineNumber;
            if (bottomLineNumber === viewport.endLineNumber) {
                for (let i = previousFrame.length - 1; !previousFrameBottom && i >= 0; i--) {
                    if (previousFrame[i].lineNumber === bottomLineNumber) {
                        previousFrameBottom = previousFrame[i].ranges[0];
                    }
                }
            }
            if (previousFrameTop && !previousFrameTop.startStyle) {
                previousFrameTop = null;
            }
            if (previousFrameBottom && !previousFrameBottom.startStyle) {
                previousFrameBottom = null;
            }
        }
        for (let i = 0, len = linesVisibleRanges.length; i < len; i++) {
            // We know for a fact that there is precisely one range on each line
            const curLineRange = linesVisibleRanges[i].ranges[0];
            const curLeft = curLineRange.left;
            const curRight = curLineRange.left + curLineRange.width;
            const startStyle = {
                top: 0 /* CornerStyle.EXTERN */,
                bottom: 0 /* CornerStyle.EXTERN */
            };
            const endStyle = {
                top: 0 /* CornerStyle.EXTERN */,
                bottom: 0 /* CornerStyle.EXTERN */
            };
            if (i > 0) {
                // Look above
                const prevLeft = linesVisibleRanges[i - 1].ranges[0].left;
                const prevRight = linesVisibleRanges[i - 1].ranges[0].left + linesVisibleRanges[i - 1].ranges[0].width;
                if (abs(curLeft - prevLeft) < epsilon) {
                    startStyle.top = 2 /* CornerStyle.FLAT */;
                }
                else if (curLeft > prevLeft) {
                    startStyle.top = 1 /* CornerStyle.INTERN */;
                }
                if (abs(curRight - prevRight) < epsilon) {
                    endStyle.top = 2 /* CornerStyle.FLAT */;
                }
                else if (prevLeft < curRight && curRight < prevRight) {
                    endStyle.top = 1 /* CornerStyle.INTERN */;
                }
            }
            else if (previousFrameTop) {
                // Accept some hiccups near the viewport edges to save on repaints
                startStyle.top = previousFrameTop.startStyle.top;
                endStyle.top = previousFrameTop.endStyle.top;
            }
            if (i + 1 < len) {
                // Look below
                const nextLeft = linesVisibleRanges[i + 1].ranges[0].left;
                const nextRight = linesVisibleRanges[i + 1].ranges[0].left + linesVisibleRanges[i + 1].ranges[0].width;
                if (abs(curLeft - nextLeft) < epsilon) {
                    startStyle.bottom = 2 /* CornerStyle.FLAT */;
                }
                else if (nextLeft < curLeft && curLeft < nextRight) {
                    startStyle.bottom = 1 /* CornerStyle.INTERN */;
                }
                if (abs(curRight - nextRight) < epsilon) {
                    endStyle.bottom = 2 /* CornerStyle.FLAT */;
                }
                else if (curRight < nextRight) {
                    endStyle.bottom = 1 /* CornerStyle.INTERN */;
                }
            }
            else if (previousFrameBottom) {
                // Accept some hiccups near the viewport edges to save on repaints
                startStyle.bottom = previousFrameBottom.startStyle.bottom;
                endStyle.bottom = previousFrameBottom.endStyle.bottom;
            }
            curLineRange.startStyle = startStyle;
            curLineRange.endStyle = endStyle;
        }
    }
    _getVisibleRangesWithStyle(selection, ctx, previousFrame) {
        const _linesVisibleRanges = ctx.linesVisibleRangesForRange(selection, true) || [];
        const linesVisibleRanges = _linesVisibleRanges.map(toStyled);
        const visibleRangesHaveGaps = this._visibleRangesHaveGaps(linesVisibleRanges);
        if (!visibleRangesHaveGaps && this._roundedSelection) {
            this._enrichVisibleRangesWithStyle(ctx.visibleRange, linesVisibleRanges, previousFrame);
        }
        // The visible ranges are sorted TOP-BOTTOM and LEFT-RIGHT
        return linesVisibleRanges;
    }
    _createSelectionPiece(top, height, className, left, width) {
        return ('<div class="cslr '
            + className
            + '" style="top:'
            + top.toString()
            + 'px;left:'
            + left.toString()
            + 'px;width:'
            + width.toString()
            + 'px;height:'
            + height
            + 'px;"></div>');
    }
    _actualRenderOneSelection(output2, visibleStartLineNumber, hasMultipleSelections, visibleRanges) {
        if (visibleRanges.length === 0) {
            return;
        }
        const visibleRangesHaveStyle = !!visibleRanges[0].ranges[0].startStyle;
        const fullLineHeight = (this._lineHeight).toString();
        const reducedLineHeight = (this._lineHeight - 1).toString();
        const firstLineNumber = visibleRanges[0].lineNumber;
        const lastLineNumber = visibleRanges[visibleRanges.length - 1].lineNumber;
        for (let i = 0, len = visibleRanges.length; i < len; i++) {
            const lineVisibleRanges = visibleRanges[i];
            const lineNumber = lineVisibleRanges.lineNumber;
            const lineIndex = lineNumber - visibleStartLineNumber;
            const lineHeight = hasMultipleSelections ? (lineNumber === lastLineNumber || lineNumber === firstLineNumber ? reducedLineHeight : fullLineHeight) : fullLineHeight;
            const top = hasMultipleSelections ? (lineNumber === firstLineNumber ? 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 /* CornerStyle.INTERN */ || startStyle.bottom === 1 /* CornerStyle.INTERN */) {
                        // Reverse rounded corner to the left
                        // First comes the selection (blue layer)
                        innerCornerOutput += this._createSelectionPiece(top, lineHeight, SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left - SelectionsOverlay.ROUNDED_PIECE_WIDTH, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
                        // Second comes the background (white layer) with inverse border radius
                        let className = SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME;
                        if (startStyle.top === 1 /* CornerStyle.INTERN */) {
                            className += ' ' + SelectionsOverlay.SELECTION_TOP_RIGHT;
                        }
                        if (startStyle.bottom === 1 /* CornerStyle.INTERN */) {
                            className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
                        }
                        innerCornerOutput += this._createSelectionPiece(top, lineHeight, className, visibleRange.left - SelectionsOverlay.ROUNDED_PIECE_WIDTH, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
                    }
                    if (endStyle.top === 1 /* CornerStyle.INTERN */ || endStyle.bottom === 1 /* CornerStyle.INTERN */) {
                        // Reverse rounded corner to the right
                        // First comes the selection (blue layer)
                        innerCornerOutput += this._createSelectionPiece(top, lineHeight, SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left + visibleRange.width, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
                        // Second comes the background (white layer) with inverse border radius
                        let className = SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME;
                        if (endStyle.top === 1 /* CornerStyle.INTERN */) {
                            className += ' ' + SelectionsOverlay.SELECTION_TOP_LEFT;
                        }
                        if (endStyle.bottom === 1 /* CornerStyle.INTERN */) {
                            className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_LEFT;
                        }
                        innerCornerOutput += this._createSelectionPiece(top, lineHeight, className, visibleRange.left + visibleRange.width, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
                    }
                }
                let className = SelectionsOverlay.SELECTION_CLASS_NAME;
                if (visibleRangesHaveStyle) {
                    const startStyle = visibleRange.startStyle;
                    const endStyle = visibleRange.endStyle;
                    if (startStyle.top === 0 /* CornerStyle.EXTERN */) {
                        className += ' ' + SelectionsOverlay.SELECTION_TOP_LEFT;
                    }
                    if (startStyle.bottom === 0 /* CornerStyle.EXTERN */) {
                        className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_LEFT;
                    }
                    if (endStyle.top === 0 /* CornerStyle.EXTERN */) {
                        className += ' ' + SelectionsOverlay.SELECTION_TOP_RIGHT;
                    }
                    if (endStyle.bottom === 0 /* CornerStyle.EXTERN */) {
                        className += ' ' + SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
                    }
                }
                restOfSelectionOutput += this._createSelectionPiece(top, lineHeight, className, visibleRange.left, visibleRange.width);
            }
            output2[lineIndex][0] += innerCornerOutput;
            output2[lineIndex][1] += restOfSelectionOutput;
        }
    }
    prepareRender(ctx) {
        // Build HTML for inner corners separate from HTML for the rest of selections,
        // as the inner corner HTML can interfere with that of other selections.
        // In final render, make sure to place the inner corner HTML before the rest of selection HTML. See issue #77777.
        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 i = 0, len = this._selections.length; i < len; i++) {
            const selection = this._selections[i];
            if (selection.isEmpty()) {
                thisFrameVisibleRangesWithStyle[i] = null;
                continue;
            }
            const visibleRangesWithStyle = this._getVisibleRangesWithStyle(selection, ctx, this._previousFrameVisibleRangesWithStyle[i]);
            thisFrameVisibleRangesWithStyle[i] = visibleRangesWithStyle;
            this._actualRenderOneSelection(output, visibleStartLineNumber, this._selections.length > 1, visibleRangesWithStyle);
        }
        this._previousFrameVisibleRangesWithStyle = thisFrameVisibleRangesWithStyle;
        this._renderResult = output.map(([internalCorners, restOfSelection]) => internalCorners + restOfSelection);
    }
    render(startLineNumber, lineNumber) {
        if (!this._renderResult) {
            return '';
        }
        const lineIndex = lineNumber - startLineNumber;
        if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
            return '';
        }
        return this._renderResult[lineIndex];
    }
}
SelectionsOverlay.SELECTION_CLASS_NAME = 'selected-text';
SelectionsOverlay.SELECTION_TOP_LEFT = 'top-left-radius';
SelectionsOverlay.SELECTION_BOTTOM_LEFT = 'bottom-left-radius';
SelectionsOverlay.SELECTION_TOP_RIGHT = 'top-right-radius';
SelectionsOverlay.SELECTION_BOTTOM_RIGHT = 'bottom-right-radius';
SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME = 'monaco-editor-background';
SelectionsOverlay.ROUNDED_PIECE_WIDTH = 10;
registerThemingParticipant((theme, collector) => {
    const editorSelectionColor = theme.getColor(editorSelectionBackground);
    if (editorSelectionColor) {
        collector.addRule(`.monaco-editor .focused .selected-text { background-color: ${editorSelectionColor}; }`);
    }
    const editorInactiveSelectionColor = theme.getColor(editorInactiveSelection);
    if (editorInactiveSelectionColor) {
        collector.addRule(`.monaco-editor .selected-text { background-color: ${editorInactiveSelectionColor}; }`);
    }
    const editorSelectionForegroundColor = theme.getColor(editorSelectionForeground);
    if (editorSelectionForegroundColor && !editorSelectionForegroundColor.isTransparent()) {
        collector.addRule(`.monaco-editor .view-line span.inline-selected-text { color: ${editorSelectionForegroundColor}; }`);
    }
});
function abs(n) {
    return n < 0 ? -n : n;
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/viewCursors/viewCursors.css
var viewCursors = __webpack_require__(51254);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/viewCursors/viewCursors.css

      
      
      
      
      
      
      
      
      

var viewCursors_options = {};

viewCursors_options.styleTagTransform = (styleTagTransform_default());
viewCursors_options.setAttributes = (setAttributesWithoutAttributes_default());

      viewCursors_options.insert = insertBySelector_default().bind(null, "head");
    
viewCursors_options.domAPI = (styleDomAPI_default());
viewCursors_options.insertStyleElement = (insertStyleElement_default());

var viewCursors_update = injectStylesIntoStyleTag_default()(viewCursors/* default */.A, viewCursors_options);




       /* harmony default export */ const viewCursors_viewCursors = (viewCursors/* default */.A && viewCursors/* default */.A.locals ? viewCursors/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/viewCursors/viewCursor.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/








class ViewCursorRenderData {
    constructor(top, left, width, height, textContent, textContentClassName) {
        this.top = top;
        this.left = left;
        this.width = width;
        this.height = height;
        this.textContent = textContent;
        this.textContentClassName = textContentClassName;
    }
}
class ViewCursor {
    constructor(context) {
        this._context = context;
        const options = this._context.configuration.options;
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        this._cursorStyle = options.get(24 /* EditorOption.cursorStyle */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
        this._lineCursorWidth = Math.min(options.get(27 /* EditorOption.cursorWidth */), this._typicalHalfwidthCharacterWidth);
        this._isVisible = true;
        // Create the dom node
        this._domNode = createFastDomNode(document.createElement('div'));
        this._domNode.setClassName(`cursor ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
        this._domNode.setHeight(this._lineHeight);
        this._domNode.setTop(0);
        this._domNode.setLeft(0);
        applyFontInfo(this._domNode, fontInfo);
        this._domNode.setDisplay('none');
        this._position = new Position(1, 1);
        this._lastRenderedContent = '';
        this._renderData = null;
    }
    getDomNode() {
        return this._domNode;
    }
    getPosition() {
        return this._position;
    }
    show() {
        if (!this._isVisible) {
            this._domNode.setVisibility('inherit');
            this._isVisible = true;
        }
    }
    hide() {
        if (this._isVisible) {
            this._domNode.setVisibility('hidden');
            this._isVisible = false;
        }
    }
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        this._cursorStyle = options.get(24 /* EditorOption.cursorStyle */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
        this._lineCursorWidth = Math.min(options.get(27 /* EditorOption.cursorWidth */), this._typicalHalfwidthCharacterWidth);
        applyFontInfo(this._domNode, fontInfo);
        return true;
    }
    onCursorPositionChanged(position) {
        this._position = position;
        return true;
    }
    /**
     * If `this._position` is inside a grapheme, returns the position where the grapheme starts.
     * Also returns the next grapheme.
     */
    _getGraphemeAwarePosition() {
        const { lineNumber, column } = this._position;
        const lineContent = this._context.viewModel.getLineContent(lineNumber);
        const [startOffset, endOffset] = getCharContainingOffset(lineContent, column - 1);
        return [new Position(lineNumber, startOffset + 1), lineContent.substring(startOffset, endOffset)];
    }
    _prepareRender(ctx) {
        let textContent = '';
        const [position, nextGrapheme] = this._getGraphemeAwarePosition();
        if (this._cursorStyle === TextEditorCursorStyle.Line || this._cursorStyle === TextEditorCursorStyle.LineThin) {
            const visibleRange = ctx.visibleRangeForPosition(position);
            if (!visibleRange || visibleRange.outsideRenderedLine) {
                // Outside viewport
                return null;
            }
            let width;
            if (this._cursorStyle === TextEditorCursorStyle.Line) {
                width = computeScreenAwareSize(this._lineCursorWidth > 0 ? this._lineCursorWidth : 2);
                if (width > 2) {
                    textContent = nextGrapheme;
                }
            }
            else {
                width = computeScreenAwareSize(1);
            }
            let left = visibleRange.left;
            if (width >= 2 && left >= 1) {
                // try to center cursor
                left -= 1;
            }
            const top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta;
            return new ViewCursorRenderData(top, left, width, this._lineHeight, textContent, '');
        }
        const visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new Range(position.lineNumber, position.column, position.lineNumber, position.column + nextGrapheme.length), false);
        if (!visibleRangeForCharacter || visibleRangeForCharacter.length === 0) {
            // Outside viewport
            return null;
        }
        const firstVisibleRangeForCharacter = visibleRangeForCharacter[0];
        if (firstVisibleRangeForCharacter.outsideRenderedLine || firstVisibleRangeForCharacter.ranges.length === 0) {
            // Outside viewport
            return null;
        }
        const range = firstVisibleRangeForCharacter.ranges[0];
        const width = (nextGrapheme === '\t'
            ? this._typicalHalfwidthCharacterWidth
            : (range.width < 1
                ? this._typicalHalfwidthCharacterWidth
                : range.width));
        let textContentClassName = '';
        if (this._cursorStyle === TextEditorCursorStyle.Block) {
            const lineData = this._context.viewModel.getViewLineData(position.lineNumber);
            textContent = nextGrapheme;
            const tokenIndex = lineData.tokens.findTokenIndexAtOffset(position.column - 1);
            textContentClassName = lineData.tokens.getClassName(tokenIndex);
        }
        let top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta;
        let height = this._lineHeight;
        // Underline might interfere with clicking
        if (this._cursorStyle === TextEditorCursorStyle.Underline || this._cursorStyle === TextEditorCursorStyle.UnderlineThin) {
            top += this._lineHeight - 2;
            height = 2;
        }
        return new ViewCursorRenderData(top, range.left, width, height, textContent, textContentClassName);
    }
    prepareRender(ctx) {
        this._renderData = this._prepareRender(ctx);
    }
    render(ctx) {
        if (!this._renderData) {
            this._domNode.setDisplay('none');
            return null;
        }
        if (this._lastRenderedContent !== this._renderData.textContent) {
            this._lastRenderedContent = this._renderData.textContent;
            this._domNode.domNode.textContent = this._lastRenderedContent;
        }
        this._domNode.setClassName(`cursor ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ${this._renderData.textContentClassName}`);
        this._domNode.setDisplay('block');
        this._domNode.setTop(this._renderData.top);
        this._domNode.setLeft(this._renderData.left);
        this._domNode.setWidth(this._renderData.width);
        this._domNode.setLineHeight(this._renderData.height);
        this._domNode.setHeight(this._renderData.height);
        return {
            domNode: this._domNode.domNode,
            position: this._position,
            contentLeft: this._renderData.left,
            height: this._renderData.height,
            width: 2
        };
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/viewCursors/viewCursors.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









class ViewCursors extends ViewPart {
    constructor(context) {
        super(context);
        const options = this._context.configuration.options;
        this._readOnly = options.get(83 /* EditorOption.readOnly */);
        this._cursorBlinking = options.get(22 /* EditorOption.cursorBlinking */);
        this._cursorStyle = options.get(24 /* EditorOption.cursorStyle */);
        this._cursorSmoothCaretAnimation = options.get(23 /* EditorOption.cursorSmoothCaretAnimation */);
        this._selectionIsEmpty = true;
        this._isComposingInput = false;
        this._isVisible = false;
        this._primaryCursor = new ViewCursor(this._context);
        this._secondaryCursors = [];
        this._renderData = [];
        this._domNode = createFastDomNode(document.createElement('div'));
        this._domNode.setAttribute('role', 'presentation');
        this._domNode.setAttribute('aria-hidden', 'true');
        this._updateDomClassName();
        this._domNode.appendChild(this._primaryCursor.getDomNode());
        this._startCursorBlinkAnimation = new TimeoutTimer();
        this._cursorFlatBlinkInterval = new IntervalTimer();
        this._blinkingEnabled = false;
        this._editorHasFocus = false;
        this._updateBlinking();
    }
    dispose() {
        super.dispose();
        this._startCursorBlinkAnimation.dispose();
        this._cursorFlatBlinkInterval.dispose();
    }
    getDomNode() {
        return this._domNode;
    }
    // --- begin event handlers
    onCompositionStart(e) {
        this._isComposingInput = true;
        this._updateBlinking();
        return true;
    }
    onCompositionEnd(e) {
        this._isComposingInput = false;
        this._updateBlinking();
        return true;
    }
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        this._readOnly = options.get(83 /* EditorOption.readOnly */);
        this._cursorBlinking = options.get(22 /* EditorOption.cursorBlinking */);
        this._cursorStyle = options.get(24 /* EditorOption.cursorStyle */);
        this._cursorSmoothCaretAnimation = options.get(23 /* EditorOption.cursorSmoothCaretAnimation */);
        this._updateBlinking();
        this._updateDomClassName();
        this._primaryCursor.onConfigurationChanged(e);
        for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
            this._secondaryCursors[i].onConfigurationChanged(e);
        }
        return true;
    }
    _onCursorPositionChanged(position, secondaryPositions) {
        this._primaryCursor.onCursorPositionChanged(position);
        this._updateBlinking();
        if (this._secondaryCursors.length < secondaryPositions.length) {
            // Create new cursors
            const addCnt = secondaryPositions.length - this._secondaryCursors.length;
            for (let i = 0; i < addCnt; i++) {
                const newCursor = new ViewCursor(this._context);
                this._domNode.domNode.insertBefore(newCursor.getDomNode().domNode, this._primaryCursor.getDomNode().domNode.nextSibling);
                this._secondaryCursors.push(newCursor);
            }
        }
        else if (this._secondaryCursors.length > secondaryPositions.length) {
            // Remove some cursors
            const removeCnt = this._secondaryCursors.length - secondaryPositions.length;
            for (let i = 0; i < removeCnt; i++) {
                this._domNode.removeChild(this._secondaryCursors[0].getDomNode());
                this._secondaryCursors.splice(0, 1);
            }
        }
        for (let i = 0; i < secondaryPositions.length; i++) {
            this._secondaryCursors[i].onCursorPositionChanged(secondaryPositions[i]);
        }
    }
    onCursorStateChanged(e) {
        const positions = [];
        for (let i = 0, len = e.selections.length; i < len; i++) {
            positions[i] = e.selections[i].getPosition();
        }
        this._onCursorPositionChanged(positions[0], positions.slice(1));
        const selectionIsEmpty = e.selections[0].isEmpty();
        if (this._selectionIsEmpty !== selectionIsEmpty) {
            this._selectionIsEmpty = selectionIsEmpty;
            this._updateDomClassName();
        }
        return true;
    }
    onDecorationsChanged(e) {
        // true for inline decorations that can end up relayouting text
        return true;
    }
    onFlushed(e) {
        return true;
    }
    onFocusChanged(e) {
        this._editorHasFocus = e.isFocused;
        this._updateBlinking();
        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 i = 0, len = e.ranges.length; i < len; i++) {
                if (e.ranges[i].fromLineNumber <= position.lineNumber && position.lineNumber <= e.ranges[i].toLineNumber) {
                    return true;
                }
            }
            return false;
        };
        if (shouldRender(this._primaryCursor.getPosition())) {
            return true;
        }
        for (const secondaryCursor of this._secondaryCursors) {
            if (shouldRender(secondaryCursor.getPosition())) {
                return true;
            }
        }
        return false;
    }
    onZonesChanged(e) {
        return true;
    }
    // --- end event handlers
    // ---- blinking logic
    _getCursorBlinking() {
        if (this._isComposingInput) {
            // avoid double cursors
            return 0 /* TextEditorCursorBlinkingStyle.Hidden */;
        }
        if (!this._editorHasFocus) {
            return 0 /* TextEditorCursorBlinkingStyle.Hidden */;
        }
        if (this._readOnly) {
            return 5 /* TextEditorCursorBlinkingStyle.Solid */;
        }
        return this._cursorBlinking;
    }
    _updateBlinking() {
        this._startCursorBlinkAnimation.cancel();
        this._cursorFlatBlinkInterval.cancel();
        const blinkingStyle = this._getCursorBlinking();
        // hidden and solid are special as they involve no animations
        const isHidden = (blinkingStyle === 0 /* TextEditorCursorBlinkingStyle.Hidden */);
        const isSolid = (blinkingStyle === 5 /* TextEditorCursorBlinkingStyle.Solid */);
        if (isHidden) {
            this._hide();
        }
        else {
            this._show();
        }
        this._blinkingEnabled = false;
        this._updateDomClassName();
        if (!isHidden && !isSolid) {
            if (blinkingStyle === 1 /* TextEditorCursorBlinkingStyle.Blink */) {
                // flat blinking is handled by JavaScript to save battery life due to Chromium step timing issue https://bugs.chromium.org/p/chromium/issues/detail?id=361587
                this._cursorFlatBlinkInterval.cancelAndSet(() => {
                    if (this._isVisible) {
                        this._hide();
                    }
                    else {
                        this._show();
                    }
                }, ViewCursors.BLINK_INTERVAL);
            }
            else {
                this._startCursorBlinkAnimation.setIfNotSet(() => {
                    this._blinkingEnabled = true;
                    this._updateDomClassName();
                }, ViewCursors.BLINK_INTERVAL);
            }
        }
    }
    // --- end blinking logic
    _updateDomClassName() {
        this._domNode.setClassName(this._getClassName());
    }
    _getClassName() {
        let result = 'cursors-layer';
        if (!this._selectionIsEmpty) {
            result += ' has-selection';
        }
        switch (this._cursorStyle) {
            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._blinkingEnabled) {
            switch (this._getCursorBlinking()) {
                case 1 /* TextEditorCursorBlinkingStyle.Blink */:
                    result += ' cursor-blink';
                    break;
                case 2 /* TextEditorCursorBlinkingStyle.Smooth */:
                    result += ' cursor-smooth';
                    break;
                case 3 /* TextEditorCursorBlinkingStyle.Phase */:
                    result += ' cursor-phase';
                    break;
                case 4 /* TextEditorCursorBlinkingStyle.Expand */:
                    result += ' cursor-expand';
                    break;
                case 5 /* TextEditorCursorBlinkingStyle.Solid */:
                    result += ' cursor-solid';
                    break;
                default:
                    result += ' cursor-solid';
            }
        }
        else {
            result += ' cursor-solid';
        }
        if (this._cursorSmoothCaretAnimation) {
            result += ' cursor-smooth-caret-animation';
        }
        return result;
    }
    _show() {
        this._primaryCursor.show();
        for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
            this._secondaryCursors[i].show();
        }
        this._isVisible = true;
    }
    _hide() {
        this._primaryCursor.hide();
        for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
            this._secondaryCursors[i].hide();
        }
        this._isVisible = false;
    }
    // ---- IViewPart implementation
    prepareRender(ctx) {
        this._primaryCursor.prepareRender(ctx);
        for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
            this._secondaryCursors[i].prepareRender(ctx);
        }
    }
    render(ctx) {
        const renderData = [];
        let renderDataLen = 0;
        const primaryRenderData = this._primaryCursor.render(ctx);
        if (primaryRenderData) {
            renderData[renderDataLen++] = primaryRenderData;
        }
        for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
            const secondaryRenderData = this._secondaryCursors[i].render(ctx);
            if (secondaryRenderData) {
                renderData[renderDataLen++] = secondaryRenderData;
            }
        }
        this._renderData = renderData;
    }
    getLastRenderData() {
        return this._renderData;
    }
}
ViewCursors.BLINK_INTERVAL = 500;
registerThemingParticipant((theme, collector) => {
    const caret = theme.getColor(editorCursorForeground);
    if (caret) {
        let caretBackground = theme.getColor(editorCursorBackground);
        if (!caretBackground) {
            caretBackground = caret.opposite();
        }
        collector.addRule(`.monaco-editor .inputarea.ime-input { caret-color: ${caret}; }`);
        collector.addRule(`.monaco-editor .cursors-layer .cursor { background-color: ${caret}; border-color: ${caret}; color: ${caretBackground}; }`);
        if (isHighContrast(theme.type)) {
            collector.addRule(`.monaco-editor .cursors-layer.has-selection .cursor { border-left: 1px solid ${caretBackground}; border-right: 1px solid ${caretBackground}; }`);
        }
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/viewZones/viewZones.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




const viewZones_invalidFunc = () => { throw new Error(`Invalid change accessor`); };
class ViewZones extends ViewPart {
    constructor(context) {
        super(context);
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._contentWidth = layoutInfo.contentWidth;
        this._contentLeft = layoutInfo.contentLeft;
        this.domNode = createFastDomNode(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 = createFastDomNode(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._zones = {};
    }
    dispose() {
        super.dispose();
        this._zones = {};
    }
    // ---- begin view event handlers
    _recomputeWhitespacesProps() {
        const whitespaces = this._context.viewLayout.getWhitespaces();
        const oldWhitespaces = 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._zones);
            for (let i = 0, len = keys.length; i < len; i++) {
                const id = keys[i];
                const zone = this._zones[id];
                const props = this._computeWhitespaceProps(zone.delegate);
                zone.isInHiddenArea = props.isInHiddenArea;
                const oldWhitespace = oldWhitespaces.get(id);
                if (oldWhitespace && (oldWhitespace.afterLineNumber !== props.afterViewLineNumber || oldWhitespace.height !== props.heightInPx)) {
                    whitespaceAccessor.changeOneWhitespace(id, props.afterViewLineNumber, props.heightInPx);
                    this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
                    hadAChange = true;
                }
            }
        });
        return hadAChange;
    }
    onConfigurationChanged(e) {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this._lineHeight = options.get(61 /* EditorOption.lineHeight */);
        this._contentWidth = layoutInfo.contentWidth;
        this._contentLeft = layoutInfo.contentLeft;
        if (e.hasChanged(61 /* EditorOption.lineHeight */)) {
            this._recomputeWhitespacesProps();
        }
        return true;
    }
    onLineMappingChanged(e) {
        return this._recomputeWhitespacesProps();
    }
    onLinesDeleted(e) {
        return true;
    }
    onScrollChanged(e) {
        return e.scrollTopChanged || e.scrollWidthChanged;
    }
    onZonesChanged(e) {
        return true;
    }
    onLinesInserted(e) {
        return true;
    }
    // ---- end view event handlers
    _getZoneOrdinal(zone) {
        if (typeof zone.afterColumn !== 'undefined') {
            return zone.afterColumn;
        }
        return 10000;
    }
    _computeWhitespaceProps(zone) {
        if (zone.afterLineNumber === 0) {
            return {
                isInHiddenArea: false,
                afterViewLineNumber: 0,
                heightInPx: this._heightInPixels(zone),
                minWidthInPx: this._minWidthInPixels(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 Position(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);
        const isVisible = this._context.viewModel.coordinatesConverter.modelPositionIsVisible(zoneBeforeModelPosition);
        return {
            isInHiddenArea: !isVisible,
            afterViewLineNumber: viewPosition.lineNumber,
            heightInPx: (isVisible ? this._heightInPixels(zone) : 0),
            minWidthInPx: this._minWidthInPixels(zone)
        };
    }
    changeViewZones(callback) {
        let zonesHaveChanged = false;
        this._context.viewModel.changeWhitespace((whitespaceAccessor) => {
            const changeAccessor = {
                addZone: (zone) => {
                    zonesHaveChanged = true;
                    return this._addZone(whitespaceAccessor, zone);
                },
                removeZone: (id) => {
                    if (!id) {
                        return;
                    }
                    zonesHaveChanged = this._removeZone(whitespaceAccessor, id) || zonesHaveChanged;
                },
                layoutZone: (id) => {
                    if (!id) {
                        return;
                    }
                    zonesHaveChanged = this._layoutZone(whitespaceAccessor, id) || zonesHaveChanged;
                }
            };
            safeInvoke1Arg(callback, changeAccessor);
            // Invalidate changeAccessor
            changeAccessor.addZone = viewZones_invalidFunc;
            changeAccessor.removeZone = viewZones_invalidFunc;
            changeAccessor.layoutZone = viewZones_invalidFunc;
        });
        return zonesHaveChanged;
    }
    _addZone(whitespaceAccessor, zone) {
        const props = this._computeWhitespaceProps(zone);
        const whitespaceId = whitespaceAccessor.insertWhitespace(props.afterViewLineNumber, this._getZoneOrdinal(zone), props.heightInPx, props.minWidthInPx);
        const myZone = {
            whitespaceId: whitespaceId,
            delegate: zone,
            isInHiddenArea: props.isInHiddenArea,
            isVisible: false,
            domNode: createFastDomNode(zone.domNode),
            marginDomNode: zone.marginDomNode ? createFastDomNode(zone.marginDomNode) : null
        };
        this._safeCallOnComputedHeight(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._zones[myZone.whitespaceId] = myZone;
        this.setShouldRender();
        return myZone.whitespaceId;
    }
    _removeZone(whitespaceAccessor, id) {
        if (this._zones.hasOwnProperty(id)) {
            const zone = this._zones[id];
            delete this._zones[id];
            whitespaceAccessor.removeWhitespace(zone.whitespaceId);
            zone.domNode.removeAttribute('monaco-visible-view-zone');
            zone.domNode.removeAttribute('monaco-view-zone');
            zone.domNode.domNode.parentNode.removeChild(zone.domNode.domNode);
            if (zone.marginDomNode) {
                zone.marginDomNode.removeAttribute('monaco-visible-view-zone');
                zone.marginDomNode.removeAttribute('monaco-view-zone');
                zone.marginDomNode.domNode.parentNode.removeChild(zone.marginDomNode.domNode);
            }
            this.setShouldRender();
            return true;
        }
        return false;
    }
    _layoutZone(whitespaceAccessor, id) {
        if (this._zones.hasOwnProperty(id)) {
            const zone = this._zones[id];
            const props = this._computeWhitespaceProps(zone.delegate);
            zone.isInHiddenArea = props.isInHiddenArea;
            // const newOrdinal = this._getZoneOrdinal(zone.delegate);
            whitespaceAccessor.changeOneWhitespace(zone.whitespaceId, props.afterViewLineNumber, props.heightInPx);
            // TODO@Alex: change `newOrdinal` too
            this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
            this.setShouldRender();
            return true;
        }
        return false;
    }
    shouldSuppressMouseDownOnViewZone(id) {
        if (this._zones.hasOwnProperty(id)) {
            const zone = this._zones[id];
            return Boolean(zone.delegate.suppressMouseDown);
        }
        return false;
    }
    _heightInPixels(zone) {
        if (typeof zone.heightInPx === 'number') {
            return zone.heightInPx;
        }
        if (typeof zone.heightInLines === 'number') {
            return this._lineHeight * zone.heightInLines;
        }
        return this._lineHeight;
    }
    _minWidthInPixels(zone) {
        if (typeof zone.minWidthInPx === 'number') {
            return zone.minWidthInPx;
        }
        return 0;
    }
    _safeCallOnComputedHeight(zone, height) {
        if (typeof zone.onComputedHeight === 'function') {
            try {
                zone.onComputedHeight(height);
            }
            catch (e) {
                onUnexpectedError(e);
            }
        }
    }
    _safeCallOnDomNodeTop(zone, top) {
        if (typeof zone.onDomNodeTop === 'function') {
            try {
                zone.onDomNodeTop(top);
            }
            catch (e) {
                onUnexpectedError(e);
            }
        }
    }
    prepareRender(ctx) {
        // Nothing to read
    }
    render(ctx) {
        const visibleWhitespaces = ctx.viewportData.whitespaceViewportData;
        const visibleZones = {};
        let hasVisibleZone = false;
        for (const visibleWhitespace of visibleWhitespaces) {
            if (this._zones[visibleWhitespace.id].isInHiddenArea) {
                continue;
            }
            visibleZones[visibleWhitespace.id] = visibleWhitespace;
            hasVisibleZone = true;
        }
        const keys = Object.keys(this._zones);
        for (let i = 0, len = keys.length; i < len; i++) {
            const id = keys[i];
            const zone = this._zones[id];
            let newTop = 0;
            let newHeight = 0;
            let newDisplay = 'none';
            if (visibleZones.hasOwnProperty(id)) {
                newTop = visibleZones[id].verticalOffset - ctx.bigNumbersDelta;
                newHeight = visibleZones[id].height;
                newDisplay = 'block';
                // zone is visible
                if (!zone.isVisible) {
                    zone.domNode.setAttribute('monaco-visible-view-zone', 'true');
                    zone.isVisible = true;
                }
                this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(visibleZones[id].verticalOffset));
            }
            else {
                if (zone.isVisible) {
                    zone.domNode.removeAttribute('monaco-visible-view-zone');
                    zone.isVisible = false;
                }
                this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(-1000000));
            }
            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._contentWidth));
            this.marginDomNode.setWidth(this._contentLeft);
        }
    }
}
function safeInvoke1Arg(func, arg1) {
    try {
        return func(arg1);
    }
    catch (e) {
        onUnexpectedError(e);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/editorTheme.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class EditorTheme {
    constructor(theme) {
        this._theme = theme;
    }
    get type() {
        return this._theme.type;
    }
    get value() {
        return this._theme;
    }
    update(theme) {
        this._theme = theme;
    }
    getColor(color) {
        return this._theme.getColor(color);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewModel/viewContext.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class ViewContext {
    constructor(configuration, theme, model) {
        this.configuration = configuration;
        this.theme = new EditorTheme(theme);
        this.viewModel = model;
        this.viewLayout = model.viewLayout;
    }
    addEventHandler(eventHandler) {
        this.viewModel.addViewEventHandler(eventHandler);
    }
    removeEventHandler(eventHandler) {
        this.viewModel.removeViewEventHandler(eventHandler);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewLayout/viewLinesViewportData.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/**
 * Contains all data needed to render at a specific viewport.
 */
class ViewportData {
    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.whitespaceViewportData = whitespaceViewportData;
        this._model = model;
        this.visibleRange = new Range(partialData.startLineNumber, this._model.getLineMinColumn(partialData.startLineNumber), partialData.endLineNumber, this._model.getLineMaxColumn(partialData.endLineNumber));
    }
    getViewLineRenderingData(lineNumber) {
        return this._model.getViewportViewLineRenderingData(this.visibleRange, lineNumber);
    }
    getDecorationsInViewport() {
        return this._model.getDecorationsInViewport(this.visibleRange);
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/blockDecorations/blockDecorations.css
var blockDecorations = __webpack_require__(2904);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/blockDecorations/blockDecorations.css

      
      
      
      
      
      
      
      
      

var blockDecorations_options = {};

blockDecorations_options.styleTagTransform = (styleTagTransform_default());
blockDecorations_options.setAttributes = (setAttributesWithoutAttributes_default());

      blockDecorations_options.insert = insertBySelector_default().bind(null, "head");
    
blockDecorations_options.domAPI = (styleDomAPI_default());
blockDecorations_options.insertStyleElement = (insertStyleElement_default());

var blockDecorations_update = injectStylesIntoStyleTag_default()(blockDecorations/* default */.A, blockDecorations_options);




       /* harmony default export */ const blockDecorations_blockDecorations = (blockDecorations/* default */.A && blockDecorations/* default */.A.locals ? blockDecorations/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/blockDecorations/blockDecorations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class BlockDecorations extends ViewPart {
    constructor(context) {
        super(context);
        this.blocks = [];
        this.contentWidth = -1;
        this.domNode = createFastDomNode(document.createElement('div'));
        this.domNode.setAttribute('role', 'presentation');
        this.domNode.setAttribute('aria-hidden', 'true');
        this.domNode.setClassName('blockDecorations-container');
        this.update();
    }
    update() {
        let didChange = false;
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        const newContentWidth = layoutInfo.contentWidth - layoutInfo.verticalScrollbarWidth;
        if (this.contentWidth !== newContentWidth) {
            this.contentWidth = newContentWidth;
            didChange = true;
        }
        return didChange;
    }
    dispose() {
        super.dispose();
    }
    // --- begin event handlers
    onConfigurationChanged(e) {
        return this.update();
    }
    onScrollChanged(e) {
        return e.scrollTopChanged || e.scrollLeftChanged;
    }
    onDecorationsChanged(e) {
        return true;
    }
    onZonesChanged(e) {
        return true;
    }
    // --- end event handlers
    prepareRender(ctx) {
        // Nothing to read
    }
    render(ctx) {
        let count = 0;
        const decorations = ctx.getDecorationsInViewport();
        for (const decoration of decorations) {
            if (!decoration.options.blockClassName) {
                continue;
            }
            let block = this.blocks[count];
            if (!block) {
                block = this.blocks[count] = createFastDomNode(document.createElement('div'));
                this.domNode.appendChild(block);
            }
            const top = ctx.getVerticalOffsetForLineNumber(decoration.range.startLineNumber);
            // See https://github.com/microsoft/vscode/pull/152740#discussion_r902661546
            const bottom = ctx.getVerticalOffsetForLineNumber(decoration.range.endLineNumber + 1);
            block.setClassName('blockDecorations-block ' + decoration.options.blockClassName);
            block.setLeft(ctx.scrollLeft);
            block.setWidth(this.contentWidth);
            block.setTop(top);
            block.setHeight(bottom - top);
            count++;
        }
        for (let i = count; i < this.blocks.length; i++) {
            this.blocks[i].domNode.remove();
        }
        this.blocks.length = count;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/view.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







































class View extends ViewEventHandler {
    constructor(commandDelegate, configuration, colorTheme, model, userInputEvents, overflowWidgetsDomNode) {
        super();
        this._selections = [new Selection(1, 1, 1, 1)];
        this._renderAnimationFrame = null;
        const viewController = new ViewController(configuration, model, userInputEvents, commandDelegate);
        // The view context is passed on to most classes (basically to reduce param. counts in ctors)
        this._context = new ViewContext(configuration, colorTheme, model);
        // Ensure the view is the first event handler in order to update the layout
        this._context.addEventHandler(this);
        this._viewParts = [];
        // Keyboard handler
        this._textAreaHandler = new TextAreaHandler(this._context, viewController, this._createTextAreaHandlerHelper());
        this._viewParts.push(this._textAreaHandler);
        // These two dom nodes must be constructed up front, since references are needed in the layout provider (scrolling & co.)
        this._linesContent = createFastDomNode(document.createElement('div'));
        this._linesContent.setClassName('lines-content' + ' monaco-editor-background');
        this._linesContent.setPosition('absolute');
        this.domNode = createFastDomNode(document.createElement('div'));
        this.domNode.setClassName(this._getEditorClassName());
        // Set role 'code' for better screen reader support https://github.com/microsoft/vscode/issues/93438
        this.domNode.setAttribute('role', 'code');
        this._overflowGuardContainer = createFastDomNode(document.createElement('div'));
        PartFingerprints.write(this._overflowGuardContainer, 3 /* PartFingerprint.OverflowGuard */);
        this._overflowGuardContainer.setClassName('overflow-guard');
        this._scrollbar = new editorScrollbar_EditorScrollbar(this._context, this._linesContent, this.domNode, this._overflowGuardContainer);
        this._viewParts.push(this._scrollbar);
        // View Lines
        this._viewLines = new ViewLines(this._context, this._linesContent);
        // View Zones
        this._viewZones = new ViewZones(this._context);
        this._viewParts.push(this._viewZones);
        // Decorations overview ruler
        const decorationsOverviewRuler = new DecorationsOverviewRuler(this._context);
        this._viewParts.push(decorationsOverviewRuler);
        const scrollDecoration = new ScrollDecorationViewPart(this._context);
        this._viewParts.push(scrollDecoration);
        const contentViewOverlays = new ContentViewOverlays(this._context);
        this._viewParts.push(contentViewOverlays);
        contentViewOverlays.addDynamicOverlay(new CurrentLineHighlightOverlay(this._context));
        contentViewOverlays.addDynamicOverlay(new SelectionsOverlay(this._context));
        contentViewOverlays.addDynamicOverlay(new IndentGuidesOverlay(this._context));
        contentViewOverlays.addDynamicOverlay(new DecorationsOverlay(this._context));
        const marginViewOverlays = new MarginViewOverlays(this._context);
        this._viewParts.push(marginViewOverlays);
        marginViewOverlays.addDynamicOverlay(new CurrentLineMarginHighlightOverlay(this._context));
        marginViewOverlays.addDynamicOverlay(new GlyphMarginOverlay(this._context));
        marginViewOverlays.addDynamicOverlay(new MarginViewLineDecorationsOverlay(this._context));
        marginViewOverlays.addDynamicOverlay(new LinesDecorationsOverlay(this._context));
        marginViewOverlays.addDynamicOverlay(new LineNumbersOverlay(this._context));
        const margin = new Margin(this._context);
        margin.getDomNode().appendChild(this._viewZones.marginDomNode);
        margin.getDomNode().appendChild(marginViewOverlays.getDomNode());
        this._viewParts.push(margin);
        // Content widgets
        this._contentWidgets = new ViewContentWidgets(this._context, this.domNode);
        this._viewParts.push(this._contentWidgets);
        this._viewCursors = new ViewCursors(this._context);
        this._viewParts.push(this._viewCursors);
        // Overlay widgets
        this._overlayWidgets = new ViewOverlayWidgets(this._context);
        this._viewParts.push(this._overlayWidgets);
        const rulers = new Rulers(this._context);
        this._viewParts.push(rulers);
        const blockOutline = new BlockDecorations(this._context);
        this._viewParts.push(blockOutline);
        const minimap = new Minimap(this._context);
        this._viewParts.push(minimap);
        // -------------- Wire dom nodes up
        if (decorationsOverviewRuler) {
            const overviewRulerData = this._scrollbar.getOverviewRulerLayoutInfo();
            overviewRulerData.parent.insertBefore(decorationsOverviewRuler.getDomNode(), overviewRulerData.insertBefore);
        }
        this._linesContent.appendChild(contentViewOverlays.getDomNode());
        this._linesContent.appendChild(rulers.domNode);
        this._linesContent.appendChild(blockOutline.domNode);
        this._linesContent.appendChild(this._viewZones.domNode);
        this._linesContent.appendChild(this._viewLines.getDomNode());
        this._linesContent.appendChild(this._contentWidgets.domNode);
        this._linesContent.appendChild(this._viewCursors.getDomNode());
        this._overflowGuardContainer.appendChild(margin.getDomNode());
        this._overflowGuardContainer.appendChild(this._scrollbar.getDomNode());
        this._overflowGuardContainer.appendChild(scrollDecoration.getDomNode());
        this._overflowGuardContainer.appendChild(this._textAreaHandler.textArea);
        this._overflowGuardContainer.appendChild(this._textAreaHandler.textAreaCover);
        this._overflowGuardContainer.appendChild(this._overlayWidgets.getDomNode());
        this._overflowGuardContainer.appendChild(minimap.getDomNode());
        this.domNode.appendChild(this._overflowGuardContainer);
        if (overflowWidgetsDomNode) {
            overflowWidgetsDomNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode.domNode);
        }
        else {
            this.domNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode);
        }
        this._applyLayout();
        // Pointer handler
        this._pointerHandler = this._register(new PointerHandler(this._context, viewController, this._createPointerHandlerHelper()));
    }
    _flushAccumulatedAndRenderNow() {
        this._renderNow();
    }
    _createPointerHandlerHelper() {
        return {
            viewDomNode: this.domNode.domNode,
            linesContentDomNode: this._linesContent.domNode,
            viewLinesDomNode: this._viewLines.getDomNode().domNode,
            focusTextArea: () => {
                this.focus();
            },
            dispatchTextAreaEvent: (event) => {
                this._textAreaHandler.textArea.domNode.dispatchEvent(event);
            },
            getLastRenderData: () => {
                const lastViewCursorsRenderData = this._viewCursors.getLastRenderData() || [];
                const lastTextareaPosition = this._textAreaHandler.getLastRenderData();
                return new PointerHandlerLastRenderData(lastViewCursorsRenderData, lastTextareaPosition);
            },
            shouldSuppressMouseDownOnViewZone: (viewZoneId) => {
                return this._viewZones.shouldSuppressMouseDownOnViewZone(viewZoneId);
            },
            shouldSuppressMouseDownOnWidget: (widgetId) => {
                return this._contentWidgets.shouldSuppressMouseDownOnWidget(widgetId);
            },
            getPositionFromDOMInfo: (spanNode, offset) => {
                this._flushAccumulatedAndRenderNow();
                return this._viewLines.getPositionFromDOMInfo(spanNode, offset);
            },
            visibleRangeForPosition: (lineNumber, column) => {
                this._flushAccumulatedAndRenderNow();
                return this._viewLines.visibleRangeForPosition(new Position(lineNumber, column));
            },
            getLineWidth: (lineNumber) => {
                this._flushAccumulatedAndRenderNow();
                return this._viewLines.getLineWidth(lineNumber);
            }
        };
    }
    _createTextAreaHandlerHelper() {
        return {
            visibleRangeForPosition: (position) => {
                this._flushAccumulatedAndRenderNow();
                return this._viewLines.visibleRangeForPosition(position);
            }
        };
    }
    _applyLayout() {
        const options = this._context.configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        this.domNode.setWidth(layoutInfo.width);
        this.domNode.setHeight(layoutInfo.height);
        this._overflowGuardContainer.setWidth(layoutInfo.width);
        this._overflowGuardContainer.setHeight(layoutInfo.height);
        this._linesContent.setWidth(1000000);
        this._linesContent.setHeight(1000000);
    }
    _getEditorClassName() {
        const focused = this._textAreaHandler.isFocused() ? ' focused' : '';
        return this._context.configuration.options.get(130 /* EditorOption.editorClassName */) + ' ' + getThemeTypeSelector(this._context.theme.type) + focused;
    }
    // --- begin event handlers
    handleEvents(events) {
        super.handleEvents(events);
        this._scheduleRender();
    }
    onConfigurationChanged(e) {
        this.domNode.setClassName(this._getEditorClassName());
        this._applyLayout();
        return false;
    }
    onCursorStateChanged(e) {
        this._selections = e.selections;
        return false;
    }
    onFocusChanged(e) {
        this.domNode.setClassName(this._getEditorClassName());
        return false;
    }
    onThemeChanged(e) {
        this._context.theme.update(e.theme);
        this.domNode.setClassName(this._getEditorClassName());
        return false;
    }
    // --- end event handlers
    dispose() {
        if (this._renderAnimationFrame !== null) {
            this._renderAnimationFrame.dispose();
            this._renderAnimationFrame = null;
        }
        this._contentWidgets.overflowingContentWidgetsDomNode.domNode.remove();
        this._context.removeEventHandler(this);
        this._viewLines.dispose();
        // Destroy view parts
        for (const viewPart of this._viewParts) {
            viewPart.dispose();
        }
        super.dispose();
    }
    _scheduleRender() {
        if (this._renderAnimationFrame === null) {
            this._renderAnimationFrame = runAtThisOrScheduleAtNextAnimationFrame(this._onRenderScheduled.bind(this), 100);
        }
    }
    _onRenderScheduled() {
        this._renderAnimationFrame = null;
        this._flushAccumulatedAndRenderNow();
    }
    _renderNow() {
        safeInvokeNoArg(() => this._actualRender());
    }
    _getViewPartsToRender() {
        const result = [];
        let resultLen = 0;
        for (const viewPart of this._viewParts) {
            if (viewPart.shouldRender()) {
                result[resultLen++] = viewPart;
            }
        }
        return result;
    }
    _actualRender() {
        if (!isInDOM(this.domNode.domNode)) {
            return;
        }
        let viewPartsToRender = this._getViewPartsToRender();
        if (!this._viewLines.shouldRender() && viewPartsToRender.length === 0) {
            // Nothing to render
            return;
        }
        const partialViewportData = this._context.viewLayout.getLinesViewportData();
        this._context.viewModel.setViewport(partialViewportData.startLineNumber, partialViewportData.endLineNumber, partialViewportData.centeredLineNumber);
        const viewportData = new ViewportData(this._selections, partialViewportData, this._context.viewLayout.getWhitespaceViewportData(), this._context.viewModel);
        if (this._contentWidgets.shouldRender()) {
            // Give the content widgets a chance to set their max width before a possible synchronous layout
            this._contentWidgets.onBeforeRender(viewportData);
        }
        if (this._viewLines.shouldRender()) {
            this._viewLines.renderText(viewportData);
            this._viewLines.onDidRender();
            // Rendering of viewLines might cause scroll events to occur, so collect view parts to render again
            viewPartsToRender = this._getViewPartsToRender();
        }
        const renderingContext = new RenderingContext(this._context.viewLayout, viewportData, this._viewLines);
        // Render the rest of the parts
        for (const viewPart of viewPartsToRender) {
            viewPart.prepareRender(renderingContext);
        }
        for (const viewPart of viewPartsToRender) {
            viewPart.render(renderingContext);
            viewPart.onDidRender();
        }
    }
    // --- BEGIN CodeEditor helpers
    delegateVerticalScrollbarPointerDown(browserEvent) {
        this._scrollbar.delegateVerticalScrollbarPointerDown(browserEvent);
    }
    restoreState(scrollPosition) {
        this._context.viewModel.viewLayout.setScrollPosition({ scrollTop: scrollPosition.scrollTop }, 1 /* ScrollType.Immediate */);
        this._context.viewModel.tokenizeViewport();
        this._renderNow();
        this._viewLines.updateLineWidths();
        this._context.viewModel.viewLayout.setScrollPosition({ scrollLeft: scrollPosition.scrollLeft }, 1 /* ScrollType.Immediate */);
    }
    getOffsetForColumn(modelLineNumber, modelColumn) {
        const modelPosition = this._context.viewModel.model.validatePosition({
            lineNumber: modelLineNumber,
            column: modelColumn
        });
        const viewPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
        this._flushAccumulatedAndRenderNow();
        const visibleRange = this._viewLines.visibleRangeForPosition(new Position(viewPosition.lineNumber, viewPosition.column));
        if (!visibleRange) {
            return -1;
        }
        return visibleRange.left;
    }
    getTargetAtClientPoint(clientX, clientY) {
        const mouseTarget = this._pointerHandler.getTargetAtClientPoint(clientX, clientY);
        if (!mouseTarget) {
            return null;
        }
        return ViewUserInputEvents.convertViewToModelMouseTarget(mouseTarget, this._context.viewModel.coordinatesConverter);
    }
    createOverviewRuler(cssClassName) {
        return new OverviewRuler(this._context, cssClassName);
    }
    change(callback) {
        this._viewZones.changeViewZones(callback);
        this._scheduleRender();
    }
    render(now, everything) {
        if (everything) {
            // Force everything to render...
            this._viewLines.forceShouldRender();
            for (const viewPart of this._viewParts) {
                viewPart.forceShouldRender();
            }
        }
        if (now) {
            this._flushAccumulatedAndRenderNow();
        }
        else {
            this._scheduleRender();
        }
    }
    focus() {
        this._textAreaHandler.focusTextArea();
    }
    isFocused() {
        return this._textAreaHandler.isFocused();
    }
    setAriaOptions(options) {
        this._textAreaHandler.setAriaOptions(options);
    }
    addContentWidget(widgetData) {
        this._contentWidgets.addWidget(widgetData.widget);
        this.layoutContentWidget(widgetData);
        this._scheduleRender();
    }
    layoutContentWidget(widgetData) {
        var _a, _b;
        let newRange = widgetData.position ? widgetData.position.range || null : null;
        if (newRange === null) {
            const newPosition = widgetData.position ? widgetData.position.position : null;
            if (newPosition !== null) {
                newRange = new Range(newPosition.lineNumber, newPosition.column, newPosition.lineNumber, newPosition.column);
            }
        }
        const newPreference = widgetData.position ? widgetData.position.preference : null;
        this._contentWidgets.setWidgetPosition(widgetData.widget, newRange, newPreference, (_b = (_a = widgetData.position) === null || _a === void 0 ? void 0 : _a.positionAffinity) !== null && _b !== void 0 ? _b : null);
        this._scheduleRender();
    }
    removeContentWidget(widgetData) {
        this._contentWidgets.removeWidget(widgetData.widget);
        this._scheduleRender();
    }
    addOverlayWidget(widgetData) {
        this._overlayWidgets.addWidget(widgetData.widget);
        this.layoutOverlayWidget(widgetData);
        this._scheduleRender();
    }
    layoutOverlayWidget(widgetData) {
        const newPreference = widgetData.position ? widgetData.position.preference : null;
        const shouldRender = this._overlayWidgets.setWidgetPosition(widgetData.widget, newPreference);
        if (shouldRender) {
            this._scheduleRender();
        }
    }
    removeOverlayWidget(widgetData) {
        this._overlayWidgets.removeWidget(widgetData.widget);
        this._scheduleRender();
    }
}
function safeInvokeNoArg(func) {
    try {
        return func();
    }
    catch (e) {
        onUnexpectedError(e);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursor/oneCursor.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




/**
 * Represents a single cursor.
*/
class Cursor {
    constructor(context) {
        this._selTrackedRange = null;
        this._trackSelection = true;
        this._setState(context, new SingleCursorState(new Range(1, 1, 1, 1), 0, new Position(1, 1), 0), new SingleCursorState(new Range(1, 1, 1, 1), 0, new Position(1, 1), 0));
    }
    dispose(context) {
        this._removeTrackedRange(context);
    }
    startTrackingSelection(context) {
        this._trackSelection = true;
        this._updateTrackedRange(context);
    }
    stopTrackingSelection(context) {
        this._trackSelection = false;
        this._removeTrackedRange(context);
    }
    _updateTrackedRange(context) {
        if (!this._trackSelection) {
            // don't track the selection
            return;
        }
        this._selTrackedRange = context.model._setTrackedRange(this._selTrackedRange, this.modelState.selection, 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */);
    }
    _removeTrackedRange(context) {
        this._selTrackedRange = context.model._setTrackedRange(this._selTrackedRange, null, 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */);
    }
    asCursorState() {
        return new CursorState(this.modelState, this.viewState);
    }
    readSelectionFromMarkers(context) {
        const range = context.model._getTrackedRange(this._selTrackedRange);
        return Selection.fromRange(range, this.modelState.selection.getDirection());
    }
    ensureValidState(context) {
        this._setState(context, this.modelState, this.viewState);
    }
    setState(context, modelState, viewState) {
        this._setState(context, modelState, viewState);
    }
    static _validatePositionWithCache(viewModel, position, cacheInput, cacheOutput) {
        if (position.equals(cacheInput)) {
            return cacheOutput;
        }
        return viewModel.normalizePosition(position, 2 /* PositionAffinity.None */);
    }
    static _validateViewState(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._validatePositionWithCache(viewModel, sStartPosition, position, validPosition);
        const validSEndPosition = this._validatePositionWithCache(viewModel, sEndPosition, sStartPosition, validSStartPosition);
        if (position.equals(validPosition) && sStartPosition.equals(validSStartPosition) && sEndPosition.equals(validSEndPosition)) {
            // fast path: the state is valid
            return viewState;
        }
        return new SingleCursorState(Range.fromPositions(validSStartPosition, validSEndPosition), viewState.selectionStartLeftoverVisibleColumns + sStartPosition.column - validSStartPosition.column, validPosition, viewState.leftoverVisibleColumns + position.column - validPosition.column);
    }
    _setState(context, modelState, viewState) {
        if (viewState) {
            viewState = Cursor._validateViewState(context.viewModel, viewState);
        }
        if (!modelState) {
            if (!viewState) {
                return;
            }
            // We only have the view state => compute the model state
            const selectionStart = context.model.validateRange(context.coordinatesConverter.convertViewRangeToModelRange(viewState.selectionStart));
            const position = context.model.validatePosition(context.coordinatesConverter.convertViewPositionToModelPosition(viewState.position));
            modelState = new SingleCursorState(selectionStart, viewState.selectionStartLeftoverVisibleColumns, position, viewState.leftoverVisibleColumns);
        }
        else {
            // Validate new model state
            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 SingleCursorState(selectionStart, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns);
        }
        if (!viewState) {
            // We only have the model state => compute the view state
            const viewSelectionStart1 = context.coordinatesConverter.convertModelPositionToViewPosition(new Position(modelState.selectionStart.startLineNumber, modelState.selectionStart.startColumn));
            const viewSelectionStart2 = context.coordinatesConverter.convertModelPositionToViewPosition(new Position(modelState.selectionStart.endLineNumber, modelState.selectionStart.endColumn));
            const viewSelectionStart = new Range(viewSelectionStart1.lineNumber, viewSelectionStart1.column, viewSelectionStart2.lineNumber, viewSelectionStart2.column);
            const viewPosition = context.coordinatesConverter.convertModelPositionToViewPosition(modelState.position);
            viewState = new SingleCursorState(viewSelectionStart, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
        }
        else {
            // Validate new view state
            const viewSelectionStart = context.coordinatesConverter.validateViewRange(viewState.selectionStart, modelState.selectionStart);
            const viewPosition = context.coordinatesConverter.validateViewPosition(viewState.position, modelState.position);
            viewState = new SingleCursorState(viewSelectionStart, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
        }
        this.modelState = modelState;
        this.viewState = viewState;
        this._updateTrackedRange(context);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursor/cursorCollection.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class CursorCollection {
    constructor(context) {
        this.context = context;
        this.cursors = [new Cursor(context)];
        this.lastAddedCursorIndex = 0;
    }
    dispose() {
        for (const cursor of this.cursors) {
            cursor.dispose(this.context);
        }
    }
    startTrackingSelections() {
        for (const cursor of this.cursors) {
            cursor.startTrackingSelection(this.context);
        }
    }
    stopTrackingSelections() {
        for (const cursor of this.cursors) {
            cursor.stopTrackingSelection(this.context);
        }
    }
    updateContext(context) {
        this.context = context;
    }
    ensureValidState() {
        for (const cursor of this.cursors) {
            cursor.ensureValidState(this.context);
        }
    }
    readSelectionFromMarkers() {
        return this.cursors.map(c => c.readSelectionFromMarkers(this.context));
    }
    getAll() {
        return this.cursors.map(c => c.asCursorState());
    }
    getViewPositions() {
        return this.cursors.map(c => c.viewState.position);
    }
    getTopMostViewPosition() {
        return findMinBy(this.cursors, compareBy(c => c.viewState.position, Position.compare)).viewState.position;
    }
    getBottomMostViewPosition() {
        return findLastMaxBy(this.cursors, compareBy(c => c.viewState.position, Position.compare)).viewState.position;
    }
    getSelections() {
        return this.cursors.map(c => c.modelState.selection);
    }
    getViewSelections() {
        return this.cursors.map(c => c.viewState.selection);
    }
    setSelections(selections) {
        this.setStates(CursorState.fromModelSelections(selections));
    }
    getPrimaryCursor() {
        return this.cursors[0].asCursorState();
    }
    setStates(states) {
        if (states === null) {
            return;
        }
        this.cursors[0].setState(this.context, states[0].modelState, states[0].viewState);
        this._setSecondaryStates(states.slice(1));
    }
    /**
     * Creates or disposes secondary cursors as necessary to match the number of `secondarySelections`.
     */
    _setSecondaryStates(secondaryStates) {
        const secondaryCursorsLength = this.cursors.length - 1;
        const secondaryStatesLength = secondaryStates.length;
        if (secondaryCursorsLength < secondaryStatesLength) {
            const createCnt = secondaryStatesLength - secondaryCursorsLength;
            for (let i = 0; i < createCnt; i++) {
                this._addSecondaryCursor();
            }
        }
        else if (secondaryCursorsLength > secondaryStatesLength) {
            const removeCnt = secondaryCursorsLength - secondaryStatesLength;
            for (let i = 0; i < removeCnt; i++) {
                this._removeSecondaryCursor(this.cursors.length - 2);
            }
        }
        for (let i = 0; i < secondaryStatesLength; i++) {
            this.cursors[i + 1].setState(this.context, secondaryStates[i].modelState, secondaryStates[i].viewState);
        }
    }
    killSecondaryCursors() {
        this._setSecondaryStates([]);
    }
    _addSecondaryCursor() {
        this.cursors.push(new Cursor(this.context));
        this.lastAddedCursorIndex = this.cursors.length - 1;
    }
    getLastAddedCursorIndex() {
        if (this.cursors.length === 1 || this.lastAddedCursorIndex === 0) {
            return 0;
        }
        return this.lastAddedCursorIndex;
    }
    _removeSecondaryCursor(removeIndex) {
        if (this.lastAddedCursorIndex >= removeIndex + 1) {
            this.lastAddedCursorIndex--;
        }
        this.cursors[removeIndex + 1].dispose(this.context);
        this.cursors.splice(removeIndex + 1, 1);
    }
    normalize() {
        if (this.cursors.length === 1) {
            return;
        }
        const cursors = this.cursors.slice(0);
        const sortedCursors = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
            sortedCursors.push({
                index: i,
                selection: cursors[i].modelState.selection,
            });
        }
        sortedCursors.sort(compareBy(s => s.selection, Range.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.context.cursorConfig.multiCursorMergeOverlapping) {
                continue;
            }
            let shouldMergeCursors;
            if (nextSelection.isEmpty() || currentSelection.isEmpty()) {
                // Merge touching cursors if one of them is collapsed
                shouldMergeCursors = nextSelection.getStartPosition().isBeforeOrEqual(currentSelection.getEndPosition());
            }
            else {
                // Merge only overlapping cursors (i.e. allow touching ranges)
                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);
                    // Give more importance to the last added cursor (think Ctrl-dragging + hitting another cursor)
                    let resultingSelectionIsLTR;
                    if (looserIndex === this.lastAddedCursorIndex) {
                        resultingSelectionIsLTR = looserSelectionIsLTR;
                        this.lastAddedCursorIndex = winnerIndex;
                    }
                    else {
                        // Winner takes it all
                        resultingSelectionIsLTR = winnerSelectionIsLTR;
                    }
                    let resultingSelection;
                    if (resultingSelectionIsLTR) {
                        resultingSelection = new Selection(resultingRange.startLineNumber, resultingRange.startColumn, resultingRange.endLineNumber, resultingRange.endColumn);
                    }
                    else {
                        resultingSelection = new Selection(resultingRange.endLineNumber, resultingRange.endColumn, resultingRange.startLineNumber, resultingRange.startColumn);
                    }
                    sortedCursors[winnerSortedCursorIndex].selection = resultingSelection;
                    const resultingState = CursorState.fromModelSelection(resultingSelection);
                    cursors[winnerIndex].setState(this.context, resultingState.modelState, resultingState.viewState);
                }
                for (const sortedCursor of sortedCursors) {
                    if (sortedCursor.index > looserIndex) {
                        sortedCursor.index--;
                    }
                }
                cursors.splice(looserIndex, 1);
                sortedCursors.splice(looserSortedCursorIndex, 1);
                this._removeSecondaryCursor(looserIndex - 1);
                sortedCursorIndex--;
            }
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursor/cursorContext.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class CursorContext {
    constructor(model, viewModel, coordinatesConverter, cursorConfig) {
        this._cursorContextBrand = undefined;
        this.model = model;
        this.viewModel = viewModel;
        this.coordinatesConverter = coordinatesConverter;
        this.cursorConfig = cursorConfig;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewEvents.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class ViewCompositionStartEvent {
    constructor() {
        this.type = 0 /* ViewEventType.ViewCompositionStart */;
    }
}
class ViewCompositionEndEvent {
    constructor() {
        this.type = 1 /* ViewEventType.ViewCompositionEnd */;
    }
}
class ViewConfigurationChangedEvent {
    constructor(source) {
        this.type = 2 /* ViewEventType.ViewConfigurationChanged */;
        this._source = source;
    }
    hasChanged(id) {
        return this._source.hasChanged(id);
    }
}
class ViewCursorStateChangedEvent {
    constructor(selections, modelSelections) {
        this.type = 3 /* ViewEventType.ViewCursorStateChanged */;
        this.selections = selections;
        this.modelSelections = modelSelections;
    }
}
class ViewDecorationsChangedEvent {
    constructor(source) {
        this.type = 4 /* ViewEventType.ViewDecorationsChanged */;
        if (source) {
            this.affectsMinimap = source.affectsMinimap;
            this.affectsOverviewRuler = source.affectsOverviewRuler;
        }
        else {
            this.affectsMinimap = true;
            this.affectsOverviewRuler = true;
        }
    }
}
class ViewFlushedEvent {
    constructor() {
        this.type = 5 /* ViewEventType.ViewFlushed */;
        // Nothing to do
    }
}
class ViewFocusChangedEvent {
    constructor(isFocused) {
        this.type = 6 /* ViewEventType.ViewFocusChanged */;
        this.isFocused = isFocused;
    }
}
class ViewLanguageConfigurationEvent {
    constructor() {
        this.type = 7 /* ViewEventType.ViewLanguageConfigurationChanged */;
    }
}
class ViewLineMappingChangedEvent {
    constructor() {
        this.type = 8 /* ViewEventType.ViewLineMappingChanged */;
        // Nothing to do
    }
}
class ViewLinesChangedEvent {
    constructor(
    /**
     * The first line that has changed.
     */
    fromLineNumber, 
    /**
     * The number of lines that have changed.
     */
    count) {
        this.fromLineNumber = fromLineNumber;
        this.count = count;
        this.type = 9 /* ViewEventType.ViewLinesChanged */;
    }
}
class ViewLinesDeletedEvent {
    constructor(fromLineNumber, toLineNumber) {
        this.type = 10 /* ViewEventType.ViewLinesDeleted */;
        this.fromLineNumber = fromLineNumber;
        this.toLineNumber = toLineNumber;
    }
}
class ViewLinesInsertedEvent {
    constructor(fromLineNumber, toLineNumber) {
        this.type = 11 /* ViewEventType.ViewLinesInserted */;
        this.fromLineNumber = fromLineNumber;
        this.toLineNumber = toLineNumber;
    }
}
class ViewRevealRangeRequestEvent {
    constructor(
    /**
     * Source of the call that caused the event.
     */
    source, 
    /**
     * Reduce the revealing to a minimum (e.g. avoid scrolling if the bounding box is visible and near the viewport edge).
     */
    minimalReveal, 
    /**
     * Range to be reavealed.
     */
    range, 
    /**
     * Selections to be revealed.
     */
    selections, 
    /**
     * The vertical reveal strategy.
     */
    verticalType, 
    /**
     * If true: there should be a horizontal & vertical revealing.
     * If false: there should be just a vertical revealing.
     */
    revealHorizontal, 
    /**
     * The scroll type.
     */
    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 /* ViewEventType.ViewRevealRangeRequest */;
    }
}
class ViewScrollChangedEvent {
    constructor(source) {
        this.type = 13 /* ViewEventType.ViewScrollChanged */;
        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;
    }
}
class ViewThemeChangedEvent {
    constructor(theme) {
        this.theme = theme;
        this.type = 14 /* ViewEventType.ViewThemeChanged */;
    }
}
class ViewTokensChangedEvent {
    constructor(ranges) {
        this.type = 15 /* ViewEventType.ViewTokensChanged */;
        this.ranges = ranges;
    }
}
class ViewTokensColorsChangedEvent {
    constructor() {
        this.type = 16 /* ViewEventType.ViewTokensColorsChanged */;
        // Nothing to do
    }
}
class ViewZonesChangedEvent {
    constructor() {
        this.type = 17 /* ViewEventType.ViewZonesChanged */;
        // Nothing to do
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewModelEventDispatcher.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class ViewModelEventDispatcher extends Disposable {
    constructor() {
        super();
        this._onEvent = this._register(new Emitter());
        this.onEvent = this._onEvent.event;
        this._eventHandlers = [];
        this._viewEventQueue = null;
        this._isConsumingViewEventQueue = false;
        this._collector = null;
        this._collectorCnt = 0;
        this._outgoingEvents = [];
    }
    emitOutgoingEvent(e) {
        this._addOutgoingEvent(e);
        this._emitOutgoingEvents();
    }
    _addOutgoingEvent(e) {
        for (let i = 0, len = this._outgoingEvents.length; i < len; i++) {
            const mergeResult = (this._outgoingEvents[i].kind === e.kind ? this._outgoingEvents[i].attemptToMerge(e) : null);
            if (mergeResult) {
                this._outgoingEvents[i] = mergeResult;
                return;
            }
        }
        // not merged
        this._outgoingEvents.push(e);
    }
    _emitOutgoingEvents() {
        while (this._outgoingEvents.length > 0) {
            if (this._collector || this._isConsumingViewEventQueue) {
                // right now collecting or emitting view events, so let's postpone emitting
                return;
            }
            const event = this._outgoingEvents.shift();
            if (event.isNoOp()) {
                continue;
            }
            this._onEvent.fire(event);
        }
    }
    addViewEventHandler(eventHandler) {
        for (let i = 0, len = this._eventHandlers.length; i < len; i++) {
            if (this._eventHandlers[i] === eventHandler) {
                console.warn('Detected duplicate listener in ViewEventDispatcher', eventHandler);
            }
        }
        this._eventHandlers.push(eventHandler);
    }
    removeViewEventHandler(eventHandler) {
        for (let i = 0; i < this._eventHandlers.length; i++) {
            if (this._eventHandlers[i] === eventHandler) {
                this._eventHandlers.splice(i, 1);
                break;
            }
        }
    }
    beginEmitViewEvents() {
        this._collectorCnt++;
        if (this._collectorCnt === 1) {
            this._collector = new ViewModelEventsCollector();
        }
        return this._collector;
    }
    endEmitViewEvents() {
        this._collectorCnt--;
        if (this._collectorCnt === 0) {
            const outgoingEvents = this._collector.outgoingEvents;
            const viewEvents = this._collector.viewEvents;
            this._collector = null;
            for (const outgoingEvent of outgoingEvents) {
                this._addOutgoingEvent(outgoingEvent);
            }
            if (viewEvents.length > 0) {
                this._emitMany(viewEvents);
            }
        }
        this._emitOutgoingEvents();
    }
    emitSingleViewEvent(event) {
        try {
            const eventsCollector = this.beginEmitViewEvents();
            eventsCollector.emitViewEvent(event);
        }
        finally {
            this.endEmitViewEvents();
        }
    }
    _emitMany(events) {
        if (this._viewEventQueue) {
            this._viewEventQueue = this._viewEventQueue.concat(events);
        }
        else {
            this._viewEventQueue = events;
        }
        if (!this._isConsumingViewEventQueue) {
            this._consumeViewEventQueue();
        }
    }
    _consumeViewEventQueue() {
        try {
            this._isConsumingViewEventQueue = true;
            this._doConsumeQueue();
        }
        finally {
            this._isConsumingViewEventQueue = false;
        }
    }
    _doConsumeQueue() {
        while (this._viewEventQueue) {
            // Empty event queue, as events might come in while sending these off
            const events = this._viewEventQueue;
            this._viewEventQueue = null;
            // Use a clone of the event handlers list, as they might remove themselves
            const eventHandlers = this._eventHandlers.slice(0);
            for (const eventHandler of eventHandlers) {
                eventHandler.handleEvents(events);
            }
        }
    }
}
class ViewModelEventsCollector {
    constructor() {
        this.viewEvents = [];
        this.outgoingEvents = [];
    }
    emitViewEvent(event) {
        this.viewEvents.push(event);
    }
    emitOutgoingEvent(e) {
        this.outgoingEvents.push(e);
    }
}
class ContentSizeChangedEvent {
    constructor(oldContentWidth, oldContentHeight, contentWidth, contentHeight) {
        this.kind = 0 /* OutgoingViewModelEventKind.ContentSizeChanged */;
        this._oldContentWidth = oldContentWidth;
        this._oldContentHeight = oldContentHeight;
        this.contentWidth = contentWidth;
        this.contentHeight = contentHeight;
        this.contentWidthChanged = (this._oldContentWidth !== this.contentWidth);
        this.contentHeightChanged = (this._oldContentHeight !== this.contentHeight);
    }
    isNoOp() {
        return (!this.contentWidthChanged && !this.contentHeightChanged);
    }
    attemptToMerge(other) {
        if (other.kind !== this.kind) {
            return null;
        }
        return new ContentSizeChangedEvent(this._oldContentWidth, this._oldContentHeight, other.contentWidth, other.contentHeight);
    }
}
class FocusChangedEvent {
    constructor(oldHasFocus, hasFocus) {
        this.kind = 1 /* OutgoingViewModelEventKind.FocusChanged */;
        this.oldHasFocus = oldHasFocus;
        this.hasFocus = hasFocus;
    }
    isNoOp() {
        return (this.oldHasFocus === this.hasFocus);
    }
    attemptToMerge(other) {
        if (other.kind !== this.kind) {
            return null;
        }
        return new FocusChangedEvent(this.oldHasFocus, other.hasFocus);
    }
}
class ScrollChangedEvent {
    constructor(oldScrollWidth, oldScrollLeft, oldScrollHeight, oldScrollTop, scrollWidth, scrollLeft, scrollHeight, scrollTop) {
        this.kind = 2 /* OutgoingViewModelEventKind.ScrollChanged */;
        this._oldScrollWidth = oldScrollWidth;
        this._oldScrollLeft = oldScrollLeft;
        this._oldScrollHeight = oldScrollHeight;
        this._oldScrollTop = oldScrollTop;
        this.scrollWidth = scrollWidth;
        this.scrollLeft = scrollLeft;
        this.scrollHeight = scrollHeight;
        this.scrollTop = scrollTop;
        this.scrollWidthChanged = (this._oldScrollWidth !== this.scrollWidth);
        this.scrollLeftChanged = (this._oldScrollLeft !== this.scrollLeft);
        this.scrollHeightChanged = (this._oldScrollHeight !== this.scrollHeight);
        this.scrollTopChanged = (this._oldScrollTop !== this.scrollTop);
    }
    isNoOp() {
        return (!this.scrollWidthChanged && !this.scrollLeftChanged && !this.scrollHeightChanged && !this.scrollTopChanged);
    }
    attemptToMerge(other) {
        if (other.kind !== this.kind) {
            return null;
        }
        return new ScrollChangedEvent(this._oldScrollWidth, this._oldScrollLeft, this._oldScrollHeight, this._oldScrollTop, other.scrollWidth, other.scrollLeft, other.scrollHeight, other.scrollTop);
    }
}
class viewModelEventDispatcher_ViewZonesChangedEvent {
    constructor() {
        this.kind = 3 /* OutgoingViewModelEventKind.ViewZonesChanged */;
    }
    isNoOp() {
        return false;
    }
    attemptToMerge(other) {
        if (other.kind !== this.kind) {
            return null;
        }
        return this;
    }
}
class HiddenAreasChangedEvent {
    constructor() {
        this.kind = 4 /* OutgoingViewModelEventKind.HiddenAreasChanged */;
    }
    isNoOp() {
        return false;
    }
    attemptToMerge(other) {
        if (other.kind !== this.kind) {
            return null;
        }
        return this;
    }
}
class CursorStateChangedEvent {
    constructor(oldSelections, selections, oldModelVersionId, modelVersionId, source, reason, reachedMaxCursorCount) {
        this.kind = 6 /* OutgoingViewModelEventKind.CursorStateChanged */;
        this.oldSelections = oldSelections;
        this.selections = selections;
        this.oldModelVersionId = oldModelVersionId;
        this.modelVersionId = modelVersionId;
        this.source = source;
        this.reason = reason;
        this.reachedMaxCursorCount = reachedMaxCursorCount;
    }
    static _selectionsAreEqual(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 i = 0; i < aLen; i++) {
            if (!a[i].equalsSelection(b[i])) {
                return false;
            }
        }
        return true;
    }
    isNoOp() {
        return (CursorStateChangedEvent._selectionsAreEqual(this.oldSelections, this.selections)
            && this.oldModelVersionId === this.modelVersionId);
    }
    attemptToMerge(other) {
        if (other.kind !== this.kind) {
            return null;
        }
        return new CursorStateChangedEvent(this.oldSelections, other.selections, this.oldModelVersionId, other.modelVersionId, other.source, other.reason, this.reachedMaxCursorCount || other.reachedMaxCursorCount);
    }
}
class ReadOnlyEditAttemptEvent {
    constructor() {
        this.kind = 5 /* OutgoingViewModelEventKind.ReadOnlyEditAttempt */;
    }
    isNoOp() {
        return false;
    }
    attemptToMerge(other) {
        if (other.kind !== this.kind) {
            return null;
        }
        return this;
    }
}
class ModelDecorationsChangedEvent {
    constructor(event) {
        this.event = event;
        this.kind = 7 /* OutgoingViewModelEventKind.ModelDecorationsChanged */;
    }
    isNoOp() {
        return false;
    }
    attemptToMerge(other) {
        return null;
    }
}
class ModelLanguageChangedEvent {
    constructor(event) {
        this.event = event;
        this.kind = 8 /* OutgoingViewModelEventKind.ModelLanguageChanged */;
    }
    isNoOp() {
        return false;
    }
    attemptToMerge(other) {
        return null;
    }
}
class ModelLanguageConfigurationChangedEvent {
    constructor(event) {
        this.event = event;
        this.kind = 9 /* OutgoingViewModelEventKind.ModelLanguageConfigurationChanged */;
    }
    isNoOp() {
        return false;
    }
    attemptToMerge(other) {
        return null;
    }
}
class ModelContentChangedEvent {
    constructor(event) {
        this.event = event;
        this.kind = 10 /* OutgoingViewModelEventKind.ModelContentChanged */;
    }
    isNoOp() {
        return false;
    }
    attemptToMerge(other) {
        return null;
    }
}
class ModelOptionsChangedEvent {
    constructor(event) {
        this.event = event;
        this.kind = 11 /* OutgoingViewModelEventKind.ModelOptionsChanged */;
    }
    isNoOp() {
        return false;
    }
    attemptToMerge(other) {
        return null;
    }
}
class ModelTokensChangedEvent {
    constructor(event) {
        this.event = event;
        this.kind = 12 /* OutgoingViewModelEventKind.ModelTokensChanged */;
    }
    isNoOp() {
        return false;
    }
    attemptToMerge(other) {
        return null;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/cursor/cursor.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/













class CursorsController extends Disposable {
    constructor(model, viewModel, coordinatesConverter, cursorConfig) {
        super();
        this._model = model;
        this._knownModelVersionId = this._model.getVersionId();
        this._viewModel = viewModel;
        this._coordinatesConverter = coordinatesConverter;
        this.context = new CursorContext(this._model, this._viewModel, this._coordinatesConverter, cursorConfig);
        this._cursors = new CursorCollection(this.context);
        this._hasFocus = false;
        this._isHandling = false;
        this._compositionState = null;
        this._columnSelectData = null;
        this._autoClosedActions = [];
        this._prevEditOperationType = 0 /* EditOperationType.Other */;
    }
    dispose() {
        this._cursors.dispose();
        this._autoClosedActions = dispose(this._autoClosedActions);
        super.dispose();
    }
    updateConfiguration(cursorConfig) {
        this.context = new CursorContext(this._model, this._viewModel, this._coordinatesConverter, cursorConfig);
        this._cursors.updateContext(this.context);
    }
    onLineMappingChanged(eventsCollector) {
        if (this._knownModelVersionId !== this._model.getVersionId()) {
            // There are model change events that I didn't yet receive.
            //
            // This can happen when editing the model, and the view model receives the change events first,
            // and the view model emits line mapping changed events, all before the cursor gets a chance to
            // recover from markers.
            //
            // The model change listener above will be called soon and we'll ensure a valid cursor state there.
            return;
        }
        // Ensure valid state
        this.setStates(eventsCollector, 'viewModel', 0 /* CursorChangeReason.NotSet */, this.getCursorStates());
    }
    setHasFocus(hasFocus) {
        this._hasFocus = hasFocus;
    }
    _validateAutoClosedActions() {
        if (this._autoClosedActions.length > 0) {
            const selections = this._cursors.getSelections();
            for (let i = 0; i < this._autoClosedActions.length; i++) {
                const autoClosedAction = this._autoClosedActions[i];
                if (!autoClosedAction.isValid(selections)) {
                    autoClosedAction.dispose();
                    this._autoClosedActions.splice(i, 1);
                    i--;
                }
            }
        }
    }
    // ------ some getters/setters
    getPrimaryCursorState() {
        return this._cursors.getPrimaryCursor();
    }
    getLastAddedCursorIndex() {
        return this._cursors.getLastAddedCursorIndex();
    }
    getCursorStates() {
        return this._cursors.getAll();
    }
    setStates(eventsCollector, source, reason, states) {
        let reachedMaxCursorCount = false;
        if (states !== null && states.length > CursorsController.MAX_CURSOR_COUNT) {
            states = states.slice(0, CursorsController.MAX_CURSOR_COUNT);
            reachedMaxCursorCount = true;
        }
        const oldState = CursorModelState.from(this._model, this);
        this._cursors.setStates(states);
        this._cursors.normalize();
        this._columnSelectData = null;
        this._validateAutoClosedActions();
        return this._emitStateChangedIfNecessary(eventsCollector, source, reason, oldState, reachedMaxCursorCount);
    }
    setCursorColumnSelectData(columnSelectData) {
        this._columnSelectData = columnSelectData;
    }
    revealPrimary(eventsCollector, source, minimalReveal, verticalType, revealHorizontal, scrollType) {
        const viewPositions = this._cursors.getViewPositions();
        let revealViewRange = null;
        let revealViewSelections = null;
        if (viewPositions.length > 1) {
            revealViewSelections = this._cursors.getViewSelections();
        }
        else {
            revealViewRange = Range.fromPositions(viewPositions[0], viewPositions[0]);
        }
        eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source, minimalReveal, revealViewRange, revealViewSelections, verticalType, revealHorizontal, scrollType));
    }
    saveState() {
        const result = [];
        const selections = this._cursors.getSelections();
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            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 i = 0, len = states.length; i < len; i++) {
            const state = states[i];
            let positionLineNumber = 1;
            let positionColumn = 1;
            // Avoid missing properties on the literal
            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;
            // Avoid missing properties on the literal
            if (state.selectionStart && state.selectionStart.lineNumber) {
                selectionStartLineNumber = state.selectionStart.lineNumber;
            }
            if (state.selectionStart && state.selectionStart.column) {
                selectionStartColumn = state.selectionStart.column;
            }
            desiredSelections.push({
                selectionStartLineNumber: selectionStartLineNumber,
                selectionStartColumn: selectionStartColumn,
                positionLineNumber: positionLineNumber,
                positionColumn: positionColumn
            });
        }
        this.setStates(eventsCollector, 'restoreState', 0 /* CursorChangeReason.NotSet */, CursorState.fromModelSelections(desiredSelections));
        this.revealPrimary(eventsCollector, 'restoreState', false, 0 /* VerticalRevealType.Simple */, true, 1 /* editorCommon.ScrollType.Immediate */);
    }
    onModelContentChanged(eventsCollector, event) {
        if (event instanceof ModelInjectedTextChangedEvent) {
            // If injected texts change, the view positions of all cursors need to be updated.
            if (this._isHandling) {
                // The view positions will be updated when handling finishes
                return;
            }
            // setStates might remove markers, which could trigger a decoration change.
            // If there are injected text decorations for that line, `onModelContentChanged` is emitted again
            // and an endless recursion happens.
            // _isHandling prevents that.
            this._isHandling = true;
            try {
                this.setStates(eventsCollector, 'modelChange', 0 /* CursorChangeReason.NotSet */, this.getCursorStates());
            }
            finally {
                this._isHandling = false;
            }
        }
        else {
            const e = event.rawContentChangedEvent;
            this._knownModelVersionId = e.versionId;
            if (this._isHandling) {
                return;
            }
            const hadFlushEvent = e.containsEvent(1 /* RawContentChangedType.Flush */);
            this._prevEditOperationType = 0 /* EditOperationType.Other */;
            if (hadFlushEvent) {
                // a model.setValue() was called
                this._cursors.dispose();
                this._cursors = new CursorCollection(this.context);
                this._validateAutoClosedActions();
                this._emitStateChangedIfNecessary(eventsCollector, 'model', 1 /* CursorChangeReason.ContentFlush */, null, false);
            }
            else {
                if (this._hasFocus && e.resultingSelection && e.resultingSelection.length > 0) {
                    const cursorState = CursorState.fromModelSelections(e.resultingSelection);
                    if (this.setStates(eventsCollector, 'modelChange', e.isUndoing ? 5 /* CursorChangeReason.Undo */ : e.isRedoing ? 6 /* CursorChangeReason.Redo */ : 2 /* CursorChangeReason.RecoverFromMarkers */, cursorState)) {
                        this.revealPrimary(eventsCollector, 'modelChange', false, 0 /* VerticalRevealType.Simple */, true, 0 /* editorCommon.ScrollType.Smooth */);
                    }
                }
                else {
                    const selectionsFromMarkers = this._cursors.readSelectionFromMarkers();
                    this.setStates(eventsCollector, 'modelChange', 2 /* CursorChangeReason.RecoverFromMarkers */, CursorState.fromModelSelections(selectionsFromMarkers));
                }
            }
        }
    }
    getSelection() {
        return this._cursors.getPrimaryCursor().modelState.selection;
    }
    getTopMostViewPosition() {
        return this._cursors.getTopMostViewPosition();
    }
    getBottomMostViewPosition() {
        return this._cursors.getBottomMostViewPosition();
    }
    getCursorColumnSelectData() {
        if (this._columnSelectData) {
            return this._columnSelectData;
        }
        const primaryCursor = this._cursors.getPrimaryCursor();
        const viewSelectionStart = primaryCursor.viewState.selectionStart.getStartPosition();
        const viewPosition = primaryCursor.viewState.position;
        return {
            isReal: false,
            fromViewLineNumber: viewSelectionStart.lineNumber,
            fromViewVisualColumn: this.context.cursorConfig.visibleColumnFromColumn(this._viewModel, viewSelectionStart),
            toViewLineNumber: viewPosition.lineNumber,
            toViewVisualColumn: this.context.cursorConfig.visibleColumnFromColumn(this._viewModel, viewPosition),
        };
    }
    getSelections() {
        return this._cursors.getSelections();
    }
    setSelections(eventsCollector, source, selections, reason) {
        this.setStates(eventsCollector, source, reason, CursorState.fromModelSelections(selections));
    }
    getPrevEditOperationType() {
        return this._prevEditOperationType;
    }
    setPrevEditOperationType(type) {
        this._prevEditOperationType = type;
    }
    // ------ auxiliary handling logic
    _pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges) {
        const autoClosedCharactersDeltaDecorations = [];
        const autoClosedEnclosingDeltaDecorations = [];
        for (let i = 0, len = autoClosedCharactersRanges.length; i < len; i++) {
            autoClosedCharactersDeltaDecorations.push({
                range: autoClosedCharactersRanges[i],
                options: {
                    description: 'auto-closed-character',
                    inlineClassName: 'auto-closed-character',
                    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
                }
            });
            autoClosedEnclosingDeltaDecorations.push({
                range: autoClosedEnclosingRanges[i],
                options: {
                    description: 'auto-closed-enclosing',
                    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
                }
            });
        }
        const autoClosedCharactersDecorations = this._model.deltaDecorations([], autoClosedCharactersDeltaDecorations);
        const autoClosedEnclosingDecorations = this._model.deltaDecorations([], autoClosedEnclosingDeltaDecorations);
        this._autoClosedActions.push(new AutoClosedAction(this._model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations));
    }
    _executeEditOperation(opResult) {
        if (!opResult) {
            // Nothing to execute
            return;
        }
        if (opResult.shouldPushStackElementBefore) {
            this._model.pushStackElement();
        }
        const result = CommandExecutor.executeCommands(this._model, this._cursors.getSelections(), opResult.commands);
        if (result) {
            // The commands were applied correctly
            this._interpretCommandResult(result);
            // Check for auto-closing closed characters
            const autoClosedCharactersRanges = [];
            const autoClosedEnclosingRanges = [];
            for (let i = 0; i < opResult.commands.length; i++) {
                const command = opResult.commands[i];
                if (command instanceof TypeWithAutoClosingCommand && command.enclosingRange && command.closeCharacterRange) {
                    autoClosedCharactersRanges.push(command.closeCharacterRange);
                    autoClosedEnclosingRanges.push(command.enclosingRange);
                }
            }
            if (autoClosedCharactersRanges.length > 0) {
                this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
            }
            this._prevEditOperationType = opResult.type;
        }
        if (opResult.shouldPushStackElementAfter) {
            this._model.pushStackElement();
        }
    }
    _interpretCommandResult(cursorState) {
        if (!cursorState || cursorState.length === 0) {
            cursorState = this._cursors.readSelectionFromMarkers();
        }
        this._columnSelectData = null;
        this._cursors.setSelections(cursorState);
        this._cursors.normalize();
    }
    // -----------------------------------------------------------------------------------------------------------
    // ----- emitting events
    _emitStateChangedIfNecessary(eventsCollector, source, reason, oldState, reachedMaxCursorCount) {
        const newState = CursorModelState.from(this._model, this);
        if (newState.equals(oldState)) {
            return false;
        }
        const selections = this._cursors.getSelections();
        const viewSelections = this._cursors.getViewSelections();
        // Let the view get the event first.
        eventsCollector.emitViewEvent(new ViewCursorStateChangedEvent(viewSelections, selections));
        // Only after the view has been notified, let the rest of the world know...
        if (!oldState
            || oldState.cursorState.length !== newState.cursorState.length
            || newState.cursorState.some((newCursorState, i) => !newCursorState.modelState.equals(oldState.cursorState[i].modelState))) {
            const oldSelections = oldState ? oldState.cursorState.map(s => s.modelState.selection) : null;
            const oldModelVersionId = oldState ? oldState.modelVersionId : 0;
            eventsCollector.emitOutgoingEvent(new CursorStateChangedEvent(oldSelections, selections, oldModelVersionId, newState.modelVersionId, source || 'keyboard', reason, reachedMaxCursorCount));
        }
        return true;
    }
    // -----------------------------------------------------------------------------------------------------------
    // ----- handlers beyond this point
    _findAutoClosingPairs(edits) {
        if (!edits.length) {
            return null;
        }
        const indices = [];
        for (let i = 0, len = edits.length; i < len; i++) {
            const edit = edits[i];
            if (!edit.text || edit.text.indexOf('\n') >= 0) {
                return null;
            }
            const m = edit.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 = edit.text.length - m[2].length - 1;
            const openCharIndex = edit.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._findAutoClosingPairs(edits);
        }
        if (autoClosingIndices) {
            edits[0]._isTracked = true;
        }
        const autoClosedCharactersRanges = [];
        const autoClosedEnclosingRanges = [];
        const selections = this._model.pushEditOperations(this.getSelections(), edits, (undoEdits) => {
            if (autoClosingIndices) {
                for (let i = 0, len = autoClosingIndices.length; i < len; i++) {
                    const [openCharInnerIndex, closeCharInnerIndex] = autoClosingIndices[i];
                    const undoEdit = undoEdits[i];
                    const lineNumber = undoEdit.range.startLineNumber;
                    const openCharIndex = undoEdit.range.startColumn - 1 + openCharInnerIndex;
                    const closeCharIndex = undoEdit.range.startColumn - 1 + closeCharInnerIndex;
                    autoClosedCharactersRanges.push(new Range(lineNumber, closeCharIndex + 1, lineNumber, closeCharIndex + 2));
                    autoClosedEnclosingRanges.push(new Range(lineNumber, openCharIndex + 1, lineNumber, closeCharIndex + 2));
                }
            }
            const selections = cursorStateComputer(undoEdits);
            if (selections) {
                // Don't recover the selection from markers because
                // we know what it should be.
                this._isHandling = true;
            }
            return selections;
        });
        if (selections) {
            this._isHandling = false;
            this.setSelections(eventsCollector, source, selections, 0 /* CursorChangeReason.NotSet */);
        }
        if (autoClosedCharactersRanges.length > 0) {
            this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
        }
    }
    _executeEdit(callback, eventsCollector, source, cursorChangeReason = 0 /* CursorChangeReason.NotSet */) {
        if (this.context.cursorConfig.readOnly) {
            // we cannot edit when read only...
            return;
        }
        const oldState = CursorModelState.from(this._model, this);
        this._cursors.stopTrackingSelections();
        this._isHandling = true;
        try {
            this._cursors.ensureValidState();
            callback();
        }
        catch (err) {
            onUnexpectedError(err);
        }
        this._isHandling = false;
        this._cursors.startTrackingSelections();
        this._validateAutoClosedActions();
        if (this._emitStateChangedIfNecessary(eventsCollector, source, cursorChangeReason, oldState, false)) {
            this.revealPrimary(eventsCollector, source, false, 0 /* VerticalRevealType.Simple */, true, 0 /* editorCommon.ScrollType.Smooth */);
        }
    }
    getAutoClosedCharacters() {
        return AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions);
    }
    startComposition(eventsCollector) {
        this._compositionState = new CompositionState(this._model, this.getSelections());
    }
    endComposition(eventsCollector, source) {
        const compositionOutcome = this._compositionState ? this._compositionState.deduceOutcome(this._model, this.getSelections()) : null;
        this._compositionState = null;
        this._executeEdit(() => {
            if (source === 'keyboard') {
                // composition finishes, let's check if we need to auto complete if necessary.
                this._executeEditOperation(TypeOperations.compositionEndWithInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, compositionOutcome, this.getSelections(), this.getAutoClosedCharacters()));
            }
        }, eventsCollector, source);
    }
    type(eventsCollector, text, source) {
        this._executeEdit(() => {
            if (source === 'keyboard') {
                // If this event is coming straight from the keyboard, look for electric characters and enter
                const len = text.length;
                let offset = 0;
                while (offset < len) {
                    const charLength = nextCharLength(text, offset);
                    const chr = text.substr(offset, charLength);
                    // Here we must interpret each typed character individually
                    this._executeEditOperation(TypeOperations.typeWithInterceptors(!!this._compositionState, this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), this.getAutoClosedCharacters(), chr));
                    offset += charLength;
                }
            }
            else {
                this._executeEditOperation(TypeOperations.typeWithoutInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text));
            }
        }, eventsCollector, source);
    }
    compositionType(eventsCollector, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) {
        if (text.length === 0 && replacePrevCharCnt === 0 && replaceNextCharCnt === 0) {
            // this edit is a no-op
            if (positionDelta !== 0) {
                // but it still wants to move the cursor
                const newSelections = this.getSelections().map(selection => {
                    const position = selection.getPosition();
                    return new Selection(position.lineNumber, position.column + positionDelta, position.lineNumber, position.column + positionDelta);
                });
                this.setSelections(eventsCollector, source, newSelections, 0 /* CursorChangeReason.NotSet */);
            }
            return;
        }
        this._executeEdit(() => {
            this._executeEditOperation(TypeOperations.compositionType(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text, replacePrevCharCnt, replaceNextCharCnt, positionDelta));
        }, eventsCollector, source);
    }
    paste(eventsCollector, text, pasteOnNewLine, multicursorText, source) {
        this._executeEdit(() => {
            this._executeEditOperation(TypeOperations.paste(this.context.cursorConfig, this._model, this.getSelections(), text, pasteOnNewLine, multicursorText || []));
        }, eventsCollector, source, 4 /* CursorChangeReason.Paste */);
    }
    cut(eventsCollector, source) {
        this._executeEdit(() => {
            this._executeEditOperation(DeleteOperations.cut(this.context.cursorConfig, this._model, this.getSelections()));
        }, eventsCollector, source);
    }
    executeCommand(eventsCollector, command, source) {
        this._executeEdit(() => {
            this._cursors.killSecondaryCursors();
            this._executeEditOperation(new EditOperationResult(0 /* EditOperationType.Other */, [command], {
                shouldPushStackElementBefore: false,
                shouldPushStackElementAfter: false
            }));
        }, eventsCollector, source);
    }
    executeCommands(eventsCollector, commands, source) {
        this._executeEdit(() => {
            this._executeEditOperation(new EditOperationResult(0 /* EditOperationType.Other */, commands, {
                shouldPushStackElementBefore: false,
                shouldPushStackElementAfter: false
            }));
        }, eventsCollector, source);
    }
}
CursorsController.MAX_CURSOR_COUNT = 10000;
/**
 * A snapshot of the cursor and the model state
 */
class CursorModelState {
    constructor(modelVersionId, cursorState) {
        this.modelVersionId = modelVersionId;
        this.cursorState = cursorState;
    }
    static from(model, cursor) {
        return new CursorModelState(model.getVersionId(), cursor.getCursorStates());
    }
    equals(other) {
        if (!other) {
            return false;
        }
        if (this.modelVersionId !== other.modelVersionId) {
            return false;
        }
        if (this.cursorState.length !== other.cursorState.length) {
            return false;
        }
        for (let i = 0, len = this.cursorState.length; i < len; i++) {
            if (!this.cursorState[i].equals(other.cursorState[i])) {
                return false;
            }
        }
        return true;
    }
}
class AutoClosedAction {
    constructor(model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations) {
        this._model = model;
        this._autoClosedCharactersDecorations = autoClosedCharactersDecorations;
        this._autoClosedEnclosingDecorations = autoClosedEnclosingDecorations;
    }
    static getAllAutoClosedCharacters(autoClosedActions) {
        let autoClosedCharacters = [];
        for (const autoClosedAction of autoClosedActions) {
            autoClosedCharacters = autoClosedCharacters.concat(autoClosedAction.getAutoClosedCharactersRanges());
        }
        return autoClosedCharacters;
    }
    dispose() {
        this._autoClosedCharactersDecorations = this._model.deltaDecorations(this._autoClosedCharactersDecorations, []);
        this._autoClosedEnclosingDecorations = this._model.deltaDecorations(this._autoClosedEnclosingDecorations, []);
    }
    getAutoClosedCharactersRanges() {
        const result = [];
        for (let i = 0; i < this._autoClosedCharactersDecorations.length; i++) {
            const decorationRange = this._model.getDecorationRange(this._autoClosedCharactersDecorations[i]);
            if (decorationRange) {
                result.push(decorationRange);
            }
        }
        return result;
    }
    isValid(selections) {
        const enclosingRanges = [];
        for (let i = 0; i < this._autoClosedEnclosingDecorations.length; i++) {
            const decorationRange = this._model.getDecorationRange(this._autoClosedEnclosingDecorations[i]);
            if (decorationRange) {
                enclosingRanges.push(decorationRange);
                if (decorationRange.startLineNumber !== decorationRange.endLineNumber) {
                    // Stop tracking if the range becomes multiline...
                    return false;
                }
            }
        }
        enclosingRanges.sort(Range.compareRangesUsingStarts);
        selections.sort(Range.compareRangesUsingStarts);
        for (let i = 0; i < selections.length; i++) {
            if (i >= enclosingRanges.length) {
                return false;
            }
            if (!enclosingRanges[i].strictContainsRange(selections[i])) {
                return false;
            }
        }
        return true;
    }
}
class CommandExecutor {
    static executeCommands(model, selectionsBefore, commands) {
        const ctx = {
            model: model,
            selectionsBefore: selectionsBefore,
            trackedRanges: [],
            trackedRangesDirection: []
        };
        const result = this._innerExecuteCommands(ctx, commands);
        for (let i = 0, len = ctx.trackedRanges.length; i < len; i++) {
            ctx.model._setTrackedRange(ctx.trackedRanges[i], null, 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */);
        }
        return result;
    }
    static _innerExecuteCommands(ctx, commands) {
        if (this._arrayIsEmpty(commands)) {
            return null;
        }
        const commandsData = this._getEditOperations(ctx, commands);
        if (commandsData.operations.length === 0) {
            return null;
        }
        const rawOperations = commandsData.operations;
        const loserCursorsMap = this._getLoserCursorMap(rawOperations);
        if (loserCursorsMap.hasOwnProperty('0')) {
            // These commands are very messed up
            console.warn('Ignoring commands');
            return null;
        }
        // Remove operations belonging to losing cursors
        const filteredOperations = [];
        for (let i = 0, len = rawOperations.length; i < len; i++) {
            if (!loserCursorsMap.hasOwnProperty(rawOperations[i].identifier.major.toString())) {
                filteredOperations.push(rawOperations[i]);
            }
        }
        // TODO@Alex: find a better way to do this.
        // give the hint that edit operations are tracked to the model
        if (commandsData.hadTrackedEditOperation && filteredOperations.length > 0) {
            filteredOperations[0]._isTracked = true;
        }
        let selectionsAfter = ctx.model.pushEditOperations(ctx.selectionsBefore, filteredOperations, (inverseEditOperations) => {
            const groupedInverseEditOperations = [];
            for (let i = 0; i < ctx.selectionsBefore.length; i++) {
                groupedInverseEditOperations[i] = [];
            }
            for (const op of inverseEditOperations) {
                if (!op.identifier) {
                    // perhaps auto whitespace trim edits
                    continue;
                }
                groupedInverseEditOperations[op.identifier.major].push(op);
            }
            const minorBasedSorter = (a, b) => {
                return a.identifier.minor - b.identifier.minor;
            };
            const cursorSelections = [];
            for (let i = 0; i < ctx.selectionsBefore.length; i++) {
                if (groupedInverseEditOperations[i].length > 0) {
                    groupedInverseEditOperations[i].sort(minorBasedSorter);
                    cursorSelections[i] = commands[i].computeCursorState(ctx.model, {
                        getInverseEditOperations: () => {
                            return groupedInverseEditOperations[i];
                        },
                        getTrackedSelection: (id) => {
                            const idx = parseInt(id, 10);
                            const range = ctx.model._getTrackedRange(ctx.trackedRanges[idx]);
                            if (ctx.trackedRangesDirection[idx] === 0 /* SelectionDirection.LTR */) {
                                return new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
                            }
                            return new Selection(range.endLineNumber, range.endColumn, range.startLineNumber, range.startColumn);
                        }
                    });
                }
                else {
                    cursorSelections[i] = ctx.selectionsBefore[i];
                }
            }
            return cursorSelections;
        });
        if (!selectionsAfter) {
            selectionsAfter = ctx.selectionsBefore;
        }
        // Extract losing cursors
        const losingCursors = [];
        for (const losingCursorIndex in loserCursorsMap) {
            if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) {
                losingCursors.push(parseInt(losingCursorIndex, 10));
            }
        }
        // Sort losing cursors descending
        losingCursors.sort((a, b) => {
            return b - a;
        });
        // Remove losing cursors
        for (const losingCursor of losingCursors) {
            selectionsAfter.splice(losingCursor, 1);
        }
        return selectionsAfter;
    }
    static _arrayIsEmpty(commands) {
        for (let i = 0, len = commands.length; i < len; i++) {
            if (commands[i]) {
                return false;
            }
        }
        return true;
    }
    static _getEditOperations(ctx, commands) {
        let operations = [];
        let hadTrackedEditOperation = false;
        for (let i = 0, len = commands.length; i < len; i++) {
            const command = commands[i];
            if (command) {
                const r = this._getEditOperationsFromCommand(ctx, i, command);
                operations = operations.concat(r.operations);
                hadTrackedEditOperation = hadTrackedEditOperation || r.hadTrackedEditOperation;
            }
        }
        return {
            operations: operations,
            hadTrackedEditOperation: hadTrackedEditOperation
        };
    }
    static _getEditOperationsFromCommand(ctx, majorIdentifier, command) {
        // This method acts as a transaction, if the command fails
        // everything it has done is ignored
        const operations = [];
        let operationMinor = 0;
        const addEditOperation = (range, text, forceMoveMarkers = false) => {
            if (Range.isEmpty(range) && text === '') {
                // This command wants to add a no-op => no thank you
                return;
            }
            operations.push({
                identifier: {
                    major: majorIdentifier,
                    minor: operationMinor++
                },
                range: range,
                text: text,
                forceMoveMarkers: forceMoveMarkers,
                isAutoWhitespaceEdit: command.insertsAutoWhitespace
            });
        };
        let hadTrackedEditOperation = false;
        const addTrackedEditOperation = (selection, text, forceMoveMarkers) => {
            hadTrackedEditOperation = true;
            addEditOperation(selection, text, forceMoveMarkers);
        };
        const trackSelection = (_selection, trackPreviousOnEmpty) => {
            const selection = Selection.liftSelection(_selection);
            let stickiness;
            if (selection.isEmpty()) {
                if (typeof trackPreviousOnEmpty === 'boolean') {
                    if (trackPreviousOnEmpty) {
                        stickiness = 2 /* TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */;
                    }
                    else {
                        stickiness = 3 /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */;
                    }
                }
                else {
                    // Try to lock it with surrounding text
                    const maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber);
                    if (selection.startColumn === maxLineColumn) {
                        stickiness = 2 /* TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */;
                    }
                    else {
                        stickiness = 3 /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */;
                    }
                }
            }
            else {
                stickiness = 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */;
            }
            const l = ctx.trackedRanges.length;
            const id = ctx.model._setTrackedRange(null, selection, stickiness);
            ctx.trackedRanges[l] = id;
            ctx.trackedRangesDirection[l] = selection.getDirection();
            return l.toString();
        };
        const editOperationBuilder = {
            addEditOperation: addEditOperation,
            addTrackedEditOperation: addTrackedEditOperation,
            trackSelection: trackSelection
        };
        try {
            command.getEditOperations(ctx.model, editOperationBuilder);
        }
        catch (e) {
            // TODO@Alex use notification service if this should be user facing
            // e.friendlyMessage = nls.localize('corrupt.commands', "Unexpected exception while executing command.");
            onUnexpectedError(e);
            return {
                operations: [],
                hadTrackedEditOperation: false
            };
        }
        return {
            operations: operations,
            hadTrackedEditOperation: hadTrackedEditOperation
        };
    }
    static _getLoserCursorMap(operations) {
        // This is destructive on the array
        operations = operations.slice(0);
        // Sort operations with last one first
        operations.sort((a, b) => {
            // Note the minus!
            return -(Range.compareRangesUsingEnds(a.range, b.range));
        });
        // Operations can not overlap!
        const loserCursorsMap = {};
        for (let i = 1; i < operations.length; i++) {
            const previousOp = operations[i - 1];
            const currentOp = operations[i];
            if (Range.getStartPosition(previousOp.range).isBefore(Range.getEndPosition(currentOp.range))) {
                let loserMajor;
                if (previousOp.identifier.major > currentOp.identifier.major) {
                    // previousOp loses the battle
                    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 < i) {
                            i--;
                        }
                        j--;
                    }
                }
                if (i > 0) {
                    i--;
                }
            }
        }
        return loserCursorsMap;
    }
}
class CompositionLineState {
    constructor(text, startSelection, endSelection) {
        this.text = text;
        this.startSelection = startSelection;
        this.endSelection = endSelection;
    }
}
class CompositionState {
    constructor(textModel, selections) {
        this._original = CompositionState._capture(textModel, selections);
    }
    static _capture(textModel, selections) {
        const result = [];
        for (const selection of selections) {
            if (selection.startLineNumber !== selection.endLineNumber) {
                return null;
            }
            result.push(new CompositionLineState(textModel.getLineContent(selection.startLineNumber), selection.startColumn - 1, selection.endColumn - 1));
        }
        return result;
    }
    /**
     * 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._original) {
            return null;
        }
        const current = CompositionState._capture(textModel, selections);
        if (!current) {
            return null;
        }
        if (this._original.length !== current.length) {
            return null;
        }
        const result = [];
        for (let i = 0, len = this._original.length; i < len; i++) {
            result.push(CompositionState._deduceOutcome(this._original[i], current[i]));
        }
        return result;
    }
    static _deduceOutcome(original, current) {
        const commonPrefix = Math.min(original.startSelection, current.startSelection, strings_commonPrefixLength(original.text, current.text));
        const commonSuffix = Math.min(original.text.length - original.endSelection, current.text.length - current.endSelection, strings_commonSuffixLength(original.text, current.text));
        const deletedText = original.text.substring(commonPrefix, original.text.length - commonSuffix);
        const insertedText = current.text.substring(commonPrefix, current.text.length - commonSuffix);
        return new CompositionOutcome(deletedText, original.startSelection - commonPrefix, original.endSelection - commonPrefix, insertedText, current.startSelection - commonPrefix, current.endSelection - commonPrefix);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/editorAction.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class InternalEditorAction {
    constructor(id, label, alias, precondition, run, contextKeyService) {
        this.id = id;
        this.label = label;
        this.alias = alias;
        this._precondition = precondition;
        this._run = run;
        this._contextKeyService = contextKeyService;
    }
    isSupported() {
        return this._contextKeyService.contextMatchesRules(this._precondition);
    }
    run() {
        if (!this.isSupported()) {
            return Promise.resolve(undefined);
        }
        return this._run();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/editorCommon.js
/**
 * The type of the `IEditor`.
 */
const EditorType = {
    ICodeEditor: 'vs.editor.ICodeEditor',
    IDiffEditor: 'vs.editor.IDiffEditor'
};

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/textToHtmlTokenizer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var textToHtmlTokenizer_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};




const fallback = {
    getInitialState: () => NullState,
    tokenizeEncoded: (buffer, hasEOL, state) => nullTokenizeEncoded(0 /* LanguageId.Null */, state)
};
function tokenizeToString(languageService, text, languageId) {
    return textToHtmlTokenizer_awaiter(this, void 0, void 0, function* () {
        if (!languageId) {
            return _tokenizeToString(text, languageService.languageIdCodec, fallback);
        }
        const tokenizationSupport = yield languages_TokenizationRegistry.getOrCreate(languageId);
        return _tokenizeToString(text, languageService.languageIdCodec, tokenizationSupport || fallback);
    });
}
function tokenizeLineToHTML(text, 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 = text.charCodeAt(charIndex);
            switch (charCode) {
                case 9 /* CharCode.Tab */: {
                    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 /* CharCode.LessThan */:
                    partContent += '&lt;';
                    prevIsSpace = false;
                    break;
                case 62 /* CharCode.GreaterThan */:
                    partContent += '&gt;';
                    prevIsSpace = false;
                    break;
                case 38 /* CharCode.Ampersand */:
                    partContent += '&amp;';
                    prevIsSpace = false;
                    break;
                case 0 /* CharCode.Null */:
                    partContent += '&#00;';
                    prevIsSpace = false;
                    break;
                case 65279 /* CharCode.UTF8_BOM */:
                case 8232 /* CharCode.LINE_SEPARATOR */:
                case 8233 /* CharCode.PARAGRAPH_SEPARATOR */:
                case 133 /* CharCode.NEXT_LINE */:
                    partContent += '\ufffd';
                    prevIsSpace = false;
                    break;
                case 13 /* CharCode.CarriageReturn */:
                    // zero width space, because carriage return would introduce a line break
                    partContent += '&#8203';
                    prevIsSpace = false;
                    break;
                case 32 /* CharCode.Space */:
                    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 _tokenizeToString(text, languageIdCodec, tokenizationSupport) {
    let result = `<div class="monaco-tokenized-source">`;
    const lines = splitLines(text);
    let currentState = tokenizationSupport.getInitialState();
    for (let i = 0, len = lines.length; i < len; i++) {
        const line = lines[i];
        if (i > 0) {
            result += `<br/>`;
        }
        const tokenizationResult = tokenizationSupport.tokenizeEncoded(line, true, currentState);
        LineTokens.convertToEndOffset(tokenizationResult.tokens, line.length);
        const lineTokens = new LineTokens(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}">${strings_escape(line.substring(startOffset, endIndex))}</span>`;
            startOffset = endIndex;
        }
        currentState = tokenizationResult.endState;
    }
    result += `</div>`;
    return result;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewLayout/linesLayout.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class PendingChanges {
    constructor() {
        this._hasPending = false;
        this._inserts = [];
        this._changes = [];
        this._removes = [];
    }
    insert(x) {
        this._hasPending = true;
        this._inserts.push(x);
    }
    change(x) {
        this._hasPending = true;
        this._changes.push(x);
    }
    remove(x) {
        this._hasPending = true;
        this._removes.push(x);
    }
    mustCommit() {
        return this._hasPending;
    }
    commit(linesLayout) {
        if (!this._hasPending) {
            return;
        }
        const inserts = this._inserts;
        const changes = this._changes;
        const removes = this._removes;
        this._hasPending = false;
        this._inserts = [];
        this._changes = [];
        this._removes = [];
        linesLayout._commitPendingChanges(inserts, changes, removes);
    }
}
class EditorWhitespace {
    constructor(id, afterLineNumber, ordinal, height, minWidth) {
        this.id = id;
        this.afterLineNumber = afterLineNumber;
        this.ordinal = ordinal;
        this.height = height;
        this.minWidth = minWidth;
        this.prefixSum = 0;
    }
}
/**
 * Layouting of objects that take vertical space (by having a height) and push down other objects.
 *
 * These objects are basically either text (lines) or spaces between those lines (whitespaces).
 * This provides commodity operations for working with lines that contain whitespace that pushes lines lower (vertically).
 */
class LinesLayout {
    constructor(lineCount, lineHeight, paddingTop, paddingBottom) {
        this._instanceId = singleLetterHash(++LinesLayout.INSTANCE_COUNT);
        this._pendingChanges = new PendingChanges();
        this._lastWhitespaceId = 0;
        this._arr = [];
        this._prefixSumValidIndex = -1;
        this._minWidth = -1; /* marker for not being computed */
        this._lineCount = lineCount;
        this._lineHeight = lineHeight;
        this._paddingTop = paddingTop;
        this._paddingBottom = 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._checkPendingChanges();
        this._lineHeight = lineHeight;
    }
    /**
     * Changes the padding used to calculate vertical offsets.
     */
    setPadding(paddingTop, paddingBottom) {
        this._paddingTop = paddingTop;
        this._paddingBottom = paddingBottom;
    }
    /**
     * Set the number of lines.
     *
     * @param lineCount New number of lines.
     */
    onFlushed(lineCount) {
        this._checkPendingChanges();
        this._lineCount = 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 id = this._instanceId + (++this._lastWhitespaceId);
                    this._pendingChanges.insert(new EditorWhitespace(id, afterLineNumber, ordinal, heightInPx, minWidth));
                    return id;
                },
                changeOneWhitespace: (id, newAfterLineNumber, newHeight) => {
                    hadAChange = true;
                    newAfterLineNumber = newAfterLineNumber | 0;
                    newHeight = newHeight | 0;
                    this._pendingChanges.change({ id, newAfterLineNumber, newHeight });
                },
                removeWhitespace: (id) => {
                    hadAChange = true;
                    this._pendingChanges.remove({ id });
                }
            };
            callback(accessor);
        }
        finally {
            this._pendingChanges.commit(this);
        }
        return hadAChange;
    }
    _commitPendingChanges(inserts, changes, removes) {
        if (inserts.length > 0 || removes.length > 0) {
            this._minWidth = -1; /* marker for not being computed */
        }
        if (inserts.length + changes.length + removes.length <= 1) {
            // when only one thing happened, handle it "delicately"
            for (const insert of inserts) {
                this._insertWhitespace(insert);
            }
            for (const change of changes) {
                this._changeOneWhitespace(change.id, change.newAfterLineNumber, change.newHeight);
            }
            for (const remove of removes) {
                const index = this._findWhitespaceIndex(remove.id);
                if (index === -1) {
                    continue;
                }
                this._removeWhitespace(index);
            }
            return;
        }
        // simply rebuild the entire datastructure
        const toRemove = new Set();
        for (const remove of removes) {
            toRemove.add(remove.id);
        }
        const toChange = new Map();
        for (const change of changes) {
            toChange.set(change.id, change);
        }
        const applyRemoveAndChange = (whitespaces) => {
            const result = [];
            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;
                }
                result.push(whitespace);
            }
            return result;
        };
        const result = applyRemoveAndChange(this._arr).concat(applyRemoveAndChange(inserts));
        result.sort((a, b) => {
            if (a.afterLineNumber === b.afterLineNumber) {
                return a.ordinal - b.ordinal;
            }
            return a.afterLineNumber - b.afterLineNumber;
        });
        this._arr = result;
        this._prefixSumValidIndex = -1;
    }
    _checkPendingChanges() {
        if (this._pendingChanges.mustCommit()) {
            this._pendingChanges.commit(this);
        }
    }
    _insertWhitespace(whitespace) {
        const insertIndex = LinesLayout.findInsertionIndex(this._arr, whitespace.afterLineNumber, whitespace.ordinal);
        this._arr.splice(insertIndex, 0, whitespace);
        this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1);
    }
    _findWhitespaceIndex(id) {
        const arr = this._arr;
        for (let i = 0, len = arr.length; i < len; i++) {
            if (arr[i].id === id) {
                return i;
            }
        }
        return -1;
    }
    _changeOneWhitespace(id, newAfterLineNumber, newHeight) {
        const index = this._findWhitespaceIndex(id);
        if (index === -1) {
            return;
        }
        if (this._arr[index].height !== newHeight) {
            this._arr[index].height = newHeight;
            this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, index - 1);
        }
        if (this._arr[index].afterLineNumber !== newAfterLineNumber) {
            // `afterLineNumber` changed for this whitespace
            // Record old whitespace
            const whitespace = this._arr[index];
            // Since changing `afterLineNumber` can trigger a reordering, we're gonna remove this whitespace
            this._removeWhitespace(index);
            whitespace.afterLineNumber = newAfterLineNumber;
            // And add it again
            this._insertWhitespace(whitespace);
        }
    }
    _removeWhitespace(removeIndex) {
        this._arr.splice(removeIndex, 1);
        this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, 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._checkPendingChanges();
        fromLineNumber = fromLineNumber | 0;
        toLineNumber = toLineNumber | 0;
        this._lineCount -= (toLineNumber - fromLineNumber + 1);
        for (let i = 0, len = this._arr.length; i < len; i++) {
            const afterLineNumber = this._arr[i].afterLineNumber;
            if (fromLineNumber <= afterLineNumber && afterLineNumber <= toLineNumber) {
                // The line this whitespace was after has been deleted
                //  => move whitespace to before first deleted line
                this._arr[i].afterLineNumber = fromLineNumber - 1;
            }
            else if (afterLineNumber > toLineNumber) {
                // The line this whitespace was after has been moved up
                //  => move whitespace up
                this._arr[i].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._checkPendingChanges();
        fromLineNumber = fromLineNumber | 0;
        toLineNumber = toLineNumber | 0;
        this._lineCount += (toLineNumber - fromLineNumber + 1);
        for (let i = 0, len = this._arr.length; i < len; i++) {
            const afterLineNumber = this._arr[i].afterLineNumber;
            if (fromLineNumber <= afterLineNumber) {
                this._arr[i].afterLineNumber += (toLineNumber - fromLineNumber + 1);
            }
        }
    }
    /**
     * Get the sum of all the whitespaces.
     */
    getWhitespacesTotalHeight() {
        this._checkPendingChanges();
        if (this._arr.length === 0) {
            return 0;
        }
        return this.getWhitespacesAccumulatedHeight(this._arr.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._checkPendingChanges();
        index = index | 0;
        let startIndex = Math.max(0, this._prefixSumValidIndex + 1);
        if (startIndex === 0) {
            this._arr[0].prefixSum = this._arr[0].height;
            startIndex++;
        }
        for (let i = startIndex; i <= index; i++) {
            this._arr[i].prefixSum = this._arr[i - 1].prefixSum + this._arr[i].height;
        }
        this._prefixSumValidIndex = Math.max(this._prefixSumValidIndex, index);
        return this._arr[index].prefixSum;
    }
    /**
     * Get the sum of heights for all objects.
     *
     * @return The sum of heights for all objects.
     */
    getLinesTotalHeight() {
        this._checkPendingChanges();
        const linesHeight = this._lineHeight * this._lineCount;
        const whitespacesHeight = this.getWhitespacesTotalHeight();
        return linesHeight + whitespacesHeight + this._paddingTop + this._paddingBottom;
    }
    /**
     * Returns the accumulated height of whitespaces before the given line number.
     *
     * @param lineNumber The line number
     */
    getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber) {
        this._checkPendingChanges();
        lineNumber = lineNumber | 0;
        const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
        if (lastWhitespaceBeforeLineNumber === -1) {
            return 0;
        }
        return this.getWhitespacesAccumulatedHeight(lastWhitespaceBeforeLineNumber);
    }
    _findLastWhitespaceBeforeLineNumber(lineNumber) {
        lineNumber = lineNumber | 0;
        // Find the whitespace before line number
        const arr = this._arr;
        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;
    }
    _findFirstWhitespaceAfterLineNumber(lineNumber) {
        lineNumber = lineNumber | 0;
        const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
        const firstWhitespaceAfterLineNumber = lastWhitespaceBeforeLineNumber + 1;
        if (firstWhitespaceAfterLineNumber < this._arr.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._checkPendingChanges();
        lineNumber = lineNumber | 0;
        return this._findFirstWhitespaceAfterLineNumber(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._checkPendingChanges();
        lineNumber = lineNumber | 0;
        let previousLinesHeight;
        if (lineNumber > 1) {
            previousLinesHeight = this._lineHeight * (lineNumber - 1);
        }
        else {
            previousLinesHeight = 0;
        }
        const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber - (includeViewZones ? 1 : 0));
        return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
    }
    /**
     * 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._checkPendingChanges();
        lineNumber = lineNumber | 0;
        const previousLinesHeight = this._lineHeight * lineNumber;
        const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber + (includeViewZones ? 1 : 0));
        return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
    }
    /**
     * The maximum min width for all whitespaces.
     */
    getWhitespaceMinWidth() {
        this._checkPendingChanges();
        if (this._minWidth === -1) {
            let minWidth = 0;
            for (let i = 0, len = this._arr.length; i < len; i++) {
                minWidth = Math.max(minWidth, this._arr[i].minWidth);
            }
            this._minWidth = minWidth;
        }
        return this._minWidth;
    }
    /**
     * Check if `verticalOffset` is below all lines.
     */
    isAfterLines(verticalOffset) {
        this._checkPendingChanges();
        const totalHeight = this.getLinesTotalHeight();
        return verticalOffset > totalHeight;
    }
    isInTopPadding(verticalOffset) {
        if (this._paddingTop === 0) {
            return false;
        }
        this._checkPendingChanges();
        return (verticalOffset < this._paddingTop);
    }
    isInBottomPadding(verticalOffset) {
        if (this._paddingBottom === 0) {
            return false;
        }
        this._checkPendingChanges();
        const totalHeight = this.getLinesTotalHeight();
        return (verticalOffset >= totalHeight - this._paddingBottom);
    }
    /**
     * 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._checkPendingChanges();
        verticalOffset = verticalOffset | 0;
        if (verticalOffset < 0) {
            return 1;
        }
        const linesCount = this._lineCount | 0;
        const lineHeight = this._lineHeight;
        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) {
                // vertical offset is after mid line number
                minLineNumber = midLineNumber + 1;
            }
            else if (verticalOffset >= midLineNumberVerticalOffset) {
                // Hit
                return midLineNumber;
            }
            else {
                // vertical offset is before mid line number, but mid line number could still be what we're searching for
                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._checkPendingChanges();
        verticalOffset1 = verticalOffset1 | 0;
        verticalOffset2 = verticalOffset2 | 0;
        const lineHeight = this._lineHeight;
        // Find first line number
        // We don't live in a perfect world, so the line number might start before or after verticalOffset1
        const startLineNumber = this.getLineNumberAtOrAfterVerticalOffset(verticalOffset1) | 0;
        const startLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(startLineNumber) | 0;
        let endLineNumber = this._lineCount | 0;
        // Also keep track of what whitespace we've got
        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;
        // IE (all versions) cannot handle units above about 1,533,908 px, so every 500k pixels bring numbers down
        const STEP_SIZE = 500000;
        let bigNumbersDelta = 0;
        if (startLineNumberVerticalOffset >= STEP_SIZE) {
            // Compute a delta that guarantees that lines are positioned at `lineHeight` increments
            bigNumbersDelta = Math.floor(startLineNumberVerticalOffset / STEP_SIZE) * STEP_SIZE;
            bigNumbersDelta = Math.floor(bigNumbersDelta / lineHeight) * lineHeight;
            currentLineRelativeOffset -= bigNumbersDelta;
        }
        const linesOffsets = [];
        const verticalCenter = verticalOffset1 + (verticalOffset2 - verticalOffset1) / 2;
        let centeredLineNumber = -1;
        // Figure out how far the lines go
        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;
                }
            }
            // Count current line height in the vertical offsets
            currentVerticalOffset += lineHeight;
            linesOffsets[lineNumber - startLineNumber] = currentLineRelativeOffset;
            // Next line starts immediately after this one
            currentLineRelativeOffset += lineHeight;
            while (currentWhitespaceAfterLineNumber === lineNumber) {
                // Push down next line with the height of the current whitespace
                currentLineRelativeOffset += currentWhitespaceHeight;
                // Count current whitespace in the vertical offsets
                currentVerticalOffset += currentWhitespaceHeight;
                whitespaceIndex++;
                if (whitespaceIndex >= whitespaceCount) {
                    currentWhitespaceAfterLineNumber = endLineNumber + 1;
                }
                else {
                    currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
                    currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
                }
            }
            if (currentVerticalOffset >= verticalOffset2) {
                // We have covered the entire viewport area, time to stop
                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: bigNumbersDelta,
            startLineNumber: startLineNumber,
            endLineNumber: endLineNumber,
            relativeVerticalOffset: linesOffsets,
            centeredLineNumber: centeredLineNumber,
            completelyVisibleStartLineNumber: completelyVisibleStartLineNumber,
            completelyVisibleEndLineNumber: completelyVisibleEndLineNumber
        };
    }
    getVerticalOffsetForWhitespaceIndex(whitespaceIndex) {
        this._checkPendingChanges();
        whitespaceIndex = whitespaceIndex | 0;
        const afterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex);
        let previousLinesHeight;
        if (afterLineNumber >= 1) {
            previousLinesHeight = this._lineHeight * afterLineNumber;
        }
        else {
            previousLinesHeight = 0;
        }
        let previousWhitespacesHeight;
        if (whitespaceIndex > 0) {
            previousWhitespacesHeight = this.getWhitespacesAccumulatedHeight(whitespaceIndex - 1);
        }
        else {
            previousWhitespacesHeight = 0;
        }
        return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
    }
    getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset) {
        this._checkPendingChanges();
        verticalOffset = verticalOffset | 0;
        let minWhitespaceIndex = 0;
        let maxWhitespaceIndex = this.getWhitespacesCount() - 1;
        if (maxWhitespaceIndex < 0) {
            return -1;
        }
        // Special case: nothing to be found
        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) {
                // vertical offset is after whitespace
                minWhitespaceIndex = midWhitespaceIndex + 1;
            }
            else if (verticalOffset >= midWhitespaceVerticalOffset) {
                // Hit
                return midWhitespaceIndex;
            }
            else {
                // vertical offset is before whitespace, but midWhitespaceIndex might still be what we're searching for
                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._checkPendingChanges();
        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._checkPendingChanges();
        verticalOffset1 = verticalOffset1 | 0;
        verticalOffset2 = verticalOffset2 | 0;
        const startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1);
        const endIndex = this.getWhitespacesCount() - 1;
        if (startIndex < 0) {
            return [];
        }
        const result = [];
        for (let i = startIndex; i <= endIndex; i++) {
            const top = this.getVerticalOffsetForWhitespaceIndex(i);
            const height = this.getHeightForWhitespaceIndex(i);
            if (top >= verticalOffset2) {
                break;
            }
            result.push({
                id: this.getIdForWhitespaceIndex(i),
                afterLineNumber: this.getAfterLineNumberForWhitespaceIndex(i),
                verticalOffset: top,
                height: height
            });
        }
        return result;
    }
    /**
     * Get all whitespaces.
     */
    getWhitespaces() {
        this._checkPendingChanges();
        return this._arr.slice(0);
    }
    /**
     * The number of whitespaces.
     */
    getWhitespacesCount() {
        this._checkPendingChanges();
        return this._arr.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._checkPendingChanges();
        index = index | 0;
        return this._arr[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._checkPendingChanges();
        index = index | 0;
        return this._arr[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._checkPendingChanges();
        index = index | 0;
        return this._arr[index].height;
    }
}
LinesLayout.INSTANCE_COUNT = 0;

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewLayout/viewLayout.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






const SMOOTH_SCROLLING_TIME = 125;
class EditorScrollDimensions {
    constructor(width, contentWidth, height, contentHeight) {
        width = width | 0;
        contentWidth = contentWidth | 0;
        height = height | 0;
        contentHeight = contentHeight | 0;
        if (width < 0) {
            width = 0;
        }
        if (contentWidth < 0) {
            contentWidth = 0;
        }
        if (height < 0) {
            height = 0;
        }
        if (contentHeight < 0) {
            contentHeight = 0;
        }
        this.width = width;
        this.contentWidth = contentWidth;
        this.scrollWidth = Math.max(width, 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);
    }
}
class EditorScrollable extends Disposable {
    constructor(smoothScrollDuration, scheduleAtNextAnimationFrame) {
        super();
        this._onDidContentSizeChange = this._register(new Emitter());
        this.onDidContentSizeChange = this._onDidContentSizeChange.event;
        this._dimensions = new EditorScrollDimensions(0, 0, 0, 0);
        this._scrollable = this._register(new Scrollable({
            forceIntegerValues: true,
            smoothScrollDuration,
            scheduleAtNextAnimationFrame
        }));
        this.onDidScroll = this._scrollable.onScroll;
    }
    getScrollable() {
        return this._scrollable;
    }
    setSmoothScrollDuration(smoothScrollDuration) {
        this._scrollable.setSmoothScrollDuration(smoothScrollDuration);
    }
    validateScrollPosition(scrollPosition) {
        return this._scrollable.validateScrollPosition(scrollPosition);
    }
    getScrollDimensions() {
        return this._dimensions;
    }
    setScrollDimensions(dimensions) {
        if (this._dimensions.equals(dimensions)) {
            return;
        }
        const oldDimensions = this._dimensions;
        this._dimensions = dimensions;
        this._scrollable.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._onDidContentSizeChange.fire(new ContentSizeChangedEvent(oldDimensions.contentWidth, oldDimensions.contentHeight, dimensions.contentWidth, dimensions.contentHeight));
        }
    }
    getFutureScrollPosition() {
        return this._scrollable.getFutureScrollPosition();
    }
    getCurrentScrollPosition() {
        return this._scrollable.getCurrentScrollPosition();
    }
    setScrollPositionNow(update) {
        this._scrollable.setScrollPositionNow(update);
    }
    setScrollPositionSmooth(update) {
        this._scrollable.setScrollPositionSmooth(update);
    }
}
class ViewLayout extends Disposable {
    constructor(configuration, lineCount, scheduleAtNextAnimationFrame) {
        super();
        this._configuration = configuration;
        const options = this._configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        const padding = options.get(77 /* EditorOption.padding */);
        this._linesLayout = new LinesLayout(lineCount, options.get(61 /* EditorOption.lineHeight */), padding.top, padding.bottom);
        this._scrollable = this._register(new EditorScrollable(0, scheduleAtNextAnimationFrame));
        this._configureSmoothScrollDuration();
        this._scrollable.setScrollDimensions(new EditorScrollDimensions(layoutInfo.contentWidth, 0, layoutInfo.height, 0));
        this.onDidScroll = this._scrollable.onDidScroll;
        this.onDidContentSizeChange = this._scrollable.onDidContentSizeChange;
        this._updateHeight();
    }
    dispose() {
        super.dispose();
    }
    getScrollable() {
        return this._scrollable.getScrollable();
    }
    onHeightMaybeChanged() {
        this._updateHeight();
    }
    _configureSmoothScrollDuration() {
        this._scrollable.setSmoothScrollDuration(this._configuration.options.get(105 /* EditorOption.smoothScrolling */) ? SMOOTH_SCROLLING_TIME : 0);
    }
    // ---- begin view event handlers
    onConfigurationChanged(e) {
        const options = this._configuration.options;
        if (e.hasChanged(61 /* EditorOption.lineHeight */)) {
            this._linesLayout.setLineHeight(options.get(61 /* EditorOption.lineHeight */));
        }
        if (e.hasChanged(77 /* EditorOption.padding */)) {
            const padding = options.get(77 /* EditorOption.padding */);
            this._linesLayout.setPadding(padding.top, padding.bottom);
        }
        if (e.hasChanged(133 /* EditorOption.layoutInfo */)) {
            const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
            const width = layoutInfo.contentWidth;
            const height = layoutInfo.height;
            const scrollDimensions = this._scrollable.getScrollDimensions();
            const contentWidth = scrollDimensions.contentWidth;
            this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, contentWidth)));
        }
        else {
            this._updateHeight();
        }
        if (e.hasChanged(105 /* EditorOption.smoothScrolling */)) {
            this._configureSmoothScrollDuration();
        }
    }
    onFlushed(lineCount) {
        this._linesLayout.onFlushed(lineCount);
    }
    onLinesDeleted(fromLineNumber, toLineNumber) {
        this._linesLayout.onLinesDeleted(fromLineNumber, toLineNumber);
    }
    onLinesInserted(fromLineNumber, toLineNumber) {
        this._linesLayout.onLinesInserted(fromLineNumber, toLineNumber);
    }
    // ---- end view event handlers
    _getHorizontalScrollbarHeight(width, scrollWidth) {
        const options = this._configuration.options;
        const scrollbar = options.get(94 /* EditorOption.scrollbar */);
        if (scrollbar.horizontal === 2 /* ScrollbarVisibility.Hidden */) {
            // horizontal scrollbar not visible
            return 0;
        }
        if (width >= scrollWidth) {
            // horizontal scrollbar not visible
            return 0;
        }
        return scrollbar.horizontalScrollbarSize;
    }
    _getContentHeight(width, height, contentWidth) {
        const options = this._configuration.options;
        let result = this._linesLayout.getLinesTotalHeight();
        if (options.get(96 /* EditorOption.scrollBeyondLastLine */)) {
            result += Math.max(0, height - options.get(61 /* EditorOption.lineHeight */) - options.get(77 /* EditorOption.padding */).bottom);
        }
        else {
            result += this._getHorizontalScrollbarHeight(width, contentWidth);
        }
        return result;
    }
    _updateHeight() {
        const scrollDimensions = this._scrollable.getScrollDimensions();
        const width = scrollDimensions.width;
        const height = scrollDimensions.height;
        const contentWidth = scrollDimensions.contentWidth;
        this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, contentWidth)));
    }
    // ---- Layouting logic
    getCurrentViewport() {
        const scrollDimensions = this._scrollable.getScrollDimensions();
        const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
        return new Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
    }
    getFutureViewport() {
        const scrollDimensions = this._scrollable.getScrollDimensions();
        const currentScrollPosition = this._scrollable.getFutureScrollPosition();
        return new Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
    }
    _computeContentWidth(maxLineWidth) {
        const options = this._configuration.options;
        const wrappingInfo = options.get(134 /* EditorOption.wrappingInfo */);
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        if (wrappingInfo.isViewportWrapping) {
            const minimap = options.get(67 /* EditorOption.minimap */);
            if (maxLineWidth > layoutInfo.contentWidth + fontInfo.typicalHalfwidthCharacterWidth) {
                // This is a case where viewport wrapping is on, but the line extends above the viewport
                if (minimap.enabled && minimap.side === 'right') {
                    // We need to accomodate the scrollbar width
                    return maxLineWidth + layoutInfo.verticalScrollbarWidth;
                }
            }
            return maxLineWidth;
        }
        else {
            const extraHorizontalSpace = options.get(95 /* EditorOption.scrollBeyondLastColumn */) * fontInfo.typicalHalfwidthCharacterWidth;
            const whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth();
            return Math.max(maxLineWidth + extraHorizontalSpace + layoutInfo.verticalScrollbarWidth, whitespaceMinWidth);
        }
    }
    setMaxLineWidth(maxLineWidth) {
        const scrollDimensions = this._scrollable.getScrollDimensions();
        // const newScrollWidth = ;
        this._scrollable.setScrollDimensions(new EditorScrollDimensions(scrollDimensions.width, this._computeContentWidth(maxLineWidth), scrollDimensions.height, scrollDimensions.contentHeight));
        // The height might depend on the fact that there is a horizontal scrollbar or not
        this._updateHeight();
    }
    // ---- view state
    saveState() {
        const currentScrollPosition = this._scrollable.getFutureScrollPosition();
        const scrollTop = currentScrollPosition.scrollTop;
        const firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop);
        const whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport);
        return {
            scrollTop: scrollTop,
            scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine,
            scrollLeft: currentScrollPosition.scrollLeft
        };
    }
    // ----
    changeWhitespace(callback) {
        const hadAChange = this._linesLayout.changeWhitespace(callback);
        if (hadAChange) {
            this.onHeightMaybeChanged();
        }
        return hadAChange;
    }
    getVerticalOffsetForLineNumber(lineNumber, includeViewZones = false) {
        return this._linesLayout.getVerticalOffsetForLineNumber(lineNumber, includeViewZones);
    }
    getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones = false) {
        return this._linesLayout.getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones);
    }
    isAfterLines(verticalOffset) {
        return this._linesLayout.isAfterLines(verticalOffset);
    }
    isInTopPadding(verticalOffset) {
        return this._linesLayout.isInTopPadding(verticalOffset);
    }
    isInBottomPadding(verticalOffset) {
        return this._linesLayout.isInBottomPadding(verticalOffset);
    }
    getLineNumberAtVerticalOffset(verticalOffset) {
        return this._linesLayout.getLineNumberAtOrAfterVerticalOffset(verticalOffset);
    }
    getWhitespaceAtVerticalOffset(verticalOffset) {
        return this._linesLayout.getWhitespaceAtVerticalOffset(verticalOffset);
    }
    getLinesViewportData() {
        const visibleBox = this.getCurrentViewport();
        return this._linesLayout.getLinesViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
    }
    getLinesViewportDataAtScrollTop(scrollTop) {
        // do some minimal validations on scrollTop
        const scrollDimensions = this._scrollable.getScrollDimensions();
        if (scrollTop + scrollDimensions.height > scrollDimensions.scrollHeight) {
            scrollTop = scrollDimensions.scrollHeight - scrollDimensions.height;
        }
        if (scrollTop < 0) {
            scrollTop = 0;
        }
        return this._linesLayout.getLinesViewportData(scrollTop, scrollTop + scrollDimensions.height);
    }
    getWhitespaceViewportData() {
        const visibleBox = this.getCurrentViewport();
        return this._linesLayout.getWhitespaceViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
    }
    getWhitespaces() {
        return this._linesLayout.getWhitespaces();
    }
    // ----
    getContentWidth() {
        const scrollDimensions = this._scrollable.getScrollDimensions();
        return scrollDimensions.contentWidth;
    }
    getScrollWidth() {
        const scrollDimensions = this._scrollable.getScrollDimensions();
        return scrollDimensions.scrollWidth;
    }
    getContentHeight() {
        const scrollDimensions = this._scrollable.getScrollDimensions();
        return scrollDimensions.contentHeight;
    }
    getScrollHeight() {
        const scrollDimensions = this._scrollable.getScrollDimensions();
        return scrollDimensions.scrollHeight;
    }
    getCurrentScrollLeft() {
        const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
        return currentScrollPosition.scrollLeft;
    }
    getCurrentScrollTop() {
        const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
        return currentScrollPosition.scrollTop;
    }
    validateScrollPosition(scrollPosition) {
        return this._scrollable.validateScrollPosition(scrollPosition);
    }
    setScrollPosition(position, type) {
        if (type === 1 /* ScrollType.Immediate */) {
            this._scrollable.setScrollPositionNow(position);
        }
        else {
            this._scrollable.setScrollPositionSmooth(position);
        }
    }
    deltaScrollNow(deltaScrollLeft, deltaScrollTop) {
        const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
        this._scrollable.setScrollPositionNow({
            scrollLeft: currentScrollPosition.scrollLeft + deltaScrollLeft,
            scrollTop: currentScrollPosition.scrollTop + deltaScrollTop
        });
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewModel/viewModelDecorations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class ViewModelDecorations {
    constructor(editorId, model, configuration, linesCollection, coordinatesConverter) {
        this.editorId = editorId;
        this.model = model;
        this.configuration = configuration;
        this._linesCollection = linesCollection;
        this._coordinatesConverter = coordinatesConverter;
        this._decorationsCache = Object.create(null);
        this._cachedModelDecorationsResolver = null;
        this._cachedModelDecorationsResolverViewRange = null;
    }
    _clearCachedModelDecorationsResolver() {
        this._cachedModelDecorationsResolver = null;
        this._cachedModelDecorationsResolverViewRange = null;
    }
    dispose() {
        this._decorationsCache = Object.create(null);
        this._clearCachedModelDecorationsResolver();
    }
    reset() {
        this._decorationsCache = Object.create(null);
        this._clearCachedModelDecorationsResolver();
    }
    onModelDecorationsChanged() {
        this._decorationsCache = Object.create(null);
        this._clearCachedModelDecorationsResolver();
    }
    onLineMappingChanged() {
        this._decorationsCache = Object.create(null);
        this._clearCachedModelDecorationsResolver();
    }
    _getOrCreateViewModelDecoration(modelDecoration) {
        const id = modelDecoration.id;
        let r = this._decorationsCache[id];
        if (!r) {
            const modelRange = modelDecoration.range;
            const options = modelDecoration.options;
            let viewRange;
            if (options.isWholeLine) {
                const start = this._coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.startLineNumber, 1), 0 /* PositionAffinity.Left */);
                const end = this._coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber)), 1 /* PositionAffinity.Right */);
                viewRange = new Range(start.lineNumber, start.column, end.lineNumber, end.column);
            }
            else {
                // For backwards compatibility reasons, we want injected text before any decoration.
                // Thus, move decorations to the right.
                viewRange = this._coordinatesConverter.convertModelRangeToViewRange(modelRange, 1 /* PositionAffinity.Right */);
            }
            r = new ViewModelDecoration(viewRange, options);
            this._decorationsCache[id] = r;
        }
        return r;
    }
    getDecorationsViewportData(viewRange) {
        let cacheIsValid = (this._cachedModelDecorationsResolver !== null);
        cacheIsValid = cacheIsValid && (viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange));
        if (!cacheIsValid) {
            this._cachedModelDecorationsResolver = this._getDecorationsInRange(viewRange);
            this._cachedModelDecorationsResolverViewRange = viewRange;
        }
        return this._cachedModelDecorationsResolver;
    }
    getInlineDecorationsOnLine(lineNumber) {
        const range = new Range(lineNumber, this._linesCollection.getViewLineMinColumn(lineNumber), lineNumber, this._linesCollection.getViewLineMaxColumn(lineNumber));
        return this._getDecorationsInRange(range).inlineDecorations[0];
    }
    _getDecorationsInRange(viewRange) {
        const modelDecorations = this._linesCollection.getDecorationsInRange(viewRange, this.editorId, filterValidationDecorations(this.configuration.options));
        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 i = 0, len = modelDecorations.length; i < len; i++) {
            const modelDecoration = modelDecorations[i];
            const decorationOptions = modelDecoration.options;
            if (!isModelDecorationVisible(this.model, modelDecoration)) {
                continue;
            }
            const viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration);
            const viewRange = viewModelDecoration.range;
            decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration;
            if (decorationOptions.inlineClassName) {
                const inlineDecoration = new InlineDecoration(viewRange, decorationOptions.inlineClassName, decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 /* InlineDecorationType.RegularAffectingLetterSpacing */ : 0 /* InlineDecorationType.Regular */);
                const intersectedStartLineNumber = Math.max(startLineNumber, viewRange.startLineNumber);
                const intersectedEndLineNumber = Math.min(endLineNumber, viewRange.endLineNumber);
                for (let j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) {
                    inlineDecorations[j - startLineNumber].push(inlineDecoration);
                }
            }
            if (decorationOptions.beforeContentClassName) {
                if (startLineNumber <= viewRange.startLineNumber && viewRange.startLineNumber <= endLineNumber) {
                    const inlineDecoration = new InlineDecoration(new Range(viewRange.startLineNumber, viewRange.startColumn, viewRange.startLineNumber, viewRange.startColumn), decorationOptions.beforeContentClassName, 1 /* InlineDecorationType.Before */);
                    inlineDecorations[viewRange.startLineNumber - startLineNumber].push(inlineDecoration);
                }
            }
            if (decorationOptions.afterContentClassName) {
                if (startLineNumber <= viewRange.endLineNumber && viewRange.endLineNumber <= endLineNumber) {
                    const inlineDecoration = new InlineDecoration(new Range(viewRange.endLineNumber, viewRange.endColumn, viewRange.endLineNumber, viewRange.endColumn), decorationOptions.afterContentClassName, 2 /* InlineDecorationType.After */);
                    inlineDecorations[viewRange.endLineNumber - startLineNumber].push(inlineDecoration);
                }
            }
        }
        return {
            decorations: decorationsInViewport,
            inlineDecorations: inlineDecorations
        };
    }
}
function isModelDecorationVisible(model, decoration) {
    if (decoration.options.hideInCommentTokens && isModelDecorationInComment(model, decoration)) {
        return false;
    }
    if (decoration.options.hideInStringTokens && isModelDecorationInString(model, decoration)) {
        return false;
    }
    return true;
}
function isModelDecorationInComment(model, decoration) {
    return testTokensInRange(model, decoration.range, (tokenType) => tokenType === 1 /* StandardTokenType.Comment */);
}
function isModelDecorationInString(model, decoration) {
    return testTokensInRange(model, decoration.range, (tokenType) => tokenType === 2 /* StandardTokenType.String */);
}
/**
 * Calls the callback for every token that intersects the range.
 * If the callback returns `false`, iteration stops and `false` is returned.
 * Otherwise, `true` is returned.
 */
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;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewModel/modelLineProjection.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




function createModelLineProjection(lineBreakData, isVisible) {
    if (lineBreakData === null) {
        // No mapping needed
        if (isVisible) {
            return IdentityModelLineProjection.INSTANCE;
        }
        return HiddenModelLineProjection.INSTANCE;
    }
    else {
        return new ModelLineProjection(lineBreakData, isVisible);
    }
}
/**
 * This projection is used to
 * * wrap model lines
 * * inject text
 */
class ModelLineProjection {
    constructor(lineBreakData, isVisible) {
        this._projectionData = lineBreakData;
        this._isVisible = isVisible;
    }
    isVisible() {
        return this._isVisible;
    }
    setVisible(isVisible) {
        this._isVisible = isVisible;
        return this;
    }
    getProjectionData() {
        return this._projectionData;
    }
    getViewLineCount() {
        if (!this._isVisible) {
            return 0;
        }
        return this._projectionData.getOutputLineCount();
    }
    getViewLineContent(model, modelLineNumber, outputLineIndex) {
        this._assertVisible();
        const startOffsetInInputWithInjections = outputLineIndex > 0 ? this._projectionData.breakOffsets[outputLineIndex - 1] : 0;
        const endOffsetInInputWithInjections = this._projectionData.breakOffsets[outputLineIndex];
        let r;
        if (this._projectionData.injectionOffsets !== null) {
            const injectedTexts = this._projectionData.injectionOffsets.map((offset, idx) => new LineInjectedText(0, 0, offset + 1, this._projectionData.injectionOptions[idx], 0));
            const lineWithInjections = LineInjectedText.applyInjectedText(model.getLineContent(modelLineNumber), injectedTexts);
            r = lineWithInjections.substring(startOffsetInInputWithInjections, endOffsetInInputWithInjections);
        }
        else {
            r = model.getValueInRange({
                startLineNumber: modelLineNumber,
                startColumn: startOffsetInInputWithInjections + 1,
                endLineNumber: modelLineNumber,
                endColumn: endOffsetInInputWithInjections + 1
            });
        }
        if (outputLineIndex > 0) {
            r = spaces(this._projectionData.wrappedTextIndentLength) + r;
        }
        return r;
    }
    getViewLineLength(model, modelLineNumber, outputLineIndex) {
        this._assertVisible();
        return this._projectionData.getLineLength(outputLineIndex);
    }
    getViewLineMinColumn(_model, _modelLineNumber, outputLineIndex) {
        this._assertVisible();
        return this._projectionData.getMinOutputOffset(outputLineIndex) + 1;
    }
    getViewLineMaxColumn(model, modelLineNumber, outputLineIndex) {
        this._assertVisible();
        return this._projectionData.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._assertVisible();
        const lineBreakData = this._projectionData;
        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) {
                        // Injected text only starts in later wrapped lines.
                        break;
                    }
                    if (lineStartOffsetInInputWithInjections < injectedTextEndOffsetInInputWithInjections) {
                        // Injected text ends after or in this line (but also starts in or before this line).
                        const options = injectionOptions[currentInjectedOffset];
                        if (options.inlineClassName) {
                            const offset = (outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0);
                            const start = offset + Math.max(injectedTextStartOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, 0);
                            const end = offset + Math.min(injectedTextEndOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, lineEndOffsetInInputWithInjections);
                            if (start !== end) {
                                inlineDecorations.push(new SingleLineInlineDecoration(start, end, options.inlineClassName, options.inlineClassNameAffectsLetterSpacing));
                            }
                        }
                    }
                    if (injectedTextEndOffsetInInputWithInjections <= lineEndOffsetInInputWithInjections) {
                        totalInjectedTextLengthBefore += length;
                        currentInjectedOffset++;
                    }
                    else {
                        // injected text breaks into next line, process it again
                        break;
                    }
                }
            }
        }
        let lineWithInjections;
        if (injectionOffsets) {
            lineWithInjections = model.tokenization.getLineTokens(modelLineNumber).withInserted(injectionOffsets.map((offset, idx) => ({
                offset,
                text: injectionOptions[idx].content,
                tokenMetadata: LineTokens.defaultTokenMetadata
            })));
        }
        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._getViewLineData(lineWithInjections, inlineDecorationsPerOutputLine ? inlineDecorationsPerOutputLine[outputLineIndex] : null, outputLineIndex);
        }
    }
    _getViewLineData(lineWithInjections, inlineDecorations, outputLineIndex) {
        this._assertVisible();
        const lineBreakData = this._projectionData;
        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._projectionData.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 ViewLineData(lineContent, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations);
    }
    getModelColumnOfViewPosition(outputLineIndex, outputColumn) {
        this._assertVisible();
        return this._projectionData.translateToInputOffset(outputLineIndex, outputColumn - 1) + 1;
    }
    getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity = 2 /* PositionAffinity.None */) {
        this._assertVisible();
        const r = this._projectionData.translateToOutputPosition(inputColumn - 1, affinity);
        return r.toPosition(deltaLineNumber);
    }
    getViewLineNumberOfModelPosition(deltaLineNumber, inputColumn) {
        this._assertVisible();
        const r = this._projectionData.translateToOutputPosition(inputColumn - 1);
        return deltaLineNumber + r.outputLineIndex;
    }
    normalizePosition(outputLineIndex, outputPosition, affinity) {
        const baseViewLineNumber = outputPosition.lineNumber - outputLineIndex;
        const normalizedOutputPosition = this._projectionData.normalizeOutputPosition(outputLineIndex, outputPosition.column - 1, affinity);
        const result = normalizedOutputPosition.toPosition(baseViewLineNumber);
        return result;
    }
    getInjectedTextAt(outputLineIndex, outputColumn) {
        return this._projectionData.getInjectedText(outputLineIndex, outputColumn - 1);
    }
    _assertVisible() {
        if (!this._isVisible) {
            throw new Error('Not supported');
        }
    }
}
/**
 * This projection does not change the model line.
*/
class 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 ViewLineData(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 Position(deltaLineNumber, inputColumn);
    }
    getViewLineNumberOfModelPosition(deltaLineNumber, _inputColumn) {
        return deltaLineNumber;
    }
    normalizePosition(outputLineIndex, outputPosition, affinity) {
        return outputPosition;
    }
    getInjectedTextAt(_outputLineIndex, _outputColumn) {
        return null;
    }
}
IdentityModelLineProjection.INSTANCE = new IdentityModelLineProjection();
/**
 * This projection hides the model line.
 */
class 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');
    }
}
HiddenModelLineProjection.INSTANCE = new HiddenModelLineProjection();
const _spaces = [''];
function spaces(count) {
    if (count >= _spaces.length) {
        for (let i = 1; i <= count; i++) {
            _spaces[i] = _makeSpaces(i);
        }
    }
    return _spaces[count];
}
function _makeSpaces(count) {
    return new Array(count + 1).join(' ');
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/prefixSumComputer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class PrefixSumComputer {
    constructor(values) {
        this.values = values;
        this.prefixSum = new Uint32Array(values.length);
        this.prefixSumValidIndex = new Int32Array(1);
        this.prefixSumValidIndex[0] = -1;
    }
    insertValues(insertIndex, insertValues) {
        insertIndex = toUint32(insertIndex);
        const oldValues = this.values;
        const oldPrefixSum = this.prefixSum;
        const insertValuesLen = insertValues.length;
        if (insertValuesLen === 0) {
            return false;
        }
        this.values = new Uint32Array(oldValues.length + insertValuesLen);
        this.values.set(oldValues.subarray(0, insertIndex), 0);
        this.values.set(oldValues.subarray(insertIndex), insertIndex + insertValuesLen);
        this.values.set(insertValues, insertIndex);
        if (insertIndex - 1 < this.prefixSumValidIndex[0]) {
            this.prefixSumValidIndex[0] = insertIndex - 1;
        }
        this.prefixSum = new Uint32Array(this.values.length);
        if (this.prefixSumValidIndex[0] >= 0) {
            this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
        }
        return true;
    }
    setValue(index, value) {
        index = toUint32(index);
        value = toUint32(value);
        if (this.values[index] === value) {
            return false;
        }
        this.values[index] = value;
        if (index - 1 < this.prefixSumValidIndex[0]) {
            this.prefixSumValidIndex[0] = index - 1;
        }
        return true;
    }
    removeValues(startIndex, count) {
        startIndex = toUint32(startIndex);
        count = toUint32(count);
        const oldValues = this.values;
        const oldPrefixSum = this.prefixSum;
        if (startIndex >= oldValues.length) {
            return false;
        }
        const maxCount = oldValues.length - startIndex;
        if (count >= maxCount) {
            count = maxCount;
        }
        if (count === 0) {
            return false;
        }
        this.values = new Uint32Array(oldValues.length - count);
        this.values.set(oldValues.subarray(0, startIndex), 0);
        this.values.set(oldValues.subarray(startIndex + count), startIndex);
        this.prefixSum = new Uint32Array(this.values.length);
        if (startIndex - 1 < this.prefixSumValidIndex[0]) {
            this.prefixSumValidIndex[0] = startIndex - 1;
        }
        if (this.prefixSumValidIndex[0] >= 0) {
            this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
        }
        return true;
    }
    getTotalSum() {
        if (this.values.length === 0) {
            return 0;
        }
        return this._getPrefixSum(this.values.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 = toUint32(index);
        return this._getPrefixSum(index);
    }
    _getPrefixSum(index) {
        if (index <= this.prefixSumValidIndex[0]) {
            return this.prefixSum[index];
        }
        let startIndex = this.prefixSumValidIndex[0] + 1;
        if (startIndex === 0) {
            this.prefixSum[0] = this.values[0];
            startIndex++;
        }
        if (index >= this.values.length) {
            index = this.values.length - 1;
        }
        for (let i = startIndex; i <= index; i++) {
            this.prefixSum[i] = this.prefixSum[i - 1] + this.values[i];
        }
        this.prefixSumValidIndex[0] = Math.max(this.prefixSumValidIndex[0], index);
        return this.prefixSum[index];
    }
    getIndexOf(sum) {
        sum = Math.floor(sum);
        // Compute all sums (to get a fully valid prefixSum)
        this.getTotalSum();
        let low = 0;
        let high = this.values.length - 1;
        let mid = 0;
        let midStop = 0;
        let midStart = 0;
        while (low <= high) {
            mid = low + ((high - low) / 2) | 0;
            midStop = this.prefixSum[mid];
            midStart = midStop - this.values[mid];
            if (sum < midStart) {
                high = mid - 1;
            }
            else if (sum >= midStop) {
                low = mid + 1;
            }
            else {
                break;
            }
        }
        return new PrefixSumIndexOfResult(mid, sum - midStart);
    }
}
/**
 * {@link getIndexOf} has an amortized runtime complexity of O(1).
 *
 * ({@link PrefixSumComputer.getIndexOf} is just  O(log n))
*/
class ConstantTimePrefixSumComputer {
    constructor(values) {
        this._values = values;
        this._isValid = false;
        this._validEndIndex = -1;
        this._prefixSum = [];
        this._indexBySum = [];
    }
    /**
     * @returns SUM(0 <= j < values.length, values[j])
     */
    getTotalSum() {
        this._ensureValid();
        return this._indexBySum.length;
    }
    /**
     * Returns the sum of the first `count` many items.
     * @returns `SUM(0 <= j < count, values[j])`.
     */
    getPrefixSum(count) {
        this._ensureValid();
        if (count === 0) {
            return 0;
        }
        return this._prefixSum[count - 1];
    }
    /**
     * @returns `result`, such that `getPrefixSum(result.index) + result.remainder = sum`
     */
    getIndexOf(sum) {
        this._ensureValid();
        const idx = this._indexBySum[sum];
        const viewLinesAbove = idx > 0 ? this._prefixSum[idx - 1] : 0;
        return new PrefixSumIndexOfResult(idx, sum - viewLinesAbove);
    }
    removeValues(start, deleteCount) {
        this._values.splice(start, deleteCount);
        this._invalidate(start);
    }
    insertValues(insertIndex, insertArr) {
        this._values = arrayInsert(this._values, insertIndex, insertArr);
        this._invalidate(insertIndex);
    }
    _invalidate(index) {
        this._isValid = false;
        this._validEndIndex = Math.min(this._validEndIndex, index - 1);
    }
    _ensureValid() {
        if (this._isValid) {
            return;
        }
        for (let i = this._validEndIndex + 1, len = this._values.length; i < len; i++) {
            const value = this._values[i];
            const sumAbove = i > 0 ? this._prefixSum[i - 1] : 0;
            this._prefixSum[i] = sumAbove + value;
            for (let j = 0; j < value; j++) {
                this._indexBySum[sumAbove + j] = i;
            }
        }
        // trim things
        this._prefixSum.length = this._values.length;
        this._indexBySum.length = this._prefixSum[this._prefixSum.length - 1];
        // mark as valid
        this._isValid = true;
        this._validEndIndex = this._values.length - 1;
    }
    setValue(index, value) {
        if (this._values[index] === value) {
            // no change
            return;
        }
        this._values[index] = value;
        this._invalidate(index);
    }
}
class PrefixSumIndexOfResult {
    constructor(index, remainder) {
        this.index = index;
        this.remainder = remainder;
        this._prefixSumIndexOfResultBrand = undefined;
        this.index = index;
        this.remainder = remainder;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewModel/viewModelLines.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/










class ViewModelLinesFromProjectedModel {
    constructor(editorId, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, tabSize, wrappingStrategy, wrappingColumn, wrappingIndent) {
        this._editorId = editorId;
        this.model = model;
        this._validModelVersionId = -1;
        this._domLineBreaksComputerFactory = domLineBreaksComputerFactory;
        this._monospaceLineBreaksComputerFactory = monospaceLineBreaksComputerFactory;
        this.fontInfo = fontInfo;
        this.tabSize = tabSize;
        this.wrappingStrategy = wrappingStrategy;
        this.wrappingColumn = wrappingColumn;
        this.wrappingIndent = wrappingIndent;
        this._constructLines(/*resetHiddenAreas*/ true, null);
    }
    dispose() {
        this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, []);
    }
    createCoordinatesConverter() {
        return new CoordinatesConverter(this);
    }
    _constructLines(resetHiddenAreas, previousLineBreaks) {
        this.modelLineProjections = [];
        if (resetHiddenAreas) {
            this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, []);
        }
        const linesContent = this.model.getLinesContent();
        const injectedTextDecorations = this.model.getInjectedTextDecorations(this._editorId);
        const lineCount = linesContent.length;
        const lineBreaksComputer = this.createLineBreaksComputer();
        const injectedTextQueue = new ArrayQueue(LineInjectedText.fromDecorations(injectedTextDecorations));
        for (let i = 0; i < lineCount; i++) {
            const lineInjectedText = injectedTextQueue.takeWhile(t => t.lineNumber === i + 1);
            lineBreaksComputer.addRequest(linesContent[i], lineInjectedText, previousLineBreaks ? previousLineBreaks[i] : null);
        }
        const linesBreaks = lineBreaksComputer.finalize();
        const values = [];
        const hiddenAreas = this.hiddenAreasDecorationIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(Range.compareRangesUsingStarts);
        let hiddenAreaStart = 1, hiddenAreaEnd = 0;
        let hiddenAreaIdx = -1;
        let nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : lineCount + 2;
        for (let i = 0; i < lineCount; i++) {
            const lineNumber = i + 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 = createModelLineProjection(linesBreaks[i], !isInHiddenArea);
            values[i] = line.getViewLineCount();
            this.modelLineProjections[i] = line;
        }
        this._validModelVersionId = this.model.getVersionId();
        this.projectedModelLineLineCounts = new ConstantTimePrefixSumComputer(values);
    }
    getHiddenAreas() {
        return this.hiddenAreasDecorationIds.map((decId) => this.model.getDecorationRange(decId));
    }
    setHiddenAreas(_ranges) {
        const validatedRanges = _ranges.map(r => this.model.validateRange(r));
        const newRanges = normalizeLineRanges(validatedRanges);
        // TODO@Martin: Please stop calling this method on each model change!
        // This checks if there really was a change
        const oldRanges = this.hiddenAreasDecorationIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(Range.compareRangesUsingStarts);
        if (newRanges.length === oldRanges.length) {
            let hasDifference = false;
            for (let i = 0; i < newRanges.length; i++) {
                if (!newRanges[i].equalsRange(oldRanges[i])) {
                    hasDifference = true;
                    break;
                }
            }
            if (!hasDifference) {
                return false;
            }
        }
        const newDecorations = newRanges.map((r) => ({
            range: r,
            options: ModelDecorationOptions.EMPTY,
        }));
        this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, newDecorations);
        const hiddenAreas = newRanges;
        let hiddenAreaStart = 1, hiddenAreaEnd = 0;
        let hiddenAreaIdx = -1;
        let nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.modelLineProjections.length + 2;
        let hasVisibleLine = false;
        for (let i = 0; i < this.modelLineProjections.length; i++) {
            const lineNumber = i + 1;
            if (lineNumber === nextLineNumberToUpdateHiddenArea) {
                hiddenAreaIdx++;
                hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
                hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
                nextLineNumberToUpdateHiddenArea = (hiddenAreaIdx + 1 < hiddenAreas.length) ? hiddenAreaEnd + 1 : this.modelLineProjections.length + 2;
            }
            let lineChanged = false;
            if (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd) {
                // Line should be hidden
                if (this.modelLineProjections[i].isVisible()) {
                    this.modelLineProjections[i] = this.modelLineProjections[i].setVisible(false);
                    lineChanged = true;
                }
            }
            else {
                hasVisibleLine = true;
                // Line should be visible
                if (!this.modelLineProjections[i].isVisible()) {
                    this.modelLineProjections[i] = this.modelLineProjections[i].setVisible(true);
                    lineChanged = true;
                }
            }
            if (lineChanged) {
                const newOutputLineCount = this.modelLineProjections[i].getViewLineCount();
                this.projectedModelLineLineCounts.setValue(i, newOutputLineCount);
            }
        }
        if (!hasVisibleLine) {
            // Cannot have everything be hidden => reveal everything!
            this.setHiddenAreas([]);
        }
        return true;
    }
    modelPositionIsVisible(modelLineNumber, _modelColumn) {
        if (modelLineNumber < 1 || modelLineNumber > this.modelLineProjections.length) {
            // invalid arguments
            return false;
        }
        return this.modelLineProjections[modelLineNumber - 1].isVisible();
    }
    getModelLineViewLineCount(modelLineNumber) {
        if (modelLineNumber < 1 || modelLineNumber > this.modelLineProjections.length) {
            // invalid arguments
            return 1;
        }
        return this.modelLineProjections[modelLineNumber - 1].getViewLineCount();
    }
    setTabSize(newTabSize) {
        if (this.tabSize === newTabSize) {
            return false;
        }
        this.tabSize = newTabSize;
        this._constructLines(/*resetHiddenAreas*/ false, null);
        return true;
    }
    setWrappingSettings(fontInfo, wrappingStrategy, wrappingColumn, wrappingIndent) {
        const equalFontInfo = this.fontInfo.equals(fontInfo);
        const equalWrappingStrategy = (this.wrappingStrategy === wrappingStrategy);
        const equalWrappingColumn = (this.wrappingColumn === wrappingColumn);
        const equalWrappingIndent = (this.wrappingIndent === wrappingIndent);
        if (equalFontInfo && equalWrappingStrategy && equalWrappingColumn && equalWrappingIndent) {
            return false;
        }
        const onlyWrappingColumnChanged = (equalFontInfo && equalWrappingStrategy && !equalWrappingColumn && equalWrappingIndent);
        this.fontInfo = fontInfo;
        this.wrappingStrategy = wrappingStrategy;
        this.wrappingColumn = wrappingColumn;
        this.wrappingIndent = wrappingIndent;
        let previousLineBreaks = null;
        if (onlyWrappingColumnChanged) {
            previousLineBreaks = [];
            for (let i = 0, len = this.modelLineProjections.length; i < len; i++) {
                previousLineBreaks[i] = this.modelLineProjections[i].getProjectionData();
            }
        }
        this._constructLines(/*resetHiddenAreas*/ false, previousLineBreaks);
        return true;
    }
    createLineBreaksComputer() {
        const lineBreaksComputerFactory = (this.wrappingStrategy === 'advanced'
            ? this._domLineBreaksComputerFactory
            : this._monospaceLineBreaksComputerFactory);
        return lineBreaksComputerFactory.createLineBreaksComputer(this.fontInfo, this.tabSize, this.wrappingColumn, this.wrappingIndent);
    }
    onModelFlushed() {
        this._constructLines(/*resetHiddenAreas*/ true, null);
    }
    onModelLinesDeleted(versionId, fromLineNumber, toLineNumber) {
        if (!versionId || versionId <= this._validModelVersionId) {
            // Here we check for versionId in case the lines were reconstructed in the meantime.
            // We don't want to apply stale change events on top of a newer read model state.
            return null;
        }
        const outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.projectedModelLineLineCounts.getPrefixSum(fromLineNumber - 1) + 1);
        const outputToLineNumber = this.projectedModelLineLineCounts.getPrefixSum(toLineNumber);
        this.modelLineProjections.splice(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
        this.projectedModelLineLineCounts.removeValues(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
        return new ViewLinesDeletedEvent(outputFromLineNumber, outputToLineNumber);
    }
    onModelLinesInserted(versionId, fromLineNumber, _toLineNumber, lineBreaks) {
        if (!versionId || versionId <= this._validModelVersionId) {
            // Here we check for versionId in case the lines were reconstructed in the meantime.
            // We don't want to apply stale change events on top of a newer read model state.
            return null;
        }
        // cannot use this.getHiddenAreas() because those decorations have already seen the effect of this model change
        const isInHiddenArea = (fromLineNumber > 2 && !this.modelLineProjections[fromLineNumber - 2].isVisible());
        const outputFromLineNumber = (fromLineNumber === 1 ? 1 : this.projectedModelLineLineCounts.getPrefixSum(fromLineNumber - 1) + 1);
        let totalOutputLineCount = 0;
        const insertLines = [];
        const insertPrefixSumValues = [];
        for (let i = 0, len = lineBreaks.length; i < len; i++) {
            const line = createModelLineProjection(lineBreaks[i], !isInHiddenArea);
            insertLines.push(line);
            const outputLineCount = line.getViewLineCount();
            totalOutputLineCount += outputLineCount;
            insertPrefixSumValues[i] = outputLineCount;
        }
        // TODO@Alex: use arrays.arrayInsert
        this.modelLineProjections =
            this.modelLineProjections.slice(0, fromLineNumber - 1)
                .concat(insertLines)
                .concat(this.modelLineProjections.slice(fromLineNumber - 1));
        this.projectedModelLineLineCounts.insertValues(fromLineNumber - 1, insertPrefixSumValues);
        return new ViewLinesInsertedEvent(outputFromLineNumber, outputFromLineNumber + totalOutputLineCount - 1);
    }
    onModelLineChanged(versionId, lineNumber, lineBreakData) {
        if (versionId !== null && versionId <= this._validModelVersionId) {
            // Here we check for versionId in case the lines were reconstructed in the meantime.
            // We don't want to apply stale change events on top of a newer read model state.
            return [false, null, null, null];
        }
        const lineIndex = lineNumber - 1;
        const oldOutputLineCount = this.modelLineProjections[lineIndex].getViewLineCount();
        const isVisible = this.modelLineProjections[lineIndex].isVisible();
        const line = createModelLineProjection(lineBreakData, isVisible);
        this.modelLineProjections[lineIndex] = line;
        const newOutputLineCount = this.modelLineProjections[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.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
            changeTo = changeFrom + newOutputLineCount - 1;
            deleteFrom = changeTo + 1;
            deleteTo = deleteFrom + (oldOutputLineCount - newOutputLineCount) - 1;
            lineMappingChanged = true;
        }
        else if (oldOutputLineCount < newOutputLineCount) {
            changeFrom = this.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
            changeTo = changeFrom + oldOutputLineCount - 1;
            insertFrom = changeTo + 1;
            insertTo = insertFrom + (newOutputLineCount - oldOutputLineCount) - 1;
            lineMappingChanged = true;
        }
        else {
            changeFrom = this.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
            changeTo = changeFrom + newOutputLineCount - 1;
        }
        this.projectedModelLineLineCounts.setValue(lineIndex, newOutputLineCount);
        const viewLinesChangedEvent = (changeFrom <= changeTo ? new ViewLinesChangedEvent(changeFrom, changeTo - changeFrom + 1) : null);
        const viewLinesInsertedEvent = (insertFrom <= insertTo ? new ViewLinesInsertedEvent(insertFrom, insertTo) : null);
        const viewLinesDeletedEvent = (deleteFrom <= deleteTo ? new ViewLinesDeletedEvent(deleteFrom, deleteTo) : null);
        return [lineMappingChanged, viewLinesChangedEvent, viewLinesInsertedEvent, viewLinesDeletedEvent];
    }
    acceptVersionId(versionId) {
        this._validModelVersionId = versionId;
        if (this.modelLineProjections.length === 1 && !this.modelLineProjections[0].isVisible()) {
            // At least one line must be visible => reset hidden areas
            this.setHiddenAreas([]);
        }
    }
    getViewLineCount() {
        return this.projectedModelLineLineCounts.getTotalSum();
    }
    _toValidViewLineNumber(viewLineNumber) {
        if (viewLineNumber < 1) {
            return 1;
        }
        const viewLineCount = this.getViewLineCount();
        if (viewLineNumber > viewLineCount) {
            return viewLineCount;
        }
        return viewLineNumber | 0;
    }
    getActiveIndentGuide(viewLineNumber, minLineNumber, maxLineNumber) {
        viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
        minLineNumber = this._toValidViewLineNumber(minLineNumber);
        maxLineNumber = this._toValidViewLineNumber(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.model.guides.getActiveIndentGuide(modelPosition.lineNumber, modelMinPosition.lineNumber, modelMaxPosition.lineNumber);
        const viewStartPosition = this.convertModelPositionToViewPosition(result.startLineNumber, 1);
        const viewEndPosition = this.convertModelPositionToViewPosition(result.endLineNumber, this.model.getLineMaxColumn(result.endLineNumber));
        return {
            startLineNumber: viewStartPosition.lineNumber,
            endLineNumber: viewEndPosition.lineNumber,
            indent: result.indent
        };
    }
    // #region ViewLineInfo
    getViewLineInfo(viewLineNumber) {
        viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
        const r = this.projectedModelLineLineCounts.getIndexOf(viewLineNumber - 1);
        const lineIndex = r.index;
        const remainder = r.remainder;
        return new ViewLineInfo(lineIndex + 1, remainder);
    }
    getMinColumnOfViewLine(viewLineInfo) {
        return this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewLineMinColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
    }
    getMaxColumnOfViewLine(viewLineInfo) {
        return this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewLineMaxColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
    }
    getModelStartPositionOfViewLine(viewLineInfo) {
        const line = this.modelLineProjections[viewLineInfo.modelLineNumber - 1];
        const minViewColumn = line.getViewLineMinColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
        const column = line.getModelColumnOfViewPosition(viewLineInfo.modelLineWrappedLineIdx, minViewColumn);
        return new Position(viewLineInfo.modelLineNumber, column);
    }
    getModelEndPositionOfViewLine(viewLineInfo) {
        const line = this.modelLineProjections[viewLineInfo.modelLineNumber - 1];
        const maxViewColumn = line.getViewLineMaxColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
        const column = line.getModelColumnOfViewPosition(viewLineInfo.modelLineWrappedLineIdx, maxViewColumn);
        return new Position(viewLineInfo.modelLineNumber, column);
    }
    getViewLineInfosGroupedByModelRanges(viewStartLineNumber, viewEndLineNumber) {
        const startViewLine = this.getViewLineInfo(viewStartLineNumber);
        const endViewLine = this.getViewLineInfo(viewEndLineNumber);
        const result = new Array();
        let lastVisibleModelPos = this.getModelStartPositionOfViewLine(startViewLine);
        let viewLines = new Array();
        for (let curModelLine = startViewLine.modelLineNumber; curModelLine <= endViewLine.modelLineNumber; curModelLine++) {
            const line = this.modelLineProjections[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 i = startOffset; i < endOffset; i++) {
                    viewLines.push(new ViewLineInfo(curModelLine, i));
                }
            }
            if (!line.isVisible() && lastVisibleModelPos) {
                const lastVisibleModelPos2 = new Position(curModelLine - 1, this.model.getLineMaxColumn(curModelLine - 1) + 1);
                const modelRange = Range.fromPositions(lastVisibleModelPos, lastVisibleModelPos2);
                result.push(new ViewLineInfoGroupedByModelRange(modelRange, viewLines));
                viewLines = [];
                lastVisibleModelPos = null;
            }
            else if (line.isVisible() && !lastVisibleModelPos) {
                lastVisibleModelPos = new Position(curModelLine, 1);
            }
        }
        if (lastVisibleModelPos) {
            const modelRange = Range.fromPositions(lastVisibleModelPos, this.getModelEndPositionOfViewLine(endViewLine));
            result.push(new ViewLineInfoGroupedByModelRange(modelRange, viewLines));
        }
        return result;
    }
    // #endregion
    getViewLinesBracketGuides(viewStartLineNumber, viewEndLineNumber, activeViewPosition, options) {
        const modelActivePosition = activeViewPosition ? this.convertViewPositionToModelPosition(activeViewPosition.lineNumber, activeViewPosition.column) : null;
        const resultPerViewLine = [];
        for (const group of this.getViewLineInfosGroupedByModelRanges(viewStartLineNumber, viewEndLineNumber)) {
            const modelRangeStartLineNumber = group.modelRange.startLineNumber;
            const bracketGuidesPerModelLine = this.model.guides.getLinesBracketGuides(modelRangeStartLineNumber, group.modelRange.endLineNumber, modelActivePosition, options);
            for (const viewLineInfo of group.viewLines) {
                const bracketGuides = bracketGuidesPerModelLine[viewLineInfo.modelLineNumber - modelRangeStartLineNumber];
                // visibleColumns stay as they are (this is a bug and needs to be fixed, but it is not a regression)
                // model-columns must be converted to view-model columns.
                const result = bracketGuides.map(g => {
                    if (g.forWrappedLinesAfterColumn !== -1) {
                        const p = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.forWrappedLinesAfterColumn);
                        if (p.lineNumber >= viewLineInfo.modelLineWrappedLineIdx) {
                            return undefined;
                        }
                    }
                    if (g.forWrappedLinesBeforeOrAtColumn !== -1) {
                        const p = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.forWrappedLinesBeforeOrAtColumn);
                        if (p.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
                            return undefined;
                        }
                    }
                    if (!g.horizontalLine) {
                        return g;
                    }
                    let column = -1;
                    if (g.column !== -1) {
                        const p = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.column);
                        if (p.lineNumber === viewLineInfo.modelLineWrappedLineIdx) {
                            column = p.column;
                        }
                        else if (p.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
                            column = this.getMinColumnOfViewLine(viewLineInfo);
                        }
                        else if (p.lineNumber > viewLineInfo.modelLineWrappedLineIdx) {
                            return undefined;
                        }
                    }
                    const viewPosition = this.convertModelPositionToViewPosition(viewLineInfo.modelLineNumber, g.horizontalLine.endColumn);
                    const p = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.horizontalLine.endColumn);
                    if (p.lineNumber === viewLineInfo.modelLineWrappedLineIdx) {
                        return new IndentGuide(g.visibleColumn, column, g.className, new IndentGuideHorizontalLine(g.horizontalLine.top, viewPosition.column), -1, -1);
                    }
                    else if (p.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
                        return undefined;
                    }
                    else {
                        if (g.visibleColumn !== -1) {
                            // Don't repeat horizontal lines that use visibleColumn for unrelated lines.
                            return undefined;
                        }
                        return new IndentGuide(g.visibleColumn, column, g.className, new IndentGuideHorizontalLine(g.horizontalLine.top, this.getMaxColumnOfViewLine(viewLineInfo)), -1, -1);
                    }
                });
                resultPerViewLine.push(result.filter((r) => !!r));
            }
        }
        return resultPerViewLine;
    }
    getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
        // TODO: Use the same code as in `getViewLinesBracketGuides`.
        // Future TODO: Merge with `getViewLinesBracketGuides`.
        // However, this requires more refactoring of indent guides.
        viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
        viewEndLineNumber = this._toValidViewLineNumber(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.modelLineProjections[modelLineIndex];
            if (line.isVisible()) {
                const viewLineStartIndex = line.getViewLineNumberOfModelPosition(0, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
                const viewLineEndIndex = line.getViewLineNumberOfModelPosition(0, this.model.getLineMaxColumn(modelLineIndex + 1));
                const count = viewLineEndIndex - viewLineStartIndex + 1;
                let option = 0 /* IndentGuideRepeatOption.BlockNone */;
                if (count > 1 && line.getViewLineMinColumn(this.model, modelLineIndex + 1, viewLineEndIndex) === 1) {
                    // wrapped lines should block indent guides
                    option = (viewLineStartIndex === 0 ? 1 /* IndentGuideRepeatOption.BlockSubsequent */ : 2 /* IndentGuideRepeatOption.BlockAll */);
                }
                resultRepeatCount.push(count);
                resultRepeatOption.push(option);
                // merge into previous request
                if (reqStart === null) {
                    reqStart = new Position(modelLineIndex + 1, 0);
                }
            }
            else {
                // hit invisible line => flush request
                if (reqStart !== null) {
                    result = result.concat(this.model.guides.getLinesIndentGuides(reqStart.lineNumber, modelLineIndex));
                    reqStart = null;
                }
            }
        }
        if (reqStart !== null) {
            result = result.concat(this.model.guides.getLinesIndentGuides(reqStart.lineNumber, modelEnd.lineNumber));
            reqStart = null;
        }
        const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
        const viewIndents = new Array(viewLineCount);
        let currIndex = 0;
        for (let i = 0, len = result.length; i < len; i++) {
            let value = result[i];
            const count = Math.min(viewLineCount - currIndex, resultRepeatCount[i]);
            const option = resultRepeatOption[i];
            let blockAtIndex;
            if (option === 2 /* IndentGuideRepeatOption.BlockAll */) {
                blockAtIndex = 0;
            }
            else if (option === 1 /* IndentGuideRepeatOption.BlockSubsequent */) {
                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.getViewLineInfo(viewLineNumber);
        return this.modelLineProjections[info.modelLineNumber - 1].getViewLineContent(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
    }
    getViewLineLength(viewLineNumber) {
        const info = this.getViewLineInfo(viewLineNumber);
        return this.modelLineProjections[info.modelLineNumber - 1].getViewLineLength(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
    }
    getViewLineMinColumn(viewLineNumber) {
        const info = this.getViewLineInfo(viewLineNumber);
        return this.modelLineProjections[info.modelLineNumber - 1].getViewLineMinColumn(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
    }
    getViewLineMaxColumn(viewLineNumber) {
        const info = this.getViewLineInfo(viewLineNumber);
        return this.modelLineProjections[info.modelLineNumber - 1].getViewLineMaxColumn(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
    }
    getViewLineData(viewLineNumber) {
        const info = this.getViewLineInfo(viewLineNumber);
        return this.modelLineProjections[info.modelLineNumber - 1].getViewLineData(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
    }
    getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
        viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
        viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
        const start = this.projectedModelLineLineCounts.getIndexOf(viewStartLineNumber - 1);
        let viewLineNumber = viewStartLineNumber;
        const startModelLineIndex = start.index;
        const startRemainder = start.remainder;
        const result = [];
        for (let modelLineIndex = startModelLineIndex, len = this.model.getLineCount(); modelLineIndex < len; modelLineIndex++) {
            const line = this.modelLineProjections[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.model, modelLineIndex + 1, fromViewLineIndex, remainingViewLineCount, viewLineNumber - viewStartLineNumber, needed, result);
            viewLineNumber += remainingViewLineCount;
            if (lastLine) {
                break;
            }
        }
        return result;
    }
    validateViewPosition(viewLineNumber, viewColumn, expectedModelPosition) {
        viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
        const r = this.projectedModelLineLineCounts.getIndexOf(viewLineNumber - 1);
        const lineIndex = r.index;
        const remainder = r.remainder;
        const line = this.modelLineProjections[lineIndex];
        const minColumn = line.getViewLineMinColumn(this.model, lineIndex + 1, remainder);
        const maxColumn = line.getViewLineMaxColumn(this.model, lineIndex + 1, remainder);
        if (viewColumn < minColumn) {
            viewColumn = minColumn;
        }
        if (viewColumn > maxColumn) {
            viewColumn = maxColumn;
        }
        const computedModelColumn = line.getModelColumnOfViewPosition(remainder, viewColumn);
        const computedModelPosition = this.model.validatePosition(new Position(lineIndex + 1, computedModelColumn));
        if (computedModelPosition.equals(expectedModelPosition)) {
            return new Position(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 Range(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column);
    }
    convertViewPositionToModelPosition(viewLineNumber, viewColumn) {
        const info = this.getViewLineInfo(viewLineNumber);
        const inputColumn = this.modelLineProjections[info.modelLineNumber - 1].getModelColumnOfViewPosition(info.modelLineWrappedLineIdx, viewColumn);
        // console.log('out -> in ' + viewLineNumber + ',' + viewColumn + ' ===> ' + (lineIndex+1) + ',' + inputColumn);
        return this.model.validatePosition(new Position(info.modelLineNumber, inputColumn));
    }
    convertViewRangeToModelRange(viewRange) {
        const start = this.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn);
        const end = this.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn);
        return new Range(start.lineNumber, start.column, end.lineNumber, end.column);
    }
    convertModelPositionToViewPosition(_modelLineNumber, _modelColumn, affinity = 2 /* PositionAffinity.None */) {
        const validPosition = this.model.validatePosition(new Position(_modelLineNumber, _modelColumn));
        const inputLineNumber = validPosition.lineNumber;
        const inputColumn = validPosition.column;
        let lineIndex = inputLineNumber - 1, lineIndexChanged = false;
        while (lineIndex > 0 && !this.modelLineProjections[lineIndex].isVisible()) {
            lineIndex--;
            lineIndexChanged = true;
        }
        if (lineIndex === 0 && !this.modelLineProjections[lineIndex].isVisible()) {
            // Could not reach a real line
            // console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + 1 + ',' + 1);
            return new Position(1, 1);
        }
        const deltaLineNumber = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
        let r;
        if (lineIndexChanged) {
            r = this.modelLineProjections[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1), affinity);
        }
        else {
            r = this.modelLineProjections[inputLineNumber - 1].getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity);
        }
        // console.log('in -> out ' + inputLineNumber + ',' + inputColumn + ' ===> ' + r.lineNumber + ',' + r);
        return r;
    }
    /**
     * @param affinity The affinity in case of an empty range. Has no effect for non-empty ranges.
    */
    convertModelRangeToViewRange(modelRange, affinity = 0 /* PositionAffinity.Left */) {
        if (modelRange.isEmpty()) {
            const start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn, affinity);
            return Range.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 Range(start.lineNumber, start.column, end.lineNumber, end.column);
        }
    }
    getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
        let lineIndex = modelLineNumber - 1;
        if (this.modelLineProjections[lineIndex].isVisible()) {
            // this model line is visible
            const deltaLineNumber = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
            return this.modelLineProjections[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, modelColumn);
        }
        // this model line is not visible
        while (lineIndex > 0 && !this.modelLineProjections[lineIndex].isVisible()) {
            lineIndex--;
        }
        if (lineIndex === 0 && !this.modelLineProjections[lineIndex].isVisible()) {
            // Could not reach a real line
            return 1;
        }
        const deltaLineNumber = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
        return this.modelLineProjections[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1));
    }
    getDecorationsInRange(range, ownerId, filterOutValidation) {
        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) {
            // most likely there are no hidden lines => fast path
            // fetch decorations from column 1 to cover the case of wrapped lines that have whole line decorations at column 1
            return this.model.getDecorationsInRange(new Range(modelStart.lineNumber, 1, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation);
        }
        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.modelLineProjections[modelLineIndex];
            if (line.isVisible()) {
                // merge into previous request
                if (reqStart === null) {
                    reqStart = new Position(modelLineIndex + 1, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
                }
            }
            else {
                // hit invisible line => flush request
                if (reqStart !== null) {
                    const maxLineColumn = this.model.getLineMaxColumn(modelLineIndex);
                    result = result.concat(this.model.getDecorationsInRange(new Range(reqStart.lineNumber, reqStart.column, modelLineIndex, maxLineColumn), ownerId, filterOutValidation));
                    reqStart = null;
                }
            }
        }
        if (reqStart !== null) {
            result = result.concat(this.model.getDecorationsInRange(new Range(reqStart.lineNumber, reqStart.column, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation));
            reqStart = null;
        }
        result.sort((a, b) => {
            const res = Range.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;
        });
        // Eliminate duplicate decorations that might have intersected our visible ranges multiple times
        const finalResult = [];
        let finalResultLen = 0;
        let prevDecId = null;
        for (const dec of result) {
            const decId = dec.id;
            if (prevDecId === decId) {
                // skip
                continue;
            }
            prevDecId = decId;
            finalResult[finalResultLen++] = dec;
        }
        return finalResult;
    }
    getInjectedTextAt(position) {
        const info = this.getViewLineInfo(position.lineNumber);
        return this.modelLineProjections[info.modelLineNumber - 1].getInjectedTextAt(info.modelLineWrappedLineIdx, position.column);
    }
    normalizePosition(position, affinity) {
        const info = this.getViewLineInfo(position.lineNumber);
        return this.modelLineProjections[info.modelLineNumber - 1].normalizePosition(info.modelLineWrappedLineIdx, position, affinity);
    }
    getLineIndentColumn(lineNumber) {
        const info = this.getViewLineInfo(lineNumber);
        if (info.modelLineWrappedLineIdx === 0) {
            return this.model.getLineIndentColumn(info.modelLineNumber);
        }
        // wrapped lines have no indentation.
        // We deliberately don't handle the case that indentation is wrapped
        // to avoid two view lines reporting indentation for the very same model line.
        return 0;
    }
}
/**
 * Overlapping unsorted ranges:
 * [   )      [ )       [  )
 *    [    )      [       )
 * ->
 * Non overlapping sorted ranges:
 * [       )  [ ) [        )
 *
 * Note: This function only considers line information! Columns are ignored.
*/
function normalizeLineRanges(ranges) {
    if (ranges.length === 0) {
        return [];
    }
    const sortedRanges = ranges.slice();
    sortedRanges.sort(Range.compareRangesUsingStarts);
    const result = [];
    let currentRangeStart = sortedRanges[0].startLineNumber;
    let currentRangeEnd = sortedRanges[0].endLineNumber;
    for (let i = 1, len = sortedRanges.length; i < len; i++) {
        const range = sortedRanges[i];
        if (range.startLineNumber > currentRangeEnd + 1) {
            result.push(new Range(currentRangeStart, 1, currentRangeEnd, 1));
            currentRangeStart = range.startLineNumber;
            currentRangeEnd = range.endLineNumber;
        }
        else if (range.endLineNumber > currentRangeEnd) {
            currentRangeEnd = range.endLineNumber;
        }
    }
    result.push(new Range(currentRangeStart, 1, currentRangeEnd, 1));
    return result;
}
/**
 * Represents a view line. Can be used to efficiently query more information about it.
 */
class ViewLineInfo {
    constructor(modelLineNumber, modelLineWrappedLineIdx) {
        this.modelLineNumber = modelLineNumber;
        this.modelLineWrappedLineIdx = modelLineWrappedLineIdx;
    }
}
/**
 * A list of view lines that have a contiguous span in the model.
*/
class ViewLineInfoGroupedByModelRange {
    constructor(modelRange, viewLines) {
        this.modelRange = modelRange;
        this.viewLines = viewLines;
    }
}
class CoordinatesConverter {
    constructor(lines) {
        this._lines = lines;
    }
    // View -> Model conversion and related methods
    convertViewPositionToModelPosition(viewPosition) {
        return this._lines.convertViewPositionToModelPosition(viewPosition.lineNumber, viewPosition.column);
    }
    convertViewRangeToModelRange(viewRange) {
        return this._lines.convertViewRangeToModelRange(viewRange);
    }
    validateViewPosition(viewPosition, expectedModelPosition) {
        return this._lines.validateViewPosition(viewPosition.lineNumber, viewPosition.column, expectedModelPosition);
    }
    validateViewRange(viewRange, expectedModelRange) {
        return this._lines.validateViewRange(viewRange, expectedModelRange);
    }
    // Model -> View conversion and related methods
    convertModelPositionToViewPosition(modelPosition, affinity) {
        return this._lines.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column, affinity);
    }
    convertModelRangeToViewRange(modelRange, affinity) {
        return this._lines.convertModelRangeToViewRange(modelRange, affinity);
    }
    modelPositionIsVisible(modelPosition) {
        return this._lines.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column);
    }
    getModelLineViewLineCount(modelLineNumber) {
        return this._lines.getModelLineViewLineCount(modelLineNumber);
    }
    getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
        return this._lines.getViewLineNumberOfModelPosition(modelLineNumber, modelColumn);
    }
}
class ViewModelLinesFromModelAsIs {
    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 ViewLinesDeletedEvent(fromLineNumber, toLineNumber);
    }
    onModelLinesInserted(_versionId, fromLineNumber, toLineNumber, lineBreaks) {
        return new ViewLinesInsertedEvent(fromLineNumber, toLineNumber);
    }
    onModelLineChanged(_versionId, lineNumber, lineBreakData) {
        return [false, new ViewLinesChangedEvent(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 i = 0; i < viewLineCount; i++) {
            result[i] = 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 ViewLineData(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, ownerId, filterOutValidation) {
        return this.model.getDecorationsInRange(range, ownerId, filterOutValidation);
    }
    normalizePosition(position, affinity) {
        return this.model.normalizePosition(position, affinity);
    }
    getLineIndentColumn(lineNumber) {
        return this.model.getLineIndentColumn(lineNumber);
    }
    getInjectedTextAt(position) {
        // Identity lines collection does not support injected text.
        return null;
    }
}
class IdentityCoordinatesConverter {
    constructor(lines) {
        this._lines = lines;
    }
    _validPosition(pos) {
        return this._lines.model.validatePosition(pos);
    }
    _validRange(range) {
        return this._lines.model.validateRange(range);
    }
    // View -> Model conversion and related methods
    convertViewPositionToModelPosition(viewPosition) {
        return this._validPosition(viewPosition);
    }
    convertViewRangeToModelRange(viewRange) {
        return this._validRange(viewRange);
    }
    validateViewPosition(_viewPosition, expectedModelPosition) {
        return this._validPosition(expectedModelPosition);
    }
    validateViewRange(_viewRange, expectedModelRange) {
        return this._validRange(expectedModelRange);
    }
    // Model -> View conversion and related methods
    convertModelPositionToViewPosition(modelPosition) {
        return this._validPosition(modelPosition);
    }
    convertModelRangeToViewRange(modelRange) {
        return this._validRange(modelRange);
    }
    modelPositionIsVisible(modelPosition) {
        const lineCount = this._lines.model.getLineCount();
        if (modelPosition.lineNumber < 1 || modelPosition.lineNumber > lineCount) {
            // invalid arguments
            return false;
        }
        return true;
    }
    getModelLineViewLineCount(modelLineNumber) {
        return 1;
    }
    getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
        return modelLineNumber;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewModel/viewModelImpl.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






















const USE_IDENTITY_LINES_COLLECTION = true;
class ViewModel extends Disposable {
    constructor(editorId, configuration, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, scheduleAtNextAnimationFrame, languageConfigurationService, _themeService) {
        super();
        this.languageConfigurationService = languageConfigurationService;
        this._themeService = _themeService;
        this._editorId = editorId;
        this._configuration = configuration;
        this.model = model;
        this._eventDispatcher = new ViewModelEventDispatcher();
        this.onEvent = this._eventDispatcher.onEvent;
        this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
        this._tokenizeViewportSoon = this._register(new RunOnceScheduler(() => this.tokenizeViewport(), 50));
        this._updateConfigurationViewLineCount = this._register(new RunOnceScheduler(() => this._updateConfigurationViewLineCountNow(), 0));
        this._hasFocus = false;
        this._viewportStart = ViewportStart.create(this.model);
        if (USE_IDENTITY_LINES_COLLECTION && this.model.isTooLargeForTokenization()) {
            this._lines = new ViewModelLinesFromModelAsIs(this.model);
        }
        else {
            const options = this._configuration.options;
            const fontInfo = options.get(46 /* EditorOption.fontInfo */);
            const wrappingStrategy = options.get(127 /* EditorOption.wrappingStrategy */);
            const wrappingInfo = options.get(134 /* EditorOption.wrappingInfo */);
            const wrappingIndent = options.get(126 /* EditorOption.wrappingIndent */);
            this._lines = new ViewModelLinesFromProjectedModel(this._editorId, this.model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, this.model.getOptions().tabSize, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent);
        }
        this.coordinatesConverter = this._lines.createCoordinatesConverter();
        this._cursor = this._register(new CursorsController(model, this, this.coordinatesConverter, this.cursorConfig));
        this.viewLayout = this._register(new ViewLayout(this._configuration, this.getLineCount(), scheduleAtNextAnimationFrame));
        this._register(this.viewLayout.onDidScroll((e) => {
            if (e.scrollTopChanged) {
                this._tokenizeViewportSoon.schedule();
            }
            if (e.scrollTopChanged) {
                this._viewportStart.invalidate();
            }
            this._eventDispatcher.emitSingleViewEvent(new ViewScrollChangedEvent(e));
            this._eventDispatcher.emitOutgoingEvent(new ScrollChangedEvent(e.oldScrollWidth, e.oldScrollLeft, e.oldScrollHeight, e.oldScrollTop, e.scrollWidth, e.scrollLeft, e.scrollHeight, e.scrollTop));
        }));
        this._register(this.viewLayout.onDidContentSizeChange((e) => {
            this._eventDispatcher.emitOutgoingEvent(e);
        }));
        this._decorations = new ViewModelDecorations(this._editorId, this.model, this._configuration, this._lines, this.coordinatesConverter);
        this._registerModelEvents();
        this._register(this._configuration.onDidChangeFast((e) => {
            try {
                const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
                this._onConfigurationChanged(eventsCollector, e);
            }
            finally {
                this._eventDispatcher.endEmitViewEvents();
            }
        }));
        this._register(MinimapTokensColorTracker.getInstance().onDidChange(() => {
            this._eventDispatcher.emitSingleViewEvent(new ViewTokensColorsChangedEvent());
        }));
        this._register(this._themeService.onDidColorThemeChange((theme) => {
            this._invalidateDecorationsColorCache();
            this._eventDispatcher.emitSingleViewEvent(new ViewThemeChangedEvent(theme));
        }));
        this._updateConfigurationViewLineCountNow();
    }
    dispose() {
        // First remove listeners, as disposing the lines might end up sending
        // model decoration changed events ... and we no longer care about them ...
        super.dispose();
        this._decorations.dispose();
        this._lines.dispose();
        this._viewportStart.dispose();
        this._eventDispatcher.dispose();
    }
    createLineBreaksComputer() {
        return this._lines.createLineBreaksComputer();
    }
    addViewEventHandler(eventHandler) {
        this._eventDispatcher.addViewEventHandler(eventHandler);
    }
    removeViewEventHandler(eventHandler) {
        this._eventDispatcher.removeViewEventHandler(eventHandler);
    }
    _updateConfigurationViewLineCountNow() {
        this._configuration.setViewLineCount(this._lines.getViewLineCount());
    }
    tokenizeViewport() {
        const linesViewportData = this.viewLayout.getLinesViewportData();
        const viewVisibleRange = new Range(linesViewportData.startLineNumber, this.getLineMinColumn(linesViewportData.startLineNumber), linesViewportData.endLineNumber, this.getLineMaxColumn(linesViewportData.endLineNumber));
        const modelVisibleRanges = this._toModelVisibleRanges(viewVisibleRange);
        for (const modelVisibleRange of modelVisibleRanges) {
            this.model.tokenization.tokenizeViewport(modelVisibleRange.startLineNumber, modelVisibleRange.endLineNumber);
        }
    }
    setHasFocus(hasFocus) {
        this._hasFocus = hasFocus;
        this._cursor.setHasFocus(hasFocus);
        this._eventDispatcher.emitSingleViewEvent(new ViewFocusChangedEvent(hasFocus));
        this._eventDispatcher.emitOutgoingEvent(new FocusChangedEvent(!hasFocus, hasFocus));
    }
    onCompositionStart() {
        this._eventDispatcher.emitSingleViewEvent(new ViewCompositionStartEvent());
    }
    onCompositionEnd() {
        this._eventDispatcher.emitSingleViewEvent(new ViewCompositionEndEvent());
    }
    _onConfigurationChanged(eventsCollector, e) {
        // We might need to restore the current centered view range, so save it (if available)
        let previousViewportStartModelPosition = null;
        if (this._viewportStart.isValid) {
            const previousViewportStartViewPosition = new Position(this._viewportStart.viewLineNumber, this.getLineMinColumn(this._viewportStart.viewLineNumber));
            previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition);
        }
        let restorePreviousViewportStart = false;
        const options = this._configuration.options;
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        const wrappingStrategy = options.get(127 /* EditorOption.wrappingStrategy */);
        const wrappingInfo = options.get(134 /* EditorOption.wrappingInfo */);
        const wrappingIndent = options.get(126 /* EditorOption.wrappingIndent */);
        if (this._lines.setWrappingSettings(fontInfo, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent)) {
            eventsCollector.emitViewEvent(new ViewFlushedEvent());
            eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
            eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
            this._cursor.onLineMappingChanged(eventsCollector);
            this._decorations.onLineMappingChanged();
            this.viewLayout.onFlushed(this.getLineCount());
            if (this.viewLayout.getCurrentScrollTop() !== 0) {
                // Never change the scroll position from 0 to something else...
                restorePreviousViewportStart = true;
            }
            this._updateConfigurationViewLineCount.schedule();
        }
        if (e.hasChanged(83 /* EditorOption.readOnly */)) {
            // Must read again all decorations due to readOnly filtering
            this._decorations.reset();
            eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
        }
        eventsCollector.emitViewEvent(new ViewConfigurationChangedEvent(e));
        this.viewLayout.onConfigurationChanged(e);
        if (restorePreviousViewportStart && previousViewportStartModelPosition) {
            const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(previousViewportStartModelPosition);
            const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
            this.viewLayout.setScrollPosition({ scrollTop: viewPositionTop + this._viewportStart.startLineDelta }, 1 /* ScrollType.Immediate */);
        }
        if (CursorConfiguration.shouldRecreate(e)) {
            this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
            this._cursor.updateConfiguration(this.cursorConfig);
        }
    }
    _registerModelEvents() {
        this._register(this.model.onDidChangeContentOrInjectedText((e) => {
            try {
                const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
                let hadOtherModelChange = false;
                let hadModelLineChangeThatChangedLineMapping = false;
                const changes = (e instanceof InternalModelContentChangeEvent ? e.rawContentChangedEvent.changes : e.changes);
                const versionId = (e instanceof InternalModelContentChangeEvent ? e.rawContentChangedEvent.versionId : null);
                // Do a first pass to compute line mappings, and a second pass to actually interpret them
                const lineBreaksComputer = this._lines.createLineBreaksComputer();
                for (const change of changes) {
                    switch (change.changeType) {
                        case 4 /* textModelEvents.RawContentChangedType.LinesInserted */: {
                            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._editorId));
                                }
                                lineBreaksComputer.addRequest(line, injectedText, null);
                            }
                            break;
                        }
                        case 2 /* textModelEvents.RawContentChangedType.LineChanged */: {
                            let injectedText = null;
                            if (change.injectedText) {
                                injectedText = change.injectedText.filter(element => (!element.ownerId || element.ownerId === this._editorId));
                            }
                            lineBreaksComputer.addRequest(change.detail, injectedText, null);
                            break;
                        }
                    }
                }
                const lineBreaks = lineBreaksComputer.finalize();
                const lineBreakQueue = new ArrayQueue(lineBreaks);
                for (const change of changes) {
                    switch (change.changeType) {
                        case 1 /* textModelEvents.RawContentChangedType.Flush */: {
                            this._lines.onModelFlushed();
                            eventsCollector.emitViewEvent(new ViewFlushedEvent());
                            this._decorations.reset();
                            this.viewLayout.onFlushed(this.getLineCount());
                            hadOtherModelChange = true;
                            break;
                        }
                        case 3 /* textModelEvents.RawContentChangedType.LinesDeleted */: {
                            const linesDeletedEvent = this._lines.onModelLinesDeleted(versionId, change.fromLineNumber, change.toLineNumber);
                            if (linesDeletedEvent !== null) {
                                eventsCollector.emitViewEvent(linesDeletedEvent);
                                this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
                            }
                            hadOtherModelChange = true;
                            break;
                        }
                        case 4 /* textModelEvents.RawContentChangedType.LinesInserted */: {
                            const insertedLineBreaks = lineBreakQueue.takeCount(change.detail.length);
                            const linesInsertedEvent = this._lines.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 /* textModelEvents.RawContentChangedType.LineChanged */: {
                            const changedLineBreakData = lineBreakQueue.dequeue();
                            const [lineMappingChanged, linesChangedEvent, linesInsertedEvent, linesDeletedEvent] = this._lines.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 /* textModelEvents.RawContentChangedType.EOLChanged */: {
                            // Nothing to do. The new version will be accepted below
                            break;
                        }
                    }
                }
                if (versionId !== null) {
                    this._lines.acceptVersionId(versionId);
                }
                this.viewLayout.onHeightMaybeChanged();
                if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) {
                    eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
                    eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
                    this._cursor.onLineMappingChanged(eventsCollector);
                    this._decorations.onLineMappingChanged();
                }
            }
            finally {
                this._eventDispatcher.endEmitViewEvents();
            }
            // Update the configuration and reset the centered view line
            const viewportStartWasValid = this._viewportStart.isValid;
            this._viewportStart.invalidate();
            this._configuration.setModelLineCount(this.model.getLineCount());
            this._updateConfigurationViewLineCountNow();
            // Recover viewport
            if (!this._hasFocus && this.model.getAttachedEditorCount() >= 2 && viewportStartWasValid) {
                const modelRange = this.model._getTrackedRange(this._viewportStart.modelTrackedRange);
                if (modelRange) {
                    const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition());
                    const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
                    this.viewLayout.setScrollPosition({ scrollTop: viewPositionTop + this._viewportStart.startLineDelta }, 1 /* ScrollType.Immediate */);
                }
            }
            try {
                const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
                if (e instanceof InternalModelContentChangeEvent) {
                    eventsCollector.emitOutgoingEvent(new ModelContentChangedEvent(e.contentChangedEvent));
                }
                this._cursor.onModelContentChanged(eventsCollector, e);
            }
            finally {
                this._eventDispatcher.endEmitViewEvents();
            }
            this._tokenizeViewportSoon.schedule();
        }));
        this._register(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 Position(modelRange.fromLineNumber, 1)).lineNumber;
                const viewEndLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.toLineNumber, this.model.getLineMaxColumn(modelRange.toLineNumber))).lineNumber;
                viewRanges[j] = {
                    fromLineNumber: viewStartLineNumber,
                    toLineNumber: viewEndLineNumber
                };
            }
            this._eventDispatcher.emitSingleViewEvent(new ViewTokensChangedEvent(viewRanges));
            if (e.tokenizationSupportChanged) {
                this._tokenizeViewportSoon.schedule();
            }
            this._eventDispatcher.emitOutgoingEvent(new ModelTokensChangedEvent(e));
        }));
        this._register(this.model.onDidChangeLanguageConfiguration((e) => {
            this._eventDispatcher.emitSingleViewEvent(new ViewLanguageConfigurationEvent());
            this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
            this._cursor.updateConfiguration(this.cursorConfig);
            this._eventDispatcher.emitOutgoingEvent(new ModelLanguageConfigurationChangedEvent(e));
        }));
        this._register(this.model.onDidChangeLanguage((e) => {
            this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
            this._cursor.updateConfiguration(this.cursorConfig);
            this._eventDispatcher.emitOutgoingEvent(new ModelLanguageChangedEvent(e));
        }));
        this._register(this.model.onDidChangeOptions((e) => {
            // A tab size change causes a line mapping changed event => all view parts will repaint OK, no further event needed here
            if (this._lines.setTabSize(this.model.getOptions().tabSize)) {
                try {
                    const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
                    eventsCollector.emitViewEvent(new ViewFlushedEvent());
                    eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
                    eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
                    this._cursor.onLineMappingChanged(eventsCollector);
                    this._decorations.onLineMappingChanged();
                    this.viewLayout.onFlushed(this.getLineCount());
                }
                finally {
                    this._eventDispatcher.endEmitViewEvents();
                }
                this._updateConfigurationViewLineCount.schedule();
            }
            this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
            this._cursor.updateConfiguration(this.cursorConfig);
            this._eventDispatcher.emitOutgoingEvent(new ModelOptionsChangedEvent(e));
        }));
        this._register(this.model.onDidChangeDecorations((e) => {
            this._decorations.onModelDecorationsChanged();
            this._eventDispatcher.emitSingleViewEvent(new ViewDecorationsChangedEvent(e));
            this._eventDispatcher.emitOutgoingEvent(new ModelDecorationsChangedEvent(e));
        }));
    }
    setHiddenAreas(ranges) {
        let lineMappingChanged = false;
        try {
            const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
            lineMappingChanged = this._lines.setHiddenAreas(ranges);
            if (lineMappingChanged) {
                eventsCollector.emitViewEvent(new ViewFlushedEvent());
                eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
                eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
                this._cursor.onLineMappingChanged(eventsCollector);
                this._decorations.onLineMappingChanged();
                this.viewLayout.onFlushed(this.getLineCount());
                this.viewLayout.onHeightMaybeChanged();
            }
        }
        finally {
            this._eventDispatcher.endEmitViewEvents();
        }
        this._updateConfigurationViewLineCount.schedule();
        if (lineMappingChanged) {
            this._eventDispatcher.emitOutgoingEvent(new HiddenAreasChangedEvent());
        }
    }
    getVisibleRangesPlusViewportAboveBelow() {
        const layoutInfo = this._configuration.options.get(133 /* EditorOption.layoutInfo */);
        const lineHeight = this._configuration.options.get(61 /* 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._toModelVisibleRanges(new Range(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber)));
    }
    getVisibleRanges() {
        const visibleViewRange = this.getCompletelyVisibleViewRange();
        return this._toModelVisibleRanges(visibleViewRange);
    }
    getHiddenAreas() {
        return this._lines.getHiddenAreas();
    }
    _toModelVisibleRanges(visibleViewRange) {
        const visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
        const hiddenAreas = this._lines.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 i = 0, len = hiddenAreas.length; i < len; i++) {
            const hiddenStartLineNumber = hiddenAreas[i].startLineNumber;
            const hiddenEndLineNumber = hiddenAreas[i].endLineNumber;
            if (hiddenEndLineNumber < startLineNumber) {
                continue;
            }
            if (hiddenStartLineNumber > endLineNumber) {
                continue;
            }
            if (startLineNumber < hiddenStartLineNumber) {
                result[resultLen++] = new Range(startLineNumber, startColumn, hiddenStartLineNumber - 1, this.model.getLineMaxColumn(hiddenStartLineNumber - 1));
            }
            startLineNumber = hiddenEndLineNumber + 1;
            startColumn = 1;
        }
        if (startLineNumber < endLineNumber || (startLineNumber === endLineNumber && startColumn < endColumn)) {
            result[resultLen++] = new Range(startLineNumber, startColumn, endLineNumber, endColumn);
        }
        return result;
    }
    getCompletelyVisibleViewRange() {
        const partialData = this.viewLayout.getLinesViewportData();
        const startViewLineNumber = partialData.completelyVisibleStartLineNumber;
        const endViewLineNumber = partialData.completelyVisibleEndLineNumber;
        return new Range(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 Range(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 Position(firstViewLineNumber, this.getLineMinColumn(firstViewLineNumber)));
        const firstPositionDeltaTop = this.viewLayout.getVerticalOffsetForLineNumber(firstViewLineNumber) - scrollTop;
        return {
            scrollLeft: compatViewState.scrollLeft,
            firstPosition: firstPosition,
            firstPositionDeltaTop: firstPositionDeltaTop
        };
    }
    reduceRestoreState(state) {
        if (typeof state.firstPosition === 'undefined') {
            // This is a view state serialized by an older version
            return this._reduceRestoreStateCompatibility(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: scrollTop
        };
    }
    _reduceRestoreStateCompatibility(state) {
        return {
            scrollLeft: state.scrollLeft,
            scrollTop: state.scrollTopWithoutViewZones
        };
    }
    getTabSize() {
        return this.model.getOptions().tabSize;
    }
    getLineCount() {
        return this._lines.getViewLineCount();
    }
    /**
     * Gives a hint that a lot of requests are about to come in for these line numbers.
     */
    setViewport(startLineNumber, endLineNumber, centeredLineNumber) {
        this._viewportStart.update(this, startLineNumber);
    }
    getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
        return this._lines.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber);
    }
    getLinesIndentGuides(startLineNumber, endLineNumber) {
        return this._lines.getViewLinesIndentGuides(startLineNumber, endLineNumber);
    }
    getBracketGuidesInRangeByLine(startLineNumber, endLineNumber, activePosition, options) {
        return this._lines.getViewLinesBracketGuides(startLineNumber, endLineNumber, activePosition, options);
    }
    getLineContent(lineNumber) {
        return this._lines.getViewLineContent(lineNumber);
    }
    getLineLength(lineNumber) {
        return this._lines.getViewLineLength(lineNumber);
    }
    getLineMinColumn(lineNumber) {
        return this._lines.getViewLineMinColumn(lineNumber);
    }
    getLineMaxColumn(lineNumber) {
        return this._lines.getViewLineMaxColumn(lineNumber);
    }
    getLineFirstNonWhitespaceColumn(lineNumber) {
        const result = strings_firstNonWhitespaceIndex(this.getLineContent(lineNumber));
        if (result === -1) {
            return 0;
        }
        return result + 1;
    }
    getLineLastNonWhitespaceColumn(lineNumber) {
        const result = strings_lastNonWhitespaceIndex(this.getLineContent(lineNumber));
        if (result === -1) {
            return 0;
        }
        return result + 2;
    }
    getDecorationsInViewport(visibleRange) {
        return this._decorations.getDecorationsViewportData(visibleRange).decorations;
    }
    getInjectedTextAt(viewPosition) {
        return this._lines.getInjectedTextAt(viewPosition);
    }
    getViewportViewLineRenderingData(visibleRange, lineNumber) {
        const allInlineDecorations = this._decorations.getDecorationsViewportData(visibleRange).inlineDecorations;
        const inlineDecorations = allInlineDecorations[lineNumber - visibleRange.startLineNumber];
        return this._getViewLineRenderingData(lineNumber, inlineDecorations);
    }
    getViewLineRenderingData(lineNumber) {
        const inlineDecorations = this._decorations.getInlineDecorationsOnLine(lineNumber);
        return this._getViewLineRenderingData(lineNumber, inlineDecorations);
    }
    _getViewLineRenderingData(lineNumber, inlineDecorations) {
        const mightContainRTL = this.model.mightContainRTL();
        const mightContainNonBasicASCII = this.model.mightContainNonBasicASCII();
        const tabSize = this.getTabSize();
        const lineData = this._lines.getViewLineData(lineNumber);
        if (lineData.inlineDecorations) {
            inlineDecorations = [
                ...inlineDecorations,
                ...lineData.inlineDecorations.map(d => d.toInlineDecoration(lineNumber))
            ];
        }
        return new ViewLineRenderingData(lineData.minColumn, lineData.maxColumn, lineData.content, lineData.continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize, lineData.startVisibleColumn);
    }
    getViewLineData(lineNumber) {
        return this._lines.getViewLineData(lineNumber);
    }
    getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
        const result = this._lines.getViewLinesData(startLineNumber, endLineNumber, needed);
        return new MinimapLinesRenderingData(this.getTabSize(), result);
    }
    getAllOverviewRulerDecorations(theme) {
        const decorations = this.model.getOverviewRulerDecorations(this._editorId, filterValidationDecorations(this._configuration.options));
        const result = new OverviewRulerDecorations();
        for (const decoration of decorations) {
            const decorationOptions = decoration.options;
            const opts = decorationOptions.overviewRuler;
            if (!opts) {
                continue;
            }
            const lane = opts.position;
            if (lane === 0) {
                continue;
            }
            const color = opts.getColor(theme.value);
            const viewStartLineNumber = this.coordinatesConverter.getViewLineNumberOfModelPosition(decoration.range.startLineNumber, decoration.range.startColumn);
            const viewEndLineNumber = this.coordinatesConverter.getViewLineNumberOfModelPosition(decoration.range.endLineNumber, decoration.range.endColumn);
            result.accept(color, decorationOptions.zIndex, viewStartLineNumber, viewEndLineNumber, lane);
        }
        return result.asArray;
    }
    _invalidateDecorationsColorCache() {
        const decorations = this.model.getOverviewRulerDecorations();
        for (const decoration of decorations) {
            const opts1 = decoration.options.overviewRuler;
            if (opts1) {
                opts1.invalidateCachedColor();
            }
            const opts2 = decoration.options.minimap;
            if (opts2) {
                opts2.invalidateCachedColor();
            }
        }
    }
    getValueInRange(range, eol) {
        const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range);
        return this.model.getValueInRange(modelRange, eol);
    }
    deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt) {
        const modelAnchor = this.coordinatesConverter.convertViewPositionToModelPosition(viewAnchorPosition);
        if (this.model.getEOL().length === 2) {
            // This model uses CRLF, so the delta must take that into account
            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(Range.compareRangesUsingStarts);
        let hasEmptyRange = false;
        let hasNonEmptyRange = false;
        for (const range of modelRanges) {
            if (range.isEmpty()) {
                hasEmptyRange = true;
            }
            else {
                hasNonEmptyRange = true;
            }
        }
        if (!hasNonEmptyRange) {
            // all ranges are empty
            if (!emptySelectionClipboard) {
                return '';
            }
            const modelLineNumbers = modelRanges.map((r) => r.startLineNumber);
            let result = '';
            for (let i = 0; i < modelLineNumbers.length; i++) {
                if (i > 0 && modelLineNumbers[i - 1] === modelLineNumbers[i]) {
                    continue;
                }
                result += this.model.getLineContent(modelLineNumbers[i]) + newLineCharacter;
            }
            return result;
        }
        if (hasEmptyRange && emptySelectionClipboard) {
            // mixed empty selections and non-empty selections
            const result = [];
            let prevModelLineNumber = 0;
            for (const modelRange of modelRanges) {
                const modelLineNumber = modelRange.startLineNumber;
                if (modelRange.isEmpty()) {
                    if (modelLineNumber !== prevModelLineNumber) {
                        result.push(this.model.getLineContent(modelLineNumber));
                    }
                }
                else {
                    result.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 /* EndOfLinePreference.CRLF */ : 0 /* EndOfLinePreference.TextDefined */));
                }
                prevModelLineNumber = modelLineNumber;
            }
            return result.length === 1 ? result[0] : result;
        }
        const result = [];
        for (const modelRange of modelRanges) {
            if (!modelRange.isEmpty()) {
                result.push(this.model.getValueInRange(modelRange, forceCRLF ? 2 /* EndOfLinePreference.CRLF */ : 0 /* EndOfLinePreference.TextDefined */));
            }
        }
        return result.length === 1 ? result[0] : result;
    }
    getRichTextToCopy(modelRanges, emptySelectionClipboard) {
        const languageId = this.model.getLanguageId();
        if (languageId === PLAINTEXT_LANGUAGE_ID) {
            return null;
        }
        if (modelRanges.length !== 1) {
            // no multiple selection support at this time
            return null;
        }
        let range = modelRanges[0];
        if (range.isEmpty()) {
            if (!emptySelectionClipboard) {
                // nothing to copy
                return null;
            }
            const lineNumber = range.startLineNumber;
            range = new Range(lineNumber, this.model.getLineMinColumn(lineNumber), lineNumber, this.model.getLineMaxColumn(lineNumber));
        }
        const fontInfo = this._configuration.options.get(46 /* EditorOption.fontInfo */);
        const colorMap = this._getColorMap();
        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._getHTMLToCopy(range, colorMap)
                + '</div>')
        };
    }
    _getHTMLToCopy(modelRange, colorMap) {
        const startLineNumber = modelRange.startLineNumber;
        const startColumn = modelRange.startColumn;
        const endLineNumber = modelRange.endLineNumber;
        const endColumn = modelRange.endColumn;
        const tabSize = this.getTabSize();
        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 += tokenizeLineToHTML(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, isWindows);
            }
        }
        return result;
    }
    _getColorMap() {
        const colorMap = languages_TokenizationRegistry.getColorMap();
        const result = ['#000000'];
        if (colorMap) {
            for (let i = 1, len = colorMap.length; i < len; i++) {
                result[i] = Color.Format.CSS.formatHex(colorMap[i]);
            }
        }
        return result;
    }
    //#region cursor operations
    getPrimaryCursorState() {
        return this._cursor.getPrimaryCursorState();
    }
    getLastAddedCursorIndex() {
        return this._cursor.getLastAddedCursorIndex();
    }
    getCursorStates() {
        return this._cursor.getCursorStates();
    }
    setCursorStates(source, reason, states) {
        return this._withViewEventsCollector(eventsCollector => this._cursor.setStates(eventsCollector, source, reason, states));
    }
    getCursorColumnSelectData() {
        return this._cursor.getCursorColumnSelectData();
    }
    getCursorAutoClosedCharacters() {
        return this._cursor.getAutoClosedCharacters();
    }
    setCursorColumnSelectData(columnSelectData) {
        this._cursor.setCursorColumnSelectData(columnSelectData);
    }
    getPrevEditOperationType() {
        return this._cursor.getPrevEditOperationType();
    }
    setPrevEditOperationType(type) {
        this._cursor.setPrevEditOperationType(type);
    }
    getSelection() {
        return this._cursor.getSelection();
    }
    getSelections() {
        return this._cursor.getSelections();
    }
    getPosition() {
        return this._cursor.getPrimaryCursorState().modelState.position;
    }
    setSelections(source, selections, reason = 0 /* CursorChangeReason.NotSet */) {
        this._withViewEventsCollector(eventsCollector => this._cursor.setSelections(eventsCollector, source, selections, reason));
    }
    saveCursorState() {
        return this._cursor.saveState();
    }
    restoreCursorState(states) {
        this._withViewEventsCollector(eventsCollector => this._cursor.restoreState(eventsCollector, states));
    }
    _executeCursorEdit(callback) {
        if (this._cursor.context.cursorConfig.readOnly) {
            // we cannot edit when read only...
            this._eventDispatcher.emitOutgoingEvent(new ReadOnlyEditAttemptEvent());
            return;
        }
        this._withViewEventsCollector(callback);
    }
    executeEdits(source, edits, cursorStateComputer) {
        this._executeCursorEdit(eventsCollector => this._cursor.executeEdits(eventsCollector, source, edits, cursorStateComputer));
    }
    startComposition() {
        this._executeCursorEdit(eventsCollector => this._cursor.startComposition(eventsCollector));
    }
    endComposition(source) {
        this._executeCursorEdit(eventsCollector => this._cursor.endComposition(eventsCollector, source));
    }
    type(text, source) {
        this._executeCursorEdit(eventsCollector => this._cursor.type(eventsCollector, text, source));
    }
    compositionType(text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) {
        this._executeCursorEdit(eventsCollector => this._cursor.compositionType(eventsCollector, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source));
    }
    paste(text, pasteOnNewLine, multicursorText, source) {
        this._executeCursorEdit(eventsCollector => this._cursor.paste(eventsCollector, text, pasteOnNewLine, multicursorText, source));
    }
    cut(source) {
        this._executeCursorEdit(eventsCollector => this._cursor.cut(eventsCollector, source));
    }
    executeCommand(command, source) {
        this._executeCursorEdit(eventsCollector => this._cursor.executeCommand(eventsCollector, command, source));
    }
    executeCommands(commands, source) {
        this._executeCursorEdit(eventsCollector => this._cursor.executeCommands(eventsCollector, commands, source));
    }
    revealPrimaryCursor(source, revealHorizontal, minimalReveal = false) {
        this._withViewEventsCollector(eventsCollector => this._cursor.revealPrimary(eventsCollector, source, minimalReveal, 0 /* viewEvents.VerticalRevealType.Simple */, revealHorizontal, 0 /* ScrollType.Smooth */));
    }
    revealTopMostCursor(source) {
        const viewPosition = this._cursor.getTopMostViewPosition();
        const viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
        this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source, false, viewRange, null, 0 /* viewEvents.VerticalRevealType.Simple */, true, 0 /* ScrollType.Smooth */)));
    }
    revealBottomMostCursor(source) {
        const viewPosition = this._cursor.getBottomMostViewPosition();
        const viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
        this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source, false, viewRange, null, 0 /* viewEvents.VerticalRevealType.Simple */, true, 0 /* ScrollType.Smooth */)));
    }
    revealRange(source, revealHorizontal, viewRange, verticalType, scrollType) {
        this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source, false, viewRange, null, verticalType, revealHorizontal, scrollType)));
    }
    //#endregion
    //#region viewLayout
    changeWhitespace(callback) {
        const hadAChange = this.viewLayout.changeWhitespace(callback);
        if (hadAChange) {
            this._eventDispatcher.emitSingleViewEvent(new ViewZonesChangedEvent());
            this._eventDispatcher.emitOutgoingEvent(new viewModelEventDispatcher_ViewZonesChangedEvent());
        }
    }
    //#endregion
    _withViewEventsCollector(callback) {
        try {
            const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
            return callback(eventsCollector);
        }
        finally {
            this._eventDispatcher.endEmitViewEvents();
        }
    }
    normalizePosition(position, affinity) {
        return this._lines.normalizePosition(position, affinity);
    }
    /**
     * Gets the column at which indentation stops at a given line.
     * @internal
    */
    getLineIndentColumn(lineNumber) {
        return this._lines.getLineIndentColumn(lineNumber);
    }
}
class ViewportStart {
    constructor(_model, _viewLineNumber, _isValid, _modelTrackedRange, _startLineDelta) {
        this._model = _model;
        this._viewLineNumber = _viewLineNumber;
        this._isValid = _isValid;
        this._modelTrackedRange = _modelTrackedRange;
        this._startLineDelta = _startLineDelta;
    }
    static create(model) {
        const viewportStartLineTrackedRange = model._setTrackedRange(null, new Range(1, 1, 1, 1), 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */);
        return new ViewportStart(model, 1, false, viewportStartLineTrackedRange, 0);
    }
    get viewLineNumber() {
        return this._viewLineNumber;
    }
    get isValid() {
        return this._isValid;
    }
    get modelTrackedRange() {
        return this._modelTrackedRange;
    }
    get startLineDelta() {
        return this._startLineDelta;
    }
    dispose() {
        this._model._setTrackedRange(this._modelTrackedRange, null, 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */);
    }
    update(viewModel, startLineNumber) {
        const position = viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position(startLineNumber, viewModel.getLineMinColumn(startLineNumber)));
        const viewportStartLineTrackedRange = viewModel.model._setTrackedRange(this._modelTrackedRange, new Range(position.lineNumber, position.column, position.lineNumber, position.column), 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */);
        const viewportStartLineTop = viewModel.viewLayout.getVerticalOffsetForLineNumber(startLineNumber);
        const scrollTop = viewModel.viewLayout.getCurrentScrollTop();
        this._viewLineNumber = startLineNumber;
        this._isValid = true;
        this._modelTrackedRange = viewportStartLineTrackedRange;
        this._startLineDelta = scrollTop - viewportStartLineTop;
    }
    invalidate() {
        this._isValid = false;
    }
}
class OverviewRulerDecorations {
    constructor() {
        this._asMap = Object.create(null);
        this.asArray = [];
    }
    accept(color, zIndex, startLineNumber, endLineNumber, lane) {
        const prevGroup = this._asMap[color];
        if (prevGroup) {
            const prevData = prevGroup.data;
            const prevLane = prevData[prevData.length - 3];
            const prevEndLineNumber = prevData[prevData.length - 1];
            if (prevLane === lane && prevEndLineNumber + 1 >= startLineNumber) {
                // merge into prev
                if (endLineNumber > prevEndLineNumber) {
                    prevData[prevData.length - 1] = endLineNumber;
                }
                return;
            }
            // push
            prevData.push(lane, startLineNumber, endLineNumber);
        }
        else {
            const group = new OverviewRulerDecorationsGroup(color, zIndex, [lane, startLineNumber, endLineNumber]);
            this._asMap[color] = group;
            this.asArray.push(group);
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/instantiation/common/serviceCollection.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class ServiceCollection {
    constructor(...entries) {
        this._entries = new Map();
        for (const [id, service] of entries) {
            this.set(id, service);
        }
    }
    set(id, instanceOrDescriptor) {
        const result = this._entries.get(id);
        this._entries.set(id, instanceOrDescriptor);
        return result;
    }
    get(id) {
        return this._entries.get(id);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/modelLineProjectionData.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



/**
 * *input*:
 * ```
 * xxxxxxxxxxxxxxxxxxxxxxxxxxx
 * ```
 *
 * -> Applying injections `[i...i]`, *inputWithInjections*:
 * ```
 * xxxxxx[iiiiiiiiii]xxxxxxxxxxxxxxxxx[ii]xxxx
 * ```
 *
 * -> breaking at offsets `|` in `xxxxxx[iiiiiii|iii]xxxxxxxxxxx|xxxxxx[ii]xxxx|`:
 * ```
 * xxxxxx[iiiiiii
 * iii]xxxxxxxxxxx
 * xxxxxx[ii]xxxx
 * ```
 *
 * -> applying wrappedTextIndentLength, *output*:
 * ```
 * xxxxxx[iiiiiii
 *    iii]xxxxxxxxxxx
 *    xxxxxx[ii]xxxx
 * ```
 */
class ModelLineProjectionData {
    constructor(injectionOffsets, 
    /**
     * `injectionOptions.length` must equal `injectionOffsets.length`
     */
    injectionOptions, 
    /**
     * Refers to offsets after applying injections to the source.
     * The last break offset indicates the length of the source after applying injections.
     */
    breakOffsets, 
    /**
     * Refers to offsets after applying injections
     */
    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) {
        // These offsets refer to model text with injected text.
        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 i = 0; i < this.injectionOffsets.length; i++) {
                if (offsetInInput > this.injectionOffsets[i]) {
                    if (offsetInInput < this.injectionOffsets[i] + this.injectionOptions[i].content.length) {
                        // `inputOffset` is within injected text
                        offsetInInput = this.injectionOffsets[i];
                    }
                    else {
                        offsetInInput -= this.injectionOptions[i].content.length;
                    }
                }
                else {
                    break;
                }
            }
        }
        return offsetInInput;
    }
    translateToOutputPosition(inputOffset, affinity = 2 /* PositionAffinity.None */) {
        let inputOffsetInInputWithInjection = inputOffset;
        if (this.injectionOffsets !== null) {
            for (let i = 0; i < this.injectionOffsets.length; i++) {
                if (inputOffset < this.injectionOffsets[i]) {
                    break;
                }
                if (affinity !== 1 /* PositionAffinity.Right */ && inputOffset === this.injectionOffsets[i]) {
                    break;
                }
                inputOffsetInInputWithInjection += this.injectionOptions[i].content.length;
            }
        }
        return this.offsetInInputWithInjectionsToOutputPosition(inputOffsetInInputWithInjection, affinity);
    }
    offsetInInputWithInjectionsToOutputPosition(offsetInInputWithInjections, affinity = 2 /* PositionAffinity.None */) {
        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 /* PositionAffinity.Left */) {
                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 OutputPosition(mid, outputOffset);
    }
    normalizeOutputPosition(outputLineIndex, outputOffset, affinity) {
        if (this.injectionOffsets !== null) {
            const offsetInInputWithInjections = this.outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset);
            const normalizedOffsetInUnwrappedLine = this.normalizeOffsetInInputWithInjectionsAroundInjections(offsetInInputWithInjections, affinity);
            if (normalizedOffsetInUnwrappedLine !== offsetInInputWithInjections) {
                // injected text caused a change
                return this.offsetInInputWithInjectionsToOutputPosition(normalizedOffsetInUnwrappedLine, affinity);
            }
        }
        if (affinity === 0 /* PositionAffinity.Left */) {
            if (outputLineIndex > 0 && outputOffset === this.getMinOutputOffset(outputLineIndex)) {
                return new OutputPosition(outputLineIndex - 1, this.getMaxOutputOffset(outputLineIndex - 1));
            }
        }
        else if (affinity === 1 /* PositionAffinity.Right */) {
            const maxOutputLineIndex = this.getOutputLineCount() - 1;
            if (outputLineIndex < maxOutputLineIndex && outputOffset === this.getMaxOutputOffset(outputLineIndex)) {
                return new OutputPosition(outputLineIndex + 1, this.getMinOutputOffset(outputLineIndex + 1));
            }
        }
        return new OutputPosition(outputLineIndex, outputOffset);
    }
    outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset) {
        if (outputLineIndex > 0) {
            outputOffset = Math.max(0, outputOffset - this.wrappedTextIndentLength);
        }
        const result = (outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0) + outputOffset;
        return result;
    }
    normalizeOffsetInInputWithInjectionsAroundInjections(offsetInInputWithInjections, affinity) {
        const injectedText = this.getInjectedTextAtOffset(offsetInInputWithInjections);
        if (!injectedText) {
            return offsetInInputWithInjections;
        }
        if (affinity === 2 /* PositionAffinity.None */) {
            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 /* PositionAffinity.Right */ || affinity === 4 /* PositionAffinity.RightOfInjectedText */) {
            let result = injectedText.offsetInInputWithInjections + injectedText.length;
            let index = injectedText.injectedTextIndex;
            // traverse all injected text that touch each other
            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 /* PositionAffinity.Left */ || affinity === 3 /* PositionAffinity.LeftOfInjectedText */) {
            // affinity is left
            let result = injectedText.offsetInInputWithInjections;
            let index = injectedText.injectedTextIndex;
            // traverse all injected text that touch each other
            while (index - 1 >= 0 && this.injectionOffsets[index - 1] === this.injectionOffsets[index]) {
                result -= this.injectionOptions[index - 1].content.length;
                index--;
            }
            return result;
        }
        assertNever(affinity);
    }
    getInjectedText(outputLineIndex, outputOffset) {
        const offset = this.outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset);
        const injectedText = this.getInjectedTextAtOffset(offset);
        if (!injectedText) {
            return null;
        }
        return {
            options: this.injectionOptions[injectedText.injectedTextIndex]
        };
    }
    getInjectedTextAtOffset(offsetInInputWithInjections) {
        const injectionOffsets = this.injectionOffsets;
        const injectionOptions = this.injectionOptions;
        if (injectionOffsets !== null) {
            let totalInjectedTextLengthBefore = 0;
            for (let i = 0; i < injectionOffsets.length; i++) {
                const length = injectionOptions[i].content.length;
                const injectedTextStartOffsetInInputWithInjections = injectionOffsets[i] + totalInjectedTextLengthBefore;
                const injectedTextEndOffsetInInputWithInjections = injectionOffsets[i] + totalInjectedTextLengthBefore + length;
                if (injectedTextStartOffsetInInputWithInjections > offsetInInputWithInjections) {
                    // Injected text starts later.
                    break; // All later injected texts have an even larger offset.
                }
                if (offsetInInputWithInjections <= injectedTextEndOffsetInInputWithInjections) {
                    // Injected text ends after or with the given position (but also starts with or before it).
                    return {
                        injectedTextIndex: i,
                        offsetInInputWithInjections: injectedTextStartOffsetInInputWithInjections,
                        length
                    };
                }
                totalInjectedTextLengthBefore += length;
            }
        }
        return undefined;
    }
}
function hasRightCursorStop(cursorStop) {
    if (cursorStop === null || cursorStop === undefined) {
        return true;
    }
    return cursorStop === InjectedTextCursorStops.Right || cursorStop === InjectedTextCursorStops.Both;
}
function hasLeftCursorStop(cursorStop) {
    if (cursorStop === null || cursorStop === undefined) {
        return true;
    }
    return cursorStop === InjectedTextCursorStops.Left || cursorStop === InjectedTextCursorStops.Both;
}
class InjectedText {
    constructor(options) {
        this.options = options;
    }
}
class OutputPosition {
    constructor(outputLineIndex, outputOffset) {
        this.outputLineIndex = outputLineIndex;
        this.outputOffset = outputOffset;
    }
    toString() {
        return `${this.outputLineIndex}:${this.outputOffset}`;
    }
    toPosition(baseLineNumber) {
        return new Position(baseLineNumber + this.outputLineIndex, this.outputOffset + 1);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/viewModel/monospaceLineBreaksComputer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class MonospaceLineBreaksComputerFactory {
    constructor(breakBeforeChars, breakAfterChars) {
        this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars);
    }
    static create(options) {
        return new MonospaceLineBreaksComputerFactory(options.get(122 /* EditorOption.wordWrapBreakBeforeCharacters */), options.get(121 /* EditorOption.wordWrapBreakAfterCharacters */));
    }
    createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent) {
        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 i = 0, len = requests.length; i < len; i++) {
                    const injectedText = injectedTexts[i];
                    const previousLineBreakData = previousBreakingData[i];
                    if (previousLineBreakData && !previousLineBreakData.injectionOptions && !injectedText) {
                        result[i] = createLineBreaksFromPreviousLineBreaks(this.classifier, previousLineBreakData, requests[i], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent);
                    }
                    else {
                        result[i] = createLineBreaks(this.classifier, requests[i], injectedText, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent);
                    }
                }
                arrPool1.length = 0;
                arrPool2.length = 0;
                return result;
            }
        };
    }
}
class WrappingCharacterClassifier extends CharacterClassifier {
    constructor(BREAK_BEFORE, BREAK_AFTER) {
        super(0 /* CharacterClass.NONE */);
        for (let i = 0; i < BREAK_BEFORE.length; i++) {
            this.set(BREAK_BEFORE.charCodeAt(i), 1 /* CharacterClass.BREAK_BEFORE */);
        }
        for (let i = 0; i < BREAK_AFTER.length; i++) {
            this.set(BREAK_AFTER.charCodeAt(i), 2 /* CharacterClass.BREAK_AFTER */);
        }
    }
    get(charCode) {
        if (charCode >= 0 && charCode < 256) {
            return this._asciiMap[charCode];
        }
        else {
            // Initialize CharacterClass.BREAK_IDEOGRAPHIC for these Unicode ranges:
            // 1. CJK Unified Ideographs (0x4E00 -- 0x9FFF)
            // 2. CJK Unified Ideographs Extension A (0x3400 -- 0x4DBF)
            // 3. Hiragana and Katakana (0x3040 -- 0x30FF)
            if ((charCode >= 0x3040 && charCode <= 0x30FF)
                || (charCode >= 0x3400 && charCode <= 0x4DBF)
                || (charCode >= 0x4E00 && charCode <= 0x9FFF)) {
                return 3 /* CharacterClass.BREAK_IDEOGRAPHIC */;
            }
            return (this._map.get(charCode) || this._defaultValue);
        }
    }
}
let arrPool1 = [];
let arrPool2 = [];
function createLineBreaksFromPreviousLineBreaks(classifier, previousBreakingData, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
    if (firstLineBreakColumn === -1) {
        return null;
    }
    const len = lineText.length;
    if (len <= 1) {
        return null;
    }
    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) {
        // Allow for prevIndex to be -1 (for the case where we hit a tab when walking backwards from the first break)
        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;
        // initially, we search as much as possible to the right (if it fits)
        if (prevBreakOffsetVisibleColumn <= breakingColumn) {
            let visibleColumn = prevBreakOffsetVisibleColumn;
            let prevCharCode = prevBreakOffset === 0 ? 0 /* CharCode.Null */ : lineText.charCodeAt(prevBreakOffset - 1);
            let prevCharCodeClass = prevBreakOffset === 0 ? 0 /* CharacterClass.NONE */ : classifier.get(prevCharCode);
            let entireLineFits = true;
            for (let i = prevBreakOffset; i < len; i++) {
                const charStartOffset = i;
                const charCode = lineText.charCodeAt(i);
                let charCodeClass;
                let charWidth;
                if (isHighSurrogate(charCode)) {
                    // A surrogate pair must always be considered as a single unit, so it is never to be broken
                    i++;
                    charCodeClass = 0 /* CharacterClass.NONE */;
                    charWidth = 2;
                }
                else {
                    charCodeClass = classifier.get(charCode);
                    charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
                }
                if (charStartOffset > lastBreakingOffset && canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass)) {
                    breakOffset = charStartOffset;
                    breakOffsetVisibleColumn = visibleColumn;
                }
                visibleColumn += charWidth;
                // check if adding character at `i` will go over the breaking column
                if (visibleColumn > breakingColumn) {
                    // We need to break at least before character at `i`:
                    if (charStartOffset > lastBreakingOffset) {
                        forcedBreakOffset = charStartOffset;
                        forcedBreakOffsetVisibleColumn = visibleColumn - charWidth;
                    }
                    else {
                        // we need to advance at least by one character
                        forcedBreakOffset = i + 1;
                        forcedBreakOffsetVisibleColumn = visibleColumn;
                    }
                    if (visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
                        // Cannot break at `breakOffset` => reset it if it was set
                        breakOffset = 0;
                    }
                    entireLineFits = false;
                    break;
                }
                prevCharCode = charCode;
                prevCharCodeClass = charCodeClass;
            }
            if (entireLineFits) {
                // there is no more need to break => stop the outer loop!
                if (breakingOffsetsCount > 0) {
                    // Add last segment, no need to assign to `lastBreakingOffset` and `lastBreakingOffsetVisibleColumn`
                    breakingOffsets[breakingOffsetsCount] = prevBreakingOffsets[prevBreakingOffsets.length - 1];
                    breakingOffsetsVisibleColumn[breakingOffsetsCount] = prevBreakingOffsetsVisibleColumn[prevBreakingOffsets.length - 1];
                    breakingOffsetsCount++;
                }
                break;
            }
        }
        if (breakOffset === 0) {
            // must search left
            let visibleColumn = prevBreakOffsetVisibleColumn;
            let charCode = lineText.charCodeAt(prevBreakOffset);
            let charCodeClass = classifier.get(charCode);
            let hitATabCharacter = false;
            for (let i = prevBreakOffset - 1; i >= lastBreakingOffset; i--) {
                const charStartOffset = i + 1;
                const prevCharCode = lineText.charCodeAt(i);
                if (prevCharCode === 9 /* CharCode.Tab */) {
                    // cannot determine the width of a tab when going backwards, so we must go forwards
                    hitATabCharacter = true;
                    break;
                }
                let prevCharCodeClass;
                let prevCharWidth;
                if (isLowSurrogate(prevCharCode)) {
                    // A surrogate pair must always be considered as a single unit, so it is never to be broken
                    i--;
                    prevCharCodeClass = 0 /* CharacterClass.NONE */;
                    prevCharWidth = 2;
                }
                else {
                    prevCharCodeClass = classifier.get(prevCharCode);
                    prevCharWidth = (isFullWidthCharacter(prevCharCode) ? columnsForFullWidthChar : 1);
                }
                if (visibleColumn <= breakingColumn) {
                    if (forcedBreakOffset === 0) {
                        forcedBreakOffset = charStartOffset;
                        forcedBreakOffsetVisibleColumn = visibleColumn;
                    }
                    if (visibleColumn <= breakingColumn - wrappedLineBreakColumn) {
                        // went too far!
                        break;
                    }
                    if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass)) {
                        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 (isHighSurrogate(charCodeAtForcedBreakOffset)) {
                        // A surrogate pair must always be considered as a single unit, so it is never to be broken
                        charWidth = 2;
                    }
                    else {
                        charWidth = computeCharWidth(charCodeAtForcedBreakOffset, forcedBreakOffsetVisibleColumn, tabSize, columnsForFullWidthChar);
                    }
                    if (remainingWidthOfNextLine - charWidth < 0) {
                        // it is not worth it to break at breakOffset, it just introduces an extra needless line!
                        breakOffset = 0;
                    }
                }
            }
            if (hitATabCharacter) {
                // cannot determine the width of a tab when going backwards, so we must go forwards from the previous break
                prevIndex--;
                continue;
            }
        }
        if (breakOffset === 0) {
            // Could not find a good breaking point
            breakOffset = forcedBreakOffset;
            breakOffsetVisibleColumn = forcedBreakOffsetVisibleColumn;
        }
        if (breakOffset <= lastBreakingOffset) {
            // Make sure that we are advancing (at least one character)
            const charCode = lineText.charCodeAt(lastBreakingOffset);
            if (isHighSurrogate(charCode)) {
                // A surrogate pair must always be considered as a single unit, so it is never to be broken
                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;
    }
    // Doing here some object reuse which ends up helping a huge deal with GC pauses!
    breakingOffsets.length = breakingOffsetsCount;
    breakingOffsetsVisibleColumn.length = breakingOffsetsCount;
    arrPool1 = previousBreakingData.breakOffsets;
    arrPool2 = previousBreakingData.breakOffsetsVisibleColumn;
    previousBreakingData.breakOffsets = breakingOffsets;
    previousBreakingData.breakOffsetsVisibleColumn = breakingOffsetsVisibleColumn;
    previousBreakingData.wrappedTextIndentLength = wrappedTextIndentLength;
    return previousBreakingData;
}
function createLineBreaks(classifier, _lineText, injectedTexts, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
    const lineText = LineInjectedText.applyInjectedText(_lineText, injectedTexts);
    let injectionOptions;
    let injectionOffsets;
    if (injectedTexts && injectedTexts.length > 0) {
        injectionOptions = injectedTexts.map(t => t.options);
        injectionOffsets = injectedTexts.map(text => text.column - 1);
    }
    else {
        injectionOptions = null;
        injectionOffsets = null;
    }
    if (firstLineBreakColumn === -1) {
        if (!injectionOptions) {
            return null;
        }
        // creating a `LineBreakData` with an invalid `breakOffsetsVisibleColumn` is OK
        // because `breakOffsetsVisibleColumn` will never be used because it contains injected text
        return new ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
    }
    const len = lineText.length;
    if (len <= 1) {
        if (!injectionOptions) {
            return null;
        }
        // creating a `LineBreakData` with an invalid `breakOffsetsVisibleColumn` is OK
        // because `breakOffsetsVisibleColumn` will never be used because it contains injected text
        return new ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
    }
    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 (isHighSurrogate(prevCharCode)) {
        // A surrogate pair must always be considered as a single unit, so it is never to be broken
        visibleColumn += 1;
        prevCharCode = lineText.charCodeAt(1);
        prevCharCodeClass = classifier.get(prevCharCode);
        startOffset++;
    }
    for (let i = startOffset; i < len; i++) {
        const charStartOffset = i;
        const charCode = lineText.charCodeAt(i);
        let charCodeClass;
        let charWidth;
        if (isHighSurrogate(charCode)) {
            // A surrogate pair must always be considered as a single unit, so it is never to be broken
            i++;
            charCodeClass = 0 /* CharacterClass.NONE */;
            charWidth = 2;
        }
        else {
            charCodeClass = classifier.get(charCode);
            charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
        }
        if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass)) {
            breakOffset = charStartOffset;
            breakOffsetVisibleColumn = visibleColumn;
        }
        visibleColumn += charWidth;
        // check if adding character at `i` will go over the breaking column
        if (visibleColumn > breakingColumn) {
            // We need to break at least before character at `i`:
            if (breakOffset === 0 || visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
                // Cannot break at `breakOffset`, must break at `i`
                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;
    }
    // Add last segment
    breakingOffsets[breakingOffsetsCount] = len;
    breakingOffsetsVisibleColumn[breakingOffsetsCount] = visibleColumn;
    return new ModelLineProjectionData(injectionOffsets, injectionOptions, breakingOffsets, breakingOffsetsVisibleColumn, wrappedTextIndentLength);
}
function computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar) {
    if (charCode === 9 /* CharCode.Tab */) {
        return (tabSize - (visibleColumn % tabSize));
    }
    if (isFullWidthCharacter(charCode)) {
        return columnsForFullWidthChar;
    }
    if (charCode < 32) {
        // when using `editor.renderControlCharacters`, the substitutions are often wide
        return columnsForFullWidthChar;
    }
    return 1;
}
function tabCharacterWidth(visibleColumn, tabSize) {
    return (tabSize - (visibleColumn % tabSize));
}
/**
 * Kinsoku Shori : Don't break after a leading character, like an open bracket
 * Kinsoku Shori : Don't break before a trailing character, like a period
 */
function canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass) {
    return (charCode !== 32 /* CharCode.Space */
        && ((prevCharCodeClass === 2 /* CharacterClass.BREAK_AFTER */ && charCodeClass !== 2 /* CharacterClass.BREAK_AFTER */) // break at the end of multiple BREAK_AFTER
            || (prevCharCodeClass !== 1 /* CharacterClass.BREAK_BEFORE */ && charCodeClass === 1 /* CharacterClass.BREAK_BEFORE */) // break at the start of multiple BREAK_BEFORE
            || (prevCharCodeClass === 3 /* CharacterClass.BREAK_IDEOGRAPHIC */ && charCodeClass !== 2 /* CharacterClass.BREAK_AFTER */)
            || (charCodeClass === 3 /* CharacterClass.BREAK_IDEOGRAPHIC */ && prevCharCodeClass !== 1 /* CharacterClass.BREAK_BEFORE */)));
}
function computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
    let wrappedTextIndentLength = 0;
    if (wrappingIndent !== 0 /* WrappingIndent.None */) {
        const firstNonWhitespaceIndex = strings_firstNonWhitespaceIndex(lineText);
        if (firstNonWhitespaceIndex !== -1) {
            // Track existing indent
            for (let i = 0; i < firstNonWhitespaceIndex; i++) {
                const charWidth = (lineText.charCodeAt(i) === 9 /* CharCode.Tab */ ? tabCharacterWidth(wrappedTextIndentLength, tabSize) : 1);
                wrappedTextIndentLength += charWidth;
            }
            // Increase indent of continuation lines, if desired
            const numberOfAdditionalTabs = (wrappingIndent === 3 /* WrappingIndent.DeepIndent */ ? 2 : wrappingIndent === 2 /* WrappingIndent.Indent */ ? 1 : 0);
            for (let i = 0; i < numberOfAdditionalTabs; i++) {
                const charWidth = tabCharacterWidth(wrappedTextIndentLength, tabSize);
                wrappedTextIndentLength += charWidth;
            }
            // Force sticking to beginning of line if no character would fit except for the indentation
            if (wrappedTextIndentLength + columnsForFullWidthChar > firstLineBreakColumn) {
                wrappedTextIndentLength = 0;
            }
        }
    }
    return wrappedTextIndentLength;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/view/domLineBreaksComputer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var domLineBreaksComputer_a;





const ttPolicy = (domLineBreaksComputer_a = window.trustedTypes) === null || domLineBreaksComputer_a === void 0 ? void 0 : domLineBreaksComputer_a.createPolicy('domLineBreaksComputer', { createHTML: value => value });
class DOMLineBreaksComputerFactory {
    static create() {
        return new DOMLineBreaksComputerFactory();
    }
    constructor() {
    }
    createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent) {
        const requests = [];
        const injectedTexts = [];
        return {
            addRequest: (lineText, injectedText, previousLineBreakData) => {
                requests.push(lineText);
                injectedTexts.push(injectedText);
            },
            finalize: () => {
                return domLineBreaksComputer_createLineBreaks(requests, fontInfo, tabSize, wrappingColumn, wrappingIndent, injectedTexts);
            }
        };
    }
}
function domLineBreaksComputer_createLineBreaks(requests, fontInfo, tabSize, firstLineBreakColumn, wrappingIndent, injectedTextsPerLine) {
    var _a;
    function createEmptyLineBreakWithPossiblyInjectedText(requestIdx) {
        const injectedTexts = injectedTextsPerLine[requestIdx];
        if (injectedTexts) {
            const lineText = LineInjectedText.applyInjectedText(requests[requestIdx], injectedTexts);
            const injectionOptions = injectedTexts.map(t => t.options);
            const injectionOffsets = injectedTexts.map(text => text.column - 1);
            // creating a `LineBreakData` with an invalid `breakOffsetsVisibleColumn` is OK
            // because `breakOffsetsVisibleColumn` will never be used because it contains injected text
            return new ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
        }
        else {
            return null;
        }
    }
    if (firstLineBreakColumn === -1) {
        const result = [];
        for (let i = 0, len = requests.length; i < len; i++) {
            result[i] = createEmptyLineBreakWithPossiblyInjectedText(i);
        }
        return result;
    }
    const overallWidth = Math.round(firstLineBreakColumn * fontInfo.typicalHalfwidthCharacterWidth);
    const additionalIndent = (wrappingIndent === 3 /* WrappingIndent.DeepIndent */ ? 2 : wrappingIndent === 2 /* WrappingIndent.Indent */ ? 1 : 0);
    const additionalIndentSize = Math.round(tabSize * additionalIndent);
    const additionalIndentLength = Math.ceil(fontInfo.spaceWidth * additionalIndentSize);
    const containerDomNode = document.createElement('div');
    applyFontInfo(containerDomNode, fontInfo);
    const sb = createStringBuilder(10000);
    const firstNonWhitespaceIndices = [];
    const wrappedTextIndentLengths = [];
    const renderLineContents = [];
    const allCharOffsets = [];
    const allVisibleColumns = [];
    for (let i = 0; i < requests.length; i++) {
        const lineContent = LineInjectedText.applyInjectedText(requests[i], injectedTextsPerLine[i]);
        let firstNonWhitespaceIndex = 0;
        let wrappedTextIndentLength = 0;
        let width = overallWidth;
        if (wrappingIndent !== 0 /* WrappingIndent.None */) {
            firstNonWhitespaceIndex = strings_firstNonWhitespaceIndex(lineContent);
            if (firstNonWhitespaceIndex === -1) {
                // all whitespace line
                firstNonWhitespaceIndex = 0;
            }
            else {
                // Track existing indent
                for (let i = 0; i < firstNonWhitespaceIndex; i++) {
                    const charWidth = (lineContent.charCodeAt(i) === 9 /* CharCode.Tab */
                        ? (tabSize - (wrappedTextIndentLength % tabSize))
                        : 1);
                    wrappedTextIndentLength += charWidth;
                }
                const indentWidth = Math.ceil(fontInfo.spaceWidth * wrappedTextIndentLength);
                // Force sticking to beginning of line if no character would fit except for the indentation
                if (indentWidth + fontInfo.typicalFullwidthCharacterWidth > overallWidth) {
                    firstNonWhitespaceIndex = 0;
                    wrappedTextIndentLength = 0;
                }
                else {
                    width = overallWidth - indentWidth;
                }
            }
        }
        const renderLineContent = lineContent.substr(firstNonWhitespaceIndex);
        const tmp = renderLine(renderLineContent, wrappedTextIndentLength, tabSize, width, sb, additionalIndentLength);
        firstNonWhitespaceIndices[i] = firstNonWhitespaceIndex;
        wrappedTextIndentLengths[i] = wrappedTextIndentLength;
        renderLineContents[i] = renderLineContent;
        allCharOffsets[i] = tmp[0];
        allVisibleColumns[i] = tmp[1];
    }
    const html = sb.build();
    const trustedhtml = (_a = ttPolicy === null || ttPolicy === void 0 ? void 0 : ttPolicy.createHTML(html)) !== null && _a !== void 0 ? _a : html;
    containerDomNode.innerHTML = trustedhtml;
    containerDomNode.style.position = 'absolute';
    containerDomNode.style.top = '10000';
    containerDomNode.style.wordWrap = 'break-word';
    document.body.appendChild(containerDomNode);
    const range = document.createRange();
    const lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0);
    const result = [];
    for (let i = 0; i < requests.length; i++) {
        const lineDomNode = lineDomNodes[i];
        const breakOffsets = readLineBreaks(range, lineDomNode, renderLineContents[i], allCharOffsets[i]);
        if (breakOffsets === null) {
            result[i] = createEmptyLineBreakWithPossiblyInjectedText(i);
            continue;
        }
        const firstNonWhitespaceIndex = firstNonWhitespaceIndices[i];
        const wrappedTextIndentLength = wrappedTextIndentLengths[i] + additionalIndentSize;
        const visibleColumns = allVisibleColumns[i];
        const breakOffsetsVisibleColumn = [];
        for (let j = 0, len = breakOffsets.length; j < len; j++) {
            breakOffsetsVisibleColumn[j] = visibleColumns[breakOffsets[j]];
        }
        if (firstNonWhitespaceIndex !== 0) {
            // All break offsets are relative to the renderLineContent, make them absolute again
            for (let j = 0, len = breakOffsets.length; j < len; j++) {
                breakOffsets[j] += firstNonWhitespaceIndex;
            }
        }
        let injectionOptions;
        let injectionOffsets;
        const curInjectedTexts = injectedTextsPerLine[i];
        if (curInjectedTexts) {
            injectionOptions = curInjectedTexts.map(t => t.options);
            injectionOffsets = curInjectedTexts.map(text => text.column - 1);
        }
        else {
            injectionOptions = null;
            injectionOffsets = null;
        }
        result[i] = new ModelLineProjectionData(injectionOffsets, injectionOptions, breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength);
    }
    document.body.removeChild(containerDomNode);
    return result;
}
function renderLine(lineContent, initialVisibleColumn, tabSize, width, sb, wrappingIndentLength) {
    if (wrappingIndentLength !== 0) {
        const hangingOffset = String(wrappingIndentLength);
        sb.appendASCIIString('<div style="text-indent: -');
        sb.appendASCIIString(hangingOffset);
        sb.appendASCIIString('px; padding-left: ');
        sb.appendASCIIString(hangingOffset);
        sb.appendASCIIString('px; box-sizing: border-box; width:');
    }
    else {
        sb.appendASCIIString('<div style="width:');
    }
    sb.appendASCIIString(String(width));
    sb.appendASCIIString('px;">');
    // if (containsRTL) {
    // 	sb.appendASCIIString('" dir="ltr');
    // }
    const len = lineContent.length;
    let visibleColumn = initialVisibleColumn;
    let charOffset = 0;
    const charOffsets = [];
    const visibleColumns = [];
    let nextCharCode = (0 < len ? lineContent.charCodeAt(0) : 0 /* CharCode.Null */);
    sb.appendASCIIString('<span>');
    for (let charIndex = 0; charIndex < len; charIndex++) {
        if (charIndex !== 0 && charIndex % 16384 /* Constants.SPAN_MODULO_LIMIT */ === 0) {
            sb.appendASCIIString('</span><span>');
        }
        charOffsets[charIndex] = charOffset;
        visibleColumns[charIndex] = visibleColumn;
        const charCode = nextCharCode;
        nextCharCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0 /* CharCode.Null */);
        let producedCharacters = 1;
        let charWidth = 1;
        switch (charCode) {
            case 9 /* CharCode.Tab */:
                producedCharacters = (tabSize - (visibleColumn % tabSize));
                charWidth = producedCharacters;
                for (let space = 1; space <= producedCharacters; space++) {
                    if (space < producedCharacters) {
                        sb.write1(0xA0); // &nbsp;
                    }
                    else {
                        sb.appendASCII(32 /* CharCode.Space */);
                    }
                }
                break;
            case 32 /* CharCode.Space */:
                if (nextCharCode === 32 /* CharCode.Space */) {
                    sb.write1(0xA0); // &nbsp;
                }
                else {
                    sb.appendASCII(32 /* CharCode.Space */);
                }
                break;
            case 60 /* CharCode.LessThan */:
                sb.appendASCIIString('&lt;');
                break;
            case 62 /* CharCode.GreaterThan */:
                sb.appendASCIIString('&gt;');
                break;
            case 38 /* CharCode.Ampersand */:
                sb.appendASCIIString('&amp;');
                break;
            case 0 /* CharCode.Null */:
                sb.appendASCIIString('&#00;');
                break;
            case 65279 /* CharCode.UTF8_BOM */:
            case 8232 /* CharCode.LINE_SEPARATOR */:
            case 8233 /* CharCode.PARAGRAPH_SEPARATOR */:
            case 133 /* CharCode.NEXT_LINE */:
                sb.write1(0xFFFD);
                break;
            default:
                if (isFullWidthCharacter(charCode)) {
                    charWidth++;
                }
                if (charCode < 32) {
                    sb.write1(9216 + charCode);
                }
                else {
                    sb.write1(charCode);
                }
        }
        charOffset += producedCharacters;
        visibleColumn += charWidth;
    }
    sb.appendASCIIString('</span>');
    charOffsets[lineContent.length] = charOffset;
    visibleColumns[lineContent.length] = visibleColumn;
    sb.appendASCIIString('</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) {
        // same line
        return;
    }
    // there is at least one line break between these two offsets
    if (low + 1 === high) {
        // the two characters are adjacent, so the line break must be exactly between them
        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 /* Constants.SPAN_MODULO_LIMIT */) | 0].firstChild, startOffset % 16384 /* Constants.SPAN_MODULO_LIMIT */);
    range.setEnd(spans[(endOffset / 16384 /* Constants.SPAN_MODULO_LIMIT */) | 0].firstChild, endOffset % 16384 /* Constants.SPAN_MODULO_LIMIT */);
    return range.getClientRects();
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/widget/codeEditorWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var codeEditorWidget_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var codeEditorWidget_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var codeEditorWidget_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};








































let EDITOR_ID = 0;
class ModelData {
    constructor(model, viewModel, view, hasRealView, listenersToRemove) {
        this.model = model;
        this.viewModel = viewModel;
        this.view = view;
        this.hasRealView = hasRealView;
        this.listenersToRemove = listenersToRemove;
    }
    dispose() {
        dispose(this.listenersToRemove);
        this.model.onBeforeDetached();
        if (this.hasRealView) {
            this.view.dispose();
        }
        this.viewModel.dispose();
    }
}
let CodeEditorWidget = class CodeEditorWidget extends Disposable {
    constructor(domElement, _options, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
        super();
        this.languageConfigurationService = languageConfigurationService;
        //#region Eventing
        this._deliveryQueue = new EventDeliveryQueue();
        this._onDidDispose = this._register(new Emitter());
        this.onDidDispose = this._onDidDispose.event;
        this._onDidChangeModelContent = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeModelContent = this._onDidChangeModelContent.event;
        this._onDidChangeModelLanguage = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeModelLanguage = this._onDidChangeModelLanguage.event;
        this._onDidChangeModelLanguageConfiguration = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeModelLanguageConfiguration = this._onDidChangeModelLanguageConfiguration.event;
        this._onDidChangeModelOptions = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeModelOptions = this._onDidChangeModelOptions.event;
        this._onDidChangeModelDecorations = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeModelDecorations = this._onDidChangeModelDecorations.event;
        this._onDidChangeModelTokens = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeModelTokens = this._onDidChangeModelTokens.event;
        this._onDidChangeConfiguration = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
        this._onDidChangeModel = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeModel = this._onDidChangeModel.event;
        this._onDidChangeCursorPosition = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeCursorPosition = this._onDidChangeCursorPosition.event;
        this._onDidChangeCursorSelection = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeCursorSelection = this._onDidChangeCursorSelection.event;
        this._onDidAttemptReadOnlyEdit = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidAttemptReadOnlyEdit = this._onDidAttemptReadOnlyEdit.event;
        this._onDidLayoutChange = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidLayoutChange = this._onDidLayoutChange.event;
        this._editorTextFocus = this._register(new BooleanEventEmitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidFocusEditorText = this._editorTextFocus.onDidChangeToTrue;
        this.onDidBlurEditorText = this._editorTextFocus.onDidChangeToFalse;
        this._editorWidgetFocus = this._register(new BooleanEventEmitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidFocusEditorWidget = this._editorWidgetFocus.onDidChangeToTrue;
        this.onDidBlurEditorWidget = this._editorWidgetFocus.onDidChangeToFalse;
        this._onWillType = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onWillType = this._onWillType.event;
        this._onDidType = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidType = this._onDidType.event;
        this._onDidCompositionStart = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidCompositionStart = this._onDidCompositionStart.event;
        this._onDidCompositionEnd = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidCompositionEnd = this._onDidCompositionEnd.event;
        this._onDidPaste = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidPaste = this._onDidPaste.event;
        this._onMouseUp = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onMouseUp = this._onMouseUp.event;
        this._onMouseDown = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onMouseDown = this._onMouseDown.event;
        this._onMouseDrag = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onMouseDrag = this._onMouseDrag.event;
        this._onMouseDrop = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onMouseDrop = this._onMouseDrop.event;
        this._onMouseDropCanceled = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onMouseDropCanceled = this._onMouseDropCanceled.event;
        this._onDropIntoEditor = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDropIntoEditor = this._onDropIntoEditor.event;
        this._onContextMenu = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onContextMenu = this._onContextMenu.event;
        this._onMouseMove = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onMouseMove = this._onMouseMove.event;
        this._onMouseLeave = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onMouseLeave = this._onMouseLeave.event;
        this._onMouseWheel = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onMouseWheel = this._onMouseWheel.event;
        this._onKeyUp = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onKeyUp = this._onKeyUp.event;
        this._onKeyDown = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onKeyDown = this._onKeyDown.event;
        this._onDidContentSizeChange = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidContentSizeChange = this._onDidContentSizeChange.event;
        this._onDidScrollChange = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidScrollChange = this._onDidScrollChange.event;
        this._onDidChangeViewZones = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeViewZones = this._onDidChangeViewZones.event;
        this._onDidChangeHiddenAreas = this._register(new Emitter({ deliveryQueue: this._deliveryQueue }));
        this.onDidChangeHiddenAreas = this._onDidChangeHiddenAreas.event;
        this._bannerDomNode = null;
        this._dropIntoEditorDecorations = this.createDecorationsCollection();
        const options = Object.assign({}, _options);
        this._domElement = domElement;
        this._overflowWidgetsDomNode = options.overflowWidgetsDomNode;
        delete options.overflowWidgetsDomNode;
        this._id = (++EDITOR_ID);
        this._decorationTypeKeysToIds = {};
        this._decorationTypeSubtypes = {};
        this._telemetryData = codeEditorWidgetOptions.telemetryData;
        this._configuration = this._register(this._createConfiguration(codeEditorWidgetOptions.isSimpleWidget || false, options, accessibilityService));
        this._register(this._configuration.onDidChange((e) => {
            this._onDidChangeConfiguration.fire(e);
            const options = this._configuration.options;
            if (e.hasChanged(133 /* EditorOption.layoutInfo */)) {
                const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
                this._onDidLayoutChange.fire(layoutInfo);
            }
        }));
        this._contextKeyService = this._register(contextKeyService.createScoped(this._domElement));
        this._notificationService = notificationService;
        this._codeEditorService = codeEditorService;
        this._commandService = commandService;
        this._themeService = themeService;
        this._register(new EditorContextKeysManager(this, this._contextKeyService));
        this._register(new EditorModeContext(this, this._contextKeyService, languageFeaturesService));
        this._instantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService]));
        this._modelData = null;
        this._contributions = {};
        this._actions = {};
        this._focusTracker = new CodeEditorWidgetFocusTracker(domElement);
        this._register(this._focusTracker.onChange(() => {
            this._editorWidgetFocus.setValue(this._focusTracker.hasFocus());
        }));
        this._contentWidgets = {};
        this._overlayWidgets = {};
        let contributions;
        if (Array.isArray(codeEditorWidgetOptions.contributions)) {
            contributions = codeEditorWidgetOptions.contributions;
        }
        else {
            contributions = EditorExtensionsRegistry.getEditorContributions();
        }
        for (const desc of contributions) {
            if (this._contributions[desc.id]) {
                onUnexpectedError(new Error(`Cannot have two contributions with the same id ${desc.id}`));
                continue;
            }
            try {
                const contribution = this._instantiationService.createInstance(desc.ctor, this);
                this._contributions[desc.id] = contribution;
            }
            catch (err) {
                onUnexpectedError(err);
            }
        }
        EditorExtensionsRegistry.getEditorActions().forEach((action) => {
            if (this._actions[action.id]) {
                onUnexpectedError(new Error(`Cannot have two actions with the same id ${action.id}`));
                return;
            }
            const internalAction = new InternalEditorAction(action.id, action.label, action.alias, withNullAsUndefined(action.precondition), () => {
                return this._instantiationService.invokeFunction((accessor) => {
                    return Promise.resolve(action.runEditorCommand(accessor, this, null));
                });
            }, this._contextKeyService);
            this._actions[internalAction.id] = internalAction;
        });
        const isDropIntoEnabled = () => {
            return !this._configuration.options.get(83 /* EditorOption.readOnly */)
                && this._configuration.options.get(32 /* EditorOption.dropIntoEditor */).enabled;
        };
        this._register(new DragAndDropObserver(this._domElement, {
            onDragEnter: () => undefined,
            onDragOver: e => {
                if (!isDropIntoEnabled()) {
                    return;
                }
                const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
                if (target === null || target === void 0 ? void 0 : target.position) {
                    this.showDropIndicatorAt(target.position);
                }
            },
            onDrop: (e) => codeEditorWidget_awaiter(this, void 0, void 0, function* () {
                if (!isDropIntoEnabled()) {
                    return;
                }
                this.removeDropIndicator();
                if (!e.dataTransfer) {
                    return;
                }
                const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
                if (target === null || target === void 0 ? void 0 : target.position) {
                    this._onDropIntoEditor.fire({ position: target.position, event: e });
                }
            }),
            onDragLeave: () => {
                this.removeDropIndicator();
            },
            onDragEnd: () => {
                this.removeDropIndicator();
            },
        }));
        this._codeEditorService.addCodeEditor(this);
    }
    //#endregion
    get isSimpleWidget() {
        return this._configuration.isSimpleWidget;
    }
    _createConfiguration(isSimpleWidget, options, accessibilityService) {
        return new EditorConfiguration(isSimpleWidget, options, this._domElement, accessibilityService);
    }
    getId() {
        return this.getEditorType() + ':' + this._id;
    }
    getEditorType() {
        return EditorType.ICodeEditor;
    }
    dispose() {
        this._codeEditorService.removeCodeEditor(this);
        this._focusTracker.dispose();
        const keys = Object.keys(this._contributions);
        for (let i = 0, len = keys.length; i < len; i++) {
            const contributionId = keys[i];
            this._contributions[contributionId].dispose();
        }
        this._contributions = {};
        this._actions = {};
        this._contentWidgets = {};
        this._overlayWidgets = {};
        this._removeDecorationTypes();
        this._postDetachModelCleanup(this._detachModel());
        this._onDidDispose.fire();
        super.dispose();
    }
    invokeWithinContext(fn) {
        return this._instantiationService.invokeFunction(fn);
    }
    updateOptions(newOptions) {
        this._configuration.updateOptions(newOptions || {});
    }
    getOptions() {
        return this._configuration.options;
    }
    getOption(id) {
        return this._configuration.options.get(id);
    }
    getRawOptions() {
        return this._configuration.getRawOptions();
    }
    getOverflowWidgetsDomNode() {
        return this._overflowWidgetsDomNode;
    }
    getConfiguredWordAtPosition(position) {
        if (!this._modelData) {
            return null;
        }
        return WordOperations.getWordAtPosition(this._modelData.model, this._configuration.options.get(119 /* EditorOption.wordSeparators */), position);
    }
    getValue(options = null) {
        if (!this._modelData) {
            return '';
        }
        const preserveBOM = (options && options.preserveBOM) ? true : false;
        let eolPreference = 0 /* EndOfLinePreference.TextDefined */;
        if (options && options.lineEnding && options.lineEnding === '\n') {
            eolPreference = 1 /* EndOfLinePreference.LF */;
        }
        else if (options && options.lineEnding && options.lineEnding === '\r\n') {
            eolPreference = 2 /* EndOfLinePreference.CRLF */;
        }
        return this._modelData.model.getValue(eolPreference, preserveBOM);
    }
    setValue(newValue) {
        if (!this._modelData) {
            return;
        }
        this._modelData.model.setValue(newValue);
    }
    getModel() {
        if (!this._modelData) {
            return null;
        }
        return this._modelData.model;
    }
    setModel(_model = null) {
        const model = _model;
        if (this._modelData === null && model === null) {
            // Current model is the new model
            return;
        }
        if (this._modelData && this._modelData.model === model) {
            // Current model is the new model
            return;
        }
        const hasTextFocus = this.hasTextFocus();
        const detachedModel = this._detachModel();
        this._attachModel(model);
        if (hasTextFocus && this.hasModel()) {
            this.focus();
        }
        const e = {
            oldModelUrl: detachedModel ? detachedModel.uri : null,
            newModelUrl: model ? model.uri : null
        };
        this._removeDecorationTypes();
        this._onDidChangeModel.fire(e);
        this._postDetachModelCleanup(detachedModel);
    }
    _removeDecorationTypes() {
        this._decorationTypeKeysToIds = {};
        if (this._decorationTypeSubtypes) {
            for (const decorationType in this._decorationTypeSubtypes) {
                const subTypes = this._decorationTypeSubtypes[decorationType];
                for (const subType in subTypes) {
                    this._removeDecorationType(decorationType + '-' + subType);
                }
            }
            this._decorationTypeSubtypes = {};
        }
    }
    getVisibleRanges() {
        if (!this._modelData) {
            return [];
        }
        return this._modelData.viewModel.getVisibleRanges();
    }
    getVisibleRangesPlusViewportAboveBelow() {
        if (!this._modelData) {
            return [];
        }
        return this._modelData.viewModel.getVisibleRangesPlusViewportAboveBelow();
    }
    getWhitespaces() {
        if (!this._modelData) {
            return [];
        }
        return this._modelData.viewModel.viewLayout.getWhitespaces();
    }
    static _getVerticalOffsetAfterPosition(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._modelData) {
            return -1;
        }
        return CodeEditorWidget._getVerticalOffsetForPosition(this._modelData, lineNumber, 1, includeViewZones);
    }
    getTopForPosition(lineNumber, column) {
        if (!this._modelData) {
            return -1;
        }
        return CodeEditorWidget._getVerticalOffsetForPosition(this._modelData, lineNumber, column, false);
    }
    static _getVerticalOffsetForPosition(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._modelData) {
            return -1;
        }
        return CodeEditorWidget._getVerticalOffsetAfterPosition(this._modelData, lineNumber, 1, includeViewZones);
    }
    setHiddenAreas(ranges) {
        var _a;
        (_a = this._modelData) === null || _a === void 0 ? void 0 : _a.viewModel.setHiddenAreas(ranges.map(r => Range.lift(r)));
    }
    getVisibleColumnFromPosition(rawPosition) {
        if (!this._modelData) {
            return rawPosition.column;
        }
        const position = this._modelData.model.validatePosition(rawPosition);
        const tabSize = this._modelData.model.getOptions().tabSize;
        return CursorColumns.visibleColumnFromColumn(this._modelData.model.getLineContent(position.lineNumber), position.column, tabSize) + 1;
    }
    getPosition() {
        if (!this._modelData) {
            return null;
        }
        return this._modelData.viewModel.getPosition();
    }
    setPosition(position, source = 'api') {
        if (!this._modelData) {
            return;
        }
        if (!Position.isIPosition(position)) {
            throw new Error('Invalid arguments');
        }
        this._modelData.viewModel.setSelections(source, [{
                selectionStartLineNumber: position.lineNumber,
                selectionStartColumn: position.column,
                positionLineNumber: position.lineNumber,
                positionColumn: position.column
            }]);
    }
    _sendRevealRange(modelRange, verticalType, revealHorizontal, scrollType) {
        if (!this._modelData) {
            return;
        }
        if (!Range.isIRange(modelRange)) {
            throw new Error('Invalid arguments');
        }
        const validatedModelRange = this._modelData.model.validateRange(modelRange);
        const viewRange = this._modelData.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange);
        this._modelData.viewModel.revealRange('api', revealHorizontal, viewRange, verticalType, scrollType);
    }
    revealLine(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealLine(lineNumber, 0 /* VerticalRevealType.Simple */, scrollType);
    }
    revealLineInCenter(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealLine(lineNumber, 1 /* VerticalRevealType.Center */, scrollType);
    }
    revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealLine(lineNumber, 2 /* VerticalRevealType.CenterIfOutsideViewport */, scrollType);
    }
    revealLineNearTop(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealLine(lineNumber, 5 /* VerticalRevealType.NearTop */, scrollType);
    }
    _revealLine(lineNumber, revealType, scrollType) {
        if (typeof lineNumber !== 'number') {
            throw new Error('Invalid arguments');
        }
        this._sendRevealRange(new Range(lineNumber, 1, lineNumber, 1), revealType, false, scrollType);
    }
    revealPosition(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealPosition(position, 0 /* VerticalRevealType.Simple */, true, scrollType);
    }
    revealPositionInCenter(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealPosition(position, 1 /* VerticalRevealType.Center */, true, scrollType);
    }
    revealPositionInCenterIfOutsideViewport(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealPosition(position, 2 /* VerticalRevealType.CenterIfOutsideViewport */, true, scrollType);
    }
    revealPositionNearTop(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealPosition(position, 5 /* VerticalRevealType.NearTop */, true, scrollType);
    }
    _revealPosition(position, verticalType, revealHorizontal, scrollType) {
        if (!Position.isIPosition(position)) {
            throw new Error('Invalid arguments');
        }
        this._sendRevealRange(new Range(position.lineNumber, position.column, position.lineNumber, position.column), verticalType, revealHorizontal, scrollType);
    }
    getSelection() {
        if (!this._modelData) {
            return null;
        }
        return this._modelData.viewModel.getSelection();
    }
    getSelections() {
        if (!this._modelData) {
            return null;
        }
        return this._modelData.viewModel.getSelections();
    }
    setSelection(something, source = 'api') {
        const isSelection = Selection.isISelection(something);
        const isRange = Range.isIRange(something);
        if (!isSelection && !isRange) {
            throw new Error('Invalid arguments');
        }
        if (isSelection) {
            this._setSelectionImpl(something, source);
        }
        else if (isRange) {
            // act as if it was an IRange
            const selection = {
                selectionStartLineNumber: something.startLineNumber,
                selectionStartColumn: something.startColumn,
                positionLineNumber: something.endLineNumber,
                positionColumn: something.endColumn
            };
            this._setSelectionImpl(selection, source);
        }
    }
    _setSelectionImpl(sel, source) {
        if (!this._modelData) {
            return;
        }
        const selection = new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
        this._modelData.viewModel.setSelections(source, [selection]);
    }
    revealLines(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealLines(startLineNumber, endLineNumber, 0 /* VerticalRevealType.Simple */, scrollType);
    }
    revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealLines(startLineNumber, endLineNumber, 1 /* VerticalRevealType.Center */, scrollType);
    }
    revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealLines(startLineNumber, endLineNumber, 2 /* VerticalRevealType.CenterIfOutsideViewport */, scrollType);
    }
    revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealLines(startLineNumber, endLineNumber, 5 /* VerticalRevealType.NearTop */, scrollType);
    }
    _revealLines(startLineNumber, endLineNumber, verticalType, scrollType) {
        if (typeof startLineNumber !== 'number' || typeof endLineNumber !== 'number') {
            throw new Error('Invalid arguments');
        }
        this._sendRevealRange(new Range(startLineNumber, 1, endLineNumber, 1), verticalType, false, scrollType);
    }
    revealRange(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */, revealVerticalInCenter = false, revealHorizontal = true) {
        this._revealRange(range, revealVerticalInCenter ? 1 /* VerticalRevealType.Center */ : 0 /* VerticalRevealType.Simple */, revealHorizontal, scrollType);
    }
    revealRangeInCenter(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealRange(range, 1 /* VerticalRevealType.Center */, true, scrollType);
    }
    revealRangeInCenterIfOutsideViewport(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealRange(range, 2 /* VerticalRevealType.CenterIfOutsideViewport */, true, scrollType);
    }
    revealRangeNearTop(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealRange(range, 5 /* VerticalRevealType.NearTop */, true, scrollType);
    }
    revealRangeNearTopIfOutsideViewport(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealRange(range, 6 /* VerticalRevealType.NearTopIfOutsideViewport */, true, scrollType);
    }
    revealRangeAtTop(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._revealRange(range, 3 /* VerticalRevealType.Top */, true, scrollType);
    }
    _revealRange(range, verticalType, revealHorizontal, scrollType) {
        if (!Range.isIRange(range)) {
            throw new Error('Invalid arguments');
        }
        this._sendRevealRange(Range.lift(range), verticalType, revealHorizontal, scrollType);
    }
    setSelections(ranges, source = 'api', reason = 0 /* CursorChangeReason.NotSet */) {
        if (!this._modelData) {
            return;
        }
        if (!ranges || ranges.length === 0) {
            throw new Error('Invalid arguments');
        }
        for (let i = 0, len = ranges.length; i < len; i++) {
            if (!Selection.isISelection(ranges[i])) {
                throw new Error('Invalid arguments');
            }
        }
        this._modelData.viewModel.setSelections(source, ranges, reason);
    }
    getContentWidth() {
        if (!this._modelData) {
            return -1;
        }
        return this._modelData.viewModel.viewLayout.getContentWidth();
    }
    getScrollWidth() {
        if (!this._modelData) {
            return -1;
        }
        return this._modelData.viewModel.viewLayout.getScrollWidth();
    }
    getScrollLeft() {
        if (!this._modelData) {
            return -1;
        }
        return this._modelData.viewModel.viewLayout.getCurrentScrollLeft();
    }
    getContentHeight() {
        if (!this._modelData) {
            return -1;
        }
        return this._modelData.viewModel.viewLayout.getContentHeight();
    }
    getScrollHeight() {
        if (!this._modelData) {
            return -1;
        }
        return this._modelData.viewModel.viewLayout.getScrollHeight();
    }
    getScrollTop() {
        if (!this._modelData) {
            return -1;
        }
        return this._modelData.viewModel.viewLayout.getCurrentScrollTop();
    }
    setScrollLeft(newScrollLeft, scrollType = 1 /* editorCommon.ScrollType.Immediate */) {
        if (!this._modelData) {
            return;
        }
        if (typeof newScrollLeft !== 'number') {
            throw new Error('Invalid arguments');
        }
        this._modelData.viewModel.viewLayout.setScrollPosition({
            scrollLeft: newScrollLeft
        }, scrollType);
    }
    setScrollTop(newScrollTop, scrollType = 1 /* editorCommon.ScrollType.Immediate */) {
        if (!this._modelData) {
            return;
        }
        if (typeof newScrollTop !== 'number') {
            throw new Error('Invalid arguments');
        }
        this._modelData.viewModel.viewLayout.setScrollPosition({
            scrollTop: newScrollTop
        }, scrollType);
    }
    setScrollPosition(position, scrollType = 1 /* editorCommon.ScrollType.Immediate */) {
        if (!this._modelData) {
            return;
        }
        this._modelData.viewModel.viewLayout.setScrollPosition(position, scrollType);
    }
    saveViewState() {
        if (!this._modelData) {
            return null;
        }
        const contributionsState = {};
        const keys = Object.keys(this._contributions);
        for (const id of keys) {
            const contribution = this._contributions[id];
            if (typeof contribution.saveViewState === 'function') {
                contributionsState[id] = contribution.saveViewState();
            }
        }
        const cursorState = this._modelData.viewModel.saveCursorState();
        const viewState = this._modelData.viewModel.saveState();
        return {
            cursorState: cursorState,
            viewState: viewState,
            contributionsState: contributionsState
        };
    }
    restoreViewState(s) {
        if (!this._modelData || !this._modelData.hasRealView) {
            return;
        }
        const codeEditorState = s;
        if (codeEditorState && codeEditorState.cursorState && codeEditorState.viewState) {
            const cursorState = codeEditorState.cursorState;
            if (Array.isArray(cursorState)) {
                if (cursorState.length > 0) {
                    this._modelData.viewModel.restoreCursorState(cursorState);
                }
            }
            else {
                // Backwards compatibility
                this._modelData.viewModel.restoreCursorState([cursorState]);
            }
            const contributionsState = codeEditorState.contributionsState || {};
            const keys = Object.keys(this._contributions);
            for (let i = 0, len = keys.length; i < len; i++) {
                const id = keys[i];
                const contribution = this._contributions[id];
                if (typeof contribution.restoreViewState === 'function') {
                    contribution.restoreViewState(contributionsState[id]);
                }
            }
            const reducedState = this._modelData.viewModel.reduceRestoreState(codeEditorState.viewState);
            this._modelData.view.restoreState(reducedState);
        }
    }
    getContribution(id) {
        return (this._contributions[id] || null);
    }
    getActions() {
        const result = [];
        const keys = Object.keys(this._actions);
        for (let i = 0, len = keys.length; i < len; i++) {
            const id = keys[i];
            result.push(this._actions[id]);
        }
        return result;
    }
    getSupportedActions() {
        let result = this.getActions();
        result = result.filter(action => action.isSupported());
        return result;
    }
    getAction(id) {
        return this._actions[id] || null;
    }
    trigger(source, handlerId, payload) {
        payload = payload || {};
        switch (handlerId) {
            case "compositionStart" /* editorCommon.Handler.CompositionStart */:
                this._startComposition();
                return;
            case "compositionEnd" /* editorCommon.Handler.CompositionEnd */:
                this._endComposition(source);
                return;
            case "type" /* editorCommon.Handler.Type */: {
                const args = payload;
                this._type(source, args.text || '');
                return;
            }
            case "replacePreviousChar" /* editorCommon.Handler.ReplacePreviousChar */: {
                const args = payload;
                this._compositionType(source, args.text || '', args.replaceCharCnt || 0, 0, 0);
                return;
            }
            case "compositionType" /* editorCommon.Handler.CompositionType */: {
                const args = payload;
                this._compositionType(source, args.text || '', args.replacePrevCharCnt || 0, args.replaceNextCharCnt || 0, args.positionDelta || 0);
                return;
            }
            case "paste" /* editorCommon.Handler.Paste */: {
                const args = payload;
                this._paste(source, args.text || '', args.pasteOnNewLine || false, args.multicursorText || null, args.mode || null);
                return;
            }
            case "cut" /* editorCommon.Handler.Cut */:
                this._cut(source);
                return;
        }
        const action = this.getAction(handlerId);
        if (action) {
            Promise.resolve(action.run()).then(undefined, onUnexpectedError);
            return;
        }
        if (!this._modelData) {
            return;
        }
        if (this._triggerEditorCommand(source, handlerId, payload)) {
            return;
        }
        this._triggerCommand(handlerId, payload);
    }
    _triggerCommand(handlerId, payload) {
        this._commandService.executeCommand(handlerId, payload);
    }
    _startComposition() {
        if (!this._modelData) {
            return;
        }
        this._modelData.viewModel.startComposition();
        this._onDidCompositionStart.fire();
    }
    _endComposition(source) {
        if (!this._modelData) {
            return;
        }
        this._modelData.viewModel.endComposition(source);
        this._onDidCompositionEnd.fire();
    }
    _type(source, text) {
        if (!this._modelData || text.length === 0) {
            return;
        }
        if (source === 'keyboard') {
            this._onWillType.fire(text);
        }
        this._modelData.viewModel.type(text, source);
        if (source === 'keyboard') {
            this._onDidType.fire(text);
        }
    }
    _compositionType(source, text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
        if (!this._modelData) {
            return;
        }
        this._modelData.viewModel.compositionType(text, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source);
    }
    _paste(source, text, pasteOnNewLine, multicursorText, mode) {
        if (!this._modelData || text.length === 0) {
            return;
        }
        const viewModel = this._modelData.viewModel;
        const startPosition = viewModel.getSelection().getStartPosition();
        viewModel.paste(text, pasteOnNewLine, multicursorText, source);
        const endPosition = viewModel.getSelection().getStartPosition();
        if (source === 'keyboard') {
            this._onDidPaste.fire({
                range: new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column),
                languageId: mode
            });
        }
    }
    _cut(source) {
        if (!this._modelData) {
            return;
        }
        this._modelData.viewModel.cut(source);
    }
    _triggerEditorCommand(source, handlerId, payload) {
        const command = EditorExtensionsRegistry.getEditorCommand(handlerId);
        if (command) {
            payload = payload || {};
            payload.source = source;
            this._instantiationService.invokeFunction((accessor) => {
                Promise.resolve(command.runEditorCommand(accessor, this, payload)).then(undefined, onUnexpectedError);
            });
            return true;
        }
        return false;
    }
    _getViewModel() {
        if (!this._modelData) {
            return null;
        }
        return this._modelData.viewModel;
    }
    pushUndoStop() {
        if (!this._modelData) {
            return false;
        }
        if (this._configuration.options.get(83 /* EditorOption.readOnly */)) {
            // read only editor => sorry!
            return false;
        }
        this._modelData.model.pushStackElement();
        return true;
    }
    popUndoStop() {
        if (!this._modelData) {
            return false;
        }
        if (this._configuration.options.get(83 /* EditorOption.readOnly */)) {
            // read only editor => sorry!
            return false;
        }
        this._modelData.model.popStackElement();
        return true;
    }
    executeEdits(source, edits, endCursorState) {
        if (!this._modelData) {
            return false;
        }
        if (this._configuration.options.get(83 /* EditorOption.readOnly */)) {
            // read only editor => sorry!
            return false;
        }
        let cursorStateComputer;
        if (!endCursorState) {
            cursorStateComputer = () => null;
        }
        else if (Array.isArray(endCursorState)) {
            cursorStateComputer = () => endCursorState;
        }
        else {
            cursorStateComputer = endCursorState;
        }
        this._modelData.viewModel.executeEdits(source, edits, cursorStateComputer);
        return true;
    }
    executeCommand(source, command) {
        if (!this._modelData) {
            return;
        }
        this._modelData.viewModel.executeCommand(command, source);
    }
    executeCommands(source, commands) {
        if (!this._modelData) {
            return;
        }
        this._modelData.viewModel.executeCommands(commands, source);
    }
    createDecorationsCollection(decorations) {
        return new EditorDecorationsCollection(this, decorations);
    }
    changeDecorations(callback) {
        if (!this._modelData) {
            // callback will not be called
            return null;
        }
        return this._modelData.model.changeDecorations(callback, this._id);
    }
    getLineDecorations(lineNumber) {
        if (!this._modelData) {
            return null;
        }
        return this._modelData.model.getLineDecorations(lineNumber, this._id, filterValidationDecorations(this._configuration.options));
    }
    getDecorationsInRange(range) {
        if (!this._modelData) {
            return null;
        }
        return this._modelData.model.getDecorationsInRange(range, this._id, filterValidationDecorations(this._configuration.options));
    }
    /**
     * @deprecated
     */
    deltaDecorations(oldDecorations, newDecorations) {
        if (!this._modelData) {
            return [];
        }
        if (oldDecorations.length === 0 && newDecorations.length === 0) {
            return oldDecorations;
        }
        return this._modelData.model.deltaDecorations(oldDecorations, newDecorations, this._id);
    }
    removeDecorations(decorationIds) {
        if (!this._modelData || decorationIds.length === 0) {
            return;
        }
        this._modelData.model.changeDecorations((changeAccessor) => {
            changeAccessor.deltaDecorations(decorationIds, []);
        });
    }
    removeDecorationsByType(decorationTypeKey) {
        // remove decorations for type and sub type
        const oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey];
        if (oldDecorationsIds) {
            this.deltaDecorations(oldDecorationsIds, []);
        }
        if (this._decorationTypeKeysToIds.hasOwnProperty(decorationTypeKey)) {
            delete this._decorationTypeKeysToIds[decorationTypeKey];
        }
        if (this._decorationTypeSubtypes.hasOwnProperty(decorationTypeKey)) {
            delete this._decorationTypeSubtypes[decorationTypeKey];
        }
    }
    getLayoutInfo() {
        const options = this._configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        return layoutInfo;
    }
    createOverviewRuler(cssClassName) {
        if (!this._modelData || !this._modelData.hasRealView) {
            return null;
        }
        return this._modelData.view.createOverviewRuler(cssClassName);
    }
    getContainerDomNode() {
        return this._domElement;
    }
    getDomNode() {
        if (!this._modelData || !this._modelData.hasRealView) {
            return null;
        }
        return this._modelData.view.domNode.domNode;
    }
    delegateVerticalScrollbarPointerDown(browserEvent) {
        if (!this._modelData || !this._modelData.hasRealView) {
            return;
        }
        this._modelData.view.delegateVerticalScrollbarPointerDown(browserEvent);
    }
    layout(dimension) {
        this._configuration.observeContainer(dimension);
        this.render();
    }
    focus() {
        if (!this._modelData || !this._modelData.hasRealView) {
            return;
        }
        this._modelData.view.focus();
    }
    hasTextFocus() {
        if (!this._modelData || !this._modelData.hasRealView) {
            return false;
        }
        return this._modelData.view.isFocused();
    }
    hasWidgetFocus() {
        return this._focusTracker && this._focusTracker.hasFocus();
    }
    addContentWidget(widget) {
        const widgetData = {
            widget: widget,
            position: widget.getPosition()
        };
        if (this._contentWidgets.hasOwnProperty(widget.getId())) {
            console.warn('Overwriting a content widget with the same id.');
        }
        this._contentWidgets[widget.getId()] = widgetData;
        if (this._modelData && this._modelData.hasRealView) {
            this._modelData.view.addContentWidget(widgetData);
        }
    }
    layoutContentWidget(widget) {
        const widgetId = widget.getId();
        if (this._contentWidgets.hasOwnProperty(widgetId)) {
            const widgetData = this._contentWidgets[widgetId];
            widgetData.position = widget.getPosition();
            if (this._modelData && this._modelData.hasRealView) {
                this._modelData.view.layoutContentWidget(widgetData);
            }
        }
    }
    removeContentWidget(widget) {
        const widgetId = widget.getId();
        if (this._contentWidgets.hasOwnProperty(widgetId)) {
            const widgetData = this._contentWidgets[widgetId];
            delete this._contentWidgets[widgetId];
            if (this._modelData && this._modelData.hasRealView) {
                this._modelData.view.removeContentWidget(widgetData);
            }
        }
    }
    addOverlayWidget(widget) {
        const widgetData = {
            widget: widget,
            position: widget.getPosition()
        };
        if (this._overlayWidgets.hasOwnProperty(widget.getId())) {
            console.warn('Overwriting an overlay widget with the same id.');
        }
        this._overlayWidgets[widget.getId()] = widgetData;
        if (this._modelData && this._modelData.hasRealView) {
            this._modelData.view.addOverlayWidget(widgetData);
        }
    }
    layoutOverlayWidget(widget) {
        const widgetId = widget.getId();
        if (this._overlayWidgets.hasOwnProperty(widgetId)) {
            const widgetData = this._overlayWidgets[widgetId];
            widgetData.position = widget.getPosition();
            if (this._modelData && this._modelData.hasRealView) {
                this._modelData.view.layoutOverlayWidget(widgetData);
            }
        }
    }
    removeOverlayWidget(widget) {
        const widgetId = widget.getId();
        if (this._overlayWidgets.hasOwnProperty(widgetId)) {
            const widgetData = this._overlayWidgets[widgetId];
            delete this._overlayWidgets[widgetId];
            if (this._modelData && this._modelData.hasRealView) {
                this._modelData.view.removeOverlayWidget(widgetData);
            }
        }
    }
    changeViewZones(callback) {
        if (!this._modelData || !this._modelData.hasRealView) {
            return;
        }
        this._modelData.view.change(callback);
    }
    getTargetAtClientPoint(clientX, clientY) {
        if (!this._modelData || !this._modelData.hasRealView) {
            return null;
        }
        return this._modelData.view.getTargetAtClientPoint(clientX, clientY);
    }
    getScrolledVisiblePosition(rawPosition) {
        if (!this._modelData || !this._modelData.hasRealView) {
            return null;
        }
        const position = this._modelData.model.validatePosition(rawPosition);
        const options = this._configuration.options;
        const layoutInfo = options.get(133 /* EditorOption.layoutInfo */);
        const top = CodeEditorWidget._getVerticalOffsetForPosition(this._modelData, position.lineNumber, position.column) - this.getScrollTop();
        const left = this._modelData.view.getOffsetForColumn(position.lineNumber, position.column) + layoutInfo.glyphMarginWidth + layoutInfo.lineNumbersWidth + layoutInfo.decorationsWidth - this.getScrollLeft();
        return {
            top: top,
            left: left,
            height: options.get(61 /* EditorOption.lineHeight */)
        };
    }
    getOffsetForColumn(lineNumber, column) {
        if (!this._modelData || !this._modelData.hasRealView) {
            return -1;
        }
        return this._modelData.view.getOffsetForColumn(lineNumber, column);
    }
    render(forceRedraw = false) {
        if (!this._modelData || !this._modelData.hasRealView) {
            return;
        }
        this._modelData.view.render(true, forceRedraw);
    }
    setAriaOptions(options) {
        if (!this._modelData || !this._modelData.hasRealView) {
            return;
        }
        this._modelData.view.setAriaOptions(options);
    }
    applyFontInfo(target) {
        applyFontInfo(target, this._configuration.options.get(46 /* EditorOption.fontInfo */));
    }
    setBanner(domNode, domNodeHeight) {
        if (this._bannerDomNode && this._domElement.contains(this._bannerDomNode)) {
            this._domElement.removeChild(this._bannerDomNode);
        }
        this._bannerDomNode = domNode;
        this._configuration.setReservedHeight(domNode ? domNodeHeight : 0);
        if (this._bannerDomNode) {
            this._domElement.prepend(this._bannerDomNode);
        }
    }
    _attachModel(model) {
        if (!model) {
            this._modelData = null;
            return;
        }
        const listenersToRemove = [];
        this._domElement.setAttribute('data-mode-id', model.getLanguageId());
        this._configuration.setIsDominatedByLongLines(model.isDominatedByLongLines());
        this._configuration.setModelLineCount(model.getLineCount());
        model.onBeforeAttached();
        const viewModel = new ViewModel(this._id, this._configuration, model, DOMLineBreaksComputerFactory.create(), MonospaceLineBreaksComputerFactory.create(this._configuration.options), (callback) => scheduleAtNextAnimationFrame(callback), this.languageConfigurationService, this._themeService);
        // Someone might destroy the model from under the editor, so prevent any exceptions by setting a null model
        listenersToRemove.push(model.onWillDispose(() => this.setModel(null)));
        listenersToRemove.push(viewModel.onEvent((e) => {
            switch (e.kind) {
                case 0 /* OutgoingViewModelEventKind.ContentSizeChanged */:
                    this._onDidContentSizeChange.fire(e);
                    break;
                case 1 /* OutgoingViewModelEventKind.FocusChanged */:
                    this._editorTextFocus.setValue(e.hasFocus);
                    break;
                case 2 /* OutgoingViewModelEventKind.ScrollChanged */:
                    this._onDidScrollChange.fire(e);
                    break;
                case 3 /* OutgoingViewModelEventKind.ViewZonesChanged */:
                    this._onDidChangeViewZones.fire();
                    break;
                case 4 /* OutgoingViewModelEventKind.HiddenAreasChanged */:
                    this._onDidChangeHiddenAreas.fire();
                    break;
                case 5 /* OutgoingViewModelEventKind.ReadOnlyEditAttempt */:
                    this._onDidAttemptReadOnlyEdit.fire();
                    break;
                case 6 /* OutgoingViewModelEventKind.CursorStateChanged */: {
                    if (e.reachedMaxCursorCount) {
                        this._notificationService.warn(localize('cursors.maximum', "The number of cursors has been limited to {0}.", CursorsController.MAX_CURSOR_COUNT));
                    }
                    const positions = [];
                    for (let i = 0, len = e.selections.length; i < len; i++) {
                        positions[i] = e.selections[i].getPosition();
                    }
                    const e1 = {
                        position: positions[0],
                        secondaryPositions: positions.slice(1),
                        reason: e.reason,
                        source: e.source
                    };
                    this._onDidChangeCursorPosition.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._onDidChangeCursorSelection.fire(e2);
                    break;
                }
                case 7 /* OutgoingViewModelEventKind.ModelDecorationsChanged */:
                    this._onDidChangeModelDecorations.fire(e.event);
                    break;
                case 8 /* OutgoingViewModelEventKind.ModelLanguageChanged */:
                    this._domElement.setAttribute('data-mode-id', model.getLanguageId());
                    this._onDidChangeModelLanguage.fire(e.event);
                    break;
                case 9 /* OutgoingViewModelEventKind.ModelLanguageConfigurationChanged */:
                    this._onDidChangeModelLanguageConfiguration.fire(e.event);
                    break;
                case 10 /* OutgoingViewModelEventKind.ModelContentChanged */:
                    this._onDidChangeModelContent.fire(e.event);
                    break;
                case 11 /* OutgoingViewModelEventKind.ModelOptionsChanged */:
                    this._onDidChangeModelOptions.fire(e.event);
                    break;
                case 12 /* OutgoingViewModelEventKind.ModelTokensChanged */:
                    this._onDidChangeModelTokens.fire(e.event);
                    break;
            }
        }));
        const [view, hasRealView] = this._createView(viewModel);
        if (hasRealView) {
            this._domElement.appendChild(view.domNode.domNode);
            let keys = Object.keys(this._contentWidgets);
            for (let i = 0, len = keys.length; i < len; i++) {
                const widgetId = keys[i];
                view.addContentWidget(this._contentWidgets[widgetId]);
            }
            keys = Object.keys(this._overlayWidgets);
            for (let i = 0, len = keys.length; i < len; i++) {
                const widgetId = keys[i];
                view.addOverlayWidget(this._overlayWidgets[widgetId]);
            }
            view.render(false, true);
            view.domNode.domNode.setAttribute('data-uri', model.uri.toString());
        }
        this._modelData = new ModelData(model, viewModel, view, hasRealView, listenersToRemove);
    }
    _createView(viewModel) {
        let commandDelegate;
        if (this.isSimpleWidget) {
            commandDelegate = {
                paste: (text, pasteOnNewLine, multicursorText, mode) => {
                    this._paste('keyboard', text, pasteOnNewLine, multicursorText, mode);
                },
                type: (text) => {
                    this._type('keyboard', text);
                },
                compositionType: (text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) => {
                    this._compositionType('keyboard', text, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
                },
                startComposition: () => {
                    this._startComposition();
                },
                endComposition: () => {
                    this._endComposition('keyboard');
                },
                cut: () => {
                    this._cut('keyboard');
                }
            };
        }
        else {
            commandDelegate = {
                paste: (text, pasteOnNewLine, multicursorText, mode) => {
                    const payload = { text, pasteOnNewLine, multicursorText, mode };
                    this._commandService.executeCommand("paste" /* editorCommon.Handler.Paste */, payload);
                },
                type: (text) => {
                    const payload = { text };
                    this._commandService.executeCommand("type" /* editorCommon.Handler.Type */, payload);
                },
                compositionType: (text, replacePrevCharCnt, replaceNextCharCnt, positionDelta) => {
                    // Try if possible to go through the existing `replacePreviousChar` command
                    if (replaceNextCharCnt || positionDelta) {
                        // must be handled through the new command
                        const payload = { text, replacePrevCharCnt, replaceNextCharCnt, positionDelta };
                        this._commandService.executeCommand("compositionType" /* editorCommon.Handler.CompositionType */, payload);
                    }
                    else {
                        const payload = { text, replaceCharCnt: replacePrevCharCnt };
                        this._commandService.executeCommand("replacePreviousChar" /* editorCommon.Handler.ReplacePreviousChar */, payload);
                    }
                },
                startComposition: () => {
                    this._commandService.executeCommand("compositionStart" /* editorCommon.Handler.CompositionStart */, {});
                },
                endComposition: () => {
                    this._commandService.executeCommand("compositionEnd" /* editorCommon.Handler.CompositionEnd */, {});
                },
                cut: () => {
                    this._commandService.executeCommand("cut" /* editorCommon.Handler.Cut */, {});
                }
            };
        }
        const viewUserInputEvents = new ViewUserInputEvents(viewModel.coordinatesConverter);
        viewUserInputEvents.onKeyDown = (e) => this._onKeyDown.fire(e);
        viewUserInputEvents.onKeyUp = (e) => this._onKeyUp.fire(e);
        viewUserInputEvents.onContextMenu = (e) => this._onContextMenu.fire(e);
        viewUserInputEvents.onMouseMove = (e) => this._onMouseMove.fire(e);
        viewUserInputEvents.onMouseLeave = (e) => this._onMouseLeave.fire(e);
        viewUserInputEvents.onMouseDown = (e) => this._onMouseDown.fire(e);
        viewUserInputEvents.onMouseUp = (e) => this._onMouseUp.fire(e);
        viewUserInputEvents.onMouseDrag = (e) => this._onMouseDrag.fire(e);
        viewUserInputEvents.onMouseDrop = (e) => this._onMouseDrop.fire(e);
        viewUserInputEvents.onMouseDropCanceled = (e) => this._onMouseDropCanceled.fire(e);
        viewUserInputEvents.onMouseWheel = (e) => this._onMouseWheel.fire(e);
        const view = new View(commandDelegate, this._configuration, this._themeService.getColorTheme(), viewModel, viewUserInputEvents, this._overflowWidgetsDomNode);
        return [view, true];
    }
    _postDetachModelCleanup(detachedModel) {
        detachedModel === null || detachedModel === void 0 ? void 0 : detachedModel.removeAllDecorationsWithOwnerId(this._id);
    }
    _detachModel() {
        if (!this._modelData) {
            return null;
        }
        const model = this._modelData.model;
        const removeDomNode = this._modelData.hasRealView ? this._modelData.view.domNode.domNode : null;
        this._modelData.dispose();
        this._modelData = null;
        this._domElement.removeAttribute('data-mode-id');
        if (removeDomNode && this._domElement.contains(removeDomNode)) {
            this._domElement.removeChild(removeDomNode);
        }
        if (this._bannerDomNode && this._domElement.contains(this._bannerDomNode)) {
            this._domElement.removeChild(this._bannerDomNode);
        }
        return model;
    }
    _removeDecorationType(key) {
        this._codeEditorService.removeDecorationType(key);
    }
    hasModel() {
        return (this._modelData !== null);
    }
    showDropIndicatorAt(position) {
        const newDecorations = [{
                range: new Range(position.lineNumber, position.column, position.lineNumber, position.column),
                options: CodeEditorWidget.dropIntoEditorDecorationOptions
            }];
        this._dropIntoEditorDecorations.set(newDecorations);
        this.revealPosition(position, 1 /* editorCommon.ScrollType.Immediate */);
    }
    removeDropIndicator() {
        this._dropIntoEditorDecorations.clear();
    }
};
CodeEditorWidget.dropIntoEditorDecorationOptions = ModelDecorationOptions.register({
    description: 'workbench-dnd-target',
    className: 'dnd-target'
});
CodeEditorWidget = codeEditorWidget_decorate([
    codeEditorWidget_param(3, IInstantiationService),
    codeEditorWidget_param(4, ICodeEditorService),
    codeEditorWidget_param(5, ICommandService),
    codeEditorWidget_param(6, IContextKeyService),
    codeEditorWidget_param(7, IThemeService),
    codeEditorWidget_param(8, INotificationService),
    codeEditorWidget_param(9, IAccessibilityService),
    codeEditorWidget_param(10, ILanguageConfigurationService),
    codeEditorWidget_param(11, ILanguageFeaturesService)
], CodeEditorWidget);

class BooleanEventEmitter extends Disposable {
    constructor(_emitterOptions) {
        super();
        this._emitterOptions = _emitterOptions;
        this._onDidChangeToTrue = this._register(new Emitter(this._emitterOptions));
        this.onDidChangeToTrue = this._onDidChangeToTrue.event;
        this._onDidChangeToFalse = this._register(new Emitter(this._emitterOptions));
        this.onDidChangeToFalse = this._onDidChangeToFalse.event;
        this._value = 0 /* BooleanEventValue.NotSet */;
    }
    setValue(_value) {
        const value = (_value ? 2 /* BooleanEventValue.True */ : 1 /* BooleanEventValue.False */);
        if (this._value === value) {
            return;
        }
        this._value = value;
        if (this._value === 2 /* BooleanEventValue.True */) {
            this._onDidChangeToTrue.fire();
        }
        else if (this._value === 1 /* BooleanEventValue.False */) {
            this._onDidChangeToFalse.fire();
        }
    }
}
class EditorContextKeysManager extends Disposable {
    constructor(editor, contextKeyService) {
        super();
        this._editor = editor;
        contextKeyService.createKey('editorId', editor.getId());
        this._editorSimpleInput = EditorContextKeys.editorSimpleInput.bindTo(contextKeyService);
        this._editorFocus = EditorContextKeys.focus.bindTo(contextKeyService);
        this._textInputFocus = EditorContextKeys.textInputFocus.bindTo(contextKeyService);
        this._editorTextFocus = EditorContextKeys.editorTextFocus.bindTo(contextKeyService);
        this._editorTabMovesFocus = EditorContextKeys.tabMovesFocus.bindTo(contextKeyService);
        this._editorReadonly = EditorContextKeys.readOnly.bindTo(contextKeyService);
        this._inDiffEditor = EditorContextKeys.inDiffEditor.bindTo(contextKeyService);
        this._editorColumnSelection = EditorContextKeys.columnSelection.bindTo(contextKeyService);
        this._hasMultipleSelections = EditorContextKeys.hasMultipleSelections.bindTo(contextKeyService);
        this._hasNonEmptySelection = EditorContextKeys.hasNonEmptySelection.bindTo(contextKeyService);
        this._canUndo = EditorContextKeys.canUndo.bindTo(contextKeyService);
        this._canRedo = EditorContextKeys.canRedo.bindTo(contextKeyService);
        this._register(this._editor.onDidChangeConfiguration(() => this._updateFromConfig()));
        this._register(this._editor.onDidChangeCursorSelection(() => this._updateFromSelection()));
        this._register(this._editor.onDidFocusEditorWidget(() => this._updateFromFocus()));
        this._register(this._editor.onDidBlurEditorWidget(() => this._updateFromFocus()));
        this._register(this._editor.onDidFocusEditorText(() => this._updateFromFocus()));
        this._register(this._editor.onDidBlurEditorText(() => this._updateFromFocus()));
        this._register(this._editor.onDidChangeModel(() => this._updateFromModel()));
        this._register(this._editor.onDidChangeConfiguration(() => this._updateFromModel()));
        this._updateFromConfig();
        this._updateFromSelection();
        this._updateFromFocus();
        this._updateFromModel();
        this._editorSimpleInput.set(this._editor.isSimpleWidget);
    }
    _updateFromConfig() {
        const options = this._editor.getOptions();
        this._editorTabMovesFocus.set(options.get(132 /* EditorOption.tabFocusMode */));
        this._editorReadonly.set(options.get(83 /* EditorOption.readOnly */));
        this._inDiffEditor.set(options.get(56 /* EditorOption.inDiffEditor */));
        this._editorColumnSelection.set(options.get(18 /* EditorOption.columnSelection */));
    }
    _updateFromSelection() {
        const selections = this._editor.getSelections();
        if (!selections) {
            this._hasMultipleSelections.reset();
            this._hasNonEmptySelection.reset();
        }
        else {
            this._hasMultipleSelections.set(selections.length > 1);
            this._hasNonEmptySelection.set(selections.some(s => !s.isEmpty()));
        }
    }
    _updateFromFocus() {
        this._editorFocus.set(this._editor.hasWidgetFocus() && !this._editor.isSimpleWidget);
        this._editorTextFocus.set(this._editor.hasTextFocus() && !this._editor.isSimpleWidget);
        this._textInputFocus.set(this._editor.hasTextFocus());
    }
    _updateFromModel() {
        const model = this._editor.getModel();
        this._canUndo.set(Boolean(model && model.canUndo()));
        this._canRedo.set(Boolean(model && model.canRedo()));
    }
}
class EditorModeContext extends Disposable {
    constructor(_editor, _contextKeyService, _languageFeaturesService) {
        super();
        this._editor = _editor;
        this._contextKeyService = _contextKeyService;
        this._languageFeaturesService = _languageFeaturesService;
        this._langId = EditorContextKeys.languageId.bindTo(_contextKeyService);
        this._hasCompletionItemProvider = EditorContextKeys.hasCompletionItemProvider.bindTo(_contextKeyService);
        this._hasCodeActionsProvider = EditorContextKeys.hasCodeActionsProvider.bindTo(_contextKeyService);
        this._hasCodeLensProvider = EditorContextKeys.hasCodeLensProvider.bindTo(_contextKeyService);
        this._hasDefinitionProvider = EditorContextKeys.hasDefinitionProvider.bindTo(_contextKeyService);
        this._hasDeclarationProvider = EditorContextKeys.hasDeclarationProvider.bindTo(_contextKeyService);
        this._hasImplementationProvider = EditorContextKeys.hasImplementationProvider.bindTo(_contextKeyService);
        this._hasTypeDefinitionProvider = EditorContextKeys.hasTypeDefinitionProvider.bindTo(_contextKeyService);
        this._hasHoverProvider = EditorContextKeys.hasHoverProvider.bindTo(_contextKeyService);
        this._hasDocumentHighlightProvider = EditorContextKeys.hasDocumentHighlightProvider.bindTo(_contextKeyService);
        this._hasDocumentSymbolProvider = EditorContextKeys.hasDocumentSymbolProvider.bindTo(_contextKeyService);
        this._hasReferenceProvider = EditorContextKeys.hasReferenceProvider.bindTo(_contextKeyService);
        this._hasRenameProvider = EditorContextKeys.hasRenameProvider.bindTo(_contextKeyService);
        this._hasSignatureHelpProvider = EditorContextKeys.hasSignatureHelpProvider.bindTo(_contextKeyService);
        this._hasInlayHintsProvider = EditorContextKeys.hasInlayHintsProvider.bindTo(_contextKeyService);
        this._hasDocumentFormattingProvider = EditorContextKeys.hasDocumentFormattingProvider.bindTo(_contextKeyService);
        this._hasDocumentSelectionFormattingProvider = EditorContextKeys.hasDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
        this._hasMultipleDocumentFormattingProvider = EditorContextKeys.hasMultipleDocumentFormattingProvider.bindTo(_contextKeyService);
        this._hasMultipleDocumentSelectionFormattingProvider = EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
        this._isInWalkThrough = EditorContextKeys.isInWalkThroughSnippet.bindTo(_contextKeyService);
        const update = () => this._update();
        // update when model/mode changes
        this._register(_editor.onDidChangeModel(update));
        this._register(_editor.onDidChangeModelLanguage(update));
        // update when registries change
        this._register(_languageFeaturesService.completionProvider.onDidChange(update));
        this._register(_languageFeaturesService.codeActionProvider.onDidChange(update));
        this._register(_languageFeaturesService.codeLensProvider.onDidChange(update));
        this._register(_languageFeaturesService.definitionProvider.onDidChange(update));
        this._register(_languageFeaturesService.declarationProvider.onDidChange(update));
        this._register(_languageFeaturesService.implementationProvider.onDidChange(update));
        this._register(_languageFeaturesService.typeDefinitionProvider.onDidChange(update));
        this._register(_languageFeaturesService.hoverProvider.onDidChange(update));
        this._register(_languageFeaturesService.documentHighlightProvider.onDidChange(update));
        this._register(_languageFeaturesService.documentSymbolProvider.onDidChange(update));
        this._register(_languageFeaturesService.referenceProvider.onDidChange(update));
        this._register(_languageFeaturesService.renameProvider.onDidChange(update));
        this._register(_languageFeaturesService.documentFormattingEditProvider.onDidChange(update));
        this._register(_languageFeaturesService.documentRangeFormattingEditProvider.onDidChange(update));
        this._register(_languageFeaturesService.signatureHelpProvider.onDidChange(update));
        this._register(_languageFeaturesService.inlayHintsProvider.onDidChange(update));
        update();
    }
    dispose() {
        super.dispose();
    }
    reset() {
        this._contextKeyService.bufferChangeEvents(() => {
            this._langId.reset();
            this._hasCompletionItemProvider.reset();
            this._hasCodeActionsProvider.reset();
            this._hasCodeLensProvider.reset();
            this._hasDefinitionProvider.reset();
            this._hasDeclarationProvider.reset();
            this._hasImplementationProvider.reset();
            this._hasTypeDefinitionProvider.reset();
            this._hasHoverProvider.reset();
            this._hasDocumentHighlightProvider.reset();
            this._hasDocumentSymbolProvider.reset();
            this._hasReferenceProvider.reset();
            this._hasRenameProvider.reset();
            this._hasDocumentFormattingProvider.reset();
            this._hasDocumentSelectionFormattingProvider.reset();
            this._hasSignatureHelpProvider.reset();
            this._isInWalkThrough.reset();
        });
    }
    _update() {
        const model = this._editor.getModel();
        if (!model) {
            this.reset();
            return;
        }
        this._contextKeyService.bufferChangeEvents(() => {
            this._langId.set(model.getLanguageId());
            this._hasCompletionItemProvider.set(this._languageFeaturesService.completionProvider.has(model));
            this._hasCodeActionsProvider.set(this._languageFeaturesService.codeActionProvider.has(model));
            this._hasCodeLensProvider.set(this._languageFeaturesService.codeLensProvider.has(model));
            this._hasDefinitionProvider.set(this._languageFeaturesService.definitionProvider.has(model));
            this._hasDeclarationProvider.set(this._languageFeaturesService.declarationProvider.has(model));
            this._hasImplementationProvider.set(this._languageFeaturesService.implementationProvider.has(model));
            this._hasTypeDefinitionProvider.set(this._languageFeaturesService.typeDefinitionProvider.has(model));
            this._hasHoverProvider.set(this._languageFeaturesService.hoverProvider.has(model));
            this._hasDocumentHighlightProvider.set(this._languageFeaturesService.documentHighlightProvider.has(model));
            this._hasDocumentSymbolProvider.set(this._languageFeaturesService.documentSymbolProvider.has(model));
            this._hasReferenceProvider.set(this._languageFeaturesService.referenceProvider.has(model));
            this._hasRenameProvider.set(this._languageFeaturesService.renameProvider.has(model));
            this._hasSignatureHelpProvider.set(this._languageFeaturesService.signatureHelpProvider.has(model));
            this._hasInlayHintsProvider.set(this._languageFeaturesService.inlayHintsProvider.has(model));
            this._hasDocumentFormattingProvider.set(this._languageFeaturesService.documentFormattingEditProvider.has(model) || this._languageFeaturesService.documentRangeFormattingEditProvider.has(model));
            this._hasDocumentSelectionFormattingProvider.set(this._languageFeaturesService.documentRangeFormattingEditProvider.has(model));
            this._hasMultipleDocumentFormattingProvider.set(this._languageFeaturesService.documentFormattingEditProvider.all(model).length + this._languageFeaturesService.documentRangeFormattingEditProvider.all(model).length > 1);
            this._hasMultipleDocumentSelectionFormattingProvider.set(this._languageFeaturesService.documentRangeFormattingEditProvider.all(model).length > 1);
            this._isInWalkThrough.set(model.uri.scheme === Schemas.walkThroughSnippet);
        });
    }
}
class CodeEditorWidgetFocusTracker extends Disposable {
    constructor(domElement) {
        super();
        this._onChange = this._register(new Emitter());
        this.onChange = this._onChange.event;
        this._hasFocus = false;
        this._domFocusTracker = this._register(trackFocus(domElement));
        this._register(this._domFocusTracker.onDidFocus(() => {
            this._hasFocus = true;
            this._onChange.fire(undefined);
        }));
        this._register(this._domFocusTracker.onDidBlur(() => {
            this._hasFocus = false;
            this._onChange.fire(undefined);
        }));
    }
    hasFocus() {
        return this._hasFocus;
    }
}
class EditorDecorationsCollection {
    constructor(_editor, decorations) {
        this._editor = _editor;
        this._decorationIds = [];
        this._isChangingDecorations = false;
        if (Array.isArray(decorations) && decorations.length > 0) {
            this.set(decorations);
        }
    }
    get length() {
        return this._decorationIds.length;
    }
    onDidChange(listener, thisArgs, disposables) {
        return this._editor.onDidChangeModelDecorations((e) => {
            if (this._isChangingDecorations) {
                return;
            }
            listener.call(thisArgs, e);
        }, disposables);
    }
    getRange(index) {
        if (!this._editor.hasModel()) {
            return null;
        }
        if (index >= this._decorationIds.length) {
            return null;
        }
        return this._editor.getModel().getDecorationRange(this._decorationIds[index]);
    }
    getRanges() {
        if (!this._editor.hasModel()) {
            return [];
        }
        const model = this._editor.getModel();
        const result = [];
        for (const decorationId of this._decorationIds) {
            const range = model.getDecorationRange(decorationId);
            if (range) {
                result.push(range);
            }
        }
        return result;
    }
    has(decoration) {
        return this._decorationIds.includes(decoration.id);
    }
    clear() {
        if (this._decorationIds.length === 0) {
            // nothing to do
            return;
        }
        this.set([]);
    }
    set(newDecorations) {
        try {
            this._isChangingDecorations = true;
            this._editor.changeDecorations((accessor) => {
                this._decorationIds = accessor.deltaDecorations(this._decorationIds, newDecorations);
            });
        }
        finally {
            this._isChangingDecorations = false;
        }
    }
}
const 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='`);
const 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(color) {
    return squigglyStart + encodeURIComponent(color.toString()) + squigglyEnd;
}
const dotdotdotStart = encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" height="3" width="12"><g fill="`);
const 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(color) {
    return dotdotdotStart + encodeURIComponent(color.toString()) + dotdotdotEnd;
}
registerThemingParticipant((theme, collector) => {
    const errorBorderColor = theme.getColor(editorErrorBorder);
    if (errorBorderColor) {
        collector.addRule(`.monaco-editor .${"squiggly-error" /* ClassName.EditorErrorDecoration */} { border-bottom: 4px double ${errorBorderColor}; }`);
    }
    const errorForeground = theme.getColor(editorErrorForeground);
    if (errorForeground) {
        collector.addRule(`.monaco-editor .${"squiggly-error" /* ClassName.EditorErrorDecoration */} { background: url("data:image/svg+xml,${getSquigglySVGData(errorForeground)}") repeat-x bottom left; }`);
    }
    const errorBackground = theme.getColor(editorErrorBackground);
    if (errorBackground) {
        collector.addRule(`.monaco-editor .${"squiggly-error" /* ClassName.EditorErrorDecoration */}::before { display: block; content: ''; width: 100%; height: 100%; background: ${errorBackground}; }`);
    }
    const warningBorderColor = theme.getColor(editorWarningBorder);
    if (warningBorderColor) {
        collector.addRule(`.monaco-editor .${"squiggly-warning" /* ClassName.EditorWarningDecoration */} { border-bottom: 4px double ${warningBorderColor}; }`);
    }
    const warningForeground = theme.getColor(editorWarningForeground);
    if (warningForeground) {
        collector.addRule(`.monaco-editor .${"squiggly-warning" /* ClassName.EditorWarningDecoration */} { background: url("data:image/svg+xml,${getSquigglySVGData(warningForeground)}") repeat-x bottom left; }`);
    }
    const warningBackground = theme.getColor(editorWarningBackground);
    if (warningBackground) {
        collector.addRule(`.monaco-editor .${"squiggly-warning" /* ClassName.EditorWarningDecoration */}::before { display: block; content: ''; width: 100%; height: 100%; background: ${warningBackground}; }`);
    }
    const infoBorderColor = theme.getColor(editorInfoBorder);
    if (infoBorderColor) {
        collector.addRule(`.monaco-editor .${"squiggly-info" /* ClassName.EditorInfoDecoration */} { border-bottom: 4px double ${infoBorderColor}; }`);
    }
    const infoForeground = theme.getColor(editorInfoForeground);
    if (infoForeground) {
        collector.addRule(`.monaco-editor .${"squiggly-info" /* ClassName.EditorInfoDecoration */} { background: url("data:image/svg+xml,${getSquigglySVGData(infoForeground)}") repeat-x bottom left; }`);
    }
    const infoBackground = theme.getColor(editorInfoBackground);
    if (infoBackground) {
        collector.addRule(`.monaco-editor .${"squiggly-info" /* ClassName.EditorInfoDecoration */}::before { display: block; content: ''; width: 100%; height: 100%; background: ${infoBackground}; }`);
    }
    const hintBorderColor = theme.getColor(editorHintBorder);
    if (hintBorderColor) {
        collector.addRule(`.monaco-editor .${"squiggly-hint" /* ClassName.EditorHintDecoration */} { border-bottom: 2px dotted ${hintBorderColor}; }`);
    }
    const hintForeground = theme.getColor(editorHintForeground);
    if (hintForeground) {
        collector.addRule(`.monaco-editor .${"squiggly-hint" /* ClassName.EditorHintDecoration */} { background: url("data:image/svg+xml,${getDotDotDotSVGData(hintForeground)}") no-repeat bottom left; }`);
    }
    const unnecessaryForeground = theme.getColor(editorUnnecessaryCodeOpacity);
    if (unnecessaryForeground) {
        collector.addRule(`.monaco-editor.showUnused .${"squiggly-inline-unnecessary" /* ClassName.EditorUnnecessaryInlineDecoration */} { opacity: ${unnecessaryForeground.rgba.a}; }`);
    }
    const unnecessaryBorder = theme.getColor(editorUnnecessaryCodeBorder);
    if (unnecessaryBorder) {
        collector.addRule(`.monaco-editor.showUnused .${"squiggly-unnecessary" /* ClassName.EditorUnnecessaryDecoration */} { border-bottom: 2px dashed ${unnecessaryBorder}; }`);
    }
    const deprecatedForeground = theme.getColor(editorForeground) || 'inherit';
    collector.addRule(`.monaco-editor.showDeprecated .${"squiggly-inline-deprecated" /* ClassName.EditorDeprecatedInlineDecoration */} { text-decoration: line-through; text-decoration-color: ${deprecatedForeground}}`);
});

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/widget/embeddedCodeEditorWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var embeddedCodeEditorWidget_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var embeddedCodeEditorWidget_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};











let EmbeddedCodeEditorWidget = class EmbeddedCodeEditorWidget extends CodeEditorWidget {
    constructor(domElement, options, parentEditor, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
        super(domElement, Object.assign(Object.assign({}, parentEditor.getRawOptions()), { overflowWidgetsDomNode: parentEditor.getOverflowWidgetsDomNode() }), {}, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
        this._parentEditor = parentEditor;
        this._overwriteOptions = options;
        // Overwrite parent's options
        super.updateOptions(this._overwriteOptions);
        this._register(parentEditor.onDidChangeConfiguration((e) => this._onParentConfigurationChanged(e)));
    }
    getParentEditor() {
        return this._parentEditor;
    }
    _onParentConfigurationChanged(e) {
        super.updateOptions(this._parentEditor.getRawOptions());
        super.updateOptions(this._overwriteOptions);
    }
    updateOptions(newOptions) {
        mixin(this._overwriteOptions, newOptions, true);
        super.updateOptions(this._overwriteOptions);
    }
};
EmbeddedCodeEditorWidget = embeddedCodeEditorWidget_decorate([
    embeddedCodeEditorWidget_param(3, IInstantiationService),
    embeddedCodeEditorWidget_param(4, ICodeEditorService),
    embeddedCodeEditorWidget_param(5, ICommandService),
    embeddedCodeEditorWidget_param(6, IContextKeyService),
    embeddedCodeEditorWidget_param(7, IThemeService),
    embeddedCodeEditorWidget_param(8, INotificationService),
    embeddedCodeEditorWidget_param(9, IAccessibilityService),
    embeddedCodeEditorWidget_param(10, ILanguageConfigurationService),
    embeddedCodeEditorWidget_param(11, ILanguageFeaturesService)
], EmbeddedCodeEditorWidget);


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/sash/sash.css
var sash = __webpack_require__(4851);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/sash/sash.css

      
      
      
      
      
      
      
      
      

var sash_options = {};

sash_options.styleTagTransform = (styleTagTransform_default());
sash_options.setAttributes = (setAttributesWithoutAttributes_default());

      sash_options.insert = insertBySelector_default().bind(null, "head");
    
sash_options.domAPI = (styleDomAPI_default());
sash_options.insertStyleElement = (insertStyleElement_default());

var sash_update = injectStylesIntoStyleTag_default()(sash/* default */.A, sash_options);




       /* harmony default export */ const sash_sash = (sash/* default */.A && sash/* default */.A.locals ? sash/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/sash/sash.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var sash_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};









/**
 * Allow the sashes to be visible at runtime.
 * @remark Use for development purposes only.
 */
const DEBUG = false;
var OrthogonalEdge;
(function (OrthogonalEdge) {
    OrthogonalEdge["North"] = "north";
    OrthogonalEdge["South"] = "south";
    OrthogonalEdge["East"] = "east";
    OrthogonalEdge["West"] = "west";
})(OrthogonalEdge || (OrthogonalEdge = {}));
let globalSize = 4;
const onDidChangeGlobalSize = new Emitter();
let globalHoverDelay = 300;
const onDidChangeHoverDelay = new Emitter();
class MouseEventFactory {
    constructor() {
        this.disposables = new DisposableStore();
    }
    get onPointerMove() {
        return this.disposables.add(new DomEmitter(window, 'mousemove')).event;
    }
    get onPointerUp() {
        return this.disposables.add(new DomEmitter(window, 'mouseup')).event;
    }
    dispose() {
        this.disposables.dispose();
    }
}
sash_decorate([
    memoize
], MouseEventFactory.prototype, "onPointerMove", null);
sash_decorate([
    memoize
], MouseEventFactory.prototype, "onPointerUp", null);
class GestureEventFactory {
    constructor(el) {
        this.el = el;
        this.disposables = new DisposableStore();
    }
    get onPointerMove() {
        return this.disposables.add(new DomEmitter(this.el, touch_EventType.Change)).event;
    }
    get onPointerUp() {
        return this.disposables.add(new DomEmitter(this.el, touch_EventType.End)).event;
    }
    dispose() {
        this.disposables.dispose();
    }
}
sash_decorate([
    memoize
], GestureEventFactory.prototype, "onPointerMove", null);
sash_decorate([
    memoize
], GestureEventFactory.prototype, "onPointerUp", null);
class OrthogonalPointerEventFactory {
    constructor(factory) {
        this.factory = factory;
    }
    get onPointerMove() {
        return this.factory.onPointerMove;
    }
    get onPointerUp() {
        return this.factory.onPointerUp;
    }
    dispose() {
        // noop
    }
}
sash_decorate([
    memoize
], OrthogonalPointerEventFactory.prototype, "onPointerMove", null);
sash_decorate([
    memoize
], OrthogonalPointerEventFactory.prototype, "onPointerUp", null);
const PointerEventsDisabledCssClass = 'pointer-events-disabled';
/**
 * The {@link Sash} is the UI component which allows the user to resize other
 * components. It's usually an invisible horizontal or vertical line which, when
 * hovered, becomes highlighted and can be dragged along the perpendicular dimension
 * to its direction.
 *
 * Features:
 * - Touch event handling
 * - Corner sash support
 * - Hover with different mouse cursor support
 * - Configurable hover size
 * - Linked sash support, for 2x2 corner sashes
 */
class Sash extends Disposable {
    constructor(container, layoutProvider, options) {
        super();
        this.hoverDelay = globalHoverDelay;
        this.hoverDelayer = this._register(new Delayer(this.hoverDelay));
        this._state = 3 /* SashState.Enabled */;
        this.onDidEnablementChange = this._register(new Emitter());
        this._onDidStart = this._register(new Emitter());
        this._onDidChange = this._register(new Emitter());
        this._onDidReset = this._register(new Emitter());
        this._onDidEnd = this._register(new Emitter());
        this.orthogonalStartSashDisposables = this._register(new DisposableStore());
        this.orthogonalStartDragHandleDisposables = this._register(new DisposableStore());
        this.orthogonalEndSashDisposables = this._register(new DisposableStore());
        this.orthogonalEndDragHandleDisposables = this._register(new DisposableStore());
        /**
         * An event which fires whenever the user starts dragging this sash.
         */
        this.onDidStart = this._onDidStart.event;
        /**
         * An event which fires whenever the user moves the mouse while
         * dragging this sash.
         */
        this.onDidChange = this._onDidChange.event;
        /**
         * An event which fires whenever the user double clicks this sash.
         */
        this.onDidReset = this._onDidReset.event;
        /**
         * An event which fires whenever the user stops dragging this sash.
         */
        this.onDidEnd = this._onDidEnd.event;
        /**
         * A linked sash will be forwarded the same user interactions and events
         * so it moves exactly the same way as this sash.
         *
         * Useful in 2x2 grids. Not meant for widespread usage.
         */
        this.linkedSash = undefined;
        this.el = append(container, dom_$('.monaco-sash'));
        if (options.orthogonalEdge) {
            this.el.classList.add(`orthogonal-edge-${options.orthogonalEdge}`);
        }
        if (isMacintosh) {
            this.el.classList.add('mac');
        }
        const onMouseDown = this._register(new DomEmitter(this.el, 'mousedown')).event;
        this._register(onMouseDown(e => this.onPointerStart(e, new MouseEventFactory()), this));
        const onMouseDoubleClick = this._register(new DomEmitter(this.el, 'dblclick')).event;
        this._register(onMouseDoubleClick(this.onPointerDoublePress, this));
        const onMouseEnter = this._register(new DomEmitter(this.el, 'mouseenter')).event;
        this._register(onMouseEnter(() => Sash.onMouseEnter(this)));
        const onMouseLeave = this._register(new DomEmitter(this.el, 'mouseleave')).event;
        this._register(onMouseLeave(() => Sash.onMouseLeave(this)));
        this._register(Gesture.addTarget(this.el));
        const onTouchStart = Event.map(this._register(new DomEmitter(this.el, touch_EventType.Start)).event, e => { var _a; return (Object.assign(Object.assign({}, e), { target: (_a = e.initialTarget) !== null && _a !== void 0 ? _a : null })); });
        this._register(onTouchStart(e => this.onPointerStart(e, new GestureEventFactory(this.el)), this));
        const onTap = this._register(new DomEmitter(this.el, touch_EventType.Tap)).event;
        const onDoubleTap = Event.map(Event.filter(Event.debounce(onTap, (res, event) => { var _a; return ({ event, count: ((_a = res === null || res === void 0 ? void 0 : res.count) !== null && _a !== void 0 ? _a : 0) + 1 }); }, 250), ({ count }) => count === 2), ({ event }) => { var _a; return (Object.assign(Object.assign({}, event), { target: (_a = event.initialTarget) !== null && _a !== void 0 ? _a : null })); });
        this._register(onDoubleTap(this.onPointerDoublePress, this));
        if (typeof options.size === 'number') {
            this.size = options.size;
            if (options.orientation === 0 /* Orientation.VERTICAL */) {
                this.el.style.width = `${this.size}px`;
            }
            else {
                this.el.style.height = `${this.size}px`;
            }
        }
        else {
            this.size = globalSize;
            this._register(onDidChangeGlobalSize.event(size => {
                this.size = size;
                this.layout();
            }));
        }
        this._register(onDidChangeHoverDelay.event(delay => this.hoverDelay = delay));
        this.layoutProvider = layoutProvider;
        this.orthogonalStartSash = options.orthogonalStartSash;
        this.orthogonalEndSash = options.orthogonalEndSash;
        this.orientation = options.orientation || 0 /* Orientation.VERTICAL */;
        if (this.orientation === 1 /* Orientation.HORIZONTAL */) {
            this.el.classList.add('horizontal');
            this.el.classList.remove('vertical');
        }
        else {
            this.el.classList.remove('horizontal');
            this.el.classList.add('vertical');
        }
        this.el.classList.toggle('debug', DEBUG);
        this.layout();
    }
    get state() { return this._state; }
    get orthogonalStartSash() { return this._orthogonalStartSash; }
    get orthogonalEndSash() { return this._orthogonalEndSash; }
    /**
     * 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._state === state) {
            return;
        }
        this.el.classList.toggle('disabled', state === 0 /* SashState.Disabled */);
        this.el.classList.toggle('minimum', state === 1 /* SashState.AtMinimum */);
        this.el.classList.toggle('maximum', state === 2 /* SashState.AtMaximum */);
        this._state = state;
        this.onDidEnablementChange.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) {
        this.orthogonalStartDragHandleDisposables.clear();
        this.orthogonalStartSashDisposables.clear();
        if (sash) {
            const onChange = (state) => {
                this.orthogonalStartDragHandleDisposables.clear();
                if (state !== 0 /* SashState.Disabled */) {
                    this._orthogonalStartDragHandle = append(this.el, dom_$('.orthogonal-drag-handle.start'));
                    this.orthogonalStartDragHandleDisposables.add(toDisposable(() => this._orthogonalStartDragHandle.remove()));
                    this.orthogonalStartDragHandleDisposables.add(new DomEmitter(this._orthogonalStartDragHandle, 'mouseenter')).event(() => Sash.onMouseEnter(sash), undefined, this.orthogonalStartDragHandleDisposables);
                    this.orthogonalStartDragHandleDisposables.add(new DomEmitter(this._orthogonalStartDragHandle, 'mouseleave')).event(() => Sash.onMouseLeave(sash), undefined, this.orthogonalStartDragHandleDisposables);
                }
            };
            this.orthogonalStartSashDisposables.add(sash.onDidEnablementChange.event(onChange, this));
            onChange(sash.state);
        }
        this._orthogonalStartSash = 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) {
        this.orthogonalEndDragHandleDisposables.clear();
        this.orthogonalEndSashDisposables.clear();
        if (sash) {
            const onChange = (state) => {
                this.orthogonalEndDragHandleDisposables.clear();
                if (state !== 0 /* SashState.Disabled */) {
                    this._orthogonalEndDragHandle = append(this.el, dom_$('.orthogonal-drag-handle.end'));
                    this.orthogonalEndDragHandleDisposables.add(toDisposable(() => this._orthogonalEndDragHandle.remove()));
                    this.orthogonalEndDragHandleDisposables.add(new DomEmitter(this._orthogonalEndDragHandle, 'mouseenter')).event(() => Sash.onMouseEnter(sash), undefined, this.orthogonalEndDragHandleDisposables);
                    this.orthogonalEndDragHandleDisposables.add(new DomEmitter(this._orthogonalEndDragHandle, 'mouseleave')).event(() => Sash.onMouseLeave(sash), undefined, this.orthogonalEndDragHandleDisposables);
                }
            };
            this.orthogonalEndSashDisposables.add(sash.onDidEnablementChange.event(onChange, this));
            onChange(sash.state);
        }
        this._orthogonalEndSash = sash;
    }
    onPointerStart(event, pointerEventFactory) {
        EventHelper.stop(event);
        let isMultisashResize = false;
        if (!event.__orthogonalSashEvent) {
            const orthogonalSash = this.getOrthogonalSash(event);
            if (orthogonalSash) {
                isMultisashResize = true;
                event.__orthogonalSashEvent = true;
                orthogonalSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory));
            }
        }
        if (this.linkedSash && !event.__linkedSashEvent) {
            event.__linkedSashEvent = true;
            this.linkedSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory));
        }
        if (!this.state) {
            return;
        }
        const iframes = getElementsByTagName('iframe');
        for (const iframe of iframes) {
            iframe.classList.add(PointerEventsDisabledCssClass); // disable mouse events on iframes as long as we drag the sash
        }
        const startX = event.pageX;
        const startY = event.pageY;
        const altKey = event.altKey;
        const startEvent = { startX, currentX: startX, startY, currentY: startY, altKey };
        this.el.classList.add('active');
        this._onDidStart.fire(startEvent);
        // fix https://github.com/microsoft/vscode/issues/21675
        const style = createStyleSheet(this.el);
        const updateStyle = () => {
            let cursor = '';
            if (isMultisashResize) {
                cursor = 'all-scroll';
            }
            else if (this.orientation === 1 /* Orientation.HORIZONTAL */) {
                if (this.state === 1 /* SashState.AtMinimum */) {
                    cursor = 's-resize';
                }
                else if (this.state === 2 /* SashState.AtMaximum */) {
                    cursor = 'n-resize';
                }
                else {
                    cursor = isMacintosh ? 'row-resize' : 'ns-resize';
                }
            }
            else {
                if (this.state === 1 /* SashState.AtMinimum */) {
                    cursor = 'e-resize';
                }
                else if (this.state === 2 /* SashState.AtMaximum */) {
                    cursor = 'w-resize';
                }
                else {
                    cursor = isMacintosh ? 'col-resize' : 'ew-resize';
                }
            }
            style.textContent = `* { cursor: ${cursor} !important; }`;
        };
        const disposables = new DisposableStore();
        updateStyle();
        if (!isMultisashResize) {
            this.onDidEnablementChange.event(updateStyle, null, disposables);
        }
        const onPointerMove = (e) => {
            EventHelper.stop(e, false);
            const event = { startX, currentX: e.pageX, startY, currentY: e.pageY, altKey };
            this._onDidChange.fire(event);
        };
        const onPointerUp = (e) => {
            EventHelper.stop(e, false);
            this.el.removeChild(style);
            this.el.classList.remove('active');
            this._onDidEnd.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);
    }
    onPointerDoublePress(e) {
        const orthogonalSash = this.getOrthogonalSash(e);
        if (orthogonalSash) {
            orthogonalSash._onDidReset.fire();
        }
        if (this.linkedSash) {
            this.linkedSash._onDidReset.fire();
        }
        this._onDidReset.fire();
    }
    static onMouseEnter(sash, fromLinkedSash = false) {
        if (sash.el.classList.contains('active')) {
            sash.hoverDelayer.cancel();
            sash.el.classList.add('hover');
        }
        else {
            sash.hoverDelayer.trigger(() => sash.el.classList.add('hover'), sash.hoverDelay).then(undefined, () => { });
        }
        if (!fromLinkedSash && sash.linkedSash) {
            Sash.onMouseEnter(sash.linkedSash, true);
        }
    }
    static onMouseLeave(sash, fromLinkedSash = false) {
        sash.hoverDelayer.cancel();
        sash.el.classList.remove('hover');
        if (!fromLinkedSash && sash.linkedSash) {
            Sash.onMouseLeave(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() {
        Sash.onMouseLeave(this);
    }
    /**
     * Layout the sash. The sash will size and position itself
     * based on its provided {@link ISashLayoutProvider layout provider}.
     */
    layout() {
        if (this.orientation === 0 /* Orientation.VERTICAL */) {
            const verticalProvider = this.layoutProvider;
            this.el.style.left = verticalProvider.getVerticalSashLeft(this) - (this.size / 2) + 'px';
            if (verticalProvider.getVerticalSashTop) {
                this.el.style.top = verticalProvider.getVerticalSashTop(this) + 'px';
            }
            if (verticalProvider.getVerticalSashHeight) {
                this.el.style.height = verticalProvider.getVerticalSashHeight(this) + 'px';
            }
        }
        else {
            const horizontalProvider = this.layoutProvider;
            this.el.style.top = horizontalProvider.getHorizontalSashTop(this) - (this.size / 2) + 'px';
            if (horizontalProvider.getHorizontalSashLeft) {
                this.el.style.left = horizontalProvider.getHorizontalSashLeft(this) + 'px';
            }
            if (horizontalProvider.getHorizontalSashWidth) {
                this.el.style.width = horizontalProvider.getHorizontalSashWidth(this) + 'px';
            }
        }
    }
    getOrthogonalSash(e) {
        if (!e.target || !(e.target instanceof HTMLElement)) {
            return undefined;
        }
        if (e.target.classList.contains('orthogonal-drag-handle')) {
            return e.target.classList.contains('start') ? this.orthogonalStartSash : this.orthogonalEndSash;
        }
        return undefined;
    }
    dispose() {
        super.dispose();
        this.el.remove();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/idGenerator.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class IdGenerator {
    constructor(prefix) {
        this._prefix = prefix;
        this._lastId = 0;
    }
    nextId() {
        return this._prefix + (++this._lastId);
    }
}
const defaultGenerator = new IdGenerator('id#');

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/zoneWidget/browser/zoneWidget.css
var zoneWidget = __webpack_require__(63618);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/zoneWidget/browser/zoneWidget.css

      
      
      
      
      
      
      
      
      

var zoneWidget_options = {};

zoneWidget_options.styleTagTransform = (styleTagTransform_default());
zoneWidget_options.setAttributes = (setAttributesWithoutAttributes_default());

      zoneWidget_options.insert = insertBySelector_default().bind(null, "head");
    
zoneWidget_options.domAPI = (styleDomAPI_default());
zoneWidget_options.insertStyleElement = (insertStyleElement_default());

var zoneWidget_update = injectStylesIntoStyleTag_default()(zoneWidget/* default */.A, zoneWidget_options);




       /* harmony default export */ const browser_zoneWidget = (zoneWidget/* default */.A && zoneWidget/* default */.A.locals ? zoneWidget/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/zoneWidget/browser/zoneWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









const defaultColor = new Color(new RGBA(0, 122, 204));
const defaultOptions = {
    showArrow: true,
    showFrame: true,
    className: '',
    frameColor: defaultColor,
    arrowColor: defaultColor,
    keepEditorSelection: false
};
const WIDGET_ID = 'vs.editor.contrib.zoneWidget';
class ViewZoneDelegate {
    constructor(domNode, afterLineNumber, afterColumn, heightInLines, onDomNodeTop, onComputedHeight) {
        this.id = ''; // A valid zone id should be greater than 0
        this.domNode = domNode;
        this.afterLineNumber = afterLineNumber;
        this.afterColumn = afterColumn;
        this.heightInLines = heightInLines;
        this._onDomNodeTop = onDomNodeTop;
        this._onComputedHeight = onComputedHeight;
    }
    onDomNodeTop(top) {
        this._onDomNodeTop(top);
    }
    onComputedHeight(height) {
        this._onComputedHeight(height);
    }
}
class OverlayWidgetDelegate {
    constructor(id, domNode) {
        this._id = id;
        this._domNode = domNode;
    }
    getId() {
        return this._id;
    }
    getDomNode() {
        return this._domNode;
    }
    getPosition() {
        return null;
    }
}
class Arrow {
    constructor(_editor) {
        this._editor = _editor;
        this._ruleName = Arrow._IdGenerator.nextId();
        this._decorations = this._editor.createDecorationsCollection();
        this._color = null;
        this._height = -1;
    }
    dispose() {
        this.hide();
        removeCSSRulesContainingSelector(this._ruleName);
    }
    set color(value) {
        if (this._color !== value) {
            this._color = value;
            this._updateStyle();
        }
    }
    set height(value) {
        if (this._height !== value) {
            this._height = value;
            this._updateStyle();
        }
    }
    _updateStyle() {
        removeCSSRulesContainingSelector(this._ruleName);
        createCSSRule(`.monaco-editor ${this._ruleName}`, `border-style: solid; border-color: transparent; border-bottom-color: ${this._color}; border-width: ${this._height}px; bottom: -${this._height}px; margin-left: -${this._height}px; `);
    }
    show(where) {
        if (where.column === 1) {
            // the arrow isn't pretty at column 1 and we need to push it out a little
            where = { lineNumber: where.lineNumber, column: 2 };
        }
        this._decorations.set([{
                range: Range.fromPositions(where),
                options: {
                    description: 'zone-widget-arrow',
                    className: this._ruleName,
                    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
                }
            }]);
    }
    hide() {
        this._decorations.clear();
    }
}
Arrow._IdGenerator = new IdGenerator('.arrow-decoration-');
class ZoneWidget {
    constructor(editor, options = {}) {
        this._arrow = null;
        this._overlayWidget = null;
        this._resizeSash = null;
        this._viewZone = null;
        this._disposables = new DisposableStore();
        this.container = null;
        this._isShowing = false;
        this.editor = editor;
        this._positionMarkerId = this.editor.createDecorationsCollection();
        this.options = deepClone(options);
        mixin(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._disposables.add(this.editor.onDidLayoutChange((info) => {
            const width = this._getWidth(info);
            this.domNode.style.width = width + 'px';
            this.domNode.style.left = this._getLeft(info) + 'px';
            this._onWidth(width);
        }));
    }
    dispose() {
        if (this._overlayWidget) {
            this.editor.removeOverlayWidget(this._overlayWidget);
            this._overlayWidget = null;
        }
        if (this._viewZone) {
            this.editor.changeViewZones(accessor => {
                if (this._viewZone) {
                    accessor.removeZone(this._viewZone.id);
                }
                this._viewZone = null;
            });
        }
        this._positionMarkerId.clear();
        this._disposables.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._arrow = new Arrow(this.editor);
            this._disposables.add(this._arrow);
        }
        this._fillContainer(this.container);
        this._initSash();
        this._applyStyles();
    }
    style(styles) {
        if (styles.frameColor) {
            this.options.frameColor = styles.frameColor;
        }
        if (styles.arrowColor) {
            this.options.arrowColor = styles.arrowColor;
        }
        this._applyStyles();
    }
    _applyStyles() {
        if (this.container && this.options.frameColor) {
            const frameColor = this.options.frameColor.toString();
            this.container.style.borderTopColor = frameColor;
            this.container.style.borderBottomColor = frameColor;
        }
        if (this._arrow && this.options.arrowColor) {
            const arrowColor = this.options.arrowColor.toString();
            this._arrow.color = arrowColor;
        }
    }
    _getWidth(info) {
        return info.width - info.minimap.minimapWidth - info.verticalScrollbarWidth;
    }
    _getLeft(info) {
        // If minimap is to the left, we move beyond it
        if (info.minimap.minimapWidth > 0 && info.minimap.minimapLeft === 0) {
            return info.minimap.minimapWidth;
        }
        return 0;
    }
    _onViewZoneTop(top) {
        this.domNode.style.top = top + 'px';
    }
    _onViewZoneHeight(height) {
        this.domNode.style.height = `${height}px`;
        if (this.container) {
            const containerHeight = height - this._decoratingElementsHeight();
            this.container.style.height = `${containerHeight}px`;
            const layoutInfo = this.editor.getLayoutInfo();
            this._doLayout(containerHeight, this._getWidth(layoutInfo));
        }
        if (this._resizeSash) {
            this._resizeSash.layout();
        }
    }
    get position() {
        const range = this._positionMarkerId.getRange(0);
        if (!range) {
            return undefined;
        }
        return range.getStartPosition();
    }
    show(rangeOrPos, heightInLines) {
        const range = Range.isIRange(rangeOrPos) ? Range.lift(rangeOrPos) : Range.fromPositions(rangeOrPos);
        this._isShowing = true;
        this._showImpl(range, heightInLines);
        this._isShowing = false;
        this._positionMarkerId.set([{ range, options: ModelDecorationOptions.EMPTY }]);
    }
    hide() {
        if (this._viewZone) {
            this.editor.changeViewZones(accessor => {
                if (this._viewZone) {
                    accessor.removeZone(this._viewZone.id);
                }
            });
            this._viewZone = null;
        }
        if (this._overlayWidget) {
            this.editor.removeOverlayWidget(this._overlayWidget);
            this._overlayWidget = null;
        }
        if (this._arrow) {
            this._arrow.hide();
        }
    }
    _decoratingElementsHeight() {
        const lineHeight = this.editor.getOption(61 /* 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;
    }
    _showImpl(where, heightInLines) {
        const position = where.getStartPosition();
        const layoutInfo = this.editor.getLayoutInfo();
        const width = this._getWidth(layoutInfo);
        this.domNode.style.width = `${width}px`;
        this.domNode.style.left = this._getLeft(layoutInfo) + 'px';
        // Render the widget as zone (rendering) and widget (lifecycle)
        const viewZoneDomNode = document.createElement('div');
        viewZoneDomNode.style.overflow = 'hidden';
        const lineHeight = this.editor.getOption(61 /* EditorOption.lineHeight */);
        // adjust heightInLines to viewport
        const maxHeightInLines = Math.max(12, (this.editor.getLayoutInfo().height / lineHeight) * 0.8);
        heightInLines = Math.min(heightInLines, maxHeightInLines);
        let arrowHeight = 0;
        let frameThickness = 0;
        // Render the arrow one 1/3 of an editor line height
        if (this._arrow && this.options.showArrow) {
            arrowHeight = Math.round(lineHeight / 3);
            this._arrow.height = arrowHeight;
            this._arrow.show(position);
        }
        // Render the frame as 1/9 of an editor line height
        if (this.options.showFrame) {
            frameThickness = Math.round(lineHeight / 9);
        }
        // insert zone widget
        this.editor.changeViewZones((accessor) => {
            if (this._viewZone) {
                accessor.removeZone(this._viewZone.id);
            }
            if (this._overlayWidget) {
                this.editor.removeOverlayWidget(this._overlayWidget);
                this._overlayWidget = null;
            }
            this.domNode.style.top = '-1000px';
            this._viewZone = new ViewZoneDelegate(viewZoneDomNode, position.lineNumber, position.column, heightInLines, (top) => this._onViewZoneTop(top), (height) => this._onViewZoneHeight(height));
            this._viewZone.id = accessor.addZone(this._viewZone);
            this._overlayWidget = new OverlayWidgetDelegate(WIDGET_ID + this._viewZone.id, this.domNode);
            this.editor.addOverlayWidget(this._overlayWidget);
        });
        if (this.container && this.options.showFrame) {
            const width = this.options.frameWidth ? this.options.frameWidth : frameThickness;
            this.container.style.borderTopWidth = width + 'px';
            this.container.style.borderBottomWidth = width + 'px';
        }
        const containerHeight = heightInLines * lineHeight - this._decoratingElementsHeight();
        if (this.container) {
            this.container.style.top = arrowHeight + 'px';
            this.container.style.height = containerHeight + 'px';
            this.container.style.overflow = 'hidden';
        }
        this._doLayout(containerHeight, width);
        if (!this.options.keepEditorSelection) {
            this.editor.setSelection(where);
        }
        const model = this.editor.getModel();
        if (model) {
            const revealLine = where.endLineNumber + 1;
            if (revealLine <= model.getLineCount()) {
                // reveal line below the zone widget
                this.revealLine(revealLine, false);
            }
            else {
                // reveal last line atop
                this.revealLine(model.getLineCount(), true);
            }
        }
    }
    revealLine(lineNumber, isLastLine) {
        if (isLastLine) {
            this.editor.revealLineInCenter(lineNumber, 0 /* ScrollType.Smooth */);
        }
        else {
            this.editor.revealLine(lineNumber, 0 /* ScrollType.Smooth */);
        }
    }
    setCssClass(className, classToReplace) {
        if (!this.container) {
            return;
        }
        if (classToReplace) {
            this.container.classList.remove(classToReplace);
        }
        this.container.classList.add(className);
    }
    _onWidth(widthInPixel) {
        // implement in subclass
    }
    _doLayout(heightInPixel, widthInPixel) {
        // implement in subclass
    }
    _relayout(newHeightInLines) {
        if (this._viewZone && this._viewZone.heightInLines !== newHeightInLines) {
            this.editor.changeViewZones(accessor => {
                if (this._viewZone) {
                    this._viewZone.heightInLines = newHeightInLines;
                    accessor.layoutZone(this._viewZone.id);
                }
            });
        }
    }
    // --- sash
    _initSash() {
        if (this._resizeSash) {
            return;
        }
        this._resizeSash = this._disposables.add(new Sash(this.domNode, this, { orientation: 1 /* Orientation.HORIZONTAL */ }));
        if (!this.options.isResizeable) {
            this._resizeSash.state = 0 /* SashState.Disabled */;
        }
        let data;
        this._disposables.add(this._resizeSash.onDidStart((e) => {
            if (this._viewZone) {
                data = {
                    startY: e.startY,
                    heightInLines: this._viewZone.heightInLines,
                };
            }
        }));
        this._disposables.add(this._resizeSash.onDidEnd(() => {
            data = undefined;
        }));
        this._disposables.add(this._resizeSash.onDidChange((evt) => {
            if (data) {
                const lineDelta = (evt.currentY - data.startY) / this.editor.getOption(61 /* EditorOption.lineHeight */);
                const roundedLineDelta = lineDelta < 0 ? Math.ceil(lineDelta) : Math.floor(lineDelta);
                const newHeightInLines = data.heightInLines + roundedLineDelta;
                if (newHeightInLines > 5 && newHeightInLines < 35) {
                    this._relayout(newHeightInLines);
                }
            }
        }));
    }
    getHorizontalSashLeft() {
        return 0;
    }
    getHorizontalSashTop() {
        return (this.domNode.style.height === null ? 0 : parseInt(this.domNode.style.height)) - (this._decoratingElementsHeight() / 2);
    }
    getHorizontalSashWidth() {
        const layoutInfo = this.editor.getLayoutInfo();
        return layoutInfo.width - layoutInfo.minimap.minimapWidth;
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/dropdown/dropdown.css
var dropdown = __webpack_require__(17951);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/dropdown/dropdown.css

      
      
      
      
      
      
      
      
      

var dropdown_options = {};

dropdown_options.styleTagTransform = (styleTagTransform_default());
dropdown_options.setAttributes = (setAttributesWithoutAttributes_default());

      dropdown_options.insert = insertBySelector_default().bind(null, "head");
    
dropdown_options.domAPI = (styleDomAPI_default());
dropdown_options.insertStyleElement = (insertStyleElement_default());

var dropdown_update = injectStylesIntoStyleTag_default()(dropdown/* default */.A, dropdown_options);




       /* harmony default export */ const dropdown_dropdown = (dropdown/* default */.A && dropdown/* default */.A.locals ? dropdown/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/dropdown/dropdown.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class BaseDropdown extends ActionRunner {
    constructor(container, options) {
        super();
        this._onDidChangeVisibility = this._register(new Emitter());
        this.onDidChangeVisibility = this._onDidChangeVisibility.event;
        this._element = append(container, dom_$('.monaco-dropdown'));
        this._label = append(this._element, dom_$('.dropdown-label'));
        let labelRenderer = options.labelRenderer;
        if (!labelRenderer) {
            labelRenderer = (container) => {
                container.textContent = options.label || '';
                return null;
            };
        }
        for (const event of [EventType.CLICK, EventType.MOUSE_DOWN, touch_EventType.Tap]) {
            this._register(addDisposableListener(this.element, event, e => EventHelper.stop(e, true))); // prevent default click behaviour to trigger
        }
        for (const event of [EventType.MOUSE_DOWN, touch_EventType.Tap]) {
            this._register(addDisposableListener(this._label, event, e => {
                if (e instanceof MouseEvent && (e.detail > 1 || e.button !== 0)) {
                    // prevent right click trigger to allow separate context menu (https://github.com/microsoft/vscode/issues/151064)
                    // prevent multiple clicks to open multiple context menus (https://github.com/microsoft/vscode/issues/41363)
                    return;
                }
                if (this.visible) {
                    this.hide();
                }
                else {
                    this.show();
                }
            }));
        }
        this._register(addDisposableListener(this._label, EventType.KEY_UP, e => {
            const event = new StandardKeyboardEvent(e);
            if (event.equals(3 /* KeyCode.Enter */) || event.equals(10 /* KeyCode.Space */)) {
                EventHelper.stop(e, true); // https://github.com/microsoft/vscode/issues/57997
                if (this.visible) {
                    this.hide();
                }
                else {
                    this.show();
                }
            }
        }));
        const cleanupFn = labelRenderer(this._label);
        if (cleanupFn) {
            this._register(cleanupFn);
        }
        this._register(Gesture.addTarget(this._label));
    }
    get element() {
        return this._element;
    }
    show() {
        if (!this.visible) {
            this.visible = true;
            this._onDidChangeVisibility.fire(true);
        }
    }
    hide() {
        if (this.visible) {
            this.visible = false;
            this._onDidChangeVisibility.fire(false);
        }
    }
    dispose() {
        super.dispose();
        this.hide();
        if (this.boxContainer) {
            this.boxContainer.remove();
            this.boxContainer = undefined;
        }
        if (this.contents) {
            this.contents.remove();
            this.contents = undefined;
        }
        if (this._label) {
            this._label.remove();
            this._label = undefined;
        }
    }
}
class DropdownMenu extends BaseDropdown {
    constructor(container, options) {
        super(container, options);
        this._actions = [];
        this._contextMenuProvider = options.contextMenuProvider;
        this.actions = options.actions || [];
        this.actionProvider = options.actionProvider;
        this.menuClassName = options.menuClassName || '';
        this.menuAsChild = !!options.menuAsChild;
    }
    set menuOptions(options) {
        this._menuOptions = options;
    }
    get menuOptions() {
        return this._menuOptions;
    }
    get actions() {
        if (this.actionProvider) {
            return this.actionProvider.getActions();
        }
        return this._actions;
    }
    set actions(actions) {
        this._actions = actions;
    }
    show() {
        super.show();
        this.element.classList.add('active');
        this._contextMenuProvider.showContextMenu({
            getAnchor: () => this.element,
            getActions: () => this.actions,
            getActionsContext: () => this.menuOptions ? this.menuOptions.context : null,
            getActionViewItem: action => this.menuOptions && this.menuOptions.actionViewItemProvider ? this.menuOptions.actionViewItemProvider(action) : undefined,
            getKeyBinding: action => this.menuOptions && this.menuOptions.getKeyBinding ? this.menuOptions.getKeyBinding(action) : undefined,
            getMenuClassName: () => this.menuClassName,
            onHide: () => this.onHide(),
            actionRunner: this.menuOptions ? this.menuOptions.actionRunner : undefined,
            anchorAlignment: this.menuOptions ? this.menuOptions.anchorAlignment : 0 /* AnchorAlignment.LEFT */,
            domForShadowRoot: this.menuAsChild ? this.element : undefined
        });
    }
    hide() {
        super.hide();
    }
    onHide() {
        this.hide();
        this.element.classList.remove('active');
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/dropdown/dropdownActionViewItem.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class DropdownMenuActionViewItem extends BaseActionViewItem {
    constructor(action, menuActionsOrProvider, contextMenuProvider, options = Object.create(null)) {
        super(null, action, options);
        this.actionItem = null;
        this._onDidChangeVisibility = this._register(new Emitter());
        this.menuActionsOrProvider = menuActionsOrProvider;
        this.contextMenuProvider = contextMenuProvider;
        this.options = options;
        if (this.options.actionRunner) {
            this.actionRunner = this.options.actionRunner;
        }
    }
    render(container) {
        this.actionItem = container;
        const labelRenderer = (el) => {
            this.element = append(el, dom_$('a.action-label'));
            let classNames = [];
            if (typeof this.options.classNames === 'string') {
                classNames = this.options.classNames.split(/\s+/g).filter(s => !!s);
            }
            else if (this.options.classNames) {
                classNames = this.options.classNames;
            }
            // todo@aeschli: remove codicon, should come through `this.options.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');
            this.element.title = this._action.label || '';
            this.element.ariaLabel = this._action.label || '';
            return null;
        };
        const isActionsArray = Array.isArray(this.menuActionsOrProvider);
        const options = {
            contextMenuProvider: this.contextMenuProvider,
            labelRenderer: labelRenderer,
            menuAsChild: this.options.menuAsChild,
            actions: isActionsArray ? this.menuActionsOrProvider : undefined,
            actionProvider: isActionsArray ? undefined : this.menuActionsOrProvider
        };
        this.dropdownMenu = this._register(new DropdownMenu(container, options));
        this._register(this.dropdownMenu.onDidChangeVisibility(visible => {
            var _a;
            (_a = this.element) === null || _a === void 0 ? void 0 : _a.setAttribute('aria-expanded', `${visible}`);
            this._onDidChangeVisibility.fire(visible);
        }));
        this.dropdownMenu.menuOptions = {
            actionViewItemProvider: this.options.actionViewItemProvider,
            actionRunner: this.actionRunner,
            getKeyBinding: this.options.keybindingProvider,
            context: this._context
        };
        if (this.options.anchorAlignmentProvider) {
            const that = this;
            this.dropdownMenu.menuOptions = Object.assign(Object.assign({}, this.dropdownMenu.menuOptions), { get anchorAlignment() {
                    return that.options.anchorAlignmentProvider();
                } });
        }
        this.updateTooltip();
        this.updateEnabled();
    }
    getTooltip() {
        let title = null;
        if (this.getAction().tooltip) {
            title = this.getAction().tooltip;
        }
        else if (this.getAction().label) {
            title = this.getAction().label;
        }
        return title !== null && title !== void 0 ? title : undefined;
    }
    setActionContext(newContext) {
        super.setActionContext(newContext);
        if (this.dropdownMenu) {
            if (this.dropdownMenu.menuOptions) {
                this.dropdownMenu.menuOptions.context = newContext;
            }
            else {
                this.dropdownMenu.menuOptions = { context: newContext };
            }
        }
    }
    updateEnabled() {
        var _a, _b;
        const disabled = !this.getAction().enabled;
        (_a = this.actionItem) === null || _a === void 0 ? void 0 : _a.classList.toggle('disabled', disabled);
        (_b = this.element) === null || _b === void 0 ? void 0 : _b.classList.toggle('disabled', disabled);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/keybindingLabels.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class ModifierLabelProvider {
    constructor(mac, windows, linux = windows) {
        this.modifierLabels = [null]; // index 0 will never me accessed.
        this.modifierLabels[2 /* OperatingSystem.Macintosh */] = mac;
        this.modifierLabels[1 /* OperatingSystem.Windows */] = windows;
        this.modifierLabels[3 /* OperatingSystem.Linux */] = linux;
    }
    toLabel(OS, parts, keyLabelProvider) {
        if (parts.length === 0) {
            return null;
        }
        const result = [];
        for (let i = 0, len = parts.length; i < len; i++) {
            const part = parts[i];
            const keyLabel = keyLabelProvider(part);
            if (keyLabel === null) {
                // this keybinding cannot be expressed...
                return null;
            }
            result[i] = _simpleAsString(part, keyLabel, this.modifierLabels[OS]);
        }
        return result.join(' ');
    }
}
/**
 * A label provider that prints modifiers in a suitable format for displaying in the UI.
 */
const UILabelProvider = new ModifierLabelProvider({
    ctrlKey: '\u2303',
    shiftKey: '⇧',
    altKey: '⌥',
    metaKey: '⌘',
    separator: '',
}, {
    ctrlKey: localize({ key: 'ctrlKey', comment: ['This is the short form for the Control key on the keyboard'] }, "Ctrl"),
    shiftKey: localize({ key: 'shiftKey', comment: ['This is the short form for the Shift key on the keyboard'] }, "Shift"),
    altKey: localize({ key: 'altKey', comment: ['This is the short form for the Alt key on the keyboard'] }, "Alt"),
    metaKey: localize({ key: 'windowsKey', comment: ['This is the short form for the Windows key on the keyboard'] }, "Windows"),
    separator: '+',
}, {
    ctrlKey: localize({ key: 'ctrlKey', comment: ['This is the short form for the Control key on the keyboard'] }, "Ctrl"),
    shiftKey: localize({ key: 'shiftKey', comment: ['This is the short form for the Shift key on the keyboard'] }, "Shift"),
    altKey: localize({ key: 'altKey', comment: ['This is the short form for the Alt key on the keyboard'] }, "Alt"),
    metaKey: localize({ key: 'superKey', comment: ['This is the short form for the Super key on the keyboard'] }, "Super"),
    separator: '+',
});
/**
 * A label provider that prints modifiers in a suitable format for ARIA.
 */
const AriaLabelProvider = new ModifierLabelProvider({
    ctrlKey: localize({ key: 'ctrlKey.long', comment: ['This is the long form for the Control key on the keyboard'] }, "Control"),
    shiftKey: localize({ key: 'shiftKey.long', comment: ['This is the long form for the Shift key on the keyboard'] }, "Shift"),
    altKey: localize({ key: 'optKey.long', comment: ['This is the long form for the Alt/Option key on the keyboard'] }, "Option"),
    metaKey: localize({ key: 'cmdKey.long', comment: ['This is the long form for the Command key on the keyboard'] }, "Command"),
    separator: '+',
}, {
    ctrlKey: localize({ key: 'ctrlKey.long', comment: ['This is the long form for the Control key on the keyboard'] }, "Control"),
    shiftKey: localize({ key: 'shiftKey.long', comment: ['This is the long form for the Shift key on the keyboard'] }, "Shift"),
    altKey: localize({ key: 'altKey.long', comment: ['This is the long form for the Alt key on the keyboard'] }, "Alt"),
    metaKey: localize({ key: 'windowsKey.long', comment: ['This is the long form for the Windows key on the keyboard'] }, "Windows"),
    separator: '+',
}, {
    ctrlKey: localize({ key: 'ctrlKey.long', comment: ['This is the long form for the Control key on the keyboard'] }, "Control"),
    shiftKey: localize({ key: 'shiftKey.long', comment: ['This is the long form for the Shift key on the keyboard'] }, "Shift"),
    altKey: localize({ key: 'altKey.long', comment: ['This is the long form for the Alt key on the keyboard'] }, "Alt"),
    metaKey: localize({ key: 'superKey.long', comment: ['This is the long form for the Super key on the keyboard'] }, "Super"),
    separator: '+',
});
/**
 * A label provider that prints modifiers in a suitable format for Electron Accelerators.
 * See https://github.com/electron/electron/blob/master/docs/api/accelerator.md
 */
const ElectronAcceleratorLabelProvider = new ModifierLabelProvider({
    ctrlKey: 'Ctrl',
    shiftKey: 'Shift',
    altKey: 'Alt',
    metaKey: 'Cmd',
    separator: '+',
}, {
    ctrlKey: 'Ctrl',
    shiftKey: 'Shift',
    altKey: 'Alt',
    metaKey: 'Super',
    separator: '+',
});
/**
 * A label provider that prints modifiers in a suitable format for user settings.
 */
const UserSettingsLabelProvider = new ModifierLabelProvider({
    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, key, labels) {
    if (key === null) {
        return '';
    }
    const result = [];
    // translate modifier keys: Ctrl-Shift-Alt-Meta
    if (modifiers.ctrlKey) {
        result.push(labels.ctrlKey);
    }
    if (modifiers.shiftKey) {
        result.push(labels.shiftKey);
    }
    if (modifiers.altKey) {
        result.push(labels.altKey);
    }
    if (modifiers.metaKey) {
        result.push(labels.metaKey);
    }
    // the actual key
    if (key !== '') {
        result.push(key);
    }
    return result.join(labels.separator);
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/platform/actions/browser/menuEntryActionViewItem.css
var menuEntryActionViewItem = __webpack_require__(39540);
;// ../../node_modules/monaco-editor/esm/vs/platform/actions/browser/menuEntryActionViewItem.css

      
      
      
      
      
      
      
      
      

var menuEntryActionViewItem_options = {};

menuEntryActionViewItem_options.styleTagTransform = (styleTagTransform_default());
menuEntryActionViewItem_options.setAttributes = (setAttributesWithoutAttributes_default());

      menuEntryActionViewItem_options.insert = insertBySelector_default().bind(null, "head");
    
menuEntryActionViewItem_options.domAPI = (styleDomAPI_default());
menuEntryActionViewItem_options.insertStyleElement = (insertStyleElement_default());

var menuEntryActionViewItem_update = injectStylesIntoStyleTag_default()(menuEntryActionViewItem/* default */.A, menuEntryActionViewItem_options);




       /* harmony default export */ const browser_menuEntryActionViewItem = (menuEntryActionViewItem/* default */.A && menuEntryActionViewItem/* default */.A.locals ? menuEntryActionViewItem/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/platform/actions/browser/menuEntryActionViewItem.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var menuEntryActionViewItem_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var menuEntryActionViewItem_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var menuEntryActionViewItem_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};




















function createAndFillInActionBarActions(menu, options, target, primaryGroup, primaryMaxCount, shouldInlineSubmenu, useSeparatorsInPrimaryActions) {
    const groups = menu.getActions(options);
    const isPrimaryAction = typeof primaryGroup === 'string' ? (actionGroup) => actionGroup === primaryGroup : primaryGroup;
    // Action bars handle alternative actions on their own so the alternative actions should be ignored
    fillInActions(groups, target, false, isPrimaryAction, primaryMaxCount, shouldInlineSubmenu, useSeparatorsInPrimaryActions);
    return asDisposable(groups);
}
function asDisposable(groups) {
    const disposables = new DisposableStore();
    for (const [, actions] of groups) {
        for (const action of actions) {
            disposables.add(action);
        }
    }
    return disposables;
}
function fillInActions(groups, target, useAlternativeActions, isPrimaryAction = actionGroup => actionGroup === 'navigation', primaryMaxCount = Number.MAX_SAFE_INTEGER, 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 = new Set();
    for (const [group, actions] of groups) {
        let target;
        if (isPrimaryAction(group)) {
            target = primaryBucket;
            if (target.length > 0 && useSeparatorsInPrimaryActions) {
                target.push(new Separator());
            }
        }
        else {
            target = secondaryBucket;
            if (target.length > 0) {
                target.push(new Separator());
            }
        }
        for (let action of actions) {
            if (useAlternativeActions) {
                action = action instanceof MenuItemAction && action.alt ? action.alt : action;
            }
            const newLen = target.push(action);
            // keep submenu info for later inlining
            if (action instanceof SubmenuAction) {
                submenuInfo.add({ group, action, index: newLen - 1 });
            }
        }
    }
    // ask the outside if submenu should be inlined or not. only ask when
    // there would be enough space
    for (const { group, action, index } of submenuInfo) {
        const target = isPrimaryAction(group) ? primaryBucket : secondaryBucket;
        // inlining submenus with length 0 or 1 is easy,
        // larger submenus need to be checked with the overall limit
        const submenuActions = action.actions;
        if ((submenuActions.length <= 1 || target.length + submenuActions.length - 2 <= primaryMaxCount) && shouldInlineSubmenu(action, group, target.length)) {
            target.splice(index, 1, ...submenuActions);
        }
    }
    // overflow items from the primary group into the secondary bucket
    if (primaryBucket !== secondaryBucket && primaryBucket.length > primaryMaxCount) {
        const overflow = primaryBucket.splice(primaryMaxCount, primaryBucket.length - primaryMaxCount);
        secondaryBucket.unshift(...overflow, new Separator());
    }
}
let MenuEntryActionViewItem = class MenuEntryActionViewItem extends ActionViewItem {
    constructor(action, options, _keybindingService, _notificationService, _contextKeyService, _themeService, _contextMenuService) {
        super(undefined, action, { icon: !!(action.class || action.item.icon), label: !action.class && !action.item.icon, draggable: options === null || options === void 0 ? void 0 : options.draggable, keybinding: options === null || options === void 0 ? void 0 : options.keybinding, hoverDelegate: options === null || options === void 0 ? void 0 : options.hoverDelegate });
        this._keybindingService = _keybindingService;
        this._notificationService = _notificationService;
        this._contextKeyService = _contextKeyService;
        this._themeService = _themeService;
        this._contextMenuService = _contextMenuService;
        this._wantsAltCommand = false;
        this._itemClassDispose = this._register(new MutableDisposable());
        this._altKey = ModifierKeyEmitter.getInstance();
    }
    get _menuItemAction() {
        return this._action;
    }
    get _commandAction() {
        return this._wantsAltCommand && this._menuItemAction.alt || this._menuItemAction;
    }
    onClick(event) {
        return menuEntryActionViewItem_awaiter(this, void 0, void 0, function* () {
            event.preventDefault();
            event.stopPropagation();
            try {
                yield this.actionRunner.run(this._commandAction, this._context);
            }
            catch (err) {
                this._notificationService.error(err);
            }
        });
    }
    render(container) {
        super.render(container);
        container.classList.add('menu-entry');
        this._updateItemClass(this._menuItemAction.item);
        let mouseOver = false;
        let alternativeKeyDown = this._altKey.keyStatus.altKey || ((isWindows || isLinux) && this._altKey.keyStatus.shiftKey);
        const updateAltState = () => {
            var _a;
            const wantsAltCommand = mouseOver && alternativeKeyDown && !!((_a = this._commandAction.alt) === null || _a === void 0 ? void 0 : _a.enabled);
            if (wantsAltCommand !== this._wantsAltCommand) {
                this._wantsAltCommand = wantsAltCommand;
                this.updateLabel();
                this.updateTooltip();
                this.updateClass();
            }
        };
        if (this._menuItemAction.alt) {
            this._register(this._altKey.event(value => {
                alternativeKeyDown = value.altKey || ((isWindows || isLinux) && value.shiftKey);
                updateAltState();
            }));
        }
        this._register(addDisposableListener(container, 'mouseleave', _ => {
            mouseOver = false;
            updateAltState();
        }));
        this._register(addDisposableListener(container, 'mouseenter', _ => {
            mouseOver = true;
            updateAltState();
        }));
    }
    updateLabel() {
        if (this.options.label && this.label) {
            this.label.textContent = this._commandAction.label;
        }
    }
    getTooltip() {
        var _a;
        const keybinding = this._keybindingService.lookupKeybinding(this._commandAction.id, this._contextKeyService);
        const keybindingLabel = keybinding && keybinding.getLabel();
        const tooltip = this._commandAction.tooltip || this._commandAction.label;
        let title = keybindingLabel
            ? localize('titleAndKb', "{0} ({1})", tooltip, keybindingLabel)
            : tooltip;
        if (!this._wantsAltCommand && ((_a = this._menuItemAction.alt) === null || _a === void 0 ? void 0 : _a.enabled)) {
            const altTooltip = this._menuItemAction.alt.tooltip || this._menuItemAction.alt.label;
            const altKeybinding = this._keybindingService.lookupKeybinding(this._menuItemAction.alt.id, this._contextKeyService);
            const altKeybindingLabel = altKeybinding && altKeybinding.getLabel();
            const altTitleSection = altKeybindingLabel
                ? localize('titleAndKb', "{0} ({1})", altTooltip, altKeybindingLabel)
                : altTooltip;
            title = localize('titleAndKbAndAlt', "{0}\n[{1}] {2}", title, UILabelProvider.modifierLabels[OS].altKey, altTitleSection);
        }
        return title;
    }
    updateClass() {
        if (this.options.icon) {
            if (this._commandAction !== this._menuItemAction) {
                if (this._menuItemAction.alt) {
                    this._updateItemClass(this._menuItemAction.alt.item);
                }
            }
            else {
                this._updateItemClass(this._menuItemAction.item);
            }
        }
    }
    _updateItemClass(item) {
        var _a;
        this._itemClassDispose.value = undefined;
        const { element, label } = this;
        if (!element || !label) {
            return;
        }
        const icon = this._commandAction.checked && ((_a = item.toggled) === null || _a === void 0 ? void 0 : _a.icon) ? item.toggled.icon : item.icon;
        if (!icon) {
            return;
        }
        if (ThemeIcon.isThemeIcon(icon)) {
            // theme icons
            const iconClasses = ThemeIcon.asClassNameArray(icon);
            label.classList.add(...iconClasses);
            this._itemClassDispose.value = toDisposable(() => {
                label.classList.remove(...iconClasses);
            });
        }
        else {
            // icon path/url
            label.style.backgroundImage = (isDark(this._themeService.getColorTheme().type)
                ? asCSSUrl(icon.dark)
                : asCSSUrl(icon.light));
            label.classList.add('icon');
            this._itemClassDispose.value = combinedDisposable(toDisposable(() => {
                label.style.backgroundImage = '';
                label.classList.remove('icon');
            }), this._themeService.onDidColorThemeChange(() => {
                // refresh when the theme changes in case we go between dark <-> light
                this.updateClass();
            }));
        }
    }
};
MenuEntryActionViewItem = menuEntryActionViewItem_decorate([
    menuEntryActionViewItem_param(2, IKeybindingService),
    menuEntryActionViewItem_param(3, INotificationService),
    menuEntryActionViewItem_param(4, IContextKeyService),
    menuEntryActionViewItem_param(5, IThemeService),
    menuEntryActionViewItem_param(6, IContextMenuService)
], MenuEntryActionViewItem);

let SubmenuEntryActionViewItem = class SubmenuEntryActionViewItem extends DropdownMenuActionViewItem {
    constructor(action, options, _contextMenuService, _themeService) {
        var _a, _b;
        const dropdownOptions = Object.assign({}, options !== null && options !== void 0 ? options : Object.create(null), {
            menuAsChild: (_a = options === null || options === void 0 ? void 0 : options.menuAsChild) !== null && _a !== void 0 ? _a : false,
            classNames: (_b = options === null || options === void 0 ? void 0 : options.classNames) !== null && _b !== void 0 ? _b : (ThemeIcon.isThemeIcon(action.item.icon) ? ThemeIcon.asClassName(action.item.icon) : undefined),
        });
        super(action, { getActions: () => action.actions }, _contextMenuService, dropdownOptions);
        this._contextMenuService = _contextMenuService;
        this._themeService = _themeService;
    }
    render(container) {
        super.render(container);
        assertType(this.element);
        container.classList.add('menu-entry');
        const action = this._action;
        const { icon } = action.item;
        if (icon && !ThemeIcon.isThemeIcon(icon)) {
            this.element.classList.add('icon');
            const setBackgroundImage = () => {
                if (this.element) {
                    this.element.style.backgroundImage = (isDark(this._themeService.getColorTheme().type)
                        ? asCSSUrl(icon.dark)
                        : asCSSUrl(icon.light));
                }
            };
            setBackgroundImage();
            this._register(this._themeService.onDidColorThemeChange(() => {
                // refresh when the theme changes in case we go between dark <-> light
                setBackgroundImage();
            }));
        }
    }
};
SubmenuEntryActionViewItem = menuEntryActionViewItem_decorate([
    menuEntryActionViewItem_param(2, IContextMenuService),
    menuEntryActionViewItem_param(3, IThemeService)
], SubmenuEntryActionViewItem);

let DropdownWithDefaultActionViewItem = class DropdownWithDefaultActionViewItem extends BaseActionViewItem {
    constructor(submenuAction, options, _keybindingService, _notificationService, _contextMenuService, _menuService, _instaService, _storageService) {
        var _a, _b, _c;
        super(null, submenuAction);
        this._keybindingService = _keybindingService;
        this._notificationService = _notificationService;
        this._contextMenuService = _contextMenuService;
        this._menuService = _menuService;
        this._instaService = _instaService;
        this._storageService = _storageService;
        this._container = null;
        this._options = options;
        this._storageKey = `${submenuAction.item.submenu.id}_lastActionId`;
        // determine default action
        let defaultAction;
        const defaultActionId = _storageService.get(this._storageKey, 1 /* StorageScope.WORKSPACE */);
        if (defaultActionId) {
            defaultAction = submenuAction.actions.find(a => defaultActionId === a.id);
        }
        if (!defaultAction) {
            defaultAction = submenuAction.actions[0];
        }
        this._defaultAction = this._instaService.createInstance(MenuEntryActionViewItem, defaultAction, { keybinding: this._getDefaultActionKeybindingLabel(defaultAction) });
        const dropdownOptions = Object.assign({}, options !== null && options !== void 0 ? options : Object.create(null), {
            menuAsChild: (_a = options === null || options === void 0 ? void 0 : options.menuAsChild) !== null && _a !== void 0 ? _a : true,
            classNames: (_b = options === null || options === void 0 ? void 0 : options.classNames) !== null && _b !== void 0 ? _b : ['codicon', 'codicon-chevron-down'],
            actionRunner: (_c = options === null || options === void 0 ? void 0 : options.actionRunner) !== null && _c !== void 0 ? _c : new ActionRunner()
        });
        this._dropdown = new DropdownMenuActionViewItem(submenuAction, submenuAction.actions, this._contextMenuService, dropdownOptions);
        this._dropdown.actionRunner.onDidRun((e) => {
            if (e.action instanceof MenuItemAction) {
                this.update(e.action);
            }
        });
    }
    update(lastAction) {
        this._storageService.store(this._storageKey, lastAction.id, 1 /* StorageScope.WORKSPACE */, 0 /* StorageTarget.USER */);
        this._defaultAction.dispose();
        this._defaultAction = this._instaService.createInstance(MenuEntryActionViewItem, lastAction, { keybinding: this._getDefaultActionKeybindingLabel(lastAction) });
        this._defaultAction.actionRunner = new class extends ActionRunner {
            runAction(action, context) {
                return menuEntryActionViewItem_awaiter(this, void 0, void 0, function* () {
                    yield action.run(undefined);
                });
            }
        }();
        if (this._container) {
            this._defaultAction.render(prepend(this._container, dom_$('.action-container')));
        }
    }
    _getDefaultActionKeybindingLabel(defaultAction) {
        var _a;
        let defaultActionKeybinding;
        if ((_a = this._options) === null || _a === void 0 ? void 0 : _a.renderKeybindingWithDefaultActionLabel) {
            const kb = this._keybindingService.lookupKeybinding(defaultAction.id);
            if (kb) {
                defaultActionKeybinding = `(${kb.getLabel()})`;
            }
        }
        return defaultActionKeybinding;
    }
    setActionContext(newContext) {
        super.setActionContext(newContext);
        this._defaultAction.setActionContext(newContext);
        this._dropdown.setActionContext(newContext);
    }
    render(container) {
        this._container = container;
        super.render(this._container);
        this._container.classList.add('monaco-dropdown-with-default');
        const primaryContainer = dom_$('.action-container');
        this._defaultAction.render(append(this._container, primaryContainer));
        this._register(addDisposableListener(primaryContainer, EventType.KEY_DOWN, (e) => {
            const event = new StandardKeyboardEvent(e);
            if (event.equals(17 /* KeyCode.RightArrow */)) {
                this._defaultAction.element.tabIndex = -1;
                this._dropdown.focus();
                event.stopPropagation();
            }
        }));
        const dropdownContainer = dom_$('.dropdown-action-container');
        this._dropdown.render(append(this._container, dropdownContainer));
        this._register(addDisposableListener(dropdownContainer, EventType.KEY_DOWN, (e) => {
            var _a;
            const event = new StandardKeyboardEvent(e);
            if (event.equals(15 /* KeyCode.LeftArrow */)) {
                this._defaultAction.element.tabIndex = 0;
                this._dropdown.setFocusable(false);
                (_a = this._defaultAction.element) === null || _a === void 0 ? void 0 : _a.focus();
                event.stopPropagation();
            }
        }));
    }
    focus(fromRight) {
        if (fromRight) {
            this._dropdown.focus();
        }
        else {
            this._defaultAction.element.tabIndex = 0;
            this._defaultAction.element.focus();
        }
    }
    blur() {
        this._defaultAction.element.tabIndex = -1;
        this._dropdown.blur();
        this._container.blur();
    }
    setFocusable(focusable) {
        if (focusable) {
            this._defaultAction.element.tabIndex = 0;
        }
        else {
            this._defaultAction.element.tabIndex = -1;
            this._dropdown.setFocusable(false);
        }
    }
    dispose() {
        this._defaultAction.dispose();
        this._dropdown.dispose();
        super.dispose();
    }
};
DropdownWithDefaultActionViewItem = menuEntryActionViewItem_decorate([
    menuEntryActionViewItem_param(2, IKeybindingService),
    menuEntryActionViewItem_param(3, INotificationService),
    menuEntryActionViewItem_param(4, IContextMenuService),
    menuEntryActionViewItem_param(5, IMenuService),
    menuEntryActionViewItem_param(6, IInstantiationService),
    menuEntryActionViewItem_param(7, IStorageService)
], DropdownWithDefaultActionViewItem);

/**
 * Creates action view items for menu actions or submenu actions.
 */
function createActionViewItem(instaService, action, options) {
    if (action instanceof MenuItemAction) {
        return instaService.createInstance(MenuEntryActionViewItem, action, options);
    }
    else if (action instanceof SubmenuItemAction) {
        if (action.item.rememberDefaultAction) {
            return instaService.createInstance(DropdownWithDefaultActionViewItem, action, options);
        }
        else {
            return instaService.createInstance(SubmenuEntryActionViewItem, action, options);
        }
    }
    else {
        return undefined;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/peekView/browser/peekView.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var peekView_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var peekView_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};


















const IPeekViewService = createDecorator('IPeekViewService');
registerSingleton(IPeekViewService, class {
    constructor() {
        this._widgets = new Map();
    }
    addExclusiveWidget(editor, widget) {
        const existing = this._widgets.get(editor);
        if (existing) {
            existing.listener.dispose();
            existing.widget.dispose();
        }
        const remove = () => {
            const data = this._widgets.get(editor);
            if (data && data.widget === widget) {
                data.listener.dispose();
                this._widgets.delete(editor);
            }
        };
        this._widgets.set(editor, { widget, listener: widget.onDidClose(remove) });
    }
});
var PeekContext;
(function (PeekContext) {
    PeekContext.inPeekEditor = new RawContextKey('inReferenceSearchEditor', true, localize('inReferenceSearchEditor', "Whether the current code editor is embedded inside peek"));
    PeekContext.notInPeekEditor = PeekContext.inPeekEditor.toNegated();
})(PeekContext || (PeekContext = {}));
let PeekContextController = class PeekContextController {
    constructor(editor, contextKeyService) {
        if (editor instanceof EmbeddedCodeEditorWidget) {
            PeekContext.inPeekEditor.bindTo(contextKeyService);
        }
    }
    dispose() { }
};
PeekContextController.ID = 'editor.contrib.referenceController';
PeekContextController = peekView_decorate([
    peekView_param(1, IContextKeyService)
], PeekContextController);
registerEditorContribution(PeekContextController.ID, PeekContextController);
function getOuterEditor(accessor) {
    const editor = accessor.get(ICodeEditorService).getFocusedCodeEditor();
    if (editor instanceof EmbeddedCodeEditorWidget) {
        return editor.getParentEditor();
    }
    return editor;
}
const peekView_defaultOptions = {
    headerBackgroundColor: Color.white,
    primaryHeadingColor: Color.fromHex('#333333'),
    secondaryHeadingColor: Color.fromHex('#6c6c6cb3')
};
let PeekViewWidget = class PeekViewWidget extends ZoneWidget {
    constructor(editor, options, instantiationService) {
        super(editor, options);
        this.instantiationService = instantiationService;
        this._onDidClose = new Emitter();
        this.onDidClose = this._onDidClose.event;
        mixin(this.options, peekView_defaultOptions, false);
    }
    dispose() {
        if (!this.disposed) {
            this.disposed = true; // prevent consumers who dispose on onDidClose from looping
            super.dispose();
            this._onDidClose.fire(this);
        }
    }
    style(styles) {
        const options = this.options;
        if (styles.headerBackgroundColor) {
            options.headerBackgroundColor = styles.headerBackgroundColor;
        }
        if (styles.primaryHeadingColor) {
            options.primaryHeadingColor = styles.primaryHeadingColor;
        }
        if (styles.secondaryHeadingColor) {
            options.secondaryHeadingColor = styles.secondaryHeadingColor;
        }
        super.style(styles);
    }
    _applyStyles() {
        super._applyStyles();
        const options = this.options;
        if (this._headElement && options.headerBackgroundColor) {
            this._headElement.style.backgroundColor = options.headerBackgroundColor.toString();
        }
        if (this._primaryHeading && options.primaryHeadingColor) {
            this._primaryHeading.style.color = options.primaryHeadingColor.toString();
        }
        if (this._secondaryHeading && options.secondaryHeadingColor) {
            this._secondaryHeading.style.color = options.secondaryHeadingColor.toString();
        }
        if (this._bodyElement && options.frameColor) {
            this._bodyElement.style.borderColor = options.frameColor.toString();
        }
    }
    _fillContainer(container) {
        this.setCssClass('peekview-widget');
        this._headElement = dom_$('.head');
        this._bodyElement = dom_$('.body');
        this._fillHead(this._headElement);
        this._fillBody(this._bodyElement);
        container.appendChild(this._headElement);
        container.appendChild(this._bodyElement);
    }
    _fillHead(container, noCloseAction) {
        const titleElement = dom_$('.peekview-title');
        if (this.options.supportOnTitleClick) {
            titleElement.classList.add('clickable');
            addStandardDisposableListener(titleElement, 'click', event => this._onTitleClick(event));
        }
        append(this._headElement, titleElement);
        this._fillTitleIcon(titleElement);
        this._primaryHeading = dom_$('span.filename');
        this._secondaryHeading = dom_$('span.dirname');
        this._metaHeading = dom_$('span.meta');
        append(titleElement, this._primaryHeading, this._secondaryHeading, this._metaHeading);
        const actionsContainer = dom_$('.peekview-actions');
        append(this._headElement, actionsContainer);
        const actionBarOptions = this._getActionBarOptions();
        this._actionbarWidget = new ActionBar(actionsContainer, actionBarOptions);
        this._disposables.add(this._actionbarWidget);
        if (!noCloseAction) {
            this._actionbarWidget.push(new Action('peekview.close', localize('label.close', "Close"), Codicon.close.classNames, true, () => {
                this.dispose();
                return Promise.resolve();
            }), { label: false, icon: true });
        }
    }
    _fillTitleIcon(container) {
    }
    _getActionBarOptions() {
        return {
            actionViewItemProvider: createActionViewItem.bind(undefined, this.instantiationService),
            orientation: 0 /* ActionsOrientation.HORIZONTAL */
        };
    }
    _onTitleClick(event) {
        // implement me if supportOnTitleClick option is set
    }
    setTitle(primaryHeading, secondaryHeading) {
        if (this._primaryHeading && this._secondaryHeading) {
            this._primaryHeading.innerText = primaryHeading;
            this._primaryHeading.setAttribute('title', primaryHeading);
            if (secondaryHeading) {
                this._secondaryHeading.innerText = secondaryHeading;
            }
            else {
                clearNode(this._secondaryHeading);
            }
        }
    }
    setMetaTitle(value) {
        if (this._metaHeading) {
            if (value) {
                this._metaHeading.innerText = value;
                show(this._metaHeading);
            }
            else {
                hide(this._metaHeading);
            }
        }
    }
    _doLayout(heightInPixel, widthInPixel) {
        if (!this._isShowing && heightInPixel < 0) {
            // Looks like the view zone got folded away!
            this.dispose();
            return;
        }
        const headHeight = Math.ceil(this.editor.getOption(61 /* EditorOption.lineHeight */) * 1.2);
        const bodyHeight = Math.round(heightInPixel - (headHeight + 2 /* the border-top/bottom width*/));
        this._doLayoutHead(headHeight, widthInPixel);
        this._doLayoutBody(bodyHeight, widthInPixel);
    }
    _doLayoutHead(heightInPixel, widthInPixel) {
        if (this._headElement) {
            this._headElement.style.height = `${heightInPixel}px`;
            this._headElement.style.lineHeight = this._headElement.style.height;
        }
    }
    _doLayoutBody(heightInPixel, widthInPixel) {
        if (this._bodyElement) {
            this._bodyElement.style.height = `${heightInPixel}px`;
        }
    }
};
PeekViewWidget = peekView_decorate([
    peekView_param(2, IInstantiationService)
], PeekViewWidget);

const peekViewTitleBackground = registerColor('peekViewTitle.background', { dark: transparent(editorInfoForeground, .1), light: transparent(editorInfoForeground, .1), hcDark: null, hcLight: null }, localize('peekViewTitleBackground', 'Background color of the peek view title area.'));
const peekViewTitleForeground = registerColor('peekViewTitleLabel.foreground', { dark: Color.white, light: Color.black, hcDark: Color.white, hcLight: editorForeground }, localize('peekViewTitleForeground', 'Color of the peek view title.'));
const peekViewTitleInfoForeground = registerColor('peekViewTitleDescription.foreground', { dark: '#ccccccb3', light: '#616161', hcDark: '#FFFFFF99', hcLight: '#292929' }, localize('peekViewTitleInfoForeground', 'Color of the peek view title info.'));
const peekViewBorder = registerColor('peekView.border', { dark: editorInfoForeground, light: editorInfoForeground, hcDark: contrastBorder, hcLight: contrastBorder }, localize('peekViewBorder', 'Color of the peek view borders and arrow.'));
const peekViewResultsBackground = registerColor('peekViewResult.background', { dark: '#252526', light: '#F3F3F3', hcDark: Color.black, hcLight: Color.white }, localize('peekViewResultsBackground', 'Background color of the peek view result list.'));
const peekViewResultsMatchForeground = registerColor('peekViewResult.lineForeground', { dark: '#bbbbbb', light: '#646465', hcDark: Color.white, hcLight: editorForeground }, localize('peekViewResultsMatchForeground', 'Foreground color for line nodes in the peek view result list.'));
const peekViewResultsFileForeground = registerColor('peekViewResult.fileForeground', { dark: Color.white, light: '#1E1E1E', hcDark: Color.white, hcLight: editorForeground }, localize('peekViewResultsFileForeground', 'Foreground color for file nodes in the peek view result list.'));
const peekViewResultsSelectionBackground = registerColor('peekViewResult.selectionBackground', { dark: '#3399ff33', light: '#3399ff33', hcDark: null, hcLight: null }, localize('peekViewResultsSelectionBackground', 'Background color of the selected entry in the peek view result list.'));
const peekViewResultsSelectionForeground = registerColor('peekViewResult.selectionForeground', { dark: Color.white, light: '#6C6C6C', hcDark: Color.white, hcLight: editorForeground }, localize('peekViewResultsSelectionForeground', 'Foreground color of the selected entry in the peek view result list.'));
const peekViewEditorBackground = registerColor('peekViewEditor.background', { dark: '#001F33', light: '#F2F8FC', hcDark: Color.black, hcLight: Color.white }, localize('peekViewEditorBackground', 'Background color of the peek view editor.'));
const peekViewEditorGutterBackground = registerColor('peekViewEditorGutter.background', { dark: peekViewEditorBackground, light: peekViewEditorBackground, hcDark: peekViewEditorBackground, hcLight: peekViewEditorBackground }, localize('peekViewEditorGutterBackground', 'Background color of the gutter in the peek view editor.'));
const peekViewResultsMatchHighlight = registerColor('peekViewResult.matchHighlightBackground', { dark: '#ea5c004d', light: '#ea5c004d', hcDark: null, hcLight: null }, localize('peekViewResultsMatchHighlight', 'Match highlight color in the peek view result list.'));
const peekViewEditorMatchHighlight = registerColor('peekViewEditor.matchHighlightBackground', { dark: '#ff8f0099', light: '#f5d802de', hcDark: null, hcLight: null }, localize('peekViewEditorMatchHighlight', 'Match highlight color in the peek view editor.'));
const peekViewEditorMatchHighlightBorder = registerColor('peekViewEditor.matchHighlightBorder', { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('peekViewEditorMatchHighlightBorder', 'Match highlight border in the peek view editor.'));

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/editorBrowser.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/**
 *@internal
 */
function isCodeEditor(thing) {
    if (thing && typeof thing.getEditorType === 'function') {
        return thing.getEditorType() === EditorType.ICodeEditor;
    }
    else {
        return false;
    }
}
/**
 *@internal
 */
function isDiffEditor(thing) {
    if (thing && typeof thing.getEditorType === 'function') {
        return thing.getEditorType() === EditorType.IDiffEditor;
    }
    else {
        return false;
    }
}
/**
 *@internal
 */
function getCodeEditor(thing) {
    if (isCodeEditor(thing)) {
        return thing;
    }
    if (isDiffEditor(thing)) {
        return thing.getModifiedEditor();
    }
    return null;
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/list/listPaging.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class PagedRenderer {
    constructor(renderer, modelProvider) {
        this.renderer = renderer;
        this.modelProvider = modelProvider;
    }
    get templateId() { return this.renderer.templateId; }
    renderTemplate(container) {
        const data = this.renderer.renderTemplate(container);
        return { data, disposable: Disposable.None };
    }
    renderElement(index, _, data, height) {
        if (data.disposable) {
            data.disposable.dispose();
        }
        if (!data.data) {
            return;
        }
        const model = this.modelProvider();
        if (model.isResolved(index)) {
            return this.renderer.renderElement(model.get(index), index, data.data, height);
        }
        const cts = new CancellationTokenSource();
        const promise = model.resolve(index, cts.token);
        data.disposable = { dispose: () => cts.cancel() };
        this.renderer.renderPlaceholder(index, data.data);
        promise.then(entry => this.renderer.renderElement(entry, index, data.data, height));
    }
    disposeTemplate(data) {
        if (data.disposable) {
            data.disposable.dispose();
            data.disposable = undefined;
        }
        if (data.data) {
            this.renderer.disposeTemplate(data.data);
            data.data = undefined;
        }
    }
}
class PagedAccessibilityProvider {
    constructor(modelProvider, accessibilityProvider) {
        this.modelProvider = modelProvider;
        this.accessibilityProvider = accessibilityProvider;
    }
    getWidgetAriaLabel() {
        return this.accessibilityProvider.getWidgetAriaLabel();
    }
    getAriaLabel(index) {
        const model = this.modelProvider();
        if (!model.isResolved(index)) {
            return null;
        }
        return this.accessibilityProvider.getAriaLabel(model.get(index));
    }
}
function fromPagedListOptions(modelProvider, options) {
    return Object.assign(Object.assign({}, options), { accessibilityProvider: options.accessibilityProvider && new PagedAccessibilityProvider(modelProvider, options.accessibilityProvider) });
}
class PagedList {
    constructor(user, container, virtualDelegate, renderers, options = {}) {
        const modelProvider = () => this.model;
        const pagedRenderers = renderers.map(r => new PagedRenderer(r, modelProvider));
        this.list = new List(user, container, virtualDelegate, pagedRenderers, fromPagedListOptions(modelProvider, options));
    }
    updateOptions(options) {
        this.list.updateOptions(options);
    }
    getHTMLElement() {
        return this.list.getHTMLElement();
    }
    get onDidFocus() {
        return this.list.onDidFocus;
    }
    get onDidDispose() {
        return this.list.onDidDispose;
    }
    get onMouseDblClick() {
        return Event.map(this.list.onMouseDblClick, ({ element, index, browserEvent }) => ({ element: element === undefined ? undefined : this._model.get(element), index, browserEvent }));
    }
    get onPointer() {
        return Event.map(this.list.onPointer, ({ element, index, browserEvent }) => ({ element: element === undefined ? undefined : this._model.get(element), index, browserEvent }));
    }
    get onDidChangeSelection() {
        return Event.map(this.list.onDidChangeSelection, ({ elements, indexes, browserEvent }) => ({ elements: elements.map(e => this._model.get(e)), indexes, browserEvent }));
    }
    get model() {
        return this._model;
    }
    set model(model) {
        this._model = model;
        this.list.splice(0, this.list.length, range(model.length));
    }
    getFocus() {
        return this.list.getFocus();
    }
    getSelection() {
        return this.list.getSelection();
    }
    getSelectedElements() {
        return this.getSelection().map(i => this.model.get(i));
    }
    style(styles) {
        this.list.style(styles);
    }
    dispose() {
        this.list.dispose();
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/splitview/splitview.css
var splitview = __webpack_require__(47539);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/splitview/splitview.css

      
      
      
      
      
      
      
      
      

var splitview_options = {};

splitview_options.styleTagTransform = (styleTagTransform_default());
splitview_options.setAttributes = (setAttributesWithoutAttributes_default());

      splitview_options.insert = insertBySelector_default().bind(null, "head");
    
splitview_options.domAPI = (styleDomAPI_default());
splitview_options.insertStyleElement = (insertStyleElement_default());

var splitview_update = injectStylesIntoStyleTag_default()(splitview/* default */.A, splitview_options);




       /* harmony default export */ const splitview_splitview = (splitview/* default */.A && splitview/* default */.A.locals ? splitview/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/splitview/splitview.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/











const splitview_defaultStyles = {
    separatorBorder: Color.transparent
};
class ViewItem {
    constructor(container, view, size, disposable) {
        this.container = container;
        this.view = view;
        this.disposable = disposable;
        this._cachedVisibleSize = undefined;
        if (typeof size === 'number') {
            this._size = size;
            this._cachedVisibleSize = undefined;
            container.classList.add('visible');
        }
        else {
            this._size = 0;
            this._cachedVisibleSize = size.cachedVisibleSize;
        }
    }
    set size(size) {
        this._size = size;
    }
    get size() {
        return this._size;
    }
    get visible() {
        return typeof this._cachedVisibleSize === 'undefined';
    }
    setVisible(visible, size) {
        var _a, _b;
        if (visible === this.visible) {
            return;
        }
        if (visible) {
            this.size = clamp(this._cachedVisibleSize, this.viewMinimumSize, this.viewMaximumSize);
            this._cachedVisibleSize = undefined;
        }
        else {
            this._cachedVisibleSize = typeof size === 'number' ? size : this.size;
            this.size = 0;
        }
        this.container.classList.toggle('visible', visible);
        (_b = (_a = this.view).setVisible) === null || _b === void 0 ? void 0 : _b.call(_a, visible);
    }
    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 snap() { return !!this.view.snap; }
    set enabled(enabled) {
        this.container.style.pointerEvents = enabled ? '' : 'none';
    }
    layout(offset, layoutContext) {
        this.layoutContainer(offset);
        this.view.layout(this.size, offset, layoutContext);
    }
    dispose() {
        this.disposable.dispose();
        return this.view;
    }
}
class VerticalViewItem extends ViewItem {
    layoutContainer(offset) {
        this.container.style.top = `${offset}px`;
        this.container.style.height = `${this.size}px`;
    }
}
class HorizontalViewItem extends ViewItem {
    layoutContainer(offset) {
        this.container.style.left = `${offset}px`;
        this.container.style.width = `${this.size}px`;
    }
}
var State;
(function (State) {
    State[State["Idle"] = 0] = "Idle";
    State[State["Busy"] = 1] = "Busy";
})(State || (State = {}));
var Sizing;
(function (Sizing) {
    /**
     * When adding or removing views, distribute the delta space among
     * all other views.
     */
    Sizing.Distribute = { type: 'distribute' };
    /**
     * When adding or removing views, split the delta space with another
     * specific view, indexed by the provided `index`.
     */
    function Split(index) { return { type: 'split', index }; }
    Sizing.Split = Split;
    /**
     * When adding or removing views, assume the view is invisible.
     */
    function Invisible(cachedVisibleSize) { return { type: 'invisible', cachedVisibleSize }; }
    Sizing.Invisible = Invisible;
})(Sizing || (Sizing = {}));
/**
 * The {@link SplitView} is the UI component which implements a one dimensional
 * flex-like layout algorithm for a collection of {@link IView} instances, which
 * are essentially HTMLElement instances with the following size constraints:
 *
 * - {@link IView.minimumSize}
 * - {@link IView.maximumSize}
 * - {@link IView.priority}
 * - {@link IView.snap}
 *
 * In case the SplitView doesn't have enough size to fit all views, it will overflow
 * its content with a scrollbar.
 *
 * In between each pair of views there will be a {@link Sash} allowing the user
 * to resize the views, making sure the constraints are respected.
 *
 * An optional {@link TLayoutContext layout context type} may be used in order to
 * pass along layout contextual data from the {@link SplitView.layout} method down
 * to each view's {@link IView.layout} calls.
 *
 * Features:
 * - Flex-like layout algorithm
 * - Snap support
 * - Orthogonal sash support, for corner sashes
 * - View hide/show support
 * - View swap/move support
 * - Alt key modifier behavior, macOS style
 */
class SplitView extends Disposable {
    /**
     * Create a new {@link SplitView} instance.
     */
    constructor(container, options = {}) {
        var _a, _b, _c, _d, _e;
        super();
        this.size = 0;
        this.contentSize = 0;
        this.proportions = undefined;
        this.viewItems = [];
        this.sashItems = [];
        this.state = State.Idle;
        this._onDidSashChange = this._register(new Emitter());
        this._onDidSashReset = this._register(new Emitter());
        this._startSnappingEnabled = true;
        this._endSnappingEnabled = true;
        /**
         * Fires whenever the user resizes a {@link Sash sash}.
         */
        this.onDidSashChange = this._onDidSashChange.event;
        /**
         * Fires whenever the user double clicks a {@link Sash sash}.
         */
        this.onDidSashReset = this._onDidSashReset.event;
        this.orientation = (_a = options.orientation) !== null && _a !== void 0 ? _a : 0 /* Orientation.VERTICAL */;
        this.inverseAltBehavior = (_b = options.inverseAltBehavior) !== null && _b !== void 0 ? _b : false;
        this.proportionalLayout = (_c = options.proportionalLayout) !== null && _c !== void 0 ? _c : true;
        this.getSashOrthogonalSize = options.getSashOrthogonalSize;
        this.el = document.createElement('div');
        this.el.classList.add('monaco-split-view2');
        this.el.classList.add(this.orientation === 0 /* Orientation.VERTICAL */ ? 'vertical' : 'horizontal');
        container.appendChild(this.el);
        this.sashContainer = append(this.el, dom_$('.sash-container'));
        this.viewContainer = dom_$('.split-view-container');
        this.scrollable = new Scrollable({
            forceIntegerValues: true,
            smoothScrollDuration: 125,
            scheduleAtNextAnimationFrame: scheduleAtNextAnimationFrame
        });
        this.scrollableElement = this._register(new SmoothScrollableElement(this.viewContainer, {
            vertical: this.orientation === 0 /* Orientation.VERTICAL */ ? ((_d = options.scrollbarVisibility) !== null && _d !== void 0 ? _d : 1 /* ScrollbarVisibility.Auto */) : 2 /* ScrollbarVisibility.Hidden */,
            horizontal: this.orientation === 1 /* Orientation.HORIZONTAL */ ? ((_e = options.scrollbarVisibility) !== null && _e !== void 0 ? _e : 1 /* ScrollbarVisibility.Auto */) : 2 /* ScrollbarVisibility.Hidden */
        }, this.scrollable));
        this.onDidScroll = this.scrollableElement.onScroll;
        this._register(this.onDidScroll(e => {
            this.viewContainer.scrollTop = e.scrollTop;
            this.viewContainer.scrollLeft = e.scrollLeft;
        }));
        append(this.el, this.scrollableElement.getDomNode());
        this.style(options.styles || splitview_defaultStyles);
        // We have an existing set of view, add them now
        if (options.descriptor) {
            this.size = options.descriptor.size;
            options.descriptor.views.forEach((viewDescriptor, index) => {
                const sizing = isUndefined(viewDescriptor.visible) || viewDescriptor.visible ? viewDescriptor.size : { type: 'invisible', cachedVisibleSize: viewDescriptor.size };
                const view = viewDescriptor.view;
                this.doAddView(view, sizing, index, true);
            });
            // Initialize content size and proportions for first layout
            this.contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
            this.saveProportions();
        }
    }
    get orthogonalStartSash() { return this._orthogonalStartSash; }
    get orthogonalEndSash() { return this._orthogonalEndSash; }
    get startSnappingEnabled() { return this._startSnappingEnabled; }
    get endSnappingEnabled() { return this._endSnappingEnabled; }
    /**
     * A reference to a sash, perpendicular to all sashes in this {@link SplitView},
     * 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._orthogonalStartSash = sash;
    }
    /**
     * A reference to a sash, perpendicular to all sashes in this {@link SplitView},
     * 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._orthogonalEndSash = sash;
    }
    /**
     * Enable/disable snapping at the beginning of this {@link SplitView}.
     */
    set startSnappingEnabled(startSnappingEnabled) {
        if (this._startSnappingEnabled === startSnappingEnabled) {
            return;
        }
        this._startSnappingEnabled = startSnappingEnabled;
        this.updateSashEnablement();
    }
    /**
     * Enable/disable snapping at the end of this {@link SplitView}.
     */
    set endSnappingEnabled(endSnappingEnabled) {
        if (this._endSnappingEnabled === endSnappingEnabled) {
            return;
        }
        this._endSnappingEnabled = endSnappingEnabled;
        this.updateSashEnablement();
    }
    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 SplitView}.
     *
     * @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.viewItems.length, skipLayout) {
        this.doAddView(view, size, index, skipLayout);
    }
    /**
     * Layout the {@link SplitView}.
     *
     * @param size The entire size of the {@link SplitView}.
     * @param layoutContext An optional layout context to pass along to {@link IView views}.
     */
    layout(size, layoutContext) {
        const previousSize = Math.max(this.size, this.contentSize);
        this.size = size;
        this.layoutContext = layoutContext;
        if (!this.proportions) {
            const indexes = range(this.viewItems.length);
            const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 1 /* LayoutPriority.Low */);
            const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* LayoutPriority.High */);
            this.resize(this.viewItems.length - 1, size - previousSize, undefined, lowPriorityIndexes, highPriorityIndexes);
        }
        else {
            for (let i = 0; i < this.viewItems.length; i++) {
                const item = this.viewItems[i];
                item.size = clamp(Math.round(this.proportions[i] * size), item.minimumSize, item.maximumSize);
            }
        }
        this.distributeEmptySpace();
        this.layoutViews();
    }
    saveProportions() {
        if (this.proportionalLayout && this.contentSize > 0) {
            this.proportions = this.viewItems.map(i => i.size / this.contentSize);
        }
    }
    onSashStart({ sash, start, alt }) {
        for (const item of this.viewItems) {
            item.enabled = false;
        }
        const index = this.sashItems.findIndex(item => item.sash === sash);
        // This way, we can press Alt while we resize a sash, macOS style!
        const disposable = combinedDisposable(addDisposableListener(document.body, 'keydown', e => resetSashDragState(this.sashDragState.current, e.altKey)), addDisposableListener(document.body, 'keyup', () => resetSashDragState(this.sashDragState.current, false)));
        const resetSashDragState = (start, alt) => {
            const sizes = this.viewItems.map(i => i.size);
            let minDelta = Number.NEGATIVE_INFINITY;
            let maxDelta = Number.POSITIVE_INFINITY;
            if (this.inverseAltBehavior) {
                alt = !alt;
            }
            if (alt) {
                // When we're using the last sash with Alt, we're resizing
                // the view to the left/up, instead of right/down as usual
                // Thus, we must do the inverse of the usual
                const isLastSash = index === this.sashItems.length - 1;
                if (isLastSash) {
                    const viewItem = this.viewItems[index];
                    minDelta = (viewItem.minimumSize - viewItem.size) / 2;
                    maxDelta = (viewItem.maximumSize - viewItem.size) / 2;
                }
                else {
                    const viewItem = this.viewItems[index + 1];
                    minDelta = (viewItem.size - viewItem.maximumSize) / 2;
                    maxDelta = (viewItem.size - viewItem.minimumSize) / 2;
                }
            }
            let snapBefore;
            let snapAfter;
            if (!alt) {
                const upIndexes = range(index, -1);
                const downIndexes = range(index + 1, this.viewItems.length);
                const minDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].minimumSize - sizes[i]), 0);
                const maxDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].viewMaximumSize - sizes[i]), 0);
                const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].minimumSize), 0);
                const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].viewMaximumSize), 0);
                const minDelta = Math.max(minDeltaUp, minDeltaDown);
                const maxDelta = Math.min(maxDeltaDown, maxDeltaUp);
                const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
                const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
                if (typeof snapBeforeIndex === 'number') {
                    const viewItem = this.viewItems[snapBeforeIndex];
                    const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
                    snapBefore = {
                        index: snapBeforeIndex,
                        limitDelta: viewItem.visible ? minDelta - halfSize : minDelta + halfSize,
                        size: viewItem.size
                    };
                }
                if (typeof snapAfterIndex === 'number') {
                    const viewItem = this.viewItems[snapAfterIndex];
                    const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
                    snapAfter = {
                        index: snapAfterIndex,
                        limitDelta: viewItem.visible ? maxDelta + halfSize : maxDelta - halfSize,
                        size: viewItem.size
                    };
                }
            }
            this.sashDragState = { start, current: start, index, sizes, minDelta, maxDelta, alt, snapBefore, snapAfter, disposable };
        };
        resetSashDragState(start, alt);
    }
    onSashChange({ current }) {
        const { index, start, sizes, alt, minDelta, maxDelta, snapBefore, snapAfter } = this.sashDragState;
        this.sashDragState.current = current;
        const delta = current - start;
        const newDelta = this.resize(index, delta, sizes, undefined, undefined, minDelta, maxDelta, snapBefore, snapAfter);
        if (alt) {
            const isLastSash = index === this.sashItems.length - 1;
            const newSizes = this.viewItems.map(i => i.size);
            const viewItemIndex = isLastSash ? index : index + 1;
            const viewItem = this.viewItems[viewItemIndex];
            const newMinDelta = viewItem.size - viewItem.maximumSize;
            const newMaxDelta = viewItem.size - viewItem.minimumSize;
            const resizeIndex = isLastSash ? index - 1 : index + 1;
            this.resize(resizeIndex, -newDelta, newSizes, undefined, undefined, newMinDelta, newMaxDelta);
        }
        this.distributeEmptySpace();
        this.layoutViews();
    }
    onSashEnd(index) {
        this._onDidSashChange.fire(index);
        this.sashDragState.disposable.dispose();
        this.saveProportions();
        for (const item of this.viewItems) {
            item.enabled = true;
        }
    }
    onViewChange(item, size) {
        const index = this.viewItems.indexOf(item);
        if (index < 0 || index >= this.viewItems.length) {
            return;
        }
        size = typeof size === 'number' ? size : item.size;
        size = clamp(size, item.minimumSize, item.maximumSize);
        if (this.inverseAltBehavior && index > 0) {
            // In this case, we want the view to grow or shrink both sides equally
            // so we just resize the "left" side by half and let `resize` do the clamping magic
            this.resize(index - 1, Math.floor((item.size - size) / 2));
            this.distributeEmptySpace();
            this.layoutViews();
        }
        else {
            item.size = size;
            this.relayout([index], undefined);
        }
    }
    /**
     * Resize a {@link IView view} within the {@link SplitView}.
     *
     * @param index The {@link IView view} index.
     * @param size The {@link IView view} size.
     */
    resizeView(index, size) {
        if (this.state !== State.Idle) {
            throw new Error('Cant modify splitview');
        }
        this.state = State.Busy;
        if (index < 0 || index >= this.viewItems.length) {
            return;
        }
        const indexes = range(this.viewItems.length).filter(i => i !== index);
        const lowPriorityIndexes = [...indexes.filter(i => this.viewItems[i].priority === 1 /* LayoutPriority.Low */), index];
        const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* LayoutPriority.High */);
        const item = this.viewItems[index];
        size = Math.round(size);
        size = clamp(size, item.minimumSize, Math.min(item.maximumSize, this.size));
        item.size = size;
        this.relayout(lowPriorityIndexes, highPriorityIndexes);
        this.state = State.Idle;
    }
    /**
     * Distribute the entire {@link SplitView} size among all {@link IView views}.
     */
    distributeViewSizes() {
        const flexibleViewItems = [];
        let flexibleSize = 0;
        for (const item of this.viewItems) {
            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 = clamp(size, item.minimumSize, item.maximumSize);
        }
        const indexes = range(this.viewItems.length);
        const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 1 /* LayoutPriority.Low */);
        const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* LayoutPriority.High */);
        this.relayout(lowPriorityIndexes, highPriorityIndexes);
    }
    /**
     * Returns the size of a {@link IView view}.
     */
    getViewSize(index) {
        if (index < 0 || index >= this.viewItems.length) {
            return -1;
        }
        return this.viewItems[index].size;
    }
    doAddView(view, size, index = this.viewItems.length, skipLayout) {
        if (this.state !== State.Idle) {
            throw new Error('Cant modify splitview');
        }
        this.state = State.Busy;
        // Add view
        const container = dom_$('.split-view-view');
        if (index === this.viewItems.length) {
            this.viewContainer.appendChild(container);
        }
        else {
            this.viewContainer.insertBefore(container, this.viewContainer.children.item(index));
        }
        const onChangeDisposable = view.onDidChange(size => this.onViewChange(item, size));
        const containerDisposable = toDisposable(() => this.viewContainer.removeChild(container));
        const disposable = combinedDisposable(onChangeDisposable, containerDisposable);
        let viewSize;
        if (typeof size === 'number') {
            viewSize = size;
        }
        else 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 /* Orientation.VERTICAL */
            ? new VerticalViewItem(container, view, viewSize, disposable)
            : new HorizontalViewItem(container, view, viewSize, disposable);
        this.viewItems.splice(index, 0, item);
        // Add sash
        if (this.viewItems.length > 1) {
            const opts = { orthogonalStartSash: this.orthogonalStartSash, orthogonalEndSash: this.orthogonalEndSash };
            const sash = this.orientation === 0 /* Orientation.VERTICAL */
                ? new Sash(this.sashContainer, { getHorizontalSashTop: s => this.getSashPosition(s), getHorizontalSashWidth: this.getSashOrthogonalSize }, Object.assign(Object.assign({}, opts), { orientation: 1 /* Orientation.HORIZONTAL */ }))
                : new Sash(this.sashContainer, { getVerticalSashLeft: s => this.getSashPosition(s), getVerticalSashHeight: this.getSashOrthogonalSize }, Object.assign(Object.assign({}, opts), { orientation: 0 /* Orientation.VERTICAL */ }));
            const sashEventMapper = this.orientation === 0 /* Orientation.VERTICAL */
                ? (e) => ({ sash, start: e.startY, current: e.currentY, alt: e.altKey })
                : (e) => ({ sash, start: e.startX, current: e.currentX, alt: e.altKey });
            const onStart = Event.map(sash.onDidStart, sashEventMapper);
            const onStartDisposable = onStart(this.onSashStart, this);
            const onChange = Event.map(sash.onDidChange, sashEventMapper);
            const onChangeDisposable = onChange(this.onSashChange, this);
            const onEnd = Event.map(sash.onDidEnd, () => this.sashItems.findIndex(item => item.sash === sash));
            const onEndDisposable = onEnd(this.onSashEnd, this);
            const onDidResetDisposable = sash.onDidReset(() => {
                const index = this.sashItems.findIndex(item => item.sash === sash);
                const upIndexes = range(index, -1);
                const downIndexes = range(index + 1, this.viewItems.length);
                const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
                const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
                if (typeof snapBeforeIndex === 'number' && !this.viewItems[snapBeforeIndex].visible) {
                    return;
                }
                if (typeof snapAfterIndex === 'number' && !this.viewItems[snapAfterIndex].visible) {
                    return;
                }
                this._onDidSashReset.fire(index);
            });
            const disposable = combinedDisposable(onStartDisposable, onChangeDisposable, onEndDisposable, onDidResetDisposable, sash);
            const sashItem = { sash, disposable };
            this.sashItems.splice(index - 1, 0, sashItem);
        }
        container.appendChild(view.element);
        let highPriorityIndexes;
        if (typeof size !== 'number' && size.type === 'split') {
            highPriorityIndexes = [size.index];
        }
        if (!skipLayout) {
            this.relayout([index], highPriorityIndexes);
        }
        this.state = State.Idle;
        if (!skipLayout && typeof size !== 'number' && size.type === 'distribute') {
            this.distributeViewSizes();
        }
    }
    relayout(lowPriorityIndexes, highPriorityIndexes) {
        const contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
        this.resize(this.viewItems.length - 1, this.size - contentSize, undefined, lowPriorityIndexes, highPriorityIndexes);
        this.distributeEmptySpace();
        this.layoutViews();
        this.saveProportions();
    }
    resize(index, delta, sizes = this.viewItems.map(i => i.size), lowPriorityIndexes, highPriorityIndexes, overloadMinDelta = Number.NEGATIVE_INFINITY, overloadMaxDelta = Number.POSITIVE_INFINITY, snapBefore, snapAfter) {
        if (index < 0 || index >= this.viewItems.length) {
            return 0;
        }
        const upIndexes = range(index, -1);
        const downIndexes = range(index + 1, this.viewItems.length);
        if (highPriorityIndexes) {
            for (const index of highPriorityIndexes) {
                pushToStart(upIndexes, index);
                pushToStart(downIndexes, index);
            }
        }
        if (lowPriorityIndexes) {
            for (const index of lowPriorityIndexes) {
                pushToEnd(upIndexes, index);
                pushToEnd(downIndexes, index);
            }
        }
        const upItems = upIndexes.map(i => this.viewItems[i]);
        const upSizes = upIndexes.map(i => sizes[i]);
        const downItems = downIndexes.map(i => this.viewItems[i]);
        const downSizes = downIndexes.map(i => sizes[i]);
        const minDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].minimumSize - sizes[i]), 0);
        const maxDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].maximumSize - sizes[i]), 0);
        const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].minimumSize), 0);
        const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].maximumSize), 0);
        const minDelta = Math.max(minDeltaUp, minDeltaDown, overloadMinDelta);
        const maxDelta = Math.min(maxDeltaDown, maxDeltaUp, overloadMaxDelta);
        let snapped = false;
        if (snapBefore) {
            const snapView = this.viewItems[snapBefore.index];
            const visible = delta >= snapBefore.limitDelta;
            snapped = visible !== snapView.visible;
            snapView.setVisible(visible, snapBefore.size);
        }
        if (!snapped && snapAfter) {
            const snapView = this.viewItems[snapAfter.index];
            const visible = delta < snapAfter.limitDelta;
            snapped = visible !== snapView.visible;
            snapView.setVisible(visible, snapAfter.size);
        }
        if (snapped) {
            return this.resize(index, delta, sizes, lowPriorityIndexes, highPriorityIndexes, overloadMinDelta, overloadMaxDelta);
        }
        delta = clamp(delta, minDelta, maxDelta);
        for (let i = 0, deltaUp = delta; i < upItems.length; i++) {
            const item = upItems[i];
            const size = clamp(upSizes[i] + deltaUp, item.minimumSize, item.maximumSize);
            const viewDelta = size - upSizes[i];
            deltaUp -= viewDelta;
            item.size = size;
        }
        for (let i = 0, deltaDown = delta; i < downItems.length; i++) {
            const item = downItems[i];
            const size = clamp(downSizes[i] - deltaDown, item.minimumSize, item.maximumSize);
            const viewDelta = size - downSizes[i];
            deltaDown += viewDelta;
            item.size = size;
        }
        return delta;
    }
    distributeEmptySpace(lowPriorityIndex) {
        const contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
        let emptyDelta = this.size - contentSize;
        const indexes = range(this.viewItems.length - 1, -1);
        const lowPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 1 /* LayoutPriority.Low */);
        const highPriorityIndexes = indexes.filter(i => this.viewItems[i].priority === 2 /* LayoutPriority.High */);
        for (const index of highPriorityIndexes) {
            pushToStart(indexes, index);
        }
        for (const index of lowPriorityIndexes) {
            pushToEnd(indexes, index);
        }
        if (typeof lowPriorityIndex === 'number') {
            pushToEnd(indexes, lowPriorityIndex);
        }
        for (let i = 0; emptyDelta !== 0 && i < indexes.length; i++) {
            const item = this.viewItems[indexes[i]];
            const size = clamp(item.size + emptyDelta, item.minimumSize, item.maximumSize);
            const viewDelta = size - item.size;
            emptyDelta -= viewDelta;
            item.size = size;
        }
    }
    layoutViews() {
        // Save new content size
        this.contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
        // Layout views
        let offset = 0;
        for (const viewItem of this.viewItems) {
            viewItem.layout(offset, this.layoutContext);
            offset += viewItem.size;
        }
        // Layout sashes
        this.sashItems.forEach(item => item.sash.layout());
        this.updateSashEnablement();
        this.updateScrollableElement();
    }
    updateScrollableElement() {
        if (this.orientation === 0 /* Orientation.VERTICAL */) {
            this.scrollableElement.setScrollDimensions({
                height: this.size,
                scrollHeight: this.contentSize
            });
        }
        else {
            this.scrollableElement.setScrollDimensions({
                width: this.size,
                scrollWidth: this.contentSize
            });
        }
    }
    updateSashEnablement() {
        let previous = false;
        const collapsesDown = this.viewItems.map(i => previous = (i.size - i.minimumSize > 0) || previous);
        previous = false;
        const expandsDown = this.viewItems.map(i => previous = (i.maximumSize - i.size > 0) || previous);
        const reverseViews = [...this.viewItems].reverse();
        previous = false;
        const collapsesUp = reverseViews.map(i => previous = (i.size - i.minimumSize > 0) || previous).reverse();
        previous = false;
        const expandsUp = reverseViews.map(i => previous = (i.maximumSize - i.size > 0) || previous).reverse();
        let position = 0;
        for (let index = 0; index < this.sashItems.length; index++) {
            const { sash } = this.sashItems[index];
            const viewItem = this.viewItems[index];
            position += viewItem.size;
            const min = !(collapsesDown[index] && expandsUp[index + 1]);
            const max = !(expandsDown[index] && collapsesUp[index + 1]);
            if (min && max) {
                const upIndexes = range(index, -1);
                const downIndexes = range(index + 1, this.viewItems.length);
                const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
                const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
                const snappedBefore = typeof snapBeforeIndex === 'number' && !this.viewItems[snapBeforeIndex].visible;
                const snappedAfter = typeof snapAfterIndex === 'number' && !this.viewItems[snapAfterIndex].visible;
                if (snappedBefore && collapsesUp[index] && (position > 0 || this.startSnappingEnabled)) {
                    sash.state = 1 /* SashState.AtMinimum */;
                }
                else if (snappedAfter && collapsesDown[index] && (position < this.contentSize || this.endSnappingEnabled)) {
                    sash.state = 2 /* SashState.AtMaximum */;
                }
                else {
                    sash.state = 0 /* SashState.Disabled */;
                }
            }
            else if (min && !max) {
                sash.state = 1 /* SashState.AtMinimum */;
            }
            else if (!min && max) {
                sash.state = 2 /* SashState.AtMaximum */;
            }
            else {
                sash.state = 3 /* SashState.Enabled */;
            }
        }
    }
    getSashPosition(sash) {
        let position = 0;
        for (let i = 0; i < this.sashItems.length; i++) {
            position += this.viewItems[i].size;
            if (this.sashItems[i].sash === sash) {
                return position;
            }
        }
        return 0;
    }
    findFirstSnapIndex(indexes) {
        // visible views first
        for (const index of indexes) {
            const viewItem = this.viewItems[index];
            if (!viewItem.visible) {
                continue;
            }
            if (viewItem.snap) {
                return index;
            }
        }
        // then, hidden views
        for (const index of indexes) {
            const viewItem = this.viewItems[index];
            if (viewItem.visible && viewItem.maximumSize - viewItem.minimumSize > 0) {
                return undefined;
            }
            if (!viewItem.visible && viewItem.snap) {
                return index;
            }
        }
        return undefined;
    }
    dispose() {
        super.dispose();
        dispose(this.viewItems);
        this.viewItems = [];
        this.sashItems.forEach(i => i.disposable.dispose());
        this.sashItems = [];
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/table/table.css
var table = __webpack_require__(60331);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/table/table.css

      
      
      
      
      
      
      
      
      

var table_options = {};

table_options.styleTagTransform = (styleTagTransform_default());
table_options.setAttributes = (setAttributesWithoutAttributes_default());

      table_options.insert = insertBySelector_default().bind(null, "head");
    
table_options.domAPI = (styleDomAPI_default());
table_options.insertStyleElement = (insertStyleElement_default());

var table_update = injectStylesIntoStyleTag_default()(table/* default */.A, table_options);




       /* harmony default export */ const table_table = (table/* default */.A && table/* default */.A.locals ? table/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/table/tableWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class TableListRenderer {
    constructor(columns, renderers, getColumnSize) {
        this.columns = columns;
        this.getColumnSize = getColumnSize;
        this.templateId = TableListRenderer.TemplateId;
        this.renderedTemplates = new Set();
        const rendererMap = new Map(renderers.map(r => [r.templateId, r]));
        this.renderers = [];
        for (const column of columns) {
            const renderer = rendererMap.get(column.templateId);
            if (!renderer) {
                throw new Error(`Table cell renderer for template id ${column.templateId} not found.`);
            }
            this.renderers.push(renderer);
        }
    }
    renderTemplate(container) {
        const rowContainer = append(container, dom_$('.monaco-table-tr'));
        const cellContainers = [];
        const cellTemplateData = [];
        for (let i = 0; i < this.columns.length; i++) {
            const renderer = this.renderers[i];
            const cellContainer = append(rowContainer, dom_$('.monaco-table-td', { 'data-col-index': i }));
            cellContainer.style.width = `${this.getColumnSize(i)}px`;
            cellContainers.push(cellContainer);
            cellTemplateData.push(renderer.renderTemplate(cellContainer));
        }
        const result = { container, cellContainers, cellTemplateData };
        this.renderedTemplates.add(result);
        return result;
    }
    renderElement(element, index, templateData, height) {
        for (let i = 0; i < this.columns.length; i++) {
            const column = this.columns[i];
            const cell = column.project(element);
            const renderer = this.renderers[i];
            renderer.renderElement(cell, index, templateData.cellTemplateData[i], height);
        }
    }
    disposeElement(element, index, templateData, height) {
        for (let i = 0; i < this.columns.length; i++) {
            const renderer = this.renderers[i];
            if (renderer.disposeElement) {
                const column = this.columns[i];
                const cell = column.project(element);
                renderer.disposeElement(cell, index, templateData.cellTemplateData[i], height);
            }
        }
    }
    disposeTemplate(templateData) {
        for (let i = 0; i < this.columns.length; i++) {
            const renderer = this.renderers[i];
            renderer.disposeTemplate(templateData.cellTemplateData[i]);
        }
        clearNode(templateData.container);
        this.renderedTemplates.delete(templateData);
    }
    layoutColumn(index, size) {
        for (const { cellContainers } of this.renderedTemplates) {
            cellContainers[index].style.width = `${size}px`;
        }
    }
}
TableListRenderer.TemplateId = 'row';
function asListVirtualDelegate(delegate) {
    return {
        getHeight(row) { return delegate.getHeight(row); },
        getTemplateId() { return TableListRenderer.TemplateId; },
    };
}
class ColumnHeader {
    constructor(column, index) {
        this.column = column;
        this.index = index;
        this._onDidLayout = new Emitter();
        this.onDidLayout = this._onDidLayout.event;
        this.element = dom_$('.monaco-table-th', { 'data-col-index': index, title: column.tooltip }, column.label);
    }
    get minimumSize() { var _a; return (_a = this.column.minimumWidth) !== null && _a !== void 0 ? _a : 120; }
    get maximumSize() { var _a; return (_a = this.column.maximumWidth) !== null && _a !== void 0 ? _a : Number.POSITIVE_INFINITY; }
    get onDidChange() { var _a; return (_a = this.column.onDidChangeWidthConstraints) !== null && _a !== void 0 ? _a : Event.None; }
    layout(size) {
        this._onDidLayout.fire([this.index, size]);
    }
}
class Table {
    constructor(user, container, virtualDelegate, columns, renderers, _options) {
        this.virtualDelegate = virtualDelegate;
        this.domId = `table_id_${++Table.InstanceCount}`;
        this.disposables = new DisposableStore();
        this.cachedWidth = 0;
        this.cachedHeight = 0;
        this.domNode = append(container, dom_$(`.monaco-table.${this.domId}`));
        const headers = columns.map((c, i) => new ColumnHeader(c, i));
        const descriptor = {
            size: headers.reduce((a, b) => a + b.column.weight, 0),
            views: headers.map(view => ({ size: view.column.weight, view }))
        };
        this.splitview = this.disposables.add(new SplitView(this.domNode, {
            orientation: 1 /* Orientation.HORIZONTAL */,
            scrollbarVisibility: 2 /* ScrollbarVisibility.Hidden */,
            getSashOrthogonalSize: () => this.cachedHeight,
            descriptor
        }));
        this.splitview.el.style.height = `${virtualDelegate.headerRowHeight}px`;
        this.splitview.el.style.lineHeight = `${virtualDelegate.headerRowHeight}px`;
        const renderer = new TableListRenderer(columns, renderers, i => this.splitview.getViewSize(i));
        this.list = this.disposables.add(new List(user, this.domNode, asListVirtualDelegate(virtualDelegate), [renderer], _options));
        Event.any(...headers.map(h => h.onDidLayout))(([index, size]) => renderer.layoutColumn(index, size), null, this.disposables);
        this.splitview.onDidSashReset(index => {
            const totalWeight = columns.reduce((r, c) => r + c.weight, 0);
            const size = columns[index].weight / totalWeight * this.cachedWidth;
            this.splitview.resizeView(index, size);
        }, null, this.disposables);
        this.styleElement = createStyleSheet(this.domNode);
        this.style({});
    }
    get onDidChangeFocus() { return this.list.onDidChangeFocus; }
    get onDidChangeSelection() { return this.list.onDidChangeSelection; }
    get onMouseDblClick() { return this.list.onMouseDblClick; }
    get onPointer() { return this.list.onPointer; }
    get onDidFocus() { return this.list.onDidFocus; }
    get onDidDispose() { return this.list.onDidDispose; }
    updateOptions(options) {
        this.list.updateOptions(options);
    }
    splice(start, deleteCount, elements = []) {
        this.list.splice(start, deleteCount, elements);
    }
    getHTMLElement() {
        return this.domNode;
    }
    style(styles) {
        const content = [];
        content.push(`.monaco-table.${this.domId} > .monaco-split-view2 .monaco-sash.vertical::before {
			top: ${this.virtualDelegate.headerRowHeight + 1}px;
			height: calc(100% - ${this.virtualDelegate.headerRowHeight}px);
		}`);
        this.styleElement.textContent = content.join('\n');
        this.list.style(styles);
    }
    getSelectedElements() {
        return this.list.getSelectedElements();
    }
    getSelection() {
        return this.list.getSelection();
    }
    getFocus() {
        return this.list.getFocus();
    }
    dispose() {
        this.disposables.dispose();
    }
}
Table.InstanceCount = 0;

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/toggle/toggle.css
var toggle = __webpack_require__(61825);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/toggle/toggle.css

      
      
      
      
      
      
      
      
      

var toggle_options = {};

toggle_options.styleTagTransform = (styleTagTransform_default());
toggle_options.setAttributes = (setAttributesWithoutAttributes_default());

      toggle_options.insert = insertBySelector_default().bind(null, "head");
    
toggle_options.domAPI = (styleDomAPI_default());
toggle_options.insertStyleElement = (insertStyleElement_default());

var toggle_update = injectStylesIntoStyleTag_default()(toggle/* default */.A, toggle_options);




       /* harmony default export */ const toggle_toggle = (toggle/* default */.A && toggle/* default */.A.locals ? toggle/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/toggle/toggle.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





const defaultOpts = {
    inputActiveOptionBorder: Color.fromHex('#007ACC00'),
    inputActiveOptionForeground: Color.fromHex('#FFFFFF'),
    inputActiveOptionBackground: Color.fromHex('#0E639C50')
};
class Toggle extends Widget {
    constructor(opts) {
        super();
        this._onChange = this._register(new Emitter());
        this.onChange = this._onChange.event;
        this._onKeyDown = this._register(new Emitter());
        this.onKeyDown = this._onKeyDown.event;
        this._opts = Object.assign(Object.assign({}, defaultOpts), opts);
        this._checked = this._opts.isChecked;
        const classes = ['monaco-custom-toggle'];
        if (this._opts.icon) {
            this._icon = this._opts.icon;
            classes.push(...CSSIcon.asClassNameArray(this._icon));
        }
        if (this._opts.actionClassName) {
            classes.push(...this._opts.actionClassName.split(' '));
        }
        if (this._checked) {
            classes.push('checked');
        }
        this.domNode = document.createElement('div');
        this.domNode.title = this._opts.title;
        this.domNode.classList.add(...classes);
        if (!this._opts.notFocusable) {
            this.domNode.tabIndex = 0;
        }
        this.domNode.setAttribute('role', 'checkbox');
        this.domNode.setAttribute('aria-checked', String(this._checked));
        this.domNode.setAttribute('aria-label', this._opts.title);
        this.applyStyles();
        this.onclick(this.domNode, (ev) => {
            if (this.enabled) {
                this.checked = !this._checked;
                this._onChange.fire(false);
                ev.preventDefault();
            }
        });
        this.ignoreGesture(this.domNode);
        this.onkeydown(this.domNode, (keyboardEvent) => {
            if (keyboardEvent.keyCode === 10 /* KeyCode.Space */ || keyboardEvent.keyCode === 3 /* KeyCode.Enter */) {
                this.checked = !this._checked;
                this._onChange.fire(true);
                keyboardEvent.preventDefault();
                keyboardEvent.stopPropagation();
                return;
            }
            this._onKeyDown.fire(keyboardEvent);
        });
    }
    get enabled() {
        return this.domNode.getAttribute('aria-disabled') !== 'true';
    }
    focus() {
        this.domNode.focus();
    }
    get checked() {
        return this._checked;
    }
    set checked(newIsChecked) {
        this._checked = newIsChecked;
        this.domNode.setAttribute('aria-checked', String(this._checked));
        this.domNode.classList.toggle('checked', this._checked);
        this.applyStyles();
    }
    width() {
        return 2 /*margin left*/ + 2 /*border*/ + 2 /*padding*/ + 16 /* icon width */;
    }
    style(styles) {
        if (styles.inputActiveOptionBorder) {
            this._opts.inputActiveOptionBorder = styles.inputActiveOptionBorder;
        }
        if (styles.inputActiveOptionForeground) {
            this._opts.inputActiveOptionForeground = styles.inputActiveOptionForeground;
        }
        if (styles.inputActiveOptionBackground) {
            this._opts.inputActiveOptionBackground = styles.inputActiveOptionBackground;
        }
        this.applyStyles();
    }
    applyStyles() {
        if (this.domNode) {
            this.domNode.style.borderColor = this._checked && this._opts.inputActiveOptionBorder ? this._opts.inputActiveOptionBorder.toString() : '';
            this.domNode.style.color = this._checked && this._opts.inputActiveOptionForeground ? this._opts.inputActiveOptionForeground.toString() : 'inherit';
            this.domNode.style.backgroundColor = this._checked && this._opts.inputActiveOptionBackground ? this._opts.inputActiveOptionBackground.toString() : '';
        }
    }
    enable() {
        this.domNode.setAttribute('aria-disabled', String(false));
    }
    disable() {
        this.domNode.setAttribute('aria-disabled', String(true));
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/findinput/findInputToggles.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



const NLS_CASE_SENSITIVE_TOGGLE_LABEL = localize('caseDescription', "Match Case");
const NLS_WHOLE_WORD_TOGGLE_LABEL = localize('wordsDescription', "Match Whole Word");
const NLS_REGEX_TOGGLE_LABEL = localize('regexDescription', "Use Regular Expression");
class CaseSensitiveToggle extends Toggle {
    constructor(opts) {
        super({
            icon: Codicon.caseSensitive,
            title: NLS_CASE_SENSITIVE_TOGGLE_LABEL + opts.appendTitle,
            isChecked: opts.isChecked,
            inputActiveOptionBorder: opts.inputActiveOptionBorder,
            inputActiveOptionForeground: opts.inputActiveOptionForeground,
            inputActiveOptionBackground: opts.inputActiveOptionBackground
        });
    }
}
class WholeWordsToggle extends Toggle {
    constructor(opts) {
        super({
            icon: Codicon.wholeWord,
            title: NLS_WHOLE_WORD_TOGGLE_LABEL + opts.appendTitle,
            isChecked: opts.isChecked,
            inputActiveOptionBorder: opts.inputActiveOptionBorder,
            inputActiveOptionForeground: opts.inputActiveOptionForeground,
            inputActiveOptionBackground: opts.inputActiveOptionBackground
        });
    }
}
class RegexToggle extends Toggle {
    constructor(opts) {
        super({
            icon: Codicon.regex,
            title: NLS_REGEX_TOGGLE_LABEL + opts.appendTitle,
            isChecked: opts.isChecked,
            inputActiveOptionBorder: opts.inputActiveOptionBorder,
            inputActiveOptionForeground: opts.inputActiveOptionForeground,
            inputActiveOptionBackground: opts.inputActiveOptionBackground
        });
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/navigator.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class ArrayNavigator {
    constructor(items, start = 0, end = items.length, index = start - 1) {
        this.items = items;
        this.start = start;
        this.end = end;
        this.index = index;
    }
    current() {
        if (this.index === this.start - 1 || this.index === this.end) {
            return null;
        }
        return this.items[this.index];
    }
    next() {
        this.index = Math.min(this.index + 1, this.end);
        return this.current();
    }
    previous() {
        this.index = Math.max(this.index - 1, this.start - 1);
        return this.current();
    }
    first() {
        this.index = this.start;
        return this.current();
    }
    last() {
        this.index = this.end - 1;
        return this.current();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/history.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class HistoryNavigator {
    constructor(history = [], limit = 10) {
        this._initialize(history);
        this._limit = limit;
        this._onChange();
    }
    getHistory() {
        return this._elements;
    }
    add(t) {
        this._history.delete(t);
        this._history.add(t);
        this._onChange();
    }
    next() {
        if (this._currentPosition() !== this._elements.length - 1) {
            return this._navigator.next();
        }
        return null;
    }
    previous() {
        if (this._currentPosition() !== 0) {
            return this._navigator.previous();
        }
        return null;
    }
    current() {
        return this._navigator.current();
    }
    first() {
        return this._navigator.first();
    }
    last() {
        return this._navigator.last();
    }
    has(t) {
        return this._history.has(t);
    }
    _onChange() {
        this._reduceToLimit();
        const elements = this._elements;
        this._navigator = new ArrayNavigator(elements, 0, elements.length, elements.length);
    }
    _reduceToLimit() {
        const data = this._elements;
        if (data.length > this._limit) {
            this._initialize(data.slice(data.length - this._limit));
        }
    }
    _currentPosition() {
        const currentElement = this._navigator.current();
        if (!currentElement) {
            return -1;
        }
        return this._elements.indexOf(currentElement);
    }
    _initialize(history) {
        this._history = new Set();
        for (const entry of history) {
            this._history.add(entry);
        }
    }
    get _elements() {
        const elements = [];
        this._history.forEach(e => elements.push(e));
        return elements;
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/inputbox/inputBox.css
var inputBox = __webpack_require__(1943);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/inputbox/inputBox.css

      
      
      
      
      
      
      
      
      

var inputBox_options = {};

inputBox_options.styleTagTransform = (styleTagTransform_default());
inputBox_options.setAttributes = (setAttributesWithoutAttributes_default());

      inputBox_options.insert = insertBySelector_default().bind(null, "head");
    
inputBox_options.domAPI = (styleDomAPI_default());
inputBox_options.insertStyleElement = (insertStyleElement_default());

var inputBox_update = injectStylesIntoStyleTag_default()(inputBox/* default */.A, inputBox_options);




       /* harmony default export */ const inputbox_inputBox = (inputBox/* default */.A && inputBox/* default */.A.locals ? inputBox/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/inputbox/inputBox.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/













const inputBox_$ = dom_$;
const inputBox_defaultOpts = {
    inputBackground: Color.fromHex('#3C3C3C'),
    inputForeground: Color.fromHex('#CCCCCC'),
    inputValidationInfoBorder: Color.fromHex('#55AAFF'),
    inputValidationInfoBackground: Color.fromHex('#063B49'),
    inputValidationWarningBorder: Color.fromHex('#B89500'),
    inputValidationWarningBackground: Color.fromHex('#352A05'),
    inputValidationErrorBorder: Color.fromHex('#BE1100'),
    inputValidationErrorBackground: Color.fromHex('#5A1D1D')
};
class InputBox extends Widget {
    constructor(container, contextViewProvider, options) {
        var _a;
        super();
        this.state = 'idle';
        this.maxHeight = Number.POSITIVE_INFINITY;
        this._onDidChange = this._register(new Emitter());
        this.onDidChange = this._onDidChange.event;
        this._onDidHeightChange = this._register(new Emitter());
        this.onDidHeightChange = this._onDidHeightChange.event;
        this.contextViewProvider = contextViewProvider;
        this.options = options || Object.create(null);
        mixin(this.options, inputBox_defaultOpts, false);
        this.message = null;
        this.placeholder = this.options.placeholder || '';
        this.tooltip = (_a = this.options.tooltip) !== null && _a !== void 0 ? _a : (this.placeholder || '');
        this.ariaLabel = this.options.ariaLabel || '';
        this.inputBackground = this.options.inputBackground;
        this.inputForeground = this.options.inputForeground;
        this.inputBorder = this.options.inputBorder;
        this.inputValidationInfoBorder = this.options.inputValidationInfoBorder;
        this.inputValidationInfoBackground = this.options.inputValidationInfoBackground;
        this.inputValidationInfoForeground = this.options.inputValidationInfoForeground;
        this.inputValidationWarningBorder = this.options.inputValidationWarningBorder;
        this.inputValidationWarningBackground = this.options.inputValidationWarningBackground;
        this.inputValidationWarningForeground = this.options.inputValidationWarningForeground;
        this.inputValidationErrorBorder = this.options.inputValidationErrorBorder;
        this.inputValidationErrorBackground = this.options.inputValidationErrorBackground;
        this.inputValidationErrorForeground = this.options.inputValidationErrorForeground;
        if (this.options.validationOptions) {
            this.validation = this.options.validationOptions.validation;
        }
        this.element = append(container, inputBox_$('.monaco-inputbox.idle'));
        const tagName = this.options.flexibleHeight ? 'textarea' : 'input';
        const wrapper = append(this.element, inputBox_$('.ibwrapper'));
        this.input = append(wrapper, inputBox_$(tagName + '.input.empty'));
        this.input.setAttribute('autocorrect', 'off');
        this.input.setAttribute('autocapitalize', 'off');
        this.input.setAttribute('spellcheck', 'false');
        this.onfocus(this.input, () => this.element.classList.add('synthetic-focus'));
        this.onblur(this.input, () => this.element.classList.remove('synthetic-focus'));
        if (this.options.flexibleHeight) {
            this.maxHeight = typeof this.options.flexibleMaxHeight === 'number' ? this.options.flexibleMaxHeight : Number.POSITIVE_INFINITY;
            this.mirror = append(wrapper, inputBox_$('div.mirror'));
            this.mirror.innerText = '\u00a0';
            this.scrollableElement = new ScrollableElement(this.element, { vertical: 1 /* ScrollbarVisibility.Auto */ });
            if (this.options.flexibleWidth) {
                this.input.setAttribute('wrap', 'off');
                this.mirror.style.whiteSpace = 'pre';
                this.mirror.style.wordWrap = 'initial';
            }
            append(container, this.scrollableElement.getDomNode());
            this._register(this.scrollableElement);
            // from ScrollableElement to DOM
            this._register(this.scrollableElement.onScroll(e => this.input.scrollTop = e.scrollTop));
            const onSelectionChange = this._register(new DomEmitter(document, 'selectionchange'));
            const onAnchoredSelectionChange = Event.filter(onSelectionChange.event, () => {
                const selection = document.getSelection();
                return (selection === null || selection === void 0 ? void 0 : selection.anchorNode) === wrapper;
            });
            // from DOM to ScrollableElement
            this._register(onAnchoredSelectionChange(this.updateScrollDimensions, this));
            this._register(this.onDidHeightChange(this.updateScrollDimensions, this));
        }
        else {
            this.input.type = this.options.type || 'text';
            this.input.setAttribute('wrap', 'off');
        }
        if (this.ariaLabel) {
            this.input.setAttribute('aria-label', this.ariaLabel);
        }
        if (this.placeholder && !this.options.showPlaceholderOnFocus) {
            this.setPlaceHolder(this.placeholder);
        }
        if (this.tooltip) {
            this.setTooltip(this.tooltip);
        }
        this.oninput(this.input, () => this.onValueChange());
        this.onblur(this.input, () => this.onBlur());
        this.onfocus(this.input, () => this.onFocus());
        this.ignoreGesture(this.input);
        setTimeout(() => this.updateMirror(), 0);
        // Support actions
        if (this.options.actions) {
            this.actionbar = this._register(new ActionBar(this.element));
            this.actionbar.push(this.options.actions, { icon: true, label: false });
        }
        this.applyStyles();
    }
    onBlur() {
        this._hideMessage();
        if (this.options.showPlaceholderOnFocus) {
            this.input.setAttribute('placeholder', '');
        }
    }
    onFocus() {
        this._showMessage();
        if (this.options.showPlaceholderOnFocus) {
            this.input.setAttribute('placeholder', this.placeholder || '');
        }
    }
    setPlaceHolder(placeHolder) {
        this.placeholder = placeHolder;
        this.input.setAttribute('placeholder', placeHolder);
    }
    setTooltip(tooltip) {
        this.tooltip = tooltip;
        this.input.title = tooltip;
    }
    setAriaLabel(label) {
        this.ariaLabel = label;
        if (label) {
            this.input.setAttribute('aria-label', this.ariaLabel);
        }
        else {
            this.input.removeAttribute('aria-label');
        }
    }
    getAriaLabel() {
        return this.ariaLabel;
    }
    get inputElement() {
        return this.input;
    }
    get value() {
        return this.input.value;
    }
    set value(newValue) {
        if (this.input.value !== newValue) {
            this.input.value = newValue;
            this.onValueChange();
        }
    }
    get height() {
        return typeof this.cachedHeight === 'number' ? this.cachedHeight : getTotalHeight(this.element);
    }
    focus() {
        this.input.focus();
    }
    blur() {
        this.input.blur();
    }
    hasFocus() {
        return document.activeElement === this.input;
    }
    select(range = null) {
        this.input.select();
        if (range) {
            this.input.setSelectionRange(range.start, range.end);
            if (range.end === this.input.value.length) {
                this.input.scrollLeft = this.input.scrollWidth;
            }
        }
    }
    isSelectionAtEnd() {
        return this.input.selectionEnd === this.input.value.length && this.input.selectionStart === this.input.selectionEnd;
    }
    enable() {
        this.input.removeAttribute('disabled');
    }
    disable() {
        this.blur();
        this.input.disabled = true;
        this._hideMessage();
    }
    get width() {
        return getTotalWidth(this.input);
    }
    set width(width) {
        if (this.options.flexibleHeight && this.options.flexibleWidth) {
            // textarea with horizontal scrolling
            let horizontalPadding = 0;
            if (this.mirror) {
                const paddingLeft = parseFloat(this.mirror.style.paddingLeft || '') || 0;
                const paddingRight = parseFloat(this.mirror.style.paddingRight || '') || 0;
                horizontalPadding = paddingLeft + paddingRight;
            }
            this.input.style.width = (width - horizontalPadding) + 'px';
        }
        else {
            this.input.style.width = width + 'px';
        }
        if (this.mirror) {
            this.mirror.style.width = width + 'px';
        }
    }
    set paddingRight(paddingRight) {
        // Set width to avoid hint text overlapping buttons
        this.input.style.width = `calc(100% - ${paddingRight}px)`;
        if (this.mirror) {
            this.mirror.style.paddingRight = paddingRight + 'px';
        }
    }
    updateScrollDimensions() {
        if (typeof this.cachedContentHeight !== 'number' || typeof this.cachedHeight !== 'number' || !this.scrollableElement) {
            return;
        }
        const scrollHeight = this.cachedContentHeight;
        const height = this.cachedHeight;
        const scrollTop = this.input.scrollTop;
        this.scrollableElement.setScrollDimensions({ scrollHeight, height });
        this.scrollableElement.setScrollPosition({ scrollTop });
    }
    showMessage(message, force) {
        this.message = 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.classForType(message.type));
        const styles = this.stylesForType(this.message.type);
        this.element.style.border = styles.border ? `1px solid ${styles.border}` : '';
        if (this.hasFocus() || force) {
            this._showMessage();
        }
    }
    hideMessage() {
        this.message = null;
        this.element.classList.remove('info');
        this.element.classList.remove('warning');
        this.element.classList.remove('error');
        this.element.classList.add('idle');
        this._hideMessage();
        this.applyStyles();
    }
    validate() {
        let errorMsg = null;
        if (this.validation) {
            errorMsg = this.validation(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 === null || errorMsg === void 0 ? void 0 : errorMsg.type;
    }
    stylesForType(type) {
        switch (type) {
            case 1 /* MessageType.INFO */: return { border: this.inputValidationInfoBorder, background: this.inputValidationInfoBackground, foreground: this.inputValidationInfoForeground };
            case 2 /* MessageType.WARNING */: return { border: this.inputValidationWarningBorder, background: this.inputValidationWarningBackground, foreground: this.inputValidationWarningForeground };
            default: return { border: this.inputValidationErrorBorder, background: this.inputValidationErrorBackground, foreground: this.inputValidationErrorForeground };
        }
    }
    classForType(type) {
        switch (type) {
            case 1 /* MessageType.INFO */: return 'info';
            case 2 /* MessageType.WARNING */: return 'warning';
            default: return 'error';
        }
    }
    _showMessage() {
        if (!this.contextViewProvider || !this.message) {
            return;
        }
        let div;
        const layout = () => div.style.width = getTotalWidth(this.element) + 'px';
        this.contextViewProvider.showContextView({
            getAnchor: () => this.element,
            anchorAlignment: 1 /* AnchorAlignment.RIGHT */,
            render: (container) => {
                if (!this.message) {
                    return null;
                }
                div = append(container, inputBox_$('.monaco-inputbox-container'));
                layout();
                const renderOptions = {
                    inline: true,
                    className: 'monaco-inputbox-message'
                };
                const spanElement = (this.message.formatContent
                    ? renderFormattedText(this.message.content, renderOptions)
                    : renderText(this.message.content, renderOptions));
                spanElement.classList.add(this.classForType(this.message.type));
                const styles = this.stylesForType(this.message.type);
                spanElement.style.backgroundColor = styles.background ? styles.background.toString() : '';
                spanElement.style.color = styles.foreground ? styles.foreground.toString() : '';
                spanElement.style.border = styles.border ? `1px solid ${styles.border}` : '';
                append(div, spanElement);
                return null;
            },
            onHide: () => {
                this.state = 'closed';
            },
            layout: layout
        });
        // ARIA Support
        let alertText;
        if (this.message.type === 3 /* MessageType.ERROR */) {
            alertText = localize('alertErrorMessage', "Error: {0}", this.message.content);
        }
        else if (this.message.type === 2 /* MessageType.WARNING */) {
            alertText = localize('alertWarningMessage', "Warning: {0}", this.message.content);
        }
        else {
            alertText = localize('alertInfoMessage', "Info: {0}", this.message.content);
        }
        aria_alert(alertText);
        this.state = 'open';
    }
    _hideMessage() {
        if (!this.contextViewProvider) {
            return;
        }
        if (this.state === 'open') {
            this.contextViewProvider.hideContextView();
        }
        this.state = 'idle';
    }
    onValueChange() {
        this._onDidChange.fire(this.value);
        this.validate();
        this.updateMirror();
        this.input.classList.toggle('empty', !this.value);
        if (this.state === 'open' && this.contextViewProvider) {
            this.contextViewProvider.layout();
        }
    }
    updateMirror() {
        if (!this.mirror) {
            return;
        }
        const value = this.value;
        const lastCharCode = value.charCodeAt(value.length - 1);
        const suffix = lastCharCode === 10 ? ' ' : '';
        const mirrorTextContent = (value + suffix)
            .replace(/\u000c/g, ''); // Don't measure with the form feed character, which messes up sizing
        if (mirrorTextContent) {
            this.mirror.textContent = value + suffix;
        }
        else {
            this.mirror.innerText = '\u00a0';
        }
        this.layout();
    }
    style(styles) {
        this.inputBackground = styles.inputBackground;
        this.inputForeground = styles.inputForeground;
        this.inputBorder = styles.inputBorder;
        this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
        this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
        this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
        this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
        this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
        this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
        this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
        this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
        this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
        this.applyStyles();
    }
    applyStyles() {
        const background = this.inputBackground ? this.inputBackground.toString() : '';
        const foreground = this.inputForeground ? this.inputForeground.toString() : '';
        const border = this.inputBorder ? this.inputBorder.toString() : '';
        this.element.style.backgroundColor = background;
        this.element.style.color = foreground;
        this.input.style.backgroundColor = 'inherit';
        this.input.style.color = foreground;
        this.element.style.borderWidth = border ? '1px' : '';
        this.element.style.borderStyle = border ? 'solid' : '';
        this.element.style.borderColor = border;
    }
    layout() {
        if (!this.mirror) {
            return;
        }
        const previousHeight = this.cachedContentHeight;
        this.cachedContentHeight = getTotalHeight(this.mirror);
        if (previousHeight !== this.cachedContentHeight) {
            this.cachedHeight = Math.min(this.cachedContentHeight, this.maxHeight);
            this.input.style.height = this.cachedHeight + 'px';
            this._onDidHeightChange.fire(this.cachedContentHeight);
        }
    }
    insertAtCursor(text) {
        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) + text + content.substr(end);
            inputElement.setSelectionRange(start + 1, start + 1);
            this.layout();
        }
    }
    dispose() {
        this._hideMessage();
        this.message = null;
        if (this.actionbar) {
            this.actionbar.dispose();
        }
        super.dispose();
    }
}
class HistoryInputBox extends InputBox {
    constructor(container, contextViewProvider, options) {
        const NLS_PLACEHOLDER_HISTORY_HINT = localize({ key: 'history.inputbox.hint', comment: ['Text will be prefixed with \u21C5 plus a single space, then used as a hint where input field keeps history'] }, "for history");
        const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX = ` or \u21C5 ${NLS_PLACEHOLDER_HISTORY_HINT}`;
        const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS = ` (\u21C5 ${NLS_PLACEHOLDER_HISTORY_HINT})`;
        super(container, contextViewProvider, options);
        this._onDidFocus = this._register(new Emitter());
        this.onDidFocus = this._onDidFocus.event;
        this._onDidBlur = this._register(new Emitter());
        this.onDidBlur = this._onDidBlur.event;
        this.history = new HistoryNavigator(options.history, 100);
        // Function to append the history suffix to the placeholder if necessary
        const addSuffix = () => {
            if (options.showHistoryHint && options.showHistoryHint() && !this.placeholder.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX) && !this.placeholder.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS) && this.history.getHistory().length) {
                const suffix = this.placeholder.endsWith(')') ? NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX : NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS;
                const suffixedPlaceholder = this.placeholder + suffix;
                if (options.showPlaceholderOnFocus && document.activeElement !== this.input) {
                    this.placeholder = suffixedPlaceholder;
                }
                else {
                    this.setPlaceHolder(suffixedPlaceholder);
                }
            }
        };
        // Spot the change to the textarea class attribute which occurs when it changes between non-empty and empty,
        // and add the history suffix to the placeholder if not yet present
        this.observer = new MutationObserver((mutationList, observer) => {
            mutationList.forEach((mutation) => {
                if (!mutation.target.textContent) {
                    addSuffix();
                }
            });
        });
        this.observer.observe(this.input, { attributeFilter: ['class'] });
        this.onfocus(this.input, () => addSuffix());
        this.onblur(this.input, () => {
            const resetPlaceholder = (historyHint) => {
                if (!this.placeholder.endsWith(historyHint)) {
                    return false;
                }
                else {
                    const revertedPlaceholder = this.placeholder.slice(0, this.placeholder.length - historyHint.length);
                    if (options.showPlaceholderOnFocus) {
                        this.placeholder = revertedPlaceholder;
                    }
                    else {
                        this.setPlaceHolder(revertedPlaceholder);
                    }
                    return true;
                }
            };
            if (!resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS)) {
                resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX);
            }
        });
    }
    dispose() {
        super.dispose();
        if (this.observer) {
            this.observer.disconnect();
            this.observer = undefined;
        }
    }
    addToHistory() {
        if (this.value && this.value !== this.getCurrentValue()) {
            this.history.add(this.value);
        }
    }
    showNextValue() {
        if (!this.history.has(this.value)) {
            this.addToHistory();
        }
        let next = this.getNextValue();
        if (next) {
            next = next === this.value ? this.getNextValue() : next;
        }
        if (next) {
            this.value = next;
            aria_status(this.value);
        }
    }
    showPreviousValue() {
        if (!this.history.has(this.value)) {
            this.addToHistory();
        }
        let previous = this.getPreviousValue();
        if (previous) {
            previous = previous === this.value ? this.getPreviousValue() : previous;
        }
        if (previous) {
            this.value = previous;
            aria_status(this.value);
        }
    }
    onBlur() {
        super.onBlur();
        this._onDidBlur.fire();
    }
    onFocus() {
        super.onFocus();
        this._onDidFocus.fire();
    }
    getCurrentValue() {
        let currentValue = this.history.current();
        if (!currentValue) {
            currentValue = this.history.last();
            this.history.next();
        }
        return currentValue;
    }
    getPreviousValue() {
        return this.history.previous() || this.history.first();
    }
    getNextValue() {
        return this.history.next() || this.history.last();
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/findinput/findInput.css
var findInput = __webpack_require__(69019);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/findinput/findInput.css

      
      
      
      
      
      
      
      
      

var findInput_options = {};

findInput_options.styleTagTransform = (styleTagTransform_default());
findInput_options.setAttributes = (setAttributesWithoutAttributes_default());

      findInput_options.insert = insertBySelector_default().bind(null, "head");
    
findInput_options.domAPI = (styleDomAPI_default());
findInput_options.insertStyleElement = (insertStyleElement_default());

var findInput_update = injectStylesIntoStyleTag_default()(findInput/* default */.A, findInput_options);




       /* harmony default export */ const findinput_findInput = (findInput/* default */.A && findInput/* default */.A.locals ? findInput/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/findinput/findInput.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







const NLS_DEFAULT_LABEL = localize('defaultLabel', "input");
class FindInput extends Widget {
    constructor(parent, contextViewProvider, _showOptionButtons, options) {
        var _a;
        super();
        this._showOptionButtons = _showOptionButtons;
        this.fixFocusOnOptionClickEnabled = true;
        this.imeSessionInProgress = false;
        this.additionalToggles = [];
        this._onDidOptionChange = this._register(new Emitter());
        this.onDidOptionChange = this._onDidOptionChange.event;
        this._onKeyDown = this._register(new Emitter());
        this.onKeyDown = this._onKeyDown.event;
        this._onMouseDown = this._register(new Emitter());
        this.onMouseDown = this._onMouseDown.event;
        this._onInput = this._register(new Emitter());
        this._onKeyUp = this._register(new Emitter());
        this._onCaseSensitiveKeyDown = this._register(new Emitter());
        this.onCaseSensitiveKeyDown = this._onCaseSensitiveKeyDown.event;
        this._onRegexKeyDown = this._register(new Emitter());
        this.onRegexKeyDown = this._onRegexKeyDown.event;
        this._lastHighlightFindOptions = 0;
        this.contextViewProvider = contextViewProvider;
        this.placeholder = options.placeholder || '';
        this.validation = options.validation;
        this.label = options.label || NLS_DEFAULT_LABEL;
        this.inputActiveOptionBorder = options.inputActiveOptionBorder;
        this.inputActiveOptionForeground = options.inputActiveOptionForeground;
        this.inputActiveOptionBackground = options.inputActiveOptionBackground;
        this.inputBackground = options.inputBackground;
        this.inputForeground = options.inputForeground;
        this.inputBorder = options.inputBorder;
        this.inputValidationInfoBorder = options.inputValidationInfoBorder;
        this.inputValidationInfoBackground = options.inputValidationInfoBackground;
        this.inputValidationInfoForeground = options.inputValidationInfoForeground;
        this.inputValidationWarningBorder = options.inputValidationWarningBorder;
        this.inputValidationWarningBackground = options.inputValidationWarningBackground;
        this.inputValidationWarningForeground = options.inputValidationWarningForeground;
        this.inputValidationErrorBorder = options.inputValidationErrorBorder;
        this.inputValidationErrorBackground = options.inputValidationErrorBackground;
        this.inputValidationErrorForeground = options.inputValidationErrorForeground;
        const appendCaseSensitiveLabel = options.appendCaseSensitiveLabel || '';
        const appendWholeWordsLabel = options.appendWholeWordsLabel || '';
        const appendRegexLabel = options.appendRegexLabel || '';
        const history = options.history || [];
        const flexibleHeight = !!options.flexibleHeight;
        const flexibleWidth = !!options.flexibleWidth;
        const flexibleMaxHeight = options.flexibleMaxHeight;
        this.domNode = document.createElement('div');
        this.domNode.classList.add('monaco-findInput');
        this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
            placeholder: this.placeholder || '',
            ariaLabel: this.label || '',
            validationOptions: {
                validation: this.validation
            },
            inputBackground: this.inputBackground,
            inputForeground: this.inputForeground,
            inputBorder: this.inputBorder,
            inputValidationInfoBackground: this.inputValidationInfoBackground,
            inputValidationInfoForeground: this.inputValidationInfoForeground,
            inputValidationInfoBorder: this.inputValidationInfoBorder,
            inputValidationWarningBackground: this.inputValidationWarningBackground,
            inputValidationWarningForeground: this.inputValidationWarningForeground,
            inputValidationWarningBorder: this.inputValidationWarningBorder,
            inputValidationErrorBackground: this.inputValidationErrorBackground,
            inputValidationErrorForeground: this.inputValidationErrorForeground,
            inputValidationErrorBorder: this.inputValidationErrorBorder,
            history,
            showHistoryHint: options.showHistoryHint,
            flexibleHeight,
            flexibleWidth,
            flexibleMaxHeight
        }));
        this.regex = this._register(new RegexToggle({
            appendTitle: appendRegexLabel,
            isChecked: false,
            inputActiveOptionBorder: this.inputActiveOptionBorder,
            inputActiveOptionForeground: this.inputActiveOptionForeground,
            inputActiveOptionBackground: this.inputActiveOptionBackground
        }));
        this._register(this.regex.onChange(viaKeyboard => {
            this._onDidOptionChange.fire(viaKeyboard);
            if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
                this.inputBox.focus();
            }
            this.validate();
        }));
        this._register(this.regex.onKeyDown(e => {
            this._onRegexKeyDown.fire(e);
        }));
        this.wholeWords = this._register(new WholeWordsToggle({
            appendTitle: appendWholeWordsLabel,
            isChecked: false,
            inputActiveOptionBorder: this.inputActiveOptionBorder,
            inputActiveOptionForeground: this.inputActiveOptionForeground,
            inputActiveOptionBackground: this.inputActiveOptionBackground
        }));
        this._register(this.wholeWords.onChange(viaKeyboard => {
            this._onDidOptionChange.fire(viaKeyboard);
            if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
                this.inputBox.focus();
            }
            this.validate();
        }));
        this.caseSensitive = this._register(new CaseSensitiveToggle({
            appendTitle: appendCaseSensitiveLabel,
            isChecked: false,
            inputActiveOptionBorder: this.inputActiveOptionBorder,
            inputActiveOptionForeground: this.inputActiveOptionForeground,
            inputActiveOptionBackground: this.inputActiveOptionBackground
        }));
        this._register(this.caseSensitive.onChange(viaKeyboard => {
            this._onDidOptionChange.fire(viaKeyboard);
            if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
                this.inputBox.focus();
            }
            this.validate();
        }));
        this._register(this.caseSensitive.onKeyDown(e => {
            this._onCaseSensitiveKeyDown.fire(e);
        }));
        // Arrow-Key support to navigate between options
        const indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
        this.onkeydown(this.domNode, (event) => {
            if (event.equals(15 /* KeyCode.LeftArrow */) || event.equals(17 /* KeyCode.RightArrow */) || event.equals(9 /* KeyCode.Escape */)) {
                const index = indexes.indexOf(document.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();
                    }
                    EventHelper.stop(event, true);
                }
            }
        });
        this.controls = document.createElement('div');
        this.controls.className = 'controls';
        this.controls.style.display = this._showOptionButtons ? 'block' : 'none';
        this.controls.appendChild(this.caseSensitive.domNode);
        this.controls.appendChild(this.wholeWords.domNode);
        this.controls.appendChild(this.regex.domNode);
        if (!this._showOptionButtons) {
            this.caseSensitive.domNode.style.display = 'none';
            this.wholeWords.domNode.style.display = 'none';
            this.regex.domNode.style.display = 'none';
        }
        for (const toggle of (_a = options === null || options === void 0 ? void 0 : options.additionalToggles) !== null && _a !== void 0 ? _a : []) {
            this._register(toggle);
            this.controls.appendChild(toggle.domNode);
            this._register(toggle.onChange(viaKeyboard => {
                this._onDidOptionChange.fire(viaKeyboard);
                if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
                    this.inputBox.focus();
                }
            }));
            this.additionalToggles.push(toggle);
        }
        if (this.additionalToggles.length > 0) {
            this.controls.style.display = 'block';
        }
        this.inputBox.paddingRight =
            (this._showOptionButtons ? this.caseSensitive.width() + this.wholeWords.width() + this.regex.width() : 0)
                + this.additionalToggles.reduce((r, t) => r + t.width(), 0);
        this.domNode.appendChild(this.controls);
        parent === null || parent === void 0 ? void 0 : parent.appendChild(this.domNode);
        this._register(addDisposableListener(this.inputBox.inputElement, 'compositionstart', (e) => {
            this.imeSessionInProgress = true;
        }));
        this._register(addDisposableListener(this.inputBox.inputElement, 'compositionend', (e) => {
            this.imeSessionInProgress = false;
            this._onInput.fire();
        }));
        this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
        this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
        this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
        this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
    }
    get onDidChange() {
        return this.inputBox.onDidChange;
    }
    enable() {
        this.domNode.classList.remove('disabled');
        this.inputBox.enable();
        this.regex.enable();
        this.wholeWords.enable();
        this.caseSensitive.enable();
        for (const toggle of this.additionalToggles) {
            toggle.enable();
        }
    }
    disable() {
        this.domNode.classList.add('disabled');
        this.inputBox.disable();
        this.regex.disable();
        this.wholeWords.disable();
        this.caseSensitive.disable();
        for (const toggle of this.additionalToggles) {
            toggle.disable();
        }
    }
    setFocusInputOnOptionClick(value) {
        this.fixFocusOnOptionClickEnabled = value;
    }
    setEnabled(enabled) {
        if (enabled) {
            this.enable();
        }
        else {
            this.disable();
        }
    }
    getValue() {
        return this.inputBox.value;
    }
    setValue(value) {
        if (this.inputBox.value !== value) {
            this.inputBox.value = value;
        }
    }
    style(styles) {
        this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
        this.inputActiveOptionForeground = styles.inputActiveOptionForeground;
        this.inputActiveOptionBackground = styles.inputActiveOptionBackground;
        this.inputBackground = styles.inputBackground;
        this.inputForeground = styles.inputForeground;
        this.inputBorder = styles.inputBorder;
        this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
        this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
        this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
        this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
        this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
        this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
        this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
        this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
        this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
        this.applyStyles();
    }
    applyStyles() {
        if (this.domNode) {
            const toggleStyles = {
                inputActiveOptionBorder: this.inputActiveOptionBorder,
                inputActiveOptionForeground: this.inputActiveOptionForeground,
                inputActiveOptionBackground: this.inputActiveOptionBackground,
            };
            this.regex.style(toggleStyles);
            this.wholeWords.style(toggleStyles);
            this.caseSensitive.style(toggleStyles);
            for (const toggle of this.additionalToggles) {
                toggle.style(toggleStyles);
            }
            const inputBoxStyles = {
                inputBackground: this.inputBackground,
                inputForeground: this.inputForeground,
                inputBorder: this.inputBorder,
                inputValidationInfoBackground: this.inputValidationInfoBackground,
                inputValidationInfoForeground: this.inputValidationInfoForeground,
                inputValidationInfoBorder: this.inputValidationInfoBorder,
                inputValidationWarningBackground: this.inputValidationWarningBackground,
                inputValidationWarningForeground: this.inputValidationWarningForeground,
                inputValidationWarningBorder: this.inputValidationWarningBorder,
                inputValidationErrorBackground: this.inputValidationErrorBackground,
                inputValidationErrorForeground: this.inputValidationErrorForeground,
                inputValidationErrorBorder: this.inputValidationErrorBorder
            };
            this.inputBox.style(inputBoxStyles);
        }
    }
    select() {
        this.inputBox.select();
    }
    focus() {
        this.inputBox.focus();
    }
    getCaseSensitive() {
        return this.caseSensitive.checked;
    }
    setCaseSensitive(value) {
        this.caseSensitive.checked = value;
    }
    getWholeWords() {
        return this.wholeWords.checked;
    }
    setWholeWords(value) {
        this.wholeWords.checked = value;
    }
    getRegex() {
        return this.regex.checked;
    }
    setRegex(value) {
        this.regex.checked = value;
        this.validate();
    }
    focusOnCaseSensitive() {
        this.caseSensitive.focus();
    }
    highlightFindOptions() {
        this.domNode.classList.remove('highlight-' + (this._lastHighlightFindOptions));
        this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
        this.domNode.classList.add('highlight-' + (this._lastHighlightFindOptions));
    }
    validate() {
        this.inputBox.validate();
    }
    showMessage(message) {
        this.inputBox.showMessage(message);
    }
    clearMessage() {
        this.inputBox.hideMessage();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/tree/tree.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var TreeMouseEventTarget;
(function (TreeMouseEventTarget) {
    TreeMouseEventTarget[TreeMouseEventTarget["Unknown"] = 0] = "Unknown";
    TreeMouseEventTarget[TreeMouseEventTarget["Twistie"] = 1] = "Twistie";
    TreeMouseEventTarget[TreeMouseEventTarget["Element"] = 2] = "Element";
    TreeMouseEventTarget[TreeMouseEventTarget["Filter"] = 3] = "Filter";
})(TreeMouseEventTarget || (TreeMouseEventTarget = {}));
class TreeError extends Error {
    constructor(user, message) {
        super(`TreeError [${user}] ${message}`);
    }
}
class WeakMapper {
    constructor(fn) {
        this.fn = fn;
        this._map = new WeakMap();
    }
    map(key) {
        let result = this._map.get(key);
        if (!result) {
            result = this.fn(key);
            this._map.set(key, result);
        }
        return result;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/diff/diffChange.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/**
 * Represents information about a specific difference between two sequences.
 */
class DiffChange {
    /**
     * Constructs a new DiffChange with the given sequence information
     * and content.
     */
    constructor(originalStart, originalLength, modifiedStart, modifiedLength) {
        //Debug.Assert(originalLength > 0 || modifiedLength > 0, "originalLength and modifiedLength cannot both be <= 0");
        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;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/diff/diff.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class StringDiffSequence {
    constructor(source) {
        this.source = source;
    }
    getElements() {
        const source = this.source;
        const characters = new Int32Array(source.length);
        for (let i = 0, len = source.length; i < len; i++) {
            characters[i] = source.charCodeAt(i);
        }
        return characters;
    }
}
function stringDiff(original, modified, pretty) {
    return new LcsDiff(new StringDiffSequence(original), new StringDiffSequence(modified)).ComputeDiff(pretty).changes;
}
//
// The code below has been ported from a C# implementation in VS
//
class Debug {
    static Assert(condition, message) {
        if (!condition) {
            throw new Error(message);
        }
    }
}
class MyArray {
    /**
     * 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 i = 0; i < length; i++) {
            destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i];
        }
    }
    static Copy2(sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
        for (let i = 0; i < length; i++) {
            destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i];
        }
    }
}
/**
 * A utility class which helps to create the set of DiffChanges from
 * a difference operation. This class accepts original DiffElements and
 * modified DiffElements that are involved in a particular change. The
 * MarkNextChange() method can be called to mark the separation between
 * distinct changes. At the end, the Changes property can be called to retrieve
 * the constructed changes.
 */
class DiffChangeHelper {
    /**
     * Constructs a new DiffChangeHelper for the given DiffSequences.
     */
    constructor() {
        this.m_changes = [];
        this.m_originalStart = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
        this.m_modifiedStart = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
        this.m_originalCount = 0;
        this.m_modifiedCount = 0;
    }
    /**
     * Marks the beginning of the next change in the set of differences.
     */
    MarkNextChange() {
        // Only add to the list if there is something to add
        if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
            // Add the new change to our list
            this.m_changes.push(new DiffChange(this.m_originalStart, this.m_originalCount, this.m_modifiedStart, this.m_modifiedCount));
        }
        // Reset for the next change
        this.m_originalCount = 0;
        this.m_modifiedCount = 0;
        this.m_originalStart = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
        this.m_modifiedStart = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
    }
    /**
     * 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) {
        // The 'true' start index is the smallest of the ones we've seen
        this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
        this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
        this.m_originalCount++;
    }
    /**
     * 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) {
        // The 'true' start index is the smallest of the ones we've seen
        this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
        this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
        this.m_modifiedCount++;
    }
    /**
     * Retrieves all of the changes marked by the class.
     */
    getChanges() {
        if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
            // Finish up on whatever is left
            this.MarkNextChange();
        }
        return this.m_changes;
    }
    /**
     * Retrieves all of the changes marked by the class in the reverse order
     */
    getReverseChanges() {
        if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
            // Finish up on whatever is left
            this.MarkNextChange();
        }
        this.m_changes.reverse();
        return this.m_changes;
    }
}
/**
 * An implementation of the difference algorithm described in
 * "An O(ND) Difference Algorithm and its variations" by Eugene W. Myers
 */
class LcsDiff {
    /**
     * Constructs the DiffFinder
     */
    constructor(originalSequence, modifiedSequence, continueProcessingPredicate = null) {
        this.ContinueProcessingPredicate = continueProcessingPredicate;
        this._originalSequence = originalSequence;
        this._modifiedSequence = modifiedSequence;
        const [originalStringElements, originalElementsOrHash, originalHasStrings] = LcsDiff._getElements(originalSequence);
        const [modifiedStringElements, modifiedElementsOrHash, modifiedHasStrings] = LcsDiff._getElements(modifiedSequence);
        this._hasStrings = (originalHasStrings && modifiedHasStrings);
        this._originalStringElements = originalStringElements;
        this._originalElementsOrHash = originalElementsOrHash;
        this._modifiedStringElements = modifiedStringElements;
        this._modifiedElementsOrHash = modifiedElementsOrHash;
        this.m_forwardHistory = [];
        this.m_reverseHistory = [];
    }
    static _isStringArray(arr) {
        return (arr.length > 0 && typeof arr[0] === 'string');
    }
    static _getElements(sequence) {
        const elements = sequence.getElements();
        if (LcsDiff._isStringArray(elements)) {
            const hashes = new Int32Array(elements.length);
            for (let i = 0, len = elements.length; i < len; i++) {
                hashes[i] = stringHash(elements[i], 0);
            }
            return [elements, hashes, true];
        }
        if (elements instanceof Int32Array) {
            return [[], elements, false];
        }
        return [[], new Int32Array(elements), false];
    }
    ElementsAreEqual(originalIndex, newIndex) {
        if (this._originalElementsOrHash[originalIndex] !== this._modifiedElementsOrHash[newIndex]) {
            return false;
        }
        return (this._hasStrings ? this._originalStringElements[originalIndex] === this._modifiedStringElements[newIndex] : true);
    }
    ElementsAreStrictEqual(originalIndex, newIndex) {
        if (!this.ElementsAreEqual(originalIndex, newIndex)) {
            return false;
        }
        const originalElement = LcsDiff._getStrictElement(this._originalSequence, originalIndex);
        const modifiedElement = LcsDiff._getStrictElement(this._modifiedSequence, newIndex);
        return (originalElement === modifiedElement);
    }
    static _getStrictElement(sequence, index) {
        if (typeof sequence.getStrictElement === 'function') {
            return sequence.getStrictElement(index);
        }
        return null;
    }
    OriginalElementsAreEqual(index1, index2) {
        if (this._originalElementsOrHash[index1] !== this._originalElementsOrHash[index2]) {
            return false;
        }
        return (this._hasStrings ? this._originalStringElements[index1] === this._originalStringElements[index2] : true);
    }
    ModifiedElementsAreEqual(index1, index2) {
        if (this._modifiedElementsOrHash[index1] !== this._modifiedElementsOrHash[index2]) {
            return false;
        }
        return (this._hasStrings ? this._modifiedStringElements[index1] === this._modifiedStringElements[index2] : true);
    }
    ComputeDiff(pretty) {
        return this._ComputeDiff(0, this._originalElementsOrHash.length - 1, 0, this._modifiedElementsOrHash.length - 1, pretty);
    }
    /**
     * 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.
     */
    _ComputeDiff(originalStart, originalEnd, modifiedStart, modifiedEnd, pretty) {
        const quitEarlyArr = [false];
        let changes = this.ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr);
        if (pretty) {
            // We have to clean up the computed diff to be more intuitive
            // but it turns out this cannot be done correctly until the entire set
            // of diffs have been computed
            changes = this.PrettifyChanges(changes);
        }
        return {
            quitEarly: quitEarlyArr[0],
            changes: changes
        };
    }
    /**
     * Private helper method which computes the differences on the bounded range
     * recursively.
     * @returns An array of the differences between the two input sequences.
     */
    ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr) {
        quitEarlyArr[0] = false;
        // Find the start of the differences
        while (originalStart <= originalEnd && modifiedStart <= modifiedEnd && this.ElementsAreEqual(originalStart, modifiedStart)) {
            originalStart++;
            modifiedStart++;
        }
        // Find the end of the differences
        while (originalEnd >= originalStart && modifiedEnd >= modifiedStart && this.ElementsAreEqual(originalEnd, modifiedEnd)) {
            originalEnd--;
            modifiedEnd--;
        }
        // In the special case where we either have all insertions or all deletions or the sequences are identical
        if (originalStart > originalEnd || modifiedStart > modifiedEnd) {
            let changes;
            if (modifiedStart <= modifiedEnd) {
                Debug.Assert(originalStart === originalEnd + 1, 'originalStart should only be one more than originalEnd');
                // All insertions
                changes = [
                    new DiffChange(originalStart, 0, modifiedStart, modifiedEnd - modifiedStart + 1)
                ];
            }
            else if (originalStart <= originalEnd) {
                Debug.Assert(modifiedStart === modifiedEnd + 1, 'modifiedStart should only be one more than modifiedEnd');
                // All deletions
                changes = [
                    new DiffChange(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');
                // Identical sequences - No differences
                changes = [];
            }
            return changes;
        }
        // This problem can be solved using the Divide-And-Conquer technique.
        const midOriginalArr = [0];
        const midModifiedArr = [0];
        const result = this.ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr);
        const midOriginal = midOriginalArr[0];
        const midModified = midModifiedArr[0];
        if (result !== null) {
            // Result is not-null when there was enough memory to compute the changes while
            // searching for the recursion point
            return result;
        }
        else if (!quitEarlyArr[0]) {
            // We can break the problem down recursively by finding the changes in the
            // First Half:   (originalStart, modifiedStart) to (midOriginal, midModified)
            // Second Half:  (midOriginal + 1, minModified + 1) to (originalEnd, modifiedEnd)
            // NOTE: ComputeDiff() is inclusive, therefore the second range starts on the next point
            const leftChanges = this.ComputeDiffRecursive(originalStart, midOriginal, modifiedStart, midModified, quitEarlyArr);
            let rightChanges = [];
            if (!quitEarlyArr[0]) {
                rightChanges = this.ComputeDiffRecursive(midOriginal + 1, originalEnd, midModified + 1, modifiedEnd, quitEarlyArr);
            }
            else {
                // We didn't have time to finish the first half, so we don't have time to compute this half.
                // Consider the entire rest of the sequence different.
                rightChanges = [
                    new DiffChange(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1)
                ];
            }
            return this.ConcatenateChanges(leftChanges, rightChanges);
        }
        // If we hit here, we quit early, and so can't return anything meaningful
        return [
            new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
        ];
    }
    WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr) {
        let forwardChanges = null;
        let reverseChanges = null;
        // First, walk backward through the forward diagonals history
        let changeHelper = new DiffChangeHelper();
        let diagonalMin = diagonalForwardStart;
        let diagonalMax = diagonalForwardEnd;
        let diagonalRelative = (midOriginalArr[0] - midModifiedArr[0]) - diagonalForwardOffset;
        let lastOriginalIndex = -1073741824 /* Constants.MIN_SAFE_SMALL_INTEGER */;
        let historyIndex = this.m_forwardHistory.length - 1;
        do {
            // Get the diagonal index from the relative diagonal number
            const diagonal = diagonalRelative + diagonalForwardBase;
            // Figure out where we came from
            if (diagonal === diagonalMin || (diagonal < diagonalMax && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1])) {
                // Vertical line (the element is an insert)
                originalIndex = forwardPoints[diagonal + 1];
                modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
                if (originalIndex < lastOriginalIndex) {
                    changeHelper.MarkNextChange();
                }
                lastOriginalIndex = originalIndex;
                changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex);
                diagonalRelative = (diagonal + 1) - diagonalForwardBase; //Setup for the next iteration
            }
            else {
                // Horizontal line (the element is a deletion)
                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; //Setup for the next iteration
            }
            if (historyIndex >= 0) {
                forwardPoints = this.m_forwardHistory[historyIndex];
                diagonalForwardBase = forwardPoints[0]; //We stored this in the first spot
                diagonalMin = 1;
                diagonalMax = forwardPoints.length - 1;
            }
        } while (--historyIndex >= -1);
        // Ironically, we get the forward changes as the reverse of the
        // order we added them since we technically added them backwards
        forwardChanges = changeHelper.getReverseChanges();
        if (quitEarlyArr[0]) {
            // TODO: Calculate a partial from the reverse diagonals.
            //       For now, just assume everything after the midOriginal/midModified point is a diff
            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 DiffChange(originalStartPoint, originalEnd - originalStartPoint + 1, modifiedStartPoint, modifiedEnd - modifiedStartPoint + 1)
            ];
        }
        else {
            // Now walk backward through the reverse diagonals history
            changeHelper = new DiffChangeHelper();
            diagonalMin = diagonalReverseStart;
            diagonalMax = diagonalReverseEnd;
            diagonalRelative = (midOriginalArr[0] - midModifiedArr[0]) - diagonalReverseOffset;
            lastOriginalIndex = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
            historyIndex = (deltaIsEven) ? this.m_reverseHistory.length - 1 : this.m_reverseHistory.length - 2;
            do {
                // Get the diagonal index from the relative diagonal number
                const diagonal = diagonalRelative + diagonalReverseBase;
                // Figure out where we came from
                if (diagonal === diagonalMin || (diagonal < diagonalMax && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1])) {
                    // Horizontal line (the element is a deletion))
                    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; //Setup for the next iteration
                }
                else {
                    // Vertical line (the element is an insertion)
                    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; //Setup for the next iteration
                }
                if (historyIndex >= 0) {
                    reversePoints = this.m_reverseHistory[historyIndex];
                    diagonalReverseBase = reversePoints[0]; //We stored this in the first spot
                    diagonalMin = 1;
                    diagonalMax = reversePoints.length - 1;
                }
            } while (--historyIndex >= -1);
            // There are cases where the reverse history will find diffs that
            // are correct, but not intuitive, so we need shift them.
            reverseChanges = changeHelper.getChanges();
        }
        return this.ConcatenateChanges(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
     */
    ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr) {
        let originalIndex = 0, modifiedIndex = 0;
        let diagonalForwardStart = 0, diagonalForwardEnd = 0;
        let diagonalReverseStart = 0, diagonalReverseEnd = 0;
        // To traverse the edit graph and produce the proper LCS, our actual
        // start position is just outside the given boundary
        originalStart--;
        modifiedStart--;
        // We set these up to make the compiler happy, but they will
        // be replaced before we return with the actual recursion point
        midOriginalArr[0] = 0;
        midModifiedArr[0] = 0;
        // Clear out the history
        this.m_forwardHistory = [];
        this.m_reverseHistory = [];
        // Each cell in the two arrays corresponds to a diagonal in the edit graph.
        // The integer value in the cell represents the originalIndex of the furthest
        // reaching point found so far that ends in that diagonal.
        // The modifiedIndex can be computed mathematically from the originalIndex and the diagonal number.
        const maxDifferences = (originalEnd - originalStart) + (modifiedEnd - modifiedStart);
        const numDiagonals = maxDifferences + 1;
        const forwardPoints = new Int32Array(numDiagonals);
        const reversePoints = new Int32Array(numDiagonals);
        // diagonalForwardBase: Index into forwardPoints of the diagonal which passes through (originalStart, modifiedStart)
        // diagonalReverseBase: Index into reversePoints of the diagonal which passes through (originalEnd, modifiedEnd)
        const diagonalForwardBase = (modifiedEnd - modifiedStart);
        const diagonalReverseBase = (originalEnd - originalStart);
        // diagonalForwardOffset: Geometric offset which allows modifiedIndex to be computed from originalIndex and the
        //    diagonal number (relative to diagonalForwardBase)
        // diagonalReverseOffset: Geometric offset which allows modifiedIndex to be computed from originalIndex and the
        //    diagonal number (relative to diagonalReverseBase)
        const diagonalForwardOffset = (originalStart - modifiedStart);
        const diagonalReverseOffset = (originalEnd - modifiedEnd);
        // delta: The difference between the end diagonal and the start diagonal. This is used to relate diagonal numbers
        //   relative to the start diagonal with diagonal numbers relative to the end diagonal.
        // The Even/Oddn-ness of this delta is important for determining when we should check for overlap
        const delta = diagonalReverseBase - diagonalForwardBase;
        const deltaIsEven = (delta % 2 === 0);
        // Here we set up the start and end points as the furthest points found so far
        // in both the forward and reverse directions, respectively
        forwardPoints[diagonalForwardBase] = originalStart;
        reversePoints[diagonalReverseBase] = originalEnd;
        // Remember if we quit early, and thus need to do a best-effort result instead of a real result.
        quitEarlyArr[0] = false;
        // A couple of points:
        // --With this method, we iterate on the number of differences between the two sequences.
        //   The more differences there actually are, the longer this will take.
        // --Also, as the number of differences increases, we have to search on diagonals further
        //   away from the reference diagonal (which is diagonalForwardBase for forward, diagonalReverseBase for reverse).
        // --We extend on even diagonals (relative to the reference diagonal) only when numDifferences
        //   is even and odd diagonals only when numDifferences is odd.
        for (let numDifferences = 1; numDifferences <= (maxDifferences / 2) + 1; numDifferences++) {
            let furthestOriginalIndex = 0;
            let furthestModifiedIndex = 0;
            // Run the algorithm in the forward direction
            diagonalForwardStart = this.ClipDiagonalBound(diagonalForwardBase - numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
            diagonalForwardEnd = this.ClipDiagonalBound(diagonalForwardBase + numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
            for (let diagonal = diagonalForwardStart; diagonal <= diagonalForwardEnd; diagonal += 2) {
                // STEP 1: We extend the furthest reaching point in the present diagonal
                // by looking at the diagonals above and below and picking the one whose point
                // is further away from the start point (originalStart, modifiedStart)
                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;
                // Save the current originalIndex so we can test for false overlap in step 3
                const tempOriginalIndex = originalIndex;
                // STEP 2: We can continue to extend the furthest reaching point in the present diagonal
                // so long as the elements are equal.
                while (originalIndex < originalEnd && modifiedIndex < modifiedEnd && this.ElementsAreEqual(originalIndex + 1, modifiedIndex + 1)) {
                    originalIndex++;
                    modifiedIndex++;
                }
                forwardPoints[diagonal] = originalIndex;
                if (originalIndex + modifiedIndex > furthestOriginalIndex + furthestModifiedIndex) {
                    furthestOriginalIndex = originalIndex;
                    furthestModifiedIndex = modifiedIndex;
                }
                // STEP 3: If delta is odd (overlap first happens on forward when delta is odd)
                // and diagonal is in the range of reverse diagonals computed for numDifferences-1
                // (the previous iteration; we haven't computed reverse diagonals for numDifferences yet)
                // then check for overlap.
                if (!deltaIsEven && Math.abs(diagonal - diagonalReverseBase) <= (numDifferences - 1)) {
                    if (originalIndex >= reversePoints[diagonal]) {
                        midOriginalArr[0] = originalIndex;
                        midModifiedArr[0] = modifiedIndex;
                        if (tempOriginalIndex <= reversePoints[diagonal] && 1447 /* LocalConstants.MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* LocalConstants.MaxDifferencesHistory */ + 1)) {
                            // BINGO! We overlapped, and we have the full trace in memory!
                            return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
                        }
                        else {
                            // Either false overlap, or we didn't have enough memory for the full trace
                            // Just return the recursion point
                            return null;
                        }
                    }
                }
            }
            // Check to see if we should be quitting early, before moving on to the next iteration.
            const matchLengthOfLongest = ((furthestOriginalIndex - originalStart) + (furthestModifiedIndex - modifiedStart) - numDifferences) / 2;
            if (this.ContinueProcessingPredicate !== null && !this.ContinueProcessingPredicate(furthestOriginalIndex, matchLengthOfLongest)) {
                // We can't finish, so skip ahead to generating a result from what we have.
                quitEarlyArr[0] = true;
                // Use the furthest distance we got in the forward direction.
                midOriginalArr[0] = furthestOriginalIndex;
                midModifiedArr[0] = furthestModifiedIndex;
                if (matchLengthOfLongest > 0 && 1447 /* LocalConstants.MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* LocalConstants.MaxDifferencesHistory */ + 1)) {
                    // Enough of the history is in memory to walk it backwards
                    return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
                }
                else {
                    // We didn't actually remember enough of the history.
                    //Since we are quitting the diff early, we need to shift back the originalStart and modified start
                    //back into the boundary limits since we decremented their value above beyond the boundary limit.
                    originalStart++;
                    modifiedStart++;
                    return [
                        new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
                    ];
                }
            }
            // Run the algorithm in the reverse direction
            diagonalReverseStart = this.ClipDiagonalBound(diagonalReverseBase - numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
            diagonalReverseEnd = this.ClipDiagonalBound(diagonalReverseBase + numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
            for (let diagonal = diagonalReverseStart; diagonal <= diagonalReverseEnd; diagonal += 2) {
                // STEP 1: We extend the furthest reaching point in the present diagonal
                // by looking at the diagonals above and below and picking the one whose point
                // is further away from the start point (originalEnd, modifiedEnd)
                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;
                // Save the current originalIndex so we can test for false overlap
                const tempOriginalIndex = originalIndex;
                // STEP 2: We can continue to extend the furthest reaching point in the present diagonal
                // as long as the elements are equal.
                while (originalIndex > originalStart && modifiedIndex > modifiedStart && this.ElementsAreEqual(originalIndex, modifiedIndex)) {
                    originalIndex--;
                    modifiedIndex--;
                }
                reversePoints[diagonal] = originalIndex;
                // STEP 4: If delta is even (overlap first happens on reverse when delta is even)
                // and diagonal is in the range of forward diagonals computed for numDifferences
                // then check for overlap.
                if (deltaIsEven && Math.abs(diagonal - diagonalForwardBase) <= numDifferences) {
                    if (originalIndex <= forwardPoints[diagonal]) {
                        midOriginalArr[0] = originalIndex;
                        midModifiedArr[0] = modifiedIndex;
                        if (tempOriginalIndex >= forwardPoints[diagonal] && 1447 /* LocalConstants.MaxDifferencesHistory */ > 0 && numDifferences <= (1447 /* LocalConstants.MaxDifferencesHistory */ + 1)) {
                            // BINGO! We overlapped, and we have the full trace in memory!
                            return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
                        }
                        else {
                            // Either false overlap, or we didn't have enough memory for the full trace
                            // Just return the recursion point
                            return null;
                        }
                    }
                }
            }
            // Save current vectors to history before the next iteration
            if (numDifferences <= 1447 /* LocalConstants.MaxDifferencesHistory */) {
                // We are allocating space for one extra int, which we fill with
                // the index of the diagonal base index
                let temp = new Int32Array(diagonalForwardEnd - diagonalForwardStart + 2);
                temp[0] = diagonalForwardBase - diagonalForwardStart + 1;
                MyArray.Copy2(forwardPoints, diagonalForwardStart, temp, 1, diagonalForwardEnd - diagonalForwardStart + 1);
                this.m_forwardHistory.push(temp);
                temp = new Int32Array(diagonalReverseEnd - diagonalReverseStart + 2);
                temp[0] = diagonalReverseBase - diagonalReverseStart + 1;
                MyArray.Copy2(reversePoints, diagonalReverseStart, temp, 1, diagonalReverseEnd - diagonalReverseStart + 1);
                this.m_reverseHistory.push(temp);
            }
        }
        // If we got here, then we have the full trace in history. We just have to convert it to a change list
        // NOTE: This part is a bit messy
        return this.WALKTRACE(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
     */
    PrettifyChanges(changes) {
        // Shift all the changes down first
        for (let i = 0; i < changes.length; i++) {
            const change = changes[i];
            const originalStop = (i < changes.length - 1) ? changes[i + 1].originalStart : this._originalElementsOrHash.length;
            const modifiedStop = (i < changes.length - 1) ? changes[i + 1].modifiedStart : this._modifiedElementsOrHash.length;
            const checkOriginal = change.originalLength > 0;
            const checkModified = change.modifiedLength > 0;
            while (change.originalStart + change.originalLength < originalStop
                && change.modifiedStart + change.modifiedLength < modifiedStop
                && (!checkOriginal || this.OriginalElementsAreEqual(change.originalStart, change.originalStart + change.originalLength))
                && (!checkModified || this.ModifiedElementsAreEqual(change.modifiedStart, change.modifiedStart + change.modifiedLength))) {
                const startStrictEqual = this.ElementsAreStrictEqual(change.originalStart, change.modifiedStart);
                const endStrictEqual = this.ElementsAreStrictEqual(change.originalStart + change.originalLength, change.modifiedStart + change.modifiedLength);
                if (endStrictEqual && !startStrictEqual) {
                    // moving the change down would create an equal change, but the elements are not strict equal
                    break;
                }
                change.originalStart++;
                change.modifiedStart++;
            }
            const mergedChangeArr = [null];
            if (i < changes.length - 1 && this.ChangesOverlap(changes[i], changes[i + 1], mergedChangeArr)) {
                changes[i] = mergedChangeArr[0];
                changes.splice(i + 1, 1);
                i--;
                continue;
            }
        }
        // Shift changes back up until we hit empty or whitespace-only lines
        for (let i = changes.length - 1; i >= 0; i--) {
            const change = changes[i];
            let originalStop = 0;
            let modifiedStop = 0;
            if (i > 0) {
                const prevChange = changes[i - 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._boundaryScore(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.OriginalElementsAreEqual(originalStart, originalStart + change.originalLength)) {
                    break;
                }
                if (checkModified && !this.ModifiedElementsAreEqual(modifiedStart, modifiedStart + change.modifiedLength)) {
                    break;
                }
                const touchingPreviousChange = (originalStart === originalStop && modifiedStart === modifiedStop);
                const score = ((touchingPreviousChange ? 5 : 0)
                    + this._boundaryScore(originalStart, change.originalLength, modifiedStart, change.modifiedLength));
                if (score > bestScore) {
                    bestScore = score;
                    bestDelta = delta;
                }
            }
            change.originalStart -= bestDelta;
            change.modifiedStart -= bestDelta;
            const mergedChangeArr = [null];
            if (i > 0 && this.ChangesOverlap(changes[i - 1], changes[i], mergedChangeArr)) {
                changes[i - 1] = mergedChangeArr[0];
                changes.splice(i, 1);
                i++;
                continue;
            }
        }
        // There could be multiple longest common substrings.
        // Give preference to the ones containing longer lines
        if (this._hasStrings) {
            for (let i = 1, len = changes.length; i < len; i++) {
                const aChange = changes[i - 1];
                const bChange = changes[i];
                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;
                // Avoid wasting a lot of time with these searches
                if (matchedLength < 5 && abOriginalLength < 20 && abModifiedLength < 20) {
                    const t = this._findBetterContiguousSequence(aOriginalStart, abOriginalLength, aModifiedStart, abModifiedLength, matchedLength);
                    if (t) {
                        const [originalMatchStart, modifiedMatchStart] = t;
                        if (originalMatchStart !== aChange.originalStart + aChange.originalLength || modifiedMatchStart !== aChange.modifiedStart + aChange.modifiedLength) {
                            // switch to another sequence that has a better score
                            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;
    }
    _findBetterContiguousSequence(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 i = originalStart; i < originalMax; i++) {
            for (let j = modifiedStart; j < modifiedMax; j++) {
                const score = this._contiguousSequenceScore(i, j, desiredLength);
                if (score > 0 && score > bestScore) {
                    bestScore = score;
                    bestOriginalStart = i;
                    bestModifiedStart = j;
                }
            }
        }
        if (bestScore > 0) {
            return [bestOriginalStart, bestModifiedStart];
        }
        return null;
    }
    _contiguousSequenceScore(originalStart, modifiedStart, length) {
        let score = 0;
        for (let l = 0; l < length; l++) {
            if (!this.ElementsAreEqual(originalStart + l, modifiedStart + l)) {
                return 0;
            }
            score += this._originalStringElements[originalStart + l].length;
        }
        return score;
    }
    _OriginalIsBoundary(index) {
        if (index <= 0 || index >= this._originalElementsOrHash.length - 1) {
            return true;
        }
        return (this._hasStrings && /^\s*$/.test(this._originalStringElements[index]));
    }
    _OriginalRegionIsBoundary(originalStart, originalLength) {
        if (this._OriginalIsBoundary(originalStart) || this._OriginalIsBoundary(originalStart - 1)) {
            return true;
        }
        if (originalLength > 0) {
            const originalEnd = originalStart + originalLength;
            if (this._OriginalIsBoundary(originalEnd - 1) || this._OriginalIsBoundary(originalEnd)) {
                return true;
            }
        }
        return false;
    }
    _ModifiedIsBoundary(index) {
        if (index <= 0 || index >= this._modifiedElementsOrHash.length - 1) {
            return true;
        }
        return (this._hasStrings && /^\s*$/.test(this._modifiedStringElements[index]));
    }
    _ModifiedRegionIsBoundary(modifiedStart, modifiedLength) {
        if (this._ModifiedIsBoundary(modifiedStart) || this._ModifiedIsBoundary(modifiedStart - 1)) {
            return true;
        }
        if (modifiedLength > 0) {
            const modifiedEnd = modifiedStart + modifiedLength;
            if (this._ModifiedIsBoundary(modifiedEnd - 1) || this._ModifiedIsBoundary(modifiedEnd)) {
                return true;
            }
        }
        return false;
    }
    _boundaryScore(originalStart, originalLength, modifiedStart, modifiedLength) {
        const originalScore = (this._OriginalRegionIsBoundary(originalStart, originalLength) ? 1 : 0);
        const modifiedScore = (this._ModifiedRegionIsBoundary(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
     */
    ConcatenateChanges(left, right) {
        const mergedChangeArr = [];
        if (left.length === 0 || right.length === 0) {
            return (right.length > 0) ? right : left;
        }
        else if (this.ChangesOverlap(left[left.length - 1], right[0], mergedChangeArr)) {
            // Since we break the problem down recursively, it is possible that we
            // might recurse in the middle of a change thereby splitting it into
            // two changes. Here in the combining stage, we detect and fuse those
            // changes back together
            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
     */
    ChangesOverlap(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 DiffChange(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.
     */
    ClipDiagonalBound(diagonal, numDifferences, diagonalBaseIndex, numDiagonals) {
        if (diagonal >= 0 && diagonal < numDiagonals) {
            // Nothing to clip, its in range
            return diagonal;
        }
        // diagonalsBelow: The number of diagonals below the reference diagonal
        // diagonalsAbove: The number of diagonals above the reference 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;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/tree/indexTreeModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






function isFilterResult(obj) {
    return typeof obj === 'object' && 'visibility' in obj && 'data' in obj;
}
function getVisibleState(visibility) {
    switch (visibility) {
        case true: return 1 /* TreeVisibility.Visible */;
        case false: return 0 /* TreeVisibility.Hidden */;
        default: return visibility;
    }
}
function isCollapsibleStateUpdate(update) {
    return typeof update.collapsible === 'boolean';
}
class IndexTreeModel {
    constructor(user, list, rootElement, options = {}) {
        this.user = user;
        this.list = list;
        this.rootRef = [];
        this.eventBufferer = new EventBufferer();
        this._onDidChangeCollapseState = new Emitter();
        this.onDidChangeCollapseState = this.eventBufferer.wrapEvent(this._onDidChangeCollapseState.event);
        this._onDidChangeRenderNodeCount = new Emitter();
        this.onDidChangeRenderNodeCount = this.eventBufferer.wrapEvent(this._onDidChangeRenderNodeCount.event);
        this._onDidSplice = new Emitter();
        this.onDidSplice = this._onDidSplice.event;
        this.refilterDelayer = new Delayer(MicrotaskDelay);
        this.collapseByDefault = typeof options.collapseByDefault === 'undefined' ? false : options.collapseByDefault;
        this.filter = options.filter;
        this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === 'undefined' ? false : options.autoExpandSingleChildren;
        this.root = {
            parent: undefined,
            element: rootElement,
            children: [],
            depth: 0,
            visibleChildrenCount: 0,
            visibleChildIndex: -1,
            collapsible: false,
            collapsed: false,
            renderNodeCount: 0,
            visibility: 1 /* TreeVisibility.Visible */,
            visible: true,
            filterData: undefined
        };
    }
    splice(location, deleteCount, toInsert = Iterable.empty(), options = {}) {
        if (location.length === 0) {
            throw new TreeError(this.user, 'Invalid tree location');
        }
        if (options.diffIdentityProvider) {
            this.spliceSmart(options.diffIdentityProvider, location, deleteCount, toInsert, options);
        }
        else {
            this.spliceSimple(location, deleteCount, toInsert, options);
        }
    }
    spliceSmart(identity, location, deleteCount, toInsertIterable, options, recurseLevels) {
        var _a;
        if (toInsertIterable === void 0) { toInsertIterable = Iterable.empty(); }
        if (recurseLevels === void 0) { recurseLevels = (_a = options.diffDepth) !== null && _a !== void 0 ? _a : 0; }
        const { parentNode } = this.getParentNodeWithListIndex(location);
        if (!parentNode.lastDiffIds) {
            return this.spliceSimple(location, deleteCount, toInsertIterable, options);
        }
        const toInsert = [...toInsertIterable];
        const index = location[location.length - 1];
        const diff = new LcsDiff({ 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 we were given a 'best effort' diff, use default behavior
        if (diff.quitEarly) {
            parentNode.lastDiffIds = undefined;
            return this.spliceSimple(location, deleteCount, toInsert, options);
        }
        const locationPrefix = location.slice(0, -1);
        const recurseSplice = (fromOriginal, fromModified, count) => {
            if (recurseLevels > 0) {
                for (let i = 0; i < count; i++) {
                    fromOriginal--;
                    fromModified--;
                    this.spliceSmart(identity, [...locationPrefix, fromOriginal, 0], Number.MAX_SAFE_INTEGER, toInsert[fromModified].children, options, recurseLevels - 1);
                }
            }
        };
        let lastStartO = Math.min(parentNode.children.length, index + deleteCount);
        let lastStartM = toInsert.length;
        for (const change of diff.changes.sort((a, b) => b.originalStart - a.originalStart)) {
            recurseSplice(lastStartO, lastStartM, lastStartO - (change.originalStart + change.originalLength));
            lastStartO = change.originalStart;
            lastStartM = change.modifiedStart - index;
            this.spliceSimple([...locationPrefix, lastStartO], change.originalLength, Iterable.slice(toInsert, lastStartM, lastStartM + change.modifiedLength), options);
        }
        // at this point, startO === startM === count since any remaining prefix should match
        recurseSplice(lastStartO, lastStartM, lastStartO);
    }
    spliceSimple(location, deleteCount, toInsert = Iterable.empty(), { onDidCreateNode, onDidDeleteNode, diffIdentityProvider }) {
        const { parentNode, listIndex, revealed, visible } = this.getParentNodeWithListIndex(location);
        const treeListElementsToInsert = [];
        const nodesToInsertIterator = Iterable.map(toInsert, el => this.createTreeNode(el, parentNode, parentNode.visible ? 1 /* TreeVisibility.Visible */ : 0 /* TreeVisibility.Hidden */, revealed, treeListElementsToInsert, onDidCreateNode));
        const lastIndex = location[location.length - 1];
        const lastHadChildren = parentNode.children.length > 0;
        // figure out what's the visible child start index right before the
        // splice point
        let visibleChildStartIndex = 0;
        for (let i = lastIndex; i >= 0 && i < parentNode.children.length; i--) {
            const child = parentNode.children[i];
            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 = splice(parentNode.children, lastIndex, deleteCount, nodesToInsert);
        if (!diffIdentityProvider) {
            parentNode.lastDiffIds = undefined;
        }
        else if (parentNode.lastDiffIds) {
            splice(parentNode.lastDiffIds, lastIndex, deleteCount, nodesToInsert.map(n => diffIdentityProvider.getId(n.element).toString()));
        }
        else {
            parentNode.lastDiffIds = parentNode.children.map(n => diffIdentityProvider.getId(n.element).toString());
        }
        // figure out what is the count of deleted visible children
        let deletedVisibleChildrenCount = 0;
        for (const child of deletedNodes) {
            if (child.visible) {
                deletedVisibleChildrenCount++;
            }
        }
        // and adjust for all visible children after the splice point
        if (deletedVisibleChildrenCount !== 0) {
            for (let i = lastIndex + nodesToInsert.length; i < parentNode.children.length; i++) {
                const child = parentNode.children[i];
                if (child.visible) {
                    child.visibleChildIndex -= deletedVisibleChildrenCount;
                }
            }
        }
        // update parent's visible children count
        parentNode.visibleChildrenCount += insertedVisibleChildrenCount - deletedVisibleChildrenCount;
        if (revealed && visible) {
            const visibleDeleteCount = deletedNodes.reduce((r, node) => r + (node.visible ? node.renderNodeCount : 0), 0);
            this._updateAncestorsRenderNodeCount(parentNode, renderNodeCount - visibleDeleteCount);
            this.list.splice(listIndex, visibleDeleteCount, treeListElementsToInsert);
        }
        if (deletedNodes.length > 0 && onDidDeleteNode) {
            const visit = (node) => {
                onDidDeleteNode(node);
                node.children.forEach(visit);
            };
            deletedNodes.forEach(visit);
        }
        this._onDidSplice.fire({ insertedNodes: nodesToInsert, deletedNodes });
        const currentlyHasChildren = parentNode.children.length > 0;
        if (lastHadChildren !== currentlyHasChildren) {
            this.setCollapsible(location.slice(0, -1), currentlyHasChildren);
        }
        let node = parentNode;
        while (node) {
            if (node.visibility === 2 /* TreeVisibility.Recurse */) {
                // delayed to avoid excessive refiltering, see #135941
                this.refilterDelayer.trigger(() => this.refilter());
                break;
            }
            node = node.parent;
        }
    }
    rerender(location) {
        if (location.length === 0) {
            throw new TreeError(this.user, 'Invalid tree location');
        }
        const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location);
        if (node.visible && revealed) {
            this.list.splice(listIndex, 1, [node]);
        }
    }
    has(location) {
        return this.hasTreeNode(location);
    }
    getListIndex(location) {
        const { listIndex, visible, revealed } = this.getTreeNodeWithListIndex(location);
        return visible && revealed ? listIndex : -1;
    }
    getListRenderCount(location) {
        return this.getTreeNode(location).renderNodeCount;
    }
    isCollapsible(location) {
        return this.getTreeNode(location).collapsible;
    }
    setCollapsible(location, collapsible) {
        const node = this.getTreeNode(location);
        if (typeof collapsible === 'undefined') {
            collapsible = !node.collapsible;
        }
        const update = { collapsible };
        return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update));
    }
    isCollapsed(location) {
        return this.getTreeNode(location).collapsed;
    }
    setCollapsed(location, collapsed, recursive) {
        const node = this.getTreeNode(location);
        if (typeof collapsed === 'undefined') {
            collapsed = !node.collapsed;
        }
        const update = { collapsed, recursive: recursive || false };
        return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update));
    }
    _setCollapseState(location, update) {
        const { node, listIndex, revealed } = this.getTreeNodeWithListIndex(location);
        const result = this._setListNodeCollapseState(node, listIndex, revealed, update);
        if (node !== this.root && this.autoExpandSingleChildren && result && !isCollapsibleStateUpdate(update) && node.collapsible && !node.collapsed && !update.recursive) {
            let onlyVisibleChildIndex = -1;
            for (let i = 0; i < node.children.length; i++) {
                const child = node.children[i];
                if (child.visible) {
                    if (onlyVisibleChildIndex > -1) {
                        onlyVisibleChildIndex = -1;
                        break;
                    }
                    else {
                        onlyVisibleChildIndex = i;
                    }
                }
            }
            if (onlyVisibleChildIndex > -1) {
                this._setCollapseState([...location, onlyVisibleChildIndex], update);
            }
        }
        return result;
    }
    _setListNodeCollapseState(node, listIndex, revealed, update) {
        const result = this._setNodeCollapseState(node, update, false);
        if (!revealed || !node.visible || !result) {
            return result;
        }
        const previousRenderNodeCount = node.renderNodeCount;
        const toInsert = this.updateNodeAfterCollapseChange(node);
        const deleteCount = previousRenderNodeCount - (listIndex === -1 ? 0 : 1);
        this.list.splice(listIndex + 1, deleteCount, toInsert.slice(1));
        return result;
    }
    _setNodeCollapseState(node, update, deep) {
        let result;
        if (node === this.root) {
            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._onDidChangeCollapseState.fire({ node, deep });
            }
        }
        if (!isCollapsibleStateUpdate(update) && update.recursive) {
            for (const child of node.children) {
                result = this._setNodeCollapseState(child, update, true) || result;
            }
        }
        return result;
    }
    expandTo(location) {
        this.eventBufferer.bufferEvents(() => {
            let node = this.getTreeNode(location);
            while (node.parent) {
                node = node.parent;
                location = location.slice(0, location.length - 1);
                if (node.collapsed) {
                    this._setCollapseState(location, { collapsed: false, recursive: false });
                }
            }
        });
    }
    refilter() {
        const previousRenderNodeCount = this.root.renderNodeCount;
        const toInsert = this.updateNodeAfterFilterChange(this.root);
        this.list.splice(0, previousRenderNodeCount, toInsert);
        this.refilterDelayer.cancel();
    }
    createTreeNode(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.collapseByDefault : treeElement.collapsed,
            renderNodeCount: 1,
            visibility: 1 /* TreeVisibility.Visible */,
            visible: true,
            filterData: undefined
        };
        const visibility = this._filterNode(node, parentVisibility);
        node.visibility = visibility;
        if (revealed) {
            treeListElements.push(node);
        }
        const childElements = treeElement.children || Iterable.empty();
        const childRevealed = revealed && visibility !== 0 /* TreeVisibility.Hidden */ && !node.collapsed;
        const childNodes = Iterable.map(childElements, el => this.createTreeNode(el, node, visibility, childRevealed, treeListElements, onDidCreateNode));
        let visibleChildrenCount = 0;
        let renderNodeCount = 1;
        for (const child of childNodes) {
            node.children.push(child);
            renderNodeCount += child.renderNodeCount;
            if (child.visible) {
                child.visibleChildIndex = visibleChildrenCount++;
            }
        }
        node.collapsible = node.collapsible || node.children.length > 0;
        node.visibleChildrenCount = visibleChildrenCount;
        node.visible = visibility === 2 /* TreeVisibility.Recurse */ ? visibleChildrenCount > 0 : (visibility === 1 /* TreeVisibility.Visible */);
        if (!node.visible) {
            node.renderNodeCount = 0;
            if (revealed) {
                treeListElements.pop();
            }
        }
        else if (!node.collapsed) {
            node.renderNodeCount = renderNodeCount;
        }
        onDidCreateNode === null || onDidCreateNode === void 0 ? void 0 : onDidCreateNode(node);
        return node;
    }
    updateNodeAfterCollapseChange(node) {
        const previousRenderNodeCount = node.renderNodeCount;
        const result = [];
        this._updateNodeAfterCollapseChange(node, result);
        this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount);
        return result;
    }
    _updateNodeAfterCollapseChange(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._updateNodeAfterCollapseChange(child, result);
            }
        }
        this._onDidChangeRenderNodeCount.fire(node);
        return node.renderNodeCount;
    }
    updateNodeAfterFilterChange(node) {
        const previousRenderNodeCount = node.renderNodeCount;
        const result = [];
        this._updateNodeAfterFilterChange(node, node.visible ? 1 /* TreeVisibility.Visible */ : 0 /* TreeVisibility.Hidden */, result);
        this._updateAncestorsRenderNodeCount(node.parent, result.length - previousRenderNodeCount);
        return result;
    }
    _updateNodeAfterFilterChange(node, parentVisibility, result, revealed = true) {
        let visibility;
        if (node !== this.root) {
            visibility = this._filterNode(node, parentVisibility);
            if (visibility === 0 /* TreeVisibility.Hidden */) {
                node.visible = false;
                node.renderNodeCount = 0;
                return false;
            }
            if (revealed) {
                result.push(node);
            }
        }
        const resultStartLength = result.length;
        node.renderNodeCount = node === this.root ? 0 : 1;
        let hasVisibleDescendants = false;
        if (!node.collapsed || visibility !== 0 /* TreeVisibility.Hidden */) {
            let visibleChildIndex = 0;
            for (const child of node.children) {
                hasVisibleDescendants = this._updateNodeAfterFilterChange(child, visibility, result, revealed && !node.collapsed) || hasVisibleDescendants;
                if (child.visible) {
                    child.visibleChildIndex = visibleChildIndex++;
                }
            }
            node.visibleChildrenCount = visibleChildIndex;
        }
        else {
            node.visibleChildrenCount = 0;
        }
        if (node !== this.root) {
            node.visible = visibility === 2 /* TreeVisibility.Recurse */ ? hasVisibleDescendants : (visibility === 1 /* TreeVisibility.Visible */);
            node.visibility = visibility;
        }
        if (!node.visible) {
            node.renderNodeCount = 0;
            if (revealed) {
                result.pop();
            }
        }
        else if (!node.collapsed) {
            node.renderNodeCount += result.length - resultStartLength;
        }
        this._onDidChangeRenderNodeCount.fire(node);
        return node.visible;
    }
    _updateAncestorsRenderNodeCount(node, diff) {
        if (diff === 0) {
            return;
        }
        while (node) {
            node.renderNodeCount += diff;
            this._onDidChangeRenderNodeCount.fire(node);
            node = node.parent;
        }
    }
    _filterNode(node, parentVisibility) {
        const result = this.filter ? this.filter.filter(node.element, parentVisibility) : 1 /* TreeVisibility.Visible */;
        if (typeof result === 'boolean') {
            node.filterData = undefined;
            return result ? 1 /* TreeVisibility.Visible */ : 0 /* TreeVisibility.Hidden */;
        }
        else if (isFilterResult(result)) {
            node.filterData = result.data;
            return getVisibleState(result.visibility);
        }
        else {
            node.filterData = undefined;
            return getVisibleState(result);
        }
    }
    // cheap
    hasTreeNode(location, node = this.root) {
        if (!location || location.length === 0) {
            return true;
        }
        const [index, ...rest] = location;
        if (index < 0 || index > node.children.length) {
            return false;
        }
        return this.hasTreeNode(rest, node.children[index]);
    }
    // cheap
    getTreeNode(location, node = this.root) {
        if (!location || location.length === 0) {
            return node;
        }
        const [index, ...rest] = location;
        if (index < 0 || index > node.children.length) {
            throw new TreeError(this.user, 'Invalid tree location');
        }
        return this.getTreeNode(rest, node.children[index]);
    }
    // expensive
    getTreeNodeWithListIndex(location) {
        if (location.length === 0) {
            return { node: this.root, listIndex: -1, revealed: true, visible: false };
        }
        const { parentNode, listIndex, revealed, visible } = this.getParentNodeWithListIndex(location);
        const index = location[location.length - 1];
        if (index < 0 || index > parentNode.children.length) {
            throw new TreeError(this.user, 'Invalid tree location');
        }
        const node = parentNode.children[index];
        return { node, listIndex, revealed, visible: visible && node.visible };
    }
    getParentNodeWithListIndex(location, node = this.root, listIndex = 0, revealed = true, visible = true) {
        const [index, ...rest] = location;
        if (index < 0 || index > node.children.length) {
            throw new TreeError(this.user, 'Invalid tree location');
        }
        // TODO@joao perf!
        for (let i = 0; i < index; i++) {
            listIndex += node.children[i].renderNodeCount;
        }
        revealed = revealed && !node.collapsed;
        visible = visible && node.visible;
        if (rest.length === 0) {
            return { parentNode: node, listIndex, revealed, visible };
        }
        return this.getParentNodeWithListIndex(rest, node.children[index], listIndex + 1, revealed, visible);
    }
    getNode(location = []) {
        return this.getTreeNode(location);
    }
    // TODO@joao perf!
    getNodeLocation(node) {
        const location = [];
        let indexTreeNode = node; // typing woes
        while (indexTreeNode.parent) {
            location.push(indexTreeNode.parent.children.indexOf(indexTreeNode));
            indexTreeNode = indexTreeNode.parent;
        }
        return location.reverse();
    }
    getParentNodeLocation(location) {
        if (location.length === 0) {
            return undefined;
        }
        else if (location.length === 1) {
            return [];
        }
        else {
            return tail2(location)[0];
        }
    }
    getFirstElementChild(location) {
        const node = this.getTreeNode(location);
        if (node.children.length === 0) {
            return undefined;
        }
        return node.children[0].element;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/collections.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class SetMap {
    constructor() {
        this.map = new Map();
    }
    add(key, value) {
        let values = this.map.get(key);
        if (!values) {
            values = new Set();
            this.map.set(key, values);
        }
        values.add(value);
    }
    delete(key, value) {
        const values = this.map.get(key);
        if (!values) {
            return;
        }
        values.delete(value);
        if (values.size === 0) {
            this.map.delete(key);
        }
    }
    forEach(key, fn) {
        const values = this.map.get(key);
        if (!values) {
            return;
        }
        values.forEach(fn);
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/tree/media/tree.css
var tree = __webpack_require__(52398);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/tree/media/tree.css

      
      
      
      
      
      
      
      
      

var tree_options = {};

tree_options.styleTagTransform = (styleTagTransform_default());
tree_options.setAttributes = (setAttributesWithoutAttributes_default());

      tree_options.insert = insertBySelector_default().bind(null, "head");
    
tree_options.domAPI = (styleDomAPI_default());
tree_options.insertStyleElement = (insertStyleElement_default());

var tree_update = injectStylesIntoStyleTag_default()(tree/* default */.A, tree_options);




       /* harmony default export */ const media_tree = (tree/* default */.A && tree/* default */.A.locals ? tree/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/tree/abstractTree.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var abstractTree_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};






















class TreeElementsDragAndDropData extends ElementsDragAndDropData {
    constructor(data) {
        super(data.elements.map(node => node.element));
        this.data = data;
    }
}
function asTreeDragAndDropData(data) {
    if (data instanceof ElementsDragAndDropData) {
        return new TreeElementsDragAndDropData(data);
    }
    return data;
}
class TreeNodeListDragAndDrop {
    constructor(modelProvider, dnd) {
        this.modelProvider = modelProvider;
        this.dnd = dnd;
        this.autoExpandDisposable = Disposable.None;
    }
    getDragURI(node) {
        return this.dnd.getDragURI(node.element);
    }
    getDragLabel(nodes, originalEvent) {
        if (this.dnd.getDragLabel) {
            return this.dnd.getDragLabel(nodes.map(node => node.element), originalEvent);
        }
        return undefined;
    }
    onDragStart(data, originalEvent) {
        var _a, _b;
        (_b = (_a = this.dnd).onDragStart) === null || _b === void 0 ? void 0 : _b.call(_a, asTreeDragAndDropData(data), originalEvent);
    }
    onDragOver(data, targetNode, targetIndex, originalEvent, raw = true) {
        const result = this.dnd.onDragOver(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
        const didChangeAutoExpandNode = this.autoExpandNode !== targetNode;
        if (didChangeAutoExpandNode) {
            this.autoExpandDisposable.dispose();
            this.autoExpandNode = targetNode;
        }
        if (typeof targetNode === 'undefined') {
            return result;
        }
        if (didChangeAutoExpandNode && typeof result !== 'boolean' && result.autoExpand) {
            this.autoExpandDisposable = disposableTimeout(() => {
                const model = this.modelProvider();
                const ref = model.getNodeLocation(targetNode);
                if (model.isCollapsed(ref)) {
                    model.setCollapsed(ref, false);
                }
                this.autoExpandNode = undefined;
            }, 500);
        }
        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' ? undefined : result.effect;
                return { accept, effect, feedback: [targetIndex] };
            }
            return result;
        }
        if (result.bubble === 1 /* TreeDragOverBubble.Up */) {
            const model = this.modelProvider();
            const ref = model.getNodeLocation(targetNode);
            const parentRef = model.getParentNodeLocation(ref);
            const parentNode = model.getNode(parentRef);
            const parentIndex = parentRef && model.getListIndex(parentRef);
            return this.onDragOver(data, parentNode, parentIndex, originalEvent, false);
        }
        const model = this.modelProvider();
        const ref = model.getNodeLocation(targetNode);
        const start = model.getListIndex(ref);
        const length = model.getListRenderCount(ref);
        return Object.assign(Object.assign({}, result), { feedback: range(start, start + length) });
    }
    drop(data, targetNode, targetIndex, originalEvent) {
        this.autoExpandDisposable.dispose();
        this.autoExpandNode = undefined;
        this.dnd.drop(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
    }
    onDragEnd(originalEvent) {
        var _a, _b;
        (_b = (_a = this.dnd).onDragEnd) === null || _b === void 0 ? void 0 : _b.call(_a, originalEvent);
    }
}
function asListOptions(modelProvider, options) {
    return options && Object.assign(Object.assign({}, options), { identityProvider: options.identityProvider && {
            getId(el) {
                return options.identityProvider.getId(el.element);
            }
        }, dnd: options.dnd && new TreeNodeListDragAndDrop(modelProvider, options.dnd), multipleSelectionController: options.multipleSelectionController && {
            isSelectionSingleChangeEvent(e) {
                return options.multipleSelectionController.isSelectionSingleChangeEvent(Object.assign(Object.assign({}, e), { element: e.element }));
            },
            isSelectionRangeChangeEvent(e) {
                return options.multipleSelectionController.isSelectionRangeChangeEvent(Object.assign(Object.assign({}, e), { element: e.element }));
            }
        }, accessibilityProvider: options.accessibilityProvider && Object.assign(Object.assign({}, options.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: options.accessibilityProvider && options.accessibilityProvider.isChecked ? (node) => {
                return options.accessibilityProvider.isChecked(node.element);
            } : undefined, getRole: options.accessibilityProvider && options.accessibilityProvider.getRole ? (node) => {
                return options.accessibilityProvider.getRole(node.element);
            } : () => 'treeitem', getAriaLabel(e) {
                return options.accessibilityProvider.getAriaLabel(e.element);
            },
            getWidgetAriaLabel() {
                return options.accessibilityProvider.getWidgetAriaLabel();
            }, getWidgetRole: options.accessibilityProvider && options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => 'tree', getAriaLevel: options.accessibilityProvider && options.accessibilityProvider.getAriaLevel ? (node) => options.accessibilityProvider.getAriaLevel(node.element) : (node) => {
                return node.depth;
            }, getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (node => {
                return options.accessibilityProvider.getActiveDescendantId(node.element);
            }) }), keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, options.keyboardNavigationLabelProvider), { getKeyboardNavigationLabel(node) {
                return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(node.element);
            } }) });
}
class ComposedTreeDelegate {
    constructor(delegate) {
        this.delegate = delegate;
    }
    getHeight(element) {
        return this.delegate.getHeight(element.element);
    }
    getTemplateId(element) {
        return this.delegate.getTemplateId(element.element);
    }
    hasDynamicHeight(element) {
        return !!this.delegate.hasDynamicHeight && this.delegate.hasDynamicHeight(element.element);
    }
    setDynamicHeight(element, height) {
        var _a, _b;
        (_b = (_a = this.delegate).setDynamicHeight) === null || _b === void 0 ? void 0 : _b.call(_a, element.element, height);
    }
}
var RenderIndentGuides;
(function (RenderIndentGuides) {
    RenderIndentGuides["None"] = "none";
    RenderIndentGuides["OnHover"] = "onHover";
    RenderIndentGuides["Always"] = "always";
})(RenderIndentGuides || (RenderIndentGuides = {}));
class EventCollection {
    constructor(onDidChange, _elements = []) {
        this._elements = _elements;
        this.disposables = new DisposableStore();
        this.onDidChange = Event.forEach(onDidChange, elements => this._elements = elements, this.disposables);
    }
    get elements() {
        return this._elements;
    }
    dispose() {
        this.disposables.dispose();
    }
}
class TreeRenderer {
    constructor(renderer, modelProvider, onDidChangeCollapseState, activeNodes, options = {}) {
        var _a;
        this.renderer = renderer;
        this.modelProvider = modelProvider;
        this.activeNodes = activeNodes;
        this.renderedElements = new Map();
        this.renderedNodes = new Map();
        this.indent = TreeRenderer.DefaultIndent;
        this.hideTwistiesOfChildlessElements = false;
        this.shouldRenderIndentGuides = false;
        this.renderedIndentGuides = new SetMap();
        this.activeIndentNodes = new Set();
        this.indentGuidesDisposable = Disposable.None;
        this.disposables = new DisposableStore();
        this.templateId = renderer.templateId;
        this.updateOptions(options);
        Event.map(onDidChangeCollapseState, e => e.node)(this.onDidChangeNodeTwistieState, this, this.disposables);
        (_a = renderer.onDidChangeTwistieState) === null || _a === void 0 ? void 0 : _a.call(renderer, this.onDidChangeTwistieState, this, this.disposables);
    }
    updateOptions(options = {}) {
        if (typeof options.indent !== 'undefined') {
            this.indent = clamp(options.indent, 0, 40);
        }
        if (typeof options.renderIndentGuides !== 'undefined') {
            const shouldRenderIndentGuides = options.renderIndentGuides !== RenderIndentGuides.None;
            if (shouldRenderIndentGuides !== this.shouldRenderIndentGuides) {
                this.shouldRenderIndentGuides = shouldRenderIndentGuides;
                this.indentGuidesDisposable.dispose();
                if (shouldRenderIndentGuides) {
                    const disposables = new DisposableStore();
                    this.activeNodes.onDidChange(this._onDidChangeActiveNodes, this, disposables);
                    this.indentGuidesDisposable = disposables;
                    this._onDidChangeActiveNodes(this.activeNodes.elements);
                }
            }
        }
        if (typeof options.hideTwistiesOfChildlessElements !== 'undefined') {
            this.hideTwistiesOfChildlessElements = options.hideTwistiesOfChildlessElements;
        }
    }
    renderTemplate(container) {
        const el = append(container, dom_$('.monaco-tl-row'));
        const indent = append(el, dom_$('.monaco-tl-indent'));
        const twistie = append(el, dom_$('.monaco-tl-twistie'));
        const contents = append(el, dom_$('.monaco-tl-contents'));
        const templateData = this.renderer.renderTemplate(contents);
        return { container, indent, twistie, indentGuidesDisposable: Disposable.None, templateData };
    }
    renderElement(node, index, templateData, height) {
        if (typeof height === 'number') {
            this.renderedNodes.set(node, { templateData, height });
            this.renderedElements.set(node.element, node);
        }
        const indent = TreeRenderer.DefaultIndent + (node.depth - 1) * this.indent;
        templateData.twistie.style.paddingLeft = `${indent}px`;
        templateData.indent.style.width = `${indent + this.indent - 16}px`;
        this.renderTwistie(node, templateData);
        if (typeof height === 'number') {
            this.renderIndentGuides(node, templateData);
        }
        this.renderer.renderElement(node, index, templateData.templateData, height);
    }
    disposeElement(node, index, templateData, height) {
        var _a, _b;
        templateData.indentGuidesDisposable.dispose();
        (_b = (_a = this.renderer).disposeElement) === null || _b === void 0 ? void 0 : _b.call(_a, node, index, templateData.templateData, height);
        if (typeof height === 'number') {
            this.renderedNodes.delete(node);
            this.renderedElements.delete(node.element);
        }
    }
    disposeTemplate(templateData) {
        this.renderer.disposeTemplate(templateData.templateData);
    }
    onDidChangeTwistieState(element) {
        const node = this.renderedElements.get(element);
        if (!node) {
            return;
        }
        this.onDidChangeNodeTwistieState(node);
    }
    onDidChangeNodeTwistieState(node) {
        const data = this.renderedNodes.get(node);
        if (!data) {
            return;
        }
        this.renderTwistie(node, data.templateData);
        this._onDidChangeActiveNodes(this.activeNodes.elements);
        this.renderIndentGuides(node, data.templateData);
    }
    renderTwistie(node, templateData) {
        templateData.twistie.classList.remove(...Codicon.treeItemExpanded.classNamesArray);
        let twistieRendered = false;
        if (this.renderer.renderTwistie) {
            twistieRendered = this.renderer.renderTwistie(node.element, templateData.twistie);
        }
        if (node.collapsible && (!this.hideTwistiesOfChildlessElements || node.visibleChildrenCount > 0)) {
            if (!twistieRendered) {
                templateData.twistie.classList.add(...Codicon.treeItemExpanded.classNamesArray);
            }
            templateData.twistie.classList.add('collapsible');
            templateData.twistie.classList.toggle('collapsed', node.collapsed);
        }
        else {
            templateData.twistie.classList.remove('collapsible', 'collapsed');
        }
        if (node.collapsible) {
            templateData.container.setAttribute('aria-expanded', String(!node.collapsed));
        }
        else {
            templateData.container.removeAttribute('aria-expanded');
        }
    }
    renderIndentGuides(target, templateData) {
        clearNode(templateData.indent);
        templateData.indentGuidesDisposable.dispose();
        if (!this.shouldRenderIndentGuides) {
            return;
        }
        const disposableStore = new DisposableStore();
        const model = this.modelProvider();
        let node = target;
        while (true) {
            const ref = model.getNodeLocation(node);
            const parentRef = model.getParentNodeLocation(ref);
            if (!parentRef) {
                break;
            }
            const parent = model.getNode(parentRef);
            const guide = dom_$('.indent-guide', { style: `width: ${this.indent}px` });
            if (this.activeIndentNodes.has(parent)) {
                guide.classList.add('active');
            }
            if (templateData.indent.childElementCount === 0) {
                templateData.indent.appendChild(guide);
            }
            else {
                templateData.indent.insertBefore(guide, templateData.indent.firstElementChild);
            }
            this.renderedIndentGuides.add(parent, guide);
            disposableStore.add(toDisposable(() => this.renderedIndentGuides.delete(parent, guide)));
            node = parent;
        }
        templateData.indentGuidesDisposable = disposableStore;
    }
    _onDidChangeActiveNodes(nodes) {
        if (!this.shouldRenderIndentGuides) {
            return;
        }
        const set = new Set();
        const model = this.modelProvider();
        nodes.forEach(node => {
            const ref = model.getNodeLocation(node);
            try {
                const parentRef = model.getParentNodeLocation(ref);
                if (node.collapsible && node.children.length > 0 && !node.collapsed) {
                    set.add(node);
                }
                else if (parentRef) {
                    set.add(model.getNode(parentRef));
                }
            }
            catch (_a) {
                // noop
            }
        });
        this.activeIndentNodes.forEach(node => {
            if (!set.has(node)) {
                this.renderedIndentGuides.forEach(node, line => line.classList.remove('active'));
            }
        });
        set.forEach(node => {
            if (!this.activeIndentNodes.has(node)) {
                this.renderedIndentGuides.forEach(node, line => line.classList.add('active'));
            }
        });
        this.activeIndentNodes = set;
    }
    dispose() {
        this.renderedNodes.clear();
        this.renderedElements.clear();
        this.indentGuidesDisposable.dispose();
        dispose(this.disposables);
    }
}
TreeRenderer.DefaultIndent = 8;
class FindFilter {
    constructor(tree, keyboardNavigationLabelProvider, _filter) {
        this.tree = tree;
        this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
        this._filter = _filter;
        this._totalCount = 0;
        this._matchCount = 0;
        this._pattern = '';
        this._lowercasePattern = '';
        this.disposables = new DisposableStore();
        tree.onWillRefilter(this.reset, this, this.disposables);
    }
    get totalCount() { return this._totalCount; }
    get matchCount() { return this._matchCount; }
    filter(element, parentVisibility) {
        let visibility = 1 /* TreeVisibility.Visible */;
        if (this._filter) {
            const result = this._filter.filter(element, parentVisibility);
            if (typeof result === 'boolean') {
                visibility = result ? 1 /* TreeVisibility.Visible */ : 0 /* TreeVisibility.Hidden */;
            }
            else if (isFilterResult(result)) {
                visibility = getVisibleState(result.visibility);
            }
            else {
                visibility = result;
            }
            if (visibility === 0 /* TreeVisibility.Hidden */) {
                return false;
            }
        }
        this._totalCount++;
        if (!this._pattern) {
            this._matchCount++;
            return { data: FuzzyScore.Default, visibility };
        }
        const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(element);
        const labels = Array.isArray(label) ? label : [label];
        for (const l of labels) {
            const labelStr = l && l.toString();
            if (typeof labelStr === 'undefined') {
                return { data: FuzzyScore.Default, visibility };
            }
            const score = fuzzyScore(this._pattern, this._lowercasePattern, 0, labelStr, labelStr.toLowerCase(), 0, { firstMatchCanBeWeak: true, boostFullMatch: true });
            if (score) {
                this._matchCount++;
                return labels.length === 1 ?
                    { data: score, visibility } :
                    { data: { label: labelStr, score: score }, visibility };
            }
        }
        if (this.tree.findMode === TreeFindMode.Filter) {
            return 2 /* TreeVisibility.Recurse */;
        }
        else {
            return { data: FuzzyScore.Default, visibility };
        }
    }
    reset() {
        this._totalCount = 0;
        this._matchCount = 0;
    }
    dispose() {
        dispose(this.disposables);
    }
}
class ModeToggle extends Toggle {
    constructor(opts) {
        var _a;
        super({
            icon: Codicon.filter,
            title: localize('filter', "Filter"),
            isChecked: (_a = opts === null || opts === void 0 ? void 0 : opts.isChecked) !== null && _a !== void 0 ? _a : false,
            inputActiveOptionBorder: opts === null || opts === void 0 ? void 0 : opts.inputActiveOptionBorder,
            inputActiveOptionForeground: opts === null || opts === void 0 ? void 0 : opts.inputActiveOptionForeground,
            inputActiveOptionBackground: opts === null || opts === void 0 ? void 0 : opts.inputActiveOptionBackground
        });
    }
}
var TreeFindMode;
(function (TreeFindMode) {
    TreeFindMode[TreeFindMode["Highlight"] = 0] = "Highlight";
    TreeFindMode[TreeFindMode["Filter"] = 1] = "Filter";
})(TreeFindMode || (TreeFindMode = {}));
class FindWidget extends Disposable {
    constructor(container, tree, contextViewProvider, mode, options) {
        super();
        this.tree = tree;
        this.elements = h('.monaco-tree-type-filter', [
            h('.monaco-tree-type-filter-grab.codicon.codicon-debug-gripper@grab', { tabIndex: 0 }),
            h('.monaco-tree-type-filter-input@findInput'),
            h('.monaco-tree-type-filter-actionbar@actionbar'),
        ]);
        this.width = 0;
        this.right = 0;
        this._onDidDisable = new Emitter();
        container.appendChild(this.elements.root);
        this._register(toDisposable(() => container.removeChild(this.elements.root)));
        this.modeToggle = this._register(new ModeToggle(Object.assign(Object.assign({}, options), { isChecked: mode === TreeFindMode.Filter })));
        this.onDidChangeMode = Event.map(this.modeToggle.onChange, () => this.modeToggle.checked ? TreeFindMode.Filter : TreeFindMode.Highlight, this._store);
        this.findInput = this._register(new FindInput(this.elements.findInput, contextViewProvider, false, {
            label: localize('type to search', "Type to search"),
            additionalToggles: [this.modeToggle]
        }));
        this.actionbar = this._register(new ActionBar(this.elements.actionbar));
        this.mode = mode;
        const emitter = this._register(new DomEmitter(this.findInput.inputBox.inputElement, 'keydown'));
        const onKeyDown = this._register(Event.chain(emitter.event))
            .map(e => new StandardKeyboardEvent(e))
            .event;
        this._register(onKeyDown((e) => {
            switch (e.keyCode) {
                case 18 /* KeyCode.DownArrow */:
                    e.preventDefault();
                    e.stopPropagation();
                    this.tree.domFocus();
                    return;
            }
        }));
        const closeAction = this._register(new Action('close', localize('close', "Close"), 'codicon codicon-close', true, () => this.dispose()));
        this.actionbar.push(closeAction, { icon: true, label: false });
        const onGrabMouseDown = this._register(new DomEmitter(this.elements.grab, 'mousedown'));
        this._register(onGrabMouseDown.event(e => {
            const disposables = new DisposableStore();
            const onWindowMouseMove = disposables.add(new DomEmitter(window, 'mousemove'));
            const onWindowMouseUp = disposables.add(new DomEmitter(window, 'mouseup'));
            const startRight = this.right;
            const startX = e.pageX;
            this.elements.grab.classList.add('grabbing');
            const update = (e) => {
                const deltaX = e.pageX - startX;
                this.right = startRight - deltaX;
                this.layout();
            };
            disposables.add(onWindowMouseMove.event(update));
            disposables.add(onWindowMouseUp.event(e => {
                update(e);
                this.elements.grab.classList.remove('grabbing');
                disposables.dispose();
            }));
        }));
        const onGrabKeyDown = this._register(Event.chain(this._register(new DomEmitter(this.elements.grab, 'keydown')).event))
            .map(e => new StandardKeyboardEvent(e))
            .event;
        this._register(onGrabKeyDown((e) => {
            let right;
            if (e.keyCode === 15 /* KeyCode.LeftArrow */) {
                right = Number.POSITIVE_INFINITY;
            }
            else if (e.keyCode === 17 /* KeyCode.RightArrow */) {
                right = 0;
            }
            else if (e.keyCode === 10 /* KeyCode.Space */) {
                right = this.right === 0 ? Number.POSITIVE_INFINITY : 0;
            }
            if (right !== undefined) {
                e.preventDefault();
                e.stopPropagation();
                this.right = right;
                this.layout();
            }
        }));
        this.onDidChangeValue = this.findInput.onDidChange;
        this.style(options !== null && options !== void 0 ? options : {});
    }
    set mode(mode) {
        this.modeToggle.checked = mode === TreeFindMode.Filter;
        this.findInput.inputBox.setPlaceHolder(mode === TreeFindMode.Filter ? localize('type to filter', "Type to filter") : localize('type to search', "Type to search"));
    }
    style(styles) {
        this.findInput.style(styles);
        if (styles.listFilterWidgetBackground) {
            this.elements.root.style.backgroundColor = styles.listFilterWidgetBackground.toString();
        }
        if (styles.listFilterWidgetShadow) {
            this.elements.root.style.boxShadow = `0 0 8px 2px ${styles.listFilterWidgetShadow}`;
        }
    }
    layout(width = this.width) {
        this.width = width;
        this.right = clamp(this.right, 0, Math.max(0, width - 212));
        this.elements.root.style.right = `${this.right}px`;
    }
    showMessage(message) {
        this.findInput.showMessage(message);
    }
    clearMessage() {
        this.findInput.clearMessage();
    }
    dispose() {
        const _super = Object.create(null, {
            dispose: { get: () => super.dispose }
        });
        return abstractTree_awaiter(this, void 0, void 0, function* () {
            this._onDidDisable.fire();
            this.elements.root.classList.add('disabled');
            yield timeout(300);
            _super.dispose.call(this);
        });
    }
}
class FindController {
    constructor(tree, model, view, filter, contextViewProvider) {
        var _a;
        this.tree = tree;
        this.view = view;
        this.filter = filter;
        this.contextViewProvider = contextViewProvider;
        this._pattern = '';
        this.width = 0;
        this._onDidChangeMode = new Emitter();
        this.onDidChangeMode = this._onDidChangeMode.event;
        this._onDidChangePattern = new Emitter();
        this._onDidChangeOpenState = new Emitter();
        this.onDidChangeOpenState = this._onDidChangeOpenState.event;
        this.enabledDisposables = new DisposableStore();
        this.disposables = new DisposableStore();
        this._mode = (_a = tree.options.defaultFindMode) !== null && _a !== void 0 ? _a : TreeFindMode.Highlight;
        model.onDidSplice(this.onDidSpliceModel, this, this.disposables);
    }
    get pattern() { return this._pattern; }
    get mode() { return this._mode; }
    set mode(mode) {
        if (mode === this._mode) {
            return;
        }
        this._mode = mode;
        if (this.widget) {
            this.widget.mode = this._mode;
        }
        this.tree.refilter();
        this.render();
        this._onDidChangeMode.fire(mode);
    }
    onDidSpliceModel() {
        if (!this.widget || this.pattern.length === 0) {
            return;
        }
        this.tree.refilter();
        this.render();
    }
    render() {
        var _a, _b;
        const noMatches = this.filter.totalCount > 0 && this.filter.matchCount === 0;
        if (this.pattern && noMatches) {
            (_a = this.widget) === null || _a === void 0 ? void 0 : _a.showMessage({ type: 2 /* MessageType.WARNING */, content: localize('not found', "No elements found.") });
        }
        else {
            (_b = this.widget) === null || _b === void 0 ? void 0 : _b.clearMessage();
        }
    }
    shouldAllowFocus(node) {
        if (!this.widget || !this.pattern || this._mode === TreeFindMode.Filter) {
            return true;
        }
        if (this.filter.totalCount > 0 && this.filter.matchCount <= 1) {
            return true;
        }
        return !FuzzyScore.isDefault(node.filterData);
    }
    style(styles) {
        var _a;
        this.styles = styles;
        (_a = this.widget) === null || _a === void 0 ? void 0 : _a.style(styles);
    }
    layout(width) {
        var _a;
        this.width = width;
        (_a = this.widget) === null || _a === void 0 ? void 0 : _a.layout(width);
    }
    dispose() {
        this._onDidChangePattern.dispose();
        this.enabledDisposables.dispose();
        this.disposables.dispose();
    }
}
function asTreeMouseEvent(event) {
    let target = TreeMouseEventTarget.Unknown;
    if (hasParentWithClass(event.browserEvent.target, 'monaco-tl-twistie', 'monaco-tl-row')) {
        target = TreeMouseEventTarget.Twistie;
    }
    else if (hasParentWithClass(event.browserEvent.target, 'monaco-tl-contents', 'monaco-tl-row')) {
        target = TreeMouseEventTarget.Element;
    }
    else if (hasParentWithClass(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 dfs(node, fn) {
    fn(node);
    node.children.forEach(child => dfs(child, fn));
}
/**
 * The trait concept needs to exist at the tree level, because collapsed
 * tree nodes will not be known by the list.
 */
class abstractTree_Trait {
    constructor(getFirstViewElementWithTrait, identityProvider) {
        this.getFirstViewElementWithTrait = getFirstViewElementWithTrait;
        this.identityProvider = identityProvider;
        this.nodes = [];
        this._onDidChange = new Emitter();
        this.onDidChange = this._onDidChange.event;
    }
    get nodeSet() {
        if (!this._nodeSet) {
            this._nodeSet = this.createNodeSet();
        }
        return this._nodeSet;
    }
    set(nodes, browserEvent) {
        if (!(browserEvent === null || browserEvent === void 0 ? void 0 : browserEvent.__forceEvent) && equals(this.nodes, nodes)) {
            return;
        }
        this._set(nodes, false, browserEvent);
    }
    _set(nodes, silent, browserEvent) {
        this.nodes = [...nodes];
        this.elements = undefined;
        this._nodeSet = undefined;
        if (!silent) {
            const that = this;
            this._onDidChange.fire({ get elements() { return that.get(); }, browserEvent });
        }
    }
    get() {
        if (!this.elements) {
            this.elements = this.nodes.map(node => node.element);
        }
        return [...this.elements];
    }
    getNodes() {
        return this.nodes;
    }
    has(node) {
        return this.nodeSet.has(node);
    }
    onDidModelSplice({ insertedNodes, deletedNodes }) {
        if (!this.identityProvider) {
            const set = this.createNodeSet();
            const visit = (node) => set.delete(node);
            deletedNodes.forEach(node => dfs(node, visit));
            this.set([...set.values()]);
            return;
        }
        const deletedNodesIdSet = new Set();
        const deletedNodesVisitor = (node) => deletedNodesIdSet.add(this.identityProvider.getId(node.element).toString());
        deletedNodes.forEach(node => dfs(node, deletedNodesVisitor));
        const insertedNodesMap = new Map();
        const insertedNodesVisitor = (node) => insertedNodesMap.set(this.identityProvider.getId(node.element).toString(), node);
        insertedNodes.forEach(node => dfs(node, insertedNodesVisitor));
        const nodes = [];
        for (const node of this.nodes) {
            const id = this.identityProvider.getId(node.element).toString();
            const wasDeleted = deletedNodesIdSet.has(id);
            if (!wasDeleted) {
                nodes.push(node);
            }
            else {
                const insertedNode = insertedNodesMap.get(id);
                if (insertedNode) {
                    nodes.push(insertedNode);
                }
            }
        }
        if (this.nodes.length > 0 && nodes.length === 0) {
            const node = this.getFirstViewElementWithTrait();
            if (node) {
                nodes.push(node);
            }
        }
        this._set(nodes, true);
    }
    createNodeSet() {
        const set = new Set();
        for (const node of this.nodes) {
            set.add(node);
        }
        return set;
    }
}
class TreeNodeListMouseController extends MouseController {
    constructor(list, tree) {
        super(list);
        this.tree = tree;
    }
    onViewPointer(e) {
        if (isButton(e.browserEvent.target) ||
            isInputElement(e.browserEvent.target) ||
            isMonacoEditor(e.browserEvent.target)) {
            return;
        }
        const node = e.element;
        if (!node) {
            return super.onViewPointer(e);
        }
        if (this.isSelectionRangeChangeEvent(e) || this.isSelectionSingleChangeEvent(e)) {
            return super.onViewPointer(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);
        let expandOnlyOnTwistieClick = false;
        if (typeof this.tree.expandOnlyOnTwistieClick === 'function') {
            expandOnlyOnTwistieClick = this.tree.expandOnlyOnTwistieClick(node.element);
        }
        else {
            expandOnlyOnTwistieClick = !!this.tree.expandOnlyOnTwistieClick;
        }
        if (expandOnlyOnTwistieClick && !onTwistie && e.browserEvent.detail !== 2) {
            return super.onViewPointer(e);
        }
        if (!this.tree.expandOnDoubleClick && e.browserEvent.detail === 2) {
            return super.onViewPointer(e);
        }
        if (node.collapsible) {
            const model = this.tree.model; // internal
            const location = model.getNodeLocation(node);
            const recursive = e.browserEvent.altKey;
            this.tree.setFocus([location]);
            model.setCollapsed(location, undefined, recursive);
            if (expandOnlyOnTwistieClick && onTwistie) {
                return;
            }
        }
        super.onViewPointer(e);
    }
    onDoubleClick(e) {
        const onTwistie = e.browserEvent.target.classList.contains('monaco-tl-twistie');
        if (onTwistie || !this.tree.expandOnDoubleClick) {
            return;
        }
        super.onDoubleClick(e);
    }
}
/**
 * We use this List subclass to restore selection and focus as nodes
 * get rendered in the list, possibly due to a node expand() call.
 */
class TreeNodeList extends List {
    constructor(user, container, virtualDelegate, renderers, focusTrait, selectionTrait, anchorTrait, options) {
        super(user, container, virtualDelegate, renderers, options);
        this.focusTrait = focusTrait;
        this.selectionTrait = selectionTrait;
        this.anchorTrait = anchorTrait;
    }
    createMouseController(options) {
        return new TreeNodeListMouseController(this, options.tree);
    }
    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.focusTrait.has(node)) {
                additionalFocus.push(start + index);
            }
            if (this.selectionTrait.has(node)) {
                additionalSelection.push(start + index);
            }
            if (this.anchorTrait.has(node)) {
                anchor = start + index;
            }
        });
        if (additionalFocus.length > 0) {
            super.setFocus(distinct([...super.getFocus(), ...additionalFocus]));
        }
        if (additionalSelection.length > 0) {
            super.setSelection(distinct([...super.getSelection(), ...additionalSelection]));
        }
        if (typeof anchor === 'number') {
            super.setAnchor(anchor);
        }
    }
    setFocus(indexes, browserEvent, fromAPI = false) {
        super.setFocus(indexes, browserEvent);
        if (!fromAPI) {
            this.focusTrait.set(indexes.map(i => this.element(i)), browserEvent);
        }
    }
    setSelection(indexes, browserEvent, fromAPI = false) {
        super.setSelection(indexes, browserEvent);
        if (!fromAPI) {
            this.selectionTrait.set(indexes.map(i => this.element(i)), browserEvent);
        }
    }
    setAnchor(index, fromAPI = false) {
        super.setAnchor(index);
        if (!fromAPI) {
            if (typeof index === 'undefined') {
                this.anchorTrait.set([]);
            }
            else {
                this.anchorTrait.set([this.element(index)]);
            }
        }
    }
}
class AbstractTree {
    constructor(_user, container, delegate, renderers, _options = {}) {
        var _a;
        this._user = _user;
        this._options = _options;
        this.eventBufferer = new EventBufferer();
        this.onDidChangeFindOpenState = Event.None;
        this.disposables = new DisposableStore();
        this._onWillRefilter = new Emitter();
        this.onWillRefilter = this._onWillRefilter.event;
        this._onDidUpdateOptions = new Emitter();
        const treeDelegate = new ComposedTreeDelegate(delegate);
        const onDidChangeCollapseStateRelay = new Relay();
        const onDidChangeActiveNodes = new Relay();
        const activeNodes = this.disposables.add(new EventCollection(onDidChangeActiveNodes.event));
        this.renderers = renderers.map(r => new TreeRenderer(r, () => this.model, onDidChangeCollapseStateRelay.event, activeNodes, _options));
        for (const r of this.renderers) {
            this.disposables.add(r);
        }
        let filter;
        if (_options.keyboardNavigationLabelProvider) {
            filter = new FindFilter(this, _options.keyboardNavigationLabelProvider, _options.filter);
            _options = Object.assign(Object.assign({}, _options), { filter: filter }); // TODO need typescript help here
            this.disposables.add(filter);
        }
        this.focus = new abstractTree_Trait(() => this.view.getFocusedElements()[0], _options.identityProvider);
        this.selection = new abstractTree_Trait(() => this.view.getSelectedElements()[0], _options.identityProvider);
        this.anchor = new abstractTree_Trait(() => this.view.getAnchorElement(), _options.identityProvider);
        this.view = new TreeNodeList(_user, container, treeDelegate, this.renderers, this.focus, this.selection, this.anchor, Object.assign(Object.assign({}, asListOptions(() => this.model, _options)), { tree: this }));
        this.model = this.createModel(_user, this.view, _options);
        onDidChangeCollapseStateRelay.input = this.model.onDidChangeCollapseState;
        const onDidModelSplice = Event.forEach(this.model.onDidSplice, e => {
            this.eventBufferer.bufferEvents(() => {
                this.focus.onDidModelSplice(e);
                this.selection.onDidModelSplice(e);
            });
        }, this.disposables);
        // Make sure the `forEach` always runs
        onDidModelSplice(() => null, null, this.disposables);
        // Active nodes can change when the model changes or when focus or selection change.
        // We debounce it with 0 delay since these events may fire in the same stack and we only
        // want to run this once. It also doesn't matter if it runs on the next tick since it's only
        // a nice to have UI feature.
        onDidChangeActiveNodes.input = Event.chain(Event.any(onDidModelSplice, this.focus.onDidChange, this.selection.onDidChange))
            .debounce(() => null, 0)
            .map(() => {
            const set = new Set();
            for (const node of this.focus.getNodes()) {
                set.add(node);
            }
            for (const node of this.selection.getNodes()) {
                set.add(node);
            }
            return [...set.values()];
        }).event;
        if (_options.keyboardSupport !== false) {
            const onKeyDown = Event.chain(this.view.onKeyDown)
                .filter(e => !isInputElement(e.target))
                .map(e => new StandardKeyboardEvent(e));
            onKeyDown.filter(e => e.keyCode === 15 /* KeyCode.LeftArrow */).on(this.onLeftArrow, this, this.disposables);
            onKeyDown.filter(e => e.keyCode === 17 /* KeyCode.RightArrow */).on(this.onRightArrow, this, this.disposables);
            onKeyDown.filter(e => e.keyCode === 10 /* KeyCode.Space */).on(this.onSpace, this, this.disposables);
        }
        if (((_a = _options.findWidgetEnabled) !== null && _a !== void 0 ? _a : true) && _options.keyboardNavigationLabelProvider && _options.contextViewProvider) {
            this.findController = new FindController(this, this.model, this.view, filter, _options.contextViewProvider);
            this.focusNavigationFilter = node => this.findController.shouldAllowFocus(node);
            this.onDidChangeFindOpenState = this.findController.onDidChangeOpenState;
            this.disposables.add(this.findController);
            this.onDidChangeFindMode = this.findController.onDidChangeMode;
        }
        else {
            this.onDidChangeFindMode = Event.None;
        }
        this.styleElement = createStyleSheet(this.view.getHTMLElement());
        this.getHTMLElement().classList.toggle('always', this._options.renderIndentGuides === RenderIndentGuides.Always);
    }
    get onDidChangeFocus() { return this.eventBufferer.wrapEvent(this.focus.onDidChange); }
    get onDidChangeSelection() { return this.eventBufferer.wrapEvent(this.selection.onDidChange); }
    get onMouseDblClick() { return Event.filter(Event.map(this.view.onMouseDblClick, asTreeMouseEvent), e => e.target !== TreeMouseEventTarget.Filter); }
    get onPointer() { return Event.map(this.view.onPointer, asTreeMouseEvent); }
    get onDidFocus() { return this.view.onDidFocus; }
    get onDidChangeModel() { return Event.signal(this.model.onDidSplice); }
    get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; }
    get findMode() { var _a, _b; return (_b = (_a = this.findController) === null || _a === void 0 ? void 0 : _a.mode) !== null && _b !== void 0 ? _b : TreeFindMode.Highlight; }
    set findMode(findMode) { if (this.findController) {
        this.findController.mode = findMode;
    } }
    get expandOnDoubleClick() { return typeof this._options.expandOnDoubleClick === 'undefined' ? true : this._options.expandOnDoubleClick; }
    get expandOnlyOnTwistieClick() { return typeof this._options.expandOnlyOnTwistieClick === 'undefined' ? true : this._options.expandOnlyOnTwistieClick; }
    get onDidDispose() { return this.view.onDidDispose; }
    updateOptions(optionsUpdate = {}) {
        this._options = Object.assign(Object.assign({}, this._options), optionsUpdate);
        for (const renderer of this.renderers) {
            renderer.updateOptions(optionsUpdate);
        }
        this.view.updateOptions(this._options);
        this._onDidUpdateOptions.fire(this._options);
        this.getHTMLElement().classList.toggle('always', this._options.renderIndentGuides === RenderIndentGuides.Always);
    }
    get options() {
        return this._options;
    }
    // Widget
    getHTMLElement() {
        return this.view.getHTMLElement();
    }
    get scrollTop() {
        return this.view.scrollTop;
    }
    set scrollTop(scrollTop) {
        this.view.scrollTop = scrollTop;
    }
    domFocus() {
        this.view.domFocus();
    }
    layout(height, width) {
        var _a;
        this.view.layout(height, width);
        if (isNumber(width)) {
            (_a = this.findController) === null || _a === void 0 ? void 0 : _a.layout(width);
        }
    }
    style(styles) {
        var _a;
        const suffix = `.${this.view.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.treeIndentGuidesStroke.transparent(0.4)}; }`);
            content.push(`.monaco-list${suffix} .monaco-tl-indent > .indent-guide.active { border-color: ${styles.treeIndentGuidesStroke}; }`);
        }
        this.styleElement.textContent = content.join('\n');
        (_a = this.findController) === null || _a === void 0 ? void 0 : _a.style(styles);
        this.view.style(styles);
    }
    // Tree navigation
    getParentElement(location) {
        const parentRef = this.model.getParentNodeLocation(location);
        const parentNode = this.model.getNode(parentRef);
        return parentNode.element;
    }
    getFirstElementChild(location) {
        return this.model.getFirstElementChild(location);
    }
    // Tree
    getNode(location) {
        return this.model.getNode(location);
    }
    collapse(location, recursive = false) {
        return this.model.setCollapsed(location, true, recursive);
    }
    expand(location, recursive = false) {
        return this.model.setCollapsed(location, false, recursive);
    }
    isCollapsible(location) {
        return this.model.isCollapsible(location);
    }
    setCollapsible(location, collapsible) {
        return this.model.setCollapsible(location, collapsible);
    }
    isCollapsed(location) {
        return this.model.isCollapsed(location);
    }
    refilter() {
        this._onWillRefilter.fire(undefined);
        this.model.refilter();
    }
    setSelection(elements, browserEvent) {
        const nodes = elements.map(e => this.model.getNode(e));
        this.selection.set(nodes, browserEvent);
        const indexes = elements.map(e => this.model.getListIndex(e)).filter(i => i > -1);
        this.view.setSelection(indexes, browserEvent, true);
    }
    getSelection() {
        return this.selection.get();
    }
    setFocus(elements, browserEvent) {
        const nodes = elements.map(e => this.model.getNode(e));
        this.focus.set(nodes, browserEvent);
        const indexes = elements.map(e => this.model.getListIndex(e)).filter(i => i > -1);
        this.view.setFocus(indexes, browserEvent, true);
    }
    getFocus() {
        return this.focus.get();
    }
    reveal(location, relativeTop) {
        this.model.expandTo(location);
        const index = this.model.getListIndex(location);
        if (index === -1) {
            return;
        }
        this.view.reveal(index, relativeTop);
    }
    // List
    onLeftArrow(e) {
        e.preventDefault();
        e.stopPropagation();
        const nodes = this.view.getFocusedElements();
        if (nodes.length === 0) {
            return;
        }
        const node = nodes[0];
        const location = this.model.getNodeLocation(node);
        const didChange = this.model.setCollapsed(location, true);
        if (!didChange) {
            const parentLocation = this.model.getParentNodeLocation(location);
            if (!parentLocation) {
                return;
            }
            const parentListIndex = this.model.getListIndex(parentLocation);
            this.view.reveal(parentListIndex);
            this.view.setFocus([parentListIndex]);
        }
    }
    onRightArrow(e) {
        e.preventDefault();
        e.stopPropagation();
        const nodes = this.view.getFocusedElements();
        if (nodes.length === 0) {
            return;
        }
        const node = nodes[0];
        const location = this.model.getNodeLocation(node);
        const didChange = this.model.setCollapsed(location, false);
        if (!didChange) {
            if (!node.children.some(child => child.visible)) {
                return;
            }
            const [focusedIndex] = this.view.getFocus();
            const firstChildIndex = focusedIndex + 1;
            this.view.reveal(firstChildIndex);
            this.view.setFocus([firstChildIndex]);
        }
    }
    onSpace(e) {
        e.preventDefault();
        e.stopPropagation();
        const nodes = this.view.getFocusedElements();
        if (nodes.length === 0) {
            return;
        }
        const node = nodes[0];
        const location = this.model.getNodeLocation(node);
        const recursive = e.browserEvent.altKey;
        this.model.setCollapsed(location, undefined, recursive);
    }
    dispose() {
        dispose(this.disposables);
        this.view.dispose();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/tree/objectTreeModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class ObjectTreeModel {
    constructor(user, list, options = {}) {
        this.user = user;
        this.rootRef = null;
        this.nodes = new Map();
        this.nodesByIdentity = new Map();
        this.model = new IndexTreeModel(user, list, null, options);
        this.onDidSplice = this.model.onDidSplice;
        this.onDidChangeCollapseState = this.model.onDidChangeCollapseState;
        this.onDidChangeRenderNodeCount = this.model.onDidChangeRenderNodeCount;
        if (options.sorter) {
            this.sorter = {
                compare(a, b) {
                    return options.sorter.compare(a.element, b.element);
                }
            };
        }
        this.identityProvider = options.identityProvider;
    }
    setChildren(element, children = Iterable.empty(), options = {}) {
        const location = this.getElementLocation(element);
        this._setChildren(location, this.preserveCollapseState(children), options);
    }
    _setChildren(location, children = Iterable.empty(), options) {
        const insertedElements = new Set();
        const insertedElementIds = new Set();
        const onDidCreateNode = (node) => {
            var _a;
            if (node.element === null) {
                return;
            }
            const tnode = node;
            insertedElements.add(tnode.element);
            this.nodes.set(tnode.element, tnode);
            if (this.identityProvider) {
                const id = this.identityProvider.getId(tnode.element).toString();
                insertedElementIds.add(id);
                this.nodesByIdentity.set(id, tnode);
            }
            (_a = options.onDidCreateNode) === null || _a === void 0 ? void 0 : _a.call(options, tnode);
        };
        const onDidDeleteNode = (node) => {
            var _a;
            if (node.element === null) {
                return;
            }
            const tnode = node;
            if (!insertedElements.has(tnode.element)) {
                this.nodes.delete(tnode.element);
            }
            if (this.identityProvider) {
                const id = this.identityProvider.getId(tnode.element).toString();
                if (!insertedElementIds.has(id)) {
                    this.nodesByIdentity.delete(id);
                }
            }
            (_a = options.onDidDeleteNode) === null || _a === void 0 ? void 0 : _a.call(options, tnode);
        };
        this.model.splice([...location, 0], Number.MAX_VALUE, children, Object.assign(Object.assign({}, options), { onDidCreateNode, onDidDeleteNode }));
    }
    preserveCollapseState(elements = Iterable.empty()) {
        if (this.sorter) {
            elements = [...elements].sort(this.sorter.compare.bind(this.sorter));
        }
        return Iterable.map(elements, treeElement => {
            let node = this.nodes.get(treeElement.element);
            if (!node && this.identityProvider) {
                const id = this.identityProvider.getId(treeElement.element).toString();
                node = this.nodesByIdentity.get(id);
            }
            if (!node) {
                return Object.assign(Object.assign({}, treeElement), { children: this.preserveCollapseState(treeElement.children) });
            }
            const collapsible = typeof treeElement.collapsible === 'boolean' ? treeElement.collapsible : node.collapsible;
            const collapsed = typeof treeElement.collapsed !== 'undefined' ? treeElement.collapsed : node.collapsed;
            return Object.assign(Object.assign({}, treeElement), { collapsible,
                collapsed, children: this.preserveCollapseState(treeElement.children) });
        });
    }
    rerender(element) {
        const location = this.getElementLocation(element);
        this.model.rerender(location);
    }
    getFirstElementChild(ref = null) {
        const location = this.getElementLocation(ref);
        return this.model.getFirstElementChild(location);
    }
    has(element) {
        return this.nodes.has(element);
    }
    getListIndex(element) {
        const location = this.getElementLocation(element);
        return this.model.getListIndex(location);
    }
    getListRenderCount(element) {
        const location = this.getElementLocation(element);
        return this.model.getListRenderCount(location);
    }
    isCollapsible(element) {
        const location = this.getElementLocation(element);
        return this.model.isCollapsible(location);
    }
    setCollapsible(element, collapsible) {
        const location = this.getElementLocation(element);
        return this.model.setCollapsible(location, collapsible);
    }
    isCollapsed(element) {
        const location = this.getElementLocation(element);
        return this.model.isCollapsed(location);
    }
    setCollapsed(element, collapsed, recursive) {
        const location = this.getElementLocation(element);
        return this.model.setCollapsed(location, collapsed, recursive);
    }
    expandTo(element) {
        const location = this.getElementLocation(element);
        this.model.expandTo(location);
    }
    refilter() {
        this.model.refilter();
    }
    getNode(element = null) {
        if (element === null) {
            return this.model.getNode(this.model.rootRef);
        }
        const node = this.nodes.get(element);
        if (!node) {
            throw new TreeError(this.user, `Tree element not found: ${element}`);
        }
        return node;
    }
    getNodeLocation(node) {
        return node.element;
    }
    getParentNodeLocation(element) {
        if (element === null) {
            throw new TreeError(this.user, `Invalid getParentNodeLocation call`);
        }
        const node = this.nodes.get(element);
        if (!node) {
            throw new TreeError(this.user, `Tree element not found: ${element}`);
        }
        const location = this.model.getNodeLocation(node);
        const parentLocation = this.model.getParentNodeLocation(location);
        const parent = this.model.getNode(parentLocation);
        return parent.element;
    }
    getElementLocation(element) {
        if (element === null) {
            return [];
        }
        const node = this.nodes.get(element);
        if (!node) {
            throw new TreeError(this.user, `Tree element not found: ${element}`);
        }
        return this.model.getNodeLocation(node);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/tree/compressedObjectTreeModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




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
    };
}
// Exported only for test reasons, do not use directly
function compress(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), compress),
        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
    };
}
// Exported only for test reasons, do not use directly
function decompress(element) {
    return _decompress(element, 0);
}
function compressedObjectTreeModel_splice(treeElement, element, children) {
    if (treeElement.element === element) {
        return Object.assign(Object.assign({}, treeElement), { children });
    }
    return Object.assign(Object.assign({}, treeElement), { children: Iterable.map(Iterable.from(treeElement.children), e => compressedObjectTreeModel_splice(e, element, children)) });
}
const wrapIdentityProvider = (base) => ({
    getId(node) {
        return node.elements.map(e => base.getId(e).toString()).join('\0');
    }
});
// Exported only for test reasons, do not use directly
class CompressedObjectTreeModel {
    constructor(user, list, options = {}) {
        this.user = user;
        this.rootRef = null;
        this.nodes = new Map();
        this.model = new ObjectTreeModel(user, list, options);
        this.enabled = typeof options.compressionEnabled === 'undefined' ? true : options.compressionEnabled;
        this.identityProvider = options.identityProvider;
    }
    get onDidSplice() { return this.model.onDidSplice; }
    get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; }
    get onDidChangeRenderNodeCount() { return this.model.onDidChangeRenderNodeCount; }
    setChildren(element, children = Iterable.empty(), options) {
        // Diffs must be deem, since the compression can affect nested elements.
        // @see https://github.com/microsoft/vscode/pull/114237#issuecomment-759425034
        const diffIdentityProvider = options.diffIdentityProvider && wrapIdentityProvider(options.diffIdentityProvider);
        if (element === null) {
            const compressedChildren = Iterable.map(children, this.enabled ? compress : noCompress);
            this._setChildren(null, compressedChildren, { diffIdentityProvider, diffDepth: Infinity });
            return;
        }
        const compressedNode = this.nodes.get(element);
        if (!compressedNode) {
            throw new Error('Unknown compressed tree node');
        }
        const node = this.model.getNode(compressedNode);
        const compressedParentNode = this.model.getParentNodeLocation(compressedNode);
        const parent = this.model.getNode(compressedParentNode);
        const decompressedElement = decompress(node);
        const splicedElement = compressedObjectTreeModel_splice(decompressedElement, element, children);
        const recompressedElement = (this.enabled ? compress : noCompress)(splicedElement);
        const parentChildren = parent.children
            .map(child => child === node ? recompressedElement : child);
        this._setChildren(parent.element, parentChildren, {
            diffIdentityProvider,
            diffDepth: node.depth - parent.depth,
        });
    }
    setCompressionEnabled(enabled) {
        if (enabled === this.enabled) {
            return;
        }
        this.enabled = enabled;
        const root = this.model.getNode();
        const rootChildren = root.children;
        const decompressedRootChildren = Iterable.map(rootChildren, decompress);
        const recompressedRootChildren = Iterable.map(decompressedRootChildren, enabled ? compress : noCompress);
        // it should be safe to always use deep diff mode here if an identity
        // provider is available, since we know the raw nodes are unchanged.
        this._setChildren(null, recompressedRootChildren, {
            diffIdentityProvider: this.identityProvider,
            diffDepth: Infinity,
        });
    }
    _setChildren(node, children, options) {
        const insertedElements = new Set();
        const onDidCreateNode = (node) => {
            for (const element of node.element.elements) {
                insertedElements.add(element);
                this.nodes.set(element, node.element);
            }
        };
        const onDidDeleteNode = (node) => {
            for (const element of node.element.elements) {
                if (!insertedElements.has(element)) {
                    this.nodes.delete(element);
                }
            }
        };
        this.model.setChildren(node, children, Object.assign(Object.assign({}, options), { onDidCreateNode, onDidDeleteNode }));
    }
    has(element) {
        return this.nodes.has(element);
    }
    getListIndex(location) {
        const node = this.getCompressedNode(location);
        return this.model.getListIndex(node);
    }
    getListRenderCount(location) {
        const node = this.getCompressedNode(location);
        return this.model.getListRenderCount(node);
    }
    getNode(location) {
        if (typeof location === 'undefined') {
            return this.model.getNode();
        }
        const node = this.getCompressedNode(location);
        return this.model.getNode(node);
    }
    // TODO: review this
    getNodeLocation(node) {
        const compressedNode = this.model.getNodeLocation(node);
        if (compressedNode === null) {
            return null;
        }
        return compressedNode.elements[compressedNode.elements.length - 1];
    }
    // TODO: review this
    getParentNodeLocation(location) {
        const compressedNode = this.getCompressedNode(location);
        const parentNode = this.model.getParentNodeLocation(compressedNode);
        if (parentNode === null) {
            return null;
        }
        return parentNode.elements[parentNode.elements.length - 1];
    }
    getFirstElementChild(location) {
        const compressedNode = this.getCompressedNode(location);
        return this.model.getFirstElementChild(compressedNode);
    }
    isCollapsible(location) {
        const compressedNode = this.getCompressedNode(location);
        return this.model.isCollapsible(compressedNode);
    }
    setCollapsible(location, collapsible) {
        const compressedNode = this.getCompressedNode(location);
        return this.model.setCollapsible(compressedNode, collapsible);
    }
    isCollapsed(location) {
        const compressedNode = this.getCompressedNode(location);
        return this.model.isCollapsed(compressedNode);
    }
    setCollapsed(location, collapsed, recursive) {
        const compressedNode = this.getCompressedNode(location);
        return this.model.setCollapsed(compressedNode, collapsed, recursive);
    }
    expandTo(location) {
        const compressedNode = this.getCompressedNode(location);
        this.model.expandTo(compressedNode);
    }
    rerender(location) {
        const compressedNode = this.getCompressedNode(location);
        this.model.rerender(compressedNode);
    }
    refilter() {
        this.model.refilter();
    }
    getCompressedNode(element) {
        if (element === null) {
            return null;
        }
        const node = this.nodes.get(element);
        if (!node) {
            throw new TreeError(this.user, `Tree element not found: ${element}`);
        }
        return node;
    }
}
const DefaultElementMapper = elements => elements[elements.length - 1];
class CompressedTreeNodeWrapper {
    constructor(unwrapper, node) {
        this.unwrapper = unwrapper;
        this.node = node;
    }
    get element() { return this.node.element === null ? null : this.unwrapper(this.node.element); }
    get children() { return this.node.children.map(node => new CompressedTreeNodeWrapper(this.unwrapper, node)); }
    get depth() { return this.node.depth; }
    get visibleChildrenCount() { return this.node.visibleChildrenCount; }
    get visibleChildIndex() { return this.node.visibleChildIndex; }
    get collapsible() { return this.node.collapsible; }
    get collapsed() { return this.node.collapsed; }
    get visible() { return this.node.visible; }
    get filterData() { return this.node.filterData; }
}
function mapList(nodeMapper, list) {
    return {
        splice(start, deleteCount, toInsert) {
            list.splice(start, deleteCount, toInsert.map(node => nodeMapper.map(node)));
        },
        updateElementHeight(index, height) {
            list.updateElementHeight(index, height);
        }
    };
}
function mapOptions(compressedNodeUnwrapper, options) {
    return Object.assign(Object.assign({}, options), { identityProvider: options.identityProvider && {
            getId(node) {
                return options.identityProvider.getId(compressedNodeUnwrapper(node));
            }
        }, sorter: options.sorter && {
            compare(node, otherNode) {
                return options.sorter.compare(node.elements[0], otherNode.elements[0]);
            }
        }, filter: options.filter && {
            filter(node, parentVisibility) {
                return options.filter.filter(compressedNodeUnwrapper(node), parentVisibility);
            }
        } });
}
class CompressibleObjectTreeModel {
    constructor(user, list, options = {}) {
        this.rootRef = null;
        this.elementMapper = options.elementMapper || DefaultElementMapper;
        const compressedNodeUnwrapper = node => this.elementMapper(node.elements);
        this.nodeMapper = new WeakMapper(node => new CompressedTreeNodeWrapper(compressedNodeUnwrapper, node));
        this.model = new CompressedObjectTreeModel(user, mapList(this.nodeMapper, list), mapOptions(compressedNodeUnwrapper, options));
    }
    get onDidSplice() {
        return Event.map(this.model.onDidSplice, ({ insertedNodes, deletedNodes }) => ({
            insertedNodes: insertedNodes.map(node => this.nodeMapper.map(node)),
            deletedNodes: deletedNodes.map(node => this.nodeMapper.map(node)),
        }));
    }
    get onDidChangeCollapseState() {
        return Event.map(this.model.onDidChangeCollapseState, ({ node, deep }) => ({
            node: this.nodeMapper.map(node),
            deep
        }));
    }
    get onDidChangeRenderNodeCount() {
        return Event.map(this.model.onDidChangeRenderNodeCount, node => this.nodeMapper.map(node));
    }
    setChildren(element, children = Iterable.empty(), options = {}) {
        this.model.setChildren(element, children, options);
    }
    setCompressionEnabled(enabled) {
        this.model.setCompressionEnabled(enabled);
    }
    has(location) {
        return this.model.has(location);
    }
    getListIndex(location) {
        return this.model.getListIndex(location);
    }
    getListRenderCount(location) {
        return this.model.getListRenderCount(location);
    }
    getNode(location) {
        return this.nodeMapper.map(this.model.getNode(location));
    }
    getNodeLocation(node) {
        return node.element;
    }
    getParentNodeLocation(location) {
        return this.model.getParentNodeLocation(location);
    }
    getFirstElementChild(location) {
        const result = this.model.getFirstElementChild(location);
        if (result === null || typeof result === 'undefined') {
            return result;
        }
        return this.elementMapper(result.elements);
    }
    isCollapsible(location) {
        return this.model.isCollapsible(location);
    }
    setCollapsible(location, collapsed) {
        return this.model.setCollapsible(location, collapsed);
    }
    isCollapsed(location) {
        return this.model.isCollapsed(location);
    }
    setCollapsed(location, collapsed, recursive) {
        return this.model.setCollapsed(location, collapsed, recursive);
    }
    expandTo(location) {
        return this.model.expandTo(location);
    }
    rerender(location) {
        return this.model.rerender(location);
    }
    refilter() {
        return this.model.refilter();
    }
    getCompressedTreeNode(location = null) {
        return this.model.getNode(location);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/tree/objectTree.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var objectTree_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};





class ObjectTree extends AbstractTree {
    constructor(user, container, delegate, renderers, options = {}) {
        super(user, container, delegate, renderers, options);
        this.user = user;
    }
    get onDidChangeCollapseState() { return this.model.onDidChangeCollapseState; }
    setChildren(element, children = Iterable.empty(), options) {
        this.model.setChildren(element, children, options);
    }
    rerender(element) {
        if (element === undefined) {
            this.view.rerender();
            return;
        }
        this.model.rerender(element);
    }
    hasElement(element) {
        return this.model.has(element);
    }
    createModel(user, view, options) {
        return new ObjectTreeModel(user, view, options);
    }
}
class CompressibleRenderer {
    constructor(_compressedTreeNodeProvider, renderer) {
        this._compressedTreeNodeProvider = _compressedTreeNodeProvider;
        this.renderer = renderer;
        this.templateId = renderer.templateId;
        if (renderer.onDidChangeTwistieState) {
            this.onDidChangeTwistieState = renderer.onDidChangeTwistieState;
        }
    }
    get compressedTreeNodeProvider() {
        return this._compressedTreeNodeProvider();
    }
    renderTemplate(container) {
        const data = this.renderer.renderTemplate(container);
        return { compressedTreeNode: undefined, data };
    }
    renderElement(node, index, templateData, height) {
        const compressedTreeNode = this.compressedTreeNodeProvider.getCompressedTreeNode(node.element);
        if (compressedTreeNode.element.elements.length === 1) {
            templateData.compressedTreeNode = undefined;
            this.renderer.renderElement(node, index, templateData.data, height);
        }
        else {
            templateData.compressedTreeNode = compressedTreeNode;
            this.renderer.renderCompressedElements(compressedTreeNode, index, templateData.data, height);
        }
    }
    disposeElement(node, index, templateData, height) {
        var _a, _b, _c, _d;
        if (templateData.compressedTreeNode) {
            (_b = (_a = this.renderer).disposeCompressedElements) === null || _b === void 0 ? void 0 : _b.call(_a, templateData.compressedTreeNode, index, templateData.data, height);
        }
        else {
            (_d = (_c = this.renderer).disposeElement) === null || _d === void 0 ? void 0 : _d.call(_c, node, index, templateData.data, height);
        }
    }
    disposeTemplate(templateData) {
        this.renderer.disposeTemplate(templateData.data);
    }
    renderTwistie(element, twistieElement) {
        if (this.renderer.renderTwistie) {
            return this.renderer.renderTwistie(element, twistieElement);
        }
        return false;
    }
}
objectTree_decorate([
    memoize
], CompressibleRenderer.prototype, "compressedTreeNodeProvider", null);
function asObjectTreeOptions(compressedTreeNodeProvider, options) {
    return options && Object.assign(Object.assign({}, options), { keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
            getKeyboardNavigationLabel(e) {
                let compressedTreeNode;
                try {
                    compressedTreeNode = compressedTreeNodeProvider().getCompressedTreeNode(e);
                }
                catch (_a) {
                    return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
                }
                if (compressedTreeNode.element.elements.length === 1) {
                    return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
                }
                else {
                    return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(compressedTreeNode.element.elements);
                }
            }
        } });
}
class CompressibleObjectTree extends ObjectTree {
    constructor(user, container, delegate, renderers, options = {}) {
        const compressedTreeNodeProvider = () => this;
        const compressibleRenderers = renderers.map(r => new CompressibleRenderer(compressedTreeNodeProvider, r));
        super(user, container, delegate, compressibleRenderers, asObjectTreeOptions(compressedTreeNodeProvider, options));
    }
    setChildren(element, children = Iterable.empty(), options) {
        this.model.setChildren(element, children, options);
    }
    createModel(user, view, options) {
        return new CompressibleObjectTreeModel(user, view, options);
    }
    updateOptions(optionsUpdate = {}) {
        super.updateOptions(optionsUpdate);
        if (typeof optionsUpdate.compressionEnabled !== 'undefined') {
            this.model.setCompressionEnabled(optionsUpdate.compressionEnabled);
        }
    }
    getCompressedTreeNode(element = null) {
        return this.model.getCompressedTreeNode(element);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/tree/asyncDataTree.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var asyncDataTree_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};












function createAsyncDataTreeNode(props) {
    return Object.assign(Object.assign({}, props), { children: [], refreshPromise: undefined, stale: true, slow: false, collapsedByDefault: undefined });
}
function asyncDataTree_isAncestor(ancestor, descendant) {
    if (!descendant.parent) {
        return false;
    }
    else if (descendant.parent === ancestor) {
        return true;
    }
    else {
        return asyncDataTree_isAncestor(ancestor, descendant.parent);
    }
}
function intersects(node, other) {
    return node === other || asyncDataTree_isAncestor(node, other) || asyncDataTree_isAncestor(other, node);
}
class AsyncDataTreeNodeWrapper {
    constructor(node) {
        this.node = node;
    }
    get element() { return this.node.element.element; }
    get children() { return this.node.children.map(node => new AsyncDataTreeNodeWrapper(node)); }
    get depth() { return this.node.depth; }
    get visibleChildrenCount() { return this.node.visibleChildrenCount; }
    get visibleChildIndex() { return this.node.visibleChildIndex; }
    get collapsible() { return this.node.collapsible; }
    get collapsed() { return this.node.collapsed; }
    get visible() { return this.node.visible; }
    get filterData() { return this.node.filterData; }
}
class AsyncDataTreeRenderer {
    constructor(renderer, nodeMapper, onDidChangeTwistieState) {
        this.renderer = renderer;
        this.nodeMapper = nodeMapper;
        this.onDidChangeTwistieState = onDidChangeTwistieState;
        this.renderedNodes = new Map();
        this.templateId = renderer.templateId;
    }
    renderTemplate(container) {
        const templateData = this.renderer.renderTemplate(container);
        return { templateData };
    }
    renderElement(node, index, templateData, height) {
        this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, height);
    }
    renderTwistie(element, twistieElement) {
        if (element.slow) {
            twistieElement.classList.add(...Codicon.treeItemLoading.classNamesArray);
            return true;
        }
        else {
            twistieElement.classList.remove(...Codicon.treeItemLoading.classNamesArray);
            return false;
        }
    }
    disposeElement(node, index, templateData, height) {
        var _a, _b;
        (_b = (_a = this.renderer).disposeElement) === null || _b === void 0 ? void 0 : _b.call(_a, this.nodeMapper.map(node), index, templateData.templateData, height);
    }
    disposeTemplate(templateData) {
        this.renderer.disposeTemplate(templateData.templateData);
    }
    dispose() {
        this.renderedNodes.clear();
    }
}
function asTreeEvent(e) {
    return {
        browserEvent: e.browserEvent,
        elements: e.elements.map(e => e.element)
    };
}
function asyncDataTree_asTreeMouseEvent(e) {
    return {
        browserEvent: e.browserEvent,
        element: e.element && e.element.element,
        target: e.target
    };
}
class AsyncDataTreeElementsDragAndDropData extends ElementsDragAndDropData {
    constructor(data) {
        super(data.elements.map(node => node.element));
        this.data = data;
    }
}
function asAsyncDataTreeDragAndDropData(data) {
    if (data instanceof ElementsDragAndDropData) {
        return new AsyncDataTreeElementsDragAndDropData(data);
    }
    return data;
}
class AsyncDataTreeNodeListDragAndDrop {
    constructor(dnd) {
        this.dnd = dnd;
    }
    getDragURI(node) {
        return this.dnd.getDragURI(node.element);
    }
    getDragLabel(nodes, originalEvent) {
        if (this.dnd.getDragLabel) {
            return this.dnd.getDragLabel(nodes.map(node => node.element), originalEvent);
        }
        return undefined;
    }
    onDragStart(data, originalEvent) {
        var _a, _b;
        (_b = (_a = this.dnd).onDragStart) === null || _b === void 0 ? void 0 : _b.call(_a, asAsyncDataTreeDragAndDropData(data), originalEvent);
    }
    onDragOver(data, targetNode, targetIndex, originalEvent, raw = true) {
        return this.dnd.onDragOver(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
    }
    drop(data, targetNode, targetIndex, originalEvent) {
        this.dnd.drop(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
    }
    onDragEnd(originalEvent) {
        var _a, _b;
        (_b = (_a = this.dnd).onDragEnd) === null || _b === void 0 ? void 0 : _b.call(_a, originalEvent);
    }
}
function asyncDataTree_asObjectTreeOptions(options) {
    return options && Object.assign(Object.assign({}, options), { collapseByDefault: true, identityProvider: options.identityProvider && {
            getId(el) {
                return options.identityProvider.getId(el.element);
            }
        }, dnd: options.dnd && new AsyncDataTreeNodeListDragAndDrop(options.dnd), multipleSelectionController: options.multipleSelectionController && {
            isSelectionSingleChangeEvent(e) {
                return options.multipleSelectionController.isSelectionSingleChangeEvent(Object.assign(Object.assign({}, e), { element: e.element }));
            },
            isSelectionRangeChangeEvent(e) {
                return options.multipleSelectionController.isSelectionRangeChangeEvent(Object.assign(Object.assign({}, e), { element: e.element }));
            }
        }, accessibilityProvider: options.accessibilityProvider && Object.assign(Object.assign({}, options.accessibilityProvider), { getPosInSet: undefined, getSetSize: undefined, getRole: options.accessibilityProvider.getRole ? (el) => {
                return options.accessibilityProvider.getRole(el.element);
            } : () => 'treeitem', isChecked: options.accessibilityProvider.isChecked ? (e) => {
                var _a;
                return !!((_a = options.accessibilityProvider) === null || _a === void 0 ? void 0 : _a.isChecked(e.element));
            } : undefined, getAriaLabel(e) {
                return options.accessibilityProvider.getAriaLabel(e.element);
            },
            getWidgetAriaLabel() {
                return options.accessibilityProvider.getWidgetAriaLabel();
            }, getWidgetRole: options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => 'tree', getAriaLevel: options.accessibilityProvider.getAriaLevel && (node => {
                return options.accessibilityProvider.getAriaLevel(node.element);
            }), getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (node => {
                return options.accessibilityProvider.getActiveDescendantId(node.element);
            }) }), filter: options.filter && {
            filter(e, parentVisibility) {
                return options.filter.filter(e.element, parentVisibility);
            }
        }, keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, options.keyboardNavigationLabelProvider), { getKeyboardNavigationLabel(e) {
                return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e.element);
            } }), sorter: undefined, expandOnlyOnTwistieClick: typeof options.expandOnlyOnTwistieClick === 'undefined' ? undefined : (typeof options.expandOnlyOnTwistieClick !== 'function' ? options.expandOnlyOnTwistieClick : (e => options.expandOnlyOnTwistieClick(e.element))), additionalScrollHeight: options.additionalScrollHeight });
}
function asyncDataTree_dfs(node, fn) {
    fn(node);
    node.children.forEach(child => asyncDataTree_dfs(child, fn));
}
class AsyncDataTree {
    constructor(user, container, delegate, renderers, dataSource, options = {}) {
        this.user = user;
        this.dataSource = dataSource;
        this.nodes = new Map();
        this.subTreeRefreshPromises = new Map();
        this.refreshPromises = new Map();
        this._onDidRender = new Emitter();
        this._onDidChangeNodeSlowState = new Emitter();
        this.nodeMapper = new WeakMapper(node => new AsyncDataTreeNodeWrapper(node));
        this.disposables = new DisposableStore();
        this.identityProvider = options.identityProvider;
        this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === 'undefined' ? false : options.autoExpandSingleChildren;
        this.sorter = options.sorter;
        this.collapseByDefault = options.collapseByDefault;
        this.tree = this.createTree(user, container, delegate, renderers, options);
        this.onDidChangeFindMode = this.tree.onDidChangeFindMode;
        this.root = createAsyncDataTreeNode({
            element: undefined,
            parent: null,
            hasChildren: true
        });
        if (this.identityProvider) {
            this.root = Object.assign(Object.assign({}, this.root), { id: null });
        }
        this.nodes.set(null, this.root);
        this.tree.onDidChangeCollapseState(this._onDidChangeCollapseState, this, this.disposables);
    }
    get onDidChangeFocus() { return Event.map(this.tree.onDidChangeFocus, asTreeEvent); }
    get onDidChangeSelection() { return Event.map(this.tree.onDidChangeSelection, asTreeEvent); }
    get onMouseDblClick() { return Event.map(this.tree.onMouseDblClick, asyncDataTree_asTreeMouseEvent); }
    get onPointer() { return Event.map(this.tree.onPointer, asyncDataTree_asTreeMouseEvent); }
    get onDidFocus() { return this.tree.onDidFocus; }
    get onDidChangeModel() { return this.tree.onDidChangeModel; }
    get onDidChangeCollapseState() { return this.tree.onDidChangeCollapseState; }
    get onDidChangeFindOpenState() { return this.tree.onDidChangeFindOpenState; }
    get onDidDispose() { return this.tree.onDidDispose; }
    createTree(user, container, delegate, renderers, options) {
        const objectTreeDelegate = new ComposedTreeDelegate(delegate);
        const objectTreeRenderers = renderers.map(r => new AsyncDataTreeRenderer(r, this.nodeMapper, this._onDidChangeNodeSlowState.event));
        const objectTreeOptions = asyncDataTree_asObjectTreeOptions(options) || {};
        return new ObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
    }
    updateOptions(options = {}) {
        this.tree.updateOptions(options);
    }
    // Widget
    getHTMLElement() {
        return this.tree.getHTMLElement();
    }
    get scrollTop() {
        return this.tree.scrollTop;
    }
    set scrollTop(scrollTop) {
        this.tree.scrollTop = scrollTop;
    }
    domFocus() {
        this.tree.domFocus();
    }
    layout(height, width) {
        this.tree.layout(height, width);
    }
    style(styles) {
        this.tree.style(styles);
    }
    // Model
    getInput() {
        return this.root.element;
    }
    setInput(input, viewState) {
        return asyncDataTree_awaiter(this, void 0, void 0, function* () {
            this.refreshPromises.forEach(promise => promise.cancel());
            this.refreshPromises.clear();
            this.root.element = input;
            const viewStateContext = viewState && { viewState, focus: [], selection: [] };
            yield this._updateChildren(input, true, false, viewStateContext);
            if (viewStateContext) {
                this.tree.setFocus(viewStateContext.focus);
                this.tree.setSelection(viewStateContext.selection);
            }
            if (viewState && typeof viewState.scrollTop === 'number') {
                this.scrollTop = viewState.scrollTop;
            }
        });
    }
    _updateChildren(element = this.root.element, recursive = true, rerender = false, viewStateContext, options) {
        return asyncDataTree_awaiter(this, void 0, void 0, function* () {
            if (typeof this.root.element === 'undefined') {
                throw new TreeError(this.user, 'Tree input not set');
            }
            if (this.root.refreshPromise) {
                yield this.root.refreshPromise;
                yield Event.toPromise(this._onDidRender.event);
            }
            const node = this.getDataNode(element);
            yield this.refreshAndRenderNode(node, recursive, viewStateContext, options);
            if (rerender) {
                try {
                    this.tree.rerender(node);
                }
                catch (_a) {
                    // missing nodes are fine, this could've resulted from
                    // parallel refresh calls, removing `node` altogether
                }
            }
        });
    }
    // View
    rerender(element) {
        if (element === undefined || element === this.root.element) {
            this.tree.rerender();
            return;
        }
        const node = this.getDataNode(element);
        this.tree.rerender(node);
    }
    // Tree
    getNode(element = this.root.element) {
        const dataNode = this.getDataNode(element);
        const node = this.tree.getNode(dataNode === this.root ? null : dataNode);
        return this.nodeMapper.map(node);
    }
    collapse(element, recursive = false) {
        const node = this.getDataNode(element);
        return this.tree.collapse(node === this.root ? null : node, recursive);
    }
    expand(element, recursive = false) {
        return asyncDataTree_awaiter(this, void 0, void 0, function* () {
            if (typeof this.root.element === 'undefined') {
                throw new TreeError(this.user, 'Tree input not set');
            }
            if (this.root.refreshPromise) {
                yield this.root.refreshPromise;
                yield Event.toPromise(this._onDidRender.event);
            }
            const node = this.getDataNode(element);
            if (this.tree.hasElement(node) && !this.tree.isCollapsible(node)) {
                return false;
            }
            if (node.refreshPromise) {
                yield this.root.refreshPromise;
                yield Event.toPromise(this._onDidRender.event);
            }
            if (node !== this.root && !node.refreshPromise && !this.tree.isCollapsed(node)) {
                return false;
            }
            const result = this.tree.expand(node === this.root ? null : node, recursive);
            if (node.refreshPromise) {
                yield this.root.refreshPromise;
                yield Event.toPromise(this._onDidRender.event);
            }
            return result;
        });
    }
    setSelection(elements, browserEvent) {
        const nodes = elements.map(e => this.getDataNode(e));
        this.tree.setSelection(nodes, browserEvent);
    }
    getSelection() {
        const nodes = this.tree.getSelection();
        return nodes.map(n => n.element);
    }
    setFocus(elements, browserEvent) {
        const nodes = elements.map(e => this.getDataNode(e));
        this.tree.setFocus(nodes, browserEvent);
    }
    getFocus() {
        const nodes = this.tree.getFocus();
        return nodes.map(n => n.element);
    }
    reveal(element, relativeTop) {
        this.tree.reveal(this.getDataNode(element), relativeTop);
    }
    // Tree navigation
    getParentElement(element) {
        const node = this.tree.getParentElement(this.getDataNode(element));
        return (node && node.element);
    }
    getFirstElementChild(element = this.root.element) {
        const dataNode = this.getDataNode(element);
        const node = this.tree.getFirstElementChild(dataNode === this.root ? null : dataNode);
        return (node && node.element);
    }
    // Implementation
    getDataNode(element) {
        const node = this.nodes.get((element === this.root.element ? null : element));
        if (!node) {
            throw new TreeError(this.user, `Data tree node not found: ${element}`);
        }
        return node;
    }
    refreshAndRenderNode(node, recursive, viewStateContext, options) {
        return asyncDataTree_awaiter(this, void 0, void 0, function* () {
            yield this.refreshNode(node, recursive, viewStateContext);
            this.render(node, viewStateContext, options);
        });
    }
    refreshNode(node, recursive, viewStateContext) {
        return asyncDataTree_awaiter(this, void 0, void 0, function* () {
            let result;
            this.subTreeRefreshPromises.forEach((refreshPromise, refreshNode) => {
                if (!result && intersects(refreshNode, node)) {
                    result = refreshPromise.then(() => this.refreshNode(node, recursive, viewStateContext));
                }
            });
            if (result) {
                return result;
            }
            if (node !== this.root) {
                const treeNode = this.tree.getNode(node);
                if (treeNode.collapsed) {
                    node.hasChildren = !!this.dataSource.hasChildren(node.element);
                    node.stale = true;
                    return;
                }
            }
            return this.doRefreshSubTree(node, recursive, viewStateContext);
        });
    }
    doRefreshSubTree(node, recursive, viewStateContext) {
        return asyncDataTree_awaiter(this, void 0, void 0, function* () {
            let done;
            node.refreshPromise = new Promise(c => done = c);
            this.subTreeRefreshPromises.set(node, node.refreshPromise);
            node.refreshPromise.finally(() => {
                node.refreshPromise = undefined;
                this.subTreeRefreshPromises.delete(node);
            });
            try {
                const childrenToRefresh = yield this.doRefreshNode(node, recursive, viewStateContext);
                node.stale = false;
                yield Promises.settled(childrenToRefresh.map(child => this.doRefreshSubTree(child, recursive, viewStateContext)));
            }
            finally {
                done();
            }
        });
    }
    doRefreshNode(node, recursive, viewStateContext) {
        return asyncDataTree_awaiter(this, void 0, void 0, function* () {
            node.hasChildren = !!this.dataSource.hasChildren(node.element);
            let childrenPromise;
            if (!node.hasChildren) {
                childrenPromise = Promise.resolve(Iterable.empty());
            }
            else {
                const children = this.doGetChildren(node);
                if (isIterable(children)) {
                    childrenPromise = Promise.resolve(children);
                }
                else {
                    const slowTimeout = timeout(800);
                    slowTimeout.then(() => {
                        node.slow = true;
                        this._onDidChangeNodeSlowState.fire(node);
                    }, _ => null);
                    childrenPromise = children.finally(() => slowTimeout.cancel());
                }
            }
            try {
                const children = yield childrenPromise;
                return this.setChildren(node, children, recursive, viewStateContext);
            }
            catch (err) {
                if (node !== this.root && this.tree.hasElement(node)) {
                    this.tree.collapse(node);
                }
                if (isCancellationError(err)) {
                    return [];
                }
                throw err;
            }
            finally {
                if (node.slow) {
                    node.slow = false;
                    this._onDidChangeNodeSlowState.fire(node);
                }
            }
        });
    }
    doGetChildren(node) {
        let result = this.refreshPromises.get(node);
        if (result) {
            return result;
        }
        const children = this.dataSource.getChildren(node.element);
        if (isIterable(children)) {
            return this.processChildren(children);
        }
        else {
            result = createCancelablePromise(() => asyncDataTree_awaiter(this, void 0, void 0, function* () { return this.processChildren(yield children); }));
            this.refreshPromises.set(node, result);
            return result.finally(() => { this.refreshPromises.delete(node); });
        }
    }
    _onDidChangeCollapseState({ node, deep }) {
        if (node.element === null) {
            return;
        }
        if (!node.collapsed && node.element.stale) {
            if (deep) {
                this.collapse(node.element.element);
            }
            else {
                this.refreshAndRenderNode(node.element, false)
                    .catch(onUnexpectedError);
            }
        }
    }
    setChildren(node, childrenElementsIterable, recursive, viewStateContext) {
        const childrenElements = [...childrenElementsIterable];
        // perf: if the node was and still is a leaf, avoid all this hassle
        if (node.children.length === 0 && childrenElements.length === 0) {
            return [];
        }
        const nodesToForget = new Map();
        const childrenTreeNodesById = new Map();
        for (const child of node.children) {
            nodesToForget.set(child.element, child);
            if (this.identityProvider) {
                const collapsed = this.tree.isCollapsed(child);
                childrenTreeNodesById.set(child.id, { node: child, collapsed });
            }
        }
        const childrenToRefresh = [];
        const children = childrenElements.map(element => {
            const hasChildren = !!this.dataSource.hasChildren(element);
            if (!this.identityProvider) {
                const asyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, hasChildren });
                if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) {
                    asyncDataTreeNode.collapsedByDefault = false;
                    childrenToRefresh.push(asyncDataTreeNode);
                }
                return asyncDataTreeNode;
            }
            const id = this.identityProvider.getId(element).toString();
            const result = childrenTreeNodesById.get(id);
            if (result) {
                const asyncDataTreeNode = result.node;
                nodesToForget.delete(asyncDataTreeNode.element);
                this.nodes.delete(asyncDataTreeNode.element);
                this.nodes.set(element, asyncDataTreeNode);
                asyncDataTreeNode.element = element;
                asyncDataTreeNode.hasChildren = hasChildren;
                if (recursive) {
                    if (result.collapsed) {
                        asyncDataTreeNode.children.forEach(node => asyncDataTree_dfs(node, node => this.nodes.delete(node.element)));
                        asyncDataTreeNode.children.splice(0, asyncDataTreeNode.children.length);
                        asyncDataTreeNode.stale = true;
                    }
                    else {
                        childrenToRefresh.push(asyncDataTreeNode);
                    }
                }
                else if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) {
                    asyncDataTreeNode.collapsedByDefault = false;
                    childrenToRefresh.push(asyncDataTreeNode);
                }
                return asyncDataTreeNode;
            }
            const childAsyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, id, hasChildren });
            if (viewStateContext && viewStateContext.viewState.focus && viewStateContext.viewState.focus.indexOf(id) > -1) {
                viewStateContext.focus.push(childAsyncDataTreeNode);
            }
            if (viewStateContext && viewStateContext.viewState.selection && viewStateContext.viewState.selection.indexOf(id) > -1) {
                viewStateContext.selection.push(childAsyncDataTreeNode);
            }
            if (viewStateContext && viewStateContext.viewState.expanded && viewStateContext.viewState.expanded.indexOf(id) > -1) {
                childrenToRefresh.push(childAsyncDataTreeNode);
            }
            else if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) {
                childAsyncDataTreeNode.collapsedByDefault = false;
                childrenToRefresh.push(childAsyncDataTreeNode);
            }
            return childAsyncDataTreeNode;
        });
        for (const node of nodesToForget.values()) {
            asyncDataTree_dfs(node, node => this.nodes.delete(node.element));
        }
        for (const child of children) {
            this.nodes.set(child.element, child);
        }
        node.children.splice(0, node.children.length, ...children);
        // TODO@joao this doesn't take filter into account
        if (node !== this.root && this.autoExpandSingleChildren && children.length === 1 && childrenToRefresh.length === 0) {
            children[0].collapsedByDefault = false;
            childrenToRefresh.push(children[0]);
        }
        return childrenToRefresh;
    }
    render(node, viewStateContext, options) {
        const children = node.children.map(node => this.asTreeElement(node, viewStateContext));
        const objectTreeOptions = options && Object.assign(Object.assign({}, options), { diffIdentityProvider: options.diffIdentityProvider && {
                getId(node) {
                    return options.diffIdentityProvider.getId(node.element);
                }
            } });
        this.tree.setChildren(node === this.root ? null : node, children, objectTreeOptions);
        if (node !== this.root) {
            this.tree.setCollapsible(node, node.hasChildren);
        }
        this._onDidRender.fire();
    }
    asTreeElement(node, viewStateContext) {
        if (node.stale) {
            return {
                element: node,
                collapsible: node.hasChildren,
                collapsed: true
            };
        }
        let collapsed;
        if (viewStateContext && viewStateContext.viewState.expanded && node.id && viewStateContext.viewState.expanded.indexOf(node.id) > -1) {
            collapsed = false;
        }
        else {
            collapsed = node.collapsedByDefault;
        }
        node.collapsedByDefault = undefined;
        return {
            element: node,
            children: node.hasChildren ? Iterable.map(node.children, child => this.asTreeElement(child, viewStateContext)) : [],
            collapsible: node.hasChildren,
            collapsed
        };
    }
    processChildren(children) {
        if (this.sorter) {
            children = [...children].sort(this.sorter.compare.bind(this.sorter));
        }
        return children;
    }
    dispose() {
        this.disposables.dispose();
    }
}
class CompressibleAsyncDataTreeNodeWrapper {
    constructor(node) {
        this.node = node;
    }
    get element() {
        return {
            elements: this.node.element.elements.map(e => e.element),
            incompressible: this.node.element.incompressible
        };
    }
    get children() { return this.node.children.map(node => new CompressibleAsyncDataTreeNodeWrapper(node)); }
    get depth() { return this.node.depth; }
    get visibleChildrenCount() { return this.node.visibleChildrenCount; }
    get visibleChildIndex() { return this.node.visibleChildIndex; }
    get collapsible() { return this.node.collapsible; }
    get collapsed() { return this.node.collapsed; }
    get visible() { return this.node.visible; }
    get filterData() { return this.node.filterData; }
}
class CompressibleAsyncDataTreeRenderer {
    constructor(renderer, nodeMapper, compressibleNodeMapperProvider, onDidChangeTwistieState) {
        this.renderer = renderer;
        this.nodeMapper = nodeMapper;
        this.compressibleNodeMapperProvider = compressibleNodeMapperProvider;
        this.onDidChangeTwistieState = onDidChangeTwistieState;
        this.renderedNodes = new Map();
        this.disposables = [];
        this.templateId = renderer.templateId;
    }
    renderTemplate(container) {
        const templateData = this.renderer.renderTemplate(container);
        return { templateData };
    }
    renderElement(node, index, templateData, height) {
        this.renderer.renderElement(this.nodeMapper.map(node), index, templateData.templateData, height);
    }
    renderCompressedElements(node, index, templateData, height) {
        this.renderer.renderCompressedElements(this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, height);
    }
    renderTwistie(element, twistieElement) {
        if (element.slow) {
            twistieElement.classList.add(...Codicon.treeItemLoading.classNamesArray);
            return true;
        }
        else {
            twistieElement.classList.remove(...Codicon.treeItemLoading.classNamesArray);
            return false;
        }
    }
    disposeElement(node, index, templateData, height) {
        var _a, _b;
        (_b = (_a = this.renderer).disposeElement) === null || _b === void 0 ? void 0 : _b.call(_a, this.nodeMapper.map(node), index, templateData.templateData, height);
    }
    disposeCompressedElements(node, index, templateData, height) {
        var _a, _b;
        (_b = (_a = this.renderer).disposeCompressedElements) === null || _b === void 0 ? void 0 : _b.call(_a, this.compressibleNodeMapperProvider().map(node), index, templateData.templateData, height);
    }
    disposeTemplate(templateData) {
        this.renderer.disposeTemplate(templateData.templateData);
    }
    dispose() {
        this.renderedNodes.clear();
        this.disposables = dispose(this.disposables);
    }
}
function asCompressibleObjectTreeOptions(options) {
    const objectTreeOptions = options && asyncDataTree_asObjectTreeOptions(options);
    return objectTreeOptions && Object.assign(Object.assign({}, objectTreeOptions), { keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, objectTreeOptions.keyboardNavigationLabelProvider), { getCompressedNodeKeyboardNavigationLabel(els) {
                return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(els.map(e => e.element));
            } }) });
}
class CompressibleAsyncDataTree extends AsyncDataTree {
    constructor(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options = {}) {
        super(user, container, virtualDelegate, renderers, dataSource, options);
        this.compressionDelegate = compressionDelegate;
        this.compressibleNodeMapper = new WeakMapper(node => new CompressibleAsyncDataTreeNodeWrapper(node));
        this.filter = options.filter;
    }
    createTree(user, container, delegate, renderers, options) {
        const objectTreeDelegate = new ComposedTreeDelegate(delegate);
        const objectTreeRenderers = renderers.map(r => new CompressibleAsyncDataTreeRenderer(r, this.nodeMapper, () => this.compressibleNodeMapper, this._onDidChangeNodeSlowState.event));
        const objectTreeOptions = asCompressibleObjectTreeOptions(options) || {};
        return new CompressibleObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
    }
    asTreeElement(node, viewStateContext) {
        return Object.assign({ incompressible: this.compressionDelegate.isIncompressible(node.element) }, super.asTreeElement(node, viewStateContext));
    }
    updateOptions(options = {}) {
        this.tree.updateOptions(options);
    }
    render(node, viewStateContext) {
        if (!this.identityProvider) {
            return super.render(node, viewStateContext);
        }
        // Preserve traits across compressions. Hacky but does the trick.
        // This is hard to fix properly since it requires rewriting the traits
        // across trees and lists. Let's just keep it this way for now.
        const getId = (element) => this.identityProvider.getId(element).toString();
        const getUncompressedIds = (nodes) => {
            const result = new Set();
            for (const node of nodes) {
                const compressedNode = this.tree.getCompressedTreeNode(node === this.root ? null : node);
                if (!compressedNode.element) {
                    continue;
                }
                for (const node of compressedNode.element.elements) {
                    result.add(getId(node.element));
                }
            }
            return result;
        };
        const oldSelection = getUncompressedIds(this.tree.getSelection());
        const oldFocus = getUncompressedIds(this.tree.getFocus());
        super.render(node, viewStateContext);
        const selection = this.getSelection();
        let didChangeSelection = false;
        const focus = this.getFocus();
        let didChangeFocus = false;
        const visit = (node) => {
            const compressedNode = node.element;
            if (compressedNode) {
                for (let i = 0; i < compressedNode.elements.length; i++) {
                    const id = getId(compressedNode.elements[i].element);
                    const element = compressedNode.elements[compressedNode.elements.length - 1].element;
                    // github.com/microsoft/vscode/issues/85938
                    if (oldSelection.has(id) && selection.indexOf(element) === -1) {
                        selection.push(element);
                        didChangeSelection = true;
                    }
                    if (oldFocus.has(id) && focus.indexOf(element) === -1) {
                        focus.push(element);
                        didChangeFocus = true;
                    }
                }
            }
            node.children.forEach(visit);
        };
        visit(this.tree.getCompressedTreeNode(node === this.root ? 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
    processChildren(children) {
        if (this.filter) {
            children = Iterable.filter(children, e => {
                const result = this.filter.filter(e, 1 /* TreeVisibility.Visible */);
                const visibility = getVisibility(result);
                if (visibility === 2 /* TreeVisibility.Recurse */) {
                    throw new Error('Recursive tree visibility not supported in async data compressed trees');
                }
                return visibility === 1 /* TreeVisibility.Visible */;
            });
        }
        return super.processChildren(children);
    }
}
function getVisibility(filterResult) {
    if (typeof filterResult === 'boolean') {
        return filterResult ? 1 /* TreeVisibility.Visible */ : 0 /* TreeVisibility.Hidden */;
    }
    else if (isFilterResult(filterResult)) {
        return getVisibleState(filterResult.visibility);
    }
    else {
        return getVisibleState(filterResult);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/tree/dataTree.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class DataTree extends AbstractTree {
    constructor(user, container, delegate, renderers, dataSource, options = {}) {
        super(user, container, delegate, renderers, options);
        this.user = user;
        this.dataSource = dataSource;
        this.identityProvider = options.identityProvider;
    }
    createModel(user, view, options) {
        return new ObjectTreeModel(user, view, options);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/contextkey/common/contextkeys.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



const IsMacContext = new RawContextKey('isMac', isMacintosh, localize('isMac', "Whether the operating system is macOS"));
const IsLinuxContext = new RawContextKey('isLinux', isLinux, localize('isLinux', "Whether the operating system is Linux"));
const IsWindowsContext = new RawContextKey('isWindows', isWindows, localize('isWindows', "Whether the operating system is Windows"));
const IsWebContext = new RawContextKey('isWeb', isWeb, localize('isWeb', "Whether the platform is a web browser"));
const IsMacNativeContext = new RawContextKey('isMacNative', isMacintosh && !isWeb, localize('isMacNative', "Whether the operating system is macOS on a non-browser platform"));
const IsIOSContext = new RawContextKey('isIOS', isIOS, localize('isIOS', "Whether the operating system is iOS"));
const IsDevelopmentContext = new RawContextKey('isDevelopment', false, true);
const ProductQualityContext = new RawContextKey('productQualityType', '', localize('productQualityType', "Quality type of VS Code"));
const InputFocusedContextKey = 'inputFocus';
const InputFocusedContext = new RawContextKey(InputFocusedContextKey, false, localize('inputFocus', "Whether keyboard focus is inside an input box"));

;// ../../node_modules/monaco-editor/esm/vs/platform/theme/common/styler.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

function computeStyles(theme, styleMap) {
    const styles = Object.create(null);
    for (const key in styleMap) {
        const value = styleMap[key];
        if (value) {
            styles[key] = resolveColorValue(value, theme);
        }
    }
    return styles;
}
function attachStyler(themeService, styleMap, widgetOrCallback) {
    function applyStyles() {
        const styles = computeStyles(themeService.getColorTheme(), styleMap);
        if (typeof widgetOrCallback === 'function') {
            widgetOrCallback(styles);
        }
        else {
            widgetOrCallback.style(styles);
        }
    }
    applyStyles();
    return themeService.onDidColorThemeChange(applyStyles);
}
function attachBadgeStyler(widget, themeService, style) {
    return attachStyler(themeService, {
        badgeBackground: (style === null || style === void 0 ? void 0 : style.badgeBackground) || badgeBackground,
        badgeForeground: (style === null || style === void 0 ? void 0 : style.badgeForeground) || badgeForeground,
        badgeBorder: contrastBorder
    }, widget);
}
function attachListStyler(widget, themeService, overrides) {
    return attachStyler(themeService, Object.assign(Object.assign({}, defaultListStyles), (overrides || {})), widget);
}
const defaultListStyles = {
    listFocusBackground: listFocusBackground,
    listFocusForeground: listFocusForeground,
    listFocusOutline: listFocusOutline,
    listActiveSelectionBackground: listActiveSelectionBackground,
    listActiveSelectionForeground: listActiveSelectionForeground,
    listActiveSelectionIconForeground: listActiveSelectionIconForeground,
    listFocusAndSelectionOutline: listFocusAndSelectionOutline,
    listFocusAndSelectionBackground: listActiveSelectionBackground,
    listFocusAndSelectionForeground: listActiveSelectionForeground,
    listInactiveSelectionBackground: listInactiveSelectionBackground,
    listInactiveSelectionIconForeground: listInactiveSelectionIconForeground,
    listInactiveSelectionForeground: listInactiveSelectionForeground,
    listInactiveFocusBackground: listInactiveFocusBackground,
    listInactiveFocusOutline: listInactiveFocusOutline,
    listHoverBackground: listHoverBackground,
    listHoverForeground: listHoverForeground,
    listDropBackground: listDropBackground,
    listSelectionOutline: activeContrastBorder,
    listHoverOutline: activeContrastBorder,
    listFilterWidgetBackground: listFilterWidgetBackground,
    listFilterWidgetOutline: listFilterWidgetOutline,
    listFilterWidgetNoMatchesOutline: listFilterWidgetNoMatchesOutline,
    listFilterWidgetShadow: listFilterWidgetShadow,
    treeIndentGuidesStroke: treeIndentGuidesStroke,
    tableColumnsBorder: tableColumnsBorder,
    tableOddRowsBackgroundColor: tableOddRowsBackgroundColor,
    inputActiveOptionBorder: inputActiveOptionBorder,
    inputActiveOptionForeground: inputActiveOptionForeground,
    inputActiveOptionBackground: inputActiveOptionBackground,
    inputBackground: inputBackground,
    inputForeground: inputForeground,
    inputBorder: inputBorder,
    inputValidationInfoBackground: inputValidationInfoBackground,
    inputValidationInfoForeground: inputValidationInfoForeground,
    inputValidationInfoBorder: inputValidationInfoBorder,
    inputValidationWarningBackground: inputValidationWarningBackground,
    inputValidationWarningForeground: inputValidationWarningForeground,
    inputValidationWarningBorder: inputValidationWarningBorder,
    inputValidationErrorBackground: inputValidationErrorBackground,
    inputValidationErrorForeground: inputValidationErrorForeground,
    inputValidationErrorBorder: inputValidationErrorBorder,
};
const defaultMenuStyles = {
    shadowColor: widgetShadow,
    borderColor: menuBorder,
    foregroundColor: menuForeground,
    backgroundColor: menuBackground,
    selectionForegroundColor: menuSelectionForeground,
    selectionBackgroundColor: menuSelectionBackground,
    selectionBorderColor: menuSelectionBorder,
    separatorColor: menuSeparatorBackground,
    scrollbarShadow: scrollbarShadow,
    scrollbarSliderBackground: scrollbarSliderBackground,
    scrollbarSliderHoverBackground: scrollbarSliderHoverBackground,
    scrollbarSliderActiveBackground: scrollbarSliderActiveBackground
};
function attachMenuStyler(widget, themeService, style) {
    return attachStyler(themeService, Object.assign(Object.assign({}, defaultMenuStyles), style), widget);
}

;// ../../node_modules/monaco-editor/esm/vs/platform/list/browser/listService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var listService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var listService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};





















const IListService = createDecorator('listService');
let ListService = class ListService {
    constructor(_themeService) {
        this._themeService = _themeService;
        this.disposables = new DisposableStore();
        this.lists = [];
        this._lastFocusedWidget = undefined;
        this._hasCreatedStyleController = false;
    }
    get lastFocusedList() {
        return this._lastFocusedWidget;
    }
    setLastFocusedList(widget) {
        var _a, _b;
        if (widget === this._lastFocusedWidget) {
            return;
        }
        (_a = this._lastFocusedWidget) === null || _a === void 0 ? void 0 : _a.getHTMLElement().classList.remove('last-focused');
        this._lastFocusedWidget = widget;
        (_b = this._lastFocusedWidget) === null || _b === void 0 ? void 0 : _b.getHTMLElement().classList.add('last-focused');
    }
    register(widget, extraContextKeys) {
        if (!this._hasCreatedStyleController) {
            this._hasCreatedStyleController = true;
            // create a shared default tree style sheet for performance reasons
            const styleController = new DefaultStyleController(createStyleSheet(), '');
            this.disposables.add(attachListStyler(styleController, this._themeService));
        }
        if (this.lists.some(l => l.widget === widget)) {
            throw new Error('Cannot register the same widget multiple times');
        }
        // Keep in our lists list
        const registeredList = { widget, extraContextKeys };
        this.lists.push(registeredList);
        // Check for currently being focused
        if (widget.getHTMLElement() === document.activeElement) {
            this.setLastFocusedList(widget);
        }
        return combinedDisposable(widget.onDidFocus(() => this.setLastFocusedList(widget)), toDisposable(() => this.lists.splice(this.lists.indexOf(registeredList), 1)), widget.onDidDispose(() => {
            this.lists = this.lists.filter(l => l !== registeredList);
            if (this._lastFocusedWidget === widget) {
                this.setLastFocusedList(undefined);
            }
        }));
    }
    dispose() {
        this.disposables.dispose();
    }
};
ListService = listService_decorate([
    listService_param(0, IThemeService)
], ListService);

const RawWorkbenchListFocusContextKey = new RawContextKey('listFocus', true);
const WorkbenchListSupportsMultiSelectContextKey = new RawContextKey('listSupportsMultiselect', true);
const WorkbenchListFocusContextKey = ContextKeyExpr.and(RawWorkbenchListFocusContextKey, ContextKeyExpr.not(InputFocusedContextKey));
const WorkbenchListHasSelectionOrFocus = new RawContextKey('listHasSelectionOrFocus', false);
const WorkbenchListDoubleSelection = new RawContextKey('listDoubleSelection', false);
const WorkbenchListMultiSelection = new RawContextKey('listMultiSelection', false);
const WorkbenchListSelectionNavigation = new RawContextKey('listSelectionNavigation', false);
const WorkbenchListSupportsFind = new RawContextKey('listSupportsFind', true);
const WorkbenchTreeElementCanCollapse = new RawContextKey('treeElementCanCollapse', false);
const WorkbenchTreeElementHasParent = new RawContextKey('treeElementHasParent', false);
const WorkbenchTreeElementCanExpand = new RawContextKey('treeElementCanExpand', false);
const WorkbenchTreeElementHasChild = new RawContextKey('treeElementHasChild', false);
const WorkbenchTreeFindOpen = new RawContextKey('treeFindOpen', false);
const WorkbenchListTypeNavigationModeKey = 'listTypeNavigationMode';
/**
 * @deprecated in favor of WorkbenchListTypeNavigationModeKey
 */
const WorkbenchListAutomaticKeyboardNavigationLegacyKey = 'listAutomaticKeyboardNavigation';
function createScopedContextKeyService(contextKeyService, widget) {
    const result = contextKeyService.createScoped(widget.getHTMLElement());
    RawWorkbenchListFocusContextKey.bindTo(result);
    return result;
}
const multiSelectModifierSettingKey = 'workbench.list.multiSelectModifier';
const openModeSettingKey = 'workbench.list.openMode';
const horizontalScrollingKey = 'workbench.list.horizontalScrolling';
const defaultFindModeSettingKey = 'workbench.list.defaultFindMode';
/** @deprecated in favor of workbench.list.defaultFindMode */
const keyboardNavigationSettingKey = 'workbench.list.keyboardNavigation';
const treeIndentKey = 'workbench.tree.indent';
const treeRenderIndentGuidesKey = 'workbench.tree.renderIndentGuides';
const listSmoothScrolling = 'workbench.list.smoothScrolling';
const mouseWheelScrollSensitivityKey = 'workbench.list.mouseWheelScrollSensitivity';
const fastScrollSensitivityKey = 'workbench.list.fastScrollSensitivity';
const treeExpandMode = 'workbench.tree.expandMode';
function useAltAsMultipleSelectionModifier(configurationService) {
    return configurationService.getValue(multiSelectModifierSettingKey) === 'alt';
}
class MultipleSelectionController extends Disposable {
    constructor(configurationService) {
        super();
        this.configurationService = configurationService;
        this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
        this.registerListeners();
    }
    registerListeners() {
        this._register(this.configurationService.onDidChangeConfiguration(e => {
            if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
                this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(this.configurationService);
            }
        }));
    }
    isSelectionSingleChangeEvent(event) {
        if (this.useAltAsMultipleSelectionModifier) {
            return event.browserEvent.altKey;
        }
        return isSelectionSingleChangeEvent(event);
    }
    isSelectionRangeChangeEvent(event) {
        return isSelectionRangeChangeEvent(event);
    }
}
function toWorkbenchListOptions(accessor, options) {
    var _a;
    const configurationService = accessor.get(IConfigurationService);
    const keybindingService = accessor.get(IKeybindingService);
    const disposables = new DisposableStore();
    const result = Object.assign(Object.assign({}, options), { keyboardNavigationDelegate: { mightProducePrintableCharacter(e) { return keybindingService.mightProducePrintableCharacter(e); } }, smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)), mouseWheelScrollSensitivity: configurationService.getValue(mouseWheelScrollSensitivityKey), fastScrollSensitivity: configurationService.getValue(fastScrollSensitivityKey), multipleSelectionController: (_a = options.multipleSelectionController) !== null && _a !== void 0 ? _a : disposables.add(new MultipleSelectionController(configurationService)), keyboardNavigationEventFilter: createKeyboardNavigationEventFilter(keybindingService) });
    return [result, disposables];
}
let WorkbenchList = class WorkbenchList extends List {
    constructor(user, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, instantiationService) {
        const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
        const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
        super(user, container, delegate, renderers, Object.assign(Object.assign(Object.assign({ keyboardSupport: false }, computeStyles(themeService.getColorTheme(), defaultListStyles)), workbenchListOptions), { horizontalScrolling }));
        this.disposables.add(workbenchListOptionsDisposable);
        this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
        this.themeService = themeService;
        this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
        this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
        const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
        listSelectionNavigation.set(Boolean(options.selectionNavigation));
        this.listHasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
        this.listDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
        this.listMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
        this.horizontalScrolling = options.horizontalScrolling;
        this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
        this.disposables.add(this.contextKeyService);
        this.disposables.add(listService.register(this));
        if (options.overrideStyles) {
            this.updateStyles(options.overrideStyles);
        }
        this.disposables.add(this.onDidChangeSelection(() => {
            const selection = this.getSelection();
            const focus = this.getFocus();
            this.contextKeyService.bufferChangeEvents(() => {
                this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
                this.listMultiSelection.set(selection.length > 1);
                this.listDoubleSelection.set(selection.length === 2);
            });
        }));
        this.disposables.add(this.onDidChangeFocus(() => {
            const selection = this.getSelection();
            const focus = this.getFocus();
            this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
        }));
        this.disposables.add(configurationService.onDidChangeConfiguration(e => {
            if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
                this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
            }
            let options = {};
            if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === undefined) {
                const horizontalScrolling = Boolean(configurationService.getValue(horizontalScrollingKey));
                options = Object.assign(Object.assign({}, options), { horizontalScrolling });
            }
            if (e.affectsConfiguration(listSmoothScrolling)) {
                const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
                options = Object.assign(Object.assign({}, options), { smoothScrolling });
            }
            if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
                const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
                options = Object.assign(Object.assign({}, options), { mouseWheelScrollSensitivity });
            }
            if (e.affectsConfiguration(fastScrollSensitivityKey)) {
                const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
                options = Object.assign(Object.assign({}, options), { fastScrollSensitivity });
            }
            if (Object.keys(options).length > 0) {
                this.updateOptions(options);
            }
        }));
        this.navigator = new ListResourceNavigator(this, Object.assign({ configurationService }, options));
        this.disposables.add(this.navigator);
    }
    updateOptions(options) {
        super.updateOptions(options);
        if (options.overrideStyles) {
            this.updateStyles(options.overrideStyles);
        }
        if (options.multipleSelectionSupport !== undefined) {
            this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
        }
    }
    updateStyles(styles) {
        var _a;
        (_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
        this._styler = attachListStyler(this, this.themeService, styles);
    }
    dispose() {
        var _a;
        (_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
        super.dispose();
    }
};
WorkbenchList = listService_decorate([
    listService_param(5, IContextKeyService),
    listService_param(6, IListService),
    listService_param(7, IThemeService),
    listService_param(8, IConfigurationService),
    listService_param(9, IInstantiationService)
], WorkbenchList);

let WorkbenchPagedList = class WorkbenchPagedList extends PagedList {
    constructor(user, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, instantiationService) {
        const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
        const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
        super(user, container, delegate, renderers, Object.assign(Object.assign(Object.assign({ keyboardSupport: false }, computeStyles(themeService.getColorTheme(), defaultListStyles)), workbenchListOptions), { horizontalScrolling }));
        this.disposables = new DisposableStore();
        this.disposables.add(workbenchListOptionsDisposable);
        this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
        this.themeService = themeService;
        this.horizontalScrolling = options.horizontalScrolling;
        this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
        this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
        const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
        listSelectionNavigation.set(Boolean(options.selectionNavigation));
        this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
        this.disposables.add(this.contextKeyService);
        this.disposables.add(listService.register(this));
        if (options.overrideStyles) {
            this.updateStyles(options.overrideStyles);
        }
        if (options.overrideStyles) {
            this.disposables.add(attachListStyler(this, themeService, options.overrideStyles));
        }
        this.disposables.add(configurationService.onDidChangeConfiguration(e => {
            if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
                this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
            }
            let options = {};
            if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === undefined) {
                const horizontalScrolling = Boolean(configurationService.getValue(horizontalScrollingKey));
                options = Object.assign(Object.assign({}, options), { horizontalScrolling });
            }
            if (e.affectsConfiguration(listSmoothScrolling)) {
                const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
                options = Object.assign(Object.assign({}, options), { smoothScrolling });
            }
            if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
                const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
                options = Object.assign(Object.assign({}, options), { mouseWheelScrollSensitivity });
            }
            if (e.affectsConfiguration(fastScrollSensitivityKey)) {
                const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
                options = Object.assign(Object.assign({}, options), { fastScrollSensitivity });
            }
            if (Object.keys(options).length > 0) {
                this.updateOptions(options);
            }
        }));
        this.navigator = new ListResourceNavigator(this, Object.assign({ configurationService }, options));
        this.disposables.add(this.navigator);
    }
    updateOptions(options) {
        super.updateOptions(options);
        if (options.overrideStyles) {
            this.updateStyles(options.overrideStyles);
        }
        if (options.multipleSelectionSupport !== undefined) {
            this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
        }
    }
    updateStyles(styles) {
        var _a;
        (_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
        this._styler = attachListStyler(this, this.themeService, styles);
    }
    dispose() {
        var _a;
        (_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
        this.disposables.dispose();
        super.dispose();
    }
};
WorkbenchPagedList = listService_decorate([
    listService_param(5, IContextKeyService),
    listService_param(6, IListService),
    listService_param(7, IThemeService),
    listService_param(8, IConfigurationService),
    listService_param(9, IInstantiationService)
], WorkbenchPagedList);

let WorkbenchTable = class WorkbenchTable extends Table {
    constructor(user, container, delegate, columns, renderers, options, contextKeyService, listService, themeService, configurationService, instantiationService) {
        const horizontalScrolling = typeof options.horizontalScrolling !== 'undefined' ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
        const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
        super(user, container, delegate, columns, renderers, Object.assign(Object.assign(Object.assign({ keyboardSupport: false }, computeStyles(themeService.getColorTheme(), defaultListStyles)), workbenchListOptions), { horizontalScrolling }));
        this.disposables.add(workbenchListOptionsDisposable);
        this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
        this.themeService = themeService;
        this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
        this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
        const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
        listSelectionNavigation.set(Boolean(options.selectionNavigation));
        this.listHasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
        this.listDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
        this.listMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
        this.horizontalScrolling = options.horizontalScrolling;
        this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
        this.disposables.add(this.contextKeyService);
        this.disposables.add(listService.register(this));
        if (options.overrideStyles) {
            this.updateStyles(options.overrideStyles);
        }
        this.disposables.add(this.onDidChangeSelection(() => {
            const selection = this.getSelection();
            const focus = this.getFocus();
            this.contextKeyService.bufferChangeEvents(() => {
                this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
                this.listMultiSelection.set(selection.length > 1);
                this.listDoubleSelection.set(selection.length === 2);
            });
        }));
        this.disposables.add(this.onDidChangeFocus(() => {
            const selection = this.getSelection();
            const focus = this.getFocus();
            this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
        }));
        this.disposables.add(configurationService.onDidChangeConfiguration(e => {
            if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
                this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
            }
            let options = {};
            if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === undefined) {
                const horizontalScrolling = Boolean(configurationService.getValue(horizontalScrollingKey));
                options = Object.assign(Object.assign({}, options), { horizontalScrolling });
            }
            if (e.affectsConfiguration(listSmoothScrolling)) {
                const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
                options = Object.assign(Object.assign({}, options), { smoothScrolling });
            }
            if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
                const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
                options = Object.assign(Object.assign({}, options), { mouseWheelScrollSensitivity });
            }
            if (e.affectsConfiguration(fastScrollSensitivityKey)) {
                const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
                options = Object.assign(Object.assign({}, options), { fastScrollSensitivity });
            }
            if (Object.keys(options).length > 0) {
                this.updateOptions(options);
            }
        }));
        this.navigator = new TableResourceNavigator(this, Object.assign({ configurationService }, options));
        this.disposables.add(this.navigator);
    }
    updateOptions(options) {
        super.updateOptions(options);
        if (options.overrideStyles) {
            this.updateStyles(options.overrideStyles);
        }
        if (options.multipleSelectionSupport !== undefined) {
            this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
        }
    }
    updateStyles(styles) {
        var _a;
        (_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
        this._styler = attachListStyler(this, this.themeService, styles);
    }
    dispose() {
        var _a;
        (_a = this._styler) === null || _a === void 0 ? void 0 : _a.dispose();
        this.disposables.dispose();
        super.dispose();
    }
};
WorkbenchTable = listService_decorate([
    listService_param(6, IContextKeyService),
    listService_param(7, IListService),
    listService_param(8, IThemeService),
    listService_param(9, IConfigurationService),
    listService_param(10, IInstantiationService)
], WorkbenchTable);

class ResourceNavigator extends Disposable {
    constructor(widget, options) {
        var _a;
        super();
        this.widget = widget;
        this._onDidOpen = this._register(new Emitter());
        this.onDidOpen = this._onDidOpen.event;
        this._register(Event.filter(this.widget.onDidChangeSelection, e => e.browserEvent instanceof KeyboardEvent)(e => this.onSelectionFromKeyboard(e)));
        this._register(this.widget.onPointer((e) => this.onPointer(e.element, e.browserEvent)));
        this._register(this.widget.onMouseDblClick((e) => this.onMouseDblClick(e.element, e.browserEvent)));
        if (typeof (options === null || options === void 0 ? void 0 : options.openOnSingleClick) !== 'boolean' && (options === null || options === void 0 ? void 0 : options.configurationService)) {
            this.openOnSingleClick = (options === null || options === void 0 ? void 0 : options.configurationService.getValue(openModeSettingKey)) !== 'doubleClick';
            this._register(options === null || options === void 0 ? void 0 : options.configurationService.onDidChangeConfiguration(() => {
                this.openOnSingleClick = (options === null || options === void 0 ? void 0 : options.configurationService.getValue(openModeSettingKey)) !== 'doubleClick';
            }));
        }
        else {
            this.openOnSingleClick = (_a = options === null || options === void 0 ? void 0 : options.openOnSingleClick) !== null && _a !== void 0 ? _a : true;
        }
    }
    onSelectionFromKeyboard(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._open(this.getSelectedElement(), preserveFocus, pinned, sideBySide, event.browserEvent);
    }
    onPointer(element, browserEvent) {
        if (!this.openOnSingleClick) {
            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._open(element, preserveFocus, pinned, sideBySide, browserEvent);
    }
    onMouseDblClick(element, browserEvent) {
        if (!browserEvent) {
            return;
        }
        // copied from AbstractTree
        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._open(element, preserveFocus, pinned, sideBySide, browserEvent);
    }
    _open(element, preserveFocus, pinned, sideBySide, browserEvent) {
        if (!element) {
            return;
        }
        this._onDidOpen.fire({
            editorOptions: {
                preserveFocus,
                pinned,
                revealIfVisible: true
            },
            sideBySide,
            element,
            browserEvent
        });
    }
}
class ListResourceNavigator extends ResourceNavigator {
    constructor(widget, options) {
        super(widget, options);
        this.widget = widget;
    }
    getSelectedElement() {
        return this.widget.getSelectedElements()[0];
    }
}
class TableResourceNavigator extends ResourceNavigator {
    constructor(widget, options) {
        super(widget, options);
    }
    getSelectedElement() {
        return this.widget.getSelectedElements()[0];
    }
}
class TreeResourceNavigator extends ResourceNavigator {
    constructor(widget, options) {
        super(widget, options);
    }
    getSelectedElement() {
        var _a;
        return (_a = this.widget.getSelection()[0]) !== null && _a !== void 0 ? _a : undefined;
    }
}
function createKeyboardNavigationEventFilter(keybindingService) {
    let inChord = false;
    return event => {
        if (event.toKeybinding().isModifierKey()) {
            return false;
        }
        if (inChord) {
            inChord = false;
            return false;
        }
        const result = keybindingService.softDispatch(event, event.target);
        if (result === null || result === void 0 ? void 0 : result.enterChord) {
            inChord = true;
            return false;
        }
        inChord = false;
        return !result;
    };
}
let WorkbenchObjectTree = class WorkbenchObjectTree extends ObjectTree {
    constructor(user, container, delegate, renderers, options, instantiationService, contextKeyService, listService, themeService, configurationService) {
        const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
        super(user, container, delegate, renderers, treeOptions);
        this.disposables.add(disposable);
        this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, themeService, configurationService);
        this.disposables.add(this.internals);
    }
    updateOptions(options) {
        super.updateOptions(options);
        this.internals.updateOptions(options);
    }
};
WorkbenchObjectTree = listService_decorate([
    listService_param(5, IInstantiationService),
    listService_param(6, IContextKeyService),
    listService_param(7, IListService),
    listService_param(8, IThemeService),
    listService_param(9, IConfigurationService)
], WorkbenchObjectTree);

let WorkbenchCompressibleObjectTree = class WorkbenchCompressibleObjectTree extends CompressibleObjectTree {
    constructor(user, container, delegate, renderers, options, instantiationService, contextKeyService, listService, themeService, configurationService) {
        const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
        super(user, container, delegate, renderers, treeOptions);
        this.disposables.add(disposable);
        this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, themeService, configurationService);
        this.disposables.add(this.internals);
    }
    updateOptions(options = {}) {
        super.updateOptions(options);
        if (options.overrideStyles) {
            this.internals.updateStyleOverrides(options.overrideStyles);
        }
        this.internals.updateOptions(options);
    }
};
WorkbenchCompressibleObjectTree = listService_decorate([
    listService_param(5, IInstantiationService),
    listService_param(6, IContextKeyService),
    listService_param(7, IListService),
    listService_param(8, IThemeService),
    listService_param(9, IConfigurationService)
], WorkbenchCompressibleObjectTree);

let WorkbenchDataTree = class WorkbenchDataTree extends DataTree {
    constructor(user, container, delegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, themeService, configurationService) {
        const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
        super(user, container, delegate, renderers, dataSource, treeOptions);
        this.disposables.add(disposable);
        this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, themeService, configurationService);
        this.disposables.add(this.internals);
    }
    updateOptions(options = {}) {
        super.updateOptions(options);
        if (options.overrideStyles) {
            this.internals.updateStyleOverrides(options.overrideStyles);
        }
        this.internals.updateOptions(options);
    }
};
WorkbenchDataTree = listService_decorate([
    listService_param(6, IInstantiationService),
    listService_param(7, IContextKeyService),
    listService_param(8, IListService),
    listService_param(9, IThemeService),
    listService_param(10, IConfigurationService)
], WorkbenchDataTree);

let WorkbenchAsyncDataTree = class WorkbenchAsyncDataTree extends AsyncDataTree {
    constructor(user, container, delegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, themeService, configurationService) {
        const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
        super(user, container, delegate, renderers, dataSource, treeOptions);
        this.disposables.add(disposable);
        this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, themeService, configurationService);
        this.disposables.add(this.internals);
    }
    get onDidOpen() { return this.internals.onDidOpen; }
    updateOptions(options = {}) {
        super.updateOptions(options);
        if (options.overrideStyles) {
            this.internals.updateStyleOverrides(options.overrideStyles);
        }
        this.internals.updateOptions(options);
    }
};
WorkbenchAsyncDataTree = listService_decorate([
    listService_param(6, IInstantiationService),
    listService_param(7, IContextKeyService),
    listService_param(8, IListService),
    listService_param(9, IThemeService),
    listService_param(10, IConfigurationService)
], WorkbenchAsyncDataTree);

let WorkbenchCompressibleAsyncDataTree = class WorkbenchCompressibleAsyncDataTree extends CompressibleAsyncDataTree {
    constructor(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, themeService, configurationService) {
        const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
        super(user, container, virtualDelegate, compressionDelegate, renderers, dataSource, treeOptions);
        this.disposables.add(disposable);
        this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, themeService, configurationService);
        this.disposables.add(this.internals);
    }
    updateOptions(options) {
        super.updateOptions(options);
        this.internals.updateOptions(options);
    }
};
WorkbenchCompressibleAsyncDataTree = listService_decorate([
    listService_param(7, IInstantiationService),
    listService_param(8, IContextKeyService),
    listService_param(9, IListService),
    listService_param(10, IThemeService),
    listService_param(11, IConfigurationService)
], WorkbenchCompressibleAsyncDataTree);

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 undefined;
}
function workbenchTreeDataPreamble(accessor, options) {
    var _a;
    const configurationService = accessor.get(IConfigurationService);
    const contextViewService = accessor.get(IContextViewService);
    const contextKeyService = accessor.get(IContextKeyService);
    const instantiationService = accessor.get(IInstantiationService);
    const getTypeNavigationMode = () => {
        // give priority to the context key value to specify a value
        const modeString = contextKeyService.getContextKeyValue(WorkbenchListTypeNavigationModeKey);
        if (modeString === 'automatic') {
            return TypeNavigationMode.Automatic;
        }
        else if (modeString === 'trigger') {
            return TypeNavigationMode.Trigger;
        }
        // also check the deprecated context key to set the mode to 'trigger'
        const modeBoolean = contextKeyService.getContextKeyValue(WorkbenchListAutomaticKeyboardNavigationLegacyKey);
        if (modeBoolean === false) {
            return TypeNavigationMode.Trigger;
        }
        return undefined;
    };
    const horizontalScrolling = options.horizontalScrolling !== undefined ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
    const [workbenchListOptions, disposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
    const additionalScrollHeight = options.additionalScrollHeight;
    return {
        getTypeNavigationMode,
        disposable,
        options: Object.assign(Object.assign({ 
            // ...options, // TODO@Joao why is this not splatted here?
            keyboardSupport: false }, workbenchListOptions), { indent: typeof configurationService.getValue(treeIndentKey) === 'number' ? configurationService.getValue(treeIndentKey) : undefined, renderIndentGuides: configurationService.getValue(treeRenderIndentGuidesKey), smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)), defaultFindMode: getDefaultTreeFindMode(configurationService), horizontalScrolling,
            additionalScrollHeight, hideTwistiesOfChildlessElements: options.hideTwistiesOfChildlessElements, expandOnlyOnTwistieClick: (_a = options.expandOnlyOnTwistieClick) !== null && _a !== void 0 ? _a : (configurationService.getValue(treeExpandMode) === 'doubleClick'), contextViewProvider: contextViewService })
    };
}
let WorkbenchTreeInternals = class WorkbenchTreeInternals {
    constructor(tree, options, getTypeNavigationMode, overrideStyles, contextKeyService, listService, themeService, configurationService) {
        var _a;
        this.tree = tree;
        this.themeService = themeService;
        this.disposables = [];
        this.contextKeyService = createScopedContextKeyService(contextKeyService, tree);
        this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
        this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
        const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
        listSelectionNavigation.set(Boolean(options.selectionNavigation));
        this.listSupportFindWidget = WorkbenchListSupportsFind.bindTo(this.contextKeyService);
        this.listSupportFindWidget.set((_a = options.findWidgetEnabled) !== null && _a !== void 0 ? _a : true);
        this.hasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
        this.hasDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
        this.hasMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
        this.treeElementCanCollapse = WorkbenchTreeElementCanCollapse.bindTo(this.contextKeyService);
        this.treeElementHasParent = WorkbenchTreeElementHasParent.bindTo(this.contextKeyService);
        this.treeElementCanExpand = WorkbenchTreeElementCanExpand.bindTo(this.contextKeyService);
        this.treeElementHasChild = WorkbenchTreeElementHasChild.bindTo(this.contextKeyService);
        this.treeFindOpen = WorkbenchTreeFindOpen.bindTo(this.contextKeyService);
        this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
        this.updateStyleOverrides(overrideStyles);
        const updateCollapseContextKeys = () => {
            const focus = tree.getFocus()[0];
            if (!focus) {
                return;
            }
            const node = tree.getNode(focus);
            this.treeElementCanCollapse.set(node.collapsible && !node.collapsed);
            this.treeElementHasParent.set(!!tree.getParentElement(focus));
            this.treeElementCanExpand.set(node.collapsible && node.collapsed);
            this.treeElementHasChild.set(!!tree.getFirstElementChild(focus));
        };
        const interestingContextKeys = new Set();
        interestingContextKeys.add(WorkbenchListTypeNavigationModeKey);
        interestingContextKeys.add(WorkbenchListAutomaticKeyboardNavigationLegacyKey);
        this.disposables.push(this.contextKeyService, listService.register(tree), tree.onDidChangeSelection(() => {
            const selection = tree.getSelection();
            const focus = tree.getFocus();
            this.contextKeyService.bufferChangeEvents(() => {
                this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
                this.hasMultiSelection.set(selection.length > 1);
                this.hasDoubleSelection.set(selection.length === 2);
            });
        }), tree.onDidChangeFocus(() => {
            const selection = tree.getSelection();
            const focus = tree.getFocus();
            this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
            updateCollapseContextKeys();
        }), tree.onDidChangeCollapseState(updateCollapseContextKeys), tree.onDidChangeModel(updateCollapseContextKeys), tree.onDidChangeFindOpenState(enabled => this.treeFindOpen.set(enabled)), configurationService.onDidChangeConfiguration(e => {
            let newOptions = {};
            if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
                this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
            }
            if (e.affectsConfiguration(treeIndentKey)) {
                const indent = configurationService.getValue(treeIndentKey);
                newOptions = Object.assign(Object.assign({}, newOptions), { indent });
            }
            if (e.affectsConfiguration(treeRenderIndentGuidesKey)) {
                const renderIndentGuides = configurationService.getValue(treeRenderIndentGuidesKey);
                newOptions = Object.assign(Object.assign({}, newOptions), { renderIndentGuides });
            }
            if (e.affectsConfiguration(listSmoothScrolling)) {
                const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
                newOptions = Object.assign(Object.assign({}, newOptions), { smoothScrolling });
            }
            if (e.affectsConfiguration(defaultFindModeSettingKey) || e.affectsConfiguration(keyboardNavigationSettingKey)) {
                tree.updateOptions({ defaultFindMode: getDefaultTreeFindMode(configurationService) });
            }
            if (e.affectsConfiguration(horizontalScrollingKey) && options.horizontalScrolling === undefined) {
                const horizontalScrolling = Boolean(configurationService.getValue(horizontalScrollingKey));
                newOptions = Object.assign(Object.assign({}, newOptions), { horizontalScrolling });
            }
            if (e.affectsConfiguration(treeExpandMode) && options.expandOnlyOnTwistieClick === undefined) {
                newOptions = Object.assign(Object.assign({}, newOptions), { expandOnlyOnTwistieClick: configurationService.getValue(treeExpandMode) === 'doubleClick' });
            }
            if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
                const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
                newOptions = Object.assign(Object.assign({}, newOptions), { mouseWheelScrollSensitivity });
            }
            if (e.affectsConfiguration(fastScrollSensitivityKey)) {
                const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
                newOptions = Object.assign(Object.assign({}, newOptions), { fastScrollSensitivity });
            }
            if (Object.keys(newOptions).length > 0) {
                tree.updateOptions(newOptions);
            }
        }), this.contextKeyService.onDidChangeContext(e => {
            if (e.affectsSome(interestingContextKeys)) {
                tree.updateOptions({ typeNavigationMode: getTypeNavigationMode() });
            }
        }));
        this.navigator = new TreeResourceNavigator(tree, Object.assign({ configurationService }, options));
        this.disposables.push(this.navigator);
    }
    get onDidOpen() { return this.navigator.onDidOpen; }
    updateOptions(options) {
        if (options.multipleSelectionSupport !== undefined) {
            this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
        }
    }
    updateStyleOverrides(overrideStyles) {
        dispose(this.styler);
        this.styler = overrideStyles ? attachListStyler(this.tree, this.themeService, overrideStyles) : Disposable.None;
    }
    dispose() {
        this.disposables = dispose(this.disposables);
        dispose(this.styler);
        this.styler = undefined;
    }
};
WorkbenchTreeInternals = listService_decorate([
    listService_param(4, IContextKeyService),
    listService_param(5, IListService),
    listService_param(6, IThemeService),
    listService_param(7, IConfigurationService)
], WorkbenchTreeInternals);
const listService_configurationRegistry = Registry.as(configurationRegistry_Extensions.Configuration);
listService_configurationRegistry.registerConfiguration({
    id: 'workbench',
    order: 7,
    title: localize('workbenchConfigurationTitle', "Workbench"),
    type: 'object',
    properties: {
        [multiSelectModifierSettingKey]: {
            type: 'string',
            enum: ['ctrlCmd', 'alt'],
            markdownEnumDescriptions: [
                localize('multiSelectModifier.ctrlCmd', "Maps to `Control` on Windows and Linux and to `Command` on macOS."),
                localize('multiSelectModifier.alt', "Maps to `Alt` on Windows and Linux and to `Option` on macOS.")
            ],
            default: 'ctrlCmd',
            description: localize({
                key: 'multiSelectModifier',
                comment: [
                    '- `ctrlCmd` refers to a value the setting can take and should not be localized.',
                    '- `Control` and `Command` refer to the modifier keys Ctrl or Cmd on the keyboard and can be localized.'
                ]
            }, "The modifier to be used to add an item in trees and lists to a multi-selection with the mouse (for example in the explorer, open editors and scm view). The 'Open to Side' mouse gestures - if supported - will adapt such that they do not conflict with the multiselect modifier.")
        },
        [openModeSettingKey]: {
            type: 'string',
            enum: ['singleClick', 'doubleClick'],
            default: 'singleClick',
            description: localize({
                key: 'openModeModifier',
                comment: ['`singleClick` and `doubleClick` refers to a value the setting can take and should not be localized.']
            }, "Controls how to open items in trees and lists using the mouse (if supported). Note that some trees and lists might choose to ignore this setting if it is not applicable.")
        },
        [horizontalScrollingKey]: {
            type: 'boolean',
            default: false,
            description: localize('horizontalScrolling setting', "Controls whether lists and trees support horizontal scrolling in the workbench. Warning: turning on this setting has a performance implication.")
        },
        [treeIndentKey]: {
            type: 'number',
            default: 8,
            minimum: 4,
            maximum: 40,
            description: localize('tree indent setting', "Controls tree indentation in pixels.")
        },
        [treeRenderIndentGuidesKey]: {
            type: 'string',
            enum: ['none', 'onHover', 'always'],
            default: 'onHover',
            description: localize('render tree indent guides', "Controls whether the tree should render indent guides.")
        },
        [listSmoothScrolling]: {
            type: 'boolean',
            default: false,
            description: localize('list smoothScrolling setting', "Controls whether lists and trees have smooth scrolling."),
        },
        [mouseWheelScrollSensitivityKey]: {
            type: 'number',
            default: 1,
            markdownDescription: localize('Mouse Wheel Scroll Sensitivity', "A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.")
        },
        [fastScrollSensitivityKey]: {
            type: 'number',
            default: 5,
            description: localize('Fast Scroll Sensitivity', "Scrolling speed multiplier when pressing `Alt`.")
        },
        [defaultFindModeSettingKey]: {
            type: 'string',
            enum: ['highlight', 'filter'],
            enumDescriptions: [
                localize('defaultFindModeSettingKey.highlight', "Highlight elements when searching. Further up and down navigation will traverse only the highlighted elements."),
                localize('defaultFindModeSettingKey.filter', "Filter elements when searching.")
            ],
            default: 'highlight',
            description: localize('defaultFindModeSettingKey', "Controls the default find mode for lists and trees in the workbench.")
        },
        [keyboardNavigationSettingKey]: {
            type: 'string',
            enum: ['simple', 'highlight', 'filter'],
            enumDescriptions: [
                localize('keyboardNavigationSettingKey.simple', "Simple keyboard navigation focuses elements which match the keyboard input. Matching is done only on prefixes."),
                localize('keyboardNavigationSettingKey.highlight', "Highlight keyboard navigation highlights elements which match the keyboard input. Further up and down navigation will traverse only the highlighted elements."),
                localize('keyboardNavigationSettingKey.filter', "Filter keyboard navigation will filter out and hide all the elements which do not match the keyboard input.")
            ],
            default: 'highlight',
            description: localize('keyboardNavigationSettingKey', "Controls the keyboard navigation style for lists and trees in the workbench. Can be simple, highlight and filter."),
            deprecated: true,
            deprecationMessage: localize('keyboardNavigationSettingKeyDeprecated', "Please use 'workbench.list.defaultFindMode' instead.")
        },
        [treeExpandMode]: {
            type: 'string',
            enum: ['singleClick', 'doubleClick'],
            default: 'singleClick',
            description: localize('expand mode', "Controls how tree folders are expanded when clicking the folder names. Note that some trees and lists might choose to ignore this setting if it is not applicable."),
        }
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/referencesModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var referencesModel_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};









class OneReference {
    constructor(isProviderFirst, parent, link, _rangeCallback) {
        this.isProviderFirst = isProviderFirst;
        this.parent = parent;
        this.link = link;
        this._rangeCallback = _rangeCallback;
        this.id = defaultGenerator.nextId();
    }
    get uri() {
        return this.link.uri;
    }
    get range() {
        var _a, _b;
        return (_b = (_a = this._range) !== null && _a !== void 0 ? _a : this.link.targetSelectionRange) !== null && _b !== void 0 ? _b : this.link.range;
    }
    set range(value) {
        this._range = value;
        this._rangeCallback(this);
    }
    get ariaMessage() {
        var _a;
        const preview = (_a = this.parent.getPreview(this)) === null || _a === void 0 ? void 0 : _a.preview(this.range);
        if (!preview) {
            return localize('aria.oneReference', "symbol in {0} on line {1} at column {2}", resources_basename(this.uri), this.range.startLineNumber, this.range.startColumn);
        }
        else {
            return localize({ key: 'aria.oneReference.preview', comment: ['Placeholders are: 0: filename, 1:line number, 2: column number, 3: preview snippet of source code'] }, "symbol in {0} on line {1} at column {2}, {3}", resources_basename(this.uri), this.range.startLineNumber, this.range.startColumn, preview.value);
        }
    }
}
class FilePreview {
    constructor(_modelReference) {
        this._modelReference = _modelReference;
    }
    dispose() {
        this._modelReference.dispose();
    }
    preview(range, n = 8) {
        const model = this._modelReference.object.textEditorModel;
        if (!model) {
            return undefined;
        }
        const { startLineNumber, startColumn, endLineNumber, endColumn } = range;
        const word = model.getWordUntilPosition({ lineNumber: startLineNumber, column: startColumn - n });
        const beforeRange = new Range(startLineNumber, word.startColumn, startLineNumber, startColumn);
        const afterRange = new Range(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 }
        };
    }
}
class FileReferences {
    constructor(parent, uri) {
        this.parent = parent;
        this.uri = uri;
        this.children = [];
        this._previews = new ResourceMap();
    }
    dispose() {
        dispose(this._previews.values());
        this._previews.clear();
    }
    getPreview(child) {
        return this._previews.get(child.uri);
    }
    get ariaMessage() {
        const len = this.children.length;
        if (len === 1) {
            return localize('aria.fileReferences.1', "1 symbol in {0}, full path {1}", resources_basename(this.uri), this.uri.fsPath);
        }
        else {
            return localize('aria.fileReferences.N', "{0} symbols in {1}, full path {2}", len, resources_basename(this.uri), this.uri.fsPath);
        }
    }
    resolve(textModelResolverService) {
        return referencesModel_awaiter(this, void 0, void 0, function* () {
            if (this._previews.size !== 0) {
                return this;
            }
            for (const child of this.children) {
                if (this._previews.has(child.uri)) {
                    continue;
                }
                try {
                    const ref = yield textModelResolverService.createModelReference(child.uri);
                    this._previews.set(child.uri, new FilePreview(ref));
                }
                catch (err) {
                    onUnexpectedError(err);
                }
            }
            return this;
        });
    }
}
class ReferencesModel {
    constructor(links, title) {
        this.groups = [];
        this.references = [];
        this._onDidChangeReferenceRange = new Emitter();
        this.onDidChangeReferenceRange = this._onDidChangeReferenceRange.event;
        this._links = links;
        this._title = title;
        // grouping and sorting
        const [providersFirst] = links;
        links.sort(ReferencesModel._compareReferences);
        let current;
        for (const link of links) {
            if (!current || !extUri.isEqual(current.uri, link.uri, true)) {
                // new group
                current = new FileReferences(this, link.uri);
                this.groups.push(current);
            }
            // append, check for equality first!
            if (current.children.length === 0 || ReferencesModel._compareReferences(link, current.children[current.children.length - 1]) !== 0) {
                const oneRef = new OneReference(providersFirst === link, current, link, ref => this._onDidChangeReferenceRange.fire(ref));
                this.references.push(oneRef);
                current.children.push(oneRef);
            }
        }
    }
    dispose() {
        dispose(this.groups);
        this._onDidChangeReferenceRange.dispose();
        this.groups.length = 0;
    }
    clone() {
        return new ReferencesModel(this._links, this._title);
    }
    get title() {
        return this._title;
    }
    get isEmpty() {
        return this.groups.length === 0;
    }
    get ariaMessage() {
        if (this.isEmpty) {
            return localize('aria.result.0', "No results found");
        }
        else if (this.references.length === 1) {
            return localize('aria.result.1', "Found 1 symbol in {0}", this.references[0].uri.fsPath);
        }
        else if (this.groups.length === 1) {
            return localize('aria.result.n1', "Found {0} symbols in {1}", this.references.length, this.groups[0].uri.fsPath);
        }
        else {
            return localize('aria.result.nm', "Found {0} symbols in {1} files", 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) {
            // cycling within one file
            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: strings_commonPrefixLength(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 undefined;
    }
    referenceAt(resource, position) {
        for (const ref of this.references) {
            if (ref.uri.toString() === resource.toString()) {
                if (Range.containsPosition(ref.range, position)) {
                    return ref;
                }
            }
        }
        return undefined;
    }
    firstReference() {
        for (const ref of this.references) {
            if (ref.isProviderFirst) {
                return ref;
            }
        }
        return this.references[0];
    }
    static _compareReferences(a, b) {
        return extUri.compare(a.uri, b.uri) || Range.compareRangesUsingStarts(a.range, b.range);
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget.css
var referencesWidget = __webpack_require__(77863);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget.css

      
      
      
      
      
      
      
      
      

var referencesWidget_options = {};

referencesWidget_options.styleTagTransform = (styleTagTransform_default());
referencesWidget_options.setAttributes = (setAttributesWithoutAttributes_default());

      referencesWidget_options.insert = insertBySelector_default().bind(null, "head");
    
referencesWidget_options.domAPI = (styleDomAPI_default());
referencesWidget_options.insertStyleElement = (insertStyleElement_default());

var referencesWidget_update = injectStylesIntoStyleTag_default()(referencesWidget/* default */.A, referencesWidget_options);




       /* harmony default export */ const peek_referencesWidget = (referencesWidget/* default */.A && referencesWidget/* default */.A.locals ? referencesWidget/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/countBadge/countBadge.css
var countBadge = __webpack_require__(67609);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/countBadge/countBadge.css

      
      
      
      
      
      
      
      
      

var countBadge_options = {};

countBadge_options.styleTagTransform = (styleTagTransform_default());
countBadge_options.setAttributes = (setAttributesWithoutAttributes_default());

      countBadge_options.insert = insertBySelector_default().bind(null, "head");
    
countBadge_options.domAPI = (styleDomAPI_default());
countBadge_options.insertStyleElement = (insertStyleElement_default());

var countBadge_update = injectStylesIntoStyleTag_default()(countBadge/* default */.A, countBadge_options);




       /* harmony default export */ const countBadge_countBadge = (countBadge/* default */.A && countBadge/* default */.A.locals ? countBadge/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/countBadge/countBadge.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





const countBadge_defaultOpts = {
    badgeBackground: Color.fromHex('#4D4D4D'),
    badgeForeground: Color.fromHex('#FFFFFF')
};
class CountBadge {
    constructor(container, options) {
        this.count = 0;
        this.options = options || Object.create(null);
        mixin(this.options, countBadge_defaultOpts, false);
        this.badgeBackground = this.options.badgeBackground;
        this.badgeForeground = this.options.badgeForeground;
        this.badgeBorder = this.options.badgeBorder;
        this.element = append(container, dom_$('.monaco-count-badge'));
        this.countFormat = this.options.countFormat || '{0}';
        this.titleFormat = this.options.titleFormat || '';
        this.setCount(this.options.count || 0);
    }
    setCount(count) {
        this.count = count;
        this.render();
    }
    setTitleFormat(titleFormat) {
        this.titleFormat = titleFormat;
        this.render();
    }
    render() {
        this.element.textContent = format(this.countFormat, this.count);
        this.element.title = format(this.titleFormat, this.count);
        this.applyStyles();
    }
    style(styles) {
        this.badgeBackground = styles.badgeBackground;
        this.badgeForeground = styles.badgeForeground;
        this.badgeBorder = styles.badgeBorder;
        this.applyStyles();
    }
    applyStyles() {
        if (this.element) {
            const background = this.badgeBackground ? this.badgeBackground.toString() : '';
            const foreground = this.badgeForeground ? this.badgeForeground.toString() : '';
            const border = this.badgeBorder ? this.badgeBorder.toString() : '';
            this.element.style.backgroundColor = background;
            this.element.style.color = foreground;
            this.element.style.borderWidth = border ? '1px' : '';
            this.element.style.borderStyle = border ? 'solid' : '';
            this.element.style.borderColor = border;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/highlightedlabel/highlightedLabel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



/**
 * A widget which can render a label with substring highlights, often
 * originating from a filter function like the fuzzy matcher.
 */
class HighlightedLabel {
    /**
     * Create a new {@link HighlightedLabel}.
     *
     * @param container The parent container to append to.
     */
    constructor(container, options) {
        var _a;
        this.text = '';
        this.title = '';
        this.highlights = [];
        this.didEverRender = false;
        this.supportIcons = (_a = options === null || options === void 0 ? void 0 : options.supportIcons) !== null && _a !== void 0 ? _a : false;
        this.domNode = append(container, dom_$('span.monaco-highlighted-label'));
    }
    /**
     * The label's DOM node.
     */
    get element() {
        return this.domNode;
    }
    /**
     * 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(text, highlights = [], title = '', escapeNewLines) {
        if (!text) {
            text = '';
        }
        if (escapeNewLines) {
            // adjusts highlights inplace
            text = HighlightedLabel.escapeNewLines(text, highlights);
        }
        if (this.didEverRender && this.text === text && this.title === title && objects_equals(this.highlights, highlights)) {
            return;
        }
        this.text = text;
        this.title = title;
        this.highlights = highlights;
        this.render();
    }
    render() {
        const children = [];
        let pos = 0;
        for (const highlight of this.highlights) {
            if (highlight.end === highlight.start) {
                continue;
            }
            if (pos < highlight.start) {
                const substring = this.text.substring(pos, highlight.start);
                children.push(dom_$('span', undefined, ...this.supportIcons ? renderLabelWithIcons(substring) : [substring]));
                pos = highlight.end;
            }
            const substring = this.text.substring(highlight.start, highlight.end);
            const element = dom_$('span.highlight', undefined, ...this.supportIcons ? renderLabelWithIcons(substring) : [substring]);
            if (highlight.extraClasses) {
                element.classList.add(...highlight.extraClasses);
            }
            children.push(element);
            pos = highlight.end;
        }
        if (pos < this.text.length) {
            const substring = this.text.substring(pos);
            children.push(dom_$('span', undefined, ...this.supportIcons ? renderLabelWithIcons(substring) : [substring]));
        }
        dom_reset(this.domNode, ...children);
        if (this.title) {
            this.domNode.title = this.title;
        }
        else {
            this.domNode.removeAttribute('title');
        }
        this.didEverRender = true;
    }
    static escapeNewLines(text, highlights) {
        let total = 0;
        let extra = 0;
        return text.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';
        });
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/iconLabel/iconlabel.css
var iconlabel = __webpack_require__(50303);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/iconLabel/iconlabel.css

      
      
      
      
      
      
      
      
      

var iconlabel_options = {};

iconlabel_options.styleTagTransform = (styleTagTransform_default());
iconlabel_options.setAttributes = (setAttributesWithoutAttributes_default());

      iconlabel_options.insert = insertBySelector_default().bind(null, "head");
    
iconlabel_options.domAPI = (styleDomAPI_default());
iconlabel_options.insertStyleElement = (insertStyleElement_default());

var iconlabel_update = injectStylesIntoStyleTag_default()(iconlabel/* default */.A, iconlabel_options);




       /* harmony default export */ const iconLabel_iconlabel = (iconlabel/* default */.A && iconlabel/* default */.A.locals ? iconlabel/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/iconLabel/iconLabel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







class FastLabelNode {
    constructor(_element) {
        this._element = _element;
    }
    get element() {
        return this._element;
    }
    set textContent(content) {
        if (this.disposed || content === this._textContent) {
            return;
        }
        this._textContent = content;
        this._element.textContent = content;
    }
    set className(className) {
        if (this.disposed || className === this._className) {
            return;
        }
        this._className = className;
        this._element.className = className;
    }
    set empty(empty) {
        if (this.disposed || empty === this._empty) {
            return;
        }
        this._empty = empty;
        this._element.style.marginLeft = empty ? '0' : '';
    }
    dispose() {
        this.disposed = true;
    }
}
class IconLabel extends Disposable {
    constructor(container, options) {
        super();
        this.customHovers = new Map();
        this.domNode = this._register(new FastLabelNode(append(container, dom_$('.monaco-icon-label'))));
        this.labelContainer = append(this.domNode.element, dom_$('.monaco-icon-label-container'));
        const nameContainer = append(this.labelContainer, dom_$('span.monaco-icon-name-container'));
        this.descriptionContainer = this._register(new FastLabelNode(append(this.labelContainer, dom_$('span.monaco-icon-description-container'))));
        if ((options === null || options === void 0 ? void 0 : options.supportHighlights) || (options === null || options === void 0 ? void 0 : options.supportIcons)) {
            this.nameNode = new LabelWithHighlights(nameContainer, !!options.supportIcons);
        }
        else {
            this.nameNode = new Label(nameContainer);
        }
        if (options === null || options === void 0 ? void 0 : options.supportDescriptionHighlights) {
            this.descriptionNodeFactory = () => new HighlightedLabel(append(this.descriptionContainer.element, dom_$('span.label-description')), { supportIcons: !!options.supportIcons });
        }
        else {
            this.descriptionNodeFactory = () => this._register(new FastLabelNode(append(this.descriptionContainer.element, dom_$('span.label-description'))));
        }
        this.hoverDelegate = options === null || options === void 0 ? void 0 : options.hoverDelegate;
    }
    get element() {
        return this.domNode.element;
    }
    setLabel(label, description, options) {
        const classes = ['monaco-icon-label'];
        if (options) {
            if (options.extraClasses) {
                classes.push(...options.extraClasses);
            }
            if (options.italic) {
                classes.push('italic');
            }
            if (options.strikethrough) {
                classes.push('strikethrough');
            }
        }
        this.domNode.className = classes.join(' ');
        this.setupHover((options === null || options === void 0 ? void 0 : options.descriptionTitle) ? this.labelContainer : this.element, options === null || options === void 0 ? void 0 : options.title);
        this.nameNode.setLabel(label, options);
        if (description || this.descriptionNode) {
            if (!this.descriptionNode) {
                this.descriptionNode = this.descriptionNodeFactory(); // description node is created lazily on demand
            }
            if (this.descriptionNode instanceof HighlightedLabel) {
                this.descriptionNode.set(description || '', options ? options.descriptionMatches : undefined);
                this.setupHover(this.descriptionNode.element, options === null || options === void 0 ? void 0 : options.descriptionTitle);
            }
            else {
                this.descriptionNode.textContent = description || '';
                this.setupHover(this.descriptionNode.element, (options === null || options === void 0 ? void 0 : options.descriptionTitle) || '');
                this.descriptionNode.empty = !description;
            }
        }
    }
    setupHover(htmlElement, tooltip) {
        const previousCustomHover = this.customHovers.get(htmlElement);
        if (previousCustomHover) {
            previousCustomHover.dispose();
            this.customHovers.delete(htmlElement);
        }
        if (!tooltip) {
            htmlElement.removeAttribute('title');
            return;
        }
        if (!this.hoverDelegate) {
            setupNativeHover(htmlElement, tooltip);
        }
        else {
            const hoverDisposable = setupCustomHover(this.hoverDelegate, htmlElement, tooltip);
            if (hoverDisposable) {
                this.customHovers.set(htmlElement, hoverDisposable);
            }
        }
    }
    dispose() {
        super.dispose();
        for (const disposable of this.customHovers.values()) {
            disposable.dispose();
        }
        this.customHovers.clear();
    }
}
class Label {
    constructor(container) {
        this.container = container;
        this.label = undefined;
        this.singleLabel = undefined;
    }
    setLabel(label, options) {
        if (this.label === label && objects_equals(this.options, options)) {
            return;
        }
        this.label = label;
        this.options = options;
        if (typeof label === 'string') {
            if (!this.singleLabel) {
                this.container.innerText = '';
                this.container.classList.remove('multiple');
                this.singleLabel = append(this.container, dom_$('a.label-name', { id: options === null || options === void 0 ? void 0 : options.domId }));
            }
            this.singleLabel.textContent = label;
        }
        else {
            this.container.innerText = '';
            this.container.classList.add('multiple');
            this.singleLabel = undefined;
            for (let i = 0; i < label.length; i++) {
                const l = label[i];
                const id = (options === null || options === void 0 ? void 0 : options.domId) && `${options === null || options === void 0 ? void 0 : options.domId}_${i}`;
                append(this.container, dom_$('a.label-name', { id, 'data-icon-label-count': label.length, 'data-icon-label-index': i, 'role': 'treeitem' }, l));
                if (i < label.length - 1) {
                    append(this.container, dom_$('span.label-separator', undefined, (options === null || options === void 0 ? void 0 : options.separator) || '/'));
                }
            }
        }
    }
}
function splitMatches(labels, separator, matches) {
    if (!matches) {
        return undefined;
    }
    let labelStart = 0;
    return labels.map(label => {
        const labelRange = { start: labelStart, end: labelStart + label.length };
        const result = matches
            .map(match => range_Range.intersect(labelRange, match))
            .filter(range => !range_Range.isEmpty(range))
            .map(({ start, end }) => ({ start: start - labelStart, end: end - labelStart }));
        labelStart = labelRange.end + separator.length;
        return result;
    });
}
class LabelWithHighlights {
    constructor(container, supportIcons) {
        this.container = container;
        this.supportIcons = supportIcons;
        this.label = undefined;
        this.singleLabel = undefined;
    }
    setLabel(label, options) {
        if (this.label === label && objects_equals(this.options, options)) {
            return;
        }
        this.label = label;
        this.options = options;
        if (typeof label === 'string') {
            if (!this.singleLabel) {
                this.container.innerText = '';
                this.container.classList.remove('multiple');
                this.singleLabel = new HighlightedLabel(append(this.container, dom_$('a.label-name', { id: options === null || options === void 0 ? void 0 : options.domId })), { supportIcons: this.supportIcons });
            }
            this.singleLabel.set(label, options === null || options === void 0 ? void 0 : options.matches, undefined, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines);
        }
        else {
            this.container.innerText = '';
            this.container.classList.add('multiple');
            this.singleLabel = undefined;
            const separator = (options === null || options === void 0 ? void 0 : options.separator) || '/';
            const matches = splitMatches(label, separator, options === null || options === void 0 ? void 0 : options.matches);
            for (let i = 0; i < label.length; i++) {
                const l = label[i];
                const m = matches ? matches[i] : undefined;
                const id = (options === null || options === void 0 ? void 0 : options.domId) && `${options === null || options === void 0 ? void 0 : options.domId}_${i}`;
                const name = dom_$('a.label-name', { id, 'data-icon-label-count': label.length, 'data-icon-label-index': i, 'role': 'treeitem' });
                const highlightedLabel = new HighlightedLabel(append(this.container, name), { supportIcons: this.supportIcons });
                highlightedLabel.set(l, m, undefined, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines);
                if (i < label.length - 1) {
                    append(name, dom_$('span.label-separator', undefined, separator));
                }
            }
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/label/common/label.js

const ILabelService = createDecorator('labelService');

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/peek/referencesTree.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var referencesTree_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var referencesTree_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};















let DataSource = class DataSource {
    constructor(_resolverService) {
        this._resolverService = _resolverService;
    }
    hasChildren(element) {
        if (element instanceof ReferencesModel) {
            return true;
        }
        if (element instanceof FileReferences) {
            return true;
        }
        return false;
    }
    getChildren(element) {
        if (element instanceof ReferencesModel) {
            return element.groups;
        }
        if (element instanceof FileReferences) {
            return element.resolve(this._resolverService).then(val => {
                // if (element.failure) {
                // 	// refresh the element on failure so that
                // 	// we can update its rendering
                // 	return tree.refresh(element).then(() => val.children);
                // }
                return val.children;
            });
        }
        throw new Error('bad tree');
    }
};
DataSource = referencesTree_decorate([
    referencesTree_param(0, ITextModelService)
], DataSource);

//#endregion
class Delegate {
    getHeight() {
        return 23;
    }
    getTemplateId(element) {
        if (element instanceof FileReferences) {
            return FileReferencesRenderer.id;
        }
        else {
            return OneReferenceRenderer.id;
        }
    }
}
let StringRepresentationProvider = class StringRepresentationProvider {
    constructor(_keybindingService) {
        this._keybindingService = _keybindingService;
    }
    getKeyboardNavigationLabel(element) {
        var _a;
        if (element instanceof OneReference) {
            const parts = (_a = element.parent.getPreview(element)) === null || _a === void 0 ? void 0 : _a.preview(element.range);
            if (parts) {
                return parts.value;
            }
        }
        // FileReferences or unresolved OneReference
        return resources_basename(element.uri);
    }
};
StringRepresentationProvider = referencesTree_decorate([
    referencesTree_param(0, IKeybindingService)
], StringRepresentationProvider);

class IdentityProvider {
    getId(element) {
        return element instanceof OneReference ? element.id : element.uri;
    }
}
//#region render: File
let FileReferencesTemplate = class FileReferencesTemplate extends Disposable {
    constructor(container, _labelService, themeService) {
        super();
        this._labelService = _labelService;
        const parent = document.createElement('div');
        parent.classList.add('reference-file');
        this.file = this._register(new IconLabel(parent, { supportHighlights: true }));
        this.badge = new CountBadge(append(parent, dom_$('.count')));
        this._register(attachBadgeStyler(this.badge, themeService));
        container.appendChild(parent);
    }
    set(element, matches) {
        const parent = dirname(element.uri);
        this.file.setLabel(this._labelService.getUriBasenameLabel(element.uri), this._labelService.getUriLabel(parent, { relative: true }), { title: this._labelService.getUriLabel(element.uri), matches });
        const len = element.children.length;
        this.badge.setCount(len);
        if (len > 1) {
            this.badge.setTitleFormat(localize('referencesCount', "{0} references", len));
        }
        else {
            this.badge.setTitleFormat(localize('referenceCount', "{0} reference", len));
        }
    }
};
FileReferencesTemplate = referencesTree_decorate([
    referencesTree_param(1, ILabelService),
    referencesTree_param(2, IThemeService)
], FileReferencesTemplate);
let FileReferencesRenderer = class FileReferencesRenderer {
    constructor(_instantiationService) {
        this._instantiationService = _instantiationService;
        this.templateId = FileReferencesRenderer.id;
    }
    renderTemplate(container) {
        return this._instantiationService.createInstance(FileReferencesTemplate, container);
    }
    renderElement(node, index, template) {
        template.set(node.element, createMatches(node.filterData));
    }
    disposeTemplate(templateData) {
        templateData.dispose();
    }
};
FileReferencesRenderer.id = 'FileReferencesRenderer';
FileReferencesRenderer = referencesTree_decorate([
    referencesTree_param(0, IInstantiationService)
], FileReferencesRenderer);

//#endregion
//#region render: Reference
class OneReferenceTemplate {
    constructor(container) {
        this.label = new HighlightedLabel(container);
    }
    set(element, score) {
        var _a;
        const preview = (_a = element.parent.getPreview(element)) === null || _a === void 0 ? void 0 : _a.preview(element.range);
        if (!preview || !preview.value) {
            // this means we FAILED to resolve the document or the value is the empty string
            this.label.set(`${resources_basename(element.uri)}:${element.range.startLineNumber + 1}:${element.range.startColumn + 1}`);
        }
        else {
            // render search match as highlight unless
            // we have score, then render the score
            const { value, highlight } = preview;
            if (score && !FuzzyScore.isDefault(score)) {
                this.label.element.classList.toggle('referenceMatch', false);
                this.label.set(value, createMatches(score));
            }
            else {
                this.label.element.classList.toggle('referenceMatch', true);
                this.label.set(value, [highlight]);
            }
        }
    }
}
class OneReferenceRenderer {
    constructor() {
        this.templateId = OneReferenceRenderer.id;
    }
    renderTemplate(container) {
        return new OneReferenceTemplate(container);
    }
    renderElement(node, index, templateData) {
        templateData.set(node.element, node.filterData);
    }
    disposeTemplate() {
    }
}
OneReferenceRenderer.id = 'OneReferenceRenderer';
//#endregion
class AccessibilityProvider {
    getWidgetAriaLabel() {
        return localize('treeAriaLabel', "References");
    }
    getAriaLabel(element) {
        return element.ariaMessage;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var referencesWidget_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var referencesWidget_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var referencesWidget_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};

























class DecorationsManager {
    constructor(_editor, _model) {
        this._editor = _editor;
        this._model = _model;
        this._decorations = new Map();
        this._decorationIgnoreSet = new Set();
        this._callOnDispose = new DisposableStore();
        this._callOnModelChange = new DisposableStore();
        this._callOnDispose.add(this._editor.onDidChangeModel(() => this._onModelChanged()));
        this._onModelChanged();
    }
    dispose() {
        this._callOnModelChange.dispose();
        this._callOnDispose.dispose();
        this.removeDecorations();
    }
    _onModelChanged() {
        this._callOnModelChange.clear();
        const model = this._editor.getModel();
        if (!model) {
            return;
        }
        for (const ref of this._model.references) {
            if (ref.uri.toString() === model.uri.toString()) {
                this._addDecorations(ref.parent);
                return;
            }
        }
    }
    _addDecorations(reference) {
        if (!this._editor.hasModel()) {
            return;
        }
        this._callOnModelChange.add(this._editor.getModel().onDidChangeDecorations(() => this._onDecorationChanged()));
        const newDecorations = [];
        const newDecorationsActualIndex = [];
        for (let i = 0, len = reference.children.length; i < len; i++) {
            const oneReference = reference.children[i];
            if (this._decorationIgnoreSet.has(oneReference.id)) {
                continue;
            }
            if (oneReference.uri.toString() !== this._editor.getModel().uri.toString()) {
                continue;
            }
            newDecorations.push({
                range: oneReference.range,
                options: DecorationsManager.DecorationOptions
            });
            newDecorationsActualIndex.push(i);
        }
        this._editor.changeDecorations((changeAccessor) => {
            const decorations = changeAccessor.deltaDecorations([], newDecorations);
            for (let i = 0; i < decorations.length; i++) {
                this._decorations.set(decorations[i], reference.children[newDecorationsActualIndex[i]]);
            }
        });
    }
    _onDecorationChanged() {
        const toRemove = [];
        const model = this._editor.getModel();
        if (!model) {
            return;
        }
        for (const [decorationId, reference] of this._decorations) {
            const newRange = model.getDecorationRange(decorationId);
            if (!newRange) {
                continue;
            }
            let ignore = false;
            if (Range.equalsRange(newRange, reference.range)) {
                continue;
            }
            if (Range.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._decorationIgnoreSet.add(reference.id);
                toRemove.push(decorationId);
            }
            else {
                reference.range = newRange;
            }
        }
        for (let i = 0, len = toRemove.length; i < len; i++) {
            this._decorations.delete(toRemove[i]);
        }
        this._editor.removeDecorations(toRemove);
    }
    removeDecorations() {
        this._editor.removeDecorations([...this._decorations.keys()]);
        this._decorations.clear();
    }
}
DecorationsManager.DecorationOptions = ModelDecorationOptions.register({
    description: 'reference-decoration',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    className: 'reference-decoration'
});
class LayoutData {
    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 (_a) {
            //
        }
        return {
            ratio: ratio || 0.7,
            heightInLines: heightInLines || 18
        };
    }
}
class ReferencesTree extends WorkbenchAsyncDataTree {
}
/**
 * ZoneWidget that is shown inside the editor
 */
let ReferenceWidget = class ReferenceWidget extends PeekViewWidget {
    constructor(editor, _defaultTreeKeyboardSupport, layoutData, themeService, _textModelResolverService, _instantiationService, _peekViewService, _uriLabel, _undoRedoService, _keybindingService, _languageService, _languageConfigurationService) {
        super(editor, { showFrame: false, showArrow: true, isResizeable: true, isAccessible: true, supportOnTitleClick: true }, _instantiationService);
        this._defaultTreeKeyboardSupport = _defaultTreeKeyboardSupport;
        this.layoutData = layoutData;
        this._textModelResolverService = _textModelResolverService;
        this._instantiationService = _instantiationService;
        this._peekViewService = _peekViewService;
        this._uriLabel = _uriLabel;
        this._undoRedoService = _undoRedoService;
        this._keybindingService = _keybindingService;
        this._languageService = _languageService;
        this._languageConfigurationService = _languageConfigurationService;
        this._disposeOnNewModel = new DisposableStore();
        this._callOnDispose = new DisposableStore();
        this._onDidSelectReference = new Emitter();
        this.onDidSelectReference = this._onDidSelectReference.event;
        this._dim = new Dimension(0, 0);
        this._applyTheme(themeService.getColorTheme());
        this._callOnDispose.add(themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
        this._peekViewService.addExclusiveWidget(editor, this);
        this.create();
    }
    dispose() {
        this.setModel(undefined);
        this._callOnDispose.dispose();
        this._disposeOnNewModel.dispose();
        dispose(this._preview);
        dispose(this._previewNotAvailableMessage);
        dispose(this._tree);
        dispose(this._previewModelReference);
        this._splitView.dispose();
        super.dispose();
    }
    _applyTheme(theme) {
        const borderColor = theme.getColor(peekViewBorder) || Color.transparent;
        this.style({
            arrowColor: borderColor,
            frameColor: borderColor,
            headerBackgroundColor: theme.getColor(peekViewTitleBackground) || Color.transparent,
            primaryHeadingColor: theme.getColor(peekViewTitleForeground),
            secondaryHeadingColor: theme.getColor(peekViewTitleInfoForeground)
        });
    }
    show(where) {
        super.show(where, this.layoutData.heightInLines || 18);
    }
    focusOnReferenceTree() {
        this._tree.domFocus();
    }
    focusOnPreviewEditor() {
        this._preview.focus();
    }
    isPreviewEditorFocused() {
        return this._preview.hasTextFocus();
    }
    _onTitleClick(e) {
        if (this._preview && this._preview.getModel()) {
            this._onDidSelectReference.fire({
                element: this._getFocusedReference(),
                kind: e.ctrlKey || e.metaKey || e.altKey ? 'side' : 'open',
                source: 'title'
            });
        }
    }
    _fillBody(containerElement) {
        this.setCssClass('reference-zone-widget');
        // message pane
        this._messageContainer = append(containerElement, dom_$('div.messages'));
        hide(this._messageContainer);
        this._splitView = new SplitView(containerElement, { orientation: 1 /* Orientation.HORIZONTAL */ });
        // editor
        this._previewContainer = append(containerElement, dom_$('div.preview.inline'));
        const options = {
            scrollBeyondLastLine: false,
            scrollbar: {
                verticalScrollbarSize: 14,
                horizontal: 'auto',
                useShadows: true,
                verticalHasArrows: false,
                horizontalHasArrows: false,
                alwaysConsumeMouseWheel: false
            },
            overviewRulerLanes: 2,
            fixedOverflowWidgets: true,
            minimap: {
                enabled: false
            }
        };
        this._preview = this._instantiationService.createInstance(EmbeddedCodeEditorWidget, this._previewContainer, options, this.editor);
        hide(this._previewContainer);
        this._previewNotAvailableMessage = new TextModel(localize('missingPreviewMessage', "no preview available"), PLAINTEXT_LANGUAGE_ID, TextModel.DEFAULT_CREATION_OPTIONS, null, this._undoRedoService, this._languageService, this._languageConfigurationService);
        // tree
        this._treeContainer = append(containerElement, dom_$('div.ref-tree.inline'));
        const treeOptions = {
            keyboardSupport: this._defaultTreeKeyboardSupport,
            accessibilityProvider: new AccessibilityProvider(),
            keyboardNavigationLabelProvider: this._instantiationService.createInstance(StringRepresentationProvider),
            identityProvider: new IdentityProvider(),
            openOnSingleClick: true,
            selectionNavigation: true,
            overrideStyles: {
                listBackground: peekViewResultsBackground
            }
        };
        if (this._defaultTreeKeyboardSupport) {
            // the tree will consume `Escape` and prevent the widget from closing
            this._callOnDispose.add(addStandardDisposableListener(this._treeContainer, 'keydown', (e) => {
                if (e.equals(9 /* KeyCode.Escape */)) {
                    this._keybindingService.dispatchEvent(e, e.target);
                    e.stopPropagation();
                }
            }, true));
        }
        this._tree = this._instantiationService.createInstance(ReferencesTree, 'ReferencesWidget', this._treeContainer, new Delegate(), [
            this._instantiationService.createInstance(FileReferencesRenderer),
            this._instantiationService.createInstance(OneReferenceRenderer),
        ], this._instantiationService.createInstance(DataSource), treeOptions);
        // split stuff
        this._splitView.addView({
            onDidChange: Event.None,
            element: this._previewContainer,
            minimumSize: 200,
            maximumSize: Number.MAX_VALUE,
            layout: (width) => {
                this._preview.layout({ height: this._dim.height, width });
            }
        }, Sizing.Distribute);
        this._splitView.addView({
            onDidChange: Event.None,
            element: this._treeContainer,
            minimumSize: 100,
            maximumSize: Number.MAX_VALUE,
            layout: (width) => {
                this._treeContainer.style.height = `${this._dim.height}px`;
                this._treeContainer.style.width = `${width}px`;
                this._tree.layout(this._dim.height, width);
            }
        }, Sizing.Distribute);
        this._disposables.add(this._splitView.onDidSashChange(() => {
            if (this._dim.width) {
                this.layoutData.ratio = this._splitView.getViewSize(0) / this._dim.width;
            }
        }, undefined));
        // listen on selection and focus
        const onEvent = (element, kind) => {
            if (element instanceof OneReference) {
                if (kind === 'show') {
                    this._revealReference(element, false);
                }
                this._onDidSelectReference.fire({ element, kind, source: 'tree' });
            }
        };
        this._tree.onDidOpen(e => {
            if (e.sideBySide) {
                onEvent(e.element, 'side');
            }
            else if (e.editorOptions.pinned) {
                onEvent(e.element, 'goto');
            }
            else {
                onEvent(e.element, 'show');
            }
        });
        hide(this._treeContainer);
    }
    _onWidth(width) {
        if (this._dim) {
            this._doLayoutBody(this._dim.height, width);
        }
    }
    _doLayoutBody(heightInPixel, widthInPixel) {
        super._doLayoutBody(heightInPixel, widthInPixel);
        this._dim = new Dimension(widthInPixel, heightInPixel);
        this.layoutData.heightInLines = this._viewZone ? this._viewZone.heightInLines : this.layoutData.heightInLines;
        this._splitView.layout(widthInPixel);
        this._splitView.resizeView(0, widthInPixel * this.layoutData.ratio);
    }
    setSelection(selection) {
        return this._revealReference(selection, true).then(() => {
            if (!this._model) {
                // disposed
                return;
            }
            // show in tree
            this._tree.setSelection([selection]);
            this._tree.setFocus([selection]);
        });
    }
    setModel(newModel) {
        // clean up
        this._disposeOnNewModel.clear();
        this._model = newModel;
        if (this._model) {
            return this._onNewModel();
        }
        return Promise.resolve();
    }
    _onNewModel() {
        if (!this._model) {
            return Promise.resolve(undefined);
        }
        if (this._model.isEmpty) {
            this.setTitle('');
            this._messageContainer.innerText = localize('noResults', "No results");
            show(this._messageContainer);
            return Promise.resolve(undefined);
        }
        hide(this._messageContainer);
        this._decorationsManager = new DecorationsManager(this._preview, this._model);
        this._disposeOnNewModel.add(this._decorationsManager);
        // listen on model changes
        this._disposeOnNewModel.add(this._model.onDidChangeReferenceRange(reference => this._tree.rerender(reference)));
        // listen on editor
        this._disposeOnNewModel.add(this._preview.onMouseDown(e => {
            const { event, target } = e;
            if (event.detail !== 2) {
                return;
            }
            const element = this._getFocusedReference();
            if (!element) {
                return;
            }
            this._onDidSelectReference.fire({
                element: { uri: element.uri, range: target.range },
                kind: (event.ctrlKey || event.metaKey || event.altKey) ? 'side' : 'open',
                source: 'editor'
            });
        }));
        // make sure things are rendered
        this.container.classList.add('results-loaded');
        show(this._treeContainer);
        show(this._previewContainer);
        this._splitView.layout(this._dim.width);
        this.focusOnReferenceTree();
        // pick input and a reference to begin with
        return this._tree.setInput(this._model.groups.length === 1 ? this._model.groups[0] : this._model);
    }
    _getFocusedReference() {
        const [element] = this._tree.getFocus();
        if (element instanceof OneReference) {
            return element;
        }
        else if (element instanceof FileReferences) {
            if (element.children.length > 0) {
                return element.children[0];
            }
        }
        return undefined;
    }
    revealReference(reference) {
        return referencesWidget_awaiter(this, void 0, void 0, function* () {
            yield this._revealReference(reference, false);
            this._onDidSelectReference.fire({ element: reference, kind: 'goto', source: 'tree' });
        });
    }
    _revealReference(reference, revealParent) {
        return referencesWidget_awaiter(this, void 0, void 0, function* () {
            // check if there is anything to do...
            if (this._revealedReference === reference) {
                return;
            }
            this._revealedReference = reference;
            // Update widget header
            if (reference.uri.scheme !== Schemas.inMemory) {
                this.setTitle(basenameOrAuthority(reference.uri), this._uriLabel.getUriLabel(dirname(reference.uri)));
            }
            else {
                this.setTitle(localize('peekView.alternateTitle', "References"));
            }
            const promise = this._textModelResolverService.createModelReference(reference.uri);
            if (this._tree.getInput() === reference.parent) {
                this._tree.reveal(reference);
            }
            else {
                if (revealParent) {
                    this._tree.reveal(reference.parent);
                }
                yield this._tree.expand(reference.parent);
                this._tree.reveal(reference);
            }
            const ref = yield promise;
            if (!this._model) {
                // disposed
                ref.dispose();
                return;
            }
            dispose(this._previewModelReference);
            // show in editor
            const model = ref.object;
            if (model) {
                const scrollType = this._preview.getModel() === model.textEditorModel ? 0 /* ScrollType.Smooth */ : 1 /* ScrollType.Immediate */;
                const sel = Range.lift(reference.range).collapseToStart();
                this._previewModelReference = ref;
                this._preview.setModel(model.textEditorModel);
                this._preview.setSelection(sel);
                this._preview.revealRangeInCenter(sel, scrollType);
            }
            else {
                this._preview.setModel(this._previewNotAvailableMessage);
                ref.dispose();
            }
        });
    }
};
ReferenceWidget = referencesWidget_decorate([
    referencesWidget_param(3, IThemeService),
    referencesWidget_param(4, ITextModelService),
    referencesWidget_param(5, IInstantiationService),
    referencesWidget_param(6, IPeekViewService),
    referencesWidget_param(7, ILabelService),
    referencesWidget_param(8, IUndoRedoService),
    referencesWidget_param(9, IKeybindingService),
    referencesWidget_param(10, ILanguageService),
    referencesWidget_param(11, ILanguageConfigurationService)
], ReferenceWidget);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/peek/referencesController.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var referencesController_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var referencesController_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var referencesController_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};



















const ctxReferenceSearchVisible = new RawContextKey('referenceSearchVisible', false, localize('referenceSearchVisible', "Whether reference peek is visible, like 'Peek References' or 'Peek Definition'"));
let ReferencesController = class ReferencesController {
    constructor(_defaultTreeKeyboardSupport, _editor, contextKeyService, _editorService, _notificationService, _instantiationService, _storageService, _configurationService) {
        this._defaultTreeKeyboardSupport = _defaultTreeKeyboardSupport;
        this._editor = _editor;
        this._editorService = _editorService;
        this._notificationService = _notificationService;
        this._instantiationService = _instantiationService;
        this._storageService = _storageService;
        this._configurationService = _configurationService;
        this._disposables = new DisposableStore();
        this._requestIdPool = 0;
        this._ignoreModelChangeEvent = false;
        this._referenceSearchVisible = ctxReferenceSearchVisible.bindTo(contextKeyService);
    }
    static get(editor) {
        return editor.getContribution(ReferencesController.ID);
    }
    dispose() {
        var _a, _b;
        this._referenceSearchVisible.reset();
        this._disposables.dispose();
        (_a = this._widget) === null || _a === void 0 ? void 0 : _a.dispose();
        (_b = this._model) === null || _b === void 0 ? void 0 : _b.dispose();
        this._widget = undefined;
        this._model = undefined;
    }
    toggleWidget(range, modelPromise, peekMode) {
        // close current widget and return early is position didn't change
        let widgetPosition;
        if (this._widget) {
            widgetPosition = this._widget.position;
        }
        this.closeWidget();
        if (!!widgetPosition && range.containsPosition(widgetPosition)) {
            return;
        }
        this._peekMode = peekMode;
        this._referenceSearchVisible.set(true);
        // close the widget on model/mode changes
        this._disposables.add(this._editor.onDidChangeModelLanguage(() => { this.closeWidget(); }));
        this._disposables.add(this._editor.onDidChangeModel(() => {
            if (!this._ignoreModelChangeEvent) {
                this.closeWidget();
            }
        }));
        const storageKey = 'peekViewLayout';
        const data = LayoutData.fromJSON(this._storageService.get(storageKey, 0 /* StorageScope.PROFILE */, '{}'));
        this._widget = this._instantiationService.createInstance(ReferenceWidget, this._editor, this._defaultTreeKeyboardSupport, data);
        this._widget.setTitle(localize('labelLoading', "Loading..."));
        this._widget.show(range);
        this._disposables.add(this._widget.onDidClose(() => {
            modelPromise.cancel();
            if (this._widget) {
                this._storageService.store(storageKey, JSON.stringify(this._widget.layoutData), 0 /* StorageScope.PROFILE */, 1 /* StorageTarget.MACHINE */);
                this._widget = undefined;
            }
            this.closeWidget();
        }));
        this._disposables.add(this._widget.onDidSelectReference(event => {
            const { element, kind } = event;
            if (!element) {
                return;
            }
            switch (kind) {
                case 'open':
                    if (event.source !== 'editor' || !this._configurationService.getValue('editor.stablePeek')) {
                        // when stable peek is configured we don't close
                        // the peek window on selecting the editor
                        this.openReference(element, false, false);
                    }
                    break;
                case 'side':
                    this.openReference(element, true, false);
                    break;
                case 'goto':
                    if (peekMode) {
                        this._gotoReference(element);
                    }
                    else {
                        this.openReference(element, false, true);
                    }
                    break;
            }
        }));
        const requestId = ++this._requestIdPool;
        modelPromise.then(model => {
            var _a;
            // still current request? widget still open?
            if (requestId !== this._requestIdPool || !this._widget) {
                model.dispose();
                return undefined;
            }
            (_a = this._model) === null || _a === void 0 ? void 0 : _a.dispose();
            this._model = model;
            // show widget
            return this._widget.setModel(this._model).then(() => {
                if (this._widget && this._model && this._editor.hasModel()) { // might have been closed
                    // set title
                    if (!this._model.isEmpty) {
                        this._widget.setMetaTitle(localize('metaTitle.N', "{0} ({1})", this._model.title, this._model.references.length));
                    }
                    else {
                        this._widget.setMetaTitle('');
                    }
                    // set 'best' selection
                    const uri = this._editor.getModel().uri;
                    const pos = new Position(range.startLineNumber, range.startColumn);
                    const selection = this._model.nearestReference(uri, pos);
                    if (selection) {
                        return this._widget.setSelection(selection).then(() => {
                            if (this._widget && this._editor.getOption(79 /* EditorOption.peekWidgetDefaultFocus */) === 'editor') {
                                this._widget.focusOnPreviewEditor();
                            }
                        });
                    }
                }
                return undefined;
            });
        }, error => {
            this._notificationService.error(error);
        });
    }
    changeFocusBetweenPreviewAndReferences() {
        if (!this._widget) {
            // can be called while still resolving...
            return;
        }
        if (this._widget.isPreviewEditorFocused()) {
            this._widget.focusOnReferenceTree();
        }
        else {
            this._widget.focusOnPreviewEditor();
        }
    }
    goToNextOrPreviousReference(fwd) {
        return referencesController_awaiter(this, void 0, void 0, function* () {
            if (!this._editor.hasModel() || !this._model || !this._widget) {
                // can be called while still resolving...
                return;
            }
            const currentPosition = this._widget.position;
            if (!currentPosition) {
                return;
            }
            const source = this._model.nearestReference(this._editor.getModel().uri, currentPosition);
            if (!source) {
                return;
            }
            const target = this._model.nextOrPreviousReference(source, fwd);
            const editorFocus = this._editor.hasTextFocus();
            const previewEditorFocus = this._widget.isPreviewEditorFocused();
            yield this._widget.setSelection(target);
            yield this._gotoReference(target);
            if (editorFocus) {
                this._editor.focus();
            }
            else if (this._widget && previewEditorFocus) {
                this._widget.focusOnPreviewEditor();
            }
        });
    }
    revealReference(reference) {
        return referencesController_awaiter(this, void 0, void 0, function* () {
            if (!this._editor.hasModel() || !this._model || !this._widget) {
                // can be called while still resolving...
                return;
            }
            yield this._widget.revealReference(reference);
        });
    }
    closeWidget(focusEditor = true) {
        var _a, _b;
        (_a = this._widget) === null || _a === void 0 ? void 0 : _a.dispose();
        (_b = this._model) === null || _b === void 0 ? void 0 : _b.dispose();
        this._referenceSearchVisible.reset();
        this._disposables.clear();
        this._widget = undefined;
        this._model = undefined;
        if (focusEditor) {
            this._editor.focus();
        }
        this._requestIdPool += 1; // Cancel pending requests
    }
    _gotoReference(ref) {
        if (this._widget) {
            this._widget.hide();
        }
        this._ignoreModelChangeEvent = true;
        const range = Range.lift(ref.range).collapseToStart();
        return this._editorService.openCodeEditor({
            resource: ref.uri,
            options: { selection: range, selectionSource: "code.jump" /* TextEditorSelectionSource.JUMP */ }
        }, this._editor).then(openedEditor => {
            var _a;
            this._ignoreModelChangeEvent = false;
            if (!openedEditor || !this._widget) {
                // something went wrong...
                this.closeWidget();
                return;
            }
            if (this._editor === openedEditor) {
                //
                this._widget.show(range);
                this._widget.focusOnReferenceTree();
            }
            else {
                // we opened a different editor instance which means a different controller instance.
                // therefore we stop with this controller and continue with the other
                const other = ReferencesController.get(openedEditor);
                const model = this._model.clone();
                this.closeWidget();
                openedEditor.focus();
                other === null || other === void 0 ? void 0 : other.toggleWidget(range, createCancelablePromise(_ => Promise.resolve(model)), (_a = this._peekMode) !== null && _a !== void 0 ? _a : false);
            }
        }, (err) => {
            this._ignoreModelChangeEvent = false;
            onUnexpectedError(err);
        });
    }
    openReference(ref, sideBySide, pinned) {
        // clear stage
        if (!sideBySide) {
            this.closeWidget();
        }
        const { uri, range } = ref;
        this._editorService.openCodeEditor({
            resource: uri,
            options: { selection: range, selectionSource: "code.jump" /* TextEditorSelectionSource.JUMP */, pinned }
        }, this._editor, sideBySide);
    }
};
ReferencesController.ID = 'editor.contrib.referencesController';
ReferencesController = referencesController_decorate([
    referencesController_param(2, IContextKeyService),
    referencesController_param(3, ICodeEditorService),
    referencesController_param(4, INotificationService),
    referencesController_param(5, IInstantiationService),
    referencesController_param(6, IStorageService),
    referencesController_param(7, IConfigurationService)
], ReferencesController);

function withController(accessor, fn) {
    const outerEditor = getOuterEditor(accessor);
    if (!outerEditor) {
        return;
    }
    const controller = ReferencesController.get(outerEditor);
    if (controller) {
        fn(controller);
    }
}
KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: 'togglePeekWidgetFocus',
    weight: 100 /* KeybindingWeight.EditorContrib */,
    primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 60 /* KeyCode.F2 */),
    when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
    handler(accessor) {
        withController(accessor, controller => {
            controller.changeFocusBetweenPreviewAndReferences();
        });
    }
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: 'goToNextReference',
    weight: 100 /* KeybindingWeight.EditorContrib */ - 10,
    primary: 62 /* KeyCode.F4 */,
    secondary: [70 /* KeyCode.F12 */],
    when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
    handler(accessor) {
        withController(accessor, controller => {
            controller.goToNextOrPreviousReference(true);
        });
    }
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: 'goToPreviousReference',
    weight: 100 /* KeybindingWeight.EditorContrib */ - 10,
    primary: 1024 /* KeyMod.Shift */ | 62 /* KeyCode.F4 */,
    secondary: [1024 /* KeyMod.Shift */ | 70 /* KeyCode.F12 */],
    when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
    handler(accessor) {
        withController(accessor, controller => {
            controller.goToNextOrPreviousReference(false);
        });
    }
});
// commands that aren't needed anymore because there is now ContextKeyExpr.OR
CommandsRegistry.registerCommandAlias('goToNextReferenceFromEmbeddedEditor', 'goToNextReference');
CommandsRegistry.registerCommandAlias('goToPreviousReferenceFromEmbeddedEditor', 'goToPreviousReference');
// close
CommandsRegistry.registerCommandAlias('closeReferenceSearchEditor', 'closeReferenceSearch');
CommandsRegistry.registerCommand('closeReferenceSearch', accessor => withController(accessor, controller => controller.closeWidget()));
KeybindingsRegistry.registerKeybindingRule({
    id: 'closeReferenceSearch',
    weight: 100 /* KeybindingWeight.EditorContrib */ - 101,
    primary: 9 /* KeyCode.Escape */,
    secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */],
    when: ContextKeyExpr.and(PeekContext.inPeekEditor, ContextKeyExpr.not('config.editor.stablePeek'))
});
KeybindingsRegistry.registerKeybindingRule({
    id: 'closeReferenceSearch',
    weight: 200 /* KeybindingWeight.WorkbenchContrib */ + 50,
    primary: 9 /* KeyCode.Escape */,
    secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */],
    when: ContextKeyExpr.and(ctxReferenceSearchVisible, ContextKeyExpr.not('config.editor.stablePeek'))
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: 'revealReference',
    weight: 200 /* KeybindingWeight.WorkbenchContrib */,
    primary: 3 /* KeyCode.Enter */,
    mac: {
        primary: 3 /* KeyCode.Enter */,
        secondary: [2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */]
    },
    when: ContextKeyExpr.and(ctxReferenceSearchVisible, WorkbenchListFocusContextKey, WorkbenchTreeElementCanCollapse.negate(), WorkbenchTreeElementCanExpand.negate()),
    handler(accessor) {
        var _a;
        const listService = accessor.get(IListService);
        const focus = (_a = listService.lastFocusedList) === null || _a === void 0 ? void 0 : _a.getFocus();
        if (Array.isArray(focus) && focus[0] instanceof OneReference) {
            withController(accessor, controller => controller.revealReference(focus[0]));
        }
    }
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: 'openReferenceToSide',
    weight: 100 /* KeybindingWeight.EditorContrib */,
    primary: 2048 /* KeyMod.CtrlCmd */ | 3 /* KeyCode.Enter */,
    mac: {
        primary: 256 /* KeyMod.WinCtrl */ | 3 /* KeyCode.Enter */
    },
    when: ContextKeyExpr.and(ctxReferenceSearchVisible, WorkbenchListFocusContextKey, WorkbenchTreeElementCanCollapse.negate(), WorkbenchTreeElementCanExpand.negate()),
    handler(accessor) {
        var _a;
        const listService = accessor.get(IListService);
        const focus = (_a = listService.lastFocusedList) === null || _a === void 0 ? void 0 : _a.getFocus();
        if (Array.isArray(focus) && focus[0] instanceof OneReference) {
            withController(accessor, controller => controller.openReference(focus[0], true, true));
        }
    }
});
CommandsRegistry.registerCommand('openReference', (accessor) => {
    var _a;
    const listService = accessor.get(IListService);
    const focus = (_a = listService.lastFocusedList) === null || _a === void 0 ? void 0 : _a.getFocus();
    if (Array.isArray(focus) && focus[0] instanceof OneReference) {
        withController(accessor, controller => controller.openReference(focus[0], false, true));
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/symbolNavigation.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var symbolNavigation_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var symbolNavigation_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};













const ctxHasSymbols = new RawContextKey('hasSymbols', false, localize('hasSymbols', "Whether there are symbol locations that can be navigated via keyboard-only."));
const ISymbolNavigationService = createDecorator('ISymbolNavigationService');
let SymbolNavigationService = class SymbolNavigationService {
    constructor(contextKeyService, _editorService, _notificationService, _keybindingService) {
        this._editorService = _editorService;
        this._notificationService = _notificationService;
        this._keybindingService = _keybindingService;
        this._currentModel = undefined;
        this._currentIdx = -1;
        this._ignoreEditorChange = false;
        this._ctxHasSymbols = ctxHasSymbols.bindTo(contextKeyService);
    }
    reset() {
        var _a, _b;
        this._ctxHasSymbols.reset();
        (_a = this._currentState) === null || _a === void 0 ? void 0 : _a.dispose();
        (_b = this._currentMessage) === null || _b === void 0 ? void 0 : _b.dispose();
        this._currentModel = undefined;
        this._currentIdx = -1;
    }
    put(anchor) {
        const refModel = anchor.parent.parent;
        if (refModel.references.length <= 1) {
            this.reset();
            return;
        }
        this._currentModel = refModel;
        this._currentIdx = refModel.references.indexOf(anchor);
        this._ctxHasSymbols.set(true);
        this._showMessage();
        const editorState = new symbolNavigation_EditorState(this._editorService);
        const listener = editorState.onDidChange(_ => {
            if (this._ignoreEditorChange) {
                return;
            }
            const editor = this._editorService.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 (isEqual(reference.uri, model.uri)) {
                    seenUri = true;
                    seenPosition = seenPosition || Range.containsPosition(reference.range, position);
                }
                else if (seenUri) {
                    break;
                }
            }
            if (!seenUri || !seenPosition) {
                this.reset();
            }
        });
        this._currentState = combinedDisposable(editorState, listener);
    }
    revealNext(source) {
        if (!this._currentModel) {
            return Promise.resolve();
        }
        // get next result and advance
        this._currentIdx += 1;
        this._currentIdx %= this._currentModel.references.length;
        const reference = this._currentModel.references[this._currentIdx];
        // status
        this._showMessage();
        // open editor, ignore events while that happens
        this._ignoreEditorChange = true;
        return this._editorService.openCodeEditor({
            resource: reference.uri,
            options: {
                selection: Range.collapseToStart(reference.range),
                selectionRevealType: 3 /* TextEditorSelectionRevealType.NearTopIfOutsideViewport */
            }
        }, source).finally(() => {
            this._ignoreEditorChange = false;
        });
    }
    _showMessage() {
        var _a;
        (_a = this._currentMessage) === null || _a === void 0 ? void 0 : _a.dispose();
        const kb = this._keybindingService.lookupKeybinding('editor.gotoNextSymbolFromResult');
        const message = kb
            ? localize('location.kb', "Symbol {0} of {1}, {2} for next", this._currentIdx + 1, this._currentModel.references.length, kb.getLabel())
            : localize('location', "Symbol {0} of {1}", this._currentIdx + 1, this._currentModel.references.length);
        this._currentMessage = this._notificationService.status(message);
    }
};
SymbolNavigationService = symbolNavigation_decorate([
    symbolNavigation_param(0, IContextKeyService),
    symbolNavigation_param(1, ICodeEditorService),
    symbolNavigation_param(2, INotificationService),
    symbolNavigation_param(3, IKeybindingService)
], SymbolNavigationService);
registerSingleton(ISymbolNavigationService, SymbolNavigationService, true);
registerEditorCommand(new class extends EditorCommand {
    constructor() {
        super({
            id: 'editor.gotoNextSymbolFromResult',
            precondition: ctxHasSymbols,
            kbOpts: {
                weight: 100 /* KeybindingWeight.EditorContrib */,
                primary: 70 /* KeyCode.F12 */
            }
        });
    }
    runEditorCommand(accessor, editor) {
        return accessor.get(ISymbolNavigationService).revealNext(editor);
    }
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: 'editor.gotoNextSymbolFromResult.cancel',
    weight: 100 /* KeybindingWeight.EditorContrib */,
    when: ctxHasSymbols,
    primary: 9 /* KeyCode.Escape */,
    handler(accessor) {
        accessor.get(ISymbolNavigationService).reset();
    }
});
//
let symbolNavigation_EditorState = class EditorState {
    constructor(editorService) {
        this._listener = new Map();
        this._disposables = new DisposableStore();
        this._onDidChange = new Emitter();
        this.onDidChange = this._onDidChange.event;
        this._disposables.add(editorService.onCodeEditorRemove(this._onDidRemoveEditor, this));
        this._disposables.add(editorService.onCodeEditorAdd(this._onDidAddEditor, this));
        editorService.listCodeEditors().forEach(this._onDidAddEditor, this);
    }
    dispose() {
        this._disposables.dispose();
        this._onDidChange.dispose();
        dispose(this._listener.values());
    }
    _onDidAddEditor(editor) {
        this._listener.set(editor, combinedDisposable(editor.onDidChangeCursorPosition(_ => this._onDidChange.fire({ editor })), editor.onDidChangeModelContent(_ => this._onDidChange.fire({ editor }))));
    }
    _onDidRemoveEditor(editor) {
        var _a;
        (_a = this._listener.get(editor)) === null || _a === void 0 ? void 0 : _a.dispose();
        this._listener.delete(editor);
    }
};
symbolNavigation_EditorState = symbolNavigation_decorate([
    symbolNavigation_param(0, ICodeEditorService)
], symbolNavigation_EditorState);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/goToSymbol.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var goToSymbol_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};





function getLocationLinks(model, position, registry, provide) {
    const provider = registry.ordered(model);
    // get results
    const promises = provider.map((provider) => {
        return Promise.resolve(provide(provider, model, position)).then(undefined, err => {
            onUnexpectedExternalError(err);
            return undefined;
        });
    });
    return Promise.all(promises).then(values => {
        const result = [];
        for (const value of values) {
            if (Array.isArray(value)) {
                result.push(...value);
            }
            else if (value) {
                result.push(value);
            }
        }
        return result;
    });
}
function getDefinitionsAtPosition(registry, model, position, token) {
    return getLocationLinks(model, position, registry, (provider, model, position) => {
        return provider.provideDefinition(model, position, token);
    });
}
function getDeclarationsAtPosition(registry, model, position, token) {
    return getLocationLinks(model, position, registry, (provider, model, position) => {
        return provider.provideDeclaration(model, position, token);
    });
}
function getImplementationsAtPosition(registry, model, position, token) {
    return getLocationLinks(model, position, registry, (provider, model, position) => {
        return provider.provideImplementation(model, position, token);
    });
}
function getTypeDefinitionsAtPosition(registry, model, position, token) {
    return getLocationLinks(model, position, registry, (provider, model, position) => {
        return provider.provideTypeDefinition(model, position, token);
    });
}
function getReferencesAtPosition(registry, model, position, compact, token) {
    return getLocationLinks(model, position, registry, (provider, model, position) => goToSymbol_awaiter(this, void 0, void 0, function* () {
        const result = yield provider.provideReferences(model, position, { includeDeclaration: true }, token);
        if (!compact || !result || result.length !== 2) {
            return result;
        }
        const resultWithoutDeclaration = yield provider.provideReferences(model, position, { includeDeclaration: false }, token);
        if (resultWithoutDeclaration && resultWithoutDeclaration.length === 1) {
            return resultWithoutDeclaration;
        }
        return result;
    }));
}
// -- API commands ----
function _sortedAndDeduped(callback) {
    return goToSymbol_awaiter(this, void 0, void 0, function* () {
        const rawLinks = yield callback();
        const model = new ReferencesModel(rawLinks, '');
        const modelLinks = model.references.map(ref => ref.link);
        model.dispose();
        return modelLinks;
    });
}
registerModelAndPositionCommand('_executeDefinitionProvider', (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getDefinitionsAtPosition(languageFeaturesService.definitionProvider, model, position, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
});
registerModelAndPositionCommand('_executeTypeDefinitionProvider', (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getTypeDefinitionsAtPosition(languageFeaturesService.typeDefinitionProvider, model, position, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
});
registerModelAndPositionCommand('_executeDeclarationProvider', (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getDeclarationsAtPosition(languageFeaturesService.declarationProvider, model, position, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
});
registerModelAndPositionCommand('_executeReferenceProvider', (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, false, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
});
registerModelAndPositionCommand('_executeImplementationProvider', (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const promise = getImplementationsAtPosition(languageFeaturesService.implementationProvider, model, position, CancellationToken.None);
    return _sortedAndDeduped(() => promise);
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/goToCommands.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var goToCommands_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
var goToCommands_a, goToCommands_b, _c, _d, _e, _f, _g, _h;






























MenuRegistry.appendMenuItem(MenuId.EditorContext, {
    submenu: MenuId.EditorContextPeek,
    title: localize('peek.submenu', "Peek"),
    group: 'navigation',
    order: 100
});
const _goToActionIds = new Set();
function registerGoToAction(ctor) {
    const result = new ctor();
    registerInstantiatedEditorAction(result);
    _goToActionIds.add(result.id);
    return result;
}
class SymbolNavigationAnchor {
    constructor(model, position) {
        this.model = model;
        this.position = position;
    }
    static is(thing) {
        if (!thing || typeof thing !== 'object') {
            return false;
        }
        if (thing instanceof SymbolNavigationAnchor) {
            return true;
        }
        if (Position.isIPosition(thing.position) && thing.model) {
            return true;
        }
        return false;
    }
}
class SymbolNavigationAction extends EditorAction {
    constructor(configuration, opts) {
        super(opts);
        this.configuration = configuration;
    }
    run(accessor, editor, arg) {
        if (!editor.hasModel()) {
            return Promise.resolve(undefined);
        }
        const notificationService = accessor.get(INotificationService);
        const editorService = accessor.get(ICodeEditorService);
        const progressService = accessor.get(IEditorProgressService);
        const symbolNavService = accessor.get(ISymbolNavigationService);
        const languageFeaturesService = accessor.get(ILanguageFeaturesService);
        const model = editor.getModel();
        const position = editor.getPosition();
        const anchor = SymbolNavigationAnchor.is(arg) ? arg : new SymbolNavigationAnchor(model, position);
        const cts = new EditorStateCancellationTokenSource(editor, 1 /* CodeEditorStateFlag.Value */ | 4 /* CodeEditorStateFlag.Position */);
        const promise = raceCancellation(this._getLocationModel(languageFeaturesService, anchor.model, anchor.position, cts.token), cts.token).then((references) => goToCommands_awaiter(this, void 0, void 0, function* () {
            var _a;
            if (!references || cts.token.isCancellationRequested) {
                return;
            }
            aria_alert(references.ariaMessage);
            let altAction;
            if (references.referenceAt(model.uri, position)) {
                const altActionId = this._getAlternativeCommand(editor);
                if (!SymbolNavigationAction._activeAlternativeCommands.has(altActionId) && _goToActionIds.has(altActionId)) {
                    altAction = editor.getAction(altActionId);
                }
            }
            const referenceCount = references.references.length;
            if (referenceCount === 0) {
                // no result -> show message
                if (!this.configuration.muteMessage) {
                    const info = model.getWordAtPosition(position);
                    (_a = MessageController.get(editor)) === null || _a === void 0 ? void 0 : _a.showMessage(this._getNoResultFoundMessage(info), position);
                }
            }
            else if (referenceCount === 1 && altAction) {
                // already at the only result, run alternative
                SymbolNavigationAction._activeAlternativeCommands.add(this.id);
                altAction.run().finally(() => {
                    SymbolNavigationAction._activeAlternativeCommands.delete(this.id);
                });
            }
            else {
                // normal results handling
                return this._onResult(editorService, symbolNavService, editor, references);
            }
        }), (err) => {
            // report an error
            notificationService.error(err);
        }).finally(() => {
            cts.dispose();
        });
        progressService.showWhile(promise, 250);
        return promise;
    }
    _onResult(editorService, symbolNavService, editor, model) {
        return goToCommands_awaiter(this, void 0, void 0, function* () {
            const gotoLocation = this._getGoToPreference(editor);
            if (!(editor instanceof EmbeddedCodeEditorWidget) && (this.configuration.openInPeek || (gotoLocation === 'peek' && model.references.length > 1))) {
                this._openInPeek(editor, model);
            }
            else {
                const next = model.firstReference();
                const peek = model.references.length > 1 && gotoLocation === 'gotoAndPeek';
                const targetEditor = yield this._openReference(editor, editorService, next, this.configuration.openToSide, !peek);
                if (peek && targetEditor) {
                    this._openInPeek(targetEditor, model);
                }
                else {
                    model.dispose();
                }
                // keep remaining locations around when using
                // 'goto'-mode
                if (gotoLocation === 'goto') {
                    symbolNavService.put(next);
                }
            }
        });
    }
    _openReference(editor, editorService, reference, sideBySide, highlight) {
        return goToCommands_awaiter(this, void 0, void 0, function* () {
            // range is the target-selection-range when we have one
            // and the fallback is the 'full' range
            let range = undefined;
            if (isLocationLink(reference)) {
                range = reference.targetSelectionRange;
            }
            if (!range) {
                range = reference.range;
            }
            if (!range) {
                return undefined;
            }
            const targetEditor = yield editorService.openCodeEditor({
                resource: reference.uri,
                options: {
                    selection: Range.collapseToStart(range),
                    selectionRevealType: 3 /* TextEditorSelectionRevealType.NearTopIfOutsideViewport */,
                    selectionSource: "code.jump" /* TextEditorSelectionSource.JUMP */
                }
            }, editor, sideBySide);
            if (!targetEditor) {
                return undefined;
            }
            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;
        });
    }
    _openInPeek(target, model) {
        const controller = ReferencesController.get(target);
        if (controller && target.hasModel()) {
            controller.toggleWidget(target.getSelection(), createCancelablePromise(_ => Promise.resolve(model)), this.configuration.openInPeek);
        }
        else {
            model.dispose();
        }
    }
}
SymbolNavigationAction._activeAlternativeCommands = new Set();
//#region --- DEFINITION
class DefinitionAction extends SymbolNavigationAction {
    _getLocationModel(languageFeaturesService, model, position, token) {
        return goToCommands_awaiter(this, void 0, void 0, function* () {
            return new ReferencesModel(yield getDefinitionsAtPosition(languageFeaturesService.definitionProvider, model, position, token), localize('def.title', 'Definitions'));
        });
    }
    _getNoResultFoundMessage(info) {
        return info && info.word
            ? localize('noResultWord', "No definition found for '{0}'", info.word)
            : localize('generic.noResults', "No definition found");
    }
    _getAlternativeCommand(editor) {
        return editor.getOption(53 /* EditorOption.gotoLocation */).alternativeDefinitionCommand;
    }
    _getGoToPreference(editor) {
        return editor.getOption(53 /* EditorOption.gotoLocation */).multipleDefinitions;
    }
}
const goToDefinitionKb = isWeb && !isStandalone()
    ? 2048 /* KeyMod.CtrlCmd */ | 70 /* KeyCode.F12 */
    : 70 /* KeyCode.F12 */;
registerGoToAction((goToCommands_a = class GoToDefinitionAction extends DefinitionAction {
        constructor() {
            super({
                openToSide: false,
                openInPeek: false,
                muteMessage: false
            }, {
                id: GoToDefinitionAction.id,
                label: localize('actions.goToDecl.label', "Go to Definition"),
                alias: 'Go to Definition',
                precondition: ContextKeyExpr.and(EditorContextKeys.hasDefinitionProvider, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
                kbOpts: {
                    kbExpr: EditorContextKeys.editorTextFocus,
                    primary: goToDefinitionKb,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    group: 'navigation',
                    order: 1.1
                }
            });
            CommandsRegistry.registerCommandAlias('editor.action.goToDeclaration', GoToDefinitionAction.id);
        }
    },
    goToCommands_a.id = 'editor.action.revealDefinition',
    goToCommands_a));
registerGoToAction((goToCommands_b = class OpenDefinitionToSideAction extends DefinitionAction {
        constructor() {
            super({
                openToSide: true,
                openInPeek: false,
                muteMessage: false
            }, {
                id: OpenDefinitionToSideAction.id,
                label: localize('actions.goToDeclToSide.label', "Open Definition to the Side"),
                alias: 'Open Definition to the Side',
                precondition: ContextKeyExpr.and(EditorContextKeys.hasDefinitionProvider, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
                kbOpts: {
                    kbExpr: EditorContextKeys.editorTextFocus,
                    primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, goToDefinitionKb),
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            });
            CommandsRegistry.registerCommandAlias('editor.action.openDeclarationToTheSide', OpenDefinitionToSideAction.id);
        }
    },
    goToCommands_b.id = 'editor.action.revealDefinitionAside',
    goToCommands_b));
registerGoToAction((_c = class PeekDefinitionAction extends DefinitionAction {
        constructor() {
            super({
                openToSide: false,
                openInPeek: true,
                muteMessage: false
            }, {
                id: PeekDefinitionAction.id,
                label: localize('actions.previewDecl.label', "Peek Definition"),
                alias: 'Peek Definition',
                precondition: ContextKeyExpr.and(EditorContextKeys.hasDefinitionProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
                kbOpts: {
                    kbExpr: EditorContextKeys.editorTextFocus,
                    primary: 512 /* KeyMod.Alt */ | 70 /* KeyCode.F12 */,
                    linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 68 /* KeyCode.F10 */ },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    menuId: MenuId.EditorContextPeek,
                    group: 'peek',
                    order: 2
                }
            });
            CommandsRegistry.registerCommandAlias('editor.action.previewDeclaration', PeekDefinitionAction.id);
        }
    },
    _c.id = 'editor.action.peekDefinition',
    _c));
//#endregion
//#region --- DECLARATION
class DeclarationAction extends SymbolNavigationAction {
    _getLocationModel(languageFeaturesService, model, position, token) {
        return goToCommands_awaiter(this, void 0, void 0, function* () {
            return new ReferencesModel(yield getDeclarationsAtPosition(languageFeaturesService.declarationProvider, model, position, token), localize('decl.title', 'Declarations'));
        });
    }
    _getNoResultFoundMessage(info) {
        return info && info.word
            ? localize('decl.noResultWord', "No declaration found for '{0}'", info.word)
            : localize('decl.generic.noResults', "No declaration found");
    }
    _getAlternativeCommand(editor) {
        return editor.getOption(53 /* EditorOption.gotoLocation */).alternativeDeclarationCommand;
    }
    _getGoToPreference(editor) {
        return editor.getOption(53 /* EditorOption.gotoLocation */).multipleDeclarations;
    }
}
registerGoToAction((_d = class GoToDeclarationAction extends DeclarationAction {
        constructor() {
            super({
                openToSide: false,
                openInPeek: false,
                muteMessage: false
            }, {
                id: GoToDeclarationAction.id,
                label: localize('actions.goToDeclaration.label', "Go to Declaration"),
                alias: 'Go to Declaration',
                precondition: ContextKeyExpr.and(EditorContextKeys.hasDeclarationProvider, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
                contextMenuOpts: {
                    group: 'navigation',
                    order: 1.3
                },
            });
        }
        _getNoResultFoundMessage(info) {
            return info && info.word
                ? localize('decl.noResultWord', "No declaration found for '{0}'", info.word)
                : localize('decl.generic.noResults', "No declaration found");
        }
    },
    _d.id = 'editor.action.revealDeclaration',
    _d));
registerGoToAction(class PeekDeclarationAction extends DeclarationAction {
    constructor() {
        super({
            openToSide: false,
            openInPeek: true,
            muteMessage: false
        }, {
            id: 'editor.action.peekDeclaration',
            label: localize('actions.peekDecl.label', "Peek Declaration"),
            alias: 'Peek Declaration',
            precondition: ContextKeyExpr.and(EditorContextKeys.hasDeclarationProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
            contextMenuOpts: {
                menuId: MenuId.EditorContextPeek,
                group: 'peek',
                order: 3
            }
        });
    }
});
//#endregion
//#region --- TYPE DEFINITION
class TypeDefinitionAction extends SymbolNavigationAction {
    _getLocationModel(languageFeaturesService, model, position, token) {
        return goToCommands_awaiter(this, void 0, void 0, function* () {
            return new ReferencesModel(yield getTypeDefinitionsAtPosition(languageFeaturesService.typeDefinitionProvider, model, position, token), localize('typedef.title', 'Type Definitions'));
        });
    }
    _getNoResultFoundMessage(info) {
        return info && info.word
            ? localize('goToTypeDefinition.noResultWord', "No type definition found for '{0}'", info.word)
            : localize('goToTypeDefinition.generic.noResults', "No type definition found");
    }
    _getAlternativeCommand(editor) {
        return editor.getOption(53 /* EditorOption.gotoLocation */).alternativeTypeDefinitionCommand;
    }
    _getGoToPreference(editor) {
        return editor.getOption(53 /* EditorOption.gotoLocation */).multipleTypeDefinitions;
    }
}
registerGoToAction((_e = class GoToTypeDefinitionAction extends TypeDefinitionAction {
        constructor() {
            super({
                openToSide: false,
                openInPeek: false,
                muteMessage: false
            }, {
                id: GoToTypeDefinitionAction.ID,
                label: localize('actions.goToTypeDefinition.label', "Go to Type Definition"),
                alias: 'Go to Type Definition',
                precondition: ContextKeyExpr.and(EditorContextKeys.hasTypeDefinitionProvider, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
                kbOpts: {
                    kbExpr: EditorContextKeys.editorTextFocus,
                    primary: 0,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    group: 'navigation',
                    order: 1.4
                }
            });
        }
    },
    _e.ID = 'editor.action.goToTypeDefinition',
    _e));
registerGoToAction((_f = class PeekTypeDefinitionAction extends TypeDefinitionAction {
        constructor() {
            super({
                openToSide: false,
                openInPeek: true,
                muteMessage: false
            }, {
                id: PeekTypeDefinitionAction.ID,
                label: localize('actions.peekTypeDefinition.label', "Peek Type Definition"),
                alias: 'Peek Type Definition',
                precondition: ContextKeyExpr.and(EditorContextKeys.hasTypeDefinitionProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
                contextMenuOpts: {
                    menuId: MenuId.EditorContextPeek,
                    group: 'peek',
                    order: 4
                }
            });
        }
    },
    _f.ID = 'editor.action.peekTypeDefinition',
    _f));
//#endregion
//#region --- IMPLEMENTATION
class ImplementationAction extends SymbolNavigationAction {
    _getLocationModel(languageFeaturesService, model, position, token) {
        return goToCommands_awaiter(this, void 0, void 0, function* () {
            return new ReferencesModel(yield getImplementationsAtPosition(languageFeaturesService.implementationProvider, model, position, token), localize('impl.title', 'Implementations'));
        });
    }
    _getNoResultFoundMessage(info) {
        return info && info.word
            ? localize('goToImplementation.noResultWord', "No implementation found for '{0}'", info.word)
            : localize('goToImplementation.generic.noResults', "No implementation found");
    }
    _getAlternativeCommand(editor) {
        return editor.getOption(53 /* EditorOption.gotoLocation */).alternativeImplementationCommand;
    }
    _getGoToPreference(editor) {
        return editor.getOption(53 /* EditorOption.gotoLocation */).multipleImplementations;
    }
}
registerGoToAction((_g = class GoToImplementationAction extends ImplementationAction {
        constructor() {
            super({
                openToSide: false,
                openInPeek: false,
                muteMessage: false
            }, {
                id: GoToImplementationAction.ID,
                label: localize('actions.goToImplementation.label', "Go to Implementations"),
                alias: 'Go to Implementations',
                precondition: ContextKeyExpr.and(EditorContextKeys.hasImplementationProvider, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
                kbOpts: {
                    kbExpr: EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 70 /* KeyCode.F12 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    group: 'navigation',
                    order: 1.45
                }
            });
        }
    },
    _g.ID = 'editor.action.goToImplementation',
    _g));
registerGoToAction((_h = class PeekImplementationAction extends ImplementationAction {
        constructor() {
            super({
                openToSide: false,
                openInPeek: true,
                muteMessage: false
            }, {
                id: PeekImplementationAction.ID,
                label: localize('actions.peekImplementation.label', "Peek Implementations"),
                alias: 'Peek Implementations',
                precondition: ContextKeyExpr.and(EditorContextKeys.hasImplementationProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
                kbOpts: {
                    kbExpr: EditorContextKeys.editorTextFocus,
                    primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 70 /* KeyCode.F12 */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                },
                contextMenuOpts: {
                    menuId: MenuId.EditorContextPeek,
                    group: 'peek',
                    order: 5
                }
            });
        }
    },
    _h.ID = 'editor.action.peekImplementation',
    _h));
//#endregion
//#region --- REFERENCES
class ReferencesAction extends SymbolNavigationAction {
    _getNoResultFoundMessage(info) {
        return info
            ? localize('references.no', "No references found for '{0}'", info.word)
            : localize('references.noGeneric', "No references found");
    }
    _getAlternativeCommand(editor) {
        return editor.getOption(53 /* EditorOption.gotoLocation */).alternativeReferenceCommand;
    }
    _getGoToPreference(editor) {
        return editor.getOption(53 /* EditorOption.gotoLocation */).multipleReferences;
    }
}
registerGoToAction(class GoToReferencesAction extends ReferencesAction {
    constructor() {
        super({
            openToSide: false,
            openInPeek: false,
            muteMessage: false
        }, {
            id: 'editor.action.goToReferences',
            label: localize('goToReferences.label', "Go to References"),
            alias: 'Go to References',
            precondition: ContextKeyExpr.and(EditorContextKeys.hasReferenceProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 1024 /* KeyMod.Shift */ | 70 /* KeyCode.F12 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            contextMenuOpts: {
                group: 'navigation',
                order: 1.45
            }
        });
    }
    _getLocationModel(languageFeaturesService, model, position, token) {
        return goToCommands_awaiter(this, void 0, void 0, function* () {
            return new ReferencesModel(yield getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, true, token), localize('ref.title', 'References'));
        });
    }
});
registerGoToAction(class PeekReferencesAction extends ReferencesAction {
    constructor() {
        super({
            openToSide: false,
            openInPeek: true,
            muteMessage: false
        }, {
            id: 'editor.action.referenceSearch.trigger',
            label: localize('references.action.label', "Peek References"),
            alias: 'Peek References',
            precondition: ContextKeyExpr.and(EditorContextKeys.hasReferenceProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
            contextMenuOpts: {
                menuId: MenuId.EditorContextPeek,
                group: 'peek',
                order: 6
            }
        });
    }
    _getLocationModel(languageFeaturesService, model, position, token) {
        return goToCommands_awaiter(this, void 0, void 0, function* () {
            return new ReferencesModel(yield getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, false, token), localize('ref.title', 'References'));
        });
    }
});
//#endregion
//#region --- GENERIC goto symbols command
class GenericGoToLocationAction extends SymbolNavigationAction {
    constructor(config, _references, _gotoMultipleBehaviour) {
        super(config, {
            id: 'editor.action.goToLocation',
            label: localize('label.generic', "Go to Any Symbol"),
            alias: 'Go to Any Symbol',
            precondition: ContextKeyExpr.and(PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
        });
        this._references = _references;
        this._gotoMultipleBehaviour = _gotoMultipleBehaviour;
    }
    _getLocationModel(languageFeaturesService, _model, _position, _token) {
        return goToCommands_awaiter(this, void 0, void 0, function* () {
            return new ReferencesModel(this._references, localize('generic.title', 'Locations'));
        });
    }
    _getNoResultFoundMessage(info) {
        return info && localize('generic.noResult', "No results for '{0}'", info.word) || '';
    }
    _getGoToPreference(editor) {
        var _a;
        return (_a = this._gotoMultipleBehaviour) !== null && _a !== void 0 ? _a : editor.getOption(53 /* EditorOption.gotoLocation */).multipleReferences;
    }
    _getAlternativeCommand() { return ''; }
}
CommandsRegistry.registerCommand({
    id: 'editor.action.goToLocations',
    description: {
        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: Position.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: (accessor, resource, position, references, multiple, noResultsMessage, openInPeek) => goToCommands_awaiter(void 0, void 0, void 0, function* () {
        assertType(URI.isUri(resource));
        assertType(Position.isIPosition(position));
        assertType(Array.isArray(references));
        assertType(typeof multiple === 'undefined' || typeof multiple === 'string');
        assertType(typeof openInPeek === 'undefined' || typeof openInPeek === 'boolean');
        const editorService = accessor.get(ICodeEditorService);
        const editor = yield editorService.openCodeEditor({ resource }, editorService.getFocusedCodeEditor());
        if (isCodeEditor(editor)) {
            editor.setPosition(position);
            editor.revealPositionInCenterIfOutsideViewport(position, 0 /* ScrollType.Smooth */);
            return editor.invokeWithinContext(accessor => {
                const command = new class extends GenericGoToLocationAction {
                    _getNoResultFoundMessage(info) {
                        return noResultsMessage || super._getNoResultFoundMessage(info);
                    }
                }({
                    muteMessage: !Boolean(noResultsMessage),
                    openInPeek: Boolean(openInPeek),
                    openToSide: false
                }, references, multiple);
                accessor.get(IInstantiationService).invokeFunction(command.run.bind(command), editor);
            });
        }
    })
});
CommandsRegistry.registerCommand({
    id: 'editor.action.peekLocations',
    description: {
        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: Position.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: (accessor, resource, position, references, multiple) => goToCommands_awaiter(void 0, void 0, void 0, function* () {
        accessor.get(ICommandService).executeCommand('editor.action.goToLocations', resource, position, references, multiple, undefined, true);
    })
});
//#endregion
//#region --- REFERENCE search special commands
CommandsRegistry.registerCommand({
    id: 'editor.action.findReferences',
    handler: (accessor, resource, position) => {
        assertType(URI.isUri(resource));
        assertType(Position.isIPosition(position));
        const languageFeaturesService = accessor.get(ILanguageFeaturesService);
        const codeEditorService = accessor.get(ICodeEditorService);
        return codeEditorService.openCodeEditor({ resource }, codeEditorService.getFocusedCodeEditor()).then(control => {
            if (!isCodeEditor(control) || !control.hasModel()) {
                return undefined;
            }
            const controller = ReferencesController.get(control);
            if (!controller) {
                return undefined;
            }
            const references = createCancelablePromise(token => getReferencesAtPosition(languageFeaturesService.referenceProvider, control.getModel(), Position.lift(position), false, token).then(references => new ReferencesModel(references, localize('ref.title', 'References'))));
            const range = new Range(position.lineNumber, position.column, position.lineNumber, position.column);
            return Promise.resolve(controller.toggleWidget(range, references, false));
        });
    }
});
// use NEW command
CommandsRegistry.registerCommandAlias('editor.action.showReferences', 'editor.action.peekLocations');
//#endregion
// -- unconditionally register goto-action
MenuRegistry.appendMenuItems([
    {
        id: MenuId.MenubarGoMenu,
        item: {
            command: {
                id: 'editor.action.revealDefinition',
                title: localize({ key: 'miGotoDefinition', comment: ['&& denotes a mnemonic'] }, "Go to &&Definition")
            },
            group: '4_symbol_nav',
            order: 2,
        },
    },
    {
        id: MenuId.MenubarGoMenu,
        item: {
            command: {
                id: 'editor.action.revealDeclaration',
                title: localize({ key: 'miGotoDeclaration', comment: ['&& denotes a mnemonic'] }, "Go to &&Declaration")
            },
            group: '4_symbol_nav',
            order: 3,
        },
    },
    {
        id: MenuId.MenubarGoMenu,
        item: {
            command: {
                id: 'editor.action.goToTypeDefinition',
                title: localize({ key: 'miGotoTypeDefinition', comment: ['&& denotes a mnemonic'] }, "Go to &&Type Definition")
            },
            group: '4_symbol_nav',
            order: 3,
        },
    },
    {
        id: MenuId.MenubarGoMenu,
        item: {
            command: {
                id: 'editor.action.goToImplementation',
                title: localize({ key: 'miGotoImplementation', comment: ['&& denotes a mnemonic'] }, "Go to &&Implementations")
            },
            group: '4_symbol_nav',
            order: 4,
        },
    },
    {
        id: MenuId.MenubarGoMenu,
        item: {
            command: {
                id: 'editor.action.goToReferences',
                title: localize({ key: 'miGotoReference', comment: ['&& denotes a mnemonic'] }, "Go to &&References")
            },
            group: '4_symbol_nav',
            order: 5,
        },
    },
]);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var goToDefinitionAtPosition_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var goToDefinitionAtPosition_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};




















let GotoDefinitionAtPositionEditorContribution = class GotoDefinitionAtPositionEditorContribution {
    constructor(editor, textModelResolverService, languageService, languageFeaturesService) {
        this.textModelResolverService = textModelResolverService;
        this.languageService = languageService;
        this.languageFeaturesService = languageFeaturesService;
        this.toUnhook = new DisposableStore();
        this.toUnhookForKeyboard = new DisposableStore();
        this.currentWordAtPosition = null;
        this.previousPromise = null;
        this.editor = editor;
        this.linkDecorations = this.editor.createDecorationsCollection();
        const linkGesture = new ClickLinkGesture(editor);
        this.toUnhook.add(linkGesture);
        this.toUnhook.add(linkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
            this.startFindDefinitionFromMouse(mouseEvent, withNullAsUndefined(keyboardEvent));
        }));
        this.toUnhook.add(linkGesture.onExecute((mouseEvent) => {
            if (this.isEnabled(mouseEvent)) {
                this.gotoDefinition(mouseEvent.target.position, mouseEvent.hasSideBySideModifier).then(() => {
                    this.removeLinkDecorations();
                }, (error) => {
                    this.removeLinkDecorations();
                    onUnexpectedError(error);
                });
            }
        }));
        this.toUnhook.add(linkGesture.onCancel(() => {
            this.removeLinkDecorations();
            this.currentWordAtPosition = null;
        }));
    }
    static get(editor) {
        return editor.getContribution(GotoDefinitionAtPositionEditorContribution.ID);
    }
    startFindDefinitionFromCursor(position) {
        // For issue: https://github.com/microsoft/vscode/issues/46257
        // equivalent to mouse move with meta/ctrl key
        // First find the definition and add decorations
        // to the editor to be shown with the content hover widget
        return this.startFindDefinition(position).then(() => {
            // Add listeners for editor cursor move and key down events
            // Dismiss the "extended" editor decorations when the user hides
            // the hover widget. There is no event for the widget itself so these
            // serve as a best effort. After removing the link decorations, the hover
            // widget is clean and will only show declarations per next request.
            this.toUnhookForKeyboard.add(this.editor.onDidChangeCursorPosition(() => {
                this.currentWordAtPosition = null;
                this.removeLinkDecorations();
                this.toUnhookForKeyboard.clear();
            }));
            this.toUnhookForKeyboard.add(this.editor.onKeyDown((e) => {
                if (e) {
                    this.currentWordAtPosition = null;
                    this.removeLinkDecorations();
                    this.toUnhookForKeyboard.clear();
                }
            }));
        });
    }
    startFindDefinitionFromMouse(mouseEvent, withKey) {
        // check if we are active and on a content widget
        if (mouseEvent.target.type === 9 /* MouseTargetType.CONTENT_WIDGET */ && this.linkDecorations.length > 0) {
            return;
        }
        if (!this.editor.hasModel() || !this.isEnabled(mouseEvent, withKey)) {
            this.currentWordAtPosition = null;
            this.removeLinkDecorations();
            return;
        }
        const position = mouseEvent.target.position;
        this.startFindDefinition(position);
    }
    startFindDefinition(position) {
        var _a;
        // Dispose listeners for updating decorations when using keyboard to show definition hover
        this.toUnhookForKeyboard.clear();
        // Find word at mouse position
        const word = position ? (_a = this.editor.getModel()) === null || _a === void 0 ? void 0 : _a.getWordAtPosition(position) : null;
        if (!word) {
            this.currentWordAtPosition = null;
            this.removeLinkDecorations();
            return Promise.resolve(0);
        }
        // Return early if word at position is still the same
        if (this.currentWordAtPosition && this.currentWordAtPosition.startColumn === word.startColumn && this.currentWordAtPosition.endColumn === word.endColumn && this.currentWordAtPosition.word === word.word) {
            return Promise.resolve(0);
        }
        this.currentWordAtPosition = word;
        // Find definition and decorate word if found
        const state = new EditorState(this.editor, 4 /* CodeEditorStateFlag.Position */ | 1 /* CodeEditorStateFlag.Value */ | 2 /* CodeEditorStateFlag.Selection */ | 8 /* CodeEditorStateFlag.Scroll */);
        if (this.previousPromise) {
            this.previousPromise.cancel();
            this.previousPromise = null;
        }
        this.previousPromise = createCancelablePromise(token => this.findDefinition(position, token));
        return this.previousPromise.then(results => {
            if (!results || !results.length || !state.validate(this.editor)) {
                this.removeLinkDecorations();
                return;
            }
            // Multiple results
            if (results.length > 1) {
                this.addDecoration(new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn), new MarkdownString().appendText(localize('multipleResults', "Click to show {0} definitions.", results.length)));
            }
            // Single result
            else {
                const result = results[0];
                if (!result.uri) {
                    return;
                }
                this.textModelResolverService.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()) {
                        // invalid range
                        ref.dispose();
                        return;
                    }
                    const previewValue = this.getPreviewValue(textEditorModel, startLineNumber, result);
                    let wordRange;
                    if (result.originSelectionRange) {
                        wordRange = Range.lift(result.originSelectionRange);
                    }
                    else {
                        wordRange = new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
                    }
                    const languageId = this.languageService.guessLanguageIdByFilepathOrFirstLine(textEditorModel.uri);
                    this.addDecoration(wordRange, new MarkdownString().appendCodeblock(languageId ? languageId : '', previewValue));
                    ref.dispose();
                });
            }
        }).then(undefined, onUnexpectedError);
    }
    getPreviewValue(textEditorModel, startLineNumber, result) {
        let rangeToUse = result.range;
        const numberOfLinesInRange = rangeToUse.endLineNumber - rangeToUse.startLineNumber;
        if (numberOfLinesInRange >= GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES) {
            rangeToUse = this.getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber);
        }
        const previewValue = this.stripIndentationFromPreviewRange(textEditorModel, startLineNumber, rangeToUse);
        return previewValue;
    }
    stripIndentationFromPreviewRange(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;
    }
    getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber) {
        const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
        const maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES);
        let endLineNumber = startLineNumber + 1;
        for (; endLineNumber < maxLineNumber; endLineNumber++) {
            const endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
            if (startIndent === endIndent) {
                break;
            }
        }
        return new Range(startLineNumber, 1, endLineNumber + 1, 1);
    }
    addDecoration(range, hoverMessage) {
        const newDecorations = {
            range: range,
            options: {
                description: 'goto-definition-link',
                inlineClassName: 'goto-definition-link',
                hoverMessage
            }
        };
        this.linkDecorations.set([newDecorations]);
    }
    removeLinkDecorations() {
        this.linkDecorations.clear();
    }
    isEnabled(mouseEvent, withKey) {
        return this.editor.hasModel() &&
            mouseEvent.isNoneOrSingleMouseDown &&
            (mouseEvent.target.type === 6 /* MouseTargetType.CONTENT_TEXT */) &&
            (mouseEvent.hasTriggerModifier || (withKey ? withKey.keyCodeIsTriggerKey : false)) &&
            this.languageFeaturesService.definitionProvider.has(this.editor.getModel());
    }
    findDefinition(position, token) {
        const model = this.editor.getModel();
        if (!model) {
            return Promise.resolve(null);
        }
        return getDefinitionsAtPosition(this.languageFeaturesService.definitionProvider, model, position, token);
    }
    gotoDefinition(position, openToSide) {
        this.editor.setPosition(position);
        return this.editor.invokeWithinContext((accessor) => {
            const canPeek = !openToSide && this.editor.getOption(80 /* EditorOption.definitionLinkOpensInPeek */) && !this.isInPeekEditor(accessor);
            const action = new DefinitionAction({ openToSide, openInPeek: canPeek, muteMessage: true }, { alias: '', label: '', id: '', precondition: undefined });
            return action.run(accessor, this.editor);
        });
    }
    isInPeekEditor(accessor) {
        const contextKeyService = accessor.get(IContextKeyService);
        return PeekContext.inPeekEditor.getValue(contextKeyService);
    }
    dispose() {
        this.toUnhook.dispose();
    }
};
GotoDefinitionAtPositionEditorContribution.ID = 'editor.contrib.gotodefinitionatposition';
GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES = 8;
GotoDefinitionAtPositionEditorContribution = goToDefinitionAtPosition_decorate([
    goToDefinitionAtPosition_param(1, ITextModelService),
    goToDefinitionAtPosition_param(2, ILanguageService),
    goToDefinitionAtPosition_param(3, ILanguageFeaturesService)
], GotoDefinitionAtPositionEditorContribution);

registerEditorContribution(GotoDefinitionAtPositionEditorContribution.ID, GotoDefinitionAtPositionEditorContribution);
registerThemingParticipant((theme, collector) => {
    const activeLinkForeground = theme.getColor(editorActiveLinkForeground);
    if (activeLinkForeground) {
        collector.addRule(`.monaco-editor .goto-definition-link { color: ${activeLinkForeground} !important; }`);
    }
});

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/hover/hover.css
var hover = __webpack_require__(20367);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/hover/hover.css

      
      
      
      
      
      
      
      
      

var hover_options = {};

hover_options.styleTagTransform = (styleTagTransform_default());
hover_options.setAttributes = (setAttributesWithoutAttributes_default());

      hover_options.insert = insertBySelector_default().bind(null, "head");
    
hover_options.domAPI = (styleDomAPI_default());
hover_options.insertStyleElement = (insertStyleElement_default());

var hover_update = injectStylesIntoStyleTag_default()(hover/* default */.A, hover_options);




       /* harmony default export */ const hover_hover = (hover/* default */.A && hover/* default */.A.locals ? hover/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/hover/hoverWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





const hoverWidget_$ = dom_$;
class HoverWidget extends Disposable {
    constructor() {
        super();
        this.containerDomNode = document.createElement('div');
        this.containerDomNode.className = 'monaco-hover';
        this.containerDomNode.tabIndex = 0;
        this.containerDomNode.setAttribute('role', 'tooltip');
        this.contentsDomNode = document.createElement('div');
        this.contentsDomNode.className = 'monaco-hover-content';
        this.scrollbar = this._register(new DomScrollableElement(this.contentsDomNode, {
            consumeMouseWheelIfScrollbarIsNeeded: true
        }));
        this.containerDomNode.appendChild(this.scrollbar.getDomNode());
    }
    onContentsChanged() {
        this.scrollbar.scanDomNode();
    }
}
class HoverAction extends Disposable {
    constructor(parent, actionOptions, keybindingLabel) {
        super();
        this.actionContainer = append(parent, hoverWidget_$('div.action-container'));
        this.actionContainer.setAttribute('tabindex', '0');
        this.action = append(this.actionContainer, hoverWidget_$('a.action'));
        this.action.setAttribute('role', 'button');
        if (actionOptions.iconClass) {
            append(this.action, hoverWidget_$(`span.icon.${actionOptions.iconClass}`));
        }
        const label = append(this.action, hoverWidget_$('span'));
        label.textContent = keybindingLabel ? `${actionOptions.label} (${keybindingLabel})` : actionOptions.label;
        this._register(addDisposableListener(this.actionContainer, EventType.CLICK, e => {
            e.stopPropagation();
            e.preventDefault();
            actionOptions.run(this.actionContainer);
        }));
        this._register(addDisposableListener(this.actionContainer, EventType.KEY_UP, e => {
            const event = new StandardKeyboardEvent(e);
            if (event.equals(3 /* KeyCode.Enter */)) {
                e.stopPropagation();
                e.preventDefault();
                actionOptions.run(this.actionContainer);
            }
        }));
        this.setEnabled(true);
    }
    static render(parent, actionOptions, keybindingLabel) {
        return new HoverAction(parent, actionOptions, keybindingLabel);
    }
    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');
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/hover/browser/hoverOperation.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var hoverOperation_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
var hoverOperation_asyncValues = (undefined && undefined.__asyncValues) || function (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); }
};




class HoverResult {
    constructor(value, isComplete, hasLoadingMessage) {
        this.value = value;
        this.isComplete = isComplete;
        this.hasLoadingMessage = hasLoadingMessage;
    }
}
/**
 * Computing the hover is very fine tuned.
 *
 * Suppose the hover delay is 300ms (the default). Then, when resting the mouse at an anchor:
 * - at 150ms, the async computation is triggered (i.e. semantic hover)
 *   - if async results already come in, they are not rendered yet.
 * - at 300ms, the sync computation is triggered (i.e. decorations, markers)
 *   - if there are sync or async results, they are rendered.
 * - at 900ms, if the async computation hasn't finished, a "Loading..." result is added.
 */
class HoverOperation extends Disposable {
    constructor(_editor, _computer) {
        super();
        this._editor = _editor;
        this._computer = _computer;
        this._onResult = this._register(new Emitter());
        this.onResult = this._onResult.event;
        this._firstWaitScheduler = this._register(new RunOnceScheduler(() => this._triggerAsyncComputation(), 0));
        this._secondWaitScheduler = this._register(new RunOnceScheduler(() => this._triggerSyncComputation(), 0));
        this._loadingMessageScheduler = this._register(new RunOnceScheduler(() => this._triggerLoadingMessage(), 0));
        this._state = 0 /* HoverOperationState.Idle */;
        this._asyncIterable = null;
        this._asyncIterableDone = false;
        this._result = [];
    }
    dispose() {
        if (this._asyncIterable) {
            this._asyncIterable.cancel();
            this._asyncIterable = null;
        }
        super.dispose();
    }
    get _hoverTime() {
        return this._editor.getOption(55 /* EditorOption.hover */).delay;
    }
    get _firstWaitTime() {
        return this._hoverTime / 2;
    }
    get _secondWaitTime() {
        return this._hoverTime - this._firstWaitTime;
    }
    get _loadingMessageTime() {
        return 3 * this._hoverTime;
    }
    _setState(state, fireResult = true) {
        this._state = state;
        if (fireResult) {
            this._fireResult();
        }
    }
    _triggerAsyncComputation() {
        this._setState(2 /* HoverOperationState.SecondWait */);
        this._secondWaitScheduler.schedule(this._secondWaitTime);
        if (this._computer.computeAsync) {
            this._asyncIterableDone = false;
            this._asyncIterable = createCancelableAsyncIterable(token => this._computer.computeAsync(token));
            (() => hoverOperation_awaiter(this, void 0, void 0, function* () {
                var e_1, _a;
                try {
                    try {
                        for (var _b = hoverOperation_asyncValues(this._asyncIterable), _c; _c = yield _b.next(), !_c.done;) {
                            const item = _c.value;
                            if (item) {
                                this._result.push(item);
                                this._fireResult();
                            }
                        }
                    }
                    catch (e_1_1) { e_1 = { error: e_1_1 }; }
                    finally {
                        try {
                            if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
                        }
                        finally { if (e_1) throw e_1.error; }
                    }
                    this._asyncIterableDone = true;
                    if (this._state === 3 /* HoverOperationState.WaitingForAsync */ || this._state === 4 /* HoverOperationState.WaitingForAsyncShowingLoading */) {
                        this._setState(0 /* HoverOperationState.Idle */);
                    }
                }
                catch (e) {
                    onUnexpectedError(e);
                }
            }))();
        }
        else {
            this._asyncIterableDone = true;
        }
    }
    _triggerSyncComputation() {
        if (this._computer.computeSync) {
            this._result = this._result.concat(this._computer.computeSync());
        }
        this._setState(this._asyncIterableDone ? 0 /* HoverOperationState.Idle */ : 3 /* HoverOperationState.WaitingForAsync */);
    }
    _triggerLoadingMessage() {
        if (this._state === 3 /* HoverOperationState.WaitingForAsync */) {
            this._setState(4 /* HoverOperationState.WaitingForAsyncShowingLoading */);
        }
    }
    _fireResult() {
        if (this._state === 1 /* HoverOperationState.FirstWait */ || this._state === 2 /* HoverOperationState.SecondWait */) {
            // Do not send out results before the hover time
            return;
        }
        const isComplete = (this._state === 0 /* HoverOperationState.Idle */);
        const hasLoadingMessage = (this._state === 4 /* HoverOperationState.WaitingForAsyncShowingLoading */);
        this._onResult.fire(new HoverResult(this._result.slice(0), isComplete, hasLoadingMessage));
    }
    start(mode) {
        if (mode === 0 /* HoverStartMode.Delayed */) {
            if (this._state === 0 /* HoverOperationState.Idle */) {
                this._setState(1 /* HoverOperationState.FirstWait */);
                this._firstWaitScheduler.schedule(this._firstWaitTime);
                this._loadingMessageScheduler.schedule(this._loadingMessageTime);
            }
        }
        else {
            switch (this._state) {
                case 0 /* HoverOperationState.Idle */:
                    this._triggerAsyncComputation();
                    this._secondWaitScheduler.cancel();
                    this._triggerSyncComputation();
                    break;
                case 2 /* HoverOperationState.SecondWait */:
                    this._secondWaitScheduler.cancel();
                    this._triggerSyncComputation();
                    break;
            }
        }
    }
    cancel() {
        this._firstWaitScheduler.cancel();
        this._secondWaitScheduler.cancel();
        this._loadingMessageScheduler.cancel();
        if (this._asyncIterable) {
            this._asyncIterable.cancel();
            this._asyncIterable = null;
        }
        this._result = [];
        this._setState(0 /* HoverOperationState.Idle */, false);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/hover/browser/hoverTypes.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class HoverRangeAnchor {
    constructor(priority, range) {
        this.priority = priority;
        this.range = range;
        this.type = 1 /* HoverAnchorType.Range */;
    }
    equals(other) {
        return (other.type === 1 /* HoverAnchorType.Range */ && this.range.equalsRange(other.range));
    }
    canAdoptVisibleHover(lastAnchor, showAtPosition) {
        return (lastAnchor.type === 1 /* HoverAnchorType.Range */ && showAtPosition.lineNumber === this.range.startLineNumber);
    }
}
class HoverForeignElementAnchor {
    constructor(priority, owner, range) {
        this.priority = priority;
        this.owner = owner;
        this.range = range;
        this.type = 2 /* HoverAnchorType.ForeignElement */;
    }
    equals(other) {
        return (other.type === 2 /* HoverAnchorType.ForeignElement */ && this.owner === other.owner);
    }
    canAdoptVisibleHover(lastAnchor, showAtPosition) {
        return (lastAnchor.type === 2 /* HoverAnchorType.ForeignElement */ && this.owner === lastAnchor.owner);
    }
}
const HoverParticipantRegistry = (new class HoverParticipantRegistry {
    constructor() {
        this._participants = [];
    }
    register(ctor) {
        this._participants.push(ctor);
    }
    getAll() {
        return this._participants;
    }
}());

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/snippet/browser/snippetParser.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class Scanner {
    constructor() {
        this.value = '';
        this.pos = 0;
    }
    static isDigitCharacter(ch) {
        return ch >= 48 /* CharCode.Digit0 */ && ch <= 57 /* CharCode.Digit9 */;
    }
    static isVariableCharacter(ch) {
        return ch === 95 /* CharCode.Underline */
            || (ch >= 97 /* CharCode.a */ && ch <= 122 /* CharCode.z */)
            || (ch >= 65 /* CharCode.A */ && ch <= 90 /* CharCode.Z */);
    }
    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 /* TokenType.EOF */, pos: this.pos, len: 0 };
        }
        const pos = this.pos;
        let len = 0;
        let ch = this.value.charCodeAt(pos);
        let type;
        // static types
        type = Scanner._table[ch];
        if (typeof type === 'number') {
            this.pos += 1;
            return { type, pos, len: 1 };
        }
        // number
        if (Scanner.isDigitCharacter(ch)) {
            type = 8 /* TokenType.Int */;
            do {
                len += 1;
                ch = this.value.charCodeAt(pos + len);
            } while (Scanner.isDigitCharacter(ch));
            this.pos += len;
            return { type, pos, len };
        }
        // variable name
        if (Scanner.isVariableCharacter(ch)) {
            type = 9 /* TokenType.VariableName */;
            do {
                ch = this.value.charCodeAt(pos + (++len));
            } while (Scanner.isVariableCharacter(ch) || Scanner.isDigitCharacter(ch));
            this.pos += len;
            return { type, pos, len };
        }
        // format
        type = 10 /* TokenType.Format */;
        do {
            len += 1;
            ch = this.value.charCodeAt(pos + len);
        } while (!isNaN(ch)
            && typeof Scanner._table[ch] === 'undefined' // not static token
            && !Scanner.isDigitCharacter(ch) // not number
            && !Scanner.isVariableCharacter(ch) // not variable
        );
        this.pos += len;
        return { type, pos, len };
    }
}
Scanner._table = {
    [36 /* CharCode.DollarSign */]: 0 /* TokenType.Dollar */,
    [58 /* CharCode.Colon */]: 1 /* TokenType.Colon */,
    [44 /* CharCode.Comma */]: 2 /* TokenType.Comma */,
    [123 /* CharCode.OpenCurlyBrace */]: 3 /* TokenType.CurlyOpen */,
    [125 /* CharCode.CloseCurlyBrace */]: 4 /* TokenType.CurlyClose */,
    [92 /* CharCode.Backslash */]: 5 /* TokenType.Backslash */,
    [47 /* CharCode.Slash */]: 6 /* TokenType.Forwardslash */,
    [124 /* CharCode.Pipe */]: 7 /* TokenType.Pipe */,
    [43 /* CharCode.Plus */]: 11 /* TokenType.Plus */,
    [45 /* CharCode.Dash */]: 12 /* TokenType.Dash */,
    [63 /* CharCode.QuestionMark */]: 13 /* TokenType.QuestionMark */,
};
class Marker {
    constructor() {
        this._children = [];
    }
    appendChild(child) {
        if (child instanceof Text && this._children[this._children.length - 1] instanceof Text) {
            // this and previous child are text -> merge them
            this._children[this._children.length - 1].value += child.value;
        }
        else {
            // normal adoption of child
            child.parent = this;
            this._children.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._children = newChildren;
        (function _fixParent(children, parent) {
            for (const child of children) {
                child.parent = parent;
                _fixParent(child.children, child);
            }
        })(others, parent);
    }
    get children() {
        return this._children;
    }
    get snippet() {
        let candidate = this;
        while (true) {
            if (!candidate) {
                return undefined;
            }
            if (candidate instanceof TextmateSnippet) {
                return candidate;
            }
            candidate = candidate.parent;
        }
    }
    toString() {
        return this.children.reduce((prev, cur) => prev + cur.toString(), '');
    }
    len() {
        return 0;
    }
}
class Text extends Marker {
    constructor(value) {
        super();
        this.value = value;
    }
    toString() {
        return this.value;
    }
    len() {
        return this.value.length;
    }
    clone() {
        return new Text(this.value);
    }
}
class TransformableMarker extends Marker {
}
class Placeholder extends TransformableMarker {
    constructor(index) {
        super();
        this.index = index;
    }
    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;
        }
    }
    get isFinalTabstop() {
        return this.index === 0;
    }
    get choice() {
        return this._children.length === 1 && this._children[0] instanceof Choice
            ? this._children[0]
            : undefined;
    }
    clone() {
        const ret = new Placeholder(this.index);
        if (this.transform) {
            ret.transform = this.transform.clone();
        }
        ret._children = this.children.map(child => child.clone());
        return ret;
    }
}
class Choice extends Marker {
    constructor() {
        super(...arguments);
        this.options = [];
    }
    appendChild(marker) {
        if (marker instanceof Text) {
            marker.parent = this;
            this.options.push(marker);
        }
        return this;
    }
    toString() {
        return this.options[0].value;
    }
    len() {
        return this.options[0].len();
    }
    clone() {
        const ret = new Choice();
        this.options.forEach(ret.appendChild, ret);
        return ret;
    }
}
class Transform extends Marker {
    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._replace(Array.prototype.slice.call(arguments, 0, -2));
        });
        // when the regex didn't match and when the transform has
        // else branches, then run those
        if (!didMatch && this._children.some(child => child instanceof FormatString && Boolean(child.elseValue))) {
            ret = this._replace([]);
        }
        return ret;
    }
    _replace(groups) {
        let ret = '';
        for (const marker of this._children) {
            if (marker instanceof FormatString) {
                let value = groups[marker.index] || '';
                value = marker.resolve(value);
                ret += value;
            }
            else {
                ret += marker.toString();
            }
        }
        return ret;
    }
    toString() {
        return '';
    }
    clone() {
        const ret = new Transform();
        ret.regexp = new RegExp(this.regexp.source, '' + (this.regexp.ignoreCase ? 'i' : '') + (this.regexp.global ? 'g' : ''));
        ret._children = this.children.map(child => child.clone());
        return ret;
    }
}
class FormatString extends Marker {
    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._toPascalCase(value);
        }
        else if (this.shorthandName === 'camelcase') {
            return !value ? '' : this._toCamelCase(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 || '';
        }
    }
    _toPascalCase(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('');
    }
    _toCamelCase(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('');
    }
    clone() {
        const ret = new FormatString(this.index, this.shorthandName, this.ifValue, this.elseValue);
        return ret;
    }
}
class Variable extends TransformableMarker {
    constructor(name) {
        super();
        this.name = name;
    }
    resolve(resolver) {
        let value = resolver.resolve(this);
        if (this.transform) {
            value = this.transform.resolve(value || '');
        }
        if (value !== undefined) {
            this._children = [new Text(value)];
            return true;
        }
        return false;
    }
    clone() {
        const ret = new Variable(this.name);
        if (this.transform) {
            ret.transform = this.transform.clone();
        }
        ret._children = this.children.map(child => child.clone());
        return ret;
    }
}
function walk(marker, visitor) {
    const stack = [...marker];
    while (stack.length > 0) {
        const marker = stack.shift();
        const recurse = visitor(marker);
        if (!recurse) {
            break;
        }
        stack.unshift(...marker.children);
    }
}
class TextmateSnippet extends Marker {
    get placeholderInfo() {
        if (!this._placeholders) {
            // fill in placeholders
            const all = [];
            let last;
            this.walk(function (candidate) {
                if (candidate instanceof Placeholder) {
                    all.push(candidate);
                    last = !last || last.index < candidate.index ? candidate : last;
                }
                return true;
            });
            this._placeholders = { all, last };
        }
        return this._placeholders;
    }
    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], marker => {
            ret += marker.len();
            return true;
        });
        return ret;
    }
    enclosingPlaceholders(placeholder) {
        const ret = [];
        let { parent } = placeholder;
        while (parent) {
            if (parent instanceof Placeholder) {
                ret.push(parent);
            }
            parent = parent.parent;
        }
        return ret;
    }
    resolveVariables(resolver) {
        this.walk(candidate => {
            if (candidate instanceof Variable) {
                if (candidate.resolve(resolver)) {
                    this._placeholders = undefined;
                }
            }
            return true;
        });
        return this;
    }
    appendChild(child) {
        this._placeholders = undefined;
        return super.appendChild(child);
    }
    replace(child, others) {
        this._placeholders = undefined;
        return super.replace(child, others);
    }
    clone() {
        const ret = new TextmateSnippet();
        this._children = this.children.map(child => child.clone());
        return ret;
    }
    walk(visitor) {
        walk(this.children, visitor);
    }
}
class SnippetParser {
    constructor() {
        this._scanner = new Scanner();
        this._token = { type: 14 /* TokenType.EOF */, pos: 0, len: 0 };
    }
    static escape(value) {
        return value.replace(/\$|}|\\/g, '\\$&');
    }
    static guessNeedsClipboard(template) {
        return /\${?CLIPBOARD/.test(template);
    }
    parse(value, insertFinalTabstop, enforceFinalTabstop) {
        const snippet = new TextmateSnippet();
        this.parseFragment(value, snippet);
        this.ensureFinalTabstop(snippet, enforceFinalTabstop !== null && enforceFinalTabstop !== void 0 ? enforceFinalTabstop : false, insertFinalTabstop !== null && insertFinalTabstop !== void 0 ? insertFinalTabstop : false);
        return snippet;
    }
    parseFragment(value, snippet) {
        const offset = snippet.children.length;
        this._scanner.text(value);
        this._token = this._scanner.next();
        while (this._parse(snippet)) {
            // nothing
        }
        // fill in values for placeholders. the first placeholder of an index
        // that has a value defines the value for all placeholders with that index
        const placeholderDefaultValues = new Map();
        const incompletePlaceholders = [];
        snippet.walk(marker => {
            if (marker instanceof Placeholder) {
                if (marker.isFinalTabstop) {
                    placeholderDefaultValues.set(0, undefined);
                }
                else if (!placeholderDefaultValues.has(marker.index) && marker.children.length > 0) {
                    placeholderDefaultValues.set(marker.index, marker.children);
                }
                else {
                    incompletePlaceholders.push(marker);
                }
            }
            return true;
        });
        for (const placeholder of incompletePlaceholders) {
            const defaultValues = placeholderDefaultValues.get(placeholder.index);
            if (defaultValues) {
                const clone = new Placeholder(placeholder.index);
                clone.transform = placeholder.transform;
                for (const child of defaultValues) {
                    clone.appendChild(child.clone());
                }
                snippet.replace(placeholder, [clone]);
            }
        }
        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) {
                // the snippet uses placeholders but has no
                // final tabstop defined -> insert at the end
                snippet.appendChild(new Placeholder(0));
            }
        }
    }
    _accept(type, value) {
        if (type === undefined || this._token.type === type) {
            const ret = !value ? true : this._scanner.tokenText(this._token);
            this._token = this._scanner.next();
            return ret;
        }
        return false;
    }
    _backTo(token) {
        this._scanner.pos = token.pos + token.len;
        this._token = token;
        return false;
    }
    _until(type) {
        const start = this._token;
        while (this._token.type !== type) {
            if (this._token.type === 14 /* TokenType.EOF */) {
                return false;
            }
            else if (this._token.type === 5 /* TokenType.Backslash */) {
                const nextToken = this._scanner.next();
                if (nextToken.type !== 0 /* TokenType.Dollar */
                    && nextToken.type !== 4 /* TokenType.CurlyClose */
                    && nextToken.type !== 5 /* TokenType.Backslash */) {
                    return false;
                }
            }
            this._token = this._scanner.next();
        }
        const value = this._scanner.value.substring(start.pos, this._token.pos).replace(/\\(\$|}|\\)/g, '$1');
        this._token = this._scanner.next();
        return value;
    }
    _parse(marker) {
        return this._parseEscaped(marker)
            || this._parseTabstopOrVariableName(marker)
            || this._parseComplexPlaceholder(marker)
            || this._parseComplexVariable(marker)
            || this._parseAnything(marker);
    }
    // \$, \\, \} -> just text
    _parseEscaped(marker) {
        let value;
        if (value = this._accept(5 /* TokenType.Backslash */, true)) {
            // saw a backslash, append escaped token or that backslash
            value = this._accept(0 /* TokenType.Dollar */, true)
                || this._accept(4 /* TokenType.CurlyClose */, true)
                || this._accept(5 /* TokenType.Backslash */, true)
                || value;
            marker.appendChild(new Text(value));
            return true;
        }
        return false;
    }
    // $foo -> variable, $1 -> tabstop
    _parseTabstopOrVariableName(parent) {
        let value;
        const token = this._token;
        const match = this._accept(0 /* TokenType.Dollar */)
            && (value = this._accept(9 /* TokenType.VariableName */, true) || this._accept(8 /* TokenType.Int */, true));
        if (!match) {
            return this._backTo(token);
        }
        parent.appendChild(/^\d+$/.test(value)
            ? new Placeholder(Number(value))
            : new Variable(value));
        return true;
    }
    // ${1:<children>}, ${1} -> placeholder
    _parseComplexPlaceholder(parent) {
        let index;
        const token = this._token;
        const match = this._accept(0 /* TokenType.Dollar */)
            && this._accept(3 /* TokenType.CurlyOpen */)
            && (index = this._accept(8 /* TokenType.Int */, true));
        if (!match) {
            return this._backTo(token);
        }
        const placeholder = new Placeholder(Number(index));
        if (this._accept(1 /* TokenType.Colon */)) {
            // ${1:<children>}
            while (true) {
                // ...} -> done
                if (this._accept(4 /* TokenType.CurlyClose */)) {
                    parent.appendChild(placeholder);
                    return true;
                }
                if (this._parse(placeholder)) {
                    continue;
                }
                // fallback
                parent.appendChild(new Text('${' + index + ':'));
                placeholder.children.forEach(parent.appendChild, parent);
                return true;
            }
        }
        else if (placeholder.index > 0 && this._accept(7 /* TokenType.Pipe */)) {
            // ${1|one,two,three|}
            const choice = new Choice();
            while (true) {
                if (this._parseChoiceElement(choice)) {
                    if (this._accept(2 /* TokenType.Comma */)) {
                        // opt, -> more
                        continue;
                    }
                    if (this._accept(7 /* TokenType.Pipe */)) {
                        placeholder.appendChild(choice);
                        if (this._accept(4 /* TokenType.CurlyClose */)) {
                            // ..|} -> done
                            parent.appendChild(placeholder);
                            return true;
                        }
                    }
                }
                this._backTo(token);
                return false;
            }
        }
        else if (this._accept(6 /* TokenType.Forwardslash */)) {
            // ${1/<regex>/<format>/<options>}
            if (this._parseTransform(placeholder)) {
                parent.appendChild(placeholder);
                return true;
            }
            this._backTo(token);
            return false;
        }
        else if (this._accept(4 /* TokenType.CurlyClose */)) {
            // ${1}
            parent.appendChild(placeholder);
            return true;
        }
        else {
            // ${1 <- missing curly or colon
            return this._backTo(token);
        }
    }
    _parseChoiceElement(parent) {
        const token = this._token;
        const values = [];
        while (true) {
            if (this._token.type === 2 /* TokenType.Comma */ || this._token.type === 7 /* TokenType.Pipe */) {
                break;
            }
            let value;
            if (value = this._accept(5 /* TokenType.Backslash */, true)) {
                // \, \|, or \\
                value = this._accept(2 /* TokenType.Comma */, true)
                    || this._accept(7 /* TokenType.Pipe */, true)
                    || this._accept(5 /* TokenType.Backslash */, true)
                    || value;
            }
            else {
                value = this._accept(undefined, true);
            }
            if (!value) {
                // EOF
                this._backTo(token);
                return false;
            }
            values.push(value);
        }
        if (values.length === 0) {
            this._backTo(token);
            return false;
        }
        parent.appendChild(new Text(values.join('')));
        return true;
    }
    // ${foo:<children>}, ${foo} -> variable
    _parseComplexVariable(parent) {
        let name;
        const token = this._token;
        const match = this._accept(0 /* TokenType.Dollar */)
            && this._accept(3 /* TokenType.CurlyOpen */)
            && (name = this._accept(9 /* TokenType.VariableName */, true));
        if (!match) {
            return this._backTo(token);
        }
        const variable = new Variable(name);
        if (this._accept(1 /* TokenType.Colon */)) {
            // ${foo:<children>}
            while (true) {
                // ...} -> done
                if (this._accept(4 /* TokenType.CurlyClose */)) {
                    parent.appendChild(variable);
                    return true;
                }
                if (this._parse(variable)) {
                    continue;
                }
                // fallback
                parent.appendChild(new Text('${' + name + ':'));
                variable.children.forEach(parent.appendChild, parent);
                return true;
            }
        }
        else if (this._accept(6 /* TokenType.Forwardslash */)) {
            // ${foo/<regex>/<format>/<options>}
            if (this._parseTransform(variable)) {
                parent.appendChild(variable);
                return true;
            }
            this._backTo(token);
            return false;
        }
        else if (this._accept(4 /* TokenType.CurlyClose */)) {
            // ${foo}
            parent.appendChild(variable);
            return true;
        }
        else {
            // ${foo <- missing curly or colon
            return this._backTo(token);
        }
    }
    _parseTransform(parent) {
        // ...<regex>/<format>/<options>}
        const transform = new Transform();
        let regexValue = '';
        let regexOptions = '';
        // (1) /regex
        while (true) {
            if (this._accept(6 /* TokenType.Forwardslash */)) {
                break;
            }
            let escaped;
            if (escaped = this._accept(5 /* TokenType.Backslash */, true)) {
                escaped = this._accept(6 /* TokenType.Forwardslash */, true) || escaped;
                regexValue += escaped;
                continue;
            }
            if (this._token.type !== 14 /* TokenType.EOF */) {
                regexValue += this._accept(undefined, true);
                continue;
            }
            return false;
        }
        // (2) /format
        while (true) {
            if (this._accept(6 /* TokenType.Forwardslash */)) {
                break;
            }
            let escaped;
            if (escaped = this._accept(5 /* TokenType.Backslash */, true)) {
                escaped = this._accept(5 /* TokenType.Backslash */, true) || this._accept(6 /* TokenType.Forwardslash */, true) || escaped;
                transform.appendChild(new Text(escaped));
                continue;
            }
            if (this._parseFormatString(transform) || this._parseAnything(transform)) {
                continue;
            }
            return false;
        }
        // (3) /option
        while (true) {
            if (this._accept(4 /* TokenType.CurlyClose */)) {
                break;
            }
            if (this._token.type !== 14 /* TokenType.EOF */) {
                regexOptions += this._accept(undefined, true);
                continue;
            }
            return false;
        }
        try {
            transform.regexp = new RegExp(regexValue, regexOptions);
        }
        catch (e) {
            // invalid regexp
            return false;
        }
        parent.transform = transform;
        return true;
    }
    _parseFormatString(parent) {
        const token = this._token;
        if (!this._accept(0 /* TokenType.Dollar */)) {
            return false;
        }
        let complex = false;
        if (this._accept(3 /* TokenType.CurlyOpen */)) {
            complex = true;
        }
        const index = this._accept(8 /* TokenType.Int */, true);
        if (!index) {
            this._backTo(token);
            return false;
        }
        else if (!complex) {
            // $1
            parent.appendChild(new FormatString(Number(index)));
            return true;
        }
        else if (this._accept(4 /* TokenType.CurlyClose */)) {
            // ${1}
            parent.appendChild(new FormatString(Number(index)));
            return true;
        }
        else if (!this._accept(1 /* TokenType.Colon */)) {
            this._backTo(token);
            return false;
        }
        if (this._accept(6 /* TokenType.Forwardslash */)) {
            // ${1:/upcase}
            const shorthand = this._accept(9 /* TokenType.VariableName */, true);
            if (!shorthand || !this._accept(4 /* TokenType.CurlyClose */)) {
                this._backTo(token);
                return false;
            }
            else {
                parent.appendChild(new FormatString(Number(index), shorthand));
                return true;
            }
        }
        else if (this._accept(11 /* TokenType.Plus */)) {
            // ${1:+<if>}
            const ifValue = this._until(4 /* TokenType.CurlyClose */);
            if (ifValue) {
                parent.appendChild(new FormatString(Number(index), undefined, ifValue, undefined));
                return true;
            }
        }
        else if (this._accept(12 /* TokenType.Dash */)) {
            // ${2:-<else>}
            const elseValue = this._until(4 /* TokenType.CurlyClose */);
            if (elseValue) {
                parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue));
                return true;
            }
        }
        else if (this._accept(13 /* TokenType.QuestionMark */)) {
            // ${2:?<if>:<else>}
            const ifValue = this._until(1 /* TokenType.Colon */);
            if (ifValue) {
                const elseValue = this._until(4 /* TokenType.CurlyClose */);
                if (elseValue) {
                    parent.appendChild(new FormatString(Number(index), undefined, ifValue, elseValue));
                    return true;
                }
            }
        }
        else {
            // ${1:<else>}
            const elseValue = this._until(4 /* TokenType.CurlyClose */);
            if (elseValue) {
                parent.appendChild(new FormatString(Number(index), undefined, undefined, elseValue));
                return true;
            }
        }
        this._backTo(token);
        return false;
    }
    _parseAnything(marker) {
        if (this._token.type !== 14 /* TokenType.EOF */) {
            marker.appendChild(new Text(this._scanner.tokenText(this._token)));
            this._accept(undefined);
            return true;
        }
        return false;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/findinput/replaceInput.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/








const replaceInput_NLS_DEFAULT_LABEL = localize('defaultLabel', "input");
const NLS_PRESERVE_CASE_LABEL = localize('label.preserveCaseToggle', "Preserve Case");
class PreserveCaseToggle extends Toggle {
    constructor(opts) {
        super({
            // TODO: does this need its own icon?
            icon: Codicon.preserveCase,
            title: NLS_PRESERVE_CASE_LABEL + opts.appendTitle,
            isChecked: opts.isChecked,
            inputActiveOptionBorder: opts.inputActiveOptionBorder,
            inputActiveOptionForeground: opts.inputActiveOptionForeground,
            inputActiveOptionBackground: opts.inputActiveOptionBackground
        });
    }
}
class ReplaceInput extends Widget {
    constructor(parent, contextViewProvider, _showOptionButtons, options) {
        super();
        this._showOptionButtons = _showOptionButtons;
        this.fixFocusOnOptionClickEnabled = true;
        this.cachedOptionsWidth = 0;
        this._onDidOptionChange = this._register(new Emitter());
        this.onDidOptionChange = this._onDidOptionChange.event;
        this._onKeyDown = this._register(new Emitter());
        this.onKeyDown = this._onKeyDown.event;
        this._onMouseDown = this._register(new Emitter());
        this._onInput = this._register(new Emitter());
        this._onKeyUp = this._register(new Emitter());
        this._onPreserveCaseKeyDown = this._register(new Emitter());
        this.onPreserveCaseKeyDown = this._onPreserveCaseKeyDown.event;
        this.contextViewProvider = contextViewProvider;
        this.placeholder = options.placeholder || '';
        this.validation = options.validation;
        this.label = options.label || replaceInput_NLS_DEFAULT_LABEL;
        this.inputActiveOptionBorder = options.inputActiveOptionBorder;
        this.inputActiveOptionForeground = options.inputActiveOptionForeground;
        this.inputActiveOptionBackground = options.inputActiveOptionBackground;
        this.inputBackground = options.inputBackground;
        this.inputForeground = options.inputForeground;
        this.inputBorder = options.inputBorder;
        this.inputValidationInfoBorder = options.inputValidationInfoBorder;
        this.inputValidationInfoBackground = options.inputValidationInfoBackground;
        this.inputValidationInfoForeground = options.inputValidationInfoForeground;
        this.inputValidationWarningBorder = options.inputValidationWarningBorder;
        this.inputValidationWarningBackground = options.inputValidationWarningBackground;
        this.inputValidationWarningForeground = options.inputValidationWarningForeground;
        this.inputValidationErrorBorder = options.inputValidationErrorBorder;
        this.inputValidationErrorBackground = options.inputValidationErrorBackground;
        this.inputValidationErrorForeground = options.inputValidationErrorForeground;
        const appendPreserveCaseLabel = options.appendPreserveCaseLabel || '';
        const history = options.history || [];
        const flexibleHeight = !!options.flexibleHeight;
        const flexibleWidth = !!options.flexibleWidth;
        const flexibleMaxHeight = options.flexibleMaxHeight;
        this.domNode = document.createElement('div');
        this.domNode.classList.add('monaco-findInput');
        this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
            ariaLabel: this.label || '',
            placeholder: this.placeholder || '',
            validationOptions: {
                validation: this.validation
            },
            inputBackground: this.inputBackground,
            inputForeground: this.inputForeground,
            inputBorder: this.inputBorder,
            inputValidationInfoBackground: this.inputValidationInfoBackground,
            inputValidationInfoForeground: this.inputValidationInfoForeground,
            inputValidationInfoBorder: this.inputValidationInfoBorder,
            inputValidationWarningBackground: this.inputValidationWarningBackground,
            inputValidationWarningForeground: this.inputValidationWarningForeground,
            inputValidationWarningBorder: this.inputValidationWarningBorder,
            inputValidationErrorBackground: this.inputValidationErrorBackground,
            inputValidationErrorForeground: this.inputValidationErrorForeground,
            inputValidationErrorBorder: this.inputValidationErrorBorder,
            history,
            showHistoryHint: options.showHistoryHint,
            flexibleHeight,
            flexibleWidth,
            flexibleMaxHeight
        }));
        this.preserveCase = this._register(new PreserveCaseToggle({
            appendTitle: appendPreserveCaseLabel,
            isChecked: false,
            inputActiveOptionBorder: this.inputActiveOptionBorder,
            inputActiveOptionForeground: this.inputActiveOptionForeground,
            inputActiveOptionBackground: this.inputActiveOptionBackground,
        }));
        this._register(this.preserveCase.onChange(viaKeyboard => {
            this._onDidOptionChange.fire(viaKeyboard);
            if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
                this.inputBox.focus();
            }
            this.validate();
        }));
        this._register(this.preserveCase.onKeyDown(e => {
            this._onPreserveCaseKeyDown.fire(e);
        }));
        if (this._showOptionButtons) {
            this.cachedOptionsWidth = this.preserveCase.width();
        }
        else {
            this.cachedOptionsWidth = 0;
        }
        // Arrow-Key support to navigate between options
        const indexes = [this.preserveCase.domNode];
        this.onkeydown(this.domNode, (event) => {
            if (event.equals(15 /* KeyCode.LeftArrow */) || event.equals(17 /* KeyCode.RightArrow */) || event.equals(9 /* KeyCode.Escape */)) {
                const index = indexes.indexOf(document.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();
                    }
                    EventHelper.stop(event, true);
                }
            }
        });
        const controls = document.createElement('div');
        controls.className = 'controls';
        controls.style.display = this._showOptionButtons ? 'block' : 'none';
        controls.appendChild(this.preserveCase.domNode);
        this.domNode.appendChild(controls);
        parent === null || parent === void 0 ? void 0 : parent.appendChild(this.domNode);
        this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
        this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
        this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
        this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
    }
    enable() {
        this.domNode.classList.remove('disabled');
        this.inputBox.enable();
        this.preserveCase.enable();
    }
    disable() {
        this.domNode.classList.add('disabled');
        this.inputBox.disable();
        this.preserveCase.disable();
    }
    setEnabled(enabled) {
        if (enabled) {
            this.enable();
        }
        else {
            this.disable();
        }
    }
    style(styles) {
        this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
        this.inputActiveOptionForeground = styles.inputActiveOptionForeground;
        this.inputActiveOptionBackground = styles.inputActiveOptionBackground;
        this.inputBackground = styles.inputBackground;
        this.inputForeground = styles.inputForeground;
        this.inputBorder = styles.inputBorder;
        this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
        this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
        this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
        this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
        this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
        this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
        this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
        this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
        this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
        this.applyStyles();
    }
    applyStyles() {
        if (this.domNode) {
            const toggleStyles = {
                inputActiveOptionBorder: this.inputActiveOptionBorder,
                inputActiveOptionForeground: this.inputActiveOptionForeground,
                inputActiveOptionBackground: this.inputActiveOptionBackground,
            };
            this.preserveCase.style(toggleStyles);
            const inputBoxStyles = {
                inputBackground: this.inputBackground,
                inputForeground: this.inputForeground,
                inputBorder: this.inputBorder,
                inputValidationInfoBackground: this.inputValidationInfoBackground,
                inputValidationInfoForeground: this.inputValidationInfoForeground,
                inputValidationInfoBorder: this.inputValidationInfoBorder,
                inputValidationWarningBackground: this.inputValidationWarningBackground,
                inputValidationWarningForeground: this.inputValidationWarningForeground,
                inputValidationWarningBorder: this.inputValidationWarningBorder,
                inputValidationErrorBackground: this.inputValidationErrorBackground,
                inputValidationErrorForeground: this.inputValidationErrorForeground,
                inputValidationErrorBorder: this.inputValidationErrorBorder
            };
            this.inputBox.style(inputBoxStyles);
        }
    }
    select() {
        this.inputBox.select();
    }
    focus() {
        this.inputBox.focus();
    }
    getPreserveCase() {
        return this.preserveCase.checked;
    }
    setPreserveCase(value) {
        this.preserveCase.checked = value;
    }
    focusOnPreserve() {
        this.preserveCase.focus();
    }
    validate() {
        if (this.inputBox) {
            this.inputBox.validate();
        }
    }
    set width(newWidth) {
        this.inputBox.paddingRight = this.cachedOptionsWidth;
        this.inputBox.width = newWidth;
        this.domNode.style.width = newWidth + 'px';
    }
    dispose() {
        super.dispose();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/history/browser/contextScopedHistoryWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var contextScopedHistoryWidget_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var contextScopedHistoryWidget_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};






const historyNavigationVisible = new RawContextKey('suggestWidgetVisible', false, localize('suggestWidgetVisible', "Whether suggestion are visible"));
const HistoryNavigationWidgetFocusContext = 'historyNavigationWidgetFocus';
const HistoryNavigationForwardsEnablementContext = 'historyNavigationForwardsEnabled';
const HistoryNavigationBackwardsEnablementContext = 'historyNavigationBackwardsEnabled';
let lastFocusedWidget = undefined;
const widgets = [];
function registerAndCreateHistoryNavigationContext(contextKeyService, widget) {
    if (widgets.includes(widget)) {
        throw new Error('Cannot register the same widget multiple times');
    }
    widgets.push(widget);
    const disposableStore = new DisposableStore();
    const scopedContextKeyService = disposableStore.add(contextKeyService.createScoped(widget.element));
    const historyNavigationWidgetFocus = new RawContextKey(HistoryNavigationWidgetFocusContext, false).bindTo(scopedContextKeyService);
    const historyNavigationForwardsEnablement = new RawContextKey(HistoryNavigationForwardsEnablementContext, true).bindTo(scopedContextKeyService);
    const historyNavigationBackwardsEnablement = new RawContextKey(HistoryNavigationBackwardsEnablementContext, true).bindTo(scopedContextKeyService);
    const onDidFocus = () => {
        historyNavigationWidgetFocus.set(true);
        lastFocusedWidget = widget;
    };
    const onDidBlur = () => {
        historyNavigationWidgetFocus.set(false);
        if (lastFocusedWidget === widget) {
            lastFocusedWidget = undefined;
        }
    };
    // Check for currently being focused
    if (widget.element === document.activeElement) {
        onDidFocus();
    }
    disposableStore.add(widget.onDidFocus(() => onDidFocus()));
    disposableStore.add(widget.onDidBlur(() => onDidBlur()));
    disposableStore.add(toDisposable(() => {
        widgets.splice(widgets.indexOf(widget), 1);
        onDidBlur();
    }));
    return {
        scopedContextKeyService,
        historyNavigationForwardsEnablement,
        historyNavigationBackwardsEnablement,
        dispose() {
            disposableStore.dispose();
        }
    };
}
let ContextScopedFindInput = class ContextScopedFindInput extends FindInput {
    constructor(container, contextViewProvider, options, contextKeyService, showFindOptions = false) {
        super(container, contextViewProvider, showFindOptions, options);
        this._register(registerAndCreateHistoryNavigationContext(contextKeyService, this.inputBox));
    }
};
ContextScopedFindInput = contextScopedHistoryWidget_decorate([
    contextScopedHistoryWidget_param(3, IContextKeyService)
], ContextScopedFindInput);

let ContextScopedReplaceInput = class ContextScopedReplaceInput extends ReplaceInput {
    constructor(container, contextViewProvider, options, contextKeyService, showReplaceOptions = false) {
        super(container, contextViewProvider, showReplaceOptions, options);
        this._register(registerAndCreateHistoryNavigationContext(contextKeyService, this.inputBox));
    }
};
ContextScopedReplaceInput = contextScopedHistoryWidget_decorate([
    contextScopedHistoryWidget_param(3, IContextKeyService)
], ContextScopedReplaceInput);

KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: 'history.showPrevious',
    weight: 200 /* KeybindingWeight.WorkbenchContrib */,
    when: ContextKeyExpr.and(ContextKeyExpr.has(HistoryNavigationWidgetFocusContext), ContextKeyExpr.equals(HistoryNavigationBackwardsEnablementContext, true), historyNavigationVisible.isEqualTo(false)),
    primary: 16 /* KeyCode.UpArrow */,
    secondary: [512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */],
    handler: (accessor) => {
        if (lastFocusedWidget) {
            lastFocusedWidget.showPreviousValue();
        }
    }
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
    id: 'history.showNext',
    weight: 200 /* KeybindingWeight.WorkbenchContrib */,
    when: ContextKeyExpr.and(ContextKeyExpr.has(HistoryNavigationWidgetFocusContext), ContextKeyExpr.equals(HistoryNavigationForwardsEnablementContext, true), historyNavigationVisible.isEqualTo(false)),
    primary: 18 /* KeyCode.DownArrow */,
    secondary: [512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */],
    handler: (accessor) => {
        if (lastFocusedWidget) {
            lastFocusedWidget.showNextValue();
        }
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggest.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var suggest_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};

















const suggest_Context = {
    Visible: historyNavigationVisible,
    HasFocusedSuggestion: new RawContextKey('suggestWidgetHasFocusedSuggestion', false, localize('suggestWidgetHasSelection', "Whether any suggestion is focused")),
    DetailsVisible: new RawContextKey('suggestWidgetDetailsVisible', false, localize('suggestWidgetDetailsVisible', "Whether suggestion details are visible")),
    MultipleSuggestions: new RawContextKey('suggestWidgetMultipleSuggestions', false, localize('suggestWidgetMultipleSuggestions', "Whether there are multiple suggestions to pick from")),
    MakesTextEdit: new RawContextKey('suggestionMakesTextEdit', true, localize('suggestionMakesTextEdit', "Whether inserting the current suggestion yields in a change or has everything already been typed")),
    AcceptSuggestionsOnEnter: new RawContextKey('acceptSuggestionOnEnter', true, localize('acceptSuggestionOnEnter', "Whether suggestions are inserted when pressing Enter")),
    HasInsertAndReplaceRange: new RawContextKey('suggestionHasInsertAndReplaceRange', false, localize('suggestionHasInsertAndReplaceRange', "Whether the current suggestion has insert and replace behaviour")),
    InsertMode: new RawContextKey('suggestionInsertMode', undefined, { type: 'string', description: localize('suggestionInsertMode', "Whether the default behaviour is to insert or replace") }),
    CanResolve: new RawContextKey('suggestionCanResolve', false, localize('suggestionCanResolve', "Whether the current suggestion supports to resolve further details")),
};
const suggestWidgetStatusbarMenu = new MenuId('suggestWidgetStatusBar');
class CompletionItem {
    constructor(position, completion, container, provider) {
        this.position = position;
        this.completion = completion;
        this.container = container;
        this.provider = provider;
        // validation
        this.isInvalid = false;
        // sorting, filtering
        this.score = FuzzyScore.Default;
        this.distance = 0;
        this.textLabel = typeof completion.label === 'string'
            ? completion.label
            : completion.label.label;
        // ensure lower-variants (perf)
        this.labelLow = this.textLabel.toLowerCase();
        // validate label
        this.isInvalid = !this.textLabel;
        this.sortTextLow = completion.sortText && completion.sortText.toLowerCase();
        this.filterTextLow = completion.filterText && completion.filterText.toLowerCase();
        this.extensionId = completion.extensionId;
        // normalize ranges
        if (Range.isIRange(completion.range)) {
            this.editStart = new Position(completion.range.startLineNumber, completion.range.startColumn);
            this.editInsertEnd = new Position(completion.range.endLineNumber, completion.range.endColumn);
            this.editReplaceEnd = new Position(completion.range.endLineNumber, completion.range.endColumn);
            // validate range
            this.isInvalid = this.isInvalid
                || Range.spansMultipleLines(completion.range) || completion.range.startLineNumber !== position.lineNumber;
        }
        else {
            this.editStart = new Position(completion.range.insert.startLineNumber, completion.range.insert.startColumn);
            this.editInsertEnd = new Position(completion.range.insert.endLineNumber, completion.range.insert.endColumn);
            this.editReplaceEnd = new Position(completion.range.replace.endLineNumber, completion.range.replace.endColumn);
            // validate ranges
            this.isInvalid = this.isInvalid
                || Range.spansMultipleLines(completion.range.insert) || Range.spansMultipleLines(completion.range.replace)
                || completion.range.insert.startLineNumber !== position.lineNumber || completion.range.replace.startLineNumber !== position.lineNumber
                || completion.range.insert.startColumn !== completion.range.replace.startColumn;
        }
        // create the suggestion resolver
        if (typeof provider.resolveCompletionItem !== 'function') {
            this._resolveCache = Promise.resolve();
            this._isResolved = true;
        }
    }
    // ---- resolving
    get isResolved() {
        return !!this._isResolved;
    }
    resolve(token) {
        return suggest_awaiter(this, void 0, void 0, function* () {
            if (!this._resolveCache) {
                const sub = token.onCancellationRequested(() => {
                    this._resolveCache = undefined;
                    this._isResolved = false;
                });
                this._resolveCache = Promise.resolve(this.provider.resolveCompletionItem(this.completion, token)).then(value => {
                    Object.assign(this.completion, value);
                    this._isResolved = true;
                    sub.dispose();
                }, err => {
                    if (isCancellationError(err)) {
                        // the IPC queue will reject the request with the
                        // cancellation error -> reset cached
                        this._resolveCache = undefined;
                        this._isResolved = false;
                    }
                });
            }
            return this._resolveCache;
        });
    }
}
class CompletionOptions {
    constructor(snippetSortOrder = 2 /* SnippetSortOrder.Bottom */, kindFilter = new Set(), providerFilter = new Set(), showDeprecated = true) {
        this.snippetSortOrder = snippetSortOrder;
        this.kindFilter = kindFilter;
        this.providerFilter = providerFilter;
        this.showDeprecated = showDeprecated;
    }
}
CompletionOptions.default = new CompletionOptions();
let _snippetSuggestSupport;
function getSnippetSuggestSupport() {
    return _snippetSuggestSupport;
}
class CompletionItemModel {
    constructor(items, needsClipboard, durations, disposable) {
        this.items = items;
        this.needsClipboard = needsClipboard;
        this.durations = durations;
        this.disposable = disposable;
    }
}
function provideSuggestionItems(registry, model, position, options = CompletionOptions.default, context = { triggerKind: 0 /* languages.CompletionTriggerKind.Invoke */ }, token = CancellationToken.None) {
    return suggest_awaiter(this, void 0, void 0, function* () {
        const sw = new StopWatch(true);
        position = position.clone();
        const word = model.getWordAtPosition(position);
        const defaultReplaceRange = word ? new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn) : Range.fromPositions(position);
        const defaultRange = { replace: defaultReplaceRange, insert: defaultReplaceRange.setEndPosition(position.lineNumber, position.column) };
        const result = [];
        const disposables = new DisposableStore();
        const durations = [];
        let needsClipboard = false;
        const onCompletionList = (provider, container, sw) => {
            var _a, _b, _c;
            let didAddResult = false;
            if (!container) {
                return didAddResult;
            }
            for (const suggestion of container.suggestions) {
                if (!options.kindFilter.has(suggestion.kind)) {
                    // skip if not showing deprecated suggestions
                    if (!options.showDeprecated && ((_a = suggestion === null || suggestion === void 0 ? void 0 : suggestion.tags) === null || _a === void 0 ? void 0 : _a.includes(1 /* languages.CompletionItemTag.Deprecated */))) {
                        continue;
                    }
                    // fill in default range when missing
                    if (!suggestion.range) {
                        suggestion.range = defaultRange;
                    }
                    // fill in default sortText when missing
                    if (!suggestion.sortText) {
                        suggestion.sortText = typeof suggestion.label === 'string' ? suggestion.label : suggestion.label.label;
                    }
                    if (!needsClipboard && suggestion.insertTextRules && suggestion.insertTextRules & 4 /* languages.CompletionItemInsertTextRule.InsertAsSnippet */) {
                        needsClipboard = SnippetParser.guessNeedsClipboard(suggestion.insertText);
                    }
                    result.push(new CompletionItem(position, suggestion, container, provider));
                    didAddResult = true;
                }
            }
            if (isDisposable(container)) {
                disposables.add(container);
            }
            durations.push({
                providerName: (_b = provider._debugDisplayName) !== null && _b !== void 0 ? _b : 'unknown_provider', elapsedProvider: (_c = container.duration) !== null && _c !== void 0 ? _c : -1, elapsedOverall: sw.elapsed()
            });
            return didAddResult;
        };
        // ask for snippets in parallel to asking "real" providers. Only do something if configured to
        // do so - no snippet filter, no special-providers-only request
        const snippetCompletions = (() => suggest_awaiter(this, void 0, void 0, function* () {
            if (!_snippetSuggestSupport || options.kindFilter.has(27 /* languages.CompletionItemKind.Snippet */)) {
                return;
            }
            if (options.providerFilter.size > 0 && !options.providerFilter.has(_snippetSuggestSupport)) {
                return;
            }
            const sw = new StopWatch(true);
            const list = yield _snippetSuggestSupport.provideCompletionItems(model, position, context, token);
            onCompletionList(_snippetSuggestSupport, list, sw);
        }))();
        // add suggestions from contributed providers - providers are ordered in groups of
        // equal score and once a group produces a result the process stops
        // get provider groups, always add snippet suggestion provider
        for (const providerGroup of registry.orderedGroups(model)) {
            // for each support in the group ask for suggestions
            let didAddResult = false;
            yield Promise.all(providerGroup.map((provider) => suggest_awaiter(this, void 0, void 0, function* () {
                if (options.providerFilter.size > 0 && !options.providerFilter.has(provider)) {
                    return;
                }
                try {
                    const sw = new StopWatch(true);
                    const list = yield provider.provideCompletionItems(model, position, context, token);
                    didAddResult = onCompletionList(provider, list, sw) || didAddResult;
                }
                catch (err) {
                    onUnexpectedExternalError(err);
                }
            })));
            if (didAddResult || token.isCancellationRequested) {
                break;
            }
        }
        yield snippetCompletions;
        if (token.isCancellationRequested) {
            disposables.dispose();
            return Promise.reject(new CancellationError());
        }
        return new CompletionItemModel(result.sort(getSuggestionComparator(options.snippetSortOrder)), needsClipboard, { entries: durations, elapsed: sw.elapsed() }, disposables);
    });
}
function defaultComparator(a, b) {
    // check with 'sortText'
    if (a.sortTextLow && b.sortTextLow) {
        if (a.sortTextLow < b.sortTextLow) {
            return -1;
        }
        else if (a.sortTextLow > b.sortTextLow) {
            return 1;
        }
    }
    // check with 'label'
    if (a.textLabel < b.textLabel) {
        return -1;
    }
    else if (a.textLabel > b.textLabel) {
        return 1;
    }
    // check with 'type'
    return a.completion.kind - b.completion.kind;
}
function snippetUpComparator(a, b) {
    if (a.completion.kind !== b.completion.kind) {
        if (a.completion.kind === 27 /* languages.CompletionItemKind.Snippet */) {
            return -1;
        }
        else if (b.completion.kind === 27 /* languages.CompletionItemKind.Snippet */) {
            return 1;
        }
    }
    return defaultComparator(a, b);
}
function snippetDownComparator(a, b) {
    if (a.completion.kind !== b.completion.kind) {
        if (a.completion.kind === 27 /* languages.CompletionItemKind.Snippet */) {
            return 1;
        }
        else if (b.completion.kind === 27 /* languages.CompletionItemKind.Snippet */) {
            return -1;
        }
    }
    return defaultComparator(a, b);
}
const _snippetComparators = new Map();
_snippetComparators.set(0 /* SnippetSortOrder.Top */, snippetUpComparator);
_snippetComparators.set(2 /* SnippetSortOrder.Bottom */, snippetDownComparator);
_snippetComparators.set(1 /* SnippetSortOrder.Inline */, defaultComparator);
function getSuggestionComparator(snippetConfig) {
    return _snippetComparators.get(snippetConfig);
}
CommandsRegistry.registerCommand('_executeCompletionItemProvider', (accessor, ...args) => suggest_awaiter(void 0, void 0, void 0, function* () {
    const [uri, position, triggerCharacter, maxItemsToResolve] = args;
    assertType(URI.isUri(uri));
    assertType(Position.isIPosition(position));
    assertType(typeof triggerCharacter === 'string' || !triggerCharacter);
    assertType(typeof maxItemsToResolve === 'number' || !maxItemsToResolve);
    const { completionProvider } = accessor.get(ILanguageFeaturesService);
    const ref = yield accessor.get(ITextModelService).createModelReference(uri);
    try {
        const result = {
            incomplete: false,
            suggestions: []
        };
        const resolving = [];
        const completions = yield provideSuggestionItems(completionProvider, ref.object.textEditorModel, Position.lift(position), undefined, { triggerCharacter, triggerKind: triggerCharacter ? 1 /* languages.CompletionTriggerKind.TriggerCharacter */ : 0 /* languages.CompletionTriggerKind.Invoke */ });
        for (const item of completions.items) {
            if (resolving.length < (maxItemsToResolve !== null && maxItemsToResolve !== void 0 ? maxItemsToResolve : 0)) {
                resolving.push(item.resolve(CancellationToken.None));
            }
            result.incomplete = result.incomplete || item.container.incomplete;
            result.suggestions.push(item.completion);
        }
        try {
            yield Promise.all(resolving);
            return result;
        }
        finally {
            setTimeout(() => completions.disposable.dispose(), 100);
        }
    }
    finally {
        ref.dispose();
    }
}));
function showSimpleSuggestions(editor, provider) {
    var _a;
    (_a = editor.getContribution('editor.contrib.suggestController')) === null || _a === void 0 ? void 0 : _a.triggerSuggest(new Set().add(provider), undefined, true);
}
class QuickSuggestionsOptions {
    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 /* StandardTokenType.Comment */: return config.comments;
            case 2 /* StandardTokenType.String */: return config.strings;
            default: return config.other;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/hover/browser/contentHover.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var contentHover_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var contentHover_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
















const contentHover_$ = dom_$;
let ContentHoverController = class ContentHoverController extends Disposable {
    constructor(_editor, _instantiationService, _keybindingService) {
        super();
        this._editor = _editor;
        this._instantiationService = _instantiationService;
        this._keybindingService = _keybindingService;
        this._widget = this._register(this._instantiationService.createInstance(ContentHoverWidget, this._editor));
        this._isChangingDecorations = false;
        this._messages = [];
        this._messagesAreComplete = false;
        // Instantiate participants and sort them by `hoverOrdinal` which is relevant for rendering order.
        this._participants = [];
        for (const participant of HoverParticipantRegistry.getAll()) {
            this._participants.push(this._instantiationService.createInstance(participant, this._editor));
        }
        this._participants.sort((p1, p2) => p1.hoverOrdinal - p2.hoverOrdinal);
        this._computer = new ContentHoverComputer(this._editor, this._participants);
        this._hoverOperation = this._register(new HoverOperation(this._editor, this._computer));
        this._register(this._hoverOperation.onResult((result) => {
            this._withResult(result.value, result.isComplete, result.hasLoadingMessage);
        }));
        this._register(this._editor.onDidChangeModelDecorations(() => {
            if (this._isChangingDecorations) {
                return;
            }
            this._onModelDecorationsChanged();
        }));
        this._register(addStandardDisposableListener(this._widget.getDomNode(), 'keydown', (e) => {
            if (e.equals(9 /* KeyCode.Escape */)) {
                this.hide();
            }
        }));
        this._register(languages_TokenizationRegistry.onDidChange(() => {
            if (this._widget.position && this._computer.anchor && this._messages.length > 0) {
                this._widget.clear();
                this._renderMessages(this._computer.anchor, this._messages);
            }
        }));
    }
    _onModelDecorationsChanged() {
        if (this._widget.position) {
            // The decorations have changed and the hover is visible,
            // we need to recompute the displayed text
            this._hoverOperation.cancel();
            if (!this._widget.isColorPickerVisible) { // TODO@Michel ensure that displayed text for other decorations is computed even if color picker is in place
                this._hoverOperation.start(0 /* HoverStartMode.Delayed */);
            }
        }
    }
    maybeShowAt(mouseEvent) {
        const anchorCandidates = [];
        for (const participant of this._participants) {
            if (participant.suggestHoverAnchor) {
                const anchor = participant.suggestHoverAnchor(mouseEvent);
                if (anchor) {
                    anchorCandidates.push(anchor);
                }
            }
        }
        const target = mouseEvent.target;
        if (target.type === 6 /* MouseTargetType.CONTENT_TEXT */) {
            anchorCandidates.push(new HoverRangeAnchor(0, target.range));
        }
        if (target.type === 7 /* MouseTargetType.CONTENT_EMPTY */) {
            const epsilon = this._editor.getOption(46 /* EditorOption.fontInfo */).typicalHalfwidthCharacterWidth / 2;
            if (!target.detail.isAfterLines && typeof target.detail.horizontalDistanceToText === 'number' && target.detail.horizontalDistanceToText < epsilon) {
                // Let hover kick in even when the mouse is technically in the empty area after a line, given the distance is small enough
                anchorCandidates.push(new HoverRangeAnchor(0, target.range));
            }
        }
        if (anchorCandidates.length === 0) {
            return false;
        }
        anchorCandidates.sort((a, b) => b.priority - a.priority);
        this._startShowingAt(anchorCandidates[0], 0 /* HoverStartMode.Delayed */, false);
        return true;
    }
    startShowingAtRange(range, mode, focus) {
        this._startShowingAt(new HoverRangeAnchor(0, range), mode, focus);
    }
    _startShowingAt(anchor, mode, focus) {
        if (this._computer.anchor && this._computer.anchor.equals(anchor)) {
            // We have to show the widget at the exact same range as before, so no work is needed
            return;
        }
        this._hoverOperation.cancel();
        if (this._widget.position) {
            // The range might have changed, but the hover is visible
            // Instead of hiding it completely, filter out messages that are still in the new range and
            // kick off a new computation
            if (!this._computer.anchor || !anchor.canAdoptVisibleHover(this._computer.anchor, this._widget.position)) {
                this.hide();
            }
            else {
                const filteredMessages = this._messages.filter((m) => m.isValidForHoverAnchor(anchor));
                if (filteredMessages.length === 0) {
                    this.hide();
                }
                else if (filteredMessages.length === this._messages.length && this._messagesAreComplete) {
                    // no change
                    return;
                }
                else {
                    this._renderMessages(anchor, filteredMessages);
                }
            }
        }
        this._computer.anchor = anchor;
        this._computer.shouldFocus = focus;
        this._hoverOperation.start(mode);
    }
    hide() {
        this._computer.anchor = null;
        this._hoverOperation.cancel();
        this._widget.hide();
    }
    isColorPickerVisible() {
        return this._widget.isColorPickerVisible;
    }
    containsNode(node) {
        return this._widget.getDomNode().contains(node);
    }
    _addLoadingMessage(result) {
        if (this._computer.anchor) {
            for (const participant of this._participants) {
                if (participant.createLoadingMessage) {
                    const loadingMessage = participant.createLoadingMessage(this._computer.anchor);
                    if (loadingMessage) {
                        return result.slice(0).concat([loadingMessage]);
                    }
                }
            }
        }
        return result;
    }
    _withResult(result, isComplete, hasLoadingMessage) {
        this._messages = (hasLoadingMessage ? this._addLoadingMessage(result) : result);
        this._messagesAreComplete = isComplete;
        if (this._computer.anchor && this._messages.length > 0) {
            this._renderMessages(this._computer.anchor, this._messages);
        }
        else if (isComplete) {
            this.hide();
        }
    }
    _renderMessages(anchor, messages) {
        const { showAtPosition, showAtRange, highlightRange } = ContentHoverController.computeHoverRanges(anchor.range, messages);
        const disposables = new DisposableStore();
        const statusBar = disposables.add(new EditorHoverStatusBar(this._keybindingService));
        const fragment = document.createDocumentFragment();
        let colorPicker = null;
        const context = {
            fragment,
            statusBar,
            setColorPicker: (widget) => colorPicker = widget,
            onContentsChanged: () => this._widget.onContentsChanged(),
            hide: () => this.hide()
        };
        for (const participant of this._participants) {
            const hoverParts = messages.filter(msg => msg.owner === participant);
            if (hoverParts.length > 0) {
                disposables.add(participant.renderHoverParts(context, hoverParts));
            }
        }
        if (statusBar.hasContent) {
            fragment.appendChild(statusBar.hoverElement);
        }
        if (fragment.hasChildNodes()) {
            if (highlightRange) {
                const highlightDecoration = this._editor.createDecorationsCollection();
                try {
                    this._isChangingDecorations = true;
                    highlightDecoration.set([{
                            range: highlightRange,
                            options: ContentHoverController._DECORATION_OPTIONS
                        }]);
                }
                finally {
                    this._isChangingDecorations = false;
                }
                disposables.add(toDisposable(() => {
                    try {
                        this._isChangingDecorations = true;
                        highlightDecoration.clear();
                    }
                    finally {
                        this._isChangingDecorations = false;
                    }
                }));
            }
            this._widget.showAt(fragment, new ContentHoverVisibleData(colorPicker, showAtPosition, showAtRange, this._editor.getOption(55 /* EditorOption.hover */).above, this._computer.shouldFocus, disposables));
        }
        else {
            disposables.dispose();
        }
    }
    static computeHoverRanges(anchorRange, messages) {
        // The anchor range is always on a single line
        const anchorLineNumber = anchorRange.startLineNumber;
        let renderStartColumn = anchorRange.startColumn;
        let renderEndColumn = anchorRange.endColumn;
        let highlightRange = messages[0].range;
        let forceShowAtRange = null;
        for (const msg of messages) {
            highlightRange = Range.plusRange(highlightRange, msg.range);
            if (msg.range.startLineNumber === anchorLineNumber && msg.range.endLineNumber === anchorLineNumber) {
                // this message has a range that is completely sitting on the line of the anchor
                renderStartColumn = Math.min(renderStartColumn, msg.range.startColumn);
                renderEndColumn = Math.max(renderEndColumn, msg.range.endColumn);
            }
            if (msg.forceShowAtRange) {
                forceShowAtRange = msg.range;
            }
        }
        return {
            showAtPosition: forceShowAtRange ? forceShowAtRange.getStartPosition() : new Position(anchorRange.startLineNumber, renderStartColumn),
            showAtRange: forceShowAtRange ? forceShowAtRange : new Range(anchorLineNumber, renderStartColumn, anchorLineNumber, renderEndColumn),
            highlightRange
        };
    }
};
ContentHoverController._DECORATION_OPTIONS = ModelDecorationOptions.register({
    description: 'content-hover-highlight',
    className: 'hoverHighlight'
});
ContentHoverController = contentHover_decorate([
    contentHover_param(1, IInstantiationService),
    contentHover_param(2, IKeybindingService)
], ContentHoverController);

class ContentHoverVisibleData {
    constructor(colorPicker, showAtPosition, showAtRange, preferAbove, stoleFocus, disposables) {
        this.colorPicker = colorPicker;
        this.showAtPosition = showAtPosition;
        this.showAtRange = showAtRange;
        this.preferAbove = preferAbove;
        this.stoleFocus = stoleFocus;
        this.disposables = disposables;
    }
}
let ContentHoverWidget = class ContentHoverWidget extends Disposable {
    constructor(_editor, _contextKeyService) {
        super();
        this._editor = _editor;
        this._contextKeyService = _contextKeyService;
        this.allowEditorOverflow = true;
        this._hoverVisibleKey = EditorContextKeys.hoverVisible.bindTo(this._contextKeyService);
        this._hover = this._register(new HoverWidget());
        this._visibleData = null;
        this._register(this._editor.onDidLayoutChange(() => this._layout()));
        this._register(this._editor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(46 /* EditorOption.fontInfo */)) {
                this._updateFont();
            }
        }));
        this._setVisibleData(null);
        this._layout();
        this._editor.addContentWidget(this);
    }
    /**
     * Returns `null` if the hover is not visible.
     */
    get position() {
        var _a, _b;
        return (_b = (_a = this._visibleData) === null || _a === void 0 ? void 0 : _a.showAtPosition) !== null && _b !== void 0 ? _b : null;
    }
    get isColorPickerVisible() {
        var _a;
        return Boolean((_a = this._visibleData) === null || _a === void 0 ? void 0 : _a.colorPicker);
    }
    dispose() {
        this._editor.removeContentWidget(this);
        if (this._visibleData) {
            this._visibleData.disposables.dispose();
        }
        super.dispose();
    }
    getId() {
        return ContentHoverWidget.ID;
    }
    getDomNode() {
        return this._hover.containerDomNode;
    }
    getPosition() {
        if (!this._visibleData) {
            return null;
        }
        let preferAbove = this._visibleData.preferAbove;
        if (!preferAbove && this._contextKeyService.getContextKeyValue(suggest_Context.Visible.key)) {
            // Prefer rendering above if the suggest widget is visible
            preferAbove = true;
        }
        return {
            position: this._visibleData.showAtPosition,
            range: this._visibleData.showAtRange,
            preference: (preferAbove
                ? [1 /* ContentWidgetPositionPreference.ABOVE */, 2 /* ContentWidgetPositionPreference.BELOW */]
                : [2 /* ContentWidgetPositionPreference.BELOW */, 1 /* ContentWidgetPositionPreference.ABOVE */]),
        };
    }
    _setVisibleData(visibleData) {
        if (this._visibleData) {
            this._visibleData.disposables.dispose();
        }
        this._visibleData = visibleData;
        this._hoverVisibleKey.set(!!this._visibleData);
        this._hover.containerDomNode.classList.toggle('hidden', !this._visibleData);
    }
    _layout() {
        const height = Math.max(this._editor.getLayoutInfo().height / 4, 250);
        const { fontSize, lineHeight } = this._editor.getOption(46 /* EditorOption.fontInfo */);
        this._hover.contentsDomNode.style.fontSize = `${fontSize}px`;
        this._hover.contentsDomNode.style.lineHeight = `${lineHeight / fontSize}`;
        this._hover.contentsDomNode.style.maxHeight = `${height}px`;
        this._hover.contentsDomNode.style.maxWidth = `${Math.max(this._editor.getLayoutInfo().width * 0.66, 500)}px`;
    }
    _updateFont() {
        const codeClasses = Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName('code'));
        codeClasses.forEach(node => this._editor.applyFontInfo(node));
    }
    showAt(node, visibleData) {
        this._setVisibleData(visibleData);
        this._hover.contentsDomNode.textContent = '';
        this._hover.contentsDomNode.appendChild(node);
        this._hover.contentsDomNode.style.paddingBottom = '';
        this._updateFont();
        this.onContentsChanged();
        // Simply force a synchronous render on the editor
        // such that the widget does not really render with left = '0px'
        this._editor.render();
        // See https://github.com/microsoft/vscode/issues/140339
        // TODO: Doing a second layout of the hover after force rendering the editor
        this.onContentsChanged();
        if (visibleData.stoleFocus) {
            this._hover.containerDomNode.focus();
        }
        if (visibleData.colorPicker) {
            visibleData.colorPicker.layout();
        }
    }
    hide() {
        if (this._visibleData) {
            const stoleFocus = this._visibleData.stoleFocus;
            this._setVisibleData(null);
            this._editor.layoutContentWidget(this);
            if (stoleFocus) {
                this._editor.focus();
            }
        }
    }
    onContentsChanged() {
        this._editor.layoutContentWidget(this);
        this._hover.onContentsChanged();
        const scrollDimensions = this._hover.scrollbar.getScrollDimensions();
        const hasHorizontalScrollbar = (scrollDimensions.scrollWidth > scrollDimensions.width);
        if (hasHorizontalScrollbar) {
            // There is just a horizontal scrollbar
            const extraBottomPadding = `${this._hover.scrollbar.options.horizontalScrollbarSize}px`;
            if (this._hover.contentsDomNode.style.paddingBottom !== extraBottomPadding) {
                this._hover.contentsDomNode.style.paddingBottom = extraBottomPadding;
                this._editor.layoutContentWidget(this);
                this._hover.onContentsChanged();
            }
        }
    }
    clear() {
        this._hover.contentsDomNode.textContent = '';
    }
};
ContentHoverWidget.ID = 'editor.contrib.contentHoverWidget';
ContentHoverWidget = contentHover_decorate([
    contentHover_param(1, IContextKeyService)
], ContentHoverWidget);

let EditorHoverStatusBar = class EditorHoverStatusBar extends Disposable {
    constructor(_keybindingService) {
        super();
        this._keybindingService = _keybindingService;
        this._hasContent = false;
        this.hoverElement = contentHover_$('div.hover-row.status-bar');
        this.actionsElement = append(this.hoverElement, contentHover_$('div.actions'));
    }
    get hasContent() {
        return this._hasContent;
    }
    addAction(actionOptions) {
        const keybinding = this._keybindingService.lookupKeybinding(actionOptions.commandId);
        const keybindingLabel = keybinding ? keybinding.getLabel() : null;
        this._hasContent = true;
        return this._register(HoverAction.render(this.actionsElement, actionOptions, keybindingLabel));
    }
    append(element) {
        const result = append(this.actionsElement, element);
        this._hasContent = true;
        return result;
    }
};
EditorHoverStatusBar = contentHover_decorate([
    contentHover_param(0, IKeybindingService)
], EditorHoverStatusBar);
class ContentHoverComputer {
    constructor(_editor, _participants) {
        this._editor = _editor;
        this._participants = _participants;
        this._anchor = null;
        this._shouldFocus = false;
    }
    get anchor() { return this._anchor; }
    set anchor(value) { this._anchor = value; }
    get shouldFocus() { return this._shouldFocus; }
    set shouldFocus(value) { this._shouldFocus = value; }
    static _getLineDecorations(editor, anchor) {
        if (anchor.type !== 1 /* HoverAnchorType.Range */) {
            return [];
        }
        const model = editor.getModel();
        const lineNumber = anchor.range.startLineNumber;
        if (lineNumber > model.getLineCount()) {
            // invalid line
            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) {
                // Relax check around `showIfCollapsed` decorations to also include +/- 1 character
                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(token) {
        const anchor = this._anchor;
        if (!this._editor.hasModel() || !anchor) {
            return AsyncIterableObject.EMPTY;
        }
        const lineDecorations = ContentHoverComputer._getLineDecorations(this._editor, anchor);
        return AsyncIterableObject.merge(this._participants.map((participant) => {
            if (!participant.computeAsync) {
                return AsyncIterableObject.EMPTY;
            }
            return participant.computeAsync(anchor, lineDecorations, token);
        }));
    }
    computeSync() {
        if (!this._editor.hasModel() || !this._anchor) {
            return [];
        }
        const lineDecorations = ContentHoverComputer._getLineDecorations(this._editor, this._anchor);
        let result = [];
        for (const participant of this._participants) {
            result = result.concat(participant.computeSync(this._anchor, lineDecorations));
        }
        return coalesce(result);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/marked/marked.js
/**
 * marked - a markdown parser
 * Copyright (c) 2011-2022, Christopher Jeffrey. (MIT Licensed)
 * https://github.com/markedjs/marked
 */

/**
 * DO NOT EDIT THIS FILE
 * The code in this file is generated from files in ./src/
 */

// ESM-uncomment-begin
let __marked_exports = {};
(function() {
  function define(deps, factory) {
    factory(__marked_exports);
  }
  define.amd = true;
// ESM-uncomment-end

 (function (global, factory) {
  typeof exports === 'object' && "object" !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.marked = {}));
})(this, (function (exports) { 'use strict';

  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    Object.defineProperty(Constructor, "prototype", {
      writable: false
    });
    return Constructor;
  }

  function _unsupportedIterableToArray(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _arrayLikeToArray(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(o);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  }

  function _arrayLikeToArray(arr, len) {
    if (len == null || len > arr.length) len = arr.length;

    for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];

    return arr2;
  }

  function _createForOfIteratorHelperLoose(o, allowArrayLike) {
    var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
    if (it) return (it = it.call(o)).next.bind(it);

    if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
      if (it) o = it;
      var i = 0;
      return function () {
        if (i >= o.length) return {
          done: true
        };
        return {
          done: false,
          value: o[i++]
        };
      };
    }

    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }

  function getDefaults() {
    return {
      baseUrl: null,
      breaks: false,
      extensions: null,
      gfm: true,
      headerIds: true,
      headerPrefix: '',
      highlight: null,
      langPrefix: 'language-',
      mangle: true,
      pedantic: false,
      renderer: null,
      sanitize: false,
      sanitizer: null,
      silent: false,
      smartLists: false,
      smartypants: false,
      tokenizer: null,
      walkTokens: null,
      xhtml: false
    };
  }
  exports.defaults = getDefaults();
  function changeDefaults(newDefaults) {
    exports.defaults = newDefaults;
  }

  /**
   * Helpers
   */
  var escapeTest = /[&<>"']/;
  var escapeReplace = /[&<>"']/g;
  var escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/;
  var escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g;
  var escapeReplacements = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
  };

  var getEscapeReplacement = function getEscapeReplacement(ch) {
    return escapeReplacements[ch];
  };

  function escape(html, encode) {
    if (encode) {
      if (escapeTest.test(html)) {
        return html.replace(escapeReplace, getEscapeReplacement);
      }
    } else {
      if (escapeTestNoEncode.test(html)) {
        return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
      }
    }

    return html;
  }
  var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
  /**
   * @param {string} html
   */

  function unescape(html) {
    // explicitly match decimal, hex, and named HTML entities
    return html.replace(unescapeTest, function (_, 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 '';
    });
  }
  var caret = /(^|[^\[])\^/g;
  /**
   * @param {string | RegExp} regex
   * @param {string} opt
   */

  function edit(regex, opt) {
    regex = typeof regex === 'string' ? regex : regex.source;
    opt = opt || '';
    var obj = {
      replace: function replace(name, val) {
        val = val.source || val;
        val = val.replace(caret, '$1');
        regex = regex.replace(name, val);
        return obj;
      },
      getRegex: function getRegex() {
        return new RegExp(regex, opt);
      }
    };
    return obj;
  }
  var nonWordAndColonTest = /[^\w:]/g;
  var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
  /**
   * @param {boolean} sanitize
   * @param {string} base
   * @param {string} href
   */

  function cleanUrl(sanitize, base, href) {
    if (sanitize) {
      var prot;

      try {
        prot = decodeURIComponent(unescape(href)).replace(nonWordAndColonTest, '').toLowerCase();
      } catch (e) {
        return null;
      }

      if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
        return null;
      }
    }

    if (base && !originIndependentUrl.test(href)) {
      href = resolveUrl(base, href);
    }

    try {
      href = encodeURI(href).replace(/%25/g, '%');
    } catch (e) {
      return null;
    }

    return href;
  }
  var baseUrls = {};
  var justDomain = /^[^:]+:\/*[^/]*$/;
  var protocol = /^([^:]+:)[\s\S]*$/;
  var domain = /^([^:]+:\/*[^/]*)[\s\S]*$/;
  /**
   * @param {string} base
   * @param {string} href
   */

  function resolveUrl(base, href) {
    if (!baseUrls[' ' + base]) {
      // we can ignore everything in base after the last slash of its path component,
      // but we might need to add _that_
      // https://tools.ietf.org/html/rfc3986#section-3
      if (justDomain.test(base)) {
        baseUrls[' ' + base] = base + '/';
      } else {
        baseUrls[' ' + base] = rtrim(base, '/', true);
      }
    }

    base = baseUrls[' ' + base];
    var relativeBase = base.indexOf(':') === -1;

    if (href.substring(0, 2) === '//') {
      if (relativeBase) {
        return href;
      }

      return base.replace(protocol, '$1') + href;
    } else if (href.charAt(0) === '/') {
      if (relativeBase) {
        return href;
      }

      return base.replace(domain, '$1') + href;
    } else {
      return base + href;
    }
  }
  var noopTest = {
    exec: function noopTest() {}
  };
  function merge(obj) {
    var i = 1,
        target,
        key;

    for (; i < arguments.length; i++) {
      target = arguments[i];

      for (key in target) {
        if (Object.prototype.hasOwnProperty.call(target, key)) {
          obj[key] = target[key];
        }
      }
    }

    return obj;
  }
  function splitCells(tableRow, count) {
    // ensure that every cell-delimiting pipe has a space
    // before it to distinguish it from an escaped pipe
    var row = tableRow.replace(/\|/g, function (match, offset, str) {
      var escaped = false,
          curr = offset;

      while (--curr >= 0 && str[curr] === '\\') {
        escaped = !escaped;
      }

      if (escaped) {
        // odd number of slashes means | is escaped
        // so we leave it alone
        return '|';
      } else {
        // add space before unescaped |
        return ' |';
      }
    }),
        cells = row.split(/ \|/);
    var i = 0; // First/last cell in a row cannot be empty if it has no leading/trailing pipe

    if (!cells[0].trim()) {
      cells.shift();
    }

    if (cells.length > 0 && !cells[cells.length - 1].trim()) {
      cells.pop();
    }

    if (cells.length > count) {
      cells.splice(count);
    } else {
      while (cells.length < count) {
        cells.push('');
      }
    }

    for (; i < cells.length; i++) {
      // leading or trailing whitespace is ignored per the gfm spec
      cells[i] = cells[i].trim().replace(/\\\|/g, '|');
    }

    return cells;
  }
  /**
   * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
   * /c*$/ is vulnerable to REDOS.
   *
   * @param {string} str
   * @param {string} c
   * @param {boolean} invert Remove suffix of non-c chars instead. Default falsey.
   */

  function rtrim(str, c, invert) {
    var l = str.length;

    if (l === 0) {
      return '';
    } // Length of suffix matching the invert condition.


    var suffLen = 0; // Step left until we fail to match the invert condition.

    while (suffLen < l) {
      var 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;
    }

    var l = str.length;
    var level = 0,
        i = 0;

    for (; i < l; i++) {
      if (str[i] === '\\') {
        i++;
      } else if (str[i] === b[0]) {
        level++;
      } else if (str[i] === b[1]) {
        level--;

        if (level < 0) {
          return i;
        }
      }
    }

    return -1;
  }
  function checkSanitizeDeprecation(opt) {
    if (opt && opt.sanitize && !opt.silent) {
      console.warn('marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options');
    }
  } // copied from https://stackoverflow.com/a/5450113/806777

  /**
   * @param {string} pattern
   * @param {number} count
   */

  function repeatString(pattern, count) {
    if (count < 1) {
      return '';
    }

    var result = '';

    while (count > 1) {
      if (count & 1) {
        result += pattern;
      }

      count >>= 1;
      pattern += pattern;
    }

    return result + pattern;
  }

  function outputLink(cap, link, raw, lexer) {
    var href = link.href;
    var title = link.title ? escape(link.title) : null;
    var text = cap[1].replace(/\\([\[\]])/g, '$1');

    if (cap[0].charAt(0) !== '!') {
      lexer.state.inLink = true;
      var token = {
        type: 'link',
        raw: raw,
        href: href,
        title: title,
        text: text,
        tokens: lexer.inlineTokens(text, [])
      };
      lexer.state.inLink = false;
      return token;
    }

    return {
      type: 'image',
      raw: raw,
      href: href,
      title: title,
      text: escape(text)
    };
  }

  function indentCodeCompensation(raw, text) {
    var matchIndentToCode = raw.match(/^(\s+)(?:```)/);

    if (matchIndentToCode === null) {
      return text;
    }

    var indentToCode = matchIndentToCode[1];
    return text.split('\n').map(function (node) {
      var matchIndentInNode = node.match(/^\s+/);

      if (matchIndentInNode === null) {
        return node;
      }

      var indentInNode = matchIndentInNode[0];

      if (indentInNode.length >= indentToCode.length) {
        return node.slice(indentToCode.length);
      }

      return node;
    }).join('\n');
  }
  /**
   * Tokenizer
   */


  var Tokenizer = /*#__PURE__*/function () {
    function Tokenizer(options) {
      this.options = options || exports.defaults;
    }

    var _proto = Tokenizer.prototype;

    _proto.space = function space(src) {
      var cap = this.rules.block.newline.exec(src);

      if (cap && cap[0].length > 0) {
        return {
          type: 'space',
          raw: cap[0]
        };
      }
    };

    _proto.code = function code(src) {
      var cap = this.rules.block.code.exec(src);

      if (cap) {
        var text = cap[0].replace(/^ {1,4}/gm, '');
        return {
          type: 'code',
          raw: cap[0],
          codeBlockStyle: 'indented',
          text: !this.options.pedantic ? rtrim(text, '\n') : text
        };
      }
    };

    _proto.fences = function fences(src) {
      var cap = this.rules.block.fences.exec(src);

      if (cap) {
        var raw = cap[0];
        var text = indentCodeCompensation(raw, cap[3] || '');
        return {
          type: 'code',
          raw: raw,
          lang: cap[2] ? cap[2].trim() : cap[2],
          text: text
        };
      }
    };

    _proto.heading = function heading(src) {
      var cap = this.rules.block.heading.exec(src);

      if (cap) {
        var text = cap[2].trim(); // remove trailing #s

        if (/#$/.test(text)) {
          var trimmed = rtrim(text, '#');

          if (this.options.pedantic) {
            text = trimmed.trim();
          } else if (!trimmed || / $/.test(trimmed)) {
            // CommonMark requires space before trailing #s
            text = trimmed.trim();
          }
        }

        var token = {
          type: 'heading',
          raw: cap[0],
          depth: cap[1].length,
          text: text,
          tokens: []
        };
        this.lexer.inline(token.text, token.tokens);
        return token;
      }
    };

    _proto.hr = function hr(src) {
      var cap = this.rules.block.hr.exec(src);

      if (cap) {
        return {
          type: 'hr',
          raw: cap[0]
        };
      }
    };

    _proto.blockquote = function blockquote(src) {
      var cap = this.rules.block.blockquote.exec(src);

      if (cap) {
        var text = cap[0].replace(/^ *>[ \t]?/gm, '');
        return {
          type: 'blockquote',
          raw: cap[0],
          tokens: this.lexer.blockTokens(text, []),
          text: text
        };
      }
    };

    _proto.list = function list(src) {
      var cap = this.rules.block.list.exec(src);

      if (cap) {
        var raw, istask, ischecked, indent, i, blankLine, endsWithBlankLine, line, nextLine, rawLine, itemContents, endEarly;
        var bull = cap[1].trim();
        var isordered = bull.length > 1;
        var list = {
          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 : '[*+-]';
        } // Get next list item


        var itemRegex = new RegExp("^( {0,3}" + bull + ")((?:[\t ][^\\n]*)?(?:\\n|$))"); // Check if current bullet point can start a new List Item

        while (src) {
          endEarly = false;

          if (!(cap = itemRegex.exec(src))) {
            break;
          }

          if (this.rules.block.hr.test(src)) {
            // End list if bullet was actually HR (possibly move into itemRegex?)
            break;
          }

          raw = cap[0];
          src = src.substring(raw.length);
          line = cap[2].split('\n', 1)[0];
          nextLine = src.split('\n', 1)[0];

          if (this.options.pedantic) {
            indent = 2;
            itemContents = line.trimLeft();
          } else {
            indent = cap[2].search(/[^ ]/); // Find first non-space char

            indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent

            itemContents = line.slice(indent);
            indent += cap[1].length;
          }

          blankLine = false;

          if (!line && /^ *$/.test(nextLine)) {
            // Items begin with at most one blank line
            raw += nextLine + '\n';
            src = src.substring(nextLine.length + 1);
            endEarly = true;
          }

          if (!endEarly) {
            var nextBulletRegex = new RegExp("^ {0," + Math.min(3, indent - 1) + "}(?:[*+-]|\\d{1,9}[.)])((?: [^\\n]*)?(?:\\n|$))");
            var hrRegex = new RegExp("^ {0," + Math.min(3, indent - 1) + "}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)"); // Check if following lines should be included in List Item

            while (src) {
              rawLine = src.split('\n', 1)[0];
              line = rawLine; // Re-align to follow commonmark nesting rules

              if (this.options.pedantic) {
                line = line.replace(/^ {1,4}(?=( {4})*[^ ])/g, '  ');
              } // End list item if found start of new bullet


              if (nextBulletRegex.test(line)) {
                break;
              } // Horizontal rule found


              if (hrRegex.test(src)) {
                break;
              }

              if (line.search(/[^ ]/) >= indent || !line.trim()) {
                // Dedent if possible
                itemContents += '\n' + line.slice(indent);
              } else if (!blankLine) {
                // Until blank line, item doesn't need indentation
                itemContents += '\n' + line;
              } else {
                // Otherwise, improper indentation ends this item
                break;
              }

              if (!blankLine && !line.trim()) {
                // Check if current line is blank
                blankLine = true;
              }

              raw += rawLine + '\n';
              src = src.substring(rawLine.length + 1);
            }
          }

          if (!list.loose) {
            // If the previous item ended with a blank line, the list is loose
            if (endsWithBlankLine) {
              list.loose = true;
            } else if (/\n *\n *$/.test(raw)) {
              endsWithBlankLine = true;
            }
          } // Check for task list items


          if (this.options.gfm) {
            istask = /^\[[ xX]\] /.exec(itemContents);

            if (istask) {
              ischecked = istask[0] !== '[ ] ';
              itemContents = itemContents.replace(/^\[[ xX]\] +/, '');
            }
          }

          list.items.push({
            type: 'list_item',
            raw: raw,
            task: !!istask,
            checked: ischecked,
            loose: false,
            text: itemContents
          });
          list.raw += raw;
        } // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic


        list.items[list.items.length - 1].raw = raw.trimRight();
        list.items[list.items.length - 1].text = itemContents.trimRight();
        list.raw = list.raw.trimRight();
        var l = list.items.length; // Item child tokens handled here at end because we needed to have the final item to trim it first

        for (i = 0; i < l; i++) {
          this.lexer.state.top = false;
          list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);
          var spacers = list.items[i].tokens.filter(function (t) {
            return t.type === 'space';
          });
          var hasMultipleLineBreaks = spacers.every(function (t) {
            var chars = t.raw.split('');
            var lineBreaks = 0;

            for (var _iterator = _createForOfIteratorHelperLoose(chars), _step; !(_step = _iterator()).done;) {
              var _char = _step.value;

              if (_char === '\n') {
                lineBreaks += 1;
              }

              if (lineBreaks > 1) {
                return true;
              }
            }

            return false;
          });

          if (!list.loose && spacers.length && hasMultipleLineBreaks) {
            // Having a single line break doesn't mean a list is loose. A single line break is terminating the last list item
            list.loose = true;
            list.items[i].loose = true;
          }
        }

        return list;
      }
    };

    _proto.html = function html(src) {
      var cap = this.rules.block.html.exec(src);

      if (cap) {
        var token = {
          type: 'html',
          raw: cap[0],
          pre: !this.options.sanitizer && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
          text: cap[0]
        };

        if (this.options.sanitize) {
          token.type = 'paragraph';
          token.text = this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]);
          token.tokens = [];
          this.lexer.inline(token.text, token.tokens);
        }

        return token;
      }
    };

    _proto.def = function def(src) {
      var cap = this.rules.block.def.exec(src);

      if (cap) {
        if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1);
        var tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
        return {
          type: 'def',
          tag: tag,
          raw: cap[0],
          href: cap[2],
          title: cap[3]
        };
      }
    };

    _proto.table = function table(src) {
      var cap = this.rules.block.table.exec(src);

      if (cap) {
        var item = {
          type: 'table',
          header: splitCells(cap[1]).map(function (c) {
            return {
              text: c
            };
          }),
          align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
          rows: cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : []
        };

        if (item.header.length === item.align.length) {
          item.raw = cap[0];
          var l = item.align.length;
          var i, j, k, row;

          for (i = 0; i < l; i++) {
            if (/^ *-+: *$/.test(item.align[i])) {
              item.align[i] = 'right';
            } else if (/^ *:-+: *$/.test(item.align[i])) {
              item.align[i] = 'center';
            } else if (/^ *:-+ *$/.test(item.align[i])) {
              item.align[i] = 'left';
            } else {
              item.align[i] = null;
            }
          }

          l = item.rows.length;

          for (i = 0; i < l; i++) {
            item.rows[i] = splitCells(item.rows[i], item.header.length).map(function (c) {
              return {
                text: c
              };
            });
          } // parse child tokens inside headers and cells
          // header child tokens


          l = item.header.length;

          for (j = 0; j < l; j++) {
            item.header[j].tokens = [];
            this.lexer.inline(item.header[j].text, item.header[j].tokens);
          } // cell child tokens


          l = item.rows.length;

          for (j = 0; j < l; j++) {
            row = item.rows[j];

            for (k = 0; k < row.length; k++) {
              row[k].tokens = [];
              this.lexer.inline(row[k].text, row[k].tokens);
            }
          }

          return item;
        }
      }
    };

    _proto.lheading = function lheading(src) {
      var cap = this.rules.block.lheading.exec(src);

      if (cap) {
        var token = {
          type: 'heading',
          raw: cap[0],
          depth: cap[2].charAt(0) === '=' ? 1 : 2,
          text: cap[1],
          tokens: []
        };
        this.lexer.inline(token.text, token.tokens);
        return token;
      }
    };

    _proto.paragraph = function paragraph(src) {
      var cap = this.rules.block.paragraph.exec(src);

      if (cap) {
        var token = {
          type: 'paragraph',
          raw: cap[0],
          text: cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1],
          tokens: []
        };
        this.lexer.inline(token.text, token.tokens);
        return token;
      }
    };

    _proto.text = function text(src) {
      var cap = this.rules.block.text.exec(src);

      if (cap) {
        var token = {
          type: 'text',
          raw: cap[0],
          text: cap[0],
          tokens: []
        };
        this.lexer.inline(token.text, token.tokens);
        return token;
      }
    };

    _proto.escape = function escape$1(src) {
      var cap = this.rules.inline.escape.exec(src);

      if (cap) {
        return {
          type: 'escape',
          raw: cap[0],
          text: escape(cap[1])
        };
      }
    };

    _proto.tag = function tag(src) {
      var 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: this.options.sanitize ? 'text' : 'html',
          raw: cap[0],
          inLink: this.lexer.state.inLink,
          inRawBlock: this.lexer.state.inRawBlock,
          text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0]
        };
      }
    };

    _proto.link = function link(src) {
      var cap = this.rules.inline.link.exec(src);

      if (cap) {
        var trimmedUrl = cap[2].trim();

        if (!this.options.pedantic && /^</.test(trimmedUrl)) {
          // commonmark requires matching angle brackets
          if (!/>$/.test(trimmedUrl)) {
            return;
          } // ending angle bracket cannot be escaped


          var rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\');

          if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
            return;
          }
        } else {
          // find closing parenthesis
          var lastParenIndex = findClosingBracket(cap[2], '()');

          if (lastParenIndex > -1) {
            var start = cap[0].indexOf('!') === 0 ? 5 : 4;
            var linkLen = start + cap[1].length + lastParenIndex;
            cap[2] = cap[2].substring(0, lastParenIndex);
            cap[0] = cap[0].substring(0, linkLen).trim();
            cap[3] = '';
          }
        }

        var href = cap[2];
        var title = '';

        if (this.options.pedantic) {
          // split pedantic href and title
          var link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);

          if (link) {
            href = link[1];
            title = link[3];
          }
        } else {
          title = cap[3] ? cap[3].slice(1, -1) : '';
        }

        href = href.trim();

        if (/^</.test(href)) {
          if (this.options.pedantic && !/>$/.test(trimmedUrl)) {
            // pedantic allows starting angle bracket without ending angle bracket
            href = href.slice(1);
          } else {
            href = href.slice(1, -1);
          }
        }

        return outputLink(cap, {
          href: href ? href.replace(this.rules.inline._escapes, '$1') : href,
          title: title ? title.replace(this.rules.inline._escapes, '$1') : title
        }, cap[0], this.lexer);
      }
    };

    _proto.reflink = function reflink(src, links) {
      var cap;

      if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
        var link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
        link = links[link.toLowerCase()];

        if (!link || !link.href) {
          var text = cap[0].charAt(0);
          return {
            type: 'text',
            raw: text,
            text: text
          };
        }

        return outputLink(cap, link, cap[0], this.lexer);
      }
    };

    _proto.emStrong = function emStrong(src, maskedSrc, prevChar) {
      if (prevChar === void 0) {
        prevChar = '';
      }

      var match = this.rules.inline.emStrong.lDelim.exec(src);
      if (!match) return; // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well

      if (match[3] && prevChar.match(/(?:[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xBC-\xBE\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09F9\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BF2\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C78-\u0C7E\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D58-\u0D61\u0D66-\u0D78\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F33\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1369-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2150-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2CFD\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3192-\u3195\u31A0-\u31BF\u31F0-\u31FF\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA830-\uA835\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD07-\uDD33\uDD40-\uDD78\uDD8A\uDD8B\uDE80-\uDE9C\uDEA0-\uDED0\uDEE1-\uDEFB\uDF00-\uDF23\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC58-\uDC76\uDC79-\uDC9E\uDCA7-\uDCAF\uDCE0-\uDCF2\uDCF4\uDCF5\uDCFB-\uDD1B\uDD20-\uDD39\uDD80-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE40-\uDE48\uDE60-\uDE7E\uDE80-\uDE9F\uDEC0-\uDEC7\uDEC9-\uDEE4\uDEEB-\uDEEF\uDF00-\uDF35\uDF40-\uDF55\uDF58-\uDF72\uDF78-\uDF91\uDFA9-\uDFAF]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDCFA-\uDD23\uDD30-\uDD39\uDE60-\uDE7E\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF27\uDF30-\uDF45\uDF51-\uDF54\uDF70-\uDF81\uDFB0-\uDFCB\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC52-\uDC6F\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDDE1-\uDDF4\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF3B\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCF2\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC6C\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0\uDFC0-\uDFD4]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDE70-\uDEBE\uDEC0-\uDEC9\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF5B-\uDF61\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE96\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD834[\uDEE0-\uDEF3\uDF60-\uDF78]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD837[\uDF00-\uDF1E]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDCC7-\uDCCF\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDC71-\uDCAB\uDCAD-\uDCAF\uDCB1-\uDCB4\uDD01-\uDD2D\uDD2F-\uDD3D\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83C[\uDD00-\uDD0C]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])/)) return;
      var nextChar = match[1] || match[2] || '';

      if (!nextChar || nextChar && (prevChar === '' || this.rules.inline.punctuation.exec(prevChar))) {
        var lLength = match[0].length - 1;
        var rDelim,
            rLength,
            delimTotal = lLength,
            midDelimTotal = 0;
        var endReg = match[0][0] === '*' ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd;
        endReg.lastIndex = 0; // Clip maskedSrc to same section of string as src (move to lexer?)

        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; // skip single * in __abc*abc__

          rLength = rDelim.length;

          if (match[3] || match[4]) {
            // found another Left Delim
            delimTotal += rLength;
            continue;
          } else if (match[5] || match[6]) {
            // either Left or Right Delim
            if (lLength % 3 && !((lLength + rLength) % 3)) {
              midDelimTotal += rLength;
              continue; // CommonMark Emphasis Rules 9-10
            }
          }

          delimTotal -= rLength;
          if (delimTotal > 0) continue; // Haven't found enough closing delimiters
          // Remove extra characters. *a*** -> *a*

          rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); // Create `em` if smallest delimiter has odd char count. *a***

          if (Math.min(lLength, rLength) % 2) {
            var _text = src.slice(1, lLength + match.index + rLength);

            return {
              type: 'em',
              raw: src.slice(0, lLength + match.index + rLength + 1),
              text: _text,
              tokens: this.lexer.inlineTokens(_text, [])
            };
          } // Create 'strong' if smallest delimiter has even char count. **a***


          var text = src.slice(2, lLength + match.index + rLength - 1);
          return {
            type: 'strong',
            raw: src.slice(0, lLength + match.index + rLength + 1),
            text: text,
            tokens: this.lexer.inlineTokens(text, [])
          };
        }
      }
    };

    _proto.codespan = function codespan(src) {
      var cap = this.rules.inline.code.exec(src);

      if (cap) {
        var text = cap[2].replace(/\n/g, ' ');
        var hasNonSpaceChars = /[^ ]/.test(text);
        var hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);

        if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
          text = text.substring(1, text.length - 1);
        }

        text = escape(text, true);
        return {
          type: 'codespan',
          raw: cap[0],
          text: text
        };
      }
    };

    _proto.br = function br(src) {
      var cap = this.rules.inline.br.exec(src);

      if (cap) {
        return {
          type: 'br',
          raw: cap[0]
        };
      }
    };

    _proto.del = function del(src) {
      var cap = this.rules.inline.del.exec(src);

      if (cap) {
        return {
          type: 'del',
          raw: cap[0],
          text: cap[2],
          tokens: this.lexer.inlineTokens(cap[2], [])
        };
      }
    };

    _proto.autolink = function autolink(src, mangle) {
      var cap = this.rules.inline.autolink.exec(src);

      if (cap) {
        var text, href;

        if (cap[2] === '@') {
          text = escape(this.options.mangle ? mangle(cap[1]) : cap[1]);
          href = 'mailto:' + text;
        } else {
          text = escape(cap[1]);
          href = text;
        }

        return {
          type: 'link',
          raw: cap[0],
          text: text,
          href: href,
          tokens: [{
            type: 'text',
            raw: text,
            text: text
          }]
        };
      }
    };

    _proto.url = function url(src, mangle) {
      var cap;

      if (cap = this.rules.inline.url.exec(src)) {
        var text, href;

        if (cap[2] === '@') {
          text = escape(this.options.mangle ? mangle(cap[0]) : cap[0]);
          href = 'mailto:' + text;
        } else {
          // do extended autolink path validation
          var prevCapZero;

          do {
            prevCapZero = cap[0];
            cap[0] = this.rules.inline._backpedal.exec(cap[0])[0];
          } while (prevCapZero !== cap[0]);

          text = escape(cap[0]);

          if (cap[1] === 'www.') {
            href = 'http://' + text;
          } else {
            href = text;
          }
        }

        return {
          type: 'link',
          raw: cap[0],
          text: text,
          href: href,
          tokens: [{
            type: 'text',
            raw: text,
            text: text
          }]
        };
      }
    };

    _proto.inlineText = function inlineText(src, smartypants) {
      var cap = this.rules.inline.text.exec(src);

      if (cap) {
        var text;

        if (this.lexer.state.inRawBlock) {
          text = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0];
        } else {
          text = escape(this.options.smartypants ? smartypants(cap[0]) : cap[0]);
        }

        return {
          type: 'text',
          raw: cap[0],
          text: text
        };
      }
    };

    return Tokenizer;
  }();

  /**
   * Block-Level Grammar
   */

  var block = {
    newline: /^(?: *(?:\n|$))+/,
    code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,
    fences: /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?=\n|$)|$)/,
    hr: /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,
    heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,
    blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
    list: /^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,
    html: '^ {0,3}(?:' // optional indentation
    + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
    + '|comment[^\\n]*(\\n+|$)' // (2)
    + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3)
    + '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4)
    + '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5)
    + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (6)
    + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) open tag
    + '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) closing tag
    + ')',
    def: /^ {0,3}\[(label)\]: *(?:\n *)?<?([^\s>]+)>?(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,
    table: noopTest,
    lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,
    // regex template, placeholders will be replaced according to different paragraph
    // interruption rules of commonmark and the original markdown spec:
    _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,
    text: /^[^\n]+/
  };
  block._label = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
  block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
  block.def = edit(block.def).replace('label', block._label).replace('title', block._title).getRegex();
  block.bullet = /(?:[*+-]|\d{1,9}[.)])/;
  block.listItemStart = edit(/^( *)(bull) */).replace('bull', block.bullet).getRegex();
  block.list = edit(block.list).replace(/bull/g, block.bullet).replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))').replace('def', '\\n+(?=' + block.def.source + ')').getRegex();
  block._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|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + '|track|ul';
  block._comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/;
  block.html = edit(block.html, 'i').replace('comment', block._comment).replace('tag', block._tag).replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
  block.paragraph = edit(block._paragraph).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
  .replace('|table', '').replace('blockquote', ' {0,3}>').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
  .getRegex();
  block.blockquote = edit(block.blockquote).replace('paragraph', block.paragraph).getRegex();
  /**
   * Normal Block Grammar
   */

  block.normal = merge({}, block);
  /**
   * GFM Block Grammar
   */

  block.gfm = merge({}, block.normal, {
    table: '^ *([^\\n ].*\\|.*)\\n' // Header
    + ' {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?' // Align
    + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)' // Cells

  });
  block.gfm.table = edit(block.gfm.table).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('blockquote', ' {0,3}>').replace('code', ' {4}[^\\n]').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', block._tag) // tables can be interrupted by type (6) html blocks
  .getRegex();
  block.gfm.paragraph = edit(block._paragraph).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
  .replace('table', block.gfm.table) // interrupt paragraphs with table
  .replace('blockquote', ' {0,3}>').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
  .getRegex();
  /**
   * Pedantic grammar (original John Gruber's loose markdown specification)
   */

  block.pedantic = merge({}, block.normal, {
    html: edit('^ *(?:comment *(?:\\n|\\s*$)' + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
    + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))').replace('comment', block._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
    paragraph: edit(block.normal._paragraph).replace('hr', block.hr).replace('heading', ' *#{1,6} *[^\n]').replace('lheading', block.lheading).replace('blockquote', ' {0,3}>').replace('|fences', '').replace('|list', '').replace('|html', '').getRegex()
  });
  /**
   * Inline-Level Grammar
   */

  var inline = {
    escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
    autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
    url: noopTest,
    tag: '^comment' + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
    + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
    + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
    + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
    + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>',
    // CDATA section
    link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,
    reflink: /^!?\[(label)\]\[(ref)\]/,
    nolink: /^!?\[(ref)\](?:\[\])?/,
    reflinkSearch: 'reflink|nolink(?!\\()',
    emStrong: {
      lDelim: /^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,
      //        (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left.  (5) and (6) can be either Left or Right.
      //          () Skip orphan inside strong  () Consume to delim (1) #***                (2) a***#, a***                   (3) #***a, ***a                 (4) ***#              (5) #***#                 (6) a***a
      rDelimAst: /^[^_*]*?\_\_[^_*]*?\*[^_*]*?(?=\_\_)|[^*]+(?=[^*])|[punct_](\*+)(?=[\s]|$)|[^punct*_\s](\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|[^punct*_\s](\*+)(?=[^punct*_\s])/,
      rDelimUnd: /^[^_*]*?\*\*[^_*]*?\_[^_*]*?(?=\*\*)|[^_]+(?=[^_])|[punct*](\_+)(?=[\s]|$)|[^punct*_\s](\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/ // ^- Not allowed for _

    },
    code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
    br: /^( {2,}|\\)\n(?!\s*$)/,
    del: noopTest,
    text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,
    punctuation: /^([\spunctuation])/
  }; // list of punctuation marks from CommonMark spec
  // without * and _ to handle the different emphasis markers * and _

  inline._punctuation = '!"#$%&\'()+\\-.,/:;<=>?@\\[\\]`^{|}~';
  inline.punctuation = edit(inline.punctuation).replace(/punctuation/g, inline._punctuation).getRegex(); // sequences em should skip over [title](link), `code`, <html>

  inline.blockSkip = /\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g;
  inline.escapedEmSt = /\\\*|\\_/g;
  inline._comment = edit(block._comment).replace('(?:-->|$)', '-->').getRegex();
  inline.emStrong.lDelim = edit(inline.emStrong.lDelim).replace(/punct/g, inline._punctuation).getRegex();
  inline.emStrong.rDelimAst = edit(inline.emStrong.rDelimAst, 'g').replace(/punct/g, inline._punctuation).getRegex();
  inline.emStrong.rDelimUnd = edit(inline.emStrong.rDelimUnd, 'g').replace(/punct/g, inline._punctuation).getRegex();
  inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;
  inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
  inline._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])?)+(?![-_])/;
  inline.autolink = edit(inline.autolink).replace('scheme', inline._scheme).replace('email', inline._email).getRegex();
  inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
  inline.tag = edit(inline.tag).replace('comment', inline._comment).replace('attribute', inline._attribute).getRegex();
  inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
  inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;
  inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
  inline.link = edit(inline.link).replace('label', inline._label).replace('href', inline._href).replace('title', inline._title).getRegex();
  inline.reflink = edit(inline.reflink).replace('label', inline._label).replace('ref', block._label).getRegex();
  inline.nolink = edit(inline.nolink).replace('ref', block._label).getRegex();
  inline.reflinkSearch = edit(inline.reflinkSearch, 'g').replace('reflink', inline.reflink).replace('nolink', inline.nolink).getRegex();
  /**
   * Normal Inline Grammar
   */

  inline.normal = merge({}, inline);
  /**
   * Pedantic Inline Grammar
   */

  inline.pedantic = merge({}, inline.normal, {
    strong: {
      start: /^__|\*\*/,
      middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
      endAst: /\*\*(?!\*)/g,
      endUnd: /__(?!_)/g
    },
    em: {
      start: /^_|\*/,
      middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,
      endAst: /\*(?!\*)/g,
      endUnd: /_(?!_)/g
    },
    link: edit(/^!?\[(label)\]\((.*?)\)/).replace('label', inline._label).getRegex(),
    reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace('label', inline._label).getRegex()
  });
  /**
   * GFM Inline Grammar
   */

  inline.gfm = merge({}, inline.normal, {
    escape: edit(inline.escape).replace('])', '~|])').getRegex(),
    _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,
    url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
    _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.!#$%&'*+\/=?_`{\|}~-]+@)))/
  });
  inline.gfm.url = edit(inline.gfm.url, 'i').replace('email', inline.gfm._extended_email).getRegex();
  /**
   * GFM + Line Breaks Inline Grammar
   */

  inline.breaks = merge({}, inline.gfm, {
    br: edit(inline.br).replace('{2,}', '*').getRegex(),
    text: edit(inline.gfm.text).replace('\\b_', '\\b_| {2,}\\n').replace(/\{2,\}/g, '*').getRegex()
  });

  /**
   * smartypants text replacement
   * @param {string} text
   */

  function smartypants(text) {
    return text // em-dashes
    .replace(/---/g, "\u2014") // en-dashes
    .replace(/--/g, "\u2013") // opening singles
    .replace(/(^|[-\u2014/(\[{"\s])'/g, "$1\u2018") // closing singles & apostrophes
    .replace(/'/g, "\u2019") // opening doubles
    .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1\u201C") // closing doubles
    .replace(/"/g, "\u201D") // ellipses
    .replace(/\.{3}/g, "\u2026");
  }
  /**
   * mangle email addresses
   * @param {string} text
   */


  function mangle(text) {
    var out = '',
        i,
        ch;
    var l = text.length;

    for (i = 0; i < l; i++) {
      ch = text.charCodeAt(i);

      if (Math.random() > 0.5) {
        ch = 'x' + ch.toString(16);
      }

      out += '&#' + ch + ';';
    }

    return out;
  }
  /**
   * Block Lexer
   */


  var Lexer = /*#__PURE__*/function () {
    function Lexer(options) {
      this.tokens = [];
      this.tokens.links = Object.create(null);
      this.options = options || exports.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
      };
      var 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 Lex Method
     */
    Lexer.lex = function lex(src, options) {
      var lexer = new Lexer(options);
      return lexer.lex(src);
    }
    /**
     * Static Lex Inline Method
     */
    ;

    Lexer.lexInline = function lexInline(src, options) {
      var lexer = new Lexer(options);
      return lexer.inlineTokens(src);
    }
    /**
     * Preprocessing
     */
    ;

    var _proto = Lexer.prototype;

    _proto.lex = function lex(src) {
      src = src.replace(/\r\n|\r/g, '\n');
      this.blockTokens(src, this.tokens);
      var next;

      while (next = this.inlineQueue.shift()) {
        this.inlineTokens(next.src, next.tokens);
      }

      return this.tokens;
    }
    /**
     * Lexing
     */
    ;

    _proto.blockTokens = function blockTokens(src, tokens) {
      var _this = this;

      if (tokens === void 0) {
        tokens = [];
      }

      if (this.options.pedantic) {
        src = src.replace(/\t/g, '    ').replace(/^ +$/gm, '');
      } else {
        src = src.replace(/^( *)(\t+)/gm, function (_, leading, tabs) {
          return leading + '    '.repeat(tabs.length);
        });
      }

      var token, lastToken, cutSrc, lastParagraphClipped;

      while (src) {
        if (this.options.extensions && this.options.extensions.block && this.options.extensions.block.some(function (extTokenizer) {
          if (token = extTokenizer.call({
            lexer: _this
          }, src, tokens)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            return true;
          }

          return false;
        })) {
          continue;
        } // newline


        if (token = this.tokenizer.space(src)) {
          src = src.substring(token.raw.length);

          if (token.raw.length === 1 && tokens.length > 0) {
            // if there's a single \n as a spacer, it's terminating the last line,
            // so move it there so that we don't get unecessary paragraph tags
            tokens[tokens.length - 1].raw += '\n';
          } else {
            tokens.push(token);
          }

          continue;
        } // code


        if (token = this.tokenizer.code(src)) {
          src = src.substring(token.raw.length);
          lastToken = tokens[tokens.length - 1]; // An indented code block cannot interrupt a paragraph.

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


        if (token = this.tokenizer.fences(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // heading


        if (token = this.tokenizer.heading(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // hr


        if (token = this.tokenizer.hr(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // blockquote


        if (token = this.tokenizer.blockquote(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // list


        if (token = this.tokenizer.list(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // html


        if (token = this.tokenizer.html(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // def


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


        if (token = this.tokenizer.table(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // lheading


        if (token = this.tokenizer.lheading(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // top-level paragraph
        // prevent paragraph consuming extensions by clipping 'src' to extension start


        cutSrc = src;

        if (this.options.extensions && this.options.extensions.startBlock) {
          (function () {
            var startIndex = Infinity;
            var tempSrc = src.slice(1);
            var tempStart = void 0;

            _this.options.extensions.startBlock.forEach(function (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;
        } // text


        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) {
          var 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;
    };

    _proto.inline = function inline(src, tokens) {
      this.inlineQueue.push({
        src: src,
        tokens: tokens
      });
    }
    /**
     * Lexing/Compiling
     */
    ;

    _proto.inlineTokens = function inlineTokens(src, tokens) {
      var _this2 = this;

      if (tokens === void 0) {
        tokens = [];
      }

      var token, lastToken, cutSrc; // String with links masked to avoid interference with em and strong

      var maskedSrc = src;
      var match;
      var keepPrevChar, prevChar; // Mask out reflinks

      if (this.tokens.links) {
        var 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) + '[' + repeatString('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
            }
          }
        }
      } // Mask out other blocks


      while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
        maskedSrc = maskedSrc.slice(0, match.index) + '[' + repeatString('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
      } // Mask out escaped em & strong delimiters


      while ((match = this.tokenizer.rules.inline.escapedEmSt.exec(maskedSrc)) != null) {
        maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex);
      }

      while (src) {
        if (!keepPrevChar) {
          prevChar = '';
        }

        keepPrevChar = false; // extensions

        if (this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some(function (extTokenizer) {
          if (token = extTokenizer.call({
            lexer: _this2
          }, src, tokens)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            return true;
          }

          return false;
        })) {
          continue;
        } // escape


        if (token = this.tokenizer.escape(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // tag


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


        if (token = this.tokenizer.link(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // reflink, nolink


        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;
        } // em & strong


        if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // code


        if (token = this.tokenizer.codespan(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // br


        if (token = this.tokenizer.br(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // del (gfm)


        if (token = this.tokenizer.del(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // autolink


        if (token = this.tokenizer.autolink(src, mangle)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // url (gfm)


        if (!this.state.inLink && (token = this.tokenizer.url(src, mangle))) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // text
        // prevent inlineText consuming extensions by clipping 'src' to extension start


        cutSrc = src;

        if (this.options.extensions && this.options.extensions.startInline) {
          (function () {
            var startIndex = Infinity;
            var tempSrc = src.slice(1);
            var tempStart = void 0;

            _this2.options.extensions.startInline.forEach(function (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, smartypants)) {
          src = src.substring(token.raw.length);

          if (token.raw.slice(-1) !== '_') {
            // Track prevChar before string of ____ started
            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) {
          var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);

          if (this.options.silent) {
            console.error(errMsg);
            break;
          } else {
            throw new Error(errMsg);
          }
        }
      }

      return tokens;
    };

    _createClass(Lexer, null, [{
      key: "rules",
      get: function get() {
        return {
          block: block,
          inline: inline
        };
      }
    }]);

    return Lexer;
  }();

  /**
   * Renderer
   */

  var Renderer = /*#__PURE__*/function () {
    function Renderer(options) {
      this.options = options || exports.defaults;
    }

    var _proto = Renderer.prototype;

    _proto.code = function code(_code, infostring, escaped) {
      var lang = (infostring || '').match(/\S*/)[0];

      if (this.options.highlight) {
        var out = this.options.highlight(_code, lang);

        if (out != null && out !== _code) {
          escaped = true;
          _code = out;
        }
      }

      _code = _code.replace(/\n$/, '') + '\n';

      if (!lang) {
        return '<pre><code>' + (escaped ? _code : escape(_code, true)) + '</code></pre>\n';
      }

      return '<pre><code class="' + this.options.langPrefix + escape(lang, true) + '">' + (escaped ? _code : escape(_code, true)) + '</code></pre>\n';
    }
    /**
     * @param {string} quote
     */
    ;

    _proto.blockquote = function blockquote(quote) {
      return "<blockquote>\n" + quote + "</blockquote>\n";
    };

    _proto.html = function html(_html) {
      return _html;
    }
    /**
     * @param {string} text
     * @param {string} level
     * @param {string} raw
     * @param {any} slugger
     */
    ;

    _proto.heading = function heading(text, level, raw, slugger) {
      if (this.options.headerIds) {
        var id = this.options.headerPrefix + slugger.slug(raw);
        return "<h" + level + " id=\"" + id + "\">" + text + "</h" + level + ">\n";
      } // ignore IDs


      return "<h" + level + ">" + text + "</h" + level + ">\n";
    };

    _proto.hr = function hr() {
      return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
    };

    _proto.list = function list(body, ordered, start) {
      var type = ordered ? 'ol' : 'ul',
          startatt = ordered && start !== 1 ? ' start="' + start + '"' : '';
      return '<' + type + startatt + '>\n' + body + '</' + type + '>\n';
    }
    /**
     * @param {string} text
     */
    ;

    _proto.listitem = function listitem(text) {
      return "<li>" + text + "</li>\n";
    };

    _proto.checkbox = function checkbox(checked) {
      return '<input ' + (checked ? 'checked="" ' : '') + 'disabled="" type="checkbox"' + (this.options.xhtml ? ' /' : '') + '> ';
    }
    /**
     * @param {string} text
     */
    ;

    _proto.paragraph = function paragraph(text) {
      return "<p>" + text + "</p>\n";
    }
    /**
     * @param {string} header
     * @param {string} body
     */
    ;

    _proto.table = function table(header, body) {
      if (body) body = "<tbody>" + body + "</tbody>";
      return '<table>\n' + '<thead>\n' + header + '</thead>\n' + body + '</table>\n';
    }
    /**
     * @param {string} content
     */
    ;

    _proto.tablerow = function tablerow(content) {
      return "<tr>\n" + content + "</tr>\n";
    };

    _proto.tablecell = function tablecell(content, flags) {
      var type = flags.header ? 'th' : 'td';
      var tag = flags.align ? "<" + type + " align=\"" + flags.align + "\">" : "<" + type + ">";
      return tag + content + ("</" + type + ">\n");
    }
    /**
     * span level renderer
     * @param {string} text
     */
    ;

    _proto.strong = function strong(text) {
      return "<strong>" + text + "</strong>";
    }
    /**
     * @param {string} text
     */
    ;

    _proto.em = function em(text) {
      return "<em>" + text + "</em>";
    }
    /**
     * @param {string} text
     */
    ;

    _proto.codespan = function codespan(text) {
      return "<code>" + text + "</code>";
    };

    _proto.br = function br() {
      return this.options.xhtml ? '<br/>' : '<br>';
    }
    /**
     * @param {string} text
     */
    ;

    _proto.del = function del(text) {
      return "<del>" + text + "</del>";
    }
    /**
     * @param {string} href
     * @param {string} title
     * @param {string} text
     */
    ;

    _proto.link = function link(href, title, text) {
      href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);

      if (href === null) {
        return text;
      }

      var out = '<a href="' + escape(href) + '"';

      if (title) {
        out += ' title="' + title + '"';
      }

      out += '>' + text + '</a>';
      return out;
    }
    /**
     * @param {string} href
     * @param {string} title
     * @param {string} text
     */
    ;

    _proto.image = function image(href, title, text) {
      href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);

      if (href === null) {
        return text;
      }

      var out = "<img src=\"" + href + "\" alt=\"" + text + "\"";

      if (title) {
        out += " title=\"" + title + "\"";
      }

      out += this.options.xhtml ? '/>' : '>';
      return out;
    };

    _proto.text = function text(_text) {
      return _text;
    };

    return Renderer;
  }();

  /**
   * TextRenderer
   * returns only the textual part of the token
   */
  var TextRenderer = /*#__PURE__*/function () {
    function TextRenderer() {}

    var _proto = TextRenderer.prototype;

    // no need for block level renderers
    _proto.strong = function strong(text) {
      return text;
    };

    _proto.em = function em(text) {
      return text;
    };

    _proto.codespan = function codespan(text) {
      return text;
    };

    _proto.del = function del(text) {
      return text;
    };

    _proto.html = function html(text) {
      return text;
    };

    _proto.text = function text(_text) {
      return _text;
    };

    _proto.link = function link(href, title, text) {
      return '' + text;
    };

    _proto.image = function image(href, title, text) {
      return '' + text;
    };

    _proto.br = function br() {
      return '';
    };

    return TextRenderer;
  }();

  /**
   * Slugger generates header id
   */
  var Slugger = /*#__PURE__*/function () {
    function Slugger() {
      this.seen = {};
    }
    /**
     * @param {string} value
     */


    var _proto = Slugger.prototype;

    _proto.serialize = function serialize(value) {
      return value.toLowerCase().trim() // remove html tags
      .replace(/<[!\/a-z].*?>/ig, '') // remove unwanted chars
      .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '').replace(/\s/g, '-');
    }
    /**
     * Finds the next safe (unique) slug to use
     * @param {string} originalSlug
     * @param {boolean} isDryRun
     */
    ;

    _proto.getNextSafeSlug = function getNextSafeSlug(originalSlug, isDryRun) {
      var slug = originalSlug;
      var occurenceAccumulator = 0;

      if (this.seen.hasOwnProperty(slug)) {
        occurenceAccumulator = this.seen[originalSlug];

        do {
          occurenceAccumulator++;
          slug = originalSlug + '-' + occurenceAccumulator;
        } while (this.seen.hasOwnProperty(slug));
      }

      if (!isDryRun) {
        this.seen[originalSlug] = occurenceAccumulator;
        this.seen[slug] = 0;
      }

      return slug;
    }
    /**
     * Convert string to unique id
     * @param {object} [options]
     * @param {boolean} [options.dryrun] Generates the next unique slug without
     * updating the internal accumulator.
     */
    ;

    _proto.slug = function slug(value, options) {
      if (options === void 0) {
        options = {};
      }

      var slug = this.serialize(value);
      return this.getNextSafeSlug(slug, options.dryrun);
    };

    return Slugger;
  }();

  /**
   * Parsing & Compiling
   */

  var Parser = /*#__PURE__*/function () {
    function Parser(options) {
      this.options = options || exports.defaults;
      this.options.renderer = this.options.renderer || new Renderer();
      this.renderer = this.options.renderer;
      this.renderer.options = this.options;
      this.textRenderer = new TextRenderer();
      this.slugger = new Slugger();
    }
    /**
     * Static Parse Method
     */


    Parser.parse = function parse(tokens, options) {
      var parser = new Parser(options);
      return parser.parse(tokens);
    }
    /**
     * Static Parse Inline Method
     */
    ;

    Parser.parseInline = function parseInline(tokens, options) {
      var parser = new Parser(options);
      return parser.parseInline(tokens);
    }
    /**
     * Parse Loop
     */
    ;

    var _proto = Parser.prototype;

    _proto.parse = function parse(tokens, top) {
      if (top === void 0) {
        top = true;
      }

      var out = '',
          i,
          j,
          k,
          l2,
          l3,
          row,
          cell,
          header,
          body,
          token,
          ordered,
          start,
          loose,
          itemBody,
          item,
          checked,
          task,
          checkbox,
          ret;
      var l = tokens.length;

      for (i = 0; i < l; i++) {
        token = tokens[i]; // Run any renderer extensions

        if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
          ret = this.options.extensions.renderers[token.type].call({
            parser: this
          }, token);

          if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(token.type)) {
            out += ret || '';
            continue;
          }
        }

        switch (token.type) {
          case 'space':
            {
              continue;
            }

          case 'hr':
            {
              out += this.renderer.hr();
              continue;
            }

          case 'heading':
            {
              out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape(this.parseInline(token.tokens, this.textRenderer)), this.slugger);
              continue;
            }

          case 'code':
            {
              out += this.renderer.code(token.text, token.lang, token.escaped);
              continue;
            }

          case 'table':
            {
              header = ''; // header

              cell = '';
              l2 = token.header.length;

              for (j = 0; j < l2; j++) {
                cell += this.renderer.tablecell(this.parseInline(token.header[j].tokens), {
                  header: true,
                  align: token.align[j]
                });
              }

              header += this.renderer.tablerow(cell);
              body = '';
              l2 = token.rows.length;

              for (j = 0; j < l2; j++) {
                row = token.rows[j];
                cell = '';
                l3 = row.length;

                for (k = 0; k < l3; k++) {
                  cell += this.renderer.tablecell(this.parseInline(row[k].tokens), {
                    header: false,
                    align: token.align[k]
                  });
                }

                body += this.renderer.tablerow(cell);
              }

              out += this.renderer.table(header, body);
              continue;
            }

          case 'blockquote':
            {
              body = this.parse(token.tokens);
              out += this.renderer.blockquote(body);
              continue;
            }

          case 'list':
            {
              ordered = token.ordered;
              start = token.start;
              loose = token.loose;
              l2 = token.items.length;
              body = '';

              for (j = 0; j < l2; j++) {
                item = token.items[j];
                checked = item.checked;
                task = item.task;
                itemBody = '';

                if (item.task) {
                  checkbox = this.renderer.checkbox(checked);

                  if (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',
                        text: checkbox
                      });
                    }
                  } else {
                    itemBody += checkbox;
                  }
                }

                itemBody += this.parse(item.tokens, loose);
                body += this.renderer.listitem(itemBody, task, checked);
              }

              out += this.renderer.list(body, ordered, start);
              continue;
            }

          case 'html':
            {
              // TODO parse inline content if parameter markdown=1
              out += this.renderer.html(token.text);
              continue;
            }

          case 'paragraph':
            {
              out += this.renderer.paragraph(this.parseInline(token.tokens));
              continue;
            }

          case 'text':
            {
              body = token.tokens ? this.parseInline(token.tokens) : token.text;

              while (i + 1 < l && tokens[i + 1].type === 'text') {
                token = tokens[++i];
                body += '\n' + (token.tokens ? this.parseInline(token.tokens) : token.text);
              }

              out += top ? this.renderer.paragraph(body) : body;
              continue;
            }

          default:
            {
              var 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
     */
    ;

    _proto.parseInline = function parseInline(tokens, renderer) {
      renderer = renderer || this.renderer;
      var out = '',
          i,
          token,
          ret;
      var l = tokens.length;

      for (i = 0; i < l; i++) {
        token = tokens[i]; // Run any renderer extensions

        if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
          ret = this.options.extensions.renderers[token.type].call({
            parser: this
          }, token);

          if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(token.type)) {
            out += ret || '';
            continue;
          }
        }

        switch (token.type) {
          case 'escape':
            {
              out += renderer.text(token.text);
              break;
            }

          case 'html':
            {
              out += renderer.html(token.text);
              break;
            }

          case 'link':
            {
              out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer));
              break;
            }

          case 'image':
            {
              out += renderer.image(token.href, token.title, token.text);
              break;
            }

          case 'strong':
            {
              out += renderer.strong(this.parseInline(token.tokens, renderer));
              break;
            }

          case 'em':
            {
              out += renderer.em(this.parseInline(token.tokens, renderer));
              break;
            }

          case 'codespan':
            {
              out += renderer.codespan(token.text);
              break;
            }

          case 'br':
            {
              out += renderer.br();
              break;
            }

          case 'del':
            {
              out += renderer.del(this.parseInline(token.tokens, renderer));
              break;
            }

          case 'text':
            {
              out += renderer.text(token.text);
              break;
            }

          default:
            {
              var errMsg = 'Token with "' + token.type + '" type was not found.';

              if (this.options.silent) {
                console.error(errMsg);
                return;
              } else {
                throw new Error(errMsg);
              }
            }
        }
      }

      return out;
    };

    return Parser;
  }();

  /**
   * Marked
   */

  function marked(src, opt, callback) {
    // throw error in case of non string input
    if (typeof src === 'undefined' || src === null) {
      throw new Error('marked(): input parameter is undefined or null');
    }

    if (typeof src !== 'string') {
      throw new Error('marked(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected');
    }

    if (typeof opt === 'function') {
      callback = opt;
      opt = null;
    }

    opt = merge({}, marked.defaults, opt || {});
    checkSanitizeDeprecation(opt);

    if (callback) {
      var highlight = opt.highlight;
      var tokens;

      try {
        tokens = Lexer.lex(src, opt);
      } catch (e) {
        return callback(e);
      }

      var done = function done(err) {
        var out;

        if (!err) {
          try {
            if (opt.walkTokens) {
              marked.walkTokens(tokens, opt.walkTokens);
            }

            out = Parser.parse(tokens, opt);
          } catch (e) {
            err = e;
          }
        }

        opt.highlight = highlight;
        return err ? callback(err) : callback(null, out);
      };

      if (!highlight || highlight.length < 3) {
        return done();
      }

      delete opt.highlight;
      if (!tokens.length) return done();
      var pending = 0;
      marked.walkTokens(tokens, function (token) {
        if (token.type === 'code') {
          pending++;
          setTimeout(function () {
            highlight(token.text, token.lang, function (err, code) {
              if (err) {
                return done(err);
              }

              if (code != null && code !== token.text) {
                token.text = code;
                token.escaped = true;
              }

              pending--;

              if (pending === 0) {
                done();
              }
            });
          }, 0);
        }
      });

      if (pending === 0) {
        done();
      }

      return;
    }

    try {
      var _tokens = Lexer.lex(src, opt);

      if (opt.walkTokens) {
        marked.walkTokens(_tokens, opt.walkTokens);
      }

      return Parser.parse(_tokens, opt);
    } catch (e) {
      e.message += '\nPlease report this to https://github.com/markedjs/marked.';

      if (opt.silent) {
        return '<p>An error occurred:</p><pre>' + escape(e.message + '', true) + '</pre>';
      }

      throw e;
    }
  }
  /**
   * Options
   */

  marked.options = marked.setOptions = function (opt) {
    merge(marked.defaults, opt);
    changeDefaults(marked.defaults);
    return marked;
  };

  marked.getDefaults = getDefaults;
  marked.defaults = exports.defaults;
  /**
   * Use Extension
   */

  marked.use = function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    var opts = merge.apply(void 0, [{}].concat(args));
    var extensions = marked.defaults.extensions || {
      renderers: {},
      childTokens: {}
    };
    var hasExtensions;
    args.forEach(function (pack) {
      // ==-- Parse "addon" extensions --== //
      if (pack.extensions) {
        hasExtensions = true;
        pack.extensions.forEach(function (ext) {
          if (!ext.name) {
            throw new Error('extension name required');
          }

          if (ext.renderer) {
            // Renderer extensions
            var prevRenderer = extensions.renderers ? extensions.renderers[ext.name] : null;

            if (prevRenderer) {
              // Replace extension with func to run new extension but fall back if false
              extensions.renderers[ext.name] = function () {
                for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                  args[_key2] = arguments[_key2];
                }

                var ret = ext.renderer.apply(this, args);

                if (ret === false) {
                  ret = prevRenderer.apply(this, args);
                }

                return ret;
              };
            } else {
              extensions.renderers[ext.name] = ext.renderer;
            }
          }

          if (ext.tokenizer) {
            // Tokenizer Extensions
            if (!ext.level || ext.level !== 'block' && ext.level !== 'inline') {
              throw new Error("extension level must be 'block' or 'inline'");
            }

            if (extensions[ext.level]) {
              extensions[ext.level].unshift(ext.tokenizer);
            } else {
              extensions[ext.level] = [ext.tokenizer];
            }

            if (ext.start) {
              // Function to check for start of token
              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 (ext.childTokens) {
            // Child tokens to be visited by walkTokens
            extensions.childTokens[ext.name] = ext.childTokens;
          }
        });
      } // ==-- Parse "overwrite" extensions --== //


      if (pack.renderer) {
        (function () {
          var renderer = marked.defaults.renderer || new Renderer();

          var _loop = function _loop(prop) {
            var prevRenderer = renderer[prop]; // Replace renderer with func to run extension, but fall back if false

            renderer[prop] = function () {
              for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
                args[_key3] = arguments[_key3];
              }

              var ret = pack.renderer[prop].apply(renderer, args);

              if (ret === false) {
                ret = prevRenderer.apply(renderer, args);
              }

              return ret;
            };
          };

          for (var prop in pack.renderer) {
            _loop(prop);
          }

          opts.renderer = renderer;
        })();
      }

      if (pack.tokenizer) {
        (function () {
          var tokenizer = marked.defaults.tokenizer || new Tokenizer();

          var _loop2 = function _loop2(prop) {
            var prevTokenizer = tokenizer[prop]; // Replace tokenizer with func to run extension, but fall back if false

            tokenizer[prop] = function () {
              for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
                args[_key4] = arguments[_key4];
              }

              var ret = pack.tokenizer[prop].apply(tokenizer, args);

              if (ret === false) {
                ret = prevTokenizer.apply(tokenizer, args);
              }

              return ret;
            };
          };

          for (var prop in pack.tokenizer) {
            _loop2(prop);
          }

          opts.tokenizer = tokenizer;
        })();
      } // ==-- Parse WalkTokens extensions --== //


      if (pack.walkTokens) {
        var _walkTokens = marked.defaults.walkTokens;

        opts.walkTokens = function (token) {
          pack.walkTokens.call(this, token);

          if (_walkTokens) {
            _walkTokens.call(this, token);
          }
        };
      }

      if (hasExtensions) {
        opts.extensions = extensions;
      }

      marked.setOptions(opts);
    });
  };
  /**
   * Run callback for every token
   */


  marked.walkTokens = function (tokens, callback) {
    var _loop3 = function _loop3() {
      var token = _step.value;
      callback.call(marked, token);

      switch (token.type) {
        case 'table':
          {
            for (var _iterator2 = _createForOfIteratorHelperLoose(token.header), _step2; !(_step2 = _iterator2()).done;) {
              var cell = _step2.value;
              marked.walkTokens(cell.tokens, callback);
            }

            for (var _iterator3 = _createForOfIteratorHelperLoose(token.rows), _step3; !(_step3 = _iterator3()).done;) {
              var row = _step3.value;

              for (var _iterator4 = _createForOfIteratorHelperLoose(row), _step4; !(_step4 = _iterator4()).done;) {
                var _cell = _step4.value;
                marked.walkTokens(_cell.tokens, callback);
              }
            }

            break;
          }

        case 'list':
          {
            marked.walkTokens(token.items, callback);
            break;
          }

        default:
          {
            if (marked.defaults.extensions && marked.defaults.extensions.childTokens && marked.defaults.extensions.childTokens[token.type]) {
              // Walk any extensions
              marked.defaults.extensions.childTokens[token.type].forEach(function (childTokens) {
                marked.walkTokens(token[childTokens], callback);
              });
            } else if (token.tokens) {
              marked.walkTokens(token.tokens, callback);
            }
          }
      }
    };

    for (var _iterator = _createForOfIteratorHelperLoose(tokens), _step; !(_step = _iterator()).done;) {
      _loop3();
    }
  };
  /**
   * Parse Inline
   * @param {string} src
   */


  marked.parseInline = function (src, opt) {
    // throw error in case of non string input
    if (typeof src === 'undefined' || src === null) {
      throw new Error('marked.parseInline(): input parameter is undefined or null');
    }

    if (typeof src !== 'string') {
      throw new Error('marked.parseInline(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected');
    }

    opt = merge({}, marked.defaults, opt || {});
    checkSanitizeDeprecation(opt);

    try {
      var tokens = Lexer.lexInline(src, opt);

      if (opt.walkTokens) {
        marked.walkTokens(tokens, opt.walkTokens);
      }

      return Parser.parseInline(tokens, opt);
    } catch (e) {
      e.message += '\nPlease report this to https://github.com/markedjs/marked.';

      if (opt.silent) {
        return '<p>An error occurred:</p><pre>' + escape(e.message + '', true) + '</pre>';
      }

      throw e;
    }
  };
  /**
   * Expose
   */


  marked.Parser = Parser;
  marked.parser = Parser.parse;
  marked.Renderer = Renderer;
  marked.TextRenderer = TextRenderer;
  marked.Lexer = Lexer;
  marked.lexer = Lexer.lex;
  marked.Tokenizer = Tokenizer;
  marked.Slugger = Slugger;
  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;

  exports.Lexer = Lexer;
  exports.Parser = Parser;
  exports.Renderer = Renderer;
  exports.Slugger = Slugger;
  exports.TextRenderer = TextRenderer;
  exports.Tokenizer = Tokenizer;
  exports.getDefaults = getDefaults;
  exports.lexer = lexer;
  exports.marked = marked;
  exports.options = options;
  exports.parse = parse;
  exports.parseInline = parseInline;
  exports.parser = parser;
  exports.setOptions = setOptions;
  exports.use = use;
  exports.walkTokens = walkTokens;

  Object.defineProperty(exports, '__esModule', { value: true });

}));

// ESM-uncomment-begin
})();
var marked = (__marked_exports || exports);
// ESM-uncomment-end

;// ../../node_modules/monaco-editor/esm/vs/base/common/marshalling.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


function parse(text) {
    let data = JSON.parse(text);
    data = revive(data);
    return data;
}
function revive(obj, depth = 0) {
    if (!obj || depth > 200) {
        return obj;
    }
    if (typeof obj === 'object') {
        switch (obj.$mid) {
            case 1 /* MarshalledId.Uri */: return URI.revive(obj);
            case 2 /* MarshalledId.Regexp */: return new RegExp(obj.source, obj.flags);
            case 14 /* MarshalledId.Date */: return new Date(obj.source);
        }
        if (obj instanceof VSBuffer
            || obj instanceof Uint8Array) {
            return obj;
        }
        if (Array.isArray(obj)) {
            for (let i = 0; i < obj.length; ++i) {
                obj[i] = revive(obj[i], depth + 1);
            }
        }
        else {
            // walk object
            for (const key in obj) {
                if (Object.hasOwnProperty.call(obj, key)) {
                    obj[key] = revive(obj[key], depth + 1);
                }
            }
        }
    }
    return obj;
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/markdownRenderer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



















/**
 * Low-level way create a html element from a markdown string.
 *
 * **Note** that for most cases you should be using [`MarkdownRenderer`](./src/vs/editor/contrib/markdownRenderer/browser/markdownRenderer.ts)
 * which comes with support for pretty code block rendering and which uses the default way of handling links.
 */
function renderMarkdown(markdown, options = {}, markedOptions = {}) {
    var _a;
    const disposables = new DisposableStore();
    let isDisposed = false;
    const element = createElement(options);
    const _uriMassage = function (part) {
        let data;
        try {
            data = parse(decodeURIComponent(part));
        }
        catch (e) {
            // ignore
        }
        if (!data) {
            return part;
        }
        data = cloneAndChange(data, value => {
            if (markdown.uris && markdown.uris[value]) {
                return URI.revive(markdown.uris[value]);
            }
            else {
                return undefined;
            }
        });
        return encodeURIComponent(JSON.stringify(data));
    };
    const _href = function (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);
            }
            // this URI will end up as "src"-attribute of a dom node
            // and because of that special rewriting needs to be done
            // so that the URI uses a protocol that's understood by
            // browsers (like http or https)
            return FileAccess.asBrowserUri(uri).toString(true);
        }
        if (!uri) {
            return href;
        }
        if (URI.parse(href).toString() === uri.toString()) {
            return href; // no transformation performed
        }
        if (uri.query) {
            uri = uri.with({ query: _uriMassage(uri.query) });
        }
        return uri.toString();
    };
    const renderer = new marked.Renderer();
    renderer.image = (href, title, text) => {
        let dimensions = [];
        let attributes = [];
        if (href) {
            ({ href, dimensions } = parseHrefAndDimensions(href));
            attributes.push(`src="${escapeDoubleQuotes(href)}"`);
        }
        if (text) {
            attributes.push(`alt="${escapeDoubleQuotes(text)}"`);
        }
        if (title) {
            attributes.push(`title="${escapeDoubleQuotes(title)}"`);
        }
        if (dimensions.length) {
            attributes = attributes.concat(dimensions);
        }
        return '<img ' + attributes.join(' ') + '>';
    };
    renderer.link = (href, title, text) => {
        if (typeof href !== 'string') {
            return '';
        }
        // Remove markdown escapes. Workaround for https://github.com/chjj/marked/issues/829
        if (href === text) { // raw link case
            text = removeMarkdownEscapes(text);
        }
        title = typeof title === 'string' ? escapeDoubleQuotes(removeMarkdownEscapes(title)) : '';
        href = removeMarkdownEscapes(href);
        // HTML Encode 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}">${text}</a>`;
    };
    renderer.paragraph = (text) => {
        return `<p>${text}</p>`;
    };
    // Will collect [id, renderedElement] tuples
    const codeBlocks = [];
    if (options.codeBlockRenderer) {
        renderer.code = (code, lang) => {
            const id = defaultGenerator.nextId();
            const value = options.codeBlockRenderer(lang !== null && lang !== void 0 ? lang : '', code);
            codeBlocks.push(value.then(element => [id, element]));
            return `<div class="code" data-code="${id}">${strings_escape(code)}</div>`;
        };
    }
    if (options.actionHandler) {
        const onClick = options.actionHandler.disposables.add(new DomEmitter(element, 'click'));
        const onAuxClick = options.actionHandler.disposables.add(new DomEmitter(element, 'auxclick'));
        options.actionHandler.disposables.add(Event.any(onClick.event, onAuxClick.event)(e => {
            const mouseEvent = new StandardMouseEvent(e);
            if (!mouseEvent.leftButton && !mouseEvent.middleButton) {
                return;
            }
            let target = mouseEvent.target;
            if (target.tagName !== 'A') {
                target = target.parentElement;
                if (!target || target.tagName !== 'A') {
                    return;
                }
            }
            try {
                let href = target.dataset['href'];
                if (href) {
                    if (markdown.baseUri) {
                        href = resolveWithBaseUri(URI.from(markdown.baseUri), href);
                    }
                    options.actionHandler.callback(href, mouseEvent);
                }
            }
            catch (err) {
                onUnexpectedError(err);
            }
            finally {
                mouseEvent.preventDefault();
            }
        }));
    }
    if (!markdown.supportHtml) {
        // TODO: Can we deprecated this in favor of 'supportHtml'?
        // Use our own sanitizer so that we can let through only spans.
        // Otherwise, we'd be letting all html be rendered.
        // If we want to allow markdown permitted tags, then we can delete sanitizer and sanitize.
        // We always pass the output through dompurify after this so that we don't rely on
        // marked for sanitization.
        markedOptions.sanitizer = (html) => {
            const match = markdown.isTrusted ? html.match(/^(<span[^>]+>)|(<\/\s*span>)$/) : undefined;
            return match ? html : '';
        };
        markedOptions.sanitize = true;
        markedOptions.silent = true;
    }
    markedOptions.renderer = renderer;
    // values that are too long will freeze the UI
    let value = (_a = markdown.value) !== null && _a !== void 0 ? _a : '';
    if (value.length > 100000) {
        value = `${value.substr(0, 100000)}…`;
    }
    // escape theme icons
    if (markdown.supportThemeIcons) {
        value = markdownEscapeEscapedIcons(value);
    }
    let renderedMarkdown = marked.parse(value, markedOptions);
    // Rewrite theme icons
    if (markdown.supportThemeIcons) {
        const elements = renderLabelWithIcons(renderedMarkdown);
        renderedMarkdown = elements.map(e => typeof e === 'string' ? e : e.outerHTML).join('');
    }
    const htmlParser = new DOMParser();
    const markdownHtmlDoc = htmlParser.parseFromString(sanitizeRenderedMarkdown(markdown, renderedMarkdown), 'text/html');
    markdownHtmlDoc.body.querySelectorAll('img')
        .forEach(img => {
        const src = img.getAttribute('src'); // Get the raw 'src' attribute value as text, not the resolved 'src'
        if (src) {
            let href = src;
            try {
                if (markdown.baseUri) { // absolute or relative local path, or file: uri
                    href = resolveWithBaseUri(URI.from(markdown.baseUri), href);
                }
            }
            catch (err) { }
            img.src = _href(href, true);
        }
    });
    markdownHtmlDoc.body.querySelectorAll('a')
        .forEach(a => {
        const href = a.getAttribute('href'); // Get the raw 'href' attribute value as text, not the resolved 'href'
        a.setAttribute('href', ''); // Clear out href. We use the `data-href` for handling clicks instead
        if (!href
            || /^data:|javascript:/i.test(href)
            || (/^command:/i.test(href) && !markdown.isTrusted)
            || /^command:(\/\/\/)?_workbench\.downloadResource/i.test(href)) {
            // drop the link
            a.replaceWith(...a.childNodes);
        }
        else {
            let resolvedHref = _href(href, false);
            if (markdown.baseUri) {
                resolvedHref = resolveWithBaseUri(URI.from(markdown.baseUri), href);
            }
            a.dataset.href = resolvedHref;
        }
    });
    element.innerHTML = sanitizeRenderedMarkdown(markdown, markdownHtmlDoc.body.innerHTML);
    if (codeBlocks.length > 0) {
        Promise.all(codeBlocks).then((tuples) => {
            var _a, _b;
            if (isDisposed) {
                return;
            }
            const renderedElements = new Map(tuples);
            const placeholderElements = element.querySelectorAll(`div[data-code]`);
            for (const placeholderElement of placeholderElements) {
                const renderedElement = renderedElements.get((_a = placeholderElement.dataset['code']) !== null && _a !== void 0 ? _a : '');
                if (renderedElement) {
                    dom_reset(placeholderElement, renderedElement);
                }
            }
            (_b = options.asyncRenderCallback) === null || _b === void 0 ? void 0 : _b.call(options);
        });
    }
    // signal size changes for image tags
    if (options.asyncRenderCallback) {
        for (const img of element.getElementsByTagName('img')) {
            const listener = disposables.add(addDisposableListener(img, 'load', () => {
                listener.dispose();
                options.asyncRenderCallback();
            }));
        }
    }
    return {
        element,
        dispose: () => {
            isDisposed = true;
            disposables.dispose();
        }
    };
}
function resolveWithBaseUri(baseUri, href) {
    const hasScheme = /^\w[\w\d+.-]*:/.test(href);
    if (hasScheme) {
        return href;
    }
    if (baseUri.path.endsWith('/')) {
        return resolvePath(baseUri, href).toString();
    }
    else {
        return resolvePath(dirname(baseUri), href).toString();
    }
}
function sanitizeRenderedMarkdown(options, renderedMarkdown) {
    const { config, allowedSchemes } = getSanitizerOptions(options);
    addHook('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]+;)?(background-color\:#[0-9a-fA-F]+;)?$/.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;
        }
    });
    const hook = hookDomPurifyHrefAndSrcSanitizer(allowedSchemes);
    try {
        return sanitize(renderedMarkdown, Object.assign(Object.assign({}, config), { RETURN_TRUSTED_TYPE: true }));
    }
    finally {
        removeHook('uponSanitizeAttribute');
        hook.dispose();
    }
}
function getSanitizerOptions(options) {
    const allowedSchemes = [
        Schemas.http,
        Schemas.https,
        Schemas.mailto,
        Schemas.data,
        Schemas.file,
        Schemas.vscodeFileResource,
        Schemas.vscodeRemote,
        Schemas.vscodeRemoteResource,
    ];
    if (options.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: ['ul', 'li', 'p', 'b', 'i', 'code', 'blockquote', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'em', 'pre', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'div', 'del', 'a', 'strong', 'br', 'img', 'span'],
            ALLOWED_ATTR: ['href', 'data-href', 'target', 'title', 'src', 'alt', 'class', 'style', 'data-code', 'width', 'height', 'align'],
            ALLOW_UNKNOWN_PROTOCOLS: true,
        },
        allowedSchemes
    };
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/markdownRenderer/browser/markdownRenderer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var markdownRenderer_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var markdownRenderer_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var markdownRenderer_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
var markdownRenderer_a;









/**
 * Markdown renderer that can render codeblocks with the editor mechanics. This
 * renderer should always be preferred.
 */
let MarkdownRenderer = class MarkdownRenderer {
    constructor(_options, _languageService, _openerService) {
        this._options = _options;
        this._languageService = _languageService;
        this._openerService = _openerService;
        this._onDidRenderAsync = new Emitter();
        this.onDidRenderAsync = this._onDidRenderAsync.event;
    }
    dispose() {
        this._onDidRenderAsync.dispose();
    }
    render(markdown, options, markedOptions) {
        if (!markdown) {
            const element = document.createElement('span');
            return { element, dispose: () => { } };
        }
        const disposables = new DisposableStore();
        const rendered = disposables.add(renderMarkdown(markdown, Object.assign(Object.assign({}, this._getRenderOptions(markdown, disposables)), options), markedOptions));
        return {
            element: rendered.element,
            dispose: () => disposables.dispose()
        };
    }
    _getRenderOptions(markdown, disposables) {
        return {
            codeBlockRenderer: (languageAlias, value) => markdownRenderer_awaiter(this, void 0, void 0, function* () {
                var _a, _b, _c;
                // In markdown,
                // it is possible that we stumble upon language aliases (e.g.js instead of javascript)
                // it is possible no alias is given in which case we fall back to the current editor lang
                let languageId;
                if (languageAlias) {
                    languageId = this._languageService.getLanguageIdByLanguageName(languageAlias);
                }
                else if (this._options.editor) {
                    languageId = (_a = this._options.editor.getModel()) === null || _a === void 0 ? void 0 : _a.getLanguageId();
                }
                if (!languageId) {
                    languageId = PLAINTEXT_LANGUAGE_ID;
                }
                const html = yield tokenizeToString(this._languageService, value, languageId);
                const element = document.createElement('span');
                element.innerHTML = ((_c = (_b = MarkdownRenderer._ttpTokenizer) === null || _b === void 0 ? void 0 : _b.createHTML(html)) !== null && _c !== void 0 ? _c : html);
                // use "good" font
                if (this._options.editor) {
                    const fontInfo = this._options.editor.getOption(46 /* EditorOption.fontInfo */);
                    applyFontInfo(element, fontInfo);
                }
                else if (this._options.codeBlockFontFamily) {
                    element.style.fontFamily = this._options.codeBlockFontFamily;
                }
                if (this._options.codeBlockFontSize !== undefined) {
                    element.style.fontSize = this._options.codeBlockFontSize;
                }
                return element;
            }),
            asyncRenderCallback: () => this._onDidRenderAsync.fire(),
            actionHandler: {
                callback: (content) => this._openerService.open(content, { fromUserGesture: true, allowContributedOpeners: true, allowCommands: markdown.isTrusted }).catch(onUnexpectedError),
                disposables: disposables
            }
        };
    }
};
MarkdownRenderer._ttpTokenizer = (markdownRenderer_a = window.trustedTypes) === null || markdownRenderer_a === void 0 ? void 0 : markdownRenderer_a.createPolicy('tokenizeToString', {
    createHTML(html) {
        return html;
    }
});
MarkdownRenderer = markdownRenderer_decorate([
    markdownRenderer_param(1, ILanguageService),
    markdownRenderer_param(2, IOpenerService)
], MarkdownRenderer);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/hover/browser/marginHover.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/








const marginHover_$ = dom_$;
class MarginHoverWidget extends Disposable {
    constructor(editor, languageService, openerService = NullOpenerService) {
        super();
        this._renderDisposeables = this._register(new DisposableStore());
        this._editor = editor;
        this._isVisible = false;
        this._messages = [];
        this._hover = this._register(new HoverWidget());
        this._hover.containerDomNode.classList.toggle('hidden', !this._isVisible);
        this._markdownRenderer = this._register(new MarkdownRenderer({ editor: this._editor }, languageService, openerService));
        this._computer = new MarginHoverComputer(this._editor);
        this._hoverOperation = this._register(new HoverOperation(this._editor, this._computer));
        this._register(this._hoverOperation.onResult((result) => {
            this._withResult(result.value);
        }));
        this._register(this._editor.onDidChangeModelDecorations(() => this._onModelDecorationsChanged()));
        this._register(this._editor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(46 /* EditorOption.fontInfo */)) {
                this._updateFont();
            }
        }));
        this._editor.addOverlayWidget(this);
    }
    dispose() {
        this._editor.removeOverlayWidget(this);
        super.dispose();
    }
    getId() {
        return MarginHoverWidget.ID;
    }
    getDomNode() {
        return this._hover.containerDomNode;
    }
    getPosition() {
        return null;
    }
    _updateFont() {
        const codeClasses = Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName('code'));
        codeClasses.forEach(node => this._editor.applyFontInfo(node));
    }
    _onModelDecorationsChanged() {
        if (this._isVisible) {
            // The decorations have changed and the hover is visible,
            // we need to recompute the displayed text
            this._hoverOperation.cancel();
            this._hoverOperation.start(0 /* HoverStartMode.Delayed */);
        }
    }
    startShowingAt(lineNumber) {
        if (this._computer.lineNumber === lineNumber) {
            // We have to show the widget at the exact same line number as before, so no work is needed
            return;
        }
        this._hoverOperation.cancel();
        this.hide();
        this._computer.lineNumber = lineNumber;
        this._hoverOperation.start(0 /* HoverStartMode.Delayed */);
    }
    hide() {
        this._computer.lineNumber = -1;
        this._hoverOperation.cancel();
        if (!this._isVisible) {
            return;
        }
        this._isVisible = false;
        this._hover.containerDomNode.classList.toggle('hidden', !this._isVisible);
    }
    _withResult(result) {
        this._messages = result;
        if (this._messages.length > 0) {
            this._renderMessages(this._computer.lineNumber, this._messages);
        }
        else {
            this.hide();
        }
    }
    _renderMessages(lineNumber, messages) {
        this._renderDisposeables.clear();
        const fragment = document.createDocumentFragment();
        for (const msg of messages) {
            const markdownHoverElement = marginHover_$('div.hover-row.markdown-hover');
            const hoverContentsElement = append(markdownHoverElement, marginHover_$('div.hover-contents'));
            const renderedContents = this._renderDisposeables.add(this._markdownRenderer.render(msg.value));
            hoverContentsElement.appendChild(renderedContents.element);
            fragment.appendChild(markdownHoverElement);
        }
        this._updateContents(fragment);
        this._showAt(lineNumber);
    }
    _updateContents(node) {
        this._hover.contentsDomNode.textContent = '';
        this._hover.contentsDomNode.appendChild(node);
        this._updateFont();
    }
    _showAt(lineNumber) {
        if (!this._isVisible) {
            this._isVisible = true;
            this._hover.containerDomNode.classList.toggle('hidden', !this._isVisible);
        }
        const editorLayout = this._editor.getLayoutInfo();
        const topForLineNumber = this._editor.getTopForLineNumber(lineNumber);
        const editorScrollTop = this._editor.getScrollTop();
        const lineHeight = this._editor.getOption(61 /* EditorOption.lineHeight */);
        const nodeHeight = this._hover.containerDomNode.clientHeight;
        const top = topForLineNumber - editorScrollTop - ((nodeHeight - lineHeight) / 2);
        this._hover.containerDomNode.style.left = `${editorLayout.glyphMarginLeft + editorLayout.glyphMarginWidth}px`;
        this._hover.containerDomNode.style.top = `${Math.max(Math.round(top), 0)}px`;
    }
}
MarginHoverWidget.ID = 'editor.contrib.modesGlyphHoverWidget';
class MarginHoverComputer {
    constructor(_editor) {
        this._editor = _editor;
        this._lineNumber = -1;
    }
    get lineNumber() {
        return this._lineNumber;
    }
    set lineNumber(value) {
        this._lineNumber = value;
    }
    computeSync() {
        const toHoverMessage = (contents) => {
            return {
                value: contents
            };
        };
        const lineDecorations = this._editor.getLineDecorations(this._lineNumber);
        const result = [];
        if (!lineDecorations) {
            return result;
        }
        for (const d of lineDecorations) {
            if (!d.options.glyphMarginClassName) {
                continue;
            }
            const hoverMessage = d.options.glyphMarginHoverMessage;
            if (!hoverMessage || isEmptyMarkdownString(hoverMessage)) {
                continue;
            }
            result.push(...asArray(hoverMessage).map(toHoverMessage));
        }
        return result;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/hover/browser/getHover.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var getHover_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};





class HoverProviderResult {
    constructor(provider, hover, ordinal) {
        this.provider = provider;
        this.hover = hover;
        this.ordinal = ordinal;
    }
}
function executeProvider(provider, ordinal, model, position, token) {
    return getHover_awaiter(this, void 0, void 0, function* () {
        try {
            const result = yield Promise.resolve(provider.provideHover(model, position, token));
            if (result && isValid(result)) {
                return new HoverProviderResult(provider, result, ordinal);
            }
        }
        catch (err) {
            onUnexpectedExternalError(err);
        }
        return undefined;
    });
}
function getHover(registry, model, position, token) {
    const providers = registry.ordered(model);
    const promises = providers.map((provider, index) => executeProvider(provider, index, model, position, token));
    return AsyncIterableObject.fromPromises(promises).coalesce();
}
function getHoverPromise(registry, model, position, token) {
    return getHover(registry, model, position, token).map(item => item.hover).toPromise();
}
registerModelAndPositionCommand('_executeHoverProvider', (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    return getHoverPromise(languageFeaturesService.hoverProvider, model, position, CancellationToken.None);
});
function isValid(result) {
    const hasRange = (typeof result.range !== 'undefined');
    const hasHtmlContent = typeof result.contents !== 'undefined' && result.contents && result.contents.length > 0;
    return hasRange && hasHtmlContent;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/hover/browser/markdownHoverParticipant.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var markdownHoverParticipant_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var markdownHoverParticipant_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};














const markdownHoverParticipant_$ = dom_$;
class MarkdownHover {
    constructor(owner, range, contents, ordinal) {
        this.owner = owner;
        this.range = range;
        this.contents = contents;
        this.ordinal = ordinal;
    }
    isValidForHoverAnchor(anchor) {
        return (anchor.type === 1 /* HoverAnchorType.Range */
            && this.range.startColumn <= anchor.range.startColumn
            && this.range.endColumn >= anchor.range.endColumn);
    }
}
let MarkdownHoverParticipant = class MarkdownHoverParticipant {
    constructor(_editor, _languageService, _openerService, _configurationService, _languageFeaturesService) {
        this._editor = _editor;
        this._languageService = _languageService;
        this._openerService = _openerService;
        this._configurationService = _configurationService;
        this._languageFeaturesService = _languageFeaturesService;
        this.hoverOrdinal = 2;
    }
    createLoadingMessage(anchor) {
        return new MarkdownHover(this, anchor.range, [new MarkdownString().appendText(localize('modesContentHover.loading', "Loading..."))], 2000);
    }
    computeSync(anchor, lineDecorations) {
        if (!this._editor.hasModel() || anchor.type !== 1 /* HoverAnchorType.Range */) {
            return [];
        }
        const model = this._editor.getModel();
        const lineNumber = anchor.range.startLineNumber;
        const maxColumn = model.getLineMaxColumn(lineNumber);
        const result = [];
        let index = 1000;
        const lineLength = model.getLineLength(lineNumber);
        const languageId = model.getLanguageIdAtPosition(anchor.range.startLineNumber, anchor.range.startColumn);
        const maxTokenizationLineLength = this._configurationService.getValue('editor.maxTokenizationLineLength', {
            overrideIdentifier: languageId
        });
        if (typeof maxTokenizationLineLength === 'number' && lineLength >= maxTokenizationLineLength) {
            result.push(new MarkdownHover(this, anchor.range, [{
                    value: localize('too many characters', "Tokenization is skipped for long lines for performance reasons. This can be configured via `editor.maxTokenizationLineLength`.")
                }], index++));
        }
        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 || isEmptyMarkdownString(hoverMessage)) {
                continue;
            }
            const range = new Range(anchor.range.startLineNumber, startColumn, anchor.range.startLineNumber, endColumn);
            result.push(new MarkdownHover(this, range, asArray(hoverMessage), index++));
        }
        return result;
    }
    computeAsync(anchor, lineDecorations, token) {
        if (!this._editor.hasModel() || anchor.type !== 1 /* HoverAnchorType.Range */) {
            return AsyncIterableObject.EMPTY;
        }
        const model = this._editor.getModel();
        if (!this._languageFeaturesService.hoverProvider.has(model)) {
            return AsyncIterableObject.EMPTY;
        }
        const position = new Position(anchor.range.startLineNumber, anchor.range.startColumn);
        return getHover(this._languageFeaturesService.hoverProvider, model, position, token)
            .filter(item => !isEmptyMarkdownString(item.hover.contents))
            .map(item => {
            const rng = item.hover.range ? Range.lift(item.hover.range) : anchor.range;
            return new MarkdownHover(this, rng, item.hover.contents, item.ordinal);
        });
    }
    renderHoverParts(context, hoverParts) {
        return renderMarkdownHovers(context, hoverParts, this._editor, this._languageService, this._openerService);
    }
};
MarkdownHoverParticipant = markdownHoverParticipant_decorate([
    markdownHoverParticipant_param(1, ILanguageService),
    markdownHoverParticipant_param(2, IOpenerService),
    markdownHoverParticipant_param(3, IConfigurationService),
    markdownHoverParticipant_param(4, ILanguageFeaturesService)
], MarkdownHoverParticipant);

function renderMarkdownHovers(context, hoverParts, editor, languageService, openerService) {
    // Sort hover parts to keep them stable since they might come in async, out-of-order
    hoverParts.sort((a, b) => a.ordinal - b.ordinal);
    const disposables = new DisposableStore();
    for (const hoverPart of hoverParts) {
        for (const contents of hoverPart.contents) {
            if (isEmptyMarkdownString(contents)) {
                continue;
            }
            const markdownHoverElement = markdownHoverParticipant_$('div.hover-row.markdown-hover');
            const hoverContentsElement = append(markdownHoverElement, markdownHoverParticipant_$('div.hover-contents'));
            const renderer = disposables.add(new MarkdownRenderer({ editor }, languageService, openerService));
            disposables.add(renderer.onDidRenderAsync(() => {
                hoverContentsElement.className = 'hover-contents code-hover-contents';
                context.onContentsChanged();
            }));
            const renderedContents = disposables.add(renderer.render(contents));
            hoverContentsElement.appendChild(renderedContents.element);
            context.fragment.appendChild(markdownHoverElement);
        }
    }
    return disposables;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoError/browser/markerNavigationService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var markerNavigationService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var markerNavigationService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};











class MarkerCoordinate {
    constructor(marker, index, total) {
        this.marker = marker;
        this.index = index;
        this.total = total;
    }
}
let MarkerList = class MarkerList {
    constructor(resourceFilter, _markerService, _configService) {
        this._markerService = _markerService;
        this._configService = _configService;
        this._onDidChange = new Emitter();
        this.onDidChange = this._onDidChange.event;
        this._dispoables = new DisposableStore();
        this._markers = [];
        this._nextIdx = -1;
        if (URI.isUri(resourceFilter)) {
            this._resourceFilter = uri => uri.toString() === resourceFilter.toString();
        }
        else if (resourceFilter) {
            this._resourceFilter = resourceFilter;
        }
        const compareOrder = this._configService.getValue('problems.sortOrder');
        const compareMarker = (a, b) => {
            let res = compare(a.resource.toString(), b.resource.toString());
            if (res === 0) {
                if (compareOrder === 'position') {
                    res = Range.compareRangesUsingStarts(a, b) || MarkerSeverity.compare(a.severity, b.severity);
                }
                else {
                    res = MarkerSeverity.compare(a.severity, b.severity) || Range.compareRangesUsingStarts(a, b);
                }
            }
            return res;
        };
        const updateMarker = () => {
            this._markers = this._markerService.read({
                resource: URI.isUri(resourceFilter) ? resourceFilter : undefined,
                severities: MarkerSeverity.Error | MarkerSeverity.Warning | MarkerSeverity.Info
            });
            if (typeof resourceFilter === 'function') {
                this._markers = this._markers.filter(m => this._resourceFilter(m.resource));
            }
            this._markers.sort(compareMarker);
        };
        updateMarker();
        this._dispoables.add(_markerService.onMarkerChanged(uris => {
            if (!this._resourceFilter || uris.some(uri => this._resourceFilter(uri))) {
                updateMarker();
                this._nextIdx = -1;
                this._onDidChange.fire();
            }
        }));
    }
    dispose() {
        this._dispoables.dispose();
        this._onDidChange.dispose();
    }
    matches(uri) {
        if (!this._resourceFilter && !uri) {
            return true;
        }
        if (!this._resourceFilter || !uri) {
            return false;
        }
        return this._resourceFilter(uri);
    }
    get selected() {
        const marker = this._markers[this._nextIdx];
        return marker && new MarkerCoordinate(marker, this._nextIdx + 1, this._markers.length);
    }
    _initIdx(model, position, fwd) {
        let found = false;
        let idx = this._markers.findIndex(marker => marker.resource.toString() === model.uri.toString());
        if (idx < 0) {
            idx = binarySearch(this._markers, { resource: model.uri }, (a, b) => compare(a.resource.toString(), b.resource.toString()));
            if (idx < 0) {
                idx = ~idx;
            }
        }
        for (let i = idx; i < this._markers.length; i++) {
            let range = Range.lift(this._markers[i]);
            if (range.isEmpty()) {
                const word = model.getWordAtPosition(range.getStartPosition());
                if (word) {
                    range = new Range(range.startLineNumber, word.startColumn, range.startLineNumber, word.endColumn);
                }
            }
            if (position && (range.containsPosition(position) || position.isBeforeOrEqual(range.getStartPosition()))) {
                this._nextIdx = i;
                found = true;
                break;
            }
            if (this._markers[i].resource.toString() !== model.uri.toString()) {
                break;
            }
        }
        if (!found) {
            // after the last change
            this._nextIdx = fwd ? 0 : this._markers.length - 1;
        }
        if (this._nextIdx < 0) {
            this._nextIdx = this._markers.length - 1;
        }
    }
    resetIndex() {
        this._nextIdx = -1;
    }
    move(fwd, model, position) {
        if (this._markers.length === 0) {
            return false;
        }
        const oldIdx = this._nextIdx;
        if (this._nextIdx === -1) {
            this._initIdx(model, position, fwd);
        }
        else if (fwd) {
            this._nextIdx = (this._nextIdx + 1) % this._markers.length;
        }
        else if (!fwd) {
            this._nextIdx = (this._nextIdx - 1 + this._markers.length) % this._markers.length;
        }
        if (oldIdx !== this._nextIdx) {
            return true;
        }
        return false;
    }
    find(uri, position) {
        let idx = this._markers.findIndex(marker => marker.resource.toString() === uri.toString());
        if (idx < 0) {
            return undefined;
        }
        for (; idx < this._markers.length; idx++) {
            if (Range.containsPosition(this._markers[idx], position)) {
                return new MarkerCoordinate(this._markers[idx], idx + 1, this._markers.length);
            }
        }
        return undefined;
    }
};
MarkerList = markerNavigationService_decorate([
    markerNavigationService_param(1, IMarkerService),
    markerNavigationService_param(2, IConfigurationService)
], MarkerList);

const IMarkerNavigationService = createDecorator('IMarkerNavigationService');
let MarkerNavigationService = class MarkerNavigationService {
    constructor(_markerService, _configService) {
        this._markerService = _markerService;
        this._configService = _configService;
        this._provider = new LinkedList();
    }
    getMarkerList(resource) {
        for (const provider of this._provider) {
            const result = provider.getMarkerList(resource);
            if (result) {
                return result;
            }
        }
        // default
        return new MarkerList(resource, this._markerService, this._configService);
    }
};
MarkerNavigationService = markerNavigationService_decorate([
    markerNavigationService_param(0, IMarkerService),
    markerNavigationService_param(1, IConfigurationService)
], MarkerNavigationService);
registerSingleton(IMarkerNavigationService, MarkerNavigationService, true);

;// ../../node_modules/monaco-editor/esm/vs/platform/theme/common/iconRegistry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









// icon registry
const iconRegistry_Extensions = {
    IconContribution: 'base.contributions.icons'
};
var IconContribution;
(function (IconContribution) {
    function getDefinition(contribution, registry) {
        let definition = contribution.defaults;
        while (ThemeIcon.isThemeIcon(definition)) {
            const c = iconRegistry.getIcon(definition.id);
            if (!c) {
                return undefined;
            }
            definition = c.defaults;
        }
        return definition;
    }
    IconContribution.getDefinition = getDefinition;
})(IconContribution || (IconContribution = {}));
var IconFontDefinition;
(function (IconFontDefinition) {
    function toJSONObject(iconFont) {
        return {
            weight: iconFont.weight,
            style: iconFont.style,
            src: iconFont.src.map(s => ({ format: s.format, location: s.location.toString() }))
        };
    }
    IconFontDefinition.toJSONObject = toJSONObject;
    function fromJSONObject(json) {
        const stringOrUndef = (s) => isString(s) ? s : undefined;
        if (json && Array.isArray(json.src) && json.src.every((s) => isString(s.format) && isString(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 undefined;
    }
    IconFontDefinition.fromJSONObject = fromJSONObject;
})(IconFontDefinition || (IconFontDefinition = {}));
class IconRegistry {
    constructor() {
        this._onDidChange = new Emitter();
        this.onDidChange = this._onDidChange.event;
        this.iconSchema = {
            definitions: {
                icons: {
                    type: 'object',
                    properties: {
                        fontId: { type: 'string', description: localize('iconDefinition.fontId', 'The id of the font to use. If not set, the font that is defined first is used.') },
                        fontCharacter: { type: 'string', description: localize('iconDefinition.fontCharacter', 'The font character associated with the icon definition.') }
                    },
                    additionalProperties: false,
                    defaultSnippets: [{ body: { fontCharacter: '\\\\e030' } }]
                }
            },
            type: 'object',
            properties: {}
        };
        this.iconReferenceSchema = { type: 'string', pattern: `^${CSSIcon.iconNameExpression}$`, enum: [], enumDescriptions: [] };
        this.iconsById = {};
        this.iconFontsById = {};
    }
    registerIcon(id, defaults, description, deprecationMessage) {
        const existing = this.iconsById[id];
        if (existing) {
            if (description && !existing.description) {
                existing.description = description;
                this.iconSchema.properties[id].markdownDescription = `${description} $(${id})`;
                const enumIndex = this.iconReferenceSchema.enum.indexOf(id);
                if (enumIndex !== -1) {
                    this.iconReferenceSchema.enumDescriptions[enumIndex] = description;
                }
                this._onDidChange.fire();
            }
            return existing;
        }
        const iconContribution = { id, description, defaults, deprecationMessage };
        this.iconsById[id] = iconContribution;
        const propertySchema = { $ref: '#/definitions/icons' };
        if (deprecationMessage) {
            propertySchema.deprecationMessage = deprecationMessage;
        }
        if (description) {
            propertySchema.markdownDescription = `${description}: $(${id})`;
        }
        this.iconSchema.properties[id] = propertySchema;
        this.iconReferenceSchema.enum.push(id);
        this.iconReferenceSchema.enumDescriptions.push(description || '');
        this._onDidChange.fire();
        return { id };
    }
    getIcons() {
        return Object.keys(this.iconsById).map(id => this.iconsById[id]);
    }
    getIcon(id) {
        return this.iconsById[id];
    }
    getIconSchema() {
        return this.iconSchema;
    }
    toString() {
        const sorter = (i1, i2) => {
            return i1.id.localeCompare(i2.id);
        };
        const classNames = (i) => {
            while (ThemeIcon.isThemeIcon(i.defaults)) {
                i = this.iconsById[i.defaults.id];
            }
            return `codicon codicon-${i ? i.id : ''}`;
        };
        const reference = [];
        reference.push(`| preview     | identifier                        | default codicon ID                | description`);
        reference.push(`| ----------- | --------------------------------- | --------------------------------- | --------------------------------- |`);
        const contributions = Object.keys(this.iconsById).map(key => this.iconsById[key]);
        for (const i of contributions.filter(i => !!i.description).sort(sorter)) {
            reference.push(`|<i class="${classNames(i)}"></i>|${i.id}|${ThemeIcon.isThemeIcon(i.defaults) ? i.defaults.id : i.id}|${i.description || ''}|`);
        }
        reference.push(`| preview     | identifier                        `);
        reference.push(`| ----------- | --------------------------------- |`);
        for (const i of contributions.filter(i => !ThemeIcon.isThemeIcon(i.defaults)).sort(sorter)) {
            reference.push(`|<i class="${classNames(i)}"></i>|${i.id}|`);
        }
        return reference.join('\n');
    }
}
const iconRegistry = new IconRegistry();
Registry.add(iconRegistry_Extensions.IconContribution, iconRegistry);
function registerIcon(id, defaults, description, deprecationMessage) {
    return iconRegistry.registerIcon(id, defaults, description, deprecationMessage);
}
function getIconRegistry() {
    return iconRegistry;
}
function initialize() {
    for (const icon of Codicon.getAll()) {
        iconRegistry.registerIcon(icon.id, icon.definition, icon.description);
    }
}
initialize();
const iconsSchemaId = 'vscode://schemas/icons';
const iconRegistry_schemaRegistry = Registry.as(jsonContributionRegistry_Extensions.JSONContribution);
iconRegistry_schemaRegistry.registerSchema(iconsSchemaId, iconRegistry.getIconSchema());
const iconRegistry_delayer = new RunOnceScheduler(() => iconRegistry_schemaRegistry.notifySchemaChanged(iconsSchemaId), 200);
iconRegistry.onDidChange(() => {
    if (!iconRegistry_delayer.isScheduled()) {
        iconRegistry_delayer.schedule();
    }
});
//setTimeout(_ => console.log(iconRegistry.toString()), 5000);
// common icons
const widgetClose = registerIcon('widget-close', Codicon.close, localize('widgetClose', 'Icon for the close action in widgets.'));
const gotoPreviousLocation = registerIcon('goto-previous-location', Codicon.arrowUp, localize('previousChangeIcon', 'Icon for goto previous editor location.'));
const gotoNextLocation = registerIcon('goto-next-location', Codicon.arrowDown, localize('nextChangeIcon', 'Icon for goto next editor location.'));
const syncing = ThemeIcon.modify(Codicon.sync, 'spin');
const spinningLoading = ThemeIcon.modify(Codicon.loading, 'spin');

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoError/browser/media/gotoErrorWidget.css
var gotoErrorWidget = __webpack_require__(82171);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoError/browser/media/gotoErrorWidget.css

      
      
      
      
      
      
      
      
      

var gotoErrorWidget_options = {};

gotoErrorWidget_options.styleTagTransform = (styleTagTransform_default());
gotoErrorWidget_options.setAttributes = (setAttributesWithoutAttributes_default());

      gotoErrorWidget_options.insert = insertBySelector_default().bind(null, "head");
    
gotoErrorWidget_options.domAPI = (styleDomAPI_default());
gotoErrorWidget_options.insertStyleElement = (insertStyleElement_default());

var gotoErrorWidget_update = injectStylesIntoStyleTag_default()(gotoErrorWidget/* default */.A, gotoErrorWidget_options);




       /* harmony default export */ const media_gotoErrorWidget = (gotoErrorWidget/* default */.A && gotoErrorWidget/* default */.A.locals ? gotoErrorWidget/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/platform/severityIcon/common/severityIcon.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




var SeverityIcon;
(function (SeverityIcon) {
    function className(severity) {
        switch (severity) {
            case common_severity.Ignore:
                return 'severity-ignore ' + Codicon.info.classNames;
            case common_severity.Info:
                return Codicon.info.classNames;
            case common_severity.Warning:
                return Codicon.warning.classNames;
            case common_severity.Error:
                return Codicon.error.classNames;
            default:
                return '';
        }
    }
    SeverityIcon.className = className;
})(SeverityIcon || (SeverityIcon = {}));
registerThemingParticipant((theme, collector) => {
    const errorIconForeground = theme.getColor(problemsErrorIconForeground);
    if (errorIconForeground) {
        const errorCodiconSelector = Codicon.error.cssSelector;
        collector.addRule(`
			.monaco-editor .zone-widget ${errorCodiconSelector},
			.markers-panel .marker-icon${errorCodiconSelector},
			.text-search-provider-messages .providerMessage ${errorCodiconSelector},
			.extensions-viewlet > .extensions ${errorCodiconSelector} {
				color: ${errorIconForeground};
			}
		`);
    }
    const warningIconForeground = theme.getColor(problemsWarningIconForeground);
    if (warningIconForeground) {
        const warningCodiconSelector = Codicon.warning.cssSelector;
        collector.addRule(`
			.monaco-editor .zone-widget ${warningCodiconSelector},
			.markers-panel .marker-icon${warningCodiconSelector},
			.extensions-viewlet > .extensions ${warningCodiconSelector},
			.extension-editor ${warningCodiconSelector},
			.text-search-provider-messages .providerMessage ${warningCodiconSelector},
			.preferences-editor ${warningCodiconSelector} {
				color: ${warningIconForeground};
			}
		`);
    }
    const infoIconForeground = theme.getColor(problemsInfoIconForeground);
    if (infoIconForeground) {
        const infoCodiconSelector = Codicon.info.cssSelector;
        collector.addRule(`
			.monaco-editor .zone-widget ${infoCodiconSelector},
			.markers-panel .marker-icon${infoCodiconSelector},
			.extensions-viewlet > .extensions ${infoCodiconSelector},
			.text-search-provider-messages .providerMessage ${infoCodiconSelector},
			.extension-editor ${infoCodiconSelector} {
				color: ${infoIconForeground};
			}
		`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoError/browser/gotoErrorWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var gotoErrorWidget_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var gotoErrorWidget_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};






















class gotoErrorWidget_MessageWidget {
    constructor(parent, editor, onRelatedInformation, _openerService, _labelService) {
        this._openerService = _openerService;
        this._labelService = _labelService;
        this._lines = 0;
        this._longestLineLength = 0;
        this._relatedDiagnostics = new WeakMap();
        this._disposables = new DisposableStore();
        this._editor = editor;
        const domNode = document.createElement('div');
        domNode.className = 'descriptioncontainer';
        this._messageBlock = document.createElement('div');
        this._messageBlock.classList.add('message');
        this._messageBlock.setAttribute('aria-live', 'assertive');
        this._messageBlock.setAttribute('role', 'alert');
        domNode.appendChild(this._messageBlock);
        this._relatedBlock = document.createElement('div');
        domNode.appendChild(this._relatedBlock);
        this._disposables.add(addStandardDisposableListener(this._relatedBlock, 'click', event => {
            event.preventDefault();
            const related = this._relatedDiagnostics.get(event.target);
            if (related) {
                onRelatedInformation(related);
            }
        }));
        this._scrollable = new ScrollableElement(domNode, {
            horizontal: 1 /* ScrollbarVisibility.Auto */,
            vertical: 1 /* ScrollbarVisibility.Auto */,
            useShadows: false,
            horizontalScrollbarSize: 6,
            verticalScrollbarSize: 6
        });
        parent.appendChild(this._scrollable.getDomNode());
        this._disposables.add(this._scrollable.onScroll(e => {
            domNode.style.left = `-${e.scrollLeft}px`;
            domNode.style.top = `-${e.scrollTop}px`;
        }));
        this._disposables.add(this._scrollable);
    }
    dispose() {
        dispose(this._disposables);
    }
    update(marker) {
        const { source, message, relatedInformation, code } = marker;
        let sourceAndCodeLength = ((source === null || source === void 0 ? void 0 : source.length) || 0) + '()'.length;
        if (code) {
            if (typeof code === 'string') {
                sourceAndCodeLength += code.length;
            }
            else {
                sourceAndCodeLength += code.value.length;
            }
        }
        const lines = splitLines(message);
        this._lines = lines.length;
        this._longestLineLength = 0;
        for (const line of lines) {
            this._longestLineLength = Math.max(line.length + sourceAndCodeLength, this._longestLineLength);
        }
        clearNode(this._messageBlock);
        this._messageBlock.setAttribute('aria-label', this.getAriaLabel(marker));
        this._editor.applyFontInfo(this._messageBlock);
        let lastLineElement = this._messageBlock;
        for (const line of lines) {
            lastLineElement = document.createElement('div');
            lastLineElement.innerText = line;
            if (line === '') {
                lastLineElement.style.height = this._messageBlock.style.lineHeight;
            }
            this._messageBlock.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._codeLink = dom_$('a.code-link');
                    this._codeLink.setAttribute('href', `${code.target.toString()}`);
                    this._codeLink.onclick = (e) => {
                        this._openerService.open(code.target, { allowCommands: true });
                        e.preventDefault();
                        e.stopPropagation();
                    };
                    const codeElement = append(this._codeLink, dom_$('span'));
                    codeElement.innerText = code.value;
                    detailsElement.appendChild(this._codeLink);
                }
            }
        }
        clearNode(this._relatedBlock);
        this._editor.applyFontInfo(this._relatedBlock);
        if (isNonEmptyArray(relatedInformation)) {
            const relatedInformationNode = this._relatedBlock.appendChild(document.createElement('div'));
            relatedInformationNode.style.paddingTop = `${Math.floor(this._editor.getOption(61 /* EditorOption.lineHeight */) * 0.66)}px`;
            this._lines += 1;
            for (const related of relatedInformation) {
                const container = document.createElement('div');
                const relatedResource = document.createElement('a');
                relatedResource.classList.add('filename');
                relatedResource.innerText = `${this._labelService.getUriBasenameLabel(related.resource)}(${related.startLineNumber}, ${related.startColumn}): `;
                relatedResource.title = this._labelService.getUriLabel(related.resource);
                this._relatedDiagnostics.set(relatedResource, related);
                const relatedMessage = document.createElement('span');
                relatedMessage.innerText = related.message;
                container.appendChild(relatedResource);
                container.appendChild(relatedMessage);
                this._lines += 1;
                relatedInformationNode.appendChild(container);
            }
        }
        const fontInfo = this._editor.getOption(46 /* EditorOption.fontInfo */);
        const scrollWidth = Math.ceil(fontInfo.typicalFullwidthCharacterWidth * this._longestLineLength * 0.75);
        const scrollHeight = fontInfo.lineHeight * this._lines;
        this._scrollable.setScrollDimensions({ scrollWidth, scrollHeight });
    }
    layout(height, width) {
        this._scrollable.getDomNode().style.height = `${height}px`;
        this._scrollable.getDomNode().style.width = `${width}px`;
        this._scrollable.setScrollDimensions({ width, height });
    }
    getHeightInLines() {
        return Math.min(17, this._lines);
    }
    getAriaLabel(marker) {
        let severityLabel = '';
        switch (marker.severity) {
            case MarkerSeverity.Error:
                severityLabel = localize('Error', "Error");
                break;
            case MarkerSeverity.Warning:
                severityLabel = localize('Warning', "Warning");
                break;
            case MarkerSeverity.Info:
                severityLabel = localize('Info', "Info");
                break;
            case MarkerSeverity.Hint:
                severityLabel = localize('Hint', "Hint");
                break;
        }
        let ariaLabel = localize('marker aria', "{0} at {1}. ", severityLabel, marker.startLineNumber + ':' + marker.startColumn);
        const model = this._editor.getModel();
        if (model && (marker.startLineNumber <= model.getLineCount()) && (marker.startLineNumber >= 1)) {
            const lineContent = model.getLineContent(marker.startLineNumber);
            ariaLabel = `${lineContent}, ${ariaLabel}`;
        }
        return ariaLabel;
    }
}
let MarkerNavigationWidget = class MarkerNavigationWidget extends PeekViewWidget {
    constructor(editor, _themeService, _openerService, _menuService, instantiationService, _contextKeyService, _labelService) {
        super(editor, { showArrow: true, showFrame: true, isAccessible: true, frameWidth: 1 }, instantiationService);
        this._themeService = _themeService;
        this._openerService = _openerService;
        this._menuService = _menuService;
        this._contextKeyService = _contextKeyService;
        this._labelService = _labelService;
        this._callOnDispose = new DisposableStore();
        this._onDidSelectRelatedInformation = new Emitter();
        this.onDidSelectRelatedInformation = this._onDidSelectRelatedInformation.event;
        this._severity = MarkerSeverity.Warning;
        this._backgroundColor = Color.white;
        this._applyTheme(_themeService.getColorTheme());
        this._callOnDispose.add(_themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
        this.create();
    }
    _applyTheme(theme) {
        this._backgroundColor = theme.getColor(editorMarkerNavigationBackground);
        let colorId = editorMarkerNavigationError;
        let headerBackground = editorMarkerNavigationErrorHeader;
        if (this._severity === MarkerSeverity.Warning) {
            colorId = editorMarkerNavigationWarning;
            headerBackground = editorMarkerNavigationWarningHeader;
        }
        else if (this._severity === MarkerSeverity.Info) {
            colorId = editorMarkerNavigationInfo;
            headerBackground = editorMarkerNavigationInfoHeader;
        }
        const frameColor = theme.getColor(colorId);
        const headerBg = theme.getColor(headerBackground);
        this.style({
            arrowColor: frameColor,
            frameColor: frameColor,
            headerBackgroundColor: headerBg,
            primaryHeadingColor: theme.getColor(peekViewTitleForeground),
            secondaryHeadingColor: theme.getColor(peekViewTitleInfoForeground)
        }); // style() will trigger _applyStyles
    }
    _applyStyles() {
        if (this._parentContainer) {
            this._parentContainer.style.backgroundColor = this._backgroundColor ? this._backgroundColor.toString() : '';
        }
        super._applyStyles();
    }
    dispose() {
        this._callOnDispose.dispose();
        super.dispose();
    }
    _fillHead(container) {
        super._fillHead(container);
        this._disposables.add(this._actionbarWidget.actionRunner.onBeforeRun(e => this.editor.focus()));
        const actions = [];
        const menu = this._menuService.createMenu(MarkerNavigationWidget.TitleMenu, this._contextKeyService);
        createAndFillInActionBarActions(menu, undefined, actions);
        this._actionbarWidget.push(actions, { label: false, icon: true, index: 0 });
        menu.dispose();
    }
    _fillTitleIcon(container) {
        this._icon = append(container, dom_$(''));
    }
    _fillBody(container) {
        this._parentContainer = container;
        container.classList.add('marker-widget');
        this._parentContainer.tabIndex = 0;
        this._parentContainer.setAttribute('role', 'tooltip');
        this._container = document.createElement('div');
        container.appendChild(this._container);
        this._message = new gotoErrorWidget_MessageWidget(this._container, this.editor, related => this._onDidSelectRelatedInformation.fire(related), this._openerService, this._labelService);
        this._disposables.add(this._message);
    }
    show() {
        throw new Error('call showAtMarker');
    }
    showAtMarker(marker, markerIdx, markerCount) {
        // update:
        // * title
        // * message
        this._container.classList.remove('stale');
        this._message.update(marker);
        // update frame color (only applied on 'show')
        this._severity = marker.severity;
        this._applyTheme(this._themeService.getColorTheme());
        // show
        const range = Range.lift(marker);
        const editorPosition = this.editor.getPosition();
        const position = editorPosition && range.containsPosition(editorPosition) ? editorPosition : range.getStartPosition();
        super.show(position, this.computeRequiredHeight());
        const model = this.editor.getModel();
        if (model) {
            const detail = markerCount > 1
                ? localize('problems', "{0} of {1} problems", markerIdx, markerCount)
                : localize('change', "{0} of {1} problem", markerIdx, markerCount);
            this.setTitle(resources_basename(model.uri), detail);
        }
        this._icon.className = `codicon ${SeverityIcon.className(MarkerSeverity.toSeverity(this._severity))}`;
        this.editor.revealPositionNearTop(position, 0 /* ScrollType.Smooth */);
        this.editor.focus();
    }
    updateMarker(marker) {
        this._container.classList.remove('stale');
        this._message.update(marker);
    }
    showStale() {
        this._container.classList.add('stale');
        this._relayout();
    }
    _doLayoutBody(heightInPixel, widthInPixel) {
        super._doLayoutBody(heightInPixel, widthInPixel);
        this._heightInPixel = heightInPixel;
        this._message.layout(heightInPixel, widthInPixel);
        this._container.style.height = `${heightInPixel}px`;
    }
    _onWidth(widthInPixel) {
        this._message.layout(this._heightInPixel, widthInPixel);
    }
    _relayout() {
        super._relayout(this.computeRequiredHeight());
    }
    computeRequiredHeight() {
        return 3 + this._message.getHeightInLines();
    }
};
MarkerNavigationWidget.TitleMenu = new MenuId('gotoErrorTitleMenu');
MarkerNavigationWidget = gotoErrorWidget_decorate([
    gotoErrorWidget_param(1, IThemeService),
    gotoErrorWidget_param(2, IOpenerService),
    gotoErrorWidget_param(3, IMenuService),
    gotoErrorWidget_param(4, IInstantiationService),
    gotoErrorWidget_param(5, IContextKeyService),
    gotoErrorWidget_param(6, ILabelService)
], MarkerNavigationWidget);

// theming
const errorDefault = oneOf(editorErrorForeground, editorErrorBorder);
const warningDefault = oneOf(editorWarningForeground, editorWarningBorder);
const infoDefault = oneOf(editorInfoForeground, editorInfoBorder);
const editorMarkerNavigationError = registerColor('editorMarkerNavigationError.background', { dark: errorDefault, light: errorDefault, hcDark: contrastBorder, hcLight: contrastBorder }, localize('editorMarkerNavigationError', 'Editor marker navigation widget error color.'));
const editorMarkerNavigationErrorHeader = registerColor('editorMarkerNavigationError.headerBackground', { dark: transparent(editorMarkerNavigationError, .1), light: transparent(editorMarkerNavigationError, .1), hcDark: null, hcLight: null }, localize('editorMarkerNavigationErrorHeaderBackground', 'Editor marker navigation widget error heading background.'));
const editorMarkerNavigationWarning = registerColor('editorMarkerNavigationWarning.background', { dark: warningDefault, light: warningDefault, hcDark: contrastBorder, hcLight: contrastBorder }, localize('editorMarkerNavigationWarning', 'Editor marker navigation widget warning color.'));
const editorMarkerNavigationWarningHeader = registerColor('editorMarkerNavigationWarning.headerBackground', { dark: transparent(editorMarkerNavigationWarning, .1), light: transparent(editorMarkerNavigationWarning, .1), hcDark: '#0C141F', hcLight: transparent(editorMarkerNavigationWarning, .2) }, localize('editorMarkerNavigationWarningBackground', 'Editor marker navigation widget warning heading background.'));
const editorMarkerNavigationInfo = registerColor('editorMarkerNavigationInfo.background', { dark: infoDefault, light: infoDefault, hcDark: contrastBorder, hcLight: contrastBorder }, localize('editorMarkerNavigationInfo', 'Editor marker navigation widget info color.'));
const editorMarkerNavigationInfoHeader = registerColor('editorMarkerNavigationInfo.headerBackground', { dark: transparent(editorMarkerNavigationInfo, .1), light: transparent(editorMarkerNavigationInfo, .1), hcDark: null, hcLight: null }, localize('editorMarkerNavigationInfoHeaderBackground', 'Editor marker navigation widget info heading background.'));
const editorMarkerNavigationBackground = registerColor('editorMarkerNavigation.background', { dark: editorBackground, light: editorBackground, hcDark: editorBackground, hcLight: editorBackground }, localize('editorMarkerNavigationBackground', 'Editor marker navigation widget background.'));

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoError/browser/gotoError.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var gotoError_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var gotoError_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var gotoError_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};














let MarkerController = class MarkerController {
    constructor(editor, _markerNavigationService, _contextKeyService, _editorService, _instantiationService) {
        this._markerNavigationService = _markerNavigationService;
        this._contextKeyService = _contextKeyService;
        this._editorService = _editorService;
        this._instantiationService = _instantiationService;
        this._sessionDispoables = new DisposableStore();
        this._editor = editor;
        this._widgetVisible = CONTEXT_MARKERS_NAVIGATION_VISIBLE.bindTo(this._contextKeyService);
    }
    static get(editor) {
        return editor.getContribution(MarkerController.ID);
    }
    dispose() {
        this._cleanUp();
        this._sessionDispoables.dispose();
    }
    _cleanUp() {
        this._widgetVisible.reset();
        this._sessionDispoables.clear();
        this._widget = undefined;
        this._model = undefined;
    }
    _getOrCreateModel(uri) {
        if (this._model && this._model.matches(uri)) {
            return this._model;
        }
        let reusePosition = false;
        if (this._model) {
            reusePosition = true;
            this._cleanUp();
        }
        this._model = this._markerNavigationService.getMarkerList(uri);
        if (reusePosition) {
            this._model.move(true, this._editor.getModel(), this._editor.getPosition());
        }
        this._widget = this._instantiationService.createInstance(MarkerNavigationWidget, this._editor);
        this._widget.onDidClose(() => this.close(), this, this._sessionDispoables);
        this._widgetVisible.set(true);
        this._sessionDispoables.add(this._model);
        this._sessionDispoables.add(this._widget);
        // follow cursor
        this._sessionDispoables.add(this._editor.onDidChangeCursorPosition(e => {
            var _a, _b, _c;
            if (!((_a = this._model) === null || _a === void 0 ? void 0 : _a.selected) || !Range.containsPosition((_b = this._model) === null || _b === void 0 ? void 0 : _b.selected.marker, e.position)) {
                (_c = this._model) === null || _c === void 0 ? void 0 : _c.resetIndex();
            }
        }));
        // update markers
        this._sessionDispoables.add(this._model.onDidChange(() => {
            if (!this._widget || !this._widget.position || !this._model) {
                return;
            }
            const info = this._model.find(this._editor.getModel().uri, this._widget.position);
            if (info) {
                this._widget.updateMarker(info.marker);
            }
            else {
                this._widget.showStale();
            }
        }));
        // open related
        this._sessionDispoables.add(this._widget.onDidSelectRelatedInformation(related => {
            this._editorService.openCodeEditor({
                resource: related.resource,
                options: { pinned: true, revealIfOpened: true, selection: Range.lift(related).collapseToStart() }
            }, this._editor);
            this.close(false);
        }));
        this._sessionDispoables.add(this._editor.onDidChangeModel(() => this._cleanUp()));
        return this._model;
    }
    close(focusEditor = true) {
        this._cleanUp();
        if (focusEditor) {
            this._editor.focus();
        }
    }
    showAtMarker(marker) {
        if (this._editor.hasModel()) {
            const model = this._getOrCreateModel(this._editor.getModel().uri);
            model.resetIndex();
            model.move(true, this._editor.getModel(), new Position(marker.startLineNumber, marker.startColumn));
            if (model.selected) {
                this._widget.showAtMarker(model.selected.marker, model.selected.index, model.selected.total);
            }
        }
    }
    nagivate(next, multiFile) {
        var _a, _b;
        return gotoError_awaiter(this, void 0, void 0, function* () {
            if (this._editor.hasModel()) {
                const model = this._getOrCreateModel(multiFile ? undefined : this._editor.getModel().uri);
                model.move(next, this._editor.getModel(), this._editor.getPosition());
                if (!model.selected) {
                    return;
                }
                if (model.selected.marker.resource.toString() !== this._editor.getModel().uri.toString()) {
                    // show in different editor
                    this._cleanUp();
                    const otherEditor = yield this._editorService.openCodeEditor({
                        resource: model.selected.marker.resource,
                        options: { pinned: false, revealIfOpened: true, selectionRevealType: 2 /* TextEditorSelectionRevealType.NearTop */, selection: model.selected.marker }
                    }, this._editor);
                    if (otherEditor) {
                        (_a = MarkerController.get(otherEditor)) === null || _a === void 0 ? void 0 : _a.close();
                        (_b = MarkerController.get(otherEditor)) === null || _b === void 0 ? void 0 : _b.nagivate(next, multiFile);
                    }
                }
                else {
                    // show in this editor
                    this._widget.showAtMarker(model.selected.marker, model.selected.index, model.selected.total);
                }
            }
        });
    }
};
MarkerController.ID = 'editor.contrib.markerController';
MarkerController = gotoError_decorate([
    gotoError_param(1, IMarkerNavigationService),
    gotoError_param(2, IContextKeyService),
    gotoError_param(3, ICodeEditorService),
    gotoError_param(4, IInstantiationService)
], MarkerController);

class MarkerNavigationAction extends EditorAction {
    constructor(_next, _multiFile, opts) {
        super(opts);
        this._next = _next;
        this._multiFile = _multiFile;
    }
    run(_accessor, editor) {
        var _a;
        return gotoError_awaiter(this, void 0, void 0, function* () {
            if (editor.hasModel()) {
                (_a = MarkerController.get(editor)) === null || _a === void 0 ? void 0 : _a.nagivate(this._next, this._multiFile);
            }
        });
    }
}
class NextMarkerAction extends MarkerNavigationAction {
    constructor() {
        super(true, false, {
            id: NextMarkerAction.ID,
            label: NextMarkerAction.LABEL,
            alias: 'Go to Next Problem (Error, Warning, Info)',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: 512 /* KeyMod.Alt */ | 66 /* KeyCode.F8 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MarkerNavigationWidget.TitleMenu,
                title: NextMarkerAction.LABEL,
                icon: registerIcon('marker-navigation-next', Codicon.arrowDown, localize('nextMarkerIcon', 'Icon for goto next marker.')),
                group: 'navigation',
                order: 1
            }
        });
    }
}
NextMarkerAction.ID = 'editor.action.marker.next';
NextMarkerAction.LABEL = localize('markerAction.next.label', "Go to Next Problem (Error, Warning, Info)");
class PrevMarkerAction extends MarkerNavigationAction {
    constructor() {
        super(false, false, {
            id: PrevMarkerAction.ID,
            label: PrevMarkerAction.LABEL,
            alias: 'Go to Previous Problem (Error, Warning, Info)',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 66 /* KeyCode.F8 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MarkerNavigationWidget.TitleMenu,
                title: PrevMarkerAction.LABEL,
                icon: registerIcon('marker-navigation-previous', Codicon.arrowUp, localize('previousMarkerIcon', 'Icon for goto previous marker.')),
                group: 'navigation',
                order: 2
            }
        });
    }
}
PrevMarkerAction.ID = 'editor.action.marker.prev';
PrevMarkerAction.LABEL = localize('markerAction.previous.label', "Go to Previous Problem (Error, Warning, Info)");
class NextMarkerInFilesAction extends MarkerNavigationAction {
    constructor() {
        super(true, true, {
            id: 'editor.action.marker.nextInFiles',
            label: localize('markerAction.nextInFiles.label', "Go to Next Problem in Files (Error, Warning, Info)"),
            alias: 'Go to Next Problem in Files (Error, Warning, Info)',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: 66 /* KeyCode.F8 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarGoMenu,
                title: localize({ key: 'miGotoNextProblem', comment: ['&& denotes a mnemonic'] }, "Next &&Problem"),
                group: '6_problem_nav',
                order: 1
            }
        });
    }
}
class PrevMarkerInFilesAction extends MarkerNavigationAction {
    constructor() {
        super(false, true, {
            id: 'editor.action.marker.prevInFiles',
            label: localize('markerAction.previousInFiles.label', "Go to Previous Problem in Files (Error, Warning, Info)"),
            alias: 'Go to Previous Problem in Files (Error, Warning, Info)',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: 1024 /* KeyMod.Shift */ | 66 /* KeyCode.F8 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarGoMenu,
                title: localize({ key: 'miGotoPreviousProblem', comment: ['&& denotes a mnemonic'] }, "Previous &&Problem"),
                group: '6_problem_nav',
                order: 2
            }
        });
    }
}
registerEditorContribution(MarkerController.ID, MarkerController);
registerEditorAction(NextMarkerAction);
registerEditorAction(PrevMarkerAction);
registerEditorAction(NextMarkerInFilesAction);
registerEditorAction(PrevMarkerInFilesAction);
const CONTEXT_MARKERS_NAVIGATION_VISIBLE = new RawContextKey('markersNavigationVisible', false);
const MarkerCommand = EditorCommand.bindToContribution(MarkerController.get);
registerEditorCommand(new MarkerCommand({
    id: 'closeMarkersNavigation',
    precondition: CONTEXT_MARKERS_NAVIGATION_VISIBLE,
    handler: x => x.close(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 50,
        kbExpr: EditorContextKeys.focus,
        primary: 9 /* KeyCode.Escape */,
        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
    }
}));

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/hover/browser/markerHoverParticipant.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var markerHoverParticipant_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var markerHoverParticipant_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};



















const markerHoverParticipant_$ = dom_$;
class MarkerHover {
    constructor(owner, range, marker) {
        this.owner = owner;
        this.range = range;
        this.marker = marker;
    }
    isValidForHoverAnchor(anchor) {
        return (anchor.type === 1 /* HoverAnchorType.Range */
            && this.range.startColumn <= anchor.range.startColumn
            && this.range.endColumn >= anchor.range.endColumn);
    }
}
const markerCodeActionTrigger = {
    type: 1 /* CodeActionTriggerType.Invoke */,
    filter: { include: CodeActionKind.QuickFix },
    triggerAction: CodeActionTriggerSource.QuickFixHover
};
let MarkerHoverParticipant = class MarkerHoverParticipant {
    constructor(_editor, _markerDecorationsService, _openerService, _languageFeaturesService) {
        this._editor = _editor;
        this._markerDecorationsService = _markerDecorationsService;
        this._openerService = _openerService;
        this._languageFeaturesService = _languageFeaturesService;
        this.hoverOrdinal = 5;
        this.recentMarkerCodeActionsInfo = undefined;
    }
    computeSync(anchor, lineDecorations) {
        if (!this._editor.hasModel() || anchor.type !== 1 /* HoverAnchorType.Range */) {
            return [];
        }
        const model = this._editor.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._markerDecorationsService.getMarker(model.uri, d);
            if (!marker) {
                continue;
            }
            const range = new Range(anchor.range.startLineNumber, startColumn, anchor.range.startLineNumber, endColumn);
            result.push(new MarkerHover(this, range, marker));
        }
        return result;
    }
    renderHoverParts(context, hoverParts) {
        if (!hoverParts.length) {
            return Disposable.None;
        }
        const disposables = new DisposableStore();
        hoverParts.forEach(msg => context.fragment.appendChild(this.renderMarkerHover(msg, disposables)));
        const markerHoverForStatusbar = hoverParts.length === 1 ? hoverParts[0] : hoverParts.sort((a, b) => MarkerSeverity.compare(a.marker.severity, b.marker.severity))[0];
        this.renderMarkerStatusbar(context, markerHoverForStatusbar, disposables);
        return disposables;
    }
    renderMarkerHover(markerHover, disposables) {
        const hoverElement = markerHoverParticipant_$('div.hover-row');
        const markerElement = append(hoverElement, markerHoverParticipant_$('div.marker.hover-contents'));
        const { source, message, code, relatedInformation } = markerHover.marker;
        this._editor.applyFontInfo(markerElement);
        const messageElement = append(markerElement, markerHoverParticipant_$('span'));
        messageElement.style.whiteSpace = 'pre-wrap';
        messageElement.innerText = message;
        if (source || code) {
            // Code has link
            if (code && typeof code !== 'string') {
                const sourceAndCodeElement = markerHoverParticipant_$('span');
                if (source) {
                    const sourceElement = append(sourceAndCodeElement, markerHoverParticipant_$('span'));
                    sourceElement.innerText = source;
                }
                const codeLink = append(sourceAndCodeElement, markerHoverParticipant_$('a.code-link'));
                codeLink.setAttribute('href', code.target.toString());
                disposables.add(addDisposableListener(codeLink, 'click', (e) => {
                    this._openerService.open(code.target, { allowCommands: true });
                    e.preventDefault();
                    e.stopPropagation();
                }));
                const codeElement = append(codeLink, markerHoverParticipant_$('span'));
                codeElement.innerText = code.value;
                const detailsElement = append(markerElement, sourceAndCodeElement);
                detailsElement.style.opacity = '0.6';
                detailsElement.style.paddingLeft = '6px';
            }
            else {
                const detailsElement = append(markerElement, markerHoverParticipant_$('span'));
                detailsElement.style.opacity = '0.6';
                detailsElement.style.paddingLeft = '6px';
                detailsElement.innerText = source && code ? `${source}(${code})` : source ? source : `(${code})`;
            }
        }
        if (isNonEmptyArray(relatedInformation)) {
            for (const { message, resource, startLineNumber, startColumn } of relatedInformation) {
                const relatedInfoContainer = append(markerElement, markerHoverParticipant_$('div'));
                relatedInfoContainer.style.marginTop = '8px';
                const a = append(relatedInfoContainer, markerHoverParticipant_$('a'));
                a.innerText = `${resources_basename(resource)}(${startLineNumber}, ${startColumn}): `;
                a.style.cursor = 'pointer';
                disposables.add(addDisposableListener(a, 'click', (e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    if (this._openerService) {
                        this._openerService.open(resource, {
                            fromUserGesture: true,
                            editorOptions: { selection: { startLineNumber, startColumn } }
                        }).catch(onUnexpectedError);
                    }
                }));
                const messageElement = append(relatedInfoContainer, markerHoverParticipant_$('span'));
                messageElement.innerText = message;
                this._editor.applyFontInfo(messageElement);
            }
        }
        return hoverElement;
    }
    renderMarkerStatusbar(context, markerHover, disposables) {
        if (markerHover.marker.severity === MarkerSeverity.Error || markerHover.marker.severity === MarkerSeverity.Warning || markerHover.marker.severity === MarkerSeverity.Info) {
            context.statusBar.addAction({
                label: localize('view problem', "View Problem"),
                commandId: NextMarkerAction.ID,
                run: () => {
                    var _a;
                    context.hide();
                    (_a = MarkerController.get(this._editor)) === null || _a === void 0 ? void 0 : _a.showAtMarker(markerHover.marker);
                    this._editor.focus();
                }
            });
        }
        if (!this._editor.getOption(83 /* EditorOption.readOnly */)) {
            const quickfixPlaceholderElement = context.statusBar.append(markerHoverParticipant_$('div'));
            if (this.recentMarkerCodeActionsInfo) {
                if (IMarkerData.makeKey(this.recentMarkerCodeActionsInfo.marker) === IMarkerData.makeKey(markerHover.marker)) {
                    if (!this.recentMarkerCodeActionsInfo.hasCodeActions) {
                        quickfixPlaceholderElement.textContent = localize('noQuickFixes', "No quick fixes available");
                    }
                }
                else {
                    this.recentMarkerCodeActionsInfo = undefined;
                }
            }
            const updatePlaceholderDisposable = this.recentMarkerCodeActionsInfo && !this.recentMarkerCodeActionsInfo.hasCodeActions ? Disposable.None : disposables.add(disposableTimeout(() => quickfixPlaceholderElement.textContent = localize('checkingForQuickFixes', "Checking for quick fixes..."), 200));
            if (!quickfixPlaceholderElement.textContent) {
                // Have some content in here to avoid flickering
                quickfixPlaceholderElement.textContent = String.fromCharCode(0xA0); // &nbsp;
            }
            const codeActionsPromise = this.getCodeActions(markerHover.marker);
            disposables.add(toDisposable(() => codeActionsPromise.cancel()));
            codeActionsPromise.then(actions => {
                updatePlaceholderDisposable.dispose();
                this.recentMarkerCodeActionsInfo = { marker: markerHover.marker, hasCodeActions: actions.validActions.length > 0 };
                if (!this.recentMarkerCodeActionsInfo.hasCodeActions) {
                    actions.dispose();
                    quickfixPlaceholderElement.textContent = localize('noQuickFixes', "No quick fixes available");
                    return;
                }
                quickfixPlaceholderElement.style.display = 'none';
                let showing = false;
                disposables.add(toDisposable(() => {
                    if (!showing) {
                        actions.dispose();
                    }
                }));
                context.statusBar.addAction({
                    label: localize('quick fixes', "Quick Fix..."),
                    commandId: QuickFixAction.Id,
                    run: (target) => {
                        showing = true;
                        const controller = QuickFixController.get(this._editor);
                        const elementPosition = getDomNodePagePosition(target);
                        // Hide the hover pre-emptively, otherwise the editor can close the code actions
                        // context menu as well when using keyboard navigation
                        context.hide();
                        controller === null || controller === void 0 ? void 0 : controller.showCodeActions(markerCodeActionTrigger, actions, {
                            x: elementPosition.left + 6,
                            y: elementPosition.top + elementPosition.height + 6,
                            width: elementPosition.width,
                            height: elementPosition.height
                        });
                    }
                });
            }, onUnexpectedError);
        }
    }
    getCodeActions(marker) {
        return createCancelablePromise(cancellationToken => {
            return getCodeActions(this._languageFeaturesService.codeActionProvider, this._editor.getModel(), new Range(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn), markerCodeActionTrigger, Progress.None, cancellationToken);
        });
    }
};
MarkerHoverParticipant = markerHoverParticipant_decorate([
    markerHoverParticipant_param(1, IMarkerDecorationsService),
    markerHoverParticipant_param(2, IOpenerService),
    markerHoverParticipant_param(3, ILanguageFeaturesService)
], MarkerHoverParticipant);

registerThemingParticipant((theme, collector) => {
    const linkFg = theme.getColor(textLinkForeground);
    if (linkFg) {
        collector.addRule(`.monaco-hover .hover-contents a.code-link span { color: ${linkFg}; }`);
    }
    const activeLinkFg = theme.getColor(textLinkActiveForeground);
    if (activeLinkFg) {
        collector.addRule(`.monaco-hover .hover-contents a.code-link span:hover { color: ${activeLinkFg}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/hover/browser/hover.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var hover_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var hover_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};


















let ModesHoverController = class ModesHoverController {
    constructor(_editor, _instantiationService, _openerService, _languageService, _contextKeyService) {
        this._editor = _editor;
        this._instantiationService = _instantiationService;
        this._openerService = _openerService;
        this._languageService = _languageService;
        this._toUnhook = new DisposableStore();
        this._isMouseDown = false;
        this._hoverClicked = false;
        this._contentWidget = null;
        this._glyphWidget = null;
        this._hookEvents();
        this._didChangeConfigurationHandler = this._editor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(55 /* EditorOption.hover */)) {
                this._unhookEvents();
                this._hookEvents();
            }
        });
    }
    static get(editor) {
        return editor.getContribution(ModesHoverController.ID);
    }
    _hookEvents() {
        const hideWidgetsEventHandler = () => this._hideWidgets();
        const hoverOpts = this._editor.getOption(55 /* EditorOption.hover */);
        this._isHoverEnabled = hoverOpts.enabled;
        this._isHoverSticky = hoverOpts.sticky;
        if (this._isHoverEnabled) {
            this._toUnhook.add(this._editor.onMouseDown((e) => this._onEditorMouseDown(e)));
            this._toUnhook.add(this._editor.onMouseUp((e) => this._onEditorMouseUp(e)));
            this._toUnhook.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
            this._toUnhook.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
        }
        else {
            this._toUnhook.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
            this._toUnhook.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
        }
        this._toUnhook.add(this._editor.onMouseLeave((e) => this._onEditorMouseLeave(e)));
        this._toUnhook.add(this._editor.onDidChangeModel(hideWidgetsEventHandler));
        this._toUnhook.add(this._editor.onDidScrollChange((e) => this._onEditorScrollChanged(e)));
    }
    _unhookEvents() {
        this._toUnhook.clear();
    }
    _onEditorScrollChanged(e) {
        if (e.scrollTopChanged || e.scrollLeftChanged) {
            this._hideWidgets();
        }
    }
    _onEditorMouseDown(mouseEvent) {
        this._isMouseDown = true;
        const target = mouseEvent.target;
        if (target.type === 9 /* MouseTargetType.CONTENT_WIDGET */ && target.detail === ContentHoverWidget.ID) {
            this._hoverClicked = true;
            // mouse down on top of content hover widget
            return;
        }
        if (target.type === 12 /* MouseTargetType.OVERLAY_WIDGET */ && target.detail === MarginHoverWidget.ID) {
            // mouse down on top of overlay hover widget
            return;
        }
        if (target.type !== 12 /* MouseTargetType.OVERLAY_WIDGET */) {
            this._hoverClicked = false;
        }
        this._hideWidgets();
    }
    _onEditorMouseUp(mouseEvent) {
        this._isMouseDown = false;
    }
    _onEditorMouseLeave(mouseEvent) {
        var _a;
        const targetEm = (mouseEvent.event.browserEvent.relatedTarget);
        if ((_a = this._contentWidget) === null || _a === void 0 ? void 0 : _a.containsNode(targetEm)) {
            // when the mouse is inside hover widget
            return;
        }
        this._hideWidgets();
    }
    _onEditorMouseMove(mouseEvent) {
        var _a, _b, _c, _d, _e;
        const target = mouseEvent.target;
        if (this._isMouseDown && this._hoverClicked) {
            return;
        }
        if (this._isHoverSticky && target.type === 9 /* MouseTargetType.CONTENT_WIDGET */ && target.detail === ContentHoverWidget.ID) {
            // mouse moved on top of content hover widget
            return;
        }
        if (this._isHoverSticky && !((_b = (_a = mouseEvent.event.browserEvent.view) === null || _a === void 0 ? void 0 : _a.getSelection()) === null || _b === void 0 ? void 0 : _b.isCollapsed)) {
            // selected text within content hover widget
            return;
        }
        if (!this._isHoverSticky && target.type === 9 /* MouseTargetType.CONTENT_WIDGET */ && target.detail === ContentHoverWidget.ID
            && ((_c = this._contentWidget) === null || _c === void 0 ? void 0 : _c.isColorPickerVisible())) {
            // though the hover is not sticky, the color picker needs to.
            return;
        }
        if (this._isHoverSticky && target.type === 12 /* MouseTargetType.OVERLAY_WIDGET */ && target.detail === MarginHoverWidget.ID) {
            // mouse moved on top of overlay hover widget
            return;
        }
        if (!this._isHoverEnabled) {
            this._hideWidgets();
            return;
        }
        const contentWidget = this._getOrCreateContentWidget();
        if (contentWidget.maybeShowAt(mouseEvent)) {
            (_d = this._glyphWidget) === null || _d === void 0 ? void 0 : _d.hide();
            return;
        }
        if (target.type === 2 /* MouseTargetType.GUTTER_GLYPH_MARGIN */ && target.position) {
            (_e = this._contentWidget) === null || _e === void 0 ? void 0 : _e.hide();
            if (!this._glyphWidget) {
                this._glyphWidget = new MarginHoverWidget(this._editor, this._languageService, this._openerService);
            }
            this._glyphWidget.startShowingAt(target.position.lineNumber);
            return;
        }
        this._hideWidgets();
    }
    _onKeyDown(e) {
        if (e.keyCode !== 5 /* KeyCode.Ctrl */ && e.keyCode !== 6 /* KeyCode.Alt */ && e.keyCode !== 57 /* KeyCode.Meta */ && e.keyCode !== 4 /* KeyCode.Shift */) {
            // Do not hide hover when a modifier key is pressed
            this._hideWidgets();
        }
    }
    _hideWidgets() {
        var _a, _b, _c;
        if ((this._isMouseDown && this._hoverClicked && ((_a = this._contentWidget) === null || _a === void 0 ? void 0 : _a.isColorPickerVisible()))) {
            return;
        }
        this._hoverClicked = false;
        (_b = this._glyphWidget) === null || _b === void 0 ? void 0 : _b.hide();
        (_c = this._contentWidget) === null || _c === void 0 ? void 0 : _c.hide();
    }
    _getOrCreateContentWidget() {
        if (!this._contentWidget) {
            this._contentWidget = this._instantiationService.createInstance(ContentHoverController, this._editor);
        }
        return this._contentWidget;
    }
    isColorPickerVisible() {
        var _a;
        return ((_a = this._contentWidget) === null || _a === void 0 ? void 0 : _a.isColorPickerVisible()) || false;
    }
    showContentHover(range, mode, focus) {
        this._getOrCreateContentWidget().startShowingAtRange(range, mode, focus);
    }
    dispose() {
        var _a, _b;
        this._unhookEvents();
        this._toUnhook.dispose();
        this._didChangeConfigurationHandler.dispose();
        (_a = this._glyphWidget) === null || _a === void 0 ? void 0 : _a.dispose();
        (_b = this._contentWidget) === null || _b === void 0 ? void 0 : _b.dispose();
    }
};
ModesHoverController.ID = 'editor.contrib.hover';
ModesHoverController = hover_decorate([
    hover_param(1, IInstantiationService),
    hover_param(2, IOpenerService),
    hover_param(3, ILanguageService),
    hover_param(4, IContextKeyService)
], ModesHoverController);

class ShowHoverAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.showHover',
            label: localize({
                key: 'showHover',
                comment: [
                    'Label for action that will trigger the showing of a hover in the editor.',
                    'This allows for users to show the hover without using the mouse.'
                ]
            }, "Show Hover"),
            alias: 'Show Hover',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        if (!editor.hasModel()) {
            return;
        }
        const controller = ModesHoverController.get(editor);
        if (!controller) {
            return;
        }
        const position = editor.getPosition();
        const range = new Range(position.lineNumber, position.column, position.lineNumber, position.column);
        const focus = editor.getOption(2 /* EditorOption.accessibilitySupport */) === 2 /* AccessibilitySupport.Enabled */;
        controller.showContentHover(range, 1 /* HoverStartMode.Immediate */, focus);
    }
}
class ShowDefinitionPreviewHoverAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.showDefinitionPreviewHover',
            label: localize({
                key: 'showDefinitionPreviewHover',
                comment: [
                    'Label for action that will trigger the showing of definition preview hover in the editor.',
                    'This allows for users to show the definition preview hover without using the mouse.'
                ]
            }, "Show Definition Preview Hover"),
            alias: 'Show Definition Preview Hover',
            precondition: undefined
        });
    }
    run(accessor, editor) {
        const controller = ModesHoverController.get(editor);
        if (!controller) {
            return;
        }
        const position = editor.getPosition();
        if (!position) {
            return;
        }
        const range = new Range(position.lineNumber, position.column, position.lineNumber, position.column);
        const goto = GotoDefinitionAtPositionEditorContribution.get(editor);
        if (!goto) {
            return;
        }
        const promise = goto.startFindDefinitionFromCursor(position);
        promise.then(() => {
            controller.showContentHover(range, 1 /* HoverStartMode.Immediate */, true);
        });
    }
}
registerEditorContribution(ModesHoverController.ID, ModesHoverController);
registerEditorAction(ShowHoverAction);
registerEditorAction(ShowDefinitionPreviewHoverAction);
HoverParticipantRegistry.register(MarkdownHoverParticipant);
HoverParticipantRegistry.register(MarkerHoverParticipant);
// theming
registerThemingParticipant((theme, collector) => {
    const editorHoverHighlightColor = theme.getColor(editorHoverHighlight);
    if (editorHoverHighlightColor) {
        collector.addRule(`.monaco-editor .hoverHighlight { background-color: ${editorHoverHighlightColor}; }`);
    }
    const hoverBackground = theme.getColor(editorHoverBackground);
    if (hoverBackground) {
        collector.addRule(`.monaco-editor .monaco-hover { background-color: ${hoverBackground}; }`);
    }
    const hoverBorder = theme.getColor(editorHoverBorder);
    if (hoverBorder) {
        collector.addRule(`.monaco-editor .monaco-hover { border: 1px solid ${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)}; }`);
    }
    const link = theme.getColor(textLinkForeground);
    if (link) {
        collector.addRule(`.monaco-editor .monaco-hover a { color: ${link}; }`);
    }
    const linkHover = theme.getColor(textLinkActiveForeground);
    if (linkHover) {
        collector.addRule(`.monaco-editor .monaco-hover a:hover { color: ${linkHover}; }`);
    }
    const hoverForeground = theme.getColor(editorHoverForeground);
    if (hoverForeground) {
        collector.addRule(`.monaco-editor .monaco-hover { color: ${hoverForeground}; }`);
    }
    const actionsBackground = theme.getColor(editorHoverStatusBarBackground);
    if (actionsBackground) {
        collector.addRule(`.monaco-editor .monaco-hover .hover-row .actions { background-color: ${actionsBackground}; }`);
    }
    const codeBackground = theme.getColor(textCodeBlockBackground);
    if (codeBackground) {
        collector.addRule(`.monaco-editor .monaco-hover code { background-color: ${codeBackground}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/colorPicker/browser/colorContributions.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







class ColorContribution extends Disposable {
    constructor(_editor) {
        super();
        this._editor = _editor;
        this._register(_editor.onMouseDown((e) => this.onMouseDown(e)));
    }
    dispose() {
        super.dispose();
    }
    onMouseDown(mouseEvent) {
        const target = mouseEvent.target;
        if (target.type !== 6 /* MouseTargetType.CONTENT_TEXT */) {
            return;
        }
        if (!target.detail.injectedText) {
            return;
        }
        if (target.detail.injectedText.options.attachedData !== ColorDecorationInjectedTextMarker) {
            return;
        }
        if (!target.range) {
            return;
        }
        const hoverController = this._editor.getContribution(ModesHoverController.ID);
        if (!hoverController) {
            return;
        }
        if (!hoverController.isColorPickerVisible()) {
            const range = new Range(target.range.startLineNumber, target.range.startColumn + 1, target.range.endLineNumber, target.range.endColumn + 1);
            hoverController.showContentHover(range, 1 /* HoverStartMode.Immediate */, false);
        }
    }
}
ColorContribution.ID = 'editor.contrib.colorContribution'; // ms
registerEditorContribution(ColorContribution.ID, ColorContribution);
HoverParticipantRegistry.register(ColorHoverParticipant);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/core/editOperation.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class EditOperation {
    static insert(position, text) {
        return {
            range: new Range(position.lineNumber, position.column, position.lineNumber, position.column),
            text: text,
            forceMoveMarkers: true
        };
    }
    static delete(range) {
        return {
            range: range,
            text: null
        };
    }
    static replace(range, text) {
        return {
            range: range,
            text: text
        };
    }
    static replaceMove(range, text) {
        return {
            range: range,
            text: text,
            forceMoveMarkers: true
        };
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/comment/browser/blockCommentCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class BlockCommentCommand {
    constructor(selection, insertSpace, languageConfigurationService) {
        this.languageConfigurationService = languageConfigurationService;
        this._selection = selection;
        this._insertSpace = insertSpace;
        this._usedEndToken = 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 i = 0; i < needleLength; i++) {
            const codeA = haystack.charCodeAt(offset + i);
            const codeB = needle.charCodeAt(i);
            if (codeA === codeB) {
                continue;
            }
            if (codeA >= 65 /* CharCode.A */ && codeA <= 90 /* CharCode.Z */ && codeA + 32 === codeB) {
                // codeA is upper-case variant of codeB
                continue;
            }
            if (codeB >= 65 /* CharCode.A */ && codeB <= 90 /* CharCode.Z */ && codeB + 32 === codeA) {
                // codeB is upper-case variant of codeA
                continue;
            }
            return false;
        }
        return true;
    }
    _createOperationsForBlockComment(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) {
                    // force to add a block comment
                    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) {
                    // force to add a block comment
                    startTokenIndex = -1;
                    endTokenIndex = -1;
                }
            }
        }
        let ops;
        if (startTokenIndex !== -1 && endTokenIndex !== -1) {
            // Consider spaces as part of the comment tokens
            if (insertSpace && startTokenIndex + startToken.length < startLineText.length && startLineText.charCodeAt(startTokenIndex + startToken.length) === 32 /* CharCode.Space */) {
                // Pretend the start token contains a trailing space
                startToken = startToken + ' ';
            }
            if (insertSpace && endTokenIndex > 0 && endLineText.charCodeAt(endTokenIndex - 1) === 32 /* CharCode.Space */) {
                // Pretend the end token contains a leading space
                endToken = ' ' + endToken;
                endTokenIndex -= 1;
            }
            ops = BlockCommentCommand._createRemoveBlockCommentOperations(new Range(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
        }
        else {
            ops = BlockCommentCommand._createAddBlockCommentOperations(selection, startToken, endToken, this._insertSpace);
            this._usedEndToken = ops.length === 1 ? endToken : null;
        }
        for (const op of ops) {
            builder.addTrackedEditOperation(op.range, op.text);
        }
    }
    static _createRemoveBlockCommentOperations(r, startToken, endToken) {
        const res = [];
        if (!Range.isEmpty(r)) {
            // Remove block comment start
            res.push(EditOperation.delete(new Range(r.startLineNumber, r.startColumn - startToken.length, r.startLineNumber, r.startColumn)));
            // Remove block comment end
            res.push(EditOperation.delete(new Range(r.endLineNumber, r.endColumn, r.endLineNumber, r.endColumn + endToken.length)));
        }
        else {
            // Remove both continuously
            res.push(EditOperation.delete(new Range(r.startLineNumber, r.startColumn - startToken.length, r.endLineNumber, r.endColumn + endToken.length)));
        }
        return res;
    }
    static _createAddBlockCommentOperations(r, startToken, endToken, insertSpace) {
        const res = [];
        if (!Range.isEmpty(r)) {
            // Insert block comment start
            res.push(EditOperation.insert(new Position(r.startLineNumber, r.startColumn), startToken + (insertSpace ? ' ' : '')));
            // Insert block comment end
            res.push(EditOperation.insert(new Position(r.endLineNumber, r.endColumn), (insertSpace ? ' ' : '') + endToken));
        }
        else {
            // Insert both continuously
            res.push(EditOperation.replace(new Range(r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn), startToken + '  ' + endToken));
        }
        return res;
    }
    getEditOperations(model, builder) {
        const startLineNumber = this._selection.startLineNumber;
        const startColumn = this._selection.startColumn;
        model.tokenization.tokenizeIfCheap(startLineNumber);
        const languageId = model.getLanguageIdAtPosition(startLineNumber, startColumn);
        const config = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
        if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) {
            // Mode does not support block comments
            return;
        }
        this._createOperationsForBlockComment(this._selection, config.blockCommentStartToken, config.blockCommentEndToken, this._insertSpace, model, builder);
    }
    computeCursorState(model, helper) {
        const inverseEditOperations = helper.getInverseEditOperations();
        if (inverseEditOperations.length === 2) {
            const startTokenEditOperation = inverseEditOperations[0];
            const endTokenEditOperation = inverseEditOperations[1];
            return new Selection(startTokenEditOperation.range.endLineNumber, startTokenEditOperation.range.endColumn, endTokenEditOperation.range.startLineNumber, endTokenEditOperation.range.startColumn);
        }
        else {
            const srcRange = inverseEditOperations[0].range;
            const deltaColumn = this._usedEndToken ? -this._usedEndToken.length - 1 : 0; // minus 1 space before endToken
            return new Selection(srcRange.endLineNumber, srcRange.endColumn + deltaColumn, srcRange.endLineNumber, srcRange.endColumn + deltaColumn);
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/comment/browser/lineCommentCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class LineCommentCommand {
    constructor(languageConfigurationService, selection, tabSize, type, insertSpace, ignoreEmptyLines, ignoreFirstLine) {
        this.languageConfigurationService = languageConfigurationService;
        this._selection = selection;
        this._tabSize = tabSize;
        this._type = type;
        this._insertSpace = insertSpace;
        this._selectionId = null;
        this._deltaColumn = 0;
        this._moveEndPositionDown = false;
        this._ignoreEmptyLines = ignoreEmptyLines;
        this._ignoreFirstLine = 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 _gatherPreflightCommentStrings(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) {
            // Mode does not support line comments
            return null;
        }
        const lines = [];
        for (let i = 0, lineCount = endLineNumber - startLineNumber + 1; i < lineCount; i++) {
            lines[i] = {
                ignore: false,
                commentStr: 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 /* Type.Toggle */) {
            shouldRemoveComments = true;
        }
        else if (type === 1 /* Type.ForceAdd */) {
            shouldRemoveComments = false;
        }
        else {
            shouldRemoveComments = true;
        }
        for (let i = 0, lineCount = lines.length; i < lineCount; i++) {
            const lineData = lines[i];
            const lineNumber = startLineNumber + i;
            if (lineNumber === startLineNumber && ignoreFirstLine) {
                // first line ignored
                lineData.ignore = true;
                continue;
            }
            const lineContent = model.getLineContent(lineNumber);
            const lineContentStartOffset = strings_firstNonWhitespaceIndex(lineContent);
            if (lineContentStartOffset === -1) {
                // Empty or whitespace only line
                lineData.ignore = ignoreEmptyLines;
                lineData.commentStrOffset = lineContent.length;
                continue;
            }
            onlyWhitespaceLines = false;
            lineData.ignore = false;
            lineData.commentStrOffset = lineContentStartOffset;
            if (shouldRemoveComments && !BlockCommentCommand._haystackHasNeedleAtOffset(lineContent, lineData.commentStr, lineContentStartOffset)) {
                if (type === 0 /* Type.Toggle */) {
                    // Every line so far has been a line comment, but this one is not
                    shouldRemoveComments = false;
                }
                else if (type === 1 /* Type.ForceAdd */) {
                    // Will not happen
                }
                else {
                    lineData.ignore = true;
                }
            }
            if (shouldRemoveComments && insertSpace) {
                // Remove a following space if present
                const commentStrEndOffset = lineContentStartOffset + lineData.commentStrLength;
                if (commentStrEndOffset < lineContent.length && lineContent.charCodeAt(commentStrEndOffset) === 32 /* CharCode.Space */) {
                    lineData.commentStrLength += 1;
                }
            }
        }
        if (type === 0 /* Type.Toggle */ && onlyWhitespaceLines) {
            // For only whitespace lines, we insert comments
            shouldRemoveComments = false;
            // Also, no longer ignore them
            for (let i = 0, lineCount = lines.length; i < lineCount; i++) {
                lines[i].ignore = false;
            }
        }
        return {
            supported: true,
            shouldRemoveComments: shouldRemoveComments,
            lines: 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 = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber, languageConfigurationService);
        if (lines === null) {
            return {
                supported: false
            };
        }
        return LineCommentCommand._analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService);
    }
    /**
     * Given a successful analysis, execute either insert line comments, either remove line comments
     */
    _executeLineComments(model, builder, data, s) {
        let ops;
        if (data.shouldRemoveComments) {
            ops = LineCommentCommand._createRemoveLineCommentsOperations(data.lines, s.startLineNumber);
        }
        else {
            LineCommentCommand._normalizeInsertionPoint(model, data.lines, s.startLineNumber, this._tabSize);
            ops = this._createAddLineCommentsOperations(data.lines, s.startLineNumber);
        }
        const cursorPosition = new Position(s.positionLineNumber, s.positionColumn);
        for (let i = 0, len = ops.length; i < len; i++) {
            builder.addEditOperation(ops[i].range, ops[i].text);
            if (Range.isEmpty(ops[i].range) && Range.getStartPosition(ops[i].range).equals(cursorPosition)) {
                const lineContent = model.getLineContent(cursorPosition.lineNumber);
                if (lineContent.length + 1 === cursorPosition.column) {
                    this._deltaColumn = (ops[i].text || '').length;
                }
            }
        }
        this._selectionId = builder.trackSelection(s);
    }
    _attemptRemoveBlockComment(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);
            }
        }
        // We have to adjust to possible inner white space.
        // For Space after startToken, add Space to startToken - range math will work out.
        if (startTokenIndex !== -1 && model.getLineContent(startLineNumber).charCodeAt(startTokenIndex + startToken.length) === 32 /* CharCode.Space */) {
            startToken += ' ';
        }
        // For Space before endToken, add Space before endToken and shift index one left.
        if (endTokenIndex !== -1 && model.getLineContent(endLineNumber).charCodeAt(endTokenIndex - 1) === 32 /* CharCode.Space */) {
            endToken = ' ' + endToken;
            endTokenIndex -= 1;
        }
        if (startTokenIndex !== -1 && endTokenIndex !== -1) {
            return BlockCommentCommand._createRemoveBlockCommentOperations(new Range(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
        }
        return null;
    }
    /**
     * Given an unsuccessful analysis, delegate to the block comment command
     */
    _executeBlockComment(model, builder, s) {
        model.tokenization.tokenizeIfCheap(s.startLineNumber);
        const languageId = model.getLanguageIdAtPosition(s.startLineNumber, 1);
        const config = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
        if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) {
            // Mode does not support block comments
            return;
        }
        const startToken = config.blockCommentStartToken;
        const endToken = config.blockCommentEndToken;
        let ops = this._attemptRemoveBlockComment(model, s, startToken, endToken);
        if (!ops) {
            if (s.isEmpty()) {
                const lineContent = model.getLineContent(s.startLineNumber);
                let firstNonWhitespaceIndex = strings_firstNonWhitespaceIndex(lineContent);
                if (firstNonWhitespaceIndex === -1) {
                    // Line is empty or contains only whitespace
                    firstNonWhitespaceIndex = lineContent.length;
                }
                ops = BlockCommentCommand._createAddBlockCommentOperations(new Range(s.startLineNumber, firstNonWhitespaceIndex + 1, s.startLineNumber, lineContent.length + 1), startToken, endToken, this._insertSpace);
            }
            else {
                ops = BlockCommentCommand._createAddBlockCommentOperations(new Range(s.startLineNumber, model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), startToken, endToken, this._insertSpace);
            }
            if (ops.length === 1) {
                // Leave cursor after token and Space
                this._deltaColumn = startToken.length + 1;
            }
        }
        this._selectionId = builder.trackSelection(s);
        for (const op of ops) {
            builder.addEditOperation(op.range, op.text);
        }
    }
    getEditOperations(model, builder) {
        let s = this._selection;
        this._moveEndPositionDown = false;
        if (s.startLineNumber === s.endLineNumber && this._ignoreFirstLine) {
            builder.addEditOperation(new Range(s.startLineNumber, model.getLineMaxColumn(s.startLineNumber), s.startLineNumber + 1, 1), s.startLineNumber === model.getLineCount() ? '' : '\n');
            this._selectionId = builder.trackSelection(s);
            return;
        }
        if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
            this._moveEndPositionDown = true;
            s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
        }
        const data = LineCommentCommand._gatherPreflightData(this._type, this._insertSpace, model, s.startLineNumber, s.endLineNumber, this._ignoreEmptyLines, this._ignoreFirstLine, this.languageConfigurationService);
        if (data.supported) {
            return this._executeLineComments(model, builder, data, s);
        }
        return this._executeBlockComment(model, builder, s);
    }
    computeCursorState(model, helper) {
        let result = helper.getTrackedSelection(this._selectionId);
        if (this._moveEndPositionDown) {
            result = result.setEndPosition(result.endLineNumber + 1, 1);
        }
        return new Selection(result.selectionStartLineNumber, result.selectionStartColumn + this._deltaColumn, result.positionLineNumber, result.positionColumn + this._deltaColumn);
    }
    /**
     * Generate edit operations in the remove line comment case
     */
    static _createRemoveLineCommentsOperations(lines, startLineNumber) {
        const res = [];
        for (let i = 0, len = lines.length; i < len; i++) {
            const lineData = lines[i];
            if (lineData.ignore) {
                continue;
            }
            res.push(EditOperation.delete(new Range(startLineNumber + i, lineData.commentStrOffset + 1, startLineNumber + i, lineData.commentStrOffset + lineData.commentStrLength + 1)));
        }
        return res;
    }
    /**
     * Generate edit operations in the add line comment case
     */
    _createAddLineCommentsOperations(lines, startLineNumber) {
        const res = [];
        const afterCommentStr = this._insertSpace ? ' ' : '';
        for (let i = 0, len = lines.length; i < len; i++) {
            const lineData = lines[i];
            if (lineData.ignore) {
                continue;
            }
            res.push(EditOperation.insert(new Position(startLineNumber + i, lineData.commentStrOffset + 1), lineData.commentStr + afterCommentStr));
        }
        return res;
    }
    static nextVisibleColumn(currentVisibleColumn, tabSize, isTab, columnSize) {
        if (isTab) {
            return currentVisibleColumn + (tabSize - (currentVisibleColumn % tabSize));
        }
        return currentVisibleColumn + columnSize;
    }
    /**
     * Adjust insertion points to have them vertically aligned in the add line comment case
     */
    static _normalizeInsertionPoint(model, lines, startLineNumber, tabSize) {
        let minVisibleColumn = 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */;
        let j;
        let lenJ;
        for (let i = 0, len = lines.length; i < len; i++) {
            if (lines[i].ignore) {
                continue;
            }
            const lineContent = model.getLineContent(startLineNumber + i);
            let currentVisibleColumn = 0;
            for (let j = 0, lenJ = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) {
                currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, tabSize, lineContent.charCodeAt(j) === 9 /* CharCode.Tab */, 1);
            }
            if (currentVisibleColumn < minVisibleColumn) {
                minVisibleColumn = currentVisibleColumn;
            }
        }
        minVisibleColumn = Math.floor(minVisibleColumn / tabSize) * tabSize;
        for (let i = 0, len = lines.length; i < len; i++) {
            if (lines[i].ignore) {
                continue;
            }
            const lineContent = model.getLineContent(startLineNumber + i);
            let currentVisibleColumn = 0;
            for (j = 0, lenJ = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) {
                currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, tabSize, lineContent.charCodeAt(j) === 9 /* CharCode.Tab */, 1);
            }
            if (currentVisibleColumn > minVisibleColumn) {
                lines[i].commentStrOffset = j - 1;
            }
            else {
                lines[i].commentStrOffset = j;
            }
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/comment/browser/comment.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









class CommentLineAction extends EditorAction {
    constructor(type, opts) {
        super(opts);
        this._type = type;
    }
    run(accessor, editor) {
        const languageConfigurationService = accessor.get(ILanguageConfigurationService);
        if (!editor.hasModel()) {
            return;
        }
        const model = editor.getModel();
        const commands = [];
        const modelOptions = model.getOptions();
        const commentsOptions = editor.getOption(19 /* EditorOption.comments */);
        const selections = editor.getSelections().map((selection, index) => ({ selection, index, ignoreFirstLine: false }));
        selections.sort((a, b) => Range.compareRangesUsingStarts(a.selection, b.selection));
        // Remove selections that would result in copying the same line
        let prev = selections[0];
        for (let i = 1; i < selections.length; i++) {
            const curr = selections[i];
            if (prev.selection.endLineNumber === curr.selection.startLineNumber) {
                // these two selections would copy the same line
                if (prev.index < curr.index) {
                    // prev wins
                    curr.ignoreFirstLine = true;
                }
                else {
                    // curr wins
                    prev.ignoreFirstLine = true;
                    prev = curr;
                }
            }
        }
        for (const selection of selections) {
            commands.push(new LineCommentCommand(languageConfigurationService, selection.selection, modelOptions.tabSize, this._type, commentsOptions.insertSpace, commentsOptions.ignoreEmptyLines, selection.ignoreFirstLine));
        }
        editor.pushUndoStop();
        editor.executeCommands(this.id, commands);
        editor.pushUndoStop();
    }
}
class ToggleCommentLineAction extends CommentLineAction {
    constructor() {
        super(0 /* Type.Toggle */, {
            id: 'editor.action.commentLine',
            label: localize('comment.line', "Toggle Line Comment"),
            alias: 'Toggle Line Comment',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 85 /* KeyCode.Slash */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarEditMenu,
                group: '5_insert',
                title: localize({ key: 'miToggleLineComment', comment: ['&& denotes a mnemonic'] }, "&&Toggle Line Comment"),
                order: 1
            }
        });
    }
}
class AddLineCommentAction extends CommentLineAction {
    constructor() {
        super(1 /* Type.ForceAdd */, {
            id: 'editor.action.addCommentLine',
            label: localize('comment.line.add', "Add Line Comment"),
            alias: 'Add Line Comment',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 33 /* KeyCode.KeyC */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
class RemoveLineCommentAction extends CommentLineAction {
    constructor() {
        super(2 /* Type.ForceRemove */, {
            id: 'editor.action.removeCommentLine',
            label: localize('comment.line.remove', "Remove Line Comment"),
            alias: 'Remove Line Comment',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 51 /* KeyCode.KeyU */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
class BlockCommentAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.blockComment',
            label: localize('comment.block', "Toggle Block Comment"),
            alias: 'Toggle Block Comment',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 31 /* KeyCode.KeyA */,
                linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 31 /* KeyCode.KeyA */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarEditMenu,
                group: '5_insert',
                title: localize({ key: 'miToggleBlockComment', comment: ['&& denotes a mnemonic'] }, "Toggle &&Block Comment"),
                order: 2
            }
        });
    }
    run(accessor, editor) {
        const languageConfigurationService = accessor.get(ILanguageConfigurationService);
        if (!editor.hasModel()) {
            return;
        }
        const commentsOptions = editor.getOption(19 /* EditorOption.comments */);
        const commands = [];
        const selections = editor.getSelections();
        for (const selection of selections) {
            commands.push(new BlockCommentCommand(selection, commentsOptions.insertSpace, languageConfigurationService));
        }
        editor.pushUndoStop();
        editor.executeCommands(this.id, commands);
        editor.pushUndoStop();
    }
}
registerEditorAction(ToggleCommentLineAction);
registerEditorAction(AddLineCommentAction);
registerEditorAction(RemoveLineCommentAction);
registerEditorAction(BlockCommentAction);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/contextmenu/browser/contextmenu.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var contextmenu_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var contextmenu_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};













let ContextMenuController = class ContextMenuController {
    constructor(editor, _contextMenuService, _contextViewService, _contextKeyService, _keybindingService, _menuService, _configurationService) {
        this._contextMenuService = _contextMenuService;
        this._contextViewService = _contextViewService;
        this._contextKeyService = _contextKeyService;
        this._keybindingService = _keybindingService;
        this._menuService = _menuService;
        this._configurationService = _configurationService;
        this._toDispose = new DisposableStore();
        this._contextMenuIsBeingShownCount = 0;
        this._editor = editor;
        this._toDispose.add(this._editor.onContextMenu((e) => this._onContextMenu(e)));
        this._toDispose.add(this._editor.onMouseWheel((e) => {
            if (this._contextMenuIsBeingShownCount > 0) {
                const view = this._contextViewService.getContextViewElement();
                const target = e.srcElement;
                // Event triggers on shadow root host first
                // Check if the context view is under this host before hiding it #103169
                if (!(target.shadowRoot && getShadowRoot(view) === target.shadowRoot)) {
                    this._contextViewService.hideContextView();
                }
            }
        }));
        this._toDispose.add(this._editor.onKeyDown((e) => {
            if (!this._editor.getOption(20 /* EditorOption.contextmenu */)) {
                return; // Context menu is turned off through configuration
            }
            if (e.keyCode === 58 /* KeyCode.ContextMenu */) {
                // Chrome is funny like that
                e.preventDefault();
                e.stopPropagation();
                this.showContextMenu();
            }
        }));
    }
    static get(editor) {
        return editor.getContribution(ContextMenuController.ID);
    }
    _onContextMenu(e) {
        if (!this._editor.hasModel()) {
            return;
        }
        if (!this._editor.getOption(20 /* EditorOption.contextmenu */)) {
            this._editor.focus();
            // Ensure the cursor is at the position of the mouse click
            if (e.target.position && !this._editor.getSelection().containsPosition(e.target.position)) {
                this._editor.setPosition(e.target.position);
            }
            return; // Context menu is turned off through configuration
        }
        if (e.target.type === 12 /* MouseTargetType.OVERLAY_WIDGET */) {
            return; // allow native menu on widgets to support right click on input field for example in find
        }
        if (e.target.type === 6 /* MouseTargetType.CONTENT_TEXT */ && e.target.detail.injectedText) {
            return; // allow native menu on injected text
        }
        e.event.preventDefault();
        e.event.stopPropagation();
        if (e.target.type === 11 /* MouseTargetType.SCROLLBAR */) {
            return this._showScrollbarContextMenu({ x: e.event.posx - 1, width: 2, y: e.event.posy - 1, height: 2 });
        }
        if (e.target.type !== 6 /* MouseTargetType.CONTENT_TEXT */ && e.target.type !== 7 /* MouseTargetType.CONTENT_EMPTY */ && e.target.type !== 1 /* MouseTargetType.TEXTAREA */) {
            return; // only support mouse click into text or native context menu key for now
        }
        // Ensure the editor gets focus if it hasn't, so the right events are being sent to other contributions
        this._editor.focus();
        // Ensure the cursor is at the position of the mouse click
        if (e.target.position) {
            let hasSelectionAtPosition = false;
            for (const selection of this._editor.getSelections()) {
                if (selection.containsPosition(e.target.position)) {
                    hasSelectionAtPosition = true;
                    break;
                }
            }
            if (!hasSelectionAtPosition) {
                this._editor.setPosition(e.target.position);
            }
        }
        // Unless the user triggerd the context menu through Shift+F10, use the mouse position as menu position
        let anchor = null;
        if (e.target.type !== 1 /* MouseTargetType.TEXTAREA */) {
            anchor = { x: e.event.posx - 1, width: 2, y: e.event.posy - 1, height: 2 };
        }
        // Show the context menu
        this.showContextMenu(anchor);
    }
    showContextMenu(anchor) {
        if (!this._editor.getOption(20 /* EditorOption.contextmenu */)) {
            return; // Context menu is turned off through configuration
        }
        if (!this._editor.hasModel()) {
            return;
        }
        // Find actions available for menu
        const menuActions = this._getMenuActions(this._editor.getModel(), this._editor.isSimpleWidget ? MenuId.SimpleEditorContext : MenuId.EditorContext);
        // Show menu if we have actions to show
        if (menuActions.length > 0) {
            this._doShowContextMenu(menuActions, anchor);
        }
    }
    _getMenuActions(model, menuId) {
        const result = [];
        // get menu groups
        const menu = this._menuService.createMenu(menuId, this._contextKeyService);
        const groups = menu.getActions({ arg: model.uri });
        menu.dispose();
        // translate them into other actions
        for (const group of groups) {
            const [, actions] = group;
            let addedItems = 0;
            for (const action of actions) {
                if (action instanceof SubmenuItemAction) {
                    const subActions = this._getMenuActions(model, action.item.submenu);
                    if (subActions.length > 0) {
                        result.push(new SubmenuAction(action.id, action.label, subActions));
                        addedItems++;
                    }
                }
                else {
                    result.push(action);
                    addedItems++;
                }
            }
            if (addedItems) {
                result.push(new Separator());
            }
        }
        if (result.length) {
            result.pop(); // remove last separator
        }
        return result;
    }
    _doShowContextMenu(actions, anchor = null) {
        if (!this._editor.hasModel()) {
            return;
        }
        // Disable hover
        const oldHoverSetting = this._editor.getOption(55 /* EditorOption.hover */);
        this._editor.updateOptions({
            hover: {
                enabled: false
            }
        });
        if (!anchor) {
            // Ensure selection is visible
            this._editor.revealPosition(this._editor.getPosition(), 1 /* ScrollType.Immediate */);
            this._editor.render();
            const cursorCoords = this._editor.getScrolledVisiblePosition(this._editor.getPosition());
            // Translate to absolute editor position
            const editorCoords = getDomNodePagePosition(this._editor.getDomNode());
            const posx = editorCoords.left + cursorCoords.left;
            const posy = editorCoords.top + cursorCoords.top + cursorCoords.height;
            anchor = { x: posx, y: posy };
        }
        const useShadowDOM = this._editor.getOption(117 /* EditorOption.useShadowDOM */) && !isIOS; // Do not use shadow dom on IOS #122035
        // Show menu
        this._contextMenuIsBeingShownCount++;
        this._contextMenuService.showContextMenu({
            domForShadowRoot: useShadowDOM ? this._editor.getDomNode() : undefined,
            getAnchor: () => anchor,
            getActions: () => actions,
            getActionViewItem: (action) => {
                const keybinding = this._keybindingFor(action);
                if (keybinding) {
                    return new ActionViewItem(action, action, { label: true, keybinding: keybinding.getLabel(), isMenu: true });
                }
                const customActionViewItem = action;
                if (typeof customActionViewItem.getActionViewItem === 'function') {
                    return customActionViewItem.getActionViewItem();
                }
                return new ActionViewItem(action, action, { icon: true, label: true, isMenu: true });
            },
            getKeyBinding: (action) => {
                return this._keybindingFor(action);
            },
            onHide: (wasCancelled) => {
                this._contextMenuIsBeingShownCount--;
                this._editor.focus();
                this._editor.updateOptions({
                    hover: oldHoverSetting
                });
            }
        });
    }
    _showScrollbarContextMenu(anchor) {
        if (!this._editor.hasModel()) {
            return;
        }
        const minimapOptions = this._editor.getOption(67 /* EditorOption.minimap */);
        let lastId = 0;
        const createAction = (opts) => {
            return {
                id: `menu-action-${++lastId}`,
                label: opts.label,
                tooltip: '',
                class: undefined,
                enabled: (typeof opts.enabled === 'undefined' ? true : opts.enabled),
                checked: opts.checked,
                run: opts.run,
                dispose: () => null
            };
        };
        const createSubmenuAction = (label, actions) => {
            return new SubmenuAction(`menu-action-${++lastId}`, label, actions, undefined);
        };
        const createEnumAction = (label, enabled, configName, configuredValue, options) => {
            if (!enabled) {
                return createAction({ label, enabled, run: () => { } });
            }
            const createRunner = (value) => {
                return () => {
                    this._configurationService.updateValue(configName, value);
                };
            };
            const actions = [];
            for (const option of options) {
                actions.push(createAction({
                    label: option.label,
                    checked: configuredValue === option.value,
                    run: createRunner(option.value)
                }));
            }
            return createSubmenuAction(label, actions);
        };
        const actions = [];
        actions.push(createAction({
            label: localize('context.minimap.minimap', "Minimap"),
            checked: minimapOptions.enabled,
            run: () => {
                this._configurationService.updateValue(`editor.minimap.enabled`, !minimapOptions.enabled);
            }
        }));
        actions.push(new Separator());
        actions.push(createAction({
            label: localize('context.minimap.renderCharacters', "Render Characters"),
            enabled: minimapOptions.enabled,
            checked: minimapOptions.renderCharacters,
            run: () => {
                this._configurationService.updateValue(`editor.minimap.renderCharacters`, !minimapOptions.renderCharacters);
            }
        }));
        actions.push(createEnumAction(localize('context.minimap.size', "Vertical size"), minimapOptions.enabled, 'editor.minimap.size', minimapOptions.size, [{
                label: localize('context.minimap.size.proportional', "Proportional"),
                value: 'proportional'
            }, {
                label: localize('context.minimap.size.fill', "Fill"),
                value: 'fill'
            }, {
                label: localize('context.minimap.size.fit', "Fit"),
                value: 'fit'
            }]));
        actions.push(createEnumAction(localize('context.minimap.slider', "Slider"), minimapOptions.enabled, 'editor.minimap.showSlider', minimapOptions.showSlider, [{
                label: localize('context.minimap.slider.mouseover', "Mouse Over"),
                value: 'mouseover'
            }, {
                label: localize('context.minimap.slider.always', "Always"),
                value: 'always'
            }]));
        const useShadowDOM = this._editor.getOption(117 /* EditorOption.useShadowDOM */) && !isIOS; // Do not use shadow dom on IOS #122035
        this._contextMenuIsBeingShownCount++;
        this._contextMenuService.showContextMenu({
            domForShadowRoot: useShadowDOM ? this._editor.getDomNode() : undefined,
            getAnchor: () => anchor,
            getActions: () => actions,
            onHide: (wasCancelled) => {
                this._contextMenuIsBeingShownCount--;
                this._editor.focus();
            }
        });
    }
    _keybindingFor(action) {
        return this._keybindingService.lookupKeybinding(action.id);
    }
    dispose() {
        if (this._contextMenuIsBeingShownCount > 0) {
            this._contextViewService.hideContextView();
        }
        this._toDispose.dispose();
    }
};
ContextMenuController.ID = 'editor.contrib.contextmenu';
ContextMenuController = contextmenu_decorate([
    contextmenu_param(1, IContextMenuService),
    contextmenu_param(2, IContextViewService),
    contextmenu_param(3, IContextKeyService),
    contextmenu_param(4, IKeybindingService),
    contextmenu_param(5, IMenuService),
    contextmenu_param(6, IConfigurationService)
], ContextMenuController);

class ShowContextMenu extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.showContextMenu',
            label: localize('action.showContextMenu.label', "Show Editor Context Menu"),
            alias: 'Show Editor Context Menu',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 1024 /* KeyMod.Shift */ | 68 /* KeyCode.F10 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        var _a;
        (_a = ContextMenuController.get(editor)) === null || _a === void 0 ? void 0 : _a.showContextMenu();
    }
}
registerEditorContribution(ContextMenuController.ID, ContextMenuController);
registerEditorAction(ShowContextMenu);

;// ../../node_modules/monaco-editor/esm/vs/base/common/dataTransfer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var dataTransfer_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
function createStringDataTransferItem(stringOrPromise) {
    return {
        asString: () => dataTransfer_awaiter(this, void 0, void 0, function* () { return stringOrPromise; }),
        asFile: () => undefined,
        value: typeof stringOrPromise === 'string' ? stringOrPromise : undefined,
    };
}
function createFileDataTransferItem(fileName, uri, data) {
    return {
        asString: () => dataTransfer_awaiter(this, void 0, void 0, function* () { return ''; }),
        asFile: () => ({ name: fileName, uri, data }),
        value: undefined,
    };
}
class VSDataTransfer {
    constructor() {
        this._entries = new Map();
    }
    get size() {
        return this._entries.size;
    }
    has(mimeType) {
        return this._entries.has(this.toKey(mimeType));
    }
    get(mimeType) {
        var _a;
        return (_a = this._entries.get(this.toKey(mimeType))) === null || _a === void 0 ? void 0 : _a[0];
    }
    append(mimeType, value) {
        const existing = this._entries.get(mimeType);
        if (existing) {
            existing.push(value);
        }
        else {
            this._entries.set(this.toKey(mimeType), [value]);
        }
    }
    replace(mimeType, value) {
        this._entries.set(this.toKey(mimeType), [value]);
    }
    delete(mimeType) {
        this._entries.delete(this.toKey(mimeType));
    }
    *entries() {
        for (const [mine, items] of this._entries.entries()) {
            for (const item of items) {
                yield [mine, item];
            }
        }
    }
    values() {
        return Array.from(this._entries.values()).flat();
    }
    forEach(f) {
        for (const [mime, item] of this.entries()) {
            f(item, mime);
        }
    }
    toKey(mimeType) {
        return mimeType.toLowerCase();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/uuid.js
const generateUuid = (function () {
    // use `randomUUID` if possible
    if (typeof crypto === 'object' && typeof crypto.randomUUID === 'function') {
        return crypto.randomUUID.bind(crypto);
    }
    // use `randomValues` if possible
    let getRandomValues;
    if (typeof crypto === 'object' && typeof crypto.getRandomValues === 'function') {
        getRandomValues = crypto.getRandomValues.bind(crypto);
    }
    else {
        getRandomValues = function (bucket) {
            for (let i = 0; i < bucket.length; i++) {
                bucket[i] = Math.floor(Math.random() * 256);
            }
            return bucket;
        };
    }
    // prep-work
    const _data = new Uint8Array(16);
    const _hex = [];
    for (let i = 0; i < 256; i++) {
        _hex.push(i.toString(16).padStart(2, '0'));
    }
    return function generateUuid() {
        // get data
        getRandomValues(_data);
        // set version bits
        _data[6] = (_data[6] & 0x0f) | 0x40;
        _data[8] = (_data[8] & 0x3f) | 0x80;
        // print as string
        let i = 0;
        let result = '';
        result += _hex[_data[i++]];
        result += _hex[_data[i++]];
        result += _hex[_data[i++]];
        result += _hex[_data[i++]];
        result += '-';
        result += _hex[_data[i++]];
        result += _hex[_data[i++]];
        result += '-';
        result += _hex[_data[i++]];
        result += _hex[_data[i++]];
        result += '-';
        result += _hex[_data[i++]];
        result += _hex[_data[i++]];
        result += '-';
        result += _hex[_data[i++]];
        result += _hex[_data[i++]];
        result += _hex[_data[i++]];
        result += _hex[_data[i++]];
        result += _hex[_data[i++]];
        result += _hex[_data[i++]];
        return result;
    };
})();

;// ../../node_modules/monaco-editor/esm/vs/platform/dnd/browser/dnd.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





//#region Editor / Resources DND
const CodeDataTransfers = {
    EDITORS: 'CodeEditors',
    FILES: 'CodeFiles'
};
function extractEditorsDropData(e) {
    var _a;
    const editors = [];
    if (e.dataTransfer && e.dataTransfer.types.length > 0) {
        // Data Transfer: Code Editors
        const rawEditorsData = e.dataTransfer.getData(CodeDataTransfers.EDITORS);
        if (rawEditorsData) {
            try {
                editors.push(...parse(rawEditorsData));
            }
            catch (error) {
                // Invalid transfer
            }
        }
        // Data Transfer: Resources
        else {
            try {
                const rawResourcesData = e.dataTransfer.getData(DataTransfers.RESOURCES);
                editors.push(...createDraggedEditorInputFromRawResourcesData(rawResourcesData));
            }
            catch (error) {
                // Invalid transfer
            }
        }
        // Check for native file transfer
        if ((_a = e.dataTransfer) === null || _a === void 0 ? void 0 : _a.files) {
            for (let i = 0; i < e.dataTransfer.files.length; i++) {
                const file = e.dataTransfer.files[i];
                if (file && file.path /* Electron only */) {
                    try {
                        editors.push({ resource: URI.file(file.path), isExternal: true, allowWorkspaceOpen: true });
                    }
                    catch (error) {
                        // Invalid URI
                    }
                }
            }
        }
        // Check for CodeFiles transfer
        const rawCodeFiles = e.dataTransfer.getData(CodeDataTransfers.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) {
                // Invalid transfer
            }
        }
        // Workbench contributions
        const contributions = Registry.as(dnd_Extensions.DragAndDropContribution).getAll();
        for (const contribution of contributions) {
            const data = e.dataTransfer.getData(contribution.dataFormatKey);
            if (data) {
                try {
                    editors.push(...contribution.getEditorInputs(data));
                }
                catch (error) {
                    // Invalid transfer
                }
            }
        }
    }
    return editors;
}
function createDraggedEditorInputFromRawResourcesData(rawResourcesData) {
    const editors = [];
    if (rawResourcesData) {
        const resourcesRaw = JSON.parse(rawResourcesData);
        for (const resourceRaw of resourcesRaw) {
            if (resourceRaw.indexOf(':') > 0) { // mitigate https://github.com/microsoft/vscode/issues/124946
                const { selection, uri } = extractSelection(URI.parse(resourceRaw));
                editors.push({ resource: uri, options: { selection } });
            }
        }
    }
    return editors;
}
class DragAndDropContributionRegistry {
    constructor() {
        this._contributions = new Map();
    }
    getAll() {
        return this._contributions.values();
    }
}
const dnd_Extensions = {
    DragAndDropContribution: 'workbench.contributions.dragAndDrop'
};
Registry.add(dnd_Extensions.DragAndDropContribution, new DragAndDropContributionRegistry());
//#endregion

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/dnd.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var dnd_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};






function toVSDataTransfer(dataTransfer) {
    const vsDataTransfer = new VSDataTransfer();
    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, createStringDataTransferItem(asStringValue));
        }
        else if (item.kind === 'file') {
            const file = item.getAsFile();
            if (file) {
                vsDataTransfer.append(type, createFileDataTransferItemFromFile(file));
            }
        }
    }
    return vsDataTransfer;
}
function createFileDataTransferItemFromFile(file) {
    const uri = file.path ? URI.parse(file.path) : undefined;
    return createFileDataTransferItem(file.name, uri, () => dnd_awaiter(this, void 0, void 0, function* () {
        return new Uint8Array(yield file.arrayBuffer());
    }));
}
const INTERNAL_DND_MIME_TYPES = Object.freeze([
    CodeDataTransfers.EDITORS,
    CodeDataTransfers.FILES,
    DataTransfers.RESOURCES,
]);
function addExternalEditorsDropData(dataTransfer, dragEvent, overwriteUriList = false) {
    var _a;
    if (dragEvent.dataTransfer && (overwriteUriList || !dataTransfer.has(Mimes.uriList))) {
        const editorData = extractEditorsDropData(dragEvent)
            .filter(input => input.resource)
            .map(input => input.resource.toString());
        // Also add in the files
        for (const item of (_a = dragEvent.dataTransfer) === null || _a === void 0 ? void 0 : _a.items) {
            const file = item.getAsFile();
            if (file) {
                editorData.push(file.path ? URI.file(file.path).toString() : file.name);
            }
        }
        if (editorData.length) {
            dataTransfer.replace(Mimes.uriList, createStringDataTransferItem(UriList.create(editorData)));
        }
    }
    for (const internal of INTERNAL_DND_MIME_TYPES) {
        dataTransfer.delete(internal);
    }
}
const UriList = Object.freeze({
    // http://amundsen.com/hypermedia/urilist/
    create: (entries) => {
        return distinct(entries.map(x => x.toString())).join('\r\n');
    },
    parse: (str) => {
        return str.split('\r\n').filter(value => !value.startsWith('#'));
    }
});

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/snippet/browser/snippetSession.css
var snippetSession = __webpack_require__(74740);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/snippet/browser/snippetSession.css

      
      
      
      
      
      
      
      
      

var snippetSession_options = {};

snippetSession_options.styleTagTransform = (styleTagTransform_default());
snippetSession_options.setAttributes = (setAttributesWithoutAttributes_default());

      snippetSession_options.insert = insertBySelector_default().bind(null, "head");
    
snippetSession_options.domAPI = (styleDomAPI_default());
snippetSession_options.insertStyleElement = (insertStyleElement_default());

var snippetSession_update = injectStylesIntoStyleTag_default()(snippetSession/* default */.A, snippetSession_options);




       /* harmony default export */ const browser_snippetSession = (snippetSession/* default */.A && snippetSession/* default */.A.locals ? snippetSession/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/platform/workspace/common/workspace.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




const IWorkspaceContextService = createDecorator('contextService');
function isSingleFolderWorkspaceIdentifier(obj) {
    const singleFolderIdentifier = obj;
    return typeof (singleFolderIdentifier === null || singleFolderIdentifier === void 0 ? void 0 : singleFolderIdentifier.id) === 'string' && URI.isUri(singleFolderIdentifier.uri);
}
function toWorkspaceIdentifier(workspace) {
    // Multi root
    if (workspace.configuration) {
        return {
            id: workspace.id,
            configPath: workspace.configuration
        };
    }
    // Single folder
    if (workspace.folders.length === 1) {
        return {
            id: workspace.id,
            uri: workspace.folders[0].uri
        };
    }
    // Empty workspace
    return undefined;
}
class Workspace {
    constructor(_id, folders, _transient, _configuration, _ignorePathCasing) {
        this._id = _id;
        this._transient = _transient;
        this._configuration = _configuration;
        this._ignorePathCasing = _ignorePathCasing;
        this._foldersMap = TernarySearchTree.forUris(this._ignorePathCasing, () => true);
        this.folders = folders;
    }
    get folders() {
        return this._folders;
    }
    set folders(folders) {
        this._folders = folders;
        this.updateFoldersMap();
    }
    get id() {
        return this._id;
    }
    get transient() {
        return this._transient;
    }
    get configuration() {
        return this._configuration;
    }
    set configuration(configuration) {
        this._configuration = configuration;
    }
    getFolder(resource) {
        if (!resource) {
            return null;
        }
        return this._foldersMap.findSubstr(resource) || null;
    }
    updateFoldersMap() {
        this._foldersMap = TernarySearchTree.forUris(this._ignorePathCasing, () => true);
        for (const folder of this.folders) {
            this._foldersMap.set(folder.uri, folder);
        }
    }
    toJSON() {
        return { id: this.id, folders: this.folders, transient: this.transient, configuration: this.configuration };
    }
}
class WorkspaceFolder {
    constructor(data, 
    /**
     * Provides access to the original metadata for this workspace
     * folder. This can be different from the metadata provided in
     * this class:
     * - raw paths can be relative
     * - raw paths are not normalized
     */
    raw) {
        this.raw = raw;
        this.uri = data.uri;
        this.index = data.index;
        this.name = data.name;
    }
    toJSON() {
        return { uri: this.uri, name: this.name, index: this.index };
    }
}
const WORKSPACE_EXTENSION = 'code-workspace';
const WORKSPACE_FILTER = [{ name: localize('codeWorkspace', "Code Workspace"), extensions: [WORKSPACE_EXTENSION] }];

;// ../../node_modules/monaco-editor/esm/vs/base/common/labels.js


function normalizeDriveLetter(path, isWindowsOS = isWindows) {
    if (hasDriveLetter(path, isWindowsOS)) {
        return path.charAt(0).toUpperCase() + path.slice(1);
    }
    return path;
}
let normalizedUserHomeCached = Object.create(null);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/snippet/browser/snippetVariables.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var snippetVariables_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var snippetVariables_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};









const KnownSnippetVariableNames = 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,
    '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,
    'CURSOR_NUMBER': true,
    '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
});
class CompositeSnippetVariableResolver {
    constructor(_delegates) {
        this._delegates = _delegates;
        //
    }
    resolve(variable) {
        for (const delegate of this._delegates) {
            const value = delegate.resolve(variable);
            if (value !== undefined) {
                return value;
            }
        }
        return undefined;
    }
}
class SelectionBasedVariableResolver {
    constructor(_model, _selection, _selectionIdx, _overtypingCapturer) {
        this._model = _model;
        this._selection = _selection;
        this._selectionIdx = _selectionIdx;
        this._overtypingCapturer = _overtypingCapturer;
        //
    }
    resolve(variable) {
        const { name } = variable;
        if (name === 'SELECTION' || name === 'TM_SELECTED_TEXT') {
            let value = this._model.getValueInRange(this._selection) || undefined;
            let isMultiline = this._selection.startLineNumber !== this._selection.endLineNumber;
            // If there was no selected text, try to get last overtyped text
            if (!value && this._overtypingCapturer) {
                const info = this._overtypingCapturer.getLastOvertypedInfo(this._selectionIdx);
                if (info) {
                    value = info.value;
                    isMultiline = info.multiline;
                }
            }
            if (value && isMultiline && variable.snippet) {
                // Selection is a multiline string which we indentation we now
                // need to adjust. We compare the indentation of this variable
                // with the indentation at the editor position and add potential
                // extra indentation to the value
                const line = this._model.getLineContent(this._selection.startLineNumber);
                const lineLeadingWhitespace = getLeadingWhitespace(line, 0, this._selection.startColumn - 1);
                let varLeadingWhitespace = lineLeadingWhitespace;
                variable.snippet.walk(marker => {
                    if (marker === variable) {
                        return false;
                    }
                    if (marker instanceof Text) {
                        varLeadingWhitespace = getLeadingWhitespace(splitLines(marker.value).pop());
                    }
                    return true;
                });
                const whitespaceCommonLength = strings_commonPrefixLength(varLeadingWhitespace, lineLeadingWhitespace);
                value = value.replace(/(\r\n|\r|\n)(.*)/g, (m, newline, rest) => `${newline}${varLeadingWhitespace.substr(whitespaceCommonLength)}${rest}`);
            }
            return value;
        }
        else if (name === 'TM_CURRENT_LINE') {
            return this._model.getLineContent(this._selection.positionLineNumber);
        }
        else if (name === 'TM_CURRENT_WORD') {
            const info = this._model.getWordAtPosition({
                lineNumber: this._selection.positionLineNumber,
                column: this._selection.positionColumn
            });
            return info && info.word || undefined;
        }
        else if (name === 'TM_LINE_INDEX') {
            return String(this._selection.positionLineNumber - 1);
        }
        else if (name === 'TM_LINE_NUMBER') {
            return String(this._selection.positionLineNumber);
        }
        else if (name === 'CURSOR_INDEX') {
            return String(this._selectionIdx);
        }
        else if (name === 'CURSOR_NUMBER') {
            return String(this._selectionIdx + 1);
        }
        return undefined;
    }
}
class ModelBasedVariableResolver {
    constructor(_labelService, _model) {
        this._labelService = _labelService;
        this._model = _model;
        //
    }
    resolve(variable) {
        const { name } = variable;
        if (name === 'TM_FILENAME') {
            return basename(this._model.uri.fsPath);
        }
        else if (name === 'TM_FILENAME_BASE') {
            const name = basename(this._model.uri.fsPath);
            const idx = name.lastIndexOf('.');
            if (idx <= 0) {
                return name;
            }
            else {
                return name.slice(0, idx);
            }
        }
        else if (name === 'TM_DIRECTORY') {
            if (path_dirname(this._model.uri.fsPath) === '.') {
                return '';
            }
            return this._labelService.getUriLabel(dirname(this._model.uri));
        }
        else if (name === 'TM_FILEPATH') {
            return this._labelService.getUriLabel(this._model.uri);
        }
        else if (name === 'RELATIVE_FILEPATH') {
            return this._labelService.getUriLabel(this._model.uri, { relative: true, noPrefix: true });
        }
        return undefined;
    }
}
class ClipboardBasedVariableResolver {
    constructor(_readClipboardText, _selectionIdx, _selectionCount, _spread) {
        this._readClipboardText = _readClipboardText;
        this._selectionIdx = _selectionIdx;
        this._selectionCount = _selectionCount;
        this._spread = _spread;
        //
    }
    resolve(variable) {
        if (variable.name !== 'CLIPBOARD') {
            return undefined;
        }
        const clipboardText = this._readClipboardText();
        if (!clipboardText) {
            return undefined;
        }
        // `spread` is assigning each cursor a line of the clipboard
        // text whenever there the line count equals the cursor count
        // and when enabled
        if (this._spread) {
            const lines = clipboardText.split(/\r\n|\n|\r/).filter(s => !isFalsyOrWhitespace(s));
            if (lines.length === this._selectionCount) {
                return lines[this._selectionIdx];
            }
        }
        return clipboardText;
    }
}
let CommentBasedVariableResolver = class CommentBasedVariableResolver {
    constructor(_model, _selection, _languageConfigurationService) {
        this._model = _model;
        this._selection = _selection;
        this._languageConfigurationService = _languageConfigurationService;
        //
    }
    resolve(variable) {
        const { name } = variable;
        const langId = this._model.getLanguageIdAtPosition(this._selection.selectionStartLineNumber, this._selection.selectionStartColumn);
        const config = this._languageConfigurationService.getLanguageConfiguration(langId).comments;
        if (!config) {
            return undefined;
        }
        if (name === 'LINE_COMMENT') {
            return config.lineCommentToken || undefined;
        }
        else if (name === 'BLOCK_COMMENT_START') {
            return config.blockCommentStartToken || undefined;
        }
        else if (name === 'BLOCK_COMMENT_END') {
            return config.blockCommentEndToken || undefined;
        }
        return undefined;
    }
};
CommentBasedVariableResolver = snippetVariables_decorate([
    snippetVariables_param(2, ILanguageConfigurationService)
], CommentBasedVariableResolver);

class TimeBasedVariableResolver {
    constructor() {
        this._date = new Date();
    }
    resolve(variable) {
        const { name } = variable;
        if (name === 'CURRENT_YEAR') {
            return String(this._date.getFullYear());
        }
        else if (name === 'CURRENT_YEAR_SHORT') {
            return String(this._date.getFullYear()).slice(-2);
        }
        else if (name === 'CURRENT_MONTH') {
            return String(this._date.getMonth().valueOf() + 1).padStart(2, '0');
        }
        else if (name === 'CURRENT_DATE') {
            return String(this._date.getDate().valueOf()).padStart(2, '0');
        }
        else if (name === 'CURRENT_HOUR') {
            return String(this._date.getHours().valueOf()).padStart(2, '0');
        }
        else if (name === 'CURRENT_MINUTE') {
            return String(this._date.getMinutes().valueOf()).padStart(2, '0');
        }
        else if (name === 'CURRENT_SECOND') {
            return String(this._date.getSeconds().valueOf()).padStart(2, '0');
        }
        else if (name === 'CURRENT_DAY_NAME') {
            return TimeBasedVariableResolver.dayNames[this._date.getDay()];
        }
        else if (name === 'CURRENT_DAY_NAME_SHORT') {
            return TimeBasedVariableResolver.dayNamesShort[this._date.getDay()];
        }
        else if (name === 'CURRENT_MONTH_NAME') {
            return TimeBasedVariableResolver.monthNames[this._date.getMonth()];
        }
        else if (name === 'CURRENT_MONTH_NAME_SHORT') {
            return TimeBasedVariableResolver.monthNamesShort[this._date.getMonth()];
        }
        else if (name === 'CURRENT_SECONDS_UNIX') {
            return String(Math.floor(this._date.getTime() / 1000));
        }
        return undefined;
    }
}
TimeBasedVariableResolver.dayNames = [localize('Sunday', "Sunday"), localize('Monday', "Monday"), localize('Tuesday', "Tuesday"), localize('Wednesday', "Wednesday"), localize('Thursday', "Thursday"), localize('Friday', "Friday"), localize('Saturday', "Saturday")];
TimeBasedVariableResolver.dayNamesShort = [localize('SundayShort', "Sun"), localize('MondayShort', "Mon"), localize('TuesdayShort', "Tue"), localize('WednesdayShort', "Wed"), localize('ThursdayShort', "Thu"), localize('FridayShort', "Fri"), localize('SaturdayShort', "Sat")];
TimeBasedVariableResolver.monthNames = [localize('January', "January"), localize('February', "February"), localize('March', "March"), localize('April', "April"), localize('May', "May"), localize('June', "June"), localize('July', "July"), localize('August', "August"), localize('September', "September"), localize('October', "October"), localize('November', "November"), localize('December', "December")];
TimeBasedVariableResolver.monthNamesShort = [localize('JanuaryShort', "Jan"), localize('FebruaryShort', "Feb"), localize('MarchShort', "Mar"), localize('AprilShort', "Apr"), localize('MayShort', "May"), localize('JuneShort', "Jun"), localize('JulyShort', "Jul"), localize('AugustShort', "Aug"), localize('SeptemberShort', "Sep"), localize('OctoberShort', "Oct"), localize('NovemberShort', "Nov"), localize('DecemberShort', "Dec")];
class WorkspaceBasedVariableResolver {
    constructor(_workspaceService) {
        this._workspaceService = _workspaceService;
        //
    }
    resolve(variable) {
        if (!this._workspaceService) {
            return undefined;
        }
        const workspaceIdentifier = toWorkspaceIdentifier(this._workspaceService.getWorkspace());
        if (!workspaceIdentifier) {
            return undefined;
        }
        if (variable.name === 'WORKSPACE_NAME') {
            return this._resolveWorkspaceName(workspaceIdentifier);
        }
        else if (variable.name === 'WORKSPACE_FOLDER') {
            return this._resoveWorkspacePath(workspaceIdentifier);
        }
        return undefined;
    }
    _resolveWorkspaceName(workspaceIdentifier) {
        if (isSingleFolderWorkspaceIdentifier(workspaceIdentifier)) {
            return basename(workspaceIdentifier.uri.path);
        }
        let filename = basename(workspaceIdentifier.configPath.path);
        if (filename.endsWith(WORKSPACE_EXTENSION)) {
            filename = filename.substr(0, filename.length - WORKSPACE_EXTENSION.length - 1);
        }
        return filename;
    }
    _resoveWorkspacePath(workspaceIdentifier) {
        if (isSingleFolderWorkspaceIdentifier(workspaceIdentifier)) {
            return normalizeDriveLetter(workspaceIdentifier.uri.fsPath);
        }
        const filename = basename(workspaceIdentifier.configPath.path);
        let folderpath = workspaceIdentifier.configPath.fsPath;
        if (folderpath.endsWith(filename)) {
            folderpath = folderpath.substr(0, folderpath.length - filename.length - 1);
        }
        return (folderpath ? normalizeDriveLetter(folderpath) : '/');
    }
}
class RandomBasedVariableResolver {
    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 generateUuid();
        }
        return undefined;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/snippet/browser/snippetSession.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var snippetSession_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var snippetSession_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};













class OneSnippet {
    constructor(_editor, _snippet, _snippetLineLeadingWhitespace) {
        this._editor = _editor;
        this._snippet = _snippet;
        this._snippetLineLeadingWhitespace = _snippetLineLeadingWhitespace;
        this._offset = -1;
        this._nestingLevel = 1;
        this._placeholderGroups = groupBy(_snippet.placeholders, Placeholder.compareByIndex);
        this._placeholderGroupsIdx = -1;
    }
    initialize(textChange) {
        this._offset = textChange.newPosition;
    }
    dispose() {
        if (this._placeholderDecorations) {
            this._editor.removeDecorations([...this._placeholderDecorations.values()]);
        }
        this._placeholderGroups.length = 0;
    }
    _initDecorations() {
        if (this._offset === -1) {
            throw new Error(`Snippet not initialized!`);
        }
        if (this._placeholderDecorations) {
            // already initialized
            return;
        }
        this._placeholderDecorations = new Map();
        const model = this._editor.getModel();
        this._editor.changeDecorations(accessor => {
            // create a decoration for each placeholder
            for (const placeholder of this._snippet.placeholders) {
                const placeholderOffset = this._snippet.offset(placeholder);
                const placeholderLen = this._snippet.fullLen(placeholder);
                const range = Range.fromPositions(model.getPositionAt(this._offset + placeholderOffset), model.getPositionAt(this._offset + placeholderOffset + placeholderLen));
                const options = placeholder.isFinalTabstop ? OneSnippet._decor.inactiveFinal : OneSnippet._decor.inactive;
                const handle = accessor.addDecoration(range, options);
                this._placeholderDecorations.set(placeholder, handle);
            }
        });
    }
    move(fwd) {
        if (!this._editor.hasModel()) {
            return [];
        }
        this._initDecorations();
        // Transform placeholder text if necessary
        if (this._placeholderGroupsIdx >= 0) {
            const operations = [];
            for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
                // Check if the placeholder has a transformation
                if (placeholder.transform) {
                    const id = this._placeholderDecorations.get(placeholder);
                    const range = this._editor.getModel().getDecorationRange(id);
                    const currentValue = this._editor.getModel().getValueInRange(range);
                    const transformedValueLines = placeholder.transform.resolve(currentValue).split(/\r\n|\r|\n/);
                    // fix indentation for transformed lines
                    for (let i = 1; i < transformedValueLines.length; i++) {
                        transformedValueLines[i] = this._editor.getModel().normalizeIndentation(this._snippetLineLeadingWhitespace + transformedValueLines[i]);
                    }
                    operations.push(EditOperation.replace(range, transformedValueLines.join(this._editor.getModel().getEOL())));
                }
            }
            if (operations.length > 0) {
                this._editor.executeEdits('snippet.placeholderTransform', operations);
            }
        }
        let couldSkipThisPlaceholder = false;
        if (fwd === true && this._placeholderGroupsIdx < this._placeholderGroups.length - 1) {
            this._placeholderGroupsIdx += 1;
            couldSkipThisPlaceholder = true;
        }
        else if (fwd === false && this._placeholderGroupsIdx > 0) {
            this._placeholderGroupsIdx -= 1;
            couldSkipThisPlaceholder = true;
        }
        else {
            // the selection of the current placeholder might
            // not acurate any more -> simply restore it
        }
        const newSelections = this._editor.getModel().changeDecorations(accessor => {
            const activePlaceholders = new Set();
            // change stickiness to always grow when typing at its edges
            // because these decorations represent the currently active
            // tabstop.
            // Special case #1: reaching the final tabstop
            // Special case #2: placeholders enclosing active placeholders
            const selections = [];
            for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
                const id = this._placeholderDecorations.get(placeholder);
                const range = this._editor.getModel().getDecorationRange(id);
                selections.push(new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn));
                // consider to skip this placeholder index when the decoration
                // range is empty but when the placeholder wasn't. that's a strong
                // hint that the placeholder has been deleted. (all placeholder must match this)
                couldSkipThisPlaceholder = couldSkipThisPlaceholder && this._hasPlaceholderBeenCollapsed(placeholder);
                accessor.changeDecorationOptions(id, placeholder.isFinalTabstop ? OneSnippet._decor.activeFinal : OneSnippet._decor.active);
                activePlaceholders.add(placeholder);
                for (const enclosingPlaceholder of this._snippet.enclosingPlaceholders(placeholder)) {
                    const id = this._placeholderDecorations.get(enclosingPlaceholder);
                    accessor.changeDecorationOptions(id, enclosingPlaceholder.isFinalTabstop ? OneSnippet._decor.activeFinal : OneSnippet._decor.active);
                    activePlaceholders.add(enclosingPlaceholder);
                }
            }
            // change stickness to never grow when typing at its edges
            // so that in-active tabstops never grow
            for (const [placeholder, id] of this._placeholderDecorations) {
                if (!activePlaceholders.has(placeholder)) {
                    accessor.changeDecorationOptions(id, placeholder.isFinalTabstop ? OneSnippet._decor.inactiveFinal : OneSnippet._decor.inactive);
                }
            }
            return selections;
        });
        return !couldSkipThisPlaceholder ? newSelections !== null && newSelections !== void 0 ? newSelections : [] : this.move(fwd);
    }
    _hasPlaceholderBeenCollapsed(placeholder) {
        // A placeholder is empty when it wasn't empty when authored but
        // when its tracking decoration is empty. This also applies to all
        // potential parent placeholders
        let marker = placeholder;
        while (marker) {
            if (marker instanceof Placeholder) {
                const id = this._placeholderDecorations.get(marker);
                const range = this._editor.getModel().getDecorationRange(id);
                if (range.isEmpty() && marker.toString().length > 0) {
                    return true;
                }
            }
            marker = marker.parent;
        }
        return false;
    }
    get isAtFirstPlaceholder() {
        return this._placeholderGroupsIdx <= 0 || this._placeholderGroups.length === 0;
    }
    get isAtLastPlaceholder() {
        return this._placeholderGroupsIdx === this._placeholderGroups.length - 1;
    }
    get hasPlaceholder() {
        return this._snippet.placeholders.length > 0;
    }
    get isTrivialSnippet() {
        return this._snippet.placeholders.length === 0
            || (this._snippet.placeholders.length === 1 && this._snippet.placeholders[0].isFinalTabstop);
    }
    computePossibleSelections() {
        const result = new Map();
        for (const placeholdersWithEqualIndex of this._placeholderGroups) {
            let ranges;
            for (const placeholder of placeholdersWithEqualIndex) {
                if (placeholder.isFinalTabstop) {
                    // ignore those
                    break;
                }
                if (!ranges) {
                    ranges = [];
                    result.set(placeholder.index, ranges);
                }
                const id = this._placeholderDecorations.get(placeholder);
                const range = this._editor.getModel().getDecorationRange(id);
                if (!range) {
                    // one of the placeholder lost its decoration and
                    // therefore we bail out and pretend the placeholder
                    // (with its mirrors) doesn't exist anymore.
                    result.delete(placeholder.index);
                    break;
                }
                ranges.push(range);
            }
        }
        return result;
    }
    get activeChoice() {
        if (!this._placeholderDecorations) {
            return undefined;
        }
        const placeholder = this._placeholderGroups[this._placeholderGroupsIdx][0];
        if (!(placeholder === null || placeholder === void 0 ? void 0 : placeholder.choice)) {
            return undefined;
        }
        const id = this._placeholderDecorations.get(placeholder);
        if (!id) {
            return undefined;
        }
        const range = this._editor.getModel().getDecorationRange(id);
        if (!range) {
            return undefined;
        }
        return { range, choice: placeholder.choice };
    }
    get hasChoice() {
        let result = false;
        this._snippet.walk(marker => {
            result = marker instanceof Choice;
            return !result;
        });
        return result;
    }
    merge(others) {
        const model = this._editor.getModel();
        this._nestingLevel *= 10;
        this._editor.changeDecorations(accessor => {
            // For each active placeholder take one snippet and merge it
            // in that the placeholder (can be many for `$1foo$1foo`). Because
            // everything is sorted by editor selection we can simply remove
            // elements from the beginning of the array
            for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
                const nested = others.shift();
                console.assert(nested._offset !== -1);
                console.assert(!nested._placeholderDecorations);
                // Massage placeholder-indicies of the nested snippet to be
                // sorted right after the insertion point. This ensures we move
                // through the placeholders in the correct order
                const indexLastPlaceholder = nested._snippet.placeholderInfo.last.index;
                for (const nestedPlaceholder of nested._snippet.placeholderInfo.all) {
                    if (nestedPlaceholder.isFinalTabstop) {
                        nestedPlaceholder.index = placeholder.index + ((indexLastPlaceholder + 1) / this._nestingLevel);
                    }
                    else {
                        nestedPlaceholder.index = placeholder.index + (nestedPlaceholder.index / this._nestingLevel);
                    }
                }
                this._snippet.replace(placeholder, nested._snippet.children);
                // Remove the placeholder at which position are inserting
                // the snippet and also remove its decoration.
                const id = this._placeholderDecorations.get(placeholder);
                accessor.removeDecoration(id);
                this._placeholderDecorations.delete(placeholder);
                // For each *new* placeholder we create decoration to monitor
                // how and if it grows/shrinks.
                for (const placeholder of nested._snippet.placeholders) {
                    const placeholderOffset = nested._snippet.offset(placeholder);
                    const placeholderLen = nested._snippet.fullLen(placeholder);
                    const range = Range.fromPositions(model.getPositionAt(nested._offset + placeholderOffset), model.getPositionAt(nested._offset + placeholderOffset + placeholderLen));
                    const handle = accessor.addDecoration(range, OneSnippet._decor.inactive);
                    this._placeholderDecorations.set(placeholder, handle);
                }
            }
            // Last, re-create the placeholder groups by sorting placeholders by their index.
            this._placeholderGroups = groupBy(this._snippet.placeholders, Placeholder.compareByIndex);
        });
    }
}
OneSnippet._decor = {
    active: ModelDecorationOptions.register({ description: 'snippet-placeholder-1', stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */, className: 'snippet-placeholder' }),
    inactive: ModelDecorationOptions.register({ description: 'snippet-placeholder-2', stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */, className: 'snippet-placeholder' }),
    activeFinal: ModelDecorationOptions.register({ description: 'snippet-placeholder-3', stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */, className: 'finish-snippet-placeholder' }),
    inactiveFinal: ModelDecorationOptions.register({ description: 'snippet-placeholder-4', stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */, className: 'finish-snippet-placeholder' }),
};
const _defaultOptions = {
    overwriteBefore: 0,
    overwriteAfter: 0,
    adjustWhitespace: true,
    clipboardText: undefined,
    overtypingCapturer: undefined
};
let SnippetSession = class SnippetSession {
    constructor(_editor, _template, _options = _defaultOptions, _languageConfigurationService) {
        this._editor = _editor;
        this._template = _template;
        this._options = _options;
        this._languageConfigurationService = _languageConfigurationService;
        this._templateMerges = [];
        this._snippets = [];
    }
    static adjustWhitespace(model, position, snippet, adjustIndentation, adjustNewlines) {
        const line = model.getLineContent(position.lineNumber);
        const lineLeadingWhitespace = getLeadingWhitespace(line, 0, position.column - 1);
        // the snippet as inserted
        let snippetTextString;
        snippet.walk(marker => {
            // all text elements that are not inside choice
            if (!(marker instanceof Text) || marker.parent instanceof Choice) {
                return true;
            }
            const lines = marker.value.split(/\r\n|\r|\n/);
            if (adjustIndentation) {
                // adjust indentation of snippet test
                // -the snippet-start doesn't get extra-indented (lineLeadingWhitespace), only normalized
                // -all N+1 lines get extra-indented and normalized
                // -the text start get extra-indented and normalized when following a linebreak
                const offset = snippet.offset(marker);
                if (offset === 0) {
                    // snippet start
                    lines[0] = model.normalizeIndentation(lines[0]);
                }
                else {
                    // check if text start is after a linebreak
                    snippetTextString = snippetTextString !== null && snippetTextString !== void 0 ? snippetTextString : snippet.toString();
                    const prevChar = snippetTextString.charCodeAt(offset - 1);
                    if (prevChar === 10 /* CharCode.LineFeed */ || prevChar === 13 /* CharCode.CarriageReturn */) {
                        lines[0] = model.normalizeIndentation(lineLeadingWhitespace + lines[0]);
                    }
                }
                for (let i = 1; i < lines.length; i++) {
                    lines[i] = model.normalizeIndentation(lineLeadingWhitespace + lines[i]);
                }
            }
            const newValue = lines.join(model.getEOL());
            if (newValue !== marker.value) {
                marker.parent.replace(marker, [new Text(newValue)]);
                snippetTextString = undefined;
            }
            return true;
        });
        return lineLeadingWhitespace;
    }
    static adjustSelection(model, selection, overwriteBefore, overwriteAfter) {
        if (overwriteBefore !== 0 || overwriteAfter !== 0) {
            // overwrite[Before|After] is compute using the position, not the whole
            // selection. therefore we adjust the selection around that position
            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 = Selection.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(IWorkspaceContextService));
        const modelBasedVariableResolver = editor.invokeWithinContext(accessor => new ModelBasedVariableResolver(accessor.get(ILabelService), model));
        const readClipboardText = () => clipboardText;
        // know what text the overwrite[Before|After] extensions
        // of the primary curser have selected because only when
        // secondary selections extend to the same text we can grow them
        const firstBeforeText = model.getValueInRange(SnippetSession.adjustSelection(model, editor.getSelection(), overwriteBefore, 0));
        const firstAfterText = model.getValueInRange(SnippetSession.adjustSelection(model, editor.getSelection(), 0, overwriteAfter));
        // remember the first non-whitespace column to decide if
        // `keepWhitespace` should be overruled for secondary selections
        const firstLineFirstNonWhitespace = model.getLineFirstNonWhitespaceColumn(editor.getSelection().positionLineNumber);
        // sort selections by their start position but remeber
        // the original index. that allows you to create correct
        // offset-based selection logic without changing the
        // primary selection
        const indexedSelections = editor.getSelections()
            .map((selection, idx) => ({ selection, idx }))
            .sort((a, b) => Range.compareRangesUsingStarts(a.selection, b.selection));
        for (const { selection, idx } of indexedSelections) {
            // extend selection with the `overwriteBefore` and `overwriteAfter` and then
            // compare if this matches the extensions of the primary selection
            let extensionBefore = SnippetSession.adjustSelection(model, selection, overwriteBefore, 0);
            let extensionAfter = SnippetSession.adjustSelection(model, selection, 0, overwriteAfter);
            if (firstBeforeText !== model.getValueInRange(extensionBefore)) {
                extensionBefore = selection;
            }
            if (firstAfterText !== model.getValueInRange(extensionAfter)) {
                extensionAfter = selection;
            }
            // merge the before and after selection into one
            const snippetSelection = selection
                .setStartPosition(extensionBefore.startLineNumber, extensionBefore.startColumn)
                .setEndPosition(extensionAfter.endLineNumber, extensionAfter.endColumn);
            const snippet = new SnippetParser().parse(template, true, enforceFinalTabstop);
            // adjust the template string to match the indentation and
            // whitespace rules of this insert location (can be different for each cursor)
            // happens when being asked for (default) or when this is a secondary
            // cursor and the leading whitespace is different
            const start = snippetSelection.getStartPosition();
            const snippetLineLeadingWhitespace = SnippetSession.adjustWhitespace(model, start, snippet, adjustWhitespace || (idx > 0 && firstLineFirstNonWhitespace !== model.getLineFirstNonWhitespaceColumn(selection.positionLineNumber)), true);
            snippet.resolveVariables(new CompositeSnippetVariableResolver([
                modelBasedVariableResolver,
                new ClipboardBasedVariableResolver(readClipboardText, idx, indexedSelections.length, editor.getOption(73 /* EditorOption.multiCursorPaste */) === 'spread'),
                new SelectionBasedVariableResolver(model, selection, idx, overtypingCapturer),
                new CommentBasedVariableResolver(model, selection, languageConfigurationService),
                new TimeBasedVariableResolver,
                new WorkspaceBasedVariableResolver(workspaceService),
                new RandomBasedVariableResolver,
            ]));
            // store snippets with the index of their originating selection.
            // that ensures the primiary cursor stays primary despite not being
            // the one with lowest start position
            edits[idx] = EditOperation.replace(snippetSelection, snippet.toString());
            edits[idx].identifier = { major: idx, minor: 0 }; // mark the edit so only our undo edits will be used to generate end cursors
            edits[idx]._isTracked = true;
            snippets[idx] = new OneSnippet(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 parser = new SnippetParser();
        const snippet = new TextmateSnippet();
        // snippet variables resolver
        const resolver = new CompositeSnippetVariableResolver([
            editor.invokeWithinContext(accessor => new ModelBasedVariableResolver(accessor.get(ILabelService), model)),
            new ClipboardBasedVariableResolver(() => clipboardText, 0, editor.getSelections().length, editor.getOption(73 /* EditorOption.multiCursorPaste */) === 'spread'),
            new SelectionBasedVariableResolver(model, editor.getSelection(), 0, overtypingCapturer),
            new CommentBasedVariableResolver(model, editor.getSelection(), languageConfigurationService),
            new TimeBasedVariableResolver,
            new WorkspaceBasedVariableResolver(editor.invokeWithinContext(accessor => accessor.get(IWorkspaceContextService))),
            new RandomBasedVariableResolver,
        ]);
        //
        snippetEdits = snippetEdits.sort((a, b) => Range.compareRangesUsingStarts(a.range, b.range));
        let offset = 0;
        for (let i = 0; i < snippetEdits.length; i++) {
            const { range, template } = snippetEdits[i];
            // gaps between snippet edits are appended as text nodes. this
            // ensures placeholder-offsets are later correct
            if (i > 0) {
                const lastRange = snippetEdits[i - 1].range;
                const textRange = Range.fromPositions(lastRange.getEndPosition(), range.getStartPosition());
                const textNode = new Text(model.getValueInRange(textRange));
                snippet.appendChild(textNode);
                offset += textNode.value.length;
            }
            parser.parseFragment(template, snippet);
            snippet.resolveVariables(resolver);
            const snippetText = snippet.toString();
            const snippetFragmentText = snippetText.slice(offset);
            offset = snippetText.length;
            // make edit
            const edit = EditOperation.replace(range, snippetFragmentText);
            edit.identifier = { major: i, minor: 0 }; // mark the edit so only our undo edits will be used to generate end cursors
            edit._isTracked = true;
            edits.push(edit);
        }
        //
        parser.ensureFinalTabstop(snippet, enforceFinalTabstop, true);
        return {
            edits,
            snippets: [new OneSnippet(editor, snippet, '')]
        };
    }
    dispose() {
        dispose(this._snippets);
    }
    _logInfo() {
        return `template="${this._template}", merged_templates="${this._templateMerges.join(' -> ')}"`;
    }
    insert() {
        if (!this._editor.hasModel()) {
            return;
        }
        // make insert edit and start with first selections
        const { edits, snippets } = typeof this._template === 'string'
            ? SnippetSession.createEditsAndSnippetsFromSelections(this._editor, this._template, this._options.overwriteBefore, this._options.overwriteAfter, false, this._options.adjustWhitespace, this._options.clipboardText, this._options.overtypingCapturer, this._languageConfigurationService)
            : SnippetSession.createEditsAndSnippetsFromEdits(this._editor, this._template, false, this._options.adjustWhitespace, this._options.clipboardText, this._options.overtypingCapturer, this._languageConfigurationService);
        this._snippets = snippets;
        this._editor.executeEdits('snippet', edits, _undoEdits => {
            // Sometimes, the text buffer will remove automatic whitespace when doing any edits,
            // so we need to look only at the undo edits relevant for us.
            // Our edits have an identifier set so that's how we can distinguish them
            const undoEdits = _undoEdits.filter(edit => !!edit.identifier);
            for (let idx = 0; idx < snippets.length; idx++) {
                snippets[idx].initialize(undoEdits[idx].textChange);
            }
            if (this._snippets[0].hasPlaceholder) {
                return this._move(true);
            }
            else {
                return undoEdits
                    .map(edit => Selection.fromPositions(edit.range.getEndPosition()));
            }
        });
        this._editor.revealRange(this._editor.getSelections()[0]);
    }
    merge(template, options = _defaultOptions) {
        if (!this._editor.hasModel()) {
            return;
        }
        this._templateMerges.push([this._snippets[0]._nestingLevel, this._snippets[0]._placeholderGroupsIdx, template]);
        const { edits, snippets } = SnippetSession.createEditsAndSnippetsFromSelections(this._editor, template, options.overwriteBefore, options.overwriteAfter, true, options.adjustWhitespace, options.clipboardText, options.overtypingCapturer, this._languageConfigurationService);
        this._editor.executeEdits('snippet', edits, _undoEdits => {
            // Sometimes, the text buffer will remove automatic whitespace when doing any edits,
            // so we need to look only at the undo edits relevant for us.
            // Our edits have an identifier set so that's how we can distinguish them
            const undoEdits = _undoEdits.filter(edit => !!edit.identifier);
            for (let idx = 0; idx < snippets.length; idx++) {
                snippets[idx].initialize(undoEdits[idx].textChange);
            }
            // Trivial snippets have no placeholder or are just the final placeholder. That means they
            // are just text insertions and we don't need to merge the nested snippet into the existing
            // snippet
            const isTrivialSnippet = snippets[0].isTrivialSnippet;
            if (!isTrivialSnippet) {
                for (const snippet of this._snippets) {
                    snippet.merge(snippets);
                }
                console.assert(snippets.length === 0);
            }
            if (this._snippets[0].hasPlaceholder && !isTrivialSnippet) {
                return this._move(undefined);
            }
            else {
                return undoEdits.map(edit => Selection.fromPositions(edit.range.getEndPosition()));
            }
        });
    }
    next() {
        const newSelections = this._move(true);
        this._editor.setSelections(newSelections);
        this._editor.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition());
    }
    prev() {
        const newSelections = this._move(false);
        this._editor.setSelections(newSelections);
        this._editor.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition());
    }
    _move(fwd) {
        const selections = [];
        for (const snippet of this._snippets) {
            const oneSelection = snippet.move(fwd);
            selections.push(...oneSelection);
        }
        return selections;
    }
    get isAtFirstPlaceholder() {
        return this._snippets[0].isAtFirstPlaceholder;
    }
    get isAtLastPlaceholder() {
        return this._snippets[0].isAtLastPlaceholder;
    }
    get hasPlaceholder() {
        return this._snippets[0].hasPlaceholder;
    }
    get hasChoice() {
        return this._snippets[0].hasChoice;
    }
    get activeChoice() {
        return this._snippets[0].activeChoice;
    }
    isSelectionWithinPlaceholders() {
        if (!this.hasPlaceholder) {
            return false;
        }
        const selections = this._editor.getSelections();
        if (selections.length < this._snippets.length) {
            // this means we started snippet mode with N
            // selections and have M (N > M) selections.
            // So one snippet is without selection -> cancel
            return false;
        }
        const allPossibleSelections = new Map();
        for (const snippet of this._snippets) {
            const possibleSelections = snippet.computePossibleSelections();
            // for the first snippet find the placeholder (and its ranges)
            // that contain at least one selection. for all remaining snippets
            // the same placeholder (and their ranges) must be used.
            if (allPossibleSelections.size === 0) {
                for (const [index, ranges] of possibleSelections) {
                    ranges.sort(Range.compareRangesUsingStarts);
                    for (const selection of selections) {
                        if (ranges[0].containsRange(selection)) {
                            allPossibleSelections.set(index, []);
                            break;
                        }
                    }
                }
            }
            if (allPossibleSelections.size === 0) {
                // return false if we couldn't associate a selection to
                // this (the first) snippet
                return false;
            }
            // add selections from 'this' snippet so that we know all
            // selections for this placeholder
            allPossibleSelections.forEach((array, index) => {
                array.push(...possibleSelections.get(index));
            });
        }
        // sort selections (and later placeholder-ranges). then walk both
        // arrays and make sure the placeholder-ranges contain the corresponding
        // selection
        selections.sort(Range.compareRangesUsingStarts);
        for (const [index, ranges] of allPossibleSelections) {
            if (ranges.length !== selections.length) {
                allPossibleSelections.delete(index);
                continue;
            }
            ranges.sort(Range.compareRangesUsingStarts);
            for (let i = 0; i < ranges.length; i++) {
                if (!ranges[i].containsRange(selections[i])) {
                    allPossibleSelections.delete(index);
                    continue;
                }
            }
        }
        // from all possible selections we have deleted those
        // that don't match with the current selection. if we don't
        // have any left, we don't have a selection anymore
        return allPossibleSelections.size > 0;
    }
};
SnippetSession = snippetSession_decorate([
    snippetSession_param(3, ILanguageConfigurationService)
], SnippetSession);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/snippet/browser/snippetController2.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var snippetController2_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var snippetController2_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};













const snippetController2_defaultOptions = {
    overwriteBefore: 0,
    overwriteAfter: 0,
    undoStopBefore: true,
    undoStopAfter: true,
    adjustWhitespace: true,
    clipboardText: undefined,
    overtypingCapturer: undefined
};
let SnippetController2 = class SnippetController2 {
    constructor(_editor, _logService, _languageFeaturesService, contextKeyService, _languageConfigurationService) {
        this._editor = _editor;
        this._logService = _logService;
        this._languageFeaturesService = _languageFeaturesService;
        this._languageConfigurationService = _languageConfigurationService;
        this._snippetListener = new DisposableStore();
        this._modelVersionId = -1;
        this._inSnippet = SnippetController2.InSnippetMode.bindTo(contextKeyService);
        this._hasNextTabstop = SnippetController2.HasNextTabstop.bindTo(contextKeyService);
        this._hasPrevTabstop = SnippetController2.HasPrevTabstop.bindTo(contextKeyService);
    }
    static get(editor) {
        return editor.getContribution(SnippetController2.ID);
    }
    dispose() {
        var _a;
        this._inSnippet.reset();
        this._hasPrevTabstop.reset();
        this._hasNextTabstop.reset();
        (_a = this._session) === null || _a === void 0 ? void 0 : _a.dispose();
        this._snippetListener.dispose();
    }
    apply(edits, opts) {
        try {
            this._doInsert(edits, typeof opts === 'undefined' ? snippetController2_defaultOptions : Object.assign(Object.assign({}, snippetController2_defaultOptions), opts));
        }
        catch (e) {
            this.cancel();
            this._logService.error(e);
            this._logService.error('snippet_error');
            this._logService.error('insert_edits=', edits);
            this._logService.error('existing_template=', this._session ? this._session._logInfo() : '<no_session>');
        }
    }
    insert(template, opts) {
        // this is here to find out more about the yet-not-understood
        // error that sometimes happens when we fail to inserted a nested
        // snippet
        try {
            this._doInsert(template, typeof opts === 'undefined' ? snippetController2_defaultOptions : Object.assign(Object.assign({}, snippetController2_defaultOptions), opts));
        }
        catch (e) {
            this.cancel();
            this._logService.error(e);
            this._logService.error('snippet_error');
            this._logService.error('insert_template=', template);
            this._logService.error('existing_template=', this._session ? this._session._logInfo() : '<no_session>');
        }
    }
    _doInsert(template, opts) {
        var _a;
        if (!this._editor.hasModel()) {
            return;
        }
        // don't listen while inserting the snippet
        // as that is the inflight state causing cancelation
        this._snippetListener.clear();
        if (opts.undoStopBefore) {
            this._editor.getModel().pushStackElement();
        }
        // don't merge
        if (this._session && typeof template !== 'string') {
            this.cancel();
        }
        if (!this._session) {
            this._modelVersionId = this._editor.getModel().getAlternativeVersionId();
            this._session = new SnippetSession(this._editor, template, opts, this._languageConfigurationService);
            this._session.insert();
        }
        else {
            assertType(typeof template === 'string');
            this._session.merge(template, opts);
        }
        if (opts.undoStopAfter) {
            this._editor.getModel().pushStackElement();
        }
        // regster completion item provider when there is any choice element
        if ((_a = this._session) === null || _a === void 0 ? void 0 : _a.hasChoice) {
            this._choiceCompletionItemProvider = {
                provideCompletionItems: (model, position) => {
                    if (!this._session || model !== this._editor.getModel() || !Position.equals(this._editor.getPosition(), position)) {
                        return undefined;
                    }
                    const { activeChoice } = this._session;
                    if (!activeChoice || activeChoice.choice.options.length === 0) {
                        return undefined;
                    }
                    const word = model.getValueInRange(activeChoice.range);
                    const isAnyOfOptions = Boolean(activeChoice.choice.options.find(o => o.value === word));
                    const suggestions = [];
                    for (let i = 0; i < activeChoice.choice.options.length; i++) {
                        const option = activeChoice.choice.options[i];
                        suggestions.push({
                            kind: 13 /* CompletionItemKind.Value */,
                            label: option.value,
                            insertText: option.value,
                            sortText: 'a'.repeat(i + 1),
                            range: activeChoice.range,
                            filterText: isAnyOfOptions ? `${word}_${option.value}` : undefined,
                            command: { id: 'jumpToNextSnippetPlaceholder', title: localize('next', 'Go to next placeholder...') }
                        });
                    }
                    return { suggestions };
                }
            };
            const registration = this._languageFeaturesService.completionProvider.register({
                language: this._editor.getModel().getLanguageId(),
                pattern: this._editor.getModel().uri.fsPath,
                scheme: this._editor.getModel().uri.scheme
            }, this._choiceCompletionItemProvider);
            this._snippetListener.add(registration);
        }
        this._updateState();
        this._snippetListener.add(this._editor.onDidChangeModelContent(e => e.isFlush && this.cancel()));
        this._snippetListener.add(this._editor.onDidChangeModel(() => this.cancel()));
        this._snippetListener.add(this._editor.onDidChangeCursorSelection(() => this._updateState()));
    }
    _updateState() {
        if (!this._session || !this._editor.hasModel()) {
            // canceled in the meanwhile
            return;
        }
        if (this._modelVersionId === this._editor.getModel().getAlternativeVersionId()) {
            // undo until the 'before' state happened
            // and makes use cancel snippet mode
            return this.cancel();
        }
        if (!this._session.hasPlaceholder) {
            // don't listen for selection changes and don't
            // update context keys when the snippet is plain text
            return this.cancel();
        }
        if (this._session.isAtLastPlaceholder || !this._session.isSelectionWithinPlaceholders()) {
            this._editor.getModel().pushStackElement();
            return this.cancel();
        }
        this._inSnippet.set(true);
        this._hasPrevTabstop.set(!this._session.isAtFirstPlaceholder);
        this._hasNextTabstop.set(!this._session.isAtLastPlaceholder);
        this._handleChoice();
    }
    _handleChoice() {
        if (!this._session || !this._editor.hasModel()) {
            this._currentChoice = undefined;
            return;
        }
        const { activeChoice } = this._session;
        if (!activeChoice || !this._choiceCompletionItemProvider) {
            this._currentChoice = undefined;
            return;
        }
        if (this._currentChoice !== activeChoice.choice) {
            this._currentChoice = activeChoice.choice;
            // trigger suggest with the special choice completion provider
            queueMicrotask(() => {
                showSimpleSuggestions(this._editor, this._choiceCompletionItemProvider);
            });
        }
    }
    finish() {
        while (this._inSnippet.get()) {
            this.next();
        }
    }
    cancel(resetSelection = false) {
        var _a;
        this._inSnippet.reset();
        this._hasPrevTabstop.reset();
        this._hasNextTabstop.reset();
        this._snippetListener.clear();
        this._currentChoice = undefined;
        (_a = this._session) === null || _a === void 0 ? void 0 : _a.dispose();
        this._session = undefined;
        this._modelVersionId = -1;
        if (resetSelection) {
            // reset selection to the primary cursor when being asked
            // for. this happens when explicitly cancelling snippet mode,
            // e.g. when pressing ESC
            this._editor.setSelections([this._editor.getSelection()]);
        }
    }
    prev() {
        if (this._session) {
            this._session.prev();
        }
        this._updateState();
    }
    next() {
        if (this._session) {
            this._session.next();
        }
        this._updateState();
    }
    isInSnippet() {
        return Boolean(this._inSnippet.get());
    }
};
SnippetController2.ID = 'snippetController2';
SnippetController2.InSnippetMode = new RawContextKey('inSnippetMode', false, localize('inSnippetMode', "Whether the editor in current in snippet mode"));
SnippetController2.HasNextTabstop = new RawContextKey('hasNextTabstop', false, localize('hasNextTabstop', "Whether there is a next tab stop when in snippet mode"));
SnippetController2.HasPrevTabstop = new RawContextKey('hasPrevTabstop', false, localize('hasPrevTabstop', "Whether there is a previous tab stop when in snippet mode"));
SnippetController2 = snippetController2_decorate([
    snippetController2_param(1, ILogService),
    snippetController2_param(2, ILanguageFeaturesService),
    snippetController2_param(3, IContextKeyService),
    snippetController2_param(4, ILanguageConfigurationService)
], SnippetController2);

registerEditorContribution(SnippetController2.ID, SnippetController2);
const CommandCtor = EditorCommand.bindToContribution(SnippetController2.get);
registerEditorCommand(new CommandCtor({
    id: 'jumpToNextSnippetPlaceholder',
    precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasNextTabstop),
    handler: ctrl => ctrl.next(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 30,
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2 /* KeyCode.Tab */
    }
}));
registerEditorCommand(new CommandCtor({
    id: 'jumpToPrevSnippetPlaceholder',
    precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasPrevTabstop),
    handler: ctrl => ctrl.prev(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 30,
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */
    }
}));
registerEditorCommand(new CommandCtor({
    id: 'leaveSnippet',
    precondition: SnippetController2.InSnippetMode,
    handler: ctrl => ctrl.cancel(true),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 30,
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 9 /* KeyCode.Escape */,
        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
    }
}));
registerEditorCommand(new CommandCtor({
    id: 'acceptSnippet',
    precondition: SnippetController2.InSnippetMode,
    handler: ctrl => ctrl.finish(),
    // kbOpts: {
    // 	weight: KeybindingWeight.EditorContrib + 30,
    // 	kbExpr: EditorContextKeys.textFocus,
    // 	primary: KeyCode.Enter,
    // }
}));
// ---
function performSnippetEdit(editor, snippet, selections) {
    const controller = SnippetController2.get(editor);
    if (!controller) {
        return false;
    }
    editor.focus();
    controller.apply(selections.map(selection => {
        return {
            range: Selection.liftSelection(selection),
            template: snippet
        };
    }));
    return controller.isInSnippet();
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/copyPaste/browser/copyPasteController.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var copyPasteController_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var copyPasteController_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var copyPasteController_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
















const vscodeClipboardMime = 'application/vnd.code.copyMetadata';
let CopyPasteController = class CopyPasteController extends Disposable {
    constructor(editor, _bulkEditService, _clipboardService, _configurationService, _languageFeaturesService) {
        super();
        this._bulkEditService = _bulkEditService;
        this._clipboardService = _clipboardService;
        this._configurationService = _configurationService;
        this._languageFeaturesService = _languageFeaturesService;
        this._editor = editor;
        const container = editor.getContainerDomNode();
        this._register(addDisposableListener(container, 'copy', e => this.handleCopy(e)));
        this._register(addDisposableListener(container, 'cut', e => this.handleCopy(e)));
        this._register(addDisposableListener(container, 'paste', e => this.handlePaste(e), true));
    }
    arePasteActionsEnabled(model) {
        return this._configurationService.getValue('editor.experimental.pasteActions.enabled', {
            resource: model.uri
        });
    }
    handleCopy(e) {
        var _a;
        if (!e.clipboardData || !this._editor.hasTextFocus()) {
            return;
        }
        const model = this._editor.getModel();
        const selections = this._editor.getSelections();
        if (!model || !(selections === null || selections === void 0 ? void 0 : selections.length)) {
            return;
        }
        if (!this.arePasteActionsEnabled(model)) {
            return;
        }
        const ranges = [...selections];
        const primarySelection = selections[0];
        const wasFromEmptySelection = primarySelection.isEmpty();
        if (wasFromEmptySelection) {
            if (!this._editor.getOption(33 /* EditorOption.emptySelectionClipboard */)) {
                return;
            }
            ranges[0] = new Range(primarySelection.startLineNumber, 0, primarySelection.startLineNumber, model.getLineLength(primarySelection.startLineNumber));
        }
        const providers = this._languageFeaturesService.documentPasteEditProvider.ordered(model).filter(x => !!x.prepareDocumentPaste);
        if (!providers.length) {
            this.setCopyMetadata(e.clipboardData, { wasFromEmptySelection });
            return;
        }
        const dataTransfer = toVSDataTransfer(e.clipboardData);
        // Save off a handle pointing to data that VS Code maintains.
        const handle = generateUuid();
        this.setCopyMetadata(e.clipboardData, {
            id: handle,
            wasFromEmptySelection,
        });
        const promise = createCancelablePromise((token) => copyPasteController_awaiter(this, void 0, void 0, function* () {
            const results = yield Promise.all(providers.map(provider => {
                return provider.prepareDocumentPaste(model, ranges, dataTransfer, token);
            }));
            for (const result of results) {
                result === null || result === void 0 ? void 0 : result.forEach((value, key) => {
                    dataTransfer.replace(key, value);
                });
            }
            return dataTransfer;
        }));
        (_a = this._currentClipboardItem) === null || _a === void 0 ? void 0 : _a.dataTransferPromise.cancel();
        this._currentClipboardItem = { handle: handle, dataTransferPromise: promise };
    }
    setCopyMetadata(dataTransfer, metadata) {
        dataTransfer.setData(vscodeClipboardMime, JSON.stringify(metadata));
    }
    handlePaste(e) {
        var _a, _b, _c;
        return copyPasteController_awaiter(this, void 0, void 0, function* () {
            if (!e.clipboardData || !this._editor.hasTextFocus()) {
                return;
            }
            const selections = this._editor.getSelections();
            if (!(selections === null || selections === void 0 ? void 0 : selections.length) || !this._editor.hasModel()) {
                return;
            }
            const model = this._editor.getModel();
            if (!this.arePasteActionsEnabled(model)) {
                return;
            }
            let metadata;
            const rawMetadata = (_a = e.clipboardData) === null || _a === void 0 ? void 0 : _a.getData(vscodeClipboardMime);
            if (rawMetadata && typeof rawMetadata === 'string') {
                metadata = JSON.parse(rawMetadata);
            }
            const providers = this._languageFeaturesService.documentPasteEditProvider.ordered(model);
            if (!providers.length) {
                return;
            }
            e.preventDefault();
            e.stopImmediatePropagation();
            const originalDocVersion = model.getVersionId();
            const tokenSource = new EditorStateCancellationTokenSource(this._editor, 1 /* CodeEditorStateFlag.Value */ | 2 /* CodeEditorStateFlag.Selection */);
            try {
                const dataTransfer = toVSDataTransfer(e.clipboardData);
                if ((metadata === null || metadata === void 0 ? void 0 : metadata.id) && ((_b = this._currentClipboardItem) === null || _b === void 0 ? void 0 : _b.handle) === metadata.id) {
                    const toMergeDataTransfer = yield this._currentClipboardItem.dataTransferPromise;
                    toMergeDataTransfer.forEach((value, key) => {
                        dataTransfer.replace(key, value);
                    });
                }
                if (!dataTransfer.has(Mimes.uriList)) {
                    const resources = yield this._clipboardService.readResources();
                    if (resources.length) {
                        dataTransfer.append(Mimes.uriList, createStringDataTransferItem(UriList.create(resources)));
                    }
                }
                dataTransfer.delete(vscodeClipboardMime);
                for (const provider of providers) {
                    if (!provider.pasteMimeTypes.some(type => {
                        if (type.toLowerCase() === DataTransfers.FILES.toLowerCase()) {
                            return [...dataTransfer.values()].some(item => item.asFile());
                        }
                        return dataTransfer.has(type);
                    })) {
                        continue;
                    }
                    const edit = yield provider.provideDocumentPasteEdits(model, selections, dataTransfer, tokenSource.token);
                    if (originalDocVersion !== model.getVersionId()) {
                        return;
                    }
                    if (edit) {
                        performSnippetEdit(this._editor, typeof edit.insertText === 'string' ? SnippetParser.escape(edit.insertText) : edit.insertText.snippet, selections);
                        if (edit.additionalEdit) {
                            yield this._bulkEditService.apply(ResourceEdit.convert(edit.additionalEdit), { editor: this._editor });
                        }
                        return;
                    }
                }
                // Default handler
                const textDataTransfer = (_c = dataTransfer.get(Mimes.text)) !== null && _c !== void 0 ? _c : dataTransfer.get('text');
                if (!textDataTransfer) {
                    return;
                }
                const text = yield textDataTransfer.asString();
                if (originalDocVersion !== model.getVersionId()) {
                    return;
                }
                this._editor.trigger('keyboard', "paste" /* Handler.Paste */, {
                    text: text,
                    pasteOnNewLine: metadata === null || metadata === void 0 ? void 0 : metadata.wasFromEmptySelection,
                    multicursorText: null
                });
            }
            finally {
                tokenSource.dispose();
            }
        });
    }
};
CopyPasteController.ID = 'editor.contrib.copyPasteActionController';
CopyPasteController = copyPasteController_decorate([
    copyPasteController_param(1, IBulkEditService),
    copyPasteController_param(2, IClipboardService),
    copyPasteController_param(3, IConfigurationService),
    copyPasteController_param(4, ILanguageFeaturesService)
], CopyPasteController);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/copyPaste/browser/copyPasteContribution.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






registerEditorContribution(CopyPasteController.ID, CopyPasteController);
Registry.as(configurationRegistry_Extensions.Configuration).registerConfiguration(Object.assign(Object.assign({}, editorConfigurationBaseNode), { properties: {
        'editor.experimental.pasteActions.enabled': {
            type: 'boolean',
            scope: 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */,
            description: localize('pasteActions', "Enable/disable running edits from extensions on paste."),
            default: false,
        },
    } }));

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/cursorUndo/browser/cursorUndo.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class cursorUndo_CursorState {
    constructor(selections) {
        this.selections = selections;
    }
    equals(other) {
        const thisLen = this.selections.length;
        const otherLen = other.selections.length;
        if (thisLen !== otherLen) {
            return false;
        }
        for (let i = 0; i < thisLen; i++) {
            if (!this.selections[i].equalsSelection(other.selections[i])) {
                return false;
            }
        }
        return true;
    }
}
class StackElement {
    constructor(cursorState, scrollTop, scrollLeft) {
        this.cursorState = cursorState;
        this.scrollTop = scrollTop;
        this.scrollLeft = scrollLeft;
    }
}
class CursorUndoRedoController extends Disposable {
    constructor(editor) {
        super();
        this._editor = editor;
        this._isCursorUndoRedo = false;
        this._undoStack = [];
        this._redoStack = [];
        this._register(editor.onDidChangeModel((e) => {
            this._undoStack = [];
            this._redoStack = [];
        }));
        this._register(editor.onDidChangeModelContent((e) => {
            this._undoStack = [];
            this._redoStack = [];
        }));
        this._register(editor.onDidChangeCursorSelection((e) => {
            if (this._isCursorUndoRedo) {
                return;
            }
            if (!e.oldSelections) {
                return;
            }
            if (e.oldModelVersionId !== e.modelVersionId) {
                return;
            }
            const prevState = new cursorUndo_CursorState(e.oldSelections);
            const isEqualToLastUndoStack = (this._undoStack.length > 0 && this._undoStack[this._undoStack.length - 1].cursorState.equals(prevState));
            if (!isEqualToLastUndoStack) {
                this._undoStack.push(new StackElement(prevState, editor.getScrollTop(), editor.getScrollLeft()));
                this._redoStack = [];
                if (this._undoStack.length > 50) {
                    // keep the cursor undo stack bounded
                    this._undoStack.shift();
                }
            }
        }));
    }
    static get(editor) {
        return editor.getContribution(CursorUndoRedoController.ID);
    }
    cursorUndo() {
        if (!this._editor.hasModel() || this._undoStack.length === 0) {
            return;
        }
        this._redoStack.push(new StackElement(new cursorUndo_CursorState(this._editor.getSelections()), this._editor.getScrollTop(), this._editor.getScrollLeft()));
        this._applyState(this._undoStack.pop());
    }
    cursorRedo() {
        if (!this._editor.hasModel() || this._redoStack.length === 0) {
            return;
        }
        this._undoStack.push(new StackElement(new cursorUndo_CursorState(this._editor.getSelections()), this._editor.getScrollTop(), this._editor.getScrollLeft()));
        this._applyState(this._redoStack.pop());
    }
    _applyState(stackElement) {
        this._isCursorUndoRedo = true;
        this._editor.setSelections(stackElement.cursorState.selections);
        this._editor.setScrollPosition({
            scrollTop: stackElement.scrollTop,
            scrollLeft: stackElement.scrollLeft
        });
        this._isCursorUndoRedo = false;
    }
}
CursorUndoRedoController.ID = 'editor.contrib.cursorUndoRedoController';
class CursorUndo extends EditorAction {
    constructor() {
        super({
            id: 'cursorUndo',
            label: localize('cursor.undo', "Cursor Undo"),
            alias: 'Cursor Undo',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 51 /* KeyCode.KeyU */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor, args) {
        var _a;
        (_a = CursorUndoRedoController.get(editor)) === null || _a === void 0 ? void 0 : _a.cursorUndo();
    }
}
class CursorRedo extends EditorAction {
    constructor() {
        super({
            id: 'cursorRedo',
            label: localize('cursor.redo', "Cursor Redo"),
            alias: 'Cursor Redo',
            precondition: undefined
        });
    }
    run(accessor, editor, args) {
        var _a;
        (_a = CursorUndoRedoController.get(editor)) === null || _a === void 0 ? void 0 : _a.cursorRedo();
    }
}
registerEditorContribution(CursorUndoRedoController.ID, CursorUndoRedoController);
registerEditorAction(CursorUndo);
registerEditorAction(CursorRedo);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/dnd/browser/dnd.css
var dnd = __webpack_require__(33994);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/dnd/browser/dnd.css

      
      
      
      
      
      
      
      
      

var dnd_options = {};

dnd_options.styleTagTransform = (styleTagTransform_default());
dnd_options.setAttributes = (setAttributesWithoutAttributes_default());

      dnd_options.insert = insertBySelector_default().bind(null, "head");
    
dnd_options.domAPI = (styleDomAPI_default());
dnd_options.insertStyleElement = (insertStyleElement_default());

var dnd_update = injectStylesIntoStyleTag_default()(dnd/* default */.A, dnd_options);




       /* harmony default export */ const browser_dnd = (dnd/* default */.A && dnd/* default */.A.locals ? dnd/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/dnd/browser/dragAndDropCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class DragAndDropCommand {
    constructor(selection, targetPosition, copy) {
        this.selection = selection;
        this.targetPosition = targetPosition;
        this.copy = copy;
        this.targetSelection = null;
    }
    getEditOperations(model, builder) {
        const text = model.getValueInRange(this.selection);
        if (!this.copy) {
            builder.addEditOperation(this.selection, null);
        }
        builder.addEditOperation(new Range(this.targetPosition.lineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.targetPosition.column), text);
        if (this.selection.containsPosition(this.targetPosition) && !(this.copy && (this.selection.getEndPosition().equals(this.targetPosition) || this.selection.getStartPosition().equals(this.targetPosition)) // we allow users to paste content beside the selection
        )) {
            this.targetSelection = this.selection;
            return;
        }
        if (this.copy) {
            this.targetSelection = new Selection(this.targetPosition.lineNumber, this.targetPosition.column, this.selection.endLineNumber - this.selection.startLineNumber + this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
                this.targetPosition.column + this.selection.endColumn - this.selection.startColumn :
                this.selection.endColumn);
            return;
        }
        if (this.targetPosition.lineNumber > this.selection.endLineNumber) {
            // Drag the selection downwards
            this.targetSelection = new Selection(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
                this.targetPosition.column + this.selection.endColumn - this.selection.startColumn :
                this.selection.endColumn);
            return;
        }
        if (this.targetPosition.lineNumber < this.selection.endLineNumber) {
            // Drag the selection upwards
            this.targetSelection = new Selection(this.targetPosition.lineNumber, this.targetPosition.column, this.targetPosition.lineNumber + this.selection.endLineNumber - this.selection.startLineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
                this.targetPosition.column + this.selection.endColumn - this.selection.startColumn :
                this.selection.endColumn);
            return;
        }
        // The target position is at the same line as the selection's end position.
        if (this.selection.endColumn <= this.targetPosition.column) {
            // The target position is after the selection's end position
            this.targetSelection = new Selection(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
                this.targetPosition.column - this.selection.endColumn + this.selection.startColumn :
                this.targetPosition.column - this.selection.endColumn + this.selection.startColumn, this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ?
                this.targetPosition.column :
                this.selection.endColumn);
        }
        else {
            // The target position is before the selection's end position. Since the selection doesn't contain the target position, the selection is one-line and target position is before this selection.
            this.targetSelection = new Selection(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.targetPosition.column + this.selection.endColumn - this.selection.startColumn);
        }
    }
    computeCursorState(model, helper) {
        return this.targetSelection;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/dnd/browser/dnd.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









function hasTriggerModifier(e) {
    if (isMacintosh) {
        return e.altKey;
    }
    else {
        return e.ctrlKey;
    }
}
class DragAndDropController extends Disposable {
    constructor(editor) {
        super();
        this._editor = editor;
        this._dndDecorationIds = this._editor.createDecorationsCollection();
        this._register(this._editor.onMouseDown((e) => this._onEditorMouseDown(e)));
        this._register(this._editor.onMouseUp((e) => this._onEditorMouseUp(e)));
        this._register(this._editor.onMouseDrag((e) => this._onEditorMouseDrag(e)));
        this._register(this._editor.onMouseDrop((e) => this._onEditorMouseDrop(e)));
        this._register(this._editor.onMouseDropCanceled(() => this._onEditorMouseDropCanceled()));
        this._register(this._editor.onKeyDown((e) => this.onEditorKeyDown(e)));
        this._register(this._editor.onKeyUp((e) => this.onEditorKeyUp(e)));
        this._register(this._editor.onDidBlurEditorWidget(() => this.onEditorBlur()));
        this._register(this._editor.onDidBlurEditorText(() => this.onEditorBlur()));
        this._mouseDown = false;
        this._modifierPressed = false;
        this._dragSelection = null;
    }
    onEditorBlur() {
        this._removeDecoration();
        this._dragSelection = null;
        this._mouseDown = false;
        this._modifierPressed = false;
    }
    onEditorKeyDown(e) {
        if (!this._editor.getOption(31 /* EditorOption.dragAndDrop */) || this._editor.getOption(18 /* EditorOption.columnSelection */)) {
            return;
        }
        if (hasTriggerModifier(e)) {
            this._modifierPressed = true;
        }
        if (this._mouseDown && hasTriggerModifier(e)) {
            this._editor.updateOptions({
                mouseStyle: 'copy'
            });
        }
    }
    onEditorKeyUp(e) {
        if (!this._editor.getOption(31 /* EditorOption.dragAndDrop */) || this._editor.getOption(18 /* EditorOption.columnSelection */)) {
            return;
        }
        if (hasTriggerModifier(e)) {
            this._modifierPressed = false;
        }
        if (this._mouseDown && e.keyCode === DragAndDropController.TRIGGER_KEY_VALUE) {
            this._editor.updateOptions({
                mouseStyle: 'default'
            });
        }
    }
    _onEditorMouseDown(mouseEvent) {
        this._mouseDown = true;
    }
    _onEditorMouseUp(mouseEvent) {
        this._mouseDown = false;
        // Whenever users release the mouse, the drag and drop operation should finish and the cursor should revert to text.
        this._editor.updateOptions({
            mouseStyle: 'text'
        });
    }
    _onEditorMouseDrag(mouseEvent) {
        const target = mouseEvent.target;
        if (this._dragSelection === null) {
            const selections = this._editor.getSelections() || [];
            const possibleSelections = selections.filter(selection => target.position && selection.containsPosition(target.position));
            if (possibleSelections.length === 1) {
                this._dragSelection = possibleSelections[0];
            }
            else {
                return;
            }
        }
        if (hasTriggerModifier(mouseEvent.event)) {
            this._editor.updateOptions({
                mouseStyle: 'copy'
            });
        }
        else {
            this._editor.updateOptions({
                mouseStyle: 'default'
            });
        }
        if (target.position) {
            if (this._dragSelection.containsPosition(target.position)) {
                this._removeDecoration();
            }
            else {
                this.showAt(target.position);
            }
        }
    }
    _onEditorMouseDropCanceled() {
        this._editor.updateOptions({
            mouseStyle: 'text'
        });
        this._removeDecoration();
        this._dragSelection = null;
        this._mouseDown = false;
    }
    _onEditorMouseDrop(mouseEvent) {
        if (mouseEvent.target && (this._hitContent(mouseEvent.target) || this._hitMargin(mouseEvent.target)) && mouseEvent.target.position) {
            const newCursorPosition = new Position(mouseEvent.target.position.lineNumber, mouseEvent.target.position.column);
            if (this._dragSelection === null) {
                let newSelections = null;
                if (mouseEvent.event.shiftKey) {
                    const primarySelection = this._editor.getSelection();
                    if (primarySelection) {
                        const { selectionStartLineNumber, selectionStartColumn } = primarySelection;
                        newSelections = [new Selection(selectionStartLineNumber, selectionStartColumn, newCursorPosition.lineNumber, newCursorPosition.column)];
                    }
                }
                else {
                    newSelections = (this._editor.getSelections() || []).map(selection => {
                        if (selection.containsPosition(newCursorPosition)) {
                            return new Selection(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
                        }
                        else {
                            return selection;
                        }
                    });
                }
                // Use `mouse` as the source instead of `api` and setting the reason to explicit (to behave like any other mouse operation).
                this._editor.setSelections(newSelections || [], 'mouse', 3 /* CursorChangeReason.Explicit */);
            }
            else if (!this._dragSelection.containsPosition(newCursorPosition) ||
                ((hasTriggerModifier(mouseEvent.event) ||
                    this._modifierPressed) && (this._dragSelection.getEndPosition().equals(newCursorPosition) || this._dragSelection.getStartPosition().equals(newCursorPosition)) // we allow users to paste content beside the selection
                )) {
                this._editor.pushUndoStop();
                this._editor.executeCommand(DragAndDropController.ID, new DragAndDropCommand(this._dragSelection, newCursorPosition, hasTriggerModifier(mouseEvent.event) || this._modifierPressed));
                this._editor.pushUndoStop();
            }
        }
        this._editor.updateOptions({
            mouseStyle: 'text'
        });
        this._removeDecoration();
        this._dragSelection = null;
        this._mouseDown = false;
    }
    showAt(position) {
        this._dndDecorationIds.set([{
                range: new Range(position.lineNumber, position.column, position.lineNumber, position.column),
                options: DragAndDropController._DECORATION_OPTIONS
            }]);
        this._editor.revealPosition(position, 1 /* ScrollType.Immediate */);
    }
    _removeDecoration() {
        this._dndDecorationIds.clear();
    }
    _hitContent(target) {
        return target.type === 6 /* MouseTargetType.CONTENT_TEXT */ ||
            target.type === 7 /* MouseTargetType.CONTENT_EMPTY */;
    }
    _hitMargin(target) {
        return target.type === 2 /* MouseTargetType.GUTTER_GLYPH_MARGIN */ ||
            target.type === 3 /* MouseTargetType.GUTTER_LINE_NUMBERS */ ||
            target.type === 4 /* MouseTargetType.GUTTER_LINE_DECORATIONS */;
    }
    dispose() {
        this._removeDecoration();
        this._dragSelection = null;
        this._mouseDown = false;
        this._modifierPressed = false;
        super.dispose();
    }
}
DragAndDropController.ID = 'editor.contrib.dragAndDrop';
DragAndDropController.TRIGGER_KEY_VALUE = isMacintosh ? 6 /* KeyCode.Alt */ : 5 /* KeyCode.Ctrl */;
DragAndDropController._DECORATION_OPTIONS = ModelDecorationOptions.register({
    description: 'dnd-target',
    className: 'dnd-target'
});
registerEditorContribution(DragAndDropController.ID, DragAndDropController);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/documentSymbols/browser/outlineModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var outlineModel_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var outlineModel_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var outlineModel_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};













class TreeElement {
    remove() {
        var _a;
        (_a = this.parent) === null || _a === void 0 ? void 0 : _a.children.delete(this.id);
    }
    static findId(candidate, container) {
        // complex id-computation which contains the origin/extension,
        // the parent path, and some dedupe logic when names collide
        let candidateId;
        if (typeof candidate === 'string') {
            candidateId = `${container.id}/${candidate}`;
        }
        else {
            candidateId = `${container.id}/${candidate.name}`;
            if (container.children.get(candidateId) !== undefined) {
                candidateId = `${container.id}/${candidate.name}_${candidate.range.startLineNumber}_${candidate.range.startColumn}`;
            }
        }
        let id = candidateId;
        for (let i = 0; container.children.get(id) !== undefined; i++) {
            id = `${candidateId}_${i}`;
        }
        return id;
    }
    static empty(element) {
        return element.children.size === 0;
    }
}
class OutlineElement extends TreeElement {
    constructor(id, parent, symbol) {
        super();
        this.id = id;
        this.parent = parent;
        this.symbol = symbol;
        this.children = new Map();
    }
}
class OutlineGroup extends TreeElement {
    constructor(id, parent, label, order) {
        super();
        this.id = id;
        this.parent = parent;
        this.label = label;
        this.order = order;
        this.children = new Map();
    }
}
class OutlineModel extends TreeElement {
    constructor(uri) {
        super();
        this.uri = uri;
        this.id = 'root';
        this.parent = undefined;
        this._groups = new Map();
        this.children = new Map();
        this.id = 'root';
        this.parent = undefined;
    }
    static create(registry, textModel, token) {
        const cts = new CancellationTokenSource(token);
        const result = new OutlineModel(textModel.uri);
        const provider = registry.ordered(textModel);
        const promises = provider.map((provider, index) => {
            var _a;
            const id = TreeElement.findId(`provider_${index}`, result);
            const group = new OutlineGroup(id, result, (_a = provider.displayName) !== null && _a !== void 0 ? _a : 'Unknown Outline Provider', index);
            return Promise.resolve(provider.provideDocumentSymbols(textModel, cts.token)).then(result => {
                for (const info of result || []) {
                    OutlineModel._makeOutlineElement(info, group);
                }
                return group;
            }, err => {
                onUnexpectedExternalError(err);
                return group;
            }).then(group => {
                if (!TreeElement.empty(group)) {
                    result._groups.set(id, group);
                }
                else {
                    group.remove();
                }
            });
        });
        const listener = registry.onDidChange(() => {
            const newProvider = registry.ordered(textModel);
            if (!equals(newProvider, provider)) {
                cts.cancel();
            }
        });
        return Promise.all(promises).then(() => {
            if (cts.token.isCancellationRequested && !token.isCancellationRequested) {
                return OutlineModel.create(registry, textModel, token);
            }
            else {
                return result._compact();
            }
        }).finally(() => {
            listener.dispose();
        });
    }
    static _makeOutlineElement(info, container) {
        const id = TreeElement.findId(info, container);
        const res = new OutlineElement(id, container, info);
        if (info.children) {
            for (const childInfo of info.children) {
                OutlineModel._makeOutlineElement(childInfo, res);
            }
        }
        container.children.set(res.id, res);
    }
    _compact() {
        let count = 0;
        for (const [key, group] of this._groups) {
            if (group.children.size === 0) { // empty
                this._groups.delete(key);
            }
            else {
                count += 1;
            }
        }
        if (count !== 1) {
            //
            this.children = this._groups;
        }
        else {
            // adopt all elements of the first group
            const group = Iterable.first(this._groups.values());
            for (const [, child] of group.children) {
                child.parent = this;
                this.children.set(child.id, child);
            }
        }
        return this;
    }
    getTopLevelSymbols() {
        const roots = [];
        for (const child of this.children.values()) {
            if (child instanceof OutlineElement) {
                roots.push(child.symbol);
            }
            else {
                roots.push(...Iterable.map(child.children.values(), child => child.symbol));
            }
        }
        return roots.sort((a, b) => Range.compareRangesUsingStarts(a.range, b.range));
    }
    asListOfDocumentSymbols() {
        const roots = this.getTopLevelSymbols();
        const bucket = [];
        OutlineModel._flattenDocumentSymbols(bucket, roots, '');
        return bucket.sort((a, b) => Position.compare(Range.getStartPosition(a.range), Range.getStartPosition(b.range)) || Position.compare(Range.getEndPosition(b.range), Range.getEndPosition(a.range)));
    }
    static _flattenDocumentSymbols(bucket, entries, overrideContainerLabel) {
        for (const entry of entries) {
            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: undefined, // we flatten it...
            });
            // Recurse over children
            if (entry.children) {
                OutlineModel._flattenDocumentSymbols(bucket, entry.children, entry.name);
            }
        }
    }
}
const IOutlineModelService = createDecorator('IOutlineModelService');
let OutlineModelService = class OutlineModelService {
    constructor(_languageFeaturesService, debounces, modelService) {
        this._languageFeaturesService = _languageFeaturesService;
        this._disposables = new DisposableStore();
        this._cache = new LRUCache(10, 0.7);
        this._debounceInformation = debounces.for(_languageFeaturesService.documentSymbolProvider, 'DocumentSymbols', { min: 350 });
        // don't cache outline models longer than their text model
        this._disposables.add(modelService.onModelRemoved(textModel => {
            this._cache.delete(textModel.id);
        }));
    }
    dispose() {
        this._disposables.dispose();
    }
    getOrCreate(textModel, token) {
        return outlineModel_awaiter(this, void 0, void 0, function* () {
            const registry = this._languageFeaturesService.documentSymbolProvider;
            const provider = registry.ordered(textModel);
            let data = this._cache.get(textModel.id);
            if (!data || data.versionId !== textModel.getVersionId() || !equals(data.provider, provider)) {
                const source = new CancellationTokenSource();
                data = {
                    versionId: textModel.getVersionId(),
                    provider,
                    promiseCnt: 0,
                    source,
                    promise: OutlineModel.create(registry, textModel, source.token),
                    model: undefined,
                };
                this._cache.set(textModel.id, data);
                const now = Date.now();
                data.promise.then(outlineModel => {
                    data.model = outlineModel;
                    this._debounceInformation.update(textModel, Date.now() - now);
                }).catch(_err => {
                    this._cache.delete(textModel.id);
                });
            }
            if (data.model) {
                // resolved -> return data
                return data.model;
            }
            // increase usage counter
            data.promiseCnt += 1;
            const listener = token.onCancellationRequested(() => {
                // last -> cancel provider request, remove cached promise
                if (--data.promiseCnt === 0) {
                    data.source.cancel();
                    this._cache.delete(textModel.id);
                }
            });
            try {
                return yield data.promise;
            }
            finally {
                listener.dispose();
            }
        });
    }
};
OutlineModelService = outlineModel_decorate([
    outlineModel_param(0, ILanguageFeaturesService),
    outlineModel_param(1, ILanguageFeatureDebounceService),
    outlineModel_param(2, IModelService)
], OutlineModelService);

registerSingleton(IOutlineModelService, OutlineModelService, true);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/documentSymbols/browser/documentSymbols.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var documentSymbols_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};






CommandsRegistry.registerCommand('_executeDocumentSymbolProvider', function (accessor, ...args) {
    return documentSymbols_awaiter(this, void 0, void 0, function* () {
        const [resource] = args;
        assertType(URI.isUri(resource));
        const outlineService = accessor.get(IOutlineModelService);
        const modelService = accessor.get(ITextModelService);
        const reference = yield modelService.createModelReference(resource);
        try {
            return (yield outlineService.getOrCreate(reference.object.textEditorModel, CancellationToken.None)).getTopLevelSymbols();
        }
        finally {
            reference.dispose();
        }
    });
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/dropIntoEditor/browser/dropIntoEditorContribution.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var dropIntoEditorContribution_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var dropIntoEditorContribution_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var dropIntoEditorContribution_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};


















let DropIntoEditorController = class DropIntoEditorController extends Disposable {
    constructor(editor, _bulkEditService, _languageFeaturesService, _progressService, workspaceContextService) {
        super();
        this._bulkEditService = _bulkEditService;
        this._languageFeaturesService = _languageFeaturesService;
        this._progressService = _progressService;
        this._register(editor.onDropIntoEditor(e => this.onDropIntoEditor(editor, e.position, e.event)));
        this._languageFeaturesService.documentOnDropEditProvider.register('*', new DefaultOnDropProvider(workspaceContextService));
    }
    onDropIntoEditor(editor, position, dragEvent) {
        return dropIntoEditorContribution_awaiter(this, void 0, void 0, function* () {
            if (!dragEvent.dataTransfer || !editor.hasModel()) {
                return;
            }
            const model = editor.getModel();
            const initialModelVersion = model.getVersionId();
            const ourDataTransfer = yield this.extractDataTransferData(dragEvent);
            if (ourDataTransfer.size === 0) {
                return;
            }
            if (editor.getModel().getVersionId() !== initialModelVersion) {
                return;
            }
            const tokenSource = new EditorStateCancellationTokenSource(editor, 1 /* CodeEditorStateFlag.Value */);
            try {
                const providers = this._languageFeaturesService.documentOnDropEditProvider.ordered(model);
                const edit = yield this._progressService.withProgress({
                    location: 15 /* ProgressLocation.Notification */,
                    delay: 750,
                    title: localize('dropProgressTitle', "Running drop handlers..."),
                    cancellable: true,
                }, () => {
                    return raceCancellation((() => dropIntoEditorContribution_awaiter(this, void 0, void 0, function* () {
                        for (const provider of providers) {
                            const edit = yield provider.provideDocumentOnDropEdits(model, position, ourDataTransfer, tokenSource.token);
                            if (tokenSource.token.isCancellationRequested) {
                                return undefined;
                            }
                            if (edit) {
                                return edit;
                            }
                        }
                        return undefined;
                    }))(), tokenSource.token);
                }, () => {
                    tokenSource.cancel();
                });
                if (tokenSource.token.isCancellationRequested || editor.getModel().getVersionId() !== initialModelVersion) {
                    return;
                }
                if (edit) {
                    const range = new Range(position.lineNumber, position.column, position.lineNumber, position.column);
                    performSnippetEdit(editor, typeof edit.insertText === 'string' ? SnippetParser.escape(edit.insertText) : edit.insertText.snippet, [Selection.fromRange(range, 0 /* SelectionDirection.LTR */)]);
                    if (edit.additionalEdit) {
                        yield this._bulkEditService.apply(ResourceEdit.convert(edit.additionalEdit), { editor });
                    }
                    return;
                }
            }
            finally {
                tokenSource.dispose();
            }
        });
    }
    extractDataTransferData(dragEvent) {
        return dropIntoEditorContribution_awaiter(this, void 0, void 0, function* () {
            if (!dragEvent.dataTransfer) {
                return new VSDataTransfer();
            }
            const textEditorDataTransfer = toVSDataTransfer(dragEvent.dataTransfer);
            addExternalEditorsDropData(textEditorDataTransfer, dragEvent);
            return textEditorDataTransfer;
        });
    }
};
DropIntoEditorController.ID = 'editor.contrib.dropIntoEditorController';
DropIntoEditorController = dropIntoEditorContribution_decorate([
    dropIntoEditorContribution_param(1, IBulkEditService),
    dropIntoEditorContribution_param(2, ILanguageFeaturesService),
    dropIntoEditorContribution_param(3, IProgressService),
    dropIntoEditorContribution_param(4, IWorkspaceContextService)
], DropIntoEditorController);

let DefaultOnDropProvider = class DefaultOnDropProvider {
    constructor(_workspaceContextService) {
        this._workspaceContextService = _workspaceContextService;
    }
    provideDocumentOnDropEdits(_model, _position, dataTransfer, _token) {
        var _a;
        return dropIntoEditorContribution_awaiter(this, void 0, void 0, function* () {
            const urlListEntry = dataTransfer.get(Mimes.uriList);
            if (urlListEntry) {
                const urlList = yield urlListEntry.asString();
                const snippet = this.getUriListInsertText(urlList);
                if (snippet) {
                    return { insertText: snippet };
                }
            }
            const textEntry = (_a = dataTransfer.get('text')) !== null && _a !== void 0 ? _a : dataTransfer.get(Mimes.text);
            if (textEntry) {
                const text = yield textEntry.asString();
                return { insertText: text };
            }
            return undefined;
        });
    }
    getUriListInsertText(strUriList) {
        const uris = [];
        for (const resource of UriList.parse(strUriList)) {
            try {
                uris.push(URI.parse(resource));
            }
            catch (_a) {
                // noop
            }
        }
        if (!uris.length) {
            return;
        }
        return uris
            .map(uri => {
            const root = this._workspaceContextService.getWorkspaceFolder(uri);
            if (root) {
                const rel = relativePath(root.uri, uri);
                if (rel) {
                    return rel;
                }
            }
            return uri.fsPath;
        })
            .join(' ');
    }
};
DefaultOnDropProvider = dropIntoEditorContribution_decorate([
    dropIntoEditorContribution_param(0, IWorkspaceContextService)
], DefaultOnDropProvider);
registerEditorContribution(DropIntoEditorController.ID, DropIntoEditorController);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/find/browser/findDecorations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class FindDecorations {
    constructor(editor) {
        this._editor = editor;
        this._decorations = [];
        this._overviewRulerApproximateDecorations = [];
        this._findScopeDecorationIds = [];
        this._rangeHighlightDecorationId = null;
        this._highlightedDecorationId = null;
        this._startPosition = this._editor.getPosition();
    }
    dispose() {
        this._editor.removeDecorations(this._allDecorations());
        this._decorations = [];
        this._overviewRulerApproximateDecorations = [];
        this._findScopeDecorationIds = [];
        this._rangeHighlightDecorationId = null;
        this._highlightedDecorationId = null;
    }
    reset() {
        this._decorations = [];
        this._overviewRulerApproximateDecorations = [];
        this._findScopeDecorationIds = [];
        this._rangeHighlightDecorationId = null;
        this._highlightedDecorationId = null;
    }
    getCount() {
        return this._decorations.length;
    }
    /** @deprecated use getFindScopes to support multiple selections */
    getFindScope() {
        if (this._findScopeDecorationIds[0]) {
            return this._editor.getModel().getDecorationRange(this._findScopeDecorationIds[0]);
        }
        return null;
    }
    getFindScopes() {
        if (this._findScopeDecorationIds.length) {
            const scopes = this._findScopeDecorationIds.map(findScopeDecorationId => this._editor.getModel().getDecorationRange(findScopeDecorationId)).filter(element => !!element);
            if (scopes.length) {
                return scopes;
            }
        }
        return null;
    }
    getStartPosition() {
        return this._startPosition;
    }
    setStartPosition(newStartPosition) {
        this._startPosition = newStartPosition;
        this.setCurrentFindMatch(null);
    }
    _getDecorationIndex(decorationId) {
        const index = this._decorations.indexOf(decorationId);
        if (index >= 0) {
            return index + 1;
        }
        return 1;
    }
    getCurrentMatchesPosition(desiredRange) {
        const candidates = this._editor.getModel().getDecorationsInRange(desiredRange);
        for (const candidate of candidates) {
            const candidateOpts = candidate.options;
            if (candidateOpts === FindDecorations._FIND_MATCH_DECORATION || candidateOpts === FindDecorations._CURRENT_FIND_MATCH_DECORATION) {
                return this._getDecorationIndex(candidate.id);
            }
        }
        // We don't know the current match position, so returns zero to show '?' in find widget
        return 0;
    }
    setCurrentFindMatch(nextMatch) {
        let newCurrentDecorationId = null;
        let matchPosition = 0;
        if (nextMatch) {
            for (let i = 0, len = this._decorations.length; i < len; i++) {
                const range = this._editor.getModel().getDecorationRange(this._decorations[i]);
                if (nextMatch.equalsRange(range)) {
                    newCurrentDecorationId = this._decorations[i];
                    matchPosition = (i + 1);
                    break;
                }
            }
        }
        if (this._highlightedDecorationId !== null || newCurrentDecorationId !== null) {
            this._editor.changeDecorations((changeAccessor) => {
                if (this._highlightedDecorationId !== null) {
                    changeAccessor.changeDecorationOptions(this._highlightedDecorationId, FindDecorations._FIND_MATCH_DECORATION);
                    this._highlightedDecorationId = null;
                }
                if (newCurrentDecorationId !== null) {
                    this._highlightedDecorationId = newCurrentDecorationId;
                    changeAccessor.changeDecorationOptions(this._highlightedDecorationId, FindDecorations._CURRENT_FIND_MATCH_DECORATION);
                }
                if (this._rangeHighlightDecorationId !== null) {
                    changeAccessor.removeDecoration(this._rangeHighlightDecorationId);
                    this._rangeHighlightDecorationId = null;
                }
                if (newCurrentDecorationId !== null) {
                    let rng = this._editor.getModel().getDecorationRange(newCurrentDecorationId);
                    if (rng.startLineNumber !== rng.endLineNumber && rng.endColumn === 1) {
                        const lineBeforeEnd = rng.endLineNumber - 1;
                        const lineBeforeEndMaxColumn = this._editor.getModel().getLineMaxColumn(lineBeforeEnd);
                        rng = new Range(rng.startLineNumber, rng.startColumn, lineBeforeEnd, lineBeforeEndMaxColumn);
                    }
                    this._rangeHighlightDecorationId = changeAccessor.addDecoration(rng, FindDecorations._RANGE_HIGHLIGHT_DECORATION);
                }
            });
        }
        return matchPosition;
    }
    set(findMatches, findScopes) {
        this._editor.changeDecorations((accessor) => {
            let findMatchesOptions = FindDecorations._FIND_MATCH_DECORATION;
            const newOverviewRulerApproximateDecorations = [];
            if (findMatches.length > 1000) {
                // we go into a mode where the overview ruler gets "approximate" decorations
                // the reason is that the overview ruler paints all the decorations in the file and we don't want to cause freezes
                findMatchesOptions = FindDecorations._FIND_MATCH_NO_OVERVIEW_DECORATION;
                // approximate a distance in lines where matches should be merged
                const lineCount = this._editor.getModel().getLineCount();
                const height = this._editor.getLayoutInfo().height;
                const approxPixelsPerLine = height / lineCount;
                const mergeLinesDelta = Math.max(2, Math.ceil(3 / approxPixelsPerLine));
                // merge decorations as much as possible
                let prevStartLineNumber = findMatches[0].range.startLineNumber;
                let prevEndLineNumber = findMatches[0].range.endLineNumber;
                for (let i = 1, len = findMatches.length; i < len; i++) {
                    const range = findMatches[i].range;
                    if (prevEndLineNumber + mergeLinesDelta >= range.startLineNumber) {
                        if (range.endLineNumber > prevEndLineNumber) {
                            prevEndLineNumber = range.endLineNumber;
                        }
                    }
                    else {
                        newOverviewRulerApproximateDecorations.push({
                            range: new Range(prevStartLineNumber, 1, prevEndLineNumber, 1),
                            options: FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION
                        });
                        prevStartLineNumber = range.startLineNumber;
                        prevEndLineNumber = range.endLineNumber;
                    }
                }
                newOverviewRulerApproximateDecorations.push({
                    range: new Range(prevStartLineNumber, 1, prevEndLineNumber, 1),
                    options: FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION
                });
            }
            // Find matches
            const newFindMatchesDecorations = new Array(findMatches.length);
            for (let i = 0, len = findMatches.length; i < len; i++) {
                newFindMatchesDecorations[i] = {
                    range: findMatches[i].range,
                    options: findMatchesOptions
                };
            }
            this._decorations = accessor.deltaDecorations(this._decorations, newFindMatchesDecorations);
            // Overview ruler approximate decorations
            this._overviewRulerApproximateDecorations = accessor.deltaDecorations(this._overviewRulerApproximateDecorations, newOverviewRulerApproximateDecorations);
            // Range highlight
            if (this._rangeHighlightDecorationId) {
                accessor.removeDecoration(this._rangeHighlightDecorationId);
                this._rangeHighlightDecorationId = null;
            }
            // Find scope
            if (this._findScopeDecorationIds.length) {
                this._findScopeDecorationIds.forEach(findScopeDecorationId => accessor.removeDecoration(findScopeDecorationId));
                this._findScopeDecorationIds = [];
            }
            if (findScopes === null || findScopes === void 0 ? void 0 : findScopes.length) {
                this._findScopeDecorationIds = findScopes.map(findScope => accessor.addDecoration(findScope, FindDecorations._FIND_SCOPE_DECORATION));
            }
        });
    }
    matchBeforePosition(position) {
        if (this._decorations.length === 0) {
            return null;
        }
        for (let i = this._decorations.length - 1; i >= 0; i--) {
            const decorationId = this._decorations[i];
            const r = this._editor.getModel().getDecorationRange(decorationId);
            if (!r || r.endLineNumber > position.lineNumber) {
                continue;
            }
            if (r.endLineNumber < position.lineNumber) {
                return r;
            }
            if (r.endColumn > position.column) {
                continue;
            }
            return r;
        }
        return this._editor.getModel().getDecorationRange(this._decorations[this._decorations.length - 1]);
    }
    matchAfterPosition(position) {
        if (this._decorations.length === 0) {
            return null;
        }
        for (let i = 0, len = this._decorations.length; i < len; i++) {
            const decorationId = this._decorations[i];
            const r = this._editor.getModel().getDecorationRange(decorationId);
            if (!r || r.startLineNumber < position.lineNumber) {
                continue;
            }
            if (r.startLineNumber > position.lineNumber) {
                return r;
            }
            if (r.startColumn < position.column) {
                continue;
            }
            return r;
        }
        return this._editor.getModel().getDecorationRange(this._decorations[0]);
    }
    _allDecorations() {
        let result = [];
        result = result.concat(this._decorations);
        result = result.concat(this._overviewRulerApproximateDecorations);
        if (this._findScopeDecorationIds.length) {
            result.push(...this._findScopeDecorationIds);
        }
        if (this._rangeHighlightDecorationId) {
            result.push(this._rangeHighlightDecorationId);
        }
        return result;
    }
}
FindDecorations._CURRENT_FIND_MATCH_DECORATION = ModelDecorationOptions.register({
    description: 'current-find-match',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    zIndex: 13,
    className: 'currentFindMatch',
    showIfCollapsed: true,
    overviewRuler: {
        color: themeColorFromId(overviewRulerFindMatchForeground),
        position: OverviewRulerLane.Center
    },
    minimap: {
        color: themeColorFromId(minimapFindMatch),
        position: MinimapPosition.Inline
    }
});
FindDecorations._FIND_MATCH_DECORATION = ModelDecorationOptions.register({
    description: 'find-match',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    zIndex: 10,
    className: 'findMatch',
    showIfCollapsed: true,
    overviewRuler: {
        color: themeColorFromId(overviewRulerFindMatchForeground),
        position: OverviewRulerLane.Center
    },
    minimap: {
        color: themeColorFromId(minimapFindMatch),
        position: MinimapPosition.Inline
    }
});
FindDecorations._FIND_MATCH_NO_OVERVIEW_DECORATION = ModelDecorationOptions.register({
    description: 'find-match-no-overview',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    className: 'findMatch',
    showIfCollapsed: true
});
FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION = ModelDecorationOptions.register({
    description: 'find-match-only-overview',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    overviewRuler: {
        color: themeColorFromId(overviewRulerFindMatchForeground),
        position: OverviewRulerLane.Center
    }
});
FindDecorations._RANGE_HIGHLIGHT_DECORATION = ModelDecorationOptions.register({
    description: 'find-range-highlight',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    className: 'rangeHighlight',
    isWholeLine: true
});
FindDecorations._FIND_SCOPE_DECORATION = ModelDecorationOptions.register({
    description: 'find-scope',
    className: 'findScope',
    isWholeLine: true
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/find/browser/replaceAllCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class ReplaceAllCommand {
    constructor(editorSelection, ranges, replaceStrings) {
        this._editorSelection = editorSelection;
        this._ranges = ranges;
        this._replaceStrings = replaceStrings;
        this._trackedEditorSelectionId = null;
    }
    getEditOperations(model, builder) {
        if (this._ranges.length > 0) {
            // Collect all edit operations
            const ops = [];
            for (let i = 0; i < this._ranges.length; i++) {
                ops.push({
                    range: this._ranges[i],
                    text: this._replaceStrings[i]
                });
            }
            // Sort them in ascending order by range starts
            ops.sort((o1, o2) => {
                return Range.compareRangesUsingStarts(o1.range, o2.range);
            });
            // Merge operations that touch each other
            const resultOps = [];
            let previousOp = ops[0];
            for (let i = 1; i < ops.length; i++) {
                if (previousOp.range.endLineNumber === ops[i].range.startLineNumber && previousOp.range.endColumn === ops[i].range.startColumn) {
                    // These operations are one after another and can be merged
                    previousOp.range = previousOp.range.plusRange(ops[i].range);
                    previousOp.text = previousOp.text + ops[i].text;
                }
                else {
                    resultOps.push(previousOp);
                    previousOp = ops[i];
                }
            }
            resultOps.push(previousOp);
            for (const op of resultOps) {
                builder.addEditOperation(op.range, op.text);
            }
        }
        this._trackedEditorSelectionId = builder.trackSelection(this._editorSelection);
    }
    computeCursorState(model, helper) {
        return helper.getTrackedSelection(this._trackedEditorSelectionId);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/search.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

function buildReplaceStringWithCasePreserved(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 (containsUppercaseCharacter(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 {
            // we don't understand its pattern yet.
            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 += buildReplaceStringWithCasePreserved([splitMatchAtSpecialCharacter[index]], splitValue) + specialCharacter;
    });
    return replaceString.slice(0, -1);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/find/browser/replacePattern.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/**
 * Assigned when the replace pattern is entirely static.
 */
class StaticValueReplacePattern {
    constructor(staticValue) {
        this.staticValue = staticValue;
        this.kind = 0 /* ReplacePatternKind.StaticValue */;
    }
}
/**
 * Assigned when the replace pattern has replacement patterns.
 */
class DynamicPiecesReplacePattern {
    constructor(pieces) {
        this.pieces = pieces;
        this.kind = 1 /* ReplacePatternKind.DynamicPieces */;
    }
}
class ReplacePattern {
    constructor(pieces) {
        if (!pieces || pieces.length === 0) {
            this._state = new StaticValueReplacePattern('');
        }
        else if (pieces.length === 1 && pieces[0].staticValue !== null) {
            this._state = new StaticValueReplacePattern(pieces[0].staticValue);
        }
        else {
            this._state = new DynamicPiecesReplacePattern(pieces);
        }
    }
    static fromStaticValue(value) {
        return new ReplacePattern([ReplacePiece.staticValue(value)]);
    }
    get hasReplacementPatterns() {
        return (this._state.kind === 1 /* ReplacePatternKind.DynamicPieces */);
    }
    buildReplaceString(matches, preserveCase) {
        if (this._state.kind === 0 /* ReplacePatternKind.StaticValue */) {
            if (preserveCase) {
                return buildReplaceStringWithCasePreserved(matches, this._state.staticValue);
            }
            else {
                return this._state.staticValue;
            }
        }
        let result = '';
        for (let i = 0, len = this._state.pieces.length; i < len; i++) {
            const piece = this._state.pieces[i];
            if (piece.staticValue !== null) {
                // static value ReplacePiece
                result += piece.staticValue;
                continue;
            }
            // match index ReplacePiece
            let match = ReplacePattern._substitute(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, len = match.length; idx < len; 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 _substitute(matchIndex, matches) {
        if (matches === null) {
            return '';
        }
        if (matchIndex === 0) {
            return matches[0];
        }
        let remainder = '';
        while (matchIndex > 0) {
            if (matchIndex < matches.length) {
                // A match can be undefined
                const match = (matches[matchIndex] || '');
                return match + remainder;
            }
            remainder = String(matchIndex % 10) + remainder;
            matchIndex = Math.floor(matchIndex / 10);
        }
        return '$' + remainder;
    }
}
/**
 * A replace piece can either be a static string or an index to a specific match.
 */
class ReplacePiece {
    constructor(staticValue, matchIndex, caseOps) {
        this.staticValue = staticValue;
        this.matchIndex = matchIndex;
        if (!caseOps || caseOps.length === 0) {
            this.caseOps = null;
        }
        else {
            this.caseOps = caseOps.slice(0);
        }
    }
    static staticValue(value) {
        return new ReplacePiece(value, -1, null);
    }
    static caseOps(index, caseOps) {
        return new ReplacePiece(null, index, caseOps);
    }
}
class ReplacePieceBuilder {
    constructor(source) {
        this._source = source;
        this._lastCharIndex = 0;
        this._result = [];
        this._resultLen = 0;
        this._currentStaticPiece = '';
    }
    emitUnchanged(toCharIndex) {
        this._emitStatic(this._source.substring(this._lastCharIndex, toCharIndex));
        this._lastCharIndex = toCharIndex;
    }
    emitStatic(value, toCharIndex) {
        this._emitStatic(value);
        this._lastCharIndex = toCharIndex;
    }
    _emitStatic(value) {
        if (value.length === 0) {
            return;
        }
        this._currentStaticPiece += value;
    }
    emitMatchIndex(index, toCharIndex, caseOps) {
        if (this._currentStaticPiece.length !== 0) {
            this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece);
            this._currentStaticPiece = '';
        }
        this._result[this._resultLen++] = ReplacePiece.caseOps(index, caseOps);
        this._lastCharIndex = toCharIndex;
    }
    finalize() {
        this.emitUnchanged(this._source.length);
        if (this._currentStaticPiece.length !== 0) {
            this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece);
            this._currentStaticPiece = '';
        }
        return new ReplacePattern(this._result);
    }
}
/**
 * \n			=> inserts a LF
 * \t			=> inserts a TAB
 * \\			=> inserts a "\".
 * \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.
 * $$			=> inserts a "$".
 * $& and $0	=> inserts the matched substring.
 * $n			=> Where n is a non-negative integer lesser than 100, inserts the nth parenthesized submatch string
 * everything else stays untouched
 *
 * Also see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter
 */
function parseReplaceString(replaceString) {
    if (!replaceString || replaceString.length === 0) {
        return new ReplacePattern(null);
    }
    const caseOps = [];
    const result = new ReplacePieceBuilder(replaceString);
    for (let i = 0, len = replaceString.length; i < len; i++) {
        const chCode = replaceString.charCodeAt(i);
        if (chCode === 92 /* CharCode.Backslash */) {
            // move to next char
            i++;
            if (i >= len) {
                // string ends with a \
                break;
            }
            const nextChCode = replaceString.charCodeAt(i);
            // let replaceWithCharacter: string | null = null;
            switch (nextChCode) {
                case 92 /* CharCode.Backslash */:
                    // \\ => inserts a "\"
                    result.emitUnchanged(i - 1);
                    result.emitStatic('\\', i + 1);
                    break;
                case 110 /* CharCode.n */:
                    // \n => inserts a LF
                    result.emitUnchanged(i - 1);
                    result.emitStatic('\n', i + 1);
                    break;
                case 116 /* CharCode.t */:
                    // \t => inserts a TAB
                    result.emitUnchanged(i - 1);
                    result.emitStatic('\t', i + 1);
                    break;
                // Case modification of string replacements, patterned after Boost, but only applied
                // to the replacement text, not subsequent content.
                case 117 /* CharCode.u */:
                // \u => upper-cases one character.
                case 85 /* CharCode.U */:
                // \U => upper-cases ALL following characters.
                case 108 /* CharCode.l */:
                // \l => lower-cases one character.
                case 76 /* CharCode.L */:
                    // \L => lower-cases ALL following characters.
                    result.emitUnchanged(i - 1);
                    result.emitStatic('', i + 1);
                    caseOps.push(String.fromCharCode(nextChCode));
                    break;
            }
            continue;
        }
        if (chCode === 36 /* CharCode.DollarSign */) {
            // move to next char
            i++;
            if (i >= len) {
                // string ends with a $
                break;
            }
            const nextChCode = replaceString.charCodeAt(i);
            if (nextChCode === 36 /* CharCode.DollarSign */) {
                // $$ => inserts a "$"
                result.emitUnchanged(i - 1);
                result.emitStatic('$', i + 1);
                continue;
            }
            if (nextChCode === 48 /* CharCode.Digit0 */ || nextChCode === 38 /* CharCode.Ampersand */) {
                // $& and $0 => inserts the matched substring.
                result.emitUnchanged(i - 1);
                result.emitMatchIndex(0, i + 1, caseOps);
                caseOps.length = 0;
                continue;
            }
            if (49 /* CharCode.Digit1 */ <= nextChCode && nextChCode <= 57 /* CharCode.Digit9 */) {
                // $n
                let matchIndex = nextChCode - 48 /* CharCode.Digit0 */;
                // peek next char to probe for $nn
                if (i + 1 < len) {
                    const nextNextChCode = replaceString.charCodeAt(i + 1);
                    if (48 /* CharCode.Digit0 */ <= nextNextChCode && nextNextChCode <= 57 /* CharCode.Digit9 */) {
                        // $nn
                        // move to next char
                        i++;
                        matchIndex = matchIndex * 10 + (nextNextChCode - 48 /* CharCode.Digit0 */);
                        result.emitUnchanged(i - 2);
                        result.emitMatchIndex(matchIndex, i + 1, caseOps);
                        caseOps.length = 0;
                        continue;
                    }
                }
                result.emitUnchanged(i - 1);
                result.emitMatchIndex(matchIndex, i + 1, caseOps);
                caseOps.length = 0;
                continue;
            }
        }
    }
    return result.finalize();
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/find/browser/findModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/












const CONTEXT_FIND_WIDGET_VISIBLE = new RawContextKey('findWidgetVisible', false);
const CONTEXT_FIND_WIDGET_NOT_VISIBLE = CONTEXT_FIND_WIDGET_VISIBLE.toNegated();
// Keep ContextKey use of 'Focussed' to not break when clauses
const CONTEXT_FIND_INPUT_FOCUSED = new RawContextKey('findInputFocussed', false);
const CONTEXT_REPLACE_INPUT_FOCUSED = new RawContextKey('replaceInputFocussed', false);
const ToggleCaseSensitiveKeybinding = {
    primary: 512 /* KeyMod.Alt */ | 33 /* KeyCode.KeyC */,
    mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 33 /* KeyCode.KeyC */ }
};
const ToggleWholeWordKeybinding = {
    primary: 512 /* KeyMod.Alt */ | 53 /* KeyCode.KeyW */,
    mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 53 /* KeyCode.KeyW */ }
};
const ToggleRegexKeybinding = {
    primary: 512 /* KeyMod.Alt */ | 48 /* KeyCode.KeyR */,
    mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 48 /* KeyCode.KeyR */ }
};
const ToggleSearchScopeKeybinding = {
    primary: 512 /* KeyMod.Alt */ | 42 /* KeyCode.KeyL */,
    mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 42 /* KeyCode.KeyL */ }
};
const TogglePreserveCaseKeybinding = {
    primary: 512 /* KeyMod.Alt */ | 46 /* KeyCode.KeyP */,
    mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 46 /* KeyCode.KeyP */ }
};
const FIND_IDS = {
    StartFindAction: 'actions.find',
    StartFindWithSelection: 'actions.findWithSelection',
    StartFindWithArgs: 'editor.actions.findWithArgs',
    NextMatchFindAction: 'editor.action.nextMatchFindAction',
    PreviousMatchFindAction: 'editor.action.previousMatchFindAction',
    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'
};
const MATCHES_LIMIT = 19999;
const RESEARCH_DELAY = 240;
class FindModelBoundToEditorModel {
    constructor(editor, state) {
        this._toDispose = new DisposableStore();
        this._editor = editor;
        this._state = state;
        this._isDisposed = false;
        this._startSearchingTimer = new TimeoutTimer();
        this._decorations = new FindDecorations(editor);
        this._toDispose.add(this._decorations);
        this._updateDecorationsScheduler = new RunOnceScheduler(() => this.research(false), 100);
        this._toDispose.add(this._updateDecorationsScheduler);
        this._toDispose.add(this._editor.onDidChangeCursorPosition((e) => {
            if (e.reason === 3 /* CursorChangeReason.Explicit */
                || e.reason === 5 /* CursorChangeReason.Undo */
                || e.reason === 6 /* CursorChangeReason.Redo */) {
                this._decorations.setStartPosition(this._editor.getPosition());
            }
        }));
        this._ignoreModelContentChanged = false;
        this._toDispose.add(this._editor.onDidChangeModelContent((e) => {
            if (this._ignoreModelContentChanged) {
                return;
            }
            if (e.isFlush) {
                // a model.setValue() was called
                this._decorations.reset();
            }
            this._decorations.setStartPosition(this._editor.getPosition());
            this._updateDecorationsScheduler.schedule();
        }));
        this._toDispose.add(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
        this.research(false, this._state.searchScope);
    }
    dispose() {
        this._isDisposed = true;
        dispose(this._startSearchingTimer);
        this._toDispose.dispose();
    }
    _onStateChanged(e) {
        if (this._isDisposed) {
            // The find model is disposed during a find state changed event
            return;
        }
        if (!this._editor.hasModel()) {
            // The find model will be disposed momentarily
            return;
        }
        if (e.searchString || e.isReplaceRevealed || e.isRegex || e.wholeWord || e.matchCase || e.searchScope) {
            const model = this._editor.getModel();
            if (model.isTooLargeForSyncing()) {
                this._startSearchingTimer.cancel();
                this._startSearchingTimer.setIfNotSet(() => {
                    if (e.searchScope) {
                        this.research(e.moveCursor, this._state.searchScope);
                    }
                    else {
                        this.research(e.moveCursor);
                    }
                }, RESEARCH_DELAY);
            }
            else {
                if (e.searchScope) {
                    this.research(e.moveCursor, this._state.searchScope);
                }
                else {
                    this.research(e.moveCursor);
                }
            }
        }
    }
    static _getSearchRange(model, findScope) {
        // If we have set now or before a find scope, use it for computing the search range
        if (findScope) {
            return findScope;
        }
        return model.getFullModelRange();
    }
    research(moveCursor, newFindScope) {
        let findScopes = null;
        if (typeof newFindScope !== 'undefined') {
            if (newFindScope !== null) {
                if (!Array.isArray(newFindScope)) {
                    findScopes = [newFindScope];
                }
                else {
                    findScopes = newFindScope;
                }
            }
        }
        else {
            findScopes = this._decorations.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 Range(findScope.startLineNumber, 1, endLineNumber, this._editor.getModel().getLineMaxColumn(endLineNumber));
                }
                return findScope;
            });
        }
        const findMatches = this._findMatches(findScopes, false, MATCHES_LIMIT);
        this._decorations.set(findMatches, findScopes);
        const editorSelection = this._editor.getSelection();
        let currentMatchesPosition = this._decorations.getCurrentMatchesPosition(editorSelection);
        if (currentMatchesPosition === 0 && findMatches.length > 0) {
            // current selection is not on top of a match
            // try to find its nearest result from the top of the document
            const matchAfterSelection = findFirstInSorted(findMatches.map(match => match.range), range => Range.compareRangesUsingStarts(range, editorSelection) >= 0);
            currentMatchesPosition = matchAfterSelection > 0 ? matchAfterSelection - 1 + 1 /** match position is one based */ : currentMatchesPosition;
        }
        this._state.changeMatchInfo(currentMatchesPosition, this._decorations.getCount(), undefined);
        if (moveCursor && this._editor.getOption(37 /* EditorOption.find */).cursorMoveOnType) {
            this._moveToNextMatch(this._decorations.getStartPosition());
        }
    }
    _hasMatches() {
        return (this._state.matchesCount > 0);
    }
    _cannotFind() {
        if (!this._hasMatches()) {
            const findScope = this._decorations.getFindScope();
            if (findScope) {
                // Reveal the selection so user is reminded that 'selection find' is on.
                this._editor.revealRangeInCenterIfOutsideViewport(findScope, 0 /* ScrollType.Smooth */);
            }
            return true;
        }
        return false;
    }
    _setCurrentFindMatch(match) {
        const matchesPosition = this._decorations.setCurrentFindMatch(match);
        this._state.changeMatchInfo(matchesPosition, this._decorations.getCount(), match);
        this._editor.setSelection(match);
        this._editor.revealRangeInCenterIfOutsideViewport(match, 0 /* ScrollType.Smooth */);
    }
    _prevSearchPosition(before) {
        const isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf('^') >= 0
            || this._state.searchString.indexOf('$') >= 0);
        let { lineNumber, column } = before;
        const model = this._editor.getModel();
        if (isUsingLineStops || column === 1) {
            if (lineNumber === 1) {
                lineNumber = model.getLineCount();
            }
            else {
                lineNumber--;
            }
            column = model.getLineMaxColumn(lineNumber);
        }
        else {
            column--;
        }
        return new Position(lineNumber, column);
    }
    _moveToPrevMatch(before, isRecursed = false) {
        if (!this._state.canNavigateBack()) {
            // we are beyond the first matched find result
            // instead of doing nothing, we should refocus the first item
            const nextMatchRange = this._decorations.matchAfterPosition(before);
            if (nextMatchRange) {
                this._setCurrentFindMatch(nextMatchRange);
            }
            return;
        }
        if (this._decorations.getCount() < MATCHES_LIMIT) {
            let prevMatchRange = this._decorations.matchBeforePosition(before);
            if (prevMatchRange && prevMatchRange.isEmpty() && prevMatchRange.getStartPosition().equals(before)) {
                before = this._prevSearchPosition(before);
                prevMatchRange = this._decorations.matchBeforePosition(before);
            }
            if (prevMatchRange) {
                this._setCurrentFindMatch(prevMatchRange);
            }
            return;
        }
        if (this._cannotFind()) {
            return;
        }
        const findScope = this._decorations.getFindScope();
        const searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.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._editor.getModel();
        let position = new Position(lineNumber, column);
        let prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(119 /* EditorOption.wordSeparators */) : null, false);
        if (prevMatch && prevMatch.range.isEmpty() && prevMatch.range.getStartPosition().equals(position)) {
            // Looks like we're stuck at this position, unacceptable!
            position = this._prevSearchPosition(position);
            prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(119 /* EditorOption.wordSeparators */) : null, false);
        }
        if (!prevMatch) {
            // there is precisely one match and selection is on top of it
            return;
        }
        if (!isRecursed && !searchRange.containsRange(prevMatch.range)) {
            return this._moveToPrevMatch(prevMatch.range.getStartPosition(), true);
        }
        this._setCurrentFindMatch(prevMatch.range);
    }
    moveToPrevMatch() {
        this._moveToPrevMatch(this._editor.getSelection().getStartPosition());
    }
    _nextSearchPosition(after) {
        const isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf('^') >= 0
            || this._state.searchString.indexOf('$') >= 0);
        let { lineNumber, column } = after;
        const model = this._editor.getModel();
        if (isUsingLineStops || column === model.getLineMaxColumn(lineNumber)) {
            if (lineNumber === model.getLineCount()) {
                lineNumber = 1;
            }
            else {
                lineNumber++;
            }
            column = 1;
        }
        else {
            column++;
        }
        return new Position(lineNumber, column);
    }
    _moveToNextMatch(after) {
        if (!this._state.canNavigateForward()) {
            // we are beyond the last matched find result
            // instead of doing nothing, we should refocus the last item
            const prevMatchRange = this._decorations.matchBeforePosition(after);
            if (prevMatchRange) {
                this._setCurrentFindMatch(prevMatchRange);
            }
            return;
        }
        if (this._decorations.getCount() < MATCHES_LIMIT) {
            let nextMatchRange = this._decorations.matchAfterPosition(after);
            if (nextMatchRange && nextMatchRange.isEmpty() && nextMatchRange.getStartPosition().equals(after)) {
                // Looks like we're stuck at this position, unacceptable!
                after = this._nextSearchPosition(after);
                nextMatchRange = this._decorations.matchAfterPosition(after);
            }
            if (nextMatchRange) {
                this._setCurrentFindMatch(nextMatchRange);
            }
            return;
        }
        const nextMatch = this._getNextMatch(after, false, true);
        if (nextMatch) {
            this._setCurrentFindMatch(nextMatch.range);
        }
    }
    _getNextMatch(after, captureMatches, forceMove, isRecursed = false) {
        if (this._cannotFind()) {
            return null;
        }
        const findScope = this._decorations.getFindScope();
        const searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.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._editor.getModel();
        let position = new Position(lineNumber, column);
        let nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(119 /* EditorOption.wordSeparators */) : null, captureMatches);
        if (forceMove && nextMatch && nextMatch.range.isEmpty() && nextMatch.range.getStartPosition().equals(position)) {
            // Looks like we're stuck at this position, unacceptable!
            position = this._nextSearchPosition(position);
            nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(119 /* EditorOption.wordSeparators */) : null, captureMatches);
        }
        if (!nextMatch) {
            // there is precisely one match and selection is on top of it
            return null;
        }
        if (!isRecursed && !searchRange.containsRange(nextMatch.range)) {
            return this._getNextMatch(nextMatch.range.getEndPosition(), captureMatches, forceMove, true);
        }
        return nextMatch;
    }
    moveToNextMatch() {
        this._moveToNextMatch(this._editor.getSelection().getEndPosition());
    }
    _getReplacePattern() {
        if (this._state.isRegex) {
            return parseReplaceString(this._state.replaceString);
        }
        return ReplacePattern.fromStaticValue(this._state.replaceString);
    }
    replace() {
        if (!this._hasMatches()) {
            return;
        }
        const replacePattern = this._getReplacePattern();
        const selection = this._editor.getSelection();
        const nextMatch = this._getNextMatch(selection.getStartPosition(), true, false);
        if (nextMatch) {
            if (selection.equalsRange(nextMatch.range)) {
                // selection sits on a find match => replace it!
                const replaceString = replacePattern.buildReplaceString(nextMatch.matches, this._state.preserveCase);
                const command = new ReplaceCommand(selection, replaceString);
                this._executeEditorCommand('replace', command);
                this._decorations.setStartPosition(new Position(selection.startLineNumber, selection.startColumn + replaceString.length));
                this.research(true);
            }
            else {
                this._decorations.setStartPosition(this._editor.getPosition());
                this._setCurrentFindMatch(nextMatch.range);
            }
        }
    }
    _findMatches(findScopes, captureMatches, limitResultCount) {
        const searchRanges = (findScopes || [null]).map((scope) => FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), scope));
        return this._editor.getModel().findMatches(this._state.searchString, searchRanges, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(119 /* EditorOption.wordSeparators */) : null, captureMatches, limitResultCount);
    }
    replaceAll() {
        if (!this._hasMatches()) {
            return;
        }
        const findScopes = this._decorations.getFindScopes();
        if (findScopes === null && this._state.matchesCount >= MATCHES_LIMIT) {
            // Doing a replace on the entire file that is over ${MATCHES_LIMIT} matches
            this._largeReplaceAll();
        }
        else {
            this._regularReplaceAll(findScopes);
        }
        this.research(false);
    }
    _largeReplaceAll() {
        const searchParams = new SearchParams(this._state.searchString, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(119 /* 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._editor.getModel();
        const modelText = model.getValue(1 /* EndOfLinePreference.LF */);
        const fullModelRange = model.getFullModelRange();
        const replacePattern = this._getReplacePattern();
        let resultText;
        const preserveCase = this._state.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 command = new ReplaceCommandThatPreservesSelection(fullModelRange, resultText, this._editor.getSelection());
        this._executeEditorCommand('replaceAll', command);
    }
    _regularReplaceAll(findScopes) {
        const replacePattern = this._getReplacePattern();
        // Get all the ranges (even more than the highlighted ones)
        const matches = this._findMatches(findScopes, replacePattern.hasReplacementPatterns || this._state.preserveCase, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
        const replaceStrings = [];
        for (let i = 0, len = matches.length; i < len; i++) {
            replaceStrings[i] = replacePattern.buildReplaceString(matches[i].matches, this._state.preserveCase);
        }
        const command = new ReplaceAllCommand(this._editor.getSelection(), matches.map(m => m.range), replaceStrings);
        this._executeEditorCommand('replaceAll', command);
    }
    selectAllMatches() {
        if (!this._hasMatches()) {
            return;
        }
        const findScopes = this._decorations.getFindScopes();
        // Get all the ranges (even more than the highlighted ones)
        const matches = this._findMatches(findScopes, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
        let selections = matches.map(m => new Selection(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn));
        // If one of the ranges is the editor selection, then maintain it as primary
        const editorSelection = this._editor.getSelection();
        for (let i = 0, len = selections.length; i < len; i++) {
            const sel = selections[i];
            if (sel.equalsRange(editorSelection)) {
                selections = [editorSelection].concat(selections.slice(0, i)).concat(selections.slice(i + 1));
                break;
            }
        }
        this._editor.setSelections(selections);
    }
    _executeEditorCommand(source, command) {
        try {
            this._ignoreModelContentChanged = true;
            this._editor.pushUndoStop();
            this._editor.executeCommand(source, command);
            this._editor.pushUndoStop();
        }
        finally {
            this._ignoreModelContentChanged = false;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/find/browser/findOptionsWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







class FindOptionsWidget extends Widget {
    constructor(editor, state, keybindingService, themeService) {
        super();
        this._hideSoon = this._register(new RunOnceScheduler(() => this._hide(), 2000));
        this._isVisible = false;
        this._editor = editor;
        this._state = state;
        this._keybindingService = keybindingService;
        this._domNode = document.createElement('div');
        this._domNode.className = 'findOptionsWidget';
        this._domNode.style.display = 'none';
        this._domNode.style.top = '10px';
        this._domNode.setAttribute('role', 'presentation');
        this._domNode.setAttribute('aria-hidden', 'true');
        const inputActiveOptionBorderColor = themeService.getColorTheme().getColor(inputActiveOptionBorder);
        const inputActiveOptionForegroundColor = themeService.getColorTheme().getColor(inputActiveOptionForeground);
        const inputActiveOptionBackgroundColor = themeService.getColorTheme().getColor(inputActiveOptionBackground);
        this.caseSensitive = this._register(new CaseSensitiveToggle({
            appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleCaseSensitiveCommand),
            isChecked: this._state.matchCase,
            inputActiveOptionBorder: inputActiveOptionBorderColor,
            inputActiveOptionForeground: inputActiveOptionForegroundColor,
            inputActiveOptionBackground: inputActiveOptionBackgroundColor
        }));
        this._domNode.appendChild(this.caseSensitive.domNode);
        this._register(this.caseSensitive.onChange(() => {
            this._state.change({
                matchCase: this.caseSensitive.checked
            }, false);
        }));
        this.wholeWords = this._register(new WholeWordsToggle({
            appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleWholeWordCommand),
            isChecked: this._state.wholeWord,
            inputActiveOptionBorder: inputActiveOptionBorderColor,
            inputActiveOptionForeground: inputActiveOptionForegroundColor,
            inputActiveOptionBackground: inputActiveOptionBackgroundColor
        }));
        this._domNode.appendChild(this.wholeWords.domNode);
        this._register(this.wholeWords.onChange(() => {
            this._state.change({
                wholeWord: this.wholeWords.checked
            }, false);
        }));
        this.regex = this._register(new RegexToggle({
            appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleRegexCommand),
            isChecked: this._state.isRegex,
            inputActiveOptionBorder: inputActiveOptionBorderColor,
            inputActiveOptionForeground: inputActiveOptionForegroundColor,
            inputActiveOptionBackground: inputActiveOptionBackgroundColor
        }));
        this._domNode.appendChild(this.regex.domNode);
        this._register(this.regex.onChange(() => {
            this._state.change({
                isRegex: this.regex.checked
            }, false);
        }));
        this._editor.addOverlayWidget(this);
        this._register(this._state.onFindReplaceStateChange((e) => {
            let somethingChanged = false;
            if (e.isRegex) {
                this.regex.checked = this._state.isRegex;
                somethingChanged = true;
            }
            if (e.wholeWord) {
                this.wholeWords.checked = this._state.wholeWord;
                somethingChanged = true;
            }
            if (e.matchCase) {
                this.caseSensitive.checked = this._state.matchCase;
                somethingChanged = true;
            }
            if (!this._state.isRevealed && somethingChanged) {
                this._revealTemporarily();
            }
        }));
        this._register(addDisposableListener(this._domNode, EventType.MOUSE_LEAVE, (e) => this._onMouseLeave()));
        this._register(addDisposableListener(this._domNode, 'mouseover', (e) => this._onMouseOver()));
        this._applyTheme(themeService.getColorTheme());
        this._register(themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
    }
    _keybindingLabelFor(actionId) {
        const kb = this._keybindingService.lookupKeybinding(actionId);
        if (!kb) {
            return '';
        }
        return ` (${kb.getLabel()})`;
    }
    dispose() {
        this._editor.removeOverlayWidget(this);
        super.dispose();
    }
    // ----- IOverlayWidget API
    getId() {
        return FindOptionsWidget.ID;
    }
    getDomNode() {
        return this._domNode;
    }
    getPosition() {
        return {
            preference: 0 /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */
        };
    }
    highlightFindOptions() {
        this._revealTemporarily();
    }
    _revealTemporarily() {
        this._show();
        this._hideSoon.schedule();
    }
    _onMouseLeave() {
        this._hideSoon.schedule();
    }
    _onMouseOver() {
        this._hideSoon.cancel();
    }
    _show() {
        if (this._isVisible) {
            return;
        }
        this._isVisible = true;
        this._domNode.style.display = 'block';
    }
    _hide() {
        if (!this._isVisible) {
            return;
        }
        this._isVisible = false;
        this._domNode.style.display = 'none';
    }
    _applyTheme(theme) {
        const inputStyles = {
            inputActiveOptionBorder: theme.getColor(inputActiveOptionBorder),
            inputActiveOptionForeground: theme.getColor(inputActiveOptionForeground),
            inputActiveOptionBackground: theme.getColor(inputActiveOptionBackground)
        };
        this.caseSensitive.style(inputStyles);
        this.wholeWords.style(inputStyles);
        this.regex.style(inputStyles);
    }
}
FindOptionsWidget.ID = 'editor.contrib.findOptionsWidget';
registerThemingParticipant((theme, collector) => {
    const widgetBackground = theme.getColor(editorWidgetBackground);
    if (widgetBackground) {
        collector.addRule(`.monaco-editor .findOptionsWidget { background-color: ${widgetBackground}; }`);
    }
    const widgetForeground = theme.getColor(editorWidgetForeground);
    if (widgetForeground) {
        collector.addRule(`.monaco-editor .findOptionsWidget { color: ${widgetForeground}; }`);
    }
    const widgetShadowColor = theme.getColor(widgetShadow);
    if (widgetShadowColor) {
        collector.addRule(`.monaco-editor .findOptionsWidget { box-shadow: 0 0 8px 2px ${widgetShadowColor}; }`);
    }
    const hcBorder = theme.getColor(contrastBorder);
    if (hcBorder) {
        collector.addRule(`.monaco-editor .findOptionsWidget { border: 2px solid ${hcBorder}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/find/browser/findState.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




function effectiveOptionValue(override, value) {
    if (override === 1 /* FindOptionOverride.True */) {
        return true;
    }
    if (override === 2 /* FindOptionOverride.False */) {
        return false;
    }
    return value;
}
class FindReplaceState extends Disposable {
    constructor() {
        super();
        this._onFindReplaceStateChange = this._register(new Emitter());
        this.onFindReplaceStateChange = this._onFindReplaceStateChange.event;
        this._searchString = '';
        this._replaceString = '';
        this._isRevealed = false;
        this._isReplaceRevealed = false;
        this._isRegex = false;
        this._isRegexOverride = 0 /* FindOptionOverride.NotSet */;
        this._wholeWord = false;
        this._wholeWordOverride = 0 /* FindOptionOverride.NotSet */;
        this._matchCase = false;
        this._matchCaseOverride = 0 /* FindOptionOverride.NotSet */;
        this._preserveCase = false;
        this._preserveCaseOverride = 0 /* FindOptionOverride.NotSet */;
        this._searchScope = null;
        this._matchesPosition = 0;
        this._matchesCount = 0;
        this._currentMatch = null;
        this._loop = true;
        this._isSearching = false;
        this._filters = null;
    }
    get searchString() { return this._searchString; }
    get replaceString() { return this._replaceString; }
    get isRevealed() { return this._isRevealed; }
    get isReplaceRevealed() { return this._isReplaceRevealed; }
    get isRegex() { return effectiveOptionValue(this._isRegexOverride, this._isRegex); }
    get wholeWord() { return effectiveOptionValue(this._wholeWordOverride, this._wholeWord); }
    get matchCase() { return effectiveOptionValue(this._matchCaseOverride, this._matchCase); }
    get preserveCase() { return effectiveOptionValue(this._preserveCaseOverride, this._preserveCase); }
    get actualIsRegex() { return this._isRegex; }
    get actualWholeWord() { return this._wholeWord; }
    get actualMatchCase() { return this._matchCase; }
    get actualPreserveCase() { return this._preserveCase; }
    get searchScope() { return this._searchScope; }
    get matchesPosition() { return this._matchesPosition; }
    get matchesCount() { return this._matchesCount; }
    get currentMatch() { return this._currentMatch; }
    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._matchesPosition !== matchesPosition) {
            this._matchesPosition = matchesPosition;
            changeEvent.matchesPosition = true;
            somethingChanged = true;
        }
        if (this._matchesCount !== matchesCount) {
            this._matchesCount = matchesCount;
            changeEvent.matchesCount = true;
            somethingChanged = true;
        }
        if (typeof currentMatch !== 'undefined') {
            if (!Range.equalsRange(this._currentMatch, currentMatch)) {
                this._currentMatch = currentMatch;
                changeEvent.currentMatch = true;
                somethingChanged = true;
            }
        }
        if (somethingChanged) {
            this._onFindReplaceStateChange.fire(changeEvent);
        }
    }
    change(newState, moveCursor, updateHistory = true) {
        var _a;
        const changeEvent = {
            moveCursor: moveCursor,
            updateHistory: 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._searchString !== newState.searchString) {
                this._searchString = newState.searchString;
                changeEvent.searchString = true;
                somethingChanged = true;
            }
        }
        if (typeof newState.replaceString !== 'undefined') {
            if (this._replaceString !== newState.replaceString) {
                this._replaceString = newState.replaceString;
                changeEvent.replaceString = true;
                somethingChanged = true;
            }
        }
        if (typeof newState.isRevealed !== 'undefined') {
            if (this._isRevealed !== newState.isRevealed) {
                this._isRevealed = newState.isRevealed;
                changeEvent.isRevealed = true;
                somethingChanged = true;
            }
        }
        if (typeof newState.isReplaceRevealed !== 'undefined') {
            if (this._isReplaceRevealed !== newState.isReplaceRevealed) {
                this._isReplaceRevealed = newState.isReplaceRevealed;
                changeEvent.isReplaceRevealed = true;
                somethingChanged = true;
            }
        }
        if (typeof newState.isRegex !== 'undefined') {
            this._isRegex = newState.isRegex;
        }
        if (typeof newState.wholeWord !== 'undefined') {
            this._wholeWord = newState.wholeWord;
        }
        if (typeof newState.matchCase !== 'undefined') {
            this._matchCase = newState.matchCase;
        }
        if (typeof newState.preserveCase !== 'undefined') {
            this._preserveCase = newState.preserveCase;
        }
        if (typeof newState.searchScope !== 'undefined') {
            if (!((_a = newState.searchScope) === null || _a === void 0 ? void 0 : _a.every((newSearchScope) => {
                var _a;
                return (_a = this._searchScope) === null || _a === void 0 ? void 0 : _a.some(existingSearchScope => {
                    return !Range.equalsRange(existingSearchScope, newSearchScope);
                });
            }))) {
                this._searchScope = newState.searchScope;
                changeEvent.searchScope = true;
                somethingChanged = true;
            }
        }
        if (typeof newState.loop !== 'undefined') {
            if (this._loop !== newState.loop) {
                this._loop = newState.loop;
                changeEvent.loop = true;
                somethingChanged = true;
            }
        }
        if (typeof newState.isSearching !== 'undefined') {
            if (this._isSearching !== newState.isSearching) {
                this._isSearching = newState.isSearching;
                changeEvent.isSearching = true;
                somethingChanged = true;
            }
        }
        if (typeof newState.filters !== 'undefined') {
            if (this._filters) {
                this._filters.update(newState.filters);
            }
            else {
                this._filters = newState.filters;
            }
            changeEvent.filters = true;
            somethingChanged = true;
        }
        // Overrides get set when they explicitly come in and get reset anytime something else changes
        this._isRegexOverride = (typeof newState.isRegexOverride !== 'undefined' ? newState.isRegexOverride : 0 /* FindOptionOverride.NotSet */);
        this._wholeWordOverride = (typeof newState.wholeWordOverride !== 'undefined' ? newState.wholeWordOverride : 0 /* FindOptionOverride.NotSet */);
        this._matchCaseOverride = (typeof newState.matchCaseOverride !== 'undefined' ? newState.matchCaseOverride : 0 /* FindOptionOverride.NotSet */);
        this._preserveCaseOverride = (typeof newState.preserveCaseOverride !== 'undefined' ? newState.preserveCaseOverride : 0 /* FindOptionOverride.NotSet */);
        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._onFindReplaceStateChange.fire(changeEvent);
        }
    }
    canNavigateBack() {
        return this.canNavigateInLoop() || (this.matchesPosition !== 1);
    }
    canNavigateForward() {
        return this.canNavigateInLoop() || (this.matchesPosition < this.matchesCount);
    }
    canNavigateInLoop() {
        return this._loop || (this.matchesCount >= MATCHES_LIMIT);
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/find/browser/findWidget.css
var findWidget = __webpack_require__(26864);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/find/browser/findWidget.css

      
      
      
      
      
      
      
      
      

var findWidget_options = {};

findWidget_options.styleTagTransform = (styleTagTransform_default());
findWidget_options.setAttributes = (setAttributesWithoutAttributes_default());

      findWidget_options.insert = insertBySelector_default().bind(null, "head");
    
findWidget_options.domAPI = (styleDomAPI_default());
findWidget_options.insertStyleElement = (insertStyleElement_default());

var findWidget_update = injectStylesIntoStyleTag_default()(findWidget/* default */.A, findWidget_options);




       /* harmony default export */ const browser_findWidget = (findWidget/* default */.A && findWidget/* default */.A.locals ? findWidget/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/platform/history/browser/historyWidgetKeybindingHint.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
function showHistoryKeybindingHint(keybindingService) {
    var _a, _b;
    return ((_a = keybindingService.lookupKeybinding('history.showPrevious')) === null || _a === void 0 ? void 0 : _a.getElectronAccelerator()) === 'Up' && ((_b = keybindingService.lookupKeybinding('history.showNext')) === null || _b === void 0 ? void 0 : _b.getElectronAccelerator()) === 'Down';
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/find/browser/findWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var findWidget_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};





















const findSelectionIcon = registerIcon('find-selection', Codicon.selection, localize('findSelectionIcon', 'Icon for \'Find in Selection\' in the editor find widget.'));
const findCollapsedIcon = registerIcon('find-collapsed', Codicon.chevronRight, localize('findCollapsedIcon', 'Icon to indicate that the editor find widget is collapsed.'));
const findExpandedIcon = registerIcon('find-expanded', Codicon.chevronDown, localize('findExpandedIcon', 'Icon to indicate that the editor find widget is expanded.'));
const findReplaceIcon = registerIcon('find-replace', Codicon.replace, localize('findReplaceIcon', 'Icon for \'Replace\' in the editor find widget.'));
const findReplaceAllIcon = registerIcon('find-replace-all', Codicon.replaceAll, localize('findReplaceAllIcon', 'Icon for \'Replace All\' in the editor find widget.'));
const findPreviousMatchIcon = registerIcon('find-previous-match', Codicon.arrowUp, localize('findPreviousMatchIcon', 'Icon for \'Find Previous\' in the editor find widget.'));
const findNextMatchIcon = registerIcon('find-next-match', Codicon.arrowDown, localize('findNextMatchIcon', 'Icon for \'Find Next\' in the editor find widget.'));
const NLS_FIND_INPUT_LABEL = localize('label.find', "Find");
const NLS_FIND_INPUT_PLACEHOLDER = localize('placeholder.find', "Find");
const NLS_PREVIOUS_MATCH_BTN_LABEL = localize('label.previousMatchButton', "Previous Match");
const NLS_NEXT_MATCH_BTN_LABEL = localize('label.nextMatchButton', "Next Match");
const NLS_TOGGLE_SELECTION_FIND_TITLE = localize('label.toggleSelectionFind', "Find in Selection");
const NLS_CLOSE_BTN_LABEL = localize('label.closeButton', "Close");
const NLS_REPLACE_INPUT_LABEL = localize('label.replace', "Replace");
const NLS_REPLACE_INPUT_PLACEHOLDER = localize('placeholder.replace', "Replace");
const NLS_REPLACE_BTN_LABEL = localize('label.replaceButton', "Replace");
const NLS_REPLACE_ALL_BTN_LABEL = localize('label.replaceAllButton', "Replace All");
const NLS_TOGGLE_REPLACE_MODE_BTN_LABEL = localize('label.toggleReplaceButton', "Toggle Replace");
const NLS_MATCHES_COUNT_LIMIT_TITLE = localize('title.matchesCountLimit', "Only the first {0} results are highlighted, but all find operations work on the entire text.", MATCHES_LIMIT);
const NLS_MATCHES_LOCATION = localize('label.matchesLocation', "{0} of {1}");
const NLS_NO_RESULTS = localize('label.noResults', "No results");
const FIND_WIDGET_INITIAL_WIDTH = 419;
const PART_WIDTH = 275;
const FIND_INPUT_AREA_WIDTH = PART_WIDTH - 54;
let MAX_MATCHES_COUNT_WIDTH = 69;
// let FIND_ALL_CONTROLS_WIDTH = 17/** Find Input margin-left */ + (MAX_MATCHES_COUNT_WIDTH + 3 + 1) /** Match Results */ + 23 /** Button */ * 4 + 2/** sash */;
const FIND_INPUT_AREA_HEIGHT = 33; // The height of Find Widget when Replace Input is not visible.
const ctrlEnterReplaceAllWarningPromptedKey = 'ctrlEnterReplaceAll.windows.donotask';
const findWidget_ctrlKeyMod = (isMacintosh ? 256 /* KeyMod.WinCtrl */ : 2048 /* KeyMod.CtrlCmd */);
class FindWidgetViewZone {
    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 isMultiline = !!value.match(/\n/);
    if (textarea && isMultiline && textarea.selectionStart > 0) {
        event.stopPropagation();
        return;
    }
}
function stopPropagationForMultiLineDownwards(event, value, textarea) {
    const isMultiline = !!value.match(/\n/);
    if (textarea && isMultiline && textarea.selectionEnd < textarea.value.length) {
        event.stopPropagation();
        return;
    }
}
class findWidget_FindWidget extends Widget {
    constructor(codeEditor, controller, state, contextViewProvider, keybindingService, contextKeyService, themeService, storageService, notificationService) {
        super();
        this._cachedHeight = null;
        this._revealTimeouts = [];
        this._codeEditor = codeEditor;
        this._controller = controller;
        this._state = state;
        this._contextViewProvider = contextViewProvider;
        this._keybindingService = keybindingService;
        this._contextKeyService = contextKeyService;
        this._storageService = storageService;
        this._notificationService = notificationService;
        this._ctrlEnterReplaceAllWarningPrompted = !!storageService.getBoolean(ctrlEnterReplaceAllWarningPromptedKey, 0 /* StorageScope.PROFILE */);
        this._isVisible = false;
        this._isReplaceVisible = false;
        this._ignoreChangeEvent = false;
        this._updateHistoryDelayer = new Delayer(500);
        this._register(toDisposable(() => this._updateHistoryDelayer.cancel()));
        this._register(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
        this._buildDomNode();
        this._updateButtons();
        this._tryUpdateWidgetWidth();
        this._findInput.inputBox.layout();
        this._register(this._codeEditor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(83 /* EditorOption.readOnly */)) {
                if (this._codeEditor.getOption(83 /* EditorOption.readOnly */)) {
                    // Hide replace part if editor becomes read only
                    this._state.change({ isReplaceRevealed: false }, false);
                }
                this._updateButtons();
            }
            if (e.hasChanged(133 /* EditorOption.layoutInfo */)) {
                this._tryUpdateWidgetWidth();
            }
            if (e.hasChanged(2 /* EditorOption.accessibilitySupport */)) {
                this.updateAccessibilitySupport();
            }
            if (e.hasChanged(37 /* EditorOption.find */)) {
                const addExtraSpaceOnTop = this._codeEditor.getOption(37 /* EditorOption.find */).addExtraSpaceOnTop;
                if (addExtraSpaceOnTop && !this._viewZone) {
                    this._viewZone = new FindWidgetViewZone(0);
                    this._showViewZone();
                }
                if (!addExtraSpaceOnTop && this._viewZone) {
                    this._removeViewZone();
                }
            }
        }));
        this.updateAccessibilitySupport();
        this._register(this._codeEditor.onDidChangeCursorSelection(() => {
            if (this._isVisible) {
                this._updateToggleSelectionFindButton();
            }
        }));
        this._register(this._codeEditor.onDidFocusEditorWidget(() => findWidget_awaiter(this, void 0, void 0, function* () {
            if (this._isVisible) {
                const globalBufferTerm = yield this._controller.getGlobalBufferTerm();
                if (globalBufferTerm && globalBufferTerm !== this._state.searchString) {
                    this._state.change({ searchString: globalBufferTerm }, false);
                    this._findInput.select();
                }
            }
        })));
        this._findInputFocused = CONTEXT_FIND_INPUT_FOCUSED.bindTo(contextKeyService);
        this._findFocusTracker = this._register(trackFocus(this._findInput.inputBox.inputElement));
        this._register(this._findFocusTracker.onDidFocus(() => {
            this._findInputFocused.set(true);
            this._updateSearchScope();
        }));
        this._register(this._findFocusTracker.onDidBlur(() => {
            this._findInputFocused.set(false);
        }));
        this._replaceInputFocused = CONTEXT_REPLACE_INPUT_FOCUSED.bindTo(contextKeyService);
        this._replaceFocusTracker = this._register(trackFocus(this._replaceInput.inputBox.inputElement));
        this._register(this._replaceFocusTracker.onDidFocus(() => {
            this._replaceInputFocused.set(true);
            this._updateSearchScope();
        }));
        this._register(this._replaceFocusTracker.onDidBlur(() => {
            this._replaceInputFocused.set(false);
        }));
        this._codeEditor.addOverlayWidget(this);
        if (this._codeEditor.getOption(37 /* EditorOption.find */).addExtraSpaceOnTop) {
            this._viewZone = new FindWidgetViewZone(0); // Put it before the first line then users can scroll beyond the first line.
        }
        this._applyTheme(themeService.getColorTheme());
        this._register(themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
        this._register(this._codeEditor.onDidChangeModel(() => {
            if (!this._isVisible) {
                return;
            }
            this._viewZoneId = undefined;
        }));
        this._register(this._codeEditor.onDidScrollChange((e) => {
            if (e.scrollTopChanged) {
                this._layoutViewZone();
                return;
            }
            // for other scroll changes, layout the viewzone in next tick to avoid ruining current rendering.
            setTimeout(() => {
                this._layoutViewZone();
            }, 0);
        }));
    }
    // ----- IOverlayWidget API
    getId() {
        return findWidget_FindWidget.ID;
    }
    getDomNode() {
        return this._domNode;
    }
    getPosition() {
        if (this._isVisible) {
            return {
                preference: 0 /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */
            };
        }
        return null;
    }
    // ----- React to state changes
    _onStateChanged(e) {
        if (e.searchString) {
            try {
                this._ignoreChangeEvent = true;
                this._findInput.setValue(this._state.searchString);
            }
            finally {
                this._ignoreChangeEvent = false;
            }
            this._updateButtons();
        }
        if (e.replaceString) {
            this._replaceInput.inputBox.value = this._state.replaceString;
        }
        if (e.isRevealed) {
            if (this._state.isRevealed) {
                this._reveal();
            }
            else {
                this._hide(true);
            }
        }
        if (e.isReplaceRevealed) {
            if (this._state.isReplaceRevealed) {
                if (!this._codeEditor.getOption(83 /* EditorOption.readOnly */) && !this._isReplaceVisible) {
                    this._isReplaceVisible = true;
                    this._replaceInput.width = getTotalWidth(this._findInput.domNode);
                    this._updateButtons();
                    this._replaceInput.inputBox.layout();
                }
            }
            else {
                if (this._isReplaceVisible) {
                    this._isReplaceVisible = false;
                    this._updateButtons();
                }
            }
        }
        if ((e.isRevealed || e.isReplaceRevealed) && (this._state.isRevealed || this._state.isReplaceRevealed)) {
            if (this._tryUpdateHeight()) {
                this._showViewZone();
            }
        }
        if (e.isRegex) {
            this._findInput.setRegex(this._state.isRegex);
        }
        if (e.wholeWord) {
            this._findInput.setWholeWords(this._state.wholeWord);
        }
        if (e.matchCase) {
            this._findInput.setCaseSensitive(this._state.matchCase);
        }
        if (e.preserveCase) {
            this._replaceInput.setPreserveCase(this._state.preserveCase);
        }
        if (e.searchScope) {
            if (this._state.searchScope) {
                this._toggleSelectionFind.checked = true;
            }
            else {
                this._toggleSelectionFind.checked = false;
            }
            this._updateToggleSelectionFindButton();
        }
        if (e.searchString || e.matchesCount || e.matchesPosition) {
            const showRedOutline = (this._state.searchString.length > 0 && this._state.matchesCount === 0);
            this._domNode.classList.toggle('no-results', showRedOutline);
            this._updateMatchesCount();
            this._updateButtons();
        }
        if (e.searchString || e.currentMatch) {
            this._layoutViewZone();
        }
        if (e.updateHistory) {
            this._delayedUpdateHistory();
        }
        if (e.loop) {
            this._updateButtons();
        }
    }
    _delayedUpdateHistory() {
        this._updateHistoryDelayer.trigger(this._updateHistory.bind(this)).then(undefined, onUnexpectedError);
    }
    _updateHistory() {
        if (this._state.searchString) {
            this._findInput.inputBox.addToHistory();
        }
        if (this._state.replaceString) {
            this._replaceInput.inputBox.addToHistory();
        }
    }
    _updateMatchesCount() {
        this._matchesCount.style.minWidth = MAX_MATCHES_COUNT_WIDTH + 'px';
        if (this._state.matchesCount >= MATCHES_LIMIT) {
            this._matchesCount.title = NLS_MATCHES_COUNT_LIMIT_TITLE;
        }
        else {
            this._matchesCount.title = '';
        }
        // remove previous content
        if (this._matchesCount.firstChild) {
            this._matchesCount.removeChild(this._matchesCount.firstChild);
        }
        let label;
        if (this._state.matchesCount > 0) {
            let matchesCount = String(this._state.matchesCount);
            if (this._state.matchesCount >= MATCHES_LIMIT) {
                matchesCount += '+';
            }
            let matchesPosition = String(this._state.matchesPosition);
            if (matchesPosition === '0') {
                matchesPosition = '?';
            }
            label = format(NLS_MATCHES_LOCATION, matchesPosition, matchesCount);
        }
        else {
            label = NLS_NO_RESULTS;
        }
        this._matchesCount.appendChild(document.createTextNode(label));
        aria_alert(this._getAriaLabel(label, this._state.currentMatch, this._state.searchString));
        MAX_MATCHES_COUNT_WIDTH = Math.max(MAX_MATCHES_COUNT_WIDTH, this._matchesCount.clientWidth);
    }
    // ----- actions
    _getAriaLabel(label, currentMatch, searchString) {
        if (label === NLS_NO_RESULTS) {
            return searchString === ''
                ? localize('ariaSearchNoResultEmpty', "{0} found", label)
                : localize('ariaSearchNoResult', "{0} found for '{1}'", label, searchString);
        }
        if (currentMatch) {
            const ariaLabel = localize('ariaSearchNoResultWithLineNum', "{0} found for '{1}', at {2}", label, searchString, currentMatch.startLineNumber + ':' + currentMatch.startColumn);
            const model = this._codeEditor.getModel();
            if (model && (currentMatch.startLineNumber <= model.getLineCount()) && (currentMatch.startLineNumber >= 1)) {
                const lineContent = model.getLineContent(currentMatch.startLineNumber);
                return `${lineContent}, ${ariaLabel}`;
            }
            return ariaLabel;
        }
        return localize('ariaSearchNoResultWithLineNumNoCurrentMatch', "{0} found for '{1}'", label, 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.
     */
    _updateToggleSelectionFindButton() {
        const selection = this._codeEditor.getSelection();
        const isSelection = selection ? (selection.startLineNumber !== selection.endLineNumber || selection.startColumn !== selection.endColumn) : false;
        const isChecked = this._toggleSelectionFind.checked;
        if (this._isVisible && (isChecked || isSelection)) {
            this._toggleSelectionFind.enable();
        }
        else {
            this._toggleSelectionFind.disable();
        }
    }
    _updateButtons() {
        this._findInput.setEnabled(this._isVisible);
        this._replaceInput.setEnabled(this._isVisible && this._isReplaceVisible);
        this._updateToggleSelectionFindButton();
        this._closeBtn.setEnabled(this._isVisible);
        const findInputIsNonEmpty = (this._state.searchString.length > 0);
        const matchesCount = this._state.matchesCount ? true : false;
        this._prevBtn.setEnabled(this._isVisible && findInputIsNonEmpty && matchesCount && this._state.canNavigateBack());
        this._nextBtn.setEnabled(this._isVisible && findInputIsNonEmpty && matchesCount && this._state.canNavigateForward());
        this._replaceBtn.setEnabled(this._isVisible && this._isReplaceVisible && findInputIsNonEmpty);
        this._replaceAllBtn.setEnabled(this._isVisible && this._isReplaceVisible && findInputIsNonEmpty);
        this._domNode.classList.toggle('replaceToggled', this._isReplaceVisible);
        this._toggleReplaceBtn.setExpanded(this._isReplaceVisible);
        const canReplace = !this._codeEditor.getOption(83 /* EditorOption.readOnly */);
        this._toggleReplaceBtn.setEnabled(this._isVisible && canReplace);
    }
    _reveal() {
        this._revealTimeouts.forEach(e => {
            clearTimeout(e);
        });
        this._revealTimeouts = [];
        if (!this._isVisible) {
            this._isVisible = true;
            const selection = this._codeEditor.getSelection();
            switch (this._codeEditor.getOption(37 /* EditorOption.find */).autoFindInSelection) {
                case 'always':
                    this._toggleSelectionFind.checked = true;
                    break;
                case 'never':
                    this._toggleSelectionFind.checked = false;
                    break;
                case 'multiline': {
                    const isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber;
                    this._toggleSelectionFind.checked = isSelectionMultipleLine;
                    break;
                }
                default:
                    break;
            }
            this._tryUpdateWidgetWidth();
            this._updateButtons();
            this._revealTimeouts.push(setTimeout(() => {
                this._domNode.classList.add('visible');
                this._domNode.setAttribute('aria-hidden', 'false');
            }, 0));
            // validate query again as it's being dismissed when we hide the find widget.
            this._revealTimeouts.push(setTimeout(() => {
                this._findInput.validate();
            }, 200));
            this._codeEditor.layoutOverlayWidget(this);
            let adjustEditorScrollTop = true;
            if (this._codeEditor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection && selection) {
                const domNode = this._codeEditor.getDomNode();
                if (domNode) {
                    const editorCoords = getDomNodePagePosition(domNode);
                    const startCoords = this._codeEditor.getScrolledVisiblePosition(selection.getStartPosition());
                    const startLeft = editorCoords.left + (startCoords ? startCoords.left : 0);
                    const startTop = startCoords ? startCoords.top : 0;
                    if (this._viewZone && startTop < this._viewZone.heightInPx) {
                        if (selection.endLineNumber > selection.startLineNumber) {
                            adjustEditorScrollTop = false;
                        }
                        const leftOfFindWidget = getTopLeftOffset(this._domNode).left;
                        if (startLeft > leftOfFindWidget) {
                            adjustEditorScrollTop = false;
                        }
                        const endCoords = this._codeEditor.getScrolledVisiblePosition(selection.getEndPosition());
                        const endLeft = editorCoords.left + (endCoords ? endCoords.left : 0);
                        if (endLeft > leftOfFindWidget) {
                            adjustEditorScrollTop = false;
                        }
                    }
                }
            }
            this._showViewZone(adjustEditorScrollTop);
        }
    }
    _hide(focusTheEditor) {
        this._revealTimeouts.forEach(e => {
            clearTimeout(e);
        });
        this._revealTimeouts = [];
        if (this._isVisible) {
            this._isVisible = false;
            this._updateButtons();
            this._domNode.classList.remove('visible');
            this._domNode.setAttribute('aria-hidden', 'true');
            this._findInput.clearMessage();
            if (focusTheEditor) {
                this._codeEditor.focus();
            }
            this._codeEditor.layoutOverlayWidget(this);
            this._removeViewZone();
        }
    }
    _layoutViewZone(targetScrollTop) {
        const addExtraSpaceOnTop = this._codeEditor.getOption(37 /* EditorOption.find */).addExtraSpaceOnTop;
        if (!addExtraSpaceOnTop) {
            this._removeViewZone();
            return;
        }
        if (!this._isVisible) {
            return;
        }
        const viewZone = this._viewZone;
        if (this._viewZoneId !== undefined || !viewZone) {
            return;
        }
        this._codeEditor.changeViewZones((accessor) => {
            viewZone.heightInPx = this._getHeight();
            this._viewZoneId = accessor.addZone(viewZone);
            // scroll top adjust to make sure the editor doesn't scroll when adding viewzone at the beginning.
            this._codeEditor.setScrollTop(targetScrollTop || this._codeEditor.getScrollTop() + viewZone.heightInPx);
        });
    }
    _showViewZone(adjustScroll = true) {
        if (!this._isVisible) {
            return;
        }
        const addExtraSpaceOnTop = this._codeEditor.getOption(37 /* EditorOption.find */).addExtraSpaceOnTop;
        if (!addExtraSpaceOnTop) {
            return;
        }
        if (this._viewZone === undefined) {
            this._viewZone = new FindWidgetViewZone(0);
        }
        const viewZone = this._viewZone;
        this._codeEditor.changeViewZones((accessor) => {
            if (this._viewZoneId !== undefined) {
                // the view zone already exists, we need to update the height
                const newHeight = this._getHeight();
                if (newHeight === viewZone.heightInPx) {
                    return;
                }
                const scrollAdjustment = newHeight - viewZone.heightInPx;
                viewZone.heightInPx = newHeight;
                accessor.layoutZone(this._viewZoneId);
                if (adjustScroll) {
                    this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() + scrollAdjustment);
                }
                return;
            }
            else {
                let scrollAdjustment = this._getHeight();
                // if the editor has top padding, factor that into the zone height
                scrollAdjustment -= this._codeEditor.getOption(77 /* EditorOption.padding */).top;
                if (scrollAdjustment <= 0) {
                    return;
                }
                viewZone.heightInPx = scrollAdjustment;
                this._viewZoneId = accessor.addZone(viewZone);
                if (adjustScroll) {
                    this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() + scrollAdjustment);
                }
            }
        });
    }
    _removeViewZone() {
        this._codeEditor.changeViewZones((accessor) => {
            if (this._viewZoneId !== undefined) {
                accessor.removeZone(this._viewZoneId);
                this._viewZoneId = undefined;
                if (this._viewZone) {
                    this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() - this._viewZone.heightInPx);
                    this._viewZone = undefined;
                }
            }
        });
    }
    _applyTheme(theme) {
        const inputStyles = {
            inputActiveOptionBorder: theme.getColor(inputActiveOptionBorder),
            inputActiveOptionBackground: theme.getColor(inputActiveOptionBackground),
            inputActiveOptionForeground: theme.getColor(inputActiveOptionForeground),
            inputBackground: theme.getColor(inputBackground),
            inputForeground: theme.getColor(inputForeground),
            inputBorder: theme.getColor(inputBorder),
            inputValidationInfoBackground: theme.getColor(inputValidationInfoBackground),
            inputValidationInfoForeground: theme.getColor(inputValidationInfoForeground),
            inputValidationInfoBorder: theme.getColor(inputValidationInfoBorder),
            inputValidationWarningBackground: theme.getColor(inputValidationWarningBackground),
            inputValidationWarningForeground: theme.getColor(inputValidationWarningForeground),
            inputValidationWarningBorder: theme.getColor(inputValidationWarningBorder),
            inputValidationErrorBackground: theme.getColor(inputValidationErrorBackground),
            inputValidationErrorForeground: theme.getColor(inputValidationErrorForeground),
            inputValidationErrorBorder: theme.getColor(inputValidationErrorBorder),
        };
        this._findInput.style(inputStyles);
        this._replaceInput.style(inputStyles);
        this._toggleSelectionFind.style(inputStyles);
    }
    _tryUpdateWidgetWidth() {
        if (!this._isVisible) {
            return;
        }
        if (!isInDOM(this._domNode)) {
            // the widget is not in the DOM
            return;
        }
        const layoutInfo = this._codeEditor.getLayoutInfo();
        const editorContentWidth = layoutInfo.contentWidth;
        if (editorContentWidth <= 0) {
            // for example, diff view original editor
            this._domNode.classList.add('hiddenEditor');
            return;
        }
        else if (this._domNode.classList.contains('hiddenEditor')) {
            this._domNode.classList.remove('hiddenEditor');
        }
        const editorWidth = layoutInfo.width;
        const minimapWidth = layoutInfo.minimap.minimapWidth;
        let collapsedFindWidget = false;
        let reducedFindWidget = false;
        let narrowFindWidget = false;
        if (this._resized) {
            const widgetWidth = getTotalWidth(this._domNode);
            if (widgetWidth > FIND_WIDGET_INITIAL_WIDTH) {
                // as the widget is resized by users, we may need to change the max width of the widget as the editor width changes.
                this._domNode.style.maxWidth = `${editorWidth - 28 - minimapWidth - 15}px`;
                this._replaceInput.width = getTotalWidth(this._findInput.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._domNode.classList.toggle('collapsed-find-widget', collapsedFindWidget);
        this._domNode.classList.toggle('narrow-find-widget', narrowFindWidget);
        this._domNode.classList.toggle('reduced-find-widget', reducedFindWidget);
        if (!narrowFindWidget && !collapsedFindWidget) {
            // the minimal left offset of findwidget is 15px.
            this._domNode.style.maxWidth = `${editorWidth - 28 - minimapWidth - 15}px`;
        }
        if (this._resized) {
            this._findInput.inputBox.layout();
            const findInputWidth = this._findInput.inputBox.element.clientWidth;
            if (findInputWidth > 0) {
                this._replaceInput.width = findInputWidth;
            }
        }
        else if (this._isReplaceVisible) {
            this._replaceInput.width = getTotalWidth(this._findInput.domNode);
        }
    }
    _getHeight() {
        let totalheight = 0;
        // find input margin top
        totalheight += 4;
        // find input height
        totalheight += this._findInput.inputBox.height + 2 /** input box border */;
        if (this._isReplaceVisible) {
            // replace input margin
            totalheight += 4;
            totalheight += this._replaceInput.inputBox.height + 2 /** input box border */;
        }
        // margin bottom
        totalheight += 4;
        return totalheight;
    }
    _tryUpdateHeight() {
        const totalHeight = this._getHeight();
        if (this._cachedHeight !== null && this._cachedHeight === totalHeight) {
            return false;
        }
        this._cachedHeight = totalHeight;
        this._domNode.style.height = `${totalHeight}px`;
        return true;
    }
    // ----- Public
    focusFindInput() {
        this._findInput.select();
        // Edge browser requires focus() in addition to select()
        this._findInput.focus();
    }
    focusReplaceInput() {
        this._replaceInput.select();
        // Edge browser requires focus() in addition to select()
        this._replaceInput.focus();
    }
    highlightFindOptions() {
        this._findInput.highlightFindOptions();
    }
    _updateSearchScope() {
        if (!this._codeEditor.hasModel()) {
            return;
        }
        if (this._toggleSelectionFind.checked) {
            const selections = this._codeEditor.getSelections();
            selections.map(selection => {
                if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
                    selection = selection.setEndPosition(selection.endLineNumber - 1, this._codeEditor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
                }
                const currentMatch = this._state.currentMatch;
                if (selection.startLineNumber !== selection.endLineNumber) {
                    if (!Range.equalsRange(selection, currentMatch)) {
                        return selection;
                    }
                }
                return null;
            }).filter(element => !!element);
            if (selections.length) {
                this._state.change({ searchScope: selections }, true);
            }
        }
    }
    _onFindInputMouseDown(e) {
        // on linux, middle key does pasting.
        if (e.middleButton) {
            e.stopPropagation();
        }
    }
    _onFindInputKeyDown(e) {
        if (e.equals(findWidget_ctrlKeyMod | 3 /* KeyCode.Enter */)) {
            if (this._keybindingService.dispatchEvent(e, e.target)) {
                e.preventDefault();
                return;
            }
            else {
                this._findInput.inputBox.insertAtCursor('\n');
                e.preventDefault();
                return;
            }
        }
        if (e.equals(2 /* KeyCode.Tab */)) {
            if (this._isReplaceVisible) {
                this._replaceInput.focus();
            }
            else {
                this._findInput.focusOnCaseSensitive();
            }
            e.preventDefault();
            return;
        }
        if (e.equals(2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */)) {
            this._codeEditor.focus();
            e.preventDefault();
            return;
        }
        if (e.equals(16 /* KeyCode.UpArrow */)) {
            return stopPropagationForMultiLineUpwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector('textarea'));
        }
        if (e.equals(18 /* KeyCode.DownArrow */)) {
            return stopPropagationForMultiLineDownwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector('textarea'));
        }
    }
    _onReplaceInputKeyDown(e) {
        if (e.equals(findWidget_ctrlKeyMod | 3 /* KeyCode.Enter */)) {
            if (this._keybindingService.dispatchEvent(e, e.target)) {
                e.preventDefault();
                return;
            }
            else {
                if (isWindows && isNative && !this._ctrlEnterReplaceAllWarningPrompted) {
                    // this is the first time when users press Ctrl + Enter to replace all
                    this._notificationService.info(localize('ctrlEnter.keybindingChanged', 'Ctrl+Enter now inserts line break instead of replacing all. You can modify the keybinding for editor.action.replaceAll to override this behavior.'));
                    this._ctrlEnterReplaceAllWarningPrompted = true;
                    this._storageService.store(ctrlEnterReplaceAllWarningPromptedKey, true, 0 /* StorageScope.PROFILE */, 0 /* StorageTarget.USER */);
                }
                this._replaceInput.inputBox.insertAtCursor('\n');
                e.preventDefault();
                return;
            }
        }
        if (e.equals(2 /* KeyCode.Tab */)) {
            this._findInput.focusOnCaseSensitive();
            e.preventDefault();
            return;
        }
        if (e.equals(1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */)) {
            this._findInput.focus();
            e.preventDefault();
            return;
        }
        if (e.equals(2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */)) {
            this._codeEditor.focus();
            e.preventDefault();
            return;
        }
        if (e.equals(16 /* KeyCode.UpArrow */)) {
            return stopPropagationForMultiLineUpwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector('textarea'));
        }
        if (e.equals(18 /* KeyCode.DownArrow */)) {
            return stopPropagationForMultiLineDownwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector('textarea'));
        }
    }
    // ----- sash
    getVerticalSashLeft(_sash) {
        return 0;
    }
    // ----- initialization
    _keybindingLabelFor(actionId) {
        const kb = this._keybindingService.lookupKeybinding(actionId);
        if (!kb) {
            return '';
        }
        return ` (${kb.getLabel()})`;
    }
    _buildDomNode() {
        const flexibleHeight = true;
        const flexibleWidth = true;
        // Find input
        this._findInput = this._register(new ContextScopedFindInput(null, this._contextViewProvider, {
            width: FIND_INPUT_AREA_WIDTH,
            label: NLS_FIND_INPUT_LABEL,
            placeholder: NLS_FIND_INPUT_PLACEHOLDER,
            appendCaseSensitiveLabel: this._keybindingLabelFor(FIND_IDS.ToggleCaseSensitiveCommand),
            appendWholeWordsLabel: this._keybindingLabelFor(FIND_IDS.ToggleWholeWordCommand),
            appendRegexLabel: this._keybindingLabelFor(FIND_IDS.ToggleRegexCommand),
            validation: (value) => {
                if (value.length === 0 || !this._findInput.getRegex()) {
                    return null;
                }
                try {
                    // use `g` and `u` which are also used by the TextModel search
                    new RegExp(value, 'gu');
                    return null;
                }
                catch (e) {
                    return { content: e.message };
                }
            },
            flexibleHeight,
            flexibleWidth,
            flexibleMaxHeight: 118,
            showHistoryHint: () => showHistoryKeybindingHint(this._keybindingService)
        }, this._contextKeyService, true));
        this._findInput.setRegex(!!this._state.isRegex);
        this._findInput.setCaseSensitive(!!this._state.matchCase);
        this._findInput.setWholeWords(!!this._state.wholeWord);
        this._register(this._findInput.onKeyDown((e) => this._onFindInputKeyDown(e)));
        this._register(this._findInput.inputBox.onDidChange(() => {
            if (this._ignoreChangeEvent) {
                return;
            }
            this._state.change({ searchString: this._findInput.getValue() }, true);
        }));
        this._register(this._findInput.onDidOptionChange(() => {
            this._state.change({
                isRegex: this._findInput.getRegex(),
                wholeWord: this._findInput.getWholeWords(),
                matchCase: this._findInput.getCaseSensitive()
            }, true);
        }));
        this._register(this._findInput.onCaseSensitiveKeyDown((e) => {
            if (e.equals(1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */)) {
                if (this._isReplaceVisible) {
                    this._replaceInput.focus();
                    e.preventDefault();
                }
            }
        }));
        this._register(this._findInput.onRegexKeyDown((e) => {
            if (e.equals(2 /* KeyCode.Tab */)) {
                if (this._isReplaceVisible) {
                    this._replaceInput.focusOnPreserve();
                    e.preventDefault();
                }
            }
        }));
        this._register(this._findInput.inputBox.onDidHeightChange((e) => {
            if (this._tryUpdateHeight()) {
                this._showViewZone();
            }
        }));
        if (isLinux) {
            this._register(this._findInput.onMouseDown((e) => this._onFindInputMouseDown(e)));
        }
        this._matchesCount = document.createElement('div');
        this._matchesCount.className = 'matchesCount';
        this._updateMatchesCount();
        // Previous button
        this._prevBtn = this._register(new SimpleButton({
            label: NLS_PREVIOUS_MATCH_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.PreviousMatchFindAction),
            icon: findPreviousMatchIcon,
            onTrigger: () => {
                this._codeEditor.getAction(FIND_IDS.PreviousMatchFindAction).run().then(undefined, onUnexpectedError);
            }
        }));
        // Next button
        this._nextBtn = this._register(new SimpleButton({
            label: NLS_NEXT_MATCH_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.NextMatchFindAction),
            icon: findNextMatchIcon,
            onTrigger: () => {
                this._codeEditor.getAction(FIND_IDS.NextMatchFindAction).run().then(undefined, onUnexpectedError);
            }
        }));
        const findPart = document.createElement('div');
        findPart.className = 'find-part';
        findPart.appendChild(this._findInput.domNode);
        const actionsContainer = document.createElement('div');
        actionsContainer.className = 'find-actions';
        findPart.appendChild(actionsContainer);
        actionsContainer.appendChild(this._matchesCount);
        actionsContainer.appendChild(this._prevBtn.domNode);
        actionsContainer.appendChild(this._nextBtn.domNode);
        // Toggle selection button
        this._toggleSelectionFind = this._register(new Toggle({
            icon: findSelectionIcon,
            title: NLS_TOGGLE_SELECTION_FIND_TITLE + this._keybindingLabelFor(FIND_IDS.ToggleSearchScopeCommand),
            isChecked: false
        }));
        this._register(this._toggleSelectionFind.onChange(() => {
            if (this._toggleSelectionFind.checked) {
                if (this._codeEditor.hasModel()) {
                    const selections = this._codeEditor.getSelections();
                    selections.map(selection => {
                        if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
                            selection = selection.setEndPosition(selection.endLineNumber - 1, this._codeEditor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
                        }
                        if (!selection.isEmpty()) {
                            return selection;
                        }
                        return null;
                    }).filter(element => !!element);
                    if (selections.length) {
                        this._state.change({ searchScope: selections }, true);
                    }
                }
            }
            else {
                this._state.change({ searchScope: null }, true);
            }
        }));
        actionsContainer.appendChild(this._toggleSelectionFind.domNode);
        // Close button
        this._closeBtn = this._register(new SimpleButton({
            label: NLS_CLOSE_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.CloseFindWidgetCommand),
            icon: widgetClose,
            onTrigger: () => {
                this._state.change({ isRevealed: false, searchScope: null }, false);
            },
            onKeyDown: (e) => {
                if (e.equals(2 /* KeyCode.Tab */)) {
                    if (this._isReplaceVisible) {
                        if (this._replaceBtn.isEnabled()) {
                            this._replaceBtn.focus();
                        }
                        else {
                            this._codeEditor.focus();
                        }
                        e.preventDefault();
                    }
                }
            }
        }));
        actionsContainer.appendChild(this._closeBtn.domNode);
        // Replace input
        this._replaceInput = this._register(new ContextScopedReplaceInput(null, undefined, {
            label: NLS_REPLACE_INPUT_LABEL,
            placeholder: NLS_REPLACE_INPUT_PLACEHOLDER,
            appendPreserveCaseLabel: this._keybindingLabelFor(FIND_IDS.TogglePreserveCaseCommand),
            history: [],
            flexibleHeight,
            flexibleWidth,
            flexibleMaxHeight: 118,
            showHistoryHint: () => showHistoryKeybindingHint(this._keybindingService)
        }, this._contextKeyService, true));
        this._replaceInput.setPreserveCase(!!this._state.preserveCase);
        this._register(this._replaceInput.onKeyDown((e) => this._onReplaceInputKeyDown(e)));
        this._register(this._replaceInput.inputBox.onDidChange(() => {
            this._state.change({ replaceString: this._replaceInput.inputBox.value }, false);
        }));
        this._register(this._replaceInput.inputBox.onDidHeightChange((e) => {
            if (this._isReplaceVisible && this._tryUpdateHeight()) {
                this._showViewZone();
            }
        }));
        this._register(this._replaceInput.onDidOptionChange(() => {
            this._state.change({
                preserveCase: this._replaceInput.getPreserveCase()
            }, true);
        }));
        this._register(this._replaceInput.onPreserveCaseKeyDown((e) => {
            if (e.equals(2 /* KeyCode.Tab */)) {
                if (this._prevBtn.isEnabled()) {
                    this._prevBtn.focus();
                }
                else if (this._nextBtn.isEnabled()) {
                    this._nextBtn.focus();
                }
                else if (this._toggleSelectionFind.enabled) {
                    this._toggleSelectionFind.focus();
                }
                else if (this._closeBtn.isEnabled()) {
                    this._closeBtn.focus();
                }
                e.preventDefault();
            }
        }));
        // Replace one button
        this._replaceBtn = this._register(new SimpleButton({
            label: NLS_REPLACE_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.ReplaceOneAction),
            icon: findReplaceIcon,
            onTrigger: () => {
                this._controller.replace();
            },
            onKeyDown: (e) => {
                if (e.equals(1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */)) {
                    this._closeBtn.focus();
                    e.preventDefault();
                }
            }
        }));
        // Replace all button
        this._replaceAllBtn = this._register(new SimpleButton({
            label: NLS_REPLACE_ALL_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.ReplaceAllAction),
            icon: findReplaceAllIcon,
            onTrigger: () => {
                this._controller.replaceAll();
            }
        }));
        const replacePart = document.createElement('div');
        replacePart.className = 'replace-part';
        replacePart.appendChild(this._replaceInput.domNode);
        const replaceActionsContainer = document.createElement('div');
        replaceActionsContainer.className = 'replace-actions';
        replacePart.appendChild(replaceActionsContainer);
        replaceActionsContainer.appendChild(this._replaceBtn.domNode);
        replaceActionsContainer.appendChild(this._replaceAllBtn.domNode);
        // Toggle replace button
        this._toggleReplaceBtn = this._register(new SimpleButton({
            label: NLS_TOGGLE_REPLACE_MODE_BTN_LABEL,
            className: 'codicon toggle left',
            onTrigger: () => {
                this._state.change({ isReplaceRevealed: !this._isReplaceVisible }, false);
                if (this._isReplaceVisible) {
                    this._replaceInput.width = getTotalWidth(this._findInput.domNode);
                    this._replaceInput.inputBox.layout();
                }
                this._showViewZone();
            }
        }));
        this._toggleReplaceBtn.setExpanded(this._isReplaceVisible);
        // Widget
        this._domNode = document.createElement('div');
        this._domNode.className = 'editor-widget find-widget';
        this._domNode.setAttribute('aria-hidden', 'true');
        // We need to set this explicitly, otherwise on IE11, the width inheritence of flex doesn't work.
        this._domNode.style.width = `${FIND_WIDGET_INITIAL_WIDTH}px`;
        this._domNode.appendChild(this._toggleReplaceBtn.domNode);
        this._domNode.appendChild(findPart);
        this._domNode.appendChild(replacePart);
        this._resizeSash = new Sash(this._domNode, this, { orientation: 0 /* Orientation.VERTICAL */, size: 2 });
        this._resized = false;
        let originalWidth = FIND_WIDGET_INITIAL_WIDTH;
        this._register(this._resizeSash.onDidStart(() => {
            originalWidth = getTotalWidth(this._domNode);
        }));
        this._register(this._resizeSash.onDidChange((evt) => {
            this._resized = true;
            const width = originalWidth + evt.startX - evt.currentX;
            if (width < FIND_WIDGET_INITIAL_WIDTH) {
                // narrow down the find widget should be handled by CSS.
                return;
            }
            const maxWidth = parseFloat(dom_getComputedStyle(this._domNode).maxWidth) || 0;
            if (width > maxWidth) {
                return;
            }
            this._domNode.style.width = `${width}px`;
            if (this._isReplaceVisible) {
                this._replaceInput.width = getTotalWidth(this._findInput.domNode);
            }
            this._findInput.inputBox.layout();
            this._tryUpdateHeight();
        }));
        this._register(this._resizeSash.onDidReset(() => {
            // users double click on the sash
            const currentWidth = getTotalWidth(this._domNode);
            if (currentWidth < FIND_WIDGET_INITIAL_WIDTH) {
                // The editor is narrow and the width of the find widget is controlled fully by CSS.
                return;
            }
            let width = FIND_WIDGET_INITIAL_WIDTH;
            if (!this._resized || currentWidth === FIND_WIDGET_INITIAL_WIDTH) {
                // 1. never resized before, double click should maximizes it
                // 2. users resized it already but its width is the same as default
                const layoutInfo = this._codeEditor.getLayoutInfo();
                width = layoutInfo.width - 28 - layoutInfo.minimap.minimapWidth - 15;
                this._resized = true;
            }
            else {
                /**
                 * no op, the find widget should be shrinked to its default size.
                 */
            }
            this._domNode.style.width = `${width}px`;
            if (this._isReplaceVisible) {
                this._replaceInput.width = getTotalWidth(this._findInput.domNode);
            }
            this._findInput.inputBox.layout();
        }));
    }
    updateAccessibilitySupport() {
        const value = this._codeEditor.getOption(2 /* EditorOption.accessibilitySupport */);
        this._findInput.setFocusInputOnOptionClick(value !== 2 /* AccessibilitySupport.Enabled */);
    }
}
findWidget_FindWidget.ID = 'editor.contrib.findWidget';
class SimpleButton extends Widget {
    constructor(opts) {
        super();
        this._opts = opts;
        let className = 'button';
        if (this._opts.className) {
            className = className + ' ' + this._opts.className;
        }
        if (this._opts.icon) {
            className = className + ' ' + ThemeIcon.asClassName(this._opts.icon);
        }
        this._domNode = document.createElement('div');
        this._domNode.title = this._opts.label;
        this._domNode.tabIndex = 0;
        this._domNode.className = className;
        this._domNode.setAttribute('role', 'button');
        this._domNode.setAttribute('aria-label', this._opts.label);
        this.onclick(this._domNode, (e) => {
            this._opts.onTrigger();
            e.preventDefault();
        });
        this.onkeydown(this._domNode, (e) => {
            var _a, _b;
            if (e.equals(10 /* KeyCode.Space */) || e.equals(3 /* KeyCode.Enter */)) {
                this._opts.onTrigger();
                e.preventDefault();
                return;
            }
            (_b = (_a = this._opts).onKeyDown) === null || _b === void 0 ? void 0 : _b.call(_a, e);
        });
    }
    get domNode() {
        return this._domNode;
    }
    isEnabled() {
        return (this._domNode.tabIndex >= 0);
    }
    focus() {
        this._domNode.focus();
    }
    setEnabled(enabled) {
        this._domNode.classList.toggle('disabled', !enabled);
        this._domNode.setAttribute('aria-disabled', String(!enabled));
        this._domNode.tabIndex = enabled ? 0 : -1;
    }
    setExpanded(expanded) {
        this._domNode.setAttribute('aria-expanded', String(!!expanded));
        if (expanded) {
            this._domNode.classList.remove(...ThemeIcon.asClassNameArray(findCollapsedIcon));
            this._domNode.classList.add(...ThemeIcon.asClassNameArray(findExpandedIcon));
        }
        else {
            this._domNode.classList.remove(...ThemeIcon.asClassNameArray(findExpandedIcon));
            this._domNode.classList.add(...ThemeIcon.asClassNameArray(findCollapsedIcon));
        }
    }
}
// theming
registerThemingParticipant((theme, collector) => {
    const addBackgroundColorRule = (selector, color) => {
        if (color) {
            collector.addRule(`.monaco-editor ${selector} { background-color: ${color}; }`);
        }
    };
    addBackgroundColorRule('.findMatch', theme.getColor(editorFindMatchHighlight));
    addBackgroundColorRule('.currentFindMatch', theme.getColor(editorFindMatch));
    addBackgroundColorRule('.findScope', theme.getColor(editorFindRangeHighlight));
    const widgetBackground = theme.getColor(editorWidgetBackground);
    addBackgroundColorRule('.find-widget', widgetBackground);
    const widgetShadowColor = theme.getColor(widgetShadow);
    if (widgetShadowColor) {
        collector.addRule(`.monaco-editor .find-widget { box-shadow: 0 0 8px 2px ${widgetShadowColor}; }`);
    }
    const findMatchHighlightBorder = theme.getColor(editorFindMatchHighlightBorder);
    if (findMatchHighlightBorder) {
        collector.addRule(`.monaco-editor .findMatch { border: 1px ${isHighContrast(theme.type) ? 'dotted' : 'solid'} ${findMatchHighlightBorder}; box-sizing: border-box; }`);
    }
    const findMatchBorder = theme.getColor(editorFindMatchBorder);
    if (findMatchBorder) {
        collector.addRule(`.monaco-editor .currentFindMatch { border: 2px solid ${findMatchBorder}; padding: 1px; box-sizing: border-box; }`);
    }
    const findRangeHighlightBorder = theme.getColor(editorFindRangeHighlightBorder);
    if (findRangeHighlightBorder) {
        collector.addRule(`.monaco-editor .findScope { border: 1px ${isHighContrast(theme.type) ? 'dashed' : 'solid'} ${findRangeHighlightBorder}; }`);
    }
    const hcBorder = theme.getColor(contrastBorder);
    if (hcBorder) {
        collector.addRule(`.monaco-editor .find-widget { border: 1px solid ${hcBorder}; }`);
    }
    const foreground = theme.getColor(editorWidgetForeground);
    if (foreground) {
        collector.addRule(`.monaco-editor .find-widget { color: ${foreground}; }`);
    }
    const error = theme.getColor(errorForeground);
    if (error) {
        collector.addRule(`.monaco-editor .find-widget.no-results .matchesCount { color: ${error}; }`);
    }
    const resizeBorderBackground = theme.getColor(editorWidgetResizeBorder);
    if (resizeBorderBackground) {
        collector.addRule(`.monaco-editor .find-widget .monaco-sash { background-color: ${resizeBorderBackground}; }`);
    }
    else {
        const border = theme.getColor(editorWidgetBorder);
        if (border) {
            collector.addRule(`.monaco-editor .find-widget .monaco-sash { background-color: ${border}; }`);
        }
    }
    // Action bars
    const toolbarHoverBackgroundColor = theme.getColor(toolbarHoverBackground);
    if (toolbarHoverBackgroundColor) {
        collector.addRule(`
		.monaco-editor .find-widget .button:not(.disabled):hover,
		.monaco-editor .find-widget .codicon-find-selection:hover {
			background-color: ${toolbarHoverBackgroundColor} !important;
		}
	`);
    }
    // This rule is used to override the outline color for synthetic-focus find input.
    const focusOutline = theme.getColor(focusBorder);
    if (focusOutline) {
        collector.addRule(`.monaco-editor .find-widget .monaco-inputbox.synthetic-focus { outline-color: ${focusOutline}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/find/browser/findController.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var findController_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var findController_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var findController_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};


















const SEARCH_STRING_MAX_LENGTH = 524288;
function getSelectionSearchString(editor, seedSearchStringFromSelection = 'single', seedSearchStringFromNonEmptySelection = false) {
    if (!editor.hasModel()) {
        return null;
    }
    const selection = editor.getSelection();
    // if selection spans multiple lines, default search string to empty
    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;
}
let CommonFindController = class CommonFindController extends Disposable {
    constructor(editor, contextKeyService, storageService, clipboardService) {
        super();
        this._editor = editor;
        this._findWidgetVisible = CONTEXT_FIND_WIDGET_VISIBLE.bindTo(contextKeyService);
        this._contextKeyService = contextKeyService;
        this._storageService = storageService;
        this._clipboardService = clipboardService;
        this._updateHistoryDelayer = new Delayer(500);
        this._state = this._register(new FindReplaceState());
        this.loadQueryState();
        this._register(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
        this._model = null;
        this._register(this._editor.onDidChangeModel(() => {
            const shouldRestartFind = (this._editor.getModel() && this._state.isRevealed);
            this.disposeModel();
            this._state.change({
                searchScope: null,
                matchCase: this._storageService.getBoolean('editor.matchCase', 1 /* StorageScope.WORKSPACE */, false),
                wholeWord: this._storageService.getBoolean('editor.wholeWord', 1 /* StorageScope.WORKSPACE */, false),
                isRegex: this._storageService.getBoolean('editor.isRegex', 1 /* StorageScope.WORKSPACE */, false),
                preserveCase: this._storageService.getBoolean('editor.preserveCase', 1 /* StorageScope.WORKSPACE */, false)
            }, false);
            if (shouldRestartFind) {
                this._start({
                    forceRevealReplace: false,
                    seedSearchStringFromSelection: 'none',
                    seedSearchStringFromNonEmptySelection: false,
                    seedSearchStringFromGlobalClipboard: false,
                    shouldFocus: 0 /* FindStartFocusAction.NoFocusChange */,
                    shouldAnimate: false,
                    updateSearchScope: false,
                    loop: this._editor.getOption(37 /* EditorOption.find */).loop
                });
            }
        }));
    }
    get editor() {
        return this._editor;
    }
    static get(editor) {
        return editor.getContribution(CommonFindController.ID);
    }
    dispose() {
        this.disposeModel();
        super.dispose();
    }
    disposeModel() {
        if (this._model) {
            this._model.dispose();
            this._model = null;
        }
    }
    _onStateChanged(e) {
        this.saveQueryState(e);
        if (e.isRevealed) {
            if (this._state.isRevealed) {
                this._findWidgetVisible.set(true);
            }
            else {
                this._findWidgetVisible.reset();
                this.disposeModel();
            }
        }
        if (e.searchString) {
            this.setGlobalBufferTerm(this._state.searchString);
        }
    }
    saveQueryState(e) {
        if (e.isRegex) {
            this._storageService.store('editor.isRegex', this._state.actualIsRegex, 1 /* StorageScope.WORKSPACE */, 0 /* StorageTarget.USER */);
        }
        if (e.wholeWord) {
            this._storageService.store('editor.wholeWord', this._state.actualWholeWord, 1 /* StorageScope.WORKSPACE */, 0 /* StorageTarget.USER */);
        }
        if (e.matchCase) {
            this._storageService.store('editor.matchCase', this._state.actualMatchCase, 1 /* StorageScope.WORKSPACE */, 0 /* StorageTarget.USER */);
        }
        if (e.preserveCase) {
            this._storageService.store('editor.preserveCase', this._state.actualPreserveCase, 1 /* StorageScope.WORKSPACE */, 0 /* StorageTarget.USER */);
        }
    }
    loadQueryState() {
        this._state.change({
            matchCase: this._storageService.getBoolean('editor.matchCase', 1 /* StorageScope.WORKSPACE */, this._state.matchCase),
            wholeWord: this._storageService.getBoolean('editor.wholeWord', 1 /* StorageScope.WORKSPACE */, this._state.wholeWord),
            isRegex: this._storageService.getBoolean('editor.isRegex', 1 /* StorageScope.WORKSPACE */, this._state.isRegex),
            preserveCase: this._storageService.getBoolean('editor.preserveCase', 1 /* StorageScope.WORKSPACE */, this._state.preserveCase)
        }, false);
    }
    isFindInputFocused() {
        return !!CONTEXT_FIND_INPUT_FOCUSED.getValue(this._contextKeyService);
    }
    getState() {
        return this._state;
    }
    closeFindWidget() {
        this._state.change({
            isRevealed: false,
            searchScope: null
        }, false);
        this._editor.focus();
    }
    toggleCaseSensitive() {
        this._state.change({ matchCase: !this._state.matchCase }, false);
        if (!this._state.isRevealed) {
            this.highlightFindOptions();
        }
    }
    toggleWholeWords() {
        this._state.change({ wholeWord: !this._state.wholeWord }, false);
        if (!this._state.isRevealed) {
            this.highlightFindOptions();
        }
    }
    toggleRegex() {
        this._state.change({ isRegex: !this._state.isRegex }, false);
        if (!this._state.isRevealed) {
            this.highlightFindOptions();
        }
    }
    togglePreserveCase() {
        this._state.change({ preserveCase: !this._state.preserveCase }, false);
        if (!this._state.isRevealed) {
            this.highlightFindOptions();
        }
    }
    toggleSearchScope() {
        if (this._state.searchScope) {
            this._state.change({ searchScope: null }, true);
        }
        else {
            if (this._editor.hasModel()) {
                const selections = this._editor.getSelections();
                selections.map(selection => {
                    if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
                        selection = selection.setEndPosition(selection.endLineNumber - 1, this._editor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
                    }
                    if (!selection.isEmpty()) {
                        return selection;
                    }
                    return null;
                }).filter(element => !!element);
                if (selections.length) {
                    this._state.change({ searchScope: selections }, true);
                }
            }
        }
    }
    setSearchString(searchString) {
        if (this._state.isRegex) {
            searchString = escapeRegExpCharacters(searchString);
        }
        this._state.change({ searchString: searchString }, false);
    }
    highlightFindOptions(ignoreWhenVisible = false) {
        // overwritten in subclass
    }
    _start(opts, newState) {
        return findController_awaiter(this, void 0, void 0, function* () {
            this.disposeModel();
            if (!this._editor.hasModel()) {
                // cannot do anything with an editor that doesn't have a model...
                return;
            }
            const stateChanges = Object.assign(Object.assign({}, newState), { isRevealed: true });
            if (opts.seedSearchStringFromSelection === 'single') {
                const selectionSearchString = getSelectionSearchString(this._editor, opts.seedSearchStringFromSelection, opts.seedSearchStringFromNonEmptySelection);
                if (selectionSearchString) {
                    if (this._state.isRegex) {
                        stateChanges.searchString = escapeRegExpCharacters(selectionSearchString);
                    }
                    else {
                        stateChanges.searchString = selectionSearchString;
                    }
                }
            }
            else if (opts.seedSearchStringFromSelection === 'multiple' && !opts.updateSearchScope) {
                const selectionSearchString = getSelectionSearchString(this._editor, opts.seedSearchStringFromSelection);
                if (selectionSearchString) {
                    stateChanges.searchString = selectionSearchString;
                }
            }
            if (!stateChanges.searchString && opts.seedSearchStringFromGlobalClipboard) {
                const selectionSearchString = yield this.getGlobalBufferTerm();
                if (!this._editor.hasModel()) {
                    // the editor has lost its model in the meantime
                    return;
                }
                if (selectionSearchString) {
                    stateChanges.searchString = selectionSearchString;
                }
            }
            // Overwrite isReplaceRevealed
            if (opts.forceRevealReplace || stateChanges.isReplaceRevealed) {
                stateChanges.isReplaceRevealed = true;
            }
            else if (!this._findWidgetVisible.get()) {
                stateChanges.isReplaceRevealed = false;
            }
            if (opts.updateSearchScope) {
                const currentSelections = this._editor.getSelections();
                if (currentSelections.some(selection => !selection.isEmpty())) {
                    stateChanges.searchScope = currentSelections;
                }
            }
            stateChanges.loop = opts.loop;
            this._state.change(stateChanges, false);
            if (!this._model) {
                this._model = new FindModelBoundToEditorModel(this._editor, this._state);
            }
        });
    }
    start(opts, newState) {
        return this._start(opts, newState);
    }
    moveToNextMatch() {
        if (this._model) {
            this._model.moveToNextMatch();
            return true;
        }
        return false;
    }
    moveToPrevMatch() {
        if (this._model) {
            this._model.moveToPrevMatch();
            return true;
        }
        return false;
    }
    replace() {
        if (this._model) {
            this._model.replace();
            return true;
        }
        return false;
    }
    replaceAll() {
        if (this._model) {
            this._model.replaceAll();
            return true;
        }
        return false;
    }
    selectAllMatches() {
        if (this._model) {
            this._model.selectAllMatches();
            this._editor.focus();
            return true;
        }
        return false;
    }
    getGlobalBufferTerm() {
        return findController_awaiter(this, void 0, void 0, function* () {
            if (this._editor.getOption(37 /* EditorOption.find */).globalFindClipboard
                && this._editor.hasModel()
                && !this._editor.getModel().isTooLargeForSyncing()) {
                return this._clipboardService.readFindText();
            }
            return '';
        });
    }
    setGlobalBufferTerm(text) {
        if (this._editor.getOption(37 /* EditorOption.find */).globalFindClipboard
            && this._editor.hasModel()
            && !this._editor.getModel().isTooLargeForSyncing()) {
            // intentionally not awaited
            this._clipboardService.writeFindText(text);
        }
    }
};
CommonFindController.ID = 'editor.contrib.findController';
CommonFindController = findController_decorate([
    findController_param(1, IContextKeyService),
    findController_param(2, IStorageService),
    findController_param(3, IClipboardService)
], CommonFindController);

let findController_FindController = class FindController extends CommonFindController {
    constructor(editor, _contextViewService, _contextKeyService, _keybindingService, _themeService, _notificationService, _storageService, clipboardService) {
        super(editor, _contextKeyService, _storageService, clipboardService);
        this._contextViewService = _contextViewService;
        this._keybindingService = _keybindingService;
        this._themeService = _themeService;
        this._notificationService = _notificationService;
        this._widget = null;
        this._findOptionsWidget = null;
    }
    _start(opts, newState) {
        const _super = Object.create(null, {
            _start: { get: () => super._start }
        });
        return findController_awaiter(this, void 0, void 0, function* () {
            if (!this._widget) {
                this._createFindWidget();
            }
            const selection = this._editor.getSelection();
            let updateSearchScope = false;
            switch (this._editor.getOption(37 /* 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;
            yield _super._start.call(this, opts, newState);
            if (this._widget) {
                if (opts.shouldFocus === 2 /* FindStartFocusAction.FocusReplaceInput */) {
                    this._widget.focusReplaceInput();
                }
                else if (opts.shouldFocus === 1 /* FindStartFocusAction.FocusFindInput */) {
                    this._widget.focusFindInput();
                }
            }
        });
    }
    highlightFindOptions(ignoreWhenVisible = false) {
        if (!this._widget) {
            this._createFindWidget();
        }
        if (this._state.isRevealed && !ignoreWhenVisible) {
            this._widget.highlightFindOptions();
        }
        else {
            this._findOptionsWidget.highlightFindOptions();
        }
    }
    _createFindWidget() {
        this._widget = this._register(new findWidget_FindWidget(this._editor, this, this._state, this._contextViewService, this._keybindingService, this._contextKeyService, this._themeService, this._storageService, this._notificationService));
        this._findOptionsWidget = this._register(new FindOptionsWidget(this._editor, this._state, this._keybindingService, this._themeService));
    }
};
findController_FindController = findController_decorate([
    findController_param(1, IContextViewService),
    findController_param(2, IContextKeyService),
    findController_param(3, IKeybindingService),
    findController_param(4, IThemeService),
    findController_param(5, INotificationService),
    findController_param(6, IStorageService),
    findController_param(7, IClipboardService)
], findController_FindController);

const StartFindAction = registerMultiEditorAction(new MultiEditorAction({
    id: FIND_IDS.StartFindAction,
    label: localize('startFindAction', "Find"),
    alias: 'Find',
    precondition: ContextKeyExpr.or(EditorContextKeys.focus, ContextKeyExpr.has('editorIsOpen')),
    kbOpts: {
        kbExpr: null,
        primary: 2048 /* KeyMod.CtrlCmd */ | 36 /* KeyCode.KeyF */,
        weight: 100 /* KeybindingWeight.EditorContrib */
    },
    menuOpts: {
        menuId: MenuId.MenubarEditMenu,
        group: '3_find',
        title: localize({ key: 'miFind', comment: ['&& denotes a mnemonic'] }, "&&Find"),
        order: 1
    }
}));
StartFindAction.addImplementation(0, (accessor, editor, args) => {
    const controller = CommonFindController.get(editor);
    if (!controller) {
        return false;
    }
    return controller.start({
        forceRevealReplace: false,
        seedSearchStringFromSelection: editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
        seedSearchStringFromNonEmptySelection: editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection === 'selection',
        seedSearchStringFromGlobalClipboard: editor.getOption(37 /* EditorOption.find */).globalFindClipboard,
        shouldFocus: 1 /* FindStartFocusAction.FocusFindInput */,
        shouldAnimate: true,
        updateSearchScope: false,
        loop: editor.getOption(37 /* EditorOption.find */).loop
    });
});
const 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' },
                    regex: { type: 'boolean' },
                    regexOverride: {
                        type: 'number',
                        description: localize('actions.find.isRegexOverride', 'Overrides "Use Regular Expression" flag.\nThe flag will not be saved for the future.\n0: Do Nothing\n1: True\n2: False')
                    },
                    wholeWord: { type: 'boolean' },
                    wholeWordOverride: {
                        type: 'number',
                        description: localize('actions.find.wholeWordOverride', 'Overrides "Match Whole Word" flag.\nThe flag will not be saved for the future.\n0: Do Nothing\n1: True\n2: False')
                    },
                    matchCase: { type: 'boolean' },
                    matchCaseOverride: {
                        type: 'number',
                        description: localize('actions.find.matchCaseOverride', 'Overrides "Math Case" flag.\nThe flag will not be saved for the future.\n0: Do Nothing\n1: True\n2: False')
                    },
                    preserveCase: { type: 'boolean' },
                    preserveCaseOverride: {
                        type: 'number',
                        description: localize('actions.find.preserveCaseOverride', 'Overrides "Preserve Case" flag.\nThe flag will not be saved for the future.\n0: Do Nothing\n1: True\n2: False')
                    },
                    findInSelection: { type: 'boolean' },
                }
            }
        }]
};
class StartFindWithArgsAction extends EditorAction {
    constructor() {
        super({
            id: FIND_IDS.StartFindWithArgs,
            label: localize('startFindWithArgsAction', "Find With Arguments"),
            alias: 'Find With Arguments',
            precondition: undefined,
            kbOpts: {
                kbExpr: null,
                primary: 0,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            description: findArgDescription
        });
    }
    run(accessor, editor, args) {
        return findController_awaiter(this, void 0, void 0, function* () {
            const controller = CommonFindController.get(editor);
            if (controller) {
                const newState = args ? {
                    searchString: args.searchString,
                    replaceString: args.replaceString,
                    isReplaceRevealed: args.replaceString !== undefined,
                    isRegex: args.isRegex,
                    // isRegexOverride: args.regexOverride,
                    wholeWord: args.matchWholeWord,
                    // wholeWordOverride: args.wholeWordOverride,
                    matchCase: args.isCaseSensitive,
                    // matchCaseOverride: args.matchCaseOverride,
                    preserveCase: args.preserveCase,
                    // preserveCaseOverride: args.preserveCaseOverride,
                } : {};
                yield controller.start({
                    forceRevealReplace: false,
                    seedSearchStringFromSelection: (controller.getState().searchString.length === 0) && editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
                    seedSearchStringFromNonEmptySelection: editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection === 'selection',
                    seedSearchStringFromGlobalClipboard: true,
                    shouldFocus: 1 /* FindStartFocusAction.FocusFindInput */,
                    shouldAnimate: true,
                    updateSearchScope: (args === null || args === void 0 ? void 0 : args.findInSelection) || false,
                    loop: editor.getOption(37 /* EditorOption.find */).loop
                }, newState);
                controller.setGlobalBufferTerm(controller.getState().searchString);
            }
        });
    }
}
class StartFindWithSelectionAction extends EditorAction {
    constructor() {
        super({
            id: FIND_IDS.StartFindWithSelection,
            label: localize('startFindWithSelectionAction', "Find With Selection"),
            alias: 'Find With Selection',
            precondition: undefined,
            kbOpts: {
                kbExpr: null,
                primary: 0,
                mac: {
                    primary: 2048 /* KeyMod.CtrlCmd */ | 35 /* KeyCode.KeyE */,
                },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        return findController_awaiter(this, void 0, void 0, function* () {
            const controller = CommonFindController.get(editor);
            if (controller) {
                yield controller.start({
                    forceRevealReplace: false,
                    seedSearchStringFromSelection: 'multiple',
                    seedSearchStringFromNonEmptySelection: false,
                    seedSearchStringFromGlobalClipboard: false,
                    shouldFocus: 0 /* FindStartFocusAction.NoFocusChange */,
                    shouldAnimate: true,
                    updateSearchScope: false,
                    loop: editor.getOption(37 /* EditorOption.find */).loop
                });
                controller.setGlobalBufferTerm(controller.getState().searchString);
            }
        });
    }
}
class MatchFindAction extends EditorAction {
    run(accessor, editor) {
        return findController_awaiter(this, void 0, void 0, function* () {
            const controller = CommonFindController.get(editor);
            if (controller && !this._run(controller)) {
                yield controller.start({
                    forceRevealReplace: false,
                    seedSearchStringFromSelection: (controller.getState().searchString.length === 0) && editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
                    seedSearchStringFromNonEmptySelection: editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection === 'selection',
                    seedSearchStringFromGlobalClipboard: true,
                    shouldFocus: 0 /* FindStartFocusAction.NoFocusChange */,
                    shouldAnimate: true,
                    updateSearchScope: false,
                    loop: editor.getOption(37 /* EditorOption.find */).loop
                });
                this._run(controller);
            }
        });
    }
}
class NextMatchFindAction extends MatchFindAction {
    constructor() {
        super({
            id: FIND_IDS.NextMatchFindAction,
            label: localize('findNextMatchAction', "Find Next"),
            alias: 'Find Next',
            precondition: undefined,
            kbOpts: [{
                    kbExpr: EditorContextKeys.focus,
                    primary: 61 /* KeyCode.F3 */,
                    mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 37 /* KeyCode.KeyG */, secondary: [61 /* KeyCode.F3 */] },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }, {
                    kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_FIND_INPUT_FOCUSED),
                    primary: 3 /* KeyCode.Enter */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }]
        });
    }
    _run(controller) {
        const result = controller.moveToNextMatch();
        if (result) {
            controller.editor.pushUndoStop();
            return true;
        }
        return false;
    }
}
class PreviousMatchFindAction extends MatchFindAction {
    constructor() {
        super({
            id: FIND_IDS.PreviousMatchFindAction,
            label: localize('findPreviousMatchAction', "Find Previous"),
            alias: 'Find Previous',
            precondition: undefined,
            kbOpts: [{
                    kbExpr: EditorContextKeys.focus,
                    primary: 1024 /* KeyMod.Shift */ | 61 /* KeyCode.F3 */,
                    mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 37 /* KeyCode.KeyG */, secondary: [1024 /* KeyMod.Shift */ | 61 /* KeyCode.F3 */] },
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }, {
                    kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_FIND_INPUT_FOCUSED),
                    primary: 1024 /* KeyMod.Shift */ | 3 /* KeyCode.Enter */,
                    weight: 100 /* KeybindingWeight.EditorContrib */
                }
            ]
        });
    }
    _run(controller) {
        return controller.moveToPrevMatch();
    }
}
class SelectionMatchFindAction extends EditorAction {
    run(accessor, editor) {
        return findController_awaiter(this, void 0, void 0, function* () {
            const controller = CommonFindController.get(editor);
            if (!controller) {
                return;
            }
            const seedSearchStringFromNonEmptySelection = editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection === 'selection';
            let selectionSearchString = null;
            if (editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection !== 'never') {
                selectionSearchString = getSelectionSearchString(editor, 'single', seedSearchStringFromNonEmptySelection);
            }
            if (selectionSearchString) {
                controller.setSearchString(selectionSearchString);
            }
            if (!this._run(controller)) {
                yield controller.start({
                    forceRevealReplace: false,
                    seedSearchStringFromSelection: editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection !== 'never' ? 'single' : 'none',
                    seedSearchStringFromNonEmptySelection: seedSearchStringFromNonEmptySelection,
                    seedSearchStringFromGlobalClipboard: false,
                    shouldFocus: 0 /* FindStartFocusAction.NoFocusChange */,
                    shouldAnimate: true,
                    updateSearchScope: false,
                    loop: editor.getOption(37 /* EditorOption.find */).loop
                });
                this._run(controller);
            }
        });
    }
}
class NextSelectionMatchFindAction extends SelectionMatchFindAction {
    constructor() {
        super({
            id: FIND_IDS.NextSelectionMatchFindAction,
            label: localize('nextSelectionMatchFindAction', "Find Next Selection"),
            alias: 'Find Next Selection',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 61 /* KeyCode.F3 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    _run(controller) {
        return controller.moveToNextMatch();
    }
}
class PreviousSelectionMatchFindAction extends SelectionMatchFindAction {
    constructor() {
        super({
            id: FIND_IDS.PreviousSelectionMatchFindAction,
            label: localize('previousSelectionMatchFindAction', "Find Previous Selection"),
            alias: 'Find Previous Selection',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 61 /* KeyCode.F3 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    _run(controller) {
        return controller.moveToPrevMatch();
    }
}
const StartFindReplaceAction = registerMultiEditorAction(new MultiEditorAction({
    id: FIND_IDS.StartFindReplaceAction,
    label: localize('startReplace', "Replace"),
    alias: 'Replace',
    precondition: ContextKeyExpr.or(EditorContextKeys.focus, ContextKeyExpr.has('editorIsOpen')),
    kbOpts: {
        kbExpr: null,
        primary: 2048 /* KeyMod.CtrlCmd */ | 38 /* KeyCode.KeyH */,
        mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 36 /* KeyCode.KeyF */ },
        weight: 100 /* KeybindingWeight.EditorContrib */
    },
    menuOpts: {
        menuId: MenuId.MenubarEditMenu,
        group: '3_find',
        title: localize({ key: 'miReplace', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
        order: 2
    }
}));
StartFindReplaceAction.addImplementation(0, (accessor, editor, args) => {
    if (!editor.hasModel() || editor.getOption(83 /* EditorOption.readOnly */)) {
        return false;
    }
    const controller = CommonFindController.get(editor);
    if (!controller) {
        return false;
    }
    const currentSelection = editor.getSelection();
    const findInputFocused = controller.isFindInputFocused();
    // we only seed search string from selection when the current selection is single line and not empty,
    // + the find input is not focused
    const seedSearchStringFromSelection = !currentSelection.isEmpty()
        && currentSelection.startLineNumber === currentSelection.endLineNumber
        && (editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection !== 'never')
        && !findInputFocused;
    /*
    * if the existing search string in find widget is empty and we don't seed search string from selection, it means the Find Input is still empty, so we should focus the Find Input instead of Replace Input.

    * findInputFocused true -> seedSearchStringFromSelection false, FocusReplaceInput
    * findInputFocused false, seedSearchStringFromSelection true FocusReplaceInput
    * findInputFocused false seedSearchStringFromSelection false FocusFindInput
    */
    const shouldFocus = (findInputFocused || seedSearchStringFromSelection) ?
        2 /* FindStartFocusAction.FocusReplaceInput */ : 1 /* FindStartFocusAction.FocusFindInput */;
    return controller.start({
        forceRevealReplace: true,
        seedSearchStringFromSelection: seedSearchStringFromSelection ? 'single' : 'none',
        seedSearchStringFromNonEmptySelection: editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection === 'selection',
        seedSearchStringFromGlobalClipboard: editor.getOption(37 /* EditorOption.find */).seedSearchStringFromSelection !== 'never',
        shouldFocus: shouldFocus,
        shouldAnimate: true,
        updateSearchScope: false,
        loop: editor.getOption(37 /* EditorOption.find */).loop
    });
});
registerEditorContribution(CommonFindController.ID, findController_FindController);
registerEditorAction(StartFindWithArgsAction);
registerEditorAction(StartFindWithSelectionAction);
registerEditorAction(NextMatchFindAction);
registerEditorAction(PreviousMatchFindAction);
registerEditorAction(NextSelectionMatchFindAction);
registerEditorAction(PreviousSelectionMatchFindAction);
const FindCommand = EditorCommand.bindToContribution(CommonFindController.get);
registerEditorCommand(new FindCommand({
    id: FIND_IDS.CloseFindWidgetCommand,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: x => x.closeFindWidget(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
        kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, ContextKeyExpr.not('isComposing')),
        primary: 9 /* KeyCode.Escape */,
        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
    }
}));
registerEditorCommand(new FindCommand({
    id: FIND_IDS.ToggleCaseSensitiveCommand,
    precondition: undefined,
    handler: x => x.toggleCaseSensitive(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
        kbExpr: EditorContextKeys.focus,
        primary: ToggleCaseSensitiveKeybinding.primary,
        mac: ToggleCaseSensitiveKeybinding.mac,
        win: ToggleCaseSensitiveKeybinding.win,
        linux: ToggleCaseSensitiveKeybinding.linux
    }
}));
registerEditorCommand(new FindCommand({
    id: FIND_IDS.ToggleWholeWordCommand,
    precondition: undefined,
    handler: x => x.toggleWholeWords(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
        kbExpr: EditorContextKeys.focus,
        primary: ToggleWholeWordKeybinding.primary,
        mac: ToggleWholeWordKeybinding.mac,
        win: ToggleWholeWordKeybinding.win,
        linux: ToggleWholeWordKeybinding.linux
    }
}));
registerEditorCommand(new FindCommand({
    id: FIND_IDS.ToggleRegexCommand,
    precondition: undefined,
    handler: x => x.toggleRegex(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
        kbExpr: EditorContextKeys.focus,
        primary: ToggleRegexKeybinding.primary,
        mac: ToggleRegexKeybinding.mac,
        win: ToggleRegexKeybinding.win,
        linux: ToggleRegexKeybinding.linux
    }
}));
registerEditorCommand(new FindCommand({
    id: FIND_IDS.ToggleSearchScopeCommand,
    precondition: undefined,
    handler: x => x.toggleSearchScope(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
        kbExpr: EditorContextKeys.focus,
        primary: ToggleSearchScopeKeybinding.primary,
        mac: ToggleSearchScopeKeybinding.mac,
        win: ToggleSearchScopeKeybinding.win,
        linux: ToggleSearchScopeKeybinding.linux
    }
}));
registerEditorCommand(new FindCommand({
    id: FIND_IDS.TogglePreserveCaseCommand,
    precondition: undefined,
    handler: x => x.togglePreserveCase(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
        kbExpr: EditorContextKeys.focus,
        primary: TogglePreserveCaseKeybinding.primary,
        mac: TogglePreserveCaseKeybinding.mac,
        win: TogglePreserveCaseKeybinding.win,
        linux: TogglePreserveCaseKeybinding.linux
    }
}));
registerEditorCommand(new FindCommand({
    id: FIND_IDS.ReplaceOneAction,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: x => x.replace(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
        kbExpr: EditorContextKeys.focus,
        primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 22 /* KeyCode.Digit1 */
    }
}));
registerEditorCommand(new FindCommand({
    id: FIND_IDS.ReplaceOneAction,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: x => x.replace(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
        kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_REPLACE_INPUT_FOCUSED),
        primary: 3 /* KeyCode.Enter */
    }
}));
registerEditorCommand(new FindCommand({
    id: FIND_IDS.ReplaceAllAction,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: x => x.replaceAll(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
        kbExpr: EditorContextKeys.focus,
        primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 3 /* KeyCode.Enter */
    }
}));
registerEditorCommand(new FindCommand({
    id: FIND_IDS.ReplaceAllAction,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: x => x.replaceAll(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
        kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_REPLACE_INPUT_FOCUSED),
        primary: undefined,
        mac: {
            primary: 2048 /* KeyMod.CtrlCmd */ | 3 /* KeyCode.Enter */,
        }
    }
}));
registerEditorCommand(new FindCommand({
    id: FIND_IDS.SelectAllMatchesAction,
    precondition: CONTEXT_FIND_WIDGET_VISIBLE,
    handler: x => x.selectAllMatches(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 5,
        kbExpr: EditorContextKeys.focus,
        primary: 512 /* KeyMod.Alt */ | 3 /* KeyCode.Enter */
    }
}));

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/folding/browser/folding.css
var folding = __webpack_require__(45018);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/folding/browser/folding.css

      
      
      
      
      
      
      
      
      

var folding_options = {};

folding_options.styleTagTransform = (styleTagTransform_default());
folding_options.setAttributes = (setAttributesWithoutAttributes_default());

      folding_options.insert = insertBySelector_default().bind(null, "head");
    
folding_options.domAPI = (styleDomAPI_default());
folding_options.insertStyleElement = (insertStyleElement_default());

var folding_update = injectStylesIntoStyleTag_default()(folding/* default */.A, folding_options);




       /* harmony default export */ const browser_folding = (folding/* default */.A && folding/* default */.A.locals ? folding/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/folding/browser/foldingRanges.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
const MAX_FOLDING_REGIONS = 0xFFFF;
const MAX_LINE_NUMBER = 0xFFFFFF;
const MASK_INDENT = 0xFF000000;
class BitField {
    constructor(size) {
        const numWords = Math.ceil(size / 32);
        this._states = new Uint32Array(numWords);
    }
    get(index) {
        const arrayIndex = (index / 32) | 0;
        const bit = index % 32;
        return (this._states[arrayIndex] & (1 << bit)) !== 0;
    }
    set(index, newState) {
        const arrayIndex = (index / 32) | 0;
        const bit = index % 32;
        const value = this._states[arrayIndex];
        if (newState) {
            this._states[arrayIndex] = value | (1 << bit);
        }
        else {
            this._states[arrayIndex] = value & ~(1 << bit);
        }
    }
}
class FoldingRegions {
    constructor(startIndexes, endIndexes, types) {
        this.sourceAbbr = {
            [0 /* FoldSource.provider */]: ' ',
            [1 /* FoldSource.userDefined */]: 'u',
            [2 /* FoldSource.recovered */]: 'r',
        };
        if (startIndexes.length !== endIndexes.length || startIndexes.length > MAX_FOLDING_REGIONS) {
            throw new Error('invalid startIndexes or endIndexes size');
        }
        this._startIndexes = startIndexes;
        this._endIndexes = endIndexes;
        this._collapseStates = new BitField(startIndexes.length);
        this._userDefinedStates = new BitField(startIndexes.length);
        this._recoveredStates = new BitField(startIndexes.length);
        this._types = types;
        this._parentsComputed = false;
    }
    ensureParentIndices() {
        if (!this._parentsComputed) {
            this._parentsComputed = true;
            const parentIndexes = [];
            const isInsideLast = (startLineNumber, endLineNumber) => {
                const index = parentIndexes[parentIndexes.length - 1];
                return this.getStartLineNumber(index) <= startLineNumber && this.getEndLineNumber(index) >= endLineNumber;
            };
            for (let i = 0, len = this._startIndexes.length; i < len; i++) {
                const startLineNumber = this._startIndexes[i];
                const endLineNumber = this._endIndexes[i];
                if (startLineNumber > MAX_LINE_NUMBER || endLineNumber > MAX_LINE_NUMBER) {
                    throw new Error('startLineNumber or endLineNumber must not exceed ' + MAX_LINE_NUMBER);
                }
                while (parentIndexes.length > 0 && !isInsideLast(startLineNumber, endLineNumber)) {
                    parentIndexes.pop();
                }
                const parentIndex = parentIndexes.length > 0 ? parentIndexes[parentIndexes.length - 1] : -1;
                parentIndexes.push(i);
                this._startIndexes[i] = startLineNumber + ((parentIndex & 0xFF) << 24);
                this._endIndexes[i] = endLineNumber + ((parentIndex & 0xFF00) << 16);
            }
        }
    }
    get length() {
        return this._startIndexes.length;
    }
    getStartLineNumber(index) {
        return this._startIndexes[index] & MAX_LINE_NUMBER;
    }
    getEndLineNumber(index) {
        return this._endIndexes[index] & MAX_LINE_NUMBER;
    }
    getType(index) {
        return this._types ? this._types[index] : undefined;
    }
    hasTypes() {
        return !!this._types;
    }
    isCollapsed(index) {
        return this._collapseStates.get(index);
    }
    setCollapsed(index, newState) {
        this._collapseStates.set(index, newState);
    }
    isUserDefined(index) {
        return this._userDefinedStates.get(index);
    }
    setUserDefined(index, newState) {
        return this._userDefinedStates.set(index, newState);
    }
    isRecovered(index) {
        return this._recoveredStates.get(index);
    }
    setRecovered(index, newState) {
        return this._recoveredStates.set(index, newState);
    }
    getSource(index) {
        if (this.isUserDefined(index)) {
            return 1 /* FoldSource.userDefined */;
        }
        else if (this.isRecovered(index)) {
            return 2 /* FoldSource.recovered */;
        }
        return 0 /* FoldSource.provider */;
    }
    setSource(index, source) {
        if (source === 1 /* FoldSource.userDefined */) {
            this.setUserDefined(index, true);
            this.setRecovered(index, false);
        }
        else if (source === 2 /* FoldSource.recovered */) {
            this.setUserDefined(index, false);
            this.setRecovered(index, true);
        }
        else {
            this.setUserDefined(index, false);
            this.setRecovered(index, false);
        }
    }
    setCollapsedAllOfType(type, newState) {
        let hasChanged = false;
        if (this._types) {
            for (let i = 0; i < this._types.length; i++) {
                if (this._types[i] === type) {
                    this.setCollapsed(i, newState);
                    hasChanged = true;
                }
            }
        }
        return hasChanged;
    }
    toRegion(index) {
        return new FoldingRegion(this, index);
    }
    getParentIndex(index) {
        this.ensureParentIndices();
        const parent = ((this._startIndexes[index] & MASK_INDENT) >>> 24) + ((this._endIndexes[index] & MASK_INDENT) >>> 16);
        if (parent === MAX_FOLDING_REGIONS) {
            return -1;
        }
        return parent;
    }
    contains(index, line) {
        return this.getStartLineNumber(index) <= line && this.getEndLineNumber(index) >= line;
    }
    findIndex(line) {
        let low = 0, high = this._startIndexes.length;
        if (high === 0) {
            return -1; // no children
        }
        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.findIndex(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 i = 0; i < this.length; i++) {
            res[i] = `[${this.sourceAbbr[this.getSource(i)]}${this.isCollapsed(i) ? '+' : '-'}] ${this.getStartLineNumber(i)}/${this.getEndLineNumber(i)}`;
        }
        return res.join(', ');
    }
    toFoldRange(index) {
        return {
            startLineNumber: this._startIndexes[index] & MAX_LINE_NUMBER,
            endLineNumber: this._endIndexes[index] & MAX_LINE_NUMBER,
            type: this._types ? this._types[index] : undefined,
            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 i = 0; i < rangesLength; i++) {
            const range = ranges[i];
            startIndexes[i] = range.startLineNumber;
            endIndexes[i] = range.endLineNumber;
            types.push(range.type);
            if (range.type) {
                gotTypes = true;
            }
        }
        if (!gotTypes) {
            types = undefined;
        }
        const regions = new FoldingRegions(startIndexes, endIndexes, types);
        for (let i = 0; i < rangesLength; i++) {
            if (ranges[i].isCollapsed) {
                regions.setCollapsed(i, true);
            }
            regions.setSource(i, ranges[i].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) {
        maxLineNumber = maxLineNumber !== null && maxLineNumber !== void 0 ? maxLineNumber : Number.MAX_VALUE;
        const getIndexedFunction = (r, limit) => {
            return Array.isArray(r)
                ? ((i) => { return (i < limit) ? r[i] : undefined; })
                : ((i) => { return (i < limit) ? r.toFoldRange(i) : undefined; });
        };
        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 = undefined;
            if (nextB && (!nextA || nextA.startLineNumber >= nextB.startLineNumber)) {
                if (nextA && nextA.startLineNumber === nextB.startLineNumber) {
                    if (nextB.source === 1 /* FoldSource.userDefined */) {
                        // a user defined range (possibly unfolded)
                        useRange = nextB;
                    }
                    else {
                        // a previously folded range or a (possibly unfolded) recovered range
                        useRange = nextA;
                        useRange.isCollapsed = nextB.isCollapsed && nextA.endLineNumber === nextB.endLineNumber;
                        useRange.source = 0 /* FoldSource.provider */;
                    }
                    nextA = getA(++indexA); // not necessary, just for speed
                }
                else {
                    useRange = nextB;
                    if (nextB.isCollapsed && nextB.source === 0 /* FoldSource.provider */) {
                        // a previously collapsed range
                        useRange.source = 2 /* FoldSource.recovered */;
                    }
                }
                nextB = getB(++indexB);
            }
            else {
                // nextA is next. The user folded B set takes precedence and we sometimes need to look
                // ahead in it to check for an upcoming conflict.
                let scanIndex = indexB;
                let prescanB = nextB;
                while (true) {
                    if (!prescanB || prescanB.startLineNumber > nextA.endLineNumber) {
                        useRange = nextA;
                        break; // no conflict, use this nextA
                    }
                    if (prescanB.source === 1 /* FoldSource.userDefined */ && prescanB.endLineNumber > nextA.endLineNumber) {
                        // we found a user folded range, it wins
                        break; // without setting nextResult, so this nextA gets skipped
                    }
                    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;
    }
}
class FoldingRegion {
    constructor(ranges, index) {
        this.ranges = ranges;
        this.index = index;
    }
    get startLineNumber() {
        return this.ranges.getStartLineNumber(this.index);
    }
    get endLineNumber() {
        return this.ranges.getEndLineNumber(this.index);
    }
    get regionIndex() {
        return this.index;
    }
    get parentIndex() {
        return this.ranges.getParentIndex(this.index);
    }
    get isCollapsed() {
        return this.ranges.isCollapsed(this.index);
    }
    containedBy(range) {
        return range.startLineNumber <= this.startLineNumber && range.endLineNumber >= this.endLineNumber;
    }
    containsLine(lineNumber) {
        return this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/folding/browser/foldingModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class FoldingModel {
    constructor(textModel, decorationProvider) {
        this._updateEventEmitter = new Emitter();
        this.onDidChange = this._updateEventEmitter.event;
        this._textModel = textModel;
        this._decorationProvider = decorationProvider;
        this._regions = new FoldingRegions(new Uint32Array(0), new Uint32Array(0));
        this._editorDecorationIds = [];
    }
    get regions() { return this._regions; }
    get textModel() { return this._textModel; }
    toggleCollapseState(toggledRegions) {
        if (!toggledRegions.length) {
            return;
        }
        toggledRegions = toggledRegions.sort((r1, r2) => r1.regionIndex - r2.regionIndex);
        const processed = {};
        this._decorationProvider.changeDecorations(accessor => {
            let k = 0; // index from [0 ... this.regions.length]
            let dirtyRegionEndLine = -1; // end of the range where decorations need to be updated
            let lastHiddenLine = -1; // the end of the last hidden lines
            const updateDecorationsUntil = (index) => {
                while (k < index) {
                    const endLineNumber = this._regions.getEndLineNumber(k);
                    const isCollapsed = this._regions.isCollapsed(k);
                    if (endLineNumber <= dirtyRegionEndLine) {
                        const isManual = this.regions.getSource(k) !== 0 /* FoldSource.provider */;
                        accessor.changeDecorationOptions(this._editorDecorationIds[k], this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual));
                    }
                    if (isCollapsed && endLineNumber > lastHiddenLine) {
                        lastHiddenLine = endLineNumber;
                    }
                    k++;
                }
            };
            for (const region of toggledRegions) {
                const index = region.regionIndex;
                const editorDecorationId = this._editorDecorationIds[index];
                if (editorDecorationId && !processed[editorDecorationId]) {
                    processed[editorDecorationId] = true;
                    updateDecorationsUntil(index); // update all decorations up to current index using the old dirtyRegionEndLine
                    const newCollapseState = !this._regions.isCollapsed(index);
                    this._regions.setCollapsed(index, newCollapseState);
                    dirtyRegionEndLine = Math.max(dirtyRegionEndLine, this._regions.getEndLineNumber(index));
                }
            }
            updateDecorationsUntil(this._regions.length);
        });
        this._updateEventEmitter.fire({ model: this, collapseStateChanged: toggledRegions });
    }
    removeManualRanges(ranges) {
        const newFoldingRanges = new Array();
        const intersects = (foldRange) => {
            for (const range of ranges) {
                if (!(range.startLineNumber > foldRange.endLineNumber || foldRange.startLineNumber > range.endLineNumber)) {
                    return true;
                }
            }
            return false;
        };
        for (let i = 0; i < this._regions.length; i++) {
            const foldRange = this._regions.toFoldRange(i);
            if (foldRange.source === 0 /* FoldSource.provider */ || !intersects(foldRange)) {
                newFoldingRanges.push(foldRange);
            }
        }
        this.updatePost(FoldingRegions.fromFoldRanges(newFoldingRanges));
    }
    update(newRegions, blockedLineNumers = []) {
        const foldedOrManualRanges = this._currentFoldedOrManualRanges(blockedLineNumers);
        const newRanges = FoldingRegions.sanitizeAndMerge(newRegions, foldedOrManualRanges, this._textModel.getLineCount());
        this.updatePost(FoldingRegions.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 /* FoldSource.provider */;
            const decorationRange = {
                startLineNumber: startLineNumber,
                startColumn: this._textModel.getLineMaxColumn(startLineNumber),
                endLineNumber: endLineNumber,
                endColumn: this._textModel.getLineMaxColumn(endLineNumber) + 1
            };
            newEditorDecorations.push({ range: decorationRange, options: this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual) });
            if (isCollapsed && endLineNumber > lastHiddenLine) {
                lastHiddenLine = endLineNumber;
            }
        }
        this._decorationProvider.changeDecorations(accessor => this._editorDecorationIds = accessor.deltaDecorations(this._editorDecorationIds, newEditorDecorations));
        this._regions = newRegions;
        this._updateEventEmitter.fire({ model: this });
    }
    _currentFoldedOrManualRanges(blockedLineNumers = []) {
        const isBlocked = (startLineNumber, endLineNumber) => {
            for (const blockedLineNumber of blockedLineNumers) {
                if (startLineNumber < blockedLineNumber && blockedLineNumber <= endLineNumber) { // first line is visible
                    return true;
                }
            }
            return false;
        };
        const foldedRanges = [];
        for (let i = 0, limit = this._regions.length; i < limit; i++) {
            let isCollapsed = this.regions.isCollapsed(i);
            const source = this.regions.getSource(i);
            if (isCollapsed || source !== 0 /* FoldSource.provider */) {
                const foldRange = this._regions.toFoldRange(i);
                const decRange = this._textModel.getDecorationRange(this._editorDecorationIds[i]);
                if (decRange) {
                    if (isCollapsed && (isBlocked(decRange.startLineNumber, decRange.endLineNumber) || decRange.endLineNumber - decRange.startLineNumber !== foldRange.endLineNumber - foldRange.startLineNumber)) {
                        isCollapsed = false; // uncollapse is the range is blocked or there has been lines removed or added
                    }
                    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._currentFoldedOrManualRanges();
        const result = [];
        for (let i = 0, limit = foldedOrManualRanges.length; i < limit; i++) {
            const range = foldedOrManualRanges[i];
            const checksum = this._getLinesChecksum(range.startLineNumber + 1, range.endLineNumber);
            result.push({
                startLineNumber: range.startLineNumber,
                endLineNumber: range.endLineNumber,
                isCollapsed: range.isCollapsed,
                source: range.source,
                checksum: checksum
            });
        }
        return (result.length > 0) ? result : undefined;
    }
    /**
     * Apply persisted state, for persistence only
     */
    applyMemento(state) {
        var _a, _b;
        if (!Array.isArray(state)) {
            return;
        }
        const rangesToRestore = [];
        const maxLineNumber = this._textModel.getLineCount();
        for (const range of state) {
            if (range.startLineNumber >= range.endLineNumber || range.startLineNumber < 1 || range.endLineNumber > maxLineNumber) {
                continue;
            }
            const checksum = this._getLinesChecksum(range.startLineNumber + 1, range.endLineNumber);
            if (!range.checksum || checksum === range.checksum) {
                rangesToRestore.push({
                    startLineNumber: range.startLineNumber,
                    endLineNumber: range.endLineNumber,
                    type: undefined,
                    isCollapsed: (_a = range.isCollapsed) !== null && _a !== void 0 ? _a : true,
                    source: (_b = range.source) !== null && _b !== void 0 ? _b : 0 /* FoldSource.provider */
                });
            }
        }
        const newRanges = FoldingRegions.sanitizeAndMerge(this._regions, rangesToRestore, maxLineNumber);
        this.updatePost(FoldingRegions.fromFoldRanges(newRanges));
    }
    _getLinesChecksum(lineNumber1, lineNumber2) {
        const h = hash(this._textModel.getLineContent(lineNumber1)
            + this._textModel.getLineContent(lineNumber2));
        return h % 1000000; // 6 digits is plenty
    }
    dispose() {
        this._decorationProvider.removeDecorations(this._editorDecorationIds);
    }
    getAllRegionsAtLine(lineNumber, filter) {
        const result = [];
        if (this._regions) {
            let index = this._regions.findRange(lineNumber);
            let level = 1;
            while (index >= 0) {
                const current = this._regions.toRegion(index);
                if (!filter || filter(current, level)) {
                    result.push(current);
                }
                level++;
                index = current.parentIndex;
            }
        }
        return result;
    }
    getRegionAtLine(lineNumber) {
        if (this._regions) {
            const index = this._regions.findRange(lineNumber);
            if (index >= 0) {
                return this._regions.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 i = index, len = this._regions.length; i < len; i++) {
                const current = this._regions.toRegion(i);
                if (this._regions.getStartLineNumber(i) < 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 i = index, len = this._regions.length; i < len; i++) {
                const current = this._regions.toRegion(i);
                if (this._regions.getStartLineNumber(i) < endLineNumber) {
                    if (!filter || filter(current)) {
                        result.push(current);
                    }
                }
                else {
                    break;
                }
            }
        }
        return result;
    }
}
/**
 * Collapse or expand the regions at the given locations
 * @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
 * @param lineNumbers the location of the regions to collapse or expand, or if not set, all regions in the model.
 */
function toggleCollapseState(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, (r, level) => r.isCollapsed !== doCollapse && level < levels);
                toToggle.push(...regionsInside);
            }
        }
    }
    foldingModel.toggleCollapseState(toToggle);
}
/**
 * Collapse or expand the regions at the given locations including all children.
 * @param doCollapse Whether to collapse or expand
 * @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
 * @param lineNumbers the location of the regions to collapse or expand, or if not set, all regions in the model.
 */
function setCollapseStateLevelsDown(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, (r, level) => r.isCollapsed !== doCollapse && level < levels);
                    toToggle.push(...regionsInside);
                }
            }
        }
    }
    else {
        const regionsInside = foldingModel.getRegionsInside(null, (r, level) => r.isCollapsed !== doCollapse && level < levels);
        toToggle.push(...regionsInside);
    }
    foldingModel.toggleCollapseState(toToggle);
}
/**
 * Collapse or expand the regions at the given locations including all parents.
 * @param doCollapse Whether to collapse or expand
 * @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels.
 * @param lineNumbers the location of the regions to collapse or expand.
 */
function setCollapseStateLevelsUp(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);
}
/**
 * Collapse or expand a region at the given locations. If the inner most region is already collapsed/expanded, uses the first parent instead.
 * @param doCollapse Whether to collapse or expand
 * @param lineNumbers the location of the regions to collapse or expand.
 */
function setCollapseStateUp(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);
}
/**
 * Folds or unfolds all regions that have a given level, except if they contain one of the blocked lines.
 * @param foldLevel level. Level == 1 is the top level
 * @param doCollapse Whether to collapse or expand
*/
function setCollapseStateAtLevel(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);
}
/**
 * Folds or unfolds all regions, except if they contain or are contained by a region of one of the blocked lines.
 * @param doCollapse Whether to collapse or expand
 * @param blockedLineNumbers the location of regions to not collapse or expand
 */
function setCollapseStateForRest(foldingModel, doCollapse, blockedLineNumbers) {
    const filteredRegions = [];
    for (const lineNumber of blockedLineNumbers) {
        const regions = foldingModel.getAllRegionsAtLine(lineNumber, undefined);
        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);
}
/**
 * Folds all regions for which the lines start with a given regex
 * @param foldingModel the folding model
 */
function setCollapseStateForMatchingLines(foldingModel, regExp, doCollapse) {
    const editorModel = foldingModel.textModel;
    const regions = foldingModel.regions;
    const toToggle = [];
    for (let i = regions.length - 1; i >= 0; i--) {
        if (doCollapse !== regions.isCollapsed(i)) {
            const startLineNumber = regions.getStartLineNumber(i);
            if (regExp.test(editorModel.getLineContent(startLineNumber))) {
                toToggle.push(regions.toRegion(i));
            }
        }
    }
    foldingModel.toggleCollapseState(toToggle);
}
/**
 * Folds all regions of the given type
 * @param foldingModel the folding model
 */
function setCollapseStateForType(foldingModel, type, doCollapse) {
    const regions = foldingModel.regions;
    const toToggle = [];
    for (let i = regions.length - 1; i >= 0; i--) {
        if (doCollapse !== regions.isCollapsed(i) && type === regions.getType(i)) {
            toToggle.push(regions.toRegion(i));
        }
    }
    foldingModel.toggleCollapseState(toToggle);
}
/**
 * Get line to go to for parent fold of current line
 * @param lineNumber the current line number
 * @param foldingModel the folding model
 *
 * @return Parent fold start line
 */
function getParentFoldLine(lineNumber, foldingModel) {
    let startLineNumber = null;
    const foldingRegion = foldingModel.getRegionAtLine(lineNumber);
    if (foldingRegion !== null) {
        startLineNumber = foldingRegion.startLineNumber;
        // If current line is not the start of the current fold, go to top line of current fold. If not, go to parent fold
        if (lineNumber === startLineNumber) {
            const parentFoldingIdx = foldingRegion.parentIndex;
            if (parentFoldingIdx !== -1) {
                startLineNumber = foldingModel.regions.getStartLineNumber(parentFoldingIdx);
            }
            else {
                startLineNumber = null;
            }
        }
    }
    return startLineNumber;
}
/**
 * Get line to go to for previous fold at the same level of current line
 * @param lineNumber the current line number
 * @param foldingModel the folding model
 *
 * @return Previous fold start line
 */
function getPreviousFoldLine(lineNumber, foldingModel) {
    let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
    // If on the folding range start line, go to previous sibling.
    if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
        // If current line is not the start of the current fold, go to top line of current fold. If not, go to previous fold.
        if (lineNumber !== foldingRegion.startLineNumber) {
            return foldingRegion.startLineNumber;
        }
        else {
            // Find min line number to stay within parent.
            const expectedParentIndex = foldingRegion.parentIndex;
            let minLineNumber = 0;
            if (expectedParentIndex !== -1) {
                minLineNumber = foldingModel.regions.getStartLineNumber(foldingRegion.parentIndex);
            }
            // Find fold at same level.
            while (foldingRegion !== null) {
                if (foldingRegion.regionIndex > 0) {
                    foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
                    // Keep at same level.
                    if (foldingRegion.startLineNumber <= minLineNumber) {
                        return null;
                    }
                    else if (foldingRegion.parentIndex === expectedParentIndex) {
                        return foldingRegion.startLineNumber;
                    }
                }
                else {
                    return null;
                }
            }
        }
    }
    else {
        // Go to last fold that's before the current line.
        if (foldingModel.regions.length > 0) {
            foldingRegion = foldingModel.regions.toRegion(foldingModel.regions.length - 1);
            while (foldingRegion !== null) {
                // Found fold before current line.
                if (foldingRegion.startLineNumber < lineNumber) {
                    return foldingRegion.startLineNumber;
                }
                if (foldingRegion.regionIndex > 0) {
                    foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
                }
                else {
                    foldingRegion = null;
                }
            }
        }
    }
    return null;
}
/**
 * Get line to go to next fold at the same level of current line
 * @param lineNumber the current line number
 * @param foldingModel the folding model
 *
 * @return Next fold start line
 */
function getNextFoldLine(lineNumber, foldingModel) {
    let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
    // If on the folding range start line, go to next sibling.
    if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
        // Find max line number to stay within parent.
        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);
        }
        // Find fold at same level.
        while (foldingRegion !== null) {
            if (foldingRegion.regionIndex < foldingModel.regions.length) {
                foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1);
                // Keep at same level.
                if (foldingRegion.startLineNumber >= maxLineNumber) {
                    return null;
                }
                else if (foldingRegion.parentIndex === expectedParentIndex) {
                    return foldingRegion.startLineNumber;
                }
            }
            else {
                return null;
            }
        }
    }
    else {
        // Go to first fold that's after the current line.
        if (foldingModel.regions.length > 0) {
            foldingRegion = foldingModel.regions.toRegion(0);
            while (foldingRegion !== null) {
                // Found fold after current line.
                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;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/folding/browser/hiddenRangeModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class HiddenRangeModel {
    constructor(model) {
        this._updateEventEmitter = new Emitter();
        this._hasLineChanges = false;
        this._foldingModel = model;
        this._foldingModelListener = model.onDidChange(_ => this.updateHiddenRanges());
        this._hiddenRanges = [];
        if (model.regions.length) {
            this.updateHiddenRanges();
        }
    }
    get onDidChange() { return this._updateEventEmitter.event; }
    get hiddenRanges() { return this._hiddenRanges; }
    notifyChangeModelContent(e) {
        if (this._hiddenRanges.length && !this._hasLineChanges) {
            this._hasLineChanges = e.changes.some(change => {
                return change.range.endLineNumber !== change.range.startLineNumber || countEOL(change.text)[0] !== 0;
            });
        }
    }
    updateHiddenRanges() {
        let updateHiddenAreas = false;
        const newHiddenAreas = [];
        let i = 0; // index into hidden
        let k = 0;
        let lastCollapsedStart = Number.MAX_VALUE;
        let lastCollapsedEnd = -1;
        const ranges = this._foldingModel.regions;
        for (; i < ranges.length; i++) {
            if (!ranges.isCollapsed(i)) {
                continue;
            }
            const startLineNumber = ranges.getStartLineNumber(i) + 1; // the first line is not hidden
            const endLineNumber = ranges.getEndLineNumber(i);
            if (lastCollapsedStart <= startLineNumber && endLineNumber <= lastCollapsedEnd) {
                // ignore ranges contained in collapsed regions
                continue;
            }
            if (!updateHiddenAreas && k < this._hiddenRanges.length && this._hiddenRanges[k].startLineNumber === startLineNumber && this._hiddenRanges[k].endLineNumber === endLineNumber) {
                // reuse the old ranges
                newHiddenAreas.push(this._hiddenRanges[k]);
                k++;
            }
            else {
                updateHiddenAreas = true;
                newHiddenAreas.push(new Range(startLineNumber, 1, endLineNumber, 1));
            }
            lastCollapsedStart = startLineNumber;
            lastCollapsedEnd = endLineNumber;
        }
        if (this._hasLineChanges || updateHiddenAreas || k < this._hiddenRanges.length) {
            this.applyHiddenRanges(newHiddenAreas);
        }
    }
    applyHiddenRanges(newHiddenAreas) {
        this._hiddenRanges = newHiddenAreas;
        this._hasLineChanges = false;
        this._updateEventEmitter.fire(newHiddenAreas);
    }
    hasRanges() {
        return this._hiddenRanges.length > 0;
    }
    isHidden(line) {
        return findRange(this._hiddenRanges, line) !== null;
    }
    adjustSelections(selections) {
        let hasChanges = false;
        const editorModel = this._foldingModel.textModel;
        let lastRange = null;
        const adjustLine = (line) => {
            if (!lastRange || !isInside(line, lastRange)) {
                lastRange = findRange(this._hiddenRanges, line);
            }
            if (lastRange) {
                return lastRange.startLineNumber - 1;
            }
            return null;
        };
        for (let i = 0, len = selections.length; i < len; i++) {
            let selection = selections[i];
            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[i] = selection;
        }
        return hasChanges;
    }
    dispose() {
        if (this.hiddenRanges.length > 0) {
            this._hiddenRanges = [];
            this._updateEventEmitter.fire(this._hiddenRanges);
        }
        if (this._foldingModelListener) {
            this._foldingModelListener.dispose();
            this._foldingModelListener = null;
        }
    }
}
function isInside(line, range) {
    return line >= range.startLineNumber && line <= range.endLineNumber;
}
function findRange(ranges, line) {
    const i = findFirstInSorted(ranges, r => line < r.startLineNumber) - 1;
    if (i >= 0 && ranges[i].endLineNumber >= line) {
        return ranges[i];
    }
    return null;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/folding/browser/indentRangeProvider.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


const MAX_FOLDING_REGIONS_FOR_INDENT_DEFAULT = 5000;
const ID_INDENT_PROVIDER = 'indent';
class IndentRangeProvider {
    constructor(editorModel, languageConfigurationService, maxFoldingRegions) {
        this.editorModel = editorModel;
        this.languageConfigurationService = languageConfigurationService;
        this.maxFoldingRegions = maxFoldingRegions;
        this.id = ID_INDENT_PROVIDER;
    }
    dispose() { }
    compute(cancelationToken, notifyTooManyRegions) {
        const foldingRules = this.languageConfigurationService.getLanguageConfiguration(this.editorModel.getLanguageId()).foldingRules;
        const offSide = foldingRules && !!foldingRules.offSide;
        const markers = foldingRules && foldingRules.markers;
        return Promise.resolve(computeRanges(this.editorModel, offSide, markers, this.maxFoldingRegions, notifyTooManyRegions));
    }
}
// public only for testing
class RangesCollector {
    constructor(foldingRangesLimit, _notifyTooManyRegions) {
        this._notifyTooManyRegions = _notifyTooManyRegions;
        this._startIndexes = [];
        this._endIndexes = [];
        this._indentOccurrences = [];
        this._length = 0;
        this._foldingRangesLimit = foldingRangesLimit;
    }
    insertFirst(startLineNumber, endLineNumber, indent) {
        if (startLineNumber > MAX_LINE_NUMBER || endLineNumber > MAX_LINE_NUMBER) {
            return;
        }
        const index = this._length;
        this._startIndexes[index] = startLineNumber;
        this._endIndexes[index] = endLineNumber;
        this._length++;
        if (indent < 1000) {
            this._indentOccurrences[indent] = (this._indentOccurrences[indent] || 0) + 1;
        }
    }
    toIndentRanges(model) {
        var _a;
        if (this._length <= this._foldingRangesLimit) {
            // reverse and create arrays of the exact length
            const startIndexes = new Uint32Array(this._length);
            const endIndexes = new Uint32Array(this._length);
            for (let i = this._length - 1, k = 0; i >= 0; i--, k++) {
                startIndexes[k] = this._startIndexes[i];
                endIndexes[k] = this._endIndexes[i];
            }
            return new FoldingRegions(startIndexes, endIndexes);
        }
        else {
            (_a = this._notifyTooManyRegions) === null || _a === void 0 ? void 0 : _a.call(this, this._foldingRangesLimit);
            let entries = 0;
            let maxIndent = this._indentOccurrences.length;
            for (let i = 0; i < this._indentOccurrences.length; i++) {
                const n = this._indentOccurrences[i];
                if (n) {
                    if (n + entries > this._foldingRangesLimit) {
                        maxIndent = i;
                        break;
                    }
                    entries += n;
                }
            }
            const tabSize = model.getOptions().tabSize;
            // reverse and create arrays of the exact length
            const startIndexes = new Uint32Array(this._foldingRangesLimit);
            const endIndexes = new Uint32Array(this._foldingRangesLimit);
            for (let i = this._length - 1, k = 0; i >= 0; i--) {
                const startIndex = this._startIndexes[i];
                const lineContent = model.getLineContent(startIndex);
                const indent = computeIndentLevel(lineContent, tabSize);
                if (indent < maxIndent || (indent === maxIndent && entries++ < this._foldingRangesLimit)) {
                    startIndexes[k] = startIndex;
                    endIndexes[k] = this._endIndexes[i];
                    k++;
                }
            }
            return new FoldingRegions(startIndexes, endIndexes);
        }
    }
}
function computeRanges(model, offSide, markers, foldingRangesLimit, notifyTooManyRegions) {
    const tabSize = model.getOptions().tabSize;
    foldingRangesLimit = foldingRangesLimit !== null && foldingRangesLimit !== void 0 ? foldingRangesLimit : MAX_FOLDING_REGIONS_FOR_INDENT_DEFAULT;
    const result = new RangesCollector(foldingRangesLimit, notifyTooManyRegions);
    let pattern = undefined;
    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 }); // sentinel, to make sure there's at least one entry
    for (let line = model.getLineCount(); line > 0; line--) {
        const lineContent = model.getLineContent(line);
        const indent = computeIndentLevel(lineContent, tabSize);
        let previous = previousRegions[previousRegions.length - 1];
        if (indent === -1) {
            if (offSide) {
                // for offSide languages, empty lines are associated to the previous block
                // note: the next block is already written to the results, so this only
                // impacts the end position of the block before
                previous.endAbove = line;
            }
            continue; // only whitespace
        }
        let m;
        if (pattern && (m = lineContent.match(pattern))) {
            // folding pattern match
            if (m[1]) { // start pattern match
                // discard all regions until the folding pattern
                let i = previousRegions.length - 1;
                while (i > 0 && previousRegions[i].indent !== -2) {
                    i--;
                }
                if (i > 0) {
                    previousRegions.length = i + 1;
                    previous = previousRegions[i];
                    // new folding range from pattern, includes the end line
                    result.insertFirst(line, previous.line, indent);
                    previous.line = line;
                    previous.indent = indent;
                    previous.endAbove = line;
                    continue;
                }
                else {
                    // no end marker found, treat line as a regular line
                }
            }
            else { // end pattern match
                previousRegions.push({ indent: -2, endAbove: line, line });
                continue;
            }
        }
        if (previous.indent > indent) {
            // discard all regions with larger indent
            do {
                previousRegions.pop();
                previous = previousRegions[previousRegions.length - 1];
            } while (previous.indent > indent);
            // new folding range
            const endLineNumber = previous.endAbove - 1;
            if (endLineNumber - line >= 1) { // needs at east size 1
                result.insertFirst(line, endLineNumber, indent);
            }
        }
        if (previous.indent === indent) {
            previous.endAbove = line;
        }
        else { // previous.indent < indent
            // new region with a bigger indent
            previousRegions.push({ indent, endAbove: line, line });
        }
    }
    return result.toIndentRanges(model);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/folding/browser/foldingDecorations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





const foldingExpandedIcon = registerIcon('folding-expanded', Codicon.chevronDown, localize('foldingExpandedIcon', 'Icon for expanded ranges in the editor glyph margin.'));
const foldingCollapsedIcon = registerIcon('folding-collapsed', Codicon.chevronRight, localize('foldingCollapsedIcon', 'Icon for collapsed ranges in the editor glyph margin.'));
const foldingManualCollapsedIcon = registerIcon('folding-manual-collapsed', foldingCollapsedIcon, localize('foldingManualCollapedIcon', 'Icon for manually collapsed ranges in the editor glyph margin.'));
const foldingManualExpandedIcon = registerIcon('folding-manual-expanded', foldingExpandedIcon, localize('foldingManualExpandedIcon', 'Icon for manually expanded ranges in the editor glyph margin.'));
class FoldingDecorationProvider {
    constructor(editor) {
        this.editor = editor;
        this.showFoldingControls = 'mouseover';
        this.showFoldingHighlights = true;
    }
    getDecorationOption(isCollapsed, isHidden, isManual) {
        if (isHidden // is inside another collapsed region
            || this.showFoldingControls === 'never') {
            return FoldingDecorationProvider.HIDDEN_RANGE_DECORATION;
        }
        if (isCollapsed) {
            return isManual ?
                (this.showFoldingHighlights ? FoldingDecorationProvider.MANUALLY_COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : FoldingDecorationProvider.MANUALLY_COLLAPSED_VISUAL_DECORATION)
                : (this.showFoldingHighlights ? FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION);
        }
        else if (this.showFoldingControls === 'mouseover') {
            return isManual ? FoldingDecorationProvider.MANUALLY_EXPANDED_AUTO_HIDE_VISUAL_DECORATION : FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION;
        }
        else {
            return isManual ? FoldingDecorationProvider.MANUALLY_EXPANDED_VISUAL_DECORATION : FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION;
        }
    }
    changeDecorations(callback) {
        return this.editor.changeDecorations(callback);
    }
    removeDecorations(decorationIds) {
        this.editor.removeDecorations(decorationIds);
    }
}
FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: 'folding-collapsed-visual-decoration',
    stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
    afterContentClassName: 'inline-folded',
    isWholeLine: true,
    firstLineDecorationClassName: ThemeIcon.asClassName(foldingCollapsedIcon)
});
FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: 'folding-collapsed-highlighted-visual-decoration',
    stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
    afterContentClassName: 'inline-folded',
    className: 'folded-background',
    isWholeLine: true,
    firstLineDecorationClassName: ThemeIcon.asClassName(foldingCollapsedIcon)
});
FoldingDecorationProvider.MANUALLY_COLLAPSED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: 'folding-manually-collapsed-visual-decoration',
    stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
    afterContentClassName: 'inline-folded',
    isWholeLine: true,
    firstLineDecorationClassName: 'alwaysShowFoldIcons ' + ThemeIcon.asClassName(foldingExpandedIcon)
});
FoldingDecorationProvider.MANUALLY_COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: 'folding-manually-collapsed-highlighted-visual-decoration',
    stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
    afterContentClassName: 'inline-folded',
    className: 'folded-background',
    isWholeLine: true,
    firstLineDecorationClassName: ThemeIcon.asClassName(foldingManualCollapsedIcon)
});
FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: 'folding-expanded-auto-hide-visual-decoration',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    isWholeLine: true,
    firstLineDecorationClassName: ThemeIcon.asClassName(foldingExpandedIcon)
});
FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: 'folding-expanded-visual-decoration',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    isWholeLine: true,
    firstLineDecorationClassName: 'alwaysShowFoldIcons ' + ThemeIcon.asClassName(foldingExpandedIcon)
});
FoldingDecorationProvider.MANUALLY_EXPANDED_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: 'folding-manually-expanded-visual-decoration',
    stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
    isWholeLine: true,
    firstLineDecorationClassName: 'alwaysShowFoldIcons ' + ThemeIcon.asClassName(foldingManualExpandedIcon)
});
FoldingDecorationProvider.MANUALLY_EXPANDED_AUTO_HIDE_VISUAL_DECORATION = ModelDecorationOptions.register({
    description: 'folding-manually-expanded-visual-decoration',
    stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
    isWholeLine: true,
    firstLineDecorationClassName: ThemeIcon.asClassName(foldingManualExpandedIcon)
});
FoldingDecorationProvider.HIDDEN_RANGE_DECORATION = ModelDecorationOptions.register({
    description: 'folding-hidden-range-decoration',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/folding/browser/syntaxRangeProvider.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



const foldingContext = {};
const ID_SYNTAX_PROVIDER = 'syntax';
class SyntaxRangeProvider {
    constructor(editorModel, providers, handleFoldingRangesChange, limit) {
        this.editorModel = editorModel;
        this.providers = providers;
        this.limit = limit;
        this.id = ID_SYNTAX_PROVIDER;
        for (const provider of providers) {
            if (typeof provider.onDidChange === 'function') {
                if (!this.disposables) {
                    this.disposables = new DisposableStore();
                }
                this.disposables.add(provider.onDidChange(handleFoldingRangesChange));
            }
        }
    }
    compute(cancellationToken, notifyTooManyRegions) {
        return collectSyntaxRanges(this.providers, this.editorModel, cancellationToken).then(ranges => {
            if (ranges) {
                const res = sanitizeRanges(ranges, this.limit, notifyTooManyRegions);
                return res;
            }
            return null;
        });
    }
    dispose() {
        var _a;
        (_a = this.disposables) === null || _a === void 0 ? void 0 : _a.dispose();
    }
}
function collectSyntaxRanges(providers, model, cancellationToken) {
    let rangeData = null;
    const promises = providers.map((provider, i) => {
        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 r of ranges) {
                    if (r.start > 0 && r.end > r.start && r.end <= nLines) {
                        rangeData.push({ start: r.start, end: r.end, rank: i, kind: r.kind });
                    }
                }
            }
        }, onUnexpectedExternalError);
    });
    return Promise.all(promises).then(_ => {
        return rangeData;
    });
}
class syntaxRangeProvider_RangesCollector {
    constructor(foldingRangesLimit, _notifyTooManyRegions) {
        this._notifyTooManyRegions = _notifyTooManyRegions;
        this._startIndexes = [];
        this._endIndexes = [];
        this._nestingLevels = [];
        this._nestingLevelCounts = [];
        this._types = [];
        this._length = 0;
        this._foldingRangesLimit = foldingRangesLimit;
    }
    add(startLineNumber, endLineNumber, type, nestingLevel) {
        if (startLineNumber > MAX_LINE_NUMBER || endLineNumber > MAX_LINE_NUMBER) {
            return;
        }
        const index = this._length;
        this._startIndexes[index] = startLineNumber;
        this._endIndexes[index] = endLineNumber;
        this._nestingLevels[index] = nestingLevel;
        this._types[index] = type;
        this._length++;
        if (nestingLevel < 30) {
            this._nestingLevelCounts[nestingLevel] = (this._nestingLevelCounts[nestingLevel] || 0) + 1;
        }
    }
    toIndentRanges() {
        var _a;
        if (this._length <= this._foldingRangesLimit) {
            const startIndexes = new Uint32Array(this._length);
            const endIndexes = new Uint32Array(this._length);
            for (let i = 0; i < this._length; i++) {
                startIndexes[i] = this._startIndexes[i];
                endIndexes[i] = this._endIndexes[i];
            }
            return new FoldingRegions(startIndexes, endIndexes, this._types);
        }
        else {
            (_a = this._notifyTooManyRegions) === null || _a === void 0 ? void 0 : _a.call(this, this._foldingRangesLimit);
            let entries = 0;
            let maxLevel = this._nestingLevelCounts.length;
            for (let i = 0; i < this._nestingLevelCounts.length; i++) {
                const n = this._nestingLevelCounts[i];
                if (n) {
                    if (n + entries > this._foldingRangesLimit) {
                        maxLevel = i;
                        break;
                    }
                    entries += n;
                }
            }
            const startIndexes = new Uint32Array(this._foldingRangesLimit);
            const endIndexes = new Uint32Array(this._foldingRangesLimit);
            const types = [];
            for (let i = 0, k = 0; i < this._length; i++) {
                const level = this._nestingLevels[i];
                if (level < maxLevel || (level === maxLevel && entries++ < this._foldingRangesLimit)) {
                    startIndexes[k] = this._startIndexes[i];
                    endIndexes[k] = this._endIndexes[i];
                    types[k] = this._types[i];
                    k++;
                }
            }
            return new FoldingRegions(startIndexes, endIndexes, types);
        }
    }
}
function sanitizeRanges(rangeData, limit, notifyTooManyRegions) {
    const sorted = rangeData.sort((d1, d2) => {
        let diff = d1.start - d2.start;
        if (diff === 0) {
            diff = d1.rank - d2.rank;
        }
        return diff;
    });
    const collector = new syntaxRangeProvider_RangesCollector(limit, notifyTooManyRegions);
    let top = undefined;
    const previous = [];
    for (const entry of sorted) {
        if (!top) {
            top = entry;
            collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
        }
        else {
            if (entry.start > top.start) {
                if (entry.end <= top.end) {
                    previous.push(top);
                    top = entry;
                    collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
                }
                else {
                    if (entry.start > top.end) {
                        do {
                            top = previous.pop();
                        } while (top && entry.start > top.end);
                        if (top) {
                            previous.push(top);
                        }
                        top = entry;
                    }
                    collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
                }
            }
        }
    }
    return collector.toIndentRanges();
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/folding/browser/folding.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var folding_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var folding_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};



























const CONTEXT_FOLDING_ENABLED = new RawContextKey('foldingEnabled', false);
let FoldingController = class FoldingController extends Disposable {
    constructor(editor, contextKeyService, languageConfigurationService, notificationService, languageFeatureDebounceService, languageFeaturesService) {
        super();
        this.contextKeyService = contextKeyService;
        this.languageConfigurationService = languageConfigurationService;
        this.languageFeaturesService = languageFeaturesService;
        this._tooManyRegionsNotified = false;
        this.localToDispose = this._register(new DisposableStore());
        this.editor = editor;
        const options = this.editor.getOptions();
        this._isEnabled = options.get(39 /* EditorOption.folding */);
        this._useFoldingProviders = options.get(40 /* EditorOption.foldingStrategy */) !== 'indentation';
        this._unfoldOnClickAfterEndOfLine = options.get(44 /* EditorOption.unfoldOnClickAfterEndOfLine */);
        this._restoringViewState = false;
        this._currentModelHasFoldedImports = false;
        this._foldingImportsByDefault = options.get(42 /* EditorOption.foldingImportsByDefault */);
        this._maxFoldingRegions = options.get(43 /* EditorOption.foldingMaximumRegions */);
        this.updateDebounceInfo = languageFeatureDebounceService.for(languageFeaturesService.foldingRangeProvider, 'Folding', { min: 200 });
        this.foldingModel = null;
        this.hiddenRangeModel = null;
        this.rangeProvider = null;
        this.foldingRegionPromise = null;
        this.foldingModelPromise = null;
        this.updateScheduler = null;
        this.cursorChangedScheduler = null;
        this.mouseDownInfo = null;
        this.foldingDecorationProvider = new FoldingDecorationProvider(editor);
        this.foldingDecorationProvider.showFoldingControls = options.get(101 /* EditorOption.showFoldingControls */);
        this.foldingDecorationProvider.showFoldingHighlights = options.get(41 /* EditorOption.foldingHighlight */);
        this.foldingEnabled = CONTEXT_FOLDING_ENABLED.bindTo(this.contextKeyService);
        this.foldingEnabled.set(this._isEnabled);
        this._notifyTooManyRegions = (maxFoldingRegions) => {
            // Message will display once per time vscode runs. Once per file would be tricky.
            if (!this._tooManyRegionsNotified) {
                notificationService.notify({
                    severity: common_severity.Warning,
                    sticky: true,
                    message: localize('maximum fold ranges', "The number of foldable regions is limited to a maximum of {0}. Increase configuration option ['Folding Maximum Regions'](command:workbench.action.openSettings?[\"editor.foldingMaximumRegions\"]) to enable more.", maxFoldingRegions)
                });
                this._tooManyRegionsNotified = true;
            }
        };
        this._register(this.editor.onDidChangeModel(() => this.onModelChanged()));
        this._register(this.editor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(39 /* EditorOption.folding */)) {
                this._isEnabled = this.editor.getOptions().get(39 /* EditorOption.folding */);
                this.foldingEnabled.set(this._isEnabled);
                this.onModelChanged();
            }
            if (e.hasChanged(43 /* EditorOption.foldingMaximumRegions */)) {
                this._maxFoldingRegions = this.editor.getOptions().get(43 /* EditorOption.foldingMaximumRegions */);
                this._tooManyRegionsNotified = false;
                this.onModelChanged();
            }
            if (e.hasChanged(101 /* EditorOption.showFoldingControls */) || e.hasChanged(41 /* EditorOption.foldingHighlight */)) {
                const options = this.editor.getOptions();
                this.foldingDecorationProvider.showFoldingControls = options.get(101 /* EditorOption.showFoldingControls */);
                this.foldingDecorationProvider.showFoldingHighlights = options.get(41 /* EditorOption.foldingHighlight */);
                this.triggerFoldingModelChanged();
            }
            if (e.hasChanged(40 /* EditorOption.foldingStrategy */)) {
                this._useFoldingProviders = this.editor.getOptions().get(40 /* EditorOption.foldingStrategy */) !== 'indentation';
                this.onFoldingStrategyChanged();
            }
            if (e.hasChanged(44 /* EditorOption.unfoldOnClickAfterEndOfLine */)) {
                this._unfoldOnClickAfterEndOfLine = this.editor.getOptions().get(44 /* EditorOption.unfoldOnClickAfterEndOfLine */);
            }
            if (e.hasChanged(42 /* EditorOption.foldingImportsByDefault */)) {
                this._foldingImportsByDefault = this.editor.getOptions().get(42 /* EditorOption.foldingImportsByDefault */);
            }
        }));
        this.onModelChanged();
    }
    static get(editor) {
        return editor.getContribution(FoldingController.ID);
    }
    /**
     * Store view state.
     */
    saveViewState() {
        const model = this.editor.getModel();
        if (!model || !this._isEnabled || model.isTooLargeForTokenization()) {
            return {};
        }
        if (this.foldingModel) { // disposed ?
            const collapsedRegions = this.foldingModel.getMemento();
            const provider = this.rangeProvider ? this.rangeProvider.id : undefined;
            return { collapsedRegions, lineCount: model.getLineCount(), provider, foldedImports: this._currentModelHasFoldedImports };
        }
        return undefined;
    }
    /**
     * Restore view state.
     */
    restoreViewState(state) {
        const model = this.editor.getModel();
        if (!model || !this._isEnabled || model.isTooLargeForTokenization() || !this.hiddenRangeModel) {
            return;
        }
        if (!state || state.lineCount !== model.getLineCount()) {
            return;
        }
        this._currentModelHasFoldedImports = !!state.foldedImports;
        if (state.collapsedRegions && state.collapsedRegions.length > 0 && this.foldingModel) {
            this._restoringViewState = true;
            try {
                this.foldingModel.applyMemento(state.collapsedRegions);
            }
            finally {
                this._restoringViewState = false;
            }
        }
    }
    onModelChanged() {
        this.localToDispose.clear();
        const model = this.editor.getModel();
        if (!this._isEnabled || !model || model.isTooLargeForTokenization()) {
            // huge files get no view model, so they cannot support hidden areas
            return;
        }
        this._currentModelHasFoldedImports = false;
        this.foldingModel = new FoldingModel(model, this.foldingDecorationProvider);
        this.localToDispose.add(this.foldingModel);
        this.hiddenRangeModel = new HiddenRangeModel(this.foldingModel);
        this.localToDispose.add(this.hiddenRangeModel);
        this.localToDispose.add(this.hiddenRangeModel.onDidChange(hr => this.onHiddenRangesChanges(hr)));
        this.updateScheduler = new Delayer(this.updateDebounceInfo.get(model));
        this.cursorChangedScheduler = new RunOnceScheduler(() => this.revealCursor(), 200);
        this.localToDispose.add(this.cursorChangedScheduler);
        this.localToDispose.add(this.languageFeaturesService.foldingRangeProvider.onDidChange(() => this.onFoldingStrategyChanged()));
        this.localToDispose.add(this.editor.onDidChangeModelLanguageConfiguration(() => this.onFoldingStrategyChanged())); // covers model language changes as well
        this.localToDispose.add(this.editor.onDidChangeModelContent(e => this.onDidChangeModelContent(e)));
        this.localToDispose.add(this.editor.onDidChangeCursorPosition(() => this.onCursorPositionChanged()));
        this.localToDispose.add(this.editor.onMouseDown(e => this.onEditorMouseDown(e)));
        this.localToDispose.add(this.editor.onMouseUp(e => this.onEditorMouseUp(e)));
        this.localToDispose.add({
            dispose: () => {
                if (this.foldingRegionPromise) {
                    this.foldingRegionPromise.cancel();
                    this.foldingRegionPromise = null;
                }
                if (this.updateScheduler) {
                    this.updateScheduler.cancel();
                }
                this.updateScheduler = null;
                this.foldingModel = null;
                this.foldingModelPromise = null;
                this.hiddenRangeModel = null;
                this.cursorChangedScheduler = null;
                if (this.rangeProvider) {
                    this.rangeProvider.dispose();
                }
                this.rangeProvider = null;
            }
        });
        this.triggerFoldingModelChanged();
    }
    onFoldingStrategyChanged() {
        if (this.rangeProvider) {
            this.rangeProvider.dispose();
        }
        this.rangeProvider = null;
        this.triggerFoldingModelChanged();
    }
    getRangeProvider(editorModel) {
        if (this.rangeProvider) {
            return this.rangeProvider;
        }
        this.rangeProvider = new IndentRangeProvider(editorModel, this.languageConfigurationService, this._maxFoldingRegions); // fallback
        if (this._useFoldingProviders && this.foldingModel) {
            const foldingProviders = this.languageFeaturesService.foldingRangeProvider.ordered(this.foldingModel.textModel);
            if (foldingProviders.length > 0) {
                this.rangeProvider = new SyntaxRangeProvider(editorModel, foldingProviders, () => this.triggerFoldingModelChanged(), this._maxFoldingRegions);
            }
        }
        return this.rangeProvider;
    }
    getFoldingModel() {
        return this.foldingModelPromise;
    }
    onDidChangeModelContent(e) {
        var _a;
        (_a = this.hiddenRangeModel) === null || _a === void 0 ? void 0 : _a.notifyChangeModelContent(e);
        this.triggerFoldingModelChanged();
    }
    triggerFoldingModelChanged() {
        if (this.updateScheduler) {
            if (this.foldingRegionPromise) {
                this.foldingRegionPromise.cancel();
                this.foldingRegionPromise = null;
            }
            this.foldingModelPromise = this.updateScheduler.trigger(() => {
                const foldingModel = this.foldingModel;
                if (!foldingModel) { // null if editor has been disposed, or folding turned off
                    return null;
                }
                const sw = new StopWatch(true);
                const provider = this.getRangeProvider(foldingModel.textModel);
                const foldingRegionPromise = this.foldingRegionPromise = createCancelablePromise(token => provider.compute(token, this._notifyTooManyRegions));
                return foldingRegionPromise.then(foldingRanges => {
                    if (foldingRanges && foldingRegionPromise === this.foldingRegionPromise) { // new request or cancelled in the meantime?
                        let scrollState;
                        if (this._foldingImportsByDefault && !this._currentModelHasFoldedImports) {
                            const hasChanges = foldingRanges.setCollapsedAllOfType(FoldingRangeKind.Imports.value, true);
                            if (hasChanges) {
                                scrollState = StableEditorScrollState.capture(this.editor);
                                this._currentModelHasFoldedImports = hasChanges;
                            }
                        }
                        // some cursors might have moved into hidden regions, make sure they are in expanded regions
                        const selections = this.editor.getSelections();
                        const selectionLineNumbers = selections ? selections.map(s => s.startLineNumber) : [];
                        foldingModel.update(foldingRanges, selectionLineNumbers);
                        scrollState === null || scrollState === void 0 ? void 0 : scrollState.restore(this.editor);
                        // update debounce info
                        const newValue = this.updateDebounceInfo.update(foldingModel.textModel, sw.elapsed());
                        if (this.updateScheduler) {
                            this.updateScheduler.defaultDelay = newValue;
                        }
                    }
                    return foldingModel;
                });
            }).then(undefined, (err) => {
                onUnexpectedError(err);
                return null;
            });
        }
    }
    onHiddenRangesChanges(hiddenRanges) {
        if (this.hiddenRangeModel && hiddenRanges.length && !this._restoringViewState) {
            const selections = this.editor.getSelections();
            if (selections) {
                if (this.hiddenRangeModel.adjustSelections(selections)) {
                    this.editor.setSelections(selections);
                }
            }
        }
        this.editor.setHiddenAreas(hiddenRanges);
    }
    onCursorPositionChanged() {
        if (this.hiddenRangeModel && this.hiddenRangeModel.hasRanges()) {
            this.cursorChangedScheduler.schedule();
        }
    }
    revealCursor() {
        const foldingModel = this.getFoldingModel();
        if (!foldingModel) {
            return;
        }
        foldingModel.then(foldingModel => {
            if (foldingModel) {
                const selections = this.editor.getSelections();
                if (selections && selections.length > 0) {
                    const toToggle = [];
                    for (const selection of selections) {
                        const lineNumber = selection.selectionStartLineNumber;
                        if (this.hiddenRangeModel && this.hiddenRangeModel.isHidden(lineNumber)) {
                            toToggle.push(...foldingModel.getAllRegionsAtLine(lineNumber, r => r.isCollapsed && lineNumber > r.startLineNumber));
                        }
                    }
                    if (toToggle.length) {
                        foldingModel.toggleCollapseState(toToggle);
                        this.reveal(selections[0].getPosition());
                    }
                }
            }
        }).then(undefined, onUnexpectedError);
    }
    onEditorMouseDown(e) {
        this.mouseDownInfo = null;
        if (!this.hiddenRangeModel || !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 /* MouseTargetType.GUTTER_LINE_DECORATIONS */: {
                const data = e.target.detail;
                const offsetLeftInGutter = e.target.element.offsetLeft;
                const gutterOffsetX = data.offsetX - offsetLeftInGutter;
                // const gutterOffsetX = data.offsetX - data.glyphMarginWidth - data.lineNumbersWidth - data.glyphMarginLeft;
                // TODO@joao TODO@alex TODO@martin this is such that we don't collide with dirty diff
                if (gutterOffsetX < 5) { // the whitespace between the border and the real folding icon border is 5px
                    return;
                }
                iconClicked = true;
                break;
            }
            case 7 /* MouseTargetType.CONTENT_EMPTY */: {
                if (this._unfoldOnClickAfterEndOfLine && this.hiddenRangeModel.hasRanges()) {
                    const data = e.target.detail;
                    if (!data.isAfterLines) {
                        break;
                    }
                }
                return;
            }
            case 6 /* MouseTargetType.CONTENT_TEXT */: {
                if (this.hiddenRangeModel.hasRanges()) {
                    const model = this.editor.getModel();
                    if (model && range.startColumn === model.getLineMaxColumn(range.startLineNumber)) {
                        break;
                    }
                }
                return;
            }
            default:
                return;
        }
        this.mouseDownInfo = { lineNumber: range.startLineNumber, iconClicked };
    }
    onEditorMouseUp(e) {
        const foldingModel = this.foldingModel;
        if (!foldingModel || !this.mouseDownInfo || !e.target) {
            return;
        }
        const lineNumber = this.mouseDownInfo.lineNumber;
        const iconClicked = this.mouseDownInfo.iconClicked;
        const range = e.target.range;
        if (!range || range.startLineNumber !== lineNumber) {
            return;
        }
        if (iconClicked) {
            if (e.target.type !== 4 /* MouseTargetType.GUTTER_LINE_DECORATIONS */) {
                return;
            }
        }
        else {
            const model = this.editor.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 r of toMaybeToggle) {
                        if (r.isCollapsed) {
                            toToggle.push(r);
                        }
                    }
                    // if any surrounding regions are folded, unfold those. Otherwise, fold all surrounding
                    if (toToggle.length === 0) {
                        toToggle = toMaybeToggle;
                    }
                }
                else {
                    const recursive = e.event.middleButton || e.event.shiftKey;
                    if (recursive) {
                        for (const r of foldingModel.getRegionsInside(region)) {
                            if (r.isCollapsed === isCollapsed) {
                                toToggle.push(r);
                            }
                        }
                    }
                    // when recursive, first only collapse all children. If all are already folded or there are no children, also fold parent.
                    if (isCollapsed || !recursive || toToggle.length === 0) {
                        toToggle.push(region);
                    }
                }
                foldingModel.toggleCollapseState(toToggle);
                this.reveal({ lineNumber, column: 1 });
            }
        }
    }
    reveal(position) {
        this.editor.revealPositionInCenterIfOutsideViewport(position, 0 /* ScrollType.Smooth */);
    }
};
FoldingController.ID = 'editor.contrib.folding';
FoldingController = folding_decorate([
    folding_param(1, IContextKeyService),
    folding_param(2, ILanguageConfigurationService),
    folding_param(3, INotificationService),
    folding_param(4, ILanguageFeatureDebounceService),
    folding_param(5, ILanguageFeaturesService)
], FoldingController);

class FoldingAction extends EditorAction {
    runEditorCommand(accessor, editor, args) {
        const languageConfigurationService = accessor.get(ILanguageConfigurationService);
        const foldingController = FoldingController.get(editor);
        if (!foldingController) {
            return;
        }
        const foldingModelPromise = foldingController.getFoldingModel();
        if (foldingModelPromise) {
            this.reportTelemetry(accessor, editor);
            return foldingModelPromise.then(foldingModel => {
                if (foldingModel) {
                    this.invoke(foldingController, foldingModel, editor, args, languageConfigurationService);
                    const selection = editor.getSelection();
                    if (selection) {
                        foldingController.reveal(selection.getStartPosition());
                    }
                }
            });
        }
    }
    getSelectedLines(editor) {
        const selections = editor.getSelections();
        return selections ? selections.map(s => s.startLineNumber) : [];
    }
    getLineNumbers(args, editor) {
        if (args && args.selectionLines) {
            return args.selectionLines.map(l => l + 1); // to 0-bases line numbers
        }
        return this.getSelectedLines(editor);
    }
    run(_accessor, _editor) {
    }
}
function foldingArgumentsConstraint(args) {
    if (!isUndefined(args)) {
        if (!isObject(args)) {
            return false;
        }
        const foldingArgs = args;
        if (!isUndefined(foldingArgs.levels) && !isNumber(foldingArgs.levels)) {
            return false;
        }
        if (!isUndefined(foldingArgs.direction) && !isString(foldingArgs.direction)) {
            return false;
        }
        if (!isUndefined(foldingArgs.selectionLines) && (!isArray(foldingArgs.selectionLines) || !foldingArgs.selectionLines.every(isNumber))) {
            return false;
        }
    }
    return true;
}
class UnfoldAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.unfold',
            label: localize('unfoldAction.label', "Unfold"),
            alias: 'Unfold',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 89 /* KeyCode.BracketRight */,
                mac: {
                    primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 89 /* KeyCode.BracketRight */
                },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            description: {
                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, args) {
        const levels = args && args.levels || 1;
        const lineNumbers = this.getLineNumbers(args, editor);
        if (args && args.direction === 'up') {
            setCollapseStateLevelsUp(foldingModel, false, levels, lineNumbers);
        }
        else {
            setCollapseStateLevelsDown(foldingModel, false, levels, lineNumbers);
        }
    }
}
class UnFoldRecursivelyAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.unfoldRecursively',
            label: localize('unFoldRecursivelyAction.label', "Unfold Recursively"),
            alias: 'Unfold Recursively',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 89 /* KeyCode.BracketRight */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor, _args) {
        setCollapseStateLevelsDown(foldingModel, false, Number.MAX_VALUE, this.getSelectedLines(editor));
    }
}
class FoldAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.fold',
            label: localize('foldAction.label', "Fold"),
            alias: 'Fold',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 87 /* KeyCode.BracketLeft */,
                mac: {
                    primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 87 /* KeyCode.BracketLeft */
                },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            description: {
                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, args) {
        const lineNumbers = this.getLineNumbers(args, editor);
        const levels = args && args.levels;
        const direction = args && args.direction;
        if (typeof levels !== 'number' && typeof direction !== 'string') {
            // fold the region at the location or if already collapsed, the first uncollapsed parent instead.
            setCollapseStateUp(foldingModel, true, lineNumbers);
        }
        else {
            if (direction === 'up') {
                setCollapseStateLevelsUp(foldingModel, true, levels || 1, lineNumbers);
            }
            else {
                setCollapseStateLevelsDown(foldingModel, true, levels || 1, lineNumbers);
            }
        }
    }
}
class ToggleFoldAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.toggleFold',
            label: localize('toggleFoldAction.label', "Toggle Fold"),
            alias: 'Toggle Fold',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 42 /* KeyCode.KeyL */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor) {
        const selectedLines = this.getSelectedLines(editor);
        toggleCollapseState(foldingModel, 1, selectedLines);
    }
}
class FoldRecursivelyAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.foldRecursively',
            label: localize('foldRecursivelyAction.label', "Fold Recursively"),
            alias: 'Fold Recursively',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 87 /* KeyCode.BracketLeft */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor) {
        const selectedLines = this.getSelectedLines(editor);
        setCollapseStateLevelsDown(foldingModel, true, Number.MAX_VALUE, selectedLines);
    }
}
class FoldAllBlockCommentsAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.foldAllBlockComments',
            label: localize('foldAllBlockComments.label', "Fold All Block Comments"),
            alias: 'Fold All Block Comments',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 85 /* KeyCode.Slash */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor, args, languageConfigurationService) {
        if (foldingModel.regions.hasTypes()) {
            setCollapseStateForType(foldingModel, FoldingRangeKind.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*' + escapeRegExpCharacters(comments.blockCommentStartToken));
                setCollapseStateForMatchingLines(foldingModel, regExp, true);
            }
        }
    }
}
class FoldAllRegionsAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.foldAllMarkerRegions',
            label: localize('foldAllMarkerRegions.label', "Fold All Regions"),
            alias: 'Fold All Regions',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 29 /* KeyCode.Digit8 */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor, args, languageConfigurationService) {
        if (foldingModel.regions.hasTypes()) {
            setCollapseStateForType(foldingModel, FoldingRangeKind.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);
                setCollapseStateForMatchingLines(foldingModel, regExp, true);
            }
        }
    }
}
class UnfoldAllRegionsAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.unfoldAllMarkerRegions',
            label: localize('unfoldAllMarkerRegions.label', "Unfold All Regions"),
            alias: 'Unfold All Regions',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 30 /* KeyCode.Digit9 */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor, args, languageConfigurationService) {
        if (foldingModel.regions.hasTypes()) {
            setCollapseStateForType(foldingModel, FoldingRangeKind.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);
                setCollapseStateForMatchingLines(foldingModel, regExp, false);
            }
        }
    }
}
class FoldAllRegionsExceptAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.foldAllExcept',
            label: localize('foldAllExcept.label', "Fold All Regions Except Selected"),
            alias: 'Fold All Regions Except Selected',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 83 /* KeyCode.Minus */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor) {
        const selectedLines = this.getSelectedLines(editor);
        setCollapseStateForRest(foldingModel, true, selectedLines);
    }
}
class UnfoldAllRegionsExceptAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.unfoldAllExcept',
            label: localize('unfoldAllExcept.label', "Unfold All Regions Except Selected"),
            alias: 'Unfold All Regions Except Selected',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 81 /* KeyCode.Equal */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor) {
        const selectedLines = this.getSelectedLines(editor);
        setCollapseStateForRest(foldingModel, false, selectedLines);
    }
}
class FoldAllAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.foldAll',
            label: localize('foldAllAction.label', "Fold All"),
            alias: 'Fold All',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 21 /* KeyCode.Digit0 */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, _editor) {
        setCollapseStateLevelsDown(foldingModel, true);
    }
}
class UnfoldAllAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.unfoldAll',
            label: localize('unfoldAllAction.label', "Unfold All"),
            alias: 'Unfold All',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 40 /* KeyCode.KeyJ */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, _editor) {
        setCollapseStateLevelsDown(foldingModel, false);
    }
}
class FoldLevelAction extends FoldingAction {
    getFoldingLevel() {
        return parseInt(this.id.substr(FoldLevelAction.ID_PREFIX.length));
    }
    invoke(_foldingController, foldingModel, editor) {
        setCollapseStateAtLevel(foldingModel, this.getFoldingLevel(), true, this.getSelectedLines(editor));
    }
}
FoldLevelAction.ID_PREFIX = 'editor.foldLevel';
FoldLevelAction.ID = (level) => FoldLevelAction.ID_PREFIX + level;
/** Action to go to the parent fold of current line */
class GotoParentFoldAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.gotoParentFold',
            label: localize('gotoParentFold.label', "Go to Parent Fold"),
            alias: 'Go to Parent Fold',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor) {
        const selectedLines = this.getSelectedLines(editor);
        if (selectedLines.length > 0) {
            const startLineNumber = getParentFoldLine(selectedLines[0], foldingModel);
            if (startLineNumber !== null) {
                editor.setSelection({
                    startLineNumber: startLineNumber,
                    startColumn: 1,
                    endLineNumber: startLineNumber,
                    endColumn: 1
                });
            }
        }
    }
}
/** Action to go to the previous fold of current line */
class GotoPreviousFoldAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.gotoPreviousFold',
            label: localize('gotoPreviousFold.label', "Go to Previous Folding Range"),
            alias: 'Go to Previous Folding Range',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor) {
        const selectedLines = this.getSelectedLines(editor);
        if (selectedLines.length > 0) {
            const startLineNumber = getPreviousFoldLine(selectedLines[0], foldingModel);
            if (startLineNumber !== null) {
                editor.setSelection({
                    startLineNumber: startLineNumber,
                    startColumn: 1,
                    endLineNumber: startLineNumber,
                    endColumn: 1
                });
            }
        }
    }
}
/** Action to go to the next fold of current line */
class GotoNextFoldAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.gotoNextFold',
            label: localize('gotoNextFold.label', "Go to Next Folding Range"),
            alias: 'Go to Next Folding Range',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor) {
        const selectedLines = this.getSelectedLines(editor);
        if (selectedLines.length > 0) {
            const startLineNumber = getNextFoldLine(selectedLines[0], foldingModel);
            if (startLineNumber !== null) {
                editor.setSelection({
                    startLineNumber: startLineNumber,
                    startColumn: 1,
                    endLineNumber: startLineNumber,
                    endColumn: 1
                });
            }
        }
    }
}
class FoldRangeFromSelectionAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.createFoldingRangeFromSelection',
            label: localize('createManualFoldRange.label', "Create Manual Folding Range from Selection"),
            alias: 'Create Folding Range from Selection',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 82 /* KeyCode.Comma */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    invoke(_foldingController, foldingModel, editor) {
        var _a;
        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: endLineNumber,
                        type: undefined,
                        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 = FoldingRegions.sanitizeAndMerge(foldingModel.regions, collapseRanges, (_a = editor.getModel()) === null || _a === void 0 ? void 0 : _a.getLineCount());
                foldingModel.updatePost(FoldingRegions.fromFoldRanges(newRanges));
            }
        }
    }
}
class RemoveFoldRangeFromSelectionAction extends FoldingAction {
    constructor() {
        super({
            id: 'editor.removeManualFoldingRanges',
            label: localize('removeManualFoldingRanges.label', "Remove Manual Folding Ranges"),
            alias: 'Remove Manual Folding Ranges',
            precondition: CONTEXT_FOLDING_ENABLED,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 84 /* 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();
        }
    }
}
registerEditorContribution(FoldingController.ID, FoldingController);
registerEditorAction(UnfoldAction);
registerEditorAction(UnFoldRecursivelyAction);
registerEditorAction(FoldAction);
registerEditorAction(FoldRecursivelyAction);
registerEditorAction(FoldAllAction);
registerEditorAction(UnfoldAllAction);
registerEditorAction(FoldAllBlockCommentsAction);
registerEditorAction(FoldAllRegionsAction);
registerEditorAction(UnfoldAllRegionsAction);
registerEditorAction(FoldAllRegionsExceptAction);
registerEditorAction(UnfoldAllRegionsExceptAction);
registerEditorAction(ToggleFoldAction);
registerEditorAction(GotoParentFoldAction);
registerEditorAction(GotoPreviousFoldAction);
registerEditorAction(GotoNextFoldAction);
registerEditorAction(FoldRangeFromSelectionAction);
registerEditorAction(RemoveFoldRangeFromSelectionAction);
for (let i = 1; i <= 7; i++) {
    registerInstantiatedEditorAction(new FoldLevelAction({
        id: FoldLevelAction.ID(i),
        label: localize('foldLevelAction.label', "Fold Level {0}", i),
        alias: `Fold Level ${i}`,
        precondition: CONTEXT_FOLDING_ENABLED,
        kbOpts: {
            kbExpr: EditorContextKeys.editorTextFocus,
            primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | (21 /* KeyCode.Digit0 */ + i)),
            weight: 100 /* KeybindingWeight.EditorContrib */
        }
    }));
}
const foldBackgroundBackground = registerColor('editor.foldBackground', { light: transparent(editorSelectionBackground, 0.3), dark: transparent(editorSelectionBackground, 0.3), hcDark: null, hcLight: null }, localize('foldBackgroundBackground', "Background color behind folded ranges. The color must not be opaque so as not to hide underlying decorations."), true);
const editorFoldForeground = registerColor('editorGutter.foldingControlForeground', { dark: iconForeground, light: iconForeground, hcDark: iconForeground, hcLight: iconForeground }, localize('editorGutter.foldingControlForeground', 'Color of the folding control in the editor gutter.'));
registerThemingParticipant((theme, collector) => {
    const foldBackground = theme.getColor(foldBackgroundBackground);
    if (foldBackground) {
        collector.addRule(`.monaco-editor .folded-background { background-color: ${foldBackground}; }`);
    }
    const editorFoldColor = theme.getColor(editorFoldForeground);
    if (editorFoldColor) {
        collector.addRule(`
		.monaco-editor .cldr${ThemeIcon.asCSSSelector(foldingExpandedIcon)},
		.monaco-editor .cldr${ThemeIcon.asCSSSelector(foldingCollapsedIcon)},
		.monaco-editor .cldr${ThemeIcon.asCSSSelector(foldingManualExpandedIcon)},
		.monaco-editor .cldr${ThemeIcon.asCSSSelector(foldingManualCollapsedIcon)} {
			color: ${editorFoldColor} !important;
		}
		`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/fontZoom/browser/fontZoom.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class EditorFontZoomIn extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.fontZoomIn',
            label: localize('EditorFontZoomIn.label', "Editor Font Zoom In"),
            alias: 'Editor Font Zoom In',
            precondition: undefined
        });
    }
    run(accessor, editor) {
        EditorZoom.setZoomLevel(EditorZoom.getZoomLevel() + 1);
    }
}
class EditorFontZoomOut extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.fontZoomOut',
            label: localize('EditorFontZoomOut.label', "Editor Font Zoom Out"),
            alias: 'Editor Font Zoom Out',
            precondition: undefined
        });
    }
    run(accessor, editor) {
        EditorZoom.setZoomLevel(EditorZoom.getZoomLevel() - 1);
    }
}
class EditorFontZoomReset extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.fontZoomReset',
            label: localize('EditorFontZoomReset.label', "Editor Font Zoom Reset"),
            alias: 'Editor Font Zoom Reset',
            precondition: undefined
        });
    }
    run(accessor, editor) {
        EditorZoom.setZoomLevel(0);
    }
}
registerEditorAction(EditorFontZoomIn);
registerEditorAction(EditorFontZoomOut);
registerEditorAction(EditorFontZoomReset);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/editorWorker.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const ID_EDITOR_WORKER_SERVICE = 'editorWorkerService';
const IEditorWorkerService = createDecorator(ID_EDITOR_WORKER_SERVICE);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/format/browser/formattingEdit.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class FormattingEdit {
    static _handleEolEdits(editor, edits) {
        let newEol = undefined;
        const singleEdits = [];
        for (const edit of edits) {
            if (typeof edit.eol === 'number') {
                newEol = edit.eol;
            }
            if (edit.range && typeof edit.text === 'string') {
                singleEdits.push(edit);
            }
        }
        if (typeof newEol === 'number') {
            if (editor.hasModel()) {
                editor.getModel().pushEOL(newEol);
            }
        }
        return singleEdits;
    }
    static _isFullModelReplaceEdit(editor, edit) {
        if (!editor.hasModel()) {
            return false;
        }
        const model = editor.getModel();
        const editRange = model.validateRange(edit.range);
        const fullModelRange = model.getFullModelRange();
        return fullModelRange.equalsRange(editRange);
    }
    static execute(editor, _edits, addUndoStops) {
        if (addUndoStops) {
            editor.pushUndoStop();
        }
        const edits = FormattingEdit._handleEolEdits(editor, _edits);
        if (edits.length === 1 && FormattingEdit._isFullModelReplaceEdit(editor, edits[0])) {
            // We use replace semantics and hope that markers stay put...
            editor.executeEdits('formatEditsCommand', edits.map(edit => EditOperation.replace(Range.lift(edit.range), edit.text)));
        }
        else {
            editor.executeEdits('formatEditsCommand', edits.map(edit => EditOperation.replaceMove(Range.lift(edit.range), edit.text)));
        }
        if (addUndoStops) {
            editor.pushUndoStop();
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/extensions/common/extensions.js
/**
 * **!Do not construct directly!**
 *
 * **!Only static methods because it gets serialized!**
 *
 * This represents the "canonical" version for an extension identifier. Extension ids
 * have to be case-insensitive (due to the marketplace), but we must ensure case
 * preservation because the extension API is already public at this time.
 *
 * For example, given an extension with the publisher `"Hello"` and the name `"World"`,
 * its canonical extension identifier is `"Hello.World"`. This extension could be
 * referenced in some other extension's dependencies using the string `"hello.world"`.
 *
 * To make matters more complicated, an extension can optionally have an UUID. When two
 * extensions have the same UUID, they are considered equal even if their identifier is different.
 */
class ExtensionIdentifier {
    constructor(value) {
        this.value = value;
        this._lower = value.toLowerCase();
    }
    /**
     * Gives the value by which to index (for equality).
     */
    static toKey(id) {
        if (typeof id === 'string') {
            return id.toLowerCase();
        }
        return id._lower;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/format/browser/format.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var format_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};





















function alertFormattingEdits(edits) {
    edits = edits.filter(edit => edit.range);
    if (!edits.length) {
        return;
    }
    let { range } = edits[0];
    for (let i = 1; i < edits.length; i++) {
        range = Range.plusRange(range, edits[i].range);
    }
    const { startLineNumber, endLineNumber } = range;
    if (startLineNumber === endLineNumber) {
        if (edits.length === 1) {
            aria_alert(localize('hint11', "Made 1 formatting edit on line {0}", startLineNumber));
        }
        else {
            aria_alert(localize('hintn1', "Made {0} formatting edits on line {1}", edits.length, startLineNumber));
        }
    }
    else {
        if (edits.length === 1) {
            aria_alert(localize('hint1n', "Made 1 formatting edit between lines {0} and {1}", startLineNumber, endLineNumber));
        }
        else {
            aria_alert(localize('hintnn', "Made {0} formatting edits between lines {1} and {2}", edits.length, startLineNumber, endLineNumber));
        }
    }
}
function getRealAndSyntheticDocumentFormattersOrdered(documentFormattingEditProvider, documentRangeFormattingEditProvider, model) {
    const result = [];
    const seen = new Set();
    // (1) add all document formatter
    const docFormatter = documentFormattingEditProvider.ordered(model);
    for (const formatter of docFormatter) {
        result.push(formatter);
        if (formatter.extensionId) {
            seen.add(ExtensionIdentifier.toKey(formatter.extensionId));
        }
    }
    // (2) add all range formatter as document formatter (unless the same extension already did that)
    const rangeFormatter = documentRangeFormattingEditProvider.ordered(model);
    for (const formatter of rangeFormatter) {
        if (formatter.extensionId) {
            if (seen.has(ExtensionIdentifier.toKey(formatter.extensionId))) {
                continue;
            }
            seen.add(ExtensionIdentifier.toKey(formatter.extensionId));
        }
        result.push({
            displayName: formatter.displayName,
            extensionId: formatter.extensionId,
            provideDocumentFormattingEdits(model, options, token) {
                return formatter.provideDocumentRangeFormattingEdits(model, model.getFullModelRange(), options, token);
            }
        });
    }
    return result;
}
class FormattingConflicts {
    static setFormatterSelector(selector) {
        const remove = FormattingConflicts._selectors.unshift(selector);
        return { dispose: remove };
    }
    static select(formatter, document, mode) {
        return format_awaiter(this, void 0, void 0, function* () {
            if (formatter.length === 0) {
                return undefined;
            }
            const selector = Iterable.first(FormattingConflicts._selectors);
            if (selector) {
                return yield selector(formatter, document, mode);
            }
            return undefined;
        });
    }
}
FormattingConflicts._selectors = new LinkedList();
function formatDocumentRangesWithSelectedProvider(accessor, editorOrModel, rangeOrRanges, mode, progress, token) {
    return format_awaiter(this, void 0, void 0, function* () {
        const instaService = accessor.get(IInstantiationService);
        const { documentRangeFormattingEditProvider: documentRangeFormattingEditProviderRegistry } = accessor.get(ILanguageFeaturesService);
        const model = isCodeEditor(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
        const provider = documentRangeFormattingEditProviderRegistry.ordered(model);
        const selected = yield FormattingConflicts.select(provider, model, mode);
        if (selected) {
            progress.report(selected);
            yield instaService.invokeFunction(formatDocumentRangesWithProvider, selected, editorOrModel, rangeOrRanges, token);
        }
    });
}
function formatDocumentRangesWithProvider(accessor, provider, editorOrModel, rangeOrRanges, token) {
    return format_awaiter(this, void 0, void 0, function* () {
        const workerService = accessor.get(IEditorWorkerService);
        let model;
        let cts;
        if (isCodeEditor(editorOrModel)) {
            model = editorOrModel.getModel();
            cts = new EditorStateCancellationTokenSource(editorOrModel, 1 /* CodeEditorStateFlag.Value */ | 4 /* CodeEditorStateFlag.Position */, undefined, token);
        }
        else {
            model = editorOrModel;
            cts = new TextModelCancellationTokenSource(editorOrModel, token);
        }
        // make sure that ranges don't overlap nor touch each other
        const ranges = [];
        let len = 0;
        for (const range of asArray(rangeOrRanges).sort(Range.compareRangesUsingStarts)) {
            if (len > 0 && Range.areIntersectingOrTouching(ranges[len - 1], range)) {
                ranges[len - 1] = Range.fromPositions(ranges[len - 1].getStartPosition(), range.getEndPosition());
            }
            else {
                len = ranges.push(range);
            }
        }
        const computeEdits = (range) => format_awaiter(this, void 0, void 0, function* () {
            return (yield provider.provideDocumentRangeFormattingEdits(model, range, model.getFormattingOptions(), cts.token)) || [];
        });
        const hasIntersectingEdit = (a, b) => {
            if (!a.length || !b.length) {
                return false;
            }
            // quick exit if the list of ranges are completely unrelated [O(n)]
            const mergedA = a.reduce((acc, val) => { return Range.plusRange(acc, val.range); }, a[0].range);
            if (!b.some(x => { return Range.intersectRanges(mergedA, x.range); })) {
                return false;
            }
            // fallback to a complete check [O(n^2)]
            for (const edit of a) {
                for (const otherEdit of b) {
                    if (Range.intersectRanges(edit.range, otherEdit.range)) {
                        return true;
                    }
                }
            }
            return false;
        };
        const allEdits = [];
        const rawEditsList = [];
        try {
            for (const range of ranges) {
                if (cts.token.isCancellationRequested) {
                    return true;
                }
                rawEditsList.push(yield computeEdits(range));
            }
            for (let i = 0; i < ranges.length; ++i) {
                for (let j = i + 1; j < ranges.length; ++j) {
                    if (cts.token.isCancellationRequested) {
                        return true;
                    }
                    if (hasIntersectingEdit(rawEditsList[i], rawEditsList[j])) {
                        // Merge ranges i and j into a single range, recompute the associated edits
                        const mergedRange = Range.plusRange(ranges[i], ranges[j]);
                        const edits = yield computeEdits(mergedRange);
                        ranges.splice(j, 1);
                        ranges.splice(i, 1);
                        ranges.push(mergedRange);
                        rawEditsList.splice(j, 1);
                        rawEditsList.splice(i, 1);
                        rawEditsList.push(edits);
                        // Restart scanning
                        i = 0;
                        j = 0;
                    }
                }
            }
            for (const rawEdits of rawEditsList) {
                if (cts.token.isCancellationRequested) {
                    return true;
                }
                const minimalEdits = yield workerService.computeMoreMinimalEdits(model.uri, rawEdits);
                if (minimalEdits) {
                    allEdits.push(...minimalEdits);
                }
            }
        }
        finally {
            cts.dispose();
        }
        if (allEdits.length === 0) {
            return false;
        }
        if (isCodeEditor(editorOrModel)) {
            // use editor to apply edits
            FormattingEdit.execute(editorOrModel, allEdits, true);
            alertFormattingEdits(allEdits);
            editorOrModel.revealPositionInCenterIfOutsideViewport(editorOrModel.getPosition(), 1 /* ScrollType.Immediate */);
        }
        else {
            // use model to apply edits
            const [{ range }] = allEdits;
            const initialSelection = new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
            model.pushEditOperations([initialSelection], allEdits.map(edit => {
                return {
                    text: edit.text,
                    range: Range.lift(edit.range),
                    forceMoveMarkers: true
                };
            }), undoEdits => {
                for (const { range } of undoEdits) {
                    if (Range.areIntersectingOrTouching(range, initialSelection)) {
                        return [new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn)];
                    }
                }
                return null;
            });
        }
        return true;
    });
}
function formatDocumentWithSelectedProvider(accessor, editorOrModel, mode, progress, token) {
    return format_awaiter(this, void 0, void 0, function* () {
        const instaService = accessor.get(IInstantiationService);
        const languageFeaturesService = accessor.get(ILanguageFeaturesService);
        const model = isCodeEditor(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
        const provider = getRealAndSyntheticDocumentFormattersOrdered(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
        const selected = yield FormattingConflicts.select(provider, model, mode);
        if (selected) {
            progress.report(selected);
            yield instaService.invokeFunction(formatDocumentWithProvider, selected, editorOrModel, mode, token);
        }
    });
}
function formatDocumentWithProvider(accessor, provider, editorOrModel, mode, token) {
    return format_awaiter(this, void 0, void 0, function* () {
        const workerService = accessor.get(IEditorWorkerService);
        let model;
        let cts;
        if (isCodeEditor(editorOrModel)) {
            model = editorOrModel.getModel();
            cts = new EditorStateCancellationTokenSource(editorOrModel, 1 /* CodeEditorStateFlag.Value */ | 4 /* CodeEditorStateFlag.Position */, undefined, token);
        }
        else {
            model = editorOrModel;
            cts = new TextModelCancellationTokenSource(editorOrModel, token);
        }
        let edits;
        try {
            const rawEdits = yield provider.provideDocumentFormattingEdits(model, model.getFormattingOptions(), cts.token);
            edits = yield workerService.computeMoreMinimalEdits(model.uri, rawEdits);
            if (cts.token.isCancellationRequested) {
                return true;
            }
        }
        finally {
            cts.dispose();
        }
        if (!edits || edits.length === 0) {
            return false;
        }
        if (isCodeEditor(editorOrModel)) {
            // use editor to apply edits
            FormattingEdit.execute(editorOrModel, edits, mode !== 2 /* FormattingMode.Silent */);
            if (mode !== 2 /* FormattingMode.Silent */) {
                alertFormattingEdits(edits);
                editorOrModel.revealPositionInCenterIfOutsideViewport(editorOrModel.getPosition(), 1 /* ScrollType.Immediate */);
            }
        }
        else {
            // use model to apply edits
            const [{ range }] = edits;
            const initialSelection = new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
            model.pushEditOperations([initialSelection], edits.map(edit => {
                return {
                    text: edit.text,
                    range: Range.lift(edit.range),
                    forceMoveMarkers: true
                };
            }), undoEdits => {
                for (const { range } of undoEdits) {
                    if (Range.areIntersectingOrTouching(range, initialSelection)) {
                        return [new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn)];
                    }
                }
                return null;
            });
        }
        return true;
    });
}
function getDocumentRangeFormattingEditsUntilResult(workerService, languageFeaturesService, model, range, options, token) {
    return format_awaiter(this, void 0, void 0, function* () {
        const providers = languageFeaturesService.documentRangeFormattingEditProvider.ordered(model);
        for (const provider of providers) {
            const rawEdits = yield Promise.resolve(provider.provideDocumentRangeFormattingEdits(model, range, options, token)).catch(onUnexpectedExternalError);
            if (isNonEmptyArray(rawEdits)) {
                return yield workerService.computeMoreMinimalEdits(model.uri, rawEdits);
            }
        }
        return undefined;
    });
}
function getDocumentFormattingEditsUntilResult(workerService, languageFeaturesService, model, options, token) {
    return format_awaiter(this, void 0, void 0, function* () {
        const providers = getRealAndSyntheticDocumentFormattersOrdered(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
        for (const provider of providers) {
            const rawEdits = yield Promise.resolve(provider.provideDocumentFormattingEdits(model, options, token)).catch(onUnexpectedExternalError);
            if (isNonEmptyArray(rawEdits)) {
                return yield workerService.computeMoreMinimalEdits(model.uri, rawEdits);
            }
        }
        return undefined;
    });
}
function getOnTypeFormattingEdits(workerService, languageFeaturesService, model, position, ch, options, token) {
    const providers = languageFeaturesService.onTypeFormattingEditProvider.ordered(model);
    if (providers.length === 0) {
        return Promise.resolve(undefined);
    }
    if (providers[0].autoFormatTriggerCharacters.indexOf(ch) < 0) {
        return Promise.resolve(undefined);
    }
    return Promise.resolve(providers[0].provideOnTypeFormattingEdits(model, position, ch, options, token)).catch(onUnexpectedExternalError).then(edits => {
        return workerService.computeMoreMinimalEdits(model.uri, edits);
    });
}
CommandsRegistry.registerCommand('_executeFormatRangeProvider', function (accessor, ...args) {
    return format_awaiter(this, void 0, void 0, function* () {
        const [resource, range, options] = args;
        assertType(URI.isUri(resource));
        assertType(Range.isIRange(range));
        const resolverService = accessor.get(ITextModelService);
        const workerService = accessor.get(IEditorWorkerService);
        const languageFeaturesService = accessor.get(ILanguageFeaturesService);
        const reference = yield resolverService.createModelReference(resource);
        try {
            return getDocumentRangeFormattingEditsUntilResult(workerService, languageFeaturesService, reference.object.textEditorModel, Range.lift(range), options, CancellationToken.None);
        }
        finally {
            reference.dispose();
        }
    });
});
CommandsRegistry.registerCommand('_executeFormatDocumentProvider', function (accessor, ...args) {
    return format_awaiter(this, void 0, void 0, function* () {
        const [resource, options] = args;
        assertType(URI.isUri(resource));
        const resolverService = accessor.get(ITextModelService);
        const workerService = accessor.get(IEditorWorkerService);
        const languageFeaturesService = accessor.get(ILanguageFeaturesService);
        const reference = yield resolverService.createModelReference(resource);
        try {
            return getDocumentFormattingEditsUntilResult(workerService, languageFeaturesService, reference.object.textEditorModel, options, CancellationToken.None);
        }
        finally {
            reference.dispose();
        }
    });
});
CommandsRegistry.registerCommand('_executeFormatOnTypeProvider', function (accessor, ...args) {
    return format_awaiter(this, void 0, void 0, function* () {
        const [resource, position, ch, options] = args;
        assertType(URI.isUri(resource));
        assertType(Position.isIPosition(position));
        assertType(typeof ch === 'string');
        const resolverService = accessor.get(ITextModelService);
        const workerService = accessor.get(IEditorWorkerService);
        const languageFeaturesService = accessor.get(ILanguageFeaturesService);
        const reference = yield resolverService.createModelReference(resource);
        try {
            return getOnTypeFormattingEdits(workerService, languageFeaturesService, reference.object.textEditorModel, Position.lift(position), ch, options, CancellationToken.None);
        }
        finally {
            reference.dispose();
        }
    });
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/format/browser/formatActions.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var formatActions_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var formatActions_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var formatActions_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};



















let FormatOnType = class FormatOnType {
    constructor(_editor, _languageFeaturesService, _workerService) {
        this._editor = _editor;
        this._languageFeaturesService = _languageFeaturesService;
        this._workerService = _workerService;
        this._disposables = new DisposableStore();
        this._sessionDisposables = new DisposableStore();
        this._disposables.add(_languageFeaturesService.onTypeFormattingEditProvider.onDidChange(this._update, this));
        this._disposables.add(_editor.onDidChangeModel(() => this._update()));
        this._disposables.add(_editor.onDidChangeModelLanguage(() => this._update()));
        this._disposables.add(_editor.onDidChangeConfiguration(e => {
            if (e.hasChanged(51 /* EditorOption.formatOnType */)) {
                this._update();
            }
        }));
    }
    dispose() {
        this._disposables.dispose();
        this._sessionDisposables.dispose();
    }
    _update() {
        // clean up
        this._sessionDisposables.clear();
        // we are disabled
        if (!this._editor.getOption(51 /* EditorOption.formatOnType */)) {
            return;
        }
        // no model
        if (!this._editor.hasModel()) {
            return;
        }
        const model = this._editor.getModel();
        // no support
        const [support] = this._languageFeaturesService.onTypeFormattingEditProvider.ordered(model);
        if (!support || !support.autoFormatTriggerCharacters) {
            return;
        }
        // register typing listeners that will trigger the format
        const triggerChars = new CharacterSet();
        for (const ch of support.autoFormatTriggerCharacters) {
            triggerChars.add(ch.charCodeAt(0));
        }
        this._sessionDisposables.add(this._editor.onDidType((text) => {
            const lastCharCode = text.charCodeAt(text.length - 1);
            if (triggerChars.has(lastCharCode)) {
                this._trigger(String.fromCharCode(lastCharCode));
            }
        }));
    }
    _trigger(ch) {
        if (!this._editor.hasModel()) {
            return;
        }
        if (this._editor.getSelections().length > 1 || !this._editor.getSelection().isEmpty()) {
            return;
        }
        const model = this._editor.getModel();
        const position = this._editor.getPosition();
        const cts = new CancellationTokenSource();
        // install a listener that checks if edits happens before the
        // position on which we format right now. If so, we won't
        // apply the format edits
        const unbind = this._editor.onDidChangeModelContent((e) => {
            if (e.isFlush) {
                // a model.setValue() was called
                // cancel only once
                cts.cancel();
                unbind.dispose();
                return;
            }
            for (let i = 0, len = e.changes.length; i < len; i++) {
                const change = e.changes[i];
                if (change.range.endLineNumber <= position.lineNumber) {
                    // cancel only once
                    cts.cancel();
                    unbind.dispose();
                    return;
                }
            }
        });
        getOnTypeFormattingEdits(this._workerService, this._languageFeaturesService, model, position, ch, model.getFormattingOptions(), cts.token).then(edits => {
            if (cts.token.isCancellationRequested) {
                return;
            }
            if (isNonEmptyArray(edits)) {
                FormattingEdit.execute(this._editor, edits, true);
                alertFormattingEdits(edits);
            }
        }).finally(() => {
            unbind.dispose();
        });
    }
};
FormatOnType.ID = 'editor.contrib.autoFormat';
FormatOnType = formatActions_decorate([
    formatActions_param(1, ILanguageFeaturesService),
    formatActions_param(2, IEditorWorkerService)
], FormatOnType);
let FormatOnPaste = class FormatOnPaste {
    constructor(editor, _languageFeaturesService, _instantiationService) {
        this.editor = editor;
        this._languageFeaturesService = _languageFeaturesService;
        this._instantiationService = _instantiationService;
        this._callOnDispose = new DisposableStore();
        this._callOnModel = new DisposableStore();
        this._callOnDispose.add(editor.onDidChangeConfiguration(() => this._update()));
        this._callOnDispose.add(editor.onDidChangeModel(() => this._update()));
        this._callOnDispose.add(editor.onDidChangeModelLanguage(() => this._update()));
        this._callOnDispose.add(_languageFeaturesService.documentRangeFormattingEditProvider.onDidChange(this._update, this));
    }
    dispose() {
        this._callOnDispose.dispose();
        this._callOnModel.dispose();
    }
    _update() {
        // clean up
        this._callOnModel.clear();
        // we are disabled
        if (!this.editor.getOption(50 /* EditorOption.formatOnPaste */)) {
            return;
        }
        // no model
        if (!this.editor.hasModel()) {
            return;
        }
        // no formatter
        if (!this._languageFeaturesService.documentRangeFormattingEditProvider.has(this.editor.getModel())) {
            return;
        }
        this._callOnModel.add(this.editor.onDidPaste(({ range }) => this._trigger(range)));
    }
    _trigger(range) {
        if (!this.editor.hasModel()) {
            return;
        }
        if (this.editor.getSelections().length > 1) {
            return;
        }
        this._instantiationService.invokeFunction(formatDocumentRangesWithSelectedProvider, this.editor, range, 2 /* FormattingMode.Silent */, Progress.None, CancellationToken.None).catch(onUnexpectedError);
    }
};
FormatOnPaste.ID = 'editor.contrib.formatOnPaste';
FormatOnPaste = formatActions_decorate([
    formatActions_param(1, ILanguageFeaturesService),
    formatActions_param(2, IInstantiationService)
], FormatOnPaste);
class FormatDocumentAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.formatDocument',
            label: localize('formatDocument.label', "Format Document"),
            alias: 'Format Document',
            precondition: ContextKeyExpr.and(EditorContextKeys.notInCompositeEditor, EditorContextKeys.writable, EditorContextKeys.hasDocumentFormattingProvider),
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 36 /* KeyCode.KeyF */,
                linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 39 /* KeyCode.KeyI */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            contextMenuOpts: {
                group: '1_modification',
                order: 1.3
            }
        });
    }
    run(accessor, editor) {
        return formatActions_awaiter(this, void 0, void 0, function* () {
            if (editor.hasModel()) {
                const instaService = accessor.get(IInstantiationService);
                const progressService = accessor.get(IEditorProgressService);
                yield progressService.showWhile(instaService.invokeFunction(formatDocumentWithSelectedProvider, editor, 1 /* FormattingMode.Explicit */, Progress.None, CancellationToken.None), 250);
            }
        });
    }
}
class FormatSelectionAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.formatSelection',
            label: localize('formatSelection.label', "Format Selection"),
            alias: 'Format Selection',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasDocumentSelectionFormattingProvider),
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 36 /* KeyCode.KeyF */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            contextMenuOpts: {
                when: EditorContextKeys.hasNonEmptySelection,
                group: '1_modification',
                order: 1.31
            }
        });
    }
    run(accessor, editor) {
        return formatActions_awaiter(this, void 0, void 0, function* () {
            if (!editor.hasModel()) {
                return;
            }
            const instaService = accessor.get(IInstantiationService);
            const model = editor.getModel();
            const ranges = editor.getSelections().map(range => {
                return range.isEmpty()
                    ? new Range(range.startLineNumber, 1, range.startLineNumber, model.getLineMaxColumn(range.startLineNumber))
                    : range;
            });
            const progressService = accessor.get(IEditorProgressService);
            yield progressService.showWhile(instaService.invokeFunction(formatDocumentRangesWithSelectedProvider, editor, ranges, 1 /* FormattingMode.Explicit */, Progress.None, CancellationToken.None), 250);
        });
    }
}
registerEditorContribution(FormatOnType.ID, FormatOnType);
registerEditorContribution(FormatOnPaste.ID, FormatOnPaste);
registerEditorAction(FormatDocumentAction);
registerEditorAction(FormatSelectionAction);
// this is the old format action that does both (format document OR format selection)
// and we keep it here such that existing keybinding configurations etc will still work
CommandsRegistry.registerCommand('editor.action.format', (accessor) => formatActions_awaiter(void 0, void 0, void 0, function* () {
    const editor = accessor.get(ICodeEditorService).getFocusedCodeEditor();
    if (!editor || !editor.hasModel()) {
        return;
    }
    const commandService = accessor.get(ICommandService);
    if (editor.getSelection().isEmpty()) {
        yield commandService.executeCommand('editor.action.formatDocument');
    }
    else {
        yield commandService.executeCommand('editor.action.formatSelection');
    }
}));

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/quickAccess/browser/editorNavigationQuickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







/**
 * A reusable quick access provider for the editor with support
 * for adding decorations for navigating in the currently active file
 * (for example "Go to line", "Go to symbol").
 */
class AbstractEditorNavigationQuickAccessProvider {
    constructor(options) {
        this.options = options;
        //#endregion
        //#region Decorations Utils
        this.rangeHighlightDecorationId = undefined;
    }
    //#region Provider methods
    provide(picker, token) {
        var _a;
        const disposables = new DisposableStore();
        // Apply options if any
        picker.canAcceptInBackground = !!((_a = this.options) === null || _a === void 0 ? void 0 : _a.canAcceptInBackground);
        // Disable filtering & sorting, we control the results
        picker.matchOnLabel = picker.matchOnDescription = picker.matchOnDetail = picker.sortByLabel = false;
        // Provide based on current active editor
        const pickerDisposable = disposables.add(new MutableDisposable());
        pickerDisposable.value = this.doProvide(picker, token);
        // Re-create whenever the active editor changes
        disposables.add(this.onDidActiveTextEditorControlChange(() => {
            // Clear old
            pickerDisposable.value = undefined;
            // Add new
            pickerDisposable.value = this.doProvide(picker, token);
        }));
        return disposables;
    }
    doProvide(picker, token) {
        const disposables = new DisposableStore();
        // With text control
        const editor = this.activeTextEditorControl;
        if (editor && this.canProvideWithTextEditor(editor)) {
            const context = { editor };
            // Restore any view state if this picker was closed
            // without actually going to a line
            const codeEditor = getCodeEditor(editor);
            if (codeEditor) {
                // Remember view state and update it when the cursor position
                // changes even later because it could be that the user has
                // configured quick access to remain open when focus is lost and
                // we always want to restore the current location.
                let lastKnownEditorViewState = withNullAsUndefined(editor.saveViewState());
                disposables.add(codeEditor.onDidChangeCursorPosition(() => {
                    lastKnownEditorViewState = withNullAsUndefined(editor.saveViewState());
                }));
                context.restoreViewState = () => {
                    if (lastKnownEditorViewState && editor === this.activeTextEditorControl) {
                        editor.restoreViewState(lastKnownEditorViewState);
                    }
                };
                disposables.add(once(token.onCancellationRequested)(() => { var _a; return (_a = context.restoreViewState) === null || _a === void 0 ? void 0 : _a.call(context); }));
            }
            // Clean up decorations on dispose
            disposables.add(toDisposable(() => this.clearDecorations(editor)));
            // Ask subclass for entries
            disposables.add(this.provideWithTextEditor(context, picker, token));
        }
        // Without text control
        else {
            disposables.add(this.provideWithoutTextEditor(picker, token));
        }
        return disposables;
    }
    /**
     * Subclasses to implement if they can operate on the text editor.
     */
    canProvideWithTextEditor(editor) {
        return true;
    }
    gotoLocation({ editor }, options) {
        editor.setSelection(options.range);
        editor.revealRangeInCenter(options.range, 0 /* ScrollType.Smooth */);
        if (!options.preserveFocus) {
            editor.focus();
        }
    }
    getModel(editor) {
        var _a;
        return isDiffEditor(editor) ?
            (_a = editor.getModel()) === null || _a === void 0 ? void 0 : _a.modified :
            editor.getModel();
    }
    addDecorations(editor, range) {
        editor.changeDecorations(changeAccessor => {
            // Reset old decorations if any
            const deleteDecorations = [];
            if (this.rangeHighlightDecorationId) {
                deleteDecorations.push(this.rangeHighlightDecorationId.overviewRulerDecorationId);
                deleteDecorations.push(this.rangeHighlightDecorationId.rangeHighlightId);
                this.rangeHighlightDecorationId = undefined;
            }
            // Add new decorations for the range
            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: themeColorFromId(overviewRulerRangeHighlight),
                            position: OverviewRulerLane.Full
                        }
                    }
                }
            ];
            const [rangeHighlightId, overviewRulerDecorationId] = changeAccessor.deltaDecorations(deleteDecorations, newDecorations);
            this.rangeHighlightDecorationId = { rangeHighlightId, overviewRulerDecorationId };
        });
    }
    clearDecorations(editor) {
        const rangeHighlightDecorationId = this.rangeHighlightDecorationId;
        if (rangeHighlightDecorationId) {
            editor.changeDecorations(changeAccessor => {
                changeAccessor.deltaDecorations([
                    rangeHighlightDecorationId.overviewRulerDecorationId,
                    rangeHighlightDecorationId.rangeHighlightId
                ], []);
            });
            this.rangeHighlightDecorationId = undefined;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/quickAccess/browser/gotoLineQuickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class AbstractGotoLineQuickAccessProvider extends AbstractEditorNavigationQuickAccessProvider {
    constructor() {
        super({ canAcceptInBackground: true });
    }
    provideWithoutTextEditor(picker) {
        const label = localize('cannotRunGotoLine', "Open a text editor first to go to a line.");
        picker.items = [{ label }];
        picker.ariaLabel = label;
        return Disposable.None;
    }
    provideWithTextEditor(context, picker, token) {
        const editor = context.editor;
        const disposables = new DisposableStore();
        // Goto line once picked
        disposables.add(picker.onDidAccept(event => {
            const [item] = picker.selectedItems;
            if (item) {
                if (!this.isValidLineNumber(editor, item.lineNumber)) {
                    return;
                }
                this.gotoLocation(context, { range: this.toRange(item.lineNumber, item.column), keyMods: picker.keyMods, preserveFocus: event.inBackground });
                if (!event.inBackground) {
                    picker.hide();
                }
            }
        }));
        // React to picker changes
        const updatePickerAndEditor = () => {
            const position = this.parsePosition(editor, picker.value.trim().substr(AbstractGotoLineQuickAccessProvider.PREFIX.length));
            const label = this.getPickLabel(editor, position.lineNumber, position.column);
            // Picker
            picker.items = [{
                    lineNumber: position.lineNumber,
                    column: position.column,
                    label
                }];
            // ARIA Label
            picker.ariaLabel = label;
            // Clear decorations for invalid range
            if (!this.isValidLineNumber(editor, position.lineNumber)) {
                this.clearDecorations(editor);
                return;
            }
            // Reveal
            const range = this.toRange(position.lineNumber, position.column);
            editor.revealRangeInCenter(range, 0 /* ScrollType.Smooth */);
            // Decorate
            this.addDecorations(editor, range);
        };
        updatePickerAndEditor();
        disposables.add(picker.onDidChangeValue(() => updatePickerAndEditor()));
        // Adjust line number visibility as needed
        const codeEditor = getCodeEditor(editor);
        if (codeEditor) {
            const options = codeEditor.getOptions();
            const lineNumbers = options.get(62 /* EditorOption.lineNumbers */);
            if (lineNumbers.renderType === 2 /* RenderLineNumbersType.Relative */) {
                codeEditor.updateOptions({ lineNumbers: 'on' });
                disposables.add(toDisposable(() => codeEditor.updateOptions({ lineNumbers: 'relative' })));
            }
        }
        return disposables;
    }
    toRange(lineNumber = 1, column = 1) {
        return {
            startLineNumber: lineNumber,
            startColumn: column,
            endLineNumber: lineNumber,
            endColumn: column
        };
    }
    parsePosition(editor, value) {
        // Support line-col formats of `line,col`, `line:col`, `line#col`
        const numbers = value.split(/,|:|#/).map(part => parseInt(part, 10)).filter(part => !isNaN(part));
        const endLine = this.lineCount(editor) + 1;
        return {
            lineNumber: numbers[0] > 0 ? numbers[0] : endLine + numbers[0],
            column: numbers[1]
        };
    }
    getPickLabel(editor, lineNumber, column) {
        // Location valid: indicate this as picker label
        if (this.isValidLineNumber(editor, lineNumber)) {
            if (this.isValidColumn(editor, lineNumber, column)) {
                return localize('gotoLineColumnLabel', "Go to line {0} and character {1}.", lineNumber, column);
            }
            return localize('gotoLineLabel', "Go to line {0}.", lineNumber);
        }
        // Location invalid: show generic label
        const position = editor.getPosition() || { lineNumber: 1, column: 1 };
        const lineCount = this.lineCount(editor);
        if (lineCount > 1) {
            return localize('gotoLineLabelEmptyWithLimit', "Current Line: {0}, Character: {1}. Type a line number between 1 and {2} to navigate to.", position.lineNumber, position.column, lineCount);
        }
        return localize('gotoLineLabelEmpty', "Current Line: {0}, Character: {1}. Type a line number to navigate to.", position.lineNumber, position.column);
    }
    isValidLineNumber(editor, lineNumber) {
        if (!lineNumber || typeof lineNumber !== 'number') {
            return false;
        }
        return lineNumber > 0 && lineNumber <= this.lineCount(editor);
    }
    isValidColumn(editor, lineNumber, column) {
        if (!column || typeof column !== 'number') {
            return false;
        }
        const model = this.getModel(editor);
        if (!model) {
            return false;
        }
        const positionCandidate = { lineNumber, column };
        return model.validatePosition(positionCandidate).equals(positionCandidate);
    }
    lineCount(editor) {
        var _a, _b;
        return (_b = (_a = this.getModel(editor)) === null || _a === void 0 ? void 0 : _a.getLineCount()) !== null && _b !== void 0 ? _b : 0;
    }
}
AbstractGotoLineQuickAccessProvider.PREFIX = ':';

;// ../../node_modules/monaco-editor/esm/vs/platform/quickinput/common/quickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



var DefaultQuickAccessFilterValue;
(function (DefaultQuickAccessFilterValue) {
    /**
     * Keep the value as it is given to quick access.
     */
    DefaultQuickAccessFilterValue[DefaultQuickAccessFilterValue["PRESERVE"] = 0] = "PRESERVE";
    /**
     * Use the value that was used last time something was accepted from the picker.
     */
    DefaultQuickAccessFilterValue[DefaultQuickAccessFilterValue["LAST"] = 1] = "LAST";
})(DefaultQuickAccessFilterValue || (DefaultQuickAccessFilterValue = {}));
const quickAccess_Extensions = {
    Quickaccess: 'workbench.contributions.quickaccess'
};
class QuickAccessRegistry {
    constructor() {
        this.providers = [];
        this.defaultProvider = undefined;
    }
    registerQuickAccessProvider(provider) {
        // Extract the default provider when no prefix is present
        if (provider.prefix.length === 0) {
            this.defaultProvider = provider;
        }
        else {
            this.providers.push(provider);
        }
        // sort the providers by decreasing prefix length, such that longer
        // prefixes take priority: 'ext' vs 'ext install' - the latter should win
        this.providers.sort((providerA, providerB) => providerB.prefix.length - providerA.prefix.length);
        return toDisposable(() => {
            this.providers.splice(this.providers.indexOf(provider), 1);
            if (this.defaultProvider === provider) {
                this.defaultProvider = undefined;
            }
        });
    }
    getQuickAccessProviders() {
        return coalesce([this.defaultProvider, ...this.providers]);
    }
    getQuickAccessProvider(prefix) {
        const result = prefix ? (this.providers.find(provider => prefix.startsWith(provider.prefix)) || undefined) : undefined;
        return result || this.defaultProvider;
    }
}
Registry.add(quickAccess_Extensions.Quickaccess, new QuickAccessRegistry());

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickAccess/standaloneGotoLineQuickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var standaloneGotoLineQuickAccess_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var standaloneGotoLineQuickAccess_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};










let StandaloneGotoLineQuickAccessProvider = class StandaloneGotoLineQuickAccessProvider extends AbstractGotoLineQuickAccessProvider {
    constructor(editorService) {
        super();
        this.editorService = editorService;
        this.onDidActiveTextEditorControlChange = Event.None;
    }
    get activeTextEditorControl() {
        return withNullAsUndefined(this.editorService.getFocusedCodeEditor());
    }
};
StandaloneGotoLineQuickAccessProvider = standaloneGotoLineQuickAccess_decorate([
    standaloneGotoLineQuickAccess_param(0, ICodeEditorService)
], StandaloneGotoLineQuickAccessProvider);

class GotoLineAction extends EditorAction {
    constructor() {
        super({
            id: GotoLineAction.ID,
            label: GoToLineNLS.gotoLineActionLabel,
            alias: 'Go to Line/Column...',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 37 /* KeyCode.KeyG */,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 37 /* KeyCode.KeyG */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor) {
        accessor.get(IQuickInputService).quickAccess.show(StandaloneGotoLineQuickAccessProvider.PREFIX);
    }
}
GotoLineAction.ID = 'editor.action.gotoLine';
registerEditorAction(GotoLineAction);
Registry.as(quickAccess_Extensions.Quickaccess).registerQuickAccessProvider({
    ctor: StandaloneGotoLineQuickAccessProvider,
    prefix: StandaloneGotoLineQuickAccessProvider.PREFIX,
    helpEntries: [{ description: GoToLineNLS.gotoLineActionLabel, commandId: GotoLineAction.ID }]
});

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard.css
var iPadShowKeyboard = __webpack_require__(10660);
;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard.css

      
      
      
      
      
      
      
      
      

var iPadShowKeyboard_options = {};

iPadShowKeyboard_options.styleTagTransform = (styleTagTransform_default());
iPadShowKeyboard_options.setAttributes = (setAttributesWithoutAttributes_default());

      iPadShowKeyboard_options.insert = insertBySelector_default().bind(null, "head");
    
iPadShowKeyboard_options.domAPI = (styleDomAPI_default());
iPadShowKeyboard_options.insertStyleElement = (insertStyleElement_default());

var iPadShowKeyboard_update = injectStylesIntoStyleTag_default()(iPadShowKeyboard/* default */.A, iPadShowKeyboard_options);




       /* harmony default export */ const iPadShowKeyboard_iPadShowKeyboard = (iPadShowKeyboard/* default */.A && iPadShowKeyboard/* default */.A.locals ? iPadShowKeyboard/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class IPadShowKeyboard extends Disposable {
    constructor(editor) {
        super();
        this.editor = editor;
        this.widget = null;
        if (isIOS) {
            this._register(editor.onDidChangeConfiguration(() => this.update()));
            this.update();
        }
    }
    update() {
        const shouldHaveWidget = (!this.editor.getOption(83 /* EditorOption.readOnly */));
        if (!this.widget && shouldHaveWidget) {
            this.widget = new ShowKeyboardWidget(this.editor);
        }
        else if (this.widget && !shouldHaveWidget) {
            this.widget.dispose();
            this.widget = null;
        }
    }
    dispose() {
        super.dispose();
        if (this.widget) {
            this.widget.dispose();
            this.widget = null;
        }
    }
}
IPadShowKeyboard.ID = 'editor.contrib.iPadShowKeyboard';
class ShowKeyboardWidget extends Disposable {
    constructor(editor) {
        super();
        this.editor = editor;
        this._domNode = document.createElement('textarea');
        this._domNode.className = 'iPadShowKeyboard';
        this._register(addDisposableListener(this._domNode, 'touchstart', (e) => {
            this.editor.focus();
        }));
        this._register(addDisposableListener(this._domNode, 'focus', (e) => {
            this.editor.focus();
        }));
        this.editor.addOverlayWidget(this);
    }
    dispose() {
        this.editor.removeOverlayWidget(this);
        super.dispose();
    }
    // ----- IOverlayWidget API
    getId() {
        return ShowKeyboardWidget.ID;
    }
    getDomNode() {
        return this._domNode;
    }
    getPosition() {
        return {
            preference: 1 /* OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER */
        };
    }
}
ShowKeyboardWidget.ID = 'editor.contrib.ShowKeyboardWidget';
registerEditorContribution(IPadShowKeyboard.ID, IPadShowKeyboard);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inPlaceReplace/browser/inPlaceReplaceCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class InPlaceReplaceCommand {
    constructor(editRange, originalSelection, text) {
        this._editRange = editRange;
        this._originalSelection = originalSelection;
        this._text = text;
    }
    getEditOperations(model, builder) {
        builder.addTrackedEditOperation(this._editRange, this._text);
    }
    computeCursorState(model, helper) {
        const inverseEditOperations = helper.getInverseEditOperations();
        const srcRange = inverseEditOperations[0].range;
        if (!this._originalSelection.isEmpty()) {
            // Preserve selection and extends to typed text
            return new Selection(srcRange.endLineNumber, srcRange.endColumn - this._text.length, srcRange.endLineNumber, srcRange.endColumn);
        }
        return new Selection(srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn), srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn));
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inPlaceReplace/browser/inPlaceReplace.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var inPlaceReplace_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var inPlaceReplace_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};













let InPlaceReplaceController = class InPlaceReplaceController {
    constructor(editor, editorWorkerService) {
        this.editor = editor;
        this.editorWorkerService = editorWorkerService;
        this.decorations = this.editor.createDecorationsCollection();
    }
    static get(editor) {
        return editor.getContribution(InPlaceReplaceController.ID);
    }
    dispose() {
    }
    run(source, up) {
        // cancel any pending request
        if (this.currentRequest) {
            this.currentRequest.cancel();
        }
        const editorSelection = this.editor.getSelection();
        const model = this.editor.getModel();
        if (!model || !editorSelection) {
            return undefined;
        }
        let selection = editorSelection;
        if (selection.startLineNumber !== selection.endLineNumber) {
            // Can't accept multiline selection
            return undefined;
        }
        const state = new EditorState(this.editor, 1 /* CodeEditorStateFlag.Value */ | 4 /* CodeEditorStateFlag.Position */);
        const modelURI = model.uri;
        if (!this.editorWorkerService.canNavigateValueSet(modelURI)) {
            return Promise.resolve(undefined);
        }
        this.currentRequest = createCancelablePromise(token => this.editorWorkerService.navigateValueSet(modelURI, selection, up));
        return this.currentRequest.then(result => {
            if (!result || !result.range || !result.value) {
                // No proper result
                return;
            }
            if (!state.validate(this.editor)) {
                // state has changed
                return;
            }
            // Selection
            const editRange = Range.lift(result.range);
            let highlightRange = result.range;
            const diff = result.value.length - (selection.endColumn - selection.startColumn);
            // highlight
            highlightRange = {
                startLineNumber: highlightRange.startLineNumber,
                startColumn: highlightRange.startColumn,
                endLineNumber: highlightRange.endLineNumber,
                endColumn: highlightRange.startColumn + result.value.length
            };
            if (diff > 1) {
                selection = new Selection(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn + diff - 1);
            }
            // Insert new text
            const command = new InPlaceReplaceCommand(editRange, selection, result.value);
            this.editor.pushUndoStop();
            this.editor.executeCommand(source, command);
            this.editor.pushUndoStop();
            // add decoration
            this.decorations.set([{
                    range: highlightRange,
                    options: InPlaceReplaceController.DECORATION
                }]);
            // remove decoration after delay
            if (this.decorationRemover) {
                this.decorationRemover.cancel();
            }
            this.decorationRemover = timeout(350);
            this.decorationRemover.then(() => this.decorations.clear()).catch(onUnexpectedError);
        }).catch(onUnexpectedError);
    }
};
InPlaceReplaceController.ID = 'editor.contrib.inPlaceReplaceController';
InPlaceReplaceController.DECORATION = ModelDecorationOptions.register({
    description: 'in-place-replace',
    className: 'valueSetReplacement'
});
InPlaceReplaceController = inPlaceReplace_decorate([
    inPlaceReplace_param(1, IEditorWorkerService)
], InPlaceReplaceController);
class InPlaceReplaceUp extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.inPlaceReplace.up',
            label: localize('InPlaceReplaceAction.previous.label', "Replace with Previous Value"),
            alias: 'Replace with Previous Value',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 82 /* KeyCode.Comma */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        const controller = InPlaceReplaceController.get(editor);
        if (!controller) {
            return Promise.resolve(undefined);
        }
        return controller.run(this.id, true);
    }
}
class InPlaceReplaceDown extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.inPlaceReplace.down',
            label: localize('InPlaceReplaceAction.next.label', "Replace with Next Value"),
            alias: 'Replace with Next Value',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 84 /* KeyCode.Period */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        const controller = InPlaceReplaceController.get(editor);
        if (!controller) {
            return Promise.resolve(undefined);
        }
        return controller.run(this.id, false);
    }
}
registerEditorContribution(InPlaceReplaceController.ID, InPlaceReplaceController);
registerEditorAction(InPlaceReplaceUp);
registerEditorAction(InPlaceReplaceDown);
registerThemingParticipant((theme, collector) => {
    const border = theme.getColor(editorBracketMatchBorder);
    if (border) {
        collector.addRule(`.monaco-editor.vs .valueSetReplacement { outline: solid 2px ${border}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/indentation/browser/indentUtils.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
function getSpaceCnt(str, tabSize) {
    let spacesCnt = 0;
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) === '\t') {
            spacesCnt += tabSize;
        }
        else {
            spacesCnt++;
        }
    }
    return spacesCnt;
}
function generateIndent(spacesCnt, tabSize, insertSpaces) {
    spacesCnt = spacesCnt < 0 ? 0 : spacesCnt;
    let result = '';
    if (!insertSpaces) {
        const tabsCnt = Math.floor(spacesCnt / tabSize);
        spacesCnt = spacesCnt % tabSize;
        for (let i = 0; i < tabsCnt; i++) {
            result += '\t';
        }
    }
    for (let i = 0; i < spacesCnt; i++) {
        result += ' ';
    }
    return result;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/indentation/browser/indentation.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var indentation_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var indentation_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};















function getReindentEditOperations(model, languageConfigurationService, startLineNumber, endLineNumber, inheritedIndent) {
    if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
        // Model is empty
        return [];
    }
    const indentationRules = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentationRules;
    if (!indentationRules) {
        return [];
    }
    endLineNumber = Math.min(endLineNumber, model.getLineCount());
    // Skip `unIndentedLinePattern` lines
    while (startLineNumber <= endLineNumber) {
        if (!indentationRules.unIndentedLinePattern) {
            break;
        }
        const text = model.getLineContent(startLineNumber);
        if (!indentationRules.unIndentedLinePattern.test(text)) {
            break;
        }
        startLineNumber++;
    }
    if (startLineNumber > endLineNumber - 1) {
        return [];
    }
    const { tabSize, indentSize, insertSpaces } = model.getOptions();
    const shiftIndent = (indentation, count) => {
        count = count || 1;
        return ShiftCommand.shiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
    };
    const unshiftIndent = (indentation, count) => {
        count = count || 1;
        return ShiftCommand.unshiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
    };
    const indentEdits = [];
    // indentation being passed to lines below
    let globalIndent;
    // Calculate indentation for the first line
    // If there is no passed-in indentation, we use the indentation of the first line as base.
    const currentLineText = model.getLineContent(startLineNumber);
    let adjustedLineContent = currentLineText;
    if (inheritedIndent !== undefined && inheritedIndent !== null) {
        globalIndent = inheritedIndent;
        const oldIndentation = getLeadingWhitespace(currentLineText);
        adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length);
        if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent)) {
            globalIndent = unshiftIndent(globalIndent);
            adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length);
        }
        if (currentLineText !== adjustedLineContent) {
            indentEdits.push(EditOperation.replaceMove(new Selection(startLineNumber, 1, startLineNumber, oldIndentation.length + 1), normalizeIndentation(globalIndent, indentSize, insertSpaces)));
        }
    }
    else {
        globalIndent = getLeadingWhitespace(currentLineText);
    }
    // idealIndentForNextLine doesn't equal globalIndent when there is a line matching `indentNextLinePattern`.
    let idealIndentForNextLine = globalIndent;
    if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent)) {
        idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
        globalIndent = shiftIndent(globalIndent);
    }
    else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent)) {
        idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
    }
    startLineNumber++;
    // Calculate indentation adjustment for all following lines
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const text = model.getLineContent(lineNumber);
        const oldIndentation = getLeadingWhitespace(text);
        const adjustedLineContent = idealIndentForNextLine + text.substring(oldIndentation.length);
        if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent)) {
            idealIndentForNextLine = unshiftIndent(idealIndentForNextLine);
            globalIndent = unshiftIndent(globalIndent);
        }
        if (oldIndentation !== idealIndentForNextLine) {
            indentEdits.push(EditOperation.replaceMove(new Selection(lineNumber, 1, lineNumber, oldIndentation.length + 1), normalizeIndentation(idealIndentForNextLine, indentSize, insertSpaces)));
        }
        // calculate idealIndentForNextLine
        if (indentationRules.unIndentedLinePattern && indentationRules.unIndentedLinePattern.test(text)) {
            // In reindent phase, if the line matches `unIndentedLinePattern` we inherit indentation from above lines
            // but don't change globalIndent and idealIndentForNextLine.
            continue;
        }
        else if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent)) {
            globalIndent = shiftIndent(globalIndent);
            idealIndentForNextLine = globalIndent;
        }
        else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent)) {
            idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
        }
        else {
            idealIndentForNextLine = globalIndent;
        }
    }
    return indentEdits;
}
class IndentationToSpacesAction extends EditorAction {
    constructor() {
        super({
            id: IndentationToSpacesAction.ID,
            label: localize('indentationToSpaces', "Convert Indentation to Spaces"),
            alias: 'Convert Indentation to Spaces',
            precondition: EditorContextKeys.writable
        });
    }
    run(accessor, editor) {
        const model = editor.getModel();
        if (!model) {
            return;
        }
        const modelOpts = model.getOptions();
        const selection = editor.getSelection();
        if (!selection) {
            return;
        }
        const command = new IndentationToSpacesCommand(selection, modelOpts.tabSize);
        editor.pushUndoStop();
        editor.executeCommands(this.id, [command]);
        editor.pushUndoStop();
        model.updateOptions({
            insertSpaces: true
        });
    }
}
IndentationToSpacesAction.ID = 'editor.action.indentationToSpaces';
class IndentationToTabsAction extends EditorAction {
    constructor() {
        super({
            id: IndentationToTabsAction.ID,
            label: localize('indentationToTabs', "Convert Indentation to Tabs"),
            alias: 'Convert Indentation to Tabs',
            precondition: EditorContextKeys.writable
        });
    }
    run(accessor, editor) {
        const model = editor.getModel();
        if (!model) {
            return;
        }
        const modelOpts = model.getOptions();
        const selection = editor.getSelection();
        if (!selection) {
            return;
        }
        const command = new IndentationToTabsCommand(selection, modelOpts.tabSize);
        editor.pushUndoStop();
        editor.executeCommands(this.id, [command]);
        editor.pushUndoStop();
        model.updateOptions({
            insertSpaces: false
        });
    }
}
IndentationToTabsAction.ID = 'editor.action.indentationToTabs';
class ChangeIndentationSizeAction extends EditorAction {
    constructor(insertSpaces, opts) {
        super(opts);
        this.insertSpaces = insertSpaces;
    }
    run(accessor, editor) {
        const quickInputService = accessor.get(IQuickInputService);
        const modelService = accessor.get(IModelService);
        const model = editor.getModel();
        if (!model) {
            return;
        }
        const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
        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 ? localize('configuredTabSize', "Configured Tab Size") : undefined
        }));
        // auto focus the tabSize set for the current editor
        const autoFocusIndex = Math.min(model.getOptions().tabSize - 1, 7);
        setTimeout(() => {
            quickInputService.pick(picks, { placeHolder: localize({ key: 'selectTabWidth', comment: ['Tab corresponds to the tab key'] }, "Select Tab Size for Current File"), activeItem: picks[autoFocusIndex] }).then(pick => {
                if (pick) {
                    if (model && !model.isDisposed()) {
                        model.updateOptions({
                            tabSize: parseInt(pick.label, 10),
                            insertSpaces: this.insertSpaces
                        });
                    }
                }
            });
        }, 50 /* quick input is sensitive to being opened so soon after another */);
    }
}
class IndentUsingTabs extends ChangeIndentationSizeAction {
    constructor() {
        super(false, {
            id: IndentUsingTabs.ID,
            label: localize('indentUsingTabs', "Indent Using Tabs"),
            alias: 'Indent Using Tabs',
            precondition: undefined
        });
    }
}
IndentUsingTabs.ID = 'editor.action.indentUsingTabs';
class IndentUsingSpaces extends ChangeIndentationSizeAction {
    constructor() {
        super(true, {
            id: IndentUsingSpaces.ID,
            label: localize('indentUsingSpaces', "Indent Using Spaces"),
            alias: 'Indent Using Spaces',
            precondition: undefined
        });
    }
}
IndentUsingSpaces.ID = 'editor.action.indentUsingSpaces';
class DetectIndentation extends EditorAction {
    constructor() {
        super({
            id: DetectIndentation.ID,
            label: localize('detectIndentation', "Detect Indentation from Content"),
            alias: 'Detect Indentation from Content',
            precondition: undefined
        });
    }
    run(accessor, editor) {
        const modelService = accessor.get(IModelService);
        const model = editor.getModel();
        if (!model) {
            return;
        }
        const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
        model.detectIndentation(creationOpts.insertSpaces, creationOpts.tabSize);
    }
}
DetectIndentation.ID = 'editor.action.detectIndentation';
class ReindentLinesAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.reindentlines',
            label: localize('editor.reindentlines', "Reindent Lines"),
            alias: 'Reindent Lines',
            precondition: EditorContextKeys.writable
        });
    }
    run(accessor, editor) {
        const languageConfigurationService = accessor.get(ILanguageConfigurationService);
        const model = editor.getModel();
        if (!model) {
            return;
        }
        const edits = getReindentEditOperations(model, languageConfigurationService, 1, model.getLineCount());
        if (edits.length > 0) {
            editor.pushUndoStop();
            editor.executeEdits(this.id, edits);
            editor.pushUndoStop();
        }
    }
}
class ReindentSelectedLinesAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.reindentselectedlines',
            label: localize('editor.reindentselectedlines', "Reindent Selected Lines"),
            alias: 'Reindent Selected Lines',
            precondition: EditorContextKeys.writable
        });
    }
    run(accessor, editor) {
        const languageConfigurationService = accessor.get(ILanguageConfigurationService);
        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 = getReindentEditOperations(model, languageConfigurationService, startLineNumber, endLineNumber);
            edits.push(...editOperations);
        }
        if (edits.length > 0) {
            editor.pushUndoStop();
            editor.executeEdits(this.id, edits);
            editor.pushUndoStop();
        }
    }
}
class AutoIndentOnPasteCommand {
    constructor(edits, initialSelection) {
        this._initialSelection = initialSelection;
        this._edits = [];
        this._selectionId = null;
        for (const edit of edits) {
            if (edit.range && typeof edit.text === 'string') {
                this._edits.push(edit);
            }
        }
    }
    getEditOperations(model, builder) {
        for (const edit of this._edits) {
            builder.addEditOperation(Range.lift(edit.range), edit.text);
        }
        let selectionIsSet = false;
        if (Array.isArray(this._edits) && this._edits.length === 1 && this._initialSelection.isEmpty()) {
            if (this._edits[0].range.startColumn === this._initialSelection.endColumn &&
                this._edits[0].range.startLineNumber === this._initialSelection.endLineNumber) {
                selectionIsSet = true;
                this._selectionId = builder.trackSelection(this._initialSelection, true);
            }
            else if (this._edits[0].range.endColumn === this._initialSelection.startColumn &&
                this._edits[0].range.endLineNumber === this._initialSelection.startLineNumber) {
                selectionIsSet = true;
                this._selectionId = builder.trackSelection(this._initialSelection, false);
            }
        }
        if (!selectionIsSet) {
            this._selectionId = builder.trackSelection(this._initialSelection);
        }
    }
    computeCursorState(model, helper) {
        return helper.getTrackedSelection(this._selectionId);
    }
}
let AutoIndentOnPaste = class AutoIndentOnPaste {
    constructor(editor, _languageConfigurationService) {
        this.editor = editor;
        this._languageConfigurationService = _languageConfigurationService;
        this.callOnDispose = new DisposableStore();
        this.callOnModel = new DisposableStore();
        this.callOnDispose.add(editor.onDidChangeConfiguration(() => this.update()));
        this.callOnDispose.add(editor.onDidChangeModel(() => this.update()));
        this.callOnDispose.add(editor.onDidChangeModelLanguage(() => this.update()));
    }
    update() {
        // clean up
        this.callOnModel.clear();
        // we are disabled
        if (this.editor.getOption(9 /* EditorOption.autoIndent */) < 4 /* EditorAutoIndentStrategy.Full */ || this.editor.getOption(50 /* EditorOption.formatOnPaste */)) {
            return;
        }
        // no model
        if (!this.editor.hasModel()) {
            return;
        }
        this.callOnModel.add(this.editor.onDidPaste(({ range }) => {
            this.trigger(range);
        }));
    }
    trigger(range) {
        const selections = this.editor.getSelections();
        if (selections === null || selections.length > 1) {
            return;
        }
        const model = this.editor.getModel();
        if (!model) {
            return;
        }
        if (!model.tokenization.isCheapToTokenize(range.getStartPosition().lineNumber)) {
            return;
        }
        const autoIndent = this.editor.getOption(9 /* EditorOption.autoIndent */);
        const { tabSize, indentSize, insertSpaces } = model.getOptions();
        const textEdits = [];
        const indentConverter = {
            shiftIndent: (indentation) => {
                return ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
            },
            unshiftIndent: (indentation) => {
                return ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
            }
        };
        let startLineNumber = range.startLineNumber;
        while (startLineNumber <= range.endLineNumber) {
            if (this.shouldIgnoreLine(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 = getGoodIndentForLine(autoIndent, model, model.getLanguageId(), startLineNumber, indentConverter, this._languageConfigurationService);
            if (indentOfFirstLine !== null) {
                const oldIndentation = getLeadingWhitespace(firstLineText);
                const newSpaceCnt = getSpaceCnt(indentOfFirstLine, tabSize);
                const oldSpaceCnt = getSpaceCnt(oldIndentation, tabSize);
                if (newSpaceCnt !== oldSpaceCnt) {
                    const newIndent = generateIndent(newSpaceCnt, tabSize, insertSpaces);
                    textEdits.push({
                        range: new Range(startLineNumber, 1, startLineNumber, oldIndentation.length + 1),
                        text: newIndent
                    });
                    firstLineText = newIndent + firstLineText.substr(oldIndentation.length);
                }
                else {
                    const indentMetadata = getIndentMetadata(model, startLineNumber, this._languageConfigurationService);
                    if (indentMetadata === 0 || indentMetadata === 8 /* IndentConsts.UNINDENT_MASK */) {
                        // we paste content into a line where only contains whitespaces
                        // after pasting, the indentation of the first line is already correct
                        // the first line doesn't match any indentation rule
                        // then no-op.
                        return;
                    }
                }
            }
        }
        const firstLineNumber = startLineNumber;
        // ignore empty or ignored lines
        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 = getGoodIndentForLine(autoIndent, virtualModel, model.getLanguageId(), startLineNumber + 1, indentConverter, this._languageConfigurationService);
            if (indentOfSecondLine !== null) {
                const newSpaceCntOfSecondLine = getSpaceCnt(indentOfSecondLine, tabSize);
                const oldSpaceCntOfSecondLine = getSpaceCnt(getLeadingWhitespace(model.getLineContent(startLineNumber + 1)), tabSize);
                if (newSpaceCntOfSecondLine !== oldSpaceCntOfSecondLine) {
                    const spaceCntOffset = newSpaceCntOfSecondLine - oldSpaceCntOfSecondLine;
                    for (let i = startLineNumber + 1; i <= range.endLineNumber; i++) {
                        const lineContent = model.getLineContent(i);
                        const originalIndent = getLeadingWhitespace(lineContent);
                        const originalSpacesCnt = getSpaceCnt(originalIndent, tabSize);
                        const newSpacesCnt = originalSpacesCnt + spaceCntOffset;
                        const newIndent = generateIndent(newSpacesCnt, tabSize, insertSpaces);
                        if (newIndent !== originalIndent) {
                            textEdits.push({
                                range: new Range(i, 1, i, originalIndent.length + 1),
                                text: newIndent
                            });
                        }
                    }
                }
            }
        }
        if (textEdits.length > 0) {
            this.editor.pushUndoStop();
            const cmd = new AutoIndentOnPasteCommand(textEdits, this.editor.getSelection());
            this.editor.executeCommand('autoIndentOnPaste', cmd);
            this.editor.pushUndoStop();
        }
    }
    shouldIgnoreLine(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 /* StandardTokenType.Comment */) {
                return true;
            }
        }
        return false;
    }
    dispose() {
        this.callOnDispose.dispose();
        this.callOnModel.dispose();
    }
};
AutoIndentOnPaste.ID = 'editor.contrib.autoIndentOnPaste';
AutoIndentOnPaste = indentation_decorate([
    indentation_param(1, ILanguageConfigurationService)
], AutoIndentOnPaste);

function getIndentationEditOperations(model, builder, tabSize, tabsToSpaces) {
    if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
        // Model is empty
        return;
    }
    let spaces = '';
    for (let i = 0; i < tabSize; i++) {
        spaces += ' ';
    }
    const spacesRegExp = new RegExp(spaces, '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 Range(lineNumber, 1, lineNumber, lastIndentationColumn);
        const originalIndentation = model.getValueInRange(originalIndentationRange);
        const newIndentation = (tabsToSpaces
            ? originalIndentation.replace(/\t/ig, spaces)
            : originalIndentation.replace(spacesRegExp, '\t'));
        builder.addEditOperation(originalIndentationRange, newIndentation);
    }
}
class IndentationToSpacesCommand {
    constructor(selection, tabSize) {
        this.selection = selection;
        this.tabSize = tabSize;
        this.selectionId = null;
    }
    getEditOperations(model, builder) {
        this.selectionId = builder.trackSelection(this.selection);
        getIndentationEditOperations(model, builder, this.tabSize, true);
    }
    computeCursorState(model, helper) {
        return helper.getTrackedSelection(this.selectionId);
    }
}
class IndentationToTabsCommand {
    constructor(selection, tabSize) {
        this.selection = selection;
        this.tabSize = tabSize;
        this.selectionId = null;
    }
    getEditOperations(model, builder) {
        this.selectionId = builder.trackSelection(this.selection);
        getIndentationEditOperations(model, builder, this.tabSize, false);
    }
    computeCursorState(model, helper) {
        return helper.getTrackedSelection(this.selectionId);
    }
}
registerEditorContribution(AutoIndentOnPaste.ID, AutoIndentOnPaste);
registerEditorAction(IndentationToSpacesAction);
registerEditorAction(IndentationToTabsAction);
registerEditorAction(IndentUsingTabs);
registerEditorAction(IndentUsingSpaces);
registerEditorAction(DetectIndentation);
registerEditorAction(ReindentLinesAction);
registerEditorAction(ReindentSelectedLinesAction);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlayHints/browser/inlayHints.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var inlayHints_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};






class InlayHintAnchor {
    constructor(range, direction) {
        this.range = range;
        this.direction = direction;
    }
}
class InlayHintItem {
    constructor(hint, anchor, provider) {
        this.hint = hint;
        this.anchor = anchor;
        this.provider = provider;
        this._isResolved = false;
    }
    with(delta) {
        const result = new InlayHintItem(this.hint, delta.anchor, this.provider);
        result._isResolved = this._isResolved;
        result._currentResolve = this._currentResolve;
        return result;
    }
    resolve(token) {
        return inlayHints_awaiter(this, void 0, void 0, function* () {
            if (typeof this.provider.resolveInlayHint !== 'function') {
                return;
            }
            if (this._currentResolve) {
                // wait for an active resolve operation and try again
                // when that's done.
                yield this._currentResolve;
                if (token.isCancellationRequested) {
                    return;
                }
                return this.resolve(token);
            }
            if (!this._isResolved) {
                this._currentResolve = this._doResolve(token)
                    .finally(() => this._currentResolve = undefined);
            }
            yield this._currentResolve;
        });
    }
    _doResolve(token) {
        var _a, _b;
        return inlayHints_awaiter(this, void 0, void 0, function* () {
            try {
                const newHint = yield Promise.resolve(this.provider.resolveInlayHint(this.hint, token));
                this.hint.tooltip = (_a = newHint === null || newHint === void 0 ? void 0 : newHint.tooltip) !== null && _a !== void 0 ? _a : this.hint.tooltip;
                this.hint.label = (_b = newHint === null || newHint === void 0 ? void 0 : newHint.label) !== null && _b !== void 0 ? _b : this.hint.label;
                this._isResolved = true;
            }
            catch (err) {
                onUnexpectedExternalError(err);
                this._isResolved = false;
            }
        });
    }
}
class InlayHintsFragments {
    constructor(ranges, data, model) {
        this._disposables = new DisposableStore();
        this.ranges = ranges;
        this.provider = new Set();
        const items = [];
        for (const [list, provider] of data) {
            this._disposables.add(list);
            this.provider.add(provider);
            for (const hint of list.hints) {
                // compute the range to which the item should be attached to
                const position = model.validatePosition(hint.position);
                let direction = 'before';
                const wordRange = InlayHintsFragments._getRangeAtPosition(model, position);
                let range;
                if (wordRange.getStartPosition().isBefore(position)) {
                    range = Range.fromPositions(wordRange.getStartPosition(), position);
                    direction = 'after';
                }
                else {
                    range = Range.fromPositions(position, wordRange.getEndPosition());
                    direction = 'before';
                }
                items.push(new InlayHintItem(hint, new InlayHintAnchor(range, direction), provider));
            }
        }
        this.items = items.sort((a, b) => Position.compare(a.hint.position, b.hint.position));
    }
    static create(registry, model, ranges, token) {
        return inlayHints_awaiter(this, void 0, void 0, function* () {
            const data = [];
            const promises = registry.ordered(model).reverse().map(provider => ranges.map((range) => inlayHints_awaiter(this, void 0, void 0, function* () {
                try {
                    const result = yield provider.provideInlayHints(model, range, token);
                    if (result === null || result === void 0 ? void 0 : result.hints.length) {
                        data.push([result, provider]);
                    }
                }
                catch (err) {
                    onUnexpectedExternalError(err);
                }
            })));
            yield Promise.all(promises.flat());
            if (token.isCancellationRequested || model.isDisposed()) {
                throw new CancellationError();
            }
            return new InlayHintsFragments(ranges, data, model);
        });
    }
    dispose() {
        this._disposables.dispose();
    }
    static _getRangeAtPosition(model, position) {
        const line = position.lineNumber;
        const word = model.getWordAtPosition(position);
        if (word) {
            // always prefer the word range
            return new Range(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) {
            // single character token, when at its end try leading/trailing token instead
            if (start === offset && idx > 1) {
                // leading token
                start = tokens.getStartOffset(idx - 1);
                end = tokens.getEndOffset(idx - 1);
            }
            else if (end === offset && idx < tokens.getCount() - 1) {
                // trailing token
                start = tokens.getStartOffset(idx + 1);
                end = tokens.getEndOffset(idx + 1);
            }
        }
        return new Range(line, start + 1, line, end + 1);
    }
}
function asCommandLink(command) {
    return URI.from({
        scheme: Schemas.command,
        path: command.id,
        query: command.arguments && encodeURIComponent(JSON.stringify(command.arguments))
    }).toString();
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlayHints/browser/inlayHintsLocations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var inlayHintsLocations_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};














function showGoToContextMenu(accessor, editor, anchor, part) {
    var _a;
    return inlayHintsLocations_awaiter(this, void 0, void 0, function* () {
        const resolverService = accessor.get(ITextModelService);
        const contextMenuService = accessor.get(IContextMenuService);
        const commandService = accessor.get(ICommandService);
        const instaService = accessor.get(IInstantiationService);
        const notificationService = accessor.get(INotificationService);
        yield part.item.resolve(CancellationToken.None);
        if (!part.part.location) {
            return;
        }
        const location = part.part.location;
        const menuActions = [];
        // from all registered (not active) context menu actions select those
        // that are a symbol navigation action
        const filter = new Set(MenuRegistry.getMenuItems(MenuId.EditorContext)
            .map(item => isIMenuItem(item) ? item.command.id : ''));
        for (const delegate of EditorExtensionsRegistry.getEditorActions()) {
            if (delegate instanceof SymbolNavigationAction && filter.has(delegate.id)) {
                menuActions.push(new Action(delegate.id, delegate.label, undefined, true, () => inlayHintsLocations_awaiter(this, void 0, void 0, function* () {
                    const ref = yield resolverService.createModelReference(location.uri);
                    try {
                        yield instaService.invokeFunction(delegate.run.bind(delegate), editor, new SymbolNavigationAnchor(ref.object.textEditorModel, Range.getStartPosition(location.range)));
                    }
                    finally {
                        ref.dispose();
                    }
                })));
            }
        }
        if (part.part.command) {
            const { command } = part.part;
            menuActions.push(new Separator());
            menuActions.push(new Action(command.id, command.title, undefined, true, () => inlayHintsLocations_awaiter(this, void 0, void 0, function* () {
                var _b;
                try {
                    yield commandService.executeCommand(command.id, ...((_b = command.arguments) !== null && _b !== void 0 ? _b : []));
                }
                catch (err) {
                    notificationService.notify({
                        severity: notification_Severity.Error,
                        source: part.item.provider.displayName,
                        message: err
                    });
                }
            })));
        }
        // show context menu
        const useShadowDOM = editor.getOption(117 /* EditorOption.useShadowDOM */);
        contextMenuService.showContextMenu({
            domForShadowRoot: useShadowDOM ? (_a = editor.getDomNode()) !== null && _a !== void 0 ? _a : undefined : undefined,
            getAnchor: () => {
                const box = getDomNodePagePosition(anchor);
                return { x: box.left, y: box.top + box.height + 8 };
            },
            getActions: () => menuActions,
            onHide: () => {
                editor.focus();
            },
            autoSelectFirstItem: true,
        });
    });
}
function goToDefinitionWithLocation(accessor, event, editor, location) {
    return inlayHintsLocations_awaiter(this, void 0, void 0, function* () {
        const resolverService = accessor.get(ITextModelService);
        const ref = yield resolverService.createModelReference(location.uri);
        yield editor.invokeWithinContext((accessor) => inlayHintsLocations_awaiter(this, void 0, void 0, function* () {
            const openToSide = event.hasSideBySideModifier;
            const contextKeyService = accessor.get(IContextKeyService);
            const isInPeek = PeekContext.inPeekEditor.getValue(contextKeyService);
            const canPeek = !openToSide && editor.getOption(80 /* EditorOption.definitionLinkOpensInPeek */) && !isInPeek;
            const action = new DefinitionAction({ openToSide, openInPeek: canPeek, muteMessage: true }, { alias: '', label: '', id: '', precondition: undefined });
            return action.run(accessor, editor, { model: ref.object.textEditorModel, position: Range.getStartPosition(location.range) });
        }));
        ref.dispose();
    });
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlayHints/browser/inlayHintsController.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var inlayHintsController_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var inlayHintsController_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var inlayHintsController_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};




























// --- hint caching service (per session)
class InlayHintsCache {
    constructor() {
        this._entries = new LRUCache(50);
    }
    get(model) {
        const key = InlayHintsCache._key(model);
        return this._entries.get(key);
    }
    set(model, value) {
        const key = InlayHintsCache._key(model);
        this._entries.set(key, value);
    }
    static _key(model) {
        return `${model.uri.toString()}/${model.getVersionId()}`;
    }
}
const IInlayHintsCache = createDecorator('IInlayHintsCache');
registerSingleton(IInlayHintsCache, InlayHintsCache, true);
// --- rendered label
class RenderedInlayHintLabelPart {
    constructor(item, index) {
        this.item = item;
        this.index = index;
    }
    get part() {
        const label = this.item.hint.label;
        if (typeof label === 'string') {
            return { label };
        }
        else {
            return label[this.index];
        }
    }
}
class ActiveInlayHintInfo {
    constructor(part, hasTriggerModifier) {
        this.part = part;
        this.hasTriggerModifier = hasTriggerModifier;
    }
}
// --- controller
let InlayHintsController = class InlayHintsController {
    constructor(_editor, _languageFeaturesService, _featureDebounce, _inlayHintsCache, _commandService, _notificationService, _instaService) {
        this._editor = _editor;
        this._languageFeaturesService = _languageFeaturesService;
        this._inlayHintsCache = _inlayHintsCache;
        this._commandService = _commandService;
        this._notificationService = _notificationService;
        this._instaService = _instaService;
        this._disposables = new DisposableStore();
        this._sessionDisposables = new DisposableStore();
        this._decorationsMetadata = new Map();
        this._ruleFactory = new DynamicCssRules(this._editor);
        this._activeRenderMode = 0 /* RenderMode.Normal */;
        this._debounceInfo = _featureDebounce.for(_languageFeaturesService.inlayHintsProvider, 'InlayHint', { min: 25 });
        this._disposables.add(_languageFeaturesService.inlayHintsProvider.onDidChange(() => this._update()));
        this._disposables.add(_editor.onDidChangeModel(() => this._update()));
        this._disposables.add(_editor.onDidChangeModelLanguage(() => this._update()));
        this._disposables.add(_editor.onDidChangeConfiguration(e => {
            if (e.hasChanged(129 /* EditorOption.inlayHints */)) {
                this._update();
            }
        }));
        this._update();
    }
    static get(editor) {
        var _a;
        return (_a = editor.getContribution(InlayHintsController.ID)) !== null && _a !== void 0 ? _a : undefined;
    }
    dispose() {
        this._sessionDisposables.dispose();
        this._removeAllDecorations();
        this._disposables.dispose();
    }
    _update() {
        this._sessionDisposables.clear();
        this._removeAllDecorations();
        const options = this._editor.getOption(129 /* EditorOption.inlayHints */);
        if (options.enabled === 'off') {
            return;
        }
        const model = this._editor.getModel();
        if (!model || !this._languageFeaturesService.inlayHintsProvider.has(model)) {
            return;
        }
        // iff possible, quickly update from cache
        const cached = this._inlayHintsCache.get(model);
        if (cached) {
            this._updateHintsDecorators([model.getFullModelRange()], cached);
        }
        this._sessionDisposables.add(toDisposable(() => {
            // cache items when switching files etc
            if (!model.isDisposed()) {
                this._cacheHintsForFastRestore(model);
            }
        }));
        let cts;
        const watchedProviders = new Set();
        const scheduler = new RunOnceScheduler(() => inlayHintsController_awaiter(this, void 0, void 0, function* () {
            const t1 = Date.now();
            cts === null || cts === void 0 ? void 0 : cts.dispose(true);
            cts = new CancellationTokenSource();
            const listener = model.onWillDispose(() => cts === null || cts === void 0 ? void 0 : cts.cancel());
            try {
                const myToken = cts.token;
                const inlayHints = yield InlayHintsFragments.create(this._languageFeaturesService.inlayHintsProvider, model, this._getHintsRanges(), myToken);
                scheduler.delay = this._debounceInfo.update(model, Date.now() - t1);
                if (myToken.isCancellationRequested) {
                    inlayHints.dispose();
                    return;
                }
                // listen to provider changes
                for (const provider of inlayHints.provider) {
                    if (typeof provider.onDidChangeInlayHints === 'function' && !watchedProviders.has(provider)) {
                        watchedProviders.add(provider);
                        this._sessionDisposables.add(provider.onDidChangeInlayHints(() => {
                            if (!scheduler.isScheduled()) { // ignore event when request is already scheduled
                                scheduler.schedule();
                            }
                        }));
                    }
                }
                this._sessionDisposables.add(inlayHints);
                this._updateHintsDecorators(inlayHints.ranges, inlayHints.items);
                this._cacheHintsForFastRestore(model);
            }
            catch (err) {
                onUnexpectedError(err);
            }
            finally {
                cts.dispose();
                listener.dispose();
            }
        }), this._debounceInfo.get(model));
        this._sessionDisposables.add(scheduler);
        this._sessionDisposables.add(toDisposable(() => cts === null || cts === void 0 ? void 0 : cts.dispose(true)));
        scheduler.schedule(0);
        this._sessionDisposables.add(this._editor.onDidScrollChange((e) => {
            // update when scroll position changes
            // uses scrollTopChanged has weak heuristic to differenatiate between scrolling due to
            // typing or due to "actual" scrolling
            if (e.scrollTopChanged || !scheduler.isScheduled()) {
                scheduler.schedule();
            }
        }));
        this._sessionDisposables.add(this._editor.onDidChangeModelContent((e) => {
            // update less aggressive when typing
            const delay = Math.max(scheduler.delay, 1250);
            scheduler.schedule(delay);
        }));
        if (options.enabled === 'on') {
            // different "on" modes: always
            this._activeRenderMode = 0 /* RenderMode.Normal */;
        }
        else {
            // different "on" modes: offUnlessPressed, or onUnlessPressed
            let defaultMode;
            let altMode;
            if (options.enabled === 'onUnlessPressed') {
                defaultMode = 0 /* RenderMode.Normal */;
                altMode = 1 /* RenderMode.Invisible */;
            }
            else {
                defaultMode = 1 /* RenderMode.Invisible */;
                altMode = 0 /* RenderMode.Normal */;
            }
            this._activeRenderMode = defaultMode;
            this._sessionDisposables.add(ModifierKeyEmitter.getInstance().event(e => {
                if (!this._editor.hasModel()) {
                    return;
                }
                const newRenderMode = e.altKey && e.ctrlKey ? altMode : defaultMode;
                if (newRenderMode !== this._activeRenderMode) {
                    this._activeRenderMode = newRenderMode;
                    const model = this._editor.getModel();
                    const copies = this._copyInlayHintsWithCurrentAnchor(model);
                    this._updateHintsDecorators([model.getFullModelRange()], copies);
                    scheduler.schedule(0);
                }
            }));
        }
        // mouse gestures
        this._sessionDisposables.add(this._installDblClickGesture(() => scheduler.schedule(0)));
        this._sessionDisposables.add(this._installLinkGesture());
        this._sessionDisposables.add(this._installContextMenu());
    }
    _installLinkGesture() {
        const store = new DisposableStore();
        const gesture = store.add(new ClickLinkGesture(this._editor));
        // let removeHighlight = () => { };
        const sessionStore = new DisposableStore();
        store.add(sessionStore);
        store.add(gesture.onMouseMoveOrRelevantKeyDown(e => {
            const [mouseEvent] = e;
            const labelPart = this._getInlayHintLabelPart(mouseEvent);
            const model = this._editor.getModel();
            if (!labelPart || !model) {
                sessionStore.clear();
                return;
            }
            // resolve the item
            const cts = new CancellationTokenSource();
            sessionStore.add(toDisposable(() => cts.dispose(true)));
            labelPart.item.resolve(cts.token);
            // render link => when the modifier is pressed and when there is a command or location
            this._activeInlayHintPart = labelPart.part.command || labelPart.part.location
                ? new ActiveInlayHintInfo(labelPart, mouseEvent.hasTriggerModifier)
                : undefined;
            const lineNumber = labelPart.item.hint.position.lineNumber;
            const range = new Range(lineNumber, 1, lineNumber, model.getLineMaxColumn(lineNumber));
            const lineHints = this._getInlineHintsForRange(range);
            this._updateHintsDecorators([range], lineHints);
            sessionStore.add(toDisposable(() => {
                this._activeInlayHintPart = undefined;
                this._updateHintsDecorators([range], lineHints);
            }));
        }));
        store.add(gesture.onCancel(() => sessionStore.clear()));
        store.add(gesture.onExecute((e) => inlayHintsController_awaiter(this, void 0, void 0, function* () {
            const label = this._getInlayHintLabelPart(e);
            if (label) {
                const part = label.part;
                if (part.location) {
                    // location -> execute go to def
                    this._instaService.invokeFunction(goToDefinitionWithLocation, e, this._editor, part.location);
                }
                else if (languages_Command.is(part.command)) {
                    // command -> execute it
                    yield this._invokeCommand(part.command, label.item);
                }
            }
        })));
        return store;
    }
    _getInlineHintsForRange(range) {
        const lineHints = new Set();
        for (const data of this._decorationsMetadata.values()) {
            if (range.containsRange(data.item.anchor.range)) {
                lineHints.add(data.item);
            }
        }
        return Array.from(lineHints);
    }
    _installDblClickGesture(updateInlayHints) {
        return this._editor.onMouseUp((e) => inlayHintsController_awaiter(this, void 0, void 0, function* () {
            if (e.event.detail !== 2) {
                return;
            }
            const part = this._getInlayHintLabelPart(e);
            if (!part) {
                return;
            }
            e.event.preventDefault();
            yield part.item.resolve(CancellationToken.None);
            if (isNonEmptyArray(part.item.hint.textEdits)) {
                const edits = part.item.hint.textEdits.map(edit => EditOperation.replace(Range.lift(edit.range), edit.text));
                this._editor.executeEdits('inlayHint.default', edits);
                updateInlayHints();
            }
        }));
    }
    _installContextMenu() {
        return this._editor.onContextMenu((e) => inlayHintsController_awaiter(this, void 0, void 0, function* () {
            if (!(e.event.target instanceof HTMLElement)) {
                return;
            }
            const part = this._getInlayHintLabelPart(e);
            if (part) {
                yield this._instaService.invokeFunction(showGoToContextMenu, this._editor, e.event.target, part);
            }
        }));
    }
    _getInlayHintLabelPart(e) {
        var _a;
        if (e.target.type !== 6 /* MouseTargetType.CONTENT_TEXT */) {
            return undefined;
        }
        const options = (_a = e.target.detail.injectedText) === null || _a === void 0 ? void 0 : _a.options;
        if (options instanceof ModelDecorationInjectedTextOptions && (options === null || options === void 0 ? void 0 : options.attachedData) instanceof RenderedInlayHintLabelPart) {
            return options.attachedData;
        }
        return undefined;
    }
    _invokeCommand(command, item) {
        var _a;
        return inlayHintsController_awaiter(this, void 0, void 0, function* () {
            try {
                yield this._commandService.executeCommand(command.id, ...((_a = command.arguments) !== null && _a !== void 0 ? _a : []));
            }
            catch (err) {
                this._notificationService.notify({
                    severity: notification_Severity.Error,
                    source: item.provider.displayName,
                    message: err
                });
            }
        });
    }
    _cacheHintsForFastRestore(model) {
        const hints = this._copyInlayHintsWithCurrentAnchor(model);
        this._inlayHintsCache.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
    _copyInlayHintsWithCurrentAnchor(model) {
        const items = new Map();
        for (const [id, obj] of this._decorationsMetadata) {
            if (items.has(obj.item)) {
                // an inlay item can be rendered as multiple decorations
                // but they will all uses the same range
                continue;
            }
            const range = model.getDecorationRange(id);
            if (range) {
                // update range with whatever the editor has tweaked it to
                const anchor = new InlayHintAnchor(range, obj.item.anchor.direction);
                const copy = obj.item.with({ anchor });
                items.set(obj.item, copy);
            }
        }
        return Array.from(items.values());
    }
    _getHintsRanges() {
        const extra = 30;
        const model = this._editor.getModel();
        const visibleRanges = this._editor.getVisibleRangesPlusViewportAboveBelow();
        const result = [];
        for (const range of visibleRanges.sort(Range.compareRangesUsingStarts)) {
            const extendedRange = model.validateRange(new Range(range.startLineNumber - extra, range.startColumn, range.endLineNumber + extra, range.endColumn));
            if (result.length === 0 || !Range.areIntersectingOrTouching(result[result.length - 1], extendedRange)) {
                result.push(extendedRange);
            }
            else {
                result[result.length - 1] = Range.plusRange(result[result.length - 1], extendedRange);
            }
        }
        return result;
    }
    _updateHintsDecorators(ranges, items) {
        var _a, _b;
        // utils to collect/create injected text decorations
        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(),
                        collapseOnReplaceEdit: !item.anchor.range.isEmpty(),
                        stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
                        [item.anchor.direction]: this._activeRenderMode === 0 /* RenderMode.Normal */ ? opts : undefined
                    }
                }
            });
        };
        const addInjectedWhitespace = (item, isLast) => {
            const marginRule = this._ruleFactory.createClassNameRef({
                width: `${(fontSize / 3) | 0}px`,
                display: 'inline-block'
            });
            addInjectedText(item, marginRule, '\u200a', isLast ? InjectedTextCursorStops.Right : InjectedTextCursorStops.None);
        };
        //
        const { fontSize, fontFamily, padding, isUniform } = this._getLayoutInfo();
        const fontFamilyVar = '--code-editorInlayHintsFontFamily';
        this._editor.getContainerDomNode().style.setProperty(fontFamilyVar, fontFamily);
        for (const item of items) {
            // whitespace leading the actual label
            if (item.hint.paddingLeft) {
                addInjectedWhitespace(item, false);
            }
            // the label with its parts
            const parts = typeof item.hint.label === 'string'
                ? [{ label: item.hint.label }]
                : item.hint.label;
            for (let i = 0; i < parts.length; i++) {
                const part = parts[i];
                const isFirst = i === 0;
                const isLast = i === parts.length - 1;
                const cssProperties = {
                    fontSize: `${fontSize}px`,
                    fontFamily: `var(${fontFamilyVar}), ${EDITOR_FONT_DEFAULTS.fontFamily}`,
                    verticalAlign: isUniform ? 'baseline' : 'middle',
                };
                if (isNonEmptyArray(item.hint.textEdits)) {
                    cssProperties.cursor = 'default';
                }
                this._fillInColors(cssProperties, item.hint);
                if ((part.command || part.location) && ((_a = this._activeInlayHintPart) === null || _a === void 0 ? void 0 : _a.part.item) === item && this._activeInlayHintPart.part.index === i) {
                    // active link!
                    cssProperties.textDecoration = 'underline';
                    if (this._activeInlayHintPart.hasTriggerModifier) {
                        cssProperties.color = themeColorFromId(editorActiveLinkForeground);
                        cssProperties.cursor = 'pointer';
                    }
                }
                if (padding) {
                    if (isFirst && isLast) {
                        // only element
                        cssProperties.padding = `1px ${Math.max(1, fontSize / 4) | 0}px`;
                        cssProperties.borderRadius = `${(fontSize / 4) | 0}px`;
                    }
                    else if (isFirst) {
                        // first element
                        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) {
                        // last element
                        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._ruleFactory.createClassNameRef(cssProperties), fixSpace(part.label), isLast && !item.hint.paddingRight ? InjectedTextCursorStops.Right : InjectedTextCursorStops.None, new RenderedInlayHintLabelPart(item, i));
            }
            // whitespace trailing the actual label
            if (item.hint.paddingRight) {
                addInjectedWhitespace(item, true);
            }
            if (newDecorationsData.length > InlayHintsController._MAX_DECORATORS) {
                break;
            }
        }
        // collect all decoration ids that are affected by the ranges
        // and only update those decorations
        const decorationIdsToReplace = [];
        for (const range of ranges) {
            for (const { id } of (_b = this._editor.getDecorationsInRange(range)) !== null && _b !== void 0 ? _b : []) {
                const metadata = this._decorationsMetadata.get(id);
                if (metadata) {
                    decorationIdsToReplace.push(id);
                    metadata.classNameRef.dispose();
                    this._decorationsMetadata.delete(id);
                }
            }
        }
        this._editor.changeDecorations(accessor => {
            const newDecorationIds = accessor.deltaDecorations(decorationIdsToReplace, newDecorationsData.map(d => d.decoration));
            for (let i = 0; i < newDecorationIds.length; i++) {
                const data = newDecorationsData[i];
                this._decorationsMetadata.set(newDecorationIds[i], data);
            }
        });
    }
    _fillInColors(props, hint) {
        if (hint.kind === InlayHintKind.Parameter) {
            props.backgroundColor = themeColorFromId(editorInlayHintParameterBackground);
            props.color = themeColorFromId(editorInlayHintParameterForeground);
        }
        else if (hint.kind === InlayHintKind.Type) {
            props.backgroundColor = themeColorFromId(editorInlayHintTypeBackground);
            props.color = themeColorFromId(editorInlayHintTypeForeground);
        }
        else {
            props.backgroundColor = themeColorFromId(editorInlayHintBackground);
            props.color = themeColorFromId(editorInlayHintForeground);
        }
    }
    _getLayoutInfo() {
        const options = this._editor.getOption(129 /* EditorOption.inlayHints */);
        const padding = options.padding;
        const editorFontSize = this._editor.getOption(48 /* EditorOption.fontSize */);
        const editorFontFamily = this._editor.getOption(45 /* EditorOption.fontFamily */);
        let fontSize = options.fontSize;
        if (!fontSize || fontSize < 5 || fontSize > editorFontSize) {
            fontSize = editorFontSize;
        }
        const fontFamily = options.fontFamily || editorFontFamily;
        const isUniform = !padding
            && fontFamily === editorFontFamily
            && fontSize === editorFontSize;
        return { fontSize, fontFamily, padding, isUniform };
    }
    _removeAllDecorations() {
        this._editor.removeDecorations(Array.from(this._decorationsMetadata.keys()));
        for (const obj of this._decorationsMetadata.values()) {
            obj.classNameRef.dispose();
        }
        this._decorationsMetadata.clear();
    }
};
InlayHintsController.ID = 'editor.contrib.InlayHints';
InlayHintsController._MAX_DECORATORS = 1500;
InlayHintsController = inlayHintsController_decorate([
    inlayHintsController_param(1, ILanguageFeaturesService),
    inlayHintsController_param(2, ILanguageFeatureDebounceService),
    inlayHintsController_param(3, IInlayHintsCache),
    inlayHintsController_param(4, ICommandService),
    inlayHintsController_param(5, INotificationService),
    inlayHintsController_param(6, IInstantiationService)
], InlayHintsController);

// Prevents the view from potentially visible whitespace
function fixSpace(str) {
    const noBreakWhitespace = '\xa0';
    return str.replace(/[ \t]/g, noBreakWhitespace);
}
CommandsRegistry.registerCommand('_executeInlayHintProvider', (accessor, ...args) => inlayHintsController_awaiter(void 0, void 0, void 0, function* () {
    const [uri, range] = args;
    assertType(URI.isUri(uri));
    assertType(Range.isIRange(range));
    const { inlayHintsProvider } = accessor.get(ILanguageFeaturesService);
    const ref = yield accessor.get(ITextModelService).createModelReference(uri);
    try {
        const model = yield InlayHintsFragments.create(inlayHintsProvider, ref.object.textEditorModel, [Range.lift(range)], CancellationToken.None);
        const result = model.items.map(i => i.hint);
        setTimeout(() => model.dispose(), 0); // dispose after sending to ext host
        return result;
    }
    finally {
        ref.dispose();
    }
}));

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlayHints/browser/inlayHintsHover.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var inlayHintsHover_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var inlayHintsHover_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var inlayHintsHover_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
var inlayHintsHover_asyncValues = (undefined && undefined.__asyncValues) || function (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); }
};

















class InlayHintsHoverAnchor extends HoverForeignElementAnchor {
    constructor(part, owner) {
        super(10, owner, part.item.anchor.range);
        this.part = part;
    }
}
let InlayHintsHover = class InlayHintsHover extends MarkdownHoverParticipant {
    constructor(editor, languageService, openerService, configurationService, _resolverService, languageFeaturesService) {
        super(editor, languageService, openerService, configurationService, languageFeaturesService);
        this._resolverService = _resolverService;
        this.hoverOrdinal = 6;
    }
    suggestHoverAnchor(mouseEvent) {
        var _a;
        const controller = InlayHintsController.get(this._editor);
        if (!controller) {
            return null;
        }
        if (mouseEvent.target.type !== 6 /* MouseTargetType.CONTENT_TEXT */) {
            return null;
        }
        const options = (_a = mouseEvent.target.detail.injectedText) === null || _a === void 0 ? void 0 : _a.options;
        if (!(options instanceof ModelDecorationInjectedTextOptions && options.attachedData instanceof RenderedInlayHintLabelPart)) {
            return null;
        }
        return new InlayHintsHoverAnchor(options.attachedData, this);
    }
    computeSync() {
        return [];
    }
    computeAsync(anchor, _lineDecorations, token) {
        if (!(anchor instanceof InlayHintsHoverAnchor)) {
            return AsyncIterableObject.EMPTY;
        }
        return new AsyncIterableObject((executor) => inlayHintsHover_awaiter(this, void 0, void 0, function* () {
            var e_1, _a;
            const { part } = anchor;
            yield part.item.resolve(token);
            if (token.isCancellationRequested) {
                return;
            }
            // (1) Inlay Tooltip
            let itemTooltip;
            if (typeof part.item.hint.tooltip === 'string') {
                itemTooltip = new MarkdownString().appendText(part.item.hint.tooltip);
            }
            else if (part.item.hint.tooltip) {
                itemTooltip = part.item.hint.tooltip;
            }
            if (itemTooltip) {
                executor.emitOne(new MarkdownHover(this, anchor.range, [itemTooltip], 0));
            }
            // (1.2) Inlay dbl-click gesture
            if (isNonEmptyArray(part.item.hint.textEdits)) {
                executor.emitOne(new MarkdownHover(this, anchor.range, [new MarkdownString().appendText(localize('hint.dbl', "Double click to insert"))], 10001));
            }
            // (2) Inlay Label Part Tooltip
            let partTooltip;
            if (typeof part.part.tooltip === 'string') {
                partTooltip = new MarkdownString().appendText(part.part.tooltip);
            }
            else if (part.part.tooltip) {
                partTooltip = part.part.tooltip;
            }
            if (partTooltip) {
                executor.emitOne(new MarkdownHover(this, anchor.range, [partTooltip], 1));
            }
            // (2.2) Inlay Label Part Help Hover
            if (part.part.location || part.part.command) {
                let linkHint;
                const useMetaKey = this._editor.getOption(72 /* EditorOption.multiCursorModifier */) === 'altKey';
                const kb = useMetaKey
                    ? isMacintosh
                        ? localize('links.navigate.kb.meta.mac', "cmd + click")
                        : localize('links.navigate.kb.meta', "ctrl + click")
                    : isMacintosh
                        ? localize('links.navigate.kb.alt.mac', "option + click")
                        : localize('links.navigate.kb.alt', "alt + click");
                if (part.part.location && part.part.command) {
                    linkHint = new MarkdownString().appendText(localize('hint.defAndCommand', 'Go to Definition ({0}), right click for more', kb));
                }
                else if (part.part.location) {
                    linkHint = new MarkdownString().appendText(localize('hint.def', 'Go to Definition ({0})', kb));
                }
                else if (part.part.command) {
                    linkHint = new MarkdownString(`[${localize('hint.cmd', "Execute Command")}](${asCommandLink(part.part.command)} "${part.part.command.title}") (${kb})`, { isTrusted: true });
                }
                if (linkHint) {
                    executor.emitOne(new MarkdownHover(this, anchor.range, [linkHint], 10000));
                }
            }
            // (3) Inlay Label Part Location tooltip
            const iterable = yield this._resolveInlayHintLabelPartHover(part, token);
            try {
                for (var iterable_1 = inlayHintsHover_asyncValues(iterable), iterable_1_1; iterable_1_1 = yield iterable_1.next(), !iterable_1_1.done;) {
                    const item = iterable_1_1.value;
                    executor.emitOne(item);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) yield _a.call(iterable_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }));
    }
    _resolveInlayHintLabelPartHover(part, token) {
        return inlayHintsHover_awaiter(this, void 0, void 0, function* () {
            if (!part.part.location) {
                return AsyncIterableObject.EMPTY;
            }
            const { uri, range } = part.part.location;
            const ref = yield this._resolverService.createModelReference(uri);
            try {
                const model = ref.object.textEditorModel;
                if (!this._languageFeaturesService.hoverProvider.has(model)) {
                    return AsyncIterableObject.EMPTY;
                }
                return getHover(this._languageFeaturesService.hoverProvider, model, new Position(range.startLineNumber, range.startColumn), token)
                    .filter(item => !isEmptyMarkdownString(item.hover.contents))
                    .map(item => new MarkdownHover(this, part.item.anchor.range, item.hover.contents, 2 + item.ordinal));
            }
            finally {
                ref.dispose();
            }
        });
    }
};
InlayHintsHover = inlayHintsHover_decorate([
    inlayHintsHover_param(1, ILanguageService),
    inlayHintsHover_param(2, IOpenerService),
    inlayHintsHover_param(3, IConfigurationService),
    inlayHintsHover_param(4, ITextModelService),
    inlayHintsHover_param(5, ILanguageFeaturesService)
], InlayHintsHover);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlayHints/browser/inlayHintsContribution.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




registerEditorContribution(InlayHintsController.ID, InlayHintsController);
HoverParticipantRegistry.register(InlayHintsHover);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/consts.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
const inlineSuggestCommitId = 'editor.action.inlineSuggest.commit';

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/utils.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

function utils_createDisposableRef(object, disposable) {
    return {
        object,
        dispose: () => disposable === null || disposable === void 0 ? void 0 : disposable.dispose(),
    };
}
function applyEdits(text, edits) {
    const transformer = new PositionOffsetTransformer(text);
    const offsetEdits = edits.map(e => {
        const range = Range.lift(e.range);
        return ({
            startOffset: transformer.getOffset(range.getStartPosition()),
            endOffset: transformer.getOffset(range.getEndPosition()),
            text: e.text
        });
    });
    offsetEdits.sort((a, b) => b.startOffset - a.startOffset);
    for (const edit of offsetEdits) {
        text = text.substring(0, edit.startOffset) + edit.text + text.substring(edit.endOffset);
    }
    return text;
}
class PositionOffsetTransformer {
    constructor(text) {
        this.lineStartOffsetByLineIdx = [];
        this.lineStartOffsetByLineIdx.push(0);
        for (let i = 0; i < text.length; i++) {
            if (text.charAt(i) === '\n') {
                this.lineStartOffsetByLineIdx.push(i + 1);
            }
        }
    }
    getOffset(position) {
        return this.lineStartOffsetByLineIdx[position.lineNumber - 1] + position.column - 1;
    }
}
const array = [];
function getReadonlyEmptyArray() {
    return array;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/ghostText.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class GhostText {
    constructor(lineNumber, parts, additionalReservedLineCount = 0) {
        this.lineNumber = lineNumber;
        this.parts = parts;
        this.additionalReservedLineCount = additionalReservedLineCount;
    }
    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 text = applyEdits(cappedLineText, this.parts.map(p => ({
            range: { startLineNumber: 1, endLineNumber: 1, startColumn: p.column, endColumn: p.column },
            text: p.lines.join('\n')
        })));
        return text.substring(this.parts[0].column - 1);
    }
    isEmpty() {
        return this.parts.every(p => p.lines.length === 0);
    }
}
class GhostTextPart {
    constructor(column, lines, 
    /**
     * Indicates if this part is a preview of an inline suggestion when a suggestion is previewed.
    */
    preview) {
        this.column = column;
        this.lines = lines;
        this.preview = preview;
    }
}
class GhostTextReplacement {
    constructor(lineNumber, columnStart, length, newLines, additionalReservedLineCount = 0) {
        this.lineNumber = lineNumber;
        this.columnStart = columnStart;
        this.length = length;
        this.newLines = newLines;
        this.additionalReservedLineCount = additionalReservedLineCount;
        this.parts = [
            new GhostTextPart(this.columnStart + this.length, this.newLines, false),
        ];
    }
    renderForScreenReader(_lineText) {
        return this.newLines.join('\n');
    }
}
class BaseGhostTextWidgetModel extends Disposable {
    constructor(editor) {
        super();
        this.editor = editor;
        this._expanded = undefined;
        this.onDidChangeEmitter = new Emitter();
        this.onDidChange = this.onDidChangeEmitter.event;
        this._register(editor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(108 /* EditorOption.suggest */) && this._expanded === undefined) {
                this.onDidChangeEmitter.fire();
            }
        }));
    }
    setExpanded(expanded) {
        this._expanded = true;
        this.onDidChangeEmitter.fire();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/inlineCompletionToGhostText.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




function minimizeInlineCompletion(model, inlineCompletion) {
    if (!inlineCompletion) {
        return inlineCompletion;
    }
    const valueToReplace = model.getValueInRange(inlineCompletion.range);
    const commonPrefixLen = strings_commonPrefixLength(valueToReplace, inlineCompletion.insertText);
    const startOffset = model.getOffsetAt(inlineCompletion.range.getStartPosition()) + commonPrefixLen;
    const start = model.getPositionAt(startOffset);
    const remainingValueToReplace = valueToReplace.substr(commonPrefixLen);
    const commonSuffixLen = strings_commonSuffixLength(remainingValueToReplace, inlineCompletion.insertText);
    const end = model.getPositionAt(Math.max(startOffset, model.getOffsetAt(inlineCompletion.range.getEndPosition()) - commonSuffixLen));
    return {
        range: Range.fromPositions(start, end),
        insertText: inlineCompletion.insertText.substr(commonPrefixLen, inlineCompletion.insertText.length - commonPrefixLen - commonSuffixLen),
        snippetInfo: inlineCompletion.snippetInfo,
        filterText: inlineCompletion.filterText,
        additionalTextEdits: inlineCompletion.additionalTextEdits,
    };
}
function normalizedInlineCompletionsEquals(a, b) {
    if (a === b) {
        return true;
    }
    if (!a || !b) {
        return false;
    }
    return a.range.equalsRange(b.range) && a.insertText === b.insertText && a.command === b.command;
}
/**
 * @param previewSuffixLength Sets where to split `inlineCompletion.text`.
 * 	If the text is `hello` and the suffix length is 2, the non-preview part is `hel` and the preview-part is `lo`.
*/
function inlineCompletionToGhostText(inlineCompletion, textModel, mode, cursorPosition, previewSuffixLength = 0) {
    if (inlineCompletion.range.startLineNumber !== inlineCompletion.range.endLineNumber) {
        // Only single line replacements are supported.
        return undefined;
    }
    const sourceLine = textModel.getLineContent(inlineCompletion.range.startLineNumber);
    const sourceIndentationLength = getLeadingWhitespace(sourceLine).length;
    const suggestionTouchesIndentation = inlineCompletion.range.startColumn - 1 <= sourceIndentationLength;
    if (suggestionTouchesIndentation) {
        // source:      ··········[······abc]
        //                         ^^^^^^^^^ inlineCompletion.range
        //              ^^^^^^^^^^ ^^^^^^ sourceIndentationLength
        //                         ^^^^^^ replacedIndentation.length
        //                               ^^^ rangeThatDoesNotReplaceIndentation
        // inlineCompletion.text: '··foo'
        //                         ^^ suggestionAddedIndentationLength
        const suggestionAddedIndentationLength = getLeadingWhitespace(inlineCompletion.insertText).length;
        const replacedIndentation = sourceLine.substring(inlineCompletion.range.startColumn - 1, sourceIndentationLength);
        const rangeThatDoesNotReplaceIndentation = Range.fromPositions(inlineCompletion.range.getStartPosition().delta(0, replacedIndentation.length), inlineCompletion.range.getEndPosition());
        const suggestionWithoutIndentationChange = inlineCompletion.insertText.startsWith(replacedIndentation)
            // Adds more indentation without changing existing indentation: We can add ghost text for this
            ? inlineCompletion.insertText.substring(replacedIndentation.length)
            // Changes or removes existing indentation. Only add ghost text for the non-indentation part.
            : inlineCompletion.insertText.substring(suggestionAddedIndentationLength);
        inlineCompletion = {
            range: rangeThatDoesNotReplaceIndentation,
            insertText: suggestionWithoutIndentationChange,
            command: inlineCompletion.command,
            snippetInfo: undefined,
            filterText: inlineCompletion.filterText,
            additionalTextEdits: inlineCompletion.additionalTextEdits,
        };
    }
    // This is a single line string
    const valueToBeReplaced = textModel.getValueInRange(inlineCompletion.range);
    const changes = cachingDiff(valueToBeReplaced, inlineCompletion.insertText);
    if (!changes) {
        // No ghost text in case the diff would be too slow to compute
        return undefined;
    }
    const lineNumber = inlineCompletion.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) {
            // Prefixes only have a single change.
            return undefined;
        }
    }
    const previewStartInCompletionText = inlineCompletion.insertText.length - previewSuffixLength;
    for (const c of changes) {
        const insertColumn = inlineCompletion.range.startColumn + c.originalStart + c.originalLength;
        if (mode === 'subwordSmart' && cursorPosition && cursorPosition.lineNumber === inlineCompletion.range.startLineNumber && insertColumn < cursorPosition.column) {
            // No ghost text before cursor
            return undefined;
        }
        if (c.originalLength > 0) {
            return undefined;
        }
        if (c.modifiedLength === 0) {
            continue;
        }
        const modifiedEnd = c.modifiedStart + c.modifiedLength;
        const nonPreviewTextEnd = Math.max(c.modifiedStart, Math.min(modifiedEnd, previewStartInCompletionText));
        const nonPreviewText = inlineCompletion.insertText.substring(c.modifiedStart, nonPreviewTextEnd);
        const italicText = inlineCompletion.insertText.substring(nonPreviewTextEnd, Math.max(c.modifiedStart, modifiedEnd));
        if (nonPreviewText.length > 0) {
            const lines = splitLines(nonPreviewText);
            parts.push(new GhostTextPart(insertColumn, lines, false));
        }
        if (italicText.length > 0) {
            const lines = splitLines(italicText);
            parts.push(new GhostTextPart(insertColumn, lines, true));
        }
    }
    return new GhostText(lineNumber, parts, 0);
}
let lastRequest = undefined;
function cachingDiff(originalValue, newValue) {
    if ((lastRequest === null || lastRequest === void 0 ? void 0 : lastRequest.originalValue) === originalValue && (lastRequest === null || lastRequest === void 0 ? void 0 : lastRequest.newValue) === newValue) {
        return lastRequest === null || lastRequest === void 0 ? void 0 : lastRequest.changes;
    }
    else {
        let changes = smartDiff(originalValue, newValue, true);
        if (changes) {
            const deletedChars = deletedCharacters(changes);
            if (deletedChars > 0) {
                // For performance reasons, don't compute diff if there is nothing to improve
                const newChanges = smartDiff(originalValue, newValue, false);
                if (newChanges && deletedCharacters(newChanges) < deletedChars) {
                    // Disabling smartness seems to be better here
                    changes = newChanges;
                }
            }
        }
        lastRequest = {
            originalValue,
            newValue,
            changes
        };
        return changes;
    }
}
function deletedCharacters(changes) {
    let sum = 0;
    for (const c of changes) {
        sum += Math.max(c.originalLength - c.modifiedLength, 0);
    }
    return sum;
}
/**
 * When matching `if ()` with `if (f() = 1) { g(); }`,
 * align it like this:        `if (       )`
 * Not like this:			  `if (  )`
 * Also not like this:		  `if (             )`.
 *
 * The parenthesis are preprocessed to ensure that they match correctly.
 */
function smartDiff(originalValue, newValue, smartBracketMatching) {
    if (originalValue.length > 5000 || newValue.length > 5000) {
        // We don't want to work on strings that are too big
        return undefined;
    }
    function getMaxCharCode(val) {
        let maxCharCode = 0;
        for (let i = 0, len = val.length; i < len; i++) {
            const charCode = val.charCodeAt(i);
            if (charCode > maxCharCode) {
                maxCharCode = charCode;
            }
        }
        return maxCharCode;
    }
    const maxCharCode = Math.max(getMaxCharCode(originalValue), getMaxCharCode(newValue));
    function getUniqueCharCode(id) {
        if (id < 0) {
            throw new Error('unexpected');
        }
        return maxCharCode + id + 1;
    }
    function getElements(source) {
        let level = 0;
        let group = 0;
        const characters = new Int32Array(source.length);
        for (let i = 0, len = source.length; i < len; i++) {
            // TODO support more brackets
            if (smartBracketMatching && source[i] === '(') {
                const id = group * 100 + level;
                characters[i] = getUniqueCharCode(2 * id);
                level++;
            }
            else if (smartBracketMatching && source[i] === ')') {
                level = Math.max(level - 1, 0);
                const id = group * 100 + level;
                characters[i] = getUniqueCharCode(2 * id + 1);
                if (level === 0) {
                    group++;
                }
            }
            else {
                characters[i] = source.charCodeAt(i);
            }
        }
        return characters;
    }
    const elements1 = getElements(originalValue);
    const elements2 = getElements(newValue);
    return new LcsDiff({ getElements: () => elements1 }, { getElements: () => elements2 }).ComputeDiff(false).changes;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/bracketPairsTextModelPart/fixBrackets.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





function fixBracketsInLine(tokens, languageConfigurationService) {
    const denseKeyProvider = new DenseKeyProvider();
    const bracketTokens = new LanguageAgnosticBracketTokens(denseKeyProvider, (languageId) => languageConfigurationService.getLanguageConfiguration(languageId));
    const tokenizer = new TextBufferTokenizer(new StaticTokenizerSource([tokens]), bracketTokens);
    const node = parseDocument(tokenizer, [], undefined, true);
    let str = '';
    const line = tokens.getLineContent();
    function processNode(node, offset) {
        if (node.kind === 2 /* AstNodeKind.Pair */) {
            processNode(node.openingBracket, offset);
            offset = lengthAdd(offset, node.openingBracket.length);
            if (node.child) {
                processNode(node.child, offset);
                offset = lengthAdd(offset, node.child.length);
            }
            if (node.closingBracket) {
                processNode(node.closingBracket, offset);
                offset = lengthAdd(offset, node.closingBracket.length);
            }
            else {
                const singleLangBracketTokens = bracketTokens.getSingleLanguageBracketTokens(node.openingBracket.languageId);
                const closingTokenText = singleLangBracketTokens.findClosingTokenText(node.openingBracket.bracketIds);
                str += closingTokenText;
            }
        }
        else if (node.kind === 3 /* AstNodeKind.UnexpectedClosingBracket */) {
            // remove the bracket
        }
        else if (node.kind === 0 /* AstNodeKind.Text */ || node.kind === 1 /* AstNodeKind.Bracket */) {
            str += line.substring(lengthGetColumnCountIfZeroLineCount(offset), lengthGetColumnCountIfZeroLineCount(lengthAdd(offset, node.length)));
        }
        else if (node.kind === 4 /* AstNodeKind.List */) {
            for (const child of node.children) {
                processNode(child, offset);
                offset = lengthAdd(offset, child.length);
            }
        }
    }
    processNode(node, lengthZero);
    return str;
}
class StaticTokenizerSource {
    constructor(lines) {
        this.lines = lines;
        this.tokenization = {
            getLineTokens: (lineNumber) => {
                return this.lines[lineNumber - 1];
            }
        };
    }
    getLineCount() {
        return this.lines.length;
    }
    getLineLength(lineNumber) {
        return this.lines[lineNumber - 1].getLineContent().length;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/inlineCompletionsModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var inlineCompletionsModel_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var inlineCompletionsModel_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var inlineCompletionsModel_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};























let InlineCompletionsModel = class InlineCompletionsModel extends Disposable {
    constructor(editor, cache, commandService, languageConfigurationService, languageFeaturesService, debounceService, configurationService) {
        super();
        this.editor = editor;
        this.cache = cache;
        this.commandService = commandService;
        this.languageConfigurationService = languageConfigurationService;
        this.languageFeaturesService = languageFeaturesService;
        this.debounceService = debounceService;
        this.onDidChangeEmitter = new Emitter();
        this.onDidChange = this.onDidChangeEmitter.event;
        this.completionSession = this._register(new MutableDisposable());
        this.active = false;
        this.disposed = false;
        this.debounceValue = this.debounceService.for(this.languageFeaturesService.inlineCompletionsProvider, 'InlineCompletionsDebounce', { min: 50, max: 50 });
        this._register(commandService.onDidExecuteCommand((e) => {
            // These commands don't trigger onDidType.
            const commands = new Set([
                CoreEditingCommands.Tab.id,
                CoreEditingCommands.DeleteLeft.id,
                CoreEditingCommands.DeleteRight.id,
                inlineSuggestCommitId,
                'acceptSelectedSuggestion',
            ]);
            if (commands.has(e.commandId) && editor.hasTextFocus()) {
                this.handleUserInput();
            }
        }));
        this._register(this.editor.onDidType((e) => {
            this.handleUserInput();
        }));
        this._register(this.editor.onDidChangeCursorPosition((e) => {
            if (e.reason === 3 /* CursorChangeReason.Explicit */ ||
                this.session && !this.session.isValid) {
                this.hide();
            }
        }));
        this._register(toDisposable(() => {
            this.disposed = true;
        }));
        this._register(this.editor.onDidBlurEditorWidget(() => {
            // This is a hidden setting very useful for debugging
            if (configurationService.getValue('editor.inlineSuggest.hideOnBlur')) {
                return;
            }
            this.hide();
        }));
    }
    handleUserInput() {
        if (this.session && !this.session.isValid) {
            this.hide();
        }
        setTimeout(() => {
            if (this.disposed) {
                return;
            }
            // Wait for the cursor update that happens in the same iteration loop iteration
            this.startSessionIfTriggered();
        }, 0);
    }
    get session() {
        return this.completionSession.value;
    }
    get ghostText() {
        var _a;
        return (_a = this.session) === null || _a === void 0 ? void 0 : _a.ghostText;
    }
    get minReservedLineCount() {
        return this.session ? this.session.minReservedLineCount : 0;
    }
    setExpanded(expanded) {
        var _a;
        (_a = this.session) === null || _a === void 0 ? void 0 : _a.setExpanded(expanded);
    }
    setActive(active) {
        var _a;
        this.active = active;
        if (active) {
            (_a = this.session) === null || _a === void 0 ? void 0 : _a.scheduleAutomaticUpdate();
        }
    }
    startSessionIfTriggered() {
        const suggestOptions = this.editor.getOption(57 /* EditorOption.inlineSuggest */);
        if (!suggestOptions.enabled) {
            return;
        }
        if (this.session && this.session.isValid) {
            return;
        }
        this.trigger(InlineCompletionTriggerKind.Automatic);
    }
    trigger(triggerKind) {
        if (this.completionSession.value) {
            if (triggerKind === InlineCompletionTriggerKind.Explicit) {
                void this.completionSession.value.ensureUpdateWithExplicitContext();
            }
            return;
        }
        this.completionSession.value = new InlineCompletionsSession(this.editor, this.editor.getPosition(), () => this.active, this.commandService, this.cache, triggerKind, this.languageConfigurationService, this.languageFeaturesService.inlineCompletionsProvider, this.debounceValue);
        this.completionSession.value.takeOwnership(this.completionSession.value.onDidChange(() => {
            this.onDidChangeEmitter.fire();
        }));
    }
    hide() {
        this.completionSession.clear();
        this.onDidChangeEmitter.fire();
    }
    commitCurrentSuggestion() {
        var _a;
        // Don't dispose the session, so that after committing, more suggestions are shown.
        (_a = this.session) === null || _a === void 0 ? void 0 : _a.commitCurrentCompletion();
    }
    showNext() {
        var _a;
        (_a = this.session) === null || _a === void 0 ? void 0 : _a.showNextInlineCompletion();
    }
    showPrevious() {
        var _a;
        (_a = this.session) === null || _a === void 0 ? void 0 : _a.showPreviousInlineCompletion();
    }
    hasMultipleInlineCompletions() {
        var _a;
        return inlineCompletionsModel_awaiter(this, void 0, void 0, function* () {
            const result = yield ((_a = this.session) === null || _a === void 0 ? void 0 : _a.hasMultipleInlineCompletions());
            return result !== undefined ? result : false;
        });
    }
};
InlineCompletionsModel = inlineCompletionsModel_decorate([
    inlineCompletionsModel_param(2, ICommandService),
    inlineCompletionsModel_param(3, ILanguageConfigurationService),
    inlineCompletionsModel_param(4, ILanguageFeaturesService),
    inlineCompletionsModel_param(5, ILanguageFeatureDebounceService),
    inlineCompletionsModel_param(6, IConfigurationService)
], InlineCompletionsModel);

class InlineCompletionsSession extends BaseGhostTextWidgetModel {
    constructor(editor, triggerPosition, shouldUpdate, commandService, cache, initialTriggerKind, languageConfigurationService, registry, debounce) {
        super(editor);
        this.triggerPosition = triggerPosition;
        this.shouldUpdate = shouldUpdate;
        this.commandService = commandService;
        this.cache = cache;
        this.initialTriggerKind = initialTriggerKind;
        this.languageConfigurationService = languageConfigurationService;
        this.registry = registry;
        this.debounce = debounce;
        this.minReservedLineCount = 0;
        this.updateOperation = this._register(new MutableDisposable());
        this.updateSoon = this._register(new RunOnceScheduler(() => {
            const triggerKind = this.initialTriggerKind;
            // All subsequent triggers are automatic.
            this.initialTriggerKind = InlineCompletionTriggerKind.Automatic;
            return this.update(triggerKind);
        }, 50));
        this.filteredCompletions = [];
        //#region Selection
        // We use a semantic id to track the selection even if the cache changes.
        this.currentlySelectedCompletionId = undefined;
        let lastCompletionItem = undefined;
        this._register(this.onDidChange(() => {
            var _a;
            const currentCompletion = this.currentCompletion;
            if (currentCompletion && currentCompletion.sourceInlineCompletion !== lastCompletionItem) {
                lastCompletionItem = currentCompletion.sourceInlineCompletion;
                const provider = currentCompletion.sourceProvider;
                (_a = provider.handleItemDidShow) === null || _a === void 0 ? void 0 : _a.call(provider, currentCompletion.sourceInlineCompletions, lastCompletionItem);
            }
        }));
        this._register(toDisposable(() => {
            this.cache.clear();
        }));
        this._register(this.editor.onDidChangeCursorPosition((e) => {
            var _a;
            if (e.reason === 3 /* CursorChangeReason.Explicit */) {
                return;
            }
            // Ghost text depends on the cursor position
            (_a = this.cache.value) === null || _a === void 0 ? void 0 : _a.updateRanges();
            if (this.cache.value) {
                this.updateFilteredInlineCompletions();
                this.onDidChangeEmitter.fire();
            }
        }));
        this._register(this.editor.onDidChangeModelContent((e) => {
            var _a;
            // Call this in case `onDidChangeModelContent` calls us first.
            (_a = this.cache.value) === null || _a === void 0 ? void 0 : _a.updateRanges();
            this.updateFilteredInlineCompletions();
            this.scheduleAutomaticUpdate();
        }));
        this._register(this.registry.onDidChange(() => {
            this.updateSoon.schedule(this.debounce.get(this.editor.getModel()));
        }));
        this.scheduleAutomaticUpdate();
    }
    updateFilteredInlineCompletions() {
        if (!this.cache.value) {
            this.filteredCompletions = [];
            return;
        }
        const model = this.editor.getModel();
        const cursorPosition = model.validatePosition(this.editor.getPosition());
        this.filteredCompletions = this.cache.value.completions.filter(c => {
            const originalValue = model.getValueInRange(c.synchronizedRange).toLowerCase();
            const filterText = c.inlineCompletion.filterText.toLowerCase();
            const indent = model.getLineIndentColumn(c.synchronizedRange.startLineNumber);
            const cursorPosIndex = Math.max(0, cursorPosition.column - c.synchronizedRange.startColumn);
            let filterTextBefore = filterText.substring(0, cursorPosIndex);
            let filterTextAfter = filterText.substring(cursorPosIndex);
            let originalValueBefore = originalValue.substring(0, cursorPosIndex);
            let originalValueAfter = originalValue.substring(cursorPosIndex);
            if (c.synchronizedRange.startColumn <= indent) {
                // Remove indentation
                originalValueBefore = originalValueBefore.trimStart();
                if (originalValueBefore.length === 0) {
                    originalValueAfter = originalValueAfter.trimStart();
                }
                filterTextBefore = filterTextBefore.trimStart();
                if (filterTextBefore.length === 0) {
                    filterTextAfter = filterTextAfter.trimStart();
                }
            }
            return filterTextBefore.startsWith(originalValueBefore)
                && matchesSubString(originalValueAfter, filterTextAfter);
        });
    }
    fixAndGetIndexOfCurrentSelection() {
        if (!this.currentlySelectedCompletionId || !this.cache.value) {
            return 0;
        }
        if (this.cache.value.completions.length === 0) {
            // don't reset the selection in this case
            return 0;
        }
        const idx = this.filteredCompletions.findIndex(v => v.semanticId === this.currentlySelectedCompletionId);
        if (idx === -1) {
            // Reset the selection so that the selection does not jump back when it appears again
            this.currentlySelectedCompletionId = undefined;
            return 0;
        }
        return idx;
    }
    get currentCachedCompletion() {
        if (!this.cache.value) {
            return undefined;
        }
        return this.filteredCompletions[this.fixAndGetIndexOfCurrentSelection()];
    }
    showNextInlineCompletion() {
        return inlineCompletionsModel_awaiter(this, void 0, void 0, function* () {
            yield this.ensureUpdateWithExplicitContext();
            const completions = this.filteredCompletions || [];
            if (completions.length > 0) {
                const newIdx = (this.fixAndGetIndexOfCurrentSelection() + 1) % completions.length;
                this.currentlySelectedCompletionId = completions[newIdx].semanticId;
            }
            else {
                this.currentlySelectedCompletionId = undefined;
            }
            this.onDidChangeEmitter.fire();
        });
    }
    showPreviousInlineCompletion() {
        return inlineCompletionsModel_awaiter(this, void 0, void 0, function* () {
            yield this.ensureUpdateWithExplicitContext();
            const completions = this.filteredCompletions || [];
            if (completions.length > 0) {
                const newIdx = (this.fixAndGetIndexOfCurrentSelection() + completions.length - 1) % completions.length;
                this.currentlySelectedCompletionId = completions[newIdx].semanticId;
            }
            else {
                this.currentlySelectedCompletionId = undefined;
            }
            this.onDidChangeEmitter.fire();
        });
    }
    ensureUpdateWithExplicitContext() {
        var _a;
        return inlineCompletionsModel_awaiter(this, void 0, void 0, function* () {
            if (this.updateOperation.value) {
                // Restart or wait for current update operation
                if (this.updateOperation.value.triggerKind === InlineCompletionTriggerKind.Explicit) {
                    yield this.updateOperation.value.promise;
                }
                else {
                    yield this.update(InlineCompletionTriggerKind.Explicit);
                }
            }
            else if (((_a = this.cache.value) === null || _a === void 0 ? void 0 : _a.triggerKind) !== InlineCompletionTriggerKind.Explicit) {
                // Refresh cache
                yield this.update(InlineCompletionTriggerKind.Explicit);
            }
        });
    }
    hasMultipleInlineCompletions() {
        var _a;
        return inlineCompletionsModel_awaiter(this, void 0, void 0, function* () {
            yield this.ensureUpdateWithExplicitContext();
            return (((_a = this.cache.value) === null || _a === void 0 ? void 0 : _a.completions.length) || 0) > 1;
        });
    }
    //#endregion
    get ghostText() {
        const currentCompletion = this.currentCompletion;
        if (!currentCompletion) {
            return undefined;
        }
        const cursorPosition = this.editor.getPosition();
        if (currentCompletion.range.getEndPosition().isBefore(cursorPosition)) {
            return undefined;
        }
        const mode = this.editor.getOptions().get(57 /* EditorOption.inlineSuggest */).mode;
        const ghostText = inlineCompletionToGhostText(currentCompletion, this.editor.getModel(), mode, cursorPosition);
        if (ghostText) {
            if (ghostText.isEmpty()) {
                return undefined;
            }
            return ghostText;
        }
        return new GhostTextReplacement(currentCompletion.range.startLineNumber, currentCompletion.range.startColumn, currentCompletion.range.endColumn - currentCompletion.range.startColumn, currentCompletion.insertText.split('\n'), 0);
    }
    get currentCompletion() {
        const completion = this.currentCachedCompletion;
        if (!completion) {
            return undefined;
        }
        return completion.toLiveInlineCompletion();
    }
    get isValid() {
        return this.editor.getPosition().lineNumber === this.triggerPosition.lineNumber;
    }
    scheduleAutomaticUpdate() {
        // Since updateSoon debounces, starvation can happen.
        // To prevent stale cache, we clear the current update operation.
        this.updateOperation.clear();
        this.updateSoon.schedule(this.debounce.get(this.editor.getModel()));
    }
    update(triggerKind) {
        return inlineCompletionsModel_awaiter(this, void 0, void 0, function* () {
            if (!this.shouldUpdate()) {
                return;
            }
            const position = this.editor.getPosition();
            const startTime = new Date();
            const promise = createCancelablePromise((token) => inlineCompletionsModel_awaiter(this, void 0, void 0, function* () {
                let result;
                try {
                    result = yield provideInlineCompletions(this.registry, position, this.editor.getModel(), { triggerKind, selectedSuggestionInfo: undefined }, token, this.languageConfigurationService);
                    const endTime = new Date();
                    this.debounce.update(this.editor.getModel(), endTime.getTime() - startTime.getTime());
                }
                catch (e) {
                    onUnexpectedError(e);
                    return;
                }
                if (token.isCancellationRequested) {
                    return;
                }
                this.cache.setValue(this.editor, result, triggerKind);
                this.updateFilteredInlineCompletions();
                this.onDidChangeEmitter.fire();
            }));
            const operation = new UpdateOperation(promise, triggerKind);
            this.updateOperation.value = operation;
            yield promise;
            if (this.updateOperation.value === operation) {
                this.updateOperation.clear();
            }
        });
    }
    takeOwnership(disposable) {
        this._register(disposable);
    }
    commitCurrentCompletion() {
        const ghostText = this.ghostText;
        if (!ghostText) {
            // No ghost text was shown for this completion.
            // Thus, we don't want to commit anything.
            return;
        }
        const completion = this.currentCompletion;
        if (completion) {
            this.commit(completion);
        }
    }
    commit(completion) {
        var _a;
        // Mark the cache as stale, but don't dispose it yet,
        // otherwise command args might get disposed.
        const cache = this.cache.clearAndLeak();
        if (completion.snippetInfo) {
            this.editor.executeEdits('inlineSuggestion.accept', [
                EditOperation.replaceMove(completion.range, ''),
                ...completion.additionalTextEdits
            ]);
            this.editor.setPosition(completion.snippetInfo.range.getStartPosition());
            (_a = SnippetController2.get(this.editor)) === null || _a === void 0 ? void 0 : _a.insert(completion.snippetInfo.snippet);
        }
        else {
            this.editor.executeEdits('inlineSuggestion.accept', [
                EditOperation.replaceMove(completion.range, completion.insertText),
                ...completion.additionalTextEdits
            ]);
        }
        if (completion.command) {
            this.commandService
                .executeCommand(completion.command.id, ...(completion.command.arguments || []))
                .finally(() => {
                cache === null || cache === void 0 ? void 0 : cache.dispose();
            })
                .then(undefined, onUnexpectedExternalError);
        }
        else {
            cache === null || cache === void 0 ? void 0 : cache.dispose();
        }
        this.onDidChangeEmitter.fire();
    }
    get commands() {
        var _a;
        const lists = new Set(((_a = this.cache.value) === null || _a === void 0 ? void 0 : _a.completions.map(c => c.inlineCompletion.sourceInlineCompletions)) || []);
        return [...lists].flatMap(l => l.commands || []);
    }
}
class UpdateOperation {
    constructor(promise, triggerKind) {
        this.promise = promise;
        this.triggerKind = triggerKind;
    }
    dispose() {
        this.promise.cancel();
    }
}
/**
 * The cache keeps itself in sync with the editor.
 * It also owns the completions result and disposes it when the cache is diposed.
*/
class SynchronizedInlineCompletionsCache extends Disposable {
    constructor(completionsSource, editor, onChange, triggerKind) {
        super();
        this.editor = editor;
        this.onChange = onChange;
        this.triggerKind = triggerKind;
        this.isDisposing = false;
        const decorationIds = editor.changeDecorations((changeAccessor) => {
            return changeAccessor.deltaDecorations([], completionsSource.items.map(i => ({
                range: i.range,
                options: {
                    description: 'inline-completion-tracking-range'
                },
            })));
        });
        this._register(toDisposable(() => {
            this.isDisposing = true;
            editor.removeDecorations(decorationIds);
        }));
        this.completions = completionsSource.items.map((c, idx) => new CachedInlineCompletion(c, decorationIds[idx]));
        this._register(editor.onDidChangeModelContent(() => {
            this.updateRanges();
        }));
        this._register(completionsSource);
    }
    updateRanges() {
        if (this.isDisposing) {
            return;
        }
        let hasChanged = false;
        const model = this.editor.getModel();
        for (const c of this.completions) {
            const newRange = model.getDecorationRange(c.decorationId);
            if (!newRange) {
                onUnexpectedError(new Error('Decoration has no range'));
                continue;
            }
            if (!c.synchronizedRange.equalsRange(newRange)) {
                hasChanged = true;
                c.synchronizedRange = newRange;
            }
        }
        if (hasChanged) {
            this.onChange();
        }
    }
}
class CachedInlineCompletion {
    constructor(inlineCompletion, decorationId) {
        this.inlineCompletion = inlineCompletion;
        this.decorationId = decorationId;
        this.semanticId = JSON.stringify({
            text: this.inlineCompletion.insertText,
            abbreviation: this.inlineCompletion.filterText,
            startLine: this.inlineCompletion.range.startLineNumber,
            startColumn: this.inlineCompletion.range.startColumn,
            command: this.inlineCompletion.command
        });
        this.synchronizedRange = inlineCompletion.range;
    }
    toLiveInlineCompletion() {
        return {
            insertText: this.inlineCompletion.insertText,
            range: this.synchronizedRange,
            command: this.inlineCompletion.command,
            sourceProvider: this.inlineCompletion.sourceProvider,
            sourceInlineCompletions: this.inlineCompletion.sourceInlineCompletions,
            sourceInlineCompletion: this.inlineCompletion.sourceInlineCompletion,
            snippetInfo: this.inlineCompletion.snippetInfo,
            filterText: this.inlineCompletion.filterText,
            additionalTextEdits: this.inlineCompletion.additionalTextEdits,
        };
    }
}
function provideInlineCompletions(registry, position, model, context, token = CancellationToken.None, languageConfigurationService) {
    return inlineCompletionsModel_awaiter(this, void 0, void 0, function* () {
        const defaultReplaceRange = getDefaultRange(position, model);
        const providers = registry.all(model);
        const results = yield Promise.all(providers.map((provider) => inlineCompletionsModel_awaiter(this, void 0, void 0, function* () {
            const completions = yield Promise.resolve(provider.provideInlineCompletions(model, position, context, token)).catch(onUnexpectedExternalError);
            return ({
                completions,
                provider,
                dispose: () => {
                    if (completions) {
                        provider.freeInlineCompletions(completions);
                    }
                }
            });
        })));
        const itemsByHash = new Map();
        for (const result of results) {
            const completions = result.completions;
            if (!completions) {
                continue;
            }
            for (const item of completions.items) {
                let range = item.range ? Range.lift(item.range) : defaultReplaceRange;
                if (range.startLineNumber !== range.endLineNumber) {
                    // Ignore invalid ranges.
                    continue;
                }
                let insertText;
                let snippetInfo;
                if (typeof item.insertText === 'string') {
                    insertText = item.insertText;
                    if (languageConfigurationService && item.completeBracketPairs) {
                        insertText = closeBrackets(insertText, range.getStartPosition(), model, languageConfigurationService);
                        // Modify range depending on if brackets are added or removed
                        const diff = insertText.length - item.insertText.length;
                        if (diff !== 0) {
                            range = new Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn + diff);
                        }
                    }
                    snippetInfo = undefined;
                }
                else if ('snippet' in item.insertText) {
                    const snippet = new SnippetParser().parse(item.insertText.snippet);
                    insertText = snippet.toString();
                    snippetInfo = {
                        snippet: item.insertText.snippet,
                        range: range
                    };
                }
                else {
                    assertNever(item.insertText);
                }
                const trackedItem = ({
                    insertText,
                    snippetInfo,
                    range,
                    command: item.command,
                    sourceProvider: result.provider,
                    sourceInlineCompletions: completions,
                    sourceInlineCompletion: item,
                    filterText: item.filterText || insertText,
                    additionalTextEdits: item.additionalTextEdits || getReadonlyEmptyArray()
                });
                itemsByHash.set(JSON.stringify({ insertText, range: item.range }), trackedItem);
            }
        }
        return {
            items: [...itemsByHash.values()],
            dispose: () => {
                for (const result of results) {
                    result.dispose();
                }
            },
        };
    });
}
function getDefaultRange(position, model) {
    const word = model.getWordAtPosition(position);
    const maxColumn = model.getLineMaxColumn(position.lineNumber);
    // By default, always replace up until the end of the current line.
    // This default might be subject to change!
    return word
        ? new Range(position.lineNumber, word.startColumn, position.lineNumber, maxColumn)
        : Range.fromPositions(position, position.with(undefined, maxColumn));
}
function closeBrackets(text, position, model, languageConfigurationService) {
    const lineStart = model.getLineContent(position.lineNumber).substring(0, position.column - 1);
    const newLine = lineStart + text;
    const newTokens = model.tokenization.tokenizeLineWithEdit(position, newLine.length - (position.column - 1), text);
    const slicedTokens = newTokens === null || newTokens === void 0 ? void 0 : newTokens.sliceAndInflate(position.column - 1, newLine.length, 0);
    if (!slicedTokens) {
        return text;
    }
    const newText = fixBracketsInLine(slicedTokens, languageConfigurationService);
    return newText;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggestMemory.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var suggestMemory_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var suggestMemory_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};








class Memory {
    constructor(name) {
        this.name = name;
    }
    select(model, pos, items) {
        if (items.length === 0) {
            return 0;
        }
        const topScore = items[0].score[0];
        for (let i = 0; i < items.length; i++) {
            const { score, completion: suggestion } = items[i];
            if (score[0] !== topScore) {
                // stop when leaving the group of top matches
                break;
            }
            if (suggestion.preselect) {
                // stop when seeing an auto-select-item
                return i;
            }
        }
        return 0;
    }
}
class NoMemory extends Memory {
    constructor() {
        super('first');
    }
    memorize(model, pos, item) {
        // no-op
    }
    toJSON() {
        return undefined;
    }
    fromJSON() {
        //
    }
}
class LRUMemory extends Memory {
    constructor() {
        super('recentlyUsed');
        this._cache = new LRUCache(300, 0.66);
        this._seq = 0;
    }
    memorize(model, pos, item) {
        const key = `${model.getLanguageId()}/${item.textLabel}`;
        this._cache.set(key, {
            touch: this._seq++,
            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 i = 0; i < items.length; i++) {
            if (items[i].score[0] !== topScore) {
                // consider only top items
                break;
            }
            const key = `${model.getLanguageId()}/${items[i].textLabel}`;
            const item = this._cache.peek(key);
            if (item && item.touch > seq && item.type === items[i].completion.kind && item.insertText === items[i].completion.insertText) {
                seq = item.touch;
                indexRecency = i;
            }
            if (items[i].completion.preselect && indexPreselect === -1) {
                // stop when seeing an auto-select-item
                return indexPreselect = i;
            }
        }
        if (indexRecency !== -1) {
            return indexRecency;
        }
        else if (indexPreselect !== -1) {
            return indexPreselect;
        }
        else {
            return 0;
        }
    }
    toJSON() {
        return this._cache.toJSON();
    }
    fromJSON(data) {
        this._cache.clear();
        const seq = 0;
        for (const [key, value] of data) {
            value.touch = seq;
            value.type = typeof value.type === 'number' ? value.type : CompletionItemKinds.fromString(value.type);
            this._cache.set(key, value);
        }
        this._seq = this._cache.size;
    }
}
class PrefixMemory extends Memory {
    constructor() {
        super('recentlyUsedByPrefix');
        this._trie = map_TernarySearchTree.forStrings();
        this._seq = 0;
    }
    memorize(model, pos, item) {
        const { word } = model.getWordUntilPosition(pos);
        const key = `${model.getLanguageId()}/${word}`;
        this._trie.set(key, {
            type: item.completion.kind,
            insertText: item.completion.insertText,
            touch: this._seq++
        });
    }
    select(model, pos, items) {
        const { word } = model.getWordUntilPosition(pos);
        if (!word) {
            return super.select(model, pos, items);
        }
        const key = `${model.getLanguageId()}/${word}`;
        let item = this._trie.get(key);
        if (!item) {
            item = this._trie.findSubstr(key);
        }
        if (item) {
            for (let i = 0; i < items.length; i++) {
                const { kind, insertText } = items[i].completion;
                if (kind === item.type && insertText === item.insertText) {
                    return i;
                }
            }
        }
        return super.select(model, pos, items);
    }
    toJSON() {
        const entries = [];
        this._trie.forEach((value, key) => entries.push([key, value]));
        // sort by last recently used (touch), then
        // take the top 200 item and normalize their
        // touch
        entries
            .sort((a, b) => -(a[1].touch - b[1].touch))
            .forEach((value, i) => value[1].touch = i);
        return entries.slice(0, 200);
    }
    fromJSON(data) {
        this._trie.clear();
        if (data.length > 0) {
            this._seq = data[0][1].touch + 1;
            for (const [key, value] of data) {
                value.type = typeof value.type === 'number' ? value.type : CompletionItemKinds.fromString(value.type);
                this._trie.set(key, value);
            }
        }
    }
}
let SuggestMemoryService = class SuggestMemoryService {
    constructor(_storageService, _configService) {
        this._storageService = _storageService;
        this._configService = _configService;
        this._disposables = new DisposableStore();
        this._persistSoon = new RunOnceScheduler(() => this._saveState(), 500);
        this._disposables.add(_storageService.onWillSaveState(e => {
            if (e.reason === WillSaveStateReason.SHUTDOWN) {
                this._saveState();
            }
        }));
    }
    dispose() {
        this._disposables.dispose();
        this._persistSoon.dispose();
    }
    memorize(model, pos, item) {
        this._withStrategy(model, pos).memorize(model, pos, item);
        this._persistSoon.schedule();
    }
    select(model, pos, items) {
        return this._withStrategy(model, pos).select(model, pos, items);
    }
    _withStrategy(model, pos) {
        var _a;
        const mode = this._configService.getValue('editor.suggestSelection', {
            overrideIdentifier: model.getLanguageIdAtPosition(pos.lineNumber, pos.column),
            resource: model.uri
        });
        if (((_a = this._strategy) === null || _a === void 0 ? void 0 : _a.name) !== mode) {
            this._saveState();
            const ctor = SuggestMemoryService._strategyCtors.get(mode) || NoMemory;
            this._strategy = new ctor();
            try {
                const share = this._configService.getValue('editor.suggest.shareSuggestSelections');
                const scope = share ? 0 /* StorageScope.PROFILE */ : 1 /* StorageScope.WORKSPACE */;
                const raw = this._storageService.get(`${SuggestMemoryService._storagePrefix}/${mode}`, scope);
                if (raw) {
                    this._strategy.fromJSON(JSON.parse(raw));
                }
            }
            catch (e) {
                // things can go wrong with JSON...
            }
        }
        return this._strategy;
    }
    _saveState() {
        if (this._strategy) {
            const share = this._configService.getValue('editor.suggest.shareSuggestSelections');
            const scope = share ? 0 /* StorageScope.PROFILE */ : 1 /* StorageScope.WORKSPACE */;
            const raw = JSON.stringify(this._strategy);
            this._storageService.store(`${SuggestMemoryService._storagePrefix}/${this._strategy.name}`, raw, scope, 1 /* StorageTarget.MACHINE */);
        }
    }
};
SuggestMemoryService._strategyCtors = new Map([
    ['recentlyUsedByPrefix', PrefixMemory],
    ['recentlyUsed', LRUMemory],
    ['first', NoMemory]
]);
SuggestMemoryService._storagePrefix = 'suggest/memories';
SuggestMemoryService = suggestMemory_decorate([
    suggestMemory_param(0, IStorageService),
    suggestMemory_param(1, IConfigurationService)
], SuggestMemoryService);

const ISuggestMemoryService = createDecorator('ISuggestMemories');
registerSingleton(ISuggestMemoryService, SuggestMemoryService, true);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/wordContextKey.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var wordContextKey_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var wordContextKey_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};

let WordContextKey = class WordContextKey {
    constructor(_editor, contextKeyService) {
        this._editor = _editor;
        this._enabled = false;
        this._ckAtEnd = WordContextKey.AtEnd.bindTo(contextKeyService);
        this._configListener = this._editor.onDidChangeConfiguration(e => e.hasChanged(113 /* EditorOption.tabCompletion */) && this._update());
        this._update();
    }
    dispose() {
        var _a;
        this._configListener.dispose();
        (_a = this._selectionListener) === null || _a === void 0 ? void 0 : _a.dispose();
        this._ckAtEnd.reset();
    }
    _update() {
        // only update this when tab completions are enabled
        const enabled = this._editor.getOption(113 /* EditorOption.tabCompletion */) === 'on';
        if (this._enabled === enabled) {
            return;
        }
        this._enabled = enabled;
        if (this._enabled) {
            const checkForWordEnd = () => {
                if (!this._editor.hasModel()) {
                    this._ckAtEnd.set(false);
                    return;
                }
                const model = this._editor.getModel();
                const selection = this._editor.getSelection();
                const word = model.getWordAtPosition(selection.getStartPosition());
                if (!word) {
                    this._ckAtEnd.set(false);
                    return;
                }
                this._ckAtEnd.set(word.endColumn === selection.getStartPosition().column);
            };
            this._selectionListener = this._editor.onDidChangeCursorSelection(checkForWordEnd);
            checkForWordEnd();
        }
        else if (this._selectionListener) {
            this._ckAtEnd.reset();
            this._selectionListener.dispose();
            this._selectionListener = undefined;
        }
    }
};
WordContextKey.AtEnd = new RawContextKey('atEndOfWord', false);
WordContextKey = wordContextKey_decorate([
    wordContextKey_param(1, IContextKeyService)
], WordContextKey);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggestAlternatives.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var suggestAlternatives_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var suggestAlternatives_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};

let SuggestAlternatives = class SuggestAlternatives {
    constructor(_editor, contextKeyService) {
        this._editor = _editor;
        this._index = 0;
        this._ckOtherSuggestions = SuggestAlternatives.OtherSuggestions.bindTo(contextKeyService);
    }
    dispose() {
        this.reset();
    }
    reset() {
        var _a;
        this._ckOtherSuggestions.reset();
        (_a = this._listener) === null || _a === void 0 ? void 0 : _a.dispose();
        this._model = undefined;
        this._acceptNext = undefined;
        this._ignore = false;
    }
    set({ model, index }, acceptNext) {
        // no suggestions -> nothing to do
        if (model.items.length === 0) {
            this.reset();
            return;
        }
        // no alternative suggestions -> nothing to do
        const nextIndex = SuggestAlternatives._moveIndex(true, model, index);
        if (nextIndex === index) {
            this.reset();
            return;
        }
        this._acceptNext = acceptNext;
        this._model = model;
        this._index = index;
        this._listener = this._editor.onDidChangeCursorPosition(() => {
            if (!this._ignore) {
                this.reset();
            }
        });
        this._ckOtherSuggestions.set(true);
    }
    static _moveIndex(fwd, model, index) {
        let newIndex = index;
        while (true) {
            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._move(true);
    }
    prev() {
        this._move(false);
    }
    _move(fwd) {
        if (!this._model) {
            // nothing to reason about
            return;
        }
        try {
            this._ignore = true;
            this._index = SuggestAlternatives._moveIndex(fwd, this._model, this._index);
            this._acceptNext({ index: this._index, item: this._model.items[this._index], model: this._model });
        }
        finally {
            this._ignore = false;
        }
    }
};
SuggestAlternatives.OtherSuggestions = new RawContextKey('hasOtherSuggestions', false);
SuggestAlternatives = suggestAlternatives_decorate([
    suggestAlternatives_param(1, IContextKeyService)
], SuggestAlternatives);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggestCommitCharacters.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class CommitCharacterController {
    constructor(editor, widget, accept) {
        this._disposables = new DisposableStore();
        this._disposables.add(widget.onDidShow(() => this._onItem(widget.getFocusedItem())));
        this._disposables.add(widget.onDidFocus(this._onItem, this));
        this._disposables.add(widget.onDidHide(this.reset, this));
        this._disposables.add(editor.onWillType(text => {
            if (this._active && !widget.isFrozen()) {
                const ch = text.charCodeAt(text.length - 1);
                if (this._active.acceptCharacters.has(ch) && editor.getOption(0 /* EditorOption.acceptSuggestionOnCommitCharacter */)) {
                    accept(this._active.item);
                }
            }
        }));
    }
    _onItem(selected) {
        if (!selected || !isNonEmptyArray(selected.item.completion.commitCharacters)) {
            // no item or no commit characters
            this.reset();
            return;
        }
        if (this._active && this._active.item.item === selected.item) {
            // still the same item
            return;
        }
        // keep item and its commit characters
        const acceptCharacters = new CharacterSet();
        for (const ch of selected.item.completion.commitCharacters) {
            if (ch.length > 0) {
                acceptCharacters.add(ch.charCodeAt(0));
            }
        }
        this._active = { acceptCharacters, item: selected };
    }
    reset() {
        this._active = undefined;
    }
    dispose() {
        this._disposables.dispose();
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/smartSelect/browser/bracketSelections.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var bracketSelections_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};



class BracketSelectionRangeProvider {
    provideSelectionRanges(model, positions) {
        return bracketSelections_awaiter(this, void 0, void 0, function* () {
            const result = [];
            for (const position of positions) {
                const bucket = [];
                result.push(bucket);
                const ranges = new Map();
                yield new Promise(resolve => BracketSelectionRangeProvider._bracketsRightYield(resolve, 0, model, position, ranges));
                yield new Promise(resolve => BracketSelectionRangeProvider._bracketsLeftYield(resolve, 0, model, position, ranges, bucket));
            }
            return result;
        });
    }
    static _bracketsRightYield(resolve, round, model, pos, ranges) {
        const counts = new Map();
        const t1 = Date.now();
        while (true) {
            if (round >= BracketSelectionRangeProvider._maxRounds) {
                resolve();
                break;
            }
            if (!pos) {
                resolve();
                break;
            }
            const bracket = model.bracketPairs.findNextBracket(pos);
            if (!bracket) {
                resolve();
                break;
            }
            const d = Date.now() - t1;
            if (d > BracketSelectionRangeProvider._maxDuration) {
                setTimeout(() => BracketSelectionRangeProvider._bracketsRightYield(resolve, round + 1, model, pos, ranges));
                break;
            }
            if (bracket.bracketInfo.isOpeningBracket) {
                const key = bracket.bracketInfo.bracketText;
                // wait for closing
                const val = counts.has(key) ? counts.get(key) : 0;
                counts.set(key, val + 1);
            }
            else {
                const key = bracket.bracketInfo.getClosedBrackets()[0].bracketText;
                // process closing
                let val = counts.has(key) ? counts.get(key) : 0;
                val -= 1;
                counts.set(key, Math.max(0, val));
                if (val < 0) {
                    let list = ranges.get(key);
                    if (!list) {
                        list = new LinkedList();
                        ranges.set(key, list);
                    }
                    list.push(bracket.range);
                }
            }
            pos = bracket.range.getEndPosition();
        }
    }
    static _bracketsLeftYield(resolve, round, model, pos, ranges, bucket) {
        const counts = new Map();
        const t1 = Date.now();
        while (true) {
            if (round >= BracketSelectionRangeProvider._maxRounds && 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 > BracketSelectionRangeProvider._maxDuration) {
                setTimeout(() => BracketSelectionRangeProvider._bracketsLeftYield(resolve, round + 1, model, pos, ranges, bucket));
                break;
            }
            if (!bracket.bracketInfo.isOpeningBracket) {
                const key = bracket.bracketInfo.getClosedBrackets()[0].bracketText;
                // wait for opening
                const val = counts.has(key) ? counts.get(key) : 0;
                counts.set(key, val + 1);
            }
            else {
                const key = bracket.bracketInfo.bracketText;
                // opening
                let val = counts.has(key) ? counts.get(key) : 0;
                val -= 1;
                counts.set(key, Math.max(0, val));
                if (val < 0) {
                    const list = ranges.get(key);
                    if (list) {
                        const closing = list.shift();
                        if (list.size === 0) {
                            ranges.delete(key);
                        }
                        const innerBracket = Range.fromPositions(bracket.range.getEndPosition(), closing.getStartPosition());
                        const outerBracket = Range.fromPositions(bracket.range.getStartPosition(), closing.getEndPosition());
                        bucket.push({ range: innerBracket });
                        bucket.push({ range: outerBracket });
                        BracketSelectionRangeProvider._addBracketLeading(model, outerBracket, bucket);
                    }
                }
            }
            pos = bracket.range.getStartPosition();
        }
    }
    static _addBracketLeading(model, bracket, bucket) {
        if (bracket.startLineNumber === bracket.endLineNumber) {
            return;
        }
        // xxxxxxxx {
        //
        // }
        const startLine = bracket.startLineNumber;
        const column = model.getLineFirstNonWhitespaceColumn(startLine);
        if (column !== 0 && column !== bracket.startColumn) {
            bucket.push({ range: Range.fromPositions(new Position(startLine, column), bracket.getEndPosition()) });
            bucket.push({ range: Range.fromPositions(new Position(startLine, 1), bracket.getEndPosition()) });
        }
        // xxxxxxxx
        // {
        //
        // }
        const aboveLine = startLine - 1;
        if (aboveLine > 0) {
            const column = model.getLineFirstNonWhitespaceColumn(aboveLine);
            if (column === bracket.startColumn && column !== model.getLineLastNonWhitespaceColumn(aboveLine)) {
                bucket.push({ range: Range.fromPositions(new Position(aboveLine, column), bracket.getEndPosition()) });
                bucket.push({ range: Range.fromPositions(new Position(aboveLine, 1), bracket.getEndPosition()) });
            }
        }
    }
}
BracketSelectionRangeProvider._maxDuration = 30;
BracketSelectionRangeProvider._maxRounds = 2;

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/wordDistance.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var wordDistance_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};



class WordDistance {
    static create(service, editor) {
        return wordDistance_awaiter(this, void 0, void 0, function* () {
            if (!editor.getOption(108 /* EditorOption.suggest */).localityBonus) {
                return WordDistance.None;
            }
            if (!editor.hasModel()) {
                return WordDistance.None;
            }
            const model = editor.getModel();
            const position = editor.getPosition();
            if (!service.canComputeWordRanges(model.uri)) {
                return WordDistance.None;
            }
            const [ranges] = yield new BracketSelectionRangeProvider().provideSelectionRanges(model, [position]);
            if (ranges.length === 0) {
                return WordDistance.None;
            }
            const wordRanges = yield service.computeWordRanges(model.uri, ranges[0].range);
            if (!wordRanges) {
                return WordDistance.None;
            }
            // remove current word
            const wordUntilPos = model.getWordUntilPosition(position);
            delete wordRanges[wordUntilPos.word];
            return new class extends WordDistance {
                distance(anchor, item) {
                    if (!position.equals(editor.getPosition())) {
                        return 0;
                    }
                    if (item.kind === 17 /* CompletionItemKind.Keyword */) {
                        return 2 << 20;
                    }
                    const word = typeof item.label === 'string' ? item.label : item.label.label;
                    const wordLines = wordRanges[word];
                    if (isFalsyOrEmpty(wordLines)) {
                        return 2 << 20;
                    }
                    const idx = binarySearch(wordLines, Range.fromPositions(anchor), Range.compareRangesUsingStarts);
                    const bestWordRange = idx >= 0 ? wordLines[idx] : wordLines[Math.max(0, ~idx - 1)];
                    let blockDistance = ranges.length;
                    for (const range of ranges) {
                        if (!Range.containsRange(range.range, bestWordRange)) {
                            break;
                        }
                        blockDistance -= 1;
                    }
                    return blockDistance;
                }
            };
        });
    }
}
WordDistance.None = new class extends WordDistance {
    distance() { return 0; }
};

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/completionModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class LineContext {
    constructor(leadingLineContent, characterCountDelta) {
        this.leadingLineContent = leadingLineContent;
        this.characterCountDelta = characterCountDelta;
    }
}
/**
 * Sorted, filtered completion view model
 * */
class CompletionModel {
    constructor(items, column, lineContext, wordDistance, options, snippetSuggestions, fuzzyScoreOptions = FuzzyScoreOptions.default, clipboardText = undefined) {
        this.clipboardText = clipboardText;
        this._snippetCompareFn = CompletionModel._compareCompletionItems;
        this._items = items;
        this._column = column;
        this._wordDistance = wordDistance;
        this._options = options;
        this._refilterKind = 1 /* Refilter.All */;
        this._lineContext = lineContext;
        this._fuzzyScoreOptions = fuzzyScoreOptions;
        if (snippetSuggestions === 'top') {
            this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsUp;
        }
        else if (snippetSuggestions === 'bottom') {
            this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsDown;
        }
    }
    get lineContext() {
        return this._lineContext;
    }
    set lineContext(value) {
        if (this._lineContext.leadingLineContent !== value.leadingLineContent
            || this._lineContext.characterCountDelta !== value.characterCountDelta) {
            this._refilterKind = this._lineContext.characterCountDelta < value.characterCountDelta && this._filteredItems ? 2 /* Refilter.Incr */ : 1 /* Refilter.All */;
            this._lineContext = value;
        }
    }
    get items() {
        this._ensureCachedState();
        return this._filteredItems;
    }
    get allProvider() {
        this._ensureCachedState();
        return this._providerInfo.keys();
    }
    get incomplete() {
        this._ensureCachedState();
        const result = new Set();
        for (const [provider, incomplete] of this._providerInfo) {
            if (incomplete) {
                result.add(provider);
            }
        }
        return result;
    }
    adopt(except) {
        const res = [];
        for (let i = 0; i < this._items.length;) {
            if (!except.has(this._items[i].provider)) {
                res.push(this._items[i]);
                // unordered removed
                this._items[i] = this._items[this._items.length - 1];
                this._items.pop();
            }
            else {
                // continue with next item
                i++;
            }
        }
        this._refilterKind = 1 /* Refilter.All */;
        return res;
    }
    get stats() {
        this._ensureCachedState();
        return this._stats;
    }
    _ensureCachedState() {
        if (this._refilterKind !== 0 /* Refilter.Nothing */) {
            this._createCachedState();
        }
    }
    _createCachedState() {
        this._providerInfo = new Map();
        const labelLengths = [];
        const { leadingLineContent, characterCountDelta } = this._lineContext;
        let word = '';
        let wordLow = '';
        // incrementally filter less
        const source = this._refilterKind === 1 /* Refilter.All */ ? this._items : this._filteredItems;
        const target = [];
        // picks a score function based on the number of
        // items that we have to score/filter and based on the
        // user-configuration
        const scoreFn = (!this._options.filterGraceful || source.length > 2000) ? fuzzyScore : fuzzyScoreGracefulAggressive;
        for (let i = 0; i < source.length; i++) {
            const item = source[i];
            if (item.isInvalid) {
                continue; // SKIP invalid items
            }
            // collect all support, know if their result is incomplete
            this._providerInfo.set(item.provider, Boolean(item.container.incomplete));
            // 'word' is that remainder of the current line that we
            // filter and score against. In theory each suggestion uses a
            // different word, but in practice not - that's why we cache
            const overwriteBefore = item.position.column - item.editStart.column;
            const wordLen = overwriteBefore + characterCountDelta - (item.position.column - this._column);
            if (word.length !== wordLen) {
                word = wordLen === 0 ? '' : leadingLineContent.slice(-wordLen);
                wordLow = word.toLowerCase();
            }
            // remember the word against which this item was
            // scored
            item.word = word;
            if (wordLen === 0) {
                // when there is nothing to score against, don't
                // event try to do. Use a const rank and rely on
                // the fallback-sort using the initial sort order.
                // use a score of `-100` because that is out of the
                // bound of values `fuzzyScore` will return
                item.score = FuzzyScore.Default;
            }
            else {
                // skip word characters that are whitespace until
                // we have hit the replace range (overwriteBefore)
                let wordPos = 0;
                while (wordPos < overwriteBefore) {
                    const ch = word.charCodeAt(wordPos);
                    if (ch === 32 /* CharCode.Space */ || ch === 9 /* CharCode.Tab */) {
                        wordPos += 1;
                    }
                    else {
                        break;
                    }
                }
                if (wordPos >= wordLen) {
                    // the wordPos at which scoring starts is the whole word
                    // and therefore the same rules as not having a word apply
                    item.score = FuzzyScore.Default;
                }
                else if (typeof item.completion.filterText === 'string') {
                    // when there is a `filterText` it must match the `word`.
                    // if it matches we check with the label to compute highlights
                    // and if that doesn't yield a result we have no highlights,
                    // despite having the match
                    const match = scoreFn(word, wordLow, wordPos, item.completion.filterText, item.filterTextLow, 0, this._fuzzyScoreOptions);
                    if (!match) {
                        continue; // NO match
                    }
                    if (compareIgnoreCase(item.completion.filterText, item.textLabel) === 0) {
                        // filterText and label are actually the same -> use good highlights
                        item.score = match;
                    }
                    else {
                        // re-run the scorer on the label in the hope of a result BUT use the rank
                        // of the filterText-match
                        item.score = anyScore(word, wordLow, wordPos, item.textLabel, item.labelLow, 0);
                        item.score[0] = match[0]; // use score from filterText
                    }
                }
                else {
                    // by default match `word` against the `label`
                    const match = scoreFn(word, wordLow, wordPos, item.textLabel, item.labelLow, 0, this._fuzzyScoreOptions);
                    if (!match) {
                        continue; // NO match
                    }
                    item.score = match;
                }
            }
            item.idx = i;
            item.distance = this._wordDistance.distance(item.position, item.completion);
            target.push(item);
            // update stats
            labelLengths.push(item.textLabel.length);
        }
        this._filteredItems = target.sort(this._snippetCompareFn);
        this._refilterKind = 0 /* Refilter.Nothing */;
        this._stats = {
            pLabelLen: labelLengths.length ?
                quickSelect(labelLengths.length - .85, labelLengths, (a, b) => a - b)
                : 0
        };
    }
    static _compareCompletionItems(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 _compareCompletionItemsSnippetsDown(a, b) {
        if (a.completion.kind !== b.completion.kind) {
            if (a.completion.kind === 27 /* CompletionItemKind.Snippet */) {
                return 1;
            }
            else if (b.completion.kind === 27 /* CompletionItemKind.Snippet */) {
                return -1;
            }
        }
        return CompletionModel._compareCompletionItems(a, b);
    }
    static _compareCompletionItemsSnippetsUp(a, b) {
        if (a.completion.kind !== b.completion.kind) {
            if (a.completion.kind === 27 /* CompletionItemKind.Snippet */) {
                return -1;
            }
            else if (b.completion.kind === 27 /* CompletionItemKind.Snippet */) {
                return 1;
            }
        }
        return CompletionModel._compareCompletionItems(a, b);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggestModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var suggestModel_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var suggestModel_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var suggestModel_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};


















class suggestModel_LineContext {
    constructor(model, position, auto, shy, noSelect) {
        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.auto = auto;
        this.shy = shy;
        this.noSelect = noSelect;
    }
    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) {
            return false;
        }
        if (!isNaN(Number(word.word))) {
            return false;
        }
        return true;
    }
}
function isSuggestPreviewEnabled(editor) {
    return editor.getOption(108 /* EditorOption.suggest */).preview;
}
function canShowQuickSuggest(editor, contextKeyService, configurationService) {
    if (!Boolean(contextKeyService.getContextKeyValue('inlineSuggestionVisible'))) {
        // Allow if there is no inline suggestion.
        return true;
    }
    const allowQuickSuggestions = configurationService.getValue('editor.inlineSuggest.allowQuickSuggestions');
    if (allowQuickSuggestions !== undefined) {
        // Use setting if available.
        return Boolean(allowQuickSuggestions);
    }
    // Don't allow if inline suggestions are visible and no suggest preview is configured.
    // TODO disabled for copilot
    return  false && 0;
}
function canShowSuggestOnTriggerCharacters(editor, contextKeyService, configurationService) {
    if (!Boolean(contextKeyService.getContextKeyValue('inlineSuggestionVisible'))) {
        // Allow if there is no inline suggestion.
        return true;
    }
    const allowQuickSuggestions = configurationService.getValue('editor.inlineSuggest.allowSuggestOnTriggerCharacters');
    if (allowQuickSuggestions !== undefined) {
        // Use setting if available.
        return Boolean(allowQuickSuggestions);
    }
    // Don't allow if inline suggestions are visible and no suggest preview is configured.
    // TODO disabled for copilot
    return  false && 0;
}
let SuggestModel = class SuggestModel {
    constructor(_editor, _editorWorkerService, _clipboardService, _telemetryService, _logService, _contextKeyService, _configurationService, _languageFeaturesService) {
        this._editor = _editor;
        this._editorWorkerService = _editorWorkerService;
        this._clipboardService = _clipboardService;
        this._telemetryService = _telemetryService;
        this._logService = _logService;
        this._contextKeyService = _contextKeyService;
        this._configurationService = _configurationService;
        this._languageFeaturesService = _languageFeaturesService;
        this._toDispose = new DisposableStore();
        this._triggerCharacterListener = new DisposableStore();
        this._triggerQuickSuggest = new TimeoutTimer();
        this._state = 0 /* State.Idle */;
        this._completionDisposables = new DisposableStore();
        this._onDidCancel = new Emitter();
        this._onDidTrigger = new Emitter();
        this._onDidSuggest = new Emitter();
        this.onDidCancel = this._onDidCancel.event;
        this.onDidTrigger = this._onDidTrigger.event;
        this.onDidSuggest = this._onDidSuggest.event;
        this._telemetryGate = 0;
        this._currentSelection = this._editor.getSelection() || new Selection(1, 1, 1, 1);
        // wire up various listeners
        this._toDispose.add(this._editor.onDidChangeModel(() => {
            this._updateTriggerCharacters();
            this.cancel();
        }));
        this._toDispose.add(this._editor.onDidChangeModelLanguage(() => {
            this._updateTriggerCharacters();
            this.cancel();
        }));
        this._toDispose.add(this._editor.onDidChangeConfiguration(() => {
            this._updateTriggerCharacters();
        }));
        this._toDispose.add(this._languageFeaturesService.completionProvider.onDidChange(() => {
            this._updateTriggerCharacters();
            this._updateActiveSuggestSession();
        }));
        let editorIsComposing = false;
        this._toDispose.add(this._editor.onDidCompositionStart(() => {
            editorIsComposing = true;
        }));
        this._toDispose.add(this._editor.onDidCompositionEnd(() => {
            editorIsComposing = false;
            this._onCompositionEnd();
        }));
        this._toDispose.add(this._editor.onDidChangeCursorSelection(e => {
            // only trigger suggest when the editor isn't composing a character
            if (!editorIsComposing) {
                this._onCursorChange(e);
            }
        }));
        this._toDispose.add(this._editor.onDidChangeModelContent(() => {
            // only filter completions when the editor isn't composing a character
            // allow-any-unicode-next-line
            // e.g. ¨ + u makes ü but just ¨ cannot be used for filtering
            if (!editorIsComposing) {
                this._refilterCompletionItems();
            }
        }));
        this._updateTriggerCharacters();
    }
    dispose() {
        dispose(this._triggerCharacterListener);
        dispose([this._onDidCancel, this._onDidSuggest, this._onDidTrigger, this._triggerQuickSuggest]);
        this._toDispose.dispose();
        this._completionDisposables.dispose();
        this.cancel();
    }
    _updateTriggerCharacters() {
        this._triggerCharacterListener.clear();
        if (this._editor.getOption(83 /* EditorOption.readOnly */)
            || !this._editor.hasModel()
            || !this._editor.getOption(111 /* EditorOption.suggestOnTriggerCharacters */)) {
            return;
        }
        const supportsByTriggerCharacter = new Map();
        for (const support of this._languageFeaturesService.completionProvider.all(this._editor.getModel())) {
            for (const ch of support.triggerCharacters || []) {
                let set = supportsByTriggerCharacter.get(ch);
                if (!set) {
                    set = new Set();
                    set.add(getSnippetSuggestSupport());
                    supportsByTriggerCharacter.set(ch, set);
                }
                set.add(support);
            }
        }
        const checkTriggerCharacter = (text) => {
            if (!canShowSuggestOnTriggerCharacters(this._editor, this._contextKeyService, this._configurationService)) {
                return;
            }
            if (suggestModel_LineContext.shouldAutoTrigger(this._editor)) {
                // don't trigger by trigger characters when this is a case for quick suggest
                return;
            }
            if (!text) {
                // came here from the compositionEnd-event
                const position = this._editor.getPosition();
                const model = this._editor.getModel();
                text = model.getLineContent(position.lineNumber).substr(0, position.column - 1);
            }
            let lastChar = '';
            if (isLowSurrogate(text.charCodeAt(text.length - 1))) {
                if (isHighSurrogate(text.charCodeAt(text.length - 2))) {
                    lastChar = text.substr(text.length - 2);
                }
            }
            else {
                lastChar = text.charAt(text.length - 1);
            }
            const supports = supportsByTriggerCharacter.get(lastChar);
            if (supports) {
                // keep existing items that where not computed by the
                // supports/providers that want to trigger now
                const existing = this._completionModel
                    ? { items: this._completionModel.adopt(supports), clipboardText: this._completionModel.clipboardText }
                    : undefined;
                this.trigger({ auto: true, shy: false, noSelect: false, triggerCharacter: lastChar }, Boolean(this._completionModel), supports, existing);
            }
        };
        this._triggerCharacterListener.add(this._editor.onDidType(checkTriggerCharacter));
        this._triggerCharacterListener.add(this._editor.onDidCompositionEnd(() => checkTriggerCharacter()));
    }
    // --- trigger/retrigger/cancel suggest
    get state() {
        return this._state;
    }
    cancel(retrigger = false) {
        var _a;
        if (this._state !== 0 /* State.Idle */) {
            this._triggerQuickSuggest.cancel();
            (_a = this._requestToken) === null || _a === void 0 ? void 0 : _a.cancel();
            this._requestToken = undefined;
            this._state = 0 /* State.Idle */;
            this._completionModel = undefined;
            this._context = undefined;
            this._onDidCancel.fire({ retrigger });
        }
    }
    clear() {
        this._completionDisposables.clear();
    }
    _updateActiveSuggestSession() {
        if (this._state !== 0 /* State.Idle */) {
            if (!this._editor.hasModel() || !this._languageFeaturesService.completionProvider.has(this._editor.getModel())) {
                this.cancel();
            }
            else {
                this.trigger({ auto: this._state === 2 /* State.Auto */, shy: false, noSelect: false }, true);
            }
        }
    }
    _onCursorChange(e) {
        if (!this._editor.hasModel()) {
            return;
        }
        const prevSelection = this._currentSelection;
        this._currentSelection = this._editor.getSelection();
        if (!e.selection.isEmpty()
            || (e.reason !== 0 /* CursorChangeReason.NotSet */ && e.reason !== 3 /* CursorChangeReason.Explicit */)
            || (e.source !== 'keyboard' && e.source !== 'deleteLeft')) {
            // Early exit if nothing needs to be done!
            // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;)
            this.cancel();
            return;
        }
        if (this._state === 0 /* State.Idle */ && e.reason === 0 /* CursorChangeReason.NotSet */) {
            if (prevSelection.containsRange(this._currentSelection) || prevSelection.getEndPosition().isBeforeOrEqual(this._currentSelection.getPosition())) {
                // cursor did move RIGHT due to typing -> trigger quick suggest
                this._doTriggerQuickSuggest();
            }
        }
        else if (this._state !== 0 /* State.Idle */ && e.reason === 3 /* CursorChangeReason.Explicit */) {
            // suggest is active and something like cursor keys are used to move
            // the cursor. this means we can refilter at the new position
            this._refilterCompletionItems();
        }
    }
    _onCompositionEnd() {
        // trigger or refilter when composition ends
        if (this._state === 0 /* State.Idle */) {
            this._doTriggerQuickSuggest();
        }
        else {
            this._refilterCompletionItems();
        }
    }
    _doTriggerQuickSuggest() {
        var _a;
        if (QuickSuggestionsOptions.isAllOff(this._editor.getOption(81 /* EditorOption.quickSuggestions */))) {
            // not enabled
            return;
        }
        if (this._editor.getOption(108 /* EditorOption.suggest */).snippetsPreventQuickSuggestions && ((_a = SnippetController2.get(this._editor)) === null || _a === void 0 ? void 0 : _a.isInSnippet())) {
            // no quick suggestion when in snippet mode
            return;
        }
        this.cancel();
        this._triggerQuickSuggest.cancelAndSet(() => {
            if (this._state !== 0 /* State.Idle */) {
                return;
            }
            if (!suggestModel_LineContext.shouldAutoTrigger(this._editor)) {
                return;
            }
            if (!this._editor.hasModel() || !this._editor.hasWidgetFocus()) {
                return;
            }
            const model = this._editor.getModel();
            const pos = this._editor.getPosition();
            // validate enabled now
            const config = this._editor.getOption(81 /* EditorOption.quickSuggestions */);
            if (QuickSuggestionsOptions.isAllOff(config)) {
                return;
            }
            if (!QuickSuggestionsOptions.isAllOn(config)) {
                // Check the type of the token that triggered this
                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 (QuickSuggestionsOptions.valueFor(config, tokenType) !== 'on') {
                    return;
                }
            }
            if (!canShowQuickSuggest(this._editor, this._contextKeyService, this._configurationService)) {
                // do not trigger quick suggestions if inline suggestions are shown
                return;
            }
            if (!this._languageFeaturesService.completionProvider.has(model)) {
                return;
            }
            // we made it till here -> trigger now
            this.trigger({ auto: true, shy: false, noSelect: false });
        }, this._editor.getOption(82 /* EditorOption.quickSuggestionsDelay */));
    }
    _refilterCompletionItems() {
        // Re-filter suggestions. This MUST run async because filtering/scoring
        // uses the model content AND the cursor position. The latter is NOT
        // updated when the document has changed (the event which drives this method)
        // and therefore a little pause (next mirco task) is needed. See:
        // https://stackoverflow.com/questions/25915634/difference-between-microtask-and-macrotask-within-an-event-loop-context#25933985
        Promise.resolve().then(() => {
            if (this._state === 0 /* State.Idle */) {
                return;
            }
            if (!this._editor.hasModel()) {
                return;
            }
            const model = this._editor.getModel();
            const position = this._editor.getPosition();
            const ctx = new suggestModel_LineContext(model, position, this._state === 2 /* State.Auto */, false, false);
            this._onNewContext(ctx);
        });
    }
    trigger(context, retrigger = false, onlyFrom, existing, noFilter) {
        var _a;
        if (!this._editor.hasModel()) {
            return;
        }
        const model = this._editor.getModel();
        const auto = context.auto;
        const ctx = new suggestModel_LineContext(model, this._editor.getPosition(), auto, context.shy, context.noSelect);
        // Cancel previous requests, change state & update UI
        this.cancel(retrigger);
        this._state = auto ? 2 /* State.Auto */ : 1 /* State.Manual */;
        this._onDidTrigger.fire({ auto, shy: context.shy, position: this._editor.getPosition() });
        // Capture context when request was sent
        this._context = ctx;
        // Build context for request
        let suggestCtx = { triggerKind: (_a = context.triggerKind) !== null && _a !== void 0 ? _a : 0 /* CompletionTriggerKind.Invoke */ };
        if (context.triggerCharacter) {
            suggestCtx = {
                triggerKind: 1 /* CompletionTriggerKind.TriggerCharacter */,
                triggerCharacter: context.triggerCharacter
            };
        }
        this._requestToken = new CancellationTokenSource();
        // kind filter and snippet sort rules
        const snippetSuggestions = this._editor.getOption(103 /* EditorOption.snippetSuggestions */);
        let snippetSortOrder = 1 /* SnippetSortOrder.Inline */;
        switch (snippetSuggestions) {
            case 'top':
                snippetSortOrder = 0 /* SnippetSortOrder.Top */;
                break;
            // 	↓ that's the default anyways...
            // case 'inline':
            // 	snippetSortOrder = SnippetSortOrder.Inline;
            // 	break;
            case 'bottom':
                snippetSortOrder = 2 /* SnippetSortOrder.Bottom */;
                break;
        }
        const { itemKind: itemKindFilter, showDeprecated } = SuggestModel._createSuggestFilter(this._editor);
        const completionOptions = new CompletionOptions(snippetSortOrder, !noFilter ? itemKindFilter : new Set(), onlyFrom, showDeprecated);
        const wordDistance = WordDistance.create(this._editorWorkerService, this._editor);
        const completions = provideSuggestionItems(this._languageFeaturesService.completionProvider, model, this._editor.getPosition(), completionOptions, suggestCtx, this._requestToken.token);
        Promise.all([completions, wordDistance]).then(([completions, wordDistance]) => suggestModel_awaiter(this, void 0, void 0, function* () {
            var _b;
            (_b = this._requestToken) === null || _b === void 0 ? void 0 : _b.dispose();
            if (!this._editor.hasModel()) {
                return;
            }
            let clipboardText = existing === null || existing === void 0 ? void 0 : existing.clipboardText;
            if (!clipboardText && completions.needsClipboard) {
                clipboardText = yield this._clipboardService.readText();
            }
            if (this._state === 0 /* State.Idle */) {
                return;
            }
            const model = this._editor.getModel();
            let items = completions.items;
            if (existing) {
                const cmpFn = getSuggestionComparator(snippetSortOrder);
                items = items.concat(existing.items).sort(cmpFn);
            }
            const ctx = new suggestModel_LineContext(model, this._editor.getPosition(), auto, context.shy, context.noSelect);
            this._completionModel = new CompletionModel(items, this._context.column, {
                leadingLineContent: ctx.leadingLineContent,
                characterCountDelta: ctx.column - this._context.column
            }, wordDistance, this._editor.getOption(108 /* EditorOption.suggest */), this._editor.getOption(103 /* EditorOption.snippetSuggestions */), undefined, clipboardText);
            // store containers so that they can be disposed later
            this._completionDisposables.add(completions.disposable);
            this._onNewContext(ctx);
            // finally report telemetry about durations
            this._reportDurationsTelemetry(completions.durations);
        })).catch(onUnexpectedError);
    }
    _reportDurationsTelemetry(durations) {
        if (this._telemetryGate++ % 230 !== 0) {
            return;
        }
        setTimeout(() => {
            this._telemetryService.publicLog2('suggest.durations.json', { data: JSON.stringify(durations) });
            this._logService.debug('suggest.durations.json', durations);
        });
    }
    static _createSuggestFilter(editor) {
        // kind filter and snippet sort rules
        const result = new Set();
        // snippet setting
        const snippetSuggestions = editor.getOption(103 /* EditorOption.snippetSuggestions */);
        if (snippetSuggestions === 'none') {
            result.add(27 /* CompletionItemKind.Snippet */);
        }
        // type setting
        const suggestOptions = editor.getOption(108 /* 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 };
    }
    _onNewContext(ctx) {
        if (!this._context) {
            // happens when 24x7 IntelliSense is enabled and still in its delay
            return;
        }
        if (ctx.lineNumber !== this._context.lineNumber) {
            // e.g. happens when pressing Enter while IntelliSense is computed
            this.cancel();
            return;
        }
        if (getLeadingWhitespace(ctx.leadingLineContent) !== getLeadingWhitespace(this._context.leadingLineContent)) {
            // cancel IntelliSense when line start changes
            // happens when the current word gets outdented
            this.cancel();
            return;
        }
        if (ctx.column < this._context.column) {
            // typed -> moved cursor LEFT -> retrigger if still on a word
            if (ctx.leadingWord.word) {
                this.trigger({ auto: this._context.auto, shy: false, noSelect: false }, true);
            }
            else {
                this.cancel();
            }
            return;
        }
        if (!this._completionModel) {
            // happens when IntelliSense is not yet computed
            return;
        }
        if (ctx.leadingWord.word.length !== 0 && ctx.leadingWord.startColumn > this._context.leadingWord.startColumn) {
            // started a new word while IntelliSense shows -> retrigger
            // Select those providers have not contributed to this completion model and re-trigger completions for
            // them. Also adopt the existing items and merge them into the new completion model
            const inactiveProvider = new Set(this._languageFeaturesService.completionProvider.all(this._editor.getModel()));
            for (const provider of this._completionModel.allProvider) {
                inactiveProvider.delete(provider);
            }
            const items = this._completionModel.adopt(new Set());
            this.trigger({ auto: this._context.auto, shy: false, noSelect: false }, true, inactiveProvider, { items, clipboardText: this._completionModel.clipboardText });
            return;
        }
        if (ctx.column > this._context.column && this._completionModel.incomplete.size > 0 && ctx.leadingWord.word.length !== 0) {
            // typed -> moved cursor RIGHT & incomple model & still on a word -> retrigger
            const { incomplete } = this._completionModel;
            const items = this._completionModel.adopt(incomplete);
            this.trigger({ auto: this._state === 2 /* State.Auto */, shy: false, noSelect: false, triggerKind: 2 /* CompletionTriggerKind.TriggerForIncompleteCompletions */ }, true, incomplete, { items, clipboardText: this._completionModel.clipboardText });
        }
        else {
            // typed -> moved cursor RIGHT -> update UI
            const oldLineContext = this._completionModel.lineContext;
            let isFrozen = false;
            this._completionModel.lineContext = {
                leadingLineContent: ctx.leadingLineContent,
                characterCountDelta: ctx.column - this._context.column
            };
            if (this._completionModel.items.length === 0) {
                if (suggestModel_LineContext.shouldAutoTrigger(this._editor) && this._context.leadingWord.endColumn < ctx.leadingWord.startColumn) {
                    // retrigger when heading into a new word
                    this.trigger({ auto: this._context.auto, shy: false, noSelect: false }, true);
                    return;
                }
                if (!this._context.auto) {
                    // freeze when IntelliSense was manually requested
                    this._completionModel.lineContext = oldLineContext;
                    isFrozen = this._completionModel.items.length > 0;
                    if (isFrozen && ctx.leadingWord.word.length === 0) {
                        // there were results before but now there aren't
                        // and also we are not on a word anymore -> cancel
                        this.cancel();
                        return;
                    }
                }
                else {
                    // nothing left
                    this.cancel();
                    return;
                }
            }
            this._onDidSuggest.fire({
                completionModel: this._completionModel,
                auto: this._context.auto,
                shy: this._context.shy,
                noSelect: this._context.noSelect,
                isFrozen,
            });
        }
    }
};
SuggestModel = suggestModel_decorate([
    suggestModel_param(1, IEditorWorkerService),
    suggestModel_param(2, IClipboardService),
    suggestModel_param(3, ITelemetryService),
    suggestModel_param(4, ILogService),
    suggestModel_param(5, IContextKeyService),
    suggestModel_param(6, IConfigurationService),
    suggestModel_param(7, ILanguageFeaturesService)
], SuggestModel);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggestOvertypingCapturer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class OvertypingCapturer {
    constructor(editor, suggestModel) {
        this._disposables = new DisposableStore();
        this._lastOvertyped = [];
        this._empty = true;
        this._disposables.add(editor.onWillType(() => {
            if (!this._empty) {
                return;
            }
            if (!editor.hasModel()) {
                return;
            }
            const selections = editor.getSelections();
            const selectionsLength = selections.length;
            // Check if it will overtype any selections
            let willOvertype = false;
            for (let i = 0; i < selectionsLength; i++) {
                if (!selections[i].isEmpty()) {
                    willOvertype = true;
                    break;
                }
            }
            if (!willOvertype) {
                return;
            }
            this._lastOvertyped = [];
            const model = editor.getModel();
            for (let i = 0; i < selectionsLength; i++) {
                const selection = selections[i];
                // Check for overtyping capturer restrictions
                if (model.getValueLengthInRange(selection) > OvertypingCapturer._maxSelectionLength) {
                    return;
                }
                this._lastOvertyped[i] = { value: model.getValueInRange(selection), multiline: selection.startLineNumber !== selection.endLineNumber };
            }
            this._empty = false;
        }));
        this._disposables.add(suggestModel.onDidCancel(e => {
            if (!this._empty && !e.retrigger) {
                this._empty = true;
            }
        }));
    }
    getLastOvertypedInfo(idx) {
        if (!this._empty && idx >= 0 && idx < this._lastOvertyped.length) {
            return this._lastOvertyped[idx];
        }
        return undefined;
    }
    dispose() {
        this._disposables.dispose();
    }
}
OvertypingCapturer._maxSelectionLength = 51200;

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/codicons/codicon/codicon.css
var codicon = __webpack_require__(10800);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/codicons/codicon/codicon.css

      
      
      
      
      
      
      
      
      

var codicon_options = {};

codicon_options.styleTagTransform = (styleTagTransform_default());
codicon_options.setAttributes = (setAttributesWithoutAttributes_default());

      codicon_options.insert = insertBySelector_default().bind(null, "head");
    
codicon_options.domAPI = (styleDomAPI_default());
codicon_options.insertStyleElement = (insertStyleElement_default());

var codicon_update = injectStylesIntoStyleTag_default()(codicon/* default */.A, codicon_options);




       /* harmony default export */ const codicon_codicon = (codicon/* default */.A && codicon/* default */.A.locals ? codicon/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/codicons/codicon/codicon-modifiers.css
var codicon_modifiers = __webpack_require__(59089);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/codicons/codicon/codicon-modifiers.css

      
      
      
      
      
      
      
      
      

var codicon_modifiers_options = {};

codicon_modifiers_options.styleTagTransform = (styleTagTransform_default());
codicon_modifiers_options.setAttributes = (setAttributesWithoutAttributes_default());

      codicon_modifiers_options.insert = insertBySelector_default().bind(null, "head");
    
codicon_modifiers_options.domAPI = (styleDomAPI_default());
codicon_modifiers_options.insertStyleElement = (insertStyleElement_default());

var codicon_modifiers_update = injectStylesIntoStyleTag_default()(codicon_modifiers/* default */.A, codicon_modifiers_options);




       /* harmony default export */ const codicon_codicon_modifiers = (codicon_modifiers/* default */.A && codicon_modifiers/* default */.A.locals ? codicon_modifiers/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/codicons/codiconStyles.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



function formatRule(c) {
    let def = c.definition;
    while (def instanceof Codicon) {
        def = def.definition;
    }
    return `.codicon-${c.id}:before { content: '${def.fontCharacter}'; }`;
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/media/suggest.css
var suggest = __webpack_require__(10835);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/media/suggest.css

      
      
      
      
      
      
      
      
      

var suggest_options = {};

suggest_options.styleTagTransform = (styleTagTransform_default());
suggest_options.setAttributes = (setAttributesWithoutAttributes_default());

      suggest_options.insert = insertBySelector_default().bind(null, "head");
    
suggest_options.domAPI = (styleDomAPI_default());
suggest_options.insertStyleElement = (insertStyleElement_default());

var suggest_update = injectStylesIntoStyleTag_default()(suggest/* default */.A, suggest_options);




       /* harmony default export */ const media_suggest = (suggest/* default */.A && suggest/* default */.A.locals ? suggest/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggestWidgetStatus.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var suggestWidgetStatus_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var suggestWidgetStatus_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};









class StatusBarViewItem extends MenuEntryActionViewItem {
    updateLabel() {
        const kb = this._keybindingService.lookupKeybinding(this._action.id, this._contextKeyService);
        if (!kb) {
            return super.updateLabel();
        }
        if (this.label) {
            this.label.textContent = localize('ddd', '{0} ({1})', this._action.label, StatusBarViewItem.symbolPrintEnter(kb));
        }
    }
    static symbolPrintEnter(kb) {
        var _a;
        return (_a = kb.getLabel()) === null || _a === void 0 ? void 0 : _a.replace(/\benter\b/gi, '\u23CE');
    }
}
let SuggestWidgetStatus = class SuggestWidgetStatus {
    constructor(container, instantiationService, _menuService, _contextKeyService) {
        this._menuService = _menuService;
        this._contextKeyService = _contextKeyService;
        this._menuDisposables = new DisposableStore();
        this.element = append(container, dom_$('.suggest-status-bar'));
        const actionViewItemProvider = (action => {
            return action instanceof MenuItemAction ? instantiationService.createInstance(StatusBarViewItem, action, undefined) : undefined;
        });
        this._leftActions = new ActionBar(this.element, { actionViewItemProvider });
        this._rightActions = new ActionBar(this.element, { actionViewItemProvider });
        this._leftActions.domNode.classList.add('left');
        this._rightActions.domNode.classList.add('right');
    }
    dispose() {
        this._menuDisposables.dispose();
        this.element.remove();
    }
    show() {
        const menu = this._menuService.createMenu(suggestWidgetStatusbarMenu, this._contextKeyService);
        const renderMenu = () => {
            const left = [];
            const right = [];
            for (const [group, actions] of menu.getActions()) {
                if (group === 'left') {
                    left.push(...actions);
                }
                else {
                    right.push(...actions);
                }
            }
            this._leftActions.clear();
            this._leftActions.push(left);
            this._rightActions.clear();
            this._rightActions.push(right);
        };
        this._menuDisposables.add(menu.onDidChange(() => renderMenu()));
        this._menuDisposables.add(menu);
    }
    hide() {
        this._menuDisposables.clear();
    }
};
SuggestWidgetStatus = suggestWidgetStatus_decorate([
    suggestWidgetStatus_param(1, IInstantiationService),
    suggestWidgetStatus_param(2, IMenuService),
    suggestWidgetStatus_param(3, IContextKeyService)
], SuggestWidgetStatus);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/symbolIcons/browser/symbolIcons.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




const SYMBOL_ICON_ARRAY_FOREGROUND = registerColor('symbolIcon.arrayForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground,
}, localize('symbolIcon.arrayForeground', 'The foreground color for array symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_BOOLEAN_FOREGROUND = registerColor('symbolIcon.booleanForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground,
}, localize('symbolIcon.booleanForeground', 'The foreground color for boolean symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_CLASS_FOREGROUND = registerColor('symbolIcon.classForeground', {
    dark: '#EE9D28',
    light: '#D67E00',
    hcDark: '#EE9D28',
    hcLight: '#D67E00'
}, localize('symbolIcon.classForeground', 'The foreground color for class symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_COLOR_FOREGROUND = registerColor('symbolIcon.colorForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.colorForeground', 'The foreground color for color symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_CONSTANT_FOREGROUND = registerColor('symbolIcon.constantForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.constantForeground', 'The foreground color for constant symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_CONSTRUCTOR_FOREGROUND = registerColor('symbolIcon.constructorForeground', {
    dark: '#B180D7',
    light: '#652D90',
    hcDark: '#B180D7',
    hcLight: '#652D90'
}, localize('symbolIcon.constructorForeground', 'The foreground color for constructor symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_ENUMERATOR_FOREGROUND = registerColor('symbolIcon.enumeratorForeground', {
    dark: '#EE9D28',
    light: '#D67E00',
    hcDark: '#EE9D28',
    hcLight: '#D67E00'
}, localize('symbolIcon.enumeratorForeground', 'The foreground color for enumerator symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_ENUMERATOR_MEMBER_FOREGROUND = registerColor('symbolIcon.enumeratorMemberForeground', {
    dark: '#75BEFF',
    light: '#007ACC',
    hcDark: '#75BEFF',
    hcLight: '#007ACC'
}, localize('symbolIcon.enumeratorMemberForeground', 'The foreground color for enumerator member symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_EVENT_FOREGROUND = registerColor('symbolIcon.eventForeground', {
    dark: '#EE9D28',
    light: '#D67E00',
    hcDark: '#EE9D28',
    hcLight: '#D67E00'
}, localize('symbolIcon.eventForeground', 'The foreground color for event symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_FIELD_FOREGROUND = registerColor('symbolIcon.fieldForeground', {
    dark: '#75BEFF',
    light: '#007ACC',
    hcDark: '#75BEFF',
    hcLight: '#007ACC'
}, localize('symbolIcon.fieldForeground', 'The foreground color for field symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_FILE_FOREGROUND = registerColor('symbolIcon.fileForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.fileForeground', 'The foreground color for file symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_FOLDER_FOREGROUND = registerColor('symbolIcon.folderForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.folderForeground', 'The foreground color for folder symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_FUNCTION_FOREGROUND = registerColor('symbolIcon.functionForeground', {
    dark: '#B180D7',
    light: '#652D90',
    hcDark: '#B180D7',
    hcLight: '#652D90'
}, localize('symbolIcon.functionForeground', 'The foreground color for function symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_INTERFACE_FOREGROUND = registerColor('symbolIcon.interfaceForeground', {
    dark: '#75BEFF',
    light: '#007ACC',
    hcDark: '#75BEFF',
    hcLight: '#007ACC'
}, localize('symbolIcon.interfaceForeground', 'The foreground color for interface symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_KEY_FOREGROUND = registerColor('symbolIcon.keyForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.keyForeground', 'The foreground color for key symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_KEYWORD_FOREGROUND = registerColor('symbolIcon.keywordForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.keywordForeground', 'The foreground color for keyword symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_METHOD_FOREGROUND = registerColor('symbolIcon.methodForeground', {
    dark: '#B180D7',
    light: '#652D90',
    hcDark: '#B180D7',
    hcLight: '#652D90'
}, localize('symbolIcon.methodForeground', 'The foreground color for method symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_MODULE_FOREGROUND = registerColor('symbolIcon.moduleForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.moduleForeground', 'The foreground color for module symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_NAMESPACE_FOREGROUND = registerColor('symbolIcon.namespaceForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.namespaceForeground', 'The foreground color for namespace symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_NULL_FOREGROUND = registerColor('symbolIcon.nullForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.nullForeground', 'The foreground color for null symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_NUMBER_FOREGROUND = registerColor('symbolIcon.numberForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.numberForeground', 'The foreground color for number symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_OBJECT_FOREGROUND = registerColor('symbolIcon.objectForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.objectForeground', 'The foreground color for object symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_OPERATOR_FOREGROUND = registerColor('symbolIcon.operatorForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.operatorForeground', 'The foreground color for operator symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_PACKAGE_FOREGROUND = registerColor('symbolIcon.packageForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.packageForeground', 'The foreground color for package symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_PROPERTY_FOREGROUND = registerColor('symbolIcon.propertyForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.propertyForeground', 'The foreground color for property symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_REFERENCE_FOREGROUND = registerColor('symbolIcon.referenceForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.referenceForeground', 'The foreground color for reference symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_SNIPPET_FOREGROUND = registerColor('symbolIcon.snippetForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.snippetForeground', 'The foreground color for snippet symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_STRING_FOREGROUND = registerColor('symbolIcon.stringForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.stringForeground', 'The foreground color for string symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_STRUCT_FOREGROUND = registerColor('symbolIcon.structForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground,
}, localize('symbolIcon.structForeground', 'The foreground color for struct symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_TEXT_FOREGROUND = registerColor('symbolIcon.textForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.textForeground', 'The foreground color for text symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_TYPEPARAMETER_FOREGROUND = registerColor('symbolIcon.typeParameterForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.typeParameterForeground', 'The foreground color for type parameter symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_UNIT_FOREGROUND = registerColor('symbolIcon.unitForeground', {
    dark: foreground,
    light: foreground,
    hcDark: foreground,
    hcLight: foreground
}, localize('symbolIcon.unitForeground', 'The foreground color for unit symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
const SYMBOL_ICON_VARIABLE_FOREGROUND = registerColor('symbolIcon.variableForeground', {
    dark: '#75BEFF',
    light: '#007ACC',
    hcDark: '#75BEFF',
    hcLight: '#007ACC',
}, localize('symbolIcon.variableForeground', 'The foreground color for variable symbols. These symbols appear in the outline, breadcrumb, and suggest widget.'));
registerThemingParticipant((theme, collector) => {
    const symbolIconArrayColor = theme.getColor(SYMBOL_ICON_ARRAY_FOREGROUND);
    if (symbolIconArrayColor) {
        collector.addRule(`${Codicon.symbolArray.cssSelector} { color: ${symbolIconArrayColor}; }`);
    }
    const symbolIconBooleanColor = theme.getColor(SYMBOL_ICON_BOOLEAN_FOREGROUND);
    if (symbolIconBooleanColor) {
        collector.addRule(`${Codicon.symbolBoolean.cssSelector} { color: ${symbolIconBooleanColor}; }`);
    }
    const symbolIconClassColor = theme.getColor(SYMBOL_ICON_CLASS_FOREGROUND);
    if (symbolIconClassColor) {
        collector.addRule(`${Codicon.symbolClass.cssSelector} { color: ${symbolIconClassColor}; }`);
    }
    const symbolIconMethodColor = theme.getColor(SYMBOL_ICON_METHOD_FOREGROUND);
    if (symbolIconMethodColor) {
        collector.addRule(`${Codicon.symbolMethod.cssSelector} { color: ${symbolIconMethodColor}; }`);
    }
    const symbolIconColorColor = theme.getColor(SYMBOL_ICON_COLOR_FOREGROUND);
    if (symbolIconColorColor) {
        collector.addRule(`${Codicon.symbolColor.cssSelector} { color: ${symbolIconColorColor}; }`);
    }
    const symbolIconConstantColor = theme.getColor(SYMBOL_ICON_CONSTANT_FOREGROUND);
    if (symbolIconConstantColor) {
        collector.addRule(`${Codicon.symbolConstant.cssSelector} { color: ${symbolIconConstantColor}; }`);
    }
    const symbolIconConstructorColor = theme.getColor(SYMBOL_ICON_CONSTRUCTOR_FOREGROUND);
    if (symbolIconConstructorColor) {
        collector.addRule(`${Codicon.symbolConstructor.cssSelector} { color: ${symbolIconConstructorColor}; }`);
    }
    const symbolIconEnumeratorColor = theme.getColor(SYMBOL_ICON_ENUMERATOR_FOREGROUND);
    if (symbolIconEnumeratorColor) {
        collector.addRule(`
			${Codicon.symbolValue.cssSelector},${Codicon.symbolEnum.cssSelector} { color: ${symbolIconEnumeratorColor}; }`);
    }
    const symbolIconEnumeratorMemberColor = theme.getColor(SYMBOL_ICON_ENUMERATOR_MEMBER_FOREGROUND);
    if (symbolIconEnumeratorMemberColor) {
        collector.addRule(`${Codicon.symbolEnumMember.cssSelector} { color: ${symbolIconEnumeratorMemberColor}; }`);
    }
    const symbolIconEventColor = theme.getColor(SYMBOL_ICON_EVENT_FOREGROUND);
    if (symbolIconEventColor) {
        collector.addRule(`${Codicon.symbolEvent.cssSelector} { color: ${symbolIconEventColor}; }`);
    }
    const symbolIconFieldColor = theme.getColor(SYMBOL_ICON_FIELD_FOREGROUND);
    if (symbolIconFieldColor) {
        collector.addRule(`${Codicon.symbolField.cssSelector} { color: ${symbolIconFieldColor}; }`);
    }
    const symbolIconFileColor = theme.getColor(SYMBOL_ICON_FILE_FOREGROUND);
    if (symbolIconFileColor) {
        collector.addRule(`${Codicon.symbolFile.cssSelector} { color: ${symbolIconFileColor}; }`);
    }
    const symbolIconFolderColor = theme.getColor(SYMBOL_ICON_FOLDER_FOREGROUND);
    if (symbolIconFolderColor) {
        collector.addRule(`${Codicon.symbolFolder.cssSelector} { color: ${symbolIconFolderColor}; }`);
    }
    const symbolIconFunctionColor = theme.getColor(SYMBOL_ICON_FUNCTION_FOREGROUND);
    if (symbolIconFunctionColor) {
        collector.addRule(`${Codicon.symbolFunction.cssSelector} { color: ${symbolIconFunctionColor}; }`);
    }
    const symbolIconInterfaceColor = theme.getColor(SYMBOL_ICON_INTERFACE_FOREGROUND);
    if (symbolIconInterfaceColor) {
        collector.addRule(`${Codicon.symbolInterface.cssSelector} { color: ${symbolIconInterfaceColor}; }`);
    }
    const symbolIconKeyColor = theme.getColor(SYMBOL_ICON_KEY_FOREGROUND);
    if (symbolIconKeyColor) {
        collector.addRule(`${Codicon.symbolKey.cssSelector} { color: ${symbolIconKeyColor}; }`);
    }
    const symbolIconKeywordColor = theme.getColor(SYMBOL_ICON_KEYWORD_FOREGROUND);
    if (symbolIconKeywordColor) {
        collector.addRule(`${Codicon.symbolKeyword.cssSelector} { color: ${symbolIconKeywordColor}; }`);
    }
    const symbolIconModuleColor = theme.getColor(SYMBOL_ICON_MODULE_FOREGROUND);
    if (symbolIconModuleColor) {
        collector.addRule(`${Codicon.symbolModule.cssSelector} { color: ${symbolIconModuleColor}; }`);
    }
    const outlineNamespaceColor = theme.getColor(SYMBOL_ICON_NAMESPACE_FOREGROUND);
    if (outlineNamespaceColor) {
        collector.addRule(`${Codicon.symbolNamespace.cssSelector} { color: ${outlineNamespaceColor}; }`);
    }
    const symbolIconNullColor = theme.getColor(SYMBOL_ICON_NULL_FOREGROUND);
    if (symbolIconNullColor) {
        collector.addRule(`${Codicon.symbolNull.cssSelector} { color: ${symbolIconNullColor}; }`);
    }
    const symbolIconNumberColor = theme.getColor(SYMBOL_ICON_NUMBER_FOREGROUND);
    if (symbolIconNumberColor) {
        collector.addRule(`${Codicon.symbolNumber.cssSelector} { color: ${symbolIconNumberColor}; }`);
    }
    const symbolIconObjectColor = theme.getColor(SYMBOL_ICON_OBJECT_FOREGROUND);
    if (symbolIconObjectColor) {
        collector.addRule(`${Codicon.symbolObject.cssSelector} { color: ${symbolIconObjectColor}; }`);
    }
    const symbolIconOperatorColor = theme.getColor(SYMBOL_ICON_OPERATOR_FOREGROUND);
    if (symbolIconOperatorColor) {
        collector.addRule(`${Codicon.symbolOperator.cssSelector} { color: ${symbolIconOperatorColor}; }`);
    }
    const symbolIconPackageColor = theme.getColor(SYMBOL_ICON_PACKAGE_FOREGROUND);
    if (symbolIconPackageColor) {
        collector.addRule(`${Codicon.symbolPackage.cssSelector} { color: ${symbolIconPackageColor}; }`);
    }
    const symbolIconPropertyColor = theme.getColor(SYMBOL_ICON_PROPERTY_FOREGROUND);
    if (symbolIconPropertyColor) {
        collector.addRule(`${Codicon.symbolProperty.cssSelector} { color: ${symbolIconPropertyColor}; }`);
    }
    const symbolIconReferenceColor = theme.getColor(SYMBOL_ICON_REFERENCE_FOREGROUND);
    if (symbolIconReferenceColor) {
        collector.addRule(`${Codicon.symbolReference.cssSelector} { color: ${symbolIconReferenceColor}; }`);
    }
    const symbolIconSnippetColor = theme.getColor(SYMBOL_ICON_SNIPPET_FOREGROUND);
    if (symbolIconSnippetColor) {
        collector.addRule(`${Codicon.symbolSnippet.cssSelector} { color: ${symbolIconSnippetColor}; }`);
    }
    const symbolIconStringColor = theme.getColor(SYMBOL_ICON_STRING_FOREGROUND);
    if (symbolIconStringColor) {
        collector.addRule(`${Codicon.symbolString.cssSelector} { color: ${symbolIconStringColor}; }`);
    }
    const symbolIconStructColor = theme.getColor(SYMBOL_ICON_STRUCT_FOREGROUND);
    if (symbolIconStructColor) {
        collector.addRule(`${Codicon.symbolStruct.cssSelector} { color: ${symbolIconStructColor}; }`);
    }
    const symbolIconTextColor = theme.getColor(SYMBOL_ICON_TEXT_FOREGROUND);
    if (symbolIconTextColor) {
        collector.addRule(`${Codicon.symbolText.cssSelector} { color: ${symbolIconTextColor}; }`);
    }
    const symbolIconTypeParameterColor = theme.getColor(SYMBOL_ICON_TYPEPARAMETER_FOREGROUND);
    if (symbolIconTypeParameterColor) {
        collector.addRule(`${Codicon.symbolTypeParameter.cssSelector} { color: ${symbolIconTypeParameterColor}; }`);
    }
    const symbolIconUnitColor = theme.getColor(SYMBOL_ICON_UNIT_FOREGROUND);
    if (symbolIconUnitColor) {
        collector.addRule(`${Codicon.symbolUnit.cssSelector} { color: ${symbolIconUnitColor}; }`);
    }
    const symbolIconVariableColor = theme.getColor(SYMBOL_ICON_VARIABLE_FOREGROUND);
    if (symbolIconVariableColor) {
        collector.addRule(`${Codicon.symbolVariable.cssSelector} { color: ${symbolIconVariableColor}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/resizable/resizable.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class ResizableHTMLElement {
    constructor() {
        this._onDidWillResize = new Emitter();
        this.onDidWillResize = this._onDidWillResize.event;
        this._onDidResize = new Emitter();
        this.onDidResize = this._onDidResize.event;
        this._sashListener = new DisposableStore();
        this._size = new Dimension(0, 0);
        this._minSize = new Dimension(0, 0);
        this._maxSize = new Dimension(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
        this.domNode = document.createElement('div');
        this._eastSash = new Sash(this.domNode, { getVerticalSashLeft: () => this._size.width }, { orientation: 0 /* Orientation.VERTICAL */ });
        this._westSash = new Sash(this.domNode, { getVerticalSashLeft: () => 0 }, { orientation: 0 /* Orientation.VERTICAL */ });
        this._northSash = new Sash(this.domNode, { getHorizontalSashTop: () => 0 }, { orientation: 1 /* Orientation.HORIZONTAL */, orthogonalEdge: OrthogonalEdge.North });
        this._southSash = new Sash(this.domNode, { getHorizontalSashTop: () => this._size.height }, { orientation: 1 /* Orientation.HORIZONTAL */, orthogonalEdge: OrthogonalEdge.South });
        this._northSash.orthogonalStartSash = this._westSash;
        this._northSash.orthogonalEndSash = this._eastSash;
        this._southSash.orthogonalStartSash = this._westSash;
        this._southSash.orthogonalEndSash = this._eastSash;
        let currentSize;
        let deltaY = 0;
        let deltaX = 0;
        this._sashListener.add(Event.any(this._northSash.onDidStart, this._eastSash.onDidStart, this._southSash.onDidStart, this._westSash.onDidStart)(() => {
            if (currentSize === undefined) {
                this._onDidWillResize.fire();
                currentSize = this._size;
                deltaY = 0;
                deltaX = 0;
            }
        }));
        this._sashListener.add(Event.any(this._northSash.onDidEnd, this._eastSash.onDidEnd, this._southSash.onDidEnd, this._westSash.onDidEnd)(() => {
            if (currentSize !== undefined) {
                currentSize = undefined;
                deltaY = 0;
                deltaX = 0;
                this._onDidResize.fire({ dimension: this._size, done: true });
            }
        }));
        this._sashListener.add(this._eastSash.onDidChange(e => {
            if (currentSize) {
                deltaX = e.currentX - e.startX;
                this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
                this._onDidResize.fire({ dimension: this._size, done: false, east: true });
            }
        }));
        this._sashListener.add(this._westSash.onDidChange(e => {
            if (currentSize) {
                deltaX = -(e.currentX - e.startX);
                this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
                this._onDidResize.fire({ dimension: this._size, done: false, west: true });
            }
        }));
        this._sashListener.add(this._northSash.onDidChange(e => {
            if (currentSize) {
                deltaY = -(e.currentY - e.startY);
                this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
                this._onDidResize.fire({ dimension: this._size, done: false, north: true });
            }
        }));
        this._sashListener.add(this._southSash.onDidChange(e => {
            if (currentSize) {
                deltaY = e.currentY - e.startY;
                this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
                this._onDidResize.fire({ dimension: this._size, done: false, south: true });
            }
        }));
        this._sashListener.add(Event.any(this._eastSash.onDidReset, this._westSash.onDidReset)(e => {
            if (this._preferredSize) {
                this.layout(this._size.height, this._preferredSize.width);
                this._onDidResize.fire({ dimension: this._size, done: true });
            }
        }));
        this._sashListener.add(Event.any(this._northSash.onDidReset, this._southSash.onDidReset)(e => {
            if (this._preferredSize) {
                this.layout(this._preferredSize.height, this._size.width);
                this._onDidResize.fire({ dimension: this._size, done: true });
            }
        }));
    }
    dispose() {
        this._northSash.dispose();
        this._southSash.dispose();
        this._eastSash.dispose();
        this._westSash.dispose();
        this._sashListener.dispose();
        this._onDidResize.dispose();
        this._onDidWillResize.dispose();
        this.domNode.remove();
    }
    enableSashes(north, east, south, west) {
        this._northSash.state = north ? 3 /* SashState.Enabled */ : 0 /* SashState.Disabled */;
        this._eastSash.state = east ? 3 /* SashState.Enabled */ : 0 /* SashState.Disabled */;
        this._southSash.state = south ? 3 /* SashState.Enabled */ : 0 /* SashState.Disabled */;
        this._westSash.state = west ? 3 /* SashState.Enabled */ : 0 /* SashState.Disabled */;
    }
    layout(height = this.size.height, width = this.size.width) {
        const { height: minHeight, width: minWidth } = this._minSize;
        const { height: maxHeight, width: maxWidth } = this._maxSize;
        height = Math.max(minHeight, Math.min(maxHeight, height));
        width = Math.max(minWidth, Math.min(maxWidth, width));
        const newSize = new Dimension(width, height);
        if (!Dimension.equals(newSize, this._size)) {
            this.domNode.style.height = height + 'px';
            this.domNode.style.width = width + 'px';
            this._size = newSize;
            this._northSash.layout();
            this._eastSash.layout();
            this._southSash.layout();
            this._westSash.layout();
        }
    }
    clearSashHoverState() {
        this._eastSash.clearSashHoverState();
        this._westSash.clearSashHoverState();
        this._northSash.clearSashHoverState();
        this._southSash.clearSashHoverState();
    }
    get size() {
        return this._size;
    }
    set maxSize(value) {
        this._maxSize = value;
    }
    get maxSize() {
        return this._maxSize;
    }
    set minSize(value) {
        this._minSize = value;
    }
    get minSize() {
        return this._minSize;
    }
    set preferredSize(value) {
        this._preferredSize = value;
    }
    get preferredSize() {
        return this._preferredSize;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggestWidgetDetails.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var suggestWidgetDetails_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var suggestWidgetDetails_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};










function canExpandCompletionItem(item) {
    return !!item && Boolean(item.completion.documentation || item.completion.detail && item.completion.detail !== item.completion.label);
}
let SuggestDetailsWidget = class SuggestDetailsWidget {
    constructor(_editor, instaService) {
        this._editor = _editor;
        this._onDidClose = new Emitter();
        this.onDidClose = this._onDidClose.event;
        this._onDidChangeContents = new Emitter();
        this.onDidChangeContents = this._onDidChangeContents.event;
        this._disposables = new DisposableStore();
        this._renderDisposeable = new DisposableStore();
        this._borderWidth = 1;
        this._size = new Dimension(330, 0);
        this.domNode = dom_$('.suggest-details');
        this.domNode.classList.add('no-docs');
        this._markdownRenderer = instaService.createInstance(MarkdownRenderer, { editor: _editor });
        this._body = dom_$('.body');
        this._scrollbar = new DomScrollableElement(this._body, {
            alwaysConsumeMouseWheel: true,
        });
        append(this.domNode, this._scrollbar.getDomNode());
        this._disposables.add(this._scrollbar);
        this._header = append(this._body, dom_$('.header'));
        this._close = append(this._header, dom_$('span' + Codicon.close.cssSelector));
        this._close.title = localize('details.close', "Close");
        this._type = append(this._header, dom_$('p.type'));
        this._docs = append(this._body, dom_$('p.docs'));
        this._configureFont();
        this._disposables.add(this._editor.onDidChangeConfiguration(e => {
            if (e.hasChanged(46 /* EditorOption.fontInfo */)) {
                this._configureFont();
            }
        }));
    }
    dispose() {
        this._disposables.dispose();
        this._renderDisposeable.dispose();
    }
    _configureFont() {
        const options = this._editor.getOptions();
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        const fontFamily = fontInfo.getMassagedFontFamily();
        const fontSize = options.get(109 /* EditorOption.suggestFontSize */) || fontInfo.fontSize;
        const lineHeight = options.get(110 /* 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._type.style.fontFamily = fontFamily;
        this._close.style.height = lineHeightPx;
        this._close.style.width = lineHeightPx;
    }
    getLayoutInfo() {
        const lineHeight = this._editor.getOption(110 /* EditorOption.suggestLineHeight */) || this._editor.getOption(46 /* EditorOption.fontInfo */).lineHeight;
        const borderWidth = this._borderWidth;
        const borderHeight = borderWidth * 2;
        return {
            lineHeight,
            borderWidth,
            borderHeight,
            verticalPadding: 22,
            horizontalPadding: 14
        };
    }
    renderLoading() {
        this._type.textContent = localize('loading', "Loading...");
        this._docs.textContent = '';
        this.domNode.classList.remove('no-docs', 'no-type');
        this.layout(this.size.width, this.getLayoutInfo().lineHeight * 2);
        this._onDidChangeContents.fire(this);
    }
    renderItem(item, explainMode) {
        var _a, _b;
        this._renderDisposeable.clear();
        let { detail, documentation } = item.completion;
        if (explainMode) {
            let md = '';
            md += `score: ${item.score[0]}\n`;
            md += `prefix: ${(_a = item.word) !== null && _a !== void 0 ? _a : '(no prefix)'}\n`;
            md += `word: ${item.completion.filterText ? item.completion.filterText + ' (filterText)' : item.textLabel}\n`;
            md += `distance: ${item.distance} (localityBonus-setting)\n`;
            md += `index: ${item.idx}, based on ${item.completion.sortText && `sortText: "${item.completion.sortText}"` || 'label'}\n`;
            md += `commit_chars: ${(_b = item.completion.commitCharacters) === null || _b === void 0 ? void 0 : _b.join('')}\n`;
            documentation = new MarkdownString().appendCodeblock('empty', md);
            detail = `Provider: ${item.provider._debugDisplayName}`;
        }
        if (!explainMode && !canExpandCompletionItem(item)) {
            this.clearContents();
            return;
        }
        this.domNode.classList.remove('no-docs', 'no-type');
        // --- details
        if (detail) {
            const cappedDetail = detail.length > 100000 ? `${detail.substr(0, 100000)}…` : detail;
            this._type.textContent = cappedDetail;
            this._type.title = cappedDetail;
            show(this._type);
            this._type.classList.toggle('auto-wrap', !/\r?\n^\s+/gmi.test(cappedDetail));
        }
        else {
            clearNode(this._type);
            this._type.title = '';
            hide(this._type);
            this.domNode.classList.add('no-type');
        }
        // --- documentation
        clearNode(this._docs);
        if (typeof documentation === 'string') {
            this._docs.classList.remove('markdown-docs');
            this._docs.textContent = documentation;
        }
        else if (documentation) {
            this._docs.classList.add('markdown-docs');
            clearNode(this._docs);
            const renderedContents = this._markdownRenderer.render(documentation);
            this._docs.appendChild(renderedContents.element);
            this._renderDisposeable.add(renderedContents);
            this._renderDisposeable.add(this._markdownRenderer.onDidRenderAsync(() => {
                this.layout(this._size.width, this._type.clientHeight + this._docs.clientHeight);
                this._onDidChangeContents.fire(this);
            }));
        }
        this.domNode.style.userSelect = 'text';
        this.domNode.tabIndex = -1;
        this._close.onmousedown = e => {
            e.preventDefault();
            e.stopPropagation();
        };
        this._close.onclick = e => {
            e.preventDefault();
            e.stopPropagation();
            this._onDidClose.fire();
        };
        this._body.scrollTop = 0;
        this.layout(this._size.width, this._type.clientHeight + this._docs.clientHeight);
        this._onDidChangeContents.fire(this);
    }
    clearContents() {
        this.domNode.classList.add('no-docs');
        this._type.textContent = '';
        this._docs.textContent = '';
    }
    get size() {
        return this._size;
    }
    layout(width, height) {
        const newSize = new Dimension(width, height);
        if (!Dimension.equals(newSize, this._size)) {
            this._size = newSize;
            size(this.domNode, width, height);
        }
        this._scrollbar.scanDomNode();
    }
    scrollDown(much = 8) {
        this._body.scrollTop += much;
    }
    scrollUp(much = 8) {
        this._body.scrollTop -= much;
    }
    scrollTop() {
        this._body.scrollTop = 0;
    }
    scrollBottom() {
        this._body.scrollTop = this._body.scrollHeight;
    }
    pageDown() {
        this.scrollDown(80);
    }
    pageUp() {
        this.scrollUp(80);
    }
    set borderWidth(width) {
        this._borderWidth = width;
    }
    get borderWidth() {
        return this._borderWidth;
    }
};
SuggestDetailsWidget = suggestWidgetDetails_decorate([
    suggestWidgetDetails_param(1, IInstantiationService)
], SuggestDetailsWidget);

class SuggestDetailsOverlay {
    constructor(widget, _editor) {
        this.widget = widget;
        this._editor = _editor;
        this._disposables = new DisposableStore();
        this._added = false;
        this._preferAlignAtTop = true;
        this._resizable = new ResizableHTMLElement();
        this._resizable.domNode.classList.add('suggest-details-container');
        this._resizable.domNode.appendChild(widget.domNode);
        this._resizable.enableSashes(false, true, true, false);
        let topLeftNow;
        let sizeNow;
        let deltaTop = 0;
        let deltaLeft = 0;
        this._disposables.add(this._resizable.onDidWillResize(() => {
            topLeftNow = this._topLeft;
            sizeNow = this._resizable.size;
        }));
        this._disposables.add(this._resizable.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._applyTopLeft({
                        top: topLeftNow.top + deltaTop,
                        left: topLeftNow.left + deltaLeft,
                    });
                }
            }
            if (e.done) {
                topLeftNow = undefined;
                sizeNow = undefined;
                deltaTop = 0;
                deltaLeft = 0;
                this._userSize = e.dimension;
            }
        }));
        this._disposables.add(this.widget.onDidChangeContents(() => {
            var _a;
            if (this._anchorBox) {
                this._placeAtAnchor(this._anchorBox, (_a = this._userSize) !== null && _a !== void 0 ? _a : this.widget.size, this._preferAlignAtTop);
            }
        }));
    }
    dispose() {
        this._resizable.dispose();
        this._disposables.dispose();
        this.hide();
    }
    getId() {
        return 'suggest.details';
    }
    getDomNode() {
        return this._resizable.domNode;
    }
    getPosition() {
        return null;
    }
    show() {
        if (!this._added) {
            this._editor.addOverlayWidget(this);
            this.getDomNode().style.position = 'fixed';
            this._added = true;
        }
    }
    hide(sessionEnded = false) {
        this._resizable.clearSashHoverState();
        if (this._added) {
            this._editor.removeOverlayWidget(this);
            this._added = false;
            this._anchorBox = undefined;
            this._topLeft = undefined;
        }
        if (sessionEnded) {
            this._userSize = undefined;
            this.widget.clearContents();
        }
    }
    placeAtAnchor(anchor, preferAlignAtTop) {
        var _a;
        const anchorBox = anchor.getBoundingClientRect();
        this._anchorBox = anchorBox;
        this._preferAlignAtTop = preferAlignAtTop;
        this._placeAtAnchor(this._anchorBox, (_a = this._userSize) !== null && _a !== void 0 ? _a : this.widget.size, preferAlignAtTop);
    }
    _placeAtAnchor(anchorBox, size, preferAlignAtTop) {
        var _a;
        const bodyBox = getClientArea(document.body);
        const info = this.widget.getLayoutInfo();
        const defaultMinSize = new Dimension(220, 2 * info.lineHeight);
        const defaultTop = anchorBox.top;
        // EAST
        const eastPlacement = (function () {
            const width = bodyBox.width - (anchorBox.left + anchorBox.width + info.borderWidth + info.horizontalPadding);
            const left = -info.borderWidth + anchorBox.left + anchorBox.width;
            const maxSizeTop = new Dimension(width, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding);
            const maxSizeBottom = maxSizeTop.with(undefined, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding);
            return { top: defaultTop, left, fit: width - size.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width, defaultMinSize.width)) };
        })();
        // WEST
        const westPlacement = (function () {
            const width = anchorBox.left - info.borderWidth - info.horizontalPadding;
            const left = Math.max(info.horizontalPadding, anchorBox.left - size.width - info.borderWidth);
            const maxSizeTop = new Dimension(width, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding);
            const maxSizeBottom = maxSizeTop.with(undefined, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding);
            return { top: defaultTop, left, fit: width - size.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width, defaultMinSize.width)) };
        })();
        // SOUTH
        const southPacement = (function () {
            const left = anchorBox.left;
            const top = -info.borderWidth + anchorBox.top + anchorBox.height;
            const maxSizeBottom = new Dimension(anchorBox.width - info.borderHeight, bodyBox.height - anchorBox.top - anchorBox.height - info.verticalPadding);
            return { top, left, fit: maxSizeBottom.height - size.height, maxSizeBottom, maxSizeTop: maxSizeBottom, minSize: defaultMinSize.with(maxSizeBottom.width) };
        })();
        // take first placement that fits or the first with "least bad" fit
        const placements = [eastPlacement, westPlacement, southPacement];
        const placement = (_a = placements.find(p => p.fit >= 0)) !== null && _a !== void 0 ? _a : placements.sort((a, b) => b.fit - a.fit)[0];
        // top/bottom placement
        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;
            }
        }
        this._applyTopLeft({ left: placement.left, top: alignAtTop ? placement.top : bottom - height });
        this.getDomNode().style.position = 'fixed';
        this._resizable.enableSashes(!alignAtTop, placement === eastPlacement, alignAtTop, placement !== eastPlacement);
        this._resizable.minSize = placement.minSize;
        this._resizable.maxSize = maxSize;
        this._resizable.layout(height, Math.min(maxSize.width, size.width));
        this.widget.layout(this._resizable.size.width, this._resizable.size.height);
    }
    _applyTopLeft(topLeft) {
        this._topLeft = topLeft;
        this.getDomNode().style.left = `${this._topLeft.left}px`;
        this.getDomNode().style.top = `${this._topLeft.top}px`;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/files/common/files.js
//#endregion
//#region Utilities
var FileKind;
(function (FileKind) {
    FileKind[FileKind["FILE"] = 0] = "FILE";
    FileKind[FileKind["FOLDER"] = 1] = "FOLDER";
    FileKind[FileKind["ROOT_FOLDER"] = 2] = "ROOT_FOLDER";
})(FileKind || (FileKind = {}));
//#endregion

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/getIconClasses.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




const fileIconDirectoryRegex = /(?:\/|^)(?:([^\/]+)\/)?([^\/]+)$/;
function getIconClasses(modelService, languageService, resource, fileKind) {
    // we always set these base classes even if we do not have a path
    const classes = fileKind === FileKind.ROOT_FOLDER ? ['rootfolder-icon'] : fileKind === FileKind.FOLDER ? ['folder-icon'] : ['file-icon'];
    if (resource) {
        // Get the path and name of the resource. For data-URIs, we need to parse specially
        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 = cssEscape(match[2].toLowerCase());
                if (match[1]) {
                    classes.push(`${cssEscape(match[1].toLowerCase())}-name-dir-icon`); // parent directory
                }
            }
            else {
                name = cssEscape(resource.authority.toLowerCase());
            }
        }
        // Folders
        if (fileKind === FileKind.FOLDER) {
            classes.push(`${name}-name-folder-icon`);
        }
        // Files
        else {
            // Name & Extension(s)
            if (name) {
                classes.push(`${name}-name-file-icon`);
                classes.push(`name-file-icon`); // extra segment to increase file-name score
                // Avoid doing an explosive combination of extensions for very long filenames
                // (most file systems do not allow files > 255 length) with lots of `.` characters
                // https://github.com/microsoft/vscode/issues/116199
                if (name.length <= 255) {
                    const dotSegments = name.split('.');
                    for (let i = 1; i < dotSegments.length; i++) {
                        classes.push(`${dotSegments.slice(i).join('.')}-ext-file-icon`); // add each combination of all found extensions if more than one
                    }
                }
                classes.push(`ext-file-icon`); // extra segment to increase file-ext score
            }
            // Detected Mode
            const detectedLanguageId = detectLanguageId(modelService, languageService, resource);
            if (detectedLanguageId) {
                classes.push(`${cssEscape(detectedLanguageId)}-lang-file-icon`);
            }
        }
    }
    return classes;
}
function detectLanguageId(modelService, languageService, resource) {
    if (!resource) {
        return null; // we need a resource at least
    }
    let languageId = null;
    // Data URI: check for encoded metadata
    if (resource.scheme === Schemas.data) {
        const metadata = DataUri.parseMetaData(resource);
        const mime = metadata.get(DataUri.META_DATA_MIME);
        if (mime) {
            languageId = languageService.getLanguageIdByMimeType(mime);
        }
    }
    // Any other URI: check for model if existing
    else {
        const model = modelService.getModel(resource);
        if (model) {
            languageId = model.getLanguageId();
        }
    }
    // only take if the language id is specific (aka no just plain text)
    if (languageId && languageId !== PLAINTEXT_LANGUAGE_ID) {
        return languageId;
    }
    // otherwise fallback to path based detection
    return languageService.guessLanguageIdByFilepathOrFirstLine(resource);
}
function cssEscape(str) {
    return str.replace(/[\11\12\14\15\40]/g, '/'); // HTML class names can not contain certain whitespace characters, use / instead, which doesn't exist in file names.
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggestWidgetRenderer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var suggestWidgetRenderer_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var suggestWidgetRenderer_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var suggestWidgetRenderer_a;
















function getAriaId(index) {
    return `suggest-aria-id:${index}`;
}
const suggestMoreInfoIcon = registerIcon('suggest-more-info', Codicon.chevronRight, localize('suggestMoreInfoIcon', 'Icon for more information in the suggest widget.'));
const _completionItemColor = new (suggestWidgetRenderer_a = class ColorExtractor {
        extract(item, out) {
            if (item.textLabel.match(ColorExtractor._regexStrict)) {
                out[0] = item.textLabel;
                return true;
            }
            if (item.completion.detail && item.completion.detail.match(ColorExtractor._regexStrict)) {
                out[0] = item.completion.detail;
                return true;
            }
            if (typeof item.completion.documentation === 'string') {
                const match = ColorExtractor._regexRelaxed.exec(item.completion.documentation);
                if (match && (match.index === 0 || match.index + match[0].length === item.completion.documentation.length)) {
                    out[0] = match[0];
                    return true;
                }
            }
            return false;
        }
    },
    suggestWidgetRenderer_a._regexRelaxed = /(#([\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*\))/,
    suggestWidgetRenderer_a._regexStrict = new RegExp(`^${suggestWidgetRenderer_a._regexRelaxed.source}$`, 'i'),
    suggestWidgetRenderer_a);
let ItemRenderer = class ItemRenderer {
    constructor(_editor, _modelService, _languageService, _themeService) {
        this._editor = _editor;
        this._modelService = _modelService;
        this._languageService = _languageService;
        this._themeService = _themeService;
        this._onDidToggleDetails = new Emitter();
        this.onDidToggleDetails = this._onDidToggleDetails.event;
        this.templateId = 'suggestion';
    }
    dispose() {
        this._onDidToggleDetails.dispose();
    }
    renderTemplate(container) {
        const data = Object.create(null);
        data.disposables = new DisposableStore();
        data.root = container;
        data.root.classList.add('show-file-icons');
        data.icon = append(container, dom_$('.icon'));
        data.colorspan = append(data.icon, dom_$('span.colorspan'));
        const text = append(container, dom_$('.contents'));
        const main = append(text, dom_$('.main'));
        data.iconContainer = append(main, dom_$('.icon-label.codicon'));
        data.left = append(main, dom_$('span.left'));
        data.right = append(main, dom_$('span.right'));
        data.iconLabel = new IconLabel(data.left, { supportHighlights: true, supportIcons: true });
        data.disposables.add(data.iconLabel);
        data.parametersLabel = append(data.left, dom_$('span.signature-label'));
        data.qualifierLabel = append(data.left, dom_$('span.qualifier-label'));
        data.detailsLabel = append(data.right, dom_$('span.details-label'));
        data.readMore = append(data.right, dom_$('span.readMore' + ThemeIcon.asCSSSelector(suggestMoreInfoIcon)));
        data.readMore.title = localize('readMore', "Read More");
        const configureFont = () => {
            const options = this._editor.getOptions();
            const fontInfo = options.get(46 /* EditorOption.fontInfo */);
            const fontFamily = fontInfo.getMassagedFontFamily();
            const fontFeatureSettings = fontInfo.fontFeatureSettings;
            const fontSize = options.get(109 /* EditorOption.suggestFontSize */) || fontInfo.fontSize;
            const lineHeight = options.get(110 /* EditorOption.suggestLineHeight */) || fontInfo.lineHeight;
            const fontWeight = fontInfo.fontWeight;
            const letterSpacing = fontInfo.letterSpacing;
            const fontSizePx = `${fontSize}px`;
            const lineHeightPx = `${lineHeight}px`;
            const letterSpacingPx = `${letterSpacing}px`;
            data.root.style.fontSize = fontSizePx;
            data.root.style.fontWeight = fontWeight;
            data.root.style.letterSpacing = letterSpacingPx;
            main.style.fontFamily = fontFamily;
            main.style.fontFeatureSettings = fontFeatureSettings;
            main.style.lineHeight = lineHeightPx;
            data.icon.style.height = lineHeightPx;
            data.icon.style.width = lineHeightPx;
            data.readMore.style.height = lineHeightPx;
            data.readMore.style.width = lineHeightPx;
        };
        configureFont();
        data.disposables.add(this._editor.onDidChangeConfiguration(e => {
            if (e.hasChanged(46 /* EditorOption.fontInfo */) || e.hasChanged(109 /* EditorOption.suggestFontSize */) || e.hasChanged(110 /* EditorOption.suggestLineHeight */)) {
                configureFont();
            }
        }));
        return data;
    }
    renderElement(element, index, data) {
        const { completion } = element;
        data.root.id = getAriaId(index);
        data.colorspan.style.backgroundColor = '';
        const labelOptions = {
            labelEscapeNewLines: true,
            matches: createMatches(element.score)
        };
        const color = [];
        if (completion.kind === 19 /* CompletionItemKind.Color */ && _completionItemColor.extract(element, color)) {
            // special logic for 'color' completion items
            data.icon.className = 'icon customcolor';
            data.iconContainer.className = 'icon hide';
            data.colorspan.style.backgroundColor = color[0];
        }
        else if (completion.kind === 20 /* CompletionItemKind.File */ && this._themeService.getFileIconTheme().hasFileIcons) {
            // special logic for 'file' completion items
            data.icon.className = 'icon hide';
            data.iconContainer.className = 'icon hide';
            const labelClasses = getIconClasses(this._modelService, this._languageService, URI.from({ scheme: 'fake', path: element.textLabel }), FileKind.FILE);
            const detailClasses = getIconClasses(this._modelService, this._languageService, URI.from({ scheme: 'fake', path: completion.detail }), FileKind.FILE);
            labelOptions.extraClasses = labelClasses.length > detailClasses.length ? labelClasses : detailClasses;
        }
        else if (completion.kind === 23 /* CompletionItemKind.Folder */ && this._themeService.getFileIconTheme().hasFolderIcons) {
            // special logic for 'folder' completion items
            data.icon.className = 'icon hide';
            data.iconContainer.className = 'icon hide';
            labelOptions.extraClasses = [
                getIconClasses(this._modelService, this._languageService, URI.from({ scheme: 'fake', path: element.textLabel }), FileKind.FOLDER),
                getIconClasses(this._modelService, this._languageService, URI.from({ scheme: 'fake', path: completion.detail }), FileKind.FOLDER)
            ].flat();
        }
        else {
            // normal icon
            data.icon.className = 'icon hide';
            data.iconContainer.className = '';
            data.iconContainer.classList.add('suggest-icon', ...CSSIcon.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, undefined, 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._editor.getOption(108 /* EditorOption.suggest */).showInlineDetails) {
            show(data.detailsLabel);
        }
        else {
            hide(data.detailsLabel);
        }
        if (canExpandCompletionItem(element)) {
            data.right.classList.add('can-expand-details');
            show(data.readMore);
            data.readMore.onmousedown = e => {
                e.stopPropagation();
                e.preventDefault();
            };
            data.readMore.onclick = e => {
                e.stopPropagation();
                e.preventDefault();
                this._onDidToggleDetails.fire();
            };
        }
        else {
            data.right.classList.remove('can-expand-details');
            hide(data.readMore);
            data.readMore.onmousedown = null;
            data.readMore.onclick = null;
        }
    }
    disposeTemplate(templateData) {
        templateData.disposables.dispose();
    }
};
ItemRenderer = suggestWidgetRenderer_decorate([
    suggestWidgetRenderer_param(1, IModelService),
    suggestWidgetRenderer_param(2, ILanguageService),
    suggestWidgetRenderer_param(3, IThemeService)
], ItemRenderer);

function stripNewLines(str) {
    return str.replace(/\r\n|\r|\n/g, '');
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggestWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var suggestWidget_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var suggestWidget_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var suggestWidget_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};

 // The codicon symbol styles are defined here and must be loaded










 // The codicon symbol colors are defined here and must be loaded to get colors












/**
 * Suggest widget colors
 */
const editorSuggestWidgetBackground = registerColor('editorSuggestWidget.background', { dark: editorWidgetBackground, light: editorWidgetBackground, hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize('editorSuggestWidgetBackground', 'Background color of the suggest widget.'));
const editorSuggestWidgetBorder = registerColor('editorSuggestWidget.border', { dark: editorWidgetBorder, light: editorWidgetBorder, hcDark: editorWidgetBorder, hcLight: editorWidgetBorder }, localize('editorSuggestWidgetBorder', 'Border color of the suggest widget.'));
const editorSuggestWidgetForeground = registerColor('editorSuggestWidget.foreground', { dark: editorForeground, light: editorForeground, hcDark: editorForeground, hcLight: editorForeground }, localize('editorSuggestWidgetForeground', 'Foreground color of the suggest widget.'));
const editorSuggestWidgetSelectedForeground = registerColor('editorSuggestWidget.selectedForeground', { dark: quickInputListFocusForeground, light: quickInputListFocusForeground, hcDark: quickInputListFocusForeground, hcLight: quickInputListFocusForeground }, localize('editorSuggestWidgetSelectedForeground', 'Foreground color of the selected entry in the suggest widget.'));
const editorSuggestWidgetSelectedIconForeground = registerColor('editorSuggestWidget.selectedIconForeground', { dark: quickInputListFocusIconForeground, light: quickInputListFocusIconForeground, hcDark: quickInputListFocusIconForeground, hcLight: quickInputListFocusIconForeground }, localize('editorSuggestWidgetSelectedIconForeground', 'Icon foreground color of the selected entry in the suggest widget.'));
const editorSuggestWidgetSelectedBackground = registerColor('editorSuggestWidget.selectedBackground', { dark: quickInputListFocusBackground, light: quickInputListFocusBackground, hcDark: quickInputListFocusBackground, hcLight: quickInputListFocusBackground }, localize('editorSuggestWidgetSelectedBackground', 'Background color of the selected entry in the suggest widget.'));
const editorSuggestWidgetHighlightForeground = registerColor('editorSuggestWidget.highlightForeground', { dark: listHighlightForeground, light: listHighlightForeground, hcDark: listHighlightForeground, hcLight: listHighlightForeground }, localize('editorSuggestWidgetHighlightForeground', 'Color of the match highlights in the suggest widget.'));
const editorSuggestWidgetHighlightFocusForeground = registerColor('editorSuggestWidget.focusHighlightForeground', { dark: listFocusHighlightForeground, light: listFocusHighlightForeground, hcDark: listFocusHighlightForeground, hcLight: listFocusHighlightForeground }, localize('editorSuggestWidgetFocusHighlightForeground', 'Color of the match highlights in the suggest widget when an item is focused.'));
const editorSuggestWidgetStatusForeground = registerColor('editorSuggestWidgetStatus.foreground', { dark: transparent(editorSuggestWidgetForeground, .5), light: transparent(editorSuggestWidgetForeground, .5), hcDark: transparent(editorSuggestWidgetForeground, .5), hcLight: transparent(editorSuggestWidgetForeground, .5) }, localize('editorSuggestWidgetStatusForeground', 'Foreground color of the suggest widget status.'));
class PersistedWidgetSize {
    constructor(_service, editor) {
        this._service = _service;
        this._key = `suggestWidget.size/${editor.getEditorType()}/${editor instanceof EmbeddedCodeEditorWidget}`;
    }
    restore() {
        var _a;
        const raw = (_a = this._service.get(this._key, 0 /* StorageScope.PROFILE */)) !== null && _a !== void 0 ? _a : '';
        try {
            const obj = JSON.parse(raw);
            if (Dimension.is(obj)) {
                return Dimension.lift(obj);
            }
        }
        catch (_b) {
            // ignore
        }
        return undefined;
    }
    store(size) {
        this._service.store(this._key, JSON.stringify(size), 0 /* StorageScope.PROFILE */, 1 /* StorageTarget.MACHINE */);
    }
    reset() {
        this._service.remove(this._key, 0 /* StorageScope.PROFILE */);
    }
}
let SuggestWidget = class SuggestWidget {
    constructor(editor, _storageService, _contextKeyService, _themeService, instantiationService) {
        this.editor = editor;
        this._storageService = _storageService;
        this._state = 0 /* State.Hidden */;
        this._isAuto = false;
        this._ignoreFocusEvents = false;
        this._forceRenderingAbove = false;
        this._explainMode = false;
        this._showTimeout = new TimeoutTimer();
        this._disposables = new DisposableStore();
        this._onDidSelect = new Emitter();
        this._onDidFocus = new Emitter();
        this._onDidHide = new Emitter();
        this._onDidShow = new Emitter();
        this.onDidSelect = this._onDidSelect.event;
        this.onDidFocus = this._onDidFocus.event;
        this.onDidHide = this._onDidHide.event;
        this.onDidShow = this._onDidShow.event;
        this._onDetailsKeydown = new Emitter();
        this.onDetailsKeyDown = this._onDetailsKeydown.event;
        this.element = new ResizableHTMLElement();
        this.element.domNode.classList.add('editor-widget', 'suggest-widget');
        this._contentWidget = new SuggestContentWidget(this, editor);
        this._persistedSize = new PersistedWidgetSize(_storageService, editor);
        class ResizeState {
            constructor(persistedSize, currentSize, persistHeight = false, persistWidth = false) {
                this.persistedSize = persistedSize;
                this.currentSize = currentSize;
                this.persistHeight = persistHeight;
                this.persistWidth = persistWidth;
            }
        }
        let state;
        this._disposables.add(this.element.onDidWillResize(() => {
            this._contentWidget.lockPreference();
            state = new ResizeState(this._persistedSize.restore(), this.element.size);
        }));
        this._disposables.add(this.element.onDidResize(e => {
            var _a, _b, _c, _d;
            this._resize(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) {
                // only store width or height value that have changed and also
                // only store changes that are above a certain threshold
                const { itemHeight, defaultSize } = this.getLayoutInfo();
                const threshold = Math.round(itemHeight / 2);
                let { width, height } = this.element.size;
                if (!state.persistHeight || Math.abs(state.currentSize.height - height) <= threshold) {
                    height = (_b = (_a = state.persistedSize) === null || _a === void 0 ? void 0 : _a.height) !== null && _b !== void 0 ? _b : defaultSize.height;
                }
                if (!state.persistWidth || Math.abs(state.currentSize.width - width) <= threshold) {
                    width = (_d = (_c = state.persistedSize) === null || _c === void 0 ? void 0 : _c.width) !== null && _d !== void 0 ? _d : defaultSize.width;
                }
                this._persistedSize.store(new Dimension(width, height));
            }
            // reset working state
            this._contentWidget.unlockPreference();
            state = undefined;
        }));
        this._messageElement = append(this.element.domNode, dom_$('.message'));
        this._listElement = append(this.element.domNode, dom_$('.tree'));
        const details = instantiationService.createInstance(SuggestDetailsWidget, this.editor);
        details.onDidClose(this.toggleDetails, this, this._disposables);
        this._details = new SuggestDetailsOverlay(details, this.editor);
        const applyIconStyle = () => this.element.domNode.classList.toggle('no-icons', !this.editor.getOption(108 /* EditorOption.suggest */).showIcons);
        applyIconStyle();
        const renderer = instantiationService.createInstance(ItemRenderer, this.editor);
        this._disposables.add(renderer);
        this._disposables.add(renderer.onDidToggleDetails(() => this.toggleDetails()));
        this._list = new List('SuggestWidget', this._listElement, {
            getHeight: (_element) => this.getLayoutInfo().itemHeight,
            getTemplateId: (_element) => 'suggestion'
        }, [renderer], {
            alwaysConsumeMouseWheel: true,
            useShadows: false,
            mouseSupport: false,
            multipleSelectionSupport: false,
            accessibilityProvider: {
                getRole: () => 'option',
                getWidgetAriaLabel: () => localize('suggest', "Suggest"),
                getWidgetRole: () => 'listbox',
                getAriaLabel: (item) => {
                    let label = item.textLabel;
                    if (typeof item.completion.label !== 'string') {
                        const { detail, description } = item.completion.label;
                        if (detail && description) {
                            label = localize('label.full', '{0}{1}, {2}', label, detail, description);
                        }
                        else if (detail) {
                            label = localize('label.detail', '{0}{1}', label, detail);
                        }
                        else if (description) {
                            label = localize('label.desc', '{0}, {1}', label, description);
                        }
                    }
                    if (!item.isResolved || !this._isDetailsVisible()) {
                        return label;
                    }
                    const { documentation, detail } = item.completion;
                    const docs = format('{0}{1}', detail || '', documentation ? (typeof documentation === 'string' ? documentation : documentation.value) : '');
                    return localize('ariaCurrenttSuggestionReadDetails', "{0}, docs: {1}", label, docs);
                },
            }
        });
        this._status = instantiationService.createInstance(SuggestWidgetStatus, this.element.domNode);
        const applyStatusBarStyle = () => this.element.domNode.classList.toggle('with-status-bar', this.editor.getOption(108 /* EditorOption.suggest */).showStatusBar);
        applyStatusBarStyle();
        this._disposables.add(attachListStyler(this._list, _themeService, {
            listInactiveFocusBackground: editorSuggestWidgetSelectedBackground,
            listInactiveFocusOutline: activeContrastBorder
        }));
        this._disposables.add(_themeService.onDidColorThemeChange(t => this._onThemeChange(t)));
        this._onThemeChange(_themeService.getColorTheme());
        this._disposables.add(this._list.onMouseDown(e => this._onListMouseDownOrTap(e)));
        this._disposables.add(this._list.onTap(e => this._onListMouseDownOrTap(e)));
        this._disposables.add(this._list.onDidChangeSelection(e => this._onListSelection(e)));
        this._disposables.add(this._list.onDidChangeFocus(e => this._onListFocus(e)));
        this._disposables.add(this.editor.onDidChangeCursorSelection(() => this._onCursorSelectionChanged()));
        this._disposables.add(this.editor.onDidChangeConfiguration(e => {
            if (e.hasChanged(108 /* EditorOption.suggest */)) {
                applyStatusBarStyle();
                applyIconStyle();
            }
        }));
        this._ctxSuggestWidgetVisible = suggest_Context.Visible.bindTo(_contextKeyService);
        this._ctxSuggestWidgetDetailsVisible = suggest_Context.DetailsVisible.bindTo(_contextKeyService);
        this._ctxSuggestWidgetMultipleSuggestions = suggest_Context.MultipleSuggestions.bindTo(_contextKeyService);
        this._ctxSuggestWidgetHasFocusedSuggestion = suggest_Context.HasFocusedSuggestion.bindTo(_contextKeyService);
        this._disposables.add(addStandardDisposableListener(this._details.widget.domNode, 'keydown', e => {
            this._onDetailsKeydown.fire(e);
        }));
        this._disposables.add(this.editor.onMouseDown((e) => this._onEditorMouseDown(e)));
    }
    dispose() {
        var _a;
        this._details.widget.dispose();
        this._details.dispose();
        this._list.dispose();
        this._status.dispose();
        this._disposables.dispose();
        (_a = this._loadingTimeout) === null || _a === void 0 ? void 0 : _a.dispose();
        this._showTimeout.dispose();
        this._contentWidget.dispose();
        this.element.dispose();
    }
    _onEditorMouseDown(mouseEvent) {
        if (this._details.widget.domNode.contains(mouseEvent.target.element)) {
            // Clicking inside details
            this._details.widget.domNode.focus();
        }
        else {
            // Clicking outside details and inside suggest
            if (this.element.domNode.contains(mouseEvent.target.element)) {
                this.editor.focus();
            }
        }
    }
    _onCursorSelectionChanged() {
        if (this._state !== 0 /* State.Hidden */) {
            this._contentWidget.layout();
        }
    }
    _onListMouseDownOrTap(e) {
        if (typeof e.element === 'undefined' || typeof e.index === 'undefined') {
            return;
        }
        // prevent stealing browser focus from the editor
        e.browserEvent.preventDefault();
        e.browserEvent.stopPropagation();
        this._select(e.element, e.index);
    }
    _onListSelection(e) {
        if (e.elements.length) {
            this._select(e.elements[0], e.indexes[0]);
        }
    }
    _select(item, index) {
        const completionModel = this._completionModel;
        if (completionModel) {
            this._onDidSelect.fire({ item, index, model: completionModel });
            this.editor.focus();
        }
    }
    _onThemeChange(theme) {
        this._details.widget.borderWidth = isHighContrast(theme.type) ? 2 : 1;
    }
    _onListFocus(e) {
        var _a;
        if (this._ignoreFocusEvents) {
            return;
        }
        if (!e.elements.length) {
            if (this._currentSuggestionDetails) {
                this._currentSuggestionDetails.cancel();
                this._currentSuggestionDetails = undefined;
                this._focusedItem = undefined;
            }
            this.editor.setAriaOptions({ activeDescendant: undefined });
            this._ctxSuggestWidgetHasFocusedSuggestion.set(false);
            return;
        }
        if (!this._completionModel) {
            return;
        }
        this._ctxSuggestWidgetHasFocusedSuggestion.set(true);
        const item = e.elements[0];
        const index = e.indexes[0];
        if (item !== this._focusedItem) {
            (_a = this._currentSuggestionDetails) === null || _a === void 0 ? void 0 : _a.cancel();
            this._currentSuggestionDetails = undefined;
            this._focusedItem = item;
            this._list.reveal(index);
            this._currentSuggestionDetails = createCancelablePromise((token) => suggestWidget_awaiter(this, void 0, void 0, function* () {
                const loading = disposableTimeout(() => {
                    if (this._isDetailsVisible()) {
                        this.showDetails(true);
                    }
                }, 250);
                const sub = token.onCancellationRequested(() => loading.dispose());
                const result = yield item.resolve(token);
                loading.dispose();
                sub.dispose();
                return result;
            }));
            this._currentSuggestionDetails.then(() => {
                if (index >= this._list.length || item !== this._list.element(index)) {
                    return;
                }
                // item can have extra information, so re-render
                this._ignoreFocusEvents = true;
                this._list.splice(index, 1, [item]);
                this._list.setFocus([index]);
                this._ignoreFocusEvents = false;
                if (this._isDetailsVisible()) {
                    this.showDetails(false);
                }
                else {
                    this.element.domNode.classList.remove('docs-side');
                }
                this.editor.setAriaOptions({ activeDescendant: getAriaId(index) });
            }).catch(onUnexpectedError);
        }
        // emit an event
        this._onDidFocus.fire({ item, index, model: this._completionModel });
    }
    _setState(state) {
        if (this._state === state) {
            return;
        }
        this._state = state;
        this.element.domNode.classList.toggle('frozen', state === 4 /* State.Frozen */);
        this.element.domNode.classList.remove('message');
        switch (state) {
            case 0 /* State.Hidden */:
                hide(this._messageElement, this._listElement, this._status.element);
                this._details.hide(true);
                this._status.hide();
                this._contentWidget.hide();
                this._ctxSuggestWidgetVisible.reset();
                this._ctxSuggestWidgetMultipleSuggestions.reset();
                this._ctxSuggestWidgetHasFocusedSuggestion.reset();
                this._showTimeout.cancel();
                this.element.domNode.classList.remove('visible');
                this._list.splice(0, this._list.length);
                this._focusedItem = undefined;
                this._cappedHeight = undefined;
                this._explainMode = false;
                break;
            case 1 /* State.Loading */:
                this.element.domNode.classList.add('message');
                this._messageElement.textContent = SuggestWidget.LOADING_MESSAGE;
                hide(this._listElement, this._status.element);
                show(this._messageElement);
                this._details.hide();
                this._show();
                this._focusedItem = undefined;
                break;
            case 2 /* State.Empty */:
                this.element.domNode.classList.add('message');
                this._messageElement.textContent = SuggestWidget.NO_SUGGESTIONS_MESSAGE;
                hide(this._listElement, this._status.element);
                show(this._messageElement);
                this._details.hide();
                this._show();
                this._focusedItem = undefined;
                break;
            case 3 /* State.Open */:
                hide(this._messageElement);
                show(this._listElement, this._status.element);
                this._show();
                break;
            case 4 /* State.Frozen */:
                hide(this._messageElement);
                show(this._listElement, this._status.element);
                this._show();
                break;
            case 5 /* State.Details */:
                hide(this._messageElement);
                show(this._listElement, this._status.element);
                this._details.show();
                this._show();
                break;
        }
    }
    _show() {
        this._status.show();
        this._contentWidget.show();
        this._layout(this._persistedSize.restore());
        this._ctxSuggestWidgetVisible.set(true);
        this._showTimeout.cancelAndSet(() => {
            this.element.domNode.classList.add('visible');
            this._onDidShow.fire(this);
        }, 100);
    }
    showTriggered(auto, delay) {
        if (this._state !== 0 /* State.Hidden */) {
            return;
        }
        this._contentWidget.setPosition(this.editor.getPosition());
        this._isAuto = !!auto;
        if (!this._isAuto) {
            this._loadingTimeout = disposableTimeout(() => this._setState(1 /* State.Loading */), delay);
        }
    }
    showSuggestions(completionModel, selectionIndex, isFrozen, isAuto) {
        var _a, _b;
        this._contentWidget.setPosition(this.editor.getPosition());
        (_a = this._loadingTimeout) === null || _a === void 0 ? void 0 : _a.dispose();
        (_b = this._currentSuggestionDetails) === null || _b === void 0 ? void 0 : _b.cancel();
        this._currentSuggestionDetails = undefined;
        if (this._completionModel !== completionModel) {
            this._completionModel = completionModel;
        }
        if (isFrozen && this._state !== 2 /* State.Empty */ && this._state !== 0 /* State.Hidden */) {
            this._setState(4 /* State.Frozen */);
            return;
        }
        const visibleCount = this._completionModel.items.length;
        const isEmpty = visibleCount === 0;
        this._ctxSuggestWidgetMultipleSuggestions.set(visibleCount > 1);
        if (isEmpty) {
            this._setState(isAuto ? 0 /* State.Hidden */ : 2 /* State.Empty */);
            this._completionModel = undefined;
            return;
        }
        this._focusedItem = undefined;
        this._list.splice(0, this._list.length, this._completionModel.items);
        this._setState(isFrozen ? 4 /* State.Frozen */ : 3 /* State.Open */);
        if (selectionIndex >= 0) {
            this._list.reveal(selectionIndex, 0);
            this._list.setFocus([selectionIndex]);
        }
        this._layout(this.element.size);
        // Reset focus border
        this._details.widget.domNode.classList.remove('focused');
    }
    selectNextPage() {
        switch (this._state) {
            case 0 /* State.Hidden */:
                return false;
            case 5 /* State.Details */:
                this._details.widget.pageDown();
                return true;
            case 1 /* State.Loading */:
                return !this._isAuto;
            default:
                this._list.focusNextPage();
                return true;
        }
    }
    selectNext() {
        switch (this._state) {
            case 0 /* State.Hidden */:
                return false;
            case 1 /* State.Loading */:
                return !this._isAuto;
            default:
                this._list.focusNext(1, true);
                return true;
        }
    }
    selectLast() {
        switch (this._state) {
            case 0 /* State.Hidden */:
                return false;
            case 5 /* State.Details */:
                this._details.widget.scrollBottom();
                return true;
            case 1 /* State.Loading */:
                return !this._isAuto;
            default:
                this._list.focusLast();
                return true;
        }
    }
    selectPreviousPage() {
        switch (this._state) {
            case 0 /* State.Hidden */:
                return false;
            case 5 /* State.Details */:
                this._details.widget.pageUp();
                return true;
            case 1 /* State.Loading */:
                return !this._isAuto;
            default:
                this._list.focusPreviousPage();
                return true;
        }
    }
    selectPrevious() {
        switch (this._state) {
            case 0 /* State.Hidden */:
                return false;
            case 1 /* State.Loading */:
                return !this._isAuto;
            default:
                this._list.focusPrevious(1, true);
                return false;
        }
    }
    selectFirst() {
        switch (this._state) {
            case 0 /* State.Hidden */:
                return false;
            case 5 /* State.Details */:
                this._details.widget.scrollTop();
                return true;
            case 1 /* State.Loading */:
                return !this._isAuto;
            default:
                this._list.focusFirst();
                return true;
        }
    }
    getFocusedItem() {
        if (this._state !== 0 /* State.Hidden */
            && this._state !== 2 /* State.Empty */
            && this._state !== 1 /* State.Loading */
            && this._completionModel) {
            return {
                item: this._list.getFocusedElements()[0],
                index: this._list.getFocus()[0],
                model: this._completionModel
            };
        }
        return undefined;
    }
    toggleDetailsFocus() {
        if (this._state === 5 /* State.Details */) {
            this._setState(3 /* State.Open */);
            this._details.widget.domNode.classList.remove('focused');
        }
        else if (this._state === 3 /* State.Open */ && this._isDetailsVisible()) {
            this._setState(5 /* State.Details */);
            this._details.widget.domNode.classList.add('focused');
        }
    }
    toggleDetails() {
        if (this._isDetailsVisible()) {
            // hide details widget
            this._ctxSuggestWidgetDetailsVisible.set(false);
            this._setDetailsVisible(false);
            this._details.hide();
            this.element.domNode.classList.remove('shows-details');
        }
        else if ((canExpandCompletionItem(this._list.getFocusedElements()[0]) || this._explainMode) && (this._state === 3 /* State.Open */ || this._state === 5 /* State.Details */ || this._state === 4 /* State.Frozen */)) {
            // show details widget (iff possible)
            this._ctxSuggestWidgetDetailsVisible.set(true);
            this._setDetailsVisible(true);
            this.showDetails(false);
        }
    }
    showDetails(loading) {
        this._details.show();
        if (loading) {
            this._details.widget.renderLoading();
        }
        else {
            this._details.widget.renderItem(this._list.getFocusedElements()[0], this._explainMode);
        }
        this._positionDetails();
        this.editor.focus();
        this.element.domNode.classList.add('shows-details');
    }
    toggleExplainMode() {
        if (this._list.getFocusedElements()[0]) {
            this._explainMode = !this._explainMode;
            if (!this._isDetailsVisible()) {
                this.toggleDetails();
            }
            else {
                this.showDetails(false);
            }
        }
    }
    resetPersistedSize() {
        this._persistedSize.reset();
    }
    hideWidget() {
        var _a;
        (_a = this._loadingTimeout) === null || _a === void 0 ? void 0 : _a.dispose();
        this._setState(0 /* State.Hidden */);
        this._onDidHide.fire(this);
        this.element.clearSashHoverState();
        // ensure that a reasonable widget height is persisted so that
        // accidential "resize-to-single-items" cases aren't happening
        const dim = this._persistedSize.restore();
        const minPersistedHeight = Math.ceil(this.getLayoutInfo().itemHeight * 4.3);
        if (dim && dim.height < minPersistedHeight) {
            this._persistedSize.store(dim.with(undefined, minPersistedHeight));
        }
    }
    isFrozen() {
        return this._state === 4 /* State.Frozen */;
    }
    _afterRender(position) {
        if (position === null) {
            if (this._isDetailsVisible()) {
                this._details.hide(); //todo@jrieken soft-hide
            }
            return;
        }
        if (this._state === 2 /* State.Empty */ || this._state === 1 /* State.Loading */) {
            // no special positioning when widget isn't showing list
            return;
        }
        if (this._isDetailsVisible()) {
            this._details.show();
        }
        this._positionDetails();
    }
    _layout(size) {
        var _a, _b, _c;
        if (!this.editor.hasModel()) {
            return;
        }
        if (!this.editor.getDomNode()) {
            // happens when running tests
            return;
        }
        const bodyBox = getClientArea(document.body);
        const info = this.getLayoutInfo();
        if (!size) {
            size = info.defaultSize;
        }
        let height = size.height;
        let width = size.width;
        // status bar
        this._status.element.style.lineHeight = `${info.itemHeight}px`;
        if (this._state === 2 /* State.Empty */ || this._state === 1 /* State.Loading */) {
            // showing a message only
            height = info.itemHeight + info.borderHeight;
            width = info.defaultSize.width / 2;
            this.element.enableSashes(false, false, false, false);
            this.element.minSize = this.element.maxSize = new Dimension(width, height);
            this._contentWidget.setPreference(2 /* ContentWidgetPositionPreference.BELOW */);
        }
        else {
            // showing items
            // width math
            const maxWidth = bodyBox.width - info.borderHeight - 2 * info.horizontalPadding;
            if (width > maxWidth) {
                width = maxWidth;
            }
            const preferredWidth = this._completionModel ? this._completionModel.stats.pLabelLen * info.typicalHalfwidthCharacterWidth : width;
            // height math
            const fullHeight = info.statusBarHeight + this._list.contentHeight + info.borderHeight;
            const minHeight = info.itemHeight + info.statusBarHeight;
            const editorBox = getDomNodePagePosition(this.editor.getDomNode());
            const cursorBox = this.editor.getScrolledVisiblePosition(this.editor.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 === ((_a = this._cappedHeight) === null || _a === void 0 ? void 0 : _a.capped)) {
                // Restore the old (wanted) height when the current
                // height is capped to fit
                height = this._cappedHeight.wanted;
            }
            if (height < minHeight) {
                height = minHeight;
            }
            if (height > maxHeight) {
                height = maxHeight;
            }
            const forceRenderingAboveRequiredSpace = 150;
            if (height > maxHeightBelow || (this._forceRenderingAbove && availableSpaceAbove > forceRenderingAboveRequiredSpace)) {
                this._contentWidget.setPreference(1 /* ContentWidgetPositionPreference.ABOVE */);
                this.element.enableSashes(true, true, false, false);
                maxHeight = maxHeightAbove;
            }
            else {
                this._contentWidget.setPreference(2 /* ContentWidgetPositionPreference.BELOW */);
                this.element.enableSashes(false, true, true, false);
                maxHeight = maxHeightBelow;
            }
            this.element.preferredSize = new Dimension(preferredWidth, info.defaultSize.height);
            this.element.maxSize = new Dimension(maxWidth, maxHeight);
            this.element.minSize = new Dimension(220, minHeight);
            // Know when the height was capped to fit and remember
            // the wanted height for later. This is required when going
            // left to widen suggestions.
            this._cappedHeight = height === fullHeight
                ? { wanted: (_c = (_b = this._cappedHeight) === null || _b === void 0 ? void 0 : _b.wanted) !== null && _c !== void 0 ? _c : size.height, capped: height }
                : undefined;
        }
        this._resize(width, height);
    }
    _resize(width, height) {
        const { width: maxWidth, height: maxHeight } = this.element.maxSize;
        width = Math.min(maxWidth, width);
        height = Math.min(maxHeight, height);
        const { statusBarHeight } = this.getLayoutInfo();
        this._list.layout(height - statusBarHeight, width);
        this._listElement.style.height = `${height - statusBarHeight}px`;
        this.element.layout(height, width);
        this._contentWidget.layout();
        this._positionDetails();
    }
    _positionDetails() {
        var _a;
        if (this._isDetailsVisible()) {
            this._details.placeAtAnchor(this.element.domNode, ((_a = this._contentWidget.getPosition()) === null || _a === void 0 ? void 0 : _a.preference[0]) === 2 /* ContentWidgetPositionPreference.BELOW */);
        }
    }
    getLayoutInfo() {
        const fontInfo = this.editor.getOption(46 /* EditorOption.fontInfo */);
        const itemHeight = clamp(this.editor.getOption(110 /* EditorOption.suggestLineHeight */) || fontInfo.lineHeight, 8, 1000);
        const statusBarHeight = !this.editor.getOption(108 /* EditorOption.suggest */).showStatusBar || this._state === 2 /* State.Empty */ || this._state === 1 /* State.Loading */ ? 0 : itemHeight;
        const borderWidth = this._details.widget.borderWidth;
        const borderHeight = 2 * borderWidth;
        return {
            itemHeight,
            statusBarHeight,
            borderWidth,
            borderHeight,
            typicalHalfwidthCharacterWidth: fontInfo.typicalHalfwidthCharacterWidth,
            verticalPadding: 22,
            horizontalPadding: 14,
            defaultSize: new Dimension(430, statusBarHeight + 12 * itemHeight + borderHeight)
        };
    }
    _isDetailsVisible() {
        return this._storageService.getBoolean('expandSuggestionDocs', 0 /* StorageScope.PROFILE */, false);
    }
    _setDetailsVisible(value) {
        this._storageService.store('expandSuggestionDocs', value, 0 /* StorageScope.PROFILE */, 0 /* StorageTarget.USER */);
    }
    forceRenderingAbove() {
        if (!this._forceRenderingAbove) {
            this._forceRenderingAbove = true;
            this._layout(this._persistedSize.restore());
        }
    }
    stopForceRenderingAbove() {
        this._forceRenderingAbove = false;
    }
};
SuggestWidget.LOADING_MESSAGE = localize('suggestWidget.loading', "Loading...");
SuggestWidget.NO_SUGGESTIONS_MESSAGE = localize('suggestWidget.noSuggestions', "No suggestions.");
SuggestWidget = suggestWidget_decorate([
    suggestWidget_param(1, IStorageService),
    suggestWidget_param(2, IContextKeyService),
    suggestWidget_param(3, IThemeService),
    suggestWidget_param(4, IInstantiationService)
], SuggestWidget);

class SuggestContentWidget {
    constructor(_widget, _editor) {
        this._widget = _widget;
        this._editor = _editor;
        this.allowEditorOverflow = true;
        this.suppressMouseDown = false;
        this._preferenceLocked = false;
        this._added = false;
        this._hidden = false;
    }
    dispose() {
        if (this._added) {
            this._added = false;
            this._editor.removeContentWidget(this);
        }
    }
    getId() {
        return 'editor.widget.suggestWidget';
    }
    getDomNode() {
        return this._widget.element.domNode;
    }
    show() {
        this._hidden = false;
        if (!this._added) {
            this._added = true;
            this._editor.addContentWidget(this);
        }
    }
    hide() {
        if (!this._hidden) {
            this._hidden = true;
            this.layout();
        }
    }
    layout() {
        this._editor.layoutContentWidget(this);
    }
    getPosition() {
        if (this._hidden || !this._position || !this._preference) {
            return null;
        }
        return {
            position: this._position,
            preference: [this._preference]
        };
    }
    beforeRender() {
        const { height, width } = this._widget.element.size;
        const { borderWidth, horizontalPadding } = this._widget.getLayoutInfo();
        return new Dimension(width + 2 * borderWidth + horizontalPadding, height + 2 * borderWidth);
    }
    afterRender(position) {
        this._widget._afterRender(position);
    }
    setPreference(preference) {
        if (!this._preferenceLocked) {
            this._preference = preference;
        }
    }
    lockPreference() {
        this._preferenceLocked = true;
    }
    unlockPreference() {
        this._preferenceLocked = false;
    }
    setPosition(position) {
        this._position = position;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggestController.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var suggestController_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var suggestController_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};



































// sticky suggest widget which doesn't disappear on focus out and such
const _sticky = false;
// _sticky = Boolean("true"); // done "weirdly" so that a lint warning prevents you from pushing this
class LineSuffix {
    constructor(_model, _position) {
        this._model = _model;
        this._position = _position;
        // spy on what's happening right of the cursor. two cases:
        // 1. end of line -> check that it's still end of line
        // 2. mid of line -> add a marker and compute the delta
        const maxColumn = _model.getLineMaxColumn(_position.lineNumber);
        if (maxColumn !== _position.column) {
            const offset = _model.getOffsetAt(_position);
            const end = _model.getPositionAt(offset + 1);
            this._marker = _model.deltaDecorations([], [{
                    range: Range.fromPositions(_position, end),
                    options: { description: 'suggest-line-suffix', stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */ }
                }]);
        }
    }
    dispose() {
        if (this._marker && !this._model.isDisposed()) {
            this._model.deltaDecorations(this._marker, []);
        }
    }
    delta(position) {
        if (this._model.isDisposed() || this._position.lineNumber !== position.lineNumber) {
            // bail out early if things seems fishy
            return 0;
        }
        // read the marker (in case suggest was triggered at line end) or compare
        // the cursor to the line end.
        if (this._marker) {
            const range = this._model.getDecorationRange(this._marker[0]);
            const end = this._model.getOffsetAt(range.getStartPosition());
            return end - this._model.getOffsetAt(position);
        }
        else {
            return this._model.getLineMaxColumn(position.lineNumber) - position.column;
        }
    }
}
let SuggestController = class SuggestController {
    constructor(editor, _memoryService, _commandService, _contextKeyService, _instantiationService, _logService, _telemetryService) {
        this._memoryService = _memoryService;
        this._commandService = _commandService;
        this._contextKeyService = _contextKeyService;
        this._instantiationService = _instantiationService;
        this._logService = _logService;
        this._telemetryService = _telemetryService;
        this._lineSuffix = new MutableDisposable();
        this._toDispose = new DisposableStore();
        this._selectors = new PriorityRegistry(s => s.priority);
        this._telemetryGate = 0;
        this.editor = editor;
        this.model = _instantiationService.createInstance(SuggestModel, this.editor);
        // context key: update insert/replace mode
        const ctxInsertMode = suggest_Context.InsertMode.bindTo(_contextKeyService);
        ctxInsertMode.set(editor.getOption(108 /* EditorOption.suggest */).insertMode);
        this.model.onDidTrigger(() => ctxInsertMode.set(editor.getOption(108 /* EditorOption.suggest */).insertMode));
        this.widget = this._toDispose.add(new IdleValue(() => {
            const widget = this._instantiationService.createInstance(SuggestWidget, this.editor);
            this._toDispose.add(widget);
            this._toDispose.add(widget.onDidSelect(item => this._insertSuggestion(item, 0), this));
            // Wire up logic to accept a suggestion on certain characters
            const commitCharacterController = new CommitCharacterController(this.editor, widget, item => this._insertSuggestion(item, 2 /* InsertFlags.NoAfterUndoStop */));
            this._toDispose.add(commitCharacterController);
            this._toDispose.add(this.model.onDidSuggest(e => {
                if (e.completionModel.items.length === 0) {
                    commitCharacterController.reset();
                }
            }));
            // Wire up makes text edit context key
            const ctxMakesTextEdit = suggest_Context.MakesTextEdit.bindTo(this._contextKeyService);
            const ctxHasInsertAndReplace = suggest_Context.HasInsertAndReplaceRange.bindTo(this._contextKeyService);
            const ctxCanResolve = suggest_Context.CanResolve.bindTo(this._contextKeyService);
            this._toDispose.add(toDisposable(() => {
                ctxMakesTextEdit.reset();
                ctxHasInsertAndReplace.reset();
                ctxCanResolve.reset();
            }));
            this._toDispose.add(widget.onDidFocus(({ item }) => {
                // (ctx: makesTextEdit)
                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 /* State.Auto */
                    && !item.completion.additionalTextEdits
                    && !(item.completion.insertTextRules & 4 /* CompletionItemInsertTextRule.InsertAsSnippet */)
                    && 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);
                // (ctx: hasInsertAndReplaceRange)
                ctxHasInsertAndReplace.set(!Position.equals(item.editInsertEnd, item.editReplaceEnd));
                // (ctx: canResolve)
                ctxCanResolve.set(Boolean(item.provider.resolveCompletionItem) || Boolean(item.completion.documentation) || item.completion.detail !== item.completion.label);
            }));
            this._toDispose.add(widget.onDetailsKeyDown(e => {
                // cmd + c on macOS, ctrl + c on Win / Linux
                if (e.toKeybinding().equals(new SimpleKeybinding(true, false, false, false, 33 /* KeyCode.KeyC */)) ||
                    (isMacintosh && e.toKeybinding().equals(new SimpleKeybinding(false, false, false, true, 33 /* KeyCode.KeyC */)))) {
                    e.stopPropagation();
                    return;
                }
                if (!e.toKeybinding().isModifierKey()) {
                    this.editor.focus();
                }
            }));
            return widget;
        }));
        // Wire up text overtyping capture
        this._overtypingCapturer = this._toDispose.add(new IdleValue(() => {
            return this._toDispose.add(new OvertypingCapturer(this.editor, this.model));
        }));
        this._alternatives = this._toDispose.add(new IdleValue(() => {
            return this._toDispose.add(new SuggestAlternatives(this.editor, this._contextKeyService));
        }));
        this._toDispose.add(_instantiationService.createInstance(WordContextKey, editor));
        this._toDispose.add(this.model.onDidTrigger(e => {
            this.widget.value.showTriggered(e.auto, e.shy ? 250 : 50);
            this._lineSuffix.value = new LineSuffix(this.editor.getModel(), e.position);
        }));
        this._toDispose.add(this.model.onDidSuggest(e => {
            if (e.shy) {
                return;
            }
            let index = -1;
            if (!e.noSelect) {
                for (const selector of this._selectors.itemsOrderedByPriorityDesc) {
                    index = selector.select(this.editor.getModel(), this.editor.getPosition(), e.completionModel.items);
                    if (index !== -1) {
                        break;
                    }
                }
                if (index === -1) {
                    index = this._memoryService.select(this.editor.getModel(), this.editor.getPosition(), e.completionModel.items);
                }
            }
            this.widget.value.showSuggestions(e.completionModel, index, e.isFrozen, e.auto);
        }));
        this._toDispose.add(this.model.onDidCancel(e => {
            if (!e.retrigger) {
                this.widget.value.hideWidget();
            }
        }));
        this._toDispose.add(this.editor.onDidBlurEditorWidget(() => {
            if (!_sticky) {
                this.model.cancel();
                this.model.clear();
            }
        }));
        // Manage the acceptSuggestionsOnEnter context key
        const acceptSuggestionsOnEnter = suggest_Context.AcceptSuggestionsOnEnter.bindTo(_contextKeyService);
        const updateFromConfig = () => {
            const acceptSuggestionOnEnter = this.editor.getOption(1 /* EditorOption.acceptSuggestionOnEnter */);
            acceptSuggestionsOnEnter.set(acceptSuggestionOnEnter === 'on' || acceptSuggestionOnEnter === 'smart');
        };
        this._toDispose.add(this.editor.onDidChangeConfiguration(() => updateFromConfig()));
        updateFromConfig();
    }
    static get(editor) {
        return editor.getContribution(SuggestController.ID);
    }
    dispose() {
        this._alternatives.dispose();
        this._toDispose.dispose();
        this.widget.dispose();
        this.model.dispose();
        this._lineSuffix.dispose();
    }
    _insertSuggestion(event, flags) {
        if (!event || !event.item) {
            this._alternatives.value.reset();
            this.model.cancel();
            this.model.clear();
            return;
        }
        if (!this.editor.hasModel()) {
            return;
        }
        const snippetController = SnippetController2.get(this.editor);
        if (!snippetController) {
            return;
        }
        const model = this.editor.getModel();
        const modelVersionNow = model.getAlternativeVersionId();
        const { item } = event;
        //
        const tasks = [];
        const cts = new CancellationTokenSource();
        // pushing undo stops *before* additional text edits and
        // *after* the main edit
        if (!(flags & 1 /* InsertFlags.NoBeforeUndoStop */)) {
            this.editor.pushUndoStop();
        }
        // compute overwrite[Before|After] deltas BEFORE applying extra edits
        const info = this.getOverwriteInfo(item, Boolean(flags & 8 /* InsertFlags.AlternativeOverwriteConfig */));
        // keep item in memory
        this._memoryService.memorize(model, this.editor.getPosition(), item);
        if (Array.isArray(item.completion.additionalTextEdits)) {
            // sync additional edits
            const scrollState = StableEditorScrollState.capture(this.editor);
            this.editor.executeEdits('suggestController.additionalTextEdits.sync', item.completion.additionalTextEdits.map(edit => EditOperation.replaceMove(Range.lift(edit.range), edit.text)));
            scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
        }
        else if (!item.isResolved) {
            // async additional edits
            const sw = new StopWatch(true);
            let position;
            const docListener = model.onDidChangeContent(e => {
                if (e.isFlush) {
                    cts.cancel();
                    docListener.dispose();
                    return;
                }
                for (const change of e.changes) {
                    const thisPosition = Range.getEndPosition(change.range);
                    if (!position || Position.isBefore(thisPosition, position)) {
                        position = thisPosition;
                    }
                }
            });
            const oldFlags = flags;
            flags |= 2 /* InsertFlags.NoAfterUndoStop */;
            let didType = false;
            const typeListener = this.editor.onWillType(() => {
                typeListener.dispose();
                didType = true;
                if (!(oldFlags & 2 /* InsertFlags.NoAfterUndoStop */)) {
                    this.editor.pushUndoStop();
                }
            });
            tasks.push(item.resolve(cts.token).then(() => {
                if (!item.completion.additionalTextEdits || cts.token.isCancellationRequested) {
                    return false;
                }
                if (position && item.completion.additionalTextEdits.some(edit => Position.isBefore(position, Range.getStartPosition(edit.range)))) {
                    return false;
                }
                if (didType) {
                    this.editor.pushUndoStop();
                }
                const scrollState = StableEditorScrollState.capture(this.editor);
                this.editor.executeEdits('suggestController.additionalTextEdits.async', item.completion.additionalTextEdits.map(edit => EditOperation.replaceMove(Range.lift(edit.range), edit.text)));
                scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
                if (didType || !(oldFlags & 2 /* InsertFlags.NoAfterUndoStop */)) {
                    this.editor.pushUndoStop();
                }
                return true;
            }).then(applied => {
                this._logService.trace('[suggest] async resolving of edits DONE (ms, applied?)', sw.elapsed(), applied);
                docListener.dispose();
                typeListener.dispose();
            }));
        }
        let { insertText } = item.completion;
        if (!(item.completion.insertTextRules & 4 /* CompletionItemInsertTextRule.InsertAsSnippet */)) {
            insertText = SnippetParser.escape(insertText);
        }
        snippetController.insert(insertText, {
            overwriteBefore: info.overwriteBefore,
            overwriteAfter: info.overwriteAfter,
            undoStopBefore: false,
            undoStopAfter: false,
            adjustWhitespace: !(item.completion.insertTextRules & 1 /* CompletionItemInsertTextRule.KeepWhitespace */),
            clipboardText: event.model.clipboardText,
            overtypingCapturer: this._overtypingCapturer.value
        });
        if (!(flags & 2 /* InsertFlags.NoAfterUndoStop */)) {
            this.editor.pushUndoStop();
        }
        if (!item.completion.command) {
            // done
            this.model.cancel();
        }
        else if (item.completion.command.id === TriggerSuggestAction.id) {
            // retigger
            this.model.trigger({ auto: true, shy: false, noSelect: false }, true);
        }
        else {
            // exec command, done
            tasks.push(this._commandService.executeCommand(item.completion.command.id, ...(item.completion.command.arguments ? [...item.completion.command.arguments] : [])).catch(onUnexpectedError));
            this.model.cancel();
        }
        if (flags & 4 /* InsertFlags.KeepAlternativeSuggestions */) {
            this._alternatives.value.set(event, next => {
                // cancel resolving of additional edits
                cts.cancel();
                // this is not so pretty. when inserting the 'next'
                // suggestion we undo until we are at the state at
                // which we were before inserting the previous suggestion...
                while (model.canUndo()) {
                    if (modelVersionNow !== model.getAlternativeVersionId()) {
                        model.undo();
                    }
                    this._insertSuggestion(next, 1 /* InsertFlags.NoBeforeUndoStop */ | 2 /* InsertFlags.NoAfterUndoStop */ | (flags & 8 /* InsertFlags.AlternativeOverwriteConfig */ ? 8 /* InsertFlags.AlternativeOverwriteConfig */ : 0));
                    break;
                }
            });
        }
        this._alertCompletionItem(item);
        // clear only now - after all tasks are done
        Promise.all(tasks).finally(() => {
            this._reportSuggestionAcceptedTelemetry(item, model, event);
            this.model.clear();
            cts.dispose();
        });
    }
    _reportSuggestionAcceptedTelemetry(item, model, acceptedSuggestion) {
        var _a;
        if (this._telemetryGate++ % 100 !== 0) {
            return;
        }
        // _debugDisplayName looks like `vscode.css-language-features(/-:)`, where the last bit is the trigger chars
        // normalize it to just the extension ID and lowercase
        const providerId = item.extensionId ? item.extensionId.value : ((_a = acceptedSuggestion.item.provider._debugDisplayName) !== null && _a !== void 0 ? _a : 'unknown').split('(', 1)[0].toLowerCase();
        this._telemetryService.publicLog2('suggest.acceptedSuggestion', {
            providerId,
            kind: item.completion.kind,
            basenameHash: hash(resources_basename(model.uri)).toString(16),
            languageId: model.getLanguageId(),
            fileExtension: resources_extname(model.uri),
        });
    }
    getOverwriteInfo(item, toggleMode) {
        assertType(this.editor.hasModel());
        let replace = this.editor.getOption(108 /* 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._lineSuffix.value ? this._lineSuffix.value.delta(this.editor.getPosition()) : 0;
        return {
            overwriteBefore: overwriteBefore + columnDelta,
            overwriteAfter: overwriteAfter + suffixDelta
        };
    }
    _alertCompletionItem(item) {
        if (isNonEmptyArray(item.completion.additionalTextEdits)) {
            const msg = localize('aria.alert.snippet', "Accepting '{0}' made {1} additional edits", item.textLabel, item.completion.additionalTextEdits.length);
            aria_alert(msg);
        }
    }
    triggerSuggest(onlyFrom, auto, noFilter, noSelect) {
        if (this.editor.hasModel()) {
            this.model.trigger({ auto: auto !== null && auto !== void 0 ? auto : false, shy: false, noSelect: noSelect !== null && noSelect !== void 0 ? noSelect : false }, false, onlyFrom, undefined, noFilter);
            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 fallback = () => {
            if (positionNow.equals(this.editor.getPosition())) {
                this._commandService.executeCommand(arg.fallback);
            }
        };
        const makesTextEdit = (item) => {
            if (item.completion.insertTextRules & 4 /* CompletionItemInsertTextRule.InsertAsSnippet */ || item.completion.additionalTextEdits) {
                // snippet, other editor -> makes edit
                return true;
            }
            const position = this.editor.getPosition();
            const startColumn = item.editStart.column;
            const endColumn = position.column;
            if (endColumn - startColumn !== item.completion.insertText.length) {
                // unequal lengths -> makes edit
                return true;
            }
            const textNow = this.editor.getModel().getValueInRange({
                startLineNumber: position.lineNumber,
                startColumn,
                endLineNumber: position.lineNumber,
                endColumn
            });
            // unequal text -> makes edit
            return textNow !== item.completion.insertText;
        };
        Event.once(this.model.onDidTrigger)(_ => {
            // wait for trigger because only then the cancel-event is trustworthy
            const listener = [];
            Event.any(this.model.onDidTrigger, this.model.onDidCancel)(() => {
                // retrigger or cancel -> try to type default text
                dispose(listener);
                fallback();
            }, undefined, listener);
            this.model.onDidSuggest(({ completionModel }) => {
                dispose(listener);
                if (completionModel.items.length === 0) {
                    fallback();
                    return;
                }
                const index = this._memoryService.select(this.editor.getModel(), this.editor.getPosition(), completionModel.items);
                const item = completionModel.items[index];
                if (!makesTextEdit(item)) {
                    fallback();
                    return;
                }
                this.editor.pushUndoStop();
                this._insertSuggestion({ index, item, model: completionModel }, 4 /* InsertFlags.KeepAlternativeSuggestions */ | 1 /* InsertFlags.NoBeforeUndoStop */ | 2 /* InsertFlags.NoAfterUndoStop */);
            }, undefined, listener);
        });
        this.model.trigger({ auto: false, shy: true, noSelect: false });
        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 /* InsertFlags.KeepAlternativeSuggestions */;
        }
        if (alternativeOverwriteConfig) {
            flags |= 8 /* InsertFlags.AlternativeOverwriteConfig */;
        }
        this._insertSuggestion(item, flags);
    }
    acceptNextSuggestion() {
        this._alternatives.value.next();
    }
    acceptPrevSuggestion() {
        this._alternatives.value.prev();
    }
    cancelSuggestWidget() {
        this.model.cancel();
        this.model.clear();
        this.widget.value.hideWidget();
    }
    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) {
            // This method has no effect if the widget is not initialized yet.
            return;
        }
        this.widget.value.stopForceRenderingAbove();
    }
    registerSelector(selector) {
        return this._selectors.register(selector);
    }
};
SuggestController.ID = 'editor.contrib.suggestController';
SuggestController = suggestController_decorate([
    suggestController_param(1, ISuggestMemoryService),
    suggestController_param(2, ICommandService),
    suggestController_param(3, IContextKeyService),
    suggestController_param(4, IInstantiationService),
    suggestController_param(5, ILogService),
    suggestController_param(6, ITelemetryService)
], SuggestController);

class PriorityRegistry {
    constructor(prioritySelector) {
        this.prioritySelector = prioritySelector;
        this._items = new Array();
    }
    register(value) {
        if (this._items.indexOf(value) !== -1) {
            throw new Error('Value is already registered');
        }
        this._items.push(value);
        this._items.sort((s1, s2) => this.prioritySelector(s2) - this.prioritySelector(s1));
        return {
            dispose: () => {
                const idx = this._items.indexOf(value);
                if (idx >= 0) {
                    this._items.splice(idx, 1);
                }
            }
        };
    }
    get itemsOrderedByPriorityDesc() {
        return this._items;
    }
}
class TriggerSuggestAction extends EditorAction {
    constructor() {
        super({
            id: TriggerSuggestAction.id,
            label: localize('suggest.trigger.label', "Trigger Suggest"),
            alias: 'Trigger Suggest',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCompletionItemProvider),
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 10 /* KeyCode.Space */,
                secondary: [2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */],
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 10 /* KeyCode.Space */, secondary: [512 /* KeyMod.Alt */ | 9 /* KeyCode.Escape */, 2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */] },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor, args) {
        const controller = SuggestController.get(editor);
        if (!controller) {
            return;
        }
        let auto;
        let noSelect;
        if (args && typeof args === 'object') {
            if (args.auto === true) {
                auto = true;
            }
            if (args.noSelection === true) {
                noSelect = true;
            }
        }
        controller.triggerSuggest(undefined, auto, undefined, noSelect);
    }
}
TriggerSuggestAction.id = 'editor.action.triggerSuggest';
registerEditorContribution(SuggestController.ID, SuggestController);
registerEditorAction(TriggerSuggestAction);
const suggestController_weight = 100 /* KeybindingWeight.EditorContrib */ + 90;
const SuggestCommand = EditorCommand.bindToContribution(SuggestController.get);
registerEditorCommand(new SuggestCommand({
    id: 'acceptSelectedSuggestion',
    precondition: ContextKeyExpr.and(suggest_Context.Visible, suggest_Context.HasFocusedSuggestion),
    handler(x) {
        x.acceptSelectedSuggestion(true, false);
    },
    kbOpts: [{
            // normal tab
            primary: 2 /* KeyCode.Tab */,
            kbExpr: ContextKeyExpr.and(suggest_Context.Visible, EditorContextKeys.textInputFocus),
            weight: suggestController_weight,
        }, {
            // accept on enter has special rules
            primary: 3 /* KeyCode.Enter */,
            kbExpr: ContextKeyExpr.and(suggest_Context.Visible, EditorContextKeys.textInputFocus, suggest_Context.AcceptSuggestionsOnEnter, suggest_Context.MakesTextEdit),
            weight: suggestController_weight,
        }],
    menuOpts: [{
            menuId: suggestWidgetStatusbarMenu,
            title: localize('accept.insert', "Insert"),
            group: 'left',
            order: 1,
            when: suggest_Context.HasInsertAndReplaceRange.toNegated()
        }, {
            menuId: suggestWidgetStatusbarMenu,
            title: localize('accept.insert', "Insert"),
            group: 'left',
            order: 1,
            when: ContextKeyExpr.and(suggest_Context.HasInsertAndReplaceRange, suggest_Context.InsertMode.isEqualTo('insert'))
        }, {
            menuId: suggestWidgetStatusbarMenu,
            title: localize('accept.replace', "Replace"),
            group: 'left',
            order: 1,
            when: ContextKeyExpr.and(suggest_Context.HasInsertAndReplaceRange, suggest_Context.InsertMode.isEqualTo('replace'))
        }]
}));
registerEditorCommand(new SuggestCommand({
    id: 'acceptAlternativeSelectedSuggestion',
    precondition: ContextKeyExpr.and(suggest_Context.Visible, EditorContextKeys.textInputFocus, suggest_Context.HasFocusedSuggestion),
    kbOpts: {
        weight: suggestController_weight,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 1024 /* KeyMod.Shift */ | 3 /* KeyCode.Enter */,
        secondary: [1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */],
    },
    handler(x) {
        x.acceptSelectedSuggestion(false, true);
    },
    menuOpts: [{
            menuId: suggestWidgetStatusbarMenu,
            group: 'left',
            order: 2,
            when: ContextKeyExpr.and(suggest_Context.HasInsertAndReplaceRange, suggest_Context.InsertMode.isEqualTo('insert')),
            title: localize('accept.replace', "Replace")
        }, {
            menuId: suggestWidgetStatusbarMenu,
            group: 'left',
            order: 2,
            when: ContextKeyExpr.and(suggest_Context.HasInsertAndReplaceRange, suggest_Context.InsertMode.isEqualTo('replace')),
            title: localize('accept.insert', "Insert")
        }]
}));
// continue to support the old command
CommandsRegistry.registerCommandAlias('acceptSelectedSuggestionOnEnter', 'acceptSelectedSuggestion');
registerEditorCommand(new SuggestCommand({
    id: 'hideSuggestWidget',
    precondition: suggest_Context.Visible,
    handler: x => x.cancelSuggestWidget(),
    kbOpts: {
        weight: suggestController_weight,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 9 /* KeyCode.Escape */,
        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
    }
}));
registerEditorCommand(new SuggestCommand({
    id: 'selectNextSuggestion',
    precondition: ContextKeyExpr.and(suggest_Context.Visible, suggest_Context.MultipleSuggestions),
    handler: c => c.selectNextSuggestion(),
    kbOpts: {
        weight: suggestController_weight,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 18 /* KeyCode.DownArrow */,
        secondary: [2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */],
        mac: { primary: 18 /* KeyCode.DownArrow */, secondary: [2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */, 256 /* KeyMod.WinCtrl */ | 44 /* KeyCode.KeyN */] }
    }
}));
registerEditorCommand(new SuggestCommand({
    id: 'selectNextPageSuggestion',
    precondition: ContextKeyExpr.and(suggest_Context.Visible, suggest_Context.MultipleSuggestions),
    handler: c => c.selectNextPageSuggestion(),
    kbOpts: {
        weight: suggestController_weight,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 12 /* KeyCode.PageDown */,
        secondary: [2048 /* KeyMod.CtrlCmd */ | 12 /* KeyCode.PageDown */]
    }
}));
registerEditorCommand(new SuggestCommand({
    id: 'selectLastSuggestion',
    precondition: ContextKeyExpr.and(suggest_Context.Visible, suggest_Context.MultipleSuggestions),
    handler: c => c.selectLastSuggestion()
}));
registerEditorCommand(new SuggestCommand({
    id: 'selectPrevSuggestion',
    precondition: ContextKeyExpr.and(suggest_Context.Visible, suggest_Context.MultipleSuggestions),
    handler: c => c.selectPrevSuggestion(),
    kbOpts: {
        weight: suggestController_weight,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 16 /* KeyCode.UpArrow */,
        secondary: [2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */],
        mac: { primary: 16 /* KeyCode.UpArrow */, secondary: [2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */, 256 /* KeyMod.WinCtrl */ | 46 /* KeyCode.KeyP */] }
    }
}));
registerEditorCommand(new SuggestCommand({
    id: 'selectPrevPageSuggestion',
    precondition: ContextKeyExpr.and(suggest_Context.Visible, suggest_Context.MultipleSuggestions),
    handler: c => c.selectPrevPageSuggestion(),
    kbOpts: {
        weight: suggestController_weight,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 11 /* KeyCode.PageUp */,
        secondary: [2048 /* KeyMod.CtrlCmd */ | 11 /* KeyCode.PageUp */]
    }
}));
registerEditorCommand(new SuggestCommand({
    id: 'selectFirstSuggestion',
    precondition: ContextKeyExpr.and(suggest_Context.Visible, suggest_Context.MultipleSuggestions),
    handler: c => c.selectFirstSuggestion()
}));
registerEditorCommand(new SuggestCommand({
    id: 'toggleSuggestionDetails',
    precondition: suggest_Context.Visible,
    handler: x => x.toggleSuggestionDetails(),
    kbOpts: {
        weight: suggestController_weight,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 /* KeyMod.CtrlCmd */ | 10 /* KeyCode.Space */,
        secondary: [2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */],
        mac: { primary: 256 /* KeyMod.WinCtrl */ | 10 /* KeyCode.Space */, secondary: [2048 /* KeyMod.CtrlCmd */ | 39 /* KeyCode.KeyI */] }
    },
    menuOpts: [{
            menuId: suggestWidgetStatusbarMenu,
            group: 'right',
            order: 1,
            when: ContextKeyExpr.and(suggest_Context.DetailsVisible, suggest_Context.CanResolve),
            title: localize('detail.more', "show less")
        }, {
            menuId: suggestWidgetStatusbarMenu,
            group: 'right',
            order: 1,
            when: ContextKeyExpr.and(suggest_Context.DetailsVisible.toNegated(), suggest_Context.CanResolve),
            title: localize('detail.less', "show more")
        }]
}));
registerEditorCommand(new SuggestCommand({
    id: 'toggleExplainMode',
    precondition: suggest_Context.Visible,
    handler: x => x.toggleExplainMode(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */,
        primary: 2048 /* KeyMod.CtrlCmd */ | 85 /* KeyCode.Slash */,
    }
}));
registerEditorCommand(new SuggestCommand({
    id: 'toggleSuggestionFocus',
    precondition: suggest_Context.Visible,
    handler: x => x.toggleSuggestionFocus(),
    kbOpts: {
        weight: suggestController_weight,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 10 /* KeyCode.Space */,
        mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 10 /* KeyCode.Space */ }
    }
}));
//#region tab completions
registerEditorCommand(new SuggestCommand({
    id: 'insertBestCompletion',
    precondition: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.equals('config.editor.tabCompletion', 'on'), WordContextKey.AtEnd, suggest_Context.Visible.toNegated(), SuggestAlternatives.OtherSuggestions.toNegated(), SnippetController2.InSnippetMode.toNegated()),
    handler: (x, arg) => {
        x.triggerSuggestAndAcceptBest(isObject(arg) ? Object.assign({ fallback: 'tab' }, arg) : { fallback: 'tab' });
    },
    kbOpts: {
        weight: suggestController_weight,
        primary: 2 /* KeyCode.Tab */
    }
}));
registerEditorCommand(new SuggestCommand({
    id: 'insertNextSuggestion',
    precondition: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.equals('config.editor.tabCompletion', 'on'), SuggestAlternatives.OtherSuggestions, suggest_Context.Visible.toNegated(), SnippetController2.InSnippetMode.toNegated()),
    handler: x => x.acceptNextSuggestion(),
    kbOpts: {
        weight: suggestController_weight,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2 /* KeyCode.Tab */
    }
}));
registerEditorCommand(new SuggestCommand({
    id: 'insertPrevSuggestion',
    precondition: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.equals('config.editor.tabCompletion', 'on'), SuggestAlternatives.OtherSuggestions, suggest_Context.Visible.toNegated(), SnippetController2.InSnippetMode.toNegated()),
    handler: x => x.acceptPrevSuggestion(),
    kbOpts: {
        weight: suggestController_weight,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 1024 /* KeyMod.Shift */ | 2 /* KeyCode.Tab */
    }
}));
registerEditorAction(class extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.resetSuggestSize',
            label: localize('suggest.reset.label', "Reset Suggest Widget Size"),
            alias: 'Reset Suggest Widget Size',
            precondition: undefined
        });
    }
    run(_accessor, editor) {
        var _a;
        (_a = SuggestController.get(editor)) === null || _a === void 0 ? void 0 : _a.resetWidgetSize();
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/suggestWidgetInlineCompletionProvider.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/










class SuggestWidgetInlineCompletionProvider extends Disposable {
    constructor(editor, suggestControllerPreselector) {
        super();
        this.editor = editor;
        this.suggestControllerPreselector = suggestControllerPreselector;
        this.isSuggestWidgetVisible = false;
        this.isShiftKeyPressed = false;
        this._isActive = false;
        this._currentSuggestItemInfo = undefined;
        this.onDidChangeEmitter = new Emitter();
        this.onDidChange = this.onDidChangeEmitter.event;
        // This delay fixes a suggest widget issue when typing "." immediately restarts the suggestion session.
        this.setInactiveDelayed = this._register(new RunOnceScheduler(() => {
            if (!this.isSuggestWidgetVisible) {
                if (this._isActive) {
                    this._isActive = false;
                    this.onDidChangeEmitter.fire();
                }
            }
        }, 100));
        // See the command acceptAlternativeSelectedSuggestion that is bound to shift+tab
        this._register(editor.onKeyDown(e => {
            if (e.shiftKey && !this.isShiftKeyPressed) {
                this.isShiftKeyPressed = true;
                this.update(this._isActive);
            }
        }));
        this._register(editor.onKeyUp(e => {
            if (e.shiftKey && this.isShiftKeyPressed) {
                this.isShiftKeyPressed = false;
                this.update(this._isActive);
            }
        }));
        const suggestController = SuggestController.get(this.editor);
        if (suggestController) {
            this._register(suggestController.registerSelector({
                priority: 100,
                select: (model, pos, suggestItems) => {
                    const textModel = this.editor.getModel();
                    const normalizedItemToPreselect = minimizeInlineCompletion(textModel, this.suggestControllerPreselector());
                    if (!normalizedItemToPreselect) {
                        return -1;
                    }
                    const position = Position.lift(pos);
                    const candidates = suggestItems
                        .map((suggestItem, index) => {
                        const inlineSuggestItem = suggestionToSuggestItemInfo(suggestController, position, suggestItem, this.isShiftKeyPressed);
                        const normalizedSuggestItem = minimizeInlineCompletion(textModel, inlineSuggestItem === null || inlineSuggestItem === void 0 ? void 0 : inlineSuggestItem.normalizedInlineCompletion);
                        if (!normalizedSuggestItem) {
                            return undefined;
                        }
                        const valid = rangeStartsWith(normalizedItemToPreselect.range, normalizedSuggestItem.range) &&
                            normalizedItemToPreselect.insertText.startsWith(normalizedSuggestItem.insertText);
                        return { index, valid, prefixLength: normalizedSuggestItem.insertText.length, suggestItem };
                    })
                        .filter(item => item && item.valid);
                    const result = findMaxBy(candidates, compareBy(s => s.prefixLength, numberComparator));
                    return result ? result.index : -1;
                }
            }));
            let isBoundToSuggestWidget = false;
            const bindToSuggestWidget = () => {
                if (isBoundToSuggestWidget) {
                    return;
                }
                isBoundToSuggestWidget = true;
                this._register(suggestController.widget.value.onDidShow(() => {
                    this.isSuggestWidgetVisible = true;
                    this.update(true);
                }));
                this._register(suggestController.widget.value.onDidHide(() => {
                    this.isSuggestWidgetVisible = false;
                    this.setInactiveDelayed.schedule();
                    this.update(this._isActive);
                }));
                this._register(suggestController.widget.value.onDidFocus(() => {
                    this.isSuggestWidgetVisible = true;
                    this.update(true);
                }));
            };
            this._register(Event.once(suggestController.model.onDidTrigger)(e => {
                bindToSuggestWidget();
            }));
        }
        this.update(this._isActive);
    }
    /**
     * Returns undefined if the suggest widget is not active.
    */
    get state() {
        if (!this._isActive) {
            return undefined;
        }
        return { selectedItem: this._currentSuggestItemInfo };
    }
    update(newActive) {
        const newInlineCompletion = this.getSuggestItemInfo();
        let shouldFire = false;
        if (!suggestItemInfoEquals(this._currentSuggestItemInfo, newInlineCompletion)) {
            this._currentSuggestItemInfo = newInlineCompletion;
            shouldFire = true;
        }
        if (this._isActive !== newActive) {
            this._isActive = newActive;
            shouldFire = true;
        }
        if (shouldFire) {
            this.onDidChangeEmitter.fire();
        }
    }
    getSuggestItemInfo() {
        const suggestController = SuggestController.get(this.editor);
        if (!suggestController) {
            return undefined;
        }
        if (!this.isSuggestWidgetVisible) {
            return undefined;
        }
        const focusedItem = suggestController.widget.value.getFocusedItem();
        if (!focusedItem) {
            return undefined;
        }
        // TODO: item.isResolved
        return suggestionToSuggestItemInfo(suggestController, this.editor.getPosition(), focusedItem.item, this.isShiftKeyPressed);
    }
    stopForceRenderingAbove() {
        const suggestController = SuggestController.get(this.editor);
        if (suggestController) {
            suggestController.stopForceRenderingAbove();
        }
    }
    forceRenderingAbove() {
        const suggestController = SuggestController.get(this.editor);
        if (suggestController) {
            suggestController.forceRenderingAbove();
        }
    }
}
function rangeStartsWith(rangeToTest, prefix) {
    return (prefix.startLineNumber === rangeToTest.startLineNumber &&
        prefix.startColumn === rangeToTest.startColumn &&
        (prefix.endLineNumber < rangeToTest.endLineNumber ||
            (prefix.endLineNumber === rangeToTest.endLineNumber &&
                prefix.endColumn <= rangeToTest.endColumn)));
}
function suggestItemInfoEquals(a, b) {
    if (a === b) {
        return true;
    }
    if (!a || !b) {
        return false;
    }
    return a.completionItemKind === b.completionItemKind &&
        a.isSnippetText === b.isSnippetText &&
        normalizedInlineCompletionsEquals(a.normalizedInlineCompletion, b.normalizedInlineCompletion);
}
function suggestionToSuggestItemInfo(suggestController, position, item, toggleMode) {
    // additionalTextEdits might not be resolved here, this could be problematic.
    if (Array.isArray(item.completion.additionalTextEdits) && item.completion.additionalTextEdits.length > 0) {
        // cannot represent additional text edits. TODO: Now we can.
        return {
            completionItemKind: item.completion.kind,
            isSnippetText: false,
            normalizedInlineCompletion: {
                // Dummy element, so that space is reserved, but no text is shown
                range: Range.fromPositions(position, position),
                insertText: '',
                filterText: '',
                snippetInfo: undefined,
                additionalTextEdits: [],
            },
        };
    }
    let { insertText } = item.completion;
    let isSnippetText = false;
    if (item.completion.insertTextRules & 4 /* CompletionItemInsertTextRule.InsertAsSnippet */) {
        const snippet = new SnippetParser().parse(insertText);
        const model = suggestController.editor.getModel();
        // Ignore snippets that are too large.
        // Adjust whitespace is expensive for them.
        if (snippet.children.length > 100) {
            return undefined;
        }
        SnippetSession.adjustWhitespace(model, position, snippet, true, true);
        insertText = snippet.toString();
        isSnippetText = true;
    }
    const info = suggestController.getOverwriteInfo(item, toggleMode);
    return {
        isSnippetText,
        completionItemKind: item.completion.kind,
        normalizedInlineCompletion: {
            insertText: insertText,
            filterText: insertText,
            range: Range.fromPositions(position.delta(0, -info.overwriteBefore), position.delta(0, Math.max(info.overwriteAfter, 0))),
            snippetInfo: undefined,
            additionalTextEdits: [],
        }
    };
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/suggestWidgetPreviewModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var suggestWidgetPreviewModel_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var suggestWidgetPreviewModel_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var suggestWidgetPreviewModel_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};









let SuggestWidgetPreviewModel = class SuggestWidgetPreviewModel extends BaseGhostTextWidgetModel {
    constructor(editor, cache, languageFeaturesService) {
        super(editor);
        this.cache = cache;
        this.languageFeaturesService = languageFeaturesService;
        this.suggestionInlineCompletionSource = this._register(new SuggestWidgetInlineCompletionProvider(this.editor, 
        // Use the first cache item (if any) as preselection.
        () => { var _a, _b; return (_b = (_a = this.cache.value) === null || _a === void 0 ? void 0 : _a.completions[0]) === null || _b === void 0 ? void 0 : _b.toLiveInlineCompletion(); }));
        this.updateOperation = this._register(new MutableDisposable());
        this.updateCacheSoon = this._register(new RunOnceScheduler(() => this.updateCache(), 50));
        this.minReservedLineCount = 0;
        this._register(this.suggestionInlineCompletionSource.onDidChange(() => {
            if (!this.editor.hasModel()) {
                // onDidChange might be called when calling setModel on the editor, before we are disposed.
                return;
            }
            this.updateCacheSoon.schedule();
            const suggestWidgetState = this.suggestionInlineCompletionSource.state;
            if (!suggestWidgetState) {
                this.minReservedLineCount = 0;
            }
            const newGhostText = this.ghostText;
            if (newGhostText) {
                this.minReservedLineCount = Math.max(this.minReservedLineCount, sum(newGhostText.parts.map(p => p.lines.length - 1)));
            }
            if (this.minReservedLineCount >= 1) {
                this.suggestionInlineCompletionSource.forceRenderingAbove();
            }
            else {
                this.suggestionInlineCompletionSource.stopForceRenderingAbove();
            }
            this.onDidChangeEmitter.fire();
        }));
        this._register(this.cache.onDidChange(() => {
            this.onDidChangeEmitter.fire();
        }));
        this._register(this.editor.onDidChangeCursorPosition((e) => {
            this.minReservedLineCount = 0;
            this.updateCacheSoon.schedule();
            this.onDidChangeEmitter.fire();
        }));
        this._register(toDisposable(() => this.suggestionInlineCompletionSource.stopForceRenderingAbove()));
    }
    get isActive() {
        return this.suggestionInlineCompletionSource.state !== undefined;
    }
    isSuggestionPreviewEnabled() {
        const suggestOptions = this.editor.getOption(108 /* EditorOption.suggest */);
        return suggestOptions.preview;
    }
    updateCache() {
        return suggestWidgetPreviewModel_awaiter(this, void 0, void 0, function* () {
            const state = this.suggestionInlineCompletionSource.state;
            if (!state || !state.selectedItem) {
                return;
            }
            const info = {
                text: state.selectedItem.normalizedInlineCompletion.insertText,
                range: state.selectedItem.normalizedInlineCompletion.range,
                isSnippetText: state.selectedItem.isSnippetText,
                completionKind: state.selectedItem.completionItemKind,
            };
            const position = this.editor.getPosition();
            if (state.selectedItem.isSnippetText ||
                state.selectedItem.completionItemKind === 27 /* CompletionItemKind.Snippet */ ||
                state.selectedItem.completionItemKind === 20 /* CompletionItemKind.File */ ||
                state.selectedItem.completionItemKind === 23 /* CompletionItemKind.Folder */) {
                // Don't ask providers for these types of suggestions.
                this.cache.clear();
                return;
            }
            const promise = createCancelablePromise((token) => suggestWidgetPreviewModel_awaiter(this, void 0, void 0, function* () {
                let result;
                try {
                    result = yield provideInlineCompletions(this.languageFeaturesService.inlineCompletionsProvider, position, this.editor.getModel(), { triggerKind: InlineCompletionTriggerKind.Automatic, selectedSuggestionInfo: info }, token);
                }
                catch (e) {
                    onUnexpectedError(e);
                    return;
                }
                if (token.isCancellationRequested) {
                    result.dispose();
                    return;
                }
                this.cache.setValue(this.editor, result, InlineCompletionTriggerKind.Automatic);
                this.onDidChangeEmitter.fire();
            }));
            const operation = new UpdateOperation(promise, InlineCompletionTriggerKind.Automatic);
            this.updateOperation.value = operation;
            yield promise;
            if (this.updateOperation.value === operation) {
                this.updateOperation.clear();
            }
        });
    }
    get ghostText() {
        var _a, _b, _c;
        const isSuggestionPreviewEnabled = this.isSuggestionPreviewEnabled();
        const model = this.editor.getModel();
        const augmentedCompletion = minimizeInlineCompletion(model, (_b = (_a = this.cache.value) === null || _a === void 0 ? void 0 : _a.completions[0]) === null || _b === void 0 ? void 0 : _b.toLiveInlineCompletion());
        const suggestWidgetState = this.suggestionInlineCompletionSource.state;
        const suggestInlineCompletion = minimizeInlineCompletion(model, (_c = suggestWidgetState === null || suggestWidgetState === void 0 ? void 0 : suggestWidgetState.selectedItem) === null || _c === void 0 ? void 0 : _c.normalizedInlineCompletion);
        const isAugmentedCompletionValid = augmentedCompletion
            && suggestInlineCompletion
            && augmentedCompletion.insertText.startsWith(suggestInlineCompletion.insertText)
            && augmentedCompletion.range.equalsRange(suggestInlineCompletion.range);
        if (!isSuggestionPreviewEnabled && !isAugmentedCompletionValid) {
            return undefined;
        }
        // If the augmented completion is not valid and there is no suggest inline completion, we still show the augmented completion.
        const finalCompletion = isAugmentedCompletionValid ? augmentedCompletion : (suggestInlineCompletion || augmentedCompletion);
        const inlineCompletionPreviewLength = isAugmentedCompletionValid ? finalCompletion.insertText.length - suggestInlineCompletion.insertText.length : 0;
        const newGhostText = this.toGhostText(finalCompletion, inlineCompletionPreviewLength);
        return newGhostText;
    }
    toGhostText(completion, inlineCompletionPreviewLength) {
        const mode = this.editor.getOptions().get(108 /* EditorOption.suggest */).previewMode;
        return completion
            ? (inlineCompletionToGhostText(completion, this.editor.getModel(), mode, this.editor.getPosition(), inlineCompletionPreviewLength) ||
                // Show an invisible ghost text to reserve space
                new GhostText(completion.range.endLineNumber, [], this.minReservedLineCount))
            : undefined;
    }
};
SuggestWidgetPreviewModel = suggestWidgetPreviewModel_decorate([
    suggestWidgetPreviewModel_param(2, ILanguageFeaturesService)
], SuggestWidgetPreviewModel);

function sum(arr) {
    return arr.reduce((a, b) => a + b, 0);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/ghostTextModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var ghostTextModel_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var ghostTextModel_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var ghostTextModel_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};








class DelegatingModel extends Disposable {
    constructor() {
        super(...arguments);
        this.onDidChangeEmitter = new Emitter();
        this.onDidChange = this.onDidChangeEmitter.event;
        this.hasCachedGhostText = false;
        this.currentModelRef = this._register(new MutableDisposable());
    }
    get targetModel() {
        var _a;
        return (_a = this.currentModelRef.value) === null || _a === void 0 ? void 0 : _a.object;
    }
    setTargetModel(model) {
        var _a;
        if (((_a = this.currentModelRef.value) === null || _a === void 0 ? void 0 : _a.object) === model) {
            return;
        }
        this.currentModelRef.clear();
        this.currentModelRef.value = model ? utils_createDisposableRef(model, model.onDidChange(() => {
            this.hasCachedGhostText = false;
            this.onDidChangeEmitter.fire();
        })) : undefined;
        this.hasCachedGhostText = false;
        this.onDidChangeEmitter.fire();
    }
    get ghostText() {
        var _a, _b;
        if (!this.hasCachedGhostText) {
            this.cachedGhostText = (_b = (_a = this.currentModelRef.value) === null || _a === void 0 ? void 0 : _a.object) === null || _b === void 0 ? void 0 : _b.ghostText;
            this.hasCachedGhostText = true;
        }
        return this.cachedGhostText;
    }
    setExpanded(expanded) {
        var _a;
        (_a = this.targetModel) === null || _a === void 0 ? void 0 : _a.setExpanded(expanded);
    }
    get minReservedLineCount() {
        return this.targetModel ? this.targetModel.minReservedLineCount : 0;
    }
}
/**
 * A ghost text model that is both driven by inline completions and the suggest widget.
*/
let GhostTextModel = class GhostTextModel extends DelegatingModel {
    constructor(editor, instantiationService) {
        super();
        this.editor = editor;
        this.instantiationService = instantiationService;
        this.sharedCache = this._register(new SharedInlineCompletionCache());
        this.suggestWidgetAdapterModel = this._register(this.instantiationService.createInstance(SuggestWidgetPreviewModel, this.editor, this.sharedCache));
        this.inlineCompletionsModel = this._register(this.instantiationService.createInstance(InlineCompletionsModel, this.editor, this.sharedCache));
        this._register(this.suggestWidgetAdapterModel.onDidChange(() => {
            this.updateModel();
        }));
        this.updateModel();
    }
    get activeInlineCompletionsModel() {
        if (this.targetModel === this.inlineCompletionsModel) {
            return this.inlineCompletionsModel;
        }
        return undefined;
    }
    updateModel() {
        this.setTargetModel(this.suggestWidgetAdapterModel.isActive
            ? this.suggestWidgetAdapterModel
            : this.inlineCompletionsModel);
        this.inlineCompletionsModel.setActive(this.targetModel === this.inlineCompletionsModel);
    }
    shouldShowHoverAt(hoverRange) {
        var _a;
        const ghostText = (_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.ghostText;
        if (ghostText) {
            return ghostText.parts.some(p => hoverRange.containsPosition(new Position(ghostText.lineNumber, p.column)));
        }
        return false;
    }
    triggerInlineCompletion() {
        var _a;
        (_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.trigger(InlineCompletionTriggerKind.Explicit);
    }
    commitInlineCompletion() {
        var _a;
        (_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.commitCurrentSuggestion();
    }
    hideInlineCompletion() {
        var _a;
        (_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.hide();
    }
    showNextInlineCompletion() {
        var _a;
        (_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.showNext();
    }
    showPreviousInlineCompletion() {
        var _a;
        (_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.showPrevious();
    }
    hasMultipleInlineCompletions() {
        var _a;
        return ghostTextModel_awaiter(this, void 0, void 0, function* () {
            const result = yield ((_a = this.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.hasMultipleInlineCompletions());
            return result !== undefined ? result : false;
        });
    }
};
GhostTextModel = ghostTextModel_decorate([
    ghostTextModel_param(1, IInstantiationService)
], GhostTextModel);

class SharedInlineCompletionCache extends Disposable {
    constructor() {
        super(...arguments);
        this.onDidChangeEmitter = new Emitter();
        this.onDidChange = this.onDidChangeEmitter.event;
        this.cache = this._register(new MutableDisposable());
    }
    get value() {
        return this.cache.value;
    }
    setValue(editor, completionsSource, triggerKind) {
        this.cache.value = new SynchronizedInlineCompletionsCache(completionsSource, editor, () => this.onDidChangeEmitter.fire(), triggerKind);
    }
    clearAndLeak() {
        return this.cache.clearAndLeak();
    }
    clear() {
        this.cache.clear();
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/ghostText.css
var ghostText = __webpack_require__(98222);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/ghostText.css

      
      
      
      
      
      
      
      
      

var ghostText_options = {};

ghostText_options.styleTagTransform = (styleTagTransform_default());
ghostText_options.setAttributes = (setAttributesWithoutAttributes_default());

      ghostText_options.insert = insertBySelector_default().bind(null, "head");
    
ghostText_options.domAPI = (styleDomAPI_default());
ghostText_options.insertStyleElement = (insertStyleElement_default());

var ghostText_update = injectStylesIntoStyleTag_default()(ghostText/* default */.A, ghostText_options);




       /* harmony default export */ const browser_ghostText = (ghostText/* default */.A && ghostText/* default */.A.locals ? ghostText/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/ghostTextWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var ghostTextWidget_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var ghostTextWidget_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var ghostTextWidget_a;


















const ghostTextWidget_ttPolicy = (ghostTextWidget_a = window.trustedTypes) === null || ghostTextWidget_a === void 0 ? void 0 : ghostTextWidget_a.createPolicy('editorGhostText', { createHTML: value => value });
let GhostTextWidget = class GhostTextWidget extends Disposable {
    constructor(editor, model, instantiationService, languageService) {
        super();
        this.editor = editor;
        this.model = model;
        this.instantiationService = instantiationService;
        this.languageService = languageService;
        this.disposed = false;
        this.partsWidget = this._register(this.instantiationService.createInstance(DecorationsWidget, this.editor));
        this.additionalLinesWidget = this._register(new AdditionalLinesWidget(this.editor, this.languageService.languageIdCodec));
        this.viewMoreContentWidget = undefined;
        this.replacementDecoration = this._register(new DisposableDecorations(this.editor));
        this._register(this.editor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(29 /* EditorOption.disableMonospaceOptimizations */)
                || e.hasChanged(107 /* EditorOption.stopRenderingLineAfter */)
                || e.hasChanged(90 /* EditorOption.renderWhitespace */)
                || e.hasChanged(85 /* EditorOption.renderControlCharacters */)
                || e.hasChanged(47 /* EditorOption.fontLigatures */)
                || e.hasChanged(46 /* EditorOption.fontInfo */)
                || e.hasChanged(61 /* EditorOption.lineHeight */)) {
                this.update();
            }
        }));
        this._register(toDisposable(() => {
            var _a;
            this.disposed = true;
            this.update();
            (_a = this.viewMoreContentWidget) === null || _a === void 0 ? void 0 : _a.dispose();
            this.viewMoreContentWidget = undefined;
        }));
        this._register(model.onDidChange(() => {
            this.update();
        }));
        this.update();
    }
    shouldShowHoverAtViewZone(viewZoneId) {
        return (this.additionalLinesWidget.viewZoneId === viewZoneId);
    }
    update() {
        var _a;
        const ghostText = this.model.ghostText;
        if (!this.editor.hasModel() || !ghostText || this.disposed) {
            this.partsWidget.clear();
            this.additionalLinesWidget.clear();
            this.replacementDecoration.clear();
            return;
        }
        const inlineTexts = new Array();
        const additionalLines = new Array();
        function addToAdditionalLines(lines, className) {
            if (additionalLines.length > 0) {
                const lastLine = additionalLines[additionalLines.length - 1];
                if (className) {
                    lastLine.decorations.push(new LineDecoration(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 LineDecoration(1, line.length + 1, className, 0 /* InlineDecorationType.Regular */)] : []
                });
            }
        }
        if (ghostText instanceof GhostTextReplacement) {
            this.replacementDecoration.setDecorations([
                {
                    range: new Range(ghostText.lineNumber, ghostText.columnStart, ghostText.lineNumber, ghostText.columnStart + ghostText.length),
                    options: {
                        inlineClassName: 'inline-completion-text-to-replace',
                        description: 'GhostTextReplacement'
                    }
                },
            ]);
        }
        else {
            this.replacementDecoration.setDecorations([]);
        }
        const textBufferLine = this.editor.getModel().getLineContent(ghostText.lineNumber);
        let hiddenTextStartColumn = undefined;
        let lastIdx = 0;
        for (const part of ghostText.parts) {
            let lines = part.lines;
            if (hiddenTextStartColumn === undefined) {
                inlineTexts.push({
                    column: part.column,
                    text: lines[0],
                    preview: part.preview,
                });
                lines = lines.slice(1);
            }
            else {
                addToAdditionalLines([textBufferLine.substring(lastIdx, part.column - 1)], undefined);
            }
            if (lines.length > 0) {
                addToAdditionalLines(lines, 'ghost-text');
                if (hiddenTextStartColumn === undefined && part.column <= textBufferLine.length) {
                    hiddenTextStartColumn = part.column;
                }
            }
            lastIdx = part.column - 1;
        }
        if (hiddenTextStartColumn !== undefined) {
            addToAdditionalLines([textBufferLine.substring(lastIdx)], undefined);
        }
        this.partsWidget.setParts(ghostText.lineNumber, inlineTexts, hiddenTextStartColumn !== undefined ? { column: hiddenTextStartColumn, length: textBufferLine.length + 1 - hiddenTextStartColumn } : undefined);
        this.additionalLinesWidget.updateLines(ghostText.lineNumber, additionalLines, ghostText.additionalReservedLineCount);
        if (false) // removed by dead control flow
{}
        else {
            (_a = this.viewMoreContentWidget) === null || _a === void 0 ? void 0 : _a.dispose();
            this.viewMoreContentWidget = undefined;
        }
    }
    renderViewMoreLines(position, firstLineText, remainingLinesLength) {
        const fontInfo = this.editor.getOption(46 /* EditorOption.fontInfo */);
        const domNode = document.createElement('div');
        domNode.className = 'suggest-preview-additional-widget';
        applyFontInfo(domNode, fontInfo);
        const spacer = document.createElement('span');
        spacer.className = 'content-spacer';
        spacer.append(firstLineText);
        domNode.append(spacer);
        const newline = document.createElement('span');
        newline.className = 'content-newline suggest-preview-text';
        newline.append('⏎  ');
        domNode.append(newline);
        const disposableStore = new DisposableStore();
        const button = document.createElement('div');
        button.className = 'button suggest-preview-text';
        button.append(`+${remainingLinesLength} lines…`);
        disposableStore.add(addStandardDisposableListener(button, 'mousedown', (e) => {
            var _a;
            (_a = this.model) === null || _a === void 0 ? void 0 : _a.setExpanded(true);
            e.preventDefault();
            this.editor.focus();
        }));
        domNode.append(button);
        return new ViewMoreLinesContentWidget(this.editor, position, domNode, disposableStore);
    }
};
GhostTextWidget = ghostTextWidget_decorate([
    ghostTextWidget_param(2, IInstantiationService),
    ghostTextWidget_param(3, ILanguageService)
], GhostTextWidget);

class DisposableDecorations {
    constructor(editor) {
        this.editor = editor;
        this.decorationIds = [];
    }
    setDecorations(decorations) {
        // Using change decorations ensures that we update the id's before some event handler is called.
        this.editor.changeDecorations(accessor => {
            this.decorationIds = accessor.deltaDecorations(this.decorationIds, decorations);
        });
    }
    clear() {
        this.setDecorations([]);
    }
    dispose() {
        this.clear();
    }
}
class DecorationsWidget {
    constructor(editor) {
        this.editor = editor;
        this.decorationIds = [];
    }
    dispose() {
        this.clear();
    }
    clear() {
        // Using change decorations ensures that we update the id's before some event handler is called.
        this.editor.changeDecorations(accessor => {
            this.decorationIds = accessor.deltaDecorations(this.decorationIds, []);
        });
    }
    setParts(lineNumber, parts, hiddenText) {
        const textModel = this.editor.getModel();
        if (!textModel) {
            return;
        }
        const hiddenTextDecorations = new Array();
        if (hiddenText) {
            hiddenTextDecorations.push({
                range: Range.fromPositions(new Position(lineNumber, hiddenText.column), new Position(lineNumber, hiddenText.column + hiddenText.length)),
                options: {
                    inlineClassName: 'ghost-text-hidden',
                    description: 'ghost-text-hidden',
                }
            });
        }
        // Using change decorations ensures that we update the id's before some event handler is called.
        this.editor.changeDecorations(accessor => {
            this.decorationIds = accessor.deltaDecorations(this.decorationIds, parts.map(p => {
                return ({
                    range: Range.fromPositions(new Position(lineNumber, p.column)),
                    options: {
                        description: 'ghost-text',
                        after: { content: p.text, inlineClassName: p.preview ? 'ghost-text-decoration-preview' : 'ghost-text-decoration', cursorStops: InjectedTextCursorStops.Left },
                        showIfCollapsed: true,
                    }
                });
            }).concat(hiddenTextDecorations));
        });
    }
}
class AdditionalLinesWidget {
    constructor(editor, languageIdCodec) {
        this.editor = editor;
        this.languageIdCodec = languageIdCodec;
        this._viewZoneId = undefined;
    }
    get viewZoneId() { return this._viewZoneId; }
    dispose() {
        this.clear();
    }
    clear() {
        this.editor.changeViewZones((changeAccessor) => {
            if (this._viewZoneId) {
                changeAccessor.removeZone(this._viewZoneId);
                this._viewZoneId = undefined;
            }
        });
    }
    updateLines(lineNumber, additionalLines, minReservedLineCount) {
        const textModel = this.editor.getModel();
        if (!textModel) {
            return;
        }
        const { tabSize } = textModel.getOptions();
        this.editor.changeViewZones((changeAccessor) => {
            if (this._viewZoneId) {
                changeAccessor.removeZone(this._viewZoneId);
                this._viewZoneId = undefined;
            }
            const heightInLines = Math.max(additionalLines.length, minReservedLineCount);
            if (heightInLines > 0) {
                const domNode = document.createElement('div');
                renderLines(domNode, tabSize, additionalLines, this.editor.getOptions(), this.languageIdCodec);
                this._viewZoneId = changeAccessor.addZone({
                    afterLineNumber: lineNumber,
                    heightInLines: heightInLines,
                    domNode,
                    afterColumnAffinity: 1 /* PositionAffinity.Right */
                });
            }
        });
    }
}
function renderLines(domNode, tabSize, lines, opts, languageIdCodec) {
    const disableMonospaceOptimizations = opts.get(29 /* EditorOption.disableMonospaceOptimizations */);
    const stopRenderingLineAfter = opts.get(107 /* EditorOption.stopRenderingLineAfter */);
    // To avoid visual confusion, we don't want to render visible whitespace
    const renderWhitespace = 'none';
    const renderControlCharacters = opts.get(85 /* EditorOption.renderControlCharacters */);
    const fontLigatures = opts.get(47 /* EditorOption.fontLigatures */);
    const fontInfo = opts.get(46 /* EditorOption.fontInfo */);
    const lineHeight = opts.get(61 /* EditorOption.lineHeight */);
    const sb = createStringBuilder(10000);
    sb.appendASCIIString('<div class="suggest-preview-text">');
    for (let i = 0, len = lines.length; i < len; i++) {
        const lineData = lines[i];
        const line = lineData.content;
        sb.appendASCIIString('<div class="view-line');
        sb.appendASCIIString('" style="top:');
        sb.appendASCIIString(String(i * lineHeight));
        sb.appendASCIIString('px;width:1000000px;">');
        const isBasicASCII = strings_isBasicASCII(line);
        const containsRTL = strings_containsRTL(line);
        const lineTokens = LineTokens.createEmpty(line, languageIdCodec);
        renderViewLine(new RenderLineInput((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.appendASCIIString('</div>');
    }
    sb.appendASCIIString('</div>');
    applyFontInfo(domNode, fontInfo);
    const html = sb.build();
    const trustedhtml = ghostTextWidget_ttPolicy ? ghostTextWidget_ttPolicy.createHTML(html) : html;
    domNode.innerHTML = trustedhtml;
}
class ViewMoreLinesContentWidget extends Disposable {
    constructor(editor, position, domNode, disposableStore) {
        super();
        this.editor = editor;
        this.position = position;
        this.domNode = domNode;
        this.allowEditorOverflow = false;
        this.suppressMouseDown = false;
        this._register(disposableStore);
        this._register(toDisposable(() => {
            this.editor.removeContentWidget(this);
        }));
        this.editor.addContentWidget(this);
    }
    getId() {
        return 'editor.widget.viewMoreLinesWidget';
    }
    getDomNode() {
        return this.domNode;
    }
    getPosition() {
        return {
            position: this.position,
            preference: [0 /* ContentWidgetPositionPreference.EXACT */]
        };
    }
}
registerThemingParticipant((theme, collector) => {
    const foreground = theme.getColor(ghostTextForeground);
    if (foreground) {
        // `!important` ensures that other decorations don't cause a style conflict (#132017).
        collector.addRule(`.monaco-editor .ghost-text-decoration { color: ${foreground.toString()} !important; }`);
        collector.addRule(`.monaco-editor .ghost-text-decoration-preview { color: ${foreground.toString()} !important; }`);
        collector.addRule(`.monaco-editor .suggest-preview-text .ghost-text { color: ${foreground.toString()} !important; }`);
    }
    const background = theme.getColor(ghostTextBackground);
    if (background) {
        collector.addRule(`.monaco-editor .ghost-text-decoration { background-color: ${background.toString()}; }`);
        collector.addRule(`.monaco-editor .ghost-text-decoration-preview { background-color: ${background.toString()}; }`);
        collector.addRule(`.monaco-editor .suggest-preview-text .ghost-text { background-color: ${background.toString()}; }`);
    }
    const border = theme.getColor(ghostTextBorder);
    if (border) {
        collector.addRule(`.monaco-editor .suggest-preview-text .ghost-text { border: 1px solid ${border}; }`);
        collector.addRule(`.monaco-editor .ghost-text-decoration { border: 1px solid ${border}; }`);
        collector.addRule(`.monaco-editor .ghost-text-decoration-preview { border: 1px solid ${border}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/ghostTextController.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var ghostTextController_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var ghostTextController_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var ghostTextController_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};











let GhostTextController = class GhostTextController extends Disposable {
    constructor(editor, instantiationService) {
        super();
        this.editor = editor;
        this.instantiationService = instantiationService;
        this.triggeredExplicitly = false;
        this.activeController = this._register(new MutableDisposable());
        this.activeModelDidChangeEmitter = this._register(new Emitter());
        this._register(this.editor.onDidChangeModel(() => {
            this.updateModelController();
        }));
        this._register(this.editor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(108 /* EditorOption.suggest */)) {
                this.updateModelController();
            }
            if (e.hasChanged(57 /* EditorOption.inlineSuggest */)) {
                this.updateModelController();
            }
        }));
        this.updateModelController();
    }
    static get(editor) {
        return editor.getContribution(GhostTextController.ID);
    }
    get activeModel() {
        var _a;
        return (_a = this.activeController.value) === null || _a === void 0 ? void 0 : _a.model;
    }
    // Don't call this method when not necessary. It will recreate the activeController.
    updateModelController() {
        const suggestOptions = this.editor.getOption(108 /* EditorOption.suggest */);
        const inlineSuggestOptions = this.editor.getOption(57 /* EditorOption.inlineSuggest */);
        this.activeController.value = undefined;
        // ActiveGhostTextController is only created if one of those settings is set or if the inline completions are triggered explicitly.
        this.activeController.value =
            this.editor.hasModel() && (suggestOptions.preview || inlineSuggestOptions.enabled || this.triggeredExplicitly)
                ? this.instantiationService.createInstance(ActiveGhostTextController, this.editor)
                : undefined;
        this.activeModelDidChangeEmitter.fire();
    }
    shouldShowHoverAt(hoverRange) {
        var _a;
        return ((_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.shouldShowHoverAt(hoverRange)) || false;
    }
    shouldShowHoverAtViewZone(viewZoneId) {
        var _a, _b;
        return ((_b = (_a = this.activeController.value) === null || _a === void 0 ? void 0 : _a.widget) === null || _b === void 0 ? void 0 : _b.shouldShowHoverAtViewZone(viewZoneId)) || false;
    }
    trigger() {
        var _a;
        this.triggeredExplicitly = true;
        if (!this.activeController.value) {
            this.updateModelController();
        }
        (_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.triggerInlineCompletion();
    }
    commit() {
        var _a;
        (_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.commitInlineCompletion();
    }
    hide() {
        var _a;
        (_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.hideInlineCompletion();
    }
    showNextInlineCompletion() {
        var _a;
        (_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.showNextInlineCompletion();
    }
    showPreviousInlineCompletion() {
        var _a;
        (_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.showPreviousInlineCompletion();
    }
    hasMultipleInlineCompletions() {
        var _a;
        return ghostTextController_awaiter(this, void 0, void 0, function* () {
            const result = yield ((_a = this.activeModel) === null || _a === void 0 ? void 0 : _a.hasMultipleInlineCompletions());
            return result !== undefined ? result : false;
        });
    }
};
GhostTextController.inlineSuggestionVisible = new RawContextKey('inlineSuggestionVisible', false, localize('inlineSuggestionVisible', "Whether an inline suggestion is visible"));
GhostTextController.inlineSuggestionHasIndentation = new RawContextKey('inlineSuggestionHasIndentation', false, localize('inlineSuggestionHasIndentation', "Whether the inline suggestion starts with whitespace"));
GhostTextController.inlineSuggestionHasIndentationLessThanTabSize = new RawContextKey('inlineSuggestionHasIndentationLessThanTabSize', true, localize('inlineSuggestionHasIndentationLessThanTabSize', "Whether the inline suggestion starts with whitespace that is less than what would be inserted by tab"));
GhostTextController.ID = 'editor.contrib.ghostTextController';
GhostTextController = ghostTextController_decorate([
    ghostTextController_param(1, IInstantiationService)
], GhostTextController);

class GhostTextContextKeys {
    constructor(contextKeyService) {
        this.contextKeyService = contextKeyService;
        this.inlineCompletionVisible = GhostTextController.inlineSuggestionVisible.bindTo(this.contextKeyService);
        this.inlineCompletionSuggestsIndentation = GhostTextController.inlineSuggestionHasIndentation.bindTo(this.contextKeyService);
        this.inlineCompletionSuggestsIndentationLessThanTabSize = GhostTextController.inlineSuggestionHasIndentationLessThanTabSize.bindTo(this.contextKeyService);
    }
}
/**
 * The controller for a text editor with an initialized text model.
 * Must be disposed as soon as the model detaches from the editor.
*/
let ActiveGhostTextController = class ActiveGhostTextController extends Disposable {
    constructor(editor, instantiationService, contextKeyService) {
        super();
        this.editor = editor;
        this.instantiationService = instantiationService;
        this.contextKeyService = contextKeyService;
        this.contextKeys = new GhostTextContextKeys(this.contextKeyService);
        this.model = this._register(this.instantiationService.createInstance(GhostTextModel, this.editor));
        this.widget = this._register(this.instantiationService.createInstance(GhostTextWidget, this.editor, this.model));
        this._register(toDisposable(() => {
            this.contextKeys.inlineCompletionVisible.set(false);
            this.contextKeys.inlineCompletionSuggestsIndentation.set(false);
            this.contextKeys.inlineCompletionSuggestsIndentationLessThanTabSize.set(true);
        }));
        this._register(this.model.onDidChange(() => {
            this.updateContextKeys();
        }));
        this.updateContextKeys();
    }
    updateContextKeys() {
        var _a;
        this.contextKeys.inlineCompletionVisible.set(((_a = this.model.activeInlineCompletionsModel) === null || _a === void 0 ? void 0 : _a.ghostText) !== undefined);
        let startsWithIndentation = false;
        let startsWithIndentationLessThanTabSize = true;
        const ghostText = this.model.inlineCompletionsModel.ghostText;
        if (!!this.model.activeInlineCompletionsModel && ghostText && ghostText.parts.length > 0) {
            const { column, lines } = ghostText.parts[0];
            const firstLine = lines[0];
            const indentationEndColumn = this.editor.getModel().getLineIndentColumn(ghostText.lineNumber);
            const inIndentation = column <= indentationEndColumn;
            if (inIndentation) {
                let firstNonWsIdx = strings_firstNonWhitespaceIndex(firstLine);
                if (firstNonWsIdx === -1) {
                    firstNonWsIdx = firstLine.length - 1;
                }
                startsWithIndentation = firstNonWsIdx > 0;
                const tabSize = this.editor.getModel().getOptions().tabSize;
                const visibleColumnIndentation = CursorColumns.visibleColumnFromColumn(firstLine, firstNonWsIdx + 1, tabSize);
                startsWithIndentationLessThanTabSize = visibleColumnIndentation < tabSize;
            }
        }
        this.contextKeys.inlineCompletionSuggestsIndentation.set(startsWithIndentation);
        this.contextKeys.inlineCompletionSuggestsIndentationLessThanTabSize.set(startsWithIndentationLessThanTabSize);
    }
};
ActiveGhostTextController = ghostTextController_decorate([
    ghostTextController_param(1, IInstantiationService),
    ghostTextController_param(2, IContextKeyService)
], ActiveGhostTextController);

class ShowNextInlineSuggestionAction extends EditorAction {
    constructor() {
        super({
            id: ShowNextInlineSuggestionAction.ID,
            label: localize('action.inlineSuggest.showNext', "Show Next Inline Suggestion"),
            alias: 'Show Next Inline Suggestion',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, GhostTextController.inlineSuggestionVisible),
            kbOpts: {
                weight: 100,
                primary: 512 /* KeyMod.Alt */ | 89 /* KeyCode.BracketRight */,
            },
        });
    }
    run(accessor, editor) {
        return ghostTextController_awaiter(this, void 0, void 0, function* () {
            const controller = GhostTextController.get(editor);
            if (controller) {
                controller.showNextInlineCompletion();
                editor.focus();
            }
        });
    }
}
ShowNextInlineSuggestionAction.ID = 'editor.action.inlineSuggest.showNext';
class ShowPreviousInlineSuggestionAction extends EditorAction {
    constructor() {
        super({
            id: ShowPreviousInlineSuggestionAction.ID,
            label: localize('action.inlineSuggest.showPrevious', "Show Previous Inline Suggestion"),
            alias: 'Show Previous Inline Suggestion',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, GhostTextController.inlineSuggestionVisible),
            kbOpts: {
                weight: 100,
                primary: 512 /* KeyMod.Alt */ | 87 /* KeyCode.BracketLeft */,
            },
        });
    }
    run(accessor, editor) {
        return ghostTextController_awaiter(this, void 0, void 0, function* () {
            const controller = GhostTextController.get(editor);
            if (controller) {
                controller.showPreviousInlineCompletion();
                editor.focus();
            }
        });
    }
}
ShowPreviousInlineSuggestionAction.ID = 'editor.action.inlineSuggest.showPrevious';
class TriggerInlineSuggestionAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.inlineSuggest.trigger',
            label: localize('action.inlineSuggest.trigger', "Trigger Inline Suggestion"),
            alias: 'Trigger Inline Suggestion',
            precondition: EditorContextKeys.writable
        });
    }
    run(accessor, editor) {
        return ghostTextController_awaiter(this, void 0, void 0, function* () {
            const controller = GhostTextController.get(editor);
            if (controller) {
                controller.trigger();
            }
        });
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/ghostTextHoverParticipant.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var ghostTextHoverParticipant_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var ghostTextHoverParticipant_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};















class InlineCompletionsHover {
    constructor(owner, range, controller) {
        this.owner = owner;
        this.range = range;
        this.controller = controller;
    }
    isValidForHoverAnchor(anchor) {
        return (anchor.type === 1 /* HoverAnchorType.Range */
            && this.range.startColumn <= anchor.range.startColumn
            && this.range.endColumn >= anchor.range.endColumn);
    }
    hasMultipleSuggestions() {
        return this.controller.hasMultipleInlineCompletions();
    }
    get commands() {
        var _a, _b, _c;
        return ((_c = (_b = (_a = this.controller.activeModel) === null || _a === void 0 ? void 0 : _a.activeInlineCompletionsModel) === null || _b === void 0 ? void 0 : _b.completionSession.value) === null || _c === void 0 ? void 0 : _c.commands) || [];
    }
}
let InlineCompletionsHoverParticipant = class InlineCompletionsHoverParticipant {
    constructor(_editor, _commandService, _menuService, _contextKeyService, _languageService, _openerService, accessibilityService) {
        this._editor = _editor;
        this._commandService = _commandService;
        this._menuService = _menuService;
        this._contextKeyService = _contextKeyService;
        this._languageService = _languageService;
        this._openerService = _openerService;
        this.accessibilityService = accessibilityService;
        this.hoverOrdinal = 3;
    }
    suggestHoverAnchor(mouseEvent) {
        const controller = GhostTextController.get(this._editor);
        if (!controller) {
            return null;
        }
        const target = mouseEvent.target;
        if (target.type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */) {
            // handle the case where the mouse is over the view zone
            const viewZoneData = target.detail;
            if (controller.shouldShowHoverAtViewZone(viewZoneData.viewZoneId)) {
                return new HoverForeignElementAnchor(1000, this, Range.fromPositions(viewZoneData.positionBefore || viewZoneData.position, viewZoneData.positionBefore || viewZoneData.position));
            }
        }
        if (target.type === 7 /* MouseTargetType.CONTENT_EMPTY */) {
            // handle the case where the mouse is over the empty portion of a line following ghost text
            if (controller.shouldShowHoverAt(target.range)) {
                return new HoverForeignElementAnchor(1000, this, target.range);
            }
        }
        if (target.type === 6 /* MouseTargetType.CONTENT_TEXT */) {
            // handle the case where the mouse is directly over ghost text
            const mightBeForeignElement = target.detail.mightBeForeignElement;
            if (mightBeForeignElement && controller.shouldShowHoverAt(target.range)) {
                return new HoverForeignElementAnchor(1000, this, target.range);
            }
        }
        return null;
    }
    computeSync(anchor, lineDecorations) {
        const controller = GhostTextController.get(this._editor);
        if (controller && controller.shouldShowHoverAt(anchor.range)) {
            return [new InlineCompletionsHover(this, anchor.range, controller)];
        }
        return [];
    }
    renderHoverParts(context, hoverParts) {
        const disposableStore = new DisposableStore();
        const part = hoverParts[0];
        if (this.accessibilityService.isScreenReaderOptimized()) {
            this.renderScreenReaderText(context, part, disposableStore);
        }
        // TODO@hediet: deprecate MenuId.InlineCompletionsActions
        const menu = disposableStore.add(this._menuService.createMenu(MenuId.InlineCompletionsActions, this._contextKeyService));
        const previousAction = context.statusBar.addAction({
            label: localize('showNextInlineSuggestion', "Next"),
            commandId: ShowNextInlineSuggestionAction.ID,
            run: () => this._commandService.executeCommand(ShowNextInlineSuggestionAction.ID)
        });
        const nextAction = context.statusBar.addAction({
            label: localize('showPreviousInlineSuggestion', "Previous"),
            commandId: ShowPreviousInlineSuggestionAction.ID,
            run: () => this._commandService.executeCommand(ShowPreviousInlineSuggestionAction.ID)
        });
        context.statusBar.addAction({
            label: localize('acceptInlineSuggestion', "Accept"),
            commandId: inlineSuggestCommitId,
            run: () => this._commandService.executeCommand(inlineSuggestCommitId)
        });
        const actions = [previousAction, nextAction];
        for (const action of actions) {
            action.setEnabled(false);
        }
        part.hasMultipleSuggestions().then(hasMore => {
            for (const action of actions) {
                action.setEnabled(hasMore);
            }
        });
        for (const command of part.commands) {
            context.statusBar.addAction({
                label: command.title,
                commandId: command.id,
                run: () => this._commandService.executeCommand(command.id, ...(command.arguments || []))
            });
        }
        for (const [_, group] of menu.getActions()) {
            for (const action of group) {
                if (action instanceof MenuItemAction) {
                    context.statusBar.addAction({
                        label: action.label,
                        commandId: action.item.id,
                        run: () => this._commandService.executeCommand(action.item.id)
                    });
                }
            }
        }
        return disposableStore;
    }
    renderScreenReaderText(context, part, disposableStore) {
        var _a, _b;
        const $ = dom_$;
        const markdownHoverElement = $('div.hover-row.markdown-hover');
        const hoverContentsElement = append(markdownHoverElement, $('div.hover-contents'));
        const renderer = disposableStore.add(new MarkdownRenderer({ editor: this._editor }, this._languageService, this._openerService));
        const render = (code) => {
            disposableStore.add(renderer.onDidRenderAsync(() => {
                hoverContentsElement.className = 'hover-contents code-hover-contents';
                context.onContentsChanged();
            }));
            const inlineSuggestionAvailable = localize('inlineSuggestionFollows', "Suggestion:");
            const renderedContents = disposableStore.add(renderer.render(new MarkdownString().appendText(inlineSuggestionAvailable).appendCodeblock('text', code)));
            hoverContentsElement.replaceChildren(renderedContents.element);
        };
        const ghostText = (_b = (_a = part.controller.activeModel) === null || _a === void 0 ? void 0 : _a.inlineCompletionsModel) === null || _b === void 0 ? void 0 : _b.ghostText;
        if (ghostText) {
            const lineText = this._editor.getModel().getLineContent(ghostText.lineNumber);
            render(ghostText.renderForScreenReader(lineText));
        }
        context.fragment.appendChild(markdownHoverElement);
    }
};
InlineCompletionsHoverParticipant = ghostTextHoverParticipant_decorate([
    ghostTextHoverParticipant_param(1, ICommandService),
    ghostTextHoverParticipant_param(2, IMenuService),
    ghostTextHoverParticipant_param(3, IContextKeyService),
    ghostTextHoverParticipant_param(4, ILanguageService),
    ghostTextHoverParticipant_param(5, IOpenerService),
    ghostTextHoverParticipant_param(6, IAccessibilityService)
], InlineCompletionsHoverParticipant);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/ghostText.contribution.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/








registerEditorContribution(GhostTextController.ID, GhostTextController);
registerEditorAction(TriggerInlineSuggestionAction);
registerEditorAction(ShowNextInlineSuggestionAction);
registerEditorAction(ShowPreviousInlineSuggestionAction);
HoverParticipantRegistry.register(InlineCompletionsHoverParticipant);
const GhostTextCommand = EditorCommand.bindToContribution(GhostTextController.get);
const commitInlineSuggestionAction = new GhostTextCommand({
    id: inlineSuggestCommitId,
    precondition: GhostTextController.inlineSuggestionVisible,
    handler(x) {
        x.commit();
        x.editor.focus();
    }
});
registerEditorCommand(commitInlineSuggestionAction);
KeybindingsRegistry.registerKeybindingRule({
    primary: 2 /* KeyCode.Tab */,
    weight: 200,
    id: commitInlineSuggestionAction.id,
    when: ContextKeyExpr.and(commitInlineSuggestionAction.precondition, EditorContextKeys.tabMovesFocus.toNegated(), GhostTextController.inlineSuggestionHasIndentationLessThanTabSize),
});
registerEditorCommand(new GhostTextCommand({
    id: 'editor.action.inlineSuggest.hide',
    precondition: GhostTextController.inlineSuggestionVisible,
    kbOpts: {
        weight: 100,
        primary: 9 /* KeyCode.Escape */,
    },
    handler(x) {
        x.hide();
    }
}));

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/inspectTokens/inspectTokens.css
var inspectTokens = __webpack_require__(95586);
;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/inspectTokens/inspectTokens.css

      
      
      
      
      
      
      
      
      

var inspectTokens_options = {};

inspectTokens_options.styleTagTransform = (styleTagTransform_default());
inspectTokens_options.setAttributes = (setAttributesWithoutAttributes_default());

      inspectTokens_options.insert = insertBySelector_default().bind(null, "head");
    
inspectTokens_options.domAPI = (styleDomAPI_default());
inspectTokens_options.insertStyleElement = (insertStyleElement_default());

var inspectTokens_update = injectStylesIntoStyleTag_default()(inspectTokens/* default */.A, inspectTokens_options);




       /* harmony default export */ const inspectTokens_inspectTokens = (inspectTokens/* default */.A && inspectTokens/* default */.A.locals ? inspectTokens/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/common/standaloneTheme.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const IStandaloneThemeService = createDecorator('themeService');

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/inspectTokens/inspectTokens.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var inspectTokens_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var inspectTokens_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};














let InspectTokensController = class InspectTokensController extends Disposable {
    constructor(editor, standaloneColorService, languageService) {
        super();
        this._editor = editor;
        this._languageService = languageService;
        this._widget = null;
        this._register(this._editor.onDidChangeModel((e) => this.stop()));
        this._register(this._editor.onDidChangeModelLanguage((e) => this.stop()));
        this._register(languages_TokenizationRegistry.onDidChange((e) => this.stop()));
        this._register(this._editor.onKeyUp((e) => e.keyCode === 9 /* KeyCode.Escape */ && this.stop()));
    }
    static get(editor) {
        return editor.getContribution(InspectTokensController.ID);
    }
    dispose() {
        this.stop();
        super.dispose();
    }
    launch() {
        if (this._widget) {
            return;
        }
        if (!this._editor.hasModel()) {
            return;
        }
        this._widget = new InspectTokensWidget(this._editor, this._languageService);
    }
    stop() {
        if (this._widget) {
            this._widget.dispose();
            this._widget = null;
        }
    }
};
InspectTokensController.ID = 'editor.contrib.inspectTokens';
InspectTokensController = inspectTokens_decorate([
    inspectTokens_param(1, IStandaloneThemeService),
    inspectTokens_param(2, ILanguageService)
], InspectTokensController);
class InspectTokens extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.inspectTokens',
            label: InspectTokensNLS.inspectTokensAction,
            alias: 'Developer: Inspect Tokens',
            precondition: undefined
        });
    }
    run(accessor, editor) {
        const controller = InspectTokensController.get(editor);
        if (controller) {
            controller.launch();
        }
    }
}
function renderTokenText(tokenText) {
    let result = '';
    for (let charIndex = 0, len = tokenText.length; charIndex < len; charIndex++) {
        const charCode = tokenText.charCodeAt(charIndex);
        switch (charCode) {
            case 9 /* CharCode.Tab */:
                result += '\u2192'; // &rarr;
                break;
            case 32 /* CharCode.Space */:
                result += '\u00B7'; // &middot;
                break;
            default:
                result += String.fromCharCode(charCode);
        }
    }
    return result;
}
function getSafeTokenizationSupport(languageIdCodec, languageId) {
    const tokenizationSupport = languages_TokenizationRegistry.get(languageId);
    if (tokenizationSupport) {
        return tokenizationSupport;
    }
    const encodedLanguageId = languageIdCodec.encodeLanguageId(languageId);
    return {
        getInitialState: () => NullState,
        tokenize: (line, hasEOL, state) => nullTokenize(languageId, state),
        tokenizeEncoded: (line, hasEOL, state) => nullTokenizeEncoded(encodedLanguageId, state)
    };
}
class InspectTokensWidget extends Disposable {
    constructor(editor, languageService) {
        super();
        // Editor.IContentWidget.allowEditorOverflow
        this.allowEditorOverflow = true;
        this._editor = editor;
        this._languageService = languageService;
        this._model = this._editor.getModel();
        this._domNode = document.createElement('div');
        this._domNode.className = 'tokens-inspect-widget';
        this._tokenizationSupport = getSafeTokenizationSupport(this._languageService.languageIdCodec, this._model.getLanguageId());
        this._compute(this._editor.getPosition());
        this._register(this._editor.onDidChangeCursorPosition((e) => this._compute(this._editor.getPosition())));
        this._editor.addContentWidget(this);
    }
    dispose() {
        this._editor.removeContentWidget(this);
        super.dispose();
    }
    getId() {
        return InspectTokensWidget._ID;
    }
    _compute(position) {
        const data = this._getTokensAtLine(position.lineNumber);
        let token1Index = 0;
        for (let i = data.tokens1.length - 1; i >= 0; i--) {
            const t = data.tokens1[i];
            if (position.column - 1 >= t.offset) {
                token1Index = i;
                break;
            }
        }
        let token2Index = 0;
        for (let i = (data.tokens2.length >>> 1); i >= 0; i--) {
            if (position.column - 1 >= data.tokens2[(i << 1)]) {
                token2Index = i;
                break;
            }
        }
        const lineContent = this._model.getLineContent(position.lineNumber);
        let tokenText = '';
        if (token1Index < data.tokens1.length) {
            const tokenStartIndex = data.tokens1[token1Index].offset;
            const tokenEndIndex = token1Index + 1 < data.tokens1.length ? data.tokens1[token1Index + 1].offset : lineContent.length;
            tokenText = lineContent.substring(tokenStartIndex, tokenEndIndex);
        }
        dom_reset(this._domNode, dom_$('h2.tm-token', undefined, renderTokenText(tokenText), dom_$('span.tm-token-length', undefined, `${tokenText.length} ${tokenText.length === 1 ? 'char' : 'chars'}`)));
        append(this._domNode, dom_$('hr.tokens-inspect-separator', { 'style': 'clear:both' }));
        const metadata = (token2Index << 1) + 1 < data.tokens2.length ? this._decodeMetadata(data.tokens2[(token2Index << 1) + 1]) : null;
        append(this._domNode, dom_$('table.tm-metadata-table', undefined, dom_$('tbody', undefined, dom_$('tr', undefined, dom_$('td.tm-metadata-key', undefined, 'language'), dom_$('td.tm-metadata-value', undefined, `${metadata ? metadata.languageId : '-?-'}`)), dom_$('tr', undefined, dom_$('td.tm-metadata-key', undefined, 'token type'), dom_$('td.tm-metadata-value', undefined, `${metadata ? this._tokenTypeToString(metadata.tokenType) : '-?-'}`)), dom_$('tr', undefined, dom_$('td.tm-metadata-key', undefined, 'font style'), dom_$('td.tm-metadata-value', undefined, `${metadata ? this._fontStyleToString(metadata.fontStyle) : '-?-'}`)), dom_$('tr', undefined, dom_$('td.tm-metadata-key', undefined, 'foreground'), dom_$('td.tm-metadata-value', undefined, `${metadata ? Color.Format.CSS.formatHex(metadata.foreground) : '-?-'}`)), dom_$('tr', undefined, dom_$('td.tm-metadata-key', undefined, 'background'), dom_$('td.tm-metadata-value', undefined, `${metadata ? Color.Format.CSS.formatHex(metadata.background) : '-?-'}`)))));
        append(this._domNode, dom_$('hr.tokens-inspect-separator'));
        if (token1Index < data.tokens1.length) {
            append(this._domNode, dom_$('span.tm-token-type', undefined, data.tokens1[token1Index].type));
        }
        this._editor.layoutContentWidget(this);
    }
    _decodeMetadata(metadata) {
        const colorMap = languages_TokenizationRegistry.getColorMap();
        const languageId = TokenMetadata.getLanguageId(metadata);
        const tokenType = TokenMetadata.getTokenType(metadata);
        const fontStyle = TokenMetadata.getFontStyle(metadata);
        const foreground = TokenMetadata.getForeground(metadata);
        const background = TokenMetadata.getBackground(metadata);
        return {
            languageId: this._languageService.languageIdCodec.decodeLanguageId(languageId),
            tokenType: tokenType,
            fontStyle: fontStyle,
            foreground: colorMap[foreground],
            background: colorMap[background]
        };
    }
    _tokenTypeToString(tokenType) {
        switch (tokenType) {
            case 0 /* StandardTokenType.Other */: return 'Other';
            case 1 /* StandardTokenType.Comment */: return 'Comment';
            case 2 /* StandardTokenType.String */: return 'String';
            case 3 /* StandardTokenType.RegEx */: return 'RegEx';
            default: return '??';
        }
    }
    _fontStyleToString(fontStyle) {
        let r = '';
        if (fontStyle & 1 /* FontStyle.Italic */) {
            r += 'italic ';
        }
        if (fontStyle & 2 /* FontStyle.Bold */) {
            r += 'bold ';
        }
        if (fontStyle & 4 /* FontStyle.Underline */) {
            r += 'underline ';
        }
        if (fontStyle & 8 /* FontStyle.Strikethrough */) {
            r += 'strikethrough ';
        }
        if (r.length === 0) {
            r = '---';
        }
        return r;
    }
    _getTokensAtLine(lineNumber) {
        const stateBeforeLine = this._getStateBeforeLine(lineNumber);
        const tokenizationResult1 = this._tokenizationSupport.tokenize(this._model.getLineContent(lineNumber), true, stateBeforeLine);
        const tokenizationResult2 = this._tokenizationSupport.tokenizeEncoded(this._model.getLineContent(lineNumber), true, stateBeforeLine);
        return {
            startState: stateBeforeLine,
            tokens1: tokenizationResult1.tokens,
            tokens2: tokenizationResult2.tokens,
            endState: tokenizationResult1.endState
        };
    }
    _getStateBeforeLine(lineNumber) {
        let state = this._tokenizationSupport.getInitialState();
        for (let i = 1; i < lineNumber; i++) {
            const tokenizationResult = this._tokenizationSupport.tokenize(this._model.getLineContent(i), true, state);
            state = tokenizationResult.endState;
        }
        return state;
    }
    getDomNode() {
        return this._domNode;
    }
    getPosition() {
        return {
            position: this._editor.getPosition(),
            preference: [2 /* ContentWidgetPositionPreference.BELOW */, 1 /* ContentWidgetPositionPreference.ABOVE */]
        };
    }
}
InspectTokensWidget._ID = 'editor.contrib.inspectTokensWidget';
registerEditorContribution(InspectTokensController.ID, InspectTokensController);
registerEditorAction(InspectTokens);
registerThemingParticipant((theme, collector) => {
    const border = theme.getColor(editorHoverBorder);
    if (border) {
        const borderWidth = isHighContrast(theme.type) ? 2 : 1;
        collector.addRule(`.monaco-editor .tokens-inspect-widget { border: ${borderWidth}px solid ${border}; }`);
        collector.addRule(`.monaco-editor .tokens-inspect-widget .tokens-inspect-separator { background-color: ${border}; }`);
    }
    const background = theme.getColor(editorHoverBackground);
    if (background) {
        collector.addRule(`.monaco-editor .tokens-inspect-widget { background-color: ${background}; }`);
    }
    const foreground = theme.getColor(editorHoverForeground);
    if (foreground) {
        collector.addRule(`.monaco-editor .tokens-inspect-widget { color: ${foreground}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/lineSelection/browser/lineSelection.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class ExpandLineSelectionAction extends EditorAction {
    constructor() {
        super({
            id: 'expandLineSelection',
            label: localize('expandLineSelection', "Expand Line Selection"),
            alias: 'Expand Line Selection',
            precondition: undefined,
            kbOpts: {
                weight: 0 /* KeybindingWeight.EditorCore */,
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 42 /* KeyCode.KeyL */
            },
        });
    }
    run(_accessor, editor, args) {
        args = args || {};
        if (!editor.hasModel()) {
            return;
        }
        const viewModel = editor._getViewModel();
        viewModel.model.pushStackElement();
        viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, CursorMoveCommands.expandLineSelection(viewModel, viewModel.getCursorStates()));
        viewModel.revealPrimaryCursor(args.source, true);
    }
}
registerEditorAction(ExpandLineSelectionAction);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/commands/trimTrailingWhitespaceCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class TrimTrailingWhitespaceCommand {
    constructor(selection, cursors) {
        this._selection = selection;
        this._cursors = cursors;
        this._selectionId = null;
    }
    getEditOperations(model, builder) {
        const ops = trimTrailingWhitespace(model, this._cursors);
        for (let i = 0, len = ops.length; i < len; i++) {
            const op = ops[i];
            builder.addEditOperation(op.range, op.text);
        }
        this._selectionId = builder.trackSelection(this._selection);
    }
    computeCursorState(model, helper) {
        return helper.getTrackedSelection(this._selectionId);
    }
}
/**
 * Generate commands for trimming trailing whitespace on a model and ignore lines on which cursors are sitting.
 */
function trimTrailingWhitespace(model, cursors) {
    // Sort cursors ascending
    cursors.sort((a, b) => {
        if (a.lineNumber === b.lineNumber) {
            return a.column - b.column;
        }
        return a.lineNumber - b.lineNumber;
    });
    // Reduce multiple cursors on the same line and only keep the last one on the line
    for (let i = cursors.length - 2; i >= 0; i--) {
        if (cursors[i].lineNumber === cursors[i + 1].lineNumber) {
            // Remove cursor at `i`
            cursors.splice(i, 1);
        }
    }
    const r = [];
    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) {
                // The cursor is at the end of the line => no edits for sure on this line
                continue;
            }
        }
        if (lineContent.length === 0) {
            continue;
        }
        const lastNonWhitespaceIndex = strings_lastNonWhitespaceIndex(lineContent);
        let fromColumn = 0;
        if (lastNonWhitespaceIndex === -1) {
            // Entire line is whitespace
            fromColumn = 1;
        }
        else if (lastNonWhitespaceIndex !== lineContent.length - 1) {
            // There is trailing whitespace
            fromColumn = lastNonWhitespaceIndex + 2;
        }
        else {
            // There is no trailing whitespace
            continue;
        }
        fromColumn = Math.max(minEditColumn, fromColumn);
        r[rLen++] = EditOperation.delete(new Range(lineNumber, fromColumn, lineNumber, maxLineColumn));
    }
    return r;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/linesOperations/browser/copyLinesCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class CopyLinesCommand {
    constructor(selection, isCopyingDown, noop) {
        this._selection = selection;
        this._isCopyingDown = isCopyingDown;
        this._noop = noop || false;
        this._selectionDirection = 0 /* SelectionDirection.LTR */;
        this._selectionId = null;
        this._startLineNumberDelta = 0;
        this._endLineNumberDelta = 0;
    }
    getEditOperations(model, builder) {
        let s = this._selection;
        this._startLineNumberDelta = 0;
        this._endLineNumberDelta = 0;
        if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
            this._endLineNumberDelta = 1;
            s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
        }
        const sourceLines = [];
        for (let i = s.startLineNumber; i <= s.endLineNumber; i++) {
            sourceLines.push(model.getLineContent(i));
        }
        const sourceText = sourceLines.join('\n');
        if (sourceText === '') {
            // Duplicating empty line
            if (this._isCopyingDown) {
                this._startLineNumberDelta++;
                this._endLineNumberDelta++;
            }
        }
        if (this._noop) {
            builder.addEditOperation(new Range(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber + 1, 1), s.endLineNumber === model.getLineCount() ? '' : '\n');
        }
        else {
            if (!this._isCopyingDown) {
                builder.addEditOperation(new Range(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), '\n' + sourceText);
            }
            else {
                builder.addEditOperation(new Range(s.startLineNumber, 1, s.startLineNumber, 1), sourceText + '\n');
            }
        }
        this._selectionId = builder.trackSelection(s);
        this._selectionDirection = this._selection.getDirection();
    }
    computeCursorState(model, helper) {
        let result = helper.getTrackedSelection(this._selectionId);
        if (this._startLineNumberDelta !== 0 || this._endLineNumberDelta !== 0) {
            let startLineNumber = result.startLineNumber;
            let startColumn = result.startColumn;
            let endLineNumber = result.endLineNumber;
            let endColumn = result.endColumn;
            if (this._startLineNumberDelta !== 0) {
                startLineNumber = startLineNumber + this._startLineNumberDelta;
                startColumn = 1;
            }
            if (this._endLineNumberDelta !== 0) {
                endLineNumber = endLineNumber + this._endLineNumberDelta;
                endColumn = 1;
            }
            result = Selection.createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, this._selectionDirection);
        }
        return result;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/linesOperations/browser/moveLinesCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var moveLinesCommand_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var moveLinesCommand_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};









let MoveLinesCommand = class MoveLinesCommand {
    constructor(selection, isMovingDown, autoIndent, _languageConfigurationService) {
        this._languageConfigurationService = _languageConfigurationService;
        this._selection = selection;
        this._isMovingDown = isMovingDown;
        this._autoIndent = autoIndent;
        this._selectionId = null;
        this._moveEndLineSelectionShrink = false;
    }
    getEditOperations(model, builder) {
        const modelLineCount = model.getLineCount();
        if (this._isMovingDown && this._selection.endLineNumber === modelLineCount) {
            this._selectionId = builder.trackSelection(this._selection);
            return;
        }
        if (!this._isMovingDown && this._selection.startLineNumber === 1) {
            this._selectionId = builder.trackSelection(this._selection);
            return;
        }
        this._moveEndPositionDown = false;
        let s = this._selection;
        if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
            this._moveEndPositionDown = true;
            s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
        }
        const { tabSize, indentSize, insertSpaces } = model.getOptions();
        const indentConverter = this.buildIndentConverter(tabSize, indentSize, insertSpaces);
        const virtualModel = {
            tokenization: {
                getLineTokens: (lineNumber) => {
                    return model.tokenization.getLineTokens(lineNumber);
                },
                getLanguageId: () => {
                    return model.getLanguageId();
                },
                getLanguageIdAtPosition: (lineNumber, column) => {
                    return model.getLanguageIdAtPosition(lineNumber, column);
                },
            },
            getLineContent: null,
        };
        if (s.startLineNumber === s.endLineNumber && model.getLineMaxColumn(s.startLineNumber) === 1) {
            // Current line is empty
            const lineNumber = s.startLineNumber;
            const otherLineNumber = (this._isMovingDown ? lineNumber + 1 : lineNumber - 1);
            if (model.getLineMaxColumn(otherLineNumber) === 1) {
                // Other line number is empty too, so no editing is needed
                // Add a no-op to force running by the model
                builder.addEditOperation(new Range(1, 1, 1, 1), null);
            }
            else {
                // Type content from other line number on line number
                builder.addEditOperation(new Range(lineNumber, 1, lineNumber, 1), model.getLineContent(otherLineNumber));
                // Remove content from other line number
                builder.addEditOperation(new Range(otherLineNumber, 1, otherLineNumber, model.getLineMaxColumn(otherLineNumber)), null);
            }
            // Track selection at the other line number
            s = new Selection(otherLineNumber, 1, otherLineNumber, 1);
        }
        else {
            let movingLineNumber;
            let movingLineText;
            if (this._isMovingDown) {
                movingLineNumber = s.endLineNumber + 1;
                movingLineText = model.getLineContent(movingLineNumber);
                // Delete line that needs to be moved
                builder.addEditOperation(new Range(movingLineNumber - 1, model.getLineMaxColumn(movingLineNumber - 1), movingLineNumber, model.getLineMaxColumn(movingLineNumber)), null);
                let insertingText = movingLineText;
                if (this.shouldAutoIndent(model, s)) {
                    const movingLineMatchResult = this.matchEnterRule(model, indentConverter, tabSize, movingLineNumber, s.startLineNumber - 1);
                    // if s.startLineNumber - 1 matches onEnter rule, we still honor that.
                    if (movingLineMatchResult !== null) {
                        const oldIndentation = getLeadingWhitespace(model.getLineContent(movingLineNumber));
                        const newSpaceCnt = movingLineMatchResult + getSpaceCnt(oldIndentation, tabSize);
                        const newIndentation = generateIndent(newSpaceCnt, tabSize, insertSpaces);
                        insertingText = newIndentation + this.trimLeft(movingLineText);
                    }
                    else {
                        // no enter rule matches, let's check indentatin rules then.
                        virtualModel.getLineContent = (lineNumber) => {
                            if (lineNumber === s.startLineNumber) {
                                return model.getLineContent(movingLineNumber);
                            }
                            else {
                                return model.getLineContent(lineNumber);
                            }
                        };
                        const indentOfMovingLine = getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber, indentConverter, this._languageConfigurationService);
                        if (indentOfMovingLine !== null) {
                            const oldIndentation = getLeadingWhitespace(model.getLineContent(movingLineNumber));
                            const newSpaceCnt = getSpaceCnt(indentOfMovingLine, tabSize);
                            const oldSpaceCnt = getSpaceCnt(oldIndentation, tabSize);
                            if (newSpaceCnt !== oldSpaceCnt) {
                                const newIndentation = generateIndent(newSpaceCnt, tabSize, insertSpaces);
                                insertingText = newIndentation + this.trimLeft(movingLineText);
                            }
                        }
                    }
                    // add edit operations for moving line first to make sure it's executed after we make indentation change
                    // to s.startLineNumber
                    builder.addEditOperation(new Range(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + '\n');
                    const ret = this.matchEnterRuleMovingDown(model, indentConverter, tabSize, s.startLineNumber, movingLineNumber, insertingText);
                    // check if the line being moved before matches onEnter rules, if so let's adjust the indentation by onEnter rules.
                    if (ret !== null) {
                        if (ret !== 0) {
                            this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret);
                        }
                    }
                    else {
                        // it doesn't match onEnter rules, let's check indentation rules then.
                        virtualModel.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 = getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber + 1, indentConverter, this._languageConfigurationService);
                        if (newIndentatOfMovingBlock !== null) {
                            const oldIndentation = getLeadingWhitespace(model.getLineContent(s.startLineNumber));
                            const newSpaceCnt = getSpaceCnt(newIndentatOfMovingBlock, tabSize);
                            const oldSpaceCnt = getSpaceCnt(oldIndentation, tabSize);
                            if (newSpaceCnt !== oldSpaceCnt) {
                                const spaceCntOffset = newSpaceCnt - oldSpaceCnt;
                                this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
                            }
                        }
                    }
                }
                else {
                    // Insert line that needs to be moved before
                    builder.addEditOperation(new Range(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + '\n');
                }
            }
            else {
                movingLineNumber = s.startLineNumber - 1;
                movingLineText = model.getLineContent(movingLineNumber);
                // Delete line that needs to be moved
                builder.addEditOperation(new Range(movingLineNumber, 1, movingLineNumber + 1, 1), null);
                // Insert line that needs to be moved after
                builder.addEditOperation(new Range(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), '\n' + movingLineText);
                if (this.shouldAutoIndent(model, s)) {
                    virtualModel.getLineContent = (lineNumber) => {
                        if (lineNumber === movingLineNumber) {
                            return model.getLineContent(s.startLineNumber);
                        }
                        else {
                            return model.getLineContent(lineNumber);
                        }
                    };
                    const ret = this.matchEnterRule(model, indentConverter, tabSize, s.startLineNumber, s.startLineNumber - 2);
                    // check if s.startLineNumber - 2 matches onEnter rules, if so adjust the moving block by onEnter rules.
                    if (ret !== null) {
                        if (ret !== 0) {
                            this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret);
                        }
                    }
                    else {
                        // it doesn't match any onEnter rule, let's check indentation rules then.
                        const indentOfFirstLine = getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(s.startLineNumber, 1), movingLineNumber, indentConverter, this._languageConfigurationService);
                        if (indentOfFirstLine !== null) {
                            // adjust the indentation of the moving block
                            const oldIndent = getLeadingWhitespace(model.getLineContent(s.startLineNumber));
                            const newSpaceCnt = getSpaceCnt(indentOfFirstLine, tabSize);
                            const oldSpaceCnt = getSpaceCnt(oldIndent, tabSize);
                            if (newSpaceCnt !== oldSpaceCnt) {
                                const spaceCntOffset = newSpaceCnt - oldSpaceCnt;
                                this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
                            }
                        }
                    }
                }
            }
        }
        this._selectionId = builder.trackSelection(s);
    }
    buildIndentConverter(tabSize, indentSize, insertSpaces) {
        return {
            shiftIndent: (indentation) => {
                return ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
            },
            unshiftIndent: (indentation) => {
                return ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
            }
        };
    }
    parseEnterResult(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.trimLeft(movingLineText).indexOf(this.trimLeft(enterPrefix)) >= 0) {
                const oldIndentation = getLeadingWhitespace(model.getLineContent(line));
                let newIndentation = getLeadingWhitespace(enterPrefix);
                const indentMetadataOfMovelingLine = getIndentMetadata(model, line, this._languageConfigurationService);
                if (indentMetadataOfMovelingLine !== null && indentMetadataOfMovelingLine & 2 /* IndentConsts.DECREASE_MASK */) {
                    newIndentation = indentConverter.unshiftIndent(newIndentation);
                }
                const newSpaceCnt = getSpaceCnt(newIndentation, tabSize);
                const oldSpaceCnt = getSpaceCnt(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
     */
    matchEnterRuleMovingDown(model, indentConverter, tabSize, line, futureAboveLineNumber, futureAboveLineText) {
        if (strings_lastNonWhitespaceIndex(futureAboveLineText) >= 0) {
            // break
            const maxColumn = model.getLineMaxColumn(futureAboveLineNumber);
            const enter = getEnterAction(this._autoIndent, model, new Range(futureAboveLineNumber, maxColumn, futureAboveLineNumber, maxColumn), this._languageConfigurationService);
            return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
        }
        else {
            // go upwards, starting from `line - 1`
            let validPrecedingLine = line - 1;
            while (validPrecedingLine >= 1) {
                const lineContent = model.getLineContent(validPrecedingLine);
                const nonWhitespaceIdx = strings_lastNonWhitespaceIndex(lineContent);
                if (nonWhitespaceIdx >= 0) {
                    break;
                }
                validPrecedingLine--;
            }
            if (validPrecedingLine < 1 || line > model.getLineCount()) {
                return null;
            }
            const maxColumn = model.getLineMaxColumn(validPrecedingLine);
            const enter = getEnterAction(this._autoIndent, model, new Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn), this._languageConfigurationService);
            return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
        }
    }
    matchEnterRule(model, indentConverter, tabSize, line, oneLineAbove, previousLineText) {
        let validPrecedingLine = oneLineAbove;
        while (validPrecedingLine >= 1) {
            // ship empty lines as empty lines just inherit indentation
            let lineContent;
            if (validPrecedingLine === oneLineAbove && previousLineText !== undefined) {
                lineContent = previousLineText;
            }
            else {
                lineContent = model.getLineContent(validPrecedingLine);
            }
            const nonWhitespaceIdx = strings_lastNonWhitespaceIndex(lineContent);
            if (nonWhitespaceIdx >= 0) {
                break;
            }
            validPrecedingLine--;
        }
        if (validPrecedingLine < 1 || line > model.getLineCount()) {
            return null;
        }
        const maxColumn = model.getLineMaxColumn(validPrecedingLine);
        const enter = getEnterAction(this._autoIndent, model, new Range(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn), this._languageConfigurationService);
        return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
    }
    trimLeft(str) {
        return str.replace(/^\s+/, '');
    }
    shouldAutoIndent(model, selection) {
        if (this._autoIndent < 4 /* EditorAutoIndentStrategy.Full */) {
            return false;
        }
        // if it's not easy to tokenize, we stop auto indent.
        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._languageConfigurationService.getLanguageConfiguration(languageAtSelectionStart).indentRulesSupport === null) {
            return false;
        }
        return true;
    }
    getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, offset) {
        for (let i = s.startLineNumber; i <= s.endLineNumber; i++) {
            const lineContent = model.getLineContent(i);
            const originalIndent = getLeadingWhitespace(lineContent);
            const originalSpacesCnt = getSpaceCnt(originalIndent, tabSize);
            const newSpacesCnt = originalSpacesCnt + offset;
            const newIndent = generateIndent(newSpacesCnt, tabSize, insertSpaces);
            if (newIndent !== originalIndent) {
                builder.addEditOperation(new Range(i, 1, i, originalIndent.length + 1), newIndent);
                if (i === s.endLineNumber && s.endColumn <= originalIndent.length + 1 && newIndent === '') {
                    // as users select part of the original indent white spaces
                    // when we adjust the indentation of endLine, we should adjust the cursor position as well.
                    this._moveEndLineSelectionShrink = true;
                }
            }
        }
    }
    computeCursorState(model, helper) {
        let result = helper.getTrackedSelection(this._selectionId);
        if (this._moveEndPositionDown) {
            result = result.setEndPosition(result.endLineNumber + 1, 1);
        }
        if (this._moveEndLineSelectionShrink && result.startLineNumber < result.endLineNumber) {
            result = result.setEndPosition(result.endLineNumber, 2);
        }
        return result;
    }
};
MoveLinesCommand = moveLinesCommand_decorate([
    moveLinesCommand_param(3, ILanguageConfigurationService)
], MoveLinesCommand);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/linesOperations/browser/sortLinesCommand.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class SortLinesCommand {
    constructor(selection, descending) {
        this.selection = selection;
        this.descending = descending;
        this.selectionId = null;
    }
    static getCollator() {
        if (!SortLinesCommand._COLLATOR) {
            SortLinesCommand._COLLATOR = new Intl.Collator();
        }
        return SortLinesCommand._COLLATOR;
    }
    getEditOperations(model, builder) {
        const op = sortLines(model, this.selection, this.descending);
        if (op) {
            builder.addEditOperation(op.range, op.text);
        }
        this.selectionId = builder.trackSelection(this.selection);
    }
    computeCursorState(model, helper) {
        return helper.getTrackedSelection(this.selectionId);
    }
    static canRun(model, selection, descending) {
        if (model === null) {
            return false;
        }
        const data = getSortData(model, selection, descending);
        if (!data) {
            return false;
        }
        for (let i = 0, len = data.before.length; i < len; i++) {
            if (data.before[i] !== data.after[i]) {
                return true;
            }
        }
        return false;
    }
}
SortLinesCommand._COLLATOR = null;
function getSortData(model, selection, descending) {
    const startLineNumber = selection.startLineNumber;
    let endLineNumber = selection.endLineNumber;
    if (selection.endColumn === 1) {
        endLineNumber--;
    }
    // Nothing to sort if user didn't select anything.
    if (startLineNumber >= endLineNumber) {
        return null;
    }
    const linesToSort = [];
    // Get the contents of the selection to be sorted.
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        linesToSort.push(model.getLineContent(lineNumber));
    }
    let sorted = linesToSort.slice(0);
    sorted.sort(SortLinesCommand.getCollator().compare);
    // If descending, reverse the order.
    if (descending === true) {
        sorted = sorted.reverse();
    }
    return {
        startLineNumber: startLineNumber,
        endLineNumber: endLineNumber,
        before: linesToSort,
        after: sorted
    };
}
/**
 * Generate commands for sorting lines on a model.
 */
function sortLines(model, selection, descending) {
    const data = getSortData(model, selection, descending);
    if (!data) {
        return null;
    }
    return EditOperation.replace(new Range(data.startLineNumber, 1, data.endLineNumber, model.getLineMaxColumn(data.endLineNumber)), data.after.join('\n'));
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/linesOperations/browser/linesOperations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

















// copy lines
class AbstractCopyLinesAction extends EditorAction {
    constructor(down, opts) {
        super(opts);
        this.down = down;
    }
    run(_accessor, editor) {
        if (!editor.hasModel()) {
            return;
        }
        const selections = editor.getSelections().map((selection, index) => ({ selection, index, ignore: false }));
        selections.sort((a, b) => Range.compareRangesUsingStarts(a.selection, b.selection));
        // Remove selections that would result in copying the same line
        let prev = selections[0];
        for (let i = 1; i < selections.length; i++) {
            const curr = selections[i];
            if (prev.selection.endLineNumber === curr.selection.startLineNumber) {
                // these two selections would copy the same line
                if (prev.index < curr.index) {
                    // prev wins
                    curr.ignore = true;
                }
                else {
                    // curr wins
                    prev.ignore = true;
                    prev = curr;
                }
            }
        }
        const commands = [];
        for (const selection of selections) {
            commands.push(new CopyLinesCommand(selection.selection, this.down, selection.ignore));
        }
        editor.pushUndoStop();
        editor.executeCommands(this.id, commands);
        editor.pushUndoStop();
    }
}
class CopyLinesUpAction extends AbstractCopyLinesAction {
    constructor() {
        super(false, {
            id: 'editor.action.copyLinesUpAction',
            label: localize('lines.copyUp', "Copy Line Up"),
            alias: 'Copy Line Up',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */,
                linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '2_line',
                title: localize({ key: 'miCopyLinesUp', comment: ['&& denotes a mnemonic'] }, "&&Copy Line Up"),
                order: 1
            }
        });
    }
}
class CopyLinesDownAction extends AbstractCopyLinesAction {
    constructor() {
        super(true, {
            id: 'editor.action.copyLinesDownAction',
            label: localize('lines.copyDown', "Copy Line Down"),
            alias: 'Copy Line Down',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */,
                linux: { primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '2_line',
                title: localize({ key: 'miCopyLinesDown', comment: ['&& denotes a mnemonic'] }, "Co&&py Line Down"),
                order: 2
            }
        });
    }
}
class DuplicateSelectionAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.duplicateSelection',
            label: localize('duplicateSelection', "Duplicate Selection"),
            alias: 'Duplicate Selection',
            precondition: EditorContextKeys.writable,
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '2_line',
                title: localize({ key: 'miDuplicateSelection', comment: ['&& denotes a mnemonic'] }, "&&Duplicate Selection"),
                order: 5
            }
        });
    }
    run(accessor, editor, args) {
        if (!editor.hasModel()) {
            return;
        }
        const commands = [];
        const selections = editor.getSelections();
        const model = editor.getModel();
        for (const selection of selections) {
            if (selection.isEmpty()) {
                commands.push(new CopyLinesCommand(selection, true));
            }
            else {
                const insertSelection = new Selection(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn);
                commands.push(new ReplaceCommandThatSelectsText(insertSelection, model.getValueInRange(selection)));
            }
        }
        editor.pushUndoStop();
        editor.executeCommands(this.id, commands);
        editor.pushUndoStop();
    }
}
// move lines
class AbstractMoveLinesAction extends EditorAction {
    constructor(down, opts) {
        super(opts);
        this.down = down;
    }
    run(accessor, editor) {
        const languageConfigurationService = accessor.get(ILanguageConfigurationService);
        const commands = [];
        const selections = editor.getSelections() || [];
        const autoIndent = editor.getOption(9 /* EditorOption.autoIndent */);
        for (const selection of selections) {
            commands.push(new MoveLinesCommand(selection, this.down, autoIndent, languageConfigurationService));
        }
        editor.pushUndoStop();
        editor.executeCommands(this.id, commands);
        editor.pushUndoStop();
    }
}
class MoveLinesUpAction extends AbstractMoveLinesAction {
    constructor() {
        super(false, {
            id: 'editor.action.moveLinesUpAction',
            label: localize('lines.moveUp', "Move Line Up"),
            alias: 'Move Line Up',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */,
                linux: { primary: 512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '2_line',
                title: localize({ key: 'miMoveLinesUp', comment: ['&& denotes a mnemonic'] }, "Mo&&ve Line Up"),
                order: 3
            }
        });
    }
}
class MoveLinesDownAction extends AbstractMoveLinesAction {
    constructor() {
        super(true, {
            id: 'editor.action.moveLinesDownAction',
            label: localize('lines.moveDown', "Move Line Down"),
            alias: 'Move Line Down',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */,
                linux: { primary: 512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '2_line',
                title: localize({ key: 'miMoveLinesDown', comment: ['&& denotes a mnemonic'] }, "Move &&Line Down"),
                order: 4
            }
        });
    }
}
class AbstractSortLinesAction extends EditorAction {
    constructor(descending, opts) {
        super(opts);
        this.descending = descending;
    }
    run(_accessor, editor) {
        const selections = editor.getSelections() || [];
        for (const selection of selections) {
            if (!SortLinesCommand.canRun(editor.getModel(), selection, this.descending)) {
                return;
            }
        }
        const commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            commands[i] = new SortLinesCommand(selections[i], this.descending);
        }
        editor.pushUndoStop();
        editor.executeCommands(this.id, commands);
        editor.pushUndoStop();
    }
}
class SortLinesAscendingAction extends AbstractSortLinesAction {
    constructor() {
        super(false, {
            id: 'editor.action.sortLinesAscending',
            label: localize('lines.sortAscending', "Sort Lines Ascending"),
            alias: 'Sort Lines Ascending',
            precondition: EditorContextKeys.writable
        });
    }
}
class SortLinesDescendingAction extends AbstractSortLinesAction {
    constructor() {
        super(true, {
            id: 'editor.action.sortLinesDescending',
            label: localize('lines.sortDescending', "Sort Lines Descending"),
            alias: 'Sort Lines Descending',
            precondition: EditorContextKeys.writable
        });
    }
}
class DeleteDuplicateLinesAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.removeDuplicateLines',
            label: localize('lines.deleteDuplicates', "Delete Duplicate Lines"),
            alias: '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;
        for (const selection of editor.getSelections()) {
            const uniqueLines = new Set();
            const lines = [];
            for (let i = selection.startLineNumber; i <= selection.endLineNumber; i++) {
                const line = model.getLineContent(i);
                if (uniqueLines.has(line)) {
                    continue;
                }
                lines.push(line);
                uniqueLines.add(line);
            }
            const selectionToReplace = new Selection(selection.startLineNumber, 1, selection.endLineNumber, model.getLineMaxColumn(selection.endLineNumber));
            const adjustedSelectionStart = selection.startLineNumber - linesDeleted;
            const finalSelection = new Selection(adjustedSelectionStart, 1, adjustedSelectionStart + lines.length - 1, lines[lines.length - 1].length);
            edits.push(EditOperation.replace(selectionToReplace, lines.join('\n')));
            endCursorState.push(finalSelection);
            linesDeleted += (selection.endLineNumber - selection.startLineNumber + 1) - lines.length;
        }
        editor.pushUndoStop();
        editor.executeEdits(this.id, edits, endCursorState);
        editor.pushUndoStop();
    }
}
class TrimTrailingWhitespaceAction extends EditorAction {
    constructor() {
        super({
            id: TrimTrailingWhitespaceAction.ID,
            label: localize('lines.trimTrailingWhitespace', "Trim Trailing Whitespace"),
            alias: 'Trim Trailing Whitespace',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 54 /* KeyCode.KeyX */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor, args) {
        let cursors = [];
        if (args.reason === 'auto-save') {
            // See https://github.com/editorconfig/editorconfig-vscode/issues/47
            // It is very convenient for the editor config extension to invoke this action.
            // So, if we get a reason:'auto-save' passed in, let's preserve cursor positions.
            cursors = (editor.getSelections() || []).map(s => new Position(s.positionLineNumber, s.positionColumn));
        }
        const selection = editor.getSelection();
        if (selection === null) {
            return;
        }
        const command = new TrimTrailingWhitespaceCommand(selection, cursors);
        editor.pushUndoStop();
        editor.executeCommands(this.id, [command]);
        editor.pushUndoStop();
    }
}
TrimTrailingWhitespaceAction.ID = 'editor.action.trimTrailingWhitespace';
class DeleteLinesAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.deleteLines',
            label: localize('lines.delete', "Delete Line"),
            alias: 'Delete Line',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 41 /* KeyCode.KeyK */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor) {
        if (!editor.hasModel()) {
            return;
        }
        const ops = this._getLinesToRemove(editor);
        const model = editor.getModel();
        if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
            // Model is empty
            return;
        }
        let linesDeleted = 0;
        const edits = [];
        const cursorState = [];
        for (let i = 0, len = ops.length; i < len; i++) {
            const op = ops[i];
            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(EditOperation.replace(new Selection(startLineNumber, startColumn, endLineNumber, endColumn), ''));
            cursorState.push(new Selection(startLineNumber - linesDeleted, op.positionColumn, startLineNumber - linesDeleted, op.positionColumn));
            linesDeleted += (op.endLineNumber - op.startLineNumber + 1);
        }
        editor.pushUndoStop();
        editor.executeEdits(this.id, edits, cursorState);
        editor.pushUndoStop();
    }
    _getLinesToRemove(editor) {
        // Construct delete operations
        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: endLineNumber,
                positionColumn: s.positionColumn
            };
        });
        // Sort delete operations
        operations.sort((a, b) => {
            if (a.startLineNumber === b.startLineNumber) {
                return a.endLineNumber - b.endLineNumber;
            }
            return a.startLineNumber - b.startLineNumber;
        });
        // Merge delete operations which are adjacent or overlapping
        const mergedOperations = [];
        let previousOperation = operations[0];
        for (let i = 1; i < operations.length; i++) {
            if (previousOperation.endLineNumber + 1 >= operations[i].startLineNumber) {
                // Merge current operations into the previous one
                previousOperation.endLineNumber = operations[i].endLineNumber;
            }
            else {
                // Push previous operation
                mergedOperations.push(previousOperation);
                previousOperation = operations[i];
            }
        }
        // Push the last operation
        mergedOperations.push(previousOperation);
        return mergedOperations;
    }
}
class IndentLinesAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.indentLines',
            label: localize('lines.indent', "Indent Line"),
            alias: 'Indent Line',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 89 /* KeyCode.BracketRight */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor) {
        const viewModel = editor._getViewModel();
        if (!viewModel) {
            return;
        }
        editor.pushUndoStop();
        editor.executeCommands(this.id, TypeOperations.indent(viewModel.cursorConfig, editor.getModel(), editor.getSelections()));
        editor.pushUndoStop();
    }
}
class OutdentLinesAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.outdentLines',
            label: localize('lines.outdent', "Outdent Line"),
            alias: 'Outdent Line',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 87 /* KeyCode.BracketLeft */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor) {
        CoreEditingCommands.Outdent.runEditorCommand(_accessor, editor, null);
    }
}
class InsertLineBeforeAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.insertLineBefore',
            label: localize('lines.insertBefore', "Insert Line Above"),
            alias: 'Insert Line Above',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 3 /* KeyCode.Enter */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor) {
        const viewModel = editor._getViewModel();
        if (!viewModel) {
            return;
        }
        editor.pushUndoStop();
        editor.executeCommands(this.id, TypeOperations.lineInsertBefore(viewModel.cursorConfig, editor.getModel(), editor.getSelections()));
    }
}
class InsertLineAfterAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.insertLineAfter',
            label: localize('lines.insertAfter', "Insert Line Below"),
            alias: 'Insert Line Below',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 3 /* KeyCode.Enter */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(_accessor, editor) {
        const viewModel = editor._getViewModel();
        if (!viewModel) {
            return;
        }
        editor.pushUndoStop();
        editor.executeCommands(this.id, TypeOperations.lineInsertAfter(viewModel.cursorConfig, editor.getModel(), editor.getSelections()));
    }
}
class AbstractDeleteAllToBoundaryAction extends EditorAction {
    run(_accessor, editor) {
        if (!editor.hasModel()) {
            return;
        }
        const primaryCursor = editor.getSelection();
        const rangesToDelete = this._getRangesToDelete(editor);
        // merge overlapping selections
        const effectiveRanges = [];
        for (let i = 0, count = rangesToDelete.length - 1; i < count; i++) {
            const range = rangesToDelete[i];
            const nextRange = rangesToDelete[i + 1];
            if (Range.intersectRanges(range, nextRange) === null) {
                effectiveRanges.push(range);
            }
            else {
                rangesToDelete[i + 1] = Range.plusRange(range, nextRange);
            }
        }
        effectiveRanges.push(rangesToDelete[rangesToDelete.length - 1]);
        const endCursorState = this._getEndCursorState(primaryCursor, effectiveRanges);
        const edits = effectiveRanges.map(range => {
            return EditOperation.replace(range, '');
        });
        editor.pushUndoStop();
        editor.executeEdits(this.id, edits, endCursorState);
        editor.pushUndoStop();
    }
}
class DeleteAllLeftAction extends AbstractDeleteAllToBoundaryAction {
    constructor() {
        super({
            id: 'deleteAllLeft',
            label: localize('lines.deleteAllLeft', "Delete All Left"),
            alias: 'Delete All Left',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 2048 /* KeyMod.CtrlCmd */ | 1 /* KeyCode.Backspace */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    _getEndCursorState(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 Selection(newStartLine, range.startColumn, newStartLine, range.startColumn);
            }
            else {
                endCursor = new Selection(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;
    }
    _getRangesToDelete(editor) {
        const selections = editor.getSelections();
        if (selections === null) {
            return [];
        }
        let rangesToDelete = selections;
        const model = editor.getModel();
        if (model === null) {
            return [];
        }
        rangesToDelete.sort(Range.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.getLineContent(deleteFromLine).length + 1;
                    return new Range(deleteFromLine, deleteFromColumn, selection.startLineNumber, 1);
                }
                else {
                    return new Range(selection.startLineNumber, 1, selection.startLineNumber, selection.startColumn);
                }
            }
            else {
                return new Range(selection.startLineNumber, 1, selection.endLineNumber, selection.endColumn);
            }
        });
        return rangesToDelete;
    }
}
class DeleteAllRightAction extends AbstractDeleteAllToBoundaryAction {
    constructor() {
        super({
            id: 'deleteAllRight',
            label: localize('lines.deleteAllRight', "Delete All Right"),
            alias: 'Delete All Right',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 41 /* KeyCode.KeyK */, secondary: [2048 /* KeyMod.CtrlCmd */ | 20 /* KeyCode.Delete */] },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    _getEndCursorState(primaryCursor, rangesToDelete) {
        let endPrimaryCursor = null;
        const endCursorState = [];
        for (let i = 0, len = rangesToDelete.length, offset = 0; i < len; i++) {
            const range = rangesToDelete[i];
            const endCursor = new Selection(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;
    }
    _getRangesToDelete(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 Range(sel.startLineNumber, sel.startColumn, sel.startLineNumber + 1, 1);
                }
                else {
                    return new Range(sel.startLineNumber, sel.startColumn, sel.startLineNumber, maxColumn);
                }
            }
            return sel;
        });
        rangesToDelete.sort(Range.compareRangesUsingStarts);
        return rangesToDelete;
    }
}
class JoinLinesAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.joinLines',
            label: localize('lines.joinLines', "Join Lines"),
            alias: 'Join Lines',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 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(Range.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 Selection(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn);
                }
            }
            else {
                if (currentValue.startLineNumber > previousValue.endLineNumber) {
                    reducedSelections.push(previousValue);
                    return currentValue;
                }
                else {
                    return new Selection(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 i = 0, len = reducedSelections.length; i < len; i++) {
            const selection = reducedSelections[i];
            const startLineNumber = selection.startLineNumber;
            const startColumn = 1;
            let columnDeltaOffset = 0;
            let endLineNumber, endColumn;
            const selectionEndPositionOffset = model.getLineContent(selection.endLineNumber).length - 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 i = startLineNumber + 1; i <= endLineNumber; i++) {
                const lineText = model.getLineContent(i);
                const firstNonWhitespaceIdx = model.getLineFirstNonWhitespaceColumn(i);
                if (firstNonWhitespaceIdx >= 1) {
                    let insertSpace = true;
                    if (trimmedLinesContent === '') {
                        insertSpace = false;
                    }
                    if (insertSpace && (trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === ' ' ||
                        trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === '\t')) {
                        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 Range(startLineNumber, startColumn, endLineNumber, endColumn);
            if (!deleteSelection.isEmpty()) {
                let resultSelection;
                if (selection.isEmpty()) {
                    edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent));
                    resultSelection = new Selection(deleteSelection.startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1, startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1);
                }
                else {
                    if (selection.startLineNumber === selection.endLineNumber) {
                        edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent));
                        resultSelection = new Selection(selection.startLineNumber - lineOffset, selection.startColumn, selection.endLineNumber - lineOffset, selection.endColumn);
                    }
                    else {
                        edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent));
                        resultSelection = new Selection(selection.startLineNumber - lineOffset, selection.startColumn, selection.startLineNumber - lineOffset, trimmedLinesContent.length - selectionEndPositionOffset);
                    }
                }
                if (Range.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();
    }
}
class TransposeAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.transpose',
            label: localize('editor.transpose', "Transpose characters around the cursor"),
            alias: '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 commands = [];
        for (let i = 0, len = selections.length; i < len; i++) {
            const selection = selections[i];
            if (!selection.isEmpty()) {
                continue;
            }
            const cursor = selection.getStartPosition();
            const maxColumn = model.getLineMaxColumn(cursor.lineNumber);
            if (cursor.column >= maxColumn) {
                if (cursor.lineNumber === model.getLineCount()) {
                    continue;
                }
                // The cursor is at the end of current line and current line is not empty
                // then we transpose the character before the cursor and the line break if there is any following line.
                const deleteSelection = new Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1);
                const chars = model.getValueInRange(deleteSelection).split('').reverse().join('');
                commands.push(new ReplaceCommand(new Selection(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1), chars));
            }
            else {
                const deleteSelection = new Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber, cursor.column + 1);
                const chars = model.getValueInRange(deleteSelection).split('').reverse().join('');
                commands.push(new ReplaceCommandThatPreservesSelection(deleteSelection, chars, new Selection(cursor.lineNumber, cursor.column + 1, cursor.lineNumber, cursor.column + 1)));
            }
        }
        editor.pushUndoStop();
        editor.executeCommands(this.id, commands);
        editor.pushUndoStop();
    }
}
class AbstractCaseAction extends EditorAction {
    run(_accessor, editor) {
        const selections = editor.getSelections();
        if (selections === null) {
            return;
        }
        const model = editor.getModel();
        if (model === null) {
            return;
        }
        const wordSeparators = editor.getOption(119 /* 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 Range(cursor.lineNumber, word.startColumn, cursor.lineNumber, word.endColumn);
                const text = model.getValueInRange(wordRange);
                textEdits.push(EditOperation.replace(wordRange, this._modifyText(text, wordSeparators)));
            }
            else {
                const text = model.getValueInRange(selection);
                textEdits.push(EditOperation.replace(selection, this._modifyText(text, wordSeparators)));
            }
        }
        editor.pushUndoStop();
        editor.executeEdits(this.id, textEdits);
        editor.pushUndoStop();
    }
}
class UpperCaseAction extends AbstractCaseAction {
    constructor() {
        super({
            id: 'editor.action.transformToUppercase',
            label: localize('editor.transformToUppercase', "Transform to Uppercase"),
            alias: 'Transform to Uppercase',
            precondition: EditorContextKeys.writable
        });
    }
    _modifyText(text, wordSeparators) {
        return text.toLocaleUpperCase();
    }
}
class LowerCaseAction extends AbstractCaseAction {
    constructor() {
        super({
            id: 'editor.action.transformToLowercase',
            label: localize('editor.transformToLowercase', "Transform to Lowercase"),
            alias: 'Transform to Lowercase',
            precondition: EditorContextKeys.writable
        });
    }
    _modifyText(text, wordSeparators) {
        return text.toLocaleLowerCase();
    }
}
class BackwardsCompatibleRegExp {
    constructor(_pattern, _flags) {
        this._pattern = _pattern;
        this._flags = _flags;
        this._actual = null;
        this._evaluated = false;
    }
    get() {
        if (!this._evaluated) {
            this._evaluated = true;
            try {
                this._actual = new RegExp(this._pattern, this._flags);
            }
            catch (err) {
                // this browser does not support this regular expression
            }
        }
        return this._actual;
    }
    isSupported() {
        return (this.get() !== null);
    }
}
class TitleCaseAction extends AbstractCaseAction {
    constructor() {
        super({
            id: 'editor.action.transformToTitlecase',
            label: localize('editor.transformToTitlecase', "Transform to Title Case"),
            alias: 'Transform to Title Case',
            precondition: EditorContextKeys.writable
        });
    }
    _modifyText(text, wordSeparators) {
        const titleBoundary = TitleCaseAction.titleBoundary.get();
        if (!titleBoundary) {
            // cannot support this
            return text;
        }
        return text
            .toLocaleLowerCase()
            .replace(titleBoundary, (b) => b.toLocaleUpperCase());
    }
}
TitleCaseAction.titleBoundary = new BackwardsCompatibleRegExp('(^|[^\\p{L}\\p{N}\']|((^|\\P{L})\'))\\p{L}', 'gmu');
class SnakeCaseAction extends AbstractCaseAction {
    constructor() {
        super({
            id: 'editor.action.transformToSnakecase',
            label: localize('editor.transformToSnakecase', "Transform to Snake Case"),
            alias: 'Transform to Snake Case',
            precondition: EditorContextKeys.writable
        });
    }
    _modifyText(text, wordSeparators) {
        const caseBoundary = SnakeCaseAction.caseBoundary.get();
        const singleLetters = SnakeCaseAction.singleLetters.get();
        if (!caseBoundary || !singleLetters) {
            // cannot support this
            return text;
        }
        return (text
            .replace(caseBoundary, '$1_$2')
            .replace(singleLetters, '$1_$2$3')
            .toLocaleLowerCase());
    }
}
SnakeCaseAction.caseBoundary = new BackwardsCompatibleRegExp('(\\p{Ll})(\\p{Lu})', 'gmu');
SnakeCaseAction.singleLetters = new BackwardsCompatibleRegExp('(\\p{Lu}|\\p{N})(\\p{Lu})(\\p{Ll})', 'gmu');
class KebabCaseAction extends AbstractCaseAction {
    constructor() {
        super({
            id: 'editor.action.transformToKebabcase',
            label: localize('editor.transformToKebabcase', 'Transform to Kebab Case'),
            alias: 'Transform to Kebab Case',
            precondition: EditorContextKeys.writable
        });
    }
    static isSupported() {
        const areAllRegexpsSupported = [
            this.caseBoundary,
            this.singleLetters,
            this.underscoreBoundary,
        ].every((regexp) => regexp.isSupported());
        return areAllRegexpsSupported;
    }
    _modifyText(text, _) {
        const caseBoundary = KebabCaseAction.caseBoundary.get();
        const singleLetters = KebabCaseAction.singleLetters.get();
        const underscoreBoundary = KebabCaseAction.underscoreBoundary.get();
        if (!caseBoundary || !singleLetters || !underscoreBoundary) {
            // one or more regexps aren't supported
            return text;
        }
        return text
            .replace(underscoreBoundary, '$1-$3')
            .replace(caseBoundary, '$1-$2')
            .replace(singleLetters, '$1-$2')
            .toLocaleLowerCase();
    }
}
KebabCaseAction.caseBoundary = new BackwardsCompatibleRegExp('(\\p{Ll})(\\p{Lu})', 'gmu');
KebabCaseAction.singleLetters = new BackwardsCompatibleRegExp('(\\p{Lu}|\\p{N})(\\p{Lu}\\p{Ll})', 'gmu');
KebabCaseAction.underscoreBoundary = new BackwardsCompatibleRegExp('(\\S)(_)(\\S)', 'gm');
registerEditorAction(CopyLinesUpAction);
registerEditorAction(CopyLinesDownAction);
registerEditorAction(DuplicateSelectionAction);
registerEditorAction(MoveLinesUpAction);
registerEditorAction(MoveLinesDownAction);
registerEditorAction(SortLinesAscendingAction);
registerEditorAction(SortLinesDescendingAction);
registerEditorAction(DeleteDuplicateLinesAction);
registerEditorAction(TrimTrailingWhitespaceAction);
registerEditorAction(DeleteLinesAction);
registerEditorAction(IndentLinesAction);
registerEditorAction(OutdentLinesAction);
registerEditorAction(InsertLineBeforeAction);
registerEditorAction(InsertLineAfterAction);
registerEditorAction(DeleteAllLeftAction);
registerEditorAction(DeleteAllRightAction);
registerEditorAction(JoinLinesAction);
registerEditorAction(TransposeAction);
registerEditorAction(UpperCaseAction);
registerEditorAction(LowerCaseAction);
if (SnakeCaseAction.caseBoundary.isSupported() && SnakeCaseAction.singleLetters.isSupported()) {
    registerEditorAction(SnakeCaseAction);
}
if (TitleCaseAction.titleBoundary.isSupported()) {
    registerEditorAction(TitleCaseAction);
}
if (KebabCaseAction.isSupported()) {
    registerEditorAction(KebabCaseAction);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/linkedEditing/browser/linkedEditing.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var linkedEditing_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var linkedEditing_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var linkedEditing_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};























const CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE = new RawContextKey('LinkedEditingInputVisible', false);
const DECORATION_CLASS_NAME = 'linked-editing-decoration';
let LinkedEditingContribution = class LinkedEditingContribution extends Disposable {
    constructor(editor, contextKeyService, languageFeaturesService, languageConfigurationService, languageFeatureDebounceService) {
        super();
        this.languageConfigurationService = languageConfigurationService;
        this._syncRangesToken = 0;
        this._localToDispose = this._register(new DisposableStore());
        this._editor = editor;
        this._providers = languageFeaturesService.linkedEditingRangeProvider;
        this._enabled = false;
        this._visibleContextKey = CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
        this._debounceInformation = languageFeatureDebounceService.for(this._providers, 'Linked Editing', { min: 200 });
        this._currentDecorations = this._editor.createDecorationsCollection();
        this._languageWordPattern = null;
        this._currentWordPattern = null;
        this._ignoreChangeEvent = false;
        this._localToDispose = this._register(new DisposableStore());
        this._rangeUpdateTriggerPromise = null;
        this._rangeSyncTriggerPromise = null;
        this._currentRequest = null;
        this._currentRequestPosition = null;
        this._currentRequestModelVersion = null;
        this._register(this._editor.onDidChangeModel(() => this.reinitialize(true)));
        this._register(this._editor.onDidChangeConfiguration(e => {
            if (e.hasChanged(64 /* EditorOption.linkedEditing */) || e.hasChanged(84 /* EditorOption.renameOnType */)) {
                this.reinitialize(false);
            }
        }));
        this._register(this._providers.onDidChange(() => this.reinitialize(false)));
        this._register(this._editor.onDidChangeModelLanguage(() => this.reinitialize(true)));
        this.reinitialize(true);
    }
    static get(editor) {
        return editor.getContribution(LinkedEditingContribution.ID);
    }
    reinitialize(forceRefresh) {
        const model = this._editor.getModel();
        const isEnabled = model !== null && (this._editor.getOption(64 /* EditorOption.linkedEditing */) || this._editor.getOption(84 /* EditorOption.renameOnType */)) && this._providers.has(model);
        if (isEnabled === this._enabled && !forceRefresh) {
            return;
        }
        this._enabled = isEnabled;
        this.clearRanges();
        this._localToDispose.clear();
        if (!isEnabled || model === null) {
            return;
        }
        this._localToDispose.add(Event.runAndSubscribe(model.onDidChangeLanguageConfiguration, () => {
            this._languageWordPattern = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
        }));
        const rangeUpdateScheduler = new Delayer(this._debounceInformation.get(model));
        const triggerRangeUpdate = () => {
            var _a;
            this._rangeUpdateTriggerPromise = rangeUpdateScheduler.trigger(() => this.updateRanges(), (_a = this._debounceDuration) !== null && _a !== void 0 ? _a : this._debounceInformation.get(model));
        };
        const rangeSyncScheduler = new Delayer(0);
        const triggerRangeSync = (token) => {
            this._rangeSyncTriggerPromise = rangeSyncScheduler.trigger(() => this._syncRanges(token));
        };
        this._localToDispose.add(this._editor.onDidChangeCursorPosition(() => {
            triggerRangeUpdate();
        }));
        this._localToDispose.add(this._editor.onDidChangeModelContent((e) => {
            if (!this._ignoreChangeEvent) {
                if (this._currentDecorations.length > 0) {
                    const referenceRange = this._currentDecorations.getRange(0);
                    if (referenceRange && e.changes.every(c => referenceRange.intersectRanges(c.range))) {
                        triggerRangeSync(this._syncRangesToken);
                        return;
                    }
                }
            }
            triggerRangeUpdate();
        }));
        this._localToDispose.add({
            dispose: () => {
                rangeUpdateScheduler.dispose();
                rangeSyncScheduler.dispose();
            }
        });
        this.updateRanges();
    }
    _syncRanges(token) {
        // dalayed invocation, make sure we're still on
        if (!this._editor.hasModel() || token !== this._syncRangesToken || this._currentDecorations.length === 0) {
            // nothing to do
            return;
        }
        const model = this._editor.getModel();
        const referenceRange = this._currentDecorations.getRange(0);
        if (!referenceRange || referenceRange.startLineNumber !== referenceRange.endLineNumber) {
            return this.clearRanges();
        }
        const referenceValue = model.getValueInRange(referenceRange);
        if (this._currentWordPattern) {
            const match = referenceValue.match(this._currentWordPattern);
            const matchLength = match ? match[0].length : 0;
            if (matchLength !== referenceValue.length) {
                return this.clearRanges();
            }
        }
        const edits = [];
        for (let i = 1, len = this._currentDecorations.length; i < len; i++) {
            const mirrorRange = this._currentDecorations.getRange(i);
            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 = strings_commonPrefixLength(oldValue, newValue);
                rangeStartColumn += commonPrefixLength;
                oldValue = oldValue.substr(commonPrefixLength);
                newValue = newValue.substr(commonPrefixLength);
                const commonSuffixLength = strings_commonSuffixLength(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 Range(mirrorRange.startLineNumber, rangeStartColumn, mirrorRange.endLineNumber, rangeEndColumn),
                        text: newValue
                    });
                }
            }
        }
        if (edits.length === 0) {
            return;
        }
        try {
            this._editor.popUndoStop();
            this._ignoreChangeEvent = true;
            const prevEditOperationType = this._editor._getViewModel().getPrevEditOperationType();
            this._editor.executeEdits('linkedEditing', edits);
            this._editor._getViewModel().setPrevEditOperationType(prevEditOperationType);
        }
        finally {
            this._ignoreChangeEvent = false;
        }
    }
    dispose() {
        this.clearRanges();
        super.dispose();
    }
    clearRanges() {
        this._visibleContextKey.set(false);
        this._currentDecorations.clear();
        if (this._currentRequest) {
            this._currentRequest.cancel();
            this._currentRequest = null;
            this._currentRequestPosition = null;
        }
    }
    updateRanges(force = false) {
        return linkedEditing_awaiter(this, void 0, void 0, function* () {
            if (!this._editor.hasModel()) {
                this.clearRanges();
                return;
            }
            const position = this._editor.getPosition();
            if (!this._enabled && !force || this._editor.getSelections().length > 1) {
                // disabled or multicursor
                this.clearRanges();
                return;
            }
            const model = this._editor.getModel();
            const modelVersionId = model.getVersionId();
            if (this._currentRequestPosition && this._currentRequestModelVersion === modelVersionId) {
                if (position.equals(this._currentRequestPosition)) {
                    return; // same position
                }
                if (this._currentDecorations.length > 0) {
                    const range = this._currentDecorations.getRange(0);
                    if (range && range.containsPosition(position)) {
                        return; // just moving inside the existing primary range
                    }
                }
            }
            this._currentRequestPosition = position;
            this._currentRequestModelVersion = modelVersionId;
            const request = createCancelablePromise((token) => linkedEditing_awaiter(this, void 0, void 0, function* () {
                try {
                    const sw = new StopWatch(false);
                    const response = yield getLinkedEditingRanges(this._providers, model, position, token);
                    this._debounceInformation.update(model, sw.elapsed());
                    if (request !== this._currentRequest) {
                        return;
                    }
                    this._currentRequest = null;
                    if (modelVersionId !== model.getVersionId()) {
                        return;
                    }
                    let ranges = [];
                    if (response === null || response === void 0 ? void 0 : response.ranges) {
                        ranges = response.ranges;
                    }
                    this._currentWordPattern = (response === null || response === void 0 ? void 0 : response.wordPattern) || this._languageWordPattern;
                    let foundReferenceRange = false;
                    for (let i = 0, len = ranges.length; i < len; i++) {
                        if (Range.containsPosition(ranges[i], position)) {
                            foundReferenceRange = true;
                            if (i !== 0) {
                                const referenceRange = ranges[i];
                                ranges.splice(i, 1);
                                ranges.unshift(referenceRange);
                            }
                            break;
                        }
                    }
                    if (!foundReferenceRange) {
                        // Cannot do linked editing if the ranges are not where the cursor is...
                        this.clearRanges();
                        return;
                    }
                    const decorations = ranges.map(range => ({ range: range, options: LinkedEditingContribution.DECORATION }));
                    this._visibleContextKey.set(true);
                    this._currentDecorations.set(decorations);
                    this._syncRangesToken++; // cancel any pending syncRanges call
                }
                catch (err) {
                    if (!isCancellationError(err)) {
                        onUnexpectedError(err);
                    }
                    if (this._currentRequest === request || !this._currentRequest) {
                        // stop if we are still the latest request
                        this.clearRanges();
                    }
                }
            }));
            this._currentRequest = request;
            return request;
        });
    }
};
LinkedEditingContribution.ID = 'editor.contrib.linkedEditing';
LinkedEditingContribution.DECORATION = ModelDecorationOptions.register({
    description: 'linked-editing',
    stickiness: 0 /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */,
    className: DECORATION_CLASS_NAME
});
LinkedEditingContribution = linkedEditing_decorate([
    linkedEditing_param(1, IContextKeyService),
    linkedEditing_param(2, ILanguageFeaturesService),
    linkedEditing_param(3, ILanguageConfigurationService),
    linkedEditing_param(4, ILanguageFeatureDebounceService)
], LinkedEditingContribution);

class LinkedEditingAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.linkedEditing',
            label: localize('linkedEditing.label', "Start Linked Editing"),
            alias: 'Start Linked Editing',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasRenameProvider),
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 60 /* KeyCode.F2 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    runCommand(accessor, args) {
        const editorService = accessor.get(ICodeEditorService);
        const [uri, pos] = Array.isArray(args) && args || [undefined, undefined];
        if (URI.isUri(uri) && Position.isIPosition(pos)) {
            return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then(editor => {
                if (!editor) {
                    return;
                }
                editor.setPosition(pos);
                editor.invokeWithinContext(accessor => {
                    this.reportTelemetry(accessor, editor);
                    return this.run(accessor, editor);
                });
            }, onUnexpectedError);
        }
        return super.runCommand(accessor, args);
    }
    run(_accessor, editor) {
        const controller = LinkedEditingContribution.get(editor);
        if (controller) {
            return Promise.resolve(controller.updateRanges(true));
        }
        return Promise.resolve();
    }
}
const LinkedEditingCommand = EditorCommand.bindToContribution(LinkedEditingContribution.get);
registerEditorCommand(new LinkedEditingCommand({
    id: 'cancelLinkedEditingInput',
    precondition: CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE,
    handler: x => x.clearRanges(),
    kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        weight: 100 /* KeybindingWeight.EditorContrib */ + 99,
        primary: 9 /* KeyCode.Escape */,
        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
    }
}));
function getLinkedEditingRanges(providers, model, position, token) {
    const orderedByScore = providers.ordered(model);
    // in order of score ask the linked editing range provider
    // until someone response with a good result
    // (good = not null)
    return first(orderedByScore.map(provider => () => linkedEditing_awaiter(this, void 0, void 0, function* () {
        try {
            return yield provider.provideLinkedEditingRanges(model, position, token);
        }
        catch (e) {
            onUnexpectedExternalError(e);
            return undefined;
        }
    })), result => !!result && isNonEmptyArray(result === null || result === void 0 ? void 0 : result.ranges));
}
const editorLinkedEditingBackground = registerColor('editor.linkedEditingBackground', { dark: Color.fromHex('#f00').transparent(0.3), light: Color.fromHex('#f00').transparent(0.3), hcDark: Color.fromHex('#f00').transparent(0.3), hcLight: Color.white }, localize('editorLinkedEditingBackground', 'Background color when the editor auto renames on type.'));
registerThemingParticipant((theme, collector) => {
    const editorLinkedEditingBackgroundColor = theme.getColor(editorLinkedEditingBackground);
    if (editorLinkedEditingBackgroundColor) {
        collector.addRule(`.monaco-editor .${DECORATION_CLASS_NAME} { background: ${editorLinkedEditingBackgroundColor}; border-left-color: ${editorLinkedEditingBackgroundColor}; }`);
    }
});
registerModelAndPositionCommand('_executeLinkedEditingProvider', (_accessor, model, position) => {
    const { linkedEditingRangeProvider } = _accessor.get(ILanguageFeaturesService);
    return getLinkedEditingRanges(linkedEditingRangeProvider, model, position, CancellationToken.None);
});
registerEditorContribution(LinkedEditingContribution.ID, LinkedEditingContribution);
registerEditorAction(LinkedEditingAction);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/links/browser/links.css
var links = __webpack_require__(52494);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/links/browser/links.css

      
      
      
      
      
      
      
      
      

var links_options = {};

links_options.styleTagTransform = (styleTagTransform_default());
links_options.setAttributes = (setAttributesWithoutAttributes_default());

      links_options.insert = insertBySelector_default().bind(null, "head");
    
links_options.domAPI = (styleDomAPI_default());
links_options.insertStyleElement = (insertStyleElement_default());

var links_update = injectStylesIntoStyleTag_default()(links/* default */.A, links_options);




       /* harmony default export */ const browser_links = (links/* default */.A && links/* default */.A.locals ? links/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/links/browser/getLinks.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var getLinks_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};










class Link {
    constructor(link, provider) {
        this._link = link;
        this._provider = provider;
    }
    toJSON() {
        return {
            range: this.range,
            url: this.url,
            tooltip: this.tooltip
        };
    }
    get range() {
        return this._link.range;
    }
    get url() {
        return this._link.url;
    }
    get tooltip() {
        return this._link.tooltip;
    }
    resolve(token) {
        return getLinks_awaiter(this, void 0, void 0, function* () {
            if (this._link.url) {
                return this._link.url;
            }
            if (typeof this._provider.resolveLink === 'function') {
                return Promise.resolve(this._provider.resolveLink(this._link, token)).then(value => {
                    this._link = value || this._link;
                    if (this._link.url) {
                        // recurse
                        return this.resolve(token);
                    }
                    return Promise.reject(new Error('missing'));
                });
            }
            return Promise.reject(new Error('missing'));
        });
    }
}
class LinksList {
    constructor(tuples) {
        this._disposables = new DisposableStore();
        let links = [];
        for (const [list, provider] of tuples) {
            // merge all links
            const newLinks = list.links.map(link => new Link(link, provider));
            links = LinksList._union(links, newLinks);
            // register disposables
            if (isDisposable(list)) {
                this._disposables.add(list);
            }
        }
        this.links = links;
    }
    dispose() {
        this._disposables.dispose();
        this.links.length = 0;
    }
    static _union(oldLinks, newLinks) {
        // reunite oldLinks with newLinks and remove duplicates
        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 (Range.areIntersectingOrTouching(oldLink.range, newLink.range)) {
                // Remove the oldLink
                oldIndex++;
                continue;
            }
            const comparisonResult = Range.compareRangesUsingStarts(oldLink.range, newLink.range);
            if (comparisonResult < 0) {
                // oldLink is before
                result.push(oldLink);
                oldIndex++;
            }
            else {
                // newLink is before
                result.push(newLink);
                newIndex++;
            }
        }
        for (; oldIndex < oldLen; oldIndex++) {
            result.push(oldLinks[oldIndex]);
        }
        for (; newIndex < newLen; newIndex++) {
            result.push(newLinks[newIndex]);
        }
        return result;
    }
}
function getLinks(providers, model, token) {
    const lists = [];
    // ask all providers for links in parallel
    const promises = providers.ordered(model).reverse().map((provider, i) => {
        return Promise.resolve(provider.provideLinks(model, token)).then(result => {
            if (result) {
                lists[i] = [result, provider];
            }
        }, onUnexpectedExternalError);
    });
    return Promise.all(promises).then(() => {
        const result = new LinksList(coalesce(lists));
        if (!token.isCancellationRequested) {
            return result;
        }
        result.dispose();
        return new LinksList([]);
    });
}
CommandsRegistry.registerCommand('_executeLinkProvider', (accessor, ...args) => getLinks_awaiter(void 0, void 0, void 0, function* () {
    let [uri, resolveCount] = args;
    assertType(uri instanceof URI);
    if (typeof resolveCount !== 'number') {
        resolveCount = 0;
    }
    const { linkProvider } = accessor.get(ILanguageFeaturesService);
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
        return [];
    }
    const list = yield getLinks(linkProvider, model, CancellationToken.None);
    if (!list) {
        return [];
    }
    // resolve links
    for (let i = 0; i < Math.min(resolveCount, list.links.length); i++) {
        yield list.links[i].resolve(CancellationToken.None);
    }
    const result = list.links.slice(0);
    list.dispose();
    return result;
}));

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/links/browser/links.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var links_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var links_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var links_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};






















let LinkDetector = class LinkDetector extends Disposable {
    constructor(editor, openerService, notificationService, languageFeaturesService, languageFeatureDebounceService) {
        super();
        this.editor = editor;
        this.openerService = openerService;
        this.notificationService = notificationService;
        this.languageFeaturesService = languageFeaturesService;
        this.providers = this.languageFeaturesService.linkProvider;
        this.debounceInformation = languageFeatureDebounceService.for(this.providers, 'Links', { min: 1000, max: 4000 });
        this.computeLinks = this._register(new RunOnceScheduler(() => this.computeLinksNow(), 1000));
        this.computePromise = null;
        this.activeLinksList = null;
        this.currentOccurrences = {};
        this.activeLinkDecorationId = null;
        const clickLinkGesture = this._register(new ClickLinkGesture(editor));
        this._register(clickLinkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
            this._onEditorMouseMove(mouseEvent, keyboardEvent);
        }));
        this._register(clickLinkGesture.onExecute((e) => {
            this.onEditorMouseUp(e);
        }));
        this._register(clickLinkGesture.onCancel((e) => {
            this.cleanUpActiveLinkDecoration();
        }));
        this._register(editor.onDidChangeConfiguration((e) => {
            if (!e.hasChanged(65 /* EditorOption.links */)) {
                return;
            }
            // Remove any links (for the getting disabled case)
            this.updateDecorations([]);
            // Stop any computation (for the getting disabled case)
            this.stop();
            // Start computing (for the getting enabled case)
            this.computeLinks.schedule(0);
        }));
        this._register(editor.onDidChangeModelContent((e) => {
            if (!this.editor.hasModel()) {
                return;
            }
            this.computeLinks.schedule(this.debounceInformation.get(this.editor.getModel()));
        }));
        this._register(editor.onDidChangeModel((e) => {
            this.currentOccurrences = {};
            this.activeLinkDecorationId = null;
            this.stop();
            this.computeLinks.schedule(0);
        }));
        this._register(editor.onDidChangeModelLanguage((e) => {
            this.stop();
            this.computeLinks.schedule(0);
        }));
        this._register(this.providers.onDidChange((e) => {
            this.stop();
            this.computeLinks.schedule(0);
        }));
        this.computeLinks.schedule(0);
    }
    static get(editor) {
        return editor.getContribution(LinkDetector.ID);
    }
    computeLinksNow() {
        return links_awaiter(this, void 0, void 0, function* () {
            if (!this.editor.hasModel() || !this.editor.getOption(65 /* EditorOption.links */)) {
                return;
            }
            const model = this.editor.getModel();
            if (!this.providers.has(model)) {
                return;
            }
            if (this.activeLinksList) {
                this.activeLinksList.dispose();
                this.activeLinksList = null;
            }
            this.computePromise = createCancelablePromise(token => getLinks(this.providers, model, token));
            try {
                const sw = new StopWatch(false);
                this.activeLinksList = yield this.computePromise;
                this.debounceInformation.update(model, sw.elapsed());
                if (model.isDisposed()) {
                    return;
                }
                this.updateDecorations(this.activeLinksList.links);
            }
            catch (err) {
                onUnexpectedError(err);
            }
            finally {
                this.computePromise = null;
            }
        });
    }
    updateDecorations(links) {
        const useMetaKey = (this.editor.getOption(72 /* EditorOption.multiCursorModifier */) === 'altKey');
        const oldDecorations = [];
        const keys = Object.keys(this.currentOccurrences);
        for (const decorationId of keys) {
            const occurence = this.currentOccurrences[decorationId];
            oldDecorations.push(occurence.decorationId);
        }
        const newDecorations = [];
        if (links) {
            // Not sure why this is sometimes null
            for (const link of links) {
                newDecorations.push(LinkOccurrence.decoration(link, useMetaKey));
            }
        }
        this.editor.changeDecorations((changeAccessor) => {
            const decorations = changeAccessor.deltaDecorations(oldDecorations, newDecorations);
            this.currentOccurrences = {};
            this.activeLinkDecorationId = null;
            for (let i = 0, len = decorations.length; i < len; i++) {
                const occurence = new LinkOccurrence(links[i], decorations[i]);
                this.currentOccurrences[occurence.decorationId] = occurence;
            }
        });
    }
    _onEditorMouseMove(mouseEvent, withKey) {
        const useMetaKey = (this.editor.getOption(72 /* EditorOption.multiCursorModifier */) === 'altKey');
        if (this.isEnabled(mouseEvent, withKey)) {
            this.cleanUpActiveLinkDecoration(); // always remove previous link decoration as their can only be one
            const occurrence = this.getLinkOccurrence(mouseEvent.target.position);
            if (occurrence) {
                this.editor.changeDecorations((changeAccessor) => {
                    occurrence.activate(changeAccessor, useMetaKey);
                    this.activeLinkDecorationId = occurrence.decorationId;
                });
            }
        }
        else {
            this.cleanUpActiveLinkDecoration();
        }
    }
    cleanUpActiveLinkDecoration() {
        const useMetaKey = (this.editor.getOption(72 /* EditorOption.multiCursorModifier */) === 'altKey');
        if (this.activeLinkDecorationId) {
            const occurrence = this.currentOccurrences[this.activeLinkDecorationId];
            if (occurrence) {
                this.editor.changeDecorations((changeAccessor) => {
                    occurrence.deactivate(changeAccessor, useMetaKey);
                });
            }
            this.activeLinkDecorationId = null;
        }
    }
    onEditorMouseUp(mouseEvent) {
        if (!this.isEnabled(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.openerService) {
            return;
        }
        const { link } = occurrence;
        link.resolve(CancellationToken.None).then(uri => {
            // Support for relative file URIs of the shape file://./relativeFile.txt or file:///./relativeFile.txt
            if (typeof uri === 'string' && this.editor.hasModel()) {
                const modelUri = this.editor.getModel().uri;
                if (modelUri.scheme === Schemas.file && uri.startsWith(`${Schemas.file}:`)) {
                    const parsedUri = URI.parse(uri);
                    if (parsedUri.scheme === Schemas.file) {
                        const fsPath = originalFSPath(parsedUri);
                        let relativePath = null;
                        if (fsPath.startsWith('/./')) {
                            relativePath = `.${fsPath.substr(1)}`;
                        }
                        else if (fsPath.startsWith('//./')) {
                            relativePath = `.${fsPath.substr(2)}`;
                        }
                        if (relativePath) {
                            uri = joinPath(modelUri, relativePath);
                        }
                    }
                }
            }
            return this.openerService.open(uri, { openToSide, fromUserGesture, allowContributedOpeners: true, allowCommands: true, fromWorkspace: true });
        }, err => {
            const messageOrError = err instanceof Error ? err.message : err;
            // different error cases
            if (messageOrError === 'invalid') {
                this.notificationService.warn(localize('invalid.url', 'Failed to open this link because it is not well-formed: {0}', link.url.toString()));
            }
            else if (messageOrError === 'missing') {
                this.notificationService.warn(localize('missing.url', 'Failed to open this link because its target is missing.'));
            }
            else {
                onUnexpectedError(err);
            }
        });
    }
    getLinkOccurrence(position) {
        if (!this.editor.hasModel() || !position) {
            return null;
        }
        const decorations = this.editor.getModel().getDecorationsInRange({
            startLineNumber: position.lineNumber,
            startColumn: position.column,
            endLineNumber: position.lineNumber,
            endColumn: position.column
        }, 0, true);
        for (const decoration of decorations) {
            const currentOccurrence = this.currentOccurrences[decoration.id];
            if (currentOccurrence) {
                return currentOccurrence;
            }
        }
        return null;
    }
    isEnabled(mouseEvent, withKey) {
        return Boolean((mouseEvent.target.type === 6 /* MouseTargetType.CONTENT_TEXT */)
            && (mouseEvent.hasTriggerModifier || (withKey && withKey.keyCodeIsTriggerKey)));
    }
    stop() {
        var _a;
        this.computeLinks.cancel();
        if (this.activeLinksList) {
            (_a = this.activeLinksList) === null || _a === void 0 ? void 0 : _a.dispose();
            this.activeLinksList = null;
        }
        if (this.computePromise) {
            this.computePromise.cancel();
            this.computePromise = null;
        }
    }
    dispose() {
        super.dispose();
        this.stop();
    }
};
LinkDetector.ID = 'editor.linkDetector';
LinkDetector = links_decorate([
    links_param(1, IOpenerService),
    links_param(2, INotificationService),
    links_param(3, ILanguageFeaturesService),
    links_param(4, ILanguageFeatureDebounceService)
], LinkDetector);

const decoration = {
    general: ModelDecorationOptions.register({
        description: 'detected-link',
        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
        collapseOnReplaceEdit: true,
        inlineClassName: 'detected-link'
    }),
    active: ModelDecorationOptions.register({
        description: 'detected-link-active',
        stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
        collapseOnReplaceEdit: true,
        inlineClassName: 'detected-link-active'
    })
};
class LinkOccurrence {
    constructor(link, decorationId) {
        this.link = link;
        this.decorationId = decorationId;
    }
    static decoration(link, useMetaKey) {
        return {
            range: link.range,
            options: LinkOccurrence._getOptions(link, useMetaKey, false)
        };
    }
    static _getOptions(link, useMetaKey, isActive) {
        const options = Object.assign({}, (isActive ? decoration.active : decoration.general));
        options.hoverMessage = getHoverMessage(link, useMetaKey);
        return options;
    }
    activate(changeAccessor, useMetaKey) {
        changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, true));
    }
    deactivate(changeAccessor, useMetaKey) {
        changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, false));
    }
}
function getHoverMessage(link, useMetaKey) {
    const executeCmd = link.url && /^command:/i.test(link.url.toString());
    const label = link.tooltip
        ? link.tooltip
        : executeCmd
            ? localize('links.navigate.executeCmd', 'Execute command')
            : localize('links.navigate.follow', 'Follow link');
    const kb = useMetaKey
        ? isMacintosh
            ? localize('links.navigate.kb.meta.mac', "cmd + click")
            : localize('links.navigate.kb.meta', "ctrl + click")
        : isMacintosh
            ? localize('links.navigate.kb.alt.mac', "option + click")
            : localize('links.navigate.kb.alt', "alt + click");
    if (link.url) {
        let nativeLabel = '';
        if (/^command:/i.test(link.url.toString())) {
            // Don't show complete command arguments in the native tooltip
            const match = link.url.toString().match(/^command:([^?#]+)/);
            if (match) {
                const commandId = match[1];
                nativeLabel = localize('tooltip.explanation', "Execute command {0}", commandId);
            }
        }
        const hoverMessage = new MarkdownString('', true)
            .appendLink(link.url.toString(true).replace(/ /g, '%20'), label, nativeLabel)
            .appendMarkdown(` (${kb})`);
        return hoverMessage;
    }
    else {
        return new MarkdownString().appendText(`${label} (${kb})`);
    }
}
class OpenLinkAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.openLink',
            label: localize('label', "Open Link"),
            alias: 'Open Link',
            precondition: undefined
        });
    }
    run(accessor, editor) {
        const linkDetector = LinkDetector.get(editor);
        if (!linkDetector) {
            return;
        }
        if (!editor.hasModel()) {
            return;
        }
        const selections = editor.getSelections();
        for (const sel of selections) {
            const link = linkDetector.getLinkOccurrence(sel.getEndPosition());
            if (link) {
                linkDetector.openLinkOccurrence(link, false);
            }
        }
    }
}
registerEditorContribution(LinkDetector.ID, LinkDetector);
registerEditorAction(OpenLinkAction);
registerThemingParticipant((theme, collector) => {
    const activeLinkForeground = theme.getColor(editorActiveLinkForeground);
    if (activeLinkForeground) {
        collector.addRule(`.monaco-editor .detected-link-active { color: ${activeLinkForeground} !important; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/multicursor/browser/multicursor.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var multicursor_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var multicursor_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};


















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('cursorAdded', "Cursor added: {0}", cursorPositions) : localize('cursorsAdded', "Cursors added: {0}", cursorPositions);
        aria_status(msg);
    }
}
class InsertCursorAbove extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.insertCursorAbove',
            label: localize('mutlicursor.insertAbove', "Add Cursor Above"),
            alias: 'Add Cursor Above',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */,
                linux: {
                    primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */,
                    secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 16 /* KeyCode.UpArrow */]
                },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '3_multi',
                title: localize({ key: 'miInsertCursorAbove', comment: ['&& denotes a mnemonic'] }, "&&Add Cursor Above"),
                order: 2
            }
        });
    }
    run(accessor, editor, args) {
        if (!editor.hasModel()) {
            return;
        }
        let useLogicalLine = true;
        if (args && args.logicalLine === false) {
            useLogicalLine = false;
        }
        const viewModel = editor._getViewModel();
        if (viewModel.cursorConfig.readOnly) {
            return;
        }
        viewModel.model.pushStackElement();
        const previousCursorState = viewModel.getCursorStates();
        viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, CursorMoveCommands.addCursorUp(viewModel, previousCursorState, useLogicalLine));
        viewModel.revealTopMostCursor(args.source);
        announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
}
class InsertCursorBelow extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.insertCursorBelow',
            label: localize('mutlicursor.insertBelow', "Add Cursor Below"),
            alias: 'Add Cursor Below',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */,
                linux: {
                    primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */,
                    secondary: [2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 18 /* KeyCode.DownArrow */]
                },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '3_multi',
                title: localize({ key: 'miInsertCursorBelow', comment: ['&& denotes a mnemonic'] }, "A&&dd Cursor Below"),
                order: 3
            }
        });
    }
    run(accessor, editor, args) {
        if (!editor.hasModel()) {
            return;
        }
        let useLogicalLine = true;
        if (args && args.logicalLine === false) {
            useLogicalLine = false;
        }
        const viewModel = editor._getViewModel();
        if (viewModel.cursorConfig.readOnly) {
            return;
        }
        viewModel.model.pushStackElement();
        const previousCursorState = viewModel.getCursorStates();
        viewModel.setCursorStates(args.source, 3 /* CursorChangeReason.Explicit */, CursorMoveCommands.addCursorDown(viewModel, previousCursorState, useLogicalLine));
        viewModel.revealBottomMostCursor(args.source);
        announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
}
class InsertCursorAtEndOfEachLineSelected extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.insertCursorAtEndOfEachLineSelected',
            label: localize('mutlicursor.insertAtEndOfEachLineSelected', "Add Cursors to Line Ends"),
            alias: 'Add Cursors to Line Ends',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 39 /* KeyCode.KeyI */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '3_multi',
                title: localize({ key: 'miInsertCursorAtEndOfEachLineSelected', comment: ['&& denotes a mnemonic'] }, "Add C&&ursors to Line Ends"),
                order: 4
            }
        });
    }
    getCursorsForSelection(selection, model, result) {
        if (selection.isEmpty()) {
            return;
        }
        for (let i = selection.startLineNumber; i < selection.endLineNumber; i++) {
            const currentLineMaxColumn = model.getLineMaxColumn(i);
            result.push(new Selection(i, currentLineMaxColumn, i, currentLineMaxColumn));
        }
        if (selection.endColumn > 1) {
            result.push(new Selection(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.getCursorsForSelection(sel, model, newSelections));
        if (newSelections.length > 0) {
            editor.setSelections(newSelections);
        }
        announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
}
class InsertCursorAtEndOfLineSelected extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.addCursorsToBottom',
            label: localize('mutlicursor.addCursorsToBottom', "Add Cursors To Bottom"),
            alias: 'Add Cursors To Bottom',
            precondition: undefined
        });
    }
    run(accessor, editor) {
        if (!editor.hasModel()) {
            return;
        }
        const selections = editor.getSelections();
        const lineCount = editor.getModel().getLineCount();
        const newSelections = [];
        for (let i = selections[0].startLineNumber; i <= lineCount; i++) {
            newSelections.push(new Selection(i, selections[0].startColumn, i, selections[0].endColumn));
        }
        const viewModel = editor._getViewModel();
        const previousCursorState = viewModel.getCursorStates();
        if (newSelections.length > 0) {
            editor.setSelections(newSelections);
        }
        announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
}
class InsertCursorAtTopOfLineSelected extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.addCursorsToTop',
            label: localize('mutlicursor.addCursorsToTop', "Add Cursors To Top"),
            alias: 'Add Cursors To Top',
            precondition: undefined
        });
    }
    run(accessor, editor) {
        if (!editor.hasModel()) {
            return;
        }
        const selections = editor.getSelections();
        const newSelections = [];
        for (let i = selections[0].startLineNumber; i >= 1; i--) {
            newSelections.push(new Selection(i, selections[0].startColumn, i, selections[0].endColumn));
        }
        const viewModel = editor._getViewModel();
        const previousCursorState = viewModel.getCursorStates();
        if (newSelections.length > 0) {
            editor.setSelections(newSelections);
        }
        announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
}
class MultiCursorSessionResult {
    constructor(selections, revealRange, revealScrollType) {
        this.selections = selections;
        this.revealRange = revealRange;
        this.revealScrollType = revealScrollType;
    }
}
class MultiCursorSession {
    constructor(_editor, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch) {
        this._editor = _editor;
        this.findController = findController;
        this.isDisconnectedFromFindController = isDisconnectedFromFindController;
        this.searchText = searchText;
        this.wholeWord = wholeWord;
        this.matchCase = matchCase;
        this.currentMatch = currentMatch;
    }
    static create(editor, findController) {
        if (!editor.hasModel()) {
            return null;
        }
        const findState = findController.getState();
        // Find widget owns entirely what we search for if:
        //  - focus is not in the editor (i.e. it is in the find widget)
        //  - and the search widget is visible
        //  - and the search string is non-empty
        if (!editor.hasTextFocus() && findState.isRevealed && findState.searchString.length > 0) {
            // Find widget owns what is searched for
            return new MultiCursorSession(editor, findController, false, findState.searchString, findState.wholeWord, findState.matchCase, null);
        }
        // Otherwise, the selection gives the search text, and the find widget gives the search settings
        // The exception is the find state disassociation case: when beginning with a single, collapsed selection
        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;
        }
        // Selection owns what is searched for
        const s = editor.getSelection();
        let searchText;
        let currentMatch = null;
        if (s.isEmpty()) {
            // selection is empty => expand to current word
            const word = editor.getConfiguredWordAtPosition(s.getStartPosition());
            if (!word) {
                return null;
            }
            searchText = word.word;
            currentMatch = new Selection(s.startLineNumber, word.startColumn, s.startLineNumber, word.endColumn);
        }
        else {
            searchText = editor.getModel().getValueInRange(s).replace(/\r\n/g, '\n');
        }
        return new MultiCursorSession(editor, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch);
    }
    addSelectionToNextFindMatch() {
        if (!this._editor.hasModel()) {
            return null;
        }
        const nextMatch = this._getNextMatch();
        if (!nextMatch) {
            return null;
        }
        const allSelections = this._editor.getSelections();
        return new MultiCursorSessionResult(allSelections.concat(nextMatch), nextMatch, 0 /* ScrollType.Smooth */);
    }
    moveSelectionToNextFindMatch() {
        if (!this._editor.hasModel()) {
            return null;
        }
        const nextMatch = this._getNextMatch();
        if (!nextMatch) {
            return null;
        }
        const allSelections = this._editor.getSelections();
        return new MultiCursorSessionResult(allSelections.slice(0, allSelections.length - 1).concat(nextMatch), nextMatch, 0 /* ScrollType.Smooth */);
    }
    _getNextMatch() {
        if (!this._editor.hasModel()) {
            return null;
        }
        if (this.currentMatch) {
            const result = this.currentMatch;
            this.currentMatch = null;
            return result;
        }
        this.findController.highlightFindOptions();
        const allSelections = this._editor.getSelections();
        const lastAddedSelection = allSelections[allSelections.length - 1];
        const nextMatch = this._editor.getModel().findNextMatch(this.searchText, lastAddedSelection.getEndPosition(), false, this.matchCase, this.wholeWord ? this._editor.getOption(119 /* EditorOption.wordSeparators */) : null, false);
        if (!nextMatch) {
            return null;
        }
        return new Selection(nextMatch.range.startLineNumber, nextMatch.range.startColumn, nextMatch.range.endLineNumber, nextMatch.range.endColumn);
    }
    addSelectionToPreviousFindMatch() {
        if (!this._editor.hasModel()) {
            return null;
        }
        const previousMatch = this._getPreviousMatch();
        if (!previousMatch) {
            return null;
        }
        const allSelections = this._editor.getSelections();
        return new MultiCursorSessionResult(allSelections.concat(previousMatch), previousMatch, 0 /* ScrollType.Smooth */);
    }
    moveSelectionToPreviousFindMatch() {
        if (!this._editor.hasModel()) {
            return null;
        }
        const previousMatch = this._getPreviousMatch();
        if (!previousMatch) {
            return null;
        }
        const allSelections = this._editor.getSelections();
        return new MultiCursorSessionResult(allSelections.slice(0, allSelections.length - 1).concat(previousMatch), previousMatch, 0 /* ScrollType.Smooth */);
    }
    _getPreviousMatch() {
        if (!this._editor.hasModel()) {
            return null;
        }
        if (this.currentMatch) {
            const result = this.currentMatch;
            this.currentMatch = null;
            return result;
        }
        this.findController.highlightFindOptions();
        const allSelections = this._editor.getSelections();
        const lastAddedSelection = allSelections[allSelections.length - 1];
        const previousMatch = this._editor.getModel().findPreviousMatch(this.searchText, lastAddedSelection.getStartPosition(), false, this.matchCase, this.wholeWord ? this._editor.getOption(119 /* EditorOption.wordSeparators */) : null, false);
        if (!previousMatch) {
            return null;
        }
        return new Selection(previousMatch.range.startLineNumber, previousMatch.range.startColumn, previousMatch.range.endLineNumber, previousMatch.range.endColumn);
    }
    selectAll(searchScope) {
        if (!this._editor.hasModel()) {
            return [];
        }
        this.findController.highlightFindOptions();
        const editorModel = this._editor.getModel();
        if (searchScope) {
            return editorModel.findMatches(this.searchText, searchScope, false, this.matchCase, this.wholeWord ? this._editor.getOption(119 /* EditorOption.wordSeparators */) : null, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
        }
        return editorModel.findMatches(this.searchText, true, false, this.matchCase, this.wholeWord ? this._editor.getOption(119 /* EditorOption.wordSeparators */) : null, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
    }
}
class MultiCursorSelectionController extends Disposable {
    constructor(editor) {
        super();
        this._sessionDispose = this._register(new DisposableStore());
        this._editor = editor;
        this._ignoreSelectionChange = false;
        this._session = null;
    }
    static get(editor) {
        return editor.getContribution(MultiCursorSelectionController.ID);
    }
    dispose() {
        this._endSession();
        super.dispose();
    }
    _beginSessionIfNeeded(findController) {
        if (!this._session) {
            // Create a new session
            const session = MultiCursorSession.create(this._editor, findController);
            if (!session) {
                return;
            }
            this._session = session;
            const newState = { searchString: this._session.searchText };
            if (this._session.isDisconnectedFromFindController) {
                newState.wholeWordOverride = 1 /* FindOptionOverride.True */;
                newState.matchCaseOverride = 1 /* FindOptionOverride.True */;
                newState.isRegexOverride = 2 /* FindOptionOverride.False */;
            }
            findController.getState().change(newState, false);
            this._sessionDispose.add(this._editor.onDidChangeCursorSelection((e) => {
                if (this._ignoreSelectionChange) {
                    return;
                }
                this._endSession();
            }));
            this._sessionDispose.add(this._editor.onDidBlurEditorText(() => {
                this._endSession();
            }));
            this._sessionDispose.add(findController.getState().onFindReplaceStateChange((e) => {
                if (e.matchCase || e.wholeWord) {
                    this._endSession();
                }
            }));
        }
    }
    _endSession() {
        this._sessionDispose.clear();
        if (this._session && this._session.isDisconnectedFromFindController) {
            const newState = {
                wholeWordOverride: 0 /* FindOptionOverride.NotSet */,
                matchCaseOverride: 0 /* FindOptionOverride.NotSet */,
                isRegexOverride: 0 /* FindOptionOverride.NotSet */,
            };
            this._session.findController.getState().change(newState, false);
        }
        this._session = null;
    }
    _setSelections(selections) {
        this._ignoreSelectionChange = true;
        this._editor.setSelections(selections);
        this._ignoreSelectionChange = false;
    }
    _expandEmptyToWord(model, selection) {
        if (!selection.isEmpty()) {
            return selection;
        }
        const word = this._editor.getConfiguredWordAtPosition(selection.getStartPosition());
        if (!word) {
            return selection;
        }
        return new Selection(selection.startLineNumber, word.startColumn, selection.startLineNumber, word.endColumn);
    }
    _applySessionResult(result) {
        if (!result) {
            return;
        }
        this._setSelections(result.selections);
        if (result.revealRange) {
            this._editor.revealRangeInCenterIfOutsideViewport(result.revealRange, result.revealScrollType);
        }
    }
    getSession(findController) {
        return this._session;
    }
    addSelectionToNextFindMatch(findController) {
        if (!this._editor.hasModel()) {
            return;
        }
        if (!this._session) {
            // If there are multiple cursors, handle the case where they do not all select the same text.
            const allSelections = this._editor.getSelections();
            if (allSelections.length > 1) {
                const findState = findController.getState();
                const matchCase = findState.matchCase;
                const selectionsContainSameText = modelRangesContainSameText(this._editor.getModel(), allSelections, matchCase);
                if (!selectionsContainSameText) {
                    const model = this._editor.getModel();
                    const resultingSelections = [];
                    for (let i = 0, len = allSelections.length; i < len; i++) {
                        resultingSelections[i] = this._expandEmptyToWord(model, allSelections[i]);
                    }
                    this._editor.setSelections(resultingSelections);
                    return;
                }
            }
        }
        this._beginSessionIfNeeded(findController);
        if (this._session) {
            this._applySessionResult(this._session.addSelectionToNextFindMatch());
        }
    }
    addSelectionToPreviousFindMatch(findController) {
        this._beginSessionIfNeeded(findController);
        if (this._session) {
            this._applySessionResult(this._session.addSelectionToPreviousFindMatch());
        }
    }
    moveSelectionToNextFindMatch(findController) {
        this._beginSessionIfNeeded(findController);
        if (this._session) {
            this._applySessionResult(this._session.moveSelectionToNextFindMatch());
        }
    }
    moveSelectionToPreviousFindMatch(findController) {
        this._beginSessionIfNeeded(findController);
        if (this._session) {
            this._applySessionResult(this._session.moveSelectionToPreviousFindMatch());
        }
    }
    selectAll(findController) {
        if (!this._editor.hasModel()) {
            return;
        }
        let matches = null;
        const findState = findController.getState();
        // Special case: find widget owns entirely what we search for if:
        // - focus is not in the editor (i.e. it is in the find widget)
        // - and the search widget is visible
        // - and the search string is non-empty
        // - and we're searching for a regex
        if (findState.isRevealed && findState.searchString.length > 0 && findState.isRegex) {
            const editorModel = this._editor.getModel();
            if (findState.searchScope) {
                matches = editorModel.findMatches(findState.searchString, findState.searchScope, findState.isRegex, findState.matchCase, findState.wholeWord ? this._editor.getOption(119 /* EditorOption.wordSeparators */) : null, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
            }
            else {
                matches = editorModel.findMatches(findState.searchString, true, findState.isRegex, findState.matchCase, findState.wholeWord ? this._editor.getOption(119 /* EditorOption.wordSeparators */) : null, false, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
            }
        }
        else {
            this._beginSessionIfNeeded(findController);
            if (!this._session) {
                return;
            }
            matches = this._session.selectAll(findState.searchScope);
        }
        if (matches.length > 0) {
            const editorSelection = this._editor.getSelection();
            // Have the primary cursor remain the one where the action was invoked
            for (let i = 0, len = matches.length; i < len; i++) {
                const match = matches[i];
                const intersection = match.range.intersectRanges(editorSelection);
                if (intersection) {
                    // bingo!
                    matches[i] = matches[0];
                    matches[0] = match;
                    break;
                }
            }
            this._setSelections(matches.map(m => new Selection(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn)));
        }
    }
}
MultiCursorSelectionController.ID = 'editor.contrib.multiCursorController';
class MultiCursorSelectionControllerAction extends EditorAction {
    run(accessor, editor) {
        const multiCursorController = MultiCursorSelectionController.get(editor);
        if (!multiCursorController) {
            return;
        }
        const findController = CommonFindController.get(editor);
        if (!findController) {
            return;
        }
        const viewModel = editor._getViewModel();
        if (viewModel) {
            const previousCursorState = viewModel.getCursorStates();
            this._run(multiCursorController, findController);
            announceCursorChange(previousCursorState, viewModel.getCursorStates());
        }
    }
}
class AddSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
    constructor() {
        super({
            id: 'editor.action.addSelectionToNextFindMatch',
            label: localize('addSelectionToNextFindMatch', "Add Selection To Next Find Match"),
            alias: 'Add Selection To Next Find Match',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 34 /* KeyCode.KeyD */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '3_multi',
                title: localize({ key: 'miAddSelectionToNextFindMatch', comment: ['&& denotes a mnemonic'] }, "Add &&Next Occurrence"),
                order: 5
            }
        });
    }
    _run(multiCursorController, findController) {
        multiCursorController.addSelectionToNextFindMatch(findController);
    }
}
class AddSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
    constructor() {
        super({
            id: 'editor.action.addSelectionToPreviousFindMatch',
            label: localize('addSelectionToPreviousFindMatch', "Add Selection To Previous Find Match"),
            alias: 'Add Selection To Previous Find Match',
            precondition: undefined,
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '3_multi',
                title: localize({ key: 'miAddSelectionToPreviousFindMatch', comment: ['&& denotes a mnemonic'] }, "Add P&&revious Occurrence"),
                order: 6
            }
        });
    }
    _run(multiCursorController, findController) {
        multiCursorController.addSelectionToPreviousFindMatch(findController);
    }
}
class MoveSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
    constructor() {
        super({
            id: 'editor.action.moveSelectionToNextFindMatch',
            label: localize('moveSelectionToNextFindMatch', "Move Last Selection To Next Find Match"),
            alias: 'Move Last Selection To Next Find Match',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: KeyChord(2048 /* KeyMod.CtrlCmd */ | 41 /* KeyCode.KeyK */, 2048 /* KeyMod.CtrlCmd */ | 34 /* KeyCode.KeyD */),
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    _run(multiCursorController, findController) {
        multiCursorController.moveSelectionToNextFindMatch(findController);
    }
}
class MoveSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
    constructor() {
        super({
            id: 'editor.action.moveSelectionToPreviousFindMatch',
            label: localize('moveSelectionToPreviousFindMatch', "Move Last Selection To Previous Find Match"),
            alias: 'Move Last Selection To Previous Find Match',
            precondition: undefined
        });
    }
    _run(multiCursorController, findController) {
        multiCursorController.moveSelectionToPreviousFindMatch(findController);
    }
}
class SelectHighlightsAction extends MultiCursorSelectionControllerAction {
    constructor() {
        super({
            id: 'editor.action.selectHighlights',
            label: localize('selectAllOccurrencesOfFindMatch', "Select All Occurrences of Find Match"),
            alias: 'Select All Occurrences of Find Match',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 42 /* KeyCode.KeyL */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '3_multi',
                title: localize({ key: 'miSelectHighlights', comment: ['&& denotes a mnemonic'] }, "Select All &&Occurrences"),
                order: 7
            }
        });
    }
    _run(multiCursorController, findController) {
        multiCursorController.selectAll(findController);
    }
}
class CompatChangeAll extends MultiCursorSelectionControllerAction {
    constructor() {
        super({
            id: 'editor.action.changeAll',
            label: localize('changeAll.label', "Change All Occurrences"),
            alias: 'Change All Occurrences',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.editorTextFocus),
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 60 /* KeyCode.F2 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            contextMenuOpts: {
                group: '1_modification',
                order: 1.2
            }
        });
    }
    _run(multiCursorController, findController) {
        multiCursorController.selectAll(findController);
    }
}
class SelectionHighlighterState {
    constructor(_model, _searchText, _matchCase, _wordSeparators, prevState) {
        this._model = _model;
        this._searchText = _searchText;
        this._matchCase = _matchCase;
        this._wordSeparators = _wordSeparators;
        this._modelVersionId = this._model.getVersionId();
        this._cachedFindMatches = null;
        if (prevState
            && this._model === prevState._model
            && this._searchText === prevState._searchText
            && this._matchCase === prevState._matchCase
            && this._wordSeparators === prevState._wordSeparators
            && this._modelVersionId === prevState._modelVersionId) {
            this._cachedFindMatches = prevState._cachedFindMatches;
        }
    }
    findMatches() {
        if (this._cachedFindMatches === null) {
            this._cachedFindMatches = this._model.findMatches(this._searchText, true, false, this._matchCase, this._wordSeparators, false).map(m => m.range);
            this._cachedFindMatches.sort(Range.compareRangesUsingStarts);
        }
        return this._cachedFindMatches;
    }
}
let SelectionHighlighter = class SelectionHighlighter extends Disposable {
    constructor(editor, _languageFeaturesService) {
        super();
        this._languageFeaturesService = _languageFeaturesService;
        this.editor = editor;
        this._isEnabled = editor.getOption(99 /* EditorOption.selectionHighlight */);
        this._decorations = editor.createDecorationsCollection();
        this.updateSoon = this._register(new RunOnceScheduler(() => this._update(), 300));
        this.state = null;
        this._register(editor.onDidChangeConfiguration((e) => {
            this._isEnabled = editor.getOption(99 /* EditorOption.selectionHighlight */);
        }));
        this._register(editor.onDidChangeCursorSelection((e) => {
            if (!this._isEnabled) {
                // Early exit if nothing needs to be done!
                // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;)
                return;
            }
            if (e.selection.isEmpty()) {
                if (e.reason === 3 /* CursorChangeReason.Explicit */) {
                    if (this.state) {
                        // no longer valid
                        this._setState(null);
                    }
                    this.updateSoon.schedule();
                }
                else {
                    this._setState(null);
                }
            }
            else {
                this._update();
            }
        }));
        this._register(editor.onDidChangeModel((e) => {
            this._setState(null);
        }));
        this._register(editor.onDidChangeModelContent((e) => {
            if (this._isEnabled) {
                this.updateSoon.schedule();
            }
        }));
        const findController = CommonFindController.get(editor);
        if (findController) {
            this._register(findController.getState().onFindReplaceStateChange((e) => {
                this._update();
            }));
        }
    }
    _update() {
        this._setState(SelectionHighlighter._createState(this.state, this._isEnabled, this.editor));
    }
    static _createState(oldState, isEnabled, editor) {
        if (!isEnabled) {
            return null;
        }
        if (!editor.hasModel()) {
            return null;
        }
        const s = editor.getSelection();
        if (s.startLineNumber !== s.endLineNumber) {
            // multiline forbidden for perf reasons
            return null;
        }
        const multiCursorController = MultiCursorSelectionController.get(editor);
        if (!multiCursorController) {
            return null;
        }
        const findController = CommonFindController.get(editor);
        if (!findController) {
            return null;
        }
        let r = multiCursorController.getSession(findController);
        if (!r) {
            const allSelections = editor.getSelections();
            if (allSelections.length > 1) {
                const findState = findController.getState();
                const matchCase = findState.matchCase;
                const selectionsContainSameText = modelRangesContainSameText(editor.getModel(), allSelections, matchCase);
                if (!selectionsContainSameText) {
                    return null;
                }
            }
            r = MultiCursorSession.create(editor, findController);
        }
        if (!r) {
            return null;
        }
        if (r.currentMatch) {
            // This is an empty selection
            // Do not interfere with semantic word highlighting in the no selection case
            return null;
        }
        if (/^[ \t]+$/.test(r.searchText)) {
            // whitespace only selection
            return null;
        }
        if (r.searchText.length > 200) {
            // very long selection
            return null;
        }
        // TODO: better handling of this case
        const findState = findController.getState();
        const caseSensitive = findState.matchCase;
        // Return early if the find widget shows the exact same matches
        if (findState.isRevealed) {
            let findStateSearchString = findState.searchString;
            if (!caseSensitive) {
                findStateSearchString = findStateSearchString.toLowerCase();
            }
            let mySearchString = r.searchText;
            if (!caseSensitive) {
                mySearchString = mySearchString.toLowerCase();
            }
            if (findStateSearchString === mySearchString && r.matchCase === findState.matchCase && r.wholeWord === findState.wholeWord && !findState.isRegex) {
                return null;
            }
        }
        return new SelectionHighlighterState(editor.getModel(), r.searchText, r.matchCase, r.wholeWord ? editor.getOption(119 /* EditorOption.wordSeparators */) : null, oldState);
    }
    _setState(newState) {
        this.state = newState;
        if (!this.state) {
            this._decorations.clear();
            return;
        }
        if (!this.editor.hasModel()) {
            return;
        }
        const model = this.editor.getModel();
        if (model.isTooLargeForTokenization()) {
            // the file is too large, so searching word under cursor in the whole document would be blocking the UI.
            return;
        }
        const allMatches = this.state.findMatches();
        const selections = this.editor.getSelections();
        selections.sort(Range.compareRangesUsingStarts);
        // do not overlap with selection (issue #64 and #512)
        const matches = [];
        for (let i = 0, j = 0, len = allMatches.length, lenJ = selections.length; i < len;) {
            const match = allMatches[i];
            if (j >= lenJ) {
                // finished all editor selections
                matches.push(match);
                i++;
            }
            else {
                const cmp = Range.compareRangesUsingStarts(match, selections[j]);
                if (cmp < 0) {
                    // match is before sel
                    if (selections[j].isEmpty() || !Range.areIntersecting(match, selections[j])) {
                        matches.push(match);
                    }
                    i++;
                }
                else if (cmp > 0) {
                    // sel is before match
                    j++;
                }
                else {
                    // sel is equal to match
                    i++;
                    j++;
                }
            }
        }
        const hasFindOccurrences = this._languageFeaturesService.documentHighlightProvider.has(model) && this.editor.getOption(74 /* EditorOption.occurrencesHighlight */);
        const decorations = matches.map(r => {
            return {
                range: r,
                // Show in overviewRuler only if model has no semantic highlighting
                options: (hasFindOccurrences ? SelectionHighlighter._SELECTION_HIGHLIGHT : SelectionHighlighter._SELECTION_HIGHLIGHT_OVERVIEW)
            };
        });
        this._decorations.set(decorations);
    }
    dispose() {
        this._setState(null);
        super.dispose();
    }
};
SelectionHighlighter.ID = 'editor.contrib.selectionHighlighter';
SelectionHighlighter._SELECTION_HIGHLIGHT_OVERVIEW = ModelDecorationOptions.register({
    description: 'selection-highlight-overview',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    className: 'selectionHighlight',
    minimap: {
        color: themeColorFromId(minimapSelectionOccurrenceHighlight),
        position: MinimapPosition.Inline
    },
    overviewRuler: {
        color: themeColorFromId(overviewRulerSelectionHighlightForeground),
        position: OverviewRulerLane.Center
    }
});
SelectionHighlighter._SELECTION_HIGHLIGHT = ModelDecorationOptions.register({
    description: 'selection-highlight',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    className: 'selectionHighlight',
});
SelectionHighlighter = multicursor_decorate([
    multicursor_param(1, ILanguageFeaturesService)
], SelectionHighlighter);

function modelRangesContainSameText(model, ranges, matchCase) {
    const selectedText = getValueInRange(model, ranges[0], !matchCase);
    for (let i = 1, len = ranges.length; i < len; i++) {
        const range = ranges[i];
        if (range.isEmpty()) {
            return false;
        }
        const thisSelectedText = getValueInRange(model, range, !matchCase);
        if (selectedText !== thisSelectedText) {
            return false;
        }
    }
    return true;
}
function getValueInRange(model, range, toLowerCase) {
    const text = model.getValueInRange(range);
    return (toLowerCase ? text.toLowerCase() : text);
}
class FocusNextCursor extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.focusNextCursor',
            label: localize('mutlicursor.focusNextCursor', "Focus Next Cursor"),
            description: {
                description: localize('mutlicursor.focusNextCursor.description', "Focuses the next cursor"),
                args: [],
            },
            alias: 'Focus Next Cursor',
            precondition: undefined
        });
    }
    run(accessor, editor, args) {
        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(args.source, 3 /* CursorChangeReason.Explicit */, previousCursorState);
        viewModel.revealPrimaryCursor(args.source, true);
        announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
}
class FocusPreviousCursor extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.focusPreviousCursor',
            label: localize('mutlicursor.focusPreviousCursor', "Focus Previous Cursor"),
            description: {
                description: localize('mutlicursor.focusPreviousCursor.description', "Focuses the previous cursor"),
                args: [],
            },
            alias: 'Focus Previous Cursor',
            precondition: undefined
        });
    }
    run(accessor, editor, args) {
        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(args.source, 3 /* CursorChangeReason.Explicit */, previousCursorState);
        viewModel.revealPrimaryCursor(args.source, true);
        announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
}
registerEditorContribution(MultiCursorSelectionController.ID, MultiCursorSelectionController);
registerEditorContribution(SelectionHighlighter.ID, SelectionHighlighter);
registerEditorAction(InsertCursorAbove);
registerEditorAction(InsertCursorBelow);
registerEditorAction(InsertCursorAtEndOfEachLineSelected);
registerEditorAction(AddSelectionToNextFindMatchAction);
registerEditorAction(AddSelectionToPreviousFindMatchAction);
registerEditorAction(MoveSelectionToNextFindMatchAction);
registerEditorAction(MoveSelectionToPreviousFindMatchAction);
registerEditorAction(SelectHighlightsAction);
registerEditorAction(CompatChangeAll);
registerEditorAction(InsertCursorAtEndOfLineSelected);
registerEditorAction(InsertCursorAtTopOfLineSelected);
registerEditorAction(FocusNextCursor);
registerEditorAction(FocusPreviousCursor);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/parameterHints/browser/provideSignatureHelp.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var provideSignatureHelp_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};










const provideSignatureHelp_Context = {
    Visible: new RawContextKey('parameterHintsVisible', false),
    MultipleSignatures: new RawContextKey('parameterHintsMultipleSignatures', false),
};
function provideSignatureHelp(registry, model, position, context, token) {
    return provideSignatureHelp_awaiter(this, void 0, void 0, function* () {
        const supports = registry.ordered(model);
        for (const support of supports) {
            try {
                const result = yield support.provideSignatureHelp(model, position, token, context);
                if (result) {
                    return result;
                }
            }
            catch (err) {
                onUnexpectedExternalError(err);
            }
        }
        return undefined;
    });
}
CommandsRegistry.registerCommand('_executeSignatureHelpProvider', (accessor, ...args) => provideSignatureHelp_awaiter(void 0, void 0, void 0, function* () {
    const [uri, position, triggerCharacter] = args;
    assertType(URI.isUri(uri));
    assertType(Position.isIPosition(position));
    assertType(typeof triggerCharacter === 'string' || !triggerCharacter);
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const ref = yield accessor.get(ITextModelService).createModelReference(uri);
    try {
        const result = yield provideSignatureHelp(languageFeaturesService.signatureHelpProvider, ref.object.textEditorModel, Position.lift(position), {
            triggerKind: SignatureHelpTriggerKind.Invoke,
            isRetrigger: false,
            triggerCharacter,
        }, CancellationToken.None);
        if (!result) {
            return undefined;
        }
        setTimeout(() => result.dispose(), 0);
        return result.value;
    }
    finally {
        ref.dispose();
    }
}));

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/parameterHints/browser/parameterHints.css
var parameterHints = __webpack_require__(69184);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/parameterHints/browser/parameterHints.css

      
      
      
      
      
      
      
      
      

var parameterHints_options = {};

parameterHints_options.styleTagTransform = (styleTagTransform_default());
parameterHints_options.setAttributes = (setAttributesWithoutAttributes_default());

      parameterHints_options.insert = insertBySelector_default().bind(null, "head");
    
parameterHints_options.domAPI = (styleDomAPI_default());
parameterHints_options.insertStyleElement = (insertStyleElement_default());

var parameterHints_update = injectStylesIntoStyleTag_default()(parameterHints/* default */.A, parameterHints_options);




       /* harmony default export */ const browser_parameterHints = (parameterHints/* default */.A && parameterHints/* default */.A.locals ? parameterHints/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/parameterHints/browser/parameterHintsModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var parameterHintsModel_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};







var ParameterHintState;
(function (ParameterHintState) {
    ParameterHintState.Default = { type: 0 /* Type.Default */ };
    class Pending {
        constructor(request, previouslyActiveHints) {
            this.request = request;
            this.previouslyActiveHints = previouslyActiveHints;
            this.type = 2 /* Type.Pending */;
        }
    }
    ParameterHintState.Pending = Pending;
    class Active {
        constructor(hints) {
            this.hints = hints;
            this.type = 1 /* Type.Active */;
        }
    }
    ParameterHintState.Active = Active;
})(ParameterHintState || (ParameterHintState = {}));
class ParameterHintsModel extends Disposable {
    constructor(editor, providers, delay = ParameterHintsModel.DEFAULT_DELAY) {
        super();
        this._onChangedHints = this._register(new Emitter());
        this.onChangedHints = this._onChangedHints.event;
        this.triggerOnType = false;
        this._state = ParameterHintState.Default;
        this._pendingTriggers = [];
        this._lastSignatureHelpResult = this._register(new MutableDisposable());
        this.triggerChars = new CharacterSet();
        this.retriggerChars = new CharacterSet();
        this.triggerId = 0;
        this.editor = editor;
        this.providers = providers;
        this.throttledDelayer = new Delayer(delay);
        this._register(this.editor.onDidBlurEditorWidget(() => this.cancel()));
        this._register(this.editor.onDidChangeConfiguration(() => this.onEditorConfigurationChange()));
        this._register(this.editor.onDidChangeModel(e => this.onModelChanged()));
        this._register(this.editor.onDidChangeModelLanguage(_ => this.onModelChanged()));
        this._register(this.editor.onDidChangeCursorSelection(e => this.onCursorChange(e)));
        this._register(this.editor.onDidChangeModelContent(e => this.onModelContentChange()));
        this._register(this.providers.onDidChange(this.onModelChanged, this));
        this._register(this.editor.onDidType(text => this.onDidType(text)));
        this.onEditorConfigurationChange();
        this.onModelChanged();
    }
    get state() { return this._state; }
    set state(value) {
        if (this._state.type === 2 /* ParameterHintState.Type.Pending */) {
            this._state.request.cancel();
        }
        this._state = value;
    }
    cancel(silent = false) {
        this.state = ParameterHintState.Default;
        this.throttledDelayer.cancel();
        if (!silent) {
            this._onChangedHints.fire(undefined);
        }
    }
    trigger(context, delay) {
        const model = this.editor.getModel();
        if (!model || !this.providers.has(model)) {
            return;
        }
        const triggerId = ++this.triggerId;
        this._pendingTriggers.push(context);
        this.throttledDelayer.trigger(() => {
            return this.doTrigger(triggerId);
        }, delay)
            .catch(onUnexpectedError);
    }
    next() {
        if (this.state.type !== 1 /* ParameterHintState.Type.Active */) {
            return;
        }
        const length = this.state.hints.signatures.length;
        const activeSignature = this.state.hints.activeSignature;
        const last = (activeSignature % length) === (length - 1);
        const cycle = this.editor.getOption(78 /* EditorOption.parameterHints */).cycle;
        // If there is only one signature, or we're on last signature of list
        if ((length < 2 || last) && !cycle) {
            this.cancel();
            return;
        }
        this.updateActiveSignature(last && cycle ? 0 : activeSignature + 1);
    }
    previous() {
        if (this.state.type !== 1 /* ParameterHintState.Type.Active */) {
            return;
        }
        const length = this.state.hints.signatures.length;
        const activeSignature = this.state.hints.activeSignature;
        const first = activeSignature === 0;
        const cycle = this.editor.getOption(78 /* EditorOption.parameterHints */).cycle;
        // If there is only one signature, or we're on first signature of list
        if ((length < 2 || first) && !cycle) {
            this.cancel();
            return;
        }
        this.updateActiveSignature(first && cycle ? length - 1 : activeSignature - 1);
    }
    updateActiveSignature(activeSignature) {
        if (this.state.type !== 1 /* ParameterHintState.Type.Active */) {
            return;
        }
        this.state = new ParameterHintState.Active(Object.assign(Object.assign({}, this.state.hints), { activeSignature }));
        this._onChangedHints.fire(this.state.hints);
    }
    doTrigger(triggerId) {
        return parameterHintsModel_awaiter(this, void 0, void 0, function* () {
            const isRetrigger = this.state.type === 1 /* ParameterHintState.Type.Active */ || this.state.type === 2 /* ParameterHintState.Type.Pending */;
            const activeSignatureHelp = this.getLastActiveHints();
            this.cancel(true);
            if (this._pendingTriggers.length === 0) {
                return false;
            }
            const context = this._pendingTriggers.reduce(mergeTriggerContexts);
            this._pendingTriggers = [];
            const triggerContext = {
                triggerKind: context.triggerKind,
                triggerCharacter: context.triggerCharacter,
                isRetrigger: isRetrigger,
                activeSignatureHelp: activeSignatureHelp
            };
            if (!this.editor.hasModel()) {
                return false;
            }
            const model = this.editor.getModel();
            const position = this.editor.getPosition();
            this.state = new ParameterHintState.Pending(createCancelablePromise(token => provideSignatureHelp(this.providers, model, position, triggerContext, token)), activeSignatureHelp);
            try {
                const result = yield this.state.request;
                // Check that we are still resolving the correct signature help
                if (triggerId !== this.triggerId) {
                    result === null || result === void 0 ? void 0 : result.dispose();
                    return false;
                }
                if (!result || !result.value.signatures || result.value.signatures.length === 0) {
                    result === null || result === void 0 ? void 0 : result.dispose();
                    this._lastSignatureHelpResult.clear();
                    this.cancel();
                    return false;
                }
                else {
                    this.state = new ParameterHintState.Active(result.value);
                    this._lastSignatureHelpResult.value = result;
                    this._onChangedHints.fire(this.state.hints);
                    return true;
                }
            }
            catch (error) {
                if (triggerId === this.triggerId) {
                    this.state = ParameterHintState.Default;
                }
                onUnexpectedError(error);
                return false;
            }
        });
    }
    getLastActiveHints() {
        switch (this.state.type) {
            case 1 /* ParameterHintState.Type.Active */: return this.state.hints;
            case 2 /* ParameterHintState.Type.Pending */: return this.state.previouslyActiveHints;
            default: return undefined;
        }
    }
    get isTriggered() {
        return this.state.type === 1 /* ParameterHintState.Type.Active */
            || this.state.type === 2 /* ParameterHintState.Type.Pending */
            || this.throttledDelayer.isTriggered();
    }
    onModelChanged() {
        this.cancel();
        // Update trigger characters
        this.triggerChars = new CharacterSet();
        this.retriggerChars = new CharacterSet();
        const model = this.editor.getModel();
        if (!model) {
            return;
        }
        for (const support of this.providers.ordered(model)) {
            for (const ch of support.signatureHelpTriggerCharacters || []) {
                this.triggerChars.add(ch.charCodeAt(0));
                // All trigger characters are also considered retrigger characters
                this.retriggerChars.add(ch.charCodeAt(0));
            }
            for (const ch of support.signatureHelpRetriggerCharacters || []) {
                this.retriggerChars.add(ch.charCodeAt(0));
            }
        }
    }
    onDidType(text) {
        if (!this.triggerOnType) {
            return;
        }
        const lastCharIndex = text.length - 1;
        const triggerCharCode = text.charCodeAt(lastCharIndex);
        if (this.triggerChars.has(triggerCharCode) || this.isTriggered && this.retriggerChars.has(triggerCharCode)) {
            this.trigger({
                triggerKind: SignatureHelpTriggerKind.TriggerCharacter,
                triggerCharacter: text.charAt(lastCharIndex),
            });
        }
    }
    onCursorChange(e) {
        if (e.source === 'mouse') {
            this.cancel();
        }
        else if (this.isTriggered) {
            this.trigger({ triggerKind: SignatureHelpTriggerKind.ContentChange });
        }
    }
    onModelContentChange() {
        if (this.isTriggered) {
            this.trigger({ triggerKind: SignatureHelpTriggerKind.ContentChange });
        }
    }
    onEditorConfigurationChange() {
        this.triggerOnType = this.editor.getOption(78 /* EditorOption.parameterHints */).enabled;
        if (!this.triggerOnType) {
            this.cancel();
        }
    }
    dispose() {
        this.cancel(true);
        super.dispose();
    }
}
ParameterHintsModel.DEFAULT_DELAY = 120; // ms
function mergeTriggerContexts(previous, current) {
    switch (current.triggerKind) {
        case SignatureHelpTriggerKind.Invoke:
            // Invoke overrides previous triggers.
            return current;
        case SignatureHelpTriggerKind.ContentChange:
            // Ignore content changes triggers
            return previous;
        case SignatureHelpTriggerKind.TriggerCharacter:
        default:
            return current;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/parameterHints/browser/parameterHintsWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var parameterHintsWidget_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var parameterHintsWidget_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};





















const parameterHintsWidget_$ = dom_$;
const parameterHintsNextIcon = registerIcon('parameter-hints-next', Codicon.chevronDown, localize('parameterHintsNextIcon', 'Icon for show next parameter hint.'));
const parameterHintsPreviousIcon = registerIcon('parameter-hints-previous', Codicon.chevronUp, localize('parameterHintsPreviousIcon', 'Icon for show previous parameter hint.'));
let ParameterHintsWidget = class ParameterHintsWidget extends Disposable {
    constructor(editor, contextKeyService, openerService, languageService, languageFeaturesService) {
        super();
        this.editor = editor;
        this.renderDisposeables = this._register(new DisposableStore());
        this.visible = false;
        this.announcedLabel = null;
        // Editor.IContentWidget.allowEditorOverflow
        this.allowEditorOverflow = true;
        this.markdownRenderer = this._register(new MarkdownRenderer({ editor }, languageService, openerService));
        this.model = this._register(new ParameterHintsModel(editor, languageFeaturesService.signatureHelpProvider));
        this.keyVisible = provideSignatureHelp_Context.Visible.bindTo(contextKeyService);
        this.keyMultipleSignatures = provideSignatureHelp_Context.MultipleSignatures.bindTo(contextKeyService);
        this._register(this.model.onChangedHints(newParameterHints => {
            if (newParameterHints) {
                this.show();
                this.render(newParameterHints);
            }
            else {
                this.hide();
            }
        }));
    }
    createParameterHintDOMNodes() {
        const element = parameterHintsWidget_$('.editor-widget.parameter-hints-widget');
        const wrapper = append(element, parameterHintsWidget_$('.phwrapper'));
        wrapper.tabIndex = -1;
        const controls = append(wrapper, parameterHintsWidget_$('.controls'));
        const previous = append(controls, parameterHintsWidget_$('.button' + ThemeIcon.asCSSSelector(parameterHintsPreviousIcon)));
        const overloads = append(controls, parameterHintsWidget_$('.overloads'));
        const next = append(controls, parameterHintsWidget_$('.button' + ThemeIcon.asCSSSelector(parameterHintsNextIcon)));
        this._register(addDisposableListener(previous, 'click', e => {
            EventHelper.stop(e);
            this.previous();
        }));
        this._register(addDisposableListener(next, 'click', e => {
            EventHelper.stop(e);
            this.next();
        }));
        const body = parameterHintsWidget_$('.body');
        const scrollbar = new DomScrollableElement(body, {
            alwaysConsumeMouseWheel: true,
        });
        this._register(scrollbar);
        wrapper.appendChild(scrollbar.getDomNode());
        const signature = append(body, parameterHintsWidget_$('.signature'));
        const docs = append(body, parameterHintsWidget_$('.docs'));
        element.style.userSelect = 'text';
        this.domNodes = {
            element,
            signature,
            overloads,
            docs,
            scrollbar,
        };
        this.editor.addContentWidget(this);
        this.hide();
        this._register(this.editor.onDidChangeCursorSelection(e => {
            if (this.visible) {
                this.editor.layoutContentWidget(this);
            }
        }));
        const updateFont = () => {
            if (!this.domNodes) {
                return;
            }
            const fontInfo = this.editor.getOption(46 /* EditorOption.fontInfo */);
            this.domNodes.element.style.fontSize = `${fontInfo.fontSize}px`;
            this.domNodes.element.style.lineHeight = `${fontInfo.lineHeight / fontInfo.fontSize}`;
        };
        updateFont();
        this._register(Event.chain(this.editor.onDidChangeConfiguration.bind(this.editor))
            .filter(e => e.hasChanged(46 /* EditorOption.fontInfo */))
            .on(updateFont, null));
        this._register(this.editor.onDidLayoutChange(e => this.updateMaxHeight()));
        this.updateMaxHeight();
    }
    show() {
        if (this.visible) {
            return;
        }
        if (!this.domNodes) {
            this.createParameterHintDOMNodes();
        }
        this.keyVisible.set(true);
        this.visible = true;
        setTimeout(() => {
            var _a;
            (_a = this.domNodes) === null || _a === void 0 ? void 0 : _a.element.classList.add('visible');
        }, 100);
        this.editor.layoutContentWidget(this);
    }
    hide() {
        var _a;
        this.renderDisposeables.clear();
        if (!this.visible) {
            return;
        }
        this.keyVisible.reset();
        this.visible = false;
        this.announcedLabel = null;
        (_a = this.domNodes) === null || _a === void 0 ? void 0 : _a.element.classList.remove('visible');
        this.editor.layoutContentWidget(this);
    }
    getPosition() {
        if (this.visible) {
            return {
                position: this.editor.getPosition(),
                preference: [1 /* ContentWidgetPositionPreference.ABOVE */, 2 /* ContentWidgetPositionPreference.BELOW */]
            };
        }
        return null;
    }
    render(hints) {
        var _a;
        this.renderDisposeables.clear();
        if (!this.domNodes) {
            return;
        }
        const multiple = hints.signatures.length > 1;
        this.domNodes.element.classList.toggle('multiple', multiple);
        this.keyMultipleSignatures.set(multiple);
        this.domNodes.signature.innerText = '';
        this.domNodes.docs.innerText = '';
        const signature = hints.signatures[hints.activeSignature];
        if (!signature) {
            return;
        }
        const code = append(this.domNodes.signature, parameterHintsWidget_$('.code'));
        const fontInfo = this.editor.getOption(46 /* EditorOption.fontInfo */);
        code.style.fontSize = `${fontInfo.fontSize}px`;
        code.style.fontFamily = fontInfo.fontFamily;
        const hasParameters = signature.parameters.length > 0;
        const activeParameterIndex = (_a = signature.activeParameter) !== null && _a !== void 0 ? _a : hints.activeParameter;
        if (!hasParameters) {
            const label = append(code, parameterHintsWidget_$('span'));
            label.textContent = signature.label;
        }
        else {
            this.renderParameters(code, signature, activeParameterIndex);
        }
        const activeParameter = signature.parameters[activeParameterIndex];
        if (activeParameter === null || activeParameter === void 0 ? void 0 : activeParameter.documentation) {
            const documentation = parameterHintsWidget_$('span.documentation');
            if (typeof activeParameter.documentation === 'string') {
                documentation.textContent = activeParameter.documentation;
            }
            else {
                const renderedContents = this.renderMarkdownDocs(activeParameter.documentation);
                documentation.appendChild(renderedContents.element);
            }
            append(this.domNodes.docs, parameterHintsWidget_$('p', {}, documentation));
        }
        if (signature.documentation === undefined) {
            /** no op */
        }
        else if (typeof signature.documentation === 'string') {
            append(this.domNodes.docs, parameterHintsWidget_$('p', {}, signature.documentation));
        }
        else {
            const renderedContents = this.renderMarkdownDocs(signature.documentation);
            append(this.domNodes.docs, renderedContents.element);
        }
        const hasDocs = this.hasDocs(signature, activeParameter);
        this.domNodes.signature.classList.toggle('has-docs', hasDocs);
        this.domNodes.docs.classList.toggle('empty', !hasDocs);
        this.domNodes.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}`;
            }
            // Select method gets called on every user type while parameter hints are visible.
            // We do not want to spam the user with same announcements, so we only announce if the current parameter changed.
            if (this.announcedLabel !== labelToAnnounce) {
                aria_alert(localize('hint', "{0}, hint", labelToAnnounce));
                this.announcedLabel = labelToAnnounce;
            }
        }
        this.editor.layoutContentWidget(this);
        this.domNodes.scrollbar.scanDomNode();
    }
    renderMarkdownDocs(markdown) {
        const renderedContents = this.renderDisposeables.add(this.markdownRenderer.render(markdown, {
            asyncRenderCallback: () => {
                var _a;
                (_a = this.domNodes) === null || _a === void 0 ? void 0 : _a.scrollbar.scanDomNode();
            }
        }));
        renderedContents.element.classList.add('markdown-docs');
        return renderedContents;
    }
    hasDocs(signature, activeParameter) {
        if (activeParameter && typeof activeParameter.documentation === 'string' && assertIsDefined(activeParameter.documentation).length > 0) {
            return true;
        }
        if (activeParameter && typeof activeParameter.documentation === 'object' && assertIsDefined(activeParameter.documentation).value.length > 0) {
            return true;
        }
        if (signature.documentation && typeof signature.documentation === 'string' && assertIsDefined(signature.documentation).length > 0) {
            return true;
        }
        if (signature.documentation && typeof signature.documentation === 'object' && assertIsDefined(signature.documentation.value).length > 0) {
            return true;
        }
        return false;
    }
    renderParameters(parent, signature, activeParameterIndex) {
        const [start, end] = this.getParameterLabelOffsets(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);
        append(parent, beforeSpan, paramSpan, afterSpan);
    }
    getParameterLabelOffsets(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|^)${escapeRegExpCharacters(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.editor.focus();
        this.model.next();
    }
    previous() {
        this.editor.focus();
        this.model.previous();
    }
    cancel() {
        this.model.cancel();
    }
    getDomNode() {
        if (!this.domNodes) {
            this.createParameterHintDOMNodes();
        }
        return this.domNodes.element;
    }
    getId() {
        return ParameterHintsWidget.ID;
    }
    trigger(context) {
        this.model.trigger(context, 0);
    }
    updateMaxHeight() {
        if (!this.domNodes) {
            return;
        }
        const height = Math.max(this.editor.getLayoutInfo().height / 4, 250);
        const maxHeight = `${height}px`;
        this.domNodes.element.style.maxHeight = maxHeight;
        const wrapper = this.domNodes.element.getElementsByClassName('phwrapper');
        if (wrapper.length) {
            wrapper[0].style.maxHeight = maxHeight;
        }
    }
};
ParameterHintsWidget.ID = 'editor.widget.parameterHintsWidget';
ParameterHintsWidget = parameterHintsWidget_decorate([
    parameterHintsWidget_param(1, IContextKeyService),
    parameterHintsWidget_param(2, IOpenerService),
    parameterHintsWidget_param(3, ILanguageService),
    parameterHintsWidget_param(4, ILanguageFeaturesService)
], ParameterHintsWidget);

const editorHoverWidgetHighlightForeground = registerColor('editorHoverWidget.highlightForeground', { dark: listHighlightForeground, light: listHighlightForeground, hcDark: listHighlightForeground, hcLight: listHighlightForeground }, localize('editorHoverWidgetHighlightForeground', 'Foreground color of the active item in the parameter hint.'));
registerThemingParticipant((theme, collector) => {
    const border = theme.getColor(editorHoverBorder);
    if (border) {
        const borderWidth = isHighContrast(theme.type) ? 2 : 1;
        collector.addRule(`.monaco-editor .parameter-hints-widget { border: ${borderWidth}px solid ${border}; }`);
        collector.addRule(`.monaco-editor .parameter-hints-widget.multiple .body { border-left: 1px solid ${border.transparent(0.5)}; }`);
        collector.addRule(`.monaco-editor .parameter-hints-widget .signature.has-docs { border-bottom: 1px solid ${border.transparent(0.5)}; }`);
    }
    const background = theme.getColor(editorHoverBackground);
    if (background) {
        collector.addRule(`.monaco-editor .parameter-hints-widget { background-color: ${background}; }`);
    }
    const link = theme.getColor(textLinkForeground);
    if (link) {
        collector.addRule(`.monaco-editor .parameter-hints-widget a { color: ${link}; }`);
    }
    const linkHover = theme.getColor(textLinkActiveForeground);
    if (linkHover) {
        collector.addRule(`.monaco-editor .parameter-hints-widget a:hover { color: ${linkHover}; }`);
    }
    const foreground = theme.getColor(editorHoverForeground);
    if (foreground) {
        collector.addRule(`.monaco-editor .parameter-hints-widget { color: ${foreground}; }`);
    }
    const codeBackground = theme.getColor(textCodeBlockBackground);
    if (codeBackground) {
        collector.addRule(`.monaco-editor .parameter-hints-widget code { background-color: ${codeBackground}; }`);
    }
    const parameterHighlightColor = theme.getColor(editorHoverWidgetHighlightForeground);
    if (parameterHighlightColor) {
        collector.addRule(`.monaco-editor .parameter-hints-widget .parameter.active { color: ${parameterHighlightColor}}`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/parameterHints/browser/parameterHints.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var parameterHints_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var parameterHints_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};









let ParameterHintsController = class ParameterHintsController extends Disposable {
    constructor(editor, instantiationService) {
        super();
        this.editor = editor;
        this.widget = this._register(instantiationService.createInstance(ParameterHintsWidget, this.editor));
    }
    static get(editor) {
        return editor.getContribution(ParameterHintsController.ID);
    }
    cancel() {
        this.widget.cancel();
    }
    previous() {
        this.widget.previous();
    }
    next() {
        this.widget.next();
    }
    trigger(context) {
        this.widget.trigger(context);
    }
};
ParameterHintsController.ID = 'editor.controller.parameterHints';
ParameterHintsController = parameterHints_decorate([
    parameterHints_param(1, IInstantiationService)
], ParameterHintsController);
class TriggerParameterHintsAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.triggerParameterHints',
            label: localize('parameterHints.trigger.label', "Trigger Parameter Hints"),
            alias: 'Trigger Parameter Hints',
            precondition: EditorContextKeys.hasSignatureHelpProvider,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 10 /* KeyCode.Space */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        const controller = ParameterHintsController.get(editor);
        if (controller) {
            controller.trigger({
                triggerKind: SignatureHelpTriggerKind.Invoke
            });
        }
    }
}
registerEditorContribution(ParameterHintsController.ID, ParameterHintsController);
registerEditorAction(TriggerParameterHintsAction);
const parameterHints_weight = 100 /* KeybindingWeight.EditorContrib */ + 75;
const ParameterHintsCommand = EditorCommand.bindToContribution(ParameterHintsController.get);
registerEditorCommand(new ParameterHintsCommand({
    id: 'closeParameterHints',
    precondition: provideSignatureHelp_Context.Visible,
    handler: x => x.cancel(),
    kbOpts: {
        weight: parameterHints_weight,
        kbExpr: EditorContextKeys.focus,
        primary: 9 /* KeyCode.Escape */,
        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
    }
}));
registerEditorCommand(new ParameterHintsCommand({
    id: 'showPrevParameterHint',
    precondition: ContextKeyExpr.and(provideSignatureHelp_Context.Visible, provideSignatureHelp_Context.MultipleSignatures),
    handler: x => x.previous(),
    kbOpts: {
        weight: parameterHints_weight,
        kbExpr: EditorContextKeys.focus,
        primary: 16 /* KeyCode.UpArrow */,
        secondary: [512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */],
        mac: { primary: 16 /* KeyCode.UpArrow */, secondary: [512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */, 256 /* KeyMod.WinCtrl */ | 46 /* KeyCode.KeyP */] }
    }
}));
registerEditorCommand(new ParameterHintsCommand({
    id: 'showNextParameterHint',
    precondition: ContextKeyExpr.and(provideSignatureHelp_Context.Visible, provideSignatureHelp_Context.MultipleSignatures),
    handler: x => x.next(),
    kbOpts: {
        weight: parameterHints_weight,
        kbExpr: EditorContextKeys.focus,
        primary: 18 /* KeyCode.DownArrow */,
        secondary: [512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */],
        mac: { primary: 18 /* KeyCode.DownArrow */, secondary: [512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */, 256 /* KeyMod.WinCtrl */ | 44 /* KeyCode.KeyN */] }
    }
}));

;// ../../node_modules/monaco-editor/esm/vs/base/common/errorMessage.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



function exceptionToErrorMessage(exception, verbose) {
    if (verbose && (exception.stack || exception.stacktrace)) {
        return localize('stackTrace.format', "{0}: {1}", 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) {
    // See https://nodejs.org/api/errors.html#errors_class_system_error
    if (typeof exception.code === 'string' && typeof exception.errno === 'number' && typeof exception.syscall === 'string') {
        return localize('nodeExceptionMessage', "A system error occurred ({0})", exception.message);
    }
    return exception.message || localize('error.defaultMessage', "An unknown error occurred. Please consult the log for more details.");
}
/**
 * Tries to generate a human readable error message out of the error. If the verbose parameter
 * is set to true, the error message will include stacktrace details if provided.
 *
 * @returns A string containing the error message.
 */
function toErrorMessage(error = null, verbose = false) {
    if (!error) {
        return localize('error.defaultMessage', "An unknown error occurred. Please consult the log for more details.");
    }
    if (Array.isArray(error)) {
        const errors = coalesce(error);
        const msg = toErrorMessage(errors[0], verbose);
        if (errors.length > 1) {
            return localize('error.moreErrors', "{0} ({1} errors in total)", msg, errors.length);
        }
        return msg;
    }
    if (isString(error)) {
        return error;
    }
    if (error.detail) {
        const detail = error.detail;
        if (detail.error) {
            return exceptionToErrorMessage(detail.error, verbose);
        }
        if (detail.exception) {
            return exceptionToErrorMessage(detail.exception, verbose);
        }
    }
    if (error.stack) {
        return exceptionToErrorMessage(error, verbose);
    }
    if (error.message) {
        return error.message;
    }
    return localize('error.defaultMessage', "An unknown error occurred. Please consult the log for more details.");
}

;// ../../node_modules/monaco-editor/esm/vs/platform/dialogs/common/dialogs.js

const IDialogService = createDecorator('dialogService');

;// ../../node_modules/monaco-editor/esm/vs/platform/quickinput/browser/pickerQuickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var pickerQuickAccess_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};



var TriggerAction;
(function (TriggerAction) {
    /**
     * Do nothing after the button was clicked.
     */
    TriggerAction[TriggerAction["NO_ACTION"] = 0] = "NO_ACTION";
    /**
     * Close the picker.
     */
    TriggerAction[TriggerAction["CLOSE_PICKER"] = 1] = "CLOSE_PICKER";
    /**
     * Update the results of the picker.
     */
    TriggerAction[TriggerAction["REFRESH_PICKER"] = 2] = "REFRESH_PICKER";
    /**
     * Remove the item from the picker.
     */
    TriggerAction[TriggerAction["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;
}
class PickerQuickAccessProvider extends Disposable {
    constructor(prefix, options) {
        super();
        this.prefix = prefix;
        this.options = options;
    }
    provide(picker, token) {
        var _a;
        const disposables = new DisposableStore();
        // Apply options if any
        picker.canAcceptInBackground = !!((_a = this.options) === null || _a === void 0 ? void 0 : _a.canAcceptInBackground);
        // Disable filtering & sorting, we control the results
        picker.matchOnLabel = picker.matchOnDescription = picker.matchOnDetail = picker.sortByLabel = false;
        // Set initial picks and update on type
        let picksCts = undefined;
        const picksDisposable = disposables.add(new MutableDisposable());
        const updatePickerItems = () => pickerQuickAccess_awaiter(this, void 0, void 0, function* () {
            const picksDisposables = picksDisposable.value = new DisposableStore();
            // Cancel any previous ask for picks and busy
            picksCts === null || picksCts === void 0 ? void 0 : picksCts.dispose(true);
            picker.busy = false;
            // Create new cancellation source for this run
            picksCts = new CancellationTokenSource(token);
            // Collect picks and support both long running and short or combined
            const picksToken = picksCts.token;
            const picksFilter = picker.value.substr(this.prefix.length).trim();
            const providedPicks = this._getPicks(picksFilter, picksDisposables, picksToken);
            const applyPicks = (picks, skipEmpty) => {
                var _a;
                let items;
                let activeItem = undefined;
                if (isPicksWithActive(picks)) {
                    items = picks.items;
                    activeItem = picks.active;
                }
                else {
                    items = picks;
                }
                if (items.length === 0) {
                    if (skipEmpty) {
                        return false;
                    }
                    if (picksFilter.length > 0 && ((_a = this.options) === null || _a === void 0 ? void 0 : _a.noResultsPick)) {
                        items = [this.options.noResultsPick];
                    }
                }
                picker.items = items;
                if (activeItem) {
                    picker.activeItems = [activeItem];
                }
                return true;
            };
            // No Picks
            if (providedPicks === null) {
                // Ignore
            }
            // Fast and Slow Picks
            else if (isFastAndSlowPicks(providedPicks)) {
                let fastPicksApplied = false;
                let slowPicksApplied = false;
                yield Promise.all([
                    // Fast Picks: to reduce amount of flicker, we race against
                    // the slow picks over 500ms and then set the fast picks.
                    // If the slow picks are faster, we reduce the flicker by
                    // only setting the items once.
                    (() => pickerQuickAccess_awaiter(this, void 0, void 0, function* () {
                        yield timeout(PickerQuickAccessProvider.FAST_PICKS_RACE_DELAY);
                        if (picksToken.isCancellationRequested) {
                            return;
                        }
                        if (!slowPicksApplied) {
                            fastPicksApplied = applyPicks(providedPicks.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.
                    (() => pickerQuickAccess_awaiter(this, void 0, void 0, function* () {
                        picker.busy = true;
                        try {
                            const awaitedAdditionalPicks = yield providedPicks.additionalPicks;
                            if (picksToken.isCancellationRequested) {
                                return;
                            }
                            let picks;
                            let activePick = undefined;
                            if (isPicksWithActive(providedPicks.picks)) {
                                picks = providedPicks.picks.items;
                                activePick = providedPicks.picks.active;
                            }
                            else {
                                picks = providedPicks.picks;
                            }
                            let additionalPicks;
                            let additionalActivePick = undefined;
                            if (isPicksWithActive(awaitedAdditionalPicks)) {
                                additionalPicks = awaitedAdditionalPicks.items;
                                additionalActivePick = awaitedAdditionalPicks.active;
                            }
                            else {
                                additionalPicks = awaitedAdditionalPicks;
                            }
                            if (additionalPicks.length > 0 || !fastPicksApplied) {
                                // If we do not have any activePick or additionalActivePick
                                // we try to preserve the currently active pick from the
                                // fast results. This fixes an issue where the user might
                                // have made a pick active before the additional results
                                // kick in.
                                // See https://github.com/microsoft/vscode/issues/102480
                                let fallbackActivePick = undefined;
                                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;
                        }
                    }))()
                ]);
            }
            // Fast Picks
            else if (!(providedPicks instanceof Promise)) {
                applyPicks(providedPicks);
            }
            // Slow Picks
            else {
                picker.busy = true;
                try {
                    const awaitedPicks = yield providedPicks;
                    if (picksToken.isCancellationRequested) {
                        return;
                    }
                    applyPicks(awaitedPicks);
                }
                finally {
                    if (!picksToken.isCancellationRequested) {
                        picker.busy = false;
                    }
                }
            }
        });
        disposables.add(picker.onDidChangeValue(() => updatePickerItems()));
        updatePickerItems();
        // Accept the pick on accept and hide picker
        disposables.add(picker.onDidAccept(event => {
            const [item] = picker.selectedItems;
            if (typeof (item === null || item === void 0 ? void 0 : item.accept) === 'function') {
                if (!event.inBackground) {
                    picker.hide(); // hide picker unless we accept in background
                }
                item.accept(picker.keyMods, event);
            }
        }));
        // Trigger the pick with button index if button triggered
        disposables.add(picker.onDidTriggerItemButton(({ button, item }) => pickerQuickAccess_awaiter(this, void 0, void 0, function* () {
            var _b, _c;
            if (typeof item.trigger === 'function') {
                const buttonIndex = (_c = (_b = item.buttons) === null || _b === void 0 ? void 0 : _b.indexOf(button)) !== null && _c !== void 0 ? _c : -1;
                if (buttonIndex >= 0) {
                    const result = item.trigger(buttonIndex, picker.keyMods);
                    const action = (typeof result === 'number') ? result : yield 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;
                        }
                    }
                }
            }
        })));
        return disposables;
    }
}
PickerQuickAccessProvider.FAST_PICKS_RACE_DELAY = 200; // timeout before we accept fast results before slow results are present

;// ../../node_modules/monaco-editor/esm/vs/platform/quickinput/browser/commandsQuickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var commandsQuickAccess_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var commandsQuickAccess_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var commandsQuickAccess_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
















let AbstractCommandsQuickAccessProvider = class AbstractCommandsQuickAccessProvider extends PickerQuickAccessProvider {
    constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) {
        super(AbstractCommandsQuickAccessProvider.PREFIX, options);
        this.instantiationService = instantiationService;
        this.keybindingService = keybindingService;
        this.commandService = commandService;
        this.telemetryService = telemetryService;
        this.dialogService = dialogService;
        this.commandsHistory = this._register(this.instantiationService.createInstance(CommandsHistory));
        this.options = options;
    }
    _getPicks(filter, disposables, token) {
        return commandsQuickAccess_awaiter(this, void 0, void 0, function* () {
            // Ask subclass for all command picks
            const allCommandPicks = yield this.getCommandPicks(disposables, token);
            if (token.isCancellationRequested) {
                return [];
            }
            // Filter
            const filteredCommandPicks = [];
            for (const commandPick of allCommandPicks) {
                const labelHighlights = withNullAsUndefined(AbstractCommandsQuickAccessProvider.WORD_FILTER(filter, commandPick.label));
                const aliasHighlights = commandPick.commandAlias ? withNullAsUndefined(AbstractCommandsQuickAccessProvider.WORD_FILTER(filter, commandPick.commandAlias)) : undefined;
                // Add if matching in label or alias
                if (labelHighlights || aliasHighlights) {
                    commandPick.highlights = {
                        label: labelHighlights,
                        detail: this.options.showAlias ? aliasHighlights : undefined
                    };
                    filteredCommandPicks.push(commandPick);
                }
                // Also add if we have a 100% command ID match
                else if (filter === commandPick.commandId) {
                    filteredCommandPicks.push(commandPick);
                }
            }
            // Add description to commands that have duplicate labels
            const mapLabelToCommand = 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);
                }
            }
            // Sort by MRU order and fallback to name otherwise
            filteredCommandPicks.sort((commandPickA, commandPickB) => {
                const commandACounter = this.commandsHistory.peek(commandPickA.commandId);
                const commandBCounter = this.commandsHistory.peek(commandPickB.commandId);
                if (commandACounter && commandBCounter) {
                    return commandACounter > commandBCounter ? -1 : 1; // use more recently used command before older
                }
                if (commandACounter) {
                    return -1; // first command was used, so it wins over the non used one
                }
                if (commandBCounter) {
                    return 1; // other command was used so it wins over the command
                }
                // both commands were never used, so we sort by name
                return commandPickA.label.localeCompare(commandPickB.label);
            });
            const commandPicks = [];
            let addSeparator = false;
            for (let i = 0; i < filteredCommandPicks.length; i++) {
                const commandPick = filteredCommandPicks[i];
                const keybinding = this.keybindingService.lookupKeybinding(commandPick.commandId);
                const ariaLabel = keybinding ?
                    localize('commandPickAriaLabelWithKeybinding', "{0}, {1}", commandPick.label, keybinding.getAriaLabel()) :
                    commandPick.label;
                // Separator: recently used
                if (i === 0 && this.commandsHistory.peek(commandPick.commandId)) {
                    commandPicks.push({ type: 'separator', label: localize('recentlyUsed', "recently used") });
                    addSeparator = true;
                }
                // Separator: other commands
                if (i !== 0 && addSeparator && !this.commandsHistory.peek(commandPick.commandId)) {
                    commandPicks.push({ type: 'separator', label: localize('morecCommands', "other commands") });
                    addSeparator = false; // only once
                }
                // Command
                commandPicks.push(Object.assign(Object.assign({}, commandPick), { ariaLabel, detail: this.options.showAlias && commandPick.commandAlias !== commandPick.label ? commandPick.commandAlias : undefined, keybinding, accept: () => commandsQuickAccess_awaiter(this, void 0, void 0, function* () {
                        // Add to history
                        this.commandsHistory.push(commandPick.commandId);
                        // Telementry
                        this.telemetryService.publicLog2('workbenchActionExecuted', {
                            id: commandPick.commandId,
                            from: 'quick open'
                        });
                        // Run
                        try {
                            yield this.commandService.executeCommand(commandPick.commandId);
                        }
                        catch (error) {
                            if (!isCancellationError(error)) {
                                this.dialogService.show(common_severity.Error, localize('canNotRun', "Command '{0}' resulted in an error ({1})", commandPick.label, toErrorMessage(error)));
                            }
                        }
                    }) }));
            }
            return commandPicks;
        });
    }
};
AbstractCommandsQuickAccessProvider.PREFIX = '>';
AbstractCommandsQuickAccessProvider.WORD_FILTER = or(matchesPrefix, matchesWords, matchesContiguousSubString);
AbstractCommandsQuickAccessProvider = commandsQuickAccess_decorate([
    commandsQuickAccess_param(1, IInstantiationService),
    commandsQuickAccess_param(2, IKeybindingService),
    commandsQuickAccess_param(3, ICommandService),
    commandsQuickAccess_param(4, ITelemetryService),
    commandsQuickAccess_param(5, IDialogService)
], AbstractCommandsQuickAccessProvider);

let CommandsHistory = class CommandsHistory extends Disposable {
    constructor(storageService, configurationService) {
        super();
        this.storageService = storageService;
        this.configurationService = configurationService;
        this.configuredCommandsHistoryLength = 0;
        this.updateConfiguration();
        this.load();
        this.registerListeners();
    }
    registerListeners() {
        this._register(this.configurationService.onDidChangeConfiguration(() => this.updateConfiguration()));
    }
    updateConfiguration() {
        this.configuredCommandsHistoryLength = CommandsHistory.getConfiguredCommandHistoryLength(this.configurationService);
        if (CommandsHistory.cache && CommandsHistory.cache.limit !== this.configuredCommandsHistoryLength) {
            CommandsHistory.cache.limit = this.configuredCommandsHistoryLength;
            CommandsHistory.saveState(this.storageService);
        }
    }
    load() {
        const raw = this.storageService.get(CommandsHistory.PREF_KEY_CACHE, 0 /* StorageScope.PROFILE */);
        let serializedCache;
        if (raw) {
            try {
                serializedCache = JSON.parse(raw);
            }
            catch (error) {
                // invalid data
            }
        }
        const cache = CommandsHistory.cache = new LRUCache(this.configuredCommandsHistoryLength, 1);
        if (serializedCache) {
            let entries;
            if (serializedCache.usesLRU) {
                entries = serializedCache.entries;
            }
            else {
                entries = serializedCache.entries.sort((a, b) => a.value - b.value);
            }
            entries.forEach(entry => cache.set(entry.key, entry.value));
        }
        CommandsHistory.counter = this.storageService.getNumber(CommandsHistory.PREF_KEY_COUNTER, 0 /* StorageScope.PROFILE */, CommandsHistory.counter);
    }
    push(commandId) {
        if (!CommandsHistory.cache) {
            return;
        }
        CommandsHistory.cache.set(commandId, CommandsHistory.counter++); // set counter to command
        CommandsHistory.saveState(this.storageService);
    }
    peek(commandId) {
        var _a;
        return (_a = CommandsHistory.cache) === null || _a === void 0 ? void 0 : _a.peek(commandId);
    }
    static saveState(storageService) {
        if (!CommandsHistory.cache) {
            return;
        }
        const serializedCache = { usesLRU: true, entries: [] };
        CommandsHistory.cache.forEach((value, key) => serializedCache.entries.push({ key, value }));
        storageService.store(CommandsHistory.PREF_KEY_CACHE, JSON.stringify(serializedCache), 0 /* StorageScope.PROFILE */, 0 /* StorageTarget.USER */);
        storageService.store(CommandsHistory.PREF_KEY_COUNTER, CommandsHistory.counter, 0 /* StorageScope.PROFILE */, 0 /* StorageTarget.USER */);
    }
    static getConfiguredCommandHistoryLength(configurationService) {
        var _a, _b;
        const config = configurationService.getValue();
        const configuredCommandHistoryLength = (_b = (_a = config.workbench) === null || _a === void 0 ? void 0 : _a.commandPalette) === null || _b === void 0 ? void 0 : _b.history;
        if (typeof configuredCommandHistoryLength === 'number') {
            return configuredCommandHistoryLength;
        }
        return CommandsHistory.DEFAULT_COMMANDS_HISTORY_LENGTH;
    }
};
CommandsHistory.DEFAULT_COMMANDS_HISTORY_LENGTH = 50;
CommandsHistory.PREF_KEY_CACHE = 'commandPalette.mru.cache';
CommandsHistory.PREF_KEY_COUNTER = 'commandPalette.mru.counter';
CommandsHistory.counter = 1;
CommandsHistory = commandsQuickAccess_decorate([
    commandsQuickAccess_param(0, IStorageService),
    commandsQuickAccess_param(1, IConfigurationService)
], CommandsHistory);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/quickAccess/browser/commandsQuickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class AbstractEditorCommandsQuickAccessProvider extends AbstractCommandsQuickAccessProvider {
    constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) {
        super(options, instantiationService, keybindingService, commandService, telemetryService, dialogService);
    }
    getCodeEditorCommandPicks() {
        const activeTextEditorControl = this.activeTextEditorControl;
        if (!activeTextEditorControl) {
            return [];
        }
        const editorCommandPicks = [];
        for (const editorAction of activeTextEditorControl.getSupportedActions()) {
            editorCommandPicks.push({
                commandId: editorAction.id,
                commandAlias: editorAction.alias,
                label: stripIcons(editorAction.label) || editorAction.id,
            });
        }
        return editorCommandPicks;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickAccess/standaloneCommandsQuickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var standaloneCommandsQuickAccess_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var standaloneCommandsQuickAccess_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var standaloneCommandsQuickAccess_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};














let StandaloneCommandsQuickAccessProvider = class StandaloneCommandsQuickAccessProvider extends AbstractEditorCommandsQuickAccessProvider {
    constructor(instantiationService, codeEditorService, keybindingService, commandService, telemetryService, dialogService) {
        super({ showAlias: false }, instantiationService, keybindingService, commandService, telemetryService, dialogService);
        this.codeEditorService = codeEditorService;
    }
    get activeTextEditorControl() { return withNullAsUndefined(this.codeEditorService.getFocusedCodeEditor()); }
    getCommandPicks() {
        return standaloneCommandsQuickAccess_awaiter(this, void 0, void 0, function* () {
            return this.getCodeEditorCommandPicks();
        });
    }
};
StandaloneCommandsQuickAccessProvider = standaloneCommandsQuickAccess_decorate([
    standaloneCommandsQuickAccess_param(0, IInstantiationService),
    standaloneCommandsQuickAccess_param(1, ICodeEditorService),
    standaloneCommandsQuickAccess_param(2, IKeybindingService),
    standaloneCommandsQuickAccess_param(3, ICommandService),
    standaloneCommandsQuickAccess_param(4, ITelemetryService),
    standaloneCommandsQuickAccess_param(5, IDialogService)
], StandaloneCommandsQuickAccessProvider);

class standaloneCommandsQuickAccess_GotoLineAction extends EditorAction {
    constructor() {
        super({
            id: standaloneCommandsQuickAccess_GotoLineAction.ID,
            label: QuickCommandNLS.quickCommandActionLabel,
            alias: 'Command Palette',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: 59 /* KeyCode.F1 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            contextMenuOpts: {
                group: 'z_commands',
                order: 1
            }
        });
    }
    run(accessor) {
        accessor.get(IQuickInputService).quickAccess.show(StandaloneCommandsQuickAccessProvider.PREFIX);
    }
}
standaloneCommandsQuickAccess_GotoLineAction.ID = 'editor.action.quickCommand';
registerEditorAction(standaloneCommandsQuickAccess_GotoLineAction);
Registry.as(quickAccess_Extensions.Quickaccess).registerQuickAccessProvider({
    ctor: StandaloneCommandsQuickAccessProvider,
    prefix: StandaloneCommandsQuickAccessProvider.PREFIX,
    helpEntries: [{ description: QuickCommandNLS.quickCommandHelp, commandId: standaloneCommandsQuickAccess_GotoLineAction.ID }]
});

;// ../../node_modules/monaco-editor/esm/vs/platform/quickinput/browser/helpQuickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var helpQuickAccess_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var helpQuickAccess_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};






let HelpQuickAccessProvider = class HelpQuickAccessProvider {
    constructor(quickInputService, keybindingService) {
        this.quickInputService = quickInputService;
        this.keybindingService = keybindingService;
        this.registry = Registry.as(quickAccess_Extensions.Quickaccess);
    }
    provide(picker) {
        const disposables = new DisposableStore();
        // Open a picker with the selected value if picked
        disposables.add(picker.onDidAccept(() => {
            const [item] = picker.selectedItems;
            if (item) {
                this.quickInputService.quickAccess.show(item.prefix, { preserveValue: true });
            }
        }));
        // Also open a picker when we detect the user typed the exact
        // name of a provider (e.g. `?term` for terminals)
        disposables.add(picker.onDidChangeValue(value => {
            const providerDescriptor = this.registry.getQuickAccessProvider(value.substr(HelpQuickAccessProvider.PREFIX.length));
            if (providerDescriptor && providerDescriptor.prefix && providerDescriptor.prefix !== HelpQuickAccessProvider.PREFIX) {
                this.quickInputService.quickAccess.show(providerDescriptor.prefix, { preserveValue: true });
            }
        }));
        // Fill in all providers
        picker.items = this.getQuickAccessProviders();
        return disposables;
    }
    getQuickAccessProviders() {
        const providers = [];
        for (const provider of this.registry.getQuickAccessProviders().sort((providerA, providerB) => providerA.prefix.localeCompare(providerB.prefix))) {
            if (provider.prefix === HelpQuickAccessProvider.PREFIX) {
                continue; // exclude help which is already active
            }
            for (const helpEntry of provider.helpEntries) {
                const prefix = helpEntry.prefix || provider.prefix;
                const label = prefix || '\u2026' /* ... */;
                providers.push({
                    prefix,
                    label,
                    keybinding: helpEntry.commandId ? this.keybindingService.lookupKeybinding(helpEntry.commandId) : undefined,
                    ariaLabel: localize('helpPickAriaLabel', "{0}, {1}", label, helpEntry.description),
                    description: helpEntry.description
                });
            }
        }
        return providers;
    }
};
HelpQuickAccessProvider.PREFIX = '?';
HelpQuickAccessProvider = helpQuickAccess_decorate([
    helpQuickAccess_param(0, IQuickInputService),
    helpQuickAccess_param(1, IKeybindingService)
], HelpQuickAccessProvider);


;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




Registry.as(quickAccess_Extensions.Quickaccess).registerQuickAccessProvider({
    ctor: HelpQuickAccessProvider,
    prefix: '',
    helpEntries: [{ description: QuickHelpNLS.helpQuickAccessActionLabel }]
});

;// ../../node_modules/monaco-editor/esm/vs/base/common/fuzzyScorer.js




const NO_SCORE2 = [undefined, []];
function scoreFuzzy2(target, query, patternStart = 0, wordStart = 0) {
    // Score: multiple inputs
    const preparedQuery = query;
    if (preparedQuery.values && preparedQuery.values.length > 1) {
        return doScoreFuzzy2Multiple(target, preparedQuery.values, patternStart, wordStart);
    }
    // Score: single input
    return doScoreFuzzy2Single(target, query, patternStart, wordStart);
}
function doScoreFuzzy2Multiple(target, query, patternStart, wordStart) {
    let totalScore = 0;
    const totalMatches = [];
    for (const queryPiece of query) {
        const [score, matches] = doScoreFuzzy2Single(target, queryPiece, patternStart, wordStart);
        if (typeof score !== 'number') {
            // if a single query value does not match, return with
            // no score entirely, we require all queries to match
            return NO_SCORE2;
        }
        totalScore += score;
        totalMatches.push(...matches);
    }
    // if we have a score, ensure that the positions are
    // sorted in ascending order and distinct
    return [totalScore, normalizeMatches(totalMatches)];
}
function doScoreFuzzy2Single(target, query, patternStart, wordStart) {
    const score = fuzzyScore(query.original, query.originalLowercase, patternStart, target, target.toLowerCase(), wordStart, { firstMatchCanBeWeak: true, boostFullMatch: true });
    if (!score) {
        return NO_SCORE2;
    }
    return [score[0], createMatches(score)];
}
const NO_ITEM_SCORE = Object.freeze({ score: 0 });
function normalizeMatches(matches) {
    // sort matches by start to be able to normalize
    const sortedMatches = matches.sort((matchA, matchB) => {
        return matchA.start - matchB.start;
    });
    // merge matches that overlap
    const normalizedMatches = [];
    let currentMatch = undefined;
    for (const match of sortedMatches) {
        // if we have no current match or the matches
        // do not overlap, we take it as is and remember
        // it for future merging
        if (!currentMatch || !matchOverlaps(currentMatch, match)) {
            currentMatch = match;
            normalizedMatches.push(match);
        }
        // otherwise we merge the matches
        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; // A ends before B starts
    }
    if (matchB.end < matchA.start) {
        return false; // B ends before A starts
    }
    return true;
}
/*
 * If a query is wrapped in quotes, the user does not want to
 * use fuzzy search for this query.
 */
function queryExpectsExactMatch(query) {
    return query.startsWith('"') && query.endsWith('"');
}
/**
 * Helper function to prepare a search value for scoring by removing unwanted characters
 * and allowing to score on multiple pieces separated by whitespace character.
 */
const MULTIPLE_QUERY_VALUES_SEPARATOR = ' ';
function prepareQuery(original) {
    if (typeof original !== 'string') {
        original = '';
    }
    const originalLowercase = original.toLowerCase();
    const { pathNormalized, normalized, normalizedLowercase } = normalizeQuery(original);
    const containsPathSeparator = pathNormalized.indexOf(path_sep) >= 0;
    const expectExactMatch = queryExpectsExactMatch(original);
    let values = undefined;
    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 (isWindows) {
        pathNormalized = original.replace(/\//g, path_sep); // Help Windows users to search for paths when using slash
    }
    else {
        pathNormalized = original.replace(/\\/g, path_sep); // Help macOS/Linux users to search for paths when using backslash
    }
    // we remove quotes here because quotes are used for exact match search
    const normalized = stripWildcards(pathNormalized).replace(/\s|"/g, '');
    return {
        pathNormalized,
        normalized,
        normalizedLowercase: normalized.toLowerCase()
    };
}
function pieceToQuery(arg1) {
    if (Array.isArray(arg1)) {
        return prepareQuery(arg1.map(piece => piece.original).join(MULTIPLE_QUERY_VALUES_SEPARATOR));
    }
    return prepareQuery(arg1.original);
}
//#endregion

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/quickAccess/browser/gotoSymbolQuickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var gotoSymbolQuickAccess_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var gotoSymbolQuickAccess_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var gotoSymbolQuickAccess_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};













let AbstractGotoSymbolQuickAccessProvider = class AbstractGotoSymbolQuickAccessProvider extends AbstractEditorNavigationQuickAccessProvider {
    constructor(_languageFeaturesService, _outlineModelService, options = Object.create(null)) {
        super(options);
        this._languageFeaturesService = _languageFeaturesService;
        this._outlineModelService = _outlineModelService;
        this.options = options;
        this.options.canAcceptInBackground = true;
    }
    provideWithoutTextEditor(picker) {
        this.provideLabelPick(picker, localize('cannotRunGotoSymbolWithoutEditor', "To go to a symbol, first open a text editor with symbol information."));
        return Disposable.None;
    }
    provideWithTextEditor(context, picker, token) {
        const editor = context.editor;
        const model = this.getModel(editor);
        if (!model) {
            return Disposable.None;
        }
        // Provide symbols from model if available in registry
        if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
            return this.doProvideWithEditorSymbols(context, model, picker, token);
        }
        // Otherwise show an entry for a model without registry
        // But give a chance to resolve the symbols at a later
        // point if possible
        return this.doProvideWithoutEditorSymbols(context, model, picker, token);
    }
    doProvideWithoutEditorSymbols(context, model, picker, token) {
        const disposables = new DisposableStore();
        // Generic pick for not having any symbol information
        this.provideLabelPick(picker, localize('cannotRunGotoSymbolWithoutSymbolProvider', "The active text editor does not provide symbol information."));
        // Wait for changes to the registry and see if eventually
        // we do get symbols. This can happen if the picker is opened
        // very early after the model has loaded but before the
        // language registry is ready.
        // https://github.com/microsoft/vscode/issues/70607
        (() => gotoSymbolQuickAccess_awaiter(this, void 0, void 0, function* () {
            const result = yield this.waitForLanguageSymbolRegistry(model, disposables);
            if (!result || token.isCancellationRequested) {
                return;
            }
            disposables.add(this.doProvideWithEditorSymbols(context, model, picker, token));
        }))();
        return disposables;
    }
    provideLabelPick(picker, label) {
        picker.items = [{ label, index: 0, kind: 14 /* SymbolKind.String */ }];
        picker.ariaLabel = label;
    }
    waitForLanguageSymbolRegistry(model, disposables) {
        return gotoSymbolQuickAccess_awaiter(this, void 0, void 0, function* () {
            if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
                return true;
            }
            const symbolProviderRegistryPromise = new DeferredPromise();
            // Resolve promise when registry knows model
            const symbolProviderListener = disposables.add(this._languageFeaturesService.documentSymbolProvider.onDidChange(() => {
                if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
                    symbolProviderListener.dispose();
                    symbolProviderRegistryPromise.complete(true);
                }
            }));
            // Resolve promise when we get disposed too
            disposables.add(toDisposable(() => symbolProviderRegistryPromise.complete(false)));
            return symbolProviderRegistryPromise.p;
        });
    }
    doProvideWithEditorSymbols(context, model, picker, token) {
        var _a;
        const editor = context.editor;
        const disposables = new DisposableStore();
        // Goto symbol once picked
        disposables.add(picker.onDidAccept(event => {
            const [item] = picker.selectedItems;
            if (item && item.range) {
                this.gotoLocation(context, { range: item.range.selection, keyMods: picker.keyMods, preserveFocus: event.inBackground });
                if (!event.inBackground) {
                    picker.hide();
                }
            }
        }));
        // Goto symbol side by side if enabled
        disposables.add(picker.onDidTriggerItemButton(({ item }) => {
            if (item && item.range) {
                this.gotoLocation(context, { range: item.range.selection, keyMods: picker.keyMods, forceSideBySide: true });
                picker.hide();
            }
        }));
        // Resolve symbols from document once and reuse this
        // request for all filtering and typing then on
        const symbolsPromise = this.getDocumentSymbols(model, token);
        // Set initial picks and update on type
        let picksCts = undefined;
        const updatePickerItems = (positionToEnclose) => gotoSymbolQuickAccess_awaiter(this, void 0, void 0, function* () {
            // Cancel any previous ask for picks and busy
            picksCts === null || picksCts === void 0 ? void 0 : picksCts.dispose(true);
            picker.busy = false;
            // Create new cancellation source for this run
            picksCts = new CancellationTokenSource(token);
            // Collect symbol picks
            picker.busy = true;
            try {
                const query = prepareQuery(picker.value.substr(AbstractGotoSymbolQuickAccessProvider.PREFIX.length).trim());
                const items = yield this.doGetSymbolPicks(symbolsPromise, query, undefined, picksCts.token);
                if (token.isCancellationRequested) {
                    return;
                }
                if (items.length > 0) {
                    picker.items = items;
                    if (positionToEnclose && query.original.length === 0) {
                        const candidate = findLast(items, item => Boolean(item.type !== 'separator' && item.range && Range.containsPosition(item.range.decoration, positionToEnclose)));
                        if (candidate) {
                            picker.activeItems = [candidate];
                        }
                    }
                }
                else {
                    if (query.original.length > 0) {
                        this.provideLabelPick(picker, localize('noMatchingSymbolResults', "No matching editor symbols"));
                    }
                    else {
                        this.provideLabelPick(picker, localize('noSymbolResults', "No editor symbols"));
                    }
                }
            }
            finally {
                if (!token.isCancellationRequested) {
                    picker.busy = false;
                }
            }
        });
        disposables.add(picker.onDidChangeValue(() => updatePickerItems(undefined)));
        updatePickerItems((_a = editor.getSelection()) === null || _a === void 0 ? void 0 : _a.getPosition());
        // Reveal and decorate when active item changes
        // However, ignore the very first two events so that
        // opening the picker is not immediately revealing
        // and decorating the first entry.
        let ignoreFirstActiveEvent = 2;
        disposables.add(picker.onDidChangeActive(() => {
            const [item] = picker.activeItems;
            if (item && item.range) {
                if (ignoreFirstActiveEvent-- > 0) {
                    return;
                }
                // Reveal
                editor.revealRangeInCenter(item.range.selection, 0 /* ScrollType.Smooth */);
                // Decorate
                this.addDecorations(editor, item.range.decoration);
            }
        }));
        return disposables;
    }
    doGetSymbolPicks(symbolsPromise, query, options, token) {
        return gotoSymbolQuickAccess_awaiter(this, void 0, void 0, function* () {
            const symbols = yield symbolsPromise;
            if (token.isCancellationRequested) {
                return [];
            }
            const filterBySymbolKind = query.original.indexOf(AbstractGotoSymbolQuickAccessProvider.SCOPE_PREFIX) === 0;
            const filterPos = filterBySymbolKind ? 1 : 0;
            // Split between symbol and container query
            let symbolQuery;
            let containerQuery;
            if (query.values && query.values.length > 1) {
                symbolQuery = pieceToQuery(query.values[0]); // symbol: only match on first part
                containerQuery = pieceToQuery(query.values.slice(1)); // container: match on all but first parts
            }
            else {
                symbolQuery = query;
            }
            // Convert to symbol picks and apply filtering
            const filteredSymbolPicks = [];
            for (let index = 0; index < symbols.length; index++) {
                const symbol = symbols[index];
                const symbolLabel = trim(symbol.name);
                const symbolLabelWithIcon = `$(${SymbolKinds.toIcon(symbol.kind).id}) ${symbolLabel}`;
                const symbolLabelIconOffset = symbolLabelWithIcon.length - symbolLabel.length;
                let containerLabel = symbol.containerName;
                if (options === null || options === void 0 ? void 0 : options.extraContainerLabel) {
                    if (containerLabel) {
                        containerLabel = `${options.extraContainerLabel} • ${containerLabel}`;
                    }
                    else {
                        containerLabel = options.extraContainerLabel;
                    }
                }
                let symbolScore = undefined;
                let symbolMatches = undefined;
                let containerScore = undefined;
                let containerMatches = undefined;
                if (query.original.length > filterPos) {
                    // First: try to score on the entire query, it is possible that
                    // the symbol matches perfectly (e.g. searching for "change log"
                    // can be a match on a markdown symbol "change log"). In that
                    // case we want to skip the container query altogether.
                    let skipContainerQuery = false;
                    if (symbolQuery !== query) {
                        [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon, Object.assign(Object.assign({}, query), { values: undefined /* disable multi-query support */ }), filterPos, symbolLabelIconOffset);
                        if (typeof symbolScore === 'number') {
                            skipContainerQuery = true; // since we consumed the query, skip any container matching
                        }
                    }
                    // Otherwise: score on the symbol query and match on the container later
                    if (typeof symbolScore !== 'number') {
                        [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon, symbolQuery, filterPos, symbolLabelIconOffset);
                        if (typeof symbolScore !== 'number') {
                            continue;
                        }
                    }
                    // Score by container if specified
                    if (!skipContainerQuery && containerQuery) {
                        if (containerLabel && containerQuery.original.length > 0) {
                            [containerScore, containerMatches] = scoreFuzzy2(containerLabel, containerQuery);
                        }
                        if (typeof containerScore !== 'number') {
                            continue;
                        }
                        if (typeof symbolScore === 'number') {
                            symbolScore += containerScore; // boost symbolScore by containerScore
                        }
                    }
                }
                const deprecated = symbol.tags && symbol.tags.indexOf(1 /* SymbolTag.Deprecated */) >= 0;
                filteredSymbolPicks.push({
                    index,
                    kind: symbol.kind,
                    score: symbolScore,
                    label: symbolLabelWithIcon,
                    ariaLabel: symbolLabel,
                    description: containerLabel,
                    highlights: deprecated ? undefined : {
                        label: symbolMatches,
                        description: containerMatches
                    },
                    range: {
                        selection: Range.collapseToStart(symbol.selectionRange),
                        decoration: symbol.range
                    },
                    strikethrough: deprecated,
                    buttons: (() => {
                        var _a, _b;
                        const openSideBySideDirection = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.openSideBySideDirection) ? (_b = this.options) === null || _b === void 0 ? void 0 : _b.openSideBySideDirection() : undefined;
                        if (!openSideBySideDirection) {
                            return undefined;
                        }
                        return [
                            {
                                iconClass: openSideBySideDirection === 'right' ? Codicon.splitHorizontal.classNames : Codicon.splitVertical.classNames,
                                tooltip: openSideBySideDirection === 'right' ? localize('openToSide', "Open to the Side") : localize('openToBottom', "Open to the Bottom")
                            }
                        ];
                    })()
                });
            }
            // Sort by score
            const sortedFilteredSymbolPicks = filteredSymbolPicks.sort((symbolA, symbolB) => filterBySymbolKind ?
                this.compareByKindAndScore(symbolA, symbolB) :
                this.compareByScore(symbolA, symbolB));
            // Add separator for types
            // - @  only total number of symbols
            // - @: grouped by symbol kind
            let symbolPicks = [];
            if (filterBySymbolKind) {
                let lastSymbolKind = undefined;
                let lastSeparator = undefined;
                let lastSymbolKindCounter = 0;
                function updateLastSeparatorLabel() {
                    if (lastSeparator && typeof lastSymbolKind === 'number' && lastSymbolKindCounter > 0) {
                        lastSeparator.label = format(NLS_SYMBOL_KIND_CACHE[lastSymbolKind] || FALLBACK_NLS_SYMBOL_KIND, lastSymbolKindCounter);
                    }
                }
                for (const symbolPick of sortedFilteredSymbolPicks) {
                    // Found new kind
                    if (lastSymbolKind !== symbolPick.kind) {
                        // Update last separator with number of symbols we found for kind
                        updateLastSeparatorLabel();
                        lastSymbolKind = symbolPick.kind;
                        lastSymbolKindCounter = 1;
                        // Add new separator for new kind
                        lastSeparator = { type: 'separator' };
                        symbolPicks.push(lastSeparator);
                    }
                    // Existing kind, keep counting
                    else {
                        lastSymbolKindCounter++;
                    }
                    // Add to final result
                    symbolPicks.push(symbolPick);
                }
                // Update last separator with number of symbols we found for kind
                updateLastSeparatorLabel();
            }
            else if (sortedFilteredSymbolPicks.length > 0) {
                symbolPicks = [
                    { label: localize('symbols', "symbols ({0})", filteredSymbolPicks.length), type: 'separator' },
                    ...sortedFilteredSymbolPicks
                ];
            }
            return symbolPicks;
        });
    }
    compareByScore(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;
    }
    compareByKindAndScore(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;
        // Sort by type first if scoped search
        const result = kindA.localeCompare(kindB);
        if (result === 0) {
            return this.compareByScore(symbolA, symbolB);
        }
        return result;
    }
    getDocumentSymbols(document, token) {
        return gotoSymbolQuickAccess_awaiter(this, void 0, void 0, function* () {
            const model = yield this._outlineModelService.getOrCreate(document, token);
            return token.isCancellationRequested ? [] : model.asListOfDocumentSymbols();
        });
    }
};
AbstractGotoSymbolQuickAccessProvider.PREFIX = '@';
AbstractGotoSymbolQuickAccessProvider.SCOPE_PREFIX = ':';
AbstractGotoSymbolQuickAccessProvider.PREFIX_BY_CATEGORY = `${AbstractGotoSymbolQuickAccessProvider.PREFIX}${AbstractGotoSymbolQuickAccessProvider.SCOPE_PREFIX}`;
AbstractGotoSymbolQuickAccessProvider = gotoSymbolQuickAccess_decorate([
    gotoSymbolQuickAccess_param(0, ILanguageFeaturesService),
    gotoSymbolQuickAccess_param(1, IOutlineModelService)
], AbstractGotoSymbolQuickAccessProvider);

// #region NLS Helpers
const FALLBACK_NLS_SYMBOL_KIND = localize('property', "properties ({0})");
const NLS_SYMBOL_KIND_CACHE = {
    [5 /* SymbolKind.Method */]: localize('method', "methods ({0})"),
    [11 /* SymbolKind.Function */]: localize('function', "functions ({0})"),
    [8 /* SymbolKind.Constructor */]: localize('_constructor', "constructors ({0})"),
    [12 /* SymbolKind.Variable */]: localize('variable', "variables ({0})"),
    [4 /* SymbolKind.Class */]: localize('class', "classes ({0})"),
    [22 /* SymbolKind.Struct */]: localize('struct', "structs ({0})"),
    [23 /* SymbolKind.Event */]: localize('event', "events ({0})"),
    [24 /* SymbolKind.Operator */]: localize('operator', "operators ({0})"),
    [10 /* SymbolKind.Interface */]: localize('interface', "interfaces ({0})"),
    [2 /* SymbolKind.Namespace */]: localize('namespace', "namespaces ({0})"),
    [3 /* SymbolKind.Package */]: localize('package', "packages ({0})"),
    [25 /* SymbolKind.TypeParameter */]: localize('typeParameter', "type parameters ({0})"),
    [1 /* SymbolKind.Module */]: localize('modules', "modules ({0})"),
    [6 /* SymbolKind.Property */]: localize('property', "properties ({0})"),
    [9 /* SymbolKind.Enum */]: localize('enum', "enumerations ({0})"),
    [21 /* SymbolKind.EnumMember */]: localize('enumMember', "enumeration members ({0})"),
    [14 /* SymbolKind.String */]: localize('string', "strings ({0})"),
    [0 /* SymbolKind.File */]: localize('file', "files ({0})"),
    [17 /* SymbolKind.Array */]: localize('array', "arrays ({0})"),
    [15 /* SymbolKind.Number */]: localize('number', "numbers ({0})"),
    [16 /* SymbolKind.Boolean */]: localize('boolean', "booleans ({0})"),
    [18 /* SymbolKind.Object */]: localize('object', "objects ({0})"),
    [19 /* SymbolKind.Key */]: localize('key', "keys ({0})"),
    [7 /* SymbolKind.Field */]: localize('field', "fields ({0})"),
    [13 /* SymbolKind.Constant */]: localize('constant', "constants ({0})")
};
//#endregion

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickAccess/standaloneGotoSymbolQuickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var standaloneGotoSymbolQuickAccess_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var standaloneGotoSymbolQuickAccess_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
 // The codicon symbol styles are defined here and must be loaded
 // The codicon symbol colors are defined here and must be loaded to get colors












let StandaloneGotoSymbolQuickAccessProvider = class StandaloneGotoSymbolQuickAccessProvider extends AbstractGotoSymbolQuickAccessProvider {
    constructor(editorService, languageFeaturesService, outlineModelService) {
        super(languageFeaturesService, outlineModelService);
        this.editorService = editorService;
        this.onDidActiveTextEditorControlChange = Event.None;
    }
    get activeTextEditorControl() {
        return withNullAsUndefined(this.editorService.getFocusedCodeEditor());
    }
};
StandaloneGotoSymbolQuickAccessProvider = standaloneGotoSymbolQuickAccess_decorate([
    standaloneGotoSymbolQuickAccess_param(0, ICodeEditorService),
    standaloneGotoSymbolQuickAccess_param(1, ILanguageFeaturesService),
    standaloneGotoSymbolQuickAccess_param(2, IOutlineModelService)
], StandaloneGotoSymbolQuickAccessProvider);

class GotoSymbolAction extends EditorAction {
    constructor() {
        super({
            id: GotoSymbolAction.ID,
            label: QuickOutlineNLS.quickOutlineActionLabel,
            alias: 'Go to Symbol...',
            precondition: EditorContextKeys.hasDocumentSymbolProvider,
            kbOpts: {
                kbExpr: EditorContextKeys.focus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 45 /* KeyCode.KeyO */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            contextMenuOpts: {
                group: 'navigation',
                order: 3
            }
        });
    }
    run(accessor) {
        accessor.get(IQuickInputService).quickAccess.show(AbstractGotoSymbolQuickAccessProvider.PREFIX);
    }
}
GotoSymbolAction.ID = 'editor.action.quickOutline';
registerEditorAction(GotoSymbolAction);
Registry.as(quickAccess_Extensions.Quickaccess).registerQuickAccessProvider({
    ctor: StandaloneGotoSymbolQuickAccessProvider,
    prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX,
    helpEntries: [
        { description: QuickOutlineNLS.quickOutlineActionLabel, prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX, commandId: GotoSymbolAction.ID },
        { description: QuickOutlineNLS.quickOutlineByCategoryActionLabel, prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX_BY_CATEGORY }
    ]
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/readOnlyMessage/browser/contribution.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




class ReadOnlyMessageController extends Disposable {
    constructor(editor) {
        super();
        this.editor = editor;
        this._register(this.editor.onDidAttemptReadOnlyEdit(() => this._onDidAttemptReadOnlyEdit()));
    }
    _onDidAttemptReadOnlyEdit() {
        const messageController = MessageController.get(this.editor);
        if (messageController && this.editor.hasModel()) {
            if (this.editor.isSimpleWidget) {
                messageController.showMessage(localize('editor.simple.readonly', "Cannot edit in read-only input"), this.editor.getPosition());
            }
            else {
                messageController.showMessage(localize('editor.readonly', "Cannot edit in read-only editor"), this.editor.getPosition());
            }
        }
    }
}
ReadOnlyMessageController.ID = 'editor.contrib.readOnlyMessageController';
registerEditorContribution(ReadOnlyMessageController.ID, ReadOnlyMessageController);

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var standaloneReferenceSearch_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var standaloneReferenceSearch_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};








let StandaloneReferencesController = class StandaloneReferencesController extends ReferencesController {
    constructor(editor, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService) {
        super(true, editor, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService);
    }
};
StandaloneReferencesController = standaloneReferenceSearch_decorate([
    standaloneReferenceSearch_param(1, IContextKeyService),
    standaloneReferenceSearch_param(2, ICodeEditorService),
    standaloneReferenceSearch_param(3, INotificationService),
    standaloneReferenceSearch_param(4, IInstantiationService),
    standaloneReferenceSearch_param(5, IStorageService),
    standaloneReferenceSearch_param(6, IConfigurationService)
], StandaloneReferencesController);

registerEditorContribution(ReferencesController.ID, StandaloneReferencesController);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/textResourceConfiguration.js

const ITextResourceConfigurationService = createDecorator('textResourceConfigurationService');
const ITextResourcePropertiesService = createDecorator('textResourcePropertiesService');

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/rename/browser/renameInputField.css
var renameInputField = __webpack_require__(79162);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/rename/browser/renameInputField.css

      
      
      
      
      
      
      
      
      

var renameInputField_options = {};

renameInputField_options.styleTagTransform = (styleTagTransform_default());
renameInputField_options.setAttributes = (setAttributesWithoutAttributes_default());

      renameInputField_options.insert = insertBySelector_default().bind(null, "head");
    
renameInputField_options.domAPI = (styleDomAPI_default());
renameInputField_options.insertStyleElement = (insertStyleElement_default());

var renameInputField_update = injectStylesIntoStyleTag_default()(renameInputField/* default */.A, renameInputField_options);




       /* harmony default export */ const browser_renameInputField = (renameInputField/* default */.A && renameInputField/* default */.A.locals ? renameInputField/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/rename/browser/renameInputField.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var renameInputField_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var renameInputField_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};








const CONTEXT_RENAME_INPUT_VISIBLE = new RawContextKey('renameInputVisible', false, localize('renameInputVisible', "Whether the rename input widget is visible"));
let RenameInputField = class RenameInputField {
    constructor(_editor, _acceptKeybindings, _themeService, _keybindingService, contextKeyService) {
        this._editor = _editor;
        this._acceptKeybindings = _acceptKeybindings;
        this._themeService = _themeService;
        this._keybindingService = _keybindingService;
        this._disposables = new DisposableStore();
        this.allowEditorOverflow = true;
        this._visibleContextKey = CONTEXT_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
        this._editor.addContentWidget(this);
        this._disposables.add(this._editor.onDidChangeConfiguration(e => {
            if (e.hasChanged(46 /* EditorOption.fontInfo */)) {
                this._updateFont();
            }
        }));
        this._disposables.add(_themeService.onDidColorThemeChange(this._updateStyles, this));
    }
    dispose() {
        this._disposables.dispose();
        this._editor.removeContentWidget(this);
    }
    getId() {
        return '__renameInputWidget';
    }
    getDomNode() {
        if (!this._domNode) {
            this._domNode = document.createElement('div');
            this._domNode.className = 'monaco-editor rename-box';
            this._input = document.createElement('input');
            this._input.className = 'rename-input';
            this._input.type = 'text';
            this._input.setAttribute('aria-label', localize('renameAriaLabel', "Rename input. Type new name and press Enter to commit."));
            this._domNode.appendChild(this._input);
            this._label = document.createElement('div');
            this._label.className = 'rename-label';
            this._domNode.appendChild(this._label);
            const updateLabel = () => {
                var _a, _b;
                const [accept, preview] = this._acceptKeybindings;
                this._keybindingService.lookupKeybinding(accept);
                this._label.innerText = localize({ key: 'label', comment: ['placeholders are keybindings, e.g "F2 to Rename, Shift+F2 to Preview"'] }, "{0} to Rename, {1} to Preview", (_a = this._keybindingService.lookupKeybinding(accept)) === null || _a === void 0 ? void 0 : _a.getLabel(), (_b = this._keybindingService.lookupKeybinding(preview)) === null || _b === void 0 ? void 0 : _b.getLabel());
            };
            updateLabel();
            this._disposables.add(this._keybindingService.onDidUpdateKeybindings(updateLabel));
            this._updateFont();
            this._updateStyles(this._themeService.getColorTheme());
        }
        return this._domNode;
    }
    _updateStyles(theme) {
        var _a, _b, _c, _d;
        if (!this._input || !this._domNode) {
            return;
        }
        const widgetShadowColor = theme.getColor(widgetShadow);
        this._domNode.style.backgroundColor = String((_a = theme.getColor(editorWidgetBackground)) !== null && _a !== void 0 ? _a : '');
        this._domNode.style.boxShadow = widgetShadowColor ? ` 0 0 8px 2px ${widgetShadowColor}` : '';
        this._domNode.style.color = String((_b = theme.getColor(inputForeground)) !== null && _b !== void 0 ? _b : '');
        this._input.style.backgroundColor = String((_c = theme.getColor(inputBackground)) !== null && _c !== void 0 ? _c : '');
        // this._input.style.color = String(theme.getColor(inputForeground) ?? '');
        const border = theme.getColor(inputBorder);
        this._input.style.borderWidth = border ? '1px' : '0px';
        this._input.style.borderStyle = border ? 'solid' : 'none';
        this._input.style.borderColor = (_d = border === null || border === void 0 ? void 0 : border.toString()) !== null && _d !== void 0 ? _d : 'none';
    }
    _updateFont() {
        if (!this._input || !this._label) {
            return;
        }
        const fontInfo = this._editor.getOption(46 /* EditorOption.fontInfo */);
        this._input.style.fontFamily = fontInfo.fontFamily;
        this._input.style.fontWeight = fontInfo.fontWeight;
        this._input.style.fontSize = `${fontInfo.fontSize}px`;
        this._label.style.fontSize = `${fontInfo.fontSize * 0.8}px`;
    }
    getPosition() {
        if (!this._visible) {
            return null;
        }
        return {
            position: this._position,
            preference: [2 /* ContentWidgetPositionPreference.BELOW */, 1 /* ContentWidgetPositionPreference.ABOVE */]
        };
    }
    afterRender(position) {
        if (!position) {
            // cancel rename when input widget isn't rendered anymore
            this.cancelInput(true);
        }
    }
    acceptInput(wantsPreview) {
        var _a;
        (_a = this._currentAcceptInput) === null || _a === void 0 ? void 0 : _a.call(this, wantsPreview);
    }
    cancelInput(focusEditor) {
        var _a;
        (_a = this._currentCancelInput) === null || _a === void 0 ? void 0 : _a.call(this, focusEditor);
    }
    getInput(where, value, selectionStart, selectionEnd, supportPreview, token) {
        this._domNode.classList.toggle('preview', supportPreview);
        this._position = new Position(where.startLineNumber, where.startColumn);
        this._input.value = value;
        this._input.setAttribute('selectionStart', selectionStart.toString());
        this._input.setAttribute('selectionEnd', selectionEnd.toString());
        this._input.size = Math.max((where.endColumn - where.startColumn) * 1.1, 20);
        const disposeOnDone = new DisposableStore();
        return new Promise(resolve => {
            this._currentCancelInput = (focusEditor) => {
                this._currentAcceptInput = undefined;
                this._currentCancelInput = undefined;
                resolve(focusEditor);
                return true;
            };
            this._currentAcceptInput = (wantsPreview) => {
                if (this._input.value.trim().length === 0 || this._input.value === value) {
                    // empty or whitespace only or not changed
                    this.cancelInput(true);
                    return;
                }
                this._currentAcceptInput = undefined;
                this._currentCancelInput = undefined;
                resolve({
                    newName: this._input.value,
                    wantsPreview: supportPreview && wantsPreview
                });
            };
            disposeOnDone.add(token.onCancellationRequested(() => this.cancelInput(true)));
            disposeOnDone.add(this._editor.onDidBlurEditorWidget(() => this.cancelInput(false)));
            this._show();
        }).finally(() => {
            disposeOnDone.dispose();
            this._hide();
        });
    }
    _show() {
        this._editor.revealLineInCenterIfOutsideViewport(this._position.lineNumber, 0 /* ScrollType.Smooth */);
        this._visible = true;
        this._visibleContextKey.set(true);
        this._editor.layoutContentWidget(this);
        setTimeout(() => {
            this._input.focus();
            this._input.setSelectionRange(parseInt(this._input.getAttribute('selectionStart')), parseInt(this._input.getAttribute('selectionEnd')));
        }, 100);
    }
    _hide() {
        this._visible = false;
        this._visibleContextKey.reset();
        this._editor.layoutContentWidget(this);
    }
};
RenameInputField = renameInputField_decorate([
    renameInputField_param(2, IThemeService),
    renameInputField_param(3, IKeybindingService),
    renameInputField_param(4, IContextKeyService)
], RenameInputField);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/rename/browser/rename.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var rename_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var rename_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var rename_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};


























class RenameSkeleton {
    constructor(model, position, registry) {
        this.model = model;
        this.position = position;
        this._providerRenameIdx = 0;
        this._providers = registry.ordered(model);
    }
    hasProvider() {
        return this._providers.length > 0;
    }
    resolveRenameLocation(token) {
        return rename_awaiter(this, void 0, void 0, function* () {
            const rejects = [];
            for (this._providerRenameIdx = 0; this._providerRenameIdx < this._providers.length; this._providerRenameIdx++) {
                const provider = this._providers[this._providerRenameIdx];
                if (!provider.resolveRenameLocation) {
                    break;
                }
                const res = yield provider.resolveRenameLocation(this.model, this.position, token);
                if (!res) {
                    continue;
                }
                if (res.rejectReason) {
                    rejects.push(res.rejectReason);
                    continue;
                }
                return res;
            }
            const word = this.model.getWordAtPosition(this.position);
            if (!word) {
                return {
                    range: Range.fromPositions(this.position),
                    text: '',
                    rejectReason: rejects.length > 0 ? rejects.join('\n') : undefined
                };
            }
            return {
                range: new Range(this.position.lineNumber, word.startColumn, this.position.lineNumber, word.endColumn),
                text: word.word,
                rejectReason: rejects.length > 0 ? rejects.join('\n') : undefined
            };
        });
    }
    provideRenameEdits(newName, token) {
        return rename_awaiter(this, void 0, void 0, function* () {
            return this._provideRenameEdits(newName, this._providerRenameIdx, [], token);
        });
    }
    _provideRenameEdits(newName, i, rejects, token) {
        return rename_awaiter(this, void 0, void 0, function* () {
            const provider = this._providers[i];
            if (!provider) {
                return {
                    edits: [],
                    rejectReason: rejects.join('\n')
                };
            }
            const result = yield provider.provideRenameEdits(this.model, this.position, newName, token);
            if (!result) {
                return this._provideRenameEdits(newName, i + 1, rejects.concat(localize('no result', "No result.")), token);
            }
            else if (result.rejectReason) {
                return this._provideRenameEdits(newName, i + 1, rejects.concat(result.rejectReason), token);
            }
            return result;
        });
    }
}
function rename(registry, model, position, newName) {
    return rename_awaiter(this, void 0, void 0, function* () {
        const skeleton = new RenameSkeleton(model, position, registry);
        const loc = yield skeleton.resolveRenameLocation(CancellationToken.None);
        if (loc === null || loc === void 0 ? void 0 : loc.rejectReason) {
            return { edits: [], rejectReason: loc.rejectReason };
        }
        return skeleton.provideRenameEdits(newName, CancellationToken.None);
    });
}
// ---  register actions and commands
let RenameController = class RenameController {
    constructor(editor, _instaService, _notificationService, _bulkEditService, _progressService, _logService, _configService, _languageFeaturesService) {
        this.editor = editor;
        this._instaService = _instaService;
        this._notificationService = _notificationService;
        this._bulkEditService = _bulkEditService;
        this._progressService = _progressService;
        this._logService = _logService;
        this._configService = _configService;
        this._languageFeaturesService = _languageFeaturesService;
        this._disposableStore = new DisposableStore();
        this._cts = new CancellationTokenSource();
        this._renameInputField = this._disposableStore.add(new IdleValue(() => this._disposableStore.add(this._instaService.createInstance(RenameInputField, this.editor, ['acceptRenameInput', 'acceptRenameInputWithPreview']))));
    }
    static get(editor) {
        return editor.getContribution(RenameController.ID);
    }
    dispose() {
        this._disposableStore.dispose();
        this._cts.dispose(true);
    }
    run() {
        var _a, _b;
        return rename_awaiter(this, void 0, void 0, function* () {
            this._cts.dispose(true);
            if (!this.editor.hasModel()) {
                return undefined;
            }
            const position = this.editor.getPosition();
            const skeleton = new RenameSkeleton(this.editor.getModel(), position, this._languageFeaturesService.renameProvider);
            if (!skeleton.hasProvider()) {
                return undefined;
            }
            this._cts = new EditorStateCancellationTokenSource(this.editor, 4 /* CodeEditorStateFlag.Position */ | 1 /* CodeEditorStateFlag.Value */);
            // resolve rename location
            let loc;
            try {
                const resolveLocationOperation = skeleton.resolveRenameLocation(this._cts.token);
                this._progressService.showWhile(resolveLocationOperation, 250);
                loc = yield resolveLocationOperation;
            }
            catch (e) {
                (_a = MessageController.get(this.editor)) === null || _a === void 0 ? void 0 : _a.showMessage(e || localize('resolveRenameLocationFailed', "An unknown error occurred while resolving rename location"), position);
                return undefined;
            }
            if (!loc) {
                return undefined;
            }
            if (loc.rejectReason) {
                (_b = MessageController.get(this.editor)) === null || _b === void 0 ? void 0 : _b.showMessage(loc.rejectReason, position);
                return undefined;
            }
            if (this._cts.token.isCancellationRequested) {
                return undefined;
            }
            this._cts.dispose();
            this._cts = new EditorStateCancellationTokenSource(this.editor, 4 /* CodeEditorStateFlag.Position */ | 1 /* CodeEditorStateFlag.Value */, loc.range);
            // do rename at location
            const selection = this.editor.getSelection();
            let selectionStart = 0;
            let selectionEnd = loc.text.length;
            if (!Range.isEmpty(selection) && !Range.spansMultipleLines(selection) && Range.containsRange(loc.range, selection)) {
                selectionStart = Math.max(0, selection.startColumn - loc.range.startColumn);
                selectionEnd = Math.min(loc.range.endColumn, selection.endColumn) - loc.range.startColumn;
            }
            const supportPreview = this._bulkEditService.hasPreviewHandler() && this._configService.getValue(this.editor.getModel().uri, 'editor.rename.enablePreview');
            const inputFieldResult = yield this._renameInputField.value.getInput(loc.range, loc.text, selectionStart, selectionEnd, supportPreview, this._cts.token);
            // no result, only hint to focus the editor or not
            if (typeof inputFieldResult === 'boolean') {
                if (inputFieldResult) {
                    this.editor.focus();
                }
                return undefined;
            }
            this.editor.focus();
            const renameOperation = raceCancellation(skeleton.provideRenameEdits(inputFieldResult.newName, this._cts.token), this._cts.token).then((renameResult) => rename_awaiter(this, void 0, void 0, function* () {
                if (!renameResult || !this.editor.hasModel()) {
                    return;
                }
                if (renameResult.rejectReason) {
                    this._notificationService.info(renameResult.rejectReason);
                    return;
                }
                // collapse selection to active end
                this.editor.setSelection(Range.fromPositions(this.editor.getSelection().getPosition()));
                this._bulkEditService.apply(ResourceEdit.convert(renameResult), {
                    editor: this.editor,
                    showPreview: inputFieldResult.wantsPreview,
                    label: localize('label', "Renaming '{0}' to '{1}'", loc === null || loc === void 0 ? void 0 : loc.text, inputFieldResult.newName),
                    code: 'undoredo.rename',
                    quotableLabel: localize('quotableLabel', "Renaming {0} to {1}", loc === null || loc === void 0 ? void 0 : loc.text, inputFieldResult.newName),
                    respectAutoSaveConfig: true
                }).then(result => {
                    if (result.ariaSummary) {
                        aria_alert(localize('aria', "Successfully renamed '{0}' to '{1}'. Summary: {2}", loc.text, inputFieldResult.newName, result.ariaSummary));
                    }
                }).catch(err => {
                    this._notificationService.error(localize('rename.failedApply', "Rename failed to apply edits"));
                    this._logService.error(err);
                });
            }), err => {
                this._notificationService.error(localize('rename.failed', "Rename failed to compute edits"));
                this._logService.error(err);
            });
            this._progressService.showWhile(renameOperation, 250);
            return renameOperation;
        });
    }
    acceptRenameInput(wantsPreview) {
        this._renameInputField.value.acceptInput(wantsPreview);
    }
    cancelRenameInput() {
        this._renameInputField.value.cancelInput(true);
    }
};
RenameController.ID = 'editor.contrib.renameController';
RenameController = rename_decorate([
    rename_param(1, IInstantiationService),
    rename_param(2, INotificationService),
    rename_param(3, IBulkEditService),
    rename_param(4, IEditorProgressService),
    rename_param(5, ILogService),
    rename_param(6, ITextResourceConfigurationService),
    rename_param(7, ILanguageFeaturesService)
], RenameController);
// ---- action implementation
class RenameAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.rename',
            label: localize('rename.label', "Rename Symbol"),
            alias: 'Rename Symbol',
            precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasRenameProvider),
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 60 /* KeyCode.F2 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            contextMenuOpts: {
                group: '1_modification',
                order: 1.1
            }
        });
    }
    runCommand(accessor, args) {
        const editorService = accessor.get(ICodeEditorService);
        const [uri, pos] = Array.isArray(args) && args || [undefined, undefined];
        if (URI.isUri(uri) && Position.isIPosition(pos)) {
            return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then(editor => {
                if (!editor) {
                    return;
                }
                editor.setPosition(pos);
                editor.invokeWithinContext(accessor => {
                    this.reportTelemetry(accessor, editor);
                    return this.run(accessor, editor);
                });
            }, onUnexpectedError);
        }
        return super.runCommand(accessor, args);
    }
    run(accessor, editor) {
        const controller = RenameController.get(editor);
        if (controller) {
            return controller.run();
        }
        return Promise.resolve();
    }
}
registerEditorContribution(RenameController.ID, RenameController);
registerEditorAction(RenameAction);
const RenameCommand = EditorCommand.bindToContribution(RenameController.get);
registerEditorCommand(new RenameCommand({
    id: 'acceptRenameInput',
    precondition: CONTEXT_RENAME_INPUT_VISIBLE,
    handler: x => x.acceptRenameInput(false),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 99,
        kbExpr: EditorContextKeys.focus,
        primary: 3 /* KeyCode.Enter */
    }
}));
registerEditorCommand(new RenameCommand({
    id: 'acceptRenameInputWithPreview',
    precondition: ContextKeyExpr.and(CONTEXT_RENAME_INPUT_VISIBLE, ContextKeyExpr.has('config.editor.rename.enablePreview')),
    handler: x => x.acceptRenameInput(true),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 99,
        kbExpr: EditorContextKeys.focus,
        primary: 1024 /* KeyMod.Shift */ + 3 /* KeyCode.Enter */
    }
}));
registerEditorCommand(new RenameCommand({
    id: 'cancelRenameInput',
    precondition: CONTEXT_RENAME_INPUT_VISIBLE,
    handler: x => x.cancelRenameInput(),
    kbOpts: {
        weight: 100 /* KeybindingWeight.EditorContrib */ + 99,
        kbExpr: EditorContextKeys.focus,
        primary: 9 /* KeyCode.Escape */,
        secondary: [1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */]
    }
}));
// ---- api bridge command
registerModelAndPositionCommand('_executeDocumentRenameProvider', function (accessor, model, position, ...args) {
    const [newName] = args;
    assertType(typeof newName === 'string');
    const { renameProvider } = accessor.get(ILanguageFeaturesService);
    return rename(renameProvider, model, position, newName);
});
registerModelAndPositionCommand('_executePrepareRename', function (accessor, model, position) {
    return rename_awaiter(this, void 0, void 0, function* () {
        const { renameProvider } = accessor.get(ILanguageFeaturesService);
        const skeleton = new RenameSkeleton(model, position, renameProvider);
        const loc = yield skeleton.resolveRenameLocation(CancellationToken.None);
        if (loc === null || loc === void 0 ? void 0 : loc.rejectReason) {
            throw new Error(loc.rejectReason);
        }
        return loc;
    });
});
//todo@jrieken use editor options world
Registry.as(configurationRegistry_Extensions.Configuration).registerConfiguration({
    id: 'editor',
    properties: {
        'editor.rename.enablePreview': {
            scope: 5 /* ConfigurationScope.LANGUAGE_OVERRIDABLE */,
            description: localize('enablePreview', "Enable/disable the ability to preview changes before renaming"),
            default: true,
            type: 'boolean'
        }
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/smartSelect/browser/wordSelections.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


class WordSelectionRangeProvider {
    provideSelectionRanges(model, positions) {
        const result = [];
        for (const position of positions) {
            const bucket = [];
            result.push(bucket);
            this._addInWordRanges(bucket, model, position);
            this._addWordRanges(bucket, model, position);
            this._addWhitespaceLine(bucket, model, position);
            bucket.push({ range: model.getFullModelRange() });
        }
        return result;
    }
    _addInWordRanges(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;
        // LEFT anchor (start)
        for (; start >= 0; start--) {
            const ch = word.charCodeAt(start);
            if ((start !== offset) && (ch === 95 /* CharCode.Underline */ || ch === 45 /* CharCode.Dash */)) {
                // foo-bar OR foo_bar
                break;
            }
            else if (isLowerAsciiLetter(ch) && isUpperAsciiLetter(lastCh)) {
                // fooBar
                break;
            }
            lastCh = ch;
        }
        start += 1;
        // RIGHT anchor (end)
        for (; end < word.length; end++) {
            const ch = word.charCodeAt(end);
            if (isUpperAsciiLetter(ch) && isLowerAsciiLetter(lastCh)) {
                // fooBar
                break;
            }
            else if (ch === 95 /* CharCode.Underline */ || ch === 45 /* CharCode.Dash */) {
                // foo-bar OR foo_bar
                break;
            }
            lastCh = ch;
        }
        if (start < end) {
            bucket.push({ range: new Range(pos.lineNumber, startColumn + start, pos.lineNumber, startColumn + end) });
        }
    }
    _addWordRanges(bucket, model, pos) {
        const word = model.getWordAtPosition(pos);
        if (word) {
            bucket.push({ range: new Range(pos.lineNumber, word.startColumn, pos.lineNumber, word.endColumn) });
        }
    }
    _addWhitespaceLine(bucket, model, pos) {
        if (model.getLineLength(pos.lineNumber) > 0
            && model.getLineFirstNonWhitespaceColumn(pos.lineNumber) === 0
            && model.getLineLastNonWhitespaceColumn(pos.lineNumber) === 0) {
            bucket.push({ range: new Range(pos.lineNumber, 1, pos.lineNumber, model.getLineMaxColumn(pos.lineNumber)) });
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/smartSelect/browser/smartSelect.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var smartSelect_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var smartSelect_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var smartSelect_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};

















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])) {
            // next range equals this range, retry with next-next
            return res.mov(fwd);
        }
        return res;
    }
}
let SmartSelectController = class SmartSelectController {
    constructor(_editor, _languageFeaturesService) {
        this._editor = _editor;
        this._languageFeaturesService = _languageFeaturesService;
        this._ignoreSelection = false;
    }
    static get(editor) {
        return editor.getContribution(SmartSelectController.ID);
    }
    dispose() {
        var _a;
        (_a = this._selectionListener) === null || _a === void 0 ? void 0 : _a.dispose();
    }
    run(forward) {
        return smartSelect_awaiter(this, void 0, void 0, function* () {
            if (!this._editor.hasModel()) {
                return;
            }
            const selections = this._editor.getSelections();
            const model = this._editor.getModel();
            if (!this._state) {
                yield provideSelectionRanges(this._languageFeaturesService.selectionRangeProvider, model, selections.map(s => s.getPosition()), this._editor.getOption(104 /* EditorOption.smartSelect */), CancellationToken.None).then(ranges => {
                    var _a;
                    if (!isNonEmptyArray(ranges) || ranges.length !== selections.length) {
                        // invalid result
                        return;
                    }
                    if (!this._editor.hasModel() || !equals(this._editor.getSelections(), selections, (a, b) => a.equalsSelection(b))) {
                        // invalid editor state
                        return;
                    }
                    for (let i = 0; i < ranges.length; i++) {
                        ranges[i] = ranges[i].filter(range => {
                            // filter ranges inside the selection
                            return range.containsPosition(selections[i].getStartPosition()) && range.containsPosition(selections[i].getEndPosition());
                        });
                        // prepend current selection
                        ranges[i].unshift(selections[i]);
                    }
                    this._state = ranges.map(ranges => new SelectionRanges(0, ranges));
                    // listen to caret move and forget about state
                    (_a = this._selectionListener) === null || _a === void 0 ? void 0 : _a.dispose();
                    this._selectionListener = this._editor.onDidChangeCursorPosition(() => {
                        var _a;
                        if (!this._ignoreSelection) {
                            (_a = this._selectionListener) === null || _a === void 0 ? void 0 : _a.dispose();
                            this._state = undefined;
                        }
                    });
                });
            }
            if (!this._state) {
                // no state
                return;
            }
            this._state = this._state.map(state => state.mov(forward));
            const newSelections = this._state.map(state => Selection.fromPositions(state.ranges[state.index].getStartPosition(), state.ranges[state.index].getEndPosition()));
            this._ignoreSelection = true;
            try {
                this._editor.setSelections(newSelections);
            }
            finally {
                this._ignoreSelection = false;
            }
        });
    }
};
SmartSelectController.ID = 'editor.contrib.smartSelectController';
SmartSelectController = smartSelect_decorate([
    smartSelect_param(1, ILanguageFeaturesService)
], SmartSelectController);
class AbstractSmartSelect extends EditorAction {
    constructor(forward, opts) {
        super(opts);
        this._forward = forward;
    }
    run(_accessor, editor) {
        return smartSelect_awaiter(this, void 0, void 0, function* () {
            const controller = SmartSelectController.get(editor);
            if (controller) {
                yield controller.run(this._forward);
            }
        });
    }
}
class GrowSelectionAction extends AbstractSmartSelect {
    constructor() {
        super(true, {
            id: 'editor.action.smartSelect.expand',
            label: localize('smartSelect.expand', "Expand Selection"),
            alias: 'Expand Selection',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 17 /* KeyCode.RightArrow */,
                mac: {
                    primary: 2048 /* KeyMod.CtrlCmd */ | 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */,
                    secondary: [256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */],
                },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '1_basic',
                title: localize({ key: 'miSmartSelectGrow', comment: ['&& denotes a mnemonic'] }, "&&Expand Selection"),
                order: 2
            }
        });
    }
}
// renamed command id
CommandsRegistry.registerCommandAlias('editor.action.smartSelect.grow', 'editor.action.smartSelect.expand');
class ShrinkSelectionAction extends AbstractSmartSelect {
    constructor() {
        super(false, {
            id: 'editor.action.smartSelect.shrink',
            label: localize('smartSelect.shrink', "Shrink Selection"),
            alias: 'Shrink Selection',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 1024 /* KeyMod.Shift */ | 512 /* KeyMod.Alt */ | 15 /* KeyCode.LeftArrow */,
                mac: {
                    primary: 2048 /* KeyMod.CtrlCmd */ | 256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */,
                    secondary: [256 /* KeyMod.WinCtrl */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */],
                },
                weight: 100 /* KeybindingWeight.EditorContrib */
            },
            menuOpts: {
                menuId: MenuId.MenubarSelectionMenu,
                group: '1_basic',
                title: localize({ key: 'miSmartSelectShrink', comment: ['&& denotes a mnemonic'] }, "&&Shrink Selection"),
                order: 3
            }
        });
    }
}
registerEditorContribution(SmartSelectController.ID, SmartSelectController);
registerEditorAction(GrowSelectionAction);
registerEditorAction(ShrinkSelectionAction);
function provideSelectionRanges(registry, model, positions, options, token) {
    return smartSelect_awaiter(this, void 0, void 0, function* () {
        const providers = registry.all(model)
            .concat(new WordSelectionRangeProvider()); // ALWAYS have word based selection range
        if (providers.length === 1) {
            // add word selection and bracket selection when no provider exists
            providers.unshift(new BracketSelectionRangeProvider());
        }
        const work = [];
        const allRawRanges = [];
        for (const provider of providers) {
            work.push(Promise.resolve(provider.provideSelectionRanges(model, positions, token)).then(allProviderRanges => {
                if (isNonEmptyArray(allProviderRanges) && allProviderRanges.length === positions.length) {
                    for (let i = 0; i < positions.length; i++) {
                        if (!allRawRanges[i]) {
                            allRawRanges[i] = [];
                        }
                        for (const oneProviderRanges of allProviderRanges[i]) {
                            if (Range.isIRange(oneProviderRanges.range) && Range.containsPosition(oneProviderRanges.range, positions[i])) {
                                allRawRanges[i].push(Range.lift(oneProviderRanges.range));
                            }
                        }
                    }
                }
            }, onUnexpectedExternalError));
        }
        yield Promise.all(work);
        return allRawRanges.map(oneRawRanges => {
            if (oneRawRanges.length === 0) {
                return [];
            }
            // sort all by start/end position
            oneRawRanges.sort((a, b) => {
                if (Position.isBefore(a.getStartPosition(), b.getStartPosition())) {
                    return 1;
                }
                else if (Position.isBefore(b.getStartPosition(), a.getStartPosition())) {
                    return -1;
                }
                else if (Position.isBefore(a.getEndPosition(), b.getEndPosition())) {
                    return -1;
                }
                else if (Position.isBefore(b.getEndPosition(), a.getEndPosition())) {
                    return 1;
                }
                else {
                    return 0;
                }
            });
            // remove ranges that don't contain the former range or that are equal to the
            // former range
            const oneRanges = [];
            let last;
            for (const range of oneRawRanges) {
                if (!last || (Range.containsRange(range, last) && !Range.equalsRange(range, last))) {
                    oneRanges.push(range);
                    last = range;
                }
            }
            if (!options.selectLeadingAndTrailingWhitespace) {
                return oneRanges;
            }
            // add ranges that expand trivia at line starts and ends whenever a range
            // wraps onto the a new line
            const oneRangesWithTrivia = [oneRanges[0]];
            for (let i = 1; i < oneRanges.length; i++) {
                const prev = oneRanges[i - 1];
                const cur = oneRanges[i];
                if (cur.startLineNumber !== prev.startLineNumber || cur.endLineNumber !== prev.endLineNumber) {
                    // add line/block range without leading/failing whitespace
                    const rangeNoWhitespace = new Range(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);
                    }
                    // add line/block range
                    const rangeFull = new Range(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;
        });
    });
}
CommandsRegistry.registerCommand('_executeSelectionRangeProvider', function (accessor, ...args) {
    return smartSelect_awaiter(this, void 0, void 0, function* () {
        const [resource, positions] = args;
        assertType(URI.isUri(resource));
        const registry = accessor.get(ILanguageFeaturesService).selectionRangeProvider;
        const reference = yield accessor.get(ITextModelService).createModelReference(resource);
        try {
            return provideSelectionRanges(registry, reference.object.textEditorModel, positions, { selectLeadingAndTrailingWhitespace: true }, CancellationToken.None);
        }
        finally {
            reference.dispose();
        }
    });
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/stickyScroll/browser/stickyScroll.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var stickyScroll_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var stickyScroll_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var stickyScroll_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
var stickyScroll_a;











let StickyScrollController = class StickyScrollController extends Disposable {
    constructor(editor, _languageFeaturesService) {
        super();
        this._sessionStore = new DisposableStore();
        this._ranges = [];
        this._rangesVersionId = 0;
        this._editor = editor;
        this._languageFeaturesService = _languageFeaturesService;
        this.stickyScrollWidget = new StickyScrollWidget(this._editor);
        this._register(this._editor.onDidChangeConfiguration(e => {
            if (e.hasChanged(34 /* EditorOption.experimental */)) {
                this.onConfigurationChange();
            }
        }));
        this._updateSoon = this._register(new RunOnceScheduler(() => this._update(true), 50));
        this.onConfigurationChange();
    }
    onConfigurationChange() {
        const options = this._editor.getOption(34 /* EditorOption.experimental */);
        if (options.stickyScroll.enabled === false) {
            this.stickyScrollWidget.emptyRootNode();
            this._editor.removeOverlayWidget(this.stickyScrollWidget);
            this._sessionStore.clear();
            return;
        }
        else {
            this._editor.addOverlayWidget(this.stickyScrollWidget);
            this._sessionStore.add(this._editor.onDidChangeModel(() => this._update(true)));
            this._sessionStore.add(this._editor.onDidScrollChange(() => this._update(false)));
            this._sessionStore.add(this._editor.onDidChangeHiddenAreas(() => this._update(true)));
            this._sessionStore.add(this._editor.onDidChangeModelTokens((e) => this._onTokensChange(e)));
            this._sessionStore.add(this._editor.onDidChangeModelContent(() => this._updateSoon.schedule()));
            this._sessionStore.add(this._languageFeaturesService.documentSymbolProvider.onDidChange(() => this._update(true)));
            this._update(true);
        }
    }
    _needsUpdate(event) {
        const stickyLineNumbers = this.stickyScrollWidget.getCurrentLines();
        for (const stickyLineNumber of stickyLineNumbers) {
            for (const range of event.ranges) {
                if (stickyLineNumber >= range.fromLineNumber && stickyLineNumber <= range.toLineNumber) {
                    return true;
                }
            }
        }
        return false;
    }
    _onTokensChange(event) {
        if (this._needsUpdate(event)) {
            this._update(false);
        }
    }
    _update(updateOutline = false) {
        var _a, _b;
        return stickyScroll_awaiter(this, void 0, void 0, function* () {
            if (updateOutline) {
                (_a = this._cts) === null || _a === void 0 ? void 0 : _a.dispose(true);
                this._cts = new CancellationTokenSource();
                yield this._updateOutlineModel(this._cts.token);
            }
            const hiddenRanges = (_b = this._editor._getViewModel()) === null || _b === void 0 ? void 0 : _b.getHiddenAreas();
            if (hiddenRanges) {
                for (const hiddenRange of hiddenRanges) {
                    this._ranges = this._ranges.filter(range => { return !(range[0] >= hiddenRange.startLineNumber && range[1] <= hiddenRange.endLineNumber + 1); });
                }
            }
            this._renderStickyScroll();
        });
    }
    _findLineRanges(outlineElement, depth) {
        if (outlineElement === null || outlineElement === void 0 ? void 0 : outlineElement.children.size) {
            let didRecursion = false;
            for (const outline of outlineElement === null || outlineElement === void 0 ? void 0 : outlineElement.children.values()) {
                const kind = outline.symbol.kind;
                if (kind === 4 /* SymbolKind.Class */ || kind === 8 /* SymbolKind.Constructor */ || kind === 11 /* SymbolKind.Function */ || kind === 10 /* SymbolKind.Interface */ || kind === 5 /* SymbolKind.Method */ || kind === 1 /* SymbolKind.Module */) {
                    didRecursion = true;
                    this._findLineRanges(outline, depth + 1);
                }
            }
            if (!didRecursion) {
                this._addOutlineRanges(outlineElement, depth);
            }
        }
        else {
            this._addOutlineRanges(outlineElement, depth);
        }
    }
    _addOutlineRanges(outlineElement, depth) {
        let currentStartLine = 0;
        let currentEndLine = 0;
        while (outlineElement) {
            const kind = outlineElement.symbol.kind;
            if (kind === 4 /* SymbolKind.Class */ || kind === 8 /* SymbolKind.Constructor */ || kind === 11 /* SymbolKind.Function */ || kind === 10 /* SymbolKind.Interface */ || kind === 5 /* SymbolKind.Method */ || kind === 1 /* SymbolKind.Module */) {
                currentStartLine = outlineElement === null || outlineElement === void 0 ? void 0 : outlineElement.symbol.range.startLineNumber;
                currentEndLine = outlineElement === null || outlineElement === void 0 ? void 0 : outlineElement.symbol.range.endLineNumber;
                this._ranges.push([currentStartLine, currentEndLine, depth]);
                depth--;
            }
            if (outlineElement.parent instanceof OutlineElement) {
                outlineElement = outlineElement.parent;
            }
            else {
                break;
            }
        }
    }
    _updateOutlineModel(token) {
        return stickyScroll_awaiter(this, void 0, void 0, function* () {
            if (this._editor.hasModel()) {
                const model = this._editor.getModel();
                const modelVersionId = model.getVersionId();
                const outlineModel = yield OutlineModel.create(this._languageFeaturesService.documentSymbolProvider, model, token);
                if (token.isCancellationRequested) {
                    return;
                }
                this._ranges = [];
                this._rangesVersionId = modelVersionId;
                for (const outline of outlineModel.children.values()) {
                    if (outline instanceof OutlineElement) {
                        const kind = outline.symbol.kind;
                        if (kind === 4 /* SymbolKind.Class */ || kind === 8 /* SymbolKind.Constructor */ || kind === 11 /* SymbolKind.Function */ || kind === 10 /* SymbolKind.Interface */ || kind === 5 /* SymbolKind.Method */ || kind === 1 /* SymbolKind.Module */) {
                            this._findLineRanges(outline, 1);
                        }
                        else {
                            this._findLineRanges(outline, 0);
                        }
                    }
                    this._ranges = this._ranges.sort(function (a, b) {
                        if (a[0] !== b[0]) {
                            return a[0] - b[0];
                        }
                        else if (a[1] !== b[1]) {
                            return b[1] - a[1];
                        }
                        else {
                            return a[2] - b[2];
                        }
                    });
                    let previous = [];
                    for (const [index, arr] of this._ranges.entries()) {
                        const [start, end, _depth] = arr;
                        if (previous[0] === start && previous[1] === end) {
                            this._ranges.splice(index, 1);
                        }
                        else {
                            previous = arr;
                        }
                    }
                }
            }
        });
    }
    _renderStickyScroll() {
        if (!(this._editor.hasModel())) {
            return;
        }
        const lineHeight = this._editor.getOption(61 /* EditorOption.lineHeight */);
        const model = this._editor.getModel();
        if (this._rangesVersionId !== model.getVersionId()) {
            // Old _ranges not updated yet
            return;
        }
        const scrollTop = this._editor.getScrollTop();
        this.stickyScrollWidget.emptyRootNode();
        const beginningLinesConsidered = new Set();
        for (const [index, arr] of this._ranges.entries()) {
            const [start, end, depth] = arr;
            if (end - start > 0 && model.getLineContent(start) !== '') {
                const topOfElementAtDepth = (depth - 1) * lineHeight;
                const bottomOfElementAtDepth = depth * lineHeight;
                const bottomOfBeginningLine = this._editor.getBottomForLineNumber(start) - scrollTop;
                const topOfEndLine = this._editor.getTopForLineNumber(end) - scrollTop;
                const bottomOfEndLine = this._editor.getBottomForLineNumber(end) - scrollTop;
                if (!beginningLinesConsidered.has(start)) {
                    if (topOfElementAtDepth >= topOfEndLine - 1 && topOfElementAtDepth < bottomOfEndLine - 2) {
                        beginningLinesConsidered.add(start);
                        this.stickyScrollWidget.pushCodeLine(new StickyScrollCodeLine(start, depth, this._editor, -1, bottomOfEndLine - bottomOfElementAtDepth));
                        break;
                    }
                    else if (bottomOfElementAtDepth > bottomOfBeginningLine && bottomOfElementAtDepth < bottomOfEndLine - 1) {
                        beginningLinesConsidered.add(start);
                        this.stickyScrollWidget.pushCodeLine(new StickyScrollCodeLine(start, depth, this._editor, 0, 0));
                    }
                }
                else {
                    this._ranges.splice(index, 1);
                }
            }
        }
        this.stickyScrollWidget.updateRootNode();
    }
    dispose() {
        super.dispose();
        this._sessionStore.dispose();
    }
};
StickyScrollController.ID = 'store.contrib.stickyScrollController';
StickyScrollController = stickyScroll_decorate([
    stickyScroll_param(1, ILanguageFeaturesService)
], StickyScrollController);
const _ttPolicy = (stickyScroll_a = window.trustedTypes) === null || stickyScroll_a === void 0 ? void 0 : stickyScroll_a.createPolicy('stickyScrollViewLayer', { createHTML: value => value });
class StickyScrollCodeLine {
    constructor(_lineNumber, _depth, _editor, _zIndex, _relativePosition) {
        this._lineNumber = _lineNumber;
        this._depth = _depth;
        this._editor = _editor;
        this._zIndex = _zIndex;
        this._relativePosition = _relativePosition;
        this.effectiveLineHeight = 0;
        this.effectiveLineHeight = this._editor.getOption(61 /* EditorOption.lineHeight */) + this._relativePosition;
    }
    get lineNumber() {
        return this._lineNumber;
    }
    getDomNode() {
        const root = document.createElement('div');
        const viewModel = this._editor._getViewModel();
        const viewLineNumber = viewModel.coordinatesConverter.convertModelPositionToViewPosition(new Position(this._lineNumber, 1)).lineNumber;
        const lineRenderingData = viewModel.getViewLineRenderingData(viewLineNumber);
        let actualInlineDecorations;
        try {
            actualInlineDecorations = LineDecoration.filter(lineRenderingData.inlineDecorations, viewLineNumber, lineRenderingData.minColumn, lineRenderingData.maxColumn);
        }
        catch (err) {
            actualInlineDecorations = [];
        }
        const renderLineInput = new RenderLineInput(true, true, lineRenderingData.content, lineRenderingData.continuesWithWrappedLine, lineRenderingData.isBasicASCII, lineRenderingData.containsRTL, 0, lineRenderingData.tokens, actualInlineDecorations, lineRenderingData.tabSize, lineRenderingData.startVisibleColumn, 1, 1, 1, 100, 'none', true, true, null);
        const sb = createStringBuilder(400);
        renderViewLine(renderLineInput, sb);
        let newLine;
        if (_ttPolicy) {
            newLine = _ttPolicy.createHTML(sb.build());
        }
        else {
            newLine = sb.build();
        }
        const lineHTMLNode = document.createElement('span');
        lineHTMLNode.style.backgroundColor = `var(--vscode-editorStickyScroll-background)`;
        lineHTMLNode.style.overflow = 'hidden';
        lineHTMLNode.style.whiteSpace = 'nowrap';
        lineHTMLNode.style.display = 'inline-block';
        lineHTMLNode.style.lineHeight = this._editor.getOption(61 /* EditorOption.lineHeight */).toString() + 'px';
        lineHTMLNode.innerHTML = newLine;
        const lineNumberHTMLNode = document.createElement('span');
        lineNumberHTMLNode.style.width = this._editor.getLayoutInfo().contentLeft.toString() + 'px';
        lineNumberHTMLNode.style.backgroundColor = `var(--vscode-editorStickyScroll-background)`;
        lineNumberHTMLNode.style.color = 'var(--vscode-editorLineNumber-foreground)';
        lineNumberHTMLNode.style.display = 'inline-block';
        lineNumberHTMLNode.style.lineHeight = this._editor.getOption(61 /* EditorOption.lineHeight */).toString() + 'px';
        const innerLineNumberHTML = document.createElement('span');
        innerLineNumberHTML.innerText = this._lineNumber.toString();
        innerLineNumberHTML.style.paddingLeft = this._editor.getLayoutInfo().lineNumbersLeft.toString() + 'px';
        innerLineNumberHTML.style.width = this._editor.getLayoutInfo().lineNumbersWidth.toString() + 'px';
        innerLineNumberHTML.style.backgroundColor = `var(--vscode-editorStickyScroll-background)`;
        innerLineNumberHTML.style.textAlign = 'right';
        innerLineNumberHTML.style.float = 'left';
        innerLineNumberHTML.style.lineHeight = this._editor.getOption(61 /* EditorOption.lineHeight */).toString() + 'px';
        lineNumberHTMLNode.appendChild(innerLineNumberHTML);
        root.onclick = e => {
            e.stopPropagation();
            e.preventDefault();
            this._editor.revealPosition({ lineNumber: this._lineNumber - this._depth + 1, column: 1 });
        };
        root.onmouseover = e => {
            innerLineNumberHTML.style.background = `var(--vscode-editorStickyScrollHover-background)`;
            lineHTMLNode.style.backgroundColor = `var(--vscode-editorStickyScrollHover-background)`;
            lineNumberHTMLNode.style.backgroundColor = `var(--vscode-editorStickyScrollHover-background)`;
            root.style.backgroundColor = `var(--vscode-editorStickyScrollHover-background)`;
            innerLineNumberHTML.style.cursor = `pointer`;
            lineHTMLNode.style.cursor = `pointer`;
            root.style.cursor = `pointer`;
            lineNumberHTMLNode.style.cursor = `pointer`;
        };
        root.onmouseleave = e => {
            innerLineNumberHTML.style.background = `var(--vscode-editorStickyScroll-background)`;
            lineHTMLNode.style.backgroundColor = `var(--vscode-editorStickyScroll-background)`;
            lineNumberHTMLNode.style.backgroundColor = `var(--vscode-editorStickyScroll-background)`;
            root.style.backgroundColor = `var(--vscode-editorStickyScroll-background)`;
        };
        this._editor.applyFontInfo(lineHTMLNode);
        this._editor.applyFontInfo(innerLineNumberHTML);
        root.appendChild(lineNumberHTMLNode);
        root.appendChild(lineHTMLNode);
        root.style.zIndex = this._zIndex.toString();
        root.style.backgroundColor = `var(--vscode-editorStickyScroll-background)`;
        root.style.overflow = 'hidden';
        root.style.whiteSpace = 'nowrap';
        root.style.width = '100%';
        root.style.lineHeight = this._editor.getOption(61 /* EditorOption.lineHeight */).toString() + 'px';
        root.style.height = this._editor.getOption(61 /* EditorOption.lineHeight */).toString() + 'px';
        // Special case for last line of sticky scroll
        if (this._relativePosition) {
            root.style.position = 'relative';
            root.style.top = this._relativePosition + 'px';
            root.style.width = '100%';
        }
        return root;
    }
}
class StickyScrollWidget {
    constructor(_editor) {
        this._editor = _editor;
        this.arrayOfCodeLines = [];
        this.rootDomNode = document.createElement('div');
        this.rootDomNode = document.createElement('div');
        this.rootDomNode.style.width = '100%';
        this.rootDomNode.style.boxShadow = `var(--vscode-scrollbar-shadow) 0 6px 6px -6px`;
    }
    getCurrentLines() {
        const widgetLineRange = [];
        for (const codeLine of this.arrayOfCodeLines) {
            widgetLineRange.push(codeLine.lineNumber);
        }
        return widgetLineRange;
    }
    pushCodeLine(codeLine) {
        this.arrayOfCodeLines.push(codeLine);
    }
    updateRootNode() {
        let widgetHeight = 0;
        for (const line of this.arrayOfCodeLines) {
            widgetHeight += line.effectiveLineHeight;
            this.rootDomNode.appendChild(line.getDomNode());
        }
        this.rootDomNode.style.height = widgetHeight.toString() + 'px';
    }
    emptyRootNode() {
        this.arrayOfCodeLines.length = 0;
        clearNode(this.rootDomNode);
    }
    getId() {
        return 'editor.contrib.stickyScrollWidget';
    }
    getDomNode() {
        this.rootDomNode.style.zIndex = '2';
        this.rootDomNode.style.backgroundColor = `var(--vscode-editorStickyScroll-background)`;
        return this.rootDomNode;
    }
    getPosition() {
        return {
            preference: null
        };
    }
}
registerEditorContribution(StickyScrollController.ID, StickyScrollController);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/standalone/standaloneEnums.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
// THIS IS A GENERATED FILE. DO NOT EDIT DIRECTLY.
var AccessibilitySupport;
(function (AccessibilitySupport) {
    /**
     * This should be the browser case where it is not known if a screen reader is attached or no.
     */
    AccessibilitySupport[AccessibilitySupport["Unknown"] = 0] = "Unknown";
    AccessibilitySupport[AccessibilitySupport["Disabled"] = 1] = "Disabled";
    AccessibilitySupport[AccessibilitySupport["Enabled"] = 2] = "Enabled";
})(AccessibilitySupport || (AccessibilitySupport = {}));
var CodeActionTriggerType;
(function (CodeActionTriggerType) {
    CodeActionTriggerType[CodeActionTriggerType["Invoke"] = 1] = "Invoke";
    CodeActionTriggerType[CodeActionTriggerType["Auto"] = 2] = "Auto";
})(CodeActionTriggerType || (CodeActionTriggerType = {}));
var CompletionItemInsertTextRule;
(function (CompletionItemInsertTextRule) {
    /**
     * Adjust whitespace/indentation of multiline insert texts to
     * match the current line indentation.
     */
    CompletionItemInsertTextRule[CompletionItemInsertTextRule["KeepWhitespace"] = 1] = "KeepWhitespace";
    /**
     * `insertText` is a snippet.
     */
    CompletionItemInsertTextRule[CompletionItemInsertTextRule["InsertAsSnippet"] = 4] = "InsertAsSnippet";
})(CompletionItemInsertTextRule || (CompletionItemInsertTextRule = {}));
var CompletionItemKind;
(function (CompletionItemKind) {
    CompletionItemKind[CompletionItemKind["Method"] = 0] = "Method";
    CompletionItemKind[CompletionItemKind["Function"] = 1] = "Function";
    CompletionItemKind[CompletionItemKind["Constructor"] = 2] = "Constructor";
    CompletionItemKind[CompletionItemKind["Field"] = 3] = "Field";
    CompletionItemKind[CompletionItemKind["Variable"] = 4] = "Variable";
    CompletionItemKind[CompletionItemKind["Class"] = 5] = "Class";
    CompletionItemKind[CompletionItemKind["Struct"] = 6] = "Struct";
    CompletionItemKind[CompletionItemKind["Interface"] = 7] = "Interface";
    CompletionItemKind[CompletionItemKind["Module"] = 8] = "Module";
    CompletionItemKind[CompletionItemKind["Property"] = 9] = "Property";
    CompletionItemKind[CompletionItemKind["Event"] = 10] = "Event";
    CompletionItemKind[CompletionItemKind["Operator"] = 11] = "Operator";
    CompletionItemKind[CompletionItemKind["Unit"] = 12] = "Unit";
    CompletionItemKind[CompletionItemKind["Value"] = 13] = "Value";
    CompletionItemKind[CompletionItemKind["Constant"] = 14] = "Constant";
    CompletionItemKind[CompletionItemKind["Enum"] = 15] = "Enum";
    CompletionItemKind[CompletionItemKind["EnumMember"] = 16] = "EnumMember";
    CompletionItemKind[CompletionItemKind["Keyword"] = 17] = "Keyword";
    CompletionItemKind[CompletionItemKind["Text"] = 18] = "Text";
    CompletionItemKind[CompletionItemKind["Color"] = 19] = "Color";
    CompletionItemKind[CompletionItemKind["File"] = 20] = "File";
    CompletionItemKind[CompletionItemKind["Reference"] = 21] = "Reference";
    CompletionItemKind[CompletionItemKind["Customcolor"] = 22] = "Customcolor";
    CompletionItemKind[CompletionItemKind["Folder"] = 23] = "Folder";
    CompletionItemKind[CompletionItemKind["TypeParameter"] = 24] = "TypeParameter";
    CompletionItemKind[CompletionItemKind["User"] = 25] = "User";
    CompletionItemKind[CompletionItemKind["Issue"] = 26] = "Issue";
    CompletionItemKind[CompletionItemKind["Snippet"] = 27] = "Snippet";
})(CompletionItemKind || (CompletionItemKind = {}));
var CompletionItemTag;
(function (CompletionItemTag) {
    CompletionItemTag[CompletionItemTag["Deprecated"] = 1] = "Deprecated";
})(CompletionItemTag || (CompletionItemTag = {}));
/**
 * How a suggest provider was triggered.
 */
var CompletionTriggerKind;
(function (CompletionTriggerKind) {
    CompletionTriggerKind[CompletionTriggerKind["Invoke"] = 0] = "Invoke";
    CompletionTriggerKind[CompletionTriggerKind["TriggerCharacter"] = 1] = "TriggerCharacter";
    CompletionTriggerKind[CompletionTriggerKind["TriggerForIncompleteCompletions"] = 2] = "TriggerForIncompleteCompletions";
})(CompletionTriggerKind || (CompletionTriggerKind = {}));
/**
 * A positioning preference for rendering content widgets.
 */
var ContentWidgetPositionPreference;
(function (ContentWidgetPositionPreference) {
    /**
     * Place the content widget exactly at a position
     */
    ContentWidgetPositionPreference[ContentWidgetPositionPreference["EXACT"] = 0] = "EXACT";
    /**
     * Place the content widget above a position
     */
    ContentWidgetPositionPreference[ContentWidgetPositionPreference["ABOVE"] = 1] = "ABOVE";
    /**
     * Place the content widget below a position
     */
    ContentWidgetPositionPreference[ContentWidgetPositionPreference["BELOW"] = 2] = "BELOW";
})(ContentWidgetPositionPreference || (ContentWidgetPositionPreference = {}));
/**
 * Describes the reason the cursor has changed its position.
 */
var CursorChangeReason;
(function (CursorChangeReason) {
    /**
     * Unknown or not set.
     */
    CursorChangeReason[CursorChangeReason["NotSet"] = 0] = "NotSet";
    /**
     * A `model.setValue()` was called.
     */
    CursorChangeReason[CursorChangeReason["ContentFlush"] = 1] = "ContentFlush";
    /**
     * The `model` has been changed outside of this cursor and the cursor recovers its position from associated markers.
     */
    CursorChangeReason[CursorChangeReason["RecoverFromMarkers"] = 2] = "RecoverFromMarkers";
    /**
     * There was an explicit user gesture.
     */
    CursorChangeReason[CursorChangeReason["Explicit"] = 3] = "Explicit";
    /**
     * There was a Paste.
     */
    CursorChangeReason[CursorChangeReason["Paste"] = 4] = "Paste";
    /**
     * There was an Undo.
     */
    CursorChangeReason[CursorChangeReason["Undo"] = 5] = "Undo";
    /**
     * There was a Redo.
     */
    CursorChangeReason[CursorChangeReason["Redo"] = 6] = "Redo";
})(CursorChangeReason || (CursorChangeReason = {}));
/**
 * The default end of line to use when instantiating models.
 */
var DefaultEndOfLine;
(function (DefaultEndOfLine) {
    /**
     * Use line feed (\n) as the end of line character.
     */
    DefaultEndOfLine[DefaultEndOfLine["LF"] = 1] = "LF";
    /**
     * Use carriage return and line feed (\r\n) as the end of line character.
     */
    DefaultEndOfLine[DefaultEndOfLine["CRLF"] = 2] = "CRLF";
})(DefaultEndOfLine || (DefaultEndOfLine = {}));
/**
 * A document highlight kind.
 */
var standaloneEnums_DocumentHighlightKind;
(function (DocumentHighlightKind) {
    /**
     * A textual occurrence.
     */
    DocumentHighlightKind[DocumentHighlightKind["Text"] = 0] = "Text";
    /**
     * Read-access of a symbol, like reading a variable.
     */
    DocumentHighlightKind[DocumentHighlightKind["Read"] = 1] = "Read";
    /**
     * Write-access of a symbol, like writing to a variable.
     */
    DocumentHighlightKind[DocumentHighlightKind["Write"] = 2] = "Write";
})(standaloneEnums_DocumentHighlightKind || (standaloneEnums_DocumentHighlightKind = {}));
/**
 * Configuration options for auto indentation in the editor
 */
var EditorAutoIndentStrategy;
(function (EditorAutoIndentStrategy) {
    EditorAutoIndentStrategy[EditorAutoIndentStrategy["None"] = 0] = "None";
    EditorAutoIndentStrategy[EditorAutoIndentStrategy["Keep"] = 1] = "Keep";
    EditorAutoIndentStrategy[EditorAutoIndentStrategy["Brackets"] = 2] = "Brackets";
    EditorAutoIndentStrategy[EditorAutoIndentStrategy["Advanced"] = 3] = "Advanced";
    EditorAutoIndentStrategy[EditorAutoIndentStrategy["Full"] = 4] = "Full";
})(EditorAutoIndentStrategy || (EditorAutoIndentStrategy = {}));
var EditorOption;
(function (EditorOption) {
    EditorOption[EditorOption["acceptSuggestionOnCommitCharacter"] = 0] = "acceptSuggestionOnCommitCharacter";
    EditorOption[EditorOption["acceptSuggestionOnEnter"] = 1] = "acceptSuggestionOnEnter";
    EditorOption[EditorOption["accessibilitySupport"] = 2] = "accessibilitySupport";
    EditorOption[EditorOption["accessibilityPageSize"] = 3] = "accessibilityPageSize";
    EditorOption[EditorOption["ariaLabel"] = 4] = "ariaLabel";
    EditorOption[EditorOption["autoClosingBrackets"] = 5] = "autoClosingBrackets";
    EditorOption[EditorOption["autoClosingDelete"] = 6] = "autoClosingDelete";
    EditorOption[EditorOption["autoClosingOvertype"] = 7] = "autoClosingOvertype";
    EditorOption[EditorOption["autoClosingQuotes"] = 8] = "autoClosingQuotes";
    EditorOption[EditorOption["autoIndent"] = 9] = "autoIndent";
    EditorOption[EditorOption["automaticLayout"] = 10] = "automaticLayout";
    EditorOption[EditorOption["autoSurround"] = 11] = "autoSurround";
    EditorOption[EditorOption["bracketPairColorization"] = 12] = "bracketPairColorization";
    EditorOption[EditorOption["guides"] = 13] = "guides";
    EditorOption[EditorOption["codeLens"] = 14] = "codeLens";
    EditorOption[EditorOption["codeLensFontFamily"] = 15] = "codeLensFontFamily";
    EditorOption[EditorOption["codeLensFontSize"] = 16] = "codeLensFontSize";
    EditorOption[EditorOption["colorDecorators"] = 17] = "colorDecorators";
    EditorOption[EditorOption["columnSelection"] = 18] = "columnSelection";
    EditorOption[EditorOption["comments"] = 19] = "comments";
    EditorOption[EditorOption["contextmenu"] = 20] = "contextmenu";
    EditorOption[EditorOption["copyWithSyntaxHighlighting"] = 21] = "copyWithSyntaxHighlighting";
    EditorOption[EditorOption["cursorBlinking"] = 22] = "cursorBlinking";
    EditorOption[EditorOption["cursorSmoothCaretAnimation"] = 23] = "cursorSmoothCaretAnimation";
    EditorOption[EditorOption["cursorStyle"] = 24] = "cursorStyle";
    EditorOption[EditorOption["cursorSurroundingLines"] = 25] = "cursorSurroundingLines";
    EditorOption[EditorOption["cursorSurroundingLinesStyle"] = 26] = "cursorSurroundingLinesStyle";
    EditorOption[EditorOption["cursorWidth"] = 27] = "cursorWidth";
    EditorOption[EditorOption["disableLayerHinting"] = 28] = "disableLayerHinting";
    EditorOption[EditorOption["disableMonospaceOptimizations"] = 29] = "disableMonospaceOptimizations";
    EditorOption[EditorOption["domReadOnly"] = 30] = "domReadOnly";
    EditorOption[EditorOption["dragAndDrop"] = 31] = "dragAndDrop";
    EditorOption[EditorOption["dropIntoEditor"] = 32] = "dropIntoEditor";
    EditorOption[EditorOption["emptySelectionClipboard"] = 33] = "emptySelectionClipboard";
    EditorOption[EditorOption["experimental"] = 34] = "experimental";
    EditorOption[EditorOption["extraEditorClassName"] = 35] = "extraEditorClassName";
    EditorOption[EditorOption["fastScrollSensitivity"] = 36] = "fastScrollSensitivity";
    EditorOption[EditorOption["find"] = 37] = "find";
    EditorOption[EditorOption["fixedOverflowWidgets"] = 38] = "fixedOverflowWidgets";
    EditorOption[EditorOption["folding"] = 39] = "folding";
    EditorOption[EditorOption["foldingStrategy"] = 40] = "foldingStrategy";
    EditorOption[EditorOption["foldingHighlight"] = 41] = "foldingHighlight";
    EditorOption[EditorOption["foldingImportsByDefault"] = 42] = "foldingImportsByDefault";
    EditorOption[EditorOption["foldingMaximumRegions"] = 43] = "foldingMaximumRegions";
    EditorOption[EditorOption["unfoldOnClickAfterEndOfLine"] = 44] = "unfoldOnClickAfterEndOfLine";
    EditorOption[EditorOption["fontFamily"] = 45] = "fontFamily";
    EditorOption[EditorOption["fontInfo"] = 46] = "fontInfo";
    EditorOption[EditorOption["fontLigatures"] = 47] = "fontLigatures";
    EditorOption[EditorOption["fontSize"] = 48] = "fontSize";
    EditorOption[EditorOption["fontWeight"] = 49] = "fontWeight";
    EditorOption[EditorOption["formatOnPaste"] = 50] = "formatOnPaste";
    EditorOption[EditorOption["formatOnType"] = 51] = "formatOnType";
    EditorOption[EditorOption["glyphMargin"] = 52] = "glyphMargin";
    EditorOption[EditorOption["gotoLocation"] = 53] = "gotoLocation";
    EditorOption[EditorOption["hideCursorInOverviewRuler"] = 54] = "hideCursorInOverviewRuler";
    EditorOption[EditorOption["hover"] = 55] = "hover";
    EditorOption[EditorOption["inDiffEditor"] = 56] = "inDiffEditor";
    EditorOption[EditorOption["inlineSuggest"] = 57] = "inlineSuggest";
    EditorOption[EditorOption["letterSpacing"] = 58] = "letterSpacing";
    EditorOption[EditorOption["lightbulb"] = 59] = "lightbulb";
    EditorOption[EditorOption["lineDecorationsWidth"] = 60] = "lineDecorationsWidth";
    EditorOption[EditorOption["lineHeight"] = 61] = "lineHeight";
    EditorOption[EditorOption["lineNumbers"] = 62] = "lineNumbers";
    EditorOption[EditorOption["lineNumbersMinChars"] = 63] = "lineNumbersMinChars";
    EditorOption[EditorOption["linkedEditing"] = 64] = "linkedEditing";
    EditorOption[EditorOption["links"] = 65] = "links";
    EditorOption[EditorOption["matchBrackets"] = 66] = "matchBrackets";
    EditorOption[EditorOption["minimap"] = 67] = "minimap";
    EditorOption[EditorOption["mouseStyle"] = 68] = "mouseStyle";
    EditorOption[EditorOption["mouseWheelScrollSensitivity"] = 69] = "mouseWheelScrollSensitivity";
    EditorOption[EditorOption["mouseWheelZoom"] = 70] = "mouseWheelZoom";
    EditorOption[EditorOption["multiCursorMergeOverlapping"] = 71] = "multiCursorMergeOverlapping";
    EditorOption[EditorOption["multiCursorModifier"] = 72] = "multiCursorModifier";
    EditorOption[EditorOption["multiCursorPaste"] = 73] = "multiCursorPaste";
    EditorOption[EditorOption["occurrencesHighlight"] = 74] = "occurrencesHighlight";
    EditorOption[EditorOption["overviewRulerBorder"] = 75] = "overviewRulerBorder";
    EditorOption[EditorOption["overviewRulerLanes"] = 76] = "overviewRulerLanes";
    EditorOption[EditorOption["padding"] = 77] = "padding";
    EditorOption[EditorOption["parameterHints"] = 78] = "parameterHints";
    EditorOption[EditorOption["peekWidgetDefaultFocus"] = 79] = "peekWidgetDefaultFocus";
    EditorOption[EditorOption["definitionLinkOpensInPeek"] = 80] = "definitionLinkOpensInPeek";
    EditorOption[EditorOption["quickSuggestions"] = 81] = "quickSuggestions";
    EditorOption[EditorOption["quickSuggestionsDelay"] = 82] = "quickSuggestionsDelay";
    EditorOption[EditorOption["readOnly"] = 83] = "readOnly";
    EditorOption[EditorOption["renameOnType"] = 84] = "renameOnType";
    EditorOption[EditorOption["renderControlCharacters"] = 85] = "renderControlCharacters";
    EditorOption[EditorOption["renderFinalNewline"] = 86] = "renderFinalNewline";
    EditorOption[EditorOption["renderLineHighlight"] = 87] = "renderLineHighlight";
    EditorOption[EditorOption["renderLineHighlightOnlyWhenFocus"] = 88] = "renderLineHighlightOnlyWhenFocus";
    EditorOption[EditorOption["renderValidationDecorations"] = 89] = "renderValidationDecorations";
    EditorOption[EditorOption["renderWhitespace"] = 90] = "renderWhitespace";
    EditorOption[EditorOption["revealHorizontalRightPadding"] = 91] = "revealHorizontalRightPadding";
    EditorOption[EditorOption["roundedSelection"] = 92] = "roundedSelection";
    EditorOption[EditorOption["rulers"] = 93] = "rulers";
    EditorOption[EditorOption["scrollbar"] = 94] = "scrollbar";
    EditorOption[EditorOption["scrollBeyondLastColumn"] = 95] = "scrollBeyondLastColumn";
    EditorOption[EditorOption["scrollBeyondLastLine"] = 96] = "scrollBeyondLastLine";
    EditorOption[EditorOption["scrollPredominantAxis"] = 97] = "scrollPredominantAxis";
    EditorOption[EditorOption["selectionClipboard"] = 98] = "selectionClipboard";
    EditorOption[EditorOption["selectionHighlight"] = 99] = "selectionHighlight";
    EditorOption[EditorOption["selectOnLineNumbers"] = 100] = "selectOnLineNumbers";
    EditorOption[EditorOption["showFoldingControls"] = 101] = "showFoldingControls";
    EditorOption[EditorOption["showUnused"] = 102] = "showUnused";
    EditorOption[EditorOption["snippetSuggestions"] = 103] = "snippetSuggestions";
    EditorOption[EditorOption["smartSelect"] = 104] = "smartSelect";
    EditorOption[EditorOption["smoothScrolling"] = 105] = "smoothScrolling";
    EditorOption[EditorOption["stickyTabStops"] = 106] = "stickyTabStops";
    EditorOption[EditorOption["stopRenderingLineAfter"] = 107] = "stopRenderingLineAfter";
    EditorOption[EditorOption["suggest"] = 108] = "suggest";
    EditorOption[EditorOption["suggestFontSize"] = 109] = "suggestFontSize";
    EditorOption[EditorOption["suggestLineHeight"] = 110] = "suggestLineHeight";
    EditorOption[EditorOption["suggestOnTriggerCharacters"] = 111] = "suggestOnTriggerCharacters";
    EditorOption[EditorOption["suggestSelection"] = 112] = "suggestSelection";
    EditorOption[EditorOption["tabCompletion"] = 113] = "tabCompletion";
    EditorOption[EditorOption["tabIndex"] = 114] = "tabIndex";
    EditorOption[EditorOption["unicodeHighlighting"] = 115] = "unicodeHighlighting";
    EditorOption[EditorOption["unusualLineTerminators"] = 116] = "unusualLineTerminators";
    EditorOption[EditorOption["useShadowDOM"] = 117] = "useShadowDOM";
    EditorOption[EditorOption["useTabStops"] = 118] = "useTabStops";
    EditorOption[EditorOption["wordSeparators"] = 119] = "wordSeparators";
    EditorOption[EditorOption["wordWrap"] = 120] = "wordWrap";
    EditorOption[EditorOption["wordWrapBreakAfterCharacters"] = 121] = "wordWrapBreakAfterCharacters";
    EditorOption[EditorOption["wordWrapBreakBeforeCharacters"] = 122] = "wordWrapBreakBeforeCharacters";
    EditorOption[EditorOption["wordWrapColumn"] = 123] = "wordWrapColumn";
    EditorOption[EditorOption["wordWrapOverride1"] = 124] = "wordWrapOverride1";
    EditorOption[EditorOption["wordWrapOverride2"] = 125] = "wordWrapOverride2";
    EditorOption[EditorOption["wrappingIndent"] = 126] = "wrappingIndent";
    EditorOption[EditorOption["wrappingStrategy"] = 127] = "wrappingStrategy";
    EditorOption[EditorOption["showDeprecated"] = 128] = "showDeprecated";
    EditorOption[EditorOption["inlayHints"] = 129] = "inlayHints";
    EditorOption[EditorOption["editorClassName"] = 130] = "editorClassName";
    EditorOption[EditorOption["pixelRatio"] = 131] = "pixelRatio";
    EditorOption[EditorOption["tabFocusMode"] = 132] = "tabFocusMode";
    EditorOption[EditorOption["layoutInfo"] = 133] = "layoutInfo";
    EditorOption[EditorOption["wrappingInfo"] = 134] = "wrappingInfo";
})(EditorOption || (EditorOption = {}));
/**
 * End of line character preference.
 */
var EndOfLinePreference;
(function (EndOfLinePreference) {
    /**
     * Use the end of line character identified in the text buffer.
     */
    EndOfLinePreference[EndOfLinePreference["TextDefined"] = 0] = "TextDefined";
    /**
     * Use line feed (\n) as the end of line character.
     */
    EndOfLinePreference[EndOfLinePreference["LF"] = 1] = "LF";
    /**
     * Use carriage return and line feed (\r\n) as the end of line character.
     */
    EndOfLinePreference[EndOfLinePreference["CRLF"] = 2] = "CRLF";
})(EndOfLinePreference || (EndOfLinePreference = {}));
/**
 * End of line character preference.
 */
var EndOfLineSequence;
(function (EndOfLineSequence) {
    /**
     * Use line feed (\n) as the end of line character.
     */
    EndOfLineSequence[EndOfLineSequence["LF"] = 0] = "LF";
    /**
     * Use carriage return and line feed (\r\n) as the end of line character.
     */
    EndOfLineSequence[EndOfLineSequence["CRLF"] = 1] = "CRLF";
})(EndOfLineSequence || (EndOfLineSequence = {}));
/**
 * Describes what to do with the indentation when pressing Enter.
 */
var standaloneEnums_IndentAction;
(function (IndentAction) {
    /**
     * Insert new line and copy the previous line's indentation.
     */
    IndentAction[IndentAction["None"] = 0] = "None";
    /**
     * Insert new line and indent once (relative to the previous line's indentation).
     */
    IndentAction[IndentAction["Indent"] = 1] = "Indent";
    /**
     * Insert two new lines:
     *  - the first one indented which will hold the cursor
     *  - the second one at the same indentation level
     */
    IndentAction[IndentAction["IndentOutdent"] = 2] = "IndentOutdent";
    /**
     * Insert new line and outdent once (relative to the previous line's indentation).
     */
    IndentAction[IndentAction["Outdent"] = 3] = "Outdent";
})(standaloneEnums_IndentAction || (standaloneEnums_IndentAction = {}));
var standaloneEnums_InjectedTextCursorStops;
(function (InjectedTextCursorStops) {
    InjectedTextCursorStops[InjectedTextCursorStops["Both"] = 0] = "Both";
    InjectedTextCursorStops[InjectedTextCursorStops["Right"] = 1] = "Right";
    InjectedTextCursorStops[InjectedTextCursorStops["Left"] = 2] = "Left";
    InjectedTextCursorStops[InjectedTextCursorStops["None"] = 3] = "None";
})(standaloneEnums_InjectedTextCursorStops || (standaloneEnums_InjectedTextCursorStops = {}));
var standaloneEnums_InlayHintKind;
(function (InlayHintKind) {
    InlayHintKind[InlayHintKind["Type"] = 1] = "Type";
    InlayHintKind[InlayHintKind["Parameter"] = 2] = "Parameter";
})(standaloneEnums_InlayHintKind || (standaloneEnums_InlayHintKind = {}));
/**
 * How an {@link InlineCompletionsProvider inline completion provider} was triggered.
 */
var standaloneEnums_InlineCompletionTriggerKind;
(function (InlineCompletionTriggerKind) {
    /**
     * Completion was triggered automatically while editing.
     * It is sufficient to return a single completion item in this case.
     */
    InlineCompletionTriggerKind[InlineCompletionTriggerKind["Automatic"] = 0] = "Automatic";
    /**
     * Completion was triggered explicitly by a user gesture.
     * Return multiple completion items to enable cycling through them.
     */
    InlineCompletionTriggerKind[InlineCompletionTriggerKind["Explicit"] = 1] = "Explicit";
})(standaloneEnums_InlineCompletionTriggerKind || (standaloneEnums_InlineCompletionTriggerKind = {}));
/**
 * Virtual Key Codes, the value does not hold any inherent meaning.
 * Inspired somewhat from https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
 * But these are "more general", as they should work across browsers & OS`s.
 */
var KeyCode;
(function (KeyCode) {
    KeyCode[KeyCode["DependsOnKbLayout"] = -1] = "DependsOnKbLayout";
    /**
     * Placed first to cover the 0 value of the enum.
     */
    KeyCode[KeyCode["Unknown"] = 0] = "Unknown";
    KeyCode[KeyCode["Backspace"] = 1] = "Backspace";
    KeyCode[KeyCode["Tab"] = 2] = "Tab";
    KeyCode[KeyCode["Enter"] = 3] = "Enter";
    KeyCode[KeyCode["Shift"] = 4] = "Shift";
    KeyCode[KeyCode["Ctrl"] = 5] = "Ctrl";
    KeyCode[KeyCode["Alt"] = 6] = "Alt";
    KeyCode[KeyCode["PauseBreak"] = 7] = "PauseBreak";
    KeyCode[KeyCode["CapsLock"] = 8] = "CapsLock";
    KeyCode[KeyCode["Escape"] = 9] = "Escape";
    KeyCode[KeyCode["Space"] = 10] = "Space";
    KeyCode[KeyCode["PageUp"] = 11] = "PageUp";
    KeyCode[KeyCode["PageDown"] = 12] = "PageDown";
    KeyCode[KeyCode["End"] = 13] = "End";
    KeyCode[KeyCode["Home"] = 14] = "Home";
    KeyCode[KeyCode["LeftArrow"] = 15] = "LeftArrow";
    KeyCode[KeyCode["UpArrow"] = 16] = "UpArrow";
    KeyCode[KeyCode["RightArrow"] = 17] = "RightArrow";
    KeyCode[KeyCode["DownArrow"] = 18] = "DownArrow";
    KeyCode[KeyCode["Insert"] = 19] = "Insert";
    KeyCode[KeyCode["Delete"] = 20] = "Delete";
    KeyCode[KeyCode["Digit0"] = 21] = "Digit0";
    KeyCode[KeyCode["Digit1"] = 22] = "Digit1";
    KeyCode[KeyCode["Digit2"] = 23] = "Digit2";
    KeyCode[KeyCode["Digit3"] = 24] = "Digit3";
    KeyCode[KeyCode["Digit4"] = 25] = "Digit4";
    KeyCode[KeyCode["Digit5"] = 26] = "Digit5";
    KeyCode[KeyCode["Digit6"] = 27] = "Digit6";
    KeyCode[KeyCode["Digit7"] = 28] = "Digit7";
    KeyCode[KeyCode["Digit8"] = 29] = "Digit8";
    KeyCode[KeyCode["Digit9"] = 30] = "Digit9";
    KeyCode[KeyCode["KeyA"] = 31] = "KeyA";
    KeyCode[KeyCode["KeyB"] = 32] = "KeyB";
    KeyCode[KeyCode["KeyC"] = 33] = "KeyC";
    KeyCode[KeyCode["KeyD"] = 34] = "KeyD";
    KeyCode[KeyCode["KeyE"] = 35] = "KeyE";
    KeyCode[KeyCode["KeyF"] = 36] = "KeyF";
    KeyCode[KeyCode["KeyG"] = 37] = "KeyG";
    KeyCode[KeyCode["KeyH"] = 38] = "KeyH";
    KeyCode[KeyCode["KeyI"] = 39] = "KeyI";
    KeyCode[KeyCode["KeyJ"] = 40] = "KeyJ";
    KeyCode[KeyCode["KeyK"] = 41] = "KeyK";
    KeyCode[KeyCode["KeyL"] = 42] = "KeyL";
    KeyCode[KeyCode["KeyM"] = 43] = "KeyM";
    KeyCode[KeyCode["KeyN"] = 44] = "KeyN";
    KeyCode[KeyCode["KeyO"] = 45] = "KeyO";
    KeyCode[KeyCode["KeyP"] = 46] = "KeyP";
    KeyCode[KeyCode["KeyQ"] = 47] = "KeyQ";
    KeyCode[KeyCode["KeyR"] = 48] = "KeyR";
    KeyCode[KeyCode["KeyS"] = 49] = "KeyS";
    KeyCode[KeyCode["KeyT"] = 50] = "KeyT";
    KeyCode[KeyCode["KeyU"] = 51] = "KeyU";
    KeyCode[KeyCode["KeyV"] = 52] = "KeyV";
    KeyCode[KeyCode["KeyW"] = 53] = "KeyW";
    KeyCode[KeyCode["KeyX"] = 54] = "KeyX";
    KeyCode[KeyCode["KeyY"] = 55] = "KeyY";
    KeyCode[KeyCode["KeyZ"] = 56] = "KeyZ";
    KeyCode[KeyCode["Meta"] = 57] = "Meta";
    KeyCode[KeyCode["ContextMenu"] = 58] = "ContextMenu";
    KeyCode[KeyCode["F1"] = 59] = "F1";
    KeyCode[KeyCode["F2"] = 60] = "F2";
    KeyCode[KeyCode["F3"] = 61] = "F3";
    KeyCode[KeyCode["F4"] = 62] = "F4";
    KeyCode[KeyCode["F5"] = 63] = "F5";
    KeyCode[KeyCode["F6"] = 64] = "F6";
    KeyCode[KeyCode["F7"] = 65] = "F7";
    KeyCode[KeyCode["F8"] = 66] = "F8";
    KeyCode[KeyCode["F9"] = 67] = "F9";
    KeyCode[KeyCode["F10"] = 68] = "F10";
    KeyCode[KeyCode["F11"] = 69] = "F11";
    KeyCode[KeyCode["F12"] = 70] = "F12";
    KeyCode[KeyCode["F13"] = 71] = "F13";
    KeyCode[KeyCode["F14"] = 72] = "F14";
    KeyCode[KeyCode["F15"] = 73] = "F15";
    KeyCode[KeyCode["F16"] = 74] = "F16";
    KeyCode[KeyCode["F17"] = 75] = "F17";
    KeyCode[KeyCode["F18"] = 76] = "F18";
    KeyCode[KeyCode["F19"] = 77] = "F19";
    KeyCode[KeyCode["NumLock"] = 78] = "NumLock";
    KeyCode[KeyCode["ScrollLock"] = 79] = "ScrollLock";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the ';:' key
     */
    KeyCode[KeyCode["Semicolon"] = 80] = "Semicolon";
    /**
     * For any country/region, the '+' key
     * For the US standard keyboard, the '=+' key
     */
    KeyCode[KeyCode["Equal"] = 81] = "Equal";
    /**
     * For any country/region, the ',' key
     * For the US standard keyboard, the ',<' key
     */
    KeyCode[KeyCode["Comma"] = 82] = "Comma";
    /**
     * For any country/region, the '-' key
     * For the US standard keyboard, the '-_' key
     */
    KeyCode[KeyCode["Minus"] = 83] = "Minus";
    /**
     * For any country/region, the '.' key
     * For the US standard keyboard, the '.>' key
     */
    KeyCode[KeyCode["Period"] = 84] = "Period";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the '/?' key
     */
    KeyCode[KeyCode["Slash"] = 85] = "Slash";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the '`~' key
     */
    KeyCode[KeyCode["Backquote"] = 86] = "Backquote";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the '[{' key
     */
    KeyCode[KeyCode["BracketLeft"] = 87] = "BracketLeft";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the '\|' key
     */
    KeyCode[KeyCode["Backslash"] = 88] = "Backslash";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the ']}' key
     */
    KeyCode[KeyCode["BracketRight"] = 89] = "BracketRight";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     * For the US standard keyboard, the ''"' key
     */
    KeyCode[KeyCode["Quote"] = 90] = "Quote";
    /**
     * Used for miscellaneous characters; it can vary by keyboard.
     */
    KeyCode[KeyCode["OEM_8"] = 91] = "OEM_8";
    /**
     * Either the angle bracket key or the backslash key on the RT 102-key keyboard.
     */
    KeyCode[KeyCode["IntlBackslash"] = 92] = "IntlBackslash";
    KeyCode[KeyCode["Numpad0"] = 93] = "Numpad0";
    KeyCode[KeyCode["Numpad1"] = 94] = "Numpad1";
    KeyCode[KeyCode["Numpad2"] = 95] = "Numpad2";
    KeyCode[KeyCode["Numpad3"] = 96] = "Numpad3";
    KeyCode[KeyCode["Numpad4"] = 97] = "Numpad4";
    KeyCode[KeyCode["Numpad5"] = 98] = "Numpad5";
    KeyCode[KeyCode["Numpad6"] = 99] = "Numpad6";
    KeyCode[KeyCode["Numpad7"] = 100] = "Numpad7";
    KeyCode[KeyCode["Numpad8"] = 101] = "Numpad8";
    KeyCode[KeyCode["Numpad9"] = 102] = "Numpad9";
    KeyCode[KeyCode["NumpadMultiply"] = 103] = "NumpadMultiply";
    KeyCode[KeyCode["NumpadAdd"] = 104] = "NumpadAdd";
    KeyCode[KeyCode["NUMPAD_SEPARATOR"] = 105] = "NUMPAD_SEPARATOR";
    KeyCode[KeyCode["NumpadSubtract"] = 106] = "NumpadSubtract";
    KeyCode[KeyCode["NumpadDecimal"] = 107] = "NumpadDecimal";
    KeyCode[KeyCode["NumpadDivide"] = 108] = "NumpadDivide";
    /**
     * Cover all key codes when IME is processing input.
     */
    KeyCode[KeyCode["KEY_IN_COMPOSITION"] = 109] = "KEY_IN_COMPOSITION";
    KeyCode[KeyCode["ABNT_C1"] = 110] = "ABNT_C1";
    KeyCode[KeyCode["ABNT_C2"] = 111] = "ABNT_C2";
    KeyCode[KeyCode["AudioVolumeMute"] = 112] = "AudioVolumeMute";
    KeyCode[KeyCode["AudioVolumeUp"] = 113] = "AudioVolumeUp";
    KeyCode[KeyCode["AudioVolumeDown"] = 114] = "AudioVolumeDown";
    KeyCode[KeyCode["BrowserSearch"] = 115] = "BrowserSearch";
    KeyCode[KeyCode["BrowserHome"] = 116] = "BrowserHome";
    KeyCode[KeyCode["BrowserBack"] = 117] = "BrowserBack";
    KeyCode[KeyCode["BrowserForward"] = 118] = "BrowserForward";
    KeyCode[KeyCode["MediaTrackNext"] = 119] = "MediaTrackNext";
    KeyCode[KeyCode["MediaTrackPrevious"] = 120] = "MediaTrackPrevious";
    KeyCode[KeyCode["MediaStop"] = 121] = "MediaStop";
    KeyCode[KeyCode["MediaPlayPause"] = 122] = "MediaPlayPause";
    KeyCode[KeyCode["LaunchMediaPlayer"] = 123] = "LaunchMediaPlayer";
    KeyCode[KeyCode["LaunchMail"] = 124] = "LaunchMail";
    KeyCode[KeyCode["LaunchApp2"] = 125] = "LaunchApp2";
    /**
     * VK_CLEAR, 0x0C, CLEAR key
     */
    KeyCode[KeyCode["Clear"] = 126] = "Clear";
    /**
     * Placed last to cover the length of the enum.
     * Please do not depend on this value!
     */
    KeyCode[KeyCode["MAX_VALUE"] = 127] = "MAX_VALUE";
})(KeyCode || (KeyCode = {}));
var standaloneEnums_MarkerSeverity;
(function (MarkerSeverity) {
    MarkerSeverity[MarkerSeverity["Hint"] = 1] = "Hint";
    MarkerSeverity[MarkerSeverity["Info"] = 2] = "Info";
    MarkerSeverity[MarkerSeverity["Warning"] = 4] = "Warning";
    MarkerSeverity[MarkerSeverity["Error"] = 8] = "Error";
})(standaloneEnums_MarkerSeverity || (standaloneEnums_MarkerSeverity = {}));
var MarkerTag;
(function (MarkerTag) {
    MarkerTag[MarkerTag["Unnecessary"] = 1] = "Unnecessary";
    MarkerTag[MarkerTag["Deprecated"] = 2] = "Deprecated";
})(MarkerTag || (MarkerTag = {}));
/**
 * Position in the minimap to render the decoration.
 */
var standaloneEnums_MinimapPosition;
(function (MinimapPosition) {
    MinimapPosition[MinimapPosition["Inline"] = 1] = "Inline";
    MinimapPosition[MinimapPosition["Gutter"] = 2] = "Gutter";
})(standaloneEnums_MinimapPosition || (standaloneEnums_MinimapPosition = {}));
/**
 * Type of hit element with the mouse in the editor.
 */
var MouseTargetType;
(function (MouseTargetType) {
    /**
     * Mouse is on top of an unknown element.
     */
    MouseTargetType[MouseTargetType["UNKNOWN"] = 0] = "UNKNOWN";
    /**
     * Mouse is on top of the textarea used for input.
     */
    MouseTargetType[MouseTargetType["TEXTAREA"] = 1] = "TEXTAREA";
    /**
     * Mouse is on top of the glyph margin
     */
    MouseTargetType[MouseTargetType["GUTTER_GLYPH_MARGIN"] = 2] = "GUTTER_GLYPH_MARGIN";
    /**
     * Mouse is on top of the line numbers
     */
    MouseTargetType[MouseTargetType["GUTTER_LINE_NUMBERS"] = 3] = "GUTTER_LINE_NUMBERS";
    /**
     * Mouse is on top of the line decorations
     */
    MouseTargetType[MouseTargetType["GUTTER_LINE_DECORATIONS"] = 4] = "GUTTER_LINE_DECORATIONS";
    /**
     * Mouse is on top of the whitespace left in the gutter by a view zone.
     */
    MouseTargetType[MouseTargetType["GUTTER_VIEW_ZONE"] = 5] = "GUTTER_VIEW_ZONE";
    /**
     * Mouse is on top of text in the content.
     */
    MouseTargetType[MouseTargetType["CONTENT_TEXT"] = 6] = "CONTENT_TEXT";
    /**
     * Mouse is on top of empty space in the content (e.g. after line text or below last line)
     */
    MouseTargetType[MouseTargetType["CONTENT_EMPTY"] = 7] = "CONTENT_EMPTY";
    /**
     * Mouse is on top of a view zone in the content.
     */
    MouseTargetType[MouseTargetType["CONTENT_VIEW_ZONE"] = 8] = "CONTENT_VIEW_ZONE";
    /**
     * Mouse is on top of a content widget.
     */
    MouseTargetType[MouseTargetType["CONTENT_WIDGET"] = 9] = "CONTENT_WIDGET";
    /**
     * Mouse is on top of the decorations overview ruler.
     */
    MouseTargetType[MouseTargetType["OVERVIEW_RULER"] = 10] = "OVERVIEW_RULER";
    /**
     * Mouse is on top of a scrollbar.
     */
    MouseTargetType[MouseTargetType["SCROLLBAR"] = 11] = "SCROLLBAR";
    /**
     * Mouse is on top of an overlay widget.
     */
    MouseTargetType[MouseTargetType["OVERLAY_WIDGET"] = 12] = "OVERLAY_WIDGET";
    /**
     * Mouse is outside of the editor.
     */
    MouseTargetType[MouseTargetType["OUTSIDE_EDITOR"] = 13] = "OUTSIDE_EDITOR";
})(MouseTargetType || (MouseTargetType = {}));
/**
 * A positioning preference for rendering overlay widgets.
 */
var OverlayWidgetPositionPreference;
(function (OverlayWidgetPositionPreference) {
    /**
     * Position the overlay widget in the top right corner
     */
    OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["TOP_RIGHT_CORNER"] = 0] = "TOP_RIGHT_CORNER";
    /**
     * Position the overlay widget in the bottom right corner
     */
    OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["BOTTOM_RIGHT_CORNER"] = 1] = "BOTTOM_RIGHT_CORNER";
    /**
     * Position the overlay widget in the top center
     */
    OverlayWidgetPositionPreference[OverlayWidgetPositionPreference["TOP_CENTER"] = 2] = "TOP_CENTER";
})(OverlayWidgetPositionPreference || (OverlayWidgetPositionPreference = {}));
/**
 * Vertical Lane in the overview ruler of the editor.
 */
var standaloneEnums_OverviewRulerLane;
(function (OverviewRulerLane) {
    OverviewRulerLane[OverviewRulerLane["Left"] = 1] = "Left";
    OverviewRulerLane[OverviewRulerLane["Center"] = 2] = "Center";
    OverviewRulerLane[OverviewRulerLane["Right"] = 4] = "Right";
    OverviewRulerLane[OverviewRulerLane["Full"] = 7] = "Full";
})(standaloneEnums_OverviewRulerLane || (standaloneEnums_OverviewRulerLane = {}));
var PositionAffinity;
(function (PositionAffinity) {
    /**
     * Prefers the left most position.
    */
    PositionAffinity[PositionAffinity["Left"] = 0] = "Left";
    /**
     * Prefers the right most position.
    */
    PositionAffinity[PositionAffinity["Right"] = 1] = "Right";
    /**
     * No preference.
    */
    PositionAffinity[PositionAffinity["None"] = 2] = "None";
    /**
     * If the given position is on injected text, prefers the position left of it.
    */
    PositionAffinity[PositionAffinity["LeftOfInjectedText"] = 3] = "LeftOfInjectedText";
    /**
     * If the given position is on injected text, prefers the position right of it.
    */
    PositionAffinity[PositionAffinity["RightOfInjectedText"] = 4] = "RightOfInjectedText";
})(PositionAffinity || (PositionAffinity = {}));
var RenderLineNumbersType;
(function (RenderLineNumbersType) {
    RenderLineNumbersType[RenderLineNumbersType["Off"] = 0] = "Off";
    RenderLineNumbersType[RenderLineNumbersType["On"] = 1] = "On";
    RenderLineNumbersType[RenderLineNumbersType["Relative"] = 2] = "Relative";
    RenderLineNumbersType[RenderLineNumbersType["Interval"] = 3] = "Interval";
    RenderLineNumbersType[RenderLineNumbersType["Custom"] = 4] = "Custom";
})(RenderLineNumbersType || (RenderLineNumbersType = {}));
var RenderMinimap;
(function (RenderMinimap) {
    RenderMinimap[RenderMinimap["None"] = 0] = "None";
    RenderMinimap[RenderMinimap["Text"] = 1] = "Text";
    RenderMinimap[RenderMinimap["Blocks"] = 2] = "Blocks";
})(RenderMinimap || (RenderMinimap = {}));
var ScrollType;
(function (ScrollType) {
    ScrollType[ScrollType["Smooth"] = 0] = "Smooth";
    ScrollType[ScrollType["Immediate"] = 1] = "Immediate";
})(ScrollType || (ScrollType = {}));
var ScrollbarVisibility;
(function (ScrollbarVisibility) {
    ScrollbarVisibility[ScrollbarVisibility["Auto"] = 1] = "Auto";
    ScrollbarVisibility[ScrollbarVisibility["Hidden"] = 2] = "Hidden";
    ScrollbarVisibility[ScrollbarVisibility["Visible"] = 3] = "Visible";
})(ScrollbarVisibility || (ScrollbarVisibility = {}));
/**
 * The direction of a selection.
 */
var SelectionDirection;
(function (SelectionDirection) {
    /**
     * The selection starts above where it ends.
     */
    SelectionDirection[SelectionDirection["LTR"] = 0] = "LTR";
    /**
     * The selection starts below where it ends.
     */
    SelectionDirection[SelectionDirection["RTL"] = 1] = "RTL";
})(SelectionDirection || (SelectionDirection = {}));
var standaloneEnums_SignatureHelpTriggerKind;
(function (SignatureHelpTriggerKind) {
    SignatureHelpTriggerKind[SignatureHelpTriggerKind["Invoke"] = 1] = "Invoke";
    SignatureHelpTriggerKind[SignatureHelpTriggerKind["TriggerCharacter"] = 2] = "TriggerCharacter";
    SignatureHelpTriggerKind[SignatureHelpTriggerKind["ContentChange"] = 3] = "ContentChange";
})(standaloneEnums_SignatureHelpTriggerKind || (standaloneEnums_SignatureHelpTriggerKind = {}));
/**
 * A symbol kind.
 */
var SymbolKind;
(function (SymbolKind) {
    SymbolKind[SymbolKind["File"] = 0] = "File";
    SymbolKind[SymbolKind["Module"] = 1] = "Module";
    SymbolKind[SymbolKind["Namespace"] = 2] = "Namespace";
    SymbolKind[SymbolKind["Package"] = 3] = "Package";
    SymbolKind[SymbolKind["Class"] = 4] = "Class";
    SymbolKind[SymbolKind["Method"] = 5] = "Method";
    SymbolKind[SymbolKind["Property"] = 6] = "Property";
    SymbolKind[SymbolKind["Field"] = 7] = "Field";
    SymbolKind[SymbolKind["Constructor"] = 8] = "Constructor";
    SymbolKind[SymbolKind["Enum"] = 9] = "Enum";
    SymbolKind[SymbolKind["Interface"] = 10] = "Interface";
    SymbolKind[SymbolKind["Function"] = 11] = "Function";
    SymbolKind[SymbolKind["Variable"] = 12] = "Variable";
    SymbolKind[SymbolKind["Constant"] = 13] = "Constant";
    SymbolKind[SymbolKind["String"] = 14] = "String";
    SymbolKind[SymbolKind["Number"] = 15] = "Number";
    SymbolKind[SymbolKind["Boolean"] = 16] = "Boolean";
    SymbolKind[SymbolKind["Array"] = 17] = "Array";
    SymbolKind[SymbolKind["Object"] = 18] = "Object";
    SymbolKind[SymbolKind["Key"] = 19] = "Key";
    SymbolKind[SymbolKind["Null"] = 20] = "Null";
    SymbolKind[SymbolKind["EnumMember"] = 21] = "EnumMember";
    SymbolKind[SymbolKind["Struct"] = 22] = "Struct";
    SymbolKind[SymbolKind["Event"] = 23] = "Event";
    SymbolKind[SymbolKind["Operator"] = 24] = "Operator";
    SymbolKind[SymbolKind["TypeParameter"] = 25] = "TypeParameter";
})(SymbolKind || (SymbolKind = {}));
var SymbolTag;
(function (SymbolTag) {
    SymbolTag[SymbolTag["Deprecated"] = 1] = "Deprecated";
})(SymbolTag || (SymbolTag = {}));
/**
 * The kind of animation in which the editor's cursor should be rendered.
 */
var TextEditorCursorBlinkingStyle;
(function (TextEditorCursorBlinkingStyle) {
    /**
     * Hidden
     */
    TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Hidden"] = 0] = "Hidden";
    /**
     * Blinking
     */
    TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Blink"] = 1] = "Blink";
    /**
     * Blinking with smooth fading
     */
    TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Smooth"] = 2] = "Smooth";
    /**
     * Blinking with prolonged filled state and smooth fading
     */
    TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Phase"] = 3] = "Phase";
    /**
     * Expand collapse animation on the y axis
     */
    TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Expand"] = 4] = "Expand";
    /**
     * No-Blinking
     */
    TextEditorCursorBlinkingStyle[TextEditorCursorBlinkingStyle["Solid"] = 5] = "Solid";
})(TextEditorCursorBlinkingStyle || (TextEditorCursorBlinkingStyle = {}));
/**
 * The style in which the editor's cursor should be rendered.
 */
var standaloneEnums_TextEditorCursorStyle;
(function (TextEditorCursorStyle) {
    /**
     * As a vertical line (sitting between two characters).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["Line"] = 1] = "Line";
    /**
     * As a block (sitting on top of a character).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["Block"] = 2] = "Block";
    /**
     * As a horizontal line (sitting under a character).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["Underline"] = 3] = "Underline";
    /**
     * As a thin vertical line (sitting between two characters).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["LineThin"] = 4] = "LineThin";
    /**
     * As an outlined block (sitting on top of a character).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["BlockOutline"] = 5] = "BlockOutline";
    /**
     * As a thin horizontal line (sitting under a character).
     */
    TextEditorCursorStyle[TextEditorCursorStyle["UnderlineThin"] = 6] = "UnderlineThin";
})(standaloneEnums_TextEditorCursorStyle || (standaloneEnums_TextEditorCursorStyle = {}));
/**
 * Describes the behavior of decorations when typing/editing near their edges.
 * Note: Please do not edit the values, as they very carefully match `DecorationRangeBehavior`
 */
var TrackedRangeStickiness;
(function (TrackedRangeStickiness) {
    TrackedRangeStickiness[TrackedRangeStickiness["AlwaysGrowsWhenTypingAtEdges"] = 0] = "AlwaysGrowsWhenTypingAtEdges";
    TrackedRangeStickiness[TrackedRangeStickiness["NeverGrowsWhenTypingAtEdges"] = 1] = "NeverGrowsWhenTypingAtEdges";
    TrackedRangeStickiness[TrackedRangeStickiness["GrowsOnlyWhenTypingBefore"] = 2] = "GrowsOnlyWhenTypingBefore";
    TrackedRangeStickiness[TrackedRangeStickiness["GrowsOnlyWhenTypingAfter"] = 3] = "GrowsOnlyWhenTypingAfter";
})(TrackedRangeStickiness || (TrackedRangeStickiness = {}));
/**
 * Describes how to indent wrapped lines.
 */
var WrappingIndent;
(function (WrappingIndent) {
    /**
     * No indentation => wrapped lines begin at column 1.
     */
    WrappingIndent[WrappingIndent["None"] = 0] = "None";
    /**
     * Same => wrapped lines get the same indentation as the parent.
     */
    WrappingIndent[WrappingIndent["Same"] = 1] = "Same";
    /**
     * Indent => wrapped lines get +1 indentation toward the parent.
     */
    WrappingIndent[WrappingIndent["Indent"] = 2] = "Indent";
    /**
     * DeepIndent => wrapped lines get +2 indentation toward the parent.
     */
    WrappingIndent[WrappingIndent["DeepIndent"] = 3] = "DeepIndent";
})(WrappingIndent || (WrappingIndent = {}));

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/browser/suggestInlineCompletions.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var suggestInlineCompletions_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var suggestInlineCompletions_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var suggestInlineCompletions_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};















class SuggestInlineCompletion {
    constructor(range, insertText, filterText, additionalTextEdits, command, completion) {
        this.range = range;
        this.insertText = insertText;
        this.filterText = filterText;
        this.additionalTextEdits = additionalTextEdits;
        this.command = command;
        this.completion = completion;
    }
}
let InlineCompletionResults = class InlineCompletionResults extends RefCountedDisposable {
    constructor(model, line, word, completionModel, completions, _suggestMemoryService) {
        super(completions.disposable);
        this.model = model;
        this.line = line;
        this.word = word;
        this.completionModel = completionModel;
        this._suggestMemoryService = _suggestMemoryService;
    }
    canBeReused(model, line, word) {
        return this.model === model // same model
            && this.line === line
            && this.word.word.length > 0
            && this.word.startColumn === word.startColumn && this.word.endColumn < word.endColumn // same word
            && this.completionModel.incomplete.size === 0; // no incomplete results
    }
    get items() {
        var _a;
        const result = [];
        // Split items by preselected index. This ensures the memory-selected item shows first and that better/worst
        // ranked items are before/after
        const { items } = this.completionModel;
        const selectedIndex = this._suggestMemoryService.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) {
                // skip items that have no overlap
                continue;
            }
            const range = new Range(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 & CompletionItemInsertTextRule.InsertAsSnippet)
                ? { snippet: item.completion.insertText }
                : item.completion.insertText;
            result.push(new SuggestInlineCompletion(range, insertText, (_a = item.filterTextLow) !== null && _a !== void 0 ? _a : item.labelLow, item.completion.additionalTextEdits, item.completion.command, item));
            // resolve the first N suggestions eagerly
            if (resolveCount-- >= 0) {
                item.resolve(CancellationToken.None);
            }
        }
        return result;
    }
};
InlineCompletionResults = suggestInlineCompletions_decorate([
    suggestInlineCompletions_param(5, ISuggestMemoryService)
], InlineCompletionResults);
let SuggestInlineCompletions = class SuggestInlineCompletions {
    constructor(_getEditorOption, _languageFeatureService, _clipboardService, _suggestMemoryService) {
        this._getEditorOption = _getEditorOption;
        this._languageFeatureService = _languageFeatureService;
        this._clipboardService = _clipboardService;
        this._suggestMemoryService = _suggestMemoryService;
    }
    provideInlineCompletions(model, position, context, token) {
        var _a;
        return suggestInlineCompletions_awaiter(this, void 0, void 0, function* () {
            if (context.selectedSuggestionInfo) {
                return;
            }
            const config = this._getEditorOption(81 /* EditorOption.quickSuggestions */, model);
            if (QuickSuggestionsOptions.isAllOff(config)) {
                // quick suggest is off (for this model/language)
                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 (QuickSuggestionsOptions.valueFor(config, tokenType) !== 'inline') {
                // quick suggest is off (for this token)
                return undefined;
            }
            // We consider non-empty leading words and trigger characters. The latter only
            // when no word is being typed (word characters superseed trigger characters)
            let wordInfo = model.getWordAtPosition(position);
            let triggerCharacterInfo;
            if (!(wordInfo === null || wordInfo === void 0 ? void 0 : wordInfo.word)) {
                triggerCharacterInfo = this._getTriggerCharacterInfo(model, position);
            }
            if (!(wordInfo === null || wordInfo === void 0 ? void 0 : wordInfo.word) && !triggerCharacterInfo) {
                // not at word, not a trigger character
                return;
            }
            // ensure that we have word information and that we are at the end of a word
            // otherwise we stop because we don't want to do quick suggestions inside words
            if (!wordInfo) {
                wordInfo = model.getWordUntilPosition(position);
            }
            if (wordInfo.endColumn !== position.column) {
                return;
            }
            let result;
            const leadingLineContents = model.getValueInRange(new Range(position.lineNumber, 1, position.lineNumber, position.column));
            if (!triggerCharacterInfo && ((_a = this._lastResult) === null || _a === void 0 ? void 0 : _a.canBeReused(model, position.lineNumber, wordInfo))) {
                // reuse a previous result iff possible, only a refilter is needed
                // TODO@jrieken this can be improved further and only incomplete results can be updated
                // console.log(`REUSE with ${wordInfo.word}`);
                const newLineContext = new LineContext(leadingLineContents, position.column - this._lastResult.word.endColumn);
                this._lastResult.completionModel.lineContext = newLineContext;
                this._lastResult.acquire();
                result = this._lastResult;
            }
            else {
                // refesh model is required
                const completions = yield provideSuggestionItems(this._languageFeatureService.completionProvider, model, position, new CompletionOptions(undefined, undefined, triggerCharacterInfo === null || triggerCharacterInfo === void 0 ? void 0 : triggerCharacterInfo.providers), triggerCharacterInfo && { triggerKind: 1 /* CompletionTriggerKind.TriggerCharacter */, triggerCharacter: triggerCharacterInfo.ch }, token);
                let clipboardText;
                if (completions.needsClipboard) {
                    clipboardText = yield this._clipboardService.readText();
                }
                const completionModel = new CompletionModel(completions.items, position.column, new LineContext(leadingLineContents, 0), WordDistance.None, this._getEditorOption(108 /* EditorOption.suggest */, model), this._getEditorOption(103 /* EditorOption.snippetSuggestions */, model), { boostFullMatch: false, firstMatchCanBeWeak: false }, clipboardText);
                result = new InlineCompletionResults(model, position.lineNumber, wordInfo, completionModel, completions, this._suggestMemoryService);
            }
            this._lastResult = result;
            return result;
        });
    }
    handleItemDidShow(_completions, item) {
        item.completion.resolve(CancellationToken.None);
    }
    freeInlineCompletions(result) {
        result.release();
    }
    _getTriggerCharacterInfo(model, position) {
        var _a;
        const ch = model.getValueInRange(Range.fromPositions({ lineNumber: position.lineNumber, column: position.column - 1 }, position));
        const providers = new Set();
        for (const provider of this._languageFeatureService.completionProvider.all(model)) {
            if ((_a = provider.triggerCharacters) === null || _a === void 0 ? void 0 : _a.includes(ch)) {
                providers.add(provider);
            }
        }
        if (providers.size === 0) {
            return undefined;
        }
        return { providers, ch };
    }
};
SuggestInlineCompletions = suggestInlineCompletions_decorate([
    suggestInlineCompletions_param(1, ILanguageFeaturesService),
    suggestInlineCompletions_param(2, IClipboardService),
    suggestInlineCompletions_param(3, ISuggestMemoryService)
], SuggestInlineCompletions);

let EditorContribution = class EditorContribution {
    constructor(_editor, languageFeatureService, editorService, instaService) {
        // HACK - way to contribute something only once
        if (++EditorContribution._counter === 1) {
            const provider = instaService.createInstance(SuggestInlineCompletions, (id, model) => {
                var _a;
                // HACK - reuse the editor options world outside from a "normal" contribution
                const editor = (_a = editorService.listCodeEditors().find(editor => editor.getModel() === model)) !== null && _a !== void 0 ? _a : _editor;
                return editor.getOption(id);
            });
            EditorContribution._disposable = languageFeatureService.inlineCompletionsProvider.register('*', provider);
        }
    }
    dispose() {
        var _a;
        if (--EditorContribution._counter === 0) {
            (_a = EditorContribution._disposable) === null || _a === void 0 ? void 0 : _a.dispose();
            EditorContribution._disposable = undefined;
        }
    }
};
EditorContribution._counter = 0;
EditorContribution = suggestInlineCompletions_decorate([
    suggestInlineCompletions_param(1, ILanguageFeaturesService),
    suggestInlineCompletions_param(2, ICodeEditorService),
    suggestInlineCompletions_param(3, IInstantiationService)
], EditorContribution);
registerEditorContribution('suggest.inlineCompletionsProvider', EditorContribution);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/supports/tokenization.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class ParsedTokenThemeRule {
    constructor(token, index, fontStyle, foreground, background) {
        this._parsedThemeRuleBrand = undefined;
        this.token = token;
        this.index = index;
        this.fontStyle = fontStyle;
        this.foreground = foreground;
        this.background = background;
    }
}
/**
 * Parse a raw theme into rules.
 */
function parseTokenTheme(source) {
    if (!source || !Array.isArray(source)) {
        return [];
    }
    const result = [];
    let resultLen = 0;
    for (let i = 0, len = source.length; i < len; i++) {
        const entry = source[i];
        let fontStyle = -1 /* FontStyle.NotSet */;
        if (typeof entry.fontStyle === 'string') {
            fontStyle = 0 /* FontStyle.None */;
            const segments = entry.fontStyle.split(' ');
            for (let j = 0, lenJ = segments.length; j < lenJ; j++) {
                const segment = segments[j];
                switch (segment) {
                    case 'italic':
                        fontStyle = fontStyle | 1 /* FontStyle.Italic */;
                        break;
                    case 'bold':
                        fontStyle = fontStyle | 2 /* FontStyle.Bold */;
                        break;
                    case 'underline':
                        fontStyle = fontStyle | 4 /* FontStyle.Underline */;
                        break;
                    case 'strikethrough':
                        fontStyle = fontStyle | 8 /* FontStyle.Strikethrough */;
                        break;
                }
            }
        }
        let foreground = null;
        if (typeof entry.foreground === 'string') {
            foreground = entry.foreground;
        }
        let background = null;
        if (typeof entry.background === 'string') {
            background = entry.background;
        }
        result[resultLen++] = new ParsedTokenThemeRule(entry.token || '', i, fontStyle, foreground, background);
    }
    return result;
}
/**
 * Resolve rules (i.e. inheritance).
 */
function resolveParsedTokenThemeRules(parsedThemeRules, customTokenColors) {
    // Sort rules lexicographically, and then by index if necessary
    parsedThemeRules.sort((a, b) => {
        const r = strcmp(a.token, b.token);
        if (r !== 0) {
            return r;
        }
        return a.index - b.index;
    });
    // Determine defaults
    let defaultFontStyle = 0 /* FontStyle.None */;
    let defaultForeground = '000000';
    let defaultBackground = 'ffffff';
    while (parsedThemeRules.length >= 1 && parsedThemeRules[0].token === '') {
        const incomingDefaults = parsedThemeRules.shift();
        if (incomingDefaults.fontStyle !== -1 /* FontStyle.NotSet */) {
            defaultFontStyle = incomingDefaults.fontStyle;
        }
        if (incomingDefaults.foreground !== null) {
            defaultForeground = incomingDefaults.foreground;
        }
        if (incomingDefaults.background !== null) {
            defaultBackground = incomingDefaults.background;
        }
    }
    const colorMap = new ColorMap();
    // start with token colors from custom token themes
    for (const color of customTokenColors) {
        colorMap.getId(color);
    }
    const foregroundColorId = colorMap.getId(defaultForeground);
    const backgroundColorId = colorMap.getId(defaultBackground);
    const defaults = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId);
    const root = new ThemeTrieElement(defaults);
    for (let i = 0, len = parsedThemeRules.length; i < len; i++) {
        const rule = parsedThemeRules[i];
        root.insert(rule.token, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));
    }
    return new TokenTheme(colorMap, root);
}
const colorRegExp = /^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/;
class ColorMap {
    constructor() {
        this._lastColorId = 0;
        this._id2color = [];
        this._color2id = new Map();
    }
    getId(color) {
        if (color === null) {
            return 0;
        }
        const match = color.match(colorRegExp);
        if (!match) {
            throw new Error('Illegal value for token color: ' + color);
        }
        color = match[1].toUpperCase();
        let value = this._color2id.get(color);
        if (value) {
            return value;
        }
        value = ++this._lastColorId;
        this._color2id.set(color, value);
        this._id2color[value] = Color.fromHex('#' + color);
        return value;
    }
    getColorMap() {
        return this._id2color.slice(0);
    }
}
class TokenTheme {
    constructor(colorMap, root) {
        this._colorMap = colorMap;
        this._root = root;
        this._cache = new Map();
    }
    static createFromRawTokenTheme(source, customTokenColors) {
        return this.createFromParsedTokenTheme(parseTokenTheme(source), customTokenColors);
    }
    static createFromParsedTokenTheme(source, customTokenColors) {
        return resolveParsedTokenThemeRules(source, customTokenColors);
    }
    getColorMap() {
        return this._colorMap.getColorMap();
    }
    _match(token) {
        return this._root.match(token);
    }
    match(languageId, token) {
        // The cache contains the metadata without the language bits set.
        let result = this._cache.get(token);
        if (typeof result === 'undefined') {
            const rule = this._match(token);
            const standardToken = toStandardTokenType(token);
            result = (rule.metadata
                | (standardToken << 8 /* MetadataConsts.TOKEN_TYPE_OFFSET */)) >>> 0;
            this._cache.set(token, result);
        }
        return (result
            | (languageId << 0 /* MetadataConsts.LANGUAGEID_OFFSET */)) >>> 0;
    }
}
const STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|regexp)\b/;
function toStandardTokenType(tokenType) {
    const m = tokenType.match(STANDARD_TOKEN_TYPE_REGEXP);
    if (!m) {
        return 0 /* StandardTokenType.Other */;
    }
    switch (m[1]) {
        case 'comment':
            return 1 /* StandardTokenType.Comment */;
        case 'string':
            return 2 /* StandardTokenType.String */;
        case 'regex':
            return 3 /* StandardTokenType.RegEx */;
        case 'regexp':
            return 3 /* StandardTokenType.RegEx */;
    }
    throw new Error('Unexpected match for standard token type!');
}
function strcmp(a, b) {
    if (a < b) {
        return -1;
    }
    if (a > b) {
        return 1;
    }
    return 0;
}
class ThemeTrieElementRule {
    constructor(fontStyle, foreground, background) {
        this._themeTrieElementRuleBrand = undefined;
        this._fontStyle = fontStyle;
        this._foreground = foreground;
        this._background = background;
        this.metadata = ((this._fontStyle << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
            | (this._foreground << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
            | (this._background << 24 /* MetadataConsts.BACKGROUND_OFFSET */)) >>> 0;
    }
    clone() {
        return new ThemeTrieElementRule(this._fontStyle, this._foreground, this._background);
    }
    acceptOverwrite(fontStyle, foreground, background) {
        if (fontStyle !== -1 /* FontStyle.NotSet */) {
            this._fontStyle = fontStyle;
        }
        if (foreground !== 0 /* ColorId.None */) {
            this._foreground = foreground;
        }
        if (background !== 0 /* ColorId.None */) {
            this._background = background;
        }
        this.metadata = ((this._fontStyle << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
            | (this._foreground << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
            | (this._background << 24 /* MetadataConsts.BACKGROUND_OFFSET */)) >>> 0;
    }
}
class ThemeTrieElement {
    constructor(mainRule) {
        this._themeTrieElementBrand = undefined;
        this._mainRule = mainRule;
        this._children = new Map();
    }
    match(token) {
        if (token === '') {
            return this._mainRule;
        }
        const dotIndex = token.indexOf('.');
        let head;
        let tail;
        if (dotIndex === -1) {
            head = token;
            tail = '';
        }
        else {
            head = token.substring(0, dotIndex);
            tail = token.substring(dotIndex + 1);
        }
        const child = this._children.get(head);
        if (typeof child !== 'undefined') {
            return child.match(tail);
        }
        return this._mainRule;
    }
    insert(token, fontStyle, foreground, background) {
        if (token === '') {
            // Merge into the main rule
            this._mainRule.acceptOverwrite(fontStyle, foreground, background);
            return;
        }
        const dotIndex = token.indexOf('.');
        let head;
        let tail;
        if (dotIndex === -1) {
            head = token;
            tail = '';
        }
        else {
            head = token.substring(0, dotIndex);
            tail = token.substring(dotIndex + 1);
        }
        let child = this._children.get(head);
        if (typeof child === 'undefined') {
            child = new ThemeTrieElement(this._mainRule.clone());
            this._children.set(head, child);
        }
        child.insert(tail, fontStyle, foreground, background);
    }
}
function generateTokensCSSForColorMap(colorMap) {
    const rules = [];
    for (let i = 1, len = colorMap.length; i < len; i++) {
        const color = colorMap[i];
        rules[i] = `.mtk${i} { color: ${color}; }`;
    }
    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');
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/common/themes.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


/* -------------------------------- Begin vs theme -------------------------------- */
const vs = {
    base: 'vs',
    inherit: false,
    rules: [
        { token: '', foreground: '000000', background: 'fffffe' },
        { token: 'invalid', foreground: 'cd3131' },
        { token: 'emphasis', fontStyle: 'italic' },
        { token: 'strong', fontStyle: 'bold' },
        { token: 'variable', foreground: '001188' },
        { token: 'variable.predefined', foreground: '4864AA' },
        { token: 'constant', foreground: 'dd0000' },
        { token: 'comment', foreground: '008000' },
        { token: 'number', foreground: '098658' },
        { token: 'number.hex', foreground: '3030c0' },
        { token: 'regexp', foreground: '800000' },
        { token: 'annotation', foreground: '808080' },
        { token: 'type', foreground: '008080' },
        { token: 'delimiter', foreground: '000000' },
        { token: 'delimiter.html', foreground: '383838' },
        { token: 'delimiter.xml', foreground: '0000FF' },
        { token: 'tag', foreground: '800000' },
        { token: 'tag.id.pug', foreground: '4F76AC' },
        { token: 'tag.class.pug', foreground: '4F76AC' },
        { token: 'meta.scss', foreground: '800000' },
        { token: 'metatag', foreground: 'e00000' },
        { token: 'metatag.content.html', foreground: 'FF0000' },
        { token: 'metatag.html', foreground: '808080' },
        { token: 'metatag.xml', foreground: '808080' },
        { token: 'metatag.php', fontStyle: 'bold' },
        { token: 'key', foreground: '863B00' },
        { token: 'string.key.json', foreground: 'A31515' },
        { token: 'string.value.json', foreground: '0451A5' },
        { token: 'attribute.name', foreground: 'FF0000' },
        { token: 'attribute.value', foreground: '0451A5' },
        { token: 'attribute.value.number', foreground: '098658' },
        { token: 'attribute.value.unit', foreground: '098658' },
        { token: 'attribute.value.html', foreground: '0000FF' },
        { token: 'attribute.value.xml', foreground: '0000FF' },
        { token: 'string', foreground: 'A31515' },
        { token: 'string.html', foreground: '0000FF' },
        { token: 'string.sql', foreground: 'FF0000' },
        { token: 'string.yaml', foreground: '0451A5' },
        { token: 'keyword', foreground: '0000FF' },
        { token: 'keyword.json', foreground: '0451A5' },
        { token: 'keyword.flow', foreground: 'AF00DB' },
        { token: 'keyword.flow.scss', foreground: '0000FF' },
        { token: 'operator.scss', foreground: '666666' },
        { token: 'operator.sql', foreground: '778899' },
        { token: 'operator.swift', foreground: '666666' },
        { token: 'predefined.sql', foreground: 'C700C7' },
    ],
    colors: {
        [editorBackground]: '#FFFFFE',
        [editorForeground]: '#000000',
        [editorInactiveSelection]: '#E5EBF1',
        [editorIndentGuides]: '#D3D3D3',
        [editorActiveIndentGuides]: '#939393',
        [editorSelectionHighlight]: '#ADD6FF4D'
    }
};
/* -------------------------------- End vs theme -------------------------------- */
/* -------------------------------- Begin vs-dark theme -------------------------------- */
const vs_dark = {
    base: 'vs-dark',
    inherit: false,
    rules: [
        { token: '', foreground: 'D4D4D4', background: '1E1E1E' },
        { token: 'invalid', foreground: 'f44747' },
        { token: 'emphasis', fontStyle: 'italic' },
        { token: 'strong', fontStyle: 'bold' },
        { token: 'variable', foreground: '74B0DF' },
        { token: 'variable.predefined', foreground: '4864AA' },
        { token: 'variable.parameter', foreground: '9CDCFE' },
        { token: 'constant', foreground: '569CD6' },
        { token: 'comment', foreground: '608B4E' },
        { token: 'number', foreground: 'B5CEA8' },
        { token: 'number.hex', foreground: '5BB498' },
        { token: 'regexp', foreground: 'B46695' },
        { token: 'annotation', foreground: 'cc6666' },
        { token: 'type', foreground: '3DC9B0' },
        { token: 'delimiter', foreground: 'DCDCDC' },
        { token: 'delimiter.html', foreground: '808080' },
        { token: 'delimiter.xml', foreground: '808080' },
        { token: 'tag', foreground: '569CD6' },
        { token: 'tag.id.pug', foreground: '4F76AC' },
        { token: 'tag.class.pug', foreground: '4F76AC' },
        { token: 'meta.scss', foreground: 'A79873' },
        { token: 'meta.tag', foreground: 'CE9178' },
        { token: 'metatag', foreground: 'DD6A6F' },
        { token: 'metatag.content.html', foreground: '9CDCFE' },
        { token: 'metatag.html', foreground: '569CD6' },
        { token: 'metatag.xml', foreground: '569CD6' },
        { token: 'metatag.php', fontStyle: 'bold' },
        { token: 'key', foreground: '9CDCFE' },
        { token: 'string.key.json', foreground: '9CDCFE' },
        { token: 'string.value.json', foreground: 'CE9178' },
        { token: 'attribute.name', foreground: '9CDCFE' },
        { token: 'attribute.value', foreground: 'CE9178' },
        { token: 'attribute.value.number.css', foreground: 'B5CEA8' },
        { token: 'attribute.value.unit.css', foreground: 'B5CEA8' },
        { token: 'attribute.value.hex.css', foreground: 'D4D4D4' },
        { token: 'string', foreground: 'CE9178' },
        { token: 'string.sql', foreground: 'FF0000' },
        { token: 'keyword', foreground: '569CD6' },
        { token: 'keyword.flow', foreground: 'C586C0' },
        { token: 'keyword.json', foreground: 'CE9178' },
        { token: 'keyword.flow.scss', foreground: '569CD6' },
        { token: 'operator.scss', foreground: '909090' },
        { token: 'operator.sql', foreground: '778899' },
        { token: 'operator.swift', foreground: '909090' },
        { token: 'predefined.sql', foreground: 'FF00FF' },
    ],
    colors: {
        [editorBackground]: '#1E1E1E',
        [editorForeground]: '#D4D4D4',
        [editorInactiveSelection]: '#3A3D41',
        [editorIndentGuides]: '#404040',
        [editorActiveIndentGuides]: '#707070',
        [editorSelectionHighlight]: '#ADD6FF26'
    }
};
/* -------------------------------- End vs-dark theme -------------------------------- */
/* -------------------------------- Begin hc-black theme -------------------------------- */
const hc_black = {
    base: 'hc-black',
    inherit: false,
    rules: [
        { token: '', foreground: 'FFFFFF', background: '000000' },
        { token: 'invalid', foreground: 'f44747' },
        { token: 'emphasis', fontStyle: 'italic' },
        { token: 'strong', fontStyle: 'bold' },
        { token: 'variable', foreground: '1AEBFF' },
        { token: 'variable.parameter', foreground: '9CDCFE' },
        { token: 'constant', foreground: '569CD6' },
        { token: 'comment', foreground: '608B4E' },
        { token: 'number', foreground: 'FFFFFF' },
        { token: 'regexp', foreground: 'C0C0C0' },
        { token: 'annotation', foreground: '569CD6' },
        { token: 'type', foreground: '3DC9B0' },
        { token: 'delimiter', foreground: 'FFFF00' },
        { token: 'delimiter.html', foreground: 'FFFF00' },
        { token: 'tag', foreground: '569CD6' },
        { token: 'tag.id.pug', foreground: '4F76AC' },
        { token: 'tag.class.pug', foreground: '4F76AC' },
        { token: 'meta', foreground: 'D4D4D4' },
        { token: 'meta.tag', foreground: 'CE9178' },
        { token: 'metatag', foreground: '569CD6' },
        { token: 'metatag.content.html', foreground: '1AEBFF' },
        { token: 'metatag.html', foreground: '569CD6' },
        { token: 'metatag.xml', foreground: '569CD6' },
        { token: 'metatag.php', fontStyle: 'bold' },
        { token: 'key', foreground: '9CDCFE' },
        { token: 'string.key', foreground: '9CDCFE' },
        { token: 'string.value', foreground: 'CE9178' },
        { token: 'attribute.name', foreground: '569CD6' },
        { token: 'attribute.value', foreground: '3FF23F' },
        { token: 'string', foreground: 'CE9178' },
        { token: 'string.sql', foreground: 'FF0000' },
        { token: 'keyword', foreground: '569CD6' },
        { token: 'keyword.flow', foreground: 'C586C0' },
        { token: 'operator.sql', foreground: '778899' },
        { token: 'operator.swift', foreground: '909090' },
        { token: 'predefined.sql', foreground: 'FF00FF' },
    ],
    colors: {
        [editorBackground]: '#000000',
        [editorForeground]: '#FFFFFF',
        [editorIndentGuides]: '#FFFFFF',
        [editorActiveIndentGuides]: '#FFFFFF',
    }
};
/* -------------------------------- End hc-black theme -------------------------------- */
/* -------------------------------- Begin hc-light theme -------------------------------- */
const hc_light = {
    base: 'hc-light',
    inherit: false,
    rules: [
        { token: '', foreground: '292929', background: 'FFFFFF' },
        { token: 'invalid', foreground: 'B5200D' },
        { token: 'emphasis', fontStyle: 'italic' },
        { token: 'strong', fontStyle: 'bold' },
        { token: 'variable', foreground: '264F70' },
        { token: 'variable.predefined', foreground: '4864AA' },
        { token: 'constant', foreground: 'dd0000' },
        { token: 'comment', foreground: '008000' },
        { token: 'number', foreground: '098658' },
        { token: 'number.hex', foreground: '3030c0' },
        { token: 'regexp', foreground: '800000' },
        { token: 'annotation', foreground: '808080' },
        { token: 'type', foreground: '008080' },
        { token: 'delimiter', foreground: '000000' },
        { token: 'delimiter.html', foreground: '383838' },
        { token: 'tag', foreground: '800000' },
        { token: 'tag.id.pug', foreground: '4F76AC' },
        { token: 'tag.class.pug', foreground: '4F76AC' },
        { token: 'meta.scss', foreground: '800000' },
        { token: 'metatag', foreground: 'e00000' },
        { token: 'metatag.content.html', foreground: 'B5200D' },
        { token: 'metatag.html', foreground: '808080' },
        { token: 'metatag.xml', foreground: '808080' },
        { token: 'metatag.php', fontStyle: 'bold' },
        { token: 'key', foreground: '863B00' },
        { token: 'string.key.json', foreground: 'A31515' },
        { token: 'string.value.json', foreground: '0451A5' },
        { token: 'attribute.name', foreground: '264F78' },
        { token: 'attribute.value', foreground: '0451A5' },
        { token: 'string', foreground: 'A31515' },
        { token: 'string.sql', foreground: 'B5200D' },
        { token: 'keyword', foreground: '0000FF' },
        { token: 'keyword.flow', foreground: 'AF00DB' },
        { token: 'operator.sql', foreground: '778899' },
        { token: 'operator.swift', foreground: '666666' },
        { token: 'predefined.sql', foreground: 'C700C7' },
    ],
    colors: {
        [editorBackground]: '#FFFFFF',
        [editorForeground]: '#292929',
        [editorIndentGuides]: '#292929',
        [editorActiveIndentGuides]: '#292929',
    }
};
/* -------------------------------- End hc-light theme -------------------------------- */

;// ../../node_modules/monaco-editor/esm/vs/platform/theme/browser/iconsStyleSheet.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




function getIconsStyleSheet(themeService) {
    const onDidChangeEmmiter = new Emitter();
    const iconRegistry = getIconRegistry();
    iconRegistry.onDidChange(() => onDidChangeEmmiter.fire());
    themeService === null || themeService === void 0 ? void 0 : themeService.onDidProductIconThemeChange(() => onDidChangeEmmiter.fire());
    return {
        onDidChange: onDidChangeEmmiter.event,
        getCSS() {
            const productIconTheme = themeService ? themeService.getProductIconTheme() : new UnthemedProductIconTheme();
            const usedFontIds = {};
            const formatIconRule = (contribution) => {
                const definition = productIconTheme.getIcon(contribution);
                if (!definition) {
                    return undefined;
                }
                const fontContribution = definition.font;
                if (fontContribution) {
                    usedFontIds[fontContribution.id] = fontContribution.definition;
                    return `.codicon-${contribution.id}:before { content: '${definition.fontCharacter}'; font-family: ${asCSSPropertyValue(fontContribution.id)}; }`;
                }
                // default font (codicon)
                return `.codicon-${contribution.id}:before { content: '${definition.fontCharacter}'; }`;
            };
            const rules = [];
            for (const contribution of iconRegistry.getIcons()) {
                const rule = formatIconRule(contribution);
                if (rule) {
                    rules.push(rule);
                }
            }
            for (const id in usedFontIds) {
                const definition = usedFontIds[id];
                const fontWeight = definition.weight ? `font-weight: ${definition.weight};` : '';
                const fontStyle = definition.style ? `font-style: ${definition.style};` : '';
                const src = definition.src.map(l => `${asCSSUrl(l.location)} format('${l.format}')`).join(', ');
                rules.push(`@font-face { src: ${src}; font-family: ${asCSSPropertyValue(id)};${fontWeight}${fontStyle} font-display: block; }`);
            }
            return rules.join('\n');
        }
    };
}
class UnthemedProductIconTheme {
    getIcon(contribution) {
        const iconRegistry = getIconRegistry();
        let definition = contribution.defaults;
        while (ThemeIcon.isThemeIcon(definition)) {
            const c = iconRegistry.getIcon(definition.id);
            if (!c) {
                return undefined;
            }
            definition = c.defaults;
        }
        return definition;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/standaloneThemeService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/














const VS_LIGHT_THEME_NAME = 'vs';
const VS_DARK_THEME_NAME = 'vs-dark';
const HC_BLACK_THEME_NAME = 'hc-black';
const HC_LIGHT_THEME_NAME = 'hc-light';
const standaloneThemeService_colorRegistry = Registry.as(colorRegistry_Extensions.ColorContribution);
const standaloneThemeService_themingRegistry = Registry.as(Extensions.ThemingContribution);
class StandaloneTheme {
    constructor(name, standaloneThemeData) {
        this.semanticHighlighting = false;
        this.themeData = standaloneThemeData;
        const base = standaloneThemeData.base;
        if (name.length > 0) {
            if (isBuiltinTheme(name)) {
                this.id = name;
            }
            else {
                this.id = base + ' ' + name;
            }
            this.themeName = name;
        }
        else {
            this.id = base;
            this.themeName = base;
        }
        this.colors = null;
        this.defaultColors = Object.create(null);
        this._tokenTheme = null;
    }
    get base() {
        return this.themeData.base;
    }
    notifyBaseUpdated() {
        if (this.themeData.inherit) {
            this.colors = null;
            this._tokenTheme = null;
        }
    }
    getColors() {
        if (!this.colors) {
            const colors = new Map();
            for (const id in this.themeData.colors) {
                colors.set(id, Color.fromHex(this.themeData.colors[id]));
            }
            if (this.themeData.inherit) {
                const baseData = getBuiltinRules(this.themeData.base);
                for (const id in baseData.colors) {
                    if (!colors.has(id)) {
                        colors.set(id, Color.fromHex(baseData.colors[id]));
                    }
                }
            }
            this.colors = colors;
        }
        return this.colors;
    }
    getColor(colorId, useDefault) {
        const color = this.getColors().get(colorId);
        if (color) {
            return color;
        }
        if (useDefault !== false) {
            return this.getDefault(colorId);
        }
        return undefined;
    }
    getDefault(colorId) {
        let color = this.defaultColors[colorId];
        if (color) {
            return color;
        }
        color = standaloneThemeService_colorRegistry.resolveDefaultColor(colorId, this);
        this.defaultColors[colorId] = color;
        return color;
    }
    defines(colorId) {
        return Object.prototype.hasOwnProperty.call(this.getColors(), colorId);
    }
    get type() {
        switch (this.base) {
            case VS_LIGHT_THEME_NAME: return ColorScheme.LIGHT;
            case HC_BLACK_THEME_NAME: return ColorScheme.HIGH_CONTRAST_DARK;
            case HC_LIGHT_THEME_NAME: return ColorScheme.HIGH_CONTRAST_LIGHT;
            default: return ColorScheme.DARK;
        }
    }
    get tokenTheme() {
        if (!this._tokenTheme) {
            let rules = [];
            let encodedTokensColors = [];
            if (this.themeData.inherit) {
                const baseData = getBuiltinRules(this.themeData.base);
                rules = baseData.rules;
                if (baseData.encodedTokensColors) {
                    encodedTokensColors = baseData.encodedTokensColors;
                }
            }
            // Pick up default colors from `editor.foreground` and `editor.background` if available
            const editorForeground = this.themeData.colors['editor.foreground'];
            const editorBackground = this.themeData.colors['editor.background'];
            if (editorForeground || editorBackground) {
                const rule = { token: '' };
                if (editorForeground) {
                    rule.foreground = editorForeground;
                }
                if (editorBackground) {
                    rule.background = editorBackground;
                }
                rules.push(rule);
            }
            rules = rules.concat(this.themeData.rules);
            if (this.themeData.encodedTokensColors) {
                encodedTokensColors = this.themeData.encodedTokensColors;
            }
            this._tokenTheme = TokenTheme.createFromRawTokenTheme(rules, encodedTokensColors);
        }
        return this._tokenTheme;
    }
    getTokenStyleMetadata(type, modifiers, modelLanguage) {
        // use theme rules match
        const style = this.tokenTheme._match([type].concat(modifiers).join('.'));
        const metadata = style.metadata;
        const foreground = TokenMetadata.getForeground(metadata);
        const fontStyle = TokenMetadata.getFontStyle(metadata);
        return {
            foreground: 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 */)
        };
    }
}
function isBuiltinTheme(themeName) {
    return (themeName === VS_LIGHT_THEME_NAME
        || themeName === VS_DARK_THEME_NAME
        || themeName === HC_BLACK_THEME_NAME
        || themeName === HC_LIGHT_THEME_NAME);
}
function getBuiltinRules(builtinTheme) {
    switch (builtinTheme) {
        case VS_LIGHT_THEME_NAME:
            return vs;
        case VS_DARK_THEME_NAME:
            return vs_dark;
        case HC_BLACK_THEME_NAME:
            return hc_black;
        case HC_LIGHT_THEME_NAME:
            return hc_light;
    }
}
function newBuiltInTheme(builtinTheme) {
    const themeData = getBuiltinRules(builtinTheme);
    return new StandaloneTheme(builtinTheme, themeData);
}
class StandaloneThemeService extends Disposable {
    constructor() {
        super();
        this._onColorThemeChange = this._register(new Emitter());
        this.onDidColorThemeChange = this._onColorThemeChange.event;
        this._onProductIconThemeChange = this._register(new Emitter());
        this.onDidProductIconThemeChange = this._onProductIconThemeChange.event;
        this._environment = Object.create(null);
        this._builtInProductIconTheme = new UnthemedProductIconTheme();
        this._autoDetectHighContrast = true;
        this._knownThemes = new Map();
        this._knownThemes.set(VS_LIGHT_THEME_NAME, newBuiltInTheme(VS_LIGHT_THEME_NAME));
        this._knownThemes.set(VS_DARK_THEME_NAME, newBuiltInTheme(VS_DARK_THEME_NAME));
        this._knownThemes.set(HC_BLACK_THEME_NAME, newBuiltInTheme(HC_BLACK_THEME_NAME));
        this._knownThemes.set(HC_LIGHT_THEME_NAME, newBuiltInTheme(HC_LIGHT_THEME_NAME));
        const iconsStyleSheet = getIconsStyleSheet(this);
        this._codiconCSS = iconsStyleSheet.getCSS();
        this._themeCSS = '';
        this._allCSS = `${this._codiconCSS}\n${this._themeCSS}`;
        this._globalStyleElement = null;
        this._styleElements = [];
        this._colorMapOverride = null;
        this.setTheme(VS_LIGHT_THEME_NAME);
        this._onOSSchemeChanged();
        iconsStyleSheet.onDidChange(() => {
            this._codiconCSS = iconsStyleSheet.getCSS();
            this._updateCSS();
        });
        addMatchMediaChangeListener('(forced-colors: active)', () => {
            this._onOSSchemeChanged();
        });
    }
    registerEditorContainer(domNode) {
        if (isInShadowDOM(domNode)) {
            return this._registerShadowDomContainer(domNode);
        }
        return this._registerRegularEditorContainer();
    }
    _registerRegularEditorContainer() {
        if (!this._globalStyleElement) {
            this._globalStyleElement = createStyleSheet();
            this._globalStyleElement.className = 'monaco-colors';
            this._globalStyleElement.textContent = this._allCSS;
            this._styleElements.push(this._globalStyleElement);
        }
        return Disposable.None;
    }
    _registerShadowDomContainer(domNode) {
        const styleElement = createStyleSheet(domNode);
        styleElement.className = 'monaco-colors';
        styleElement.textContent = this._allCSS;
        this._styleElements.push(styleElement);
        return {
            dispose: () => {
                for (let i = 0; i < this._styleElements.length; i++) {
                    if (this._styleElements[i] === styleElement) {
                        this._styleElements.splice(i, 1);
                        return;
                    }
                }
            }
        };
    }
    defineTheme(themeName, themeData) {
        if (!/^[a-z0-9\-]+$/i.test(themeName)) {
            throw new Error('Illegal theme name!');
        }
        if (!isBuiltinTheme(themeData.base) && !isBuiltinTheme(themeName)) {
            throw new Error('Illegal theme base!');
        }
        // set or replace theme
        this._knownThemes.set(themeName, new StandaloneTheme(themeName, themeData));
        if (isBuiltinTheme(themeName)) {
            this._knownThemes.forEach(theme => {
                if (theme.base === themeName) {
                    theme.notifyBaseUpdated();
                }
            });
        }
        if (this._theme.themeName === themeName) {
            this.setTheme(themeName); // refresh theme
        }
    }
    getColorTheme() {
        return this._theme;
    }
    setColorMapOverride(colorMapOverride) {
        this._colorMapOverride = colorMapOverride;
        this._updateThemeOrColorMap();
    }
    setTheme(themeName) {
        let theme;
        if (this._knownThemes.has(themeName)) {
            theme = this._knownThemes.get(themeName);
        }
        else {
            theme = this._knownThemes.get(VS_LIGHT_THEME_NAME);
        }
        this._updateActualTheme(theme);
    }
    _updateActualTheme(desiredTheme) {
        if (!desiredTheme || this._theme === desiredTheme) {
            // Nothing to do
            return;
        }
        this._theme = desiredTheme;
        this._updateThemeOrColorMap();
    }
    _onOSSchemeChanged() {
        if (this._autoDetectHighContrast) {
            const wantsHighContrast = window.matchMedia(`(forced-colors: active)`).matches;
            if (wantsHighContrast !== isHighContrast(this._theme.type)) {
                // switch to high contrast or non-high contrast but stick to dark or light
                let newThemeName;
                if (isDark(this._theme.type)) {
                    newThemeName = wantsHighContrast ? HC_BLACK_THEME_NAME : VS_DARK_THEME_NAME;
                }
                else {
                    newThemeName = wantsHighContrast ? HC_LIGHT_THEME_NAME : VS_LIGHT_THEME_NAME;
                }
                this._updateActualTheme(this._knownThemes.get(newThemeName));
            }
        }
    }
    setAutoDetectHighContrast(autoDetectHighContrast) {
        this._autoDetectHighContrast = autoDetectHighContrast;
        this._onOSSchemeChanged();
    }
    _updateThemeOrColorMap() {
        const cssRules = [];
        const hasRule = {};
        const ruleCollector = {
            addRule: (rule) => {
                if (!hasRule[rule]) {
                    cssRules.push(rule);
                    hasRule[rule] = true;
                }
            }
        };
        standaloneThemeService_themingRegistry.getThemingParticipants().forEach(p => p(this._theme, ruleCollector, this._environment));
        const colorVariables = [];
        for (const item of standaloneThemeService_colorRegistry.getColors()) {
            const color = this._theme.getColor(item.id, true);
            if (color) {
                colorVariables.push(`${asCssVariableName(item.id)}: ${color.toString()};`);
            }
        }
        ruleCollector.addRule(`.monaco-editor { ${colorVariables.join('\n')} }`);
        const colorMap = this._colorMapOverride || this._theme.tokenTheme.getColorMap();
        ruleCollector.addRule(generateTokensCSSForColorMap(colorMap));
        this._themeCSS = cssRules.join('\n');
        this._updateCSS();
        languages_TokenizationRegistry.setColorMap(colorMap);
        this._onColorThemeChange.fire(this._theme);
    }
    _updateCSS() {
        this._allCSS = `${this._codiconCSS}\n${this._themeCSS}`;
        this._styleElements.forEach(styleElement => styleElement.textContent = this._allCSS);
    }
    getFileIconTheme() {
        return {
            hasFileIcons: false,
            hasFolderIcons: false,
            hidesExplorerArrows: false
        };
    }
    getProductIconTheme() {
        return this._builtInProductIconTheme;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class ToggleHighContrast extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.toggleHighContrast',
            label: ToggleHighContrastNLS.toggleHighContrast,
            alias: 'Toggle High Contrast Theme',
            precondition: undefined
        });
        this._originalThemeName = null;
    }
    run(accessor, editor) {
        const standaloneThemeService = accessor.get(IStandaloneThemeService);
        const currentTheme = standaloneThemeService.getColorTheme();
        if (isHighContrast(currentTheme.type)) {
            // We must toggle back to the integrator's theme
            standaloneThemeService.setTheme(this._originalThemeName || (isDark(currentTheme.type) ? VS_DARK_THEME_NAME : VS_LIGHT_THEME_NAME));
            this._originalThemeName = null;
        }
        else {
            standaloneThemeService.setTheme(isDark(currentTheme.type) ? HC_BLACK_THEME_NAME : HC_LIGHT_THEME_NAME);
            this._originalThemeName = currentTheme.themeName;
        }
    }
}
registerEditorAction(ToggleHighContrast);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/tokenization/browser/tokenization.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class ForceRetokenizeAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.forceRetokenize',
            label: localize('forceRetokenize', "Developer: Force Retokenize"),
            alias: 'Developer: Force Retokenize',
            precondition: undefined
        });
    }
    run(accessor, editor) {
        if (!editor.hasModel()) {
            return;
        }
        const model = editor.getModel();
        model.tokenization.resetTokenization();
        const sw = new StopWatch(true);
        model.tokenization.forceTokenization(model.getLineCount());
        sw.stop();
        console.log(`tokenization took ${sw.elapsed()}`);
    }
}
registerEditorAction(ForceRetokenizeAction);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter.css
var unicodeHighlighter = __webpack_require__(70914);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter.css

      
      
      
      
      
      
      
      
      

var unicodeHighlighter_options = {};

unicodeHighlighter_options.styleTagTransform = (styleTagTransform_default());
unicodeHighlighter_options.setAttributes = (setAttributesWithoutAttributes_default());

      unicodeHighlighter_options.insert = insertBySelector_default().bind(null, "head");
    
unicodeHighlighter_options.domAPI = (styleDomAPI_default());
unicodeHighlighter_options.insertStyleElement = (insertStyleElement_default());

var unicodeHighlighter_update = injectStylesIntoStyleTag_default()(unicodeHighlighter/* default */.A, unicodeHighlighter_options);




       /* harmony default export */ const browser_unicodeHighlighter = (unicodeHighlighter/* default */.A && unicodeHighlighter/* default */.A.locals ? unicodeHighlighter/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/unicodeTextModelHighlighter.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





class UnicodeTextModelHighlighter {
    static computeUnicodeHighlights(model, options, range) {
        const startLine = range ? range.startLineNumber : 1;
        const endLine = range ? range.endLineNumber : model.getLineCount();
        const codePointHighlighter = new CodePointHighlighter(options);
        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 Searcher(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;
            // Reset regex to search from the beginning
            searcher.reset(0);
            do {
                m = searcher.next(lineContent);
                if (m) {
                    let startIndex = m.index;
                    let endIndex = m.index + m[0].length;
                    // Extend range to entire code point
                    if (startIndex > 0) {
                        const charCodeBefore = lineContent.charCodeAt(startIndex - 1);
                        if (isHighSurrogate(charCodeBefore)) {
                            startIndex--;
                        }
                    }
                    if (endIndex + 1 < lineLength) {
                        const charCodeBefore = lineContent.charCodeAt(endIndex - 1);
                        if (isHighSurrogate(charCodeBefore)) {
                            endIndex++;
                        }
                    }
                    const str = lineContent.substring(startIndex, endIndex);
                    const word = getWordAtText(startIndex + 1, DEFAULT_WORD_REGEXP, lineContent, 0);
                    const highlightReason = codePointHighlighter.shouldHighlightNonBasicASCII(str, word ? word.word : null);
                    if (highlightReason !== 0 /* SimpleHighlightReason.None */) {
                        if (highlightReason === 3 /* SimpleHighlightReason.Ambiguous */) {
                            ambiguousCharacterCount++;
                        }
                        else if (highlightReason === 2 /* SimpleHighlightReason.Invisible */) {
                            invisibleCharacterCount++;
                        }
                        else if (highlightReason === 1 /* SimpleHighlightReason.NonBasicASCII */) {
                            nonBasicAsciiCharacterCount++;
                        }
                        else {
                            assertNever(highlightReason);
                        }
                        const MAX_RESULT_LENGTH = 1000;
                        if (ranges.length >= MAX_RESULT_LENGTH) {
                            hasMore = true;
                            break forLoop;
                        }
                        ranges.push(new Range(lineNumber, startIndex + 1, lineNumber, endIndex + 1));
                    }
                }
            } while (m);
        }
        return {
            ranges,
            hasMore,
            ambiguousCharacterCount,
            invisibleCharacterCount,
            nonBasicAsciiCharacterCount
        };
    }
    static computeUnicodeHighlightReason(char, options) {
        const codePointHighlighter = new CodePointHighlighter(options);
        const reason = codePointHighlighter.shouldHighlightNonBasicASCII(char, null);
        switch (reason) {
            case 0 /* SimpleHighlightReason.None */:
                return null;
            case 2 /* SimpleHighlightReason.Invisible */:
                return { kind: 1 /* UnicodeHighlighterReasonKind.Invisible */ };
            case 3 /* SimpleHighlightReason.Ambiguous */: {
                const codePoint = char.codePointAt(0);
                const primaryConfusable = codePointHighlighter.ambiguousCharacters.getPrimaryConfusable(codePoint);
                const notAmbiguousInLocales = AmbiguousCharacters.getLocales().filter((l) => !AmbiguousCharacters.getInstance(new Set([...options.allowedLocales, l])).isAmbiguous(codePoint));
                return { kind: 0 /* UnicodeHighlighterReasonKind.Ambiguous */, confusableWith: String.fromCodePoint(primaryConfusable), notAmbiguousInLocales };
            }
            case 1 /* SimpleHighlightReason.NonBasicASCII */:
                return { kind: 2 /* UnicodeHighlighterReasonKind.NonBasicAscii */ };
        }
    }
}
function buildRegExpCharClassExpr(codePoints, flags) {
    const src = `[${escapeRegExpCharacters(codePoints.map((i) => String.fromCodePoint(i)).join(''))}]`;
    return src;
}
class CodePointHighlighter {
    constructor(options) {
        this.options = options;
        this.allowedCodePoints = new Set(options.allowedCodePoints);
        this.ambiguousCharacters = AmbiguousCharacters.getInstance(new Set(options.allowedLocales));
    }
    getCandidateCodePoints() {
        if (this.options.nonBasicASCII) {
            return 'allNonBasicAscii';
        }
        const set = new Set();
        if (this.options.invisibleCharacters) {
            for (const cp of InvisibleCharacters.codePoints) {
                if (!isAllowedInvisibleCharacter(String.fromCodePoint(cp))) {
                    set.add(cp);
                }
            }
        }
        if (this.options.ambiguousCharacters) {
            for (const cp of this.ambiguousCharacters.getConfusableCodePoints()) {
                set.add(cp);
            }
        }
        for (const cp of this.allowedCodePoints) {
            set.delete(cp);
        }
        return set;
    }
    shouldHighlightNonBasicASCII(character, wordContext) {
        const codePoint = character.codePointAt(0);
        if (this.allowedCodePoints.has(codePoint)) {
            return 0 /* SimpleHighlightReason.None */;
        }
        if (this.options.nonBasicASCII) {
            return 1 /* SimpleHighlightReason.NonBasicASCII */;
        }
        let hasBasicASCIICharacters = false;
        let hasNonConfusableNonBasicAsciiCharacter = false;
        if (wordContext) {
            for (const char of wordContext) {
                const codePoint = char.codePointAt(0);
                const isBasicASCII = strings_isBasicASCII(char);
                hasBasicASCIICharacters = hasBasicASCIICharacters || isBasicASCII;
                if (!isBasicASCII &&
                    !this.ambiguousCharacters.isAmbiguous(codePoint) &&
                    !InvisibleCharacters.isInvisibleCharacter(codePoint)) {
                    hasNonConfusableNonBasicAsciiCharacter = true;
                }
            }
        }
        if (
        /* Don't allow mixing weird looking characters with ASCII */ !hasBasicASCIICharacters &&
            /* Is there an obviously weird looking character? */ hasNonConfusableNonBasicAsciiCharacter) {
            return 0 /* SimpleHighlightReason.None */;
        }
        if (this.options.invisibleCharacters) {
            // TODO check for emojis
            if (!isAllowedInvisibleCharacter(character) && InvisibleCharacters.isInvisibleCharacter(codePoint)) {
                return 2 /* SimpleHighlightReason.Invisible */;
            }
        }
        if (this.options.ambiguousCharacters) {
            if (this.ambiguousCharacters.isAmbiguous(codePoint)) {
                return 3 /* SimpleHighlightReason.Ambiguous */;
            }
        }
        return 0 /* SimpleHighlightReason.None */;
    }
}
function isAllowedInvisibleCharacter(character) {
    return character === ' ' || character === '\n' || character === '\t';
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/contrib/unicodeHighlighter/browser/bannerController.css
var bannerController = __webpack_require__(10014);
;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/unicodeHighlighter/browser/bannerController.css

      
      
      
      
      
      
      
      
      

var bannerController_options = {};

bannerController_options.styleTagTransform = (styleTagTransform_default());
bannerController_options.setAttributes = (setAttributesWithoutAttributes_default());

      bannerController_options.insert = insertBySelector_default().bind(null, "head");
    
bannerController_options.domAPI = (styleDomAPI_default());
bannerController_options.insertStyleElement = (insertStyleElement_default());

var bannerController_update = injectStylesIntoStyleTag_default()(bannerController/* default */.A, bannerController_options);




       /* harmony default export */ const browser_bannerController = (bannerController/* default */.A && bannerController/* default */.A.locals ? bannerController/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/platform/opener/browser/link.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var link_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var link_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};









let link_Link = class Link extends Disposable {
    constructor(container, _link, options = {}, openerService) {
        var _a;
        super();
        this._link = _link;
        this._enabled = true;
        this.el = append(container, dom_$('a.monaco-link', {
            tabIndex: (_a = _link.tabIndex) !== null && _a !== void 0 ? _a : 0,
            href: _link.href,
            title: _link.title
        }, _link.label));
        this.el.setAttribute('role', 'button');
        const onClickEmitter = this._register(new DomEmitter(this.el, 'click'));
        const onKeyPress = this._register(new DomEmitter(this.el, 'keypress'));
        const onEnterPress = Event.chain(onKeyPress.event)
            .map(e => new StandardKeyboardEvent(e))
            .filter(e => e.keyCode === 3 /* KeyCode.Enter */)
            .event;
        const onTap = this._register(new DomEmitter(this.el, touch_EventType.Tap)).event;
        this._register(Gesture.addTarget(this.el));
        const onOpen = Event.any(onClickEmitter.event, onEnterPress, onTap);
        this._register(onOpen(e => {
            if (!this.enabled) {
                return;
            }
            EventHelper.stop(e, true);
            if (options === null || options === void 0 ? void 0 : options.opener) {
                options.opener(this._link.href);
            }
            else {
                openerService.open(this._link.href, { allowCommands: true });
            }
        }));
        this.enabled = true;
    }
    get enabled() {
        return this._enabled;
    }
    set enabled(enabled) {
        if (enabled) {
            this.el.setAttribute('aria-disabled', 'false');
            this.el.tabIndex = 0;
            this.el.style.pointerEvents = 'auto';
            this.el.style.opacity = '1';
            this.el.style.cursor = 'pointer';
            this._enabled = false;
        }
        else {
            this.el.setAttribute('aria-disabled', 'true');
            this.el.tabIndex = -1;
            this.el.style.pointerEvents = 'none';
            this.el.style.opacity = '0.4';
            this.el.style.cursor = 'default';
            this._enabled = true;
        }
        this._enabled = enabled;
    }
};
link_Link = link_decorate([
    link_param(3, IOpenerService)
], link_Link);

registerThemingParticipant((theme, collector) => {
    const textLinkForegroundColor = theme.getColor(textLinkForeground);
    if (textLinkForegroundColor) {
        collector.addRule(`.monaco-link { color: ${textLinkForegroundColor}; }`);
    }
    const textLinkActiveForegroundColor = theme.getColor(textLinkActiveForeground);
    if (textLinkActiveForegroundColor) {
        collector.addRule(`.monaco-link:hover { color: ${textLinkActiveForegroundColor}; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/unicodeHighlighter/browser/bannerController.js
var bannerController_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var bannerController_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/










const BANNER_ELEMENT_HEIGHT = 26;
let BannerController = class BannerController extends Disposable {
    constructor(_editor, instantiationService) {
        super();
        this._editor = _editor;
        this.instantiationService = instantiationService;
        this.banner = this._register(this.instantiationService.createInstance(Banner));
    }
    hide() {
        this._editor.setBanner(null, 0);
        this.banner.clear();
    }
    show(item) {
        this.banner.show(Object.assign(Object.assign({}, item), { onClose: () => {
                var _a;
                this.hide();
                (_a = item.onClose) === null || _a === void 0 ? void 0 : _a.call(item);
            } }));
        this._editor.setBanner(this.banner.element, BANNER_ELEMENT_HEIGHT);
    }
};
BannerController = bannerController_decorate([
    bannerController_param(1, IInstantiationService)
], BannerController);

// TODO@hediet: Investigate if this can be reused by the workspace banner (bannerPart.ts).
let Banner = class Banner extends Disposable {
    constructor(instantiationService) {
        super();
        this.instantiationService = instantiationService;
        this.markdownRenderer = this.instantiationService.createInstance(MarkdownRenderer, {});
        this.element = dom_$('div.editor-banner');
        this.element.tabIndex = 0;
    }
    getAriaLabel(item) {
        if (item.ariaLabel) {
            return item.ariaLabel;
        }
        if (typeof item.message === 'string') {
            return item.message;
        }
        return undefined;
    }
    getBannerMessage(message) {
        if (typeof message === 'string') {
            const element = dom_$('span');
            element.innerText = message;
            return element;
        }
        return this.markdownRenderer.render(message).element;
    }
    clear() {
        clearNode(this.element);
    }
    show(item) {
        // Clear previous item
        clearNode(this.element);
        // Banner aria label
        const ariaLabel = this.getAriaLabel(item);
        if (ariaLabel) {
            this.element.setAttribute('aria-label', ariaLabel);
        }
        // Icon
        const iconContainer = append(this.element, dom_$('div.icon-container'));
        iconContainer.setAttribute('aria-hidden', 'true');
        if (item.icon) {
            iconContainer.appendChild(dom_$(`div${ThemeIcon.asCSSSelector(item.icon)}`));
        }
        // Message
        const messageContainer = append(this.element, dom_$('div.message-container'));
        messageContainer.setAttribute('aria-hidden', 'true');
        messageContainer.appendChild(this.getBannerMessage(item.message));
        // Message Actions
        this.messageActionsContainer = append(this.element, dom_$('div.message-actions-container'));
        if (item.actions) {
            for (const action of item.actions) {
                this._register(this.instantiationService.createInstance(link_Link, this.messageActionsContainer, Object.assign(Object.assign({}, action), { tabIndex: -1 }), {}));
            }
        }
        // Action
        const actionBarContainer = append(this.element, dom_$('div.action-container'));
        this.actionBar = this._register(new ActionBar(actionBarContainer));
        this.actionBar.push(this._register(new Action('banner.close', 'Close Banner', ThemeIcon.asClassName(widgetClose), true, () => {
            if (typeof item.onClose === 'function') {
                item.onClose();
            }
        })), { icon: true, label: false });
        this.actionBar.setFocusable(false);
    }
};
Banner = bannerController_decorate([
    bannerController_param(0, IInstantiationService)
], Banner);

;// ../../node_modules/monaco-editor/esm/vs/platform/workspace/common/workspaceTrust.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const IWorkspaceTrustManagementService = createDecorator('workspaceTrustManagementService');

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var unicodeHighlighter_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var unicodeHighlighter_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var unicodeHighlighter_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
























const warningIcon = registerIcon('extensions-warning-message', Codicon.warning, localize('warningIcon', 'Icon shown with a warning message in the extensions editor.'));
let UnicodeHighlighter = class UnicodeHighlighter extends Disposable {
    constructor(_editor, _editorWorkerService, _workspaceTrustService, instantiationService) {
        super();
        this._editor = _editor;
        this._editorWorkerService = _editorWorkerService;
        this._workspaceTrustService = _workspaceTrustService;
        this._highlighter = null;
        this._bannerClosed = false;
        this._updateState = (state) => {
            if (state && state.hasMore) {
                if (this._bannerClosed) {
                    return;
                }
                // This document contains many non-basic ASCII characters.
                const max = Math.max(state.ambiguousCharacterCount, state.nonBasicAsciiCharacterCount, state.invisibleCharacterCount);
                let data;
                if (state.nonBasicAsciiCharacterCount >= max) {
                    data = {
                        message: localize('unicodeHighlighting.thisDocumentHasManyNonBasicAsciiUnicodeCharacters', 'This document contains many non-basic ASCII unicode characters'),
                        command: new DisableHighlightingOfNonBasicAsciiCharactersAction(),
                    };
                }
                else if (state.ambiguousCharacterCount >= max) {
                    data = {
                        message: localize('unicodeHighlighting.thisDocumentHasManyAmbiguousUnicodeCharacters', 'This document contains many ambiguous unicode characters'),
                        command: new DisableHighlightingOfAmbiguousCharactersAction(),
                    };
                }
                else if (state.invisibleCharacterCount >= max) {
                    data = {
                        message: localize('unicodeHighlighting.thisDocumentHasManyInvisibleUnicodeCharacters', 'This document contains many invisible unicode characters'),
                        command: new DisableHighlightingOfInvisibleCharactersAction(),
                    };
                }
                else {
                    throw new Error('Unreachable');
                }
                this._bannerController.show({
                    id: 'unicodeHighlightBanner',
                    message: data.message,
                    icon: warningIcon,
                    actions: [
                        {
                            label: data.command.shortLabel,
                            href: `command:${data.command.id}`
                        }
                    ],
                    onClose: () => {
                        this._bannerClosed = true;
                    },
                });
            }
            else {
                this._bannerController.hide();
            }
        };
        this._bannerController = this._register(instantiationService.createInstance(BannerController, _editor));
        this._register(this._editor.onDidChangeModel(() => {
            this._bannerClosed = false;
            this._updateHighlighter();
        }));
        this._options = _editor.getOption(115 /* EditorOption.unicodeHighlighting */);
        this._register(_workspaceTrustService.onDidChangeTrust(e => {
            this._updateHighlighter();
        }));
        this._register(_editor.onDidChangeConfiguration(e => {
            if (e.hasChanged(115 /* EditorOption.unicodeHighlighting */)) {
                this._options = _editor.getOption(115 /* EditorOption.unicodeHighlighting */);
                this._updateHighlighter();
            }
        }));
        this._updateHighlighter();
    }
    dispose() {
        if (this._highlighter) {
            this._highlighter.dispose();
            this._highlighter = null;
        }
        super.dispose();
    }
    _updateHighlighter() {
        this._updateState(null);
        if (this._highlighter) {
            this._highlighter.dispose();
            this._highlighter = null;
        }
        if (!this._editor.hasModel()) {
            return;
        }
        const options = unicodeHighlighter_resolveOptions(this._workspaceTrustService.isWorkspaceTrusted(), this._options);
        if ([
            options.nonBasicASCII,
            options.ambiguousCharacters,
            options.invisibleCharacters,
        ].every((option) => option === false)) {
            // Don't do anything if the feature is fully disabled
            return;
        }
        const highlightOptions = {
            nonBasicASCII: options.nonBasicASCII,
            ambiguousCharacters: options.ambiguousCharacters,
            invisibleCharacters: options.invisibleCharacters,
            includeComments: options.includeComments,
            includeStrings: options.includeStrings,
            allowedCodePoints: Object.keys(options.allowedCharacters).map(c => c.codePointAt(0)),
            allowedLocales: Object.keys(options.allowedLocales).map(locale => {
                if (locale === '_os') {
                    const osLocale = new Intl.NumberFormat().resolvedOptions().locale;
                    return osLocale;
                }
                else if (locale === '_vscode') {
                    return language;
                }
                return locale;
            }),
        };
        if (this._editorWorkerService.canComputeUnicodeHighlights(this._editor.getModel().uri)) {
            this._highlighter = new DocumentUnicodeHighlighter(this._editor, highlightOptions, this._updateState, this._editorWorkerService);
        }
        else {
            this._highlighter = new ViewportUnicodeHighlighter(this._editor, highlightOptions, this._updateState);
        }
    }
    getDecorationInfo(decoration) {
        if (this._highlighter) {
            return this._highlighter.getDecorationInfo(decoration);
        }
        return null;
    }
};
UnicodeHighlighter.ID = 'editor.contrib.unicodeHighlighter';
UnicodeHighlighter = unicodeHighlighter_decorate([
    unicodeHighlighter_param(1, IEditorWorkerService),
    unicodeHighlighter_param(2, IWorkspaceTrustManagementService),
    unicodeHighlighter_param(3, IInstantiationService)
], UnicodeHighlighter);

function unicodeHighlighter_resolveOptions(trusted, options) {
    return {
        nonBasicASCII: options.nonBasicASCII === inUntrustedWorkspace ? !trusted : options.nonBasicASCII,
        ambiguousCharacters: options.ambiguousCharacters,
        invisibleCharacters: options.invisibleCharacters,
        includeComments: options.includeComments === inUntrustedWorkspace ? !trusted : options.includeComments,
        includeStrings: options.includeStrings === inUntrustedWorkspace ? !trusted : options.includeStrings,
        allowedCharacters: options.allowedCharacters,
        allowedLocales: options.allowedLocales,
    };
}
let DocumentUnicodeHighlighter = class DocumentUnicodeHighlighter extends Disposable {
    constructor(_editor, _options, _updateState, _editorWorkerService) {
        super();
        this._editor = _editor;
        this._options = _options;
        this._updateState = _updateState;
        this._editorWorkerService = _editorWorkerService;
        this._model = this._editor.getModel();
        this._decorations = this._editor.createDecorationsCollection();
        this._updateSoon = this._register(new RunOnceScheduler(() => this._update(), 250));
        this._register(this._editor.onDidChangeModelContent(() => {
            this._updateSoon.schedule();
        }));
        this._updateSoon.schedule();
    }
    dispose() {
        this._decorations.clear();
        super.dispose();
    }
    _update() {
        if (this._model.isDisposed()) {
            return;
        }
        if (!this._model.mightContainNonBasicASCII()) {
            this._decorations.clear();
            return;
        }
        const modelVersionId = this._model.getVersionId();
        this._editorWorkerService
            .computedUnicodeHighlights(this._model.uri, this._options)
            .then((info) => {
            if (this._model.isDisposed()) {
                return;
            }
            if (this._model.getVersionId() !== modelVersionId) {
                // model changed in the meantime
                return;
            }
            this._updateState(info);
            const decorations = [];
            if (!info.hasMore) {
                // Don't show decoration if there are too many.
                // In this case, a banner is shown.
                for (const range of info.ranges) {
                    decorations.push({
                        range: range,
                        options: Decorations.instance.getDecorationFromOptions(this._options),
                    });
                }
            }
            this._decorations.set(decorations);
        });
    }
    getDecorationInfo(decoration) {
        if (!this._decorations.has(decoration)) {
            return null;
        }
        const model = this._editor.getModel();
        if (!isModelDecorationVisible(model, decoration)) {
            return null;
        }
        const text = model.getValueInRange(decoration.range);
        return {
            reason: computeReason(text, this._options),
            inComment: isModelDecorationInComment(model, decoration),
            inString: isModelDecorationInString(model, decoration),
        };
    }
};
DocumentUnicodeHighlighter = unicodeHighlighter_decorate([
    unicodeHighlighter_param(3, IEditorWorkerService)
], DocumentUnicodeHighlighter);
class ViewportUnicodeHighlighter extends Disposable {
    constructor(_editor, _options, _updateState) {
        super();
        this._editor = _editor;
        this._options = _options;
        this._updateState = _updateState;
        this._model = this._editor.getModel();
        this._decorations = this._editor.createDecorationsCollection();
        this._updateSoon = this._register(new RunOnceScheduler(() => this._update(), 250));
        this._register(this._editor.onDidLayoutChange(() => {
            this._updateSoon.schedule();
        }));
        this._register(this._editor.onDidScrollChange(() => {
            this._updateSoon.schedule();
        }));
        this._register(this._editor.onDidChangeHiddenAreas(() => {
            this._updateSoon.schedule();
        }));
        this._register(this._editor.onDidChangeModelContent(() => {
            this._updateSoon.schedule();
        }));
        this._updateSoon.schedule();
    }
    dispose() {
        this._decorations.clear();
        super.dispose();
    }
    _update() {
        if (this._model.isDisposed()) {
            return;
        }
        if (!this._model.mightContainNonBasicASCII()) {
            this._decorations.clear();
            return;
        }
        const ranges = this._editor.getVisibleRanges();
        const decorations = [];
        const totalResult = {
            ranges: [],
            ambiguousCharacterCount: 0,
            invisibleCharacterCount: 0,
            nonBasicAsciiCharacterCount: 0,
            hasMore: false,
        };
        for (const range of ranges) {
            const result = UnicodeTextModelHighlighter.computeUnicodeHighlights(this._model, this._options, range);
            for (const r of result.ranges) {
                totalResult.ranges.push(r);
            }
            totalResult.ambiguousCharacterCount += totalResult.ambiguousCharacterCount;
            totalResult.invisibleCharacterCount += totalResult.invisibleCharacterCount;
            totalResult.nonBasicAsciiCharacterCount += totalResult.nonBasicAsciiCharacterCount;
            totalResult.hasMore = totalResult.hasMore || result.hasMore;
        }
        if (!totalResult.hasMore) {
            // Don't show decorations if there are too many.
            // A banner will be shown instead.
            for (const range of totalResult.ranges) {
                decorations.push({ range, options: Decorations.instance.getDecorationFromOptions(this._options) });
            }
        }
        this._updateState(totalResult);
        this._decorations.set(decorations);
    }
    getDecorationInfo(decoration) {
        if (!this._decorations.has(decoration)) {
            return null;
        }
        const model = this._editor.getModel();
        const text = model.getValueInRange(decoration.range);
        if (!isModelDecorationVisible(model, decoration)) {
            return null;
        }
        return {
            reason: computeReason(text, this._options),
            inComment: isModelDecorationInComment(model, decoration),
            inString: isModelDecorationInString(model, decoration),
        };
    }
}
let UnicodeHighlighterHoverParticipant = class UnicodeHighlighterHoverParticipant {
    constructor(_editor, _languageService, _openerService) {
        this._editor = _editor;
        this._languageService = _languageService;
        this._openerService = _openerService;
        this.hoverOrdinal = 4;
    }
    computeSync(anchor, lineDecorations) {
        if (!this._editor.hasModel() || anchor.type !== 1 /* HoverAnchorType.Range */) {
            return [];
        }
        const model = this._editor.getModel();
        const unicodeHighlighter = this._editor.getContribution(UnicodeHighlighter.ID);
        if (!unicodeHighlighter) {
            return [];
        }
        const result = [];
        let index = 300;
        for (const d of lineDecorations) {
            const highlightInfo = unicodeHighlighter.getDecorationInfo(d);
            if (!highlightInfo) {
                continue;
            }
            const char = model.getValueInRange(d.range);
            // text refers to a single character.
            const codePoint = char.codePointAt(0);
            const codePointStr = formatCodePointMarkdown(codePoint);
            let reason;
            switch (highlightInfo.reason.kind) {
                case 0 /* UnicodeHighlighterReasonKind.Ambiguous */:
                    reason = localize('unicodeHighlight.characterIsAmbiguous', 'The character {0} could be confused with the character {1}, which is more common in source code.', codePointStr, formatCodePointMarkdown(highlightInfo.reason.confusableWith.codePointAt(0)));
                    break;
                case 1 /* UnicodeHighlighterReasonKind.Invisible */:
                    reason = localize('unicodeHighlight.characterIsInvisible', 'The character {0} is invisible.', codePointStr);
                    break;
                case 2 /* UnicodeHighlighterReasonKind.NonBasicAscii */:
                    reason = localize('unicodeHighlight.characterIsNonBasicAscii', 'The character {0} is not a basic ASCII character.', codePointStr);
                    break;
            }
            const adjustSettingsArgs = {
                codePoint: codePoint,
                reason: highlightInfo.reason,
                inComment: highlightInfo.inComment,
                inString: highlightInfo.inString,
            };
            const adjustSettings = localize('unicodeHighlight.adjustSettings', 'Adjust settings');
            const uri = `command:${ShowExcludeOptions.ID}?${encodeURIComponent(JSON.stringify(adjustSettingsArgs))}`;
            const markdown = new MarkdownString('', true)
                .appendMarkdown(reason)
                .appendText(' ')
                .appendLink(uri, adjustSettings);
            result.push(new MarkdownHover(this, d.range, [markdown], index++));
        }
        return result;
    }
    renderHoverParts(context, hoverParts) {
        return renderMarkdownHovers(context, hoverParts, this._editor, this._languageService, this._openerService);
    }
};
UnicodeHighlighterHoverParticipant = unicodeHighlighter_decorate([
    unicodeHighlighter_param(1, ILanguageService),
    unicodeHighlighter_param(2, IOpenerService)
], UnicodeHighlighterHoverParticipant);

function codePointToHex(codePoint) {
    return `U+${codePoint.toString(16).padStart(4, '0')}`;
}
function formatCodePointMarkdown(codePoint) {
    let value = `\`${codePointToHex(codePoint)}\``;
    if (!InvisibleCharacters.isInvisibleCharacter(codePoint)) {
        // Don't render any control characters or any invisible characters, as they cannot be seen anyways.
        value += ` "${`${renderCodePointAsInlineCode(codePoint)}`}"`;
    }
    return value;
}
function renderCodePointAsInlineCode(codePoint) {
    if (codePoint === 96 /* CharCode.BackTick */) {
        return '`` ` ``';
    }
    return '`' + String.fromCodePoint(codePoint) + '`';
}
function computeReason(char, options) {
    return UnicodeTextModelHighlighter.computeUnicodeHighlightReason(char, options);
}
class Decorations {
    constructor() {
        this.map = new Map();
    }
    getDecorationFromOptions(options) {
        return this.getDecoration(!options.includeComments, !options.includeStrings);
    }
    getDecoration(hideInComments, hideInStrings) {
        const key = `${hideInComments}${hideInStrings}`;
        let options = this.map.get(key);
        if (!options) {
            options = ModelDecorationOptions.createDynamic({
                description: 'unicode-highlight',
                stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
                className: 'unicode-highlight',
                showIfCollapsed: true,
                overviewRuler: null,
                minimap: null,
                hideInCommentTokens: hideInComments,
                hideInStringTokens: hideInStrings,
            });
            this.map.set(key, options);
        }
        return options;
    }
}
Decorations.instance = new Decorations();
class DisableHighlightingInCommentsAction extends EditorAction {
    constructor() {
        super({
            id: DisableHighlightingOfAmbiguousCharactersAction.ID,
            label: localize('action.unicodeHighlight.disableHighlightingInComments', 'Disable highlighting of characters in comments'),
            alias: 'Disable highlighting of characters in comments',
            precondition: undefined
        });
        this.shortLabel = localize('unicodeHighlight.disableHighlightingInComments.shortLabel', 'Disable Highlight In Comments');
    }
    run(accessor, editor, args) {
        return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
            const configurationService = accessor === null || accessor === void 0 ? void 0 : accessor.get(IConfigurationService);
            if (configurationService) {
                this.runAction(configurationService);
            }
        });
    }
    runAction(configurationService) {
        return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
            yield configurationService.updateValue(unicodeHighlightConfigKeys.includeComments, false, 2 /* ConfigurationTarget.USER */);
        });
    }
}
class DisableHighlightingInStringsAction extends EditorAction {
    constructor() {
        super({
            id: DisableHighlightingOfAmbiguousCharactersAction.ID,
            label: localize('action.unicodeHighlight.disableHighlightingInStrings', 'Disable highlighting of characters in strings'),
            alias: 'Disable highlighting of characters in strings',
            precondition: undefined
        });
        this.shortLabel = localize('unicodeHighlight.disableHighlightingInStrings.shortLabel', 'Disable Highlight In Strings');
    }
    run(accessor, editor, args) {
        return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
            const configurationService = accessor === null || accessor === void 0 ? void 0 : accessor.get(IConfigurationService);
            if (configurationService) {
                this.runAction(configurationService);
            }
        });
    }
    runAction(configurationService) {
        return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
            yield configurationService.updateValue(unicodeHighlightConfigKeys.includeStrings, false, 2 /* ConfigurationTarget.USER */);
        });
    }
}
class DisableHighlightingOfAmbiguousCharactersAction extends EditorAction {
    constructor() {
        super({
            id: DisableHighlightingOfAmbiguousCharactersAction.ID,
            label: localize('action.unicodeHighlight.disableHighlightingOfAmbiguousCharacters', 'Disable highlighting of ambiguous characters'),
            alias: 'Disable highlighting of ambiguous characters',
            precondition: undefined
        });
        this.shortLabel = localize('unicodeHighlight.disableHighlightingOfAmbiguousCharacters.shortLabel', 'Disable Ambiguous Highlight');
    }
    run(accessor, editor, args) {
        return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
            const configurationService = accessor === null || accessor === void 0 ? void 0 : accessor.get(IConfigurationService);
            if (configurationService) {
                this.runAction(configurationService);
            }
        });
    }
    runAction(configurationService) {
        return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
            yield configurationService.updateValue(unicodeHighlightConfigKeys.ambiguousCharacters, false, 2 /* ConfigurationTarget.USER */);
        });
    }
}
DisableHighlightingOfAmbiguousCharactersAction.ID = 'editor.action.unicodeHighlight.disableHighlightingOfAmbiguousCharacters';
class DisableHighlightingOfInvisibleCharactersAction extends EditorAction {
    constructor() {
        super({
            id: DisableHighlightingOfInvisibleCharactersAction.ID,
            label: localize('action.unicodeHighlight.disableHighlightingOfInvisibleCharacters', 'Disable highlighting of invisible characters'),
            alias: 'Disable highlighting of invisible characters',
            precondition: undefined
        });
        this.shortLabel = localize('unicodeHighlight.disableHighlightingOfInvisibleCharacters.shortLabel', 'Disable Invisible Highlight');
    }
    run(accessor, editor, args) {
        return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
            const configurationService = accessor === null || accessor === void 0 ? void 0 : accessor.get(IConfigurationService);
            if (configurationService) {
                this.runAction(configurationService);
            }
        });
    }
    runAction(configurationService) {
        return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
            yield configurationService.updateValue(unicodeHighlightConfigKeys.invisibleCharacters, false, 2 /* ConfigurationTarget.USER */);
        });
    }
}
DisableHighlightingOfInvisibleCharactersAction.ID = 'editor.action.unicodeHighlight.disableHighlightingOfInvisibleCharacters';
class DisableHighlightingOfNonBasicAsciiCharactersAction extends EditorAction {
    constructor() {
        super({
            id: DisableHighlightingOfNonBasicAsciiCharactersAction.ID,
            label: localize('action.unicodeHighlight.disableHighlightingOfNonBasicAsciiCharacters', 'Disable highlighting of non basic ASCII characters'),
            alias: 'Disable highlighting of non basic ASCII characters',
            precondition: undefined
        });
        this.shortLabel = localize('unicodeHighlight.disableHighlightingOfNonBasicAsciiCharacters.shortLabel', 'Disable Non ASCII Highlight');
    }
    run(accessor, editor, args) {
        return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
            const configurationService = accessor === null || accessor === void 0 ? void 0 : accessor.get(IConfigurationService);
            if (configurationService) {
                this.runAction(configurationService);
            }
        });
    }
    runAction(configurationService) {
        return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
            yield configurationService.updateValue(unicodeHighlightConfigKeys.nonBasicASCII, false, 2 /* ConfigurationTarget.USER */);
        });
    }
}
DisableHighlightingOfNonBasicAsciiCharactersAction.ID = 'editor.action.unicodeHighlight.disableHighlightingOfNonBasicAsciiCharacters';
class ShowExcludeOptions extends EditorAction {
    constructor() {
        super({
            id: ShowExcludeOptions.ID,
            label: localize('action.unicodeHighlight.showExcludeOptions', "Show Exclude Options"),
            alias: 'Show Exclude Options',
            precondition: undefined
        });
    }
    run(accessor, editor, args) {
        return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
            const { codePoint, reason, inString, inComment } = args;
            const char = String.fromCodePoint(codePoint);
            const quickPickService = accessor.get(IQuickInputService);
            const configurationService = accessor.get(IConfigurationService);
            function getExcludeCharFromBeingHighlightedLabel(codePoint) {
                if (InvisibleCharacters.isInvisibleCharacter(codePoint)) {
                    return localize('unicodeHighlight.excludeInvisibleCharFromBeingHighlighted', 'Exclude {0} (invisible character) from being highlighted', codePointToHex(codePoint));
                }
                return localize('unicodeHighlight.excludeCharFromBeingHighlighted', 'Exclude {0} from being highlighted', `${codePointToHex(codePoint)} "${char}"`);
            }
            const options = [];
            if (reason.kind === 0 /* UnicodeHighlighterReasonKind.Ambiguous */) {
                for (const locale of reason.notAmbiguousInLocales) {
                    options.push({
                        label: localize("unicodeHighlight.allowCommonCharactersInLanguage", "Allow unicode characters that are more common in the language \"{0}\".", locale),
                        run: () => unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
                            excludeLocaleFromBeingHighlighted(configurationService, [locale]);
                        }),
                    });
                }
            }
            options.push({
                label: getExcludeCharFromBeingHighlightedLabel(codePoint),
                run: () => excludeCharFromBeingHighlighted(configurationService, [codePoint])
            });
            if (inComment) {
                const action = new DisableHighlightingInCommentsAction();
                options.push({ label: action.label, run: () => unicodeHighlighter_awaiter(this, void 0, void 0, function* () { return action.runAction(configurationService); }) });
            }
            else if (inString) {
                const action = new DisableHighlightingInStringsAction();
                options.push({ label: action.label, run: () => unicodeHighlighter_awaiter(this, void 0, void 0, function* () { return action.runAction(configurationService); }) });
            }
            if (reason.kind === 0 /* UnicodeHighlighterReasonKind.Ambiguous */) {
                const action = new DisableHighlightingOfAmbiguousCharactersAction();
                options.push({ label: action.label, run: () => unicodeHighlighter_awaiter(this, void 0, void 0, function* () { return action.runAction(configurationService); }) });
            }
            else if (reason.kind === 1 /* UnicodeHighlighterReasonKind.Invisible */) {
                const action = new DisableHighlightingOfInvisibleCharactersAction();
                options.push({ label: action.label, run: () => unicodeHighlighter_awaiter(this, void 0, void 0, function* () { return action.runAction(configurationService); }) });
            }
            else if (reason.kind === 2 /* UnicodeHighlighterReasonKind.NonBasicAscii */) {
                const action = new DisableHighlightingOfNonBasicAsciiCharactersAction();
                options.push({ label: action.label, run: () => unicodeHighlighter_awaiter(this, void 0, void 0, function* () { return action.runAction(configurationService); }) });
            }
            else {
                expectNever(reason);
            }
            const result = yield quickPickService.pick(options, { title: localize('unicodeHighlight.configureUnicodeHighlightOptions', 'Configure Unicode Highlight Options') });
            if (result) {
                yield result.run();
            }
        });
    }
}
ShowExcludeOptions.ID = 'editor.action.unicodeHighlight.showExcludeOptions';
function excludeCharFromBeingHighlighted(configurationService, charCodes) {
    return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
        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;
        }
        yield configurationService.updateValue(unicodeHighlightConfigKeys.allowedCharacters, value, 2 /* ConfigurationTarget.USER */);
    });
}
function excludeLocaleFromBeingHighlighted(configurationService, locales) {
    var _a;
    return unicodeHighlighter_awaiter(this, void 0, void 0, function* () {
        const existingValue = (_a = configurationService.inspect(unicodeHighlightConfigKeys.allowedLocales).user) === null || _a === void 0 ? void 0 : _a.value;
        let value;
        if ((typeof existingValue === 'object') && existingValue) {
            // Copy value, as the existing value is read only
            value = Object.assign({}, existingValue);
        }
        else {
            value = {};
        }
        for (const locale of locales) {
            value[locale] = true;
        }
        yield configurationService.updateValue(unicodeHighlightConfigKeys.allowedLocales, value, 2 /* ConfigurationTarget.USER */);
    });
}
function expectNever(value) {
    throw new Error(`Unexpected value: ${value}`);
}
registerEditorAction(DisableHighlightingOfAmbiguousCharactersAction);
registerEditorAction(DisableHighlightingOfInvisibleCharactersAction);
registerEditorAction(DisableHighlightingOfNonBasicAsciiCharactersAction);
registerEditorAction(ShowExcludeOptions);
registerEditorContribution(UnicodeHighlighter.ID, UnicodeHighlighter);
HoverParticipantRegistry.register(UnicodeHighlighterHoverParticipant);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/unusualLineTerminators/browser/unusualLineTerminators.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var unusualLineTerminators_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var unusualLineTerminators_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var unusualLineTerminators_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};






const ignoreUnusualLineTerminators = 'ignoreUnusualLineTerminators';
function writeIgnoreState(codeEditorService, model, state) {
    codeEditorService.setModelProperty(model.uri, ignoreUnusualLineTerminators, state);
}
function readIgnoreState(codeEditorService, model) {
    return codeEditorService.getModelProperty(model.uri, ignoreUnusualLineTerminators);
}
let UnusualLineTerminatorsDetector = class UnusualLineTerminatorsDetector extends Disposable {
    constructor(_editor, _dialogService, _codeEditorService) {
        super();
        this._editor = _editor;
        this._dialogService = _dialogService;
        this._codeEditorService = _codeEditorService;
        this._config = this._editor.getOption(116 /* EditorOption.unusualLineTerminators */);
        this._register(this._editor.onDidChangeConfiguration((e) => {
            if (e.hasChanged(116 /* EditorOption.unusualLineTerminators */)) {
                this._config = this._editor.getOption(116 /* EditorOption.unusualLineTerminators */);
                this._checkForUnusualLineTerminators();
            }
        }));
        this._register(this._editor.onDidChangeModel(() => {
            this._checkForUnusualLineTerminators();
        }));
        this._register(this._editor.onDidChangeModelContent((e) => {
            if (e.isUndoing) {
                // skip checking in case of undoing
                return;
            }
            this._checkForUnusualLineTerminators();
        }));
    }
    _checkForUnusualLineTerminators() {
        return unusualLineTerminators_awaiter(this, void 0, void 0, function* () {
            if (this._config === 'off') {
                return;
            }
            if (!this._editor.hasModel()) {
                return;
            }
            const model = this._editor.getModel();
            if (!model.mightContainUnusualLineTerminators()) {
                return;
            }
            const ignoreState = readIgnoreState(this._codeEditorService, model);
            if (ignoreState === true) {
                // this model should be ignored
                return;
            }
            if (this._editor.getOption(83 /* EditorOption.readOnly */)) {
                // read only editor => sorry!
                return;
            }
            if (this._config === 'auto') {
                // just do it!
                model.removeUnusualLineTerminators(this._editor.getSelections());
                return;
            }
            const result = yield this._dialogService.confirm({
                title: localize('unusualLineTerminators.title', "Unusual Line Terminators"),
                message: localize('unusualLineTerminators.message', "Detected unusual line terminators"),
                detail: localize('unusualLineTerminators.detail', "The file '{0}' contains one or more unusual line terminator characters, like Line Separator (LS) or Paragraph Separator (PS).\n\nIt is recommended to remove them from the file. This can be configured via `editor.unusualLineTerminators`.", resources_basename(model.uri)),
                primaryButton: localize('unusualLineTerminators.fix', "Remove Unusual Line Terminators"),
                secondaryButton: localize('unusualLineTerminators.ignore', "Ignore")
            });
            if (!result.confirmed) {
                // this model should be ignored
                writeIgnoreState(this._codeEditorService, model, true);
                return;
            }
            model.removeUnusualLineTerminators(this._editor.getSelections());
        });
    }
};
UnusualLineTerminatorsDetector.ID = 'editor.contrib.unusualLineTerminatorsDetector';
UnusualLineTerminatorsDetector = unusualLineTerminators_decorate([
    unusualLineTerminators_param(1, IDialogService),
    unusualLineTerminators_param(2, ICodeEditorService)
], UnusualLineTerminatorsDetector);

registerEditorContribution(UnusualLineTerminatorsDetector.ID, UnusualLineTerminatorsDetector);

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/semanticTokensDto.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


function reverseEndianness(arr) {
    for (let i = 0, len = arr.length; i < len; i += 4) {
        // flip bytes 0<->3 and 1<->2
        const b0 = arr[i + 0];
        const b1 = arr[i + 1];
        const b2 = arr[i + 2];
        const b3 = arr[i + 3];
        arr[i + 0] = b3;
        arr[i + 1] = b2;
        arr[i + 2] = b1;
        arr[i + 3] = b0;
    }
}
function toLittleEndianBuffer(arr) {
    const uint8Arr = new Uint8Array(arr.buffer, arr.byteOffset, arr.length * 4);
    if (!isLittleEndian()) {
        // the byte order must be changed
        reverseEndianness(uint8Arr);
    }
    return VSBuffer.wrap(uint8Arr);
}
function encodeSemanticTokensDto(semanticTokens) {
    const dest = new Uint32Array(encodeSemanticTokensDtoSize(semanticTokens));
    let offset = 0;
    dest[offset++] = semanticTokens.id;
    if (semanticTokens.type === 'full') {
        dest[offset++] = 1 /* EncodedSemanticTokensType.Full */;
        dest[offset++] = semanticTokens.data.length;
        dest.set(semanticTokens.data, offset);
        offset += semanticTokens.data.length;
    }
    else {
        dest[offset++] = 2 /* EncodedSemanticTokensType.Delta */;
        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 // id
        + 1 // type
    );
    if (semanticTokens.type === 'full') {
        result += (+1 // data length
            + semanticTokens.data.length);
    }
    else {
        result += (+1 // delta count
        );
        result += (+1 // start
            + 1 // deleteCount
            + 1 // data length
        ) * semanticTokens.deltas.length;
        for (const delta of semanticTokens.deltas) {
            if (delta.data) {
                result += delta.data.length;
            }
        }
    }
    return result;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/getSemanticTokens.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var getSemanticTokens_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};









function isSemanticTokens(v) {
    return v && !!(v.data);
}
function isSemanticTokensEdits(v) {
    return v && Array.isArray(v.edits);
}
class DocumentSemanticTokensResult {
    constructor(provider, tokens, error) {
        this.provider = provider;
        this.tokens = tokens;
        this.error = error;
    }
}
function hasDocumentSemanticTokensProvider(registry, model) {
    return registry.has(model);
}
function getDocumentSemanticTokensProviders(registry, model) {
    const groups = registry.orderedGroups(model);
    return (groups.length > 0 ? groups[0] : []);
}
function getDocumentSemanticTokens(registry, model, lastProvider, lastResultId, token) {
    return getSemanticTokens_awaiter(this, void 0, void 0, function* () {
        const providers = getDocumentSemanticTokensProviders(registry, model);
        // Get tokens from all providers at the same time.
        const results = yield Promise.all(providers.map((provider) => getSemanticTokens_awaiter(this, void 0, void 0, function* () {
            let result;
            let error = null;
            try {
                result = yield provider.provideDocumentSemanticTokens(model, (provider === lastProvider ? lastResultId : null), token);
            }
            catch (err) {
                error = err;
                result = null;
            }
            if (!result || (!isSemanticTokens(result) && !isSemanticTokensEdits(result))) {
                result = null;
            }
            return new DocumentSemanticTokensResult(provider, result, error);
        })));
        // Try to return the first result with actual tokens or
        // the first result which threw an error (!!)
        for (const result of results) {
            if (result.error) {
                throw result.error;
            }
            if (result.tokens) {
                return result;
            }
        }
        // Return the first result, even if it doesn't have tokens
        if (results.length > 0) {
            return results[0];
        }
        return null;
    });
}
function _getDocumentSemanticTokensProviderHighestGroup(registry, model) {
    const result = registry.orderedGroups(model);
    return (result.length > 0 ? result[0] : null);
}
class DocumentRangeSemanticTokensResult {
    constructor(provider, tokens) {
        this.provider = provider;
        this.tokens = tokens;
    }
}
function hasDocumentRangeSemanticTokensProvider(providers, model) {
    return providers.has(model);
}
function getDocumentRangeSemanticTokensProviders(providers, model) {
    const groups = providers.orderedGroups(model);
    return (groups.length > 0 ? groups[0] : []);
}
function getDocumentRangeSemanticTokens(registry, model, range, token) {
    return getSemanticTokens_awaiter(this, void 0, void 0, function* () {
        const providers = getDocumentRangeSemanticTokensProviders(registry, model);
        // Get tokens from all providers at the same time.
        const results = yield Promise.all(providers.map((provider) => getSemanticTokens_awaiter(this, void 0, void 0, function* () {
            let result;
            try {
                result = yield provider.provideDocumentRangeSemanticTokens(model, range, token);
            }
            catch (err) {
                onUnexpectedExternalError(err);
                result = null;
            }
            if (!result || !isSemanticTokens(result)) {
                result = null;
            }
            return new DocumentRangeSemanticTokensResult(provider, result);
        })));
        // Try to return the first result with actual tokens
        for (const result of results) {
            if (result.tokens) {
                return result;
            }
        }
        // Return the first result, even if it doesn't have tokens
        if (results.length > 0) {
            return results[0];
        }
        return null;
    });
}
CommandsRegistry.registerCommand('_provideDocumentSemanticTokensLegend', (accessor, ...args) => getSemanticTokens_awaiter(void 0, void 0, void 0, function* () {
    const [uri] = args;
    assertType(uri instanceof URI);
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
        return undefined;
    }
    const { documentSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
    const providers = _getDocumentSemanticTokensProviderHighestGroup(documentSemanticTokensProvider, model);
    if (!providers) {
        // there is no provider => fall back to a document range semantic tokens provider
        return accessor.get(ICommandService).executeCommand('_provideDocumentRangeSemanticTokensLegend', uri);
    }
    return providers[0].getLegend();
}));
CommandsRegistry.registerCommand('_provideDocumentSemanticTokens', (accessor, ...args) => getSemanticTokens_awaiter(void 0, void 0, void 0, function* () {
    const [uri] = args;
    assertType(uri instanceof URI);
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
        return undefined;
    }
    const { documentSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
    if (!hasDocumentSemanticTokensProvider(documentSemanticTokensProvider, model)) {
        // there is no provider => fall back to a document range semantic tokens provider
        return accessor.get(ICommandService).executeCommand('_provideDocumentRangeSemanticTokens', uri, model.getFullModelRange());
    }
    const r = yield getDocumentSemanticTokens(documentSemanticTokensProvider, model, null, null, CancellationToken.None);
    if (!r) {
        return undefined;
    }
    const { provider, tokens } = r;
    if (!tokens || !isSemanticTokens(tokens)) {
        return undefined;
    }
    const buff = encodeSemanticTokensDto({
        id: 0,
        type: 'full',
        data: tokens.data
    });
    if (tokens.resultId) {
        provider.releaseDocumentSemanticTokens(tokens.resultId);
    }
    return buff;
}));
CommandsRegistry.registerCommand('_provideDocumentRangeSemanticTokensLegend', (accessor, ...args) => getSemanticTokens_awaiter(void 0, void 0, void 0, function* () {
    const [uri, range] = args;
    assertType(uri instanceof URI);
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
        return undefined;
    }
    const { documentRangeSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
    const providers = getDocumentRangeSemanticTokensProviders(documentRangeSemanticTokensProvider, model);
    if (providers.length === 0) {
        // no providers
        return undefined;
    }
    if (providers.length === 1) {
        // straight forward case, just a single provider
        return providers[0].getLegend();
    }
    if (!range || !Range.isIRange(range)) {
        // if no range is provided, we cannot support multiple providers
        // as we cannot fall back to the one which would give results
        // => return the first legend for backwards compatibility and print a warning
        console.warn(`provideDocumentRangeSemanticTokensLegend might be out-of-sync with provideDocumentRangeSemanticTokens unless a range argument is passed in`);
        return providers[0].getLegend();
    }
    const result = yield getDocumentRangeSemanticTokens(documentRangeSemanticTokensProvider, model, Range.lift(range), CancellationToken.None);
    if (!result) {
        return undefined;
    }
    return result.provider.getLegend();
}));
CommandsRegistry.registerCommand('_provideDocumentRangeSemanticTokens', (accessor, ...args) => getSemanticTokens_awaiter(void 0, void 0, void 0, function* () {
    const [uri, range] = args;
    assertType(uri instanceof URI);
    assertType(Range.isIRange(range));
    const model = accessor.get(IModelService).getModel(uri);
    if (!model) {
        return undefined;
    }
    const { documentRangeSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
    const result = yield getDocumentRangeSemanticTokens(documentRangeSemanticTokensProvider, model, Range.lift(range), CancellationToken.None);
    if (!result || !result.tokens) {
        // there is no provider or it didn't return tokens
        return undefined;
    }
    return encodeSemanticTokensDto({
        id: 0,
        type: 'full',
        data: result.tokens.data
    });
}));

;// ../../node_modules/monaco-editor/esm/vs/editor/common/tokens/sparseMultilineTokens.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



/**
 * Represents sparse tokens over a contiguous range of lines.
 */
class SparseMultilineTokens {
    constructor(startLineNumber, tokens) {
        this._startLineNumber = startLineNumber;
        this._tokens = tokens;
        this._endLineNumber = this._startLineNumber + this._tokens.getMaxDeltaLine();
    }
    static create(startLineNumber, tokens) {
        return new SparseMultilineTokens(startLineNumber, new SparseMultilineTokensStorage(tokens));
    }
    /**
     * (Inclusive) start line number for these tokens.
     */
    get startLineNumber() {
        return this._startLineNumber;
    }
    /**
     * (Inclusive) end line number for these tokens.
     */
    get endLineNumber() {
        return this._endLineNumber;
    }
    toString() {
        return this._tokens.toString(this._startLineNumber);
    }
    _updateEndLineNumber() {
        this._endLineNumber = this._startLineNumber + this._tokens.getMaxDeltaLine();
    }
    isEmpty() {
        return this._tokens.isEmpty();
    }
    getLineTokens(lineNumber) {
        if (this._startLineNumber <= lineNumber && lineNumber <= this._endLineNumber) {
            return this._tokens.getLineTokens(lineNumber - this._startLineNumber);
        }
        return null;
    }
    getRange() {
        const deltaRange = this._tokens.getRange();
        if (!deltaRange) {
            return deltaRange;
        }
        return new Range(this._startLineNumber + deltaRange.startLineNumber, deltaRange.startColumn, this._startLineNumber + deltaRange.endLineNumber, deltaRange.endColumn);
    }
    removeTokens(range) {
        const startLineIndex = range.startLineNumber - this._startLineNumber;
        const endLineIndex = range.endLineNumber - this._startLineNumber;
        this._startLineNumber += this._tokens.removeTokens(startLineIndex, range.startColumn - 1, endLineIndex, range.endColumn - 1);
        this._updateEndLineNumber();
    }
    split(range) {
        // split tokens to two:
        // a) all the tokens before `range`
        // b) all the tokens after `range`
        const startLineIndex = range.startLineNumber - this._startLineNumber;
        const endLineIndex = range.endLineNumber - this._startLineNumber;
        const [a, b, bDeltaLine] = this._tokens.split(startLineIndex, range.startColumn - 1, endLineIndex, range.endColumn - 1);
        return [new SparseMultilineTokens(this._startLineNumber, a), new SparseMultilineTokens(this._startLineNumber + bDeltaLine, b)];
    }
    applyEdit(range, text) {
        const [eolCount, firstLineLength, lastLineLength] = countEOL(text);
        this.acceptEdit(range, eolCount, firstLineLength, lastLineLength, text.length > 0 ? text.charCodeAt(0) : 0 /* CharCode.Null */);
    }
    acceptEdit(range, eolCount, firstLineLength, lastLineLength, firstCharCode) {
        this._acceptDeleteRange(range);
        this._acceptInsertText(new Position(range.startLineNumber, range.startColumn), eolCount, firstLineLength, lastLineLength, firstCharCode);
        this._updateEndLineNumber();
    }
    _acceptDeleteRange(range) {
        if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
            // Nothing to delete
            return;
        }
        const firstLineIndex = range.startLineNumber - this._startLineNumber;
        const lastLineIndex = range.endLineNumber - this._startLineNumber;
        if (lastLineIndex < 0) {
            // this deletion occurs entirely before this block, so we only need to adjust line numbers
            const deletedLinesCount = lastLineIndex - firstLineIndex;
            this._startLineNumber -= deletedLinesCount;
            return;
        }
        const tokenMaxDeltaLine = this._tokens.getMaxDeltaLine();
        if (firstLineIndex >= tokenMaxDeltaLine + 1) {
            // this deletion occurs entirely after this block, so there is nothing to do
            return;
        }
        if (firstLineIndex < 0 && lastLineIndex >= tokenMaxDeltaLine + 1) {
            // this deletion completely encompasses this block
            this._startLineNumber = 0;
            this._tokens.clear();
            return;
        }
        if (firstLineIndex < 0) {
            const deletedBefore = -firstLineIndex;
            this._startLineNumber -= deletedBefore;
            this._tokens.acceptDeleteRange(range.startColumn - 1, 0, 0, lastLineIndex, range.endColumn - 1);
        }
        else {
            this._tokens.acceptDeleteRange(0, firstLineIndex, range.startColumn - 1, lastLineIndex, range.endColumn - 1);
        }
    }
    _acceptInsertText(position, eolCount, firstLineLength, lastLineLength, firstCharCode) {
        if (eolCount === 0 && firstLineLength === 0) {
            // Nothing to insert
            return;
        }
        const lineIndex = position.lineNumber - this._startLineNumber;
        if (lineIndex < 0) {
            // this insertion occurs before this block, so we only need to adjust line numbers
            this._startLineNumber += eolCount;
            return;
        }
        const tokenMaxDeltaLine = this._tokens.getMaxDeltaLine();
        if (lineIndex >= tokenMaxDeltaLine + 1) {
            // this insertion occurs after this block, so there is nothing to do
            return;
        }
        this._tokens.acceptInsertText(lineIndex, position.column - 1, eolCount, firstLineLength, lastLineLength, firstCharCode);
    }
}
class SparseMultilineTokensStorage {
    constructor(tokens) {
        this._tokens = tokens;
        this._tokenCount = tokens.length / 4;
    }
    toString(startLineNumber) {
        const pieces = [];
        for (let i = 0; i < this._tokenCount; i++) {
            pieces.push(`(${this._getDeltaLine(i) + startLineNumber},${this._getStartCharacter(i)}-${this._getEndCharacter(i)})`);
        }
        return `[${pieces.join(',')}]`;
    }
    getMaxDeltaLine() {
        const tokenCount = this._getTokenCount();
        if (tokenCount === 0) {
            return -1;
        }
        return this._getDeltaLine(tokenCount - 1);
    }
    getRange() {
        const tokenCount = this._getTokenCount();
        if (tokenCount === 0) {
            return null;
        }
        const startChar = this._getStartCharacter(0);
        const maxDeltaLine = this._getDeltaLine(tokenCount - 1);
        const endChar = this._getEndCharacter(tokenCount - 1);
        return new Range(0, startChar + 1, maxDeltaLine, endChar + 1);
    }
    _getTokenCount() {
        return this._tokenCount;
    }
    _getDeltaLine(tokenIndex) {
        return this._tokens[4 * tokenIndex];
    }
    _getStartCharacter(tokenIndex) {
        return this._tokens[4 * tokenIndex + 1];
    }
    _getEndCharacter(tokenIndex) {
        return this._tokens[4 * tokenIndex + 2];
    }
    isEmpty() {
        return (this._getTokenCount() === 0);
    }
    getLineTokens(deltaLine) {
        let low = 0;
        let high = this._getTokenCount() - 1;
        while (low < high) {
            const mid = low + Math.floor((high - low) / 2);
            const midDeltaLine = this._getDeltaLine(mid);
            if (midDeltaLine < deltaLine) {
                low = mid + 1;
            }
            else if (midDeltaLine > deltaLine) {
                high = mid - 1;
            }
            else {
                let min = mid;
                while (min > low && this._getDeltaLine(min - 1) === deltaLine) {
                    min--;
                }
                let max = mid;
                while (max < high && this._getDeltaLine(max + 1) === deltaLine) {
                    max++;
                }
                return new SparseLineTokens(this._tokens.subarray(4 * min, 4 * max + 4));
            }
        }
        if (this._getDeltaLine(low) === deltaLine) {
            return new SparseLineTokens(this._tokens.subarray(4 * low, 4 * low + 4));
        }
        return null;
    }
    clear() {
        this._tokenCount = 0;
    }
    removeTokens(startDeltaLine, startChar, endDeltaLine, endChar) {
        const tokens = this._tokens;
        const tokenCount = this._tokenCount;
        let newTokenCount = 0;
        let hasDeletedTokens = false;
        let firstDeltaLine = 0;
        for (let i = 0; i < tokenCount; i++) {
            const srcOffset = 4 * i;
            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) {
                    // must move the token to the left
                    const destOffset = 4 * newTokenCount;
                    tokens[destOffset] = tokenDeltaLine - firstDeltaLine;
                    tokens[destOffset + 1] = tokenStartCharacter;
                    tokens[destOffset + 2] = tokenEndCharacter;
                    tokens[destOffset + 3] = tokenMetadata;
                }
                newTokenCount++;
            }
        }
        this._tokenCount = newTokenCount;
        return firstDeltaLine;
    }
    split(startDeltaLine, startChar, endDeltaLine, endChar) {
        const tokens = this._tokens;
        const tokenCount = this._tokenCount;
        const aTokens = [];
        const bTokens = [];
        let destTokens = aTokens;
        let destOffset = 0;
        let destFirstDeltaLine = 0;
        for (let i = 0; i < tokenCount; i++) {
            const srcOffset = 4 * i;
            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))) {
                    // this token is touching the range
                    continue;
                }
                else {
                    // this token is after the range
                    if (destTokens !== bTokens) {
                        // this token is the first token after the range
                        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) {
        // This is a bit complex, here are the cases I used to think about this:
        //
        // 1. The token starts before the deletion range
        // 1a. The token is completely before the deletion range
        //               -----------
        //                          xxxxxxxxxxx
        // 1b. The token starts before, the deletion range ends after the token
        //               -----------
        //                      xxxxxxxxxxx
        // 1c. The token starts before, the deletion range ends precisely with the token
        //               ---------------
        //                      xxxxxxxx
        // 1d. The token starts before, the deletion range is inside the token
        //               ---------------
        //                    xxxxx
        //
        // 2. The token starts at the same position with the deletion range
        // 2a. The token starts at the same position, and ends inside the deletion range
        //               -------
        //               xxxxxxxxxxx
        // 2b. The token starts at the same position, and ends at the same position as the deletion range
        //               ----------
        //               xxxxxxxxxx
        // 2c. The token starts at the same position, and ends after the deletion range
        //               -------------
        //               xxxxxxx
        //
        // 3. The token starts inside the deletion range
        // 3a. The token is inside the deletion range
        //                -------
        //             xxxxxxxxxxxxx
        // 3b. The token starts inside the deletion range, and ends at the same position as the deletion range
        //                ----------
        //             xxxxxxxxxxxxx
        // 3c. The token starts inside the deletion range, and ends after the deletion range
        //                ------------
        //             xxxxxxxxxxx
        //
        // 4. The token starts after the deletion range
        //                  -----------
        //          xxxxxxxx
        //
        const tokens = this._tokens;
        const tokenCount = this._tokenCount;
        const deletedLineCount = (endDeltaLine - startDeltaLine);
        let newTokenCount = 0;
        let hasDeletedTokens = false;
        for (let i = 0; i < tokenCount; i++) {
            const srcOffset = 4 * i;
            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)) {
                // 1a. The token is completely before the deletion range
                // => nothing to do
                newTokenCount++;
                continue;
            }
            else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter < startCharacter) {
                // 1b, 1c, 1d
                // => the token survives, but it needs to shrink
                if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
                    // 1d. The token starts before, the deletion range is inside the token
                    // => the token shrinks by the deletion character count
                    tokenEndCharacter -= (endCharacter - startCharacter);
                }
                else {
                    // 1b. The token starts before, the deletion range ends after the token
                    // 1c. The token starts before, the deletion range ends precisely with the token
                    // => the token shrinks its ending to the deletion start
                    tokenEndCharacter = startCharacter;
                }
            }
            else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter === startCharacter) {
                // 2a, 2b, 2c
                if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
                    // 2c. The token starts at the same position, and ends after the deletion range
                    // => the token shrinks by the deletion character count
                    tokenEndCharacter -= (endCharacter - startCharacter);
                }
                else {
                    // 2a. The token starts at the same position, and ends inside the deletion range
                    // 2b. The token starts at the same position, and ends at the same position as the deletion range
                    // => the token is deleted
                    hasDeletedTokens = true;
                    continue;
                }
            }
            else if (tokenDeltaLine < endDeltaLine || (tokenDeltaLine === endDeltaLine && tokenStartCharacter < endCharacter)) {
                // 3a, 3b, 3c
                if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
                    // 3c. The token starts inside the deletion range, and ends after the deletion range
                    // => the token moves left and shrinks
                    if (tokenDeltaLine === startDeltaLine) {
                        // the deletion started on the same line as the token
                        // => the token moves left and shrinks
                        tokenStartCharacter = startCharacter;
                        tokenEndCharacter = tokenStartCharacter + (tokenEndCharacter - endCharacter);
                    }
                    else {
                        // the deletion started on a line above the token
                        // => the token moves to the beginning of the line
                        tokenStartCharacter = 0;
                        tokenEndCharacter = tokenStartCharacter + (tokenEndCharacter - endCharacter);
                    }
                }
                else {
                    // 3a. The token is inside the deletion range
                    // 3b. The token starts inside the deletion range, and ends at the same position as the deletion range
                    // => the token is deleted
                    hasDeletedTokens = true;
                    continue;
                }
            }
            else if (tokenDeltaLine > endDeltaLine) {
                // 4. (partial) The token starts after the deletion range, on a line below...
                if (deletedLineCount === 0 && !hasDeletedTokens) {
                    // early stop, there is no need to walk all the tokens and do nothing...
                    newTokenCount = tokenCount;
                    break;
                }
                tokenDeltaLine -= deletedLineCount;
            }
            else if (tokenDeltaLine === endDeltaLine && tokenStartCharacter >= endCharacter) {
                // 4. (continued) The token starts after the deletion range, on the last line where a deletion occurs
                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._tokenCount = newTokenCount;
    }
    acceptInsertText(deltaLine, character, eolCount, firstLineLength, lastLineLength, firstCharCode) {
        // Here are the cases I used to think about this:
        //
        // 1. The token is completely before the insertion point
        //            -----------   |
        // 2. The token ends precisely at the insertion point
        //            -----------|
        // 3. The token contains the insertion point
        //            -----|------
        // 4. The token starts precisely at the insertion point
        //            |-----------
        // 5. The token is completely after the insertion point
        //            |   -----------
        //
        const isInsertingPreciselyOneWordCharacter = (eolCount === 0
            && firstLineLength === 1
            && ((firstCharCode >= 48 /* CharCode.Digit0 */ && firstCharCode <= 57 /* CharCode.Digit9 */)
                || (firstCharCode >= 65 /* CharCode.A */ && firstCharCode <= 90 /* CharCode.Z */)
                || (firstCharCode >= 97 /* CharCode.a */ && firstCharCode <= 122 /* CharCode.z */)));
        const tokens = this._tokens;
        const tokenCount = this._tokenCount;
        for (let i = 0; i < tokenCount; i++) {
            const offset = 4 * i;
            let tokenDeltaLine = tokens[offset];
            let tokenStartCharacter = tokens[offset + 1];
            let tokenEndCharacter = tokens[offset + 2];
            if (tokenDeltaLine < deltaLine || (tokenDeltaLine === deltaLine && tokenEndCharacter < character)) {
                // 1. The token is completely before the insertion point
                // => nothing to do
                continue;
            }
            else if (tokenDeltaLine === deltaLine && tokenEndCharacter === character) {
                // 2. The token ends precisely at the insertion point
                // => expand the end character only if inserting precisely one character that is a word character
                if (isInsertingPreciselyOneWordCharacter) {
                    tokenEndCharacter += 1;
                }
                else {
                    continue;
                }
            }
            else if (tokenDeltaLine === deltaLine && tokenStartCharacter < character && character < tokenEndCharacter) {
                // 3. The token contains the insertion point
                if (eolCount === 0) {
                    // => just expand the end character
                    tokenEndCharacter += firstLineLength;
                }
                else {
                    // => cut off the token
                    tokenEndCharacter = character;
                }
            }
            else {
                // 4. or 5.
                if (tokenDeltaLine === deltaLine && tokenStartCharacter === character) {
                    // 4. The token starts precisely at the insertion point
                    // => grow the token (by keeping its start constant) only if inserting precisely one character that is a word character
                    // => otherwise behave as in case 5.
                    if (isInsertingPreciselyOneWordCharacter) {
                        continue;
                    }
                }
                // => the token must move and keep its size constant
                if (tokenDeltaLine === deltaLine) {
                    tokenDeltaLine += eolCount;
                    // this token is on the line where the insertion is taking place
                    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;
        }
    }
}
class SparseLineTokens {
    constructor(tokens) {
        this._tokens = tokens;
    }
    getCount() {
        return this._tokens.length / 4;
    }
    getStartCharacter(tokenIndex) {
        return this._tokens[4 * tokenIndex + 1];
    }
    getEndCharacter(tokenIndex) {
        return this._tokens[4 * tokenIndex + 2];
    }
    getMetadata(tokenIndex) {
        return this._tokens[4 * tokenIndex + 3];
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/semanticTokensProviderStyling.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var semanticTokensProviderStyling_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var semanticTokensProviderStyling_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};





let SemanticTokensProviderStyling = class SemanticTokensProviderStyling {
    constructor(_legend, _themeService, _languageService, _logService) {
        this._legend = _legend;
        this._themeService = _themeService;
        this._languageService = _languageService;
        this._logService = _logService;
        this._hasWarnedOverlappingTokens = false;
        this._hasWarnedInvalidLengthTokens = false;
        this._hasWarnedInvalidEditStart = false;
        this._hashTable = new HashTable();
    }
    getMetadata(tokenTypeIndex, tokenModifierSet, languageId) {
        const encodedLanguageId = this._languageService.languageIdCodec.encodeLanguageId(languageId);
        const entry = this._hashTable.get(tokenTypeIndex, tokenModifierSet, encodedLanguageId);
        let metadata;
        if (entry) {
            metadata = entry.metadata;
            if (this._logService.getLevel() === LogLevel.Trace) {
                this._logService.trace(`SemanticTokensProviderStyling [CACHED] ${tokenTypeIndex} / ${tokenModifierSet}: foreground ${TokenMetadata.getForeground(metadata)}, fontStyle ${TokenMetadata.getFontStyle(metadata).toString(2)}`);
            }
        }
        else {
            let tokenType = this._legend.tokenTypes[tokenTypeIndex];
            const tokenModifiers = [];
            if (tokenType) {
                let modifierSet = tokenModifierSet;
                for (let modifierIndex = 0; modifierSet > 0 && modifierIndex < this._legend.tokenModifiers.length; modifierIndex++) {
                    if (modifierSet & 1) {
                        tokenModifiers.push(this._legend.tokenModifiers[modifierIndex]);
                    }
                    modifierSet = modifierSet >> 1;
                }
                if (modifierSet > 0 && this._logService.getLevel() === LogLevel.Trace) {
                    this._logService.trace(`SemanticTokensProviderStyling: unknown token modifier index: ${tokenModifierSet.toString(2)} for legend: ${JSON.stringify(this._legend.tokenModifiers)}`);
                    tokenModifiers.push('not-in-legend');
                }
                const tokenStyle = this._themeService.getColorTheme().getTokenStyleMetadata(tokenType, tokenModifiers, languageId);
                if (typeof tokenStyle === 'undefined') {
                    metadata = 2147483647 /* SemanticTokensProviderStylingConstants.NO_STYLING */;
                }
                else {
                    metadata = 0;
                    if (typeof tokenStyle.italic !== 'undefined') {
                        const italicBit = (tokenStyle.italic ? 1 /* FontStyle.Italic */ : 0) << 11 /* MetadataConsts.FONT_STYLE_OFFSET */;
                        metadata |= italicBit | 1 /* MetadataConsts.SEMANTIC_USE_ITALIC */;
                    }
                    if (typeof tokenStyle.bold !== 'undefined') {
                        const boldBit = (tokenStyle.bold ? 2 /* FontStyle.Bold */ : 0) << 11 /* MetadataConsts.FONT_STYLE_OFFSET */;
                        metadata |= boldBit | 2 /* MetadataConsts.SEMANTIC_USE_BOLD */;
                    }
                    if (typeof tokenStyle.underline !== 'undefined') {
                        const underlineBit = (tokenStyle.underline ? 4 /* FontStyle.Underline */ : 0) << 11 /* MetadataConsts.FONT_STYLE_OFFSET */;
                        metadata |= underlineBit | 4 /* MetadataConsts.SEMANTIC_USE_UNDERLINE */;
                    }
                    if (typeof tokenStyle.strikethrough !== 'undefined') {
                        const strikethroughBit = (tokenStyle.strikethrough ? 8 /* FontStyle.Strikethrough */ : 0) << 11 /* MetadataConsts.FONT_STYLE_OFFSET */;
                        metadata |= strikethroughBit | 8 /* MetadataConsts.SEMANTIC_USE_STRIKETHROUGH */;
                    }
                    if (tokenStyle.foreground) {
                        const foregroundBits = (tokenStyle.foreground) << 15 /* MetadataConsts.FOREGROUND_OFFSET */;
                        metadata |= foregroundBits | 16 /* MetadataConsts.SEMANTIC_USE_FOREGROUND */;
                    }
                    if (metadata === 0) {
                        // Nothing!
                        metadata = 2147483647 /* SemanticTokensProviderStylingConstants.NO_STYLING */;
                    }
                }
            }
            else {
                if (this._logService.getLevel() === LogLevel.Trace) {
                    this._logService.trace(`SemanticTokensProviderStyling: unknown token type index: ${tokenTypeIndex} for legend: ${JSON.stringify(this._legend.tokenTypes)}`);
                }
                metadata = 2147483647 /* SemanticTokensProviderStylingConstants.NO_STYLING */;
                tokenType = 'not-in-legend';
            }
            this._hashTable.add(tokenTypeIndex, tokenModifierSet, encodedLanguageId, metadata);
            if (this._logService.getLevel() === LogLevel.Trace) {
                this._logService.trace(`SemanticTokensProviderStyling ${tokenTypeIndex} (${tokenType}) / ${tokenModifierSet} (${tokenModifiers.join(' ')}): foreground ${TokenMetadata.getForeground(metadata)}, fontStyle ${TokenMetadata.getFontStyle(metadata).toString(2)}`);
            }
        }
        return metadata;
    }
    warnOverlappingSemanticTokens(lineNumber, startColumn) {
        if (!this._hasWarnedOverlappingTokens) {
            this._hasWarnedOverlappingTokens = true;
            console.warn(`Overlapping semantic tokens detected at lineNumber ${lineNumber}, column ${startColumn}`);
        }
    }
    warnInvalidLengthSemanticTokens(lineNumber, startColumn) {
        if (!this._hasWarnedInvalidLengthTokens) {
            this._hasWarnedInvalidLengthTokens = true;
            console.warn(`Semantic token with invalid length detected at lineNumber ${lineNumber}, column ${startColumn}`);
        }
    }
    warnInvalidEditStart(previousResultId, resultId, editIndex, editStart, maxExpectedStart) {
        if (!this._hasWarnedInvalidEditStart) {
            this._hasWarnedInvalidEditStart = true;
            console.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}).`);
        }
    }
};
SemanticTokensProviderStyling = semanticTokensProviderStyling_decorate([
    semanticTokensProviderStyling_param(1, IThemeService),
    semanticTokensProviderStyling_param(2, ILanguageService),
    semanticTokensProviderStyling_param(3, ILogService)
], SemanticTokensProviderStyling);

function toMultilineTokens2(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);
        // Keep tokens on the same line in the same area...
        if (tokenEndIndex < tokenCount) {
            let smallTokenEndIndex = tokenEndIndex;
            while (smallTokenEndIndex - 1 > tokenStartIndex && srcData[5 * smallTokenEndIndex] === 0) {
                smallTokenEndIndex--;
            }
            if (smallTokenEndIndex - 1 === tokenStartIndex) {
                // there are so many tokens on this line that our area would be empty, we must now go right
                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];
            // Casting both `lineNumber`, `startCharacter` and `endCharacter` here to uint32 using `|0`
            // to validate below with the actual values that will be inserted in the Uint32Array result
            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) {
                // this token is invalid (most likely a negative length casted to uint32)
                styling.warnInvalidLengthSemanticTokens(lineNumber, startCharacter + 1);
            }
            else if (prevLineNumber === lineNumber && prevEndCharacter > startCharacter) {
                // this token overlaps with the previous token
                styling.warnOverlappingSemanticTokens(lineNumber, startCharacter + 1);
            }
            else {
                const metadata = styling.getMetadata(tokenTypeIndex, tokenModifierSet, languageId);
                if (metadata !== 2147483647 /* SemanticTokensProviderStylingConstants.NO_STYLING */) {
                    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 tokens = SparseMultilineTokens.create(areaLine, destData);
        result.push(tokens);
    }
    return result;
}
class HashTableEntry {
    constructor(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
        this.tokenTypeIndex = tokenTypeIndex;
        this.tokenModifierSet = tokenModifierSet;
        this.languageId = languageId;
        this.metadata = metadata;
        this.next = null;
    }
}
class HashTable {
    constructor() {
        this._elementsCount = 0;
        this._currentLengthIndex = 0;
        this._currentLength = HashTable._SIZES[this._currentLengthIndex];
        this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
        this._elements = [];
        HashTable._nullOutEntries(this._elements, this._currentLength);
    }
    static _nullOutEntries(entries, length) {
        for (let i = 0; i < length; i++) {
            entries[i] = null;
        }
    }
    _hash2(n1, n2) {
        return (((n1 << 5) - n1) + n2) | 0; // n1 * 31 + n2, keep as int32
    }
    _hashFunc(tokenTypeIndex, tokenModifierSet, languageId) {
        return this._hash2(this._hash2(tokenTypeIndex, tokenModifierSet), languageId) % this._currentLength;
    }
    get(tokenTypeIndex, tokenModifierSet, languageId) {
        const hash = this._hashFunc(tokenTypeIndex, tokenModifierSet, languageId);
        let p = this._elements[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._elementsCount++;
        if (this._growCount !== 0 && this._elementsCount >= this._growCount) {
            // expand!
            const oldElements = this._elements;
            this._currentLengthIndex++;
            this._currentLength = HashTable._SIZES[this._currentLengthIndex];
            this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
            this._elements = [];
            HashTable._nullOutEntries(this._elements, this._currentLength);
            for (const first of oldElements) {
                let p = first;
                while (p) {
                    const oldNext = p.next;
                    p.next = null;
                    this._add(p);
                    p = oldNext;
                }
            }
        }
        this._add(new HashTableEntry(tokenTypeIndex, tokenModifierSet, languageId, metadata));
    }
    _add(element) {
        const hash = this._hashFunc(element.tokenTypeIndex, element.tokenModifierSet, element.languageId);
        element.next = this._elements[hash];
        this._elements[hash] = element;
    }
}
HashTable._SIZES = [3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143];

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/modelService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var modelService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var modelService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};


























function modelService_MODEL_ID(resource) {
    return resource.toString();
}
function computeModelSha1(model) {
    // compute the sha1
    const shaComputer = new StringSHA1();
    const snapshot = model.createSnapshot();
    let text;
    while ((text = snapshot.read())) {
        shaComputer.update(text);
    }
    return shaComputer.digest();
}
class modelService_ModelData {
    constructor(model, onWillDispose, onDidChangeLanguage) {
        this._modelEventListeners = new DisposableStore();
        this.model = model;
        this._languageSelection = null;
        this._languageSelectionListener = null;
        this._modelEventListeners.add(model.onWillDispose(() => onWillDispose(model)));
        this._modelEventListeners.add(model.onDidChangeLanguage((e) => onDidChangeLanguage(model, e)));
    }
    _disposeLanguageSelection() {
        if (this._languageSelectionListener) {
            this._languageSelectionListener.dispose();
            this._languageSelectionListener = null;
        }
    }
    dispose() {
        this._modelEventListeners.dispose();
        this._disposeLanguageSelection();
    }
    setLanguage(languageSelection) {
        this._disposeLanguageSelection();
        this._languageSelection = languageSelection;
        this._languageSelectionListener = this._languageSelection.onDidChange(() => this.model.setMode(languageSelection.languageId));
        this.model.setMode(languageSelection.languageId);
    }
}
const DEFAULT_EOL = (isLinux || isMacintosh) ? 1 /* DefaultEndOfLine.LF */ : 2 /* DefaultEndOfLine.CRLF */;
class DisposedModelInfo {
    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;
    }
}
let ModelService = class ModelService extends Disposable {
    constructor(_configurationService, _resourcePropertiesService, _themeService, _logService, _undoRedoService, _languageService, _languageConfigurationService, _languageFeatureDebounceService, languageFeaturesService) {
        super();
        this._configurationService = _configurationService;
        this._resourcePropertiesService = _resourcePropertiesService;
        this._themeService = _themeService;
        this._logService = _logService;
        this._undoRedoService = _undoRedoService;
        this._languageService = _languageService;
        this._languageConfigurationService = _languageConfigurationService;
        this._languageFeatureDebounceService = _languageFeatureDebounceService;
        this._onModelAdded = this._register(new Emitter());
        this.onModelAdded = this._onModelAdded.event;
        this._onModelRemoved = this._register(new Emitter());
        this.onModelRemoved = this._onModelRemoved.event;
        this._onModelModeChanged = this._register(new Emitter());
        this.onModelLanguageChanged = this._onModelModeChanged.event;
        this._modelCreationOptionsByLanguageAndResource = Object.create(null);
        this._models = {};
        this._disposedModels = new Map();
        this._disposedModelsHeapSize = 0;
        this._semanticStyling = this._register(new SemanticStyling(this._themeService, this._languageService, this._logService));
        this._register(this._configurationService.onDidChangeConfiguration(() => this._updateModelOptions()));
        this._updateModelOptions();
        this._register(new SemanticColoringFeature(this._semanticStyling, this, this._themeService, this._configurationService, this._languageFeatureDebounceService, languageFeaturesService));
    }
    static _readModelOptions(config, isForSimpleWidget) {
        var _a;
        let tabSize = EDITOR_MODEL_DEFAULTS.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 = parsedIndentSize;
            }
            if (indentSize < 1) {
                indentSize = 1;
            }
        }
        let insertSpaces = EDITOR_MODEL_DEFAULTS.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 /* DefaultEndOfLine.CRLF */;
        }
        else if (eol === '\n') {
            newDefaultEOL = 1 /* DefaultEndOfLine.LF */;
        }
        let trimAutoWhitespace = EDITOR_MODEL_DEFAULTS.trimAutoWhitespace;
        if (config.editor && typeof config.editor.trimAutoWhitespace !== 'undefined') {
            trimAutoWhitespace = (config.editor.trimAutoWhitespace === 'false' ? false : Boolean(config.editor.trimAutoWhitespace));
        }
        let detectIndentation = EDITOR_MODEL_DEFAULTS.detectIndentation;
        if (config.editor && typeof config.editor.detectIndentation !== 'undefined') {
            detectIndentation = (config.editor.detectIndentation === 'false' ? false : Boolean(config.editor.detectIndentation));
        }
        let largeFileOptimizations = EDITOR_MODEL_DEFAULTS.largeFileOptimizations;
        if (config.editor && typeof config.editor.largeFileOptimizations !== 'undefined') {
            largeFileOptimizations = (config.editor.largeFileOptimizations === 'false' ? false : Boolean(config.editor.largeFileOptimizations));
        }
        let bracketPairColorizationOptions = EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions;
        if (((_a = config.editor) === null || _a === void 0 ? void 0 : _a.bracketPairColorization) && typeof config.editor.bracketPairColorization === 'object') {
            bracketPairColorizationOptions = {
                enabled: !!config.editor.bracketPairColorization.enabled,
                independentColorPoolPerBracketType: !!config.editor.bracketPairColorization.independentColorPoolPerBracketType
            };
        }
        return {
            isForSimpleWidget: isForSimpleWidget,
            tabSize: tabSize,
            indentSize: indentSize,
            insertSpaces: insertSpaces,
            detectIndentation: detectIndentation,
            defaultEOL: newDefaultEOL,
            trimAutoWhitespace: trimAutoWhitespace,
            largeFileOptimizations: largeFileOptimizations,
            bracketPairColorizationOptions
        };
    }
    _getEOL(resource, language) {
        if (resource) {
            return this._resourcePropertiesService.getEOL(resource, language);
        }
        const eol = this._configurationService.getValue('files.eol', { overrideIdentifier: language });
        if (eol && typeof eol === 'string' && eol !== 'auto') {
            return eol;
        }
        return OS === 3 /* platform.OperatingSystem.Linux */ || OS === 2 /* platform.OperatingSystem.Macintosh */ ? '\n' : '\r\n';
    }
    _shouldRestoreUndoStack() {
        const result = this._configurationService.getValue('files.restoreUndoStack');
        if (typeof result === 'boolean') {
            return result;
        }
        return true;
    }
    getCreationOptions(language, resource, isForSimpleWidget) {
        let creationOptions = this._modelCreationOptionsByLanguageAndResource[language + resource];
        if (!creationOptions) {
            const editor = this._configurationService.getValue('editor', { overrideIdentifier: language, resource });
            const eol = this._getEOL(resource, language);
            creationOptions = ModelService._readModelOptions({ editor, eol }, isForSimpleWidget);
            this._modelCreationOptionsByLanguageAndResource[language + resource] = creationOptions;
        }
        return creationOptions;
    }
    _updateModelOptions() {
        const oldOptionsByLanguageAndResource = this._modelCreationOptionsByLanguageAndResource;
        this._modelCreationOptionsByLanguageAndResource = Object.create(null);
        // Update options on all models
        const keys = Object.keys(this._models);
        for (let i = 0, len = keys.length; i < len; i++) {
            const modelId = keys[i];
            const modelData = this._models[modelId];
            const language = modelData.model.getLanguageId();
            const uri = modelData.model.uri;
            const oldOptions = oldOptionsByLanguageAndResource[language + uri];
            const newOptions = this.getCreationOptions(language, uri, modelData.model.isForSimpleWidget);
            ModelService._setModelOptionsForModel(modelData.model, newOptions, oldOptions);
        }
    }
    static _setModelOptionsForModel(model, newOptions, currentOptions) {
        if (currentOptions && currentOptions.defaultEOL !== newOptions.defaultEOL && model.getLineCount() === 1) {
            model.setEOL(newOptions.defaultEOL === 1 /* DefaultEndOfLine.LF */ ? 0 /* EndOfLineSequence.LF */ : 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)
            && objects_equals(currentOptions.bracketPairColorizationOptions, newOptions.bracketPairColorizationOptions)) {
            // Same indent opts, no need to touch the model
            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
    _insertDisposedModel(disposedModelData) {
        this._disposedModels.set(modelService_MODEL_ID(disposedModelData.uri), disposedModelData);
        this._disposedModelsHeapSize += disposedModelData.heapSize;
    }
    _removeDisposedModel(resource) {
        const disposedModelData = this._disposedModels.get(modelService_MODEL_ID(resource));
        if (disposedModelData) {
            this._disposedModelsHeapSize -= disposedModelData.heapSize;
        }
        this._disposedModels.delete(modelService_MODEL_ID(resource));
        return disposedModelData;
    }
    _ensureDisposedModelsHeapSize(maxModelsHeapSize) {
        if (this._disposedModelsHeapSize > maxModelsHeapSize) {
            // we must remove some old undo stack elements to free up some memory
            const disposedModels = [];
            this._disposedModels.forEach(entry => {
                if (!entry.sharesUndoRedoStack) {
                    disposedModels.push(entry);
                }
            });
            disposedModels.sort((a, b) => a.time - b.time);
            while (disposedModels.length > 0 && this._disposedModelsHeapSize > maxModelsHeapSize) {
                const disposedModel = disposedModels.shift();
                this._removeDisposedModel(disposedModel.uri);
                if (disposedModel.initialUndoRedoSnapshot !== null) {
                    this._undoRedoService.restoreSnapshot(disposedModel.initialUndoRedoSnapshot);
                }
            }
        }
    }
    _createModelData(value, languageId, resource, isForSimpleWidget) {
        // create & save the model
        const options = this.getCreationOptions(languageId, resource, isForSimpleWidget);
        const model = new TextModel(value, languageId, options, resource, this._undoRedoService, this._languageService, this._languageConfigurationService);
        if (resource && this._disposedModels.has(modelService_MODEL_ID(resource))) {
            const disposedModelData = this._removeDisposedModel(resource);
            const elements = this._undoRedoService.getElements(resource);
            const sha1IsEqual = (computeModelSha1(model) === disposedModelData.sha1);
            if (sha1IsEqual || disposedModelData.sharesUndoRedoStack) {
                for (const element of elements.past) {
                    if (isEditStackElement(element) && element.matchesResource(resource)) {
                        element.setModel(model);
                    }
                }
                for (const element of elements.future) {
                    if (isEditStackElement(element) && element.matchesResource(resource)) {
                        element.setModel(model);
                    }
                }
                this._undoRedoService.setElementsValidFlag(resource, true, (element) => (isEditStackElement(element) && element.matchesResource(resource)));
                if (sha1IsEqual) {
                    model._overwriteVersionId(disposedModelData.versionId);
                    model._overwriteAlternativeVersionId(disposedModelData.alternativeVersionId);
                    model._overwriteInitialUndoRedoSnapshot(disposedModelData.initialUndoRedoSnapshot);
                }
            }
            else {
                if (disposedModelData.initialUndoRedoSnapshot !== null) {
                    this._undoRedoService.restoreSnapshot(disposedModelData.initialUndoRedoSnapshot);
                }
            }
        }
        const modelId = modelService_MODEL_ID(model.uri);
        if (this._models[modelId]) {
            // There already exists a model with this id => this is a programmer error
            throw new Error('ModelService: Cannot add model because it already exists!');
        }
        const modelData = new modelService_ModelData(model, (model) => this._onWillDispose(model), (model, e) => this._onDidChangeLanguage(model, e));
        this._models[modelId] = modelData;
        return modelData;
    }
    createModel(value, languageSelection, resource, isForSimpleWidget = false) {
        let modelData;
        if (languageSelection) {
            modelData = this._createModelData(value, languageSelection.languageId, resource, isForSimpleWidget);
            this.setMode(modelData.model, languageSelection);
        }
        else {
            modelData = this._createModelData(value, PLAINTEXT_LANGUAGE_ID, resource, isForSimpleWidget);
        }
        this._onModelAdded.fire(modelData.model);
        return modelData.model;
    }
    setMode(model, languageSelection) {
        if (!languageSelection) {
            return;
        }
        const modelData = this._models[modelService_MODEL_ID(model.uri)];
        if (!modelData) {
            return;
        }
        modelData.setLanguage(languageSelection);
    }
    getModels() {
        const ret = [];
        const keys = Object.keys(this._models);
        for (let i = 0, len = keys.length; i < len; i++) {
            const modelId = keys[i];
            ret.push(this._models[modelId].model);
        }
        return ret;
    }
    getModel(resource) {
        const modelId = modelService_MODEL_ID(resource);
        const modelData = this._models[modelId];
        if (!modelData) {
            return null;
        }
        return modelData.model;
    }
    getSemanticTokensProviderStyling(provider) {
        return this._semanticStyling.get(provider);
    }
    // --- end IModelService
    _schemaShouldMaintainUndoRedoElements(resource) {
        return (resource.scheme === Schemas.file
            || resource.scheme === Schemas.vscodeRemote
            || resource.scheme === Schemas.vscodeUserData
            || resource.scheme === Schemas.vscodeNotebookCell
            || resource.scheme === 'fake-fs' // for tests
        );
    }
    _onWillDispose(model) {
        const modelId = modelService_MODEL_ID(model.uri);
        const modelData = this._models[modelId];
        const sharesUndoRedoStack = (this._undoRedoService.getUriComparisonKey(model.uri) !== model.uri.toString());
        let maintainUndoRedoStack = false;
        let heapSize = 0;
        if (sharesUndoRedoStack || (this._shouldRestoreUndoStack() && this._schemaShouldMaintainUndoRedoElements(model.uri))) {
            const elements = this._undoRedoService.getElements(model.uri);
            if (elements.past.length > 0 || elements.future.length > 0) {
                for (const element of elements.past) {
                    if (isEditStackElement(element) && element.matchesResource(model.uri)) {
                        maintainUndoRedoStack = true;
                        heapSize += element.heapSize(model.uri);
                        element.setModel(model.uri); // remove reference from text buffer instance
                    }
                }
                for (const element of elements.future) {
                    if (isEditStackElement(element) && element.matchesResource(model.uri)) {
                        maintainUndoRedoStack = true;
                        heapSize += element.heapSize(model.uri);
                        element.setModel(model.uri); // remove reference from text buffer instance
                    }
                }
            }
        }
        const maxMemory = ModelService.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK;
        if (!maintainUndoRedoStack) {
            if (!sharesUndoRedoStack) {
                const initialUndoRedoSnapshot = modelData.model.getInitialUndoRedoSnapshot();
                if (initialUndoRedoSnapshot !== null) {
                    this._undoRedoService.restoreSnapshot(initialUndoRedoSnapshot);
                }
            }
        }
        else if (!sharesUndoRedoStack && heapSize > maxMemory) {
            // the undo stack for this file would never fit in the configured memory, so don't bother with it.
            const initialUndoRedoSnapshot = modelData.model.getInitialUndoRedoSnapshot();
            if (initialUndoRedoSnapshot !== null) {
                this._undoRedoService.restoreSnapshot(initialUndoRedoSnapshot);
            }
        }
        else {
            this._ensureDisposedModelsHeapSize(maxMemory - heapSize);
            // We only invalidate the elements, but they remain in the undo-redo service.
            this._undoRedoService.setElementsValidFlag(model.uri, false, (element) => (isEditStackElement(element) && element.matchesResource(model.uri)));
            this._insertDisposedModel(new DisposedModelInfo(model.uri, modelData.model.getInitialUndoRedoSnapshot(), Date.now(), sharesUndoRedoStack, heapSize, computeModelSha1(model), model.getVersionId(), model.getAlternativeVersionId()));
        }
        delete this._models[modelId];
        modelData.dispose();
        // clean up cache
        delete this._modelCreationOptionsByLanguageAndResource[model.getLanguageId() + model.uri];
        this._onModelRemoved.fire(model);
    }
    _onDidChangeLanguage(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);
        ModelService._setModelOptionsForModel(model, newOptions, oldOptions);
        this._onModelModeChanged.fire({ model, oldLanguageId: oldLanguageId });
    }
};
ModelService.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK = 20 * 1024 * 1024;
ModelService = modelService_decorate([
    modelService_param(0, IConfigurationService),
    modelService_param(1, ITextResourcePropertiesService),
    modelService_param(2, IThemeService),
    modelService_param(3, ILogService),
    modelService_param(4, IUndoRedoService),
    modelService_param(5, ILanguageService),
    modelService_param(6, ILanguageConfigurationService),
    modelService_param(7, ILanguageFeatureDebounceService),
    modelService_param(8, ILanguageFeaturesService)
], ModelService);

const SEMANTIC_HIGHLIGHTING_SETTING_ID = 'editor.semanticHighlighting';
function isSemanticColoringEnabled(model, themeService, configurationService) {
    var _a;
    const setting = (_a = configurationService.getValue(SEMANTIC_HIGHLIGHTING_SETTING_ID, { overrideIdentifier: model.getLanguageId(), resource: model.uri })) === null || _a === void 0 ? void 0 : _a.enabled;
    if (typeof setting === 'boolean') {
        return setting;
    }
    return themeService.getColorTheme().semanticHighlighting;
}
let SemanticColoringFeature = class SemanticColoringFeature extends Disposable {
    constructor(semanticStyling, modelService, themeService, configurationService, languageFeatureDebounceService, languageFeaturesService) {
        super();
        this._watchers = Object.create(null);
        this._semanticStyling = semanticStyling;
        const register = (model) => {
            this._watchers[model.uri.toString()] = new ModelSemanticColoring(model, this._semanticStyling, themeService, languageFeatureDebounceService, languageFeaturesService);
        };
        const deregister = (model, modelSemanticColoring) => {
            modelSemanticColoring.dispose();
            delete this._watchers[model.uri.toString()];
        };
        const handleSettingOrThemeChange = () => {
            for (const model of modelService.getModels()) {
                const curr = this._watchers[model.uri.toString()];
                if (isSemanticColoringEnabled(model, themeService, configurationService)) {
                    if (!curr) {
                        register(model);
                    }
                }
                else {
                    if (curr) {
                        deregister(model, curr);
                    }
                }
            }
        };
        this._register(modelService.onModelAdded((model) => {
            if (isSemanticColoringEnabled(model, themeService, configurationService)) {
                register(model);
            }
        }));
        this._register(modelService.onModelRemoved((model) => {
            const curr = this._watchers[model.uri.toString()];
            if (curr) {
                deregister(model, curr);
            }
        }));
        this._register(configurationService.onDidChangeConfiguration(e => {
            if (e.affectsConfiguration(SEMANTIC_HIGHLIGHTING_SETTING_ID)) {
                handleSettingOrThemeChange();
            }
        }));
        this._register(themeService.onDidColorThemeChange(handleSettingOrThemeChange));
    }
    dispose() {
        // Dispose all watchers
        for (const watcher of Object.values(this._watchers)) {
            watcher.dispose();
        }
        super.dispose();
    }
};
SemanticColoringFeature = modelService_decorate([
    modelService_param(1, IModelService),
    modelService_param(2, IThemeService),
    modelService_param(3, IConfigurationService),
    modelService_param(4, ILanguageFeatureDebounceService),
    modelService_param(5, ILanguageFeaturesService)
], SemanticColoringFeature);
class SemanticStyling extends Disposable {
    constructor(_themeService, _languageService, _logService) {
        super();
        this._themeService = _themeService;
        this._languageService = _languageService;
        this._logService = _logService;
        this._caches = new WeakMap();
        this._register(this._themeService.onDidColorThemeChange(() => {
            this._caches = new WeakMap();
        }));
    }
    get(provider) {
        if (!this._caches.has(provider)) {
            this._caches.set(provider, new SemanticTokensProviderStyling(provider.getLegend(), this._themeService, this._languageService, this._logService));
        }
        return this._caches.get(provider);
    }
}
class SemanticTokensResponse {
    constructor(provider, resultId, data) {
        this.provider = provider;
        this.resultId = resultId;
        this.data = data;
    }
    dispose() {
        this.provider.releaseDocumentSemanticTokens(this.resultId);
    }
}
let ModelSemanticColoring = class ModelSemanticColoring extends Disposable {
    constructor(model, stylingProvider, themeService, languageFeatureDebounceService, languageFeaturesService) {
        super();
        this._isDisposed = false;
        this._model = model;
        this._semanticStyling = stylingProvider;
        this._provider = languageFeaturesService.documentSemanticTokensProvider;
        this._debounceInformation = languageFeatureDebounceService.for(this._provider, 'DocumentSemanticTokens', { min: ModelSemanticColoring.REQUEST_MIN_DELAY, max: ModelSemanticColoring.REQUEST_MAX_DELAY });
        this._fetchDocumentSemanticTokens = this._register(new RunOnceScheduler(() => this._fetchDocumentSemanticTokensNow(), ModelSemanticColoring.REQUEST_MIN_DELAY));
        this._currentDocumentResponse = null;
        this._currentDocumentRequestCancellationTokenSource = null;
        this._documentProvidersChangeListeners = [];
        this._register(this._model.onDidChangeContent(() => {
            if (!this._fetchDocumentSemanticTokens.isScheduled()) {
                this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
            }
        }));
        this._register(this._model.onDidChangeLanguage(() => {
            // clear any outstanding state
            if (this._currentDocumentResponse) {
                this._currentDocumentResponse.dispose();
                this._currentDocumentResponse = null;
            }
            if (this._currentDocumentRequestCancellationTokenSource) {
                this._currentDocumentRequestCancellationTokenSource.cancel();
                this._currentDocumentRequestCancellationTokenSource = null;
            }
            this._setDocumentSemanticTokens(null, null, null, []);
            this._fetchDocumentSemanticTokens.schedule(0);
        }));
        const bindDocumentChangeListeners = () => {
            dispose(this._documentProvidersChangeListeners);
            this._documentProvidersChangeListeners = [];
            for (const provider of this._provider.all(model)) {
                if (typeof provider.onDidChange === 'function') {
                    this._documentProvidersChangeListeners.push(provider.onDidChange(() => this._fetchDocumentSemanticTokens.schedule(0)));
                }
            }
        };
        bindDocumentChangeListeners();
        this._register(this._provider.onDidChange(() => {
            bindDocumentChangeListeners();
            this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
        }));
        this._register(themeService.onDidColorThemeChange(_ => {
            // clear out existing tokens
            this._setDocumentSemanticTokens(null, null, null, []);
            this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
        }));
        this._fetchDocumentSemanticTokens.schedule(0);
    }
    dispose() {
        if (this._currentDocumentResponse) {
            this._currentDocumentResponse.dispose();
            this._currentDocumentResponse = null;
        }
        if (this._currentDocumentRequestCancellationTokenSource) {
            this._currentDocumentRequestCancellationTokenSource.cancel();
            this._currentDocumentRequestCancellationTokenSource = null;
        }
        this._setDocumentSemanticTokens(null, null, null, []);
        this._isDisposed = true;
        super.dispose();
    }
    _fetchDocumentSemanticTokensNow() {
        if (this._currentDocumentRequestCancellationTokenSource) {
            // there is already a request running, let it finish...
            return;
        }
        if (!hasDocumentSemanticTokensProvider(this._provider, this._model)) {
            // there is no provider
            if (this._currentDocumentResponse) {
                // there are semantic tokens set
                this._model.tokenization.setSemanticTokens(null, false);
            }
            return;
        }
        const cancellationTokenSource = new CancellationTokenSource();
        const lastProvider = this._currentDocumentResponse ? this._currentDocumentResponse.provider : null;
        const lastResultId = this._currentDocumentResponse ? this._currentDocumentResponse.resultId || null : null;
        const request = getDocumentSemanticTokens(this._provider, this._model, lastProvider, lastResultId, cancellationTokenSource.token);
        this._currentDocumentRequestCancellationTokenSource = cancellationTokenSource;
        const pendingChanges = [];
        const contentChangeListener = this._model.onDidChangeContent((e) => {
            pendingChanges.push(e);
        });
        const sw = new StopWatch(false);
        request.then((res) => {
            this._debounceInformation.update(this._model, sw.elapsed());
            this._currentDocumentRequestCancellationTokenSource = null;
            contentChangeListener.dispose();
            if (!res) {
                this._setDocumentSemanticTokens(null, null, null, pendingChanges);
            }
            else {
                const { provider, tokens } = res;
                const styling = this._semanticStyling.get(provider);
                this._setDocumentSemanticTokens(provider, tokens || null, styling, pendingChanges);
            }
        }, (err) => {
            const isExpectedError = err && (isCancellationError(err) || (typeof err.message === 'string' && err.message.indexOf('busy') !== -1));
            if (!isExpectedError) {
                onUnexpectedError(err);
            }
            // Semantic tokens eats up all errors and considers errors to mean that the result is temporarily not available
            // The API does not have a special error kind to express this...
            this._currentDocumentRequestCancellationTokenSource = null;
            contentChangeListener.dispose();
            if (pendingChanges.length > 0) {
                // More changes occurred while the request was running
                if (!this._fetchDocumentSemanticTokens.isScheduled()) {
                    this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
                }
            }
        });
    }
    static _copy(src, srcOffset, dest, destOffset, length) {
        // protect against overflows
        length = Math.min(length, dest.length - destOffset, src.length - srcOffset);
        for (let i = 0; i < length; i++) {
            dest[destOffset + i] = src[srcOffset + i];
        }
    }
    _setDocumentSemanticTokens(provider, tokens, styling, pendingChanges) {
        const currentResponse = this._currentDocumentResponse;
        const rescheduleIfNeeded = () => {
            if (pendingChanges.length > 0 && !this._fetchDocumentSemanticTokens.isScheduled()) {
                this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
            }
        };
        if (this._currentDocumentResponse) {
            this._currentDocumentResponse.dispose();
            this._currentDocumentResponse = null;
        }
        if (this._isDisposed) {
            // disposed!
            if (provider && tokens) {
                provider.releaseDocumentSemanticTokens(tokens.resultId);
            }
            return;
        }
        if (!provider || !styling) {
            this._model.tokenization.setSemanticTokens(null, false);
            return;
        }
        if (!tokens) {
            this._model.tokenization.setSemanticTokens(null, true);
            rescheduleIfNeeded();
            return;
        }
        if (isSemanticTokensEdits(tokens)) {
            if (!currentResponse) {
                // not possible!
                this._model.tokenization.setSemanticTokens(null, true);
                return;
            }
            if (tokens.edits.length === 0) {
                // nothing to do!
                tokens = {
                    resultId: tokens.resultId,
                    data: currentResponse.data
                };
            }
            else {
                let deltaLength = 0;
                for (const edit of tokens.edits) {
                    deltaLength += (edit.data ? edit.data.length : 0) - edit.deleteCount;
                }
                const srcData = currentResponse.data;
                const destData = new Uint32Array(srcData.length + deltaLength);
                let srcLastStart = srcData.length;
                let destLastStart = destData.length;
                for (let i = tokens.edits.length - 1; i >= 0; i--) {
                    const edit = tokens.edits[i];
                    if (edit.start > srcData.length) {
                        styling.warnInvalidEditStart(currentResponse.resultId, tokens.resultId, i, edit.start, srcData.length);
                        // The edits are invalid and there's no way to recover
                        this._model.tokenization.setSemanticTokens(null, true);
                        return;
                    }
                    const copyCount = srcLastStart - (edit.start + edit.deleteCount);
                    if (copyCount > 0) {
                        ModelSemanticColoring._copy(srcData, srcLastStart - copyCount, destData, destLastStart - copyCount, copyCount);
                        destLastStart -= copyCount;
                    }
                    if (edit.data) {
                        ModelSemanticColoring._copy(edit.data, 0, destData, destLastStart - edit.data.length, edit.data.length);
                        destLastStart -= edit.data.length;
                    }
                    srcLastStart = edit.start;
                }
                if (srcLastStart > 0) {
                    ModelSemanticColoring._copy(srcData, 0, destData, 0, srcLastStart);
                }
                tokens = {
                    resultId: tokens.resultId,
                    data: destData
                };
            }
        }
        if (isSemanticTokens(tokens)) {
            this._currentDocumentResponse = new SemanticTokensResponse(provider, tokens.resultId, tokens.data);
            const result = toMultilineTokens2(tokens, styling, this._model.getLanguageId());
            // Adjust incoming semantic tokens
            if (pendingChanges.length > 0) {
                // More changes occurred while the request was running
                // We need to:
                // 1. Adjust incoming semantic tokens
                // 2. Request them again
                for (const change of pendingChanges) {
                    for (const area of result) {
                        for (const singleChange of change.changes) {
                            area.applyEdit(singleChange.range, singleChange.text);
                        }
                    }
                }
            }
            this._model.tokenization.setSemanticTokens(result, true);
        }
        else {
            this._model.tokenization.setSemanticTokens(null, true);
        }
        rescheduleIfNeeded();
    }
};
ModelSemanticColoring.REQUEST_MIN_DELAY = 300;
ModelSemanticColoring.REQUEST_MAX_DELAY = 2000;
ModelSemanticColoring = modelService_decorate([
    modelService_param(2, IThemeService),
    modelService_param(3, ILanguageFeatureDebounceService),
    modelService_param(4, ILanguageFeaturesService)
], ModelSemanticColoring);


;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/viewportSemanticTokens/browser/viewportSemanticTokens.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var viewportSemanticTokens_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var viewportSemanticTokens_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};












let ViewportSemanticTokensContribution = class ViewportSemanticTokensContribution extends Disposable {
    constructor(editor, _modelService, _themeService, _configurationService, languageFeatureDebounceService, languageFeaturesService) {
        super();
        this._modelService = _modelService;
        this._themeService = _themeService;
        this._configurationService = _configurationService;
        this._editor = editor;
        this._provider = languageFeaturesService.documentRangeSemanticTokensProvider;
        this._debounceInformation = languageFeatureDebounceService.for(this._provider, 'DocumentRangeSemanticTokens', { min: 100, max: 500 });
        this._tokenizeViewport = this._register(new RunOnceScheduler(() => this._tokenizeViewportNow(), 100));
        this._outstandingRequests = [];
        const scheduleTokenizeViewport = () => {
            if (this._editor.hasModel()) {
                this._tokenizeViewport.schedule(this._debounceInformation.get(this._editor.getModel()));
            }
        };
        this._register(this._editor.onDidScrollChange(() => {
            scheduleTokenizeViewport();
        }));
        this._register(this._editor.onDidChangeModel(() => {
            this._cancelAll();
            scheduleTokenizeViewport();
        }));
        this._register(this._editor.onDidChangeModelContent((e) => {
            this._cancelAll();
            scheduleTokenizeViewport();
        }));
        this._register(this._provider.onDidChange(() => {
            this._cancelAll();
            scheduleTokenizeViewport();
        }));
        this._register(this._configurationService.onDidChangeConfiguration(e => {
            if (e.affectsConfiguration(SEMANTIC_HIGHLIGHTING_SETTING_ID)) {
                this._cancelAll();
                scheduleTokenizeViewport();
            }
        }));
        this._register(this._themeService.onDidColorThemeChange(() => {
            this._cancelAll();
            scheduleTokenizeViewport();
        }));
    }
    _cancelAll() {
        for (const request of this._outstandingRequests) {
            request.cancel();
        }
        this._outstandingRequests = [];
    }
    _removeOutstandingRequest(req) {
        for (let i = 0, len = this._outstandingRequests.length; i < len; i++) {
            if (this._outstandingRequests[i] === req) {
                this._outstandingRequests.splice(i, 1);
                return;
            }
        }
    }
    _tokenizeViewportNow() {
        if (!this._editor.hasModel()) {
            return;
        }
        const model = this._editor.getModel();
        if (model.tokenization.hasCompleteSemanticTokens()) {
            return;
        }
        if (!isSemanticColoringEnabled(model, this._themeService, this._configurationService)) {
            if (model.tokenization.hasSomeSemanticTokens()) {
                model.tokenization.setSemanticTokens(null, false);
            }
            return;
        }
        if (!hasDocumentRangeSemanticTokensProvider(this._provider, model)) {
            if (model.tokenization.hasSomeSemanticTokens()) {
                model.tokenization.setSemanticTokens(null, false);
            }
            return;
        }
        const visibleRanges = this._editor.getVisibleRangesPlusViewportAboveBelow();
        this._outstandingRequests = this._outstandingRequests.concat(visibleRanges.map(range => this._requestRange(model, range)));
    }
    _requestRange(model, range) {
        const requestVersionId = model.getVersionId();
        const request = createCancelablePromise(token => Promise.resolve(getDocumentRangeSemanticTokens(this._provider, model, range, token)));
        const sw = new StopWatch(false);
        request.then((r) => {
            this._debounceInformation.update(model, sw.elapsed());
            if (!r || !r.tokens || model.isDisposed() || model.getVersionId() !== requestVersionId) {
                return;
            }
            const { provider, tokens: result } = r;
            const styling = this._modelService.getSemanticTokensProviderStyling(provider);
            model.tokenization.setPartialSemanticTokens(range, toMultilineTokens2(result, styling, model.getLanguageId()));
        }).then(() => this._removeOutstandingRequest(request), () => this._removeOutstandingRequest(request));
        return request;
    }
};
ViewportSemanticTokensContribution.ID = 'editor.contrib.viewportSemanticTokens';
ViewportSemanticTokensContribution = viewportSemanticTokens_decorate([
    viewportSemanticTokens_param(1, IModelService),
    viewportSemanticTokens_param(2, IThemeService),
    viewportSemanticTokens_param(3, IConfigurationService),
    viewportSemanticTokens_param(4, ILanguageFeatureDebounceService),
    viewportSemanticTokens_param(5, ILanguageFeaturesService)
], ViewportSemanticTokensContribution);
registerEditorContribution(ViewportSemanticTokensContribution.ID, ViewportSemanticTokensContribution);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/wordHighlighter/browser/wordHighlighter.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var wordHighlighter_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var wordHighlighter_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};


















const editorWordHighlight = registerColor('editor.wordHighlightBackground', { dark: '#575757B8', light: '#57575740', hcDark: null, hcLight: null }, localize('wordHighlight', 'Background color of a symbol during read-access, like reading a variable. The color must not be opaque so as not to hide underlying decorations.'), true);
const editorWordHighlightStrong = registerColor('editor.wordHighlightStrongBackground', { dark: '#004972B8', light: '#0e639c40', hcDark: null, hcLight: null }, localize('wordHighlightStrong', 'Background color of a symbol during write-access, like writing to a variable. The color must not be opaque so as not to hide underlying decorations.'), true);
const editorWordHighlightBorder = registerColor('editor.wordHighlightBorder', { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('wordHighlightBorder', 'Border color of a symbol during read-access, like reading a variable.'));
const editorWordHighlightStrongBorder = registerColor('editor.wordHighlightStrongBorder', { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize('wordHighlightStrongBorder', 'Border color of a symbol during write-access, like writing to a variable.'));
const overviewRulerWordHighlightForeground = registerColor('editorOverviewRuler.wordHighlightForeground', { dark: '#A0A0A0CC', light: '#A0A0A0CC', hcDark: '#A0A0A0CC', hcLight: '#A0A0A0CC' }, localize('overviewRulerWordHighlightForeground', 'Overview ruler marker color for symbol highlights. The color must not be opaque so as not to hide underlying decorations.'), true);
const overviewRulerWordHighlightStrongForeground = registerColor('editorOverviewRuler.wordHighlightStrongForeground', { dark: '#C0A0C0CC', light: '#C0A0C0CC', hcDark: '#C0A0C0CC', hcLight: '#C0A0C0CC' }, localize('overviewRulerWordHighlightStrongForeground', 'Overview ruler marker color for write-access symbol highlights. The color must not be opaque so as not to hide underlying decorations.'), true);
const ctxHasWordHighlights = new RawContextKey('hasWordHighlights', false);
function getOccurrencesAtPosition(registry, model, position, token) {
    const orderedByScore = registry.ordered(model);
    // in order of score ask the occurrences provider
    // until someone response with a good result
    // (good = none empty array)
    return first(orderedByScore.map(provider => () => {
        return Promise.resolve(provider.provideDocumentHighlights(model, position, token))
            .then(undefined, onUnexpectedExternalError);
    }), isNonEmptyArray);
}
class OccurenceAtPositionRequest {
    constructor(_model, _selection, _wordSeparators) {
        this._model = _model;
        this._selection = _selection;
        this._wordSeparators = _wordSeparators;
        this._wordRange = this._getCurrentWordRange(_model, _selection);
        this._result = null;
    }
    get result() {
        if (!this._result) {
            this._result = createCancelablePromise(token => this._compute(this._model, this._selection, this._wordSeparators, token));
        }
        return this._result;
    }
    _getCurrentWordRange(model, selection) {
        const word = model.getWordAtPosition(selection.getPosition());
        if (word) {
            return new Range(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._getCurrentWordRange(model, selection);
        let requestIsValid = Boolean(this._wordRange && this._wordRange.equalsRange(currentWordRange));
        // Even if we are on a different word, if that word is in the decorations ranges, the request is still valid
        // (Same symbol)
        for (let i = 0, len = decorations.length; !requestIsValid && i < len; i++) {
            const range = decorations.getRange(i);
            if (range && range.startLineNumber === lineNumber) {
                if (range.startColumn <= startColumn && range.endColumn >= endColumn) {
                    requestIsValid = true;
                }
            }
        }
        return requestIsValid;
    }
    cancel() {
        this.result.cancel();
    }
}
class SemanticOccurenceAtPositionRequest extends OccurenceAtPositionRequest {
    constructor(model, selection, wordSeparators, providers) {
        super(model, selection, wordSeparators);
        this._providers = providers;
    }
    _compute(model, selection, wordSeparators, token) {
        return getOccurrencesAtPosition(this._providers, model, selection.getPosition(), token).then(value => value || []);
    }
}
class TextualOccurenceAtPositionRequest extends OccurenceAtPositionRequest {
    constructor(model, selection, wordSeparators) {
        super(model, selection, wordSeparators);
        this._selectionIsEmpty = selection.isEmpty();
    }
    _compute(model, selection, wordSeparators, token) {
        return timeout(250, token).then(() => {
            if (!selection.isEmpty()) {
                return [];
            }
            const word = model.getWordAtPosition(selection.getPosition());
            if (!word || word.word.length > 1000) {
                return [];
            }
            const matches = model.findMatches(word.word, true, false, true, wordSeparators, false);
            return matches.map(m => {
                return {
                    range: m.range,
                    kind: DocumentHighlightKind.Text
                };
            });
        });
    }
    isValid(model, selection, decorations) {
        const currentSelectionIsEmpty = selection.isEmpty();
        if (this._selectionIsEmpty !== currentSelectionIsEmpty) {
            return false;
        }
        return super.isValid(model, selection, decorations);
    }
}
function computeOccurencesAtPosition(registry, model, selection, wordSeparators) {
    if (registry.has(model)) {
        return new SemanticOccurenceAtPositionRequest(model, selection, wordSeparators, registry);
    }
    return new TextualOccurenceAtPositionRequest(model, selection, wordSeparators);
}
registerModelAndPositionCommand('_executeDocumentHighlights', (accessor, model, position) => {
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    return getOccurrencesAtPosition(languageFeaturesService.documentHighlightProvider, model, position, CancellationToken.None);
});
class WordHighlighter {
    constructor(editor, providers, contextKeyService) {
        this.toUnhook = new DisposableStore();
        this.workerRequestTokenId = 0;
        this.workerRequestCompleted = false;
        this.workerRequestValue = [];
        this.lastCursorPositionChangeTime = 0;
        this.renderDecorationsTimer = -1;
        this.editor = editor;
        this.providers = providers;
        this._hasWordHighlights = ctxHasWordHighlights.bindTo(contextKeyService);
        this._ignorePositionChangeEvent = false;
        this.occurrencesHighlight = this.editor.getOption(74 /* EditorOption.occurrencesHighlight */);
        this.model = this.editor.getModel();
        this.toUnhook.add(editor.onDidChangeCursorPosition((e) => {
            if (this._ignorePositionChangeEvent) {
                // We are changing the position => ignore this event
                return;
            }
            if (!this.occurrencesHighlight) {
                // Early exit if nothing needs to be done!
                // Leave some form of early exit check here if you wish to continue being a cursor position change listener ;)
                return;
            }
            this._onPositionChanged(e);
        }));
        this.toUnhook.add(editor.onDidChangeModelContent((e) => {
            this._stopAll();
        }));
        this.toUnhook.add(editor.onDidChangeConfiguration((e) => {
            const newValue = this.editor.getOption(74 /* EditorOption.occurrencesHighlight */);
            if (this.occurrencesHighlight !== newValue) {
                this.occurrencesHighlight = newValue;
                this._stopAll();
            }
        }));
        this.decorations = this.editor.createDecorationsCollection();
        this.workerRequestTokenId = 0;
        this.workerRequest = null;
        this.workerRequestCompleted = false;
        this.lastCursorPositionChangeTime = 0;
        this.renderDecorationsTimer = -1;
    }
    hasDecorations() {
        return (this.decorations.length > 0);
    }
    restore() {
        if (!this.occurrencesHighlight) {
            return;
        }
        this._run();
    }
    _getSortedHighlights() {
        return (this.decorations.getRanges()
            .sort(Range.compareRangesUsingStarts));
    }
    moveNext() {
        const highlights = this._getSortedHighlights();
        const index = highlights.findIndex((range) => range.containsPosition(this.editor.getPosition()));
        const newIndex = ((index + 1) % highlights.length);
        const dest = highlights[newIndex];
        try {
            this._ignorePositionChangeEvent = true;
            this.editor.setPosition(dest.getStartPosition());
            this.editor.revealRangeInCenterIfOutsideViewport(dest);
            const word = this._getWord();
            if (word) {
                const lineContent = this.editor.getModel().getLineContent(dest.startLineNumber);
                aria_alert(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word.word}'`);
            }
        }
        finally {
            this._ignorePositionChangeEvent = false;
        }
    }
    moveBack() {
        const highlights = this._getSortedHighlights();
        const index = highlights.findIndex((range) => range.containsPosition(this.editor.getPosition()));
        const newIndex = ((index - 1 + highlights.length) % highlights.length);
        const dest = highlights[newIndex];
        try {
            this._ignorePositionChangeEvent = true;
            this.editor.setPosition(dest.getStartPosition());
            this.editor.revealRangeInCenterIfOutsideViewport(dest);
            const word = this._getWord();
            if (word) {
                const lineContent = this.editor.getModel().getLineContent(dest.startLineNumber);
                aria_alert(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word.word}'`);
            }
        }
        finally {
            this._ignorePositionChangeEvent = false;
        }
    }
    _removeDecorations() {
        if (this.decorations.length > 0) {
            // remove decorations
            this.decorations.clear();
            this._hasWordHighlights.set(false);
        }
    }
    _stopAll() {
        // Remove any existing decorations
        this._removeDecorations();
        // Cancel any renderDecorationsTimer
        if (this.renderDecorationsTimer !== -1) {
            clearTimeout(this.renderDecorationsTimer);
            this.renderDecorationsTimer = -1;
        }
        // Cancel any worker request
        if (this.workerRequest !== null) {
            this.workerRequest.cancel();
            this.workerRequest = null;
        }
        // Invalidate any worker request callback
        if (!this.workerRequestCompleted) {
            this.workerRequestTokenId++;
            this.workerRequestCompleted = true;
        }
    }
    _onPositionChanged(e) {
        // disabled
        if (!this.occurrencesHighlight) {
            this._stopAll();
            return;
        }
        // ignore typing & other
        if (e.reason !== 3 /* CursorChangeReason.Explicit */) {
            this._stopAll();
            return;
        }
        this._run();
    }
    _getWord() {
        const editorSelection = this.editor.getSelection();
        const lineNumber = editorSelection.startLineNumber;
        const startColumn = editorSelection.startColumn;
        return this.model.getWordAtPosition({
            lineNumber: lineNumber,
            column: startColumn
        });
    }
    _run() {
        const editorSelection = this.editor.getSelection();
        // ignore multiline selection
        if (editorSelection.startLineNumber !== editorSelection.endLineNumber) {
            this._stopAll();
            return;
        }
        const startColumn = editorSelection.startColumn;
        const endColumn = editorSelection.endColumn;
        const word = this._getWord();
        // The selection must be inside a word or surround one word at most
        if (!word || word.startColumn > startColumn || word.endColumn < endColumn) {
            this._stopAll();
            return;
        }
        // All the effort below is trying to achieve this:
        // - when cursor is moved to a word, trigger immediately a findOccurrences request
        // - 250ms later after the last cursor move event, render the occurrences
        // - no flickering!
        const workerRequestIsValid = (this.workerRequest && this.workerRequest.isValid(this.model, editorSelection, this.decorations));
        // There are 4 cases:
        // a) old workerRequest is valid & completed, renderDecorationsTimer fired
        // b) old workerRequest is valid & completed, renderDecorationsTimer not fired
        // c) old workerRequest is valid, but not completed
        // d) old workerRequest is not valid
        // For a) no action is needed
        // For c), member 'lastCursorPositionChangeTime' will be used when installing the timer so no action is needed
        this.lastCursorPositionChangeTime = (new Date()).getTime();
        if (workerRequestIsValid) {
            if (this.workerRequestCompleted && this.renderDecorationsTimer !== -1) {
                // case b)
                // Delay the firing of renderDecorationsTimer by an extra 250 ms
                clearTimeout(this.renderDecorationsTimer);
                this.renderDecorationsTimer = -1;
                this._beginRenderDecorations();
            }
        }
        else {
            // case d)
            // Stop all previous actions and start fresh
            this._stopAll();
            const myRequestId = ++this.workerRequestTokenId;
            this.workerRequestCompleted = false;
            this.workerRequest = computeOccurencesAtPosition(this.providers, this.model, this.editor.getSelection(), this.editor.getOption(119 /* EditorOption.wordSeparators */));
            this.workerRequest.result.then(data => {
                if (myRequestId === this.workerRequestTokenId) {
                    this.workerRequestCompleted = true;
                    this.workerRequestValue = data || [];
                    this._beginRenderDecorations();
                }
            }, onUnexpectedError);
        }
    }
    _beginRenderDecorations() {
        const currentTime = (new Date()).getTime();
        const minimumRenderTime = this.lastCursorPositionChangeTime + 250;
        if (currentTime >= minimumRenderTime) {
            // Synchronous
            this.renderDecorationsTimer = -1;
            this.renderDecorations();
        }
        else {
            // Asynchronous
            this.renderDecorationsTimer = setTimeout(() => {
                this.renderDecorations();
            }, (minimumRenderTime - currentTime));
        }
    }
    renderDecorations() {
        this.renderDecorationsTimer = -1;
        const decorations = [];
        for (const info of this.workerRequestValue) {
            if (info.range) {
                decorations.push({
                    range: info.range,
                    options: WordHighlighter._getDecorationOptions(info.kind)
                });
            }
        }
        this.decorations.set(decorations);
        this._hasWordHighlights.set(this.hasDecorations());
    }
    static _getDecorationOptions(kind) {
        if (kind === DocumentHighlightKind.Write) {
            return this._WRITE_OPTIONS;
        }
        else if (kind === DocumentHighlightKind.Text) {
            return this._TEXT_OPTIONS;
        }
        else {
            return this._REGULAR_OPTIONS;
        }
    }
    dispose() {
        this._stopAll();
        this.toUnhook.dispose();
    }
}
WordHighlighter._WRITE_OPTIONS = ModelDecorationOptions.register({
    description: 'word-highlight-strong',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    className: 'wordHighlightStrong',
    overviewRuler: {
        color: themeColorFromId(overviewRulerWordHighlightStrongForeground),
        position: OverviewRulerLane.Center
    },
    minimap: {
        color: themeColorFromId(minimapSelectionOccurrenceHighlight),
        position: MinimapPosition.Inline
    },
});
WordHighlighter._TEXT_OPTIONS = ModelDecorationOptions.register({
    description: 'selection-highlight',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    className: 'selectionHighlight',
    overviewRuler: {
        color: themeColorFromId(overviewRulerSelectionHighlightForeground),
        position: OverviewRulerLane.Center
    },
    minimap: {
        color: themeColorFromId(minimapSelectionOccurrenceHighlight),
        position: MinimapPosition.Inline
    },
});
WordHighlighter._REGULAR_OPTIONS = ModelDecorationOptions.register({
    description: 'word-highlight',
    stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
    className: 'wordHighlight',
    overviewRuler: {
        color: themeColorFromId(overviewRulerWordHighlightForeground),
        position: OverviewRulerLane.Center
    },
    minimap: {
        color: themeColorFromId(minimapSelectionOccurrenceHighlight),
        position: MinimapPosition.Inline
    },
});
let WordHighlighterContribution = class WordHighlighterContribution extends Disposable {
    constructor(editor, contextKeyService, languageFeaturesService) {
        super();
        this.wordHighlighter = null;
        const createWordHighlighterIfPossible = () => {
            if (editor.hasModel()) {
                this.wordHighlighter = new WordHighlighter(editor, languageFeaturesService.documentHighlightProvider, contextKeyService);
            }
        };
        this._register(editor.onDidChangeModel((e) => {
            if (this.wordHighlighter) {
                this.wordHighlighter.dispose();
                this.wordHighlighter = null;
            }
            createWordHighlighterIfPossible();
        }));
        createWordHighlighterIfPossible();
    }
    static get(editor) {
        return editor.getContribution(WordHighlighterContribution.ID);
    }
    saveViewState() {
        if (this.wordHighlighter && this.wordHighlighter.hasDecorations()) {
            return true;
        }
        return false;
    }
    moveNext() {
        if (this.wordHighlighter) {
            this.wordHighlighter.moveNext();
        }
    }
    moveBack() {
        if (this.wordHighlighter) {
            this.wordHighlighter.moveBack();
        }
    }
    restoreViewState(state) {
        if (this.wordHighlighter && state) {
            this.wordHighlighter.restore();
        }
    }
    dispose() {
        if (this.wordHighlighter) {
            this.wordHighlighter.dispose();
            this.wordHighlighter = null;
        }
        super.dispose();
    }
};
WordHighlighterContribution.ID = 'editor.contrib.wordHighlighter';
WordHighlighterContribution = wordHighlighter_decorate([
    wordHighlighter_param(1, IContextKeyService),
    wordHighlighter_param(2, ILanguageFeaturesService)
], WordHighlighterContribution);
class WordHighlightNavigationAction extends EditorAction {
    constructor(next, opts) {
        super(opts);
        this._isNext = next;
    }
    run(accessor, editor) {
        const controller = WordHighlighterContribution.get(editor);
        if (!controller) {
            return;
        }
        if (this._isNext) {
            controller.moveNext();
        }
        else {
            controller.moveBack();
        }
    }
}
class NextWordHighlightAction extends WordHighlightNavigationAction {
    constructor() {
        super(true, {
            id: 'editor.action.wordHighlight.next',
            label: localize('wordHighlight.next.label', "Go to Next Symbol Highlight"),
            alias: 'Go to Next Symbol Highlight',
            precondition: ctxHasWordHighlights,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 65 /* KeyCode.F7 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
class PrevWordHighlightAction extends WordHighlightNavigationAction {
    constructor() {
        super(false, {
            id: 'editor.action.wordHighlight.prev',
            label: localize('wordHighlight.previous.label', "Go to Previous Symbol Highlight"),
            alias: 'Go to Previous Symbol Highlight',
            precondition: ctxHasWordHighlights,
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 1024 /* KeyMod.Shift */ | 65 /* KeyCode.F7 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
class TriggerWordHighlightAction extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.wordHighlight.trigger',
            label: localize('wordHighlight.trigger.label', "Trigger Symbol Highlight"),
            alias: 'Trigger Symbol Highlight',
            precondition: ctxHasWordHighlights.toNegated(),
            kbOpts: {
                kbExpr: EditorContextKeys.editorTextFocus,
                primary: 0,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor, args) {
        const controller = WordHighlighterContribution.get(editor);
        if (!controller) {
            return;
        }
        controller.restoreViewState(true);
    }
}
registerEditorContribution(WordHighlighterContribution.ID, WordHighlighterContribution);
registerEditorAction(NextWordHighlightAction);
registerEditorAction(PrevWordHighlightAction);
registerEditorAction(TriggerWordHighlightAction);
registerThemingParticipant((theme, collector) => {
    const selectionHighlight = theme.getColor(editorSelectionHighlight);
    if (selectionHighlight) {
        collector.addRule(`.monaco-editor .focused .selectionHighlight { background-color: ${selectionHighlight}; }`);
        collector.addRule(`.monaco-editor .selectionHighlight { background-color: ${selectionHighlight.transparent(0.5)}; }`);
    }
    const wordHighlight = theme.getColor(editorWordHighlight);
    if (wordHighlight) {
        collector.addRule(`.monaco-editor .wordHighlight { background-color: ${wordHighlight}; }`);
    }
    const wordHighlightStrong = theme.getColor(editorWordHighlightStrong);
    if (wordHighlightStrong) {
        collector.addRule(`.monaco-editor .wordHighlightStrong { background-color: ${wordHighlightStrong}; }`);
    }
    const selectionHighlightBorder = theme.getColor(editorSelectionHighlightBorder);
    if (selectionHighlightBorder) {
        collector.addRule(`.monaco-editor .selectionHighlight { border: 1px ${isHighContrast(theme.type) ? 'dotted' : 'solid'} ${selectionHighlightBorder}; box-sizing: border-box; }`);
    }
    const wordHighlightBorder = theme.getColor(editorWordHighlightBorder);
    if (wordHighlightBorder) {
        collector.addRule(`.monaco-editor .wordHighlight { border: 1px ${isHighContrast(theme.type) ? 'dashed' : 'solid'} ${wordHighlightBorder}; box-sizing: border-box; }`);
    }
    const wordHighlightStrongBorder = theme.getColor(editorWordHighlightStrongBorder);
    if (wordHighlightStrongBorder) {
        collector.addRule(`.monaco-editor .wordHighlightStrong { border: 1px ${isHighContrast(theme.type) ? 'dashed' : 'solid'} ${wordHighlightStrongBorder}; box-sizing: border-box; }`);
    }
});

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/wordOperations/browser/wordOperations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/















class MoveWordCommand extends EditorCommand {
    constructor(opts) {
        super(opts);
        this._inSelectionMode = opts.inSelectionMode;
        this._wordNavigationType = opts.wordNavigationType;
    }
    runEditorCommand(accessor, editor, args) {
        if (!editor.hasModel()) {
            return;
        }
        const wordSeparators = getMapForWordSeparators(editor.getOption(119 /* EditorOption.wordSeparators */));
        const model = editor.getModel();
        const selections = editor.getSelections();
        const result = selections.map((sel) => {
            const inPosition = new Position(sel.positionLineNumber, sel.positionColumn);
            const outPosition = this._move(wordSeparators, model, inPosition, this._wordNavigationType);
            return this._moveTo(sel, outPosition, this._inSelectionMode);
        });
        model.pushStackElement();
        editor._getViewModel().setCursorStates('moveWordCommand', 3 /* CursorChangeReason.Explicit */, result.map(r => CursorState.fromModelSelection(r)));
        if (result.length === 1) {
            const pos = new Position(result[0].positionLineNumber, result[0].positionColumn);
            editor.revealPosition(pos, 0 /* ScrollType.Smooth */);
        }
    }
    _moveTo(from, to, inSelectionMode) {
        if (inSelectionMode) {
            // move just position
            return new Selection(from.selectionStartLineNumber, from.selectionStartColumn, to.lineNumber, to.column);
        }
        else {
            // move everything
            return new Selection(to.lineNumber, to.column, to.lineNumber, to.column);
        }
    }
}
class WordLeftCommand extends MoveWordCommand {
    _move(wordSeparators, model, position, wordNavigationType) {
        return WordOperations.moveWordLeft(wordSeparators, model, position, wordNavigationType);
    }
}
class WordRightCommand extends MoveWordCommand {
    _move(wordSeparators, model, position, wordNavigationType) {
        return WordOperations.moveWordRight(wordSeparators, model, position, wordNavigationType);
    }
}
class CursorWordStartLeft extends WordLeftCommand {
    constructor() {
        super({
            inSelectionMode: false,
            wordNavigationType: 0 /* WordNavigationType.WordStart */,
            id: 'cursorWordStartLeft',
            precondition: undefined
        });
    }
}
class CursorWordEndLeft extends WordLeftCommand {
    constructor() {
        super({
            inSelectionMode: false,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'cursorWordEndLeft',
            precondition: undefined
        });
    }
}
class CursorWordLeft extends WordLeftCommand {
    constructor() {
        var _a;
        super({
            inSelectionMode: false,
            wordNavigationType: 1 /* WordNavigationType.WordStartFast */,
            id: 'cursorWordLeft',
            precondition: undefined,
            kbOpts: {
                kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, (_a = ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)) === null || _a === void 0 ? void 0 : _a.negate()),
                primary: 2048 /* KeyMod.CtrlCmd */ | 15 /* KeyCode.LeftArrow */,
                mac: { primary: 512 /* KeyMod.Alt */ | 15 /* KeyCode.LeftArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
class CursorWordStartLeftSelect extends WordLeftCommand {
    constructor() {
        super({
            inSelectionMode: true,
            wordNavigationType: 0 /* WordNavigationType.WordStart */,
            id: 'cursorWordStartLeftSelect',
            precondition: undefined
        });
    }
}
class CursorWordEndLeftSelect extends WordLeftCommand {
    constructor() {
        super({
            inSelectionMode: true,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'cursorWordEndLeftSelect',
            precondition: undefined
        });
    }
}
class CursorWordLeftSelect extends WordLeftCommand {
    constructor() {
        var _a;
        super({
            inSelectionMode: true,
            wordNavigationType: 1 /* WordNavigationType.WordStartFast */,
            id: 'cursorWordLeftSelect',
            precondition: undefined,
            kbOpts: {
                kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, (_a = ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)) === null || _a === void 0 ? void 0 : _a.negate()),
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */,
                mac: { primary: 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
// Accessibility navigation commands should only be enabled on windows since they are tuned to what NVDA expects
class CursorWordAccessibilityLeft extends WordLeftCommand {
    constructor() {
        super({
            inSelectionMode: false,
            wordNavigationType: 3 /* WordNavigationType.WordAccessibility */,
            id: 'cursorWordAccessibilityLeft',
            precondition: undefined
        });
    }
    _move(_, model, position, wordNavigationType) {
        return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
    }
}
class CursorWordAccessibilityLeftSelect extends WordLeftCommand {
    constructor() {
        super({
            inSelectionMode: true,
            wordNavigationType: 3 /* WordNavigationType.WordAccessibility */,
            id: 'cursorWordAccessibilityLeftSelect',
            precondition: undefined
        });
    }
    _move(_, model, position, wordNavigationType) {
        return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
    }
}
class CursorWordStartRight extends WordRightCommand {
    constructor() {
        super({
            inSelectionMode: false,
            wordNavigationType: 0 /* WordNavigationType.WordStart */,
            id: 'cursorWordStartRight',
            precondition: undefined
        });
    }
}
class CursorWordEndRight extends WordRightCommand {
    constructor() {
        var _a;
        super({
            inSelectionMode: false,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'cursorWordEndRight',
            precondition: undefined,
            kbOpts: {
                kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, (_a = ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)) === null || _a === void 0 ? void 0 : _a.negate()),
                primary: 2048 /* KeyMod.CtrlCmd */ | 17 /* KeyCode.RightArrow */,
                mac: { primary: 512 /* KeyMod.Alt */ | 17 /* KeyCode.RightArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
class CursorWordRight extends WordRightCommand {
    constructor() {
        super({
            inSelectionMode: false,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'cursorWordRight',
            precondition: undefined
        });
    }
}
class CursorWordStartRightSelect extends WordRightCommand {
    constructor() {
        super({
            inSelectionMode: true,
            wordNavigationType: 0 /* WordNavigationType.WordStart */,
            id: 'cursorWordStartRightSelect',
            precondition: undefined
        });
    }
}
class CursorWordEndRightSelect extends WordRightCommand {
    constructor() {
        var _a;
        super({
            inSelectionMode: true,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'cursorWordEndRightSelect',
            precondition: undefined,
            kbOpts: {
                kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, (_a = ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)) === null || _a === void 0 ? void 0 : _a.negate()),
                primary: 2048 /* KeyMod.CtrlCmd */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */,
                mac: { primary: 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
class CursorWordRightSelect extends WordRightCommand {
    constructor() {
        super({
            inSelectionMode: true,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'cursorWordRightSelect',
            precondition: undefined
        });
    }
}
class CursorWordAccessibilityRight extends WordRightCommand {
    constructor() {
        super({
            inSelectionMode: false,
            wordNavigationType: 3 /* WordNavigationType.WordAccessibility */,
            id: 'cursorWordAccessibilityRight',
            precondition: undefined
        });
    }
    _move(_, model, position, wordNavigationType) {
        return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
    }
}
class CursorWordAccessibilityRightSelect extends WordRightCommand {
    constructor() {
        super({
            inSelectionMode: true,
            wordNavigationType: 3 /* WordNavigationType.WordAccessibility */,
            id: 'cursorWordAccessibilityRightSelect',
            precondition: undefined
        });
    }
    _move(_, model, position, wordNavigationType) {
        return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
    }
}
class DeleteWordCommand extends EditorCommand {
    constructor(opts) {
        super(opts);
        this._whitespaceHeuristics = opts.whitespaceHeuristics;
        this._wordNavigationType = opts.wordNavigationType;
    }
    runEditorCommand(accessor, editor, args) {
        const languageConfigurationService = accessor.get(ILanguageConfigurationService);
        if (!editor.hasModel()) {
            return;
        }
        const wordSeparators = getMapForWordSeparators(editor.getOption(119 /* EditorOption.wordSeparators */));
        const model = editor.getModel();
        const selections = editor.getSelections();
        const autoClosingBrackets = editor.getOption(5 /* EditorOption.autoClosingBrackets */);
        const autoClosingQuotes = editor.getOption(8 /* EditorOption.autoClosingQuotes */);
        const autoClosingPairs = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getAutoClosingPairs();
        const viewModel = editor._getViewModel();
        const commands = selections.map((sel) => {
            const deleteRange = this._delete({
                wordSeparators,
                model,
                selection: sel,
                whitespaceHeuristics: this._whitespaceHeuristics,
                autoClosingDelete: editor.getOption(6 /* EditorOption.autoClosingDelete */),
                autoClosingBrackets,
                autoClosingQuotes,
                autoClosingPairs,
                autoClosedCharacters: viewModel.getCursorAutoClosedCharacters()
            }, this._wordNavigationType);
            return new ReplaceCommand(deleteRange, '');
        });
        editor.pushUndoStop();
        editor.executeCommands(this.id, commands);
        editor.pushUndoStop();
    }
}
class DeleteWordLeftCommand extends DeleteWordCommand {
    _delete(ctx, wordNavigationType) {
        const r = WordOperations.deleteWordLeft(ctx, wordNavigationType);
        if (r) {
            return r;
        }
        return new Range(1, 1, 1, 1);
    }
}
class DeleteWordRightCommand extends DeleteWordCommand {
    _delete(ctx, wordNavigationType) {
        const r = WordOperations.deleteWordRight(ctx, wordNavigationType);
        if (r) {
            return r;
        }
        const lineCount = ctx.model.getLineCount();
        const maxColumn = ctx.model.getLineMaxColumn(lineCount);
        return new Range(lineCount, maxColumn, lineCount, maxColumn);
    }
}
class DeleteWordStartLeft extends DeleteWordLeftCommand {
    constructor() {
        super({
            whitespaceHeuristics: false,
            wordNavigationType: 0 /* WordNavigationType.WordStart */,
            id: 'deleteWordStartLeft',
            precondition: EditorContextKeys.writable
        });
    }
}
class DeleteWordEndLeft extends DeleteWordLeftCommand {
    constructor() {
        super({
            whitespaceHeuristics: false,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'deleteWordEndLeft',
            precondition: EditorContextKeys.writable
        });
    }
}
class DeleteWordLeft extends DeleteWordLeftCommand {
    constructor() {
        super({
            whitespaceHeuristics: true,
            wordNavigationType: 0 /* WordNavigationType.WordStart */,
            id: 'deleteWordLeft',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 1 /* KeyCode.Backspace */,
                mac: { primary: 512 /* KeyMod.Alt */ | 1 /* KeyCode.Backspace */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
class DeleteWordStartRight extends DeleteWordRightCommand {
    constructor() {
        super({
            whitespaceHeuristics: false,
            wordNavigationType: 0 /* WordNavigationType.WordStart */,
            id: 'deleteWordStartRight',
            precondition: EditorContextKeys.writable
        });
    }
}
class DeleteWordEndRight extends DeleteWordRightCommand {
    constructor() {
        super({
            whitespaceHeuristics: false,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'deleteWordEndRight',
            precondition: EditorContextKeys.writable
        });
    }
}
class DeleteWordRight extends DeleteWordRightCommand {
    constructor() {
        super({
            whitespaceHeuristics: true,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'deleteWordRight',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 2048 /* KeyMod.CtrlCmd */ | 20 /* KeyCode.Delete */,
                mac: { primary: 512 /* KeyMod.Alt */ | 20 /* KeyCode.Delete */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
class DeleteInsideWord extends EditorAction {
    constructor() {
        super({
            id: 'deleteInsideWord',
            precondition: EditorContextKeys.writable,
            label: localize('deleteInsideWord', "Delete Word"),
            alias: 'Delete Word'
        });
    }
    run(accessor, editor, args) {
        if (!editor.hasModel()) {
            return;
        }
        const wordSeparators = getMapForWordSeparators(editor.getOption(119 /* EditorOption.wordSeparators */));
        const model = editor.getModel();
        const selections = editor.getSelections();
        const commands = selections.map((sel) => {
            const deleteRange = WordOperations.deleteInsideWord(wordSeparators, model, sel);
            return new ReplaceCommand(deleteRange, '');
        });
        editor.pushUndoStop();
        editor.executeCommands(this.id, commands);
        editor.pushUndoStop();
    }
}
registerEditorCommand(new CursorWordStartLeft());
registerEditorCommand(new CursorWordEndLeft());
registerEditorCommand(new CursorWordLeft());
registerEditorCommand(new CursorWordStartLeftSelect());
registerEditorCommand(new CursorWordEndLeftSelect());
registerEditorCommand(new CursorWordLeftSelect());
registerEditorCommand(new CursorWordStartRight());
registerEditorCommand(new CursorWordEndRight());
registerEditorCommand(new CursorWordRight());
registerEditorCommand(new CursorWordStartRightSelect());
registerEditorCommand(new CursorWordEndRightSelect());
registerEditorCommand(new CursorWordRightSelect());
registerEditorCommand(new CursorWordAccessibilityLeft());
registerEditorCommand(new CursorWordAccessibilityLeftSelect());
registerEditorCommand(new CursorWordAccessibilityRight());
registerEditorCommand(new CursorWordAccessibilityRightSelect());
registerEditorCommand(new DeleteWordStartLeft());
registerEditorCommand(new DeleteWordEndLeft());
registerEditorCommand(new DeleteWordLeft());
registerEditorCommand(new DeleteWordStartRight());
registerEditorCommand(new DeleteWordEndRight());
registerEditorCommand(new DeleteWordRight());
registerEditorAction(DeleteInsideWord);

;// ../../node_modules/monaco-editor/esm/vs/editor/contrib/wordPartOperations/browser/wordPartOperations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class DeleteWordPartLeft extends DeleteWordCommand {
    constructor() {
        super({
            whitespaceHeuristics: true,
            wordNavigationType: 0 /* WordNavigationType.WordStart */,
            id: 'deleteWordPartLeft',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 1 /* KeyCode.Backspace */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    _delete(ctx, wordNavigationType) {
        const r = WordPartOperations.deleteWordPartLeft(ctx);
        if (r) {
            return r;
        }
        return new Range(1, 1, 1, 1);
    }
}
class DeleteWordPartRight extends DeleteWordCommand {
    constructor() {
        super({
            whitespaceHeuristics: true,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'deleteWordPartRight',
            precondition: EditorContextKeys.writable,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 20 /* KeyCode.Delete */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    _delete(ctx, wordNavigationType) {
        const r = WordPartOperations.deleteWordPartRight(ctx);
        if (r) {
            return r;
        }
        const lineCount = ctx.model.getLineCount();
        const maxColumn = ctx.model.getLineMaxColumn(lineCount);
        return new Range(lineCount, maxColumn, lineCount, maxColumn);
    }
}
class WordPartLeftCommand extends MoveWordCommand {
    _move(wordSeparators, model, position, wordNavigationType) {
        return WordPartOperations.moveWordPartLeft(wordSeparators, model, position);
    }
}
class CursorWordPartLeft extends WordPartLeftCommand {
    constructor() {
        super({
            inSelectionMode: false,
            wordNavigationType: 0 /* WordNavigationType.WordStart */,
            id: 'cursorWordPartLeft',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 15 /* KeyCode.LeftArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
// Register previous id for compatibility purposes
CommandsRegistry.registerCommandAlias('cursorWordPartStartLeft', 'cursorWordPartLeft');
class CursorWordPartLeftSelect extends WordPartLeftCommand {
    constructor() {
        super({
            inSelectionMode: true,
            wordNavigationType: 0 /* WordNavigationType.WordStart */,
            id: 'cursorWordPartLeftSelect',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 15 /* KeyCode.LeftArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
// Register previous id for compatibility purposes
CommandsRegistry.registerCommandAlias('cursorWordPartStartLeftSelect', 'cursorWordPartLeftSelect');
class WordPartRightCommand extends MoveWordCommand {
    _move(wordSeparators, model, position, wordNavigationType) {
        return WordPartOperations.moveWordPartRight(wordSeparators, model, position);
    }
}
class CursorWordPartRight extends WordPartRightCommand {
    constructor() {
        super({
            inSelectionMode: false,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'cursorWordPartRight',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 17 /* KeyCode.RightArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
class CursorWordPartRightSelect extends WordPartRightCommand {
    constructor() {
        super({
            inSelectionMode: true,
            wordNavigationType: 2 /* WordNavigationType.WordEnd */,
            id: 'cursorWordPartRightSelect',
            precondition: undefined,
            kbOpts: {
                kbExpr: EditorContextKeys.textInputFocus,
                primary: 0,
                mac: { primary: 256 /* KeyMod.WinCtrl */ | 512 /* KeyMod.Alt */ | 1024 /* KeyMod.Shift */ | 17 /* KeyCode.RightArrow */ },
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
}
registerEditorCommand(new DeleteWordPartLeft());
registerEditorCommand(new DeleteWordPartRight());
registerEditorCommand(new CursorWordPartLeft());
registerEditorCommand(new CursorWordPartLeftSelect());
registerEditorCommand(new CursorWordPartRight());
registerEditorCommand(new CursorWordPartRightSelect());

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/editorBaseApi.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/









class KeyMod {
    static chord(firstPart, secondPart) {
        return KeyChord(firstPart, secondPart);
    }
}
KeyMod.CtrlCmd = 2048 /* ConstKeyMod.CtrlCmd */;
KeyMod.Shift = 1024 /* ConstKeyMod.Shift */;
KeyMod.Alt = 512 /* ConstKeyMod.Alt */;
KeyMod.WinCtrl = 256 /* ConstKeyMod.WinCtrl */;
function createMonacoBaseAPI() {
    return {
        editor: undefined,
        languages: undefined,
        CancellationTokenSource: CancellationTokenSource,
        Emitter: Emitter,
        KeyCode: KeyCode,
        KeyMod: KeyMod,
        Position: Position,
        Range: Range,
        Selection: Selection,
        SelectionDirection: SelectionDirection,
        MarkerSeverity: standaloneEnums_MarkerSeverity,
        MarkerTag: MarkerTag,
        Uri: URI,
        Token: languages_Token
    };
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/standalone-tokens.css
var standalone_tokens = __webpack_require__(28663);
;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/standalone-tokens.css

      
      
      
      
      
      
      
      
      

var standalone_tokens_options = {};

standalone_tokens_options.styleTagTransform = (styleTagTransform_default());
standalone_tokens_options.setAttributes = (setAttributesWithoutAttributes_default());

      standalone_tokens_options.insert = insertBySelector_default().bind(null, "head");
    
standalone_tokens_options.domAPI = (styleDomAPI_default());
standalone_tokens_options.insertStyleElement = (insertStyleElement_default());

var standalone_tokens_update = injectStylesIntoStyleTag_default()(standalone_tokens/* default */.A, standalone_tokens_options);




       /* harmony default export */ const browser_standalone_tokens = (standalone_tokens/* default */.A && standalone_tokens/* default */.A.locals ? standalone_tokens/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/widget/diffNavigator.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





const diffNavigator_defaultOptions = {
    followsCaret: true,
    ignoreCharChanges: true,
    alwaysRevealFirst: true
};
/**
 * Create a new diff navigator for the provided diff editor.
 */
class DiffNavigator extends Disposable {
    constructor(editor, options = {}) {
        super();
        this._onDidUpdate = this._register(new Emitter());
        this._editor = editor;
        this._options = mixin(options, diffNavigator_defaultOptions, false);
        this.disposed = false;
        this.nextIdx = -1;
        this.ranges = [];
        this.ignoreSelectionChange = false;
        this.revealFirst = Boolean(this._options.alwaysRevealFirst);
        // hook up to diff editor for diff, disposal, and caret move
        this._register(this._editor.onDidDispose(() => this.dispose()));
        this._register(this._editor.onDidUpdateDiff(() => this._onDiffUpdated()));
        if (this._options.followsCaret) {
            this._register(this._editor.getModifiedEditor().onDidChangeCursorPosition((e) => {
                if (this.ignoreSelectionChange) {
                    return;
                }
                this.nextIdx = -1;
            }));
        }
        if (this._options.alwaysRevealFirst) {
            this._register(this._editor.getModifiedEditor().onDidChangeModel((e) => {
                this.revealFirst = true;
            }));
        }
        // init things
        this._init();
    }
    _init() {
        const changes = this._editor.getLineChanges();
        if (!changes) {
            return;
        }
    }
    _onDiffUpdated() {
        this._init();
        this._compute(this._editor.getLineChanges());
        if (this.revealFirst) {
            // Only reveal first on first non-null changes
            if (this._editor.getLineChanges() !== null) {
                this.revealFirst = false;
                this.nextIdx = -1;
                this.next(1 /* ScrollType.Immediate */);
            }
        }
    }
    _compute(lineChanges) {
        // new ranges
        this.ranges = [];
        if (lineChanges) {
            // create ranges from changes
            lineChanges.forEach((lineChange) => {
                if (!this._options.ignoreCharChanges && lineChange.charChanges) {
                    lineChange.charChanges.forEach((charChange) => {
                        this.ranges.push({
                            rhs: true,
                            range: new Range(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn)
                        });
                    });
                }
                else {
                    if (lineChange.modifiedEndLineNumber === 0) {
                        // a deletion
                        this.ranges.push({
                            rhs: true,
                            range: new Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedStartLineNumber + 1, 1)
                        });
                    }
                    else {
                        // an insertion or modification
                        this.ranges.push({
                            rhs: true,
                            range: new Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber + 1, 1)
                        });
                    }
                }
            });
        }
        // sort
        this.ranges.sort((left, right) => Range.compareRangesUsingStarts(left.range, right.range));
        this._onDidUpdate.fire(this);
    }
    _initIdx(fwd) {
        let found = false;
        const position = this._editor.getPosition();
        if (!position) {
            this.nextIdx = 0;
            return;
        }
        for (let i = 0, len = this.ranges.length; i < len && !found; i++) {
            const range = this.ranges[i].range;
            if (position.isBeforeOrEqual(range.getStartPosition())) {
                this.nextIdx = i + (fwd ? 0 : -1);
                found = true;
            }
        }
        if (!found) {
            // after the last change
            this.nextIdx = fwd ? 0 : this.ranges.length - 1;
        }
        if (this.nextIdx < 0) {
            this.nextIdx = this.ranges.length - 1;
        }
    }
    _move(fwd, scrollType) {
        ok(!this.disposed, 'Illegal State - diff navigator has been disposed');
        if (!this.canNavigate()) {
            return;
        }
        if (this.nextIdx === -1) {
            this._initIdx(fwd);
        }
        else if (fwd) {
            this.nextIdx += 1;
            if (this.nextIdx >= this.ranges.length) {
                this.nextIdx = 0;
            }
        }
        else {
            this.nextIdx -= 1;
            if (this.nextIdx < 0) {
                this.nextIdx = this.ranges.length - 1;
            }
        }
        const info = this.ranges[this.nextIdx];
        this.ignoreSelectionChange = true;
        try {
            const pos = info.range.getStartPosition();
            this._editor.setPosition(pos);
            this._editor.revealRangeInCenter(info.range, scrollType);
        }
        finally {
            this.ignoreSelectionChange = false;
        }
    }
    canNavigate() {
        return this.ranges && this.ranges.length > 0;
    }
    next(scrollType = 0 /* ScrollType.Smooth */) {
        this._move(true, scrollType);
    }
    previous(scrollType = 0 /* ScrollType.Smooth */) {
        this._move(false, scrollType);
    }
    dispose() {
        super.dispose();
        this.ranges = [];
        this.disposed = true;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/worker/simpleWorker.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






const INITIALIZE = '$initialize';
let webWorkerWarningLogged = false;
function logOnceWebWorkerWarning(err) {
    if (!isWeb) {
        // running tests
        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);
}
class RequestMessage {
    constructor(vsWorker, req, method, args) {
        this.vsWorker = vsWorker;
        this.req = req;
        this.method = method;
        this.args = args;
        this.type = 0 /* MessageType.Request */;
    }
}
class ReplyMessage {
    constructor(vsWorker, seq, res, err) {
        this.vsWorker = vsWorker;
        this.seq = seq;
        this.res = res;
        this.err = err;
        this.type = 1 /* MessageType.Reply */;
    }
}
class SubscribeEventMessage {
    constructor(vsWorker, req, eventName, arg) {
        this.vsWorker = vsWorker;
        this.req = req;
        this.eventName = eventName;
        this.arg = arg;
        this.type = 2 /* MessageType.SubscribeEvent */;
    }
}
class EventMessage {
    constructor(vsWorker, req, event) {
        this.vsWorker = vsWorker;
        this.req = req;
        this.event = event;
        this.type = 3 /* MessageType.Event */;
    }
}
class UnsubscribeEventMessage {
    constructor(vsWorker, req) {
        this.vsWorker = vsWorker;
        this.req = req;
        this.type = 4 /* MessageType.UnsubscribeEvent */;
    }
}
class SimpleWorkerProtocol {
    constructor(handler) {
        this._workerId = -1;
        this._handler = handler;
        this._lastSentReq = 0;
        this._pendingReplies = Object.create(null);
        this._pendingEmitters = new Map();
        this._pendingEvents = new Map();
    }
    setWorkerId(workerId) {
        this._workerId = workerId;
    }
    sendMessage(method, args) {
        const req = String(++this._lastSentReq);
        return new Promise((resolve, reject) => {
            this._pendingReplies[req] = {
                resolve: resolve,
                reject: reject
            };
            this._send(new RequestMessage(this._workerId, req, method, args));
        });
    }
    listen(eventName, arg) {
        let req = null;
        const emitter = new Emitter({
            onFirstListenerAdd: () => {
                req = String(++this._lastSentReq);
                this._pendingEmitters.set(req, emitter);
                this._send(new SubscribeEventMessage(this._workerId, req, eventName, arg));
            },
            onLastListenerRemove: () => {
                this._pendingEmitters.delete(req);
                this._send(new UnsubscribeEventMessage(this._workerId, req));
                req = null;
            }
        });
        return emitter.event;
    }
    handleMessage(message) {
        if (!message || !message.vsWorker) {
            return;
        }
        if (this._workerId !== -1 && message.vsWorker !== this._workerId) {
            return;
        }
        this._handleMessage(message);
    }
    _handleMessage(msg) {
        switch (msg.type) {
            case 1 /* MessageType.Reply */:
                return this._handleReplyMessage(msg);
            case 0 /* MessageType.Request */:
                return this._handleRequestMessage(msg);
            case 2 /* MessageType.SubscribeEvent */:
                return this._handleSubscribeEventMessage(msg);
            case 3 /* MessageType.Event */:
                return this._handleEventMessage(msg);
            case 4 /* MessageType.UnsubscribeEvent */:
                return this._handleUnsubscribeEventMessage(msg);
        }
    }
    _handleReplyMessage(replyMessage) {
        if (!this._pendingReplies[replyMessage.seq]) {
            console.warn('Got reply to unknown seq');
            return;
        }
        const reply = this._pendingReplies[replyMessage.seq];
        delete this._pendingReplies[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);
    }
    _handleRequestMessage(requestMessage) {
        const req = requestMessage.req;
        const result = this._handler.handleMessage(requestMessage.method, requestMessage.args);
        result.then((r) => {
            this._send(new ReplyMessage(this._workerId, req, r, undefined));
        }, (e) => {
            if (e.detail instanceof Error) {
                // Loading errors have a detail property that points to the actual error
                e.detail = transformErrorForSerialization(e.detail);
            }
            this._send(new ReplyMessage(this._workerId, req, undefined, transformErrorForSerialization(e)));
        });
    }
    _handleSubscribeEventMessage(msg) {
        const req = msg.req;
        const disposable = this._handler.handleEvent(msg.eventName, msg.arg)((event) => {
            this._send(new EventMessage(this._workerId, req, event));
        });
        this._pendingEvents.set(req, disposable);
    }
    _handleEventMessage(msg) {
        if (!this._pendingEmitters.has(msg.req)) {
            console.warn('Got event for unknown req');
            return;
        }
        this._pendingEmitters.get(msg.req).fire(msg.event);
    }
    _handleUnsubscribeEventMessage(msg) {
        if (!this._pendingEvents.has(msg.req)) {
            console.warn('Got unsubscribe for unknown req');
            return;
        }
        this._pendingEvents.get(msg.req).dispose();
        this._pendingEvents.delete(msg.req);
    }
    _send(msg) {
        const transfer = [];
        if (msg.type === 0 /* MessageType.Request */) {
            for (let i = 0; i < msg.args.length; i++) {
                if (msg.args[i] instanceof ArrayBuffer) {
                    transfer.push(msg.args[i]);
                }
            }
        }
        else if (msg.type === 1 /* MessageType.Reply */) {
            if (msg.res instanceof ArrayBuffer) {
                transfer.push(msg.res);
            }
        }
        this._handler.sendMessage(msg, transfer);
    }
}
/**
 * Main thread side
 */
class SimpleWorkerClient extends Disposable {
    constructor(workerFactory, moduleId, host) {
        super();
        let lazyProxyReject = null;
        this._worker = this._register(workerFactory.create('vs/base/common/worker/simpleWorker', (msg) => {
            this._protocol.handleMessage(msg);
        }, (err) => {
            // in Firefox, web workers fail lazily :(
            // we will reject the proxy
            lazyProxyReject === null || lazyProxyReject === void 0 ? void 0 : lazyProxyReject(err);
        }));
        this._protocol = new SimpleWorkerProtocol({
            sendMessage: (msg, transfer) => {
                this._worker.postMessage(msg, transfer);
            },
            handleMessage: (method, args) => {
                if (typeof host[method] !== 'function') {
                    return Promise.reject(new Error('Missing method ' + method + ' on main thread host.'));
                }
                try {
                    return Promise.resolve(host[method].apply(host, args));
                }
                catch (e) {
                    return Promise.reject(e);
                }
            },
            handleEvent: (eventName, arg) => {
                if (propertyIsDynamicEvent(eventName)) {
                    const event = host[eventName].call(host, arg);
                    if (typeof event !== 'function') {
                        throw new Error(`Missing dynamic event ${eventName} on main thread host.`);
                    }
                    return event;
                }
                if (propertyIsEvent(eventName)) {
                    const event = host[eventName];
                    if (typeof event !== 'function') {
                        throw new Error(`Missing event ${eventName} on main thread host.`);
                    }
                    return event;
                }
                throw new Error(`Malformed event name ${eventName}`);
            }
        });
        this._protocol.setWorkerId(this._worker.getId());
        // Gather loader configuration
        let loaderConfiguration = null;
        if (typeof platform_globals.require !== 'undefined' && typeof platform_globals.require.getConfig === 'function') {
            // Get the configuration from the Monaco AMD Loader
            loaderConfiguration = platform_globals.require.getConfig();
        }
        else if (typeof platform_globals.requirejs !== 'undefined') {
            // Get the configuration from requirejs
            loaderConfiguration = platform_globals.requirejs.s.contexts._.config;
        }
        const hostMethods = getAllMethodNames(host);
        // Send initialize message
        this._onModuleLoaded = this._protocol.sendMessage(INITIALIZE, [
            this._worker.getId(),
            JSON.parse(JSON.stringify(loaderConfiguration)),
            moduleId,
            hostMethods,
        ]);
        // Create proxy to loaded code
        const proxyMethodRequest = (method, args) => {
            return this._request(method, args);
        };
        const proxyListen = (eventName, arg) => {
            return this._protocol.listen(eventName, arg);
        };
        this._lazyProxy = new Promise((resolve, reject) => {
            lazyProxyReject = reject;
            this._onModuleLoaded.then((availableMethods) => {
                resolve(simpleWorker_createProxyObject(availableMethods, proxyMethodRequest, proxyListen));
            }, (e) => {
                reject(e);
                this._onError('Worker failed to load ' + moduleId, e);
            });
        });
    }
    getProxyObject() {
        return this._lazyProxy;
    }
    _request(method, args) {
        return new Promise((resolve, reject) => {
            this._onModuleLoaded.then(() => {
                this._protocol.sendMessage(method, args).then(resolve, reject);
            }, reject);
        });
    }
    _onError(message, error) {
        console.error(message);
        console.info(error);
    }
}
function propertyIsEvent(name) {
    // Assume a property is an event if it has a form of "onSomething"
    return name[0] === 'o' && name[1] === 'n' && isUpperAsciiLetter(name.charCodeAt(2));
}
function propertyIsDynamicEvent(name) {
    // Assume a property is a dynamic event (a method that returns an event) if it has a form of "onDynamicSomething"
    return /^onDynamic/.test(name) && isUpperAsciiLetter(name.charCodeAt(9));
}
function simpleWorker_createProxyObject(methodNames, invoke, proxyListen) {
    const createProxyMethod = (method) => {
        return function () {
            const args = Array.prototype.slice.call(arguments, 0);
            return invoke(method, args);
        };
    };
    const createProxyDynamicEvent = (eventName) => {
        return function (arg) {
            return proxyListen(eventName, arg);
        };
    };
    const result = {};
    for (const methodName of methodNames) {
        if (propertyIsDynamicEvent(methodName)) {
            result[methodName] = createProxyDynamicEvent(methodName);
            continue;
        }
        if (propertyIsEvent(methodName)) {
            result[methodName] = proxyListen(methodName, undefined);
            continue;
        }
        result[methodName] = createProxyMethod(methodName);
    }
    return result;
}
/**
 * Worker side
 */
class SimpleWorkerServer {
    constructor(postMessage, requestHandlerFactory) {
        this._requestHandlerFactory = requestHandlerFactory;
        this._requestHandler = null;
        this._protocol = new SimpleWorkerProtocol({
            sendMessage: (msg, transfer) => {
                postMessage(msg, transfer);
            },
            handleMessage: (method, args) => this._handleMessage(method, args),
            handleEvent: (eventName, arg) => this._handleEvent(eventName, arg)
        });
    }
    onmessage(msg) {
        this._protocol.handleMessage(msg);
    }
    _handleMessage(method, args) {
        if (method === INITIALIZE) {
            return this.initialize(args[0], args[1], args[2], args[3]);
        }
        if (!this._requestHandler || typeof this._requestHandler[method] !== 'function') {
            return Promise.reject(new Error('Missing requestHandler or method: ' + method));
        }
        try {
            return Promise.resolve(this._requestHandler[method].apply(this._requestHandler, args));
        }
        catch (e) {
            return Promise.reject(e);
        }
    }
    _handleEvent(eventName, arg) {
        if (!this._requestHandler) {
            throw new Error(`Missing requestHandler`);
        }
        if (propertyIsDynamicEvent(eventName)) {
            const event = this._requestHandler[eventName].call(this._requestHandler, arg);
            if (typeof event !== 'function') {
                throw new Error(`Missing dynamic event ${eventName} on request handler.`);
            }
            return event;
        }
        if (propertyIsEvent(eventName)) {
            const event = this._requestHandler[eventName];
            if (typeof event !== 'function') {
                throw new Error(`Missing event ${eventName} on request handler.`);
            }
            return event;
        }
        throw new Error(`Malformed event name ${eventName}`);
    }
    initialize(workerId, loaderConfig, moduleId, hostMethods) {
        this._protocol.setWorkerId(workerId);
        const proxyMethodRequest = (method, args) => {
            return this._protocol.sendMessage(method, args);
        };
        const proxyListen = (eventName, arg) => {
            return this._protocol.listen(eventName, arg);
        };
        const hostProxy = simpleWorker_createProxyObject(hostMethods, proxyMethodRequest, proxyListen);
        if (this._requestHandlerFactory) {
            // static request handler
            this._requestHandler = this._requestHandlerFactory(hostProxy);
            return Promise.resolve(types.getAllMethodNames(this._requestHandler));
        }
        if (loaderConfig) {
            // Remove 'baseUrl', handling it is beyond scope for now
            if (typeof loaderConfig.baseUrl !== 'undefined') {
                delete loaderConfig['baseUrl'];
            }
            if (typeof loaderConfig.paths !== 'undefined') {
                if (typeof loaderConfig.paths.vs !== 'undefined') {
                    delete loaderConfig.paths['vs'];
                }
            }
            if (typeof loaderConfig.trustedTypesPolicy !== undefined) {
                // don't use, it has been destroyed during serialize
                delete loaderConfig['trustedTypesPolicy'];
            }
            // Since this is in a web worker, enable catching errors
            loaderConfig.catchError = true;
            globals.require.config(loaderConfig);
        }
        return new Promise((resolve, reject) => {
            // Use the global require to be sure to get the global config
            // ESM-comment-begin
            // 			const req = (globals.require || require);
            // ESM-comment-end
            // ESM-uncomment-begin
            const req = globals.require;
            // ESM-uncomment-end
            req([moduleId], (module) => {
                this._requestHandler = module.create(hostProxy);
                if (!this._requestHandler) {
                    reject(new Error(`No RequestHandler!`));
                    return;
                }
                resolve(types.getAllMethodNames(this._requestHandler));
            }, reject);
        });
    }
}
/**
 * Called on the worker side
 */
function simpleWorker_create(postMessage) {
    return new SimpleWorkerServer(postMessage, null);
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/defaultWorkerFactory.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var defaultWorkerFactory_a;


const defaultWorkerFactory_ttPolicy = (defaultWorkerFactory_a = window.trustedTypes) === null || defaultWorkerFactory_a === void 0 ? void 0 : defaultWorkerFactory_a.createPolicy('defaultWorkerFactory', { createScriptURL: value => value });
function getWorker(label) {
    // Option for hosts to overwrite the worker script (used in the standalone editor)
    if (platform_globals.MonacoEnvironment) {
        if (typeof platform_globals.MonacoEnvironment.getWorker === 'function') {
            return platform_globals.MonacoEnvironment.getWorker('workerMain.js', label);
        }
        if (typeof platform_globals.MonacoEnvironment.getWorkerUrl === 'function') {
            const workerUrl = platform_globals.MonacoEnvironment.getWorkerUrl('workerMain.js', label);
            return new Worker(defaultWorkerFactory_ttPolicy ? defaultWorkerFactory_ttPolicy.createScriptURL(workerUrl) : workerUrl, { name: label });
        }
    }
    // ESM-comment-begin
    // 	if (typeof require === 'function') {
    // 		// check if the JS lives on a different origin
    // 		const workerMain = require.toUrl('vs/base/worker/workerMain.js'); // explicitly using require.toUrl(), see https://github.com/microsoft/vscode/issues/107440#issuecomment-698982321
    // 		const workerUrl = getWorkerBootstrapUrl(workerMain, label);
    // 		return new Worker(ttPolicy ? ttPolicy.createScriptURL(workerUrl) as unknown as string : workerUrl, { name: label });
    // 	}
    // ESM-comment-end
    throw new Error(`You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker`);
}
// ESM-comment-begin
// export function getWorkerBootstrapUrl(scriptPath: string, label: string): string {
// 	if (/^((http:)|(https:)|(file:))/.test(scriptPath) && scriptPath.substring(0, self.origin.length) !== self.origin) {
// 		// this is the cross-origin case
// 		// i.e. the webpage is running at a different origin than where the scripts are loaded from
// 		const myPath = 'vs/base/worker/defaultWorkerFactory.js';
// 		const workerBaseUrl = require.toUrl(myPath).slice(0, -myPath.length); // explicitly using require.toUrl(), see https://github.com/microsoft/vscode/issues/107440#issuecomment-698982321
// 		const js = `/*${label}*/self.MonacoEnvironment={baseUrl: '${workerBaseUrl}'};const ttPolicy = self.trustedTypes?.createPolicy('defaultWorkerFactory', { createScriptURL: value => value });importScripts(ttPolicy?.createScriptURL('${scriptPath}') ?? '${scriptPath}');/*${label}*/`;
// 		const blob = new Blob([js], { type: 'application/javascript' });
// 		return URL.createObjectURL(blob);
// 	}
// 	return scriptPath + '#' + label;
// }
// ESM-comment-end
function isPromiseLike(obj) {
    if (typeof obj.then === 'function') {
        return true;
    }
    return false;
}
/**
 * A worker that uses HTML5 web workers so that is has
 * its own global scope and its own thread.
 */
class WebWorker {
    constructor(moduleId, id, label, onMessageCallback, onErrorCallback) {
        this.id = id;
        const workerOrPromise = getWorker(label);
        if (isPromiseLike(workerOrPromise)) {
            this.worker = workerOrPromise;
        }
        else {
            this.worker = Promise.resolve(workerOrPromise);
        }
        this.postMessage(moduleId, []);
        this.worker.then((w) => {
            w.onmessage = function (ev) {
                onMessageCallback(ev.data);
            };
            w.onmessageerror = onErrorCallback;
            if (typeof w.addEventListener === 'function') {
                w.addEventListener('error', onErrorCallback);
            }
        });
    }
    getId() {
        return this.id;
    }
    postMessage(message, transfer) {
        var _a;
        (_a = this.worker) === null || _a === void 0 ? void 0 : _a.then(w => w.postMessage(message, transfer));
    }
    dispose() {
        var _a;
        (_a = this.worker) === null || _a === void 0 ? void 0 : _a.then(w => w.terminate());
        this.worker = null;
    }
}
class DefaultWorkerFactory {
    constructor(label) {
        this._label = label;
        this._webWorkerFailedBeforeError = false;
    }
    create(moduleId, onMessageCallback, onErrorCallback) {
        const workerId = (++DefaultWorkerFactory.LAST_WORKER_ID);
        if (this._webWorkerFailedBeforeError) {
            throw this._webWorkerFailedBeforeError;
        }
        return new WebWorker(moduleId, workerId, this._label || 'anonymous' + workerId, onMessageCallback, (err) => {
            logOnceWebWorkerWarning(err);
            this._webWorkerFailedBeforeError = err;
            onErrorCallback(err);
        });
    }
}
DefaultWorkerFactory.LAST_WORKER_ID = 0;

;// ../../node_modules/monaco-editor/esm/vs/editor/common/diff/diffComputer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


const MINIMUM_MATCHING_CHARACTER_LENGTH = 3;
function computeDiff(originalSequence, modifiedSequence, continueProcessingPredicate, pretty) {
    const diffAlgo = new LcsDiff(originalSequence, modifiedSequence, continueProcessingPredicate);
    return diffAlgo.ComputeDiff(pretty);
}
class LineSequence {
    constructor(lines) {
        const startColumns = [];
        const endColumns = [];
        for (let i = 0, length = lines.length; i < length; i++) {
            startColumns[i] = getFirstNonBlankColumn(lines[i], 1);
            endColumns[i] = getLastNonBlankColumn(lines[i], 1);
        }
        this.lines = lines;
        this._startColumns = startColumns;
        this._endColumns = endColumns;
    }
    getElements() {
        const elements = [];
        for (let i = 0, len = this.lines.length; i < len; i++) {
            elements[i] = this.lines[i].substring(this._startColumns[i] - 1, this._endColumns[i] - 1);
        }
        return elements;
    }
    getStrictElement(index) {
        return this.lines[index];
    }
    getStartLineNumber(i) {
        return i + 1;
    }
    getEndLineNumber(i) {
        return i + 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._startColumns[index] : 1);
            const endColumn = (shouldIgnoreTrimWhitespace ? this._endColumns[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) {
                // Add \n if trim whitespace is not ignored
                charCodes[len] = 10 /* CharCode.LineFeed */;
                lineNumbers[len] = index + 1;
                columns[len] = lineContent.length + 1;
                len++;
            }
        }
        return new CharSequence(charCodes, lineNumbers, columns);
    }
}
class CharSequence {
    constructor(charCodes, lineNumbers, columns) {
        this._charCodes = charCodes;
        this._lineNumbers = lineNumbers;
        this._columns = columns;
    }
    toString() {
        return ('[' + this._charCodes.map((s, idx) => (s === 10 /* CharCode.LineFeed */ ? '\\n' : String.fromCharCode(s)) + `-(${this._lineNumbers[idx]},${this._columns[idx]})`).join(', ') + ']');
    }
    _assertIndex(index, arr) {
        if (index < 0 || index >= arr.length) {
            throw new Error(`Illegal index`);
        }
    }
    getElements() {
        return this._charCodes;
    }
    getStartLineNumber(i) {
        if (i > 0 && i === this._lineNumbers.length) {
            // the start line number of the element after the last element
            // is the end line number of the last element
            return this.getEndLineNumber(i - 1);
        }
        this._assertIndex(i, this._lineNumbers);
        return this._lineNumbers[i];
    }
    getEndLineNumber(i) {
        if (i === -1) {
            // the end line number of the element before the first element
            // is the start line number of the first element
            return this.getStartLineNumber(i + 1);
        }
        this._assertIndex(i, this._lineNumbers);
        if (this._charCodes[i] === 10 /* CharCode.LineFeed */) {
            return this._lineNumbers[i] + 1;
        }
        return this._lineNumbers[i];
    }
    getStartColumn(i) {
        if (i > 0 && i === this._columns.length) {
            // the start column of the element after the last element
            // is the end column of the last element
            return this.getEndColumn(i - 1);
        }
        this._assertIndex(i, this._columns);
        return this._columns[i];
    }
    getEndColumn(i) {
        if (i === -1) {
            // the end column of the element before the first element
            // is the start column of the first element
            return this.getStartColumn(i + 1);
        }
        this._assertIndex(i, this._columns);
        if (this._charCodes[i] === 10 /* CharCode.LineFeed */) {
            return 1;
        }
        return this._columns[i] + 1;
    }
}
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 i = 1, len = rawChanges.length; i < len; i++) {
        const currChange = rawChanges[i];
        const originalMatchingLength = currChange.originalStart - (prevChange.originalStart + prevChange.originalLength);
        const modifiedMatchingLength = currChange.modifiedStart - (prevChange.modifiedStart + prevChange.modifiedLength);
        // Both of the above should be equal, but the continueProcessingPredicate may prevent this from being true
        const matchingLength = Math.min(originalMatchingLength, modifiedMatchingLength);
        if (matchingLength < MINIMUM_MATCHING_CHARACTER_LENGTH) {
            // Merge the current change into the previous one
            prevChange.originalLength = (currChange.originalStart + currChange.originalLength) - prevChange.originalStart;
            prevChange.modifiedLength = (currChange.modifiedStart + currChange.modifiedLength) - prevChange.modifiedStart;
        }
        else {
            // Add the current change
            result.push(currChange);
            prevChange = currChange;
        }
    }
    return result;
}
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 = undefined;
        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()) {
            // Compute character changes for diff chunks of at most 20 lines...
            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 i = 0, length = rawChanges.length; i < length; i++) {
                    charChanges.push(CharChange.createFromDiffChange(rawChanges[i], originalCharSequence, modifiedCharSequence));
                }
            }
        }
        return new LineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges);
    }
}
class DiffComputer {
    constructor(originalLines, modifiedLines, opts) {
        this.shouldComputeCharChanges = opts.shouldComputeCharChanges;
        this.shouldPostProcessCharChanges = opts.shouldPostProcessCharChanges;
        this.shouldIgnoreTrimWhitespace = opts.shouldIgnoreTrimWhitespace;
        this.shouldMakePrettyDiff = opts.shouldMakePrettyDiff;
        this.originalLines = originalLines;
        this.modifiedLines = modifiedLines;
        this.original = new LineSequence(originalLines);
        this.modified = new LineSequence(modifiedLines);
        this.continueLineDiff = createContinueProcessingPredicate(opts.maxComputationTime);
        this.continueCharDiff = createContinueProcessingPredicate(opts.maxComputationTime === 0 ? 0 : Math.min(opts.maxComputationTime, 5000)); // never run after 5s for character changes...
    }
    computeDiff() {
        if (this.original.lines.length === 1 && this.original.lines[0].length === 0) {
            // empty original => fast path
            if (this.modified.lines.length === 1 && this.modified.lines[0].length === 0) {
                return {
                    quitEarly: false,
                    changes: []
                };
            }
            return {
                quitEarly: false,
                changes: [{
                        originalStartLineNumber: 1,
                        originalEndLineNumber: 1,
                        modifiedStartLineNumber: 1,
                        modifiedEndLineNumber: this.modified.lines.length,
                        charChanges: [{
                                modifiedEndColumn: 0,
                                modifiedEndLineNumber: 0,
                                modifiedStartColumn: 0,
                                modifiedStartLineNumber: 0,
                                originalEndColumn: 0,
                                originalEndLineNumber: 0,
                                originalStartColumn: 0,
                                originalStartLineNumber: 0
                            }]
                    }]
            };
        }
        if (this.modified.lines.length === 1 && this.modified.lines[0].length === 0) {
            // empty modified => fast path
            return {
                quitEarly: false,
                changes: [{
                        originalStartLineNumber: 1,
                        originalEndLineNumber: this.original.lines.length,
                        modifiedStartLineNumber: 1,
                        modifiedEndLineNumber: 1,
                        charChanges: [{
                                modifiedEndColumn: 0,
                                modifiedEndLineNumber: 0,
                                modifiedStartColumn: 0,
                                modifiedStartLineNumber: 0,
                                originalEndColumn: 0,
                                originalEndLineNumber: 0,
                                originalStartColumn: 0,
                                originalStartLineNumber: 0
                            }]
                    }]
            };
        }
        const diffResult = computeDiff(this.original, this.modified, this.continueLineDiff, this.shouldMakePrettyDiff);
        const rawChanges = diffResult.changes;
        const quitEarly = diffResult.quitEarly;
        // The diff is always computed with ignoring trim whitespace
        // This ensures we get the prettiest diff
        if (this.shouldIgnoreTrimWhitespace) {
            const lineChanges = [];
            for (let i = 0, length = rawChanges.length; i < length; i++) {
                lineChanges.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, rawChanges[i], this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
            }
            return {
                quitEarly: quitEarly,
                changes: lineChanges
            };
        }
        // Need to post-process and introduce changes where the trim whitespace is different
        // Note that we are looping starting at -1 to also cover the lines before the first change
        const result = [];
        let originalLineIndex = 0;
        let modifiedLineIndex = 0;
        for (let i = -1 /* !!!! */, len = rawChanges.length; i < len; i++) {
            const nextChange = (i + 1 < len ? rawChanges[i + 1] : null);
            const originalStop = (nextChange ? nextChange.originalStart : this.originalLines.length);
            const modifiedStop = (nextChange ? nextChange.modifiedStart : this.modifiedLines.length);
            while (originalLineIndex < originalStop && modifiedLineIndex < modifiedStop) {
                const originalLine = this.originalLines[originalLineIndex];
                const modifiedLine = this.modifiedLines[modifiedLineIndex];
                if (originalLine !== modifiedLine) {
                    // These lines differ only in trim whitespace
                    // Check the leading whitespace
                    {
                        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._pushTrimWhitespaceCharChange(result, originalLineIndex + 1, 1, originalStartColumn, modifiedLineIndex + 1, 1, modifiedStartColumn);
                        }
                    }
                    // Check the trailing whitespace
                    {
                        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._pushTrimWhitespaceCharChange(result, originalLineIndex + 1, originalEndColumn, originalMaxColumn, modifiedLineIndex + 1, modifiedEndColumn, modifiedMaxColumn);
                        }
                    }
                }
                originalLineIndex++;
                modifiedLineIndex++;
            }
            if (nextChange) {
                // Emit the actual change
                result.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, nextChange, this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
                originalLineIndex += nextChange.originalLength;
                modifiedLineIndex += nextChange.modifiedLength;
            }
        }
        return {
            quitEarly: quitEarly,
            changes: result
        };
    }
    _pushTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
        if (this._mergeTrimWhitespaceCharChange(result, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn)) {
            // Merged into previous
            return;
        }
        let charChanges = undefined;
        if (this.shouldComputeCharChanges) {
            charChanges = [new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn)];
        }
        result.push(new LineChange(originalLineNumber, originalLineNumber, modifiedLineNumber, modifiedLineNumber, charChanges));
    }
    _mergeTrimWhitespaceCharChange(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) {
            // Don't merge with inserts/deletes
            return false;
        }
        if (prevChange.originalEndLineNumber + 1 === originalLineNumber && prevChange.modifiedEndLineNumber + 1 === modifiedLineNumber) {
            prevChange.originalEndLineNumber = originalLineNumber;
            prevChange.modifiedEndLineNumber = modifiedLineNumber;
            if (this.shouldComputeCharChanges && prevChange.charChanges) {
                prevChange.charChanges.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn));
            }
            return true;
        }
        return false;
    }
}
function getFirstNonBlankColumn(txt, defaultValue) {
    const r = strings_firstNonWhitespaceIndex(txt);
    if (r === -1) {
        return defaultValue;
    }
    return r + 1;
}
function getLastNonBlankColumn(txt, defaultValue) {
    const r = strings_lastNonWhitespaceIndex(txt);
    if (r === -1) {
        return defaultValue;
    }
    return r + 2;
}
function createContinueProcessingPredicate(maximumRuntime) {
    if (maximumRuntime === 0) {
        return () => true;
    }
    const startTime = Date.now();
    return () => {
        return Date.now() - startTime < maximumRuntime;
    };
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/model/mirrorTextModel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class MirrorTextModel {
    constructor(uri, lines, eol, versionId) {
        this._uri = uri;
        this._lines = lines;
        this._eol = eol;
        this._versionId = versionId;
        this._lineStarts = null;
        this._cachedTextValue = null;
    }
    dispose() {
        this._lines.length = 0;
    }
    get version() {
        return this._versionId;
    }
    getText() {
        if (this._cachedTextValue === null) {
            this._cachedTextValue = this._lines.join(this._eol);
        }
        return this._cachedTextValue;
    }
    onEvents(e) {
        if (e.eol && e.eol !== this._eol) {
            this._eol = e.eol;
            this._lineStarts = null;
        }
        // Update my lines
        const changes = e.changes;
        for (const change of changes) {
            this._acceptDeleteRange(change.range);
            this._acceptInsertText(new Position(change.range.startLineNumber, change.range.startColumn), change.text);
        }
        this._versionId = e.versionId;
        this._cachedTextValue = null;
    }
    _ensureLineStarts() {
        if (!this._lineStarts) {
            const eolLength = this._eol.length;
            const linesLength = this._lines.length;
            const lineStartValues = new Uint32Array(linesLength);
            for (let i = 0; i < linesLength; i++) {
                lineStartValues[i] = this._lines[i].length + eolLength;
            }
            this._lineStarts = new PrefixSumComputer(lineStartValues);
        }
    }
    /**
     * All changes to a line's text go through this method
     */
    _setLineText(lineIndex, newValue) {
        this._lines[lineIndex] = newValue;
        if (this._lineStarts) {
            // update prefix sum
            this._lineStarts.setValue(lineIndex, this._lines[lineIndex].length + this._eol.length);
        }
    }
    _acceptDeleteRange(range) {
        if (range.startLineNumber === range.endLineNumber) {
            if (range.startColumn === range.endColumn) {
                // Nothing to delete
                return;
            }
            // Delete text on the affected line
            this._setLineText(range.startLineNumber - 1, this._lines[range.startLineNumber - 1].substring(0, range.startColumn - 1)
                + this._lines[range.startLineNumber - 1].substring(range.endColumn - 1));
            return;
        }
        // Take remaining text on last line and append it to remaining text on first line
        this._setLineText(range.startLineNumber - 1, this._lines[range.startLineNumber - 1].substring(0, range.startColumn - 1)
            + this._lines[range.endLineNumber - 1].substring(range.endColumn - 1));
        // Delete middle lines
        this._lines.splice(range.startLineNumber, range.endLineNumber - range.startLineNumber);
        if (this._lineStarts) {
            // update prefix sum
            this._lineStarts.removeValues(range.startLineNumber, range.endLineNumber - range.startLineNumber);
        }
    }
    _acceptInsertText(position, insertText) {
        if (insertText.length === 0) {
            // Nothing to insert
            return;
        }
        const insertLines = splitLines(insertText);
        if (insertLines.length === 1) {
            // Inserting text on one line
            this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1)
                + insertLines[0]
                + this._lines[position.lineNumber - 1].substring(position.column - 1));
            return;
        }
        // Append overflowing text from first line to the end of text to insert
        insertLines[insertLines.length - 1] += this._lines[position.lineNumber - 1].substring(position.column - 1);
        // Delete overflowing text from first line and insert text on first line
        this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1)
            + insertLines[0]);
        // Insert new lines & store lengths
        const newLengths = new Uint32Array(insertLines.length - 1);
        for (let i = 1; i < insertLines.length; i++) {
            this._lines.splice(position.lineNumber + i - 1, 0, insertLines[i]);
            newLengths[i - 1] = insertLines[i].length + this._eol.length;
        }
        if (this._lineStarts) {
            // update prefix sum
            this._lineStarts.insertValues(position.lineNumber, newLengths);
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/linkComputer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class Uint8Matrix {
    constructor(rows, cols, defaultValue) {
        const data = new Uint8Array(rows * cols);
        for (let i = 0, len = rows * cols; i < len; i++) {
            data[i] = defaultValue;
        }
        this._data = data;
        this.rows = rows;
        this.cols = cols;
    }
    get(row, col) {
        return this._data[row * this.cols + col];
    }
    set(row, col, value) {
        this._data[row * this.cols + col] = value;
    }
}
class StateMachine {
    constructor(edges) {
        let maxCharCode = 0;
        let maxState = 0 /* State.Invalid */;
        for (let i = 0, len = edges.length; i < len; i++) {
            const [from, chCode, to] = edges[i];
            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 i = 0, len = edges.length; i < len; i++) {
            const [from, chCode, to] = edges[i];
            states.set(from, chCode, to);
        }
        this._states = states;
        this._maxCharCode = maxCharCode;
    }
    nextState(currentState, chCode) {
        if (chCode < 0 || chCode >= this._maxCharCode) {
            return 0 /* State.Invalid */;
        }
        return this._states.get(currentState, chCode);
    }
}
// State machine for http:// or https:// or file://
let _stateMachine = null;
function getStateMachine() {
    if (_stateMachine === null) {
        _stateMachine = new StateMachine([
            [1 /* State.Start */, 104 /* CharCode.h */, 2 /* State.H */],
            [1 /* State.Start */, 72 /* CharCode.H */, 2 /* State.H */],
            [1 /* State.Start */, 102 /* CharCode.f */, 6 /* State.F */],
            [1 /* State.Start */, 70 /* CharCode.F */, 6 /* State.F */],
            [2 /* State.H */, 116 /* CharCode.t */, 3 /* State.HT */],
            [2 /* State.H */, 84 /* CharCode.T */, 3 /* State.HT */],
            [3 /* State.HT */, 116 /* CharCode.t */, 4 /* State.HTT */],
            [3 /* State.HT */, 84 /* CharCode.T */, 4 /* State.HTT */],
            [4 /* State.HTT */, 112 /* CharCode.p */, 5 /* State.HTTP */],
            [4 /* State.HTT */, 80 /* CharCode.P */, 5 /* State.HTTP */],
            [5 /* State.HTTP */, 115 /* CharCode.s */, 9 /* State.BeforeColon */],
            [5 /* State.HTTP */, 83 /* CharCode.S */, 9 /* State.BeforeColon */],
            [5 /* State.HTTP */, 58 /* CharCode.Colon */, 10 /* State.AfterColon */],
            [6 /* State.F */, 105 /* CharCode.i */, 7 /* State.FI */],
            [6 /* State.F */, 73 /* CharCode.I */, 7 /* State.FI */],
            [7 /* State.FI */, 108 /* CharCode.l */, 8 /* State.FIL */],
            [7 /* State.FI */, 76 /* CharCode.L */, 8 /* State.FIL */],
            [8 /* State.FIL */, 101 /* CharCode.e */, 9 /* State.BeforeColon */],
            [8 /* State.FIL */, 69 /* CharCode.E */, 9 /* State.BeforeColon */],
            [9 /* State.BeforeColon */, 58 /* CharCode.Colon */, 10 /* State.AfterColon */],
            [10 /* State.AfterColon */, 47 /* CharCode.Slash */, 11 /* State.AlmostThere */],
            [11 /* State.AlmostThere */, 47 /* CharCode.Slash */, 12 /* State.End */],
        ]);
    }
    return _stateMachine;
}
let _classifier = null;
function getClassifier() {
    if (_classifier === null) {
        _classifier = new CharacterClassifier(0 /* CharacterClass.None */);
        // allow-any-unicode-next-line
        const FORCE_TERMINATION_CHARACTERS = ' \t<>\'\"、。｡､，．：；‘〈「『〔（［｛｢｣｝］）〕』」〉’｀～…';
        for (let i = 0; i < FORCE_TERMINATION_CHARACTERS.length; i++) {
            _classifier.set(FORCE_TERMINATION_CHARACTERS.charCodeAt(i), 1 /* CharacterClass.ForceTermination */);
        }
        const CANNOT_END_WITH_CHARACTERS = '.,;:';
        for (let i = 0; i < CANNOT_END_WITH_CHARACTERS.length; i++) {
            _classifier.set(CANNOT_END_WITH_CHARACTERS.charCodeAt(i), 2 /* CharacterClass.CannotEndIn */);
        }
    }
    return _classifier;
}
class LinkComputer {
    static _createLink(classifier, line, lineNumber, linkBeginIndex, linkEndIndex) {
        // Do not allow to end link in certain characters...
        let lastIncludedCharIndex = linkEndIndex - 1;
        do {
            const chCode = line.charCodeAt(lastIncludedCharIndex);
            const chClass = classifier.get(chCode);
            if (chClass !== 2 /* CharacterClass.CannotEndIn */) {
                break;
            }
            lastIncludedCharIndex--;
        } while (lastIncludedCharIndex > linkBeginIndex);
        // Handle links enclosed in parens, square brackets and curlys.
        if (linkBeginIndex > 0) {
            const charCodeBeforeLink = line.charCodeAt(linkBeginIndex - 1);
            const lastCharCodeInLink = line.charCodeAt(lastIncludedCharIndex);
            if ((charCodeBeforeLink === 40 /* CharCode.OpenParen */ && lastCharCodeInLink === 41 /* CharCode.CloseParen */)
                || (charCodeBeforeLink === 91 /* CharCode.OpenSquareBracket */ && lastCharCodeInLink === 93 /* CharCode.CloseSquareBracket */)
                || (charCodeBeforeLink === 123 /* CharCode.OpenCurlyBrace */ && lastCharCodeInLink === 125 /* CharCode.CloseCurlyBrace */)) {
                // Do not end in ) if ( is before the link start
                // Do not end in ] if [ is before the link start
                // Do not end in } if { is before the link start
                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 i = 1, lineCount = model.getLineCount(); i <= lineCount; i++) {
            const line = model.getLineContent(i);
            const len = line.length;
            let j = 0;
            let linkBeginIndex = 0;
            let linkBeginChCode = 0;
            let state = 1 /* State.Start */;
            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 /* State.Accept */) {
                    let chClass;
                    switch (chCode) {
                        case 40 /* CharCode.OpenParen */:
                            hasOpenParens = true;
                            chClass = 0 /* CharacterClass.None */;
                            break;
                        case 41 /* CharCode.CloseParen */:
                            chClass = (hasOpenParens ? 0 /* CharacterClass.None */ : 1 /* CharacterClass.ForceTermination */);
                            break;
                        case 91 /* CharCode.OpenSquareBracket */:
                            inSquareBrackets = true;
                            hasOpenSquareBracket = true;
                            chClass = 0 /* CharacterClass.None */;
                            break;
                        case 93 /* CharCode.CloseSquareBracket */:
                            inSquareBrackets = false;
                            chClass = (hasOpenSquareBracket ? 0 /* CharacterClass.None */ : 1 /* CharacterClass.ForceTermination */);
                            break;
                        case 123 /* CharCode.OpenCurlyBrace */:
                            hasOpenCurlyBracket = true;
                            chClass = 0 /* CharacterClass.None */;
                            break;
                        case 125 /* CharCode.CloseCurlyBrace */:
                            chClass = (hasOpenCurlyBracket ? 0 /* CharacterClass.None */ : 1 /* CharacterClass.ForceTermination */);
                            break;
                        /* The following three rules make it that ' or " or ` are allowed inside links if the link didn't begin with them */
                        case 39 /* CharCode.SingleQuote */:
                            chClass = (linkBeginChCode === 39 /* CharCode.SingleQuote */ ? 1 /* CharacterClass.ForceTermination */ : 0 /* CharacterClass.None */);
                            break;
                        case 34 /* CharCode.DoubleQuote */:
                            chClass = (linkBeginChCode === 34 /* CharCode.DoubleQuote */ ? 1 /* CharacterClass.ForceTermination */ : 0 /* CharacterClass.None */);
                            break;
                        case 96 /* CharCode.BackTick */:
                            chClass = (linkBeginChCode === 96 /* CharCode.BackTick */ ? 1 /* CharacterClass.ForceTermination */ : 0 /* CharacterClass.None */);
                            break;
                        case 42 /* CharCode.Asterisk */:
                            // `*` terminates a link if the link began with `*`
                            chClass = (linkBeginChCode === 42 /* CharCode.Asterisk */) ? 1 /* CharacterClass.ForceTermination */ : 0 /* CharacterClass.None */;
                            break;
                        case 124 /* CharCode.Pipe */:
                            // `|` terminates a link if the link began with `|`
                            chClass = (linkBeginChCode === 124 /* CharCode.Pipe */) ? 1 /* CharacterClass.ForceTermination */ : 0 /* CharacterClass.None */;
                            break;
                        case 32 /* CharCode.Space */:
                            // ` ` allow space in between [ and ]
                            chClass = (inSquareBrackets ? 0 /* CharacterClass.None */ : 1 /* CharacterClass.ForceTermination */);
                            break;
                        default:
                            chClass = classifier.get(chCode);
                    }
                    // Check if character terminates link
                    if (chClass === 1 /* CharacterClass.ForceTermination */) {
                        result.push(LinkComputer._createLink(classifier, line, i, linkBeginIndex, j));
                        resetStateMachine = true;
                    }
                }
                else if (state === 12 /* State.End */) {
                    let chClass;
                    if (chCode === 91 /* CharCode.OpenSquareBracket */) {
                        // Allow for the authority part to contain ipv6 addresses which contain [ and ]
                        hasOpenSquareBracket = true;
                        chClass = 0 /* CharacterClass.None */;
                    }
                    else {
                        chClass = classifier.get(chCode);
                    }
                    // Check if character terminates link
                    if (chClass === 1 /* CharacterClass.ForceTermination */) {
                        resetStateMachine = true;
                    }
                    else {
                        state = 13 /* State.Accept */;
                    }
                }
                else {
                    state = stateMachine.nextState(state, chCode);
                    if (state === 0 /* State.Invalid */) {
                        resetStateMachine = true;
                    }
                }
                if (resetStateMachine) {
                    state = 1 /* State.Start */;
                    hasOpenParens = false;
                    hasOpenSquareBracket = false;
                    hasOpenCurlyBracket = false;
                    // Record where the link started
                    linkBeginIndex = j + 1;
                    linkBeginChCode = chCode;
                }
                j++;
            }
            if (state === 13 /* State.Accept */) {
                result.push(LinkComputer._createLink(classifier, line, i, linkBeginIndex, len));
            }
        }
        return result;
    }
}
/**
 * Returns an array of all links contains in the provided
 * document. *Note* that this operation is computational
 * expensive and should not run in the UI thread.
 */
function computeLinks(model) {
    if (!model || typeof model.getLineCount !== 'function' || typeof model.getLineContent !== 'function') {
        // Unknown caller!
        return [];
    }
    return LinkComputer.computeLinks(model);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languages/supports/inplaceReplaceSupport.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class BasicInplaceReplace {
    constructor() {
        this._defaultValueSet = [
            ['true', 'false'],
            ['True', 'False'],
            ['Private', 'Public', 'Friend', 'ReadOnly', 'Partial', 'Protected', 'WriteOnly'],
            ['public', 'protected', 'private'],
        ];
    }
    navigateValueSet(range1, text1, range2, text2, up) {
        if (range1 && text1) {
            const result = this.doNavigateValueSet(text1, up);
            if (result) {
                return {
                    range: range1,
                    value: result
                };
            }
        }
        if (range2 && text2) {
            const result = this.doNavigateValueSet(text2, up);
            if (result) {
                return {
                    range: range2,
                    value: result
                };
            }
        }
        return null;
    }
    doNavigateValueSet(text, up) {
        const numberResult = this.numberReplace(text, up);
        if (numberResult !== null) {
            return numberResult;
        }
        return this.textReplace(text, up);
    }
    numberReplace(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; // don't do negative
                //			} else if(n1 === 9 && up) {
                //				return null; // don't insert 10 into a number
            }
            else {
                n1 = Math.floor(n1 * precision);
                n1 += up ? precision : -precision;
                return String(n1 / precision);
            }
        }
        return null;
    }
    textReplace(value, up) {
        return this.valueSetsReplace(this._defaultValueSet, value, up);
    }
    valueSetsReplace(valueSets, value, up) {
        let result = null;
        for (let i = 0, len = valueSets.length; result === null && i < len; i++) {
            result = this.valueSetReplace(valueSets[i], value, up);
        }
        return result;
    }
    valueSetReplace(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;
    }
}
BasicInplaceReplace.INSTANCE = new BasicInplaceReplace();

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/editorSimpleWorker.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var editorSimpleWorker_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};














/**
 * @internal
 */
class MirrorModel extends MirrorTextModel {
    get uri() {
        return this._uri;
    }
    get eol() {
        return this._eol;
    }
    getValue() {
        return this.getText();
    }
    getLinesContent() {
        return this._lines.slice(0);
    }
    getLineCount() {
        return this._lines.length;
    }
    getLineContent(lineNumber) {
        return this._lines[lineNumber - 1];
    }
    getWordAtPosition(position, wordDefinition) {
        const wordAtText = getWordAtText(position.column, ensureValidWordDefinition(wordDefinition), this._lines[position.lineNumber - 1], 0);
        if (wordAtText) {
            return new Range(position.lineNumber, wordAtText.startColumn, position.lineNumber, wordAtText.endColumn);
        }
        return null;
    }
    words(wordDefinition) {
        const lines = this._lines;
        const wordenize = this._wordenize.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._lines[lineNumber - 1];
        const ranges = this._wordenize(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;
    }
    _wordenize(content, wordDefinition) {
        const result = [];
        let match;
        wordDefinition.lastIndex = 0; // reset lastIndex just to be sure
        while (match = wordDefinition.exec(content)) {
            if (match[0].length === 0) {
                // it did match the empty string
                break;
            }
            result.push({ start: match.index, end: match.index + match[0].length });
        }
        return result;
    }
    getValueInRange(range) {
        range = this._validateRange(range);
        if (range.startLineNumber === range.endLineNumber) {
            return this._lines[range.startLineNumber - 1].substring(range.startColumn - 1, range.endColumn - 1);
        }
        const lineEnding = this._eol;
        const startLineIndex = range.startLineNumber - 1;
        const endLineIndex = range.endLineNumber - 1;
        const resultLines = [];
        resultLines.push(this._lines[startLineIndex].substring(range.startColumn - 1));
        for (let i = startLineIndex + 1; i < endLineIndex; i++) {
            resultLines.push(this._lines[i]);
        }
        resultLines.push(this._lines[endLineIndex].substring(0, range.endColumn - 1));
        return resultLines.join(lineEnding);
    }
    offsetAt(position) {
        position = this._validatePosition(position);
        this._ensureLineStarts();
        return this._lineStarts.getPrefixSum(position.lineNumber - 2) + (position.column - 1);
    }
    positionAt(offset) {
        offset = Math.floor(offset);
        offset = Math.max(0, offset);
        this._ensureLineStarts();
        const out = this._lineStarts.getIndexOf(offset);
        const lineLength = this._lines[out.index].length;
        // Ensure we return a valid position
        return {
            lineNumber: 1 + out.index,
            column: 1 + Math.min(out.remainder, lineLength)
        };
    }
    _validateRange(range) {
        const start = this._validatePosition({ lineNumber: range.startLineNumber, column: range.startColumn });
        const end = this._validatePosition({ 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;
    }
    _validatePosition(position) {
        if (!Position.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._lines.length) {
            lineNumber = this._lines.length;
            column = this._lines[lineNumber - 1].length + 1;
            hasChanged = true;
        }
        else {
            const maxCharacter = this._lines[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 };
        }
    }
}
/**
 * @internal
 */
class EditorSimpleWorker {
    constructor(host, foreignModuleFactory) {
        this._host = host;
        this._models = Object.create(null);
        this._foreignModuleFactory = foreignModuleFactory;
        this._foreignModule = null;
    }
    dispose() {
        this._models = Object.create(null);
    }
    _getModel(uri) {
        return this._models[uri];
    }
    _getModels() {
        const all = [];
        Object.keys(this._models).forEach((key) => all.push(this._models[key]));
        return all;
    }
    acceptNewModel(data) {
        this._models[data.url] = new MirrorModel(URI.parse(data.url), data.lines, data.EOL, data.versionId);
    }
    acceptModelChanged(strURL, e) {
        if (!this._models[strURL]) {
            return;
        }
        const model = this._models[strURL];
        model.onEvents(e);
    }
    acceptRemovedModel(strURL) {
        if (!this._models[strURL]) {
            return;
        }
        delete this._models[strURL];
    }
    computeUnicodeHighlights(url, options, range) {
        return editorSimpleWorker_awaiter(this, void 0, void 0, function* () {
            const model = this._getModel(url);
            if (!model) {
                return { ranges: [], hasMore: false, ambiguousCharacterCount: 0, invisibleCharacterCount: 0, nonBasicAsciiCharacterCount: 0 };
            }
            return UnicodeTextModelHighlighter.computeUnicodeHighlights(model, options, range);
        });
    }
    // ---- BEGIN diff --------------------------------------------------------------------------
    computeDiff(originalUrl, modifiedUrl, ignoreTrimWhitespace, maxComputationTime) {
        return editorSimpleWorker_awaiter(this, void 0, void 0, function* () {
            const original = this._getModel(originalUrl);
            const modified = this._getModel(modifiedUrl);
            if (!original || !modified) {
                return null;
            }
            return EditorSimpleWorker.computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime);
        });
    }
    static computeDiff(originalTextModel, modifiedTextModel, ignoreTrimWhitespace, maxComputationTime) {
        const originalLines = originalTextModel.getLinesContent();
        const modifiedLines = modifiedTextModel.getLinesContent();
        const diffComputer = new DiffComputer(originalLines, modifiedLines, {
            shouldComputeCharChanges: true,
            shouldPostProcessCharChanges: true,
            shouldIgnoreTrimWhitespace: ignoreTrimWhitespace,
            shouldMakePrettyDiff: true,
            maxComputationTime: maxComputationTime
        });
        const diffResult = diffComputer.computeDiff();
        const identical = (diffResult.changes.length > 0 ? false : this._modelsAreIdentical(originalTextModel, modifiedTextModel));
        return {
            quitEarly: diffResult.quitEarly,
            identical: identical,
            changes: diffResult.changes
        };
    }
    static _modelsAreIdentical(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;
    }
    computeMoreMinimalEdits(modelUrl, edits) {
        return editorSimpleWorker_awaiter(this, void 0, void 0, function* () {
            const model = this._getModel(modelUrl);
            if (!model) {
                return edits;
            }
            const result = [];
            let lastEol = undefined;
            edits = edits.slice(0).sort((a, b) => {
                if (a.range && b.range) {
                    return Range.compareRangesUsingStarts(a.range, b.range);
                }
                // eol only changes should go to the end
                const aRng = a.range ? 0 : 1;
                const bRng = b.range ? 0 : 1;
                return aRng - bRng;
            });
            for (let { range, text, eol } of edits) {
                if (typeof eol === 'number') {
                    lastEol = eol;
                }
                if (Range.isEmpty(range) && !text) {
                    // empty change
                    continue;
                }
                const original = model.getValueInRange(range);
                text = text.replace(/\r\n|\n|\r/g, model.eol);
                if (original === text) {
                    // noop
                    continue;
                }
                // make sure diff won't take too long
                if (Math.max(text.length, original.length) > EditorSimpleWorker._diffLimit) {
                    result.push({ range, text });
                    continue;
                }
                // compute diff between original and edit.text
                const changes = stringDiff(original, text, false);
                const editOffset = model.offsetAt(Range.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: text.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;
        });
    }
    // ---- END minimal edits ---------------------------------------------------------------
    computeLinks(modelUrl) {
        return editorSimpleWorker_awaiter(this, void 0, void 0, function* () {
            const model = this._getModel(modelUrl);
            if (!model) {
                return null;
            }
            return computeLinks(model);
        });
    }
    textualSuggest(modelUrls, leadingWord, wordDef, wordDefFlags) {
        return editorSimpleWorker_awaiter(this, void 0, void 0, function* () {
            const sw = new StopWatch(true);
            const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
            const seen = new Set();
            outer: for (const url of modelUrls) {
                const model = this._getModel(url);
                if (!model) {
                    continue;
                }
                for (const word of model.words(wordDefRegExp)) {
                    if (word === leadingWord || !isNaN(Number(word))) {
                        continue;
                    }
                    seen.add(word);
                    if (seen.size > EditorSimpleWorker._suggestionsLimit) {
                        break outer;
                    }
                }
            }
            return { words: Array.from(seen), duration: sw.elapsed() };
        });
    }
    // ---- END suggest --------------------------------------------------------------------------
    //#region -- word ranges --
    computeWordRanges(modelUrl, range, wordDef, wordDefFlags) {
        return editorSimpleWorker_awaiter(this, void 0, void 0, function* () {
            const model = this._getModel(modelUrl);
            if (!model) {
                return Object.create(null);
            }
            const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
            const result = 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 array = result[word.word];
                    if (!array) {
                        array = [];
                        result[word.word] = array;
                    }
                    array.push({
                        startLineNumber: line,
                        startColumn: word.startColumn,
                        endLineNumber: line,
                        endColumn: word.endColumn
                    });
                }
            }
            return result;
        });
    }
    //#endregion
    navigateValueSet(modelUrl, range, up, wordDef, wordDefFlags) {
        return editorSimpleWorker_awaiter(this, void 0, void 0, function* () {
            const model = this._getModel(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 = BasicInplaceReplace.INSTANCE.navigateValueSet(range, selectionText, wordRange, word, up);
            return result;
        });
    }
    // ---- BEGIN foreign module support --------------------------------------------------------------------------
    loadForeignModule(moduleId, createData, foreignHostMethods) {
        const proxyMethodRequest = (method, args) => {
            return this._host.fhr(method, args);
        };
        const foreignHost = createProxyObject(foreignHostMethods, proxyMethodRequest);
        const ctx = {
            host: foreignHost,
            getMirrorModels: () => {
                return this._getModels();
            }
        };
        if (this._foreignModuleFactory) {
            this._foreignModule = this._foreignModuleFactory(ctx, createData);
            // static foreing module
            return Promise.resolve(getAllMethodNames(this._foreignModule));
        }
        // ESM-comment-begin
        // 		return new Promise<any>((resolve, reject) => {
        // 			require([moduleId], (foreignModule: { create: IForeignModuleFactory }) => {
        // 				this._foreignModule = foreignModule.create(ctx, createData);
        // 
        // 				resolve(types.getAllMethodNames(this._foreignModule));
        // 
        // 			}, reject);
        // 		});
        // ESM-comment-end
        // ESM-uncomment-begin
        return Promise.reject(new Error(`Unexpected usage`));
        // ESM-uncomment-end
    }
    // foreign method request
    fmr(method, args) {
        if (!this._foreignModule || typeof this._foreignModule[method] !== 'function') {
            return Promise.reject(new Error('Missing requestHandler or method: ' + method));
        }
        try {
            return Promise.resolve(this._foreignModule[method].apply(this._foreignModule, args));
        }
        catch (e) {
            return Promise.reject(e);
        }
    }
}
// ---- END diff --------------------------------------------------------------------------
// ---- BEGIN minimal edits ---------------------------------------------------------------
EditorSimpleWorker._diffLimit = 100000;
// ---- BEGIN suggest --------------------------------------------------------------------------
EditorSimpleWorker._suggestionsLimit = 10000;
/**
 * Called on the worker side
 * @internal
 */
function editorSimpleWorker_create(host) {
    return new EditorSimpleWorker(host, null);
}
if (typeof importScripts === 'function') {
    // Running in a web worker
    platform_globals.monaco = createMonacoBaseAPI();
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/services/editorWorkerService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var editorWorkerService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var editorWorkerService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var editorWorkerService_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};















/**
 * Stop syncing a model to the worker if it was not needed for 1 min.
 */
const STOP_SYNC_MODEL_DELTA_TIME_MS = 60 * 1000;
/**
 * Stop the worker if it was not needed for 5 min.
 */
const STOP_WORKER_DELTA_TIME_MS = 5 * 60 * 1000;
function canSyncModel(modelService, resource) {
    const model = modelService.getModel(resource);
    if (!model) {
        return false;
    }
    if (model.isTooLargeForSyncing()) {
        return false;
    }
    return true;
}
let EditorWorkerService = class EditorWorkerService extends Disposable {
    constructor(modelService, configurationService, logService, languageConfigurationService, languageFeaturesService) {
        super();
        this._modelService = modelService;
        this._workerManager = this._register(new WorkerManager(this._modelService, languageConfigurationService));
        this._logService = logService;
        // register default link-provider and default completions-provider
        this._register(languageFeaturesService.linkProvider.register({ language: '*', hasAccessToAllModels: true }, {
            provideLinks: (model, token) => {
                if (!canSyncModel(this._modelService, model.uri)) {
                    return Promise.resolve({ links: [] }); // File too large
                }
                return this._workerManager.withWorker().then(client => client.computeLinks(model.uri)).then(links => {
                    return links && { links };
                });
            }
        }));
        this._register(languageFeaturesService.completionProvider.register('*', new WordBasedCompletionItemProvider(this._workerManager, configurationService, this._modelService, languageConfigurationService)));
    }
    dispose() {
        super.dispose();
    }
    canComputeUnicodeHighlights(uri) {
        return canSyncModel(this._modelService, uri);
    }
    computedUnicodeHighlights(uri, options, range) {
        return this._workerManager.withWorker().then(client => client.computedUnicodeHighlights(uri, options, range));
    }
    computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime) {
        return this._workerManager.withWorker().then(client => client.computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime));
    }
    computeMoreMinimalEdits(resource, edits) {
        if (isNonEmptyArray(edits)) {
            if (!canSyncModel(this._modelService, resource)) {
                return Promise.resolve(edits); // File too large
            }
            const sw = StopWatch.create(true);
            const result = this._workerManager.withWorker().then(client => client.computeMoreMinimalEdits(resource, edits));
            result.finally(() => this._logService.trace('FORMAT#computeMoreMinimalEdits', resource.toString(true), sw.elapsed()));
            return Promise.race([result, timeout(1000).then(() => edits)]);
        }
        else {
            return Promise.resolve(undefined);
        }
    }
    canNavigateValueSet(resource) {
        return (canSyncModel(this._modelService, resource));
    }
    navigateValueSet(resource, range, up) {
        return this._workerManager.withWorker().then(client => client.navigateValueSet(resource, range, up));
    }
    canComputeWordRanges(resource) {
        return canSyncModel(this._modelService, resource);
    }
    computeWordRanges(resource, range) {
        return this._workerManager.withWorker().then(client => client.computeWordRanges(resource, range));
    }
};
EditorWorkerService = editorWorkerService_decorate([
    editorWorkerService_param(0, IModelService),
    editorWorkerService_param(1, ITextResourceConfigurationService),
    editorWorkerService_param(2, ILogService),
    editorWorkerService_param(3, ILanguageConfigurationService),
    editorWorkerService_param(4, ILanguageFeaturesService)
], EditorWorkerService);

class WordBasedCompletionItemProvider {
    constructor(workerManager, configurationService, modelService, languageConfigurationService) {
        this.languageConfigurationService = languageConfigurationService;
        this._debugDisplayName = 'wordbasedCompletions';
        this._workerManager = workerManager;
        this._configurationService = configurationService;
        this._modelService = modelService;
    }
    provideCompletionItems(model, position) {
        return editorWorkerService_awaiter(this, void 0, void 0, function* () {
            const config = this._configurationService.getValue(model.uri, position, 'editor');
            if (!config.wordBasedSuggestions) {
                return undefined;
            }
            const models = [];
            if (config.wordBasedSuggestionsMode === 'currentDocument') {
                // only current file and only if not too large
                if (canSyncModel(this._modelService, model.uri)) {
                    models.push(model.uri);
                }
            }
            else {
                // either all files or files of same language
                for (const candidate of this._modelService.getModels()) {
                    if (!canSyncModel(this._modelService, candidate.uri)) {
                        continue;
                    }
                    if (candidate === model) {
                        models.unshift(candidate.uri);
                    }
                    else if (config.wordBasedSuggestionsMode === 'allDocuments' || candidate.getLanguageId() === model.getLanguageId()) {
                        models.push(candidate.uri);
                    }
                }
            }
            if (models.length === 0) {
                return undefined; // File too large, no other files
            }
            const wordDefRegExp = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
            const word = model.getWordAtPosition(position);
            const replace = !word ? Range.fromPositions(position) : new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
            const insert = replace.setEndPosition(position.lineNumber, position.column);
            const client = yield this._workerManager.withWorker();
            const data = yield client.textualSuggest(models, word === null || word === void 0 ? void 0 : word.word, wordDefRegExp);
            if (!data) {
                return undefined;
            }
            return {
                duration: data.duration,
                suggestions: data.words.map((word) => {
                    return {
                        kind: 18 /* languages.CompletionItemKind.Text */,
                        label: word,
                        insertText: word,
                        range: { insert, replace }
                    };
                }),
            };
        });
    }
}
class WorkerManager extends Disposable {
    constructor(modelService, languageConfigurationService) {
        super();
        this.languageConfigurationService = languageConfigurationService;
        this._modelService = modelService;
        this._editorWorkerClient = null;
        this._lastWorkerUsedTime = (new Date()).getTime();
        const stopWorkerInterval = this._register(new IntervalTimer());
        stopWorkerInterval.cancelAndSet(() => this._checkStopIdleWorker(), Math.round(STOP_WORKER_DELTA_TIME_MS / 2));
        this._register(this._modelService.onModelRemoved(_ => this._checkStopEmptyWorker()));
    }
    dispose() {
        if (this._editorWorkerClient) {
            this._editorWorkerClient.dispose();
            this._editorWorkerClient = null;
        }
        super.dispose();
    }
    /**
     * Check if the model service has no more models and stop the worker if that is the case.
     */
    _checkStopEmptyWorker() {
        if (!this._editorWorkerClient) {
            return;
        }
        const models = this._modelService.getModels();
        if (models.length === 0) {
            // There are no more models => nothing possible for me to do
            this._editorWorkerClient.dispose();
            this._editorWorkerClient = null;
        }
    }
    /**
     * Check if the worker has been idle for a while and then stop it.
     */
    _checkStopIdleWorker() {
        if (!this._editorWorkerClient) {
            return;
        }
        const timeSinceLastWorkerUsedTime = (new Date()).getTime() - this._lastWorkerUsedTime;
        if (timeSinceLastWorkerUsedTime > STOP_WORKER_DELTA_TIME_MS) {
            this._editorWorkerClient.dispose();
            this._editorWorkerClient = null;
        }
    }
    withWorker() {
        this._lastWorkerUsedTime = (new Date()).getTime();
        if (!this._editorWorkerClient) {
            this._editorWorkerClient = new EditorWorkerClient(this._modelService, false, 'editorWorkerService', this.languageConfigurationService);
        }
        return Promise.resolve(this._editorWorkerClient);
    }
}
class EditorModelManager extends Disposable {
    constructor(proxy, modelService, keepIdleModels) {
        super();
        this._syncedModels = Object.create(null);
        this._syncedModelsLastUsedTime = Object.create(null);
        this._proxy = proxy;
        this._modelService = modelService;
        if (!keepIdleModels) {
            const timer = new IntervalTimer();
            timer.cancelAndSet(() => this._checkStopModelSync(), Math.round(STOP_SYNC_MODEL_DELTA_TIME_MS / 2));
            this._register(timer);
        }
    }
    dispose() {
        for (const modelUrl in this._syncedModels) {
            dispose(this._syncedModels[modelUrl]);
        }
        this._syncedModels = Object.create(null);
        this._syncedModelsLastUsedTime = Object.create(null);
        super.dispose();
    }
    ensureSyncedResources(resources, forceLargeModels) {
        for (const resource of resources) {
            const resourceStr = resource.toString();
            if (!this._syncedModels[resourceStr]) {
                this._beginModelSync(resource, forceLargeModels);
            }
            if (this._syncedModels[resourceStr]) {
                this._syncedModelsLastUsedTime[resourceStr] = (new Date()).getTime();
            }
        }
    }
    _checkStopModelSync() {
        const currentTime = (new Date()).getTime();
        const toRemove = [];
        for (const modelUrl in this._syncedModelsLastUsedTime) {
            const elapsedTime = currentTime - this._syncedModelsLastUsedTime[modelUrl];
            if (elapsedTime > STOP_SYNC_MODEL_DELTA_TIME_MS) {
                toRemove.push(modelUrl);
            }
        }
        for (const e of toRemove) {
            this._stopModelSync(e);
        }
    }
    _beginModelSync(resource, forceLargeModels) {
        const model = this._modelService.getModel(resource);
        if (!model) {
            return;
        }
        if (!forceLargeModels && model.isTooLargeForSyncing()) {
            return;
        }
        const modelUrl = resource.toString();
        this._proxy.acceptNewModel({
            url: model.uri.toString(),
            lines: model.getLinesContent(),
            EOL: model.getEOL(),
            versionId: model.getVersionId()
        });
        const toDispose = new DisposableStore();
        toDispose.add(model.onDidChangeContent((e) => {
            this._proxy.acceptModelChanged(modelUrl.toString(), e);
        }));
        toDispose.add(model.onWillDispose(() => {
            this._stopModelSync(modelUrl);
        }));
        toDispose.add(toDisposable(() => {
            this._proxy.acceptRemovedModel(modelUrl);
        }));
        this._syncedModels[modelUrl] = toDispose;
    }
    _stopModelSync(modelUrl) {
        const toDispose = this._syncedModels[modelUrl];
        delete this._syncedModels[modelUrl];
        delete this._syncedModelsLastUsedTime[modelUrl];
        dispose(toDispose);
    }
}
class SynchronousWorkerClient {
    constructor(instance) {
        this._instance = instance;
        this._proxyObj = Promise.resolve(this._instance);
    }
    dispose() {
        this._instance.dispose();
    }
    getProxyObject() {
        return this._proxyObj;
    }
}
class EditorWorkerHost {
    constructor(workerClient) {
        this._workerClient = workerClient;
    }
    // foreign host request
    fhr(method, args) {
        return this._workerClient.fhr(method, args);
    }
}
class EditorWorkerClient extends Disposable {
    constructor(modelService, keepIdleModels, label, languageConfigurationService) {
        super();
        this.languageConfigurationService = languageConfigurationService;
        this._disposed = false;
        this._modelService = modelService;
        this._keepIdleModels = keepIdleModels;
        this._workerFactory = new DefaultWorkerFactory(label);
        this._worker = null;
        this._modelManager = null;
    }
    // foreign host request
    fhr(method, args) {
        throw new Error(`Not implemented!`);
    }
    _getOrCreateWorker() {
        if (!this._worker) {
            try {
                this._worker = this._register(new SimpleWorkerClient(this._workerFactory, 'vs/editor/common/services/editorSimpleWorker', new EditorWorkerHost(this)));
            }
            catch (err) {
                logOnceWebWorkerWarning(err);
                this._worker = new SynchronousWorkerClient(new EditorSimpleWorker(new EditorWorkerHost(this), null));
            }
        }
        return this._worker;
    }
    _getProxy() {
        return this._getOrCreateWorker().getProxyObject().then(undefined, (err) => {
            logOnceWebWorkerWarning(err);
            this._worker = new SynchronousWorkerClient(new EditorSimpleWorker(new EditorWorkerHost(this), null));
            return this._getOrCreateWorker().getProxyObject();
        });
    }
    _getOrCreateModelManager(proxy) {
        if (!this._modelManager) {
            this._modelManager = this._register(new EditorModelManager(proxy, this._modelService, this._keepIdleModels));
        }
        return this._modelManager;
    }
    _withSyncedResources(resources, forceLargeModels = false) {
        return editorWorkerService_awaiter(this, void 0, void 0, function* () {
            if (this._disposed) {
                return Promise.reject(canceled());
            }
            return this._getProxy().then((proxy) => {
                this._getOrCreateModelManager(proxy).ensureSyncedResources(resources, forceLargeModels);
                return proxy;
            });
        });
    }
    computedUnicodeHighlights(uri, options, range) {
        return this._withSyncedResources([uri]).then(proxy => {
            return proxy.computeUnicodeHighlights(uri.toString(), options, range);
        });
    }
    computeDiff(original, modified, ignoreTrimWhitespace, maxComputationTime) {
        return this._withSyncedResources([original, modified], /* forceLargeModels */ true).then(proxy => {
            return proxy.computeDiff(original.toString(), modified.toString(), ignoreTrimWhitespace, maxComputationTime);
        });
    }
    computeMoreMinimalEdits(resource, edits) {
        return this._withSyncedResources([resource]).then(proxy => {
            return proxy.computeMoreMinimalEdits(resource.toString(), edits);
        });
    }
    computeLinks(resource) {
        return this._withSyncedResources([resource]).then(proxy => {
            return proxy.computeLinks(resource.toString());
        });
    }
    textualSuggest(resources, leadingWord, wordDefRegExp) {
        return editorWorkerService_awaiter(this, void 0, void 0, function* () {
            const proxy = yield this._withSyncedResources(resources);
            const wordDef = wordDefRegExp.source;
            const wordDefFlags = regExpFlags(wordDefRegExp);
            return proxy.textualSuggest(resources.map(r => r.toString()), leadingWord, wordDef, wordDefFlags);
        });
    }
    computeWordRanges(resource, range) {
        return this._withSyncedResources([resource]).then(proxy => {
            const model = this._modelService.getModel(resource);
            if (!model) {
                return Promise.resolve(null);
            }
            const wordDefRegExp = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
            const wordDef = wordDefRegExp.source;
            const wordDefFlags = regExpFlags(wordDefRegExp);
            return proxy.computeWordRanges(resource.toString(), range, wordDef, wordDefFlags);
        });
    }
    navigateValueSet(resource, range, up) {
        return this._withSyncedResources([resource]).then(proxy => {
            const model = this._modelService.getModel(resource);
            if (!model) {
                return null;
            }
            const wordDefRegExp = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
            const wordDef = wordDefRegExp.source;
            const wordDefFlags = regExpFlags(wordDefRegExp);
            return proxy.navigateValueSet(resource.toString(), range, up, wordDef, wordDefFlags);
        });
    }
    dispose() {
        super.dispose();
        this._disposed = true;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/services/webWorker.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


/**
 * Create a new web worker that has model syncing capabilities built in.
 * Specify an AMD module to load that will `create` an object that will be proxied.
 */
function createWebWorker(modelService, languageConfigurationService, opts) {
    return new MonacoWebWorkerImpl(modelService, languageConfigurationService, opts);
}
class MonacoWebWorkerImpl extends EditorWorkerClient {
    constructor(modelService, languageConfigurationService, opts) {
        super(modelService, opts.keepIdleModels || false, opts.label, languageConfigurationService);
        this._foreignModuleId = opts.moduleId;
        this._foreignModuleCreateData = opts.createData || null;
        this._foreignModuleHost = opts.host || null;
        this._foreignProxy = null;
    }
    // foreign host request
    fhr(method, args) {
        if (!this._foreignModuleHost || typeof this._foreignModuleHost[method] !== 'function') {
            return Promise.reject(new Error('Missing method ' + method + ' or missing main thread foreign host.'));
        }
        try {
            return Promise.resolve(this._foreignModuleHost[method].apply(this._foreignModuleHost, args));
        }
        catch (e) {
            return Promise.reject(e);
        }
    }
    _getForeignProxy() {
        if (!this._foreignProxy) {
            this._foreignProxy = this._getProxy().then((proxy) => {
                const foreignHostMethods = this._foreignModuleHost ? getAllMethodNames(this._foreignModuleHost) : [];
                return proxy.loadForeignModule(this._foreignModuleId, this._foreignModuleCreateData, foreignHostMethods).then((foreignMethods) => {
                    this._foreignModuleCreateData = null;
                    const proxyMethodRequest = (method, args) => {
                        return proxy.fmr(method, args);
                    };
                    const createProxyMethod = (method, proxyMethodRequest) => {
                        return function () {
                            const args = Array.prototype.slice.call(arguments, 0);
                            return proxyMethodRequest(method, args);
                        };
                    };
                    const foreignProxy = {};
                    for (const foreignMethod of foreignMethods) {
                        foreignProxy[foreignMethod] = createProxyMethod(foreignMethod, proxyMethodRequest);
                    }
                    return foreignProxy;
                });
            });
        }
        return this._foreignProxy;
    }
    getProxy() {
        return this._getForeignProxy();
    }
    withSyncedResources(resources) {
        return this._withSyncedResources(resources).then(_ => this.getProxy());
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/common/monarch/monarchCommon.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
function isFuzzyActionArr(what) {
    return (Array.isArray(what));
}
function isFuzzyAction(what) {
    return !isFuzzyActionArr(what);
}
function monarchCommon_isString(what) {
    return (typeof what === 'string');
}
function isIAction(what) {
    return !monarchCommon_isString(what);
}
// Small helper functions
/**
 * Is a string null, undefined, or empty?
 */
function empty(s) {
    return (s ? false : true);
}
/**
 * Puts a string to lower case if 'ignoreCase' is set.
 */
function fixCase(lexer, str) {
    return (lexer.ignoreCase && str ? str.toLowerCase() : str);
}
/**
 * Ensures there are no bad characters in a CSS token class.
 */
function monarchCommon_sanitize(s) {
    return s.replace(/[&<>'"_]/g, '-'); // used on all output token CSS classes
}
// Logging
/**
 * Logs a message.
 */
function log(lexer, msg) {
    console.log(`${lexer.languageId}: ${msg}`);
}
// Throwing errors
function createError(lexer, msg) {
    return new Error(`${lexer.languageId}: ${msg}`);
}
// Helper functions for rule finding and substitution
/**
 * substituteMatches is used on lexer strings and can substitutes predefined patterns:
 * 		$$  => $
 * 		$#  => id
 * 		$n  => matched entry n
 * 		@attr => contents of lexer[attr]
 *
 * See documentation for more info
 */
function substituteMatches(lexer, str, id, matches, state) {
    const re = /\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g;
    let stateMatches = null;
    return str.replace(re, function (full, sub, dollar, hash, n, s, attr, ofs, total) {
        if (!empty(dollar)) {
            return '$'; // $$
        }
        if (!empty(hash)) {
            return fixCase(lexer, id); // default $#
        }
        if (!empty(n) && n < matches.length) {
            return fixCase(lexer, matches[n]); // $n
        }
        if (!empty(attr) && lexer && typeof (lexer[attr]) === 'string') {
            return lexer[attr]; //@attribute
        }
        if (stateMatches === null) { // split state on demand
            stateMatches = state.split('.');
            stateMatches.unshift(state);
        }
        if (!empty(s) && s < stateMatches.length) {
            return fixCase(lexer, stateMatches[s]); //$Sn
        }
        return '';
    });
}
/**
 * Find the tokenizer rules for a specific state (i.e. next action)
 */
function findRules(lexer, inState) {
    let state = inState;
    while (state && state.length > 0) {
        const rules = lexer.tokenizer[state];
        if (rules) {
            return rules;
        }
        const idx = state.lastIndexOf('.');
        if (idx < 0) {
            state = null; // no further parent
        }
        else {
            state = state.substr(0, idx);
        }
    }
    return null;
}
/**
 * Is a certain state defined? In contrast to 'findRules' this works on a ILexerMin.
 * This is used during compilation where we may know the defined states
 * but not yet whether the corresponding rules are correct.
 */
function stateExists(lexer, inState) {
    let state = inState;
    while (state && state.length > 0) {
        const exist = lexer.stateNames[state];
        if (exist) {
            return true;
        }
        const idx = state.lastIndexOf('.');
        if (idx < 0) {
            state = null; // no further parent
        }
        else {
            state = state.substr(0, idx);
        }
    }
    return false;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/common/monarch/monarchLexer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var monarchLexer_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var monarchLexer_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};




const CACHE_STACK_DEPTH = 5;
/**
 * Reuse the same stack elements up to a certain depth.
 */
class MonarchStackElementFactory {
    constructor(maxCacheDepth) {
        this._maxCacheDepth = maxCacheDepth;
        this._entries = Object.create(null);
    }
    static create(parent, state) {
        return this._INSTANCE.create(parent, state);
    }
    create(parent, state) {
        if (parent !== null && parent.depth >= this._maxCacheDepth) {
            // no caching above a certain depth
            return new MonarchStackElement(parent, state);
        }
        let stackElementId = MonarchStackElement.getStackElementId(parent);
        if (stackElementId.length > 0) {
            stackElementId += '|';
        }
        stackElementId += state;
        let result = this._entries[stackElementId];
        if (result) {
            return result;
        }
        result = new MonarchStackElement(parent, state);
        this._entries[stackElementId] = result;
        return result;
    }
}
MonarchStackElementFactory._INSTANCE = new MonarchStackElementFactory(CACHE_STACK_DEPTH);
class MonarchStackElement {
    constructor(parent, state) {
        this.parent = parent;
        this.state = state;
        this.depth = (this.parent ? this.parent.depth : 0) + 1;
    }
    static getStackElementId(element) {
        let result = '';
        while (element !== null) {
            if (result.length > 0) {
                result += '|';
            }
            result += element.state;
            element = element.parent;
        }
        return result;
    }
    static _equals(a, b) {
        while (a !== null && b !== null) {
            if (a === b) {
                return true;
            }
            if (a.state !== b.state) {
                return false;
            }
            a = a.parent;
            b = b.parent;
        }
        if (a === null && b === null) {
            return true;
        }
        return false;
    }
    equals(other) {
        return MonarchStackElement._equals(this, other);
    }
    push(state) {
        return MonarchStackElementFactory.create(this, state);
    }
    pop() {
        return this.parent;
    }
    popall() {
        let result = this;
        while (result.parent) {
            result = result.parent;
        }
        return result;
    }
    switchTo(state) {
        return MonarchStackElementFactory.create(this.parent, state);
    }
}
class EmbeddedLanguageData {
    constructor(languageId, state) {
        this.languageId = languageId;
        this.state = state;
    }
    equals(other) {
        return (this.languageId === other.languageId
            && this.state.equals(other.state));
    }
    clone() {
        const stateClone = this.state.clone();
        // save an object
        if (stateClone === this.state) {
            return this;
        }
        return new EmbeddedLanguageData(this.languageId, this.state);
    }
}
/**
 * Reuse the same line states up to a certain depth.
 */
class MonarchLineStateFactory {
    constructor(maxCacheDepth) {
        this._maxCacheDepth = maxCacheDepth;
        this._entries = Object.create(null);
    }
    static create(stack, embeddedLanguageData) {
        return this._INSTANCE.create(stack, embeddedLanguageData);
    }
    create(stack, embeddedLanguageData) {
        if (embeddedLanguageData !== null) {
            // no caching when embedding
            return new MonarchLineState(stack, embeddedLanguageData);
        }
        if (stack !== null && stack.depth >= this._maxCacheDepth) {
            // no caching above a certain depth
            return new MonarchLineState(stack, embeddedLanguageData);
        }
        const stackElementId = MonarchStackElement.getStackElementId(stack);
        let result = this._entries[stackElementId];
        if (result) {
            return result;
        }
        result = new MonarchLineState(stack, null);
        this._entries[stackElementId] = result;
        return result;
    }
}
MonarchLineStateFactory._INSTANCE = new MonarchLineStateFactory(CACHE_STACK_DEPTH);
class MonarchLineState {
    constructor(stack, embeddedLanguageData) {
        this.stack = stack;
        this.embeddedLanguageData = embeddedLanguageData;
    }
    clone() {
        const embeddedlanguageDataClone = this.embeddedLanguageData ? this.embeddedLanguageData.clone() : null;
        // save an object
        if (embeddedlanguageDataClone === this.embeddedLanguageData) {
            return this;
        }
        return MonarchLineStateFactory.create(this.stack, this.embeddedLanguageData);
    }
    equals(other) {
        if (!(other instanceof MonarchLineState)) {
            return false;
        }
        if (!this.stack.equals(other.stack)) {
            return false;
        }
        if (this.embeddedLanguageData === null && other.embeddedLanguageData === null) {
            return true;
        }
        if (this.embeddedLanguageData === null || other.embeddedLanguageData === null) {
            return false;
        }
        return this.embeddedLanguageData.equals(other.embeddedLanguageData);
    }
}
class MonarchClassicTokensCollector {
    constructor() {
        this._tokens = [];
        this._languageId = null;
        this._lastTokenType = null;
        this._lastTokenLanguage = null;
    }
    enterLanguage(languageId) {
        this._languageId = languageId;
    }
    emit(startOffset, type) {
        if (this._lastTokenType === type && this._lastTokenLanguage === this._languageId) {
            return;
        }
        this._lastTokenType = type;
        this._lastTokenLanguage = this._languageId;
        this._tokens.push(new languages_Token(startOffset, type, this._languageId));
    }
    nestedLanguageTokenize(embeddedLanguageLine, hasEOL, embeddedLanguageData, offsetDelta) {
        const nestedLanguageId = embeddedLanguageData.languageId;
        const embeddedModeState = embeddedLanguageData.state;
        const nestedLanguageTokenizationSupport = languages_TokenizationRegistry.get(nestedLanguageId);
        if (!nestedLanguageTokenizationSupport) {
            this.enterLanguage(nestedLanguageId);
            this.emit(offsetDelta, '');
            return embeddedModeState;
        }
        const nestedResult = nestedLanguageTokenizationSupport.tokenize(embeddedLanguageLine, hasEOL, embeddedModeState);
        if (offsetDelta !== 0) {
            for (const token of nestedResult.tokens) {
                this._tokens.push(new languages_Token(token.offset + offsetDelta, token.type, token.language));
            }
        }
        else {
            this._tokens = this._tokens.concat(nestedResult.tokens);
        }
        this._lastTokenType = null;
        this._lastTokenLanguage = null;
        this._languageId = null;
        return nestedResult.endState;
    }
    finalize(endState) {
        return new TokenizationResult(this._tokens, endState);
    }
}
class MonarchModernTokensCollector {
    constructor(languageService, theme) {
        this._languageService = languageService;
        this._theme = theme;
        this._prependTokens = null;
        this._tokens = [];
        this._currentLanguageId = 0 /* LanguageId.Null */;
        this._lastTokenMetadata = 0;
    }
    enterLanguage(languageId) {
        this._currentLanguageId = this._languageService.languageIdCodec.encodeLanguageId(languageId);
    }
    emit(startOffset, type) {
        const metadata = this._theme.match(this._currentLanguageId, type);
        if (this._lastTokenMetadata === metadata) {
            return;
        }
        this._lastTokenMetadata = metadata;
        this._tokens.push(startOffset);
        this._tokens.push(metadata);
    }
    static _merge(a, b, c) {
        const aLen = (a !== null ? a.length : 0);
        const bLen = b.length;
        const cLen = (c !== null ? c.length : 0);
        if (aLen === 0 && bLen === 0 && cLen === 0) {
            return new Uint32Array(0);
        }
        if (aLen === 0 && bLen === 0) {
            return c;
        }
        if (bLen === 0 && cLen === 0) {
            return a;
        }
        const result = new Uint32Array(aLen + bLen + cLen);
        if (a !== null) {
            result.set(a);
        }
        for (let i = 0; i < bLen; i++) {
            result[aLen + i] = b[i];
        }
        if (c !== null) {
            result.set(c, aLen + bLen);
        }
        return result;
    }
    nestedLanguageTokenize(embeddedLanguageLine, hasEOL, embeddedLanguageData, offsetDelta) {
        const nestedLanguageId = embeddedLanguageData.languageId;
        const embeddedModeState = embeddedLanguageData.state;
        const nestedLanguageTokenizationSupport = languages_TokenizationRegistry.get(nestedLanguageId);
        if (!nestedLanguageTokenizationSupport) {
            this.enterLanguage(nestedLanguageId);
            this.emit(offsetDelta, '');
            return embeddedModeState;
        }
        const nestedResult = nestedLanguageTokenizationSupport.tokenizeEncoded(embeddedLanguageLine, hasEOL, embeddedModeState);
        if (offsetDelta !== 0) {
            for (let i = 0, len = nestedResult.tokens.length; i < len; i += 2) {
                nestedResult.tokens[i] += offsetDelta;
            }
        }
        this._prependTokens = MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, nestedResult.tokens);
        this._tokens = [];
        this._currentLanguageId = 0;
        this._lastTokenMetadata = 0;
        return nestedResult.endState;
    }
    finalize(endState) {
        return new EncodedTokenizationResult(MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, null), endState);
    }
}
let MonarchTokenizer = class MonarchTokenizer {
    constructor(languageService, standaloneThemeService, languageId, lexer, _configurationService) {
        this._configurationService = _configurationService;
        this._languageService = languageService;
        this._standaloneThemeService = standaloneThemeService;
        this._languageId = languageId;
        this._lexer = lexer;
        this._embeddedLanguages = Object.create(null);
        this.embeddedLoaded = Promise.resolve(undefined);
        // Set up listening for embedded modes
        let emitting = false;
        this._tokenizationRegistryListener = languages_TokenizationRegistry.onDidChange((e) => {
            if (emitting) {
                return;
            }
            let isOneOfMyEmbeddedModes = false;
            for (let i = 0, len = e.changedLanguages.length; i < len; i++) {
                const language = e.changedLanguages[i];
                if (this._embeddedLanguages[language]) {
                    isOneOfMyEmbeddedModes = true;
                    break;
                }
            }
            if (isOneOfMyEmbeddedModes) {
                emitting = true;
                languages_TokenizationRegistry.fire([this._languageId]);
                emitting = false;
            }
        });
        this._maxTokenizationLineLength = this._configurationService.getValue('editor.maxTokenizationLineLength', {
            overrideIdentifier: this._languageId
        });
        this._configurationService.onDidChangeConfiguration(e => {
            if (e.affectsConfiguration('editor.maxTokenizationLineLength')) {
                this._maxTokenizationLineLength = this._configurationService.getValue('editor.maxTokenizationLineLength', {
                    overrideIdentifier: this._languageId
                });
            }
        });
    }
    dispose() {
        this._tokenizationRegistryListener.dispose();
    }
    getLoadStatus() {
        const promises = [];
        for (const nestedLanguageId in this._embeddedLanguages) {
            const tokenizationSupport = languages_TokenizationRegistry.get(nestedLanguageId);
            if (tokenizationSupport) {
                // The nested language is already loaded
                if (tokenizationSupport instanceof MonarchTokenizer) {
                    const nestedModeStatus = tokenizationSupport.getLoadStatus();
                    if (nestedModeStatus.loaded === false) {
                        promises.push(nestedModeStatus.promise);
                    }
                }
                continue;
            }
            if (!languages_TokenizationRegistry.isResolved(nestedLanguageId)) {
                // The nested language is in the process of being loaded
                promises.push(languages_TokenizationRegistry.getOrCreate(nestedLanguageId));
            }
        }
        if (promises.length === 0) {
            return {
                loaded: true
            };
        }
        return {
            loaded: false,
            promise: Promise.all(promises).then(_ => undefined)
        };
    }
    getInitialState() {
        const rootState = MonarchStackElementFactory.create(null, this._lexer.start);
        return MonarchLineStateFactory.create(rootState, null);
    }
    tokenize(line, hasEOL, lineState) {
        if (line.length >= this._maxTokenizationLineLength) {
            return nullTokenize(this._languageId, lineState);
        }
        const tokensCollector = new MonarchClassicTokensCollector();
        const endLineState = this._tokenize(line, hasEOL, lineState, tokensCollector);
        return tokensCollector.finalize(endLineState);
    }
    tokenizeEncoded(line, hasEOL, lineState) {
        if (line.length >= this._maxTokenizationLineLength) {
            return nullTokenizeEncoded(this._languageService.languageIdCodec.encodeLanguageId(this._languageId), lineState);
        }
        const tokensCollector = new MonarchModernTokensCollector(this._languageService, this._standaloneThemeService.getColorTheme().tokenTheme);
        const endLineState = this._tokenize(line, hasEOL, lineState, tokensCollector);
        return tokensCollector.finalize(endLineState);
    }
    _tokenize(line, hasEOL, lineState, collector) {
        if (lineState.embeddedLanguageData) {
            return this._nestedTokenize(line, hasEOL, lineState, 0, collector);
        }
        else {
            return this._myTokenize(line, hasEOL, lineState, 0, collector);
        }
    }
    _findLeavingNestedLanguageOffset(line, state) {
        let rules = this._lexer.tokenizer[state.stack.state];
        if (!rules) {
            rules = findRules(this._lexer, state.stack.state); // do parent matching
            if (!rules) {
                throw createError(this._lexer, 'tokenizer state is not defined: ' + state.stack.state);
            }
        }
        let popOffset = -1;
        let hasEmbeddedPopRule = false;
        for (const rule of rules) {
            if (!isIAction(rule.action) || rule.action.nextEmbedded !== '@pop') {
                continue;
            }
            hasEmbeddedPopRule = true;
            let regex = rule.regex;
            const regexSource = rule.regex.source;
            if (regexSource.substr(0, 4) === '^(?:' && regexSource.substr(regexSource.length - 1, 1) === ')') {
                const flags = (regex.ignoreCase ? 'i' : '') + (regex.unicode ? 'u' : '');
                regex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags);
            }
            const result = line.search(regex);
            if (result === -1 || (result !== 0 && rule.matchOnlyAtLineStart)) {
                continue;
            }
            if (popOffset === -1 || result < popOffset) {
                popOffset = result;
            }
        }
        if (!hasEmbeddedPopRule) {
            throw createError(this._lexer, 'no rule containing nextEmbedded: "@pop" in tokenizer embedded state: ' + state.stack.state);
        }
        return popOffset;
    }
    _nestedTokenize(line, hasEOL, lineState, offsetDelta, tokensCollector) {
        const popOffset = this._findLeavingNestedLanguageOffset(line, lineState);
        if (popOffset === -1) {
            // tokenization will not leave nested language
            const nestedEndState = tokensCollector.nestedLanguageTokenize(line, hasEOL, lineState.embeddedLanguageData, offsetDelta);
            return MonarchLineStateFactory.create(lineState.stack, new EmbeddedLanguageData(lineState.embeddedLanguageData.languageId, nestedEndState));
        }
        const nestedLanguageLine = line.substring(0, popOffset);
        if (nestedLanguageLine.length > 0) {
            // tokenize with the nested language
            tokensCollector.nestedLanguageTokenize(nestedLanguageLine, false, lineState.embeddedLanguageData, offsetDelta);
        }
        const restOfTheLine = line.substring(popOffset);
        return this._myTokenize(restOfTheLine, hasEOL, lineState, offsetDelta + popOffset, tokensCollector);
    }
    _safeRuleName(rule) {
        if (rule) {
            return rule.name;
        }
        return '(unknown)';
    }
    _myTokenize(lineWithoutLF, hasEOL, lineState, offsetDelta, tokensCollector) {
        tokensCollector.enterLanguage(this._languageId);
        const lineWithoutLFLength = lineWithoutLF.length;
        const line = (hasEOL && this._lexer.includeLF ? lineWithoutLF + '\n' : lineWithoutLF);
        const lineLength = line.length;
        let embeddedLanguageData = lineState.embeddedLanguageData;
        let stack = lineState.stack;
        let pos = 0;
        let groupMatching = null;
        // See https://github.com/microsoft/monaco-editor/issues/1235
        // Evaluate rules at least once for an empty line
        let forceEvaluation = true;
        while (forceEvaluation || pos < lineLength) {
            const pos0 = pos;
            const stackLen0 = stack.depth;
            const groupLen0 = groupMatching ? groupMatching.groups.length : 0;
            const state = stack.state;
            let matches = null;
            let matched = null;
            let action = null;
            let rule = null;
            let enteringEmbeddedLanguage = null;
            // check if we need to process group matches first
            if (groupMatching) {
                matches = groupMatching.matches;
                const groupEntry = groupMatching.groups.shift();
                matched = groupEntry.matched;
                action = groupEntry.action;
                rule = groupMatching.rule;
                // cleanup if necessary
                if (groupMatching.groups.length === 0) {
                    groupMatching = null;
                }
            }
            else {
                // otherwise we match on the token stream
                if (!forceEvaluation && pos >= lineLength) {
                    // nothing to do
                    break;
                }
                forceEvaluation = false;
                // get the rules for this state
                let rules = this._lexer.tokenizer[state];
                if (!rules) {
                    rules = findRules(this._lexer, state); // do parent matching
                    if (!rules) {
                        throw createError(this._lexer, 'tokenizer state is not defined: ' + state);
                    }
                }
                // try each rule until we match
                const restOfLine = line.substr(pos);
                for (const rule of rules) {
                    if (pos === 0 || !rule.matchOnlyAtLineStart) {
                        matches = restOfLine.match(rule.regex);
                        if (matches) {
                            matched = matches[0];
                            action = rule.action;
                            break;
                        }
                    }
                }
            }
            // We matched 'rule' with 'matches' and 'action'
            if (!matches) {
                matches = [''];
                matched = '';
            }
            if (!action) {
                // bad: we didn't match anything, and there is no action to take
                // we need to advance the stream or we get progress trouble
                if (pos < lineLength) {
                    matches = [line.charAt(pos)];
                    matched = matches[0];
                }
                action = this._lexer.defaultToken;
            }
            if (matched === null) {
                // should never happen, needed for strict null checking
                break;
            }
            // advance stream
            pos += matched.length;
            // maybe call action function (used for 'cases')
            while (isFuzzyAction(action) && isIAction(action) && action.test) {
                action = action.test(matched, matches, state, pos === lineLength);
            }
            let result = null;
            // set the result: either a string or an array of actions
            if (typeof action === 'string' || Array.isArray(action)) {
                result = action;
            }
            else if (action.group) {
                result = action.group;
            }
            else if (action.token !== null && action.token !== undefined) {
                // do $n replacements?
                if (action.tokenSubst) {
                    result = substituteMatches(this._lexer, action.token, matched, matches, state);
                }
                else {
                    result = action.token;
                }
                // enter embedded language?
                if (action.nextEmbedded) {
                    if (action.nextEmbedded === '@pop') {
                        if (!embeddedLanguageData) {
                            throw createError(this._lexer, 'cannot pop embedded language if not inside one');
                        }
                        embeddedLanguageData = null;
                    }
                    else if (embeddedLanguageData) {
                        throw createError(this._lexer, 'cannot enter embedded language from within an embedded language');
                    }
                    else {
                        enteringEmbeddedLanguage = substituteMatches(this._lexer, action.nextEmbedded, matched, matches, state);
                    }
                }
                // state transformations
                if (action.goBack) { // back up the stream..
                    pos = Math.max(0, pos - action.goBack);
                }
                if (action.switchTo && typeof action.switchTo === 'string') {
                    let nextState = substituteMatches(this._lexer, action.switchTo, matched, matches, state); // switch state without a push...
                    if (nextState[0] === '@') {
                        nextState = nextState.substr(1); // peel off starting '@'
                    }
                    if (!findRules(this._lexer, nextState)) {
                        throw createError(this._lexer, 'trying to switch to a state \'' + nextState + '\' that is undefined in rule: ' + this._safeRuleName(rule));
                    }
                    else {
                        stack = stack.switchTo(nextState);
                    }
                }
                else if (action.transform && typeof action.transform === 'function') {
                    throw createError(this._lexer, 'action.transform not supported');
                }
                else if (action.next) {
                    if (action.next === '@push') {
                        if (stack.depth >= this._lexer.maxStack) {
                            throw createError(this._lexer, 'maximum tokenizer stack size reached: [' +
                                stack.state + ',' + stack.parent.state + ',...]');
                        }
                        else {
                            stack = stack.push(state);
                        }
                    }
                    else if (action.next === '@pop') {
                        if (stack.depth <= 1) {
                            throw createError(this._lexer, 'trying to pop an empty stack in rule: ' + this._safeRuleName(rule));
                        }
                        else {
                            stack = stack.pop();
                        }
                    }
                    else if (action.next === '@popall') {
                        stack = stack.popall();
                    }
                    else {
                        let nextState = substituteMatches(this._lexer, action.next, matched, matches, state);
                        if (nextState[0] === '@') {
                            nextState = nextState.substr(1); // peel off starting '@'
                        }
                        if (!findRules(this._lexer, nextState)) {
                            throw createError(this._lexer, 'trying to set a next state \'' + nextState + '\' that is undefined in rule: ' + this._safeRuleName(rule));
                        }
                        else {
                            stack = stack.push(nextState);
                        }
                    }
                }
                if (action.log && typeof (action.log) === 'string') {
                    log(this._lexer, this._lexer.languageId + ': ' + substituteMatches(this._lexer, action.log, matched, matches, state));
                }
            }
            // check result
            if (result === null) {
                throw createError(this._lexer, 'lexer rule has no well-defined action in rule: ' + this._safeRuleName(rule));
            }
            const computeNewStateForEmbeddedLanguage = (enteringEmbeddedLanguage) => {
                // support language names, mime types, and language ids
                const languageId = (this._languageService.getLanguageIdByLanguageName(enteringEmbeddedLanguage)
                    || this._languageService.getLanguageIdByMimeType(enteringEmbeddedLanguage)
                    || enteringEmbeddedLanguage);
                const embeddedLanguageData = this._getNestedEmbeddedLanguageData(languageId);
                if (pos < lineLength) {
                    // there is content from the embedded language on this line
                    const restOfLine = lineWithoutLF.substr(pos);
                    return this._nestedTokenize(restOfLine, hasEOL, MonarchLineStateFactory.create(stack, embeddedLanguageData), offsetDelta + pos, tokensCollector);
                }
                else {
                    return MonarchLineStateFactory.create(stack, embeddedLanguageData);
                }
            };
            // is the result a group match?
            if (Array.isArray(result)) {
                if (groupMatching && groupMatching.groups.length > 0) {
                    throw createError(this._lexer, 'groups cannot be nested: ' + this._safeRuleName(rule));
                }
                if (matches.length !== result.length + 1) {
                    throw createError(this._lexer, 'matched number of groups does not match the number of actions in rule: ' + this._safeRuleName(rule));
                }
                let totalLen = 0;
                for (let i = 1; i < matches.length; i++) {
                    totalLen += matches[i].length;
                }
                if (totalLen !== matched.length) {
                    throw createError(this._lexer, 'with groups, all characters should be matched in consecutive groups in rule: ' + this._safeRuleName(rule));
                }
                groupMatching = {
                    rule: rule,
                    matches: matches,
                    groups: []
                };
                for (let i = 0; i < result.length; i++) {
                    groupMatching.groups[i] = {
                        action: result[i],
                        matched: matches[i + 1]
                    };
                }
                pos -= matched.length;
                // call recursively to initiate first result match
                continue;
            }
            else {
                // regular result
                // check for '@rematch'
                if (result === '@rematch') {
                    pos -= matched.length;
                    matched = ''; // better set the next state too..
                    matches = null;
                    result = '';
                    // Even though `@rematch` was specified, if `nextEmbedded` also specified,
                    // a state transition should occur.
                    if (enteringEmbeddedLanguage !== null) {
                        return computeNewStateForEmbeddedLanguage(enteringEmbeddedLanguage);
                    }
                }
                // check progress
                if (matched.length === 0) {
                    if (lineLength === 0 || stackLen0 !== stack.depth || state !== stack.state || (!groupMatching ? 0 : groupMatching.groups.length) !== groupLen0) {
                        continue;
                    }
                    else {
                        throw createError(this._lexer, 'no progress in tokenizer in rule: ' + this._safeRuleName(rule));
                    }
                }
                // return the result (and check for brace matching)
                // todo: for efficiency we could pre-sanitize tokenPostfix and substitutions
                let tokenType = null;
                if (monarchCommon_isString(result) && result.indexOf('@brackets') === 0) {
                    const rest = result.substr('@brackets'.length);
                    const bracket = findBracket(this._lexer, matched);
                    if (!bracket) {
                        throw createError(this._lexer, '@brackets token returned but no bracket defined as: ' + matched);
                    }
                    tokenType = monarchCommon_sanitize(bracket.token + rest);
                }
                else {
                    const token = (result === '' ? '' : result + this._lexer.tokenPostfix);
                    tokenType = monarchCommon_sanitize(token);
                }
                if (pos0 < lineWithoutLFLength) {
                    tokensCollector.emit(pos0 + offsetDelta, tokenType);
                }
            }
            if (enteringEmbeddedLanguage !== null) {
                return computeNewStateForEmbeddedLanguage(enteringEmbeddedLanguage);
            }
        }
        return MonarchLineStateFactory.create(stack, embeddedLanguageData);
    }
    _getNestedEmbeddedLanguageData(languageId) {
        if (!this._languageService.isRegisteredLanguageId(languageId)) {
            return new EmbeddedLanguageData(languageId, NullState);
        }
        if (languageId !== this._languageId) {
            // Fire language loading event
            languages_TokenizationRegistry.getOrCreate(languageId);
            this._embeddedLanguages[languageId] = true;
        }
        const tokenizationSupport = languages_TokenizationRegistry.get(languageId);
        if (tokenizationSupport) {
            return new EmbeddedLanguageData(languageId, tokenizationSupport.getInitialState());
        }
        return new EmbeddedLanguageData(languageId, NullState);
    }
};
MonarchTokenizer = monarchLexer_decorate([
    monarchLexer_param(4, IConfigurationService)
], MonarchTokenizer);

/**
 * Searches for a bracket in the 'brackets' attribute that matches the input.
 */
function findBracket(lexer, matched) {
    if (!matched) {
        return null;
    }
    matched = fixCase(lexer, matched);
    const brackets = lexer.brackets;
    for (const bracket of brackets) {
        if (bracket.open === matched) {
            return { token: bracket.token, bracketType: 1 /* monarchCommon.MonarchBracket.Open */ };
        }
        else if (bracket.close === matched) {
            return { token: bracket.token, bracketType: -1 /* monarchCommon.MonarchBracket.Close */ };
        }
    }
    return null;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/colorizer.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var colorizer_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
var colorizer_a;






const colorizer_ttPolicy = (colorizer_a = window.trustedTypes) === null || colorizer_a === void 0 ? void 0 : colorizer_a.createPolicy('standaloneColorizer', { createHTML: value => value });
class Colorizer {
    static colorizeElement(themeService, languageService, domNode, options) {
        options = options || {};
        const theme = options.theme || 'vs';
        const mimeType = options.mimeType || domNode.getAttribute('lang') || domNode.getAttribute('data-lang');
        if (!mimeType) {
            console.error('Mode not detected');
            return Promise.resolve();
        }
        const languageId = languageService.getLanguageIdByMimeType(mimeType) || mimeType;
        themeService.setTheme(theme);
        const text = domNode.firstChild ? domNode.firstChild.nodeValue : '';
        domNode.className += ' ' + theme;
        const render = (str) => {
            var _a;
            const trustedhtml = (_a = colorizer_ttPolicy === null || colorizer_ttPolicy === void 0 ? void 0 : colorizer_ttPolicy.createHTML(str)) !== null && _a !== void 0 ? _a : str;
            domNode.innerHTML = trustedhtml;
        };
        return this.colorize(languageService, text || '', languageId, options).then(render, (err) => console.error(err));
    }
    static colorize(languageService, text, languageId, options) {
        return colorizer_awaiter(this, void 0, void 0, function* () {
            const languageIdCodec = languageService.languageIdCodec;
            let tabSize = 4;
            if (options && typeof options.tabSize === 'number') {
                tabSize = options.tabSize;
            }
            if (startsWithUTF8BOM(text)) {
                text = text.substr(1);
            }
            const lines = splitLines(text);
            if (!languageService.isRegisteredLanguageId(languageId)) {
                return _fakeColorize(lines, tabSize, languageIdCodec);
            }
            const tokenizationSupport = yield languages_TokenizationRegistry.getOrCreate(languageId);
            if (tokenizationSupport) {
                return _colorize(lines, tabSize, tokenizationSupport, languageIdCodec);
            }
            return _fakeColorize(lines, tabSize, languageIdCodec);
        });
    }
    static colorizeLine(line, mightContainNonBasicASCII, mightContainRTL, tokens, tabSize = 4) {
        const isBasicASCII = ViewLineRenderingData.isBasicASCII(line, mightContainNonBasicASCII);
        const containsRTL = ViewLineRenderingData.containsRTL(line, isBasicASCII, mightContainRTL);
        const renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, tokens, [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null));
        return renderResult.html;
    }
    static colorizeModelLine(model, lineNumber, tabSize = 4) {
        const content = model.getLineContent(lineNumber);
        model.tokenization.forceTokenization(lineNumber);
        const tokens = model.tokenization.getLineTokens(lineNumber);
        const inflatedTokens = tokens.inflate();
        return this.colorizeLine(content, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize);
    }
}
function _colorize(lines, tabSize, tokenizationSupport, languageIdCodec) {
    return new Promise((c, e) => {
        const execute = () => {
            const result = _actualColorize(lines, tabSize, tokenizationSupport, languageIdCodec);
            if (tokenizationSupport instanceof MonarchTokenizer) {
                const status = tokenizationSupport.getLoadStatus();
                if (status.loaded === false) {
                    status.promise.then(execute, e);
                    return;
                }
            }
            c(result);
        };
        execute();
    });
}
function _fakeColorize(lines, tabSize, languageIdCodec) {
    let html = [];
    const defaultMetadata = ((0 /* FontStyle.None */ << 11 /* MetadataConsts.FONT_STYLE_OFFSET */)
        | (1 /* ColorId.DefaultForeground */ << 15 /* MetadataConsts.FOREGROUND_OFFSET */)
        | (2 /* ColorId.DefaultBackground */ << 24 /* MetadataConsts.BACKGROUND_OFFSET */)) >>> 0;
    const tokens = new Uint32Array(2);
    tokens[0] = 0;
    tokens[1] = defaultMetadata;
    for (let i = 0, length = lines.length; i < length; i++) {
        const line = lines[i];
        tokens[0] = line.length;
        const lineTokens = new LineTokens(tokens, line, languageIdCodec);
        const isBasicASCII = ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true);
        const containsRTL = ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true);
        const renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null));
        html = html.concat(renderResult.html);
        html.push('<br/>');
    }
    return html.join('');
}
function _actualColorize(lines, tabSize, tokenizationSupport, languageIdCodec) {
    let html = [];
    let state = tokenizationSupport.getInitialState();
    for (let i = 0, length = lines.length; i < length; i++) {
        const line = lines[i];
        const tokenizeResult = tokenizationSupport.tokenizeEncoded(line, true, state);
        LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length);
        const lineTokens = new LineTokens(tokenizeResult.tokens, line, languageIdCodec);
        const isBasicASCII = ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true);
        const containsRTL = ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true);
        const renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens.inflate(), [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null));
        html = html.concat(renderResult.html);
        html.push('<br/>');
        state = tokenizeResult.endState;
    }
    return html.join('');
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/widget/media/diffEditor.css
var diffEditor = __webpack_require__(98819);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/widget/media/diffEditor.css

      
      
      
      
      
      
      
      
      

var diffEditor_options = {};

diffEditor_options.styleTagTransform = (styleTagTransform_default());
diffEditor_options.setAttributes = (setAttributesWithoutAttributes_default());

      diffEditor_options.insert = insertBySelector_default().bind(null, "head");
    
diffEditor_options.domAPI = (styleDomAPI_default());
diffEditor_options.insertStyleElement = (insertStyleElement_default());

var diffEditor_update = injectStylesIntoStyleTag_default()(diffEditor/* default */.A, diffEditor_options);




       /* harmony default export */ const media_diffEditor = (diffEditor/* default */.A && diffEditor/* default */.A.locals ? diffEditor/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/browser/widget/media/diffReview.css
var diffReview = __webpack_require__(89856);
;// ../../node_modules/monaco-editor/esm/vs/editor/browser/widget/media/diffReview.css

      
      
      
      
      
      
      
      
      

var diffReview_options = {};

diffReview_options.styleTagTransform = (styleTagTransform_default());
diffReview_options.setAttributes = (setAttributesWithoutAttributes_default());

      diffReview_options.insert = insertBySelector_default().bind(null, "head");
    
diffReview_options.domAPI = (styleDomAPI_default());
diffReview_options.insertStyleElement = (insertStyleElement_default());

var diffReview_update = injectStylesIntoStyleTag_default()(diffReview/* default */.A, diffReview_options);




       /* harmony default export */ const media_diffReview = (diffReview/* default */.A && diffReview/* default */.A.locals ? diffReview/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/widget/diffReview.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var diffReview_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var diffReview_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var diffReview_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};
var diffReview_a;























const DIFF_LINES_PADDING = 3;
class DiffEntry {
    constructor(originalLineStart, originalLineEnd, modifiedLineStart, modifiedLineEnd) {
        this.originalLineStart = originalLineStart;
        this.originalLineEnd = originalLineEnd;
        this.modifiedLineStart = modifiedLineStart;
        this.modifiedLineEnd = modifiedLineEnd;
    }
    getType() {
        if (this.originalLineStart === 0) {
            return 1 /* DiffEntryType.Insert */;
        }
        if (this.modifiedLineStart === 0) {
            return 2 /* DiffEntryType.Delete */;
        }
        return 0 /* DiffEntryType.Equal */;
    }
}
class Diff {
    constructor(entries) {
        this.entries = entries;
    }
}
const diffReviewInsertIcon = registerIcon('diff-review-insert', Codicon.add, localize('diffReviewInsertIcon', 'Icon for \'Insert\' in diff review.'));
const diffReviewRemoveIcon = registerIcon('diff-review-remove', Codicon.remove, localize('diffReviewRemoveIcon', 'Icon for \'Remove\' in diff review.'));
const diffReviewCloseIcon = registerIcon('diff-review-close', Codicon.close, localize('diffReviewCloseIcon', 'Icon for \'Close\' in diff review.'));
let DiffReview = class DiffReview extends Disposable {
    constructor(diffEditor, _languageService) {
        super();
        this._languageService = _languageService;
        this._width = 0;
        this._diffEditor = diffEditor;
        this._isVisible = false;
        this.shadow = createFastDomNode(document.createElement('div'));
        this.shadow.setClassName('diff-review-shadow');
        this.actionBarContainer = createFastDomNode(document.createElement('div'));
        this.actionBarContainer.setClassName('diff-review-actions');
        this._actionBar = this._register(new ActionBar(this.actionBarContainer.domNode));
        this._actionBar.push(new Action('diffreview.close', localize('label.close', "Close"), 'close-diff-review ' + ThemeIcon.asClassName(diffReviewCloseIcon), true, () => diffReview_awaiter(this, void 0, void 0, function* () { return this.hide(); })), { label: false, icon: true });
        this.domNode = createFastDomNode(document.createElement('div'));
        this.domNode.setClassName('diff-review monaco-editor-background');
        this._content = createFastDomNode(document.createElement('div'));
        this._content.setClassName('diff-review-content');
        this._content.setAttribute('role', 'code');
        this.scrollbar = this._register(new DomScrollableElement(this._content.domNode, {}));
        this.domNode.domNode.appendChild(this.scrollbar.getDomNode());
        this._register(diffEditor.onDidUpdateDiff(() => {
            if (!this._isVisible) {
                return;
            }
            this._diffs = this._compute();
            this._render();
        }));
        this._register(diffEditor.getModifiedEditor().onDidChangeCursorPosition(() => {
            if (!this._isVisible) {
                return;
            }
            this._render();
        }));
        this._register(addStandardDisposableListener(this.domNode.domNode, 'click', (e) => {
            e.preventDefault();
            const row = findParentWithClass(e.target, 'diff-review-row');
            if (row) {
                this._goToRow(row);
            }
        }));
        this._register(addStandardDisposableListener(this.domNode.domNode, 'keydown', (e) => {
            if (e.equals(18 /* KeyCode.DownArrow */)
                || e.equals(2048 /* KeyMod.CtrlCmd */ | 18 /* KeyCode.DownArrow */)
                || e.equals(512 /* KeyMod.Alt */ | 18 /* KeyCode.DownArrow */)) {
                e.preventDefault();
                this._goToRow(this._getNextRow());
            }
            if (e.equals(16 /* KeyCode.UpArrow */)
                || e.equals(2048 /* KeyMod.CtrlCmd */ | 16 /* KeyCode.UpArrow */)
                || e.equals(512 /* KeyMod.Alt */ | 16 /* KeyCode.UpArrow */)) {
                e.preventDefault();
                this._goToRow(this._getPrevRow());
            }
            if (e.equals(9 /* KeyCode.Escape */)
                || e.equals(2048 /* KeyMod.CtrlCmd */ | 9 /* KeyCode.Escape */)
                || e.equals(512 /* KeyMod.Alt */ | 9 /* KeyCode.Escape */)
                || e.equals(1024 /* KeyMod.Shift */ | 9 /* KeyCode.Escape */)) {
                e.preventDefault();
                this.hide();
            }
            if (e.equals(10 /* KeyCode.Space */)
                || e.equals(3 /* KeyCode.Enter */)) {
                e.preventDefault();
                this.accept();
            }
        }));
        this._diffs = [];
        this._currentDiff = null;
    }
    prev() {
        let index = 0;
        if (!this._isVisible) {
            this._diffs = this._compute();
        }
        if (this._isVisible) {
            let currentIndex = -1;
            for (let i = 0, len = this._diffs.length; i < len; i++) {
                if (this._diffs[i] === this._currentDiff) {
                    currentIndex = i;
                    break;
                }
            }
            index = (this._diffs.length + currentIndex - 1);
        }
        else {
            index = this._findDiffIndex(this._diffEditor.getPosition());
        }
        if (this._diffs.length === 0) {
            // Nothing to do
            return;
        }
        index = index % this._diffs.length;
        const entries = this._diffs[index].entries;
        this._diffEditor.setPosition(new Position(entries[0].modifiedLineStart, 1));
        this._diffEditor.setSelection({ startColumn: 1, startLineNumber: entries[0].modifiedLineStart, endColumn: 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, endLineNumber: entries[entries.length - 1].modifiedLineEnd });
        this._isVisible = true;
        this._diffEditor.doLayout();
        this._render();
        this._goToRow(this._getNextRow());
    }
    next() {
        let index = 0;
        if (!this._isVisible) {
            this._diffs = this._compute();
        }
        if (this._isVisible) {
            let currentIndex = -1;
            for (let i = 0, len = this._diffs.length; i < len; i++) {
                if (this._diffs[i] === this._currentDiff) {
                    currentIndex = i;
                    break;
                }
            }
            index = (currentIndex + 1);
        }
        else {
            index = this._findDiffIndex(this._diffEditor.getPosition());
        }
        if (this._diffs.length === 0) {
            // Nothing to do
            return;
        }
        index = index % this._diffs.length;
        const entries = this._diffs[index].entries;
        this._diffEditor.setPosition(new Position(entries[0].modifiedLineStart, 1));
        this._diffEditor.setSelection({ startColumn: 1, startLineNumber: entries[0].modifiedLineStart, endColumn: 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, endLineNumber: entries[entries.length - 1].modifiedLineEnd });
        this._isVisible = true;
        this._diffEditor.doLayout();
        this._render();
        this._goToRow(this._getNextRow());
    }
    accept() {
        let jumpToLineNumber = -1;
        const current = this._getCurrentFocusedRow();
        if (current) {
            const lineNumber = parseInt(current.getAttribute('data-line'), 10);
            if (!isNaN(lineNumber)) {
                jumpToLineNumber = lineNumber;
            }
        }
        this.hide();
        if (jumpToLineNumber !== -1) {
            this._diffEditor.setPosition(new Position(jumpToLineNumber, 1));
            this._diffEditor.revealPosition(new Position(jumpToLineNumber, 1), 1 /* ScrollType.Immediate */);
        }
    }
    hide() {
        this._isVisible = false;
        this._diffEditor.updateOptions({ readOnly: false });
        this._diffEditor.focus();
        this._diffEditor.doLayout();
        this._render();
    }
    _getPrevRow() {
        const current = this._getCurrentFocusedRow();
        if (!current) {
            return this._getFirstRow();
        }
        if (current.previousElementSibling) {
            return current.previousElementSibling;
        }
        return current;
    }
    _getNextRow() {
        const current = this._getCurrentFocusedRow();
        if (!current) {
            return this._getFirstRow();
        }
        if (current.nextElementSibling) {
            return current.nextElementSibling;
        }
        return current;
    }
    _getFirstRow() {
        return this.domNode.domNode.querySelector('.diff-review-row');
    }
    _getCurrentFocusedRow() {
        const result = document.activeElement;
        if (result && /diff-review-row/.test(result.className)) {
            return result;
        }
        return null;
    }
    _goToRow(row) {
        const prev = this._getCurrentFocusedRow();
        row.tabIndex = 0;
        row.focus();
        if (prev && prev !== row) {
            prev.tabIndex = -1;
        }
        this.scrollbar.scanDomNode();
    }
    isVisible() {
        return this._isVisible;
    }
    layout(top, width, height) {
        this._width = width;
        this.shadow.setTop(top - 6);
        this.shadow.setWidth(width);
        this.shadow.setHeight(this._isVisible ? 6 : 0);
        this.domNode.setTop(top);
        this.domNode.setWidth(width);
        this.domNode.setHeight(height);
        this._content.setHeight(height);
        this._content.setWidth(width);
        if (this._isVisible) {
            this.actionBarContainer.setAttribute('aria-hidden', 'false');
            this.actionBarContainer.setDisplay('block');
        }
        else {
            this.actionBarContainer.setAttribute('aria-hidden', 'true');
            this.actionBarContainer.setDisplay('none');
        }
    }
    _compute() {
        const lineChanges = this._diffEditor.getLineChanges();
        if (!lineChanges || lineChanges.length === 0) {
            return [];
        }
        const originalModel = this._diffEditor.getOriginalEditor().getModel();
        const modifiedModel = this._diffEditor.getModifiedEditor().getModel();
        if (!originalModel || !modifiedModel) {
            return [];
        }
        return DiffReview._mergeAdjacent(lineChanges, originalModel.getLineCount(), modifiedModel.getLineCount());
    }
    static _mergeAdjacent(lineChanges, originalLineCount, modifiedLineCount) {
        if (!lineChanges || lineChanges.length === 0) {
            return [];
        }
        const diffs = [];
        let diffsLength = 0;
        for (let i = 0, len = lineChanges.length; i < len; i++) {
            const lineChange = lineChanges[i];
            const originalStart = lineChange.originalStartLineNumber;
            const originalEnd = lineChange.originalEndLineNumber;
            const modifiedStart = lineChange.modifiedStartLineNumber;
            const modifiedEnd = lineChange.modifiedEndLineNumber;
            const r = [];
            let rLength = 0;
            // Emit before anchors
            {
                const originalEqualAbove = (originalEnd === 0 ? originalStart : originalStart - 1);
                const modifiedEqualAbove = (modifiedEnd === 0 ? modifiedStart : modifiedStart - 1);
                // Make sure we don't step into the previous diff
                let minOriginal = 1;
                let minModified = 1;
                if (i > 0) {
                    const prevLineChange = lineChanges[i - 1];
                    if (prevLineChange.originalEndLineNumber === 0) {
                        minOriginal = prevLineChange.originalStartLineNumber + 1;
                    }
                    else {
                        minOriginal = prevLineChange.originalEndLineNumber + 1;
                    }
                    if (prevLineChange.modifiedEndLineNumber === 0) {
                        minModified = prevLineChange.modifiedStartLineNumber + 1;
                    }
                    else {
                        minModified = prevLineChange.modifiedEndLineNumber + 1;
                    }
                }
                let fromOriginal = originalEqualAbove - DIFF_LINES_PADDING + 1;
                let fromModified = modifiedEqualAbove - DIFF_LINES_PADDING + 1;
                if (fromOriginal < minOriginal) {
                    const delta = minOriginal - fromOriginal;
                    fromOriginal = fromOriginal + delta;
                    fromModified = fromModified + delta;
                }
                if (fromModified < minModified) {
                    const delta = minModified - fromModified;
                    fromOriginal = fromOriginal + delta;
                    fromModified = fromModified + delta;
                }
                r[rLength++] = new DiffEntry(fromOriginal, originalEqualAbove, fromModified, modifiedEqualAbove);
            }
            // Emit deleted lines
            {
                if (originalEnd !== 0) {
                    r[rLength++] = new DiffEntry(originalStart, originalEnd, 0, 0);
                }
            }
            // Emit inserted lines
            {
                if (modifiedEnd !== 0) {
                    r[rLength++] = new DiffEntry(0, 0, modifiedStart, modifiedEnd);
                }
            }
            // Emit after anchors
            {
                const originalEqualBelow = (originalEnd === 0 ? originalStart + 1 : originalEnd + 1);
                const modifiedEqualBelow = (modifiedEnd === 0 ? modifiedStart + 1 : modifiedEnd + 1);
                // Make sure we don't step into the next diff
                let maxOriginal = originalLineCount;
                let maxModified = modifiedLineCount;
                if (i + 1 < len) {
                    const nextLineChange = lineChanges[i + 1];
                    if (nextLineChange.originalEndLineNumber === 0) {
                        maxOriginal = nextLineChange.originalStartLineNumber;
                    }
                    else {
                        maxOriginal = nextLineChange.originalStartLineNumber - 1;
                    }
                    if (nextLineChange.modifiedEndLineNumber === 0) {
                        maxModified = nextLineChange.modifiedStartLineNumber;
                    }
                    else {
                        maxModified = nextLineChange.modifiedStartLineNumber - 1;
                    }
                }
                let toOriginal = originalEqualBelow + DIFF_LINES_PADDING - 1;
                let toModified = modifiedEqualBelow + DIFF_LINES_PADDING - 1;
                if (toOriginal > maxOriginal) {
                    const delta = maxOriginal - toOriginal;
                    toOriginal = toOriginal + delta;
                    toModified = toModified + delta;
                }
                if (toModified > maxModified) {
                    const delta = maxModified - toModified;
                    toOriginal = toOriginal + delta;
                    toModified = toModified + delta;
                }
                r[rLength++] = new DiffEntry(originalEqualBelow, toOriginal, modifiedEqualBelow, toModified);
            }
            diffs[diffsLength++] = new Diff(r);
        }
        // Merge adjacent diffs
        let curr = diffs[0].entries;
        const r = [];
        let rLength = 0;
        for (let i = 1, len = diffs.length; i < len; i++) {
            const thisDiff = diffs[i].entries;
            const currLast = curr[curr.length - 1];
            const thisFirst = thisDiff[0];
            if (currLast.getType() === 0 /* DiffEntryType.Equal */
                && thisFirst.getType() === 0 /* DiffEntryType.Equal */
                && thisFirst.originalLineStart <= currLast.originalLineEnd) {
                // We are dealing with equal lines that overlap
                curr[curr.length - 1] = new DiffEntry(currLast.originalLineStart, thisFirst.originalLineEnd, currLast.modifiedLineStart, thisFirst.modifiedLineEnd);
                curr = curr.concat(thisDiff.slice(1));
                continue;
            }
            r[rLength++] = new Diff(curr);
            curr = thisDiff;
        }
        r[rLength++] = new Diff(curr);
        return r;
    }
    _findDiffIndex(pos) {
        const lineNumber = pos.lineNumber;
        for (let i = 0, len = this._diffs.length; i < len; i++) {
            const diff = this._diffs[i].entries;
            const lastModifiedLine = diff[diff.length - 1].modifiedLineEnd;
            if (lineNumber <= lastModifiedLine) {
                return i;
            }
        }
        return 0;
    }
    _render() {
        const originalOptions = this._diffEditor.getOriginalEditor().getOptions();
        const modifiedOptions = this._diffEditor.getModifiedEditor().getOptions();
        const originalModel = this._diffEditor.getOriginalEditor().getModel();
        const modifiedModel = this._diffEditor.getModifiedEditor().getModel();
        const originalModelOpts = originalModel.getOptions();
        const modifiedModelOpts = modifiedModel.getOptions();
        if (!this._isVisible || !originalModel || !modifiedModel) {
            clearNode(this._content.domNode);
            this._currentDiff = null;
            this.scrollbar.scanDomNode();
            return;
        }
        this._diffEditor.updateOptions({ readOnly: true });
        const diffIndex = this._findDiffIndex(this._diffEditor.getPosition());
        if (this._diffs[diffIndex] === this._currentDiff) {
            return;
        }
        this._currentDiff = this._diffs[diffIndex];
        const diffs = this._diffs[diffIndex].entries;
        const container = document.createElement('div');
        container.className = 'diff-review-table';
        container.setAttribute('role', 'list');
        container.setAttribute('aria-label', 'Difference review. Use "Stage | Unstage | Revert Selected Ranges" commands');
        applyFontInfo(container, modifiedOptions.get(46 /* EditorOption.fontInfo */));
        let minOriginalLine = 0;
        let maxOriginalLine = 0;
        let minModifiedLine = 0;
        let maxModifiedLine = 0;
        for (let i = 0, len = diffs.length; i < len; i++) {
            const diffEntry = diffs[i];
            const originalLineStart = diffEntry.originalLineStart;
            const originalLineEnd = diffEntry.originalLineEnd;
            const modifiedLineStart = diffEntry.modifiedLineStart;
            const modifiedLineEnd = diffEntry.modifiedLineEnd;
            if (originalLineStart !== 0 && ((minOriginalLine === 0 || originalLineStart < minOriginalLine))) {
                minOriginalLine = originalLineStart;
            }
            if (originalLineEnd !== 0 && ((maxOriginalLine === 0 || originalLineEnd > maxOriginalLine))) {
                maxOriginalLine = originalLineEnd;
            }
            if (modifiedLineStart !== 0 && ((minModifiedLine === 0 || modifiedLineStart < minModifiedLine))) {
                minModifiedLine = modifiedLineStart;
            }
            if (modifiedLineEnd !== 0 && ((maxModifiedLine === 0 || modifiedLineEnd > maxModifiedLine))) {
                maxModifiedLine = modifiedLineEnd;
            }
        }
        const header = document.createElement('div');
        header.className = 'diff-review-row';
        const cell = document.createElement('div');
        cell.className = 'diff-review-cell diff-review-summary';
        const originalChangedLinesCnt = maxOriginalLine - minOriginalLine + 1;
        const modifiedChangedLinesCnt = maxModifiedLine - minModifiedLine + 1;
        cell.appendChild(document.createTextNode(`${diffIndex + 1}/${this._diffs.length}: @@ -${minOriginalLine},${originalChangedLinesCnt} +${minModifiedLine},${modifiedChangedLinesCnt} @@`));
        header.setAttribute('data-line', String(minModifiedLine));
        const getAriaLines = (lines) => {
            if (lines === 0) {
                return localize('no_lines_changed', "no lines changed");
            }
            else if (lines === 1) {
                return localize('one_line_changed', "1 line changed");
            }
            else {
                return localize('more_lines_changed', "{0} lines changed", lines);
            }
        };
        const originalChangedLinesCntAria = getAriaLines(originalChangedLinesCnt);
        const modifiedChangedLinesCntAria = getAriaLines(modifiedChangedLinesCnt);
        header.setAttribute('aria-label', localize({
            key: 'header',
            comment: [
                'This is the ARIA label for a git diff header.',
                'A git diff header looks like this: @@ -154,12 +159,39 @@.',
                'That encodes that at original line 154 (which is now line 159), 12 lines were removed/changed with 39 lines.',
                'Variables 0 and 1 refer to the diff index out of total number of diffs.',
                'Variables 2 and 4 will be numbers (a line number).',
                'Variables 3 and 5 will be "no lines changed", "1 line changed" or "X lines changed", localized separately.'
            ]
        }, "Difference {0} of {1}: original line {2}, {3}, modified line {4}, {5}", (diffIndex + 1), this._diffs.length, minOriginalLine, originalChangedLinesCntAria, minModifiedLine, modifiedChangedLinesCntAria));
        header.appendChild(cell);
        // @@ -504,7 +517,7 @@
        header.setAttribute('role', 'listitem');
        container.appendChild(header);
        const lineHeight = modifiedOptions.get(61 /* EditorOption.lineHeight */);
        let modLine = minModifiedLine;
        for (let i = 0, len = diffs.length; i < len; i++) {
            const diffEntry = diffs[i];
            DiffReview._renderSection(container, diffEntry, modLine, lineHeight, this._width, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts, this._languageService.languageIdCodec);
            if (diffEntry.modifiedLineStart !== 0) {
                modLine = diffEntry.modifiedLineEnd;
            }
        }
        clearNode(this._content.domNode);
        this._content.domNode.appendChild(container);
        this.scrollbar.scanDomNode();
    }
    static _renderSection(dest, diffEntry, modLine, lineHeight, width, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts, languageIdCodec) {
        const type = diffEntry.getType();
        let rowClassName = 'diff-review-row';
        let lineNumbersExtraClassName = '';
        const spacerClassName = 'diff-review-spacer';
        let spacerIcon = null;
        switch (type) {
            case 1 /* DiffEntryType.Insert */:
                rowClassName = 'diff-review-row line-insert';
                lineNumbersExtraClassName = ' char-insert';
                spacerIcon = diffReviewInsertIcon;
                break;
            case 2 /* DiffEntryType.Delete */:
                rowClassName = 'diff-review-row line-delete';
                lineNumbersExtraClassName = ' char-delete';
                spacerIcon = diffReviewRemoveIcon;
                break;
        }
        const originalLineStart = diffEntry.originalLineStart;
        const originalLineEnd = diffEntry.originalLineEnd;
        const modifiedLineStart = diffEntry.modifiedLineStart;
        const modifiedLineEnd = diffEntry.modifiedLineEnd;
        const cnt = Math.max(modifiedLineEnd - modifiedLineStart, originalLineEnd - originalLineStart);
        const originalLayoutInfo = originalOptions.get(133 /* EditorOption.layoutInfo */);
        const originalLineNumbersWidth = originalLayoutInfo.glyphMarginWidth + originalLayoutInfo.lineNumbersWidth;
        const modifiedLayoutInfo = modifiedOptions.get(133 /* EditorOption.layoutInfo */);
        const modifiedLineNumbersWidth = 10 + modifiedLayoutInfo.glyphMarginWidth + modifiedLayoutInfo.lineNumbersWidth;
        for (let i = 0; i <= cnt; i++) {
            const originalLine = (originalLineStart === 0 ? 0 : originalLineStart + i);
            const modifiedLine = (modifiedLineStart === 0 ? 0 : modifiedLineStart + i);
            const row = document.createElement('div');
            row.style.minWidth = width + 'px';
            row.className = rowClassName;
            row.setAttribute('role', 'listitem');
            if (modifiedLine !== 0) {
                modLine = modifiedLine;
            }
            row.setAttribute('data-line', String(modLine));
            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 (originalLine !== 0) {
                originalLineNumber.appendChild(document.createTextNode(String(originalLine)));
            }
            else {
                originalLineNumber.innerText = '\u00a0';
            }
            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 (modifiedLine !== 0) {
                modifiedLineNumber.appendChild(document.createTextNode(String(modifiedLine)));
            }
            else {
                modifiedLineNumber.innerText = '\u00a0';
            }
            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 = '\u00a0\u00a0';
                spacer.appendChild(spacerCodicon);
            }
            else {
                spacer.innerText = '\u00a0\u00a0';
            }
            cell.appendChild(spacer);
            let lineContent;
            if (modifiedLine !== 0) {
                let html = this._renderLine(modifiedModel, modifiedOptions, modifiedModelOpts.tabSize, modifiedLine, languageIdCodec);
                if (DiffReview._ttPolicy) {
                    html = DiffReview._ttPolicy.createHTML(html);
                }
                cell.insertAdjacentHTML('beforeend', html);
                lineContent = modifiedModel.getLineContent(modifiedLine);
            }
            else {
                let html = this._renderLine(originalModel, originalOptions, originalModelOpts.tabSize, originalLine, languageIdCodec);
                if (DiffReview._ttPolicy) {
                    html = DiffReview._ttPolicy.createHTML(html);
                }
                cell.insertAdjacentHTML('beforeend', html);
                lineContent = originalModel.getLineContent(originalLine);
            }
            if (lineContent.length === 0) {
                lineContent = localize('blankLine', "blank");
            }
            let ariaLabel = '';
            switch (type) {
                case 0 /* DiffEntryType.Equal */:
                    if (originalLine === modifiedLine) {
                        ariaLabel = localize({ key: 'unchangedLine', comment: ['The placeholders are contents of the line and should not be translated.'] }, "{0} unchanged line {1}", lineContent, originalLine);
                    }
                    else {
                        ariaLabel = localize('equalLine', "{0} original line {1} modified line {2}", lineContent, originalLine, modifiedLine);
                    }
                    break;
                case 1 /* DiffEntryType.Insert */:
                    ariaLabel = localize('insertLine', "+ {0} modified line {1}", lineContent, modifiedLine);
                    break;
                case 2 /* DiffEntryType.Delete */:
                    ariaLabel = localize('deleteLine', "- {0} original line {1}", lineContent, originalLine);
                    break;
            }
            row.setAttribute('aria-label', ariaLabel);
            dest.appendChild(row);
        }
    }
    static _renderLine(model, options, tabSize, lineNumber, languageIdCodec) {
        const lineContent = model.getLineContent(lineNumber);
        const fontInfo = options.get(46 /* EditorOption.fontInfo */);
        const lineTokens = LineTokens.createEmpty(lineContent, languageIdCodec);
        const isBasicASCII = ViewLineRenderingData.isBasicASCII(lineContent, model.mightContainNonBasicASCII());
        const containsRTL = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII, model.mightContainRTL());
        const r = renderViewLine2(new RenderLineInput((fontInfo.isMonospace && !options.get(29 /* EditorOption.disableMonospaceOptimizations */)), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, options.get(107 /* EditorOption.stopRenderingLineAfter */), options.get(90 /* EditorOption.renderWhitespace */), options.get(85 /* EditorOption.renderControlCharacters */), options.get(47 /* EditorOption.fontLigatures */) !== EditorFontLigatures.OFF, null));
        return r.html;
    }
};
DiffReview._ttPolicy = (diffReview_a = window.trustedTypes) === null || diffReview_a === void 0 ? void 0 : diffReview_a.createPolicy('diffReview', { createHTML: value => value });
DiffReview = diffReview_decorate([
    diffReview_param(1, ILanguageService)
], DiffReview);

// theming
registerThemingParticipant((theme, collector) => {
    const lineNumbers = theme.getColor(editorLineNumbers);
    if (lineNumbers) {
        collector.addRule(`.monaco-diff-editor .diff-review-line-number { color: ${lineNumbers}; }`);
    }
    const shadow = theme.getColor(scrollbarShadow);
    if (shadow) {
        collector.addRule(`.monaco-diff-editor .diff-review-shadow { box-shadow: ${shadow} 0 -6px 6px -6px inset; }`);
    }
});
class DiffReviewNext extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.diffReview.next',
            label: localize('editor.action.diffReview.next', "Go to Next Difference"),
            alias: 'Go to Next Difference',
            precondition: ContextKeyExpr.has('isInDiffEditor'),
            kbOpts: {
                kbExpr: null,
                primary: 65 /* KeyCode.F7 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        const diffEditor = findFocusedDiffEditor(accessor);
        if (diffEditor) {
            diffEditor.diffReviewNext();
        }
    }
}
class DiffReviewPrev extends EditorAction {
    constructor() {
        super({
            id: 'editor.action.diffReview.prev',
            label: localize('editor.action.diffReview.prev', "Go to Previous Difference"),
            alias: 'Go to Previous Difference',
            precondition: ContextKeyExpr.has('isInDiffEditor'),
            kbOpts: {
                kbExpr: null,
                primary: 1024 /* KeyMod.Shift */ | 65 /* KeyCode.F7 */,
                weight: 100 /* KeybindingWeight.EditorContrib */
            }
        });
    }
    run(accessor, editor) {
        const diffEditor = findFocusedDiffEditor(accessor);
        if (diffEditor) {
            diffEditor.diffReviewPrev();
        }
    }
}
function findFocusedDiffEditor(accessor) {
    const codeEditorService = accessor.get(ICodeEditorService);
    const diffEditors = codeEditorService.listDiffEditors();
    const activeCodeEditor = codeEditorService.getActiveCodeEditor();
    if (!activeCodeEditor) {
        return null;
    }
    for (let i = 0, len = diffEditors.length; i < len; i++) {
        const diffEditor = diffEditors[i];
        if (diffEditor.getModifiedEditor().getId() === activeCodeEditor.getId() || diffEditor.getOriginalEditor().getId() === activeCodeEditor.getId()) {
            return diffEditor;
        }
    }
    return null;
}
registerEditorAction(DiffReviewNext);
registerEditorAction(DiffReviewPrev);

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/widget/inlineDiffMargin.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var inlineDiffMargin_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};






class InlineDiffMargin extends Disposable {
    constructor(_viewZoneId, _marginDomNode, editor, diff, _contextMenuService, _clipboardService) {
        super();
        this._viewZoneId = _viewZoneId;
        this._marginDomNode = _marginDomNode;
        this.editor = editor;
        this.diff = diff;
        this._contextMenuService = _contextMenuService;
        this._clipboardService = _clipboardService;
        this._visibility = false;
        // make sure the diff margin shows above overlay.
        this._marginDomNode.style.zIndex = '10';
        this._diffActions = document.createElement('div');
        this._diffActions.className = Codicon.lightBulb.classNames + ' lightbulb-glyph';
        this._diffActions.style.position = 'absolute';
        const lineHeight = editor.getOption(61 /* EditorOption.lineHeight */);
        const lineFeed = editor.getModel().getEOL();
        this._diffActions.style.right = '0px';
        this._diffActions.style.visibility = 'hidden';
        this._diffActions.style.height = `${lineHeight}px`;
        this._diffActions.style.lineHeight = `${lineHeight}px`;
        this._marginDomNode.appendChild(this._diffActions);
        const actions = [];
        const isDeletion = diff.modifiedEndLineNumber === 0;
        // default action
        actions.push(new Action('diff.clipboard.copyDeletedContent', isDeletion
            ? (diff.originalEndLineNumber > diff.modifiedStartLineNumber
                ? localize('diff.clipboard.copyDeletedLinesContent.label', "Copy deleted lines")
                : localize('diff.clipboard.copyDeletedLinesContent.single.label', "Copy deleted line"))
            : (diff.originalEndLineNumber > diff.modifiedStartLineNumber
                ? localize('diff.clipboard.copyChangedLinesContent.label', "Copy changed lines")
                : localize('diff.clipboard.copyChangedLinesContent.single.label', "Copy changed line")), undefined, true, () => inlineDiffMargin_awaiter(this, void 0, void 0, function* () {
            const range = new Range(diff.originalStartLineNumber, 1, diff.originalEndLineNumber + 1, 1);
            const deletedText = diff.originalModel.getValueInRange(range);
            yield this._clipboardService.writeText(deletedText);
        })));
        let currentLineNumberOffset = 0;
        let copyLineAction = undefined;
        if (diff.originalEndLineNumber > diff.modifiedStartLineNumber) {
            copyLineAction = new Action('diff.clipboard.copyDeletedLineContent', isDeletion
                ? localize('diff.clipboard.copyDeletedLineContent.label', "Copy deleted line ({0})", diff.originalStartLineNumber)
                : localize('diff.clipboard.copyChangedLineContent.label', "Copy changed line ({0})", diff.originalStartLineNumber), undefined, true, () => inlineDiffMargin_awaiter(this, void 0, void 0, function* () {
                const lineContent = diff.originalModel.getLineContent(diff.originalStartLineNumber + currentLineNumberOffset);
                if (lineContent === '') {
                    // empty line
                    const eof = diff.originalModel.getEndOfLineSequence();
                    yield this._clipboardService.writeText(eof === 0 /* EndOfLineSequence.LF */ ? '\n' : '\r\n');
                }
                else {
                    yield this._clipboardService.writeText(lineContent);
                }
            }));
            actions.push(copyLineAction);
        }
        const readOnly = editor.getOption(83 /* EditorOption.readOnly */);
        if (!readOnly) {
            actions.push(new Action('diff.inline.revertChange', localize('diff.inline.revertChange.label', "Revert this change"), undefined, true, () => inlineDiffMargin_awaiter(this, void 0, void 0, function* () {
                const range = new Range(diff.originalStartLineNumber, 1, diff.originalEndLineNumber, diff.originalModel.getLineMaxColumn(diff.originalEndLineNumber));
                const deletedText = diff.originalModel.getValueInRange(range);
                if (diff.modifiedEndLineNumber === 0) {
                    // deletion only
                    const column = editor.getModel().getLineMaxColumn(diff.modifiedStartLineNumber);
                    editor.executeEdits('diffEditor', [
                        {
                            range: new Range(diff.modifiedStartLineNumber, column, diff.modifiedStartLineNumber, column),
                            text: lineFeed + deletedText
                        }
                    ]);
                }
                else {
                    const column = editor.getModel().getLineMaxColumn(diff.modifiedEndLineNumber);
                    editor.executeEdits('diffEditor', [
                        {
                            range: new Range(diff.modifiedStartLineNumber, 1, diff.modifiedEndLineNumber, column),
                            text: deletedText
                        }
                    ]);
                }
            })));
        }
        const showContextMenu = (x, y) => {
            this._contextMenuService.showContextMenu({
                getAnchor: () => {
                    return {
                        x,
                        y
                    };
                },
                getActions: () => {
                    if (copyLineAction) {
                        copyLineAction.label =
                            isDeletion
                                ? localize('diff.clipboard.copyDeletedLineContent.label', "Copy deleted line ({0})", diff.originalStartLineNumber + currentLineNumberOffset)
                                : localize('diff.clipboard.copyChangedLineContent.label', "Copy changed line ({0})", diff.originalStartLineNumber + currentLineNumberOffset);
                    }
                    return actions;
                },
                autoSelectFirstItem: true
            });
        };
        this._register(addStandardDisposableListener(this._diffActions, 'mousedown', e => {
            const { top, height } = getDomNodePagePosition(this._diffActions);
            const pad = Math.floor(lineHeight / 3);
            e.preventDefault();
            showContextMenu(e.posx, top + height + pad);
        }));
        this._register(editor.onMouseMove((e) => {
            if (e.target.type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */ || e.target.type === 5 /* MouseTargetType.GUTTER_VIEW_ZONE */) {
                const viewZoneId = e.target.detail.viewZoneId;
                if (viewZoneId === this._viewZoneId) {
                    this.visibility = true;
                    currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
                }
                else {
                    this.visibility = false;
                }
            }
            else {
                this.visibility = false;
            }
        }));
        this._register(editor.onMouseDown((e) => {
            if (!e.event.rightButton) {
                return;
            }
            if (e.target.type === 8 /* MouseTargetType.CONTENT_VIEW_ZONE */ || e.target.type === 5 /* MouseTargetType.GUTTER_VIEW_ZONE */) {
                const viewZoneId = e.target.detail.viewZoneId;
                if (viewZoneId === this._viewZoneId) {
                    e.event.preventDefault();
                    currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
                    showContextMenu(e.event.posx, e.event.posy + lineHeight);
                }
            }
        }));
    }
    get visibility() {
        return this._visibility;
    }
    set visibility(_visibility) {
        if (this._visibility !== _visibility) {
            this._visibility = _visibility;
            if (_visibility) {
                this._diffActions.style.visibility = 'visible';
            }
            else {
                this._diffActions.style.visibility = 'hidden';
            }
        }
    }
    _updateLightBulbPosition(marginDomNode, y, lineHeight) {
        const { top } = getDomNodePagePosition(marginDomNode);
        const offset = y - top;
        const lineNumberOffset = Math.floor(offset / lineHeight);
        const newTop = lineNumberOffset * lineHeight;
        this._diffActions.style.top = `${newTop}px`;
        if (this.diff.viewLineCounts) {
            let acc = 0;
            for (let i = 0; i < this.diff.viewLineCounts.length; i++) {
                acc += this.diff.viewLineCounts[i];
                if (lineNumberOffset < acc) {
                    return i;
                }
            }
        }
        return lineNumberOffset;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/widget/diffEditorWidget.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var diffEditorWidget_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var diffEditorWidget_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var diffEditorWidget_a;










































class VisualEditorState {
    constructor(_contextMenuService, _clipboardService) {
        this._contextMenuService = _contextMenuService;
        this._clipboardService = _clipboardService;
        this._zones = [];
        this._inlineDiffMargins = [];
        this._zonesMap = {};
        this._decorations = [];
    }
    getForeignViewZones(allViewZones) {
        return allViewZones.filter((z) => !this._zonesMap[String(z.id)]);
    }
    clean(editor) {
        // (1) View zones
        if (this._zones.length > 0) {
            editor.changeViewZones((viewChangeAccessor) => {
                for (const zoneId of this._zones) {
                    viewChangeAccessor.removeZone(zoneId);
                }
            });
        }
        this._zones = [];
        this._zonesMap = {};
        // (2) Model decorations
        editor.changeDecorations((changeAccessor) => {
            this._decorations = changeAccessor.deltaDecorations(this._decorations, []);
        });
    }
    apply(editor, overviewRuler, newDecorations, restoreScrollState) {
        const scrollState = restoreScrollState ? StableEditorScrollState.capture(editor) : null;
        // view zones
        editor.changeViewZones((viewChangeAccessor) => {
            var _a;
            for (const zoneId of this._zones) {
                viewChangeAccessor.removeZone(zoneId);
            }
            for (const inlineDiffMargin of this._inlineDiffMargins) {
                inlineDiffMargin.dispose();
            }
            this._zones = [];
            this._zonesMap = {};
            this._inlineDiffMargins = [];
            for (let i = 0, length = newDecorations.zones.length; i < length; i++) {
                const viewZone = newDecorations.zones[i];
                viewZone.suppressMouseDown = true;
                const zoneId = viewChangeAccessor.addZone(viewZone);
                this._zones.push(zoneId);
                this._zonesMap[String(zoneId)] = true;
                if (newDecorations.zones[i].diff && viewZone.marginDomNode) {
                    viewZone.suppressMouseDown = false;
                    if (((_a = newDecorations.zones[i].diff) === null || _a === void 0 ? void 0 : _a.originalModel.getValueLength()) !== 0) {
                        // do not contribute diff margin actions for newly created files
                        this._inlineDiffMargins.push(new InlineDiffMargin(zoneId, viewZone.marginDomNode, editor, newDecorations.zones[i].diff, this._contextMenuService, this._clipboardService));
                    }
                }
            }
        });
        scrollState === null || scrollState === void 0 ? void 0 : scrollState.restore(editor);
        // decorations
        editor.changeDecorations((changeAccessor) => {
            this._decorations = changeAccessor.deltaDecorations(this._decorations, newDecorations.decorations);
        });
        // overview ruler
        overviewRuler === null || overviewRuler === void 0 ? void 0 : overviewRuler.setZones(newDecorations.overviewZones);
    }
}
let DIFF_EDITOR_ID = 0;
const diffInsertIcon = registerIcon('diff-insert', Codicon.add, localize('diffInsertIcon', 'Line decoration for inserts in the diff editor.'));
const diffRemoveIcon = registerIcon('diff-remove', Codicon.remove, localize('diffRemoveIcon', 'Line decoration for removals in the diff editor.'));
const diffEditorWidget_ttPolicy = (diffEditorWidget_a = window.trustedTypes) === null || diffEditorWidget_a === void 0 ? void 0 : diffEditorWidget_a.createPolicy('diffEditorWidget', { createHTML: value => value });
let DiffEditorWidget = class DiffEditorWidget extends Disposable {
    constructor(domElement, options, codeEditorWidgetOptions, clipboardService, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService, contextMenuService, _editorProgressService) {
        super();
        this._editorProgressService = _editorProgressService;
        this._onDidDispose = this._register(new Emitter());
        this.onDidDispose = this._onDidDispose.event;
        this._onDidUpdateDiff = this._register(new Emitter());
        this.onDidUpdateDiff = this._onDidUpdateDiff.event;
        this._onDidContentSizeChange = this._register(new Emitter());
        this._lastOriginalWarning = null;
        this._lastModifiedWarning = null;
        this._editorWorkerService = editorWorkerService;
        this._codeEditorService = codeEditorService;
        this._contextKeyService = this._register(contextKeyService.createScoped(domElement));
        this._instantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService]));
        this._contextKeyService.createKey('isInDiffEditor', true);
        this._themeService = themeService;
        this._notificationService = notificationService;
        this._id = (++DIFF_EDITOR_ID);
        this._state = 0 /* editorBrowser.DiffEditorState.Idle */;
        this._updatingDiffProgress = null;
        this._domElement = domElement;
        options = options || {};
        this._options = validateDiffEditorOptions(options, {
            enableSplitViewResizing: true,
            renderSideBySide: true,
            renderMarginRevertIcon: true,
            maxComputationTime: 5000,
            maxFileSize: 50,
            ignoreTrimWhitespace: true,
            renderIndicators: true,
            originalEditable: false,
            diffCodeLens: false,
            renderOverviewRuler: true,
            diffWordWrap: 'inherit'
        });
        if (typeof options.isInEmbeddedEditor !== 'undefined') {
            this._contextKeyService.createKey('isInEmbeddedDiffEditor', options.isInEmbeddedEditor);
        }
        else {
            this._contextKeyService.createKey('isInEmbeddedDiffEditor', false);
        }
        this._updateDecorationsRunner = this._register(new RunOnceScheduler(() => this._updateDecorations(), 0));
        this._containerDomElement = document.createElement('div');
        this._containerDomElement.className = DiffEditorWidget._getClassName(this._themeService.getColorTheme(), this._options.renderSideBySide);
        this._containerDomElement.style.position = 'relative';
        this._containerDomElement.style.height = '100%';
        this._domElement.appendChild(this._containerDomElement);
        this._overviewViewportDomElement = createFastDomNode(document.createElement('div'));
        this._overviewViewportDomElement.setClassName('diffViewport');
        this._overviewViewportDomElement.setPosition('absolute');
        this._overviewDomElement = document.createElement('div');
        this._overviewDomElement.className = 'diffOverview';
        this._overviewDomElement.style.position = 'absolute';
        this._overviewDomElement.appendChild(this._overviewViewportDomElement.domNode);
        this._register(addStandardDisposableListener(this._overviewDomElement, EventType.POINTER_DOWN, (e) => {
            this._modifiedEditor.delegateVerticalScrollbarPointerDown(e);
        }));
        if (this._options.renderOverviewRuler) {
            this._containerDomElement.appendChild(this._overviewDomElement);
        }
        // Create left side
        this._originalDomNode = document.createElement('div');
        this._originalDomNode.className = 'editor original';
        this._originalDomNode.style.position = 'absolute';
        this._originalDomNode.style.height = '100%';
        this._containerDomElement.appendChild(this._originalDomNode);
        // Create right side
        this._modifiedDomNode = document.createElement('div');
        this._modifiedDomNode.className = 'editor modified';
        this._modifiedDomNode.style.position = 'absolute';
        this._modifiedDomNode.style.height = '100%';
        this._containerDomElement.appendChild(this._modifiedDomNode);
        this._beginUpdateDecorationsTimeout = -1;
        this._currentlyChangingViewZones = false;
        this._diffComputationToken = 0;
        this._originalEditorState = new VisualEditorState(contextMenuService, clipboardService);
        this._modifiedEditorState = new VisualEditorState(contextMenuService, clipboardService);
        this._isVisible = true;
        this._isHandlingScrollEvent = false;
        this._elementSizeObserver = this._register(new ElementSizeObserver(this._containerDomElement, options.dimension));
        this._register(this._elementSizeObserver.onDidChange(() => this._onDidContainerSizeChanged()));
        if (options.automaticLayout) {
            this._elementSizeObserver.startObserving();
        }
        this._diffComputationResult = null;
        this._originalEditor = this._createLeftHandSideEditor(options, codeEditorWidgetOptions.originalEditor || {});
        this._modifiedEditor = this._createRightHandSideEditor(options, codeEditorWidgetOptions.modifiedEditor || {});
        this._originalOverviewRuler = null;
        this._modifiedOverviewRuler = null;
        this._reviewPane = instantiationService.createInstance(DiffReview, this);
        this._containerDomElement.appendChild(this._reviewPane.domNode.domNode);
        this._containerDomElement.appendChild(this._reviewPane.shadow.domNode);
        this._containerDomElement.appendChild(this._reviewPane.actionBarContainer.domNode);
        if (this._options.renderSideBySide) {
            this._setStrategy(new DiffEditorWidgetSideBySide(this._createDataSource(), this._options.enableSplitViewResizing));
        }
        else {
            this._setStrategy(new DiffEditorWidgetInline(this._createDataSource(), this._options.enableSplitViewResizing));
        }
        this._register(themeService.onDidColorThemeChange(t => {
            if (this._strategy && this._strategy.applyColors(t)) {
                this._updateDecorationsRunner.schedule();
            }
            this._containerDomElement.className = DiffEditorWidget._getClassName(this._themeService.getColorTheme(), this._options.renderSideBySide);
        }));
        const contributions = EditorExtensionsRegistry.getDiffEditorContributions();
        for (const desc of contributions) {
            try {
                this._register(instantiationService.createInstance(desc.ctor, this));
            }
            catch (err) {
                onUnexpectedError(err);
            }
        }
        this._codeEditorService.addDiffEditor(this);
    }
    _setState(newState) {
        if (this._state === newState) {
            return;
        }
        this._state = newState;
        if (this._updatingDiffProgress) {
            this._updatingDiffProgress.done();
            this._updatingDiffProgress = null;
        }
        if (this._state === 1 /* editorBrowser.DiffEditorState.ComputingDiff */) {
            this._updatingDiffProgress = this._editorProgressService.show(true, 1000);
        }
    }
    diffReviewNext() {
        this._reviewPane.next();
    }
    diffReviewPrev() {
        this._reviewPane.prev();
    }
    static _getClassName(theme, renderSideBySide) {
        let result = 'monaco-diff-editor monaco-editor-background ';
        if (renderSideBySide) {
            result += 'side-by-side ';
        }
        result += getThemeTypeSelector(theme.type);
        return result;
    }
    _disposeOverviewRulers() {
        if (this._originalOverviewRuler) {
            this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode());
            this._originalOverviewRuler.dispose();
            this._originalOverviewRuler = null;
        }
        if (this._modifiedOverviewRuler) {
            this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode());
            this._modifiedOverviewRuler.dispose();
            this._modifiedOverviewRuler = null;
        }
    }
    _createOverviewRulers() {
        if (!this._options.renderOverviewRuler) {
            return;
        }
        ok(!this._originalOverviewRuler && !this._modifiedOverviewRuler);
        if (this._originalEditor.hasModel()) {
            this._originalOverviewRuler = this._originalEditor.createOverviewRuler('original diffOverviewRuler');
            this._overviewDomElement.appendChild(this._originalOverviewRuler.getDomNode());
        }
        if (this._modifiedEditor.hasModel()) {
            this._modifiedOverviewRuler = this._modifiedEditor.createOverviewRuler('modified diffOverviewRuler');
            this._overviewDomElement.appendChild(this._modifiedOverviewRuler.getDomNode());
        }
        this._layoutOverviewRulers();
    }
    _createLeftHandSideEditor(options, codeEditorWidgetOptions) {
        const editor = this._createInnerEditor(this._instantiationService, this._originalDomNode, this._adjustOptionsForLeftHandSide(options), codeEditorWidgetOptions);
        this._register(editor.onDidScrollChange((e) => {
            if (this._isHandlingScrollEvent) {
                return;
            }
            if (!e.scrollTopChanged && !e.scrollLeftChanged && !e.scrollHeightChanged) {
                return;
            }
            this._isHandlingScrollEvent = true;
            this._modifiedEditor.setScrollPosition({
                scrollLeft: e.scrollLeft,
                scrollTop: e.scrollTop
            });
            this._isHandlingScrollEvent = false;
            this._layoutOverviewViewport();
        }));
        this._register(editor.onDidChangeViewZones(() => {
            this._onViewZonesChanged();
        }));
        this._register(editor.onDidChangeConfiguration((e) => {
            if (!editor.getModel()) {
                return;
            }
            if (e.hasChanged(46 /* EditorOption.fontInfo */)) {
                this._updateDecorationsRunner.schedule();
            }
            if (e.hasChanged(134 /* EditorOption.wrappingInfo */)) {
                this._updateDecorationsRunner.cancel();
                this._updateDecorations();
            }
        }));
        this._register(editor.onDidChangeHiddenAreas(() => {
            this._updateDecorationsRunner.cancel();
            this._updateDecorations();
        }));
        this._register(editor.onDidChangeModelContent(() => {
            if (this._isVisible) {
                this._beginUpdateDecorationsSoon();
            }
        }));
        const isInDiffLeftEditorKey = this._contextKeyService.createKey('isInDiffLeftEditor', editor.hasWidgetFocus());
        this._register(editor.onDidFocusEditorWidget(() => isInDiffLeftEditorKey.set(true)));
        this._register(editor.onDidBlurEditorWidget(() => isInDiffLeftEditorKey.set(false)));
        this._register(editor.onDidContentSizeChange(e => {
            const width = this._originalEditor.getContentWidth() + this._modifiedEditor.getContentWidth() + DiffEditorWidget.ONE_OVERVIEW_WIDTH;
            const height = Math.max(this._modifiedEditor.getContentHeight(), this._originalEditor.getContentHeight());
            this._onDidContentSizeChange.fire({
                contentHeight: height,
                contentWidth: width,
                contentHeightChanged: e.contentHeightChanged,
                contentWidthChanged: e.contentWidthChanged
            });
        }));
        return editor;
    }
    _createRightHandSideEditor(options, codeEditorWidgetOptions) {
        const editor = this._createInnerEditor(this._instantiationService, this._modifiedDomNode, this._adjustOptionsForRightHandSide(options), codeEditorWidgetOptions);
        this._register(editor.onDidScrollChange((e) => {
            if (this._isHandlingScrollEvent) {
                return;
            }
            if (!e.scrollTopChanged && !e.scrollLeftChanged && !e.scrollHeightChanged) {
                return;
            }
            this._isHandlingScrollEvent = true;
            this._originalEditor.setScrollPosition({
                scrollLeft: e.scrollLeft,
                scrollTop: e.scrollTop
            });
            this._isHandlingScrollEvent = false;
            this._layoutOverviewViewport();
        }));
        this._register(editor.onDidChangeViewZones(() => {
            this._onViewZonesChanged();
        }));
        this._register(editor.onDidChangeConfiguration((e) => {
            if (!editor.getModel()) {
                return;
            }
            if (e.hasChanged(46 /* EditorOption.fontInfo */)) {
                this._updateDecorationsRunner.schedule();
            }
            if (e.hasChanged(134 /* EditorOption.wrappingInfo */)) {
                this._updateDecorationsRunner.cancel();
                this._updateDecorations();
            }
        }));
        this._register(editor.onDidChangeHiddenAreas(() => {
            this._updateDecorationsRunner.cancel();
            this._updateDecorations();
        }));
        this._register(editor.onDidChangeModelContent(() => {
            if (this._isVisible) {
                this._beginUpdateDecorationsSoon();
            }
        }));
        this._register(editor.onDidChangeModelOptions((e) => {
            if (e.tabSize) {
                this._updateDecorationsRunner.schedule();
            }
        }));
        const isInDiffRightEditorKey = this._contextKeyService.createKey('isInDiffRightEditor', editor.hasWidgetFocus());
        this._register(editor.onDidFocusEditorWidget(() => isInDiffRightEditorKey.set(true)));
        this._register(editor.onDidBlurEditorWidget(() => isInDiffRightEditorKey.set(false)));
        this._register(editor.onDidContentSizeChange(e => {
            const width = this._originalEditor.getContentWidth() + this._modifiedEditor.getContentWidth() + DiffEditorWidget.ONE_OVERVIEW_WIDTH;
            const height = Math.max(this._modifiedEditor.getContentHeight(), this._originalEditor.getContentHeight());
            this._onDidContentSizeChange.fire({
                contentHeight: height,
                contentWidth: width,
                contentHeightChanged: e.contentHeightChanged,
                contentWidthChanged: e.contentWidthChanged
            });
        }));
        // Revert change when an arrow is clicked.
        this._register(editor.onMouseDown(event => {
            var _a, _b;
            if (!event.event.rightButton && event.target.position && ((_a = event.target.element) === null || _a === void 0 ? void 0 : _a.className.includes('arrow-revert-change'))) {
                const lineNumber = event.target.position.lineNumber;
                const change = (_b = this._diffComputationResult) === null || _b === void 0 ? void 0 : _b.changes.find(c => c.modifiedStartLineNumber === lineNumber - 1 || c.modifiedStartLineNumber === lineNumber);
                if (change) {
                    this.revertChange(change);
                }
                event.event.stopPropagation();
                this._updateDecorations();
                return;
            }
        }));
        return editor;
    }
    /**
     * Reverts a change in the modified editor.
     */
    revertChange(change) {
        const editor = this._modifiedEditor;
        const original = this._originalEditor.getModel();
        const modified = this._modifiedEditor.getModel();
        if (!original || !modified || !editor) {
            return;
        }
        const originalRange = change.originalEndLineNumber > 0 ? new Range(change.originalStartLineNumber, 1, change.originalEndLineNumber, original.getLineMaxColumn(change.originalEndLineNumber)) : null;
        const originalContent = originalRange ? original.getValueInRange(originalRange) : null;
        const newRange = change.modifiedEndLineNumber > 0 ? new Range(change.modifiedStartLineNumber, 1, change.modifiedEndLineNumber, modified.getLineMaxColumn(change.modifiedEndLineNumber)) : null;
        const eol = modified.getEOL();
        if (change.originalEndLineNumber === 0 && newRange) {
            // Insert change.
            // To revert: delete the new content and a linebreak (if possible)
            let range = newRange;
            if (change.modifiedStartLineNumber > 1) {
                // Try to include a linebreak from before.
                range = newRange.setStartPosition(change.modifiedStartLineNumber - 1, modified.getLineMaxColumn(change.modifiedStartLineNumber - 1));
            }
            else if (change.modifiedEndLineNumber < modified.getLineCount()) {
                // Try to include the linebreak from after.
                range = newRange.setEndPosition(change.modifiedEndLineNumber + 1, 1);
            }
            editor.executeEdits('diffEditor', [{
                    range,
                    text: '',
                }]);
        }
        else if (change.modifiedEndLineNumber === 0 && originalContent !== null) {
            // Delete change.
            // To revert: insert the old content and a linebreak.
            const insertAt = change.modifiedStartLineNumber < modified.getLineCount() ? new Position(change.modifiedStartLineNumber + 1, 1) : new Position(change.modifiedStartLineNumber, modified.getLineMaxColumn(change.modifiedStartLineNumber));
            editor.executeEdits('diffEditor', [{
                    range: Range.fromPositions(insertAt, insertAt),
                    text: change.modifiedStartLineNumber < modified.getLineCount() ? originalContent + eol : eol + originalContent,
                }]);
        }
        else if (newRange && originalContent !== null) {
            // Modified change.
            editor.executeEdits('diffEditor', [{
                    range: newRange,
                    text: originalContent,
                }]);
        }
    }
    _createInnerEditor(instantiationService, container, options, editorWidgetOptions) {
        return instantiationService.createInstance(CodeEditorWidget, container, options, editorWidgetOptions);
    }
    dispose() {
        this._codeEditorService.removeDiffEditor(this);
        if (this._beginUpdateDecorationsTimeout !== -1) {
            window.clearTimeout(this._beginUpdateDecorationsTimeout);
            this._beginUpdateDecorationsTimeout = -1;
        }
        this._cleanViewZonesAndDecorations();
        if (this._originalOverviewRuler) {
            this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode());
            this._originalOverviewRuler.dispose();
        }
        if (this._modifiedOverviewRuler) {
            this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode());
            this._modifiedOverviewRuler.dispose();
        }
        this._overviewDomElement.removeChild(this._overviewViewportDomElement.domNode);
        if (this._options.renderOverviewRuler) {
            this._containerDomElement.removeChild(this._overviewDomElement);
        }
        this._containerDomElement.removeChild(this._originalDomNode);
        this._originalEditor.dispose();
        this._containerDomElement.removeChild(this._modifiedDomNode);
        this._modifiedEditor.dispose();
        this._strategy.dispose();
        this._containerDomElement.removeChild(this._reviewPane.domNode.domNode);
        this._containerDomElement.removeChild(this._reviewPane.shadow.domNode);
        this._containerDomElement.removeChild(this._reviewPane.actionBarContainer.domNode);
        this._reviewPane.dispose();
        this._domElement.removeChild(this._containerDomElement);
        this._onDidDispose.fire();
        super.dispose();
    }
    //------------ begin IDiffEditor methods
    getId() {
        return this.getEditorType() + ':' + this._id;
    }
    getEditorType() {
        return EditorType.IDiffEditor;
    }
    getLineChanges() {
        if (!this._diffComputationResult) {
            return null;
        }
        return this._diffComputationResult.changes;
    }
    getOriginalEditor() {
        return this._originalEditor;
    }
    getModifiedEditor() {
        return this._modifiedEditor;
    }
    updateOptions(_newOptions) {
        const newOptions = validateDiffEditorOptions(_newOptions, this._options);
        const changed = changedDiffEditorOptions(this._options, newOptions);
        this._options = newOptions;
        const beginUpdateDecorations = (changed.ignoreTrimWhitespace || changed.renderIndicators || changed.renderMarginRevertIcon);
        const beginUpdateDecorationsSoon = (this._isVisible && (changed.maxComputationTime || changed.maxFileSize));
        if (beginUpdateDecorations) {
            this._beginUpdateDecorations();
        }
        else if (beginUpdateDecorationsSoon) {
            this._beginUpdateDecorationsSoon();
        }
        this._modifiedEditor.updateOptions(this._adjustOptionsForRightHandSide(_newOptions));
        this._originalEditor.updateOptions(this._adjustOptionsForLeftHandSide(_newOptions));
        // enableSplitViewResizing
        this._strategy.setEnableSplitViewResizing(this._options.enableSplitViewResizing);
        // renderSideBySide
        if (changed.renderSideBySide) {
            if (this._options.renderSideBySide) {
                this._setStrategy(new DiffEditorWidgetSideBySide(this._createDataSource(), this._options.enableSplitViewResizing));
            }
            else {
                this._setStrategy(new DiffEditorWidgetInline(this._createDataSource(), this._options.enableSplitViewResizing));
            }
            // Update class name
            this._containerDomElement.className = DiffEditorWidget._getClassName(this._themeService.getColorTheme(), this._options.renderSideBySide);
        }
        // renderOverviewRuler
        if (changed.renderOverviewRuler) {
            if (this._options.renderOverviewRuler) {
                this._containerDomElement.appendChild(this._overviewDomElement);
            }
            else {
                this._containerDomElement.removeChild(this._overviewDomElement);
            }
        }
    }
    getModel() {
        return {
            original: this._originalEditor.getModel(),
            modified: this._modifiedEditor.getModel()
        };
    }
    setModel(model) {
        // Guard us against partial null model
        if (model && (!model.original || !model.modified)) {
            throw new Error(!model.original ? 'DiffEditorWidget.setModel: Original model is null' : 'DiffEditorWidget.setModel: Modified model is null');
        }
        // Remove all view zones & decorations
        this._cleanViewZonesAndDecorations();
        this._disposeOverviewRulers();
        // Update code editor models
        this._originalEditor.setModel(model ? model.original : null);
        this._modifiedEditor.setModel(model ? model.modified : null);
        this._updateDecorationsRunner.cancel();
        // this.originalEditor.onDidChangeModelOptions
        if (model) {
            this._originalEditor.setScrollTop(0);
            this._modifiedEditor.setScrollTop(0);
        }
        // Disable any diff computations that will come in
        this._diffComputationResult = null;
        this._diffComputationToken++;
        this._setState(0 /* editorBrowser.DiffEditorState.Idle */);
        if (model) {
            this._createOverviewRulers();
            // Begin comparing
            this._beginUpdateDecorations();
        }
        this._layoutOverviewViewport();
    }
    getContainerDomNode() {
        return this._domElement;
    }
    getVisibleColumnFromPosition(position) {
        return this._modifiedEditor.getVisibleColumnFromPosition(position);
    }
    getPosition() {
        return this._modifiedEditor.getPosition();
    }
    setPosition(position, source = 'api') {
        this._modifiedEditor.setPosition(position, source);
    }
    revealLine(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealLine(lineNumber, scrollType);
    }
    revealLineInCenter(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealLineInCenter(lineNumber, scrollType);
    }
    revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealLineInCenterIfOutsideViewport(lineNumber, scrollType);
    }
    revealLineNearTop(lineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealLineNearTop(lineNumber, scrollType);
    }
    revealPosition(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealPosition(position, scrollType);
    }
    revealPositionInCenter(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealPositionInCenter(position, scrollType);
    }
    revealPositionInCenterIfOutsideViewport(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealPositionInCenterIfOutsideViewport(position, scrollType);
    }
    revealPositionNearTop(position, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealPositionNearTop(position, scrollType);
    }
    getSelection() {
        return this._modifiedEditor.getSelection();
    }
    getSelections() {
        return this._modifiedEditor.getSelections();
    }
    setSelection(something, source = 'api') {
        this._modifiedEditor.setSelection(something, source);
    }
    setSelections(ranges, source = 'api') {
        this._modifiedEditor.setSelections(ranges, source);
    }
    revealLines(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealLines(startLineNumber, endLineNumber, scrollType);
    }
    revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealLinesInCenter(startLineNumber, endLineNumber, scrollType);
    }
    revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType);
    }
    revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealLinesNearTop(startLineNumber, endLineNumber, scrollType);
    }
    revealRange(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */, revealVerticalInCenter = false, revealHorizontal = true) {
        this._modifiedEditor.revealRange(range, scrollType, revealVerticalInCenter, revealHorizontal);
    }
    revealRangeInCenter(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealRangeInCenter(range, scrollType);
    }
    revealRangeInCenterIfOutsideViewport(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealRangeInCenterIfOutsideViewport(range, scrollType);
    }
    revealRangeNearTop(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealRangeNearTop(range, scrollType);
    }
    revealRangeNearTopIfOutsideViewport(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealRangeNearTopIfOutsideViewport(range, scrollType);
    }
    revealRangeAtTop(range, scrollType = 0 /* editorCommon.ScrollType.Smooth */) {
        this._modifiedEditor.revealRangeAtTop(range, scrollType);
    }
    getSupportedActions() {
        return this._modifiedEditor.getSupportedActions();
    }
    saveViewState() {
        const originalViewState = this._originalEditor.saveViewState();
        const modifiedViewState = this._modifiedEditor.saveViewState();
        return {
            original: originalViewState,
            modified: modifiedViewState
        };
    }
    restoreViewState(s) {
        if (s && s.original && s.modified) {
            const diffEditorState = s;
            this._originalEditor.restoreViewState(diffEditorState.original);
            this._modifiedEditor.restoreViewState(diffEditorState.modified);
        }
    }
    layout(dimension) {
        this._elementSizeObserver.observe(dimension);
    }
    focus() {
        this._modifiedEditor.focus();
    }
    hasTextFocus() {
        return this._originalEditor.hasTextFocus() || this._modifiedEditor.hasTextFocus();
    }
    trigger(source, handlerId, payload) {
        this._modifiedEditor.trigger(source, handlerId, payload);
    }
    createDecorationsCollection(decorations) {
        return this._modifiedEditor.createDecorationsCollection(decorations);
    }
    changeDecorations(callback) {
        return this._modifiedEditor.changeDecorations(callback);
    }
    //------------ end IDiffEditor methods
    //------------ begin layouting methods
    _onDidContainerSizeChanged() {
        this._doLayout();
    }
    _getReviewHeight() {
        return this._reviewPane.isVisible() ? this._elementSizeObserver.getHeight() : 0;
    }
    _layoutOverviewRulers() {
        if (!this._options.renderOverviewRuler) {
            return;
        }
        if (!this._originalOverviewRuler || !this._modifiedOverviewRuler) {
            return;
        }
        const height = this._elementSizeObserver.getHeight();
        const reviewHeight = this._getReviewHeight();
        const freeSpace = DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH - 2 * DiffEditorWidget.ONE_OVERVIEW_WIDTH;
        const layoutInfo = this._modifiedEditor.getLayoutInfo();
        if (layoutInfo) {
            this._originalOverviewRuler.setLayout({
                top: 0,
                width: DiffEditorWidget.ONE_OVERVIEW_WIDTH,
                right: freeSpace + DiffEditorWidget.ONE_OVERVIEW_WIDTH,
                height: (height - reviewHeight)
            });
            this._modifiedOverviewRuler.setLayout({
                top: 0,
                right: 0,
                width: DiffEditorWidget.ONE_OVERVIEW_WIDTH,
                height: (height - reviewHeight)
            });
        }
    }
    //------------ end layouting methods
    _onViewZonesChanged() {
        if (this._currentlyChangingViewZones) {
            return;
        }
        this._updateDecorationsRunner.schedule();
    }
    _beginUpdateDecorationsSoon() {
        // Clear previous timeout if necessary
        if (this._beginUpdateDecorationsTimeout !== -1) {
            window.clearTimeout(this._beginUpdateDecorationsTimeout);
            this._beginUpdateDecorationsTimeout = -1;
        }
        this._beginUpdateDecorationsTimeout = window.setTimeout(() => this._beginUpdateDecorations(), DiffEditorWidget.UPDATE_DIFF_DECORATIONS_DELAY);
    }
    static _equals(a, b) {
        if (!a && !b) {
            return true;
        }
        if (!a || !b) {
            return false;
        }
        return (a.toString() === b.toString());
    }
    _beginUpdateDecorations() {
        this._beginUpdateDecorationsTimeout = -1;
        const currentOriginalModel = this._originalEditor.getModel();
        const currentModifiedModel = this._modifiedEditor.getModel();
        if (!currentOriginalModel || !currentModifiedModel) {
            return;
        }
        // Prevent old diff requests to come if a new request has been initiated
        // The best method would be to call cancel on the Promise, but this is not
        // yet supported, so using tokens for now.
        this._diffComputationToken++;
        const currentToken = this._diffComputationToken;
        const diffLimit = this._options.maxFileSize * 1024 * 1024; // MB
        const canSyncModelForDiff = (model) => {
            const bufferTextLength = model.getValueLength();
            return (diffLimit === 0 || bufferTextLength <= diffLimit);
        };
        if (!canSyncModelForDiff(currentOriginalModel) || !canSyncModelForDiff(currentModifiedModel)) {
            if (!DiffEditorWidget._equals(currentOriginalModel.uri, this._lastOriginalWarning)
                || !DiffEditorWidget._equals(currentModifiedModel.uri, this._lastModifiedWarning)) {
                this._lastOriginalWarning = currentOriginalModel.uri;
                this._lastModifiedWarning = currentModifiedModel.uri;
                this._notificationService.warn(localize("diff.tooLarge", "Cannot compare files because one file is too large."));
            }
            return;
        }
        this._setState(1 /* editorBrowser.DiffEditorState.ComputingDiff */);
        this._editorWorkerService.computeDiff(currentOriginalModel.uri, currentModifiedModel.uri, this._options.ignoreTrimWhitespace, this._options.maxComputationTime).then((result) => {
            if (currentToken === this._diffComputationToken
                && currentOriginalModel === this._originalEditor.getModel()
                && currentModifiedModel === this._modifiedEditor.getModel()) {
                this._setState(2 /* editorBrowser.DiffEditorState.DiffComputed */);
                this._diffComputationResult = result;
                this._updateDecorationsRunner.schedule();
                this._onDidUpdateDiff.fire();
            }
        }, (error) => {
            if (currentToken === this._diffComputationToken
                && currentOriginalModel === this._originalEditor.getModel()
                && currentModifiedModel === this._modifiedEditor.getModel()) {
                this._setState(2 /* editorBrowser.DiffEditorState.DiffComputed */);
                this._diffComputationResult = null;
                this._updateDecorationsRunner.schedule();
            }
        });
    }
    _cleanViewZonesAndDecorations() {
        this._originalEditorState.clean(this._originalEditor);
        this._modifiedEditorState.clean(this._modifiedEditor);
    }
    _updateDecorations() {
        if (!this._originalEditor.getModel() || !this._modifiedEditor.getModel()) {
            return;
        }
        const lineChanges = (this._diffComputationResult ? this._diffComputationResult.changes : []);
        const foreignOriginal = this._originalEditorState.getForeignViewZones(this._originalEditor.getWhitespaces());
        const foreignModified = this._modifiedEditorState.getForeignViewZones(this._modifiedEditor.getWhitespaces());
        const diffDecorations = this._strategy.getEditorsDiffDecorations(lineChanges, this._options.ignoreTrimWhitespace, this._options.renderIndicators, this._options.renderMarginRevertIcon, foreignOriginal, foreignModified);
        try {
            this._currentlyChangingViewZones = true;
            this._originalEditorState.apply(this._originalEditor, this._originalOverviewRuler, diffDecorations.original, false);
            this._modifiedEditorState.apply(this._modifiedEditor, this._modifiedOverviewRuler, diffDecorations.modified, true);
        }
        finally {
            this._currentlyChangingViewZones = false;
        }
    }
    _adjustOptionsForSubEditor(options) {
        const clonedOptions = Object.assign({}, options);
        clonedOptions.inDiffEditor = true;
        clonedOptions.automaticLayout = false;
        // Clone scrollbar options before changing them
        clonedOptions.scrollbar = Object.assign({}, (clonedOptions.scrollbar || {}));
        clonedOptions.scrollbar.vertical = 'visible';
        clonedOptions.folding = false;
        clonedOptions.codeLens = this._options.diffCodeLens;
        clonedOptions.fixedOverflowWidgets = true;
        // clonedOptions.lineDecorationsWidth = '2ch';
        // Clone minimap options before changing them
        clonedOptions.minimap = Object.assign({}, (clonedOptions.minimap || {}));
        clonedOptions.minimap.enabled = false;
        return clonedOptions;
    }
    _adjustOptionsForLeftHandSide(options) {
        const result = this._adjustOptionsForSubEditor(options);
        if (!this._options.renderSideBySide) {
            // never wrap hidden editor
            result.wordWrapOverride1 = 'off';
            result.wordWrapOverride2 = 'off';
        }
        else {
            result.wordWrapOverride1 = this._options.diffWordWrap;
        }
        if (options.originalAriaLabel) {
            result.ariaLabel = options.originalAriaLabel;
        }
        result.readOnly = !this._options.originalEditable;
        result.dropIntoEditor = { enabled: !result.readOnly };
        result.extraEditorClassName = 'original-in-monaco-diff-editor';
        return Object.assign(Object.assign({}, result), { dimension: {
                height: 0,
                width: 0
            } });
    }
    _adjustOptionsForRightHandSide(options) {
        const result = this._adjustOptionsForSubEditor(options);
        if (options.modifiedAriaLabel) {
            result.ariaLabel = options.modifiedAriaLabel;
        }
        result.wordWrapOverride1 = this._options.diffWordWrap;
        result.revealHorizontalRightPadding = EditorOptions.revealHorizontalRightPadding.defaultValue + DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH;
        result.scrollbar.verticalHasArrows = false;
        result.extraEditorClassName = 'modified-in-monaco-diff-editor';
        return Object.assign(Object.assign({}, result), { dimension: {
                height: 0,
                width: 0
            } });
    }
    doLayout() {
        this._elementSizeObserver.observe();
        this._doLayout();
    }
    _doLayout() {
        const width = this._elementSizeObserver.getWidth();
        const height = this._elementSizeObserver.getHeight();
        const reviewHeight = this._getReviewHeight();
        const splitPoint = this._strategy.layout();
        this._originalDomNode.style.width = splitPoint + 'px';
        this._originalDomNode.style.left = '0px';
        this._modifiedDomNode.style.width = (width - splitPoint) + 'px';
        this._modifiedDomNode.style.left = splitPoint + 'px';
        this._overviewDomElement.style.top = '0px';
        this._overviewDomElement.style.height = (height - reviewHeight) + 'px';
        this._overviewDomElement.style.width = DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH + 'px';
        this._overviewDomElement.style.left = (width - DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH) + 'px';
        this._overviewViewportDomElement.setWidth(DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH);
        this._overviewViewportDomElement.setHeight(30);
        this._originalEditor.layout({ width: splitPoint, height: (height - reviewHeight) });
        this._modifiedEditor.layout({ width: width - splitPoint - (this._options.renderOverviewRuler ? DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH : 0), height: (height - reviewHeight) });
        if (this._originalOverviewRuler || this._modifiedOverviewRuler) {
            this._layoutOverviewRulers();
        }
        this._reviewPane.layout(height - reviewHeight, width, reviewHeight);
        this._layoutOverviewViewport();
    }
    _layoutOverviewViewport() {
        const layout = this._computeOverviewViewport();
        if (!layout) {
            this._overviewViewportDomElement.setTop(0);
            this._overviewViewportDomElement.setHeight(0);
        }
        else {
            this._overviewViewportDomElement.setTop(layout.top);
            this._overviewViewportDomElement.setHeight(layout.height);
        }
    }
    _computeOverviewViewport() {
        const layoutInfo = this._modifiedEditor.getLayoutInfo();
        if (!layoutInfo) {
            return null;
        }
        const scrollTop = this._modifiedEditor.getScrollTop();
        const scrollHeight = this._modifiedEditor.getScrollHeight();
        const computedAvailableSize = Math.max(0, layoutInfo.height);
        const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * 0);
        const computedRatio = scrollHeight > 0 ? (computedRepresentableSize / scrollHeight) : 0;
        const computedSliderSize = Math.max(0, Math.floor(layoutInfo.height * computedRatio));
        const computedSliderPosition = Math.floor(scrollTop * computedRatio);
        return {
            height: computedSliderSize,
            top: computedSliderPosition
        };
    }
    _createDataSource() {
        return {
            getWidth: () => {
                return this._elementSizeObserver.getWidth();
            },
            getHeight: () => {
                return (this._elementSizeObserver.getHeight() - this._getReviewHeight());
            },
            getOptions: () => {
                return {
                    renderOverviewRuler: this._options.renderOverviewRuler
                };
            },
            getContainerDomNode: () => {
                return this._containerDomElement;
            },
            relayoutEditors: () => {
                this._doLayout();
            },
            getOriginalEditor: () => {
                return this._originalEditor;
            },
            getModifiedEditor: () => {
                return this._modifiedEditor;
            }
        };
    }
    _setStrategy(newStrategy) {
        if (this._strategy) {
            this._strategy.dispose();
        }
        this._strategy = newStrategy;
        newStrategy.applyColors(this._themeService.getColorTheme());
        if (this._diffComputationResult) {
            this._updateDecorations();
        }
        // Just do a layout, the strategy might need it
        this._doLayout();
    }
    _getLineChangeAtOrBeforeLineNumber(lineNumber, startLineNumberExtractor) {
        const lineChanges = (this._diffComputationResult ? this._diffComputationResult.changes : []);
        if (lineChanges.length === 0 || lineNumber < startLineNumberExtractor(lineChanges[0])) {
            // There are no changes or `lineNumber` is before the first change
            return null;
        }
        let min = 0;
        let max = lineChanges.length - 1;
        while (min < max) {
            const mid = Math.floor((min + max) / 2);
            const midStart = startLineNumberExtractor(lineChanges[mid]);
            const midEnd = (mid + 1 <= max ? startLineNumberExtractor(lineChanges[mid + 1]) : 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */);
            if (lineNumber < midStart) {
                max = mid - 1;
            }
            else if (lineNumber >= midEnd) {
                min = mid + 1;
            }
            else {
                // HIT!
                min = mid;
                max = mid;
            }
        }
        return lineChanges[min];
    }
    _getEquivalentLineForOriginalLineNumber(lineNumber) {
        const lineChange = this._getLineChangeAtOrBeforeLineNumber(lineNumber, (lineChange) => lineChange.originalStartLineNumber);
        if (!lineChange) {
            return lineNumber;
        }
        const originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
        const modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
        const lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? (lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1) : 0);
        const lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? (lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1) : 0);
        const delta = lineNumber - originalEquivalentLineNumber;
        if (delta <= lineChangeOriginalLength) {
            return modifiedEquivalentLineNumber + Math.min(delta, lineChangeModifiedLength);
        }
        return modifiedEquivalentLineNumber + lineChangeModifiedLength - lineChangeOriginalLength + delta;
    }
    _getEquivalentLineForModifiedLineNumber(lineNumber) {
        const lineChange = this._getLineChangeAtOrBeforeLineNumber(lineNumber, (lineChange) => lineChange.modifiedStartLineNumber);
        if (!lineChange) {
            return lineNumber;
        }
        const originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
        const modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
        const lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? (lineChange.originalEndLineNumber - lineChange.originalStartLineNumber + 1) : 0);
        const lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? (lineChange.modifiedEndLineNumber - lineChange.modifiedStartLineNumber + 1) : 0);
        const delta = lineNumber - modifiedEquivalentLineNumber;
        if (delta <= lineChangeModifiedLength) {
            return originalEquivalentLineNumber + Math.min(delta, lineChangeOriginalLength);
        }
        return originalEquivalentLineNumber + lineChangeOriginalLength - lineChangeModifiedLength + delta;
    }
    getDiffLineInformationForOriginal(lineNumber) {
        if (!this._diffComputationResult) {
            // Cannot answer that which I don't know
            return null;
        }
        return {
            equivalentLineNumber: this._getEquivalentLineForOriginalLineNumber(lineNumber)
        };
    }
    getDiffLineInformationForModified(lineNumber) {
        if (!this._diffComputationResult) {
            // Cannot answer that which I don't know
            return null;
        }
        return {
            equivalentLineNumber: this._getEquivalentLineForModifiedLineNumber(lineNumber)
        };
    }
};
DiffEditorWidget.ONE_OVERVIEW_WIDTH = 15;
DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH = 30;
DiffEditorWidget.UPDATE_DIFF_DECORATIONS_DELAY = 200; // ms
DiffEditorWidget = diffEditorWidget_decorate([
    diffEditorWidget_param(3, IClipboardService),
    diffEditorWidget_param(4, IEditorWorkerService),
    diffEditorWidget_param(5, IContextKeyService),
    diffEditorWidget_param(6, IInstantiationService),
    diffEditorWidget_param(7, ICodeEditorService),
    diffEditorWidget_param(8, IThemeService),
    diffEditorWidget_param(9, INotificationService),
    diffEditorWidget_param(10, IContextMenuService),
    diffEditorWidget_param(11, IEditorProgressService)
], DiffEditorWidget);

class DiffEditorWidgetStyle extends Disposable {
    constructor(dataSource) {
        super();
        this._dataSource = dataSource;
        this._insertColor = null;
        this._removeColor = null;
    }
    applyColors(theme) {
        const newInsertColor = theme.getColor(diffOverviewRulerInserted) || (theme.getColor(diffInserted) || defaultInsertColor).transparent(2);
        const newRemoveColor = theme.getColor(diffOverviewRulerRemoved) || (theme.getColor(diffRemoved) || defaultRemoveColor).transparent(2);
        const hasChanges = !newInsertColor.equals(this._insertColor) || !newRemoveColor.equals(this._removeColor);
        this._insertColor = newInsertColor;
        this._removeColor = newRemoveColor;
        return hasChanges;
    }
    getEditorsDiffDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, renderMarginRevertIcon, originalWhitespaces, modifiedWhitespaces) {
        // Get view zones
        modifiedWhitespaces = modifiedWhitespaces.sort((a, b) => {
            return a.afterLineNumber - b.afterLineNumber;
        });
        originalWhitespaces = originalWhitespaces.sort((a, b) => {
            return a.afterLineNumber - b.afterLineNumber;
        });
        const zones = this._getViewZones(lineChanges, originalWhitespaces, modifiedWhitespaces, renderIndicators);
        // Get decorations & overview ruler zones
        const originalDecorations = this._getOriginalEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators);
        const modifiedDecorations = this._getModifiedEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators, renderMarginRevertIcon);
        return {
            original: {
                decorations: originalDecorations.decorations,
                overviewZones: originalDecorations.overviewZones,
                zones: zones.original
            },
            modified: {
                decorations: modifiedDecorations.decorations,
                overviewZones: modifiedDecorations.overviewZones,
                zones: zones.modified
            }
        };
    }
}
class ForeignViewZonesIterator {
    constructor(source) {
        this._source = source;
        this._index = -1;
        this.current = null;
        this.advance();
    }
    advance() {
        this._index++;
        if (this._index < this._source.length) {
            this.current = this._source[this._index];
        }
        else {
            this.current = null;
        }
    }
}
class ViewZonesComputer {
    constructor(_lineChanges, _originalForeignVZ, _modifiedForeignVZ, _originalEditor, _modifiedEditor) {
        this._lineChanges = _lineChanges;
        this._originalForeignVZ = _originalForeignVZ;
        this._modifiedForeignVZ = _modifiedForeignVZ;
        this._originalEditor = _originalEditor;
        this._modifiedEditor = _modifiedEditor;
    }
    static _getViewLineCount(editor, startLineNumber, endLineNumber) {
        const model = editor.getModel();
        const viewModel = editor._getViewModel();
        if (model && viewModel) {
            const viewRange = getViewRange(model, viewModel, startLineNumber, endLineNumber);
            return (viewRange.endLineNumber - viewRange.startLineNumber + 1);
        }
        return (endLineNumber - startLineNumber + 1);
    }
    getViewZones() {
        const originalLineHeight = this._originalEditor.getOption(61 /* EditorOption.lineHeight */);
        const modifiedLineHeight = this._modifiedEditor.getOption(61 /* EditorOption.lineHeight */);
        const originalHasWrapping = (this._originalEditor.getOption(134 /* EditorOption.wrappingInfo */).wrappingColumn !== -1);
        const modifiedHasWrapping = (this._modifiedEditor.getOption(134 /* EditorOption.wrappingInfo */).wrappingColumn !== -1);
        const hasWrapping = (originalHasWrapping || modifiedHasWrapping);
        const originalModel = this._originalEditor.getModel();
        const originalCoordinatesConverter = this._originalEditor._getViewModel().coordinatesConverter;
        const modifiedCoordinatesConverter = this._modifiedEditor._getViewModel().coordinatesConverter;
        const result = {
            original: [],
            modified: []
        };
        let lineChangeModifiedLength = 0;
        let lineChangeOriginalLength = 0;
        let originalEquivalentLineNumber = 0;
        let modifiedEquivalentLineNumber = 0;
        let originalEndEquivalentLineNumber = 0;
        let modifiedEndEquivalentLineNumber = 0;
        const sortMyViewZones = (a, b) => {
            return a.afterLineNumber - b.afterLineNumber;
        };
        const addAndCombineIfPossible = (destination, item) => {
            if (item.domNode === null && destination.length > 0) {
                const lastItem = destination[destination.length - 1];
                if (lastItem.afterLineNumber === item.afterLineNumber && lastItem.domNode === null) {
                    lastItem.heightInLines += item.heightInLines;
                    return;
                }
            }
            destination.push(item);
        };
        const modifiedForeignVZ = new ForeignViewZonesIterator(this._modifiedForeignVZ);
        const originalForeignVZ = new ForeignViewZonesIterator(this._originalForeignVZ);
        let lastOriginalLineNumber = 1;
        let lastModifiedLineNumber = 1;
        // In order to include foreign view zones after the last line change, the for loop will iterate once more after the end of the `lineChanges` array
        for (let i = 0, length = this._lineChanges.length; i <= length; i++) {
            const lineChange = (i < length ? this._lineChanges[i] : null);
            if (lineChange !== null) {
                originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
                modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
                lineChangeOriginalLength = (lineChange.originalEndLineNumber > 0 ? ViewZonesComputer._getViewLineCount(this._originalEditor, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber) : 0);
                lineChangeModifiedLength = (lineChange.modifiedEndLineNumber > 0 ? ViewZonesComputer._getViewLineCount(this._modifiedEditor, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber) : 0);
                originalEndEquivalentLineNumber = Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
                modifiedEndEquivalentLineNumber = Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
            }
            else {
                // Increase to very large value to get the producing tests of foreign view zones running
                originalEquivalentLineNumber += 10000000 + lineChangeOriginalLength;
                modifiedEquivalentLineNumber += 10000000 + lineChangeModifiedLength;
                originalEndEquivalentLineNumber = originalEquivalentLineNumber;
                modifiedEndEquivalentLineNumber = modifiedEquivalentLineNumber;
            }
            // Each step produces view zones, and after producing them, we try to cancel them out, to avoid empty-empty view zone cases
            let stepOriginal = [];
            let stepModified = [];
            // ---------------------------- PRODUCE VIEW ZONES
            // [PRODUCE] View zones due to line mapping differences (equal lines but wrapped differently)
            if (hasWrapping) {
                let count;
                if (lineChange) {
                    if (lineChange.originalEndLineNumber > 0) {
                        count = lineChange.originalStartLineNumber - lastOriginalLineNumber;
                    }
                    else {
                        count = lineChange.modifiedStartLineNumber - lastModifiedLineNumber;
                    }
                }
                else {
                    // `lastOriginalLineNumber` has not been looked at yet
                    count = originalModel.getLineCount() - lastOriginalLineNumber + 1;
                }
                for (let i = 0; i < count; i++) {
                    const originalLineNumber = lastOriginalLineNumber + i;
                    const modifiedLineNumber = lastModifiedLineNumber + i;
                    const originalViewLineCount = originalCoordinatesConverter.getModelLineViewLineCount(originalLineNumber);
                    const modifiedViewLineCount = modifiedCoordinatesConverter.getModelLineViewLineCount(modifiedLineNumber);
                    if (originalViewLineCount < modifiedViewLineCount) {
                        stepOriginal.push({
                            afterLineNumber: originalLineNumber,
                            heightInLines: modifiedViewLineCount - originalViewLineCount,
                            domNode: null,
                            marginDomNode: null
                        });
                    }
                    else if (originalViewLineCount > modifiedViewLineCount) {
                        stepModified.push({
                            afterLineNumber: modifiedLineNumber,
                            heightInLines: originalViewLineCount - modifiedViewLineCount,
                            domNode: null,
                            marginDomNode: null
                        });
                    }
                }
                if (lineChange) {
                    lastOriginalLineNumber = (lineChange.originalEndLineNumber > 0 ? lineChange.originalEndLineNumber : lineChange.originalStartLineNumber) + 1;
                    lastModifiedLineNumber = (lineChange.modifiedEndLineNumber > 0 ? lineChange.modifiedEndLineNumber : lineChange.modifiedStartLineNumber) + 1;
                }
            }
            // [PRODUCE] View zone(s) in original-side due to foreign view zone(s) in modified-side
            while (modifiedForeignVZ.current && modifiedForeignVZ.current.afterLineNumber <= modifiedEndEquivalentLineNumber) {
                let viewZoneLineNumber;
                if (modifiedForeignVZ.current.afterLineNumber <= modifiedEquivalentLineNumber) {
                    viewZoneLineNumber = originalEquivalentLineNumber - modifiedEquivalentLineNumber + modifiedForeignVZ.current.afterLineNumber;
                }
                else {
                    viewZoneLineNumber = originalEndEquivalentLineNumber;
                }
                let marginDomNode = null;
                if (lineChange && lineChange.modifiedStartLineNumber <= modifiedForeignVZ.current.afterLineNumber && modifiedForeignVZ.current.afterLineNumber <= lineChange.modifiedEndLineNumber) {
                    marginDomNode = this._createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion();
                }
                stepOriginal.push({
                    afterLineNumber: viewZoneLineNumber,
                    heightInLines: modifiedForeignVZ.current.height / modifiedLineHeight,
                    domNode: null,
                    marginDomNode: marginDomNode
                });
                modifiedForeignVZ.advance();
            }
            // [PRODUCE] View zone(s) in modified-side due to foreign view zone(s) in original-side
            while (originalForeignVZ.current && originalForeignVZ.current.afterLineNumber <= originalEndEquivalentLineNumber) {
                let viewZoneLineNumber;
                if (originalForeignVZ.current.afterLineNumber <= originalEquivalentLineNumber) {
                    viewZoneLineNumber = modifiedEquivalentLineNumber - originalEquivalentLineNumber + originalForeignVZ.current.afterLineNumber;
                }
                else {
                    viewZoneLineNumber = modifiedEndEquivalentLineNumber;
                }
                stepModified.push({
                    afterLineNumber: viewZoneLineNumber,
                    heightInLines: originalForeignVZ.current.height / originalLineHeight,
                    domNode: null
                });
                originalForeignVZ.advance();
            }
            if (lineChange !== null && isChangeOrInsert(lineChange)) {
                const r = this._produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength);
                if (r) {
                    stepOriginal.push(r);
                }
            }
            if (lineChange !== null && isChangeOrDelete(lineChange)) {
                const r = this._produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength);
                if (r) {
                    stepModified.push(r);
                }
            }
            // ---------------------------- END PRODUCE VIEW ZONES
            // ---------------------------- EMIT MINIMAL VIEW ZONES
            // [CANCEL & EMIT] Try to cancel view zones out
            let stepOriginalIndex = 0;
            let stepModifiedIndex = 0;
            stepOriginal = stepOriginal.sort(sortMyViewZones);
            stepModified = stepModified.sort(sortMyViewZones);
            while (stepOriginalIndex < stepOriginal.length && stepModifiedIndex < stepModified.length) {
                const original = stepOriginal[stepOriginalIndex];
                const modified = stepModified[stepModifiedIndex];
                const originalDelta = original.afterLineNumber - originalEquivalentLineNumber;
                const modifiedDelta = modified.afterLineNumber - modifiedEquivalentLineNumber;
                if (originalDelta < modifiedDelta) {
                    addAndCombineIfPossible(result.original, original);
                    stepOriginalIndex++;
                }
                else if (modifiedDelta < originalDelta) {
                    addAndCombineIfPossible(result.modified, modified);
                    stepModifiedIndex++;
                }
                else if (original.shouldNotShrink) {
                    addAndCombineIfPossible(result.original, original);
                    stepOriginalIndex++;
                }
                else if (modified.shouldNotShrink) {
                    addAndCombineIfPossible(result.modified, modified);
                    stepModifiedIndex++;
                }
                else {
                    if (original.heightInLines >= modified.heightInLines) {
                        // modified view zone gets removed
                        original.heightInLines -= modified.heightInLines;
                        stepModifiedIndex++;
                    }
                    else {
                        // original view zone gets removed
                        modified.heightInLines -= original.heightInLines;
                        stepOriginalIndex++;
                    }
                }
            }
            // [EMIT] Remaining original view zones
            while (stepOriginalIndex < stepOriginal.length) {
                addAndCombineIfPossible(result.original, stepOriginal[stepOriginalIndex]);
                stepOriginalIndex++;
            }
            // [EMIT] Remaining modified view zones
            while (stepModifiedIndex < stepModified.length) {
                addAndCombineIfPossible(result.modified, stepModified[stepModifiedIndex]);
                stepModifiedIndex++;
            }
            // ---------------------------- END EMIT MINIMAL VIEW ZONES
        }
        return {
            original: ViewZonesComputer._ensureDomNodes(result.original),
            modified: ViewZonesComputer._ensureDomNodes(result.modified),
        };
    }
    static _ensureDomNodes(zones) {
        return zones.map((z) => {
            if (!z.domNode) {
                z.domNode = createFakeLinesDiv();
            }
            return z;
        });
    }
}
function createDecoration(startLineNumber, startColumn, endLineNumber, endColumn, options) {
    return {
        range: new Range(startLineNumber, startColumn, endLineNumber, endColumn),
        options: options
    };
}
const DECORATIONS = {
    arrowRevertChange: ModelDecorationOptions.register({
        description: 'diff-editor-arrow-revert-change',
        glyphMarginClassName: 'arrow-revert-change ' + ThemeIcon.asClassName(Codicon.arrowRight),
    }),
    charDelete: ModelDecorationOptions.register({
        description: 'diff-editor-char-delete',
        className: 'char-delete'
    }),
    charDeleteWholeLine: ModelDecorationOptions.register({
        description: 'diff-editor-char-delete-whole-line',
        className: 'char-delete',
        isWholeLine: true
    }),
    charInsert: ModelDecorationOptions.register({
        description: 'diff-editor-char-insert',
        className: 'char-insert'
    }),
    charInsertWholeLine: ModelDecorationOptions.register({
        description: 'diff-editor-char-insert-whole-line',
        className: 'char-insert',
        isWholeLine: true
    }),
    lineInsert: ModelDecorationOptions.register({
        description: 'diff-editor-line-insert',
        className: 'line-insert',
        marginClassName: 'gutter-insert',
        isWholeLine: true
    }),
    lineInsertWithSign: ModelDecorationOptions.register({
        description: 'diff-editor-line-insert-with-sign',
        className: 'line-insert',
        linesDecorationsClassName: 'insert-sign ' + ThemeIcon.asClassName(diffInsertIcon),
        marginClassName: 'gutter-insert',
        isWholeLine: true
    }),
    lineDelete: ModelDecorationOptions.register({
        description: 'diff-editor-line-delete',
        className: 'line-delete',
        marginClassName: 'gutter-delete',
        isWholeLine: true
    }),
    lineDeleteWithSign: ModelDecorationOptions.register({
        description: 'diff-editor-line-delete-with-sign',
        className: 'line-delete',
        linesDecorationsClassName: 'delete-sign ' + ThemeIcon.asClassName(diffRemoveIcon),
        marginClassName: 'gutter-delete',
        isWholeLine: true
    }),
    lineDeleteMargin: ModelDecorationOptions.register({
        description: 'diff-editor-line-delete-margin',
        marginClassName: 'gutter-delete',
    })
};
class DiffEditorWidgetSideBySide extends DiffEditorWidgetStyle {
    constructor(dataSource, enableSplitViewResizing) {
        super(dataSource);
        this._disableSash = (enableSplitViewResizing === false);
        this._sashRatio = null;
        this._sashPosition = null;
        this._startSashPosition = null;
        this._sash = this._register(new Sash(this._dataSource.getContainerDomNode(), this, { orientation: 0 /* Orientation.VERTICAL */ }));
        if (this._disableSash) {
            this._sash.state = 0 /* SashState.Disabled */;
        }
        this._sash.onDidStart(() => this._onSashDragStart());
        this._sash.onDidChange((e) => this._onSashDrag(e));
        this._sash.onDidEnd(() => this._onSashDragEnd());
        this._sash.onDidReset(() => this._onSashReset());
    }
    setEnableSplitViewResizing(enableSplitViewResizing) {
        const newDisableSash = (enableSplitViewResizing === false);
        if (this._disableSash !== newDisableSash) {
            this._disableSash = newDisableSash;
            this._sash.state = this._disableSash ? 0 /* SashState.Disabled */ : 3 /* SashState.Enabled */;
        }
    }
    layout(sashRatio = this._sashRatio) {
        const w = this._dataSource.getWidth();
        const contentWidth = w - (this._dataSource.getOptions().renderOverviewRuler ? DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH : 0);
        let sashPosition = Math.floor((sashRatio || 0.5) * contentWidth);
        const midPoint = Math.floor(0.5 * contentWidth);
        sashPosition = this._disableSash ? midPoint : sashPosition || midPoint;
        if (contentWidth > DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH * 2) {
            if (sashPosition < DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) {
                sashPosition = DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH;
            }
            if (sashPosition > contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) {
                sashPosition = contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH;
            }
        }
        else {
            sashPosition = midPoint;
        }
        if (this._sashPosition !== sashPosition) {
            this._sashPosition = sashPosition;
        }
        this._sash.layout();
        return this._sashPosition;
    }
    _onSashDragStart() {
        this._startSashPosition = this._sashPosition;
    }
    _onSashDrag(e) {
        const w = this._dataSource.getWidth();
        const contentWidth = w - (this._dataSource.getOptions().renderOverviewRuler ? DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH : 0);
        const sashPosition = this.layout((this._startSashPosition + (e.currentX - e.startX)) / contentWidth);
        this._sashRatio = sashPosition / contentWidth;
        this._dataSource.relayoutEditors();
    }
    _onSashDragEnd() {
        this._sash.layout();
    }
    _onSashReset() {
        this._sashRatio = 0.5;
        this._dataSource.relayoutEditors();
        this._sash.layout();
    }
    getVerticalSashTop(sash) {
        return 0;
    }
    getVerticalSashLeft(sash) {
        return this._sashPosition;
    }
    getVerticalSashHeight(sash) {
        return this._dataSource.getHeight();
    }
    _getViewZones(lineChanges, originalForeignVZ, modifiedForeignVZ) {
        const originalEditor = this._dataSource.getOriginalEditor();
        const modifiedEditor = this._dataSource.getModifiedEditor();
        const c = new SideBySideViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
        return c.getViewZones();
    }
    _getOriginalEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators) {
        const originalEditor = this._dataSource.getOriginalEditor();
        const overviewZoneColor = String(this._removeColor);
        const result = {
            decorations: [],
            overviewZones: []
        };
        const originalModel = originalEditor.getModel();
        const originalViewModel = originalEditor._getViewModel();
        for (const lineChange of lineChanges) {
            if (isChangeOrDelete(lineChange)) {
                result.decorations.push({
                    range: new Range(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
                    options: (renderIndicators ? DECORATIONS.lineDeleteWithSign : DECORATIONS.lineDelete)
                });
                if (!isChangeOrInsert(lineChange) || !lineChange.charChanges) {
                    result.decorations.push(createDecoration(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, DECORATIONS.charDeleteWholeLine));
                }
                const viewRange = getViewRange(originalModel, originalViewModel, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
                result.overviewZones.push(new OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, /*use endLineNumber*/ 0, overviewZoneColor));
                if (lineChange.charChanges) {
                    for (const charChange of lineChange.charChanges) {
                        if (isCharChangeOrDelete(charChange)) {
                            if (ignoreTrimWhitespace) {
                                for (let lineNumber = charChange.originalStartLineNumber; lineNumber <= charChange.originalEndLineNumber; lineNumber++) {
                                    let startColumn;
                                    let endColumn;
                                    if (lineNumber === charChange.originalStartLineNumber) {
                                        startColumn = charChange.originalStartColumn;
                                    }
                                    else {
                                        startColumn = originalModel.getLineFirstNonWhitespaceColumn(lineNumber);
                                    }
                                    if (lineNumber === charChange.originalEndLineNumber) {
                                        endColumn = charChange.originalEndColumn;
                                    }
                                    else {
                                        endColumn = originalModel.getLineLastNonWhitespaceColumn(lineNumber);
                                    }
                                    result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charDelete));
                                }
                            }
                            else {
                                result.decorations.push(createDecoration(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn, DECORATIONS.charDelete));
                            }
                        }
                    }
                }
            }
        }
        return result;
    }
    _getModifiedEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators, renderMarginRevertIcon) {
        const modifiedEditor = this._dataSource.getModifiedEditor();
        const overviewZoneColor = String(this._insertColor);
        const result = {
            decorations: [],
            overviewZones: []
        };
        const modifiedModel = modifiedEditor.getModel();
        const modifiedViewModel = modifiedEditor._getViewModel();
        for (const lineChange of lineChanges) {
            // Arrows for reverting changes.
            if (renderMarginRevertIcon) {
                if (lineChange.modifiedEndLineNumber > 0) {
                    result.decorations.push({
                        range: new Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedStartLineNumber, 1),
                        options: DECORATIONS.arrowRevertChange
                    });
                }
                else {
                    const viewZone = zones.modified.find(z => z.afterLineNumber === lineChange.modifiedStartLineNumber);
                    if (viewZone) {
                        viewZone.marginDomNode = createViewZoneMarginArrow();
                    }
                }
            }
            if (isChangeOrInsert(lineChange)) {
                result.decorations.push({
                    range: new Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
                    options: (renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert)
                });
                if (!isChangeOrDelete(lineChange) || !lineChange.charChanges) {
                    result.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, DECORATIONS.charInsertWholeLine));
                }
                const viewRange = getViewRange(modifiedModel, modifiedViewModel, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
                result.overviewZones.push(new OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, /*use endLineNumber*/ 0, overviewZoneColor));
                if (lineChange.charChanges) {
                    for (const charChange of lineChange.charChanges) {
                        if (isCharChangeOrInsert(charChange)) {
                            if (ignoreTrimWhitespace) {
                                for (let lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) {
                                    let startColumn;
                                    let endColumn;
                                    if (lineNumber === charChange.modifiedStartLineNumber) {
                                        startColumn = charChange.modifiedStartColumn;
                                    }
                                    else {
                                        startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber);
                                    }
                                    if (lineNumber === charChange.modifiedEndLineNumber) {
                                        endColumn = charChange.modifiedEndColumn;
                                    }
                                    else {
                                        endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber);
                                    }
                                    result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert));
                                }
                            }
                            else {
                                result.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert));
                            }
                        }
                    }
                }
            }
        }
        return result;
    }
}
DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH = 100;
class SideBySideViewZonesComputer extends ViewZonesComputer {
    constructor(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor) {
        super(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
    }
    _createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion() {
        return null;
    }
    _produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
        if (lineChangeModifiedLength > lineChangeOriginalLength) {
            return {
                afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber),
                heightInLines: (lineChangeModifiedLength - lineChangeOriginalLength),
                domNode: null
            };
        }
        return null;
    }
    _produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
        if (lineChangeOriginalLength > lineChangeModifiedLength) {
            return {
                afterLineNumber: Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber),
                heightInLines: (lineChangeOriginalLength - lineChangeModifiedLength),
                domNode: null
            };
        }
        return null;
    }
}
class DiffEditorWidgetInline extends DiffEditorWidgetStyle {
    constructor(dataSource, enableSplitViewResizing) {
        super(dataSource);
        this._decorationsLeft = dataSource.getOriginalEditor().getLayoutInfo().decorationsLeft;
        this._register(dataSource.getOriginalEditor().onDidLayoutChange((layoutInfo) => {
            if (this._decorationsLeft !== layoutInfo.decorationsLeft) {
                this._decorationsLeft = layoutInfo.decorationsLeft;
                dataSource.relayoutEditors();
            }
        }));
    }
    setEnableSplitViewResizing(enableSplitViewResizing) {
        // Nothing to do..
    }
    _getViewZones(lineChanges, originalForeignVZ, modifiedForeignVZ, renderIndicators) {
        const originalEditor = this._dataSource.getOriginalEditor();
        const modifiedEditor = this._dataSource.getModifiedEditor();
        const computer = new InlineViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators);
        return computer.getViewZones();
    }
    _getOriginalEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators) {
        const overviewZoneColor = String(this._removeColor);
        const result = {
            decorations: [],
            overviewZones: []
        };
        const originalEditor = this._dataSource.getOriginalEditor();
        const originalModel = originalEditor.getModel();
        const originalViewModel = originalEditor._getViewModel();
        let zoneIndex = 0;
        for (const lineChange of lineChanges) {
            // Add overview zones in the overview ruler
            if (isChangeOrDelete(lineChange)) {
                result.decorations.push({
                    range: new Range(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
                    options: DECORATIONS.lineDeleteMargin
                });
                while (zoneIndex < zones.modified.length) {
                    const zone = zones.modified[zoneIndex];
                    if (zone.diff && zone.diff.originalStartLineNumber >= lineChange.originalStartLineNumber) {
                        break;
                    }
                    zoneIndex++;
                }
                let zoneHeightInLines = 0;
                if (zoneIndex < zones.modified.length) {
                    const zone = zones.modified[zoneIndex];
                    if (zone.diff
                        && zone.diff.originalStartLineNumber === lineChange.originalStartLineNumber
                        && zone.diff.originalEndLineNumber === lineChange.originalEndLineNumber
                        && zone.diff.modifiedStartLineNumber === lineChange.modifiedStartLineNumber
                        && zone.diff.modifiedEndLineNumber === lineChange.modifiedEndLineNumber) {
                        zoneHeightInLines = zone.heightInLines;
                    }
                }
                const viewRange = getViewRange(originalModel, originalViewModel, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
                result.overviewZones.push(new OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, zoneHeightInLines, overviewZoneColor));
            }
        }
        return result;
    }
    _getModifiedEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators, renderMarginRevertIcon) {
        const modifiedEditor = this._dataSource.getModifiedEditor();
        const overviewZoneColor = String(this._insertColor);
        const result = {
            decorations: [],
            overviewZones: []
        };
        const modifiedModel = modifiedEditor.getModel();
        const modifiedViewModel = modifiedEditor._getViewModel();
        for (const lineChange of lineChanges) {
            // Add decorations & overview zones
            if (isChangeOrInsert(lineChange)) {
                result.decorations.push({
                    range: new Range(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
                    options: (renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert)
                });
                const viewRange = getViewRange(modifiedModel, modifiedViewModel, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
                result.overviewZones.push(new OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, /*use endLineNumber*/ 0, overviewZoneColor));
                if (lineChange.charChanges) {
                    for (const charChange of lineChange.charChanges) {
                        if (isCharChangeOrInsert(charChange)) {
                            if (ignoreTrimWhitespace) {
                                for (let lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) {
                                    let startColumn;
                                    let endColumn;
                                    if (lineNumber === charChange.modifiedStartLineNumber) {
                                        startColumn = charChange.modifiedStartColumn;
                                    }
                                    else {
                                        startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber);
                                    }
                                    if (lineNumber === charChange.modifiedEndLineNumber) {
                                        endColumn = charChange.modifiedEndColumn;
                                    }
                                    else {
                                        endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber);
                                    }
                                    result.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert));
                                }
                            }
                            else {
                                result.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert));
                            }
                        }
                    }
                }
                else {
                    result.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */, DECORATIONS.charInsertWholeLine));
                }
            }
        }
        return result;
    }
    layout() {
        // An editor should not be smaller than 5px
        return Math.max(5, this._decorationsLeft);
    }
}
class InlineViewZonesComputer extends ViewZonesComputer {
    constructor(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators) {
        super(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
        this._originalModel = originalEditor.getModel();
        this._renderIndicators = renderIndicators;
        this._pendingLineChange = [];
        this._pendingViewZones = [];
        this._lineBreaksComputer = this._modifiedEditor._getViewModel().createLineBreaksComputer();
    }
    getViewZones() {
        const result = super.getViewZones();
        this._finalize(result);
        return result;
    }
    _createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion() {
        const result = document.createElement('div');
        result.className = 'inline-added-margin-view-zone';
        return result;
    }
    _produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
        const marginDomNode = document.createElement('div');
        marginDomNode.className = 'inline-added-margin-view-zone';
        return {
            afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber),
            heightInLines: lineChangeModifiedLength,
            domNode: document.createElement('div'),
            marginDomNode: marginDomNode
        };
    }
    _produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
        const domNode = document.createElement('div');
        domNode.className = `view-lines line-delete ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`;
        const marginDomNode = document.createElement('div');
        marginDomNode.className = 'inline-deleted-margin-view-zone';
        const viewZone = {
            shouldNotShrink: true,
            afterLineNumber: (lineChange.modifiedEndLineNumber === 0 ? lineChange.modifiedStartLineNumber : lineChange.modifiedStartLineNumber - 1),
            heightInLines: lineChangeOriginalLength,
            minWidthInPx: 0,
            domNode: domNode,
            marginDomNode: marginDomNode,
            diff: {
                originalStartLineNumber: lineChange.originalStartLineNumber,
                originalEndLineNumber: lineChange.originalEndLineNumber,
                modifiedStartLineNumber: lineChange.modifiedStartLineNumber,
                modifiedEndLineNumber: lineChange.modifiedEndLineNumber,
                originalModel: this._originalModel,
                viewLineCounts: null,
            }
        };
        for (let lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) {
            this._lineBreaksComputer.addRequest(this._originalModel.getLineContent(lineNumber), null, null);
        }
        this._pendingLineChange.push(lineChange);
        this._pendingViewZones.push(viewZone);
        return viewZone;
    }
    _finalize(result) {
        const modifiedEditorOptions = this._modifiedEditor.getOptions();
        const tabSize = this._modifiedEditor.getModel().getOptions().tabSize;
        const fontInfo = modifiedEditorOptions.get(46 /* EditorOption.fontInfo */);
        const disableMonospaceOptimizations = modifiedEditorOptions.get(29 /* EditorOption.disableMonospaceOptimizations */);
        const typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
        const scrollBeyondLastColumn = modifiedEditorOptions.get(95 /* EditorOption.scrollBeyondLastColumn */);
        const mightContainNonBasicASCII = this._originalModel.mightContainNonBasicASCII();
        const mightContainRTL = this._originalModel.mightContainRTL();
        const lineHeight = modifiedEditorOptions.get(61 /* EditorOption.lineHeight */);
        const layoutInfo = modifiedEditorOptions.get(133 /* EditorOption.layoutInfo */);
        const lineDecorationsWidth = layoutInfo.decorationsWidth;
        const stopRenderingLineAfter = modifiedEditorOptions.get(107 /* EditorOption.stopRenderingLineAfter */);
        const renderWhitespace = modifiedEditorOptions.get(90 /* EditorOption.renderWhitespace */);
        const renderControlCharacters = modifiedEditorOptions.get(85 /* EditorOption.renderControlCharacters */);
        const fontLigatures = modifiedEditorOptions.get(47 /* EditorOption.fontLigatures */);
        const lineBreaks = this._lineBreaksComputer.finalize();
        let lineBreakIndex = 0;
        for (let i = 0; i < this._pendingLineChange.length; i++) {
            const lineChange = this._pendingLineChange[i];
            const viewZone = this._pendingViewZones[i];
            const domNode = viewZone.domNode;
            applyFontInfo(domNode, fontInfo);
            const marginDomNode = viewZone.marginDomNode;
            applyFontInfo(marginDomNode, fontInfo);
            const decorations = [];
            if (lineChange.charChanges) {
                for (const charChange of lineChange.charChanges) {
                    if (isCharChangeOrDelete(charChange)) {
                        decorations.push(new InlineDecoration(new Range(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn), 'char-delete', 0 /* InlineDecorationType.Regular */));
                    }
                }
            }
            const hasCharChanges = (decorations.length > 0);
            const sb = createStringBuilder(10000);
            let maxCharsPerLine = 0;
            let renderedLineCount = 0;
            let viewLineCounts = null;
            for (let lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) {
                const lineIndex = lineNumber - lineChange.originalStartLineNumber;
                const lineTokens = this._originalModel.tokenization.getLineTokens(lineNumber);
                const lineContent = lineTokens.getLineContent();
                const lineBreakData = lineBreaks[lineBreakIndex++];
                const actualDecorations = LineDecoration.filter(decorations, lineNumber, 1, lineContent.length + 1);
                if (lineBreakData) {
                    let lastBreakOffset = 0;
                    for (const breakOffset of lineBreakData.breakOffsets) {
                        const viewLineTokens = lineTokens.sliceAndInflate(lastBreakOffset, breakOffset, 0);
                        const viewLineContent = lineContent.substring(lastBreakOffset, breakOffset);
                        maxCharsPerLine = Math.max(maxCharsPerLine, this._renderOriginalLine(renderedLineCount++, viewLineContent, viewLineTokens, LineDecoration.extractWrapped(actualDecorations, lastBreakOffset, breakOffset), hasCharChanges, mightContainNonBasicASCII, mightContainRTL, fontInfo, disableMonospaceOptimizations, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, tabSize, sb, marginDomNode));
                        lastBreakOffset = breakOffset;
                    }
                    if (!viewLineCounts) {
                        viewLineCounts = [];
                    }
                    // make sure all lines before this one have an entry in `viewLineCounts`
                    while (viewLineCounts.length < lineIndex) {
                        viewLineCounts[viewLineCounts.length] = 1;
                    }
                    viewLineCounts[lineIndex] = lineBreakData.breakOffsets.length;
                    viewZone.heightInLines += (lineBreakData.breakOffsets.length - 1);
                    const marginDomNode2 = document.createElement('div');
                    marginDomNode2.className = 'gutter-delete';
                    result.original.push({
                        afterLineNumber: lineNumber,
                        afterColumn: 0,
                        heightInLines: lineBreakData.breakOffsets.length - 1,
                        domNode: createFakeLinesDiv(),
                        marginDomNode: marginDomNode2
                    });
                }
                else {
                    maxCharsPerLine = Math.max(maxCharsPerLine, this._renderOriginalLine(renderedLineCount++, lineContent, lineTokens, actualDecorations, hasCharChanges, mightContainNonBasicASCII, mightContainRTL, fontInfo, disableMonospaceOptimizations, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, tabSize, sb, marginDomNode));
                }
            }
            maxCharsPerLine += scrollBeyondLastColumn;
            const html = sb.build();
            const trustedhtml = diffEditorWidget_ttPolicy ? diffEditorWidget_ttPolicy.createHTML(html) : html;
            domNode.innerHTML = trustedhtml;
            viewZone.minWidthInPx = (maxCharsPerLine * typicalHalfwidthCharacterWidth);
            if (viewLineCounts) {
                // make sure all lines have an entry in `viewLineCounts`
                const cnt = lineChange.originalEndLineNumber - lineChange.originalStartLineNumber;
                while (viewLineCounts.length <= cnt) {
                    viewLineCounts[viewLineCounts.length] = 1;
                }
            }
            viewZone.diff.viewLineCounts = viewLineCounts;
        }
        result.original.sort((a, b) => {
            return a.afterLineNumber - b.afterLineNumber;
        });
    }
    _renderOriginalLine(renderedLineCount, lineContent, lineTokens, decorations, hasCharChanges, mightContainNonBasicASCII, mightContainRTL, fontInfo, disableMonospaceOptimizations, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, tabSize, sb, marginDomNode) {
        sb.appendASCIIString('<div class="view-line');
        if (!hasCharChanges) {
            // No char changes
            sb.appendASCIIString(' char-delete');
        }
        sb.appendASCIIString('" style="top:');
        sb.appendASCIIString(String(renderedLineCount * lineHeight));
        sb.appendASCIIString('px;width:1000000px;">');
        const isBasicASCII = ViewLineRenderingData.isBasicASCII(lineContent, mightContainNonBasicASCII);
        const containsRTL = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII, mightContainRTL);
        const output = renderViewLine(new RenderLineInput((fontInfo.isMonospace && !disableMonospaceOptimizations), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII, containsRTL, 0, lineTokens, decorations, tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures !== EditorFontLigatures.OFF, null // Send no selections, original line cannot be selected
        ), sb);
        sb.appendASCIIString('</div>');
        if (this._renderIndicators) {
            const marginElement = document.createElement('div');
            marginElement.className = `delete-sign ${ThemeIcon.asClassName(diffRemoveIcon)}`;
            marginElement.setAttribute('style', `position:absolute;top:${renderedLineCount * lineHeight}px;width:${lineDecorationsWidth}px;height:${lineHeight}px;right:0;`);
            marginDomNode.appendChild(marginElement);
        }
        return output.characterMapping.getHorizontalOffset(output.characterMapping.length);
    }
}
function validateDiffWordWrap(value, defaultValue) {
    return stringSet(value, defaultValue, ['off', 'on', 'inherit']);
}
function isChangeOrInsert(lineChange) {
    return lineChange.modifiedEndLineNumber > 0;
}
function isChangeOrDelete(lineChange) {
    return lineChange.originalEndLineNumber > 0;
}
function isCharChangeOrInsert(charChange) {
    if (charChange.modifiedStartLineNumber === charChange.modifiedEndLineNumber) {
        return charChange.modifiedEndColumn - charChange.modifiedStartColumn > 0;
    }
    return charChange.modifiedEndLineNumber - charChange.modifiedStartLineNumber > 0;
}
function isCharChangeOrDelete(charChange) {
    if (charChange.originalStartLineNumber === charChange.originalEndLineNumber) {
        return charChange.originalEndColumn - charChange.originalStartColumn > 0;
    }
    return charChange.originalEndLineNumber - charChange.originalStartLineNumber > 0;
}
function createFakeLinesDiv() {
    const r = document.createElement('div');
    r.className = 'diagonal-fill';
    return r;
}
function createViewZoneMarginArrow() {
    const arrow = document.createElement('div');
    arrow.className = 'arrow-revert-change ' + ThemeIcon.asClassName(Codicon.arrowRight);
    return dom_$('div', {}, arrow);
}
function getViewRange(model, viewModel, startLineNumber, endLineNumber) {
    const lineCount = model.getLineCount();
    startLineNumber = Math.min(lineCount, Math.max(1, startLineNumber));
    endLineNumber = Math.min(lineCount, Math.max(1, endLineNumber));
    return viewModel.coordinatesConverter.convertModelRangeToViewRange(new Range(startLineNumber, model.getLineMinColumn(startLineNumber), endLineNumber, model.getLineMaxColumn(endLineNumber)));
}
function validateDiffEditorOptions(options, defaults) {
    return {
        enableSplitViewResizing: editorOptions_boolean(options.enableSplitViewResizing, defaults.enableSplitViewResizing),
        renderSideBySide: editorOptions_boolean(options.renderSideBySide, defaults.renderSideBySide),
        renderMarginRevertIcon: editorOptions_boolean(options.renderMarginRevertIcon, defaults.renderMarginRevertIcon),
        maxComputationTime: clampedInt(options.maxComputationTime, defaults.maxComputationTime, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
        maxFileSize: clampedInt(options.maxFileSize, defaults.maxFileSize, 0, 1073741824 /* Constants.MAX_SAFE_SMALL_INTEGER */),
        ignoreTrimWhitespace: editorOptions_boolean(options.ignoreTrimWhitespace, defaults.ignoreTrimWhitespace),
        renderIndicators: editorOptions_boolean(options.renderIndicators, defaults.renderIndicators),
        originalEditable: editorOptions_boolean(options.originalEditable, defaults.originalEditable),
        diffCodeLens: editorOptions_boolean(options.diffCodeLens, defaults.diffCodeLens),
        renderOverviewRuler: editorOptions_boolean(options.renderOverviewRuler, defaults.renderOverviewRuler),
        diffWordWrap: validateDiffWordWrap(options.diffWordWrap, defaults.diffWordWrap),
    };
}
function changedDiffEditorOptions(a, b) {
    return {
        enableSplitViewResizing: (a.enableSplitViewResizing !== b.enableSplitViewResizing),
        renderSideBySide: (a.renderSideBySide !== b.renderSideBySide),
        renderMarginRevertIcon: (a.renderMarginRevertIcon !== b.renderMarginRevertIcon),
        maxComputationTime: (a.maxComputationTime !== b.maxComputationTime),
        maxFileSize: (a.maxFileSize !== b.maxFileSize),
        ignoreTrimWhitespace: (a.ignoreTrimWhitespace !== b.ignoreTrimWhitespace),
        renderIndicators: (a.renderIndicators !== b.renderIndicators),
        originalEditable: (a.originalEditable !== b.originalEditable),
        diffCodeLens: (a.diffCodeLens !== b.diffCodeLens),
        renderOverviewRuler: (a.renderOverviewRuler !== b.renderOverviewRuler),
        diffWordWrap: (a.diffWordWrap !== b.diffWordWrap),
    };
}
registerThemingParticipant((theme, collector) => {
    const added = theme.getColor(diffInserted);
    if (added) {
        collector.addRule(`.monaco-editor .char-insert, .monaco-diff-editor .char-insert { background-color: ${added}; }`);
    }
    const lineAdded = theme.getColor(diffInsertedLine) || added;
    if (lineAdded) {
        collector.addRule(`.monaco-editor .line-insert, .monaco-diff-editor .line-insert { background-color: ${lineAdded}; }`);
    }
    const gutterAdded = theme.getColor(diffInsertedLineGutter) || lineAdded;
    if (gutterAdded) {
        collector.addRule(`.monaco-editor .inline-added-margin-view-zone { background-color: ${gutterAdded}; }`);
        collector.addRule(`.monaco-editor .gutter-insert, .monaco-diff-editor .gutter-insert { background-color: ${gutterAdded}; }`);
    }
    const removed = theme.getColor(diffRemoved);
    if (removed) {
        collector.addRule(`.monaco-editor .char-delete, .monaco-diff-editor .char-delete { background-color: ${removed}; }`);
    }
    const lineRemoved = theme.getColor(diffRemovedLine) || removed;
    if (lineRemoved) {
        collector.addRule(`.monaco-editor .line-delete, .monaco-diff-editor .line-delete { background-color: ${lineRemoved}; }`);
    }
    const gutterRemoved = theme.getColor(diffRemovedLineGutter) || lineRemoved;
    if (gutterRemoved) {
        collector.addRule(`.monaco-editor .inline-deleted-margin-view-zone { background-color: ${gutterRemoved}; }`);
        collector.addRule(`.monaco-editor .gutter-delete, .monaco-diff-editor .gutter-delete { background-color: ${gutterRemoved}; }`);
    }
    const addedOutline = theme.getColor(diffInsertedOutline);
    if (addedOutline) {
        collector.addRule(`.monaco-editor .line-insert, .monaco-editor .char-insert { border: 1px ${isHighContrast(theme.type) ? 'dashed' : 'solid'} ${addedOutline}; }`);
    }
    const removedOutline = theme.getColor(diffRemovedOutline);
    if (removedOutline) {
        collector.addRule(`.monaco-editor .line-delete, .monaco-editor .char-delete { border: 1px ${isHighContrast(theme.type) ? 'dashed' : 'solid'} ${removedOutline}; }`);
    }
    const shadow = theme.getColor(scrollbarShadow);
    if (shadow) {
        collector.addRule(`.monaco-diff-editor.side-by-side .editor.modified { box-shadow: -6px 0 5px -5px ${shadow}; }`);
    }
    const border = theme.getColor(diffBorder);
    if (border) {
        collector.addRule(`.monaco-diff-editor.side-by-side .editor.modified { border-left: 1px solid ${border}; }`);
    }
    const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground);
    if (scrollbarSliderBackgroundColor) {
        collector.addRule(`
			.monaco-diff-editor .diffViewport {
				background: ${scrollbarSliderBackgroundColor};
			}
		`);
    }
    const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground);
    if (scrollbarSliderHoverBackgroundColor) {
        collector.addRule(`
			.monaco-diff-editor .diffViewport:hover {
				background: ${scrollbarSliderHoverBackgroundColor};
			}
		`);
    }
    const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground);
    if (scrollbarSliderActiveBackgroundColor) {
        collector.addRule(`
			.monaco-diff-editor .diffViewport:active {
				background: ${scrollbarSliderActiveBackgroundColor};
			}
		`);
    }
    const diffDiagonalFillColor = theme.getColor(diffDiagonalFill);
    collector.addRule(`
	.monaco-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;
	}
	`);
});

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/services/abstractCodeEditorService.js
var abstractCodeEditorService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var abstractCodeEditorService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var abstractCodeEditorService_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};




let AbstractCodeEditorService = class AbstractCodeEditorService extends Disposable {
    constructor(_themeService) {
        super();
        this._themeService = _themeService;
        this._onCodeEditorAdd = this._register(new Emitter());
        this.onCodeEditorAdd = this._onCodeEditorAdd.event;
        this._onCodeEditorRemove = this._register(new Emitter());
        this.onCodeEditorRemove = this._onCodeEditorRemove.event;
        this._onDiffEditorAdd = this._register(new Emitter());
        this.onDiffEditorAdd = this._onDiffEditorAdd.event;
        this._onDiffEditorRemove = this._register(new Emitter());
        this.onDiffEditorRemove = this._onDiffEditorRemove.event;
        this._decorationOptionProviders = new Map();
        this._codeEditorOpenHandlers = new LinkedList();
        this._modelProperties = new Map();
        this._codeEditors = Object.create(null);
        this._diffEditors = Object.create(null);
        this._globalStyleSheet = null;
    }
    addCodeEditor(editor) {
        this._codeEditors[editor.getId()] = editor;
        this._onCodeEditorAdd.fire(editor);
    }
    removeCodeEditor(editor) {
        if (delete this._codeEditors[editor.getId()]) {
            this._onCodeEditorRemove.fire(editor);
        }
    }
    listCodeEditors() {
        return Object.keys(this._codeEditors).map(id => this._codeEditors[id]);
    }
    addDiffEditor(editor) {
        this._diffEditors[editor.getId()] = editor;
        this._onDiffEditorAdd.fire(editor);
    }
    removeDiffEditor(editor) {
        if (delete this._diffEditors[editor.getId()]) {
            this._onDiffEditorRemove.fire(editor);
        }
    }
    listDiffEditors() {
        return Object.keys(this._diffEditors).map(id => this._diffEditors[id]);
    }
    getFocusedCodeEditor() {
        let editorWithWidgetFocus = null;
        const editors = this.listCodeEditors();
        for (const editor of editors) {
            if (editor.hasTextFocus()) {
                // bingo!
                return editor;
            }
            if (editor.hasWidgetFocus()) {
                editorWithWidgetFocus = editor;
            }
        }
        return editorWithWidgetFocus;
    }
    removeDecorationType(key) {
        const provider = this._decorationOptionProviders.get(key);
        if (provider) {
            provider.refCount--;
            if (provider.refCount <= 0) {
                this._decorationOptionProviders.delete(key);
                provider.dispose();
                this.listCodeEditors().forEach((ed) => ed.removeDecorationsByType(key));
            }
        }
    }
    setModelProperty(resource, key, value) {
        const key1 = resource.toString();
        let dest;
        if (this._modelProperties.has(key1)) {
            dest = this._modelProperties.get(key1);
        }
        else {
            dest = new Map();
            this._modelProperties.set(key1, dest);
        }
        dest.set(key, value);
    }
    getModelProperty(resource, key) {
        const key1 = resource.toString();
        if (this._modelProperties.has(key1)) {
            const innerMap = this._modelProperties.get(key1);
            return innerMap.get(key);
        }
        return undefined;
    }
    openCodeEditor(input, source, sideBySide) {
        return abstractCodeEditorService_awaiter(this, void 0, void 0, function* () {
            for (const handler of this._codeEditorOpenHandlers) {
                const candidate = yield handler(input, source, sideBySide);
                if (candidate !== null) {
                    return candidate;
                }
            }
            return null;
        });
    }
    registerCodeEditorOpenHandler(handler) {
        const rm = this._codeEditorOpenHandlers.unshift(handler);
        return toDisposable(rm);
    }
};
AbstractCodeEditorService = abstractCodeEditorService_decorate([
    abstractCodeEditorService_param(0, IThemeService)
], AbstractCodeEditorService);

class GlobalStyleSheet {
    constructor(styleSheet) {
        this._styleSheet = styleSheet;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/standaloneCodeEditorService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var standaloneCodeEditorService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var standaloneCodeEditorService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var standaloneCodeEditorService_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};







let StandaloneCodeEditorService = class StandaloneCodeEditorService extends AbstractCodeEditorService {
    constructor(contextKeyService, themeService) {
        super(themeService);
        this.onCodeEditorAdd(() => this._checkContextKey());
        this.onCodeEditorRemove(() => this._checkContextKey());
        this._editorIsOpen = contextKeyService.createKey('editorIsOpen', false);
        this._activeCodeEditor = null;
        this.registerCodeEditorOpenHandler((input, source, sideBySide) => standaloneCodeEditorService_awaiter(this, void 0, void 0, function* () {
            if (!source) {
                return null;
            }
            return this.doOpenEditor(source, input);
        }));
    }
    _checkContextKey() {
        let hasCodeEditor = false;
        for (const editor of this.listCodeEditors()) {
            if (!editor.isSimpleWidget) {
                hasCodeEditor = true;
                break;
            }
        }
        this._editorIsOpen.set(hasCodeEditor);
    }
    setActiveCodeEditor(activeCodeEditor) {
        this._activeCodeEditor = activeCodeEditor;
    }
    getActiveCodeEditor() {
        return this._activeCodeEditor;
    }
    doOpenEditor(editor, input) {
        const model = this.findModel(editor, input.resource);
        if (!model) {
            if (input.resource) {
                const schema = input.resource.scheme;
                if (schema === Schemas.http || schema === Schemas.https) {
                    // This is a fully qualified http or https URL
                    windowOpenNoOpener(input.resource.toString());
                    return editor;
                }
            }
            return null;
        }
        const selection = (input.options ? input.options.selection : null);
        if (selection) {
            if (typeof selection.endLineNumber === 'number' && typeof selection.endColumn === 'number') {
                editor.setSelection(selection);
                editor.revealRangeInCenter(selection, 1 /* ScrollType.Immediate */);
            }
            else {
                const pos = {
                    lineNumber: selection.startLineNumber,
                    column: selection.startColumn
                };
                editor.setPosition(pos);
                editor.revealPositionInCenter(pos, 1 /* ScrollType.Immediate */);
            }
        }
        return editor;
    }
    findModel(editor, resource) {
        const model = editor.getModel();
        if (model && model.uri.toString() !== resource.toString()) {
            return null;
        }
        return model;
    }
};
StandaloneCodeEditorService = standaloneCodeEditorService_decorate([
    standaloneCodeEditorService_param(0, IContextKeyService),
    standaloneCodeEditorService_param(1, IThemeService)
], StandaloneCodeEditorService);

registerSingleton(ICodeEditorService, StandaloneCodeEditorService);

;// ../../node_modules/monaco-editor/esm/vs/platform/layout/browser/layoutService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const ILayoutService = createDecorator('layoutService');

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/standaloneLayoutService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var standaloneLayoutService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var standaloneLayoutService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};





let StandaloneLayoutService = class StandaloneLayoutService {
    constructor(_codeEditorService) {
        this._codeEditorService = _codeEditorService;
        this.onDidLayout = Event.None;
        this.offset = { top: 0, quickPickTop: 0 };
    }
    get dimension() {
        if (!this._dimension) {
            this._dimension = getClientArea(window.document.body);
        }
        return this._dimension;
    }
    get hasContainer() {
        return false;
    }
    get container() {
        // On a page, multiple editors can be created. Therefore, there are multiple containers, not
        // just a single one. Please use `ICodeEditorService` to get the current focused code editor
        // and use its container if necessary. You can also instantiate `EditorScopedLayoutService`
        // which implements `ILayoutService` but is not a part of the service collection because
        // it is code editor instance specific.
        throw new Error(`ILayoutService.container is not available in the standalone editor!`);
    }
    focus() {
        var _a;
        (_a = this._codeEditorService.getFocusedCodeEditor()) === null || _a === void 0 ? void 0 : _a.focus();
    }
};
StandaloneLayoutService = standaloneLayoutService_decorate([
    standaloneLayoutService_param(0, ICodeEditorService)
], StandaloneLayoutService);
let EditorScopedLayoutService = class EditorScopedLayoutService extends StandaloneLayoutService {
    constructor(_container, codeEditorService) {
        super(codeEditorService);
        this._container = _container;
    }
    get hasContainer() {
        return false;
    }
    get container() {
        return this._container;
    }
};
EditorScopedLayoutService = standaloneLayoutService_decorate([
    standaloneLayoutService_param(1, ICodeEditorService)
], EditorScopedLayoutService);

registerSingleton(ILayoutService, StandaloneLayoutService);

;// ../../node_modules/monaco-editor/esm/vs/platform/undoRedo/common/undoRedoService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var undoRedoService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var undoRedoService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var undoRedoService_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};









const undoRedoService_DEBUG = false;
function getResourceLabel(resource) {
    return resource.scheme === Schemas.file ? resource.fsPath : resource.path;
}
let stackElementCounter = 0;
class ResourceStackElement {
    constructor(actual, resourceLabel, strResource, groupId, groupOrder, sourceId, sourceOrder) {
        this.id = (++stackElementCounter);
        this.type = 0 /* UndoRedoElementType.Resource */;
        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(isValid) {
        this.isValid = isValid;
    }
    toString() {
        return `[id:${this.id}] [group:${this.groupId}] [${this.isValid ? '  VALID' : 'INVALID'}] ${this.actual.constructor.name} - ${this.actual}`;
    }
}
class ResourceReasonPair {
    constructor(resourceLabel, reason) {
        this.resourceLabel = resourceLabel;
        this.reason = reason;
    }
}
class RemovedResources {
    constructor() {
        this.elements = new Map();
    }
    createMessage() {
        const externalRemoval = [];
        const noParallelUniverses = [];
        for (const [, element] of this.elements) {
            const dest = (element.reason === 0 /* RemovedResourceReason.ExternalRemoval */
                ? externalRemoval
                : noParallelUniverses);
            dest.push(element.resourceLabel);
        }
        const messages = [];
        if (externalRemoval.length > 0) {
            messages.push(localize({ key: 'externalRemoval', comment: ['{0} is a list of filenames'] }, "The following files have been closed and modified on disk: {0}.", externalRemoval.join(', ')));
        }
        if (noParallelUniverses.length > 0) {
            messages.push(localize({ key: 'noParallelUniverses', comment: ['{0} is a list of filenames'] }, "The following files have been modified in an incompatible way: {0}.", noParallelUniverses.join(', ')));
        }
        return messages.join('\n');
    }
    get size() {
        return this.elements.size;
    }
    has(strResource) {
        return this.elements.has(strResource);
    }
    set(strResource, value) {
        this.elements.set(strResource, value);
    }
    delete(strResource) {
        return this.elements.delete(strResource);
    }
}
class WorkspaceStackElement {
    constructor(actual, resourceLabels, strResources, groupId, groupOrder, sourceId, sourceOrder) {
        this.id = (++stackElementCounter);
        this.type = 1 /* UndoRedoElementType.Workspace */;
        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, isValid) {
        if (isValid) {
            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}`;
    }
}
class ResourceEditStack {
    constructor(resourceLabel, strResource) {
        this.resourceLabel = resourceLabel;
        this.strResource = strResource;
        this._past = [];
        this._future = [];
        this.locked = false;
        this.versionId = 1;
    }
    dispose() {
        for (const element of this._past) {
            if (element.type === 1 /* UndoRedoElementType.Workspace */) {
                element.removeResource(this.resourceLabel, this.strResource, 0 /* RemovedResourceReason.ExternalRemoval */);
            }
        }
        for (const element of this._future) {
            if (element.type === 1 /* UndoRedoElementType.Workspace */) {
                element.removeResource(this.resourceLabel, this.strResource, 0 /* RemovedResourceReason.ExternalRemoval */);
            }
        }
        this.versionId++;
    }
    toString() {
        const result = [];
        result.push(`* ${this.strResource}:`);
        for (let i = 0; i < this._past.length; i++) {
            result.push(`   * [UNDO] ${this._past[i]}`);
        }
        for (let i = this._future.length - 1; i >= 0; i--) {
            result.push(`   * [REDO] ${this._future[i]}`);
        }
        return result.join('\n');
    }
    flushAllElements() {
        this._past = [];
        this._future = [];
        this.versionId++;
    }
    _setElementValidFlag(element, isValid) {
        if (element.type === 1 /* UndoRedoElementType.Workspace */) {
            element.setValid(this.resourceLabel, this.strResource, isValid);
        }
        else {
            element.setValid(isValid);
        }
    }
    setElementsValidFlag(isValid, filter) {
        for (const element of this._past) {
            if (filter(element.actual)) {
                this._setElementValidFlag(element, isValid);
            }
        }
        for (const element of this._future) {
            if (filter(element.actual)) {
                this._setElementValidFlag(element, isValid);
            }
        }
    }
    pushElement(element) {
        // remove the future
        for (const futureElement of this._future) {
            if (futureElement.type === 1 /* UndoRedoElementType.Workspace */) {
                futureElement.removeResource(this.resourceLabel, this.strResource, 1 /* RemovedResourceReason.NoParallelUniverses */);
            }
        }
        this._future = [];
        this._past.push(element);
        this.versionId++;
    }
    createSnapshot(resource) {
        const elements = [];
        for (let i = 0, len = this._past.length; i < len; i++) {
            elements.push(this._past[i].id);
        }
        for (let i = this._future.length - 1; i >= 0; i--) {
            elements.push(this._future[i].id);
        }
        return new ResourceEditStackSnapshot(resource, elements);
    }
    restoreSnapshot(snapshot) {
        const snapshotLength = snapshot.elements.length;
        let isOK = true;
        let snapshotIndex = 0;
        let removePastAfter = -1;
        for (let i = 0, len = this._past.length; i < len; i++, snapshotIndex++) {
            const element = this._past[i];
            if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
                isOK = false;
                removePastAfter = 0;
            }
            if (!isOK && element.type === 1 /* UndoRedoElementType.Workspace */) {
                element.removeResource(this.resourceLabel, this.strResource, 0 /* RemovedResourceReason.ExternalRemoval */);
            }
        }
        let removeFutureBefore = -1;
        for (let i = this._future.length - 1; i >= 0; i--, snapshotIndex++) {
            const element = this._future[i];
            if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
                isOK = false;
                removeFutureBefore = i;
            }
            if (!isOK && element.type === 1 /* UndoRedoElementType.Workspace */) {
                element.removeResource(this.resourceLabel, this.strResource, 0 /* RemovedResourceReason.ExternalRemoval */);
            }
        }
        if (removePastAfter !== -1) {
            this._past = this._past.slice(0, removePastAfter);
        }
        if (removeFutureBefore !== -1) {
            this._future = this._future.slice(removeFutureBefore + 1);
        }
        this.versionId++;
    }
    getElements() {
        const past = [];
        const future = [];
        for (const element of this._past) {
            past.push(element.actual);
        }
        for (const element of this._future) {
            future.push(element.actual);
        }
        return { past, future };
    }
    getClosestPastElement() {
        if (this._past.length === 0) {
            return null;
        }
        return this._past[this._past.length - 1];
    }
    getSecondClosestPastElement() {
        if (this._past.length < 2) {
            return null;
        }
        return this._past[this._past.length - 2];
    }
    getClosestFutureElement() {
        if (this._future.length === 0) {
            return null;
        }
        return this._future[this._future.length - 1];
    }
    hasPastElements() {
        return (this._past.length > 0);
    }
    hasFutureElements() {
        return (this._future.length > 0);
    }
    splitPastWorkspaceElement(toRemove, individualMap) {
        for (let j = this._past.length - 1; j >= 0; j--) {
            if (this._past[j] === toRemove) {
                if (individualMap.has(this.strResource)) {
                    // gets replaced
                    this._past[j] = individualMap.get(this.strResource);
                }
                else {
                    // gets deleted
                    this._past.splice(j, 1);
                }
                break;
            }
        }
        this.versionId++;
    }
    splitFutureWorkspaceElement(toRemove, individualMap) {
        for (let j = this._future.length - 1; j >= 0; j--) {
            if (this._future[j] === toRemove) {
                if (individualMap.has(this.strResource)) {
                    // gets replaced
                    this._future[j] = individualMap.get(this.strResource);
                }
                else {
                    // gets deleted
                    this._future.splice(j, 1);
                }
                break;
            }
        }
        this.versionId++;
    }
    moveBackward(element) {
        this._past.pop();
        this._future.push(element);
        this.versionId++;
    }
    moveForward(element) {
        this._future.pop();
        this._past.push(element);
        this.versionId++;
    }
}
class EditStackSnapshot {
    constructor(editStacks) {
        this.editStacks = editStacks;
        this._versionIds = [];
        for (let i = 0, len = this.editStacks.length; i < len; i++) {
            this._versionIds[i] = this.editStacks[i].versionId;
        }
    }
    isValid() {
        for (let i = 0, len = this.editStacks.length; i < len; i++) {
            if (this._versionIds[i] !== this.editStacks[i].versionId) {
                return false;
            }
        }
        return true;
    }
}
const missingEditStack = new ResourceEditStack('', '');
missingEditStack.locked = true;
let UndoRedoService = class UndoRedoService {
    constructor(_dialogService, _notificationService) {
        this._dialogService = _dialogService;
        this._notificationService = _notificationService;
        this._editStacks = new Map();
        this._uriComparisonKeyComputers = [];
    }
    getUriComparisonKey(resource) {
        for (const uriComparisonKeyComputer of this._uriComparisonKeyComputers) {
            if (uriComparisonKeyComputer[0] === resource.scheme) {
                return uriComparisonKeyComputer[1].getComparisonKey(resource);
            }
        }
        return resource.toString();
    }
    _print(label) {
        console.log(`------------------------------------`);
        console.log(`AFTER ${label}: `);
        const str = [];
        for (const element of this._editStacks) {
            str.push(element[1].toString());
        }
        console.log(str.join('\n'));
    }
    pushElement(element, group = UndoRedoGroup.None, source = UndoRedoSource.None) {
        if (element.type === 0 /* UndoRedoElementType.Resource */) {
            const resourceLabel = getResourceLabel(element.resource);
            const strResource = this.getUriComparisonKey(element.resource);
            this._pushElement(new ResourceStackElement(element, resourceLabel, strResource, group.id, group.nextOrder(), source.id, source.nextOrder()));
        }
        else {
            const seen = 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._pushElement(new ResourceStackElement(element, resourceLabels[0], strResources[0], group.id, group.nextOrder(), source.id, source.nextOrder()));
            }
            else {
                this._pushElement(new WorkspaceStackElement(element, resourceLabels, strResources, group.id, group.nextOrder(), source.id, source.nextOrder()));
            }
        }
        if (undoRedoService_DEBUG) {
            this._print('pushElement');
        }
    }
    _pushElement(element) {
        for (let i = 0, len = element.strResources.length; i < len; i++) {
            const resourceLabel = element.resourceLabels[i];
            const strResource = element.strResources[i];
            let editStack;
            if (this._editStacks.has(strResource)) {
                editStack = this._editStacks.get(strResource);
            }
            else {
                editStack = new ResourceEditStack(resourceLabel, strResource);
                this._editStacks.set(strResource, editStack);
            }
            editStack.pushElement(element);
        }
    }
    getLastElement(resource) {
        const strResource = this.getUriComparisonKey(resource);
        if (this._editStacks.has(strResource)) {
            const editStack = this._editStacks.get(strResource);
            if (editStack.hasFutureElements()) {
                return null;
            }
            const closestPastElement = editStack.getClosestPastElement();
            return closestPastElement ? closestPastElement.actual : null;
        }
        return null;
    }
    _splitPastWorkspaceElement(toRemove, ignoreResources) {
        const individualArr = toRemove.actual.split();
        const individualMap = 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._editStacks.get(strResource);
            editStack.splitPastWorkspaceElement(toRemove, individualMap);
        }
    }
    _splitFutureWorkspaceElement(toRemove, ignoreResources) {
        const individualArr = toRemove.actual.split();
        const individualMap = 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._editStacks.get(strResource);
            editStack.splitFutureWorkspaceElement(toRemove, individualMap);
        }
    }
    removeElements(resource) {
        const strResource = typeof resource === 'string' ? resource : this.getUriComparisonKey(resource);
        if (this._editStacks.has(strResource)) {
            const editStack = this._editStacks.get(strResource);
            editStack.dispose();
            this._editStacks.delete(strResource);
        }
        if (undoRedoService_DEBUG) {
            this._print('removeElements');
        }
    }
    setElementsValidFlag(resource, isValid, filter) {
        const strResource = this.getUriComparisonKey(resource);
        if (this._editStacks.has(strResource)) {
            const editStack = this._editStacks.get(strResource);
            editStack.setElementsValidFlag(isValid, filter);
        }
        if (undoRedoService_DEBUG) {
            this._print('setElementsValidFlag');
        }
    }
    createSnapshot(resource) {
        const strResource = this.getUriComparisonKey(resource);
        if (this._editStacks.has(strResource)) {
            const editStack = this._editStacks.get(strResource);
            return editStack.createSnapshot(resource);
        }
        return new ResourceEditStackSnapshot(resource, []);
    }
    restoreSnapshot(snapshot) {
        const strResource = this.getUriComparisonKey(snapshot.resource);
        if (this._editStacks.has(strResource)) {
            const editStack = this._editStacks.get(strResource);
            editStack.restoreSnapshot(snapshot);
            if (!editStack.hasPastElements() && !editStack.hasFutureElements()) {
                // the edit stack is now empty, just remove it entirely
                editStack.dispose();
                this._editStacks.delete(strResource);
            }
        }
        if (undoRedoService_DEBUG) {
            this._print('restoreSnapshot');
        }
    }
    getElements(resource) {
        const strResource = this.getUriComparisonKey(resource);
        if (this._editStacks.has(strResource)) {
            const editStack = this._editStacks.get(strResource);
            return editStack.getElements();
        }
        return { past: [], future: [] };
    }
    _findClosestUndoElementWithSource(sourceId) {
        if (!sourceId) {
            return [null, null];
        }
        // find an element with the sourceId and with the highest sourceOrder ready to be undone
        let matchedElement = null;
        let matchedStrResource = null;
        for (const [strResource, editStack] of this._editStacks) {
            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 UndoRedoSource) {
            const [, matchedStrResource] = this._findClosestUndoElementWithSource(resourceOrSource.id);
            return matchedStrResource ? true : false;
        }
        const strResource = this.getUriComparisonKey(resourceOrSource);
        if (this._editStacks.has(strResource)) {
            const editStack = this._editStacks.get(strResource);
            return editStack.hasPastElements();
        }
        return false;
    }
    _onError(err, element) {
        onUnexpectedError(err);
        // An error occurred while undoing or redoing => drop the undo/redo stack for all affected resources
        for (const strResource of element.strResources) {
            this.removeElements(strResource);
        }
        this._notificationService.error(err);
    }
    _acquireLocks(editStackSnapshot) {
        // first, check if all locks can be acquired
        for (const editStack of editStackSnapshot.editStacks) {
            if (editStack.locked) {
                throw new Error('Cannot acquire edit stack lock');
            }
        }
        // can acquire all locks
        for (const editStack of editStackSnapshot.editStacks) {
            editStack.locked = true;
        }
        return () => {
            // release all locks
            for (const editStack of editStackSnapshot.editStacks) {
                editStack.locked = false;
            }
        };
    }
    _safeInvokeWithLocks(element, invoke, editStackSnapshot, cleanup, continuation) {
        const releaseLocks = this._acquireLocks(editStackSnapshot);
        let result;
        try {
            result = invoke();
        }
        catch (err) {
            releaseLocks();
            cleanup.dispose();
            return this._onError(err, element);
        }
        if (result) {
            // result is Promise<void>
            return result.then(() => {
                releaseLocks();
                cleanup.dispose();
                return continuation();
            }, (err) => {
                releaseLocks();
                cleanup.dispose();
                return this._onError(err, element);
            });
        }
        else {
            // result is void
            releaseLocks();
            cleanup.dispose();
            return continuation();
        }
    }
    _invokeWorkspacePrepare(element) {
        return undoRedoService_awaiter(this, void 0, void 0, function* () {
            if (typeof element.actual.prepareUndoRedo === 'undefined') {
                return Disposable.None;
            }
            const result = element.actual.prepareUndoRedo();
            if (typeof result === 'undefined') {
                return Disposable.None;
            }
            return result;
        });
    }
    _invokeResourcePrepare(element, callback) {
        if (element.actual.type !== 1 /* UndoRedoElementType.Workspace */ || typeof element.actual.prepareUndoRedo === 'undefined') {
            // no preparation needed
            return callback(Disposable.None);
        }
        const r = element.actual.prepareUndoRedo();
        if (!r) {
            // nothing to clean up
            return callback(Disposable.None);
        }
        if (isDisposable(r)) {
            return callback(r);
        }
        return r.then((disposable) => {
            return callback(disposable);
        });
    }
    _getAffectedEditStacks(element) {
        const affectedEditStacks = [];
        for (const strResource of element.strResources) {
            affectedEditStacks.push(this._editStacks.get(strResource) || missingEditStack);
        }
        return new EditStackSnapshot(affectedEditStacks);
    }
    _tryToSplitAndUndo(strResource, element, ignoreResources, message) {
        if (element.canSplit()) {
            this._splitPastWorkspaceElement(element, ignoreResources);
            this._notificationService.warn(message);
            return new WorkspaceVerificationError(this._undo(strResource, 0, true));
        }
        else {
            // Cannot safely split this workspace element => flush all undo/redo stacks
            for (const strResource of element.strResources) {
                this.removeElements(strResource);
            }
            this._notificationService.warn(message);
            return new WorkspaceVerificationError();
        }
    }
    _checkWorkspaceUndo(strResource, element, editStackSnapshot, checkInvalidatedResources) {
        if (element.removedResources) {
            return this._tryToSplitAndUndo(strResource, element, element.removedResources, localize({ key: 'cannotWorkspaceUndo', comment: ['{0} is a label for an operation. {1} is another message.'] }, "Could not undo '{0}' across all files. {1}", element.label, element.removedResources.createMessage()));
        }
        if (checkInvalidatedResources && element.invalidatedResources) {
            return this._tryToSplitAndUndo(strResource, element, element.invalidatedResources, localize({ key: 'cannotWorkspaceUndo', comment: ['{0} is a label for an operation. {1} is another message.'] }, "Could not undo '{0}' across all files. {1}", element.label, element.invalidatedResources.createMessage()));
        }
        // this must be the last past element in all the impacted resources!
        const cannotUndoDueToResources = [];
        for (const editStack of editStackSnapshot.editStacks) {
            if (editStack.getClosestPastElement() !== element) {
                cannotUndoDueToResources.push(editStack.resourceLabel);
            }
        }
        if (cannotUndoDueToResources.length > 0) {
            return this._tryToSplitAndUndo(strResource, element, null, localize({ key: 'cannotWorkspaceUndoDueToChanges', comment: ['{0} is a label for an operation. {1} is a list of filenames.'] }, "Could not undo '{0}' across all files because changes were made to {1}", 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._tryToSplitAndUndo(strResource, element, null, localize({ key: 'cannotWorkspaceUndoDueToInProgressUndoRedo', comment: ['{0} is a label for an operation. {1} is a list of filenames.'] }, "Could not undo '{0}' across all files because there is already an undo or redo operation running on {1}", element.label, cannotLockDueToResources.join(', ')));
        }
        // check if new stack elements were added in the meantime...
        if (!editStackSnapshot.isValid()) {
            return this._tryToSplitAndUndo(strResource, element, null, localize({ key: 'cannotWorkspaceUndoDueToInMeantimeUndoRedo', comment: ['{0} is a label for an operation. {1} is a list of filenames.'] }, "Could not undo '{0}' across all files because an undo or redo operation occurred in the meantime", element.label));
        }
        return null;
    }
    _workspaceUndo(strResource, element, undoConfirmed) {
        const affectedEditStacks = this._getAffectedEditStacks(element);
        const verificationError = this._checkWorkspaceUndo(strResource, element, affectedEditStacks, /*invalidated resources will be checked after the prepare call*/ false);
        if (verificationError) {
            return verificationError.returnValue;
        }
        return this._confirmAndExecuteWorkspaceUndo(strResource, element, affectedEditStacks, undoConfirmed);
    }
    _isPartOfUndoGroup(element) {
        if (!element.groupId) {
            return false;
        }
        // check that there is at least another element with the same groupId ready to be undone
        for (const [, editStack] of this._editStacks) {
            const pastElement = editStack.getClosestPastElement();
            if (!pastElement) {
                continue;
            }
            if (pastElement === element) {
                const secondPastElement = editStack.getSecondClosestPastElement();
                if (secondPastElement && secondPastElement.groupId === element.groupId) {
                    // there is another element with the same group id in the same stack!
                    return true;
                }
            }
            if (pastElement.groupId === element.groupId) {
                // there is another element with the same group id in another stack!
                return true;
            }
        }
        return false;
    }
    _confirmAndExecuteWorkspaceUndo(strResource, element, editStackSnapshot, undoConfirmed) {
        return undoRedoService_awaiter(this, void 0, void 0, function* () {
            if (element.canSplit() && !this._isPartOfUndoGroup(element)) {
                // this element can be split
                const result = yield this._dialogService.show(common_severity.Info, localize('confirmWorkspace', "Would you like to undo '{0}' across all files?", element.label), [
                    localize({ key: 'ok', comment: ['{0} denotes a number that is > 1'] }, "Undo in {0} Files", editStackSnapshot.editStacks.length),
                    localize('nok', "Undo this File"),
                    localize('cancel', "Cancel"),
                ], {
                    cancelId: 2
                });
                if (result.choice === 2) {
                    // choice: cancel
                    return;
                }
                if (result.choice === 1) {
                    // choice: undo this file
                    this._splitPastWorkspaceElement(element, null);
                    return this._undo(strResource, 0, true);
                }
                // choice: undo in all files
                // At this point, it is possible that the element has been made invalid in the meantime (due to the confirmation await)
                const verificationError1 = this._checkWorkspaceUndo(strResource, element, editStackSnapshot, /*invalidated resources will be checked after the prepare call*/ false);
                if (verificationError1) {
                    return verificationError1.returnValue;
                }
                undoConfirmed = true;
            }
            // prepare
            let cleanup;
            try {
                cleanup = yield this._invokeWorkspacePrepare(element);
            }
            catch (err) {
                return this._onError(err, element);
            }
            // At this point, it is possible that the element has been made invalid in the meantime (due to the prepare await)
            const verificationError2 = this._checkWorkspaceUndo(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._safeInvokeWithLocks(element, () => element.actual.undo(), editStackSnapshot, cleanup, () => this._continueUndoInGroup(element.groupId, undoConfirmed));
        });
    }
    _resourceUndo(editStack, element, undoConfirmed) {
        if (!element.isValid) {
            // invalid element => immediately flush edit stack!
            editStack.flushAllElements();
            return;
        }
        if (editStack.locked) {
            const message = localize({ key: 'cannotResourceUndoDueToInProgressUndoRedo', comment: ['{0} is a label for an operation.'] }, "Could not undo '{0}' because there is already an undo or redo operation running.", element.label);
            this._notificationService.warn(message);
            return;
        }
        return this._invokeResourcePrepare(element, (cleanup) => {
            editStack.moveBackward(element);
            return this._safeInvokeWithLocks(element, () => element.actual.undo(), new EditStackSnapshot([editStack]), cleanup, () => this._continueUndoInGroup(element.groupId, undoConfirmed));
        });
    }
    _findClosestUndoElementInGroup(groupId) {
        if (!groupId) {
            return [null, null];
        }
        // find another element with the same groupId and with the highest groupOrder ready to be undone
        let matchedElement = null;
        let matchedStrResource = null;
        for (const [strResource, editStack] of this._editStacks) {
            const candidate = editStack.getClosestPastElement();
            if (!candidate) {
                continue;
            }
            if (candidate.groupId === groupId) {
                if (!matchedElement || candidate.groupOrder > matchedElement.groupOrder) {
                    matchedElement = candidate;
                    matchedStrResource = strResource;
                }
            }
        }
        return [matchedElement, matchedStrResource];
    }
    _continueUndoInGroup(groupId, undoConfirmed) {
        if (!groupId) {
            return;
        }
        const [, matchedStrResource] = this._findClosestUndoElementInGroup(groupId);
        if (matchedStrResource) {
            return this._undo(matchedStrResource, 0, undoConfirmed);
        }
    }
    undo(resourceOrSource) {
        if (resourceOrSource instanceof UndoRedoSource) {
            const [, matchedStrResource] = this._findClosestUndoElementWithSource(resourceOrSource.id);
            return matchedStrResource ? this._undo(matchedStrResource, resourceOrSource.id, false) : undefined;
        }
        if (typeof resourceOrSource === 'string') {
            return this._undo(resourceOrSource, 0, false);
        }
        return this._undo(this.getUriComparisonKey(resourceOrSource), 0, false);
    }
    _undo(strResource, sourceId = 0, undoConfirmed) {
        if (!this._editStacks.has(strResource)) {
            return;
        }
        const editStack = this._editStacks.get(strResource);
        const element = editStack.getClosestPastElement();
        if (!element) {
            return;
        }
        if (element.groupId) {
            // this element is a part of a group, we need to make sure undoing in a group is in order
            const [matchedElement, matchedStrResource] = this._findClosestUndoElementInGroup(element.groupId);
            if (element !== matchedElement && matchedStrResource) {
                // there is an element in the same group that should be undone before this one
                return this._undo(matchedStrResource, sourceId, undoConfirmed);
            }
        }
        const shouldPromptForConfirmation = (element.sourceId !== sourceId || element.confirmBeforeUndo);
        if (shouldPromptForConfirmation && !undoConfirmed) {
            // Hit a different source or the element asks for prompt before undo, prompt for confirmation
            return this._confirmAndContinueUndo(strResource, sourceId, element);
        }
        try {
            if (element.type === 1 /* UndoRedoElementType.Workspace */) {
                return this._workspaceUndo(strResource, element, undoConfirmed);
            }
            else {
                return this._resourceUndo(editStack, element, undoConfirmed);
            }
        }
        finally {
            if (undoRedoService_DEBUG) {
                this._print('undo');
            }
        }
    }
    _confirmAndContinueUndo(strResource, sourceId, element) {
        return undoRedoService_awaiter(this, void 0, void 0, function* () {
            const result = yield this._dialogService.show(common_severity.Info, localize('confirmDifferentSource', "Would you like to undo '{0}'?", element.label), [
                localize('confirmDifferentSource.yes', "Yes"),
                localize('confirmDifferentSource.no', "No"),
            ], {
                cancelId: 1
            });
            if (result.choice === 1) {
                // choice: cancel
                return;
            }
            // choice: undo
            return this._undo(strResource, sourceId, true);
        });
    }
    _findClosestRedoElementWithSource(sourceId) {
        if (!sourceId) {
            return [null, null];
        }
        // find an element with sourceId and with the lowest sourceOrder ready to be redone
        let matchedElement = null;
        let matchedStrResource = null;
        for (const [strResource, editStack] of this._editStacks) {
            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 UndoRedoSource) {
            const [, matchedStrResource] = this._findClosestRedoElementWithSource(resourceOrSource.id);
            return matchedStrResource ? true : false;
        }
        const strResource = this.getUriComparisonKey(resourceOrSource);
        if (this._editStacks.has(strResource)) {
            const editStack = this._editStacks.get(strResource);
            return editStack.hasFutureElements();
        }
        return false;
    }
    _tryToSplitAndRedo(strResource, element, ignoreResources, message) {
        if (element.canSplit()) {
            this._splitFutureWorkspaceElement(element, ignoreResources);
            this._notificationService.warn(message);
            return new WorkspaceVerificationError(this._redo(strResource));
        }
        else {
            // Cannot safely split this workspace element => flush all undo/redo stacks
            for (const strResource of element.strResources) {
                this.removeElements(strResource);
            }
            this._notificationService.warn(message);
            return new WorkspaceVerificationError();
        }
    }
    _checkWorkspaceRedo(strResource, element, editStackSnapshot, checkInvalidatedResources) {
        if (element.removedResources) {
            return this._tryToSplitAndRedo(strResource, element, element.removedResources, localize({ key: 'cannotWorkspaceRedo', comment: ['{0} is a label for an operation. {1} is another message.'] }, "Could not redo '{0}' across all files. {1}", element.label, element.removedResources.createMessage()));
        }
        if (checkInvalidatedResources && element.invalidatedResources) {
            return this._tryToSplitAndRedo(strResource, element, element.invalidatedResources, localize({ key: 'cannotWorkspaceRedo', comment: ['{0} is a label for an operation. {1} is another message.'] }, "Could not redo '{0}' across all files. {1}", element.label, element.invalidatedResources.createMessage()));
        }
        // this must be the last future element in all the impacted resources!
        const cannotRedoDueToResources = [];
        for (const editStack of editStackSnapshot.editStacks) {
            if (editStack.getClosestFutureElement() !== element) {
                cannotRedoDueToResources.push(editStack.resourceLabel);
            }
        }
        if (cannotRedoDueToResources.length > 0) {
            return this._tryToSplitAndRedo(strResource, element, null, localize({ key: 'cannotWorkspaceRedoDueToChanges', comment: ['{0} is a label for an operation. {1} is a list of filenames.'] }, "Could not redo '{0}' across all files because changes were made to {1}", 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._tryToSplitAndRedo(strResource, element, null, localize({ key: 'cannotWorkspaceRedoDueToInProgressUndoRedo', comment: ['{0} is a label for an operation. {1} is a list of filenames.'] }, "Could not redo '{0}' across all files because there is already an undo or redo operation running on {1}", element.label, cannotLockDueToResources.join(', ')));
        }
        // check if new stack elements were added in the meantime...
        if (!editStackSnapshot.isValid()) {
            return this._tryToSplitAndRedo(strResource, element, null, localize({ key: 'cannotWorkspaceRedoDueToInMeantimeUndoRedo', comment: ['{0} is a label for an operation. {1} is a list of filenames.'] }, "Could not redo '{0}' across all files because an undo or redo operation occurred in the meantime", element.label));
        }
        return null;
    }
    _workspaceRedo(strResource, element) {
        const affectedEditStacks = this._getAffectedEditStacks(element);
        const verificationError = this._checkWorkspaceRedo(strResource, element, affectedEditStacks, /*invalidated resources will be checked after the prepare call*/ false);
        if (verificationError) {
            return verificationError.returnValue;
        }
        return this._executeWorkspaceRedo(strResource, element, affectedEditStacks);
    }
    _executeWorkspaceRedo(strResource, element, editStackSnapshot) {
        return undoRedoService_awaiter(this, void 0, void 0, function* () {
            // prepare
            let cleanup;
            try {
                cleanup = yield this._invokeWorkspacePrepare(element);
            }
            catch (err) {
                return this._onError(err, element);
            }
            // At this point, it is possible that the element has been made invalid in the meantime (due to the prepare await)
            const verificationError = this._checkWorkspaceRedo(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._safeInvokeWithLocks(element, () => element.actual.redo(), editStackSnapshot, cleanup, () => this._continueRedoInGroup(element.groupId));
        });
    }
    _resourceRedo(editStack, element) {
        if (!element.isValid) {
            // invalid element => immediately flush edit stack!
            editStack.flushAllElements();
            return;
        }
        if (editStack.locked) {
            const message = localize({ key: 'cannotResourceRedoDueToInProgressUndoRedo', comment: ['{0} is a label for an operation.'] }, "Could not redo '{0}' because there is already an undo or redo operation running.", element.label);
            this._notificationService.warn(message);
            return;
        }
        return this._invokeResourcePrepare(element, (cleanup) => {
            editStack.moveForward(element);
            return this._safeInvokeWithLocks(element, () => element.actual.redo(), new EditStackSnapshot([editStack]), cleanup, () => this._continueRedoInGroup(element.groupId));
        });
    }
    _findClosestRedoElementInGroup(groupId) {
        if (!groupId) {
            return [null, null];
        }
        // find another element with the same groupId and with the lowest groupOrder ready to be redone
        let matchedElement = null;
        let matchedStrResource = null;
        for (const [strResource, editStack] of this._editStacks) {
            const candidate = editStack.getClosestFutureElement();
            if (!candidate) {
                continue;
            }
            if (candidate.groupId === groupId) {
                if (!matchedElement || candidate.groupOrder < matchedElement.groupOrder) {
                    matchedElement = candidate;
                    matchedStrResource = strResource;
                }
            }
        }
        return [matchedElement, matchedStrResource];
    }
    _continueRedoInGroup(groupId) {
        if (!groupId) {
            return;
        }
        const [, matchedStrResource] = this._findClosestRedoElementInGroup(groupId);
        if (matchedStrResource) {
            return this._redo(matchedStrResource);
        }
    }
    redo(resourceOrSource) {
        if (resourceOrSource instanceof UndoRedoSource) {
            const [, matchedStrResource] = this._findClosestRedoElementWithSource(resourceOrSource.id);
            return matchedStrResource ? this._redo(matchedStrResource) : undefined;
        }
        if (typeof resourceOrSource === 'string') {
            return this._redo(resourceOrSource);
        }
        return this._redo(this.getUriComparisonKey(resourceOrSource));
    }
    _redo(strResource) {
        if (!this._editStacks.has(strResource)) {
            return;
        }
        const editStack = this._editStacks.get(strResource);
        const element = editStack.getClosestFutureElement();
        if (!element) {
            return;
        }
        if (element.groupId) {
            // this element is a part of a group, we need to make sure redoing in a group is in order
            const [matchedElement, matchedStrResource] = this._findClosestRedoElementInGroup(element.groupId);
            if (element !== matchedElement && matchedStrResource) {
                // there is an element in the same group that should be redone before this one
                return this._redo(matchedStrResource);
            }
        }
        try {
            if (element.type === 1 /* UndoRedoElementType.Workspace */) {
                return this._workspaceRedo(strResource, element);
            }
            else {
                return this._resourceRedo(editStack, element);
            }
        }
        finally {
            if (undoRedoService_DEBUG) {
                this._print('redo');
            }
        }
    }
};
UndoRedoService = undoRedoService_decorate([
    undoRedoService_param(0, IDialogService),
    undoRedoService_param(1, INotificationService)
], UndoRedoService);

class WorkspaceVerificationError {
    constructor(returnValue) {
        this.returnValue = returnValue;
    }
}
registerSingleton(IUndoRedoService, UndoRedoService);

;// ../../node_modules/monaco-editor/esm/vs/platform/configuration/common/configurationModels.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class ConfigurationModel {
    constructor(_contents = {}, _keys = [], _overrides = []) {
        this._contents = _contents;
        this._keys = _keys;
        this._overrides = _overrides;
        this.frozen = false;
        this.overrideConfigurations = new Map();
    }
    get contents() {
        return this.checkAndFreeze(this._contents);
    }
    get overrides() {
        return this.checkAndFreeze(this._overrides);
    }
    get keys() {
        return this.checkAndFreeze(this._keys);
    }
    isEmpty() {
        return this._keys.length === 0 && Object.keys(this._contents).length === 0 && this._overrides.length === 0;
    }
    getValue(section) {
        return section ? getConfigurationValue(this.contents, section) : this.contents;
    }
    getOverrideValue(section, overrideIdentifier) {
        const overrideContents = this.getContentsForOverrideIdentifer(overrideIdentifier);
        return overrideContents
            ? section ? getConfigurationValue(overrideContents, section) : overrideContents
            : undefined;
    }
    override(identifier) {
        let overrideConfigurationModel = this.overrideConfigurations.get(identifier);
        if (!overrideConfigurationModel) {
            overrideConfigurationModel = this.createOverrideConfigurationModel(identifier);
            this.overrideConfigurations.set(identifier, overrideConfigurationModel);
        }
        return overrideConfigurationModel;
    }
    merge(...others) {
        const contents = deepClone(this.contents);
        const overrides = deepClone(this.overrides);
        const keys = [...this.keys];
        for (const other of others) {
            if (other.isEmpty()) {
                continue;
            }
            this.mergeContents(contents, other.contents);
            for (const otherOverride of other.overrides) {
                const [override] = overrides.filter(o => equals(o.identifiers, otherOverride.identifiers));
                if (override) {
                    this.mergeContents(override.contents, otherOverride.contents);
                    override.keys.push(...otherOverride.keys);
                    override.keys = distinct(override.keys);
                }
                else {
                    overrides.push(deepClone(otherOverride));
                }
            }
            for (const key of other.keys) {
                if (keys.indexOf(key) === -1) {
                    keys.push(key);
                }
            }
        }
        return new ConfigurationModel(contents, keys, overrides);
    }
    freeze() {
        this.frozen = true;
        return this;
    }
    createOverrideConfigurationModel(identifier) {
        const overrideContents = this.getContentsForOverrideIdentifer(identifier);
        if (!overrideContents || typeof overrideContents !== 'object' || !Object.keys(overrideContents).length) {
            // If there are no valid overrides, return self
            return this;
        }
        const contents = {};
        for (const key of distinct([...Object.keys(this.contents), ...Object.keys(overrideContents)])) {
            let contentsForKey = this.contents[key];
            const overrideContentsForKey = overrideContents[key];
            // If there are override contents for the key, clone and merge otherwise use base contents
            if (overrideContentsForKey) {
                // Clone and merge only if base contents and override contents are of type object otherwise just override
                if (typeof contentsForKey === 'object' && typeof overrideContentsForKey === 'object') {
                    contentsForKey = deepClone(contentsForKey);
                    this.mergeContents(contentsForKey, overrideContentsForKey);
                }
                else {
                    contentsForKey = overrideContentsForKey;
                }
            }
            contents[key] = contentsForKey;
        }
        return new ConfigurationModel(contents, this.keys, this.overrides);
    }
    mergeContents(source, target) {
        for (const key of Object.keys(target)) {
            if (key in source) {
                if (isObject(source[key]) && isObject(target[key])) {
                    this.mergeContents(source[key], target[key]);
                    continue;
                }
            }
            source[key] = deepClone(target[key]);
        }
    }
    checkAndFreeze(data) {
        if (this.frozen && !Object.isFrozen(data)) {
            return deepFreeze(data);
        }
        return data;
    }
    getContentsForOverrideIdentifer(identifier) {
        let contentsForIdentifierOnly = null;
        let contents = null;
        const mergeContents = (contentsToMerge) => {
            if (contentsToMerge) {
                if (contents) {
                    this.mergeContents(contents, contentsToMerge);
                }
                else {
                    contents = deepClone(contentsToMerge);
                }
            }
        };
        for (const override of this.overrides) {
            if (equals(override.identifiers, [identifier])) {
                contentsForIdentifierOnly = override.contents;
            }
            else if (override.identifiers.includes(identifier)) {
                mergeContents(override.contents);
            }
        }
        // Merge contents of the identifier only at the end to take precedence.
        mergeContents(contentsForIdentifierOnly);
        return contents;
    }
    toJSON() {
        return {
            contents: this.contents,
            overrides: this.overrides,
            keys: this.keys
        };
    }
    // Update methods
    setValue(key, value) {
        this.addKey(key);
        addToValueTree(this.contents, key, value, e => { throw new Error(e); });
    }
    removeValue(key) {
        if (this.removeKey(key)) {
            removeFromValueTree(this.contents, key);
        }
    }
    addKey(key) {
        let index = this.keys.length;
        for (let i = 0; i < index; i++) {
            if (key.indexOf(this.keys[i]) === 0) {
                index = i;
            }
        }
        this.keys.splice(index, 1, key);
    }
    removeKey(key) {
        const index = this.keys.indexOf(key);
        if (index !== -1) {
            this.keys.splice(index, 1);
            return true;
        }
        return false;
    }
}
class Configuration {
    constructor(_defaultConfiguration, _policyConfiguration, _applicationConfiguration, _localUserConfiguration, _remoteUserConfiguration = new ConfigurationModel(), _workspaceConfiguration = new ConfigurationModel(), _folderConfigurations = new ResourceMap(), _memoryConfiguration = new ConfigurationModel(), _memoryConfigurationByResource = new ResourceMap(), _freeze = true) {
        this._defaultConfiguration = _defaultConfiguration;
        this._policyConfiguration = _policyConfiguration;
        this._applicationConfiguration = _applicationConfiguration;
        this._localUserConfiguration = _localUserConfiguration;
        this._remoteUserConfiguration = _remoteUserConfiguration;
        this._workspaceConfiguration = _workspaceConfiguration;
        this._folderConfigurations = _folderConfigurations;
        this._memoryConfiguration = _memoryConfiguration;
        this._memoryConfigurationByResource = _memoryConfigurationByResource;
        this._freeze = _freeze;
        this._workspaceConsolidatedConfiguration = null;
        this._foldersConsolidatedConfigurations = new ResourceMap();
        this._userConfiguration = null;
    }
    getValue(section, overrides, workspace) {
        const consolidateConfigurationModel = this.getConsolidatedConfigurationModel(section, overrides, workspace);
        return consolidateConfigurationModel.getValue(section);
    }
    updateValue(key, value, overrides = {}) {
        let memoryConfiguration;
        if (overrides.resource) {
            memoryConfiguration = this._memoryConfigurationByResource.get(overrides.resource);
            if (!memoryConfiguration) {
                memoryConfiguration = new ConfigurationModel();
                this._memoryConfigurationByResource.set(overrides.resource, memoryConfiguration);
            }
        }
        else {
            memoryConfiguration = this._memoryConfiguration;
        }
        if (value === undefined) {
            memoryConfiguration.removeValue(key);
        }
        else {
            memoryConfiguration.setValue(key, value);
        }
        if (!overrides.resource) {
            this._workspaceConsolidatedConfiguration = null;
        }
    }
    inspect(key, overrides, workspace) {
        const consolidateConfigurationModel = this.getConsolidatedConfigurationModel(key, overrides, workspace);
        const folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource, workspace);
        const memoryConfigurationModel = overrides.resource ? this._memoryConfigurationByResource.get(overrides.resource) || this._memoryConfiguration : this._memoryConfiguration;
        const defaultValue = overrides.overrideIdentifier ? this._defaultConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._defaultConfiguration.freeze().getValue(key);
        const policyValue = this._policyConfiguration.isEmpty() ? undefined : this._policyConfiguration.freeze().getValue(key);
        const applicationValue = this.applicationConfiguration.isEmpty() ? undefined : this.applicationConfiguration.freeze().getValue(key);
        const userValue = overrides.overrideIdentifier ? this.userConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.userConfiguration.freeze().getValue(key);
        const userLocalValue = overrides.overrideIdentifier ? this.localUserConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.localUserConfiguration.freeze().getValue(key);
        const userRemoteValue = overrides.overrideIdentifier ? this.remoteUserConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this.remoteUserConfiguration.freeze().getValue(key);
        const workspaceValue = workspace ? overrides.overrideIdentifier ? this._workspaceConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._workspaceConfiguration.freeze().getValue(key) : undefined; //Check on workspace exists or not because _workspaceConfiguration is never null
        const workspaceFolderValue = folderConfigurationModel ? overrides.overrideIdentifier ? folderConfigurationModel.freeze().override(overrides.overrideIdentifier).getValue(key) : folderConfigurationModel.freeze().getValue(key) : undefined;
        const memoryValue = overrides.overrideIdentifier ? memoryConfigurationModel.override(overrides.overrideIdentifier).getValue(key) : memoryConfigurationModel.getValue(key);
        const value = consolidateConfigurationModel.getValue(key);
        const overrideIdentifiers = distinct(consolidateConfigurationModel.overrides.map(override => override.identifiers).flat()).filter(overrideIdentifier => consolidateConfigurationModel.getOverrideValue(key, overrideIdentifier) !== undefined);
        return {
            defaultValue,
            policyValue,
            applicationValue,
            userValue,
            userLocalValue,
            userRemoteValue,
            workspaceValue,
            workspaceFolderValue,
            memoryValue,
            value,
            default: defaultValue !== undefined ? { value: this._defaultConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this._defaultConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
            policy: policyValue !== undefined ? { value: policyValue } : undefined,
            application: applicationValue !== undefined ? { value: applicationValue, override: overrides.overrideIdentifier ? this.applicationConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
            user: userValue !== undefined ? { value: this.userConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this.userConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
            userLocal: userLocalValue !== undefined ? { value: this.localUserConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this.localUserConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
            userRemote: userRemoteValue !== undefined ? { value: this.remoteUserConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this.remoteUserConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
            workspace: workspaceValue !== undefined ? { value: this._workspaceConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this._workspaceConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
            workspaceFolder: workspaceFolderValue !== undefined ? { value: folderConfigurationModel === null || folderConfigurationModel === void 0 ? void 0 : folderConfigurationModel.freeze().getValue(key), override: overrides.overrideIdentifier ? folderConfigurationModel === null || folderConfigurationModel === void 0 ? void 0 : folderConfigurationModel.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
            memory: memoryValue !== undefined ? { value: memoryConfigurationModel.getValue(key), override: overrides.overrideIdentifier ? memoryConfigurationModel.getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
            overrideIdentifiers: overrideIdentifiers.length ? overrideIdentifiers : undefined
        };
    }
    get applicationConfiguration() {
        return this._applicationConfiguration;
    }
    get userConfiguration() {
        if (!this._userConfiguration) {
            this._userConfiguration = this._remoteUserConfiguration.isEmpty() ? this._localUserConfiguration : this._localUserConfiguration.merge(this._remoteUserConfiguration);
            if (this._freeze) {
                this._userConfiguration.freeze();
            }
        }
        return this._userConfiguration;
    }
    get localUserConfiguration() {
        return this._localUserConfiguration;
    }
    get remoteUserConfiguration() {
        return this._remoteUserConfiguration;
    }
    getConsolidatedConfigurationModel(section, overrides, workspace) {
        let configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace);
        if (overrides.overrideIdentifier) {
            configurationModel = configurationModel.override(overrides.overrideIdentifier);
        }
        if (!this._policyConfiguration.isEmpty() && this._policyConfiguration.getValue(section) !== undefined) {
            configurationModel = configurationModel.merge(this._policyConfiguration);
        }
        return configurationModel;
    }
    getConsolidatedConfigurationModelForResource({ resource }, workspace) {
        let consolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
        if (workspace && resource) {
            const root = workspace.getFolder(resource);
            if (root) {
                consolidateConfiguration = this.getFolderConsolidatedConfiguration(root.uri) || consolidateConfiguration;
            }
            const memoryConfigurationForResource = this._memoryConfigurationByResource.get(resource);
            if (memoryConfigurationForResource) {
                consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource);
            }
        }
        return consolidateConfiguration;
    }
    getWorkspaceConsolidatedConfiguration() {
        if (!this._workspaceConsolidatedConfiguration) {
            this._workspaceConsolidatedConfiguration = this._defaultConfiguration.merge(this.applicationConfiguration, this.userConfiguration, this._workspaceConfiguration, this._memoryConfiguration);
            if (this._freeze) {
                this._workspaceConfiguration = this._workspaceConfiguration.freeze();
            }
        }
        return this._workspaceConsolidatedConfiguration;
    }
    getFolderConsolidatedConfiguration(folder) {
        let folderConsolidatedConfiguration = this._foldersConsolidatedConfigurations.get(folder);
        if (!folderConsolidatedConfiguration) {
            const workspaceConsolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
            const folderConfiguration = this._folderConfigurations.get(folder);
            if (folderConfiguration) {
                folderConsolidatedConfiguration = workspaceConsolidateConfiguration.merge(folderConfiguration);
                if (this._freeze) {
                    folderConsolidatedConfiguration = folderConsolidatedConfiguration.freeze();
                }
                this._foldersConsolidatedConfigurations.set(folder, folderConsolidatedConfiguration);
            }
            else {
                folderConsolidatedConfiguration = workspaceConsolidateConfiguration;
            }
        }
        return folderConsolidatedConfiguration;
    }
    getFolderConfigurationModelForResource(resource, workspace) {
        if (workspace && resource) {
            const root = workspace.getFolder(resource);
            if (root) {
                return this._folderConfigurations.get(root.uri);
            }
        }
        return undefined;
    }
    toData() {
        return {
            defaults: {
                contents: this._defaultConfiguration.contents,
                overrides: this._defaultConfiguration.overrides,
                keys: this._defaultConfiguration.keys
            },
            policy: {
                contents: this._policyConfiguration.contents,
                overrides: this._policyConfiguration.overrides,
                keys: this._policyConfiguration.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._workspaceConfiguration.contents,
                overrides: this._workspaceConfiguration.overrides,
                keys: this._workspaceConfiguration.keys
            },
            folders: [...this._folderConfigurations.keys()].reduce((result, folder) => {
                const { contents, overrides, keys } = this._folderConfigurations.get(folder);
                result.push([folder, { contents, overrides, keys }]);
                return result;
            }, [])
        };
    }
    static parse(data) {
        const defaultConfiguration = this.parseConfigurationModel(data.defaults);
        const policyConfiguration = this.parseConfigurationModel(data.policy);
        const applicationConfiguration = this.parseConfigurationModel(data.application);
        const userConfiguration = this.parseConfigurationModel(data.user);
        const workspaceConfiguration = this.parseConfigurationModel(data.workspace);
        const folders = data.folders.reduce((result, value) => {
            result.set(URI.revive(value[0]), this.parseConfigurationModel(value[1]));
            return result;
        }, new ResourceMap());
        return new Configuration(defaultConfiguration, policyConfiguration, applicationConfiguration, userConfiguration, new ConfigurationModel(), workspaceConfiguration, folders, new ConfigurationModel(), new ResourceMap(), false);
    }
    static parseConfigurationModel(model) {
        return new ConfigurationModel(model.contents, model.keys, model.overrides).freeze();
    }
}
class ConfigurationChangeEvent {
    constructor(change, previous, currentConfiguraiton, currentWorkspace) {
        this.change = change;
        this.previous = previous;
        this.currentConfiguraiton = currentConfiguraiton;
        this.currentWorkspace = currentWorkspace;
        this._previousConfiguration = undefined;
        const keysSet = new Set();
        change.keys.forEach(key => keysSet.add(key));
        change.overrides.forEach(([, keys]) => keys.forEach(key => keysSet.add(key)));
        this.affectedKeys = [...keysSet.values()];
        const configurationModel = new ConfigurationModel();
        this.affectedKeys.forEach(key => configurationModel.setValue(key, {}));
        this.affectedKeysTree = configurationModel.contents;
    }
    get previousConfiguration() {
        if (!this._previousConfiguration && this.previous) {
            this._previousConfiguration = Configuration.parse(this.previous.data);
        }
        return this._previousConfiguration;
    }
    affectsConfiguration(section, overrides) {
        var _a;
        if (this.doesAffectedKeysTreeContains(this.affectedKeysTree, section)) {
            if (overrides) {
                const value1 = this.previousConfiguration ? this.previousConfiguration.getValue(section, overrides, (_a = this.previous) === null || _a === void 0 ? void 0 : _a.workspace) : undefined;
                const value2 = this.currentConfiguraiton.getValue(section, overrides, this.currentWorkspace);
                return !objects_equals(value1, value2);
            }
            return true;
        }
        return false;
    }
    doesAffectedKeysTreeContains(affectedKeysTree, section) {
        let requestedTree = toValuesTree({ [section]: true }, () => { });
        let key;
        while (typeof requestedTree === 'object' && (key = Object.keys(requestedTree)[0])) { // Only one key should present, since we added only one property
            affectedKeysTree = affectedKeysTree[key];
            if (!affectedKeysTree) {
                return false; // Requested tree is not found
            }
            requestedTree = requestedTree[key];
        }
        return true;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/keybinding/common/abstractKeybindingService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




const HIGH_FREQ_COMMANDS = /^(cursor|delete)/;
class AbstractKeybindingService extends Disposable {
    constructor(_contextKeyService, _commandService, _telemetryService, _notificationService, _logService) {
        super();
        this._contextKeyService = _contextKeyService;
        this._commandService = _commandService;
        this._telemetryService = _telemetryService;
        this._notificationService = _notificationService;
        this._logService = _logService;
        this._onDidUpdateKeybindings = this._register(new Emitter());
        this._currentChord = null;
        this._currentChordChecker = new IntervalTimer();
        this._currentChordStatusMessage = null;
        this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
        this._currentSingleModifier = null;
        this._currentSingleModifierClearTimeout = new TimeoutTimer();
        this._logging = false;
    }
    get onDidUpdateKeybindings() {
        return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : Event.None; // Sinon stubbing walks properties on prototype
    }
    dispose() {
        super.dispose();
    }
    _log(str) {
        if (this._logging) {
            this._logService.info(`[KeybindingService]: ${str}`);
        }
    }
    getKeybindings() {
        return this._getResolver().getKeybindings();
    }
    lookupKeybinding(commandId, context) {
        const result = this._getResolver().lookupPrimaryKeybinding(commandId, context || this._contextKeyService);
        if (!result) {
            return undefined;
        }
        return result.resolvedKeybinding;
    }
    dispatchEvent(e, target) {
        return this._dispatch(e, target);
    }
    softDispatch(e, target) {
        this._log(`/ Soft dispatching keyboard event`);
        const keybinding = this.resolveKeyboardEvent(e);
        if (keybinding.isChord()) {
            console.warn('Unexpected keyboard event mapped to a chord');
            return null;
        }
        const [firstPart,] = keybinding.getDispatchParts();
        if (firstPart === null) {
            // cannot be dispatched, probably only modifier keys
            this._log(`\\ Keyboard event cannot be dispatched`);
            return null;
        }
        const contextValue = this._contextKeyService.getContext(target);
        const currentChord = this._currentChord ? this._currentChord.keypress : null;
        return this._getResolver().resolve(contextValue, currentChord, firstPart);
    }
    _enterChordMode(firstPart, keypressLabel) {
        this._currentChord = {
            keypress: firstPart,
            label: keypressLabel
        };
        this._currentChordStatusMessage = this._notificationService.status(localize('first.chord', "({0}) was pressed. Waiting for second key of chord...", keypressLabel));
        const chordEnterTime = Date.now();
        this._currentChordChecker.cancelAndSet(() => {
            if (!this._documentHasFocus()) {
                // Focus has been lost => leave chord mode
                this._leaveChordMode();
                return;
            }
            if (Date.now() - chordEnterTime > 5000) {
                // 5 seconds elapsed => leave chord mode
                this._leaveChordMode();
            }
        }, 500);
    }
    _leaveChordMode() {
        if (this._currentChordStatusMessage) {
            this._currentChordStatusMessage.dispose();
            this._currentChordStatusMessage = null;
        }
        this._currentChordChecker.cancel();
        this._currentChord = null;
    }
    _dispatch(e, target) {
        return this._doDispatch(this.resolveKeyboardEvent(e), target, /*isSingleModiferChord*/ false);
    }
    _singleModifierDispatch(e, target) {
        const keybinding = this.resolveKeyboardEvent(e);
        const [singleModifier,] = keybinding.getSingleModifierDispatchParts();
        if (singleModifier) {
            if (this._ignoreSingleModifiers.has(singleModifier)) {
                this._log(`+ Ignoring single modifier ${singleModifier} due to it being pressed together with other keys.`);
                this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
                this._currentSingleModifierClearTimeout.cancel();
                this._currentSingleModifier = null;
                return false;
            }
            this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
            if (this._currentSingleModifier === null) {
                // we have a valid `singleModifier`, store it for the next keyup, but clear it in 300ms
                this._log(`+ Storing single modifier for possible chord ${singleModifier}.`);
                this._currentSingleModifier = singleModifier;
                this._currentSingleModifierClearTimeout.cancelAndSet(() => {
                    this._log(`+ Clearing single modifier due to 300ms elapsed.`);
                    this._currentSingleModifier = null;
                }, 300);
                return false;
            }
            if (singleModifier === this._currentSingleModifier) {
                // bingo!
                this._log(`/ Dispatching single modifier chord ${singleModifier} ${singleModifier}`);
                this._currentSingleModifierClearTimeout.cancel();
                this._currentSingleModifier = null;
                return this._doDispatch(keybinding, target, /*isSingleModiferChord*/ true);
            }
            this._log(`+ Clearing single modifier due to modifier mismatch: ${this._currentSingleModifier} ${singleModifier}`);
            this._currentSingleModifierClearTimeout.cancel();
            this._currentSingleModifier = null;
            return false;
        }
        // When pressing a modifier and holding it pressed with any other modifier or key combination,
        // the pressed modifiers should no longer be considered for single modifier dispatch.
        const [firstPart,] = keybinding.getParts();
        this._ignoreSingleModifiers = new KeybindingModifierSet(firstPart);
        if (this._currentSingleModifier !== null) {
            this._log(`+ Clearing single modifier due to other key up.`);
        }
        this._currentSingleModifierClearTimeout.cancel();
        this._currentSingleModifier = null;
        return false;
    }
    _doDispatch(keybinding, target, isSingleModiferChord = false) {
        let shouldPreventDefault = false;
        if (keybinding.isChord()) {
            console.warn('Unexpected keyboard event mapped to a chord');
            return false;
        }
        let firstPart = null; // the first keybinding i.e. Ctrl+K
        let currentChord = null; // the "second" keybinding i.e. Ctrl+K "Ctrl+D"
        if (isSingleModiferChord) {
            const [dispatchKeyname,] = keybinding.getSingleModifierDispatchParts();
            firstPart = dispatchKeyname;
            currentChord = dispatchKeyname;
        }
        else {
            [firstPart,] = keybinding.getDispatchParts();
            currentChord = this._currentChord ? this._currentChord.keypress : null;
        }
        if (firstPart === null) {
            this._log(`\\ Keyboard event cannot be dispatched in keydown phase.`);
            // cannot be dispatched, probably only modifier keys
            return shouldPreventDefault;
        }
        const contextValue = this._contextKeyService.getContext(target);
        const keypressLabel = keybinding.getLabel();
        const resolveResult = this._getResolver().resolve(contextValue, currentChord, firstPart);
        this._logService.trace('KeybindingService#dispatch', keypressLabel, resolveResult === null || resolveResult === void 0 ? void 0 : resolveResult.commandId);
        if (resolveResult && resolveResult.enterChord) {
            shouldPreventDefault = true;
            this._enterChordMode(firstPart, keypressLabel);
            this._log(`+ Entering chord mode...`);
            return shouldPreventDefault;
        }
        if (this._currentChord) {
            if (!resolveResult || !resolveResult.commandId) {
                this._log(`+ Leaving chord mode: Nothing bound to "${this._currentChord.label} ${keypressLabel}".`);
                this._notificationService.status(localize('missing.chord', "The key combination ({0}, {1}) is not a command.", this._currentChord.label, keypressLabel), { hideAfter: 10 * 1000 /* 10s */ });
                shouldPreventDefault = true;
            }
        }
        this._leaveChordMode();
        if (resolveResult && resolveResult.commandId) {
            if (!resolveResult.bubble) {
                shouldPreventDefault = true;
            }
            this._log(`+ Invoking command ${resolveResult.commandId}.`);
            if (typeof resolveResult.commandArgs === 'undefined') {
                this._commandService.executeCommand(resolveResult.commandId).then(undefined, err => this._notificationService.warn(err));
            }
            else {
                this._commandService.executeCommand(resolveResult.commandId, resolveResult.commandArgs).then(undefined, err => this._notificationService.warn(err));
            }
            if (!HIGH_FREQ_COMMANDS.test(resolveResult.commandId)) {
                this._telemetryService.publicLog2('workbenchActionExecuted', { id: resolveResult.commandId, from: 'keybinding' });
            }
        }
        return shouldPreventDefault;
    }
    mightProducePrintableCharacter(event) {
        if (event.ctrlKey || event.metaKey) {
            // ignore ctrl/cmd-combination but not shift/alt-combinatios
            return false;
        }
        // weak check for certain ranges. this is properly implemented in a subclass
        // with access to the KeyboardMapperFactory.
        if ((event.keyCode >= 31 /* KeyCode.KeyA */ && event.keyCode <= 56 /* KeyCode.KeyZ */)
            || (event.keyCode >= 21 /* KeyCode.Digit0 */ && event.keyCode <= 30 /* KeyCode.Digit9 */)) {
            return true;
        }
        return false;
    }
}
class KeybindingModifierSet {
    constructor(source) {
        this._ctrlKey = source ? source.ctrlKey : false;
        this._shiftKey = source ? source.shiftKey : false;
        this._altKey = source ? source.altKey : false;
        this._metaKey = source ? source.metaKey : false;
    }
    has(modifier) {
        switch (modifier) {
            case 'ctrl': return this._ctrlKey;
            case 'shift': return this._shiftKey;
            case 'alt': return this._altKey;
            case 'meta': return this._metaKey;
        }
    }
}
KeybindingModifierSet.EMPTY = new KeybindingModifierSet(null);

;// ../../node_modules/monaco-editor/esm/vs/platform/keybinding/common/keybindingResolver.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

class KeybindingResolver {
    constructor(defaultKeybindings, overrides, log) {
        this._log = log;
        this._defaultKeybindings = defaultKeybindings;
        this._defaultBoundCommands = new Map();
        for (const defaultKeybinding of defaultKeybindings) {
            const command = defaultKeybinding.command;
            if (command && command.charAt(0) !== '-') {
                this._defaultBoundCommands.set(command, true);
            }
        }
        this._map = new Map();
        this._lookupMap = new Map();
        this._keybindings = KeybindingResolver.handleRemovals([].concat(defaultKeybindings).concat(overrides));
        for (let i = 0, len = this._keybindings.length; i < len; i++) {
            const k = this._keybindings[i];
            if (k.keypressParts.length === 0) {
                // unbound
                continue;
            }
            if (k.when && k.when.type === 0 /* ContextKeyExprType.False */) {
                // when condition is false
                continue;
            }
            // TODO@chords
            this._addKeyPress(k.keypressParts[0], k);
        }
    }
    static _isTargetedForRemoval(defaultKb, keypressFirstPart, keypressChordPart, when) {
        // TODO@chords
        if (keypressFirstPart && defaultKb.keypressParts[0] !== keypressFirstPart) {
            return false;
        }
        // TODO@chords
        if (keypressChordPart && defaultKb.keypressParts[1] !== keypressChordPart) {
            return false;
        }
        if (when) {
            if (!defaultKb.when) {
                return false;
            }
            if (!expressionsAreEqualWithConstantSubstitution(when, defaultKb.when)) {
                return false;
            }
        }
        return true;
    }
    /**
     * Looks for rules containing "-commandId" and removes them.
     */
    static handleRemovals(rules) {
        // Do a first pass and construct a hash-map for removals
        const removals = new Map();
        for (let i = 0, len = rules.length; i < len; i++) {
            const rule = rules[i];
            if (rule.command && rule.command.charAt(0) === '-') {
                const command = rule.command.substring(1);
                if (!removals.has(command)) {
                    removals.set(command, [rule]);
                }
                else {
                    removals.get(command).push(rule);
                }
            }
        }
        if (removals.size === 0) {
            // There are no removals
            return rules;
        }
        // Do a second pass and keep only non-removed keybindings
        const result = [];
        for (let i = 0, len = rules.length; i < len; i++) {
            const rule = rules[i];
            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) {
                // TODO@chords
                const keypressFirstPart = commandRemoval.keypressParts[0];
                const keypressChordPart = commandRemoval.keypressParts[1];
                const when = commandRemoval.when;
                if (this._isTargetedForRemoval(rule, keypressFirstPart, keypressChordPart, when)) {
                    isRemoved = true;
                    break;
                }
            }
            if (!isRemoved) {
                result.push(rule);
                continue;
            }
        }
        return result;
    }
    _addKeyPress(keypress, item) {
        const conflicts = this._map.get(keypress);
        if (typeof conflicts === 'undefined') {
            // There is no conflict so far
            this._map.set(keypress, [item]);
            this._addToLookupMap(item);
            return;
        }
        for (let i = conflicts.length - 1; i >= 0; i--) {
            const conflict = conflicts[i];
            if (conflict.command === item.command) {
                continue;
            }
            const conflictIsChord = (conflict.keypressParts.length > 1);
            const itemIsChord = (item.keypressParts.length > 1);
            // TODO@chords
            if (conflictIsChord && itemIsChord && conflict.keypressParts[1] !== item.keypressParts[1]) {
                // The conflict only shares the chord start with this command
                continue;
            }
            if (KeybindingResolver.whenIsEntirelyIncluded(conflict.when, item.when)) {
                // `item` completely overwrites `conflict`
                // Remove conflict from the lookupMap
                this._removeFromLookupMap(conflict);
            }
        }
        conflicts.push(item);
        this._addToLookupMap(item);
    }
    _addToLookupMap(item) {
        if (!item.command) {
            return;
        }
        let arr = this._lookupMap.get(item.command);
        if (typeof arr === 'undefined') {
            arr = [item];
            this._lookupMap.set(item.command, arr);
        }
        else {
            arr.push(item);
        }
    }
    _removeFromLookupMap(item) {
        if (!item.command) {
            return;
        }
        const arr = this._lookupMap.get(item.command);
        if (typeof arr === 'undefined') {
            return;
        }
        for (let i = 0, len = arr.length; i < len; i++) {
            if (arr[i] === item) {
                arr.splice(i, 1);
                return;
            }
        }
    }
    /**
     * Returns true if it is provable `a` implies `b`.
     */
    static whenIsEntirelyIncluded(a, b) {
        if (!b || b.type === 1 /* ContextKeyExprType.True */) {
            return true;
        }
        if (!a || a.type === 1 /* ContextKeyExprType.True */) {
            return false;
        }
        return implies(a, b);
    }
    getKeybindings() {
        return this._keybindings;
    }
    lookupPrimaryKeybinding(commandId, context) {
        const items = this._lookupMap.get(commandId);
        if (typeof items === 'undefined' || items.length === 0) {
            return null;
        }
        if (items.length === 1) {
            return items[0];
        }
        for (let i = items.length - 1; i >= 0; i--) {
            const item = items[i];
            if (context.contextMatchesRules(item.when)) {
                return item;
            }
        }
        return items[items.length - 1];
    }
    resolve(context, currentChord, keypress) {
        this._log(`| Resolving ${keypress}${currentChord ? ` chorded from ${currentChord}` : ``}`);
        let lookupMap = null;
        if (currentChord !== null) {
            // Fetch all chord bindings for `currentChord`
            const candidates = this._map.get(currentChord);
            if (typeof candidates === 'undefined') {
                // No chords starting with `currentChord`
                this._log(`\\ No keybinding entries.`);
                return null;
            }
            lookupMap = [];
            for (let i = 0, len = candidates.length; i < len; i++) {
                const candidate = candidates[i];
                // TODO@chords
                if (candidate.keypressParts[1] === keypress) {
                    lookupMap.push(candidate);
                }
            }
        }
        else {
            const candidates = this._map.get(keypress);
            if (typeof candidates === 'undefined') {
                // No bindings with `keypress`
                this._log(`\\ No keybinding entries.`);
                return null;
            }
            lookupMap = candidates;
        }
        const result = this._findCommand(context, lookupMap);
        if (!result) {
            this._log(`\\ From ${lookupMap.length} keybinding entries, no when clauses matched the context.`);
            return null;
        }
        // TODO@chords
        if (currentChord === null && result.keypressParts.length > 1 && result.keypressParts[1] !== null) {
            this._log(`\\ From ${lookupMap.length} keybinding entries, matched chord, when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
            return {
                enterChord: true,
                leaveChord: false,
                commandId: null,
                commandArgs: null,
                bubble: false
            };
        }
        this._log(`\\ From ${lookupMap.length} keybinding entries, matched ${result.command}, when: ${printWhenExplanation(result.when)}, source: ${printSourceExplanation(result)}.`);
        return {
            enterChord: false,
            leaveChord: result.keypressParts.length > 1,
            commandId: result.command,
            commandArgs: result.commandArgs,
            bubble: result.bubble
        };
    }
    _findCommand(context, matches) {
        for (let i = matches.length - 1; i >= 0; i--) {
            const k = matches[i];
            if (!KeybindingResolver._contextMatchesRules(context, k.when)) {
                continue;
            }
            return k;
        }
        return null;
    }
    static _contextMatchesRules(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`));
}

;// ../../node_modules/monaco-editor/esm/vs/platform/keybinding/common/resolvedKeybindingItem.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class ResolvedKeybindingItem {
    constructor(resolvedKeybinding, command, commandArgs, when, isDefault, extensionId, isBuiltinExtension) {
        this._resolvedKeybindingItemBrand = undefined;
        this.resolvedKeybinding = resolvedKeybinding;
        this.keypressParts = resolvedKeybinding ? removeElementsAfterNulls(resolvedKeybinding.getDispatchParts()) : [];
        if (resolvedKeybinding && this.keypressParts.length === 0) {
            // handle possible single modifier chord keybindings
            this.keypressParts = removeElementsAfterNulls(resolvedKeybinding.getSingleModifierDispatchParts());
        }
        this.bubble = (command ? command.charCodeAt(0) === 94 /* CharCode.Caret */ : false);
        this.command = this.bubble ? command.substr(1) : command;
        this.commandArgs = commandArgs;
        this.when = when;
        this.isDefault = isDefault;
        this.extensionId = extensionId;
        this.isBuiltinExtension = isBuiltinExtension;
    }
}
function removeElementsAfterNulls(arr) {
    const result = [];
    for (let i = 0, len = arr.length; i < len; i++) {
        const element = arr[i];
        if (!element) {
            // stop processing at first encountered null
            return result;
        }
        result.push(element);
    }
    return result;
}

;// ../../node_modules/monaco-editor/esm/vs/platform/keybinding/common/baseResolvedKeybinding.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class BaseResolvedKeybinding extends ResolvedKeybinding {
    constructor(os, parts) {
        super();
        if (parts.length === 0) {
            throw illegalArgument(`parts`);
        }
        this._os = os;
        this._parts = parts;
    }
    getLabel() {
        return UILabelProvider.toLabel(this._os, this._parts, (keybinding) => this._getLabel(keybinding));
    }
    getAriaLabel() {
        return AriaLabelProvider.toLabel(this._os, this._parts, (keybinding) => this._getAriaLabel(keybinding));
    }
    getElectronAccelerator() {
        if (this._parts.length > 1) {
            // [Electron Accelerators] Electron cannot handle chords
            return null;
        }
        if (this._parts[0].isDuplicateModifierCase()) {
            // [Electron Accelerators] Electron cannot handle modifier only keybindings
            // e.g. "shift shift"
            return null;
        }
        return ElectronAcceleratorLabelProvider.toLabel(this._os, this._parts, (keybinding) => this._getElectronAccelerator(keybinding));
    }
    isChord() {
        return (this._parts.length > 1);
    }
    getParts() {
        return this._parts.map((keybinding) => this._getPart(keybinding));
    }
    _getPart(keybinding) {
        return new ResolvedKeybindingPart(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, this._getLabel(keybinding), this._getAriaLabel(keybinding));
    }
    getDispatchParts() {
        return this._parts.map((keybinding) => this._getDispatchPart(keybinding));
    }
    getSingleModifierDispatchParts() {
        return this._parts.map((keybinding) => this._getSingleModifierDispatchPart(keybinding));
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/keybinding/common/usLayoutResolvedKeybinding.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




/**
 * Do not instantiate. Use KeybindingService to get a ResolvedKeybinding seeded with information about the current kb layout.
 */
class USLayoutResolvedKeybinding extends BaseResolvedKeybinding {
    constructor(actual, os) {
        super(os, actual.parts);
    }
    _keyCodeToUILabel(keyCode) {
        if (this._os === 2 /* OperatingSystem.Macintosh */) {
            switch (keyCode) {
                case 15 /* KeyCode.LeftArrow */:
                    return '←';
                case 16 /* KeyCode.UpArrow */:
                    return '↑';
                case 17 /* KeyCode.RightArrow */:
                    return '→';
                case 18 /* KeyCode.DownArrow */:
                    return '↓';
            }
        }
        return KeyCodeUtils.toString(keyCode);
    }
    _getLabel(keybinding) {
        if (keybinding.isDuplicateModifierCase()) {
            return '';
        }
        return this._keyCodeToUILabel(keybinding.keyCode);
    }
    _getAriaLabel(keybinding) {
        if (keybinding.isDuplicateModifierCase()) {
            return '';
        }
        return KeyCodeUtils.toString(keybinding.keyCode);
    }
    _getElectronAccelerator(keybinding) {
        return KeyCodeUtils.toElectronAccelerator(keybinding.keyCode);
    }
    _getDispatchPart(keybinding) {
        return USLayoutResolvedKeybinding.getDispatchStr(keybinding);
    }
    static getDispatchStr(keybinding) {
        if (keybinding.isModifierKey()) {
            return null;
        }
        let result = '';
        if (keybinding.ctrlKey) {
            result += 'ctrl+';
        }
        if (keybinding.shiftKey) {
            result += 'shift+';
        }
        if (keybinding.altKey) {
            result += 'alt+';
        }
        if (keybinding.metaKey) {
            result += 'meta+';
        }
        result += KeyCodeUtils.toString(keybinding.keyCode);
        return result;
    }
    _getSingleModifierDispatchPart(keybinding) {
        if (keybinding.keyCode === 5 /* KeyCode.Ctrl */ && !keybinding.shiftKey && !keybinding.altKey && !keybinding.metaKey) {
            return 'ctrl';
        }
        if (keybinding.keyCode === 4 /* KeyCode.Shift */ && !keybinding.ctrlKey && !keybinding.altKey && !keybinding.metaKey) {
            return 'shift';
        }
        if (keybinding.keyCode === 6 /* KeyCode.Alt */ && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.metaKey) {
            return 'alt';
        }
        if (keybinding.keyCode === 57 /* KeyCode.Meta */ && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.altKey) {
            return 'meta';
        }
        return null;
    }
    /**
     * *NOTE*: Check return value for `KeyCode.Unknown`.
     */
    static _scanCodeToKeyCode(scanCode) {
        const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
        if (immutableKeyCode !== -1 /* KeyCode.DependsOnKbLayout */) {
            return immutableKeyCode;
        }
        switch (scanCode) {
            case 10 /* ScanCode.KeyA */: return 31 /* KeyCode.KeyA */;
            case 11 /* ScanCode.KeyB */: return 32 /* KeyCode.KeyB */;
            case 12 /* ScanCode.KeyC */: return 33 /* KeyCode.KeyC */;
            case 13 /* ScanCode.KeyD */: return 34 /* KeyCode.KeyD */;
            case 14 /* ScanCode.KeyE */: return 35 /* KeyCode.KeyE */;
            case 15 /* ScanCode.KeyF */: return 36 /* KeyCode.KeyF */;
            case 16 /* ScanCode.KeyG */: return 37 /* KeyCode.KeyG */;
            case 17 /* ScanCode.KeyH */: return 38 /* KeyCode.KeyH */;
            case 18 /* ScanCode.KeyI */: return 39 /* KeyCode.KeyI */;
            case 19 /* ScanCode.KeyJ */: return 40 /* KeyCode.KeyJ */;
            case 20 /* ScanCode.KeyK */: return 41 /* KeyCode.KeyK */;
            case 21 /* ScanCode.KeyL */: return 42 /* KeyCode.KeyL */;
            case 22 /* ScanCode.KeyM */: return 43 /* KeyCode.KeyM */;
            case 23 /* ScanCode.KeyN */: return 44 /* KeyCode.KeyN */;
            case 24 /* ScanCode.KeyO */: return 45 /* KeyCode.KeyO */;
            case 25 /* ScanCode.KeyP */: return 46 /* KeyCode.KeyP */;
            case 26 /* ScanCode.KeyQ */: return 47 /* KeyCode.KeyQ */;
            case 27 /* ScanCode.KeyR */: return 48 /* KeyCode.KeyR */;
            case 28 /* ScanCode.KeyS */: return 49 /* KeyCode.KeyS */;
            case 29 /* ScanCode.KeyT */: return 50 /* KeyCode.KeyT */;
            case 30 /* ScanCode.KeyU */: return 51 /* KeyCode.KeyU */;
            case 31 /* ScanCode.KeyV */: return 52 /* KeyCode.KeyV */;
            case 32 /* ScanCode.KeyW */: return 53 /* KeyCode.KeyW */;
            case 33 /* ScanCode.KeyX */: return 54 /* KeyCode.KeyX */;
            case 34 /* ScanCode.KeyY */: return 55 /* KeyCode.KeyY */;
            case 35 /* ScanCode.KeyZ */: return 56 /* KeyCode.KeyZ */;
            case 36 /* ScanCode.Digit1 */: return 22 /* KeyCode.Digit1 */;
            case 37 /* ScanCode.Digit2 */: return 23 /* KeyCode.Digit2 */;
            case 38 /* ScanCode.Digit3 */: return 24 /* KeyCode.Digit3 */;
            case 39 /* ScanCode.Digit4 */: return 25 /* KeyCode.Digit4 */;
            case 40 /* ScanCode.Digit5 */: return 26 /* KeyCode.Digit5 */;
            case 41 /* ScanCode.Digit6 */: return 27 /* KeyCode.Digit6 */;
            case 42 /* ScanCode.Digit7 */: return 28 /* KeyCode.Digit7 */;
            case 43 /* ScanCode.Digit8 */: return 29 /* KeyCode.Digit8 */;
            case 44 /* ScanCode.Digit9 */: return 30 /* KeyCode.Digit9 */;
            case 45 /* ScanCode.Digit0 */: return 21 /* KeyCode.Digit0 */;
            case 51 /* ScanCode.Minus */: return 83 /* KeyCode.Minus */;
            case 52 /* ScanCode.Equal */: return 81 /* KeyCode.Equal */;
            case 53 /* ScanCode.BracketLeft */: return 87 /* KeyCode.BracketLeft */;
            case 54 /* ScanCode.BracketRight */: return 89 /* KeyCode.BracketRight */;
            case 55 /* ScanCode.Backslash */: return 88 /* KeyCode.Backslash */;
            case 56 /* ScanCode.IntlHash */: return 0 /* KeyCode.Unknown */; // missing
            case 57 /* ScanCode.Semicolon */: return 80 /* KeyCode.Semicolon */;
            case 58 /* ScanCode.Quote */: return 90 /* KeyCode.Quote */;
            case 59 /* ScanCode.Backquote */: return 86 /* KeyCode.Backquote */;
            case 60 /* ScanCode.Comma */: return 82 /* KeyCode.Comma */;
            case 61 /* ScanCode.Period */: return 84 /* KeyCode.Period */;
            case 62 /* ScanCode.Slash */: return 85 /* KeyCode.Slash */;
            case 106 /* ScanCode.IntlBackslash */: return 92 /* KeyCode.IntlBackslash */;
        }
        return 0 /* KeyCode.Unknown */;
    }
    static _resolveSimpleUserBinding(binding) {
        if (!binding) {
            return null;
        }
        if (binding instanceof SimpleKeybinding) {
            return binding;
        }
        const keyCode = this._scanCodeToKeyCode(binding.scanCode);
        if (keyCode === 0 /* KeyCode.Unknown */) {
            return null;
        }
        return new SimpleKeybinding(binding.ctrlKey, binding.shiftKey, binding.altKey, binding.metaKey, keyCode);
    }
    static resolveUserBinding(input, os) {
        const parts = removeElementsAfterNulls(input.map(keybinding => this._resolveSimpleUserBinding(keybinding)));
        if (parts.length > 0) {
            return [new USLayoutResolvedKeybinding(new ChordKeybinding(parts), os)];
        }
        return [];
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/contextview/contextview.css
var contextview = __webpack_require__(667);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/contextview/contextview.css

      
      
      
      
      
      
      
      
      

var contextview_options = {};

contextview_options.styleTagTransform = (styleTagTransform_default());
contextview_options.setAttributes = (setAttributesWithoutAttributes_default());

      contextview_options.insert = insertBySelector_default().bind(null, "head");
    
contextview_options.domAPI = (styleDomAPI_default());
contextview_options.insertStyleElement = (insertStyleElement_default());

var contextview_update = injectStylesIntoStyleTag_default()(contextview/* default */.A, contextview_options);




       /* harmony default export */ const contextview_contextview = (contextview/* default */.A && contextview/* default */.A.locals ? contextview/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/contextview/contextview.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






var LayoutAnchorMode;
(function (LayoutAnchorMode) {
    LayoutAnchorMode[LayoutAnchorMode["AVOID"] = 0] = "AVOID";
    LayoutAnchorMode[LayoutAnchorMode["ALIGN"] = 1] = "ALIGN";
})(LayoutAnchorMode || (LayoutAnchorMode = {}));
/**
 * Lays out a one dimensional view next to an anchor in a viewport.
 *
 * @returns The view offset within the viewport.
 */
function layout(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 /* LayoutAnchorPosition.Before */) {
        if (viewSize <= viewportSize - layoutAfterAnchorBoundary) {
            return layoutAfterAnchorBoundary; // happy case, lay it out after the anchor
        }
        if (viewSize <= layoutBeforeAnchorBoundary) {
            return layoutBeforeAnchorBoundary - viewSize; // ok case, lay it out before the anchor
        }
        return Math.max(viewportSize - viewSize, 0); // sad case, lay it over the anchor
    }
    else {
        if (viewSize <= layoutBeforeAnchorBoundary) {
            return layoutBeforeAnchorBoundary - viewSize; // happy case, lay it out before the anchor
        }
        if (viewSize <= viewportSize - layoutAfterAnchorBoundary) {
            return layoutAfterAnchorBoundary; // ok case, lay it out after the anchor
        }
        return 0; // sad case, lay it over the anchor
    }
}
class ContextView extends Disposable {
    constructor(container, domPosition) {
        super();
        this.container = null;
        this.delegate = null;
        this.toDisposeOnClean = Disposable.None;
        this.toDisposeOnSetContainer = Disposable.None;
        this.shadowRoot = null;
        this.shadowRootHostElement = null;
        this.view = dom_$('.context-view');
        this.useFixedPosition = false;
        this.useShadowDOM = false;
        hide(this.view);
        this.setContainer(container, domPosition);
        this._register(toDisposable(() => this.setContainer(null, 1 /* ContextViewDOMPosition.ABSOLUTE */)));
    }
    setContainer(container, domPosition) {
        var _a;
        if (this.container) {
            this.toDisposeOnSetContainer.dispose();
            if (this.shadowRoot) {
                this.shadowRoot.removeChild(this.view);
                this.shadowRoot = null;
                (_a = this.shadowRootHostElement) === null || _a === void 0 ? void 0 : _a.remove();
                this.shadowRootHostElement = null;
            }
            else {
                this.container.removeChild(this.view);
            }
            this.container = null;
        }
        if (container) {
            this.container = container;
            this.useFixedPosition = domPosition !== 1 /* ContextViewDOMPosition.ABSOLUTE */;
            this.useShadowDOM = domPosition === 3 /* ContextViewDOMPosition.FIXED_SHADOW */;
            if (this.useShadowDOM) {
                this.shadowRootHostElement = dom_$('.shadow-root-host');
                this.container.appendChild(this.shadowRootHostElement);
                this.shadowRoot = this.shadowRootHostElement.attachShadow({ mode: 'open' });
                const style = document.createElement('style');
                style.textContent = SHADOW_ROOT_CSS;
                this.shadowRoot.appendChild(style);
                this.shadowRoot.appendChild(this.view);
                this.shadowRoot.appendChild(dom_$('slot'));
            }
            else {
                this.container.appendChild(this.view);
            }
            const toDisposeOnSetContainer = new DisposableStore();
            ContextView.BUBBLE_UP_EVENTS.forEach(event => {
                toDisposeOnSetContainer.add(addStandardDisposableListener(this.container, event, (e) => {
                    this.onDOMEvent(e, false);
                }));
            });
            ContextView.BUBBLE_DOWN_EVENTS.forEach(event => {
                toDisposeOnSetContainer.add(addStandardDisposableListener(this.container, event, (e) => {
                    this.onDOMEvent(e, true);
                }, true));
            });
            this.toDisposeOnSetContainer = toDisposeOnSetContainer;
        }
    }
    show(delegate) {
        var _a, _b;
        if (this.isVisible()) {
            this.hide();
        }
        // Show static box
        clearNode(this.view);
        this.view.className = 'context-view';
        this.view.style.top = '0px';
        this.view.style.left = '0px';
        this.view.style.zIndex = '2575';
        this.view.style.position = this.useFixedPosition ? 'fixed' : 'absolute';
        show(this.view);
        // Render content
        this.toDisposeOnClean = delegate.render(this.view) || Disposable.None;
        // Set active delegate
        this.delegate = delegate;
        // Layout
        this.doLayout();
        // Focus
        (_b = (_a = this.delegate).focus) === null || _b === void 0 ? void 0 : _b.call(_a);
    }
    getViewElement() {
        return this.view;
    }
    layout() {
        if (!this.isVisible()) {
            return;
        }
        if (this.delegate.canRelayout === false && !(isIOS && canIUse_BrowserFeatures.pointerEvents)) {
            this.hide();
            return;
        }
        if (this.delegate.layout) {
            this.delegate.layout();
        }
        this.doLayout();
    }
    doLayout() {
        // Check that we still have a delegate - this.delegate.layout may have hidden
        if (!this.isVisible()) {
            return;
        }
        // Get anchor
        const anchor = this.delegate.getAnchor();
        // Compute around
        let around;
        // Get the element's position and size (to anchor the view)
        if (isHTMLElement(anchor)) {
            const elementPosition = getDomNodePagePosition(anchor);
            // In areas where zoom is applied to the element or its ancestors, we need to adjust the size of the element
            // e.g. The title bar has counter zoom behavior meaning it applies the inverse of zoom level.
            // Window Zoom Level: 1.5, Title Bar Zoom: 1/1.5, Size Multiplier: 1.5
            const zoom = getDomNodeZoomLevel(anchor);
            around = {
                top: elementPosition.top * zoom,
                left: elementPosition.left * zoom,
                width: elementPosition.width * zoom,
                height: elementPosition.height * zoom
            };
        }
        else {
            around = {
                top: anchor.y,
                left: anchor.x,
                width: anchor.width || 1,
                height: anchor.height || 2
            };
        }
        const viewSizeWidth = getTotalWidth(this.view);
        const viewSizeHeight = getTotalHeight(this.view);
        const anchorPosition = this.delegate.anchorPosition || 0 /* AnchorPosition.BELOW */;
        const anchorAlignment = this.delegate.anchorAlignment || 0 /* AnchorAlignment.LEFT */;
        const anchorAxisAlignment = this.delegate.anchorAxisAlignment || 0 /* AnchorAxisAlignment.VERTICAL */;
        let top;
        let left;
        if (anchorAxisAlignment === 0 /* AnchorAxisAlignment.VERTICAL */) {
            const verticalAnchor = { offset: around.top - window.pageYOffset, size: around.height, position: anchorPosition === 0 /* AnchorPosition.BELOW */ ? 0 /* LayoutAnchorPosition.Before */ : 1 /* LayoutAnchorPosition.After */ };
            const horizontalAnchor = { offset: around.left, size: around.width, position: anchorAlignment === 0 /* AnchorAlignment.LEFT */ ? 0 /* LayoutAnchorPosition.Before */ : 1 /* LayoutAnchorPosition.After */, mode: LayoutAnchorMode.ALIGN };
            top = layout(window.innerHeight, viewSizeHeight, verticalAnchor) + window.pageYOffset;
            // if view intersects vertically with anchor,  we must avoid the anchor
            if (range_Range.intersects({ start: top, end: top + viewSizeHeight }, { start: verticalAnchor.offset, end: verticalAnchor.offset + verticalAnchor.size })) {
                horizontalAnchor.mode = LayoutAnchorMode.AVOID;
            }
            left = layout(window.innerWidth, viewSizeWidth, horizontalAnchor);
        }
        else {
            const horizontalAnchor = { offset: around.left, size: around.width, position: anchorAlignment === 0 /* AnchorAlignment.LEFT */ ? 0 /* LayoutAnchorPosition.Before */ : 1 /* LayoutAnchorPosition.After */ };
            const verticalAnchor = { offset: around.top, size: around.height, position: anchorPosition === 0 /* AnchorPosition.BELOW */ ? 0 /* LayoutAnchorPosition.Before */ : 1 /* LayoutAnchorPosition.After */, mode: LayoutAnchorMode.ALIGN };
            left = layout(window.innerWidth, viewSizeWidth, horizontalAnchor);
            // if view intersects horizontally with anchor, we must avoid the anchor
            if (range_Range.intersects({ start: left, end: left + viewSizeWidth }, { start: horizontalAnchor.offset, end: horizontalAnchor.offset + horizontalAnchor.size })) {
                verticalAnchor.mode = LayoutAnchorMode.AVOID;
            }
            top = layout(window.innerHeight, viewSizeHeight, verticalAnchor) + window.pageYOffset;
        }
        this.view.classList.remove('top', 'bottom', 'left', 'right');
        this.view.classList.add(anchorPosition === 0 /* AnchorPosition.BELOW */ ? 'bottom' : 'top');
        this.view.classList.add(anchorAlignment === 0 /* AnchorAlignment.LEFT */ ? 'left' : 'right');
        this.view.classList.toggle('fixed', this.useFixedPosition);
        const containerPosition = getDomNodePagePosition(this.container);
        this.view.style.top = `${top - (this.useFixedPosition ? getDomNodePagePosition(this.view).top : containerPosition.top)}px`;
        this.view.style.left = `${left - (this.useFixedPosition ? getDomNodePagePosition(this.view).left : containerPosition.left)}px`;
        this.view.style.width = 'initial';
    }
    hide(data) {
        const delegate = this.delegate;
        this.delegate = null;
        if (delegate === null || delegate === void 0 ? void 0 : delegate.onHide) {
            delegate.onHide(data);
        }
        this.toDisposeOnClean.dispose();
        hide(this.view);
    }
    isVisible() {
        return !!this.delegate;
    }
    onDOMEvent(e, onCapture) {
        if (this.delegate) {
            if (this.delegate.onDOMEvent) {
                this.delegate.onDOMEvent(e, document.activeElement);
            }
            else if (onCapture && !isAncestor(e.target, this.container)) {
                this.hide();
            }
        }
    }
    dispose() {
        this.hide();
        super.dispose();
    }
}
ContextView.BUBBLE_UP_EVENTS = ['click', 'keydown', 'focus', 'blur'];
ContextView.BUBBLE_DOWN_EVENTS = ['click'];
const SHADOW_ROOT_CSS = /* css */ `
	:host {
		all: initial; /* 1st rule so subsequent properties are reset. */
	}

	@font-face {
		font-family: "codicon";
		font-display: block;
		src: url("./codicon.ttf?5d4d76ab2ce5108968ad644d591a16a6") format("truetype");
	}

	.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, "Nanum Gothic", "Apple SD Gothic Neo", "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; }
`;

;// ../../node_modules/monaco-editor/esm/vs/platform/contextview/browser/contextViewService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var contextViewService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var contextViewService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};



let ContextViewService = class ContextViewService extends Disposable {
    constructor(layoutService) {
        super();
        this.layoutService = layoutService;
        this.currentViewDisposable = Disposable.None;
        this.container = layoutService.hasContainer ? layoutService.container : null;
        this.contextView = this._register(new ContextView(this.container, 1 /* ContextViewDOMPosition.ABSOLUTE */));
        this.layout();
        this._register(layoutService.onDidLayout(() => this.layout()));
    }
    // ContextView
    setContainer(container, domPosition) {
        this.contextView.setContainer(container, domPosition || 1 /* ContextViewDOMPosition.ABSOLUTE */);
    }
    showContextView(delegate, container, shadowRoot) {
        if (container) {
            if (container !== this.container || this.shadowRoot !== shadowRoot) {
                this.container = container;
                this.setContainer(container, shadowRoot ? 3 /* ContextViewDOMPosition.FIXED_SHADOW */ : 2 /* ContextViewDOMPosition.FIXED */);
            }
        }
        else {
            if (this.layoutService.hasContainer && this.container !== this.layoutService.container) {
                this.container = this.layoutService.container;
                this.setContainer(this.container, 1 /* ContextViewDOMPosition.ABSOLUTE */);
            }
        }
        this.shadowRoot = shadowRoot;
        this.contextView.show(delegate);
        const disposable = toDisposable(() => {
            if (this.currentViewDisposable === disposable) {
                this.hideContextView();
            }
        });
        this.currentViewDisposable = disposable;
        return disposable;
    }
    getContextViewElement() {
        return this.contextView.getViewElement();
    }
    layout() {
        this.contextView.layout();
    }
    hideContextView(data) {
        this.contextView.hide(data);
    }
};
ContextViewService = contextViewService_decorate([
    contextViewService_param(0, ILayoutService)
], ContextViewService);


;// ../../node_modules/monaco-editor/esm/vs/base/common/glob.js
var glob_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};






const GLOBSTAR = '**';
const GLOB_SPLIT = '/';
const PATH_REGEX = '[/\\\\]'; // any slash or backslash
const NO_PATH_REGEX = '[^/\\\\]'; // any non-slash and non-backslash
const ALL_FORWARD_SLASHES = /\//g;
function starsToRegExp(starCount, isLastPattern) {
    switch (starCount) {
        case 0:
            return '';
        case 1:
            return `${NO_PATH_REGEX}*?`; // 1 star matches any number of characters except path separator (/ and \) - non greedy (?)
        default:
            // Matches:  (Path Sep OR Path Val followed by Path Sep) 0-many times except when it's the last pattern
            //           in which case also matches (Path Sep followed by Path Val)
            // Group is non capturing because we don't need to capture at all (?:...)
            // Overall we use non-greedy matching because it could be that we match too much
            return `(?:${PATH_REGEX}|${NO_PATH_REGEX}+${PATH_REGEX}${isLastPattern ? `|${PATH_REGEX}${NO_PATH_REGEX}+` : ''})*?`;
    }
}
function splitGlobAware(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;
    }
    // Tail
    if (curVal) {
        segments.push(curVal);
    }
    return segments;
}
function parseRegExp(pattern) {
    if (!pattern) {
        return '';
    }
    let regEx = '';
    // Split up into segments for each slash found
    const segments = splitGlobAware(pattern, GLOB_SPLIT);
    // Special case where we only have globstars
    if (segments.every(segment => segment === GLOBSTAR)) {
        regEx = '.*';
    }
    // Build regex over segments
    else {
        let previousSegmentWasGlobStar = false;
        segments.forEach((segment, index) => {
            // Treat globstar specially
            if (segment === GLOBSTAR) {
                // if we have more than one globstar after another, just ignore it
                if (previousSegmentWasGlobStar) {
                    return;
                }
                regEx += starsToRegExp(2, index === segments.length - 1);
            }
            // Anything else, not globstar
            else {
                // States
                let inBraces = false;
                let braceVal = '';
                let inBrackets = false;
                let bracketVal = '';
                for (const char of segment) {
                    // Support brace expansion
                    if (char !== '}' && inBraces) {
                        braceVal += char;
                        continue;
                    }
                    // Support brackets
                    if (inBrackets && (char !== ']' || !bracketVal) /* ] is literally only allowed as first character in brackets to match it */) {
                        let res;
                        // range operator
                        if (char === '-') {
                            res = char;
                        }
                        // negation operator (only valid on first index in bracket)
                        else if ((char === '^' || char === '!') && !bracketVal) {
                            res = '^';
                        }
                        // glob split matching is not allowed within character ranges
                        // see http://man7.org/linux/man-pages/man7/glob.7.html
                        else if (char === GLOB_SPLIT) {
                            res = '';
                        }
                        // anything else gets escaped
                        else {
                            res = escapeRegExpCharacters(char);
                        }
                        bracketVal += res;
                        continue;
                    }
                    switch (char) {
                        case '{':
                            inBraces = true;
                            continue;
                        case '[':
                            inBrackets = true;
                            continue;
                        case '}': {
                            const choices = splitGlobAware(braceVal, ',');
                            // Converts {foo,bar} => [foo|bar]
                            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; // 1 ? matches any single character except path separator (/ and \)
                            continue;
                        case '*':
                            regEx += starsToRegExp(1);
                            continue;
                        default:
                            regEx += escapeRegExpCharacters(char);
                    }
                }
                // Tail: Add the slash we had split on if there is more to
                // come and the remaining pattern is not a globstar
                // For example if pattern: some/**/*.js we want the "/" after
                // some to be included in the RegEx to prevent a folder called
                // "something" to match as well.
                if (index < segments.length - 1 && // more segments to come after this
                    (segments[index + 1] !== GLOBSTAR || // next segment is not **, or...
                        index + 2 < segments.length // ...next segment is ** but there is more segments after that
                    )) {
                    regEx += PATH_REGEX;
                }
            }
            // update globstar state
            previousSegmentWasGlobStar = (segment === GLOBSTAR);
        });
    }
    return regEx;
}
// regexes to check for trivial glob patterns that just check for String#endsWith
const T1 = /^\*\*\/\*\.[\w\.-]+$/; // **/*.something
const T2 = /^\*\*\/([\w\.-]+)\/?$/; // **/something
const T3 = /^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/; // {**/*.something,**/*.else} or {**/package.json,**/project.json}
const T3_2 = /^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/; // Like T3, with optional trailing /**
const T4 = /^\*\*((\/[\w\.-]+)+)\/?$/; // **/something/else
const T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/; // something/else
const CACHE = new LRUCache(10000); // bounded to 10000 elements
const FALSE = function () {
    return false;
};
const NULL = function () {
    return null;
};
function parsePattern(arg1, options) {
    if (!arg1) {
        return NULL;
    }
    // Handle relative patterns
    let pattern;
    if (typeof arg1 !== 'string') {
        pattern = arg1.pattern;
    }
    else {
        pattern = arg1;
    }
    // Whitespace trimming
    pattern = pattern.trim();
    // Check cache
    const patternKey = `${pattern}_${!!options.trimForExclusions}`;
    let parsedPattern = CACHE.get(patternKey);
    if (parsedPattern) {
        return wrapRelativePattern(parsedPattern, arg1);
    }
    // Check for Trivials
    let match;
    if (T1.test(pattern)) {
        parsedPattern = trivia1(pattern.substr(4), pattern); // common pattern: **/*.txt just need endsWith check
    }
    else if (match = T2.exec(trimForExclusions(pattern, options))) { // common pattern: **/some.txt just need basename check
        parsedPattern = trivia2(match[1], pattern);
    }
    else if ((options.trimForExclusions ? T3_2 : T3).test(pattern)) { // repetition of common patterns (see above) {**/*.txt,**/*.png}
        parsedPattern = trivia3(pattern, options);
    }
    else if (match = T4.exec(trimForExclusions(pattern, options))) { // common pattern: **/something/else just need endsWith check
        parsedPattern = trivia4and5(match[1].substr(1), pattern, true);
    }
    else if (match = T5.exec(trimForExclusions(pattern, options))) { // common pattern: something/else just need equals check
        parsedPattern = trivia4and5(match[1], pattern, false);
    }
    // Otherwise convert to pattern
    else {
        parsedPattern = toRegExp(pattern);
    }
    // Cache
    CACHE.set(patternKey, parsedPattern);
    return wrapRelativePattern(parsedPattern, arg1);
}
function wrapRelativePattern(parsedPattern, arg2) {
    if (typeof arg2 === 'string') {
        return parsedPattern;
    }
    const wrappedPattern = function (path, basename) {
        if (!isEqualOrParent(path, arg2.base, !isLinux)) {
            // skip glob matching if `base` is not a parent of `path`
            return null;
        }
        // Given we have checked `base` being a parent of `path`,
        // we can now remove the `base` portion of the `path`
        // and only match on the remaining path components
        return parsedPattern(path.substr(arg2.base.length + 1), basename);
    };
    // Make sure to preserve associated metadata
    wrappedPattern.allBasenames = parsedPattern.allBasenames;
    wrappedPattern.allPaths = parsedPattern.allPaths;
    wrappedPattern.basenames = parsedPattern.basenames;
    wrappedPattern.patterns = parsedPattern.patterns;
    return wrappedPattern;
}
function trimForExclusions(pattern, options) {
    return options.trimForExclusions && pattern.endsWith('/**') ? pattern.substr(0, pattern.length - 2) : pattern; // dropping **, tailing / is dropped later
}
// common pattern: **/*.txt just need endsWith check
function trivia1(base, pattern) {
    return function (path, basename) {
        return typeof path === 'string' && path.endsWith(base) ? pattern : null;
    };
}
// common pattern: **/some.txt just need basename check
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;
}
// repetition of common patterns (see above) {**/*.txt,**/*.png}
function trivia3(pattern, options) {
    const parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1)
        .split(',')
        .map(pattern => parsePattern(pattern, options))
        .filter(pattern => pattern !== NULL), pattern);
    const patternsLength = parsedPatterns.length;
    if (!patternsLength) {
        return NULL;
    }
    if (patternsLength === 1) {
        return parsedPatterns[0];
    }
    const parsedPattern = function (path, basename) {
        for (let i = 0, n = parsedPatterns.length; i < n; i++) {
            if (parsedPatterns[i](path, basename)) {
                return pattern;
            }
        }
        return null;
    };
    const withBasenames = parsedPatterns.find(pattern => !!pattern.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;
}
// common patterns: **/something/else just need endsWith check, something/else just needs and equals check
function trivia4and5(targetPath, pattern, matchPathEnds) {
    const usingPosixSep = path_sep === posix.sep;
    const nativePath = usingPosixSep ? targetPath : targetPath.replace(ALL_FORWARD_SLASHES, path_sep);
    const nativePathEnd = path_sep + nativePath;
    const targetPathEnd = posix.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; // reset RegExp to its initial state to reuse it!
            return typeof path === 'string' && regExp.test(path) ? pattern : null;
        };
    }
    catch (error) {
        return NULL;
    }
}
function match(arg1, path, hasSibling) {
    if (!arg1 || typeof path !== 'string') {
        return false;
    }
    return glob_parse(arg1)(path, undefined, hasSibling);
}
function glob_parse(arg1, options = {}) {
    if (!arg1) {
        return FALSE;
    }
    // Glob with String
    if (typeof arg1 === 'string' || isRelativePattern(arg1)) {
        const parsedPattern = parsePattern(arg1, options);
        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;
    }
    // Glob with Expression
    return parsedExpression(arg1, options);
}
function isRelativePattern(obj) {
    const rp = obj;
    if (!rp) {
        return false;
    }
    return typeof rp.base === 'string' && typeof rp.pattern === 'string';
}
function parsedExpression(expression, options) {
    const parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression)
        .map(pattern => parseExpressionPattern(pattern, expression[pattern], options))
        .filter(pattern => pattern !== NULL));
    const patternsLength = parsedPatterns.length;
    if (!patternsLength) {
        return NULL;
    }
    if (!parsedPatterns.some(parsedPattern => !!parsedPattern.requiresSiblings)) {
        if (patternsLength === 1) {
            return parsedPatterns[0];
        }
        const resultExpression = function (path, basename) {
            let resultPromises = undefined;
            for (let i = 0, n = parsedPatterns.length; i < n; i++) {
                const result = parsedPatterns[i](path, basename);
                if (typeof result === 'string') {
                    return result; // immediately return as soon as the first expression matches
                }
                // If the result is a promise, we have to keep it for
                // later processing and await the result properly.
                if (isThenable(result)) {
                    if (!resultPromises) {
                        resultPromises = [];
                    }
                    resultPromises.push(result);
                }
            }
            // With result promises, we have to loop over each and
            // await the result before we can return any result.
            if (resultPromises) {
                return (() => glob_awaiter(this, void 0, void 0, function* () {
                    for (const resultPromise of resultPromises) {
                        const result = yield 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;
    }
    const resultExpression = function (path, base, hasSibling) {
        let name = undefined;
        let resultPromises = undefined;
        for (let i = 0, n = parsedPatterns.length; i < n; i++) {
            // Pattern matches path
            const parsedPattern = parsedPatterns[i];
            if (parsedPattern.requiresSiblings && hasSibling) {
                if (!base) {
                    base = basename(path);
                }
                if (!name) {
                    name = base.substr(0, base.length - extname(path).length);
                }
            }
            const result = parsedPattern(path, base, name, hasSibling);
            if (typeof result === 'string') {
                return result; // immediately return as soon as the first expression matches
            }
            // If the result is a promise, we have to keep it for
            // later processing and await the result properly.
            if (isThenable(result)) {
                if (!resultPromises) {
                    resultPromises = [];
                }
                resultPromises.push(result);
            }
        }
        // With result promises, we have to loop over each and
        // await the result before we can return any result.
        if (resultPromises) {
            return (() => glob_awaiter(this, void 0, void 0, function* () {
                for (const resultPromise of resultPromises) {
                    const result = yield resultPromise;
                    if (typeof result === 'string') {
                        return result;
                    }
                }
                return null;
            }))();
        }
        return null;
    };
    const withBasenames = parsedPatterns.find(pattern => !!pattern.allBasenames);
    if (withBasenames) {
        resultExpression.allBasenames = withBasenames.allBasenames;
    }
    const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
    if (allPaths.length) {
        resultExpression.allPaths = allPaths;
    }
    return resultExpression;
}
function parseExpressionPattern(pattern, value, options) {
    if (value === false) {
        return NULL; // pattern is disabled
    }
    const parsedPattern = parsePattern(pattern, options);
    if (parsedPattern === NULL) {
        return NULL;
    }
    // Expression Pattern is <boolean>
    if (typeof value === 'boolean') {
        return parsedPattern;
    }
    // Expression Pattern is <SiblingClause>
    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 isThenable(matched) ?
                    matched.then(match => match ? pattern : null) :
                    matched ? pattern : null;
            };
            result.requiresSiblings = true;
            return result;
        }
    }
    // Expression is anything
    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 basenames = current.basenames;
        return basenames ? all.concat(basenames) : all;
    }, []);
    let patterns;
    if (result) {
        patterns = [];
        for (let i = 0, n = basenames.length; i < n; i++) {
            patterns.push(result);
        }
    }
    else {
        patterns = basenamePatterns.reduce((all, current) => {
            const patterns = current.patterns;
            return patterns ? all.concat(patterns) : all;
        }, []);
    }
    const aggregate = function (path, basename) {
        if (typeof path !== 'string') {
            return null;
        }
        if (!basename) {
            let i;
            for (i = path.length; i > 0; i--) {
                const ch = path.charCodeAt(i - 1);
                if (ch === 47 /* CharCode.Slash */ || ch === 92 /* CharCode.Backslash */) {
                    break;
                }
            }
            basename = path.substr(i);
        }
        const index = basenames.indexOf(basename);
        return index !== -1 ? patterns[index] : null;
    };
    aggregate.basenames = basenames;
    aggregate.patterns = patterns;
    aggregate.allBasenames = basenames;
    const aggregatedPatterns = parsedPatterns.filter(parsedPattern => !parsedPattern.basenames);
    aggregatedPatterns.push(aggregate);
    return aggregatedPatterns;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/languagesAssociations.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







let registeredAssociations = [];
let nonUserRegisteredAssociations = [];
let userRegisteredAssociations = [];
/**
 * Associate a language to the registry (platform).
 * * **NOTE**: This association will lose over associations registered using `registerConfiguredLanguageAssociation`.
 * * **NOTE**: Use `clearPlatformLanguageAssociations` to remove all associations registered using this function.
 */
function registerPlatformLanguageAssociation(association, warnOnOverwrite = false) {
    _registerLanguageAssociation(association, false, warnOnOverwrite);
}
function _registerLanguageAssociation(association, userConfigured, warnOnOverwrite) {
    // Register
    const associationItem = toLanguageAssociationItem(association, userConfigured);
    registeredAssociations.push(associationItem);
    if (!associationItem.userConfigured) {
        nonUserRegisteredAssociations.push(associationItem);
    }
    else {
        userRegisteredAssociations.push(associationItem);
    }
    // Check for conflicts unless this is a user configured association
    if (warnOnOverwrite && !associationItem.userConfigured) {
        registeredAssociations.forEach(a => {
            if (a.mime === associationItem.mime || a.userConfigured) {
                return; // same mime or userConfigured is ok
            }
            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: userConfigured,
        filenameLowercase: association.filename ? association.filename.toLowerCase() : undefined,
        extensionLowercase: association.extension ? association.extension.toLowerCase() : undefined,
        filepatternLowercase: association.filepattern ? glob_parse(association.filepattern.toLowerCase()) : undefined,
        filepatternOnPath: association.filepattern ? association.filepattern.indexOf(posix.sep) >= 0 : false
    };
}
/**
 * Clear language associations from the registry (platform).
 */
function clearPlatformLanguageAssociations() {
    registeredAssociations = registeredAssociations.filter(a => a.userConfigured);
    nonUserRegisteredAssociations = [];
}
/**
 * @see `getMimeTypes`
 */
function getLanguageIds(resource, firstLine) {
    return getAssociations(resource, firstLine).map(item => item.id);
}
function getAssociations(resource, firstLine) {
    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:
                // File path not relevant for language detection of cell
                path = undefined;
                break;
            default:
                path = resource.path;
        }
    }
    if (!path) {
        return [{ id: 'unknown', mime: Mimes.unknown }];
    }
    path = path.toLowerCase();
    const filename = basename(path);
    // 1.) User configured mappings have highest priority
    const configuredLanguage = getAssociationByPath(path, filename, userRegisteredAssociations);
    if (configuredLanguage) {
        return [configuredLanguage, { id: PLAINTEXT_LANGUAGE_ID, mime: Mimes.text }];
    }
    // 2.) Registered mappings have middle priority
    const registeredLanguage = getAssociationByPath(path, filename, nonUserRegisteredAssociations);
    if (registeredLanguage) {
        return [registeredLanguage, { id: PLAINTEXT_LANGUAGE_ID, mime: Mimes.text }];
    }
    // 3.) Firstline has lowest priority
    if (firstLine) {
        const firstlineLanguage = getAssociationByFirstline(firstLine);
        if (firstlineLanguage) {
            return [firstlineLanguage, { id: PLAINTEXT_LANGUAGE_ID, mime: Mimes.text }];
        }
    }
    return [{ id: 'unknown', mime: Mimes.unknown }];
}
function getAssociationByPath(path, filename, associations) {
    var _a;
    let filenameMatch = undefined;
    let patternMatch = undefined;
    let extensionMatch = undefined;
    // We want to prioritize associations based on the order they are registered so that the last registered
    // association wins over all other. This is for https://github.com/microsoft/vscode/issues/20074
    for (let i = associations.length - 1; i >= 0; i--) {
        const association = associations[i];
        // First exact name match
        if (filename === association.filenameLowercase) {
            filenameMatch = association;
            break; // take it!
        }
        // Longest pattern match
        if (association.filepattern) {
            if (!patternMatch || association.filepattern.length > patternMatch.filepattern.length) {
                const target = association.filepatternOnPath ? path : filename; // match on full path if pattern contains path separator
                if ((_a = association.filepatternLowercase) === null || _a === void 0 ? void 0 : _a.call(association, target)) {
                    patternMatch = association;
                }
            }
        }
        // Longest extension match
        if (association.extension) {
            if (!extensionMatch || association.extension.length > extensionMatch.extension.length) {
                if (filename.endsWith(association.extensionLowercase)) {
                    extensionMatch = association;
                }
            }
        }
    }
    // 1.) Exact name match has second highest priority
    if (filenameMatch) {
        return filenameMatch;
    }
    // 2.) Match on pattern
    if (patternMatch) {
        return patternMatch;
    }
    // 3.) Match on extension comes next
    if (extensionMatch) {
        return extensionMatch;
    }
    return undefined;
}
function getAssociationByFirstline(firstLine) {
    if (startsWithUTF8BOM(firstLine)) {
        firstLine = firstLine.substr(1);
    }
    if (firstLine.length > 0) {
        // We want to prioritize associations based on the order they are registered so that the last registered
        // association wins over all other. This is for https://github.com/microsoft/vscode/issues/20074
        for (let i = registeredAssociations.length - 1; i >= 0; i--) {
            const association = registeredAssociations[i];
            if (!association.firstline) {
                continue;
            }
            const matches = firstLine.match(association.firstline);
            if (matches && matches.length > 0) {
                return association;
            }
        }
    }
    return undefined;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/languagesRegistry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/








const languagesRegistry_hasOwnProperty = Object.prototype.hasOwnProperty;
const NULL_LANGUAGE_ID = 'vs.editor.nullLanguage';
class LanguageIdCodec {
    constructor() {
        this._languageIdToLanguage = [];
        this._languageToLanguageId = new Map();
        this._register(NULL_LANGUAGE_ID, 0 /* LanguageId.Null */);
        this._register(PLAINTEXT_LANGUAGE_ID, 1 /* LanguageId.PlainText */);
        this._nextLanguageId = 2;
    }
    _register(language, languageId) {
        this._languageIdToLanguage[languageId] = language;
        this._languageToLanguageId.set(language, languageId);
    }
    register(language) {
        if (this._languageToLanguageId.has(language)) {
            return;
        }
        const languageId = this._nextLanguageId++;
        this._register(language, languageId);
    }
    encodeLanguageId(languageId) {
        return this._languageToLanguageId.get(languageId) || 0 /* LanguageId.Null */;
    }
    decodeLanguageId(languageId) {
        return this._languageIdToLanguage[languageId] || NULL_LANGUAGE_ID;
    }
}
class LanguagesRegistry extends Disposable {
    constructor(useModesRegistry = true, warnOnOverwrite = false) {
        super();
        this._onDidChange = this._register(new Emitter());
        this.onDidChange = this._onDidChange.event;
        LanguagesRegistry.instanceCount++;
        this._warnOnOverwrite = warnOnOverwrite;
        this.languageIdCodec = new LanguageIdCodec();
        this._dynamicLanguages = [];
        this._languages = {};
        this._mimeTypesMap = {};
        this._nameMap = {};
        this._lowercaseNameMap = {};
        if (useModesRegistry) {
            this._initializeFromRegistry();
            this._register(ModesRegistry.onDidChangeLanguages((m) => {
                this._initializeFromRegistry();
            }));
        }
    }
    dispose() {
        LanguagesRegistry.instanceCount--;
        super.dispose();
    }
    _initializeFromRegistry() {
        this._languages = {};
        this._mimeTypesMap = {};
        this._nameMap = {};
        this._lowercaseNameMap = {};
        clearPlatformLanguageAssociations();
        const desc = [].concat(ModesRegistry.getLanguages()).concat(this._dynamicLanguages);
        this._registerLanguages(desc);
    }
    _registerLanguages(desc) {
        for (const d of desc) {
            this._registerLanguage(d);
        }
        // Rebuild fast path maps
        this._mimeTypesMap = {};
        this._nameMap = {};
        this._lowercaseNameMap = {};
        Object.keys(this._languages).forEach((langId) => {
            const language = this._languages[langId];
            if (language.name) {
                this._nameMap[language.name] = language.identifier;
            }
            language.aliases.forEach((alias) => {
                this._lowercaseNameMap[alias.toLowerCase()] = language.identifier;
            });
            language.mimetypes.forEach((mimetype) => {
                this._mimeTypesMap[mimetype] = language.identifier;
            });
        });
        Registry.as(configurationRegistry_Extensions.Configuration).registerOverrideIdentifiers(this.getRegisteredLanguageIds());
        this._onDidChange.fire();
    }
    _registerLanguage(lang) {
        const langId = lang.id;
        let resolvedLanguage;
        if (languagesRegistry_hasOwnProperty.call(this._languages, langId)) {
            resolvedLanguage = this._languages[langId];
        }
        else {
            this.languageIdCodec.register(langId);
            resolvedLanguage = {
                identifier: langId,
                name: null,
                mimetypes: [],
                aliases: [],
                extensions: [],
                filenames: [],
                configurationFiles: [],
                icons: []
            };
            this._languages[langId] = resolvedLanguage;
        }
        this._mergeLanguage(resolvedLanguage, lang);
    }
    _mergeLanguage(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) {
                // insert first as this appears to be the 'primary' language definition
                resolvedLanguage.extensions = lang.extensions.concat(resolvedLanguage.extensions);
            }
            else {
                resolvedLanguage.extensions = resolvedLanguage.extensions.concat(lang.extensions);
            }
            for (const extension of lang.extensions) {
                registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, extension: extension }, this._warnOnOverwrite);
            }
        }
        if (Array.isArray(lang.filenames)) {
            for (const filename of lang.filenames) {
                registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, filename: filename }, this._warnOnOverwrite);
                resolvedLanguage.filenames.push(filename);
            }
        }
        if (Array.isArray(lang.filenamePatterns)) {
            for (const filenamePattern of lang.filenamePatterns) {
                registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, filepattern: filenamePattern }, this._warnOnOverwrite);
            }
        }
        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 (!regExpLeadsToEndlessLoop(firstLineRegex)) {
                    registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, firstline: firstLineRegex }, this._warnOnOverwrite);
                }
            }
            catch (err) {
                // Most likely, the regex was bad
                onUnexpectedError(err);
            }
        }
        resolvedLanguage.aliases.push(langId);
        let langAliases = null;
        if (typeof lang.aliases !== 'undefined' && Array.isArray(lang.aliases)) {
            if (lang.aliases.length === 0) {
                // signal that this language should not get a name
                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) {
            // signal that this language should not get a name
        }
        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 languagesRegistry_hasOwnProperty.call(this._languages, languageId);
    }
    getRegisteredLanguageIds() {
        return Object.keys(this._languages);
    }
    getLanguageIdByLanguageName(languageName) {
        const languageNameLower = languageName.toLowerCase();
        if (!languagesRegistry_hasOwnProperty.call(this._lowercaseNameMap, languageNameLower)) {
            return null;
        }
        return this._lowercaseNameMap[languageNameLower];
    }
    getLanguageIdByMimeType(mimeType) {
        if (!mimeType) {
            return null;
        }
        if (languagesRegistry_hasOwnProperty.call(this._mimeTypesMap, mimeType)) {
            return this._mimeTypesMap[mimeType];
        }
        return null;
    }
    guessLanguageIdByFilepathOrFirstLine(resource, firstLine) {
        if (!resource && !firstLine) {
            return [];
        }
        return getLanguageIds(resource, firstLine);
    }
}
LanguagesRegistry.instanceCount = 0;

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/languageService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






class LanguageService extends Disposable {
    constructor(warnOnOverwrite = false) {
        super();
        this._onDidEncounterLanguage = this._register(new Emitter());
        this.onDidEncounterLanguage = this._onDidEncounterLanguage.event;
        this._onDidChange = this._register(new Emitter({ leakWarningThreshold: 200 /* https://github.com/microsoft/vscode/issues/119968 */ }));
        this.onDidChange = this._onDidChange.event;
        LanguageService.instanceCount++;
        this._encounteredLanguages = new Set();
        this._registry = this._register(new LanguagesRegistry(true, warnOnOverwrite));
        this.languageIdCodec = this._registry.languageIdCodec;
        this._register(this._registry.onDidChange(() => this._onDidChange.fire()));
    }
    dispose() {
        LanguageService.instanceCount--;
        super.dispose();
    }
    isRegisteredLanguageId(languageId) {
        return this._registry.isRegisteredLanguageId(languageId);
    }
    getLanguageIdByLanguageName(languageName) {
        return this._registry.getLanguageIdByLanguageName(languageName);
    }
    getLanguageIdByMimeType(mimeType) {
        return this._registry.getLanguageIdByMimeType(mimeType);
    }
    guessLanguageIdByFilepathOrFirstLine(resource, firstLine) {
        const languageIds = this._registry.guessLanguageIdByFilepathOrFirstLine(resource, firstLine);
        return firstOrDefault(languageIds, null);
    }
    createById(languageId) {
        return new LanguageSelection(this.onDidChange, () => {
            return this._createAndGetLanguageIdentifier(languageId);
        });
    }
    createByFilepathOrFirstLine(resource, firstLine) {
        return new LanguageSelection(this.onDidChange, () => {
            const languageId = this.guessLanguageIdByFilepathOrFirstLine(resource, firstLine);
            return this._createAndGetLanguageIdentifier(languageId);
        });
    }
    _createAndGetLanguageIdentifier(languageId) {
        if (!languageId || !this.isRegisteredLanguageId(languageId)) {
            // Fall back to plain text if language is unknown
            languageId = PLAINTEXT_LANGUAGE_ID;
        }
        if (!this._encounteredLanguages.has(languageId)) {
            this._encounteredLanguages.add(languageId);
            // Ensure tokenizers are created
            languages_TokenizationRegistry.getOrCreate(languageId);
            // Fire event
            this._onDidEncounterLanguage.fire(languageId);
        }
        return languageId;
    }
}
LanguageService.instanceCount = 0;
class LanguageSelection {
    constructor(_onDidChangeLanguages, _selector) {
        this._onDidChangeLanguages = _onDidChangeLanguages;
        this._selector = _selector;
        this._listener = null;
        this._emitter = null;
        this.languageId = this._selector();
    }
    _dispose() {
        if (this._listener) {
            this._listener.dispose();
            this._listener = null;
        }
        if (this._emitter) {
            this._emitter.dispose();
            this._emitter = null;
        }
    }
    get onDidChange() {
        if (!this._listener) {
            this._listener = this._onDidChangeLanguages(() => this._evaluate());
        }
        if (!this._emitter) {
            this._emitter = new Emitter({
                onLastListenerRemove: () => {
                    this._dispose();
                }
            });
        }
        return this._emitter.event;
    }
    _evaluate() {
        var _a;
        const languageId = this._selector();
        if (languageId === this.languageId) {
            // no change
            return;
        }
        this.languageId = languageId;
        (_a = this._emitter) === null || _a === void 0 ? void 0 : _a.fire(this.languageId);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/menu/menu.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

















const MENU_MNEMONIC_REGEX = /\(&([^\s&])\)|(^|[^&])&([^\s&])/;
const MENU_ESCAPED_MNEMONIC_REGEX = /(&amp;)?(&amp;)([^\s&])/g;
var Direction;
(function (Direction) {
    Direction[Direction["Right"] = 0] = "Right";
    Direction[Direction["Left"] = 1] = "Left";
})(Direction || (Direction = {}));
class Menu extends ActionBar {
    constructor(container, actions, options = {}) {
        container.classList.add('monaco-menu-container');
        container.setAttribute('role', 'presentation');
        const menuElement = document.createElement('div');
        menuElement.classList.add('monaco-menu');
        menuElement.setAttribute('role', 'presentation');
        super(menuElement, {
            orientation: 1 /* ActionsOrientation.VERTICAL */,
            actionViewItemProvider: action => this.doGetActionViewItem(action, options, parentData),
            context: options.context,
            actionRunner: options.actionRunner,
            ariaLabel: options.ariaLabel,
            ariaRole: 'menu',
            focusOnlyEnabledItems: true,
            triggerKeys: { keys: [3 /* KeyCode.Enter */, ...(isMacintosh || isLinux ? [10 /* KeyCode.Space */] : [])], keyDown: true }
        });
        this.menuElement = menuElement;
        this.actionsList.tabIndex = 0;
        this.menuDisposables = this._register(new DisposableStore());
        this.initializeOrUpdateStyleSheet(container, {});
        this._register(Gesture.addTarget(menuElement));
        addDisposableListener(menuElement, EventType.KEY_DOWN, (e) => {
            const event = new StandardKeyboardEvent(e);
            // Stop tab navigation of menus
            if (event.equals(2 /* KeyCode.Tab */)) {
                e.preventDefault();
            }
        });
        if (options.enableMnemonics) {
            this.menuDisposables.add(addDisposableListener(menuElement, EventType.KEY_DOWN, (e) => {
                const key = e.key.toLocaleLowerCase();
                if (this.mnemonics.has(key)) {
                    EventHelper.stop(e, true);
                    const actions = this.mnemonics.get(key);
                    if (actions.length === 1) {
                        if (actions[0] instanceof SubmenuMenuActionViewItem && actions[0].container) {
                            this.focusItemByElement(actions[0].container);
                        }
                        actions[0].onClick(e);
                    }
                    if (actions.length > 1) {
                        const action = actions.shift();
                        if (action && action.container) {
                            this.focusItemByElement(action.container);
                            actions.push(action);
                        }
                        this.mnemonics.set(key, actions);
                    }
                }
            }));
        }
        if (isLinux) {
            this._register(addDisposableListener(menuElement, EventType.KEY_DOWN, e => {
                const event = new StandardKeyboardEvent(e);
                if (event.equals(14 /* KeyCode.Home */) || event.equals(11 /* KeyCode.PageUp */)) {
                    this.focusedItem = this.viewItems.length - 1;
                    this.focusNext();
                    EventHelper.stop(e, true);
                }
                else if (event.equals(13 /* KeyCode.End */) || event.equals(12 /* KeyCode.PageDown */)) {
                    this.focusedItem = 0;
                    this.focusPrevious();
                    EventHelper.stop(e, true);
                }
            }));
        }
        this._register(addDisposableListener(this.domNode, EventType.MOUSE_OUT, e => {
            const relatedTarget = e.relatedTarget;
            if (!isAncestor(relatedTarget, this.domNode)) {
                this.focusedItem = undefined;
                this.updateFocus();
                e.stopPropagation();
            }
        }));
        this._register(addDisposableListener(this.actionsList, EventType.MOUSE_OVER, e => {
            let target = e.target;
            if (!target || !isAncestor(target, this.actionsList) || target === this.actionsList) {
                return;
            }
            while (target.parentElement !== this.actionsList && target.parentElement !== null) {
                target = target.parentElement;
            }
            if (target.classList.contains('action-item')) {
                const lastFocusedItem = this.focusedItem;
                this.setFocusedItem(target);
                if (lastFocusedItem !== this.focusedItem) {
                    this.updateFocus();
                }
            }
        }));
        // Support touch on actions list to focus items (needed for submenus)
        this._register(Gesture.addTarget(this.actionsList));
        this._register(addDisposableListener(this.actionsList, touch_EventType.Tap, e => {
            let target = e.initialTarget;
            if (!target || !isAncestor(target, this.actionsList) || target === this.actionsList) {
                return;
            }
            while (target.parentElement !== this.actionsList && target.parentElement !== null) {
                target = target.parentElement;
            }
            if (target.classList.contains('action-item')) {
                const lastFocusedItem = this.focusedItem;
                this.setFocusedItem(target);
                if (lastFocusedItem !== this.focusedItem) {
                    this.updateFocus();
                }
            }
        }));
        const parentData = {
            parent: this
        };
        this.mnemonics = new Map();
        // Scroll Logic
        this.scrollableElement = this._register(new DomScrollableElement(menuElement, {
            alwaysConsumeMouseWheel: true,
            horizontal: 2 /* ScrollbarVisibility.Hidden */,
            vertical: 3 /* ScrollbarVisibility.Visible */,
            verticalScrollbarSize: 7,
            handleMouseWheel: true,
            useShadows: true
        }));
        const scrollElement = this.scrollableElement.getDomNode();
        scrollElement.style.position = '';
        // Support scroll on menu drag
        this._register(addDisposableListener(menuElement, touch_EventType.Change, e => {
            EventHelper.stop(e, true);
            const scrollTop = this.scrollableElement.getScrollPosition().scrollTop;
            this.scrollableElement.setScrollPosition({ scrollTop: scrollTop - e.translationY });
        }));
        this._register(addDisposableListener(scrollElement, EventType.MOUSE_UP, e => {
            // Absorb clicks in menu dead space https://github.com/microsoft/vscode/issues/63575
            // We do this on the scroll element so the scroll bar doesn't dismiss the menu either
            e.preventDefault();
        }));
        menuElement.style.maxHeight = `${Math.max(10, window.innerHeight - container.getBoundingClientRect().top - 35)}px`;
        actions = actions.filter(a => {
            var _a;
            if ((_a = options.submenuIds) === null || _a === void 0 ? void 0 : _a.has(a.id)) {
                console.warn(`Found submenu cycle: ${a.id}`);
                return false;
            }
            return true;
        });
        this.push(actions, { icon: true, label: true, isMenu: true });
        container.appendChild(this.scrollableElement.getDomNode());
        this.scrollableElement.scanDomNode();
        this.viewItems.filter(item => !(item instanceof MenuSeparatorActionViewItem)).forEach((item, index, array) => {
            item.updatePositionInSet(index + 1, array.length);
        });
    }
    initializeOrUpdateStyleSheet(container, style) {
        if (!this.styleSheet) {
            if (isInShadowDOM(container)) {
                this.styleSheet = createStyleSheet(container);
            }
            else {
                if (!Menu.globalStyleSheet) {
                    Menu.globalStyleSheet = createStyleSheet();
                }
                this.styleSheet = Menu.globalStyleSheet;
            }
        }
        this.styleSheet.textContent = getMenuWidgetCSS(style, isInShadowDOM(container));
    }
    style(style) {
        const container = this.getContainer();
        this.initializeOrUpdateStyleSheet(container, style);
        const fgColor = style.foregroundColor ? `${style.foregroundColor}` : '';
        const bgColor = style.backgroundColor ? `${style.backgroundColor}` : '';
        const border = style.borderColor ? `1px solid ${style.borderColor}` : '';
        const borderRadius = '5px';
        const shadow = style.shadowColor ? `0 2px 8px ${style.shadowColor}` : '';
        container.style.outline = border;
        container.style.borderRadius = borderRadius;
        container.style.color = fgColor;
        container.style.backgroundColor = bgColor;
        container.style.boxShadow = shadow;
        if (this.viewItems) {
            this.viewItems.forEach(item => {
                if (item instanceof BaseMenuActionViewItem || item instanceof MenuSeparatorActionViewItem) {
                    item.style(style);
                }
            });
        }
    }
    getContainer() {
        return this.scrollableElement.getDomNode();
    }
    get onScroll() {
        return this.scrollableElement.onScroll;
    }
    focusItemByElement(element) {
        const lastFocusedItem = this.focusedItem;
        this.setFocusedItem(element);
        if (lastFocusedItem !== this.focusedItem) {
            this.updateFocus();
        }
    }
    setFocusedItem(element) {
        for (let i = 0; i < this.actionsList.children.length; i++) {
            const elem = this.actionsList.children[i];
            if (element === elem) {
                this.focusedItem = i;
                break;
            }
        }
    }
    updateFocus(fromRight) {
        super.updateFocus(fromRight, true, true);
        if (typeof this.focusedItem !== 'undefined') {
            // Workaround for #80047 caused by an issue in chromium
            // https://bugs.chromium.org/p/chromium/issues/detail?id=414283
            // When that's fixed, just call this.scrollableElement.scanDomNode()
            this.scrollableElement.setScrollPosition({
                scrollTop: Math.round(this.menuElement.scrollTop)
            });
        }
    }
    doGetActionViewItem(action, options, parentData) {
        if (action instanceof Separator) {
            return new MenuSeparatorActionViewItem(options.context, action, { icon: true });
        }
        else if (action instanceof SubmenuAction) {
            const menuActionViewItem = new SubmenuMenuActionViewItem(action, action.actions, parentData, Object.assign(Object.assign({}, options), { submenuIds: new Set([...(options.submenuIds || []), action.id]) }));
            if (options.enableMnemonics) {
                const mnemonic = menuActionViewItem.getMnemonic();
                if (mnemonic && menuActionViewItem.isEnabled()) {
                    let actionViewItems = [];
                    if (this.mnemonics.has(mnemonic)) {
                        actionViewItems = this.mnemonics.get(mnemonic);
                    }
                    actionViewItems.push(menuActionViewItem);
                    this.mnemonics.set(mnemonic, actionViewItems);
                }
            }
            return menuActionViewItem;
        }
        else {
            const menuItemOptions = { enableMnemonics: options.enableMnemonics, useEventAsContext: options.useEventAsContext };
            if (options.getKeyBinding) {
                const keybinding = options.getKeyBinding(action);
                if (keybinding) {
                    const keybindingLabel = keybinding.getLabel();
                    if (keybindingLabel) {
                        menuItemOptions.keybinding = keybindingLabel;
                    }
                }
            }
            const menuActionViewItem = new BaseMenuActionViewItem(options.context, action, menuItemOptions);
            if (options.enableMnemonics) {
                const mnemonic = menuActionViewItem.getMnemonic();
                if (mnemonic && menuActionViewItem.isEnabled()) {
                    let actionViewItems = [];
                    if (this.mnemonics.has(mnemonic)) {
                        actionViewItems = this.mnemonics.get(mnemonic);
                    }
                    actionViewItems.push(menuActionViewItem);
                    this.mnemonics.set(mnemonic, actionViewItems);
                }
            }
            return menuActionViewItem;
        }
    }
}
class BaseMenuActionViewItem extends BaseActionViewItem {
    constructor(ctx, action, options = {}) {
        options.isMenu = true;
        super(action, action, options);
        this.options = options;
        this.options.icon = options.icon !== undefined ? options.icon : false;
        this.options.label = options.label !== undefined ? options.label : true;
        this.cssClass = '';
        // Set mnemonic
        if (this.options.label && options.enableMnemonics) {
            const label = this.getAction().label;
            if (label) {
                const matches = MENU_MNEMONIC_REGEX.exec(label);
                if (matches) {
                    this.mnemonic = (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase();
                }
            }
        }
        // Add mouse up listener later to avoid accidental clicks
        this.runOnceToEnableMouseUp = new RunOnceScheduler(() => {
            if (!this.element) {
                return;
            }
            this._register(addDisposableListener(this.element, EventType.MOUSE_UP, e => {
                // removed default prevention as it conflicts
                // with BaseActionViewItem #101537
                // add back if issues arise and link new issue
                EventHelper.stop(e, true);
                // See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Interact_with_the_clipboard
                // > Writing to the clipboard
                // > You can use the "cut" and "copy" commands without any special
                // permission if you are using them in a short-lived event handler
                // for a user action (for example, a click handler).
                // => to get the Copy and Paste context menu actions working on Firefox,
                // there should be no timeout here
                if (browser_isFirefox) {
                    const mouseEvent = new StandardMouseEvent(e);
                    // Allowing right click to trigger the event causes the issue described below,
                    // but since the solution below does not work in FF, we must disable right click
                    if (mouseEvent.rightButton) {
                        return;
                    }
                    this.onClick(e);
                }
                // In all other cases, set timeout to allow context menu cancellation to trigger
                // otherwise the action will destroy the menu and a second context menu
                // will still trigger for right click.
                else {
                    setTimeout(() => {
                        this.onClick(e);
                    }, 0);
                }
            }));
            this._register(addDisposableListener(this.element, EventType.CONTEXT_MENU, e => {
                EventHelper.stop(e, true);
            }));
        }, 100);
        this._register(this.runOnceToEnableMouseUp);
    }
    render(container) {
        super.render(container);
        if (!this.element) {
            return;
        }
        this.container = container;
        this.item = append(this.element, dom_$('a.action-menu-item'));
        if (this._action.id === Separator.ID) {
            // A separator is a presentation item
            this.item.setAttribute('role', 'presentation');
        }
        else {
            this.item.setAttribute('role', 'menuitem');
            if (this.mnemonic) {
                this.item.setAttribute('aria-keyshortcuts', `${this.mnemonic}`);
            }
        }
        this.check = append(this.item, dom_$('span.menu-item-check' + Codicon.menuSelection.cssSelector));
        this.check.setAttribute('role', 'none');
        this.label = append(this.item, dom_$('span.action-label'));
        if (this.options.label && this.options.keybinding) {
            append(this.item, dom_$('span.keybinding')).textContent = this.options.keybinding;
        }
        // Adds mouse up listener to actually run the action
        this.runOnceToEnableMouseUp.schedule();
        this.updateClass();
        this.updateLabel();
        this.updateTooltip();
        this.updateEnabled();
        this.updateChecked();
    }
    blur() {
        super.blur();
        this.applyStyle();
    }
    focus() {
        super.focus();
        if (this.item) {
            this.item.focus();
        }
        this.applyStyle();
    }
    updatePositionInSet(pos, setSize) {
        if (this.item) {
            this.item.setAttribute('aria-posinset', `${pos}`);
            this.item.setAttribute('aria-setsize', `${setSize}`);
        }
    }
    updateLabel() {
        var _a;
        if (!this.label) {
            return;
        }
        if (this.options.label) {
            clearNode(this.label);
            let label = stripIcons(this.getAction().label);
            if (label) {
                const cleanLabel = cleanMnemonic(label);
                if (!this.options.enableMnemonics) {
                    label = cleanLabel;
                }
                this.label.setAttribute('aria-label', cleanLabel.replace(/&&/g, '&'));
                const matches = MENU_MNEMONIC_REGEX.exec(label);
                if (matches) {
                    label = strings_escape(label);
                    // This is global, reset it
                    MENU_ESCAPED_MNEMONIC_REGEX.lastIndex = 0;
                    let escMatch = MENU_ESCAPED_MNEMONIC_REGEX.exec(label);
                    // We can't use negative lookbehind so if we match our negative and skip
                    while (escMatch && escMatch[1]) {
                        escMatch = MENU_ESCAPED_MNEMONIC_REGEX.exec(label);
                    }
                    const replaceDoubleEscapes = (str) => str.replace(/&amp;&amp;/g, '&amp;');
                    if (escMatch) {
                        this.label.append(ltrim(replaceDoubleEscapes(label.substr(0, escMatch.index)), ' '), dom_$('u', { 'aria-hidden': 'true' }, escMatch[3]), rtrim(replaceDoubleEscapes(label.substr(escMatch.index + escMatch[0].length)), ' '));
                    }
                    else {
                        this.label.innerText = replaceDoubleEscapes(label).trim();
                    }
                    (_a = this.item) === null || _a === void 0 ? void 0 : _a.setAttribute('aria-keyshortcuts', (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase());
                }
                else {
                    this.label.innerText = label.replace(/&&/g, '&').trim();
                }
            }
        }
    }
    updateTooltip() {
        // menus should function like native menus and they do not have tooltips
    }
    updateClass() {
        if (this.cssClass && this.item) {
            this.item.classList.remove(...this.cssClass.split(' '));
        }
        if (this.options.icon && this.label) {
            this.cssClass = this.getAction().class || '';
            this.label.classList.add('icon');
            if (this.cssClass) {
                this.label.classList.add(...this.cssClass.split(' '));
            }
            this.updateEnabled();
        }
        else if (this.label) {
            this.label.classList.remove('icon');
        }
    }
    updateEnabled() {
        if (this.getAction().enabled) {
            if (this.element) {
                this.element.classList.remove('disabled');
                this.element.removeAttribute('aria-disabled');
            }
            if (this.item) {
                this.item.classList.remove('disabled');
                this.item.removeAttribute('aria-disabled');
                this.item.tabIndex = 0;
            }
        }
        else {
            if (this.element) {
                this.element.classList.add('disabled');
                this.element.setAttribute('aria-disabled', 'true');
            }
            if (this.item) {
                this.item.classList.add('disabled');
                this.item.setAttribute('aria-disabled', 'true');
            }
        }
    }
    updateChecked() {
        if (!this.item) {
            return;
        }
        const checked = this.getAction().checked;
        this.item.classList.toggle('checked', !!checked);
        if (checked !== undefined) {
            this.item.setAttribute('role', 'menuitemcheckbox');
            this.item.setAttribute('aria-checked', checked ? 'true' : 'false');
        }
        else {
            this.item.setAttribute('role', 'menuitem');
            this.item.setAttribute('aria-checked', '');
        }
    }
    getMnemonic() {
        return this.mnemonic;
    }
    applyStyle() {
        if (!this.menuStyle) {
            return;
        }
        const isSelected = this.element && this.element.classList.contains('focused');
        const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
        const bgColor = isSelected && this.menuStyle.selectionBackgroundColor ? this.menuStyle.selectionBackgroundColor : undefined;
        const outline = isSelected && this.menuStyle.selectionBorderColor ? `1px solid ${this.menuStyle.selectionBorderColor}` : '';
        const outlineOffset = isSelected && this.menuStyle.selectionBorderColor ? `-1px` : '';
        if (this.item) {
            this.item.style.color = fgColor ? fgColor.toString() : '';
            this.item.style.backgroundColor = bgColor ? bgColor.toString() : '';
            this.item.style.outline = outline;
            this.item.style.outlineOffset = outlineOffset;
        }
        if (this.check) {
            this.check.style.color = fgColor ? fgColor.toString() : '';
        }
    }
    style(style) {
        this.menuStyle = style;
        this.applyStyle();
    }
}
class SubmenuMenuActionViewItem extends BaseMenuActionViewItem {
    constructor(action, submenuActions, parentData, submenuOptions) {
        super(action, action, submenuOptions);
        this.submenuActions = submenuActions;
        this.parentData = parentData;
        this.submenuOptions = submenuOptions;
        this.mysubmenu = null;
        this.submenuDisposables = this._register(new DisposableStore());
        this.mouseOver = false;
        this.expandDirection = submenuOptions && submenuOptions.expandDirection !== undefined ? submenuOptions.expandDirection : Direction.Right;
        this.showScheduler = new RunOnceScheduler(() => {
            if (this.mouseOver) {
                this.cleanupExistingSubmenu(false);
                this.createSubmenu(false);
            }
        }, 250);
        this.hideScheduler = new RunOnceScheduler(() => {
            if (this.element && (!isAncestor(getActiveElement(), this.element) && this.parentData.submenu === this.mysubmenu)) {
                this.parentData.parent.focus(false);
                this.cleanupExistingSubmenu(true);
            }
        }, 750);
    }
    render(container) {
        super.render(container);
        if (!this.element) {
            return;
        }
        if (this.item) {
            this.item.classList.add('monaco-submenu-item');
            this.item.tabIndex = 0;
            this.item.setAttribute('aria-haspopup', 'true');
            this.updateAriaExpanded('false');
            this.submenuIndicator = append(this.item, dom_$('span.submenu-indicator' + Codicon.menuSubmenu.cssSelector));
            this.submenuIndicator.setAttribute('aria-hidden', 'true');
        }
        this._register(addDisposableListener(this.element, EventType.KEY_UP, e => {
            const event = new StandardKeyboardEvent(e);
            if (event.equals(17 /* KeyCode.RightArrow */) || event.equals(3 /* KeyCode.Enter */)) {
                EventHelper.stop(e, true);
                this.createSubmenu(true);
            }
        }));
        this._register(addDisposableListener(this.element, EventType.KEY_DOWN, e => {
            const event = new StandardKeyboardEvent(e);
            if (getActiveElement() === this.item) {
                if (event.equals(17 /* KeyCode.RightArrow */) || event.equals(3 /* KeyCode.Enter */)) {
                    EventHelper.stop(e, true);
                }
            }
        }));
        this._register(addDisposableListener(this.element, EventType.MOUSE_OVER, e => {
            if (!this.mouseOver) {
                this.mouseOver = true;
                this.showScheduler.schedule();
            }
        }));
        this._register(addDisposableListener(this.element, EventType.MOUSE_LEAVE, e => {
            this.mouseOver = false;
        }));
        this._register(addDisposableListener(this.element, EventType.FOCUS_OUT, e => {
            if (this.element && !isAncestor(getActiveElement(), this.element)) {
                this.hideScheduler.schedule();
            }
        }));
        this._register(this.parentData.parent.onScroll(() => {
            if (this.parentData.submenu === this.mysubmenu) {
                this.parentData.parent.focus(false);
                this.cleanupExistingSubmenu(true);
            }
        }));
    }
    updateEnabled() {
        // override on submenu entry
        // native menus do not observe enablement on sumbenus
        // we mimic that behavior
    }
    onClick(e) {
        // stop clicking from trying to run an action
        EventHelper.stop(e, true);
        this.cleanupExistingSubmenu(false);
        this.createSubmenu(true);
    }
    cleanupExistingSubmenu(force) {
        if (this.parentData.submenu && (force || (this.parentData.submenu !== this.mysubmenu))) {
            // disposal may throw if the submenu has already been removed
            try {
                this.parentData.submenu.dispose();
            }
            catch (_a) { }
            this.parentData.submenu = undefined;
            this.updateAriaExpanded('false');
            if (this.submenuContainer) {
                this.submenuDisposables.clear();
                this.submenuContainer = undefined;
            }
        }
    }
    calculateSubmenuMenuLayout(windowDimensions, submenu, entry, expandDirection) {
        const ret = { top: 0, left: 0 };
        // Start with horizontal
        ret.left = layout(windowDimensions.width, submenu.width, { position: expandDirection === Direction.Right ? 0 /* LayoutAnchorPosition.Before */ : 1 /* LayoutAnchorPosition.After */, offset: entry.left, size: entry.width });
        // We don't have enough room to layout the menu fully, so we are overlapping the menu
        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;
        }
        // Now that we have a horizontal position, try layout vertically
        ret.top = layout(windowDimensions.height, submenu.height, { position: 0 /* LayoutAnchorPosition.Before */, offset: entry.top, size: 0 });
        // We didn't have enough room below, but we did above, so we shift down to align the menu
        if (ret.top + submenu.height === entry.top && ret.top + entry.height + submenu.height <= windowDimensions.height) {
            ret.top += entry.height;
        }
        return ret;
    }
    createSubmenu(selectFirstItem = true) {
        if (!this.element) {
            return;
        }
        if (!this.parentData.submenu) {
            this.updateAriaExpanded('true');
            this.submenuContainer = append(this.element, dom_$('div.monaco-submenu'));
            this.submenuContainer.classList.add('menubar-menu-items-holder', 'context-view');
            // Set the top value of the menu container before construction
            // This allows the menu constructor to calculate the proper max height
            const computedStyles = getComputedStyle(this.parentData.parent.domNode);
            const paddingTop = parseFloat(computedStyles.paddingTop || '0') || 0;
            // this.submenuContainer.style.top = `${this.element.offsetTop - this.parentData.parent.scrollOffset - paddingTop}px`;
            this.submenuContainer.style.zIndex = '1';
            this.submenuContainer.style.position = 'fixed';
            this.submenuContainer.style.top = '0';
            this.submenuContainer.style.left = '0';
            this.parentData.submenu = new Menu(this.submenuContainer, this.submenuActions.length ? this.submenuActions : [new EmptySubmenuAction()], this.submenuOptions);
            if (this.menuStyle) {
                this.parentData.submenu.style(this.menuStyle);
            }
            // layout submenu
            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.submenuContainer.getBoundingClientRect();
            const { top, left } = this.calculateSubmenuMenuLayout(new Dimension(window.innerWidth, window.innerHeight), Dimension.lift(viewBox), entryBoxUpdated, this.expandDirection);
            // subtract offsets caused by transform parent
            this.submenuContainer.style.left = `${left - viewBox.left}px`;
            this.submenuContainer.style.top = `${top - viewBox.top}px`;
            this.submenuDisposables.add(addDisposableListener(this.submenuContainer, EventType.KEY_UP, e => {
                const event = new StandardKeyboardEvent(e);
                if (event.equals(15 /* KeyCode.LeftArrow */)) {
                    EventHelper.stop(e, true);
                    this.parentData.parent.focus();
                    this.cleanupExistingSubmenu(true);
                }
            }));
            this.submenuDisposables.add(addDisposableListener(this.submenuContainer, EventType.KEY_DOWN, e => {
                const event = new StandardKeyboardEvent(e);
                if (event.equals(15 /* KeyCode.LeftArrow */)) {
                    EventHelper.stop(e, true);
                }
            }));
            this.submenuDisposables.add(this.parentData.submenu.onDidCancel(() => {
                this.parentData.parent.focus();
                this.cleanupExistingSubmenu(true);
            }));
            this.parentData.submenu.focus(selectFirstItem);
            this.mysubmenu = this.parentData.submenu;
        }
        else {
            this.parentData.submenu.focus(false);
        }
    }
    updateAriaExpanded(value) {
        var _a;
        if (this.item) {
            (_a = this.item) === null || _a === void 0 ? void 0 : _a.setAttribute('aria-expanded', value);
        }
    }
    applyStyle() {
        var _a;
        super.applyStyle();
        if (!this.menuStyle) {
            return;
        }
        const isSelected = this.element && this.element.classList.contains('focused');
        const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
        if (this.submenuIndicator) {
            this.submenuIndicator.style.color = fgColor ? `${fgColor}` : '';
        }
        (_a = this.parentData.submenu) === null || _a === void 0 ? void 0 : _a.style(this.menuStyle);
    }
    dispose() {
        super.dispose();
        this.hideScheduler.dispose();
        if (this.mysubmenu) {
            this.mysubmenu.dispose();
            this.mysubmenu = null;
        }
        if (this.submenuContainer) {
            this.submenuContainer = undefined;
        }
    }
}
class MenuSeparatorActionViewItem extends ActionViewItem {
    style(style) {
        if (this.label) {
            this.label.style.borderBottomColor = style.separatorColor ? `${style.separatorColor}` : '';
        }
    }
}
function cleanMnemonic(label) {
    const regex = MENU_MNEMONIC_REGEX;
    const matches = regex.exec(label);
    if (!matches) {
        return label;
    }
    const mnemonicInText = !matches[1];
    return label.replace(regex, mnemonicInText ? '$2$3' : '').trim();
}
function getMenuWidgetCSS(style, isForShadowDom) {
    let result = /* css */ `
.monaco-menu {
	font-size: 13px;
	border-radius: 5px;
	min-width: 160px;
}

${formatRule(Codicon.menuSelection)}
${formatRule(Codicon.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.animated .action-item.active {
	transform: scale(1.272019649, 1.272019649); /* 1.272019649 = √φ */
}

.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;
}

.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: .6em 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;
}

.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) {
        // Only define scrollbar styles when used inside shadow dom,
        // otherwise leave their styling to the global workbench styling.
        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;
			}
		`;
        // Scrollbars
        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;
}

;// ../../node_modules/monaco-editor/esm/vs/platform/contextview/browser/contextMenuHandler.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







class ContextMenuHandler {
    constructor(contextViewService, telemetryService, notificationService, keybindingService, themeService) {
        this.contextViewService = contextViewService;
        this.telemetryService = telemetryService;
        this.notificationService = notificationService;
        this.keybindingService = keybindingService;
        this.themeService = themeService;
        this.focusToReturn = null;
        this.block = null;
        this.options = { blockMouse: true };
    }
    configure(options) {
        this.options = options;
    }
    showContextMenu(delegate) {
        const actions = delegate.getActions();
        if (!actions.length) {
            return; // Don't render an empty context menu
        }
        this.focusToReturn = document.activeElement;
        let menu;
        const shadowRootElement = isHTMLElement(delegate.domForShadowRoot) ? delegate.domForShadowRoot : undefined;
        this.contextViewService.showContextView({
            getAnchor: () => delegate.getAnchor(),
            canRelayout: false,
            anchorAlignment: delegate.anchorAlignment,
            anchorAxisAlignment: delegate.anchorAxisAlignment,
            render: (container) => {
                const className = delegate.getMenuClassName ? delegate.getMenuClassName() : '';
                if (className) {
                    container.className += ' ' + className;
                }
                // Render invisible div to block mouse interaction in the rest of the UI
                if (this.options.blockMouse) {
                    this.block = container.appendChild(dom_$('.context-view-block'));
                    this.block.style.position = 'fixed';
                    this.block.style.cursor = 'initial';
                    this.block.style.left = '0';
                    this.block.style.top = '0';
                    this.block.style.width = '100%';
                    this.block.style.height = '100%';
                    this.block.style.zIndex = '-1';
                    // TODO@Steven: this is never getting disposed
                    addDisposableListener(this.block, EventType.MOUSE_DOWN, e => e.stopPropagation());
                }
                const menuDisposables = new DisposableStore();
                const actionRunner = delegate.actionRunner || new ActionRunner();
                actionRunner.onBeforeRun(this.onActionRun, this, menuDisposables);
                actionRunner.onDidRun(this.onDidActionRun, this, menuDisposables);
                menu = new Menu(container, actions, {
                    actionViewItemProvider: delegate.getActionViewItem,
                    context: delegate.getActionsContext ? delegate.getActionsContext() : null,
                    actionRunner,
                    getKeyBinding: delegate.getKeyBinding ? delegate.getKeyBinding : action => this.keybindingService.lookupKeybinding(action.id)
                });
                menuDisposables.add(attachMenuStyler(menu, this.themeService));
                menu.onDidCancel(() => this.contextViewService.hideContextView(true), null, menuDisposables);
                menu.onDidBlur(() => this.contextViewService.hideContextView(true), null, menuDisposables);
                menuDisposables.add(addDisposableListener(window, EventType.BLUR, () => this.contextViewService.hideContextView(true)));
                menuDisposables.add(addDisposableListener(window, EventType.MOUSE_DOWN, (e) => {
                    if (e.defaultPrevented) {
                        return;
                    }
                    const event = new StandardMouseEvent(e);
                    let element = event.target;
                    // Don't do anything as we are likely creating a context menu
                    if (event.rightButton) {
                        return;
                    }
                    while (element) {
                        if (element === container) {
                            return;
                        }
                        element = element.parentElement;
                    }
                    this.contextViewService.hideContextView(true);
                }));
                return combinedDisposable(menuDisposables, menu);
            },
            focus: () => {
                menu === null || menu === void 0 ? void 0 : menu.focus(!!delegate.autoSelectFirstItem);
            },
            onHide: (didCancel) => {
                var _a;
                (_a = delegate.onHide) === null || _a === void 0 ? void 0 : _a.call(delegate, !!didCancel);
                if (this.block) {
                    this.block.remove();
                    this.block = null;
                }
                if (this.focusToReturn) {
                    this.focusToReturn.focus();
                }
            }
        }, shadowRootElement, !!shadowRootElement);
    }
    onActionRun(e) {
        this.telemetryService.publicLog2('workbenchActionExecuted', { id: e.action.id, from: 'contextMenu' });
        this.contextViewService.hideContextView(false);
        // Restore focus here
        if (this.focusToReturn) {
            this.focusToReturn.focus();
        }
    }
    onDidActionRun(e) {
        if (e.error && !isCancellationError(e.error)) {
            this.notificationService.error(e.error);
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/contextview/browser/contextMenuService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var contextMenuService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var contextMenuService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};









let ContextMenuService = class ContextMenuService extends Disposable {
    constructor(telemetryService, notificationService, contextViewService, keybindingService, themeService) {
        super();
        this._onDidShowContextMenu = new Emitter();
        this._onDidHideContextMenu = new Emitter();
        this.contextMenuHandler = new ContextMenuHandler(contextViewService, telemetryService, notificationService, keybindingService, themeService);
    }
    configure(options) {
        this.contextMenuHandler.configure(options);
    }
    // ContextMenu
    showContextMenu(delegate) {
        this.contextMenuHandler.showContextMenu(Object.assign(Object.assign({}, delegate), { onHide: (didCancel) => {
                var _a;
                (_a = delegate.onHide) === null || _a === void 0 ? void 0 : _a.call(delegate, didCancel);
                this._onDidHideContextMenu.fire();
            } }));
        ModifierKeyEmitter.getInstance().resetKeyStatus();
        this._onDidShowContextMenu.fire();
    }
};
ContextMenuService = contextMenuService_decorate([
    contextMenuService_param(0, ITelemetryService),
    contextMenuService_param(1, INotificationService),
    contextMenuService_param(2, IContextViewService),
    contextMenuService_param(3, IKeybindingService),
    contextMenuService_param(4, IThemeService)
], ContextMenuService);


;// ../../node_modules/monaco-editor/esm/vs/platform/editor/common/editor.js
var EditorOpenSource;
(function (EditorOpenSource) {
    /**
     * Default: the editor is opening via a programmatic call
     * to the editor service API.
     */
    EditorOpenSource[EditorOpenSource["API"] = 0] = "API";
    /**
     * Indicates that a user action triggered the opening, e.g.
     * via mouse or keyboard use.
     */
    EditorOpenSource[EditorOpenSource["USER"] = 1] = "USER";
})(EditorOpenSource || (EditorOpenSource = {}));

;// ../../node_modules/monaco-editor/esm/vs/editor/browser/services/openerService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var openerService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var openerService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var openerService_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};












let CommandOpener = class CommandOpener {
    constructor(_commandService) {
        this._commandService = _commandService;
    }
    open(target, options) {
        return openerService_awaiter(this, void 0, void 0, function* () {
            if (!matchesScheme(target, Schemas.command)) {
                return false;
            }
            if (!(options === null || options === void 0 ? void 0 : options.allowCommands)) {
                // silently ignore commands when command-links are disabled, also
                // surpress other openers by returning TRUE
                return true;
            }
            // run command or bail out if command isn't known
            if (typeof target === 'string') {
                target = URI.parse(target);
            }
            // execute as command
            let args = [];
            try {
                args = parse(decodeURIComponent(target.query));
            }
            catch (_a) {
                // ignore and retry
                try {
                    args = parse(target.query);
                }
                catch (_b) {
                    // ignore error
                }
            }
            if (!Array.isArray(args)) {
                args = [args];
            }
            yield this._commandService.executeCommand(target.path, ...args);
            return true;
        });
    }
};
CommandOpener = openerService_decorate([
    openerService_param(0, ICommandService)
], CommandOpener);
let EditorOpener = class EditorOpener {
    constructor(_editorService) {
        this._editorService = _editorService;
    }
    open(target, options) {
        return openerService_awaiter(this, void 0, void 0, function* () {
            if (typeof target === 'string') {
                target = URI.parse(target);
            }
            const { selection, uri } = extractSelection(target);
            target = uri;
            if (target.scheme === Schemas.file) {
                target = normalizePath(target); // workaround for non-normalized paths (https://github.com/microsoft/vscode/issues/12954)
            }
            yield this._editorService.openCodeEditor({
                resource: target,
                options: Object.assign({ selection, source: (options === null || options === void 0 ? void 0 : options.fromUserGesture) ? EditorOpenSource.USER : EditorOpenSource.API }, options === null || options === void 0 ? void 0 : options.editorOptions)
            }, this._editorService.getFocusedCodeEditor(), options === null || options === void 0 ? void 0 : options.openToSide);
            return true;
        });
    }
};
EditorOpener = openerService_decorate([
    openerService_param(0, ICodeEditorService)
], EditorOpener);
let OpenerService = class OpenerService {
    constructor(editorService, commandService) {
        this._openers = new LinkedList();
        this._validators = new LinkedList();
        this._resolvers = new LinkedList();
        this._resolvedUriTargets = new ResourceMap(uri => uri.with({ path: null, fragment: null, query: null }).toString());
        this._externalOpeners = new LinkedList();
        // Default external opener is going through window.open()
        this._defaultExternalOpener = {
            openExternal: (href) => openerService_awaiter(this, void 0, void 0, function* () {
                // ensure to open HTTP/HTTPS links into new windows
                // to not trigger a navigation. Any other link is
                // safe to be set as HREF to prevent a blank window
                // from opening.
                if (matchesSomeScheme(href, Schemas.http, Schemas.https)) {
                    windowOpenNoOpener(href);
                }
                else {
                    window.location.href = href;
                }
                return true;
            })
        };
        // Default opener: any external, maito, http(s), command, and catch-all-editors
        this._openers.push({
            open: (target, options) => openerService_awaiter(this, void 0, void 0, function* () {
                if ((options === null || options === void 0 ? void 0 : options.openExternal) || matchesSomeScheme(target, Schemas.mailto, Schemas.http, Schemas.https, Schemas.vsls)) {
                    // open externally
                    yield this._doOpenExternal(target, options);
                    return true;
                }
                return false;
            })
        });
        this._openers.push(new CommandOpener(commandService));
        this._openers.push(new EditorOpener(editorService));
    }
    registerOpener(opener) {
        const remove = this._openers.unshift(opener);
        return { dispose: remove };
    }
    registerValidator(validator) {
        const remove = this._validators.push(validator);
        return { dispose: remove };
    }
    registerExternalUriResolver(resolver) {
        const remove = this._resolvers.push(resolver);
        return { dispose: remove };
    }
    setDefaultExternalOpener(externalOpener) {
        this._defaultExternalOpener = externalOpener;
    }
    registerExternalOpener(opener) {
        const remove = this._externalOpeners.push(opener);
        return { dispose: remove };
    }
    open(target, options) {
        var _a;
        return openerService_awaiter(this, void 0, void 0, function* () {
            // check with contributed validators
            const targetURI = typeof target === 'string' ? URI.parse(target) : target;
            // validate against the original URI that this URI resolves to, if one exists
            const validationTarget = (_a = this._resolvedUriTargets.get(targetURI)) !== null && _a !== void 0 ? _a : target;
            for (const validator of this._validators) {
                if (!(yield validator.shouldOpen(validationTarget, options))) {
                    return false;
                }
            }
            // check with contributed openers
            for (const opener of this._openers) {
                const handled = yield opener.open(target, options);
                if (handled) {
                    return true;
                }
            }
            return false;
        });
    }
    resolveExternalUri(resource, options) {
        return openerService_awaiter(this, void 0, void 0, function* () {
            for (const resolver of this._resolvers) {
                try {
                    const result = yield resolver.resolveExternalUri(resource, options);
                    if (result) {
                        if (!this._resolvedUriTargets.has(result.resolved)) {
                            this._resolvedUriTargets.set(result.resolved, resource);
                        }
                        return result;
                    }
                }
                catch (_a) {
                    // noop
                }
            }
            throw new Error('Could not resolve external URI: ' + resource.toString());
        });
    }
    _doOpenExternal(resource, options) {
        return openerService_awaiter(this, void 0, void 0, function* () {
            //todo@jrieken IExternalUriResolver should support `uri: URI | string`
            const uri = typeof resource === 'string' ? URI.parse(resource) : resource;
            let externalUri;
            try {
                externalUri = (yield this.resolveExternalUri(uri, options)).resolved;
            }
            catch (_a) {
                externalUri = uri;
            }
            let href;
            if (typeof resource === 'string' && uri.toString() === externalUri.toString()) {
                // open the url-string AS IS
                href = resource;
            }
            else {
                // open URI using the toString(noEncode)+encodeURI-trick
                href = encodeURI(externalUri.toString(true));
            }
            if (options === null || options === void 0 ? void 0 : options.allowContributedOpeners) {
                const preferredOpenerId = typeof (options === null || options === void 0 ? void 0 : options.allowContributedOpeners) === 'string' ? options === null || options === void 0 ? void 0 : options.allowContributedOpeners : undefined;
                for (const opener of this._externalOpeners) {
                    const didOpen = yield opener.openExternal(href, {
                        sourceUri: uri,
                        preferredOpenerId,
                    }, CancellationToken.None);
                    if (didOpen) {
                        return true;
                    }
                }
            }
            return this._defaultExternalOpener.openExternal(href, { sourceUri: uri }, CancellationToken.None);
        });
    }
    dispose() {
        this._validators.clear();
    }
};
OpenerService = openerService_decorate([
    openerService_param(0, ICodeEditorService),
    openerService_param(1, ICommandService)
], OpenerService);


;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/markerDecorationsService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var markerDecorationsService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var markerDecorationsService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};











class MarkerDecorations extends Disposable {
    constructor(model) {
        super();
        this.model = model;
        this._markersData = new Map();
        this._register(toDisposable(() => {
            this.model.deltaDecorations([...this._markersData.keys()], []);
            this._markersData.clear();
        }));
    }
    update(markers, newDecorations) {
        const oldIds = [...this._markersData.keys()];
        this._markersData.clear();
        const ids = this.model.deltaDecorations(oldIds, newDecorations);
        for (let index = 0; index < ids.length; index++) {
            this._markersData.set(ids[index], markers[index]);
        }
        return oldIds.length !== 0 || ids.length !== 0;
    }
    getMarker(decoration) {
        return this._markersData.get(decoration.id);
    }
}
let MarkerDecorationsService = class MarkerDecorationsService extends Disposable {
    constructor(modelService, _markerService) {
        super();
        this._markerService = _markerService;
        this._onDidChangeMarker = this._register(new Emitter());
        this._markerDecorations = new ResourceMap();
        modelService.getModels().forEach(model => this._onModelAdded(model));
        this._register(modelService.onModelAdded(this._onModelAdded, this));
        this._register(modelService.onModelRemoved(this._onModelRemoved, this));
        this._register(this._markerService.onMarkerChanged(this._handleMarkerChange, this));
    }
    dispose() {
        super.dispose();
        this._markerDecorations.forEach(value => value.dispose());
        this._markerDecorations.clear();
    }
    getMarker(uri, decoration) {
        const markerDecorations = this._markerDecorations.get(uri);
        return markerDecorations ? (markerDecorations.getMarker(decoration) || null) : null;
    }
    _handleMarkerChange(changedResources) {
        changedResources.forEach((resource) => {
            const markerDecorations = this._markerDecorations.get(resource);
            if (markerDecorations) {
                this._updateDecorations(markerDecorations);
            }
        });
    }
    _onModelAdded(model) {
        const markerDecorations = new MarkerDecorations(model);
        this._markerDecorations.set(model.uri, markerDecorations);
        this._updateDecorations(markerDecorations);
    }
    _onModelRemoved(model) {
        var _a;
        const markerDecorations = this._markerDecorations.get(model.uri);
        if (markerDecorations) {
            markerDecorations.dispose();
            this._markerDecorations.delete(model.uri);
        }
        // clean up markers for internal, transient models
        if (model.uri.scheme === Schemas.inMemory
            || model.uri.scheme === Schemas.internal
            || model.uri.scheme === Schemas.vscode) {
            (_a = this._markerService) === null || _a === void 0 ? void 0 : _a.read({ resource: model.uri }).map(marker => marker.owner).forEach(owner => this._markerService.remove(owner, [model.uri]));
        }
    }
    _updateDecorations(markerDecorations) {
        // Limit to the first 500 errors/warnings
        const markers = this._markerService.read({ resource: markerDecorations.model.uri, take: 500 });
        const newModelDecorations = markers.map((marker) => {
            return {
                range: this._createDecorationRange(markerDecorations.model, marker),
                options: this._createDecorationOption(marker)
            };
        });
        if (markerDecorations.update(markers, newModelDecorations)) {
            this._onDidChangeMarker.fire(markerDecorations.model);
        }
    }
    _createDecorationRange(model, rawMarker) {
        let ret = Range.lift(rawMarker);
        if (rawMarker.severity === MarkerSeverity.Hint && !this._hasMarkerTag(rawMarker, 1 /* MarkerTag.Unnecessary */) && !this._hasMarkerTag(rawMarker, 2 /* MarkerTag.Deprecated */)) {
            // * never render hints on multiple lines
            // * make enough space for three dots
            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) {
                // empty line or behind eol
                // keep the range as is, it will be rendered 1ch wide
                return ret;
            }
            const word = model.getWordAtPosition(ret.getStartPosition());
            if (word) {
                ret = new Range(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 Range(ret.startLineNumber, minColumn, ret.endLineNumber, ret.endColumn);
                rawMarker.startColumn = minColumn;
            }
        }
        return ret;
    }
    _createDecorationOption(marker) {
        let className;
        let color = undefined;
        let zIndex;
        let inlineClassName = undefined;
        let minimap;
        switch (marker.severity) {
            case MarkerSeverity.Hint:
                if (this._hasMarkerTag(marker, 2 /* MarkerTag.Deprecated */)) {
                    className = undefined;
                }
                else if (this._hasMarkerTag(marker, 1 /* MarkerTag.Unnecessary */)) {
                    className = "squiggly-unnecessary" /* ClassName.EditorUnnecessaryDecoration */;
                }
                else {
                    className = "squiggly-hint" /* ClassName.EditorHintDecoration */;
                }
                zIndex = 0;
                break;
            case MarkerSeverity.Warning:
                className = "squiggly-warning" /* ClassName.EditorWarningDecoration */;
                color = themeColorFromId(overviewRulerWarning);
                zIndex = 20;
                minimap = {
                    color: themeColorFromId(minimapWarning),
                    position: MinimapPosition.Inline
                };
                break;
            case MarkerSeverity.Info:
                className = "squiggly-info" /* ClassName.EditorInfoDecoration */;
                color = themeColorFromId(overviewRulerInfo);
                zIndex = 10;
                break;
            case MarkerSeverity.Error:
            default:
                className = "squiggly-error" /* ClassName.EditorErrorDecoration */;
                color = themeColorFromId(overviewRulerError);
                zIndex = 30;
                minimap = {
                    color: themeColorFromId(minimapError),
                    position: MinimapPosition.Inline
                };
                break;
        }
        if (marker.tags) {
            if (marker.tags.indexOf(1 /* MarkerTag.Unnecessary */) !== -1) {
                inlineClassName = "squiggly-inline-unnecessary" /* ClassName.EditorUnnecessaryInlineDecoration */;
            }
            if (marker.tags.indexOf(2 /* MarkerTag.Deprecated */) !== -1) {
                inlineClassName = "squiggly-inline-deprecated" /* ClassName.EditorDeprecatedInlineDecoration */;
            }
        }
        return {
            description: 'marker-decoration',
            stickiness: 1 /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */,
            className,
            showIfCollapsed: true,
            overviewRuler: {
                color,
                position: OverviewRulerLane.Right
            },
            minimap,
            zIndex,
            inlineClassName,
        };
    }
    _hasMarkerTag(marker, tag) {
        if (marker.tags) {
            return marker.tags.indexOf(tag) >= 0;
        }
        return false;
    }
};
MarkerDecorationsService = markerDecorationsService_decorate([
    markerDecorationsService_param(0, IModelService),
    markerDecorationsService_param(1, IMarkerService)
], MarkerDecorationsService);


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickInput/standaloneQuickInput.css
var standaloneQuickInput = __webpack_require__(6951);
;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickInput/standaloneQuickInput.css

      
      
      
      
      
      
      
      
      

var standaloneQuickInput_options = {};

standaloneQuickInput_options.styleTagTransform = (styleTagTransform_default());
standaloneQuickInput_options.setAttributes = (setAttributesWithoutAttributes_default());

      standaloneQuickInput_options.insert = insertBySelector_default().bind(null, "head");
    
standaloneQuickInput_options.domAPI = (styleDomAPI_default());
standaloneQuickInput_options.insertStyleElement = (insertStyleElement_default());

var standaloneQuickInput_update = injectStylesIntoStyleTag_default()(standaloneQuickInput/* default */.A, standaloneQuickInput_options);




       /* harmony default export */ const quickInput_standaloneQuickInput = (standaloneQuickInput/* default */.A && standaloneQuickInput/* default */.A.locals ? standaloneQuickInput/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/button/button.css
var button_button = __webpack_require__(39357);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/button/button.css

      
      
      
      
      
      
      
      
      

var button_options = {};

button_options.styleTagTransform = (styleTagTransform_default());
button_options.setAttributes = (setAttributesWithoutAttributes_default());

      button_options.insert = insertBySelector_default().bind(null, "head");
    
button_options.domAPI = (styleDomAPI_default());
button_options.insertStyleElement = (insertStyleElement_default());

var button_update = injectStylesIntoStyleTag_default()(button_button/* default */.A, button_options);




       /* harmony default export */ const ui_button_button = (button_button/* default */.A && button_button/* default */.A.locals ? button_button/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/button/button.js









const button_defaultOptions = {
    buttonBackground: Color.fromHex('#0E639C'),
    buttonHoverBackground: Color.fromHex('#006BB3'),
    buttonSeparator: Color.white,
    buttonForeground: Color.white
};
class Button extends Disposable {
    constructor(container, options) {
        super();
        this._onDidClick = this._register(new Emitter());
        this.options = options || Object.create(null);
        mixin(this.options, button_defaultOptions, false);
        this.buttonForeground = this.options.buttonForeground;
        this.buttonBackground = this.options.buttonBackground;
        this.buttonHoverBackground = this.options.buttonHoverBackground;
        this.buttonSecondaryForeground = this.options.buttonSecondaryForeground;
        this.buttonSecondaryBackground = this.options.buttonSecondaryBackground;
        this.buttonSecondaryHoverBackground = this.options.buttonSecondaryHoverBackground;
        this.buttonBorder = this.options.buttonBorder;
        this._element = document.createElement('a');
        this._element.classList.add('monaco-button');
        this._element.tabIndex = 0;
        this._element.setAttribute('role', 'button');
        container.appendChild(this._element);
        this._register(Gesture.addTarget(this._element));
        [EventType.CLICK, touch_EventType.Tap].forEach(eventType => {
            this._register(addDisposableListener(this._element, eventType, e => {
                if (!this.enabled) {
                    EventHelper.stop(e);
                    return;
                }
                this._onDidClick.fire(e);
            }));
        });
        this._register(addDisposableListener(this._element, EventType.KEY_DOWN, e => {
            const event = new StandardKeyboardEvent(e);
            let eventHandled = false;
            if (this.enabled && (event.equals(3 /* KeyCode.Enter */) || event.equals(10 /* KeyCode.Space */))) {
                this._onDidClick.fire(e);
                eventHandled = true;
            }
            else if (event.equals(9 /* KeyCode.Escape */)) {
                this._element.blur();
                eventHandled = true;
            }
            if (eventHandled) {
                EventHelper.stop(event, true);
            }
        }));
        this._register(addDisposableListener(this._element, EventType.MOUSE_OVER, e => {
            if (!this._element.classList.contains('disabled')) {
                this.setHoverBackground();
            }
        }));
        this._register(addDisposableListener(this._element, EventType.MOUSE_OUT, e => {
            this.applyStyles(); // restore standard styles
        }));
        // Also set hover background when button is focused for feedback
        this.focusTracker = this._register(trackFocus(this._element));
        this._register(this.focusTracker.onDidFocus(() => { if (this.enabled) {
            this.setHoverBackground();
        } }));
        this._register(this.focusTracker.onDidBlur(() => { if (this.enabled) {
            this.applyStyles();
        } }));
        this.applyStyles();
    }
    get onDidClick() { return this._onDidClick.event; }
    setHoverBackground() {
        let hoverBackground;
        if (this.options.secondary) {
            hoverBackground = this.buttonSecondaryHoverBackground ? this.buttonSecondaryHoverBackground.toString() : null;
        }
        else {
            hoverBackground = this.buttonHoverBackground ? this.buttonHoverBackground.toString() : null;
        }
        if (hoverBackground) {
            this._element.style.backgroundColor = hoverBackground;
        }
    }
    style(styles) {
        this.buttonForeground = styles.buttonForeground;
        this.buttonBackground = styles.buttonBackground;
        this.buttonHoverBackground = styles.buttonHoverBackground;
        this.buttonSecondaryForeground = styles.buttonSecondaryForeground;
        this.buttonSecondaryBackground = styles.buttonSecondaryBackground;
        this.buttonSecondaryHoverBackground = styles.buttonSecondaryHoverBackground;
        this.buttonBorder = styles.buttonBorder;
        this.applyStyles();
    }
    applyStyles() {
        if (this._element) {
            let background, foreground;
            if (this.options.secondary) {
                foreground = this.buttonSecondaryForeground ? this.buttonSecondaryForeground.toString() : '';
                background = this.buttonSecondaryBackground ? this.buttonSecondaryBackground.toString() : '';
            }
            else {
                foreground = this.buttonForeground ? this.buttonForeground.toString() : '';
                background = this.buttonBackground ? this.buttonBackground.toString() : '';
            }
            const border = this.buttonBorder ? this.buttonBorder.toString() : '';
            this._element.style.color = foreground;
            this._element.style.backgroundColor = background;
            this._element.style.borderWidth = border ? '1px' : '';
            this._element.style.borderStyle = border ? 'solid' : '';
            this._element.style.borderColor = border;
        }
    }
    get element() {
        return this._element;
    }
    set label(value) {
        this._element.classList.add('monaco-text-button');
        if (this.options.supportIcons) {
            dom_reset(this._element, ...renderLabelWithIcons(value));
        }
        else {
            this._element.textContent = value;
        }
        if (typeof this.options.title === 'string') {
            this._element.title = this.options.title;
        }
        else if (this.options.title) {
            this._element.title = value;
        }
    }
    set enabled(value) {
        if (value) {
            this._element.classList.remove('disabled');
            this._element.setAttribute('aria-disabled', String(false));
            this._element.tabIndex = 0;
        }
        else {
            this._element.classList.add('disabled');
            this._element.setAttribute('aria-disabled', String(true));
        }
    }
    get enabled() {
        return !this._element.classList.contains('disabled');
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/progressbar/progressbar.css
var progressbar = __webpack_require__(99731);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/progressbar/progressbar.css

      
      
      
      
      
      
      
      
      

var progressbar_options = {};

progressbar_options.styleTagTransform = (styleTagTransform_default());
progressbar_options.setAttributes = (setAttributesWithoutAttributes_default());

      progressbar_options.insert = insertBySelector_default().bind(null, "head");
    
progressbar_options.domAPI = (styleDomAPI_default());
progressbar_options.insertStyleElement = (insertStyleElement_default());

var progressbar_update = injectStylesIntoStyleTag_default()(progressbar/* default */.A, progressbar_options);




       /* harmony default export */ const progressbar_progressbar = (progressbar/* default */.A && progressbar/* default */.A.locals ? progressbar/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/progressbar/progressbar.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






const CSS_DONE = 'done';
const CSS_ACTIVE = 'active';
const CSS_INFINITE = 'infinite';
const CSS_INFINITE_LONG_RUNNING = 'infinite-long-running';
const CSS_DISCRETE = 'discrete';
const progressbar_defaultOpts = {
    progressBarBackground: Color.fromHex('#0E70C0')
};
/**
 * A progress bar with support for infinite or discrete progress.
 */
class ProgressBar extends Disposable {
    constructor(container, options) {
        super();
        this.options = options || Object.create(null);
        mixin(this.options, progressbar_defaultOpts, false);
        this.workedVal = 0;
        this.progressBarBackground = this.options.progressBarBackground;
        this.showDelayedScheduler = this._register(new RunOnceScheduler(() => show(this.element), 0));
        this.longRunningScheduler = this._register(new RunOnceScheduler(() => this.infiniteLongRunning(), ProgressBar.LONG_RUNNING_INFINITE_THRESHOLD));
        this.create(container);
    }
    create(container) {
        this.element = document.createElement('div');
        this.element.classList.add('monaco-progress-container');
        this.element.setAttribute('role', 'progressbar');
        this.element.setAttribute('aria-valuemin', '0');
        container.appendChild(this.element);
        this.bit = document.createElement('div');
        this.bit.classList.add('progress-bit');
        this.element.appendChild(this.bit);
        this.applyStyles();
    }
    off() {
        this.bit.style.width = 'inherit';
        this.bit.style.opacity = '1';
        this.element.classList.remove(CSS_ACTIVE, CSS_INFINITE, CSS_INFINITE_LONG_RUNNING, CSS_DISCRETE);
        this.workedVal = 0;
        this.totalWork = undefined;
        this.longRunningScheduler.cancel();
    }
    /**
     * Stops the progressbar from showing any progress instantly without fading out.
     */
    stop() {
        return this.doDone(false);
    }
    doDone(delayed) {
        this.element.classList.add(CSS_DONE);
        // discrete: let it grow to 100% width and hide afterwards
        if (!this.element.classList.contains(CSS_INFINITE)) {
            this.bit.style.width = 'inherit';
            if (delayed) {
                setTimeout(() => this.off(), 200);
            }
            else {
                this.off();
            }
        }
        // infinite: let it fade out and hide afterwards
        else {
            this.bit.style.opacity = '0';
            if (delayed) {
                setTimeout(() => this.off(), 200);
            }
            else {
                this.off();
            }
        }
        return this;
    }
    /**
     * Use this mode to indicate progress that has no total number of work units.
     */
    infinite() {
        this.bit.style.width = '2%';
        this.bit.style.opacity = '1';
        this.element.classList.remove(CSS_DISCRETE, CSS_DONE, CSS_INFINITE_LONG_RUNNING);
        this.element.classList.add(CSS_ACTIVE, CSS_INFINITE);
        this.longRunningScheduler.schedule();
        return this;
    }
    infiniteLongRunning() {
        this.element.classList.add(CSS_INFINITE_LONG_RUNNING);
    }
    getContainer() {
        return this.element;
    }
    style(styles) {
        this.progressBarBackground = styles.progressBarBackground;
        this.applyStyles();
    }
    applyStyles() {
        if (this.bit) {
            const background = this.progressBarBackground ? this.progressBarBackground.toString() : '';
            this.bit.style.backgroundColor = background;
        }
    }
}
/**
 * After a certain time of showing the progress bar, switch
 * to long-running mode and throttle animations to reduce
 * the pressure on the GPU process.
 *
 * https://github.com/microsoft/vscode/issues/97900
 * https://github.com/microsoft/vscode/issues/138396
 */
ProgressBar.LONG_RUNNING_INFINITE_THRESHOLD = 10000;

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/parts/quickinput/browser/media/quickInput.css
var quickInput = __webpack_require__(95670);
;// ../../node_modules/monaco-editor/esm/vs/base/parts/quickinput/browser/media/quickInput.css

      
      
      
      
      
      
      
      
      

var quickInput_options = {};

quickInput_options.styleTagTransform = (styleTagTransform_default());
quickInput_options.setAttributes = (setAttributesWithoutAttributes_default());

      quickInput_options.insert = insertBySelector_default().bind(null, "head");
    
quickInput_options.domAPI = (styleDomAPI_default());
quickInput_options.insertStyleElement = (insertStyleElement_default());

var quickInput_update = injectStylesIntoStyleTag_default()(quickInput/* default */.A, quickInput_options);




       /* harmony default export */ const media_quickInput = (quickInput/* default */.A && quickInput/* default */.A.locals ? quickInput/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/parts/quickinput/browser/quickInputUtils.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



const iconPathToClass = {};
const iconClassGenerator = new IdGenerator('quick-input-button-icon-');
function getIconClass(iconPath) {
    if (!iconPath) {
        return undefined;
    }
    let iconClass;
    const key = iconPath.dark.toString();
    if (iconPathToClass[key]) {
        iconClass = iconPathToClass[key];
    }
    else {
        iconClass = iconClassGenerator.nextId();
        createCSSRule(`.${iconClass}, .hc-light .${iconClass}`, `background-image: ${asCSSUrl(iconPath.light || iconPath.dark)}`);
        createCSSRule(`.vs-dark .${iconClass}, .hc-black .${iconClass}`, `background-image: ${asCSSUrl(iconPath.dark)}`);
        iconPathToClass[key] = iconClass;
    }
    return iconClass;
}

;// ../../node_modules/monaco-editor/esm/vs/base/parts/quickinput/browser/quickInputBox.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







const quickInputBox_$ = dom_$;
class QuickInputBox extends Disposable {
    constructor(parent) {
        super();
        this.parent = parent;
        this.onKeyDown = (handler) => {
            return addDisposableListener(this.inputBox.inputElement, EventType.KEY_DOWN, (e) => {
                handler(new StandardKeyboardEvent(e));
            });
        };
        this.onMouseDown = (handler) => {
            return addDisposableListener(this.inputBox.inputElement, EventType.MOUSE_DOWN, (e) => {
                handler(new StandardMouseEvent(e));
            });
        };
        this.onDidChange = (handler) => {
            return this.inputBox.onDidChange(handler);
        };
        this.container = append(this.parent, quickInputBox_$('.quick-input-box'));
        this.inputBox = this._register(new InputBox(this.container, undefined));
    }
    get value() {
        return this.inputBox.value;
    }
    set value(value) {
        this.inputBox.value = value;
    }
    select(range = null) {
        this.inputBox.select(range);
    }
    isSelectionAtEnd() {
        return this.inputBox.isSelectionAtEnd();
    }
    get placeholder() {
        return this.inputBox.inputElement.getAttribute('placeholder') || '';
    }
    set placeholder(placeholder) {
        this.inputBox.setPlaceHolder(placeholder);
    }
    get ariaLabel() {
        return this.inputBox.getAriaLabel();
    }
    set ariaLabel(ariaLabel) {
        this.inputBox.setAriaLabel(ariaLabel);
    }
    get password() {
        return this.inputBox.inputElement.type === 'password';
    }
    set password(password) {
        this.inputBox.inputElement.type = password ? 'password' : 'text';
    }
    setAttribute(name, value) {
        this.inputBox.inputElement.setAttribute(name, value);
    }
    removeAttribute(name) {
        this.inputBox.inputElement.removeAttribute(name);
    }
    showDecoration(decoration) {
        if (decoration === common_severity.Ignore) {
            this.inputBox.hideMessage();
        }
        else {
            this.inputBox.showMessage({ type: decoration === common_severity.Info ? 1 /* MessageType.INFO */ : decoration === common_severity.Warning ? 2 /* MessageType.WARNING */ : 3 /* MessageType.ERROR */, content: '' });
        }
    }
    stylesForType(decoration) {
        return this.inputBox.stylesForType(decoration === common_severity.Info ? 1 /* MessageType.INFO */ : decoration === common_severity.Warning ? 2 /* MessageType.WARNING */ : 3 /* MessageType.ERROR */);
    }
    setFocus() {
        this.inputBox.focus();
    }
    layout() {
        this.inputBox.layout();
    }
    style(styles) {
        this.inputBox.style(styles);
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!../../node_modules/monaco-editor/esm/vs/base/browser/ui/keybindingLabel/keybindingLabel.css
var keybindingLabel = __webpack_require__(53767);
;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/keybindingLabel/keybindingLabel.css

      
      
      
      
      
      
      
      
      

var keybindingLabel_options = {};

keybindingLabel_options.styleTagTransform = (styleTagTransform_default());
keybindingLabel_options.setAttributes = (setAttributesWithoutAttributes_default());

      keybindingLabel_options.insert = insertBySelector_default().bind(null, "head");
    
keybindingLabel_options.domAPI = (styleDomAPI_default());
keybindingLabel_options.insertStyleElement = (insertStyleElement_default());

var keybindingLabel_update = injectStylesIntoStyleTag_default()(keybindingLabel/* default */.A, keybindingLabel_options);




       /* harmony default export */ const keybindingLabel_keybindingLabel = (keybindingLabel/* default */.A && keybindingLabel/* default */.A.locals ? keybindingLabel/* default */.A.locals : undefined);

;// ../../node_modules/monaco-editor/esm/vs/base/browser/ui/keybindingLabel/keybindingLabel.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/





const keybindingLabel_$ = dom_$;
class KeybindingLabel {
    constructor(container, os, options) {
        this.os = os;
        this.keyElements = new Set();
        this.options = options || Object.create(null);
        this.labelBackground = this.options.keybindingLabelBackground;
        this.labelForeground = this.options.keybindingLabelForeground;
        this.labelBorder = this.options.keybindingLabelBorder;
        this.labelBottomBorder = this.options.keybindingLabelBottomBorder;
        this.labelShadow = this.options.keybindingLabelShadow;
        this.domNode = append(container, keybindingLabel_$('.monaco-keybinding'));
        this.didEverRender = false;
        container.appendChild(this.domNode);
    }
    get element() {
        return this.domNode;
    }
    set(keybinding, matches) {
        if (this.didEverRender && this.keybinding === keybinding && KeybindingLabel.areSame(this.matches, matches)) {
            return;
        }
        this.keybinding = keybinding;
        this.matches = matches;
        this.render();
    }
    render() {
        this.clear();
        if (this.keybinding) {
            const [firstPart, chordPart] = this.keybinding.getParts();
            if (firstPart) {
                this.renderPart(this.domNode, firstPart, this.matches ? this.matches.firstPart : null);
            }
            if (chordPart) {
                append(this.domNode, keybindingLabel_$('span.monaco-keybinding-key-chord-separator', undefined, ' '));
                this.renderPart(this.domNode, chordPart, this.matches ? this.matches.chordPart : null);
            }
            this.domNode.title = this.keybinding.getAriaLabel() || '';
        }
        else if (this.options && this.options.renderUnboundKeybindings) {
            this.renderUnbound(this.domNode);
        }
        this.applyStyles();
        this.didEverRender = true;
    }
    clear() {
        clearNode(this.domNode);
        this.keyElements.clear();
    }
    renderPart(parent, part, match) {
        const modifierLabels = UILabelProvider.modifierLabels[this.os];
        if (part.ctrlKey) {
            this.renderKey(parent, modifierLabels.ctrlKey, Boolean(match === null || match === void 0 ? void 0 : match.ctrlKey), modifierLabels.separator);
        }
        if (part.shiftKey) {
            this.renderKey(parent, modifierLabels.shiftKey, Boolean(match === null || match === void 0 ? void 0 : match.shiftKey), modifierLabels.separator);
        }
        if (part.altKey) {
            this.renderKey(parent, modifierLabels.altKey, Boolean(match === null || match === void 0 ? void 0 : match.altKey), modifierLabels.separator);
        }
        if (part.metaKey) {
            this.renderKey(parent, modifierLabels.metaKey, Boolean(match === null || match === void 0 ? void 0 : match.metaKey), modifierLabels.separator);
        }
        const keyLabel = part.keyLabel;
        if (keyLabel) {
            this.renderKey(parent, keyLabel, Boolean(match === null || match === void 0 ? void 0 : match.keyCode), '');
        }
    }
    renderKey(parent, label, highlight, separator) {
        append(parent, this.createKeyElement(label, highlight ? '.highlight' : ''));
        if (separator) {
            append(parent, keybindingLabel_$('span.monaco-keybinding-key-separator', undefined, separator));
        }
    }
    renderUnbound(parent) {
        append(parent, this.createKeyElement(localize('unbound', "Unbound")));
    }
    createKeyElement(label, extraClass = '') {
        const keyElement = keybindingLabel_$('span.monaco-keybinding-key' + extraClass, undefined, label);
        this.keyElements.add(keyElement);
        return keyElement;
    }
    style(styles) {
        this.labelBackground = styles.keybindingLabelBackground;
        this.labelForeground = styles.keybindingLabelForeground;
        this.labelBorder = styles.keybindingLabelBorder;
        this.labelBottomBorder = styles.keybindingLabelBottomBorder;
        this.labelShadow = styles.keybindingLabelShadow;
        this.applyStyles();
    }
    applyStyles() {
        var _a;
        if (this.element) {
            for (const keyElement of this.keyElements) {
                if (this.labelBackground) {
                    keyElement.style.backgroundColor = (_a = this.labelBackground) === null || _a === void 0 ? void 0 : _a.toString();
                }
                if (this.labelBorder) {
                    keyElement.style.borderColor = this.labelBorder.toString();
                }
                if (this.labelBottomBorder) {
                    keyElement.style.borderBottomColor = this.labelBottomBorder.toString();
                }
                if (this.labelShadow) {
                    keyElement.style.boxShadow = `inset 0 -1px 0 ${this.labelShadow}`;
                }
            }
            if (this.labelForeground) {
                this.element.style.color = this.labelForeground.toString();
            }
        }
    }
    static areSame(a, b) {
        if (a === b || (!a && !b)) {
            return true;
        }
        return !!a && !!b && objects_equals(a.firstPart, b.firstPart) && objects_equals(a.chordPart, b.chordPart);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/common/comparers.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

// When comparing large numbers of strings it's better for performance to create an
// Intl.Collator object and use the function provided by its compare property
// than it is to use String.prototype.localeCompare()
// A collator with numeric sorting enabled, and no sensitivity to case, accents or diacritics.
const intlFileNameCollatorBaseNumeric = new IdleValue(() => {
    const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
    return {
        collator: collator,
        collatorIsNumeric: collator.resolvedOptions().numeric
    };
});
// A collator with numeric sorting enabled.
const intlFileNameCollatorNumeric = new IdleValue(() => {
    const collator = new Intl.Collator(undefined, { numeric: true });
    return {
        collator: collator
    };
});
// A collator with numeric sorting enabled, and sensitivity to accents and diacritics but not case.
const intlFileNameCollatorNumericCaseInsensitive = new IdleValue(() => {
    const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'accent' });
    return {
        collator: collator
    };
});
/** Compares filenames without distinguishing the name from the extension. Disambiguates by unicode comparison. */
function compareFileNames(one, other, caseSensitive = false) {
    const a = one || '';
    const b = other || '';
    const result = intlFileNameCollatorBaseNumeric.value.collator.compare(a, b);
    // Using the numeric option will make compare(`foo1`, `foo01`) === 0. Disambiguate.
    if (intlFileNameCollatorBaseNumeric.value.collatorIsNumeric && result === 0 && a !== b) {
        return a < b ? -1 : 1;
    }
    return result;
}
function compareAnything(one, other, lookFor) {
    const elementAName = one.toLowerCase();
    const elementBName = other.toLowerCase();
    // Sort prefix matches over non prefix matches
    const prefixCompare = compareByPrefix(one, other, lookFor);
    if (prefixCompare) {
        return prefixCompare;
    }
    // Sort suffix matches over non suffix matches
    const elementASuffixMatch = elementAName.endsWith(lookFor);
    const elementBSuffixMatch = elementBName.endsWith(lookFor);
    if (elementASuffixMatch !== elementBSuffixMatch) {
        return elementASuffixMatch ? -1 : 1;
    }
    // Understand file names
    const r = compareFileNames(elementAName, elementBName);
    if (r !== 0) {
        return r;
    }
    // Compare by name
    return elementAName.localeCompare(elementBName);
}
function compareByPrefix(one, other, lookFor) {
    const elementAName = one.toLowerCase();
    const elementBName = other.toLowerCase();
    // Sort prefix matches over non prefix matches
    const elementAPrefixMatch = elementAName.startsWith(lookFor);
    const elementBPrefixMatch = elementBName.startsWith(lookFor);
    if (elementAPrefixMatch !== elementBPrefixMatch) {
        return elementAPrefixMatch ? -1 : 1;
    }
    // Same prefix: Sort shorter matches to the top to have those on top that match more precisely
    else if (elementAPrefixMatch && elementBPrefixMatch) {
        if (elementAName.length < elementBName.length) {
            return -1;
        }
        if (elementAName.length > elementBName.length) {
            return 1;
        }
    }
    return 0;
}

;// ../../node_modules/monaco-editor/esm/vs/base/parts/quickinput/browser/quickInputList.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var quickInputList_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var quickInputList_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};



















const quickInputList_$ = dom_$;
class ListElement {
    constructor(init) {
        this.hidden = false;
        this._onChecked = new Emitter();
        this.onChecked = this._onChecked.event;
        Object.assign(this, init);
    }
    get checked() {
        return !!this._checked;
    }
    set checked(value) {
        if (value !== this._checked) {
            this._checked = value;
            this._onChecked.fire(value);
        }
    }
    dispose() {
        this._onChecked.dispose();
    }
}
class ListElementRenderer {
    get templateId() {
        return ListElementRenderer.ID;
    }
    renderTemplate(container) {
        const data = Object.create(null);
        data.toDisposeElement = [];
        data.toDisposeTemplate = [];
        data.entry = append(container, quickInputList_$('.quick-input-list-entry'));
        // Checkbox
        const label = append(data.entry, quickInputList_$('label.quick-input-list-label'));
        data.toDisposeTemplate.push(addStandardDisposableListener(label, EventType.CLICK, e => {
            if (!data.checkbox.offsetParent) { // If checkbox not visible:
                e.preventDefault(); // Prevent toggle of checkbox when it is immediately shown afterwards. #91740
            }
        }));
        data.checkbox = append(label, quickInputList_$('input.quick-input-list-checkbox'));
        data.checkbox.type = 'checkbox';
        data.toDisposeTemplate.push(addStandardDisposableListener(data.checkbox, EventType.CHANGE, e => {
            data.element.checked = data.checkbox.checked;
        }));
        // Rows
        const rows = append(label, quickInputList_$('.quick-input-list-rows'));
        const row1 = append(rows, quickInputList_$('.quick-input-list-row'));
        const row2 = append(rows, quickInputList_$('.quick-input-list-row'));
        // Label
        data.label = new IconLabel(row1, { supportHighlights: true, supportDescriptionHighlights: true, supportIcons: true });
        // Keybinding
        const keybindingContainer = append(row1, quickInputList_$('.quick-input-list-entry-keybinding'));
        data.keybinding = new KeybindingLabel(keybindingContainer, OS);
        // Detail
        const detailContainer = append(row2, quickInputList_$('.quick-input-list-label-meta'));
        data.detail = new IconLabel(detailContainer, { supportHighlights: true, supportIcons: true });
        // Separator
        data.separator = append(data.entry, quickInputList_$('.quick-input-list-separator'));
        // Actions
        data.actionBar = new ActionBar(data.entry);
        data.actionBar.domNode.classList.add('quick-input-list-entry-action-bar');
        data.toDisposeTemplate.push(data.actionBar);
        return data;
    }
    renderElement(element, index, data) {
        data.toDisposeElement = dispose(data.toDisposeElement);
        data.element = element;
        data.checkbox.checked = element.checked;
        data.toDisposeElement.push(element.onChecked(checked => data.checkbox.checked = checked));
        const { labelHighlights, descriptionHighlights, detailHighlights } = element;
        // Label
        const options = Object.create(null);
        options.matches = labelHighlights || [];
        options.descriptionTitle = element.saneDescription;
        options.descriptionMatches = descriptionHighlights || [];
        options.extraClasses = element.item.iconClasses;
        options.italic = element.item.italic;
        options.strikethrough = element.item.strikethrough;
        data.label.setLabel(element.saneLabel, element.saneDescription, options);
        // Keybinding
        data.keybinding.set(element.item.keybinding);
        // Meta
        if (element.saneDetail) {
            data.detail.setLabel(element.saneDetail, undefined, {
                matches: detailHighlights,
                title: element.saneDetail
            });
        }
        // Separator
        if (element.separator && element.separator.label) {
            data.separator.textContent = element.separator.label;
            data.separator.style.display = '';
        }
        else {
            data.separator.style.display = 'none';
        }
        data.entry.classList.toggle('quick-input-list-separator-border', !!element.separator);
        // Actions
        data.actionBar.clear();
        const buttons = element.item.buttons;
        if (buttons && buttons.length) {
            data.actionBar.push(buttons.map((button, index) => {
                let cssClasses = button.iconClass || (button.iconPath ? getIconClass(button.iconPath) : undefined);
                if (button.alwaysVisible) {
                    cssClasses = cssClasses ? `${cssClasses} always-visible` : 'always-visible';
                }
                const action = new Action(`id-${index}`, '', cssClasses, true, () => quickInputList_awaiter(this, void 0, void 0, function* () {
                    element.fireButtonTriggered({
                        button,
                        item: element.item
                    });
                }));
                action.tooltip = button.tooltip || '';
                return action;
            }), { icon: true, label: false });
            data.entry.classList.add('has-actions');
        }
        else {
            data.entry.classList.remove('has-actions');
        }
    }
    disposeElement(element, index, data) {
        data.toDisposeElement = dispose(data.toDisposeElement);
    }
    disposeTemplate(data) {
        data.toDisposeElement = dispose(data.toDisposeElement);
        data.toDisposeTemplate = dispose(data.toDisposeTemplate);
    }
}
ListElementRenderer.ID = 'listelement';
class ListElementDelegate {
    getHeight(element) {
        return element.saneDetail ? 44 : 22;
    }
    getTemplateId(element) {
        return ListElementRenderer.ID;
    }
}
var QuickInputListFocus;
(function (QuickInputListFocus) {
    QuickInputListFocus[QuickInputListFocus["First"] = 1] = "First";
    QuickInputListFocus[QuickInputListFocus["Second"] = 2] = "Second";
    QuickInputListFocus[QuickInputListFocus["Last"] = 3] = "Last";
    QuickInputListFocus[QuickInputListFocus["Next"] = 4] = "Next";
    QuickInputListFocus[QuickInputListFocus["Previous"] = 5] = "Previous";
    QuickInputListFocus[QuickInputListFocus["NextPage"] = 6] = "NextPage";
    QuickInputListFocus[QuickInputListFocus["PreviousPage"] = 7] = "PreviousPage";
})(QuickInputListFocus || (QuickInputListFocus = {}));
class QuickInputList {
    constructor(parent, id, options) {
        this.parent = parent;
        this.inputElements = [];
        this.elements = [];
        this.elementsToIndexes = new Map();
        this.matchOnDescription = false;
        this.matchOnDetail = false;
        this.matchOnLabel = true;
        this.matchOnLabelMode = 'fuzzy';
        this.matchOnMeta = true;
        this.sortByLabel = true;
        this._onChangedAllVisibleChecked = new Emitter();
        this.onChangedAllVisibleChecked = this._onChangedAllVisibleChecked.event;
        this._onChangedCheckedCount = new Emitter();
        this.onChangedCheckedCount = this._onChangedCheckedCount.event;
        this._onChangedVisibleCount = new Emitter();
        this.onChangedVisibleCount = this._onChangedVisibleCount.event;
        this._onChangedCheckedElements = new Emitter();
        this.onChangedCheckedElements = this._onChangedCheckedElements.event;
        this._onButtonTriggered = new Emitter();
        this.onButtonTriggered = this._onButtonTriggered.event;
        this._onKeyDown = new Emitter();
        this.onKeyDown = this._onKeyDown.event;
        this._onLeave = new Emitter();
        this.onLeave = this._onLeave.event;
        this._fireCheckedEvents = true;
        this.elementDisposables = [];
        this.disposables = [];
        this.id = id;
        this.container = append(this.parent, quickInputList_$('.quick-input-list'));
        const delegate = new ListElementDelegate();
        const accessibilityProvider = new QuickInputAccessibilityProvider();
        this.list = options.createList('QuickInput', this.container, delegate, [new ListElementRenderer()], {
            identityProvider: { getId: element => element.saneLabel },
            setRowLineHeight: false,
            multipleSelectionSupport: false,
            horizontalScrolling: false,
            accessibilityProvider
        });
        this.list.getHTMLElement().id = id;
        this.disposables.push(this.list);
        this.disposables.push(this.list.onKeyDown(e => {
            const event = new StandardKeyboardEvent(e);
            switch (event.keyCode) {
                case 10 /* KeyCode.Space */:
                    this.toggleCheckbox();
                    break;
                case 31 /* KeyCode.KeyA */:
                    if (isMacintosh ? e.metaKey : e.ctrlKey) {
                        this.list.setFocus(range(this.list.length));
                    }
                    break;
                case 16 /* KeyCode.UpArrow */: {
                    const focus1 = this.list.getFocus();
                    if (focus1.length === 1 && focus1[0] === 0) {
                        this._onLeave.fire();
                    }
                    break;
                }
                case 18 /* KeyCode.DownArrow */: {
                    const focus2 = this.list.getFocus();
                    if (focus2.length === 1 && focus2[0] === this.list.length - 1) {
                        this._onLeave.fire();
                    }
                    break;
                }
            }
            this._onKeyDown.fire(event);
        }));
        this.disposables.push(this.list.onMouseDown(e => {
            if (e.browserEvent.button !== 2) {
                // Works around / fixes #64350.
                e.browserEvent.preventDefault();
            }
        }));
        this.disposables.push(addDisposableListener(this.container, EventType.CLICK, e => {
            if (e.x || e.y) { // Avoid 'click' triggered by 'space' on checkbox.
                this._onLeave.fire();
            }
        }));
        this.disposables.push(this.list.onMouseMiddleClick(e => {
            this._onLeave.fire();
        }));
        this.disposables.push(this.list.onContextMenu(e => {
            if (typeof e.index === 'number') {
                e.browserEvent.preventDefault();
                // we want to treat a context menu event as
                // a gesture to open the item at the index
                // since we do not have any context menu
                // this enables for example macOS to Ctrl-
                // click on an item to open it.
                this.list.setSelection([e.index]);
            }
        }));
        this.disposables.push(this._onChangedAllVisibleChecked, this._onChangedCheckedCount, this._onChangedVisibleCount, this._onChangedCheckedElements, this._onButtonTriggered, this._onLeave, this._onKeyDown);
    }
    get onDidChangeFocus() {
        return Event.map(this.list.onDidChangeFocus, e => e.elements.map(e => e.item));
    }
    get onDidChangeSelection() {
        return Event.map(this.list.onDidChangeSelection, e => ({ items: e.elements.map(e => e.item), event: e.browserEvent }));
    }
    get scrollTop() {
        return this.list.scrollTop;
    }
    set scrollTop(scrollTop) {
        this.list.scrollTop = scrollTop;
    }
    getAllVisibleChecked() {
        return this.allVisibleChecked(this.elements, false);
    }
    allVisibleChecked(elements, whenNoneVisible = true) {
        for (let i = 0, n = elements.length; i < n; i++) {
            const element = elements[i];
            if (!element.hidden) {
                if (!element.checked) {
                    return false;
                }
                else {
                    whenNoneVisible = true;
                }
            }
        }
        return whenNoneVisible;
    }
    getCheckedCount() {
        let count = 0;
        const elements = this.elements;
        for (let i = 0, n = elements.length; i < n; i++) {
            if (elements[i].checked) {
                count++;
            }
        }
        return count;
    }
    getVisibleCount() {
        let count = 0;
        const elements = this.elements;
        for (let i = 0, n = elements.length; i < n; i++) {
            if (!elements[i].hidden) {
                count++;
            }
        }
        return count;
    }
    setAllVisibleChecked(checked) {
        try {
            this._fireCheckedEvents = false;
            this.elements.forEach(element => {
                if (!element.hidden) {
                    element.checked = checked;
                }
            });
        }
        finally {
            this._fireCheckedEvents = true;
            this.fireCheckedEvents();
        }
    }
    setElements(inputElements) {
        this.elementDisposables = dispose(this.elementDisposables);
        const fireButtonTriggered = (event) => this.fireButtonTriggered(event);
        this.inputElements = inputElements;
        this.elements = inputElements.reduce((result, item, index) => {
            var _a, _b, _c;
            if (item.type !== 'separator') {
                const previous = index && inputElements[index - 1];
                const saneLabel = item.label && item.label.replace(/\r?\n/g, ' ');
                const saneSortLabel = parseLabelWithIcons(saneLabel).text.trim();
                const saneMeta = item.meta && item.meta.replace(/\r?\n/g, ' ');
                const saneDescription = item.description && item.description.replace(/\r?\n/g, ' ');
                const saneDetail = item.detail && item.detail.replace(/\r?\n/g, ' ');
                const saneAriaLabel = item.ariaLabel || [saneLabel, saneDescription, saneDetail]
                    .map(s => getCodiconAriaLabel(s))
                    .filter(s => !!s)
                    .join(', ');
                const hasCheckbox = this.parent.classList.contains('show-checkboxes');
                result.push(new ListElement({
                    hasCheckbox,
                    index,
                    item,
                    saneLabel,
                    saneSortLabel,
                    saneMeta,
                    saneAriaLabel,
                    saneDescription,
                    saneDetail,
                    labelHighlights: (_a = item.highlights) === null || _a === void 0 ? void 0 : _a.label,
                    descriptionHighlights: (_b = item.highlights) === null || _b === void 0 ? void 0 : _b.description,
                    detailHighlights: (_c = item.highlights) === null || _c === void 0 ? void 0 : _c.detail,
                    checked: false,
                    separator: previous && previous.type === 'separator' ? previous : undefined,
                    fireButtonTriggered
                }));
            }
            return result;
        }, []);
        this.elementDisposables.push(...this.elements);
        this.elementDisposables.push(...this.elements.map(element => element.onChecked(() => this.fireCheckedEvents())));
        this.elementsToIndexes = this.elements.reduce((map, element, index) => {
            map.set(element.item, index);
            return map;
        }, new Map());
        this.list.splice(0, this.list.length); // Clear focus and selection first, sending the events when the list is empty.
        this.list.splice(0, this.list.length, this.elements);
        this._onChangedVisibleCount.fire(this.elements.length);
    }
    getFocusedElements() {
        return this.list.getFocusedElements()
            .map(e => e.item);
    }
    setFocusedElements(items) {
        this.list.setFocus(items
            .filter(item => this.elementsToIndexes.has(item))
            .map(item => this.elementsToIndexes.get(item)));
        if (items.length > 0) {
            const focused = this.list.getFocus()[0];
            if (typeof focused === 'number') {
                this.list.reveal(focused);
            }
        }
    }
    getActiveDescendant() {
        return this.list.getHTMLElement().getAttribute('aria-activedescendant');
    }
    setSelectedElements(items) {
        this.list.setSelection(items
            .filter(item => this.elementsToIndexes.has(item))
            .map(item => this.elementsToIndexes.get(item)));
    }
    getCheckedElements() {
        return this.elements.filter(e => e.checked)
            .map(e => e.item);
    }
    setCheckedElements(items) {
        try {
            this._fireCheckedEvents = false;
            const checked = new Set();
            for (const item of items) {
                checked.add(item);
            }
            for (const element of this.elements) {
                element.checked = checked.has(element.item);
            }
        }
        finally {
            this._fireCheckedEvents = true;
            this.fireCheckedEvents();
        }
    }
    set enabled(value) {
        this.list.getHTMLElement().style.pointerEvents = value ? '' : 'none';
    }
    focus(what) {
        if (!this.list.length) {
            return;
        }
        if (what === QuickInputListFocus.Next && this.list.getFocus()[0] === this.list.length - 1) {
            what = QuickInputListFocus.First;
        }
        if (what === QuickInputListFocus.Previous && this.list.getFocus()[0] === 0) {
            what = QuickInputListFocus.Last;
        }
        if (what === QuickInputListFocus.Second && this.list.length < 2) {
            what = QuickInputListFocus.First;
        }
        switch (what) {
            case QuickInputListFocus.First:
                this.list.focusFirst();
                break;
            case QuickInputListFocus.Second:
                this.list.focusNth(1);
                break;
            case QuickInputListFocus.Last:
                this.list.focusLast();
                break;
            case QuickInputListFocus.Next:
                this.list.focusNext();
                break;
            case QuickInputListFocus.Previous:
                this.list.focusPrevious();
                break;
            case QuickInputListFocus.NextPage:
                this.list.focusNextPage();
                break;
            case QuickInputListFocus.PreviousPage:
                this.list.focusPreviousPage();
                break;
        }
        const focused = this.list.getFocus()[0];
        if (typeof focused === 'number') {
            this.list.reveal(focused);
        }
    }
    clearFocus() {
        this.list.setFocus([]);
    }
    domFocus() {
        this.list.domFocus();
    }
    layout(maxHeight) {
        this.list.getHTMLElement().style.maxHeight = maxHeight ? `calc(${Math.floor(maxHeight / 44) * 44}px)` : '';
        this.list.layout();
    }
    filter(query) {
        if (!(this.sortByLabel || this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) {
            this.list.layout();
            return false;
        }
        const queryWithWhitespace = query;
        query = query.trim();
        // Reset filtering
        if (!query || !(this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) {
            this.elements.forEach(element => {
                element.labelHighlights = undefined;
                element.descriptionHighlights = undefined;
                element.detailHighlights = undefined;
                element.hidden = false;
                const previous = element.index && this.inputElements[element.index - 1];
                element.separator = previous && previous.type === 'separator' ? previous : undefined;
            });
        }
        // Filter by value (since we support icons in labels, use $(..) aware fuzzy matching)
        else {
            let currentSeparator;
            this.elements.forEach(element => {
                let labelHighlights;
                if (this.matchOnLabelMode === 'fuzzy') {
                    labelHighlights = this.matchOnLabel ? withNullAsUndefined(matchesFuzzyIconAware(query, parseLabelWithIcons(element.saneLabel))) : undefined;
                }
                else {
                    labelHighlights = this.matchOnLabel ? withNullAsUndefined(matchesContiguousIconAware(queryWithWhitespace, parseLabelWithIcons(element.saneLabel))) : undefined;
                }
                const descriptionHighlights = this.matchOnDescription ? withNullAsUndefined(matchesFuzzyIconAware(query, parseLabelWithIcons(element.saneDescription || ''))) : undefined;
                const detailHighlights = this.matchOnDetail ? withNullAsUndefined(matchesFuzzyIconAware(query, parseLabelWithIcons(element.saneDetail || ''))) : undefined;
                const metaHighlights = this.matchOnMeta ? withNullAsUndefined(matchesFuzzyIconAware(query, parseLabelWithIcons(element.saneMeta || ''))) : undefined;
                if (labelHighlights || descriptionHighlights || detailHighlights || metaHighlights) {
                    element.labelHighlights = labelHighlights;
                    element.descriptionHighlights = descriptionHighlights;
                    element.detailHighlights = detailHighlights;
                    element.hidden = false;
                }
                else {
                    element.labelHighlights = undefined;
                    element.descriptionHighlights = undefined;
                    element.detailHighlights = undefined;
                    element.hidden = !element.item.alwaysShow;
                }
                element.separator = undefined;
                // we can show the separator unless the list gets sorted by match
                if (!this.sortByLabel) {
                    const previous = element.index && this.inputElements[element.index - 1];
                    currentSeparator = previous && previous.type === 'separator' ? previous : currentSeparator;
                    if (currentSeparator && !element.hidden) {
                        element.separator = currentSeparator;
                        currentSeparator = undefined;
                    }
                }
            });
        }
        const shownElements = this.elements.filter(element => !element.hidden);
        // Sort by value
        if (this.sortByLabel && query) {
            const normalizedSearchValue = query.toLowerCase();
            shownElements.sort((a, b) => {
                return compareEntries(a, b, normalizedSearchValue);
            });
        }
        this.elementsToIndexes = shownElements.reduce((map, element, index) => {
            map.set(element.item, index);
            return map;
        }, new Map());
        this.list.splice(0, this.list.length, shownElements);
        this.list.setFocus([]);
        this.list.layout();
        this._onChangedAllVisibleChecked.fire(this.getAllVisibleChecked());
        this._onChangedVisibleCount.fire(shownElements.length);
        return true;
    }
    toggleCheckbox() {
        try {
            this._fireCheckedEvents = false;
            const elements = this.list.getFocusedElements();
            const allChecked = this.allVisibleChecked(elements);
            for (const element of elements) {
                element.checked = !allChecked;
            }
        }
        finally {
            this._fireCheckedEvents = true;
            this.fireCheckedEvents();
        }
    }
    display(display) {
        this.container.style.display = display ? '' : 'none';
    }
    isDisplayed() {
        return this.container.style.display !== 'none';
    }
    dispose() {
        this.elementDisposables = dispose(this.elementDisposables);
        this.disposables = dispose(this.disposables);
    }
    fireCheckedEvents() {
        if (this._fireCheckedEvents) {
            this._onChangedAllVisibleChecked.fire(this.getAllVisibleChecked());
            this._onChangedCheckedCount.fire(this.getCheckedCount());
            this._onChangedCheckedElements.fire(this.getCheckedElements());
        }
    }
    fireButtonTriggered(event) {
        this._onButtonTriggered.fire(event);
    }
    style(styles) {
        this.list.style(styles);
    }
}
quickInputList_decorate([
    memoize
], QuickInputList.prototype, "onDidChangeFocus", null);
quickInputList_decorate([
    memoize
], QuickInputList.prototype, "onDidChangeSelection", null);
function matchesContiguousIconAware(query, target) {
    const { text, iconOffsets } = target;
    // Return early if there are no icon markers in the word to match against
    if (!iconOffsets || iconOffsets.length === 0) {
        return matchesContiguous(query, text);
    }
    // Trim the word to match against because it could have leading
    // whitespace now if the word started with an icon
    const wordToMatchAgainstWithoutIconsTrimmed = ltrim(text, ' ');
    const leadingWhitespaceOffset = text.length - wordToMatchAgainstWithoutIconsTrimmed.length;
    // match on value without icon
    const matches = matchesContiguous(query, wordToMatchAgainstWithoutIconsTrimmed);
    // Map matches back to offsets with icon and trimming
    if (matches) {
        for (const match of matches) {
            const iconOffset = iconOffsets[match.start + leadingWhitespaceOffset] /* icon offsets at index */ + leadingWhitespaceOffset /* overall leading whitespace offset */;
            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 compareAnything(elementA.saneSortLabel, elementB.saneSortLabel, lookFor);
}
class QuickInputAccessibilityProvider {
    getWidgetAriaLabel() {
        return localize('quickInput', "Quick Input");
    }
    getAriaLabel(element) {
        var _a;
        return ((_a = element.separator) === null || _a === void 0 ? void 0 : _a.label)
            ? `${element.saneAriaLabel}, ${element.separator.label}`
            : element.saneAriaLabel;
    }
    getWidgetRole() {
        return 'listbox';
    }
    getRole(element) {
        return element.hasCheckbox ? 'checkbox' : 'option';
    }
    isChecked(element) {
        if (!element.hasCheckbox) {
            return undefined;
        }
        return {
            value: element.checked,
            onDidChange: element.onChecked
        };
    }
}

;// ../../node_modules/monaco-editor/esm/vs/base/parts/quickinput/browser/quickInput.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var quickInput_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};























const quickInput_$ = dom_$;
const backButton = {
    iconClass: Codicon.quickInputBack.classNames,
    tooltip: localize('quickInput.back', "Back"),
    handle: -1 // TODO
};
class QuickInput extends Disposable {
    constructor(ui) {
        super();
        this.ui = ui;
        this.visible = false;
        this._enabled = true;
        this._busy = false;
        this._ignoreFocusOut = false;
        this._buttons = [];
        this.noValidationMessage = QuickInput.noPromptMessage;
        this._severity = common_severity.Ignore;
        this.buttonsUpdated = false;
        this.onDidTriggerButtonEmitter = this._register(new Emitter());
        this.onDidHideEmitter = this._register(new Emitter());
        this.onDisposeEmitter = this._register(new Emitter());
        this.visibleDisposables = this._register(new DisposableStore());
        this.onDidHide = this.onDidHideEmitter.event;
    }
    get title() {
        return this._title;
    }
    set title(title) {
        this._title = title;
        this.update();
    }
    get description() {
        return this._description;
    }
    set description(description) {
        this._description = description;
        this.update();
    }
    get step() {
        return this._steps;
    }
    set step(step) {
        this._steps = step;
        this.update();
    }
    get totalSteps() {
        return this._totalSteps;
    }
    set totalSteps(totalSteps) {
        this._totalSteps = totalSteps;
        this.update();
    }
    get enabled() {
        return this._enabled;
    }
    set enabled(enabled) {
        this._enabled = enabled;
        this.update();
    }
    get contextKey() {
        return this._contextKey;
    }
    set contextKey(contextKey) {
        this._contextKey = contextKey;
        this.update();
    }
    get busy() {
        return this._busy;
    }
    set busy(busy) {
        this._busy = busy;
        this.update();
    }
    get ignoreFocusOut() {
        return this._ignoreFocusOut;
    }
    set ignoreFocusOut(ignoreFocusOut) {
        const shouldUpdate = this._ignoreFocusOut !== ignoreFocusOut && !isIOS;
        this._ignoreFocusOut = ignoreFocusOut && !isIOS;
        if (shouldUpdate) {
            this.update();
        }
    }
    get buttons() {
        return this._buttons;
    }
    set buttons(buttons) {
        this._buttons = buttons;
        this.buttonsUpdated = true;
        this.update();
    }
    get validationMessage() {
        return this._validationMessage;
    }
    set validationMessage(validationMessage) {
        this._validationMessage = validationMessage;
        this.update();
    }
    get severity() {
        return this._severity;
    }
    set severity(severity) {
        this._severity = severity;
        this.update();
    }
    show() {
        if (this.visible) {
            return;
        }
        this.visibleDisposables.add(this.ui.onDidTriggerButton(button => {
            if (this.buttons.indexOf(button) !== -1) {
                this.onDidTriggerButtonEmitter.fire(button);
            }
        }));
        this.ui.show(this);
        // update properties in the controller that get reset in the ui.show() call
        this.visible = true;
        // This ensures the message/prompt gets rendered
        this._lastValidationMessage = undefined;
        // This ensures the input box has the right severity applied
        this._lastSeverity = undefined;
        if (this.buttons.length) {
            // if there are buttons, the ui.show() clears them out of the UI so we should
            // rerender them.
            this.buttonsUpdated = true;
        }
        this.update();
    }
    hide() {
        if (!this.visible) {
            return;
        }
        this.ui.hide();
    }
    didHide(reason = QuickInputHideReason.Other) {
        this.visible = false;
        this.visibleDisposables.clear();
        this.onDidHideEmitter.fire({ reason });
    }
    update() {
        if (!this.visible) {
            return;
        }
        const title = this.getTitle();
        if (title && this.ui.title.textContent !== title) {
            this.ui.title.textContent = title;
        }
        else if (!title && this.ui.title.innerHTML !== '&nbsp;') {
            this.ui.title.innerText = '\u00a0';
        }
        const description = this.getDescription();
        if (this.ui.description1.textContent !== description) {
            this.ui.description1.textContent = description;
        }
        if (this.ui.description2.textContent !== description) {
            this.ui.description2.textContent = description;
        }
        if (this.busy && !this.busyDelay) {
            this.busyDelay = new TimeoutTimer();
            this.busyDelay.setIfNotSet(() => {
                if (this.visible) {
                    this.ui.progressBar.infinite();
                }
            }, 800);
        }
        if (!this.busy && this.busyDelay) {
            this.ui.progressBar.stop();
            this.busyDelay.cancel();
            this.busyDelay = undefined;
        }
        if (this.buttonsUpdated) {
            this.buttonsUpdated = false;
            this.ui.leftActionBar.clear();
            const leftButtons = this.buttons.filter(button => button === backButton);
            this.ui.leftActionBar.push(leftButtons.map((button, index) => {
                const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => quickInput_awaiter(this, void 0, void 0, function* () {
                    this.onDidTriggerButtonEmitter.fire(button);
                }));
                action.tooltip = button.tooltip || '';
                return action;
            }), { icon: true, label: false });
            this.ui.rightActionBar.clear();
            const rightButtons = this.buttons.filter(button => button !== backButton);
            this.ui.rightActionBar.push(rightButtons.map((button, index) => {
                const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => quickInput_awaiter(this, void 0, void 0, function* () {
                    this.onDidTriggerButtonEmitter.fire(button);
                }));
                action.tooltip = button.tooltip || '';
                return action;
            }), { icon: true, label: false });
        }
        this.ui.ignoreFocusOut = this.ignoreFocusOut;
        this.ui.setEnabled(this.enabled);
        this.ui.setContextKey(this.contextKey);
        const validationMessage = this.validationMessage || this.noValidationMessage;
        if (this._lastValidationMessage !== validationMessage) {
            this._lastValidationMessage = validationMessage;
            dom_reset(this.ui.message, ...renderLabelWithIcons(validationMessage));
        }
        if (this._lastSeverity !== this.severity) {
            this._lastSeverity = this.severity;
            this.showMessageDecoration(this.severity);
        }
    }
    getTitle() {
        if (this.title && this.step) {
            return `${this.title} (${this.getSteps()})`;
        }
        if (this.title) {
            return this.title;
        }
        if (this.step) {
            return this.getSteps();
        }
        return '';
    }
    getDescription() {
        return this.description || '';
    }
    getSteps() {
        if (this.step && this.totalSteps) {
            return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps);
        }
        if (this.step) {
            return String(this.step);
        }
        return '';
    }
    showMessageDecoration(severity) {
        this.ui.inputBox.showDecoration(severity);
        if (severity !== common_severity.Ignore) {
            const styles = this.ui.inputBox.stylesForType(severity);
            this.ui.message.style.color = styles.foreground ? `${styles.foreground}` : '';
            this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : '';
            this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : '';
            this.ui.message.style.marginBottom = '-2px';
        }
        else {
            this.ui.message.style.color = '';
            this.ui.message.style.backgroundColor = '';
            this.ui.message.style.border = '';
            this.ui.message.style.marginBottom = '';
        }
    }
    dispose() {
        this.hide();
        this.onDisposeEmitter.fire();
        super.dispose();
    }
}
QuickInput.noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel");
class QuickPick extends QuickInput {
    constructor() {
        super(...arguments);
        this._value = '';
        this.onDidChangeValueEmitter = this._register(new Emitter());
        this.onWillAcceptEmitter = this._register(new Emitter());
        this.onDidAcceptEmitter = this._register(new Emitter());
        this.onDidCustomEmitter = this._register(new Emitter());
        this._items = [];
        this.itemsUpdated = false;
        this._canSelectMany = false;
        this._canAcceptInBackground = false;
        this._matchOnDescription = false;
        this._matchOnDetail = false;
        this._matchOnLabel = true;
        this._matchOnLabelMode = 'fuzzy';
        this._sortByLabel = true;
        this._autoFocusOnList = true;
        this._keepScrollPosition = false;
        this._itemActivation = this.ui.isScreenReaderOptimized() ? ItemActivation.NONE /* https://github.com/microsoft/vscode/issues/57501 */ : ItemActivation.FIRST;
        this._activeItems = [];
        this.activeItemsUpdated = false;
        this.activeItemsToConfirm = [];
        this.onDidChangeActiveEmitter = this._register(new Emitter());
        this._selectedItems = [];
        this.selectedItemsUpdated = false;
        this.selectedItemsToConfirm = [];
        this.onDidChangeSelectionEmitter = this._register(new Emitter());
        this.onDidTriggerItemButtonEmitter = this._register(new Emitter());
        this.valueSelectionUpdated = true;
        this._ok = 'default';
        this._customButton = false;
        this.filterValue = (value) => value;
        this.onDidChangeValue = this.onDidChangeValueEmitter.event;
        this.onWillAccept = this.onWillAcceptEmitter.event;
        this.onDidAccept = this.onDidAcceptEmitter.event;
        this.onDidChangeActive = this.onDidChangeActiveEmitter.event;
        this.onDidChangeSelection = this.onDidChangeSelectionEmitter.event;
        this.onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event;
    }
    get quickNavigate() {
        return this._quickNavigate;
    }
    set quickNavigate(quickNavigate) {
        this._quickNavigate = quickNavigate;
        this.update();
    }
    get value() {
        return this._value;
    }
    set value(value) {
        this.doSetValue(value);
    }
    doSetValue(value, skipUpdate) {
        if (this._value !== value) {
            this._value = value;
            if (!skipUpdate) {
                this.update();
            }
            if (this.visible) {
                const didFilter = this.ui.list.filter(this.filterValue(this._value));
                if (didFilter) {
                    this.trySelectFirst();
                }
            }
            this.onDidChangeValueEmitter.fire(this._value);
        }
    }
    set ariaLabel(ariaLabel) {
        this._ariaLabel = ariaLabel;
        this.update();
    }
    get ariaLabel() {
        return this._ariaLabel;
    }
    get placeholder() {
        return this._placeholder;
    }
    set placeholder(placeholder) {
        this._placeholder = placeholder;
        this.update();
    }
    get items() {
        return this._items;
    }
    get scrollTop() {
        return this.ui.list.scrollTop;
    }
    set scrollTop(scrollTop) {
        this.ui.list.scrollTop = scrollTop;
    }
    set items(items) {
        this._items = items;
        this.itemsUpdated = true;
        this.update();
    }
    get canSelectMany() {
        return this._canSelectMany;
    }
    set canSelectMany(canSelectMany) {
        this._canSelectMany = canSelectMany;
        this.update();
    }
    get canAcceptInBackground() {
        return this._canAcceptInBackground;
    }
    set canAcceptInBackground(canAcceptInBackground) {
        this._canAcceptInBackground = canAcceptInBackground;
    }
    get matchOnDescription() {
        return this._matchOnDescription;
    }
    set matchOnDescription(matchOnDescription) {
        this._matchOnDescription = matchOnDescription;
        this.update();
    }
    get matchOnDetail() {
        return this._matchOnDetail;
    }
    set matchOnDetail(matchOnDetail) {
        this._matchOnDetail = matchOnDetail;
        this.update();
    }
    get matchOnLabel() {
        return this._matchOnLabel;
    }
    set matchOnLabel(matchOnLabel) {
        this._matchOnLabel = matchOnLabel;
        this.update();
    }
    get matchOnLabelMode() {
        return this._matchOnLabelMode;
    }
    set matchOnLabelMode(matchOnLabelMode) {
        this._matchOnLabelMode = matchOnLabelMode;
        this.update();
    }
    get sortByLabel() {
        return this._sortByLabel;
    }
    set sortByLabel(sortByLabel) {
        this._sortByLabel = sortByLabel;
        this.update();
    }
    get autoFocusOnList() {
        return this._autoFocusOnList;
    }
    set autoFocusOnList(autoFocusOnList) {
        this._autoFocusOnList = autoFocusOnList;
        this.update();
    }
    get keepScrollPosition() {
        return this._keepScrollPosition;
    }
    set keepScrollPosition(keepScrollPosition) {
        this._keepScrollPosition = keepScrollPosition;
    }
    get itemActivation() {
        return this._itemActivation;
    }
    set itemActivation(itemActivation) {
        this._itemActivation = itemActivation;
    }
    get activeItems() {
        return this._activeItems;
    }
    set activeItems(activeItems) {
        this._activeItems = activeItems;
        this.activeItemsUpdated = true;
        this.update();
    }
    get selectedItems() {
        return this._selectedItems;
    }
    set selectedItems(selectedItems) {
        this._selectedItems = selectedItems;
        this.selectedItemsUpdated = true;
        this.update();
    }
    get keyMods() {
        if (this._quickNavigate) {
            // Disable keyMods when quick navigate is enabled
            // because in this model the interaction is purely
            // keyboard driven and Ctrl/Alt are typically
            // pressed and hold during this interaction.
            return NO_KEY_MODS;
        }
        return this.ui.keyMods;
    }
    set valueSelection(valueSelection) {
        this._valueSelection = valueSelection;
        this.valueSelectionUpdated = true;
        this.update();
    }
    get customButton() {
        return this._customButton;
    }
    set customButton(showCustomButton) {
        this._customButton = showCustomButton;
        this.update();
    }
    get customLabel() {
        return this._customButtonLabel;
    }
    set customLabel(label) {
        this._customButtonLabel = label;
        this.update();
    }
    get customHover() {
        return this._customButtonHover;
    }
    set customHover(hover) {
        this._customButtonHover = hover;
        this.update();
    }
    get ok() {
        return this._ok;
    }
    set ok(showOkButton) {
        this._ok = showOkButton;
        this.update();
    }
    get hideInput() {
        return !!this._hideInput;
    }
    set hideInput(hideInput) {
        this._hideInput = hideInput;
        this.update();
    }
    trySelectFirst() {
        if (this.autoFocusOnList) {
            if (!this.canSelectMany) {
                this.ui.list.focus(QuickInputListFocus.First);
            }
        }
    }
    show() {
        if (!this.visible) {
            this.visibleDisposables.add(this.ui.inputBox.onDidChange(value => {
                this.doSetValue(value, true /* skip update since this originates from the UI */);
            }));
            this.visibleDisposables.add(this.ui.inputBox.onMouseDown(event => {
                if (!this.autoFocusOnList) {
                    this.ui.list.clearFocus();
                }
            }));
            this.visibleDisposables.add((this._hideInput ? this.ui.list : this.ui.inputBox).onKeyDown((event) => {
                switch (event.keyCode) {
                    case 18 /* KeyCode.DownArrow */:
                        this.ui.list.focus(QuickInputListFocus.Next);
                        if (this.canSelectMany) {
                            this.ui.list.domFocus();
                        }
                        EventHelper.stop(event, true);
                        break;
                    case 16 /* KeyCode.UpArrow */:
                        if (this.ui.list.getFocusedElements().length) {
                            this.ui.list.focus(QuickInputListFocus.Previous);
                        }
                        else {
                            this.ui.list.focus(QuickInputListFocus.Last);
                        }
                        if (this.canSelectMany) {
                            this.ui.list.domFocus();
                        }
                        EventHelper.stop(event, true);
                        break;
                    case 12 /* KeyCode.PageDown */:
                        this.ui.list.focus(QuickInputListFocus.NextPage);
                        if (this.canSelectMany) {
                            this.ui.list.domFocus();
                        }
                        EventHelper.stop(event, true);
                        break;
                    case 11 /* KeyCode.PageUp */:
                        this.ui.list.focus(QuickInputListFocus.PreviousPage);
                        if (this.canSelectMany) {
                            this.ui.list.domFocus();
                        }
                        EventHelper.stop(event, true);
                        break;
                    case 17 /* KeyCode.RightArrow */:
                        if (!this._canAcceptInBackground) {
                            return; // needs to be enabled
                        }
                        if (!this.ui.inputBox.isSelectionAtEnd()) {
                            return; // ensure input box selection at end
                        }
                        if (this.activeItems[0]) {
                            this._selectedItems = [this.activeItems[0]];
                            this.onDidChangeSelectionEmitter.fire(this.selectedItems);
                            this.handleAccept(true);
                        }
                        break;
                    case 14 /* KeyCode.Home */:
                        if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
                            this.ui.list.focus(QuickInputListFocus.First);
                            EventHelper.stop(event, true);
                        }
                        break;
                    case 13 /* KeyCode.End */:
                        if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
                            this.ui.list.focus(QuickInputListFocus.Last);
                            EventHelper.stop(event, true);
                        }
                        break;
                }
            }));
            this.visibleDisposables.add(this.ui.onDidAccept(() => {
                if (this.canSelectMany) {
                    // if there are no checked elements, it means that an onDidChangeSelection never fired to overwrite
                    // `_selectedItems`. In that case, we should emit one with an empty array to ensure that
                    // `.selectedItems` is up to date.
                    if (!this.ui.list.getCheckedElements().length) {
                        this._selectedItems = [];
                        this.onDidChangeSelectionEmitter.fire(this.selectedItems);
                    }
                }
                else if (this.activeItems[0]) {
                    // For single-select, we set `selectedItems` to the item that was accepted.
                    this._selectedItems = [this.activeItems[0]];
                    this.onDidChangeSelectionEmitter.fire(this.selectedItems);
                }
                this.handleAccept(false);
            }));
            this.visibleDisposables.add(this.ui.onDidCustom(() => {
                this.onDidCustomEmitter.fire();
            }));
            this.visibleDisposables.add(this.ui.list.onDidChangeFocus(focusedItems => {
                if (this.activeItemsUpdated) {
                    return; // Expect another event.
                }
                if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) {
                    return;
                }
                this._activeItems = focusedItems;
                this.onDidChangeActiveEmitter.fire(focusedItems);
            }));
            this.visibleDisposables.add(this.ui.list.onDidChangeSelection(({ items: selectedItems, event }) => {
                if (this.canSelectMany) {
                    if (selectedItems.length) {
                        this.ui.list.setSelectedElements([]);
                    }
                    return;
                }
                if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) {
                    return;
                }
                this._selectedItems = selectedItems;
                this.onDidChangeSelectionEmitter.fire(selectedItems);
                if (selectedItems.length) {
                    this.handleAccept(event instanceof MouseEvent && event.button === 1 /* mouse middle click */);
                }
            }));
            this.visibleDisposables.add(this.ui.list.onChangedCheckedElements(checkedItems => {
                if (!this.canSelectMany) {
                    return;
                }
                if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) {
                    return;
                }
                this._selectedItems = checkedItems;
                this.onDidChangeSelectionEmitter.fire(checkedItems);
            }));
            this.visibleDisposables.add(this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event)));
            this.visibleDisposables.add(this.registerQuickNavigation());
            this.valueSelectionUpdated = true;
        }
        super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.)
    }
    handleAccept(inBackground) {
        // Figure out veto via `onWillAccept` event
        let veto = false;
        this.onWillAcceptEmitter.fire({ veto: () => veto = true });
        // Continue with `onDidAccept` if no veto
        if (!veto) {
            this.onDidAcceptEmitter.fire({ inBackground });
        }
    }
    registerQuickNavigation() {
        return addDisposableListener(this.ui.container, EventType.KEY_UP, e => {
            if (this.canSelectMany || !this._quickNavigate) {
                return;
            }
            const keyboardEvent = new StandardKeyboardEvent(e);
            const keyCode = keyboardEvent.keyCode;
            // Select element when keys are pressed that signal it
            const quickNavKeys = this._quickNavigate.keybindings;
            const wasTriggerKeyPressed = quickNavKeys.some(k => {
                const [firstPart, chordPart] = k.getParts();
                if (chordPart) {
                    return false;
                }
                if (firstPart.shiftKey && keyCode === 4 /* KeyCode.Shift */) {
                    if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) {
                        return false; // this is an optimistic check for the shift key being used to navigate back in quick input
                    }
                    return true;
                }
                if (firstPart.altKey && keyCode === 6 /* KeyCode.Alt */) {
                    return true;
                }
                if (firstPart.ctrlKey && keyCode === 5 /* KeyCode.Ctrl */) {
                    return true;
                }
                if (firstPart.metaKey && keyCode === 57 /* KeyCode.Meta */) {
                    return true;
                }
                return false;
            });
            if (wasTriggerKeyPressed) {
                if (this.activeItems[0]) {
                    this._selectedItems = [this.activeItems[0]];
                    this.onDidChangeSelectionEmitter.fire(this.selectedItems);
                    this.handleAccept(false);
                }
                // Unset quick navigate after press. It is only valid once
                // and should not result in any behaviour change afterwards
                // if the picker remains open because there was no active item
                this._quickNavigate = undefined;
            }
        });
    }
    update() {
        if (!this.visible) {
            return;
        }
        // store the scrollTop before it is reset
        const scrollTopBefore = this.keepScrollPosition ? this.scrollTop : 0;
        const hideInput = !!this._hideInput && this._items.length > 0;
        this.ui.container.classList.toggle('hidden-input', hideInput && !this.description);
        const visibilities = {
            title: !!this.title || !!this.step || !!this.buttons.length,
            description: !!this.description,
            checkAll: this.canSelectMany && !this._hideCheckAll,
            checkBox: this.canSelectMany,
            inputBox: !hideInput,
            progressBar: !hideInput,
            visibleCount: true,
            count: this.canSelectMany,
            ok: this.ok === 'default' ? this.canSelectMany : this.ok,
            list: true,
            message: !!this.validationMessage,
            customButton: this.customButton
        };
        this.ui.setVisibilities(visibilities);
        super.update();
        if (this.ui.inputBox.value !== this.value) {
            this.ui.inputBox.value = this.value;
        }
        if (this.valueSelectionUpdated) {
            this.valueSelectionUpdated = false;
            this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] });
        }
        if (this.ui.inputBox.placeholder !== (this.placeholder || '')) {
            this.ui.inputBox.placeholder = (this.placeholder || '');
        }
        let ariaLabel = this.ariaLabel;
        if (!ariaLabel) {
            ariaLabel = this.placeholder || QuickPick.DEFAULT_ARIA_LABEL;
            // If we have a title, include it in the aria label.
            if (this.title) {
                ariaLabel += ` - ${this.title}`;
            }
        }
        if (this.ui.inputBox.ariaLabel !== ariaLabel) {
            this.ui.inputBox.ariaLabel = ariaLabel;
        }
        this.ui.list.matchOnDescription = this.matchOnDescription;
        this.ui.list.matchOnDetail = this.matchOnDetail;
        this.ui.list.matchOnLabel = this.matchOnLabel;
        this.ui.list.matchOnLabelMode = this.matchOnLabelMode;
        this.ui.list.sortByLabel = this.sortByLabel;
        if (this.itemsUpdated) {
            this.itemsUpdated = false;
            this.ui.list.setElements(this.items);
            this.ui.list.filter(this.filterValue(this.ui.inputBox.value));
            this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked();
            this.ui.visibleCount.setCount(this.ui.list.getVisibleCount());
            this.ui.count.setCount(this.ui.list.getCheckedCount());
            switch (this._itemActivation) {
                case ItemActivation.NONE:
                    this._itemActivation = ItemActivation.FIRST; // only valid once, then unset
                    break;
                case ItemActivation.SECOND:
                    this.ui.list.focus(QuickInputListFocus.Second);
                    this._itemActivation = ItemActivation.FIRST; // only valid once, then unset
                    break;
                case ItemActivation.LAST:
                    this.ui.list.focus(QuickInputListFocus.Last);
                    this._itemActivation = ItemActivation.FIRST; // only valid once, then unset
                    break;
                default:
                    this.trySelectFirst();
                    break;
            }
        }
        if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) {
            if (this.canSelectMany) {
                this.ui.list.clearFocus();
            }
            else {
                this.trySelectFirst();
            }
        }
        if (this.activeItemsUpdated) {
            this.activeItemsUpdated = false;
            this.activeItemsToConfirm = this._activeItems;
            this.ui.list.setFocusedElements(this.activeItems);
            if (this.activeItemsToConfirm === this._activeItems) {
                this.activeItemsToConfirm = null;
            }
        }
        if (this.selectedItemsUpdated) {
            this.selectedItemsUpdated = false;
            this.selectedItemsToConfirm = this._selectedItems;
            if (this.canSelectMany) {
                this.ui.list.setCheckedElements(this.selectedItems);
            }
            else {
                this.ui.list.setSelectedElements(this.selectedItems);
            }
            if (this.selectedItemsToConfirm === this._selectedItems) {
                this.selectedItemsToConfirm = null;
            }
        }
        this.ui.customButton.label = this.customLabel || '';
        this.ui.customButton.element.title = this.customHover || '';
        this.ui.setComboboxAccessibility(true);
        if (!visibilities.inputBox) {
            // we need to move focus into the tree to detect keybindings
            // properly when the input box is not visible (quick nav)
            this.ui.list.domFocus();
            // Focus the first element in the list if multiselect is enabled
            if (this.canSelectMany) {
                this.ui.list.focus(QuickInputListFocus.First);
            }
        }
        // Set the scroll position to what it was before updating the items
        if (this.keepScrollPosition) {
            this.scrollTop = scrollTopBefore;
        }
    }
}
QuickPick.DEFAULT_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results.");
class QuickInputController extends Disposable {
    constructor(options) {
        super();
        this.options = options;
        this.comboboxAccessibility = false;
        this.enabled = true;
        this.onDidAcceptEmitter = this._register(new Emitter());
        this.onDidCustomEmitter = this._register(new Emitter());
        this.onDidTriggerButtonEmitter = this._register(new Emitter());
        this.keyMods = { ctrlCmd: false, alt: false };
        this.controller = null;
        this.onShowEmitter = this._register(new Emitter());
        this.onShow = this.onShowEmitter.event;
        this.onHideEmitter = this._register(new Emitter());
        this.onHide = this.onHideEmitter.event;
        this.idPrefix = options.idPrefix;
        this.parentElement = options.container;
        this.styles = options.styles;
        this.registerKeyModsListeners();
    }
    registerKeyModsListeners() {
        const listener = (e) => {
            this.keyMods.ctrlCmd = e.ctrlKey || e.metaKey;
            this.keyMods.alt = e.altKey;
        };
        this._register(addDisposableListener(window, EventType.KEY_DOWN, listener, true));
        this._register(addDisposableListener(window, EventType.KEY_UP, listener, true));
        this._register(addDisposableListener(window, EventType.MOUSE_DOWN, listener, true));
    }
    getUI() {
        if (this.ui) {
            return this.ui;
        }
        const container = append(this.parentElement, quickInput_$('.quick-input-widget.show-file-icons'));
        container.tabIndex = -1;
        container.style.display = 'none';
        const styleSheet = createStyleSheet(container);
        const titleBar = append(container, quickInput_$('.quick-input-titlebar'));
        const leftActionBar = this._register(new ActionBar(titleBar));
        leftActionBar.domNode.classList.add('quick-input-left-action-bar');
        const title = append(titleBar, quickInput_$('.quick-input-title'));
        const rightActionBar = this._register(new ActionBar(titleBar));
        rightActionBar.domNode.classList.add('quick-input-right-action-bar');
        const description1 = append(container, quickInput_$('.quick-input-description'));
        const headerContainer = append(container, quickInput_$('.quick-input-header'));
        const checkAll = append(headerContainer, quickInput_$('input.quick-input-check-all'));
        checkAll.type = 'checkbox';
        checkAll.setAttribute('aria-label', localize('quickInput.checkAll', "Toggle all checkboxes"));
        this._register(addStandardDisposableListener(checkAll, EventType.CHANGE, e => {
            const checked = checkAll.checked;
            list.setAllVisibleChecked(checked);
        }));
        this._register(addDisposableListener(checkAll, EventType.CLICK, e => {
            if (e.x || e.y) { // Avoid 'click' triggered by 'space'...
                inputBox.setFocus();
            }
        }));
        const description2 = append(headerContainer, quickInput_$('.quick-input-description'));
        const extraContainer = append(headerContainer, quickInput_$('.quick-input-and-message'));
        const filterContainer = append(extraContainer, quickInput_$('.quick-input-filter'));
        const inputBox = this._register(new QuickInputBox(filterContainer));
        inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`);
        const visibleCountContainer = append(filterContainer, quickInput_$('.quick-input-visible-count'));
        visibleCountContainer.setAttribute('aria-live', 'polite');
        visibleCountContainer.setAttribute('aria-atomic', 'true');
        const visibleCount = new CountBadge(visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") });
        const countContainer = append(filterContainer, quickInput_$('.quick-input-count'));
        countContainer.setAttribute('aria-live', 'polite');
        const count = new CountBadge(countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") });
        const okContainer = append(headerContainer, quickInput_$('.quick-input-action'));
        const ok = new Button(okContainer);
        ok.label = localize('ok', "OK");
        this._register(ok.onDidClick(e => {
            this.onDidAcceptEmitter.fire();
        }));
        const customButtonContainer = append(headerContainer, quickInput_$('.quick-input-action'));
        const customButton = new Button(customButtonContainer);
        customButton.label = localize('custom', "Custom");
        this._register(customButton.onDidClick(e => {
            this.onDidCustomEmitter.fire();
        }));
        const message = append(extraContainer, quickInput_$(`#${this.idPrefix}message.quick-input-message`));
        const list = this._register(new QuickInputList(container, this.idPrefix + 'list', this.options));
        this._register(list.onChangedAllVisibleChecked(checked => {
            checkAll.checked = checked;
        }));
        this._register(list.onChangedVisibleCount(c => {
            visibleCount.setCount(c);
        }));
        this._register(list.onChangedCheckedCount(c => {
            count.setCount(c);
        }));
        this._register(list.onLeave(() => {
            // Defer to avoid the input field reacting to the triggering key.
            setTimeout(() => {
                inputBox.setFocus();
                if (this.controller instanceof QuickPick && this.controller.canSelectMany) {
                    list.clearFocus();
                }
            }, 0);
        }));
        this._register(list.onDidChangeFocus(() => {
            if (this.comboboxAccessibility) {
                this.getUI().inputBox.setAttribute('aria-activedescendant', this.getUI().list.getActiveDescendant() || '');
            }
        }));
        const progressBar = new ProgressBar(container);
        progressBar.getContainer().classList.add('quick-input-progress');
        const focusTracker = trackFocus(container);
        this._register(focusTracker);
        this._register(addDisposableListener(container, EventType.FOCUS, e => {
            this.previousFocusElement = e.relatedTarget instanceof HTMLElement ? e.relatedTarget : undefined;
        }, true));
        this._register(focusTracker.onDidBlur(() => {
            if (!this.getUI().ignoreFocusOut && !this.options.ignoreFocusOut()) {
                this.hide(QuickInputHideReason.Blur);
            }
            this.previousFocusElement = undefined;
        }));
        this._register(addDisposableListener(container, EventType.FOCUS, (e) => {
            inputBox.setFocus();
        }));
        this._register(addDisposableListener(container, EventType.KEY_DOWN, (e) => {
            const event = new StandardKeyboardEvent(e);
            switch (event.keyCode) {
                case 3 /* KeyCode.Enter */:
                    EventHelper.stop(e, true);
                    this.onDidAcceptEmitter.fire();
                    break;
                case 9 /* KeyCode.Escape */:
                    EventHelper.stop(e, true);
                    this.hide(QuickInputHideReason.Gesture);
                    break;
                case 2 /* KeyCode.Tab */:
                    if (!event.altKey && !event.ctrlKey && !event.metaKey) {
                        const selectors = ['.action-label.codicon'];
                        if (container.classList.contains('show-checkboxes')) {
                            selectors.push('input');
                        }
                        else {
                            selectors.push('input[type=text]');
                        }
                        if (this.getUI().list.isDisplayed()) {
                            selectors.push('.monaco-list');
                        }
                        const stops = container.querySelectorAll(selectors.join(', '));
                        if (event.shiftKey && event.target === stops[0]) {
                            EventHelper.stop(e, true);
                            stops[stops.length - 1].focus();
                        }
                        else if (!event.shiftKey && event.target === stops[stops.length - 1]) {
                            EventHelper.stop(e, true);
                            stops[0].focus();
                        }
                    }
                    break;
            }
        }));
        this.ui = {
            container,
            styleSheet,
            leftActionBar,
            titleBar,
            title,
            description1,
            description2,
            rightActionBar,
            checkAll,
            filterContainer,
            inputBox,
            visibleCountContainer,
            visibleCount,
            countContainer,
            count,
            okContainer,
            ok,
            message,
            customButtonContainer,
            customButton,
            list,
            progressBar,
            onDidAccept: this.onDidAcceptEmitter.event,
            onDidCustom: this.onDidCustomEmitter.event,
            onDidTriggerButton: this.onDidTriggerButtonEmitter.event,
            ignoreFocusOut: false,
            keyMods: this.keyMods,
            isScreenReaderOptimized: () => this.options.isScreenReaderOptimized(),
            show: controller => this.show(controller),
            hide: () => this.hide(),
            setVisibilities: visibilities => this.setVisibilities(visibilities),
            setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled),
            setEnabled: enabled => this.setEnabled(enabled),
            setContextKey: contextKey => this.options.setContextKey(contextKey),
        };
        this.updateStyles();
        return this.ui;
    }
    pick(picks, options = {}, token = CancellationToken.None) {
        return new Promise((doResolve, reject) => {
            let resolve = (result) => {
                var _a;
                resolve = doResolve;
                (_a = options.onKeyMods) === null || _a === void 0 ? void 0 : _a.call(options, input.keyMods);
                doResolve(result);
            };
            if (token.isCancellationRequested) {
                resolve(undefined);
                return;
            }
            const input = this.createQuickPick();
            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 && options.onDidFocus) {
                        options.onDidFocus(focused);
                    }
                }),
                input.onDidChangeSelection(items => {
                    if (!input.canSelectMany) {
                        const result = items[0];
                        if (result) {
                            resolve(result);
                            input.hide();
                        }
                    }
                }),
                input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton(Object.assign(Object.assign({}, 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(activeItem => activeItem !== removed[0]);
                            const keepScrollPositionBefore = input.keepScrollPosition;
                            input.keepScrollPosition = true;
                            input.items = items;
                            if (activeItems) {
                                input.activeItems = activeItems;
                            }
                            input.keepScrollPosition = keepScrollPositionBefore;
                        }
                    } }))),
                input.onDidChangeValue(value => {
                    if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) {
                        input.activeItems = [activeItem];
                    }
                }),
                token.onCancellationRequested(() => {
                    input.hide();
                }),
                input.onDidHide(() => {
                    dispose(disposables);
                    resolve(undefined);
                }),
            ];
            input.title = options.title;
            input.canSelectMany = !!options.canPickMany;
            input.placeholder = options.placeHolder;
            input.ignoreFocusOut = !!options.ignoreFocusLost;
            input.matchOnDescription = !!options.matchOnDescription;
            input.matchOnDetail = !!options.matchOnDetail;
            input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true
            input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true
            input.quickNavigate = options.quickNavigate;
            input.hideInput = !!options.hideInput;
            input.contextKey = options.contextKey;
            input.busy = true;
            Promise.all([picks, options.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(undefined, err => {
                reject(err);
                input.hide();
            });
        });
    }
    createQuickPick() {
        const ui = this.getUI();
        return new QuickPick(ui);
    }
    show(controller) {
        const ui = this.getUI();
        this.onShowEmitter.fire();
        const oldController = this.controller;
        this.controller = controller;
        if (oldController) {
            oldController.didHide();
        }
        this.setEnabled(true);
        ui.leftActionBar.clear();
        ui.title.textContent = '';
        ui.description1.textContent = '';
        ui.description2.textContent = '';
        ui.rightActionBar.clear();
        ui.checkAll.checked = false;
        // ui.inputBox.value = ''; Avoid triggering an event.
        ui.inputBox.placeholder = '';
        ui.inputBox.password = false;
        ui.inputBox.showDecoration(common_severity.Ignore);
        ui.visibleCount.setCount(0);
        ui.count.setCount(0);
        dom_reset(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;
        this.setComboboxAccessibility(false);
        ui.inputBox.ariaLabel = '';
        const backKeybindingLabel = this.options.backKeybindingLabel();
        backButton.tooltip = backKeybindingLabel ? localize('quickInput.backWithKeybinding', "Back ({0})", backKeybindingLabel) : localize('quickInput.back', "Back");
        ui.container.style.display = '';
        this.updateLayout();
        ui.inputBox.setFocus();
    }
    setVisibilities(visibilities) {
        const ui = this.getUI();
        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.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.display(!!visibilities.list);
        ui.container.classList[visibilities.checkBox ? 'add' : 'remove']('show-checkboxes');
        this.updateLayout(); // TODO
    }
    setComboboxAccessibility(enabled) {
        if (enabled !== this.comboboxAccessibility) {
            const ui = this.getUI();
            this.comboboxAccessibility = enabled;
            if (this.comboboxAccessibility) {
                ui.inputBox.setAttribute('role', 'combobox');
                ui.inputBox.setAttribute('aria-haspopup', 'true');
                ui.inputBox.setAttribute('aria-autocomplete', 'list');
                ui.inputBox.setAttribute('aria-activedescendant', ui.list.getActiveDescendant() || '');
            }
            else {
                ui.inputBox.removeAttribute('role');
                ui.inputBox.removeAttribute('aria-haspopup');
                ui.inputBox.removeAttribute('aria-autocomplete');
                ui.inputBox.removeAttribute('aria-activedescendant');
            }
        }
    }
    setEnabled(enabled) {
        if (enabled !== this.enabled) {
            this.enabled = enabled;
            for (const item of this.getUI().leftActionBar.viewItems) {
                item.getAction().enabled = enabled;
            }
            for (const item of this.getUI().rightActionBar.viewItems) {
                item.getAction().enabled = enabled;
            }
            this.getUI().checkAll.disabled = !enabled;
            // this.getUI().inputBox.enabled = enabled; Avoid loosing focus.
            this.getUI().ok.enabled = enabled;
            this.getUI().list.enabled = enabled;
        }
    }
    hide(reason) {
        var _a;
        const controller = this.controller;
        if (controller) {
            const focusChanged = !((_a = this.ui) === null || _a === void 0 ? void 0 : _a.container.contains(document.activeElement));
            this.controller = null;
            this.onHideEmitter.fire();
            this.getUI().container.style.display = 'none';
            if (!focusChanged) {
                let currentElement = this.previousFocusElement;
                while (currentElement && !currentElement.offsetParent) {
                    currentElement = withNullAsUndefined(currentElement.parentElement);
                }
                if (currentElement === null || currentElement === void 0 ? void 0 : currentElement.offsetParent) {
                    currentElement.focus();
                    this.previousFocusElement = undefined;
                }
                else {
                    this.options.returnFocus();
                }
            }
            controller.didHide(reason);
        }
    }
    layout(dimension, titleBarOffset) {
        this.dimension = dimension;
        this.titleBarOffset = titleBarOffset;
        this.updateLayout();
    }
    updateLayout() {
        if (this.ui) {
            this.ui.container.style.top = `${this.titleBarOffset}px`;
            const style = this.ui.container.style;
            const width = Math.min(this.dimension.width * 0.62 /* golden cut */, QuickInputController.MAX_WIDTH);
            style.width = width + 'px';
            style.marginLeft = '-' + (width / 2) + 'px';
            this.ui.inputBox.layout();
            this.ui.list.layout(this.dimension && this.dimension.height * 0.4);
        }
    }
    applyStyles(styles) {
        this.styles = styles;
        this.updateStyles();
    }
    updateStyles() {
        if (this.ui) {
            const { quickInputTitleBackground, quickInputBackground, quickInputForeground, contrastBorder, widgetShadow, } = this.styles.widget;
            this.ui.titleBar.style.backgroundColor = quickInputTitleBackground ? quickInputTitleBackground.toString() : '';
            this.ui.container.style.backgroundColor = quickInputBackground ? quickInputBackground.toString() : '';
            this.ui.container.style.color = quickInputForeground ? quickInputForeground.toString() : '';
            this.ui.container.style.border = contrastBorder ? `1px solid ${contrastBorder}` : '';
            this.ui.container.style.boxShadow = widgetShadow ? `0 0 8px 2px ${widgetShadow}` : '';
            this.ui.inputBox.style(this.styles.inputBox);
            this.ui.count.style(this.styles.countBadge);
            this.ui.ok.style(this.styles.button);
            this.ui.customButton.style(this.styles.button);
            this.ui.progressBar.style(this.styles.progressBar);
            this.ui.list.style(this.styles.list);
            const content = [];
            if (this.styles.list.pickerGroupBorder) {
                content.push(`.quick-input-list .quick-input-list-entry { border-top-color:  ${this.styles.list.pickerGroupBorder}; }`);
            }
            if (this.styles.list.pickerGroupForeground) {
                content.push(`.quick-input-list .quick-input-list-separator { color:  ${this.styles.list.pickerGroupForeground}; }`);
            }
            if (this.styles.keybindingLabel.keybindingLabelBackground ||
                this.styles.keybindingLabel.keybindingLabelBorder ||
                this.styles.keybindingLabel.keybindingLabelBottomBorder ||
                this.styles.keybindingLabel.keybindingLabelShadow ||
                this.styles.keybindingLabel.keybindingLabelForeground) {
                content.push('.quick-input-list .monaco-keybinding > .monaco-keybinding-key {');
                if (this.styles.keybindingLabel.keybindingLabelBackground) {
                    content.push(`background-color: ${this.styles.keybindingLabel.keybindingLabelBackground};`);
                }
                if (this.styles.keybindingLabel.keybindingLabelBorder) {
                    // Order matters here. `border-color` must come before `border-bottom-color`.
                    content.push(`border-color: ${this.styles.keybindingLabel.keybindingLabelBorder};`);
                }
                if (this.styles.keybindingLabel.keybindingLabelBottomBorder) {
                    content.push(`border-bottom-color: ${this.styles.keybindingLabel.keybindingLabelBottomBorder};`);
                }
                if (this.styles.keybindingLabel.keybindingLabelShadow) {
                    content.push(`box-shadow: inset 0 -1px 0 ${this.styles.keybindingLabel.keybindingLabelShadow};`);
                }
                if (this.styles.keybindingLabel.keybindingLabelForeground) {
                    content.push(`color: ${this.styles.keybindingLabel.keybindingLabelForeground};`);
                }
                content.push('}');
            }
            const newStyles = content.join('\n');
            if (newStyles !== this.ui.styleSheet.textContent) {
                this.ui.styleSheet.textContent = newStyles;
            }
        }
    }
}
QuickInputController.MAX_WIDTH = 600; // Max total width of quick input widget

;// ../../node_modules/monaco-editor/esm/vs/platform/quickinput/browser/quickAccess.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var quickAccess_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var quickAccess_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};








let QuickAccessController = class QuickAccessController extends Disposable {
    constructor(quickInputService, instantiationService) {
        super();
        this.quickInputService = quickInputService;
        this.instantiationService = instantiationService;
        this.registry = Registry.as(quickAccess_Extensions.Quickaccess);
        this.mapProviderToDescriptor = new Map();
        this.lastAcceptedPickerValues = new Map();
        this.visibleQuickAccess = undefined;
    }
    show(value = '', options) {
        this.doShowOrPick(value, false, options);
    }
    doShowOrPick(value, pick, options) {
        var _a;
        // Find provider for the value to show
        const [provider, descriptor] = this.getOrInstantiateProvider(value);
        // Return early if quick access is already showing on that same prefix
        const visibleQuickAccess = this.visibleQuickAccess;
        const visibleDescriptor = visibleQuickAccess === null || visibleQuickAccess === void 0 ? void 0 : visibleQuickAccess.descriptor;
        if (visibleQuickAccess && descriptor && visibleDescriptor === descriptor) {
            // Apply value only if it is more specific than the prefix
            // from the provider and we are not instructed to preserve
            if (value !== descriptor.prefix && !(options === null || options === void 0 ? void 0 : options.preserveValue)) {
                visibleQuickAccess.picker.value = value;
            }
            // Always adjust selection
            this.adjustValueSelection(visibleQuickAccess.picker, descriptor, options);
            return;
        }
        // Rewrite the filter value based on certain rules unless disabled
        if (descriptor && !(options === null || options === void 0 ? void 0 : options.preserveValue)) {
            let newValue = undefined;
            // If we have a visible provider with a value, take it's filter value but
            // rewrite to new provider prefix in case they differ
            if (visibleQuickAccess && visibleDescriptor && visibleDescriptor !== descriptor) {
                const newValueCandidateWithoutPrefix = visibleQuickAccess.value.substr(visibleDescriptor.prefix.length);
                if (newValueCandidateWithoutPrefix) {
                    newValue = `${descriptor.prefix}${newValueCandidateWithoutPrefix}`;
                }
            }
            // Otherwise, take a default value as instructed
            if (!newValue) {
                const defaultFilterValue = provider === null || provider === void 0 ? void 0 : provider.defaultFilterValue;
                if (defaultFilterValue === DefaultQuickAccessFilterValue.LAST) {
                    newValue = this.lastAcceptedPickerValues.get(descriptor);
                }
                else if (typeof defaultFilterValue === 'string') {
                    newValue = `${descriptor.prefix}${defaultFilterValue}`;
                }
            }
            if (typeof newValue === 'string') {
                value = newValue;
            }
        }
        // Create a picker for the provider to use with the initial value
        // and adjust the filtering to exclude the prefix from filtering
        const disposables = new DisposableStore();
        const picker = disposables.add(this.quickInputService.createQuickPick());
        picker.value = value;
        this.adjustValueSelection(picker, descriptor, options);
        picker.placeholder = descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder;
        picker.quickNavigate = options === null || options === void 0 ? void 0 : options.quickNavigateConfiguration;
        picker.hideInput = !!picker.quickNavigate && !visibleQuickAccess; // only hide input if there was no picker opened already
        if (typeof (options === null || options === void 0 ? void 0 : options.itemActivation) === 'number' || (options === null || options === void 0 ? void 0 : options.quickNavigateConfiguration)) {
            picker.itemActivation = (_a = options === null || options === void 0 ? void 0 : options.itemActivation) !== null && _a !== void 0 ? _a : ItemActivation.SECOND /* quick nav is always second */;
        }
        picker.contextKey = descriptor === null || descriptor === void 0 ? void 0 : descriptor.contextKey;
        picker.filterValue = (value) => value.substring(descriptor ? descriptor.prefix.length : 0);
        if (descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder) {
            picker.ariaLabel = descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder;
        }
        // Pick mode: setup a promise that can be resolved
        // with the selected items and prevent execution
        let pickPromise = undefined;
        if (pick) {
            pickPromise = new DeferredPromise();
            disposables.add(once(picker.onWillAccept)(e => {
                e.veto();
                picker.hide();
            }));
        }
        // Register listeners
        disposables.add(this.registerPickerListeners(picker, provider, descriptor, value));
        // Ask provider to fill the picker as needed if we have one
        // and pass over a cancellation token that will indicate when
        // the picker is hiding without a pick being made.
        const cts = disposables.add(new CancellationTokenSource());
        if (provider) {
            disposables.add(provider.provide(picker, cts.token));
        }
        // Finally, trigger disposal and cancellation when the picker
        // hides depending on items selected or not.
        once(picker.onDidHide)(() => {
            if (picker.selectedItems.length === 0) {
                cts.cancel();
            }
            // Start to dispose once picker hides
            disposables.dispose();
            // Resolve pick promise with selected items
            pickPromise === null || pickPromise === void 0 ? void 0 : pickPromise.complete(picker.selectedItems.slice(0));
        });
        // Finally, show the picker. This is important because a provider
        // may not call this and then our disposables would leak that rely
        // on the onDidHide event.
        picker.show();
        // Pick mode: return with promise
        if (pick) {
            return pickPromise === null || pickPromise === void 0 ? void 0 : pickPromise.p;
        }
    }
    adjustValueSelection(picker, descriptor, options) {
        var _a;
        let valueSelection;
        // Preserve: just always put the cursor at the end
        if (options === null || options === void 0 ? void 0 : options.preserveValue) {
            valueSelection = [picker.value.length, picker.value.length];
        }
        // Otherwise: select the value up until the prefix
        else {
            valueSelection = [(_a = descriptor === null || descriptor === void 0 ? void 0 : descriptor.prefix.length) !== null && _a !== void 0 ? _a : 0, picker.value.length];
        }
        picker.valueSelection = valueSelection;
    }
    registerPickerListeners(picker, provider, descriptor, value) {
        const disposables = new DisposableStore();
        // Remember as last visible picker and clean up once picker get's disposed
        const visibleQuickAccess = this.visibleQuickAccess = { picker, descriptor, value };
        disposables.add(toDisposable(() => {
            if (visibleQuickAccess === this.visibleQuickAccess) {
                this.visibleQuickAccess = undefined;
            }
        }));
        // Whenever the value changes, check if the provider has
        // changed and if so - re-create the picker from the beginning
        disposables.add(picker.onDidChangeValue(value => {
            const [providerForValue] = this.getOrInstantiateProvider(value);
            if (providerForValue !== provider) {
                this.show(value, { preserveValue: true } /* do not rewrite value from user typing! */);
            }
            else {
                visibleQuickAccess.value = value; // remember the value in our visible one
            }
        }));
        // Remember picker input for future use when accepting
        if (descriptor) {
            disposables.add(picker.onDidAccept(() => {
                this.lastAcceptedPickerValues.set(descriptor, picker.value);
            }));
        }
        return disposables;
    }
    getOrInstantiateProvider(value) {
        const providerDescriptor = this.registry.getQuickAccessProvider(value);
        if (!providerDescriptor) {
            return [undefined, undefined];
        }
        let provider = this.mapProviderToDescriptor.get(providerDescriptor);
        if (!provider) {
            provider = this.instantiationService.createInstance(providerDescriptor.ctor);
            this.mapProviderToDescriptor.set(providerDescriptor, provider);
        }
        return [provider, providerDescriptor];
    }
};
QuickAccessController = quickAccess_decorate([
    quickAccess_param(0, IQuickInputService),
    quickAccess_param(1, IInstantiationService)
], QuickAccessController);


;// ../../node_modules/monaco-editor/esm/vs/platform/quickinput/browser/quickInput.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var quickInput_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var quickInput_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};











let QuickInputService = class QuickInputService extends Themable {
    constructor(instantiationService, contextKeyService, themeService, accessibilityService, layoutService) {
        super(themeService);
        this.instantiationService = instantiationService;
        this.contextKeyService = contextKeyService;
        this.accessibilityService = accessibilityService;
        this.layoutService = layoutService;
        this.contexts = new Map();
    }
    get controller() {
        if (!this._controller) {
            this._controller = this._register(this.createController());
        }
        return this._controller;
    }
    get quickAccess() {
        if (!this._quickAccess) {
            this._quickAccess = this._register(this.instantiationService.createInstance(QuickAccessController));
        }
        return this._quickAccess;
    }
    createController(host = this.layoutService, options) {
        const defaultOptions = {
            idPrefix: 'quickInput_',
            container: host.container,
            ignoreFocusOut: () => false,
            isScreenReaderOptimized: () => this.accessibilityService.isScreenReaderOptimized(),
            backKeybindingLabel: () => undefined,
            setContextKey: (id) => this.setContextKey(id),
            returnFocus: () => host.focus(),
            createList: (user, container, delegate, renderers, options) => this.instantiationService.createInstance(WorkbenchList, user, container, delegate, renderers, options),
            styles: this.computeStyles()
        };
        const controller = this._register(new QuickInputController(Object.assign(Object.assign({}, defaultOptions), options)));
        controller.layout(host.dimension, host.offset.quickPickTop);
        // Layout changes
        this._register(host.onDidLayout(dimension => controller.layout(dimension, host.offset.quickPickTop)));
        // Context keys
        this._register(controller.onShow(() => this.resetContextKeys()));
        this._register(controller.onHide(() => this.resetContextKeys()));
        return controller;
    }
    setContextKey(id) {
        let key;
        if (id) {
            key = this.contexts.get(id);
            if (!key) {
                key = new RawContextKey(id, false)
                    .bindTo(this.contextKeyService);
                this.contexts.set(id, key);
            }
        }
        if (key && key.get()) {
            return; // already active context
        }
        this.resetContextKeys();
        key === null || key === void 0 ? void 0 : key.set(true);
    }
    resetContextKeys() {
        this.contexts.forEach(context => {
            if (context.get()) {
                context.reset();
            }
        });
    }
    pick(picks, options = {}, token = CancellationToken.None) {
        return this.controller.pick(picks, options, token);
    }
    createQuickPick() {
        return this.controller.createQuickPick();
    }
    updateStyles() {
        this.controller.applyStyles(this.computeStyles());
    }
    computeStyles() {
        return {
            widget: Object.assign({}, computeStyles(this.theme, {
                quickInputBackground: quickInputBackground,
                quickInputForeground: quickInputForeground,
                quickInputTitleBackground: quickInputTitleBackground,
                contrastBorder: contrastBorder,
                widgetShadow: widgetShadow
            })),
            inputBox: computeStyles(this.theme, {
                inputForeground: inputForeground,
                inputBackground: inputBackground,
                inputBorder: inputBorder,
                inputValidationInfoBackground: inputValidationInfoBackground,
                inputValidationInfoForeground: inputValidationInfoForeground,
                inputValidationInfoBorder: inputValidationInfoBorder,
                inputValidationWarningBackground: inputValidationWarningBackground,
                inputValidationWarningForeground: inputValidationWarningForeground,
                inputValidationWarningBorder: inputValidationWarningBorder,
                inputValidationErrorBackground: inputValidationErrorBackground,
                inputValidationErrorForeground: inputValidationErrorForeground,
                inputValidationErrorBorder: inputValidationErrorBorder
            }),
            countBadge: computeStyles(this.theme, {
                badgeBackground: badgeBackground,
                badgeForeground: badgeForeground,
                badgeBorder: contrastBorder
            }),
            button: computeStyles(this.theme, {
                buttonForeground: buttonForeground,
                buttonBackground: buttonBackground,
                buttonHoverBackground: buttonHoverBackground,
                buttonBorder: contrastBorder
            }),
            progressBar: computeStyles(this.theme, {
                progressBarBackground: progressBarBackground
            }),
            keybindingLabel: computeStyles(this.theme, {
                keybindingLabelBackground: keybindingLabelBackground,
                keybindingLabelForeground: keybindingLabelForeground,
                keybindingLabelBorder: keybindingLabelBorder,
                keybindingLabelBottomBorder: keybindingLabelBottomBorder,
                keybindingLabelShadow: widgetShadow
            }),
            list: computeStyles(this.theme, {
                listBackground: quickInputBackground,
                // Look like focused when inactive.
                listInactiveFocusForeground: quickInputListFocusForeground,
                listInactiveSelectionIconForeground: quickInputListFocusIconForeground,
                listInactiveFocusBackground: quickInputListFocusBackground,
                listFocusOutline: activeContrastBorder,
                listInactiveFocusOutline: activeContrastBorder,
                pickerGroupBorder: pickerGroupBorder,
                pickerGroupForeground: pickerGroupForeground
            })
        };
    }
};
QuickInputService = quickInput_decorate([
    quickInput_param(0, IInstantiationService),
    quickInput_param(1, IContextKeyService),
    quickInput_param(2, IThemeService),
    quickInput_param(3, IAccessibilityService),
    quickInput_param(4, ILayoutService)
], QuickInputService);


;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickInput/standaloneQuickInputService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var standaloneQuickInputService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var standaloneQuickInputService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};











let EditorScopedQuickInputService = class EditorScopedQuickInputService extends QuickInputService {
    constructor(editor, instantiationService, contextKeyService, themeService, accessibilityService, codeEditorService) {
        super(instantiationService, contextKeyService, themeService, accessibilityService, new EditorScopedLayoutService(editor.getContainerDomNode(), codeEditorService));
        this.host = undefined;
        // Use the passed in code editor as host for the quick input widget
        const contribution = QuickInputEditorContribution.get(editor);
        if (contribution) {
            const widget = contribution.widget;
            this.host = {
                _serviceBrand: undefined,
                get hasContainer() { return true; },
                get container() { return widget.getDomNode(); },
                get dimension() { return editor.getLayoutInfo(); },
                get onDidLayout() { return editor.onDidLayoutChange; },
                focus: () => editor.focus(),
                offset: { top: 0, quickPickTop: 0 }
            };
        }
        else {
            this.host = undefined;
        }
    }
    createController() {
        return super.createController(this.host);
    }
};
EditorScopedQuickInputService = standaloneQuickInputService_decorate([
    standaloneQuickInputService_param(1, IInstantiationService),
    standaloneQuickInputService_param(2, IContextKeyService),
    standaloneQuickInputService_param(3, IThemeService),
    standaloneQuickInputService_param(4, IAccessibilityService),
    standaloneQuickInputService_param(5, ICodeEditorService)
], EditorScopedQuickInputService);

let StandaloneQuickInputService = class StandaloneQuickInputService {
    constructor(instantiationService, codeEditorService) {
        this.instantiationService = instantiationService;
        this.codeEditorService = codeEditorService;
        this.mapEditorToService = new Map();
    }
    get activeService() {
        const editor = this.codeEditorService.getFocusedCodeEditor();
        if (!editor) {
            throw new Error('Quick input service needs a focused editor to work.');
        }
        // Find the quick input implementation for the focused
        // editor or create it lazily if not yet created
        let quickInputService = this.mapEditorToService.get(editor);
        if (!quickInputService) {
            const newQuickInputService = quickInputService = this.instantiationService.createInstance(EditorScopedQuickInputService, editor);
            this.mapEditorToService.set(editor, quickInputService);
            once(editor.onDidDispose)(() => {
                newQuickInputService.dispose();
                this.mapEditorToService.delete(editor);
            });
        }
        return quickInputService;
    }
    get quickAccess() { return this.activeService.quickAccess; }
    pick(picks, options = {}, token = CancellationToken.None) {
        return this.activeService /* TS fail */.pick(picks, options, token);
    }
    createQuickPick() {
        return this.activeService.createQuickPick();
    }
};
StandaloneQuickInputService = standaloneQuickInputService_decorate([
    standaloneQuickInputService_param(0, IInstantiationService),
    standaloneQuickInputService_param(1, ICodeEditorService)
], StandaloneQuickInputService);

class QuickInputEditorContribution {
    constructor(editor) {
        this.editor = editor;
        this.widget = new QuickInputEditorWidget(this.editor);
    }
    static get(editor) {
        return editor.getContribution(QuickInputEditorContribution.ID);
    }
    dispose() {
        this.widget.dispose();
    }
}
QuickInputEditorContribution.ID = 'editor.controller.quickInput';
class QuickInputEditorWidget {
    constructor(codeEditor) {
        this.codeEditor = codeEditor;
        this.domNode = document.createElement('div');
        this.codeEditor.addOverlayWidget(this);
    }
    getId() {
        return QuickInputEditorWidget.ID;
    }
    getDomNode() {
        return this.domNode;
    }
    getPosition() {
        return { preference: 2 /* OverlayWidgetPositionPreference.TOP_CENTER */ };
    }
    dispose() {
        this.codeEditor.removeOverlayWidget(this);
    }
}
QuickInputEditorWidget.ID = 'editor.contrib.quickInputWidget';
registerEditorContribution(QuickInputEditorContribution.ID, QuickInputEditorContribution);

;// ../../node_modules/monaco-editor/esm/vs/platform/accessibility/browser/accessibilityService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var accessibilityService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var accessibilityService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};







let AccessibilityService = class AccessibilityService extends Disposable {
    constructor(_contextKeyService, _layoutService, _configurationService) {
        super();
        this._contextKeyService = _contextKeyService;
        this._layoutService = _layoutService;
        this._configurationService = _configurationService;
        this._accessibilitySupport = 0 /* AccessibilitySupport.Unknown */;
        this._onDidChangeScreenReaderOptimized = new Emitter();
        this._onDidChangeReducedMotion = new Emitter();
        this._accessibilityModeEnabledContext = CONTEXT_ACCESSIBILITY_MODE_ENABLED.bindTo(this._contextKeyService);
        const updateContextKey = () => this._accessibilityModeEnabledContext.set(this.isScreenReaderOptimized());
        this._register(this._configurationService.onDidChangeConfiguration(e => {
            if (e.affectsConfiguration('editor.accessibilitySupport')) {
                updateContextKey();
                this._onDidChangeScreenReaderOptimized.fire();
            }
            if (e.affectsConfiguration('workbench.reduceMotion')) {
                this._configMotionReduced = this._configurationService.getValue('workbench.reduceMotion');
                this._onDidChangeReducedMotion.fire();
            }
        }));
        updateContextKey();
        this._register(this.onDidChangeScreenReaderOptimized(() => updateContextKey()));
        const reduceMotionMatcher = window.matchMedia(`(prefers-reduced-motion: reduce)`);
        this._systemMotionReduced = reduceMotionMatcher.matches;
        this._configMotionReduced = this._configurationService.getValue('workbench.reduceMotion');
        this.initReducedMotionListeners(reduceMotionMatcher);
    }
    initReducedMotionListeners(reduceMotionMatcher) {
        if (!this._layoutService.hasContainer) {
            // we can't use `ILayoutService.container` because the application
            // doesn't have a single container
            return;
        }
        this._register(addDisposableListener(reduceMotionMatcher, 'change', () => {
            this._systemMotionReduced = reduceMotionMatcher.matches;
            if (this._configMotionReduced === 'auto') {
                this._onDidChangeReducedMotion.fire();
            }
        }));
        const updateRootClasses = () => {
            const reduce = this.isMotionReduced();
            this._layoutService.container.classList.toggle('reduce-motion', reduce);
            this._layoutService.container.classList.toggle('enable-motion', !reduce);
        };
        updateRootClasses();
        this._register(this.onDidChangeReducedMotion(() => updateRootClasses()));
    }
    get onDidChangeScreenReaderOptimized() {
        return this._onDidChangeScreenReaderOptimized.event;
    }
    isScreenReaderOptimized() {
        const config = this._configurationService.getValue('editor.accessibilitySupport');
        return config === 'on' || (config === 'auto' && this._accessibilitySupport === 2 /* AccessibilitySupport.Enabled */);
    }
    get onDidChangeReducedMotion() {
        return this._onDidChangeReducedMotion.event;
    }
    isMotionReduced() {
        const config = this._configMotionReduced;
        return config === 'on' || (config === 'auto' && this._systemMotionReduced);
    }
    getAccessibilitySupport() {
        return this._accessibilitySupport;
    }
};
AccessibilityService = accessibilityService_decorate([
    accessibilityService_param(0, IContextKeyService),
    accessibilityService_param(1, ILayoutService),
    accessibilityService_param(2, IConfigurationService)
], AccessibilityService);


;// ../../node_modules/monaco-editor/esm/vs/platform/actions/common/menuService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var menuService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var menuService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};










let MenuService = class MenuService {
    constructor(_commandService, storageService) {
        this._commandService = _commandService;
        this._hiddenStates = new PersistedMenuHideState(storageService);
    }
    createMenu(id, contextKeyService, options) {
        return new menuService_Menu(id, this._hiddenStates, Object.assign({ emitEventsForSubmenuChanges: false, eventDebounceDelay: 50 }, options), this._commandService, contextKeyService, this);
    }
};
MenuService = menuService_decorate([
    menuService_param(0, ICommandService),
    menuService_param(1, IStorageService)
], MenuService);

let PersistedMenuHideState = class PersistedMenuHideState {
    constructor(_storageService) {
        this._storageService = _storageService;
        this._disposables = new DisposableStore();
        this._onDidChange = new Emitter();
        this.onDidChange = this._onDidChange.event;
        this._ignoreChangeEvent = false;
        try {
            const raw = _storageService.get(PersistedMenuHideState._key, 0 /* StorageScope.PROFILE */, '{}');
            this._data = JSON.parse(raw);
        }
        catch (err) {
            this._data = Object.create(null);
        }
        this._disposables.add(_storageService.onDidChangeValue(e => {
            if (e.key !== PersistedMenuHideState._key) {
                return;
            }
            if (!this._ignoreChangeEvent) {
                try {
                    const raw = _storageService.get(PersistedMenuHideState._key, 0 /* StorageScope.PROFILE */, '{}');
                    this._data = JSON.parse(raw);
                }
                catch (err) {
                    console.log('FAILED to read storage after UPDATE', err);
                }
            }
            this._onDidChange.fire();
        }));
    }
    dispose() {
        this._onDidChange.dispose();
        this._disposables.dispose();
    }
    isHidden(menu, commandId) {
        var _a, _b;
        return (_b = (_a = this._data[menu.id]) === null || _a === void 0 ? void 0 : _a.includes(commandId)) !== null && _b !== void 0 ? _b : false;
    }
    updateHidden(menu, commandId, hidden) {
        const entries = this._data[menu.id];
        if (!hidden) {
            // remove and cleanup
            if (entries) {
                const idx = entries.indexOf(commandId);
                if (idx >= 0) {
                    removeFastWithoutKeepingOrder(entries, idx);
                }
                if (entries.length === 0) {
                    delete this._data[menu.id];
                }
            }
        }
        else {
            // add unless already added
            if (!entries) {
                this._data[menu.id] = [commandId];
            }
            else {
                const idx = entries.indexOf(commandId);
                if (idx < 0) {
                    entries.push(commandId);
                }
            }
        }
        this._persist();
    }
    _persist() {
        try {
            this._ignoreChangeEvent = true;
            const raw = JSON.stringify(this._data);
            this._storageService.store(PersistedMenuHideState._key, raw, 0 /* StorageScope.PROFILE */, 0 /* StorageTarget.USER */);
        }
        finally {
            this._ignoreChangeEvent = false;
        }
    }
};
PersistedMenuHideState._key = 'menu.hiddenCommands';
PersistedMenuHideState = menuService_decorate([
    menuService_param(0, IStorageService)
], PersistedMenuHideState);
let menuService_Menu = class Menu {
    constructor(_id, _hiddenStates, _options, _commandService, _contextKeyService, _menuService) {
        this._id = _id;
        this._hiddenStates = _hiddenStates;
        this._options = _options;
        this._commandService = _commandService;
        this._contextKeyService = _contextKeyService;
        this._menuService = _menuService;
        this._disposables = new DisposableStore();
        this._menuGroups = [];
        this._contextKeys = new Set();
        this._build();
        // Rebuild this menu whenever the menu registry reports an event for this MenuId.
        // This usually happen while code and extensions are loaded and affects the over
        // structure of the menu
        const rebuildMenuSoon = new RunOnceScheduler(() => {
            this._build();
            this._onDidChange.fire(this);
        }, _options.eventDebounceDelay);
        this._disposables.add(rebuildMenuSoon);
        this._disposables.add(MenuRegistry.onDidChangeMenu(e => {
            if (e.has(_id)) {
                rebuildMenuSoon.schedule();
            }
        }));
        // When context keys or storage state changes we need to check if the menu also has changed. However,
        // we only do that when someone listens on this menu because (1) these events are
        // firing often and (2) menu are often leaked
        const lazyListener = this._disposables.add(new DisposableStore());
        const startLazyListener = () => {
            const fireChangeSoon = new RunOnceScheduler(() => this._onDidChange.fire(this), _options.eventDebounceDelay);
            lazyListener.add(fireChangeSoon);
            lazyListener.add(_contextKeyService.onDidChangeContext(e => {
                if (e.affectsSome(this._contextKeys)) {
                    fireChangeSoon.schedule();
                }
            }));
            lazyListener.add(_hiddenStates.onDidChange(() => {
                fireChangeSoon.schedule();
            }));
        };
        this._onDidChange = new Emitter({
            // start/stop context key listener
            onFirstListenerAdd: startLazyListener,
            onLastListenerRemove: lazyListener.clear.bind(lazyListener)
        });
        this.onDidChange = this._onDidChange.event;
    }
    dispose() {
        this._disposables.dispose();
        this._onDidChange.dispose();
    }
    _build() {
        // reset
        this._menuGroups.length = 0;
        this._contextKeys.clear();
        const menuItems = MenuRegistry.getMenuItems(this._id);
        let group;
        menuItems.sort(Menu._compareMenuItems);
        for (const item of menuItems) {
            // group by groupId
            const groupName = item.group || '';
            if (!group || group[0] !== groupName) {
                group = [groupName, []];
                this._menuGroups.push(group);
            }
            group[1].push(item);
            // keep keys for eventing
            this._collectContextKeys(item);
        }
    }
    _collectContextKeys(item) {
        Menu._fillInKbExprKeys(item.when, this._contextKeys);
        if (isIMenuItem(item)) {
            // keep precondition keys for event if applicable
            if (item.command.precondition) {
                Menu._fillInKbExprKeys(item.command.precondition, this._contextKeys);
            }
            // keep toggled keys for event if applicable
            if (item.command.toggled) {
                const toggledExpression = item.command.toggled.condition || item.command.toggled;
                Menu._fillInKbExprKeys(toggledExpression, this._contextKeys);
            }
        }
        else if (this._options.emitEventsForSubmenuChanges) {
            // recursively collect context keys from submenus so that this
            // menu fires events when context key changes affect submenus
            MenuRegistry.getMenuItems(item.submenu).forEach(this._collectContextKeys, this);
        }
    }
    getActions(options) {
        const result = [];
        const allToggleActions = [];
        for (const group of this._menuGroups) {
            const [id, items] = group;
            const toggleActions = [];
            const activeActions = [];
            for (const item of items) {
                if (this._contextKeyService.contextMatchesRules(item.when)) {
                    let action;
                    const isMenuItem = isIMenuItem(item);
                    if (isMenuItem) {
                        const menuHide = createMenuHide(this._id, item.command, this._hiddenStates);
                        action = new MenuItemAction(item.command, item.alt, options, menuHide, this._contextKeyService, this._commandService);
                    }
                    else {
                        action = new SubmenuItemAction(item, this._menuService, this._contextKeyService, options);
                        if (action.actions.length === 0) {
                            action.dispose();
                            action = undefined;
                        }
                    }
                    if (action) {
                        activeActions.push(action);
                    }
                }
            }
            if (activeActions.length > 0) {
                result.push([id, activeActions]);
            }
            if (toggleActions.length > 0) {
                allToggleActions.push(toggleActions);
            }
        }
        return result;
    }
    static _fillInKbExprKeys(exp, set) {
        if (exp) {
            for (const key of exp.keys()) {
                set.add(key);
            }
        }
    }
    static _compareMenuItems(a, b) {
        const aGroup = a.group;
        const bGroup = b.group;
        if (aGroup !== bGroup) {
            // Falsy groups come last
            if (!aGroup) {
                return 1;
            }
            else if (!bGroup) {
                return -1;
            }
            // 'navigation' group comes first
            if (aGroup === 'navigation') {
                return -1;
            }
            else if (bGroup === 'navigation') {
                return 1;
            }
            // lexical sort for groups
            const value = aGroup.localeCompare(bGroup);
            if (value !== 0) {
                return value;
            }
        }
        // sort on priority - default is 0
        const aPrio = a.order || 0;
        const bPrio = b.order || 0;
        if (aPrio < bPrio) {
            return -1;
        }
        else if (aPrio > bPrio) {
            return 1;
        }
        // sort on titles
        return Menu._compareTitles(isIMenuItem(a) ? a.command.title : a.title, isIMenuItem(b) ? b.command.title : b.title);
    }
    static _compareTitles(a, b) {
        const aStr = typeof a === 'string' ? a : a.original;
        const bStr = typeof b === 'string' ? b : b.original;
        return aStr.localeCompare(bStr);
    }
};
menuService_Menu = menuService_decorate([
    menuService_param(3, ICommandService),
    menuService_param(4, IContextKeyService),
    menuService_param(5, IMenuService)
], menuService_Menu);
function createMenuHide(menu, command, states) {
    const id = `${menu.id}/${command.id}`;
    const title = typeof command.title === 'string' ? command.title : command.title.value;
    const hide = toAction({
        id,
        label: localize('hide.label', 'Hide \'{0}\'', title),
        run() { states.updateHidden(menu, command.id, true); }
    });
    const toggle = toAction({
        id,
        label: title,
        get checked() { return !states.isHidden(menu, command.id); },
        run() {
            const newValue = !states.isHidden(menu, command.id);
            states.updateHidden(menu, command.id, newValue);
        }
    });
    return {
        hide,
        toggle,
        get isHidden() { return !toggle.checked; },
    };
}

;// ../../node_modules/monaco-editor/esm/vs/platform/clipboard/browser/clipboardService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var clipboardService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var clipboardService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var clipboardService_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};






let BrowserClipboardService = class BrowserClipboardService extends Disposable {
    constructor(layoutService, logService) {
        super();
        this.layoutService = layoutService;
        this.logService = logService;
        this.mapTextToType = new Map(); // unsupported in web (only in-memory)
        this.findText = ''; // unsupported in web (only in-memory)
        this.resources = [];
        if (browser_isSafari || isWebkitWebView) {
            this.installWebKitWriteTextWorkaround();
        }
    }
    // 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.
    installWebKitWriteTextWorkaround() {
        const handler = () => {
            const currentWritePromise = new DeferredPromise();
            // Cancel the previous promise since we just created a new one in response to this new event
            if (this.webKitPendingClipboardWritePromise && !this.webKitPendingClipboardWritePromise.isSettled) {
                this.webKitPendingClipboardWritePromise.cancel();
            }
            this.webKitPendingClipboardWritePromise = currentWritePromise;
            // The ctor of ClipboardItem allows you to pass in a promise that will resolve to a string.
            // This allows us to pass in a Promise that will either be cancelled by another event or
            // resolved with the contents of the first call to this.writeText.
            // see https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem/ClipboardItem#parameters
            navigator.clipboard.write([new ClipboardItem({
                    'text/plain': currentWritePromise.p,
                })]).catch((err) => clipboardService_awaiter(this, void 0, void 0, function* () {
                if (!(err instanceof Error) || err.name !== 'NotAllowedError' || !currentWritePromise.isRejected) {
                    this.logService.error(err);
                }
            }));
        };
        if (this.layoutService.hasContainer) {
            this._register(addDisposableListener(this.layoutService.container, 'click', handler));
            this._register(addDisposableListener(this.layoutService.container, 'keydown', handler));
        }
    }
    writeText(text, type) {
        return clipboardService_awaiter(this, void 0, void 0, function* () {
            // With type: only in-memory is supported
            if (type) {
                this.mapTextToType.set(type, text);
                return;
            }
            if (this.webKitPendingClipboardWritePromise) {
                // For Safari, we complete this Promise which allows the call to `navigator.clipboard.write()`
                // above to resolve and successfully copy to the clipboard. If we let this continue, Safari
                // would throw an error because this call stack doesn't appear to originate from a user gesture.
                return this.webKitPendingClipboardWritePromise.complete(text);
            }
            // Guard access to navigator.clipboard with try/catch
            // as we have seen DOMExceptions in certain browsers
            // due to security policies.
            try {
                return yield navigator.clipboard.writeText(text);
            }
            catch (error) {
                console.error(error);
            }
            // Fallback to textarea and execCommand solution
            const activeElement = document.activeElement;
            const textArea = document.body.appendChild(dom_$('textarea', { 'aria-hidden': true }));
            textArea.style.height = '1px';
            textArea.style.width = '1px';
            textArea.style.position = 'absolute';
            textArea.value = text;
            textArea.focus();
            textArea.select();
            document.execCommand('copy');
            if (activeElement instanceof HTMLElement) {
                activeElement.focus();
            }
            document.body.removeChild(textArea);
            return;
        });
    }
    readText(type) {
        return clipboardService_awaiter(this, void 0, void 0, function* () {
            // With type: only in-memory is supported
            if (type) {
                return this.mapTextToType.get(type) || '';
            }
            // Guard access to navigator.clipboard with try/catch
            // as we have seen DOMExceptions in certain browsers
            // due to security policies.
            try {
                return yield navigator.clipboard.readText();
            }
            catch (error) {
                console.error(error);
                return '';
            }
        });
    }
    readFindText() {
        return clipboardService_awaiter(this, void 0, void 0, function* () {
            return this.findText;
        });
    }
    writeFindText(text) {
        return clipboardService_awaiter(this, void 0, void 0, function* () {
            this.findText = text;
        });
    }
    readResources() {
        return clipboardService_awaiter(this, void 0, void 0, function* () {
            return this.resources;
        });
    }
};
BrowserClipboardService = clipboardService_decorate([
    clipboardService_param(0, ILayoutService),
    clipboardService_param(1, ILogService)
], BrowserClipboardService);


;// ../../node_modules/monaco-editor/esm/vs/platform/contextkey/browser/contextKeyService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var contextKeyService_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var contextKeyService_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};










const KEYBINDING_CONTEXT_ATTR = 'data-keybinding-context';
class contextKeyService_Context {
    constructor(id, parent) {
        this._id = id;
        this._parent = parent;
        this._value = Object.create(null);
        this._value['_contextId'] = id;
    }
    get value() {
        return Object.assign({}, this._value);
    }
    setValue(key, value) {
        // console.log('SET ' + key + ' = ' + value + ' ON ' + this._id);
        if (this._value[key] !== value) {
            this._value[key] = value;
            return true;
        }
        return false;
    }
    removeValue(key) {
        // console.log('REMOVE ' + key + ' FROM ' + this._id);
        if (key in this._value) {
            delete this._value[key];
            return true;
        }
        return false;
    }
    getValue(key) {
        const ret = this._value[key];
        if (typeof ret === 'undefined' && this._parent) {
            return this._parent.getValue(key);
        }
        return ret;
    }
}
class NullContext extends contextKeyService_Context {
    constructor() {
        super(-1, null);
    }
    setValue(key, value) {
        return false;
    }
    removeValue(key) {
        return false;
    }
    getValue(key) {
        return undefined;
    }
}
NullContext.INSTANCE = new NullContext();
class ConfigAwareContextValuesContainer extends contextKeyService_Context {
    constructor(id, _configurationService, emitter) {
        super(id, null);
        this._configurationService = _configurationService;
        this._values = map_TernarySearchTree.forConfigKeys();
        this._listener = this._configurationService.onDidChangeConfiguration(event => {
            if (event.source === 7 /* ConfigurationTarget.DEFAULT */) {
                // new setting, reset everything
                const allKeys = Array.from(Iterable.map(this._values, ([k]) => k));
                this._values.clear();
                emitter.fire(new ArrayContextKeyChangeEvent(allKeys));
            }
            else {
                const changedKeys = [];
                for (const configKey of event.affectedKeys) {
                    const contextKey = `config.${configKey}`;
                    const cachedItems = this._values.findSuperstr(contextKey);
                    if (cachedItems !== undefined) {
                        changedKeys.push(...Iterable.map(cachedItems, ([key]) => key));
                        this._values.deleteSuperstr(contextKey);
                    }
                    if (this._values.has(contextKey)) {
                        changedKeys.push(contextKey);
                        this._values.delete(contextKey);
                    }
                }
                emitter.fire(new ArrayContextKeyChangeEvent(changedKeys));
            }
        });
    }
    dispose() {
        this._listener.dispose();
    }
    getValue(key) {
        if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) {
            return super.getValue(key);
        }
        if (this._values.has(key)) {
            return this._values.get(key);
        }
        const configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length);
        const configValue = this._configurationService.getValue(configKey);
        let value = undefined;
        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._values.set(key, value);
        return value;
    }
    setValue(key, value) {
        return super.setValue(key, value);
    }
    removeValue(key) {
        return super.removeValue(key);
    }
}
ConfigAwareContextValuesContainer._keyPrefix = 'config.';
class ContextKey {
    constructor(service, key, defaultValue) {
        this._service = service;
        this._key = key;
        this._defaultValue = defaultValue;
        this.reset();
    }
    set(value) {
        this._service.setContext(this._key, value);
    }
    reset() {
        if (typeof this._defaultValue === 'undefined') {
            this._service.removeContext(this._key);
        }
        else {
            this._service.setContext(this._key, this._defaultValue);
        }
    }
    get() {
        return this._service.getContextKeyValue(this._key);
    }
}
class SimpleContextKeyChangeEvent {
    constructor(key) {
        this.key = key;
    }
    affectsSome(keys) {
        return keys.has(this.key);
    }
    allKeysContainedIn(keys) {
        return this.affectsSome(keys);
    }
}
class ArrayContextKeyChangeEvent {
    constructor(keys) {
        this.keys = keys;
    }
    affectsSome(keys) {
        for (const key of this.keys) {
            if (keys.has(key)) {
                return true;
            }
        }
        return false;
    }
    allKeysContainedIn(keys) {
        return this.keys.every(key => keys.has(key));
    }
}
class CompositeContextKeyChangeEvent {
    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)));
}
class AbstractContextKeyService {
    constructor(myContextId) {
        this._onDidChangeContext = new PauseableEmitter({ merge: input => new CompositeContextKeyChangeEvent(input) });
        this.onDidChangeContext = this._onDidChangeContext.event;
        this._isDisposed = false;
        this._myContextId = myContextId;
    }
    createKey(key, defaultValue) {
        if (this._isDisposed) {
            throw new Error(`AbstractContextKeyService has been disposed`);
        }
        return new ContextKey(this, key, defaultValue);
    }
    bufferChangeEvents(callback) {
        this._onDidChangeContext.pause();
        try {
            callback();
        }
        finally {
            this._onDidChangeContext.resume();
        }
    }
    createScoped(domNode) {
        if (this._isDisposed) {
            throw new Error(`AbstractContextKeyService has been disposed`);
        }
        return new ScopedContextKeyService(this, domNode);
    }
    contextMatchesRules(rules) {
        if (this._isDisposed) {
            throw new Error(`AbstractContextKeyService has been disposed`);
        }
        const context = this.getContextValuesContainer(this._myContextId);
        const result = (rules ? rules.evaluate(context) : true);
        // console.group(rules.serialize() + ' -> ' + result);
        // rules.keys().forEach(key => { console.log(key, ctx[key]); });
        // console.groupEnd();
        return result;
    }
    getContextKeyValue(key) {
        if (this._isDisposed) {
            return undefined;
        }
        return this.getContextValuesContainer(this._myContextId).getValue(key);
    }
    setContext(key, value) {
        if (this._isDisposed) {
            return;
        }
        const myContext = this.getContextValuesContainer(this._myContextId);
        if (!myContext) {
            return;
        }
        if (myContext.setValue(key, value)) {
            this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
        }
    }
    removeContext(key) {
        if (this._isDisposed) {
            return;
        }
        if (this.getContextValuesContainer(this._myContextId).removeValue(key)) {
            this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
        }
    }
    getContext(target) {
        if (this._isDisposed) {
            return NullContext.INSTANCE;
        }
        return this.getContextValuesContainer(findContextAttr(target));
    }
}
let ContextKeyService = class ContextKeyService extends AbstractContextKeyService {
    constructor(configurationService) {
        super(0);
        this._contexts = new Map();
        this._toDispose = new DisposableStore();
        this._lastContextId = 0;
        const myContext = new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext);
        this._contexts.set(this._myContextId, myContext);
        this._toDispose.add(myContext);
        // Uncomment this to see the contexts continuously logged
        // let lastLoggedValue: string | null = null;
        // setInterval(() => {
        // 	let values = Object.keys(this._contexts).map((key) => this._contexts[key]);
        // 	let logValue = values.map(v => JSON.stringify(v._value, null, '\t')).join('\n');
        // 	if (lastLoggedValue !== logValue) {
        // 		lastLoggedValue = logValue;
        // 		console.log(lastLoggedValue);
        // 	}
        // }, 2000);
    }
    dispose() {
        this._onDidChangeContext.dispose();
        this._isDisposed = true;
        this._toDispose.dispose();
    }
    getContextValuesContainer(contextId) {
        if (this._isDisposed) {
            return NullContext.INSTANCE;
        }
        return this._contexts.get(contextId) || NullContext.INSTANCE;
    }
    createChildContext(parentContextId = this._myContextId) {
        if (this._isDisposed) {
            throw new Error(`ContextKeyService has been disposed`);
        }
        const id = (++this._lastContextId);
        this._contexts.set(id, new contextKeyService_Context(id, this.getContextValuesContainer(parentContextId)));
        return id;
    }
    disposeContext(contextId) {
        if (!this._isDisposed) {
            this._contexts.delete(contextId);
        }
    }
};
ContextKeyService = contextKeyService_decorate([
    contextKeyService_param(0, IConfigurationService)
], ContextKeyService);

class ScopedContextKeyService extends AbstractContextKeyService {
    constructor(parent, domNode) {
        super(parent.createChildContext());
        this._parentChangeListener = new MutableDisposable();
        this._parent = parent;
        this._updateParentChangeListener();
        this._domNode = domNode;
        if (this._domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
            let extraInfo = '';
            if (this._domNode.classList) {
                extraInfo = Array.from(this._domNode.classList.values()).join(', ');
            }
            console.error(`Element already has context attribute${extraInfo ? ': ' + extraInfo : ''}`);
        }
        this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId));
    }
    _updateParentChangeListener() {
        // Forward parent events to this listener. Parent will change.
        this._parentChangeListener.value = this._parent.onDidChangeContext(e => {
            const thisContainer = this._parent.getContextValuesContainer(this._myContextId);
            const thisContextValues = thisContainer.value;
            if (!allEventKeysInContext(e, thisContextValues)) {
                this._onDidChangeContext.fire(e);
            }
        });
    }
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._onDidChangeContext.dispose();
        this._parent.disposeContext(this._myContextId);
        this._parentChangeListener.dispose();
        this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR);
        this._isDisposed = true;
    }
    getContextValuesContainer(contextId) {
        if (this._isDisposed) {
            return NullContext.INSTANCE;
        }
        return this._parent.getContextValuesContainer(contextId);
    }
    createChildContext(parentContextId = this._myContextId) {
        if (this._isDisposed) {
            throw new Error(`ScopedContextKeyService has been disposed`);
        }
        return this._parent.createChildContext(parentContextId);
    }
    disposeContext(contextId) {
        if (this._isDisposed) {
            return;
        }
        this._parent.disposeContext(contextId);
    }
}
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 setContext(accessor, contextKey, contextValue) {
    accessor.get(IContextKeyService).createKey(String(contextKey), stringifyURIs(contextValue));
}
function stringifyURIs(contextValue) {
    return cloneAndChange(contextValue, (obj) => {
        if (typeof obj === 'object' && obj.$mid === 1 /* MarshalledId.Uri */) {
            return URI.revive(obj).toString();
        }
        if (obj instanceof URI) {
            return obj.toString();
        }
        return undefined;
    });
}
CommandsRegistry.registerCommand(SET_CONTEXT_COMMAND_ID, setContext);
CommandsRegistry.registerCommand({
    id: 'getContextKeyInfo',
    handler() {
        return [...RawContextKey.all()].sort((a, b) => a.key.localeCompare(b.key));
    },
    description: {
        description: localize('getContextKeyInfo', "A command that returns information about context keys"),
        args: []
    }
});
CommandsRegistry.registerCommand('_generateContextKeyInfo', function () {
    const result = [];
    const seen = new Set();
    for (const info of RawContextKey.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, undefined, 2));
});

;// ../../node_modules/monaco-editor/esm/vs/platform/instantiation/common/graph.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
class graph_Node {
    constructor(data) {
        this.incoming = new Map();
        this.outgoing = new Map();
        this.data = data;
    }
}
class Graph {
    constructor(_hashFn) {
        this._hashFn = _hashFn;
        this._nodes = new Map();
        // empty
    }
    roots() {
        const ret = [];
        for (const node of this._nodes.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(this._hashFn(to), toNode);
        toNode.incoming.set(this._hashFn(from), fromNode);
    }
    removeNode(data) {
        const key = this._hashFn(data);
        this._nodes.delete(key);
        for (const node of this._nodes.values()) {
            node.outgoing.delete(key);
            node.incoming.delete(key);
        }
    }
    lookupOrInsertNode(data) {
        const key = this._hashFn(data);
        let node = this._nodes.get(key);
        if (!node) {
            node = new graph_Node(data);
            this._nodes.set(key, node);
        }
        return node;
    }
    isEmpty() {
        return this._nodes.size === 0;
    }
    toString() {
        const data = [];
        for (const [key, value] of this._nodes) {
            data.push(`${key}, (incoming)[${[...value.incoming.keys()].join(', ')}], (outgoing)[${[...value.outgoing.keys()].join(',')}]`);
        }
        return data.join('\n');
    }
    /**
     * This is brute force and slow and **only** be used
     * to trouble shoot.
     */
    findCycleSlow() {
        for (const [id, node] of this._nodes) {
            const seen = new Set([id]);
            const res = this._findCycle(node, seen);
            if (res) {
                return res;
            }
        }
        return undefined;
    }
    _findCycle(node, seen) {
        for (const [id, outgoing] of node.outgoing) {
            if (seen.has(id)) {
                return [...seen, id].join(' -> ');
            }
            seen.add(id);
            const value = this._findCycle(outgoing, seen);
            if (value) {
                return value;
            }
            seen.delete(id);
        }
        return undefined;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/platform/instantiation/common/instantiationService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/






// TRACING
const _enableTracing = false;
class CyclicDependencyError extends Error {
    constructor(graph) {
        var _a;
        super('cyclic dependency between services');
        this.message = (_a = graph.findCycleSlow()) !== null && _a !== void 0 ? _a : `UNABLE to detect cycle, dumping graph: \n${graph.toString()}`;
    }
}
class InstantiationService {
    constructor(services = new ServiceCollection(), strict = false, parent) {
        this._activeInstantiations = new Set();
        this._services = services;
        this._strict = strict;
        this._parent = parent;
        this._services.set(IInstantiationService, this);
    }
    createChild(services) {
        return new InstantiationService(services, this._strict, this);
    }
    invokeFunction(fn, ...args) {
        const _trace = Trace.traceInvocation(fn);
        let _done = false;
        try {
            const accessor = {
                get: (id) => {
                    if (_done) {
                        throw illegalState('service accessor is only valid during the invocation of its target method');
                    }
                    const result = this._getOrCreateServiceInstance(id, _trace);
                    if (!result) {
                        throw new Error(`[invokeFunction] unknown service '${id}'`);
                    }
                    return result;
                }
            };
            return fn(accessor, ...args);
        }
        finally {
            _done = true;
            _trace.stop();
        }
    }
    createInstance(ctorOrDescriptor, ...rest) {
        let _trace;
        let result;
        if (ctorOrDescriptor instanceof SyncDescriptor) {
            _trace = Trace.traceCreation(ctorOrDescriptor.ctor);
            result = this._createInstance(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
        }
        else {
            _trace = Trace.traceCreation(ctorOrDescriptor);
            result = this._createInstance(ctorOrDescriptor, rest, _trace);
        }
        _trace.stop();
        return result;
    }
    _createInstance(ctor, args = [], _trace) {
        // arguments defined by service decorators
        const serviceDependencies = _util.getServiceDependencies(ctor).sort((a, b) => a.index - b.index);
        const serviceArgs = [];
        for (const dependency of serviceDependencies) {
            const service = this._getOrCreateServiceInstance(dependency.id, _trace);
            if (!service) {
                this._throwIfStrict(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`, false);
            }
            serviceArgs.push(service);
        }
        const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
        // check for argument mismatches, adjust static args if needed
        if (args.length !== firstServiceArgPos) {
            console.trace(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);
            const delta = firstServiceArgPos - args.length;
            if (delta > 0) {
                args = args.concat(new Array(delta));
            }
            else {
                args = args.slice(0, firstServiceArgPos);
            }
        }
        // now create the instance
        return new ctor(...[...args, ...serviceArgs]);
    }
    _setServiceInstance(id, instance) {
        if (this._services.get(id) instanceof SyncDescriptor) {
            this._services.set(id, instance);
        }
        else if (this._parent) {
            this._parent._setServiceInstance(id, instance);
        }
        else {
            throw new Error('illegalState - setting UNKNOWN service instance');
        }
    }
    _getServiceInstanceOrDescriptor(id) {
        const instanceOrDesc = this._services.get(id);
        if (!instanceOrDesc && this._parent) {
            return this._parent._getServiceInstanceOrDescriptor(id);
        }
        else {
            return instanceOrDesc;
        }
    }
    _getOrCreateServiceInstance(id, _trace) {
        const thing = this._getServiceInstanceOrDescriptor(id);
        if (thing instanceof SyncDescriptor) {
            return this._safeCreateAndCacheServiceInstance(id, thing, _trace.branch(id, true));
        }
        else {
            _trace.branch(id, false);
            return thing;
        }
    }
    _safeCreateAndCacheServiceInstance(id, desc, _trace) {
        if (this._activeInstantiations.has(id)) {
            throw new Error(`illegal state - RECURSIVELY instantiating service '${id}'`);
        }
        this._activeInstantiations.add(id);
        try {
            return this._createAndCacheServiceInstance(id, desc, _trace);
        }
        finally {
            this._activeInstantiations.delete(id);
        }
    }
    _createAndCacheServiceInstance(id, desc, _trace) {
        const graph = new Graph(data => data.id.toString());
        let cycleCount = 0;
        const stack = [{ id, desc, _trace }];
        while (stack.length) {
            const item = stack.pop();
            graph.lookupOrInsertNode(item);
            // a weak but working heuristic for cycle checks
            if (cycleCount++ > 1000) {
                throw new CyclicDependencyError(graph);
            }
            // check all dependencies for existence and if they need to be created first
            for (const dependency of _util.getServiceDependencies(item.desc.ctor)) {
                const instanceOrDesc = this._getServiceInstanceOrDescriptor(dependency.id);
                if (!instanceOrDesc) {
                    this._throwIfStrict(`[createInstance] ${id} depends on ${dependency.id} which is NOT registered.`, true);
                }
                if (instanceOrDesc instanceof SyncDescriptor) {
                    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 there is no more roots but still
            // nodes in the graph we have a cycle
            if (roots.length === 0) {
                if (!graph.isEmpty()) {
                    throw new CyclicDependencyError(graph);
                }
                break;
            }
            for (const { data } of roots) {
                // Repeat the check for this still being a service sync descriptor. That's because
                // instantiating a dependency might have side-effect and recursively trigger instantiation
                // so that some dependencies are now fullfilled already.
                const instanceOrDesc = this._getServiceInstanceOrDescriptor(data.id);
                if (instanceOrDesc instanceof SyncDescriptor) {
                    // create instance and overwrite the service collections
                    const instance = this._createServiceInstanceWithOwner(data.id, data.desc.ctor, data.desc.staticArguments, data.desc.supportsDelayedInstantiation, data._trace);
                    this._setServiceInstance(data.id, instance);
                }
                graph.removeNode(data);
            }
        }
        return this._getServiceInstanceOrDescriptor(id);
    }
    _createServiceInstanceWithOwner(id, ctor, args = [], supportsDelayedInstantiation, _trace) {
        if (this._services.get(id) instanceof SyncDescriptor) {
            return this._createServiceInstance(ctor, args, supportsDelayedInstantiation, _trace);
        }
        else if (this._parent) {
            return this._parent._createServiceInstanceWithOwner(id, ctor, args, supportsDelayedInstantiation, _trace);
        }
        else {
            throw new Error(`illegalState - creating UNKNOWN service instance ${ctor.name}`);
        }
    }
    _createServiceInstance(ctor, args = [], _supportsDelayedInstantiation, _trace) {
        if (!_supportsDelayedInstantiation) {
            // eager instantiation
            return this._createInstance(ctor, args, _trace);
        }
        else {
            // Return a proxy object that's backed by an idle value. That
            // strategy is to instantiate services in our idle time or when actually
            // needed but not when injected into a consumer
            const idle = new IdleValue(() => this._createInstance(ctor, args, _trace));
            return new Proxy(Object.create(null), {
                get(target, key) {
                    if (key in target) {
                        return target[key];
                    }
                    const obj = idle.value;
                    let prop = obj[key];
                    if (typeof prop !== 'function') {
                        return prop;
                    }
                    prop = prop.bind(obj);
                    target[key] = prop;
                    return prop;
                },
                set(_target, p, value) {
                    idle.value[p] = value;
                    return true;
                }
            });
        }
    }
    _throwIfStrict(msg, printWarning) {
        if (printWarning) {
            console.warn(msg);
        }
        if (this._strict) {
            throw new Error(msg);
        }
    }
}
class Trace {
    constructor(type, name) {
        this.type = type;
        this.name = name;
        this._start = Date.now();
        this._dep = [];
    }
    static traceInvocation(ctor) {
        return !_enableTracing ? Trace._None : new Trace(1 /* TraceType.Invocation */, ctor.name || ctor.toString().substring(0, 42).replace(/\n/g, ''));
    }
    static traceCreation(ctor) {
        return !_enableTracing ? Trace._None : new Trace(0 /* TraceType.Creation */, ctor.name);
    }
    branch(id, first) {
        const child = new Trace(2 /* TraceType.Branch */, id.toString());
        this._dep.push([id, first, child]);
        return child;
    }
    stop() {
        const dur = Date.now() - this._start;
        Trace._totals += dur;
        let causedCreation = false;
        function printChild(n, trace) {
            const res = [];
            const prefix = new Array(n + 1).join('\t');
            for (const [id, first, child] of trace._dep) {
                if (first && child) {
                    causedCreation = true;
                    res.push(`${prefix}CREATES -> ${id}`);
                    const nested = printChild(n + 1, child);
                    if (nested) {
                        res.push(nested);
                    }
                }
                else {
                    res.push(`${prefix}uses -> ${id}`);
                }
            }
            return res.join('\n');
        }
        const lines = [
            `${this.type === 0 /* TraceType.Creation */ ? 'CREATE' : 'CALL'} ${this.name}`,
            `${printChild(1, this)}`,
            `DONE, took ${dur.toFixed(2)}ms (grand total ${Trace._totals.toFixed(2)}ms)`
        ];
        if (dur > 2 || causedCreation) {
            console.log(lines.join('\n'));
        }
    }
}
Trace._None = new class extends Trace {
    constructor() { super(-1, null); }
    stop() { }
    branch() { return this; }
};
Trace._totals = 0;
//#endregion

;// ../../node_modules/monaco-editor/esm/vs/platform/markers/common/markerService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/







class DoubleResourceMap {
    constructor() {
        this._byResource = new ResourceMap();
        this._byOwner = new Map();
    }
    set(resource, owner, value) {
        let ownerMap = this._byResource.get(resource);
        if (!ownerMap) {
            ownerMap = new Map();
            this._byResource.set(resource, ownerMap);
        }
        ownerMap.set(owner, value);
        let resourceMap = this._byOwner.get(owner);
        if (!resourceMap) {
            resourceMap = new ResourceMap();
            this._byOwner.set(owner, resourceMap);
        }
        resourceMap.set(resource, value);
    }
    get(resource, owner) {
        const ownerMap = this._byResource.get(resource);
        return ownerMap === null || ownerMap === void 0 ? void 0 : ownerMap.get(owner);
    }
    delete(resource, owner) {
        let removedA = false;
        let removedB = false;
        const ownerMap = this._byResource.get(resource);
        if (ownerMap) {
            removedA = ownerMap.delete(owner);
        }
        const resourceMap = this._byOwner.get(owner);
        if (resourceMap) {
            removedB = resourceMap.delete(resource);
        }
        if (removedA !== removedB) {
            throw new Error('illegal state');
        }
        return removedA && removedB;
    }
    values(key) {
        var _a, _b, _c, _d;
        if (typeof key === 'string') {
            return (_b = (_a = this._byOwner.get(key)) === null || _a === void 0 ? void 0 : _a.values()) !== null && _b !== void 0 ? _b : Iterable.empty();
        }
        if (URI.isUri(key)) {
            return (_d = (_c = this._byResource.get(key)) === null || _c === void 0 ? void 0 : _c.values()) !== null && _d !== void 0 ? _d : Iterable.empty();
        }
        return Iterable.map(Iterable.concat(...this._byOwner.values()), map => map[1]);
    }
}
class MarkerStats {
    constructor(service) {
        this.errors = 0;
        this.infos = 0;
        this.warnings = 0;
        this.unknowns = 0;
        this._data = new ResourceMap();
        this._service = service;
        this._subscription = service.onMarkerChanged(this._update, this);
    }
    dispose() {
        this._subscription.dispose();
    }
    _update(resources) {
        for (const resource of resources) {
            const oldStats = this._data.get(resource);
            if (oldStats) {
                this._substract(oldStats);
            }
            const newStats = this._resourceStats(resource);
            this._add(newStats);
            this._data.set(resource, newStats);
        }
    }
    _resourceStats(resource) {
        const result = { errors: 0, warnings: 0, infos: 0, unknowns: 0 };
        // TODO this is a hack
        if (resource.scheme === Schemas.inMemory || resource.scheme === Schemas.walkThrough || resource.scheme === Schemas.walkThroughSnippet || resource.scheme === Schemas.vscodeSourceControl) {
            return result;
        }
        for (const { severity } of this._service.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;
    }
    _substract(op) {
        this.errors -= op.errors;
        this.warnings -= op.warnings;
        this.infos -= op.infos;
        this.unknowns -= op.unknowns;
    }
    _add(op) {
        this.errors += op.errors;
        this.warnings += op.warnings;
        this.infos += op.infos;
        this.unknowns += op.unknowns;
    }
}
class MarkerService {
    constructor() {
        this._onMarkerChanged = new DebounceEmitter({
            delay: 0,
            merge: MarkerService._merge
        });
        this.onMarkerChanged = this._onMarkerChanged.event;
        this._data = new DoubleResourceMap();
        this._stats = new MarkerStats(this);
    }
    dispose() {
        this._stats.dispose();
        this._onMarkerChanged.dispose();
    }
    remove(owner, resources) {
        for (const resource of resources || []) {
            this.changeOne(owner, resource, []);
        }
    }
    changeOne(owner, resource, markerData) {
        if (isFalsyOrEmpty(markerData)) {
            // remove marker for this (owner,resource)-tuple
            const removed = this._data.delete(resource, owner);
            if (removed) {
                this._onMarkerChanged.fire([resource]);
            }
        }
        else {
            // insert marker for this (owner,resource)-tuple
            const markers = [];
            for (const data of markerData) {
                const marker = MarkerService._toMarker(owner, resource, data);
                if (marker) {
                    markers.push(marker);
                }
            }
            this._data.set(resource, owner, markers);
            this._onMarkerChanged.fire([resource]);
        }
    }
    static _toMarker(owner, resource, data) {
        let { code, severity, message, source, startLineNumber, startColumn, endLineNumber, endColumn, relatedInformation, tags, } = data;
        if (!message) {
            return undefined;
        }
        // santize data
        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 = [];
        // remove old marker
        const existing = this._data.values(owner);
        if (existing) {
            for (const data of existing) {
                const first = Iterable.first(data);
                if (first) {
                    changes.push(first.resource);
                    this._data.delete(first.resource, owner);
                }
            }
        }
        // add new markers
        if (isNonEmptyArray(data)) {
            // group by resource
            const groups = new ResourceMap();
            for (const { resource, marker: markerData } of data) {
                const marker = MarkerService._toMarker(owner, resource, markerData);
                if (!marker) {
                    // filter bad markers
                    continue;
                }
                const array = groups.get(resource);
                if (!array) {
                    groups.set(resource, [marker]);
                    changes.push(resource);
                }
                else {
                    array.push(marker);
                }
            }
            // insert all
            for (const [resource, value] of groups) {
                this._data.set(resource, owner, value);
            }
        }
        if (changes.length > 0) {
            this._onMarkerChanged.fire(changes);
        }
    }
    read(filter = Object.create(null)) {
        let { owner, resource, severities, take } = filter;
        if (!take || take < 0) {
            take = -1;
        }
        if (owner && resource) {
            // exactly one owner AND resource
            const data = this._data.get(resource, owner);
            if (!data) {
                return [];
            }
            else {
                const result = [];
                for (const marker of data) {
                    if (MarkerService._accept(marker, severities)) {
                        const newLen = result.push(marker);
                        if (take > 0 && newLen === take) {
                            break;
                        }
                    }
                }
                return result;
            }
        }
        else if (!owner && !resource) {
            // all
            const result = [];
            for (const markers of this._data.values()) {
                for (const data of markers) {
                    if (MarkerService._accept(data, severities)) {
                        const newLen = result.push(data);
                        if (take > 0 && newLen === take) {
                            return result;
                        }
                    }
                }
            }
            return result;
        }
        else {
            // of one resource OR owner
            const iterable = this._data.values(resource !== null && resource !== void 0 ? resource : owner);
            const result = [];
            for (const markers of iterable) {
                for (const data of markers) {
                    if (MarkerService._accept(data, severities)) {
                        const newLen = result.push(data);
                        if (take > 0 && newLen === take) {
                            return result;
                        }
                    }
                }
            }
            return result;
        }
    }
    static _accept(marker, severities) {
        return severities === undefined || (severities & marker.severity) === marker.severity;
    }
    // --- event debounce logic
    static _merge(all) {
        const set = new ResourceMap();
        for (const array of all) {
            for (const item of array) {
                set.set(item, true);
            }
        }
        return Array.from(set.keys());
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languageSelector.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


function score(selector, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType) {
    if (Array.isArray(selector)) {
        // array -> take max individual value
        let ret = 0;
        for (const filter of selector) {
            const value = score(filter, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType);
            if (value === 10) {
                return value; // already at the highest
            }
            if (value > ret) {
                ret = value;
            }
        }
        return ret;
    }
    else if (typeof selector === 'string') {
        if (!candidateIsSynchronized) {
            return 0;
        }
        // short-hand notion, desugars to
        // 'fooLang' -> { language: 'fooLang'}
        // '*' -> { language: '*' }
        if (selector === '*') {
            return 5;
        }
        else if (selector === candidateLanguage) {
            return 10;
        }
        else {
            return 0;
        }
    }
    else if (selector) {
        // filter -> select accordingly, use defaults for scheme
        const { language, pattern, scheme, hasAccessToAllModels, notebookType } = selector; // TODO: microsoft/TypeScript#42768
        if (!candidateIsSynchronized && !hasAccessToAllModels) {
            return 0;
        }
        // selector targets a notebook -> use the notebook uri instead
        // of the "normal" document uri.
        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 !== undefined) {
                ret = Math.max(ret, 5);
            }
            else {
                return 0;
            }
        }
        if (pattern) {
            let normalizedPattern;
            if (typeof pattern === 'string') {
                normalizedPattern = pattern;
            }
            else {
                // Since this pattern has a `base` property, we need
                // to normalize this path first before passing it on
                // because we will compare it against `Uri.fsPath`
                // which uses platform specific separators.
                // Refs: https://github.com/microsoft/vscode/issues/99938
                normalizedPattern = Object.assign(Object.assign({}, pattern), { base: normalize(pattern.base) });
            }
            if (normalizedPattern === candidateUri.fsPath || match(normalizedPattern, candidateUri.fsPath)) {
                ret = 10;
            }
            else {
                return 0;
            }
        }
        return ret;
    }
    else {
        return 0;
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/languageFeatureRegistry.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/




function isExclusive(selector) {
    if (typeof selector === 'string') {
        return false;
    }
    else if (Array.isArray(selector)) {
        return selector.every(isExclusive);
    }
    else {
        return !!selector.exclusive; // TODO: microsoft/TypeScript#42768
    }
}
class MatchCandidate {
    constructor(uri, languageId, notebookUri, notebookType) {
        this.uri = uri;
        this.languageId = languageId;
        this.notebookUri = notebookUri;
        this.notebookType = notebookType;
    }
    equals(other) {
        var _a, _b;
        return this.notebookType === other.notebookType
            && this.languageId === other.languageId
            && this.uri.toString() === other.uri.toString()
            && ((_a = this.notebookUri) === null || _a === void 0 ? void 0 : _a.toString()) === ((_b = other.notebookUri) === null || _b === void 0 ? void 0 : _b.toString());
    }
}
class LanguageFeatureRegistry {
    constructor(_notebookInfoResolver) {
        this._notebookInfoResolver = _notebookInfoResolver;
        this._clock = 0;
        this._entries = [];
        this._onDidChange = new Emitter();
        this.onDidChange = this._onDidChange.event;
    }
    register(selector, provider) {
        let entry = {
            selector,
            provider,
            _score: -1,
            _time: this._clock++
        };
        this._entries.push(entry);
        this._lastCandidate = undefined;
        this._onDidChange.fire(this._entries.length);
        return toDisposable(() => {
            if (entry) {
                const idx = this._entries.indexOf(entry);
                if (idx >= 0) {
                    this._entries.splice(idx, 1);
                    this._lastCandidate = undefined;
                    this._onDidChange.fire(this._entries.length);
                    entry = undefined;
                }
            }
        });
    }
    has(model) {
        return this.all(model).length > 0;
    }
    all(model) {
        if (!model) {
            return [];
        }
        this._updateScores(model);
        const result = [];
        // from registry
        for (const entry of this._entries) {
            if (entry._score > 0) {
                result.push(entry.provider);
            }
        }
        return result;
    }
    ordered(model) {
        const result = [];
        this._orderedForEach(model, entry => result.push(entry.provider));
        return result;
    }
    orderedGroups(model) {
        const result = [];
        let lastBucket;
        let lastBucketScore;
        this._orderedForEach(model, entry => {
            if (lastBucket && lastBucketScore === entry._score) {
                lastBucket.push(entry.provider);
            }
            else {
                lastBucketScore = entry._score;
                lastBucket = [entry.provider];
                result.push(lastBucket);
            }
        });
        return result;
    }
    _orderedForEach(model, callback) {
        this._updateScores(model);
        for (const entry of this._entries) {
            if (entry._score > 0) {
                callback(entry);
            }
        }
    }
    _updateScores(model) {
        var _a, _b;
        const notebookInfo = (_a = this._notebookInfoResolver) === null || _a === void 0 ? void 0 : _a.call(this, model.uri);
        // use the uri (scheme, pattern) of the notebook info iff we have one
        // otherwise it's the model's/document's uri
        const candidate = notebookInfo
            ? new MatchCandidate(model.uri, model.getLanguageId(), notebookInfo.uri, notebookInfo.type)
            : new MatchCandidate(model.uri, model.getLanguageId(), undefined, undefined);
        if ((_b = this._lastCandidate) === null || _b === void 0 ? void 0 : _b.equals(candidate)) {
            // nothing has changed
            return;
        }
        this._lastCandidate = candidate;
        for (const entry of this._entries) {
            entry._score = score(entry.selector, candidate.uri, candidate.languageId, shouldSynchronizeModel(model), candidate.notebookUri, candidate.notebookType);
            if (isExclusive(entry.selector) && entry._score > 0) {
                // support for one exclusive selector that overwrites
                // any other selector
                for (const entry of this._entries) {
                    entry._score = 0;
                }
                entry._score = 1000;
                break;
            }
        }
        // needs sorting
        this._entries.sort(LanguageFeatureRegistry._compareByScoreAndTime);
    }
    static _compareByScoreAndTime(a, b) {
        if (a._score < b._score) {
            return 1;
        }
        else if (a._score > b._score) {
            return -1;
        }
        else if (a._time < b._time) {
            return 1;
        }
        else if (a._time > b._time) {
            return -1;
        }
        else {
            return 0;
        }
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/common/services/languageFeaturesService.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



class LanguageFeaturesService {
    constructor() {
        this.referenceProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.renameProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.codeActionProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.definitionProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.typeDefinitionProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.declarationProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.implementationProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.documentSymbolProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.inlayHintsProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.colorProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.codeLensProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.documentFormattingEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.documentRangeFormattingEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.onTypeFormattingEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.signatureHelpProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.hoverProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.documentHighlightProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.selectionRangeProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.foldingRangeProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.linkProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.inlineCompletionsProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.completionProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.linkedEditingRangeProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.documentRangeSemanticTokensProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.documentSemanticTokensProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.documentOnDropEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
        this.documentPasteEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
    }
    _score(uri) {
        var _a;
        return (_a = this._notebookTypeResolver) === null || _a === void 0 ? void 0 : _a.call(this, uri);
    }
}
registerSingleton(ILanguageFeaturesService, LanguageFeaturesService, true);

;// ../../node_modules/monaco-editor/esm/vs/platform/configuration/common/configurations.js




class DefaultConfigurationModel extends ConfigurationModel {
    constructor(configurationDefaultsOverrides = {}) {
        const properties = Registry.as(configurationRegistry_Extensions.Configuration).getConfigurationProperties();
        const keys = Object.keys(properties);
        const contents = Object.create(null);
        const overrides = [];
        for (const key in properties) {
            const defaultOverrideValue = configurationDefaultsOverrides[key];
            const value = defaultOverrideValue !== undefined ? defaultOverrideValue : properties[key].default;
            addToValueTree(contents, key, value, message => console.error(`Conflict in default settings: ${message}`));
        }
        for (const key of Object.keys(contents)) {
            if (OVERRIDE_PROPERTY_REGEX.test(key)) {
                overrides.push({
                    identifiers: overrideIdentifiersFromKey(key),
                    keys: Object.keys(contents[key]),
                    contents: toValuesTree(contents[key], message => console.error(`Conflict in default settings file: ${message}`)),
                });
            }
        }
        super(contents, keys, overrides);
    }
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/standaloneServices.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var standaloneServices_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var standaloneServices_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var standaloneServices_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};















































































class SimpleModel {
    constructor(model) {
        this.disposed = false;
        this.model = model;
        this._onWillDispose = new Emitter();
    }
    get textEditorModel() {
        return this.model;
    }
    dispose() {
        this.disposed = true;
        this._onWillDispose.fire();
    }
}
let StandaloneTextModelService = class StandaloneTextModelService {
    constructor(modelService) {
        this.modelService = modelService;
    }
    createModelReference(resource) {
        const model = this.modelService.getModel(resource);
        if (!model) {
            return Promise.reject(new Error(`Model not found`));
        }
        return Promise.resolve(new ImmortalReference(new SimpleModel(model)));
    }
};
StandaloneTextModelService = standaloneServices_decorate([
    standaloneServices_param(0, IModelService)
], StandaloneTextModelService);
class StandaloneEditorProgressService {
    show() {
        return StandaloneEditorProgressService.NULL_PROGRESS_RUNNER;
    }
    showWhile(promise, delay) {
        return standaloneServices_awaiter(this, void 0, void 0, function* () {
            yield promise;
        });
    }
}
StandaloneEditorProgressService.NULL_PROGRESS_RUNNER = {
    done: () => { },
    total: () => { },
    worked: () => { }
};
class StandaloneProgressService {
    withProgress(_options, task, onDidCancel) {
        return task({
            report: () => { },
        });
    }
}
class StandaloneDialogService {
    confirm(confirmation) {
        return this.doConfirm(confirmation).then(confirmed => {
            return {
                confirmed,
                checkboxChecked: false // unsupported
            };
        });
    }
    doConfirm(confirmation) {
        let messageText = confirmation.message;
        if (confirmation.detail) {
            messageText = messageText + '\n\n' + confirmation.detail;
        }
        return Promise.resolve(window.confirm(messageText));
    }
    show(severity, message, buttons, options) {
        return Promise.resolve({ choice: 0 });
    }
}
class StandaloneNotificationService {
    info(message) {
        return this.notify({ severity: common_severity.Info, message });
    }
    warn(message) {
        return this.notify({ severity: common_severity.Warning, message });
    }
    error(error) {
        return this.notify({ severity: common_severity.Error, message: error });
    }
    notify(notification) {
        switch (notification.severity) {
            case common_severity.Error:
                console.error(notification.message);
                break;
            case common_severity.Warning:
                console.warn(notification.message);
                break;
            default:
                console.log(notification.message);
                break;
        }
        return StandaloneNotificationService.NO_OP;
    }
    status(message, options) {
        return Disposable.None;
    }
}
StandaloneNotificationService.NO_OP = new NoOpNotification();
let StandaloneCommandService = class StandaloneCommandService {
    constructor(instantiationService) {
        this._onWillExecuteCommand = new Emitter();
        this._onDidExecuteCommand = new Emitter();
        this.onWillExecuteCommand = this._onWillExecuteCommand.event;
        this.onDidExecuteCommand = this._onDidExecuteCommand.event;
        this._instantiationService = instantiationService;
    }
    executeCommand(id, ...args) {
        const command = CommandsRegistry.getCommand(id);
        if (!command) {
            return Promise.reject(new Error(`command '${id}' not found`));
        }
        try {
            this._onWillExecuteCommand.fire({ commandId: id, args });
            const result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler, ...args]);
            this._onDidExecuteCommand.fire({ commandId: id, args });
            return Promise.resolve(result);
        }
        catch (err) {
            return Promise.reject(err);
        }
    }
};
StandaloneCommandService = standaloneServices_decorate([
    standaloneServices_param(0, IInstantiationService)
], StandaloneCommandService);

let StandaloneKeybindingService = class StandaloneKeybindingService extends AbstractKeybindingService {
    constructor(contextKeyService, commandService, telemetryService, notificationService, logService, codeEditorService) {
        super(contextKeyService, commandService, telemetryService, notificationService, logService);
        this._cachedResolver = null;
        this._dynamicKeybindings = [];
        this._domNodeListeners = [];
        const addContainer = (domNode) => {
            const disposables = new DisposableStore();
            // for standard keybindings
            disposables.add(addDisposableListener(domNode, EventType.KEY_DOWN, (e) => {
                const keyEvent = new StandardKeyboardEvent(e);
                const shouldPreventDefault = this._dispatch(keyEvent, keyEvent.target);
                if (shouldPreventDefault) {
                    keyEvent.preventDefault();
                    keyEvent.stopPropagation();
                }
            }));
            // for single modifier chord keybindings (e.g. shift shift)
            disposables.add(addDisposableListener(domNode, EventType.KEY_UP, (e) => {
                const keyEvent = new StandardKeyboardEvent(e);
                const shouldPreventDefault = this._singleModifierDispatch(keyEvent, keyEvent.target);
                if (shouldPreventDefault) {
                    keyEvent.preventDefault();
                }
            }));
            this._domNodeListeners.push(new DomNodeListeners(domNode, disposables));
        };
        const removeContainer = (domNode) => {
            for (let i = 0; i < this._domNodeListeners.length; i++) {
                const domNodeListeners = this._domNodeListeners[i];
                if (domNodeListeners.domNode === domNode) {
                    this._domNodeListeners.splice(i, 1);
                    domNodeListeners.dispose();
                }
            }
        };
        const addCodeEditor = (codeEditor) => {
            if (codeEditor.getOption(56 /* EditorOption.inDiffEditor */)) {
                return;
            }
            addContainer(codeEditor.getContainerDomNode());
        };
        const removeCodeEditor = (codeEditor) => {
            if (codeEditor.getOption(56 /* EditorOption.inDiffEditor */)) {
                return;
            }
            removeContainer(codeEditor.getContainerDomNode());
        };
        this._register(codeEditorService.onCodeEditorAdd(addCodeEditor));
        this._register(codeEditorService.onCodeEditorRemove(removeCodeEditor));
        codeEditorService.listCodeEditors().forEach(addCodeEditor);
        const addDiffEditor = (diffEditor) => {
            addContainer(diffEditor.getContainerDomNode());
        };
        const removeDiffEditor = (diffEditor) => {
            removeContainer(diffEditor.getContainerDomNode());
        };
        this._register(codeEditorService.onDiffEditorAdd(addDiffEditor));
        this._register(codeEditorService.onDiffEditorRemove(removeDiffEditor));
        codeEditorService.listDiffEditors().forEach(addDiffEditor);
    }
    addDynamicKeybinding(command, keybinding, handler, when) {
        return combinedDisposable(CommandsRegistry.registerCommand(command, handler), this.addDynamicKeybindings([{
                keybinding,
                command,
                when
            }]));
    }
    addDynamicKeybindings(rules) {
        const entries = rules.map((rule) => {
            var _a, _b;
            const keybinding = createKeybinding(rule.keybinding, OS);
            return {
                keybinding: (_a = keybinding === null || keybinding === void 0 ? void 0 : keybinding.parts) !== null && _a !== void 0 ? _a : null,
                command: (_b = rule.command) !== null && _b !== void 0 ? _b : null,
                commandArgs: rule.commandArgs,
                when: rule.when,
                weight1: 1000,
                weight2: 0,
                extensionId: null,
                isBuiltinExtension: false
            };
        });
        this._dynamicKeybindings = this._dynamicKeybindings.concat(entries);
        this.updateResolver();
        return toDisposable(() => {
            // Search the first entry and remove them all since they will be contiguous
            for (let i = 0; i < this._dynamicKeybindings.length; i++) {
                if (this._dynamicKeybindings[i] === entries[0]) {
                    this._dynamicKeybindings.splice(i, entries.length);
                    this.updateResolver();
                    return;
                }
            }
        });
    }
    updateResolver() {
        this._cachedResolver = null;
        this._onDidUpdateKeybindings.fire();
    }
    _getResolver() {
        if (!this._cachedResolver) {
            const defaults = this._toNormalizedKeybindingItems(KeybindingsRegistry.getDefaultKeybindings(), true);
            const overrides = this._toNormalizedKeybindingItems(this._dynamicKeybindings, false);
            this._cachedResolver = new KeybindingResolver(defaults, overrides, (str) => this._log(str));
        }
        return this._cachedResolver;
    }
    _documentHasFocus() {
        return document.hasFocus();
    }
    _toNormalizedKeybindingItems(items, isDefault) {
        const result = [];
        let resultLen = 0;
        for (const item of items) {
            const when = item.when || undefined;
            const keybinding = item.keybinding;
            if (!keybinding) {
                // This might be a removal keybinding item in user settings => accept it
                result[resultLen++] = new ResolvedKeybindingItem(undefined, item.command, item.commandArgs, when, isDefault, null, false);
            }
            else {
                const resolvedKeybindings = USLayoutResolvedKeybinding.resolveUserBinding(keybinding, OS);
                for (const resolvedKeybinding of resolvedKeybindings) {
                    result[resultLen++] = new ResolvedKeybindingItem(resolvedKeybinding, item.command, item.commandArgs, when, isDefault, null, false);
                }
            }
        }
        return result;
    }
    resolveKeyboardEvent(keyboardEvent) {
        const keybinding = new SimpleKeybinding(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, keyboardEvent.keyCode).toChord();
        return new USLayoutResolvedKeybinding(keybinding, OS);
    }
};
StandaloneKeybindingService = standaloneServices_decorate([
    standaloneServices_param(0, IContextKeyService),
    standaloneServices_param(1, ICommandService),
    standaloneServices_param(2, ITelemetryService),
    standaloneServices_param(3, INotificationService),
    standaloneServices_param(4, ILogService),
    standaloneServices_param(5, ICodeEditorService)
], StandaloneKeybindingService);

class DomNodeListeners extends Disposable {
    constructor(domNode, disposables) {
        super();
        this.domNode = domNode;
        this._register(disposables);
    }
}
function isConfigurationOverrides(thing) {
    return thing
        && typeof thing === 'object'
        && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === 'string')
        && (!thing.resource || thing.resource instanceof URI);
}
class StandaloneConfigurationService {
    constructor() {
        this._onDidChangeConfiguration = new Emitter();
        this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
        this._configuration = new Configuration(new DefaultConfigurationModel(), new ConfigurationModel(), new ConfigurationModel(), new ConfigurationModel());
    }
    getValue(arg1, arg2) {
        const section = typeof arg1 === 'string' ? arg1 : undefined;
        const overrides = isConfigurationOverrides(arg1) ? arg1 : isConfigurationOverrides(arg2) ? arg2 : {};
        return this._configuration.getValue(section, overrides, undefined);
    }
    updateValues(values) {
        const previous = { data: this._configuration.toData() };
        const changedKeys = [];
        for (const entry of values) {
            const [key, value] = entry;
            if (this.getValue(key) === value) {
                continue;
            }
            this._configuration.updateValue(key, value);
            changedKeys.push(key);
        }
        if (changedKeys.length > 0) {
            const configurationChangeEvent = new ConfigurationChangeEvent({ keys: changedKeys, overrides: [] }, previous, this._configuration);
            configurationChangeEvent.source = 8 /* ConfigurationTarget.MEMORY */;
            configurationChangeEvent.sourceConfig = null;
            this._onDidChangeConfiguration.fire(configurationChangeEvent);
        }
        return Promise.resolve();
    }
    updateValue(key, value, arg3, arg4) {
        return this.updateValues([[key, value]]);
    }
    inspect(key, options = {}) {
        return this._configuration.inspect(key, options, undefined);
    }
}
let StandaloneResourceConfigurationService = class StandaloneResourceConfigurationService {
    constructor(configurationService) {
        this.configurationService = configurationService;
        this._onDidChangeConfiguration = new Emitter();
        this.configurationService.onDidChangeConfiguration((e) => {
            this._onDidChangeConfiguration.fire({ affectedKeys: e.affectedKeys, affectsConfiguration: (resource, configuration) => e.affectsConfiguration(configuration) });
        });
    }
    getValue(resource, arg2, arg3) {
        const position = Position.isIPosition(arg2) ? arg2 : null;
        const section = position ? (typeof arg3 === 'string' ? arg3 : undefined) : (typeof arg2 === 'string' ? arg2 : undefined);
        if (typeof section === 'undefined') {
            return this.configurationService.getValue();
        }
        return this.configurationService.getValue(section);
    }
};
StandaloneResourceConfigurationService = standaloneServices_decorate([
    standaloneServices_param(0, IConfigurationService)
], StandaloneResourceConfigurationService);
let StandaloneResourcePropertiesService = class StandaloneResourcePropertiesService {
    constructor(configurationService) {
        this.configurationService = configurationService;
    }
    getEOL(resource, language) {
        const eol = this.configurationService.getValue('files.eol', { overrideIdentifier: language, resource });
        if (eol && typeof eol === 'string' && eol !== 'auto') {
            return eol;
        }
        return (isLinux || isMacintosh) ? '\n' : '\r\n';
    }
};
StandaloneResourcePropertiesService = standaloneServices_decorate([
    standaloneServices_param(0, IConfigurationService)
], StandaloneResourcePropertiesService);
class StandaloneTelemetryService {
    publicLog(eventName, data) {
        return Promise.resolve(undefined);
    }
    publicLog2(eventName, data) {
        return this.publicLog(eventName, data);
    }
}
class StandaloneWorkspaceContextService {
    constructor() {
        const resource = URI.from({ scheme: StandaloneWorkspaceContextService.SCHEME, authority: 'model', path: '/' });
        this.workspace = { id: '4064f6ec-cb38-4ad0-af64-ee6467e63c82', folders: [new WorkspaceFolder({ uri: resource, name: '', index: 0 })] };
    }
    getWorkspace() {
        return this.workspace;
    }
    getWorkspaceFolder(resource) {
        return resource && resource.scheme === StandaloneWorkspaceContextService.SCHEME ? this.workspace.folders[0] : null;
    }
}
StandaloneWorkspaceContextService.SCHEME = 'inmemory';
function updateConfigurationService(configurationService, source, isDiffEditor) {
    if (!source) {
        return;
    }
    if (!(configurationService instanceof StandaloneConfigurationService)) {
        return;
    }
    const toUpdate = [];
    Object.keys(source).forEach((key) => {
        if (isEditorConfigurationKey(key)) {
            toUpdate.push([`editor.${key}`, source[key]]);
        }
        if (isDiffEditor && isDiffEditorConfigurationKey(key)) {
            toUpdate.push([`diffEditor.${key}`, source[key]]);
        }
    });
    if (toUpdate.length > 0) {
        configurationService.updateValues(toUpdate);
    }
}
let StandaloneBulkEditService = class StandaloneBulkEditService {
    constructor(_modelService) {
        this._modelService = _modelService;
        //
    }
    hasPreviewHandler() {
        return false;
    }
    apply(edits, _options) {
        return standaloneServices_awaiter(this, void 0, void 0, function* () {
            const textEdits = new Map();
            for (const edit of edits) {
                if (!(edit instanceof ResourceTextEdit)) {
                    throw new Error('bad edit - only text edits are supported');
                }
                const model = this._modelService.getModel(edit.resource);
                if (!model) {
                    throw new Error('bad edit - model not found');
                }
                if (typeof edit.versionId === 'number' && model.getVersionId() !== edit.versionId) {
                    throw new Error('bad state - model changed in the meantime');
                }
                let array = textEdits.get(model);
                if (!array) {
                    array = [];
                    textEdits.set(model, array);
                }
                array.push(EditOperation.replaceMove(Range.lift(edit.textEdit.range), edit.textEdit.text));
            }
            let totalEdits = 0;
            let totalFiles = 0;
            for (const [model, edits] of textEdits) {
                model.pushStackElement();
                model.pushEditOperations([], edits, () => []);
                model.pushStackElement();
                totalFiles += 1;
                totalEdits += edits.length;
            }
            return {
                ariaSummary: format(StandaloneServicesNLS.bulkEditServiceSummary, totalEdits, totalFiles)
            };
        });
    }
};
StandaloneBulkEditService = standaloneServices_decorate([
    standaloneServices_param(0, IModelService)
], StandaloneBulkEditService);
class StandaloneUriLabelService {
    getUriLabel(resource, options) {
        if (resource.scheme === 'file') {
            return resource.fsPath;
        }
        return resource.path;
    }
    getUriBasenameLabel(resource) {
        return resources_basename(resource);
    }
}
let StandaloneContextViewService = class StandaloneContextViewService extends ContextViewService {
    constructor(layoutService, _codeEditorService) {
        super(layoutService);
        this._codeEditorService = _codeEditorService;
    }
    showContextView(delegate, container, shadowRoot) {
        if (!container) {
            const codeEditor = this._codeEditorService.getFocusedCodeEditor() || this._codeEditorService.getActiveCodeEditor();
            if (codeEditor) {
                container = codeEditor.getContainerDomNode();
            }
        }
        return super.showContextView(delegate, container, shadowRoot);
    }
};
StandaloneContextViewService = standaloneServices_decorate([
    standaloneServices_param(0, ILayoutService),
    standaloneServices_param(1, ICodeEditorService)
], StandaloneContextViewService);
class StandaloneWorkspaceTrustManagementService {
    constructor() {
        this._neverEmitter = new Emitter();
        this.onDidChangeTrust = this._neverEmitter.event;
    }
    isWorkspaceTrusted() {
        return true;
    }
}
class StandaloneLanguageService extends LanguageService {
    constructor() {
        super();
    }
}
class StandaloneLogService extends LogService {
    constructor() {
        super(new ConsoleLogger());
    }
}
let StandaloneContextMenuService = class StandaloneContextMenuService extends ContextMenuService {
    constructor(telemetryService, notificationService, contextViewService, keybindingService, themeService) {
        super(telemetryService, notificationService, contextViewService, keybindingService, themeService);
        this.configure({ blockMouse: false }); // we do not want that in the standalone editor
    }
};
StandaloneContextMenuService = standaloneServices_decorate([
    standaloneServices_param(0, ITelemetryService),
    standaloneServices_param(1, INotificationService),
    standaloneServices_param(2, IContextViewService),
    standaloneServices_param(3, IKeybindingService),
    standaloneServices_param(4, IThemeService)
], StandaloneContextMenuService);
registerSingleton(IConfigurationService, StandaloneConfigurationService);
registerSingleton(ITextResourceConfigurationService, StandaloneResourceConfigurationService);
registerSingleton(ITextResourcePropertiesService, StandaloneResourcePropertiesService);
registerSingleton(IWorkspaceContextService, StandaloneWorkspaceContextService);
registerSingleton(ILabelService, StandaloneUriLabelService);
registerSingleton(ITelemetryService, StandaloneTelemetryService);
registerSingleton(IDialogService, StandaloneDialogService);
registerSingleton(INotificationService, StandaloneNotificationService);
registerSingleton(IMarkerService, MarkerService);
registerSingleton(ILanguageService, StandaloneLanguageService);
registerSingleton(IStandaloneThemeService, StandaloneThemeService);
registerSingleton(ILogService, StandaloneLogService);
registerSingleton(IModelService, ModelService);
registerSingleton(IMarkerDecorationsService, MarkerDecorationsService);
registerSingleton(IContextKeyService, ContextKeyService);
registerSingleton(IProgressService, StandaloneProgressService);
registerSingleton(IEditorProgressService, StandaloneEditorProgressService);
registerSingleton(IStorageService, InMemoryStorageService);
registerSingleton(IEditorWorkerService, EditorWorkerService);
registerSingleton(IBulkEditService, StandaloneBulkEditService);
registerSingleton(IWorkspaceTrustManagementService, StandaloneWorkspaceTrustManagementService);
registerSingleton(ITextModelService, StandaloneTextModelService);
registerSingleton(IAccessibilityService, AccessibilityService);
registerSingleton(IListService, ListService);
registerSingleton(ICommandService, StandaloneCommandService);
registerSingleton(IKeybindingService, StandaloneKeybindingService);
registerSingleton(IQuickInputService, StandaloneQuickInputService);
registerSingleton(IContextViewService, StandaloneContextViewService);
registerSingleton(IOpenerService, OpenerService);
registerSingleton(IClipboardService, BrowserClipboardService);
registerSingleton(IContextMenuService, StandaloneContextMenuService);
registerSingleton(IMenuService, MenuService);
/**
 * We don't want to eagerly instantiate services because embedders get a one time chance
 * to override services when they create the first editor.
 */
var StandaloneServices;
(function (StandaloneServices) {
    const serviceCollection = new ServiceCollection();
    for (const [id, descriptor] of getSingletonServiceDescriptors()) {
        serviceCollection.set(id, descriptor);
    }
    const instantiationService = new InstantiationService(serviceCollection, true);
    serviceCollection.set(IInstantiationService, instantiationService);
    function get(serviceId) {
        const r = serviceCollection.get(serviceId);
        if (!r) {
            throw new Error('Missing service ' + serviceId);
        }
        if (r instanceof SyncDescriptor) {
            return instantiationService.invokeFunction((accessor) => accessor.get(serviceId));
        }
        else {
            return r;
        }
    }
    StandaloneServices.get = get;
    let initialized = false;
    function initialize(overrides) {
        if (initialized) {
            return instantiationService;
        }
        initialized = true;
        // Add singletons that were registered after this module loaded
        for (const [id, descriptor] of getSingletonServiceDescriptors()) {
            if (!serviceCollection.get(id)) {
                serviceCollection.set(id, descriptor);
            }
        }
        // Initialize the service collection with the overrides, but only if the
        // service was not instantiated in the meantime.
        for (const serviceId in overrides) {
            if (overrides.hasOwnProperty(serviceId)) {
                const serviceIdentifier = createDecorator(serviceId);
                const r = serviceCollection.get(serviceIdentifier);
                if (r instanceof SyncDescriptor) {
                    serviceCollection.set(serviceIdentifier, overrides[serviceId]);
                }
            }
        }
        return instantiationService;
    }
    StandaloneServices.initialize = initialize;
})(StandaloneServices || (StandaloneServices = {}));

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/standaloneCodeEditor.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var standaloneCodeEditor_decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var standaloneCodeEditor_param = (undefined && undefined.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};




























let LAST_GENERATED_COMMAND_ID = 0;
let ariaDomNodeCreated = false;
/**
 * Create ARIA dom node inside parent,
 * or only for the first editor instantiation inside document.body.
 * @param parent container element for ARIA dom node
 */
function createAriaDomNode(parent) {
    if (!parent) {
        if (ariaDomNodeCreated) {
            return;
        }
        ariaDomNodeCreated = true;
    }
    setARIAContainer(parent || document.body);
}
/**
 * A code editor to be used both by the standalone editor and the standalone diff editor.
 */
let StandaloneCodeEditor = class StandaloneCodeEditor extends CodeEditorWidget {
    constructor(domElement, _options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
        const options = Object.assign({}, _options);
        options.ariaLabel = options.ariaLabel || StandaloneCodeEditorNLS.editorViewAccessibleLabel;
        options.ariaLabel = options.ariaLabel + ';' + (StandaloneCodeEditorNLS.accessibilityHelpMessage);
        super(domElement, options, {}, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
        if (keybindingService instanceof StandaloneKeybindingService) {
            this._standaloneKeybindingService = keybindingService;
        }
        else {
            this._standaloneKeybindingService = null;
        }
        createAriaDomNode(options.ariaContainerElement);
    }
    addCommand(keybinding, handler, context) {
        if (!this._standaloneKeybindingService) {
            console.warn('Cannot add command because the editor is configured with an unrecognized KeybindingService');
            return null;
        }
        const commandId = 'DYNAMIC_' + (++LAST_GENERATED_COMMAND_ID);
        const whenExpression = ContextKeyExpr.deserialize(context);
        this._standaloneKeybindingService.addDynamicKeybinding(commandId, keybinding, handler, whenExpression);
        return commandId;
    }
    createContextKey(key, defaultValue) {
        return this._contextKeyService.createKey(key, defaultValue);
    }
    addAction(_descriptor) {
        if ((typeof _descriptor.id !== 'string') || (typeof _descriptor.label !== 'string') || (typeof _descriptor.run !== 'function')) {
            throw new Error('Invalid action descriptor, `id`, `label` and `run` are required properties!');
        }
        if (!this._standaloneKeybindingService) {
            console.warn('Cannot add keybinding because the editor is configured with an unrecognized KeybindingService');
            return Disposable.None;
        }
        // Read descriptor options
        const id = _descriptor.id;
        const label = _descriptor.label;
        const precondition = ContextKeyExpr.and(ContextKeyExpr.equals('editorId', this.getId()), ContextKeyExpr.deserialize(_descriptor.precondition));
        const keybindings = _descriptor.keybindings;
        const keybindingsWhen = ContextKeyExpr.and(precondition, ContextKeyExpr.deserialize(_descriptor.keybindingContext));
        const contextMenuGroupId = _descriptor.contextMenuGroupId || null;
        const contextMenuOrder = _descriptor.contextMenuOrder || 0;
        const run = (accessor, ...args) => {
            return Promise.resolve(_descriptor.run(this, ...args));
        };
        const toDispose = new DisposableStore();
        // Generate a unique id to allow the same descriptor.id across multiple editor instances
        const uniqueId = this.getId() + ':' + id;
        // Register the command
        toDispose.add(CommandsRegistry.registerCommand(uniqueId, run));
        // Register the context menu item
        if (contextMenuGroupId) {
            const menuItem = {
                command: {
                    id: uniqueId,
                    title: label
                },
                when: precondition,
                group: contextMenuGroupId,
                order: contextMenuOrder
            };
            toDispose.add(MenuRegistry.appendMenuItem(MenuId.EditorContext, menuItem));
        }
        // Register the keybindings
        if (Array.isArray(keybindings)) {
            for (const kb of keybindings) {
                toDispose.add(this._standaloneKeybindingService.addDynamicKeybinding(uniqueId, kb, run, keybindingsWhen));
            }
        }
        // Finally, register an internal editor action
        const internalAction = new InternalEditorAction(uniqueId, label, label, precondition, run, this._contextKeyService);
        // Store it under the original id, such that trigger with the original id will work
        this._actions[id] = internalAction;
        toDispose.add(toDisposable(() => {
            delete this._actions[id];
        }));
        return toDispose;
    }
    _triggerCommand(handlerId, payload) {
        if (this._codeEditorService instanceof StandaloneCodeEditorService) {
            // Help commands find this editor as the active editor
            try {
                this._codeEditorService.setActiveCodeEditor(this);
                super._triggerCommand(handlerId, payload);
            }
            finally {
                this._codeEditorService.setActiveCodeEditor(null);
            }
        }
        else {
            super._triggerCommand(handlerId, payload);
        }
    }
};
StandaloneCodeEditor = standaloneCodeEditor_decorate([
    standaloneCodeEditor_param(2, IInstantiationService),
    standaloneCodeEditor_param(3, ICodeEditorService),
    standaloneCodeEditor_param(4, ICommandService),
    standaloneCodeEditor_param(5, IContextKeyService),
    standaloneCodeEditor_param(6, IKeybindingService),
    standaloneCodeEditor_param(7, IThemeService),
    standaloneCodeEditor_param(8, INotificationService),
    standaloneCodeEditor_param(9, IAccessibilityService),
    standaloneCodeEditor_param(10, ILanguageConfigurationService),
    standaloneCodeEditor_param(11, ILanguageFeaturesService)
], StandaloneCodeEditor);

let StandaloneEditor = class StandaloneEditor extends StandaloneCodeEditor {
    constructor(domElement, _options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, configurationService, accessibilityService, modelService, languageService, languageConfigurationService, languageFeaturesService) {
        const options = Object.assign({}, _options);
        updateConfigurationService(configurationService, options, false);
        const themeDomRegistration = themeService.registerEditorContainer(domElement);
        if (typeof options.theme === 'string') {
            themeService.setTheme(options.theme);
        }
        if (typeof options.autoDetectHighContrast !== 'undefined') {
            themeService.setAutoDetectHighContrast(Boolean(options.autoDetectHighContrast));
        }
        const _model = options.model;
        delete options.model;
        super(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
        this._configurationService = configurationService;
        this._standaloneThemeService = themeService;
        this._register(themeDomRegistration);
        let model;
        if (typeof _model === 'undefined') {
            const languageId = languageService.getLanguageIdByMimeType(options.language) || options.language || PLAINTEXT_LANGUAGE_ID;
            model = createTextModel(modelService, languageService, options.value || '', languageId, undefined);
            this._ownsModel = true;
        }
        else {
            model = _model;
            this._ownsModel = false;
        }
        this._attachModel(model);
        if (model) {
            const e = {
                oldModelUrl: null,
                newModelUrl: model.uri
            };
            this._onDidChangeModel.fire(e);
        }
    }
    dispose() {
        super.dispose();
    }
    updateOptions(newOptions) {
        updateConfigurationService(this._configurationService, newOptions, false);
        if (typeof newOptions.theme === 'string') {
            this._standaloneThemeService.setTheme(newOptions.theme);
        }
        if (typeof newOptions.autoDetectHighContrast !== 'undefined') {
            this._standaloneThemeService.setAutoDetectHighContrast(Boolean(newOptions.autoDetectHighContrast));
        }
        super.updateOptions(newOptions);
    }
    _postDetachModelCleanup(detachedModel) {
        super._postDetachModelCleanup(detachedModel);
        if (detachedModel && this._ownsModel) {
            detachedModel.dispose();
            this._ownsModel = false;
        }
    }
};
StandaloneEditor = standaloneCodeEditor_decorate([
    standaloneCodeEditor_param(2, IInstantiationService),
    standaloneCodeEditor_param(3, ICodeEditorService),
    standaloneCodeEditor_param(4, ICommandService),
    standaloneCodeEditor_param(5, IContextKeyService),
    standaloneCodeEditor_param(6, IKeybindingService),
    standaloneCodeEditor_param(7, IStandaloneThemeService),
    standaloneCodeEditor_param(8, INotificationService),
    standaloneCodeEditor_param(9, IConfigurationService),
    standaloneCodeEditor_param(10, IAccessibilityService),
    standaloneCodeEditor_param(11, IModelService),
    standaloneCodeEditor_param(12, ILanguageService),
    standaloneCodeEditor_param(13, ILanguageConfigurationService),
    standaloneCodeEditor_param(14, ILanguageFeaturesService)
], StandaloneEditor);

let StandaloneDiffEditor = class StandaloneDiffEditor extends DiffEditorWidget {
    constructor(domElement, _options, instantiationService, contextKeyService, editorWorkerService, codeEditorService, themeService, notificationService, configurationService, contextMenuService, editorProgressService, clipboardService) {
        const options = Object.assign({}, _options);
        updateConfigurationService(configurationService, options, true);
        const themeDomRegistration = themeService.registerEditorContainer(domElement);
        if (typeof options.theme === 'string') {
            themeService.setTheme(options.theme);
        }
        if (typeof options.autoDetectHighContrast !== 'undefined') {
            themeService.setAutoDetectHighContrast(Boolean(options.autoDetectHighContrast));
        }
        super(domElement, options, {}, clipboardService, editorWorkerService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService, contextMenuService, editorProgressService);
        this._configurationService = configurationService;
        this._standaloneThemeService = themeService;
        this._register(themeDomRegistration);
    }
    dispose() {
        super.dispose();
    }
    updateOptions(newOptions) {
        updateConfigurationService(this._configurationService, newOptions, true);
        if (typeof newOptions.theme === 'string') {
            this._standaloneThemeService.setTheme(newOptions.theme);
        }
        if (typeof newOptions.autoDetectHighContrast !== 'undefined') {
            this._standaloneThemeService.setAutoDetectHighContrast(Boolean(newOptions.autoDetectHighContrast));
        }
        super.updateOptions(newOptions);
    }
    _createInnerEditor(instantiationService, container, options) {
        return instantiationService.createInstance(StandaloneCodeEditor, container, options);
    }
    getOriginalEditor() {
        return super.getOriginalEditor();
    }
    getModifiedEditor() {
        return super.getModifiedEditor();
    }
    addCommand(keybinding, handler, context) {
        return this.getModifiedEditor().addCommand(keybinding, handler, context);
    }
    createContextKey(key, defaultValue) {
        return this.getModifiedEditor().createContextKey(key, defaultValue);
    }
    addAction(descriptor) {
        return this.getModifiedEditor().addAction(descriptor);
    }
};
StandaloneDiffEditor = standaloneCodeEditor_decorate([
    standaloneCodeEditor_param(2, IInstantiationService),
    standaloneCodeEditor_param(3, IContextKeyService),
    standaloneCodeEditor_param(4, IEditorWorkerService),
    standaloneCodeEditor_param(5, ICodeEditorService),
    standaloneCodeEditor_param(6, IStandaloneThemeService),
    standaloneCodeEditor_param(7, INotificationService),
    standaloneCodeEditor_param(8, IConfigurationService),
    standaloneCodeEditor_param(9, IContextMenuService),
    standaloneCodeEditor_param(10, IEditorProgressService),
    standaloneCodeEditor_param(11, IClipboardService)
], StandaloneDiffEditor);

/**
 * @internal
 */
function createTextModel(modelService, languageService, value, languageId, uri) {
    value = value || '';
    if (!languageId) {
        const firstLF = value.indexOf('\n');
        let firstLine = value;
        if (firstLF !== -1) {
            firstLine = value.substring(0, firstLF);
        }
        return doCreateModel(modelService, value, languageService.createByFilepathOrFirstLine(uri || null, firstLine), uri);
    }
    return doCreateModel(modelService, value, languageService.createById(languageId), uri);
}
/**
 * @internal
 */
function doCreateModel(modelService, value, languageSelection, uri) {
    return modelService.createModel(value, languageSelection, uri);
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/standaloneEditor.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/



























/**
 * Create a new editor under `domElement`.
 * `domElement` should be empty (not contain other dom nodes).
 * The editor will read the size of `domElement`.
 */
function standaloneEditor_create(domElement, options, override) {
    const instantiationService = StandaloneServices.initialize(override || {});
    return instantiationService.createInstance(StandaloneEditor, domElement, options);
}
/**
 * Emitted when an editor is created.
 * Creating a diff editor might cause this listener to be invoked with the two editors.
 * @event
 */
function onDidCreateEditor(listener) {
    const codeEditorService = StandaloneServices.get(ICodeEditorService);
    return codeEditorService.onCodeEditorAdd((editor) => {
        listener(editor);
    });
}
/**
 * Emitted when an diff editor is created.
 * @event
 */
function onDidCreateDiffEditor(listener) {
    const codeEditorService = StandaloneServices.get(ICodeEditorService);
    return codeEditorService.onDiffEditorAdd((editor) => {
        listener(editor);
    });
}
/**
 * Get all the created editors.
 */
function getEditors() {
    const codeEditorService = StandaloneServices.get(ICodeEditorService);
    return codeEditorService.listCodeEditors();
}
/**
 * Get all the created diff editors.
 */
function getDiffEditors() {
    const codeEditorService = StandaloneServices.get(ICodeEditorService);
    return codeEditorService.listDiffEditors();
}
/**
 * Create a new diff editor under `domElement`.
 * `domElement` should be empty (not contain other dom nodes).
 * The editor will read the size of `domElement`.
 */
function createDiffEditor(domElement, options, override) {
    const instantiationService = StandaloneServices.initialize(override || {});
    return instantiationService.createInstance(StandaloneDiffEditor, domElement, options);
}
function createDiffNavigator(diffEditor, opts) {
    return new DiffNavigator(diffEditor, opts);
}
/**
 * Add a command.
 */
function addCommand(descriptor) {
    if ((typeof descriptor.id !== 'string') || (typeof descriptor.run !== 'function')) {
        throw new Error('Invalid command descriptor, `id` and `run` are required properties!');
    }
    return CommandsRegistry.registerCommand(descriptor.id, descriptor.run);
}
/**
 * Add an action to all editors.
 */
function addEditorAction(descriptor) {
    if ((typeof descriptor.id !== 'string') || (typeof descriptor.label !== 'string') || (typeof descriptor.run !== 'function')) {
        throw new Error('Invalid action descriptor, `id`, `label` and `run` are required properties!');
    }
    const precondition = ContextKeyExpr.deserialize(descriptor.precondition);
    const run = (accessor, ...args) => {
        return EditorCommand.runEditorCommand(accessor, args, precondition, (accessor, editor, args) => Promise.resolve(descriptor.run(editor, ...args)));
    };
    const toDispose = new DisposableStore();
    // Register the command
    toDispose.add(CommandsRegistry.registerCommand(descriptor.id, run));
    // Register the context menu item
    if (descriptor.contextMenuGroupId) {
        const menuItem = {
            command: {
                id: descriptor.id,
                title: descriptor.label
            },
            when: precondition,
            group: descriptor.contextMenuGroupId,
            order: descriptor.contextMenuOrder || 0
        };
        toDispose.add(MenuRegistry.appendMenuItem(MenuId.EditorContext, menuItem));
    }
    // Register the keybindings
    if (Array.isArray(descriptor.keybindings)) {
        const keybindingService = StandaloneServices.get(IKeybindingService);
        if (!(keybindingService instanceof StandaloneKeybindingService)) {
            console.warn('Cannot add keybinding because the editor is configured with an unrecognized KeybindingService');
        }
        else {
            const keybindingsWhen = ContextKeyExpr.and(precondition, ContextKeyExpr.deserialize(descriptor.keybindingContext));
            toDispose.add(keybindingService.addDynamicKeybindings(descriptor.keybindings.map((keybinding) => {
                return {
                    keybinding,
                    command: descriptor.id,
                    when: keybindingsWhen
                };
            })));
        }
    }
    return toDispose;
}
/**
 * Add a keybinding rule.
 */
function addKeybindingRule(rule) {
    return addKeybindingRules([rule]);
}
/**
 * Add keybinding rules.
 */
function addKeybindingRules(rules) {
    const keybindingService = StandaloneServices.get(IKeybindingService);
    if (!(keybindingService instanceof StandaloneKeybindingService)) {
        console.warn('Cannot add keybinding because the editor is configured with an unrecognized KeybindingService');
        return Disposable.None;
    }
    return keybindingService.addDynamicKeybindings(rules.map((rule) => {
        return {
            keybinding: rule.keybinding,
            command: rule.command,
            commandArgs: rule.commandArgs,
            when: ContextKeyExpr.deserialize(rule.when),
        };
    }));
}
/**
 * Create a new editor model.
 * You can specify the language that should be set for this model or let the language be inferred from the `uri`.
 */
function createModel(value, language, uri) {
    const languageService = StandaloneServices.get(ILanguageService);
    const languageId = languageService.getLanguageIdByMimeType(language) || language;
    return createTextModel(StandaloneServices.get(IModelService), languageService, value, languageId, uri);
}
/**
 * Change the language for a model.
 */
function setModelLanguage(model, languageId) {
    const languageService = StandaloneServices.get(ILanguageService);
    const modelService = StandaloneServices.get(IModelService);
    modelService.setMode(model, languageService.createById(languageId));
}
/**
 * Set the markers for a model.
 */
function setModelMarkers(model, owner, markers) {
    if (model) {
        const markerService = StandaloneServices.get(IMarkerService);
        markerService.changeOne(owner, model.uri, markers);
    }
}
/**
 * Remove all markers of an owner.
 */
function removeAllMarkers(owner) {
    const markerService = StandaloneServices.get(IMarkerService);
    markerService.changeAll(owner, []);
}
/**
 * Get markers for owner and/or resource
 *
 * @returns list of markers
 */
function getModelMarkers(filter) {
    const markerService = StandaloneServices.get(IMarkerService);
    return markerService.read(filter);
}
/**
 * Emitted when markers change for a model.
 * @event
 */
function onDidChangeMarkers(listener) {
    const markerService = StandaloneServices.get(IMarkerService);
    return markerService.onMarkerChanged(listener);
}
/**
 * Get the model that has `uri` if it exists.
 */
function getModel(uri) {
    const modelService = StandaloneServices.get(IModelService);
    return modelService.getModel(uri);
}
/**
 * Get all the created models.
 */
function getModels() {
    const modelService = StandaloneServices.get(IModelService);
    return modelService.getModels();
}
/**
 * Emitted when a model is created.
 * @event
 */
function onDidCreateModel(listener) {
    const modelService = StandaloneServices.get(IModelService);
    return modelService.onModelAdded(listener);
}
/**
 * Emitted right before a model is disposed.
 * @event
 */
function onWillDisposeModel(listener) {
    const modelService = StandaloneServices.get(IModelService);
    return modelService.onModelRemoved(listener);
}
/**
 * Emitted when a different language is set to a model.
 * @event
 */
function onDidChangeModelLanguage(listener) {
    const modelService = StandaloneServices.get(IModelService);
    return modelService.onModelLanguageChanged((e) => {
        listener({
            model: e.model,
            oldLanguage: e.oldLanguageId
        });
    });
}
/**
 * Create a new web worker that has model syncing capabilities built in.
 * Specify an AMD module to load that will `create` an object that will be proxied.
 */
function standaloneEditor_createWebWorker(opts) {
    return createWebWorker(StandaloneServices.get(IModelService), StandaloneServices.get(ILanguageConfigurationService), opts);
}
/**
 * Colorize the contents of `domNode` using attribute `data-lang`.
 */
function colorizeElement(domNode, options) {
    const languageService = StandaloneServices.get(ILanguageService);
    const themeService = StandaloneServices.get(IStandaloneThemeService);
    themeService.registerEditorContainer(domNode);
    return Colorizer.colorizeElement(themeService, languageService, domNode, options);
}
/**
 * Colorize `text` using language `languageId`.
 */
function colorize(text, languageId, options) {
    const languageService = StandaloneServices.get(ILanguageService);
    const themeService = StandaloneServices.get(IStandaloneThemeService);
    themeService.registerEditorContainer(document.body);
    return Colorizer.colorize(languageService, text, languageId, options);
}
/**
 * Colorize a line in a model.
 */
function colorizeModelLine(model, lineNumber, tabSize = 4) {
    const themeService = StandaloneServices.get(IStandaloneThemeService);
    themeService.registerEditorContainer(document.body);
    return Colorizer.colorizeModelLine(model, lineNumber, tabSize);
}
/**
 * @internal
 */
function standaloneEditor_getSafeTokenizationSupport(language) {
    const tokenizationSupport = languages_TokenizationRegistry.get(language);
    if (tokenizationSupport) {
        return tokenizationSupport;
    }
    return {
        getInitialState: () => NullState,
        tokenize: (line, hasEOL, state) => nullTokenize(language, state)
    };
}
/**
 * Tokenize `text` using language `languageId`
 */
function tokenize(text, languageId) {
    // Needed in order to get the mode registered for subsequent look-ups
    languages_TokenizationRegistry.getOrCreate(languageId);
    const tokenizationSupport = standaloneEditor_getSafeTokenizationSupport(languageId);
    const lines = splitLines(text);
    const result = [];
    let state = tokenizationSupport.getInitialState();
    for (let i = 0, len = lines.length; i < len; i++) {
        const line = lines[i];
        const tokenizationResult = tokenizationSupport.tokenize(line, true, state);
        result[i] = tokenizationResult.tokens;
        state = tokenizationResult.endState;
    }
    return result;
}
/**
 * Define a new theme or update an existing theme.
 */
function defineTheme(themeName, themeData) {
    const standaloneThemeService = StandaloneServices.get(IStandaloneThemeService);
    standaloneThemeService.defineTheme(themeName, themeData);
}
/**
 * Switches to a theme.
 */
function setTheme(themeName) {
    const standaloneThemeService = StandaloneServices.get(IStandaloneThemeService);
    standaloneThemeService.setTheme(themeName);
}
/**
 * Clears all cached font measurements and triggers re-measurement.
 */
function remeasureFonts() {
    FontMeasurements.clearAllFontInfos();
}
/**
 * Register a command.
 */
function standaloneEditor_registerCommand(id, handler) {
    return CommandsRegistry.registerCommand({ id, handler });
}
/**
 * @internal
 */
function createMonacoEditorAPI() {
    return {
        // methods
        create: standaloneEditor_create,
        getEditors: getEditors,
        getDiffEditors: getDiffEditors,
        onDidCreateEditor: onDidCreateEditor,
        onDidCreateDiffEditor: onDidCreateDiffEditor,
        createDiffEditor: createDiffEditor,
        createDiffNavigator: createDiffNavigator,
        addCommand: addCommand,
        addEditorAction: addEditorAction,
        addKeybindingRule: addKeybindingRule,
        addKeybindingRules: addKeybindingRules,
        createModel: createModel,
        setModelLanguage: setModelLanguage,
        setModelMarkers: setModelMarkers,
        getModelMarkers: getModelMarkers,
        removeAllMarkers: removeAllMarkers,
        onDidChangeMarkers: onDidChangeMarkers,
        getModels: getModels,
        getModel: getModel,
        onDidCreateModel: onDidCreateModel,
        onWillDisposeModel: onWillDisposeModel,
        onDidChangeModelLanguage: onDidChangeModelLanguage,
        createWebWorker: standaloneEditor_createWebWorker,
        colorizeElement: colorizeElement,
        colorize: colorize,
        colorizeModelLine: colorizeModelLine,
        tokenize: tokenize,
        defineTheme: defineTheme,
        setTheme: setTheme,
        remeasureFonts: remeasureFonts,
        registerCommand: standaloneEditor_registerCommand,
        // enums
        AccessibilitySupport: AccessibilitySupport,
        ContentWidgetPositionPreference: ContentWidgetPositionPreference,
        CursorChangeReason: CursorChangeReason,
        DefaultEndOfLine: DefaultEndOfLine,
        EditorAutoIndentStrategy: EditorAutoIndentStrategy,
        EditorOption: EditorOption,
        EndOfLinePreference: EndOfLinePreference,
        EndOfLineSequence: EndOfLineSequence,
        MinimapPosition: standaloneEnums_MinimapPosition,
        MouseTargetType: MouseTargetType,
        OverlayWidgetPositionPreference: OverlayWidgetPositionPreference,
        OverviewRulerLane: standaloneEnums_OverviewRulerLane,
        RenderLineNumbersType: RenderLineNumbersType,
        RenderMinimap: RenderMinimap,
        ScrollbarVisibility: ScrollbarVisibility,
        ScrollType: ScrollType,
        TextEditorCursorBlinkingStyle: TextEditorCursorBlinkingStyle,
        TextEditorCursorStyle: standaloneEnums_TextEditorCursorStyle,
        TrackedRangeStickiness: TrackedRangeStickiness,
        WrappingIndent: WrappingIndent,
        InjectedTextCursorStops: standaloneEnums_InjectedTextCursorStops,
        PositionAffinity: PositionAffinity,
        // classes
        ConfigurationChangedEvent: ConfigurationChangedEvent,
        BareFontInfo: BareFontInfo,
        FontInfo: FontInfo,
        TextModelResolvedOptions: TextModelResolvedOptions,
        FindMatch: FindMatch,
        ApplyUpdateResult: ApplyUpdateResult,
        // vars
        EditorType: EditorType,
        EditorOptions: EditorOptions
    };
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/common/monarch/monarchCompile.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/*
 * This module only exports 'compile' which compiles a JSON language definition
 * into a typed and checked ILexer definition.
 */

/*
 * Type helpers
 *
 * Note: this is just for sanity checks on the JSON description which is
 * helpful for the programmer. No checks are done anymore once the lexer is
 * already 'compiled and checked'.
 *
 */
function isArrayOf(elemType, obj) {
    if (!obj) {
        return false;
    }
    if (!(Array.isArray(obj))) {
        return false;
    }
    for (const el of obj) {
        if (!(elemType(el))) {
            return false;
        }
    }
    return true;
}
function bool(prop, defValue) {
    if (typeof prop === 'boolean') {
        return prop;
    }
    return defValue;
}
function string(prop, defValue) {
    if (typeof (prop) === 'string') {
        return prop;
    }
    return defValue;
}
function arrayToHash(array) {
    const result = {};
    for (const e of array) {
        result[e] = true;
    }
    return result;
}
function createKeywordMatcher(arr, caseInsensitive = false) {
    if (caseInsensitive) {
        arr = arr.map(function (x) { return x.toLowerCase(); });
    }
    const hash = arrayToHash(arr);
    if (caseInsensitive) {
        return function (word) {
            return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
        };
    }
    else {
        return function (word) {
            return hash[word] !== undefined && hash.hasOwnProperty(word);
        };
    }
}
// Lexer helpers
/**
 * Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set, and the 'u' flag if 'unicode' is set.
 * Also replaces @\w+ or sequences with the content of the specified attribute
 * @\w+ replacement can be avoided by escaping `@` signs with another `@` sign.
 * @example /@attr/ will be replaced with the value of lexer[attr]
 * @example /@@text/ will not be replaced and will become /@text/.
 */
function compileRegExp(lexer, str) {
    // @@ must be interpreted as a literal @, so we replace all occurences of @@ with a placeholder character
    str = str.replace(/@@/g, `\x01`);
    let n = 0;
    let hadExpansion;
    do {
        hadExpansion = false;
        str = str.replace(/@(\w+)/g, function (s, attr) {
            hadExpansion = true;
            let sub = '';
            if (typeof (lexer[attr]) === 'string') {
                sub = lexer[attr];
            }
            else if (lexer[attr] && lexer[attr] instanceof RegExp) {
                sub = lexer[attr].source;
            }
            else {
                if (lexer[attr] === undefined) {
                    throw createError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str);
                }
                else {
                    throw createError(lexer, 'attribute reference \'' + attr + '\' must be a string, used at: ' + str);
                }
            }
            return (empty(sub) ? '' : '(?:' + sub + ')');
        });
        n++;
    } while (hadExpansion && n < 5);
    // handle escaped @@
    str = str.replace(/\x01/g, '@');
    const flags = (lexer.ignoreCase ? 'i' : '') + (lexer.unicode ? 'u' : '');
    return new RegExp(str, flags);
}
/**
 * Compiles guard functions for case matches.
 * This compiles 'cases' attributes into efficient match functions.
 *
 */
function selectScrutinee(id, matches, state, num) {
    if (num < 0) {
        return id;
    }
    if (num < matches.length) {
        return matches[num];
    }
    if (num >= 100) {
        num = num - 100;
        const parts = state.split('.');
        parts.unshift(state);
        if (num < parts.length) {
            return parts[num];
        }
    }
    return null;
}
function createGuard(lexer, ruleName, tkey, val) {
    // get the scrutinee and pattern
    let scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn
    let oppat = tkey;
    let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
    if (matches) {
        if (matches[3]) { // if digits
            scrut = parseInt(matches[3]);
            if (matches[2]) {
                scrut = scrut + 100; // if [sS] present
            }
        }
        oppat = matches[4];
    }
    // get operator
    let op = '~';
    let pat = oppat;
    if (!oppat || oppat.length === 0) {
        op = '!=';
        pat = '';
    }
    else if (/^\w*$/.test(pat)) { // just a word
        op = '==';
    }
    else {
        matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
        if (matches) {
            op = matches[1];
            pat = matches[2];
        }
    }
    // set the tester function
    let tester;
    // special case a regexp that matches just words
    if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) {
        const inWords = createKeywordMatcher(pat.split('|'), lexer.ignoreCase);
        tester = function (s) { return (op === '~' ? inWords(s) : !inWords(s)); };
    }
    else if (op === '@' || op === '!@') {
        const words = lexer[pat];
        if (!words) {
            throw createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName);
        }
        if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) {
            throw createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName);
        }
        const inWords = createKeywordMatcher(words, lexer.ignoreCase);
        tester = function (s) { return (op === '@' ? inWords(s) : !inWords(s)); };
    }
    else if (op === '~' || op === '!~') {
        if (pat.indexOf('$') < 0) {
            // precompile regular expression
            const re = compileRegExp(lexer, '^' + pat + '$');
            tester = function (s) { return (op === '~' ? re.test(s) : !re.test(s)); };
        }
        else {
            tester = function (s, id, matches, state) {
                const re = compileRegExp(lexer, '^' + substituteMatches(lexer, pat, id, matches, state) + '$');
                return re.test(s);
            };
        }
    }
    else { // if (op==='==' || op==='!=') {
        if (pat.indexOf('$') < 0) {
            const patx = fixCase(lexer, pat);
            tester = function (s) { return (op === '==' ? s === patx : s !== patx); };
        }
        else {
            const patx = fixCase(lexer, pat);
            tester = function (s, id, matches, state, eos) {
                const patexp = substituteMatches(lexer, patx, id, matches, state);
                return (op === '==' ? s === patexp : s !== patexp);
            };
        }
    }
    // return the branch object
    if (scrut === -1) {
        return {
            name: tkey, value: val, test: function (id, matches, state, eos) {
                return tester(id, id, matches, state, eos);
            }
        };
    }
    else {
        return {
            name: tkey, value: val, test: function (id, matches, state, eos) {
                const scrutinee = selectScrutinee(id, matches, state, scrut);
                return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos);
            }
        };
    }
}
/**
 * Compiles an action: i.e. optimize regular expressions and case matches
 * and do many sanity checks.
 *
 * This is called only during compilation but if the lexer definition
 * contains user functions as actions (which is usually not allowed), then this
 * may be called during lexing. It is important therefore to compile common cases efficiently
 */
function compileAction(lexer, ruleName, action) {
    if (!action) {
        return { token: '' };
    }
    else if (typeof (action) === 'string') {
        return action; // { token: action };
    }
    else if (action.token || action.token === '') {
        if (typeof (action.token) !== 'string') {
            throw createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName);
        }
        else {
            // only copy specific typed fields (only happens once during compile Lexer)
            const newAction = { token: action.token };
            if (action.token.indexOf('$') >= 0) {
                newAction.tokenSubst = true;
            }
            if (typeof (action.bracket) === 'string') {
                if (action.bracket === '@open') {
                    newAction.bracket = 1 /* monarchCommon.MonarchBracket.Open */;
                }
                else if (action.bracket === '@close') {
                    newAction.bracket = -1 /* monarchCommon.MonarchBracket.Close */;
                }
                else {
                    throw createError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName);
                }
            }
            if (action.next) {
                if (typeof (action.next) !== 'string') {
                    throw createError(lexer, 'the next state must be a string value in rule: ' + ruleName);
                }
                else {
                    let next = action.next;
                    if (!/^(@pop|@push|@popall)$/.test(next)) {
                        if (next[0] === '@') {
                            next = next.substr(1); // peel off starting @ sign
                        }
                        if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists
                            if (!stateExists(lexer, substituteMatches(lexer, next, '', [], ''))) {
                                throw createError(lexer, 'the next state \'' + action.next + '\' is not defined in rule: ' + ruleName);
                            }
                        }
                    }
                    newAction.next = next;
                }
            }
            if (typeof (action.goBack) === 'number') {
                newAction.goBack = action.goBack;
            }
            if (typeof (action.switchTo) === 'string') {
                newAction.switchTo = action.switchTo;
            }
            if (typeof (action.log) === 'string') {
                newAction.log = action.log;
            }
            if (typeof (action.nextEmbedded) === 'string') {
                newAction.nextEmbedded = action.nextEmbedded;
                lexer.usesEmbedded = true;
            }
            return newAction;
        }
    }
    else if (Array.isArray(action)) {
        const results = [];
        for (let i = 0, len = action.length; i < len; i++) {
            results[i] = compileAction(lexer, ruleName, action[i]);
        }
        return { group: results };
    }
    else if (action.cases) {
        // build an array of test cases
        const cases = [];
        // for each case, push a test function and result value
        for (const tkey in action.cases) {
            if (action.cases.hasOwnProperty(tkey)) {
                const val = compileAction(lexer, ruleName, action.cases[tkey]);
                // what kind of case
                if (tkey === '@default' || tkey === '@' || tkey === '') {
                    cases.push({ test: undefined, value: val, name: tkey });
                }
                else if (tkey === '@eos') {
                    cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });
                }
                else {
                    cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture
                }
            }
        }
        // create a matching function
        const def = lexer.defaultToken;
        return {
            test: function (id, matches, state, eos) {
                for (const _case of cases) {
                    const didmatch = (!_case.test || _case.test(id, matches, state, eos));
                    if (didmatch) {
                        return _case.value;
                    }
                }
                return def;
            }
        };
    }
    else {
        throw createError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName);
    }
}
/**
 * Helper class for creating matching rules
 */
class Rule {
    constructor(name) {
        this.regex = new RegExp('');
        this.action = { token: '' };
        this.matchOnlyAtLineStart = false;
        this.name = '';
        this.name = name;
    }
    setRegex(lexer, re) {
        let sregex;
        if (typeof (re) === 'string') {
            sregex = re;
        }
        else if (re instanceof RegExp) {
            sregex = re.source;
        }
        else {
            throw createError(lexer, 'rules must start with a match string or regular expression: ' + this.name);
        }
        this.matchOnlyAtLineStart = (sregex.length > 0 && sregex[0] === '^');
        this.name = this.name + ': ' + sregex;
        this.regex = compileRegExp(lexer, '^(?:' + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ')');
    }
    setAction(lexer, act) {
        this.action = compileAction(lexer, this.name, act);
    }
}
/**
 * Compiles a json description function into json where all regular expressions,
 * case matches etc, are compiled and all include rules are expanded.
 * We also compile the bracket definitions, supply defaults, and do many sanity checks.
 * If the 'jsonStrict' parameter is 'false', we allow at certain locations
 * regular expression objects and functions that get called during lexing.
 * (Currently we have no samples that need this so perhaps we should always have
 * jsonStrict to true).
 */
function compile(languageId, json) {
    if (!json || typeof (json) !== 'object') {
        throw new Error('Monarch: expecting a language definition object');
    }
    // Create our lexer
    const lexer = {};
    lexer.languageId = languageId;
    lexer.includeLF = bool(json.includeLF, false);
    lexer.noThrow = false; // raise exceptions during compilation
    lexer.maxStack = 100;
    // Set standard fields: be defensive about types
    lexer.start = (typeof json.start === 'string' ? json.start : null);
    lexer.ignoreCase = bool(json.ignoreCase, false);
    lexer.unicode = bool(json.unicode, false);
    lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId);
    lexer.defaultToken = string(json.defaultToken, 'source');
    lexer.usesEmbedded = false; // becomes true if we find a nextEmbedded action
    // For calling compileAction later on
    const lexerMin = json;
    lexerMin.languageId = languageId;
    lexerMin.includeLF = lexer.includeLF;
    lexerMin.ignoreCase = lexer.ignoreCase;
    lexerMin.unicode = lexer.unicode;
    lexerMin.noThrow = lexer.noThrow;
    lexerMin.usesEmbedded = lexer.usesEmbedded;
    lexerMin.stateNames = json.tokenizer;
    lexerMin.defaultToken = lexer.defaultToken;
    // Compile an array of rules into newrules where RegExp objects are created.
    function addRules(state, newrules, rules) {
        for (const rule of rules) {
            let include = rule.include;
            if (include) {
                if (typeof (include) !== 'string') {
                    throw createError(lexer, 'an \'include\' attribute must be a string at: ' + state);
                }
                if (include[0] === '@') {
                    include = include.substr(1); // peel off starting @
                }
                if (!json.tokenizer[include]) {
                    throw createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state);
                }
                addRules(state + '.' + include, newrules, json.tokenizer[include]);
            }
            else {
                const newrule = new Rule(state);
                // Set up new rule attributes
                if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) {
                    newrule.setRegex(lexerMin, rule[0]);
                    if (rule.length >= 3) {
                        if (typeof (rule[1]) === 'string') {
                            newrule.setAction(lexerMin, { token: rule[1], next: rule[2] });
                        }
                        else if (typeof (rule[1]) === 'object') {
                            const rule1 = rule[1];
                            rule1.next = rule[2];
                            newrule.setAction(lexerMin, rule1);
                        }
                        else {
                            throw createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state);
                        }
                    }
                    else {
                        newrule.setAction(lexerMin, rule[1]);
                    }
                }
                else {
                    if (!rule.regex) {
                        throw createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state);
                    }
                    if (rule.name) {
                        if (typeof rule.name === 'string') {
                            newrule.name = rule.name;
                        }
                    }
                    if (rule.matchOnlyAtStart) {
                        newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false);
                    }
                    newrule.setRegex(lexerMin, rule.regex);
                    newrule.setAction(lexerMin, rule.action);
                }
                newrules.push(newrule);
            }
        }
    }
    // compile the tokenizer rules
    if (!json.tokenizer || typeof (json.tokenizer) !== 'object') {
        throw createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object');
    }
    lexer.tokenizer = [];
    for (const key in json.tokenizer) {
        if (json.tokenizer.hasOwnProperty(key)) {
            if (!lexer.start) {
                lexer.start = key;
            }
            const rules = json.tokenizer[key];
            lexer.tokenizer[key] = new Array();
            addRules('tokenizer.' + key, lexer.tokenizer[key], rules);
        }
    }
    lexer.usesEmbedded = lexerMin.usesEmbedded; // can be set during compileAction
    // Set simple brackets
    if (json.brackets) {
        if (!(Array.isArray(json.brackets))) {
            throw createError(lexer, 'the \'brackets\' attribute must be defined as an array');
        }
    }
    else {
        json.brackets = [
            { open: '{', close: '}', token: 'delimiter.curly' },
            { open: '[', close: ']', token: 'delimiter.square' },
            { open: '(', close: ')', token: 'delimiter.parenthesis' },
            { open: '<', close: '>', token: 'delimiter.angle' }
        ];
    }
    const brackets = [];
    for (const el of json.brackets) {
        let desc = el;
        if (desc && Array.isArray(desc) && desc.length === 3) {
            desc = { token: desc[2], open: desc[0], close: desc[1] };
        }
        if (desc.open === desc.close) {
            throw createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open +
                '\n hint: use the \'bracket\' attribute if matching on equal brackets is required.');
        }
        if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') {
            brackets.push({
                token: desc.token + lexer.tokenPostfix,
                open: fixCase(lexer, desc.open),
                close: fixCase(lexer, desc.close)
            });
        }
        else {
            throw createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array');
        }
    }
    lexer.brackets = brackets;
    // Disable throw so the syntax highlighter goes, no matter what
    lexer.noThrow = true;
    return lexer;
}

;// ../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/standaloneLanguages.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var standaloneLanguages_awaiter = (undefined && undefined.__awaiter) || function (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());
    });
};














/**
 * Register information about a new language.
 */
function standaloneLanguages_register(language) {
    // Intentionally using the `ModesRegistry` here to avoid
    // instantiating services too quickly in the standalone editor.
    ModesRegistry.registerLanguage(language);
}
/**
 * Get the information of all the registered languages.
 */
function getLanguages() {
    let result = [];
    result = result.concat(ModesRegistry.getLanguages());
    return result;
}
function getEncodedLanguageId(languageId) {
    const languageService = StandaloneServices.get(ILanguageService);
    return languageService.languageIdCodec.encodeLanguageId(languageId);
}
/**
 * An event emitted when a language is needed for the first time (e.g. a model has it set).
 * @event
 */
function onLanguage(languageId, callback) {
    const languageService = StandaloneServices.get(ILanguageService);
    const disposable = languageService.onDidEncounterLanguage((encounteredLanguageId) => {
        if (encounteredLanguageId === languageId) {
            // stop listening
            disposable.dispose();
            // invoke actual listener
            callback();
        }
    });
    return disposable;
}
/**
 * Set the editing configuration for a language.
 */
function setLanguageConfiguration(languageId, configuration) {
    const languageService = StandaloneServices.get(ILanguageService);
    if (!languageService.isRegisteredLanguageId(languageId)) {
        throw new Error(`Cannot set configuration for unknown language ${languageId}`);
    }
    const languageConfigurationService = StandaloneServices.get(ILanguageConfigurationService);
    return languageConfigurationService.register(languageId, configuration, 100);
}
/**
 * @internal
 */
class EncodedTokenizationSupportAdapter {
    constructor(languageId, actual) {
        this._languageId = languageId;
        this._actual = actual;
    }
    getInitialState() {
        return this._actual.getInitialState();
    }
    tokenize(line, hasEOL, state) {
        if (typeof this._actual.tokenize === 'function') {
            return TokenizationSupportAdapter.adaptTokenize(this._languageId, this._actual, line, state);
        }
        throw new Error('Not supported!');
    }
    tokenizeEncoded(line, hasEOL, state) {
        const result = this._actual.tokenizeEncoded(line, state);
        return new EncodedTokenizationResult(result.tokens, result.endState);
    }
}
/**
 * @internal
 */
class TokenizationSupportAdapter {
    constructor(_languageId, _actual, _languageService, _standaloneThemeService) {
        this._languageId = _languageId;
        this._actual = _actual;
        this._languageService = _languageService;
        this._standaloneThemeService = _standaloneThemeService;
    }
    getInitialState() {
        return this._actual.getInitialState();
    }
    static _toClassicTokens(tokens, language) {
        const result = [];
        let previousStartIndex = 0;
        for (let i = 0, len = tokens.length; i < len; i++) {
            const t = tokens[i];
            let startIndex = t.startIndex;
            // Prevent issues stemming from a buggy external tokenizer.
            if (i === 0) {
                // Force first token to start at first index!
                startIndex = 0;
            }
            else if (startIndex < previousStartIndex) {
                // Force tokens to be after one another!
                startIndex = previousStartIndex;
            }
            result[i] = new languages_Token(startIndex, t.scopes, language);
            previousStartIndex = startIndex;
        }
        return result;
    }
    static adaptTokenize(language, actual, line, state) {
        const actualResult = actual.tokenize(line, state);
        const tokens = TokenizationSupportAdapter._toClassicTokens(actualResult.tokens, language);
        let endState;
        // try to save an object if possible
        if (actualResult.endState.equals(state)) {
            endState = state;
        }
        else {
            endState = actualResult.endState;
        }
        return new TokenizationResult(tokens, endState);
    }
    tokenize(line, hasEOL, state) {
        return TokenizationSupportAdapter.adaptTokenize(this._languageId, this._actual, line, state);
    }
    _toBinaryTokens(languageIdCodec, tokens) {
        const languageId = languageIdCodec.encodeLanguageId(this._languageId);
        const tokenTheme = this._standaloneThemeService.getColorTheme().tokenTheme;
        const result = [];
        let resultLen = 0;
        let previousStartIndex = 0;
        for (let i = 0, len = tokens.length; i < len; i++) {
            const t = tokens[i];
            const metadata = tokenTheme.match(languageId, t.scopes);
            if (resultLen > 0 && result[resultLen - 1] === metadata) {
                // same metadata
                continue;
            }
            let startIndex = t.startIndex;
            // Prevent issues stemming from a buggy external tokenizer.
            if (i === 0) {
                // Force first token to start at first index!
                startIndex = 0;
            }
            else if (startIndex < previousStartIndex) {
                // Force tokens to be after one another!
                startIndex = previousStartIndex;
            }
            result[resultLen++] = startIndex;
            result[resultLen++] = metadata;
            previousStartIndex = startIndex;
        }
        const actualResult = new Uint32Array(resultLen);
        for (let i = 0; i < resultLen; i++) {
            actualResult[i] = result[i];
        }
        return actualResult;
    }
    tokenizeEncoded(line, hasEOL, state) {
        const actualResult = this._actual.tokenize(line, state);
        const tokens = this._toBinaryTokens(this._languageService.languageIdCodec, actualResult.tokens);
        let endState;
        // try to save an object if possible
        if (actualResult.endState.equals(state)) {
            endState = state;
        }
        else {
            endState = actualResult.endState;
        }
        return new EncodedTokenizationResult(tokens, endState);
    }
}
function isATokensProvider(provider) {
    return (typeof provider.getInitialState === 'function');
}
function isEncodedTokensProvider(provider) {
    return 'tokenizeEncoded' in provider;
}
function standaloneLanguages_isThenable(obj) {
    return obj && typeof obj.then === 'function';
}
/**
 * Change the color map that is used for token colors.
 * Supported formats (hex): #RRGGBB, $RRGGBBAA, #RGB, #RGBA
 */
function setColorMap(colorMap) {
    const standaloneThemeService = StandaloneServices.get(IStandaloneThemeService);
    if (colorMap) {
        const result = [null];
        for (let i = 1, len = colorMap.length; i < len; i++) {
            result[i] = Color.fromHex(colorMap[i]);
        }
        standaloneThemeService.setColorMapOverride(result);
    }
    else {
        standaloneThemeService.setColorMapOverride(null);
    }
}
/**
 * @internal
 */
function createTokenizationSupportAdapter(languageId, provider) {
    if (isEncodedTokensProvider(provider)) {
        return new EncodedTokenizationSupportAdapter(languageId, provider);
    }
    else {
        return new TokenizationSupportAdapter(languageId, provider, StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService));
    }
}
/**
 * Register a tokens provider factory for a language. This tokenizer will be exclusive with a tokenizer
 * set using `setTokensProvider` or one created using `setMonarchTokensProvider`, but will work together
 * with a tokens provider set using `registerDocumentSemanticTokensProvider` or `registerDocumentRangeSemanticTokensProvider`.
 */
function registerTokensProviderFactory(languageId, factory) {
    const adaptedFactory = {
        createTokenizationSupport: () => standaloneLanguages_awaiter(this, void 0, void 0, function* () {
            const result = yield Promise.resolve(factory.create());
            if (!result) {
                return null;
            }
            if (isATokensProvider(result)) {
                return createTokenizationSupportAdapter(languageId, result);
            }
            return new MonarchTokenizer(StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService), languageId, compile(languageId, result), StandaloneServices.get(IConfigurationService));
        })
    };
    return languages_TokenizationRegistry.registerFactory(languageId, adaptedFactory);
}
/**
 * Set the tokens provider for a language (manual implementation). This tokenizer will be exclusive
 * with a tokenizer created using `setMonarchTokensProvider`, or with `registerTokensProviderFactory`,
 * but will work together with a tokens provider set using `registerDocumentSemanticTokensProvider`
 * or `registerDocumentRangeSemanticTokensProvider`.
 */
function setTokensProvider(languageId, provider) {
    const languageService = StandaloneServices.get(ILanguageService);
    if (!languageService.isRegisteredLanguageId(languageId)) {
        throw new Error(`Cannot set tokens provider for unknown language ${languageId}`);
    }
    if (standaloneLanguages_isThenable(provider)) {
        return registerTokensProviderFactory(languageId, { create: () => provider });
    }
    return languages_TokenizationRegistry.register(languageId, createTokenizationSupportAdapter(languageId, provider));
}
/**
 * Set the tokens provider for a language (monarch implementation). This tokenizer will be exclusive
 * with a tokenizer set using `setTokensProvider`, or with `registerTokensProviderFactory`, but will
 * work together with a tokens provider set using `registerDocumentSemanticTokensProvider` or
 * `registerDocumentRangeSemanticTokensProvider`.
 */
function setMonarchTokensProvider(languageId, languageDef) {
    const create = (languageDef) => {
        return new MonarchTokenizer(StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService), languageId, compile(languageId, languageDef), StandaloneServices.get(IConfigurationService));
    };
    if (standaloneLanguages_isThenable(languageDef)) {
        return registerTokensProviderFactory(languageId, { create: () => languageDef });
    }
    return languages_TokenizationRegistry.register(languageId, create(languageDef));
}
/**
 * Register a reference provider (used by e.g. reference search).
 */
function registerReferenceProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.referenceProvider.register(languageSelector, provider);
}
/**
 * Register a rename provider (used by e.g. rename symbol).
 */
function registerRenameProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.renameProvider.register(languageSelector, provider);
}
/**
 * Register a signature help provider (used by e.g. parameter hints).
 */
function registerSignatureHelpProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.signatureHelpProvider.register(languageSelector, provider);
}
/**
 * Register a hover provider (used by e.g. editor hover).
 */
function registerHoverProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.hoverProvider.register(languageSelector, {
        provideHover: (model, position, token) => {
            const word = model.getWordAtPosition(position);
            return Promise.resolve(provider.provideHover(model, position, token)).then((value) => {
                if (!value) {
                    return undefined;
                }
                if (!value.range && word) {
                    value.range = new Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
                }
                if (!value.range) {
                    value.range = new Range(position.lineNumber, position.column, position.lineNumber, position.column);
                }
                return value;
            });
        }
    });
}
/**
 * Register a document symbol provider (used by e.g. outline).
 */
function registerDocumentSymbolProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentSymbolProvider.register(languageSelector, provider);
}
/**
 * Register a document highlight provider (used by e.g. highlight occurrences).
 */
function registerDocumentHighlightProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentHighlightProvider.register(languageSelector, provider);
}
/**
 * Register an linked editing range provider.
 */
function registerLinkedEditingRangeProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.linkedEditingRangeProvider.register(languageSelector, provider);
}
/**
 * Register a definition provider (used by e.g. go to definition).
 */
function registerDefinitionProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.definitionProvider.register(languageSelector, provider);
}
/**
 * Register a implementation provider (used by e.g. go to implementation).
 */
function registerImplementationProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.implementationProvider.register(languageSelector, provider);
}
/**
 * Register a type definition provider (used by e.g. go to type definition).
 */
function registerTypeDefinitionProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.typeDefinitionProvider.register(languageSelector, provider);
}
/**
 * Register a code lens provider (used by e.g. inline code lenses).
 */
function registerCodeLensProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.codeLensProvider.register(languageSelector, provider);
}
/**
 * Register a code action provider (used by e.g. quick fix).
 */
function registerCodeActionProvider(languageSelector, provider, metadata) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.codeActionProvider.register(languageSelector, {
        providedCodeActionKinds: metadata === null || metadata === void 0 ? void 0 : metadata.providedCodeActionKinds,
        documentation: metadata === null || metadata === void 0 ? void 0 : metadata.documentation,
        provideCodeActions: (model, range, context, token) => {
            const markerService = StandaloneServices.get(IMarkerService);
            const markers = markerService.read({ resource: model.uri }).filter(m => {
                return Range.areIntersectingOrTouching(m, range);
            });
            return provider.provideCodeActions(model, range, { markers, only: context.only, trigger: context.trigger }, token);
        },
        resolveCodeAction: provider.resolveCodeAction
    });
}
/**
 * Register a formatter that can handle only entire models.
 */
function registerDocumentFormattingEditProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentFormattingEditProvider.register(languageSelector, provider);
}
/**
 * Register a formatter that can handle a range inside a model.
 */
function registerDocumentRangeFormattingEditProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentRangeFormattingEditProvider.register(languageSelector, provider);
}
/**
 * Register a formatter than can do formatting as the user types.
 */
function registerOnTypeFormattingEditProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.onTypeFormattingEditProvider.register(languageSelector, provider);
}
/**
 * Register a link provider that can find links in text.
 */
function registerLinkProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.linkProvider.register(languageSelector, provider);
}
/**
 * Register a completion item provider (use by e.g. suggestions).
 */
function registerCompletionItemProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.completionProvider.register(languageSelector, provider);
}
/**
 * Register a document color provider (used by Color Picker, Color Decorator).
 */
function registerColorProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.colorProvider.register(languageSelector, provider);
}
/**
 * Register a folding range provider
 */
function registerFoldingRangeProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.foldingRangeProvider.register(languageSelector, provider);
}
/**
 * Register a declaration provider
 */
function registerDeclarationProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.declarationProvider.register(languageSelector, provider);
}
/**
 * Register a selection range provider
 */
function registerSelectionRangeProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.selectionRangeProvider.register(languageSelector, provider);
}
/**
 * Register a document semantic tokens provider. A semantic tokens provider will complement and enhance a
 * simple top-down tokenizer. Simple top-down tokenizers can be set either via `setMonarchTokensProvider`
 * or `setTokensProvider`.
 *
 * For the best user experience, register both a semantic tokens provider and a top-down tokenizer.
 */
function registerDocumentSemanticTokensProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentSemanticTokensProvider.register(languageSelector, provider);
}
/**
 * Register a document range semantic tokens provider. A semantic tokens provider will complement and enhance a
 * simple top-down tokenizer. Simple top-down tokenizers can be set either via `setMonarchTokensProvider`
 * or `setTokensProvider`.
 *
 * For the best user experience, register both a semantic tokens provider and a top-down tokenizer.
 */
function registerDocumentRangeSemanticTokensProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.documentRangeSemanticTokensProvider.register(languageSelector, provider);
}
/**
 * Register an inline completions provider.
 */
function registerInlineCompletionsProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.inlineCompletionsProvider.register(languageSelector, provider);
}
/**
 * Register an inlay hints provider.
 */
function registerInlayHintsProvider(languageSelector, provider) {
    const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
    return languageFeaturesService.inlayHintsProvider.register(languageSelector, provider);
}
/**
 * @internal
 */
function createMonacoLanguagesAPI() {
    return {
        register: standaloneLanguages_register,
        getLanguages: getLanguages,
        onLanguage: onLanguage,
        getEncodedLanguageId: getEncodedLanguageId,
        // provider methods
        setLanguageConfiguration: setLanguageConfiguration,
        setColorMap: setColorMap,
        registerTokensProviderFactory: registerTokensProviderFactory,
        setTokensProvider: setTokensProvider,
        setMonarchTokensProvider: setMonarchTokensProvider,
        registerReferenceProvider: registerReferenceProvider,
        registerRenameProvider: registerRenameProvider,
        registerCompletionItemProvider: registerCompletionItemProvider,
        registerSignatureHelpProvider: registerSignatureHelpProvider,
        registerHoverProvider: registerHoverProvider,
        registerDocumentSymbolProvider: registerDocumentSymbolProvider,
        registerDocumentHighlightProvider: registerDocumentHighlightProvider,
        registerLinkedEditingRangeProvider: registerLinkedEditingRangeProvider,
        registerDefinitionProvider: registerDefinitionProvider,
        registerImplementationProvider: registerImplementationProvider,
        registerTypeDefinitionProvider: registerTypeDefinitionProvider,
        registerCodeLensProvider: registerCodeLensProvider,
        registerCodeActionProvider: registerCodeActionProvider,
        registerDocumentFormattingEditProvider: registerDocumentFormattingEditProvider,
        registerDocumentRangeFormattingEditProvider: registerDocumentRangeFormattingEditProvider,
        registerOnTypeFormattingEditProvider: registerOnTypeFormattingEditProvider,
        registerLinkProvider: registerLinkProvider,
        registerColorProvider: registerColorProvider,
        registerFoldingRangeProvider: registerFoldingRangeProvider,
        registerDeclarationProvider: registerDeclarationProvider,
        registerSelectionRangeProvider: registerSelectionRangeProvider,
        registerDocumentSemanticTokensProvider: registerDocumentSemanticTokensProvider,
        registerDocumentRangeSemanticTokensProvider: registerDocumentRangeSemanticTokensProvider,
        registerInlineCompletionsProvider: registerInlineCompletionsProvider,
        registerInlayHintsProvider: registerInlayHintsProvider,
        // enums
        DocumentHighlightKind: standaloneEnums_DocumentHighlightKind,
        CompletionItemKind: CompletionItemKind,
        CompletionItemTag: CompletionItemTag,
        CompletionItemInsertTextRule: CompletionItemInsertTextRule,
        SymbolKind: SymbolKind,
        SymbolTag: SymbolTag,
        IndentAction: standaloneEnums_IndentAction,
        CompletionTriggerKind: CompletionTriggerKind,
        SignatureHelpTriggerKind: standaloneEnums_SignatureHelpTriggerKind,
        InlayHintKind: standaloneEnums_InlayHintKind,
        InlineCompletionTriggerKind: standaloneEnums_InlineCompletionTriggerKind,
        CodeActionTriggerType: CodeActionTriggerType,
        // classes
        FoldingRangeKind: FoldingRangeKind,
    };
}

;// ../../node_modules/monaco-editor/esm/vs/editor/editor.api.js
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
var editor_api_a;






// Set defaults for standalone editor
EditorOptions.wrappingIndent.defaultValue = 0 /* WrappingIndent.None */;
EditorOptions.glyphMargin.defaultValue = false;
EditorOptions.autoIndent.defaultValue = 3 /* EditorAutoIndentStrategy.Advanced */;
EditorOptions.overviewRulerLanes.defaultValue = 2;
// We need to register a formatter selector which simply picks the first available formatter.
// See https://github.com/microsoft/monaco-editor/issues/2327
FormattingConflicts.setFormatterSelector((formatter, document, mode) => Promise.resolve(formatter[0]));
const api = createMonacoBaseAPI();
api.editor = createMonacoEditorAPI();
api.languages = createMonacoLanguagesAPI();
const editor_api_CancellationTokenSource = api.CancellationTokenSource;
const editor_api_Emitter = api.Emitter;
const editor_api_KeyCode = api.KeyCode;
const editor_api_KeyMod = api.KeyMod;
const editor_api_Position = api.Position;
const editor_api_Range = api.Range;
const editor_api_Selection = api.Selection;
const editor_api_SelectionDirection = api.SelectionDirection;
const editor_api_MarkerSeverity = api.MarkerSeverity;
const editor_api_MarkerTag = api.MarkerTag;
const editor_api_Uri = api.Uri;
const editor_api_Token = api.Token;
const editor_api_editor = api.editor;
const languages = api.languages;
if (((editor_api_a = platform_globals.MonacoEnvironment) === null || editor_api_a === void 0 ? void 0 : editor_api_a.globalAPI) || (typeof define === 'function' && __webpack_require__.amdO)) {
    self.monaco = api;
}
if (typeof self.require !== 'undefined' && typeof self.require.config === 'function') {
    self.require.config({
        ignoreDuplicateModules: [
            'vscode-languageserver-types',
            'vscode-languageserver-types/main',
            'vscode-languageserver-textdocument',
            'vscode-languageserver-textdocument/main',
            'vscode-nls',
            'vscode-nls/vscode-nls',
            'jsonc-parser',
            'jsonc-parser/main',
            'vscode-uri',
            'vscode-uri/index',
            'vs/basic-languages/typescript/typescript'
        ]
    });
}

// EXTERNAL MODULE: ../../node_modules/monaco-editor/esm/vs/basic-languages/_.contribution.js
var _contribution = __webpack_require__(86919);
;// ../../node_modules/monaco-editor/esm/vs/basic-languages/typescript/typescript.contribution.js
/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/

// src/basic-languages/typescript/typescript.contribution.ts

(0,_contribution/* registerLanguage */.K)({
  id: "typescript",
  extensions: [".ts", ".tsx"],
  aliases: ["TypeScript", "ts", "typescript"],
  mimetypes: ["text/typescript"],
  loader: () => {
    if (false) // removed by dead control flow
{} else {
      return __webpack_require__.e(/* import() */ 933).then(__webpack_require__.bind(__webpack_require__, 24933));
    }
  }
});

// EXTERNAL MODULE: ../../node_modules/monaco-editor/esm/vs/language/typescript/monaco.contribution.js
var monaco_contribution = __webpack_require__(32263);
;// ../../node_modules/monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js
/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/

// src/basic-languages/javascript/javascript.contribution.ts

(0,_contribution/* registerLanguage */.K)({
  id: "javascript",
  extensions: [".js", ".es6", ".jsx", ".mjs", ".cjs"],
  firstLine: "^#!.*\\bnode",
  filenames: ["jakefile"],
  aliases: ["JavaScript", "javascript", "js"],
  mimetypes: ["text/javascript"],
  loader: () => {
    if (false) // removed by dead control flow
{} else {
      return __webpack_require__.e(/* import() */ 693).then(__webpack_require__.bind(__webpack_require__, 46693));
    }
  }
});

;// ../../node_modules/monaco-editor/esm/vs/basic-languages/css/css.contribution.js
/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/

// src/basic-languages/css/css.contribution.ts

(0,_contribution/* registerLanguage */.K)({
  id: "css",
  extensions: [".css"],
  aliases: ["CSS", "css"],
  mimetypes: ["text/css"],
  loader: () => {
    if (false) // removed by dead control flow
{} else {
      return __webpack_require__.e(/* import() */ 445).then(__webpack_require__.bind(__webpack_require__, 17445));
    }
  }
});

// EXTERNAL MODULE: ../../node_modules/monaco-editor/esm/vs/language/css/monaco.contribution.js
var css_monaco_contribution = __webpack_require__(62877);
;// include-loader!../../node_modules/monaco-editor/esm/vs/editor/editor.api.js
self["MonacoEnvironment"] = (function (paths) {
      function stripTrailingSlash(str) {
        return str.replace(/\/$/, '');
      }
      return {
        globalAPI: true,
        getWorkerUrl: function (moduleId, label) {
          var pathPrefix =  true ? __webpack_require__.p : 0;
          var result = (pathPrefix ? stripTrailingSlash(pathPrefix) + '/' : '') + paths[label];
          if (/^((http:)|(https:)|(file:)|(\/\/))/.test(result)) {
            var currentUrl = String(window.location);
            var currentOrigin = currentUrl.substr(0, currentUrl.length - window.location.hash.length - window.location.search.length - window.location.pathname.length);
            if (result.substring(0, currentOrigin.length) !== currentOrigin) {
              if(/^(\/\/)/.test(result)) {
                result = window.location.protocol + result
              }
              var js = '/*' + label + '*/';
              if (true) {
                // module worker
                js += 'import "' + result + '";';
              } else // removed by dead control flow
{}
              var blob = new Blob([js], { type: 'application/javascript' });
              return URL.createObjectURL(blob);
            }
          }
          return result;
        }
      };
    })({
  "editorWorkerService": "editor.worker.js",
  "typescript": "ts.worker.js",
  "css": "css.worker.js",
  "javascript": "ts.worker.js",
  "less": "css.worker.js",
  "scss": "css.worker.js"
});





























































/* harmony default export */ const editor_api = (editor_api_namespaceObject);
		






/***/ }),

/***/ 15811:
/***/ (function(module, exports) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Do not edit this file; automatically generated.

/* eslint-disable */
;(function(root, factory) {
  if (true) { // AMD
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else // removed by dead control flow
{}
}(this, function() {
var $={};
var register$$module$build$src$core$registry,validate$$module$build$src$core$registry,unregister$$module$build$src$core$registry,getItem$$module$build$src$core$registry,hasItem$$module$build$src$core$registry,getClass$$module$build$src$core$registry,getObject$$module$build$src$core$registry,getAllItems$$module$build$src$core$registry,getClassFromOptions$$module$build$src$core$registry,longStart$$module$build$src$core$touch,longStop$$module$build$src$core$touch,clearTouchIdentifier$$module$build$src$core$touch,
shouldHandleEvent$$module$build$src$core$touch,getTouchIdentifierFromEvent$$module$build$src$core$touch,checkTouchIdentifier$$module$build$src$core$touch,conditionalBind$$module$build$src$core$browser_events,bind$$module$build$src$core$browser_events,unbind$$module$build$src$core$browser_events,isTargetInput$$module$build$src$core$browser_events,isRightButton$$module$build$src$core$browser_events,mouseToSvg$$module$build$src$core$browser_events,getScrollDeltaPixels$$module$build$src$core$browser_events,
getNextUniqueId$$module$build$src$core$utils$idgenerator,genUid$$module$build$src$core$utils$idgenerator,isBlockCreate$$module$build$src$core$events$predicates,isBlockDelete$$module$build$src$core$events$predicates,isBlockChange$$module$build$src$core$events$predicates,isBlockFieldIntermediateChange$$module$build$src$core$events$predicates,isBlockMove$$module$build$src$core$events$predicates,isVarCreate$$module$build$src$core$events$predicates,isVarDelete$$module$build$src$core$events$predicates,
isVarRename$$module$build$src$core$events$predicates,isBlockDrag$$module$build$src$core$events$predicates,isSelected$$module$build$src$core$events$predicates,isClick$$module$build$src$core$events$predicates,isBubbleOpen$$module$build$src$core$events$predicates,isTrashcanOpen$$module$build$src$core$events$predicates,isToolboxItemSelect$$module$build$src$core$events$predicates,isThemeChange$$module$build$src$core$events$predicates,isViewportChange$$module$build$src$core$events$predicates,isCommentCreate$$module$build$src$core$events$predicates,
isCommentDelete$$module$build$src$core$events$predicates,isCommentChange$$module$build$src$core$events$predicates,isCommentMove$$module$build$src$core$events$predicates,isCommentResize$$module$build$src$core$events$predicates,isCommentDrag$$module$build$src$core$events$predicates,isCommentCollapse$$module$build$src$core$events$predicates,isFinishedLoading$$module$build$src$core$events$predicates,getRecordUndo$$module$build$src$core$events$utils,fire$$module$build$src$core$events$utils,fireInternal$$module$build$src$core$events$utils,
fireNow$$module$build$src$core$events$utils,enqueueEvent$$module$build$src$core$events$utils,filter$$module$build$src$core$events$utils,clearPendingUndo$$module$build$src$core$events$utils,isEnabled$$module$build$src$core$events$utils,setGroupInternal$$module$build$src$core$events$utils,getDescendantIds$$module$build$src$core$events$utils,fromJson$$module$build$src$core$events$utils,get$$module$build$src$core$events$utils,disableOrphans$$module$build$src$core$events$utils,createSvgElement$$module$build$src$core$utils$dom,
addClass$$module$build$src$core$utils$dom,removeClasses$$module$build$src$core$utils$dom,removeClass$$module$build$src$core$utils$dom,hasClass$$module$build$src$core$utils$dom,removeNode$$module$build$src$core$utils$dom,insertAfter$$module$build$src$core$utils$dom,setCssTransform$$module$build$src$core$utils$dom,startTextWidthCache$$module$build$src$core$utils$dom,stopTextWidthCache$$module$build$src$core$utils$dom,getTextWidth$$module$build$src$core$utils$dom,getFastTextWidth$$module$build$src$core$utils$dom,
getFastTextWidthWithSizeString$$module$build$src$core$utils$dom,measureFontMetrics$$module$build$src$core$utils$dom,isFocusableNode$$module$build$src$core$interfaces$i_focusable_node,isSelectable$$module$build$src$core$interfaces$i_selectable,deepMerge$$module$build$src$core$utils$object,getWorkspaceById$$module$build$src$core$common,getAllWorkspaces$$module$build$src$core$common,registerWorkspace$$module$build$src$core$common,unregisterWorkpace$$module$build$src$core$common,getMainWorkspace$$module$build$src$core$common,
setMainWorkspace$$module$build$src$core$common,getSelected$$module$build$src$core$common,setSelected$$module$build$src$core$common,fireSelectedEvent$$module$build$src$core$common,getParentContainer$$module$build$src$core$common,setParentContainer$$module$build$src$core$common,svgResize$$module$build$src$core$common,getBlockTypeCounts$$module$build$src$core$common,jsonInitFactory$$module$build$src$core$common,defineBlocksWithJsonArray$$module$build$src$core$common,defineBlocksWithJsonArrayInternal$$module$build$src$core$common,
globalShortcutHandler$$module$build$src$core$common,removeElem$$module$build$src$core$utils$array,register$$module$build$src$core$css,inject$$module$build$src$core$css,getSize$$module$build$src$core$utils$style,getSizeInternal$$module$build$src$core$utils$style,getSizeWithDisplay$$module$build$src$core$utils$style,getComputedStyle$$module$build$src$core$utils$style,getPageOffset$$module$build$src$core$utils$style,getViewportPageOffset$$module$build$src$core$utils$style,getBorderBox$$module$build$src$core$utils$style,
scrollIntoContainerView$$module$build$src$core$utils$style,getContainerOffsetToScrollInto$$module$build$src$core$utils$style,getRelativeXY$$module$build$src$core$utils$svg_math,getInjectionDivXY$$module$build$src$core$utils$svg_math,getViewportBBox$$module$build$src$core$utils$svg_math,getDocumentScroll$$module$build$src$core$utils$svg_math,screenToWsCoordinates$$module$build$src$core$utils$svg_math,wsToScreenCoordinates$$module$build$src$core$utils$svg_math,injectDependencies$$module$build$src$core$utils$xml,
domToText$$module$build$src$core$utils$xml,sanitizeText$$module$build$src$core$utils$xml,convertToolboxDefToJson$$module$build$src$core$utils$toolbox,validateToolbox$$module$build$src$core$utils$toolbox,convertFlyoutDefToJsonArray$$module$build$src$core$utils$toolbox,hasCategories$$module$build$src$core$utils$toolbox,hasCategoriesInternal$$module$build$src$core$utils$toolbox,isCategoryCollapsible$$module$build$src$core$utils$toolbox,convertToToolboxJson$$module$build$src$core$utils$toolbox,xmlToJsonArray$$module$build$src$core$utils$toolbox,
addAttributes$$module$build$src$core$utils$toolbox,parseToolboxTree$$module$build$src$core$utils$toolbox,getStartPositionRect$$module$build$src$core$positionable_helpers,getCornerOppositeToolbox$$module$build$src$core$positionable_helpers,bumpPositionRect$$module$build$src$core$positionable_helpers,register$$module$build$src$core$serialization$registry,unregister$$module$build$src$core$serialization$registry,save$$module$build$src$core$serialization$workspace_comments,append$$module$build$src$core$serialization$workspace_comments,
register$$module$build$src$core$clipboard$registry,unregister$$module$build$src$core$clipboard$registry,moveCommentToNotConflict$$module$build$src$core$clipboard$workspace_comment_paster,commentOverlapsOtherExactly$$module$build$src$core$clipboard$workspace_comment_paster,setRole$$module$build$src$core$utils$aria,setState$$module$build$src$core$utils$aria,isSerializable$$module$build$src$core$interfaces$i_serializable,queueRender$$module$build$src$core$render_management,finishQueuedRenders$$module$build$src$core$render_management,
triggerQueuedRenders$$module$build$src$core$render_management,alwaysImmediatelyRender$$module$build$src$core$render_management,queueBlock$$module$build$src$core$render_management,doRenders$$module$build$src$core$render_management,dequeueBlock$$module$build$src$core$render_management,shouldRenderRootBlock$$module$build$src$core$render_management,renderBlock$$module$build$src$core$render_management,alert$$module$build$src$core$dialog,setAlert$$module$build$src$core$dialog,confirm$$module$build$src$core$dialog,
setConfirm$$module$build$src$core$dialog,prompt$$module$build$src$core$dialog,setPrompt$$module$build$src$core$dialog,toast$$module$build$src$core$dialog,setToast$$module$build$src$core$dialog,isLegacyProcedureDefBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks,isLegacyProcedureCallBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks,isVariableBackedParameterModel$$module$build$src$core$interfaces$i_variable_backed_parameter_model,warn$$module$build$src$core$utils$deprecation,
internalFlyoutCategory$$module$build$src$core$variables,flyoutCategory$$module$build$src$core$variables,generateVariableFieldJson$$module$build$src$core$variables,jsonFlyoutCategoryBlocks$$module$build$src$core$variables,xmlFlyoutCategory$$module$build$src$core$variables,flyoutCategoryBlocks$$module$build$src$core$variables,generateUniqueName$$module$build$src$core$variables,generateUniqueNameInternal$$module$build$src$core$variables,generateUniqueNameFromOptions$$module$build$src$core$variables,
createVariableButtonHandler$$module$build$src$core$variables,promptName$$module$build$src$core$variables,nameUsedWithOtherType$$module$build$src$core$variables,nameUsedWithAnyType$$module$build$src$core$variables,nameUsedWithConflictingParam$$module$build$src$core$variables,checkForConflictingParamWithProcedureModels$$module$build$src$core$variables,checkForConflictingParamWithLegacyProcedures$$module$build$src$core$variables,generateVariableFieldDom$$module$build$src$core$variables,createVariable$$module$build$src$core$variables,
getAddedVariables$$module$build$src$core$variables,compareByName$$module$build$src$core$variables,getVariableUsesById$$module$build$src$core$variables,save$$module$build$src$core$serialization$blocks,saveAttributes$$module$build$src$core$serialization$blocks,saveCoords$$module$build$src$core$serialization$blocks,saveExtraState$$module$build$src$core$serialization$blocks,saveIcons$$module$build$src$core$serialization$blocks,saveFields$$module$build$src$core$serialization$blocks,saveInputBlocks$$module$build$src$core$serialization$blocks,
saveNextBlocks$$module$build$src$core$serialization$blocks,saveConnection$$module$build$src$core$serialization$blocks,append$$module$build$src$core$serialization$blocks,appendInternal$$module$build$src$core$serialization$blocks,appendPrivate$$module$build$src$core$serialization$blocks,checkNewVariables$$module$build$src$core$serialization$blocks,loadCoords$$module$build$src$core$serialization$blocks,loadAttributes$$module$build$src$core$serialization$blocks,loadExtraState$$module$build$src$core$serialization$blocks,
tryToConnectParent$$module$build$src$core$serialization$blocks,loadIcons$$module$build$src$core$serialization$blocks,loadFields$$module$build$src$core$serialization$blocks,loadInputBlocks$$module$build$src$core$serialization$blocks,loadNextBlocks$$module$build$src$core$serialization$blocks,loadConnection$$module$build$src$core$serialization$blocks,initBlock$$module$build$src$core$serialization$blocks,hasBubble$$module$build$src$core$interfaces$i_has_bubble,toRadians$$module$build$src$core$utils$math,
toDegrees$$module$build$src$core$utils$math,clamp$$module$build$src$core$utils$math,createDom$$module$build$src$core$dropdowndiv,setBoundsElement$$module$build$src$core$dropdowndiv,getOwner$$module$build$src$core$dropdowndiv,getContentDiv$$module$build$src$core$dropdowndiv,clearContent$$module$build$src$core$dropdowndiv,setColour$$module$build$src$core$dropdowndiv,showPositionedByBlock$$module$build$src$core$dropdowndiv,showPositionedByField$$module$build$src$core$dropdowndiv,getScaledBboxOfBlock$$module$build$src$core$dropdowndiv,
getScaledBboxOfField$$module$build$src$core$dropdowndiv,showPositionedByRect$$module$build$src$core$dropdowndiv,show$$module$build$src$core$dropdowndiv,getPositionBelowMetrics$$module$build$src$core$dropdowndiv,getPositionAboveMetrics$$module$build$src$core$dropdowndiv,getPositionTopOfPageMetrics$$module$build$src$core$dropdowndiv,getPositionX$$module$build$src$core$dropdowndiv,isVisible$$module$build$src$core$dropdowndiv,hideIfOwner$$module$build$src$core$dropdowndiv,hide$$module$build$src$core$dropdowndiv,
hideWithoutAnimation$$module$build$src$core$dropdowndiv,positionInternal$$module$build$src$core$dropdowndiv,repositionForWindowResize$$module$build$src$core$dropdowndiv,shortestStringLength$$module$build$src$core$utils$string,commonWordPrefix$$module$build$src$core$utils$string,commonWordSuffix$$module$build$src$core$utils$string,wrapLine$$module$build$src$core$utils$string,wrapScore$$module$build$src$core$utils$string,wrapMutate$$module$build$src$core$utils$string,wrapToText$$module$build$src$core$utils$string,
setCustomTooltip$$module$build$src$core$tooltip,getCustomTooltip$$module$build$src$core$tooltip,isVisible$$module$build$src$core$tooltip,getDiv$$module$build$src$core$tooltip,getTooltipOfObject$$module$build$src$core$tooltip,getTargetObject$$module$build$src$core$tooltip,createDom$$module$build$src$core$tooltip,bindMouseEvents$$module$build$src$core$tooltip,unbindMouseEvents$$module$build$src$core$tooltip,onMouseOver$$module$build$src$core$tooltip,onMouseOut$$module$build$src$core$tooltip,onMouseMove$$module$build$src$core$tooltip,
dispose$$module$build$src$core$tooltip,hide$$module$build$src$core$tooltip,block$$module$build$src$core$tooltip,unblock$$module$build$src$core$tooltip,renderContent$$module$build$src$core$tooltip,renderDefaultContent$$module$build$src$core$tooltip,getPosition$$module$build$src$core$tooltip,show$$module$build$src$core$tooltip,getHsvSaturation$$module$build$src$core$utils$colour,setHsvSaturation$$module$build$src$core$utils$colour,getHsvValue$$module$build$src$core$utils$colour,setHsvValue$$module$build$src$core$utils$colour,
parse$$module$build$src$core$utils$colour,rgbToHex$$module$build$src$core$utils$colour,hexToRgb$$module$build$src$core$utils$colour,hsvToHex$$module$build$src$core$utils$colour,blend$$module$build$src$core$utils$colour,hueToHex$$module$build$src$core$utils$colour,tokenizeInterpolationInternal$$module$build$src$core$utils$parsing,tokenizeInterpolation$$module$build$src$core$utils$parsing,replaceMessageReferences$$module$build$src$core$utils$parsing,checkMessageReferences$$module$build$src$core$utils$parsing,
parseBlockColour$$module$build$src$core$utils$parsing,getDiv$$module$build$src$core$widgetdiv,testOnly_setDiv$$module$build$src$core$widgetdiv,createDom$$module$build$src$core$widgetdiv,show$$module$build$src$core$widgetdiv,hide$$module$build$src$core$widgetdiv,isVisible$$module$build$src$core$widgetdiv,hideIfOwner$$module$build$src$core$widgetdiv,hideIfOwnerIsInWorkspace$$module$build$src$core$widgetdiv,positionInternal$$module$build$src$core$widgetdiv,positionWithAnchor$$module$build$src$core$widgetdiv,
calculateX$$module$build$src$core$widgetdiv,calculateY$$module$build$src$core$widgetdiv,isRepositionable$$module$build$src$core$widgetdiv,repositionForWindowResize$$module$build$src$core$widgetdiv,getCurrentBlock$$module$build$src$core$contextmenu,setCurrentBlock$$module$build$src$core$contextmenu,show$$module$build$src$core$contextmenu,populate_$$module$build$src$core$contextmenu,position_$$module$build$src$core$contextmenu,createWidget_$$module$build$src$core$contextmenu,haltPropagation$$module$build$src$core$contextmenu,
hide$$module$build$src$core$contextmenu,dispose$$module$build$src$core$contextmenu,mouseToWorkspacePoint$$module$build$src$core$utils$drag,start$$module$build$src$core$utils$drag,move$$module$build$src$core$utils$drag,workspaceToDom$$module$build$src$core$xml,saveWorkspaceComment$$module$build$src$core$xml,variablesToDom$$module$build$src$core$xml,blockToDomWithXY$$module$build$src$core$xml,fieldToDom$$module$build$src$core$xml,allFieldsToDom$$module$build$src$core$xml,blockToDom$$module$build$src$core$xml,
cloneShadow$$module$build$src$core$xml,domToText$$module$build$src$core$xml,domToPrettyText$$module$build$src$core$xml,clearWorkspaceAndLoadFromXml$$module$build$src$core$xml,loadWorkspaceComment$$module$build$src$core$xml,appendDomToWorkspace$$module$build$src$core$xml,domToBlockInternal$$module$build$src$core$xml,domToVariables$$module$build$src$core$xml,mapSupportedXmlTags$$module$build$src$core$xml,applyMutationTagNodes$$module$build$src$core$xml,applyCommentTagNodes$$module$build$src$core$xml,
applyDataTagNodes$$module$build$src$core$xml,applyFieldTagNodes$$module$build$src$core$xml,findChildBlocks$$module$build$src$core$xml,applyInputTagNodes$$module$build$src$core$xml,applyNextTagNodes$$module$build$src$core$xml,domToBlockHeadless$$module$build$src$core$xml,domToField$$module$build$src$core$xml,deleteNext$$module$build$src$core$xml,isElement$$module$build$src$core$xml,register$$module$build$src$core$field_registry,unregister$$module$build$src$core$field_registry,fromJsonInternal$$module$build$src$core$field_registry,
isImageProperties$$module$build$src$core$field_dropdown,unregister$$module$build$src$core$extensions,isRegistered$$module$build$src$core$extensions,apply$$module$build$src$core$extensions,checkNoMutatorProperties$$module$build$src$core$extensions,checkXmlHooks$$module$build$src$core$extensions,checkJsonHooks$$module$build$src$core$extensions,checkMutatorDialog$$module$build$src$core$extensions,checkHasFunctionPair$$module$build$src$core$extensions,checkHasMutatorProperties$$module$build$src$core$extensions,
getMutatorProperties$$module$build$src$core$extensions,mutatorPropertiesMatch$$module$build$src$core$extensions,runAfterPageLoad$$module$build$src$core$extensions,checkDropdownOptionsInTable$$module$build$src$core$extensions,extensionParentTooltip$$module$build$src$core$extensions,point$$module$build$src$core$utils$svg_paths,curve$$module$build$src$core$utils$svg_paths,moveTo$$module$build$src$core$utils$svg_paths,moveBy$$module$build$src$core$utils$svg_paths,lineTo$$module$build$src$core$utils$svg_paths,
line$$module$build$src$core$utils$svg_paths,lineOnAxis$$module$build$src$core$utils$svg_paths,arc$$module$build$src$core$utils$svg_paths,connectReciprocally$$module$build$src$core$connection,getSingleConnection$$module$build$src$core$connection,getConnectionForOrphanedOutput$$module$build$src$core$connection,isIcon$$module$build$src$core$interfaces$i_icon,isCommentIcon$$module$build$src$core$interfaces$i_comment_icon,disposeUiEffect$$module$build$src$core$block_animations,disposeUiStep$$module$build$src$core$block_animations,
connectionUiEffect$$module$build$src$core$block_animations,disconnectUiEffect$$module$build$src$core$block_animations,disconnectUiStep$$module$build$src$core$block_animations,disconnectUiStop$$module$build$src$core$block_animations,moveBlockToNotConflict$$module$build$src$core$clipboard$block_paster,blockOverlapsOtherExactly$$module$build$src$core$clipboard$block_paster,blockIsInSnapRadius$$module$build$src$core$clipboard$block_paster,bumpObjectIntoBounds$$module$build$src$core$bump_objects,bumpIntoBoundsHandler$$module$build$src$core$bump_objects,
extractObjectFromEvent$$module$build$src$core$bump_objects,bumpTopObjectsIntoBounds$$module$build$src$core$bump_objects,isDeletable$$module$build$src$core$interfaces$i_deletable,getBlockNavigationCandidates$$module$build$src$core$keyboard_nav$block_navigation_policy,navigateStacks$$module$build$src$core$keyboard_nav$block_navigation_policy,navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy,register$$module$build$src$core$icons$registry,unregister$$module$build$src$core$icons$registry,
isDraggable$$module$build$src$core$interfaces$i_draggable,isAutoHideable$$module$build$src$core$interfaces$i_autohideable,isProcedureBlock$$module$build$src$core$interfaces$i_procedure_block,isObservable$$module$build$src$core$interfaces$i_observable,allProcedures$$module$build$src$core$procedures,procTupleComparator$$module$build$src$core$procedures,isLegalName$$module$build$src$core$procedures,isNameUsed$$module$build$src$core$procedures,xmlFlyoutCategory$$module$build$src$core$procedures,internalFlyoutCategory$$module$build$src$core$procedures,
flyoutCategory$$module$build$src$core$procedures,updateMutatorFlyout$$module$build$src$core$procedures,mutatorOpenListener$$module$build$src$core$procedures,mutatorChangeListener$$module$build$src$core$procedures,getCallers$$module$build$src$core$procedures,blockIsModernCallerFor$$module$build$src$core$procedures,isDynamicShape$$module$build$src$core$renderers$common$constants,isPuzzleTab$$module$build$src$core$renderers$common$constants,isNotch$$module$build$src$core$renderers$common$constants,register$$module$build$src$core$renderers$common$block_rendering,
unregister$$module$build$src$core$renderers$common$block_rendering,init$$module$build$src$core$renderers$common$block_rendering,stringButtonClickHandler$$module$build$src$core$variables_dynamic,numberButtonClickHandler$$module$build$src$core$variables_dynamic,colourButtonClickHandler$$module$build$src$core$variables_dynamic,internalFlyoutCategory$$module$build$src$core$variables_dynamic,flyoutCategory$$module$build$src$core$variables_dynamic,xmlFlyoutCategory$$module$build$src$core$variables_dynamic,
flyoutCategoryBlocks$$module$build$src$core$variables_dynamic,resizeSvgContents$$module$build$src$core$workspace_svg,copy$$module$build$src$core$clipboard,getLastCopiedData$$module$build$src$core$clipboard,setLastCopiedData$$module$build$src$core$clipboard,getLastCopiedWorkspace$$module$build$src$core$clipboard,setLastCopiedWorkspace$$module$build$src$core$clipboard,getLastCopiedLocation$$module$build$src$core$clipboard,setLastCopiedLocation$$module$build$src$core$clipboard,paste$$module$build$src$core$clipboard,
pasteFromData$$module$build$src$core$clipboard,isCopyable$$module$build$src$core$interfaces$i_copyable,registerEscape$$module$build$src$core$shortcut_items,registerDelete$$module$build$src$core$shortcut_items,isCopyable$$module$build$src$core$shortcut_items,isCuttable$$module$build$src$core$shortcut_items,registerCopy$$module$build$src$core$shortcut_items,registerCut$$module$build$src$core$shortcut_items,registerPaste$$module$build$src$core$shortcut_items,registerUndo$$module$build$src$core$shortcut_items,
registerRedo$$module$build$src$core$shortcut_items,registerDefaultShortcuts$$module$build$src$core$shortcut_items,saveProcedure$$module$build$src$core$serialization$procedures,loadProcedure$$module$build$src$core$serialization$procedures,save$$module$build$src$core$serialization$workspaces,load$$module$build$src$core$serialization$workspaces,inject$$module$build$src$core$inject,createDom$$module$build$src$core$inject,createMainWorkspace$$module$build$src$core$inject,init$$module$build$src$core$inject,
bindDocumentEvents$$module$build$src$core$inject,loadSounds$$module$build$src$core$inject,isFullBlockField$$module$build$src$core$contextmenu_items,registerUndo$$module$build$src$core$contextmenu_items,registerRedo$$module$build$src$core$contextmenu_items,registerCleanup$$module$build$src$core$contextmenu_items,toggleOption_$$module$build$src$core$contextmenu_items,registerCollapse$$module$build$src$core$contextmenu_items,registerExpand$$module$build$src$core$contextmenu_items,addDeletableBlocks_$$module$build$src$core$contextmenu_items,
getDeletableBlocks_$$module$build$src$core$contextmenu_items,deleteNext_$$module$build$src$core$contextmenu_items,registerDeleteAll$$module$build$src$core$contextmenu_items,registerWorkspaceOptions_$$module$build$src$core$contextmenu_items,registerDuplicate$$module$build$src$core$contextmenu_items,registerComment$$module$build$src$core$contextmenu_items,registerInline$$module$build$src$core$contextmenu_items,registerCollapseExpandBlock$$module$build$src$core$contextmenu_items,registerDisable$$module$build$src$core$contextmenu_items,
registerDelete$$module$build$src$core$contextmenu_items,registerHelp$$module$build$src$core$contextmenu_items,registerCommentDelete$$module$build$src$core$contextmenu_items,registerCommentDuplicate$$module$build$src$core$contextmenu_items,registerCommentCreate$$module$build$src$core$contextmenu_items,registerBlockOptions_$$module$build$src$core$contextmenu_items,registerCommentOptions$$module$build$src$core$contextmenu_items,registerDefaultOptions$$module$build$src$core$contextmenu_items,isPaster$$module$build$src$core$interfaces$i_paster,
isRenderedElement$$module$build$src$core$interfaces$i_rendered_element,isSelectableToolboxItem$$module$build$src$core$interfaces$i_selectable_toolbox_item,hideChaff$$module$build$src$core$blockly,isFocusableTree$$module$build$src$core$interfaces$i_focusable_tree,$jscomp;
register$$module$build$src$core$registry=function(a,b,c,d){if(!(a instanceof Type$$module$build$src$core$registry)&&typeof a!=="string"||`${a}`.trim()==="")throw Error('Invalid type "'+a+'". The type must be a non-empty string or a Blockly.registry.Type.');a=`${a}`.toLowerCase();if(typeof b!=="string"||b.trim()==="")throw Error('Invalid name "'+b+'". The name must be a non-empty string.');const e=b.toLowerCase();if(!c)throw Error("Can not register a null value");let f=typeMap$$module$build$src$core$registry[a],
g=nameMap$$module$build$src$core$registry[a];f||(f=typeMap$$module$build$src$core$registry[a]=Object.create(null),g=nameMap$$module$build$src$core$registry[a]=Object.create(null));validate$$module$build$src$core$registry(a,c);if(!d&&f[e]&&f[e]!==c)throw Error('Name "'+e+'" with type "'+a+'" already registered.');f[e]=c;g[e]=b};
validate$$module$build$src$core$registry=function(a,b){switch(a){case String(Type$$module$build$src$core$registry.FIELD):if(typeof b.fromJson!=="function")throw Error('Type "'+a+'" must have a fromJson function');}};
unregister$$module$build$src$core$registry=function(a,b){a=`${a}`.toLowerCase();b=b.toLowerCase();const c=typeMap$$module$build$src$core$registry[a];c&&c[b]?(delete typeMap$$module$build$src$core$registry[a][b],delete nameMap$$module$build$src$core$registry[a][b]):console.warn("Unable to unregister ["+b+"]["+a+"] from the registry.")};
getItem$$module$build$src$core$registry=function(a,b,c){a=`${a}`.toLowerCase();b=b.toLowerCase();const d=typeMap$$module$build$src$core$registry[a];if(!d||!d[b]){b="Unable to find ["+b+"]["+a+"] in the registry.";if(c)throw Error(b+" You must require or register a "+a+" plugin.");console.warn(b);return null}return d[b]};hasItem$$module$build$src$core$registry=function(a,b){a=`${a}`.toLowerCase();b=b.toLowerCase();return(a=typeMap$$module$build$src$core$registry[a])?!!a[b]:!1};
getClass$$module$build$src$core$registry=function(a,b,c){return getItem$$module$build$src$core$registry(a,b,c)};getObject$$module$build$src$core$registry=function(a,b,c){return getItem$$module$build$src$core$registry(a,b,c)};
getAllItems$$module$build$src$core$registry=function(a,b,c){a=`${a}`.toLowerCase();var d=typeMap$$module$build$src$core$registry[a];if(!d){d=`Unable to find [${a}] in the registry.`;if(c)throw Error(`${d} You must require or register a ${a} plugin.`);console.warn(d);return null}if(!b)return d;a=nameMap$$module$build$src$core$registry[a];c=Object.create(null);for(const e of Object.keys(d))c[a[e]]=d[e];return c};
getClassFromOptions$$module$build$src$core$registry=function(a,b,c){b=b.plugins[String(a)]||DEFAULT$$module$build$src$core$registry;return typeof b==="function"?b:getClass$$module$build$src$core$registry(a,b,c)};longStart$$module$build$src$core$touch=function(a,b){longStop$$module$build$src$core$touch();longPid_$$module$build$src$core$touch=setTimeout(function(){b&&b.handleRightClick(a)},LONGPRESS$$module$build$src$core$touch)};
longStop$$module$build$src$core$touch=function(){longPid_$$module$build$src$core$touch&&(clearTimeout(longPid_$$module$build$src$core$touch),longPid_$$module$build$src$core$touch=0)};clearTouchIdentifier$$module$build$src$core$touch=function(){touchIdentifier_$$module$build$src$core$touch=null};shouldHandleEvent$$module$build$src$core$touch=function(a){return!a.type.startsWith("pointer")||a instanceof PointerEvent&&checkTouchIdentifier$$module$build$src$core$touch(a)};
getTouchIdentifierFromEvent$$module$build$src$core$touch=function(a){return`${a.pointerId}`};checkTouchIdentifier$$module$build$src$core$touch=function(a){const b=getTouchIdentifierFromEvent$$module$build$src$core$touch(a);return touchIdentifier_$$module$build$src$core$touch?touchIdentifier_$$module$build$src$core$touch===b:a.type==="pointerdown"?(touchIdentifier_$$module$build$src$core$touch=b,!0):!1};
conditionalBind$$module$build$src$core$browser_events=function(a,b,c,d,e){function f(h){if(e||shouldHandleEvent$$module$build$src$core$touch(h))c?d.call(c,h):d(h)}const g=[];if(b in TOUCH_MAP$$module$build$src$core$touch)for(let h=0;h<TOUCH_MAP$$module$build$src$core$touch[b].length;h++){const k=TOUCH_MAP$$module$build$src$core$touch[b][h];a.addEventListener(k,f,!1);g.push([a,k,f])}else a.addEventListener(b,f,!1),g.push([a,b,f]);return g};
bind$$module$build$src$core$browser_events=function(a,b,c,d){function e(g){c?d.call(c,g):d(g)}const f=[];if(b in TOUCH_MAP$$module$build$src$core$touch)for(let g=0;g<TOUCH_MAP$$module$build$src$core$touch[b].length;g++){const h=TOUCH_MAP$$module$build$src$core$touch[b][g];a.addEventListener(h,e,!1);f.push([a,h,e])}else a.addEventListener(b,e,!1),f.push([a,b,e]);return f};
unbind$$module$build$src$core$browser_events=function(a){const b=a[a.length-1][2];for(;a.length;){const [c,d,e]=a.pop();c.removeEventListener(d,e,!1)}return b};
isTargetInput$$module$build$src$core$browser_events=function(a){if(a.target instanceof HTMLElement){if(a.target.isContentEditable||a.target.getAttribute("data-is-text-input")==="true")return!0;if(a.target instanceof HTMLInputElement)return a=a.target,a.type==="text"||a.type==="number"||a.type==="email"||a.type==="password"||a.type==="search"||a.type==="tel"||a.type==="url";if(a.target instanceof HTMLTextAreaElement)return!0}return!1};
isRightButton$$module$build$src$core$browser_events=function(a){return a.ctrlKey&&MAC$$module$build$src$core$utils$useragent?!0:a.button===2};mouseToSvg$$module$build$src$core$browser_events=function(a,b,c){const d=b.createSVGPoint();d.x=a.clientX;d.y=a.clientY;c||(c=b.getScreenCTM().inverse());return d.matrixTransform(c)};
getScrollDeltaPixels$$module$build$src$core$browser_events=function(a){switch(a.deltaMode){default:return{x:a.deltaX,y:a.deltaY};case 1:return{x:a.deltaX*LINE_MODE_MULTIPLIER$$module$build$src$core$browser_events,y:a.deltaY*LINE_MODE_MULTIPLIER$$module$build$src$core$browser_events};case 2:return{x:a.deltaX*PAGE_MODE_MULTIPLIER$$module$build$src$core$browser_events,y:a.deltaY*PAGE_MODE_MULTIPLIER$$module$build$src$core$browser_events}}};
getNextUniqueId$$module$build$src$core$utils$idgenerator=function(){return"blockly-"+(nextId$$module$build$src$core$utils$idgenerator++).toString(36)};genUid$$module$build$src$core$utils$idgenerator=function(){return internal$$module$build$src$core$utils$idgenerator.genUid()};isBlockCreate$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.BLOCK_CREATE};
isBlockDelete$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.BLOCK_DELETE};isBlockChange$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.BLOCK_CHANGE};isBlockFieldIntermediateChange$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.BLOCK_FIELD_INTERMEDIATE_CHANGE};
isBlockMove$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.BLOCK_MOVE};isVarCreate$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.VAR_CREATE};isVarDelete$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.VAR_DELETE};isVarRename$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.VAR_RENAME};
isBlockDrag$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.BLOCK_DRAG};isSelected$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.SELECTED};isClick$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.CLICK};isBubbleOpen$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.BUBBLE_OPEN};
isTrashcanOpen$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.TRASHCAN_OPEN};isToolboxItemSelect$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.TOOLBOX_ITEM_SELECT};isThemeChange$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.THEME_CHANGE};
isViewportChange$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.VIEWPORT_CHANGE};isCommentCreate$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.COMMENT_CREATE};isCommentDelete$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.COMMENT_DELETE};
isCommentChange$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.COMMENT_CHANGE};isCommentMove$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.COMMENT_MOVE};isCommentResize$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.COMMENT_RESIZE};
isCommentDrag$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.COMMENT_DRAG};isCommentCollapse$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.COMMENT_COLLAPSE};isFinishedLoading$$module$build$src$core$events$predicates=function(a){return a.type===EventType$$module$build$src$core$events$type.FINISHED_LOADING};
$.setRecordUndo$$module$build$src$core$events$utils=function(a){recordUndo$$module$build$src$core$events$utils=a};getRecordUndo$$module$build$src$core$events$utils=function(){return recordUndo$$module$build$src$core$events$utils};fire$$module$build$src$core$events$utils=function(a){TEST_ONLY$$module$build$src$core$events$utils.fireInternal(a)};
fireInternal$$module$build$src$core$events$utils=function(a){if(isEnabled$$module$build$src$core$events$utils()){if(!FIRE_QUEUE$$module$build$src$core$events$utils.length)try{requestAnimationFrame(()=>{setTimeout(fireNow$$module$build$src$core$events$utils,0)})}catch(b){setTimeout(fireNow$$module$build$src$core$events$utils,0)}enqueueEvent$$module$build$src$core$events$utils(a)}};
fireNow$$module$build$src$core$events$utils=function(){const a=filter$$module$build$src$core$events$utils(FIRE_QUEUE$$module$build$src$core$events$utils);FIRE_QUEUE$$module$build$src$core$events$utils.length=0;for(const b of a){if(!b.workspaceId)continue;let c;(c=getWorkspaceById$$module$build$src$core$common(b.workspaceId))==null||c.fireChangeListener(b)}};
enqueueEvent$$module$build$src$core$events$utils=function(a){if(isBlockChange$$module$build$src$core$events$predicates(a)&&a.element==="mutation"){let b;for(b=FIRE_QUEUE$$module$build$src$core$events$utils.length;b>0;b--){const c=FIRE_QUEUE$$module$build$src$core$events$utils[b-1];if(c.group!==a.group||c.workspaceId!==a.workspaceId||!isBlockMove$$module$build$src$core$events$predicates(c)||c.newParentId!==a.blockId)break}FIRE_QUEUE$$module$build$src$core$events$utils.splice(b,0,a)}else FIRE_QUEUE$$module$build$src$core$events$utils.push(a)};
filter$$module$build$src$core$events$utils=function(a){const b=[];for(const c of a)if(a=b[b.length-1],!c.isNull())if(a&&a.workspaceId===c.workspaceId&&a.group===c.group)if(isBlockMove$$module$build$src$core$events$predicates(c)&&isBlockMove$$module$build$src$core$events$predicates(a)&&c.blockId===a.blockId){if(a.newParentId=c.newParentId,a.newInputName=c.newInputName,a.newCoordinate=c.newCoordinate,a.reason||c.reason){let d,e;a.reason=Array.from(new Set(((d=a.reason)!=null?d:[]).concat((e=c.reason)!=
null?e:[])))}}else isBlockChange$$module$build$src$core$events$predicates(c)&&isBlockChange$$module$build$src$core$events$predicates(a)&&c.blockId===a.blockId&&c.element===a.element&&c.name===a.name?a.newValue=c.newValue:isViewportChange$$module$build$src$core$events$predicates(c)&&isViewportChange$$module$build$src$core$events$predicates(a)?(a.viewTop=c.viewTop,a.viewLeft=c.viewLeft,a.scale=c.scale,a.oldScale=c.oldScale):isClick$$module$build$src$core$events$predicates(c)&&isBubbleOpen$$module$build$src$core$events$predicates(a)||
b.push(c);else b.push(c);return a=b.filter(c=>!c.isNull())};clearPendingUndo$$module$build$src$core$events$utils=function(){for(let a=0,b;b=FIRE_QUEUE$$module$build$src$core$events$utils[a];a++)b.recordUndo=!1};$.disable$$module$build$src$core$events$utils=function(){disabled$$module$build$src$core$events$utils++};$.enable$$module$build$src$core$events$utils=function(){disabled$$module$build$src$core$events$utils--};
isEnabled$$module$build$src$core$events$utils=function(){return disabled$$module$build$src$core$events$utils===0};$.getGroup$$module$build$src$core$events$utils=function(){return group$$module$build$src$core$events$utils};$.setGroup$$module$build$src$core$events$utils=function(a){TEST_ONLY$$module$build$src$core$events$utils.setGroupInternal(a)};
setGroupInternal$$module$build$src$core$events$utils=function(a){group$$module$build$src$core$events$utils=typeof a==="boolean"?a?genUid$$module$build$src$core$utils$idgenerator():"":a};getDescendantIds$$module$build$src$core$events$utils=function(a){const b=[];a=a.getDescendants(!1);for(let c=0,d;d=a[c];c++)b[c]=d.id;return b};
fromJson$$module$build$src$core$events$utils=function(a,b){const c=get$$module$build$src$core$events$utils(a.type);if(!c)throw Error("Unknown event type.");return c.fromJson(a,b)};get$$module$build$src$core$events$utils=function(a){const b=getClass$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,a);if(!b)throw Error(`Event type ${a} not found in registry.`);return b};
disableOrphans$$module$build$src$core$events$utils=function(a){if((isBlockMove$$module$build$src$core$events$predicates(a)||isBlockCreate$$module$build$src$core$events$predicates(a))&&a.workspaceId){var b=getWorkspaceById$$module$build$src$core$common(a.workspaceId);if(!a.blockId)throw Error("Encountered a blockEvent without a proper blockId");if(a=b.getBlockById(a.blockId)){const c=recordUndo$$module$build$src$core$events$utils;try{recordUndo$$module$build$src$core$events$utils=!1;const d=a.getParent();
if(d&&!d.hasDisabledReason(ORPHANED_BLOCK_DISABLED_REASON$$module$build$src$core$events$utils)){const e=a.getDescendants(!1);for(let f=0,g;g=e[f];f++)g.setDisabledReason(!1,ORPHANED_BLOCK_DISABLED_REASON$$module$build$src$core$events$utils)}else if((a.outputConnection||a.previousConnection)&&!b.isDragging()){do a.setDisabledReason(!0,ORPHANED_BLOCK_DISABLED_REASON$$module$build$src$core$events$utils),a=a.getNextBlock();while(a)}}finally{recordUndo$$module$build$src$core$events$utils=c}}}};
createSvgElement$$module$build$src$core$utils$dom=function(a,b,c){a=document.createElementNS(SVG_NS$$module$build$src$core$utils$dom,`${a}`);for(const d in b)a.setAttribute(d,`${b[d]}`);c&&c.appendChild(a);return a};addClass$$module$build$src$core$utils$dom=function(a,b){b=b.split(" ");if(b.every(c=>a.classList.contains(c)))return!1;a.classList.add(...b);return!0};removeClasses$$module$build$src$core$utils$dom=function(a,b){a.classList.remove(...b.split(" "))};
removeClass$$module$build$src$core$utils$dom=function(a,b){b=b.split(" ");if(b.every(c=>!a.classList.contains(c)))return!1;a.classList.remove(...b);return!0};hasClass$$module$build$src$core$utils$dom=function(a,b){return a.classList.contains(b)};removeNode$$module$build$src$core$utils$dom=function(a){return a&&a.parentNode?a.parentNode.removeChild(a):null};
insertAfter$$module$build$src$core$utils$dom=function(a,b){const c=b.nextSibling;b=b.parentNode;if(!b)throw Error("Reference node has no parent.");c?b.insertBefore(a,c):b.appendChild(a)};setCssTransform$$module$build$src$core$utils$dom=function(a,b){a.style.transform=b;a.style["-webkit-transform"]=b};
startTextWidthCache$$module$build$src$core$utils$dom=function(){cacheReference$$module$build$src$core$utils$dom++;cacheWidths$$module$build$src$core$utils$dom||(cacheWidths$$module$build$src$core$utils$dom=Object.create(null))};stopTextWidthCache$$module$build$src$core$utils$dom=function(){cacheReference$$module$build$src$core$utils$dom--;cacheReference$$module$build$src$core$utils$dom||(cacheWidths$$module$build$src$core$utils$dom=null)};
getTextWidth$$module$build$src$core$utils$dom=function(a){const b=a.textContent+"\n"+a.className.baseVal;var c;if(cacheWidths$$module$build$src$core$utils$dom&&(c=cacheWidths$$module$build$src$core$utils$dom[b]))return c;c=window.getComputedStyle(a);c=getFastTextWidthWithSizeString$$module$build$src$core$utils$dom(a,c.fontSize,c.fontWeight,c.fontFamily);cacheWidths$$module$build$src$core$utils$dom&&(cacheWidths$$module$build$src$core$utils$dom[b]=c);return c};
getFastTextWidth$$module$build$src$core$utils$dom=function(a,b,c,d){return getFastTextWidthWithSizeString$$module$build$src$core$utils$dom(a,b+"pt",c,d)};
getFastTextWidthWithSizeString$$module$build$src$core$utils$dom=function(a,b,c,d){const e=a.textContent;a=e+"\n"+a.className.baseVal;var f;if(cacheWidths$$module$build$src$core$utils$dom&&(f=cacheWidths$$module$build$src$core$utils$dom[a]))return f;canvasContext$$module$build$src$core$utils$dom||(f=document.createElement("canvas"),f.className="blocklyComputeCanvas",document.body.appendChild(f),canvasContext$$module$build$src$core$utils$dom=f.getContext("2d"));e&&canvasContext$$module$build$src$core$utils$dom?
(canvasContext$$module$build$src$core$utils$dom.font=c+" "+b+" "+d,f=canvasContext$$module$build$src$core$utils$dom.measureText(e).width):f=0;cacheWidths$$module$build$src$core$utils$dom&&(cacheWidths$$module$build$src$core$utils$dom[a]=f);return f};
measureFontMetrics$$module$build$src$core$utils$dom=function(a,b,c,d){const e=document.createElement("span");e.style.font=c+" "+b+" "+d;e.textContent=a;a=document.createElement("div");a.style.width="1px";a.style.height="0";b=document.createElement("div");b.style.display="flex";b.style.position="fixed";b.style.top="0";b.style.left="0";b.appendChild(e);b.appendChild(a);document.body.appendChild(b);c={height:0,baseline:0};try{b.style.alignItems="baseline",c.baseline=a.offsetTop-e.offsetTop,b.style.alignItems=
"flex-end",c.height=a.offsetTop-e.offsetTop}finally{document.body.removeChild(b)}return c};$.getFocusManager$$module$build$src$core$focus_manager=function(){return FocusManager$$module$build$src$core$focus_manager.getFocusManager()};isFocusableNode$$module$build$src$core$interfaces$i_focusable_node=function(a){return a&&typeof a.getFocusableElement==="function"&&typeof a.getFocusableTree==="function"&&typeof a.onNodeFocus==="function"&&typeof a.onNodeBlur==="function"&&typeof a.canBeFocused==="function"};
isSelectable$$module$build$src$core$interfaces$i_selectable=function(a){return isFocusableNode$$module$build$src$core$interfaces$i_focusable_node(a)&&typeof a.id==="string"&&typeof a.workspace==="object"&&typeof a.select==="function"&&typeof a.unselect==="function"};
deepMerge$$module$build$src$core$utils$object=function(a,b){for(const c in b)b[c]!==null&&Array.isArray(b[c])?a[c]=deepMerge$$module$build$src$core$utils$object(a[c]||[],b[c]):a[c]=b[c]!==null&&typeof b[c]==="object"?deepMerge$$module$build$src$core$utils$object(a[c]||Object.create(null),b[c]):b[c];return a};getWorkspaceById$$module$build$src$core$common=function(a){return WorkspaceDB_$$module$build$src$core$common[a]||null};
getAllWorkspaces$$module$build$src$core$common=function(){const a=[];for(const b in WorkspaceDB_$$module$build$src$core$common)a.push(WorkspaceDB_$$module$build$src$core$common[b]);return a};registerWorkspace$$module$build$src$core$common=function(a){WorkspaceDB_$$module$build$src$core$common[a.id]=a};unregisterWorkpace$$module$build$src$core$common=function(a){delete WorkspaceDB_$$module$build$src$core$common[a.id]};getMainWorkspace$$module$build$src$core$common=function(){return mainWorkspace$$module$build$src$core$common};
setMainWorkspace$$module$build$src$core$common=function(a){mainWorkspace$$module$build$src$core$common=a};getSelected$$module$build$src$core$common=function(){const a=$.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode();return a&&isSelectable$$module$build$src$core$interfaces$i_selectable(a)?a:null};setSelected$$module$build$src$core$common=function(a){$.getFocusManager$$module$build$src$core$focus_manager().focusNode(a)};
fireSelectedEvent$$module$build$src$core$common=function(a){const b=getSelected$$module$build$src$core$common();let c,d,e,f;const g=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.SELECTED))((c=b==null?void 0:b.id)!=null?c:null,(d=a==null?void 0:a.id)!=null?d:null,(f=(e=a==null?void 0:a.workspace.id)!=null?e:b==null?void 0:b.workspace.id)!=null?f:"");fire$$module$build$src$core$events$utils(g)};getParentContainer$$module$build$src$core$common=function(){return parentContainer$$module$build$src$core$common};
setParentContainer$$module$build$src$core$common=function(a){parentContainer$$module$build$src$core$common=a};
svgResize$$module$build$src$core$common=function(a){for(;a.options.parentWorkspace;)a=a.options.parentWorkspace;const b=a.getParentSvg(),c=a.getCachedParentSvgSize();var d=b.parentElement;if(d instanceof HTMLElement){var e=d.offsetWidth;d=d.offsetHeight;c.width!==e&&(b.setAttribute("width",e+"px"),a.setCachedParentSvgSize(e,null));c.height!==d&&(b.setAttribute("height",d+"px"),a.setCachedParentSvgSize(null,d));a.resize()}};
getBlockTypeCounts$$module$build$src$core$common=function(a,b){const c=Object.create(null),d=a.getDescendants(!0);b&&(a=a.getNextBlock())&&(a=d.indexOf(a),d.splice(a,d.length-a));for(let e=0,f;f=d[e];e++)c[f.type]?c[f.type]++:c[f.type]=1;return c};jsonInitFactory$$module$build$src$core$common=function(a){return function(){this.jsonInit(a)}};defineBlocksWithJsonArray$$module$build$src$core$common=function(a){TEST_ONLY$$module$build$src$core$common.defineBlocksWithJsonArrayInternal(a)};
defineBlocksWithJsonArrayInternal$$module$build$src$core$common=function(a){$.defineBlocks$$module$build$src$core$common($.createBlockDefinitionsFromJsonArray$$module$build$src$core$common(a))};
$.createBlockDefinitionsFromJsonArray$$module$build$src$core$common=function(a){const b={};for(let c=0;c<a.length;c++){const d=a[c];if(!d){console.warn(`Block definition #${c} in JSON array is ${d}. Skipping`);continue}const e=d.type;e?b[e]={init:jsonInitFactory$$module$build$src$core$common(d)}:console.warn(`Block definition #${c} in JSON array is missing a type attribute. `+"Skipping.")}return b};
$.defineBlocks$$module$build$src$core$common=function(a){for(const b of Object.keys(a)){const c=a[b];b in Blocks$$module$build$src$core$blocks&&console.warn(`Block definition "${b}" overwrites previous definition.`);Blocks$$module$build$src$core$blocks[b]=c}};
globalShortcutHandler$$module$build$src$core$common=function(a){let b=getMainWorkspace$$module$build$src$core$common();const c=$.getFocusManager$$module$build$src$core$focus_manager().getFocusedTree();for(const d of getAllWorkspaces$$module$build$src$core$common())if(c===d){b=d;break}if(!isTargetInput$$module$build$src$core$browser_events(a)&&b&&(!b.rendered||b.isFlyout||b.isVisible()))ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.onKeyDown(b,a)};
removeElem$$module$build$src$core$utils$array=function(a,b){b=a.indexOf(b);if(b===-1)return!1;a.splice(b,1);return!0};register$$module$build$src$core$css=function(a){if(injected$$module$build$src$core$css)throw Error("CSS already injected");content$$module$build$src$core$css+="\n"+a};
inject$$module$build$src$core$css=function(a,b){injected$$module$build$src$core$css||(injected$$module$build$src$core$css=!0,a&&(a=b.replace(/[\\/]$/,""),b=content$$module$build$src$core$css.replace(/<<<PATH>>>/g,a),content$$module$build$src$core$css="",a=document.createElement("style"),a.id="blockly-common-style",b=document.createTextNode(b),a.appendChild(b),document.head.insertBefore(a,document.head.firstChild)))};getSize$$module$build$src$core$utils$style=function(a){return TEST_ONLY$$module$build$src$core$utils$style.getSizeInternal(a)};
getSizeInternal$$module$build$src$core$utils$style=function(a){if(getComputedStyle$$module$build$src$core$utils$style(a,"display")!=="none")return getSizeWithDisplay$$module$build$src$core$utils$style(a);const b=a.style,c=b.display,d=b.visibility,e=b.position;b.visibility="hidden";b.position="absolute";b.display="inline";const f=a.offsetWidth;a=a.offsetHeight;b.display=c;b.position=e;b.visibility=d;return new Size$$module$build$src$core$utils$size(f,a)};
getSizeWithDisplay$$module$build$src$core$utils$style=function(a){return new Size$$module$build$src$core$utils$size(a.offsetWidth,a.offsetHeight)};getComputedStyle$$module$build$src$core$utils$style=function(a,b){a=window.getComputedStyle(a);return a[b]||a.getPropertyValue(b)};
getPageOffset$$module$build$src$core$utils$style=function(a){const b=new Coordinate$$module$build$src$core$utils$coordinate(0,0);a=a.getBoundingClientRect();var c=document.documentElement;c=new Coordinate$$module$build$src$core$utils$coordinate(window.pageXOffset||c.scrollLeft,window.pageYOffset||c.scrollTop);b.x=a.left+c.x;b.y=a.top+c.y;return b};
getViewportPageOffset$$module$build$src$core$utils$style=function(){const a=document.body,b=document.documentElement;return new Coordinate$$module$build$src$core$utils$coordinate(a.scrollLeft||b.scrollLeft,a.scrollTop||b.scrollTop)};
getBorderBox$$module$build$src$core$utils$style=function(a){const b=parseFloat(getComputedStyle$$module$build$src$core$utils$style(a,"borderLeftWidth")),c=parseFloat(getComputedStyle$$module$build$src$core$utils$style(a,"borderRightWidth")),d=parseFloat(getComputedStyle$$module$build$src$core$utils$style(a,"borderTopWidth"));a=parseFloat(getComputedStyle$$module$build$src$core$utils$style(a,"borderBottomWidth"));return new Rect$$module$build$src$core$utils$rect(d,a,b,c)};
scrollIntoContainerView$$module$build$src$core$utils$style=function(a,b,c){a=getContainerOffsetToScrollInto$$module$build$src$core$utils$style(a,b,c);b.scrollLeft=a.x;b.scrollTop=a.y};
getContainerOffsetToScrollInto$$module$build$src$core$utils$style=function(a,b,c){var d=getPageOffset$$module$build$src$core$utils$style(a),e=getPageOffset$$module$build$src$core$utils$style(b),f=getBorderBox$$module$build$src$core$utils$style(b);const g=d.x-e.x-f.left;d=d.y-e.y-f.top;e=getSizeWithDisplay$$module$build$src$core$utils$style(a);a=b.clientWidth-e.width;e=b.clientHeight-e.height;f=b.scrollLeft;b=b.scrollTop;c?(f+=g-a/2,b+=d-e/2):(f+=Math.min(g,Math.max(g-a,0)),b+=Math.min(d,Math.max(d-
e,0)));return new Coordinate$$module$build$src$core$utils$coordinate(f,b)};
getRelativeXY$$module$build$src$core$utils$svg_math=function(a){const b=new Coordinate$$module$build$src$core$utils$coordinate(0,0);var c=a.x&&a.getAttribute("x");const d=a.y&&a.getAttribute("y");c&&(b.x=parseInt(c));d&&(b.y=parseInt(d));if(c=(c=a.getAttribute("transform"))&&c.match(XY_REGEX$$module$build$src$core$utils$svg_math))b.x+=Number(c[1]),c[3]&&(b.y+=Number(c[3]));(a=a.getAttribute("style"))&&a.includes("translate")&&(a=a.match(XY_STYLE_REGEX$$module$build$src$core$utils$svg_math))&&(b.x+=
Number(a[1]),a[3]&&(b.y+=Number(a[3])));return b};getInjectionDivXY$$module$build$src$core$utils$svg_math=function(a){let b=0,c=0;for(;a;){const d=getRelativeXY$$module$build$src$core$utils$svg_math(a);b+=d.x;c+=d.y;if((" "+(a.getAttribute("class")||"")+" ").includes(" injectionDiv "))break;a=a.parentNode}return new Coordinate$$module$build$src$core$utils$coordinate(b,c)};
getViewportBBox$$module$build$src$core$utils$svg_math=function(){const a=getViewportPageOffset$$module$build$src$core$utils$style();return new Rect$$module$build$src$core$utils$rect(a.y,document.documentElement.clientHeight+a.y,a.x,document.documentElement.clientWidth+a.x)};getDocumentScroll$$module$build$src$core$utils$svg_math=function(){const a=document.documentElement,b=window;return new Coordinate$$module$build$src$core$utils$coordinate(b.pageXOffset||a.scrollLeft,b.pageYOffset||a.scrollTop)};
screenToWsCoordinates$$module$build$src$core$utils$svg_math=function(a,b){var c=b.x;b=b.y;const d=a.getInjectionDiv().getBoundingClientRect();c=new Coordinate$$module$build$src$core$utils$coordinate(c-d.left,b-d.top);b=a.getOriginOffsetInPixels();return Coordinate$$module$build$src$core$utils$coordinate.difference(c,b).scale(1/a.scale)};
wsToScreenCoordinates$$module$build$src$core$utils$svg_math=function(a,b){var c=b.scale(a.scale);b=c.x;c=c.y;const d=a.getInjectionDiv().getBoundingClientRect();a=a.getOriginOffsetInPixels();return new Coordinate$$module$build$src$core$utils$coordinate(b+d.left+a.x,c+d.top+a.y)};
injectDependencies$$module$build$src$core$utils$xml=function(a){({document:document$$module$build$src$core$utils$xml=document$$module$build$src$core$utils$xml,DOMParser:DOMParser$$module$build$src$core$utils$xml=DOMParser$$module$build$src$core$utils$xml,XMLSerializer:XMLSerializer$$module$build$src$core$utils$xml=XMLSerializer$$module$build$src$core$utils$xml}=a);domParser$$module$build$src$core$utils$xml=new DOMParser$$module$build$src$core$utils$xml;xmlSerializer$$module$build$src$core$utils$xml=
new XMLSerializer$$module$build$src$core$utils$xml};$.createElement$$module$build$src$core$utils$xml=function(a){return document$$module$build$src$core$utils$xml.createElementNS(NAME_SPACE$$module$build$src$core$utils$xml,a)};$.createTextNode$$module$build$src$core$utils$xml=function(a){return document$$module$build$src$core$utils$xml.createTextNode(a)};
$.textToDom$$module$build$src$core$utils$xml=function(a){let b=domParser$$module$build$src$core$utils$xml.parseFromString(a,"text/xml");if(b&&b.documentElement&&!b.getElementsByTagName("parsererror").length)return b.documentElement;if((b=domParser$$module$build$src$core$utils$xml.parseFromString(a,"text/html"))&&b.body.firstChild&&b.body.firstChild.nodeName.toLowerCase()==="xml")return b.body.firstChild;throw Error(`DOMParser was unable to parse: ${a}`);};
domToText$$module$build$src$core$utils$xml=function(a){return sanitizeText$$module$build$src$core$utils$xml(xmlSerializer$$module$build$src$core$utils$xml.serializeToString(a))};sanitizeText$$module$build$src$core$utils$xml=function(a){return a.replace(INVALID_CONTROL_CHARS$$module$build$src$core$utils$xml,b=>`&#${b.charCodeAt(0)};`)};
convertToolboxDefToJson$$module$build$src$core$utils$toolbox=function(a){if(!a)return null;if(a instanceof Element||typeof a==="string")a=parseToolboxTree$$module$build$src$core$utils$toolbox(a),a=convertToToolboxJson$$module$build$src$core$utils$toolbox(a);validateToolbox$$module$build$src$core$utils$toolbox(a);return a};
validateToolbox$$module$build$src$core$utils$toolbox=function(a){const b=a.kind;a=a.contents;if(b&&b!==FLYOUT_TOOLBOX_KIND$$module$build$src$core$utils$toolbox&&b!==CATEGORY_TOOLBOX_KIND$$module$build$src$core$utils$toolbox)throw Error("Invalid toolbox kind "+b+". Please supply either "+FLYOUT_TOOLBOX_KIND$$module$build$src$core$utils$toolbox+" or "+CATEGORY_TOOLBOX_KIND$$module$build$src$core$utils$toolbox);if(!a)throw Error("Toolbox must have a contents attribute.");};
convertFlyoutDefToJsonArray$$module$build$src$core$utils$toolbox=function(a){return a?a.contents?a.contents:Array.isArray(a)&&a.length>0&&!a[0].nodeType?a:xmlToJsonArray$$module$build$src$core$utils$toolbox(a):[]};hasCategories$$module$build$src$core$utils$toolbox=function(a){return TEST_ONLY$$module$build$src$core$utils$toolbox.hasCategoriesInternal(a)};
hasCategoriesInternal$$module$build$src$core$utils$toolbox=function(a){if(!a)return!1;const b=a.kind;return b?b===CATEGORY_TOOLBOX_KIND$$module$build$src$core$utils$toolbox:!!a.contents.filter(c=>c.kind.toUpperCase()==="CATEGORY").length};isCategoryCollapsible$$module$build$src$core$utils$toolbox=function(a){return a&&a.contents?!!a.contents.filter(function(b){return b.kind.toUpperCase()==="CATEGORY"}).length:!1};
convertToToolboxJson$$module$build$src$core$utils$toolbox=function(a){const b={contents:xmlToJsonArray$$module$build$src$core$utils$toolbox(a)};a instanceof Node&&addAttributes$$module$build$src$core$utils$toolbox(a,b);return b};
xmlToJsonArray$$module$build$src$core$utils$toolbox=function(a){const b=[];let c=a.childNodes;c||(c=a);for(let d=0,e;e=c[d];d++){if(!e.tagName)continue;a={};const f=e.tagName.toUpperCase();a.kind=f;f==="BLOCK"?a.blockxml=e:e.childNodes&&e.childNodes.length>0&&(a.contents=xmlToJsonArray$$module$build$src$core$utils$toolbox(e));addAttributes$$module$build$src$core$utils$toolbox(e,a);b.push(a)}return b};
addAttributes$$module$build$src$core$utils$toolbox=function(a,b){for(let c=0;c<a.attributes.length;c++){const d=a.attributes[c];d.nodeName.includes("css-")?(b.cssconfig=b.cssconfig||{},b.cssconfig[d.nodeName.replace("css-","")]=d.value):b[d.nodeName]=d.value}};
parseToolboxTree$$module$build$src$core$utils$toolbox=function(a){let b=null;if(a)if(typeof a==="string"){if(b=$.textToDom$$module$build$src$core$utils$xml(a),b.nodeName.toLowerCase()!=="xml")throw TypeError("Toolbox should be an <xml> document.");}else a instanceof Element&&(b=a);return b};
getStartPositionRect$$module$build$src$core$positionable_helpers=function(a,b,c,d,e,f){const g=f.scrollbar&&f.scrollbar.canScrollVertically();a.horizontal===horizontalPosition$$module$build$src$core$positionable_helpers.LEFT?(c=e.absoluteMetrics.left+c,g&&f.RTL&&(c+=Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness)):(c=e.absoluteMetrics.left+e.viewMetrics.width-b.width-c,g&&!f.RTL&&(c-=Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness));a.vertical===verticalPosition$$module$build$src$core$positionable_helpers.TOP?
a=e.absoluteMetrics.top+d:(a=e.absoluteMetrics.top+e.viewMetrics.height-b.height-d,f.scrollbar&&f.scrollbar.canScrollHorizontally()&&(a-=Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness));return new Rect$$module$build$src$core$utils$rect(a,a+b.height,c,c+b.width)};
getCornerOppositeToolbox$$module$build$src$core$positionable_helpers=function(a,b){return{horizontal:b.toolboxMetrics.position===Position$$module$build$src$core$utils$toolbox.LEFT||a.horizontalLayout&&!a.RTL?horizontalPosition$$module$build$src$core$positionable_helpers.RIGHT:horizontalPosition$$module$build$src$core$positionable_helpers.LEFT,vertical:b.toolboxMetrics.position===Position$$module$build$src$core$utils$toolbox.BOTTOM?verticalPosition$$module$build$src$core$positionable_helpers.TOP:verticalPosition$$module$build$src$core$positionable_helpers.BOTTOM}};
bumpPositionRect$$module$build$src$core$positionable_helpers=function(a,b,c,d){const e=a.left,f=a.right-a.left,g=a.bottom-a.top;for(let h=0;h<d.length;h++){const k=d[h];a.intersects(k)&&(a=c===bumpDirection$$module$build$src$core$positionable_helpers.UP?k.top-g-b:k.bottom+b,a=new Rect$$module$build$src$core$utils$rect(a,a+g,e,e+f),h=-1)}return a};
register$$module$build$src$core$serialization$registry=function(a,b){register$$module$build$src$core$registry(Type$$module$build$src$core$registry.SERIALIZER,a,b)};unregister$$module$build$src$core$serialization$registry=function(a){unregister$$module$build$src$core$registry(Type$$module$build$src$core$registry.SERIALIZER,a)};
save$$module$build$src$core$serialization$workspace_comments=function(a,{addCoordinates:b=!1,saveIds:c=!0}={}){const d=a.workspace,e=Object.create(null);e.height=a.getSize().height;e.width=a.getSize().width;c&&(e.id=a.id);b&&(b=a.getRelativeToSurfaceXY(),e.x=d.RTL?d.getWidth()-b.x:b.x,e.y=b.y);a.getText()&&(e.text=a.getText());a.isCollapsed()&&(e.collapsed=!0);a.isOwnEditable()||(e.editable=!1);a.isOwnMovable()||(e.movable=!1);a.isOwnDeletable()||(e.deletable=!1);return e};
append$$module$build$src$core$serialization$workspace_comments=function(a,b,{recordUndo:c=!1}={}){const d=getRecordUndo$$module$build$src$core$events$utils();$.setRecordUndo$$module$build$src$core$events$utils(c);c=b.newComment(a.id);a.text!==void 0&&c.setText(a.text);if(a.x!==void 0||a.y!==void 0){const f=c.getRelativeToSurfaceXY();let g,h=(g=a.x)!=null?g:f.x;h=b.RTL?b.getWidth()-h:h;var e;b=(e=a.y)!=null?e:f.y;c.moveTo(new Coordinate$$module$build$src$core$utils$coordinate(h,b))}if(a.width!==void 0||
a.height){e=c.getSize();let f,g;c.setSize(new Size$$module$build$src$core$utils$size((f=a.width)!=null?f:e.width,(g=a.height)!=null?g:e.height))}a.collapsed!==void 0&&c.setCollapsed(a.collapsed);a.editable!==void 0&&c.setEditable(a.editable);a.movable!==void 0&&c.setMovable(a.movable);a.deletable!==void 0&&c.setDeletable(a.deletable);$.setRecordUndo$$module$build$src$core$events$utils(d);return c};
register$$module$build$src$core$clipboard$registry=function(a,b){register$$module$build$src$core$registry(Type$$module$build$src$core$registry.PASTER,a,b)};unregister$$module$build$src$core$clipboard$registry=function(a){unregister$$module$build$src$core$registry(Type$$module$build$src$core$registry.PASTER,a)};
moveCommentToNotConflict$$module$build$src$core$clipboard$workspace_comment_paster=function(a){const b=a.workspace,c=a.getRelativeToSurfaceXY(),d=new Coordinate$$module$build$src$core$utils$coordinate(0,0),e=b.getTopComments(!1).filter(f=>f.id!==a.id).map(f=>f.getRelativeToSurfaceXY());for(;commentOverlapsOtherExactly$$module$build$src$core$clipboard$workspace_comment_paster(Coordinate$$module$build$src$core$utils$coordinate.sum(c,d),e);)d.translate(b.RTL?-30:30,30);a.moveTo(Coordinate$$module$build$src$core$utils$coordinate.sum(c,
d))};commentOverlapsOtherExactly$$module$build$src$core$clipboard$workspace_comment_paster=function(a,b){return b.some(c=>Math.abs(c.x-a.x)<=1&&Math.abs(c.y-a.y)<=1)};setRole$$module$build$src$core$utils$aria=function(a,b){a.setAttribute(ROLE_ATTRIBUTE$$module$build$src$core$utils$aria,b)};setState$$module$build$src$core$utils$aria=function(a,b,c){Array.isArray(c)&&(c=c.join(" "));a.setAttribute(ARIA_PREFIX$$module$build$src$core$utils$aria+b,`${c}`)};
isSerializable$$module$build$src$core$interfaces$i_serializable=function(a){return a&&typeof a.saveState==="function"&&typeof a.loadState==="function"};
queueRender$$module$build$src$core$render_management=function(a){queueBlock$$module$build$src$core$render_management(a);if(alwaysImmediatelyRender$$module$build$src$core$render_management())return doRenders$$module$build$src$core$render_management(),Promise.resolve();afterRendersPromise$$module$build$src$core$render_management||(afterRendersPromise$$module$build$src$core$render_management=new Promise(b=>{afterRendersResolver$$module$build$src$core$render_management=b;animationRequestId$$module$build$src$core$render_management=
window.requestAnimationFrame(()=>{doRenders$$module$build$src$core$render_management();b()})}));return afterRendersPromise$$module$build$src$core$render_management};finishQueuedRenders$$module$build$src$core$render_management=function(){return afterRendersPromise$$module$build$src$core$render_management?afterRendersPromise$$module$build$src$core$render_management:Promise.resolve()};
triggerQueuedRenders$$module$build$src$core$render_management=function(a){a||window.cancelAnimationFrame(animationRequestId$$module$build$src$core$render_management);doRenders$$module$build$src$core$render_management(a);!a&&afterRendersResolver$$module$build$src$core$render_management&&afterRendersResolver$$module$build$src$core$render_management()};alwaysImmediatelyRender$$module$build$src$core$render_management=function(){return JavaFx$$module$build$src$core$utils$useragent};
queueBlock$$module$build$src$core$render_management=function(a){dirtyBlocks$$module$build$src$core$render_management.add(a);eventGroups$$module$build$src$core$render_management.set(a,$.getGroup$$module$build$src$core$events$utils());const b=a.getParent();b?queueBlock$$module$build$src$core$render_management(b):rootBlocks$$module$build$src$core$render_management.add(a)};
doRenders$$module$build$src$core$render_management=function(a){const b=a?new Set([a]):new Set([...rootBlocks$$module$build$src$core$render_management].map(f=>f.workspace)),c=[...rootBlocks$$module$build$src$core$render_management].filter(shouldRenderRootBlock$$module$build$src$core$render_management).filter(f=>b.has(f.workspace));for(var d of c)renderBlock$$module$build$src$core$render_management(d);for(const f of b)f.resizeContents();for(var e of c)d=e.getRelativeToSurfaceXY(),e.updateComponentLocations(d);
for(const f of c)e=$.getGroup$$module$build$src$core$events$utils(),(d=eventGroups$$module$build$src$core$render_management.get(f))&&$.setGroup$$module$build$src$core$events$utils(d),f.bumpNeighbours(),$.setGroup$$module$build$src$core$events$utils(e);for(const f of c)dequeueBlock$$module$build$src$core$render_management(f);a||(afterRendersPromise$$module$build$src$core$render_management=null)};
dequeueBlock$$module$build$src$core$render_management=function(a){rootBlocks$$module$build$src$core$render_management.delete(a);dirtyBlocks$$module$build$src$core$render_management.delete(a);eventGroups$$module$build$src$core$render_management.delete(a);for(const b of a.getChildren(!1))dequeueBlock$$module$build$src$core$render_management(b)};shouldRenderRootBlock$$module$build$src$core$render_management=function(a){return!a.isDisposed()&&!a.getParent()};
renderBlock$$module$build$src$core$render_management=function(a){if(dirtyBlocks$$module$build$src$core$render_management.has(a)&&a.initialized){for(const b of a.getChildren(!1))renderBlock$$module$build$src$core$render_management(b);a.renderEfficiently()}};alert$$module$build$src$core$dialog=function(a,b){alertImplementation$$module$build$src$core$dialog(a,b)};
setAlert$$module$build$src$core$dialog=function(a=defaultAlert$$module$build$src$core$dialog){alertImplementation$$module$build$src$core$dialog=a};confirm$$module$build$src$core$dialog=function(a,b){confirmImplementation$$module$build$src$core$dialog(a,b)};setConfirm$$module$build$src$core$dialog=function(a=defaultConfirm$$module$build$src$core$dialog){confirmImplementation$$module$build$src$core$dialog=a};
prompt$$module$build$src$core$dialog=function(a,b,c){promptImplementation$$module$build$src$core$dialog(a,b,c)};setPrompt$$module$build$src$core$dialog=function(a=defaultPrompt$$module$build$src$core$dialog){promptImplementation$$module$build$src$core$dialog=a};toast$$module$build$src$core$dialog=function(a,b){toastImplementation$$module$build$src$core$dialog(a,b)};
setToast$$module$build$src$core$dialog=function(a=defaultToast$$module$build$src$core$dialog){toastImplementation$$module$build$src$core$dialog=a};isLegacyProcedureDefBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks=function(a){return a&&typeof a.getProcedureDef==="function"};isLegacyProcedureCallBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks=function(a){return a&&typeof a.getProcedureCall==="function"&&typeof a.renameProcedure==="function"};
isVariableBackedParameterModel$$module$build$src$core$interfaces$i_variable_backed_parameter_model=function(a){return a.getVariableModel!==void 0};warn$$module$build$src$core$utils$deprecation=function(a,b,c,d){a=a+" was deprecated in "+b+" and will be deleted in "+c+".";d&&(a+="\nUse "+d+" instead.");previousWarnings$$module$build$src$core$utils$deprecation.has(a)||(previousWarnings$$module$build$src$core$utils$deprecation.add(a),console.warn(a))};
$.allUsedVarModels$$module$build$src$core$variables=function(a){a=a.getAllBlocks(!1);const b=new Set;for(let c=0;c<a.length;c++){const d=a[c].getVarModels();if(d)for(let e=0;e<d.length;e++){const f=d[e];f.getId()&&b.add(f)}}return Array.from(b.values())};$.allDeveloperVariables$$module$build$src$core$variables=function(a){a=a.getAllBlocks(!1);const b=new Set;for(let d=0,e;e=a[d];d++){var c=e.getDeveloperVariables;if(c){c=c();for(let f=0;f<c.length;f++)b.add(c[f])}}return Array.from(b.values())};
internalFlyoutCategory$$module$build$src$core$variables=function(a){return flyoutCategory$$module$build$src$core$variables(a,!1)};
flyoutCategory$$module$build$src$core$variables=function(a,b=!0){Blocks$$module$build$src$core$blocks.variables_set||Blocks$$module$build$src$core$blocks.variables_get||console.warn("There are no variable blocks, but there is a variable category.");if(b)return warn$$module$build$src$core$utils$deprecation("The XML return value of Blockly.Variables.flyoutCategory()","v12","v13","the same method, but handle a return type of FlyoutItemInfo[] (JSON) instead."),xmlFlyoutCategory$$module$build$src$core$variables(a);
a.registerButtonCallback("CREATE_VARIABLE",function(c){createVariableButtonHandler$$module$build$src$core$variables(c.getTargetWorkspace())});return[{kind:"button",text:"%{BKY_NEW_VARIABLE}",callbackkey:"CREATE_VARIABLE"},...jsonFlyoutCategoryBlocks$$module$build$src$core$variables(a,a.getVariableMap().getVariablesOfType(""),!0)]};generateVariableFieldJson$$module$build$src$core$variables=function(a){return{VAR:{name:a.getName(),type:a.getType()}}};
jsonFlyoutCategoryBlocks$$module$build$src$core$variables=function(a,b,c,d="variables_get",e="variables_set"){c&&(c=Blocks$$module$build$src$core$blocks.math_change);a=[];const f=b.slice(-1)[0];f&&(Blocks$$module$build$src$core$blocks[e]&&a.push({kind:"block",type:e,gap:c?8:24,fields:generateVariableFieldJson$$module$build$src$core$variables(f)}),c&&a.push({kind:"block",type:"math_change",gap:Blocks$$module$build$src$core$blocks[d]?20:8,fields:generateVariableFieldJson$$module$build$src$core$variables(f),
inputs:{DELTA:{shadow:{type:"math_number",fields:{NUM:1}}}}}));Blocks$$module$build$src$core$blocks[d]&&a.push(...b.sort(compareByName$$module$build$src$core$variables).map(g=>({kind:"block",type:d,gap:8,fields:generateVariableFieldJson$$module$build$src$core$variables(g)})));return a};
xmlFlyoutCategory$$module$build$src$core$variables=function(a){let b=[];const c=document.createElement("button");c.setAttribute("text","%{BKY_NEW_VARIABLE}");c.setAttribute("callbackKey","CREATE_VARIABLE");a.registerButtonCallback("CREATE_VARIABLE",function(d){createVariableButtonHandler$$module$build$src$core$variables(d.getTargetWorkspace())});b.push(c);a=flyoutCategoryBlocks$$module$build$src$core$variables(a);return b=b.concat(a)};
flyoutCategoryBlocks$$module$build$src$core$variables=function(a){a=a.getVariableMap().getVariablesOfType("");const b=[];if(a.length>0){var c=a[a.length-1];if(Blocks$$module$build$src$core$blocks.variables_set){var d=$.createElement$$module$build$src$core$utils$xml("block");d.setAttribute("type","variables_set");d.setAttribute("gap",Blocks$$module$build$src$core$blocks.math_change?"8":"24");d.appendChild(generateVariableFieldDom$$module$build$src$core$variables(c));b.push(d)}Blocks$$module$build$src$core$blocks.math_change&&
(d=$.createElement$$module$build$src$core$utils$xml("block"),d.setAttribute("type","math_change"),d.setAttribute("gap",Blocks$$module$build$src$core$blocks.variables_get?"20":"8"),d.appendChild(generateVariableFieldDom$$module$build$src$core$variables(c)),c=$.textToDom$$module$build$src$core$utils$xml('<value name="DELTA"><shadow type="math_number"><field name="NUM">1</field></shadow></value>'),d.appendChild(c),b.push(d));if(Blocks$$module$build$src$core$blocks.variables_get){a.sort(compareByName$$module$build$src$core$variables);
for(let e=0,f;f=a[e];e++)c=$.createElement$$module$build$src$core$utils$xml("block"),c.setAttribute("type","variables_get"),c.setAttribute("gap","8"),c.appendChild(generateVariableFieldDom$$module$build$src$core$variables(f)),b.push(c)}}return b};generateUniqueName$$module$build$src$core$variables=function(a){return TEST_ONLY$$module$build$src$core$variables.generateUniqueNameInternal(a)};
generateUniqueNameInternal$$module$build$src$core$variables=function(a){return generateUniqueNameFromOptions$$module$build$src$core$variables(VAR_LETTER_OPTIONS$$module$build$src$core$variables.charAt(0),a.getVariableMap().getAllVariables().map(b=>b.getName()))};
generateUniqueNameFromOptions$$module$build$src$core$variables=function(a,b){if(!b.length)return a;const c=VAR_LETTER_OPTIONS$$module$build$src$core$variables;let d="",e=c.indexOf(a);for(;;){let f=!1;for(let g=0;g<b.length;g++)if(b[g].toLowerCase()===a){f=!0;break}if(!f)break;e++;e===c.length&&(e=0,d=`${Number(d)+1}`);a=c.charAt(e)+d}return a};
createVariableButtonHandler$$module$build$src$core$variables=function(a,b,c){function d(f){promptName$$module$build$src$core$variables($.Msg$$module$build$src$core$msg.NEW_VARIABLE_TITLE,f,function(g){if(g){var h=nameUsedWithAnyType$$module$build$src$core$variables(g,a);if(h){if(h.getType()===e)var k=$.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS.replace("%1",h.getName());else k=$.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE,k=k.replace("%1",h.getName()).replace("%2",
h.getType());alert$$module$build$src$core$dialog(k,function(){d(g)})}else a.getVariableMap().createVariable(g,e),b&&b(g)}else b&&b(null)})}const e=c||"";d("")};
$.renameVariable$$module$build$src$core$variables=function(a,b,c){function d(e){const f=$.Msg$$module$build$src$core$msg.RENAME_VARIABLE_TITLE.replace("%1",b.getName());promptName$$module$build$src$core$variables(f,e,function(g){if(g){var h=nameUsedWithOtherType$$module$build$src$core$variables(g,b.getType(),a),k=nameUsedWithConflictingParam$$module$build$src$core$variables(b.getName(),g,a);if(h||k){var l="";h?l=$.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE.replace("%1",
h.getName()).replace("%2",h.getType()):k&&(l=$.Msg$$module$build$src$core$msg.VARIABLE_ALREADY_EXISTS_FOR_A_PARAMETER.replace("%1",g).replace("%2",k));alert$$module$build$src$core$dialog(l,function(){d(g)})}else a.getVariableMap().renameVariable(b,g),c&&c(g)}else c&&c(null)})}d("")};
promptName$$module$build$src$core$variables=function(a,b,c){prompt$$module$build$src$core$dialog(a,b,function(d){d&&(d=d.replace(/[\s\xa0]+/g," ").trim(),d===$.Msg$$module$build$src$core$msg.RENAME_VARIABLE||d===$.Msg$$module$build$src$core$msg.NEW_VARIABLE)&&(d=null);c(d)})};nameUsedWithOtherType$$module$build$src$core$variables=function(a,b,c){c=c.getVariableMap().getAllVariables();a=a.toLowerCase();for(let d=0,e;e=c[d];d++)if(e.getName().toLowerCase()===a&&e.getType()!==b)return e;return null};
nameUsedWithAnyType$$module$build$src$core$variables=function(a,b){b=b.getVariableMap().getAllVariables();a=a.toLowerCase();for(let c=0,d;d=b[c];c++)if(d.getName().toLowerCase()===a)return d;return null};nameUsedWithConflictingParam$$module$build$src$core$variables=function(a,b,c){return c.getProcedureMap().getProcedures().length?checkForConflictingParamWithProcedureModels$$module$build$src$core$variables(a,b,c):checkForConflictingParamWithLegacyProcedures$$module$build$src$core$variables(a,b,c)};
checkForConflictingParamWithProcedureModels$$module$build$src$core$variables=function(a,b,c){a=a.toLowerCase();b=b.toLowerCase();c=c.getProcedureMap().getProcedures();for(const e of c){var d=e.getParameters().filter(isVariableBackedParameterModel$$module$build$src$core$interfaces$i_variable_backed_parameter_model).map(f=>f.getVariableModel().getName());if(d&&(c=d.some(f=>f.toLowerCase()===a),d=d.some(f=>f.toLowerCase()===b),c&&d))return e.getName()}return null};
checkForConflictingParamWithLegacyProcedures$$module$build$src$core$variables=function(a,b,c){a=a.toLowerCase();b=b.toLowerCase();c=c.getAllBlocks(!1);for(const e of c){if(!isLegacyProcedureDefBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks(e))continue;c=e.getProcedureDef();var d=c[1];const f=d.some(g=>g.toLowerCase()===a);d=d.some(g=>g.toLowerCase()===b);if(f&&d)return c[0]}return null};
generateVariableFieldDom$$module$build$src$core$variables=function(a){const b=$.createElement$$module$build$src$core$utils$xml("field");b.setAttribute("name","VAR");b.setAttribute("id",a.getId());b.setAttribute("variabletype",a.getType());a=$.createTextNode$$module$build$src$core$utils$xml(a.getName());b.appendChild(a);return b};
$.getOrCreateVariablePackage$$module$build$src$core$variables=function(a,b,c,d){let e=$.getVariable$$module$build$src$core$variables(a,b,c,d);e||(e=createVariable$$module$build$src$core$variables(a,b,c,d));return e};
$.getVariable$$module$build$src$core$variables=function(a,b,c,d){const e=a.getPotentialVariableMap();let f=null;if(b&&(f=a.getVariableById(b),!f&&e&&(f=e.getVariableById(b)),f))return f;if(c){if(d===void 0)throw Error("Tried to look up a variable by name without a type");f=a.getVariable(c,d);!f&&e&&(f=e.getVariable(c,d))}return f};
createVariable$$module$build$src$core$variables=function(a,b,c,d){const e=a.getVariableMap(),f=a.getPotentialVariableMap();c||(c=generateUniqueName$$module$build$src$core$variables(a.isFlyout?a.targetWorkspace:a));return f?f.createVariable(c,d,b!=null?b:void 0):e.createVariable(c,d,b)};getAddedVariables$$module$build$src$core$variables=function(a,b){a=a.getAllVariables();const c=[];if(b.length!==a.length)for(let d=0;d<a.length;d++){const e=a[d];b.includes(e)||c.push(e)}return c};
compareByName$$module$build$src$core$variables=function(a,b){return a.getName().localeCompare(b.getName(),void 0,{sensitivity:"base"})};getVariableUsesById$$module$build$src$core$variables=function(a,b){const c=[];a=a.getAllBlocks(!1);for(let d=0;d<a.length;d++){const e=a[d].getVarModels();if(e)for(let f=0;f<e.length;f++)e[f].getId()===b&&c.push(a[d])}return c};
$.deleteVariable$$module$build$src$core$variables=function(a,b,c){var d=b.getName();const e=getVariableUsesById$$module$build$src$core$variables(a,b.getId());for(let f=e.length-1;f>=0;f--){const g=e[f];if(g.type==="procedures_defnoreturn"||g.type==="procedures_defreturn"){c=String(g.getFieldValue("NAME"));d=$.Msg$$module$build$src$core$msg.CANNOT_DELETE_VARIABLE_PROCEDURE.replace("%1",d).replace("%2",c);alert$$module$build$src$core$dialog(d);return}g===c&&e.splice(f,1)}c&&e.length||e.length>1?(d=
$.Msg$$module$build$src$core$msg.DELETE_VARIABLE_CONFIRMATION.replace("%1",String(e.length+(c&&!c.workspace.isFlyout?1:0))).replace("%2",d),confirm$$module$build$src$core$dialog(d,f=>{f&&b&&a.getVariableMap().deleteVariable(b)})):a.getVariableMap().deleteVariable(b)};
save$$module$build$src$core$serialization$blocks=function(a,{addCoordinates:b=!1,addInputBlocks:c=!0,addNextBlocks:d=!0,doFullSerialization:e=!0,saveIds:f=!0}={}){if(a.isInsertionMarker())return null;const g={type:a.type,id:f?a.id:void 0};b&&saveCoords$$module$build$src$core$serialization$blocks(a,g);saveAttributes$$module$build$src$core$serialization$blocks(a,g);saveExtraState$$module$build$src$core$serialization$blocks(a,g,e);saveIcons$$module$build$src$core$serialization$blocks(a,g,e);saveFields$$module$build$src$core$serialization$blocks(a,
g,e);c&&saveInputBlocks$$module$build$src$core$serialization$blocks(a,g,e,f);d&&saveNextBlocks$$module$build$src$core$serialization$blocks(a,g,e,f);return g};
saveAttributes$$module$build$src$core$serialization$blocks=function(a,b){a.isCollapsed()&&(b.collapsed=!0);a.isEnabled()||(b.disabledReasons=Array.from(a.getDisabledReasons()));a.isOwnDeletable()||(b.deletable=!1);a.isOwnMovable()||(b.movable=!1);a.isOwnEditable()||(b.editable=!1);a.inputsInline!==void 0&&a.inputsInline!==a.inputsInlineDefault&&(b.inline=a.inputsInline);a.data&&(b.data=a.data)};
saveCoords$$module$build$src$core$serialization$blocks=function(a,b){const c=a.workspace;a=a.getRelativeToSurfaceXY();b.x=Math.round(c.RTL?c.getWidth()-a.x:a.x);b.y=Math.round(a.y)};saveExtraState$$module$build$src$core$serialization$blocks=function(a,b,c){a.saveExtraState?(a=a.saveExtraState(c),a!==null&&(b.extraState=a)):a.mutationToDom&&(a=a.mutationToDom(),a!==null&&(b.extraState=domToText$$module$build$src$core$xml(a).replace(' xmlns="https://developers.google.com/blockly/xml"',"")))};
saveIcons$$module$build$src$core$serialization$blocks=function(a,b,c){const d=Object.create(null);for(const e of a.getIcons())isSerializable$$module$build$src$core$interfaces$i_serializable(e)&&(a=e.saveState(c))&&(d[e.getType().toString()]=a);Object.keys(d).length&&(b.icons=d)};saveFields$$module$build$src$core$serialization$blocks=function(a,b,c){const d=Object.create(null);for(const e of a.getFields())e.isSerializable()&&(d[e.name]=e.saveState(c));Object.keys(d).length&&(b.fields=d)};
saveInputBlocks$$module$build$src$core$serialization$blocks=function(a,b,c,d){const e=Object.create(null);for(let f=0;f<a.inputList.length;f++){const g=a.inputList[f];if(!g.connection)continue;const h=saveConnection$$module$build$src$core$serialization$blocks(g.connection,c,d);h&&(e[g.name]=h)}Object.keys(e).length&&(b.inputs=e)};
saveNextBlocks$$module$build$src$core$serialization$blocks=function(a,b,c,d){a.nextConnection&&(a=saveConnection$$module$build$src$core$serialization$blocks(a.nextConnection,c,d))&&(b.next=a)};saveConnection$$module$build$src$core$serialization$blocks=function(a,b,c){const d=a.getShadowState(!0);a=a.targetBlock();if(!d&&!a)return null;const e=Object.create(null);d&&(e.shadow=d);a&&!a.isShadow()&&(e.block=save$$module$build$src$core$serialization$blocks(a,{doFullSerialization:b,saveIds:c}));return e};
append$$module$build$src$core$serialization$blocks=function(a,b,{recordUndo:c=!1}={}){a=appendInternal$$module$build$src$core$serialization$blocks(a,b,{recordUndo:c});b.rendered&&triggerQueuedRenders$$module$build$src$core$render_management();return a};
appendInternal$$module$build$src$core$serialization$blocks=function(a,b,{parentConnection:c,isShadow:d=!1,recordUndo:e=!1}={}){const f=getRecordUndo$$module$build$src$core$events$utils();$.setRecordUndo$$module$build$src$core$events$utils(e);(e=$.getGroup$$module$build$src$core$events$utils())||$.setGroup$$module$build$src$core$events$utils(!0);$.disable$$module$build$src$core$events$utils();const g=b.getAllVariables();let h;try{h=appendPrivate$$module$build$src$core$serialization$blocks(a,b,{parentConnection:c,
isShadow:d})}finally{$.enable$$module$build$src$core$events$utils()}checkNewVariables$$module$build$src$core$serialization$blocks(b,g);isEnabled$$module$build$src$core$events$utils()&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CREATE))(h));$.setGroup$$module$build$src$core$events$utils(e);$.setRecordUndo$$module$build$src$core$events$utils(f);if(b.rendered){const k=h;setTimeout(()=>{k.disposed||k.setConnectionTracking(!0)},
1)}return h};
appendPrivate$$module$build$src$core$serialization$blocks=function(a,b,{parentConnection:c,isShadow:d=!1}={}){if(!a.type)throw new MissingBlockType$$module$build$src$core$serialization$exceptions(a);const e=b.newBlock(a.type,a.id);e.setShadow(d);loadCoords$$module$build$src$core$serialization$blocks(e,a);loadAttributes$$module$build$src$core$serialization$blocks(e,a);loadExtraState$$module$build$src$core$serialization$blocks(e,a);tryToConnectParent$$module$build$src$core$serialization$blocks(c,e,
a);loadIcons$$module$build$src$core$serialization$blocks(e,a);loadFields$$module$build$src$core$serialization$blocks(e,a);loadInputBlocks$$module$build$src$core$serialization$blocks(e,a);loadNextBlocks$$module$build$src$core$serialization$blocks(e,a);initBlock$$module$build$src$core$serialization$blocks(e,b.rendered);return e};
checkNewVariables$$module$build$src$core$serialization$blocks=function(a,b){if(isEnabled$$module$build$src$core$events$utils())for(a=getAddedVariables$$module$build$src$core$variables(a,b),b=0;b<a.length;b++){const c=a[b];fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.VAR_CREATE))(c))}};
loadCoords$$module$build$src$core$serialization$blocks=function(a,b){let c=b.x===void 0?0:b.x;b=b.y===void 0?0:b.y;const d=a.workspace;c=d.RTL?d.getWidth()-c:c;a.moveBy(c,b)};
loadAttributes$$module$build$src$core$serialization$blocks=function(a,b){b.collapsed&&a.setCollapsed(!0);b.deletable===!1&&a.setDeletable(!1);b.movable===!1&&a.setMovable(!1);b.editable===!1&&a.setEditable(!1);b.enabled===!1&&a.setDisabledReason(!0,MANUALLY_DISABLED$$module$build$src$core$constants);if(Array.isArray(b.disabledReasons))for(const c of b.disabledReasons)a.setDisabledReason(!0,c);b.inline!==void 0&&a.setInputsInline(b.inline);b.data!==void 0&&(a.data=b.data)};
loadExtraState$$module$build$src$core$serialization$blocks=function(a,b){b.extraState&&(a.loadExtraState?a.loadExtraState(b.extraState):a.domToMutation&&a.domToMutation($.textToDom$$module$build$src$core$utils$xml(b.extraState)))};
tryToConnectParent$$module$build$src$core$serialization$blocks=function(a,b,c){if(a){if(a.getSourceBlock().isShadow()&&!b.isShadow())throw new RealChildOfShadow$$module$build$src$core$serialization$exceptions(c);if(a.type===$.inputTypes$$module$build$src$core$inputs$input_types.VALUE){var d=b.outputConnection;if(!d)throw new MissingConnection$$module$build$src$core$serialization$exceptions("output",b,c);}else if(d=b.previousConnection,!d)throw new MissingConnection$$module$build$src$core$serialization$exceptions("previous",
b,c);if(!a.connect(d)){const e=b.workspace.connectionChecker;throw new BadConnectionCheck$$module$build$src$core$serialization$exceptions(e.getErrorMessage(e.canConnectWithReason(d,a,!1),d,a),a.type===$.inputTypes$$module$build$src$core$inputs$input_types.VALUE?"output connection":"previous connection",b,c);}}};
loadIcons$$module$build$src$core$serialization$blocks=function(a,b){if(b.icons){var c=Object.keys(b.icons);for(const e of c){c=b.icons[e];var d=a.getIcon(e);if(!d){d=getClass$$module$build$src$core$registry(Type$$module$build$src$core$registry.ICON,e,!1);if(!d)throw new UnregisteredIcon$$module$build$src$core$serialization$exceptions(e,a,b);d=new d(a);a.addIcon(d)}isSerializable$$module$build$src$core$interfaces$i_serializable(d)&&d.loadState(c)}}};
loadFields$$module$build$src$core$serialization$blocks=function(a,b){if(b.fields){var c=Object.keys(b.fields);for(let d=0;d<c.length;d++){const e=c[d],f=b.fields[e],g=a.getField(e);g?g.loadState(f):console.warn(`Ignoring non-existant field ${e} in block ${a.type}`)}}};
loadInputBlocks$$module$build$src$core$serialization$blocks=function(a,b){if(b.inputs){var c=Object.keys(b.inputs);for(let d=0;d<c.length;d++){const e=c[d],f=a.getInput(e);if(!f||!f.connection)throw new MissingConnection$$module$build$src$core$serialization$exceptions(e,a,b);loadConnection$$module$build$src$core$serialization$blocks(f.connection,b.inputs[e])}}};
loadNextBlocks$$module$build$src$core$serialization$blocks=function(a,b){if(b.next){if(!a.nextConnection)throw new MissingConnection$$module$build$src$core$serialization$exceptions("next",a,b);loadConnection$$module$build$src$core$serialization$blocks(a.nextConnection,b.next)}};loadConnection$$module$build$src$core$serialization$blocks=function(a,b){b.shadow&&a.setShadowState(b.shadow);b.block&&appendPrivate$$module$build$src$core$serialization$blocks(b.block,a.getSourceBlock().workspace,{parentConnection:a})};
initBlock$$module$build$src$core$serialization$blocks=function(a,b){if(b){a.setConnectionTracking(!1);a.initSvg();a.queueRender();for(const c of a.getIcons())c.onLocationChange(a.getRelativeToSurfaceXY())}else a.initModel()};hasBubble$$module$build$src$core$interfaces$i_has_bubble=function(a){return typeof a.bubbleIsVisible==="function"&&typeof a.setBubbleVisible==="function"&&typeof a.getBubble==="function"};toRadians$$module$build$src$core$utils$math=function(a){return a*Math.PI/180};
toDegrees$$module$build$src$core$utils$math=function(a){return a*180/Math.PI};clamp$$module$build$src$core$utils$math=function(a,b,c){if(c<a){const d=c;c=a;a=d}return Math.max(a,Math.min(b,c))};
createDom$$module$build$src$core$dropdowndiv=function(){document.querySelector(".blocklyDropDownDiv")||(div$$module$build$src$core$dropdowndiv=document.createElement("div"),div$$module$build$src$core$dropdowndiv.className="blocklyDropDownDiv",div$$module$build$src$core$dropdowndiv.tabIndex=-1,(getParentContainer$$module$build$src$core$common()||document.body).appendChild(div$$module$build$src$core$dropdowndiv),content$$module$build$src$core$dropdowndiv=document.createElement("div"),content$$module$build$src$core$dropdowndiv.className=
"blocklyDropDownContent",div$$module$build$src$core$dropdowndiv.appendChild(content$$module$build$src$core$dropdowndiv),keydownListener$$module$build$src$core$dropdowndiv=conditionalBind$$module$build$src$core$browser_events(content$$module$build$src$core$dropdowndiv,"keydown",null,globalShortcutHandler$$module$build$src$core$common),arrow$$module$build$src$core$dropdowndiv=document.createElement("div"),arrow$$module$build$src$core$dropdowndiv.className="blocklyDropDownArrow",div$$module$build$src$core$dropdowndiv.appendChild(arrow$$module$build$src$core$dropdowndiv),
div$$module$build$src$core$dropdowndiv.style.opacity="0",div$$module$build$src$core$dropdowndiv.style.transition="transform "+ANIMATION_TIME$$module$build$src$core$dropdowndiv+"s, opacity "+ANIMATION_TIME$$module$build$src$core$dropdowndiv+"s")};setBoundsElement$$module$build$src$core$dropdowndiv=function(a){boundsElement$$module$build$src$core$dropdowndiv=a};getOwner$$module$build$src$core$dropdowndiv=function(){return owner$$module$build$src$core$dropdowndiv};
getContentDiv$$module$build$src$core$dropdowndiv=function(){return content$$module$build$src$core$dropdowndiv};clearContent$$module$build$src$core$dropdowndiv=function(){keydownListener$$module$build$src$core$dropdowndiv&&(unbind$$module$build$src$core$browser_events(keydownListener$$module$build$src$core$dropdowndiv),keydownListener$$module$build$src$core$dropdowndiv=null);div$$module$build$src$core$dropdowndiv.remove();createDom$$module$build$src$core$dropdowndiv()};
setColour$$module$build$src$core$dropdowndiv=function(a,b){div$$module$build$src$core$dropdowndiv.style.backgroundColor=a;div$$module$build$src$core$dropdowndiv.style.borderColor=b};showPositionedByBlock$$module$build$src$core$dropdowndiv=function(a,b,c,d,e=!0){return showPositionedByRect$$module$build$src$core$dropdowndiv(getScaledBboxOfBlock$$module$build$src$core$dropdowndiv(b),a,e,c,d)};
showPositionedByField$$module$build$src$core$dropdowndiv=function(a,b,c,d=!0){positionToField$$module$build$src$core$dropdowndiv=!0;return showPositionedByRect$$module$build$src$core$dropdowndiv(getScaledBboxOfField$$module$build$src$core$dropdowndiv(a),a,d,b,c)};
getScaledBboxOfBlock$$module$build$src$core$dropdowndiv=function(a){var b=a.getSvgRoot();const c=a.workspace.scale,d=a.height*c;a=a.width*c;b=getPageOffset$$module$build$src$core$utils$style(b);return new Rect$$module$build$src$core$utils$rect(b.y,b.y+d,b.x,b.x+a)};getScaledBboxOfField$$module$build$src$core$dropdowndiv=function(a){a=a.getScaledBBox();return new Rect$$module$build$src$core$utils$rect(a.top,a.bottom,a.left,a.right)};
showPositionedByRect$$module$build$src$core$dropdowndiv=function(a,b,c,d,e){const f=a.left+(a.right-a.left)/2,g=a.bottom;a=a.top;e&&(a+=e);e=b.getSourceBlock();let h=e.workspace;for(;h.options.parentWorkspace;)h=h.options.parentWorkspace;setBoundsElement$$module$build$src$core$dropdowndiv(h.getParentSvg().parentNode);return show$$module$build$src$core$dropdowndiv(b,e.RTL,f,g,f,a,c,d)};
show$$module$build$src$core$dropdowndiv=function(a,b,c,d,e,f,g,h){owner$$module$build$src$core$dropdowndiv=a;onHide$$module$build$src$core$dropdowndiv=h||null;div$$module$build$src$core$dropdowndiv.style.direction=b?"rtl":"ltr";a=getMainWorkspace$$module$build$src$core$common();renderedClassName$$module$build$src$core$dropdowndiv=a.getRenderer().getClassName();themeClassName$$module$build$src$core$dropdowndiv=a.getTheme().getClassName();addClass$$module$build$src$core$utils$dom(div$$module$build$src$core$dropdowndiv,
renderedClassName$$module$build$src$core$dropdowndiv);addClass$$module$build$src$core$utils$dom(div$$module$build$src$core$dropdowndiv,themeClassName$$module$build$src$core$dropdowndiv);c=positionInternal$$module$build$src$core$dropdowndiv(c,d,e,f);g&&(returnEphemeralFocus$$module$build$src$core$dropdowndiv=$.getFocusManager$$module$build$src$core$focus_manager().takeEphemeralFocus(div$$module$build$src$core$dropdowndiv));return c};
getPositionBelowMetrics$$module$build$src$core$dropdowndiv=function(a,b,c,d){a=getPositionX$$module$build$src$core$dropdowndiv(a,c.left,c.right,d.width);return{initialX:a.divX,initialY:b,finalX:a.divX,finalY:b+PADDING_Y$$module$build$src$core$dropdowndiv,arrowX:a.arrowX,arrowY:-(ARROW_SIZE$$module$build$src$core$dropdowndiv/2+BORDER_SIZE$$module$build$src$core$dropdowndiv),arrowAtTop:!0,arrowVisible:!0}};
getPositionAboveMetrics$$module$build$src$core$dropdowndiv=function(a,b,c,d){a=getPositionX$$module$build$src$core$dropdowndiv(a,c.left,c.right,d.width);return{initialX:a.divX,initialY:b-d.height,finalX:a.divX,finalY:b-d.height-PADDING_Y$$module$build$src$core$dropdowndiv,arrowX:a.arrowX,arrowY:d.height-BORDER_SIZE$$module$build$src$core$dropdowndiv*2-ARROW_SIZE$$module$build$src$core$dropdowndiv/2,arrowAtTop:!1,arrowVisible:!0}};
getPositionTopOfPageMetrics$$module$build$src$core$dropdowndiv=function(a,b,c){a=getPositionX$$module$build$src$core$dropdowndiv(a,b.left,b.right,c.width);return{initialX:a.divX,initialY:0,finalX:a.divX,finalY:0,arrowAtTop:null,arrowX:null,arrowY:null,arrowVisible:!1}};
getPositionX$$module$build$src$core$dropdowndiv=function(a,b,c,d){b=clamp$$module$build$src$core$utils$math(b,a-d/2,c-d);a=a-ARROW_SIZE$$module$build$src$core$dropdowndiv/2-b;c=ARROW_HORIZONTAL_PADDING$$module$build$src$core$dropdowndiv;a=clamp$$module$build$src$core$utils$math(c,a,d-c-ARROW_SIZE$$module$build$src$core$dropdowndiv);return{arrowX:a,divX:b}};isVisible$$module$build$src$core$dropdowndiv=function(){return!!owner$$module$build$src$core$dropdowndiv};
hideIfOwner$$module$build$src$core$dropdowndiv=function(a,b){return owner$$module$build$src$core$dropdowndiv===a?(b?hideWithoutAnimation$$module$build$src$core$dropdowndiv():hide$$module$build$src$core$dropdowndiv(),!0):!1};
hide$$module$build$src$core$dropdowndiv=function(){div$$module$build$src$core$dropdowndiv.style.transform="translate(0, 0)";div$$module$build$src$core$dropdowndiv.style.opacity="0";animateOutTimer$$module$build$src$core$dropdowndiv=setTimeout(function(){hideWithoutAnimation$$module$build$src$core$dropdowndiv()},ANIMATION_TIME$$module$build$src$core$dropdowndiv*1E3);onHide$$module$build$src$core$dropdowndiv&&(onHide$$module$build$src$core$dropdowndiv(),onHide$$module$build$src$core$dropdowndiv=null)};
hideWithoutAnimation$$module$build$src$core$dropdowndiv=function(){isVisible$$module$build$src$core$dropdowndiv()&&(animateOutTimer$$module$build$src$core$dropdowndiv&&clearTimeout(animateOutTimer$$module$build$src$core$dropdowndiv),onHide$$module$build$src$core$dropdowndiv&&(onHide$$module$build$src$core$dropdowndiv(),onHide$$module$build$src$core$dropdowndiv=null),clearContent$$module$build$src$core$dropdowndiv(),owner$$module$build$src$core$dropdowndiv=null,getMainWorkspace$$module$build$src$core$common().markFocused(),
returnEphemeralFocus$$module$build$src$core$dropdowndiv&&(returnEphemeralFocus$$module$build$src$core$dropdowndiv(),returnEphemeralFocus$$module$build$src$core$dropdowndiv=null))};
positionInternal$$module$build$src$core$dropdowndiv=function(a,b,c,d){a=internal$$module$build$src$core$dropdowndiv.getPositionMetrics(a,b,c,d);a.arrowVisible?(b=a.arrowX,c=a.arrowY,d=a.arrowAtTop?45:225,arrow$$module$build$src$core$dropdowndiv.style.display="",arrow$$module$build$src$core$dropdowndiv.style.transform=`translate(${b}px, ${c}px) rotate(${d}deg)`,arrow$$module$build$src$core$dropdowndiv.setAttribute("class","blocklyDropDownArrow")):arrow$$module$build$src$core$dropdowndiv.style.display=
"none";b=Math.floor(a.initialX);c=Math.floor(a.initialY);d=Math.floor(a.finalX);const e=Math.floor(a.finalY);div$$module$build$src$core$dropdowndiv.style.left=b+"px";div$$module$build$src$core$dropdowndiv.style.top=c+"px";div$$module$build$src$core$dropdowndiv.style.display="block";div$$module$build$src$core$dropdowndiv.style.opacity="1";div$$module$build$src$core$dropdowndiv.style.transform="translate("+(d-b)+"px,"+(e-c)+"px)";return!!a.arrowAtTop};
repositionForWindowResize$$module$build$src$core$dropdowndiv=function(){if(owner$$module$build$src$core$dropdowndiv){var a=owner$$module$build$src$core$dropdowndiv.getSourceBlock();a=positionToField$$module$build$src$core$dropdowndiv?getScaledBboxOfField$$module$build$src$core$dropdowndiv(owner$$module$build$src$core$dropdowndiv):getScaledBboxOfBlock$$module$build$src$core$dropdowndiv(a);const b=a.left+(a.right-a.left)/2;positionInternal$$module$build$src$core$dropdowndiv(b,a.bottom,b,a.top)}else hide$$module$build$src$core$dropdowndiv()};
shortestStringLength$$module$build$src$core$utils$string=function(a){return a.length?a.reduce(function(b,c){return b.length<c.length?b:c}).length:0};
commonWordPrefix$$module$build$src$core$utils$string=function(a,b){if(!a.length)return 0;if(a.length===1)return a[0].length;let c=0;b=b||shortestStringLength$$module$build$src$core$utils$string(a);let d;for(d=0;d<b;d++){var e=a[0][d];for(var f=1;f<a.length;f++)if(e!==a[f][d])return c;e===" "&&(c=d+1)}for(e=1;e<a.length;e++)if((f=a[e][d])&&f!==" ")return c;return b};
commonWordSuffix$$module$build$src$core$utils$string=function(a,b){if(!a.length)return 0;if(a.length===1)return a[0].length;let c=0;b=b||shortestStringLength$$module$build$src$core$utils$string(a);let d;for(d=0;d<b;d++){var e=a[0].substr(-d-1,1);for(var f=1;f<a.length;f++)if(e!==a[f].substr(-d-1,1))return c;e===" "&&(c=d+1)}for(e=1;e<a.length;e++)if((f=a[e].charAt(a[e].length-d-1))&&f!==" ")return c;return b};
$.wrap$$module$build$src$core$utils$string=function(a,b){a=a.split("\n");for(let c=0;c<a.length;c++)a[c]=wrapLine$$module$build$src$core$utils$string(a[c],b);return a.join("\n")};
wrapLine$$module$build$src$core$utils$string=function(a,b){if(a.length<=b)return a;const c=a.trim().split(/\s+/);for(var d=0;d<c.length;d++)c[d].length>b&&(b=c[d].length);var e=-Infinity;let f,g=1;do{d=e;f=a;a=[];e=c.length/g;let h=1;for(let k=0;k<c.length-1;k++)h<(k+1.5)/e?(h++,a[k]=!0):a[k]=!1;a=wrapMutate$$module$build$src$core$utils$string(c,a,b);e=wrapScore$$module$build$src$core$utils$string(c,a,b);a=wrapToText$$module$build$src$core$utils$string(c,a);g++}while(e>d);return f};
wrapScore$$module$build$src$core$utils$string=function(a,b,c){const d=[0],e=[];for(var f=0;f<a.length;f++)d[d.length-1]+=a[f].length,b[f]===!0?(d.push(0),e.push(a[f].charAt(a[f].length-1))):b[f]===!1&&d[d.length-1]++;a=Math.max(...d);b=0;for(f=0;f<d.length;f++)b-=Math.pow(Math.abs(c-d[f]),1.5)*2,b-=Math.pow(a-d[f],1.5),".?!".includes(e[f])?b+=c/3:",;)]}".includes(e[f])&&(b+=c/4);d.length>1&&d[d.length-1]<=d[d.length-2]&&(b+=.5);return b};
wrapMutate$$module$build$src$core$utils$string=function(a,b,c){let d=wrapScore$$module$build$src$core$utils$string(a,b,c),e;for(let f=0;f<b.length-1;f++){if(b[f]===b[f+1])continue;const g=[].concat(b);g[f]=!g[f];g[f+1]=!g[f+1];const h=wrapScore$$module$build$src$core$utils$string(a,g,c);h>d&&(d=h,e=g)}return e?wrapMutate$$module$build$src$core$utils$string(a,e,c):b};
wrapToText$$module$build$src$core$utils$string=function(a,b){const c=[];for(let d=0;d<a.length;d++)c.push(a[d]),b[d]!==void 0&&c.push(b[d]?"\n":" ");return c.join("")};$.isNumber$$module$build$src$core$utils$string=function(a){return/^\s*-?\d+(\.\d+)?\s*$/.test(a)};setCustomTooltip$$module$build$src$core$tooltip=function(a){customTooltip$$module$build$src$core$tooltip=a};getCustomTooltip$$module$build$src$core$tooltip=function(){return customTooltip$$module$build$src$core$tooltip};
isVisible$$module$build$src$core$tooltip=function(){return visible$$module$build$src$core$tooltip};getDiv$$module$build$src$core$tooltip=function(){return containerDiv$$module$build$src$core$tooltip};getTooltipOfObject$$module$build$src$core$tooltip=function(a){if(a=getTargetObject$$module$build$src$core$tooltip(a)){for(a=a.tooltip;typeof a==="function";)a=a();if(typeof a!=="string")throw Error("Tooltip function must return a string.");return a}return""};
getTargetObject$$module$build$src$core$tooltip=function(a){for(;a&&a.tooltip;){if(typeof a.tooltip==="string"||typeof a.tooltip==="function")return a;a=a.tooltip}return null};createDom$$module$build$src$core$tooltip=function(){document.querySelector(".blocklyTooltipDiv")||(containerDiv$$module$build$src$core$tooltip=document.createElement("div"),containerDiv$$module$build$src$core$tooltip.className="blocklyTooltipDiv",(getParentContainer$$module$build$src$core$common()||document.body).appendChild(containerDiv$$module$build$src$core$tooltip))};
bindMouseEvents$$module$build$src$core$tooltip=function(a){a.mouseOverWrapper_=bind$$module$build$src$core$browser_events(a,"pointerover",null,onMouseOver$$module$build$src$core$tooltip);a.mouseOutWrapper_=bind$$module$build$src$core$browser_events(a,"pointerout",null,onMouseOut$$module$build$src$core$tooltip);a.addEventListener("pointermove",onMouseMove$$module$build$src$core$tooltip,!1)};
unbindMouseEvents$$module$build$src$core$tooltip=function(a){a&&(unbind$$module$build$src$core$browser_events(a.mouseOverWrapper_),unbind$$module$build$src$core$browser_events(a.mouseOutWrapper_),a.removeEventListener("pointermove",onMouseMove$$module$build$src$core$tooltip))};
onMouseOver$$module$build$src$core$tooltip=function(a){blocked$$module$build$src$core$tooltip||(a=getTargetObject$$module$build$src$core$tooltip(a.currentTarget),element$$module$build$src$core$tooltip!==a&&(hide$$module$build$src$core$tooltip(),poisonedElement$$module$build$src$core$tooltip=null,element$$module$build$src$core$tooltip=a),clearTimeout(mouseOutPid$$module$build$src$core$tooltip))};
onMouseOut$$module$build$src$core$tooltip=function(a){blocked$$module$build$src$core$tooltip||(mouseOutPid$$module$build$src$core$tooltip=setTimeout(function(){poisonedElement$$module$build$src$core$tooltip=element$$module$build$src$core$tooltip=null;hide$$module$build$src$core$tooltip()},1),clearTimeout(showPid$$module$build$src$core$tooltip),showPid$$module$build$src$core$tooltip=0)};
onMouseMove$$module$build$src$core$tooltip=function(a){if(element$$module$build$src$core$tooltip&&element$$module$build$src$core$tooltip.tooltip&&!blocked$$module$build$src$core$tooltip)if(visible$$module$build$src$core$tooltip){const b=lastX$$module$build$src$core$tooltip-a.pageX;a=lastY$$module$build$src$core$tooltip-a.pageY;Math.sqrt(b*b+a*a)>RADIUS_OK$$module$build$src$core$tooltip&&hide$$module$build$src$core$tooltip()}else poisonedElement$$module$build$src$core$tooltip!==element$$module$build$src$core$tooltip&&
(clearTimeout(showPid$$module$build$src$core$tooltip),lastX$$module$build$src$core$tooltip=a.pageX,lastY$$module$build$src$core$tooltip=a.pageY,showPid$$module$build$src$core$tooltip=setTimeout(show$$module$build$src$core$tooltip,HOVER_MS$$module$build$src$core$tooltip))};dispose$$module$build$src$core$tooltip=function(){poisonedElement$$module$build$src$core$tooltip=element$$module$build$src$core$tooltip=null;hide$$module$build$src$core$tooltip()};
hide$$module$build$src$core$tooltip=function(){visible$$module$build$src$core$tooltip&&(visible$$module$build$src$core$tooltip=!1,containerDiv$$module$build$src$core$tooltip&&(containerDiv$$module$build$src$core$tooltip.style.display="none"));showPid$$module$build$src$core$tooltip&&(clearTimeout(showPid$$module$build$src$core$tooltip),showPid$$module$build$src$core$tooltip=0)};
block$$module$build$src$core$tooltip=function(){hide$$module$build$src$core$tooltip();blocked$$module$build$src$core$tooltip=!0};unblock$$module$build$src$core$tooltip=function(){blocked$$module$build$src$core$tooltip=!1};
renderContent$$module$build$src$core$tooltip=function(){containerDiv$$module$build$src$core$tooltip&&element$$module$build$src$core$tooltip&&(typeof customTooltip$$module$build$src$core$tooltip==="function"?customTooltip$$module$build$src$core$tooltip(containerDiv$$module$build$src$core$tooltip,element$$module$build$src$core$tooltip):renderDefaultContent$$module$build$src$core$tooltip())};
renderDefaultContent$$module$build$src$core$tooltip=function(){var a=getTooltipOfObject$$module$build$src$core$tooltip(element$$module$build$src$core$tooltip);a=$.wrap$$module$build$src$core$utils$string(a,LIMIT$$module$build$src$core$tooltip);a=a.split("\n");for(let b=0;b<a.length;b++){const c=document.createElement("div");c.appendChild(document.createTextNode(a[b]));containerDiv$$module$build$src$core$tooltip.appendChild(c)}};
getPosition$$module$build$src$core$tooltip=function(a){const b=document.documentElement.clientWidth,c=document.documentElement.clientHeight;let d=lastX$$module$build$src$core$tooltip;d=a?d-(OFFSET_X$$module$build$src$core$tooltip+containerDiv$$module$build$src$core$tooltip.offsetWidth):d+OFFSET_X$$module$build$src$core$tooltip;let e=lastY$$module$build$src$core$tooltip+OFFSET_Y$$module$build$src$core$tooltip;e+containerDiv$$module$build$src$core$tooltip.offsetHeight>c+window.scrollY&&(e-=containerDiv$$module$build$src$core$tooltip.offsetHeight+
2*OFFSET_Y$$module$build$src$core$tooltip);a?d=Math.max(MARGINS$$module$build$src$core$tooltip-window.scrollX,d):d+containerDiv$$module$build$src$core$tooltip.offsetWidth>b+window.scrollX-2*MARGINS$$module$build$src$core$tooltip&&(d=b-containerDiv$$module$build$src$core$tooltip.offsetWidth-2*MARGINS$$module$build$src$core$tooltip);return{x:d,y:e}};
show$$module$build$src$core$tooltip=function(){if(!blocked$$module$build$src$core$tooltip&&(poisonedElement$$module$build$src$core$tooltip=element$$module$build$src$core$tooltip,containerDiv$$module$build$src$core$tooltip)){containerDiv$$module$build$src$core$tooltip.textContent="";renderContent$$module$build$src$core$tooltip();var a=element$$module$build$src$core$tooltip.RTL;containerDiv$$module$build$src$core$tooltip.style.direction=a?"rtl":"ltr";containerDiv$$module$build$src$core$tooltip.style.display=
"block";visible$$module$build$src$core$tooltip=!0;var {x:b,y:c}=getPosition$$module$build$src$core$tooltip(a);containerDiv$$module$build$src$core$tooltip.style.left=b+"px";containerDiv$$module$build$src$core$tooltip.style.top=c+"px"}};getHsvSaturation$$module$build$src$core$utils$colour=function(){return hsvSaturation$$module$build$src$core$utils$colour};setHsvSaturation$$module$build$src$core$utils$colour=function(a){hsvSaturation$$module$build$src$core$utils$colour=a};
getHsvValue$$module$build$src$core$utils$colour=function(){return hsvValue$$module$build$src$core$utils$colour};setHsvValue$$module$build$src$core$utils$colour=function(a){hsvValue$$module$build$src$core$utils$colour=a};
parse$$module$build$src$core$utils$colour=function(a){a=`${a}`.toLowerCase().trim();var b=names$$module$build$src$core$utils$colour[a];if(b)return b;b=a.substring(0,2)==="0x"?"#"+a.substring(2):a;b=b[0]==="#"?b:"#"+b;if(/^#[0-9a-f]{6}$/.test(b))return b;if(/^#[0-9a-f]{3}$/.test(b))return["#",b[1],b[1],b[2],b[2],b[3],b[3]].join("");var c=a.match(/^(?:rgb)?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);return c&&(a=Number(c[1]),b=Number(c[2]),c=Number(c[3]),a>=0&&a<256&&b>=0&&b<256&&c>=0&&c<256)?rgbToHex$$module$build$src$core$utils$colour(a,
b,c):null};rgbToHex$$module$build$src$core$utils$colour=function(a,b,c){b=a<<16|b<<8|c;return a<16?"#"+(16777216|b).toString(16).substr(1):"#"+b.toString(16)};hexToRgb$$module$build$src$core$utils$colour=function(a){a=parse$$module$build$src$core$utils$colour(a);if(!a)return[0,0,0];a=parseInt(a.substr(1),16);return[a>>16,a>>8&255,a&255]};
hsvToHex$$module$build$src$core$utils$colour=function(a,b,c){let d=0,e=0,f=0;if(b===0)f=e=d=c;else{const g=Math.floor(a/60),h=a/60-g;a=c*(1-b);const k=c*(1-b*h);b=c*(1-b*(1-h));switch(g){case 1:d=k;e=c;f=a;break;case 2:d=a;e=c;f=b;break;case 3:d=a;e=k;f=c;break;case 4:d=b;e=a;f=c;break;case 5:d=c;e=a;f=k;break;case 6:case 0:d=c,e=b,f=a}}return rgbToHex$$module$build$src$core$utils$colour(Math.floor(d),Math.floor(e),Math.floor(f))};
blend$$module$build$src$core$utils$colour=function(a,b,c){a=parse$$module$build$src$core$utils$colour(a);if(!a)return null;b=parse$$module$build$src$core$utils$colour(b);if(!b)return null;a=hexToRgb$$module$build$src$core$utils$colour(a);b=hexToRgb$$module$build$src$core$utils$colour(b);return rgbToHex$$module$build$src$core$utils$colour(Math.round(b[0]+c*(a[0]-b[0])),Math.round(b[1]+c*(a[1]-b[1])),Math.round(b[2]+c*(a[2]-b[2])))};
hueToHex$$module$build$src$core$utils$colour=function(a){return hsvToHex$$module$build$src$core$utils$colour(a,hsvSaturation$$module$build$src$core$utils$colour,hsvValue$$module$build$src$core$utils$colour*255)};
tokenizeInterpolationInternal$$module$build$src$core$utils$parsing=function(a,b,c){const d=[];var e=a.split("");e.push("");var f=0;a=[];let g=null;for(let l=0;l<e.length;l++){var h=e[l];if(f===0)if(h==="%")(f=a.join(""))&&d.push(f),a.length=0,f=1;else if(c&&h==="\n"){const m=a.join("");m&&d.push(m);a.length=0;d.push(h)}else a.push(h);else if(f===1)h==="%"?(a.push(h),f=0):b&&"0"<=h&&h<="9"?(f=2,g=h,(h=a.join(""))&&d.push(h),a.length=0):h==="{"?f=3:(a.push("%",h),f=0);else if(f===2)if("0"<=h&&h<="9")g+=
h;else{var k=void 0;d.push(parseInt((k=g)!=null?k:"",10));l--;f=0}else f===3&&(h===""?(a.splice(0,0,"%{"),l--,f=0):h!=="}"?a.push(h):(f=a.join(""),/[A-Z]\w*/i.test(f)?(h=f.toUpperCase(),(h=h.startsWith("BKY_")?h.substring(4):null)&&h in $.Msg$$module$build$src$core$msg?(f=$.Msg$$module$build$src$core$msg[h],typeof f==="string"?Array.prototype.push.apply(d,tokenizeInterpolationInternal$$module$build$src$core$utils$parsing(f,b,c)):b?d.push(`${f}`):d.push(f)):d.push("%{"+f+"}")):d.push("%{"+f+"}"),f=
a.length=0))}(b=a.join(""))&&d.push(b);k=[];a.length=0;for(e=0;e<d.length;e++)typeof d[e]!=="string"||c&&d[e]==="\n"?((b=a.join(""))&&k.push(b),a.length=0,k.push(d[e])):a.push(d[e]);(b=a.join(""))&&k.push(b);a.length=0;return k};tokenizeInterpolation$$module$build$src$core$utils$parsing=function(a){return tokenizeInterpolationInternal$$module$build$src$core$utils$parsing(a,!0,!0)};
replaceMessageReferences$$module$build$src$core$utils$parsing=function(a){if(typeof a!=="string")return a;a=tokenizeInterpolationInternal$$module$build$src$core$utils$parsing(a,!1,!1);return a.length?String(a[0]):""};
checkMessageReferences$$module$build$src$core$utils$parsing=function(a){let b=!0;const c=$.Msg$$module$build$src$core$msg,d=a.match(/%{BKY_[A-Z]\w*}/gi);if(d)for(let e=0;e<d.length;e++){const f=d[e].toUpperCase();c[f.slice(6,-1)]===void 0&&(console.warn("No message string for "+d[e]+" in "+a),b=!1)}return b};
parseBlockColour$$module$build$src$core$utils$parsing=function(a){const b=typeof a==="string"?replaceMessageReferences$$module$build$src$core$utils$parsing(a):a;var c=Number(b);if(!isNaN(c)&&0<=c&&c<=360)return{hue:c,hex:hsvToHex$$module$build$src$core$utils$colour(c,getHsvSaturation$$module$build$src$core$utils$colour(),getHsvValue$$module$build$src$core$utils$colour()*255)};if(c=parse$$module$build$src$core$utils$colour(b))return{hue:null,hex:c};c='Invalid colour: "'+b+'"';a!==b&&(c+=' (from "'+
a+'")');throw Error(c);};getDiv$$module$build$src$core$widgetdiv=function(){return containerDiv$$module$build$src$core$widgetdiv};testOnly_setDiv$$module$build$src$core$widgetdiv=function(a){containerDiv$$module$build$src$core$widgetdiv=a;if(a===null){let b;(b=document.querySelector("."+containerClassName$$module$build$src$core$widgetdiv))==null||b.remove()}};
createDom$$module$build$src$core$widgetdiv=function(){const a=getParentContainer$$module$build$src$core$common()||document.body,b=document.querySelector("div."+containerClassName$$module$build$src$core$widgetdiv);b?containerDiv$$module$build$src$core$widgetdiv=b:(containerDiv$$module$build$src$core$widgetdiv=document.createElement("div"),containerDiv$$module$build$src$core$widgetdiv.className=containerClassName$$module$build$src$core$widgetdiv,containerDiv$$module$build$src$core$widgetdiv.tabIndex=
-1);conditionalBind$$module$build$src$core$browser_events(containerDiv$$module$build$src$core$widgetdiv,"keydown",null,globalShortcutHandler$$module$build$src$core$common);a.appendChild(containerDiv$$module$build$src$core$widgetdiv)};
show$$module$build$src$core$widgetdiv=function(a,b,c,d,e=!0){hide$$module$build$src$core$widgetdiv();owner$$module$build$src$core$widgetdiv=a;dispose$$module$build$src$core$widgetdiv=c;if(c=containerDiv$$module$build$src$core$widgetdiv){c.style.direction=b?"rtl":"ltr";c.style.display="block";if(!d&&a instanceof Field$$module$build$src$core$field){let h;d=(h=a.getSourceBlock())==null?void 0:h.workspace}var f;ownerWorkspace$$module$build$src$core$widgetdiv=(f=d)!=null?f:null;var g;a=(g=d)!=null?g:getMainWorkspace$$module$build$src$core$common();
rendererClassName$$module$build$src$core$widgetdiv=a.getRenderer().getClassName();themeClassName$$module$build$src$core$widgetdiv=a.getTheme().getClassName();rendererClassName$$module$build$src$core$widgetdiv&&addClass$$module$build$src$core$utils$dom(c,rendererClassName$$module$build$src$core$widgetdiv);themeClassName$$module$build$src$core$widgetdiv&&addClass$$module$build$src$core$utils$dom(c,themeClassName$$module$build$src$core$widgetdiv);e&&(returnEphemeralFocus$$module$build$src$core$widgetdiv=
$.getFocusManager$$module$build$src$core$focus_manager().takeEphemeralFocus(c))}};
hide$$module$build$src$core$widgetdiv=function(){if(isVisible$$module$build$src$core$widgetdiv()){owner$$module$build$src$core$widgetdiv=null;var a=containerDiv$$module$build$src$core$widgetdiv;a&&(a.style.display="none",a.style.left="",a.style.top="",dispose$$module$build$src$core$widgetdiv&&(dispose$$module$build$src$core$widgetdiv(),dispose$$module$build$src$core$widgetdiv=null),a.textContent="",rendererClassName$$module$build$src$core$widgetdiv&&(removeClass$$module$build$src$core$utils$dom(a,
rendererClassName$$module$build$src$core$widgetdiv),rendererClassName$$module$build$src$core$widgetdiv=""),themeClassName$$module$build$src$core$widgetdiv&&(removeClass$$module$build$src$core$utils$dom(a,themeClassName$$module$build$src$core$widgetdiv),themeClassName$$module$build$src$core$widgetdiv=""),getMainWorkspace$$module$build$src$core$common().markFocused(),returnEphemeralFocus$$module$build$src$core$widgetdiv&&(returnEphemeralFocus$$module$build$src$core$widgetdiv(),returnEphemeralFocus$$module$build$src$core$widgetdiv=
null))}};isVisible$$module$build$src$core$widgetdiv=function(){return!!owner$$module$build$src$core$widgetdiv};hideIfOwner$$module$build$src$core$widgetdiv=function(a){owner$$module$build$src$core$widgetdiv===a&&hide$$module$build$src$core$widgetdiv()};hideIfOwnerIsInWorkspace$$module$build$src$core$widgetdiv=function(a){let b=ownerWorkspace$$module$build$src$core$widgetdiv===null,c=a;for(;!b&&c;){if(c===a){b=!0;break}c=a.options.parentWorkspace}b&&hide$$module$build$src$core$widgetdiv()};
positionInternal$$module$build$src$core$widgetdiv=function(a,b,c){containerDiv$$module$build$src$core$widgetdiv.style.left=a+"px";containerDiv$$module$build$src$core$widgetdiv.style.top=b+"px";containerDiv$$module$build$src$core$widgetdiv.style.height=c+"px"};
positionWithAnchor$$module$build$src$core$widgetdiv=function(a,b,c,d){const e=calculateY$$module$build$src$core$widgetdiv(a,b,c);a=calculateX$$module$build$src$core$widgetdiv(a,b,c,d);e<0?positionInternal$$module$build$src$core$widgetdiv(a,0,c.height+e):positionInternal$$module$build$src$core$widgetdiv(a,e,c.height)};calculateX$$module$build$src$core$widgetdiv=function(a,b,c,d){return d?Math.min(Math.max(b.right-c.width,a.left),a.right-c.width):Math.max(Math.min(b.left,a.right-c.width),a.left)};
calculateY$$module$build$src$core$widgetdiv=function(a,b,c){return b.bottom+c.height>=a.bottom?b.top-c.height:b.bottom};isRepositionable$$module$build$src$core$widgetdiv=function(a){return!(a==null||!a.repositionForWindowResize)};repositionForWindowResize$$module$build$src$core$widgetdiv=function(){isRepositionable$$module$build$src$core$widgetdiv(owner$$module$build$src$core$widgetdiv)&&owner$$module$build$src$core$widgetdiv.repositionForWindowResize()||hide$$module$build$src$core$widgetdiv()};
getCurrentBlock$$module$build$src$core$contextmenu=function(){return currentBlock$$module$build$src$core$contextmenu};setCurrentBlock$$module$build$src$core$contextmenu=function(a){currentBlock$$module$build$src$core$contextmenu=a};
show$$module$build$src$core$contextmenu=function(a,b,c,d,e){show$$module$build$src$core$widgetdiv(dummyOwner$$module$build$src$core$contextmenu,c,dispose$$module$build$src$core$contextmenu,d);if(b.length){e||(a instanceof PointerEvent?e=new Coordinate$$module$build$src$core$utils$coordinate(a.clientX,a.clientY):(console.warn("Context menu opened with keyboard but no location given"),e=new Coordinate$$module$build$src$core$utils$coordinate(0,0)));var f=populate_$$module$build$src$core$contextmenu(b,
c,a,e);menu_$$module$build$src$core$contextmenu=f;position_$$module$build$src$core$contextmenu(f,c,e);setTimeout(function(){f.focus()},1);currentBlock$$module$build$src$core$contextmenu=null}else hide$$module$build$src$core$contextmenu()};
populate_$$module$build$src$core$contextmenu=function(a,b,c,d){const e=new Menu$$module$build$src$core$menu;e.setRole(Role$$module$build$src$core$utils$aria.MENU);for(let f=0;f<a.length;f++){const g=a[f];if(g.separator){e.addChild(new MenuSeparator$$module$build$src$core$menu_separator);continue}const h=new MenuItem$$module$build$src$core$menuitem(g.text);h.setRightToLeft(b);h.setRole(Role$$module$build$src$core$utils$aria.MENUITEM);e.addChild(h);h.setEnabled(g.enabled);if(g.enabled)h.onAction(function(k,
l){hide$$module$build$src$core$contextmenu();requestAnimationFrame(()=>{setTimeout(()=>{g.callback(g.scope,c,l,d)},0)})},{})}return e};
position_$$module$build$src$core$contextmenu=function(a,b,c){const d=getViewportBBox$$module$build$src$core$utils$svg_math();c=new Rect$$module$build$src$core$utils$rect(c.y+d.top,c.y+d.top,c.x+d.left,c.x+d.left);createWidget_$$module$build$src$core$contextmenu(a);const e=a.getSize();b&&(c.left+=e.width,c.right+=e.width,d.left+=e.width,d.right+=e.width);positionWithAnchor$$module$build$src$core$widgetdiv(d,c,e,b);a.focus()};
createWidget_$$module$build$src$core$contextmenu=function(a){var b=getDiv$$module$build$src$core$widgetdiv();if(!b)throw Error("Attempting to create a context menu when widget div is null");b=a.render(b);addClass$$module$build$src$core$utils$dom(b,"blocklyContextMenu");conditionalBind$$module$build$src$core$browser_events(b,"contextmenu",null,haltPropagation$$module$build$src$core$contextmenu);a.focus()};haltPropagation$$module$build$src$core$contextmenu=function(a){a.preventDefault();a.stopPropagation()};
hide$$module$build$src$core$contextmenu=function(){hideIfOwner$$module$build$src$core$widgetdiv(dummyOwner$$module$build$src$core$contextmenu);currentBlock$$module$build$src$core$contextmenu=null};dispose$$module$build$src$core$contextmenu=function(){menu_$$module$build$src$core$contextmenu&&(menu_$$module$build$src$core$contextmenu.dispose(),menu_$$module$build$src$core$contextmenu=null)};
$.callbackFactory$$module$build$src$core$contextmenu=function(a,b){return()=>{$.disable$$module$build$src$core$events$utils();let c;try{c=b instanceof Element?domToBlockInternal$$module$build$src$core$xml(b,a.workspace):appendInternal$$module$build$src$core$serialization$blocks(b,a.workspace);const d=a.getRelativeToSurfaceXY();d.x=a.RTL?d.x-$.config$$module$build$src$core$config.snapRadius:d.x+$.config$$module$build$src$core$config.snapRadius;d.y+=$.config$$module$build$src$core$config.snapRadius*
2;c.moveBy(d.x,d.y)}finally{$.enable$$module$build$src$core$events$utils()}isEnabled$$module$build$src$core$events$utils()&&!c.isShadow()&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CREATE))(c));$.getFocusManager$$module$build$src$core$focus_manager().focusNode(c);return c}};
mouseToWorkspacePoint$$module$build$src$core$utils$drag=function(a,b){b=mouseToSvg$$module$build$src$core$browser_events(b,a.getParentSvg(),a.getInverseScreenCTM());b.x/=a.scale;b.y/=a.scale;return b};start$$module$build$src$core$utils$drag=function(a,b,c){b=mouseToWorkspacePoint$$module$build$src$core$utils$drag(a,b);workspaceToDragDelta$$module$build$src$core$utils$drag.set(a,Coordinate$$module$build$src$core$utils$coordinate.difference(c,b))};
move$$module$build$src$core$utils$drag=function(a,b){b=mouseToWorkspacePoint$$module$build$src$core$utils$drag(a,b);a=workspaceToDragDelta$$module$build$src$core$utils$drag.get(a);if(!a)throw Error("Drag not initialized");return Coordinate$$module$build$src$core$utils$coordinate.sum(a,b)};
workspaceToDom$$module$build$src$core$xml=function(a,b=!1){const c=$.createElement$$module$build$src$core$utils$xml("xml");var d=variablesToDom$$module$build$src$core$xml($.allUsedVarModels$$module$build$src$core$variables(a));d.hasChildNodes()&&c.appendChild(d);for(const e of a.getTopComments())c.appendChild(saveWorkspaceComment$$module$build$src$core$xml(e,b));a=a.getTopBlocks(!0);for(d=0;d<a.length;d++)c.appendChild(blockToDomWithXY$$module$build$src$core$xml(a[d],b));return c};
saveWorkspaceComment$$module$build$src$core$xml=function(a,b=!1){const c=$.createElement$$module$build$src$core$utils$xml("comment");b||c.setAttribute("id",a.id);b=a.workspace;const d=a.getRelativeToSurfaceXY().clone();d.x=b.RTL?b.getWidth()-d.x:d.x;c.setAttribute("x",`${d.x}`);c.setAttribute("y",`${d.y}`);c.setAttribute("w",`${a.getSize().width}`);c.setAttribute("h",`${a.getSize().height}`);a.getText()&&(c.textContent=a.getText());a.isCollapsed()&&c.setAttribute("collapsed","true");a.isOwnEditable()||
c.setAttribute("editable","false");a.isOwnMovable()||c.setAttribute("movable","false");a.isOwnDeletable()||c.setAttribute("deletable","false");return c};
variablesToDom$$module$build$src$core$xml=function(a){const b=$.createElement$$module$build$src$core$utils$xml("variables");for(let c=0;c<a.length;c++){const d=a[c],e=$.createElement$$module$build$src$core$utils$xml("variable");e.appendChild($.createTextNode$$module$build$src$core$utils$xml(d.getName()));d.getType()&&e.setAttribute("type",d.getType());e.id=d.getId();b.appendChild(e)}return b};
blockToDomWithXY$$module$build$src$core$xml=function(a,b){if(a.isInsertionMarker()&&(a=a.getChildren(!1)[0],!a))return new DocumentFragment;let c=0;a.workspace.RTL&&(c=a.workspace.getWidth());b=blockToDom$$module$build$src$core$xml(a,b);if(isElement$$module$build$src$core$xml(b)){const d=a.getRelativeToSurfaceXY();b.setAttribute("x",String(Math.round(a.workspace.RTL?c-d.x:d.x)));b.setAttribute("y",String(Math.round(d.y)))}return b};
fieldToDom$$module$build$src$core$xml=function(a){if(a.isSerializable()){const b=$.createElement$$module$build$src$core$utils$xml("field");b.setAttribute("name",a.name||"");return a.toXml(b)}return null};allFieldsToDom$$module$build$src$core$xml=function(a,b){for(const c of a.getFields())(a=fieldToDom$$module$build$src$core$xml(c))&&b.appendChild(a)};
blockToDom$$module$build$src$core$xml=function(a,b){if(a.isInsertionMarker())return(b=a.getChildren(!1)[0])?blockToDom$$module$build$src$core$xml(b):new DocumentFragment;const c=$.createElement$$module$build$src$core$utils$xml(a.isShadow()?"shadow":"block");c.setAttribute("type",a.type);b||(c.id=a.id);if(a.mutationToDom){var d=a.mutationToDom();d&&(d.hasChildNodes()||d.hasAttributes())&&c.appendChild(d)}allFieldsToDom$$module$build$src$core$xml(a,c);if(d=a.getCommentText()){var e=a.getIcon(IconType$$module$build$src$core$icons$icon_types.COMMENT),
f=e.getBubbleSize(),g=e.bubbleIsVisible();e=e.getBubbleLocation();var h=$.createElement$$module$build$src$core$utils$xml("comment");h.appendChild($.createTextNode$$module$build$src$core$utils$xml(d));h.setAttribute("pinned",`${g}`);h.setAttribute("h",`${f.height}`);h.setAttribute("w",`${f.width}`);e&&(h.setAttribute("x",`${a.workspace.RTL?a.workspace.getWidth()-(e.x+f.width):e.x}`),h.setAttribute("y",`${e.y}`));c.appendChild(h)}a.data&&(d=$.createElement$$module$build$src$core$utils$xml("data"),d.appendChild($.createTextNode$$module$build$src$core$utils$xml(a.data)),
c.appendChild(d));for(d=0;d<a.inputList.length;d++){f=a.inputList[d];var k=void 0;g=!0;f.type!==$.inputTypes$$module$build$src$core$inputs$input_types.DUMMY&&f.type!==$.inputTypes$$module$build$src$core$inputs$input_types.END_ROW&&(e=f.connection.targetBlock(),f.type===$.inputTypes$$module$build$src$core$inputs$input_types.VALUE?k=$.createElement$$module$build$src$core$utils$xml("value"):f.type===$.inputTypes$$module$build$src$core$inputs$input_types.STATEMENT&&(k=$.createElement$$module$build$src$core$utils$xml("statement")),
h=f.connection.getShadowDom(),!h||e&&e.isShadow()||k.appendChild(cloneShadow$$module$build$src$core$xml(h,b)),e&&(e=blockToDom$$module$build$src$core$xml(e,b),e.nodeType===NodeType$$module$build$src$core$utils$dom.ELEMENT_NODE&&(k.appendChild(e),g=!1)),k.setAttribute("name",f.name),g||c.appendChild(k))}a.inputsInline!==void 0&&a.inputsInline!==a.inputsInlineDefault&&c.setAttribute("inline",String(a.inputsInline));a.isCollapsed()&&c.setAttribute("collapsed","true");a.isEnabled()||c.setAttribute("disabled-reasons",
Array.from(a.getDisabledReasons()).map(encodeURIComponent).join(","));a.isOwnDeletable()||c.setAttribute("deletable","false");a.isOwnMovable()||c.setAttribute("movable","false");a.isOwnEditable()||c.setAttribute("editable","false");k=a.getNextBlock();let l;k&&(d=blockToDom$$module$build$src$core$xml(k,b),d.nodeType===NodeType$$module$build$src$core$utils$dom.ELEMENT_NODE&&(l=$.createElement$$module$build$src$core$utils$xml("next"),l.appendChild(d),c.appendChild(l)));a=a.nextConnection&&a.nextConnection.getShadowDom();
!a||k&&k.isShadow()||l.appendChild(cloneShadow$$module$build$src$core$xml(a,b));return c};
cloneShadow$$module$build$src$core$xml=function(a,b){let c=a=a.cloneNode(!0),d;for(;c;)if(b&&c.nodeName==="shadow"&&c.removeAttribute("id"),c.firstChild)c=c.firstChild;else{for(;c&&!c.nextSibling;){d=c;c=c.parentNode;let e;d.nodeType===NodeType$$module$build$src$core$utils$dom.TEXT_NODE&&d.data.trim()===""&&((e=c)==null?void 0:e.firstChild)!==d&&removeNode$$module$build$src$core$utils$dom(d)}c&&(d=c,c=c.nextSibling,d.nodeType===NodeType$$module$build$src$core$utils$dom.TEXT_NODE&&d.data.trim()===
""&&removeNode$$module$build$src$core$utils$dom(d))}return a};domToText$$module$build$src$core$xml=function(a){return domToText$$module$build$src$core$utils$xml(a).replace(/<(\w+)([^<]*)\/>/g,"<$1$2></$1>")};
domToPrettyText$$module$build$src$core$xml=function(a){a=domToText$$module$build$src$core$xml(a).split("<");let b="";for(let c=1;c<a.length;c++){const d=a[c];d[0]==="/"&&(b=b.substring(2));a[c]=b+"<"+d;d[0]!=="/"&&d.slice(-2)!=="/>"&&(b+="  ")}a=a.join("\n");a=a.replace(/(<(\w+)\b[^>]*>[^\n]*)\n *<\/\2>/g,"$1</$2>");return a.replace(/^\n/,"")};
clearWorkspaceAndLoadFromXml$$module$build$src$core$xml=function(a,b){b.setResizesEnabled(!1);b.clear();a=$.domToWorkspace$$module$build$src$core$xml(a,b);b.setResizesEnabled(!0);return a};
$.domToWorkspace$$module$build$src$core$xml=function(a,b){let c=0;b.RTL&&(c=b.getWidth());const d=[];startTextWidthCache$$module$build$src$core$utils$dom();const e=$.getGroup$$module$build$src$core$events$utils();e||$.setGroup$$module$build$src$core$events$utils(!0);b.setResizesEnabled&&b.setResizesEnabled(!1);let f=!0;try{for(let g=0,h;h=a.childNodes[g];g++){const k=h.nodeName.toLowerCase(),l=h;if(k==="block"||k==="shadow"&&!getRecordUndo$$module$build$src$core$events$utils()){const m=domToBlockInternal$$module$build$src$core$xml(l,
b);d.push(m.id);let n;const p=parseInt((n=l.getAttribute("x"))!=null?n:"10",10);let r;const q=parseInt((r=l.getAttribute("y"))!=null?r:"10",10);isNaN(p)||isNaN(q)||m.moveBy(b.RTL?c-p:p,q,["create"]);f=!1}else{if(k==="shadow")throw TypeError("Shadow block cannot be a top-level block.");if(k==="comment")loadWorkspaceComment$$module$build$src$core$xml(l,b);else if(k==="variables"){if(f)domToVariables$$module$build$src$core$xml(l,b);else throw Error("'variables' tag must exist once before block and shadow tag elements in the workspace XML, but it was found in another location.");
f=!1}}}}finally{$.setGroup$$module$build$src$core$events$utils(e),b.setResizesEnabled&&b.setResizesEnabled(!0),b.rendered&&triggerQueuedRenders$$module$build$src$core$render_management(),stopTextWidthCache$$module$build$src$core$utils$dom()}fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.FINISHED_LOADING))(b));return d};
loadWorkspaceComment$$module$build$src$core$xml=function(a,b){var c;const d=(c=a.getAttribute("id"))!=null?c:void 0;c=b.rendered?new RenderedWorkspaceComment$$module$build$src$core$comments$rendered_workspace_comment(b,d):new WorkspaceComment$$module$build$src$core$comments$workspace_comment(b,d);var e;c.setText((e=a.textContent)!=null?e:"");var f;e=parseInt((f=a.getAttribute("x"))!=null?f:"",10);let g;f=parseInt((g=a.getAttribute("y"))!=null?g:"",10);isNaN(e)||isNaN(f)||(e=b.RTL?b.getWidth()-e:e,
c.moveTo(new Coordinate$$module$build$src$core$utils$coordinate(e,f)));var h;b=parseInt((h=a.getAttribute("w"))!=null?h:"",10);let k;h=parseInt((k=a.getAttribute("h"))!=null?k:"",10);isNaN(b)||isNaN(h)||c.setSize(new Size$$module$build$src$core$utils$size(b,h));a.getAttribute("collapsed")==="true"&&c.setCollapsed(!0);a.getAttribute("editable")==="false"&&c.setEditable(!1);a.getAttribute("movable")==="false"&&c.setMovable(!1);a.getAttribute("deletable")==="false"&&c.setDeletable(!1);return c};
appendDomToWorkspace$$module$build$src$core$xml=function(a,b){if(!b.getBlocksBoundingBox)return $.domToWorkspace$$module$build$src$core$xml(a,b);var c=b.getBlocksBoundingBox();a=$.domToWorkspace$$module$build$src$core$xml(a,b);if(c&&c.top!==c.bottom){var d=c.bottom;c=b.RTL?c.right:c.left;var e=Infinity;let f=-Infinity,g=Infinity;for(let h=0;h<a.length;h++){const k=b.getBlockById(a[h]).getRelativeToSurfaceXY();k.y<g&&(g=k.y);k.x<e&&(e=k.x);k.x>f&&(f=k.x)}d=d-g+10;c=b.RTL?c-f:c-e;for(e=0;e<a.length;e++)b.getBlockById(a[e]).moveBy(c,
d,["create"])}return a};$.domToBlock$$module$build$src$core$xml=function(a,b){a=domToBlockInternal$$module$build$src$core$xml(a,b);b.rendered&&triggerQueuedRenders$$module$build$src$core$render_management();return a};
domToBlockInternal$$module$build$src$core$xml=function(a,b){$.disable$$module$build$src$core$events$utils();var c=b.getAllVariables();let d;try{if(d=domToBlockHeadless$$module$build$src$core$xml(a,b),b.rendered){const e=d,f=d.getDescendants(!1);e.setConnectionTracking(!1);for(let g=f.length-1;g>=0;g--)f[g].initSvg();for(let g=f.length-1;g>=0;g--)f[g].queueRender();setTimeout(function(){e.disposed||e.setConnectionTracking(!0)},1);b.resizeContents()}else{const e=d.getDescendants(!1);for(let f=e.length-
1;f>=0;f--)e[f].initModel()}}finally{$.enable$$module$build$src$core$events$utils()}if(isEnabled$$module$build$src$core$events$utils()){a=getAddedVariables$$module$build$src$core$variables(b,c);for(b=0;b<a.length;b++)c=a[b],fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.VAR_CREATE))(c));fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CREATE))(d))}return d};
domToVariables$$module$build$src$core$xml=function(a,b){for(let d=0;d<a.children.length;d++){var c=a.children[d];const e=c.getAttribute("type"),f=c.getAttribute("id");c=c.textContent;if(!c)break;let g;b.getVariableMap().createVariable(c,(g=e)!=null?g:void 0,f)}};
mapSupportedXmlTags$$module$build$src$core$xml=function(a){const b={mutation:[],comment:[],data:[],field:[],input:[],next:[]};for(let c=0;c<a.children.length;c++){const d=a.children[c];if(d.nodeType!==NodeType$$module$build$src$core$utils$dom.TEXT_NODE)switch(d.nodeName.toLowerCase()){case "mutation":b.mutation.push(d);break;case "comment":b.comment.push(d);break;case "data":b.data.push(d);break;case "title":case "field":b.field.push(d);break;case "value":case "statement":b.input.push(d);break;case "next":b.next.push(d);
break;default:console.warn("Ignoring unknown tag: "+d.nodeName)}}return b};applyMutationTagNodes$$module$build$src$core$xml=function(a,b){let c=!1;for(let d=0;d<a.length;d++){const e=a[d];b.domToMutation&&(b.domToMutation(e),b.initSvg&&(c=!0))}return c};
applyCommentTagNodes$$module$build$src$core$xml=function(a,b){for(let c=0;c<a.length;c++){const d=a[c],e=d.textContent,f=d.getAttribute("pinned")==="true";let g;const h=parseInt((g=d.getAttribute("w"))!=null?g:"50",10);let k;const l=parseInt((k=d.getAttribute("h"))!=null?k:"50",10);let m,n=parseInt((m=d.getAttribute("x"))!=null?m:"",10),p;const r=parseInt((p=d.getAttribute("y"))!=null?p:"",10);b.setCommentText(e);const q=b.getIcon(IconType$$module$build$src$core$icons$icon_types.COMMENT);isNaN(h)||
isNaN(l)||q.setBubbleSize(new Size$$module$build$src$core$utils$size(h,l));q.setBubbleVisible(f);setTimeout(()=>{isNaN(n)||isNaN(r)||(n=b.workspace.RTL?b.workspace.getWidth()-(n+h):n,q.setBubbleLocation(new Coordinate$$module$build$src$core$utils$coordinate(n,r)));q.setBubbleVisible(f)},1)}};applyDataTagNodes$$module$build$src$core$xml=function(a,b){for(let c=0;c<a.length;c++)b.data=a[c].textContent};
applyFieldTagNodes$$module$build$src$core$xml=function(a,b){for(let c=0;c<a.length;c++){const d=a[c],e=d.getAttribute("name");e?domToField$$module$build$src$core$xml(b,e,d):console.warn(`Ignoring unnamed field in block ${b.type}`)}};
findChildBlocks$$module$build$src$core$xml=function(a){let b=null,c=null;for(let d=0;d<a.childNodes.length;d++){const e=a.childNodes[d];isElement$$module$build$src$core$xml(e)&&(e.nodeName.toLowerCase()==="block"?b=e:e.nodeName.toLowerCase()==="shadow"&&(c=e))}return{childBlockElement:b,childShadowElement:c}};
applyInputTagNodes$$module$build$src$core$xml=function(a,b,c,d){for(let f=0;f<a.length;f++){var e=a[f];const g=e.getAttribute("name"),h=g?c.getInput(g):null;if(!h){console.warn("Ignoring non-existent input "+g+" in block "+d);break}e=findChildBlocks$$module$build$src$core$xml(e);if(e.childBlockElement){if(!h.connection)throw TypeError("Input connection does not exist.");domToBlockHeadless$$module$build$src$core$xml(e.childBlockElement,b,h.connection,!1)}if(e.childShadowElement){let k;(k=h.connection)==
null||k.setShadowDom(e.childShadowElement)}}};
applyNextTagNodes$$module$build$src$core$xml=function(a,b,c){for(let d=0;d<a.length;d++){const e=findChildBlocks$$module$build$src$core$xml(a[d]);if(e.childBlockElement){if(!c.nextConnection)throw TypeError("Next statement does not exist.");if(c.nextConnection.isConnected())throw TypeError("Next statement is already connected.");domToBlockHeadless$$module$build$src$core$xml(e.childBlockElement,b,c.nextConnection,!0)}e.childShadowElement&&c.nextConnection&&c.nextConnection.setShadowDom(e.childShadowElement)}};
domToBlockHeadless$$module$build$src$core$xml=function(a,b,c,d){var e;const f=a.getAttribute("type");if(!f)throw TypeError("Block type unspecified: "+a.outerHTML);var g=(e=a.getAttribute("id"))!=null?e:void 0;e=b.newBlock(f,g);g=mapSupportedXmlTags$$module$build$src$core$xml(a);const h=applyMutationTagNodes$$module$build$src$core$xml(g.mutation,e);applyCommentTagNodes$$module$build$src$core$xml(g.comment,e);applyDataTagNodes$$module$build$src$core$xml(g.data,e);if(c)if(d)if(e.previousConnection)c.connect(e.previousConnection);
else throw TypeError("Next block does not have previous statement.");else if(e.outputConnection)c.connect(e.outputConnection);else if(e.previousConnection)c.connect(e.previousConnection);else throw TypeError("Child block does not have output or previous statement.");applyFieldTagNodes$$module$build$src$core$xml(g.field,e);applyInputTagNodes$$module$build$src$core$xml(g.input,b,e,f);applyNextTagNodes$$module$build$src$core$xml(g.next,b,e);h&&e.initSvg();(b=a.getAttribute("inline"))&&e.setInputsInline(b===
"true");(b=a.getAttribute("disabled"))&&e.setDisabledReason(b==="true"||b==="disabled",MANUALLY_DISABLED$$module$build$src$core$constants);b=a.getAttribute("disabled-reasons");if(b!==null)for(var k of b.split(","))e.setDisabledReason(!0,decodeURIComponent(k));(k=a.getAttribute("deletable"))&&e.setDeletable(k==="true");(k=a.getAttribute("movable"))&&e.setMovable(k==="true");(k=a.getAttribute("editable"))&&e.setEditable(k==="true");(k=a.getAttribute("collapsed"))&&e.setCollapsed(k==="true");if(a.nodeName.toLowerCase()===
"shadow"){a=e.getChildren(!1);for(k=0;k<a.length;k++)if(!a[k].isShadow())throw TypeError("Shadow block not allowed non-shadow child.");e.setShadow(!0)}return e};domToField$$module$build$src$core$xml=function(a,b,c){const d=a.getField(b);d?d.fromXml(c):console.warn("Ignoring non-existent field "+b+" in block "+a.type)};deleteNext$$module$build$src$core$xml=function(a){for(let b=0;b<a.childNodes.length;b++){const c=a.childNodes[b];if(c.nodeName.toLowerCase()==="next"){a.removeChild(c);break}}};
isElement$$module$build$src$core$xml=function(a){return a.nodeType===NodeType$$module$build$src$core$utils$dom.ELEMENT_NODE};register$$module$build$src$core$field_registry=function(a,b){register$$module$build$src$core$registry(Type$$module$build$src$core$registry.FIELD,a,b,!0)};unregister$$module$build$src$core$field_registry=function(a){unregister$$module$build$src$core$registry(Type$$module$build$src$core$registry.FIELD,a)};$.fromJson$$module$build$src$core$field_registry=function(a){return TEST_ONLY$$module$build$src$core$field_registry.fromJsonInternal(a)};
fromJsonInternal$$module$build$src$core$field_registry=function(a){const b=getObject$$module$build$src$core$registry(Type$$module$build$src$core$registry.FIELD,a.type);return b?b.fromJson(a):(console.warn("Blockly could not create a field of type "+a.type+". The field is probably not being registered. This could be because the file is not loaded, the field does not register itself (Issue #1584), or the registration is not being reached."),null)};
isImageProperties$$module$build$src$core$field_dropdown=function(a){return a&&typeof a==="object"&&"src"in a&&typeof a.src==="string"&&"alt"in a&&typeof a.alt==="string"&&"width"in a&&typeof a.width==="number"&&"height"in a&&typeof a.height==="number"};
$.register$$module$build$src$core$extensions=function(a,b){if(typeof a!=="string"||a.trim()==="")throw Error('Error: Invalid extension name "'+a+'"');if(allExtensions$$module$build$src$core$extensions[a])throw Error('Error: Extension "'+a+'" is already registered.');if(typeof b!=="function")throw Error('Error: Extension "'+a+'" must be a function');allExtensions$$module$build$src$core$extensions[a]=b};
$.registerMixin$$module$build$src$core$extensions=function(a,b){if(!b||typeof b!=="object")throw Error('Error: Mixin "'+a+'" must be a object');$.register$$module$build$src$core$extensions(a,function(){this.mixin(b)})};
$.registerMutator$$module$build$src$core$extensions=function(a,b,c,d){const e='Error when registering mutator "'+a+'": ';checkHasMutatorProperties$$module$build$src$core$extensions(e,b);const f=checkMutatorDialog$$module$build$src$core$extensions(b,e);if(c&&typeof c!=="function")throw Error(e+'Extension "'+a+'" is not a function');$.register$$module$build$src$core$extensions(a,function(){f&&this.setMutator(new $.MutatorIcon$$module$build$src$core$icons$mutator_icon(d||[],this));this.mixin(b);c&&c.apply(this)})};
unregister$$module$build$src$core$extensions=function(a){isRegistered$$module$build$src$core$extensions(a)?delete allExtensions$$module$build$src$core$extensions[a]:console.warn('No extension mapping for name "'+a+'" found to unregister')};isRegistered$$module$build$src$core$extensions=function(a){return!!allExtensions$$module$build$src$core$extensions[a]};
apply$$module$build$src$core$extensions=function(a,b,c){const d=allExtensions$$module$build$src$core$extensions[a];if(typeof d!=="function")throw Error('Error: Extension "'+a+'" not found.');let e;c?checkNoMutatorProperties$$module$build$src$core$extensions(a,b):e=getMutatorProperties$$module$build$src$core$extensions(b);d.apply(b);if(c)checkHasMutatorProperties$$module$build$src$core$extensions('Error after applying mutator "'+a+'": ',b);else if(!mutatorPropertiesMatch$$module$build$src$core$extensions(e,
b))throw Error('Error when applying extension "'+a+'": mutation properties changed when applying a non-mutator extension.');};checkNoMutatorProperties$$module$build$src$core$extensions=function(a,b){if(getMutatorProperties$$module$build$src$core$extensions(b).length)throw Error('Error: tried to apply mutation "'+a+'" to a block that already has mutator functions.  Block id: '+b.id);};
checkXmlHooks$$module$build$src$core$extensions=function(a,b){return checkHasFunctionPair$$module$build$src$core$extensions(a.mutationToDom,a.domToMutation,b+" mutationToDom/domToMutation")};checkJsonHooks$$module$build$src$core$extensions=function(a,b){return checkHasFunctionPair$$module$build$src$core$extensions(a.saveExtraState,a.loadExtraState,b+" saveExtraState/loadExtraState")};
checkMutatorDialog$$module$build$src$core$extensions=function(a,b){return checkHasFunctionPair$$module$build$src$core$extensions(a.compose,a.decompose,b+" compose/decompose")};checkHasFunctionPair$$module$build$src$core$extensions=function(a,b,c){if(a&&b){if(typeof a!=="function"||typeof b!=="function")throw Error(c+" must be a function");return!0}if(!a&&!b)return!1;throw Error(c+"Must have both or neither functions");};
checkHasMutatorProperties$$module$build$src$core$extensions=function(a,b){const c=checkXmlHooks$$module$build$src$core$extensions(b,a),d=checkJsonHooks$$module$build$src$core$extensions(b,a);if(!c&&!d)throw Error(a+"Mutations must contain either XML hooks, or JSON hooks, or both");checkMutatorDialog$$module$build$src$core$extensions(b,a)};
getMutatorProperties$$module$build$src$core$extensions=function(a){const b=[];a.domToMutation!==void 0&&b.push(a.domToMutation);a.mutationToDom!==void 0&&b.push(a.mutationToDom);a.saveExtraState!==void 0&&b.push(a.saveExtraState);a.loadExtraState!==void 0&&b.push(a.loadExtraState);a.compose!==void 0&&b.push(a.compose);a.decompose!==void 0&&b.push(a.decompose);return b};
mutatorPropertiesMatch$$module$build$src$core$extensions=function(a,b){b=getMutatorProperties$$module$build$src$core$extensions(b);if(b.length!==a.length)return!1;for(let c=0;c<b.length;c++)if(a[c]!==b[c])return!1;return!0};
runAfterPageLoad$$module$build$src$core$extensions=function(a){if(typeof document!=="object")throw Error("runAfterPageLoad() requires browser document.");if(document.readyState==="complete")a();else{const b=setInterval(function(){document.readyState==="complete"&&(clearInterval(b),a())},10)}};
$.buildTooltipForDropdown$$module$build$src$core$extensions=function(a,b){const c=[];return function(){c.includes(this.type)||(checkDropdownOptionsInTable$$module$build$src$core$extensions(this,a,b),c.push(this.type));this.setTooltip(function(){const d=String(this.getFieldValue(a));return replaceMessageReferences$$module$build$src$core$utils$parsing(b[d])}.bind(this))}};
checkDropdownOptionsInTable$$module$build$src$core$extensions=function(a,b,c){var d=a.getField(b);if(d instanceof FieldDropdown$$module$build$src$core$field_dropdown&&!d.isOptionListDynamic()){d=d.getOptions();for(const e of d)e!==FieldDropdown$$module$build$src$core$field_dropdown.SEPARATOR&&([,d]=e,c[d]===void 0&&console.warn(`No tooltip mapping for value ${d} of field `+`${b} of block type ${a.type}.`))}};
$.buildTooltipWithFieldText$$module$build$src$core$extensions=function(a,b){return function(){this.setTooltip(function(){const c=this.getField(b);return replaceMessageReferences$$module$build$src$core$utils$parsing(a).replace("%1",c?c.getText():"")}.bind(this))}};extensionParentTooltip$$module$build$src$core$extensions=function(){const a=this.tooltip;this.setTooltip(function(){const b=this.getParent();return b&&b.getInputsInline()&&b.tooltip||a}.bind(this))};
point$$module$build$src$core$utils$svg_paths=function(a,b){return" "+a+","+b+" "};curve$$module$build$src$core$utils$svg_paths=function(a,b){return" "+a+b.join("")};moveTo$$module$build$src$core$utils$svg_paths=function(a,b){return" M "+a+","+b+" "};moveBy$$module$build$src$core$utils$svg_paths=function(a,b){return" m "+a+","+b+" "};lineTo$$module$build$src$core$utils$svg_paths=function(a,b){return" l "+a+","+b+" "};line$$module$build$src$core$utils$svg_paths=function(a){return" l"+a.join("")};
lineOnAxis$$module$build$src$core$utils$svg_paths=function(a,b){return" "+a+" "+b+" "};arc$$module$build$src$core$utils$svg_paths=function(a,b,c,d){return a+" "+c+" "+c+" "+b+d};connectReciprocally$$module$build$src$core$connection=function(a,b){if(!a||!b)throw Error("Cannot connect null connections.");a.targetConnection=b;b.targetConnection=a};
getSingleConnection$$module$build$src$core$connection=function(a,b){let c=null;b=b.outputConnection;const d=b==null?void 0:b.getConnectionChecker();for(let e=0,f;f=a.inputList[e];e++){const g=f.connection;let h;if(g&&((h=d)==null?0:h.canConnect(b,g,!1))){if(c)return null;c=g}}return c};getConnectionForOrphanedOutput$$module$build$src$core$connection=function(a,b){let c;for(;c=getSingleConnection$$module$build$src$core$connection(a,b);)if(a=c.targetBlock(),!a||a.isShadow())return c;return null};
isIcon$$module$build$src$core$interfaces$i_icon=function(a){return isFocusableNode$$module$build$src$core$interfaces$i_focusable_node(a)&&typeof a.getType==="function"&&typeof a.initView==="function"&&typeof a.dispose==="function"&&typeof a.getWeight==="function"&&typeof a.getSize==="function"&&typeof a.applyColour==="function"&&typeof a.hideForInsertionMarker==="function"&&typeof a.updateEditable==="function"&&typeof a.updateCollapsed==="function"&&typeof a.isShownWhenCollapsed==="function"&&typeof a.setOffsetInBlock===
"function"&&typeof a.onLocationChange==="function"&&typeof a.onClick==="function"};
isCommentIcon$$module$build$src$core$interfaces$i_comment_icon=function(a){return isIcon$$module$build$src$core$interfaces$i_icon(a)&&hasBubble$$module$build$src$core$interfaces$i_has_bubble(a)&&isSerializable$$module$build$src$core$interfaces$i_serializable(a)&&typeof a.setText==="function"&&typeof a.getText==="function"&&typeof a.setBubbleSize==="function"&&typeof a.getBubbleSize==="function"&&typeof a.setBubbleLocation==="function"&&typeof a.getBubbleLocation==="function"&&a.getType()===IconType$$module$build$src$core$icons$icon_types.COMMENT};
disposeUiEffect$$module$build$src$core$block_animations=function(a){if(!(a.getDescendants(!1).length>100)){var b=a.workspace,c=a.getSvgRoot();b.getAudioManager().play("delete");var d=a.getRelativeToSurfaceXY(),e=c.cloneNode(!0);e.setAttribute("transform","translate("+d.x+","+d.y+")");var f;(f=b.getLayerManager())==null||f.appendToAnimationLayer({getSvgRoot:()=>e});disposeUiStep$$module$build$src$core$block_animations(e,{x:d.x,y:d.y,width:a.width,height:a.height},b.RTL,new Date)}};
disposeUiStep$$module$build$src$core$block_animations=function(a,b,c,d){const e=((new Date).getTime()-d.getTime())/150;e>1?removeNode$$module$build$src$core$utils$dom(a):(a.setAttribute("transform","translate("+(b.x+(c?-1:1)*b.width/2*e)+","+(b.y+b.height/2*e)+") scale("+(1-e)+")"),setTimeout(disposeUiStep$$module$build$src$core$block_animations,10,a,b,c,d))};
connectionUiEffect$$module$build$src$core$block_animations=function(a){var b=a.workspace;const c=b.scale;b.getAudioManager().play("click");if(!(c<1)){var d=b.getSvgXY(a.getSvgRoot());a.outputConnection?(d.x+=(a.RTL?3:-3)*c,d.y+=13*c):a.previousConnection&&(d.x+=(a.RTL?-23:23)*c,d.y+=3*c);var e=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.CIRCLE,{cx:d.x,cy:d.y,r:0,fill:"none",stroke:"#888","stroke-width":10},b.getParentSvg());a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.ANIMATE,
{id:"animationCircle",begin:"indefinite",attributeName:"r",dur:"150ms",from:0,to:25*c},e);b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.ANIMATE,{id:"animationOpacity",begin:"indefinite",attributeName:"opacity",dur:"150ms",from:1,to:0},e);a.beginElement();b.beginElement();setTimeout(()=>void removeNode$$module$build$src$core$utils$dom(e),150)}};
disconnectUiEffect$$module$build$src$core$block_animations=function(a){disconnectUiStop$$module$build$src$core$block_animations();a.workspace.getAudioManager().play("disconnect");if(!(a.workspace.scale<1)){var b=a.getHeightWidth().height;b=Math.atan(10/b)/Math.PI*180;a.RTL||(b*=-1);wobblingBlock$$module$build$src$core$block_animations=a;disconnectUiStep$$module$build$src$core$block_animations(a,b,new Date,0)}};
disconnectUiStep$$module$build$src$core$block_animations=function(a,b,c,d){const e=[.66,1,.66,0,-.66,-1,-.66,0];let f="";c.getTime()+200>(new Date).getTime()&&(f=`skewX(${Math.round(e[d%e.length]*b)})`,disconnectPid$$module$build$src$core$block_animations=setTimeout(disconnectUiStep$$module$build$src$core$block_animations,15,a,b,c,d+1));a.getSvgRoot().setAttribute("transform",`${a.getTranslation()} ${f}`)};
disconnectUiStop$$module$build$src$core$block_animations=function(){wobblingBlock$$module$build$src$core$block_animations&&(disconnectPid$$module$build$src$core$block_animations&&(clearTimeout(disconnectPid$$module$build$src$core$block_animations),disconnectPid$$module$build$src$core$block_animations=null),wobblingBlock$$module$build$src$core$block_animations.getSvgRoot().setAttribute("transform",wobblingBlock$$module$build$src$core$block_animations.getTranslation()),wobblingBlock$$module$build$src$core$block_animations=
null)};
moveBlockToNotConflict$$module$build$src$core$clipboard$block_paster=function(a,b){a.workspace.RTL&&(b.x=a.workspace.getWidth()-b.x);const c=a.workspace,d=$.config$$module$build$src$core$config.snapRadius,e=Coordinate$$module$build$src$core$utils$coordinate.difference(b,a.getRelativeToSurfaceXY()),f=new Coordinate$$module$build$src$core$utils$coordinate(0,0),g=c.getAllBlocks(!1).filter(h=>h.id!=a.id).map(h=>h.getRelativeToSurfaceXY());for(;blockOverlapsOtherExactly$$module$build$src$core$clipboard$block_paster(Coordinate$$module$build$src$core$utils$coordinate.sum(b,f),
g)||blockIsInSnapRadius$$module$build$src$core$clipboard$block_paster(a,Coordinate$$module$build$src$core$utils$coordinate.sum(e,f),d);)c.RTL?f.translate(-d,d*2):f.translate(d,d*2);a.moveTo(Coordinate$$module$build$src$core$utils$coordinate.sum(b,f))};blockOverlapsOtherExactly$$module$build$src$core$clipboard$block_paster=function(a,b){return b.some(c=>Math.abs(c.x-a.x)<=1&&Math.abs(c.y-a.y)<=1)};
blockIsInSnapRadius$$module$build$src$core$clipboard$block_paster=function(a,b,c){return a.getConnections_(!1).some(d=>!!d.closest(c,b).connection)};
bumpObjectIntoBounds$$module$build$src$core$bump_objects=function(a,b,c){const d=c.getBoundingRectangle(),e=d.right-d.left,f=clamp$$module$build$src$core$utils$math(b.top,d.top,b.top+b.height-(d.bottom-d.top))-d.top;let g=b.left;b=b.left+b.width-e;a.RTL?g=Math.min(b,g):b=Math.max(g,b);return(a=clamp$$module$build$src$core$utils$math(g,d.left,b)-d.left)||f?(c.moveBy(a,f,["inbounds"]),!0):!1};
bumpIntoBoundsHandler$$module$build$src$core$bump_objects=function(a){return b=>{var c=a.getMetricsManager();if(c.hasFixedEdges()&&!a.isDragging()){var d;if(BUMP_EVENTS$$module$build$src$core$events$type.includes((d=b.type)!=null?d:"")){d=c.getScrollMetrics(!0);const e=extractObjectFromEvent$$module$build$src$core$bump_objects(a,b);e&&(c=$.getGroup$$module$build$src$core$events$utils()||!1,$.setGroup$$module$build$src$core$events$utils(b.group),bumpObjectIntoBounds$$module$build$src$core$bump_objects(a,
d,e)&&!b.group&&console.warn("Moved object in bounds but there was no event group. This may break undo."),$.setGroup$$module$build$src$core$events$utils(c))}else isViewportChange$$module$build$src$core$events$predicates(b)&&b.scale&&b.oldScale&&b.scale>b.oldScale&&bumpTopObjectsIntoBounds$$module$build$src$core$bump_objects(a)}}};
extractObjectFromEvent$$module$build$src$core$bump_objects=function(a,b){let c=null;switch(b.type){case EventType$$module$build$src$core$events$type.BLOCK_CREATE:case EventType$$module$build$src$core$events$type.BLOCK_MOVE:(c=a.getBlockById(b.blockId))&&(c=c.getRootBlock());break;case EventType$$module$build$src$core$events$type.COMMENT_CREATE:case EventType$$module$build$src$core$events$type.COMMENT_MOVE:case EventType$$module$build$src$core$events$type.COMMENT_RESIZE:c=a.getCommentById(b.commentId)}return c};
bumpTopObjectsIntoBounds$$module$build$src$core$bump_objects=function(a){var b=a.getMetricsManager();if(b.hasFixedEdges()&&!a.isDragging()){b=b.getScrollMetrics(!0);var c=a.getTopBoundedElements();for(let d=0,e;e=c[d];d++)bumpObjectIntoBounds$$module$build$src$core$bump_objects(a,b,e)}};isDeletable$$module$build$src$core$interfaces$i_deletable=function(a){return a&&typeof a.isDeletable==="function"&&typeof a.dispose==="function"&&typeof a.setDeleteStyle==="function"};
getBlockNavigationCandidates$$module$build$src$core$keyboard_nav$block_navigation_policy=function(a,b){const c=a.getIcons();for(const d of a.inputList){if(!d.isVisible())continue;c.push(...d.fieldRow);let e;if((e=d.connection)==null?0:e.targetBlock())if(a=d.connection.targetBlock(),d.connection.type!==ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT||b)c.push(a);else{let f;(a=(f=a.lastConnectionInStack(!1))==null?void 0:f.getSourceBlock())&&c.push(a)}else{let f;((f=d.connection)==
null?void 0:f.type)===ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE&&c.push(d.connection)}}return c};
navigateStacks$$module$build$src$core$keyboard_nav$block_navigation_policy=function(a,b){const c=a.workspace.getTopBoundedElements(!0).filter(e=>isFocusableNode$$module$build$src$core$interfaces$i_focusable_node(e));a=c.indexOf(a instanceof BlockSvg$$module$build$src$core$block_svg?a.getRootBlock():a)+b;let d=null;a>=0&&a<c.length?d=c[a]:a<0?d=c[c.length-1]:a>=c.length&&(d=c[0]);if(b<0&&d instanceof BlockSvg$$module$build$src$core$block_svg){let e,f;return(f=(e=d.lastConnectionInStack(!1))==null?
void 0:e.getSourceBlock())!=null?f:d}return d};
navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy=function(a,b){var c;let d;const e=a instanceof BlockSvg$$module$build$src$core$block_svg?(d=(c=a.outputConnection)==null?void 0:c.targetBlock())!=null?d:a.getSurroundParent():a.getSourceBlock();if(!(e instanceof BlockSvg$$module$build$src$core$block_svg))return null;c=getBlockNavigationCandidates$$module$build$src$core$keyboard_nav$block_navigation_policy(e,b>0);a=c.indexOf(a);if(a===-1)return null;b=a+b;return b>=0&&b<c.length?
c[b]:null};register$$module$build$src$core$icons$registry=function(a,b){register$$module$build$src$core$registry(Type$$module$build$src$core$registry.ICON,a.toString(),b)};unregister$$module$build$src$core$icons$registry=function(a){unregister$$module$build$src$core$registry(Type$$module$build$src$core$registry.ICON,a)};
isDraggable$$module$build$src$core$interfaces$i_draggable=function(a){return a&&typeof a.getRelativeToSurfaceXY==="function"&&typeof a.isMovable==="function"&&typeof a.startDrag==="function"&&typeof a.drag==="function"&&typeof a.endDrag==="function"&&typeof a.revertDrag==="function"};isAutoHideable$$module$build$src$core$interfaces$i_autohideable=function(a){return a&&typeof a.autoHide==="function"};
isProcedureBlock$$module$build$src$core$interfaces$i_procedure_block=function(a){return typeof a.getProcedureModel==="function"&&typeof a.doProcedureUpdate==="function"&&typeof a.isProcedureDef==="function"};isObservable$$module$build$src$core$interfaces$i_observable=function(a){return a&&typeof a.startPublishing==="function"&&typeof a.stopPublishing==="function"};
allProcedures$$module$build$src$core$procedures=function(a){const b=a.getProcedureMap().getProcedures().filter(d=>!d.getReturnTypes()).map(d=>[d.getName(),d.getParameters().map(e=>e.getName()),!1]);a.getBlocksByType("procedures_defnoreturn",!1).forEach(d=>{!isProcedureBlock$$module$build$src$core$interfaces$i_procedure_block(d)&&isLegacyProcedureDefBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks(d)&&b.push(d.getProcedureDef())});const c=a.getProcedureMap().getProcedures().filter(d=>
!!d.getReturnTypes()).map(d=>[d.getName(),d.getParameters().map(e=>e.getName()),!0]);a.getBlocksByType("procedures_defreturn",!1).forEach(d=>{!isProcedureBlock$$module$build$src$core$interfaces$i_procedure_block(d)&&isLegacyProcedureDefBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks(d)&&c.push(d.getProcedureDef())});b.sort(procTupleComparator$$module$build$src$core$procedures);c.sort(procTupleComparator$$module$build$src$core$procedures);return[b,c]};
procTupleComparator$$module$build$src$core$procedures=function(a,b){return a[0].localeCompare(b[0],void 0,{sensitivity:"base"})};$.findLegalName$$module$build$src$core$procedures=function(a,b){if(b.isInFlyout)return a;for(a=a||$.Msg$$module$build$src$core$msg.UNNAMED_KEY||"unnamed";!isLegalName$$module$build$src$core$procedures(a,b.workspace,b);){const c=a.match(/^(.*?)(\d+)$/);a=c?c[1]+(parseInt(c[2])+1):a+"2"}return a};
isLegalName$$module$build$src$core$procedures=function(a,b,c){return!isNameUsed$$module$build$src$core$procedures(a,b,c)};
isNameUsed$$module$build$src$core$procedures=function(a,b,c){for(const d of b.getAllBlocks(!1))if(d!==c&&isLegacyProcedureDefBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks(d)&&$.Names$$module$build$src$core$names.equals(d.getProcedureDef()[0],a))return!0;c=c&&isProcedureBlock$$module$build$src$core$interfaces$i_procedure_block(c)?c==null?void 0:c.getProcedureModel():void 0;for(const d of b.getProcedureMap().getProcedures())if(d!==c&&$.Names$$module$build$src$core$names.equals(d.getName(),
a))return!0;return!1};
$.rename$$module$build$src$core$procedures=function(a){var b=this.getSourceBlock();if(!b)throw new UnattachedFieldError$$module$build$src$core$field;a=a.trim();const c=$.findLegalName$$module$build$src$core$procedures(a,b);isProcedureBlock$$module$build$src$core$interfaces$i_procedure_block(b)&&!b.isInsertionMarker()&&b.getProcedureModel().setName(c);const d=this.getValue();if(d!==a&&d!==c)for(a=b.workspace.getAllBlocks(!1),b=0;b<a.length;b++){const e=a[b];e.renameProcedure&&e.renameProcedure(d,c)}return c};
xmlFlyoutCategory$$module$build$src$core$procedures=function(a){function b(f,g){for(let k=0;k<f.length;k++){var h=f[k][0];const l=f[k][1],m=$.createElement$$module$build$src$core$utils$xml("block");m.setAttribute("type",g);m.setAttribute("gap","16");const n=$.createElement$$module$build$src$core$utils$xml("mutation");n.setAttribute("name",h);m.appendChild(n);for(h=0;h<l.length;h++){const p=$.createElement$$module$build$src$core$utils$xml("arg");p.setAttribute("name",l[h]);n.appendChild(p)}c.push(m)}}
const c=[];if(Blocks$$module$build$src$core$blocks.procedures_defnoreturn){var d=$.createElement$$module$build$src$core$utils$xml("block");d.setAttribute("type","procedures_defnoreturn");d.setAttribute("gap","16");var e=$.createElement$$module$build$src$core$utils$xml("field");e.setAttribute("name","NAME");e.appendChild($.createTextNode$$module$build$src$core$utils$xml($.Msg$$module$build$src$core$msg.PROCEDURES_DEFNORETURN_PROCEDURE));d.appendChild(e);c.push(d)}Blocks$$module$build$src$core$blocks.procedures_defreturn&&
(d=$.createElement$$module$build$src$core$utils$xml("block"),d.setAttribute("type","procedures_defreturn"),d.setAttribute("gap","16"),e=$.createElement$$module$build$src$core$utils$xml("field"),e.setAttribute("name","NAME"),e.appendChild($.createTextNode$$module$build$src$core$utils$xml($.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_PROCEDURE)),d.appendChild(e),c.push(d));Blocks$$module$build$src$core$blocks.procedures_ifreturn&&(d=$.createElement$$module$build$src$core$utils$xml("block"),
d.setAttribute("type","procedures_ifreturn"),d.setAttribute("gap","16"),c.push(d));c.length&&c[c.length-1].setAttribute("gap","24");a=allProcedures$$module$build$src$core$procedures(a);b(a[0],"procedures_callnoreturn");b(a[1],"procedures_callreturn");return c};internalFlyoutCategory$$module$build$src$core$procedures=function(a){return flyoutCategory$$module$build$src$core$procedures(a,!1)};
flyoutCategory$$module$build$src$core$procedures=function(a,b=!0){function c(e,f){for(const [g,h]of e)d.push({kind:"block",type:f,gap:16,extraState:{name:g,params:h}})}if(b)return warn$$module$build$src$core$utils$deprecation("The XML return value of Blockly.Procedures.flyoutCategory()","v12","v13","the same method, but handle a return type of FlyoutItemInfo[] (JSON) instead."),xmlFlyoutCategory$$module$build$src$core$procedures(a);const d=[];Blocks$$module$build$src$core$blocks.procedures_defnoreturn&&
d.push({kind:"block",type:"procedures_defnoreturn",gap:16,fields:{NAME:$.Msg$$module$build$src$core$msg.PROCEDURES_DEFNORETURN_PROCEDURE}});Blocks$$module$build$src$core$blocks.procedures_defreturn&&d.push({kind:"block",type:"procedures_defreturn",gap:16,fields:{NAME:$.Msg$$module$build$src$core$msg.PROCEDURES_DEFRETURN_PROCEDURE}});Blocks$$module$build$src$core$blocks.procedures_ifreturn&&d.push({kind:"block",type:"procedures_ifreturn",gap:16});d.length&&(d[d.length-1].gap=24);a=allProcedures$$module$build$src$core$procedures(a);
c(a[0],"procedures_callnoreturn");c(a[1],"procedures_callreturn");return d};
updateMutatorFlyout$$module$build$src$core$procedures=function(a){var b=[],c=a.getBlocksByType("procedures_mutatorarg",!1);for(let f=0,g;g=c[f];f++)b.push(g.getFieldValue("NAME"));c=$.createElement$$module$build$src$core$utils$xml("xml");const d=$.createElement$$module$build$src$core$utils$xml("block");d.setAttribute("type","procedures_mutatorarg");const e=$.createElement$$module$build$src$core$utils$xml("field");e.setAttribute("name","NAME");b=generateUniqueNameFromOptions$$module$build$src$core$variables($.DEFAULT_ARG$$module$build$src$core$procedures,
b);b=$.createTextNode$$module$build$src$core$utils$xml(b);e.appendChild(b);d.appendChild(e);c.appendChild(d);a.updateToolbox(c)};
mutatorOpenListener$$module$build$src$core$procedures=function(a){if(isBubbleOpen$$module$build$src$core$events$predicates(a)&&a.bubbleType==="mutator"&&a.isOpen&&a.blockId){a=getWorkspaceById$$module$build$src$core$common(a.workspaceId).getBlockById(a.blockId);var b=a.type;if(b==="procedures_defnoreturn"||b==="procedures_defreturn")a=a.getIcon($.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE).getWorkspace(),updateMutatorFlyout$$module$build$src$core$procedures(a),a.addChangeListener(mutatorChangeListener$$module$build$src$core$procedures)}};
mutatorChangeListener$$module$build$src$core$procedures=function(a){if(isBlockCreate$$module$build$src$core$events$predicates(a)||isBlockDelete$$module$build$src$core$events$predicates(a)||isBlockChange$$module$build$src$core$events$predicates(a)||isBlockFieldIntermediateChange$$module$build$src$core$events$predicates(a))a=getWorkspaceById$$module$build$src$core$common(a.workspaceId),updateMutatorFlyout$$module$build$src$core$procedures(a)};
getCallers$$module$build$src$core$procedures=function(a,b){return b.getAllBlocks(!1).filter(c=>blockIsModernCallerFor$$module$build$src$core$procedures(c,a)||isLegacyProcedureCallBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks(c)&&$.Names$$module$build$src$core$names.equals(c.getProcedureCall(),a))};
blockIsModernCallerFor$$module$build$src$core$procedures=function(a,b){return isProcedureBlock$$module$build$src$core$interfaces$i_procedure_block(a)&&!a.isProcedureDef()&&a.getProcedureModel()&&$.Names$$module$build$src$core$names.equals(a.getProcedureModel().getName(),b)};
$.mutateCallers$$module$build$src$core$procedures=function(a){const b=getRecordUndo$$module$build$src$core$events$utils();var c=a.getProcedureDef()[0];const d=a.mutationToDom(!0);a=getCallers$$module$build$src$core$procedures(c,a.workspace);for(let f=0,g;g=a[f];f++){c=(c=g.mutationToDom())&&domToText$$module$build$src$core$utils$xml(c);g.domToMutation&&g.domToMutation(d);var e=g.mutationToDom();e=e&&domToText$$module$build$src$core$utils$xml(e);c!==e&&($.setRecordUndo$$module$build$src$core$events$utils(!1),
fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CHANGE))(g,"mutation",null,c,e)),$.setRecordUndo$$module$build$src$core$events$utils(b))}};
$.getDefinition$$module$build$src$core$procedures=function(a,b){for(const c of b.getAllBlocks(!1))if(isProcedureBlock$$module$build$src$core$interfaces$i_procedure_block(c)&&c.isProcedureDef()&&$.Names$$module$build$src$core$names.equals(c.getProcedureModel().getName(),a)||isLegacyProcedureDefBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks(c)&&$.Names$$module$build$src$core$names.equals(c.getProcedureDef()[0],a))return c;return null};
isDynamicShape$$module$build$src$core$renderers$common$constants=function(a){return a.isDynamic};isPuzzleTab$$module$build$src$core$renderers$common$constants=function(a){return a.pathDown!==void 0&&a.pathUp!==void 0};isNotch$$module$build$src$core$renderers$common$constants=function(a){return a.pathLeft!==void 0&&a.pathRight!==void 0};
register$$module$build$src$core$renderers$common$block_rendering=function(a,b){register$$module$build$src$core$registry(Type$$module$build$src$core$registry.RENDERER,a,b)};unregister$$module$build$src$core$renderers$common$block_rendering=function(a){unregister$$module$build$src$core$registry(Type$$module$build$src$core$registry.RENDERER,a)};
init$$module$build$src$core$renderers$common$block_rendering=function(a,b,c){a=new (getClass$$module$build$src$core$registry(Type$$module$build$src$core$registry.RENDERER,a))(a);a.init(b,c);return a};stringButtonClickHandler$$module$build$src$core$variables_dynamic=function(a){createVariableButtonHandler$$module$build$src$core$variables(a.getTargetWorkspace(),void 0,"String")};
numberButtonClickHandler$$module$build$src$core$variables_dynamic=function(a){createVariableButtonHandler$$module$build$src$core$variables(a.getTargetWorkspace(),void 0,"Number")};colourButtonClickHandler$$module$build$src$core$variables_dynamic=function(a){createVariableButtonHandler$$module$build$src$core$variables(a.getTargetWorkspace(),void 0,"Colour")};
internalFlyoutCategory$$module$build$src$core$variables_dynamic=function(a){return flyoutCategory$$module$build$src$core$variables_dynamic(a,!1)};
flyoutCategory$$module$build$src$core$variables_dynamic=function(a,b=!0){Blocks$$module$build$src$core$blocks.variables_set_dynamic||Blocks$$module$build$src$core$blocks.variables_get_dynamic||console.warn("There are no dynamic variable blocks, but there is a dynamic variable category.");if(b)return warn$$module$build$src$core$utils$deprecation("The XML return value of Blockly.VariablesDynamic.flyoutCategory()","v12","v13","the same method, but handle a return type of FlyoutItemInfo[] (JSON) instead."),
xmlFlyoutCategory$$module$build$src$core$variables_dynamic(a);a.registerButtonCallback("CREATE_VARIABLE_STRING",stringButtonClickHandler$$module$build$src$core$variables_dynamic);a.registerButtonCallback("CREATE_VARIABLE_NUMBER",numberButtonClickHandler$$module$build$src$core$variables_dynamic);a.registerButtonCallback("CREATE_VARIABLE_COLOUR",colourButtonClickHandler$$module$build$src$core$variables_dynamic);return[{kind:"button",text:$.Msg$$module$build$src$core$msg.NEW_STRING_VARIABLE,callbackkey:"CREATE_VARIABLE_STRING"},
{kind:"button",text:$.Msg$$module$build$src$core$msg.NEW_NUMBER_VARIABLE,callbackkey:"CREATE_VARIABLE_NUMBER"},{kind:"button",text:$.Msg$$module$build$src$core$msg.NEW_COLOUR_VARIABLE,callbackkey:"CREATE_VARIABLE_COLOUR"},...jsonFlyoutCategoryBlocks$$module$build$src$core$variables(a,a.getVariableMap().getAllVariables(),!1,"variables_get_dynamic","variables_set_dynamic")]};
xmlFlyoutCategory$$module$build$src$core$variables_dynamic=function(a){let b=[],c=document.createElement("button");c.setAttribute("text",$.Msg$$module$build$src$core$msg.NEW_STRING_VARIABLE);c.setAttribute("callbackKey","CREATE_VARIABLE_STRING");b.push(c);c=document.createElement("button");c.setAttribute("text",$.Msg$$module$build$src$core$msg.NEW_NUMBER_VARIABLE);c.setAttribute("callbackKey","CREATE_VARIABLE_NUMBER");b.push(c);c=document.createElement("button");c.setAttribute("text",$.Msg$$module$build$src$core$msg.NEW_COLOUR_VARIABLE);
c.setAttribute("callbackKey","CREATE_VARIABLE_COLOUR");b.push(c);a.registerButtonCallback("CREATE_VARIABLE_STRING",stringButtonClickHandler$$module$build$src$core$variables_dynamic);a.registerButtonCallback("CREATE_VARIABLE_NUMBER",numberButtonClickHandler$$module$build$src$core$variables_dynamic);a.registerButtonCallback("CREATE_VARIABLE_COLOUR",colourButtonClickHandler$$module$build$src$core$variables_dynamic);a=flyoutCategoryBlocks$$module$build$src$core$variables_dynamic(a);return b=b.concat(a)};
flyoutCategoryBlocks$$module$build$src$core$variables_dynamic=function(a){a=a.getVariableMap().getAllVariables();const b=[];if(a.length>0){if(Blocks$$module$build$src$core$blocks.variables_set_dynamic){var c=a[a.length-1];const d=$.createElement$$module$build$src$core$utils$xml("block");d.setAttribute("type","variables_set_dynamic");d.setAttribute("gap","24");d.appendChild(generateVariableFieldDom$$module$build$src$core$variables(c));b.push(d)}if(Blocks$$module$build$src$core$blocks.variables_get_dynamic){a.sort(compareByName$$module$build$src$core$variables);
for(let d=0,e;e=a[d];d++)c=$.createElement$$module$build$src$core$utils$xml("block"),c.setAttribute("type","variables_get_dynamic"),c.setAttribute("gap","8"),c.appendChild(generateVariableFieldDom$$module$build$src$core$variables(e)),b.push(c)}}return b};resizeSvgContents$$module$build$src$core$workspace_svg=function(a){a.resizeContents()};
copy$$module$build$src$core$clipboard=function(a,b){const c=a.toCopyData();stashedCopyData$$module$build$src$core$clipboard=c;stashedWorkspace$$module$build$src$core$clipboard=isSelectable$$module$build$src$core$interfaces$i_selectable(a)&&a.workspace instanceof WorkspaceSvg$$module$build$src$core$workspace_svg?a.workspace:null;stashedCoordinates$$module$build$src$core$clipboard=b;return c};getLastCopiedData$$module$build$src$core$clipboard=function(){return stashedCopyData$$module$build$src$core$clipboard};
setLastCopiedData$$module$build$src$core$clipboard=function(a){stashedCopyData$$module$build$src$core$clipboard=a};getLastCopiedWorkspace$$module$build$src$core$clipboard=function(){return stashedWorkspace$$module$build$src$core$clipboard};setLastCopiedWorkspace$$module$build$src$core$clipboard=function(a){stashedWorkspace$$module$build$src$core$clipboard=a};getLastCopiedLocation$$module$build$src$core$clipboard=function(){return stashedCoordinates$$module$build$src$core$clipboard};
setLastCopiedLocation$$module$build$src$core$clipboard=function(a){stashedCoordinates$$module$build$src$core$clipboard=a};
paste$$module$build$src$core$clipboard=function(a,b,c){return a&&b?pasteFromData$$module$build$src$core$clipboard(a,b,c):stashedCopyData$$module$build$src$core$clipboard&&stashedWorkspace$$module$build$src$core$clipboard?pasteFromData$$module$build$src$core$clipboard(stashedCopyData$$module$build$src$core$clipboard,stashedWorkspace$$module$build$src$core$clipboard,stashedCoordinates$$module$build$src$core$clipboard):null};
pasteFromData$$module$build$src$core$clipboard=function(a,b,c){let d;b=b.isMutator?b:(d=b.options.parentWorkspace)!=null?d:b;let e,f;return(f=(e=getObject$$module$build$src$core$registry(Type$$module$build$src$core$registry.PASTER,a.paster,!1))==null?void 0:e.paste(a,b,c))!=null?f:null};isCopyable$$module$build$src$core$interfaces$i_copyable=function(a){return a&&typeof a.toCopyData==="function"};
registerEscape$$module$build$src$core$shortcut_items=function(){ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.register({name:names$$module$build$src$core$shortcut_items.ESCAPE,preconditionFn(a){return!a.isReadOnly()},callback(a){a.hideChaff();return!0},keyCodes:[KeyCodes$$module$build$src$core$utils$keycodes.ESC]})};
registerDelete$$module$build$src$core$shortcut_items=function(){ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.register({name:names$$module$build$src$core$shortcut_items.DELETE,preconditionFn(a,b){b=b.focusedNode;return!a.isReadOnly()&&b!=null&&isDeletable$$module$build$src$core$interfaces$i_deletable(b)&&b.isDeletable()&&!a.isDragging()&&!$.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()},callback(a,b,c,d){b.preventDefault();a=d.focusedNode;a instanceof
BlockSvg$$module$build$src$core$block_svg?a.checkAndDelete():isDeletable$$module$build$src$core$interfaces$i_deletable(a)&&a.isDeletable()&&($.setGroup$$module$build$src$core$events$utils(!0),a.dispose(),$.setGroup$$module$build$src$core$events$utils(!1));return!0},keyCodes:[KeyCodes$$module$build$src$core$utils$keycodes.DELETE,KeyCodes$$module$build$src$core$utils$keycodes.BACKSPACE]})};
isCopyable$$module$build$src$core$shortcut_items=function(a){return isCopyable$$module$build$src$core$interfaces$i_copyable(a)&&isDeletable$$module$build$src$core$interfaces$i_deletable(a)&&isDraggable$$module$build$src$core$interfaces$i_draggable(a)?a.isCopyable?a.isCopyable():a instanceof BlockSvg$$module$build$src$core$block_svg||a instanceof RenderedWorkspaceComment$$module$build$src$core$comments$rendered_workspace_comment?a.isOwnDeletable()&&a.isOwnMovable():a.isDeletable()&&a.isMovable():!1};
isCuttable$$module$build$src$core$shortcut_items=function(a){return isCopyable$$module$build$src$core$shortcut_items(a)&&isDeletable$$module$build$src$core$interfaces$i_deletable(a)&&a.isDeletable()};
registerCopy$$module$build$src$core$shortcut_items=function(){const a=ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.createSerializedKey(KeyCodes$$module$build$src$core$utils$keycodes.C,[KeyCodes$$module$build$src$core$utils$keycodes.CTRL]),b=ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.createSerializedKey(KeyCodes$$module$build$src$core$utils$keycodes.C,[KeyCodes$$module$build$src$core$utils$keycodes.META]);ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.register({name:names$$module$build$src$core$shortcut_items.COPY,
preconditionFn(c,d){d=d.focusedNode;c=c.isFlyout?c.targetWorkspace:c;return!!d&&!!c&&!c.isDragging()&&!$.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()&&isCopyable$$module$build$src$core$shortcut_items(d)},callback(c,d,e,f){d.preventDefault();d=f.focusedNode;if(!d||!isCopyable$$module$build$src$core$interfaces$i_copyable(d)||!isCopyable$$module$build$src$core$shortcut_items(d))return!1;c=c.isFlyout?c.targetWorkspace:c;if(!c)return!1;d.workspace.isFlyout||c.hideChaff();
c=isDraggable$$module$build$src$core$interfaces$i_draggable(d)&&d.workspace==c?d.getRelativeToSurfaceXY():void 0;return!!copy$$module$build$src$core$clipboard(d,c)},keyCodes:[a,b]})};
registerCut$$module$build$src$core$shortcut_items=function(){const a=ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.createSerializedKey(KeyCodes$$module$build$src$core$utils$keycodes.X,[KeyCodes$$module$build$src$core$utils$keycodes.CTRL]),b=ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.createSerializedKey(KeyCodes$$module$build$src$core$utils$keycodes.X,[KeyCodes$$module$build$src$core$utils$keycodes.META]);ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.register({name:names$$module$build$src$core$shortcut_items.CUT,
preconditionFn(c,d){d=d.focusedNode;return!!d&&!c.isReadOnly()&&!c.isDragging()&&!$.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()&&isCuttable$$module$build$src$core$shortcut_items(d)},callback(c,d,e,f){c=f.focusedNode;if(!c||!isCuttable$$module$build$src$core$shortcut_items(c)||!isCopyable$$module$build$src$core$interfaces$i_copyable(c))return!1;d=isDraggable$$module$build$src$core$interfaces$i_draggable(c)?c.getRelativeToSurfaceXY():void 0;d=copy$$module$build$src$core$clipboard(c,
d);c instanceof BlockSvg$$module$build$src$core$block_svg?c.checkAndDelete():isDeletable$$module$build$src$core$interfaces$i_deletable(c)&&c.dispose();return!!d},keyCodes:[a,b]})};
registerPaste$$module$build$src$core$shortcut_items=function(){const a=ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.createSerializedKey(KeyCodes$$module$build$src$core$utils$keycodes.V,[KeyCodes$$module$build$src$core$utils$keycodes.CTRL]),b=ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.createSerializedKey(KeyCodes$$module$build$src$core$utils$keycodes.V,[KeyCodes$$module$build$src$core$utils$keycodes.META]);ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.register({name:names$$module$build$src$core$shortcut_items.PASTE,
preconditionFn(){var c=getLastCopiedWorkspace$$module$build$src$core$clipboard();if(!c||!c.rendered)return!1;c=c.isFlyout?c.targetWorkspace:c;return!!getLastCopiedData$$module$build$src$core$clipboard()&&!!c&&!c.isReadOnly()&&!c.isDragging()&&!$.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()},callback(c,d){c=getLastCopiedData$$module$build$src$core$clipboard();if(!c)return!1;var e=getLastCopiedWorkspace$$module$build$src$core$clipboard();if(!e)return!1;e=e.isFlyout?e.targetWorkspace:
e;if(!e||e.isReadOnly())return!1;if(d instanceof PointerEvent)return d=screenToWsCoordinates$$module$build$src$core$utils$svg_math(e,new Coordinate$$module$build$src$core$utils$coordinate(d.clientX,d.clientY)),!!paste$$module$build$src$core$clipboard(c,e,d);d=getLastCopiedLocation$$module$build$src$core$clipboard();if(!d)return!!paste$$module$build$src$core$clipboard(c,e);const {left:f,top:g,width:h,height:k}=e.getMetricsManager().getViewMetrics(!0);if((new Rect$$module$build$src$core$utils$rect(g,
g+k,f,f+h)).contains(d.x,d.y))return!!paste$$module$build$src$core$clipboard(c,e);d=new Coordinate$$module$build$src$core$utils$coordinate(f+h/2,g+k/2);return!!paste$$module$build$src$core$clipboard(c,e,d)},keyCodes:[a,b]})};
registerUndo$$module$build$src$core$shortcut_items=function(){const a=ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.createSerializedKey(KeyCodes$$module$build$src$core$utils$keycodes.Z,[KeyCodes$$module$build$src$core$utils$keycodes.CTRL]),b=ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.createSerializedKey(KeyCodes$$module$build$src$core$utils$keycodes.Z,[KeyCodes$$module$build$src$core$utils$keycodes.META]);ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.register({name:names$$module$build$src$core$shortcut_items.UNDO,
preconditionFn(c){return!c.isReadOnly()&&!c.isDragging()&&!$.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()},callback(c,d){c.hideChaff();c.undo(!1);d.preventDefault();return!0},keyCodes:[a,b]})};
registerRedo$$module$build$src$core$shortcut_items=function(){const a=ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.createSerializedKey(KeyCodes$$module$build$src$core$utils$keycodes.Z,[KeyCodes$$module$build$src$core$utils$keycodes.CTRL,KeyCodes$$module$build$src$core$utils$keycodes.SHIFT]),b=ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.createSerializedKey(KeyCodes$$module$build$src$core$utils$keycodes.Z,[KeyCodes$$module$build$src$core$utils$keycodes.META,
KeyCodes$$module$build$src$core$utils$keycodes.SHIFT]),c=ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.createSerializedKey(KeyCodes$$module$build$src$core$utils$keycodes.Y,[KeyCodes$$module$build$src$core$utils$keycodes.CTRL]);ShortcutRegistry$$module$build$src$core$shortcut_registry.registry.register({name:names$$module$build$src$core$shortcut_items.REDO,preconditionFn(d){return!d.isDragging()&&!d.isReadOnly()&&!$.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()},
callback(d,e){d.hideChaff();d.undo(!0);e.preventDefault();return!0},keyCodes:[a,b,c]})};registerDefaultShortcuts$$module$build$src$core$shortcut_items=function(){registerEscape$$module$build$src$core$shortcut_items();registerDelete$$module$build$src$core$shortcut_items();registerCopy$$module$build$src$core$shortcut_items();registerCut$$module$build$src$core$shortcut_items();registerPaste$$module$build$src$core$shortcut_items();registerUndo$$module$build$src$core$shortcut_items();registerRedo$$module$build$src$core$shortcut_items()};
saveProcedure$$module$build$src$core$serialization$procedures=function(a){const b=a.saveState();if(!a.getParameters().length)return b;b.parameters=a.getParameters().map(c=>c.saveState());return b};loadProcedure$$module$build$src$core$serialization$procedures=function(a,b,c,d){a=a.loadState(c,d);if(!c.parameters)return a;for(const [e,f]of c.parameters.entries())a.insertParameter(b.loadState(f,d),e);return a};
save$$module$build$src$core$serialization$workspaces=function(a){const b=Object.create(null),c=getAllItems$$module$build$src$core$registry(Type$$module$build$src$core$registry.SERIALIZER,!0);for(const d in c){let e;const f=(e=c[d])==null?void 0:e.save(a);f&&(b[d]=f)}return b};
load$$module$build$src$core$serialization$workspaces=function(a,b,{recordUndo:c=!1}={}){var d=getAllItems$$module$build$src$core$registry(Type$$module$build$src$core$registry.SERIALIZER,!0);if(d){d=Object.entries(d).sort((f,g)=>g[1].priority-f[1].priority);var e=getRecordUndo$$module$build$src$core$events$utils();$.setRecordUndo$$module$build$src$core$events$utils(c);(c=$.getGroup$$module$build$src$core$events$utils())||$.setGroup$$module$build$src$core$events$utils(!0);startTextWidthCache$$module$build$src$core$utils$dom();
b instanceof WorkspaceSvg$$module$build$src$core$workspace_svg&&b.setResizesEnabled(!1);for(const [,f]of d.reverse()){let g;(g=f)==null||g.clear(b)}for(const [f,g]of d.reverse())if(a[f]){let h;(h=g)==null||h.load(a[f],b)}b instanceof WorkspaceSvg$$module$build$src$core$workspace_svg&&b.setResizesEnabled(!0);stopTextWidthCache$$module$build$src$core$utils$dom();fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.FINISHED_LOADING))(b));
$.setGroup$$module$build$src$core$events$utils(c);$.setRecordUndo$$module$build$src$core$events$utils(e)}};
inject$$module$build$src$core$inject=function(a,b){let c=null;c=typeof a==="string"?document.getElementById(a)||document.querySelector(a):a;var d;if(!document.contains(c)&&document!==((d=c)==null?void 0:d.ownerDocument))throw Error("Error: container is not in current document");a=new Options$$module$build$src$core$options(b||{});d=document.createElement("div");addClass$$module$build$src$core$utils$dom(d,"injectionDiv");(b==null?0:b.rtl)&&addClass$$module$build$src$core$utils$dom(d,"blocklyRTL");c.appendChild(d);
b=createDom$$module$build$src$core$inject(d,a);const e=createMainWorkspace$$module$build$src$core$inject(d,b,a);init$$module$build$src$core$inject(e);setMainWorkspace$$module$build$src$core$common(e);svgResize$$module$build$src$core$common(e);d.addEventListener("focusin",function(){setMainWorkspace$$module$build$src$core$common(e)});conditionalBind$$module$build$src$core$browser_events(d,"keydown",null,globalShortcutHandler$$module$build$src$core$common);return e};
createDom$$module$build$src$core$inject=function(a,b){a.setAttribute("dir","LTR");inject$$module$build$src$core$css(b.hasCss,b.pathToMedia);const c=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.SVG,{xmlns:SVG_NS$$module$build$src$core$utils$dom,"xmlns:html":HTML_NS$$module$build$src$core$utils$dom,"xmlns:xlink":XLINK_NS$$module$build$src$core$utils$dom,version:"1.1","class":"blocklySvg"},a),d=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.DEFS,
{},c),e=String(Math.random()).substring(2);b.gridPattern=Grid$$module$build$src$core$grid.createDom(e,b.gridOptions,d,a);return c};
createMainWorkspace$$module$build$src$core$inject=function(a,b,c){c.parentWorkspace=null;c=new WorkspaceSvg$$module$build$src$core$workspace_svg(c);const d=c.options;c.scale=d.zoomOptions.startScale;b.appendChild(c.createDom("blocklyMainBackground",a));var e=c.getRenderer().getClassName();e&&addClass$$module$build$src$core$utils$dom(a,e);(e=c.getTheme().getClassName())&&addClass$$module$build$src$core$utils$dom(a,e);!d.hasCategories&&d.languageTree&&(a=c.addFlyout(Svg$$module$build$src$core$utils$svg.SVG),
insertAfter$$module$build$src$core$utils$dom(a,b));d.hasTrashcan&&c.addTrashcan();d.zoomOptions&&d.zoomOptions.controls&&c.addZoomControls();c.getThemeManager().subscribe(b,"workspaceBackgroundColour","background-color");c.translate(0,0);c.addChangeListener(bumpIntoBoundsHandler$$module$build$src$core$bump_objects(c));svgResize$$module$build$src$core$common(c);createDom$$module$build$src$core$widgetdiv();createDom$$module$build$src$core$dropdowndiv();createDom$$module$build$src$core$tooltip();return c};
init$$module$build$src$core$inject=function(a){const b=a.options;var c=a.getParentSvg();conditionalBind$$module$build$src$core$browser_events(c.parentNode,"contextmenu",null,function(d){isTargetInput$$module$build$src$core$browser_events(d)||d.preventDefault()});c=conditionalBind$$module$build$src$core$browser_events(window,"resize",null,function(){hide$$module$build$src$core$tooltip();a.hideComponents(!0);repositionForWindowResize$$module$build$src$core$dropdowndiv();repositionForWindowResize$$module$build$src$core$widgetdiv();
svgResize$$module$build$src$core$common(a);bumpTopObjectsIntoBounds$$module$build$src$core$bump_objects(a)});a.setResizeHandlerWrapper(c);bindDocumentEvents$$module$build$src$core$inject();if(b.languageTree){c=a.getToolbox();const d=a.getFlyout(!0);c?c.init():d&&(d.init(a),d.show(b.languageTree),typeof d.scrollToStart==="function"&&d.scrollToStart())}b.hasTrashcan&&a.trashcan.init();b.zoomOptions&&b.zoomOptions.controls&&a.zoomControls_.init();b.moveOptions&&b.moveOptions.scrollbars?(a.scrollbar=
new ScrollbarPair$$module$build$src$core$scrollbar_pair(a,b.moveOptions.scrollbars===!0||!!b.moveOptions.scrollbars.horizontal,b.moveOptions.scrollbars===!0||!!b.moveOptions.scrollbars.vertical,"blocklyMainWorkspaceScrollbar"),a.scrollbar.resize()):a.setMetrics({x:.5,y:.5});b.hasSounds&&loadSounds$$module$build$src$core$inject(b.pathToMedia,a)};
bindDocumentEvents$$module$build$src$core$inject=function(){documentEventsBound$$module$build$src$core$inject||(conditionalBind$$module$build$src$core$browser_events(document,"scroll",null,function(){const a=getAllWorkspaces$$module$build$src$core$common();for(let b=0,c;c=a[b];b++)c instanceof WorkspaceSvg$$module$build$src$core$workspace_svg&&c.updateInverseScreenCTM()}),bind$$module$build$src$core$browser_events(document,"touchend",null,longStop$$module$build$src$core$touch),bind$$module$build$src$core$browser_events(document,
"touchcancel",null,longStop$$module$build$src$core$touch));documentEventsBound$$module$build$src$core$inject=!0};
loadSounds$$module$build$src$core$inject=function(a,b){function c(){for(;e.length;){const f=e.pop();f&&unbind$$module$build$src$core$browser_events(f)}d.preload()}const d=b.getAudioManager();d.load([a+"click.mp3",a+"click.wav",a+"click.ogg"],"click");d.load([a+"disconnect.wav",a+"disconnect.mp3",a+"disconnect.ogg"],"disconnect");d.load([a+"delete.mp3",a+"delete.ogg",a+"delete.wav"],"delete");const e=[];e.push(conditionalBind$$module$build$src$core$browser_events(document,"pointermove",null,c,!0));
e.push(conditionalBind$$module$build$src$core$browser_events(document,"touchstart",null,c,!0))};isFullBlockField$$module$build$src$core$contextmenu_items=function(a){if(!a||!a.isSimpleReporter())return!1;let b;return(b=a.getFields().next().value)==null?void 0:b.isFullBlockField()};
registerUndo$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(){return $.Msg$$module$build$src$core$msg.UNDO},preconditionFn(a){return a.workspace.getUndoStack().length>0?"enabled":"disabled"},callback(a){a.workspace.undo(!1)},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.WORKSPACE,id:"undoWorkspace",weight:1})};
registerRedo$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(){return $.Msg$$module$build$src$core$msg.REDO},preconditionFn(a){return a.workspace.getRedoStack().length>0?"enabled":"disabled"},callback(a){a.workspace.undo(!0)},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.WORKSPACE,id:"redoWorkspace",weight:2})};
registerCleanup$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(){return $.Msg$$module$build$src$core$msg.CLEAN_UP},preconditionFn(a){return a.workspace.isMovable()?a.workspace.getTopBlocks(!1).length>1?"enabled":"disabled":"hidden"},callback(a){a.workspace.cleanUp()},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.WORKSPACE,id:"cleanWorkspace",weight:3})};
toggleOption_$$module$build$src$core$contextmenu_items=function(a,b){function c(f){e--;f.setCollapsed(a);e===0&&$.setGroup$$module$build$src$core$events$utils(!1)}let d=0,e=0;$.setGroup$$module$build$src$core$events$utils(!0);for(let f=0;f<b.length;f++){let g=b[f];for(;g;)e++,setTimeout(c.bind(null,g),d),g=g.getNextBlock(),d+=10}};
registerCollapse$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(){return $.Msg$$module$build$src$core$msg.COLLAPSE_ALL},preconditionFn(a){if(a.workspace.options.collapse){a=a.workspace.getTopBlocks(!1);for(let b=0;b<a.length;b++){let c=a[b];for(;c;){if(!c.isCollapsed())return"enabled";c=c.getNextBlock()}}return"disabled"}return"hidden"},callback(a){toggleOption_$$module$build$src$core$contextmenu_items(!0,
a.workspace.getTopBlocks(!0))},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.WORKSPACE,id:"collapseWorkspace",weight:4})};
registerExpand$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(){return $.Msg$$module$build$src$core$msg.EXPAND_ALL},preconditionFn(a){if(a.workspace.options.collapse){a=a.workspace.getTopBlocks(!1);for(let b=0;b<a.length;b++){let c=a[b];for(;c;){if(c.isCollapsed())return"enabled";c=c.getNextBlock()}}return"disabled"}return"hidden"},callback(a){toggleOption_$$module$build$src$core$contextmenu_items(!1,
a.workspace.getTopBlocks(!0))},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.WORKSPACE,id:"expandWorkspace",weight:5})};addDeletableBlocks_$$module$build$src$core$contextmenu_items=function(a,b){if(a.isDeletable())Array.prototype.push.apply(b,a.getDescendants(!1));else{a=a.getChildren(!1);for(let c=0;c<a.length;c++)addDeletableBlocks_$$module$build$src$core$contextmenu_items(a[c],b)}};
getDeletableBlocks_$$module$build$src$core$contextmenu_items=function(a){const b=[];a=a.getTopBlocks(!0);for(let c=0;c<a.length;c++)addDeletableBlocks_$$module$build$src$core$contextmenu_items(a[c],b);return b};
deleteNext_$$module$build$src$core$contextmenu_items=function(a,b){b?$.setGroup$$module$build$src$core$events$utils(b):($.setGroup$$module$build$src$core$events$utils(!0),b=$.getGroup$$module$build$src$core$events$utils());const c=a.shift();c&&(c.isDeadOrDying()?deleteNext_$$module$build$src$core$contextmenu_items(a,b):(c.dispose(!1,!0),setTimeout(deleteNext_$$module$build$src$core$contextmenu_items,10,a,b)));$.setGroup$$module$build$src$core$events$utils(!1)};
registerDeleteAll$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(a){if(!a.workspace)return"";a=getDeletableBlocks_$$module$build$src$core$contextmenu_items(a.workspace).length;return a===1?$.Msg$$module$build$src$core$msg.DELETE_BLOCK:$.Msg$$module$build$src$core$msg.DELETE_X_BLOCKS.replace("%1",`${a}`)},preconditionFn(a){return a.workspace?getDeletableBlocks_$$module$build$src$core$contextmenu_items(a.workspace).length>
0?"enabled":"disabled":"disabled"},callback(a){if(a.workspace){a.workspace.cancelCurrentGesture();var b=getDeletableBlocks_$$module$build$src$core$contextmenu_items(a.workspace);b.length<2?deleteNext_$$module$build$src$core$contextmenu_items(b):confirm$$module$build$src$core$dialog($.Msg$$module$build$src$core$msg.DELETE_ALL_BLOCKS.replace("%1",String(b.length)),function(c){c&&deleteNext_$$module$build$src$core$contextmenu_items(b)})}},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.WORKSPACE,
id:"workspaceDelete",weight:6})};registerWorkspaceOptions_$$module$build$src$core$contextmenu_items=function(){registerUndo$$module$build$src$core$contextmenu_items();registerRedo$$module$build$src$core$contextmenu_items();registerCleanup$$module$build$src$core$contextmenu_items();registerCollapse$$module$build$src$core$contextmenu_items();registerExpand$$module$build$src$core$contextmenu_items();registerDeleteAll$$module$build$src$core$contextmenu_items()};
registerDuplicate$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(){return $.Msg$$module$build$src$core$msg.DUPLICATE_BLOCK},preconditionFn(a){a=a.block;return!a.isInFlyout&&a.isDeletable()&&a.isMovable()?a.isDuplicatable()?"enabled":"disabled":"hidden"},callback(a){if(a.block){var b=a.block.toCopyData();b&&paste$$module$build$src$core$clipboard(b,a.block.workspace)}},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.BLOCK,
id:"blockDuplicate",weight:1})};
registerComment$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(a){return a.block.hasIcon(CommentIcon$$module$build$src$core$icons$comment_icon.TYPE)?$.Msg$$module$build$src$core$msg.REMOVE_COMMENT:$.Msg$$module$build$src$core$msg.ADD_COMMENT},preconditionFn(a){a=a.block;return!a||a.isInFlyout||!a.workspace.options.comments||a.isCollapsed()||!a.isEditable()||!a.hasIcon(CommentIcon$$module$build$src$core$icons$comment_icon.TYPE)&&isFullBlockField$$module$build$src$core$contextmenu_items(a)?
"hidden":"enabled"},callback(a){(a=a.block)&&a.hasIcon(CommentIcon$$module$build$src$core$icons$comment_icon.TYPE)?a.setCommentText(null):a.setCommentText("")},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.BLOCK,id:"blockComment",weight:2})};
registerInline$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(a){return a.block.getInputsInline()?$.Msg$$module$build$src$core$msg.EXTERNAL_INPUTS:$.Msg$$module$build$src$core$msg.INLINE_INPUTS},preconditionFn(a){a=a.block;if(!a.isInFlyout&&a.isMovable()&&!a.isCollapsed())for(let b=1;b<a.inputList.length;b++)if(!(a.inputList[b-1]instanceof StatementInput$$module$build$src$core$renderers$zelos$measurables$inputs||
a.inputList[b]instanceof StatementInput$$module$build$src$core$renderers$zelos$measurables$inputs))return"enabled";return"hidden"},callback(a){a.block.setInputsInline(!a.block.getInputsInline())},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.BLOCK,id:"blockInline",weight:3})};
registerCollapseExpandBlock$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(a){return a.block.isCollapsed()?$.Msg$$module$build$src$core$msg.EXPAND_BLOCK:$.Msg$$module$build$src$core$msg.COLLAPSE_BLOCK},preconditionFn(a){a=a.block;return!a.isInFlyout&&a.isMovable()&&a.workspace.options.collapse?"enabled":"hidden"},callback(a){a.block.setCollapsed(!a.block.isCollapsed())},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.BLOCK,
id:"blockCollapseExpand",weight:4})};
registerDisable$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(a){return a.block.hasDisabledReason(MANUALLY_DISABLED$$module$build$src$core$constants)?$.Msg$$module$build$src$core$msg.ENABLE_BLOCK:$.Msg$$module$build$src$core$msg.DISABLE_BLOCK},preconditionFn(a){a=a.block;if(!a.isInFlyout&&a.workspace.options.disable&&a.isEditable()){var b=a.getDisabledReasons();b=b.size>(b.has(MANUALLY_DISABLED$$module$build$src$core$constants)?
1:0);return a.getInheritedDisabled()||b?"disabled":"enabled"}return"hidden"},callback(a){a=a.block;const b=$.getGroup$$module$build$src$core$events$utils();b||$.setGroup$$module$build$src$core$events$utils(!0);a.setDisabledReason(!a.hasDisabledReason(MANUALLY_DISABLED$$module$build$src$core$constants),MANUALLY_DISABLED$$module$build$src$core$constants);$.setGroup$$module$build$src$core$events$utils(b)},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.BLOCK,id:"blockDisable",
weight:5})};
registerDelete$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(a){var b=a.block;a=b.getDescendants(!1).length;(b=b.getNextBlock())&&(a-=b.getDescendants(!1).length);return a===1?$.Msg$$module$build$src$core$msg.DELETE_BLOCK:$.Msg$$module$build$src$core$msg.DELETE_X_BLOCKS.replace("%1",`${a}`)},preconditionFn(a){return!a.block.isInFlyout&&a.block.isDeletable()?"enabled":"hidden"},callback(a){a.block&&a.block.checkAndDelete()},
scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.BLOCK,id:"blockDelete",weight:6})};
registerHelp$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText(){return $.Msg$$module$build$src$core$msg.HELP},preconditionFn(a){a=a.block;return(typeof a.helpUrl==="function"?a.helpUrl():a.helpUrl)?"enabled":"hidden"},callback(a){a.block.showHelp()},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.BLOCK,id:"blockHelp",weight:7})};
registerCommentDelete$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText:()=>$.Msg$$module$build$src$core$msg.REMOVE_COMMENT,preconditionFn(a){let b;return((b=a.comment)==null?0:b.isDeletable())?"enabled":"hidden"},callback(a){$.setGroup$$module$build$src$core$events$utils(!0);let b;(b=a.comment)==null||b.dispose();$.setGroup$$module$build$src$core$events$utils(!1)},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.COMMENT,
id:"commentDelete",weight:6})};
registerCommentDuplicate$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText:()=>$.Msg$$module$build$src$core$msg.DUPLICATE_COMMENT,preconditionFn(a){let b;return((b=a.comment)==null?0:b.isMovable())?"enabled":"hidden"},callback(a){if(a.comment){var b=a.comment.toCopyData();b&&paste$$module$build$src$core$clipboard(b,a.comment.workspace)}},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.COMMENT,id:"commentDuplicate",
weight:1})};
registerCommentCreate$$module$build$src$core$contextmenu_items=function(){ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.register({displayText:()=>$.Msg$$module$build$src$core$msg.ADD_COMMENT,preconditionFn:a=>{let b;return((b=a.workspace)==null?0:b.isMutator)?"hidden":"enabled"},callback:(a,b,c,d)=>{if(a=a.workspace)$.setGroup$$module$build$src$core$events$utils(!0),b=new RenderedWorkspaceComment$$module$build$src$core$comments$rendered_workspace_comment(a),b.setPlaceholderText($.Msg$$module$build$src$core$msg.WORKSPACE_COMMENT_DEFAULT_TEXT),
b.moveTo(screenToWsCoordinates$$module$build$src$core$utils$svg_math(a,new Coordinate$$module$build$src$core$utils$coordinate(d.x,d.y))),$.getFocusManager$$module$build$src$core$focus_manager().focusNode(b),$.setGroup$$module$build$src$core$events$utils(!1)},scopeType:ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType.WORKSPACE,id:"commentCreate",weight:8})};
registerBlockOptions_$$module$build$src$core$contextmenu_items=function(){registerDuplicate$$module$build$src$core$contextmenu_items();registerComment$$module$build$src$core$contextmenu_items();registerInline$$module$build$src$core$contextmenu_items();registerCollapseExpandBlock$$module$build$src$core$contextmenu_items();registerDisable$$module$build$src$core$contextmenu_items();registerDelete$$module$build$src$core$contextmenu_items();registerHelp$$module$build$src$core$contextmenu_items()};
registerCommentOptions$$module$build$src$core$contextmenu_items=function(){registerCommentDuplicate$$module$build$src$core$contextmenu_items();registerCommentDelete$$module$build$src$core$contextmenu_items();registerCommentCreate$$module$build$src$core$contextmenu_items()};registerDefaultOptions$$module$build$src$core$contextmenu_items=function(){registerWorkspaceOptions_$$module$build$src$core$contextmenu_items();registerBlockOptions_$$module$build$src$core$contextmenu_items()};
isPaster$$module$build$src$core$interfaces$i_paster=function(a){return a&&typeof a.paste==="function"};isRenderedElement$$module$build$src$core$interfaces$i_rendered_element=function(a){return a&&typeof a.getSvgRoot==="function"};isSelectableToolboxItem$$module$build$src$core$interfaces$i_selectable_toolbox_item=function(a){return a.isSelectable()};hideChaff$$module$build$src$core$blockly=function(a){getMainWorkspace$$module$build$src$core$common().hideChaff(a)};
isFocusableTree$$module$build$src$core$interfaces$i_focusable_tree=function(a){return a&&typeof a.getRootFocusableNode==="function"&&typeof a.getRestoredFocusableNode==="function"&&typeof a.getNestedTrees==="function"&&typeof a.lookUpFocusableNode==="function"&&typeof a.onTreeFocus==="function"&&typeof a.onTreeBlur==="function"};$jscomp=$jscomp||{};$jscomp.scope={};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_ES6=!1;$jscomp.ASSUME_ES2020=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;
$jscomp.ISOLATE_POLYFILLS=!1;$jscomp.FORCE_POLYFILL_PROMISE=!1;$jscomp.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1;$jscomp.INSTRUMENT_ASYNC_CONTEXT=!0;$jscomp.objectCreate=$jscomp.ASSUME_ES5||typeof Object.create=="function"?Object.create:function(a){var b=function(){};b.prototype=a;return new b};$jscomp.defineProperty=$jscomp.ASSUME_ES5||typeof Object.defineProperties=="function"?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a};
$jscomp.getGlobal=function(a){a=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var b=0;b<a.length;++b){var c=a[b];if(c&&c.Math==Math)return c}throw Error("Cannot find global object");};$jscomp.global=$jscomp.ASSUME_ES2020?globalThis:$jscomp.getGlobal(this);$jscomp.IS_SYMBOL_NATIVE=typeof Symbol==="function"&&typeof Symbol("x")==="symbol";$jscomp.TRUST_ES6_POLYFILLS=!$jscomp.ISOLATE_POLYFILLS||$jscomp.IS_SYMBOL_NATIVE;
$jscomp.polyfills={};$jscomp.propertyToPolyfillSymbol={};$jscomp.POLYFILL_PREFIX="$jscp$";var $jscomp$lookupPolyfilledValue=function(a,b,c){if(!c||a!=null){c=$jscomp.propertyToPolyfillSymbol[b];if(c==null)return a[b];c=a[c];return c!==void 0?c:a[b]}};$jscomp.polyfill=function(a,b,c,d){b&&($jscomp.ISOLATE_POLYFILLS?$jscomp.polyfillIsolated(a,b,c,d):$jscomp.polyfillUnisolated(a,b,c,d))};
$jscomp.polyfillUnisolated=function(a,b,c,d){c=$jscomp.global;a=a.split(".");for(d=0;d<a.length-1;d++){var e=a[d];if(!(e in c))return;c=c[e]}a=a[a.length-1];d=c[a];b=b(d);b!=d&&b!=null&&$jscomp.defineProperty(c,a,{configurable:!0,writable:!0,value:b})};
$jscomp.polyfillIsolated=function(a,b,c,d){var e=a.split(".");a=e.length===1;d=e[0];d=!a&&d in $jscomp.polyfills?$jscomp.polyfills:$jscomp.global;for(var f=0;f<e.length-1;f++){var g=e[f];if(!(g in d))return;d=d[g]}e=e[e.length-1];c=$jscomp.IS_SYMBOL_NATIVE&&c==="es6"?d[e]:null;b=b(c);b!=null&&(a?$jscomp.defineProperty($jscomp.polyfills,e,{configurable:!0,writable:!0,value:b}):b!==c&&($jscomp.propertyToPolyfillSymbol[e]===void 0&&(c=Math.random()*1E9>>>0,$jscomp.propertyToPolyfillSymbol[e]=$jscomp.IS_SYMBOL_NATIVE?
$jscomp.global.Symbol(e):$jscomp.POLYFILL_PREFIX+c+"$"+e),$jscomp.defineProperty(d,$jscomp.propertyToPolyfillSymbol[e],{configurable:!0,writable:!0,value:b})))};
$jscomp.getConstructImplementation=function(){function a(){function c(){}new c;Reflect.construct(c,[],function(){});return new c instanceof c}if($jscomp.TRUST_ES6_POLYFILLS&&typeof Reflect!="undefined"&&Reflect.construct){if(a())return Reflect.construct;var b=Reflect.construct;return function(c,d,e){c=b(c,d);e&&Reflect.setPrototypeOf(c,e.prototype);return c}}return function(c,d,e){e===void 0&&(e=c);e=$jscomp.objectCreate(e.prototype||Object.prototype);return Function.prototype.apply.call(c,e,d)||
e}};$jscomp.construct={valueOf:$jscomp.getConstructImplementation}.valueOf();$jscomp.underscoreProtoCanBeSet=function(){var a={a:!0},b={};try{return b.__proto__=a,b.a}catch(c){}return!1};$jscomp.setPrototypeOf=$jscomp.ASSUME_ES6||$jscomp.TRUST_ES6_POLYFILLS&&typeof Object.setPrototypeOf=="function"?Object.setPrototypeOf:$jscomp.underscoreProtoCanBeSet()?function(a,b){a.__proto__=b;if(a.__proto__!==b)throw new TypeError(a+" is not extensible");return a}:null;
$jscomp.inherits=function(a,b){a.prototype=$jscomp.objectCreate(b.prototype);a.prototype.constructor=a;if($jscomp.ASSUME_ES6||$jscomp.setPrototypeOf){var c=$jscomp.setPrototypeOf;c(a,b)}else for(c in b)if(c!="prototype")if(Object.defineProperties){var d=Object.getOwnPropertyDescriptor(b,c);d&&Object.defineProperty(a,c,d)}else a[c]=b[c];a.superClass_=b.prototype};$jscomp.arrayIteratorImpl=function(a){var b=0;return function(){return b<a.length?{done:!1,value:a[b++]}:{done:!0}}};
$jscomp.arrayIterator=function(a){return{next:$jscomp.arrayIteratorImpl(a)}};$jscomp.makeIterator=function(a){var b=typeof Symbol!="undefined"&&Symbol.iterator&&a[Symbol.iterator];if(b)return b.call(a);if(typeof a.length=="number")return $jscomp.arrayIterator(a);throw Error(String(a)+" is not an iterable or ArrayLike");};$jscomp.arrayFromIterator=function(a){for(var b,c=[];!(b=a.next()).done;)c.push(b.value);return c};$jscomp.arrayFromIterable=function(a){return a instanceof Array?a:$jscomp.arrayFromIterator($jscomp.makeIterator(a))};
$jscomp.generator={};$jscomp.generator.ensureIteratorResultIsObject_=function(a){if(!(a instanceof Object))throw new TypeError("Iterator result "+a+" is not an object");};$jscomp.generator.Context=function(){this.isRunning_=!1;this.yieldAllIterator_=null;this.yieldResult=void 0;this.nextAddress=1;this.finallyAddress_=this.catchAddress_=0;this.finallyContexts_=this.abruptCompletion_=null};
$jscomp.generator.Context.prototype.start_=function(){if(this.isRunning_)throw new TypeError("Generator is already running");this.isRunning_=!0};$jscomp.generator.Context.prototype.stop_=function(){this.isRunning_=!1};$jscomp.generator.Context.prototype.jumpToErrorHandler_=function(){this.nextAddress=this.catchAddress_||this.finallyAddress_};$jscomp.generator.Context.prototype.next_=function(a){this.yieldResult=a};
$jscomp.generator.Context.prototype.throw_=function(a){this.abruptCompletion_={exception:a,isException:!0};this.jumpToErrorHandler_()};$jscomp.generator.Context.prototype.return=function(a){this.abruptCompletion_={return:a};this.nextAddress=this.finallyAddress_};$jscomp.generator.Context.prototype.jumpThroughFinallyBlocks=function(a){this.abruptCompletion_={jumpTo:a};this.nextAddress=this.finallyAddress_};$jscomp.generator.Context.prototype.yield=function(a,b){this.nextAddress=b;return{value:a}};
$jscomp.generator.Context.prototype.yieldAll=function(a,b){a=$jscomp.makeIterator(a);var c=a.next();$jscomp.generator.ensureIteratorResultIsObject_(c);if(c.done)this.yieldResult=c.value,this.nextAddress=b;else return this.yieldAllIterator_=a,this.yield(c.value,b)};$jscomp.generator.Context.prototype.jumpTo=function(a){this.nextAddress=a};$jscomp.generator.Context.prototype.jumpToEnd=function(){this.nextAddress=0};
$jscomp.generator.Context.prototype.setCatchFinallyBlocks=function(a,b){this.catchAddress_=a;b!=void 0&&(this.finallyAddress_=b)};$jscomp.generator.Context.prototype.setFinallyBlock=function(a){this.catchAddress_=0;this.finallyAddress_=a||0};$jscomp.generator.Context.prototype.leaveTryBlock=function(a,b){this.nextAddress=a;this.catchAddress_=b||0};
$jscomp.generator.Context.prototype.enterCatchBlock=function(a){this.catchAddress_=a||0;a=this.abruptCompletion_.exception;this.abruptCompletion_=null;return a};$jscomp.generator.Context.prototype.enterFinallyBlock=function(a,b,c){c?this.finallyContexts_[c]=this.abruptCompletion_:this.finallyContexts_=[this.abruptCompletion_];this.catchAddress_=a||0;this.finallyAddress_=b||0};
$jscomp.generator.Context.prototype.leaveFinallyBlock=function(a,b){b=this.finallyContexts_.splice(b||0)[0];if(b=this.abruptCompletion_=this.abruptCompletion_||b){if(b.isException)return this.jumpToErrorHandler_();b.jumpTo!=void 0&&this.finallyAddress_<b.jumpTo?(this.nextAddress=b.jumpTo,this.abruptCompletion_=null):this.nextAddress=this.finallyAddress_}else this.nextAddress=a};$jscomp.generator.Context.prototype.forIn=function(a){return new $jscomp.generator.Context.PropertyIterator(a)};
$jscomp.generator.Context.PropertyIterator=function(a){this.object_=a;this.properties_=[];for(var b in a)this.properties_.push(b);this.properties_.reverse()};$jscomp.generator.Context.PropertyIterator.prototype.getNext=function(){for(;this.properties_.length>0;){var a=this.properties_.pop();if(a in this.object_)return a}return null};$jscomp.generator.Engine_=function(a){this.context_=new $jscomp.generator.Context;this.program_=a};
$jscomp.generator.Engine_.prototype.next_=function(a){this.context_.start_();if(this.context_.yieldAllIterator_)return this.yieldAllStep_(this.context_.yieldAllIterator_.next,a,this.context_.next_);this.context_.next_(a);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.return_=function(a){this.context_.start_();var b=this.context_.yieldAllIterator_;if(b)return this.yieldAllStep_("return"in b?b["return"]:function(c){return{value:c,done:!0}},a,this.context_.return);this.context_.return(a);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.throw_=function(a){this.context_.start_();if(this.context_.yieldAllIterator_)return this.yieldAllStep_(this.context_.yieldAllIterator_["throw"],a,this.context_.next_);this.context_.throw_(a);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.yieldAllStep_=function(a,b,c){try{var d=a.call(this.context_.yieldAllIterator_,b);$jscomp.generator.ensureIteratorResultIsObject_(d);if(!d.done)return this.context_.stop_(),d;var e=d.value}catch(f){return this.context_.yieldAllIterator_=null,this.context_.throw_(f),this.nextStep_()}this.context_.yieldAllIterator_=null;c.call(this.context_,e);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.nextStep_=function(){for(;this.context_.nextAddress;)try{var a=this.program_(this.context_);if(a)return this.context_.stop_(),{value:a.value,done:!1}}catch(b){this.context_.yieldResult=void 0,this.context_.throw_(b)}this.context_.stop_();if(this.context_.abruptCompletion_){a=this.context_.abruptCompletion_;this.context_.abruptCompletion_=null;if(a.isException)throw a.exception;return{value:a.return,done:!0}}return{value:void 0,done:!0}};
$jscomp.generator.Generator_=function(a){this.next=function(b){return a.next_(b)};this.throw=function(b){return a.throw_(b)};this.return=function(b){return a.return_(b)};this[Symbol.iterator]=function(){return this}};$jscomp.generator.createGenerator=function(a,b){b=new $jscomp.generator.Generator_(new $jscomp.generator.Engine_(b));$jscomp.setPrototypeOf&&a.prototype&&$jscomp.setPrototypeOf(b,a.prototype);return b};
$jscomp.asyncExecutePromiseGenerator=function(a){function b(d){return a.next(d)}function c(d){return a.throw(d)}return new Promise(function(d,e){function f(g){g.done?d(g.value):Promise.resolve(g.value).then(b,c).then(f,e)}f(a.next())})};$jscomp.asyncExecutePromiseGeneratorFunction=function(a){return $jscomp.asyncExecutePromiseGenerator(a())};$jscomp.asyncExecutePromiseGeneratorProgram=function(a){return $jscomp.asyncExecutePromiseGenerator(new $jscomp.generator.Generator_(new $jscomp.generator.Engine_(a)))};
$jscomp.polyfill("globalThis",function(a){return a||$jscomp.global},"es_2020","es3");$jscomp.polyfill("Array.prototype.includes",function(a){return a?a:function(b,c){var d=this;d instanceof String&&(d=String(d));var e=d.length;c=c||0;for(c<0&&(c=Math.max(c+e,0));c<e;c++){var f=d[c];if(f===b||Object.is(f,b))return!0}return!1}},"es7","es3");
$jscomp.checkEs6ConformanceViaProxy=function(){try{var a={},b=Object.create(new $jscomp.global.Proxy(a,{get:function(c,d,e){return c==a&&d=="q"&&e==b}}));return b.q===!0}catch(c){return!1}};$jscomp.USE_PROXY_FOR_ES6_CONFORMANCE_CHECKS=!1;$jscomp.ES6_CONFORMANCE=$jscomp.USE_PROXY_FOR_ES6_CONFORMANCE_CHECKS&&$jscomp.checkEs6ConformanceViaProxy();$jscomp.initSymbol=function(){};$jscomp.iteratorPrototype=function(a){a={next:a};a[Symbol.iterator]=function(){return this};return a};
$jscomp.owns=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)};$jscomp.MapEntry=function(){};$jscomp.polyfill("Set.prototype.difference",function(a){return a?a:function(b){$jscomp.checkIsSetInstance(this);$jscomp.checkIsSetLike(b);var c=$jscomp.getSmallerAndLargerSets(this,b);b=new Set(this);var d=c.smallerSetIterator;c=c.largerSet;for(var e=d.next();!e.done;)c.has(e.value)&&b.delete(e.value),e=d.next();return b}},"es_next","es6");
$jscomp.checkIsSetLike=function(a){if(typeof a!=="object"||a===null||typeof a.size!=="number"||a.size<0||typeof a.keys!=="function"||typeof a.has!=="function")throw new TypeError("Argument must be set-like");};$jscomp.checkIsValidIterator=function(a){if(typeof a!=="object"||a===null||typeof a.next!=="function")throw new TypeError("Invalid iterator.");return a};
$jscomp.getSmallerAndLargerSets=function(a,b){return a.size<=b.size?{smallerSetIterator:a.keys(),largerSet:b}:{smallerSetIterator:$jscomp.checkIsValidIterator(b.keys()),largerSet:a}};$jscomp.checkIsSetInstance=function(a){if(!(a instanceof Set))throw new TypeError("Method must be called on an instance of Set.");};
$jscomp.iteratorFromArray=function(a,b){if($jscomp.ASSUME_ES6)return a[Symbol.iterator]();a instanceof String&&(a+="");var c=0,d=!1,e={next:function(){if(!d&&c<a.length){var f=c++;return{value:b(f,a[f]),done:!1}}d=!0;return{done:!0,value:void 0}}};e[Symbol.iterator]=function(){return e};return e};$jscomp.polyfill("Array.prototype.values",function(a){return a?a:function(){return $jscomp.iteratorFromArray(this,function(b,c){return c})}},"es8","es3");
$jscomp.polyfill("Array.prototype.flatMap",function(a){return a?a:function(b,c){var d=[];Array.prototype.forEach.call(this,function(e,f){e=b.call(c,e,f,this);Array.isArray(e)?d.push.apply(d,e):d.push(e)});return d}},"es9","es5");$jscomp.polyfill("Array.prototype.flat",function(a){return a?a:function(b){b=b===void 0?1:b;var c=[];Array.prototype.forEach.call(this,function(d){Array.isArray(d)&&b>0?(d=Array.prototype.flat.call(d,b-1),c.push.apply(c,d)):c.push(d)});return c}},"es9","es5");
$jscomp.polyfill("Object.entries",function(a){return a?a:function(b){var c=[],d;for(d in b)$jscomp.owns(b,d)&&c.push([d,b[d]]);return c}},"es8","es3");$jscomp.polyfill("Object.values",function(a){return a?a:function(b){var c=[],d;for(d in b)$jscomp.owns(b,d)&&c.push(b[d]);return c}},"es8","es3");
var typeMap$$module$build$src$core$registry=Object.create(null),TEST_ONLY$$module$build$src$core$registry={typeMap:typeMap$$module$build$src$core$registry},nameMap$$module$build$src$core$registry=Object.create(null),DEFAULT$$module$build$src$core$registry="default",Type$$module$build$src$core$registry=class{constructor(a){this.name=a}toString(){return this.name}};Type$$module$build$src$core$registry.CONNECTION_CHECKER=new Type$$module$build$src$core$registry("connectionChecker");
Type$$module$build$src$core$registry.CONNECTION_PREVIEWER=new Type$$module$build$src$core$registry("connectionPreviewer");Type$$module$build$src$core$registry.CURSOR=new Type$$module$build$src$core$registry("cursor");Type$$module$build$src$core$registry.EVENT=new Type$$module$build$src$core$registry("event");Type$$module$build$src$core$registry.FIELD=new Type$$module$build$src$core$registry("field");Type$$module$build$src$core$registry.INPUT=new Type$$module$build$src$core$registry("input");
Type$$module$build$src$core$registry.RENDERER=new Type$$module$build$src$core$registry("renderer");Type$$module$build$src$core$registry.TOOLBOX=new Type$$module$build$src$core$registry("toolbox");Type$$module$build$src$core$registry.THEME=new Type$$module$build$src$core$registry("theme");Type$$module$build$src$core$registry.TOOLBOX_ITEM=new Type$$module$build$src$core$registry("toolboxItem");Type$$module$build$src$core$registry.FLYOUTS_VERTICAL_TOOLBOX=new Type$$module$build$src$core$registry("flyoutsVerticalToolbox");
Type$$module$build$src$core$registry.FLYOUTS_HORIZONTAL_TOOLBOX=new Type$$module$build$src$core$registry("flyoutsHorizontalToolbox");Type$$module$build$src$core$registry.FLYOUT_INFLATER=new Type$$module$build$src$core$registry("flyoutInflater");Type$$module$build$src$core$registry.METRICS_MANAGER=new Type$$module$build$src$core$registry("metricsManager");Type$$module$build$src$core$registry.BLOCK_DRAGGER=new Type$$module$build$src$core$registry("blockDragger");
Type$$module$build$src$core$registry.SERIALIZER=new Type$$module$build$src$core$registry("serializer");Type$$module$build$src$core$registry.ICON=new Type$$module$build$src$core$registry("icon");Type$$module$build$src$core$registry.PASTER=new Type$$module$build$src$core$registry("paster");Type$$module$build$src$core$registry.VARIABLE_MODEL=new Type$$module$build$src$core$registry("variableModel");Type$$module$build$src$core$registry.VARIABLE_MAP=new Type$$module$build$src$core$registry("variableMap");
var module$build$src$core$registry={DEFAULT:DEFAULT$$module$build$src$core$registry,TEST_ONLY:TEST_ONLY$$module$build$src$core$registry};module$build$src$core$registry.Type=Type$$module$build$src$core$registry;module$build$src$core$registry.getAllItems=getAllItems$$module$build$src$core$registry;module$build$src$core$registry.getClass=getClass$$module$build$src$core$registry;module$build$src$core$registry.getClassFromOptions=getClassFromOptions$$module$build$src$core$registry;
module$build$src$core$registry.getObject=getObject$$module$build$src$core$registry;module$build$src$core$registry.hasItem=hasItem$$module$build$src$core$registry;module$build$src$core$registry.register=register$$module$build$src$core$registry;module$build$src$core$registry.unregister=unregister$$module$build$src$core$registry;var Blocks$$module$build$src$core$blocks=Object.create(null),module$build$src$core$blocks={Blocks:Blocks$$module$build$src$core$blocks};var LONGPRESS$$module$build$src$core$touch=750,TOUCH_ENABLED$$module$build$src$core$touch="ontouchstart"in globalThis||!!(globalThis.document&&document.documentElement&&"ontouchstart"in document.documentElement)||!(!globalThis.navigator||!globalThis.navigator.maxTouchPoints&&!globalThis.navigator.msMaxTouchPoints),touchIdentifier_$$module$build$src$core$touch=null,TOUCH_MAP$$module$build$src$core$touch={mousedown:["pointerdown"],mouseenter:["pointerenter"],mouseleave:["pointerleave"],mousemove:["pointermove"],
mouseout:["pointerout"],mouseover:["pointerover"],mouseup:["pointerup","pointercancel"],touchend:["pointerup"],touchcancel:["pointercancel"]},longPid_$$module$build$src$core$touch=0,module$build$src$core$touch={TOUCH_ENABLED:TOUCH_ENABLED$$module$build$src$core$touch,TOUCH_MAP:TOUCH_MAP$$module$build$src$core$touch};module$build$src$core$touch.checkTouchIdentifier=checkTouchIdentifier$$module$build$src$core$touch;module$build$src$core$touch.clearTouchIdentifier=clearTouchIdentifier$$module$build$src$core$touch;
module$build$src$core$touch.getTouchIdentifierFromEvent=getTouchIdentifierFromEvent$$module$build$src$core$touch;module$build$src$core$touch.longStart=longStart$$module$build$src$core$touch;module$build$src$core$touch.longStop=longStop$$module$build$src$core$touch;module$build$src$core$touch.shouldHandleEvent=shouldHandleEvent$$module$build$src$core$touch;var rawUserAgent$$module$build$src$core$utils$useragent,isJavaFx$$module$build$src$core$utils$useragent,isWebKit$$module$build$src$core$utils$useragent,isGecko$$module$build$src$core$utils$useragent,isAndroid$$module$build$src$core$utils$useragent,isIPad$$module$build$src$core$utils$useragent,isIPhone$$module$build$src$core$utils$useragent,isMac$$module$build$src$core$utils$useragent,isTablet$$module$build$src$core$utils$useragent,isMobile$$module$build$src$core$utils$useragent;
(function(a){function b(d){return c.includes(d.toUpperCase())}rawUserAgent$$module$build$src$core$utils$useragent=a;const c=rawUserAgent$$module$build$src$core$utils$useragent.toUpperCase();isJavaFx$$module$build$src$core$utils$useragent=b("JavaFX");isWebKit$$module$build$src$core$utils$useragent=b("WebKit");isGecko$$module$build$src$core$utils$useragent=b("Gecko")&&!isWebKit$$module$build$src$core$utils$useragent;isAndroid$$module$build$src$core$utils$useragent=b("Android");a=globalThis.navigator&&
globalThis.navigator.maxTouchPoints;isIPad$$module$build$src$core$utils$useragent=b("iPad")||b("Macintosh")&&a>0;isIPhone$$module$build$src$core$utils$useragent=b("iPhone")&&!isIPad$$module$build$src$core$utils$useragent;isMac$$module$build$src$core$utils$useragent=b("Macintosh");isTablet$$module$build$src$core$utils$useragent=isIPad$$module$build$src$core$utils$useragent||isAndroid$$module$build$src$core$utils$useragent&&!b("Mobile")||b("Silk");isMobile$$module$build$src$core$utils$useragent=!isTablet$$module$build$src$core$utils$useragent&&
(isIPhone$$module$build$src$core$utils$useragent||isAndroid$$module$build$src$core$utils$useragent)})(globalThis.navigator&&globalThis.navigator.userAgent||"");
var raw$$module$build$src$core$utils$useragent=rawUserAgent$$module$build$src$core$utils$useragent,JavaFx$$module$build$src$core$utils$useragent=isJavaFx$$module$build$src$core$utils$useragent,GECKO$$module$build$src$core$utils$useragent=isGecko$$module$build$src$core$utils$useragent,ANDROID$$module$build$src$core$utils$useragent=isAndroid$$module$build$src$core$utils$useragent,IPAD$$module$build$src$core$utils$useragent=isIPad$$module$build$src$core$utils$useragent,IPHONE$$module$build$src$core$utils$useragent=
isIPhone$$module$build$src$core$utils$useragent,MAC$$module$build$src$core$utils$useragent=isMac$$module$build$src$core$utils$useragent,MOBILE$$module$build$src$core$utils$useragent=isMobile$$module$build$src$core$utils$useragent,module$build$src$core$utils$useragent={ANDROID:ANDROID$$module$build$src$core$utils$useragent,GECKO:GECKO$$module$build$src$core$utils$useragent,IPAD:IPAD$$module$build$src$core$utils$useragent,IPHONE:IPHONE$$module$build$src$core$utils$useragent,JavaFx:JavaFx$$module$build$src$core$utils$useragent,
MAC:MAC$$module$build$src$core$utils$useragent,MOBILE:MOBILE$$module$build$src$core$utils$useragent,raw:raw$$module$build$src$core$utils$useragent};var LINE_MODE_MULTIPLIER$$module$build$src$core$browser_events=40,PAGE_MODE_MULTIPLIER$$module$build$src$core$browser_events=125,module$build$src$core$browser_events={};module$build$src$core$browser_events.bind=bind$$module$build$src$core$browser_events;module$build$src$core$browser_events.conditionalBind=conditionalBind$$module$build$src$core$browser_events;module$build$src$core$browser_events.getScrollDeltaPixels=getScrollDeltaPixels$$module$build$src$core$browser_events;
module$build$src$core$browser_events.isRightButton=isRightButton$$module$build$src$core$browser_events;module$build$src$core$browser_events.isTargetInput=isTargetInput$$module$build$src$core$browser_events;module$build$src$core$browser_events.mouseToSvg=mouseToSvg$$module$build$src$core$browser_events;module$build$src$core$browser_events.unbind=unbind$$module$build$src$core$browser_events;var EventType$$module$build$src$core$events$type;
(function(a){a.BLOCK_CREATE="create";a.BLOCK_DELETE="delete";a.BLOCK_CHANGE="change";a.BLOCK_FIELD_INTERMEDIATE_CHANGE="block_field_intermediate_change";a.BLOCK_MOVE="move";a.VAR_CREATE="var_create";a.VAR_DELETE="var_delete";a.VAR_RENAME="var_rename";a.VAR_TYPE_CHANGE="var_type_change";a.UI="ui";a.BLOCK_DRAG="drag";a.SELECTED="selected";a.CLICK="click";a.MARKER_MOVE="marker_move";a.BUBBLE_OPEN="bubble_open";a.TRASHCAN_OPEN="trashcan_open";a.TOOLBOX_ITEM_SELECT="toolbox_item_select";a.THEME_CHANGE=
"theme_change";a.VIEWPORT_CHANGE="viewport_change";a.COMMENT_CREATE="comment_create";a.COMMENT_DELETE="comment_delete";a.COMMENT_CHANGE="comment_change";a.COMMENT_MOVE="comment_move";a.COMMENT_RESIZE="comment_resize";a.COMMENT_DRAG="comment_drag";a.COMMENT_COLLAPSE="comment_collapse";a.FINISHED_LOADING="finished_loading"})(EventType$$module$build$src$core$events$type||(EventType$$module$build$src$core$events$type={}));
var BUMP_EVENTS$$module$build$src$core$events$type=[EventType$$module$build$src$core$events$type.BLOCK_CREATE,EventType$$module$build$src$core$events$type.BLOCK_MOVE,EventType$$module$build$src$core$events$type.COMMENT_CREATE,EventType$$module$build$src$core$events$type.COMMENT_MOVE],module$build$src$core$events$type={BUMP_EVENTS:BUMP_EVENTS$$module$build$src$core$events$type};module$build$src$core$events$type.EventType=EventType$$module$build$src$core$events$type;var soup$$module$build$src$core$utils$idgenerator="!#$%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",internal$$module$build$src$core$utils$idgenerator={genUid:()=>{const a=soup$$module$build$src$core$utils$idgenerator.length,b=[];for(let c=0;c<20;c++)b[c]=soup$$module$build$src$core$utils$idgenerator.charAt(Math.random()*a);return b.join("")}},TEST_ONLY$$module$build$src$core$utils$idgenerator=internal$$module$build$src$core$utils$idgenerator,nextId$$module$build$src$core$utils$idgenerator=
0,module$build$src$core$utils$idgenerator={TEST_ONLY:internal$$module$build$src$core$utils$idgenerator};module$build$src$core$utils$idgenerator.genUid=genUid$$module$build$src$core$utils$idgenerator;module$build$src$core$utils$idgenerator.getNextUniqueId=getNextUniqueId$$module$build$src$core$utils$idgenerator;var module$build$src$core$events$predicates={};module$build$src$core$events$predicates.isBlockChange=isBlockChange$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isBlockCreate=isBlockCreate$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isBlockDelete=isBlockDelete$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isBlockDrag=isBlockDrag$$module$build$src$core$events$predicates;
module$build$src$core$events$predicates.isBlockFieldIntermediateChange=isBlockFieldIntermediateChange$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isBlockMove=isBlockMove$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isBubbleOpen=isBubbleOpen$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isClick=isClick$$module$build$src$core$events$predicates;
module$build$src$core$events$predicates.isCommentChange=isCommentChange$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isCommentCollapse=isCommentCollapse$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isCommentCreate=isCommentCreate$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isCommentDelete=isCommentDelete$$module$build$src$core$events$predicates;
module$build$src$core$events$predicates.isCommentDrag=isCommentDrag$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isCommentMove=isCommentMove$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isCommentResize=isCommentResize$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isFinishedLoading=isFinishedLoading$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isSelected=isSelected$$module$build$src$core$events$predicates;
module$build$src$core$events$predicates.isThemeChange=isThemeChange$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isToolboxItemSelect=isToolboxItemSelect$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isTrashcanOpen=isTrashcanOpen$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isVarCreate=isVarCreate$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isVarDelete=isVarDelete$$module$build$src$core$events$predicates;
module$build$src$core$events$predicates.isVarRename=isVarRename$$module$build$src$core$events$predicates;module$build$src$core$events$predicates.isViewportChange=isViewportChange$$module$build$src$core$events$predicates;var group$$module$build$src$core$events$utils="",recordUndo$$module$build$src$core$events$utils=!0,disabled$$module$build$src$core$events$utils=0,ORPHANED_BLOCK_DISABLED_REASON$$module$build$src$core$events$utils="ORPHANED_BLOCK",FIRE_QUEUE$$module$build$src$core$events$utils=[],TEST_ONLY$$module$build$src$core$events$utils={FIRE_QUEUE:FIRE_QUEUE$$module$build$src$core$events$utils,enqueueEvent:enqueueEvent$$module$build$src$core$events$utils,fireNow:fireNow$$module$build$src$core$events$utils,fireInternal:fireInternal$$module$build$src$core$events$utils,
setGroupInternal:setGroupInternal$$module$build$src$core$events$utils},module$build$src$core$events$utils={TEST_ONLY:TEST_ONLY$$module$build$src$core$events$utils};module$build$src$core$events$utils.clearPendingUndo=clearPendingUndo$$module$build$src$core$events$utils;module$build$src$core$events$utils.disable=$.disable$$module$build$src$core$events$utils;module$build$src$core$events$utils.disableOrphans=disableOrphans$$module$build$src$core$events$utils;
module$build$src$core$events$utils.enable=$.enable$$module$build$src$core$events$utils;module$build$src$core$events$utils.filter=filter$$module$build$src$core$events$utils;module$build$src$core$events$utils.fire=fire$$module$build$src$core$events$utils;module$build$src$core$events$utils.fromJson=fromJson$$module$build$src$core$events$utils;module$build$src$core$events$utils.get=get$$module$build$src$core$events$utils;module$build$src$core$events$utils.getDescendantIds=getDescendantIds$$module$build$src$core$events$utils;
module$build$src$core$events$utils.getGroup=$.getGroup$$module$build$src$core$events$utils;module$build$src$core$events$utils.getRecordUndo=getRecordUndo$$module$build$src$core$events$utils;module$build$src$core$events$utils.isEnabled=isEnabled$$module$build$src$core$events$utils;module$build$src$core$events$utils.setGroup=$.setGroup$$module$build$src$core$events$utils;module$build$src$core$events$utils.setRecordUndo=$.setRecordUndo$$module$build$src$core$events$utils;var SVG_NS$$module$build$src$core$utils$dom="http://www.w3.org/2000/svg",HTML_NS$$module$build$src$core$utils$dom="http://www.w3.org/1999/xhtml",XLINK_NS$$module$build$src$core$utils$dom="http://www.w3.org/1999/xlink",NodeType$$module$build$src$core$utils$dom;(function(a){a[a.ELEMENT_NODE=1]="ELEMENT_NODE";a[a.TEXT_NODE=3]="TEXT_NODE";a[a.COMMENT_NODE=8]="COMMENT_NODE"})(NodeType$$module$build$src$core$utils$dom||(NodeType$$module$build$src$core$utils$dom={}));
var cacheWidths$$module$build$src$core$utils$dom=null,cacheReference$$module$build$src$core$utils$dom=0,canvasContext$$module$build$src$core$utils$dom=null,module$build$src$core$utils$dom={HTML_NS:HTML_NS$$module$build$src$core$utils$dom};module$build$src$core$utils$dom.NodeType=NodeType$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.SVG_NS=SVG_NS$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.XLINK_NS=XLINK_NS$$module$build$src$core$utils$dom;
module$build$src$core$utils$dom.addClass=addClass$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.createSvgElement=createSvgElement$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.getFastTextWidth=getFastTextWidth$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.getFastTextWidthWithSizeString=getFastTextWidthWithSizeString$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.getTextWidth=getTextWidth$$module$build$src$core$utils$dom;
module$build$src$core$utils$dom.hasClass=hasClass$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.insertAfter=insertAfter$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.measureFontMetrics=measureFontMetrics$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.removeClass=removeClass$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.removeClasses=removeClasses$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.removeNode=removeNode$$module$build$src$core$utils$dom;
module$build$src$core$utils$dom.setCssTransform=setCssTransform$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.startTextWidthCache=startTextWidthCache$$module$build$src$core$utils$dom;module$build$src$core$utils$dom.stopTextWidthCache=stopTextWidthCache$$module$build$src$core$utils$dom;var FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser=class{static findFocusedNode(a){var b=a.getRootFocusableNode();if(!b.canBeFocused())return null;var c=b.getFocusableElement();if(hasClass$$module$build$src$core$utils$dom(c,FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.ACTIVE_CLASS_NAME)||hasClass$$module$build$src$core$utils$dom(c,FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.PASSIVE_CSS_CLASS_NAME))return b;
b=c.querySelector(this.ACTIVE_FOCUS_NODE_CSS_SELECTOR);if(b instanceof HTMLElement||b instanceof SVGElement)if(b=FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.findFocusableNodeFor(b,a))return b;c=c.querySelector(this.PASSIVE_FOCUS_NODE_CSS_SELECTOR);if(c instanceof HTMLElement||c instanceof SVGElement)if(a=FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.findFocusableNodeFor(c,a))return a;return null}static findFocusableNodeFor(a,b){if(!a.id||
a.id==="null"||b.getNestedTrees().map(e=>FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.findFocusableNodeFor(a,e)).findIndex(e=>!!e)!==-1)return null;var c=b.getRootFocusableNode();if(c.canBeFocused()&&a===c.getFocusableElement())return c;var d;if(c=(d=b.lookUpFocusableNode(a.id))!=null?d:null)return c;d=a.parentElement;return!c&&d?FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.findFocusableNodeFor(d,b):null}};
FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.ACTIVE_CLASS_NAME="blocklyActiveFocus";FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.PASSIVE_CSS_CLASS_NAME="blocklyPassiveFocus";FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.ACTIVE_FOCUS_NODE_CSS_SELECTOR=`.${FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.ACTIVE_CLASS_NAME}`;
FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.PASSIVE_FOCUS_NODE_CSS_SELECTOR=`.${FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.PASSIVE_CSS_CLASS_NAME}`;var module$build$src$core$utils$focusable_tree_traverser={};module$build$src$core$utils$focusable_tree_traverser.FocusableTreeTraverser=FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser;var TreeRegistration$$module$build$src$core$focus_manager=class{constructor(a,b){this.tree=a;this.rootShouldBeAutoTabbable=b}},FocusManager$$module$build$src$core$focus_manager=class{constructor(a){this.previouslyFocusedNode=this.focusedNode=null;this.registeredTrees=[];this.isUpdatingFocusedNode=this.recentlyLostAllFocus=this.lockFocusStateChanges=this.currentlyHoldsEphemeralFocus=!1;const b=c=>{if(!this.isUpdatingFocusedNode){this.recentlyLostAllFocus=!c;var d=null;if(c instanceof HTMLElement||
c instanceof SVGElement)for(var e of this.registeredTrees)if(d=FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.findFocusableNodeFor(c,e.tree))break;if(d&&d.canBeFocused()){c=d.getFocusableTree();let f;e=(f=this.focusedNode)==null?void 0:f.getFocusableTree();d===c.getRootFocusableNode()&&c!==e?this.focusTree(c):this.focusNode(d)}else this.defocusCurrentFocusedNode()}};a("focusin",c=>{c instanceof FocusEvent&&b(document.activeElement)});a("focusout",c=>{c instanceof FocusEvent&&
b(c.relatedTarget)})}registerTree(a,b=!1){this.ensureManagerIsUnlocked();if(this.isRegistered(a))throw Error(`Attempted to re-register already registered tree: ${a}.`);this.registeredTrees.push(new TreeRegistration$$module$build$src$core$focus_manager(a,b));const c=a.getRootFocusableNode().getFocusableElement();if(!c.id||c.id==="null")throw Error("Attempting to register a tree with a root element that has an "+`invalid ID: ${a}.`);b&&(c.tabIndex=0)}isRegistered(a){return!!this.lookUpRegistration(a)}lookUpRegistration(a){let b;
return(b=this.registeredTrees.find(c=>c.tree===a))!=null?b:null}unregisterTree(a){this.ensureManagerIsUnlocked();if(!this.isRegistered(a))throw Error(`Attempted to unregister not registered tree: ${a}.`);var b=this.registeredTrees.findIndex(e=>e.tree===a);const c=this.registeredTrees[b];this.registeredTrees.splice(b,1);b=FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.findFocusedNode(a);const d=a.getRootFocusableNode();b&&this.removeHighlight(b);this.focusedNode!==b&&
this.focusedNode!==d||this.updateFocusedNode(null);this.removeHighlight(d);c.rootShouldBeAutoTabbable&&a.getRootFocusableNode().getFocusableElement().removeAttribute("tabindex")}getFocusedTree(){let a,b;return(b=(a=this.focusedNode)==null?void 0:a.getFocusableTree())!=null?b:null}getFocusedNode(){return this.focusedNode}focusTree(a){this.ensureManagerIsUnlocked();if(!this.isRegistered(a))throw Error(`Attempted to focus unregistered tree: ${a}.`);const b=FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.findFocusedNode(a),
c=a.getRestoredFocusableNode(b);a=a.getRootFocusableNode();let d;this.focusNode((d=c!=null?c:b)!=null?d:a)}focusNode(a){this.ensureManagerIsUnlocked();const b=!this.currentlyHoldsEphemeralFocus;b&&(this.isUpdatingFocusedNode=!0);var c,d=((c=this.focusedNode)==null?void 0:c.getFocusableElement())!==document.activeElement;if(this.focusedNode!==a||d)if(a.canBeFocused()){c=a.getFocusableTree();if(!this.isRegistered(c))throw Error(`Attempted to focus unregistered node: ${a}.`);d=a.getFocusableElement();
d.id&&d.id!=="null"||console.warn("Trying to focus a node that has an invalid ID.");var e=FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.findFocusableNodeFor(d,c);d=FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser.findFocusedNode(c);var f=a;if(e!==a){f=c.getRestoredFocusableNode(d);a=c.getRootFocusableNode();var g;f=(g=f!=null?f:d)!=null?g:a}a=this.focusedNode;g=a==null?void 0:a.getFocusableTree();a&&this.passivelyFocusNode(a,c);c=c.getRootFocusableNode();
d&&this.removeHighlight(d);c!==f&&this.removeHighlight(c);this.currentlyHoldsEphemeralFocus||this.activelyFocusNode(f,g!=null?g:null);this.updateFocusedNode(f)}else console.warn("Trying to focus a node that can't be focused.");b&&(this.isUpdatingFocusedNode=!1)}takeEphemeralFocus(a){this.ensureManagerIsUnlocked();if(this.currentlyHoldsEphemeralFocus)throw Error("Attempted to take ephemeral focus when it's already held, "+`with new element: ${a}.`);this.currentlyHoldsEphemeralFocus=!0;this.focusedNode&&
this.passivelyFocusNode(this.focusedNode,null);a.focus({preventScroll:!0});let b=!1;return()=>{if(b)throw Error("Attempted to finish ephemeral focus twice for element: "+`${a}.`);b=!0;this.currentlyHoldsEphemeralFocus=!1;if(this.focusedNode){this.activelyFocusNode(this.focusedNode,null);const c=this.focusedNode;setTimeout(()=>{!this.focusedNode&&this.previouslyFocusedNode===c&&this.recentlyLostAllFocus&&this.focusNode(c)},0)}}}ephemeralFocusTaken(){return this.currentlyHoldsEphemeralFocus}ensureManagerIsUnlocked(){if(this.lockFocusStateChanges)throw Error("FocusManager state changes cannot happen in a tree/node focus/blur callback.");
}updateFocusedNode(a){this.previouslyFocusedNode=this.focusedNode;this.focusedNode=a}defocusCurrentFocusedNode(){this.focusedNode&&!this.currentlyHoldsEphemeralFocus&&(this.passivelyFocusNode(this.focusedNode,null),this.updateFocusedNode(null))}activelyFocusNode(a,b){this.lockFocusStateChanges=!0;const c=a.getFocusableTree(),d=a.getFocusableElement();let e;const f=(e=this.lookUpRegistration(c))==null?void 0:e.rootShouldBeAutoTabbable;c!==b&&(c.onTreeFocus(a,b),f&&(c.getRootFocusableNode().getFocusableElement().tabIndex=
-1));a.onNodeFocus();this.lockFocusStateChanges=!1;f&&a===c.getRootFocusableNode()||d.hasAttribute("tabindex")||(d.tabIndex=-1);this.setNodeToVisualActiveFocus(a);d.focus({preventScroll:!0})}passivelyFocusNode(a,b){this.lockFocusStateChanges=!0;const c=a.getFocusableTree();if(c!==b){c.onTreeBlur(b);let d;if((d=this.lookUpRegistration(c))==null?0:d.rootShouldBeAutoTabbable)c.getRootFocusableNode().getFocusableElement().tabIndex=0}a.onNodeBlur();this.lockFocusStateChanges=!1;c!==b&&this.setNodeToVisualPassiveFocus(a)}setNodeToVisualActiveFocus(a){a=
a.getFocusableElement();addClass$$module$build$src$core$utils$dom(a,FocusManager$$module$build$src$core$focus_manager.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME);removeClass$$module$build$src$core$utils$dom(a,FocusManager$$module$build$src$core$focus_manager.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME)}setNodeToVisualPassiveFocus(a){a=a.getFocusableElement();removeClass$$module$build$src$core$utils$dom(a,FocusManager$$module$build$src$core$focus_manager.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME);addClass$$module$build$src$core$utils$dom(a,
FocusManager$$module$build$src$core$focus_manager.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME)}removeHighlight(a){a=a.getFocusableElement();removeClass$$module$build$src$core$utils$dom(a,FocusManager$$module$build$src$core$focus_manager.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME);removeClass$$module$build$src$core$utils$dom(a,FocusManager$$module$build$src$core$focus_manager.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME)}static getFocusManager(){FocusManager$$module$build$src$core$focus_manager.focusManager||(FocusManager$$module$build$src$core$focus_manager.focusManager=
new FocusManager$$module$build$src$core$focus_manager(document.addEventListener));return FocusManager$$module$build$src$core$focus_manager.focusManager}};FocusManager$$module$build$src$core$focus_manager.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME="blocklyActiveFocus";FocusManager$$module$build$src$core$focus_manager.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME="blocklyPassiveFocus";FocusManager$$module$build$src$core$focus_manager.focusManager=null;var module$build$src$core$focus_manager={};
module$build$src$core$focus_manager.FocusManager=FocusManager$$module$build$src$core$focus_manager;module$build$src$core$focus_manager.getFocusManager=$.getFocusManager$$module$build$src$core$focus_manager;var module$build$src$core$interfaces$i_focusable_node={};module$build$src$core$interfaces$i_focusable_node.isFocusableNode=isFocusableNode$$module$build$src$core$interfaces$i_focusable_node;var module$build$src$core$interfaces$i_selectable={};module$build$src$core$interfaces$i_selectable.isSelectable=isSelectable$$module$build$src$core$interfaces$i_selectable;var module$build$src$core$utils$object={};module$build$src$core$utils$object.deepMerge=deepMerge$$module$build$src$core$utils$object;var ShortcutRegistry$$module$build$src$core$shortcut_registry=class{constructor(){this.shortcuts=new Map;this.keyMap=new Map;this.reset()}reset(){this.shortcuts.clear();this.keyMap.clear()}register(a,b){if(this.shortcuts.get(a.name)&&!b)throw Error(`Shortcut named "${a.name}" already exists.`);this.shortcuts.set(a.name,a);b=a.keyCodes;if(b==null?0:b.length)for(const c of b)this.addKeyMapping(c,a.name,!!a.allowCollision)}unregister(a){if(!this.shortcuts.get(a))return console.warn(`Keyboard shortcut named "${a}" not found.`),
!1;this.removeAllKeyMappings(a);this.shortcuts.delete(a);return!0}addKeyMapping(a,b,c){a=`${a}`;const d=this.keyMap.get(a);if(d&&!c)throw Error(`Shortcut named "${b}" collides with shortcuts "${d}"`);d&&c?d.unshift(b):this.keyMap.set(a,[b])}removeKeyMapping(a,b,c){const d=this.keyMap.get(a);if(!d)return c||console.warn(`No keyboard shortcut named "${b}" registered with key code "${a}"`),!1;const e=d.indexOf(b);if(e>-1)return d.splice(e,1),d.length===0&&this.keyMap.delete(a),!0;c||console.warn(`No keyboard shortcut named "${b}" registered with key code "${a}"`);
return!1}removeAllKeyMappings(a){for(const b of this.keyMap.keys())this.removeKeyMapping(b,a,!0)}setKeyMap(a){this.keyMap.clear();for(const b in a)this.keyMap.set(b,a[b])}getKeyMap(){const a=Object.create(null);for(const [b,c]of this.keyMap)a[b]=c;return a}getRegistry(){const a=Object.create(null);for(const [b,c]of this.shortcuts)a[b]=c;return deepMerge$$module$build$src$core$utils$object(Object.create(null),a)}onKeyDown(a,b){var c=this.serializeKeyEvent(b);c=this.getShortcutNamesByKeyCode(c);if(!c)return!1;
for(const d of c){c=this.shortcuts.get(d);let e;if(!c||c.preconditionFn&&!c.preconditionFn(a,{focusedNode:(e=$.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode())!=null?e:void 0}))continue;let f,g,h;if((g=(f=c).callback)==null?0:g.call(f,a,b,c,{focusedNode:(h=$.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode())!=null?h:void 0}))return!0}return!1}getShortcutNamesByKeyCode(a){let b;return((b=this.keyMap.get(a))==null?void 0:b.slice())||[]}getKeyCodesByShortcutName(a){const b=
[];for(const [c,d]of this.keyMap)d.indexOf(a)>-1&&b.push(c);return b}serializeKeyEvent(a){let b="";for(const c in ShortcutRegistry$$module$build$src$core$shortcut_registry.modifierKeys)a.getModifierState(c)&&(b!==""&&(b+="+"),b+=c);b!==""&&a.keyCode?b+="+"+a.keyCode:a.keyCode&&(b=String(a.keyCode));return b}checkModifiers(a){for(const b of a)if(!(b in ShortcutRegistry$$module$build$src$core$shortcut_registry.modifierKeys))throw Error(b+" is not a valid modifier key.");}createSerializedKey(a,b){let c=
"";if(b){this.checkModifiers(b);for(const d in ShortcutRegistry$$module$build$src$core$shortcut_registry.modifierKeys)b.includes(ShortcutRegistry$$module$build$src$core$shortcut_registry.modifierKeys[d])&&(c!==""&&(c+="+"),c+=d)}c!==""&&a?c+="+"+a:a&&(c=`${a}`);return c}};ShortcutRegistry$$module$build$src$core$shortcut_registry.registry=new ShortcutRegistry$$module$build$src$core$shortcut_registry;
(function(a){a=a.modifierKeys||(a.modifierKeys={});a[a.Shift=16]="Shift";a[a.Control=17]="Control";a[a.Alt=18]="Alt";a[a.Meta=91]="Meta"})(ShortcutRegistry$$module$build$src$core$shortcut_registry||(ShortcutRegistry$$module$build$src$core$shortcut_registry={}));var module$build$src$core$shortcut_registry={};module$build$src$core$shortcut_registry.ShortcutRegistry=ShortcutRegistry$$module$build$src$core$shortcut_registry;var WorkspaceDB_$$module$build$src$core$common=Object.create(null),mainWorkspace$$module$build$src$core$common,parentContainer$$module$build$src$core$common,draggingConnections$$module$build$src$core$common=[],TEST_ONLY$$module$build$src$core$common={defineBlocksWithJsonArrayInternal:defineBlocksWithJsonArrayInternal$$module$build$src$core$common},module$build$src$core$common={TEST_ONLY:TEST_ONLY$$module$build$src$core$common};module$build$src$core$common.createBlockDefinitionsFromJsonArray=$.createBlockDefinitionsFromJsonArray$$module$build$src$core$common;
module$build$src$core$common.defineBlocks=$.defineBlocks$$module$build$src$core$common;module$build$src$core$common.defineBlocksWithJsonArray=defineBlocksWithJsonArray$$module$build$src$core$common;module$build$src$core$common.draggingConnections=draggingConnections$$module$build$src$core$common;module$build$src$core$common.fireSelectedEvent=fireSelectedEvent$$module$build$src$core$common;module$build$src$core$common.getAllWorkspaces=getAllWorkspaces$$module$build$src$core$common;
module$build$src$core$common.getBlockTypeCounts=getBlockTypeCounts$$module$build$src$core$common;module$build$src$core$common.getMainWorkspace=getMainWorkspace$$module$build$src$core$common;module$build$src$core$common.getParentContainer=getParentContainer$$module$build$src$core$common;module$build$src$core$common.getSelected=getSelected$$module$build$src$core$common;module$build$src$core$common.getWorkspaceById=getWorkspaceById$$module$build$src$core$common;
module$build$src$core$common.globalShortcutHandler=globalShortcutHandler$$module$build$src$core$common;module$build$src$core$common.registerWorkspace=registerWorkspace$$module$build$src$core$common;module$build$src$core$common.setMainWorkspace=setMainWorkspace$$module$build$src$core$common;module$build$src$core$common.setParentContainer=setParentContainer$$module$build$src$core$common;module$build$src$core$common.setSelected=setSelected$$module$build$src$core$common;
module$build$src$core$common.svgResize=svgResize$$module$build$src$core$common;module$build$src$core$common.unregisterWorkpace=unregisterWorkpace$$module$build$src$core$common;var Abstract$$module$build$src$core$events$events_abstract=class{constructor(){this.workspaceId=void 0;this.isUiEvent=!1;this.type="";this.group=$.getGroup$$module$build$src$core$events$utils();this.recordUndo=getRecordUndo$$module$build$src$core$events$utils()}toJson(){return{type:this.type,group:this.group}}static fromJson(a,b,c){c.isBlank=!1;c.group=a.group||"";c.workspaceId=b.id;return c}isNull(){return!1}run(a){}getEventWorkspace_(){let a;this.workspaceId&&(a=getWorkspaceById$$module$build$src$core$common(this.workspaceId));
if(!a)throw Error("Workspace is null. Event must have been generated from real Blockly events.");return a}},module$build$src$core$events$events_abstract={};module$build$src$core$events$events_abstract.Abstract=Abstract$$module$build$src$core$events$events_abstract;var UiBase$$module$build$src$core$events$events_ui_base=class extends Abstract$$module$build$src$core$events$events_abstract{constructor(a){super();this.recordUndo=!1;this.isUiEvent=!0;this.isBlank=typeof a==="undefined";this.workspaceId=a?a:""}},module$build$src$core$events$events_ui_base={};module$build$src$core$events$events_ui_base.UiBase=UiBase$$module$build$src$core$events$events_ui_base;var Click$$module$build$src$core$events$events_click=class extends UiBase$$module$build$src$core$events$events_ui_base{constructor(a,b,c){b=a?a.workspace.id:b;b===null&&(b=void 0);super(b);this.type=EventType$$module$build$src$core$events$type.CLICK;this.blockId=a?a.id:void 0;this.targetType=c}toJson(){const a=super.toJson();if(!this.targetType)throw Error("The click target type is undefined. Either pass a block to the constructor, or call fromJson");a.targetType=this.targetType;a.blockId=this.blockId;
return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new Click$$module$build$src$core$events$events_click);b.targetType=a.targetType;b.blockId=a.blockId;return b}},ClickTarget$$module$build$src$core$events$events_click;(function(a){a.BLOCK="block";a.WORKSPACE="workspace";a.ZOOM_CONTROLS="zoom_controls"})(ClickTarget$$module$build$src$core$events$events_click||(ClickTarget$$module$build$src$core$events$events_click={}));
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.CLICK,Click$$module$build$src$core$events$events_click);var module$build$src$core$events$events_click={};module$build$src$core$events$events_click.Click=Click$$module$build$src$core$events$events_click;module$build$src$core$events$events_click.ClickTarget=ClickTarget$$module$build$src$core$events$events_click;var module$build$src$core$utils$array={};module$build$src$core$utils$array.removeElem=removeElem$$module$build$src$core$utils$array;var Capability$$module$build$src$core$component_manager=class{constructor(a){this.name=a}toString(){return this.name}};Capability$$module$build$src$core$component_manager.POSITIONABLE=new Capability$$module$build$src$core$component_manager("positionable");Capability$$module$build$src$core$component_manager.DRAG_TARGET=new Capability$$module$build$src$core$component_manager("drag_target");Capability$$module$build$src$core$component_manager.DELETE_AREA=new Capability$$module$build$src$core$component_manager("delete_area");
Capability$$module$build$src$core$component_manager.AUTOHIDEABLE=new Capability$$module$build$src$core$component_manager("autohideable");
var ComponentManager$$module$build$src$core$component_manager=class{constructor(){this.componentData=new Map;this.capabilityToComponentIds=new Map}addComponent(a,b){const c=a.component.id;if(!b&&this.componentData.has(c)){var d;throw Error('Plugin "'+c+'" with capabilities "'+((d=this.componentData.get(c))==null?void 0:d.capabilities)+'" already added.');}this.componentData.set(c,a);b=[];for(d=0;d<a.capabilities.length;d++){const e=String(a.capabilities[d]).toLowerCase();b.push(e);if(this.capabilityToComponentIds.has(e)){let f;
(f=this.capabilityToComponentIds.get(e))==null||f.push(c)}else this.capabilityToComponentIds.set(e,[c])}this.componentData.get(c).capabilities=b}removeComponent(a){const b=this.componentData.get(a);if(b){for(let c=0;c<b.capabilities.length;c++){const d=String(b.capabilities[c]).toLowerCase();removeElem$$module$build$src$core$utils$array(this.capabilityToComponentIds.get(d),a)}this.componentData.delete(a)}}addCapability(a,b){if(!this.getComponent(a))throw Error('Cannot add capability, "'+b+'". Plugin "'+
a+'" has not been added to the ComponentManager');if(this.hasCapability(a,b))console.warn('Plugin "'+a+'already has capability "'+b+'"');else{b=`${b}`.toLowerCase();var c;(c=this.componentData.get(a))==null||c.capabilities.push(b);var d;(d=this.capabilityToComponentIds.get(b))==null||d.push(a)}}removeCapability(a,b){if(!this.getComponent(a))throw Error('Cannot remove capability, "'+b+'". Plugin "'+a+'" has not been added to the ComponentManager');this.hasCapability(a,b)?(b=`${b}`.toLowerCase(),removeElem$$module$build$src$core$utils$array(this.componentData.get(a).capabilities,
b),removeElem$$module$build$src$core$utils$array(this.capabilityToComponentIds.get(b),a)):console.warn('Plugin "'+a+"doesn't have capability \""+b+'" to remove')}hasCapability(a,b){b=`${b}`.toLowerCase();return this.componentData.has(a)&&this.componentData.get(a).capabilities.includes(b)}getComponent(a){let b;return(b=this.componentData.get(a))==null?void 0:b.component}getComponents(a,b){a=`${a}`.toLowerCase();a=this.capabilityToComponentIds.get(a);if(!a)return[];const c=[];if(b){const d=[];a.forEach(e=>
{d.push(this.componentData.get(e))});d.sort(function(e,f){return e.weight-f.weight});d.forEach(function(e){c.push(e.component)})}else a.forEach(d=>{c.push(this.componentData.get(d).component)});return c}};ComponentManager$$module$build$src$core$component_manager.Capability=Capability$$module$build$src$core$component_manager;
(function(a){a=a.ComponentWeight||(a.ComponentWeight={});a[a.TOOLBOX_WEIGHT=0]="TOOLBOX_WEIGHT";a[a.FLYOUT_WEIGHT=1]="FLYOUT_WEIGHT";a[a.TRASHCAN_WEIGHT=2]="TRASHCAN_WEIGHT";a[a.ZOOM_CONTROLS_WEIGHT=3]="ZOOM_CONTROLS_WEIGHT"})(ComponentManager$$module$build$src$core$component_manager||(ComponentManager$$module$build$src$core$component_manager={}));
var ComponentWeight$$module$build$src$core$component_manager=ComponentManager$$module$build$src$core$component_manager.ComponentWeight,module$build$src$core$component_manager={};module$build$src$core$component_manager.ComponentManager=ComponentManager$$module$build$src$core$component_manager;module$build$src$core$component_manager.ComponentWeight=ComponentWeight$$module$build$src$core$component_manager;var injected$$module$build$src$core$css=!1,content$$module$build$src$core$css='\n.blocklySvg {\n  background-color: #fff;\n  outline: none;\n  overflow: hidden;  /* IE overflows by default. */\n  position: absolute;\n  display: block;\n}\n\n.blocklyWidgetDiv {\n  display: none;\n  position: absolute;\n  z-index: 99999;  /* big value for bootstrap3 compatibility */\n}\n\n.injectionDiv {\n  height: 100%;\n  position: relative;\n  overflow: hidden;  /* So blocks in drag surface disappear at edges */\n  touch-action: none;\n  user-select: none;\n  -webkit-user-select: none;\n}\n\n.blocklyBlockCanvas.blocklyCanvasTransitioning,\n.blocklyBubbleCanvas.blocklyCanvasTransitioning {\n  transition: transform .5s;\n}\n\n.blocklyEmboss {\n  filter: var(--blocklyEmbossFilter);\n}\n\n.blocklyTooltipDiv {\n  background-color: #ffffc7;\n  border: 1px solid #ddc;\n  box-shadow: 4px 4px 20px 1px rgba(0,0,0,.15);\n  color: #000;\n  display: none;\n  font: 9pt sans-serif;\n  opacity: .9;\n  padding: 2px;\n  position: absolute;\n  z-index: 100000;  /* big value for bootstrap3 compatibility */\n}\n\n.blocklyDropDownDiv {\n  position: absolute;\n  left: 0;\n  top: 0;\n  z-index: 1000;\n  display: none;\n  border: 1px solid;\n  border-color: #dadce0;\n  background-color: #fff;\n  border-radius: 2px;\n  padding: 4px;\n  box-shadow: 0 0 3px 1px rgba(0,0,0,.3);\n}\n\n.blocklyDropDownDiv:focus {\n  box-shadow: 0 0 6px 1px rgba(0,0,0,.3);\n}\n\n.blocklyDropDownContent {\n  max-height: 300px;  /* @todo: spec for maximum height. */\n}\n\n.blocklyDropDownArrow {\n  position: absolute;\n  left: 0;\n  top: 0;\n  width: 16px;\n  height: 16px;\n  z-index: -1;\n  background-color: inherit;\n  border-color: inherit;\n  border-top: 1px solid;\n  border-left: 1px solid;\n  border-top-left-radius: 4px;\n  border-color: inherit;\n}\n\n.blocklyHighlighted>.blocklyPath {\n  filter: var(--blocklyEmbossFilter);\n}\n\n.blocklyHighlightedConnectionPath {\n  fill: none;\n  stroke: #fc3;\n  stroke-width: 4px;\n}\n\n.blocklyPathLight {\n  fill: none;\n  stroke-linecap: round;\n  stroke-width: 1;\n}\n\n.blocklySelected>.blocklyPathLight {\n  display: none;\n}\n\n.blocklyDraggable {\n  cursor: grab;\n  cursor: -webkit-grab;\n}\n\n.blocklyDragging {\n  cursor: grabbing;\n  cursor: -webkit-grabbing;\n  /* Drag surface disables events to not block the toolbox, so we have to\n   * reenable them here for the cursor values to work. */\n  pointer-events: auto;\n}\n\n  /* Changes cursor on mouse down. Not effective in Firefox because of\n     https://bugzilla.mozilla.org/show_bug.cgi?id=771241 */\n.blocklyDraggable:active {\n  cursor: grabbing;\n  cursor: -webkit-grabbing;\n}\n\n.blocklyDragging.blocklyDraggingDelete,\n.blocklyDragging.blocklyDraggingDelete .blocklyField {\n  cursor: url("<<<PATH>>>/handdelete.cur"), auto;\n}\n\n.blocklyDragging>.blocklyPath,\n.blocklyDragging>.blocklyPathLight {\n  fill-opacity: .8;\n  stroke-opacity: .8;\n}\n\n.blocklyDragging>.blocklyPathDark {\n  display: none;\n}\n\n.blocklyDisabledPattern>.blocklyPath {\n  fill: var(--blocklyDisabledPattern);\n  fill-opacity: .5;\n  stroke-opacity: .5;\n}\n\n.blocklyDisabled>.blocklyPathLight,\n.blocklyDisabled>.blocklyPathDark {\n  display: none;\n}\n\n.blocklyInsertionMarker>.blocklyPath,\n.blocklyInsertionMarker>.blocklyPathLight,\n.blocklyInsertionMarker>.blocklyPathDark {\n  fill-opacity: .2;\n  stroke: none;\n}\n\n.blocklyNonEditableField>text {\n  pointer-events: none;\n}\n\n.blocklyFlyout {\n  position: absolute;\n  z-index: 20;\n}\n\n.blocklyText text {\n  cursor: default;\n}\n\n/*\n  Don\'t allow users to select text.  It gets annoying when trying to\n  drag a block and selected text moves instead.\n*/\n.blocklySvg text {\n  user-select: none;\n  -ms-user-select: none;\n  -webkit-user-select: none;\n  cursor: inherit;\n}\n\n.blocklyIconGroup {\n  cursor: default;\n}\n\n.blocklyIconGroup:not(:hover):not(:focus),\n.blocklyIconGroupReadonly {\n  opacity: .6;\n}\n\n.blocklyIconShape {\n  fill: #00f;\n  stroke: #fff;\n  stroke-width: 1px;\n}\n\n.blocklyIconSymbol {\n  fill: #fff;\n}\n\n.blocklyMinimalBody {\n  margin: 0;\n  padding: 0;\n  height: 100%;\n}\n\n.blocklyHtmlInput {\n  border: none;\n  border-radius: 4px;\n  height: 100%;\n  margin: 0;\n  outline: none;\n  padding: 0;\n  width: 100%;\n  text-align: center;\n  display: block;\n  box-sizing: border-box;\n}\n\n/* Remove the increase and decrease arrows on the field number editor */\ninput.blocklyHtmlInput[type=number]::-webkit-inner-spin-button,\ninput.blocklyHtmlInput[type=number]::-webkit-outer-spin-button {\n  -webkit-appearance: none;\n  margin: 0;\n}\n\ninput[type=number] {\n  -moz-appearance: textfield;\n}\n\n.blocklyMainBackground {\n  stroke-width: 1;\n  stroke: #c6c6c6;  /* Equates to #ddd due to border being off-pixel. */\n}\n\n.blocklyMutatorBackground {\n  fill: #fff;\n  stroke: #ddd;\n  stroke-width: 1;\n}\n\n.blocklyFlyoutBackground {\n  fill: #ddd;\n  fill-opacity: .8;\n}\n\n.blocklyMainWorkspaceScrollbar {\n  z-index: 20;\n}\n\n.blocklyFlyoutScrollbar {\n  z-index: 30;\n}\n\n.blocklyScrollbarHorizontal,\n.blocklyScrollbarVertical {\n  position: absolute;\n  outline: none;\n}\n\n.blocklyScrollbarBackground {\n  opacity: 0;\n  pointer-events: none;\n}\n\n.blocklyScrollbarHandle {\n  fill: #ccc;\n}\n\n.blocklyScrollbarBackground:hover+.blocklyScrollbarHandle,\n.blocklyScrollbarHandle:hover {\n  fill: #bbb;\n}\n\n/* Darken flyout scrollbars due to being on a grey background. */\n/* By contrast, workspace scrollbars are on a white background. */\n.blocklyFlyout .blocklyScrollbarHandle {\n  fill: #bbb;\n}\n\n.blocklyFlyout .blocklyScrollbarBackground:hover+.blocklyScrollbarHandle,\n.blocklyFlyout .blocklyScrollbarHandle:hover {\n  fill: #aaa;\n}\n\n.blocklyInvalidInput {\n  background: #faa;\n}\n\n.blocklyVerticalMarker {\n  stroke-width: 3px;\n  fill: rgba(255,255,255,.5);\n  pointer-events: none;\n}\n\n.blocklyComputeCanvas {\n  position: absolute;\n  width: 0;\n  height: 0;\n}\n\n.blocklyNoPointerEvents {\n  pointer-events: none;\n}\n\n.blocklyContextMenu {\n  border-radius: 4px;\n  max-height: 100%;\n}\n\n.blocklyDropdownMenu {\n  border-radius: 2px;\n  padding: 0 !important;\n}\n\n.blocklyDropdownMenu .blocklyMenuItem {\n  /* 28px on the left for icon or checkbox. */\n  padding-left: 28px;\n}\n\n/* BiDi override for the resting state. */\n.blocklyDropdownMenu .blocklyMenuItemRtl {\n  /* Flip left/right padding for BiDi. */\n  padding-left: 5px;\n  padding-right: 28px;\n}\n\n.blocklyWidgetDiv .blocklyMenu {\n  user-select: none;\n  -ms-user-select: none;\n  -webkit-user-select: none;\n  background: #fff;\n  border: 1px solid transparent;\n  box-shadow: 0 0 3px 1px rgba(0,0,0,.3);\n  font: normal 13px Arial, sans-serif;\n  margin: 0;\n  outline: none;\n  padding: 4px 0;\n  position: absolute;\n  overflow-y: auto;\n  overflow-x: hidden;\n  max-height: 100%;\n  z-index: 20000;  /* Arbitrary, but some apps depend on it... */\n}\n\n.blocklyWidgetDiv .blocklyMenu:focus {\n  box-shadow: 0 0 6px 1px rgba(0,0,0,.3);\n}\n\n.blocklyDropDownDiv .blocklyMenu {\n  user-select: none;\n  -ms-user-select: none;\n  -webkit-user-select: none;\n  background: inherit;  /* Compatibility with gapi, reset from goog-menu */\n  border: inherit;  /* Compatibility with gapi, reset from goog-menu */\n  font: normal 13px "Helvetica Neue", Helvetica, sans-serif;\n  outline: none;\n  overflow-y: auto;\n  overflow-x: hidden;\n  max-height: 100%;\n  z-index: 20000;  /* Arbitrary, but some apps depend on it... */\n}\n\n/* State: resting. */\n.blocklyMenuItem {\n  border: none;\n  color: #000;\n  cursor: pointer;\n  list-style: none;\n  margin: 0;\n  /* 7em on the right for shortcut. */\n  min-width: 7em;\n  padding: 6px 15px;\n  white-space: nowrap;\n}\n\n/* State: disabled. */\n.blocklyMenuItemDisabled {\n  color: #ccc;\n  cursor: inherit;\n}\n\n/* State: hover. */\n.blocklyMenuItemHighlight {\n  background-color: rgba(0,0,0,.1);\n}\n\n/* State: selected/checked. */\n.blocklyMenuItemCheckbox {\n  height: 16px;\n  position: absolute;\n  width: 16px;\n}\n\n.blocklyMenuItemSelected .blocklyMenuItemCheckbox {\n  background: url(<<<PATH>>>/sprites.png) no-repeat -48px -16px;\n  float: left;\n  margin-left: -24px;\n  position: static;  /* Scroll with the menu. */\n}\n\n.blocklyMenuItemRtl .blocklyMenuItemCheckbox {\n  float: right;\n  margin-right: -24px;\n}\n\n.blocklyMenuSeparator {\n  background-color: #ccc;\n  height: 1px;\n  border: 0;\n  margin-left: 4px;\n  margin-right: 4px;\n}\n\n.blocklyBlockDragSurface, .blocklyAnimationLayer {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  overflow: visible !important;\n  z-index: 80;\n  pointer-events: none;\n}\n\n.blocklyField {\n  cursor: default;\n}\n\n.blocklyInputField {\n  cursor: text;\n}\n\n.blocklyDragging .blocklyField,\n.blocklyDragging .blocklyIconGroup {\n  cursor: grabbing;\n}\n\n.blocklyActiveFocus:is(\n  .blocklyFlyout,\n  .blocklyWorkspace,\n  .blocklyField,\n  .blocklyPath,\n  .blocklyHighlightedConnectionPath,\n  .blocklyComment,\n  .blocklyBubble,\n  .blocklyIconGroup,\n  .blocklyTextarea\n) {\n  outline: none;\n}\n',
module$build$src$core$css={};module$build$src$core$css.inject=inject$$module$build$src$core$css;module$build$src$core$css.register=register$$module$build$src$core$css;var Coordinate$$module$build$src$core$utils$coordinate=class{constructor(a,b){this.x=a;this.y=b}clone(){return new Coordinate$$module$build$src$core$utils$coordinate(this.x,this.y)}scale(a){this.x*=a;this.y*=a;return this}translate(a,b){this.x+=a;this.y+=b;return this}static equals(a,b){return a===b?!0:a&&b?a.x===b.x&&a.y===b.y:!1}static distance(a,b){const c=a.x-b.x;a=a.y-b.y;return Math.sqrt(c*c+a*a)}static magnitude(a){return Math.sqrt(a.x*a.x+a.y*a.y)}static difference(a,b){return new Coordinate$$module$build$src$core$utils$coordinate(a.x-
b.x,a.y-b.y)}static sum(a,b){return new Coordinate$$module$build$src$core$utils$coordinate(a.x+b.x,a.y+b.y)}},module$build$src$core$utils$coordinate={};module$build$src$core$utils$coordinate.Coordinate=Coordinate$$module$build$src$core$utils$coordinate;var Svg$$module$build$src$core$utils$svg=class{constructor(a){this.tagName=a}toString(){return this.tagName}};Svg$$module$build$src$core$utils$svg.ANIMATE=new Svg$$module$build$src$core$utils$svg("animate");Svg$$module$build$src$core$utils$svg.CIRCLE=new Svg$$module$build$src$core$utils$svg("circle");Svg$$module$build$src$core$utils$svg.CLIPPATH=new Svg$$module$build$src$core$utils$svg("clipPath");Svg$$module$build$src$core$utils$svg.DEFS=new Svg$$module$build$src$core$utils$svg("defs");
Svg$$module$build$src$core$utils$svg.FECOMPOSITE=new Svg$$module$build$src$core$utils$svg("feComposite");Svg$$module$build$src$core$utils$svg.FECOMPONENTTRANSFER=new Svg$$module$build$src$core$utils$svg("feComponentTransfer");Svg$$module$build$src$core$utils$svg.FEFLOOD=new Svg$$module$build$src$core$utils$svg("feFlood");Svg$$module$build$src$core$utils$svg.FEFUNCA=new Svg$$module$build$src$core$utils$svg("feFuncA");Svg$$module$build$src$core$utils$svg.FEGAUSSIANBLUR=new Svg$$module$build$src$core$utils$svg("feGaussianBlur");
Svg$$module$build$src$core$utils$svg.FEPOINTLIGHT=new Svg$$module$build$src$core$utils$svg("fePointLight");Svg$$module$build$src$core$utils$svg.FESPECULARLIGHTING=new Svg$$module$build$src$core$utils$svg("feSpecularLighting");Svg$$module$build$src$core$utils$svg.FILTER=new Svg$$module$build$src$core$utils$svg("filter");Svg$$module$build$src$core$utils$svg.FOREIGNOBJECT=new Svg$$module$build$src$core$utils$svg("foreignObject");Svg$$module$build$src$core$utils$svg.G=new Svg$$module$build$src$core$utils$svg("g");
Svg$$module$build$src$core$utils$svg.IMAGE=new Svg$$module$build$src$core$utils$svg("image");Svg$$module$build$src$core$utils$svg.LINE=new Svg$$module$build$src$core$utils$svg("line");Svg$$module$build$src$core$utils$svg.PATH=new Svg$$module$build$src$core$utils$svg("path");Svg$$module$build$src$core$utils$svg.PATTERN=new Svg$$module$build$src$core$utils$svg("pattern");Svg$$module$build$src$core$utils$svg.POLYGON=new Svg$$module$build$src$core$utils$svg("polygon");
Svg$$module$build$src$core$utils$svg.RECT=new Svg$$module$build$src$core$utils$svg("rect");Svg$$module$build$src$core$utils$svg.SVG=new Svg$$module$build$src$core$utils$svg("svg");Svg$$module$build$src$core$utils$svg.TEXT=new Svg$$module$build$src$core$utils$svg("text");Svg$$module$build$src$core$utils$svg.TSPAN=new Svg$$module$build$src$core$utils$svg("tspan");var module$build$src$core$utils$svg={};module$build$src$core$utils$svg.Svg=Svg$$module$build$src$core$utils$svg;var Rect$$module$build$src$core$utils$rect=class{constructor(a,b,c,d){this.top=a;this.bottom=b;this.left=c;this.right=d}static from(a){return new Rect$$module$build$src$core$utils$rect(a.y,a.y+a.height,a.x,a.x+a.width)}clone(){return new Rect$$module$build$src$core$utils$rect(this.top,this.bottom,this.left,this.right)}getHeight(){return this.bottom-this.top}getWidth(){return this.right-this.left}getOrigin(){return new Coordinate$$module$build$src$core$utils$coordinate(this.left,this.top)}contains(a,
b){return a>=this.left&&a<=this.right&&b>=this.top&&b<=this.bottom}intersects(a){return this.left<=a.right&&this.right>=a.left&&this.bottom>=a.top&&this.top<=a.bottom}static equals(a,b){return a===b?!0:a&&b?a.top===b.top&&a.bottom===b.bottom&&a.left===b.left&&a.right===b.right:!1}static createFromPoint(a,b,c){const d=a.x;a=a.y;return new Rect$$module$build$src$core$utils$rect(a,a+c,d,d+b)}},module$build$src$core$utils$rect={};module$build$src$core$utils$rect.Rect=Rect$$module$build$src$core$utils$rect;var Size$$module$build$src$core$utils$size=class{constructor(a,b){this.width=a;this.height=b}static equals(a,b){return a===b?!0:a&&b?a.width===b.width&&a.height===b.height:!1}static max(a,b){return new Size$$module$build$src$core$utils$size(Math.max(a.width,b.width),Math.max(a.height,b.height))}static min(a,b){return new Size$$module$build$src$core$utils$size(Math.min(a.width,b.width),Math.min(a.height,b.height))}},module$build$src$core$utils$size={};module$build$src$core$utils$size.Size=Size$$module$build$src$core$utils$size;var TEST_ONLY$$module$build$src$core$utils$style={getSizeInternal:getSizeInternal$$module$build$src$core$utils$style},module$build$src$core$utils$style={TEST_ONLY:TEST_ONLY$$module$build$src$core$utils$style};module$build$src$core$utils$style.getBorderBox=getBorderBox$$module$build$src$core$utils$style;module$build$src$core$utils$style.getComputedStyle=getComputedStyle$$module$build$src$core$utils$style;module$build$src$core$utils$style.getContainerOffsetToScrollInto=getContainerOffsetToScrollInto$$module$build$src$core$utils$style;
module$build$src$core$utils$style.getPageOffset=getPageOffset$$module$build$src$core$utils$style;module$build$src$core$utils$style.getSize=getSize$$module$build$src$core$utils$style;module$build$src$core$utils$style.getViewportPageOffset=getViewportPageOffset$$module$build$src$core$utils$style;module$build$src$core$utils$style.scrollIntoContainerView=scrollIntoContainerView$$module$build$src$core$utils$style;var XY_REGEX$$module$build$src$core$utils$svg_math=/translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*)?/,XY_STYLE_REGEX$$module$build$src$core$utils$svg_math=/transform:\s*translate(?:3d)?\(\s*([-+\d.e]+)\s*px([ ,]\s*([-+\d.e]+)\s*px)?/,TEST_ONLY$$module$build$src$core$utils$svg_math={XY_REGEX:XY_REGEX$$module$build$src$core$utils$svg_math,XY_STYLE_REGEX:XY_STYLE_REGEX$$module$build$src$core$utils$svg_math},module$build$src$core$utils$svg_math={TEST_ONLY:TEST_ONLY$$module$build$src$core$utils$svg_math};
module$build$src$core$utils$svg_math.getDocumentScroll=getDocumentScroll$$module$build$src$core$utils$svg_math;module$build$src$core$utils$svg_math.getInjectionDivXY=getInjectionDivXY$$module$build$src$core$utils$svg_math;module$build$src$core$utils$svg_math.getRelativeXY=getRelativeXY$$module$build$src$core$utils$svg_math;module$build$src$core$utils$svg_math.getViewportBBox=getViewportBBox$$module$build$src$core$utils$svg_math;module$build$src$core$utils$svg_math.screenToWsCoordinates=screenToWsCoordinates$$module$build$src$core$utils$svg_math;
module$build$src$core$utils$svg_math.wsToScreenCoordinates=wsToScreenCoordinates$$module$build$src$core$utils$svg_math;var Scrollbar$$module$build$src$core$scrollbar=class{constructor(a,b,c,d,e){this.workspace=a;this.horizontal=b;this.oldHostMetrics=null;this.ratio=1;this.origin=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.startDragHandle=this.handlePosition=this.handleLength=this.scrollbarLength=this.startDragMouse=0;this.containerVisible=this.isHandleVisible=!0;this.position=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.onMouseMoveWrapper_=this.onMouseUpWrapper_=null;this.pair=
c||!1;this.margin=e!==void 0?e:Scrollbar$$module$build$src$core$scrollbar.DEFAULT_SCROLLBAR_MARGIN;a="blocklyScrollbar"+(this.horizontal?"Horizontal":"Vertical");d&&(a+=" "+d);this.outerSvg=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.SVG,{"class":a});d=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{},this.outerSvg);this.svgBackground=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,
{"class":"blocklyScrollbarBackground"},d);a=Math.floor((Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness-5)/2);this.svgHandle=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{"class":"blocklyScrollbarHandle",rx:a,ry:a},d);this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarColour","fill");this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarOpacity","fill-opacity");insertAfter$$module$build$src$core$utils$dom(this.outerSvg,
this.workspace.getParentSvg());this.setInitialThickness();b?(this.lengthAttribute_="width",this.positionAttribute_="x"):(this.lengthAttribute_="height",this.positionAttribute_="y");this.onMouseDownBarWrapper_=conditionalBind$$module$build$src$core$browser_events(this.svgBackground,"pointerdown",this,this.onMouseDownBar);this.onMouseDownHandleWrapper_=conditionalBind$$module$build$src$core$browser_events(this.svgHandle,"pointerdown",this,this.onMouseDownHandle)}setInitialThickness(){const a=Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness;
this.horizontal?(this.svgBackground.setAttribute("height",String(a)),this.outerSvg.setAttribute("height",String(a)),this.svgHandle.setAttribute("height",String(a-5)),this.svgHandle.setAttribute("y","2.5")):(this.svgBackground.setAttribute("width",String(a)),this.outerSvg.setAttribute("width",String(a)),this.svgHandle.setAttribute("width",String(a-5)),this.svgHandle.setAttribute("x","2.5"))}dispose(){this.cleanUp();unbind$$module$build$src$core$browser_events(this.onMouseDownBarWrapper_);unbind$$module$build$src$core$browser_events(this.onMouseDownHandleWrapper_);
removeNode$$module$build$src$core$utils$dom(this.outerSvg);this.workspace.getThemeManager().unsubscribe(this.svgHandle)}constrainHandleLength(a){return a=a<=0||isNaN(a)?0:Math.min(a,this.scrollbarLength)}setHandleLength(a){this.handleLength=a;this.svgHandle.setAttribute(this.lengthAttribute_,String(this.handleLength))}constrainHandlePosition(a){return a=a<=0||isNaN(a)?0:Math.min(a,this.scrollbarLength-this.handleLength)}setHandlePosition(a){this.handlePosition=a;this.svgHandle.setAttribute(this.positionAttribute_,
String(this.handlePosition))}setScrollbarLength(a){this.scrollbarLength=a;this.outerSvg.setAttribute(this.lengthAttribute_,String(this.scrollbarLength));this.svgBackground.setAttribute(this.lengthAttribute_,String(this.scrollbarLength))}setPosition(a,b){this.position.x=a;this.position.y=b;setCssTransform$$module$build$src$core$utils$dom(this.outerSvg,"translate("+(this.position.x+this.origin.x)+"px,"+(this.position.y+this.origin.y)+"px)")}resize(a){if(!a&&(a=this.workspace.getMetrics(),!a))return;
this.oldHostMetrics&&Scrollbar$$module$build$src$core$scrollbar.metricsAreEquivalent(a,this.oldHostMetrics)||(this.horizontal?this.resizeHorizontal(a):this.resizeVertical(a),this.oldHostMetrics=a,this.updateMetrics())}requiresViewResize(a){return this.oldHostMetrics?this.oldHostMetrics.viewWidth!==a.viewWidth||this.oldHostMetrics.viewHeight!==a.viewHeight||this.oldHostMetrics.absoluteLeft!==a.absoluteLeft||this.oldHostMetrics.absoluteTop!==a.absoluteTop:!0}resizeHorizontal(a){this.requiresViewResize(a)?
this.resizeViewHorizontal(a):this.resizeContentHorizontal(a)}resizeViewHorizontal(a){var b=a.viewWidth-this.margin*2;this.pair&&(b-=Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness);this.setScrollbarLength(Math.max(0,b));b=a.absoluteLeft+this.margin;this.pair&&this.workspace.RTL&&(b+=Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness);this.setPosition(b,a.absoluteTop+a.viewHeight-Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness-this.margin);this.resizeContentHorizontal(a)}resizeContentHorizontal(a){if(a.viewWidth>=
a.scrollWidth)this.setHandleLength(this.scrollbarLength),this.setHandlePosition(0),this.pair||this.setVisible(!1);else{this.pair||this.setVisible(!0);var b=this.scrollbarLength*a.viewWidth/a.scrollWidth;b=this.constrainHandleLength(b);this.setHandleLength(b);b=a.scrollWidth-a.viewWidth;var c=this.scrollbarLength-this.handleLength;a=(a.viewLeft-a.scrollLeft)/b*c;a=this.constrainHandlePosition(a);this.setHandlePosition(a);this.ratio=c/b}}resizeVertical(a){this.requiresViewResize(a)?this.resizeViewVertical(a):
this.resizeContentVertical(a)}resizeViewVertical(a){let b=a.viewHeight-this.margin*2;this.pair&&(b-=Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness);this.setScrollbarLength(Math.max(0,b));this.setPosition(this.workspace.RTL?a.absoluteLeft+this.margin:a.absoluteLeft+a.viewWidth-Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness-this.margin,a.absoluteTop+this.margin);this.resizeContentVertical(a)}resizeContentVertical(a){if(a.viewHeight>=a.scrollHeight)this.setHandleLength(this.scrollbarLength),
this.setHandlePosition(0),this.pair||this.setVisible(!1);else{this.pair||this.setVisible(!0);var b=this.scrollbarLength*a.viewHeight/a.scrollHeight;b=this.constrainHandleLength(b);this.setHandleLength(b);b=a.scrollHeight-a.viewHeight;var c=this.scrollbarLength-this.handleLength;a=(a.viewTop-a.scrollTop)/b*c;a=this.constrainHandlePosition(a);this.setHandlePosition(a);this.ratio=c/b}}isVisible(){return this.isHandleVisible}setContainerVisible(a){const b=a!==this.containerVisible;this.containerVisible=
a;b&&this.updateDisplay_()}setVisible(a){if(this.pair)throw Error("Unable to toggle visibility of paired scrollbars.");this.setVisibleInternal(a)}setVisibleInternal(a){const b=a!==this.isVisible();this.isHandleVisible=a;b&&this.updateDisplay_()}updateDisplay_(){this.containerVisible&&this.isVisible()?this.outerSvg.setAttribute("display","block"):this.outerSvg.setAttribute("display","none")}onMouseDownBar(a){this.workspace.markFocused();clearTouchIdentifier$$module$build$src$core$touch();this.cleanUp();
if(isRightButton$$module$build$src$core$browser_events(a))a.stopPropagation();else{var b=mouseToSvg$$module$build$src$core$browser_events(a,this.workspace.getParentSvg(),this.workspace.getInverseScreenCTM());b=this.horizontal?b.x:b.y;var c=getInjectionDivXY$$module$build$src$core$utils$svg_math(this.svgHandle);c=this.horizontal?c.x:c.y;var d=this.handlePosition,e=this.handleLength*.95;b<=c?d-=e:b>=c+this.handleLength&&(d+=e);this.setHandlePosition(this.constrainHandlePosition(d));this.updateMetrics();
a.stopPropagation();a.preventDefault()}}onMouseDownHandle(a){this.workspace.markFocused();this.cleanUp();isRightButton$$module$build$src$core$browser_events(a)?a.stopPropagation():(this.startDragHandle=this.handlePosition,this.startDragMouse=this.horizontal?a.clientX:a.clientY,this.onMouseUpWrapper_=conditionalBind$$module$build$src$core$browser_events(document,"pointerup",this,this.onMouseUpHandle),this.onMouseMoveWrapper_=conditionalBind$$module$build$src$core$browser_events(document,"pointermove",
this,this.onMouseMoveHandle),a.stopPropagation(),a.preventDefault())}onMouseMoveHandle(a){this.setHandlePosition(this.constrainHandlePosition(this.startDragHandle+((this.horizontal?a.clientX:a.clientY)-this.startDragMouse)));this.updateMetrics()}onMouseUpHandle(){clearTouchIdentifier$$module$build$src$core$touch();this.cleanUp()}cleanUp(){this.workspace.hideChaff(!0);this.onMouseUpWrapper_&&(unbind$$module$build$src$core$browser_events(this.onMouseUpWrapper_),this.onMouseUpWrapper_=null);this.onMouseMoveWrapper_&&
(unbind$$module$build$src$core$browser_events(this.onMouseMoveWrapper_),this.onMouseMoveWrapper_=null)}getRatio_(){let a=this.handlePosition/(this.scrollbarLength-this.handleLength);isNaN(a)&&(a=0);return a}updateMetrics(){const a=this.getRatio_();this.horizontal?this.workspace.setMetrics({x:a}):this.workspace.setMetrics({y:a})}set(a,b){this.setHandlePosition(this.constrainHandlePosition(a*this.ratio));(b||b===void 0)&&this.updateMetrics()}setOrigin(a,b){this.origin=new Coordinate$$module$build$src$core$utils$coordinate(a,
b)}static metricsAreEquivalent(a,b){return a.viewWidth===b.viewWidth&&a.viewHeight===b.viewHeight&&a.viewLeft===b.viewLeft&&a.viewTop===b.viewTop&&a.absoluteTop===b.absoluteTop&&a.absoluteLeft===b.absoluteLeft&&a.scrollWidth===b.scrollWidth&&a.scrollHeight===b.scrollHeight&&a.scrollLeft===b.scrollLeft&&a.scrollTop===b.scrollTop}};Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness=TOUCH_ENABLED$$module$build$src$core$touch?25:15;
Scrollbar$$module$build$src$core$scrollbar.DEFAULT_SCROLLBAR_MARGIN=.5;var module$build$src$core$scrollbar={};module$build$src$core$scrollbar.Scrollbar=Scrollbar$$module$build$src$core$scrollbar;var domParser$$module$build$src$core$utils$xml={parseFromString:function(){throw Error("DOMParser was not found in the global scope and was not properly injected using injectDependencies");}},xmlSerializer$$module$build$src$core$utils$xml={serializeToString:function(){throw Error("XMLSerializer was not foundin the global scope and was not properly injected using injectDependencies");}},{document:document$$module$build$src$core$utils$xml,DOMParser:DOMParser$$module$build$src$core$utils$xml,XMLSerializer:XMLSerializer$$module$build$src$core$utils$xml}=
globalThis;DOMParser$$module$build$src$core$utils$xml&&(domParser$$module$build$src$core$utils$xml=new DOMParser$$module$build$src$core$utils$xml);XMLSerializer$$module$build$src$core$utils$xml&&(xmlSerializer$$module$build$src$core$utils$xml=new XMLSerializer$$module$build$src$core$utils$xml);
var NAME_SPACE$$module$build$src$core$utils$xml="https://developers.google.com/blockly/xml",INVALID_CONTROL_CHARS$$module$build$src$core$utils$xml=/[\x00-\x09\x0B\x0C\x0E-\x1F]/g,module$build$src$core$utils$xml={NAME_SPACE:NAME_SPACE$$module$build$src$core$utils$xml};module$build$src$core$utils$xml.createElement=$.createElement$$module$build$src$core$utils$xml;module$build$src$core$utils$xml.createTextNode=$.createTextNode$$module$build$src$core$utils$xml;
module$build$src$core$utils$xml.domToText=domToText$$module$build$src$core$utils$xml;module$build$src$core$utils$xml.injectDependencies=injectDependencies$$module$build$src$core$utils$xml;module$build$src$core$utils$xml.textToDom=$.textToDom$$module$build$src$core$utils$xml;var CATEGORY_TOOLBOX_KIND$$module$build$src$core$utils$toolbox="categoryToolbox",FLYOUT_TOOLBOX_KIND$$module$build$src$core$utils$toolbox="flyoutToolbox",Position$$module$build$src$core$utils$toolbox;(function(a){a[a.TOP=0]="TOP";a[a.BOTTOM=1]="BOTTOM";a[a.LEFT=2]="LEFT";a[a.RIGHT=3]="RIGHT"})(Position$$module$build$src$core$utils$toolbox||(Position$$module$build$src$core$utils$toolbox={}));
var TEST_ONLY$$module$build$src$core$utils$toolbox={hasCategoriesInternal:hasCategoriesInternal$$module$build$src$core$utils$toolbox},module$build$src$core$utils$toolbox={};module$build$src$core$utils$toolbox.Position=Position$$module$build$src$core$utils$toolbox;module$build$src$core$utils$toolbox.TEST_ONLY=TEST_ONLY$$module$build$src$core$utils$toolbox;module$build$src$core$utils$toolbox.convertFlyoutDefToJsonArray=convertFlyoutDefToJsonArray$$module$build$src$core$utils$toolbox;
module$build$src$core$utils$toolbox.convertToolboxDefToJson=convertToolboxDefToJson$$module$build$src$core$utils$toolbox;module$build$src$core$utils$toolbox.hasCategories=hasCategories$$module$build$src$core$utils$toolbox;module$build$src$core$utils$toolbox.isCategoryCollapsible=isCategoryCollapsible$$module$build$src$core$utils$toolbox;module$build$src$core$utils$toolbox.parseToolboxTree=parseToolboxTree$$module$build$src$core$utils$toolbox;var verticalPosition$$module$build$src$core$positionable_helpers;(function(a){a[a.TOP=0]="TOP";a[a.BOTTOM=1]="BOTTOM"})(verticalPosition$$module$build$src$core$positionable_helpers||(verticalPosition$$module$build$src$core$positionable_helpers={}));var horizontalPosition$$module$build$src$core$positionable_helpers;(function(a){a[a.LEFT=0]="LEFT";a[a.RIGHT=1]="RIGHT"})(horizontalPosition$$module$build$src$core$positionable_helpers||(horizontalPosition$$module$build$src$core$positionable_helpers={}));
var bumpDirection$$module$build$src$core$positionable_helpers;(function(a){a[a.UP=0]="UP";a[a.DOWN=1]="DOWN"})(bumpDirection$$module$build$src$core$positionable_helpers||(bumpDirection$$module$build$src$core$positionable_helpers={}));var module$build$src$core$positionable_helpers={};module$build$src$core$positionable_helpers.bumpDirection=bumpDirection$$module$build$src$core$positionable_helpers;module$build$src$core$positionable_helpers.bumpPositionRect=bumpPositionRect$$module$build$src$core$positionable_helpers;
module$build$src$core$positionable_helpers.getCornerOppositeToolbox=getCornerOppositeToolbox$$module$build$src$core$positionable_helpers;module$build$src$core$positionable_helpers.getStartPositionRect=getStartPositionRect$$module$build$src$core$positionable_helpers;module$build$src$core$positionable_helpers.horizontalPosition=horizontalPosition$$module$build$src$core$positionable_helpers;module$build$src$core$positionable_helpers.verticalPosition=verticalPosition$$module$build$src$core$positionable_helpers;var SPRITE$$module$build$src$core$sprites={width:96,height:124,url:"sprites.png"},module$build$src$core$sprites={SPRITE:SPRITE$$module$build$src$core$sprites};var ZoomControls$$module$build$src$core$zoom_controls=class{constructor(a){this.workspace=a;this.id="zoomControls";this.boundEvents=[];this.zoomResetGroup=this.zoomOutGroup=this.zoomInGroup=null;this.HEIGHT=this.WIDTH=32;this.SMALL_SPACING=2;this.LARGE_SPACING=11;this.MARGIN_HORIZONTAL=this.MARGIN_VERTICAL=20;this.svgGroup=null;this.top=this.left=0;this.initialized=!1}createDom(){this.svgGroup=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{});const a=String(Math.random()).substring(2);
this.createZoomOutSvg(a);this.createZoomInSvg(a);this.workspace.isMovable()&&this.createZoomResetSvg(a);return this.svgGroup}init(){this.workspace.getComponentManager().addComponent({component:this,weight:ComponentManager$$module$build$src$core$component_manager.ComponentWeight.ZOOM_CONTROLS_WEIGHT,capabilities:[ComponentManager$$module$build$src$core$component_manager.Capability.POSITIONABLE]});this.initialized=!0}dispose(){this.workspace.getComponentManager().removeComponent("zoomControls");this.svgGroup&&
removeNode$$module$build$src$core$utils$dom(this.svgGroup);for(const a of this.boundEvents)unbind$$module$build$src$core$browser_events(a);this.boundEvents.length=0}getBoundingRectangle(){let a=this.SMALL_SPACING+2*this.HEIGHT;this.zoomResetGroup&&(a+=this.LARGE_SPACING+this.HEIGHT);return new Rect$$module$build$src$core$utils$rect(this.top,this.top+a,this.left,this.left+this.WIDTH)}position(a,b){if(this.initialized){var c=getCornerOppositeToolbox$$module$build$src$core$positionable_helpers(this.workspace,
a),d=this.SMALL_SPACING+2*this.HEIGHT;this.zoomResetGroup&&(d+=this.LARGE_SPACING+this.HEIGHT);a=getStartPositionRect$$module$build$src$core$positionable_helpers(c,new Size$$module$build$src$core$utils$size(this.WIDTH,d),this.MARGIN_HORIZONTAL,this.MARGIN_VERTICAL,a,this.workspace);c=c.vertical;b=bumpPositionRect$$module$build$src$core$positionable_helpers(a,this.MARGIN_VERTICAL,c===verticalPosition$$module$build$src$core$positionable_helpers.TOP?bumpDirection$$module$build$src$core$positionable_helpers.DOWN:
bumpDirection$$module$build$src$core$positionable_helpers.UP,b);if(c===verticalPosition$$module$build$src$core$positionable_helpers.TOP){var e=this.SMALL_SPACING+this.HEIGHT,f;(f=this.zoomInGroup)==null||f.setAttribute("transform","translate(0, "+e+")");this.zoomResetGroup&&this.zoomResetGroup.setAttribute("transform","translate(0, "+(e+this.LARGE_SPACING+this.HEIGHT)+")")}else{f=this.zoomResetGroup?this.LARGE_SPACING+this.HEIGHT:0;let h;(h=this.zoomInGroup)==null||h.setAttribute("transform","translate(0, "+
f+")");f=f+this.SMALL_SPACING+this.HEIGHT;(e=this.zoomOutGroup)==null||e.setAttribute("transform","translate(0, "+f+")")}this.top=b.top;this.left=b.left;var g;(g=this.svgGroup)==null||g.setAttribute("transform","translate("+this.left+","+this.top+")")}}createZoomOutSvg(a){this.zoomOutGroup=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{"class":"blocklyZoom blocklyZoomOut"},this.svgGroup);const b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.CLIPPATH,
{id:"blocklyZoomoutClipPath"+a},this.zoomOutGroup);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{width:32,height:32},b);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,{width:SPRITE$$module$build$src$core$sprites.width,height:SPRITE$$module$build$src$core$sprites.height,x:-64,y:-92,"clip-path":"url(#blocklyZoomoutClipPath"+a+")"},this.zoomOutGroup).setAttributeNS(XLINK_NS$$module$build$src$core$utils$dom,"xlink:href",
this.workspace.options.pathToMedia+SPRITE$$module$build$src$core$sprites.url);this.boundEvents.push(conditionalBind$$module$build$src$core$browser_events(this.zoomOutGroup,"pointerdown",null,this.zoom.bind(this,-1)))}createZoomInSvg(a){this.zoomInGroup=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{"class":"blocklyZoom blocklyZoomIn"},this.svgGroup);const b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.CLIPPATH,{id:"blocklyZoominClipPath"+
a},this.zoomInGroup);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{width:32,height:32},b);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,{width:SPRITE$$module$build$src$core$sprites.width,height:SPRITE$$module$build$src$core$sprites.height,x:-32,y:-92,"clip-path":"url(#blocklyZoominClipPath"+a+")"},this.zoomInGroup).setAttributeNS(XLINK_NS$$module$build$src$core$utils$dom,"xlink:href",this.workspace.options.pathToMedia+
SPRITE$$module$build$src$core$sprites.url);this.boundEvents.push(conditionalBind$$module$build$src$core$browser_events(this.zoomInGroup,"pointerdown",null,this.zoom.bind(this,1)))}zoom(a,b){this.workspace.markFocused();this.workspace.zoomCenter(a);this.fireZoomEvent();clearTouchIdentifier$$module$build$src$core$touch();b.stopPropagation();b.preventDefault()}createZoomResetSvg(a){this.zoomResetGroup=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{"class":"blocklyZoom blocklyZoomReset"},
this.svgGroup);const b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.CLIPPATH,{id:"blocklyZoomresetClipPath"+a},this.zoomResetGroup);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{width:32,height:32},b);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,{width:SPRITE$$module$build$src$core$sprites.width,height:SPRITE$$module$build$src$core$sprites.height,y:-92,"clip-path":"url(#blocklyZoomresetClipPath"+
a+")"},this.zoomResetGroup).setAttributeNS(XLINK_NS$$module$build$src$core$utils$dom,"xlink:href",this.workspace.options.pathToMedia+SPRITE$$module$build$src$core$sprites.url);this.boundEvents.push(conditionalBind$$module$build$src$core$browser_events(this.zoomResetGroup,"pointerdown",null,this.resetZoom.bind(this)))}resetZoom(a){this.workspace.markFocused();const b=Math.log(this.workspace.options.zoomOptions.startScale/this.workspace.scale)/Math.log(this.workspace.options.zoomOptions.scaleSpeed);
this.workspace.beginCanvasTransition();this.workspace.zoomCenter(b);this.workspace.scrollCenter();setTimeout(this.workspace.endCanvasTransition.bind(this.workspace),500);this.fireZoomEvent();clearTouchIdentifier$$module$build$src$core$touch();a.stopPropagation();a.preventDefault()}fireZoomEvent(){const a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.CLICK))(null,this.workspace.id,"zoom_controls");fire$$module$build$src$core$events$utils(a)}};register$$module$build$src$core$css("\n.blocklyZoom>image, .blocklyZoom>svg>image {\n  opacity: .4;\n}\n\n.blocklyZoom>image:hover, .blocklyZoom>svg>image:hover {\n  opacity: .6;\n}\n\n.blocklyZoom>image:active, .blocklyZoom>svg>image:active {\n  opacity: .8;\n}\n");
var module$build$src$core$zoom_controls={};module$build$src$core$zoom_controls.ZoomControls=ZoomControls$$module$build$src$core$zoom_controls;var VARIABLES$$module$build$src$core$serialization$priorities=100,PROCEDURES$$module$build$src$core$serialization$priorities=75,BLOCKS$$module$build$src$core$serialization$priorities=50,WORKSPACE_COMMENTS$$module$build$src$core$serialization$priorities=25,module$build$src$core$serialization$priorities={BLOCKS:BLOCKS$$module$build$src$core$serialization$priorities,PROCEDURES:PROCEDURES$$module$build$src$core$serialization$priorities,VARIABLES:VARIABLES$$module$build$src$core$serialization$priorities,
WORKSPACE_COMMENTS:WORKSPACE_COMMENTS$$module$build$src$core$serialization$priorities};var module$build$src$core$serialization$registry={};module$build$src$core$serialization$registry.register=register$$module$build$src$core$serialization$registry;module$build$src$core$serialization$registry.unregister=unregister$$module$build$src$core$serialization$registry;var saveComment$$module$build$src$core$serialization$workspace_comments=save$$module$build$src$core$serialization$workspace_comments,WorkspaceCommentSerializer$$module$build$src$core$serialization$workspace_comments=class{constructor(){this.priority=WORKSPACE_COMMENTS$$module$build$src$core$serialization$priorities}save(a){const b=[];for(const c of a.getTopComments())(a=save$$module$build$src$core$serialization$workspace_comments(c,{addCoordinates:!0,saveIds:!0}))&&b.push(a);return b.length?b:null}load(a,
b){for(const c of a)append$$module$build$src$core$serialization$workspace_comments(c,b,{recordUndo:getRecordUndo$$module$build$src$core$events$utils()})}clear(a){for(const b of a.getTopComments())b.dispose()}};register$$module$build$src$core$serialization$registry("workspaceComments",new WorkspaceCommentSerializer$$module$build$src$core$serialization$workspace_comments);var module$build$src$core$serialization$workspace_comments={};
module$build$src$core$serialization$workspace_comments.WorkspaceCommentSerializer=WorkspaceCommentSerializer$$module$build$src$core$serialization$workspace_comments;module$build$src$core$serialization$workspace_comments.append=append$$module$build$src$core$serialization$workspace_comments;module$build$src$core$serialization$workspace_comments.save=save$$module$build$src$core$serialization$workspace_comments;var module$build$src$core$clipboard$registry={};module$build$src$core$clipboard$registry.register=register$$module$build$src$core$clipboard$registry;module$build$src$core$clipboard$registry.unregister=unregister$$module$build$src$core$clipboard$registry;var WorkspaceCommentPaster$$module$build$src$core$clipboard$workspace_comment_paster=class{paste(a,b,c){a=a.commentState;c&&(a.x=c.x,a.y=c.y);$.disable$$module$build$src$core$events$utils();let d;try{d=append$$module$build$src$core$serialization$workspace_comments(a,b),moveCommentToNotConflict$$module$build$src$core$clipboard$workspace_comment_paster(d)}finally{$.enable$$module$build$src$core$events$utils()}if(!d)return null;isEnabled$$module$build$src$core$events$utils()&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.COMMENT_CREATE))(d));
$.getFocusManager$$module$build$src$core$focus_manager().focusNode(d);return d}};WorkspaceCommentPaster$$module$build$src$core$clipboard$workspace_comment_paster.TYPE="workspace-comment";register$$module$build$src$core$clipboard$registry(WorkspaceCommentPaster$$module$build$src$core$clipboard$workspace_comment_paster.TYPE,new WorkspaceCommentPaster$$module$build$src$core$clipboard$workspace_comment_paster);var module$build$src$core$clipboard$workspace_comment_paster={};
module$build$src$core$clipboard$workspace_comment_paster.WorkspaceCommentPaster=WorkspaceCommentPaster$$module$build$src$core$clipboard$workspace_comment_paster;var DEFAULT_SNAP_RADIUS$$module$build$src$core$config,module$build$src$core$config;DEFAULT_SNAP_RADIUS$$module$build$src$core$config=28;$.config$$module$build$src$core$config={dragRadius:5,flyoutDragRadius:10,snapRadius:DEFAULT_SNAP_RADIUS$$module$build$src$core$config,connectingSnapRadius:DEFAULT_SNAP_RADIUS$$module$build$src$core$config,currentConnectionPreference:8,bumpDelay:250};module$build$src$core$config={config:$.config$$module$build$src$core$config};var ARIA_PREFIX$$module$build$src$core$utils$aria="aria-",ROLE_ATTRIBUTE$$module$build$src$core$utils$aria="role",Role$$module$build$src$core$utils$aria;
(function(a){a.GRID="grid";a.GRIDCELL="gridcell";a.GROUP="group";a.LISTBOX="listbox";a.MENU="menu";a.MENUITEM="menuitem";a.MENUITEMCHECKBOX="menuitemcheckbox";a.OPTION="option";a.PRESENTATION="presentation";a.ROW="row";a.TREE="tree";a.TREEITEM="treeitem";a.SEPARATOR="separator";a.STATUS="status"})(Role$$module$build$src$core$utils$aria||(Role$$module$build$src$core$utils$aria={}));var State$$module$build$src$core$utils$aria;
(function(a){a.ACTIVEDESCENDANT="activedescendant";a.COLCOUNT="colcount";a.DISABLED="disabled";a.EXPANDED="expanded";a.INVALID="invalid";a.LABEL="label";a.LABELLEDBY="labelledby";a.LEVEL="level";a.ORIENTATION="orientation";a.POSINSET="posinset";a.ROWCOUNT="rowcount";a.SELECTED="selected";a.SETSIZE="setsize";a.VALUEMAX="valuemax";a.VALUEMIN="valuemin";a.LIVE="live";a.HIDDEN="hidden"})(State$$module$build$src$core$utils$aria||(State$$module$build$src$core$utils$aria={}));
var module$build$src$core$utils$aria={};module$build$src$core$utils$aria.Role=Role$$module$build$src$core$utils$aria;module$build$src$core$utils$aria.State=State$$module$build$src$core$utils$aria;module$build$src$core$utils$aria.setRole=setRole$$module$build$src$core$utils$aria;module$build$src$core$utils$aria.setState=setState$$module$build$src$core$utils$aria;var MenuItem$$module$build$src$core$menuitem=class{constructor(a,b){this.content=a;this.opt_value=b;this.enabled=!0;this.element=null;this.rightToLeft=!1;this.roleName=null;this.highlight=this.checked=this.checkable=!1;this.actionHandler=null}createDom(){const a=document.createElement("div");a.id=getNextUniqueId$$module$build$src$core$utils$idgenerator();this.element=a;a.className="blocklyMenuItem "+(this.enabled?"":"blocklyMenuItemDisabled ")+(this.checked?"blocklyMenuItemSelected ":"")+(this.highlight?
"blocklyMenuItemHighlight ":"")+(this.rightToLeft?"blocklyMenuItemRtl ":"");const b=document.createElement("div");b.className="blocklyMenuItemContent";if(this.checkable){var c=document.createElement("div");c.className="blocklyMenuItemCheckbox ";b.appendChild(c)}c=this.content;typeof this.content==="string"&&(c=document.createTextNode(this.content));b.appendChild(c);a.appendChild(b);this.roleName&&setRole$$module$build$src$core$utils$aria(a,this.roleName);setState$$module$build$src$core$utils$aria(a,
State$$module$build$src$core$utils$aria.SELECTED,this.checkable&&this.checked||!1);setState$$module$build$src$core$utils$aria(a,State$$module$build$src$core$utils$aria.DISABLED,!this.enabled);return a}dispose(){this.element=null}getElement(){return this.element}getId(){return this.element.id}getValue(){let a;return(a=this.opt_value)!=null?a:null}setRightToLeft(a){this.rightToLeft=a}setRole(a){this.roleName=a}setCheckable(a){this.checkable=a}setChecked(a){this.checked=a}setHighlighted(a){this.highlight=
a;const b=this.getElement();b&&this.isEnabled()&&(a?addClass$$module$build$src$core$utils$dom(b,"blocklyMenuItemHighlight"):removeClass$$module$build$src$core$utils$dom(b,"blocklyMenuItemHighlight"))}isEnabled(){return this.enabled}setEnabled(a){this.enabled=a}performAction(a){this.isEnabled()&&this.actionHandler&&this.actionHandler(this,a)}onAction(a,b){this.actionHandler=a.bind(b)}},module$build$src$core$menuitem={};module$build$src$core$menuitem.MenuItem=MenuItem$$module$build$src$core$menuitem;var Menu$$module$build$src$core$menu=class{constructor(){this.menuItems=[];this.roleName=this.element=this.onKeyDownHandler=this.pointerLeaveHandler=this.pointerEnterHandler=this.clickHandler=this.pointerMoveHandler=this.highlightedItem=this.openingCoords=null}addChild(a){this.menuItems.push(a)}render(a){const b=document.createElement("div");b.className="blocklyMenu";b.tabIndex=0;this.roleName&&setRole$$module$build$src$core$utils$aria(b,this.roleName);this.element=b;for(let c=0,d;d=this.menuItems[c];c++)b.appendChild(d.createDom());
this.pointerMoveHandler=conditionalBind$$module$build$src$core$browser_events(b,"pointermove",this,this.handlePointerMove,!0);this.clickHandler=conditionalBind$$module$build$src$core$browser_events(b,"pointerup",this,this.handleClick,!0);this.pointerEnterHandler=conditionalBind$$module$build$src$core$browser_events(b,"pointerenter",this,this.handlePointerEnter,!0);this.pointerLeaveHandler=conditionalBind$$module$build$src$core$browser_events(b,"pointerleave",this,this.handlePointerLeave,!0);this.onKeyDownHandler=
conditionalBind$$module$build$src$core$browser_events(b,"keydown",this,this.handleKeyEvent);a.appendChild(b);return b}getElement(){return this.element}focus(){const a=this.getElement();a&&a.focus({preventScroll:!0})}blur(){const a=this.getElement();a&&a.blur()}setRole(a){this.roleName=a}dispose(){this.pointerMoveHandler&&(unbind$$module$build$src$core$browser_events(this.pointerMoveHandler),this.pointerMoveHandler=null);this.clickHandler&&(unbind$$module$build$src$core$browser_events(this.clickHandler),
this.clickHandler=null);this.pointerEnterHandler&&(unbind$$module$build$src$core$browser_events(this.pointerEnterHandler),this.pointerEnterHandler=null);this.pointerLeaveHandler&&(unbind$$module$build$src$core$browser_events(this.pointerLeaveHandler),this.pointerLeaveHandler=null);this.onKeyDownHandler&&(unbind$$module$build$src$core$browser_events(this.onKeyDownHandler),this.onKeyDownHandler=null);for(let a=0,b;b=this.menuItems[a];a++)b.dispose();this.element=null}getMenuItem(a){const b=this.getElement();
for(;a&&a!==b;){if(a.classList.contains("blocklyMenuItem")){const c=this.getMenuItems();for(let d=0,e;e=c[d];d++)if(e.getElement()===a)return e}a=a.parentElement}return null}setHighlighted(a){var b=this.highlightedItem;b&&(b.setHighlighted(!1),this.highlightedItem=null);if(a){a.setHighlighted(!0);this.highlightedItem=a;b=this.getElement();const c=a.getElement();b&&c&&(scrollIntoContainerView$$module$build$src$core$utils$style(c,b),setState$$module$build$src$core$utils$aria(b,State$$module$build$src$core$utils$aria.ACTIVEDESCENDANT,
a.getId()))}}highlightNext(){const a=this.highlightedItem?this.menuItems.indexOf(this.highlightedItem):-1;this.highlightHelper(a,1)}highlightPrevious(){const a=this.highlightedItem?this.menuItems.indexOf(this.highlightedItem):-1;this.highlightHelper(a<0?this.menuItems.length:a,-1)}highlightFirst(){this.highlightHelper(-1,1)}highlightLast(){this.highlightHelper(this.menuItems.length,-1)}highlightHelper(a,b){a+=b;let c;const d=this.getMenuItems();for(;c=d[a];){if(c.isEnabled()){this.setHighlighted(c);
break}a+=b}}handlePointerMove(a){Math.max(Math.abs(a.movementX),Math.abs(a.movementY))!==0&&(a=this.getMenuItem(a.target))&&(a.isEnabled()?this.highlightedItem!==a&&this.setHighlighted(a):this.setHighlighted(null))}handleClick(a){var b=this.openingCoords;this.openingCoords=null;if(b&&typeof a.clientX==="number"){const c=new Coordinate$$module$build$src$core$utils$coordinate(a.clientX,a.clientY);if(Coordinate$$module$build$src$core$utils$coordinate.distance(b,c)<1)return}(b=this.getMenuItem(a.target))&&
b.performAction(a)}handlePointerEnter(a){this.focus()}handlePointerLeave(a){this.getElement()&&this.setHighlighted(null)}handleKeyEvent(a){if(this.menuItems.length&&!(a.shiftKey||a.ctrlKey||a.metaKey||a.altKey)){var b=this.highlightedItem;switch(a.key){case "Enter":case " ":b&&b.performAction(a);break;case "ArrowUp":this.highlightPrevious();break;case "ArrowDown":this.highlightNext();break;case "PageUp":case "Home":this.highlightFirst();break;case "PageDown":case "End":this.highlightLast();break;
default:return}a.preventDefault();a.stopPropagation()}}getSize(){const a=this.getElement(),b=getSize$$module$build$src$core$utils$style(a);b.height=a.scrollHeight;return b}getMenuItems(){return this.menuItems.filter(a=>a instanceof MenuItem$$module$build$src$core$menuitem)}},module$build$src$core$menu={};module$build$src$core$menu.Menu=Menu$$module$build$src$core$menu;var MenuSeparator$$module$build$src$core$menu_separator=class{constructor(){this.element=null}createDom(){this.element=document.createElement("hr");this.element.className="blocklyMenuSeparator";setRole$$module$build$src$core$utils$aria(this.element,Role$$module$build$src$core$utils$aria.SEPARATOR);return this.element}dispose(){let a;(a=this.element)==null||a.remove();this.element=null}},module$build$src$core$menu_separator={};module$build$src$core$menu_separator.MenuSeparator=MenuSeparator$$module$build$src$core$menu_separator;var COLLAPSED_INPUT_NAME$$module$build$src$core$constants="_TEMP_COLLAPSED_INPUT",COLLAPSED_FIELD_NAME$$module$build$src$core$constants="_TEMP_COLLAPSED_FIELD",MANUALLY_DISABLED$$module$build$src$core$constants="MANUALLY_DISABLED",module$build$src$core$constants={COLLAPSED_FIELD_NAME:COLLAPSED_FIELD_NAME$$module$build$src$core$constants,COLLAPSED_INPUT_NAME:COLLAPSED_INPUT_NAME$$module$build$src$core$constants,MANUALLY_DISABLED:MANUALLY_DISABLED$$module$build$src$core$constants};(function(a){a[a.VALUE=1]="VALUE";a[a.STATEMENT=3]="STATEMENT";a[a.DUMMY=5]="DUMMY";a[a.CUSTOM=6]="CUSTOM";a[a.END_ROW=7]="END_ROW"})($.inputTypes$$module$build$src$core$inputs$input_types||($.inputTypes$$module$build$src$core$inputs$input_types={}));var module$build$src$core$inputs$input_types={};module$build$src$core$inputs$input_types.inputTypes=$.inputTypes$$module$build$src$core$inputs$input_types;var module$build$src$core$interfaces$i_serializable={};module$build$src$core$interfaces$i_serializable.isSerializable=isSerializable$$module$build$src$core$interfaces$i_serializable;var rootBlocks$$module$build$src$core$render_management=new Set,dirtyBlocks$$module$build$src$core$render_management=new WeakSet,eventGroups$$module$build$src$core$render_management=new WeakMap,afterRendersPromise$$module$build$src$core$render_management=null,afterRendersResolver$$module$build$src$core$render_management=null,animationRequestId$$module$build$src$core$render_management=0,module$build$src$core$render_management={};module$build$src$core$render_management.finishQueuedRenders=finishQueuedRenders$$module$build$src$core$render_management;
module$build$src$core$render_management.queueRender=queueRender$$module$build$src$core$render_management;module$build$src$core$render_management.triggerQueuedRenders=triggerQueuedRenders$$module$build$src$core$render_management;var setLocale$$module$build$src$core$msg,module$build$src$core$msg;$.Msg$$module$build$src$core$msg=Object.create(null);setLocale$$module$build$src$core$msg=function(a){Object.keys(a).forEach(function(b){$.Msg$$module$build$src$core$msg[b]=a[b]})};module$build$src$core$msg={Msg:$.Msg$$module$build$src$core$msg,setLocale:setLocale$$module$build$src$core$msg};var CLASS_NAME$$module$build$src$core$toast="blocklyToast",MESSAGE_CLASS_NAME$$module$build$src$core$toast="blocklyToastMessage",CLOSE_BUTTON_CLASS_NAME$$module$build$src$core$toast="blocklyToastCloseButton",Toast$$module$build$src$core$toast=class{static show(a,b){if(b.oncePerSession&&b.id){if(this.shownIds.has(b.id))return;this.shownIds.add(b.id)}this.hide(a);const c=this.createDom(a,b);requestAnimationFrame(()=>{c.style.bottom="2rem"})}static createDom(a,b){const {message:c,duration:d=5,assertiveness:e=
Toast$$module$build$src$core$toast.Assertiveness.POLITE}=b,f=document.createElement("div");a.getInjectionDiv().appendChild(f);f.dataset.toastId=b.id;f.className=CLASS_NAME$$module$build$src$core$toast;setRole$$module$build$src$core$utils$aria(f,Role$$module$build$src$core$utils$aria.STATUS);setState$$module$build$src$core$utils$aria(f,State$$module$build$src$core$utils$aria.LIVE,e);b=f.appendChild(document.createElement("div"));b.className=MESSAGE_CLASS_NAME$$module$build$src$core$toast;b.innerText=
c;b=f.appendChild(document.createElement("button"));b.className=CLOSE_BUTTON_CLASS_NAME$$module$build$src$core$toast;setState$$module$build$src$core$utils$aria(b,State$$module$build$src$core$utils$aria.LABEL,$.Msg$$module$build$src$core$msg.CLOSE);var g=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.SVG,{width:24,height:24,viewBox:"0 0 24 24",fill:"none"},b);setState$$module$build$src$core$utils$aria(g,State$$module$build$src$core$utils$aria.HIDDEN,!0);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,
{x:19.7782,y:2.80762,width:2,height:24,transform:"rotate(45, 19.7782, 2.80762)",fill:"black"},g);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{x:2.80762,y:4.22183,width:2,height:24,transform:"rotate(-45, 2.80762, 4.22183)",fill:"black"},g);b.addEventListener("click",()=>{f.remove();a.markFocused()});let h;b=()=>{h=setTimeout(()=>f.remove(),d*1E3)};g=()=>clearTimeout(h);f.addEventListener("focusin",g);f.addEventListener("focusout",b);f.addEventListener("mouseenter",
g);f.addEventListener("mousemove",g);f.addEventListener("mouseleave",b);b();return f}static hide(a,b){a=a.getInjectionDiv().querySelector(`.${CLASS_NAME$$module$build$src$core$toast}`);a instanceof HTMLElement&&(!b||b===a.dataset.toastId)&&a.remove()}};Toast$$module$build$src$core$toast.shownIds=new Set;(function(a){a=a.Assertiveness||(a.Assertiveness={});a.ASSERTIVE="assertive";a.POLITE="polite"})(Toast$$module$build$src$core$toast||(Toast$$module$build$src$core$toast={}));register$$module$build$src$core$css(`
.${CLASS_NAME$$module$build$src$core$toast} {
  font-size: 1.2rem;
  position: absolute;
  bottom: -10rem;
  right: 2rem;
  padding: 1rem;
  color: black;
  background-color: white;
  border: 2px solid black;
  border-radius: 0.4rem;
  z-index: 999;
  display: flex;
  align-items: center;
  gap: 0.8rem;
  line-height: 1.5;
  transition: bottom 0.3s ease-out;
}

.${CLASS_NAME$$module$build$src$core$toast} .${MESSAGE_CLASS_NAME$$module$build$src$core$toast} {
  maxWidth: 18rem;
}

.${CLASS_NAME$$module$build$src$core$toast} .${CLOSE_BUTTON_CLASS_NAME$$module$build$src$core$toast} {
  margin: 0;
  padding: 0.2rem;
  background-color: transparent;
  color: black;
  border: none;
  cursor: pointer;
}
`);var module$build$src$core$toast={};module$build$src$core$toast.Toast=Toast$$module$build$src$core$toast;var defaultAlert$$module$build$src$core$dialog=function(a,b){window.alert(a);b&&b()},alertImplementation$$module$build$src$core$dialog=defaultAlert$$module$build$src$core$dialog,defaultConfirm$$module$build$src$core$dialog=function(a,b){b(window.confirm(a))},confirmImplementation$$module$build$src$core$dialog=defaultConfirm$$module$build$src$core$dialog,defaultPrompt$$module$build$src$core$dialog=function(a,b,c){c(window.prompt(a,b))},promptImplementation$$module$build$src$core$dialog=defaultPrompt$$module$build$src$core$dialog,
defaultToast$$module$build$src$core$dialog=Toast$$module$build$src$core$toast.show.bind(Toast$$module$build$src$core$toast),toastImplementation$$module$build$src$core$dialog=defaultToast$$module$build$src$core$dialog,module$build$src$core$dialog={};module$build$src$core$dialog.alert=alert$$module$build$src$core$dialog;module$build$src$core$dialog.confirm=confirm$$module$build$src$core$dialog;module$build$src$core$dialog.prompt=prompt$$module$build$src$core$dialog;
module$build$src$core$dialog.setAlert=setAlert$$module$build$src$core$dialog;module$build$src$core$dialog.setConfirm=setConfirm$$module$build$src$core$dialog;module$build$src$core$dialog.setPrompt=setPrompt$$module$build$src$core$dialog;module$build$src$core$dialog.setToast=setToast$$module$build$src$core$dialog;module$build$src$core$dialog.toast=toast$$module$build$src$core$dialog;var module$build$src$core$interfaces$i_legacy_procedure_blocks={};module$build$src$core$interfaces$i_legacy_procedure_blocks.isLegacyProcedureCallBlock=isLegacyProcedureCallBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks;module$build$src$core$interfaces$i_legacy_procedure_blocks.isLegacyProcedureDefBlock=isLegacyProcedureDefBlock$$module$build$src$core$interfaces$i_legacy_procedure_blocks;var module$build$src$core$interfaces$i_variable_backed_parameter_model={};module$build$src$core$interfaces$i_variable_backed_parameter_model.isVariableBackedParameterModel=isVariableBackedParameterModel$$module$build$src$core$interfaces$i_variable_backed_parameter_model;var previousWarnings$$module$build$src$core$utils$deprecation=new Set,module$build$src$core$utils$deprecation={};module$build$src$core$utils$deprecation.warn=warn$$module$build$src$core$utils$deprecation;var CATEGORY_NAME$$module$build$src$core$variables="VARIABLE",VAR_LETTER_OPTIONS$$module$build$src$core$variables="ijkmnopqrstuvwxyzabcdefgh",TEST_ONLY$$module$build$src$core$variables={generateUniqueNameInternal:generateUniqueNameInternal$$module$build$src$core$variables},module$build$src$core$variables={CATEGORY_NAME:CATEGORY_NAME$$module$build$src$core$variables,TEST_ONLY:TEST_ONLY$$module$build$src$core$variables,VAR_LETTER_OPTIONS:VAR_LETTER_OPTIONS$$module$build$src$core$variables};
module$build$src$core$variables.allDeveloperVariables=$.allDeveloperVariables$$module$build$src$core$variables;module$build$src$core$variables.allUsedVarModels=$.allUsedVarModels$$module$build$src$core$variables;module$build$src$core$variables.compareByName=compareByName$$module$build$src$core$variables;module$build$src$core$variables.createVariableButtonHandler=createVariableButtonHandler$$module$build$src$core$variables;module$build$src$core$variables.deleteVariable=$.deleteVariable$$module$build$src$core$variables;
module$build$src$core$variables.flyoutCategory=flyoutCategory$$module$build$src$core$variables;module$build$src$core$variables.flyoutCategoryBlocks=flyoutCategoryBlocks$$module$build$src$core$variables;module$build$src$core$variables.generateUniqueName=generateUniqueName$$module$build$src$core$variables;module$build$src$core$variables.generateUniqueNameFromOptions=generateUniqueNameFromOptions$$module$build$src$core$variables;module$build$src$core$variables.generateVariableFieldDom=generateVariableFieldDom$$module$build$src$core$variables;
module$build$src$core$variables.getAddedVariables=getAddedVariables$$module$build$src$core$variables;module$build$src$core$variables.getOrCreateVariablePackage=$.getOrCreateVariablePackage$$module$build$src$core$variables;module$build$src$core$variables.getVariable=$.getVariable$$module$build$src$core$variables;module$build$src$core$variables.getVariableUsesById=getVariableUsesById$$module$build$src$core$variables;module$build$src$core$variables.internalFlyoutCategory=internalFlyoutCategory$$module$build$src$core$variables;
module$build$src$core$variables.jsonFlyoutCategoryBlocks=jsonFlyoutCategoryBlocks$$module$build$src$core$variables;module$build$src$core$variables.nameUsedWithAnyType=nameUsedWithAnyType$$module$build$src$core$variables;module$build$src$core$variables.nameUsedWithConflictingParam=nameUsedWithConflictingParam$$module$build$src$core$variables;module$build$src$core$variables.promptName=promptName$$module$build$src$core$variables;module$build$src$core$variables.renameVariable=$.renameVariable$$module$build$src$core$variables;var DeserializationError$$module$build$src$core$serialization$exceptions=class extends Error{},MissingBlockType$$module$build$src$core$serialization$exceptions=class extends DeserializationError$$module$build$src$core$serialization$exceptions{constructor(a){super("Expected to find a 'type' property, defining the block type");this.state=a}},MissingConnection$$module$build$src$core$serialization$exceptions=class extends DeserializationError$$module$build$src$core$serialization$exceptions{constructor(a,
b,c){super(`The block ${b.toDevString()} is missing a(n) ${a}
connection`);this.block=b;this.state=c}},BadConnectionCheck$$module$build$src$core$serialization$exceptions=class extends DeserializationError$$module$build$src$core$serialization$exceptions{constructor(a,b,c,d){super(`The block ${c.toDevString()} could not connect its
${b} to its parent, because: ${a}`);this.childBlock=c;this.childState=d}},RealChildOfShadow$$module$build$src$core$serialization$exceptions=class extends DeserializationError$$module$build$src$core$serialization$exceptions{constructor(a){super("Encountered a real block which is defined as a child of a shadow\nblock. It is an invariant of Blockly that shadow blocks only have shadow\nchildren");this.state=a}},UnregisteredIcon$$module$build$src$core$serialization$exceptions=class extends DeserializationError$$module$build$src$core$serialization$exceptions{constructor(a,
b,c){super(`Cannot add an icon of type '${a}' to the block `+`${b.toDevString()}, because there is no icon registered with `+`type '${a}'. Make sure that all of your icons have been `+"registered.");this.block=b;this.state=c}},module$build$src$core$serialization$exceptions={};module$build$src$core$serialization$exceptions.BadConnectionCheck=BadConnectionCheck$$module$build$src$core$serialization$exceptions;module$build$src$core$serialization$exceptions.DeserializationError=DeserializationError$$module$build$src$core$serialization$exceptions;
module$build$src$core$serialization$exceptions.MissingBlockType=MissingBlockType$$module$build$src$core$serialization$exceptions;module$build$src$core$serialization$exceptions.MissingConnection=MissingConnection$$module$build$src$core$serialization$exceptions;module$build$src$core$serialization$exceptions.RealChildOfShadow=RealChildOfShadow$$module$build$src$core$serialization$exceptions;module$build$src$core$serialization$exceptions.UnregisteredIcon=UnregisteredIcon$$module$build$src$core$serialization$exceptions;var saveBlock$$module$build$src$core$serialization$blocks=save$$module$build$src$core$serialization$blocks,BlockSerializer$$module$build$src$core$serialization$blocks=class{constructor(){this.priority=BLOCKS$$module$build$src$core$serialization$priorities}save(a){const b=[];for(const c of a.getTopBlocks(!1))(a=save$$module$build$src$core$serialization$blocks(c,{addCoordinates:!0,doFullSerialization:!1}))&&b.push(a);return b.length?{languageVersion:0,blocks:b}:null}load(a,b){a=a.blocks;for(const c of a)append$$module$build$src$core$serialization$blocks(c,
b,{recordUndo:getRecordUndo$$module$build$src$core$events$utils()})}clear(a){for(const b of a.getTopBlocks(!1))b.dispose(!1)}};register$$module$build$src$core$serialization$registry("blocks",new BlockSerializer$$module$build$src$core$serialization$blocks);var module$build$src$core$serialization$blocks={};module$build$src$core$serialization$blocks.BlockSerializer=BlockSerializer$$module$build$src$core$serialization$blocks;module$build$src$core$serialization$blocks.append=append$$module$build$src$core$serialization$blocks;
module$build$src$core$serialization$blocks.appendInternal=appendInternal$$module$build$src$core$serialization$blocks;module$build$src$core$serialization$blocks.save=save$$module$build$src$core$serialization$blocks;var IconType$$module$build$src$core$icons$icon_types=class{constructor(a){this.name=a}toString(){return this.name}equals(a){return this.name===a.toString()}};IconType$$module$build$src$core$icons$icon_types.MUTATOR=new IconType$$module$build$src$core$icons$icon_types("mutator");IconType$$module$build$src$core$icons$icon_types.WARNING=new IconType$$module$build$src$core$icons$icon_types("warning");IconType$$module$build$src$core$icons$icon_types.COMMENT=new IconType$$module$build$src$core$icons$icon_types("comment");
var module$build$src$core$icons$icon_types={};module$build$src$core$icons$icon_types.IconType=IconType$$module$build$src$core$icons$icon_types;var module$build$src$core$interfaces$i_has_bubble={};module$build$src$core$interfaces$i_has_bubble.hasBubble=hasBubble$$module$build$src$core$interfaces$i_has_bubble;var BlockBase$$module$build$src$core$events$events_block_base=class extends Abstract$$module$build$src$core$events$events_abstract{constructor(a){super();this.isBlank=!a;a&&(this.blockId=a.id,this.workspaceId=a.workspace.id)}toJson(){const a=super.toJson();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");a.blockId=this.blockId;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new BlockBase$$module$build$src$core$events$events_block_base);
b.blockId=a.blockId;return b}},module$build$src$core$events$events_block_base={};module$build$src$core$events$events_block_base.BlockBase=BlockBase$$module$build$src$core$events$events_block_base;var BlockChange$$module$build$src$core$events$events_block_change=class extends BlockBase$$module$build$src$core$events$events_block_base{constructor(a,b,c,d,e){super(a);this.type=EventType$$module$build$src$core$events$type.BLOCK_CHANGE;a&&(this.element=b,this.name=c||void 0,this.oldValue=d,this.newValue=e)}toJson(){const a=super.toJson();if(!this.element)throw Error("The changed element is undefined. Either pass an element to the constructor, or call fromJson");a.element=this.element;a.name=this.name;
a.oldValue=this.oldValue;a.newValue=this.newValue;this.disabledReason&&(a.disabledReason=this.disabledReason);return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new BlockChange$$module$build$src$core$events$events_block_change);b.element=a.element;b.name=a.name;b.oldValue=a.oldValue;b.newValue=a.newValue;a.disabledReason!==void 0&&(b.disabledReason=a.disabledReason);return b}setDisabledReason(a){if(this.element!=="disabled")throw Error('Cannot set the disabled reason for a BlockChange event if the element is not "disabled".');
this.disabledReason=a}isNull(){return this.oldValue===this.newValue}run(a){var b=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");b=b.getBlockById(this.blockId);if(!b)throw Error("The associated block is undefined. Either pass a block to the constructor, or call fromJson");const c=b.getIcon(IconType$$module$build$src$core$icons$icon_types.MUTATOR);c&&hasBubble$$module$build$src$core$interfaces$i_has_bubble(c)&&
c.bubbleIsVisible()&&c.setBubbleVisible(!1);a=a?this.newValue:this.oldValue;switch(this.element){case "field":(b=b.getField(this.name))?b.setValue(a):console.warn("Can't set non-existent field: "+this.name);break;case "comment":b.setCommentText(a||null);break;case "collapsed":b.setCollapsed(!!a);break;case "disabled":var d;b.setDisabledReason(!!a,(d=this.disabledReason)!=null?d:MANUALLY_DISABLED$$module$build$src$core$constants);break;case "inline":b.setInputsInline(!!a);break;case "mutation":d=BlockChange$$module$build$src$core$events$events_block_change.getExtraBlockState_(b);
b.loadExtraState?b.loadExtraState(JSON.parse(a||"{}")):b.domToMutation&&b.domToMutation($.textToDom$$module$build$src$core$utils$xml(a||"<mutation/>"));fire$$module$build$src$core$events$utils(new BlockChange$$module$build$src$core$events$events_block_change(b,"mutation",null,d,a));break;default:console.warn("Unknown change type: "+this.element)}}static getExtraBlockState_(a){return a.saveExtraState?(a=a.saveExtraState(!0))?JSON.stringify(a):"":a.mutationToDom?(a=a.mutationToDom())?domToText$$module$build$src$core$xml(a):
"":""}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.BLOCK_CHANGE,BlockChange$$module$build$src$core$events$events_block_change);var module$build$src$core$events$events_block_change={};module$build$src$core$events$events_block_change.BlockChange=BlockChange$$module$build$src$core$events$events_block_change;var module$build$src$core$utils$math={};module$build$src$core$utils$math.clamp=clamp$$module$build$src$core$utils$math;module$build$src$core$utils$math.toDegrees=toDegrees$$module$build$src$core$utils$math;module$build$src$core$utils$math.toRadians=toRadians$$module$build$src$core$utils$math;var ARROW_SIZE$$module$build$src$core$dropdowndiv=16,BORDER_SIZE$$module$build$src$core$dropdowndiv=1,ARROW_HORIZONTAL_PADDING$$module$build$src$core$dropdowndiv=12,PADDING_Y$$module$build$src$core$dropdowndiv=16,ANIMATION_TIME$$module$build$src$core$dropdowndiv=.25,animateOutTimer$$module$build$src$core$dropdowndiv=null,onHide$$module$build$src$core$dropdowndiv=null,renderedClassName$$module$build$src$core$dropdowndiv="",themeClassName$$module$build$src$core$dropdowndiv="",div$$module$build$src$core$dropdowndiv,
content$$module$build$src$core$dropdowndiv,arrow$$module$build$src$core$dropdowndiv,boundsElement$$module$build$src$core$dropdowndiv=null,owner$$module$build$src$core$dropdowndiv=null,positionToField$$module$build$src$core$dropdowndiv=null,returnEphemeralFocus$$module$build$src$core$dropdowndiv=null,keydownListener$$module$build$src$core$dropdowndiv=null,internal$$module$build$src$core$dropdowndiv={getBoundsInfo:function(){const a=getPageOffset$$module$build$src$core$utils$style(boundsElement$$module$build$src$core$dropdowndiv),
b=getSize$$module$build$src$core$utils$style(boundsElement$$module$build$src$core$dropdowndiv);return{left:a.x,right:a.x+b.width,top:a.y,bottom:a.y+b.height,width:b.width,height:b.height}},getPositionMetrics:function(a,b,c,d){const e=internal$$module$build$src$core$dropdowndiv.getBoundsInfo(),f=getSize$$module$build$src$core$utils$style(div$$module$build$src$core$dropdowndiv);return b+f.height<e.bottom?getPositionBelowMetrics$$module$build$src$core$dropdowndiv(a,b,e,f):d-f.height>e.top?getPositionAboveMetrics$$module$build$src$core$dropdowndiv(c,
d,e,f):b+f.height<document.documentElement.clientHeight?getPositionBelowMetrics$$module$build$src$core$dropdowndiv(a,b,e,f):d-f.height>document.documentElement.clientTop?getPositionAboveMetrics$$module$build$src$core$dropdowndiv(c,d,e,f):getPositionTopOfPageMetrics$$module$build$src$core$dropdowndiv(a,e,f)}},TEST_ONLY$$module$build$src$core$dropdowndiv=internal$$module$build$src$core$dropdowndiv,module$build$src$core$dropdowndiv={ANIMATION_TIME:ANIMATION_TIME$$module$build$src$core$dropdowndiv,ARROW_HORIZONTAL_PADDING:ARROW_HORIZONTAL_PADDING$$module$build$src$core$dropdowndiv,
ARROW_SIZE:ARROW_SIZE$$module$build$src$core$dropdowndiv,BORDER_SIZE:BORDER_SIZE$$module$build$src$core$dropdowndiv,PADDING_Y:PADDING_Y$$module$build$src$core$dropdowndiv,TEST_ONLY:internal$$module$build$src$core$dropdowndiv};module$build$src$core$dropdowndiv.clearContent=clearContent$$module$build$src$core$dropdowndiv;module$build$src$core$dropdowndiv.createDom=createDom$$module$build$src$core$dropdowndiv;module$build$src$core$dropdowndiv.getContentDiv=getContentDiv$$module$build$src$core$dropdowndiv;
module$build$src$core$dropdowndiv.getOwner=getOwner$$module$build$src$core$dropdowndiv;module$build$src$core$dropdowndiv.getPositionX=getPositionX$$module$build$src$core$dropdowndiv;module$build$src$core$dropdowndiv.hide=hide$$module$build$src$core$dropdowndiv;module$build$src$core$dropdowndiv.hideIfOwner=hideIfOwner$$module$build$src$core$dropdowndiv;module$build$src$core$dropdowndiv.hideWithoutAnimation=hideWithoutAnimation$$module$build$src$core$dropdowndiv;
module$build$src$core$dropdowndiv.isVisible=isVisible$$module$build$src$core$dropdowndiv;module$build$src$core$dropdowndiv.repositionForWindowResize=repositionForWindowResize$$module$build$src$core$dropdowndiv;module$build$src$core$dropdowndiv.setBoundsElement=setBoundsElement$$module$build$src$core$dropdowndiv;module$build$src$core$dropdowndiv.setColour=setColour$$module$build$src$core$dropdowndiv;module$build$src$core$dropdowndiv.show=show$$module$build$src$core$dropdowndiv;
module$build$src$core$dropdowndiv.showPositionedByBlock=showPositionedByBlock$$module$build$src$core$dropdowndiv;module$build$src$core$dropdowndiv.showPositionedByField=showPositionedByField$$module$build$src$core$dropdowndiv;var module$build$src$core$utils$string={};module$build$src$core$utils$string.commonWordPrefix=commonWordPrefix$$module$build$src$core$utils$string;module$build$src$core$utils$string.commonWordSuffix=commonWordSuffix$$module$build$src$core$utils$string;module$build$src$core$utils$string.isNumber=$.isNumber$$module$build$src$core$utils$string;module$build$src$core$utils$string.shortestStringLength=shortestStringLength$$module$build$src$core$utils$string;module$build$src$core$utils$string.wrap=$.wrap$$module$build$src$core$utils$string;var customTooltip$$module$build$src$core$tooltip=void 0,visible$$module$build$src$core$tooltip=!1,blocked$$module$build$src$core$tooltip=!1,LIMIT$$module$build$src$core$tooltip=50,mouseOutPid$$module$build$src$core$tooltip=0,showPid$$module$build$src$core$tooltip=0,lastX$$module$build$src$core$tooltip=0,lastY$$module$build$src$core$tooltip=0,element$$module$build$src$core$tooltip=null,poisonedElement$$module$build$src$core$tooltip=null,OFFSET_X$$module$build$src$core$tooltip=0,OFFSET_Y$$module$build$src$core$tooltip=
10,RADIUS_OK$$module$build$src$core$tooltip=10,HOVER_MS$$module$build$src$core$tooltip=750,MARGINS$$module$build$src$core$tooltip=5,containerDiv$$module$build$src$core$tooltip=null,module$build$src$core$tooltip={HOVER_MS:HOVER_MS$$module$build$src$core$tooltip,LIMIT:LIMIT$$module$build$src$core$tooltip,MARGINS:MARGINS$$module$build$src$core$tooltip,OFFSET_X:OFFSET_X$$module$build$src$core$tooltip,OFFSET_Y:OFFSET_Y$$module$build$src$core$tooltip,RADIUS_OK:RADIUS_OK$$module$build$src$core$tooltip};
module$build$src$core$tooltip.bindMouseEvents=bindMouseEvents$$module$build$src$core$tooltip;module$build$src$core$tooltip.block=block$$module$build$src$core$tooltip;module$build$src$core$tooltip.createDom=createDom$$module$build$src$core$tooltip;module$build$src$core$tooltip.dispose=dispose$$module$build$src$core$tooltip;module$build$src$core$tooltip.getCustomTooltip=getCustomTooltip$$module$build$src$core$tooltip;module$build$src$core$tooltip.getDiv=getDiv$$module$build$src$core$tooltip;
module$build$src$core$tooltip.getTooltipOfObject=getTooltipOfObject$$module$build$src$core$tooltip;module$build$src$core$tooltip.hide=hide$$module$build$src$core$tooltip;module$build$src$core$tooltip.isVisible=isVisible$$module$build$src$core$tooltip;module$build$src$core$tooltip.setCustomTooltip=setCustomTooltip$$module$build$src$core$tooltip;module$build$src$core$tooltip.unbindMouseEvents=unbindMouseEvents$$module$build$src$core$tooltip;module$build$src$core$tooltip.unblock=unblock$$module$build$src$core$tooltip;var hsvSaturation$$module$build$src$core$utils$colour=.45,hsvValue$$module$build$src$core$utils$colour=.65,names$$module$build$src$core$utils$colour={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00"},module$build$src$core$utils$colour={};module$build$src$core$utils$colour.blend=blend$$module$build$src$core$utils$colour;
module$build$src$core$utils$colour.getHsvSaturation=getHsvSaturation$$module$build$src$core$utils$colour;module$build$src$core$utils$colour.getHsvValue=getHsvValue$$module$build$src$core$utils$colour;module$build$src$core$utils$colour.hexToRgb=hexToRgb$$module$build$src$core$utils$colour;module$build$src$core$utils$colour.hsvToHex=hsvToHex$$module$build$src$core$utils$colour;module$build$src$core$utils$colour.hueToHex=hueToHex$$module$build$src$core$utils$colour;
module$build$src$core$utils$colour.names=names$$module$build$src$core$utils$colour;module$build$src$core$utils$colour.parse=parse$$module$build$src$core$utils$colour;module$build$src$core$utils$colour.rgbToHex=rgbToHex$$module$build$src$core$utils$colour;module$build$src$core$utils$colour.setHsvSaturation=setHsvSaturation$$module$build$src$core$utils$colour;module$build$src$core$utils$colour.setHsvValue=setHsvValue$$module$build$src$core$utils$colour;var module$build$src$core$utils$parsing={};module$build$src$core$utils$parsing.checkMessageReferences=checkMessageReferences$$module$build$src$core$utils$parsing;module$build$src$core$utils$parsing.parseBlockColour=parseBlockColour$$module$build$src$core$utils$parsing;module$build$src$core$utils$parsing.replaceMessageReferences=replaceMessageReferences$$module$build$src$core$utils$parsing;module$build$src$core$utils$parsing.tokenizeInterpolation=tokenizeInterpolation$$module$build$src$core$utils$parsing;var Field$$module$build$src$core$field=class{get size_(){return this.size}set size_(a){this.size=a}constructor(a,b,c){this.DEFAULT_VALUE=null;this.name=void 0;this.tooltip=this.validator_=null;this.size=new Size$$module$build$src$core$utils$size(0,0);this.constants_=this.mouseDownWrapper=this.textContent_=this.textElement_=this.borderRect_=this.fieldGroup_=null;this.disposed=!1;this.maxDisplayLength=50;this.sourceBlock_=null;this.enabled_=this.visible_=this.isDirty_=!0;this.suffixField=this.prefixField=
this.clickTarget_=null;this.EDITABLE=!0;this.SERIALIZABLE=!1;this.id_=null;this.value_="DEFAULT_VALUE"in new.target.prototype?new.target.prototype.DEFAULT_VALUE:this.DEFAULT_VALUE;this.size_=new Size$$module$build$src$core$utils$size(0,0);a!==Field$$module$build$src$core$field.SKIP_SETUP&&(c&&this.configure_(c),this.setValue(a),b&&this.setValidator(b))}configure_(a){a.tooltip&&this.setTooltip(replaceMessageReferences$$module$build$src$core$utils$parsing(a.tooltip))}setSourceBlock(a){if(this.sourceBlock_)throw Error("Field already bound to a block");
this.sourceBlock_=a;if(a.id.includes("_field"))throw Error("Field ID indicator is contained in block ID. This may cause "+`problems with focus: ${a.id}.`);this.id_=`${a.id}_field_${getNextUniqueId$$module$build$src$core$utils$idgenerator()}`}getConstants(){!this.constants_&&this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&this.sourceBlock_.workspace.rendered&&(this.constants_=this.sourceBlock_.workspace.getRenderer().getConstants());return this.constants_}getSourceBlock(){return this.sourceBlock_}init(){if(!this.fieldGroup_){var a=
this.id_;if(!a)throw Error("Expected ID to be defined prior to init.");this.fieldGroup_=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{id:a});this.isVisible()||(this.fieldGroup_.style.display="none");this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_);this.initView();this.updateEditable();this.setTooltip(this.tooltip);this.bindEvents_();this.initModel();this.applyColour()}}initView(){this.createBorderRect_();this.createTextElement_();this.fieldGroup_&&
addClass$$module$build$src$core$utils$dom(this.fieldGroup_,"blocklyField")}initModel(){}isFullBlockField(){return!this.borderRect_}createBorderRect_(){this.borderRect_=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{rx:this.getConstants().FIELD_BORDER_RECT_RADIUS,ry:this.getConstants().FIELD_BORDER_RECT_RADIUS,x:0,y:0,height:this.size_.height,width:this.size_.width,"class":"blocklyFieldRect"},this.fieldGroup_)}createTextElement_(){this.textElement_=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.TEXT,
{"class":"blocklyText blocklyFieldText"},this.fieldGroup_);this.getConstants().FIELD_TEXT_BASELINE_CENTER&&this.textElement_.setAttribute("dominant-baseline","central");this.textContent_=document.createTextNode("");this.textElement_.appendChild(this.textContent_)}bindEvents_(){const a=this.getClickTarget_();if(!a)throw Error("A click target has not been set.");bindMouseEvents$$module$build$src$core$tooltip(a);this.mouseDownWrapper=conditionalBind$$module$build$src$core$browser_events(a,"pointerdown",
this,this.onMouseDown_)}fromXml(a){this.setValue(a.textContent)}toXml(a){a.textContent=this.getValue();return a}saveState(a){a=this.saveLegacyState(Field$$module$build$src$core$field);return a!==null?a:this.getValue()}loadState(a){this.loadLegacyState(Field$$module$build$src$core$field,a)||this.setValue(a)}saveLegacyState(a){return a.prototype.saveState===this.saveState&&a.prototype.toXml!==this.toXml?(a=$.createElement$$module$build$src$core$utils$xml("field"),a.setAttribute("name",this.name||""),
domToText$$module$build$src$core$utils$xml(this.toXml(a)).replace(' xmlns="https://developers.google.com/blockly/xml"',"")):null}loadLegacyState(a,b){return a.prototype.loadState===this.loadState&&a.prototype.fromXml!==this.fromXml?(this.fromXml($.textToDom$$module$build$src$core$utils$xml(b)),!0):!1}dispose(){hideIfOwner$$module$build$src$core$dropdowndiv(this);hideIfOwner$$module$build$src$core$widgetdiv(this);let a;((a=this.getSourceBlock())==null?0:a.isDeadOrDying())||removeNode$$module$build$src$core$utils$dom(this.fieldGroup_);
this.disposed=!0}updateEditable(){const a=this.fieldGroup_,b=this.getSourceBlock();this.EDITABLE&&a&&b&&(this.enabled_&&b.isEditable()?(addClass$$module$build$src$core$utils$dom(a,"blocklyEditableField"),removeClass$$module$build$src$core$utils$dom(a,"blocklyNonEditableField")):(addClass$$module$build$src$core$utils$dom(a,"blocklyNonEditableField"),removeClass$$module$build$src$core$utils$dom(a,"blocklyEditableField")))}setEnabled(a){this.enabled_=a;this.updateEditable()}isEnabled(){return this.enabled_}isClickable(){return this.enabled_&&
!!this.sourceBlock_&&this.sourceBlock_.isEditable()&&this.showEditor_!==Field$$module$build$src$core$field.prototype.showEditor_}isClickableInFlyout(a){return!a}isCurrentlyEditable(){return this.enabled_&&this.EDITABLE&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()}isSerializable(){let a=!1;this.name&&(this.SERIALIZABLE?a=!0:this.EDITABLE&&(console.warn("Detected an editable field that was not serializable. Please define SERIALIZABLE property as true on all editable custom fields. Proceeding with serialization."),
a=!0));return a}isVisible(){return this.visible_}setVisible(a){if(this.visible_!==a){this.visible_=a;var b=this.fieldGroup_;b&&(b.style.display=a?"block":"none")}}setValidator(a){this.validator_=a}getValidator(){return this.validator_}getSvgRoot(){return this.fieldGroup_}getBorderRect(){if(!this.borderRect_)throw Error(`The border rectangle is ${this.borderRect_}.`);return this.borderRect_}getTextElement(){if(!this.textElement_)throw Error(`The text element is ${this.textElement_}.`);return this.textElement_}getTextContent(){if(!this.textContent_)throw Error(`The text content is ${this.textContent_}.`);
return this.textContent_}applyColour(){}render_(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_());this.updateSize_()}showEditor(a){this.isClickable()&&this.showEditor_(a)}showEditor_(a){}repositionForWindowResize(){return!1}updateSize_(a){const b=this.getConstants();a=a!==void 0?a:this.isFullBlockField()?0:this.getConstants().FIELD_BORDER_RECT_X_PADDING;let c=a*2,d=b.FIELD_TEXT_HEIGHT,e=0;this.textElement_&&(e=getTextWidth$$module$build$src$core$utils$dom(this.textElement_),
c+=e);this.isFullBlockField()||(d=Math.max(d,b.FIELD_BORDER_RECT_HEIGHT));this.size_=new Size$$module$build$src$core$utils$size(c,d);this.positionTextElement_(a,e);this.positionBorderRect_()}positionTextElement_(a,b){if(this.textElement_){var c=this.getConstants(),d=this.size_.height/2,e;this.textElement_.setAttribute("x",String(((e=this.getSourceBlock())==null?0:e.RTL)?this.size_.width-b-a:a));this.textElement_.setAttribute("y",String(c.FIELD_TEXT_BASELINE_CENTER?d:d-c.FIELD_TEXT_HEIGHT/2+c.FIELD_TEXT_BASELINE))}}positionBorderRect_(){this.borderRect_&&
(this.borderRect_.setAttribute("width",String(this.size_.width)),this.borderRect_.setAttribute("height",String(this.size_.height)),this.borderRect_.setAttribute("rx",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)),this.borderRect_.setAttribute("ry",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)))}getSize(){if(!this.isVisible())return new Size$$module$build$src$core$utils$size(0,0);this.isDirty_&&(this.render_(),this.isDirty_=!1);return this.size_}getScaledBBox(){let a;var b=this.getSourceBlock();
if(!b)throw new UnattachedFieldError$$module$build$src$core$field;if(this.isFullBlockField()){var c=this.sourceBlock_.getHeightWidth();const d=b.workspace.scale;a=this.getAbsoluteXY_();b=(c.width+1)*d;c=(c.height+1)*d;GECKO$$module$build$src$core$utils$useragent?(a.x+=1.5*d,a.y+=1.5*d):(a.x-=.5*d,a.y-=.5*d)}else c=this.borderRect_.getBoundingClientRect(),a=getPageOffset$$module$build$src$core$utils$style(this.borderRect_),b=c.width,c=c.height;return new Rect$$module$build$src$core$utils$rect(a.y,
a.y+c,a.x,a.x+b)}onLocationChange(a){}getDisplayText_(){let a=this.getText();a.length>this.maxDisplayLength&&(a=a.substring(0,this.maxDisplayLength-2)+"\u2026");a=a.replace(/\s/g,Field$$module$build$src$core$field.NBSP);this.sourceBlock_&&this.sourceBlock_.RTL&&(a+="\u200f");return a}getText(){const a=this.getText_();return a!==null?String(a):String(this.getValue())}getText_(){return null}markDirty(){this.isDirty_=!0;this.constants_=null}forceRerender(){this.isDirty_=!0;this.sourceBlock_&&this.sourceBlock_.rendered&&
this.sourceBlock_.queueRender()}setValue(a,b=!0){if(a!==null){var c=$.getGroup$$module$build$src$core$events$utils();c||$.setGroup$$module$build$src$core$events$utils(!0);try{const k=this.doClassValidation_(a),l=this.processValidation(a,k,b);if(!(l instanceof Error)){var d,e=(d=this.getValidator())==null?void 0:d.call(this,l),f=this.processValidation(l,e,b);if(!(f instanceof Error)){var g=this.sourceBlock_;if(!g||!g.disposed){var h=this.getValue();h===f?this.doValueUpdate_(f):(this.doValueUpdate_(f),
b&&g&&isEnabled$$module$build$src$core$events$utils()&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CHANGE))(g,"field",this.name||null,h,f)),this.isDirty_&&this.forceRerender())}}}}finally{$.setGroup$$module$build$src$core$events$utils(c)}}}processValidation(a,b,c){return b===null?(this.doValueInvalid_(a,c),this.isDirty_&&this.forceRerender(),Error()):b===void 0?a:b}getValue(){return this.value_}doClassValidation_(a){return a===
null||a===void 0?null:a}doValueUpdate_(a){this.value_=a;this.isDirty_=!0}doValueInvalid_(a,b){}onMouseDown_(a){this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&(a=this.sourceBlock_.workspace.getGesture(a))&&a.setStartField(this)}setTooltip(a){a||a===""||(a=this.sourceBlock_);const b=this.getClickTarget_();b?b.tooltip=a:this.tooltip=a}getTooltip(){const a=this.getClickTarget_();return a?getTooltipOfObject$$module$build$src$core$tooltip(a):getTooltipOfObject$$module$build$src$core$tooltip({tooltip:this.tooltip})}getClickTarget_(){return this.clickTarget_||
this.getSvgRoot()}getAbsoluteXY_(){return getPageOffset$$module$build$src$core$utils$style(this.getClickTarget_())}referencesVariables(){return!1}refreshVariableName(){}getParentInput(){let a=null;const b=this.getSourceBlock();if(!b)throw new UnattachedFieldError$$module$build$src$core$field;const c=b.inputList;for(let d=0;d<b.inputList.length;d++){const e=c[d],f=e.fieldRow;for(let g=0;g<f.length;g++)if(f[g]===this){a=e;break}}return a}getFlipRtl(){return!1}onShortcut(a){return!1}getFocusableElement(){if(!this.fieldGroup_)throw Error("This field currently has no representative DOM element.");
return this.fieldGroup_}getFocusableTree(){const a=this.getSourceBlock();if(!a)throw new UnattachedFieldError$$module$build$src$core$field;return a.workspace}onNodeFocus(){const a=this.getSourceBlock();a.workspace.scrollBoundsIntoView(a.getBoundingRectangleWithoutChildren())}onNodeBlur(){}canBeFocused(){return!0}static fromJson(a){throw Error("Attempted to instantiate a field from the registry that hasn't defined a 'fromJson' method.");}};Field$$module$build$src$core$field.NBSP="\u00a0";
Field$$module$build$src$core$field.SKIP_SETUP=Symbol("SKIP_SETUP");var UnattachedFieldError$$module$build$src$core$field=class extends Error{constructor(){super("The field has not yet been attached to its input. Call appendField to attach it.")}},module$build$src$core$field={};module$build$src$core$field.Field=Field$$module$build$src$core$field;module$build$src$core$field.UnattachedFieldError=UnattachedFieldError$$module$build$src$core$field;var owner$$module$build$src$core$widgetdiv=null,ownerWorkspace$$module$build$src$core$widgetdiv=null,dispose$$module$build$src$core$widgetdiv=null,containerClassName$$module$build$src$core$widgetdiv="blocklyWidgetDiv",rendererClassName$$module$build$src$core$widgetdiv="",themeClassName$$module$build$src$core$widgetdiv="",containerDiv$$module$build$src$core$widgetdiv,returnEphemeralFocus$$module$build$src$core$widgetdiv=null,module$build$src$core$widgetdiv={};
module$build$src$core$widgetdiv.createDom=createDom$$module$build$src$core$widgetdiv;module$build$src$core$widgetdiv.getDiv=getDiv$$module$build$src$core$widgetdiv;module$build$src$core$widgetdiv.hide=hide$$module$build$src$core$widgetdiv;module$build$src$core$widgetdiv.hideIfOwner=hideIfOwner$$module$build$src$core$widgetdiv;module$build$src$core$widgetdiv.hideIfOwnerIsInWorkspace=hideIfOwnerIsInWorkspace$$module$build$src$core$widgetdiv;module$build$src$core$widgetdiv.isVisible=isVisible$$module$build$src$core$widgetdiv;
module$build$src$core$widgetdiv.positionWithAnchor=positionWithAnchor$$module$build$src$core$widgetdiv;module$build$src$core$widgetdiv.repositionForWindowResize=repositionForWindowResize$$module$build$src$core$widgetdiv;module$build$src$core$widgetdiv.show=show$$module$build$src$core$widgetdiv;module$build$src$core$widgetdiv.testOnly_setDiv=testOnly_setDiv$$module$build$src$core$widgetdiv;var currentBlock$$module$build$src$core$contextmenu=null,dummyOwner$$module$build$src$core$contextmenu={},menu_$$module$build$src$core$contextmenu=null,module$build$src$core$contextmenu={};module$build$src$core$contextmenu.callbackFactory=$.callbackFactory$$module$build$src$core$contextmenu;module$build$src$core$contextmenu.dispose=dispose$$module$build$src$core$contextmenu;module$build$src$core$contextmenu.getCurrentBlock=getCurrentBlock$$module$build$src$core$contextmenu;
module$build$src$core$contextmenu.hide=hide$$module$build$src$core$contextmenu;module$build$src$core$contextmenu.setCurrentBlock=setCurrentBlock$$module$build$src$core$contextmenu;module$build$src$core$contextmenu.show=show$$module$build$src$core$contextmenu;var ContextMenuRegistry$$module$build$src$core$contextmenu_registry=class{constructor(){this.registeredItems=new Map;this.reset()}reset(){this.registeredItems.clear()}register(a){if(this.registeredItems.has(a.id))throw Error('Menu item with ID "'+a.id+'" is already registered.');this.registeredItems.set(a.id,a)}unregister(a){if(!this.registeredItems.has(a))throw Error('Menu item with ID "'+a+'" not found.');this.registeredItems.delete(a)}getItem(a){let b;return(b=this.registeredItems.get(a))!=null?
b:null}getContextMenuOptions(a,b){const c=[];for(const d of this.registeredItems.values()){if(d.scopeType){if(d.scopeType===ScopeType$$module$build$src$core$contextmenu_registry.BLOCK&&!a.block)continue;if(d.scopeType===ScopeType$$module$build$src$core$contextmenu_registry.COMMENT&&!a.comment)continue;if(d.scopeType===ScopeType$$module$build$src$core$contextmenu_registry.WORKSPACE&&!a.workspace)continue}let e;e={scope:a,weight:d.weight};if(d.separator)e=Object.assign({},e,{separator:!0});else{const f=
d.preconditionFn(a,b);if(f==="hidden")continue;const g=typeof d.displayText==="function"?d.displayText(a):d.displayText;e=Object.assign({},e,{text:g,callback:d.callback,enabled:f==="enabled"})}c.push(e)}c.sort(function(d,e){return d.weight-e.weight});return c}};
(function(a){var b=a.ScopeType||(a.ScopeType={});b.BLOCK="block";b.WORKSPACE="workspace";b.COMMENT="comment";a.registry=new a})(ContextMenuRegistry$$module$build$src$core$contextmenu_registry||(ContextMenuRegistry$$module$build$src$core$contextmenu_registry={}));var ScopeType$$module$build$src$core$contextmenu_registry=ContextMenuRegistry$$module$build$src$core$contextmenu_registry.ScopeType,module$build$src$core$contextmenu_registry={};
module$build$src$core$contextmenu_registry.ContextMenuRegistry=ContextMenuRegistry$$module$build$src$core$contextmenu_registry;module$build$src$core$contextmenu_registry.ScopeType=ScopeType$$module$build$src$core$contextmenu_registry;var BLOCK$$module$build$src$core$layers=50,BUBBLE$$module$build$src$core$layers=100,module$build$src$core$layers={BLOCK:BLOCK$$module$build$src$core$layers,BUBBLE:BUBBLE$$module$build$src$core$layers};var CommentDragStrategy$$module$build$src$core$dragging$comment_drag_strategy=class{constructor(a){this.comment=a;this.startLoc=null;this.workspace=a.workspace}isMovable(){return this.comment.isOwnMovable()&&!this.comment.isDeadOrDying()&&!this.workspace.isReadOnly()}startDrag(){this.fireDragStartEvent();this.startLoc=this.comment.getRelativeToSurfaceXY();this.workspace.setResizesEnabled(!1);let a;(a=this.workspace.getLayerManager())==null||a.moveToDragLayer(this.comment);this.comment.setDragging(!0)}drag(a){this.comment.moveDuringDrag(a)}endDrag(){this.fireDragEndEvent();
this.fireMoveEvent();let a;(a=this.workspace.getLayerManager())==null||a.moveOffDragLayer(this.comment,BLOCK$$module$build$src$core$layers);this.comment.setDragging(!1);this.comment.snapToGrid();this.workspace.setResizesEnabled(!0)}fireDragStartEvent(){const a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.COMMENT_DRAG))(this.comment,!0);fire$$module$build$src$core$events$utils(a)}fireDragEndEvent(){const a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.COMMENT_DRAG))(this.comment,
!1);fire$$module$build$src$core$events$utils(a)}fireMoveEvent(){if(!this.comment.isDeadOrDying()){var a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.COMMENT_MOVE))(this.comment);a.setReason(["drag"]);a.oldCoordinate_=this.startLoc;a.recordNew();fire$$module$build$src$core$events$utils(a)}}revertDrag(){this.startLoc&&this.comment.moveDuringDrag(this.startLoc)}},module$build$src$core$dragging$comment_drag_strategy={};
module$build$src$core$dragging$comment_drag_strategy.CommentDragStrategy=CommentDragStrategy$$module$build$src$core$dragging$comment_drag_strategy;var workspaceToDragDelta$$module$build$src$core$utils$drag=new WeakMap,module$build$src$core$utils$drag={};module$build$src$core$utils$drag.move=move$$module$build$src$core$utils$drag;module$build$src$core$utils$drag.start=start$$module$build$src$core$utils$drag;var CommentBarButton$$module$build$src$core$comments$comment_bar_button=class{constructor(a,b,c,d){this.id=a;this.workspace=b;this.container=c;this.commentView=d}isVisible(){return this.icon.checkVisibility()}getCommentView(){return this.commentView}getSize(a=!1){var b=this.icon.getBBox();b=Rect$$module$build$src$core$utils$rect.from(b);a&&(a=this.getMargin(),b.left-=a,b.top-=a,b.bottom+=a,b.right+=a);return b}getMargin(){return(this.container.getBBox().height-this.icon.getBBox().height)/2}getFocusableElement(){return this.icon}getFocusableTree(){return this.workspace}onNodeFocus(){const a=
this.getCommentView();var b=a.getRelativeToSurfaceXY();const c=a.getSize();b=new Rect$$module$build$src$core$utils$rect(b.y,b.y+c.height,b.x,b.x+c.width);a.workspace.scrollBoundsIntoView(b)}onNodeBlur(){}canBeFocused(){return this.isVisible()}},module$build$src$core$comments$comment_bar_button={};module$build$src$core$comments$comment_bar_button.CommentBarButton=CommentBarButton$$module$build$src$core$comments$comment_bar_button;var COMMENT_COLLAPSE_BAR_BUTTON_FOCUS_IDENTIFIER$$module$build$src$core$comments$collapse_comment_bar_button="_collapse_bar_button",CollapseCommentBarButton$$module$build$src$core$comments$collapse_comment_bar_button=class extends CommentBarButton$$module$build$src$core$comments$comment_bar_button{constructor(a,b,c,d){super(a,b,c,d);this.id=a;this.workspace=b;this.container=c;this.commentView=d;this.icon=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,
{"class":"blocklyFoldoutIcon",href:`${this.workspace.options.pathToMedia}foldout-icon.svg`,id:`${this.id}${COMMENT_COLLAPSE_BAR_BUTTON_FOCUS_IDENTIFIER$$module$build$src$core$comments$collapse_comment_bar_button}`},this.container);this.bindId=conditionalBind$$module$build$src$core$browser_events(this.icon,"pointerdown",this,this.performAction.bind(this))}dispose(){unbind$$module$build$src$core$browser_events(this.bindId)}reposition(){const a=this.getMargin();this.icon.setAttribute("y",`${a}`);this.icon.setAttribute("x",
`${a}`)}performAction(a){clearTouchIdentifier$$module$build$src$core$touch();this.getCommentView().bringToFront();a&&a instanceof PointerEvent&&isRightButton$$module$build$src$core$browser_events(a)?a.stopPropagation():(this.getCommentView().setCollapsed(!this.getCommentView().isCollapsed()),this.workspace.hideChaff(),a==null||a.stopPropagation())}},module$build$src$core$comments$collapse_comment_bar_button={COMMENT_COLLAPSE_BAR_BUTTON_FOCUS_IDENTIFIER:COMMENT_COLLAPSE_BAR_BUTTON_FOCUS_IDENTIFIER$$module$build$src$core$comments$collapse_comment_bar_button};
module$build$src$core$comments$collapse_comment_bar_button.CollapseCommentBarButton=CollapseCommentBarButton$$module$build$src$core$comments$collapse_comment_bar_button;var COMMENT_EDITOR_FOCUS_IDENTIFIER$$module$build$src$core$comments$comment_editor="_comment_textarea_",CommentEditor$$module$build$src$core$comments$comment_editor=class{constructor(a,b,c){this.workspace=a;this.onFinishEditing=c;this.textChangeListeners=[];this.text="";this.foreignObject=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FOREIGNOBJECT,{"class":"blocklyCommentForeignObject"});a=document.createElementNS(HTML_NS$$module$build$src$core$utils$dom,"body");
a.setAttribute("xmlns",HTML_NS$$module$build$src$core$utils$dom);a.className="blocklyMinimalBody";this.textArea=document.createElementNS(HTML_NS$$module$build$src$core$utils$dom,"textarea");this.textArea.setAttribute("tabindex","-1");this.textArea.setAttribute("dir",this.workspace.RTL?"RTL":"LTR");addClass$$module$build$src$core$utils$dom(this.textArea,"blocklyCommentText");addClass$$module$build$src$core$utils$dom(this.textArea,"blocklyTextarea");addClass$$module$build$src$core$utils$dom(this.textArea,
"blocklyText");a.appendChild(this.textArea);this.foreignObject.appendChild(a);b&&(this.id=b+COMMENT_EDITOR_FOCUS_IDENTIFIER$$module$build$src$core$comments$comment_editor,this.textArea.setAttribute("id",this.id));conditionalBind$$module$build$src$core$browser_events(this.textArea,"change",this,this.onTextChange);conditionalBind$$module$build$src$core$browser_events(this.textArea,"pointerdown",this,d=>{d.stopPropagation();$.getFocusManager$$module$build$src$core$focus_manager().focusNode(this);clearTouchIdentifier$$module$build$src$core$touch()});
conditionalBind$$module$build$src$core$browser_events(this.textArea,"wheel",this,d=>{d.stopPropagation()});conditionalBind$$module$build$src$core$browser_events(this.textArea,"keydown",this,this.handleKeyDown)}getDom(){return this.foreignObject}getText(){return this.text}setText(a){this.textArea.value=a;this.onTextChange()}onTextChange(){const a=this.text;this.text=this.textArea.value;for(let b=this.textChangeListeners.length-1;b>=0;b--)this.textChangeListeners[b](a,this.text)}handleKeyDown(a){if(a.key===
"Escape"||a.key==="Enter"&&(a.ctrlKey||a.metaKey)){if(this.onFinishEditing)this.onFinishEditing();a.stopPropagation()}}addTextChangeListener(a){this.textChangeListeners.push(a)}removeTextChangeListener(a){this.textChangeListeners.splice(this.textChangeListeners.indexOf(a),1)}setPlaceholderText(a){this.textArea.placeholder=a}setEditable(a){a?this.textArea.removeAttribute("readonly"):this.textArea.setAttribute("readonly","true")}updateSize(a,b){this.foreignObject.setAttribute("height",`${a.height-b.height}`);
this.foreignObject.setAttribute("width",`${a.width}`);this.foreignObject.setAttribute("y",`${b.height}`);this.workspace.RTL&&this.foreignObject.setAttribute("x",`${-a.width}`)}getFocusableElement(){return this.textArea}getFocusableTree(){return this.workspace}onNodeFocus(){const a=Rect$$module$build$src$core$utils$rect.from(this.foreignObject.getBoundingClientRect());this.workspace.scrollBoundsIntoView(Rect$$module$build$src$core$utils$rect.createFromPoint(screenToWsCoordinates$$module$build$src$core$utils$svg_math(this.workspace,
a.getOrigin()),a.getWidth(),a.getHeight()))}onNodeBlur(){}canBeFocused(){return this.id?!0:!1}},module$build$src$core$comments$comment_editor={COMMENT_EDITOR_FOCUS_IDENTIFIER:COMMENT_EDITOR_FOCUS_IDENTIFIER$$module$build$src$core$comments$comment_editor};module$build$src$core$comments$comment_editor.CommentEditor=CommentEditor$$module$build$src$core$comments$comment_editor;var COMMENT_DELETE_BAR_BUTTON_FOCUS_IDENTIFIER$$module$build$src$core$comments$delete_comment_bar_button="_delete_bar_button",DeleteCommentBarButton$$module$build$src$core$comments$delete_comment_bar_button=class extends CommentBarButton$$module$build$src$core$comments$comment_bar_button{constructor(a,b,c,d){super(a,b,c,d);this.id=a;this.workspace=b;this.container=c;this.commentView=d;this.icon=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,{"class":"blocklyDeleteIcon",
href:`${this.workspace.options.pathToMedia}delete-icon.svg`,id:`${this.id}${COMMENT_DELETE_BAR_BUTTON_FOCUS_IDENTIFIER$$module$build$src$core$comments$delete_comment_bar_button}`},c);this.bindId=conditionalBind$$module$build$src$core$browser_events(this.icon,"pointerdown",this,this.performAction.bind(this))}dispose(){unbind$$module$build$src$core$browser_events(this.bindId)}reposition(){const a=this.getMargin();this.icon.setAttribute("x","0");const b=this.container.getBBox();this.icon.setAttribute("y",
`${a}`);this.icon.setAttribute("x",`${b.width-this.getSize(!0).getWidth()}`)}performAction(a){clearTouchIdentifier$$module$build$src$core$touch();a&&a instanceof PointerEvent&&isRightButton$$module$build$src$core$browser_events(a)?a.stopPropagation():(this.getCommentView().dispose(),a==null||a.stopPropagation(),$.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.workspace))}},module$build$src$core$comments$delete_comment_bar_button={COMMENT_DELETE_BAR_BUTTON_FOCUS_IDENTIFIER:COMMENT_DELETE_BAR_BUTTON_FOCUS_IDENTIFIER$$module$build$src$core$comments$delete_comment_bar_button};
module$build$src$core$comments$delete_comment_bar_button.DeleteCommentBarButton=DeleteCommentBarButton$$module$build$src$core$comments$delete_comment_bar_button;var CommentView$$module$build$src$core$comments$comment_view=class{constructor(a,b){this.workspace=a;this.commentId=b;this.collapsed=!1;this.editable=!0;this.location=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.sizeChangeListeners=[];this.disposeListeners=[];this.collapseChangeListeners=[];this.resizePointerMoveListener=this.resizePointerUpListener=null;this.disposed=this.disposing=!1;this.svgRoot=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,
{"class":"blocklyComment blocklyEditable blocklyDraggable"});this.highlightRect=this.createHighlightRect(this.svgRoot);({topBarGroup:this.topBarGroup,topBarBackground:this.topBarBackground,deleteButton:this.deleteButton,foldoutButton:this.foldoutButton,textPreview:this.textPreview,textPreviewNode:this.textPreviewNode}=this.createTopBar(this.svgRoot));this.commentEditor=this.createTextArea();this.resizeHandle=this.createResizeHandle(this.svgRoot,a);let c;(c=a.getLayerManager())==null||c.append(this,
BLOCK$$module$build$src$core$layers);this.size=CommentView$$module$build$src$core$comments$comment_view.defaultCommentSize;this.setSizeWithoutFiringEvents(this.size);this.moveTo(new Coordinate$$module$build$src$core$utils$coordinate(0,0))}createHighlightRect(a){return createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{"class":"blocklyCommentHighlight"},a)}createTopBar(a){a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,
{"class":"blocklyCommentTopbar"},a);const b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{"class":"blocklyCommentTopbarBackground"},a),c=new DeleteCommentBarButton$$module$build$src$core$comments$delete_comment_bar_button(this.commentId,this.workspace,a,this),d=new CollapseCommentBarButton$$module$build$src$core$comments$collapse_comment_bar_button(this.commentId,this.workspace,a,this);this.addDisposeListener(()=>{c.dispose();d.dispose()});const e=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.TEXT,
{"class":"blocklyCommentPreview blocklyCommentText blocklyText"},a),f=document.createTextNode("");e.appendChild(f);return{topBarGroup:a,topBarBackground:b,deleteButton:c,foldoutButton:d,textPreview:e,textPreviewNode:f}}createTextArea(){const a=new CommentEditor$$module$build$src$core$comments$comment_editor(this.workspace,this.commentId,()=>this.svgRoot.focus());this.svgRoot.appendChild(a.getDom());a.addTextChangeListener((b,c)=>{this.updateTextPreview(c);this.setSize(this.size)});return a}getEditorFocusableNode(){return this.commentEditor}createResizeHandle(a,
b){a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,{"class":"blocklyResizeHandle",href:`${b.options.pathToMedia}resize-handle.svg`},a);conditionalBind$$module$build$src$core$browser_events(a,"pointerdown",this,this.onResizePointerDown);return a}getSvgRoot(){return this.svgRoot}getSize(){return this.collapsed?this.topBarBackground.getBBox():this.size}setSizeWithoutFiringEvents(a){const b=this.topBarBackground.getBBox(),c=this.textPreview.getBBox(),d=this.resizeHandle.getBBox();
this.size=a=Size$$module$build$src$core$utils$size.max(a,this.calcMinSize(b));this.svgRoot.setAttribute("height",`${a.height}`);this.svgRoot.setAttribute("width",`${a.width}`);this.updateHighlightRect(a);this.updateTopBarSize(a);this.commentEditor.updateSize(a,b);this.deleteButton.reposition();this.foldoutButton.reposition();this.updateTextPreviewSize(a,b,c);this.updateResizeHandlePosition(a,d)}setSize(a){const b=this.preResizeSize||this.size;this.setSizeWithoutFiringEvents(a);this.onSizeChange(b,
this.size)}calcMinSize(a){var b;this.updateTextPreview((b=this.commentEditor.getText())!=null?b:"");let c=b=getTextWidth$$module$build$src$core$utils$dom(this.textPreview);this.foldoutButton.isVisible()?c+=this.foldoutButton.getSize(!0).getWidth():b&&(c+=4);this.deleteButton.isVisible()?c+=this.deleteButton.getSize(!0).getWidth():b&&(c+=4);return new Size$$module$build$src$core$utils$size(c,a.height+20)}updateHighlightRect(a){this.highlightRect.setAttribute("height",`${a.height}`);this.highlightRect.setAttribute("width",
`${a.width}`);this.workspace.RTL&&this.highlightRect.setAttribute("x",`${-a.width}`)}updateTopBarSize(a){this.topBarBackground.setAttribute("width",`${a.width}`)}updateTextPreviewSize(a,b,c){b=(b.height-c.height)/2;const d=this.foldoutButton.getSize(!0),e=this.deleteButton.getSize(!0);a=a.width-d.getWidth()-e.getWidth();this.textPreview.setAttribute("x",`${(this.workspace.RTL?-1:1)*d.getWidth()}`);this.textPreview.setAttribute("y",`${b+c.height/2}`);this.textPreview.setAttribute("width",`${a}`)}updateResizeHandlePosition(a,
b){this.resizeHandle.setAttribute("y",`${a.height-b.height}`);this.resizeHandle.setAttribute("x",`${a.width-b.width}`)}onSizeChange(a,b){for(let c=this.sizeChangeListeners.length-1;c>=0;c--)this.sizeChangeListeners[c](a,b)}addSizeChangeListener(a){this.sizeChangeListeners.push(a)}removeSizeChangeListener(a){this.sizeChangeListeners.splice(this.sizeChangeListeners.indexOf(a),1)}onResizePointerDown(a){this.isEditable()&&(this.bringToFront(),isRightButton$$module$build$src$core$browser_events(a)||(this.preResizeSize=
this.getSize(),start$$module$build$src$core$utils$drag(this.workspace,a,new Coordinate$$module$build$src$core$utils$coordinate(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=conditionalBind$$module$build$src$core$browser_events(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=conditionalBind$$module$build$src$core$browser_events(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),
a.stopPropagation())}onResizePointerUp(a){clearTouchIdentifier$$module$build$src$core$touch();this.resizePointerUpListener&&(unbind$$module$build$src$core$browser_events(this.resizePointerUpListener),this.resizePointerUpListener=null);this.resizePointerMoveListener&&(unbind$$module$build$src$core$browser_events(this.resizePointerMoveListener),this.resizePointerMoveListener=null);this.setSize(this.size);this.preResizeSize=void 0}onResizePointerMove(a){a=move$$module$build$src$core$utils$drag(this.workspace,
a);this.setSizeWithoutFiringEvents(new Size$$module$build$src$core$utils$size(this.workspace.RTL?-a.x:a.x,a.y))}isCollapsed(){return this.collapsed}setCollapsed(a){(this.collapsed=a)?addClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyCollapsed"):removeClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyCollapsed");this.setSizeWithoutFiringEvents(this.size);this.onCollapse()}onCollapse(){for(let a=this.collapseChangeListeners.length-1;a>=0;a--)this.collapseChangeListeners[a](this.collapsed)}addOnCollapseListener(a){this.collapseChangeListeners.push(a)}removeOnCollapseListener(a){this.collapseChangeListeners.splice(this.collapseChangeListeners.indexOf(a),
1)}isEditable(){return this.editable}setEditable(a){(this.editable=a)?(addClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyEditable"),removeClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyReadonly")):(removeClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyEditable"),addClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyReadonly"));this.commentEditor.setEditable(a)}getRelativeToSurfaceXY(){return this.location}moveTo(a){this.location=a;this.svgRoot.setAttribute("transform",
`translate(${a.x}, ${a.y})`)}getText(){return this.commentEditor.getText()}setText(a){this.commentEditor.setText(a)}setPlaceholderText(a){this.commentEditor.setPlaceholderText(a)}addTextChangeListener(a){this.commentEditor.addTextChangeListener(a)}removeTextChangeListener(a){this.commentEditor.removeTextChangeListener(a)}updateTextPreview(a){this.textPreviewNode.textContent=this.truncateText(a)}truncateText(a){return a.length>=12?`${a.substring(0,9)}...`:a}bringToFront(){const a=this.svgRoot.parentNode,
b=a.childNodes;b[b.length-1]!==this.svgRoot&&a.appendChild(this.svgRoot)}onDeleteDown(a){clearTouchIdentifier$$module$build$src$core$touch();isRightButton$$module$build$src$core$browser_events(a)||this.dispose();a.stopPropagation()}dispose(){this.disposing=!0;removeNode$$module$build$src$core$utils$dom(this.svgRoot);for(let a=this.disposeListeners.length-1;a>=0;a--)this.disposeListeners[a]();this.disposeListeners.length=0;this.disposed=!0}isDisposed(){return this.disposed}isDeadOrDying(){return this.disposing||
this.disposed}addDisposeListener(a){this.disposeListeners.push(a)}removeDisposeListener(a){this.disposeListeners.splice(this.disposeListeners.indexOf(a),1)}getCommentBarButtons(){return[this.foldoutButton,this.deleteButton]}};CommentView$$module$build$src$core$comments$comment_view.defaultCommentSize=new Size$$module$build$src$core$utils$size(120,100);register$$module$build$src$core$css("\n.injectionDiv {\n  --commentFillColour: #FFFCC7;\n  --commentBorderColour: #F2E49B;\n}\n\n.blocklyComment .blocklyTextarea {\n  background-color: var(--commentFillColour);\n  border: 1px solid var(--commentBorderColour);\n  box-sizing: border-box;\n  display: block;\n  outline: 0;\n  padding: 5px;\n  resize: none;\n  width: 100%;\n  height: 100%;\n}\n\n.blocklyReadonly.blocklyComment .blocklyTextarea {\n  cursor: inherit;\n}\n\n.blocklyDeleteIcon {\n  width: 20px;\n  height: 20px;\n  display: none;\n  cursor: pointer;\n}\n\n.blocklyFoldoutIcon {\n  width: 20px;\n  height: 20px;\n  transform-origin: 12px 12px;\n  cursor: pointer;\n}\n.blocklyResizeHandle {\n  width: 12px;\n  height: 12px;\n  cursor: se-resize;\n}\n.blocklyReadonly.blocklyComment .blocklyResizeHandle {\n  cursor: inherit;\n}\n\n.blocklyCommentTopbarBackground {\n  fill: var(--commentBorderColour);\n  height: 24px;\n}\n\n.blocklyComment .blocklyCommentPreview.blocklyText {\n  fill: #000;\n  dominant-baseline: middle;\n  visibility: hidden;\n}\n\n.blocklyCollapsed.blocklyComment .blocklyCommentPreview {\n  visibility: visible;\n}\n\n.blocklyCollapsed.blocklyComment .blocklyCommentForeignObject,\n.blocklyCollapsed.blocklyComment .blocklyResizeHandle {\n  display: none;\n}\n\n.blocklyCollapsed.blocklyComment .blocklyFoldoutIcon {\n  transform: rotate(-90deg);\n}\n\n.blocklyRTL .blocklyCommentTopbar {\n  transform: scale(-1, 1);\n}\n\n.blocklyRTL .blocklyCommentForeignObject {\n  direction: rtl;\n}\n\n.blocklyRTL .blocklyCommentPreview {\n  /* Revert the scale and control RTL using direction instead. */\n  transform: scale(-1, 1);\n  direction: rtl;\n}\n\n.blocklyRTL .blocklyResizeHandle {\n  transform: scale(-1, 1);\n  cursor: sw-resize;\n}\n\n.blocklyCommentHighlight {\n  fill: none;\n}\n\n.blocklyCommentText.blocklyActiveFocus {\n  border-color: #fc3;\n  border-width: 2px;\n}\n\n.blocklySelected .blocklyCommentHighlight {\n  stroke: #fc3;\n  stroke-width: 3px;\n}\n\n.blocklyCollapsed.blocklySelected .blocklyCommentHighlight {\n  stroke: none;\n}\n\n.blocklyCollapsed.blocklySelected .blocklyCommentTopbarBackground {\n  stroke: #fc3;\n  stroke-width: 3px;\n}\n");
var module$build$src$core$comments$comment_view={};module$build$src$core$comments$comment_view.CommentView=CommentView$$module$build$src$core$comments$comment_view;var WorkspaceComment$$module$build$src$core$comments$workspace_comment=class{constructor(a,b){this.workspace=a;this.text="";this.collapsed=!1;this.deletable=this.movable=this.editable=!0;this.location=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.disposing=this.disposed=!1;this.id=b&&!a.getCommentById(b)?b:genUid$$module$build$src$core$utils$idgenerator();this.size=CommentView$$module$build$src$core$comments$comment_view.defaultCommentSize;a.addTopComment(this);this.fireCreateEvent()}fireCreateEvent(){isEnabled$$module$build$src$core$events$utils()&&
fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.COMMENT_CREATE))(this))}fireDeleteEvent(){isEnabled$$module$build$src$core$events$utils()&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.COMMENT_DELETE))(this))}fireChangeEvent(a,b){isEnabled$$module$build$src$core$events$utils()&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.COMMENT_CHANGE))(this,
a,b))}fireCollapseEvent(a){isEnabled$$module$build$src$core$events$utils()&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.COMMENT_COLLAPSE))(this,a))}setText(a){const b=this.text;this.text=a;this.fireChangeEvent(b,a)}getText(){return this.text}setSize(a){const b=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.COMMENT_RESIZE))(this);this.size=a;b.recordCurrentSizeAsNewSize();
fire$$module$build$src$core$events$utils(b)}getSize(){return this.size}setCollapsed(a){this.collapsed=a;this.fireCollapseEvent(a)}isCollapsed(){return this.collapsed}setEditable(a){this.editable=a}isEditable(){return this.isOwnEditable()&&!this.workspace.isReadOnly()}isOwnEditable(){return this.editable}setMovable(a){this.movable=a}isMovable(){return this.isOwnMovable()&&!this.workspace.isReadOnly()&&!this.workspace.isFlyout}isOwnMovable(){return this.movable}setDeletable(a){this.deletable=a}isDeletable(){return this.isOwnDeletable()&&
!this.isDeadOrDying()&&!this.workspace.isReadOnly()&&!this.workspace.isFlyout}isOwnDeletable(){return this.deletable}moveTo(a,b){const c=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.COMMENT_MOVE))(this);b&&c.setReason(b);this.location=a;c.recordNew();fire$$module$build$src$core$events$utils(c)}getRelativeToSurfaceXY(){return this.location}dispose(){this.disposing=!0;this.fireDeleteEvent();this.workspace.removeTopComment(this);this.disposed=!0}isDisposed(){return this.disposed}isDeadOrDying(){return this.disposing||
this.disposed}},module$build$src$core$comments$workspace_comment={};module$build$src$core$comments$workspace_comment.WorkspaceComment=WorkspaceComment$$module$build$src$core$comments$workspace_comment;var RenderedWorkspaceComment$$module$build$src$core$comments$rendered_workspace_comment=class extends WorkspaceComment$$module$build$src$core$comments$workspace_comment{constructor(a,b){super(a,b);this.dragStrategy=new CommentDragStrategy$$module$build$src$core$dragging$comment_drag_strategy(this);this.workspace=a;this.view=new CommentView$$module$build$src$core$comments$comment_view(a,this.id);this.view.setSize(this.getSize());this.view.setEditable(this.isEditable());this.view.getSvgRoot().setAttribute("data-id",
this.id);this.view.getSvgRoot().setAttribute("id",this.id);this.addModelUpdateBindings();conditionalBind$$module$build$src$core$browser_events(this.view.getSvgRoot(),"pointerdown",this,this.startGesture)}addModelUpdateBindings(){this.view.addTextChangeListener((a,b)=>void super.setText(b));this.view.addSizeChangeListener((a,b)=>void super.setSize(b));this.view.addOnCollapseListener(()=>void super.setCollapsed(this.view.isCollapsed()));this.view.addDisposeListener(()=>{this.isDeadOrDying()||this.dispose()})}setText(a){this.view.setText(a)}setPlaceholderText(a){this.view.setPlaceholderText(a)}setSize(a){this.view.setSize(a)}setCollapsed(a){this.view.setCollapsed(a)}setEditable(a){super.setEditable(a);
this.view.setEditable(this.isEditable())}getSvgRoot(){return this.view.getSvgRoot()}getSize(){return super.getSize()}getBoundingRectangle(){const a=this.getRelativeToSurfaceXY();var b,c;const d=(c=(b=this.view)==null?void 0:b.getSize())!=null?c:this.getSize();this.workspace.RTL?(b=a.x-d.width,c=a.x):(b=a.x,c=a.x+d.width);return new Rect$$module$build$src$core$utils$rect(a.y,a.y+d.height,b,c)}moveBy(a,b,c){const d=this.getRelativeToSurfaceXY();a=new Coordinate$$module$build$src$core$utils$coordinate(d.x+
a,d.y+b);this.moveTo(a,c)}moveTo(a,b){super.moveTo(a,b);this.view.moveTo(a)}moveDuringDrag(a){this.location=a;this.view.moveTo(a)}setDragging(a){a?addClass$$module$build$src$core$utils$dom(this.getSvgRoot(),"blocklyDragging"):removeClass$$module$build$src$core$utils$dom(this.getSvgRoot(),"blocklyDragging")}dispose(){this.disposing=!0;const a=$.getFocusManager$$module$build$src$core$focus_manager();a.getFocusedNode()===this&&setTimeout(()=>a.focusTree(this.workspace),0);this.view.isDeadOrDying()||
this.view.dispose();super.dispose()}startGesture(a){const b=this.workspace.getGesture(a);b&&(b.handleCommentStart(a,this),$.getFocusManager$$module$build$src$core$focus_manager().focusNode(this))}setDeleteStyle(a){a?addClass$$module$build$src$core$utils$dom(this.getSvgRoot(),"blocklyDraggingDelete"):removeClass$$module$build$src$core$utils$dom(this.getSvgRoot(),"blocklyDraggingDelete")}isCopyable(){return this.isOwnMovable()&&this.isOwnDeletable()}isMovable(){return this.dragStrategy.isMovable()}startDrag(){this.dragStrategy.startDrag()}drag(a){this.dragStrategy.drag(a)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){addClass$$module$build$src$core$utils$dom(this.getSvgRoot(),
"blocklySelected");fireSelectedEvent$$module$build$src$core$common(this)}unselect(){removeClass$$module$build$src$core$utils$dom(this.getSvgRoot(),"blocklySelected");fireSelectedEvent$$module$build$src$core$common(null)}toCopyData(){return{paster:WorkspaceCommentPaster$$module$build$src$core$clipboard$workspace_comment_paster.TYPE,commentState:save$$module$build$src$core$serialization$workspace_comments(this,{addCoordinates:!0,saveIds:!1})}}showContextMenu(a){const b=ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.getContextMenuOptions({comment:this,
focusedNode:this},a);let c;c=a instanceof PointerEvent?new Coordinate$$module$build$src$core$utils$coordinate(a.clientX,a.clientY):wsToScreenCoordinates$$module$build$src$core$utils$svg_math(this.workspace,this.getRelativeToSurfaceXY()).translate(10,10);show$$module$build$src$core$contextmenu(a,b,this.workspace.RTL,this.workspace,c)}snapToGrid(){if(!this.isDeadOrDying()){var a=this.workspace.getGrid();if(a!=null&&a.shouldSnap()){var b=this.getRelativeToSurfaceXY();a=a.alignXY(b);a!==b&&this.moveTo(a,
["snap"])}}}getEditorFocusableNode(){return this.view.getEditorFocusableNode()}getFocusableElement(){return this.getSvgRoot()}getFocusableTree(){return this.workspace}onNodeFocus(){this.select();let a;(a=this.workspace.getLayerManager())==null||a.append(this,BLOCK$$module$build$src$core$layers);this.workspace.scrollBoundsIntoView(this.getBoundingRectangle())}onNodeBlur(){this.unselect()}canBeFocused(){return!0}},module$build$src$core$comments$rendered_workspace_comment={};
module$build$src$core$comments$rendered_workspace_comment.RenderedWorkspaceComment=RenderedWorkspaceComment$$module$build$src$core$comments$rendered_workspace_comment;var module$build$src$core$xml={};module$build$src$core$xml.appendDomToWorkspace=appendDomToWorkspace$$module$build$src$core$xml;module$build$src$core$xml.blockToDom=blockToDom$$module$build$src$core$xml;module$build$src$core$xml.blockToDomWithXY=blockToDomWithXY$$module$build$src$core$xml;module$build$src$core$xml.clearWorkspaceAndLoadFromXml=clearWorkspaceAndLoadFromXml$$module$build$src$core$xml;module$build$src$core$xml.deleteNext=deleteNext$$module$build$src$core$xml;
module$build$src$core$xml.domToBlock=$.domToBlock$$module$build$src$core$xml;module$build$src$core$xml.domToBlockInternal=domToBlockInternal$$module$build$src$core$xml;module$build$src$core$xml.domToPrettyText=domToPrettyText$$module$build$src$core$xml;module$build$src$core$xml.domToText=domToText$$module$build$src$core$xml;module$build$src$core$xml.domToVariables=domToVariables$$module$build$src$core$xml;module$build$src$core$xml.domToWorkspace=$.domToWorkspace$$module$build$src$core$xml;
module$build$src$core$xml.loadWorkspaceComment=loadWorkspaceComment$$module$build$src$core$xml;module$build$src$core$xml.saveWorkspaceComment=saveWorkspaceComment$$module$build$src$core$xml;module$build$src$core$xml.variablesToDom=variablesToDom$$module$build$src$core$xml;module$build$src$core$xml.workspaceToDom=workspaceToDom$$module$build$src$core$xml;var BlockCreate$$module$build$src$core$events$events_block_create=class extends BlockBase$$module$build$src$core$events$events_block_base{constructor(a){super(a);this.type=EventType$$module$build$src$core$events$type.BLOCK_CREATE;a&&(a.isShadow()&&(this.recordUndo=!1),this.xml=blockToDomWithXY$$module$build$src$core$xml(a),this.ids=getDescendantIds$$module$build$src$core$events$utils(a),this.json=save$$module$build$src$core$serialization$blocks(a,{addCoordinates:!0}))}toJson(){const a=super.toJson();
if(!this.xml)throw Error("The block XML is undefined. Either pass a block to the constructor, or call fromJson");if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(!this.json)throw Error("The block JSON is undefined. Either pass a block to the constructor, or call fromJson");a.xml=domToText$$module$build$src$core$xml(this.xml);a.ids=this.ids;a.json=this.json;this.recordUndo||(a.recordUndo=this.recordUndo);return a}static fromJson(a,
b,c){b=super.fromJson(a,b,c!=null?c:new BlockCreate$$module$build$src$core$events$events_block_create);b.xml=$.textToDom$$module$build$src$core$utils$xml(a.xml);b.ids=a.ids;b.json=a.json;a.recordUndo!==void 0&&(b.recordUndo=a.recordUndo);return b}run(a){const b=this.getEventWorkspace_();if(!this.json)throw Error("The block JSON is undefined. Either pass a block to the constructor, or call fromJson");if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");
if(!allShadowBlocks$$module$build$src$core$events$events_block_create(b,this.ids))if(a)append$$module$build$src$core$serialization$blocks(this.json,b);else for(a=0;a<this.ids.length;a++){const c=this.ids[a],d=b.getBlockById(c);d?d.dispose(!1):c===this.blockId&&console.warn("Can't uncreate non-existent block: "+c)}}},allShadowBlocks$$module$build$src$core$events$events_block_create=function(a,b){return b.map(c=>a.getBlockById(c)).filter(c=>c&&c.isShadow()).length===b.length};
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.BLOCK_CREATE,BlockCreate$$module$build$src$core$events$events_block_create);var module$build$src$core$events$events_block_create={};module$build$src$core$events$events_block_create.BlockCreate=BlockCreate$$module$build$src$core$events$events_block_create;var ThemeChange$$module$build$src$core$events$events_theme_change=class extends UiBase$$module$build$src$core$events$events_ui_base{constructor(a,b){super(b);this.type=EventType$$module$build$src$core$events$type.THEME_CHANGE;this.themeName=a}toJson(){const a=super.toJson();if(!this.themeName)throw Error("The theme name is undefined. Either pass a theme name to the constructor, or call fromJson");a.themeName=this.themeName;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new ThemeChange$$module$build$src$core$events$events_theme_change);
b.themeName=a.themeName;return b}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.THEME_CHANGE,ThemeChange$$module$build$src$core$events$events_theme_change);var module$build$src$core$events$events_theme_change={};module$build$src$core$events$events_theme_change.ThemeChange=ThemeChange$$module$build$src$core$events$events_theme_change;var ViewportChange$$module$build$src$core$events$events_viewport=class extends UiBase$$module$build$src$core$events$events_ui_base{constructor(a,b,c,d,e){super(d);this.type=EventType$$module$build$src$core$events$type.VIEWPORT_CHANGE;this.viewTop=a;this.viewLeft=b;this.scale=c;this.oldScale=e}toJson(){const a=super.toJson();if(this.viewTop===void 0)throw Error("The view top is undefined. Either pass a value to the constructor, or call fromJson");if(this.viewLeft===void 0)throw Error("The view left is undefined. Either pass a value to the constructor, or call fromJson");
if(this.scale===void 0)throw Error("The scale is undefined. Either pass a value to the constructor, or call fromJson");if(this.oldScale===void 0)throw Error("The old scale is undefined. Either pass a value to the constructor, or call fromJson");a.viewTop=this.viewTop;a.viewLeft=this.viewLeft;a.scale=this.scale;a.oldScale=this.oldScale;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new ViewportChange$$module$build$src$core$events$events_viewport);b.viewTop=a.viewTop;b.viewLeft=a.viewLeft;
b.scale=a.scale;b.oldScale=a.oldScale;return b}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.VIEWPORT_CHANGE,ViewportChange$$module$build$src$core$events$events_viewport);var module$build$src$core$events$events_viewport={};module$build$src$core$events$events_viewport.ViewportChange=ViewportChange$$module$build$src$core$events$events_viewport;var TEST_ONLY$$module$build$src$core$field_registry={fromJsonInternal:fromJsonInternal$$module$build$src$core$field_registry},module$build$src$core$field_registry={TEST_ONLY:TEST_ONLY$$module$build$src$core$field_registry};module$build$src$core$field_registry.fromJson=$.fromJson$$module$build$src$core$field_registry;module$build$src$core$field_registry.register=register$$module$build$src$core$field_registry;module$build$src$core$field_registry.unregister=unregister$$module$build$src$core$field_registry;var FieldDropdown$$module$build$src$core$field_dropdown=class extends Field$$module$build$src$core$field{constructor(a,b,c){super(Field$$module$build$src$core$field.SKIP_SETUP);this.svgArrow=this.arrow=this.imageElement=this.menu_=this.selectedMenuItem=null;this.SERIALIZABLE=!0;this.clickTarget_=this.suffixField=this.prefixField=this.generatedOptions=null;a!==Field$$module$build$src$core$field.SKIP_SETUP&&(this.setOptions(a),c&&this.configure_(c),b&&this.setValidator(b))}fromXml(a){this.isOptionListDynamic()&&
this.getOptions(!1);this.setValue(a.textContent)}loadState(a){this.loadLegacyState(FieldDropdown$$module$build$src$core$field_dropdown,a)||(this.isOptionListDynamic()&&this.getOptions(!1),this.setValue(a))}initView(){this.shouldAddBorderRect_()?this.createBorderRect_():this.clickTarget_=this.sourceBlock_.getSvgRoot();this.createTextElement_();this.imageElement=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,{},this.fieldGroup_);this.getConstants().FIELD_DROPDOWN_SVG_ARROW?
this.createSVGArrow_():this.createTextArrow_();this.borderRect_&&addClass$$module$build$src$core$utils$dom(this.borderRect_,"blocklyDropdownRect");this.fieldGroup_&&(addClass$$module$build$src$core$utils$dom(this.fieldGroup_,"blocklyField"),addClass$$module$build$src$core$utils$dom(this.fieldGroup_,"blocklyDropdownField"))}shouldAddBorderRect_(){let a;return!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW||this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW&&!((a=this.getSourceBlock())==
null?0:a.isShadow())}createTextArrow_(){this.arrow=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.TSPAN,{},this.textElement_);let a;this.arrow.appendChild(document.createTextNode(((a=this.getSourceBlock())==null?0:a.RTL)?FieldDropdown$$module$build$src$core$field_dropdown.ARROW_CHAR+" ":" "+FieldDropdown$$module$build$src$core$field_dropdown.ARROW_CHAR));this.getConstants().FIELD_TEXT_BASELINE_CENTER&&this.arrow.setAttribute("dominant-baseline","central");let b;
((b=this.getSourceBlock())==null?0:b.RTL)?this.getTextElement().insertBefore(this.arrow,this.textContent_):this.getTextElement().appendChild(this.arrow)}createSVGArrow_(){this.svgArrow=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,{height:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px",width:this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE+"px"},this.fieldGroup_);this.svgArrow.setAttributeNS(XLINK_NS$$module$build$src$core$utils$dom,"xlink:href",
this.getConstants().FIELD_DROPDOWN_SVG_ARROW_DATAURI)}showEditor_(a){var b=this.getSourceBlock();if(!b)throw new UnattachedFieldError$$module$build$src$core$field;this.dropdownCreate();this.menu_&&(this.menu_.openingCoords=a&&typeof a.clientX==="number"?new Coordinate$$module$build$src$core$utils$coordinate(a.clientX,a.clientY):null,clearContent$$module$build$src$core$dropdowndiv(),a=this.menu_.render(getContentDiv$$module$build$src$core$dropdowndiv()),addClass$$module$build$src$core$utils$dom(a,
"blocklyDropdownMenu"),this.getConstants().FIELD_DROPDOWN_COLOURED_DIV&&(b=b.getColour(),a=this.sourceBlock_.getColourTertiary(),setColour$$module$build$src$core$dropdowndiv(b,a)),showPositionedByField$$module$build$src$core$dropdowndiv(this,this.dropdownDispose_.bind(this)),getContentDiv$$module$build$src$core$dropdowndiv().style.height=`${this.menu_.getSize().height}px`,this.menu_.focus(),this.selectedMenuItem&&this.menu_.setHighlighted(this.selectedMenuItem),this.applyColour())}dropdownCreate(){const a=
this.getSourceBlock();if(!a)throw new UnattachedFieldError$$module$build$src$core$field;const b=new Menu$$module$build$src$core$menu;b.setRole(Role$$module$build$src$core$utils$aria.LISTBOX);this.menu_=b;const c=this.getOptions(!1);this.selectedMenuItem=null;for(let e=0;e<c.length;e++){var d=c[e];if(d===FieldDropdown$$module$build$src$core$field_dropdown.SEPARATOR){b.addChild(new MenuSeparator$$module$build$src$core$menu_separator);continue}const [f,g]=d;isImageProperties$$module$build$src$core$field_dropdown(f)?
(d=new Image(f.width,f.height),d.src=f.src,d.alt=f.alt):d=f;d=new MenuItem$$module$build$src$core$menuitem(d,g);d.setRole(Role$$module$build$src$core$utils$aria.OPTION);d.setRightToLeft(a.RTL);d.setCheckable(!0);b.addChild(d);d.setChecked(g===this.value_);g===this.value_&&(this.selectedMenuItem=d);d.onAction(this.handleMenuActionEvent,this)}}dropdownDispose_(){this.menu_&&this.menu_.dispose();this.selectedMenuItem=this.menu_=null;this.applyColour()}handleMenuActionEvent(a){hideIfOwner$$module$build$src$core$dropdowndiv(this,
!0);this.onItemSelected_(this.menu_,a)}onItemSelected_(a,b){this.setValue(b.getValue())}isOptionListDynamic(){return typeof this.menuGenerator_==="function"}getOptions(a){if(!this.menuGenerator_)throw TypeError("A menu generator was never defined.");if(Array.isArray(this.menuGenerator_))return this.menuGenerator_;if(a&&this.generatedOptions)return this.generatedOptions;this.generatedOptions=this.menuGenerator_();this.validateOptions(this.generatedOptions);return this.generatedOptions}setOptions(a){Array.isArray(a)?
(this.validateOptions(a),a=this.trimOptions(a),this.menuGenerator_=a.options,this.prefixField=a.prefix||null,this.suffixField=a.suffix||null):this.menuGenerator_=a;this.selectedOption=this.getOptions(!1)[0];this.setValue(this.selectedOption[1])}doClassValidation_(a){return this.getOptions(!0).some(b=>b[1]===a)?a:(this.sourceBlock_&&console.warn("Cannot set the dropdown's value to an unavailable option. Block type: "+this.sourceBlock_.type+", Field name: "+this.name+", Value: "+a),null)}doValueUpdate_(a){super.doValueUpdate_(a);
a=this.getOptions(!0);for(let b=0,c;c=a[b];b++)c[1]===this.value_&&(this.selectedOption=c)}applyColour(){const a=this.sourceBlock_;this.borderRect_&&(this.borderRect_.setAttribute("stroke",a.getColourTertiary()),this.menu_?this.borderRect_.setAttribute("fill",a.getColourTertiary()):this.borderRect_.setAttribute("fill","transparent"));a&&this.arrow&&(a.isShadow()?this.arrow.style.fill=a.getColourSecondary():this.arrow.style.fill=a.getColour())}render_(){this.getTextContent().nodeValue="";this.imageElement.style.display=
"none";const a=this.selectedOption&&this.selectedOption[0];isImageProperties$$module$build$src$core$field_dropdown(a)?this.renderSelectedImage(a):this.renderSelectedText();this.positionBorderRect_()}renderSelectedImage(a){const b=this.getSourceBlock();if(!b)throw new UnattachedFieldError$$module$build$src$core$field;this.imageElement.style.display="";this.imageElement.setAttributeNS(XLINK_NS$$module$build$src$core$utils$dom,"xlink:href",a.src);this.imageElement.setAttribute("height",String(a.height));
this.imageElement.setAttribute("width",String(a.width));const c=Number(a.height);a=Number(a.width);var d=!!this.borderRect_;const e=Math.max(d?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,c+FieldDropdown$$module$build$src$core$field_dropdown.IMAGE_Y_PADDING);d=d?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;let f;f=this.svgArrow?this.positionSVGArrow(a+d,e/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2):getTextWidth$$module$build$src$core$utils$dom(this.arrow);this.size_=new Size$$module$build$src$core$utils$size(a+
f+d*2,e);let g=0;b.RTL?this.imageElement.setAttribute("x",`${d+f}`):(g=a+f,this.getTextElement().setAttribute("text-anchor","end"),this.imageElement.setAttribute("x",`${d}`));this.imageElement.setAttribute("y",String(e/2-c/2));this.positionTextElement_(g+d,a+f)}renderSelectedText(){this.getTextContent().nodeValue=this.getDisplayText_();var a=this.getTextElement();addClass$$module$build$src$core$utils$dom(a,"blocklyDropdownText");a.setAttribute("text-anchor","start");var b=!!this.borderRect_;a=Math.max(b?
this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,this.getConstants().FIELD_TEXT_HEIGHT);const c=getTextWidth$$module$build$src$core$utils$dom(this.getTextElement());b=b?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;let d=0;this.svgArrow&&(d=this.positionSVGArrow(c+b,a/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2));this.size_=new Size$$module$build$src$core$utils$size(c+d+b*2,a);this.positionTextElement_(b,c)}positionSVGArrow(a,b){if(!this.svgArrow)return 0;const c=this.getSourceBlock();
if(!c)throw new UnattachedFieldError$$module$build$src$core$field;const d=this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,e=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,f=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE;this.svgArrow.setAttribute("transform","translate("+(c.RTL?d:a+e)+","+b+")");return f+e}getText_(){if(!this.selectedOption)return null;const a=this.selectedOption[0];if(isImageProperties$$module$build$src$core$field_dropdown(a))return a.alt;if(typeof HTMLElement!==
"undefined"&&a instanceof HTMLElement){let b,c;return(c=(b=a.title)!=null?b:a.ariaLabel)!=null?c:a.innerText}if(typeof a==="string")return a;console.warn("Can't get text for existing dropdown option. If you're using HTMLElement dropdown options in node, ensure you're using jsdom-global or similar.");return null}static fromJson(a){if(!a.options)throw Error("options are required for the dropdown field. The options property must be assigned an array of [humanReadableValue, languageNeutralValue] tuples.");
return new this(a.options,void 0,a)}trimOptions(a){let b=!1;const c=a.map(g=>{if(g===FieldDropdown$$module$build$src$core$field_dropdown.SEPARATOR)return b=!0,g;const [h,k]=g;if(typeof h==="string")return[replaceMessageReferences$$module$build$src$core$utils$parsing(h),k];b=!0;return[isImageProperties$$module$build$src$core$field_dropdown(h)?Object.assign({},h,{alt:replaceMessageReferences$$module$build$src$core$utils$parsing(h.alt)}):h,k]});if(b||a.length<2)return{options:c};var d=c.map(([g])=>g),
e=shortestStringLength$$module$build$src$core$utils$string(d);a=commonWordPrefix$$module$build$src$core$utils$string(d,e);const f=commonWordSuffix$$module$build$src$core$utils$string(d,e);if(!a&&!f||e<=a+f)return{options:c};e=a?d[0].substring(0,a-1):void 0;d=f?d[0].substr(1-f):void 0;return{options:this.applyTrim(c,a,f),prefix:e,suffix:d}}applyTrim(a,b,c){return a.map(([d,e])=>[d.substring(b,d.length-c),e])}validateOptions(a){if(!Array.isArray(a))throw TypeError("FieldDropdown options must be an array.");
if(!a.length)throw TypeError("FieldDropdown options must not be an empty array.");let b=!1;for(let c=0;c<a.length;c++){const d=a[c];Array.isArray(d)||d===FieldDropdown$$module$build$src$core$field_dropdown.SEPARATOR?typeof d[1]!=="string"?(b=!0,console.error(`Invalid option[${c}]: Each FieldDropdown option id must be a string.
          Found ${d[1]} in: ${d}`)):!d[0]||typeof d[0]==="string"||isImageProperties$$module$build$src$core$field_dropdown(d[0])||typeof HTMLElement!=="undefined"&&d[0]instanceof HTMLElement||(b=!0,console.error(`Invalid option[${c}]: Each FieldDropdown option must have a string
          label, image description, or HTML element. Found ${d[0]} in: ${d}`)):(b=!0,console.error(`Invalid option[${c}]: Each FieldDropdown option must be an array or
          the string literal 'separator'. Found: ${d}`))}if(b)throw TypeError("Found invalid FieldDropdown options.");}};FieldDropdown$$module$build$src$core$field_dropdown.SEPARATOR="separator";FieldDropdown$$module$build$src$core$field_dropdown.ARROW_CHAR="\u25be";FieldDropdown$$module$build$src$core$field_dropdown.IMAGE_Y_OFFSET=5;FieldDropdown$$module$build$src$core$field_dropdown.IMAGE_Y_PADDING=FieldDropdown$$module$build$src$core$field_dropdown.IMAGE_Y_OFFSET*2;
register$$module$build$src$core$field_registry("field_dropdown",FieldDropdown$$module$build$src$core$field_dropdown);var module$build$src$core$field_dropdown={};module$build$src$core$field_dropdown.FieldDropdown=FieldDropdown$$module$build$src$core$field_dropdown;var Theme$$module$build$src$core$theme=class{constructor(a,b,c,d){this.name=a;this.startHats=!1;this.blockStyles=b||Object.create(null);this.categoryStyles=c||Object.create(null);this.componentStyles=d||Object.create(null);this.fontStyle=Object.create(null);register$$module$build$src$core$registry(Type$$module$build$src$core$registry.THEME,a,this,!0)}getClassName(){return this.name+"-theme"}setBlockStyle(a,b){this.blockStyles[a]=b}setCategoryStyle(a,b){this.categoryStyles[a]=b}getComponentStyle(a){a=
this.componentStyles[a];if(!a)return null;if(typeof a==="string"){const b=this.getComponentStyle(a);if(b)return b}return`${a}`}setComponentStyle(a,b){this.componentStyles[a]=b}setFontStyle(a){this.fontStyle=a}setStartHats(a){this.startHats=a}static defineTheme(a,b){a=a.toLowerCase();const c=new Theme$$module$build$src$core$theme(a);let d=b.base;if(d){if(typeof d==="string"){let e;d=(e=getObject$$module$build$src$core$registry(Type$$module$build$src$core$registry.THEME,d))!=null?e:void 0}d instanceof
Theme$$module$build$src$core$theme&&(deepMerge$$module$build$src$core$utils$object(c,d),c.name=a)}deepMerge$$module$build$src$core$utils$object(c.blockStyles,b.blockStyles);deepMerge$$module$build$src$core$utils$object(c.categoryStyles,b.categoryStyles);deepMerge$$module$build$src$core$utils$object(c.componentStyles,b.componentStyles);deepMerge$$module$build$src$core$utils$object(c.fontStyle,b.fontStyle);b.startHats!==null&&(c.startHats=b.startHats);return c}},module$build$src$core$theme={};
module$build$src$core$theme.Theme=Theme$$module$build$src$core$theme;var defaultBlockStyles$$module$build$src$core$theme$classic={colour_blocks:{colourPrimary:"20"},list_blocks:{colourPrimary:"260"},logic_blocks:{colourPrimary:"210"},loop_blocks:{colourPrimary:"120"},math_blocks:{colourPrimary:"230"},procedure_blocks:{colourPrimary:"290"},text_blocks:{colourPrimary:"160"},variable_blocks:{colourPrimary:"330"},variable_dynamic_blocks:{colourPrimary:"310"},hat_blocks:{colourPrimary:"330",hat:"cap"}},categoryStyles$$module$build$src$core$theme$classic={colour_category:{colour:"20"},
list_category:{colour:"260"},logic_category:{colour:"210"},loop_category:{colour:"120"},math_category:{colour:"230"},procedure_category:{colour:"290"},text_category:{colour:"160"},variable_category:{colour:"330"},variable_dynamic_category:{colour:"310"}},Classic$$module$build$src$core$theme$classic=new Theme$$module$build$src$core$theme("classic",defaultBlockStyles$$module$build$src$core$theme$classic,categoryStyles$$module$build$src$core$theme$classic),module$build$src$core$theme$classic={Classic:Classic$$module$build$src$core$theme$classic};var Options$$module$build$src$core$options=class{constructor(a){this.gridPattern=null;this.getMetrics=this.setMetrics=void 0;let b=null,c=!1;var d=!1,e=!1,f=!1,g=!1,h=!1;const k=!!a.readOnly;if(!k){var l;b=convertToolboxDefToJson$$module$build$src$core$utils$toolbox((l=a.toolbox)!=null?l:null);c=hasCategories$$module$build$src$core$utils$toolbox(b);d=a.trashcan;d=d===void 0?c:d;e=a.collapse;e=e===void 0?c:e;f=a.comments;f=f===void 0?c:f;g=a.disable;g=g===void 0?c:g;h=a.sounds;h=h===void 0?!0:h}l=
a.maxTrashcanContents;d?l===void 0&&(l=32):l=0;const m=!!a.rtl;let n=a.horizontalLayout;n===void 0&&(n=!1);var p=a.toolboxPosition!=="end";p=n?p?Position$$module$build$src$core$utils$toolbox.TOP:Position$$module$build$src$core$utils$toolbox.BOTTOM:p===m?Position$$module$build$src$core$utils$toolbox.RIGHT:Position$$module$build$src$core$utils$toolbox.LEFT;let r=a.css;r===void 0&&(r=!0);let q="https://blockly-demo.appspot.com/static/media/";a.media&&(q=a.media.endsWith("/")?a.media:a.media+"/");const u=
a.oneBasedIndex,y=a.renderer||"geras",z=a.plugins||{};let t=a.modalInputs;t===void 0&&(t=!0);this.RTL=m;this.oneBasedIndex=u===void 0?!0:u;this.collapse=e;this.comments=f;this.disable=g;this.readOnly=k;this.maxBlocks=a.maxBlocks||Infinity;let v;this.maxInstances=(v=a.maxInstances)!=null?v:null;this.modalInputs=t;this.pathToMedia=q;this.hasCategories=c;this.moveOptions=Options$$module$build$src$core$options.parseMoveOptions(a,c);this.hasScrollbars=!!this.moveOptions.scrollbars;this.hasTrashcan=d;this.maxTrashcanContents=
l;this.hasSounds=h;this.hasCss=r;this.horizontalLayout=n;this.languageTree=b;this.gridOptions=Options$$module$build$src$core$options.parseGridOptions(a);this.zoomOptions=Options$$module$build$src$core$options.parseZoomOptions(a);this.toolboxPosition=p;this.theme=Options$$module$build$src$core$options.parseThemeOptions(a);this.renderer=y;let w;this.rendererOverrides=(w=a.rendererOverrides)!=null?w:null;let x;this.parentWorkspace=(x=a.parentWorkspace)!=null?x:null;this.plugins=z}static parseMoveOptions(a,
b){const c=a.move||{},d={};c.scrollbars===void 0&&a.scrollbars===void 0?d.scrollbars=b:typeof c.scrollbars==="object"?(d.scrollbars={horizontal:!!c.scrollbars.horizontal,vertical:!!c.scrollbars.vertical},d.scrollbars.horizontal&&d.scrollbars.vertical?d.scrollbars=!0:d.scrollbars.horizontal||d.scrollbars.vertical||(d.scrollbars=!1)):d.scrollbars=!!c.scrollbars||!!a.scrollbars;d.wheel=d.scrollbars&&c.wheel!==void 0?!!c.wheel:typeof d.scrollbars==="object";d.drag=d.scrollbars?c.drag===void 0?!0:!!c.drag:
!1;return d}static parseZoomOptions(a){a=a.zoom||{};const b={};b.controls=a.controls===void 0?!1:!!a.controls;b.wheel=a.wheel===void 0?!1:!!a.wheel;b.startScale=a.startScale===void 0?1:Number(a.startScale);b.maxScale=a.maxScale===void 0?3:Number(a.maxScale);b.minScale=a.minScale===void 0?.3:Number(a.minScale);b.scaleSpeed=a.scaleSpeed===void 0?1.2:Number(a.scaleSpeed);b.pinch=a.pinch===void 0?b.wheel||b.controls:!!a.pinch;return b}static parseGridOptions(a){a=a.grid||{};const b={};b.spacing=Number(a.spacing)||
0;b.colour=a.colour||"#888";b.length=a.length===void 0?1:Number(a.length);b.snap=b.spacing>0&&!!a.snap;return b}static parseThemeOptions(a){a=a.theme||Classic$$module$build$src$core$theme$classic;return typeof a==="string"?getObject$$module$build$src$core$registry(Type$$module$build$src$core$registry.THEME,a):a instanceof Theme$$module$build$src$core$theme?a:Theme$$module$build$src$core$theme.defineTheme(a.name||"builtin"+getNextUniqueId$$module$build$src$core$utils$idgenerator(),a)}},module$build$src$core$options=
{};module$build$src$core$options.Options=Options$$module$build$src$core$options;var BubbleDragStrategy$$module$build$src$core$dragging$bubble_drag_strategy=class{constructor(a,b){this.bubble=a;this.workspace=b;this.startLoc=null}isMovable(){return!0}startDrag(){this.startLoc=this.bubble.getRelativeToSurfaceXY();this.workspace.setResizesEnabled(!1);let a;(a=this.workspace.getLayerManager())==null||a.moveToDragLayer(this.bubble);this.bubble.setDragging&&this.bubble.setDragging(!0)}drag(a){this.bubble.moveDuringDrag(a)}endDrag(){this.workspace.setResizesEnabled(!0);let a;(a=this.workspace.getLayerManager())==
null||a.moveOffDragLayer(this.bubble,BUBBLE$$module$build$src$core$layers);this.bubble.setDragging(!1)}revertDrag(){this.startLoc&&this.bubble.moveDuringDrag(this.startLoc)}},module$build$src$core$dragging$bubble_drag_strategy={};module$build$src$core$dragging$bubble_drag_strategy.BubbleDragStrategy=BubbleDragStrategy$$module$build$src$core$dragging$bubble_drag_strategy;var _a$$module$build$src$core$bubbles$bubble,Bubble$$module$build$src$core$bubbles$bubble=class{constructor(a,b,c,d,e){this.workspace=a;this.anchor=b;this.ownerRect=c;this.owner=e;this.size=new Size$$module$build$src$core$utils$size(0,0);this.colour="#ffffff";this.disposed=!1;this.relativeLeft=this.relativeTop=0;this.dragStrategy=new BubbleDragStrategy$$module$build$src$core$dragging$bubble_drag_strategy(this,this.workspace);this.id=getNextUniqueId$$module$build$src$core$utils$idgenerator();this.svgRoot=
createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{"class":"blocklyBubble"},a.getBubbleCanvas());a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{"class":"blocklyEmboss"},this.svgRoot);this.tail=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,{"class":"blocklyBubbleTail"},a);this.background=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,
{"class":"blocklyDraggable",x:0,y:0,rx:_a$$module$build$src$core$bubbles$bubble.BORDER_WIDTH,ry:_a$$module$build$src$core$bubbles$bubble.BORDER_WIDTH},a);this.contentContainer=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{},this.svgRoot);this.focusableElement=d!=null?d:this.svgRoot;this.focusableElement.setAttribute("id",this.id);conditionalBind$$module$build$src$core$browser_events(this.background,"pointerdown",this,this.onMouseDown);conditionalBind$$module$build$src$core$browser_events(this.focusableElement,
"keydown",this,this.onKeyDown)}dispose(){removeNode$$module$build$src$core$utils$dom(this.svgRoot);this.disposed=!0}setAnchorLocation(a,b=!1){this.anchor=a;b?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor();this.renderTail()}setPositionRelativeToAnchor(a,b){this.relativeLeft=a;this.relativeTop=b;this.positionRelativeToAnchor();this.renderTail()}getSize(){return this.size}setSize(a,b=!1){a.width=Math.max(a.width,_a$$module$build$src$core$bubbles$bubble.MIN_SIZE);a.height=Math.max(a.height,
_a$$module$build$src$core$bubbles$bubble.MIN_SIZE);this.size=a;this.background.setAttribute("width",`${a.width}`);this.background.setAttribute("height",`${a.height}`);b?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor();this.renderTail()}getColour(){return this.colour}setColour(a){this.colour=a;this.tail.setAttribute("fill",a);this.background.setAttribute("fill",a)}onMouseDown(a){let b;(b=this.workspace.getGesture(a))==null||b.handleBubbleStart(a,this);$.getFocusManager$$module$build$src$core$focus_manager().focusNode(this)}onKeyDown(a){a.key===
"Escape"&&this.owner&&(this.owner.setBubbleVisible(!1),$.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.owner))}positionRelativeToAnchor(){let a=this.anchor.x;a=this.workspace.RTL?a-(this.relativeLeft+this.size.width):a+this.relativeLeft;this.moveTo(a,this.relativeTop+this.anchor.y)}moveTo(a,b){this.svgRoot.setAttribute("transform",`translate(${a}, ${b})`)}positionByRect(a=new Rect$$module$build$src$core$utils$rect(0,0,0,0)){var b=this.workspace.getMetricsManager().getViewMetrics(!0),
c=this.getOptimalRelativeLeft(b),d=this.getOptimalRelativeTop(b);const e={x:c,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},f={x:-this.size.width-30,y:d};d={x:a.getWidth(),y:d};var g={x:c,y:a.getHeight()};c=a.getWidth()<a.getHeight()?d:g;a=a.getWidth()<a.getHeight()?g:d;d=this.getOverlap(e,b);g=this.getOverlap(f,b);const h=this.getOverlap(c,b);b=this.getOverlap(a,b);b=Math.max(d,g,h,b);d===b?(this.relativeLeft=e.x,this.relativeTop=e.y):g===b?(this.relativeLeft=
f.x,this.relativeTop=f.y):h===b?(this.relativeLeft=c.x,this.relativeTop=c.y):(this.relativeLeft=a.x,this.relativeTop=a.y);this.positionRelativeToAnchor()}getOverlap(a,b){var c=this.workspace.RTL?this.anchor.x-a.x-this.size.width:a.x+this.anchor.x;a=a.y+this.anchor.y;return Math.max(0,Math.min(1,(Math.min(c+this.size.width,b.left+b.width)-Math.max(c,b.left))*(Math.min(a+this.size.height,b.top+b.height)-Math.max(a,b.top))/(this.size.width*this.size.height)))}getOptimalRelativeLeft(a){let b=-this.size.width/
4;if(this.size.width>a.width)return b;a=this.getWorkspaceViewRect(a);if(this.workspace.RTL){var c=this.anchor.x-b;c-this.size.width<a.left?b=-(a.left-this.anchor.x+this.size.width):c>a.right&&(b=-(a.right-this.anchor.x))}else{c=b+this.anchor.x;const d=c+this.size.width;c<a.left?b=a.left-this.anchor.x:d>a.right&&(b=a.right-this.anchor.x-this.size.width)}return b}getOptimalRelativeTop(a){let b=-this.size.height/4;if(this.size.height>a.height)return b;const c=this.anchor.y+b,d=c+this.size.height;a=this.getWorkspaceViewRect(a);
c<a.top?b=a.top-this.anchor.y:d>a.bottom&&(b=a.bottom-this.anchor.y-this.size.height);return b}getWorkspaceViewRect(a){const b=a.top;let c=a.top+a.height,d=a.left;a=a.left+a.width;c-=this.getScrollbarThickness();this.workspace.RTL?d-=this.getScrollbarThickness():a-=this.getScrollbarThickness();return new Rect$$module$build$src$core$utils$rect(b,c,d,a)}getScrollbarThickness(){return Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness/this.workspace.scale}renderTail(){const a=[];var b=this.size.width/
2,c=this.size.height/2,d=-this.relativeLeft,e=-this.relativeTop;if(b===d&&c===e)a.push("M "+b+","+c);else{e-=c;d-=b;this.workspace.RTL&&(d*=-1);var f=Math.sqrt(e*e+d*d),g=Math.acos(d/f);e<0&&(g=2*Math.PI-g);var h=g+Math.PI/2;h>Math.PI*2&&(h-=Math.PI*2);var k=Math.sin(h);const m=Math.cos(h);let n=(this.size.width+this.size.height)/_a$$module$build$src$core$bubbles$bubble.TAIL_THICKNESS;n=Math.min(n,this.size.width,this.size.height)/4;h=1-_a$$module$build$src$core$bubbles$bubble.ANCHOR_RADIUS/f;d=b+
h*d;e=c+h*e;h=b+n*m;const p=c+n*k;b-=n*m;c-=n*k;k=toRadians$$module$build$src$core$utils$math(this.workspace.RTL?-_a$$module$build$src$core$bubbles$bubble.TAIL_ANGLE:_a$$module$build$src$core$bubbles$bubble.TAIL_ANGLE);k=g+k;k>Math.PI*2&&(k-=Math.PI*2);g=Math.sin(k)*f/_a$$module$build$src$core$bubbles$bubble.TAIL_BEND;f=Math.cos(k)*f/_a$$module$build$src$core$bubbles$bubble.TAIL_BEND;a.push("M"+h+","+p);a.push("C"+(h+f)+","+(p+g)+" "+d+","+e+" "+d+","+e);a.push("C"+d+","+e+" "+(b+f)+","+(c+g)+" "+
b+","+c)}a.push("z");let l;(l=this.tail)==null||l.setAttribute("d",a.join(" "))}bringToFront(){let a;const b=(a=this.svgRoot)==null?void 0:a.parentNode;return this.svgRoot&&(b==null?void 0:b.lastChild)!==this.svgRoot?(b==null||b.appendChild(this.svgRoot),!0):!1}getRelativeToSurfaceXY(){return new Coordinate$$module$build$src$core$utils$coordinate(this.workspace.RTL?-this.relativeLeft+this.anchor.x-this.size.width:this.anchor.x+this.relativeLeft,this.anchor.y+this.relativeTop)}getSvgRoot(){return this.svgRoot}moveDuringDrag(a){this.moveTo(a.x,
a.y);this.relativeLeft=this.workspace.RTL?this.anchor.x-a.x-this.size.width:a.x-this.anchor.x;this.relativeTop=a.y-this.anchor.y;this.renderTail()}setDragging(a){}setDeleteStyle(a){}isDeletable(){return!1}showContextMenu(a){}isMovable(){return!0}startDrag(){this.dragStrategy.startDrag()}drag(a){this.dragStrategy.drag(a)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){fireSelectedEvent$$module$build$src$core$common(this)}unselect(){fireSelectedEvent$$module$build$src$core$common(null)}getFocusableElement(){return this.focusableElement}getFocusableTree(){return this.workspace}onNodeFocus(){this.select();
this.bringToFront();var a=this.getRelativeToSurfaceXY();const b=this.getSize();a=new Rect$$module$build$src$core$utils$rect(a.y,a.y+b.height,a.x,a.x+b.width);this.workspace.scrollBoundsIntoView(a)}onNodeBlur(){this.unselect()}canBeFocused(){return!0}getOwner(){return this.owner}};_a$$module$build$src$core$bubbles$bubble=Bubble$$module$build$src$core$bubbles$bubble;Bubble$$module$build$src$core$bubbles$bubble.BORDER_WIDTH=6;
Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER=_a$$module$build$src$core$bubbles$bubble.BORDER_WIDTH*2;Bubble$$module$build$src$core$bubbles$bubble.MIN_SIZE=_a$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER;Bubble$$module$build$src$core$bubbles$bubble.TAIL_THICKNESS=1;Bubble$$module$build$src$core$bubbles$bubble.TAIL_ANGLE=20;Bubble$$module$build$src$core$bubbles$bubble.TAIL_BEND=4;Bubble$$module$build$src$core$bubbles$bubble.ANCHOR_RADIUS=8;
var module$build$src$core$bubbles$bubble={};module$build$src$core$bubbles$bubble.Bubble=Bubble$$module$build$src$core$bubbles$bubble;var MiniWorkspaceBubble$$module$build$src$core$bubbles$mini_workspace_bubble=class extends Bubble$$module$build$src$core$bubbles$bubble{constructor(a,b,c,d){super(b,c,d);this.workspace=b;this.anchor=c;this.ownerRect=d;this.autoLayout=!0;b=new Options$$module$build$src$core$options(a);this.validateWorkspaceOptions(b);this.svgDialog=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.SVG,{x:Bubble$$module$build$src$core$bubbles$bubble.BORDER_WIDTH,y:Bubble$$module$build$src$core$bubbles$bubble.BORDER_WIDTH},
this.contentContainer);a.parentWorkspace=this.workspace;this.miniWorkspace=this.newWorkspaceSvg(new Options$$module$build$src$core$options(a));this.miniWorkspace.internalIsMutator=!0;a=this.miniWorkspace.createDom("blocklyMutatorBackground");this.svgDialog.appendChild(a);b.languageTree&&(a.insertBefore(this.miniWorkspace.addFlyout(Svg$$module$build$src$core$utils$svg.G),this.miniWorkspace.getCanvas()),a=this.miniWorkspace.getFlyout(),a==null||a.init(this.miniWorkspace),a==null||a.show(b.languageTree));
addClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyMiniWorkspaceBubble");this.miniWorkspace.addChangeListener(this.onWorkspaceChange.bind(this));let e,f;(e=this.miniWorkspace.getFlyout())==null||(f=e.getWorkspace())==null||f.addChangeListener(this.onWorkspaceChange.bind(this));this.updateBubbleSize()}dispose(){this.miniWorkspace.dispose();super.dispose()}getWorkspace(){return this.miniWorkspace}addWorkspaceChangeListener(a){this.miniWorkspace.addChangeListener(a)}validateWorkspaceOptions(a){if(a.hasCategories)throw Error("The miniworkspace bubble does not support toolboxes with categories");
if(a.hasTrashcan)throw Error("The miniworkspace bubble does not support trashcans");if(a.zoomOptions.controls||a.zoomOptions.wheel||a.zoomOptions.pinch)throw Error("The miniworkspace bubble does not support zooming");if(a.moveOptions.scrollbars||a.moveOptions.wheel||a.moveOptions.drag)throw Error("The miniworkspace bubble does not scrolling/moving the workspace");if(a.horizontalLayout)throw Error("The miniworkspace bubble does not support horizontal layouts");}onWorkspaceChange(){this.bumpBlocksIntoBounds();
this.updateBubbleSize()}bumpBlocksIntoBounds(){if(!this.miniWorkspace.isDragging()||this.miniWorkspace.keyboardMoveInProgress)for(const a of this.miniWorkspace.getTopBlocks(!1)){const b=a.getRelativeToSurfaceXY();b.y<20&&a.moveBy(0,20-b.y);if(a.RTL){let c=-20;const d=this.miniWorkspace.getFlyout();d&&(c-=d.getWidth());b.x>c&&a.moveBy(c-b.x,0)}else b.x<20&&a.moveBy(20-b.x,0)}}updateBubbleSize(){if(!this.miniWorkspace.isDragging()||this.miniWorkspace.keyboardMoveInProgress){this.autoLayout&&(this.autoLayout=
!this.miniWorkspace.keyboardMoveInProgress);var a=this.getSize(),b=this.calculateWorkspaceSize();Math.abs(a.width-b.width)<MiniWorkspaceBubble$$module$build$src$core$bubbles$mini_workspace_bubble.MINIMUM_VIEW_CHANGE&&Math.abs(a.height-b.height)<MiniWorkspaceBubble$$module$build$src$core$bubbles$mini_workspace_bubble.MINIMUM_VIEW_CHANGE||(this.svgDialog.setAttribute("width",`${b.width}px`),this.svgDialog.setAttribute("height",`${b.height}px`),this.miniWorkspace.setCachedParentSvgSize(b.width,b.height),
this.miniWorkspace.RTL&&this.miniWorkspace.getCanvas().setAttribute("transform",`translate(${b.width}, 0)`),this.setSize(new Size$$module$build$src$core$utils$size(b.width+Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER,b.height+Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER),this.autoLayout),this.miniWorkspace.resize(),this.miniWorkspace.recordDragTargets())}}calculateWorkspaceSize(){var a=this.miniWorkspace.getCanvas().getBBox();let b=a.width+MiniWorkspaceBubble$$module$build$src$core$bubbles$mini_workspace_bubble.MARGIN;
a=a.height+MiniWorkspaceBubble$$module$build$src$core$bubbles$mini_workspace_bubble.MARGIN;const c=this.miniWorkspace.getFlyout();if(c){const d=c.getWorkspace().getMetricsManager().getScrollMetrics();a=Math.max(a,d.height+20);b+=c.getWidth()}return new Size$$module$build$src$core$utils$size(b,a)}updateBlockStyles(){for(var a of this.miniWorkspace.getAllBlocks(!1))a.setStyle(a.getStyleName());let b;if(a=(b=this.miniWorkspace.getFlyout())==null?void 0:b.getWorkspace())for(const c of a.getAllBlocks(!1))c.setStyle(c.getStyleName())}moveDuringDrag(a){super.moveDuringDrag(a);
this.autoLayout=!1}moveTo(a,b){super.moveTo(a,b);this.miniWorkspace.recordDragTargets()}newWorkspaceSvg(a){throw Error("The implementation of newWorkspaceSvg should be monkey-patched in by blockly.ts");}};MiniWorkspaceBubble$$module$build$src$core$bubbles$mini_workspace_bubble.MINIMUM_VIEW_CHANGE=10;MiniWorkspaceBubble$$module$build$src$core$bubbles$mini_workspace_bubble.MARGIN=Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER*3;var module$build$src$core$bubbles$mini_workspace_bubble={};
module$build$src$core$bubbles$mini_workspace_bubble.MiniWorkspaceBubble=MiniWorkspaceBubble$$module$build$src$core$bubbles$mini_workspace_bubble;var Icon$$module$build$src$core$icons$icon=class{constructor(a){this.sourceBlock=a;this.offsetInBlock=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.workspaceLocation=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.svgRoot=null;this.tooltip=a;this.id=getNextUniqueId$$module$build$src$core$utils$idgenerator()}getType(){throw Error("Icons must implement getType");}initView(a){if(!this.svgRoot){var b=this.sourceBlock;this.svgRoot=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,
{"class":"blocklyIconGroup",id:this.id});b.getSvgRoot().appendChild(this.svgRoot);this.updateSvgRootOffset();conditionalBind$$module$build$src$core$browser_events(this.svgRoot,"pointerdown",this,a);this.svgRoot.tooltip=this;bindMouseEvents$$module$build$src$core$tooltip(this.svgRoot)}}dispose(){unbindMouseEvents$$module$build$src$core$tooltip(this.svgRoot);removeNode$$module$build$src$core$utils$dom(this.svgRoot)}getWeight(){return-1}getSize(){return new Size$$module$build$src$core$utils$size(0,0)}setTooltip(a){this.tooltip=
a!=null?a:this.sourceBlock}getTooltip(){return this.tooltip}applyColour(){}updateEditable(){}updateCollapsed(){this.svgRoot&&(this.sourceBlock.isCollapsed()?this.svgRoot.style.display="none":this.svgRoot.style.display="block",hasBubble$$module$build$src$core$interfaces$i_has_bubble(this)&&this.setBubbleVisible(!1))}hideForInsertionMarker(){this.svgRoot&&(this.svgRoot.style.display="none")}isShownWhenCollapsed(){return!1}setOffsetInBlock(a){this.offsetInBlock=a;this.updateSvgRootOffset()}updateSvgRootOffset(){let a;
(a=this.svgRoot)==null||a.setAttribute("transform",`translate(${this.offsetInBlock.x}, ${this.offsetInBlock.y})`)}onLocationChange(a){this.workspaceLocation=Coordinate$$module$build$src$core$utils$coordinate.sum(a,this.offsetInBlock)}onClick(){}isClickableInFlyout(a){return!0}getFocusableElement(){const a=this.svgRoot;if(!a)throw Error("Attempting to focus uninitialized icon.");return a}getFocusableTree(){return this.sourceBlock.workspace}onNodeFocus(){var a=this.sourceBlock.getBoundingRectangle();
a=new Rect$$module$build$src$core$utils$rect(a.top+this.offsetInBlock.y,a.top+this.offsetInBlock.y+this.getSize().height,a.left+this.offsetInBlock.x,a.left+this.offsetInBlock.x+this.getSize().width);this.sourceBlock.workspace.scrollBoundsIntoView(a)}onNodeBlur(){}canBeFocused(){return!0}getSourceBlock(){return this.sourceBlock}},module$build$src$core$icons$icon={};module$build$src$core$icons$icon.Icon=Icon$$module$build$src$core$icons$icon;var SIZE$$module$build$src$core$icons$mutator_icon,WORKSPACE_MARGIN$$module$build$src$core$icons$mutator_icon;SIZE$$module$build$src$core$icons$mutator_icon=17;WORKSPACE_MARGIN$$module$build$src$core$icons$mutator_icon=16;
$.MutatorIcon$$module$build$src$core$icons$mutator_icon=class extends Icon$$module$build$src$core$icons$icon{constructor(a,b){super(b);this.flyoutBlockTypes=a;this.sourceBlock=b;this.saveConnectionsListener=this.updateWorkspacePid=this.rootBlock=this.miniWorkspaceBubble=null}getType(){return $.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE}initView(a){this.svgRoot||(super.initView(a),createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{"class":"blocklyIconShape",
rx:"4",ry:"4",height:"16",width:"16"},this.svgRoot),createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,{"class":"blocklyIconSymbol",d:"m4.203,7.296 0,1.368 -0.92,0.677 -0.11,0.41 0.9,1.559 0.41,0.11 1.043,-0.457 1.187,0.683 0.127,1.134 0.3,0.3 1.8,0 0.3,-0.299 0.127,-1.138 1.185,-0.682 1.046,0.458 0.409,-0.11 0.9,-1.559 -0.11,-0.41 -0.92,-0.677 0,-1.366 0.92,-0.677 0.11,-0.41 -0.9,-1.559 -0.409,-0.109 -1.046,0.458 -1.185,-0.682 -0.127,-1.138 -0.3,-0.299 -1.8,0 -0.3,0.3 -0.126,1.135 -1.187,0.682 -1.043,-0.457 -0.41,0.11 -0.899,1.559 0.108,0.409z"},
this.svgRoot),createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.CIRCLE,{"class":"blocklyIconShape",r:"2.7",cx:"8",cy:"8"},this.svgRoot),addClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyMutatorIcon"))}dispose(){super.dispose();let a;(a=this.miniWorkspaceBubble)==null||a.dispose()}getWeight(){return $.MutatorIcon$$module$build$src$core$icons$mutator_icon.WEIGHT}getSize(){return new Size$$module$build$src$core$utils$size(SIZE$$module$build$src$core$icons$mutator_icon,
SIZE$$module$build$src$core$icons$mutator_icon)}applyColour(){super.applyColour();let a;(a=this.miniWorkspaceBubble)==null||a.setColour(this.sourceBlock.getColour());let b;(b=this.miniWorkspaceBubble)==null||b.updateBlockStyles()}updateCollapsed(){super.updateCollapsed();this.sourceBlock.isCollapsed()&&this.setBubbleVisible(!1)}onLocationChange(a){super.onLocationChange(a);let b;(b=this.miniWorkspaceBubble)==null||b.setAnchorLocation(this.getAnchorLocation())}onClick(){super.onClick();this.sourceBlock.isEditable()&&
this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}bubbleIsVisible(){return!!this.miniWorkspaceBubble}setBubbleVisible(a){const b=this;return(0,$jscomp.asyncExecutePromiseGeneratorFunction)(function*(){if(b.bubbleIsVisible()!==a){yield finishQueuedRenders$$module$build$src$core$render_management();if(a){b.miniWorkspaceBubble=new MiniWorkspaceBubble$$module$build$src$core$bubbles$mini_workspace_bubble(b.getMiniWorkspaceConfig(),b.sourceBlock.workspace,b.getAnchorLocation(),
b.getBubbleOwnerRect());b.applyColour();b.createRootBlock();b.addSaveConnectionsListener();let c;(c=b.miniWorkspaceBubble)==null||c.addWorkspaceChangeListener(b.createMiniWorkspaceChangeListener())}else{let c;(c=b.miniWorkspaceBubble)==null||c.dispose();b.miniWorkspaceBubble=null;b.saveConnectionsListener&&b.sourceBlock.workspace.removeChangeListener(b.saveConnectionsListener);b.saveConnectionsListener=null}fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BUBBLE_OPEN))(b.sourceBlock,
a,"mutator"))}})}getBubble(){return this.miniWorkspaceBubble}getMiniWorkspaceConfig(){let a;const b={disable:!1,media:this.sourceBlock.workspace.options.pathToMedia,rtl:this.sourceBlock.RTL,renderer:this.sourceBlock.workspace.options.renderer,rendererOverrides:(a=this.sourceBlock.workspace.options.rendererOverrides)!=null?a:void 0};this.flyoutBlockTypes.length&&(b.toolbox={kind:"flyoutToolbox",contents:this.flyoutBlockTypes.map(c=>({kind:"block",type:c}))});return b}getAnchorLocation(){const a=SIZE$$module$build$src$core$icons$mutator_icon/
2;return Coordinate$$module$build$src$core$utils$coordinate.sum(this.workspaceLocation,new Coordinate$$module$build$src$core$utils$coordinate(a,a))}getBubbleOwnerRect(){const a=this.sourceBlock.getSvgRoot().getBBox();return new Rect$$module$build$src$core$utils$rect(a.y,a.y+a.height,a.x,a.x+a.width)}createRootBlock(){if(!this.sourceBlock.decompose)throw Error("Blocks with mutator icons must include a decompose method");this.rootBlock=this.sourceBlock.decompose(this.miniWorkspaceBubble.getWorkspace());
for(var a of this.rootBlock.getDescendants(!1))a.queueRender();this.rootBlock.setMovable(!1);this.rootBlock.setDeletable(!1);let b,c,d,e;a=(e=(b=this.miniWorkspaceBubble)==null?void 0:(c=b.getWorkspace())==null?void 0:(d=c.getFlyout())==null?void 0:d.getWidth())!=null?e:0;this.rootBlock.moveBy(this.rootBlock.RTL?-(a+WORKSPACE_MARGIN$$module$build$src$core$icons$mutator_icon):WORKSPACE_MARGIN$$module$build$src$core$icons$mutator_icon,WORKSPACE_MARGIN$$module$build$src$core$icons$mutator_icon)}addSaveConnectionsListener(){this.sourceBlock.saveConnections&&
this.rootBlock&&(this.saveConnectionsListener=()=>{this.sourceBlock.saveConnections&&this.rootBlock&&this.sourceBlock.saveConnections(this.rootBlock)},this.saveConnectionsListener(),this.sourceBlock.workspace.addChangeListener(this.saveConnectionsListener))}createMiniWorkspaceChangeListener(){return a=>{$.MutatorIcon$$module$build$src$core$icons$mutator_icon.isIgnorableMutatorEvent(a)||this.updateWorkspacePid||(this.updateWorkspacePid=setTimeout(()=>{this.updateWorkspacePid=null;this.recomposeSourceBlock()},
0))}}static isIgnorableMutatorEvent(a){return a.isUiEvent||isBlockCreate$$module$build$src$core$events$predicates(a)||isBlockChange$$module$build$src$core$events$predicates(a)&&a.element==="disabled"}recomposeSourceBlock(){if(this.rootBlock){if(!this.sourceBlock.compose)throw Error("Blocks with mutator icons must include a compose method");var a=$.getGroup$$module$build$src$core$events$utils();a||$.setGroup$$module$build$src$core$events$utils(!0);var b=BlockChange$$module$build$src$core$events$events_block_change.getExtraBlockState_(this.sourceBlock);
this.sourceBlock.compose(this.rootBlock);var c=BlockChange$$module$build$src$core$events$events_block_change.getExtraBlockState_(this.sourceBlock);b!==c&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CHANGE))(this.sourceBlock,"mutation",null,b,c));$.setGroup$$module$build$src$core$events$utils(a)}}getWorkspace(){let a;return(a=this.miniWorkspaceBubble)==null?void 0:a.getWorkspace()}};
$.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE=IconType$$module$build$src$core$icons$icon_types.MUTATOR;$.MutatorIcon$$module$build$src$core$icons$mutator_icon.WEIGHT=1;var module$build$src$core$icons$mutator_icon={};module$build$src$core$icons$mutator_icon.MutatorIcon=$.MutatorIcon$$module$build$src$core$icons$mutator_icon;var allExtensions$$module$build$src$core$extensions=Object.create(null),TEST_ONLY$$module$build$src$core$extensions={allExtensions:allExtensions$$module$build$src$core$extensions};$.register$$module$build$src$core$extensions("parent_tooltip_when_inline",extensionParentTooltip$$module$build$src$core$extensions);var module$build$src$core$extensions={TEST_ONLY:TEST_ONLY$$module$build$src$core$extensions};module$build$src$core$extensions.apply=apply$$module$build$src$core$extensions;
module$build$src$core$extensions.buildTooltipForDropdown=$.buildTooltipForDropdown$$module$build$src$core$extensions;module$build$src$core$extensions.buildTooltipWithFieldText=$.buildTooltipWithFieldText$$module$build$src$core$extensions;module$build$src$core$extensions.isRegistered=isRegistered$$module$build$src$core$extensions;module$build$src$core$extensions.register=$.register$$module$build$src$core$extensions;module$build$src$core$extensions.registerMixin=$.registerMixin$$module$build$src$core$extensions;
module$build$src$core$extensions.registerMutator=$.registerMutator$$module$build$src$core$extensions;module$build$src$core$extensions.runAfterPageLoad=runAfterPageLoad$$module$build$src$core$extensions;module$build$src$core$extensions.unregister=unregister$$module$build$src$core$extensions;var KeyCodes$$module$build$src$core$utils$keycodes;
(function(a){a[a.WIN_KEY_FF_LINUX=0]="WIN_KEY_FF_LINUX";a[a.MAC_ENTER=3]="MAC_ENTER";a[a.BACKSPACE=8]="BACKSPACE";a[a.TAB=9]="TAB";a[a.NUM_CENTER=12]="NUM_CENTER";a[a.ENTER=13]="ENTER";a[a.SHIFT=16]="SHIFT";a[a.CTRL=17]="CTRL";a[a.ALT=18]="ALT";a[a.PAUSE=19]="PAUSE";a[a.CAPS_LOCK=20]="CAPS_LOCK";a[a.ESC=27]="ESC";a[a.SPACE=32]="SPACE";a[a.PAGE_UP=33]="PAGE_UP";a[a.PAGE_DOWN=34]="PAGE_DOWN";a[a.END=35]="END";a[a.HOME=36]="HOME";a[a.LEFT=37]="LEFT";a[a.UP=38]="UP";a[a.RIGHT=39]="RIGHT";a[a.DOWN=40]=
"DOWN";a[a.PLUS_SIGN=43]="PLUS_SIGN";a[a.PRINT_SCREEN=44]="PRINT_SCREEN";a[a.INSERT=45]="INSERT";a[a.DELETE=46]="DELETE";a[a.ZERO=48]="ZERO";a[a.ONE=49]="ONE";a[a.TWO=50]="TWO";a[a.THREE=51]="THREE";a[a.FOUR=52]="FOUR";a[a.FIVE=53]="FIVE";a[a.SIX=54]="SIX";a[a.SEVEN=55]="SEVEN";a[a.EIGHT=56]="EIGHT";a[a.NINE=57]="NINE";a[a.FF_SEMICOLON=59]="FF_SEMICOLON";a[a.FF_EQUALS=61]="FF_EQUALS";a[a.FF_DASH=173]="FF_DASH";a[a.FF_HASH=163]="FF_HASH";a[a.QUESTION_MARK=63]="QUESTION_MARK";a[a.AT_SIGN=64]="AT_SIGN";
a[a.A=65]="A";a[a.B=66]="B";a[a.C=67]="C";a[a.D=68]="D";a[a.E=69]="E";a[a.F=70]="F";a[a.G=71]="G";a[a.H=72]="H";a[a.I=73]="I";a[a.J=74]="J";a[a.K=75]="K";a[a.L=76]="L";a[a.M=77]="M";a[a.N=78]="N";a[a.O=79]="O";a[a.P=80]="P";a[a.Q=81]="Q";a[a.R=82]="R";a[a.S=83]="S";a[a.T=84]="T";a[a.U=85]="U";a[a.V=86]="V";a[a.W=87]="W";a[a.X=88]="X";a[a.Y=89]="Y";a[a.Z=90]="Z";a[a.META=91]="META";a[a.WIN_KEY_RIGHT=92]="WIN_KEY_RIGHT";a[a.CONTEXT_MENU=93]="CONTEXT_MENU";a[a.NUM_ZERO=96]="NUM_ZERO";a[a.NUM_ONE=97]=
"NUM_ONE";a[a.NUM_TWO=98]="NUM_TWO";a[a.NUM_THREE=99]="NUM_THREE";a[a.NUM_FOUR=100]="NUM_FOUR";a[a.NUM_FIVE=101]="NUM_FIVE";a[a.NUM_SIX=102]="NUM_SIX";a[a.NUM_SEVEN=103]="NUM_SEVEN";a[a.NUM_EIGHT=104]="NUM_EIGHT";a[a.NUM_NINE=105]="NUM_NINE";a[a.NUM_MULTIPLY=106]="NUM_MULTIPLY";a[a.NUM_PLUS=107]="NUM_PLUS";a[a.NUM_MINUS=109]="NUM_MINUS";a[a.NUM_PERIOD=110]="NUM_PERIOD";a[a.NUM_DIVISION=111]="NUM_DIVISION";a[a.F1=112]="F1";a[a.F2=113]="F2";a[a.F3=114]="F3";a[a.F4=115]="F4";a[a.F5=116]="F5";a[a.F6=
117]="F6";a[a.F7=118]="F7";a[a.F8=119]="F8";a[a.F9=120]="F9";a[a.F10=121]="F10";a[a.F11=122]="F11";a[a.F12=123]="F12";a[a.NUMLOCK=144]="NUMLOCK";a[a.SCROLL_LOCK=145]="SCROLL_LOCK";a[a.FIRST_MEDIA_KEY=166]="FIRST_MEDIA_KEY";a[a.LAST_MEDIA_KEY=183]="LAST_MEDIA_KEY";a[a.SEMICOLON=186]="SEMICOLON";a[a.DASH=189]="DASH";a[a.EQUALS=187]="EQUALS";a[a.COMMA=188]="COMMA";a[a.PERIOD=190]="PERIOD";a[a.SLASH=191]="SLASH";a[a.APOSTROPHE=192]="APOSTROPHE";a[a.TILDE=192]="TILDE";a[a.SINGLE_QUOTE=222]="SINGLE_QUOTE";
a[a.OPEN_SQUARE_BRACKET=219]="OPEN_SQUARE_BRACKET";a[a.BACKSLASH=220]="BACKSLASH";a[a.CLOSE_SQUARE_BRACKET=221]="CLOSE_SQUARE_BRACKET";a[a.WIN_KEY=224]="WIN_KEY";a[a.MAC_FF_META=224]="MAC_FF_META";a[a.MAC_WK_CMD_LEFT=91]="MAC_WK_CMD_LEFT";a[a.MAC_WK_CMD_RIGHT=93]="MAC_WK_CMD_RIGHT";a[a.WIN_IME=229]="WIN_IME";a[a.VK_NONAME=252]="VK_NONAME";a[a.PHANTOM=255]="PHANTOM"})(KeyCodes$$module$build$src$core$utils$keycodes||(KeyCodes$$module$build$src$core$utils$keycodes={}));
var module$build$src$core$utils$keycodes={};module$build$src$core$utils$keycodes.KeyCodes=KeyCodes$$module$build$src$core$utils$keycodes;var module$build$src$core$utils$svg_paths={};module$build$src$core$utils$svg_paths.arc=arc$$module$build$src$core$utils$svg_paths;module$build$src$core$utils$svg_paths.curve=curve$$module$build$src$core$utils$svg_paths;module$build$src$core$utils$svg_paths.line=line$$module$build$src$core$utils$svg_paths;module$build$src$core$utils$svg_paths.lineOnAxis=lineOnAxis$$module$build$src$core$utils$svg_paths;module$build$src$core$utils$svg_paths.lineTo=lineTo$$module$build$src$core$utils$svg_paths;
module$build$src$core$utils$svg_paths.moveBy=moveBy$$module$build$src$core$utils$svg_paths;module$build$src$core$utils$svg_paths.moveTo=moveTo$$module$build$src$core$utils$svg_paths;module$build$src$core$utils$svg_paths.point=point$$module$build$src$core$utils$svg_paths;var module$build$src$core$utils={};module$build$src$core$utils.Coordinate=Coordinate$$module$build$src$core$utils$coordinate;module$build$src$core$utils.KeyCodes=KeyCodes$$module$build$src$core$utils$keycodes;module$build$src$core$utils.Rect=Rect$$module$build$src$core$utils$rect;module$build$src$core$utils.Size=Size$$module$build$src$core$utils$size;module$build$src$core$utils.Svg=Svg$$module$build$src$core$utils$svg;module$build$src$core$utils.aria=module$build$src$core$utils$aria;
module$build$src$core$utils.array=module$build$src$core$utils$array;module$build$src$core$utils.browserEvents=module$build$src$core$browser_events;module$build$src$core$utils.colour=module$build$src$core$utils$colour;module$build$src$core$utils.deprecation=module$build$src$core$utils$deprecation;module$build$src$core$utils.dom=module$build$src$core$utils$dom;module$build$src$core$utils.extensions=module$build$src$core$extensions;module$build$src$core$utils.idGenerator=module$build$src$core$utils$idgenerator;
module$build$src$core$utils.math=module$build$src$core$utils$math;module$build$src$core$utils.object=module$build$src$core$utils$object;module$build$src$core$utils.parsing=module$build$src$core$utils$parsing;module$build$src$core$utils.string=module$build$src$core$utils$string;module$build$src$core$utils.style=module$build$src$core$utils$style;module$build$src$core$utils.svgMath=module$build$src$core$utils$svg_math;module$build$src$core$utils.svgPaths=module$build$src$core$utils$svg_paths;
module$build$src$core$utils.toolbox=module$build$src$core$utils$toolbox;module$build$src$core$utils.userAgent=module$build$src$core$utils$useragent;module$build$src$core$utils.xml=module$build$src$core$utils$xml;var TextInputBubble$$module$build$src$core$bubbles$textinput_bubble=class extends Bubble$$module$build$src$core$bubbles$bubble{constructor(a,b,c,d){super(a,b,c,void 0,d);this.workspace=a;this.anchor=b;this.ownerRect=c;this.owner=d;this.resizePointerMoveListener=this.resizePointerUpListener=null;this.sizeChangeListeners=[];this.locationChangeListeners=[];this.DEFAULT_SIZE=new Size$$module$build$src$core$utils$size(160+Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER,80+Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER);
this.MIN_SIZE=new Size$$module$build$src$core$utils$size(45+Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER,20+Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER);this.editable=!0;addClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyTextInputBubble");this.editor=new CommentEditor$$module$build$src$core$comments$comment_editor(a,this.id,()=>{$.getFocusManager$$module$build$src$core$focus_manager().focusNode(this)});this.contentContainer.appendChild(this.editor.getDom());
this.resizeGroup=this.createResizeHandle(this.svgRoot,a);this.setSize(this.DEFAULT_SIZE,!0)}getText(){return this.editor.getText()}setText(a){this.editor.setText(a)}setEditable(a){this.editable=a;this.editor.setEditable(a)}isEditable(){return this.editable}addTextChangeListener(a){this.editor.addTextChangeListener(a)}addSizeChangeListener(a){this.sizeChangeListeners.push(a)}addLocationChangeListener(a){this.locationChangeListeners.push(a)}createResizeHandle(a,b){a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,
{"class":"blocklyResizeHandle",href:`${b.options.pathToMedia}resize-handle.svg`},a);conditionalBind$$module$build$src$core$browser_events(a,"pointerdown",this,this.onResizePointerDown);return a}setSize(a,b=!1){a.width=Math.max(a.width,this.MIN_SIZE.width);a.height=Math.max(a.height,this.MIN_SIZE.height);const c=a.width-Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER,d=a.height-Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER;this.editor.updateSize(new Size$$module$build$src$core$utils$size(c,
d),new Size$$module$build$src$core$utils$size(0,0));this.editor.getDom().setAttribute("x",`${Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER/2}`);this.editor.getDom().setAttribute("y",`${Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER/2}`);this.resizeGroup.setAttribute("y",`${d}`);this.workspace.RTL?this.resizeGroup.setAttribute("x",`${-Bubble$$module$build$src$core$bubbles$bubble.DOUBLE_BORDER}`):this.resizeGroup.setAttribute("x",`${c}`);super.setSize(a,b);this.onSizeChange()}getSize(){return super.getSize()}moveDuringDrag(a){super.moveDuringDrag(a);
this.onLocationChange()}setPositionRelativeToAnchor(a,b){super.setPositionRelativeToAnchor(a,b);this.onLocationChange()}positionByRect(a=new Rect$$module$build$src$core$utils$rect(0,0,0,0)){super.positionByRect(a);this.onLocationChange()}onResizePointerDown(a){this.bringToFront();isRightButton$$module$build$src$core$browser_events(a)||(start$$module$build$src$core$utils$drag(this.workspace,a,new Coordinate$$module$build$src$core$utils$coordinate(this.workspace.RTL?-this.getSize().width:this.getSize().width,
this.getSize().height)),this.resizePointerUpListener=conditionalBind$$module$build$src$core$browser_events(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=conditionalBind$$module$build$src$core$browser_events(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff());a.stopPropagation()}onResizePointerUp(a){clearTouchIdentifier$$module$build$src$core$touch();this.resizePointerUpListener&&(unbind$$module$build$src$core$browser_events(this.resizePointerUpListener),
this.resizePointerUpListener=null);this.resizePointerMoveListener&&(unbind$$module$build$src$core$browser_events(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(a){a=move$$module$build$src$core$utils$drag(this.workspace,a);this.setSize(new Size$$module$build$src$core$utils$size(this.workspace.RTL?-a.x:a.x,a.y),!1);this.onSizeChange()}onSizeChange(){for(const a of this.sizeChangeListeners)a()}onLocationChange(){for(const a of this.locationChangeListeners)a()}getEditor(){return this.editor}};
register$$module$build$src$core$css("\n.blocklyTextInputBubble .blocklyTextarea {\n  background-color: var(--commentFillColour);\n  border: 0;\n  box-sizing: border-box;\n  display: block;\n  outline: 0;\n  padding: 5px;\n  resize: none;\n  width: 100%;\n  height: 100%;\n}\n");var module$build$src$core$bubbles$textinput_bubble={};module$build$src$core$bubbles$textinput_bubble.TextInputBubble=TextInputBubble$$module$build$src$core$bubbles$textinput_bubble;var ConnectionType$$module$build$src$core$connection_type;(function(a){a[a.INPUT_VALUE=1]="INPUT_VALUE";a[a.OUTPUT_VALUE=2]="OUTPUT_VALUE";a[a.NEXT_STATEMENT=3]="NEXT_STATEMENT";a[a.PREVIOUS_STATEMENT=4]="PREVIOUS_STATEMENT"})(ConnectionType$$module$build$src$core$connection_type||(ConnectionType$$module$build$src$core$connection_type={}));var module$build$src$core$connection_type={};module$build$src$core$connection_type.ConnectionType=ConnectionType$$module$build$src$core$connection_type;var ConnectionDB$$module$build$src$core$connection_db=class{constructor(a){this.connectionChecker=a;this.connections=[]}addConnection(a,b){b=this.calculateIndexForYPos(b);this.connections.splice(b,0,a)}findIndexOfConnection(a,b){if(!this.connections.length)return-1;const c=this.calculateIndexForYPos(b);if(c>=this.connections.length)return-1;b=a.y;let d=c;for(;d>=0&&this.connections[d].y===b;){if(this.connections[d]===a)return d;d--}for(d=c;d<this.connections.length&&this.connections[d].y===b;){if(this.connections[d]===
a)return d;d++}return-1}calculateIndexForYPos(a){if(!this.connections.length)return 0;let b=0,c=this.connections.length;for(;b<c;){const d=Math.floor((b+c)/2);if(this.connections[d].y<a)b=d+1;else if(this.connections[d].y>a)c=d;else{b=d;break}}return b}removeConnection(a,b){a=this.findIndexOfConnection(a,b);if(a===-1)throw Error("Unable to find connection in connectionDB.");this.connections.splice(a,1)}getNeighbours(a,b){function c(l){const m=e-d[l].x,n=f-d[l].y;Math.sqrt(m*m+n*n)<=b&&k.push(d[l]);
return n<b}const d=this.connections,e=a.x,f=a.y;a=0;let g=d.length-2,h=g;for(;a<h;)d[h].y<f?a=h:g=h,h=Math.floor((a+g)/2);const k=[];g=a=h;if(d.length){for(;a>=0&&c(a);)a--;do g++;while(g<d.length&&c(g))}return k}isInYRange(a,b,c){return Math.abs(this.connections[a].y-b)<=c}searchForClosest(a,b,c){if(!this.connections.length)return{connection:null,radius:b};const d=a.y,e=a.x;a.x=e+c.x;a.y=d+c.y;var f=this.calculateIndexForYPos(a.y);c=null;let g=b,h,k=f-1;for(;k>=0&&this.isInYRange(k,a.y,b);)h=this.connections[k],
this.connectionChecker.canConnect(a,h,!0,g)&&(c=h,g=h.distanceFrom(a)),k--;for(;f<this.connections.length&&this.isInYRange(f,a.y,b);)h=this.connections[f],this.connectionChecker.canConnect(a,h,!0,g)&&(c=h,g=h.distanceFrom(a)),f++;a.x=e;a.y=d;return{connection:c,radius:g}}static init(a){const b=[];b[ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE]=new ConnectionDB$$module$build$src$core$connection_db(a);b[ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE]=new ConnectionDB$$module$build$src$core$connection_db(a);
b[ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT]=new ConnectionDB$$module$build$src$core$connection_db(a);b[ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT]=new ConnectionDB$$module$build$src$core$connection_db(a);return b}},module$build$src$core$connection_db={};module$build$src$core$connection_db.ConnectionDB=ConnectionDB$$module$build$src$core$connection_db;var Selected$$module$build$src$core$events$events_selected=class extends UiBase$$module$build$src$core$events$events_ui_base{constructor(a,b,c){super(c);this.type=EventType$$module$build$src$core$events$type.SELECTED;this.oldElementId=a!=null?a:void 0;this.newElementId=b!=null?b:void 0}toJson(){const a=super.toJson();a.oldElementId=this.oldElementId;a.newElementId=this.newElementId;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new Selected$$module$build$src$core$events$events_selected);
b.oldElementId=a.oldElementId;b.newElementId=a.newElementId;return b}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.SELECTED,Selected$$module$build$src$core$events$events_selected);var module$build$src$core$events$events_selected={};module$build$src$core$events$events_selected.Selected=Selected$$module$build$src$core$events$events_selected;var BlockDelete$$module$build$src$core$events$events_block_delete=class extends BlockBase$$module$build$src$core$events$events_block_base{constructor(a){super(a);this.type=EventType$$module$build$src$core$events$type.BLOCK_DELETE;if(a){if(a.getParent())throw Error("Connected blocks cannot be deleted.");a.isShadow()&&(this.recordUndo=!1);this.oldXml=blockToDomWithXY$$module$build$src$core$xml(a);this.ids=getDescendantIds$$module$build$src$core$events$utils(a);this.wasShadow=a.isShadow();this.oldJson=
save$$module$build$src$core$serialization$blocks(a,{addCoordinates:!0})}}toJson(){const a=super.toJson();if(!this.oldXml)throw Error("The old block XML is undefined. Either pass a block to the constructor, or call fromJson");if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(this.wasShadow===void 0)throw Error("Whether the block was a shadow is undefined. Either pass a block to the constructor, or call fromJson");if(!this.oldJson)throw Error("The old block JSON is undefined. Either pass a block to the constructor, or call fromJson");
a.oldXml=domToText$$module$build$src$core$xml(this.oldXml);a.ids=this.ids;a.wasShadow=this.wasShadow;a.oldJson=this.oldJson;this.recordUndo||(a.recordUndo=this.recordUndo);return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new BlockDelete$$module$build$src$core$events$events_block_delete);b.oldXml=$.textToDom$$module$build$src$core$utils$xml(a.oldXml);b.ids=a.ids;b.wasShadow=a.wasShadow||b.oldXml.tagName.toLowerCase()==="shadow";b.oldJson=a.oldJson;a.recordUndo!==void 0&&(b.recordUndo=
a.recordUndo);return b}run(a){const b=this.getEventWorkspace_();if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(!this.oldJson)throw Error("The old block JSON is undefined. Either pass a block to the constructor, or call fromJson");if(a)for(a=0;a<this.ids.length;a++){const c=this.ids[a],d=b.getBlockById(c);d?d.dispose(!1):c===this.blockId&&console.warn("Can't delete non-existent block: "+c)}else append$$module$build$src$core$serialization$blocks(this.oldJson,
b)}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.BLOCK_DELETE,BlockDelete$$module$build$src$core$events$events_block_delete);var module$build$src$core$events$events_block_delete={};module$build$src$core$events$events_block_delete.BlockDelete=BlockDelete$$module$build$src$core$events$events_block_delete;var Connection$$module$build$src$core$connection=class{constructor(a,b){this.type=b;this.targetConnection=null;this.disposed=!1;this.shadowDom=this.check=null;this.y=this.x=0;this.shadowState=null;this.sourceBlock_=a;if(a.id.includes("_connection"))throw Error("Connection ID indicator is contained in block ID. This will cause "+`problems with focus: ${a.id}.`);this.id=`${a.id}_connection_${getNextUniqueId$$module$build$src$core$utils$idgenerator()}`}connect_(a){const b=ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE,
c=this.getSourceBlock();var d=a.getSourceBlock();a.isConnected()&&a.disconnectInternal(!1);let e;if(this.isConnected()){const g=this.stashShadowState(),h=this.targetBlock();h.isShadow()?h.dispose(!1):(this.disconnectInternal(),e=h);this.applyShadowState(g)}let f;isEnabled$$module$build$src$core$events$utils()&&(f=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_MOVE))(d),f.setReason(["connect"]));connectReciprocally$$module$build$src$core$connection(this,
a);d.setParent(c);f&&(f.recordNew(),fire$$module$build$src$core$events$utils(f));if(e&&(a=this.type===b?e.outputConnection:e.previousConnection))if(d=Connection$$module$build$src$core$connection.getConnectionForOrphanedConnection(d,a))a.connect(d);else a.onFailedConnect(this)}dispose(){if(this.isConnected()){this.isSuperior()&&this.setShadowStateInternal();const a=this.targetBlock();a&&!a.isDeadOrDying()&&a.unplug()}this.disposed=!0}getSourceBlock(){return this.sourceBlock_}isSuperior(){return this.type===
ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE||this.type===ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT}isConnected(){return!!this.targetConnection}getConnectionChecker(){return this.sourceBlock_.workspace.connectionChecker}onFailedConnect(a){}connect(a){if(this.targetConnection===a)return!0;if(this.getConnectionChecker().canConnect(this,a,!1)){const b=$.getGroup$$module$build$src$core$events$utils();b||$.setGroup$$module$build$src$core$events$utils(!0);
this.isSuperior()?this.connect_(a):a.connect_(this);$.setGroup$$module$build$src$core$events$utils(b)}return this.isConnected()}disconnect(){this.disconnectInternal()}disconnectInternal(a=!0){const {parentConnection:b,childConnection:c}=this.getParentAndChildConnections();if(!b||!c)throw Error("Source connection not connected.");const d=$.getGroup$$module$build$src$core$events$utils();d||$.setGroup$$module$build$src$core$events$utils(!0);let e;isEnabled$$module$build$src$core$events$utils()&&(e=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_MOVE))(c.getSourceBlock()),
e.setReason(["disconnect"]));const f=this.targetConnection;f&&(f.targetConnection=null);this.targetConnection=null;a&&c.getSourceBlock().setParent(null);e&&(e.recordNew(),fire$$module$build$src$core$events$utils(e));c.getSourceBlock().isShadow()||b.respawnShadow_();$.setGroup$$module$build$src$core$events$utils(d)}getParentAndChildConnections(){return this.targetConnection?this.isSuperior()?{parentConnection:this,childConnection:this.targetConnection}:{parentConnection:this.targetConnection,childConnection:this}:
{}}respawnShadow_(){this.createShadowBlock(!0)}reconnect(a,b){if(this.getSourceBlock().isDeadOrDying())return!1;var c;b=(c=a.getInput(b))==null?void 0:c.connection;c=this.targetBlock();return c&&c!==a||!b||b.targetConnection===this?!1:(b.isConnected()&&b.disconnect(),b.connect(this),!0)}targetBlock(){if(this.isConnected()){let a,b;return(b=(a=this.targetConnection)==null?void 0:a.getSourceBlock())!=null?b:null}return null}onCheckChanged_(){!this.isConnected()||this.targetConnection&&this.getConnectionChecker().canConnect(this,
this.targetConnection,!1)||(this.isSuperior()?this.targetBlock():this.sourceBlock_).unplug()}setCheck(a){a?(Array.isArray(a)||(a=[a]),this.check=a,this.onCheckChanged_()):this.check=null;return this}getCheck(){return this.check}setShadowDom(a){this.setShadowStateInternal({shadowDom:a})}getShadowDom(a){return a&&this.targetBlock().isShadow()?blockToDom$$module$build$src$core$xml(this.targetBlock()):this.shadowDom}setShadowState(a){this.setShadowStateInternal({shadowState:a})}getShadowState(a){return a&&
this.targetBlock()&&this.targetBlock().isShadow()?save$$module$build$src$core$serialization$blocks(this.targetBlock()):this.shadowState}neighbours(a){return[]}getParentInput(){let a=null;const b=this.sourceBlock_.inputList;for(let c=0;c<b.length;c++)if(b[c].connection===this){a=b[c];break}return a}toString(){const a=this.sourceBlock_;if(!a)return"Orphan Connection";if(a.outputConnection===this)var b="Output Connection of ";else if(a.previousConnection===this)b="Previous Connection of ";else if(a.nextConnection===
this)b="Next Connection of ";else{b=null;for(let c=0,d;d=a.inputList[c];c++)if(d.connection===this){b=d;break}if(b)b='Input "'+b.name+'" connection on ';else return console.warn("Connection not actually connected to sourceBlock_"),"Orphan Connection"}return b+a.toDevString()}stashShadowState(){const a=this.getShadowDom(!0),b=this.getShadowState(!0);this.shadowState=this.shadowDom=null;return{shadowDom:a,shadowState:b}}applyShadowState({shadowDom:a,shadowState:b}){this.shadowDom=a;this.shadowState=
b}setShadowStateInternal({shadowDom:a=null,shadowState:b=null}={}){this.shadowDom=a;this.shadowState=b;this.getSourceBlock().isDeadOrDying()||((a=this.targetBlock())?a.isShadow()?(a.dispose(!1),this.respawnShadow_(),this.targetBlock()&&this.targetBlock().isShadow()&&this.serializeShadow(this.targetBlock())):(a=this.createShadowBlock(!1),this.serializeShadow(a),a&&a.dispose(!1)):(this.respawnShadow_(),this.targetBlock()&&this.targetBlock().isShadow()&&this.serializeShadow(this.targetBlock())))}createShadowBlock(a){var b=
this.getSourceBlock();const c=this.getShadowState(),d=this.getShadowDom();if(b.isDeadOrDying()||!c&&!d)return null;if(c)return b=appendInternal$$module$build$src$core$serialization$blocks(c,b.workspace,{parentConnection:a?this:void 0,isShadow:!0,recordUndo:!1});if(d){b=domToBlockInternal$$module$build$src$core$xml(d,b.workspace);if(a)if(this.type===ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE){if(!b.outputConnection)throw Error("Shadow block is missing an output connection");
if(!this.connect(b.outputConnection))throw Error("Could not connect shadow block to connection");}else if(this.type===ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT){if(!b.previousConnection)throw Error("Shadow block is missing previous connection");if(!this.connect(b.previousConnection))throw Error("Could not connect shadow block to connection");}else throw Error("Cannot connect a shadow block to a previous/output connection");return b}return null}serializeShadow(a){a&&(this.shadowDom=
blockToDom$$module$build$src$core$xml(a),this.shadowState=save$$module$build$src$core$serialization$blocks(a))}static getConnectionForOrphanedConnection(a,b){if(b.type===ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE)return getConnectionForOrphanedOutput$$module$build$src$core$connection(a,b.getSourceBlock());a=a.lastConnectionInStack(!0);const c=b.getConnectionChecker();return a&&c.canConnect(b,a,!1)?a:null}};Connection$$module$build$src$core$connection.CAN_CONNECT=0;
Connection$$module$build$src$core$connection.REASON_SELF_CONNECTION=1;Connection$$module$build$src$core$connection.REASON_WRONG_TYPE=2;Connection$$module$build$src$core$connection.REASON_TARGET_NULL=3;Connection$$module$build$src$core$connection.REASON_CHECKS_FAILED=4;Connection$$module$build$src$core$connection.REASON_DIFFERENT_WORKSPACES=5;Connection$$module$build$src$core$connection.REASON_SHADOW_PARENT=6;Connection$$module$build$src$core$connection.REASON_DRAG_CHECKS_FAILED=7;
Connection$$module$build$src$core$connection.REASON_PREVIOUS_AND_OUTPUT=8;var module$build$src$core$connection={};module$build$src$core$connection.Connection=Connection$$module$build$src$core$connection;var DuplicateIconType$$module$build$src$core$icons$exceptions=class extends Error{constructor(a){super(`Tried to append an icon of type ${a.getType()} when an icon of `+"that type already exists on the block. Use getIcon to access the existing icon.");this.icon=a}},module$build$src$core$icons$exceptions={};module$build$src$core$icons$exceptions.DuplicateIconType=DuplicateIconType$$module$build$src$core$icons$exceptions;(function(a){a[a.LEFT=-1]="LEFT";a[a.CENTRE=0]="CENTRE";a[a.RIGHT=1]="RIGHT"})($.Align$$module$build$src$core$inputs$align||($.Align$$module$build$src$core$inputs$align={}));var module$build$src$core$inputs$align={};module$build$src$core$inputs$align.Align=$.Align$$module$build$src$core$inputs$align;var FieldLabel$$module$build$src$core$field_label=class extends Field$$module$build$src$core$field{constructor(a,b,c){super(Field$$module$build$src$core$field.SKIP_SETUP);this.class=null;this.EDITABLE=!1;this.maxDisplayLength=Infinity;a!==Field$$module$build$src$core$field.SKIP_SETUP&&(c?this.configure_(c):this.class=b||null,this.setValue(a))}configure_(a){super.configure_(a);a.class&&(this.class=a.class)}initView(){this.createTextElement_();this.class&&addClass$$module$build$src$core$utils$dom(this.getTextElement(),
this.class);this.fieldGroup_&&addClass$$module$build$src$core$utils$dom(this.fieldGroup_,"blocklyLabelField")}doClassValidation_(a){return a===null||a===void 0?null:`${a}`}setClass(a){this.textElement_&&(this.class&&removeClass$$module$build$src$core$utils$dom(this.textElement_,this.class),a&&addClass$$module$build$src$core$utils$dom(this.textElement_,a));this.class=a}static fromJson(a){return new this(replaceMessageReferences$$module$build$src$core$utils$parsing(a.text),void 0,a)}};
register$$module$build$src$core$field_registry("field_label",FieldLabel$$module$build$src$core$field_label);FieldLabel$$module$build$src$core$field_label.prototype.DEFAULT_VALUE="";var module$build$src$core$field_label={};module$build$src$core$field_label.FieldLabel=FieldLabel$$module$build$src$core$field_label;var COLLAPSE_CHARS$$module$build$src$core$internal_constants=30,OPPOSITE_TYPE$$module$build$src$core$internal_constants=[];OPPOSITE_TYPE$$module$build$src$core$internal_constants[ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE]=ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE;OPPOSITE_TYPE$$module$build$src$core$internal_constants[ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE]=ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE;
OPPOSITE_TYPE$$module$build$src$core$internal_constants[ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT]=ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT;OPPOSITE_TYPE$$module$build$src$core$internal_constants[ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT]=ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT;
var RENAME_VARIABLE_ID$$module$build$src$core$internal_constants="RENAME_VARIABLE_ID",DELETE_VARIABLE_ID$$module$build$src$core$internal_constants="DELETE_VARIABLE_ID",module$build$src$core$internal_constants={COLLAPSE_CHARS:COLLAPSE_CHARS$$module$build$src$core$internal_constants,DELETE_VARIABLE_ID:DELETE_VARIABLE_ID$$module$build$src$core$internal_constants,OPPOSITE_TYPE:OPPOSITE_TYPE$$module$build$src$core$internal_constants,RENAME_VARIABLE_ID:RENAME_VARIABLE_ID$$module$build$src$core$internal_constants};var BUMP_RANDOMNESS$$module$build$src$core$rendered_connection=10,RenderedConnection$$module$build$src$core$rendered_connection=class extends Connection$$module$build$src$core$connection{constructor(a,b){super(a,b);this.highlighted=!1;this.targetConnection=null;this.db=a.workspace.connectionDBList[b];this.dbOpposite=a.workspace.connectionDBList[OPPOSITE_TYPE$$module$build$src$core$internal_constants[b]];this.offsetInBlock=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.trackedState=
RenderedConnection$$module$build$src$core$rendered_connection.TrackedState.WILL_TRACK}dispose(){super.dispose();this.trackedState===RenderedConnection$$module$build$src$core$rendered_connection.TrackedState.TRACKED&&this.db.removeConnection(this,this.y);let a,b;(b=(a=this.sourceBlock_.pathObject).removeConnectionHighlight)==null||b.call(a,this)}getSourceBlock(){return super.getSourceBlock()}targetBlock(){return super.targetBlock()}distanceFrom(a){const b=this.x-a.x;a=this.y-a.y;return Math.sqrt(b*
b+a*a)}bumpAwayFrom(a,b=!1){if(!this.sourceBlock_.workspace.isDragging()){var c=$.config$$module$build$src$core$config.snapRadius+Math.floor(Math.random()*BUMP_RANDOMNESS$$module$build$src$core$rendered_connection),d=$.config$$module$build$src$core$config.snapRadius+Math.floor(Math.random()*BUMP_RANDOMNESS$$module$build$src$core$rendered_connection),e=a.sourceBlock_.getRootBlock(),f=this.sourceBlock_.getRootBlock();if(!e.isInFlyout&&!f.isInFlyout){var g=!0;if(f.isMovable())e.isMovable()&&b&&(d=-d);
else if(e.isMovable())g=!1,c=-c,d=-d;else return;b=g?a:this;a=g?this:a;e=g?f:e;e.RTL&&(c=-c);e.moveBy(b.x+c-a.x,b.y+d-a.y,["bump"])}}}moveTo(a,b){let c=!1;this.trackedState===RenderedConnection$$module$build$src$core$rendered_connection.TrackedState.WILL_TRACK?(this.db.addConnection(this,b),this.trackedState=RenderedConnection$$module$build$src$core$rendered_connection.TrackedState.TRACKED,c=!0):this.trackedState===RenderedConnection$$module$build$src$core$rendered_connection.TrackedState.TRACKED&&
(this.db.removeConnection(this,this.y),this.db.addConnection(this,b),c=!0);this.x=a;this.y=b;return c}moveBy(a,b){return this.moveTo(this.x+a,this.y+b)}moveToOffset(a){return this.moveTo(a.x+this.offsetInBlock.x,a.y+this.offsetInBlock.y)}setOffsetInBlock(a,b){this.offsetInBlock.x=a;this.offsetInBlock.y=b}getOffsetInBlock(){return this.offsetInBlock}tightenEfficiently(){var a=this.targetConnection;const b=this.targetBlock();a&&b&&(a=Coordinate$$module$build$src$core$utils$coordinate.difference(this.offsetInBlock,
a.offsetInBlock),b.translate(a.x,a.y))}closest(a,b){return this.dbOpposite.searchForClosest(this,a,b)}highlight(){this.highlighted=!0;const a=this.findHighlightSvg();a&&(a.style.display="")}unhighlight(){this.highlighted=!1;const a=this.findHighlightSvg();a&&(a.style.display="none")}isHighlighted(){return this.highlighted}setTracking(a){a&&this.trackedState===RenderedConnection$$module$build$src$core$rendered_connection.TrackedState.TRACKED||!a&&this.trackedState===RenderedConnection$$module$build$src$core$rendered_connection.TrackedState.UNTRACKED||
this.sourceBlock_.isInFlyout||(a?(this.db.addConnection(this,this.y),this.trackedState=RenderedConnection$$module$build$src$core$rendered_connection.TrackedState.TRACKED):(this.trackedState===RenderedConnection$$module$build$src$core$rendered_connection.TrackedState.TRACKED&&this.db.removeConnection(this,this.y),this.trackedState=RenderedConnection$$module$build$src$core$rendered_connection.TrackedState.UNTRACKED))}stopTrackingAll(){this.setTracking(!1);if(this.targetConnection){const a=this.targetBlock().getDescendants(!1);
for(let b=0;b<a.length;b++){const c=a[b],d=c.getConnections_(!0);for(let e=0;e<d.length;e++)d[e].setTracking(!1);for(const e of c.getIcons())hasBubble$$module$build$src$core$interfaces$i_has_bubble(e)&&e.setBubbleVisible(!1)}}}startTrackingAll(){this.setTracking(!0);let a=[];if(this.type!==ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE&&this.type!==ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT)return a;const b=this.targetBlock();if(b){let c;b.isCollapsed()?
(c=[],b.outputConnection&&c.push(b.outputConnection),b.nextConnection&&c.push(b.nextConnection),b.previousConnection&&c.push(b.previousConnection)):c=b.getConnections_(!0);for(let d=0;d<c.length;d++)a.push(...c[d].startTrackingAll());a.length||(a=[b])}return a}onFailedConnect(a){const b=this.getSourceBlock();if(getRecordUndo$$module$build$src$core$events$utils()){const c=$.getGroup$$module$build$src$core$events$utils();setTimeout(function(){b.isDisposed()||b.getParent()||($.setGroup$$module$build$src$core$events$utils(c),
this.bumpAwayFrom(a),$.setGroup$$module$build$src$core$events$utils(!1))}.bind(this),$.config$$module$build$src$core$config.bumpDelay)}}disconnectInternal(a=!0){const {parentConnection:b,childConnection:c}=this.getParentAndChildConnections();if(b&&c){var d=$.getGroup$$module$build$src$core$events$utils();d||$.setGroup$$module$build$src$core$events$utils(!0);var e=b.getSourceBlock(),f=c.getSourceBlock();super.disconnectInternal(a);e.queueRender();f.updateDisabled();f.queueRender();f.getSvgRoot().style.display=
"block";$.setGroup$$module$build$src$core$events$utils(d)}}respawnShadow_(){super.respawnShadow_();const a=this.targetBlock();a&&(a.initSvg(),a.queueRender())}neighbours(a){return this.dbOpposite.getNeighbours(this,a)}connect_(a){super.connect_(a);var b=this.getSourceBlock();a=a.getSourceBlock();b.updateDisabled();a.updateDisabled();a.queueRender();if(b=b.getInputWithBlock(a))b=b.isVisible(),a.getSvgRoot().style.display=b?"block":"none"}onCheckChanged_(){!this.isConnected()||this.targetConnection&&
this.getConnectionChecker().canConnect(this,this.targetConnection,!1)||(this.isSuperior()?this.targetBlock():this.sourceBlock_).unplug()}setCheck(a){super.setCheck(a);this.sourceBlock_.queueRender();return this}showContextMenu(a){const b=ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.getContextMenuOptions({focusedNode:this},a);if(b.length){var c=this.getSourceBlock(),d=c.workspace;if(a instanceof PointerEvent)var e=new Coordinate$$module$build$src$core$utils$coordinate(a.clientX,
a.clientY);else e=new Coordinate$$module$build$src$core$utils$coordinate(this.x,this.y),e=wsToScreenCoordinates$$module$build$src$core$utils$svg_math(d,e).translate(c.RTL?-5:5,5);show$$module$build$src$core$contextmenu(a,b,c.RTL,d,e)}}getFocusableElement(){const a=this.findHighlightSvg();if(a)return a;throw Error("No highlight SVG found corresponding to this connection.");}getFocusableTree(){return this.getSourceBlock().workspace}onNodeFocus(){this.highlight();this.getSourceBlock().workspace.scrollBoundsIntoView(this.getSourceBlock().getBoundingRectangleWithoutChildren())}onNodeBlur(){this.unhighlight()}canBeFocused(){return!0}findHighlightSvg(){return document.getElementById(this.id)}};
(function(a){a=a.TrackedState||(a.TrackedState={});a[a.WILL_TRACK=-1]="WILL_TRACK";a[a.UNTRACKED=0]="UNTRACKED";a[a.TRACKED=1]="TRACKED"})(RenderedConnection$$module$build$src$core$rendered_connection||(RenderedConnection$$module$build$src$core$rendered_connection={}));var TrackedState$$module$build$src$core$rendered_connection=RenderedConnection$$module$build$src$core$rendered_connection.TrackedState,module$build$src$core$rendered_connection={};
module$build$src$core$rendered_connection.RenderedConnection=RenderedConnection$$module$build$src$core$rendered_connection;module$build$src$core$rendered_connection.TrackedState=TrackedState$$module$build$src$core$rendered_connection;var Input$$module$build$src$core$inputs$input=class{constructor(a,b){this.name=a;this.sourceBlock=b;this.fieldRow=[];this.align=$.Align$$module$build$src$core$inputs$align.LEFT;this.visible=!0;this.type=$.inputTypes$$module$build$src$core$inputs$input_types.CUSTOM;this.connection=null}getSourceBlock(){return this.sourceBlock}appendField(a,b){this.insertFieldAt(this.fieldRow.length,a,b);return this}insertFieldAt(a,b,c){if(a<0||a>this.fieldRow.length)throw Error("index "+a+" out of bounds.");if(!(b||
b===""&&c))return a;typeof b==="string"&&(b=$.fromJson$$module$build$src$core$field_registry({type:"field_label",text:b}));b.setSourceBlock(this.sourceBlock);this.sourceBlock.initialized&&this.initField(b);b.name=c;b.setVisible(this.isVisible());b.prefixField&&(a=this.insertFieldAt(a,b.prefixField));this.fieldRow.splice(a,0,b);a++;b.suffixField&&(a=this.insertFieldAt(a,b.suffixField));this.sourceBlock.rendered&&this.sourceBlock.queueRender();return a}removeField(a,b){for(let c=0,d;d=this.fieldRow[c];c++)if(d.name===
a)return d.dispose(),this.fieldRow.splice(c,1),this.sourceBlock.rendered&&this.sourceBlock.queueRender(),!0;if(b)return!1;throw Error('Field "'+a+'" not found.');}isVisible(){return this.visible}setVisible(a){let b=[];if(this.visible===a)return b;this.visible=a;for(let c=0,d;d=this.fieldRow[c];c++)d.setVisible(a);if(this.connection&&this.connection instanceof RenderedConnection$$module$build$src$core$rendered_connection){a?b=this.connection.startTrackingAll():this.connection.stopTrackingAll();const c=
this.connection.targetBlock();c&&(c.getSvgRoot().style.display=a?"block":"none")}return b}markDirty(){for(let a=0,b;b=this.fieldRow[a];a++)b.markDirty()}setCheck(a){if(!this.connection)throw Error("This input does not have a connection.");this.connection.setCheck(a);return this}setAlign(a){this.align=a;this.sourceBlock.rendered&&this.sourceBlock.queueRender();return this}setShadowDom(a){if(!this.connection)throw Error("This input does not have a connection.");this.connection.setShadowDom(a);return this}getShadowDom(){if(!this.connection)throw Error("This input does not have a connection.");
return this.connection.getShadowDom()}init(){for(const a of this.fieldRow)a.init()}initModel(){for(const a of this.fieldRow)a.initModel()}initField(a){this.sourceBlock.rendered?a.init():a.initModel()}dispose(){for(let a=0,b;b=this.fieldRow[a];a++)b.dispose();this.connection&&this.connection.dispose()}makeConnection(a){return this.sourceBlock.makeConnection_(a)}},module$build$src$core$inputs$input={};module$build$src$core$inputs$input.Input=Input$$module$build$src$core$inputs$input;var DummyInput$$module$build$src$core$inputs$dummy_input=class extends Input$$module$build$src$core$inputs$input{constructor(a,b){super(a,b);this.name=a;this.type=$.inputTypes$$module$build$src$core$inputs$input_types.DUMMY}},module$build$src$core$inputs$dummy_input={};module$build$src$core$inputs$dummy_input.DummyInput=DummyInput$$module$build$src$core$inputs$dummy_input;var EndRowInput$$module$build$src$core$inputs$end_row_input=class extends Input$$module$build$src$core$inputs$input{constructor(a,b){super(a,b);this.name=a;this.type=$.inputTypes$$module$build$src$core$inputs$input_types.END_ROW}},module$build$src$core$inputs$end_row_input={};module$build$src$core$inputs$end_row_input.EndRowInput=EndRowInput$$module$build$src$core$inputs$end_row_input;var StatementInput$$module$build$src$core$inputs$statement_input=class extends Input$$module$build$src$core$inputs$input{constructor(a,b){if(!a)throw Error("Statement inputs must have a non-empty name");super(a,b);this.name=a;this.type=$.inputTypes$$module$build$src$core$inputs$input_types.STATEMENT;this.connection=this.makeConnection(ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT)}},module$build$src$core$inputs$statement_input={};
module$build$src$core$inputs$statement_input.StatementInput=StatementInput$$module$build$src$core$inputs$statement_input;var module$build$src$core$inputs$value_input;$.ValueInput$$module$build$src$core$inputs$value_input=class extends Input$$module$build$src$core$inputs$input{constructor(a,b){if(!a)throw Error("Value inputs must have a non-empty name");super(a,b);this.name=a;this.type=$.inputTypes$$module$build$src$core$inputs$input_types.VALUE;this.connection=this.makeConnection(ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE)}};module$build$src$core$inputs$value_input={};
module$build$src$core$inputs$value_input.ValueInput=$.ValueInput$$module$build$src$core$inputs$value_input;var module$build$src$core$interfaces$i_icon={};module$build$src$core$interfaces$i_icon.isIcon=isIcon$$module$build$src$core$interfaces$i_icon;var module$build$src$core$interfaces$i_comment_icon={};module$build$src$core$interfaces$i_comment_icon.isCommentIcon=isCommentIcon$$module$build$src$core$interfaces$i_comment_icon;var Block$$module$build$src$core$block=class{constructor(a,b,c){this.data=null;this.disposed=!1;this.hue=null;this.colour_="#000000";this.styleName_="";this.suppressPrefixSuffix=!1;this.previousConnection=this.nextConnection=this.outputConnection=null;this.inputList=[];this.icons=[];this.disabledReasons=new Set;this.tooltip="";this.contextMenu=!0;this.parentBlock_=null;this.childBlocks_=[];this.editable=this.movable=this.deletable=!0;this.collapsed_=this.shadow=!1;this.outputShape_=null;this.rendered=
this.isInsertionMarker_=this.initialized=this.disposing=!1;this.onchangeWrapper=this.helpUrl=null;this.statementInputCount=0;this.workspace=a;this.id=c&&!a.getBlockById(c)?c:genUid$$module$build$src$core$utils$idgenerator();a.setBlockById(this.id,this);this.xy=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.isInFlyout=a.isFlyout;this.isInMutator=a.isMutator;this.RTL=a.RTL;if(b){this.type=b;c=Blocks$$module$build$src$core$blocks[b];if(!c||typeof c!=="object")throw TypeError("Invalid block definition for type: "+
b);Object.assign(this,c)}a.addTopBlock(this);a.addTypedBlock(this);new.target===Block$$module$build$src$core$block&&this.doInit_()}doInit_(){const a=$.getGroup$$module$build$src$core$events$utils();a||$.setGroup$$module$build$src$core$events$utils(!0);const b=getRecordUndo$$module$build$src$core$events$utils();try{typeof this.init==="function"&&($.setRecordUndo$$module$build$src$core$events$utils(!1),this.init(),$.setRecordUndo$$module$build$src$core$events$utils(b)),isEnabled$$module$build$src$core$events$utils()&&
fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CREATE))(this))}finally{$.setGroup$$module$build$src$core$events$utils(a),$.setRecordUndo$$module$build$src$core$events$utils(b)}this.inputsInlineDefault=this.inputsInline;typeof this.onchange==="function"&&this.setOnChange(this.onchange)}dispose(a=!1){this.disposing=!0;this.onchangeWrapper&&this.workspace.removeChangeListener(this.onchangeWrapper);this.unplug(a);
isEnabled$$module$build$src$core$events$utils()&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_DELETE))(this));this.workspace.removeTopBlock(this);this.disposeInternal()}disposeInternal(){this.disposing=!0;this.onchangeWrapper&&this.workspace.removeChangeListener(this.onchangeWrapper);this.workspace.removeTypedBlock(this);this.workspace.removeBlockById(this.id);typeof this.destroy==="function"&&this.destroy();
this.childBlocks_.forEach(a=>a.disposeInternal());this.inputList.forEach(a=>a.dispose());this.inputList.length=0;this.getConnections_(!0).forEach(a=>a.dispose());this.disposed=!0}isDeadOrDying(){return this.disposing||this.disposed}initModel(){if(!this.initialized){for(const a of this.inputList)a.initModel();this.initialized=!0}}unplug(a){this.outputConnection&&this.unplugFromRow(a);this.previousConnection&&this.unplugFromStack(a)}unplugFromRow(a){let b=null,c;if((c=this.outputConnection)==null?0:
c.isConnected())b=this.outputConnection.targetConnection,this.outputConnection.disconnect();b&&a&&(a=this.getOnlyValueConnection())&&a.isConnected()&&!a.targetBlock().isShadow()&&(a=a.targetConnection,a==null||a.disconnect(),this.workspace.connectionChecker.canConnect(a,b,!1)?b.connect(a):a==null||a.onFailedConnect(b))}getOnlyValueConnection(){let a=null;for(let b=0;b<this.inputList.length;b++){const c=this.inputList[b].connection;if(c&&c.type===ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE&&
c.targetConnection){if(a)return null;a=c}}return a}unplugFromStack(a){let b=null,c;if((c=this.previousConnection)==null?0:c.isConnected())b=this.previousConnection.targetConnection,this.previousConnection.disconnect();if(a){for(a=this.getNextBlock();a&&(a.isShadow()||!a.isMovable());)a=a.getNextBlock();if(a){var d,e,f,g;a=(g=(d=a.previousConnection)==null?void 0:(e=d.targetBlock())==null?void 0:(f=e.nextConnection)==null?void 0:f.targetConnection)!=null?g:null;a==null||a.disconnect();b&&this.workspace.connectionChecker.canConnect(b,
a,!1)&&b.connect(a)}}}getConnections_(a){a=[];this.outputConnection&&a.push(this.outputConnection);this.previousConnection&&a.push(this.previousConnection);this.nextConnection&&a.push(this.nextConnection);for(let b=0,c;c=this.inputList[b];b++)c.connection&&a.push(c.connection);return a}lastConnectionInStack(a){let b=this.nextConnection;for(;b;){const c=b.targetBlock();if(!c||a&&c.isShadow())return b;b=c.nextConnection}return null}bumpNeighbours(){}getParent(){return this.parentBlock_}getInputWithBlock(a){for(let b=
0,c;c=this.inputList[b];b++)if(c.connection&&c.connection.targetBlock()===a)return c;return null}getSurroundParent(){let a=this,b;do if(b=a,a=a.getParent(),!a)return null;while(a.getNextBlock()===b);return a}getNextBlock(){return this.nextConnection&&this.nextConnection.targetBlock()}getPreviousBlock(){return this.previousConnection&&this.previousConnection.targetBlock()}getRootBlock(){let a,b=this;do a=b,b=a.parentBlock_;while(b);return a}getTopStackBlock(){let a=this,b;do b=a.getPreviousBlock();
while(b&&b.getNextBlock()===a&&(a=b));return a}getChildren(a){if(!a)return this.childBlocks_;a=[];for(let c=0,d;d=this.inputList[c];c++)if(d.connection){var b=d.connection.targetBlock();b&&a.push(b)}(b=this.getNextBlock())&&a.push(b);return a}setParent(a){if(a!==this.parentBlock_){var b=this.previousConnection&&this.previousConnection.targetBlock()||this.outputConnection&&this.outputConnection.targetBlock(),c=!!b;if(c&&a&&b!==a)throw Error("Block connected to superior one that is not new parent.");
if(!c&&a)throw Error("Block not connected to new parent.");if(c&&!a)throw Error("Cannot set parent to null while block is still connected to superior block.");this.parentBlock_?removeElem$$module$build$src$core$utils$array(this.parentBlock_.childBlocks_,this):this.workspace.removeTopBlock(this);(this.parentBlock_=a)?a.childBlocks_.push(this):this.workspace.addTopBlock(this)}}getDescendants(a){const b=[this],c=this.getChildren(a);for(let d,e=0;d=c[e];e++)b.push(...d.getDescendants(a));return b}isDeletable(){return this.deletable&&
!this.isInFlyout&&!this.shadow&&!this.isDeadOrDying()&&!this.workspace.isReadOnly()}isOwnDeletable(){return this.deletable}setDeletable(a){this.deletable=a}isMovable(){return this.movable&&!this.isInFlyout&&!this.shadow&&!this.isDeadOrDying()&&!this.workspace.isReadOnly()}isOwnMovable(){return this.movable}setMovable(a){this.movable=a}isDuplicatable(){return this.workspace.hasBlockLimits()?this.workspace.isCapacityAvailable(getBlockTypeCounts$$module$build$src$core$common(this,!0)):!0}isShadow(){return this.shadow}setShadow(a){this.shadow=
a}isInsertionMarker(){return this.isInsertionMarker_}setInsertionMarker(a){this.isInsertionMarker_=a}isEditable(){return this.editable&&!this.isDeadOrDying()&&!this.workspace.isReadOnly()}isOwnEditable(){return this.editable}setEditable(a){this.editable=a;for(const b of this.getFields())b.updateEditable()}isDisposed(){return this.disposed}isSimpleReporter(){if(!this.outputConnection)return!1;for(const a of this.inputList)if(a.connection||a.fieldRow.length>1)return!1;return!0}getMatchingConnection(a,
b){const c=this.getConnections_(!0);a=a.getConnections_(!0);if(c.length!==a.length)throw Error("Connection lists did not match in length.");for(let d=0;d<a.length;d++)if(a[d]===b)return c[d];return null}setHelpUrl(a){this.helpUrl=a}setTooltip(a){this.tooltip=a}getTooltip(){return getTooltipOfObject$$module$build$src$core$tooltip(this)}getColour(){return this.colour_}getStyleName(){return this.styleName_}getHue(){return this.hue}setColour(a){a=parseBlockColour$$module$build$src$core$utils$parsing(a);
this.hue=a.hue;this.colour_=a.hex}setStyle(a){this.styleName_=a}setOnChange(a){if(a&&typeof a!=="function")throw Error("onchange must be a function.");this.onchangeWrapper&&this.workspace.removeChangeListener(this.onchangeWrapper);this.onchange=a;this.onchangeWrapper=a.bind(this);this.workspace.addChangeListener(this.onchangeWrapper)}getField(a){if(typeof a!=="string")throw TypeError("Block.prototype.getField expects a string with the field name but received "+(a===void 0?"nothing":a+" of type "+
typeof a)+" instead");for(const b of this.getFields())if(b.name===a)return b;return null}*getFields(){for(const a of this.inputList)for(const b of a.fieldRow)yield b}getVars(){const a=[];for(const b of this.getFields())b.referencesVariables()&&a.push(b.getValue());return a}getVarModels(){const a=[];for(const b of this.getFields())if(b.referencesVariables()){const c=this.workspace.getVariableById(b.getValue());c&&a.push(c)}return a}updateVarName(a){for(const b of this.getFields())b.referencesVariables()&&
a.getId()===b.getValue()&&b.refreshVariableName()}renameVarById(a,b){for(const c of this.getFields())c.referencesVariables()&&a===c.getValue()&&c.setValue(b)}getFieldValue(a){return(a=this.getField(a))?a.getValue():null}setFieldValue(a,b){const c=this.getField(b);if(!c)throw Error('Field "'+b+'" not found.');c.setValue(a)}setPreviousStatement(a,b){if(a)b===void 0&&(b=null),this.previousConnection||(this.previousConnection=this.makeConnection_(ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT)),
this.previousConnection.setCheck(b);else if(this.previousConnection){if(this.previousConnection.isConnected())throw Error("Must disconnect previous statement before removing connection.");this.previousConnection.dispose();this.previousConnection=null}}setNextStatement(a,b){if(a)b===void 0&&(b=null),this.nextConnection||(this.nextConnection=this.makeConnection_(ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT)),this.nextConnection.setCheck(b);else if(this.nextConnection){if(this.nextConnection.isConnected())throw Error("Must disconnect next statement before removing connection.");
this.nextConnection.dispose();this.nextConnection=null}}setOutput(a,b){if(a)b===void 0&&(b=null),this.outputConnection||(this.outputConnection=this.makeConnection_(ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE)),this.outputConnection.setCheck(b);else if(this.outputConnection){if(this.outputConnection.isConnected())throw Error("Must disconnect output value before removing connection.");this.outputConnection.dispose();this.outputConnection=null}}setInputsInline(a){this.inputsInline!==
a&&(fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CHANGE))(this,"inline",null,this.inputsInline,a)),this.inputsInline=a)}getInputsInline(){if(this.inputsInline!==void 0)return this.inputsInline;for(var a=1;a<this.inputList.length;a++)if(this.inputList[a-1]instanceof DummyInput$$module$build$src$core$inputs$dummy_input&&this.inputList[a]instanceof DummyInput$$module$build$src$core$inputs$dummy_input)return!1;
for(a=1;a<this.inputList.length;a++)if(this.inputList[a-1]instanceof $.ValueInput$$module$build$src$core$inputs$value_input&&this.inputList[a]instanceof DummyInput$$module$build$src$core$inputs$dummy_input)return!0;for(a=0;a<this.inputList.length;a++)if(this.inputList[a]instanceof EndRowInput$$module$build$src$core$inputs$end_row_input)return!0;return!1}setOutputShape(a){this.outputShape_=a}getOutputShape(){return this.outputShape_}isEnabled(){return this.disabledReasons.size===0}setDisabledReason(a,
b){a||this.workspace.options.disable||!this.hasDisabledReason(MANUALLY_DISABLED$$module$build$src$core$constants)||b==MANUALLY_DISABLED$$module$build$src$core$constants||this.setDisabledReason(!1,MANUALLY_DISABLED$$module$build$src$core$constants);this.disabledReasons.has(b)!==a&&(a?this.disabledReasons.add(b):this.disabledReasons.delete(b),a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CHANGE))(this,"disabled",null,!a,a),a.setDisabledReason(b),fire$$module$build$src$core$events$utils(a))}getInheritedDisabled(){let a=
this.getSurroundParent();for(;a;){if(!a.isEnabled())return!0;a=a.getSurroundParent()}return!1}hasDisabledReason(a){return this.disabledReasons.has(a)}getDisabledReasons(){return this.disabledReasons}isCollapsed(){return this.collapsed_}setCollapsed(a){this.collapsed_!==a&&(fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CHANGE))(this,"collapsed",null,this.collapsed_,a)),this.collapsed_=a)}toString(a,b){b=this.toTokens(b);
for(let d=2;d<b.length;d++)b[d-2]==="("&&b[d]===")"&&(b[d-2]=b[d-1],b.splice(d-1,2));let c="";b=b.reduce((d,e)=>{d=d+(c==="("||e===")"?"":" ")+e;c=e[e.length-1];return d},"");b=b.trim()||"???";a&&b.length>a&&(b=b.substring(0,a-3)+"...");return b}toTokens(a="?"){const b=[];for(const d of this.inputList)if(d.name!=COLLAPSED_INPUT_NAME$$module$build$src$core$constants){for(const e of d.fieldRow)b.push(e.getText());if(d.connection){const e=d.connection.targetBlock();if(e){var c=d.connection;let f=c.getCheck();
!f&&c.targetConnection&&(f=c.targetConnection.getCheck());(c=!!f&&(f.includes("Boolean")||f.includes("Number")))&&b.push("(");b.push(...e.toTokens(a));c&&b.push(")")}else b.push(a)}}return b}appendValueInput(a){return this.appendInput(new $.ValueInput$$module$build$src$core$inputs$value_input(a,this))}appendStatementInput(a){this.statementInputCount++;return this.appendInput(new StatementInput$$module$build$src$core$inputs$statement_input(a,this))}appendDummyInput(a=""){return this.appendInput(new DummyInput$$module$build$src$core$inputs$dummy_input(a,
this))}appendEndRowInput(a=""){return this.appendInput(new EndRowInput$$module$build$src$core$inputs$end_row_input(a,this))}appendInput(a){this.inputList.push(a);return a}appendInputFromRegistry(a,b){return(a=getClass$$module$build$src$core$registry(Type$$module$build$src$core$registry.INPUT,a,!1))?this.appendInput(new a(b,this)):null}jsonInit(a){var b=a.type?'Block "'+a.type+'": ':"";if(a.output&&a.previousStatement)throw Error(b+"Must not have both an output and a previousStatement.");for(var c=
0;a["args"+c];){if(a["message"+c]===void 0)throw Error(b+`args${c} must have a corresponding message (message${c}).`);c++}a.style&&a.style.hat&&(this.hat=a.style.hat,a.style=null);if(a.style&&a.colour)throw Error(b+"Must not have both a colour and a style.");a.style?this.jsonInitStyle(a,b):this.jsonInitColour(a,b);for(c=0;a["message"+c]!==void 0;)this.interpolate(a["message"+c],a["args"+c]||[],a["implicitAlign"+c]||a["lastDummyAlign"+c],b),c++;a.inputsInline!==void 0&&($.disable$$module$build$src$core$events$utils(),
this.setInputsInline(a.inputsInline),$.enable$$module$build$src$core$events$utils());a.output!==void 0&&this.setOutput(!0,a.output);a.outputShape!==void 0&&this.setOutputShape(a.outputShape);a.previousStatement!==void 0&&this.setPreviousStatement(!0,a.previousStatement);a.nextStatement!==void 0&&this.setNextStatement(!0,a.nextStatement);a.tooltip!==void 0&&(c=replaceMessageReferences$$module$build$src$core$utils$parsing(a.tooltip),this.setTooltip(c));a.enableContextMenu!==void 0&&(this.contextMenu=
!!a.enableContextMenu);a.suppressPrefixSuffix!==void 0&&(this.suppressPrefixSuffix=!!a.suppressPrefixSuffix);a.helpUrl!==void 0&&(c=replaceMessageReferences$$module$build$src$core$utils$parsing(a.helpUrl),this.setHelpUrl(c));typeof a.extensions==="string"&&(console.warn(b+"JSON attribute 'extensions' should be an array of strings. Found raw string in JSON for '"+a.type+"' block."),a.extensions=[a.extensions]);a.mutator!==void 0&&apply$$module$build$src$core$extensions(a.mutator,this,!0);a=a.extensions;
if(Array.isArray(a))for(b=0;b<a.length;b++)apply$$module$build$src$core$extensions(a[b],this,!1)}jsonInitColour(a,b){if("colour"in a)if(a.colour===void 0)console.warn(b+"Undefined colour value.");else{a=a.colour;try{this.setColour(a)}catch(c){console.warn(b+"Illegal colour value: ",a)}}}jsonInitStyle(a,b){a=a.style;try{this.setStyle(a)}catch(c){console.warn(b+"Style does not exist: ",a)}}mixin(a,b){if(b!==void 0&&typeof b!=="boolean")throw Error("opt_disableCheck must be a boolean if provided");if(!b){b=
[];for(const c in a)this[c]!==void 0&&b.push(c);if(b.length)throw Error("Mixin will overwrite block members: "+JSON.stringify(b));}Object.assign(this,a)}interpolate(a,b,c,d){a=tokenizeInterpolation$$module$build$src$core$utils$parsing(a);this.validateTokens(a,b.length);b=this.interpolateArguments(a,b,c);c=[];for(let e=0,f;f=b[e];e++)if(this.isInputKeyword(f.type)){if(a=this.inputFromJson(f,d)){for(let g=0,h;h=c[g];g++)a.appendField(h[0],h[1]);c.length=0}}else(a=this.fieldFromJson(f))&&c.push([a,f.name])}validateTokens(a,
b){const c=[];let d=0;for(let e=0;e<a.length;e++){const f=a[e];if(typeof f==="number"){if(f<1||f>b)throw Error('Block "'+this.type+'": Message index %'+f+" out of range.");if(c[f])throw Error('Block "'+this.type+'": Message index %'+f+" duplicated.");c[f]=!0;d++}}if(d!==b)throw Error('Block "'+this.type+'": Message does not reference all '+b+" arg(s).");}interpolateArguments(a,b,c){const d=[];for(let f=0;f<a.length;f++){var e=a[f];typeof e==="number"&&(e=b[e-1]);if(typeof e==="string")if(e==="\n")e=
{type:"input_end_row"},c&&(e.align=c);else if(e=this.stringToFieldJson(e),!e)continue;d.push(e)}(a=d.length)&&!this.isInputKeyword(d[a-1].type)&&(a={type:"input_dummy"},c&&(a.align=c),d.push(a));return d}fieldFromJson(a){const b=$.fromJson$$module$build$src$core$field_registry(a);return!b&&a.alt?typeof a.alt==="string"?(a=this.stringToFieldJson(a.alt))?this.fieldFromJson(a):null:this.fieldFromJson(a.alt):b}inputFromJson(a,b){var c={LEFT:$.Align$$module$build$src$core$inputs$align.LEFT,RIGHT:$.Align$$module$build$src$core$inputs$align.RIGHT,
CENTRE:$.Align$$module$build$src$core$inputs$align.CENTRE,CENTER:$.Align$$module$build$src$core$inputs$align.CENTRE};let d;switch(a.type){case "input_value":d=this.appendValueInput(a.name);break;case "input_statement":d=this.appendStatementInput(a.name);break;case "input_dummy":d=this.appendDummyInput(a.name);break;case "input_end_row":d=this.appendEndRowInput(a.name);break;default:d=this.appendInputFromRegistry(a.type,a.name)}if(!d)return null;a.check&&d.setCheck(a.check);a.align&&(c=c[a.align.toUpperCase()],
c===void 0?console.warn(b+"Illegal align value: ",a.align):d.setAlign(c));return d}isInputKeyword(a){return a==="input_value"||a==="input_statement"||a==="input_dummy"||a==="input_end_row"||hasItem$$module$build$src$core$registry(Type$$module$build$src$core$registry.INPUT,a)}stringToFieldJson(a){return(a=a.trim())?{type:"field_label",text:a}:null}moveInputBefore(a,b){if(a!==b){var c=-1,d=b?-1:this.inputList.length;for(let e=0,f;f=this.inputList[e];e++)if(f.name===a){if(c=e,d!==-1)break}else if(b&&
f.name===b&&(d=e,c!==-1))break;if(c===-1)throw Error('Named input "'+a+'" not found.');if(d===-1)throw Error('Reference input "'+b+'" not found.');this.moveNumberedInputBefore(c,d)}}moveNumberedInputBefore(a,b){if(a===b)throw Error("Can't move input to itself.");if(a>=this.inputList.length)throw RangeError("Input index "+a+" out of bounds.");if(b>this.inputList.length)throw RangeError("Reference input "+b+" out of bounds.");const c=this.inputList[a];this.inputList.splice(a,1);a<b&&b--;this.inputList.splice(b,
0,c)}removeInput(a,b){for(let c=0,d;d=this.inputList[c];c++)if(d.name===a)return d instanceof StatementInput$$module$build$src$core$inputs$statement_input&&this.statementInputCount--,d.dispose(),this.inputList.splice(c,1),!0;if(b)return!1;throw Error("Input not found: "+a);}getInput(a){for(let b=0,c;c=this.inputList[b];b++)if(c.name===a)return c;return null}getInputTargetBlock(a){return(a=this.getInput(a))&&a.connection&&a.connection.targetBlock()}getCommentText(){let a,b;return(b=(a=this.getIcon(IconType$$module$build$src$core$icons$icon_types.COMMENT))==
null?void 0:a.getText())!=null?b:null}setCommentText(a){var b;let c;const d=(c=(b=this.getIcon(IconType$$module$build$src$core$icons$icon_types.COMMENT))==null?void 0:b.getText())!=null?c:null;if(d!==a){if(a!==null){b=this.getIcon(IconType$$module$build$src$core$icons$icon_types.COMMENT);if(!b){b=getClass$$module$build$src$core$registry(Type$$module$build$src$core$registry.ICON,IconType$$module$build$src$core$icons$icon_types.COMMENT.toString(),!1);if(!b)throw Error("No comment icon class is registered, so a comment cannot be set");
b=new b(this);if(!isCommentIcon$$module$build$src$core$interfaces$i_comment_icon(b))throw Error("The class registered as a comment icon does not conform to the ICommentIcon interface");b=this.addIcon(b)}$.disable$$module$build$src$core$events$utils();b.setText(a);$.enable$$module$build$src$core$events$utils()}else this.removeIcon(IconType$$module$build$src$core$icons$icon_types.COMMENT);fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CHANGE))(this,
"comment",null,d,a))}}setWarningText(a,b){}setMutator(a){}addIcon(a){if(this.hasIcon(a.getType()))throw new DuplicateIconType$$module$build$src$core$icons$exceptions(a);this.icons.push(a);this.icons.sort((b,c)=>b.getWeight()-c.getWeight());return a}removeIcon(a){if(!this.hasIcon(a))return!1;let b;(b=this.getIcon(a))==null||b.dispose();this.icons=this.icons.filter(c=>!c.getType().equals(a));return!0}hasIcon(a){return this.icons.some(b=>b.getType().equals(a))}getIcon(a){return a instanceof IconType$$module$build$src$core$icons$icon_types?
this.icons.find(b=>b.getType().equals(a)):this.icons.find(b=>b.getType().toString()===a)}getIcons(){return[...this.icons]}getRelativeToSurfaceXY(){return this.xy}moveBy(a,b,c){if(this.parentBlock_)throw Error("Block has parent");const d=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_MOVE))(this);c&&d.setReason(c);this.xy.translate(a,b);d.recordNew();fire$$module$build$src$core$events$utils(d)}makeConnection_(a){return new Connection$$module$build$src$core$connection(this,
a)}allInputsFilled(a){a===void 0&&(a=!0);if(!a&&this.isShadow())return!1;for(let c=0,d;d=this.inputList[c];c++)if(d.connection){var b=d.connection.targetBlock();if(!b||!b.allInputsFilled(a))return!1}return(b=this.getNextBlock())?b.allInputsFilled(a):!0}toDevString(){let a=this.type?'"'+this.type+'" block':"Block";this.id&&(a+=' (id="'+this.id+'")');return a}};Block$$module$build$src$core$block.COLLAPSED_INPUT_NAME=COLLAPSED_INPUT_NAME$$module$build$src$core$constants;
Block$$module$build$src$core$block.COLLAPSED_FIELD_NAME=COLLAPSED_FIELD_NAME$$module$build$src$core$constants;var module$build$src$core$block={};module$build$src$core$block.Block=Block$$module$build$src$core$block;var disconnectPid$$module$build$src$core$block_animations=null,wobblingBlock$$module$build$src$core$block_animations=null,module$build$src$core$block_animations={};module$build$src$core$block_animations.connectionUiEffect=connectionUiEffect$$module$build$src$core$block_animations;module$build$src$core$block_animations.disconnectUiEffect=disconnectUiEffect$$module$build$src$core$block_animations;module$build$src$core$block_animations.disconnectUiStop=disconnectUiStop$$module$build$src$core$block_animations;
module$build$src$core$block_animations.disposeUiEffect=disposeUiEffect$$module$build$src$core$block_animations;var BlockPaster$$module$build$src$core$clipboard$block_paster=class{paste(a,b,c){if(!b.isCapacityAvailable(a.typeCounts))return null;c&&(a.blockState.x=c.x,a.blockState.y=c.y);c=c||new Coordinate$$module$build$src$core$utils$coordinate(a.blockState.x||0,a.blockState.y||0);$.disable$$module$build$src$core$events$utils();let d;try{d=append$$module$build$src$core$serialization$blocks(a.blockState,b),moveBlockToNotConflict$$module$build$src$core$clipboard$block_paster(d,c)}finally{$.enable$$module$build$src$core$events$utils()}if(!d)return d;
isEnabled$$module$build$src$core$events$utils()&&!d.isShadow()&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CREATE))(d));const e=d;finishQueuedRenders$$module$build$src$core$render_management().then(()=>$.getFocusManager$$module$build$src$core$focus_manager().focusNode(e));return d}};BlockPaster$$module$build$src$core$clipboard$block_paster.TYPE="block";
register$$module$build$src$core$clipboard$registry(BlockPaster$$module$build$src$core$clipboard$block_paster.TYPE,new BlockPaster$$module$build$src$core$clipboard$block_paster);var module$build$src$core$clipboard$block_paster={};module$build$src$core$clipboard$block_paster.BlockPaster=BlockPaster$$module$build$src$core$clipboard$block_paster;module$build$src$core$clipboard$block_paster.moveBlockToNotConflict=moveBlockToNotConflict$$module$build$src$core$clipboard$block_paster;var bumpIntoBounds$$module$build$src$core$bump_objects=bumpObjectIntoBounds$$module$build$src$core$bump_objects,module$build$src$core$bump_objects={};module$build$src$core$bump_objects.bumpIntoBounds=bumpObjectIntoBounds$$module$build$src$core$bump_objects;module$build$src$core$bump_objects.bumpIntoBoundsHandler=bumpIntoBoundsHandler$$module$build$src$core$bump_objects;module$build$src$core$bump_objects.bumpTopObjectsIntoBounds=bumpTopObjectsIntoBounds$$module$build$src$core$bump_objects;var BlockDragStrategy$$module$build$src$core$dragging$block_drag_strategy=class{constructor(a){this.block=a;this.connectionPreviewer=this.connectionCandidate=this.startLoc=this.startChildConn=this.startParentConn=null;this.dragging=!1;this.dragOffset=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.originalEventGroup="";this.workspace=a.workspace}isMovable(){if(this.block.isShadow()){let a,b;return(b=(a=this.block.getParent())==null?void 0:a.isMovable())!=null?b:!1}return this.block.isOwnMovable()&&
!this.block.isDeadOrDying()&&!this.workspace.isReadOnly()&&!this.block.isInFlyout}startDrag(a){if(this.block.isShadow())this.startDraggingShadow(a);else{this.dragging=!0;this.fireDragStartEvent();this.startLoc=this.block.getRelativeToSurfaceXY();this.connectionCandidate=null;this.connectionPreviewer=new (getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.CONNECTION_PREVIEWER,this.workspace.options))(this.block);startTextWidthCache$$module$build$src$core$utils$dom();
this.workspace.setResizesEnabled(!1);disconnectUiStop$$module$build$src$core$block_animations();a=this.shouldHealStack(a);this.shouldDisconnect(a)&&this.disconnectBlock(a);this.block.setDragging(!0);var b;(b=this.workspace.getLayerManager())==null||b.moveToDragLayer(this.block)}}shouldHealStack(a){return!!a&&(a.altKey||a.ctrlKey||a.metaKey)}startDraggingShadow(a){const b=this.block.getParent();if(!b)throw Error("Tried to drag a shadow block with no parent. Shadow blocks should always have parents.");
this.dragOffset=Coordinate$$module$build$src$core$utils$coordinate.difference(b.getRelativeToSurfaceXY(),this.block.getRelativeToSurfaceXY());b.startDrag(a)}shouldDisconnect(a){return!!(this.block.getParent()||a&&this.block.nextConnection&&this.block.nextConnection.targetBlock())}disconnectBlock(a){let b,c,d;this.startParentConn=(d=(b=this.block.outputConnection)==null?void 0:b.targetConnection)!=null?d:(c=this.block.previousConnection)==null?void 0:c.targetConnection;if(a){let e;this.startChildConn=
(e=this.block.nextConnection)==null?void 0:e.targetConnection}this.block.unplug(a);disconnectUiEffect$$module$build$src$core$block_animations(this.block)}fireDragStartEvent(){const a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_DRAG))(this.block,!0,this.block.getDescendants(!1));fire$$module$build$src$core$events$utils(a)}fireDragEndEvent(){const a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_DRAG))(this.block,
!1,this.block.getDescendants(!1));fire$$module$build$src$core$events$utils(a)}fireMoveEvent(){if(!this.block.isDeadOrDying()){var a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_MOVE))(this.block);a.setReason(["drag"]);a.oldCoordinate=this.startLoc;a.recordNew();fire$$module$build$src$core$events$utils(a)}}drag(a){if(this.block.isShadow()){let b;(b=this.block.getParent())==null||b.drag(Coordinate$$module$build$src$core$utils$coordinate.sum(a,this.dragOffset))}else this.block.moveDuringDrag(a),
this.updateConnectionPreview(this.block,Coordinate$$module$build$src$core$utils$coordinate.difference(a,this.startLoc))}updateConnectionPreview(a,b){var c=this.connectionCandidate;const d=this.getConnectionCandidate(a,b);if(d){this.connectionCandidate=b=c&&this.currCandidateIsBetter(c,b,d)?c:d;var {local:e,neighbour:f}=b;b=e.type===ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE||e.type===ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT;var g;c=f.isConnected()&&
!((g=f.targetBlock())==null?0:g.isInsertionMarker());if(b&&c&&!this.orphanCanConnectAtEnd(a,f.targetBlock(),e.type)){let k;(k=this.connectionPreviewer)==null||k.previewReplacement(e,f,f.targetBlock())}else{var h;(h=this.connectionPreviewer)==null||h.previewConnection(e,f)}}else{let k;(k=this.connectionPreviewer)==null||k.hidePreview();this.connectionCandidate=null}}orphanCanConnectAtEnd(a,b,c){return!!Connection$$module$build$src$core$connection.getConnectionForOrphanedConnection(a,c===ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE?
b.outputConnection:b.previousConnection)}currCandidateIsBetter(a,b,c){const {local:d,neighbour:e}=a;a=new Coordinate$$module$build$src$core$utils$coordinate(d.x,d.y);const f=new Coordinate$$module$build$src$core$utils$coordinate(e.x,e.y);b=Coordinate$$module$build$src$core$utils$coordinate.distance(Coordinate$$module$build$src$core$utils$coordinate.sum(a,b),f);return c.distance>b-$.config$$module$build$src$core$config.currentConnectionPreference}getConnectionCandidate(a,b){a=this.getLocalConnections(a);
let c=this.getSearchRadius(),d=null;for(const e of a){const {connection:f,radius:g}=e.closest(c,b);f&&(d={local:e,neighbour:f,distance:g},c=g)}return d}getSearchRadius(){return this.connectionCandidate?$.config$$module$build$src$core$config.connectingSnapRadius:$.config$$module$build$src$core$config.snapRadius}getLocalConnections(a){const b=a.getConnections_(!1),c=a.lastConnectionInStack(!0);c&&c!==a.nextConnection&&b.push(c);return b}endDrag(a){if(this.block.isShadow()){let c;(c=this.block.getParent())==
null||c.endDrag(a)}else{this.originalEventGroup=$.getGroup$$module$build$src$core$events$utils();this.fireDragEndEvent();this.fireMoveEvent();stopTextWidthCache$$module$build$src$core$utils$dom();disconnectUiStop$$module$build$src$core$block_animations();var b;(b=this.connectionPreviewer)==null||b.hidePreview();if(!this.block.isDeadOrDying()&&this.dragging){let c;(c=this.workspace.getLayerManager())==null||c.moveOffDragLayer(this.block,BLOCK$$module$build$src$core$layers);this.block.setDragging(!1)}this.connectionCandidate?
(this.applyConnections(this.connectionCandidate),this.disposeStep()):this.block.queueRender().then(()=>this.disposeStep())}}disposeStep(){const a=$.getGroup$$module$build$src$core$events$utils();$.setGroup$$module$build$src$core$events$utils(this.originalEventGroup);this.block.snapToGrid();let b;(b=this.connectionPreviewer)==null||b.dispose();this.workspace.setResizesEnabled(!0);$.setGroup$$module$build$src$core$events$utils(a)}applyConnections(a){const {local:b,neighbour:c}=a;b.connect(c);const d=
b.isSuperior()?c:b,e=this.block.getRootBlock();finishQueuedRenders$$module$build$src$core$render_management().then(()=>{connectionUiEffect$$module$build$src$core$block_animations(d.getSourceBlock());setTimeout(()=>{e.bringToFront()},0)})}revertDrag(){if(this.block.isShadow()){let c;(c=this.block.getParent())==null||c.revertDrag()}else{var a;(a=this.connectionPreviewer)==null||a.hidePreview();this.connectionCandidate=null;var b;(b=this.startChildConn)==null||b.connect(this.block.nextConnection);if(this.startParentConn)switch(this.startParentConn.type){case ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE:this.startParentConn.connect(this.block.outputConnection);
break;case ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT:this.startParentConn.connect(this.block.previousConnection)}else{this.block.moveTo(this.startLoc,["drag"]);let c;(c=this.workspace.getLayerManager())==null||c.moveOffDragLayer(this.block,BLOCK$$module$build$src$core$layers);bumpObjectIntoBounds$$module$build$src$core$bump_objects(this.workspace,this.workspace.getMetricsManager().getScrollMetrics(!0),this.block)}this.startParentConn=this.startChildConn=null;this.block.setDragging(!1);
this.dragging=!1}}},module$build$src$core$dragging$block_drag_strategy={};module$build$src$core$dragging$block_drag_strategy.BlockDragStrategy=BlockDragStrategy$$module$build$src$core$dragging$block_drag_strategy;var TextBubble$$module$build$src$core$bubbles$text_bubble=class extends Bubble$$module$build$src$core$bubbles$bubble{constructor(a,b,c,d){super(b,c,d);this.text=a;this.workspace=b;this.anchor=c;this.ownerRect=d;this.paragraph=this.stringToSvg(a,this.contentContainer);this.updateBubbleSize();addClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyTextBubble")}getText(){return this.text}setText(a){this.text=a;removeNode$$module$build$src$core$utils$dom(this.paragraph);this.paragraph=this.stringToSvg(a,
this.contentContainer);this.updateBubbleSize()}stringToSvg(a,b){b=this.createParagraph(b);a=this.createTextFragments(b,a);this.workspace.RTL&&this.rightAlignTextFragments(b.getBBox().width,a);return b}createParagraph(a){return createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{"class":"blocklyText blocklyBubbleText blocklyNoPointerEvents",transform:`translate(0,${Bubble$$module$build$src$core$bubbles$bubble.BORDER_WIDTH})`,style:`direction: ${this.workspace.RTL?
"rtl":"ltr"}`},a)}createTextFragments(a,b){let c=1;return b.split("\n").map(d=>{const e=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.TEXT,{y:`${c}em`,x:Bubble$$module$build$src$core$bubbles$bubble.BORDER_WIDTH},a);d=document.createTextNode(d);e.appendChild(d);c+=1;return e})}rightAlignTextFragments(a,b){for(const c of b)c.setAttribute("text-anchor","start"),c.setAttribute("x",`${a+Bubble$$module$build$src$core$bubbles$bubble.BORDER_WIDTH}`)}updateBubbleSize(){const a=
this.paragraph.getBBox();this.setSize(new Size$$module$build$src$core$utils$size(a.width+Bubble$$module$build$src$core$bubbles$bubble.BORDER_WIDTH*2,a.height+Bubble$$module$build$src$core$bubbles$bubble.BORDER_WIDTH*2),!0)}},module$build$src$core$bubbles$text_bubble={};module$build$src$core$bubbles$text_bubble.TextBubble=TextBubble$$module$build$src$core$bubbles$text_bubble;var SIZE$$module$build$src$core$icons$warning_icon=17,WarningIcon$$module$build$src$core$icons$warning_icon=class extends Icon$$module$build$src$core$icons$icon{constructor(a){super(a);this.sourceBlock=a;this.textMap=new Map;this.textBubble=null}getType(){return WarningIcon$$module$build$src$core$icons$warning_icon.TYPE}initView(a){this.svgRoot||(super.initView(a),createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,{"class":"blocklyIconShape",d:"M2,15Q-1,15 0.5,12L6.5,1.7Q8,-1 9.5,1.7L15.5,12Q17,15 14,15z"},
this.svgRoot),createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,{"class":"blocklyIconSymbol",d:"m7,4.8v3.16l0.27,2.27h1.46l0.27,-2.27v-3.16z"},this.svgRoot),createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{"class":"blocklyIconSymbol",x:"7",y:"11",height:"2",width:"2"},this.svgRoot),addClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyWarningIcon"))}dispose(){super.dispose();let a;(a=this.textBubble)==null||
a.dispose()}getWeight(){return WarningIcon$$module$build$src$core$icons$warning_icon.WEIGHT}getSize(){return new Size$$module$build$src$core$utils$size(SIZE$$module$build$src$core$icons$warning_icon,SIZE$$module$build$src$core$icons$warning_icon)}applyColour(){super.applyColour();let a;(a=this.textBubble)==null||a.setColour(this.sourceBlock.getColour())}updateCollapsed(){}isShownWhenCollapsed(){return!0}onLocationChange(a){super.onLocationChange(a);let b;(b=this.textBubble)==null||b.setAnchorLocation(this.getAnchorLocation())}addMessage(a,
b){if(this.textMap.get(b)===a)return this;a?this.textMap.set(b,a):this.textMap.delete(b);let c;(c=this.textBubble)==null||c.setText(this.getText());return this}getText(){return[...this.textMap.values()].join("\n")}onClick(){super.onClick();this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}bubbleIsVisible(){return!!this.textBubble}setBubbleVisible(a){const b=this;return(0,$jscomp.asyncExecutePromiseGeneratorFunction)(function*(){if(b.bubbleIsVisible()!==a){yield finishQueuedRenders$$module$build$src$core$render_management();
if(a)b.textBubble=new TextBubble$$module$build$src$core$bubbles$text_bubble(b.getText(),b.sourceBlock.workspace,b.getAnchorLocation(),b.getBubbleOwnerRect()),b.applyColour();else{let c;(c=b.textBubble)==null||c.dispose();b.textBubble=null}fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BUBBLE_OPEN))(b.sourceBlock,a,"warning"))}})}getBubble(){return this.textBubble}getAnchorLocation(){const a=SIZE$$module$build$src$core$icons$warning_icon/
2;return Coordinate$$module$build$src$core$utils$coordinate.sum(this.workspaceLocation,new Coordinate$$module$build$src$core$utils$coordinate(a,a))}getBubbleOwnerRect(){const a=this.sourceBlock.getSvgRoot().getBBox();return new Rect$$module$build$src$core$utils$rect(a.y,a.y+a.height,a.x,a.x+a.width)}};WarningIcon$$module$build$src$core$icons$warning_icon.TYPE=IconType$$module$build$src$core$icons$icon_types.WARNING;WarningIcon$$module$build$src$core$icons$warning_icon.WEIGHT=2;
var module$build$src$core$icons$warning_icon={};module$build$src$core$icons$warning_icon.WarningIcon=WarningIcon$$module$build$src$core$icons$warning_icon;var BlockSvg$$module$build$src$core$block_svg=class extends Block$$module$build$src$core$block{constructor(a,b,c){super(a,b,c);this.childlessWidth=this.width=this.height=0;this.warningTextDb=new Map;this.mutator=null;this.rendered=!0;this.visuallyDisabled=!1;this.translation="";this.dragging=!1;this.relativeCoords=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.dragStrategy=new BlockDragStrategy$$module$build$src$core$dragging$block_drag_strategy(this);if(!a.rendered)throw TypeError("Cannot create a rendered block in a headless workspace");
this.workspace=a;this.svgGroup=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{});b&&addClass$$module$build$src$core$utils$dom(this.svgGroup,b);this.style=a.getRenderer().getConstants().getBlockStyle(null);this.pathObject=a.getRenderer().makePathObject(this.svgGroup,this.style);a=this.pathObject.svgPath;a.tooltip=this;bindMouseEvents$$module$build$src$core$tooltip(a);this.svgGroup.setAttribute("data-id",this.id);a.id=getNextUniqueId$$module$build$src$core$utils$idgenerator();
this.doInit_()}initSvg(){if(!this.initialized){for(var a of this.inputList)a.init();for(const b of this.getIcons())b.initView(this.createIconPointerDownListener(b)),b.updateEditable();this.applyColour();this.pathObject.updateMovable(this.isMovable()||this.isInFlyout);(a=this.getSvgRoot())&&conditionalBind$$module$build$src$core$browser_events(a,"pointerdown",this,this.onMouseDown);a.parentNode||this.workspace.getCanvas().appendChild(a);this.initialized=!0}}getColourSecondary(){return this.style.colourSecondary}getColourTertiary(){return this.style.colourTertiary}select(){this.addSelect();
fireSelectedEvent$$module$build$src$core$common(this)}unselect(){this.removeSelect();fireSelectedEvent$$module$build$src$core$common(null)}setParent(a){var b=this.parentBlock_;if(a!==b){startTextWidthCache$$module$build$src$core$utils$dom();super.setParent(a);stopTextWidthCache$$module$build$src$core$utils$dom();var c=this.getSvgRoot();if(!this.workspace.isClearing&&c){var d=this.getRelativeToSurfaceXY(),e=$.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode(),f,g=this.getSvgRoot().contains((f=
e==null?void 0:e.getFocusableElement())!=null?f:null);a?(a.getSvgRoot().appendChild(c),g&&e&&$.getFocusManager$$module$build$src$core$focus_manager().focusNode(e)):b&&(a=this.workspace.getCanvas().querySelector(".blocklyDragging"),b=a==null?void 0:a.parentElement,f=this.workspace.getCanvas(),b===f?f.insertBefore(c,a):(f.appendChild(c),g&&e&&$.getFocusManager$$module$build$src$core$focus_manager().focusNode(e)),this.translate(d.x,d.y));this.applyColour()}}}getRelativeToSurfaceXY(){const a=this.workspace.getLayerManager();
if(!a)throw Error("Cannot calculate position because the workspace has not been appended");let b=0,c=0,d=this.getSvgRoot();if(d){do{const e=getRelativeXY$$module$build$src$core$utils$svg_math(d);b+=e.x;c+=e.y;d=d.parentNode}while(d&&!a.hasLayer(d))}return new Coordinate$$module$build$src$core$utils$coordinate(b,c)}moveBy(a,b,c){if(this.parentBlock_)throw Error("Block has parent");const d=isEnabled$$module$build$src$core$events$utils();let e=null;d&&(e=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_MOVE))(this),
c&&e.setReason(c));a=new Coordinate$$module$build$src$core$utils$coordinate(a,b);b=this.getRelativeToSurfaceXY();a=Coordinate$$module$build$src$core$utils$coordinate.sum(b,a);this.translate(a.x,a.y);this.updateComponentLocations(a);d&&e&&(e.recordNew(),fire$$module$build$src$core$events$utils(e));this.workspace.resizeContents()}translate(a,b){this.translation=`translate(${a}, ${b})`;this.relativeCoords=new Coordinate$$module$build$src$core$utils$coordinate(a,b);this.getSvgRoot().setAttribute("transform",
this.getTranslation())}getTranslation(){return this.translation}moveTo(a,b){const c=this.getRelativeToSurfaceXY();this.moveBy(a.x-c.x,a.y-c.y,b)}moveDuringDrag(a){this.translate(a.x,a.y);this.getSvgRoot().setAttribute("transform",this.getTranslation());this.updateComponentLocations(a)}snapToGrid(){if(!this.isDeadOrDying()&&!this.getParent()&&!this.isInFlyout){var a=this.workspace.getGrid();if(a!=null&&a.shouldSnap()){var b=this.getRelativeToSurfaceXY();a=a.alignXY(b);a!==b&&this.moveTo(a,["snap"])}}}getBoundingRectangle(){return this.getBoundingRectangleWithDimensions(this.getHeightWidth())}getBoundingRectangleWithoutChildren(){return this.getBoundingRectangleWithDimensions({height:this.height,
width:this.childlessWidth})}getBoundingRectangleWithDimensions(a){const b=this.getRelativeToSurfaceXY();let c,d;this.RTL?(c=b.x-a.width,d=b.x):(c=b.x,d=b.x+a.width);return new Rect$$module$build$src$core$utils$rect(b.y,b.y+a.height,c,d)}markDirty(){this.pathObject.constants=this.workspace.getRenderer().getConstants();for(let a=0,b;b=this.inputList[a];a++)b.markDirty()}setCollapsed(a){this.collapsed_!==a&&(super.setCollapsed(a),this.updateCollapsed())}childHasWarning(){const a=this.getChildren(!1);
for(const b of a)if(b.getIcon(WarningIcon$$module$build$src$core$icons$warning_icon.TYPE)||b.childHasWarning())return!0;return!1}updateCollapsed(){var a=this.isCollapsed();const b=COLLAPSED_INPUT_NAME$$module$build$src$core$constants,c=COLLAPSED_FIELD_NAME$$module$build$src$core$constants;for(let e=0,f;f=this.inputList[e];e++)f.name!==b&&f.setVisible(!a);for(var d of this.getIcons())d.updateCollapsed();a?(addClass$$module$build$src$core$utils$dom(this.svgGroup,"blocklyCollapsed"),this.childHasWarning()&&
this.setWarningText($.Msg$$module$build$src$core$msg.COLLAPSED_WARNINGS_WARNING,BlockSvg$$module$build$src$core$block_svg.COLLAPSED_WARNING_ID),a=this.toString(COLLAPSE_CHARS$$module$build$src$core$internal_constants),(d=this.getField(c))?d.setValue(a):(this.getInput(b)||this.appendDummyInput(b)).appendField(new FieldLabel$$module$build$src$core$field_label(a),c)):(this.updateDisabled(),this.removeInput(b),removeClass$$module$build$src$core$utils$dom(this.svgGroup,"blocklyCollapsed"),this.setWarningText(null,
BlockSvg$$module$build$src$core$block_svg.COLLAPSED_WARNING_ID))}onMouseDown(a){if(!this.workspace.isReadOnly()){var b=this.workspace.getGesture(a);b&&b.handleBlockStart(a,this)}}showHelp(){const a=typeof this.helpUrl==="function"?this.helpUrl():this.helpUrl;a&&window.open(a)}generateContextMenu(a){if(this.workspace.isReadOnly()||!this.contextMenu)return null;a=ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.getContextMenuOptions({block:this,focusedNode:this},a);this.customContextMenu&&
this.customContextMenu(a);return a}calculateContextMenuLocation(a){if(a instanceof PointerEvent)return new Coordinate$$module$build$src$core$utils$coordinate(a.clientX,a.clientY);a=wsToScreenCoordinates$$module$build$src$core$utils$svg_math(this.workspace,this.getRelativeToSurfaceXY());let b,c;const d=(b=this.inputList.filter(e=>e.isVisible()).flatMap(e=>e.fieldRow).find(e=>e.isVisible()))==null?void 0:(c=b.getSvgRoot())==null?void 0:c.getBoundingClientRect();return new Coordinate$$module$build$src$core$utils$coordinate(this.RTL?
a.x-5:a.x+5,(d&&d.height?d.y+d.height:a.y+this.height)+5)}showContextMenu(a){const b=this.generateContextMenu(a),c=this.calculateContextMenuLocation(a);b&&b.length&&(show$$module$build$src$core$contextmenu(a,b,this.RTL,this.workspace,c),setCurrentBlock$$module$build$src$core$contextmenu(this))}updateComponentLocations(a){this.dragging||this.updateConnectionLocations(a);this.updateIconLocations(a);this.updateFieldLocations(a);for(const b of this.getChildren(!1))b.updateComponentLocations(Coordinate$$module$build$src$core$utils$coordinate.sum(a,
b.relativeCoords))}updateConnectionLocations(a){for(const b of this.getConnections_(!1))b.moveToOffset(a)}updateIconLocations(a){for(const b of this.getIcons())b.onLocationChange(a)}updateFieldLocations(a){for(const b of this.inputList)for(const c of b.fieldRow)c.onLocationChange(a)}addClass(a){addClass$$module$build$src$core$utils$dom(this.svgGroup,a)}removeClass(a){removeClass$$module$build$src$core$utils$dom(this.svgGroup,a)}setDragging(a){(this.dragging=a)?(this.translation="",draggingConnections$$module$build$src$core$common.push(...this.getConnections_(!0)),
this.addClass("blocklyDragging")):(draggingConnections$$module$build$src$core$common.length=0,this.removeClass("blocklyDragging"));for(let b=0;b<this.childBlocks_.length;b++)this.childBlocks_[b].setDragging(a)}setMovable(a){super.setMovable(a);this.pathObject.updateMovable(a)}setEditable(a){super.setEditable(a);a?removeClass$$module$build$src$core$utils$dom(this.svgGroup,"blocklyNotEditable"):addClass$$module$build$src$core$utils$dom(this.svgGroup,"blocklyNotEditable");a=this.getIcons();for(let b=
0;b<a.length;b++)a[b].updateEditable()}setShadow(a){super.setShadow(a);this.applyColour()}setInsertionMarker(a){this.isInsertionMarker_!==a&&(this.isInsertionMarker_=a)&&(this.setColour(this.workspace.getRenderer().getConstants().INSERTION_MARKER_COLOUR),this.pathObject.updateInsertionMarker(!0))}getSvgRoot(){return this.svgGroup}dispose(a,b){this.disposing=!0;dispose$$module$build$src$core$tooltip();hide$$module$build$src$core$contextmenu();const c=$.getFocusManager$$module$build$src$core$focus_manager();
var d,e;if(this.getSvgRoot().contains((e=(d=c.getFocusedNode())==null?void 0:d.getFocusableElement())!=null?e:null)){d=this.getParent();if(!d){let f;if(e=(f=this.outputConnection)!=null?f:this.previousConnection){let g;d=(g=e.closest(0,new Coordinate$$module$build$src$core$utils$coordinate(0,0)).connection)==null?void 0:g.getSourceBlock()}}d?c.focusNode(d):setTimeout(()=>c.focusTree(this.workspace),0)}b&&(this.unplug(a),disposeUiEffect$$module$build$src$core$block_animations(this));super.dispose(!!a);
removeNode$$module$build$src$core$utils$dom(this.svgGroup)}disposeInternal(){this.disposing=!0;super.disposeInternal();$.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode()===this&&this.workspace.cancelCurrentGesture();[...this.warningTextDb.values()].forEach(a=>clearTimeout(a));this.warningTextDb.clear();this.getIcons().forEach(a=>a.dispose())}checkAndDelete(){this.workspace.isFlyout||($.setGroup$$module$build$src$core$events$utils(!0),this.workspace.hideChaff(),this.outputConnection?
this.dispose(!1,!0):this.dispose(!0,!0),$.setGroup$$module$build$src$core$events$utils(!1))}toCopyData(a=!1){return this.isInsertionMarker_?null:{paster:BlockPaster$$module$build$src$core$clipboard$block_paster.TYPE,blockState:save$$module$build$src$core$serialization$blocks(this,{addCoordinates:!0,addNextBlocks:a,saveIds:!1}),typeCounts:getBlockTypeCounts$$module$build$src$core$common(this,!0)}}applyColour(){var a,b;(b=(a=this.pathObject).applyColour)==null||b.call(a,this);a=this.getIcons();for(b=
0;b<a.length;b++)a[b].applyColour();for(const c of this.getFields())c.applyColour()}updateDisabled(){const a=!this.isEnabled()||this.getInheritedDisabled();if(this.visuallyDisabled===a){let b;(b=this.getNextBlock())==null||b.updateDisabled()}else{this.applyColour();this.visuallyDisabled=a;for(const b of this.getChildren(!1))b.updateDisabled()}}setWarningText(a,b=""){if(b)this.warningTextDb.has(b)&&(clearTimeout(this.warningTextDb.get(b)),this.warningTextDb.delete(b));else{for(var c of this.warningTextDb.values())clearTimeout(c);
this.warningTextDb.clear()}if(this.workspace.isDragging())this.warningTextDb.set(b,setTimeout(()=>{this.isDeadOrDying()||(this.warningTextDb.delete(b),this.setWarningText(a,b))},100));else if(this.isInFlyout&&(a=null),c=this.getIcon(WarningIcon$$module$build$src$core$icons$warning_icon.TYPE),a){let d=this.getSurroundParent(),e=null;for(;d;)d.isCollapsed()&&(e=d),d=d.getSurroundParent();e&&e.setWarningText($.Msg$$module$build$src$core$msg.COLLAPSED_WARNINGS_WARNING,BlockSvg$$module$build$src$core$block_svg.COLLAPSED_WARNING_ID);
c?c.addMessage(a,b):this.addIcon((new WarningIcon$$module$build$src$core$icons$warning_icon(this)).addMessage(a,b))}else c&&(b?(c.addMessage("",b),c.getText()||this.removeIcon(WarningIcon$$module$build$src$core$icons$warning_icon.TYPE)):this.removeIcon(WarningIcon$$module$build$src$core$icons$warning_icon.TYPE))}setMutator(a){this.removeIcon($.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE);a&&this.addIcon(a)}addIcon(a){super.addIcon(a);a instanceof $.MutatorIcon$$module$build$src$core$icons$mutator_icon&&
(this.mutator=a);a.initView(this.createIconPointerDownListener(a));a.applyColour();a.updateEditable();this.queueRender();return a}createIconPointerDownListener(a){return b=>{this.isDeadOrDying()||(b=this.workspace.getGesture(b))&&b.setStartIcon(a)}}removeIcon(a){const b=super.removeIcon(a);a.equals($.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE)&&(this.mutator=null);this.queueRender();return b}setDisabledReason(a,b){const c=this.isEnabled();super.setDisabledReason(a,b);this.isEnabled()===
c||this.getInheritedDisabled()||this.updateDisabled()}setDeletable(a){super.setDeletable(a);a?removeClass$$module$build$src$core$utils$dom(this.svgGroup,"blocklyNotDeletable"):addClass$$module$build$src$core$utils$dom(this.svgGroup,"blocklyNotDeletable")}setHighlighted(a){this.pathObject.updateHighlighted(a)}addSelect(){this.pathObject.updateSelected(!0)}removeSelect(){this.pathObject.updateSelected(!1)}setDeleteStyle(a){this.pathObject.updateDraggingDelete(a)}getColour(){return this.style.colourPrimary}setColour(a){super.setColour(a);
a=this.workspace.getRenderer().getConstants().getBlockStyleForColour(this.colour_);let b,c;(c=(b=this.pathObject).setStyle)==null||c.call(b,a.style);this.style=a.style;this.styleName_=a.name;this.applyColour()}setStyle(a){const b=this.workspace.getRenderer().getConstants().getBlockStyle(a);this.styleName_&&removeClass$$module$build$src$core$utils$dom(this.svgGroup,this.styleName_);if(b){this.hat=b.hat;let c,d;(d=(c=this.pathObject).setStyle)==null||d.call(c,b);this.colour_=b.colourPrimary;this.style=
b;this.applyColour();addClass$$module$build$src$core$utils$dom(this.svgGroup,a);this.styleName_=a}else throw Error("Invalid style name: "+a);}getStyle(){return this.style}bringToFront(a=!1){const b=$.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode();let c=this;if(!c.isDeadOrDying()){do{const d=c.getSvgRoot(),e=d.parentNode,f=e.childNodes;f[f.length-1]!==d&&e.appendChild(d);if(a)break;c=c.getParent()}while(c);b&&$.getFocusManager$$module$build$src$core$focus_manager().focusNode(b)}}setPreviousStatement(a,
b){super.setPreviousStatement(a,b);this.queueRender()}setNextStatement(a,b){super.setNextStatement(a,b);this.queueRender()}setOutput(a,b){super.setOutput(a,b);this.queueRender()}setInputsInline(a){super.setInputsInline(a);this.queueRender()}removeInput(a,b){a=super.removeInput(a,b);this.queueRender();return a}moveNumberedInputBefore(a,b){super.moveNumberedInputBefore(a,b);this.queueRender()}appendInput(a){super.appendInput(a);this.queueRender();return a}setConnectionTracking(a){this.previousConnection&&
this.previousConnection.setTracking(a);this.outputConnection&&this.outputConnection.setTracking(a);if(this.nextConnection){this.nextConnection.setTracking(a);var b=this.nextConnection.targetBlock();b&&b.setConnectionTracking(a)}if(!this.collapsed_)for(b=0;b<this.inputList.length;b++){var c=this.inputList[b].connection;c&&(c.setTracking(a),(c=c.targetBlock())&&c.setConnectionTracking(a))}}getConnections_(a){const b=[];this.outputConnection&&b.push(this.outputConnection);this.previousConnection&&b.push(this.previousConnection);
this.nextConnection&&b.push(this.nextConnection);if(a||!this.collapsed_)for(let c=0,d;d=this.inputList[c];c++)d.connection&&b.push(d.connection);return b}lastConnectionInStack(a){return super.lastConnectionInStack(a)}getMatchingConnection(a,b){return super.getMatchingConnection(a,b)}makeConnection_(a){return new RenderedConnection$$module$build$src$core$rendered_connection(this,a)}getNextBlock(){return super.getNextBlock()}getPreviousBlock(){return super.getPreviousBlock()}bumpNeighbours(){const a=
this.getRootBlock();if(!(this.isDeadOrDying()||this.workspace.isDragging()||a.isInFlyout))for(const b of this.getConnections_(!1)){if(b.isSuperior()){let c;(c=b.targetBlock())==null||c.bumpNeighbours()}for(const c of b.neighbours($.config$$module$build$src$core$config.snapRadius))c.getSourceBlock().getRootBlock()!==a&&(b.isConnected()&&c.isConnected()||(b.isSuperior()?c.bumpAwayFrom(b,!1):b.bumpAwayFrom(c,!0)))}}scheduleSnapAndBump(){this.snapToGrid();this.bumpNeighbours()}positionNearConnection(a,
b,c){if(a.type===ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT||a.type===ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE){let d=b.x;b=b.y;d+=c.x-a.getOffsetInBlock().x;b+=c.y-a.getOffsetInBlock().y;this.moveBy(d,b)}}getChildren(a){return super.getChildren(a)}queueRender(){return queueRender$$module$build$src$core$render_management(this)}render(){this.queueRender();triggerQueuedRenders$$module$build$src$core$render_management()}renderEfficiently(){startTextWidthCache$$module$build$src$core$utils$dom();
this.isCollapsed()&&this.updateCollapsed();this.isEnabled()||this.updateDisabled();this.workspace.getRenderer().render(this);this.tightenChildrenEfficiently();stopTextWidthCache$$module$build$src$core$utils$dom()}tightenChildrenEfficiently(){for(const a of this.inputList){const b=a.connection;b&&b.tightenEfficiently()}this.nextConnection&&this.nextConnection.tightenEfficiently()}getHeightWidth(){let a=this.height,b=this.width;var c=this.getNextBlock();if(c){c=c.getHeightWidth();const d=this.workspace.getRenderer().getConstants().NOTCH_HEIGHT;
a+=c.height-d;b=Math.max(b,c.width)}return{height:a,width:b}}fadeForReplacement(a){this.pathObject.updateReplacementFade(a)}highlightShapeForInput(a,b){this.pathObject.updateShapeForInputHighlight(a,b)}getDragStrategy(){return this.dragStrategy}setDragStrategy(a){this.dragStrategy=a}isCopyable(){return this.isOwnDeletable()&&this.isOwnMovable()}isMovable(){return this.dragStrategy.isMovable()}startDrag(a){this.dragStrategy.startDrag(a)}drag(a,b){this.dragStrategy.drag(a,b)}endDrag(a){this.dragStrategy.endDrag(a)}revertDrag(){this.dragStrategy.revertDrag()}toFlyoutInfo(){const a=
Object.assign({},{kind:"BLOCK"},save$$module$build$src$core$serialization$blocks(this)),b=new Set(["id","height","width","pinned","enabled"]),c=function(d){for(const e in d)b.has(e)?delete d[e]:typeof d[e]==="object"&&c(d[e])};c(a);return[a]}jsonInit(a){super.jsonInit(a);a.classes&&this.addClass(Array.isArray(a.classes)?a.classes.join(" "):a.classes)}getFocusableElement(){return this.pathObject.svgPath}getFocusableTree(){return this.workspace}onNodeFocus(){this.select();this.workspace.scrollBoundsIntoView(this.getBoundingRectangleWithoutChildren())}onNodeBlur(){this.unselect()}canBeFocused(){return!0}};
BlockSvg$$module$build$src$core$block_svg.INLINE=-1;BlockSvg$$module$build$src$core$block_svg.COLLAPSED_WARNING_ID="TEMP_COLLAPSED_WARNING_";var module$build$src$core$block_svg={};module$build$src$core$block_svg.BlockSvg=BlockSvg$$module$build$src$core$block_svg;var DragTarget$$module$build$src$core$drag_target=class{constructor(){}onDragEnter(a){}onDragOver(a){}onDragExit(a){}onDrop(a){}getClientRect(){return null}shouldPreventMove(a){return!1}},module$build$src$core$drag_target={};module$build$src$core$drag_target.DragTarget=DragTarget$$module$build$src$core$drag_target;var module$build$src$core$interfaces$i_deletable={};module$build$src$core$interfaces$i_deletable.isDeletable=isDeletable$$module$build$src$core$interfaces$i_deletable;var DeleteArea$$module$build$src$core$delete_area=class extends DragTarget$$module$build$src$core$drag_target{constructor(){super();this.wouldDelete_=!1}wouldDelete(a){a instanceof BlockSvg$$module$build$src$core$block_svg?(a=!a.getParent()&&a.isDeletable(),this.updateWouldDelete_(a)):this.updateWouldDelete_(isDeletable$$module$build$src$core$interfaces$i_deletable(a)&&a.isDeletable());return this.wouldDelete_}updateWouldDelete_(a){this.wouldDelete_=a}},module$build$src$core$delete_area={};
module$build$src$core$delete_area.DeleteArea=DeleteArea$$module$build$src$core$delete_area;var FlyoutItem$$module$build$src$core$flyout_item=class{constructor(a,b){this.element=a;this.type=b}getElement(){return this.element}getType(){return this.type}},module$build$src$core$flyout_item={};module$build$src$core$flyout_item.FlyoutItem=FlyoutItem$$module$build$src$core$flyout_item;var MetricsManager$$module$build$src$core$metrics_manager=class{constructor(a){this.workspace_=a}getDimensionsPx_(a){let b=0,c=0;a&&(b=a.getWidth(),c=a.getHeight());return new Size$$module$build$src$core$utils$size(b,c)}getFlyoutMetrics(a){a=this.getDimensionsPx_(this.workspace_.getFlyout(a));return{width:a.width,height:a.height,position:this.workspace_.toolboxPosition}}getToolboxMetrics(){const a=this.getDimensionsPx_(this.workspace_.getToolbox());return{width:a.width,height:a.height,position:this.workspace_.toolboxPosition}}getSvgMetrics(){return this.workspace_.getCachedParentSvgSize()}getAbsoluteMetrics(){let a=
0,b=0;const c=this.getToolboxMetrics(),d=this.getFlyoutMetrics(),e=!!this.workspace_.getToolbox();var f;const g=!((f=this.workspace_.getFlyout())==null?0:f.autoClose);f=e?c.position:d.position;const h=f===Position$$module$build$src$core$utils$toolbox.TOP;f===Position$$module$build$src$core$utils$toolbox.LEFT&&(e&&(a+=c.width),g&&(a+=d.width));h&&(e&&(b+=c.height),g&&(b+=d.height));return{top:b,left:a}}getViewMetrics(a){a=a?this.workspace_.scale:1;const b=this.getSvgMetrics(),c=this.getToolboxMetrics(),
d=this.getFlyoutMetrics(),e=!!this.workspace_.getToolbox();var f;const g=!((f=this.workspace_.getFlyout())==null?0:f.autoClose);f=e?c.position:d.position;const h=f===Position$$module$build$src$core$utils$toolbox.LEFT||f===Position$$module$build$src$core$utils$toolbox.RIGHT;if(f===Position$$module$build$src$core$utils$toolbox.TOP||f===Position$$module$build$src$core$utils$toolbox.BOTTOM)e&&(b.height-=c.height),g&&(b.height-=d.height);h&&(e&&(b.width-=c.width),g&&(b.width-=d.width));return{height:b.height/
a,width:b.width/a,top:-this.workspace_.scrollY/a,left:-this.workspace_.scrollX/a}}getContentMetrics(a){a=a?1:this.workspace_.scale;const b=this.workspace_.getBlocksBoundingBox();return{height:(b.bottom-b.top)*a,width:(b.right-b.left)*a,top:b.top*a,left:b.left*a}}hasFixedEdges(){return!this.workspace_.isMovableHorizontally()||!this.workspace_.isMovableVertically()}getComputedFixedEdges_(a){if(!this.hasFixedEdges())return{};const b=this.workspace_.isMovableHorizontally(),c=this.workspace_.isMovableVertically();
a=a||this.getViewMetrics(!1);const d={};c||(d.top=a.top,d.bottom=a.top+a.height);b||(d.left=a.left,d.right=a.left+a.width);return d}getPaddedContent_(a,b){const c=b.top+b.height,d=b.left+b.width,e=a.width;a=a.height;const f=e/2,g=a/2;return{top:Math.min(b.top-g,c-a),bottom:Math.max(c+g,b.top+a),left:Math.min(b.left-f,d-e),right:Math.max(d+f,b.left+e)}}getScrollMetrics(a,b,c){a=a?this.workspace_.scale:1;b=b||this.getViewMetrics(!1);var d=c||this.getContentMetrics();c=this.getComputedFixedEdges_(b);
b=this.getPaddedContent_(b,d);d=c.top!==void 0?c.top:b.top;const e=c.left!==void 0?c.left:b.left;return{top:d/a,left:e/a,width:((c.right!==void 0?c.right:b.right)-e)/a,height:((c.bottom!==void 0?c.bottom:b.bottom)-d)/a}}getUiMetrics(){return{viewMetrics:this.getViewMetrics(),absoluteMetrics:this.getAbsoluteMetrics(),toolboxMetrics:this.getToolboxMetrics()}}getMetrics(){const a=this.getToolboxMetrics(),b=this.getFlyoutMetrics(!0),c=this.getSvgMetrics(),d=this.getAbsoluteMetrics(),e=this.getViewMetrics(),
f=this.getContentMetrics(),g=this.getScrollMetrics(!1,e,f);return{contentHeight:f.height,contentWidth:f.width,contentTop:f.top,contentLeft:f.left,scrollHeight:g.height,scrollWidth:g.width,scrollTop:g.top,scrollLeft:g.left,viewHeight:e.height,viewWidth:e.width,viewTop:e.top,viewLeft:e.left,absoluteTop:d.top,absoluteLeft:d.left,svgHeight:c.height,svgWidth:c.width,toolboxWidth:a.width,toolboxHeight:a.height,toolboxPosition:a.position,flyoutWidth:b.width,flyoutHeight:b.height}}};
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.METRICS_MANAGER,DEFAULT$$module$build$src$core$registry,MetricsManager$$module$build$src$core$metrics_manager);var module$build$src$core$metrics_manager={};module$build$src$core$metrics_manager.MetricsManager=MetricsManager$$module$build$src$core$metrics_manager;var FlyoutMetricsManager$$module$build$src$core$flyout_metrics_manager=class extends MetricsManager$$module$build$src$core$metrics_manager{constructor(a,b){super(a);this.flyout_=b}getBoundingBox(){let a;try{a=this.workspace_.getCanvas().getBBox()}catch(b){a={height:0,y:0,width:0,x:0}}return a}getContentMetrics(a){const b=this.getBoundingBox();a=a?1:this.workspace_.scale;return{height:b.height*a,width:b.width*a,top:b.y*a,left:b.x*a}}getScrollMetrics(a,b,c){b=c||this.getContentMetrics();c=this.flyout_.MARGIN*
this.workspace_.scale;a=a?this.workspace_.scale:1;return{height:(b.height+2*c)/a,width:(b.width+b.left+c)/a,top:0,left:0}}},module$build$src$core$flyout_metrics_manager={};module$build$src$core$flyout_metrics_manager.FlyoutMetricsManager=FlyoutMetricsManager$$module$build$src$core$flyout_metrics_manager;var FlyoutButton$$module$build$src$core$flyout_button=class{constructor(a,b,c,d){this.workspace=a;this.targetWorkspace=b;this.isFlyoutLabel=d;this.height=this.width=0;this.cursorSvg=this.svgText=null;this.text=c.text;this.position=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.callbackKey=c.callbackKey||c.callbackkey;this.cssClass=c["web-class"]||null;this.info=c;a=this.isFlyoutLabel?"blocklyFlyoutLabel":"blocklyFlyoutButton";this.cssClass&&(a+=" "+this.cssClass);this.id=getNextUniqueId$$module$build$src$core$utils$idgenerator();
this.svgGroup=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{id:this.id,"class":a},this.workspace.getCanvas());let e;this.isFlyoutLabel||(e=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{"class":"blocklyFlyoutButtonShadow",rx:FlyoutButton$$module$build$src$core$flyout_button.BORDER_RADIUS,ry:FlyoutButton$$module$build$src$core$flyout_button.BORDER_RADIUS,x:1,y:1},this.svgGroup));a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,
{"class":this.isFlyoutLabel?"blocklyFlyoutLabelBackground":"blocklyFlyoutButtonBackground",rx:FlyoutButton$$module$build$src$core$flyout_button.BORDER_RADIUS,ry:FlyoutButton$$module$build$src$core$flyout_button.BORDER_RADIUS},this.svgGroup);b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.TEXT,{"class":this.isFlyoutLabel?"blocklyFlyoutLabelText":"blocklyText",x:0,y:0,"text-anchor":"middle"},this.svgGroup);c=replaceMessageReferences$$module$build$src$core$utils$parsing(this.text);
this.workspace.RTL&&(c+="\u200f");b.textContent=c;this.isFlyoutLabel&&(this.svgText=b,this.workspace.getThemeManager().subscribe(this.svgText,"flyoutForegroundColour","fill"));d=getComputedStyle$$module$build$src$core$utils$style(b,"fontSize");const f=getComputedStyle$$module$build$src$core$utils$style(b,"fontWeight"),g=getComputedStyle$$module$build$src$core$utils$style(b,"fontFamily");this.width=getFastTextWidthWithSizeString$$module$build$src$core$utils$dom(b,d,f,g);c=measureFontMetrics$$module$build$src$core$utils$dom(c,
d,f,g);this.height=this.height||c.height;if(!this.isFlyoutLabel){this.width+=2*FlyoutButton$$module$build$src$core$flyout_button.TEXT_MARGIN_X;this.height+=2*FlyoutButton$$module$build$src$core$flyout_button.TEXT_MARGIN_Y;let h;(h=e)==null||h.setAttribute("width",String(this.width));let k;(k=e)==null||k.setAttribute("height",String(this.height))}a.setAttribute("width",String(this.width));a.setAttribute("height",String(this.height));b.setAttribute("x",String(this.width/2));b.setAttribute("y",String(this.height/
2-c.height/2+c.baseline));this.updateTransform();this.onMouseDownWrapper=conditionalBind$$module$build$src$core$browser_events(this.svgGroup,"pointerdown",this,this.onMouseDown);this.onMouseUpWrapper=conditionalBind$$module$build$src$core$browser_events(this.svgGroup,"pointerup",this,this.onMouseUp)}createDom(){return this.svgGroup}show(){this.updateTransform();this.svgGroup.setAttribute("display","block")}updateTransform(){this.svgGroup.setAttribute("transform","translate("+this.position.x+","+this.position.y+
")")}moveTo(a,b){this.position.x=a;this.position.y=b;this.updateTransform()}moveBy(a,b,c){this.moveTo(this.position.x+a,this.position.y+b)}isLabel(){return this.isFlyoutLabel}getPosition(){return this.position}getBoundingRectangle(){return new Rect$$module$build$src$core$utils$rect(this.position.y,this.position.y+this.height,this.position.x,this.position.x+this.width)}getButtonText(){return this.text}getTargetWorkspace(){return this.targetWorkspace}getWorkspace(){return this.workspace}dispose(){unbind$$module$build$src$core$browser_events(this.onMouseDownWrapper);
unbind$$module$build$src$core$browser_events(this.onMouseUpWrapper);this.svgGroup&&removeNode$$module$build$src$core$utils$dom(this.svgGroup);this.svgText&&this.workspace.getThemeManager().unsubscribe(this.svgText)}setCursorSvg(a){a?this.svgGroup&&(this.svgGroup.appendChild(a),this.cursorSvg=a):this.cursorSvg=null}onMouseUp(a){(a=this.targetWorkspace.getGesture(a))&&a.cancel();this.isFlyoutLabel&&this.callbackKey?console.warn("Labels should not have callbacks. Label text: "+this.text):this.isFlyoutLabel||
this.callbackKey&&this.targetWorkspace.getButtonCallback(this.callbackKey)?this.isFlyoutLabel||(a=this.targetWorkspace.getButtonCallback(this.callbackKey))&&a(this):console.warn("Buttons should have callbacks. Button text: "+this.text)}onMouseDown(a){const b=this.targetWorkspace.getGesture(a),c=this.targetWorkspace.getFlyout();b&&c&&b.handleFlyoutStart(a,c)}getSvgRoot(){return this.svgGroup}getFocusableElement(){return this.svgGroup}getFocusableTree(){return this.workspace}onNodeFocus(){var a=this.getPosition();
a=new Rect$$module$build$src$core$utils$rect(a.y,a.y+this.height,a.x,a.x+this.width);this.workspace.scrollBoundsIntoView(a)}onNodeBlur(){}canBeFocused(){return!0}};FlyoutButton$$module$build$src$core$flyout_button.TEXT_MARGIN_X=5;FlyoutButton$$module$build$src$core$flyout_button.TEXT_MARGIN_Y=2;FlyoutButton$$module$build$src$core$flyout_button.BORDER_RADIUS=4;register$$module$build$src$core$css("\n.blocklyFlyoutButton {\n  fill: #888;\n  cursor: default;\n}\n\n.blocklyFlyoutButtonShadow {\n  fill: #666;\n}\n\n.blocklyFlyoutButton:hover {\n  fill: #aaa;\n}\n\n.blocklyFlyoutLabel {\n  cursor: default;\n}\n\n.blocklyFlyoutLabelBackground {\n  opacity: 0;\n}\n");
var module$build$src$core$flyout_button={};module$build$src$core$flyout_button.FlyoutButton=FlyoutButton$$module$build$src$core$flyout_button;var FlyoutButtonNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_button_navigation_policy=class{getFirstChild(a){return null}getParent(a){return a.getWorkspace()}getNextSibling(a){return null}getPreviousSibling(a){return null}isNavigable(a){return a.canBeFocused()}isApplicable(a){return a instanceof FlyoutButton$$module$build$src$core$flyout_button}},module$build$src$core$keyboard_nav$flyout_button_navigation_policy={};
module$build$src$core$keyboard_nav$flyout_button_navigation_policy.FlyoutButtonNavigationPolicy=FlyoutButtonNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_button_navigation_policy;var FlyoutNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_navigation_policy=class{constructor(a,b){this.policy=a;this.flyout=b}getFirstChild(a){return null}getParent(a){return this.policy.getParent(a)}getNextSibling(a){const b=this.flyout.getContents();if(!b)return null;let c=b.findIndex(d=>d.getElement()===a);if(c===-1)return null;c++;c>=b.length&&(c=0);return b[c].getElement()}getPreviousSibling(a){const b=this.flyout.getContents();if(!b)return null;let c=b.findIndex(d=>d.getElement()===
a);if(c===-1)return null;c--;c<0&&(c=b.length-1);return b[c].getElement()}isNavigable(a){return this.policy.isNavigable(a)}isApplicable(a){return this.policy.isApplicable(a)}},module$build$src$core$keyboard_nav$flyout_navigation_policy={};module$build$src$core$keyboard_nav$flyout_navigation_policy.FlyoutNavigationPolicy=FlyoutNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_navigation_policy;var FlyoutSeparator$$module$build$src$core$flyout_separator=class{constructor(a,b){this.gap=a;this.axis=b;this.y=this.x=0}getBoundingRectangle(){switch(this.axis){case "x":return new Rect$$module$build$src$core$utils$rect(this.y,this.y,this.x,this.x+this.gap);case "y":return new Rect$$module$build$src$core$utils$rect(this.y,this.y+this.gap,this.x,this.x)}}moveBy(a,b,c){this.x+=a;this.y+=b}isNavigable(){return!1}getFocusableElement(){throw Error("Cannot be focused");}getFocusableTree(){throw Error("Cannot be focused");
}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!1}},module$build$src$core$flyout_separator={};module$build$src$core$flyout_separator.FlyoutSeparator=FlyoutSeparator$$module$build$src$core$flyout_separator;var FlyoutSeparatorNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_separator_navigation_policy=class{getFirstChild(a){return null}getParent(a){return null}getNextSibling(a){return null}getPreviousSibling(a){return null}isNavigable(a){return!1}isApplicable(a){return a instanceof FlyoutSeparator$$module$build$src$core$flyout_separator}},module$build$src$core$keyboard_nav$flyout_separator_navigation_policy={};
module$build$src$core$keyboard_nav$flyout_separator_navigation_policy.FlyoutSeparatorNavigationPolicy=FlyoutSeparatorNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_separator_navigation_policy;var BlockCommentNavigationPolicy$$module$build$src$core$keyboard_nav$block_comment_navigation_policy=class{getFirstChild(a){return a.getEditor()}getParent(a){let b;return(b=a.getOwner())!=null?b:null}getNextSibling(a){return null}getPreviousSibling(a){return null}isNavigable(a){return a.canBeFocused()}isApplicable(a){return a instanceof TextInputBubble$$module$build$src$core$bubbles$textinput_bubble}},module$build$src$core$keyboard_nav$block_comment_navigation_policy={};
module$build$src$core$keyboard_nav$block_comment_navigation_policy.BlockCommentNavigationPolicy=BlockCommentNavigationPolicy$$module$build$src$core$keyboard_nav$block_comment_navigation_policy;var BlockNavigationPolicy$$module$build$src$core$keyboard_nav$block_navigation_policy=class{getFirstChild(a){return getBlockNavigationCandidates$$module$build$src$core$keyboard_nav$block_navigation_policy(a,!0)[0]}getParent(a){var b;if((b=a.previousConnection)==null?0:b.targetBlock()){if(b=a.getSurroundParent())return b}else{let c;if((c=a.outputConnection)==null?0:c.targetBlock())return a.outputConnection.targetBlock()}return a.workspace}getNextSibling(a){let b;if((b=a.nextConnection)==null?0:b.targetBlock()){let d;
return(d=a.nextConnection)==null?void 0:d.targetBlock()}let c;return((c=a.outputConnection)==null?0:c.targetBlock())?navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy(a,1):a.getSurroundParent()?navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy(a.getTopStackBlock(),1):this.getParent(a)instanceof WorkspaceSvg$$module$build$src$core$workspace_svg?navigateStacks$$module$build$src$core$keyboard_nav$block_navigation_policy(a,1):null}getPreviousSibling(a){let b;
if((b=a.previousConnection)==null?0:b.targetBlock()){let d;return(d=a.previousConnection)==null?void 0:d.targetBlock()}let c;return((c=a.outputConnection)==null?0:c.targetBlock())?navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy(a,-1):this.getParent(a)instanceof WorkspaceSvg$$module$build$src$core$workspace_svg?navigateStacks$$module$build$src$core$keyboard_nav$block_navigation_policy(a,-1):null}isNavigable(a){return a.canBeFocused()}isApplicable(a){return a instanceof BlockSvg$$module$build$src$core$block_svg}},
module$build$src$core$keyboard_nav$block_navigation_policy={};module$build$src$core$keyboard_nav$block_navigation_policy.BlockNavigationPolicy=BlockNavigationPolicy$$module$build$src$core$keyboard_nav$block_navigation_policy;module$build$src$core$keyboard_nav$block_navigation_policy.navigateBlock=navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy;module$build$src$core$keyboard_nav$block_navigation_policy.navigateStacks=navigateStacks$$module$build$src$core$keyboard_nav$block_navigation_policy;var CommentBarButtonNavigationPolicy$$module$build$src$core$keyboard_nav$comment_bar_button_navigation_policy=class{getFirstChild(a){return null}getParent(a){return a.getCommentView().workspace.getCommentById(a.getCommentView().commentId)}getNextSibling(a){const b=a.getCommentView().getCommentBarButtons();a=b.indexOf(a);return a>=0&&a+1<b.length?b[a+1]:null}getPreviousSibling(a){const b=a.getCommentView().getCommentBarButtons();a=b.indexOf(a);return a>0?b[a-1]:null}isNavigable(a){return a.canBeFocused()}isApplicable(a){return a instanceof
CommentBarButton$$module$build$src$core$comments$comment_bar_button}},module$build$src$core$keyboard_nav$comment_bar_button_navigation_policy={};module$build$src$core$keyboard_nav$comment_bar_button_navigation_policy.CommentBarButtonNavigationPolicy=CommentBarButtonNavigationPolicy$$module$build$src$core$keyboard_nav$comment_bar_button_navigation_policy;var CommentEditorNavigationPolicy$$module$build$src$core$keyboard_nav$comment_editor_navigation_policy=class{getFirstChild(a){return null}getParent(a){return null}getNextSibling(a){return null}getPreviousSibling(a){return null}isNavigable(a){return a.canBeFocused()}isApplicable(a){return a instanceof CommentEditor$$module$build$src$core$comments$comment_editor}},module$build$src$core$keyboard_nav$comment_editor_navigation_policy={};
module$build$src$core$keyboard_nav$comment_editor_navigation_policy.CommentEditorNavigationPolicy=CommentEditorNavigationPolicy$$module$build$src$core$keyboard_nav$comment_editor_navigation_policy;var ConnectionNavigationPolicy$$module$build$src$core$keyboard_nav$connection_navigation_policy=class{getFirstChild(a){return a.getParentInput()?a.targetConnection:null}getParent(a){return a.getSourceBlock()}getNextSibling(a){if(a.getParentInput())return navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy(a,1);if(a.type===ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT){const c=a.targetConnection;var b=a.getSourceBlock();if(!c&&b.getRootBlock().lastConnectionInStack(!1)===
a){a=b.workspace.getTopBlocks(!0);b=a.indexOf(b.getRootBlock())+1;b>=a.length&&(b=0);b=a[b];let d;return(d=this.getParentConnection(b))!=null?d:b}return c}return a.getSourceBlock()}getPreviousSibling(a){if(a.getParentInput())return navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy(a,-1);if(a.type===ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT||a.type===ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE){const c=a.targetConnection&&
!a.targetConnection.getParentInput()?a.targetConnection:null;var b=a.getSourceBlock();if(!c&&this.getParentConnection(b.getRootBlock())===a){a=b.workspace.getTopBlocks(!0);b=a.indexOf(b.getRootBlock())-1;b<0&&(b=a.length-1);b=a[b];let d;return(d=b.lastConnectionInStack(!1))!=null?d:b}return c}return a.type===ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT?a.getSourceBlock():null}getParentConnection(a){let b;return!a.outputConnection||((b=a.previousConnection)==null?0:b.isConnected())?
a.previousConnection:a.outputConnection}isNavigable(a){return a.canBeFocused()}isApplicable(a){return a instanceof RenderedConnection$$module$build$src$core$rendered_connection}},module$build$src$core$keyboard_nav$connection_navigation_policy={};module$build$src$core$keyboard_nav$connection_navigation_policy.ConnectionNavigationPolicy=ConnectionNavigationPolicy$$module$build$src$core$keyboard_nav$connection_navigation_policy;var FieldNavigationPolicy$$module$build$src$core$keyboard_nav$field_navigation_policy=class{getFirstChild(a){return null}getParent(a){return a.getSourceBlock()}getNextSibling(a){return navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy(a,1)}getPreviousSibling(a){return navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy(a,-1)}isNavigable(a){let b;return a.canBeFocused()&&a.isVisible()&&(a.isClickable()||a.isCurrentlyEditable())&&!(((b=a.getSourceBlock())==
null?0:b.isSimpleReporter())&&a.isFullBlockField())&&a.getParentInput().isVisible()}isApplicable(a){return a instanceof Field$$module$build$src$core$field}},module$build$src$core$keyboard_nav$field_navigation_policy={};module$build$src$core$keyboard_nav$field_navigation_policy.FieldNavigationPolicy=FieldNavigationPolicy$$module$build$src$core$keyboard_nav$field_navigation_policy;var module$build$src$core$icons$registry={};module$build$src$core$icons$registry.register=register$$module$build$src$core$icons$registry;module$build$src$core$icons$registry.unregister=unregister$$module$build$src$core$icons$registry;var SIZE$$module$build$src$core$icons$comment_icon=17,DEFAULT_BUBBLE_WIDTH$$module$build$src$core$icons$comment_icon=160,DEFAULT_BUBBLE_HEIGHT$$module$build$src$core$icons$comment_icon=80,CommentIcon$$module$build$src$core$icons$comment_icon=class extends Icon$$module$build$src$core$icons$icon{constructor(a){super(a);this.sourceBlock=a;this.textInputBubble=null;this.text="";this.bubbleSize=new Size$$module$build$src$core$utils$size(DEFAULT_BUBBLE_WIDTH$$module$build$src$core$icons$comment_icon,DEFAULT_BUBBLE_HEIGHT$$module$build$src$core$icons$comment_icon);
this.bubbleVisiblity=!1}getType(){return CommentIcon$$module$build$src$core$icons$comment_icon.TYPE}initView(a){this.svgRoot||(super.initView(a),createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.CIRCLE,{"class":"blocklyIconShape",r:"8",cx:"8",cy:"8"},this.svgRoot),createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,{"class":"blocklyIconSymbol",d:"m6.8,10h2c0.003,-0.617 0.271,-0.962 0.633,-1.266 2.875,-2.4050.607,-5.534 -3.765,-3.874v1.7c3.12,-1.657 3.698,0.118 2.336,1.25-1.201,0.998 -1.201,1.528 -1.204,2.19z"},
this.svgRoot),createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{"class":"blocklyIconSymbol",x:"6.8",y:"10.78",height:"2",width:"2"},this.svgRoot),addClass$$module$build$src$core$utils$dom(this.svgRoot,"blocklyCommentIcon"))}dispose(){super.dispose();let a;(a=this.textInputBubble)==null||a.dispose()}getWeight(){return CommentIcon$$module$build$src$core$icons$comment_icon.WEIGHT}getSize(){return new Size$$module$build$src$core$utils$size(SIZE$$module$build$src$core$icons$comment_icon,
SIZE$$module$build$src$core$icons$comment_icon)}applyColour(){super.applyColour();const a=this.sourceBlock.getColour();let b;(b=this.textInputBubble)==null||b.setColour(a)}updateEditable(){const a=this,b=()=>super.updateEditable;return(0,$jscomp.asyncExecutePromiseGeneratorFunction)(function*(){b().call(a);a.bubbleIsVisible()&&(yield a.setBubbleVisible(!1),yield a.setBubbleVisible(!0))})}onLocationChange(a){const b=this.workspaceLocation;super.onLocationChange(a);this.bubbleLocation&&(a=Coordinate$$module$build$src$core$utils$coordinate.difference(this.workspaceLocation,
b),this.bubbleLocation=Coordinate$$module$build$src$core$utils$coordinate.sum(this.bubbleLocation,a));a=this.getAnchorLocation();let c;(c=this.textInputBubble)==null||c.setAnchorLocation(a)}setText(a){const b=this.text;fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CHANGE))(this.sourceBlock,"comment",null,b,a));this.text=a;let c;(c=this.textInputBubble)==null||c.setText(this.text)}getText(){return this.text}setBubbleSize(a){this.bubbleSize=
a;let b;(b=this.textInputBubble)==null||b.setSize(this.bubbleSize,!0)}getBubbleSize(){return this.bubbleSize}setBubbleLocation(a){this.bubbleLocation=a;let b;(b=this.textInputBubble)==null||b.moveDuringDrag(a)}getBubbleLocation(){return this.bubbleLocation}saveState(){if(this.text){const a={text:this.text,pinned:this.bubbleIsVisible(),height:this.bubbleSize.height,width:this.bubbleSize.width},b=this.getBubbleLocation();b&&(a.x=this.sourceBlock.workspace.RTL?this.sourceBlock.workspace.getWidth()-(b.x+
this.bubbleSize.width):b.x,a.y=b.y);return a}return null}loadState(a){let b;this.text=(b=a.text)!=null?b:"";let c,d;this.bubbleSize=new Size$$module$build$src$core$utils$size((c=a.width)!=null?c:DEFAULT_BUBBLE_WIDTH$$module$build$src$core$icons$comment_icon,(d=a.height)!=null?d:DEFAULT_BUBBLE_HEIGHT$$module$build$src$core$icons$comment_icon);let e;this.bubbleVisiblity=(e=a.pinned)!=null?e:!1;this.setBubbleVisible(this.bubbleVisiblity);let f=a.x;const g=a.y;finishQueuedRenders$$module$build$src$core$render_management().then(()=>
{f&&g&&(f=this.sourceBlock.workspace.RTL?this.sourceBlock.workspace.getWidth()-(f+this.bubbleSize.width):f,this.setBubbleLocation(new Coordinate$$module$build$src$core$utils$coordinate(f,g)))})}onClick(){super.onClick();this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(this.textInputBubble){var a=this.textInputBubble.getText();this.text!==a&&(fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CHANGE))(this.sourceBlock,
"comment",null,this.text,a)),this.text=a)}}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}onBubbleLocationChange(){this.textInputBubble&&(this.bubbleLocation=this.textInputBubble.getRelativeToSurfaceXY())}bubbleIsVisible(){return this.bubbleVisiblity}setBubbleVisible(a){const b=this;return(0,$jscomp.asyncExecutePromiseGeneratorFunction)(function*(){b.bubbleVisiblity!==a&&(b.bubbleVisiblity=a,yield finishQueuedRenders$$module$build$src$core$render_management(),
!b.sourceBlock.rendered||b.sourceBlock.isInFlyout||b.sourceBlock.isInsertionMarker()||(a?(b.sourceBlock.isEditable()?b.showEditableBubble():b.showNonEditableBubble(),b.applyColour()):b.hideBubble(),fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BUBBLE_OPEN))(b.sourceBlock,a,"comment"))))})}getBubble(){return this.textInputBubble}showEditableBubble(){this.createBubble();let a;(a=this.textInputBubble)==null||a.addTextChangeListener(()=>
this.onTextChange());let b;(b=this.textInputBubble)==null||b.addSizeChangeListener(()=>this.onSizeChange())}showNonEditableBubble(){this.createBubble();let a;(a=this.textInputBubble)==null||a.setEditable(!1)}createBubble(){this.textInputBubble=new TextInputBubble$$module$build$src$core$bubbles$textinput_bubble(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect(),this);this.textInputBubble.setText(this.getText());this.textInputBubble.setSize(this.bubbleSize,!0);this.bubbleLocation&&
this.textInputBubble.moveDuringDrag(this.bubbleLocation);this.textInputBubble.addTextChangeListener(()=>this.onTextChange());this.textInputBubble.addSizeChangeListener(()=>this.onSizeChange());this.textInputBubble.addLocationChangeListener(()=>this.onBubbleLocationChange())}hideBubble(){let a;(a=this.textInputBubble)==null||a.dispose();this.textInputBubble=null}getAnchorLocation(){const a=SIZE$$module$build$src$core$icons$comment_icon/2;return Coordinate$$module$build$src$core$utils$coordinate.sum(this.workspaceLocation,
new Coordinate$$module$build$src$core$utils$coordinate(a,a))}getBubbleOwnerRect(){return this.sourceBlock.getBoundingRectangleWithoutChildren()}};CommentIcon$$module$build$src$core$icons$comment_icon.TYPE=IconType$$module$build$src$core$icons$icon_types.COMMENT;CommentIcon$$module$build$src$core$icons$comment_icon.WEIGHT=3;register$$module$build$src$core$icons$registry(CommentIcon$$module$build$src$core$icons$comment_icon.TYPE,CommentIcon$$module$build$src$core$icons$comment_icon);
var module$build$src$core$icons$comment_icon={};module$build$src$core$icons$comment_icon.CommentIcon=CommentIcon$$module$build$src$core$icons$comment_icon;var IconNavigationPolicy$$module$build$src$core$keyboard_nav$icon_navigation_policy=class{getFirstChild(a){if(a instanceof $.MutatorIcon$$module$build$src$core$icons$mutator_icon&&a.bubbleIsVisible()&&$.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode()===a){let b,c;return(c=(b=a.getBubble())==null?void 0:b.getWorkspace())!=null?c:null}if(a instanceof CommentIcon$$module$build$src$core$icons$comment_icon&&a.bubbleIsVisible()&&$.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode()===
a){let b,c;return(c=(b=a.getBubble())==null?void 0:b.getEditor())!=null?c:null}return null}getParent(a){return a.getSourceBlock()}getNextSibling(a){return navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy(a,1)}getPreviousSibling(a){return navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy(a,-1)}isNavigable(a){return a.canBeFocused()}isApplicable(a){return a instanceof Icon$$module$build$src$core$icons$icon}},module$build$src$core$keyboard_nav$icon_navigation_policy=
{};module$build$src$core$keyboard_nav$icon_navigation_policy.IconNavigationPolicy=IconNavigationPolicy$$module$build$src$core$keyboard_nav$icon_navigation_policy;var WorkspaceCommentNavigationPolicy$$module$build$src$core$keyboard_nav$workspace_comment_navigation_policy=class{getFirstChild(a){return a.view.getCommentBarButtons()[0]}getParent(a){return a.workspace}getNextSibling(a){return navigateStacks$$module$build$src$core$keyboard_nav$block_navigation_policy(a,1)}getPreviousSibling(a){return navigateStacks$$module$build$src$core$keyboard_nav$block_navigation_policy(a,-1)}isNavigable(a){return a.canBeFocused()}isApplicable(a){return a instanceof RenderedWorkspaceComment$$module$build$src$core$comments$rendered_workspace_comment}},
module$build$src$core$keyboard_nav$workspace_comment_navigation_policy={};module$build$src$core$keyboard_nav$workspace_comment_navigation_policy.WorkspaceCommentNavigationPolicy=WorkspaceCommentNavigationPolicy$$module$build$src$core$keyboard_nav$workspace_comment_navigation_policy;var WorkspaceNavigationPolicy$$module$build$src$core$keyboard_nav$workspace_navigation_policy=class{getFirstChild(a){a=a.getTopBlocks(!0);return a.length?a[0]:null}getParent(a){return null}getNextSibling(a){return null}getPreviousSibling(a){return null}isNavigable(a){return a.canBeFocused()&&!a.isMutator}isApplicable(a){return a instanceof WorkspaceSvg$$module$build$src$core$workspace_svg}},module$build$src$core$keyboard_nav$workspace_navigation_policy={};
module$build$src$core$keyboard_nav$workspace_navigation_policy.WorkspaceNavigationPolicy=WorkspaceNavigationPolicy$$module$build$src$core$keyboard_nav$workspace_navigation_policy;var Navigator$$module$build$src$core$navigator=class{constructor(){this.rules=[new BlockNavigationPolicy$$module$build$src$core$keyboard_nav$block_navigation_policy,new FieldNavigationPolicy$$module$build$src$core$keyboard_nav$field_navigation_policy,new ConnectionNavigationPolicy$$module$build$src$core$keyboard_nav$connection_navigation_policy,new WorkspaceNavigationPolicy$$module$build$src$core$keyboard_nav$workspace_navigation_policy,new IconNavigationPolicy$$module$build$src$core$keyboard_nav$icon_navigation_policy,
new WorkspaceCommentNavigationPolicy$$module$build$src$core$keyboard_nav$workspace_comment_navigation_policy,new CommentBarButtonNavigationPolicy$$module$build$src$core$keyboard_nav$comment_bar_button_navigation_policy,new BlockCommentNavigationPolicy$$module$build$src$core$keyboard_nav$block_comment_navigation_policy,new CommentEditorNavigationPolicy$$module$build$src$core$keyboard_nav$comment_editor_navigation_policy]}addNavigationPolicy(a){this.rules.push(a)}get(a){return this.rules.find(b=>b.isApplicable(a))}getFirstChild(a){let b;
const c=(b=this.get(a))==null?void 0:b.getFirstChild(a);if(!c)return null;let d;return(d=this.get(c))!=null&&d.isNavigable(c)?c:this.getFirstChild(c)||this.getNextSibling(c)}getParent(a){let b;const c=(b=this.get(a))==null?void 0:b.getParent(a);if(!c)return null;let d;return(d=this.get(c))!=null&&d.isNavigable(c)?c:this.getParent(c)}getNextSibling(a){let b;const c=(b=this.get(a))==null?void 0:b.getNextSibling(a);if(!c)return null;let d;return(d=this.get(c))!=null&&d.isNavigable(c)?c:this.getNextSibling(c)}getPreviousSibling(a){let b;
const c=(b=this.get(a))==null?void 0:b.getPreviousSibling(a);if(!c)return null;let d;return(d=this.get(c))!=null&&d.isNavigable(c)?c:this.getPreviousSibling(c)}},module$build$src$core$navigator={};module$build$src$core$navigator.Navigator=Navigator$$module$build$src$core$navigator;var FlyoutNavigator$$module$build$src$core$flyout_navigator=class extends Navigator$$module$build$src$core$navigator{constructor(a){super();this.rules.push(new FlyoutButtonNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_button_navigation_policy,new FlyoutSeparatorNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_separator_navigation_policy);this.rules=this.rules.map(b=>new FlyoutNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_navigation_policy(b,a))}},module$build$src$core$flyout_navigator=
{};module$build$src$core$flyout_navigator.FlyoutNavigator=FlyoutNavigator$$module$build$src$core$flyout_navigator;var ScrollbarPair$$module$build$src$core$scrollbar_pair=class{constructor(a,b,c,d,e){this.workspace=a;this.oldHostMetrics=this.corner_=this.vScroll=this.hScroll=null;b=b===void 0?!0:b;c=c===void 0?!0:c;const f=b&&c;b&&(this.hScroll=new Scrollbar$$module$build$src$core$scrollbar(a,!0,f,d,e));c&&(this.vScroll=new Scrollbar$$module$build$src$core$scrollbar(a,!1,f,d,e));f&&(this.corner_=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{height:Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness,
width:Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness,"class":"blocklyScrollbarBackground"}),insertAfter$$module$build$src$core$utils$dom(this.corner_,a.getBubbleCanvas()))}dispose(){removeNode$$module$build$src$core$utils$dom(this.corner_);this.oldHostMetrics=this.corner_=null;this.hScroll&&(this.hScroll.dispose(),this.hScroll=null);this.vScroll&&(this.vScroll.dispose(),this.vScroll=null)}resize(){const a=this.workspace.getMetrics();if(a){var b=!1,c=!1;this.oldHostMetrics&&this.oldHostMetrics.viewWidth===
a.viewWidth&&this.oldHostMetrics.viewHeight===a.viewHeight&&this.oldHostMetrics.absoluteTop===a.absoluteTop&&this.oldHostMetrics.absoluteLeft===a.absoluteLeft?(this.oldHostMetrics&&this.oldHostMetrics.scrollWidth===a.scrollWidth&&this.oldHostMetrics.viewLeft===a.viewLeft&&this.oldHostMetrics.scrollLeft===a.scrollLeft||(b=!0),this.oldHostMetrics&&this.oldHostMetrics.scrollHeight===a.scrollHeight&&this.oldHostMetrics.viewTop===a.viewTop&&this.oldHostMetrics.scrollTop===a.scrollTop||(c=!0)):c=b=!0;if(b||
c){try{$.disable$$module$build$src$core$events$utils(),this.hScroll&&b&&this.hScroll.resize(a),this.vScroll&&c&&this.vScroll.resize(a)}finally{$.enable$$module$build$src$core$events$utils()}this.workspace.maybeFireViewportChangeEvent()}if(this.hScroll&&this.vScroll){if(!this.oldHostMetrics||this.oldHostMetrics.viewWidth!==a.viewWidth||this.oldHostMetrics.absoluteLeft!==a.absoluteLeft){let d;(d=this.corner_)==null||d.setAttribute("x",String(this.vScroll.position.x))}if(!this.oldHostMetrics||this.oldHostMetrics.viewHeight!==
a.viewHeight||this.oldHostMetrics.absoluteTop!==a.absoluteTop){let d;(d=this.corner_)==null||d.setAttribute("y",String(this.hScroll.position.y))}}this.oldHostMetrics=a}}canScrollHorizontally(){return!!this.hScroll}canScrollVertically(){return!!this.vScroll}setOrigin(a,b){this.hScroll&&this.hScroll.setOrigin(a,b);this.vScroll&&this.vScroll.setOrigin(a,b)}set(a,b,c){this.hScroll&&this.hScroll.set(a,!1);this.vScroll&&this.vScroll.set(b,!1);if(c||c===void 0)a={},this.hScroll&&(a.x=this.hScroll.getRatio_()),
this.vScroll&&(a.y=this.vScroll.getRatio_()),this.workspace.setMetrics(a)}setX(a){this.hScroll&&this.hScroll.set(a,!0)}setY(a){this.vScroll&&this.vScroll.set(a,!0)}setContainerVisible(a){this.hScroll&&this.hScroll.setContainerVisible(a);this.vScroll&&this.vScroll.setContainerVisible(a)}isVisible(){let a=!1;this.hScroll&&(a=this.hScroll.isVisible());this.vScroll&&(a=a||this.vScroll.isVisible());return a}setVisible(a){this.hScroll&&this.hScroll.setVisibleInternal(a);this.vScroll&&this.vScroll.setVisibleInternal(a)}resizeContent(a){this.hScroll&&
this.hScroll.resizeContentHorizontal(a);this.vScroll&&this.vScroll.resizeContentVertical(a)}resizeView(a){this.hScroll&&this.hScroll.resizeViewHorizontal(a);this.vScroll&&this.vScroll.resizeViewVertical(a)}},module$build$src$core$scrollbar_pair={};module$build$src$core$scrollbar_pair.ScrollbarPair=ScrollbarPair$$module$build$src$core$scrollbar_pair;var SEPARATOR_TYPE$$module$build$src$core$separator_flyout_inflater="sep",SeparatorFlyoutInflater$$module$build$src$core$separator_flyout_inflater=class{load(a,b){a=new FlyoutSeparator$$module$build$src$core$flyout_separator(0,b.horizontalLayout?"x":"y");return new FlyoutItem$$module$build$src$core$flyout_item(a,SEPARATOR_TYPE$$module$build$src$core$separator_flyout_inflater)}gapForItem(a,b){let c;return(c=parseInt(String(a.gap)))!=null?c:b}disposeItem(a){}getType(){return SEPARATOR_TYPE$$module$build$src$core$separator_flyout_inflater}};
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUT_INFLATER,SEPARATOR_TYPE$$module$build$src$core$separator_flyout_inflater,SeparatorFlyoutInflater$$module$build$src$core$separator_flyout_inflater);var module$build$src$core$separator_flyout_inflater={SEPARATOR_TYPE:SEPARATOR_TYPE$$module$build$src$core$separator_flyout_inflater};module$build$src$core$separator_flyout_inflater.SeparatorFlyoutInflater=SeparatorFlyoutInflater$$module$build$src$core$separator_flyout_inflater;var Flyout$$module$build$src$core$flyout_base=class extends DeleteArea$$module$build$src$core$delete_area{constructor(a){super();this.horizontalLayout=!1;this.boundEvents=[];this.reflowWrapper=null;this.contents=[];this.autoClose=!0;this.visible=!1;this.containerVisible=!0;this.CORNER_RADIUS=8;this.SCROLLBAR_MARGIN=2.5;this.height_=this.width_=0;this.dragAngleRange_=70;this.svgGroup_=this.svgBackground_=null;this.inflaters=new Map;a.setMetrics=this.setMetrics_.bind(this);this.workspace_=new WorkspaceSvg$$module$build$src$core$workspace_svg(a);
this.workspace_.setMetricsManager(new FlyoutMetricsManager$$module$build$src$core$flyout_metrics_manager(this.workspace_,this));this.workspace_.internalIsFlyout=!0;this.workspace_.setVisible(this.visible);this.workspace_.setNavigator(new FlyoutNavigator$$module$build$src$core$flyout_navigator(this));this.id=genUid$$module$build$src$core$utils$idgenerator();this.RTL=!!a.RTL;this.toolboxPosition_=a.toolboxPosition;this.tabWidth_=this.workspace_.getRenderer().getConstants().TAB_WIDTH;this.MARGIN=this.CORNER_RADIUS;
this.GAP_X=this.MARGIN*3;this.GAP_Y=this.MARGIN*3}createDom(a){this.svgGroup_=createSvgElement$$module$build$src$core$utils$dom(a,{"class":"blocklyFlyout"});this.svgGroup_.style.display="none";this.svgBackground_=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,{"class":"blocklyFlyoutBackground"},this.svgGroup_);this.svgGroup_.appendChild(this.workspace_.createDom());this.workspace_.getThemeManager().subscribe(this.svgBackground_,"flyoutBackgroundColour",
"fill");this.workspace_.getThemeManager().subscribe(this.svgBackground_,"flyoutOpacity","fill-opacity");return this.svgGroup_}init(a){this.targetWorkspace=a;this.workspace_.targetWorkspace=a;this.workspace_.scrollbar=new ScrollbarPair$$module$build$src$core$scrollbar_pair(this.workspace_,this.horizontalLayout,!this.horizontalLayout,"blocklyFlyoutScrollbar",this.SCROLLBAR_MARGIN);this.hide();this.boundEvents.push(conditionalBind$$module$build$src$core$browser_events(this.svgGroup_,"wheel",this,this.wheel_));
this.boundEvents.push(conditionalBind$$module$build$src$core$browser_events(this.svgBackground_,"pointerdown",this,this.onMouseDown));this.workspace_.getGesture=this.targetWorkspace.getGesture.bind(this.targetWorkspace);this.workspace_.setVariableMap(this.targetWorkspace.getVariableMap());this.workspace_.createPotentialVariableMap();a.getComponentManager().addComponent({component:this,weight:ComponentManager$$module$build$src$core$component_manager.ComponentWeight.FLYOUT_WEIGHT,capabilities:[ComponentManager$$module$build$src$core$component_manager.Capability.AUTOHIDEABLE,
ComponentManager$$module$build$src$core$component_manager.Capability.DELETE_AREA,ComponentManager$$module$build$src$core$component_manager.Capability.DRAG_TARGET]})}dispose(){this.hide();this.targetWorkspace.getComponentManager().removeComponent(this.id);for(const a of this.boundEvents)unbind$$module$build$src$core$browser_events(a);this.boundEvents.length=0;this.workspace_&&(this.workspace_.getThemeManager().unsubscribe(this.svgBackground_),this.workspace_.dispose());this.svgGroup_&&removeNode$$module$build$src$core$utils$dom(this.svgGroup_)}getWidth(){return this.width_}getHeight(){return this.height_}getFlyoutScale(){return this.targetWorkspace.scale}getWorkspace(){return this.workspace_}setAutoClose(a){this.autoClose=
a;this.targetWorkspace.recordDragTargets();this.targetWorkspace.resizeContents()}autoHide(a){!a&&this.targetWorkspace.getFlyout(!0)===this&&this.autoClose&&this.hide()}getTargetWorkspace(){return this.targetWorkspace}isVisible(){return this.visible}setVisible(a){const b=a!==this.isVisible();this.visible=a;b&&(this.autoClose||this.targetWorkspace.recordDragTargets(),this.updateDisplay())}setContainerVisible(a){const b=a!==this.containerVisible;this.containerVisible=a;b&&this.updateDisplay()}getContents(){return this.contents}setContents(a){this.contents=
a}updateDisplay(){let a;a=this.containerVisible?this.isVisible():!1;this.svgGroup_&&(this.svgGroup_.style.display=a?"block":"none");let b;(b=this.workspace_.scrollbar)==null||b.setContainerVisible(a)}positionAt_(a,b,c,d){let e;(e=this.svgGroup_)==null||e.setAttribute("width",`${a}`);let f;(f=this.svgGroup_)==null||f.setAttribute("height",`${b}`);this.workspace_.setCachedParentSvgSize(a,b);this.svgGroup_&&setCssTransform$$module$build$src$core$utils$dom(this.svgGroup_,"translate("+c+"px,"+d+"px)");
if(a=this.workspace_.scrollbar)a.setOrigin(c,d),a.resize(),a.hScroll&&a.hScroll.setPosition(a.hScroll.position.x,a.hScroll.position.y),a.vScroll&&a.vScroll.setPosition(a.vScroll.position.x,a.vScroll.position.y)}hide(){this.isVisible()&&(this.setVisible(!1),this.reflowWrapper&&(this.workspace_.removeChangeListener(this.reflowWrapper),this.reflowWrapper=null))}show(a){this.workspace_.setResizesEnabled(!1);this.hide();this.clearOldBlocks();typeof a==="string"&&(a=this.getDynamicCategoryContents(a));
this.setVisible(!0);a=convertFlyoutDefToJsonArray$$module$build$src$core$utils$toolbox(a);a=this.createFlyoutInfo(a);triggerQueuedRenders$$module$build$src$core$render_management(this.workspace_);this.setContents(a);this.layout_(a);this.horizontalLayout?this.height_=0:this.width_=0;this.reflow();this.workspace_.setResizesEnabled(!0);this.reflowWrapper=b=>{b.type!==EventType$$module$build$src$core$events$type.BLOCK_CHANGE&&b.type!==EventType$$module$build$src$core$events$type.BLOCK_FIELD_INTERMEDIATE_CHANGE||
this.reflow()};this.workspace_.addChangeListener(this.reflowWrapper)}createFlyoutInfo(a){const b=[],c=this.horizontalLayout?this.GAP_X:this.GAP_Y;for(const d of a)if("custom"in d&&(a=this.getDynamicCategoryContents(d.custom),a=convertFlyoutDefToJsonArray$$module$build$src$core$utils$toolbox(a),b.push(...this.createFlyoutInfo(a))),a=d.kind.toLowerCase(),a=this.getInflaterForType(a))b.push(a.load(d,this)),(a=a.gapForItem(d,c))&&b.push(new FlyoutItem$$module$build$src$core$flyout_item(new FlyoutSeparator$$module$build$src$core$flyout_separator(a,
this.horizontalLayout?"x":"y"),SEPARATOR_TYPE$$module$build$src$core$separator_flyout_inflater));return this.normalizeSeparators(b)}normalizeSeparators(a){for(let b=a.length-1;b>0;b--){const c=a[b].getType().toLowerCase(),d=a[b-1].getType().toLowerCase();c===SEPARATOR_TYPE$$module$build$src$core$separator_flyout_inflater&&d===SEPARATOR_TYPE$$module$build$src$core$separator_flyout_inflater&&a.splice(b-1,1)}return a}getDynamicCategoryContents(a){a=this.workspace_.targetWorkspace.getToolboxCategoryCallback(a);
if(typeof a!=="function")throw TypeError("Couldn't find a callback function when opening a toolbox category.");return a(this.workspace_.targetWorkspace)}clearOldBlocks(){this.getContents().forEach(b=>{let c;(c=this.getInflaterForType(b.getType()))==null||c.disposeItem(b)});let a;(a=this.workspace_.getPotentialVariableMap())==null||a.clear()}onMouseDown(a){const b=this.targetWorkspace.getGesture(a);b&&b.handleFlyoutStart(a,this)}isBlockCreatable(a){return a.isEnabled()&&!this.getTargetWorkspace().isReadOnly()}createBlock(a){let b=
null;$.disable$$module$build$src$core$events$utils();var c=this.targetWorkspace.getAllVariables();this.targetWorkspace.setResizesEnabled(!1);try{b=this.placeNewBlock(a)}finally{$.enable$$module$build$src$core$events$utils()}this.targetWorkspace.hideChaff();a=getAddedVariables$$module$build$src$core$variables(this.targetWorkspace,c);if(isEnabled$$module$build$src$core$events$utils()){$.setGroup$$module$build$src$core$events$utils(!0);for(c=0;c<a.length;c++){const d=a[c];fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.VAR_CREATE))(d))}fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CREATE))(b))}this.autoClose&&
this.hide();return b}reflow(){this.reflowWrapper&&this.workspace_.removeChangeListener(this.reflowWrapper);this.reflowInternal_();this.reflowWrapper&&this.workspace_.addChangeListener(this.reflowWrapper)}isScrollable(){return this.workspace_.scrollbar?this.workspace_.scrollbar.isVisible():!1}placeNewBlock(a){var b=this.targetWorkspace;if(!a.getSvgRoot())throw Error("oldBlock is not rendered");const c=this.serializeBlock(a);b.setResizesEnabled(!1);b=append$$module$build$src$core$serialization$blocks(c,
b);this.positionNewBlock(a,b);return b}serializeBlock(a){return save$$module$build$src$core$serialization$blocks(a)}positionNewBlock(a,b){const c=this.targetWorkspace;var d=c.getOriginOffsetInPixels(),e=this.workspace_.getOriginOffsetInPixels();a=a.getRelativeToSurfaceXY();a.scale(this.workspace_.scale);e=Coordinate$$module$build$src$core$utils$coordinate.sum(e,a);d=Coordinate$$module$build$src$core$utils$coordinate.difference(e,d);d.scale(1/c.scale);b.moveTo(new Coordinate$$module$build$src$core$utils$coordinate(d.x,
d.y))}getInflaterForType(a){if(this.inflaters.has(a)){var b;return(b=this.inflaters.get(a))!=null?b:null}return(b=getClass$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUT_INFLATER,a))?(b=new b,this.inflaters.set(a,b),b):null}getFocusableElement(){throw Error("Flyouts are not directly focusable.");}getFocusableTree(){throw Error("Flyouts are not directly focusable.");}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!1}getRootFocusableNode(){throw Error("Flyouts are not directly focusable.");
}getRestoredFocusableNode(a){throw Error("Flyouts are not directly focusable.");}getNestedTrees(){throw Error("Flyouts are not directly focusable.");}lookUpFocusableNode(a){throw Error("Flyouts are not directly focusable.");}onTreeFocus(a,b){}onTreeBlur(a){throw Error("Flyouts are not directly focusable.");}},module$build$src$core$flyout_base={};module$build$src$core$flyout_base.Flyout=Flyout$$module$build$src$core$flyout_base;var module$build$src$core$interfaces$i_draggable={};module$build$src$core$interfaces$i_draggable.isDraggable=isDraggable$$module$build$src$core$interfaces$i_draggable;var KeyboardNavigationController$$module$build$src$core$keyboard_navigation_controller=class{constructor(){this.isActive=!1;this.activeClassName="blocklyKeyboardNavigation"}setIsActive(a=!0){this.isActive=a;this.updateActiveVisualization()}getIsActive(){return this.isActive}updateActiveVisualization(){this.isActive?document.body.classList.add(this.activeClassName):document.body.classList.remove(this.activeClassName)}},keyboardNavigationController$$module$build$src$core$keyboard_navigation_controller=
new KeyboardNavigationController$$module$build$src$core$keyboard_navigation_controller,module$build$src$core$keyboard_navigation_controller={};module$build$src$core$keyboard_navigation_controller.KeyboardNavigationController=KeyboardNavigationController$$module$build$src$core$keyboard_navigation_controller;module$build$src$core$keyboard_navigation_controller.keyboardNavigationController=keyboardNavigationController$$module$build$src$core$keyboard_navigation_controller;var WorkspaceDragger$$module$build$src$core$workspace_dragger=class{constructor(a){this.workspace=a;this.horizontalScrollEnabled=this.workspace.isMovableHorizontally();this.verticalScrollEnabled=this.workspace.isMovableVertically();this.startScrollXY_=new Coordinate$$module$build$src$core$utils$coordinate(a.scrollX,a.scrollY)}dispose(){this.workspace=null}startDrag(){}endDrag(a){this.drag(a)}drag(a){a=Coordinate$$module$build$src$core$utils$coordinate.sum(this.startScrollXY_,a);if(this.horizontalScrollEnabled&&
this.verticalScrollEnabled)this.workspace.scroll(a.x,a.y);else if(this.horizontalScrollEnabled)this.workspace.scroll(a.x,this.workspace.scrollY);else if(this.verticalScrollEnabled)this.workspace.scroll(this.workspace.scrollX,a.y);else throw new TypeError("Invalid state.");}},module$build$src$core$workspace_dragger={};module$build$src$core$workspace_dragger.WorkspaceDragger=WorkspaceDragger$$module$build$src$core$workspace_dragger;var ZOOM_IN_MULTIPLIER$$module$build$src$core$gesture=5,ZOOM_OUT_MULTIPLIER$$module$build$src$core$gesture=6,Gesture$$module$build$src$core$gesture=class{constructor(a,b){this.creatorWorkspace=b;this.mouseDownXY=new Coordinate$$module$build$src$core$utils$coordinate(0,0);this.startWorkspace_=this.targetBlock=this.startComment=this.startBlock=this.startIcon=this.startField=this.startBubble=null;this.hasExceededDragRadius=!1;this.boundEvents=[];this.workspaceDragger=this.dragger=null;this.dragging=
!1;this.flyout=null;this.multiTouch=this.isEnding_=this.gestureHasStarted=this.calledUpdateIsDragging=!1;this.cachedPoints=new Map;this.startDistance=this.previousScale=0;this.currentDropdownOwner=this.isPinchZoomEnabled=null;this.mostRecentEvent=a;this.currentDragDeltaXY=new Coordinate$$module$build$src$core$utils$coordinate(0,0)}dispose(){clearTouchIdentifier$$module$build$src$core$touch();unblock$$module$build$src$core$tooltip();this.creatorWorkspace.clearGesture();for(const a of this.boundEvents)unbind$$module$build$src$core$browser_events(a);
this.boundEvents.length=0;this.workspaceDragger&&this.workspaceDragger.dispose()}updateFromEvent(a){const b=new Coordinate$$module$build$src$core$utils$coordinate(a.clientX,a.clientY);this.updateDragDelta(b)&&(this.updateIsDragging(a),longStop$$module$build$src$core$touch());this.mostRecentEvent=a}updateDragDelta(a){this.currentDragDeltaXY=Coordinate$$module$build$src$core$utils$coordinate.difference(a,this.mouseDownXY);return this.hasExceededDragRadius?!1:this.hasExceededDragRadius=Coordinate$$module$build$src$core$utils$coordinate.magnitude(this.currentDragDeltaXY)>
(this.flyout?$.config$$module$build$src$core$config.flyoutDragRadius:$.config$$module$build$src$core$config.dragRadius)}updateIsDraggingFromFlyout(){let a;if(!this.targetBlock||(a=this.flyout)==null||!a.isBlockCreatable(this.targetBlock))return!1;if(!this.flyout.targetWorkspace)throw Error("Cannot update dragging from the flyout because the ' +\n          'flyout's target workspace is undefined");return!this.flyout.isScrollable()||this.flyout.isDragTowardWorkspace(this.currentDragDeltaXY)?(this.startWorkspace_=
this.flyout.targetWorkspace,this.startWorkspace_.updateScreenCalculationsIfScrolled(),$.getGroup$$module$build$src$core$events$utils()||$.setGroup$$module$build$src$core$events$utils(!0),this.startBlock=null,this.targetBlock=this.flyout.createBlock(this.targetBlock),$.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.targetBlock),!0):!1}updateIsDraggingWorkspace(){if(!this.startWorkspace_)throw Error("Cannot update dragging the workspace because the start workspace is undefined");
if(this.flyout?this.flyout.isScrollable():this.startWorkspace_&&this.startWorkspace_.isDraggable())this.dragging=!0,this.workspaceDragger=new WorkspaceDragger$$module$build$src$core$workspace_dragger(this.startWorkspace_),this.workspaceDragger.startDrag()}updateIsDragging(a){if(!this.startWorkspace_)throw Error("Cannot update dragging because the start workspace is undefined");if(this.calledUpdateIsDragging)throw Error("updateIsDragging_ should only be called once per gesture.");this.calledUpdateIsDragging=
!0;this.flyout&&this.updateIsDraggingFromFlyout();const b=getSelected$$module$build$src$core$common();b&&isDraggable$$module$build$src$core$interfaces$i_draggable(b)&&b.isMovable()?(this.dragging=!0,this.dragger=this.createDragger(b,this.startWorkspace_),this.dragger.onDragStart(a),this.dragger.onDrag(a,this.currentDragDeltaXY)):this.updateIsDraggingWorkspace()}createDragger(a,b){return new (getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.BLOCK_DRAGGER,this.creatorWorkspace.options,
!0))(a,b)}doStart(a){if(!this.startWorkspace_)throw Error("Cannot start the touch gesture becauase the start workspace is undefined");this.isPinchZoomEnabled=this.startWorkspace_.options.zoomOptions&&this.startWorkspace_.options.zoomOptions.pinch;isTargetInput$$module$build$src$core$browser_events(a)?this.cancel():(this.gestureHasStarted=!0,disconnectUiStop$$module$build$src$core$block_animations(),this.startWorkspace_.updateScreenCalculationsIfScrolled(),this.startWorkspace_.isMutator&&this.startWorkspace_.resize(),
this.currentDropdownOwner=getOwner$$module$build$src$core$dropdowndiv(),this.startWorkspace_.hideChaff(!!this.flyout),this.startWorkspace_.markFocused(),this.mostRecentEvent=a,block$$module$build$src$core$tooltip(),isRightButton$$module$build$src$core$browser_events(a)?this.handleRightClick(a):(a.type.toLowerCase()==="pointerdown"&&a.pointerType!=="mouse"&&longStart$$module$build$src$core$touch(a,this),this.mouseDownXY=new Coordinate$$module$build$src$core$utils$coordinate(a.clientX,a.clientY),this.bindMouseEvents(a),
this.isEnding_||this.handleTouchStart(a)))}bindMouseEvents(a){this.boundEvents.push(conditionalBind$$module$build$src$core$browser_events(document,"pointerdown",null,this.handleStart.bind(this),!0));this.boundEvents.push(conditionalBind$$module$build$src$core$browser_events(document,"pointermove",null,this.handleMove.bind(this),!0));this.boundEvents.push(conditionalBind$$module$build$src$core$browser_events(document,"pointerup",null,this.handleUp.bind(this),!0));this.boundEvents.push(conditionalBind$$module$build$src$core$browser_events(document,
"pointercancel",null,this.handleUp.bind(this),!0));a.preventDefault();a.stopPropagation()}handleStart(a){this.isDragging()||(this.handleTouchStart(a),this.isMultiTouch()&&longStop$$module$build$src$core$touch())}handleMove(a){if(this.isDragging()&&shouldHandleEvent$$module$build$src$core$touch(a)||!this.isMultiTouch()){this.updateFromEvent(a);if(this.workspaceDragger)this.workspaceDragger.drag(this.currentDragDeltaXY);else if(this.dragger)this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY);
a.preventDefault();a.stopPropagation()}else this.isMultiTouch()&&(this.handleTouchMove(a),longStop$$module$build$src$core$touch())}handleUp(a){this.isDragging()||this.handleTouchEnd(a);if(!this.isMultiTouch()||this.isDragging()){if(!shouldHandleEvent$$module$build$src$core$touch(a))return;this.updateFromEvent(a);longStop$$module$build$src$core$touch();if(this.isEnding_){console.log("Trying to end a gesture recursively.");return}this.isEnding_=!0;this.dragger?(keyboardNavigationController$$module$build$src$core$keyboard_navigation_controller.setIsActive(!1),
this.dragger.onDragEnd(a,this.currentDragDeltaXY)):this.workspaceDragger?(keyboardNavigationController$$module$build$src$core$keyboard_navigation_controller.setIsActive(!1),this.workspaceDragger.endDrag(this.currentDragDeltaXY)):this.isBubbleClick()||this.isCommentClick()||(this.isFieldClick()?this.doFieldClick():this.isIconClick()?this.doIconClick():this.isBlockClick()?this.doBlockClick():this.isWorkspaceClick()&&this.doWorkspaceClick(a))}a.preventDefault();a.stopPropagation();this.dispose()}handleTouchStart(a){var b=
getTouchIdentifierFromEvent$$module$build$src$core$touch(a);this.cachedPoints.set(b,this.getTouchPoint(a));var c=Array.from(this.cachedPoints.keys());c.length===2&&(b=this.cachedPoints.get(c[0]),c=this.cachedPoints.get(c[1]),this.startDistance=Coordinate$$module$build$src$core$utils$coordinate.distance(b,c),this.multiTouch=!0,a.preventDefault())}handleTouchMove(a){const b=getTouchIdentifierFromEvent$$module$build$src$core$touch(a);this.cachedPoints.set(b,this.getTouchPoint(a));if(this.isPinchZoomEnabled&&
this.cachedPoints.size===2)this.handlePinch(a);else{this.updateFromEvent(a);if(this.workspaceDragger)this.workspaceDragger.drag(this.currentDragDeltaXY);else if(this.dragger)this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY);a.preventDefault();a.stopPropagation()}}handlePinch(a){var b=Array.from(this.cachedPoints.keys()),c=this.cachedPoints.get(b[0]);b=this.cachedPoints.get(b[1]);c=Coordinate$$module$build$src$core$utils$coordinate.distance(c,b)/this.startDistance;if(this.previousScale>
0&&this.previousScale<Infinity){b=c-this.previousScale;b=b>0?b*ZOOM_IN_MULTIPLIER$$module$build$src$core$gesture:b*ZOOM_OUT_MULTIPLIER$$module$build$src$core$gesture;if(!this.startWorkspace_)throw Error("Cannot handle a pinch because the start workspace is undefined");const d=this.startWorkspace_,e=mouseToSvg$$module$build$src$core$browser_events(a,d.getParentSvg(),d.getInverseScreenCTM());d.zoom(e.x,e.y,b)}this.previousScale=c;a.preventDefault()}handleTouchEnd(a){a=getTouchIdentifierFromEvent$$module$build$src$core$touch(a);
this.cachedPoints.has(a)&&this.cachedPoints.delete(a);this.cachedPoints.size<2&&(this.cachedPoints.clear(),this.previousScale=0)}getTouchPoint(a){return this.startWorkspace_?new Coordinate$$module$build$src$core$utils$coordinate(a.pageX,a.pageY):null}isMultiTouch(){return this.multiTouch}cancel(){if(!this.isEnding_){longStop$$module$build$src$core$touch();if(this.dragger)this.dragger.onDragEnd(this.mostRecentEvent,this.currentDragDeltaXY);else this.workspaceDragger&&this.workspaceDragger.endDrag(this.currentDragDeltaXY);
this.dispose()}}handleRightClick(a){this.targetBlock?(this.bringBlockToFront(),this.targetBlock.workspace.hideChaff(!!this.flyout),this.targetBlock.showContextMenu(a)):this.startBubble?this.startBubble.showContextMenu(a):this.startComment?(this.startComment.workspace.hideChaff(),this.startComment.showContextMenu(a)):this.startWorkspace_&&!this.flyout&&(this.startWorkspace_.hideChaff(),$.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.startWorkspace_),this.startWorkspace_.showContextMenu(a));
a.preventDefault();a.stopPropagation();keyboardNavigationController$$module$build$src$core$keyboard_navigation_controller.setIsActive(!1);this.dispose()}handleWsStart(a,b){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleWsStart, but the gesture had already been started.");this.setStartWorkspace(b);this.mostRecentEvent=a;this.startBlock||this.startBubble||this.startComment?this.startBlock&&$.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.startBlock):$.getFocusManager$$module$build$src$core$focus_manager().focusNode(b);
this.doStart(a)}fireWorkspaceClick(a){fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.CLICK))(null,a.id,"workspace"))}handleFlyoutStart(a,b){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleFlyoutStart, but the gesture had already been started.");this.setStartFlyout(b);this.handleWsStart(a,b.getWorkspace())}handleBlockStart(a,b){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBlockStart, but the gesture had already been started.");
this.setStartBlock(b);this.mostRecentEvent=a}handleBubbleStart(a,b){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBubbleStart, but the gesture had already been started.");this.setStartBubble(b);this.mostRecentEvent=a}handleCommentStart(a,b){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleCommentStart, but the gesture had already been started.");this.setStartComment(b);this.mostRecentEvent=a}doFieldClick(){if(!this.startField)throw Error("Cannot do a field click because the start field is undefined");
this.bringBlockToFront();this.currentDropdownOwner!==this.startField&&this.startField.showEditor(this.mostRecentEvent)}doIconClick(){if(!this.startIcon)throw Error("Cannot do an icon click because the start icon is undefined");this.bringBlockToFront();this.startIcon.onClick()}doBlockClick(){if(this.flyout&&this.flyout.autoClose){if(!this.targetBlock)throw Error("Cannot do a block click because the target block is undefined");if(this.flyout.isBlockCreatable(this.targetBlock)){$.getGroup$$module$build$src$core$events$utils()||
$.setGroup$$module$build$src$core$events$utils(!0);var a=this.flyout.createBlock(this.targetBlock);a.snapToGrid();a.bumpNeighbours();$.getFocusManager$$module$build$src$core$focus_manager().focusNode(a)}}else{if(!this.startWorkspace_)throw Error("Cannot do a block click because the start workspace is undefined");a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.CLICK))(this.startBlock,this.startWorkspace_.id,"block");fire$$module$build$src$core$events$utils(a)}this.bringBlockToFront();
$.setGroup$$module$build$src$core$events$utils(!1)}doWorkspaceClick(a){this.fireWorkspaceClick(this.startWorkspace_||this.creatorWorkspace)}bringBlockToFront(){this.targetBlock&&!this.flyout&&($.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.targetBlock),this.targetBlock.bringToFront())}setStartField(a){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartField, but the gesture had already been started.");this.startField||(this.startField=a)}setStartIcon(a){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartIcon, but the gesture had already been started.");
this.startIcon||(this.startIcon=a)}setStartBubble(a){this.startBubble||(this.startBubble=a)}setStartComment(a){this.startComment||(this.startComment=a)}setStartBlock(a){this.startBlock||this.startBubble||(this.startBlock=a,a.isInFlyout&&a!==a.getRootBlock()?this.setTargetBlock(a.getRootBlock()):this.setTargetBlock(a))}setTargetBlock(a){a.isShadow()?this.setTargetBlock(a.getParent()):(this.targetBlock=a,$.getFocusManager$$module$build$src$core$focus_manager().focusNode(a))}setStartWorkspace(a){this.startWorkspace_||
(this.startWorkspace_=a)}setStartFlyout(a){this.flyout||(this.flyout=a)}isBubbleClick(){return!!this.startBubble&&!this.hasExceededDragRadius}isCommentClick(){return!!this.startComment&&!this.hasExceededDragRadius}isBlockClick(){return!!this.startBlock&&!this.hasExceededDragRadius&&!this.isFieldClick()&&!this.isIconClick()}isFieldClick(){return this.startField?this.startField.isClickable()&&!this.hasExceededDragRadius&&(!this.flyout||this.startField.isClickableInFlyout(this.flyout.autoClose)):!1}isIconClick(){if(!this.startIcon)return!1;
const a=!this.flyout||!this.startIcon.isClickableInFlyout||this.startIcon.isClickableInFlyout(this.flyout.autoClose);return!this.hasExceededDragRadius&&a}isWorkspaceClick(){return!this.startBlock&&!this.startBubble&&!this.startField&&!this.hasExceededDragRadius}getCurrentDragger(){let a,b;return(b=(a=this.workspaceDragger)!=null?a:this.dragger)!=null?b:null}isDragging(){return this.dragging}hasStarted(){return this.gestureHasStarted}static inProgress(){const a=getAllWorkspaces$$module$build$src$core$common();
for(let b=0,c;c=a[b];b++)if(c.currentGesture_)return!0;return!1}},module$build$src$core$gesture={};module$build$src$core$gesture.Gesture=Gesture$$module$build$src$core$gesture;var Grid$$module$build$src$core$grid=class{constructor(a,b){this.pattern=a;this.scale=1;let c;this.spacing=(c=b.spacing)!=null?c:0;let d;this.length=(d=b.length)!=null?d:1;this.line2=(this.line1=a.firstChild)&&this.line1.nextSibling;let e;this.snapToGrid=(e=b.snap)!=null?e:!1}setSpacing(a){this.spacing=a;this.update(this.scale)}getSpacing(){return this.spacing}setLength(a){this.length=a;this.update(this.scale)}getLength(){return this.length}setSnapToGrid(a){this.snapToGrid=a}shouldSnap(){return this.snapToGrid}getPatternId(){return this.pattern.id}update(a){this.scale=
a;var b=this.spacing*a;this.pattern.setAttribute("width",`${b}`);this.pattern.setAttribute("height",`${b}`);b=Math.floor(this.spacing/2)+.5;let c=b-this.length/2,d=b+this.length/2;b*=a;c*=a;d*=a;this.setLineAttributes(this.line1,a,c,d,b,b);this.setLineAttributes(this.line2,a,b,b,c,d)}setLineAttributes(a,b,c,d,e,f){a&&(a.setAttribute("stroke-width",`${b}`),a.setAttribute("x1",`${c}`),a.setAttribute("y1",`${e}`),a.setAttribute("x2",`${d}`),a.setAttribute("y2",`${f}`))}moveTo(a,b){this.pattern.setAttribute("x",
`${a}`);this.pattern.setAttribute("y",`${b}`)}alignXY(a){var b=this.getSpacing();const c=b/2,d=Math.round(Math.round((a.x-c)/b)*b+c);b=Math.round(Math.round((a.y-c)/b)*b+c);return d===a.x&&b===a.y?a:new Coordinate$$module$build$src$core$utils$coordinate(d,b)}static createDom(a,b,c,d){a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATTERN,{id:"blocklyGridPattern"+a,patternUnits:"userSpaceOnUse"},c);let e,f;if(((e=b.length)!=null?e:1)>0&&((f=b.spacing)!=null?
f:0)>0){createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.LINE,{stroke:b.colour},a);let g;(g=b.length)!=null&&g&&createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.LINE,{stroke:b.colour},a)}else createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.LINE,{},a);d&&d.style.setProperty("--blocklyGridPattern",`url(#${a.id})`);return a}},module$build$src$core$grid={};
module$build$src$core$grid.Grid=Grid$$module$build$src$core$grid;var module$build$src$core$interfaces$i_autohideable={};module$build$src$core$interfaces$i_autohideable.isAutoHideable=isAutoHideable$$module$build$src$core$interfaces$i_autohideable;var LayerManager$$module$build$src$core$layer_manager=class{constructor(a){this.workspace=a;this.layers=new Map;if(a=a.getInjectionDiv())this.dragLayer=this.createDragLayer(a),this.animationLayer=this.createAnimationLayer(a);a=this.createLayer(BLOCK$$module$build$src$core$layers);addClass$$module$build$src$core$utils$dom(a,"blocklyBlockCanvas");a=this.createLayer(BUBBLE$$module$build$src$core$layers);addClass$$module$build$src$core$utils$dom(a,"blocklyBubbleCanvas")}createDragLayer(a){const b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.SVG,
{"class":"blocklyBlockDragSurface",xmlns:SVG_NS$$module$build$src$core$utils$dom,"xmlns:html":HTML_NS$$module$build$src$core$utils$dom,"xmlns:xlink":XLINK_NS$$module$build$src$core$utils$dom,version:"1.1"});a.append(b);return createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{},b)}createAnimationLayer(a){const b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.SVG,{"class":"blocklyAnimationLayer",xmlns:SVG_NS$$module$build$src$core$utils$dom,
"xmlns:html":HTML_NS$$module$build$src$core$utils$dom,"xmlns:xlink":XLINK_NS$$module$build$src$core$utils$dom,version:"1.1"});a.append(b);return createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{},b)}appendToAnimationLayer(a){let b;const c=(b=this.dragLayer)==null?void 0:b.getAttribute("transform");if(c){let e;(e=this.animationLayer)==null||e.setAttribute("transform",c)}let d;(d=this.animationLayer)==null||d.appendChild(a.getSvgRoot())}translateLayers(a,b){a=
`translate(${a.x}, ${a.y}) scale(${b})`;let c;(c=this.dragLayer)==null||c.setAttribute("transform",a);for(const [,d]of this.layers)d.setAttribute("transform",a)}moveToDragLayer(a){let b;(b=this.dragLayer)==null||b.appendChild(a.getSvgRoot());a.canBeFocused()&&$.getFocusManager$$module$build$src$core$focus_manager().focusNode(a)}moveOffDragLayer(a,b){this.append(a,b);a.canBeFocused()&&$.getFocusManager$$module$build$src$core$focus_manager().focusNode(a)}append(a,b){this.layers.has(b)||this.createLayer(b);
a=a.getSvgRoot();let c;if(((c=this.layers.get(b))==null?void 0:c.lastChild)!==a){let d;(d=this.layers.get(b))==null||d.appendChild(a)}}createLayer(a){const b=this.workspace.getSvgGroup(),c=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{});let d=!1;const e=[...this.layers].sort((f,g)=>f[0]-g[0]);for(const [f,g]of e)if(a<f){b.insertBefore(c,g);d=!0;break}d||b.appendChild(c);this.layers.set(a,c);return c}hasLayer(a){return a===this.dragLayer||(new Set(this.layers.values())).has(a)}getBlockLayer(){return this.layers.get(BLOCK$$module$build$src$core$layers)}getBubbleLayer(){return this.layers.get(BUBBLE$$module$build$src$core$layers)}},
module$build$src$core$layer_manager={};module$build$src$core$layer_manager.LayerManager=LayerManager$$module$build$src$core$layer_manager;var Marker$$module$build$src$core$keyboard_nav$marker=class{constructor(){this.curNode=this.colour=null;this.type="marker"}getCurNode(){return this.curNode}setCurNode(a){this.curNode=a}dispose(){this.curNode=null}getSourceBlockFromNode(a){return a instanceof BlockSvg$$module$build$src$core$block_svg?a:a instanceof Field$$module$build$src$core$field||a instanceof RenderedConnection$$module$build$src$core$rendered_connection?a.getSourceBlock():null}getSourceBlock(){return this.getSourceBlockFromNode(this.getCurNode())}},
module$build$src$core$keyboard_nav$marker={};module$build$src$core$keyboard_nav$marker.Marker=Marker$$module$build$src$core$keyboard_nav$marker;var LineCursor$$module$build$src$core$keyboard_nav$line_cursor=class extends Marker$$module$build$src$core$keyboard_nav$marker{constructor(a){super();this.workspace=a;this.type="cursor";this.potentialNodes=null}next(){var a=this.getCurNode();if(!a)return null;(a=this.getNextNode(a,b=>{let c;return b instanceof BlockSvg$$module$build$src$core$block_svg&&!((c=b.outputConnection)==null?0:c.targetBlock())||b instanceof RenderedWorkspaceComment$$module$build$src$core$comments$rendered_workspace_comment},
!0))&&this.setCurNode(a);return a}in(){var a=this.getCurNode();if(!a)return null;(a=this.getNextNode(a,()=>!0,!0))&&this.setCurNode(a);return a}prev(){var a=this.getCurNode();if(!a)return null;(a=this.getPreviousNode(a,b=>{let c;return b instanceof BlockSvg$$module$build$src$core$block_svg&&!((c=b.outputConnection)==null?0:c.targetBlock())||b instanceof RenderedWorkspaceComment$$module$build$src$core$comments$rendered_workspace_comment},!0))&&this.setCurNode(a);return a}out(){var a=this.getCurNode();
if(!a)return null;(a=this.getPreviousNode(a,()=>!0,!0))&&this.setCurNode(a);return a}atEndOfLine(){var a=this.getCurNode();if(!a)return!1;const b=this.getNextNode(a,()=>!0,!0);a=this.getNextNode(a,c=>{let d;return c instanceof BlockSvg$$module$build$src$core$block_svg&&!((d=c.outputConnection)==null?0:d.targetBlock())},!0);return b===a}getNextNodeImpl(a,b,c=new Set){if(!a||c.has(a))return null;let d=this.workspace.getNavigator().getFirstChild(a)||this.workspace.getNavigator().getNextSibling(a);for(var e=
a;e&&!d;){e=this.workspace.getNavigator().getParent(e);if(!e)break;d=this.workspace.getNavigator().getNextSibling(e)}return b(d)?d:d?(c.add(a),this.getNextNodeImpl(d,b,c)):null}getNextNode(a,b,c){return!a||!c&&this.getLastNode()===a?null:this.getNextNodeImpl(a,b)}getPreviousNodeImpl(a,b,c=new Set){if(!a||c.has(a))return null;const d=this.getRightMostChild(this.workspace.getNavigator().getPreviousSibling(a),a)||this.workspace.getNavigator().getParent(a);return b(d)?d:d?(c.add(a),this.getPreviousNodeImpl(d,
b,c)):null}getPreviousNode(a,b,c){return!a||!c&&this.getFirstNode()===a?null:this.getPreviousNodeImpl(a,b)}getRightMostChild(a,b){if(!a)return a;let c=this.workspace.getNavigator().getFirstChild(a);if(!c||c===b)return a;for(a=c;a&&a!==b;a=this.workspace.getNavigator().getNextSibling(c))c=a;return this.getRightMostChild(c,b)}preDelete(a){var b=this.getCurNode();b=b?[b]:[];var c;let d,e;const f=(e=(c=a.previousConnection)==null?void 0:c.targetConnection)!=null?e:(d=a.outputConnection)==null?void 0:
d.targetConnection;f&&b.push(f);(c=a.getNextBlock())&&b.push(c);(a=a.getParent())&&b.push(a);b.push(this.workspace);this.potentialNodes=b}postDelete(){const a=this.potentialNodes;this.potentialNodes=null;if(!a)throw Error("must call preDelete first");for(const b of a){let c;if((c=this.getSourceBlockFromNode(b))==null||!c.disposed){this.setCurNode(b);return}}throw Error("no valid nodes in this.potentialNodes");}getCurNode(){return $.getFocusManager$$module$build$src$core$focus_manager().getFocusedNode()}setCurNode(a){$.getFocusManager$$module$build$src$core$focus_manager().focusNode(a)}getFirstNode(){return this.workspace.getNavigator().getFirstChild(this.workspace)}getLastNode(){const a=
this.getFirstNode();return this.getPreviousNode(a,()=>!0,!0)}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.CURSOR,DEFAULT$$module$build$src$core$registry,LineCursor$$module$build$src$core$keyboard_nav$line_cursor);var module$build$src$core$keyboard_nav$line_cursor={};module$build$src$core$keyboard_nav$line_cursor.LineCursor=LineCursor$$module$build$src$core$keyboard_nav$line_cursor;var MarkerManager$$module$build$src$core$marker_manager=class{constructor(a){this.workspace=a;this.markers=new Map;this.cursor=new LineCursor$$module$build$src$core$keyboard_nav$line_cursor(this.workspace)}registerMarker(a,b){this.markers.has(a)&&this.unregisterMarker(a);this.markers.set(a,b)}unregisterMarker(a){const b=this.markers.get(a);if(b)b.dispose(),this.markers.delete(a);else throw Error("Marker with ID "+a+" does not exist. Can only unregister markers that exist.");}getCursor(){return this.cursor}getMarker(a){return this.markers.get(a)||
null}setCursor(a){this.cursor=a}dispose(){const a=Object.keys(this.markers);for(let b=0,c;c=a[b];b++)this.unregisterMarker(c);this.markers.clear();this.cursor.dispose()}};MarkerManager$$module$build$src$core$marker_manager.LOCAL_MARKER="local_marker_1";var module$build$src$core$marker_manager={};module$build$src$core$marker_manager.MarkerManager=MarkerManager$$module$build$src$core$marker_manager;var module$build$src$core$icons={};module$build$src$core$icons.CommentIcon=CommentIcon$$module$build$src$core$icons$comment_icon;module$build$src$core$icons.Icon=Icon$$module$build$src$core$icons$icon;module$build$src$core$icons.IconType=IconType$$module$build$src$core$icons$icon_types;module$build$src$core$icons.MutatorIcon=$.MutatorIcon$$module$build$src$core$icons$mutator_icon;module$build$src$core$icons.WarningIcon=WarningIcon$$module$build$src$core$icons$warning_icon;
module$build$src$core$icons.exceptions=module$build$src$core$icons$exceptions;module$build$src$core$icons.registry=module$build$src$core$icons$registry;var module$build$src$core$interfaces$i_procedure_block={};module$build$src$core$interfaces$i_procedure_block.isProcedureBlock=isProcedureBlock$$module$build$src$core$interfaces$i_procedure_block;$.Names$$module$build$src$core$names=class{constructor(a,b){this.db=new Map;this.dbReverse=new Set;this.variableMap=null;this.variablePrefix=b||"";this.reservedWords=new Set(a?a.split(","):[])}reset(){this.db.clear();this.dbReverse.clear();this.variableMap=null}setVariableMap(a){this.variableMap=a}getNameForUserVariable(a){return this.variableMap?(a=this.variableMap.getVariableById(a))?a.getName():null:(console.warn("Deprecated call to Names.prototype.getName without defining a variable map. To fix, add the following code in your generator's init() function:\nBlockly.YourGeneratorName.nameDB_.setVariableMap(workspace.getVariableMap());"),
null)}populateVariables(a){a=$.allUsedVarModels$$module$build$src$core$variables(a);for(let b=0;b<a.length;b++)this.getName(a[b].getId(),$.NameType$$module$build$src$core$names.VARIABLE)}populateProcedures(a){throw Error("The implementation of populateProcedures should be monkey-patched in by blockly.ts");}getName(a,b){let c=a;b===$.NameType$$module$build$src$core$names.VARIABLE&&(a=this.getNameForUserVariable(a))&&(c=a);a=c.toLowerCase();const d=b===$.NameType$$module$build$src$core$names.VARIABLE||
b===$.NameType$$module$build$src$core$names.DEVELOPER_VARIABLE?this.variablePrefix:"";this.db.has(b)||this.db.set(b,new Map);const e=this.db.get(b);if(e.has(a))return d+e.get(a);b=this.getDistinctName(c,b);e.set(a,b.substr(d.length));return b}getUserNames(a){let b;return(a=(b=this.db.get(a))==null?void 0:b.keys())?Array.from(a):[]}getDistinctName(a,b){a=this.safeName(a);let c=null,d,e;for(;this.dbReverse.has(a+((d=c)!=null?d:""))||this.reservedWords.has(a+((e=c)!=null?e:""));)c=c?c+1:2;let f;a+=(f=
c)!=null?f:"";this.dbReverse.add(a);return(b===$.NameType$$module$build$src$core$names.VARIABLE||b===$.NameType$$module$build$src$core$names.DEVELOPER_VARIABLE?this.variablePrefix:"")+a}safeName(a){a?(a=encodeURI(a.replace(/ /g,"_")).replace(/[^\w]/g,"_"),"0123456789".includes(a[0])&&(a="my_"+a)):a=$.Msg$$module$build$src$core$msg.UNNAMED_KEY||"unnamed";return a}static equals(a,b){return a.toLowerCase()===b.toLowerCase()}};
(function(a){a=a.NameType||(a.NameType={});a.DEVELOPER_VARIABLE="DEVELOPER_VARIABLE";a.VARIABLE="VARIABLE";a.PROCEDURE="PROCEDURE"})($.Names$$module$build$src$core$names||($.Names$$module$build$src$core$names={}));$.NameType$$module$build$src$core$names=$.Names$$module$build$src$core$names.NameType;$.Names$$module$build$src$core$names.DEVELOPER_VARIABLE_TYPE=$.NameType$$module$build$src$core$names.DEVELOPER_VARIABLE;var module$build$src$core$names={NameType:$.NameType$$module$build$src$core$names};
module$build$src$core$names.Names=$.Names$$module$build$src$core$names;var module$build$src$core$interfaces$i_observable={};module$build$src$core$interfaces$i_observable.isObservable=isObservable$$module$build$src$core$interfaces$i_observable;var ObservableProcedureMap$$module$build$src$core$observable_procedure_map=class extends Map{constructor(){super()}set(a,b){if(this.get(a)===b)return this;super.set(a,b);isObservable$$module$build$src$core$interfaces$i_observable(b)&&b.startPublishing();return this}delete(a){const b=this.get(a);a=super.delete(a);if(!a)return a;isObservable$$module$build$src$core$interfaces$i_observable(b)&&b.stopPublishing();return a}clear(){if(this.size)for(const a of this.keys())this.delete(a)}add(a){return this.set(a.getId(),
a)}getProcedures(){return[...this.values()]}},module$build$src$core$observable_procedure_map={};module$build$src$core$observable_procedure_map.ObservableProcedureMap=ObservableProcedureMap$$module$build$src$core$observable_procedure_map;var CATEGORY_NAME$$module$build$src$core$procedures,module$build$src$core$procedures;CATEGORY_NAME$$module$build$src$core$procedures="PROCEDURE";$.DEFAULT_ARG$$module$build$src$core$procedures="x";module$build$src$core$procedures={CATEGORY_NAME:CATEGORY_NAME$$module$build$src$core$procedures,DEFAULT_ARG:$.DEFAULT_ARG$$module$build$src$core$procedures};module$build$src$core$procedures.ObservableProcedureMap=ObservableProcedureMap$$module$build$src$core$observable_procedure_map;
module$build$src$core$procedures.allProcedures=allProcedures$$module$build$src$core$procedures;module$build$src$core$procedures.findLegalName=$.findLegalName$$module$build$src$core$procedures;module$build$src$core$procedures.flyoutCategory=flyoutCategory$$module$build$src$core$procedures;module$build$src$core$procedures.getCallers=getCallers$$module$build$src$core$procedures;module$build$src$core$procedures.getDefinition=$.getDefinition$$module$build$src$core$procedures;
module$build$src$core$procedures.internalFlyoutCategory=internalFlyoutCategory$$module$build$src$core$procedures;module$build$src$core$procedures.isNameUsed=isNameUsed$$module$build$src$core$procedures;module$build$src$core$procedures.isProcedureBlock=isProcedureBlock$$module$build$src$core$interfaces$i_procedure_block;module$build$src$core$procedures.mutateCallers=$.mutateCallers$$module$build$src$core$procedures;module$build$src$core$procedures.mutatorOpenListener=mutatorOpenListener$$module$build$src$core$procedures;
module$build$src$core$procedures.rename=$.rename$$module$build$src$core$procedures;var TypesContainer$$module$build$src$core$renderers$measurables$types=class{constructor(){this.NONE=0;this.FIELD=1;this.HAT=2;this.ICON=4;this.SPACER=8;this.BETWEEN_ROW_SPACER=16;this.IN_ROW_SPACER=32;this.EXTERNAL_VALUE_INPUT=64;this.INPUT=128;this.INLINE_INPUT=256;this.STATEMENT_INPUT=512;this.CONNECTION=1024;this.PREVIOUS_CONNECTION=2048;this.NEXT_CONNECTION=4096;this.OUTPUT_CONNECTION=8192;this.CORNER=16384;this.LEFT_SQUARE_CORNER=32768;this.LEFT_ROUND_CORNER=65536;this.RIGHT_SQUARE_CORNER=131072;
this.RIGHT_ROUND_CORNER=262144;this.JAGGED_EDGE=524288;this.ROW=1048576;this.TOP_ROW=2097152;this.BOTTOM_ROW=4194304;this.INPUT_ROW=8388608;this.LEFT_CORNER=this.LEFT_SQUARE_CORNER|this.LEFT_ROUND_CORNER;this.RIGHT_CORNER=this.RIGHT_SQUARE_CORNER|this.RIGHT_ROUND_CORNER;this.nextTypeValue_=16777216}getType(a){Object.prototype.hasOwnProperty.call(this,a)||(this[a]=this.nextTypeValue_,this.nextTypeValue_<<=1);return this[a]}isField(a){return(a.type&this.FIELD)>=1}isHat(a){return(a.type&this.HAT)>=1}isIcon(a){return(a.type&
this.ICON)>=1}isSpacer(a){return(a.type&this.SPACER)>=1}isInRowSpacer(a){return(a.type&this.IN_ROW_SPACER)>=1}isSpacerRow(a){return(a.type&this.BETWEEN_ROW_SPACER)>=1}isInput(a){return(a.type&this.INPUT)>=1}isExternalInput(a){return(a.type&this.EXTERNAL_VALUE_INPUT)>=1}isInlineInput(a){return(a.type&this.INLINE_INPUT)>=1}isStatementInput(a){return(a.type&this.STATEMENT_INPUT)>=1}isPreviousConnection(a){return(a.type&this.PREVIOUS_CONNECTION)>=1}isNextConnection(a){return(a.type&this.NEXT_CONNECTION)>=
1}isPreviousOrNextConnection(a){return this.isPreviousConnection(a)||this.isNextConnection(a)}isRoundCorner(a){return(a.type&this.LEFT_ROUND_CORNER)>=1||(a.type&this.RIGHT_ROUND_CORNER)>=1}isLeftRoundedCorner(a){return this.isRoundCorner(a)&&(a.type&this.LEFT_ROUND_CORNER)>=1}isRightRoundedCorner(a){return this.isRoundCorner(a)&&(a.type&this.RIGHT_ROUND_CORNER)>=1}isLeftSquareCorner(a){return(a.type&this.LEFT_SQUARE_CORNER)>=1}isRightSquareCorner(a){return(a.type&this.RIGHT_SQUARE_CORNER)>=1}isCorner(a){return(a.type&
this.CORNER)>=1}isJaggedEdge(a){return(a.type&this.JAGGED_EDGE)>=1}isRow(a){return(a.type&this.ROW)>=1}isBetweenRowSpacer(a){return(a.type&this.BETWEEN_ROW_SPACER)>=1}isTopRow(a){return(a.type&this.TOP_ROW)>=1}isBottomRow(a){return(a.type&this.BOTTOM_ROW)>=1}isTopOrBottomRow(a){return this.isTopRow(a)||this.isBottomRow(a)}isInputRow(a){return(a.type&this.INPUT_ROW)>=1}},Types$$module$build$src$core$renderers$measurables$types=new TypesContainer$$module$build$src$core$renderers$measurables$types,module$build$src$core$renderers$measurables$types=
{Types:Types$$module$build$src$core$renderers$measurables$types};var Measurable$$module$build$src$core$renderers$measurables$base=class{constructor(a){this.centerline=this.xPos=this.height=this.width=0;this.constants_=a;this.type=Types$$module$build$src$core$renderers$measurables$types.NONE;this.notchOffset=this.constants_.NOTCH_OFFSET_LEFT}},module$build$src$core$renderers$measurables$base={};module$build$src$core$renderers$measurables$base.Measurable=Measurable$$module$build$src$core$renderers$measurables$base;var Row$$module$build$src$core$renderers$measurables$row=class{constructor(a){this.elements=[];this.xPos=this.yPos=this.widthWithConnectedBlocks=this.minWidth=this.minHeight=this.width=this.height=0;this.hasStatement=this.hasExternalInput=!1;this.statementEdge=0;this.hasJaggedEdge=this.hasDummyInput=this.hasInlineInput=!1;this.align=null;this.constants_=a;this.type=Types$$module$build$src$core$renderers$measurables$types.ROW;this.notchOffset=this.constants_.NOTCH_OFFSET_LEFT}getLastInput(){for(let a=
this.elements.length-1;a>=0;a--){const b=this.elements[a];if(Types$$module$build$src$core$renderers$measurables$types.isInput(b))return b}return null}measure(){throw Error("Unexpected attempt to measure a base Row.");}startsWithElemSpacer(){return!0}endsWithElemSpacer(){return!0}getFirstSpacer(){for(let a=0;a<this.elements.length;a++){const b=this.elements[a];if(Types$$module$build$src$core$renderers$measurables$types.isInRowSpacer(b))return b}return null}getLastSpacer(){for(let a=this.elements.length-
1;a>=0;a--){const b=this.elements[a];if(Types$$module$build$src$core$renderers$measurables$types.isInRowSpacer(b))return b}return null}},module$build$src$core$renderers$measurables$row={};module$build$src$core$renderers$measurables$row.Row=Row$$module$build$src$core$renderers$measurables$row;var BottomRow$$module$build$src$core$renderers$measurables$bottom_row=class extends Row$$module$build$src$core$renderers$measurables$row{constructor(a){super(a);this.hasNextConnection=!1;this.connection=null;this.baseline=this.descenderHeight=0;this.type|=Types$$module$build$src$core$renderers$measurables$types.BOTTOM_ROW}hasLeftSquareCorner(a){return!!a.outputConnection||!!a.getNextBlock()}hasRightSquareCorner(a){return!0}measure(){let a=0,b=0,c=0;for(let d=0;d<this.elements.length;d++){const e=
this.elements[d];b+=e.width;Types$$module$build$src$core$renderers$measurables$types.isSpacer(e)||(Types$$module$build$src$core$renderers$measurables$types.isNextConnection(e)?c=Math.max(c,e.height):a=Math.max(a,e.height))}this.width=Math.max(this.minWidth,b);this.height=Math.max(this.minHeight,a)+c;this.descenderHeight=c;this.widthWithConnectedBlocks=this.width}startsWithElemSpacer(){return!1}endsWithElemSpacer(){return!1}},module$build$src$core$renderers$measurables$bottom_row={};
module$build$src$core$renderers$measurables$bottom_row.BottomRow=BottomRow$$module$build$src$core$renderers$measurables$bottom_row;var Connection$$module$build$src$core$renderers$measurables$connection=class extends Measurable$$module$build$src$core$renderers$measurables$base{constructor(a,b){super(a);this.connectionModel=b;this.type|=Types$$module$build$src$core$renderers$measurables$types.CONNECTION;this.shape=this.constants_.shapeFor(b);this.isDynamicShape="isDynamic"in this.shape&&this.shape.isDynamic;this.highlighted=b.isHighlighted()}},module$build$src$core$renderers$measurables$connection={};
module$build$src$core$renderers$measurables$connection.Connection=Connection$$module$build$src$core$renderers$measurables$connection;var InputConnection$$module$build$src$core$renderers$measurables$input_connection=class extends Connection$$module$build$src$core$renderers$measurables$connection{constructor(a,b){super(a,b.connection);this.input=b;this.connectionOffsetY=this.connectionOffsetX=0;this.type|=Types$$module$build$src$core$renderers$measurables$types.INPUT;this.align=b.align;(this.connectedBlock=b.connection&&b.connection.targetBlock()?b.connection.targetBlock():null)?(a=this.connectedBlock.getHeightWidth(),this.connectedBlockWidth=
a.width,this.connectedBlockHeight=a.height):this.connectedBlockHeight=this.connectedBlockWidth=0}},module$build$src$core$renderers$measurables$input_connection={};module$build$src$core$renderers$measurables$input_connection.InputConnection=InputConnection$$module$build$src$core$renderers$measurables$input_connection;var ExternalValueInput$$module$build$src$core$renderers$measurables$external_value_input=class extends InputConnection$$module$build$src$core$renderers$measurables$input_connection{constructor(a,b){super(a,b);this.height=0;this.type|=Types$$module$build$src$core$renderers$measurables$types.EXTERNAL_VALUE_INPUT;this.height=this.connectedBlock?this.connectedBlockHeight-this.constants_.TAB_OFFSET_FROM_TOP-this.constants_.MEDIUM_PADDING:this.shape.height;this.width=this.shape.width+this.constants_.EXTERNAL_VALUE_INPUT_PADDING;
this.connectionOffsetY=this.constants_.TAB_OFFSET_FROM_TOP;this.connectionHeight=this.shape.height;this.connectionWidth=this.shape.width}},module$build$src$core$renderers$measurables$external_value_input={};module$build$src$core$renderers$measurables$external_value_input.ExternalValueInput=ExternalValueInput$$module$build$src$core$renderers$measurables$external_value_input;var Field$$module$build$src$core$renderers$measurables$field=class extends Measurable$$module$build$src$core$renderers$measurables$base{constructor(a,b,c){super(a);this.field=b;this.parentInput=c;this.isEditable=b.EDITABLE;this.flipRtl=b.getFlipRtl();this.type|=Types$$module$build$src$core$renderers$measurables$types.FIELD;a=this.field.getSize();this.height=a.height;this.width=a.width}},module$build$src$core$renderers$measurables$field={};module$build$src$core$renderers$measurables$field.Field=Field$$module$build$src$core$renderers$measurables$field;var Hat$$module$build$src$core$renderers$measurables$hat=class extends Measurable$$module$build$src$core$renderers$measurables$base{constructor(a){super(a);this.type|=Types$$module$build$src$core$renderers$measurables$types.HAT;this.height=this.constants_.START_HAT.height;this.width=this.constants_.START_HAT.width;this.ascenderHeight=this.height}},module$build$src$core$renderers$measurables$hat={};module$build$src$core$renderers$measurables$hat.Hat=Hat$$module$build$src$core$renderers$measurables$hat;var Icon$$module$build$src$core$renderers$measurables$icon=class extends Measurable$$module$build$src$core$renderers$measurables$base{constructor(a,b){super(a);this.icon=b;this.flipRtl=!1;this.type|=Types$$module$build$src$core$renderers$measurables$types.ICON;a=b.getSize();this.height=a.height;this.width=a.width}},module$build$src$core$renderers$measurables$icon={};module$build$src$core$renderers$measurables$icon.Icon=Icon$$module$build$src$core$renderers$measurables$icon;var InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer=class extends Measurable$$module$build$src$core$renderers$measurables$base{constructor(a,b){super(a);this.type|=Types$$module$build$src$core$renderers$measurables$types.SPACER|Types$$module$build$src$core$renderers$measurables$types.IN_ROW_SPACER;this.width=b;this.height=this.constants_.SPACER_DEFAULT_HEIGHT}},module$build$src$core$renderers$measurables$in_row_spacer={};
module$build$src$core$renderers$measurables$in_row_spacer.InRowSpacer=InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer;var InlineInput$$module$build$src$core$renderers$measurables$inline_input=class extends InputConnection$$module$build$src$core$renderers$measurables$input_connection{constructor(a,b){super(a,b);this.type|=Types$$module$build$src$core$renderers$measurables$types.INLINE_INPUT;this.connectedBlock?(this.width=this.connectedBlockWidth,this.height=this.connectedBlockHeight):(this.height=this.constants_.EMPTY_INLINE_INPUT_HEIGHT,this.width=this.constants_.EMPTY_INLINE_INPUT_PADDING);this.connectionHeight=
this.isDynamicShape?this.shape.height(this.height):this.shape.height;this.connectionWidth=this.isDynamicShape?this.shape.width(this.height):this.shape.width;this.connectedBlock||(this.width+=this.connectionWidth*(this.isDynamicShape?2:1));this.connectionOffsetY="connectionOffsetY"in this.shape?this.shape.connectionOffsetY(this.connectionHeight):this.constants_.TAB_OFFSET_FROM_TOP;this.connectionOffsetX="connectionOffsetX"in this.shape?this.shape.connectionOffsetX(this.connectionWidth):0}},module$build$src$core$renderers$measurables$inline_input=
{};module$build$src$core$renderers$measurables$inline_input.InlineInput=InlineInput$$module$build$src$core$renderers$measurables$inline_input;var InputRow$$module$build$src$core$renderers$measurables$input_row=class extends Row$$module$build$src$core$renderers$measurables$row{constructor(a){super(a);this.connectedBlockWidths=0;this.type|=Types$$module$build$src$core$renderers$measurables$types.INPUT_ROW}measure(){this.width=this.minWidth;this.height=this.minHeight;let a=0;for(let b=0;b<this.elements.length;b++){const c=this.elements[b];this.width+=c.width;Types$$module$build$src$core$renderers$measurables$types.isInput(c)&&(Types$$module$build$src$core$renderers$measurables$types.isStatementInput(c)?
a+=c.connectedBlockWidth:Types$$module$build$src$core$renderers$measurables$types.isExternalInput(c)&&c.connectedBlockWidth!==0&&(a+=c.connectedBlockWidth-c.connectionWidth));Types$$module$build$src$core$renderers$measurables$types.isSpacer(c)||(this.height=Math.max(this.height,c.height))}this.connectedBlockWidths=a;this.widthWithConnectedBlocks=this.width+a}endsWithElemSpacer(){return!this.hasExternalInput&&!this.hasStatement}},module$build$src$core$renderers$measurables$input_row={};
module$build$src$core$renderers$measurables$input_row.InputRow=InputRow$$module$build$src$core$renderers$measurables$input_row;var JaggedEdge$$module$build$src$core$renderers$measurables$jagged_edge=class extends Measurable$$module$build$src$core$renderers$measurables$base{constructor(a){super(a);this.type|=Types$$module$build$src$core$renderers$measurables$types.JAGGED_EDGE;this.height=this.constants_.JAGGED_TEETH.height;this.width=this.constants_.JAGGED_TEETH.width}},module$build$src$core$renderers$measurables$jagged_edge={};module$build$src$core$renderers$measurables$jagged_edge.JaggedEdge=JaggedEdge$$module$build$src$core$renderers$measurables$jagged_edge;var NextConnection$$module$build$src$core$renderers$measurables$next_connection=class extends Connection$$module$build$src$core$renderers$measurables$connection{constructor(a,b){super(a,b);this.type|=Types$$module$build$src$core$renderers$measurables$types.NEXT_CONNECTION;this.height=this.shape.height;this.width=this.shape.width}},module$build$src$core$renderers$measurables$next_connection={};module$build$src$core$renderers$measurables$next_connection.NextConnection=NextConnection$$module$build$src$core$renderers$measurables$next_connection;var OutputConnection$$module$build$src$core$renderers$measurables$output_connection=class extends Connection$$module$build$src$core$renderers$measurables$connection{constructor(a,b){super(a,b);this.connectionOffsetX=0;this.type|=Types$$module$build$src$core$renderers$measurables$types.OUTPUT_CONNECTION;this.height=this.isDynamicShape?0:this.shape.height;this.startX=this.width=this.isDynamicShape?0:this.shape.width;this.connectionOffsetY=this.constants_.TAB_OFFSET_FROM_TOP}},module$build$src$core$renderers$measurables$output_connection=
{};module$build$src$core$renderers$measurables$output_connection.OutputConnection=OutputConnection$$module$build$src$core$renderers$measurables$output_connection;var PreviousConnection$$module$build$src$core$renderers$measurables$previous_connection=class extends Connection$$module$build$src$core$renderers$measurables$connection{constructor(a,b){super(a,b);this.type|=Types$$module$build$src$core$renderers$measurables$types.PREVIOUS_CONNECTION;this.height=this.shape.height;this.width=this.shape.width}},module$build$src$core$renderers$measurables$previous_connection={};module$build$src$core$renderers$measurables$previous_connection.PreviousConnection=PreviousConnection$$module$build$src$core$renderers$measurables$previous_connection;var RoundCorner$$module$build$src$core$renderers$measurables$round_corner=class extends Measurable$$module$build$src$core$renderers$measurables$base{constructor(a,b){super(a);this.type=(b&&b!=="left"?Types$$module$build$src$core$renderers$measurables$types.RIGHT_ROUND_CORNER:Types$$module$build$src$core$renderers$measurables$types.LEFT_ROUND_CORNER)|Types$$module$build$src$core$renderers$measurables$types.CORNER;this.width=this.constants_.CORNER_RADIUS;this.height=this.constants_.CORNER_RADIUS/2}},
module$build$src$core$renderers$measurables$round_corner={};module$build$src$core$renderers$measurables$round_corner.RoundCorner=RoundCorner$$module$build$src$core$renderers$measurables$round_corner;var SpacerRow$$module$build$src$core$renderers$measurables$spacer_row=class extends Row$$module$build$src$core$renderers$measurables$row{constructor(a,b,c){super(a);this.height=b;this.width=c;this.precedesStatement=this.followsStatement=!1;this.widthWithConnectedBlocks=0;this.type|=Types$$module$build$src$core$renderers$measurables$types.SPACER|Types$$module$build$src$core$renderers$measurables$types.BETWEEN_ROW_SPACER;this.elements=[new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,
c)]}measure(){}},module$build$src$core$renderers$measurables$spacer_row={};module$build$src$core$renderers$measurables$spacer_row.SpacerRow=SpacerRow$$module$build$src$core$renderers$measurables$spacer_row;var SquareCorner$$module$build$src$core$renderers$measurables$square_corner=class extends Measurable$$module$build$src$core$renderers$measurables$base{constructor(a,b){super(a);this.type=(b&&b!=="left"?Types$$module$build$src$core$renderers$measurables$types.RIGHT_SQUARE_CORNER:Types$$module$build$src$core$renderers$measurables$types.LEFT_SQUARE_CORNER)|Types$$module$build$src$core$renderers$measurables$types.CORNER;this.width=this.height=this.constants_.NO_PADDING}},module$build$src$core$renderers$measurables$square_corner=
{};module$build$src$core$renderers$measurables$square_corner.SquareCorner=SquareCorner$$module$build$src$core$renderers$measurables$square_corner;var StatementInput$$module$build$src$core$renderers$measurables$statement_input=class extends InputConnection$$module$build$src$core$renderers$measurables$input_connection{constructor(a,b){super(a,b);this.type|=Types$$module$build$src$core$renderers$measurables$types.STATEMENT_INPUT;this.height=this.connectedBlock?this.connectedBlockHeight+this.constants_.STATEMENT_BOTTOM_SPACER:this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT;this.width=this.constants_.STATEMENT_INPUT_NOTCH_OFFSET+this.shape.width}},
module$build$src$core$renderers$measurables$statement_input={};module$build$src$core$renderers$measurables$statement_input.StatementInput=StatementInput$$module$build$src$core$renderers$measurables$statement_input;var TopRow$$module$build$src$core$renderers$measurables$top_row=class extends Row$$module$build$src$core$renderers$measurables$row{constructor(a){super(a);this.ascenderHeight=this.capline=0;this.hasPreviousConnection=!1;this.connection=null;this.type|=Types$$module$build$src$core$renderers$measurables$types.TOP_ROW}hasLeftSquareCorner(a){const b=(a.hat?a.hat==="cap":this.constants_.ADD_START_HATS)&&!a.outputConnection&&!a.previousConnection,c=a.getPreviousBlock();return!!a.outputConnection||b||(c?
c.getNextBlock()===a:!1)}hasRightSquareCorner(a){return!0}measure(){let a=0,b=0,c=0;for(let d=0;d<this.elements.length;d++){const e=this.elements[d];b+=e.width;Types$$module$build$src$core$renderers$measurables$types.isSpacer(e)||(Types$$module$build$src$core$renderers$measurables$types.isHat(e)?c=Math.max(c,e.ascenderHeight):a=Math.max(a,e.height))}this.width=Math.max(this.minWidth,b);this.height=Math.max(this.minHeight,a)+c;this.capline=this.ascenderHeight=c;this.widthWithConnectedBlocks=this.width}startsWithElemSpacer(){return!1}endsWithElemSpacer(){return!1}},
module$build$src$core$renderers$measurables$top_row={};module$build$src$core$renderers$measurables$top_row.TopRow=TopRow$$module$build$src$core$renderers$measurables$top_row;var ConstantProvider$$module$build$src$core$renderers$common$constants=class{constructor(){this.NO_PADDING=0;this.SMALL_PADDING=3;this.MEDIUM_PADDING=5;this.MEDIUM_LARGE_PADDING=8;this.LARGE_PADDING=10;this.TAB_HEIGHT=15;this.TAB_OFFSET_FROM_TOP=5;this.TAB_VERTICAL_OVERLAP=2.5;this.TAB_WIDTH=8;this.NOTCH_WIDTH=15;this.NOTCH_HEIGHT=4;this.MIN_BLOCK_WIDTH=12;this.EMPTY_BLOCK_SPACER_HEIGHT=16;this.CORNER_RADIUS=8;this.NOTCH_OFFSET_LEFT=15;this.STATEMENT_BOTTOM_SPACER=0;this.STATEMENT_INPUT_PADDING_LEFT=
20;this.BETWEEN_STATEMENT_PADDING_Y=4;this.ADD_START_HATS=!1;this.START_HAT_HEIGHT=15;this.START_HAT_WIDTH=100;this.SPACER_DEFAULT_HEIGHT=15;this.MIN_BLOCK_HEIGHT=24;this.EMPTY_INLINE_INPUT_PADDING=14.5;this.EXTERNAL_VALUE_INPUT_PADDING=2;this.JAGGED_TEETH_HEIGHT=12;this.JAGGED_TEETH_WIDTH=6;this.FIELD_TEXT_FONTSIZE=11;this.FIELD_TEXT_FONTWEIGHT="normal";this.FIELD_TEXT_FONTFAMILY="sans-serif";this.FIELD_TEXT_BASELINE=this.FIELD_TEXT_HEIGHT=-1;this.FIELD_BORDER_RECT_RADIUS=4;this.FIELD_BORDER_RECT_HEIGHT=
16;this.FIELD_BORDER_RECT_X_PADDING=5;this.FIELD_BORDER_RECT_Y_PADDING=3;this.FIELD_BORDER_RECT_COLOUR="#fff";this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!1;this.FIELD_DROPDOWN_SVG_ARROW_SIZE=12;this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=!1;this.FIELD_COLOUR_DEFAULT_WIDTH=26;this.defs=null;this.embossFilterId="";this.embossFilter=null;this.disabledPatternId="";this.disabledPattern=null;this.debugFilterId="";this.cssNode=
this.debugFilter=null;this.CURSOR_COLOUR="#cc0a0a";this.MARKER_COLOUR="#4286f4";this.CURSOR_WS_WIDTH=100;this.WS_CURSOR_HEIGHT=5;this.CURSOR_STACK_PADDING=10;this.CURSOR_BLOCK_PADDING=2;this.CURSOR_STROKE_WIDTH=4;this.FULL_BLOCK_FIELDS=!1;this.INSERTION_MARKER_COLOUR="#000000";this.INSERTION_MARKER_OPACITY=.2;this.SHAPES={PUZZLE:1,NOTCH:2};this.TALL_INPUT_FIELD_OFFSET_Y=this.MEDIUM_PADDING;this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=this.DUMMY_INPUT_MIN_HEIGHT=this.TAB_HEIGHT;this.STATEMENT_INPUT_NOTCH_OFFSET=
this.NOTCH_OFFSET_LEFT;this.TOP_ROW_MIN_HEIGHT=this.MEDIUM_PADDING;this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING;this.BOTTOM_ROW_MIN_HEIGHT=this.MEDIUM_PADDING;this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING;this.EMPTY_INLINE_INPUT_HEIGHT=this.TAB_HEIGHT+11;this.EMPTY_STATEMENT_INPUT_HEIGHT=this.MIN_BLOCK_HEIGHT;this.START_POINT=moveBy$$module$build$src$core$utils$svg_paths(0,0);this.FIELD_TEXT_BASELINE_CENTER=!0;this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT;
this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING;this.FIELD_DROPDOWN_SVG_ARROW_DATAURI="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiNmZmYiLz48L3N2Zz4=";
this.FIELD_COLOUR_DEFAULT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT;this.FIELD_CHECKBOX_X_OFFSET=this.FIELD_BORDER_RECT_X_PADDING-3;this.randomIdentifier=String(Math.random()).substring(2)}init(){this.JAGGED_TEETH=this.makeJaggedTeeth();this.NOTCH=this.makeNotch();this.START_HAT=this.makeStartHat();this.PUZZLE_TAB=this.makePuzzleTab();this.INSIDE_CORNERS=this.makeInsideCorners();this.OUTSIDE_CORNERS=this.makeOutsideCorners()}setTheme(a){this.blockStyles=Object.create(null);const b=a.blockStyles;for(const c in b)this.blockStyles[c]=
this.validatedBlockStyle_(b[c]);this.setDynamicProperties_(a)}setDynamicProperties_(a){this.setFontConstants_(a);this.setComponentConstants_(a);this.ADD_START_HATS=a.startHats!==void 0?a.startHats:this.ADD_START_HATS}setFontConstants_(a){a.fontStyle&&a.fontStyle.family&&(this.FIELD_TEXT_FONTFAMILY=a.fontStyle.family);a.fontStyle&&a.fontStyle.weight&&(this.FIELD_TEXT_FONTWEIGHT=a.fontStyle.weight);a.fontStyle&&a.fontStyle.size&&(this.FIELD_TEXT_FONTSIZE=a.fontStyle.size);a=measureFontMetrics$$module$build$src$core$utils$dom("Hg",
this.FIELD_TEXT_FONTSIZE+"pt",this.FIELD_TEXT_FONTWEIGHT,this.FIELD_TEXT_FONTFAMILY);this.FIELD_TEXT_HEIGHT=a.height;this.FIELD_TEXT_BASELINE=a.baseline}setComponentConstants_(a){this.CURSOR_COLOUR=a.getComponentStyle("cursorColour")||this.CURSOR_COLOUR;this.MARKER_COLOUR=a.getComponentStyle("markerColour")||this.MARKER_COLOUR;this.INSERTION_MARKER_COLOUR=a.getComponentStyle("insertionMarkerColour")||this.INSERTION_MARKER_COLOUR;this.INSERTION_MARKER_OPACITY=Number(a.getComponentStyle("insertionMarkerOpacity"))||
this.INSERTION_MARKER_OPACITY}getBlockStyleForColour(a){const b="auto_"+a;this.blockStyles[b]||(this.blockStyles[b]=this.createBlockStyle_(a));return{style:this.blockStyles[b],name:b}}getBlockStyle(a){return this.blockStyles[a||""]||(a&&a.startsWith("auto_")?this.getBlockStyleForColour(a.substring(5)).style:this.createBlockStyle_("#000000"))}createBlockStyle_(a){return this.validatedBlockStyle_({colourPrimary:a})}validatedBlockStyle_(a){const b={};a&&Object.assign(b,a);a=parseBlockColour$$module$build$src$core$utils$parsing(b.colourPrimary||
"#000");b.colourPrimary=a.hex;b.colourSecondary=b.colourSecondary?parseBlockColour$$module$build$src$core$utils$parsing(b.colourSecondary).hex:this.generateSecondaryColour_(b.colourPrimary);b.colourTertiary=b.colourTertiary?parseBlockColour$$module$build$src$core$utils$parsing(b.colourTertiary).hex:this.generateTertiaryColour_(b.colourPrimary);b.hat=b.hat||"";return b}generateSecondaryColour_(a){return blend$$module$build$src$core$utils$colour("#fff",a,.6)||a}generateTertiaryColour_(a){return blend$$module$build$src$core$utils$colour("#fff",
a,.3)||a}dispose(){this.embossFilter&&removeNode$$module$build$src$core$utils$dom(this.embossFilter);this.disabledPattern&&removeNode$$module$build$src$core$utils$dom(this.disabledPattern);this.debugFilter&&removeNode$$module$build$src$core$utils$dom(this.debugFilter);this.cssNode=null}makeJaggedTeeth(){const a=this.JAGGED_TEETH_HEIGHT,b=this.JAGGED_TEETH_WIDTH,c=line$$module$build$src$core$utils$svg_paths([point$$module$build$src$core$utils$svg_paths(b,a/4),point$$module$build$src$core$utils$svg_paths(-b*
2,a/2),point$$module$build$src$core$utils$svg_paths(b,a/4)]);return{height:a,width:b,path:c}}makeStartHat(){const a=this.START_HAT_HEIGHT,b=this.START_HAT_WIDTH,c=curve$$module$build$src$core$utils$svg_paths("c",[point$$module$build$src$core$utils$svg_paths(30,-a),point$$module$build$src$core$utils$svg_paths(70,-a),point$$module$build$src$core$utils$svg_paths(b,0)]);return{height:a*.75,width:b,path:c}}makePuzzleTab(){function a(f){f=f?-1:1;const g=-f;var h=c/2;const k=h+2.5,l=h+.5,m=point$$module$build$src$core$utils$svg_paths(-b,
f*h);h=point$$module$build$src$core$utils$svg_paths(b,f*h);return curve$$module$build$src$core$utils$svg_paths("c",[point$$module$build$src$core$utils$svg_paths(0,f*k),point$$module$build$src$core$utils$svg_paths(-b,g*l),m])+curve$$module$build$src$core$utils$svg_paths("s",[point$$module$build$src$core$utils$svg_paths(b,g*2.5),h])}const b=this.TAB_WIDTH,c=this.TAB_HEIGHT,d=a(!0),e=a(!1);return{type:this.SHAPES.PUZZLE,width:b,height:c,pathDown:e,pathUp:d}}makeNotch(){function a(g){return line$$module$build$src$core$utils$svg_paths([point$$module$build$src$core$utils$svg_paths(g*
d,c),point$$module$build$src$core$utils$svg_paths(g*3,0),point$$module$build$src$core$utils$svg_paths(g*d,-c)])}const b=this.NOTCH_WIDTH,c=this.NOTCH_HEIGHT,d=(b-3)/2,e=a(1),f=a(-1);return{type:this.SHAPES.NOTCH,width:b,height:c,pathLeft:e,pathRight:f}}makeInsideCorners(){const a=this.CORNER_RADIUS,b=arc$$module$build$src$core$utils$svg_paths("a","0 0,0",a,point$$module$build$src$core$utils$svg_paths(-a,a)),c=arc$$module$build$src$core$utils$svg_paths("a","0 0,0",a,point$$module$build$src$core$utils$svg_paths(a,
a));return{width:a,height:a,pathTop:b,pathBottom:c}}makeOutsideCorners(){const a=this.CORNER_RADIUS,b=moveBy$$module$build$src$core$utils$svg_paths(0,a)+arc$$module$build$src$core$utils$svg_paths("a","0 0,1",a,point$$module$build$src$core$utils$svg_paths(a,-a)),c=arc$$module$build$src$core$utils$svg_paths("a","0 0,1",a,point$$module$build$src$core$utils$svg_paths(a,a)),d=arc$$module$build$src$core$utils$svg_paths("a","0 0,1",a,point$$module$build$src$core$utils$svg_paths(-a,-a)),e=arc$$module$build$src$core$utils$svg_paths("a",
"0 0,1",a,point$$module$build$src$core$utils$svg_paths(-a,a));return{topLeft:b,topRight:c,bottomRight:e,bottomLeft:d,rightHeight:a}}shapeFor(a){switch(a.type){case ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE:case ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE:return this.PUZZLE_TAB;case ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT:case ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown connection type");
}}createDom(a,b,c,d){this.injectCSS_(b,c);this.defs=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.DEFS,{},a);a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FILTER,{id:"blocklyEmbossFilter"+this.randomIdentifier},this.defs);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FEGAUSSIANBLUR,{"in":"SourceAlpha",stdDeviation:1,result:"blur"},a);b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FESPECULARLIGHTING,
{"in":"blur",surfaceScale:1,specularConstant:.5,specularExponent:10,"lighting-color":"white",result:"specOut"},a);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FEPOINTLIGHT,{x:-5E3,y:-1E4,z:2E4},b);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FECOMPOSITE,{"in":"specOut",in2:"SourceAlpha",operator:"in",result:"specOut"},a);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FECOMPOSITE,
{"in":"SourceGraphic",in2:"specOut",operator:"arithmetic",k1:0,k2:1,k3:1,k4:0},a);this.embossFilterId=a.id;this.embossFilter=a;a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATTERN,{id:"blocklyDisabledPattern"+this.randomIdentifier,patternUnits:"userSpaceOnUse",width:10,height:10},this.defs);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{width:10,height:10,fill:"#aaa"},a);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,
{d:"M 0 0 L 10 10 M 10 0 L 0 10",stroke:"#cc0"},a);this.disabledPatternId=a.id;this.disabledPattern=a;this.createDebugFilter();d&&(d.style.setProperty("--blocklyEmbossFilter",`url(#${this.embossFilterId})`),d.style.setProperty("--blocklyDisabledPattern",`url(#${this.disabledPatternId})`),d.style.setProperty("--blocklyDebugFilter",`url(#${this.debugFilterId})`))}createDebugFilter(){if(!this.debugFilter){const a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FILTER,
{id:"blocklyDebugFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},this.defs),b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FECOMPONENTTRANSFER,{result:"outBlur"},a);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},b);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FEFLOOD,{"flood-color":"#ff0000",
"flood-opacity":.5,result:"outColor"},a);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FECOMPOSITE,{"in":"outColor",in2:"outBlur",operator:"in",result:"outGlow"},a);this.debugFilterId=a.id;this.debugFilter=a}}injectCSS_(a,b){b=this.getCSS_(b);a="blockly-renderer-style-"+a;this.cssNode=document.getElementById(a);const c=b.join("\n");this.cssNode?this.cssNode.firstChild.textContent=c:(b=document.createElement("style"),b.id=a,a=document.createTextNode(c),b.appendChild(a),
document.head.insertBefore(b,document.head.firstChild),this.cssNode=b)}getCSS_(a){return[`${a} .blocklyText, `,`${a} .blocklyFlyoutLabelText {`,`font: ${this.FIELD_TEXT_FONTWEIGHT} `+`${this.FIELD_TEXT_FONTSIZE}pt ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${a} .blocklyText {`,"fill: #fff;","}",`${a} .blocklyNonEditableField>rect,`,`${a} .blocklyEditableField>rect {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"fill-opacity: .6;","stroke: none;","}",`${a} .blocklyNonEditableField>text,`,`${a} .blocklyEditableField>text {`,
"fill: #000;","}",`${a} .blocklyFlyoutLabelText {`,"fill: #000;","}",`${a} .blocklyText.blocklyBubbleText {`,"fill: #000;","}",`${a} .blocklyEditableField:not(.blocklyEditing):hover>rect {`,"stroke: #fff;","stroke-width: 2;","}",`${a} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"}",`${a} .blocklySelected>.blocklyPath {`,"stroke: #fc3;","stroke-width: 3px;","}",`${a} .blocklyHighlightedConnectionPath {`,"stroke: #fc3;","}",`${a} .blocklyReplaceable .blocklyPath {`,
"fill-opacity: .5;","}",`${a} .blocklyReplaceable .blocklyPathLight,`,`${a} .blocklyReplaceable .blocklyPathDark {`,"display: none;","}",`${a} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"]}},module$build$src$core$renderers$common$constants={};module$build$src$core$renderers$common$constants.ConstantProvider=ConstantProvider$$module$build$src$core$renderers$common$constants;
module$build$src$core$renderers$common$constants.isDynamicShape=isDynamicShape$$module$build$src$core$renderers$common$constants;module$build$src$core$renderers$common$constants.isNotch=isNotch$$module$build$src$core$renderers$common$constants;module$build$src$core$renderers$common$constants.isPuzzleTab=isPuzzleTab$$module$build$src$core$renderers$common$constants;var Drawer$$module$build$src$core$renderers$common$drawer=class{constructor(a,b){this.inlinePath_=this.outlinePath_="";this.block_=a;this.info_=b;this.topLeft_=a.getRelativeToSurfaceXY();this.constants_=b.getRenderer().getConstants()}draw(){this.drawOutline_();this.drawInternals_();this.updateConnectionHighlights();this.block_.pathObject.setPath(this.outlinePath_+"\n"+this.inlinePath_);this.info_.RTL&&this.block_.pathObject.flipRTL();this.recordSizeOnBlock_()}recordSizeOnBlock_(){this.block_.height=
this.info_.height;this.block_.width=this.info_.widthWithChildren;this.block_.childlessWidth=this.info_.width}drawOutline_(){this.drawTop_();for(let a=1;a<this.info_.rows.length-1;a++){const b=this.info_.rows[a];b.hasJaggedEdge?this.drawJaggedEdge_(b):b.hasStatement?this.drawStatementInput_(b):b.hasExternalInput?this.drawValueInput_(b):this.drawRightSideRow_(b)}this.drawBottom_();this.drawLeft_()}drawTop_(){const a=this.info_.topRow,b=a.elements;this.positionPreviousConnection_();this.outlinePath_+=
moveBy$$module$build$src$core$utils$svg_paths(a.xPos,this.info_.startY);for(let c=0,d;d=b[c];c++)Types$$module$build$src$core$renderers$measurables$types.isLeftRoundedCorner(d)?this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.topLeft:Types$$module$build$src$core$renderers$measurables$types.isRightRoundedCorner(d)?this.outlinePath_+=this.constants_.OUTSIDE_CORNERS.topRight:Types$$module$build$src$core$renderers$measurables$types.isPreviousConnection(d)?this.outlinePath_+=d.shape.pathLeft:Types$$module$build$src$core$renderers$measurables$types.isHat(d)?
this.outlinePath_+=this.constants_.START_HAT.path:Types$$module$build$src$core$renderers$measurables$types.isSpacer(d)&&(this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("h",d.width));this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("v",a.height-a.ascenderHeight)}drawJaggedEdge_(a){this.outlinePath_+=this.constants_.JAGGED_TEETH.path+lineOnAxis$$module$build$src$core$utils$svg_paths("v",a.height-this.constants_.JAGGED_TEETH.height)}drawValueInput_(a){const b=
a.getLastInput();this.positionExternalValueConnection_(a);const c=isDynamicShape$$module$build$src$core$renderers$common$constants(b.shape)?b.shape.pathDown(b.height):b.shape.pathDown;this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("H",b.xPos+b.width)+c+lineOnAxis$$module$build$src$core$utils$svg_paths("v",a.height-b.connectionHeight)}drawStatementInput_(a){var b=a.getLastInput();if(b){var c=b.xPos+b.notchOffset+b.shape.width;b=b.shape.pathRight+lineOnAxis$$module$build$src$core$utils$svg_paths("h",
-(b.notchOffset-this.constants_.INSIDE_CORNERS.width))+this.constants_.INSIDE_CORNERS.pathTop;var d=a.height-2*this.constants_.INSIDE_CORNERS.height;this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("H",c)+b+lineOnAxis$$module$build$src$core$utils$svg_paths("v",d)+this.constants_.INSIDE_CORNERS.pathBottom+lineOnAxis$$module$build$src$core$utils$svg_paths("H",a.xPos+a.width);this.positionStatementInputConnection_(a)}}drawRightSideRow_(a){this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("V",
a.yPos+a.height)}drawBottom_(){const a=this.info_.bottomRow,b=a.elements;this.positionNextConnection_();let c=0,d="";for(let e=b.length-1,f;f=b[e];e--)Types$$module$build$src$core$renderers$measurables$types.isNextConnection(f)?d+=f.shape.pathRight:Types$$module$build$src$core$renderers$measurables$types.isLeftSquareCorner(f)?d+=lineOnAxis$$module$build$src$core$utils$svg_paths("H",a.xPos):Types$$module$build$src$core$renderers$measurables$types.isLeftRoundedCorner(f)?d+=this.constants_.OUTSIDE_CORNERS.bottomLeft:
Types$$module$build$src$core$renderers$measurables$types.isRightRoundedCorner(f)?(d+=this.constants_.OUTSIDE_CORNERS.bottomRight,c=this.constants_.OUTSIDE_CORNERS.rightHeight):Types$$module$build$src$core$renderers$measurables$types.isSpacer(f)&&(d+=lineOnAxis$$module$build$src$core$utils$svg_paths("h",f.width*-1));this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("V",a.baseline-c);this.outlinePath_+=d}drawLeft_(){var a=this.info_.outputConnection;this.positionOutputConnection_();
if(a){const b=a.connectionOffsetY+a.height;a=isDynamicShape$$module$build$src$core$renderers$common$constants(a.shape)?a.shape.pathUp(a.height):a.shape.pathUp;this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("V",b)+a}this.outlinePath_+="z"}drawInternals_(){for(let a=0,b;b=this.info_.rows[a];a++)for(let c=0,d;d=b.elements[c];c++)Types$$module$build$src$core$renderers$measurables$types.isInlineInput(d)?this.drawInlineInput_(d):(Types$$module$build$src$core$renderers$measurables$types.isIcon(d)||
Types$$module$build$src$core$renderers$measurables$types.isField(d))&&this.layoutField_(d)}layoutField_(a){const b=a.centerline-a.height/2;let c=a.xPos;var d="";this.info_.RTL&&(c=-(c+a.width),a.flipRtl&&(c+=a.width,d="scale(-1 1)"));Types$$module$build$src$core$renderers$measurables$types.isIcon(a)?(d=a.icon,d.setOffsetInBlock(new Coordinate$$module$build$src$core$utils$coordinate(c,b)),this.info_.isInsertionMarker&&d.hideForInsertionMarker()):(a=a.field.getSvgRoot(),a.setAttribute("transform","translate("+
c+","+b+")"+d),this.info_.isInsertionMarker&&a.setAttribute("display","none"))}drawInlineInput_(a){const b=a.width,c=a.height,d=a.connectionOffsetY,e=a.connectionHeight+d;this.inlinePath_+=moveTo$$module$build$src$core$utils$svg_paths(a.xPos+a.connectionWidth,a.centerline-c/2)+lineOnAxis$$module$build$src$core$utils$svg_paths("v",d)+a.shape.pathDown+lineOnAxis$$module$build$src$core$utils$svg_paths("v",c-e)+lineOnAxis$$module$build$src$core$utils$svg_paths("h",b-a.connectionWidth)+lineOnAxis$$module$build$src$core$utils$svg_paths("v",
-c)+"z";this.positionInlineInputConnection_(a)}positionInlineInputConnection_(a){const b=a.centerline-a.height/2;if(a.connectionModel){let c=a.xPos+a.connectionWidth+a.connectionOffsetX;this.info_.RTL&&(c*=-1);a.connectionModel.setOffsetInBlock(c,b+a.connectionOffsetY)}}positionStatementInputConnection_(a){const b=a.getLastInput();if(b==null?0:b.connectionModel){let c=a.xPos+a.statementEdge+b.notchOffset;this.info_.RTL&&(c*=-1);b.connectionModel.setOffsetInBlock(c,a.yPos)}}positionExternalValueConnection_(a){const b=
a.getLastInput();if(b&&b.connectionModel){let c=a.xPos+a.width;this.info_.RTL&&(c*=-1);b.connectionModel.setOffsetInBlock(c,a.yPos)}}positionPreviousConnection_(){const a=this.info_.topRow;if(a.connection){const b=a.xPos+a.notchOffset;a.connection.connectionModel.setOffsetInBlock(this.info_.RTL?-b:b,0)}}positionNextConnection_(){const a=this.info_.bottomRow;if(a.connection){const b=a.connection,c=b.xPos;b.connectionModel.setOffsetInBlock(this.info_.RTL?-c:c,a.baseline)}}positionOutputConnection_(){if(this.info_.outputConnection){const a=
this.info_.startX+this.info_.outputConnection.connectionOffsetX;this.block_.outputConnection.setOffsetInBlock(this.info_.RTL?-a:a,this.info_.outputConnection.connectionOffsetY)}}updateConnectionHighlights(){for(const a of this.info_.rows)for(const b of a.elements){if(!(b instanceof Connection$$module$build$src$core$renderers$measurables$connection))continue;const c=this.drawConnectionHighlightPath(b);c&&(c.style.display=b.highlighted?"":"none")}}drawConnectionHighlightPath(a){const b=a.connectionModel;
a=b.type===ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE||b.type===ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE?this.getExpressionConnectionHighlightPath(a):this.getStatementConnectionHighlightPath(a);const c=b.getSourceBlock();let d,e;return(e=(d=c.pathObject).addConnectionHighlight)==null?void 0:e.call(d,b,a,b.getOffsetInBlock(),c.RTL)}getExpressionConnectionHighlightPath(a){let b="";isDynamicShape$$module$build$src$core$renderers$common$constants(a.shape)?
b=a.shape.pathDown(a.height):isPuzzleTab$$module$build$src$core$renderers$common$constants(a.shape)&&(b=a.shape.pathDown);a=this.constants_.TAB_OFFSET_FROM_TOP;return moveBy$$module$build$src$core$utils$svg_paths(0,-a)+lineOnAxis$$module$build$src$core$utils$svg_paths("v",a)+b+lineOnAxis$$module$build$src$core$utils$svg_paths("v",a)}getStatementConnectionHighlightPath(a){if(!isNotch$$module$build$src$core$renderers$common$constants(a.shape))throw Error("Statement connections should have notch shapes");
const b=this.constants_.NOTCH_OFFSET_LEFT-this.constants_.CORNER_RADIUS;return moveBy$$module$build$src$core$utils$svg_paths(-b,0)+lineOnAxis$$module$build$src$core$utils$svg_paths("h",b)+a.shape.pathLeft+lineOnAxis$$module$build$src$core$utils$svg_paths("h",b)}},module$build$src$core$renderers$common$drawer={};module$build$src$core$renderers$common$drawer.Drawer=Drawer$$module$build$src$core$renderers$common$drawer;var RenderInfo$$module$build$src$core$renderers$common$info=class{constructor(a,b){this.statementEdge=this.width=this.widthWithChildren=this.height=0;this.rows=[];this.inputRows=[];this.startY=this.startX=0;this.renderer_=a;this.block_=b;this.constants_=this.renderer_.getConstants();this.outputConnection=b.outputConnection?new OutputConnection$$module$build$src$core$renderers$measurables$output_connection(this.constants_,b.outputConnection):null;this.isInline=b.getInputsInline()&&!b.isCollapsed();
this.isCollapsed=b.isCollapsed();this.isInsertionMarker=b.isInsertionMarker();this.RTL=b.RTL;this.topRow=new TopRow$$module$build$src$core$renderers$measurables$top_row(this.constants_);this.bottomRow=new BottomRow$$module$build$src$core$renderers$measurables$bottom_row(this.constants_)}getRenderer(){return this.renderer_}measure(){this.createRows_();this.addElemSpacing_();this.addRowSpacing_();this.computeBounds_();this.alignRowElements_();this.finalize_()}createRows_(){this.populateTopRow_();this.rows.push(this.topRow);
let a=new InputRow$$module$build$src$core$renderers$measurables$input_row(this.constants_);this.inputRows.push(a);var b=this.block_.getIcons();for(let c=0,d;d=b[c];c++){const e=new Icon$$module$build$src$core$renderers$measurables$icon(this.constants_,d);this.isCollapsed&&!d.isShownWhenCollapsed()||a.elements.push(e)}b=void 0;for(let c=0,d;d=this.block_.inputList[c];c++)if(d.isVisible()){this.shouldStartNewRow_(d,b)&&(this.rows.push(a),a=new InputRow$$module$build$src$core$renderers$measurables$input_row(this.constants_),
this.inputRows.push(a));for(let e=0,f;f=d.fieldRow[e];e++)a.elements.push(new Field$$module$build$src$core$renderers$measurables$field(this.constants_,f,d));this.addInput_(d,a);b=d}this.isCollapsed&&(a.hasJaggedEdge=!0,a.elements.push(new JaggedEdge$$module$build$src$core$renderers$measurables$jagged_edge(this.constants_)));(a.elements.length||a.hasDummyInput)&&this.rows.push(a);this.populateBottomRow_();this.rows.push(this.bottomRow)}populateTopRow_(){var a=!!this.block_.previousConnection;const b=
(this.block_.hat?this.block_.hat==="cap":this.constants_.ADD_START_HATS)&&!this.outputConnection&&!a;let c=this.topRow.hasLeftSquareCorner(this.block_)?SquareCorner$$module$build$src$core$renderers$measurables$square_corner:RoundCorner$$module$build$src$core$renderers$measurables$round_corner;this.topRow.elements.push(new c(this.constants_));b?(a=new Hat$$module$build$src$core$renderers$measurables$hat(this.constants_),this.topRow.elements.push(a)):a&&(this.topRow.hasPreviousConnection=!0,this.topRow.connection=
new PreviousConnection$$module$build$src$core$renderers$measurables$previous_connection(this.constants_,this.block_.previousConnection),this.topRow.elements.push(this.topRow.connection));this.block_.inputList.length&&this.block_.inputList[0]instanceof StatementInput$$module$build$src$core$inputs$statement_input&&!this.block_.isCollapsed()?this.topRow.minHeight=this.constants_.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT:this.topRow.minHeight=this.constants_.TOP_ROW_MIN_HEIGHT;c=this.topRow.hasRightSquareCorner(this.block_)?
SquareCorner$$module$build$src$core$renderers$measurables$square_corner:RoundCorner$$module$build$src$core$renderers$measurables$round_corner;this.topRow.elements.push(new c(this.constants_,"right"))}populateBottomRow_(){this.bottomRow.hasNextConnection=!!this.block_.nextConnection;this.bottomRow.minHeight=this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof StatementInput$$module$build$src$core$inputs$statement_input?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:
this.constants_.BOTTOM_ROW_MIN_HEIGHT;this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new SquareCorner$$module$build$src$core$renderers$measurables$square_corner(this.constants_)):this.bottomRow.elements.push(new RoundCorner$$module$build$src$core$renderers$measurables$round_corner(this.constants_));this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new NextConnection$$module$build$src$core$renderers$measurables$next_connection(this.constants_,this.block_.nextConnection),
this.bottomRow.elements.push(this.bottomRow.connection));this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new SquareCorner$$module$build$src$core$renderers$measurables$square_corner(this.constants_,"right")):this.bottomRow.elements.push(new RoundCorner$$module$build$src$core$renderers$measurables$round_corner(this.constants_,"right"))}addInput_(a,b){if(this.isInline&&a instanceof $.ValueInput$$module$build$src$core$inputs$value_input)b.elements.push(new InlineInput$$module$build$src$core$renderers$measurables$inline_input(this.constants_,
a)),b.hasInlineInput=!0;else if(a instanceof StatementInput$$module$build$src$core$inputs$statement_input)b.elements.push(new StatementInput$$module$build$src$core$renderers$measurables$statement_input(this.constants_,a)),b.hasStatement=!0;else if(a instanceof $.ValueInput$$module$build$src$core$inputs$value_input)b.elements.push(new ExternalValueInput$$module$build$src$core$renderers$measurables$external_value_input(this.constants_,a)),b.hasExternalInput=!0;else if(a instanceof DummyInput$$module$build$src$core$inputs$dummy_input||
a instanceof EndRowInput$$module$build$src$core$inputs$end_row_input)b.minHeight=Math.max(b.minHeight,a.getSourceBlock()&&a.getSourceBlock().isShadow()?this.constants_.DUMMY_INPUT_SHADOW_MIN_HEIGHT:this.constants_.DUMMY_INPUT_MIN_HEIGHT),b.hasDummyInput=!0;b.align===null&&(b.align=a.align)}shouldStartNewRow_(a,b){return b?b instanceof EndRowInput$$module$build$src$core$inputs$end_row_input||a instanceof StatementInput$$module$build$src$core$inputs$statement_input||b instanceof StatementInput$$module$build$src$core$inputs$statement_input?
!0:a instanceof $.ValueInput$$module$build$src$core$inputs$value_input||a instanceof DummyInput$$module$build$src$core$inputs$dummy_input||b instanceof $.ValueInput$$module$build$src$core$inputs$value_input?!this.isInline:!1:!1}addElemSpacing_(){for(let a=0,b;b=this.rows[a];a++){const c=b.elements;b.elements=[];b.startsWithElemSpacer()&&b.elements.push(new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,this.getInRowSpacing_(null,c[0])));if(c.length){for(let d=
0;d<c.length-1;d++){b.elements.push(c[d]);const e=this.getInRowSpacing_(c[d],c[d+1]);b.elements.push(new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,e))}b.elements.push(c[c.length-1]);b.endsWithElemSpacer()&&b.elements.push(new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,this.getInRowSpacing_(c[c.length-1],null)))}}}getInRowSpacing_(a,b){if(!a&&b&&Types$$module$build$src$core$renderers$measurables$types.isStatementInput(b))return this.constants_.STATEMENT_INPUT_PADDING_LEFT;
if(a&&Types$$module$build$src$core$renderers$measurables$types.isInput(a)&&!b){if(Types$$module$build$src$core$renderers$measurables$types.isExternalInput(a))return this.constants_.NO_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isInlineInput(a))return this.constants_.LARGE_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isStatementInput(a))return this.constants_.NO_PADDING}return a&&Types$$module$build$src$core$renderers$measurables$types.isLeftSquareCorner(a)&&
b&&(Types$$module$build$src$core$renderers$measurables$types.isPreviousConnection(b)||Types$$module$build$src$core$renderers$measurables$types.isNextConnection(b))?b.notchOffset:a&&Types$$module$build$src$core$renderers$measurables$types.isLeftRoundedCorner(a)&&b&&(Types$$module$build$src$core$renderers$measurables$types.isPreviousConnection(b)||Types$$module$build$src$core$renderers$measurables$types.isNextConnection(b))?b.notchOffset-this.constants_.CORNER_RADIUS:a&&Types$$module$build$src$core$renderers$measurables$types.isField(a)&&
a.width===0?this.constants_.NO_PADDING:this.constants_.MEDIUM_PADDING}computeBounds_(){let a=0,b=0,c=0;for(let e=0,f;f=this.rows[e];e++){f.measure();b=Math.max(b,f.width);if(f.hasStatement){var d=f.getLastInput();let g,h;d=f.width-((h=(g=d)==null?void 0:g.width)!=null?h:0);a=Math.max(a,d)}c=Math.max(c,f.widthWithConnectedBlocks)}this.statementEdge=a;this.width=b;for(let e=0,f;f=this.rows[e];e++)f.hasStatement&&(f.statementEdge=this.statementEdge);this.widthWithChildren=Math.max(b,c);this.outputConnection&&
(this.startX=this.outputConnection.width,this.width+=this.outputConnection.width,this.widthWithChildren+=this.outputConnection.width)}alignRowElements_(){for(let b=0,c;c=this.rows[b];b++)if(c.hasStatement)this.alignStatementRow_(c);else{var a=c.width;a=this.getDesiredRowWidth_(c)-a;a>0&&this.addAlignmentPadding_(c,a);Types$$module$build$src$core$renderers$measurables$types.isTopOrBottomRow(c)&&(c.widthWithConnectedBlocks=c.width)}}getDesiredRowWidth_(a){return this.width-this.startX}addAlignmentPadding_(a,
b){const c=a.getFirstSpacer(),d=a.getLastSpacer();if(a.hasExternalInput||a.hasStatement)a.widthWithConnectedBlocks+=b;if(a.align===$.Align$$module$build$src$core$inputs$align.LEFT&&d)d.width+=b;else if(a.align===$.Align$$module$build$src$core$inputs$align.CENTRE&&c&&d)c.width+=b/2,d.width+=b/2;else if(a.align===$.Align$$module$build$src$core$inputs$align.RIGHT&&c)c.width+=b;else if(d)d.width+=b;else return;a.width+=b}alignStatementRow_(a){const b=a.getLastInput();if(b){var c=a.width-b.width,d=this.statementEdge;
c=d-c;c>0&&this.addAlignmentPadding_(a,c);c=a.width;d=this.getDesiredRowWidth_(a);b.width+=d-c;b.height=Math.max(b.height,a.height);a.width+=d-c;a.widthWithConnectedBlocks=Math.max(a.width,this.statementEdge+a.connectedBlockWidths)}}addRowSpacing_(){const a=this.rows;this.rows=[];for(let b=0;b<a.length;b++)this.rows.push(a[b]),b!==a.length-1&&this.rows.push(this.makeSpacerRow_(a[b],a[b+1]))}makeSpacerRow_(a,b){var c=this.getSpacerRowHeight_(a,b);const d=this.getSpacerRowWidth_(a,b);c=new SpacerRow$$module$build$src$core$renderers$measurables$spacer_row(this.constants_,
c,d);a.hasStatement&&(c.followsStatement=!0);b.hasStatement&&(c.precedesStatement=!0);return c}getSpacerRowWidth_(a,b){return this.width-this.startX}getSpacerRowHeight_(a,b){return this.constants_.MEDIUM_PADDING}getElemCenterline_(a,b){return Types$$module$build$src$core$renderers$measurables$types.isSpacer(b)?a.yPos+b.height/2:Types$$module$build$src$core$renderers$measurables$types.isBottomRow(a)?(a=a.yPos+a.height-a.descenderHeight,Types$$module$build$src$core$renderers$measurables$types.isNextConnection(b)?
a+b.height/2:a-b.height/2):Types$$module$build$src$core$renderers$measurables$types.isTopRow(a)?Types$$module$build$src$core$renderers$measurables$types.isHat(b)?a.capline-b.height/2:a.capline+b.height/2:a.yPos+a.height/2}recordElemPositions_(a){let b=a.xPos;for(let c=0,d;d=a.elements[c];c++)Types$$module$build$src$core$renderers$measurables$types.isSpacer(d)&&(d.height=a.height),d.xPos=b,d.centerline=this.getElemCenterline_(a,d),b+=d.width}finalize_(){let a=0,b=0;for(let c=0,d;d=this.rows[c];c++)d.yPos=
b,d.xPos=this.startX,b+=d.height,a=Math.max(a,d.widthWithConnectedBlocks),this.recordElemPositions_(d);if(this.outputConnection&&this.block_.nextConnection){const c=this.block_.nextConnection.targetBlock();c&&(a=Math.max(a,c.getHeightWidth().width))}this.widthWithChildren=a+this.startX;this.height=b;this.startY=this.topRow.capline;this.bottomRow.baseline=b-this.bottomRow.descenderHeight}getMeasureableForConnection(a){let b;if(((b=this.outputConnection)==null?void 0:b.connectionModel)===a)return this.outputConnection;
for(const c of this.rows)for(const d of c.elements)if(d instanceof Connection$$module$build$src$core$renderers$measurables$connection&&d.connectionModel===a)return d;return null}},module$build$src$core$renderers$common$info={};module$build$src$core$renderers$common$info.RenderInfo=RenderInfo$$module$build$src$core$renderers$common$info;var PathObject$$module$build$src$core$renderers$common$path_object=class{constructor(a,b,c){this.connectionHighlights=new WeakMap;this.highlightOffsets=new WeakMap;this.constants=c;this.style=b;this.svgRoot=a;this.svgPath=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,{"class":"blocklyPath"},this.svgRoot);this.setClass_("blocklyBlock",!0)}setPath(a){this.svgPath.setAttribute("d",a)}flipRTL(){this.svgPath.setAttribute("transform","scale(-1 1)")}applyColour(a){this.svgPath.setAttribute("stroke",
this.style.colourTertiary);this.svgPath.setAttribute("fill",this.style.colourPrimary);this.updateShadow_(a.isShadow());this.updateDisabled_(!a.isEnabled()||a.getInheritedDisabled())}setStyle(a){this.style=a}setClass_(a,b){a&&(b?addClass$$module$build$src$core$utils$dom(this.svgRoot,a):removeClass$$module$build$src$core$utils$dom(this.svgRoot,a))}updateHighlighted(a){a?this.setClass_("blocklyHighlighted",!0):this.setClass_("blocklyHighlighted",!1)}updateShadow_(a){a?(this.setClass_("blocklyShadow",
!0),this.svgPath.setAttribute("stroke","none"),this.svgPath.setAttribute("fill",this.style.colourSecondary)):this.setClass_("blocklyShadow",!1)}updateDisabled_(a){this.setClass_("blocklyDisabled",a);this.setClass_("blocklyDisabledPattern",a)}updateSelected(a){this.setClass_("blocklySelected",a)}updateDraggingDelete(a){this.setClass_("blocklyDraggingDelete",a)}updateInsertionMarker(a){this.setClass_("blocklyInsertionMarker",a)}updateMovable(a){this.setClass_("blocklyDraggable",a)}updateReplacementFade(a){this.setClass_("blocklyReplaceable",
a)}updateShapeForInputHighlight(a,b){}addConnectionHighlight(a,b,c,d){c=`translate(${c.x}, ${c.y})`+(d?" scale(-1 1)":"");if(d=this.connectionHighlights.get(a))return d.setAttribute("d",b),d.setAttribute("transform",c),d;b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,{id:a.id,"class":"blocklyHighlightedConnectionPath",style:"display: none;",d:b,transform:c},this.svgRoot);this.connectionHighlights.set(a,b);return b}removeConnectionHighlight(a){const b=
this.connectionHighlights.get(a);b&&(removeNode$$module$build$src$core$utils$dom(b),this.connectionHighlights.delete(a))}},module$build$src$core$renderers$common$path_object={};module$build$src$core$renderers$common$path_object.PathObject=PathObject$$module$build$src$core$renderers$common$path_object;var Renderer$$module$build$src$core$renderers$common$renderer=class{constructor(a){this.overrides=null;this.name=a}getClassName(){return this.name+"-renderer"}init(a,b){this.constants_=this.makeConstants_();b&&(this.overrides=b,Object.assign(this.constants_,b));this.constants_.setTheme(a);this.constants_.init()}createDom(a,b,c){this.constants_.createDom(a,this.name+"-"+b.name,"."+this.getClassName()+"."+b.getClassName(),c)}refreshDom(a,b,c){const d=this.getConstants();d.dispose();this.constants_=
this.makeConstants_();this.overrides&&Object.assign(this.constants_,this.overrides);this.constants_.randomIdentifier=d.randomIdentifier;this.constants_.setTheme(b);this.constants_.init();this.createDom(a,b,c)}dispose(){this.constants_&&this.constants_.dispose()}makeConstants_(){return new ConstantProvider$$module$build$src$core$renderers$common$constants}makeRenderInfo_(a){return new RenderInfo$$module$build$src$core$renderers$common$info(this,a)}makeDrawer_(a,b){return new Drawer$$module$build$src$core$renderers$common$drawer(a,
b)}makePathObject(a,b){return new PathObject$$module$build$src$core$renderers$common$path_object(a,b,this.constants_)}getConstants(){return this.constants_}shouldHighlightConnection(a){return!0}orphanCanConnectAtEnd(a,b,c){return!!Connection$$module$build$src$core$connection.getConnectionForOrphanedConnection(a,c===ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE?b.outputConnection:b.previousConnection)}render(a){const b=this.makeRenderInfo_(a);b.measure();this.makeDrawer_(a,b).draw()}},
module$build$src$core$renderers$common$renderer={};module$build$src$core$renderers$common$renderer.Renderer=Renderer$$module$build$src$core$renderers$common$renderer;var module$build$src$core$renderers$common$block_rendering={};module$build$src$core$renderers$common$block_rendering.BottomRow=BottomRow$$module$build$src$core$renderers$measurables$bottom_row;module$build$src$core$renderers$common$block_rendering.Connection=Connection$$module$build$src$core$renderers$measurables$connection;module$build$src$core$renderers$common$block_rendering.ConstantProvider=ConstantProvider$$module$build$src$core$renderers$common$constants;
module$build$src$core$renderers$common$block_rendering.Drawer=Drawer$$module$build$src$core$renderers$common$drawer;module$build$src$core$renderers$common$block_rendering.ExternalValueInput=ExternalValueInput$$module$build$src$core$renderers$measurables$external_value_input;module$build$src$core$renderers$common$block_rendering.Field=Field$$module$build$src$core$renderers$measurables$field;module$build$src$core$renderers$common$block_rendering.Hat=Hat$$module$build$src$core$renderers$measurables$hat;
module$build$src$core$renderers$common$block_rendering.Icon=Icon$$module$build$src$core$renderers$measurables$icon;module$build$src$core$renderers$common$block_rendering.InRowSpacer=InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer;module$build$src$core$renderers$common$block_rendering.InlineInput=InlineInput$$module$build$src$core$renderers$measurables$inline_input;module$build$src$core$renderers$common$block_rendering.InputConnection=InputConnection$$module$build$src$core$renderers$measurables$input_connection;
module$build$src$core$renderers$common$block_rendering.InputRow=InputRow$$module$build$src$core$renderers$measurables$input_row;module$build$src$core$renderers$common$block_rendering.JaggedEdge=JaggedEdge$$module$build$src$core$renderers$measurables$jagged_edge;module$build$src$core$renderers$common$block_rendering.Measurable=Measurable$$module$build$src$core$renderers$measurables$base;module$build$src$core$renderers$common$block_rendering.NextConnection=NextConnection$$module$build$src$core$renderers$measurables$next_connection;
module$build$src$core$renderers$common$block_rendering.OutputConnection=OutputConnection$$module$build$src$core$renderers$measurables$output_connection;module$build$src$core$renderers$common$block_rendering.PathObject=PathObject$$module$build$src$core$renderers$common$path_object;module$build$src$core$renderers$common$block_rendering.PreviousConnection=PreviousConnection$$module$build$src$core$renderers$measurables$previous_connection;
module$build$src$core$renderers$common$block_rendering.RenderInfo=RenderInfo$$module$build$src$core$renderers$common$info;module$build$src$core$renderers$common$block_rendering.Renderer=Renderer$$module$build$src$core$renderers$common$renderer;module$build$src$core$renderers$common$block_rendering.RoundCorner=RoundCorner$$module$build$src$core$renderers$measurables$round_corner;module$build$src$core$renderers$common$block_rendering.Row=Row$$module$build$src$core$renderers$measurables$row;
module$build$src$core$renderers$common$block_rendering.SpacerRow=SpacerRow$$module$build$src$core$renderers$measurables$spacer_row;module$build$src$core$renderers$common$block_rendering.SquareCorner=SquareCorner$$module$build$src$core$renderers$measurables$square_corner;module$build$src$core$renderers$common$block_rendering.StatementInput=StatementInput$$module$build$src$core$renderers$measurables$statement_input;module$build$src$core$renderers$common$block_rendering.TopRow=TopRow$$module$build$src$core$renderers$measurables$top_row;
module$build$src$core$renderers$common$block_rendering.Types=Types$$module$build$src$core$renderers$measurables$types;module$build$src$core$renderers$common$block_rendering.init=init$$module$build$src$core$renderers$common$block_rendering;module$build$src$core$renderers$common$block_rendering.register=register$$module$build$src$core$renderers$common$block_rendering;module$build$src$core$renderers$common$block_rendering.unregister=unregister$$module$build$src$core$renderers$common$block_rendering;var ThemeManager$$module$build$src$core$theme_manager=class{constructor(a,b){this.workspace=a;this.theme=b;this.subscribedWorkspaces=[];this.componentDB=new Map}getTheme(){return this.theme}setTheme(a){var b=this.theme;this.theme=a;if(a=this.workspace.getInjectionDiv())b&&(b=b.getClassName())&&removeClass$$module$build$src$core$utils$dom(a,b),(b=this.theme.getClassName())&&addClass$$module$build$src$core$utils$dom(a,b);for(let c=0,d;d=this.subscribedWorkspaces[c];c++)d.refreshTheme();for(const [c,
d]of this.componentDB)for(const e of d){a=e.element;b=e.propertyName;const f=this.theme&&this.theme.getComponentStyle(c);a.style.setProperty(b,f||"")}for(const c of this.subscribedWorkspaces)c.hideChaff()}subscribeWorkspace(a){this.subscribedWorkspaces.push(a)}unsubscribeWorkspace(a){if(!removeElem$$module$build$src$core$utils$array(this.subscribedWorkspaces,a))throw Error("Cannot unsubscribe a workspace that hasn't been subscribed.");}subscribe(a,b,c){this.componentDB.has(b)||this.componentDB.set(b,
[]);this.componentDB.get(b).push({element:a,propertyName:c});b=this.theme&&this.theme.getComponentStyle(b);a.style.setProperty(c,b||"")}unsubscribe(a){if(a)for(const [b,c]of this.componentDB){for(let d=c.length-1;d>=0;d--)c[d].element===a&&c.splice(d,1);c.length||this.componentDB.delete(b)}}dispose(){this.subscribedWorkspaces.length=0;this.componentDB.clear()}},module$build$src$core$theme_manager={};module$build$src$core$theme_manager.ThemeManager=ThemeManager$$module$build$src$core$theme_manager;var CATEGORY_NAME$$module$build$src$core$variables_dynamic="VARIABLE_DYNAMIC",onCreateVariableButtonClick_String$$module$build$src$core$variables_dynamic=stringButtonClickHandler$$module$build$src$core$variables_dynamic,onCreateVariableButtonClick_Number$$module$build$src$core$variables_dynamic=numberButtonClickHandler$$module$build$src$core$variables_dynamic,onCreateVariableButtonClick_Colour$$module$build$src$core$variables_dynamic=colourButtonClickHandler$$module$build$src$core$variables_dynamic,
module$build$src$core$variables_dynamic={CATEGORY_NAME:CATEGORY_NAME$$module$build$src$core$variables_dynamic};module$build$src$core$variables_dynamic.flyoutCategory=flyoutCategory$$module$build$src$core$variables_dynamic;module$build$src$core$variables_dynamic.flyoutCategoryBlocks=flyoutCategoryBlocks$$module$build$src$core$variables_dynamic;module$build$src$core$variables_dynamic.internalFlyoutCategory=internalFlyoutCategory$$module$build$src$core$variables_dynamic;
module$build$src$core$variables_dynamic.onCreateVariableButtonClick_Colour=colourButtonClickHandler$$module$build$src$core$variables_dynamic;module$build$src$core$variables_dynamic.onCreateVariableButtonClick_Number=numberButtonClickHandler$$module$build$src$core$variables_dynamic;module$build$src$core$variables_dynamic.onCreateVariableButtonClick_String=stringButtonClickHandler$$module$build$src$core$variables_dynamic;var ConnectionChecker$$module$build$src$core$connection_checker=class{canConnect(a,b,c,d){return this.canConnectWithReason(a,b,c,d)===Connection$$module$build$src$core$connection.CAN_CONNECT}canConnectWithReason(a,b,c,d){const e=this.doSafetyChecks(a,b);return e!==Connection$$module$build$src$core$connection.CAN_CONNECT?e:this.doTypeChecks(a,b)?c&&!this.doDragChecks(a,b,d||0)?Connection$$module$build$src$core$connection.REASON_DRAG_CHECKS_FAILED:Connection$$module$build$src$core$connection.CAN_CONNECT:
Connection$$module$build$src$core$connection.REASON_CHECKS_FAILED}getErrorMessage(a,b,c){switch(a){case Connection$$module$build$src$core$connection.REASON_SELF_CONNECTION:return"Attempted to connect a block to itself.";case Connection$$module$build$src$core$connection.REASON_DIFFERENT_WORKSPACES:return"Blocks not on same workspace.";case Connection$$module$build$src$core$connection.REASON_WRONG_TYPE:return"Attempt to connect incompatible types.";case Connection$$module$build$src$core$connection.REASON_TARGET_NULL:return"Target connection is null.";
case Connection$$module$build$src$core$connection.REASON_CHECKS_FAILED:return"Connection checks failed. "+(b+" expected "+b.getCheck()+", found "+c.getCheck());case Connection$$module$build$src$core$connection.REASON_SHADOW_PARENT:return"Connecting non-shadow to shadow block.";case Connection$$module$build$src$core$connection.REASON_DRAG_CHECKS_FAILED:return"Drag checks failed.";case Connection$$module$build$src$core$connection.REASON_PREVIOUS_AND_OUTPUT:return"Block would have an output and a previous connection.";
default:return"Unknown connection failure: this should never happen!"}}doSafetyChecks(a,b){if(!a||!b)return Connection$$module$build$src$core$connection.REASON_TARGET_NULL;let c,d,e;a.isSuperior()?(c=a.getSourceBlock(),d=b.getSourceBlock(),e=b):(d=a.getSourceBlock(),c=b.getSourceBlock(),e=a,a=b);return c===d?Connection$$module$build$src$core$connection.REASON_SELF_CONNECTION:e.type!==OPPOSITE_TYPE$$module$build$src$core$internal_constants[a.type]?Connection$$module$build$src$core$connection.REASON_WRONG_TYPE:
c.workspace!==d.workspace?Connection$$module$build$src$core$connection.REASON_DIFFERENT_WORKSPACES:c.isShadow()&&!d.isShadow()?Connection$$module$build$src$core$connection.REASON_SHADOW_PARENT:e.type===ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE&&d.previousConnection&&d.previousConnection.isConnected()||e.type===ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT&&d.outputConnection&&d.outputConnection.isConnected()?Connection$$module$build$src$core$connection.REASON_PREVIOUS_AND_OUTPUT:
Connection$$module$build$src$core$connection.CAN_CONNECT}doTypeChecks(a,b){a=a.getCheck();b=b.getCheck();if(!a||!b)return!0;for(let c=0;c<a.length;c++)if(b.includes(a[c]))return!0;return!1}doDragChecks(a,b,c){if(a.distanceFrom(b)>c||b.getSourceBlock().isInsertionMarker())return!1;switch(b.type){case ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT:return this.canConnectToPrevious_(a,b);case ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE:if(b.isConnected()&&
!b.targetBlock().isInsertionMarker()||a.isConnected())return!1;break;case ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE:if(b.isConnected()&&!b.targetBlock().isMovable()&&!b.targetBlock().isShadow())return!1;break;case ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT:if(b.isConnected()&&!a.getSourceBlock().nextConnection&&!b.targetBlock().isShadow()&&b.targetBlock().nextConnection||b.targetBlock()&&!b.targetBlock().isMovable()&&!b.targetBlock().isShadow())return!1;
break;default:return!1}return draggingConnections$$module$build$src$core$common.includes(b)?!1:!0}canConnectToPrevious_(a,b){if(a.targetConnection||draggingConnections$$module$build$src$core$common.includes(b))return!1;if(!b.targetConnection)return!0;a=b.targetBlock();return a.isInsertionMarker()?!a.getPreviousBlock():!1}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.CONNECTION_CHECKER,DEFAULT$$module$build$src$core$registry,ConnectionChecker$$module$build$src$core$connection_checker);
var module$build$src$core$connection_checker={};module$build$src$core$connection_checker.ConnectionChecker=ConnectionChecker$$module$build$src$core$connection_checker;var Workspace$$module$build$src$core$workspace=class{get isFlyout(){return this.internalIsFlyout}get isMutator(){return this.internalIsMutator}constructor(a){this.isClearing=this.internalIsMutator=this.internalIsFlyout=this.rendered=!1;this.MAX_UNDO=1024;this.connectionDBList=[];this.topBlocks=[];this.topComments=[];this.commentDB=new Map;this.listeners=[];this.undoStack_=[];this.redoStack_=[];this.blockDB=new Map;this.typedBlocksDB=new Map;this.procedureMap=new ObservableProcedureMap$$module$build$src$core$observable_procedure_map;
this.readOnly=!1;this.potentialVariableMap=null;this.id=genUid$$module$build$src$core$utils$idgenerator();registerWorkspace$$module$build$src$core$common(this);this.options=a||new Options$$module$build$src$core$options({});this.RTL=!!this.options.RTL;this.horizontalLayout=!!this.options.horizontalLayout;this.toolboxPosition=this.options.toolboxPosition;this.connectionChecker=new (getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.CONNECTION_CHECKER,this.options,
!0))(this);this.variableMap=new (this.getVariableMapClass())(this);this.setIsReadOnly(this.options.readOnly)}dispose(){this.listeners.length=0;this.clear();unregisterWorkpace$$module$build$src$core$common(this)}sortObjects(a,b){const c=d=>({getBoundingRectangle:()=>{const e=d.getRelativeToSurfaceXY();return new Rect$$module$build$src$core$utils$rect(e.y,e.y,e.x,e.x)},moveBy:()=>{}});return this.sortByOrigin(c(a),c(b))}sortByOrigin(a,b){const c=Math.sin(toRadians$$module$build$src$core$utils$math(Workspace$$module$build$src$core$workspace.SCAN_ANGLE))*
(this.RTL?-1:1);a=a.getBoundingRectangle().getOrigin();b=b.getBoundingRectangle().getOrigin();return a.y+c*a.x-(b.y+c*b.x)}addTopBlock(a){this.topBlocks.push(a)}removeTopBlock(a){if(!removeElem$$module$build$src$core$utils$array(this.topBlocks,a))throw Error("Block not present in workspace's list of top-most blocks.");}getTopBlocks(a=!1){const b=[].concat(this.topBlocks);a&&b.length>1&&b.sort(this.sortObjects.bind(this));return b}addTypedBlock(a){this.typedBlocksDB.has(a.type)||this.typedBlocksDB.set(a.type,
[]);this.typedBlocksDB.get(a.type).push(a)}removeTypedBlock(a){removeElem$$module$build$src$core$utils$array(this.typedBlocksDB.get(a.type),a);this.typedBlocksDB.get(a.type).length||this.typedBlocksDB.delete(a.type)}getBlocksByType(a,b=!1){if(!this.typedBlocksDB.has(a))return[];a=this.typedBlocksDB.get(a).slice(0);b&&a&&a.length>1&&a.sort(this.sortObjects.bind(this));return a.filter(c=>!c.isInsertionMarker())}addTopComment(a){this.topComments.push(a);this.commentDB.has(a.id)&&console.warn('Overriding an existing comment on this workspace, with id "'+
a.id+'"');this.commentDB.set(a.id,a)}removeTopComment(a){if(!removeElem$$module$build$src$core$utils$array(this.topComments,a))throw Error("Comment not present in workspace's list of top-most comments.");this.commentDB.delete(a.id)}getTopComments(a=!1){const b=[].concat(this.topComments);a&&b.length>1&&b.sort(this.sortObjects.bind(this));return b}getAllBlocks(a=!1){if(a){var b=this.getTopBlocks(!0);a=[];for(let c=0;c<b.length;c++)a.push(...b[c].getDescendants(!0))}else for(a=this.getTopBlocks(!1),
b=0;b<a.length;b++)a.push(...a[b].getChildren(!1));return a.filter(c=>!c.isInsertionMarker())}clear(){this.isClearing=!0;try{const a=$.getGroup$$module$build$src$core$events$utils();for(a||$.setGroup$$module$build$src$core$events$utils(!0);this.topBlocks.length;)this.topBlocks[0].dispose(!1);for(;this.topComments.length;)this.topComments[this.topComments.length-1].dispose();$.setGroup$$module$build$src$core$events$utils(a);this.isFlyout||this.variableMap.clear();this.potentialVariableMap&&this.potentialVariableMap.clear()}finally{this.isClearing=
!1}}renameVariableById(a,b){warn$$module$build$src$core$utils$deprecation("Blockly.Workspace.renameVariableById","v12","v13","Blockly.Workspace.getVariableMap().renameVariable");(a=this.variableMap.getVariableById(a))&&this.variableMap.renameVariable(a,b)}createVariable(a,b,c){warn$$module$build$src$core$utils$deprecation("Blockly.Workspace.createVariable","v12","v13","Blockly.Workspace.getVariableMap().createVariable");return this.variableMap.createVariable(a,b!=null?b:void 0,c!=null?c:void 0)}getVariableUsesById(a){warn$$module$build$src$core$utils$deprecation("Blockly.Workspace.getVariableUsesById",
"v12","v13","Blockly.Variables.getVariableUsesById");return getVariableUsesById$$module$build$src$core$variables(this,a)}deleteVariableById(a){warn$$module$build$src$core$utils$deprecation("Blockly.Workspace.deleteVariableById","v12","v13","Blockly.Workspace.getVariableMap().deleteVariable");const b=this.variableMap.getVariableById(a);b?$.deleteVariable$$module$build$src$core$variables(this,b):console.warn(`Can't delete non-existent variable: ${a}`)}getVariable(a,b){warn$$module$build$src$core$utils$deprecation("Blockly.Workspace.getVariable",
"v12","v13","Blockly.Workspace.getVariableMap().getVariable");return this.variableMap.getVariable(a,b)}getVariableById(a){warn$$module$build$src$core$utils$deprecation("Blockly.Workspace.getVariableById","v12","v13","Blockly.Workspace.getVariableMap().getVariableById");return this.variableMap.getVariableById(a)}getVariablesOfType(a){warn$$module$build$src$core$utils$deprecation("Blockly.Workspace.getVariablesOfType","v12","v13","Blockly.Workspace.getVariableMap().getVariablesOfType");return this.variableMap.getVariablesOfType(a!=
null?a:"")}getAllVariables(){warn$$module$build$src$core$utils$deprecation("Blockly.Workspace.getAllVariables","v12","v13","Blockly.Workspace.getVariableMap().getAllVariables");return this.variableMap.getAllVariables()}getAllVariableNames(){warn$$module$build$src$core$utils$deprecation("Blockly.Workspace.getAllVariableNames","v12","v13","Blockly.Workspace.getVariableMap().getAllVariables");return this.variableMap.getAllVariables().map(a=>a.getName())}getWidth(){return 0}newBlock(a,b){throw Error("The implementation of newBlock should be monkey-patched in by blockly.ts");
}newComment(a){throw Error("The implementation of newComment should be monkey-patched in by blockly.ts");}remainingCapacity(){return isNaN(this.options.maxBlocks)?Infinity:this.options.maxBlocks-this.getAllBlocks(!1).length}remainingCapacityOfType(a){return this.options.maxInstances?(this.options.maxInstances[a]!==void 0?this.options.maxInstances[a]:Infinity)-this.getBlocksByType(a,!1).length:Infinity}isCapacityAvailable(a){if(!this.hasBlockLimits())return!0;let b=0;for(const c in a){if(a[c]>this.remainingCapacityOfType(c))return!1;
b+=a[c]}return b>this.remainingCapacity()?!1:!0}hasBlockLimits(){return this.options.maxBlocks!==Infinity||!!this.options.maxInstances}getUndoStack(){return this.undoStack_}getRedoStack(){return this.redoStack_}undo(a){var b=a?this.redoStack_:this.undoStack_,c=a?this.undoStack_:this.redoStack_;const d=b.pop();if(d){for(var e=[d];b.length&&d.group&&d.group===b[b.length-1].group;){const f=b.pop();f&&e.push(f)}for(b=0;b<e.length;b++)c.push(e[b]);$.setRecordUndo$$module$build$src$core$events$utils(!1);
try{for(c=0;c<e.length;c++)e[c].run(a)}finally{$.setRecordUndo$$module$build$src$core$events$utils(!0)}}}clearUndo(){this.undoStack_.length=0;this.redoStack_.length=0;clearPendingUndo$$module$build$src$core$events$utils()}addChangeListener(a){this.listeners.push(a);return a}removeChangeListener(a){removeElem$$module$build$src$core$utils$array(this.listeners,a)}fireChangeListener(a){if(a.recordUndo)for(this.undoStack_.push(a),this.redoStack_.length=0;this.undoStack_.length>this.MAX_UNDO&&this.MAX_UNDO>=
0;)this.undoStack_.shift();for(let b=0;b<this.listeners.length;b++)(0,this.listeners[b])(a)}getBlockById(a){return this.blockDB.get(a)||null}setBlockById(a,b){this.blockDB.set(a,b)}removeBlockById(a){this.blockDB.delete(a)}getCommentById(a){let b;return(b=this.commentDB.get(a))!=null?b:null}allInputsFilled(a){const b=this.getTopBlocks(!1);for(let c=0;c<b.length;c++)if(!b[c].allInputsFilled(a))return!1;return!0}getPotentialVariableMap(){return this.potentialVariableMap}createPotentialVariableMap(){this.potentialVariableMap=
new (this.getVariableMapClass())(this,!0)}getVariableMap(){return this.variableMap}setVariableMap(a){this.variableMap=a}getProcedureMap(){return this.procedureMap}getRootWorkspace(){let a=null;const b=this.options.parentWorkspace;this.isFlyout?b&&b.options&&(a=b.options.parentWorkspace):b&&(a=b);return a}static getById(a){return getWorkspaceById$$module$build$src$core$common(a)}static getAll(){return getAllWorkspaces$$module$build$src$core$common()}getVariableMapClass(){const a=getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.VARIABLE_MAP,
this.options,!0);if(!a)throw Error("No variable map is registered.");return a}isReadOnly(){return this.readOnly}setIsReadOnly(a){this.readOnly=a;this.options.readOnly=a}};Workspace$$module$build$src$core$workspace.SCAN_ANGLE=3;var module$build$src$core$workspace={};module$build$src$core$workspace.Workspace=Workspace$$module$build$src$core$workspace;var SOUND_LIMIT$$module$build$src$core$workspace_audio=100,WorkspaceAudio$$module$build$src$core$workspace_audio=class{constructor(a){this.parentWorkspace=a;this.sounds=new Map;this.lastSound=null;this.muted=!1}dispose(){this.sounds.clear()}load(a,b){if(a.length){try{var c=new globalThis.Audio}catch(e){return}for(let e=0;e<a.length;e++){const f=a[e],g=f.match(/\.(\w+)$/);if(g&&c.canPlayType("audio/"+g[1])){var d=new globalThis.Audio(f);break}}d&&this.sounds.set(b,d)}}preload(){for(const a of this.sounds.values()){a.volume=
.01;const b=a.play();b!==void 0?b.then(a.pause).catch(function(){}):a.pause();if(IPAD$$module$build$src$core$utils$useragent||IPHONE$$module$build$src$core$utils$useragent)break}}play(a,b){if(!this.muted){var c=this.sounds.get(a);c?(a=new Date,this.lastSound!==null&&a.getTime()-this.lastSound.getTime()<SOUND_LIMIT$$module$build$src$core$workspace_audio||(this.lastSound=a,c=IPAD$$module$build$src$core$utils$useragent||ANDROID$$module$build$src$core$utils$useragent?c:c.cloneNode(),c.volume=b===void 0?
1:b,c.play())):this.parentWorkspace&&this.parentWorkspace.getAudioManager().play(a,b)}}setMuted(a){this.muted=a}getMuted(){return this.muted}},module$build$src$core$workspace_audio={};module$build$src$core$workspace_audio.WorkspaceAudio=WorkspaceAudio$$module$build$src$core$workspace_audio;var ZOOM_TO_FIT_MARGIN$$module$build$src$core$workspace_svg=20,WorkspaceSvg$$module$build$src$core$workspace_svg=class extends Workspace$$module$build$src$core$workspace{constructor(a){super(a);this.resizeHandlerWrapper=null;this.resizesEnabled=this.visible=this.rendered=!0;this.startScrollY=this.startScrollX=this.scrollY=this.scrollX=0;this.oldScale=this.scale=1;this.oldLeft=this.oldTop=0;this.inverseScreenCTM=this.targetWorkspace=this.dummyWheelListener=this.configureContextMenu=this.lastRecordedPageScroll=
this.injectionDiv=this.currentGesture_=this.toolbox=this.flyout=this.scrollbar=this.trashcan=null;this.inverseScreenCTMDirty=!0;this.highlightedBlocks=[];this.toolboxCategoryCallbacks=new Map;this.flyoutButtonCallbacks=new Map;this.cachedParentSvg=null;this.keyboardMoveInProgress=this.keyboardAccessibilityMode=!1;this.topBoundedElements=[];this.dragTargetAreas=[];this.zoomControls_=this.layerManager=null;this.navigator=new Navigator$$module$build$src$core$navigator;this.metricsManager=new (getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.METRICS_MANAGER,
a,!0))(this);this.getMetrics=a.getMetrics||this.metricsManager.getMetrics.bind(this.metricsManager);this.setMetrics=a.setMetrics||WorkspaceSvg$$module$build$src$core$workspace_svg.setTopLevelWorkspaceMetrics;this.componentManager=new ComponentManager$$module$build$src$core$component_manager;this.connectionDBList=ConnectionDB$$module$build$src$core$connection_db.init(this.connectionChecker);this.audioManager=new WorkspaceAudio$$module$build$src$core$workspace_audio(a.parentWorkspace);this.grid=this.options.gridPattern?
new Grid$$module$build$src$core$grid(this.options.gridPattern,a.gridOptions):null;this.markerManager=new MarkerManager$$module$build$src$core$marker_manager(this);module$build$src$core$variables&&internalFlyoutCategory$$module$build$src$core$variables&&this.registerToolboxCategoryCallback(CATEGORY_NAME$$module$build$src$core$variables,internalFlyoutCategory$$module$build$src$core$variables);module$build$src$core$variables_dynamic&&internalFlyoutCategory$$module$build$src$core$variables_dynamic&&this.registerToolboxCategoryCallback(CATEGORY_NAME$$module$build$src$core$variables_dynamic,
internalFlyoutCategory$$module$build$src$core$variables_dynamic);module$build$src$core$procedures&&internalFlyoutCategory$$module$build$src$core$procedures&&(this.registerToolboxCategoryCallback(CATEGORY_NAME$$module$build$src$core$procedures,internalFlyoutCategory$$module$build$src$core$procedures),this.addChangeListener(mutatorOpenListener$$module$build$src$core$procedures));this.addChangeListener(this.variableChangeCallback.bind(this));this.themeManager_=this.options.parentWorkspace?this.options.parentWorkspace.getThemeManager():
new ThemeManager$$module$build$src$core$theme_manager(this,this.options.theme||Classic$$module$build$src$core$theme$classic);this.themeManager_.subscribeWorkspace(this);let b;this.renderer=init$$module$build$src$core$renderers$common$block_rendering(this.options.renderer||"geras",this.getTheme(),(b=this.options.rendererOverrides)!=null?b:void 0);this.cachedParentSvgSize=new Size$$module$build$src$core$utils$size(0,0)}getMarkerManager(){return this.markerManager}getMetricsManager(){return this.metricsManager}setMetricsManager(a){this.metricsManager=
a;this.getMetrics=this.metricsManager.getMetrics.bind(this.metricsManager)}getComponentManager(){return this.componentManager}getMarker(a){return this.markerManager.getMarker(a)}getCursor(){return this.markerManager.getCursor()}getRenderer(){return this.renderer}getThemeManager(){return this.themeManager_}getTheme(){return this.themeManager_.getTheme()}setTheme(a){a||(a=Classic$$module$build$src$core$theme$classic);this.themeManager_.setTheme(a)}refreshTheme(){if(this.svgGroup_){var a=this.options.parentWorkspace===
null;this.renderer.refreshDom(this.svgGroup_,this.getTheme(),a?this.getInjectionDiv():void 0)}this.updateBlockStyles(this.getAllBlocks(!1).filter(b=>!!b.getStyleName()));this.refreshToolboxSelection();this.toolbox&&this.toolbox.refreshTheme();this.isVisible()&&this.setVisible(!0);a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.THEME_CHANGE))(this.getTheme().name,this.id);fire$$module$build$src$core$events$utils(a)}updateBlockStyles(a){for(let b=0,c;c=a[b];b++){const d=
c.getStyleName();d&&c.setStyle(d)}}getInverseScreenCTM(){if(this.inverseScreenCTMDirty){const a=this.getParentSvg().getScreenCTM();a&&(this.inverseScreenCTM=a.inverse(),this.inverseScreenCTMDirty=!1)}return this.inverseScreenCTM}updateInverseScreenCTM(){this.inverseScreenCTMDirty=!0}isVisible(){return this.visible}getSvgXY(a){let b=0,c=0,d=1;if(this.getCanvas().contains(a)||this.getBubbleCanvas().contains(a))d=this.scale;do{const e=getRelativeXY$$module$build$src$core$utils$svg_math(a);if(a===this.getCanvas()||
a===this.getBubbleCanvas())d=1;b+=e.x*d;c+=e.y*d;a=a.parentNode}while(a&&a!==this.getParentSvg()&&a!==this.getInjectionDiv());return new Coordinate$$module$build$src$core$utils$coordinate(b,c)}getCachedParentSvgSize(){const a=this.cachedParentSvgSize;return new Size$$module$build$src$core$utils$size(a.width,a.height)}getOriginOffsetInPixels(){return getInjectionDivXY$$module$build$src$core$utils$svg_math(this.getCanvas())}getInjectionDiv(){if(!this.injectionDiv){let a=this.svgGroup_;for(;a;){if((" "+
(a.getAttribute("class")||"")+" ").includes(" injectionDiv ")){this.injectionDiv=a;break}a=a.parentNode}}return this.injectionDiv}getSvgGroup(){return this.svgGroup_}getBlockCanvas(){return this.getCanvas()}setResizeHandlerWrapper(a){this.resizeHandlerWrapper=a}createDom(a,b){this.injectionDiv||(this.injectionDiv=b!=null?b:null);this.svgGroup_=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{"class":"blocklyWorkspace",id:this.id});b&&setState$$module$build$src$core$utils$aria(this.svgGroup_,
State$$module$build$src$core$utils$aria.LABEL,$.Msg$$module$build$src$core$msg.WORKSPACE_ARIA_LABEL);a&&(this.svgBackground_=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{height:"100%",width:"100%","class":a},this.svgGroup_),a==="blocklyMainBackground"&&this.grid?this.svgBackground_.style.fill="var(--blocklyGridPattern)":this.themeManager_.subscribe(this.svgBackground_,"workspaceBackgroundColour","fill"));this.layerManager=new LayerManager$$module$build$src$core$layer_manager(this);
this.svgBlockCanvas_=this.layerManager.getBlockLayer();this.svgBubbleCanvas_=this.layerManager.getBubbleLayer();this.isFlyout||(conditionalBind$$module$build$src$core$browser_events(this.svgGroup_,"pointerdown",this,this.onMouseDown,!1),this.dummyWheelListener=()=>{},document.body.addEventListener("wheel",this.dummyWheelListener),conditionalBind$$module$build$src$core$browser_events(this.svgGroup_,"wheel",this,this.onMouseWheel));this.options.hasCategories&&(this.toolbox=new (getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.TOOLBOX,
this.options,!0))(this));this.grid&&this.grid.update(this.scale);this.recordDragTargets();(a=getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.CURSOR,this.options))&&this.markerManager.setCursor(new a(this));a=this.options.parentWorkspace===null;this.renderer.createDom(this.svgGroup_,this.getTheme(),a?this.getInjectionDiv():void 0);$.getFocusManager$$module$build$src$core$focus_manager().registerTree(this,!!this.injectionDiv||this.isFlyout);return this.svgGroup_}dispose(){this.rendered=
!1;this.currentGesture_&&this.currentGesture_.cancel();this.svgGroup_&&removeNode$$module$build$src$core$utils$dom(this.svgGroup_);this.toolbox&&(this.toolbox.dispose(),this.toolbox=null);this.flyout&&(this.flyout.dispose(),this.flyout=null);this.trashcan&&(this.trashcan.dispose(),this.trashcan=null);this.scrollbar&&(this.scrollbar.dispose(),this.scrollbar=null);this.zoomControls_&&this.zoomControls_.dispose();this.audioManager&&this.audioManager.dispose();this.grid&&(this.grid=null);this.renderer.dispose();
this.markerManager.dispose();super.dispose();this.themeManager_&&(this.themeManager_.unsubscribeWorkspace(this),this.themeManager_.unsubscribe(this.svgBackground_),this.options.parentWorkspace||this.themeManager_.dispose());this.connectionDBList.length=0;this.toolboxCategoryCallbacks.clear();this.flyoutButtonCallbacks.clear();if(!this.options.parentWorkspace){const a=this.getParentSvg();a&&a.parentNode&&removeNode$$module$build$src$core$utils$dom(a.parentNode)}this.resizeHandlerWrapper&&(unbind$$module$build$src$core$browser_events(this.resizeHandlerWrapper),
this.resizeHandlerWrapper=null);this.dummyWheelListener&&(document.body.removeEventListener("wheel",this.dummyWheelListener),this.dummyWheelListener=null);$.getFocusManager$$module$build$src$core$focus_manager().isRegistered(this)&&$.getFocusManager$$module$build$src$core$focus_manager().unregisterTree(this)}addTrashcan(){this.trashcan=WorkspaceSvg$$module$build$src$core$workspace_svg.newTrashcan(this);const a=this.trashcan.createDom();this.svgGroup_.insertBefore(a,this.getCanvas())}static newTrashcan(a){throw Error("The implementation of newTrashcan should be monkey-patched in by blockly.ts");
}addZoomControls(){this.zoomControls_=new ZoomControls$$module$build$src$core$zoom_controls(this);const a=this.zoomControls_.createDom();this.svgGroup_.appendChild(a)}copyOptionsForFlyout(){return new Options$$module$build$src$core$options({parentWorkspace:this,rtl:this.RTL,oneBasedIndex:this.options.oneBasedIndex,horizontalLayout:this.horizontalLayout,renderer:this.options.renderer,rendererOverrides:this.options.rendererOverrides,plugins:this.options.plugins,modalInputs:this.options.modalInputs,
move:{scrollbars:!0}})}addFlyout(a){const b=this.copyOptionsForFlyout();b.toolboxPosition=this.options.toolboxPosition;this.flyout=this.horizontalLayout?new (getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUTS_HORIZONTAL_TOOLBOX,this.options,!0))(b):new (getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUTS_VERTICAL_TOOLBOX,this.options,!0))(b);this.flyout.autoClose=!1;this.flyout.getWorkspace().setVisible(!0);
return this.flyout.createDom(a)}getFlyout(a){return this.flyout||a?this.flyout:this.toolbox?this.toolbox.getFlyout():null}getToolbox(){return this.toolbox}updateScreenCalculations(){this.updateInverseScreenCTM();this.recordDragTargets()}resizeContents(){this.resizesEnabled&&this.rendered&&(this.scrollbar&&this.scrollbar.resize(),this.updateInverseScreenCTM())}resize(){this.toolbox?this.toolbox.position():this.flyout&&this.flyout.position();const a=this.componentManager.getComponents(ComponentManager$$module$build$src$core$component_manager.Capability.POSITIONABLE,
!0),b=this.getMetricsManager().getUiMetrics(),c=[];for(let d=0,e;e=a[d];d++){e.position(b,c);const f=e.getBoundingRectangle();f&&c.push(f)}this.scrollbar&&this.scrollbar.resize();this.updateScreenCalculations()}updateScreenCalculationsIfScrolled(){const a=getDocumentScroll$$module$build$src$core$utils$svg_math();Coordinate$$module$build$src$core$utils$coordinate.equals(this.lastRecordedPageScroll,a)||(this.lastRecordedPageScroll=a,this.updateScreenCalculations())}getLayerManager(){return this.layerManager}getCanvas(){return this.layerManager.getBlockLayer()}setCachedParentSvgSize(a,
b){const c=this.getParentSvg();a!=null&&(this.cachedParentSvgSize.width=a,c.setAttribute("data-cached-width",`${a}`));b!=null&&(this.cachedParentSvgSize.height=b,c.setAttribute("data-cached-height",`${b}`))}getBubbleCanvas(){return this.layerManager.getBubbleLayer()}getParentSvg(){if(!this.cachedParentSvg){let a=this.svgGroup_;for(;a;){if(a.tagName==="svg"){this.cachedParentSvg=a;break}a=a.parentNode}}return this.cachedParentSvg}maybeFireViewportChangeEvent(){if(isEnabled$$module$build$src$core$events$utils()){var a=
this.scale,b=-this.scrollY,c=-this.scrollX;if(!(a===this.oldScale&&Math.abs(b-this.oldTop)<1&&Math.abs(c-this.oldLeft)<1)){var d=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.VIEWPORT_CHANGE))(b,c,a,this.id,this.oldScale);this.oldScale=a;this.oldTop=b;this.oldLeft=c;fire$$module$build$src$core$events$utils(d)}}}translate(a,b){let c;(c=this.layerManager)==null||c.translateLayers(new Coordinate$$module$build$src$core$utils$coordinate(a,b),this.scale);let d;
(d=this.grid)==null||d.moveTo(a,b);this.maybeFireViewportChangeEvent()}getWidth(){const a=this.getMetrics();return a?a.viewWidth/this.scale:0}setVisible(a){this.visible=a;this.svgGroup_&&(this.scrollbar&&this.scrollbar.setContainerVisible(a),this.getFlyout()&&this.getFlyout().setContainerVisible(a),this.getParentSvg().style.display=a?"block":"none",this.toolbox&&this.toolbox.setVisible(a),a||this.hideChaff(!0))}render(){const a=this.getAllBlocks(!1);for(let b=a.length-1;b>=0;b--)a[b].queueRender();
this.getTopBlocks().flatMap(b=>b.getDescendants(!1)).filter(b=>b.isInsertionMarker()).forEach(b=>b.queueRender())}highlightBlock(a,b){if(b===void 0){for(let c=0,d;d=this.highlightedBlocks[c];c++)d.setHighlighted(!1);this.highlightedBlocks.length=0}if(a=a?this.getBlockById(a):null)(b=b===void 0||b)?this.highlightedBlocks.includes(a)||this.highlightedBlocks.push(a):removeElem$$module$build$src$core$utils$array(this.highlightedBlocks,a),a.setHighlighted(b)}variableChangeCallback(a){switch(a.type){case EventType$$module$build$src$core$events$type.VAR_CREATE:case EventType$$module$build$src$core$events$type.VAR_DELETE:case EventType$$module$build$src$core$events$type.VAR_RENAME:case EventType$$module$build$src$core$events$type.VAR_TYPE_CHANGE:this.refreshToolboxSelection()}}refreshToolboxSelection(){const a=
this.isFlyout?this.targetWorkspace:this;a&&!a.currentGesture_&&a.toolbox&&a.toolbox.getFlyout()&&a.toolbox.refreshSelection()}recordDragTargets(){const a=this.componentManager.getComponents(ComponentManager$$module$build$src$core$component_manager.Capability.DRAG_TARGET,!0);this.dragTargetAreas=[];for(let b=0,c;c=a[b];b++){const d=c.getClientRect();d&&this.dragTargetAreas.push({component:c,clientRect:d})}}newBlock(a,b){throw Error("The implementation of newBlock should be monkey-patched in by blockly.ts");
}newComment(a){throw Error("The implementation of newComment should be monkey-patched in by blockly.ts");}getDragTarget(a){for(let b=0,c;c=this.dragTargetAreas[b];b++)if(c.clientRect.contains(a.clientX,a.clientY))return c.component;return null}onMouseDown(a){const b=this.getGesture(a);b&&b.handleWsStart(a,this)}startDrag(a,b){start$$module$build$src$core$utils$drag(this,a,b)}moveDrag(a){return move$$module$build$src$core$utils$drag(this,a)}setKeyboardMoveInProgress(a){this.keyboardMoveInProgress=
a}isDragging(){return this.keyboardMoveInProgress||this.currentGesture_!==null&&this.currentGesture_.isDragging()}isDraggable(){return this.options.moveOptions&&this.options.moveOptions.drag}isMovable(){return this.options.moveOptions&&!!this.options.moveOptions.scrollbars||this.options.moveOptions&&this.options.moveOptions.wheel||this.options.moveOptions&&this.options.moveOptions.drag||this.options.zoomOptions&&this.options.zoomOptions.wheel||this.options.zoomOptions&&this.options.zoomOptions.pinch}isMovableHorizontally(){const a=
!!this.scrollbar;return this.isMovable()&&(!a||a&&this.scrollbar.canScrollHorizontally())}isMovableVertically(){const a=!!this.scrollbar;return this.isMovable()&&(!a||a&&this.scrollbar.canScrollVertically())}onMouseWheel(a){if(Gesture$$module$build$src$core$gesture.inProgress())a.preventDefault(),a.stopPropagation();else{var b=this.options.zoomOptions&&this.options.zoomOptions.wheel,c=this.options.moveOptions&&this.options.moveOptions.wheel;if(b||c){var d=getScrollDeltaPixels$$module$build$src$core$browser_events(a);
if(MAC$$module$build$src$core$utils$useragent)var e=a.metaKey;b&&(a.ctrlKey||e||!c)?(d=-d.y/50,b=mouseToSvg$$module$build$src$core$browser_events(a,this.getParentSvg(),this.getInverseScreenCTM()),this.zoom(b.x,b.y,d)):(b=this.scrollX-d.x,c=this.scrollY-d.y,a.shiftKey&&!d.x&&(b=this.scrollX-d.y,c=this.scrollY),this.scroll(b,c));a.preventDefault()}}}getBlocksBoundingBox(){const a=this.getTopBoundedElements();if(!a.length)return new Rect$$module$build$src$core$utils$rect(0,0,0,0);const b=a[0].getBoundingRectangle();
for(let d=1;d<a.length;d++){var c=a[d];c.isInsertionMarker&&c.isInsertionMarker()||(c=c.getBoundingRectangle(),c.top<b.top&&(b.top=c.top),c.bottom>b.bottom&&(b.bottom=c.bottom),c.left<b.left&&(b.left=c.left),c.right>b.right&&(b.right=c.right))}return b}cleanUp(){this.setResizesEnabled(!1);const a=$.getGroup$$module$build$src$core$events$utils();a||$.setGroup$$module$build$src$core$events$utils(!0);var b=this.getTopBlocks(!0),c=b.filter(g=>g.isMovable());const d=b.filter(g=>!g.isMovable()).map(g=>
g.getBoundingRectangle());b=function(g){for(const h of d)if(g.intersects(h))return h;return null};var e=0;const f=this.renderer.getConstants().MIN_BLOCK_HEIGHT;for(const g of c){c=g.getBoundingRectangle();g.moveBy(-c.left,e-c.top,["cleanup"]);g.snapToGrid();c=g.getBoundingRectangle();for(e=b(c);e!=null;)e=e.top+e.getHeight()+f,g.moveBy(0,e-c.top,["cleanup"]),g.snapToGrid(),c=g.getBoundingRectangle(),e=b(c);e=g.getRelativeToSurfaceXY().y+g.getHeightWidth().height+f}$.setGroup$$module$build$src$core$events$utils(a);
this.setResizesEnabled(!0)}showContextMenu(a){if(!this.isReadOnly()&&!this.isFlyout){var b=ContextMenuRegistry$$module$build$src$core$contextmenu_registry.registry.getContextMenuOptions({workspace:this,focusedNode:this},a);this.configureContextMenu&&this.configureContextMenu(b,a);var c=a instanceof PointerEvent?new Coordinate$$module$build$src$core$utils$coordinate(a.clientX,a.clientY):wsToScreenCoordinates$$module$build$src$core$utils$svg_math(this,new Coordinate$$module$build$src$core$utils$coordinate(5,
5));show$$module$build$src$core$contextmenu(a,b,this.RTL,this,c)}}updateToolbox(a){if(a=convertToolboxDefToJson$$module$build$src$core$utils$toolbox(a)){if(!this.options.languageTree)throw Error("Existing toolbox is null.  Can't create new toolbox.");if(hasCategories$$module$build$src$core$utils$toolbox(a)){if(!this.toolbox)throw Error("Existing toolbox has no categories.  Can't change mode.");this.options.languageTree=a;this.toolbox.render(a)}else{if(!this.flyout)throw Error("Existing toolbox has categories.  Can't change mode.");
this.options.languageTree=a;this.flyout.show(a)}}else if(this.options.languageTree)throw Error("Can't nullify an existing toolbox.");}markFocused(){this.options.parentWorkspace?this.options.parentWorkspace.markFocused():(setMainWorkspace$$module$build$src$core$common(this),this.getParentSvg().focus({preventScroll:!0}))}zoom(a,b,c){c=Math.pow(this.options.zoomOptions.scaleSpeed,c);const d=this.scale*c;if(this.scale!==d){d>this.options.zoomOptions.maxScale?c=this.options.zoomOptions.maxScale/this.scale:
d<this.options.zoomOptions.minScale&&(c=this.options.zoomOptions.minScale/this.scale);var e=this.getCanvas().getCTM(),f=this.getParentSvg().createSVGPoint();f.x=a;f.y=b;f=f.matrixTransform(e.inverse());a=f.x;b=f.y;e=e.translate(a*(1-c),b*(1-c)).scale(c);this.scrollX=e.e;this.scrollY=e.f;this.setScale(d)}}zoomCenter(a){var b=this.getMetrics();let c;this.flyout?(c=b.svgWidth?b.svgWidth/2:0,b=b.svgHeight?b.svgHeight/2:0):(c=b.viewWidth/2+b.absoluteLeft,b=b.viewHeight/2+b.absoluteTop);this.zoom(c,b,a)}zoomToFit(){if(this.isMovable()){var a=
this.getMetrics(),b=a.viewWidth;a=a.viewHeight;var c=this.getBlocksBoundingBox(),d=ZOOM_TO_FIT_MARGIN$$module$build$src$core$workspace_svg*2,e=c.right-c.left+d;c=c.bottom-c.top+d;if(e){this.flyout&&(this.horizontalLayout?(a+=this.flyout.getHeight(),c+=this.flyout.getHeight()/this.scale):(b+=this.flyout.getWidth(),e+=this.flyout.getWidth()/this.scale));b/=e;a/=c;$.disable$$module$build$src$core$events$utils();try{this.setScale(Math.min(b,a)),this.scrollCenter()}finally{$.enable$$module$build$src$core$events$utils()}this.maybeFireViewportChangeEvent()}}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")}beginCanvasTransition(){addClass$$module$build$src$core$utils$dom(this.getCanvas(),
"blocklyCanvasTransitioning");addClass$$module$build$src$core$utils$dom(this.getBubbleCanvas(),"blocklyCanvasTransitioning")}endCanvasTransition(){removeClass$$module$build$src$core$utils$dom(this.getCanvas(),"blocklyCanvasTransitioning");removeClass$$module$build$src$core$utils$dom(this.getBubbleCanvas(),"blocklyCanvasTransitioning")}scrollCenter(){if(this.isMovable()){var a=this.getMetrics(),b=(a.scrollWidth-a.viewWidth)/2,c=(a.scrollHeight-a.viewHeight)/2;b=-b-a.scrollLeft;c=-c-a.scrollTop;this.scroll(b,
c)}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")}centerOnBlock(a,b){if(this.isMovable()){var c=a?this.getBlockById(a):null;if(c){a=c.getRelativeToSurfaceXY();c=b?{height:c.height,width:c.width}:c.getHeightWidth();var d=this.scale;b=(a.x+(this.RTL?-1:1)*c.width/2)*d;a=(a.y+c.height/2)*d;c=this.getMetrics();this.scroll(-(b-c.viewWidth/2),-(a-c.viewHeight/2))}}else console.warn("Tried to move a non-movable workspace. This could result in blocks becoming inaccessible.")}setScale(a){this.options.zoomOptions.maxScale&&
a>this.options.zoomOptions.maxScale?a=this.options.zoomOptions.maxScale:this.options.zoomOptions.minScale&&a<this.options.zoomOptions.minScale&&(a=this.options.zoomOptions.minScale);this.scale=a;this.hideChaff(!1);(a=this.getFlyout(!1))&&a.isVisible()&&(a.reflow(),this.recordDragTargets());this.grid&&this.grid.update(this.scale);a=this.getMetrics();this.scrollX-=a.absoluteLeft;this.scrollY-=a.absoluteTop;a.viewLeft+=a.absoluteLeft;a.viewTop+=a.absoluteTop;this.scroll(this.scrollX,this.scrollY);this.scrollbar&&
(this.flyout?this.scrollbar.resizeView(a):this.scrollbar.resizeContent(a))}getScale(){return this.scale}getAbsoluteScale(){const a=c=>{if(c.isFlyout){let d;const e=(d=c.targetWorkspace)==null?void 0:d.getFlyout();if(e instanceof Flyout$$module$build$src$core$flyout_base)return e.getFlyoutScale()}return c.getScale()},b=(c,d)=>c.options.parentWorkspace&&c.options.parentWorkspace.getSvgGroup().contains(c.getSvgGroup())?b(c.options.parentWorkspace,d*a(c)):d*a(c);return b(this,1)}scroll(a,b){this.hideChaff(!0);
const c=this.getMetrics();a=Math.min(a,-c.scrollLeft);b=Math.min(b,-c.scrollTop);const d=c.scrollTop+Math.max(0,c.scrollHeight-c.viewHeight);a=Math.max(a,-(c.scrollLeft+Math.max(0,c.scrollWidth-c.viewWidth)));b=Math.max(b,-d);this.scrollX=a;this.scrollY=b;this.scrollbar&&this.scrollbar.set(-(a+c.scrollLeft),-(b+c.scrollTop),!1);a+=c.absoluteLeft;b+=c.absoluteTop;this.translate(a,b)}getBlockById(a){return super.getBlockById(a)}getAllBlocks(a=!1){return super.getAllBlocks(a)}getTopBlocks(a=!1){return super.getTopBlocks(a)}addTopBlock(a){this.addTopBoundedElement(a);
super.addTopBlock(a)}removeTopBlock(a){this.removeTopBoundedElement(a);super.removeTopBlock(a)}addTopComment(a){this.addTopBoundedElement(a);super.addTopComment(a)}removeTopComment(a){this.removeTopBoundedElement(a);super.removeTopComment(a)}getTopComments(a=!1){return super.getTopComments(a)}getCommentById(a){return super.getCommentById(a)}getRootWorkspace(){return super.getRootWorkspace()}addTopBoundedElement(a){this.topBoundedElements.push(a)}removeTopBoundedElement(a){removeElem$$module$build$src$core$utils$array(this.topBoundedElements,
a)}getTopBoundedElements(a=!1){const b=[].concat(this.topBoundedElements);a&&b.sort(this.sortByOrigin.bind(this));return b}setResizesEnabled(a){const b=!this.resizesEnabled&&a;this.resizesEnabled=a;b&&this.resizeContents()}clear(){this.setResizesEnabled(!1);super.clear();this.topBoundedElements=[];this.setResizesEnabled(!0)}registerButtonCallback(a,b){if(typeof b!=="function")throw TypeError("Button callbacks must be functions.");this.flyoutButtonCallbacks.set(a,b)}getButtonCallback(a){let b;return(b=
this.flyoutButtonCallbacks.get(a))!=null?b:null}removeButtonCallback(a){this.flyoutButtonCallbacks.delete(a)}registerToolboxCategoryCallback(a,b){if(typeof b!=="function")throw TypeError("Toolbox category callbacks must be functions.");this.toolboxCategoryCallbacks.set(a,b)}getToolboxCategoryCallback(a){return this.toolboxCategoryCallbacks.get(a)||null}removeToolboxCategoryCallback(a){this.toolboxCategoryCallbacks.delete(a)}getGesture(a){if(this.keyboardMoveInProgress)return a.preventDefault(),a.stopPropagation(),
null;const b=a.type==="pointerdown";let c;b&&((c=this.currentGesture_)==null?0:c.hasStarted())&&(console.warn("Tried to start the same gesture twice."),this.currentGesture_.cancel());!this.currentGesture_&&b&&(this.currentGesture_=new Gesture$$module$build$src$core$gesture(a,this));return this.currentGesture_}clearGesture(){this.currentGesture_=null}cancelCurrentGesture(){this.currentGesture_&&this.currentGesture_.cancel()}getAudioManager(){return this.audioManager}getGrid(){return this.grid}hideChaff(a=
!1){hide$$module$build$src$core$tooltip();hideIfOwnerIsInWorkspace$$module$build$src$core$widgetdiv(this);hideWithoutAnimation$$module$build$src$core$dropdowndiv();this.hideComponents(a)}hideComponents(a=!1){this.getComponentManager().getComponents(ComponentManager$$module$build$src$core$component_manager.Capability.AUTOHIDEABLE,!0).forEach(b=>b.autoHide(a))}static setTopLevelWorkspaceMetrics(a){const b=this.getMetrics();typeof a.x==="number"&&(this.scrollX=-(b.scrollLeft+(b.scrollWidth-b.viewWidth)*
a.x));typeof a.y==="number"&&(this.scrollY=-(b.scrollTop+(b.scrollHeight-b.viewHeight)*a.y));this.translate(this.scrollX+b.absoluteLeft,this.scrollY+b.absoluteTop)}addClass(a){this.injectionDiv&&addClass$$module$build$src$core$utils$dom(this.injectionDiv,a)}removeClass(a){this.injectionDiv&&removeClass$$module$build$src$core$utils$dom(this.injectionDiv,a)}setIsReadOnly(a){super.setIsReadOnly(a);a?this.addClass("blocklyReadOnly"):this.removeClass("blocklyReadOnly")}scrollBoundsIntoView(a,b=10){if(!Gesture$$module$build$src$core$gesture.inProgress()){var c=
this.getScale(),d=this.getMetricsManager().getViewMetrics(!0);d=new Rect$$module$build$src$core$utils$rect(d.top,d.top+d.height,d.left,d.left+d.width);if(!(a.left>=d.left&&a.top>=d.top&&a.right<=d.right&&a.bottom<=d.bottom)){a=a.clone();a.top-=b;a.bottom+=b;a.left-=b;a.right+=b;var e=b=0;a.left<d.left?b=this.RTL?Math.min(d.left-a.left,d.right-a.right):d.left-a.left:a.right>d.right&&(b=this.RTL?d.right-a.right:Math.max(d.right-a.right,d.left-a.left));a.top<d.top?e=d.top-a.top:a.bottom>d.bottom&&(e=
Math.max(d.bottom-a.bottom,d.top-a.top));this.scroll(this.scrollX+b*c,this.scrollY+e*c)}}}getFocusableElement(){return this.svgGroup_}getFocusableTree(){return this.isMutator&&this.options.parentWorkspace||this}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!0}getRootFocusableNode(){return this}getRestoredFocusableNode(a){if(a)return null;let b;a=(b=this.targetWorkspace)==null?void 0:b.getFlyout();if(this.isFlyout&&a){let d,e;return(e=(d=a.getContents().find(f=>{f=f.getElement();return isFocusableNode$$module$build$src$core$interfaces$i_focusable_node(f)&&
f.canBeFocused()}))==null?void 0:d.getElement())!=null?e:null}let c;return(c=this.getTopBlocks(!0)[0])!=null?c:null}getNestedTrees(){const a=this.getAllBlocks().map(c=>c.getIcons()).flat().filter(c=>c instanceof $.MutatorIcon$$module$build$src$core$icons$mutator_icon&&c.bubbleIsVisible()).map(c=>{let d;return(d=c.getBubble())==null?void 0:d.getWorkspace()}).filter(c=>!!c),b=this.getFlyout(!0);b&&a.push(b.getWorkspace());return a}searchForWorkspaceComment(a){for(const b of this.getTopComments())if(b instanceof
RenderedWorkspaceComment$$module$build$src$core$comments$rendered_workspace_comment&&b.canBeFocused()&&b.getFocusableElement().id===a)return b}lookUpFocusableNode(a){var b;const c=(b=this.targetWorkspace)==null?void 0:b.getFlyout();if(this.isFlyout&&c)for(var d of c.getContents())if(b=d.getElement(),isFocusableNode$$module$build$src$core$interfaces$i_focusable_node(b)&&b.canBeFocused()&&b.getFocusableElement().id===a)return b;d=a.indexOf("_field_");b=a.indexOf("_connection_");if(d!==-1){var e=a.substring(0,
d);if(e=this.getBlockById(e))for(var f of e.getFields())if(f.canBeFocused()&&f.getFocusableElement().id===a)return f;return null}if(b!==-1){e=a.substring(0,b);if(e=this.getBlockById(e))for(const h of e.getConnections_(!0))if(h.id===a)return h;return null}f=Math.max(a.indexOf(COMMENT_EDITOR_FOCUS_IDENTIFIER$$module$build$src$core$comments$comment_editor),a.indexOf(COMMENT_COLLAPSE_BAR_BUTTON_FOCUS_IDENTIFIER$$module$build$src$core$comments$collapse_comment_bar_button),a.indexOf(COMMENT_DELETE_BAR_BUTTON_FOCUS_IDENTIFIER$$module$build$src$core$comments$delete_comment_bar_button));
if(f!==-1&&(f=a.substring(0,f),f=this.searchForWorkspaceComment(f))){if(a.indexOf(COMMENT_EDITOR_FOCUS_IDENTIFIER$$module$build$src$core$comments$comment_editor)>-1)return f.getEditorFocusableNode();var g;return(g=f.view.getCommentBarButtons().find(h=>h.getFocusableElement().id.includes(a)))!=null?g:null}if((g=this.getAllBlocks(!1).find(h=>h.getFocusableElement().id===a))||(g=this.searchForWorkspaceComment(a)))return g;g=this.getAllBlocks().map(h=>h.getIcons()).flat();for(e of g){if(e.canBeFocused()&&
e.getFocusableElement().id===a)return e;if(hasBubble$$module$build$src$core$interfaces$i_has_bubble(e)){if((g=e.getBubble())&&g.canBeFocused()&&g.getFocusableElement().id===a)return g;if(g instanceof TextInputBubble$$module$build$src$core$bubbles$textinput_bubble&&g.getEditor().getFocusableElement().id===a)return g.getEditor()}}return null}onTreeFocus(a,b){}onTreeBlur(a){if(this.isFlyout&&this.targetWorkspace&&!$.getFocusManager$$module$build$src$core$focus_manager().ephemeralFocusTaken()){var b=
this.targetWorkspace.getToolbox();b&&a===b||isAutoHideable$$module$build$src$core$interfaces$i_autohideable(b)&&b.autoHide(!1)}}getNavigator(){return this.navigator}setNavigator(a){this.navigator=a}},module$build$src$core$workspace_svg={};module$build$src$core$workspace_svg.WorkspaceSvg=WorkspaceSvg$$module$build$src$core$workspace_svg;module$build$src$core$workspace_svg.resizeSvgContents=resizeSvgContents$$module$build$src$core$workspace_svg;var VarBase$$module$build$src$core$events$events_var_base=class extends Abstract$$module$build$src$core$events$events_abstract{constructor(a){super();this.isBlank=typeof a==="undefined";a&&(this.varId=a.getId(),this.workspaceId=a.getWorkspace().id)}toJson(){const a=super.toJson();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");a.varId=this.varId;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new VarBase$$module$build$src$core$events$events_var_base);
b.varId=a.varId;return b}},module$build$src$core$events$events_var_base={};module$build$src$core$events$events_var_base.VarBase=VarBase$$module$build$src$core$events$events_var_base;var VarCreate$$module$build$src$core$events$events_var_create=class extends VarBase$$module$build$src$core$events$events_var_base{constructor(a){super(a);this.type=EventType$$module$build$src$core$events$type.VAR_CREATE;a&&(this.varType=a.getType(),this.varName=a.getName())}toJson(){const a=super.toJson();if(this.varType===void 0)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");
a.varType=this.varType;a.varName=this.varName;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new VarCreate$$module$build$src$core$events$events_var_create);b.varType=a.varType;b.varName=a.varName;return b}run(a){var b=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");b=b.getVariableMap();
a?b.createVariable(this.varName,this.varType,this.varId):(a=b.getVariableById(this.varId))&&b.deleteVariable(a)}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.VAR_CREATE,VarCreate$$module$build$src$core$events$events_var_create);var module$build$src$core$events$events_var_create={};module$build$src$core$events$events_var_create.VarCreate=VarCreate$$module$build$src$core$events$events_var_create;var VariableModel$$module$build$src$core$variable_model=class{constructor(a,b,c,d){this.workspace=a;this.name=b;this.type=c||"";this.id=d||genUid$$module$build$src$core$utils$idgenerator()}getId(){return this.id}getName(){return this.name}setName(a){this.name=a;return this}getType(){return this.type}setType(a){this.type=a;return this}getWorkspace(){return this.workspace}save(){const a={name:this.getName(),id:this.getId()},b=this.getType();b&&(a.type=b);return a}static load(a,b){a=new this(b,a.name,
a.type,a.id);b.getVariableMap().addVariable(a);fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.VAR_CREATE))(a))}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.VARIABLE_MODEL,DEFAULT$$module$build$src$core$registry,VariableModel$$module$build$src$core$variable_model);var module$build$src$core$variable_model={};module$build$src$core$variable_model.VariableModel=VariableModel$$module$build$src$core$variable_model;var VarDelete$$module$build$src$core$events$events_var_delete=class extends VarBase$$module$build$src$core$events$events_var_base{constructor(a){super(a);this.type=EventType$$module$build$src$core$events$type.VAR_DELETE;a&&(this.varType=a.getType(),this.varName=a.getName())}toJson(){const a=super.toJson();if(this.varType===void 0)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");
a.varType=this.varType;a.varName=this.varName;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new VarDelete$$module$build$src$core$events$events_var_delete);b.varType=a.varType;b.varName=a.varName;return b}run(a){var b=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");b=b.getVariableMap();
a?(a=b.getVariableById(this.varId))&&b.deleteVariable(a):b.createVariable(this.varName,this.varType,this.varId)}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.VAR_DELETE,VarDelete$$module$build$src$core$events$events_var_delete);var module$build$src$core$events$events_var_delete={};module$build$src$core$events$events_var_delete.VarDelete=VarDelete$$module$build$src$core$events$events_var_delete;var VarRename$$module$build$src$core$events$events_var_rename=class extends VarBase$$module$build$src$core$events$events_var_base{constructor(a,b){super(a);this.type=EventType$$module$build$src$core$events$type.VAR_RENAME;a&&(this.oldName=a.getName(),this.newName=typeof b==="undefined"?"":b)}toJson(){const a=super.toJson();if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");
a.oldName=this.oldName;a.newName=this.newName;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new VarRename$$module$build$src$core$events$events_var_rename);b.oldName=a.oldName;b.newName=a.newName;return b}run(a){var b=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");
b=b.getVariableMap();const c=b.getVariableById(this.varId);a?c&&b.renameVariable(c,this.newName):c&&b.renameVariable(c,this.oldName)}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.VAR_RENAME,VarRename$$module$build$src$core$events$events_var_rename);var module$build$src$core$events$events_var_rename={};module$build$src$core$events$events_var_rename.VarRename=VarRename$$module$build$src$core$events$events_var_rename;var VariableMap$$module$build$src$core$variable_map=class{constructor(a,b=!1){this.workspace=a;this.potentialMap=b;this.variableMap=new Map}clear(){for(const a of this.variableMap.values())for(const b of a.values())this.deleteVariable(b);if(this.variableMap.size!==0)throw Error("Non-empty variable map");}renameVariable(a,b){if(a.getName()===b)return a;var c=a.getType();c=this.getVariable(b,c);const d=this.workspace.getAllBlocks(!1);let e="";this.potentialMap||(e=$.getGroup$$module$build$src$core$events$utils())||
$.setGroup$$module$build$src$core$events$utils(!0);try{c&&c.getId()!==a.getId()?this.renameVariableWithConflict(a,b,c,d):this.renameVariableAndUses(a,b,d)}finally{this.potentialMap||$.setGroup$$module$build$src$core$events$utils(e)}return a}changeVariableType(a,b){const c=a.getType();if(c===b)return a;var d=this.variableMap.get(c);d==null||d.delete(a.getId());(d==null?void 0:d.size)===0&&this.variableMap.delete(c);a.setType(b);let e;d=(e=this.variableMap.get(b))!=null?e:new Map;d.set(a.getId(),a);
this.variableMap.has(b)||this.variableMap.set(b,d);fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.VAR_TYPE_CHANGE))(a,c,b));return a}renameVariableById(a,b){warn$$module$build$src$core$utils$deprecation("VariableMap.renameVariableById","v12","v13","VariableMap.renameVariable");const c=this.getVariableById(a);if(!c)throw Error("Tried to rename a variable that didn't exist. ID: "+a);this.renameVariable(c,b)}renameVariableAndUses(a,
b,c){this.potentialMap||fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.VAR_RENAME))(a,b));a.setName(b);for(b=0;b<c.length;b++)c[b].updateVarName(a)}renameVariableWithConflict(a,b,c,d){const e=a.getType(),f=c.getName();b!==f&&this.renameVariableAndUses(c,b,d);for(b=0;b<d.length;b++)d[b].renameVarById(a.getId(),c.getId());this.potentialMap||fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.VAR_DELETE))(a));
let g;(g=this.variableMap.get(e))==null||g.delete(a.getId())}createVariable(a,b,c){var d=this.getVariable(a,b);if(d){if(c&&d.getId()!==c)throw Error('Variable "'+a+'" is already in use and its id is "'+d.getId()+'" which conflicts with the passed in id, "'+c+'".');return d}if(c&&this.getVariableById(c))throw Error('Variable id, "'+c+'", is already in use.');d=c||genUid$$module$build$src$core$utils$idgenerator();b=b||"";c=getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.VARIABLE_MODEL,
this.workspace.options,!0);if(!c)throw Error("No variable model is registered.");d=new c(this.workspace,a,b,d);let e;a=(e=this.variableMap.get(b))!=null?e:new Map;a.set(d.getId(),d);this.variableMap.has(b)||this.variableMap.set(b,a);this.potentialMap||fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.VAR_CREATE))(d));return d}addVariable(a){const b=a.getType();this.variableMap.has(b)||this.variableMap.set(b,new Map);
let c;(c=this.variableMap.get(b))==null||c.set(a.getId(),a)}deleteVariable(a){const b=getVariableUsesById$$module$build$src$core$variables(this.workspace,a.getId());let c="";this.potentialMap||(c=$.getGroup$$module$build$src$core$events$utils())||$.setGroup$$module$build$src$core$events$utils(!0);try{for(let e=0;e<b.length;e++)b[e].dispose(!0);const d=this.variableMap.get(a.getType());d&&d.has(a.getId())&&(d.delete(a.getId()),this.potentialMap||fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.VAR_DELETE))(a)),
d.size===0&&this.variableMap.delete(a.getType()))}finally{this.potentialMap||$.setGroup$$module$build$src$core$events$utils(c)}}deleteVariableById(a){warn$$module$build$src$core$utils$deprecation("VariableMap.deleteVariableById","v12","v13","Blockly.Variables.deleteVariable");(a=this.getVariableById(a))&&$.deleteVariable$$module$build$src$core$variables(this.workspace,a)}getVariable(a,b){b=this.variableMap.get(b||"");if(!b)return null;let c;return(c=[...b.values()].find(d=>$.Names$$module$build$src$core$names.equals(d.getName(),
a)))!=null?c:null}getVariableById(a){for(const b of this.variableMap.values())if(b.has(a)){let c;return(c=b.get(a))!=null?c:null}return null}getVariablesOfType(a){return(a=this.variableMap.get(a||""))?[...a.values()]:[]}getTypes(){return[...this.variableMap.keys()]}getAllVariables(){let a=[];for(const b of this.variableMap.values())a=a.concat(...b.values());return a}getAllVariableNames(){warn$$module$build$src$core$utils$deprecation("VariableMap.getAllVariableNames","v12","v13","Blockly.Variables.getAllVariables");
const a=[];for(const b of this.variableMap.values())for(const c of b.values())a.push(c.getName());return a}getVariableUsesById(a){warn$$module$build$src$core$utils$deprecation("VariableMap.getVariableUsesById","v12","v13","Blockly.Variables.getVariableUsesById");return getVariableUsesById$$module$build$src$core$variables(this.workspace,a)}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.VARIABLE_MAP,DEFAULT$$module$build$src$core$registry,VariableMap$$module$build$src$core$variable_map);
var module$build$src$core$variable_map={};module$build$src$core$variable_map.VariableMap=VariableMap$$module$build$src$core$variable_map;var TrashcanOpen$$module$build$src$core$events$events_trashcan_open=class extends UiBase$$module$build$src$core$events$events_ui_base{constructor(a,b){super(b);this.type=EventType$$module$build$src$core$events$type.TRASHCAN_OPEN;this.isOpen=a}toJson(){const a=super.toJson();if(this.isOpen===void 0)throw Error("Whether this is already open or not is undefined. Either pass a value to the constructor, or call fromJson");a.isOpen=this.isOpen;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?
c:new TrashcanOpen$$module$build$src$core$events$events_trashcan_open);b.isOpen=a.isOpen;return b}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.TRASHCAN_OPEN,TrashcanOpen$$module$build$src$core$events$events_trashcan_open);var module$build$src$core$events$events_trashcan_open={};module$build$src$core$events$events_trashcan_open.TrashcanOpen=TrashcanOpen$$module$build$src$core$events$events_trashcan_open;var Trashcan$$module$build$src$core$trashcan=class extends DeleteArea$$module$build$src$core$delete_area{constructor(a){super();this.workspace=a;this.id="trashcan";this.contents=[];this.flyout=null;this.isLidOpen=!1;this.minOpenness=0;this.lidTask=this.svgLid=this.svgGroup=null;this.top=this.left=this.lidOpen=0;this.initialized=!1;this.workspace.options.maxTrashcanContents<=0||(a=this.workspace.copyOptionsForFlyout(),this.workspace.horizontalLayout?(a.toolboxPosition=this.workspace.toolboxPosition===
Position$$module$build$src$core$utils$toolbox.TOP?Position$$module$build$src$core$utils$toolbox.BOTTOM:Position$$module$build$src$core$utils$toolbox.TOP,this.flyout=new (getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUTS_HORIZONTAL_TOOLBOX,this.workspace.options,!0))(a)):(a.toolboxPosition=this.workspace.toolboxPosition===Position$$module$build$src$core$utils$toolbox.RIGHT?Position$$module$build$src$core$utils$toolbox.LEFT:Position$$module$build$src$core$utils$toolbox.RIGHT,
this.flyout=new (getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUTS_VERTICAL_TOOLBOX,this.workspace.options,!0))(a)),this.workspace.addChangeListener(this.onDelete.bind(this)))}createDom(){this.svgGroup=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.G,{"class":"blocklyTrash"});let a;const b=String(Math.random()).substring(2);a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.CLIPPATH,
{id:"blocklyTrashBodyClipPath"+b},this.svgGroup);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{width:WIDTH$$module$build$src$core$trashcan,height:BODY_HEIGHT$$module$build$src$core$trashcan,y:LID_HEIGHT$$module$build$src$core$trashcan},a);const c=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,{width:SPRITE$$module$build$src$core$sprites.width,x:-SPRITE_LEFT$$module$build$src$core$trashcan,height:SPRITE$$module$build$src$core$sprites.height,
y:-SPRITE_TOP$$module$build$src$core$trashcan,"clip-path":"url(#blocklyTrashBodyClipPath"+b+")"},this.svgGroup);c.setAttributeNS(XLINK_NS$$module$build$src$core$utils$dom,"xlink:href",this.workspace.options.pathToMedia+SPRITE$$module$build$src$core$sprites.url);a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.CLIPPATH,{id:"blocklyTrashLidClipPath"+b},this.svgGroup);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.RECT,{width:WIDTH$$module$build$src$core$trashcan,
height:LID_HEIGHT$$module$build$src$core$trashcan},a);this.svgLid=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,{width:SPRITE$$module$build$src$core$sprites.width,x:-SPRITE_LEFT$$module$build$src$core$trashcan,height:SPRITE$$module$build$src$core$sprites.height,y:-SPRITE_TOP$$module$build$src$core$trashcan,"clip-path":"url(#blocklyTrashLidClipPath"+b+")"},this.svgGroup);this.svgLid.setAttributeNS(XLINK_NS$$module$build$src$core$utils$dom,"xlink:href",
this.workspace.options.pathToMedia+SPRITE$$module$build$src$core$sprites.url);bind$$module$build$src$core$browser_events(this.svgGroup,"pointerdown",this,this.blockMouseDownWhenOpenable);bind$$module$build$src$core$browser_events(this.svgGroup,"pointerup",this,this.click);bind$$module$build$src$core$browser_events(c,"pointerover",this,this.mouseOver);bind$$module$build$src$core$browser_events(c,"pointerout",this,this.mouseOut);this.animateLid();return this.svgGroup}init(){if(this.workspace.options.maxTrashcanContents>
0){const a=this.flyout.createDom(Svg$$module$build$src$core$utils$svg.SVG);addClass$$module$build$src$core$utils$dom(a,"blocklyTrashcanFlyout");insertAfter$$module$build$src$core$utils$dom(a,this.workspace.getParentSvg());this.flyout.init(this.workspace)}this.workspace.getComponentManager().addComponent({component:this,weight:ComponentManager$$module$build$src$core$component_manager.ComponentWeight.TRASHCAN_WEIGHT,capabilities:[ComponentManager$$module$build$src$core$component_manager.Capability.AUTOHIDEABLE,
ComponentManager$$module$build$src$core$component_manager.Capability.DELETE_AREA,ComponentManager$$module$build$src$core$component_manager.Capability.DRAG_TARGET,ComponentManager$$module$build$src$core$component_manager.Capability.POSITIONABLE]});this.initialized=!0;this.setLidOpen(!1)}dispose(){this.workspace.getComponentManager().removeComponent("trashcan");this.svgGroup&&removeNode$$module$build$src$core$utils$dom(this.svgGroup);this.lidTask&&clearTimeout(this.lidTask)}hasContents(){return!!this.contents.length}contentsIsOpen(){return!!this.flyout&&
this.flyout.isVisible()}openFlyout(){if(!this.contentsIsOpen()){var a=this.contents.map(function(c){return JSON.parse(c)}),b=this.workspace.getParentSvg().style;b.cursor="wait";setTimeout(()=>{let c;(c=this.flyout)==null||c.show(a);b.cursor="";let d;(d=this.workspace.scrollbar)==null||d.setVisible(!1)},10);this.fireUiEvent(!0)}}closeFlyout(){if(this.contentsIsOpen()){var a;(a=this.flyout)==null||a.hide();var b;(b=this.workspace.scrollbar)==null||b.setVisible(!0);this.fireUiEvent(!1);this.workspace.recordDragTargets()}}autoHide(a){!a&&
this.flyout&&this.closeFlyout()}emptyContents(){this.hasContents()&&(this.contents.length=0,this.setMinOpenness(0),this.closeFlyout())}position(a,b){if(this.initialized){var c=getCornerOppositeToolbox$$module$build$src$core$positionable_helpers(this.workspace,a);a=getStartPositionRect$$module$build$src$core$positionable_helpers(c,new Size$$module$build$src$core$utils$size(WIDTH$$module$build$src$core$trashcan,BODY_HEIGHT$$module$build$src$core$trashcan+LID_HEIGHT$$module$build$src$core$trashcan),
MARGIN_HORIZONTAL$$module$build$src$core$trashcan,MARGIN_VERTICAL$$module$build$src$core$trashcan,a,this.workspace);b=bumpPositionRect$$module$build$src$core$positionable_helpers(a,MARGIN_VERTICAL$$module$build$src$core$trashcan,c.vertical===verticalPosition$$module$build$src$core$positionable_helpers.TOP?bumpDirection$$module$build$src$core$positionable_helpers.DOWN:bumpDirection$$module$build$src$core$positionable_helpers.UP,b);this.top=b.top;this.left=b.left;var d;(d=this.svgGroup)==null||d.setAttribute("transform",
"translate("+this.left+","+this.top+")");var e;(e=this.flyout)==null||e.position()}}getBoundingRectangle(){return new Rect$$module$build$src$core$utils$rect(this.top,this.top+BODY_HEIGHT$$module$build$src$core$trashcan+LID_HEIGHT$$module$build$src$core$trashcan,this.left,this.left+WIDTH$$module$build$src$core$trashcan)}getClientRect(){if(!this.svgGroup)return null;var a=this.svgGroup.getBoundingClientRect();const b=a.top+SPRITE_TOP$$module$build$src$core$trashcan-MARGIN_HOTSPOT$$module$build$src$core$trashcan;
a=a.left+SPRITE_LEFT$$module$build$src$core$trashcan-MARGIN_HOTSPOT$$module$build$src$core$trashcan;return new Rect$$module$build$src$core$utils$rect(b,b+LID_HEIGHT$$module$build$src$core$trashcan+BODY_HEIGHT$$module$build$src$core$trashcan+2*MARGIN_HOTSPOT$$module$build$src$core$trashcan,a,a+WIDTH$$module$build$src$core$trashcan+2*MARGIN_HOTSPOT$$module$build$src$core$trashcan)}onDragOver(a){this.setLidOpen(this.wouldDelete_)}onDragExit(a){this.setLidOpen(!1)}onDrop(a){setTimeout(this.setLidOpen.bind(this,
!1),100)}setLidOpen(a){this.isLidOpen!==a&&(this.lidTask&&clearTimeout(this.lidTask),this.isLidOpen=a,this.animateLid())}animateLid(){const a=ANIMATION_FRAMES$$module$build$src$core$trashcan;var b=1/(a+1);this.lidOpen+=this.isLidOpen?b:-b;this.lidOpen=Math.min(Math.max(this.lidOpen,this.minOpenness),1);this.setLidAngle(this.lidOpen*MAX_LID_ANGLE$$module$build$src$core$trashcan);b=OPACITY_MIN$$module$build$src$core$trashcan+this.lidOpen*(OPACITY_MAX$$module$build$src$core$trashcan-OPACITY_MIN$$module$build$src$core$trashcan);
this.svgGroup&&(this.svgGroup.style.opacity=`${b}`);this.lidOpen>this.minOpenness&&this.lidOpen<1&&(this.lidTask=setTimeout(this.animateLid.bind(this),ANIMATION_LENGTH$$module$build$src$core$trashcan/a))}setLidAngle(a){const b=this.workspace.toolboxPosition===Position$$module$build$src$core$utils$toolbox.RIGHT||this.workspace.horizontalLayout&&this.workspace.RTL;let c;(c=this.svgLid)==null||c.setAttribute("transform","rotate("+(b?-a:a)+","+(b?4:WIDTH$$module$build$src$core$trashcan-4)+","+(LID_HEIGHT$$module$build$src$core$trashcan-
2)+")")}setMinOpenness(a){this.minOpenness=a;this.isLidOpen||this.setLidAngle(a*MAX_LID_ANGLE$$module$build$src$core$trashcan)}closeLid(){this.setLidOpen(!1)}click(){this.hasContents()&&!this.workspace.isDragging()&&this.openFlyout()}fireUiEvent(a){a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.TRASHCAN_OPEN))(a,this.workspace.id);fire$$module$build$src$core$events$utils(a)}blockMouseDownWhenOpenable(a){!this.contentsIsOpen()&&this.hasContents()&&a.stopPropagation()}mouseOver(){this.hasContents()&&
this.setLidOpen(!0)}mouseOut(){this.setLidOpen(!1)}onDelete(a){if(!(this.workspace.options.maxTrashcanContents<=0||!isBlockDelete$$module$build$src$core$events$predicates(a)||a.wasShadow)){if(!a.oldJson)throw Error("Encountered a delete event without proper oldJson");a=JSON.stringify(this.cleanBlockJson(a.oldJson));if(!this.contents.includes(a)){for(this.contents.unshift(a);this.contents.length>this.workspace.options.maxTrashcanContents;)this.contents.pop();this.setMinOpenness(HAS_BLOCKS_LID_ANGLE$$module$build$src$core$trashcan)}}}cleanBlockJson(a){function b(c){if(c){delete c.id;
delete c.x;delete c.y;delete c.enabled;delete c.disabledReasons;if(c.icons&&c.icons.comment){var d=c.icons.comment;delete d.height;delete d.width;delete d.pinned}d=c.inputs;for(var e in d){var f=d[e];const g=f.block;f=f.shadow;g&&b(g);f&&b(f)}c.next&&(e=c.next,c=e.block,e=e.shadow,c&&b(c),e&&b(e))}}a=JSON.parse(JSON.stringify(a));b(a);return Object.assign({},{kind:"BLOCK"},a)}},WIDTH$$module$build$src$core$trashcan=47,BODY_HEIGHT$$module$build$src$core$trashcan=44,LID_HEIGHT$$module$build$src$core$trashcan=
16,MARGIN_VERTICAL$$module$build$src$core$trashcan=20,MARGIN_HORIZONTAL$$module$build$src$core$trashcan=20,MARGIN_HOTSPOT$$module$build$src$core$trashcan=10,SPRITE_LEFT$$module$build$src$core$trashcan=0,SPRITE_TOP$$module$build$src$core$trashcan=32,HAS_BLOCKS_LID_ANGLE$$module$build$src$core$trashcan=.1,ANIMATION_LENGTH$$module$build$src$core$trashcan=80,ANIMATION_FRAMES$$module$build$src$core$trashcan=4,OPACITY_MIN$$module$build$src$core$trashcan=.4,OPACITY_MAX$$module$build$src$core$trashcan=.8,
MAX_LID_ANGLE$$module$build$src$core$trashcan=45,module$build$src$core$trashcan={};module$build$src$core$trashcan.Trashcan=Trashcan$$module$build$src$core$trashcan;var stashedCopyData$$module$build$src$core$clipboard=null,stashedWorkspace$$module$build$src$core$clipboard=null,stashedCoordinates$$module$build$src$core$clipboard=void 0,module$build$src$core$clipboard={};module$build$src$core$clipboard.BlockPaster=BlockPaster$$module$build$src$core$clipboard$block_paster;module$build$src$core$clipboard.copy=copy$$module$build$src$core$clipboard;module$build$src$core$clipboard.getLastCopiedData=getLastCopiedData$$module$build$src$core$clipboard;
module$build$src$core$clipboard.getLastCopiedLocation=getLastCopiedLocation$$module$build$src$core$clipboard;module$build$src$core$clipboard.getLastCopiedWorkspace=getLastCopiedWorkspace$$module$build$src$core$clipboard;module$build$src$core$clipboard.paste=paste$$module$build$src$core$clipboard;module$build$src$core$clipboard.registry=module$build$src$core$clipboard$registry;module$build$src$core$clipboard.setLastCopiedData=setLastCopiedData$$module$build$src$core$clipboard;
module$build$src$core$clipboard.setLastCopiedLocation=setLastCopiedLocation$$module$build$src$core$clipboard;module$build$src$core$clipboard.setLastCopiedWorkspace=setLastCopiedWorkspace$$module$build$src$core$clipboard;var module$build$src$core$comments={};module$build$src$core$comments.CollapseCommentBarButton=CollapseCommentBarButton$$module$build$src$core$comments$collapse_comment_bar_button;module$build$src$core$comments.CommentBarButton=CommentBarButton$$module$build$src$core$comments$comment_bar_button;module$build$src$core$comments.CommentEditor=CommentEditor$$module$build$src$core$comments$comment_editor;module$build$src$core$comments.CommentView=CommentView$$module$build$src$core$comments$comment_view;
module$build$src$core$comments.DeleteCommentBarButton=DeleteCommentBarButton$$module$build$src$core$comments$delete_comment_bar_button;module$build$src$core$comments.RenderedWorkspaceComment=RenderedWorkspaceComment$$module$build$src$core$comments$rendered_workspace_comment;module$build$src$core$comments.WorkspaceComment=WorkspaceComment$$module$build$src$core$comments$workspace_comment;var module$build$src$core$interfaces$i_copyable={};module$build$src$core$interfaces$i_copyable.isCopyable=isCopyable$$module$build$src$core$interfaces$i_copyable;var names$$module$build$src$core$shortcut_items;(function(a){a.ESCAPE="escape";a.DELETE="delete";a.COPY="copy";a.CUT="cut";a.PASTE="paste";a.UNDO="undo";a.REDO="redo"})(names$$module$build$src$core$shortcut_items||(names$$module$build$src$core$shortcut_items={}));registerDefaultShortcuts$$module$build$src$core$shortcut_items();var module$build$src$core$shortcut_items={};module$build$src$core$shortcut_items.names=names$$module$build$src$core$shortcut_items;
module$build$src$core$shortcut_items.registerCopy=registerCopy$$module$build$src$core$shortcut_items;module$build$src$core$shortcut_items.registerCut=registerCut$$module$build$src$core$shortcut_items;module$build$src$core$shortcut_items.registerDefaultShortcuts=registerDefaultShortcuts$$module$build$src$core$shortcut_items;module$build$src$core$shortcut_items.registerDelete=registerDelete$$module$build$src$core$shortcut_items;module$build$src$core$shortcut_items.registerEscape=registerEscape$$module$build$src$core$shortcut_items;
module$build$src$core$shortcut_items.registerPaste=registerPaste$$module$build$src$core$shortcut_items;module$build$src$core$shortcut_items.registerRedo=registerRedo$$module$build$src$core$shortcut_items;module$build$src$core$shortcut_items.registerUndo=registerUndo$$module$build$src$core$shortcut_items;var ProcedureSerializer$$module$build$src$core$serialization$procedures=class{constructor(a,b){this.procedureModelClass=a;this.parameterModelClass=b;this.priority=PROCEDURES$$module$build$src$core$serialization$priorities}save(a){a=a.getProcedureMap().getProcedures().map(b=>saveProcedure$$module$build$src$core$serialization$procedures(b));return a.length?a:null}load(a,b){const c=b.getProcedureMap();for(const d of a)c.add(loadProcedure$$module$build$src$core$serialization$procedures(this.procedureModelClass,
this.parameterModelClass,d,b))}clear(a){a.getProcedureMap().clear()}},module$build$src$core$serialization$procedures={};module$build$src$core$serialization$procedures.ProcedureSerializer=ProcedureSerializer$$module$build$src$core$serialization$procedures;module$build$src$core$serialization$procedures.loadProcedure=loadProcedure$$module$build$src$core$serialization$procedures;module$build$src$core$serialization$procedures.saveProcedure=saveProcedure$$module$build$src$core$serialization$procedures;var VariableSerializer$$module$build$src$core$serialization$variables=class{constructor(){this.priority=VARIABLES$$module$build$src$core$serialization$priorities}save(a){a=a.getAllVariables().map(b=>b.save());return a.length?a:null}load(a,b){const c=getObject$$module$build$src$core$registry(Type$$module$build$src$core$registry.VARIABLE_MODEL,DEFAULT$$module$build$src$core$registry);a.forEach(d=>{c==null||c.load(d,b)})}clear(a){a.getVariableMap().clear()}};
register$$module$build$src$core$serialization$registry("variables",new VariableSerializer$$module$build$src$core$serialization$variables);var module$build$src$core$serialization$variables={};module$build$src$core$serialization$variables.VariableSerializer=VariableSerializer$$module$build$src$core$serialization$variables;var module$build$src$core$serialization$workspaces={};module$build$src$core$serialization$workspaces.load=load$$module$build$src$core$serialization$workspaces;module$build$src$core$serialization$workspaces.save=save$$module$build$src$core$serialization$workspaces;var module$build$src$core$serialization={blocks:module$build$src$core$serialization$blocks,exceptions:module$build$src$core$serialization$exceptions,priorities:module$build$src$core$serialization$priorities,procedures:module$build$src$core$serialization$procedures,registry:module$build$src$core$serialization$registry,variables:module$build$src$core$serialization$variables,workspaceComments:module$build$src$core$serialization$workspace_comments,workspaces:module$build$src$core$serialization$workspaces};"Blockly"in globalThis||(globalThis.Blockly={Msg:module$build$src$core$msg});var module$build$src$core$main={};var LABEL_TYPE$$module$build$src$core$label_flyout_inflater="label",LabelFlyoutInflater$$module$build$src$core$label_flyout_inflater=class{load(a,b){a=new FlyoutButton$$module$build$src$core$flyout_button(b.getWorkspace(),b.targetWorkspace,a,!0);a.show();return new FlyoutItem$$module$build$src$core$flyout_item(a,LABEL_TYPE$$module$build$src$core$label_flyout_inflater)}gapForItem(a,b){return b}disposeItem(a){a=a.getElement();a instanceof FlyoutButton$$module$build$src$core$flyout_button&&a.dispose()}getType(){return LABEL_TYPE$$module$build$src$core$label_flyout_inflater}};
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUT_INFLATER,LABEL_TYPE$$module$build$src$core$label_flyout_inflater,LabelFlyoutInflater$$module$build$src$core$label_flyout_inflater);var module$build$src$core$label_flyout_inflater={};module$build$src$core$label_flyout_inflater.LabelFlyoutInflater=LabelFlyoutInflater$$module$build$src$core$label_flyout_inflater;var ConstantProvider$$module$build$src$core$renderers$zelos$constants=class extends ConstantProvider$$module$build$src$core$renderers$common$constants{constructor(a){super();this.GRID_UNIT=4;this.CURSOR_COLOUR="#ffa200";this.CURSOR_RADIUS=5;this.JAGGED_TEETH_WIDTH=this.JAGGED_TEETH_HEIGHT=0;this.START_HAT_HEIGHT=22;this.START_HAT_WIDTH=96;this.SHAPES={HEXAGONAL:1,ROUND:2,SQUARE:3,PUZZLE:4,NOTCH:5};this.SHAPE_IN_SHAPE_PADDING={1:{0:5*this.GRID_UNIT,1:2*this.GRID_UNIT,2:5*this.GRID_UNIT,3:5*this.GRID_UNIT},
2:{0:3*this.GRID_UNIT,1:3*this.GRID_UNIT,2:1*this.GRID_UNIT,3:2*this.GRID_UNIT},3:{0:2*this.GRID_UNIT,1:2*this.GRID_UNIT,2:2*this.GRID_UNIT,3:2*this.GRID_UNIT}};this.FULL_BLOCK_FIELDS=!0;this.FIELD_TEXT_FONTWEIGHT="bold";this.FIELD_TEXT_FONTFAMILY='"Helvetica Neue", "Segoe UI", Helvetica, sans-serif';this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!0;this.SELECTED_GLOW_COLOUR="#fff200";
this.SELECTED_GLOW_SIZE=.5;this.REPLACEMENT_GLOW_COLOUR="#fff200";this.REPLACEMENT_GLOW_SIZE=2;this.selectedGlowFilterId="";this.selectedGlowFilter=null;this.replacementGlowFilterId="";this.SQUARED=this.ROUNDED=this.HEXAGONAL=this.replacementGlowFilter=null;a&&(this.GRID_UNIT=a);this.SMALL_PADDING=this.GRID_UNIT;this.MEDIUM_PADDING=2*this.GRID_UNIT;this.MEDIUM_LARGE_PADDING=3*this.GRID_UNIT;this.LARGE_PADDING=4*this.GRID_UNIT;this.CORNER_RADIUS=1*this.GRID_UNIT;this.NOTCH_WIDTH=9*this.GRID_UNIT;this.NOTCH_HEIGHT=
2*this.GRID_UNIT;this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT=3*this.GRID_UNIT;this.MIN_BLOCK_WIDTH=2*this.GRID_UNIT;this.MIN_BLOCK_HEIGHT=12*this.GRID_UNIT;this.EMPTY_STATEMENT_INPUT_HEIGHT=6*this.GRID_UNIT;this.TOP_ROW_MIN_HEIGHT=this.CORNER_RADIUS;this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING;this.BOTTOM_ROW_MIN_HEIGHT=this.CORNER_RADIUS;this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=6*this.GRID_UNIT;this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT;this.STATEMENT_INPUT_SPACER_MIN_WIDTH=
40*this.GRID_UNIT;this.STATEMENT_INPUT_PADDING_LEFT=4*this.GRID_UNIT;this.EMPTY_INLINE_INPUT_PADDING=4*this.GRID_UNIT;this.EMPTY_INLINE_INPUT_HEIGHT=8*this.GRID_UNIT;this.DUMMY_INPUT_MIN_HEIGHT=8*this.GRID_UNIT;this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=6*this.GRID_UNIT;this.CURSOR_WS_WIDTH=20*this.GRID_UNIT;this.FIELD_TEXT_FONTSIZE=3*this.GRID_UNIT;this.FIELD_BORDER_RECT_RADIUS=this.CORNER_RADIUS;this.FIELD_BORDER_RECT_X_PADDING=2*this.GRID_UNIT;this.FIELD_BORDER_RECT_Y_PADDING=1.625*this.GRID_UNIT;this.FIELD_BORDER_RECT_HEIGHT=
8*this.GRID_UNIT;this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=8*this.GRID_UNIT;this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING;this.FIELD_COLOUR_DEFAULT_WIDTH=6*this.GRID_UNIT;this.FIELD_COLOUR_DEFAULT_HEIGHT=8*this.GRID_UNIT;this.FIELD_CHECKBOX_X_OFFSET=1*this.GRID_UNIT;this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH=12*this.GRID_UNIT}setFontConstants_(a){super.setFontConstants_(a);this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT=this.FIELD_TEXT_HEIGHT+this.FIELD_BORDER_RECT_Y_PADDING*
2}init(){super.init();this.HEXAGONAL=this.makeHexagonal();this.ROUNDED=this.makeRounded();this.SQUARED=this.makeSquared();this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT+this.INSIDE_CORNERS.rightWidth}setDynamicProperties_(a){super.setDynamicProperties_(a);this.SELECTED_GLOW_COLOUR=a.getComponentStyle("selectedGlowColour")||this.SELECTED_GLOW_COLOUR;const b=Number(a.getComponentStyle("selectedGlowSize"));this.SELECTED_GLOW_SIZE=b&&!isNaN(b)?b:this.SELECTED_GLOW_SIZE;this.REPLACEMENT_GLOW_COLOUR=
a.getComponentStyle("replacementGlowColour")||this.REPLACEMENT_GLOW_COLOUR;this.REPLACEMENT_GLOW_SIZE=(a=Number(a.getComponentStyle("replacementGlowSize")))&&!isNaN(a)?a:this.REPLACEMENT_GLOW_SIZE}dispose(){super.dispose();this.selectedGlowFilter&&removeNode$$module$build$src$core$utils$dom(this.selectedGlowFilter);this.replacementGlowFilter&&removeNode$$module$build$src$core$utils$dom(this.replacementGlowFilter)}makeStartHat(){const a=this.START_HAT_HEIGHT,b=this.START_HAT_WIDTH,c=curve$$module$build$src$core$utils$svg_paths("c",
[point$$module$build$src$core$utils$svg_paths(25,-a),point$$module$build$src$core$utils$svg_paths(71,-a),point$$module$build$src$core$utils$svg_paths(b,0)]);return{height:a*.75,width:b,path:c}}makeHexagonal(){function a(c,d,e){var f=c/2;f=f>b?b:f;e=e?-1:1;c=(d?-1:1)*c/2;return lineTo$$module$build$src$core$utils$svg_paths(-e*f,c)+lineTo$$module$build$src$core$utils$svg_paths(e*f,c)}const b=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH;return{type:this.SHAPES.HEXAGONAL,isDynamic:!0,width(c){c/=2;return c>
b?b:c},height(c){return c},connectionOffsetY(c){return c/2},connectionOffsetX(c){return-c},pathDown(c){return a(c,!1,!1)},pathUp(c){return a(c,!0,!1)},pathRightDown(c){return a(c,!1,!0)},pathRightUp(c){return a(c,!1,!0)}}}makeRounded(){function a(d,e,f){const g=d>c?d-c:0;d=(d>c?c:d)/2;const h=f===e?"0":"1";return arc$$module$build$src$core$utils$svg_paths("a","0 0,"+h,d,point$$module$build$src$core$utils$svg_paths((f?1:-1)*d,(e?-1:1)*d))+lineOnAxis$$module$build$src$core$utils$svg_paths("v",(e?-1:
1)*g)+arc$$module$build$src$core$utils$svg_paths("a","0 0,"+h,d,point$$module$build$src$core$utils$svg_paths((f?-1:1)*d,(e?-1:1)*d))}const b=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,c=b*2;return{type:this.SHAPES.ROUND,isDynamic:!0,width(d){d/=2;return d>b?b:d},height(d){return d},connectionOffsetY(d){return d/2},connectionOffsetX(d){return-d},pathDown(d){return a(d,!1,!1)},pathUp(d){return a(d,!0,!1)},pathRightDown(d){return a(d,!1,!0)},pathRightUp(d){return a(d,!1,!0)}}}makeSquared(){function a(c,
d,e){c-=b*2;const f=e===d?"0":"1";return arc$$module$build$src$core$utils$svg_paths("a","0 0,"+f,b,point$$module$build$src$core$utils$svg_paths((e?1:-1)*b,(d?-1:1)*b))+lineOnAxis$$module$build$src$core$utils$svg_paths("v",(d?-1:1)*c)+arc$$module$build$src$core$utils$svg_paths("a","0 0,"+f,b,point$$module$build$src$core$utils$svg_paths((e?-1:1)*b,(d?-1:1)*b))}const b=this.CORNER_RADIUS;return{type:this.SHAPES.SQUARE,isDynamic:!0,width(c){return b},height(c){return c},connectionOffsetY(c){return c/
2},connectionOffsetX(c){return-c},pathDown(c){return a(c,!1,!1)},pathUp(c){return a(c,!0,!1)},pathRightDown(c){return a(c,!1,!0)},pathRightUp(c){return a(c,!1,!0)}}}shapeFor(a){let b=a.getCheck();!b&&a.targetConnection&&(b=a.targetConnection.getCheck());switch(a.type){case ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE:case ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE:a=a.getSourceBlock().getOutputShape();if(a!==null)switch(a){case this.SHAPES.HEXAGONAL:return this.HEXAGONAL;
case this.SHAPES.ROUND:return this.ROUNDED;case this.SHAPES.SQUARE:return this.SQUARED}if(b&&b.includes("Boolean"))return this.HEXAGONAL;if(b&&b.includes("Number"))return this.ROUNDED;b&&b.includes("String");return this.ROUNDED;case ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT:case ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type");}}makeNotch(){function a(l){return curve$$module$build$src$core$utils$svg_paths("c",
[point$$module$build$src$core$utils$svg_paths(l*e/2,0),point$$module$build$src$core$utils$svg_paths(l*e*3/4,g/2),point$$module$build$src$core$utils$svg_paths(l*e,g)])+line$$module$build$src$core$utils$svg_paths([point$$module$build$src$core$utils$svg_paths(l*e,f)])+curve$$module$build$src$core$utils$svg_paths("c",[point$$module$build$src$core$utils$svg_paths(l*e/4,g/2),point$$module$build$src$core$utils$svg_paths(l*e/2,g),point$$module$build$src$core$utils$svg_paths(l*e,g)])+lineOnAxis$$module$build$src$core$utils$svg_paths("h",
l*d)+curve$$module$build$src$core$utils$svg_paths("c",[point$$module$build$src$core$utils$svg_paths(l*e/2,0),point$$module$build$src$core$utils$svg_paths(l*e*3/4,-(g/2)),point$$module$build$src$core$utils$svg_paths(l*e,-g)])+line$$module$build$src$core$utils$svg_paths([point$$module$build$src$core$utils$svg_paths(l*e,-f)])+curve$$module$build$src$core$utils$svg_paths("c",[point$$module$build$src$core$utils$svg_paths(l*e/4,-(g/2)),point$$module$build$src$core$utils$svg_paths(l*e/2,-g),point$$module$build$src$core$utils$svg_paths(l*
e,-g)])}const b=this.NOTCH_WIDTH,c=this.NOTCH_HEIGHT,d=b/3,e=d/3,f=c/2,g=f/2,h=a(1),k=a(-1);return{type:this.SHAPES.NOTCH,width:b,height:c,pathLeft:h,pathRight:k}}makeInsideCorners(){const a=this.CORNER_RADIUS,b=arc$$module$build$src$core$utils$svg_paths("a","0 0,0",a,point$$module$build$src$core$utils$svg_paths(-a,a)),c=arc$$module$build$src$core$utils$svg_paths("a","0 0,1",a,point$$module$build$src$core$utils$svg_paths(-a,a)),d=arc$$module$build$src$core$utils$svg_paths("a","0 0,0",a,point$$module$build$src$core$utils$svg_paths(a,
a)),e=arc$$module$build$src$core$utils$svg_paths("a","0 0,1",a,point$$module$build$src$core$utils$svg_paths(a,a));return{width:a,height:a,pathTop:b,pathBottom:d,rightWidth:a,rightHeight:a,pathTopRight:c,pathBottomRight:e}}generateSecondaryColour_(a){return blend$$module$build$src$core$utils$colour("#000",a,.15)||a}generateTertiaryColour_(a){return blend$$module$build$src$core$utils$colour("#000",a,.25)||a}createDom(a,b,c,d){super.createDom(a,b,c,d);a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.DEFS,
{},a);b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FILTER,{id:"blocklySelectedGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},a);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FEGAUSSIANBLUR,{"in":"SourceGraphic",stdDeviation:this.SELECTED_GLOW_SIZE},b);c=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FECOMPONENTTRANSFER,{result:"outBlur"},b);
createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},c);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FEFLOOD,{"flood-color":this.SELECTED_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},b);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FECOMPOSITE,{"in":"outColor",in2:"outBlur",operator:"in",result:"outGlow"},b);
this.selectedGlowFilterId=b.id;this.selectedGlowFilter=b;a=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FILTER,{id:"blocklyReplacementGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},a);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FEGAUSSIANBLUR,{"in":"SourceGraphic",stdDeviation:this.REPLACEMENT_GLOW_SIZE},a);b=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FECOMPONENTTRANSFER,
{result:"outBlur"},a);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},b);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FEFLOOD,{"flood-color":this.REPLACEMENT_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},a);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FECOMPOSITE,{"in":"outColor",in2:"outBlur",operator:"in",
result:"outGlow"},a);createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.FECOMPOSITE,{"in":"SourceGraphic",in2:"outGlow",operator:"over"},a);this.replacementGlowFilterId=a.id;this.replacementGlowFilter=a;d&&(d.style.setProperty("--blocklySelectedGlowFilter",`url(#${this.selectedGlowFilterId})`),d.style.setProperty("--blocklyReplacementGlowFilter",`url(#${this.replacementGlowFilterId})`))}getCSS_(a){return[`${a} .blocklyText,`,`${a} .blocklyFlyoutLabelText {`,`font: ${this.FIELD_TEXT_FONTWEIGHT} ${this.FIELD_TEXT_FONTSIZE}`+
`pt ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${a} .blocklyTextInputBubble textarea {`,"font-weight: normal;","}",`${a} .blocklyText {`,"fill: #fff;","}",`${a} .blocklyNonEditableField>rect:not(.blocklyDropdownRect),`,`${a} .blocklyEditableField>rect:not(.blocklyDropdownRect) {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"}",`${a} .blocklyNonEditableField>text,`,`${a} .blocklyEditableField>text,`,`${a} .blocklyNonEditableField>g>text,`,`${a} .blocklyEditableField>g>text {`,"fill: #575E75;","}",`${a} .blocklyFlyoutLabelText {`,
"fill: #575E75;","}",`${a} .blocklyText.blocklyBubbleText {`,"fill: #575E75;","}",`${a} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableField:not(.blocklyEditing):hover>rect,",`${a} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableField:not(.blocklyEditing):hover>.blocklyPath {","stroke: #fff;","stroke-width: 2;","}",`${a} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"color: #575E75;","}",`${a} .blocklyDropdownText {`,
"fill: #fff !important;","}",`${a}.blocklyWidgetDiv .blocklyMenuItem,`,`${a}.blocklyDropDownDiv .blocklyMenuItem {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${a}.blocklyDropDownDiv .blocklyMenuItemContent {`,"color: #fff;","}",`${a} .blocklyHighlightedConnectionPath {`,`stroke: ${this.SELECTED_GLOW_COLOUR};`,"}",`${a} .blocklyDisabledPattern > .blocklyOutlinePath {`,"fill: var(--blocklyDisabledPattern)","}",`${a} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,
"stroke: none;","}",`${a} .blocklySelected>.blocklyPath.blocklyPathSelected {`,"fill: none;","filter: var(--blocklySelectedGlowFilter);","}",`${a} .blocklyReplaceable>.blocklyPath {`,"filter: var(--blocklyReplacementGlowFilter);","}"]}},module$build$src$core$renderers$zelos$constants={};module$build$src$core$renderers$zelos$constants.ConstantProvider=ConstantProvider$$module$build$src$core$renderers$zelos$constants;var Drawer$$module$build$src$core$renderers$zelos$drawer=class extends Drawer$$module$build$src$core$renderers$common$drawer{constructor(a,b){super(a,b)}draw(){const a=this.block_.pathObject;a.beginDrawing();this.drawOutline_();this.drawInternals_();this.updateConnectionHighlights();a.setPath(this.outlinePath_+"\n"+this.inlinePath_);this.info_.RTL&&a.flipRTL();this.recordSizeOnBlock_();this.info_.outputConnection&&(a.outputShapeType=this.info_.outputConnection.shape.type);a.endDrawing()}drawOutline_(){this.info_.outputConnection&&
this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection?(this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_()):super.drawOutline_()}drawLeft_(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape?this.drawLeftDynamicConnection_():super.drawLeft_()}drawRightSideRow_(a){if(!(a.height<=0)){if(Types$$module$build$src$core$renderers$measurables$types.isSpacer(a)){const d=
a.precedesStatement;var b=a.followsStatement;if(d||b){const e=this.constants_.INSIDE_CORNERS;var c=e.rightHeight;c=a.height-(d?c:0);b=b?e.pathBottomRight:"";a=c>0?lineOnAxis$$module$build$src$core$utils$svg_paths("V",a.yPos+c):"";this.outlinePath_+=b+a+(d?e.pathTopRight:"");return}}this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("V",a.yPos+a.height)}}drawRightDynamicConnection_(){if(!this.info_.outputConnection)throw Error("Cannot draw the output connection of a block that doesn't have one");
this.outlinePath_+=this.info_.outputConnection.shape.pathRightDown(this.info_.outputConnection.height)}drawLeftDynamicConnection_(){if(!this.info_.outputConnection)throw Error("Cannot draw the output connection of a block that doesn't have one");this.positionOutputConnection_();this.outlinePath_+=this.info_.outputConnection.shape.pathUp(this.info_.outputConnection.height);this.outlinePath_+="z"}drawFlatTop_(){const a=this.info_.topRow;this.positionPreviousConnection_();this.outlinePath_+=moveBy$$module$build$src$core$utils$svg_paths(a.xPos,
this.info_.startY);this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("h",a.width)}drawFlatBottom_(){const a=this.info_.bottomRow;this.positionNextConnection_();this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("V",a.baseline);this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("h",-a.width)}drawInlineInput_(a){this.positionInlineInputConnection_(a);const b=a.input.name;a.connectedBlock||this.info_.isInsertionMarker||(a=moveTo$$module$build$src$core$utils$svg_paths(a.xPos+
a.connectionWidth,a.centerline-a.height/2)+this.getInlineInputPath(a),this.block_.pathObject.setOutlinePath(b,a))}getInlineInputPath(a){const b=a.width-a.connectionWidth*2,c=a.height;return lineOnAxis$$module$build$src$core$utils$svg_paths("h",b)+a.shape.pathRightDown(c)+lineOnAxis$$module$build$src$core$utils$svg_paths("h",-b)+a.shape.pathUp(c)+"z"}drawStatementInput_(a){var b=a.getLastInput();const c=b.xPos+b.notchOffset+b.shape.width,d=this.constants_.INSIDE_CORNERS,e=b.shape.pathRight+lineOnAxis$$module$build$src$core$utils$svg_paths("h",
-(b.notchOffset-d.width))+d.pathTop,f=a.height-2*d.height;b=d.pathBottom+lineOnAxis$$module$build$src$core$utils$svg_paths("h",b.notchOffset-d.width)+(b.connectedBottomNextConnection?"":b.shape.pathLeft);this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("H",c)+e+lineOnAxis$$module$build$src$core$utils$svg_paths("v",f)+b+lineOnAxis$$module$build$src$core$utils$svg_paths("H",a.xPos+a.width);this.positionStatementInputConnection_(a)}drawConnectionHighlightPath(a){const b=a.connectionModel;
if(b.type===ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT||b.type===ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT||b.type===ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE&&!a.isDynamicShape)return super.drawConnectionHighlightPath(a);a=b.type===ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE?moveTo$$module$build$src$core$utils$svg_paths(a.connectionWidth,-a.height/2)+this.getInlineInputPath(a):moveTo$$module$build$src$core$utils$svg_paths(a.width,
-a.height/2)+a.shape.pathDown(a.height);const c=b.getSourceBlock();let d,e;return(e=(d=c.pathObject).addConnectionHighlight)==null?void 0:e.call(d,b,a,b.getOffsetInBlock(),c.RTL)}},module$build$src$core$renderers$zelos$drawer={};module$build$src$core$renderers$zelos$drawer.Drawer=Drawer$$module$build$src$core$renderers$zelos$drawer;var FieldImage$$module$build$src$core$field_image=class extends Field$$module$build$src$core$field{constructor(a,b,c,d,e,f,g){super(Field$$module$build$src$core$field.SKIP_SETUP);this.imageElement=this.clickHandler=null;this.flipRtl=this.isDirty_=this.EDITABLE=!1;this.altText="";c=Number(replaceMessageReferences$$module$build$src$core$utils$parsing(c));b=Number(replaceMessageReferences$$module$build$src$core$utils$parsing(b));if(isNaN(c)||isNaN(b))throw Error("Height and width values of an image field must cast to numbers.");
if(c<=0||b<=0)throw Error("Height and width values of an image field must be greater than 0.");this.size_=new Size$$module$build$src$core$utils$size(b,c+FieldImage$$module$build$src$core$field_image.Y_PADDING);this.imageHeight=c;typeof e==="function"&&(this.clickHandler=e);a!==Field$$module$build$src$core$field.SKIP_SETUP&&(g?this.configure_(g):(this.flipRtl=!!f,this.altText=replaceMessageReferences$$module$build$src$core$utils$parsing(d)||""),this.setValue(replaceMessageReferences$$module$build$src$core$utils$parsing(a)))}configure_(a){super.configure_(a);
a.flipRtl&&(this.flipRtl=a.flipRtl);a.alt&&(this.altText=replaceMessageReferences$$module$build$src$core$utils$parsing(a.alt))}initView(){this.imageElement=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.IMAGE,{height:this.imageHeight+"px",width:this.size_.width+"px",alt:this.altText},this.fieldGroup_);this.imageElement.setAttributeNS(XLINK_NS$$module$build$src$core$utils$dom,"xlink:href",this.value_);this.fieldGroup_&&addClass$$module$build$src$core$utils$dom(this.fieldGroup_,
"blocklyImageField");this.clickHandler&&(this.imageElement.style.cursor="pointer")}updateSize_(){}doClassValidation_(a){return typeof a!=="string"?null:a}doValueUpdate_(a){this.value_=a;this.imageElement&&this.imageElement.setAttributeNS(XLINK_NS$$module$build$src$core$utils$dom,"xlink:href",this.value_)}getFlipRtl(){return this.flipRtl}setAlt(a){a!==this.altText&&(this.altText=a||"",this.imageElement&&this.imageElement.setAttribute("alt",this.altText))}isClickable(){return super.isClickable()&&!!this.clickHandler}showEditor_(){this.clickHandler&&
this.clickHandler(this)}setOnClickHandler(a){this.clickHandler=a}getText_(){return this.altText}static fromJson(a){if(!a.src||!a.width||!a.height)throw Error("src, width, and height values for an image field arerequired. The width and height must be non-zero.");return new this(a.src,a.width,a.height,void 0,void 0,void 0,a)}};FieldImage$$module$build$src$core$field_image.Y_PADDING=1;register$$module$build$src$core$field_registry("field_image",FieldImage$$module$build$src$core$field_image);
FieldImage$$module$build$src$core$field_image.prototype.DEFAULT_VALUE="";var module$build$src$core$field_image={};module$build$src$core$field_image.FieldImage=FieldImage$$module$build$src$core$field_image;var MINIMUM_WIDTH$$module$build$src$core$field_input=14,FieldInput$$module$build$src$core$field_input=class extends Field$$module$build$src$core$field{set size_(a){super.size_=a}get size_(){const a=super.size_;a.width<MINIMUM_WIDTH$$module$build$src$core$field_input&&(a.width=MINIMUM_WIDTH$$module$build$src$core$field_input);return a}constructor(a,b,c){super(Field$$module$build$src$core$field.SKIP_SETUP);this.spellcheck_=!0;this.htmlInput_=null;this.isTextValid_=this.isBeingEdited_=!1;this.onInputWrapper=
this.onKeyDownWrapper=this.valueWhenEditorWasOpened_=null;this.fullBlockClickTarget_=!1;this.workspace_=null;this.SERIALIZABLE=!0;a!==Field$$module$build$src$core$field.SKIP_SETUP&&(c&&this.configure_(c),this.setValue(a),b&&this.setValidator(b))}configure_(a){super.configure_(a);a.spellcheck!==void 0&&(this.spellcheck_=a.spellcheck)}initView(){if(!this.getSourceBlock())throw new UnattachedFieldError$$module$build$src$core$field;super.initView();this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot());
this.fieldGroup_&&addClass$$module$build$src$core$utils$dom(this.fieldGroup_,"blocklyInputField")}isFullBlockField(){const a=this.getSourceBlock();if(!a)throw new UnattachedFieldError$$module$build$src$core$field;let b;return this.fullBlockClickTarget_=!((b=this.getConstants())==null||!b.FULL_BLOCK_FIELDS)&&a.isSimpleReporter()}doValueInvalid_(a,b=!0){this.isBeingEdited_&&(this.isDirty_=!0,this.isTextValid_=!1,a=this.value_,this.value_=this.valueWhenEditorWasOpened_,this.sourceBlock_&&isEnabled$$module$build$src$core$events$utils()&&
this.value_!==a&&b&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CHANGE))(this.sourceBlock_,"field",this.name||null,a,this.value_)))}doValueUpdate_(a){this.isTextValid_=this.isDirty_=!0;this.value_=a}applyColour(){const a=this.getSourceBlock();if(!a)throw new UnattachedFieldError$$module$build$src$core$field;this.getConstants().FULL_BLOCK_FIELDS&&this.fieldGroup_&&(!this.isFullBlockField()&&this.borderRect_?
(this.borderRect_.style.display="block",this.borderRect_.setAttribute("stroke",a.getColourTertiary())):(this.borderRect_.style.display="none",a.pathObject.svgPath.setAttribute("fill",this.getConstants().FIELD_BORDER_RECT_COLOUR)))}getSize(){let a;if((a=this.getConstants())==null?0:a.FULL_BLOCK_FIELDS)this.render_(),this.isDirty_=!1;return super.getSize()}onLocationChange(){this.isBeingEdited_&&this.resizeEditor_()}render_(){super.render_();if(this.isBeingEdited_){var a=this.htmlInput_;this.isTextValid_?
(removeClass$$module$build$src$core$utils$dom(a,"blocklyInvalidInput"),setState$$module$build$src$core$utils$aria(a,State$$module$build$src$core$utils$aria.INVALID,!1)):(addClass$$module$build$src$core$utils$dom(a,"blocklyInvalidInput"),setState$$module$build$src$core$utils$aria(a,State$$module$build$src$core$utils$aria.INVALID,!0))}a=this.getSourceBlock();if(!a)throw new UnattachedFieldError$$module$build$src$core$field;this.getConstants().FULL_BLOCK_FIELDS&&a.applyColour()}setSpellcheck(a){a!==
this.spellcheck_&&(this.spellcheck_=a,this.htmlInput_&&this.htmlInput_.setAttribute("spellcheck",this.spellcheck_))}showEditor_(a,b=!1,c=!0){this.workspace_=this.sourceBlock_.workspace;!b&&this.workspace_.options.modalInputs&&(MOBILE$$module$build$src$core$utils$useragent||ANDROID$$module$build$src$core$utils$useragent||IPAD$$module$build$src$core$utils$useragent)?this.showPromptEditor():this.showInlineEditor(b,c)}showPromptEditor(){prompt$$module$build$src$core$dialog($.Msg$$module$build$src$core$msg.CHANGE_VALUE_TITLE,
this.getText(),a=>{a!==null&&this.setValue(this.getValueFromEditorText_(a));this.onFinishEditing_(this.value_)})}showInlineEditor(a,b){const c=this.getSourceBlock();if(!c)throw new UnattachedFieldError$$module$build$src$core$field;show$$module$build$src$core$widgetdiv(this,c.RTL,this.widgetDispose_.bind(this),this.workspace_,b);this.htmlInput_=this.widgetCreate_();this.isBeingEdited_=!0;this.valueWhenEditorWasOpened_=this.value_;a||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())}widgetCreate_(){var a=
this.getSourceBlock();if(!a)throw new UnattachedFieldError$$module$build$src$core$field;$.setGroup$$module$build$src$core$events$utils(!0);const b=getDiv$$module$build$src$core$widgetdiv();var c=this.getClickTarget_();if(!c)throw Error("A click target has not been set.");addClass$$module$build$src$core$utils$dom(c,"blocklyEditing");c=document.createElement("input");c.className="blocklyHtmlInput";c.setAttribute("spellcheck",this.spellcheck_);const d=this.workspace_.getAbsoluteScale();var e=this.getConstants().FIELD_TEXT_FONTSIZE*
d+"pt";b.style.fontSize=e;c.style.fontSize=e;e=FieldInput$$module$build$src$core$field_input.BORDERRADIUS*d+"px";this.isFullBlockField()&&(e=this.getScaledBBox(),e=(e.bottom-e.top)/2+"px",a=a.getParent()?a.getParent().getColourTertiary():this.sourceBlock_.getColourTertiary(),c.style.border=1*d+"px solid "+a,b.style.borderRadius=e,b.style.transition="box-shadow 0.25s ease 0s",this.getConstants().FIELD_TEXTINPUT_BOX_SHADOW&&(b.style.boxShadow="rgba(255, 255, 255, 0.3) 0 0 0 "+4*d+"px"));c.style.borderRadius=
e;b.appendChild(c);c.value=c.defaultValue=this.getEditorText_(this.value_);c.setAttribute("data-untyped-default-value",String(this.value_));this.resizeEditor_();this.bindInputEvents_(c);return c}widgetDispose_(){this.isBeingEdited_=!1;this.isTextValid_=!0;this.forceRerender();this.onFinishEditing_(this.value_);this.sourceBlock_&&isEnabled$$module$build$src$core$events$utils()&&this.valueWhenEditorWasOpened_!==null&&this.valueWhenEditorWasOpened_!==this.value_&&(fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_CHANGE))(this.sourceBlock_,
"field",this.name||null,this.valueWhenEditorWasOpened_,this.value_)),this.valueWhenEditorWasOpened_=null);$.setGroup$$module$build$src$core$events$utils(!1);this.unbindInputEvents_();var a=getDiv$$module$build$src$core$widgetdiv().style;a.width="auto";a.height="auto";a.fontSize="";a.transition="";a.boxShadow="";this.htmlInput_=null;a=this.getClickTarget_();if(!a)throw Error("A click target has not been set.");removeClass$$module$build$src$core$utils$dom(a,"blocklyEditing")}onFinishEditing_(a){}bindInputEvents_(a){this.onKeyDownWrapper=
conditionalBind$$module$build$src$core$browser_events(a,"keydown",this,this.onHtmlInputKeyDown_);this.onInputWrapper=conditionalBind$$module$build$src$core$browser_events(a,"input",this,this.onHtmlInputChange)}unbindInputEvents_(){this.onKeyDownWrapper&&(unbind$$module$build$src$core$browser_events(this.onKeyDownWrapper),this.onKeyDownWrapper=null);this.onInputWrapper&&(unbind$$module$build$src$core$browser_events(this.onInputWrapper),this.onInputWrapper=null)}onHtmlInputKeyDown_(a){if(a.key==="Enter")hideIfOwner$$module$build$src$core$widgetdiv(this),
hideWithoutAnimation$$module$build$src$core$dropdowndiv();else if(a.key==="Escape")this.setValue(this.htmlInput_.getAttribute("data-untyped-default-value"),!1),hideIfOwner$$module$build$src$core$widgetdiv(this),hideWithoutAnimation$$module$build$src$core$dropdowndiv();else if(a.key==="Tab"){a.preventDefault();var b,c=(b=this.workspace_)==null?void 0:b.getCursor();b=d=>(d instanceof FieldInput$$module$build$src$core$field_input||d instanceof BlockSvg$$module$build$src$core$block_svg&&d.isSimpleReporter())&&
d!==this.getSourceBlock();a=a.shiftKey?c==null?void 0:c.getPreviousNode(this,b,!1):c==null?void 0:c.getNextNode(this,b,!1);a=a instanceof BlockSvg$$module$build$src$core$block_svg&&a.isSimpleReporter()?a.getFields().next().value:a;a instanceof FieldInput$$module$build$src$core$field_input&&(hideIfOwner$$module$build$src$core$widgetdiv(this),hideWithoutAnimation$$module$build$src$core$dropdowndiv(),c=a.getSourceBlock(),a.isFullBlockField()&&c&&c instanceof BlockSvg$$module$build$src$core$block_svg?
$.getFocusManager$$module$build$src$core$focus_manager().focusNode(c):$.getFocusManager$$module$build$src$core$focus_manager().focusNode(a),a.showEditor())}}onHtmlInputChange(a){a=this.value_;this.setValue(this.getValueFromEditorText_(this.htmlInput_.value),!1);this.sourceBlock_&&isEnabled$$module$build$src$core$events$utils()&&this.value_!==a&&fire$$module$build$src$core$events$utils(new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.BLOCK_FIELD_INTERMEDIATE_CHANGE))(this.sourceBlock_,
this.name||null,a,this.value_))}setEditorValue_(a,b=!0){this.isDirty_=!0;this.isBeingEdited_&&(this.htmlInput_.value=this.getEditorText_(a));this.setValue(a,b)}resizeEditor_(){finishQueuedRenders$$module$build$src$core$render_management().then(()=>{const a=this.getSourceBlock();if(!a)throw new UnattachedFieldError$$module$build$src$core$field;const b=getDiv$$module$build$src$core$widgetdiv(),c=this.getScaledBBox();b.style.width=c.right-c.left+"px";b.style.height=c.bottom-c.top+"px";const d=c.top;
b.style.left=`${a.RTL?c.right-b.offsetWidth:c.left}px`;b.style.top=`${d}px`})}repositionForWindowResize(){let a;const b=(a=this.getSourceBlock())==null?void 0:a.getRootBlock();if(!(b instanceof BlockSvg$$module$build$src$core$block_svg))return!1;bumpObjectIntoBounds$$module$build$src$core$bump_objects(this.workspace_,this.workspace_.getMetricsManager().getViewMetrics(!0),b)||this.resizeEditor_();return!0}positionTextElement_(a,b){const c=a*2+b;super.positionTextElement_(a+(c<MINIMUM_WIDTH$$module$build$src$core$field_input?
(MINIMUM_WIDTH$$module$build$src$core$field_input-c)/2:0),b)}getText_(){return this.isBeingEdited_&&this.htmlInput_?this.htmlInput_.value:null}getEditorText_(a){return`${a}`}getValueFromEditorText_(a){return a}};FieldInput$$module$build$src$core$field_input.BORDERRADIUS=4;var module$build$src$core$field_input={};module$build$src$core$field_input.FieldInput=FieldInput$$module$build$src$core$field_input;$.FieldTextInput$$module$build$src$core$field_textinput=class extends FieldInput$$module$build$src$core$field_input{constructor(a,b,c){super(a,b,c)}initView(){super.initView();this.fieldGroup_&&addClass$$module$build$src$core$utils$dom(this.fieldGroup_,"blocklyTextInputField")}doClassValidation_(a){return a===void 0?null:`${a}`}static fromJson(a){return new this(replaceMessageReferences$$module$build$src$core$utils$parsing(a.text),void 0,a)}};
register$$module$build$src$core$field_registry("field_input",$.FieldTextInput$$module$build$src$core$field_textinput);$.FieldTextInput$$module$build$src$core$field_textinput.prototype.DEFAULT_VALUE="";var module$build$src$core$field_textinput={};module$build$src$core$field_textinput.FieldTextInput=$.FieldTextInput$$module$build$src$core$field_textinput;var BottomRow$$module$build$src$core$renderers$zelos$measurables$bottom_row=class extends BottomRow$$module$build$src$core$renderers$measurables$bottom_row{constructor(a){super(a)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(a){return!!a.outputConnection}hasRightSquareCorner(a){return!!a.outputConnection&&!a.statementInputCount&&!a.nextConnection}},module$build$src$core$renderers$zelos$measurables$bottom_row={};module$build$src$core$renderers$zelos$measurables$bottom_row.BottomRow=BottomRow$$module$build$src$core$renderers$zelos$measurables$bottom_row;var StatementInput$$module$build$src$core$renderers$zelos$measurables$inputs=class extends StatementInput$$module$build$src$core$renderers$measurables$statement_input{constructor(a,b){super(a,b);this.connectedBottomNextConnection=!1;if(this.connectedBlock){for(a=this.connectedBlock;b=a.getNextBlock();)a=b;a.nextConnection||(this.height=this.connectedBlockHeight,this.connectedBottomNextConnection=!0)}}},module$build$src$core$renderers$zelos$measurables$inputs={};
module$build$src$core$renderers$zelos$measurables$inputs.StatementInput=StatementInput$$module$build$src$core$renderers$zelos$measurables$inputs;var RightConnectionShape$$module$build$src$core$renderers$zelos$measurables$row_elements=class extends Measurable$$module$build$src$core$renderers$measurables$base{constructor(a){super(a);this.width=this.height=0;this.type|=Types$$module$build$src$core$renderers$measurables$types.getType("RIGHT_CONNECTION")}},module$build$src$core$renderers$zelos$measurables$row_elements={};module$build$src$core$renderers$zelos$measurables$row_elements.RightConnectionShape=RightConnectionShape$$module$build$src$core$renderers$zelos$measurables$row_elements;var TopRow$$module$build$src$core$renderers$zelos$measurables$top_row=class extends TopRow$$module$build$src$core$renderers$measurables$top_row{constructor(a){super(a)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(a){const b=(a.hat?a.hat==="cap":this.constants_.ADD_START_HATS)&&!a.outputConnection&&!a.previousConnection;return!!a.outputConnection||b}hasRightSquareCorner(a){return!!a.outputConnection&&!a.statementInputCount&&!a.nextConnection}},module$build$src$core$renderers$zelos$measurables$top_row=
{};module$build$src$core$renderers$zelos$measurables$top_row.TopRow=TopRow$$module$build$src$core$renderers$zelos$measurables$top_row;var RenderInfo$$module$build$src$core$renderers$zelos$info=class extends RenderInfo$$module$build$src$core$renderers$common$info{constructor(a,b){super(a,b);this.isInline=!0;this.renderer_=a;this.constants_=this.renderer_.getConstants();this.topRow=new TopRow$$module$build$src$core$renderers$zelos$measurables$top_row(this.constants_);this.bottomRow=new BottomRow$$module$build$src$core$renderers$zelos$measurables$bottom_row(this.constants_);this.isMultiRow=!b.getInputsInline()||b.isCollapsed();this.hasStatementInput=
b.statementInputCount>0;this.rightSide=this.outputConnection?new RightConnectionShape$$module$build$src$core$renderers$zelos$measurables$row_elements(this.constants_):null;this.rightAlignedDummyInputs=new WeakMap}getRenderer(){return this.renderer_}measure(){this.createRows_();this.addElemSpacing_();this.addRowSpacing_();this.adjustXPosition_();this.computeBounds_();this.alignRowElements_();this.finalize_()}shouldStartNewRow_(a,b){return b?b instanceof EndRowInput$$module$build$src$core$inputs$end_row_input||
a instanceof StatementInput$$module$build$src$core$inputs$statement_input||b instanceof StatementInput$$module$build$src$core$inputs$statement_input?!0:a instanceof $.ValueInput$$module$build$src$core$inputs$value_input||a instanceof DummyInput$$module$build$src$core$inputs$dummy_input||a instanceof EndRowInput$$module$build$src$core$inputs$end_row_input?!this.isInline||this.isMultiRow:!1:!1}getDesiredRowWidth_(a){return a.hasStatement?this.width-this.startX-(this.constants_.INSIDE_CORNERS.rightWidth||
0):super.getDesiredRowWidth_(a)}getInRowSpacing_(a,b){return a&&b||!this.outputConnection||!this.outputConnection.isDynamicShape||this.hasStatementInput||this.bottomRow.hasNextConnection?!a&&b&&Types$$module$build$src$core$renderers$measurables$types.isStatementInput(b)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:a&&Types$$module$build$src$core$renderers$measurables$types.isLeftRoundedCorner(a)&&b&&(Types$$module$build$src$core$renderers$measurables$types.isPreviousConnection(b)||Types$$module$build$src$core$renderers$measurables$types.isNextConnection(b))?
b.notchOffset-this.constants_.CORNER_RADIUS:a&&Types$$module$build$src$core$renderers$measurables$types.isLeftSquareCorner(a)&&b&&Types$$module$build$src$core$renderers$measurables$types.isHat(b)||a&&Types$$module$build$src$core$renderers$measurables$types.isField(a)&&a.width===0?this.constants_.NO_PADDING:this.constants_.MEDIUM_PADDING:this.constants_.NO_PADDING}getSpacerRowHeight_(a,b){if(Types$$module$build$src$core$renderers$measurables$types.isTopRow(a)&&Types$$module$build$src$core$renderers$measurables$types.isBottomRow(b))return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT;
const c=Types$$module$build$src$core$renderers$measurables$types.isInputRow(a)&&a.hasStatement,d=Types$$module$build$src$core$renderers$measurables$types.isInputRow(b)&&b.hasStatement;return d||c?(a=Math.max(this.constants_.NOTCH_HEIGHT,this.constants_.INSIDE_CORNERS.rightHeight||0),d&&c?Math.max(a,this.constants_.DUMMY_INPUT_MIN_HEIGHT):a):Types$$module$build$src$core$renderers$measurables$types.isTopRow(a)?a.hasPreviousConnection||this.outputConnection&&!this.hasStatementInput?this.constants_.NO_PADDING:
Math.abs(this.constants_.NOTCH_HEIGHT-this.constants_.CORNER_RADIUS):Types$$module$build$src$core$renderers$measurables$types.isBottomRow(b)?this.outputConnection?!b.hasNextConnection&&this.hasStatementInput?Math.abs(this.constants_.NOTCH_HEIGHT-this.constants_.CORNER_RADIUS):this.constants_.NO_PADDING:Math.max(this.topRow.minHeight,Math.max(this.constants_.NOTCH_HEIGHT,this.constants_.CORNER_RADIUS))-this.constants_.CORNER_RADIUS:this.constants_.MEDIUM_PADDING}getSpacerRowWidth_(a,b){const c=this.width-
this.startX;return Types$$module$build$src$core$renderers$measurables$types.isInputRow(a)&&a.hasStatement||Types$$module$build$src$core$renderers$measurables$types.isInputRow(b)&&b.hasStatement?Math.max(c,this.constants_.STATEMENT_INPUT_SPACER_MIN_WIDTH):c}getElemCenterline_(a,b){if(a.hasStatement&&!Types$$module$build$src$core$renderers$measurables$types.isSpacer(b)&&!Types$$module$build$src$core$renderers$measurables$types.isStatementInput(b))return a.yPos+this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT/
2;if(Types$$module$build$src$core$renderers$measurables$types.isInlineInput(b)){const c=b.connectedBlock;if(c&&c.outputConnection&&c.nextConnection)return a.yPos+c.height/2}return super.getElemCenterline_(a,b)}addInput_(a,b){if((a instanceof DummyInput$$module$build$src$core$inputs$dummy_input||a instanceof EndRowInput$$module$build$src$core$inputs$end_row_input)&&b.hasDummyInput&&b.align===$.Align$$module$build$src$core$inputs$align.LEFT&&a.align===$.Align$$module$build$src$core$inputs$align.RIGHT)this.rightAlignedDummyInputs.set(b,
a);else if(a instanceof StatementInput$$module$build$src$core$inputs$statement_input){b.elements.push(new StatementInput$$module$build$src$core$renderers$zelos$measurables$inputs(this.constants_,a));b.hasStatement=!0;b.align===null&&(b.align=a.align);return}super.addInput_(a,b)}addAlignmentPadding_(a,b){if(this.rightAlignedDummyInputs.get(a)){let c;for(let d=0;d<a.elements.length;d++){const e=a.elements[d];Types$$module$build$src$core$renderers$measurables$types.isSpacer(e)&&(c=e);if(Types$$module$build$src$core$renderers$measurables$types.isField(e)&&
e.parentInput===this.rightAlignedDummyInputs.get(a))break}if(c){c.width+=b;a.width+=b;return}}super.addAlignmentPadding_(a,b)}adjustXPosition_(){const a=this.constants_.NOTCH_OFFSET_LEFT+this.constants_.NOTCH_WIDTH;let b=a;for(let e=2;e<this.rows.length-1;e+=2){var c=this.rows[e-1];const f=this.rows[e];var d=this.rows[e+1];c=e===2?!!this.topRow.hasPreviousConnection:!!c.followsStatement;d=e+2>=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!d.precedesStatement;if(Types$$module$build$src$core$renderers$measurables$types.isInputRow(f)&&
f.hasStatement){f.measure();let g,h;b=f.width-((h=(g=f.getLastInput())==null?void 0:g.width)!=null?h:0)+a}else if(c&&(e===2||d)&&Types$$module$build$src$core$renderers$measurables$types.isInputRow(f)&&!f.hasStatement){d=f.xPos;c=null;for(let g=0;g<f.elements.length;g++){const h=f.elements[g];Types$$module$build$src$core$renderers$measurables$types.isSpacer(h)&&(c=h);!(c&&(Types$$module$build$src$core$renderers$measurables$types.isField(h)||Types$$module$build$src$core$renderers$measurables$types.isInput(h))&&
d<b)||Types$$module$build$src$core$renderers$measurables$types.isField(h)&&(h.field instanceof FieldLabel$$module$build$src$core$field_label||h.field instanceof FieldImage$$module$build$src$core$field_image)||(c.width+=b-d);d+=h.width}}}}finalizeOutputConnection_(){if(this.outputConnection&&this.outputConnection.isDynamicShape){var a=this.outputConnection.shape;if("isDynamic"in a&&a.isDynamic){var b=0;for(var c=0;c<this.rows.length;c++){const d=this.rows[c];d.yPos=b;b+=d.height}this.height=b;c=this.bottomRow.hasNextConnection?
this.height-this.bottomRow.descenderHeight:this.height;b=a.height(c);c=a.width(c);this.outputConnection.height=b;this.outputConnection.width=c;this.outputConnection.startX=c;this.outputConnection.connectionOffsetY=a.connectionOffsetY(b);this.outputConnection.connectionOffsetX=a.connectionOffsetX(c);a=0;this.hasStatementInput||this.bottomRow.hasNextConnection||(a=c,this.rightSide.height=b,this.rightSide.width=a,this.rightSide.centerline=b/2,this.rightSide.xPos=this.width+a);this.startX=c;this.width+=
c+a;this.widthWithChildren+=c+a}}}finalizeHorizontalAlignment_(){if(this.outputConnection&&!this.hasStatementInput&&!this.bottomRow.hasNextConnection){var a=0;for(var b=0;b<this.rows.length;b++){var c=this.rows[b];if(!Types$$module$build$src$core$renderers$measurables$types.isInputRow(c))continue;a=c.elements[c.elements.length-2];let d=this.getNegativeSpacing_(c.elements[1]),e=this.getNegativeSpacing_(a);a=d+e;const f=this.constants_.MIN_BLOCK_WIDTH+this.outputConnection.width*2;this.width-a<f&&(a=
this.width-f,d=a/2,e=a/2);c.elements.unshift(new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,-d));c.elements.push(new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,-e))}if(a)for(this.width-=a,this.widthWithChildren-=a,this.rightSide.xPos-=a,b=0;b<this.rows.length;b++)c=this.rows[b],Types$$module$build$src$core$renderers$measurables$types.isTopOrBottomRow(c)&&(c.elements[1].width-=a),c.width-=a,c.widthWithConnectedBlocks-=
a}}getNegativeSpacing_(a){if(!a||!this.outputConnection)return 0;const b=this.outputConnection.width;var c=this.outputConnection.shape.type;const d=this.constants_;if(this.inputRows.length>1)switch(c){case d.SHAPES.ROUND:return c=this.constants_.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,c=this.height/2>c?c:this.height/2,b-c*(1-Math.sin(Math.acos((c-this.constants_.SMALL_PADDING)/c)));default:return 0}if(Types$$module$build$src$core$renderers$measurables$types.isInlineInput(a)){const e=a.connectedBlock;a=
e?e.pathObject.outputShapeType:a.shape.type;return a==null||e&&e.outputConnection&&(e.statementInputCount||e.nextConnection)||c===d.SHAPES.HEXAGONAL&&c!==a?0:b-this.constants_.SHAPE_IN_SHAPE_PADDING[c][a]}return Types$$module$build$src$core$renderers$measurables$types.isField(a)?c===d.SHAPES.ROUND&&a.field instanceof $.FieldTextInput$$module$build$src$core$field_textinput?b-2.75*d.GRID_UNIT:b-this.constants_.SHAPE_IN_SHAPE_PADDING[c][0]:Types$$module$build$src$core$renderers$measurables$types.isIcon(a)?
this.constants_.SMALL_PADDING:0}finalizeVerticalAlignment_(){if(!this.outputConnection)for(let d=2;d<this.rows.length-1;d+=2){const e=this.rows[d-1],f=this.rows[d],g=this.rows[d+1];var a=d===2,b=d+2>=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!g.precedesStatement;if(a?this.topRow.hasPreviousConnection:e.followsStatement){var c=f.elements[1];c=f.elements.length===3&&c instanceof Field$$module$build$src$core$renderers$measurables$field&&(c.field instanceof FieldLabel$$module$build$src$core$field_label||
c.field instanceof FieldImage$$module$build$src$core$field_image);if(!a&&c)e.height-=this.constants_.SMALL_PADDING,g.height-=this.constants_.SMALL_PADDING,f.height-=this.constants_.MEDIUM_PADDING;else if(!a&&!b)e.height+=this.constants_.SMALL_PADDING;else if(b){a=!1;for(b=0;b<f.elements.length;b++)if(c=f.elements[b],Types$$module$build$src$core$renderers$measurables$types.isInlineInput(c)&&c.connectedBlock&&!c.connectedBlock.isShadow()&&c.connectedBlock.getHeightWidth().height>=40){a=!0;break}a&&
(e.height-=this.constants_.SMALL_PADDING,g.height-=this.constants_.SMALL_PADDING)}}}}finalize_(){this.finalizeOutputConnection_();this.finalizeHorizontalAlignment_();this.finalizeVerticalAlignment_();super.finalize_();this.rightSide&&(this.widthWithChildren+=this.rightSide.width)}},module$build$src$core$renderers$zelos$info={};module$build$src$core$renderers$zelos$info.RenderInfo=RenderInfo$$module$build$src$core$renderers$zelos$info;var PathObject$$module$build$src$core$renderers$zelos$path_object=class extends PathObject$$module$build$src$core$renderers$common$path_object{constructor(a,b,c){super(a,b,c);this.svgPathSelected=null;this.outlines=new Map;this.remainingOutlines=new Set;this.outputShapeType=null;this.constants=c}setPath(a){super.setPath(a);this.svgPathSelected&&this.svgPathSelected.setAttribute("d",a)}applyColour(a){super.applyColour(a);const b=a.getParent();a.isShadow()&&b&&this.svgPath.setAttribute("stroke",b.getColourTertiary());
for(const c of this.outlines.values())c.setAttribute("fill",this.style.colourTertiary)}flipRTL(){super.flipRTL();for(const a of this.outlines.values())a.setAttribute("transform","scale(-1 1)")}updateSelected(a){this.setClass_("blocklySelected",a);a?this.svgPathSelected||(this.svgPathSelected=this.svgPath.cloneNode(!0),this.svgPathSelected.classList.add("blocklyPathSelected"),removeClass$$module$build$src$core$utils$dom(this.svgPathSelected,FocusManager$$module$build$src$core$focus_manager.ACTIVE_FOCUS_NODE_CSS_CLASS_NAME),
removeClass$$module$build$src$core$utils$dom(this.svgPathSelected,FocusManager$$module$build$src$core$focus_manager.PASSIVE_FOCUS_NODE_CSS_CLASS_NAME),this.svgPathSelected.removeAttribute("tabindex"),this.svgPathSelected.removeAttribute("id"),this.svgRoot.appendChild(this.svgPathSelected)):this.svgPathSelected&&(this.svgRoot.removeChild(this.svgPathSelected),this.svgPathSelected=null)}updateReplacementFade(a){this.setClass_("blocklyReplaceable",a)}updateShapeForInputHighlight(a,b){a=a.getParentInput().name;
(a=this.getOutlinePath(a))&&(b?a.setAttribute("filter","url(#"+this.constants.replacementGlowFilterId+")"):a.removeAttribute("filter"))}beginDrawing(){this.remainingOutlines.clear();for(const a of this.outlines.keys())this.remainingOutlines.add(a)}endDrawing(){if(this.remainingOutlines.size)for(const a of this.remainingOutlines)this.removeOutlinePath(a);this.remainingOutlines.clear()}setOutlinePath(a,b){a=this.getOutlinePath(a);a.setAttribute("d",b);a.setAttribute("fill",this.style.colourTertiary)}getOutlinePath(a){this.outlines.has(a)||
this.outlines.set(a,createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,{"class":"blocklyOutlinePath",d:""},this.svgRoot));this.remainingOutlines.delete(a);return this.outlines.get(a)}removeOutlinePath(a){let b,c;(b=this.outlines.get(a))==null||(c=b.parentNode)==null||c.removeChild(this.outlines.get(a));this.outlines.delete(a)}},module$build$src$core$renderers$zelos$path_object={};module$build$src$core$renderers$zelos$path_object.PathObject=PathObject$$module$build$src$core$renderers$zelos$path_object;var Renderer$$module$build$src$core$renderers$zelos$renderer=class extends Renderer$$module$build$src$core$renderers$common$renderer{constructor(a){super(a)}makeConstants_(){return new ConstantProvider$$module$build$src$core$renderers$zelos$constants}makeRenderInfo_(a){return new RenderInfo$$module$build$src$core$renderers$zelos$info(this,a)}makeDrawer_(a,b){return new Drawer$$module$build$src$core$renderers$zelos$drawer(a,b)}makePathObject(a,b){return new PathObject$$module$build$src$core$renderers$zelos$path_object(a,
b,this.getConstants())}getConstants(){return this.constants_}};register$$module$build$src$core$renderers$common$block_rendering("zelos",Renderer$$module$build$src$core$renderers$zelos$renderer);var module$build$src$core$renderers$zelos$renderer={};module$build$src$core$renderers$zelos$renderer.Renderer=Renderer$$module$build$src$core$renderers$zelos$renderer;var InsertionMarkerPreviewer$$module$build$src$core$insertion_marker_previewer=class{constructor(a){this.staticConn=this.draggedConn=this.markerConn=this.fadedBlock=null;this.workspace=a.workspace}previewReplacement(a,b,c){$.disable$$module$build$src$core$events$utils();try{this.hidePreview(),this.fadedBlock=c,c.fadeForReplacement(!0),this.workspace.getRenderer().shouldHighlightConnection(b)&&(b.highlight(),this.staticConn=b)}finally{$.enable$$module$build$src$core$events$utils()}}previewConnection(a,
b){if(a!==this.draggedConn||b!==this.staticConn){$.disable$$module$build$src$core$events$utils();try{this.hidePreview(),this.shouldUseMarkerPreview(a,b)&&(this.markerConn=this.previewMarker(a,b)),this.workspace.getRenderer().shouldHighlightConnection(b)&&b.highlight(),this.draggedConn=a,this.staticConn=b}finally{$.enable$$module$build$src$core$events$utils()}}}shouldUseMarkerPreview(a,b){return b.type===ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT||b.type===ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT||
!(this.workspace.getRenderer()instanceof Renderer$$module$build$src$core$renderers$zelos$renderer)}previewMarker(a,b){const c=a.getSourceBlock(),d=this.createInsertionMarker(c),e=this.getMatchingConnection(c,d,a);if(!e)return null;d.queueRender();triggerQueuedRenders$$module$build$src$core$render_management();e.connect(b);const f={x:b.x-e.x,y:b.y-e.y},g=e.getOffsetInBlock().clone();finishQueuedRenders$$module$build$src$core$render_management().then(()=>{if(!d.isDeadOrDying()){$.disable$$module$build$src$core$events$utils();
try{d==null||d.positionNearConnection(e,f,g),d==null||d.getSvgRoot().setAttribute("visibility","visible")}finally{$.enable$$module$build$src$core$events$utils()}}});return e}serializeBlockToInsertionMarker(a){const b=save$$module$build$src$core$serialization$blocks(a,{addCoordinates:!1,addInputBlocks:!1,addNextBlocks:!1,doFullSerialization:!1});if(!b)throw Error(`Failed to serialize source block. ${a.toDevString()}`);return b}createInsertionMarker(a){a=this.serializeBlockToInsertionMarker(a);a=append$$module$build$src$core$serialization$blocks(a,
this.workspace);for(const b of a.getDescendants(!1))b.setInsertionMarker(!0);a.initSvg();a.getSvgRoot().setAttribute("visibility","hidden");return a}getMatchingConnection(a,b,c){a=a.getConnections_(!0);b=b.getConnections_(!0);if(a.length!==b.length)return null;for(let d=0;d<a.length;d++)if(a[d]===c)return b[d];return null}hidePreview(){$.disable$$module$build$src$core$events$utils();try{this.staticConn&&(this.staticConn.unhighlight(),this.staticConn=null),this.fadedBlock&&(this.fadedBlock.fadeForReplacement(!1),
this.fadedBlock=null),this.markerConn&&(this.hideInsertionMarker(this.markerConn),this.draggedConn=this.markerConn=null)}finally{$.enable$$module$build$src$core$events$utils()}}hideInsertionMarker(a){const b=a.getSourceBlock(),c=b.outputConnection;let d;if(((d=b.previousConnection)==null?0:d.targetConnection)||(c==null?0:c.targetConnection))b.unplug(!0);else{let e;(e=a.targetBlock())==null||e.unplug(!1)}b.dispose()}dispose(){this.hidePreview()}};
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.CONNECTION_PREVIEWER,DEFAULT$$module$build$src$core$registry,InsertionMarkerPreviewer$$module$build$src$core$insertion_marker_previewer);var module$build$src$core$insertion_marker_previewer={};module$build$src$core$insertion_marker_previewer.InsertionMarkerPreviewer=InsertionMarkerPreviewer$$module$build$src$core$insertion_marker_previewer;var module$build$src$core$inputs={};module$build$src$core$inputs.Align=$.Align$$module$build$src$core$inputs$align;module$build$src$core$inputs.DummyInput=DummyInput$$module$build$src$core$inputs$dummy_input;module$build$src$core$inputs.EndRowInput=EndRowInput$$module$build$src$core$inputs$end_row_input;module$build$src$core$inputs.Input=Input$$module$build$src$core$inputs$input;module$build$src$core$inputs.StatementInput=StatementInput$$module$build$src$core$inputs$statement_input;
module$build$src$core$inputs.ValueInput=$.ValueInput$$module$build$src$core$inputs$value_input;module$build$src$core$inputs.inputTypes=$.inputTypes$$module$build$src$core$inputs$input_types;var documentEventsBound$$module$build$src$core$inject=!1,module$build$src$core$inject={};module$build$src$core$inject.inject=inject$$module$build$src$core$inject;var module$build$src$core$generator;
$.CodeGenerator$$module$build$src$core$generator=class{constructor(a){this.forBlock=Object.create(null);this.FUNCTION_NAME_PLACEHOLDER_="{leCUI8hutHZI4480Dc}";this.STATEMENT_SUFFIX=this.STATEMENT_PREFIX=this.INFINITE_LOOP_TRAP=null;this.INDENT="  ";this.COMMENT_WRAP=60;this.ORDER_OVERRIDES=[];this.isInitialized=null;this.RESERVED_WORDS_="";this.definitions_=Object.create(null);this.functionNames_=Object.create(null);this.nameDB_=void 0;this.name_=a;this.FUNCTION_NAME_PLACEHOLDER_REGEXP_=new RegExp(this.FUNCTION_NAME_PLACEHOLDER_,
"g")}workspaceToCode(a){a||(console.warn("No workspace specified in workspaceToCode call.  Guessing."),a=getMainWorkspace$$module$build$src$core$common());var b=[];this.init(a);a=a.getTopBlocks(!0);for(let c=0,d;d=a[c];c++){let e=this.blockToCode(d);Array.isArray(e)&&(e=e[0]);e&&(d.outputConnection&&(e=this.scrubNakedValue(e),this.STATEMENT_PREFIX&&!d.suppressPrefixSuffix&&(e=this.injectId(this.STATEMENT_PREFIX,d)+e),this.STATEMENT_SUFFIX&&!d.suppressPrefixSuffix&&(e+=this.injectId(this.STATEMENT_SUFFIX,
d))),b.push(e))}b=b.join("\n");b=this.finish(b);b=b.replace(/^\s+\n/,"");b=b.replace(/\n\s+$/,"\n");return b=b.replace(/[ \t]+\n/g,"\n")}prefixLines(a,b){return b+a.replace(/(?!\n$)\n/g,"\n"+b)}allNestedComments(a){const b=[];a=a.getDescendants(!0);for(let c=0;c<a.length;c++){const d=a[c].getCommentText();d&&b.push(d)}b.length&&b.push("");return b.join("\n")}blockToCode(a,b){this.isInitialized===!1&&console.warn("CodeGenerator init was not called before blockToCode was called.");if(!a)return"";if(!a.isEnabled())return b?
"":this.blockToCode(a.getNextBlock());if(a.isInsertionMarker())return b?"":this.blockToCode(a.getChildren(!1)[0]);var c=this.forBlock[a.type];if(typeof c!=="function")throw Error(`${this.name_} generator does not know how to generate code `+`for block type "${a.type}".`);c=c.call(a,a,this);if(Array.isArray(c)){if(!a.outputConnection)throw TypeError("Expecting string from statement block: "+a.type);return[this.scrub_(a,c[0],b),c[1]]}if(typeof c==="string")return this.STATEMENT_PREFIX&&!a.suppressPrefixSuffix&&
(c=this.injectId(this.STATEMENT_PREFIX,a)+c),this.STATEMENT_SUFFIX&&!a.suppressPrefixSuffix&&(c+=this.injectId(this.STATEMENT_SUFFIX,a)),this.scrub_(a,c,b);if(c===null)return"";throw SyntaxError("Invalid code generated: "+c);}valueToCode(a,b,c){if(isNaN(c))throw TypeError("Expecting valid order from block: "+a.type);var d=a.getInputTargetBlock(b);if(!d&&!a.getInput(b))throw ReferenceError(`Input "${b}" doesn't exist on "${a.type}"`);if(!d)return"";b=this.blockToCode(d);if(b==="")return"";if(!Array.isArray(b))throw TypeError(`Expecting tuple from value block: ${d.type} See `+
"developers.google.com/blockly/guides/create-custom-blocks/generating-code for more information");a=b[0];b=b[1];if(isNaN(b))throw TypeError("Expecting valid order from value block: "+d.type);if(!a)return"";d=!1;var e=Math.floor(c);const f=Math.floor(b);if(e<=f&&(e!==f||e!==0&&e!==99))for(d=!0,e=0;e<this.ORDER_OVERRIDES.length;e++)if(this.ORDER_OVERRIDES[e][0]===c&&this.ORDER_OVERRIDES[e][1]===b){d=!1;break}d&&(a="("+a+")");return a}statementToCode(a,b){const c=a.getInputTargetBlock(b);if(!c&&!a.getInput(b))throw ReferenceError(`Input "${b}" doesn't exist on "${a.type}"`);
a=this.blockToCode(c);if(typeof a!=="string")throw TypeError("Expecting code from statement block: "+(c&&c.type));a&&(a=this.prefixLines(a,this.INDENT));return a}addLoopTrap(a,b){this.INFINITE_LOOP_TRAP&&(a=this.prefixLines(this.injectId(this.INFINITE_LOOP_TRAP,b),this.INDENT)+a);this.STATEMENT_SUFFIX&&!b.suppressPrefixSuffix&&(a=this.prefixLines(this.injectId(this.STATEMENT_SUFFIX,b),this.INDENT)+a);this.STATEMENT_PREFIX&&!b.suppressPrefixSuffix&&(a+=this.prefixLines(this.injectId(this.STATEMENT_PREFIX,
b),this.INDENT));return a}injectId(a,b){b=b.id.replace(/\$/g,"$$$$");return a.replace(/%1/g,"'"+b+"'")}addReservedWords(a){this.RESERVED_WORDS_+=a+","}provideFunction_(a,b){if(!this.definitions_[a]){const c=this.nameDB_.getDistinctName(a,$.NameType$$module$build$src$core$names.PROCEDURE);this.functionNames_[a]=c;Array.isArray(b)&&(b=b.join("\n"));b=b.trim().replace(this.FUNCTION_NAME_PLACEHOLDER_REGEXP_,c);let d;for(;d!==b;)d=b,b=b.replace(/^(( {2})*) {2}/gm,"$1\x00");b=b.replace(/\0/g,this.INDENT);
this.definitions_[a]=b}return this.functionNames_[a]}getVariableName(a){return this.getName(a,$.NameType$$module$build$src$core$names.VARIABLE)}getProcedureName(a){return this.getName(a,$.NameType$$module$build$src$core$names.PROCEDURE)}getName(a,b){if(!this.nameDB_)throw Error("Name database is not defined. You must initialize `nameDB_` in your generator class and call `init` first.");return this.nameDB_.getName(a,b)}init(a){this.definitions_=Object.create(null);this.functionNames_=Object.create(null)}scrub_(a,
b,c){return b}finish(a){this.definitions_=Object.create(null);this.functionNames_=Object.create(null);return a}scrubNakedValue(a){return a}};module$build$src$core$generator={};module$build$src$core$generator.CodeGenerator=$.CodeGenerator$$module$build$src$core$generator;var VerticalFlyout$$module$build$src$core$flyout_vertical=class extends Flyout$$module$build$src$core$flyout_base{constructor(a){super(a)}setMetrics_(a){if(this.isVisible()){var b=this.workspace_.getMetricsManager(),c=b.getScrollMetrics(),d=b.getViewMetrics();b=b.getAbsoluteMetrics();typeof a.y==="number"&&(this.workspace_.scrollY=-(c.top+(c.height-d.height)*a.y));this.workspace_.translate(this.workspace_.scrollX+b.left,this.workspace_.scrollY+b.top)}}getX(){if(!this.isVisible())return 0;var a=this.targetWorkspace.getMetricsManager();
const b=a.getAbsoluteMetrics(),c=a.getViewMetrics();a=a.getToolboxMetrics();return this.targetWorkspace.toolboxPosition===this.toolboxPosition_?this.targetWorkspace.getToolbox()?this.toolboxPosition_===Position$$module$build$src$core$utils$toolbox.LEFT?a.width:c.width-this.getWidth():this.toolboxPosition_===Position$$module$build$src$core$utils$toolbox.LEFT?0:c.width:this.toolboxPosition_===Position$$module$build$src$core$utils$toolbox.LEFT?0:c.width+b.left-this.getWidth()}getY(){return 0}position(){if(this.isVisible()&&
this.targetWorkspace.isVisible()){var a=this.targetWorkspace.getMetricsManager().getViewMetrics();this.height_=a.height;var b=this.getWidth()-this.CORNER_RADIUS;this.setBackgroundPath(b,a.height-2*this.CORNER_RADIUS);a=this.getX();b=this.getY();this.positionAt_(this.getWidth(),this.getHeight(),a,b)}}setBackgroundPath(a,b){const c=this.toolboxPosition_===Position$$module$build$src$core$utils$toolbox.RIGHT;var d=a+this.CORNER_RADIUS;d=["M "+(c?d:0)+",0"];d.push("h",c?-a:a);d.push("a",this.CORNER_RADIUS,
this.CORNER_RADIUS,0,0,c?0:1,c?-this.CORNER_RADIUS:this.CORNER_RADIUS,this.CORNER_RADIUS);d.push("v",Math.max(0,b));d.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,c?0:1,c?this.CORNER_RADIUS:-this.CORNER_RADIUS,this.CORNER_RADIUS);d.push("h",c?a:-a);d.push("z");this.svgBackground_.setAttribute("d",d.join(" "))}scrollToStart(){let a;(a=this.workspace_.scrollbar)==null||a.setY(0)}wheel_(a){var b=getScrollDeltaPixels$$module$build$src$core$browser_events(a);if(b.y){const c=this.workspace_.getMetricsManager(),
d=c.getScrollMetrics();b=c.getViewMetrics().top-d.top+b.y;let e;(e=this.workspace_.scrollbar)==null||e.setY(b);hideIfOwnerIsInWorkspace$$module$build$src$core$widgetdiv(this.workspace_);hideWithoutAnimation$$module$build$src$core$dropdowndiv()}a.preventDefault();a.stopPropagation()}layout_(a){this.workspace_.scale=this.targetWorkspace.scale;var b=this.MARGIN;const c=this.RTL?b:b+this.tabWidth_;for(const d of a)d.getElement().moveBy(c,b),b+=d.getElement().getBoundingRectangle().getHeight()}isDragTowardWorkspace(a){a=
Math.atan2(a.y,a.x)/Math.PI*180;const b=this.dragAngleRange_;return a<b&&a>-b||a<-180+b||a>180-b?!0:!1}getClientRect(){if(!this.svgGroup_||this.autoClose||!this.isVisible())return null;const a=this.svgGroup_.getBoundingClientRect(),b=a.left;return this.toolboxPosition_===Position$$module$build$src$core$utils$toolbox.LEFT?new Rect$$module$build$src$core$utils$rect(-1E9,1E9,-1E9,b+a.width):new Rect$$module$build$src$core$utils$rect(-1E9,1E9,b,1E9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();
let a=this.getContents().reduce((b,c)=>Math.max(b,c.getElement().getBoundingRectangle().getWidth()),0);a+=this.MARGIN*1.5+this.tabWidth_;a*=this.workspace_.scale;a+=Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness;if(this.getWidth()!==a){if(this.RTL)for(const b of this.getContents()){const c=b.getElement().getBoundingRectangle().left,d=a/this.workspace_.scale-b.getElement().getBoundingRectangle().getWidth()-this.MARGIN-this.tabWidth_;b.getElement().moveBy(d-c,0)}this.targetWorkspace.scrollbar||
this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Position$$module$build$src$core$utils$toolbox.LEFT||this.targetWorkspace.translate(this.targetWorkspace.scrollX+a,this.targetWorkspace.scrollY);this.width_=a;this.position();this.targetWorkspace.resizeContents();this.targetWorkspace.recordDragTargets()}}};VerticalFlyout$$module$build$src$core$flyout_vertical.registryName="verticalFlyout";
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUTS_VERTICAL_TOOLBOX,DEFAULT$$module$build$src$core$registry,VerticalFlyout$$module$build$src$core$flyout_vertical);var module$build$src$core$flyout_vertical={};module$build$src$core$flyout_vertical.VerticalFlyout=VerticalFlyout$$module$build$src$core$flyout_vertical;var HorizontalFlyout$$module$build$src$core$flyout_horizontal=class extends Flyout$$module$build$src$core$flyout_base{constructor(a){super(a);this.horizontalLayout=!0}setMetrics_(a){if(this.isVisible()){var b=this.workspace_.getMetricsManager(),c=b.getScrollMetrics(),d=b.getViewMetrics();b=b.getAbsoluteMetrics();typeof a.x==="number"&&(this.workspace_.scrollX=-(c.left+(c.width-d.width)*a.x));this.workspace_.translate(this.workspace_.scrollX+b.left,this.workspace_.scrollY+b.top)}}getX(){return 0}getY(){if(!this.isVisible())return 0;
var a=this.targetWorkspace.getMetricsManager();const b=a.getAbsoluteMetrics(),c=a.getViewMetrics();a=a.getToolboxMetrics();const d=this.toolboxPosition_===Position$$module$build$src$core$utils$toolbox.TOP;return this.targetWorkspace.toolboxPosition===this.toolboxPosition_?this.targetWorkspace.getToolbox()?d?a.height:c.height-this.getHeight():d?0:c.height:d?0:c.height+b.top-this.getHeight()}position(){if(this.isVisible()&&this.targetWorkspace.isVisible()){var a=this.targetWorkspace.getMetricsManager().getViewMetrics();
this.width_=a.width;a=a.width-2*this.CORNER_RADIUS;var b=this.getHeight()-this.CORNER_RADIUS;this.setBackgroundPath(a,b);a=this.getX();b=this.getY();this.positionAt_(this.getWidth(),this.getHeight(),a,b)}}setBackgroundPath(a,b){const c=this.toolboxPosition_===Position$$module$build$src$core$utils$toolbox.TOP,d=["M 0,"+(c?0:this.CORNER_RADIUS)];c?(d.push("h",a+2*this.CORNER_RADIUS),d.push("v",b),d.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,this.CORNER_RADIUS),d.push("h",
-a),d.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,-this.CORNER_RADIUS)):(d.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,-this.CORNER_RADIUS),d.push("h",a),d.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,this.CORNER_RADIUS),d.push("v",b),d.push("h",-a-2*this.CORNER_RADIUS));d.push("z");this.svgBackground_.setAttribute("d",d.join(" "))}scrollToStart(){let a;(a=this.workspace_.scrollbar)==null||a.setX(this.RTL?Infinity:
0)}wheel_(a){var b=getScrollDeltaPixels$$module$build$src$core$browser_events(a);if(b=b.x||b.y){const c=this.workspace_.getMetricsManager(),d=c.getScrollMetrics();b=c.getViewMetrics().left-d.left+b;let e;(e=this.workspace_.scrollbar)==null||e.setX(b);hideIfOwnerIsInWorkspace$$module$build$src$core$widgetdiv(this.workspace_);hideWithoutAnimation$$module$build$src$core$dropdowndiv()}a.preventDefault();a.stopPropagation()}layout_(a){this.workspace_.scale=this.targetWorkspace.scale;const b=this.MARGIN;
let c=b+this.tabWidth_;this.RTL&&(a=a.reverse());for(const d of a)a=d.getElement().getBoundingRectangle(),a=this.RTL?c+a.getWidth():c,d.getElement().moveBy(a,b),c+=d.getElement().getBoundingRectangle().getWidth()}isDragTowardWorkspace(a){a=Math.atan2(a.y,a.x)/Math.PI*180;const b=this.dragAngleRange_;return a<90+b&&a>90-b||a>-90-b&&a<-90+b?!0:!1}getClientRect(){if(!this.svgGroup_||this.autoClose||!this.isVisible())return null;const a=this.svgGroup_.getBoundingClientRect(),b=a.top;return this.toolboxPosition_===
Position$$module$build$src$core$utils$toolbox.TOP?new Rect$$module$build$src$core$utils$rect(-1E9,b+a.height,-1E9,1E9):new Rect$$module$build$src$core$utils$rect(b,1E9,-1E9,1E9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let a=this.getContents().reduce((b,c)=>Math.max(b,c.getElement().getBoundingRectangle().getHeight()),0);a+=this.MARGIN*1.5;a*=this.workspace_.scale;a+=Scrollbar$$module$build$src$core$scrollbar.scrollbarThickness;this.getHeight()!==a&&(this.targetWorkspace.scrollbar||
this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Position$$module$build$src$core$utils$toolbox.TOP||this.targetWorkspace.translate(this.targetWorkspace.scrollX,this.targetWorkspace.scrollY+a),this.height_=a,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets())}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUTS_HORIZONTAL_TOOLBOX,DEFAULT$$module$build$src$core$registry,HorizontalFlyout$$module$build$src$core$flyout_horizontal);
var module$build$src$core$flyout_horizontal={};module$build$src$core$flyout_horizontal.HorizontalFlyout=HorizontalFlyout$$module$build$src$core$flyout_horizontal;var FieldVariable$$module$build$src$core$field_variable=class extends FieldDropdown$$module$build$src$core$field_dropdown{constructor(a,b,c,d,e){super(Field$$module$build$src$core$field.SKIP_SETUP);this.defaultType="";this.variableTypes=[];this.variable=null;this.SERIALIZABLE=!0;this.menuGenerator_=FieldVariable$$module$build$src$core$field_variable.dropdownCreate;this.defaultVariableName=typeof a==="string"?a:"";this.size_=new Size$$module$build$src$core$utils$size(0,0);a!==Field$$module$build$src$core$field.SKIP_SETUP&&
(e?this.configure_(e):this.setTypes(c,d),b&&this.setValidator(b))}configure_(a){super.configure_(a);this.setTypes(a.variableTypes,a.defaultType)}initModel(){var a=this.getSourceBlock();if(!a)throw new UnattachedFieldError$$module$build$src$core$field;this.variable||(a=$.getOrCreateVariablePackage$$module$build$src$core$variables(a.workspace,null,this.defaultVariableName,this.defaultType),this.doValueUpdate_(a.getId()))}initView(){super.initView();addClass$$module$build$src$core$utils$dom(this.fieldGroup_,
"blocklyVariableField")}shouldAddBorderRect_(){const a=this.getSourceBlock();if(!a)throw new UnattachedFieldError$$module$build$src$core$field;return super.shouldAddBorderRect_()&&(!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW||a.type!=="variables_get")}fromXml(a){var b=this.getSourceBlock();if(!b)throw new UnattachedFieldError$$module$build$src$core$field;const c=a.getAttribute("id"),d=a.textContent,e=a.getAttribute("variabletype")||a.getAttribute("variableType")||"";b=$.getOrCreateVariablePackage$$module$build$src$core$variables(b.workspace,
c,d,e);if(e!==null&&e!==b.getType())throw Error("Serialized variable type with id '"+b.getId()+"' had type "+b.getType()+", and does not match variable field that references it: "+domToText$$module$build$src$core$xml(a)+".");this.setValue(b.getId())}toXml(a){this.initModel();a.id=this.variable.getId();a.textContent=this.variable.getName();this.variable.getType()&&a.setAttribute("variabletype",this.variable.getType());return a}saveState(a){var b=this.saveLegacyState(FieldVariable$$module$build$src$core$field_variable);
if(b!==null)return b;this.initModel();b={id:this.variable.getId()};a&&(b.name=this.variable.getName(),b.type=this.variable.getType());return b}loadState(a){const b=this.getSourceBlock();if(!b)throw new UnattachedFieldError$$module$build$src$core$field;this.loadLegacyState(FieldVariable$$module$build$src$core$field_variable,a)||(a=$.getOrCreateVariablePackage$$module$build$src$core$variables(b.workspace,a.id||null,a.name,a.type||""),this.setValue(a.getId()))}setSourceBlock(a){if(a.isShadow())throw Error("Variable fields are not allowed to exist on shadow blocks.");
super.setSourceBlock(a)}getValue(){return this.variable?this.variable.getId():null}getText(){return this.variable?this.variable.getName():""}getVariable(){return this.variable}getDefaultType(){return this.defaultType}getValidator(){return this.variable?this.validator_:null}doClassValidation_(a){if(a===null)return null;var b=this.getSourceBlock();if(!b)throw new UnattachedFieldError$$module$build$src$core$field;b=$.getVariable$$module$build$src$core$variables(b.workspace,a);if(!b)return console.warn("Variable id doesn't point to a real variable! ID was "+
a),null;b=b.getType();return this.typeIsAllowed(b)?a:(console.warn("Variable type doesn't match this field!  Type was "+b),null)}doValueUpdate_(a){const b=this.getSourceBlock();if(!b)throw new UnattachedFieldError$$module$build$src$core$field;this.variable=$.getVariable$$module$build$src$core$variables(b.workspace,a);super.doValueUpdate_(a)}typeIsAllowed(a){const b=this.getVariableTypes();if(!b)return!0;for(let c=0;c<b.length;c++)if(a===b[c])return!0;return!1}getVariableTypes(){if(this.variableTypes)return this.variableTypes;
if(!this.sourceBlock_||this.sourceBlock_.isDeadOrDying())return[""];let a=this.sourceBlock_.workspace.getVariableMap().getTypes();if(this.sourceBlock_.isInFlyout){const b=this.sourceBlock_.workspace.getPotentialVariableMap();if(!b)return a;a=Array.from(new Set([...a,...b.getTypes()]))}return a}setTypes(a=null,b=""){var c=this.getText();if(Array.isArray(a)){if(a.length===0)throw Error(`'variableTypes' of field variable ${c} was an empty list. If you want to include all variable types, pass 'null' instead.`);
c=!1;for(let d=0;d<a.length;d++)a[d]===b&&(c=!0);if(!c)throw Error("Invalid default type '"+b+"' in the definition of a FieldVariable");}else if(a!==null)throw Error(`'variableTypes' was not an array or null in the definition of FieldVariable ${c}`);this.defaultType=b;this.variableTypes=a}refreshVariableName(){this.forceRerender()}onItemSelected_(a,b){a=b.getValue();if(this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()){if(a===RENAME_VARIABLE_ID$$module$build$src$core$internal_constants&&this.variable){$.renameVariable$$module$build$src$core$variables(this.sourceBlock_.workspace,
this.variable);return}if(a===DELETE_VARIABLE_ID$$module$build$src$core$internal_constants&&this.variable){a=this.variable.getWorkspace();$.deleteVariable$$module$build$src$core$variables(a,this.variable,this.sourceBlock_);return}}this.setValue(a)}referencesVariables(){return!0}static fromJson(a){return new this(replaceMessageReferences$$module$build$src$core$utils$parsing(a.variable),void 0,void 0,void 0,a)}static dropdownCreate(){if(!this.variable)throw Error("Tried to call dropdownCreate on a variable field with no variable selected.");
const a=this.getText();let b=[];var c=this.getSourceBlock();if(c&&!c.isDeadOrDying()){c=c.workspace;const f=this.getVariableTypes();for(let g=0;g<f.length;g++){const h=f[g],k=c.getVariableMap().getVariablesOfType(h);b=b.concat(k);if(c.isFlyout){var d=void 0,e=void 0;b=b.concat((e=(d=c.getPotentialVariableMap())==null?void 0:d.getVariablesOfType(h))!=null?e:[])}}}b.sort(compareByName$$module$build$src$core$variables);d=[];for(e=0;e<b.length;e++)d[e]=[b[e].getName(),b[e].getId()];d.push([$.Msg$$module$build$src$core$msg.RENAME_VARIABLE,
RENAME_VARIABLE_ID$$module$build$src$core$internal_constants]);$.Msg$$module$build$src$core$msg.DELETE_VARIABLE&&d.push([$.Msg$$module$build$src$core$msg.DELETE_VARIABLE.replace("%1",a),DELETE_VARIABLE_ID$$module$build$src$core$internal_constants]);return d}};register$$module$build$src$core$field_registry("field_variable",FieldVariable$$module$build$src$core$field_variable);var module$build$src$core$field_variable={};module$build$src$core$field_variable.FieldVariable=FieldVariable$$module$build$src$core$field_variable;var FieldNumber$$module$build$src$core$field_number=class extends FieldInput$$module$build$src$core$field_input{constructor(a,b,c,d,e,f){super(Field$$module$build$src$core$field.SKIP_SETUP);this.min_=-Infinity;this.max_=Infinity;this.precision_=0;this.decimalPlaces=null;this.spellcheck_=!1;a!==Field$$module$build$src$core$field.SKIP_SETUP&&(f?this.configure_(f):this.setConstraints(b,c,d),this.setValue(a),e&&this.setValidator(e))}configure_(a){super.configure_(a);this.setMinInternal(a.min);this.setMaxInternal(a.max);
this.setPrecisionInternal(a.precision)}setConstraints(a,b,c){this.setMinInternal(a);this.setMaxInternal(b);this.setPrecisionInternal(c);this.setValue(this.getValue())}setMin(a){this.setMinInternal(a);this.setValue(this.getValue())}setMinInternal(a){a==null?this.min_=-Infinity:(a=Number(a),isNaN(a)||(this.min_=a))}getMin(){return this.min_}setMax(a){this.setMaxInternal(a);this.setValue(this.getValue())}setMaxInternal(a){a==null?this.max_=Infinity:(a=Number(a),isNaN(a)||(this.max_=a))}getMax(){return this.max_}setPrecision(a){this.setPrecisionInternal(a);
this.setValue(this.getValue())}setPrecisionInternal(a){this.precision_=Number(a)||0;let b=String(this.precision_);b.includes("e")&&(b=this.precision_.toLocaleString("en-US",{maximumFractionDigits:20}));const c=b.indexOf(".");this.decimalPlaces=c===-1?a?0:null:b.length-c-1}getPrecision(){return this.precision_}doClassValidation_(a){if(a===null)return null;a=`${a}`.replace(/O/gi,"0");a=a.replace(/,/g,"");a=a.replace(/infinity/i,"Infinity");a=Number(a||0);if(isNaN(a))return null;a=Math.min(Math.max(a,
this.min_),this.max_);this.precision_&&isFinite(a)&&(a=Math.round(a/this.precision_)*this.precision_);this.decimalPlaces!==null&&(a=Number(a.toFixed(this.decimalPlaces)));return a}widgetCreate_(){const a=super.widgetCreate_();this.min_>-Infinity&&(a.min=`${this.min_}`,setState$$module$build$src$core$utils$aria(a,State$$module$build$src$core$utils$aria.VALUEMIN,this.min_));this.max_<Infinity&&(a.max=`${this.max_}`,setState$$module$build$src$core$utils$aria(a,State$$module$build$src$core$utils$aria.VALUEMAX,
this.max_));return a}initView(){super.initView();this.fieldGroup_&&addClass$$module$build$src$core$utils$dom(this.fieldGroup_,"blocklyNumberField")}static fromJson(a){return new this(a.value,void 0,void 0,void 0,void 0,a)}};register$$module$build$src$core$field_registry("field_number",FieldNumber$$module$build$src$core$field_number);FieldNumber$$module$build$src$core$field_number.prototype.DEFAULT_VALUE=0;var module$build$src$core$field_number={};module$build$src$core$field_number.FieldNumber=FieldNumber$$module$build$src$core$field_number;var FieldLabelSerializable$$module$build$src$core$field_label_serializable=class extends FieldLabel$$module$build$src$core$field_label{constructor(a,b,c){super(String(a!=null?a:""),b,c);this.EDITABLE=!1;this.SERIALIZABLE=!0}static fromJson(a){return new this(replaceMessageReferences$$module$build$src$core$utils$parsing(a.text),void 0,a)}};register$$module$build$src$core$field_registry("field_label_serializable",FieldLabelSerializable$$module$build$src$core$field_label_serializable);
var module$build$src$core$field_label_serializable={};module$build$src$core$field_label_serializable.FieldLabelSerializable=FieldLabelSerializable$$module$build$src$core$field_label_serializable;var FieldCheckbox$$module$build$src$core$field_checkbox=class extends Field$$module$build$src$core$field{constructor(a,b,c){super(Field$$module$build$src$core$field.SKIP_SETUP);this.SERIALIZABLE=!0;this.value_=this.value_;this.checkChar=FieldCheckbox$$module$build$src$core$field_checkbox.CHECK_CHAR;a!==Field$$module$build$src$core$field.SKIP_SETUP&&(c&&this.configure_(c),this.setValue(a),b&&this.setValidator(b))}configure_(a){super.configure_(a);a.checkCharacter&&(this.checkChar=a.checkCharacter)}saveState(){const a=
this.saveLegacyState(FieldCheckbox$$module$build$src$core$field_checkbox);return a!==null?a:this.getValueBoolean()}initView(){super.initView();const a=this.getTextElement();addClass$$module$build$src$core$utils$dom(this.fieldGroup_,"blocklyCheckboxField");a.style.display=this.value_?"block":"none"}render_(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_());this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET)}getDisplayText_(){return this.checkChar}setCheckCharacter(a){this.checkChar=
a||FieldCheckbox$$module$build$src$core$field_checkbox.CHECK_CHAR;this.forceRerender()}showEditor_(){this.setValue(!this.value_)}doClassValidation_(a){return a===!0||a==="TRUE"?"TRUE":a===!1||a==="FALSE"?"FALSE":null}doValueUpdate_(a){this.value_=this.convertValueToBool(a);this.textElement_&&(this.textElement_.style.display=this.value_?"block":"none")}getValue(){return this.value_?"TRUE":"FALSE"}getValueBoolean(){return this.value_}getText(){return String(this.convertValueToBool(this.value_))}convertValueToBool(a){return typeof a===
"string"?a==="TRUE":!!a}static fromJson(a){return new this(a.checked,void 0,a)}};FieldCheckbox$$module$build$src$core$field_checkbox.CHECK_CHAR="\u2713";register$$module$build$src$core$field_registry("field_checkbox",FieldCheckbox$$module$build$src$core$field_checkbox);FieldCheckbox$$module$build$src$core$field_checkbox.prototype.DEFAULT_VALUE=!1;var module$build$src$core$field_checkbox={};module$build$src$core$field_checkbox.FieldCheckbox=FieldCheckbox$$module$build$src$core$field_checkbox;var Dragger$$module$build$src$core$dragging$dragger=class{constructor(a,b){this.draggable=a;this.workspace=b;this.dragTarget=null;this.startLoc=a.getRelativeToSurfaceXY()}onDragStart(a){$.getGroup$$module$build$src$core$events$utils()||$.setGroup$$module$build$src$core$events$utils(!0);this.draggable.startDrag(a)}onDrag(a,b){this.moveDraggable(a,b);b=this.getRoot(this.draggable);isDeletable$$module$build$src$core$interfaces$i_deletable(b)&&b.setDeleteStyle(this.wouldDeleteDraggable(a,b));this.updateDragTarget(a)}updateDragTarget(a){a=
this.workspace.getDragTarget(a);const b=this.getRoot(this.draggable);if(this.dragTarget!==a){let c;(c=this.dragTarget)==null||c.onDragExit(b);a==null||a.onDragEnter(b)}a==null||a.onDragOver(b);this.dragTarget=a}moveDraggable(a,b){b=this.pixelsToWorkspaceUnits(b);b=Coordinate$$module$build$src$core$utils$coordinate.sum(this.startLoc,b);this.draggable.drag(b,a)}wouldDeleteDraggable(a,b){return(a=this.workspace.getDragTarget(a))&&this.workspace.getComponentManager().hasCapability(a.id,ComponentManager$$module$build$src$core$component_manager.Capability.DELETE_AREA)?
a.wouldDelete(b):!1}onDragEnd(a){const b=$.getGroup$$module$build$src$core$events$utils();var c=this.workspace.getDragTarget(a);const d=this.getRoot(this.draggable);if(c){let e;(e=this.dragTarget)==null||e.onDrop(d)}this.shouldReturnToStart(a,d)&&this.draggable.revertDrag();(c=isDeletable$$module$build$src$core$interfaces$i_deletable(d)&&this.wouldDeleteDraggable(a,d))&&this.draggable instanceof BlockSvg$$module$build$src$core$block_svg&&disposeUiEffect$$module$build$src$core$block_animations(this.draggable.getRootBlock());
this.draggable.endDrag(a);c&&isDeletable$$module$build$src$core$interfaces$i_deletable(d)&&($.setGroup$$module$build$src$core$events$utils(b),d.dispose());$.setGroup$$module$build$src$core$events$utils(!1);!c&&isFocusableNode$$module$build$src$core$interfaces$i_focusable_node(this.draggable)&&$.getFocusManager$$module$build$src$core$focus_manager().focusNode(this.draggable)}getRoot(a){return a instanceof BlockSvg$$module$build$src$core$block_svg?a.getRootBlock():a}shouldReturnToStart(a,b){return(a=
this.workspace.getDragTarget(a))?a.shouldPreventMove(b):!1}pixelsToWorkspaceUnits(a){a=new Coordinate$$module$build$src$core$utils$coordinate(a.x/this.workspace.scale,a.y/this.workspace.scale);this.workspace.isMutator&&a.scale(1/this.workspace.options.parentWorkspace.scale);return a}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.BLOCK_DRAGGER,DEFAULT$$module$build$src$core$registry,Dragger$$module$build$src$core$dragging$dragger);
var module$build$src$core$dragging$dragger={};module$build$src$core$dragging$dragger.Dragger=Dragger$$module$build$src$core$dragging$dragger;var module$build$src$core$dragging={};module$build$src$core$dragging.BlockDragStrategy=BlockDragStrategy$$module$build$src$core$dragging$block_drag_strategy;module$build$src$core$dragging.BubbleDragStrategy=BubbleDragStrategy$$module$build$src$core$dragging$bubble_drag_strategy;module$build$src$core$dragging.CommentDragStrategy=CommentDragStrategy$$module$build$src$core$dragging$comment_drag_strategy;module$build$src$core$dragging.Dragger=Dragger$$module$build$src$core$dragging$dragger;var BlockDrag$$module$build$src$core$events$events_block_drag=class extends UiBase$$module$build$src$core$events$events_ui_base{constructor(a,b,c){super(a?a.workspace.id:void 0);this.type=EventType$$module$build$src$core$events$type.BLOCK_DRAG;a&&(this.blockId=a.id,this.isStart=b,this.blocks=c)}toJson(){const a=super.toJson();if(this.isStart===void 0)throw Error("Whether this event is the start of a drag is undefined. Either pass the value to the constructor, or call fromJson");if(this.blockId===
void 0)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");a.isStart=this.isStart;a.blockId=this.blockId;a.blocks=this.blocks;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new BlockDrag$$module$build$src$core$events$events_block_drag);b.isStart=a.isStart;b.blockId=a.blockId;b.blocks=a.blocks;return b}};
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.BLOCK_DRAG,BlockDrag$$module$build$src$core$events$events_block_drag);var module$build$src$core$events$events_block_drag={};module$build$src$core$events$events_block_drag.BlockDrag=BlockDrag$$module$build$src$core$events$events_block_drag;var BlockFieldIntermediateChange$$module$build$src$core$events$events_block_field_intermediate_change=class extends BlockBase$$module$build$src$core$events$events_block_base{constructor(a,b,c,d){super(a);this.type=EventType$$module$build$src$core$events$type.BLOCK_FIELD_INTERMEDIATE_CHANGE;this.recordUndo=!1;a&&(this.name=b,this.oldValue=c,this.newValue=d)}toJson(){const a=super.toJson();if(!this.name)throw Error("The changed field name is undefined. Either pass a name to the constructor, or call fromJson.");
a.name=this.name;a.oldValue=this.oldValue;a.newValue=this.newValue;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new BlockFieldIntermediateChange$$module$build$src$core$events$events_block_field_intermediate_change);b.name=a.name;b.oldValue=a.oldValue;b.newValue=a.newValue;return b}isNull(){return this.oldValue===this.newValue}run(a){var b=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");
b=b.getBlockById(this.blockId);if(!b)throw Error("The associated block is undefined. Either pass a block to the constructor, or call fromJson");a=a?this.newValue:this.oldValue;(b=b.getField(this.name))?b.setValue(a):console.warn("Can't set non-existent field: "+this.name)}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.BLOCK_FIELD_INTERMEDIATE_CHANGE,BlockFieldIntermediateChange$$module$build$src$core$events$events_block_field_intermediate_change);
var module$build$src$core$events$events_block_field_intermediate_change={};module$build$src$core$events$events_block_field_intermediate_change.BlockFieldIntermediateChange=BlockFieldIntermediateChange$$module$build$src$core$events$events_block_field_intermediate_change;var BlockMove$$module$build$src$core$events$events_block_move=class extends BlockBase$$module$build$src$core$events$events_block_base{constructor(a){super(a);this.type=EventType$$module$build$src$core$events$type.BLOCK_MOVE;a&&(a.isShadow()&&(this.recordUndo=!1),a=this.currentLocation(),this.oldParentId=a.parentId,this.oldInputName=a.inputName,this.oldCoordinate=a.coordinate)}toJson(){const a=super.toJson();a.oldParentId=this.oldParentId;a.oldInputName=this.oldInputName;this.oldCoordinate&&(a.oldCoordinate=
`${Math.round(this.oldCoordinate.x)}, `+`${Math.round(this.oldCoordinate.y)}`);a.newParentId=this.newParentId;a.newInputName=this.newInputName;this.newCoordinate&&(a.newCoordinate=`${Math.round(this.newCoordinate.x)}, `+`${Math.round(this.newCoordinate.y)}`);this.reason&&(a.reason=this.reason);this.recordUndo||(a.recordUndo=this.recordUndo);return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new BlockMove$$module$build$src$core$events$events_block_move);b.oldParentId=a.oldParentId;b.oldInputName=
a.oldInputName;a.oldCoordinate&&(c=a.oldCoordinate.split(","),b.oldCoordinate=new Coordinate$$module$build$src$core$utils$coordinate(Number(c[0]),Number(c[1])));b.newParentId=a.newParentId;b.newInputName=a.newInputName;a.newCoordinate&&(c=a.newCoordinate.split(","),b.newCoordinate=new Coordinate$$module$build$src$core$utils$coordinate(Number(c[0]),Number(c[1])));a.reason!==void 0&&(b.reason=a.reason);a.recordUndo!==void 0&&(b.recordUndo=a.recordUndo);return b}recordNew(){const a=this.currentLocation();
this.newParentId=a.parentId;this.newInputName=a.inputName;this.newCoordinate=a.coordinate}setReason(a){this.reason=a}currentLocation(){var a=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");var b=a.getBlockById(this.blockId);if(!b)throw Error("The block associated with the block move event could not be found");a={};const c=b.getParent();if(c){if(a.parentId=c.id,b=c.getInputWithBlock(b))a.inputName=b.name}else a.coordinate=
b.getRelativeToSurfaceXY();return a}isNull(){return this.oldParentId===this.newParentId&&this.oldInputName===this.newInputName&&Coordinate$$module$build$src$core$utils$coordinate.equals(this.oldCoordinate,this.newCoordinate)}run(a){var b=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");var c=b.getBlockById(this.blockId);if(c){var d=a?this.newParentId:this.oldParentId,e=a?this.newInputName:this.oldInputName;
a=a?this.newCoordinate:this.oldCoordinate;if(d){var f=b.getBlockById(d);if(!f){console.warn("Can't connect to non-existent block: "+d);return}}c.getParent()&&c.unplug();if(a)e=c.getRelativeToSurfaceXY(),c.moveBy(a.x-e.x,a.y-e.y,this.reason);else{b=c.outputConnection;if(!b||c.previousConnection&&c.previousConnection.isConnected())b=c.previousConnection;let g,h;c=(h=b)==null?void 0:h.type;if(e){if(c=f.getInput(e))g=c.connection}else c===ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT&&
(g=f.nextConnection);g&&b?b.connect(g):console.warn("Can't connect to non-existent input: "+e)}}else console.warn("Can't move non-existent block: "+this.blockId)}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.BLOCK_MOVE,BlockMove$$module$build$src$core$events$events_block_move);var module$build$src$core$events$events_block_move={};module$build$src$core$events$events_block_move.BlockMove=BlockMove$$module$build$src$core$events$events_block_move;var BubbleOpen$$module$build$src$core$events$events_bubble_open=class extends UiBase$$module$build$src$core$events$events_ui_base{constructor(a,b,c){super(a?a.workspace.id:void 0);this.type=EventType$$module$build$src$core$events$type.BUBBLE_OPEN;a&&(this.blockId=a.id,this.isOpen=b,this.bubbleType=c)}toJson(){const a=super.toJson();if(this.isOpen===void 0)throw Error("Whether this event is for opening the bubble is undefined. Either pass the value to the constructor, or call fromJson");if(!this.bubbleType)throw Error("The type of bubble is undefined. Either pass the value to the constructor, or call fromJson");
a.isOpen=this.isOpen;a.bubbleType=this.bubbleType;a.blockId=this.blockId||"";return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new BubbleOpen$$module$build$src$core$events$events_bubble_open);b.isOpen=a.isOpen;b.bubbleType=a.bubbleType;b.blockId=a.blockId;return b}},BubbleType$$module$build$src$core$events$events_bubble_open;
(function(a){a.MUTATOR="mutator";a.COMMENT="comment";a.WARNING="warning"})(BubbleType$$module$build$src$core$events$events_bubble_open||(BubbleType$$module$build$src$core$events$events_bubble_open={}));register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.BUBBLE_OPEN,BubbleOpen$$module$build$src$core$events$events_bubble_open);var module$build$src$core$events$events_bubble_open={};
module$build$src$core$events$events_bubble_open.BubbleOpen=BubbleOpen$$module$build$src$core$events$events_bubble_open;module$build$src$core$events$events_bubble_open.BubbleType=BubbleType$$module$build$src$core$events$events_bubble_open;var CommentBase$$module$build$src$core$events$events_comment_base=class extends Abstract$$module$build$src$core$events$events_abstract{constructor(a){super();this.isBlank=!a;a&&(this.commentId=a.id,this.workspaceId=a.workspace.id,this.group=$.getGroup$$module$build$src$core$events$utils(),this.recordUndo=getRecordUndo$$module$build$src$core$events$utils())}toJson(){const a=super.toJson();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");
a.commentId=this.commentId;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new CommentBase$$module$build$src$core$events$events_comment_base);b.commentId=a.commentId;return b}static CommentCreateDeleteHelper(a,b){const c=a.getEventWorkspace_();if(b){if(!a.json)throw Error("Encountered a comment event without proper json");append$$module$build$src$core$serialization$workspace_comments(a.json,c)}else{if(!a.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");
(b=c.getCommentById(a.commentId))?b.dispose():console.warn("Can't delete non-existent comment: "+a.commentId)}}},module$build$src$core$events$events_comment_base={};module$build$src$core$events$events_comment_base.CommentBase=CommentBase$$module$build$src$core$events$events_comment_base;var CommentChange$$module$build$src$core$events$events_comment_change=class extends CommentBase$$module$build$src$core$events$events_comment_base{constructor(a,b,c){super(a);this.type=EventType$$module$build$src$core$events$type.COMMENT_CHANGE;a&&(this.oldContents_=typeof b==="undefined"?"":b,this.newContents_=typeof c==="undefined"?"":c)}toJson(){const a=super.toJson();if(!this.oldContents_)throw Error("The old contents is undefined. Either pass a value to the constructor, or call fromJson");if(!this.newContents_)throw Error("The new contents is undefined. Either pass a value to the constructor, or call fromJson");
a.oldContents=this.oldContents_;a.newContents=this.newContents_;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new CommentChange$$module$build$src$core$events$events_comment_change);b.oldContents_=a.oldContents;b.newContents_=a.newContents;return b}isNull(){return this.oldContents_===this.newContents_}run(a){var b=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(b=b.getCommentById(this.commentId)){var c=
a?this.newContents_:this.oldContents_;if(c===void 0){if(a)throw Error("The new contents is undefined. Either pass a value to the constructor, or call fromJson");throw Error("The old contents is undefined. Either pass a value to the constructor, or call fromJson");}b.setText(c)}else console.warn("Can't change non-existent comment: "+this.commentId)}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.COMMENT_CHANGE,CommentChange$$module$build$src$core$events$events_comment_change);
var module$build$src$core$events$events_comment_change={};module$build$src$core$events$events_comment_change.CommentChange=CommentChange$$module$build$src$core$events$events_comment_change;var CommentCollapse$$module$build$src$core$events$events_comment_collapse=class extends CommentBase$$module$build$src$core$events$events_comment_base{constructor(a,b){super(a);this.newCollapsed=b;this.type=EventType$$module$build$src$core$events$type.COMMENT_COLLAPSE}toJson(){const a=super.toJson();if(this.newCollapsed===void 0)throw Error("The new collapse value undefined. Either call recordNew, or call fromJson");a.newCollapsed=this.newCollapsed;return a}static fromJson(a,b,c){b=super.fromJson(a,
b,c!=null?c:new CommentCollapse$$module$build$src$core$events$events_comment_collapse);b.newCollapsed=a.newCollapsed;return b}run(a){var b=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(b=b.getCommentById(this.commentId))?b.setCollapsed(a?!!this.newCollapsed:!this.newCollapsed):console.warn("Can't collapse or uncollapse non-existent comment: "+this.commentId)}};
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.COMMENT_COLLAPSE,CommentCollapse$$module$build$src$core$events$events_comment_collapse);var module$build$src$core$events$events_comment_collapse={};module$build$src$core$events$events_comment_collapse.CommentCollapse=CommentCollapse$$module$build$src$core$events$events_comment_collapse;var CommentCreate$$module$build$src$core$events$events_comment_create=class extends CommentBase$$module$build$src$core$events$events_comment_base{constructor(a){super(a);this.type=EventType$$module$build$src$core$events$type.COMMENT_CREATE;a&&(this.xml=saveWorkspaceComment$$module$build$src$core$xml(a),this.json=save$$module$build$src$core$serialization$workspace_comments(a,{addCoordinates:!0}))}toJson(){const a=super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");
if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");a.xml=domToText$$module$build$src$core$xml(this.xml);a.json=this.json;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new CommentCreate$$module$build$src$core$events$events_comment_create);b.xml=$.textToDom$$module$build$src$core$utils$xml(a.xml);b.json=a.json;return b}run(a){CommentBase$$module$build$src$core$events$events_comment_base.CommentCreateDeleteHelper(this,
a)}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.COMMENT_CREATE,CommentCreate$$module$build$src$core$events$events_comment_create);var module$build$src$core$events$events_comment_create={};module$build$src$core$events$events_comment_create.CommentCreate=CommentCreate$$module$build$src$core$events$events_comment_create;var CommentDelete$$module$build$src$core$events$events_comment_delete=class extends CommentBase$$module$build$src$core$events$events_comment_base{constructor(a){super(a);this.type=EventType$$module$build$src$core$events$type.COMMENT_DELETE;a&&(this.xml=saveWorkspaceComment$$module$build$src$core$xml(a),this.json=save$$module$build$src$core$serialization$workspace_comments(a,{addCoordinates:!0}))}run(a){CommentBase$$module$build$src$core$events$events_comment_base.CommentCreateDeleteHelper(this,!a)}toJson(){const a=
super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");a.xml=domToText$$module$build$src$core$xml(this.xml);a.json=this.json;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new CommentDelete$$module$build$src$core$events$events_comment_delete);b.xml=$.textToDom$$module$build$src$core$utils$xml(a.xml);
b.json=a.json;return b}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.COMMENT_DELETE,CommentDelete$$module$build$src$core$events$events_comment_delete);var module$build$src$core$events$events_comment_delete={};module$build$src$core$events$events_comment_delete.CommentDelete=CommentDelete$$module$build$src$core$events$events_comment_delete;var CommentDrag$$module$build$src$core$events$events_comment_drag=class extends UiBase$$module$build$src$core$events$events_ui_base{constructor(a,b){super(a?a.workspace.id:void 0);this.type=EventType$$module$build$src$core$events$type.COMMENT_DRAG;a&&(this.commentId=a.id,this.isStart=b)}toJson(){const a=super.toJson();if(this.isStart===void 0)throw Error("Whether this event is the start of a drag is undefined. Either pass the value to the constructor, or call fromJson");if(this.commentId===void 0)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");
a.isStart=this.isStart;a.commentId=this.commentId;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new CommentDrag$$module$build$src$core$events$events_comment_drag);b.isStart=a.isStart;b.commentId=a.commentId;return b}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.COMMENT_DRAG,CommentDrag$$module$build$src$core$events$events_comment_drag);var module$build$src$core$events$events_comment_drag={};
module$build$src$core$events$events_comment_drag.CommentDrag=CommentDrag$$module$build$src$core$events$events_comment_drag;var CommentMove$$module$build$src$core$events$events_comment_move=class extends CommentBase$$module$build$src$core$events$events_comment_base{constructor(a){super(a);this.type=EventType$$module$build$src$core$events$type.COMMENT_MOVE;a&&(this.comment_=a,this.oldCoordinate_=a.getRelativeToSurfaceXY())}recordNew(){if(this.newCoordinate_)throw Error("Tried to record the new position of a comment on the same event twice.");if(!this.comment_)throw Error("The comment is undefined. Pass a comment to the constructor if you want to use the record functionality");
this.newCoordinate_=this.comment_.getRelativeToSurfaceXY()}setReason(a){this.reason=a}setOldCoordinate(a){this.oldCoordinate_=a}toJson(){const a=super.toJson();if(!this.oldCoordinate_)throw Error("The old comment position is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newCoordinate_)throw Error("The new comment position is undefined. Either call recordNew, or call fromJson");a.oldCoordinate=`${Math.round(this.oldCoordinate_.x)}, `+`${Math.round(this.oldCoordinate_.y)}`;
a.newCoordinate=Math.round(this.newCoordinate_.x)+","+Math.round(this.newCoordinate_.y);return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new CommentMove$$module$build$src$core$events$events_comment_move);c=a.oldCoordinate.split(",");b.oldCoordinate_=new Coordinate$$module$build$src$core$utils$coordinate(Number(c[0]),Number(c[1]));c=a.newCoordinate.split(",");b.newCoordinate_=new Coordinate$$module$build$src$core$utils$coordinate(Number(c[0]),Number(c[1]));return b}isNull(){return Coordinate$$module$build$src$core$utils$coordinate.equals(this.oldCoordinate_,
this.newCoordinate_)}run(a){var b=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(b=b.getCommentById(this.commentId)){a=a?this.newCoordinate_:this.oldCoordinate_;if(!a)throw Error("Either oldCoordinate_ or newCoordinate_ is undefined. Either pass a comment to the constructor and call recordNew, or call fromJson");b.moveTo(a)}else console.warn("Can't move non-existent comment: "+this.commentId)}};
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.COMMENT_MOVE,CommentMove$$module$build$src$core$events$events_comment_move);var module$build$src$core$events$events_comment_move={};module$build$src$core$events$events_comment_move.CommentMove=CommentMove$$module$build$src$core$events$events_comment_move;var CommentResize$$module$build$src$core$events$events_comment_resize=class extends CommentBase$$module$build$src$core$events$events_comment_base{constructor(a){super(a);this.type=EventType$$module$build$src$core$events$type.COMMENT_RESIZE;a&&(this.oldSize=a.getSize())}recordCurrentSizeAsNewSize(){if(this.newSize)throw Error("Tried to record the new size of a comment on the same event twice.");var a=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");
a=a.getCommentById(this.commentId);if(!a)throw Error("The comment associated with the comment resize event could not be found");this.newSize=a.getSize()}toJson(){const a=super.toJson();if(!this.oldSize)throw Error("The old comment size is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newSize)throw Error("The new comment size is undefined. Either call recordCurrentSizeAsNewSize, or call fromJson");a.oldWidth=Math.round(this.oldSize.width);a.oldHeight=Math.round(this.oldSize.height);
a.newWidth=Math.round(this.newSize.width);a.newHeight=Math.round(this.newSize.height);return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new CommentResize$$module$build$src$core$events$events_comment_resize);b.oldSize=new Size$$module$build$src$core$utils$size(a.oldWidth,a.oldHeight);b.newSize=new Size$$module$build$src$core$utils$size(a.newWidth,a.newHeight);return b}isNull(){return Size$$module$build$src$core$utils$size.equals(this.oldSize,this.newSize)}run(a){var b=this.getEventWorkspace_();
if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(b=b.getCommentById(this.commentId)){a=a?this.newSize:this.oldSize;if(!a)throw Error("Either oldSize or newSize is undefined. Either pass a comment to the constructor and call recordCurrentSizeAsNewSize, or call fromJson");b.setSize(a)}else console.warn("Can't resize non-existent comment: "+this.commentId)}};
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.COMMENT_RESIZE,CommentResize$$module$build$src$core$events$events_comment_resize);var module$build$src$core$events$events_comment_resize={};module$build$src$core$events$events_comment_resize.CommentResize=CommentResize$$module$build$src$core$events$events_comment_resize;var ToolboxItemSelect$$module$build$src$core$events$events_toolbox_item_select=class extends UiBase$$module$build$src$core$events$events_ui_base{constructor(a,b,c){super(c);this.type=EventType$$module$build$src$core$events$type.TOOLBOX_ITEM_SELECT;this.oldItem=a!=null?a:void 0;this.newItem=b!=null?b:void 0}toJson(){const a=super.toJson();a.oldItem=this.oldItem;a.newItem=this.newItem;return a}static fromJson(a,b,c){b=super.fromJson(a,b,c!=null?c:new ToolboxItemSelect$$module$build$src$core$events$events_toolbox_item_select);
b.oldItem=a.oldItem;b.newItem=a.newItem;return b}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.TOOLBOX_ITEM_SELECT,ToolboxItemSelect$$module$build$src$core$events$events_toolbox_item_select);var module$build$src$core$events$events_toolbox_item_select={};module$build$src$core$events$events_toolbox_item_select.ToolboxItemSelect=ToolboxItemSelect$$module$build$src$core$events$events_toolbox_item_select;var VarTypeChange$$module$build$src$core$events$events_var_type_change=class extends VarBase$$module$build$src$core$events$events_var_base{constructor(a,b,c){super(a);this.oldType=b;this.newType=c;this.type=EventType$$module$build$src$core$events$type.VAR_TYPE_CHANGE}toJson(){const a=super.toJson();if(!this.oldType||!this.newType)throw Error("The variable's types are undefined. Either pass them to the constructor, or call fromJson");a.oldType=this.oldType;a.newType=this.newType;return a}static fromJson(a,
b,c){b=super.fromJson(a,b,c!=null?c:new VarTypeChange$$module$build$src$core$events$events_var_type_change);b.oldType=a.oldType;b.newType=a.newType;return b}run(a){const b=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.oldType||!this.newType)throw Error("The variable's types are undefined. Either pass them to the constructor, or call fromJson");const c=b.getVariableMap().getVariableById(this.varId);
c&&(a?b.getVariableMap().changeVariableType(c,this.newType):b.getVariableMap().changeVariableType(c,this.oldType))}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.VAR_TYPE_CHANGE,VarTypeChange$$module$build$src$core$events$events_var_type_change);var module$build$src$core$events$events_var_type_change={};module$build$src$core$events$events_var_type_change.VarTypeChange=VarTypeChange$$module$build$src$core$events$events_var_type_change;var FinishedLoading$$module$build$src$core$events$workspace_events=class extends Abstract$$module$build$src$core$events$events_abstract{constructor(a){super();this.isBlank=!0;this.recordUndo=!1;this.type=EventType$$module$build$src$core$events$type.FINISHED_LOADING;this.isBlank=!!a;a&&(this.workspaceId=a.id)}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.EVENT,EventType$$module$build$src$core$events$type.FINISHED_LOADING,FinishedLoading$$module$build$src$core$events$workspace_events);
var module$build$src$core$events$workspace_events={};module$build$src$core$events$workspace_events.FinishedLoading=FinishedLoading$$module$build$src$core$events$workspace_events;var BLOCK_DRAG$$module$build$src$core$events$events,BLOCK_FIELD_INTERMEDIATE_CHANGE$$module$build$src$core$events$events,BUBBLE_OPEN$$module$build$src$core$events$events,CHANGE$$module$build$src$core$events$events,CLICK$$module$build$src$core$events$events,COMMENT_CHANGE$$module$build$src$core$events$events,COMMENT_CREATE$$module$build$src$core$events$events,COMMENT_DELETE$$module$build$src$core$events$events,COMMENT_MOVE$$module$build$src$core$events$events,COMMENT_RESIZE$$module$build$src$core$events$events,
COMMENT_DRAG$$module$build$src$core$events$events,CREATE$$module$build$src$core$events$events,DELETE$$module$build$src$core$events$events,FINISHED_LOADING$$module$build$src$core$events$events,MOVE$$module$build$src$core$events$events,SELECTED$$module$build$src$core$events$events,THEME_CHANGE$$module$build$src$core$events$events,TOOLBOX_ITEM_SELECT$$module$build$src$core$events$events,TRASHCAN_OPEN$$module$build$src$core$events$events,UI$$module$build$src$core$events$events,VAR_CREATE$$module$build$src$core$events$events,
VAR_DELETE$$module$build$src$core$events$events,VAR_RENAME$$module$build$src$core$events$events,VIEWPORT_CHANGE$$module$build$src$core$events$events,module$build$src$core$events$events;$.BLOCK_CHANGE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.BLOCK_CHANGE;$.BLOCK_CREATE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.BLOCK_CREATE;$.BLOCK_DELETE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.BLOCK_DELETE;
BLOCK_DRAG$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.BLOCK_DRAG;$.BLOCK_MOVE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.BLOCK_MOVE;BLOCK_FIELD_INTERMEDIATE_CHANGE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.BLOCK_FIELD_INTERMEDIATE_CHANGE;BUBBLE_OPEN$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.BUBBLE_OPEN;
CHANGE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.BLOCK_CHANGE;CLICK$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.CLICK;COMMENT_CHANGE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.COMMENT_CHANGE;COMMENT_CREATE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.COMMENT_CREATE;COMMENT_DELETE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.COMMENT_DELETE;
COMMENT_MOVE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.COMMENT_MOVE;COMMENT_RESIZE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.COMMENT_RESIZE;COMMENT_DRAG$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.COMMENT_DRAG;CREATE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.BLOCK_CREATE;DELETE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.BLOCK_DELETE;
FINISHED_LOADING$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.FINISHED_LOADING;MOVE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.BLOCK_MOVE;SELECTED$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.SELECTED;THEME_CHANGE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.THEME_CHANGE;TOOLBOX_ITEM_SELECT$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.TOOLBOX_ITEM_SELECT;
TRASHCAN_OPEN$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.TRASHCAN_OPEN;UI$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.UI;VAR_CREATE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.VAR_CREATE;VAR_DELETE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.VAR_DELETE;VAR_RENAME$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.VAR_RENAME;
VIEWPORT_CHANGE$$module$build$src$core$events$events=EventType$$module$build$src$core$events$type.VIEWPORT_CHANGE;module$build$src$core$events$events={};module$build$src$core$events$events.Abstract=Abstract$$module$build$src$core$events$events_abstract;module$build$src$core$events$events.BLOCK_CHANGE=$.BLOCK_CHANGE$$module$build$src$core$events$events;module$build$src$core$events$events.BLOCK_CREATE=$.BLOCK_CREATE$$module$build$src$core$events$events;
module$build$src$core$events$events.BLOCK_DELETE=$.BLOCK_DELETE$$module$build$src$core$events$events;module$build$src$core$events$events.BLOCK_DRAG=BLOCK_DRAG$$module$build$src$core$events$events;module$build$src$core$events$events.BLOCK_FIELD_INTERMEDIATE_CHANGE=BLOCK_FIELD_INTERMEDIATE_CHANGE$$module$build$src$core$events$events;module$build$src$core$events$events.BLOCK_MOVE=$.BLOCK_MOVE$$module$build$src$core$events$events;module$build$src$core$events$events.BUBBLE_OPEN=BUBBLE_OPEN$$module$build$src$core$events$events;
module$build$src$core$events$events.BUMP_EVENTS=BUMP_EVENTS$$module$build$src$core$events$type;module$build$src$core$events$events.BlockBase=BlockBase$$module$build$src$core$events$events_block_base;module$build$src$core$events$events.BlockChange=BlockChange$$module$build$src$core$events$events_block_change;module$build$src$core$events$events.BlockCreate=BlockCreate$$module$build$src$core$events$events_block_create;module$build$src$core$events$events.BlockDelete=BlockDelete$$module$build$src$core$events$events_block_delete;
module$build$src$core$events$events.BlockDrag=BlockDrag$$module$build$src$core$events$events_block_drag;module$build$src$core$events$events.BlockFieldIntermediateChange=BlockFieldIntermediateChange$$module$build$src$core$events$events_block_field_intermediate_change;module$build$src$core$events$events.BlockMove=BlockMove$$module$build$src$core$events$events_block_move;module$build$src$core$events$events.BubbleOpen=BubbleOpen$$module$build$src$core$events$events_bubble_open;
module$build$src$core$events$events.BubbleType=BubbleType$$module$build$src$core$events$events_bubble_open;module$build$src$core$events$events.CHANGE=CHANGE$$module$build$src$core$events$events;module$build$src$core$events$events.CLICK=CLICK$$module$build$src$core$events$events;module$build$src$core$events$events.COMMENT_CHANGE=COMMENT_CHANGE$$module$build$src$core$events$events;module$build$src$core$events$events.COMMENT_CREATE=COMMENT_CREATE$$module$build$src$core$events$events;
module$build$src$core$events$events.COMMENT_DELETE=COMMENT_DELETE$$module$build$src$core$events$events;module$build$src$core$events$events.COMMENT_DRAG=COMMENT_DRAG$$module$build$src$core$events$events;module$build$src$core$events$events.COMMENT_MOVE=COMMENT_MOVE$$module$build$src$core$events$events;module$build$src$core$events$events.COMMENT_RESIZE=COMMENT_RESIZE$$module$build$src$core$events$events;module$build$src$core$events$events.CREATE=CREATE$$module$build$src$core$events$events;
module$build$src$core$events$events.Click=Click$$module$build$src$core$events$events_click;module$build$src$core$events$events.ClickTarget=ClickTarget$$module$build$src$core$events$events_click;module$build$src$core$events$events.CommentBase=CommentBase$$module$build$src$core$events$events_comment_base;module$build$src$core$events$events.CommentChange=CommentChange$$module$build$src$core$events$events_comment_change;module$build$src$core$events$events.CommentCollapse=CommentCollapse$$module$build$src$core$events$events_comment_collapse;
module$build$src$core$events$events.CommentCreate=CommentCreate$$module$build$src$core$events$events_comment_create;module$build$src$core$events$events.CommentDelete=CommentDelete$$module$build$src$core$events$events_comment_delete;module$build$src$core$events$events.CommentDrag=CommentDrag$$module$build$src$core$events$events_comment_drag;module$build$src$core$events$events.CommentMove=CommentMove$$module$build$src$core$events$events_comment_move;
module$build$src$core$events$events.CommentResize=CommentResize$$module$build$src$core$events$events_comment_resize;module$build$src$core$events$events.DELETE=DELETE$$module$build$src$core$events$events;module$build$src$core$events$events.FINISHED_LOADING=FINISHED_LOADING$$module$build$src$core$events$events;module$build$src$core$events$events.FinishedLoading=FinishedLoading$$module$build$src$core$events$workspace_events;module$build$src$core$events$events.MOVE=MOVE$$module$build$src$core$events$events;
module$build$src$core$events$events.SELECTED=SELECTED$$module$build$src$core$events$events;module$build$src$core$events$events.Selected=Selected$$module$build$src$core$events$events_selected;module$build$src$core$events$events.THEME_CHANGE=THEME_CHANGE$$module$build$src$core$events$events;module$build$src$core$events$events.TOOLBOX_ITEM_SELECT=TOOLBOX_ITEM_SELECT$$module$build$src$core$events$events;module$build$src$core$events$events.TRASHCAN_OPEN=TRASHCAN_OPEN$$module$build$src$core$events$events;
module$build$src$core$events$events.ThemeChange=ThemeChange$$module$build$src$core$events$events_theme_change;module$build$src$core$events$events.ToolboxItemSelect=ToolboxItemSelect$$module$build$src$core$events$events_toolbox_item_select;module$build$src$core$events$events.TrashcanOpen=TrashcanOpen$$module$build$src$core$events$events_trashcan_open;module$build$src$core$events$events.UI=UI$$module$build$src$core$events$events;module$build$src$core$events$events.UiBase=UiBase$$module$build$src$core$events$events_ui_base;
module$build$src$core$events$events.VAR_CREATE=VAR_CREATE$$module$build$src$core$events$events;module$build$src$core$events$events.VAR_DELETE=VAR_DELETE$$module$build$src$core$events$events;module$build$src$core$events$events.VAR_RENAME=VAR_RENAME$$module$build$src$core$events$events;module$build$src$core$events$events.VIEWPORT_CHANGE=VIEWPORT_CHANGE$$module$build$src$core$events$events;module$build$src$core$events$events.VarBase=VarBase$$module$build$src$core$events$events_var_base;
module$build$src$core$events$events.VarCreate=VarCreate$$module$build$src$core$events$events_var_create;module$build$src$core$events$events.VarDelete=VarDelete$$module$build$src$core$events$events_var_delete;module$build$src$core$events$events.VarRename=VarRename$$module$build$src$core$events$events_var_rename;module$build$src$core$events$events.VarTypeChange=VarTypeChange$$module$build$src$core$events$events_var_type_change;module$build$src$core$events$events.ViewportChange=ViewportChange$$module$build$src$core$events$events_viewport;
module$build$src$core$events$events.clearPendingUndo=clearPendingUndo$$module$build$src$core$events$utils;module$build$src$core$events$events.disable=$.disable$$module$build$src$core$events$utils;module$build$src$core$events$events.disableOrphans=disableOrphans$$module$build$src$core$events$utils;module$build$src$core$events$events.enable=$.enable$$module$build$src$core$events$utils;module$build$src$core$events$events.filter=filter$$module$build$src$core$events$utils;
module$build$src$core$events$events.fire=fire$$module$build$src$core$events$utils;module$build$src$core$events$events.fromJson=fromJson$$module$build$src$core$events$utils;module$build$src$core$events$events.get=get$$module$build$src$core$events$utils;module$build$src$core$events$events.getDescendantIds=getDescendantIds$$module$build$src$core$events$utils;module$build$src$core$events$events.getGroup=$.getGroup$$module$build$src$core$events$utils;module$build$src$core$events$events.getRecordUndo=getRecordUndo$$module$build$src$core$events$utils;
module$build$src$core$events$events.isEnabled=isEnabled$$module$build$src$core$events$utils;module$build$src$core$events$events.setGroup=$.setGroup$$module$build$src$core$events$utils;module$build$src$core$events$events.setRecordUndo=$.setRecordUndo$$module$build$src$core$events$utils;var module$build$src$core$renderers$zelos$zelos={};module$build$src$core$renderers$zelos$zelos.BottomRow=BottomRow$$module$build$src$core$renderers$zelos$measurables$bottom_row;module$build$src$core$renderers$zelos$zelos.ConstantProvider=ConstantProvider$$module$build$src$core$renderers$zelos$constants;module$build$src$core$renderers$zelos$zelos.Drawer=Drawer$$module$build$src$core$renderers$zelos$drawer;module$build$src$core$renderers$zelos$zelos.PathObject=PathObject$$module$build$src$core$renderers$zelos$path_object;
module$build$src$core$renderers$zelos$zelos.RenderInfo=RenderInfo$$module$build$src$core$renderers$zelos$info;module$build$src$core$renderers$zelos$zelos.Renderer=Renderer$$module$build$src$core$renderers$zelos$renderer;module$build$src$core$renderers$zelos$zelos.RightConnectionShape=RightConnectionShape$$module$build$src$core$renderers$zelos$measurables$row_elements;module$build$src$core$renderers$zelos$zelos.StatementInput=StatementInput$$module$build$src$core$renderers$zelos$measurables$inputs;
module$build$src$core$renderers$zelos$zelos.TopRow=TopRow$$module$build$src$core$renderers$zelos$measurables$top_row;registerDefaultOptions$$module$build$src$core$contextmenu_items();var module$build$src$core$contextmenu_items={};module$build$src$core$contextmenu_items.registerCleanup=registerCleanup$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerCollapse=registerCollapse$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerCollapseExpandBlock=registerCollapseExpandBlock$$module$build$src$core$contextmenu_items;
module$build$src$core$contextmenu_items.registerComment=registerComment$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerCommentCreate=registerCommentCreate$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerCommentDelete=registerCommentDelete$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerCommentDuplicate=registerCommentDuplicate$$module$build$src$core$contextmenu_items;
module$build$src$core$contextmenu_items.registerCommentOptions=registerCommentOptions$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerDefaultOptions=registerDefaultOptions$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerDelete=registerDelete$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerDeleteAll=registerDeleteAll$$module$build$src$core$contextmenu_items;
module$build$src$core$contextmenu_items.registerDisable=registerDisable$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerDuplicate=registerDuplicate$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerExpand=registerExpand$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerHelp=registerHelp$$module$build$src$core$contextmenu_items;
module$build$src$core$contextmenu_items.registerInline=registerInline$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerRedo=registerRedo$$module$build$src$core$contextmenu_items;module$build$src$core$contextmenu_items.registerUndo=registerUndo$$module$build$src$core$contextmenu_items;var BUTTON_TYPE$$module$build$src$core$button_flyout_inflater="button",ButtonFlyoutInflater$$module$build$src$core$button_flyout_inflater=class{load(a,b){a=new FlyoutButton$$module$build$src$core$flyout_button(b.getWorkspace(),b.targetWorkspace,a,!1);a.show();return new FlyoutItem$$module$build$src$core$flyout_item(a,BUTTON_TYPE$$module$build$src$core$button_flyout_inflater)}gapForItem(a,b){return b}disposeItem(a){a=a.getElement();a instanceof FlyoutButton$$module$build$src$core$flyout_button&&a.dispose()}getType(){return BUTTON_TYPE$$module$build$src$core$button_flyout_inflater}};
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUT_INFLATER,BUTTON_TYPE$$module$build$src$core$button_flyout_inflater,ButtonFlyoutInflater$$module$build$src$core$button_flyout_inflater);var module$build$src$core$button_flyout_inflater={};module$build$src$core$button_flyout_inflater.ButtonFlyoutInflater=ButtonFlyoutInflater$$module$build$src$core$button_flyout_inflater;var module$build$src$core$bubbles={};module$build$src$core$bubbles.Bubble=Bubble$$module$build$src$core$bubbles$bubble;module$build$src$core$bubbles.MiniWorkspaceBubble=MiniWorkspaceBubble$$module$build$src$core$bubbles$mini_workspace_bubble;module$build$src$core$bubbles.TextBubble=TextBubble$$module$build$src$core$bubbles$text_bubble;module$build$src$core$bubbles.TextInputBubble=TextInputBubble$$module$build$src$core$bubbles$textinput_bubble;var module$build$src$core$blockly_options={};var WORKSPACE_AT_BLOCK_CAPACITY_DISABLED_REASON$$module$build$src$core$block_flyout_inflater="WORKSPACE_AT_BLOCK_CAPACITY",BLOCK_TYPE$$module$build$src$core$block_flyout_inflater="block",BlockFlyoutInflater$$module$build$src$core$block_flyout_inflater=class{constructor(){this.permanentlyDisabledBlocks=new Set;this.listeners=new Map;this.capacityWrapper=this.filterFlyoutBasedOnCapacity.bind(this)}load(a,b){this.setFlyout(b);a=this.createBlock(a,b.getWorkspace());a.isEnabled()?this.updateStateBasedOnCapacity(a):
this.permanentlyDisabledBlocks.add(a);a.getDescendants(!1).forEach(c=>c.isInFlyout=!0);this.addBlockListeners(a);return new FlyoutItem$$module$build$src$core$flyout_item(a,BLOCK_TYPE$$module$build$src$core$block_flyout_inflater)}createBlock(a,b){a.blockxml?(a=typeof a.blockxml==="string"?$.textToDom$$module$build$src$core$utils$xml(a.blockxml):a.blockxml,b=domToBlockInternal$$module$build$src$core$xml(a,b)):(a.enabled===void 0&&(a.enabled=a.disabled!=="true"&&a.disabled!==!0),a.disabledReasons===
void 0&&a.enabled===!1&&(a.disabledReasons=[MANUALLY_DISABLED$$module$build$src$core$constants]),"x"in a&&delete a.x,"y"in a&&delete a.y,b=appendInternal$$module$build$src$core$serialization$blocks(a,b));return b}gapForItem(a,b){let c;a.gap?c=parseInt(String(a.gap)):a.blockxml&&(a=typeof a.blockxml==="string"?$.textToDom$$module$build$src$core$utils$xml(a.blockxml):a.blockxml,c=parseInt(a.getAttribute("gap")));return!c||isNaN(c)?b:c}disposeItem(a){a=a.getElement();a instanceof BlockSvg$$module$build$src$core$block_svg&&
(this.removeListeners(a.id),a.dispose(!1,!1))}removeListeners(a){let b;((b=this.listeners.get(a))!=null?b:[]).forEach(c=>unbind$$module$build$src$core$browser_events(c));this.listeners.delete(a)}setFlyout(a){if(this.flyout!==a){if(this.flyout){let c;(c=this.flyout.targetWorkspace)==null||c.removeChangeListener(this.capacityWrapper)}this.flyout=a;var b;(b=this.flyout.targetWorkspace)==null||b.addChangeListener(this.capacityWrapper)}}updateStateBasedOnCapacity(a){let b,c;const d=(b=this.flyout)==null?
void 0:(c=b.targetWorkspace)==null?void 0:c.isCapacityAvailable(getBlockTypeCounts$$module$build$src$core$common(a));for(;a;)a.setDisabledReason(!d,WORKSPACE_AT_BLOCK_CAPACITY_DISABLED_REASON$$module$build$src$core$block_flyout_inflater),a=a.getNextBlock()}addBlockListeners(a){const b=[];b.push(conditionalBind$$module$build$src$core$browser_events(a.getSvgRoot(),"pointerdown",a,c=>{let d,e;const f=(d=this.flyout)==null?void 0:(e=d.targetWorkspace)==null?void 0:e.getGesture(c);f&&this.flyout&&(f.setStartBlock(a),
f.handleFlyoutStart(c,this.flyout))}));b.push(bind$$module$build$src$core$browser_events(a.getSvgRoot(),"pointermove",null,()=>{let c,d;((c=this.flyout)==null?0:(d=c.targetWorkspace)==null?0:d.isDragging())||a.addSelect()}));b.push(bind$$module$build$src$core$browser_events(a.getSvgRoot(),"pointerleave",null,()=>{let c,d;((c=this.flyout)==null?0:(d=c.targetWorkspace)==null?0:d.isDragging())||a.removeSelect()}));this.listeners.set(a.id,b)}filterFlyoutBasedOnCapacity(a){!this.flyout||a&&a.type!==EventType$$module$build$src$core$events$type.BLOCK_CREATE&&
a.type!==EventType$$module$build$src$core$events$type.BLOCK_DELETE||this.flyout.getWorkspace().getTopBlocks(!1).forEach(b=>{this.permanentlyDisabledBlocks.has(b)||this.updateStateBasedOnCapacity(b)})}getType(){return BLOCK_TYPE$$module$build$src$core$block_flyout_inflater}};register$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUT_INFLATER,BLOCK_TYPE$$module$build$src$core$block_flyout_inflater,BlockFlyoutInflater$$module$build$src$core$block_flyout_inflater);
var module$build$src$core$block_flyout_inflater={};module$build$src$core$block_flyout_inflater.BlockFlyoutInflater=BlockFlyoutInflater$$module$build$src$core$block_flyout_inflater;var module$build$src$core$interfaces$i_paster={};module$build$src$core$interfaces$i_paster.isPaster=isPaster$$module$build$src$core$interfaces$i_paster;var module$build$src$core$interfaces$i_rendered_element={};module$build$src$core$interfaces$i_rendered_element.isRenderedElement=isRenderedElement$$module$build$src$core$interfaces$i_rendered_element;var ConstantProvider$$module$build$src$core$renderers$geras$constants=class extends ConstantProvider$$module$build$src$core$renderers$common$constants{constructor(){super();this.FIELD_TEXT_BASELINE_CENTER=!1;this.DARK_PATH_OFFSET=1;this.MAX_BOTTOM_WIDTH=30;this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT/2}getCSS_(a){return super.getCSS_(a).concat([`${a} .blocklyInsertionMarker>.blocklyPathLight,`,`${a} .blocklyInsertionMarker>.blocklyPathDark {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;",
"}"])}},module$build$src$core$renderers$geras$constants={};module$build$src$core$renderers$geras$constants.ConstantProvider=ConstantProvider$$module$build$src$core$renderers$geras$constants;var Highlighter$$module$build$src$core$renderers$geras$highlighter=class{constructor(a){this.inlineSteps_=this.steps_="";this.info_=a;this.RTL_=this.info_.RTL;a=a.getRenderer();this.constants_=a.getConstants();this.highlightConstants_=a.getHighlightConstants();this.highlightOffset=this.highlightConstants_.OFFSET;this.outsideCornerPaths_=this.highlightConstants_.OUTSIDE_CORNER;this.insideCornerPaths_=this.highlightConstants_.INSIDE_CORNER;this.puzzleTabPaths_=this.highlightConstants_.PUZZLE_TAB;this.notchPaths_=
this.highlightConstants_.NOTCH;this.startPaths_=this.highlightConstants_.START_HAT;this.jaggedTeethPaths_=this.highlightConstants_.JAGGED_TEETH}getPath(){return this.steps_+"\n"+this.inlineSteps_}drawTopCorner(a){this.steps_+=moveBy$$module$build$src$core$utils$svg_paths(a.xPos,this.info_.startY);for(let b=0,c;c=a.elements[b];b++)Types$$module$build$src$core$renderers$measurables$types.isLeftSquareCorner(c)?this.steps_+=this.highlightConstants_.START_POINT:Types$$module$build$src$core$renderers$measurables$types.isLeftRoundedCorner(c)?
this.steps_+=this.outsideCornerPaths_.topLeft(this.RTL_):Types$$module$build$src$core$renderers$measurables$types.isPreviousConnection(c)?this.steps_+=this.notchPaths_.pathLeft:Types$$module$build$src$core$renderers$measurables$types.isHat(c)?this.steps_+=this.startPaths_.path(this.RTL_):Types$$module$build$src$core$renderers$measurables$types.isSpacer(c)&&c.width!==0&&(this.steps_+=lineOnAxis$$module$build$src$core$utils$svg_paths("H",c.xPos+c.width-this.highlightOffset));this.steps_+=lineOnAxis$$module$build$src$core$utils$svg_paths("H",
a.xPos+a.width-this.highlightOffset)}drawJaggedEdge_(a){this.info_.RTL&&(this.steps_+=this.jaggedTeethPaths_.pathLeft+lineOnAxis$$module$build$src$core$utils$svg_paths("v",a.height-this.jaggedTeethPaths_.height-this.highlightOffset))}drawValueInput(a){const b=a.getLastInput();if(this.RTL_){const c=a.height-b.connectionHeight;this.steps_+=moveTo$$module$build$src$core$utils$svg_paths(b.xPos+b.width-this.highlightOffset,a.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)+lineOnAxis$$module$build$src$core$utils$svg_paths("v",
c)}else this.steps_+=moveTo$$module$build$src$core$utils$svg_paths(b.xPos+b.width,a.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)}drawStatementInput(a){const b=a.getLastInput();if(b)if(this.RTL_){const c=a.height-2*this.insideCornerPaths_.height;this.steps_+=moveTo$$module$build$src$core$utils$svg_paths(b.xPos,a.yPos)+this.insideCornerPaths_.pathTop(this.RTL_)+lineOnAxis$$module$build$src$core$utils$svg_paths("v",c)+this.insideCornerPaths_.pathBottom(this.RTL_)+lineTo$$module$build$src$core$utils$svg_paths(a.width-
b.xPos-this.insideCornerPaths_.width,0)}else this.steps_+=moveTo$$module$build$src$core$utils$svg_paths(b.xPos,a.yPos+a.height)+this.insideCornerPaths_.pathBottom(this.RTL_)+lineTo$$module$build$src$core$utils$svg_paths(a.width-b.xPos-this.insideCornerPaths_.width,0)}drawRightSideRow(a){const b=a.xPos+a.width-this.highlightOffset;a instanceof SpacerRow$$module$build$src$core$renderers$measurables$spacer_row&&a.followsStatement&&(this.steps_+=lineOnAxis$$module$build$src$core$utils$svg_paths("H",b));
this.RTL_&&(this.steps_+=lineOnAxis$$module$build$src$core$utils$svg_paths("H",b),a.height>this.highlightOffset&&(this.steps_+=lineOnAxis$$module$build$src$core$utils$svg_paths("V",a.yPos+a.height-this.highlightOffset)))}drawBottomRow(a){if(this.RTL_)this.steps_+=lineOnAxis$$module$build$src$core$utils$svg_paths("V",a.baseline-this.highlightOffset);else{const b=this.info_.bottomRow.elements[0];Types$$module$build$src$core$renderers$measurables$types.isLeftSquareCorner(b)?this.steps_+=moveTo$$module$build$src$core$utils$svg_paths(a.xPos+
this.highlightOffset,a.baseline-this.highlightOffset):Types$$module$build$src$core$renderers$measurables$types.isLeftRoundedCorner(b)&&(this.steps_+=moveTo$$module$build$src$core$utils$svg_paths(a.xPos,a.baseline),this.steps_+=this.outsideCornerPaths_.bottomLeft())}}drawLeft(){var a=this.info_.outputConnection;a&&(a=a.connectionOffsetY+a.height,this.RTL_?this.steps_+=moveTo$$module$build$src$core$utils$svg_paths(this.info_.startX,a):(this.steps_+=moveTo$$module$build$src$core$utils$svg_paths(this.info_.startX+
this.highlightOffset,this.info_.bottomRow.baseline-this.highlightOffset),this.steps_+=lineOnAxis$$module$build$src$core$utils$svg_paths("V",a)),this.steps_+=this.puzzleTabPaths_.pathUp(this.RTL_));this.RTL_||(a=this.info_.topRow,Types$$module$build$src$core$renderers$measurables$types.isLeftRoundedCorner(a.elements[0])?this.steps_+=lineOnAxis$$module$build$src$core$utils$svg_paths("V",this.outsideCornerPaths_.height):this.steps_+=lineOnAxis$$module$build$src$core$utils$svg_paths("V",a.capline+this.highlightOffset))}drawInlineInput(a){const b=
this.highlightOffset,c=a.xPos+a.connectionWidth;var d=a.centerline-a.height/2;const e=a.width-a.connectionWidth,f=d+b;this.RTL_?(d=a.connectionOffsetY-b,a=a.height-(a.connectionOffsetY+a.connectionHeight)+b,this.inlineSteps_+=moveTo$$module$build$src$core$utils$svg_paths(c-b,f)+lineOnAxis$$module$build$src$core$utils$svg_paths("v",d)+this.puzzleTabPaths_.pathDown(this.RTL_)+lineOnAxis$$module$build$src$core$utils$svg_paths("v",a)+lineOnAxis$$module$build$src$core$utils$svg_paths("h",e)):this.inlineSteps_+=
moveTo$$module$build$src$core$utils$svg_paths(a.xPos+a.width+b,f)+lineOnAxis$$module$build$src$core$utils$svg_paths("v",a.height)+lineOnAxis$$module$build$src$core$utils$svg_paths("h",-e)+moveTo$$module$build$src$core$utils$svg_paths(c,d+a.connectionOffsetY)+this.puzzleTabPaths_.pathDown(this.RTL_)}},module$build$src$core$renderers$geras$highlighter={};module$build$src$core$renderers$geras$highlighter.Highlighter=Highlighter$$module$build$src$core$renderers$geras$highlighter;var Drawer$$module$build$src$core$renderers$geras$drawer=class extends Drawer$$module$build$src$core$renderers$common$drawer{constructor(a,b){super(a,b);this.highlighter_=new Highlighter$$module$build$src$core$renderers$geras$highlighter(b)}draw(){this.drawOutline_();this.drawInternals_();this.updateConnectionHighlights();const a=this.block_.pathObject;a.setPath(this.outlinePath_+"\n"+this.inlinePath_);a.setHighlightPath(this.highlighter_.getPath());this.info_.RTL&&a.flipRTL();this.recordSizeOnBlock_()}drawTop_(){this.highlighter_.drawTopCorner(this.info_.topRow);
this.highlighter_.drawRightSideRow(this.info_.topRow);super.drawTop_()}drawJaggedEdge_(a){this.highlighter_.drawJaggedEdge_(a);super.drawJaggedEdge_(a)}drawValueInput_(a){this.highlighter_.drawValueInput(a);super.drawValueInput_(a)}drawStatementInput_(a){this.highlighter_.drawStatementInput(a);super.drawStatementInput_(a)}drawRightSideRow_(a){this.highlighter_.drawRightSideRow(a);this.outlinePath_+=lineOnAxis$$module$build$src$core$utils$svg_paths("H",a.xPos+a.width)+lineOnAxis$$module$build$src$core$utils$svg_paths("V",
a.yPos+a.height)}drawBottom_(){this.highlighter_.drawBottomRow(this.info_.bottomRow);super.drawBottom_()}drawLeft_(){this.highlighter_.drawLeft();super.drawLeft_()}drawInlineInput_(a){this.highlighter_.drawInlineInput(a);super.drawInlineInput_(a)}positionInlineInputConnection_(a){const b=a.centerline-a.height/2;if(a.connectionModel){let c=a.xPos+a.connectionWidth+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(c*=-1);a.connectionModel.setOffsetInBlock(c,b+a.connectionOffsetY+this.constants_.DARK_PATH_OFFSET)}}positionStatementInputConnection_(a){const b=
a.getLastInput();if(b==null?0:b.connectionModel){let c=a.xPos+a.statementEdge+b.notchOffset;c=this.info_.RTL?c*-1:c+this.constants_.DARK_PATH_OFFSET;b.connectionModel.setOffsetInBlock(c,a.yPos+this.constants_.DARK_PATH_OFFSET)}}positionExternalValueConnection_(a){const b=a.getLastInput();if(b&&b.connectionModel){let c=a.xPos+a.width+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(c*=-1);b.connectionModel.setOffsetInBlock(c,a.yPos)}}positionNextConnection_(){const a=this.info_.bottomRow;if(a.connection){const b=
a.connection,c=b.xPos;b.connectionModel.setOffsetInBlock((this.info_.RTL?-c:c)+this.constants_.DARK_PATH_OFFSET/2,a.baseline+this.constants_.DARK_PATH_OFFSET)}}},module$build$src$core$renderers$geras$drawer={};module$build$src$core$renderers$geras$drawer.Drawer=Drawer$$module$build$src$core$renderers$geras$drawer;var HighlightConstantProvider$$module$build$src$core$renderers$geras$highlight_constants=class{constructor(a){this.OFFSET=.5;this.constantProvider=a;this.START_POINT=moveBy$$module$build$src$core$utils$svg_paths(this.OFFSET,this.OFFSET)}init(){this.INSIDE_CORNER=this.makeInsideCorner();this.OUTSIDE_CORNER=this.makeOutsideCorner();this.PUZZLE_TAB=this.makePuzzleTab();this.NOTCH=this.makeNotch();this.JAGGED_TEETH=this.makeJaggedTeeth();this.START_HAT=this.makeStartHat()}makeInsideCorner(){const a=this.constantProvider.CORNER_RADIUS,
b=this.OFFSET,c=(1-Math.SQRT1_2)*(a+b)-b,d=moveBy$$module$build$src$core$utils$svg_paths(c,c)+arc$$module$build$src$core$utils$svg_paths("a","0 0,0",a,point$$module$build$src$core$utils$svg_paths(-c-b,a-c)),e=arc$$module$build$src$core$utils$svg_paths("a","0 0,0",a+b,point$$module$build$src$core$utils$svg_paths(a+b,a+b)),f=moveBy$$module$build$src$core$utils$svg_paths(c,-c)+arc$$module$build$src$core$utils$svg_paths("a","0 0,0",a+b,point$$module$build$src$core$utils$svg_paths(a-c,c+b));return{width:a+
b,height:a,pathTop(g){return g?d:""},pathBottom(g){return g?e:f}}}makeOutsideCorner(){const a=this.constantProvider.CORNER_RADIUS,b=this.OFFSET,c=(1-Math.SQRT1_2)*(a-b)+b,d=moveBy$$module$build$src$core$utils$svg_paths(c,c)+arc$$module$build$src$core$utils$svg_paths("a","0 0,1",a-b,point$$module$build$src$core$utils$svg_paths(a-c,-c+b)),e=moveBy$$module$build$src$core$utils$svg_paths(b,a)+arc$$module$build$src$core$utils$svg_paths("a","0 0,1",a-b,point$$module$build$src$core$utils$svg_paths(a,-a+
b)),f=-c,g=moveBy$$module$build$src$core$utils$svg_paths(c,f)+arc$$module$build$src$core$utils$svg_paths("a","0 0,1",a-b,point$$module$build$src$core$utils$svg_paths(-c+b,-f-a));return{height:a,topLeft(h){return h?d:e},bottomLeft(){return g}}}makePuzzleTab(){const a=this.constantProvider.TAB_WIDTH,b=this.constantProvider.TAB_HEIGHT,c=moveBy$$module$build$src$core$utils$svg_paths(-2,-b+2.5+.9)+lineTo$$module$build$src$core$utils$svg_paths(a*-.45,-2.1),d=lineOnAxis$$module$build$src$core$utils$svg_paths("v",
2.5)+moveBy$$module$build$src$core$utils$svg_paths(-a*.97,2.5)+curve$$module$build$src$core$utils$svg_paths("q",[point$$module$build$src$core$utils$svg_paths(-a*.05,10),point$$module$build$src$core$utils$svg_paths(a*.3,9.5)])+moveBy$$module$build$src$core$utils$svg_paths(a*.67,-1.9)+lineOnAxis$$module$build$src$core$utils$svg_paths("v",2.5),e=lineOnAxis$$module$build$src$core$utils$svg_paths("v",-1.5)+moveBy$$module$build$src$core$utils$svg_paths(a*-.92,-.5)+curve$$module$build$src$core$utils$svg_paths("q",
[point$$module$build$src$core$utils$svg_paths(a*-.19,-5.5),point$$module$build$src$core$utils$svg_paths(0,-11)])+moveBy$$module$build$src$core$utils$svg_paths(a*.92,1),f=moveBy$$module$build$src$core$utils$svg_paths(-5,b-.7)+lineTo$$module$build$src$core$utils$svg_paths(a*.46,-2.1);return{width:a,height:b,pathUp(g){return g?c:e},pathDown(g){return g?d:f}}}makeNotch(){return{pathLeft:lineOnAxis$$module$build$src$core$utils$svg_paths("h",this.OFFSET)+this.constantProvider.NOTCH.pathLeft}}makeJaggedTeeth(){return{pathLeft:lineTo$$module$build$src$core$utils$svg_paths(5.1,
2.6)+moveBy$$module$build$src$core$utils$svg_paths(-10.2,6.8)+lineTo$$module$build$src$core$utils$svg_paths(5.1,2.6),height:12,width:10.2}}makeStartHat(){const a=this.constantProvider.START_HAT.height,b=moveBy$$module$build$src$core$utils$svg_paths(25,-8.7)+curve$$module$build$src$core$utils$svg_paths("c",[point$$module$build$src$core$utils$svg_paths(29.7,-6.2),point$$module$build$src$core$utils$svg_paths(57.2,-.5),point$$module$build$src$core$utils$svg_paths(75,8.7)]),c=curve$$module$build$src$core$utils$svg_paths("c",
[point$$module$build$src$core$utils$svg_paths(17.8,-9.2),point$$module$build$src$core$utils$svg_paths(45.3,-14.9),point$$module$build$src$core$utils$svg_paths(75,-8.7)])+moveTo$$module$build$src$core$utils$svg_paths(100.5,a+.5);return{path(d){return d?b:c}}}},module$build$src$core$renderers$geras$highlight_constants={};module$build$src$core$renderers$geras$highlight_constants.HighlightConstantProvider=HighlightConstantProvider$$module$build$src$core$renderers$geras$highlight_constants;var InlineInput$$module$build$src$core$renderers$geras$measurables$inline_input=class extends InlineInput$$module$build$src$core$renderers$measurables$inline_input{constructor(a,b){super(a,b);this.constants_=a;this.connectedBlock&&(this.width+=this.constants_.DARK_PATH_OFFSET,this.height+=this.constants_.DARK_PATH_OFFSET)}},module$build$src$core$renderers$geras$measurables$inline_input={};module$build$src$core$renderers$geras$measurables$inline_input.InlineInput=InlineInput$$module$build$src$core$renderers$geras$measurables$inline_input;var StatementInput$$module$build$src$core$renderers$geras$measurables$statement_input=class extends StatementInput$$module$build$src$core$renderers$measurables$statement_input{constructor(a,b){super(a,b);this.constants_=a;this.connectedBlock&&(this.height+=this.constants_.DARK_PATH_OFFSET)}},module$build$src$core$renderers$geras$measurables$statement_input={};module$build$src$core$renderers$geras$measurables$statement_input.StatementInput=StatementInput$$module$build$src$core$renderers$geras$measurables$statement_input;var RenderInfo$$module$build$src$core$renderers$geras$info=class extends RenderInfo$$module$build$src$core$renderers$common$info{constructor(a,b){super(a,b);this.renderer_=a}getRenderer(){return this.renderer_}populateBottomRow_(){super.populateBottomRow_();this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof StatementInput$$module$build$src$core$inputs$statement_input||(this.bottomRow.minHeight=this.constants_.MEDIUM_PADDING-this.constants_.DARK_PATH_OFFSET)}addInput_(a,
b){if(this.isInline&&a instanceof $.ValueInput$$module$build$src$core$inputs$value_input)b.elements.push(new InlineInput$$module$build$src$core$renderers$geras$measurables$inline_input(this.constants_,a)),b.hasInlineInput=!0;else if(a instanceof StatementInput$$module$build$src$core$inputs$statement_input)b.elements.push(new StatementInput$$module$build$src$core$renderers$geras$measurables$statement_input(this.constants_,a)),b.hasStatement=!0;else if(a instanceof $.ValueInput$$module$build$src$core$inputs$value_input)b.elements.push(new ExternalValueInput$$module$build$src$core$renderers$measurables$external_value_input(this.constants_,
a)),b.hasExternalInput=!0;else if(a instanceof DummyInput$$module$build$src$core$inputs$dummy_input||a instanceof EndRowInput$$module$build$src$core$inputs$end_row_input)b.minHeight=Math.max(b.minHeight,this.constants_.DUMMY_INPUT_MIN_HEIGHT),b.hasDummyInput=!0;this.isInline||b.align!==null||(b.align=a.align)}addElemSpacing_(){let a=!1;for(let c=0,d;d=this.rows[c];c++)d.hasExternalInput&&(a=!0);for(let c=0,d;d=this.rows[c];c++){var b=d.elements;d.elements=[];d.startsWithElemSpacer()&&d.elements.push(new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,
this.getInRowSpacing_(null,b[0])));if(b.length){for(let e=0;e<b.length-1;e++){d.elements.push(b[e]);const f=this.getInRowSpacing_(b[e],b[e+1]);d.elements.push(new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,f))}d.elements.push(b[b.length-1]);d.endsWithElemSpacer()&&(b=this.getInRowSpacing_(b[b.length-1],null),a&&d.hasDummyInput&&(b+=this.constants_.TAB_WIDTH),d.elements.push(new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,
b)))}}}getInRowSpacing_(a,b){if(!a)return b&&Types$$module$build$src$core$renderers$measurables$types.isField(b)&&b.isEditable?this.constants_.MEDIUM_PADDING:b&&Types$$module$build$src$core$renderers$measurables$types.isInlineInput(b)?this.constants_.MEDIUM_LARGE_PADDING:b&&Types$$module$build$src$core$renderers$measurables$types.isStatementInput(b)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:this.constants_.LARGE_PADDING;if(!Types$$module$build$src$core$renderers$measurables$types.isInput(a)&&(!b||
Types$$module$build$src$core$renderers$measurables$types.isStatementInput(b)))return Types$$module$build$src$core$renderers$measurables$types.isField(a)&&a.isEditable?a.width===0?this.constants_.NO_PADDING:this.constants_.MEDIUM_PADDING:Types$$module$build$src$core$renderers$measurables$types.isIcon(a)?this.constants_.LARGE_PADDING*2+1:Types$$module$build$src$core$renderers$measurables$types.isHat(a)?this.constants_.NO_PADDING:Types$$module$build$src$core$renderers$measurables$types.isPreviousOrNextConnection(a)?
this.constants_.LARGE_PADDING:Types$$module$build$src$core$renderers$measurables$types.isLeftRoundedCorner(a)?this.constants_.MIN_BLOCK_WIDTH:Types$$module$build$src$core$renderers$measurables$types.isJaggedEdge(a)?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isInput(a)&&!b){if(Types$$module$build$src$core$renderers$measurables$types.isExternalInput(a))return this.constants_.NO_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isInlineInput(a))return this.constants_.LARGE_PADDING;
if(Types$$module$build$src$core$renderers$measurables$types.isStatementInput(a))return this.constants_.NO_PADDING}if(!Types$$module$build$src$core$renderers$measurables$types.isInput(a)&&b&&Types$$module$build$src$core$renderers$measurables$types.isInput(b)){if(Types$$module$build$src$core$renderers$measurables$types.isField(a)&&a.isEditable){if(Types$$module$build$src$core$renderers$measurables$types.isInlineInput(b)||Types$$module$build$src$core$renderers$measurables$types.isExternalInput(b))return this.constants_.SMALL_PADDING}else{if(Types$$module$build$src$core$renderers$measurables$types.isInlineInput(b)||
Types$$module$build$src$core$renderers$measurables$types.isExternalInput(b))return this.constants_.MEDIUM_LARGE_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isStatementInput(b))return this.constants_.LARGE_PADDING}return this.constants_.LARGE_PADDING-1}if(Types$$module$build$src$core$renderers$measurables$types.isIcon(a)&&b&&!Types$$module$build$src$core$renderers$measurables$types.isInput(b))return this.constants_.LARGE_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isInlineInput(a)&&
b&&Types$$module$build$src$core$renderers$measurables$types.isField(b))return b.isEditable?this.constants_.MEDIUM_PADDING:this.constants_.LARGE_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isLeftSquareCorner(a)&&b){if(Types$$module$build$src$core$renderers$measurables$types.isHat(b))return this.constants_.NO_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isPreviousConnection(b))return b.notchOffset;if(Types$$module$build$src$core$renderers$measurables$types.isNextConnection(b))return b.notchOffset+
(this.RTL?1:-1)*this.constants_.DARK_PATH_OFFSET/2}if(Types$$module$build$src$core$renderers$measurables$types.isLeftRoundedCorner(a)&&b){if(Types$$module$build$src$core$renderers$measurables$types.isPreviousConnection(b))return b.notchOffset-this.constants_.CORNER_RADIUS;if(Types$$module$build$src$core$renderers$measurables$types.isNextConnection(b))return b.notchOffset-this.constants_.CORNER_RADIUS+(this.RTL?1:-1)*this.constants_.DARK_PATH_OFFSET/2}return Types$$module$build$src$core$renderers$measurables$types.isField(a)&&
b&&Types$$module$build$src$core$renderers$measurables$types.isField(b)&&a.isEditable===b.isEditable?a.width===0?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING:b&&Types$$module$build$src$core$renderers$measurables$types.isJaggedEdge(b)?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING}getSpacerRowHeight_(a,b){return Types$$module$build$src$core$renderers$measurables$types.isTopRow(a)&&Types$$module$build$src$core$renderers$measurables$types.isBottomRow(b)?this.constants_.EMPTY_BLOCK_SPACER_HEIGHT:
Types$$module$build$src$core$renderers$measurables$types.isTopRow(a)||Types$$module$build$src$core$renderers$measurables$types.isBottomRow(b)?this.constants_.NO_PADDING:a.hasExternalInput&&b.hasExternalInput?this.constants_.LARGE_PADDING:!a.hasStatement&&b.hasStatement?this.constants_.BETWEEN_STATEMENT_PADDING_Y:a.hasStatement&&b.hasStatement||!a.hasStatement&&b.hasDummyInput||a.hasDummyInput?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING}getElemCenterline_(a,b){if(Types$$module$build$src$core$renderers$measurables$types.isSpacer(b))return a.yPos+
b.height/2;if(Types$$module$build$src$core$renderers$measurables$types.isBottomRow(a))return a=a.yPos+a.height-a.descenderHeight,Types$$module$build$src$core$renderers$measurables$types.isNextConnection(b)?a+b.height/2:a-b.height/2;if(Types$$module$build$src$core$renderers$measurables$types.isTopRow(a))return Types$$module$build$src$core$renderers$measurables$types.isHat(b)?a.capline-b.height/2:a.capline+b.height/2;let c=a.yPos;Types$$module$build$src$core$renderers$measurables$types.isField(b)||
Types$$module$build$src$core$renderers$measurables$types.isIcon(b)?(c+=b.height/2,(a.hasInlineInput||a.hasStatement)&&b.height+this.constants_.TALL_INPUT_FIELD_OFFSET_Y<=a.height&&(c+=this.constants_.TALL_INPUT_FIELD_OFFSET_Y)):c=Types$$module$build$src$core$renderers$measurables$types.isInlineInput(b)?c+b.height/2:c+a.height/2;return c}alignRowElements_(){if(this.isInline){var a=0,b=new WeakMap,c=null;for(let d=this.rows.length-1,e;e=this.rows[d];d--)b.set(e,a),Types$$module$build$src$core$renderers$measurables$types.isInputRow(e)&&
(e.hasStatement&&this.alignStatementRow_(e),c&&c.hasStatement&&e.width<c.width?b.set(e,c.width):a=e.hasStatement?e.width:Math.max(a,e.width),c=e);a=0;for(let d=0,e;e=this.rows[d];d++)e.hasStatement?a=this.getDesiredRowWidth_(e):Types$$module$build$src$core$renderers$measurables$types.isSpacer(e)?e.width=Math.max(a,b.get(e)):(c=e.width,a=Math.max(a,b.get(e))-c,a>0&&this.addAlignmentPadding_(e,a),a=e.width)}else super.alignRowElements_()}getDesiredRowWidth_(a){return this.isInline&&a.hasStatement?this.statementEdge+
this.constants_.MAX_BOTTOM_WIDTH+this.startX:super.getDesiredRowWidth_(a)}finalize_(){let a=0,b=0;for(let d=0,e;e=this.rows[d];d++){e.yPos=b;e.xPos=this.startX;b+=e.height;a=Math.max(a,e.widthWithConnectedBlocks);var c=b-this.topRow.ascenderHeight;e===this.bottomRow&&c<this.constants_.MIN_BLOCK_HEIGHT&&(c=this.constants_.MIN_BLOCK_HEIGHT-c,this.bottomRow.height+=c,b+=c);this.recordElemPositions_(e)}this.outputConnection&&this.block_.nextConnection&&this.block_.nextConnection.isConnected()&&(c=this.block_.nextConnection.targetBlock())&&
(a=Math.max(a,c.getHeightWidth().width-this.constants_.DARK_PATH_OFFSET));this.bottomRow.baseline=b-this.bottomRow.descenderHeight;this.widthWithChildren=a+this.startX+this.constants_.DARK_PATH_OFFSET;this.width+=this.constants_.DARK_PATH_OFFSET;this.height=b+this.constants_.DARK_PATH_OFFSET;this.startY=this.topRow.capline}},module$build$src$core$renderers$geras$info={};module$build$src$core$renderers$geras$info.RenderInfo=RenderInfo$$module$build$src$core$renderers$geras$info;var PathObject$$module$build$src$core$renderers$geras$path_object=class extends PathObject$$module$build$src$core$renderers$common$path_object{constructor(a,b,c){super(a,b,c);this.constants=c;this.colourDark="#000000";this.svgPathDark=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,{"class":"blocklyPathDark",transform:"translate(1,1)"});this.svgRoot.insertBefore(this.svgPathDark,this.svgPath);this.svgPathLight=createSvgElement$$module$build$src$core$utils$dom(Svg$$module$build$src$core$utils$svg.PATH,
{"class":"blocklyPathLight"},this.svgRoot)}setPath(a){this.svgPath.setAttribute("d",a);this.svgPathDark.setAttribute("d",a)}setHighlightPath(a){this.svgPathLight.setAttribute("d",a)}flipRTL(){this.svgPath.setAttribute("transform","scale(-1 1)");this.svgPathLight.setAttribute("transform","scale(-1 1)");this.svgPathDark.setAttribute("transform","translate(1,1) scale(-1 1)")}applyColour(a){this.svgPathLight.style.display="";this.svgPathDark.style.display="";if(!this.style.colourTertiary)throw Error("The renderer did not properly initialize the tertiary colour of the block style");
this.svgPathLight.setAttribute("stroke",this.style.colourTertiary);this.svgPathDark.setAttribute("fill",this.colourDark);super.applyColour(a);this.svgPath.setAttribute("stroke","none")}setStyle(a){this.style=a;this.colourDark=blend$$module$build$src$core$utils$colour("#000",this.style.colourPrimary,.2)||this.colourDark}updateHighlighted(a){super.updateHighlighted(a);this.svgPathLight.style.display=a?"none":"inline"}updateShadow_(a){if(a){this.svgPathLight.style.display="none";if(!this.style.colourSecondary)throw Error("The renderer did not properly initialize the secondary colour of the block style block style");
this.svgPathDark.setAttribute("fill",this.style.colourSecondary);this.svgPath.setAttribute("stroke","none");this.svgPath.setAttribute("fill",this.style.colourSecondary)}}updateDisabled_(a){super.updateDisabled_(a);a&&this.svgPath.setAttribute("stroke","none")}},module$build$src$core$renderers$geras$path_object={};module$build$src$core$renderers$geras$path_object.PathObject=PathObject$$module$build$src$core$renderers$geras$path_object;var Renderer$$module$build$src$core$renderers$geras$renderer=class extends Renderer$$module$build$src$core$renderers$common$renderer{constructor(a){super(a);this.highlightConstants=null}init(a,b){super.init(a,b);this.highlightConstants=this.makeHighlightConstants_();this.highlightConstants.init()}refreshDom(a,b,c){super.refreshDom(a,b,c);this.getHighlightConstants().init()}makeConstants_(){return new ConstantProvider$$module$build$src$core$renderers$geras$constants}makeRenderInfo_(a){return new RenderInfo$$module$build$src$core$renderers$geras$info(this,
a)}makeDrawer_(a,b){return new Drawer$$module$build$src$core$renderers$geras$drawer(a,b)}makePathObject(a,b){return new PathObject$$module$build$src$core$renderers$geras$path_object(a,b,this.getConstants())}makeHighlightConstants_(){return new HighlightConstantProvider$$module$build$src$core$renderers$geras$highlight_constants(this.getConstants())}getHighlightConstants(){if(!this.highlightConstants)throw Error("Cannot access the highlight constants because init has not been called");return this.highlightConstants}};
register$$module$build$src$core$renderers$common$block_rendering("geras",Renderer$$module$build$src$core$renderers$geras$renderer);var module$build$src$core$renderers$geras$renderer={};module$build$src$core$renderers$geras$renderer.Renderer=Renderer$$module$build$src$core$renderers$geras$renderer;var module$build$src$core$renderers$geras$geras={};module$build$src$core$renderers$geras$geras.ConstantProvider=ConstantProvider$$module$build$src$core$renderers$geras$constants;module$build$src$core$renderers$geras$geras.Drawer=Drawer$$module$build$src$core$renderers$geras$drawer;module$build$src$core$renderers$geras$geras.HighlightConstantProvider=HighlightConstantProvider$$module$build$src$core$renderers$geras$highlight_constants;module$build$src$core$renderers$geras$geras.Highlighter=Highlighter$$module$build$src$core$renderers$geras$highlighter;
module$build$src$core$renderers$geras$geras.InlineInput=InlineInput$$module$build$src$core$renderers$geras$measurables$inline_input;module$build$src$core$renderers$geras$geras.PathObject=PathObject$$module$build$src$core$renderers$geras$path_object;module$build$src$core$renderers$geras$geras.RenderInfo=RenderInfo$$module$build$src$core$renderers$geras$info;module$build$src$core$renderers$geras$geras.Renderer=Renderer$$module$build$src$core$renderers$geras$renderer;
module$build$src$core$renderers$geras$geras.StatementInput=StatementInput$$module$build$src$core$renderers$geras$measurables$statement_input;var RenderInfo$$module$build$src$core$renderers$thrasos$info=class extends RenderInfo$$module$build$src$core$renderers$common$info{constructor(a,b){super(a,b)}getRenderer(){return this.renderer_}addElemSpacing_(){let a=!1;for(var b=0;b<this.rows.length;b++)if(this.rows[b].hasExternalInput){a=!0;break}for(b=0;b<this.rows.length;b++){const d=this.rows[b];var c=d.elements;d.elements=[];d.startsWithElemSpacer()&&d.elements.push(new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,
this.getInRowSpacing_(null,c[0])));if(c.length){for(let e=0;e<c.length-1;e++){d.elements.push(c[e]);const f=this.getInRowSpacing_(c[e],c[e+1]);d.elements.push(new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,f))}d.elements.push(c[c.length-1]);d.endsWithElemSpacer()&&(c=this.getInRowSpacing_(c[c.length-1],null),a&&d.hasDummyInput&&(c+=this.constants_.TAB_WIDTH),d.elements.push(new InRowSpacer$$module$build$src$core$renderers$measurables$in_row_spacer(this.constants_,
c)))}}}getInRowSpacing_(a,b){if(!a)return b&&Types$$module$build$src$core$renderers$measurables$types.isField(b)&&b.isEditable?this.constants_.MEDIUM_PADDING:b&&Types$$module$build$src$core$renderers$measurables$types.isInlineInput(b)?this.constants_.MEDIUM_LARGE_PADDING:b&&Types$$module$build$src$core$renderers$measurables$types.isStatementInput(b)?this.constants_.STATEMENT_INPUT_PADDING_LEFT:this.constants_.LARGE_PADDING;if(!Types$$module$build$src$core$renderers$measurables$types.isInput(a)&&!b)return Types$$module$build$src$core$renderers$measurables$types.isField(a)&&
a.isEditable?a.width===0?this.constants_.NO_PADDING:this.constants_.MEDIUM_PADDING:Types$$module$build$src$core$renderers$measurables$types.isIcon(a)?this.constants_.LARGE_PADDING*2+1:Types$$module$build$src$core$renderers$measurables$types.isHat(a)?this.constants_.NO_PADDING:Types$$module$build$src$core$renderers$measurables$types.isPreviousOrNextConnection(a)?this.constants_.LARGE_PADDING:Types$$module$build$src$core$renderers$measurables$types.isLeftRoundedCorner(a)?this.constants_.MIN_BLOCK_WIDTH:
Types$$module$build$src$core$renderers$measurables$types.isJaggedEdge(a)?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isInput(a)&&!b){if(Types$$module$build$src$core$renderers$measurables$types.isExternalInput(a))return this.constants_.NO_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isInlineInput(a))return this.constants_.LARGE_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isStatementInput(a))return this.constants_.NO_PADDING}if(!Types$$module$build$src$core$renderers$measurables$types.isInput(a)&&
b&&Types$$module$build$src$core$renderers$measurables$types.isInput(b)){if(Types$$module$build$src$core$renderers$measurables$types.isField(a)&&a.isEditable){if(Types$$module$build$src$core$renderers$measurables$types.isInlineInput(b)||Types$$module$build$src$core$renderers$measurables$types.isExternalInput(b))return this.constants_.SMALL_PADDING}else{if(Types$$module$build$src$core$renderers$measurables$types.isInlineInput(b)||Types$$module$build$src$core$renderers$measurables$types.isExternalInput(b))return this.constants_.MEDIUM_LARGE_PADDING;
if(Types$$module$build$src$core$renderers$measurables$types.isStatementInput(b))return this.constants_.LARGE_PADDING}return this.constants_.LARGE_PADDING-1}if(Types$$module$build$src$core$renderers$measurables$types.isIcon(a)&&b&&!Types$$module$build$src$core$renderers$measurables$types.isInput(b))return this.constants_.LARGE_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isInlineInput(a)&&b&&Types$$module$build$src$core$renderers$measurables$types.isField(b))return b.isEditable?
this.constants_.MEDIUM_PADDING:this.constants_.LARGE_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isLeftSquareCorner(a)&&b){if(Types$$module$build$src$core$renderers$measurables$types.isHat(b))return this.constants_.NO_PADDING;if(Types$$module$build$src$core$renderers$measurables$types.isPreviousConnection(b)||Types$$module$build$src$core$renderers$measurables$types.isNextConnection(b))return b.notchOffset}return Types$$module$build$src$core$renderers$measurables$types.isLeftRoundedCorner(a)&&
b?b.notchOffset-this.constants_.CORNER_RADIUS:Types$$module$build$src$core$renderers$measurables$types.isField(a)&&b&&Types$$module$build$src$core$renderers$measurables$types.isField(b)&&a.isEditable===b.isEditable?a.width===0?this.constants_.NO_PADDING:this.constants_.LARGE_PADDING:b&&Types$$module$build$src$core$renderers$measurables$types.isJaggedEdge(b)?this.constants_.LARGE_PADDING:this.constants_.MEDIUM_PADDING}getSpacerRowHeight_(a,b){return Types$$module$build$src$core$renderers$measurables$types.isTopRow(a)&&
Types$$module$build$src$core$renderers$measurables$types.isBottomRow(b)?this.constants_.EMPTY_BLOCK_SPACER_HEIGHT:Types$$module$build$src$core$renderers$measurables$types.isTopRow(a)||Types$$module$build$src$core$renderers$measurables$types.isBottomRow(b)?this.constants_.NO_PADDING:a.hasExternalInput&&b.hasExternalInput?this.constants_.LARGE_PADDING:!a.hasStatement&&b.hasStatement?this.constants_.BETWEEN_STATEMENT_PADDING_Y:a.hasStatement&&b.hasStatement||a.hasDummyInput||b.hasDummyInput?this.constants_.LARGE_PADDING:
this.constants_.MEDIUM_PADDING}getElemCenterline_(a,b){if(Types$$module$build$src$core$renderers$measurables$types.isSpacer(b))return a.yPos+b.height/2;if(Types$$module$build$src$core$renderers$measurables$types.isBottomRow(a))return a=a.yPos+a.height-a.descenderHeight,Types$$module$build$src$core$renderers$measurables$types.isNextConnection(b)?a+b.height/2:a-b.height/2;if(Types$$module$build$src$core$renderers$measurables$types.isTopRow(a))return Types$$module$build$src$core$renderers$measurables$types.isHat(b)?
a.capline-b.height/2:a.capline+b.height/2;let c=a.yPos;return c=Types$$module$build$src$core$renderers$measurables$types.isField(b)&&a.hasStatement?c+(this.constants_.TALL_INPUT_FIELD_OFFSET_Y+b.height/2):c+a.height/2}finalize_(){let a=0,b=0;for(var c=0;c<this.rows.length;c++){const e=this.rows[c];e.yPos=b;e.xPos=this.startX;b+=e.height;a=Math.max(a,e.widthWithConnectedBlocks);var d=b-this.topRow.ascenderHeight;e===this.bottomRow&&d<this.constants_.MIN_BLOCK_HEIGHT&&(d=this.constants_.MIN_BLOCK_HEIGHT-
d,this.bottomRow.height+=d,b+=d);this.recordElemPositions_(e)}this.outputConnection&&this.block_.nextConnection&&this.block_.nextConnection.isConnected()&&(c=this.block_.nextConnection.targetBlock())&&(a=Math.max(a,c.getHeightWidth().width));this.bottomRow.baseline=b-this.bottomRow.descenderHeight;this.widthWithChildren=a+this.startX;this.height=b;this.startY=this.topRow.capline}},module$build$src$core$renderers$thrasos$info={};module$build$src$core$renderers$thrasos$info.RenderInfo=RenderInfo$$module$build$src$core$renderers$thrasos$info;var Renderer$$module$build$src$core$renderers$thrasos$renderer=class extends Renderer$$module$build$src$core$renderers$common$renderer{constructor(a){super(a)}makeRenderInfo_(a){return new RenderInfo$$module$build$src$core$renderers$thrasos$info(this,a)}};register$$module$build$src$core$renderers$common$block_rendering("thrasos",Renderer$$module$build$src$core$renderers$thrasos$renderer);var module$build$src$core$renderers$thrasos$renderer={};
module$build$src$core$renderers$thrasos$renderer.Renderer=Renderer$$module$build$src$core$renderers$thrasos$renderer;var module$build$src$core$renderers$thrasos$thrasos={};module$build$src$core$renderers$thrasos$thrasos.RenderInfo=RenderInfo$$module$build$src$core$renderers$thrasos$info;module$build$src$core$renderers$thrasos$thrasos.Renderer=Renderer$$module$build$src$core$renderers$thrasos$renderer;var defaultBlockStyles$$module$build$src$core$theme$zelos={colour_blocks:{colourPrimary:"#CF63CF",colourSecondary:"#C94FC9",colourTertiary:"#BD42BD"},list_blocks:{colourPrimary:"#9966FF",colourSecondary:"#855CD6",colourTertiary:"#774DCB"},logic_blocks:{colourPrimary:"#4C97FF",colourSecondary:"#4280D7",colourTertiary:"#3373CC"},loop_blocks:{colourPrimary:"#0fBD8C",colourSecondary:"#0DA57A",colourTertiary:"#0B8E69"},math_blocks:{colourPrimary:"#59C059",colourSecondary:"#46B946",colourTertiary:"#389438"},
procedure_blocks:{colourPrimary:"#FF6680",colourSecondary:"#FF4D6A",colourTertiary:"#FF3355"},text_blocks:{colourPrimary:"#FFBF00",colourSecondary:"#E6AC00",colourTertiary:"#CC9900"},variable_blocks:{colourPrimary:"#FF8C1A",colourSecondary:"#FF8000",colourTertiary:"#DB6E00"},variable_dynamic_blocks:{colourPrimary:"#FF8C1A",colourSecondary:"#FF8000",colourTertiary:"#DB6E00"},hat_blocks:{colourPrimary:"#4C97FF",colourSecondary:"#4280D7",colourTertiary:"#3373CC",hat:"cap"}},categoryStyles$$module$build$src$core$theme$zelos=
{colour_category:{colour:"#CF63CF"},list_category:{colour:"#9966FF"},logic_category:{colour:"#4C97FF"},loop_category:{colour:"#0fBD8C"},math_category:{colour:"#59C059"},procedure_category:{colour:"#FF6680"},text_category:{colour:"#FFBF00"},variable_category:{colour:"#FF8C1A"},variable_dynamic_category:{colour:"#FF8C1A"}},Zelos$$module$build$src$core$theme$zelos=new Theme$$module$build$src$core$theme("zelos",defaultBlockStyles$$module$build$src$core$theme$zelos,categoryStyles$$module$build$src$core$theme$zelos),
module$build$src$core$theme$zelos={Zelos:Zelos$$module$build$src$core$theme$zelos};var module$build$src$core$theme$themes={Classic:Classic$$module$build$src$core$theme$classic,Zelos:Zelos$$module$build$src$core$theme$zelos};var ToolboxItem$$module$build$src$core$toolbox$toolbox_item=class{constructor(a,b,c){this.id_=a.toolboxitemid||getNextUniqueId$$module$build$src$core$utils$idgenerator();this.level_=(this.parent_=c||null)?this.parent_.getLevel()+1:0;this.toolboxItemDef_=a;this.parentToolbox_=b;this.workspace_=this.parentToolbox_.getWorkspace()}init(){}getDiv(){return null}getClickTarget(){return null}getId(){return this.id_}getParent(){return null}getLevel(){return this.level_}isSelectable(){return!1}isCollapsible(){return!1}dispose(){}setVisible_(a){}getFocusableElement(){const a=
this.getDiv();if(!a)throw Error("Trying to access toolbox item before DOM is initialized.");if(!(a instanceof HTMLElement))throw Error("Toolbox item div is unexpectedly not an HTML element.");return a}getFocusableTree(){return this.parentToolbox_}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!0}},module$build$src$core$toolbox$toolbox_item={};module$build$src$core$toolbox$toolbox_item.ToolboxItem=ToolboxItem$$module$build$src$core$toolbox$toolbox_item;var ToolboxCategory$$module$build$src$core$toolbox$category=class extends ToolboxItem$$module$build$src$core$toolbox$toolbox_item{constructor(a,b,c){super(a,b,c);this.colour_=this.name_="";this.labelDom_=this.iconDom_=this.rowContents_=this.rowDiv_=this.htmlDiv_=null;this.isDisabled_=this.isHidden_=!1;this.flyoutItems_=[];this.cssConfig_=this.makeDefaultCssConfig_()}init(){this.parseCategoryDef_(this.toolboxItemDef_);this.parseContents_(this.toolboxItemDef_);this.createDom_();this.toolboxItemDef_.hidden===
"true"&&this.hide()}makeDefaultCssConfig_(){return{container:"blocklyToolboxCategoryContainer",row:"blocklyToolboxCategory",rowcontentcontainer:"blocklyTreeRowContentContainer",icon:"blocklyToolboxCategoryIcon",label:"blocklyToolboxCategoryLabel",contents:"blocklyToolboxCategoryGroup",selected:"blocklyToolboxSelected",openicon:"blocklyToolboxCategoryIconOpen",closedicon:"blocklyToolboxCategoryIconClosed"}}parseContents_(a){if("custom"in a)this.flyoutItems_=a.custom;else if(a=a.contents)for(let b=
0;b<a.length;b++){const c=a[b];Array.isArray(this.flyoutItems_)&&this.flyoutItems_.push(c)}}parseCategoryDef_(a){this.name_="name"in a?replaceMessageReferences$$module$build$src$core$utils$parsing(a.name):"";this.colour_=this.getColour_(a);Object.assign(this.cssConfig_,a.cssconfig||a.cssConfig)}createDom_(){this.htmlDiv_=this.createContainer_();setRole$$module$build$src$core$utils$aria(this.htmlDiv_,Role$$module$build$src$core$utils$aria.TREEITEM);setState$$module$build$src$core$utils$aria(this.htmlDiv_,
State$$module$build$src$core$utils$aria.SELECTED,!1);setState$$module$build$src$core$utils$aria(this.htmlDiv_,State$$module$build$src$core$utils$aria.LEVEL,this.level_+1);this.rowDiv_=this.createRowContainer_();this.rowDiv_.style.pointerEvents="auto";this.htmlDiv_.appendChild(this.rowDiv_);this.rowContents_=this.createRowContentsContainer_();this.rowContents_.style.pointerEvents="none";this.rowDiv_.appendChild(this.rowContents_);this.iconDom_=this.createIconDom_();setRole$$module$build$src$core$utils$aria(this.iconDom_,
Role$$module$build$src$core$utils$aria.PRESENTATION);this.rowContents_.appendChild(this.iconDom_);this.labelDom_=this.createLabelDom_(this.name_);this.rowContents_.appendChild(this.labelDom_);const a=this.labelDom_.getAttribute("id");a&&setState$$module$build$src$core$utils$aria(this.htmlDiv_,State$$module$build$src$core$utils$aria.LABELLEDBY,a);this.addColourBorder_(this.colour_);return this.htmlDiv_}createContainer_(){const a=document.createElement("div");a.tabIndex=-1;a.id=this.getId();const b=
this.cssConfig_.container;b&&addClass$$module$build$src$core$utils$dom(a,b);return a}createRowContainer_(){const a=document.createElement("div");var b=this.cssConfig_.row;b&&addClass$$module$build$src$core$utils$dom(a,b);b=`${ToolboxCategory$$module$build$src$core$toolbox$category.nestedPadding*this.getLevel()}px`;this.workspace_.RTL?a.style.paddingRight=b:a.style.paddingLeft=b;return a}createRowContentsContainer_(){const a=document.createElement("div"),b=this.cssConfig_.rowcontentcontainer;b&&addClass$$module$build$src$core$utils$dom(a,
b);return a}createIconDom_(){const a=document.createElement("span");if(!this.parentToolbox_.isHorizontal()){const b=this.cssConfig_.icon;b&&addClass$$module$build$src$core$utils$dom(a,b)}a.style.display="inline-block";return a}createLabelDom_(a){const b=document.createElement("span");b.setAttribute("id",this.getId()+".label");b.textContent=a;(a=this.cssConfig_.label)&&addClass$$module$build$src$core$utils$dom(b,a);return b}refreshTheme(){this.colour_=this.getColour_(this.toolboxItemDef_);this.addColourBorder_(this.colour_)}addColourBorder_(a){a&&
(a=ToolboxCategory$$module$build$src$core$toolbox$category.borderWidth+"px solid "+(a||"#ddd"),this.workspace_.RTL?this.rowDiv_.style.borderRight=a:this.rowDiv_.style.borderLeft=a)}getColour_(a){const b=a.categorystyle||a.categoryStyle;if((a=a.colour)&&b)console.warn('Toolbox category "'+this.name_+'" must not have both a style and a colour');else{if(b)return this.getColourfromStyle(b);if(a)return this.parseColour(a)}return""}getColourfromStyle(a){var b=this.workspace_.getTheme();if(a&&b){if((b=b.categoryStyles[a])&&
b.colour)return this.parseColour(b.colour);console.warn('Style "'+a+'" must exist and contain a colour value')}return""}getClickTarget(){return this.rowDiv_}parseColour(a){a=replaceMessageReferences$$module$build$src$core$utils$parsing(a);if(a==null||a==="")return"";var b=Number(a);if(isNaN(b)){if(b=parse$$module$build$src$core$utils$colour(a))return b;console.warn('Toolbox category "'+this.name_+'" has unrecognized colour attribute: '+a);return""}return hueToHex$$module$build$src$core$utils$colour(b)}openIcon_(a){if(a){var b=
this.cssConfig_.closedicon;b&&removeClasses$$module$build$src$core$utils$dom(a,b);(b=this.cssConfig_.openicon)&&addClass$$module$build$src$core$utils$dom(a,b)}}closeIcon_(a){if(a){var b=this.cssConfig_.openicon;b&&removeClasses$$module$build$src$core$utils$dom(a,b);(b=this.cssConfig_.closedicon)&&addClass$$module$build$src$core$utils$dom(a,b)}}setVisible_(a){this.htmlDiv_.style.display=a?"block":"none";this.isHidden_=!a;this.parentToolbox_.getSelectedItem()===this&&this.parentToolbox_.clearSelection()}hide(){this.setVisible_(!1)}show(){this.setVisible_(!0)}isVisible(){return!this.isHidden_&&
this.allAncestorsExpanded_()}allAncestorsExpanded_(){let a=this;for(;a.getParent();)if(a=a.getParent(),!a.isExpanded())return!1;return!0}isSelectable(){return this.isVisible()&&!this.isDisabled_}onClick(a){}setSelected(a){if(this.rowDiv_){var b=this.cssConfig_.selected;if(a){const c=this.parseColour(ToolboxCategory$$module$build$src$core$toolbox$category.defaultBackgroundColour);this.rowDiv_.style.backgroundColor=this.colour_||c;b&&addClass$$module$build$src$core$utils$dom(this.rowDiv_,b)}else this.rowDiv_.style.backgroundColor=
"",b&&removeClass$$module$build$src$core$utils$dom(this.rowDiv_,b);setState$$module$build$src$core$utils$aria(this.htmlDiv_,State$$module$build$src$core$utils$aria.SELECTED,a)}}setDisabled(a){this.isDisabled_=a;this.getDiv().setAttribute("disabled",`${a}`);a?this.getDiv().setAttribute("disabled","true"):this.getDiv().removeAttribute("disabled")}getName(){return this.name_}getParent(){return this.parent_}getDiv(){return this.htmlDiv_}getContents(){return this.flyoutItems_}updateFlyoutContents(a){this.flyoutItems_=
[];this.toolboxItemDef_=typeof a==="string"?{kind:this.toolboxItemDef_.kind,custom:a,id:this.toolboxItemDef_.id,categorystyle:this.toolboxItemDef_.categorystyle,colour:this.toolboxItemDef_.colour,cssconfig:this.toolboxItemDef_.cssconfig,hidden:this.toolboxItemDef_.hidden}:{kind:this.toolboxItemDef_.kind,name:"name"in this.toolboxItemDef_?this.toolboxItemDef_.name:"",contents:convertFlyoutDefToJsonArray$$module$build$src$core$utils$toolbox(a),id:this.toolboxItemDef_.id,categorystyle:this.toolboxItemDef_.categorystyle,
colour:this.toolboxItemDef_.colour,cssconfig:this.toolboxItemDef_.cssconfig,hidden:this.toolboxItemDef_.hidden};this.parseContents_(this.toolboxItemDef_)}dispose(){removeNode$$module$build$src$core$utils$dom(this.htmlDiv_)}};ToolboxCategory$$module$build$src$core$toolbox$category.registrationName="category";ToolboxCategory$$module$build$src$core$toolbox$category.nestedPadding=19;ToolboxCategory$$module$build$src$core$toolbox$category.borderWidth=8;
ToolboxCategory$$module$build$src$core$toolbox$category.defaultBackgroundColour="#57e";register$$module$build$src$core$css('\n.blocklyToolboxCategory:not(.blocklyToolboxSelected):hover {\n  background-color: rgba(255, 255, 255, .2);\n}\n\n.blocklyToolbox[layout="h"] .blocklyToolboxCategoryContainer {\n  margin: 1px 5px 1px 0;\n}\n\n.blocklyToolbox[dir="RTL"][layout="h"] .blocklyToolboxCategoryContainer {\n  margin: 1px 0 1px 5px;\n}\n\n.blocklyToolboxCategory {\n  height: 22px;\n  line-height: 22px;\n  margin-bottom: 3px;\n  padding-right: 8px;\n  white-space: nowrap;\n}\n\n.blocklyToolbox[dir="RTL"] .blocklyToolboxCategory {\n  margin-left: 8px;\n  padding-right: 0;\n}\n\n.blocklyToolboxCategoryIcon {\n  background-image: url(<<<PATH>>>/sprites.png);\n  height: 16px;\n  vertical-align: middle;\n  visibility: hidden;\n  width: 16px;\n}\n\n.blocklyToolboxCategoryIconClosed {\n  background-position: -32px -1px;\n}\n\n.blocklyToolbox[dir="RTL"] .blocklyToolboxCategoryIconClosed {\n  background-position: 0 -1px;\n}\n\n.blocklyToolboxSelected>.blocklyToolboxCategoryIconClosed {\n  background-position: -32px -17px;\n}\n\n.blocklyToolbox[dir="RTL"] .blocklyToolboxSelected>.blocklyToolboxCategoryIconClosed {\n  background-position: 0 -17px;\n}\n\n.blocklyToolboxCategoryIconOpen {\n  background-position: -16px -1px;\n}\n\n.blocklyToolboxSelected>.blocklyToolboxCategoryIconOpen {\n  background-position: -16px -17px;\n}\n\n.blocklyToolboxCategoryLabel {\n  cursor: default;\n  font: 16px sans-serif;\n  padding: 0 3px;\n  vertical-align: middle;\n}\n\n.blocklyToolboxDelete .blocklyToolboxCategoryLabel {\n  cursor: url("<<<PATH>>>/handdelete.cur"), auto;\n}\n\n.blocklyToolboxSelected .blocklyToolboxCategoryLabel {\n  color: #fff;\n}\n');
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.TOOLBOX_ITEM,ToolboxCategory$$module$build$src$core$toolbox$category.registrationName,ToolboxCategory$$module$build$src$core$toolbox$category);var module$build$src$core$toolbox$category={};module$build$src$core$toolbox$category.ToolboxCategory=ToolboxCategory$$module$build$src$core$toolbox$category;var ToolboxSeparator$$module$build$src$core$toolbox$separator=class extends ToolboxItem$$module$build$src$core$toolbox$toolbox_item{constructor(a,b){super(a,b);this.cssConfig_={container:"blocklyTreeSeparator"};this.htmlDiv=null;Object.assign(this.cssConfig_,a.cssconfig||a.cssConfig)}init(){this.createDom_()}createDom_(){const a=document.createElement("div");a.tabIndex=-1;a.id=this.getId();const b=this.cssConfig_.container;b&&addClass$$module$build$src$core$utils$dom(a,b);return this.htmlDiv=a}getDiv(){return this.htmlDiv}dispose(){removeNode$$module$build$src$core$utils$dom(this.htmlDiv)}};
ToolboxSeparator$$module$build$src$core$toolbox$separator.registrationName="sep";register$$module$build$src$core$css('\n.blocklyTreeSeparator {\n  border-bottom: solid #e5e5e5 1px;\n  height: 0;\n  margin: 5px 0;\n}\n\n.blocklyToolbox[layout="h"] .blocklyTreeSeparator {\n  border-right: solid #e5e5e5 1px;\n  border-bottom: none;\n  height: auto;\n  margin: 0 5px 0 5px;\n  padding: 5px 0;\n  width: 0;\n}\n');
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.TOOLBOX_ITEM,ToolboxSeparator$$module$build$src$core$toolbox$separator.registrationName,ToolboxSeparator$$module$build$src$core$toolbox$separator);var module$build$src$core$toolbox$separator={};module$build$src$core$toolbox$separator.ToolboxSeparator=ToolboxSeparator$$module$build$src$core$toolbox$separator;var CollapsibleToolboxCategory$$module$build$src$core$toolbox$collapsible_category=class extends ToolboxCategory$$module$build$src$core$toolbox$category{constructor(a,b,c){super(a,b,c);this.subcategoriesDiv_=null;this.expanded_=!1;this.toolboxItems_=[]}makeDefaultCssConfig_(){const a=super.makeDefaultCssConfig_();a.contents="blocklyToolboxCategoryGroup";return a}parseContents_(a){if("custom"in a)this.flyoutItems_=a.custom;else{const b=a.contents;if(b){this.flyoutItems_=[];a=!0;for(let c=0;c<b.length;c++){const d=
b[c];!hasItem$$module$build$src$core$registry(Type$$module$build$src$core$registry.TOOLBOX_ITEM,d.kind)||d.kind.toLowerCase()===ToolboxSeparator$$module$build$src$core$toolbox$separator.registrationName&&a?(this.flyoutItems_.push(d),a=!0):(this.createToolboxItem(d),a=!1)}}}}createToolboxItem(a){let b=a.kind;b.toUpperCase()==="CATEGORY"&&isCategoryCollapsible$$module$build$src$core$utils$toolbox(a)&&(b=CollapsibleToolboxCategory$$module$build$src$core$toolbox$collapsible_category.registrationName);
a=new (getClass$$module$build$src$core$registry(Type$$module$build$src$core$registry.TOOLBOX_ITEM,b))(a,this.parentToolbox_,this);this.toolboxItems_.push(a)}init(){super.init();this.setExpanded(this.toolboxItemDef_.expanded==="true"||this.toolboxItemDef_.expanded===!0)}createDom_(){super.createDom_();const a=this.getChildToolboxItems();this.subcategoriesDiv_=this.createSubCategoriesDom_(a);setRole$$module$build$src$core$utils$aria(this.subcategoriesDiv_,Role$$module$build$src$core$utils$aria.GROUP);
this.htmlDiv_.appendChild(this.subcategoriesDiv_);this.closeIcon_(this.iconDom_);setState$$module$build$src$core$utils$aria(this.htmlDiv_,State$$module$build$src$core$utils$aria.EXPANDED,!1);return this.htmlDiv_}createIconDom_(){const a=document.createElement("span");if(!this.parentToolbox_.isHorizontal()){const b=this.cssConfig_.icon;b&&addClass$$module$build$src$core$utils$dom(a,b);a.style.visibility="visible"}a.style.display="inline-block";return a}createSubCategoriesDom_(a){const b=document.createElement("div");
b.style.display="none";var c=this.cssConfig_.contents;c&&addClass$$module$build$src$core$utils$dom(b,c);for(c=0;c<a.length;c++){const d=a[c];d.init();const e=d.getDiv();b.appendChild(e);if(d.getClickTarget){let f;(f=d.getClickTarget())==null||f.setAttribute("id",d.getId())}}return b}setExpanded(a){if(this.expanded_!==a){if(this.expanded_=a)this.subcategoriesDiv_.style.display="block",this.openIcon_(this.iconDom_);else{let b;(b=this.parentToolbox_.getFlyout())==null||b.setVisible(!1);this.subcategoriesDiv_.style.display=
"none";this.closeIcon_(this.iconDom_)}setState$$module$build$src$core$utils$aria(this.htmlDiv_,State$$module$build$src$core$utils$aria.EXPANDED,a);this.parentToolbox_.handleToolboxItemResize()}}setVisible_(a){this.htmlDiv_.style.display=a?"block":"none";const b=this.getChildToolboxItems();for(let c=0;c<b.length;c++)b[c].setVisible_(a);this.isHidden_=!a;this.parentToolbox_.getSelectedItem()===this&&this.parentToolbox_.clearSelection()}isExpanded(){return this.expanded_}isCollapsible(){return!0}onClick(a){this.toggleExpanded()}toggleExpanded(){this.setExpanded(!this.expanded_)}getDiv(){return this.htmlDiv_}getChildToolboxItems(){return this.toolboxItems_}};
CollapsibleToolboxCategory$$module$build$src$core$toolbox$collapsible_category.registrationName="collapsibleCategory";register$$module$build$src$core$registry(Type$$module$build$src$core$registry.TOOLBOX_ITEM,CollapsibleToolboxCategory$$module$build$src$core$toolbox$collapsible_category.registrationName,CollapsibleToolboxCategory$$module$build$src$core$toolbox$collapsible_category);var module$build$src$core$toolbox$collapsible_category={};
module$build$src$core$toolbox$collapsible_category.CollapsibleToolboxCategory=CollapsibleToolboxCategory$$module$build$src$core$toolbox$collapsible_category;var module$build$src$core$interfaces$i_selectable_toolbox_item={};module$build$src$core$interfaces$i_selectable_toolbox_item.isSelectableToolboxItem=isSelectableToolboxItem$$module$build$src$core$interfaces$i_selectable_toolbox_item;var Toolbox$$module$build$src$core$toolbox$toolbox=class extends DeleteArea$$module$build$src$core$delete_area{constructor(a){super();this.id="toolbox";this.contentsDiv_=this.HtmlDiv=null;this.isVisible_=!1;this.height_=this.width_=0;this.flyout=null;this.contents=new Map;this.previouslySelectedItem_=this.selectedItem_=null;this.boundEvents_=[];this.workspace_=a;this.toolboxDef_=a.options.languageTree||{contents:[]};this.horizontalLayout=a.options.horizontalLayout;this.RTL=a.options.RTL;this.toolboxPosition=
a.options.toolboxPosition}onShortcut(a){return!1}init(){var a=this.workspace_;const b=a.getParentSvg();this.flyout=this.createFlyout_();this.HtmlDiv=this.createDom_(this.workspace_);const c=this.flyout.createDom("svg");addClass$$module$build$src$core$utils$dom(c,"blocklyToolboxFlyout");insertAfter$$module$build$src$core$utils$dom(c,b);this.setVisible(!0);this.flyout.init(a);this.render(this.toolboxDef_);a=a.getThemeManager();a.subscribe(this.HtmlDiv,"toolboxBackgroundColour","background-color");a.subscribe(this.HtmlDiv,
"toolboxForegroundColour","color");this.workspace_.getComponentManager().addComponent({component:this,weight:ComponentManager$$module$build$src$core$component_manager.ComponentWeight.TOOLBOX_WEIGHT,capabilities:[ComponentManager$$module$build$src$core$component_manager.Capability.AUTOHIDEABLE,ComponentManager$$module$build$src$core$component_manager.Capability.DELETE_AREA,ComponentManager$$module$build$src$core$component_manager.Capability.DRAG_TARGET]});$.getFocusManager$$module$build$src$core$focus_manager().registerTree(this,
!0)}createDom_(a){a=a.getParentSvg();const b=this.createContainer_();b.id=getNextUniqueId$$module$build$src$core$utils$idgenerator();this.contentsDiv_=this.createContentsContainer_();setRole$$module$build$src$core$utils$aria(this.contentsDiv_,Role$$module$build$src$core$utils$aria.TREE);b.appendChild(this.contentsDiv_);a.parentNode.insertBefore(b,a);this.attachEvents_(b,this.contentsDiv_);return b}createContainer_(){const a=document.createElement("div");a.setAttribute("layout",this.isHorizontal()?
"h":"v");addClass$$module$build$src$core$utils$dom(a,"blocklyToolbox");a.setAttribute("dir",this.RTL?"RTL":"LTR");return a}createContentsContainer_(){const a=document.createElement("div");addClass$$module$build$src$core$utils$dom(a,"blocklyToolboxCategoryGroup");this.isHorizontal()&&(a.style.flexDirection="row");return a}attachEvents_(a,b){a=conditionalBind$$module$build$src$core$browser_events(a,"pointerdown",this,this.onClick_,!1);this.boundEvents_.push(a);b=conditionalBind$$module$build$src$core$browser_events(b,
"keydown",this,this.onKeyDown_,!1);this.boundEvents_.push(b)}onClick_(a){if(isRightButton$$module$build$src$core$browser_events(a)||a.target===this.HtmlDiv)getMainWorkspace$$module$build$src$core$common().hideChaff(!1);else{var b=a.target.getAttribute("id");b&&(b=this.getToolboxItemById(b),b.isSelectable()&&(this.setSelectedItem(b),b.onClick(a)));getMainWorkspace$$module$build$src$core$common().hideChaff(!0)}clearTouchIdentifier$$module$build$src$core$touch()}onKeyDown_(a){let b=!1;switch(a.key){case "ArrowDown":b=
this.selectNext();break;case "ArrowUp":b=this.selectPrevious();break;case "ArrowLeft":b=this.selectParent();break;case "ArrowRight":b=this.selectChild();break;case "Enter":case " ":this.selectedItem_&&this.selectedItem_.isCollapsible()&&(this.selectedItem_.toggleExpanded(),b=!0);break;default:b=!1}!b&&this.selectedItem_&&this.selectedItem_.onKeyDown&&(b=this.selectedItem_.onKeyDown(a));b&&a.preventDefault()}createFlyout_(){const a=this.workspace_,b=a.copyOptionsForFlyout();b.toolboxPosition=a.options.toolboxPosition;
return new (a.horizontalLayout?getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUTS_HORIZONTAL_TOOLBOX,a.options,!0):getClassFromOptions$$module$build$src$core$registry(Type$$module$build$src$core$registry.FLYOUTS_VERTICAL_TOOLBOX,a.options,!0))(b)}render(a){this.toolboxDef_=a;this.contents.forEach(b=>b.dispose());this.contents.clear();this.renderContents_(a.contents);this.position();this.handleToolboxItemResize()}renderContents_(a){const b=document.createDocumentFragment();
for(let c=0;c<a.length;c++)this.createToolboxItem(a[c],b);this.contentsDiv_.appendChild(b)}createToolboxItem(a,b){var c=a.kind;c.toUpperCase()==="CATEGORY"&&isCategoryCollapsible$$module$build$src$core$utils$toolbox(a)&&(c=CollapsibleToolboxCategory$$module$build$src$core$toolbox$collapsible_category.registrationName);if(c=getClass$$module$build$src$core$registry(Type$$module$build$src$core$registry.TOOLBOX_ITEM,c.toLowerCase()))a=new c(a,this),a.init(),this.addToolboxItem_(a),(c=a.getDiv())&&b.appendChild(c),
a.getClickTarget()&&a.getClickTarget().setAttribute("id",a.getId())}addToolboxItem_(a){this.contents.set(a.getId(),a);if(a.isCollapsible()){a=a.getChildToolboxItems();for(let b=0;b<a.length;b++)this.addToolboxItem_(a[b])}}getToolboxItems(){return[...this.contents.values()]}addStyle(a){a&&this.HtmlDiv&&addClass$$module$build$src$core$utils$dom(this.HtmlDiv,a)}removeStyle(a){a&&this.HtmlDiv&&removeClass$$module$build$src$core$utils$dom(this.HtmlDiv,a)}getClientRect(){if(!this.HtmlDiv||!this.isVisible_)return null;
var a=this.HtmlDiv.getBoundingClientRect();const b=a.top,c=b+a.height,d=a.left;a=d+a.width;return this.toolboxPosition===Position$$module$build$src$core$utils$toolbox.TOP?new Rect$$module$build$src$core$utils$rect(-1E7,c,-1E7,1E7):this.toolboxPosition===Position$$module$build$src$core$utils$toolbox.BOTTOM?new Rect$$module$build$src$core$utils$rect(b,1E7,-1E7,1E7):this.toolboxPosition===Position$$module$build$src$core$utils$toolbox.LEFT?new Rect$$module$build$src$core$utils$rect(-1E7,1E7,-1E7,a):new Rect$$module$build$src$core$utils$rect(-1E7,
1E7,d,1E7)}wouldDelete(a){a instanceof BlockSvg$$module$build$src$core$block_svg?this.updateWouldDelete_(!a.getParent()&&a.isDeletable()):this.updateWouldDelete_(isDeletable$$module$build$src$core$interfaces$i_deletable(a)&&a.isDeletable());return this.wouldDelete_}onDragEnter(a){this.updateCursorDeleteStyle_(!0)}onDragExit(a){this.updateCursorDeleteStyle_(!1)}onDrop(a){this.updateCursorDeleteStyle_(!1)}updateWouldDelete_(a){a!==this.wouldDelete_&&(this.updateCursorDeleteStyle_(!1),this.wouldDelete_=
a,this.updateCursorDeleteStyle_(!0))}updateCursorDeleteStyle_(a){const b=this.wouldDelete_?"blocklyToolboxDelete":"blocklyToolboxGrab";a?this.addStyle(b):this.removeStyle(b)}getToolboxItemById(a){return this.contents.get(a)||null}getWidth(){return this.width_}getHeight(){return this.height_}getFlyout(){return this.flyout}getWorkspace(){return this.workspace_}getSelectedItem(){return this.selectedItem_}getPreviouslySelectedItem(){return this.previouslySelectedItem_}isHorizontal(){return this.horizontalLayout}position(){const a=
this.workspace_.getMetrics(),b=this.HtmlDiv;b&&(this.horizontalLayout?(b.style.left="0",b.style.height="auto",b.style.width="100%",this.height_=b.offsetHeight,this.width_=a.viewWidth,this.toolboxPosition===Position$$module$build$src$core$utils$toolbox.TOP?b.style.top="0":b.style.bottom="0"):(this.toolboxPosition===Position$$module$build$src$core$utils$toolbox.RIGHT?b.style.right="0":b.style.left="0",b.style.height="100%",this.width_=b.offsetWidth,this.height_=a.viewHeight),this.flyout.position())}handleToolboxItemResize(){const a=
this.workspace_;var b=this.HtmlDiv.getBoundingClientRect();const c=this.getFlyout(),d=this.toolboxPosition===Position$$module$build$src$core$utils$toolbox.LEFT?a.scrollX+b.width+((c==null?0:c.isVisible())?c.getWidth():0):a.scrollX;b=this.toolboxPosition===Position$$module$build$src$core$utils$toolbox.TOP?a.scrollY+b.height+((c==null?0:c.isVisible())?c.getHeight():0):a.scrollY;a.translate(d,b);svgResize$$module$build$src$core$common(a)}clearSelection(){this.setSelectedItem(null)}refreshTheme(){this.contents.forEach(a=>
{a.refreshTheme&&a.refreshTheme()})}refreshSelection(){this.selectedItem_&&this.selectedItem_.isSelectable()&&this.selectedItem_.getContents().length&&this.flyout.show(this.selectedItem_.getContents())}setVisible(a){this.isVisible_!==a&&(this.HtmlDiv.style.display=a?"block":"none",this.isVisible_=a,this.workspace_.recordDragTargets())}autoHide(a){!a&&this.flyout&&this.flyout.autoClose&&this.clearSelection()}setSelectedItem(a){const b=this.selectedItem_;!a&&!b||a&&!isSelectableToolboxItem$$module$build$src$core$interfaces$i_selectable_toolbox_item(a)||
(this.shouldDeselectItem_(b,a)&&b!==null&&this.deselectItem_(b),this.shouldSelectItem_(b,a)&&a!==null&&this.selectItem_(b,a),this.updateFlyout_(b,a),this.fireSelectEvent(b,a))}shouldDeselectItem_(a,b){return a!==null&&(!a.isCollapsible()||a!==b)}shouldSelectItem_(a,b){return b!==null&&b!==a}deselectItem_(a){this.selectedItem_=null;this.previouslySelectedItem_=a;a.setSelected(!1);setState$$module$build$src$core$utils$aria(this.contentsDiv_,State$$module$build$src$core$utils$aria.ACTIVEDESCENDANT,"")}selectItem_(a,
b){this.selectedItem_=b;this.previouslySelectedItem_=a;b.setSelected(!0);setState$$module$build$src$core$utils$aria(this.contentsDiv_,State$$module$build$src$core$utils$aria.ACTIVEDESCENDANT,b.getId())}selectItemByPosition(a){(a=this.getToolboxItems()[a])&&this.setSelectedItem(a)}updateFlyout_(a,b){b&&(a!==b||b.isCollapsible())&&b.getContents().length?(this.flyout.show(b.getContents()),this.flyout.scrollToStart()):this.flyout.hide()}fireSelectEvent(a,b){const c=a&&a.getName();let d=b&&b.getName();
a===b&&(d=null);a=new (get$$module$build$src$core$events$utils(EventType$$module$build$src$core$events$type.TOOLBOX_ITEM_SELECT))(c,d,this.workspace_.id);fire$$module$build$src$core$events$utils(a)}selectParent(){return this.selectedItem_?this.selectedItem_.isCollapsible()&&this.selectedItem_.isExpanded()?(this.selectedItem_.toggleExpanded(),!0):this.selectedItem_.getParent()&&this.selectedItem_.getParent().isSelectable()?(this.setSelectedItem(this.selectedItem_.getParent()),!0):!1:!1}selectChild(){if(!this.selectedItem_||
!this.selectedItem_.isCollapsible())return!1;const a=this.selectedItem_;a.isExpanded()?this.selectNext():a.toggleExpanded();return!0}selectNext(){if(!this.selectedItem_)return!1;const a=[...this.contents.values()];let b=a.indexOf(this.selectedItem_)+1;if(b>-1&&b<a.length){let c=a[b];for(;c&&!c.isSelectable();)c=a[++b];if(c&&c.isSelectable())return this.setSelectedItem(c),!0}return!1}selectPrevious(){if(!this.selectedItem_)return!1;const a=[...this.contents.values()];let b=a.indexOf(this.selectedItem_)-
1;if(b>-1&&b<a.length){let c=a[b];for(;c&&!c.isSelectable();)c=a[--b];if(c&&c.isSelectable())return this.setSelectedItem(c),!0}return!1}dispose(){this.workspace_.getComponentManager().removeComponent("toolbox");this.flyout.dispose();this.contents.forEach(a=>a.dispose());for(let a=0;a<this.boundEvents_.length;a++)unbind$$module$build$src$core$browser_events(this.boundEvents_[a]);this.boundEvents_=[];this.contents.clear();this.HtmlDiv&&(this.workspace_.getThemeManager().unsubscribe(this.HtmlDiv),removeNode$$module$build$src$core$utils$dom(this.HtmlDiv));
$.getFocusManager$$module$build$src$core$focus_manager().unregisterTree(this)}getFocusableElement(){if(!this.HtmlDiv)throw Error("Toolbox DOM has not yet been created.");return this.HtmlDiv}getFocusableTree(){return this}onNodeFocus(){}onNodeBlur(){}canBeFocused(){return!0}getRootFocusableNode(){return this}getRestoredFocusableNode(a){if(!a||a===this){let b;return(b=this.getToolboxItems().find(c=>c.isSelectable()))!=null?b:null}return null}getNestedTrees(){return[]}lookUpFocusableNode(a){return this.getToolboxItemById(a)}onTreeFocus(a,
b){a!==this?this.getSelectedItem()!==a&&this.setSelectedItem(a):this.clearSelection()}onTreeBlur(a){let b;a&&a===((b=this.flyout)==null?void 0:b.getWorkspace())||this.autoHide(!1)}};register$$module$build$src$core$css('\n.blocklyToolboxDelete {\n  cursor: url("<<<PATH>>>/handdelete.cur"), auto;\n}\n\n.blocklyToolboxGrab {\n  cursor: url("<<<PATH>>>/handclosed.cur"), auto;\n  cursor: grabbing;\n  cursor: -webkit-grabbing;\n}\n\n/* Category tree in Toolbox. */\n.blocklyToolbox {\n  box-sizing: border-box;\n  user-select: none;\n  -ms-user-select: none;\n  -webkit-user-select: none;\n  background-color: #ddd;\n  overflow-x: visible;\n  overflow-y: auto;\n  padding: 4px 0 4px 0;\n  position: absolute;\n  z-index: 70;  /* so blocks go under toolbox when dragging */\n  -webkit-tap-highlight-color: transparent;  /* issue #1345 */\n}\n\n.blocklyToolboxCategoryGroup {\n  display: flex;\n  flex-wrap: wrap;\n  flex-direction: column;\n}\n\n.blocklyToolboxCategoryGroup:focus {\n  outline: none;\n}\n');
register$$module$build$src$core$registry(Type$$module$build$src$core$registry.TOOLBOX,DEFAULT$$module$build$src$core$registry,Toolbox$$module$build$src$core$toolbox$toolbox);var module$build$src$core$toolbox$toolbox={};module$build$src$core$toolbox$toolbox.Toolbox=Toolbox$$module$build$src$core$toolbox$toolbox;var module$build$src$core$interfaces$i_navigation_policy={};var VERSION$$module$build$src$core$blockly="12.3.1",INPUT_VALUE$$module$build$src$core$blockly=ConnectionType$$module$build$src$core$connection_type.INPUT_VALUE,OUTPUT_VALUE$$module$build$src$core$blockly=ConnectionType$$module$build$src$core$connection_type.OUTPUT_VALUE,NEXT_STATEMENT$$module$build$src$core$blockly=ConnectionType$$module$build$src$core$connection_type.NEXT_STATEMENT,PREVIOUS_STATEMENT$$module$build$src$core$blockly=ConnectionType$$module$build$src$core$connection_type.PREVIOUS_STATEMENT,
TOOLBOX_AT_TOP$$module$build$src$core$blockly=Position$$module$build$src$core$utils$toolbox.TOP,TOOLBOX_AT_BOTTOM$$module$build$src$core$blockly=Position$$module$build$src$core$utils$toolbox.BOTTOM,TOOLBOX_AT_LEFT$$module$build$src$core$blockly=Position$$module$build$src$core$utils$toolbox.LEFT,TOOLBOX_AT_RIGHT$$module$build$src$core$blockly=Position$$module$build$src$core$utils$toolbox.RIGHT,svgResize$$module$build$src$core$blockly=svgResize$$module$build$src$core$common,getMainWorkspace$$module$build$src$core$blockly=
getMainWorkspace$$module$build$src$core$common,getSelected$$module$build$src$core$blockly=getSelected$$module$build$src$core$common,defineBlocksWithJsonArray$$module$build$src$core$blockly=defineBlocksWithJsonArray$$module$build$src$core$common,setParentContainer$$module$build$src$core$blockly=setParentContainer$$module$build$src$core$common,COLLAPSE_CHARS$$module$build$src$core$blockly=COLLAPSE_CHARS$$module$build$src$core$internal_constants,OPPOSITE_TYPE$$module$build$src$core$blockly=OPPOSITE_TYPE$$module$build$src$core$internal_constants,
RENAME_VARIABLE_ID$$module$build$src$core$blockly=RENAME_VARIABLE_ID$$module$build$src$core$internal_constants,DELETE_VARIABLE_ID$$module$build$src$core$blockly=DELETE_VARIABLE_ID$$module$build$src$core$internal_constants,COLLAPSED_INPUT_NAME$$module$build$src$core$blockly=COLLAPSED_INPUT_NAME$$module$build$src$core$constants,COLLAPSED_FIELD_NAME$$module$build$src$core$blockly=COLLAPSED_FIELD_NAME$$module$build$src$core$constants,VARIABLE_CATEGORY_NAME$$module$build$src$core$blockly=CATEGORY_NAME$$module$build$src$core$variables,
VARIABLE_DYNAMIC_CATEGORY_NAME$$module$build$src$core$blockly=CATEGORY_NAME$$module$build$src$core$variables_dynamic,PROCEDURE_CATEGORY_NAME$$module$build$src$core$blockly=CATEGORY_NAME$$module$build$src$core$procedures;Workspace$$module$build$src$core$workspace.prototype.newBlock=function(a,b){return new Block$$module$build$src$core$block(this,a,b)};WorkspaceSvg$$module$build$src$core$workspace_svg.prototype.newBlock=function(a,b){return new BlockSvg$$module$build$src$core$block_svg(this,a,b)};
Workspace$$module$build$src$core$workspace.prototype.newComment=function(a){return new WorkspaceComment$$module$build$src$core$comments$workspace_comment(this,a)};WorkspaceSvg$$module$build$src$core$workspace_svg.prototype.newComment=function(a){return new RenderedWorkspaceComment$$module$build$src$core$comments$rendered_workspace_comment(this,a)};WorkspaceSvg$$module$build$src$core$workspace_svg.newTrashcan=function(a){return new Trashcan$$module$build$src$core$trashcan(a)};
MiniWorkspaceBubble$$module$build$src$core$bubbles$mini_workspace_bubble.prototype.newWorkspaceSvg=function(a){return new WorkspaceSvg$$module$build$src$core$workspace_svg(a)};$.Names$$module$build$src$core$names.prototype.populateProcedures=function(a){a=allProcedures$$module$build$src$core$procedures(a);a=a[0].concat(a[1]);for(let b=0;b<a.length;b++)this.getName(a[b][0],$.Names$$module$build$src$core$names.NameType.PROCEDURE)};
var DropDownDiv$$module$build$src$core$blockly=module$build$src$core$dropdowndiv,module$build$src$core$blockly={};module$build$src$core$blockly.Block=Block$$module$build$src$core$block;module$build$src$core$blockly.BlockFlyoutInflater=BlockFlyoutInflater$$module$build$src$core$block_flyout_inflater;module$build$src$core$blockly.BlockNavigationPolicy=BlockNavigationPolicy$$module$build$src$core$keyboard_nav$block_navigation_policy;module$build$src$core$blockly.BlockSvg=BlockSvg$$module$build$src$core$block_svg;
module$build$src$core$blockly.Blocks=Blocks$$module$build$src$core$blocks;module$build$src$core$blockly.ButtonFlyoutInflater=ButtonFlyoutInflater$$module$build$src$core$button_flyout_inflater;module$build$src$core$blockly.COLLAPSED_FIELD_NAME=COLLAPSED_FIELD_NAME$$module$build$src$core$constants;module$build$src$core$blockly.COLLAPSED_INPUT_NAME=COLLAPSED_INPUT_NAME$$module$build$src$core$constants;module$build$src$core$blockly.COLLAPSE_CHARS=COLLAPSE_CHARS$$module$build$src$core$internal_constants;
module$build$src$core$blockly.CodeGenerator=$.CodeGenerator$$module$build$src$core$generator;module$build$src$core$blockly.CollapsibleToolboxCategory=CollapsibleToolboxCategory$$module$build$src$core$toolbox$collapsible_category;module$build$src$core$blockly.ComponentManager=ComponentManager$$module$build$src$core$component_manager;module$build$src$core$blockly.Connection=Connection$$module$build$src$core$connection;module$build$src$core$blockly.ConnectionChecker=ConnectionChecker$$module$build$src$core$connection_checker;
module$build$src$core$blockly.ConnectionDB=ConnectionDB$$module$build$src$core$connection_db;module$build$src$core$blockly.ConnectionNavigationPolicy=ConnectionNavigationPolicy$$module$build$src$core$keyboard_nav$connection_navigation_policy;module$build$src$core$blockly.ConnectionType=ConnectionType$$module$build$src$core$connection_type;module$build$src$core$blockly.ContextMenu=module$build$src$core$contextmenu;module$build$src$core$blockly.ContextMenuItems=module$build$src$core$contextmenu_items;
module$build$src$core$blockly.ContextMenuRegistry=ContextMenuRegistry$$module$build$src$core$contextmenu_registry;module$build$src$core$blockly.Css=module$build$src$core$css;module$build$src$core$blockly.DELETE_VARIABLE_ID=DELETE_VARIABLE_ID$$module$build$src$core$internal_constants;module$build$src$core$blockly.DeleteArea=DeleteArea$$module$build$src$core$delete_area;module$build$src$core$blockly.DragTarget=DragTarget$$module$build$src$core$drag_target;module$build$src$core$blockly.DropDownDiv=module$build$src$core$dropdowndiv;
module$build$src$core$blockly.Events=module$build$src$core$events$events;module$build$src$core$blockly.Extensions=module$build$src$core$extensions;module$build$src$core$blockly.Field=Field$$module$build$src$core$field;module$build$src$core$blockly.FieldCheckbox=FieldCheckbox$$module$build$src$core$field_checkbox;module$build$src$core$blockly.FieldDropdown=FieldDropdown$$module$build$src$core$field_dropdown;module$build$src$core$blockly.FieldImage=FieldImage$$module$build$src$core$field_image;
module$build$src$core$blockly.FieldLabel=FieldLabel$$module$build$src$core$field_label;module$build$src$core$blockly.FieldLabelSerializable=FieldLabelSerializable$$module$build$src$core$field_label_serializable;module$build$src$core$blockly.FieldNavigationPolicy=FieldNavigationPolicy$$module$build$src$core$keyboard_nav$field_navigation_policy;module$build$src$core$blockly.FieldNumber=FieldNumber$$module$build$src$core$field_number;module$build$src$core$blockly.FieldTextInput=$.FieldTextInput$$module$build$src$core$field_textinput;
module$build$src$core$blockly.FieldVariable=FieldVariable$$module$build$src$core$field_variable;module$build$src$core$blockly.Flyout=Flyout$$module$build$src$core$flyout_base;module$build$src$core$blockly.FlyoutButton=FlyoutButton$$module$build$src$core$flyout_button;module$build$src$core$blockly.FlyoutButtonNavigationPolicy=FlyoutButtonNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_button_navigation_policy;module$build$src$core$blockly.FlyoutItem=FlyoutItem$$module$build$src$core$flyout_item;
module$build$src$core$blockly.FlyoutMetricsManager=FlyoutMetricsManager$$module$build$src$core$flyout_metrics_manager;module$build$src$core$blockly.FlyoutNavigationPolicy=FlyoutNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_navigation_policy;module$build$src$core$blockly.FlyoutNavigator=FlyoutNavigator$$module$build$src$core$flyout_navigator;module$build$src$core$blockly.FlyoutSeparator=FlyoutSeparator$$module$build$src$core$flyout_separator;
module$build$src$core$blockly.FlyoutSeparatorNavigationPolicy=FlyoutSeparatorNavigationPolicy$$module$build$src$core$keyboard_nav$flyout_separator_navigation_policy;module$build$src$core$blockly.FocusManager=FocusManager$$module$build$src$core$focus_manager;module$build$src$core$blockly.FocusableTreeTraverser=FocusableTreeTraverser$$module$build$src$core$utils$focusable_tree_traverser;module$build$src$core$blockly.Generator=$.CodeGenerator$$module$build$src$core$generator;
module$build$src$core$blockly.Gesture=Gesture$$module$build$src$core$gesture;module$build$src$core$blockly.Grid=Grid$$module$build$src$core$grid;module$build$src$core$blockly.HorizontalFlyout=HorizontalFlyout$$module$build$src$core$flyout_horizontal;module$build$src$core$blockly.INPUT_VALUE=INPUT_VALUE$$module$build$src$core$blockly;module$build$src$core$blockly.Input=Input$$module$build$src$core$inputs$input;module$build$src$core$blockly.InsertionMarkerPreviewer=InsertionMarkerPreviewer$$module$build$src$core$insertion_marker_previewer;
module$build$src$core$blockly.KeyboardNavigationController=KeyboardNavigationController$$module$build$src$core$keyboard_navigation_controller;module$build$src$core$blockly.LabelFlyoutInflater=LabelFlyoutInflater$$module$build$src$core$label_flyout_inflater;module$build$src$core$blockly.LineCursor=LineCursor$$module$build$src$core$keyboard_nav$line_cursor;module$build$src$core$blockly.Marker=Marker$$module$build$src$core$keyboard_nav$marker;module$build$src$core$blockly.MarkerManager=MarkerManager$$module$build$src$core$marker_manager;
module$build$src$core$blockly.Menu=Menu$$module$build$src$core$menu;module$build$src$core$blockly.MenuItem=MenuItem$$module$build$src$core$menuitem;module$build$src$core$blockly.MetricsManager=MetricsManager$$module$build$src$core$metrics_manager;module$build$src$core$blockly.Msg=$.Msg$$module$build$src$core$msg;module$build$src$core$blockly.NEXT_STATEMENT=NEXT_STATEMENT$$module$build$src$core$blockly;module$build$src$core$blockly.Names=$.Names$$module$build$src$core$names;
module$build$src$core$blockly.Navigator=Navigator$$module$build$src$core$navigator;module$build$src$core$blockly.OPPOSITE_TYPE=OPPOSITE_TYPE$$module$build$src$core$internal_constants;module$build$src$core$blockly.OUTPUT_VALUE=OUTPUT_VALUE$$module$build$src$core$blockly;module$build$src$core$blockly.Options=Options$$module$build$src$core$options;module$build$src$core$blockly.PREVIOUS_STATEMENT=PREVIOUS_STATEMENT$$module$build$src$core$blockly;module$build$src$core$blockly.PROCEDURE_CATEGORY_NAME=CATEGORY_NAME$$module$build$src$core$procedures;
module$build$src$core$blockly.Procedures=module$build$src$core$procedures;module$build$src$core$blockly.RENAME_VARIABLE_ID=RENAME_VARIABLE_ID$$module$build$src$core$internal_constants;module$build$src$core$blockly.RenderedConnection=RenderedConnection$$module$build$src$core$rendered_connection;module$build$src$core$blockly.Scrollbar=Scrollbar$$module$build$src$core$scrollbar;module$build$src$core$blockly.ScrollbarPair=ScrollbarPair$$module$build$src$core$scrollbar_pair;
module$build$src$core$blockly.SeparatorFlyoutInflater=SeparatorFlyoutInflater$$module$build$src$core$separator_flyout_inflater;module$build$src$core$blockly.ShortcutItems=module$build$src$core$shortcut_items;module$build$src$core$blockly.ShortcutRegistry=ShortcutRegistry$$module$build$src$core$shortcut_registry;module$build$src$core$blockly.TOOLBOX_AT_BOTTOM=TOOLBOX_AT_BOTTOM$$module$build$src$core$blockly;module$build$src$core$blockly.TOOLBOX_AT_LEFT=TOOLBOX_AT_LEFT$$module$build$src$core$blockly;
module$build$src$core$blockly.TOOLBOX_AT_RIGHT=TOOLBOX_AT_RIGHT$$module$build$src$core$blockly;module$build$src$core$blockly.TOOLBOX_AT_TOP=TOOLBOX_AT_TOP$$module$build$src$core$blockly;module$build$src$core$blockly.Theme=Theme$$module$build$src$core$theme;module$build$src$core$blockly.ThemeManager=ThemeManager$$module$build$src$core$theme_manager;module$build$src$core$blockly.Themes=module$build$src$core$theme$themes;module$build$src$core$blockly.Toast=Toast$$module$build$src$core$toast;
module$build$src$core$blockly.Toolbox=Toolbox$$module$build$src$core$toolbox$toolbox;module$build$src$core$blockly.ToolboxCategory=ToolboxCategory$$module$build$src$core$toolbox$category;module$build$src$core$blockly.ToolboxItem=ToolboxItem$$module$build$src$core$toolbox$toolbox_item;module$build$src$core$blockly.ToolboxSeparator=ToolboxSeparator$$module$build$src$core$toolbox$separator;module$build$src$core$blockly.Tooltip=module$build$src$core$tooltip;module$build$src$core$blockly.Touch=module$build$src$core$touch;
module$build$src$core$blockly.Trashcan=Trashcan$$module$build$src$core$trashcan;module$build$src$core$blockly.UnattachedFieldError=UnattachedFieldError$$module$build$src$core$field;module$build$src$core$blockly.VARIABLE_CATEGORY_NAME=CATEGORY_NAME$$module$build$src$core$variables;module$build$src$core$blockly.VARIABLE_DYNAMIC_CATEGORY_NAME=CATEGORY_NAME$$module$build$src$core$variables_dynamic;module$build$src$core$blockly.VERSION=VERSION$$module$build$src$core$blockly;
module$build$src$core$blockly.VariableMap=VariableMap$$module$build$src$core$variable_map;module$build$src$core$blockly.VariableModel=VariableModel$$module$build$src$core$variable_model;module$build$src$core$blockly.Variables=module$build$src$core$variables;module$build$src$core$blockly.VariablesDynamic=module$build$src$core$variables_dynamic;module$build$src$core$blockly.VerticalFlyout=VerticalFlyout$$module$build$src$core$flyout_vertical;module$build$src$core$blockly.WidgetDiv=module$build$src$core$widgetdiv;
module$build$src$core$blockly.Workspace=Workspace$$module$build$src$core$workspace;module$build$src$core$blockly.WorkspaceAudio=WorkspaceAudio$$module$build$src$core$workspace_audio;module$build$src$core$blockly.WorkspaceDragger=WorkspaceDragger$$module$build$src$core$workspace_dragger;module$build$src$core$blockly.WorkspaceNavigationPolicy=WorkspaceNavigationPolicy$$module$build$src$core$keyboard_nav$workspace_navigation_policy;module$build$src$core$blockly.WorkspaceSvg=WorkspaceSvg$$module$build$src$core$workspace_svg;
module$build$src$core$blockly.Xml=module$build$src$core$xml;module$build$src$core$blockly.ZoomControls=ZoomControls$$module$build$src$core$zoom_controls;module$build$src$core$blockly.blockAnimations=module$build$src$core$block_animations;module$build$src$core$blockly.blockRendering=module$build$src$core$renderers$common$block_rendering;module$build$src$core$blockly.browserEvents=module$build$src$core$browser_events;module$build$src$core$blockly.bubbles=module$build$src$core$bubbles;
module$build$src$core$blockly.bumpObjects=module$build$src$core$bump_objects;module$build$src$core$blockly.clipboard=module$build$src$core$clipboard;module$build$src$core$blockly.comments=module$build$src$core$comments;module$build$src$core$blockly.common=module$build$src$core$common;module$build$src$core$blockly.config=$.config$$module$build$src$core$config;module$build$src$core$blockly.constants=module$build$src$core$constants;module$build$src$core$blockly.defineBlocksWithJsonArray=defineBlocksWithJsonArray$$module$build$src$core$common;
module$build$src$core$blockly.dialog=module$build$src$core$dialog;module$build$src$core$blockly.dragging=module$build$src$core$dragging;module$build$src$core$blockly.fieldRegistry=module$build$src$core$field_registry;module$build$src$core$blockly.geras=module$build$src$core$renderers$geras$geras;module$build$src$core$blockly.getFocusManager=$.getFocusManager$$module$build$src$core$focus_manager;module$build$src$core$blockly.getMainWorkspace=getMainWorkspace$$module$build$src$core$common;
module$build$src$core$blockly.getSelected=getSelected$$module$build$src$core$common;module$build$src$core$blockly.hasBubble=hasBubble$$module$build$src$core$interfaces$i_has_bubble;module$build$src$core$blockly.hideChaff=hideChaff$$module$build$src$core$blockly;module$build$src$core$blockly.icons=module$build$src$core$icons;module$build$src$core$blockly.inject=inject$$module$build$src$core$inject;module$build$src$core$blockly.inputs=module$build$src$core$inputs;
module$build$src$core$blockly.isCopyable=isCopyable$$module$build$src$core$interfaces$i_copyable;module$build$src$core$blockly.isDeletable=isDeletable$$module$build$src$core$interfaces$i_deletable;module$build$src$core$blockly.isDraggable=isDraggable$$module$build$src$core$interfaces$i_draggable;module$build$src$core$blockly.isIcon=isIcon$$module$build$src$core$interfaces$i_icon;module$build$src$core$blockly.isObservable=isObservable$$module$build$src$core$interfaces$i_observable;
module$build$src$core$blockly.isPaster=isPaster$$module$build$src$core$interfaces$i_paster;module$build$src$core$blockly.isRenderedElement=isRenderedElement$$module$build$src$core$interfaces$i_rendered_element;module$build$src$core$blockly.isSelectable=isSelectable$$module$build$src$core$interfaces$i_selectable;module$build$src$core$blockly.isSerializable=isSerializable$$module$build$src$core$interfaces$i_serializable;module$build$src$core$blockly.isVariableBackedParameterModel=isVariableBackedParameterModel$$module$build$src$core$interfaces$i_variable_backed_parameter_model;
module$build$src$core$blockly.keyboardNavigationController=keyboardNavigationController$$module$build$src$core$keyboard_navigation_controller;module$build$src$core$blockly.layers=module$build$src$core$layers;module$build$src$core$blockly.navigateBlock=navigateBlock$$module$build$src$core$keyboard_nav$block_navigation_policy;module$build$src$core$blockly.navigateStacks=navigateStacks$$module$build$src$core$keyboard_nav$block_navigation_policy;module$build$src$core$blockly.procedures=module$build$src$core$procedures;
module$build$src$core$blockly.registry=module$build$src$core$registry;module$build$src$core$blockly.renderManagement=module$build$src$core$render_management;module$build$src$core$blockly.serialization=module$build$src$core$serialization;module$build$src$core$blockly.setLocale=setLocale$$module$build$src$core$msg;module$build$src$core$blockly.setParentContainer=setParentContainer$$module$build$src$core$common;module$build$src$core$blockly.svgResize=svgResize$$module$build$src$core$common;
module$build$src$core$blockly.thrasos=module$build$src$core$renderers$thrasos$thrasos;module$build$src$core$blockly.uiPosition=module$build$src$core$positionable_helpers;module$build$src$core$blockly.utils=module$build$src$core$utils;module$build$src$core$blockly.zelos=module$build$src$core$renderers$zelos$zelos;var module$build$src$core$utils$metrics={};var module$build$src$core$renderers$common$i_path_object={};var module$build$src$core$interfaces$i_variable_model={};var module$build$src$core$interfaces$i_variable_map={};var module$build$src$core$interfaces$i_toolbox_item={};var module$build$src$core$interfaces$i_toolbox={};var module$build$src$core$interfaces$i_styleable={};var module$build$src$core$interfaces$i_serializer={};var module$build$src$core$interfaces$i_registrable={};var module$build$src$core$interfaces$i_procedure_model={};var module$build$src$core$interfaces$i_procedure_map={};var module$build$src$core$interfaces$i_positionable={};var module$build$src$core$interfaces$i_parameter_model={};var module$build$src$core$interfaces$i_movable={};var module$build$src$core$interfaces$i_metrics_manager={};var module$build$src$core$interfaces$i_keyboard_accessible={};var module$build$src$core$interfaces$i_focusable_tree={};module$build$src$core$interfaces$i_focusable_tree.isFocusableTree=isFocusableTree$$module$build$src$core$interfaces$i_focusable_tree;var module$build$src$core$interfaces$i_flyout_inflater={};var module$build$src$core$interfaces$i_flyout={};var module$build$src$core$interfaces$i_dragger={};var module$build$src$core$interfaces$i_drag_target={};var module$build$src$core$interfaces$i_delete_area={};var module$build$src$core$interfaces$i_contextmenu={};var module$build$src$core$interfaces$i_connection_previewer={};var module$build$src$core$interfaces$i_connection_checker={};var module$build$src$core$interfaces$i_component={};var module$build$src$core$interfaces$i_collapsible_toolbox_item={};var module$build$src$core$interfaces$i_bubble={};var module$build$src$core$interfaces$i_bounded_element={};
module$build$src$core$blockly.__namespace__=$;
return module$build$src$core$blockly;
}));


//# sourceMappingURL=blockly_compressed.js.map


/***/ }),

/***/ 15836:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Text-module__Root--Gaf4_{margin-block-start:0;margin-block-end:0;font-family:var(--font-family)}.Text-module__Root--Gaf4_ a{font-weight:700;color:var(--theme-color-primary);text-decoration:underline}.Text-module__Root--Gaf4_.Text-module__has-bottom-spacing--O0pzh{margin-bottom:16px}.Text-module__is-type-default--FIk9E{color:var(--theme-color-fg-default)}.Text-module__is-type-default-contrast--UxUty{color:var(--theme-color-fg-default-contrast)}.Text-module__is-type-proud--pniTA{color:var(--theme-color-fg-highlight)}.Text-module__is-type-shy--LpEfd{color:var(--theme-color-fg-muted)}.Text-module__is-type-secondary--O5pCr{color:var(--theme-color-secondary-as-fg)}.Text-module__is-type-success--rC093{color:var(--theme-color-success)}.Text-module__is-type-notice--aNSkB{color:var(--theme-color-notice)}.Text-module__is-type-danger--BeFAM{color:var(--theme-color-danger)}.Text-module__is-type-success--rC093 a,.Text-module__is-type-notice--aNSkB a,.Text-module__is-type-danger--BeFAM a{color:inherit}.Text-module__is-size-default--bn_K9{font-size:12px}.Text-module__is-size-small--hre2Z{font-size:10px;-webkit-font-smoothing:antialiased}.Text-module__is-size-medium--E2Lie{font-size:11px}.Text-module__is-inline--FltUt{display:inline}.Text-module__is-centered--qEYTu{text-align:center}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/typography/Text/Text.module.scss"],"names":[],"mappings":"AAAA,0BACE,oBAAA,CACA,kBAAA,CACA,8BAAA,CAEA,4BACE,eAAA,CACA,gCAAA,CACA,yBAAA,CAGF,iEACE,kBAAA,CAKF,qCACE,mCAAA,CAGF,8CACE,4CAAA,CAGF,mCACE,qCAAA,CAGF,iCACE,iCAAA,CAGF,uCACE,wCAAA,CAGF,qCACE,gCAAA,CAGF,oCACE,+BAAA,CAGF,oCACE,+BAAA,CAMA,mHACE,aAAA,CAMJ,qCACE,cAAA,CAGF,mCACE,cAAA,CACA,kCAAA,CAGF,oCACE,cAAA,CAIJ,+BACE,cAAA,CAGF,iCACE,iBAAA","sourcesContent":[".Root {\r\n  margin-block-start: 0;\r\n  margin-block-end: 0;\r\n  font-family: var(--font-family);\r\n\r\n  a {\r\n    font-weight: 700;\r\n    color: var(--theme-color-primary);\r\n    text-decoration: underline;\r\n  }\r\n\r\n  &.has-bottom-spacing {\r\n    margin-bottom: 16px;\r\n  }\r\n}\r\n\r\n.is-type {\r\n  &-default {\r\n    color: var(--theme-color-fg-default);\r\n  }\r\n\r\n  &-default-contrast {\r\n    color: var(--theme-color-fg-default-contrast);\r\n  }\r\n\r\n  &-proud {\r\n    color: var(--theme-color-fg-highlight);\r\n  }\r\n\r\n  &-shy {\r\n    color: var(--theme-color-fg-muted);\r\n  }\r\n\r\n  &-secondary {\r\n    color: var(--theme-color-secondary-as-fg);\r\n  }\r\n\r\n  &-success {\r\n    color: var(--theme-color-success);\r\n  }\r\n\r\n  &-notice {\r\n    color: var(--theme-color-notice);\r\n  }\r\n\r\n  &-danger {\r\n    color: var(--theme-color-danger);\r\n  }\r\n\r\n  &-success,\r\n  &-notice,\r\n  &-danger {\r\n    a {\r\n      color: inherit;\r\n    }\r\n  }\r\n}\r\n\r\n.is-size {\r\n  &-default {\r\n    font-size: 12px;\r\n  }\r\n\r\n  &-small {\r\n    font-size: 10px;\r\n    -webkit-font-smoothing: antialiased;\r\n  }\r\n\r\n  &-medium {\r\n    font-size: 11px;\r\n  }\r\n}\r\n\r\n.is-inline {\r\n  display: inline;\r\n}\r\n\r\n.is-centered {\r\n  text-align: center;\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Text-module__Root--Gaf4_`,
	"has-bottom-spacing": `Text-module__has-bottom-spacing--O0pzh`,
	"is-type-default": `Text-module__is-type-default--FIk9E`,
	"is-type-default-contrast": `Text-module__is-type-default-contrast--UxUty`,
	"is-type-proud": `Text-module__is-type-proud--pniTA`,
	"is-type-shy": `Text-module__is-type-shy--LpEfd`,
	"is-type-secondary": `Text-module__is-type-secondary--O5pCr`,
	"is-type-success": `Text-module__is-type-success--rC093`,
	"is-type-notice": `Text-module__is-type-notice--aNSkB`,
	"is-type-danger": `Text-module__is-type-danger--BeFAM`,
	"is-size-default": `Text-module__is-size-default--bn_K9`,
	"is-size-small": `Text-module__is-size-small--hre2Z`,
	"is-size-medium": `Text-module__is-size-medium--E2Lie`,
	"is-inline": `Text-module__is-inline--FltUt`,
	"is-centered": `Text-module__is-centered--qEYTu`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 15845:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _APIPromise_client;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.APIPromise = void 0;
const tslib_1 = __webpack_require__(84499);
const parse_1 = __webpack_require__(66508);
/**
 * A subclass of `Promise` providing additional helper methods
 * for interacting with the SDK.
 */
class APIPromise extends Promise {
    constructor(client, responsePromise, parseResponse = parse_1.defaultParseResponse) {
        super((resolve) => {
            // this is maybe a bit weird but this has to be a no-op to not implicitly
            // parse the response body; instead .then, .catch, .finally are overridden
            // to parse the response
            resolve(null);
        });
        this.responsePromise = responsePromise;
        this.parseResponse = parseResponse;
        _APIPromise_client.set(this, void 0);
        tslib_1.__classPrivateFieldSet(this, _APIPromise_client, client, "f");
    }
    _thenUnwrap(transform) {
        return new APIPromise(tslib_1.__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => (0, parse_1.addRequestID)(transform(await this.parseResponse(client, props), props), props.response));
    }
    /**
     * Gets the raw `Response` instance instead of parsing the response
     * data.
     *
     * If you want to parse the response body but still get the `Response`
     * instance, you can use {@link withResponse()}.
     *
     * 👋 Getting the wrong TypeScript type for `Response`?
     * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
     * to your `tsconfig.json`.
     */
    asResponse() {
        return this.responsePromise.then((p) => p.response);
    }
    /**
     * Gets the parsed response data, the raw `Response` instance and the ID of the request,
     * returned via the `request-id` header which is useful for debugging requests and resporting
     * issues to Anthropic.
     *
     * If you just want to get the raw `Response` instance without parsing it,
     * you can use {@link asResponse()}.
     *
     * 👋 Getting the wrong TypeScript type for `Response`?
     * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
     * to your `tsconfig.json`.
     */
    async withResponse() {
        const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
        return { data, response, request_id: response.headers.get('request-id') };
    }
    parse() {
        if (!this.parsedPromise) {
            this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(tslib_1.__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
        }
        return this.parsedPromise;
    }
    then(onfulfilled, onrejected) {
        return this.parse().then(onfulfilled, onrejected);
    }
    catch(onrejected) {
        return this.parse().catch(onrejected);
    }
    finally(onfinally) {
        return this.parse().finally(onfinally);
    }
}
exports.APIPromise = APIPromise;
_APIPromise_client = new WeakMap();
//# sourceMappingURL=api-promise.js.map

/***/ }),

/***/ 16125:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSearchSquare = function SvgSearchSquare(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.83691 5.47003H9.07974C9.49396 5.47003 9.82974 5.13425 9.82974 4.72003C9.82974 4.30582 9.49396 3.97003 9.07974 3.97003H4.80613C4.41647 3.97003 4.04277 4.12482 3.76724 4.40035C3.49171 4.67589 3.33691 5.04959 3.33691 5.43925V19.8235C3.33691 20.2132 3.49171 20.5869 3.76724 20.8624C4.04277 21.138 4.41647 21.2928 4.80613 21.2928H19.1904C19.5801 21.2928 19.9538 21.138 20.2293 20.8624C20.5048 20.5869 20.6596 20.2132 20.6596 19.8235V15.9488C20.6596 15.5346 20.3239 15.1988 19.9096 15.1988C19.4954 15.1988 19.1596 15.5346 19.1596 15.9488V19.7928H4.83691V5.47003Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.9102 7.25598C12.9102 5.86293 14.0394 4.73364 15.4325 4.73364C16.8255 4.73364 17.9548 5.86293 17.9548 7.25598C17.9548 8.64903 16.8255 9.77832 15.4325 9.77832C14.0394 9.77832 12.9102 8.64903 12.9102 7.25598ZM15.4325 3.23364C13.211 3.23364 11.4102 5.0345 11.4102 7.25598C11.4102 9.47745 13.211 11.2783 15.4325 11.2783C16.1102 11.2783 16.7488 11.1107 17.3091 10.8146L19.6562 13.1618C19.9491 13.4546 20.424 13.4546 20.7169 13.1618C21.0098 12.8689 21.0098 12.394 20.7169 12.1011L18.4879 9.87213C19.0907 9.1688 19.4548 8.25491 19.4548 7.25598C19.4548 5.0345 17.654 3.23364 15.4325 3.23364Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSearchSquare);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "83abcab835c33af12f200350794bba76.svg");

/***/ }),

/***/ 16163:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   j: () => (/* binding */ ComponentModel)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80002);
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(underscore__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _noodl_models_undo_queue_model__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(50867);
/* harmony import */ var _noodl_utils_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(93015);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(47821);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_shared_model__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(11138);
/* harmony import */ var _nodegraphmodel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(87844);
/* harmony import */ var _nodelibrary__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(68091);







class ComponentModel extends (_shared_model__WEBPACK_IMPORTED_MODULE_3___default()) {
    constructor(args) {
        super();
        this.name = args.name;
        this.id = args.id;
        this.metadata = args.metadata;
        if (args.graph) {
            this.bindGraph(args.graph);
        }
    }
    static fromJSON(json) {
        const _this = new ComponentModel({
            name: json.name,
            id: json.id,
            metadata: json.metadata,
            graph: _nodegraphmodel__WEBPACK_IMPORTED_MODULE_5__/* .NodeGraphModel */ .W2.fromJSON(json.graph)
        });
        return _this;
    }
    dispose() {
        this.graph.dispose();
    }
    bindGraph(graph) {
        if (this.graph) {
            this.graph.off(this);
            this.graph.owner = null;
        }
        this.graph = graph;
        this.graph.owner = this;
        this.graph.on(['nodePortRenamed'], (args) => {
            if (args.model.type.haveComponentPorts) {
                // Ports have changed on a node that exports component ports, notify that this type has changed
                this.notifyListeners('portRenamed', {
                    model: this,
                    port: this.findPortWithName(args.port.name),
                    oldName: args.oldName
                });
            }
        }, this);
        this.notifyListeners('graphModelBound');
    }
    collectAllowedChildCategories() {
        let categories = [];
        this.graph.forEachNode(function (node) {
            if (node.type.haveComponentChildren)
                categories = underscore__WEBPACK_IMPORTED_MODULE_0___default().union(node.type.haveComponentChildren, categories);
        });
        return categories.length > 0 ? categories : undefined;
    }
    // Returns the ports for this components, port types are derrived from connections
    // to any ports on node with the "haveComponentPorts" property
    getPorts() {
        const _this = this;
        const inputsMap = {}, outputsMap = {};
        // Find all nodes in graph that should contribute to component ports
        this.graph.forEachNode(function (node) {
            if (node.type && node.type.haveComponentPorts) {
                // Collect all input ports in the inputs map, also collect all connections and
                // their type
                underscore__WEBPACK_IMPORTED_MODULE_0___default().each(node.getPorts('input'), function (p) {
                    if (!inputsMap[p.name])
                        inputsMap[p.name] = { ports: [], connections: [] };
                    inputsMap[p.name].ports.push(p);
                    node.forAllConnectionsOnThisNode(function (c) {
                        if (c.toId === node.id && c.toProperty === p.name) {
                            const sourceNode = _this.graph.findNodeWithId(c.fromId);
                            const sourcePort = sourceNode.getPort(c.fromProperty, 'output');
                            if (sourcePort)
                                inputsMap[p.name].connections.push({ direction: 'from', type: sourcePort.type });
                        }
                    });
                });
                // Collect all outputs and connections, and default value
                underscore__WEBPACK_IMPORTED_MODULE_0___default().each(node.getPorts('output'), function (p) {
                    if (!outputsMap[p.name])
                        outputsMap[p.name] = { ports: [], connections: [] };
                    outputsMap[p.name].ports.push(p);
                    node.forAllConnectionsOnThisNode(function (c) {
                        if (c.fromId === node.id && c.fromProperty === p.name) {
                            const targetNode = _this.graph.findNodeWithId(c.toId);
                            const targetPort = targetNode.getPort(c.toProperty, 'input');
                            if (targetPort)
                                outputsMap[p.name].connections.push({
                                    direction: 'to',
                                    type: targetPort.type,
                                    def: targetNode.getParameter(c.toProperty),
                                    group: targetPort.group
                                });
                        }
                    });
                });
            }
        });
        function _deriveType(p) {
            if (p.connections.length === 1)
                return p.connections[0].type;
            // Just one connection, simple get the type
            else if (p.connections.length > 1)
                // Try to figure out a compatible type
                return _nodelibrary__WEBPACK_IMPORTED_MODULE_6__/* .NodeLibrary */ .m.instance.findCompatiblePortType(p.connections);
        }
        function _deriveDef(p) {
            if (p.connections.length === 1)
                return p.connections[0].def; // Just one connection we can derive the def
        }
        function _deriveGroup(p) {
            let portGroup = underscore__WEBPACK_IMPORTED_MODULE_0___default().every(p.ports, function (port) {
                return port.group === undefined || port.group === p.ports[0].group;
            })
                ? p.ports[0].group
                : undefined;
            if (!portGroup && p.connections.length >= 1)
                // If there is no port group, try to get group from connections
                portGroup = underscore__WEBPACK_IMPORTED_MODULE_0___default().every(p.connections, function (c) {
                    return c.group === undefined || c.group === p.connections[0].group;
                })
                    ? p.connections[0].group
                    : undefined;
            return portGroup;
        }
        // The port maps now contains all connections to and from the component ports
        // Now go through all ports and derive a type
        const ports = [];
        for (var i in inputsMap) {
            var p = inputsMap[i];
            var type = _deriveType(p);
            if (type == undefined)
                type = '*';
            ports.push({
                name: i,
                type: type,
                default: _deriveDef(p),
                group: _deriveGroup(p),
                plug: 'output',
                index: p.ports[0].index
            });
        }
        for (var i in outputsMap) {
            var p = outputsMap[i];
            var type = _deriveType(p);
            if (type == undefined)
                type = '*';
            ports.push({
                name: i,
                type: type,
                default: _deriveDef(p),
                group: _deriveGroup(p),
                plug: 'input',
                index: p.ports[0].index
            });
        }
        ports.sort(function (a, b) {
            return a.index - b.index;
        });
        return ports;
    }
    // Generate new Ids for component and it's nodes so it doesn't
    // collide with previous imports of this component
    rekeyAllIds() {
        this.id = this.id || _noodl_utils_utils__WEBPACK_IMPORTED_MODULE_2__["default"].guid();
        this.graph.rekeyAllIds();
    }
    // Update all references to components that start with the oldPathPrefix
    // to instead start with newPathPrefix (used when duplicating folders...)
    rerouteComponentRefs(oldPathPrefix, newPathPrefix) {
        this.graph.rerouteComponentRefs(oldPathPrefix, newPathPrefix);
    }
    // Returns a port with the given name
    findPortWithName(portname) {
        const ports = this.getPorts();
        for (const i in ports)
            if (ports[i].name === portname)
                return ports[i];
    }
    // Rename the component
    rename(newname, args) {
        const _this = this;
        const oldName = this.name;
        this.name = newname;
        this.notifyListeners('renamed', { model: this, oldName });
        // The component is a type, so tell the node library that this has been renamed
        _nodelibrary__WEBPACK_IMPORTED_MODULE_6__/* .NodeLibrary */ .m.instance.typeRenamed(this, oldName);
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : _noodl_models_undo_queue_model__WEBPACK_IMPORTED_MODULE_1__/* .UndoQueue */ .g.instance;
            undo.push({
                label: args.label,
                do: function () {
                    _this.rename(newname);
                },
                undo: function () {
                    _this.rename(oldName);
                }
            });
        }
    }
    getCreateStatus(args) {
        // Woooo... feedback
        if (args.type === this) {
            return { creatable: false, message: 'A component cannot contain an instance of itself.' };
        }
        // Check for circular references
        const _this = this;
        let circular = false;
        function traverseTypes(c) {
            if (!(c instanceof ComponentModel))
                return;
            if (c === _this) {
                circular = true;
                return;
            }
            c.graph.forEachNode(function (n) {
                traverseTypes(n.type);
            });
        }
        traverseTypes(args.type);
        if (circular) {
            return { creatable: false, message: 'A circular reference is detected, cannot create node.' };
        }
        // Parents can only contain child nodes
        if (args.parent && args.type) {
            if (!args.parent.type.allowChildrenWithCategory ||
                !args.type.category ||
                args.parent.type.allowChildrenWithCategory.indexOf(args.type.category) === -1) {
                return { creatable: false, message: 'This node cannot be a child of the selected node.' };
            }
            if (!args.type.allowAsChild) {
                return { creatable: false, message: 'This node cannot be a child.' };
            }
        }
        // Deprecated
        if (args.type && args.type.deprecated) {
            return { creatable: false, message: 'This node is deprected.' };
        }
        return { creatable: true };
    }
    // The label for component type instances are simply the local type name
    labelForNode(_node) {
        return this.localName;
    }
    // The module for the component is the owner
    getModule() {
        return this.owner;
    }
    // Iterates over all nodes in the component graph
    forEachNode(callback) {
        return this.graph.forEachNode(callback);
    }
    forEachNodeRecursive(callback) {
        return this.graph.forEachNodeRecursive(callback);
    }
    getNodes() {
        const nodes = [];
        this.graph.forEachNode((node) => {
            nodes.push(node);
        });
        return nodes;
    }
    getNodesWithType(typename) {
        const nodes = [];
        this.graph.forEachNode((node) => {
            if (node.type.name === typename)
                nodes.push(node);
        });
        return nodes;
    }
    getNodesWithTypeRecursive(typename) {
        const nodes = [];
        this.graph.forEachNodeRecursive((node) => {
            if (node.type.name === typename)
                nodes.push(node);
        });
        return nodes;
    }
    setMetaData(key, data) {
        if (!this.metadata)
            this.metadata = {};
        this.metadata[key] = data;
        this.notifyListeners('metadataChanged', { key, data });
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_4__.EventDispatcher.instance.notifyListeners('ComponentModel.metadataChanged', { key, data });
    }
    getMetaData(key) {
        if (!this.metadata)
            this.metadata = {};
        return this.metadata[key];
    }
    toJSON() {
        const json = {
            name: this.name,
            id: this.id,
            graph: this.graph.toJSON(),
            metadata: this.metadata
        };
        return json;
    }
    get ports() {
        return this.getPorts();
    }
    get category() {
        let category;
        // The component will assume the category of any roots that may act as children
        underscore__WEBPACK_IMPORTED_MODULE_0___default().each(this.graph.roots, function (root) {
            if (root.type.allowAsChild)
                category = root.type.category;
        });
        return category;
    }
    get color() {
        let color;
        // The component will assume the color of any roots that may act as children
        underscore__WEBPACK_IMPORTED_MODULE_0___default().each(this.graph.roots, function (root) {
            if (root.type.allowAsChild)
                color = root.type.color;
        });
        return color ? color : 'default';
    }
    // Is there a root in the component graph that may act as a child
    // in that case the component type may act as a child
    get allowAsChild() {
        return !!underscore__WEBPACK_IMPORTED_MODULE_0___default().find(this.graph.roots, function (n) {
            return n.type.allowAsChild;
        });
    }
    // The component can have children if there are nodes with "haveComponentChildren"
    // property, collect all categories and return as an array
    get allowChildrenWithCategory() {
        return this.collectAllowedChildCategories();
    }
    // Is there are component root that may act as export root, in that
    // case instances of this component may act as export root
    get allowAsExportRoot() {
        return !!underscore__WEBPACK_IMPORTED_MODULE_0___default().find(this.graph.roots, function (n) {
            return n.type.allowAsExportRoot;
        });
    }
    // Local type name of components are the last component of the path /xxx/yyy -> local name is yyy
    get localName() {
        const path = this.name.split('/');
        return path[path.length - 1];
    }
    // Full name is the full name of the component
    get fullName() {
        return this.name;
    }
    // Display name is local name
    get displayName() {
        return this.localName;
    }
}


/***/ }),

/***/ 16202:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  D: () => (/* reexport */ SearchInput)
});

// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/SearchInput/SearchInput.module.scss
var SearchInput_module = __webpack_require__(78052);
;// ../noodl-core-ui/src/components/inputs/SearchInput/SearchInput.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(SearchInput_module/* default */.A, options);




       /* harmony default export */ const SearchInput_SearchInput_module = (SearchInput_module/* default */.A && SearchInput_module/* default */.A.locals ? SearchInput_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/SearchInput/SearchInput.tsx




function SearchInput({ placeholder, value, inputRef, onChange, onFocus, onBlur, onClick, UNSAFE_className, UNSAFE_style, isAutoFocus }) {
    return (external_react_default().createElement("div", { className: SearchInput_SearchInput_module['Root'] },
        external_react_default().createElement("input", { className: external_classnames_default()(SearchInput_SearchInput_module['SearchInput'], UNSAFE_className), type: "text", placeholder: placeholder, ref: inputRef, onChange: (event) => onChange(event.target.value), onFocus: onFocus, onBlur: onBlur, onClick: onClick, style: UNSAFE_style, value: value, autoFocus: isAutoFocus }),
        external_react_default().createElement(Icon/* Icon */.In, { icon: Icon/* IconName */.$M.Search, UNSAFE_className: SearchInput_SearchInput_module['SearchInputIcon'] })));
}

;// ../noodl-core-ui/src/components/inputs/SearchInput/index.ts



/***/ }),

/***/ 16279:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  lg: () => (/* binding */ Branch),
  Rk: () => (/* binding */ BranchType)
});

// UNUSED EXPORTS: StartPoint

;// ../noodl-git/src/core/helpers/remove-remote-prefix.ts
/**
 * Remove the remote prefix from the string. If there is no prefix, returns
 * null. E.g.:
 *
 * origin/my-branch       -> my-branch
 * origin/thing/my-branch -> thing/my-branch
 * my-branch              -> null
 */
function removeRemotePrefix(name) {
    const pieces = name.match(/.*?\/(.*)/);
    if (!pieces || pieces.length < 2) {
        return null;
    }
    return pieces[1];
}

;// ../noodl-git/src/core/models/branch.ts

// NOTE: The values here matter as they are used to sort
// local and remote branches, Local should come before Remote
var BranchType;
(function (BranchType) {
    BranchType[BranchType["Local"] = 0] = "Local";
    BranchType[BranchType["Remote"] = 1] = "Remote";
})(BranchType || (BranchType = {}));
/** Default rules for where to create a branch from */
var StartPoint;
(function (StartPoint) {
    StartPoint["CurrentBranch"] = "CurrentBranch";
    StartPoint["DefaultBranch"] = "DefaultBranch";
    StartPoint["Head"] = "Head";
    /** Only valid for forks */
    StartPoint["UpstreamDefaultBranch"] = "UpstreamDefaultBranch";
})(StartPoint || (StartPoint = {}));
/** A branch as loaded from Git. */
class Branch {
    /**
     * A branch as loaded from Git.
     *
     * @param name The short name of the branch. E.g., `main`.
     * @param upstream The remote-prefixed upstream name. E.g., `origin/main`.
     * @param tip Basic information (sha and author) of the latest commit on the branch.
     * @param type The type of branch, e.g., local or remote.
     * @param ref The canonical ref of the branch
     */
    constructor(name, upstream, tip, type, ref, remote) {
        this.name = name;
        this.upstream = upstream;
        this.tip = tip;
        this.type = type;
        this.ref = ref;
        this.remote = remote;
    }
    withRemote(remote) {
        return new Branch(this.name, this.upstream, this.tip, this.type, this.ref, remote);
    }
    /**
     * This might be a little confusing, git has different refs.
     *
     * If the ref is "refs/remotes" then there will never be a upstream.
     * If the ref is "refs/heads" it might have a upstream if it is remote.
     *
     * "remote" variable here only means that there is a remote branch created,
     * but it might not sync with the remote branch.
     */
    get isLocal() {
        return !Boolean(this.upstream) && this.type === BranchType.Local;
    }
    /** The name of the upstream's remote. */
    get upstreamRemoteName() {
        const upstream = this.upstream;
        if (!upstream) {
            return null;
        }
        const pieces = upstream.match(/(.*?)\/.*/);
        if (!pieces || pieces.length < 2) {
            return null;
        }
        return pieces[1];
    }
    /** The name of remote for a remote branch. If local, will return null. */
    get remoteName() {
        if (this.type === BranchType.Local) {
            return null;
        }
        const pieces = this.ref.match(/^refs\/remotes\/(.*?)\/.*/);
        if (!pieces || pieces.length !== 2) {
            // This shouldn't happen, the remote ref should always be prefixed
            // with refs/remotes
            throw new Error(`Remote branch ref has unexpected format: ${this.ref}`);
        }
        return pieces[1];
    }
    /**
     * The name of the branch's upstream without the remote prefix.
     */
    get upstreamWithoutRemote() {
        if (!this.upstream) {
            return null;
        }
        return removeRemotePrefix(this.upstream);
    }
    /**
     * The name of the branch without the remote prefix. If the branch is a local
     * branch, this is the same as its `name`.
     */
    get nameWithoutRemote() {
        if (this.type === BranchType.Local) {
            return this.name;
        }
        else {
            const withoutRemote = removeRemotePrefix(this.name);
            return withoutRemote || this.name;
        }
    }
}


/***/ }),

/***/ 16406:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `:root {
    --easing-base: cubic-bezier(0.45, 0, 0.18, 0.99);
    --easing-equal: ease-in-out;

    --speed-turbo: 100ms;
    --speed-quick: 400ms;
    --speed-base: 800ms;
    --speed-slow: 1200ms;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/custom-properties/animations.css"],"names":[],"mappings":"AAAA;IACI,gDAAgD;IAChD,2BAA2B;;IAE3B,oBAAoB;IACpB,oBAAoB;IACpB,mBAAmB;IACnB,oBAAoB;AACxB","sourcesContent":[":root {\n    --easing-base: cubic-bezier(0.45, 0, 0.18, 0.99);\n    --easing-equal: ease-in-out;\n\n    --speed-turbo: 100ms;\n    --speed-quick: 400ms;\n    --speed-base: 800ms;\n    --speed-slow: 1200ms;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 16580:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.InputLabelSection-module__Root--SeXoN{font-size:14px;font-family:var(--font-family);color:var(--theme-color-fg-default);text-align:left;padding-bottom:3px;user-select:none}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/InputLabelSection/InputLabelSection.module.scss"],"names":[],"mappings":"AAAA,uCACE,cAAA,CACA,8BAAA,CACA,mCAAA,CACA,eAAA,CACA,kBAAA,CAEA,gBAAA","sourcesContent":[".Root {\n  font-size: 14px;\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-default);\n  text-align: left;\n  padding-bottom: 3px;\n\n  user-select: none;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `InputLabelSection-module__Root--SeXoN`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 16806:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgVerticalSplit = function SvgVerticalSplit(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M19.6367 5.52362L12.8867 5.52362L12.8867 18.4764L19.6367 18.4764L19.6367 5.52362ZM11.3867 18.4764L11.3867 5.52362L4.63672 5.52362L4.63672 18.4764L11.3867 18.4764ZM19.6367 4.02362C20.3687 4.02362 21.1367 4.56328 21.1367 5.43056L21.1367 18.5694C21.1367 19.4367 20.3687 19.9764 19.6367 19.9764L4.63672 19.9764C3.90471 19.9764 3.13672 19.4367 3.13672 18.5694L3.13672 5.43056C3.13672 4.56328 3.90471 4.02362 4.63672 4.02362L19.6367 4.02362Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgVerticalSplit);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "3b87057f68a3c74b1934a4e4c5cd0f7c.svg");

/***/ }),

/***/ 16885:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PropertyPanelSelectInput-module__Root--gI7zr{font-family:var(--font-family);color:var(--theme-color-fg-default);position:relative}.PropertyPanelSelectInput-module__Root--gI7zr input{cursor:pointer;user-select:none}.PropertyPanelSelectInput-module__Root--gI7zr.PropertyPanelSelectInput-module__has-caret--IuihJ input{padding-right:28px}.PropertyPanelSelectInput-module__Caret--CXGap{position:absolute;top:0;bottom:0;right:0;display:flex;align-items:center;justify-content:center;width:28px;transition:transform var(--speed-quick) var(--easing-base);pointer-events:none}.PropertyPanelSelectInput-module__Root--gI7zr:hover .PropertyPanelSelectInput-module__Caret--CXGap path{fill:var(--theme-color-fg-highlight)}.PropertyPanelSelectInput-module__Caret--CXGap.PropertyPanelSelectInput-module__is-indicating-close--OLMM3{transform:rotate(180deg)}.PropertyPanelSelectInput-module__Options--KRr3t{background-color:var(--theme-color-bg-3);list-style:none;margin:0;padding:0;font-family:var(--font-family);color:var(--theme-color-fg-default);user-select:none}.PropertyPanelSelectInput-module__Option--yhuW6{padding:6px 8px 7px;border-bottom:1px solid var(--theme-color-bg-2);font-size:12px;color:var(--theme-color-fg-default);cursor:pointer}.PropertyPanelSelectInput-module__Option--yhuW6:hover{color:var(--theme-color-fg-highlight)}.PropertyPanelSelectInput-module__Option--yhuW6.PropertyPanelSelectInput-module__is-disabled--frZpw{cursor:not-allowed;color:var(--theme-color-fg-muted) !important}.PropertyPanelSelectInput-module__Option--yhuW6.PropertyPanelSelectInput-module__has-small-text--ecPCi{font-size:10px;padding-left:4px;padding-right:4px;text-align:center}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/property-panel/PropertyPanelSelectInput/PropertyPanelSelectInput.module.scss","webpack://./../noodl-core-ui/src/styles/scss-variables/length.scss"],"names":[],"mappings":"AAEA,8CACE,8BAAA,CACA,mCAAA,CACA,iBAAA,CAEA,oDACE,cAAA,CACA,gBAAA,CAIA,sGACE,kBCbsB,CDkB5B,+CACE,iBAAA,CACA,KAAA,CACA,QAAA,CACA,OAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UC1B0B,CD2B1B,0DAAA,CACA,mBAAA,CAGE,wGACE,oCAAA,CAIJ,2GACE,wBAAA,CAIJ,iDACE,wCAAA,CACA,eAAA,CACA,QAAA,CACA,SAAA,CACA,8BAAA,CACA,mCAAA,CACA,gBAAA,CAGF,gDACE,mBCrD6B,CDsD7B,+CAAA,CACA,cAAA,CACA,mCAAA,CACA,cAAA,CAEA,sDACE,qCAAA,CAGF,oGACE,kBAAA,CACA,4CAAA,CAGF,uGACE,cAAA,CACA,gBCpE8B,CDqE9B,iBCrE8B,CDsE9B,iBAAA","sourcesContent":["@use '../../../styles/scss-variables/length.scss';\n\n.Root {\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-default);\n  position: relative;\n\n  input {\n    cursor: pointer;\n    user-select: none;\n  }\n\n  &.has-caret {\n    input {\n      padding-right: length.$property-panel-input-size;\n    }\n  }\n}\n\n.Caret {\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  right: 0;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: length.$property-panel-input-size;\n  transition: transform var(--speed-quick) var(--easing-base);\n  pointer-events: none;\n\n  .Root:hover & {\n    path {\n      fill: var(--theme-color-fg-highlight);\n    }\n  }\n\n  &.is-indicating-close {\n    transform: rotate(180deg);\n  }\n}\n\n.Options {\n  background-color: var(--theme-color-bg-3);\n  list-style: none;\n  margin: 0;\n  padding: 0;\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-default);\n  user-select: none;\n}\n\n.Option {\n  padding: length.$property-panel-input-padding;\n  border-bottom: 1px solid var(--theme-color-bg-2);\n  font-size: 12px;\n  color: var(--theme-color-fg-default);\n  cursor: pointer;\n\n  &:hover {\n    color: var(--theme-color-fg-highlight);\n  }\n\n  &.is-disabled {\n    cursor: not-allowed;\n    color: var(--theme-color-fg-muted) !important;\n  }\n\n  &.has-small-text {\n    font-size: 10px;\n    padding-left: length.$property-panel-small-xy-padding;\n    padding-right: length.$property-panel-small-xy-padding;\n    text-align: center;\n  }\n}\n","$property-panel-input-padding: 6px 8px 7px;\r\n$property-panel-input-size: 28px;\r\n$property-panel-small-xy-padding: 4px;\r\n\r\n$global-input-size: 36px;\r\n$global-input-size-small: 28px;\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PropertyPanelSelectInput-module__Root--gI7zr`,
	"has-caret": `PropertyPanelSelectInput-module__has-caret--IuihJ`,
	"Caret": `PropertyPanelSelectInput-module__Caret--CXGap`,
	"is-indicating-close": `PropertyPanelSelectInput-module__is-indicating-close--OLMM3`,
	"Options": `PropertyPanelSelectInput-module__Options--KRr3t`,
	"Option": `PropertyPanelSelectInput-module__Option--yhuW6`,
	"is-disabled": `PropertyPanelSelectInput-module__is-disabled--frZpw`,
	"has-small-text": `PropertyPanelSelectInput-module__has-small-text--ecPCi`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 16928:
/***/ ((module) => {

"use strict";
module.exports = require("path");

/***/ }),

/***/ 17549:
/***/ ((module) => {

"use strict";
module.exports = require("cookie-session");

/***/ }),

/***/ 17947:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgArrowRight = function SvgArrowRight(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M21.2437 11.9979C21.2037 11.9079 21.1537 11.8279 21.0837 11.7579L14.3337 5.00794C14.0437 4.71794 13.5637 4.71794 13.2737 5.00794C12.9837 5.29794 12.9837 5.77794 13.2737 6.06794L18.7437 11.5379H4.05371C3.64371 11.5379 3.30371 11.8779 3.30371 12.2879C3.30371 12.6979 3.64371 13.0379 4.05371 13.0379H18.7437L13.2737 18.5079C12.9837 18.7979 12.9837 19.2779 13.2737 19.5679C13.4237 19.7179 13.6137 19.7879 13.8037 19.7879C13.9937 19.7879 14.1837 19.7179 14.3337 19.5679L21.0837 12.8179C21.1537 12.7479 21.2037 12.6679 21.2437 12.5779C21.3237 12.3979 21.3237 12.1879 21.2437 12.0079V11.9979Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgArrowRight);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "57dba701e044c00a1e4659527075abf3.svg");

/***/ }),

/***/ 17951:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-dropdown {
	height: 100%;
	padding: 0;
}

.monaco-dropdown > .dropdown-label {
	cursor: pointer;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.monaco-dropdown > .dropdown-label > .action-label.disabled {
	cursor: default;
}

.monaco-dropdown-with-primary {
	display: flex !important;
	flex-direction: row;
	border-radius: 5px;
}

.monaco-dropdown-with-primary > .action-container > .action-label {
	margin-right: 0;
}

.monaco-dropdown-with-primary > .dropdown-action-container > .monaco-dropdown > .dropdown-label .codicon[class*='codicon-'] {
	font-size: 12px;
	padding-left: 0px;
	padding-right: 0px;
	line-height: 16px;
	margin-left: -3px;
}

.monaco-dropdown-with-primary > .dropdown-action-container > .monaco-dropdown > .dropdown-label > .action-label {
	display: block;
	background-size: 16px;
	background-position: center center;
	background-repeat: no-repeat;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/dropdown/dropdown.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,YAAY;CACZ,UAAU;AACX;;AAEA;CACC,eAAe;CACf,YAAY;CACZ,aAAa;CACb,mBAAmB;CACnB,uBAAuB;AACxB;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,wBAAwB;CACxB,mBAAmB;CACnB,kBAAkB;AACnB;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,eAAe;CACf,iBAAiB;CACjB,kBAAkB;CAClB,iBAAiB;CACjB,iBAAiB;AAClB;;AAEA;CACC,cAAc;CACd,qBAAqB;CACrB,kCAAkC;CAClC,4BAA4B;AAC7B","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-dropdown {\n\theight: 100%;\n\tpadding: 0;\n}\n\n.monaco-dropdown > .dropdown-label {\n\tcursor: pointer;\n\theight: 100%;\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n}\n\n.monaco-dropdown > .dropdown-label > .action-label.disabled {\n\tcursor: default;\n}\n\n.monaco-dropdown-with-primary {\n\tdisplay: flex !important;\n\tflex-direction: row;\n\tborder-radius: 5px;\n}\n\n.monaco-dropdown-with-primary > .action-container > .action-label {\n\tmargin-right: 0;\n}\n\n.monaco-dropdown-with-primary > .dropdown-action-container > .monaco-dropdown > .dropdown-label .codicon[class*='codicon-'] {\n\tfont-size: 12px;\n\tpadding-left: 0px;\n\tpadding-right: 0px;\n\tline-height: 16px;\n\tmargin-left: -3px;\n}\n\n.monaco-dropdown-with-primary > .dropdown-action-container > .monaco-dropdown > .dropdown-label > .action-label {\n\tdisplay: block;\n\tbackground-size: 16px;\n\tbackground-position: center center;\n\tbackground-repeat: no-repeat;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 18173:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.NewRecordModal-module__Overlay--vWZRX{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;z-index:1000}.NewRecordModal-module__Modal--FgHCU{background-color:var(--theme-color-bg-2);border-radius:8px;width:100%;max-width:500px;max-height:80vh;display:flex;flex-direction:column;box-shadow:0 4px 24px rgba(0,0,0,.3)}.NewRecordModal-module__Header--z7jJ8{padding:16px;border-bottom:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-3);border-radius:8px 8px 0 0}.NewRecordModal-module__Content--orBl8{padding:16px;overflow-y:auto;flex:1}.NewRecordModal-module__Field--F2wd2{margin-bottom:16px}.NewRecordModal-module__Field--F2wd2:last-child{margin-bottom:0}.NewRecordModal-module__Label--cguhs{display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:12px;color:var(--theme-color-fg-default);font-weight:500}.NewRecordModal-module__Required--oN1hG{color:var(--theme-color-danger)}.NewRecordModal-module__TypeHint--eON9p{font-size:10px;color:var(--theme-color-fg-default-shy);text-transform:uppercase;padding:2px 6px;background-color:var(--theme-color-bg-1);border-radius:4px}.NewRecordModal-module__Input--LBoM3{width:100%;padding:8px 12px;border:1px solid var(--theme-color-border-default);border-radius:4px;background-color:var(--theme-color-bg-3);color:var(--theme-color-fg-default);font-size:13px}.NewRecordModal-module__Input--LBoM3:focus{outline:none;border-color:var(--theme-color-primary)}.NewRecordModal-module__JsonInput--oww3S{width:100%;padding:8px 12px;border:1px solid var(--theme-color-border-default);border-radius:4px;background-color:var(--theme-color-bg-3);color:var(--theme-color-fg-default);font-size:12px;font-family:monospace;resize:vertical}.NewRecordModal-module__JsonInput--oww3S:focus{outline:none;border-color:var(--theme-color-primary)}.NewRecordModal-module__Error--V0AAe{padding:12px;background-color:var(--theme-color-danger-bg);border-radius:4px;margin-top:16px;color:var(--theme-color-danger)}.NewRecordModal-module__Footer--fcr4o{display:flex;justify-content:flex-end;gap:8px;padding:16px;border-top:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-3);border-radius:0 0 8px 8px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/databrowser/NewRecordModal.module.scss"],"names":[],"mappings":"AAIA,uCACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,+BAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,YAAA,CAGF,qCACE,wCAAA,CACA,iBAAA,CACA,UAAA,CACA,eAAA,CACA,eAAA,CACA,YAAA,CACA,qBAAA,CACA,oCAAA,CAGF,sCACE,YAAA,CACA,yDAAA,CACA,wCAAA,CACA,yBAAA,CAGF,uCACE,YAAA,CACA,eAAA,CACA,MAAA,CAGF,qCACE,kBAAA,CAEA,gDACE,eAAA,CAIJ,qCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,iBAAA,CACA,cAAA,CACA,mCAAA,CACA,eAAA,CAGF,wCACE,+BAAA,CAGF,wCACE,cAAA,CACA,uCAAA,CACA,wBAAA,CACA,eAAA,CACA,wCAAA,CACA,iBAAA,CAGF,qCACE,UAAA,CACA,gBAAA,CACA,kDAAA,CACA,iBAAA,CACA,wCAAA,CACA,mCAAA,CACA,cAAA,CAEA,2CACE,YAAA,CACA,uCAAA,CAIJ,yCACE,UAAA,CACA,gBAAA,CACA,kDAAA,CACA,iBAAA,CACA,wCAAA,CACA,mCAAA,CACA,cAAA,CACA,qBAAA,CACA,eAAA,CAEA,+CACE,YAAA,CACA,uCAAA,CAIJ,qCACE,YAAA,CACA,6CAAA,CACA,iBAAA,CACA,eAAA,CACA,+BAAA,CAGF,sCACE,YAAA,CACA,wBAAA,CACA,OAAA,CACA,YAAA,CACA,sDAAA,CACA,wCAAA,CACA,yBAAA","sourcesContent":["/**\n * NewRecordModal styles\n */\n\n.Overlay {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.5);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 1000;\n}\n\n.Modal {\n  background-color: var(--theme-color-bg-2);\n  border-radius: 8px;\n  width: 100%;\n  max-width: 500px;\n  max-height: 80vh;\n  display: flex;\n  flex-direction: column;\n  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.3);\n}\n\n.Header {\n  padding: 16px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-3);\n  border-radius: 8px 8px 0 0;\n}\n\n.Content {\n  padding: 16px;\n  overflow-y: auto;\n  flex: 1;\n}\n\n.Field {\n  margin-bottom: 16px;\n\n  &:last-child {\n    margin-bottom: 0;\n  }\n}\n\n.Label {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin-bottom: 6px;\n  font-size: 12px;\n  color: var(--theme-color-fg-default);\n  font-weight: 500;\n}\n\n.Required {\n  color: var(--theme-color-danger);\n}\n\n.TypeHint {\n  font-size: 10px;\n  color: var(--theme-color-fg-default-shy);\n  text-transform: uppercase;\n  padding: 2px 6px;\n  background-color: var(--theme-color-bg-1);\n  border-radius: 4px;\n}\n\n.Input {\n  width: 100%;\n  padding: 8px 12px;\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-default);\n  font-size: 13px;\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.JsonInput {\n  width: 100%;\n  padding: 8px 12px;\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n  font-family: monospace;\n  resize: vertical;\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.Error {\n  padding: 12px;\n  background-color: var(--theme-color-danger-bg);\n  border-radius: 4px;\n  margin-top: 16px;\n  color: var(--theme-color-danger);\n}\n\n.Footer {\n  display: flex;\n  justify-content: flex-end;\n  gap: 8px;\n  padding: 16px;\n  border-top: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-3);\n  border-radius: 0 0 8px 8px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Overlay": `NewRecordModal-module__Overlay--vWZRX`,
	"Modal": `NewRecordModal-module__Modal--FgHCU`,
	"Header": `NewRecordModal-module__Header--z7jJ8`,
	"Content": `NewRecordModal-module__Content--orBl8`,
	"Field": `NewRecordModal-module__Field--F2wd2`,
	"Label": `NewRecordModal-module__Label--cguhs`,
	"Required": `NewRecordModal-module__Required--oN1hG`,
	"TypeHint": `NewRecordModal-module__TypeHint--eON9p`,
	"Input": `NewRecordModal-module__Input--LBoM3`,
	"JsonInput": `NewRecordModal-module__JsonInput--oww3S`,
	"Error": `NewRecordModal-module__Error--V0AAe`,
	"Footer": `NewRecordModal-module__Footer--fcr4o`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 18216:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Batches = void 0;
const resource_1 = __webpack_require__(39929);
const pagination_1 = __webpack_require__(92081);
const headers_1 = __webpack_require__(79973);
const jsonl_1 = __webpack_require__(60535);
const error_1 = __webpack_require__(92651);
const path_1 = __webpack_require__(20854);
class Batches extends resource_1.APIResource {
    /**
     * Send a batch of Message creation requests.
     *
     * The Message Batches API can be used to process multiple Messages API requests at
     * once. Once a Message Batch is created, it begins processing immediately. Batches
     * can take up to 24 hours to complete.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * const messageBatch = await client.messages.batches.create({
     *   requests: [
     *     {
     *       custom_id: 'my-custom-id-1',
     *       params: {
     *         max_tokens: 1024,
     *         messages: [
     *           { content: 'Hello, world', role: 'user' },
     *         ],
     *         model: 'claude-sonnet-4-5-20250929',
     *       },
     *     },
     *   ],
     * });
     * ```
     */
    create(body, options) {
        return this._client.post('/v1/messages/batches', { body, ...options });
    }
    /**
     * This endpoint is idempotent and can be used to poll for Message Batch
     * completion. To access the results of a Message Batch, make a request to the
     * `results_url` field in the response.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * const messageBatch = await client.messages.batches.retrieve(
     *   'message_batch_id',
     * );
     * ```
     */
    retrieve(messageBatchID, options) {
        return this._client.get((0, path_1.path) `/v1/messages/batches/${messageBatchID}`, options);
    }
    /**
     * List all Message Batches within a Workspace. Most recently created batches are
     * returned first.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * // Automatically fetches more pages as needed.
     * for await (const messageBatch of client.messages.batches.list()) {
     *   // ...
     * }
     * ```
     */
    list(query = {}, options) {
        return this._client.getAPIList('/v1/messages/batches', (pagination_1.Page), { query, ...options });
    }
    /**
     * Delete a Message Batch.
     *
     * Message Batches can only be deleted once they've finished processing. If you'd
     * like to delete an in-progress batch, you must first cancel it.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * const deletedMessageBatch =
     *   await client.messages.batches.delete('message_batch_id');
     * ```
     */
    delete(messageBatchID, options) {
        return this._client.delete((0, path_1.path) `/v1/messages/batches/${messageBatchID}`, options);
    }
    /**
     * Batches may be canceled any time before processing ends. Once cancellation is
     * initiated, the batch enters a `canceling` state, at which time the system may
     * complete any in-progress, non-interruptible requests before finalizing
     * cancellation.
     *
     * The number of canceled requests is specified in `request_counts`. To determine
     * which requests were canceled, check the individual results within the batch.
     * Note that cancellation may not result in any canceled requests if they were
     * non-interruptible.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * const messageBatch = await client.messages.batches.cancel(
     *   'message_batch_id',
     * );
     * ```
     */
    cancel(messageBatchID, options) {
        return this._client.post((0, path_1.path) `/v1/messages/batches/${messageBatchID}/cancel`, options);
    }
    /**
     * Streams the results of a Message Batch as a `.jsonl` file.
     *
     * Each line in the file is a JSON object containing the result of a single request
     * in the Message Batch. Results are not guaranteed to be in the same order as
     * requests. Use the `custom_id` field to match results to requests.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * const messageBatchIndividualResponse =
     *   await client.messages.batches.results('message_batch_id');
     * ```
     */
    async results(messageBatchID, options) {
        const batch = await this.retrieve(messageBatchID);
        if (!batch.results_url) {
            throw new error_1.AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
        }
        return this._client
            .get(batch.results_url, {
            ...options,
            headers: (0, headers_1.buildHeaders)([{ Accept: 'application/binary' }, options?.headers]),
            stream: true,
            __binaryResponse: true,
        })
            ._thenUnwrap((_, props) => jsonl_1.JSONLDecoder.fromResponse(props.response, props.controller));
    }
}
exports.Batches = Batches;
//# sourceMappingURL=batches.js.map

/***/ }),

/***/ 18279:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.HighlightOverlay-module__highlightOverlay--_xlGd{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;overflow:hidden;z-index:100}.HighlightOverlay-module__highlightContainer--Q5Pmi{position:absolute;top:0;left:0;transform-origin:0 0;pointer-events:none}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightOverlay.module.scss"],"names":[],"mappings":"AAOA,kDACE,iBAAA,CACA,KAAA,CACA,MAAA,CACA,UAAA,CACA,WAAA,CACA,mBAAA,CACA,eAAA,CACA,WAAA,CAGF,oDACE,iBAAA,CACA,KAAA,CACA,MAAA,CACA,oBAAA,CACA,mBAAA","sourcesContent":["/**\n * HighlightOverlay container styles\n *\n * Main overlay container for rendering highlights over the canvas.\n * Uses CSS transform pattern for automatic coordinate mapping.\n */\n\n.highlightOverlay {\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  pointer-events: none;\n  overflow: hidden;\n  z-index: 100; // Above canvas but below UI elements\n}\n\n.highlightContainer {\n  position: absolute;\n  top: 0;\n  left: 0;\n  transform-origin: 0 0;\n  pointer-events: none;\n\n  // Transform applied inline via style prop:\n  // transform: translate(viewportX, viewportY) scale(zoom)\n\n  // This automatically maps all child coordinates to canvas space\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"highlightOverlay": `HighlightOverlay-module__highlightOverlay--_xlGd`,
	"highlightContainer": `HighlightOverlay-module__highlightContainer--Q5Pmi`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 18498:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   NodeGraphContextProvider: () => (/* binding */ NodeGraphContextProvider),
/* harmony export */   NodeGraphContextTmp: () => (/* binding */ NodeGraphContextTmp),
/* harmony export */   useNodeGraphContext: () => (/* binding */ useNodeGraphContext)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6203);
/* harmony import */ var _noodl_models_sidebar__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(53612);
/* harmony import */ var _noodl_utils_NodeGraph__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(52877);
/* harmony import */ var _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(11138);
/* harmony import */ var _views_nodegrapheditor__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(98278);






const NodeGraphContext = (0,react__WEBPACK_IMPORTED_MODULE_0__.createContext)({
    active: null,
    nodeGraph: null,
    switchToComponent: null
});
class NodeGraphContextTmp {
}
function NodeGraphContextProvider({ children }) {
    const [active, setActive] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null);
    const [nodeGraph, setNodeGraph] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null);
    //create node graph, and support hot reloading it
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        function createNodeGraph() {
            const newNodeGraph = new _views_nodegrapheditor__WEBPACK_IMPORTED_MODULE_5__/* .NodeGraphEditor */ ._({});
            newNodeGraph.render();
            return newNodeGraph;
        }
        let currentInstance = createNodeGraph();
        setNodeGraph(currentInstance);
        if (false) // removed by dead control flow
{}
        return () => {
            currentInstance.dispose();
        };
    }, []);
    // Detect and apply read-only mode from ProjectModel
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        if (!nodeGraph)
            return;
        const eventGroup = {};
        // Apply read-only mode when project instance changes
        const updateReadOnlyMode = () => {
            var _a;
            const isReadOnly = ((_a = _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a._isReadOnly) || false;
            nodeGraph.setReadOnly(isReadOnly);
        };
        // Listen for project changes
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_4__.EventDispatcher.instance.on('ProjectModel.instanceHasChanged', updateReadOnlyMode, eventGroup);
        // Apply immediately if project is already loaded
        updateReadOnlyMode();
        return () => {
            _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_4__.EventDispatcher.instance.off(eventGroup);
        };
    }, [nodeGraph]);
    const switchToComponent = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((component, options) => {
        if (!component)
            return;
        nodeGraph.switchToComponent(component, options);
    }, [nodeGraph]);
    //switch sidebar panel when components are selected in the node graph
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        if (!nodeGraph)
            return;
        function _update(model) {
            if ((0,_noodl_utils_NodeGraph__WEBPACK_IMPORTED_MODULE_3__/* .isComponentModel_CloudRuntime */ .dk)(model)) {
                setActive('backend');
                if (_noodl_models_sidebar__WEBPACK_IMPORTED_MODULE_2__/* .SidebarModel */ .s.instance.ActiveId === 'components') {
                    _noodl_models_sidebar__WEBPACK_IMPORTED_MODULE_2__/* .SidebarModel */ .s.instance.switch('cloud-functions');
                }
            }
            else {
                setActive('frontend');
                if (_noodl_models_sidebar__WEBPACK_IMPORTED_MODULE_2__/* .SidebarModel */ .s.instance.ActiveId === 'cloud-functions') {
                    _noodl_models_sidebar__WEBPACK_IMPORTED_MODULE_2__/* .SidebarModel */ .s.instance.switch('components');
                }
            }
        }
        const eventGroup = {};
        nodeGraph.on('activeComponentChanged', ({ model }) => {
            _update(model);
        }, eventGroup);
        _update(nodeGraph.activeComponent);
        return () => {
            nodeGraph.off(eventGroup);
        };
    }, [nodeGraph]);
    // Screenshot helper
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        function setupScreenshot() {
            window.resizeTo(1920, 1080);
            // Something something Panel size = default
            // Allow the resize to do it's thing first
            setTimeout(() => {
                nodeGraph.centerToFit(_views_nodegrapheditor__WEBPACK_IMPORTED_MODULE_5__/* .CenterToFitMode */ .v.AllNodes);
            }, 50);
        }
        // @ts-expect-error
        window.setupScreenshot = setupScreenshot;
        return function () {
            // @ts-expect-error
            window.setupScreenshot = undefined;
        };
    }, []);
    //set global on a singleton for code that can't access the react context
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        if (!nodeGraph)
            return;
        NodeGraphContextTmp.switchToComponent = switchToComponent;
        NodeGraphContextTmp.nodeGraph = nodeGraph;
        return () => {
            NodeGraphContextTmp.active = null;
            NodeGraphContextTmp.nodeGraph = null;
            NodeGraphContextTmp.switchToComponent = null;
        };
    }, [nodeGraph]);
    NodeGraphContextTmp.active = active;
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(NodeGraphContext.Provider, { value: {
            active,
            nodeGraph,
            switchToComponent
        } }, children));
}
function useNodeGraphContext() {
    const context = (0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(NodeGraphContext);
    if (context === undefined) {
        throw new Error('useNodeGraphContext must be a child of NodeGraphContextProvider');
    }
    return context;
}


/***/ }),

/***/ 18772:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgViewportHorizontalArrow = function SvgViewportHorizontalArrow(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 25,
    viewBox: "0 0 24 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M1.06299 5.51865C1.06299 4.55215 1.84649 3.76865 2.81299 3.76865H21.1929C22.1594 3.76865 22.9429 4.55215 22.9429 5.51865V20.3024C22.9429 21.2689 22.1594 22.0524 21.1929 22.0524H2.81299C1.84649 22.0524 1.06299 21.2689 1.06299 20.3024V5.51865ZM2.81299 5.26865C2.67492 5.26865 2.56299 5.38058 2.56299 5.51865V20.3024C2.56299 20.4404 2.67492 20.5524 2.81299 20.5524H21.1929C21.3309 20.5524 21.4429 20.4404 21.4429 20.3024V5.51865C21.4429 5.38057 21.3309 5.26865 21.1929 5.26865H2.81299Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M19.2861 12.9105C19.2861 13.3247 18.9503 13.6605 18.5361 13.6605H5.46423C5.05002 13.6605 4.71423 13.3247 4.71423 12.9105C4.71423 12.4963 5.05002 12.1605 5.46423 12.1605H18.5361C18.9503 12.1605 19.2861 12.4963 19.2861 12.9105Z",
    fill: "#B8B8B8"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M19.0665 12.3802C19.3594 12.6731 19.3594 13.1479 19.0665 13.4408L16.0665 16.4408C15.7736 16.7337 15.2987 16.7337 15.0058 16.4408C14.7129 16.1479 14.7129 15.6731 15.0058 15.3802L17.4755 12.9105L15.0058 10.4408C14.7129 10.1479 14.7129 9.67307 15.0058 9.38018C15.2987 9.08728 15.7736 9.08728 16.0665 9.38018L19.0665 12.3802Z",
    fill: "#B8B8B8"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.93354 12.3802C4.64064 12.6731 4.64064 13.1479 4.93354 13.4408L7.93354 16.4408C8.22643 16.7337 8.7013 16.7337 8.9942 16.4408C9.28709 16.1479 9.28709 15.6731 8.9942 15.3802L6.52453 12.9105L8.9942 10.4408C9.28709 10.1479 9.28709 9.67307 8.9942 9.38018C8.7013 9.08728 8.22643 9.08728 7.93354 9.38018L4.93354 12.3802Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgViewportHorizontalArrow);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "91ea4efbbe7b820864fe82ff33c312a2.svg");

/***/ }),

/***/ 19421:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.LauncherPage-module__Root--dB7GE{margin:0 auto;max-width:800px;margin-top:82px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherPage/LauncherPage.module.scss"],"names":[],"mappings":"AAAA,kCACE,aAAA,CACA,eAAA,CACA,eAAA","sourcesContent":[".Root {\n  margin: 0 auto;\n  max-width: 800px;\n  margin-top: 82px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `LauncherPage-module__Root--dB7GE`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 19448:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Logo-module__Root--YlwJ9{width:40px;height:40px}.Logo-module__Root--YlwJ9 svg{width:100%;height:100%}.Logo-module__Root--YlwJ9.Logo-module__is-variant-grayscale--yg53D{opacity:.7}.Logo-module__Root--YlwJ9.Logo-module__is-size-small--AEcKN{width:32px;height:32px}.Logo-module__Root--YlwJ9.Logo-module__is-size-large--tElTl{width:60px;height:60px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/common/Logo/Logo.module.scss"],"names":[],"mappings":"AAAA,0BACE,UAAA,CACA,WAAA,CAEA,8BACE,UAAA,CACA,WAAA,CAGF,mEACE,UAAA,CAGF,4DACE,UAAA,CACA,WAAA,CAGF,4DACE,UAAA,CACA,WAAA","sourcesContent":[".Root {\n  width: 40px;\n  height: 40px;\n\n  svg {\n    width: 100%;\n    height: 100%;\n  }\n\n  &.is-variant-grayscale {\n    opacity: 0.7;\n  }\n\n  &.is-size-small {\n    width: 32px;\n    height: 32px;\n  }\n\n  &.is-size-large {\n    width: 60px;\n    height: 60px;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Logo-module__Root--YlwJ9`,
	"is-variant-grayscale": `Logo-module__is-variant-grayscale--yg53D`,
	"is-size-small": `Logo-module__is-size-small--AEcKN`,
	"is-size-large": `Logo-module__is-size-large--tElTl`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 19679:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_checkAndCompact, _BetaToolRunner_generateToolResponse;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BetaToolRunner = void 0;
const tslib_1 = __webpack_require__(84499);
const error_1 = __webpack_require__(37015);
const headers_1 = __webpack_require__(79973);
const CompactionControl_1 = __webpack_require__(88159);
/**
 * Just Promise.withResolvers(), which is not available in all environments.
 */
function promiseWithResolvers() {
    let resolve;
    let reject;
    const promise = new Promise((res, rej) => {
        resolve = res;
        reject = rej;
    });
    return { promise, resolve: resolve, reject: reject };
}
/**
 * A ToolRunner handles the automatic conversation loop between the assistant and tools.
 *
 * A ToolRunner is an async iterable that yields either BetaMessage or BetaMessageStream objects
 * depending on the streaming configuration.
 */
class BetaToolRunner {
    constructor(client, params, options) {
        _BetaToolRunner_instances.add(this);
        this.client = client;
        /** Whether the async iterator has been consumed */
        _BetaToolRunner_consumed.set(this, false);
        /** Whether parameters have been mutated since the last API call */
        _BetaToolRunner_mutated.set(this, false);
        /** Current state containing the request parameters */
        _BetaToolRunner_state.set(this, void 0);
        _BetaToolRunner_options.set(this, void 0);
        /** Promise for the last message received from the assistant */
        _BetaToolRunner_message.set(this, void 0);
        /** Cached tool response to avoid redundant executions */
        _BetaToolRunner_toolResponse.set(this, void 0);
        /** Promise resolvers for waiting on completion */
        _BetaToolRunner_completion.set(this, void 0);
        /** Number of iterations (API requests) made so far */
        _BetaToolRunner_iterationCount.set(this, 0);
        tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_state, {
            params: {
                // You can't clone the entire params since there are functions as handlers.
                // You also don't really need to clone params.messages, but it probably will prevent a foot gun
                // somewhere.
                ...params,
                messages: structuredClone(params.messages),
            },
        }, "f");
        tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_options, {
            ...options,
            headers: (0, headers_1.buildHeaders)([{ 'x-stainless-helper': 'BetaToolRunner' }, options?.headers]),
        }, "f");
        tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f");
    }
    async *[(_BetaToolRunner_consumed = new WeakMap(), _BetaToolRunner_mutated = new WeakMap(), _BetaToolRunner_state = new WeakMap(), _BetaToolRunner_options = new WeakMap(), _BetaToolRunner_message = new WeakMap(), _BetaToolRunner_toolResponse = new WeakMap(), _BetaToolRunner_completion = new WeakMap(), _BetaToolRunner_iterationCount = new WeakMap(), _BetaToolRunner_instances = new WeakSet(), _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact() {
        const compactionControl = tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.compactionControl;
        if (!compactionControl || !compactionControl.enabled) {
            return false;
        }
        let tokensUsed = 0;
        if (tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_message, "f") !== undefined) {
            try {
                const message = await tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_message, "f");
                const totalInputTokens = message.usage.input_tokens +
                    (message.usage.cache_creation_input_tokens ?? 0) +
                    (message.usage.cache_read_input_tokens ?? 0);
                tokensUsed = totalInputTokens + message.usage.output_tokens;
            }
            catch {
                // If we can't get the message, skip compaction
                return false;
            }
        }
        const threshold = compactionControl.contextTokenThreshold ?? CompactionControl_1.DEFAULT_TOKEN_THRESHOLD;
        if (tokensUsed < threshold) {
            return false;
        }
        const model = compactionControl.model ?? tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.model;
        const summaryPrompt = compactionControl.summaryPrompt ?? CompactionControl_1.DEFAULT_SUMMARY_PROMPT;
        const messages = tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages;
        if (messages[messages.length - 1].role === 'assistant') {
            // Remove tool_use blocks from the last message to avoid 400 error
            // (tool_use requires tool_result, which we don't have yet)
            const lastMessage = messages[messages.length - 1];
            if (Array.isArray(lastMessage.content)) {
                const nonToolBlocks = lastMessage.content.filter((block) => block.type !== 'tool_use');
                if (nonToolBlocks.length === 0) {
                    // If all blocks were tool_use, just remove the message entirely
                    messages.pop();
                }
                else {
                    lastMessage.content = nonToolBlocks;
                }
            }
        }
        const response = await this.client.beta.messages.create({
            model,
            messages: [
                ...messages,
                {
                    role: 'user',
                    content: [
                        {
                            type: 'text',
                            text: summaryPrompt,
                        },
                    ],
                },
            ],
            max_tokens: tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens,
        }, {
            headers: { 'x-stainless-helper': 'compaction' },
        });
        if (response.content[0]?.type !== 'text') {
            throw new error_1.AnthropicError('Expected text response for compaction');
        }
        tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages = [
            {
                role: 'user',
                content: response.content,
            },
        ];
        return true;
    }, Symbol.asyncIterator)]() {
        var _a;
        if (tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) {
            throw new error_1.AnthropicError('Cannot iterate over a consumed stream');
        }
        tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f");
        tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f");
        tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f");
        try {
            while (true) {
                let stream;
                try {
                    if (tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations &&
                        tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) {
                        break;
                    }
                    tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f");
                    tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f");
                    tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a = tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a++, _a), "f");
                    tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_message, undefined, "f");
                    const { max_iterations, compactionControl, ...params } = tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params;
                    if (params.stream) {
                        stream = this.client.beta.messages.stream({ ...params }, tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_options, "f"));
                        tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_message, stream.finalMessage(), "f");
                        // Make sure that this promise doesn't throw before we get the option to do something about it.
                        // Error will be caught when we call await this.#message ultimately
                        tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_message, "f").catch(() => { });
                        yield stream;
                    }
                    else {
                        tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f");
                        yield tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_message, "f");
                    }
                    const isCompacted = await tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this);
                    if (!isCompacted) {
                        if (!tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) {
                            const { role, content } = await tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_message, "f");
                            tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ role, content });
                        }
                        const toolMessage = await tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1));
                        if (toolMessage) {
                            tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage);
                        }
                        else if (!tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) {
                            break;
                        }
                    }
                }
                finally {
                    if (stream) {
                        stream.abort();
                    }
                }
            }
            if (!tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) {
                throw new error_1.AnthropicError('ToolRunner concluded without a message from the server');
            }
            tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_message, "f"));
        }
        catch (error) {
            tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f");
            // Silence unhandled promise errors
            tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => { });
            tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error);
            tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f");
            throw error;
        }
    }
    setMessagesParams(paramsOrMutator) {
        if (typeof paramsOrMutator === 'function') {
            tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params);
        }
        else {
            tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator;
        }
        tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f");
        // Invalidate cached tool response since parameters changed
        tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f");
    }
    /**
     * Get the tool response for the last message from the assistant.
     * Avoids redundant tool executions by caching results.
     *
     * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed
     *
     * @example
     * const toolResponse = await runner.generateToolResponse();
     * if (toolResponse) {
     *   console.log('Tool results:', toolResponse.content);
     * }
     */
    async generateToolResponse() {
        const message = (await tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) ?? this.params.messages.at(-1);
        if (!message) {
            return null;
        }
        return tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message);
    }
    /**
     * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and
     * will wait for an instance to start and go to completion.
     *
     * @returns A promise that resolves to the final BetaMessage when the iterator completes
     *
     * @example
     * // Start consuming the iterator
     * for await (const message of runner) {
     *   console.log('Message:', message.content);
     * }
     *
     * // Meanwhile, wait for completion from another part of the code
     * const finalMessage = await runner.done();
     * console.log('Final response:', finalMessage.content);
     */
    done() {
        return tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise;
    }
    /**
     * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream:
     * * If the iterator has not been consumed, consume the entire iterator and return the final message from the
     * assistant.
     * * If the iterator has been consumed, waits for it to complete and returns the final message.
     *
     * @returns A promise that resolves to the final BetaMessage from the conversation
     * @throws {AnthropicError} If no messages were processed during the conversation
     *
     * @example
     * const finalMessage = await runner.runUntilDone();
     * console.log('Final response:', finalMessage.content);
     */
    async runUntilDone() {
        // If not yet consumed, start consuming and wait for completion
        if (!tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) {
            for await (const _ of this) {
                // Iterator naturally populates this.#message
            }
        }
        // If consumed but not completed, wait for completion
        return this.done();
    }
    /**
     * Get the current parameters being used by the ToolRunner.
     *
     * @returns A readonly view of the current ToolRunnerParams
     *
     * @example
     * const currentParams = runner.params;
     * console.log('Current model:', currentParams.model);
     * console.log('Message count:', currentParams.messages.length);
     */
    get params() {
        return tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params;
    }
    /**
     * Add one or more messages to the conversation history.
     *
     * @param messages - One or more BetaMessageParam objects to add to the conversation
     *
     * @example
     * runner.pushMessages(
     *   { role: 'user', content: 'Also, what about the weather in NYC?' }
     * );
     *
     * @example
     * // Adding multiple messages
     * runner.pushMessages(
     *   { role: 'user', content: 'What about NYC?' },
     *   { role: 'user', content: 'And Boston?' }
     * );
     */
    pushMessages(...messages) {
        this.setMessagesParams((params) => ({
            ...params,
            messages: [...params.messages, ...messages],
        }));
    }
    /**
     * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone()
     * This allows using `await runner` instead of `await runner.runUntilDone()`
     */
    then(onfulfilled, onrejected) {
        return this.runUntilDone().then(onfulfilled, onrejected);
    }
}
exports.BetaToolRunner = BetaToolRunner;
_BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse(lastMessage) {
    if (tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== undefined) {
        return tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f");
    }
    tslib_1.__classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage), "f");
    return tslib_1.__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f");
};
async function generateToolResponse(params, lastMessage = params.messages.at(-1)) {
    // Only process if the last message is from the assistant and has tool use blocks
    if (!lastMessage ||
        lastMessage.role !== 'assistant' ||
        !lastMessage.content ||
        typeof lastMessage.content === 'string') {
        return null;
    }
    const toolUseBlocks = lastMessage.content.filter((content) => content.type === 'tool_use');
    if (toolUseBlocks.length === 0) {
        return null;
    }
    const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => {
        const tool = params.tools.find((t) => ('name' in t ? t.name : t.mcp_server_name) === toolUse.name);
        if (!tool || !('run' in tool)) {
            return {
                type: 'tool_result',
                tool_use_id: toolUse.id,
                content: `Error: Tool '${toolUse.name}' not found`,
                is_error: true,
            };
        }
        try {
            let input = toolUse.input;
            if ('parse' in tool && tool.parse) {
                input = tool.parse(input);
            }
            const result = await tool.run(input);
            return {
                type: 'tool_result',
                tool_use_id: toolUse.id,
                content: result,
            };
        }
        catch (error) {
            return {
                type: 'tool_result',
                tool_use_id: toolUse.id,
                content: `Error: ${error instanceof Error ? error.message : String(error)}`,
                is_error: true,
            };
        }
    }));
    return {
        role: 'user',
        content: toolResults,
    };
}
//# sourceMappingURL=BetaToolRunner.js.map

/***/ }),

/***/ 19781:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgFileFill = function SvgFileFill(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M20.1711 8.1105L14.9211 2.8605C14.7782 2.7212 14.5863 2.64375 14.3867 2.64487H5.38672C4.98889 2.64487 4.60736 2.80291 4.32606 3.08421C4.04475 3.36552 3.88672 3.74705 3.88672 4.14487V20.6449C3.88672 21.0427 4.04475 21.4242 4.32606 21.7055C4.60736 21.9868 4.98889 22.1449 5.38672 22.1449H18.8867C19.2845 22.1449 19.6661 21.9868 19.9474 21.7055C20.2287 21.4242 20.3867 21.0427 20.3867 20.6449V8.64487C20.3878 8.44533 20.3104 8.25337 20.1711 8.1105ZM14.3867 8.64487V4.51987L18.5117 8.64487H14.3867Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgFileFill);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "e9799aaa8dd2bb66a6590d4798526052.svg");

/***/ }),

/***/ 19817:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.AiChatBox-module__ScrollContainer--WznUG{position:relative;height:100%;display:flex;justify-content:end;overflow:hidden;flex-direction:column}.AiChatBox-module__ScrollArea--FmmoA{display:flex;flex-direction:column;overflow-y:scroll;overflow-y:overlay}.AiChatBox-module__JumpToPresentContainer--GEcID{display:flex;justify-content:center;padding-bottom:8px;position:absolute;bottom:0;left:0;right:0;pointer-events:none}.AiChatBox-module__JumpToPresent--SVJ6F{display:none;padding:4px;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-bg-3);cursor:pointer;user-select:none;pointer-events:all;transition:background-color 100ms ease;transform:translate(0, 20%);animation:AiChatBox-module__slide--jAr8E 500ms forwards}.AiChatBox-module__JumpToPresent--SVJ6F:hover{background-color:var(--theme-color-bg-3)}.AiChatBox-module__JumpToPresent--SVJ6F.AiChatBox-module__is-past--nmAcs{display:block}@keyframes AiChatBox-module__slide--jAr8E{100%{transform:translate(0, 0)}}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/ai/AiChatBox/AiChatBox.module.scss"],"names":[],"mappings":"AAAA,0CACE,iBAAA,CACA,WAAA,CACA,YAAA,CACA,mBAAA,CACA,eAAA,CACA,qBAAA,CAGF,qCACE,YAAA,CACA,qBAAA,CAGA,iBAAA,CACA,kBAAA,CAGF,iDACE,YAAA,CACA,sBAAA,CACA,kBAAA,CACA,iBAAA,CACA,QAAA,CACA,MAAA,CACA,OAAA,CACA,mBAAA,CAGF,wCACE,YAAA,CAEA,WAAA,CACA,wCAAA,CACA,wCAAA,CAEA,cAAA,CACA,gBAAA,CACA,kBAAA,CAEA,sCAAA,CACA,2BAAA,CACA,uDAAA,CAEA,8CACE,wCAAA,CAGF,yEACE,aAAA,CAIJ,0CACE,KACE,yBAAA,CAAA","sourcesContent":[".ScrollContainer {\n  position: relative;\n  height: 100%;\n  display: flex;\n  justify-content: end;\n  overflow: hidden;\n  flex-direction: column;\n}\n\n.ScrollArea {\n  display: flex;\n  flex-direction: column;\n  // padding-top: 8px;\n  // padding-bottom: 8px;\n  overflow-y: scroll;\n  overflow-y: overlay;\n}\n\n.JumpToPresentContainer {\n  display: flex;\n  justify-content: center;\n  padding-bottom: 8px;\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  right: 0;\n  pointer-events: none;\n}\n\n.JumpToPresent {\n  display: none;\n\n  padding: 4px;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-bg-3);\n\n  cursor: pointer;\n  user-select: none;\n  pointer-events: all;\n\n  transition: background-color 100ms ease;\n  transform: translate(0, 20%);\n  animation: slide 500ms forwards;\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.is-past {\n    display: block;\n  }\n}\n\n@keyframes slide {\n  100% {\n    transform: translate(0, 0);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"ScrollContainer": `AiChatBox-module__ScrollContainer--WznUG`,
	"ScrollArea": `AiChatBox-module__ScrollArea--FmmoA`,
	"JumpToPresentContainer": `AiChatBox-module__JumpToPresentContainer--GEcID`,
	"JumpToPresent": `AiChatBox-module__JumpToPresent--SVJ6F`,
	"slide": `AiChatBox-module__slide--jAr8E`,
	"is-past": `AiChatBox-module__is-past--nmAcs`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 20014:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  N: () => (/* reexport */ Collapsible)
});

// EXTERNAL MODULE: ./src/editor/src/hooks/useCallAfterNextRender.ts
var useCallAfterNextRender = __webpack_require__(61113);
// EXTERNAL MODULE: ./src/editor/src/hooks/useCustomPropertyValue.ts
var useCustomPropertyValue = __webpack_require__(26225);
// EXTERNAL MODULE: ./src/editor/src/hooks/usePrevious.ts
var usePrevious = __webpack_require__(45217);
// EXTERNAL MODULE: ./src/editor/src/hooks/useTimeout.ts
var useTimeout = __webpack_require__(98849);
// EXTERNAL MODULE: ./src/editor/src/hooks/useWindowSize.ts
var useWindowSize = __webpack_require__(58541);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/Collapsible/Collapsible.module.scss
var Collapsible_module = __webpack_require__(37833);
;// ../noodl-core-ui/src/components/layout/Collapsible/Collapsible.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(Collapsible_module/* default */.A, options);




       /* harmony default export */ const Collapsible_Collapsible_module = (Collapsible_module/* default */.A && Collapsible_module/* default */.A.locals ? Collapsible_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/Collapsible/Collapsible.tsx







function Collapsible({ children, transitionMs = 400, easingFunction, isCollapsed, disableTransition }) {
    const innerRef = (0,external_react_.useRef)(null);
    const wasCollapsed = (0,usePrevious/* default */.A)(isCollapsed);
    const [componentHeight, setComponentHeight] = (0,external_react_.useState)('auto');
    const [hasFinishedOpening, setHasFinishedOpening] = (0,external_react_.useState)(!isCollapsed);
    const [clearTimeout, setClearTimeout] = (0,external_react_.useState)(false);
    const defaultEasing = (0,useCustomPropertyValue/* useCustomPropertyValue */.l)(useCustomPropertyValue/* CustomPropertyAnimation */.X.EasingBase);
    const easing = easingFunction || defaultEasing;
    const doAfterNextRender = (0,useCallAfterNextRender/* default */.A)();
    (0,useWindowSize/* default */.A)();
    (0,external_react_.useLayoutEffect)(() => {
        doAfterNextRender(() => {
            var _a;
            const newHeight = Math.ceil((_a = innerRef.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect().height);
            if (componentHeight !== newHeight) {
                setComponentHeight(newHeight);
            }
        });
    });
    // We calculate the full height at 0
    // so this is needed to know if the height has changed due to calculation (in which case it should not transition)
    // or if the transition should be pretty
    const doTransition = !disableTransition || wasCollapsed !== isCollapsed;
    const innerRefHeight = componentHeight || 'auto';
    let height = 'auto';
    height = isCollapsed ? 0 : innerRefHeight;
    (0,useTimeout/* default */.A)(() => {
        if (doTransition && !isCollapsed) {
            setHasFinishedOpening(true);
        }
    }, clearTimeout ? null : transitionMs);
    (0,external_react_.useEffect)(() => {
        if (doTransition) {
            if (isCollapsed) {
                setHasFinishedOpening(false);
                setClearTimeout(true);
            }
            else {
                setClearTimeout(false);
            }
        }
    }, [isCollapsed, doTransition]);
    (0,external_react_.useEffect)(() => {
        if (!height || isCollapsed || !innerRef.current)
            return undefined;
        const resizeObserver = new ResizeObserver((el) => {
            setComponentHeight(Math.ceil(el[0].contentRect.height));
        });
        resizeObserver.observe(innerRef.current);
        return () => {
            resizeObserver.disconnect();
        };
    }, [height, isCollapsed]);
    const overflow = (0,external_react_.useMemo)(() => (hasFinishedOpening ? 'visible' : 'hidden'), [hasFinishedOpening]);
    //Unmount children if transitions are disabled. Can improve performance if there are lots of child elements
    const unmountChildren = disableTransition && isCollapsed;
    return (external_react_default().createElement("div", { className: Collapsible_Collapsible_module['Root'], style: {
            height: height,
            transition: doTransition ? `height ${transitionMs}ms ${easing}` : 'none',
            overflow
        } },
        external_react_default().createElement("div", { className: Collapsible_Collapsible_module['Inner'], ref: innerRef }, unmountChildren ? null : children)));
}

;// ../noodl-core-ui/src/components/layout/Collapsible/index.ts



/***/ }),

/***/ 20180:
/***/ ((module) => {

"use strict";
module.exports = require("react-dom");

/***/ }),

/***/ 20367:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-hover {
	cursor: default;
	position: absolute;
	overflow: hidden;
	z-index: 50;
	user-select: text;
	-webkit-user-select: text;
	-ms-user-select: text;
	box-sizing: initial;
	animation: fadein 100ms linear;
	line-height: 1.5em;
}

.monaco-hover.hidden {
	display: none;
}

.monaco-hover a:hover {
	cursor: pointer;
}

.monaco-hover .hover-contents:not(.html-hover-contents) {
	padding: 4px 8px;
}

.monaco-hover .markdown-hover > .hover-contents:not(.code-hover-contents) {
	max-width: 500px;
	word-wrap: break-word;
}

.monaco-hover .markdown-hover > .hover-contents:not(.code-hover-contents) hr {
	min-width: 100%;
}

.monaco-hover p,
.monaco-hover .code,
.monaco-hover ul {
	margin: 8px 0;
}

.monaco-hover code {
	font-family: var(--monaco-monospace-font);
}

.monaco-hover hr {
	box-sizing: border-box;
	border-left: 0px;
	border-right: 0px;
	margin-top: 4px;
	margin-bottom: -4px;
	margin-left: -8px;
	margin-right: -8px;
	height: 1px;
}

.monaco-hover p:first-child,
.monaco-hover .code:first-child,
.monaco-hover ul:first-child {
	margin-top: 0;
}

.monaco-hover p:last-child,
.monaco-hover .code:last-child,
.monaco-hover ul:last-child {
	margin-bottom: 0;
}

/* MarkupContent Layout */
.monaco-hover ul {
	padding-left: 20px;
}
.monaco-hover ol {
	padding-left: 20px;
}

.monaco-hover li > p {
	margin-bottom: 0;
}

.monaco-hover li > ul {
	margin-top: 0;
}

.monaco-hover code {
	border-radius: 3px;
	padding: 0 0.4em;
}

.monaco-hover .monaco-tokenized-source {
	white-space: pre-wrap;
}

.monaco-hover .hover-row.status-bar {
	font-size: 12px;
	line-height: 22px;
}

.monaco-hover .hover-row.status-bar .actions {
	display: flex;
	padding: 0px 8px;
}

.monaco-hover .hover-row.status-bar .actions .action-container {
	margin-right: 16px;
	cursor: pointer;
}

.monaco-hover .hover-row.status-bar .actions .action-container .action .icon {
	padding-right: 4px;
}

.monaco-hover .markdown-hover .hover-contents .codicon {
	color: inherit;
	font-size: inherit;
	vertical-align: middle;
}

.monaco-hover .hover-contents a.code-link:hover,
.monaco-hover .hover-contents a.code-link {
	color: inherit;
}

.monaco-hover .hover-contents a.code-link:before {
	content: '(';
}

.monaco-hover .hover-contents a.code-link:after {
	content: ')';
}

.monaco-hover .hover-contents a.code-link > span {
	text-decoration: underline;
	/** Hack to force underline to show **/
	border-bottom: 1px solid transparent;
	text-underline-position: under;
}

/** Spans in markdown hovers need a margin-bottom to avoid looking cramped: https://github.com/microsoft/vscode/issues/101496 **/
.monaco-hover .markdown-hover .hover-contents:not(.code-hover-contents):not(.html-hover-contents) span {
	margin-bottom: 4px;
	display: inline-block;
}

.monaco-hover-content .action-container a {
	-webkit-user-select: none;
	user-select: none;
}

.monaco-hover-content .action-container.disabled {
	pointer-events: none;
	opacity: 0.4;
	cursor: default;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/hover/hover.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,eAAe;CACf,kBAAkB;CAClB,gBAAgB;CAChB,WAAW;CACX,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;CACrB,mBAAmB;CACnB,8BAA8B;CAC9B,kBAAkB;AACnB;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,gBAAgB;CAChB,qBAAqB;AACtB;;AAEA;CACC,eAAe;AAChB;;AAEA;;;CAGC,aAAa;AACd;;AAEA;CACC,yCAAyC;AAC1C;;AAEA;CACC,sBAAsB;CACtB,gBAAgB;CAChB,iBAAiB;CACjB,eAAe;CACf,mBAAmB;CACnB,iBAAiB;CACjB,kBAAkB;CAClB,WAAW;AACZ;;AAEA;;;CAGC,aAAa;AACd;;AAEA;;;CAGC,gBAAgB;AACjB;;AAEA,yBAAyB;AACzB;CACC,kBAAkB;AACnB;AACA;CACC,kBAAkB;AACnB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,kBAAkB;CAClB,gBAAgB;AACjB;;AAEA;CACC,qBAAqB;AACtB;;AAEA;CACC,eAAe;CACf,iBAAiB;AAClB;;AAEA;CACC,aAAa;CACb,gBAAgB;AACjB;;AAEA;CACC,kBAAkB;CAClB,eAAe;AAChB;;AAEA;CACC,kBAAkB;AACnB;;AAEA;CACC,cAAc;CACd,kBAAkB;CAClB,sBAAsB;AACvB;;AAEA;;CAEC,cAAc;AACf;;AAEA;CACC,YAAY;AACb;;AAEA;CACC,YAAY;AACb;;AAEA;CACC,0BAA0B;CAC1B,sCAAsC;CACtC,oCAAoC;CACpC,8BAA8B;AAC/B;;AAEA,gIAAgI;AAChI;CACC,kBAAkB;CAClB,qBAAqB;AACtB;;AAEA;CACC,yBAAyB;CACzB,iBAAiB;AAClB;;AAEA;CACC,oBAAoB;CACpB,YAAY;CACZ,eAAe;AAChB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-hover {\n\tcursor: default;\n\tposition: absolute;\n\toverflow: hidden;\n\tz-index: 50;\n\tuser-select: text;\n\t-webkit-user-select: text;\n\t-ms-user-select: text;\n\tbox-sizing: initial;\n\tanimation: fadein 100ms linear;\n\tline-height: 1.5em;\n}\n\n.monaco-hover.hidden {\n\tdisplay: none;\n}\n\n.monaco-hover a:hover {\n\tcursor: pointer;\n}\n\n.monaco-hover .hover-contents:not(.html-hover-contents) {\n\tpadding: 4px 8px;\n}\n\n.monaco-hover .markdown-hover > .hover-contents:not(.code-hover-contents) {\n\tmax-width: 500px;\n\tword-wrap: break-word;\n}\n\n.monaco-hover .markdown-hover > .hover-contents:not(.code-hover-contents) hr {\n\tmin-width: 100%;\n}\n\n.monaco-hover p,\n.monaco-hover .code,\n.monaco-hover ul {\n\tmargin: 8px 0;\n}\n\n.monaco-hover code {\n\tfont-family: var(--monaco-monospace-font);\n}\n\n.monaco-hover hr {\n\tbox-sizing: border-box;\n\tborder-left: 0px;\n\tborder-right: 0px;\n\tmargin-top: 4px;\n\tmargin-bottom: -4px;\n\tmargin-left: -8px;\n\tmargin-right: -8px;\n\theight: 1px;\n}\n\n.monaco-hover p:first-child,\n.monaco-hover .code:first-child,\n.monaco-hover ul:first-child {\n\tmargin-top: 0;\n}\n\n.monaco-hover p:last-child,\n.monaco-hover .code:last-child,\n.monaco-hover ul:last-child {\n\tmargin-bottom: 0;\n}\n\n/* MarkupContent Layout */\n.monaco-hover ul {\n\tpadding-left: 20px;\n}\n.monaco-hover ol {\n\tpadding-left: 20px;\n}\n\n.monaco-hover li > p {\n\tmargin-bottom: 0;\n}\n\n.monaco-hover li > ul {\n\tmargin-top: 0;\n}\n\n.monaco-hover code {\n\tborder-radius: 3px;\n\tpadding: 0 0.4em;\n}\n\n.monaco-hover .monaco-tokenized-source {\n\twhite-space: pre-wrap;\n}\n\n.monaco-hover .hover-row.status-bar {\n\tfont-size: 12px;\n\tline-height: 22px;\n}\n\n.monaco-hover .hover-row.status-bar .actions {\n\tdisplay: flex;\n\tpadding: 0px 8px;\n}\n\n.monaco-hover .hover-row.status-bar .actions .action-container {\n\tmargin-right: 16px;\n\tcursor: pointer;\n}\n\n.monaco-hover .hover-row.status-bar .actions .action-container .action .icon {\n\tpadding-right: 4px;\n}\n\n.monaco-hover .markdown-hover .hover-contents .codicon {\n\tcolor: inherit;\n\tfont-size: inherit;\n\tvertical-align: middle;\n}\n\n.monaco-hover .hover-contents a.code-link:hover,\n.monaco-hover .hover-contents a.code-link {\n\tcolor: inherit;\n}\n\n.monaco-hover .hover-contents a.code-link:before {\n\tcontent: '(';\n}\n\n.monaco-hover .hover-contents a.code-link:after {\n\tcontent: ')';\n}\n\n.monaco-hover .hover-contents a.code-link > span {\n\ttext-decoration: underline;\n\t/** Hack to force underline to show **/\n\tborder-bottom: 1px solid transparent;\n\ttext-underline-position: under;\n}\n\n/** Spans in markdown hovers need a margin-bottom to avoid looking cramped: https://github.com/microsoft/vscode/issues/101496 **/\n.monaco-hover .markdown-hover .hover-contents:not(.code-hover-contents):not(.html-hover-contents) span {\n\tmargin-bottom: 4px;\n\tdisplay: inline-block;\n}\n\n.monaco-hover-content .action-container a {\n\t-webkit-user-select: none;\n\tuser-select: none;\n}\n\n.monaco-hover-content .action-container.disabled {\n\tpointer-events: none;\n\topacity: 0.4;\n\tcursor: default;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 20396:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Z: () => (/* binding */ NodeType)
/* harmony export */ });
var NodeType;
(function (NodeType) {
    NodeType["Visual"] = "visual";
    NodeType["Logic"] = "logic";
    NodeType["Data"] = "data";
    NodeType["Connection"] = "component";
    NodeType["Custom"] = "javascript";
    NodeType["None"] = "none";
})(NodeType || (NodeType = {}));


/***/ }),

/***/ 20435:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


const Model = __webpack_require__(47821);
const { EventDispatcher } = __webpack_require__(11138);
const JSONStorage = __webpack_require__(78133);
const { ProjectModel } = __webpack_require__(6203);

// --------------------------------------------------------------------
// DebugInspector
// --------------------------------------------------------------------
function DebugInspector() {
  this.connectionsToPulseState = {};

  //Object.keys version of connectionsToPulseState.
  //It's needed every frame when animating so keeping it cached saves some GC cycles
  this.connectionsToPulseIDs = [];
  this.inspectorValues = {};
  this.enabled = true;

  EventDispatcher.instance.on(['viewer-refreshed', 'viewer-closed'], () => this.reset());
}

function generateIdFromConnection(con) {
  return con.fromId + con.fromProperty + con.toId + con.toProperty;
}

DebugInspector.prototype.onAnimationFrame = function () {
  const now = window.performance.now();
  var connectionsRemoved = false;

  this.connectionsToPulseIDs.forEach((id) => {
    const con = this.connectionsToPulseState[id];
    const life = now - con.created;
    con.offset = life / 20;
    con.opacity = Math.min(1, life / 50);

    if (con.removed) {
      const timeRemoved = now - con.removed;
      con.opacity = 1 - timeRemoved / 500;
      if (con.opacity <= 0) {
        connectionsRemoved = true;
        delete this.connectionsToPulseState[id];
      }
    }
  });

  if (connectionsRemoved) {
    this.connectionsToPulseIDs = Object.keys(this.connectionsToPulseState);
  }

  if (this.connectionsToPulseIDs.length === 0) {
    this.playPulseAnimation = false;
  }

  EventDispatcher.instance.notifyListeners('DebugInspectorConnectionPulseChanged');

  if (this.playPulseAnimation) {
    window.requestAnimationFrame(this.onAnimationFrame.bind(this));
  }
};

DebugInspector.prototype.startPulseAnimations = function () {
  if (this.playPulseAnimation) {
    return;
  }

  this.playPulseAnimation = true;
  window.requestAnimationFrame(this.onAnimationFrame.bind(this));
};

DebugInspector.prototype.setConnectionsToPulse = function (connections) {
  var self = this;

  var now = window.performance.now();
  var pulsingConnectionIds = {};

  connections.forEach(function (id) {
    pulsingConnectionIds[id] = true;

    if (self.connectionsToPulseState.hasOwnProperty(id) === false) {
      self.connectionsToPulseState[id] = {
        created: now,
        offset: 0,
        opacity: 0,
        removed: false
      };
    } else {
      self.connectionsToPulseState[id].removed = false;
    }
  });

  this.connectionsToPulseIDs = Object.keys(this.connectionsToPulseState);

  this.connectionsToPulseIDs.forEach(function (id) {
    if (pulsingConnectionIds.hasOwnProperty(id) === false && self.connectionsToPulseState[id].removed === false) {
      self.connectionsToPulseState[id].removed = now;
    }
  });

  this.startPulseAnimations();
};

DebugInspector.prototype.reset = function () {
  this.inspectorValues = {};
  this.connectionsToPulseState = {};
  this.connectionsToPulseIDs = [];
  this.playPulseAnimation = false;

  EventDispatcher.instance.notifyListeners('DebugInspectorReset');
};

DebugInspector.prototype.isConnectionPulsing = function (connection) {
  var id = generateIdFromConnection(connection);
  return this.connectionsToPulseState.hasOwnProperty(id);
};

DebugInspector.prototype.getPulseAnimationState = function (connection) {
  var id = generateIdFromConnection(connection);
  return this.connectionsToPulseState[id];
};

DebugInspector.prototype.isEnabled = function () {
  return this.enabled;
};

DebugInspector.prototype.setEnabled = function (enabled) {
  this.enabled = enabled;
  EventDispatcher.instance.notifyListeners('DebugInspectorEnabledChanged');
};

DebugInspector.prototype.setInspectorValues = function (inspectorValues) {
  inspectorValues.forEach((inspectorValue) => {
    this._setInspectorValue(inspectorValue);
  });
};

DebugInspector.prototype._setInspectorValue = function ({ id, value }) {
  this.inspectorValues[id] = value;
  EventDispatcher.instance.notifyListeners('DebugInspectorDataChanged.' + id, { value });
};

DebugInspector.prototype.getConnectionId = function (connection) {
  return connection.fromId + connection.fromProperty;
};

DebugInspector.prototype.valueForNode = function (nodeId) {
  if (this.inspectorValues.hasOwnProperty(nodeId)) {
    return this.inspectorValues[nodeId];
  }
};

DebugInspector.prototype.valueForConnection = function (connection) {
  const id = this.getConnectionId(connection);
  if (this.inspectorValues.hasOwnProperty(id)) {
    return { type: 'value', value: this.inspectorValues[id] };
  }

  //check if this is a signal, and in that case indicate that it hasn't been sent
  const node = ProjectModel.instance.findNodeWithId(connection.fromId);
  if (node === undefined) return;

  const port = node.getPort(connection.fromProperty);
  if (port && port.type === 'signal') {
    return { type: 'value', value: '[Signal] Not triggered' };
  }

  return undefined; //no value found
};

DebugInspector.instance = new DebugInspector();

// --------------------------------------------------------------------
// DebugInspector.InspectorsModel
// --------------------------------------------------------------------
DebugInspector.InspectorsModel = function (args) {
  Model.call(this);

  for (var i in args) this[i] = args[i];

  if (this.inspectors) {
    //update old inspectors that didn't have a type
    this.inspectors.filter((inspector) => !inspector.type).forEach((inspector) => inspector.type === 'connection');
  } else {
    this.inspectors = [];
  }
};

DebugInspector.InspectorsModel.prototype = Object.create(Model.prototype);

DebugInspector.InspectorsModel.prototype.addInspectorForConnection = function (args) {
  var connection = args.connection;

  var inspector = {
    connectionKey: generateIdFromConnection(connection),
    type: 'connection',
    pinned: false,
    position: args.position,
    connection: {
      fromId: connection.fromId,
      fromProperty: connection.fromProperty,
      toId: connection.toId,
      toProperty: connection.toProperty
    }
  };

  this.inspectors.push(inspector);
  this.notifyListeners('inspectorAdded', { model: inspector });
  DebugInspector.InspectorsModel.save();
  return inspector;
};

DebugInspector.InspectorsModel.prototype.addInspectorForNode = function (args) {
  var node = args.node;

  var inspector = { type: 'node', nodeId: node.id, pinned: false, position: args.position };

  this.inspectors.push(inspector);
  this.notifyListeners('inspectorAdded', { model: inspector });
  DebugInspector.InspectorsModel.save();
  return inspector;
};

DebugInspector.InspectorsModel.prototype.removeInspector = function (inspector) {
  var idx = this.inspectors.indexOf(inspector);
  if (idx !== -1) {
    this.inspectors.splice(idx, 1);
    this.notifyListeners('inspectorRemoved', { model: inspector });
    DebugInspector.InspectorsModel.save();
  }
};

DebugInspector.InspectorsModel.prototype.pinInspector = function (inspector) {
  inspector.pinned = true;
  DebugInspector.InspectorsModel.save();
};

DebugInspector.InspectorsModel.prototype.getInspectors = function () {
  return this.inspectors;
};

DebugInspector.InspectorsModel.prototype.toJSON = function () {
  var json = {
    inspectors: this.inspectors
  };
  return json;
};

DebugInspector.InspectorsModel.fromJSON = function (json) {
  return new DebugInspector.InspectorsModel(json);
};

var inspectorsModels = {};
DebugInspector.InspectorsModel.instanceForProject = function (project) {
  if (!inspectorsModels[project.id]) {
    inspectorsModels[project.id] = new DebugInspector.InspectorsModel({});
  }

  return inspectorsModels[project.id];
};

DebugInspector.InspectorsModel.fetch = function () {
  JSONStorage.get('connection-debugger-inspectors', function (local) {
    var models = local['connection-debugger-inspectors'];
    for (var i in models) {
      inspectorsModels[i] = DebugInspector.InspectorsModel.fromJSON(models[i]);
    }
  });
};
DebugInspector.InspectorsModel.fetch();

DebugInspector.InspectorsModel.save = function () {
  var models = {};
  for (var i in inspectorsModels) models[i] = inspectorsModels[i].toJSON();

  JSONStorage.set('debugInspector', { 'debug-inspector-inspectors': models });
};

module.exports = DebugInspector;


/***/ }),

/***/ 20490:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const DebugInspector = __webpack_require__(20435);
const { ProjectModel } = __webpack_require__(6203);
const { InspectPopup } = __webpack_require__(8263);
const { createRoot } = __webpack_require__(25873);
const React = __webpack_require__(54953);
const { EventDispatcher } = __webpack_require__(11138);

// --------------------------------------------------------------
// DebugInspector
// --------------------------------------------------------------
function DebugInspectorPopup(args) {
  this.model = args.model;
  this.owner = args.owner;

  this.div = document.createElement('div');
  this.div.style.position = 'absolute';
  this.div.style.width = 'max-content';
  this.div.style.transform = 'translate(-50%, calc(-100% - 4px))';

  args.parentElement.appendChild(this.div);
}

DebugInspectorPopup.prototype.togglePinned = function () {
  const inspectorModel = DebugInspector.InspectorsModel.instanceForProject(ProjectModel.instance);
  if (this.model.pinned) {
    // Unpin/remove
    this.remove();
  } else {
    // Pin
    inspectorModel.pinInspector(this.model);
  }

  this.render();
};

DebugInspectorPopup.prototype.isPinned = function () {
  return this.model.pinned;
};

DebugInspectorPopup.prototype.remove = function () {
  DebugInspector.InspectorsModel.instanceForProject(ProjectModel.instance).removeInspector(this.model);
  this.dispose();
};

DebugInspectorPopup.prototype.render = function () {
  const debugValue = this.getValue();
  const pos = this.getAttachPosition();

  if (!pos) {
    return;
  }

  this.div.style.left = pos.x + 'px';
  this.div.style.top = pos.y + 'px';

  const onPinClicked = () => {
    this.togglePinned();
  };

  // Create root only once, reuse for subsequent renders
  if (!this.root) {
    this.root = createRoot(this.div);
  }
  this.root.render(React.createElement(InspectPopup, { debugValue, onPinClicked, pinned: this.model.pinned }));
};

DebugInspectorPopup.prototype.dispose = function () {
  if (this.root) {
    this.root.unmount();
    this.root = null;
  }
  if (this.div.parentElement) {
    this.div.parentElement.removeChild(this.div);
  }
};

// --------------------------------------------------------------
// ConnectionInspector
// --------------------------------------------------------------
function ConnectionInspector(args) {
  DebugInspectorPopup.call(this, args);
  this.connection = args.connection;

  const id = DebugInspector.instance.getConnectionId(this.connection);

  EventDispatcher.instance.on(
    ['DebugInspectorDataChanged.' + id, 'DebugInspectorReset'],
    () => {
      this.render();
    },
    this
  );
}

ConnectionInspector.prototype = Object.create(DebugInspectorPopup.prototype);

ConnectionInspector.prototype.dispose = function () {
  DebugInspectorPopup.prototype.dispose.call(this);
  EventDispatcher.instance.off(this);
};

ConnectionInspector.prototype.getValue = function () {
  return DebugInspector.instance.valueForConnection(this.connection.model);
};

ConnectionInspector.prototype.getAttachPosition = function () {
  var c = this.connection;
  return c.pointOnCurve(this.model.position);
};

ConnectionInspector.prototype.getOrientation = function () {
  var c = this.connection;
  var from = c.fromNode.global;
  var to = c.toNode.global;

  if (Math.abs(from.x - to.x) > Math.abs(from.y - to.y)) return 'horizontal';
  else return 'vertical';
};

// --------------------------------------------------------------
// NodeInspector
// --------------------------------------------------------------

function NodeInspector(args) {
  DebugInspectorPopup.call(this, args);
  this.node = args.node;

  EventDispatcher.instance.on(
    ['DebugInspectorDataChanged.' + this.model.nodeId, 'DebugInspectorReset'],
    () => {
      this.render();
    },
    this
  );
}

NodeInspector.prototype = Object.create(DebugInspectorPopup.prototype);

NodeInspector.prototype.dispose = function () {
  DebugInspectorPopup.prototype.dispose.call(this);
  EventDispatcher.instance.off(this);
};

NodeInspector.prototype.getAttachPosition = function () {
  return {
    x: this.node.global.x + this.node.nodeSize.width / 2,
    y: this.node.global.y
  };
};

NodeInspector.prototype.getValue = function () {
  return DebugInspector.instance.valueForNode(this.model.nodeId);
};

module.exports = {
  ConnectionInspector,
  NodeInspector
};


/***/ }),

/***/ 20677:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgWarningCircleFilled = function SvgWarningCircleFilled(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 25,
    viewBox: "0 0 24 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M2.27295 12.9105C2.27295 7.53797 6.62827 3.18265 12.0008 3.18265C17.3734 3.18265 21.7287 7.53797 21.7287 12.9105C21.7287 18.2831 17.3734 22.6384 12.0008 22.6384C6.62827 22.6384 2.27295 18.2831 2.27295 12.9105ZM12.0012 7.51051C12.5176 7.51051 12.9362 7.8542 12.9362 8.27817V13.6518C12.9362 14.0757 12.5176 14.4194 12.0012 14.4194C11.4848 14.4194 11.0661 14.0757 11.0661 13.6518V8.27817C11.0661 7.8542 11.4848 7.51051 12.0012 7.51051ZM13.1126 17.199C13.1126 17.8129 12.6149 18.3106 12.001 18.3106C11.3871 18.3106 10.8894 17.8129 10.8894 17.199C10.8894 16.585 11.3871 16.0874 12.001 16.0874C12.6149 16.0874 13.1126 16.585 13.1126 17.199Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgWarningCircleFilled);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "ce47990d38a78188c0653fc84cb2b2d0.svg");

/***/ }),

/***/ 20749:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  S: () => (/* reexport */ ToastCard),
  C: () => (/* reexport */ ToastType)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/ActivityIndicator/index.ts + 2 modules
var ActivityIndicator = __webpack_require__(12093);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/LegacyIconButton/LegacyIconButton.module.scss
var LegacyIconButton_module = __webpack_require__(22862);
;// ../noodl-core-ui/src/components/inputs/LegacyIconButton/LegacyIconButton.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(LegacyIconButton_module/* default */.A, options);




       /* harmony default export */ const LegacyIconButton_LegacyIconButton_module = (LegacyIconButton_module/* default */.A && LegacyIconButton_module/* default */.A.locals ? LegacyIconButton_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/LegacyIconButton/LegacyIconButton.tsx



var LegacyIconButtonIcon;
(function (LegacyIconButtonIcon) {
    LegacyIconButtonIcon["VerticalDots"] = "vertical-dots";
    LegacyIconButtonIcon["Close"] = "close";
    LegacyIconButtonIcon["CloseDark"] = "close-dark";
    LegacyIconButtonIcon["CaretDown"] = "caret-down";
    LegacyIconButtonIcon["Generate"] = "generate";
})(LegacyIconButtonIcon || (LegacyIconButtonIcon = {}));
function LegacyIconButton({ icon, isRotated180, style, onClick, testId }) {
    return (external_react_default().createElement("button", { className: LegacyIconButton_LegacyIconButton_module['Root'], onClick: onClick, style: style, "data-test": testId },
        external_react_default().createElement("img", { className: external_classnames_default()([LegacyIconButton_LegacyIconButton_module['Icon'], isRotated180 && LegacyIconButton_LegacyIconButton_module['is-rotated-180']]), src: `/assets/icons/icon-button/${icon}.svg` })));
}

;// ../noodl-core-ui/src/components/inputs/LegacyIconButton/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/ToastLayer/components/ToastCard/ToastCard.module.scss
var ToastCard_module = __webpack_require__(92937);
;// ./src/editor/src/views/ToastLayer/components/ToastCard/ToastCard.module.scss

      
      
      
      
      
      
      
      
      

var ToastCard_module_options = {};

ToastCard_module_options.styleTagTransform = (styleTagTransform_default());
ToastCard_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ToastCard_module_options.insert = insertBySelector_default().bind(null, "head");
    
ToastCard_module_options.domAPI = (styleDomAPI_default());
ToastCard_module_options.insertStyleElement = (insertStyleElement_default());

var ToastCard_module_update = injectStylesIntoStyleTag_default()(ToastCard_module/* default */.A, ToastCard_module_options);




       /* harmony default export */ const ToastCard_ToastCard_module = (ToastCard_module/* default */.A && ToastCard_module/* default */.A.locals ? ToastCard_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/ToastLayer/components/ToastCard/ToastCard.tsx





var ToastType;
(function (ToastType) {
    ToastType["Neutral"] = "is-neutral";
    ToastType["Success"] = "is-success";
    ToastType["Danger"] = "is-danger";
    ToastType["Pending"] = "is-pending";
})(ToastType || (ToastType = {}));
function ToastCard({ message, type = ToastType.Neutral, progress, hasActivity, onClose }) {
    return (external_react_default().createElement("div", { className: external_classnames_default()(ToastCard_ToastCard_module['Root'], ToastCard_ToastCard_module[type]) },
        external_react_default().createElement("span", { className: ToastCard_ToastCard_module['Message'] }, message),
        typeof progress !== 'undefined' && external_react_default().createElement("div", { className: ToastCard_ToastCard_module['ProgressBar'], style: { width: `${progress}%` } }),
        external_react_default().createElement("div", { className: ToastCard_ToastCard_module['IndicatorContainer'] },
            hasActivity && external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, { color: ActivityIndicator/* ActivityIndicatorColor */.Iz.Dark }),
            onClose && external_react_default().createElement(LegacyIconButton, { icon: LegacyIconButtonIcon.CloseDark, onClick: onClose }))));
}

;// ./src/editor/src/views/ToastLayer/components/ToastCard/index.ts



/***/ }),

/***/ 20854:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.path = exports.createPathTagFunction = void 0;
exports.encodeURIPath = encodeURIPath;
const error_1 = __webpack_require__(37015);
/**
 * Percent-encode everything that isn't safe to have in a path without encoding safe chars.
 *
 * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3:
 * > unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
 * > sub-delims  = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
 * > pchar       = unreserved / pct-encoded / sub-delims / ":" / "@"
 */
function encodeURIPath(str) {
    return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
}
const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) {
    // If there are no params, no processing is needed.
    if (statics.length === 1)
        return statics[0];
    let postPath = false;
    const invalidSegments = [];
    const path = statics.reduce((previousValue, currentValue, index) => {
        if (/[?#]/.test(currentValue)) {
            postPath = true;
        }
        const value = params[index];
        let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value);
        if (index !== params.length &&
            (value == null ||
                (typeof value === 'object' &&
                    // handle values from other realms
                    value.toString ===
                        Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)
                            ?.toString))) {
            encoded = value + '';
            invalidSegments.push({
                start: previousValue.length + currentValue.length,
                length: encoded.length,
                error: `Value of type ${Object.prototype.toString
                    .call(value)
                    .slice(8, -1)} is not a valid path parameter`,
            });
        }
        return previousValue + currentValue + (index === params.length ? '' : encoded);
    }, '');
    const pathOnly = path.split(/[?#]/, 1)[0];
    const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
    let match;
    // Find all invalid segments
    while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
        invalidSegments.push({
            start: match.index,
            length: match[0].length,
            error: `Value "${match[0]}" can\'t be safely passed as a path parameter`,
        });
    }
    invalidSegments.sort((a, b) => a.start - b.start);
    if (invalidSegments.length > 0) {
        let lastEnd = 0;
        const underline = invalidSegments.reduce((acc, segment) => {
            const spaces = ' '.repeat(segment.start - lastEnd);
            const arrows = '^'.repeat(segment.length);
            lastEnd = segment.start + segment.length;
            return acc + spaces + arrows;
        }, '');
        throw new error_1.AnthropicError(`Path parameters result in path with invalid segments:\n${invalidSegments
            .map((e) => e.error)
            .join('\n')}\n${path}\n${underline}`);
    }
    return path;
};
exports.createPathTagFunction = createPathTagFunction;
/**
 * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced.
 */
exports.path = (0, exports.createPathTagFunction)(encodeURIPath);
//# sourceMappingURL=path.js.map

/***/ }),

/***/ 21410:
/***/ ((module) => {

"use strict";
module.exports = require("body-parser");

/***/ }),

/***/ 21569:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Modal-module__Root--qgBMF{position:relative;display:flex;flex-direction:column;background-color:var(--theme-color-bg-4);border-radius:var(--radius-lg);border:1px solid var(--theme-color-border-subtle);box-shadow:var(--shadow-popup);max-width:810px;max-height:90vh;width:80vw;overflow:hidden}.Modal-module__Root--qgBMF::after{content:"";position:absolute;left:0;bottom:-50px;right:0;height:50px;border-radius:50%;box-shadow:0 0 25px 10px var(--theme-color-bg-4)}.Modal-module__CloseButtonContainer--mB1x3{position:absolute;top:var(--spacing-2);right:var(--spacing-2)}.Modal-module__Header--kOuXF{padding:var(--spacing-5) var(--spacing-10) var(--spacing-4);display:flex;justify-content:space-between;align-items:flex-start}.Modal-module__Header--kOuXF.Modal-module__has-divider--enu2K{border-bottom:1px solid var(--theme-color-border-subtle)}.Modal-module__Footer--M58yd{padding:var(--spacing-5) var(--spacing-10) var(--spacing-4);display:flex;justify-content:space-between;align-items:flex-start}.Modal-module__Footer--M58yd.Modal-module__has-divider--enu2K{border-top:1px solid var(--theme-color-border-subtle)}.Modal-module__TitleWrapper--XB1lQ{padding-top:var(--spacing-5);padding-right:var(--spacing-10)}.Modal-module__Content--sQ8VA{padding:0 var(--spacing-10) var(--spacing-10);padding-top:var(--spacing-4);overflow-x:hidden;overflow-y:overlay}.Modal-module__Content--sQ8VA::-webkit-scrollbar{width:8px}.Modal-module__Content--sQ8VA::-webkit-scrollbar-track{background:var(--theme-color-bg-3)}.Modal-module__Content--sQ8VA::-webkit-scrollbar-thumb{background:var(--theme-color-bg-5);border-radius:var(--radius-full)}.Modal-module__Content--sQ8VA::-webkit-scrollbar-thumb:hover{background:var(--theme-color-fg-muted)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/Modal/Modal.module.scss"],"names":[],"mappings":"AAAA,2BACE,iBAAA,CACA,YAAA,CACA,qBAAA,CACA,wCAAA,CAGA,8BAAA,CAGA,iDAAA,CAGA,8BAAA,CAEA,eAAA,CACA,eAAA,CACA,UAAA,CACA,eAAA,CAEA,kCACE,UAAA,CACA,iBAAA,CACA,MAAA,CACA,YAAA,CACA,OAAA,CACA,WAAA,CACA,iBAAA,CACA,gDAAA,CAIJ,2CACE,iBAAA,CACA,oBAAA,CACA,sBAAA,CAGF,6BACE,2DAAA,CACA,YAAA,CACA,6BAAA,CACA,sBAAA,CAEA,8DACE,wDAAA,CAIJ,6BACE,2DAAA,CACA,YAAA,CACA,6BAAA,CACA,sBAAA,CAEA,8DACE,qDAAA,CAIJ,mCACE,4BAAA,CACA,+BAAA,CAGF,8BACE,6CAAA,CACA,4BAAA,CACA,iBAAA,CACA,kBAAA,CAGA,iDACE,SAAA,CAGF,uDACE,kCAAA,CAGF,uDACE,kCAAA,CACA,gCAAA,CAEA,6DACE,sCAAA","sourcesContent":[".Root {\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  background-color: var(--theme-color-bg-4);\n\n  /* Modern rounded corners */\n  border-radius: var(--radius-lg);\n\n  /* Border for definition */\n  border: 1px solid var(--theme-color-border-subtle);\n\n  /* Elevated shadow */\n  box-shadow: var(--shadow-popup);\n\n  max-width: 810px;\n  max-height: 90vh;\n  width: 80vw;\n  overflow: hidden;\n\n  &::after {\n    content: '';\n    position: absolute;\n    left: 0;\n    bottom: -50px;\n    right: 0;\n    height: 50px;\n    border-radius: 50%;\n    box-shadow: 0 0 25px 10px var(--theme-color-bg-4);\n  }\n}\n\n.CloseButtonContainer {\n  position: absolute;\n  top: var(--spacing-2);\n  right: var(--spacing-2);\n}\n\n.Header {\n  padding: var(--spacing-5) var(--spacing-10) var(--spacing-4);\n  display: flex;\n  justify-content: space-between;\n  align-items: flex-start;\n\n  &.has-divider {\n    border-bottom: 1px solid var(--theme-color-border-subtle);\n  }\n}\n\n.Footer {\n  padding: var(--spacing-5) var(--spacing-10) var(--spacing-4);\n  display: flex;\n  justify-content: space-between;\n  align-items: flex-start;\n\n  &.has-divider {\n    border-top: 1px solid var(--theme-color-border-subtle);\n  }\n}\n\n.TitleWrapper {\n  padding-top: var(--spacing-5);\n  padding-right: var(--spacing-10);\n}\n\n.Content {\n  padding: 0 var(--spacing-10) var(--spacing-10);\n  padding-top: var(--spacing-4);\n  overflow-x: hidden;\n  overflow-y: overlay;\n\n  /* Custom scrollbar styling */\n  &::-webkit-scrollbar {\n    width: 8px;\n  }\n\n  &::-webkit-scrollbar-track {\n    background: var(--theme-color-bg-3);\n  }\n\n  &::-webkit-scrollbar-thumb {\n    background: var(--theme-color-bg-5);\n    border-radius: var(--radius-full);\n\n    &:hover {\n      background: var(--theme-color-fg-muted);\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Modal-module__Root--qgBMF`,
	"CloseButtonContainer": `Modal-module__CloseButtonContainer--mB1x3`,
	"Header": `Modal-module__Header--kOuXF`,
	"has-divider": `Modal-module__has-divider--enu2K`,
	"Footer": `Modal-module__Footer--M58yd`,
	"TitleWrapper": `Modal-module__TitleWrapper--XB1lQ`,
	"Content": `Modal-module__Content--sQ8VA`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 21613:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.AiChatLoader-module__Root--XTIjZ{border-top:1px solid var(--theme-color-bg-1);background-color:var(--theme-color-bg-3)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/ai/AiChatLoader/AiChatLoader.module.scss"],"names":[],"mappings":"AAAA,kCACE,4CAAA,CACA,wCAAA","sourcesContent":[".Root {\n  border-top: 1px solid var(--theme-color-bg-1);\n  background-color: var(--theme-color-bg-3);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `AiChatLoader-module__Root--XTIjZ`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 21796:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgNestedComponent = function SvgNestedComponent(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.75 4.5C3.75 4.08579 4.08579 3.75 4.5 3.75H10.5C10.9142 3.75 11.25 4.08579 11.25 4.5V10.5C11.25 10.9142 10.9142 11.25 10.5 11.25H4.5C4.08579 11.25 3.75 10.9142 3.75 10.5V4.5ZM5.25 5.25V9.75H9.75V5.25H5.25Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.75 4.5C12.75 4.08579 13.0858 3.75 13.5 3.75H19.5C19.9142 3.75 20.25 4.08579 20.25 4.5V10.5C20.25 10.9142 19.9142 11.25 19.5 11.25H13.5C13.0858 11.25 12.75 10.9142 12.75 10.5V4.5Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.75 13.5C3.75 13.0858 4.08579 12.75 4.5 12.75H10.5C10.9142 12.75 11.25 13.0858 11.25 13.5V19.5C11.25 19.9142 10.9142 20.25 10.5 20.25H4.5C4.08579 20.25 3.75 19.9142 3.75 19.5V13.5ZM5.25 14.25V18.75H9.75V14.25H5.25Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.75 13.5C12.75 13.0858 13.0858 12.75 13.5 12.75H19.5C19.9142 12.75 20.25 13.0858 20.25 13.5V19.5C20.25 19.9142 19.9142 20.25 19.5 20.25H13.5C13.0858 20.25 12.75 19.9142 12.75 19.5V13.5ZM14.25 14.25V18.75H18.75V14.25H14.25Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgNestedComponent);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "db576eb992f94cb034f71b8f2574c94b.svg");

/***/ }),

/***/ 21834:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.TextArea-module__Root--mv_qi{flex-grow:1}.TextArea-module__Root--mv_qi.TextArea-module__has-bottom-spacing--zCs07{margin-bottom:15px}.TextArea-module__InputArea--NCTwM{background-color:var(--theme-color-bg-1);position:relative;transition:opacity var(--speed-turbo) var(--easing-base)}.TextArea-module__InputArea--NCTwM.TextArea-module__is-disabled--ezemI{opacity:.5}.TextArea-module__InputArea--NCTwM.TextArea-module__has-message--RbXDe{margin-bottom:4px}.TextArea-module__Input--o41Hm{padding:8px 10px;width:100%;font-size:14px;font-family:var(--font-family);color:var(--theme-color-fg-default);border:0;border-radius:0;background-color:rgba(0,0,0,0);resize:vertical;min-height:51px;box-sizing:border-box;user-select:none}.TextArea-module__Input--o41Hm::placeholder{color:var(--base-color-grey-600)}.TextArea-module__Input--o41Hm.TextArea-module__is-resize-disabled--PPEqW{resize:none}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/TextArea/TextArea.module.scss"],"names":[],"mappings":"AAEA,8BACE,WAAA,CAEA,yEACE,kBAAA,CAIJ,mCACE,wCAAA,CACA,iBAAA,CACA,wDAAA,CAEA,uEACE,UAAA,CAGF,uEACE,iBAAA,CAIJ,+BACE,gBAAA,CACA,UAAA,CACA,cAAA,CACA,8BAAA,CACA,mCAAA,CACA,QAAA,CACA,eAAA,CACA,8BAAA,CACA,eAAA,CACA,eAAA,CACA,qBAAA,CACA,gBAAA,CAEA,4CACE,gCAAA,CAGF,0EACE,WAAA","sourcesContent":["$_x-padding: 10px;\n\n.Root {\n  flex-grow: 1;\n\n  &.has-bottom-spacing {\n    margin-bottom: 15px;\n  }\n}\n\n.InputArea {\n  background-color: var(--theme-color-bg-1);\n  position: relative;\n  transition: opacity var(--speed-turbo) var(--easing-base);\n\n  &.is-disabled {\n    opacity: 0.5;\n  }\n\n  &.has-message {\n    margin-bottom: 4px;\n  }\n}\n\n.Input {\n  padding: 8px $_x-padding;\n  width: 100%;\n  font-size: 14px;\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-default);\n  border: 0;\n  border-radius: 0;\n  background-color: transparent;\n  resize: vertical;\n  min-height: 51px;\n  box-sizing: border-box;\n  user-select: none;\n\n  &::placeholder {\n    color: var(--base-color-grey-600);\n  }\n\n  &.is-resize-disabled {\n    resize: none;\n  }\n\n  &.is-empty {\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `TextArea-module__Root--mv_qi`,
	"has-bottom-spacing": `TextArea-module__has-bottom-spacing--zCs07`,
	"InputArea": `TextArea-module__InputArea--NCTwM`,
	"is-disabled": `TextArea-module__is-disabled--ezemI`,
	"has-message": `TextArea-module__has-message--RbXDe`,
	"Input": `TextArea-module__Input--o41Hm`,
	"is-resize-disabled": `TextArea-module__is-resize-disabled--PPEqW`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 21877:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgViewportDiagonalArrow = function SvgViewportDiagonalArrow(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 25,
    viewBox: "0 0 24 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M2.07812 4.73488C2.07812 3.76838 2.86163 2.98488 3.82812 2.98488H20.1753C21.1418 2.98488 21.9253 3.76838 21.9253 4.73488V21.0862C21.9253 22.0527 21.1418 22.8362 20.1753 22.8362H3.82812C2.86163 22.8362 2.07812 22.0527 2.07812 21.0862V4.73488ZM3.82812 4.48488C3.69005 4.48488 3.57812 4.59681 3.57812 4.73488V21.0862C3.57812 21.2242 3.69005 21.3362 3.82812 21.3362H20.1753C20.3134 21.3362 20.4253 21.2242 20.4253 21.0862V4.73488C20.4253 4.59681 20.3134 4.48488 20.1753 4.48488H3.82812Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M17.7765 7.13446C18.0694 7.42736 18.0694 7.90223 17.7765 8.19512L13.7225 12.2491C13.4296 12.542 12.9547 12.542 12.6619 12.2491C12.369 11.9562 12.369 11.4814 12.6619 11.1885L16.7159 7.13446C17.0087 6.84157 17.4836 6.84157 17.7765 7.13446Z",
    fill: "#B8B8B8"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M17.2463 6.91497C17.6605 6.91497 17.9963 7.25076 17.9963 7.66497V11.3527C17.9963 11.767 17.6605 12.1027 17.2463 12.1027C16.8321 12.1027 16.4963 11.767 16.4963 11.3527V8.41497H13.5586C13.1443 8.41497 12.8086 8.07919 12.8086 7.66497C12.8086 7.25076 13.1443 6.91497 13.5586 6.91497H17.2463Z",
    fill: "#B8B8B8"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M6.22578 18.6866C5.93289 18.3937 5.93289 17.9188 6.22578 17.6259L10.2798 13.5719C10.5727 13.279 11.0476 13.279 11.3404 13.5719C11.6333 13.8648 11.6333 14.3397 11.3404 14.6326L7.28644 18.6866C6.99355 18.9795 6.51868 18.9795 6.22578 18.6866Z",
    fill: "#B8B8B8"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M6.75598 18.9061C6.34176 18.9061 6.00598 18.5703 6.00598 18.1561L6.00598 14.4683C6.00598 14.0541 6.34176 13.7183 6.75598 13.7183C7.17019 13.7183 7.50598 14.0541 7.50598 14.4683V17.4061H10.4437C10.858 17.4061 11.1937 17.7419 11.1937 18.1561C11.1937 18.5703 10.858 18.9061 10.4437 18.9061H6.75598Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgViewportDiagonalArrow);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "e5d83eb553615adf76f064401d7064c7.svg");

/***/ }),

/***/ 21977:
/***/ ((module) => {

const ScrollBehaviourToScrollEnabled = {
  condition: function (node) {
    return node.type === 'Group' && node.parameters.hasOwnProperty('scrollBehavior');
  },
  generatePatch: function (node) {
    const params = {
      //remove old parameters
      scrollBehavior: null,
      scrollDirection: null
    };

    //add new parameters
    switch (node.parameters.scrollBehavior) {
      case 'native':
        params.scrollEnabled = true;
        params.nativeScroll = true;
        break;
      case 'noodl':
        params.scrollEnabled = true;
        break;
    }

    return {
      nodeId: node.id,
      params
    };
  }
};

const TextAlignmentAlignXNoodl20 = {
  condition: function (node) {
    return node.type === 'Text' && node.parameters.hasOwnProperty('textAlign');
  },
  generatePatch: function (node) {
    const params = {
      //remove old parameter
      textAlign: null,
      //add new
      textAlignX: node.parameters.textAlign
    };

    return {
      nodeId: node.id,
      params
    };
  }
};

const TextAlignment = {
  condition: function (node) {
    return (
      node.type === 'Text' &&
      (node.parameters.hasOwnProperty('justifyContent') || node.parameters.hasOwnProperty('alignItems'))
    );
  },
  generatePatch: function (node) {
    const params = {
      //remove old parameters
      justifyContent: null,
      alignItems: null
    };

    //add new paramters
    switch (node.parameters.justifyContent) {
      case 'flex-start':
        params.textAlignX = 'left';
        break;
      case 'center':
        params.textAlignX = 'center';
        break;
      case 'flex-end':
        params.textAlignX = 'right';
        break;
    }

    switch (node.parameters.alignItems) {
      case 'flex-start':
        params.textAlignY = 'top';
        break;
      case 'center':
        params.textAlignY = 'center';
        break;
      case 'flex-end':
        params.textAlignY = 'bottom';
        break;
    }

    return {
      nodeId: node.id,
      params
    };
  }
};

const EventSenderReceiver = {
  condition: function (node) {
    return node.type === 'Event Sender' && !node.parameters.payload && node.ports && node.ports.length > 0;
  },
  generatePatch: function (node) {
    const payloadPorts = node.ports.filter((p) => p.plug === 'input' && p.group === 'Payload');

    const payload = payloadPorts.map((p) => p.name).join(',');

    return {
      nodeId: node.id,
      params: {
        payload
      },
      portsToDelete: payloadPorts.map((p) => p.name)
    };
  }
};

module.exports = {
  Patches: [
    {
      key: 'ScrollBehaviourToScrollEnabled',
      message: 'Scroll properties have changed and been upgraded',
      notifyUser: true,
      askPermission: false,
      patches: [ScrollBehaviourToScrollEnabled]
    },
    {
      key: 'TextAlignmentAlignXNoodl20',
      message: 'Text nodes now support vertical alignment. Your project has been upgraded',
      notifyUser: true,
      askPermission: false,
      patches: [TextAlignmentAlignXNoodl20]
    },
    {
      key: 'TextAlignment',
      notifyUser: false,
      askPermission: false,
      patches: [TextAlignment]
    },
    {
      key: 'EventSenderReceiver',
      notifyUser: false,
      askPermission: false,
      patches: [EventSenderReceiver]
    }
  ]
};


/***/ }),

/***/ 22060:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5, _path6, _path7, _path8, _path9, _path0;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRoundedCornerLeftUp = function SvgRoundedCornerLeftUp(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.3335 4.9917C26.3335 5.40591 25.9977 5.7417 25.5835 5.7417C25.1693 5.7417 24.8335 5.40591 24.8335 4.9917C24.8335 4.57749 25.1693 4.2417 25.5835 4.2417C25.9977 4.2417 26.3335 4.57749 26.3335 4.9917Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.3335 18.7334C26.3335 19.1476 25.9977 19.4834 25.5835 19.4834C25.1693 19.4834 24.8335 19.1476 24.8335 18.7334C24.8335 18.3192 25.1693 17.9834 25.5835 17.9834C25.9977 17.9834 26.3335 18.3192 26.3335 18.7334Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M5.43994 18.7334C5.43994 19.1476 5.10415 19.4834 4.68994 19.4834C4.27573 19.4834 3.93994 19.1476 3.93994 18.7334C3.93994 18.3192 4.27573 17.9834 4.68994 17.9834C5.10415 17.9834 5.43994 18.3192 5.43994 18.7334Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.3335 11.8623C26.3335 12.2765 25.9977 12.6123 25.5835 12.6123C25.1693 12.6123 24.8335 12.2765 24.8335 11.8623C24.8335 11.4481 25.1693 11.1123 25.5835 11.1123C25.9977 11.1123 26.3335 11.4481 26.3335 11.8623Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.3335 25.6045C26.3335 26.0187 25.9977 26.3545 25.5835 26.3545C25.1693 26.3545 24.8335 26.0187 24.8335 25.6045C24.8335 25.1903 25.1693 24.8545 25.5835 24.8545C25.9977 24.8545 26.3335 25.1903 26.3335 25.6045Z",
    fill: "#F5F5F5"
  })), _path6 || (_path6 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.5913 25.6045C12.5913 26.0187 12.2555 26.3545 11.8413 26.3545C11.4271 26.3545 11.0913 26.0187 11.0913 25.6045C11.0913 25.1903 11.4271 24.8545 11.8413 24.8545C12.2555 24.8545 12.5913 25.1903 12.5913 25.6045Z",
    fill: "#F5F5F5"
  })), _path7 || (_path7 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M19.4624 25.6045C19.4624 26.0187 19.1266 26.3545 18.7124 26.3545C18.2982 26.3545 17.9624 26.0187 17.9624 25.6045C17.9624 25.1903 18.2982 24.8545 18.7124 24.8545C19.1266 24.8545 19.4624 25.1903 19.4624 25.6045Z",
    fill: "#F5F5F5"
  })), _path8 || (_path8 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M19.4624 4.9917C19.4624 5.40591 19.1266 5.7417 18.7124 5.7417C18.2982 5.7417 17.9624 5.40591 17.9624 4.9917C17.9624 4.57749 18.2982 4.2417 18.7124 4.2417C19.1266 4.2417 19.4624 4.57749 19.4624 4.9917Z",
    fill: "#F5F5F5"
  })), _path9 || (_path9 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M5.72021 25.6045C5.72021 26.0187 5.38443 26.3545 4.97021 26.3545C4.556 26.3545 4.22021 26.0187 4.22021 25.6045C4.22021 25.1903 4.556 24.8545 4.97021 24.8545C5.38443 24.8545 5.72021 25.1903 5.72021 25.6045Z",
    fill: "#F5F5F5"
  })), _path0 || (_path0 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.72021 11.9919L5.72021 13.0079C5.72021 13.4221 5.38443 13.7579 4.97021 13.7579C4.556 13.7579 4.22021 13.4221 4.22021 13.0079L4.22021 11.9919C4.22021 7.71167 7.69001 4.24188 11.9702 4.24188L12.9862 4.24188C13.4004 4.24188 13.7362 4.57767 13.7362 4.99188C13.7362 5.40609 13.4004 5.74188 12.9862 5.74188L11.9702 5.74188C8.51844 5.74188 5.72021 8.5401 5.72021 11.9919Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRoundedCornerLeftUp);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "8626998965d0114aacb5281d44aa4a56.svg");

/***/ }),

/***/ 22275:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

const express = __webpack_require__(99594);
const path = __webpack_require__(16928);
const Authentication = __webpack_require__(27650);
var fs = __webpack_require__(79896);

var newFeaturesInLatestVersion = [];

function getMount(mountPath) {
  mountPath = mountPath || '';
  if (!mountPath.endsWith('/')) {
    mountPath += '/';
  }
  return mountPath;
}

function checkIfIconsExistForApps(apps, iconsFolder) {
  for (var i in apps) {
    var currentApp = apps[i];
    var iconName = currentApp.iconName;
    var path = iconsFolder + '/' + iconName;

    fs.stat(path, function(err) {
      if (err) {
          if ('ENOENT' == err.code) {// file does not exist
              console.warn('Icon with file name: ' + iconName +' couldn\'t be found in icons folder!');
          } else {
            console.log(
              'An error occurd while checking for icons, please check permission!');
          }
      } else {
          //every thing was ok so for example you can read it and send it to client
      }
  } );
  }
}

module.exports = function(config, options) {
  options = options || {};
  var app = express();
  // Serve public files.
  app.use(express.static(path.join(__dirname,'parse-dashboard-public')));

  // Allow setting via middleware
  if (config.trustProxy && app.disabled('trust proxy')) {
    app.enable('trust proxy');
  }

  // wait for app to mount in order to get mountpath
  app.on('mount', function() {
    const mountPath = getMount(app.mountpath);
    const users = config.users;
    const useEncryptedPasswords = config.useEncryptedPasswords ? true : false;
    const authInstance = new Authentication(users, useEncryptedPasswords, mountPath);
    authInstance.initialize(app, { cookieSessionSecret: options.cookieSessionSecret });

    // Serve the configuration.
    app.get('/parse-dashboard-config.json', function(req, res) {
      let apps = config.apps.map((app) => Object.assign({}, app)); // make a copy
      let response = {
        apps: apps,
        newFeaturesInLatestVersion: newFeaturesInLatestVersion,
      };

      //Based on advice from Doug Wilson here:
      //https://github.com/expressjs/express/issues/2518
      const requestIsLocal =
        req.connection.remoteAddress === '127.0.0.1' ||
        req.connection.remoteAddress === '::ffff:127.0.0.1' ||
        req.connection.remoteAddress === '::1';
      if (!options.dev && !requestIsLocal) {
        if (!req.secure && !options.allowInsecureHTTP) {
          //Disallow HTTP requests except on localhost, to prevent the master key from being transmitted in cleartext
          return res.send({ success: false, error: 'Parse Dashboard can only be remotely accessed via HTTPS' });
        }

        if (!users) {
          //Accessing the dashboard over the internet can only be done with username and password
          return res.send({ success: false, error: 'Configure a user to access Parse Dashboard remotely' });
        }
      }
      const authentication = req.user;

      const successfulAuth = authentication && authentication.isAuthenticated;
      const appsUserHasAccess = authentication && authentication.appsUserHasAccessTo;
      const isReadOnly = authentication && authentication.isReadOnly;
      // User is full read-only, replace the masterKey by the read-only one
      if (isReadOnly) {
        response.apps = response.apps.map((app) => {
          app.masterKey = app.readOnlyMasterKey;
          if (!app.masterKey) {
            throw new Error('You need to provide a readOnlyMasterKey to use read-only features.');
          }
          return app;
        });
      }

      if (successfulAuth) {
        if (appsUserHasAccess) {
          // Restric access to apps defined in user dictionary
          // If they didn't supply any app id, user will access all apps
          response.apps = response.apps.filter(function (app) {
            return appsUserHasAccess.find(appUserHasAccess => {
              const isSame = app.appId === appUserHasAccess.appId;
              if (isSame && appUserHasAccess.readOnly) {
                app.masterKey = app.readOnlyMasterKey;
              }
              return isSame;
            })
          });
        }
        // They provided correct auth
        return res.json(response);
      }

      if (users) {
        //They provided incorrect auth
        return res.sendStatus(401);
      }

      //They didn't provide auth, and have configured the dashboard to not need auth
      //(ie. didn't supply usernames and passwords)
      if (requestIsLocal || options.dev) {
        //Allow no-auth access on localhost only, if they have configured the dashboard to not need auth
        return res.json(response);
      }
      //We shouldn't get here. Fail closed.
      res.send({ success: false, error: 'Something went wrong.' });
    });

    // Serve the app icons. Uses the optional `iconsFolder` parameter as
    // directory name, that was setup in the config file.
    // We are explicitly not using `__dirpath` here because one may be
    // running parse-dashboard from globally installed npm.
    if (config.iconsFolder) {
      try {
        var stat = fs.statSync(config.iconsFolder);
        if (stat.isDirectory()) {
          app.use('/appicons', express.static(config.iconsFolder));
          //Check also if the icons really exist
          checkIfIconsExistForApps(config.apps, config.iconsFolder);
        }
      } catch (e) {
        // Directory doesn't exist or something.
        console.warn('Iconsfolder at path: ' + config.iconsFolder +
          ' not found!');
      }
    }

    app.get('/login', function(req, res) {
      if (!users || (req.user && req.user.isAuthenticated)) {
        return res.redirect(`${mountPath}apps`);
      }

      let errors = req.flash('error');
      if (errors && errors.length) {
        errors = `<div id="login_errors" style="display: none;">
          ${errors.join(' ')}
        </div>`
      }
      res.send(`<!DOCTYPE html>
      <html>
        <head>
          <link rel="shortcut icon" type="image/x-icon" href="${mountPath}favicon.ico" />
          <base href="${mountPath}"/>
          <script>
            PARSE_DASHBOARD_PATH = "${mountPath}";
          </script>
          <title>Parse Dashboard</title>
        </head>
        <body>
          <div id="login_mount"></div>
          ${errors}
          <script src="${mountPath}bundles/login.bundle.js"></script>
        </body>
      </html>
      `);
    });

    // For every other request, go to index.html. Let client-side handle the rest.
    app.get('/*', function(req, res) {
      if (users && (!req.user || !req.user.isAuthenticated)) {
        return res.redirect(`${mountPath}login`);
      }
      if (users && req.user && req.user.matchingUsername ) {
        res.append('username', req.user.matchingUsername);
      }
      res.send(`<!DOCTYPE html>
      <html>
        <head>
          <link rel="shortcut icon" type="image/x-icon" href="${mountPath}favicon.ico" />
          <base href="${mountPath}"/>
          <script>
            PARSE_DASHBOARD_PATH = "${mountPath}";
          </script>
          <title>Parse Dashboard</title>
        </head>
        <body>
          <div id="browser_mount"></div>
          <script src="${mountPath}bundles/dashboard.bundle.js"></script>
        </body>
      </html>
      `);
    });
  });

  return app;
}


/***/ }),

/***/ 22391:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgJustifyContentCenter = function SvgJustifyContentCenter(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.457 14.9261H8.26953C7.90709 14.9261 7.61328 15.182 7.61328 15.4976V18.3547C7.61328 18.6703 7.90709 18.9261 8.26953 18.9261H17.457C17.8195 18.9261 18.1133 18.6703 18.1133 18.3547V15.4976C18.1133 15.182 17.8195 14.9261 17.457 14.9261Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.457 6.42615H8.26953C7.90709 6.42615 7.61328 6.68198 7.61328 6.99758V9.85472C7.61328 10.1703 7.90709 10.4261 8.26953 10.4261H17.457C17.8195 10.4261 18.1133 10.1703 18.1133 9.85472V6.99758C18.1133 6.68198 17.8195 6.42615 17.457 6.42615Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.86328 12.6761C3.86328 12.2619 4.22146 11.9261 4.6633 11.9261H21.0633C21.5051 11.9261 21.8633 12.2619 21.8633 12.6761C21.8633 13.0904 21.5051 13.4261 21.0633 13.4261H4.6633C4.22146 13.4261 3.86328 13.0904 3.86328 12.6761Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgJustifyContentCenter);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "bd11fa39d0022451de5d24d7fc6714b6.svg");

/***/ }),

/***/ 22456:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PrimaryButton-module__Root--KMqLg{border:0;font-size:var(--font-size-base);font-weight:var(--font-weight-medium);line-height:var(--line-height-tight);padding:var(--spacing-button-padding-y) var(--spacing-button-padding-x);display:flex;align-items:center;justify-content:center;gap:var(--spacing-button-gap);cursor:pointer;min-height:36px;min-width:70px;flex-grow:0;flex-shrink:0;position:relative;border-radius:var(--radius-md);transition:background-color var(--transition-default) var(--transition-ease),color var(--transition-default) var(--transition-ease),border-color var(--transition-default) var(--transition-ease),box-shadow var(--transition-default) var(--transition-ease),transform var(--transition-fast) var(--transition-ease)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-size-small--P9bel{min-height:28px;font-size:12px}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-cta--ARLBM{color:var(--theme-color-on-primary);background-color:var(--theme-color-primary);box-shadow:var(--shadow-sm)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-cta--ARLBM path{fill:var(--theme-color-on-primary)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-cta--ARLBM:hover:not(:disabled){background-color:var(--theme-color-primary-highlight);box-shadow:var(--shadow-default);transform:translateY(-1px)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-cta--ARLBM:active:not(:disabled){background-color:var(--theme-color-primary-dim);box-shadow:none;transform:translateY(0)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-muted--Cskrn{color:var(--theme-color-fg-default);background-color:var(--theme-color-bg-2)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-muted--Cskrn path{fill:var(--theme-color-fg-default)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-muted--Cskrn:hover{color:var(--theme-color-fg-highlight);background-color:var(--theme-color-bg-1)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-muted--Cskrn:hover path{fill:var(--theme-color-fg-highlight)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-muted-on-low-bg--rsdzS{color:var(--theme-color-fg-default);background-color:var(--theme-color-bg-3)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-muted-on-low-bg--rsdzS path{fill:var(--theme-color-fg-default)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-muted-on-low-bg--rsdzS:hover{color:var(--theme-color-fg-highlight);background-color:var(--theme-color-bg-1)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-muted-on-low-bg--rsdzS:hover path{fill:var(--theme-color-fg-highlight)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-ghost--mSPj1{color:var(--theme-color-primary);border:1px solid var(--theme-color-primary);background-color:rgba(0,0,0,0)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-ghost--mSPj1 path{fill:var(--theme-color-primary)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-ghost--mSPj1:hover{color:var(--theme-color-on-primary);background-color:var(--theme-color-primary)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-ghost--mSPj1:hover path{fill:var(--theme-color-on-primary)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-danger--l0q83{color:var(--theme-color-bg-1);background-color:var(--theme-color-danger)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-danger--l0q83 path{fill:var(--theme-color-bg-1)}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-variant-danger--l0q83:hover{background-color:var(--theme-color-danger-light)}.PrimaryButton-module__Root--KMqLg:disabled{cursor:not-allowed;opacity:.5;background-color:var(--theme-color-bg-3) !important;color:var(--theme-color-fg-muted);transform:none !important;box-shadow:none !important}.PrimaryButton-module__Root--KMqLg:disabled path{fill:var(--theme-color-fg-muted)}.PrimaryButton-module__Root--KMqLg:focus-visible{outline:2px solid var(--theme-color-focus-ring);outline-offset:2px}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__has-left-spacing--IlgTY{margin-left:12px}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__has-right-spacing--mjECG{margin-right:12px}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__has-bottom-spacing--gYXBb{margin-bottom:15px}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__has-top-spacing--LrkJc{margin-top:15px}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-fit-content--hrTdB{width:fit-content}.PrimaryButton-module__Root--KMqLg.PrimaryButton-module__is-growing--fESgk{flex:1;width:100%}.PrimaryButton-module__Label--ztZ26{display:inline-flex;align-items:center;transition:opacity 200ms var(--easing-base),transform 200ms var(--easing-base)}.PrimaryButton-module__Label--ztZ26.PrimaryButton-module__is-loading--T4aNn{opacity:0;transform:translateY(3px)}.PrimaryButton-module__Icon--r0HsQ{margin-right:4px}.PrimaryButton-module__Spinner--GCCBK{opacity:0;transform:translateY(calc(-50% + 3px)) translateX(-50%);position:absolute;top:50%;left:50%;transition:opacity 200ms var(--easing-base),transform 200ms var(--easing-base)}.PrimaryButton-module__Spinner--GCCBK.PrimaryButton-module__is-loading--T4aNn{opacity:1;transform:translateY(-50%) translateX(-50%)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/PrimaryButton/PrimaryButton.module.scss","webpack://./../noodl-core-ui/src/styles/scss-variables/length.scss"],"names":[],"mappings":"AAEA,mCACE,QAAA,CACA,+BAAA,CACA,qCAAA,CACA,oCAAA,CACA,uEAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,6BAAA,CACA,cAAA,CACA,eCTkB,CDUlB,cAAA,CACA,WAAA,CACA,aAAA,CACA,iBAAA,CACA,8BAAA,CACA,qTAAA,CAKA,8EACE,eCpBsB,CDqBtB,cAAA,CAGF,+EACE,mCAAA,CACA,2CAAA,CACA,2BAAA,CAEA,oFACE,kCAAA,CAGF,oGACE,qDAAA,CACA,gCAAA,CACA,0BAAA,CAGF,qGACE,+CAAA,CACA,eAAA,CACA,uBAAA,CAIJ,iFACE,mCAAA,CACA,wCAAA,CAEA,sFACE,kCAAA,CAGF,uFACE,qCAAA,CACA,wCAAA,CAEA,4FACE,oCAAA,CAKN,2FACE,mCAAA,CACA,wCAAA,CAEA,gGACE,kCAAA,CAGF,iGACE,qCAAA,CACA,wCAAA,CAEA,sGACE,oCAAA,CAKN,iFACE,gCAAA,CACA,2CAAA,CACA,8BAAA,CAEA,sFACE,+BAAA,CAGF,uFACE,mCAAA,CACA,2CAAA,CAEA,4FACE,kCAAA,CAKN,kFACE,6BAAA,CACA,0CAAA,CAEA,uFACE,4BAAA,CAGF,wFACE,gDAAA,CAIJ,4CACE,kBAAA,CACA,UAAA,CACA,mDAAA,CACA,iCAAA,CACA,yBAAA,CACA,0BAAA,CAEA,iDACE,gCAAA,CAIJ,iDACE,+CAAA,CACA,kBAAA,CAGF,iFACE,gBAAA,CAGF,kFACE,iBAAA,CAGF,mFACE,kBAAA,CAGF,gFACE,eAAA,CAGF,+EACE,iBAAA,CAGF,2EACE,MAAA,CACA,UAAA,CAIJ,oCACE,mBAAA,CACA,kBAAA,CACA,8EAAA,CAOA,4EACE,SAAA,CACA,yBAAA,CAIJ,mCACE,gBAAA,CAGF,sCACE,SAAA,CACA,uDAAA,CACA,iBAAA,CACA,OAAA,CACA,QAAA,CACA,8EAAA,CAEA,8EACE,SAAA,CACA,2CAAA","sourcesContent":["@use '../../../styles/scss-variables/length.scss';\n\n.Root {\n  border: 0;\n  font-size: var(--font-size-base);\n  font-weight: var(--font-weight-medium);\n  line-height: var(--line-height-tight);\n  padding: var(--spacing-button-padding-y) var(--spacing-button-padding-x);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  gap: var(--spacing-button-gap);\n  cursor: pointer;\n  min-height: length.$global-input-size;\n  min-width: 70px;\n  flex-grow: 0;\n  flex-shrink: 0;\n  position: relative;\n  border-radius: var(--radius-md);\n  transition: background-color var(--transition-default) var(--transition-ease),\n    color var(--transition-default) var(--transition-ease),\n    border-color var(--transition-default) var(--transition-ease),\n    box-shadow var(--transition-default) var(--transition-ease), transform var(--transition-fast) var(--transition-ease);\n\n  &.is-size-small {\n    min-height: length.$global-input-size-small;\n    font-size: 12px;\n  }\n\n  &.is-variant-cta {\n    color: var(--theme-color-on-primary);\n    background-color: var(--theme-color-primary);\n    box-shadow: var(--shadow-sm);\n\n    path {\n      fill: var(--theme-color-on-primary);\n    }\n\n    &:hover:not(:disabled) {\n      background-color: var(--theme-color-primary-highlight);\n      box-shadow: var(--shadow-default);\n      transform: translateY(-1px);\n    }\n\n    &:active:not(:disabled) {\n      background-color: var(--theme-color-primary-dim);\n      box-shadow: none;\n      transform: translateY(0);\n    }\n  }\n\n  &.is-variant-muted {\n    color: var(--theme-color-fg-default);\n    background-color: var(--theme-color-bg-2);\n\n    path {\n      fill: var(--theme-color-fg-default);\n    }\n\n    &:hover {\n      color: var(--theme-color-fg-highlight);\n      background-color: var(--theme-color-bg-1);\n\n      path {\n        fill: var(--theme-color-fg-highlight);\n      }\n    }\n  }\n\n  &.is-variant-muted-on-low-bg {\n    color: var(--theme-color-fg-default);\n    background-color: var(--theme-color-bg-3);\n\n    path {\n      fill: var(--theme-color-fg-default);\n    }\n\n    &:hover {\n      color: var(--theme-color-fg-highlight);\n      background-color: var(--theme-color-bg-1);\n\n      path {\n        fill: var(--theme-color-fg-highlight);\n      }\n    }\n  }\n\n  &.is-variant-ghost {\n    color: var(--theme-color-primary);\n    border: 1px solid var(--theme-color-primary);\n    background-color: transparent;\n\n    path {\n      fill: var(--theme-color-primary);\n    }\n\n    &:hover {\n      color: var(--theme-color-on-primary);\n      background-color: var(--theme-color-primary);\n\n      path {\n        fill: var(--theme-color-on-primary);\n      }\n    }\n  }\n\n  &.is-variant-danger {\n    color: var(--theme-color-bg-1);\n    background-color: var(--theme-color-danger);\n\n    path {\n      fill: var(--theme-color-bg-1);\n    }\n\n    &:hover {\n      background-color: var(--theme-color-danger-light);\n    }\n  }\n\n  &:disabled {\n    cursor: not-allowed;\n    opacity: 0.5;\n    background-color: var(--theme-color-bg-3) !important;\n    color: var(--theme-color-fg-muted);\n    transform: none !important;\n    box-shadow: none !important;\n\n    path {\n      fill: var(--theme-color-fg-muted);\n    }\n  }\n\n  &:focus-visible {\n    outline: 2px solid var(--theme-color-focus-ring);\n    outline-offset: 2px;\n  }\n\n  &.has-left-spacing {\n    margin-left: 12px;\n  }\n\n  &.has-right-spacing {\n    margin-right: 12px;\n  }\n\n  &.has-bottom-spacing {\n    margin-bottom: 15px;\n  }\n\n  &.has-top-spacing {\n    margin-top: 15px;\n  }\n\n  &.is-fit-content {\n    width: fit-content;\n  }\n\n  &.is-growing {\n    flex: 1;\n    width: 100%;\n  }\n}\n\n.Label {\n  display: inline-flex;\n  align-items: center;\n  transition: opacity 200ms var(--easing-base), transform 200ms var(--easing-base);\n  // text-transform: lowercase;\n\n  // &::first-letter {\n  //   text-transform: capitalize;\n  // }\n\n  &.is-loading {\n    opacity: 0;\n    transform: translateY(3px);\n  }\n}\n\n.Icon {\n  margin-right: 4px;\n}\n\n.Spinner {\n  opacity: 0;\n  transform: translateY(calc(-50% + 3px)) translateX(-50%);\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  transition: opacity 200ms var(--easing-base), transform 200ms var(--easing-base);\n\n  &.is-loading {\n    opacity: 1;\n    transform: translateY(-50%) translateX(-50%);\n  }\n}\n","$property-panel-input-padding: 6px 8px 7px;\r\n$property-panel-input-size: 28px;\r\n$property-panel-small-xy-padding: 4px;\r\n\r\n$global-input-size: 36px;\r\n$global-input-size-small: 28px;\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PrimaryButton-module__Root--KMqLg`,
	"is-size-small": `PrimaryButton-module__is-size-small--P9bel`,
	"is-variant-cta": `PrimaryButton-module__is-variant-cta--ARLBM`,
	"is-variant-muted": `PrimaryButton-module__is-variant-muted--Cskrn`,
	"is-variant-muted-on-low-bg": `PrimaryButton-module__is-variant-muted-on-low-bg--rsdzS`,
	"is-variant-ghost": `PrimaryButton-module__is-variant-ghost--mSPj1`,
	"is-variant-danger": `PrimaryButton-module__is-variant-danger--l0q83`,
	"has-left-spacing": `PrimaryButton-module__has-left-spacing--IlgTY`,
	"has-right-spacing": `PrimaryButton-module__has-right-spacing--mjECG`,
	"has-bottom-spacing": `PrimaryButton-module__has-bottom-spacing--gYXBb`,
	"has-top-spacing": `PrimaryButton-module__has-top-spacing--LrkJc`,
	"is-fit-content": `PrimaryButton-module__is-fit-content--hrTdB`,
	"is-growing": `PrimaryButton-module__is-growing--fESgk`,
	"Label": `PrimaryButton-module__Label--ztZ26`,
	"is-loading": `PrimaryButton-module__is-loading--T4aNn`,
	"Icon": `PrimaryButton-module__Icon--r0HsQ`,
	"Spinner": `PrimaryButton-module__Spinner--GCCBK`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 22484:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  a: () => (/* reexport */ Box)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/Box/Box.module.scss
var Box_module = __webpack_require__(91885);
;// ../noodl-core-ui/src/components/layout/Box/Box.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(Box_module/* default */.A, options);




       /* harmony default export */ const Box_Box_module = (Box_module/* default */.A && Box_module/* default */.A.locals ? Box_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/Box/Box.tsx



function Box({ hasLeftSpacing, hasRightSpacing, hasTopSpacing, hasBottomSpacing, hasXSpacing, hasYSpacing, UNSAFE_style, UNSAFE_className, children }) {
    const style = {
        ...UNSAFE_style
    };
    function convert(...values) {
        for (const value of values) {
            if (typeof value === 'boolean' && value) {
                return '16px';
            }
            if (typeof value === 'number') {
                return value * 4 + 'px';
            }
        }
        return undefined;
    }
    if (hasXSpacing || hasLeftSpacing) {
        style.paddingLeft = convert(hasLeftSpacing, hasXSpacing);
    }
    if (hasXSpacing || hasRightSpacing) {
        style.paddingRight = convert(hasRightSpacing, hasXSpacing);
    }
    if (hasYSpacing || hasTopSpacing) {
        style.paddingTop = convert(hasTopSpacing, hasYSpacing);
    }
    if (hasYSpacing || hasBottomSpacing) {
        style.paddingBottom = convert(hasBottomSpacing, hasYSpacing);
    }
    return (external_react_default().createElement("div", { className: external_classnames_default()([Box_Box_module['Root'], UNSAFE_className]), style: style }, children));
}

;// ../noodl-core-ui/src/components/layout/Box/index.ts



/***/ }),

/***/ 22619:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.AiChatSuggestion-module__Root--rOTlz{padding:12px 16px;border:1px solid var(--theme-color-bg-3);border-radius:2px;text-align:center;user-select:none;cursor:pointer}.AiChatSuggestion-module__Root--rOTlz:hover{background-color:var(--theme-color-bg-3)}.AiChatSuggestion-module__Mounted--buwP9{transform:translateY(0px);opacity:1;transition:background-color 100ms ease,opacity 500ms ease,transform .5s ease}.AiChatSuggestion-module__Mounting--YrwG0{transform:translateY(8px);opacity:0}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/ai/AiChatSuggestion/AiChatSuggestion.module.scss"],"names":[],"mappings":"AAAA,sCACE,iBAAA,CACA,wCAAA,CACA,iBAAA,CACA,iBAAA,CACA,gBAAA,CACA,cAAA,CAEA,4CACE,wCAAA,CAIJ,yCACE,yBAAA,CACA,SAAA,CACA,4EAAA,CAGF,0CACE,yBAAA,CACA,SAAA","sourcesContent":[".Root {\n  padding: 12px 16px;\n  border: 1px solid var(--theme-color-bg-3);\n  border-radius: 2px;\n  text-align: center;\n  user-select: none;\n  cursor: pointer;\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n.Mounted {\n  transform: translateY(0px);\n  opacity: 1;\n  transition: background-color 100ms ease, opacity 500ms ease, transform 0.5s ease;\n}\n\n.Mounting {\n  transform: translateY(8px);\n  opacity: 0;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `AiChatSuggestion-module__Root--rOTlz`,
	"Mounted": `AiChatSuggestion-module__Mounted--buwP9`,
	"Mounting": `AiChatSuggestion-module__Mounting--YrwG0`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 22744:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `@keyframes FailedStep-module__slideInUp--aSWKE{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes FailedStep-module__shake--osWyK{0%,100%{transform:translateX(0)}25%{transform:translateX(-4px)}75%{transform:translateX(4px)}}.FailedStep-module__Root--eCbMN{display:flex;flex-direction:column;height:100%;animation:FailedStep-module__slideInUp--aSWKE 300ms ease-out}.FailedStep-module__Header--NJObg{display:flex;flex-direction:column;align-items:center;gap:16px;margin-bottom:24px;padding:20px;background:linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, transparent 100%);border-radius:12px}.FailedStep-module__Header--NJObg .FailedStep-module__ErrorIcon--K3GrO{width:64px;height:64px;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg, rgba(239, 68, 68, 0.2) 0%, rgba(239, 68, 68, 0.1) 100%);border-radius:50%;animation:FailedStep-module__shake--osWyK 500ms ease-out}.FailedStep-module__Header--NJObg .FailedStep-module__ErrorIcon--K3GrO svg{width:36px;height:36px;color:var(--theme-color-danger)}.FailedStep-module__Header--NJObg h2{font-size:22px;font-weight:700;color:var(--theme-color-fg-highlight);margin:0;text-align:center}.FailedStep-module__Header--NJObg p{font-size:14px;color:var(--theme-color-fg-default);margin:0;text-align:center;line-height:1.6}.FailedStep-module__ErrorBox--dCwjQ{margin-bottom:20px;background:linear-gradient(135deg, rgba(239, 68, 68, 0.08) 0%, rgba(239, 68, 68, 0.05) 100%);border:2px solid rgba(239,68,68,.3);border-radius:12px;overflow:hidden}.FailedStep-module__ErrorHeader--LbRLr{display:flex;align-items:center;gap:12px;padding:16px 20px;background-color:rgba(239,68,68,.15);border-bottom:1px solid rgba(239,68,68,.2)}.FailedStep-module__ErrorHeader--LbRLr svg{width:20px;height:20px;color:var(--theme-color-danger);flex-shrink:0}.FailedStep-module__ErrorHeader--LbRLr h3{font-size:14px;font-weight:600;color:var(--theme-color-danger);margin:0}.FailedStep-module__ErrorMessage--PEqGK{padding:20px;font-family:monospace;font-size:13px;line-height:1.6;color:var(--theme-color-fg-highlight);background-color:var(--theme-color-bg-4);word-break:break-word;white-space:pre-wrap}.FailedStep-module__Suggestions--ZjJM9{padding:20px;background:linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);border-radius:12px;border:1px solid var(--theme-color-bg-2);margin-bottom:20px}.FailedStep-module__Suggestions--ZjJM9 h3{font-size:16px;font-weight:600;color:var(--theme-color-fg-highlight);margin:0 0 16px 0;display:flex;align-items:center;gap:8px}.FailedStep-module__Suggestions--ZjJM9 h3 svg{width:20px;height:20px;color:var(--theme-color-primary)}.FailedStep-module__SuggestionList--IXi5W{list-style:none;padding:0;margin:0}.FailedStep-module__SuggestionList--IXi5W li{display:flex;gap:16px;padding:16px;background-color:var(--theme-color-bg-4);border-radius:8px;font-size:14px;line-height:1.5;color:var(--theme-color-fg-default);transition:all 200ms ease-in-out}.FailedStep-module__SuggestionList--IXi5W li:not(:last-child){margin-bottom:10px}.FailedStep-module__SuggestionList--IXi5W li:hover{background-color:var(--theme-color-bg-3);transform:translateX(4px)}.FailedStep-module__SuggestionList--IXi5W li svg{width:20px;height:20px;flex-shrink:0;margin-top:2px;color:var(--theme-color-primary)}.FailedStep-module__Link--QmhjY{color:var(--theme-color-primary);text-decoration:underline;font-weight:500;transition:opacity 200ms ease-in-out}.FailedStep-module__Link--QmhjY:hover{opacity:.7}.FailedStep-module__SafetyNotice--AUoxa{display:flex;gap:16px;padding:20px;background:linear-gradient(135deg, rgba(34, 197, 94, 0.12) 0%, rgba(34, 197, 94, 0.08) 100%);border:2px solid rgba(34,197,94,.3);border-radius:12px;margin-bottom:20px}.FailedStep-module__SafetyNotice--AUoxa svg{width:24px;height:24px;flex-shrink:0;color:var(--theme-color-success)}.FailedStep-module__SafetyNotice--AUoxa .FailedStep-module__SafetyContent--s1Ddn{flex:1}.FailedStep-module__SafetyNotice--AUoxa .FailedStep-module__SafetyContent--s1Ddn h4{font-size:14px;font-weight:600;color:var(--theme-color-success);margin:0 0 6px 0}.FailedStep-module__SafetyNotice--AUoxa .FailedStep-module__SafetyContent--s1Ddn p{font-size:13px;line-height:1.6;color:var(--theme-color-fg-default);margin:0}.FailedStep-module__Actions--z1z7n{margin-top:auto;padding-top:24px;display:flex;justify-content:flex-end;gap:12px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/migration/steps/FailedStep.module.scss"],"names":[],"mappings":"AAMA,+CACE,KACE,SAAA,CACA,0BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,2CACE,QAEE,uBAAA,CAEF,IACE,0BAAA,CAEF,IACE,yBAAA,CAAA,CAIJ,gCACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,4DAAA,CAGF,kCACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,QAAA,CACA,kBAAA,CACA,YAAA,CACA,+EAAA,CACA,kBAAA,CAEA,uEACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,0FAAA,CACA,iBAAA,CACA,wDAAA,CAEA,2EACE,UAAA,CACA,WAAA,CACA,+BAAA,CAIJ,qCACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,QAAA,CACA,iBAAA,CAGF,oCACE,cAAA,CACA,mCAAA,CACA,QAAA,CACA,iBAAA,CACA,eAAA,CAIJ,oCACE,kBAAA,CACA,4FAAA,CACA,mCAAA,CACA,kBAAA,CACA,eAAA,CAGF,uCACE,YAAA,CACA,kBAAA,CACA,QAAA,CACA,iBAAA,CACA,oCAAA,CACA,0CAAA,CAEA,2CACE,UAAA,CACA,WAAA,CACA,+BAAA,CACA,aAAA,CAGF,0CACE,cAAA,CACA,eAAA,CACA,+BAAA,CACA,QAAA,CAIJ,wCACE,YAAA,CACA,qBAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CACA,wCAAA,CACA,qBAAA,CACA,oBAAA,CAGF,uCACE,YAAA,CACA,4FAAA,CACA,kBAAA,CACA,wCAAA,CACA,kBAAA,CAEA,0CACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,iBAAA,CACA,YAAA,CACA,kBAAA,CACA,OAAA,CAEA,8CACE,UAAA,CACA,WAAA,CACA,gCAAA,CAKN,0CACE,eAAA,CACA,SAAA,CACA,QAAA,CAEA,6CACE,YAAA,CACA,QAAA,CACA,YAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CACA,gCAAA,CAEA,8DACE,kBAAA,CAGF,mDACE,wCAAA,CACA,yBAAA,CAGF,iDACE,UAAA,CACA,WAAA,CACA,aAAA,CACA,cAAA,CACA,gCAAA,CAKN,gCACE,gCAAA,CACA,yBAAA,CACA,eAAA,CACA,oCAAA,CAEA,sCACE,UAAA,CAIJ,wCACE,YAAA,CACA,QAAA,CACA,YAAA,CACA,4FAAA,CACA,mCAAA,CACA,kBAAA,CACA,kBAAA,CAEA,4CACE,UAAA,CACA,WAAA,CACA,aAAA,CACA,gCAAA,CAGF,iFACE,MAAA,CAEA,oFACE,cAAA,CACA,eAAA,CACA,gCAAA,CACA,gBAAA,CAGF,mFACE,cAAA,CACA,eAAA,CACA,mCAAA,CACA,QAAA,CAKN,mCACE,eAAA,CACA,gBAAA,CACA,YAAA,CACA,wBAAA,CACA,QAAA","sourcesContent":["/**\n * FailedStep Styles\n * \n * Enhanced error state with helpful suggestions and beautiful error display.\n */\n\n@keyframes slideInUp {\n  from {\n    opacity: 0;\n    transform: translateY(10px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n@keyframes shake {\n  0%,\n  100% {\n    transform: translateX(0);\n  }\n  25% {\n    transform: translateX(-4px);\n  }\n  75% {\n    transform: translateX(4px);\n  }\n}\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  animation: slideInUp 300ms ease-out;\n}\n\n.Header {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 16px;\n  margin-bottom: 24px;\n  padding: 20px;\n  background: linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, transparent 100%);\n  border-radius: 12px;\n\n  .ErrorIcon {\n    width: 64px;\n    height: 64px;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    background: linear-gradient(135deg, rgba(239, 68, 68, 0.2) 0%, rgba(239, 68, 68, 0.1) 100%);\n    border-radius: 50%;\n    animation: shake 500ms ease-out;\n\n    svg {\n      width: 36px;\n      height: 36px;\n      color: var(--theme-color-danger);\n    }\n  }\n\n  h2 {\n    font-size: 22px;\n    font-weight: 700;\n    color: var(--theme-color-fg-highlight);\n    margin: 0;\n    text-align: center;\n  }\n\n  p {\n    font-size: 14px;\n    color: var(--theme-color-fg-default);\n    margin: 0;\n    text-align: center;\n    line-height: 1.6;\n  }\n}\n\n.ErrorBox {\n  margin-bottom: 20px;\n  background: linear-gradient(135deg, rgba(239, 68, 68, 0.08) 0%, rgba(239, 68, 68, 0.05) 100%);\n  border: 2px solid rgba(239, 68, 68, 0.3);\n  border-radius: 12px;\n  overflow: hidden;\n}\n\n.ErrorHeader {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  padding: 16px 20px;\n  background-color: rgba(239, 68, 68, 0.15);\n  border-bottom: 1px solid rgba(239, 68, 68, 0.2);\n\n  svg {\n    width: 20px;\n    height: 20px;\n    color: var(--theme-color-danger);\n    flex-shrink: 0;\n  }\n\n  h3 {\n    font-size: 14px;\n    font-weight: 600;\n    color: var(--theme-color-danger);\n    margin: 0;\n  }\n}\n\n.ErrorMessage {\n  padding: 20px;\n  font-family: monospace;\n  font-size: 13px;\n  line-height: 1.6;\n  color: var(--theme-color-fg-highlight);\n  background-color: var(--theme-color-bg-4);\n  word-break: break-word;\n  white-space: pre-wrap;\n}\n\n.Suggestions {\n  padding: 20px;\n  background: linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);\n  border-radius: 12px;\n  border: 1px solid var(--theme-color-bg-2);\n  margin-bottom: 20px;\n\n  h3 {\n    font-size: 16px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    margin: 0 0 16px 0;\n    display: flex;\n    align-items: center;\n    gap: 8px;\n\n    svg {\n      width: 20px;\n      height: 20px;\n      color: var(--theme-color-primary);\n    }\n  }\n}\n\n.SuggestionList {\n  list-style: none;\n  padding: 0;\n  margin: 0;\n\n  li {\n    display: flex;\n    gap: 16px;\n    padding: 16px;\n    background-color: var(--theme-color-bg-4);\n    border-radius: 8px;\n    font-size: 14px;\n    line-height: 1.5;\n    color: var(--theme-color-fg-default);\n    transition: all 200ms ease-in-out;\n\n    &:not(:last-child) {\n      margin-bottom: 10px;\n    }\n\n    &:hover {\n      background-color: var(--theme-color-bg-3);\n      transform: translateX(4px);\n    }\n\n    svg {\n      width: 20px;\n      height: 20px;\n      flex-shrink: 0;\n      margin-top: 2px;\n      color: var(--theme-color-primary);\n    }\n  }\n}\n\n.Link {\n  color: var(--theme-color-primary);\n  text-decoration: underline;\n  font-weight: 500;\n  transition: opacity 200ms ease-in-out;\n\n  &:hover {\n    opacity: 0.7;\n  }\n}\n\n.SafetyNotice {\n  display: flex;\n  gap: 16px;\n  padding: 20px;\n  background: linear-gradient(135deg, rgba(34, 197, 94, 0.12) 0%, rgba(34, 197, 94, 0.08) 100%);\n  border: 2px solid rgba(34, 197, 94, 0.3);\n  border-radius: 12px;\n  margin-bottom: 20px;\n\n  svg {\n    width: 24px;\n    height: 24px;\n    flex-shrink: 0;\n    color: var(--theme-color-success);\n  }\n\n  .SafetyContent {\n    flex: 1;\n\n    h4 {\n      font-size: 14px;\n      font-weight: 600;\n      color: var(--theme-color-success);\n      margin: 0 0 6px 0;\n    }\n\n    p {\n      font-size: 13px;\n      line-height: 1.6;\n      color: var(--theme-color-fg-default);\n      margin: 0;\n    }\n  }\n}\n\n.Actions {\n  margin-top: auto;\n  padding-top: 24px;\n  display: flex;\n  justify-content: flex-end;\n  gap: 12px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `FailedStep-module__Root--eCbMN`,
	"slideInUp": `FailedStep-module__slideInUp--aSWKE`,
	"Header": `FailedStep-module__Header--NJObg`,
	"ErrorIcon": `FailedStep-module__ErrorIcon--K3GrO`,
	"shake": `FailedStep-module__shake--osWyK`,
	"ErrorBox": `FailedStep-module__ErrorBox--dCwjQ`,
	"ErrorHeader": `FailedStep-module__ErrorHeader--LbRLr`,
	"ErrorMessage": `FailedStep-module__ErrorMessage--PEqGK`,
	"Suggestions": `FailedStep-module__Suggestions--ZjJM9`,
	"SuggestionList": `FailedStep-module__SuggestionList--IXi5W`,
	"Link": `FailedStep-module__Link--QmhjY`,
	"SafetyNotice": `FailedStep-module__SafetyNotice--AUoxa`,
	"SafetyContent": `FailedStep-module__SafetyContent--s1Ddn`,
	"Actions": `FailedStep-module__Actions--z1z7n`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 22862:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.LegacyIconButton-module__Root--p3ZUK{width:24px;height:24px;display:flex;align-items:center;justify-content:center;opacity:.5;background:rgba(0,0,0,0);border:0;border-radius:0;transition:opacity var(--speed-turbo),background-color var(--speed-turbo)}.LegacyIconButton-module__Root--p3ZUK:hover{opacity:1;background-color:var(--theme-color-bg-3)}.LegacyIconButton-module__Icon--OFFNO{width:20px;height:20px;transition:transform var(--speed-quick) var(--easing-base);pointer-events:none}.LegacyIconButton-module__Icon--OFFNO.LegacyIconButton-module__is-rotated-180--tOp_m{transform:rotate(-180deg)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/LegacyIconButton/LegacyIconButton.module.scss"],"names":[],"mappings":"AAAA,sCACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CACA,wBAAA,CACA,QAAA,CACA,eAAA,CACA,yEAAA,CAEA,4CACE,SAAA,CACA,wCAAA,CAIJ,sCACE,UAAA,CACA,WAAA,CACA,0DAAA,CACA,mBAAA,CAEA,qFACE,yBAAA","sourcesContent":[".Root {\r\n  width: 24px;\r\n  height: 24px;\r\n  display: flex;\r\n  align-items: center;\r\n  justify-content: center;\r\n  opacity: 0.5;\r\n  background: transparent;\r\n  border: 0;\r\n  border-radius: 0;\r\n  transition: opacity var(--speed-turbo), background-color var(--speed-turbo);\r\n\r\n  &:hover {\r\n    opacity: 1;\r\n    background-color: var(--theme-color-bg-3);\r\n  }\r\n}\r\n\r\n.Icon {\r\n  width: 20px;\r\n  height: 20px;\r\n  transition: transform var(--speed-quick) var(--easing-base);\r\n  pointer-events: none;\r\n\r\n  &.is-rotated-180 {\r\n    transform: rotate(-180deg);\r\n  }\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `LegacyIconButton-module__Root--p3ZUK`,
	"Icon": `LegacyIconButton-module__Icon--OFFNO`,
	"is-rotated-180": `LegacyIconButton-module__is-rotated-180--tOp_m`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 23438:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ExpressionEditorModal-module__Overlay--dhDxT{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;z-index:10000}.ExpressionEditorModal-module__Modal--SYTYN{background-color:var(--theme-color-bg-2, #1a1a1a);border-radius:8px;box-shadow:0 8px 32px rgba(0,0,0,.5);width:700px;max-width:90vw;max-height:90vh;display:flex;flex-direction:column;overflow:hidden}.ExpressionEditorModal-module__Header--Z2_jO{padding:16px 20px;border-bottom:1px solid var(--theme-color-border-default, rgba(255, 255, 255, 0.1));display:flex;align-items:center;justify-content:space-between}.ExpressionEditorModal-module__Title--qLd9C{font-size:16px;font-weight:600;color:var(--theme-color-fg-highlight, #ffffff);margin:0}.ExpressionEditorModal-module__Body--dmoOp{padding:16px 20px;flex:1;overflow:auto;display:flex;flex-direction:column;gap:12px}.ExpressionEditorModal-module__HelpText--rddOo{padding:8px 12px;background-color:var(--theme-color-bg-3, rgba(255, 255, 255, 0.05));border-radius:4px;font-size:12px;color:var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.6))}.ExpressionEditorModal-module__HelpText--rddOo code{background-color:var(--theme-color-bg-1, rgba(99, 102, 241, 0.2));padding:2px 4px;border-radius:2px;font-family:"Monaco","Menlo",monospace;font-size:11px;color:var(--theme-color-primary, #6366f1)}.ExpressionEditorModal-module__EditorWrapper--OR5v3{flex:1;min-height:300px;border-radius:4px;overflow:hidden}.ExpressionEditorModal-module__Footer--qyP2N{padding:12px 20px;border-top:1px solid var(--theme-color-border-default, rgba(255, 255, 255, 0.1));display:flex;justify-content:flex-end;gap:8px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/propertyeditor/ExpressionEditorModal/ExpressionEditorModal.module.scss"],"names":[],"mappings":"AAAA,8CACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,+BAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,aAAA,CAGF,4CACE,iDAAA,CACA,iBAAA,CACA,oCAAA,CACA,WAAA,CACA,cAAA,CACA,eAAA,CACA,YAAA,CACA,qBAAA,CACA,eAAA,CAGF,6CACE,iBAAA,CACA,mFAAA,CACA,YAAA,CACA,kBAAA,CACA,6BAAA,CAGF,4CACE,cAAA,CACA,eAAA,CACA,8CAAA,CACA,QAAA,CAGF,2CACE,iBAAA,CACA,MAAA,CACA,aAAA,CACA,YAAA,CACA,qBAAA,CACA,QAAA,CAGF,+CACE,gBAAA,CACA,mEAAA,CACA,iBAAA,CACA,cAAA,CACA,iEAAA,CAEA,oDACE,iEAAA,CACA,eAAA,CACA,iBAAA,CACA,sCAAA,CACA,cAAA,CACA,yCAAA,CAIJ,oDACE,MAAA,CACA,gBAAA,CACA,iBAAA,CACA,eAAA,CAGF,6CACE,iBAAA,CACA,gFAAA,CACA,YAAA,CACA,wBAAA,CACA,OAAA","sourcesContent":[".Overlay {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.6);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 10000;\n}\n\n.Modal {\n  background-color: var(--theme-color-bg-2, #1a1a1a);\n  border-radius: 8px;\n  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);\n  width: 700px;\n  max-width: 90vw;\n  max-height: 90vh;\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n\n.Header {\n  padding: 16px 20px;\n  border-bottom: 1px solid var(--theme-color-border-default, rgba(255, 255, 255, 0.1));\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n}\n\n.Title {\n  font-size: 16px;\n  font-weight: 600;\n  color: var(--theme-color-fg-highlight, #ffffff);\n  margin: 0;\n}\n\n.Body {\n  padding: 16px 20px;\n  flex: 1;\n  overflow: auto;\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n}\n\n.HelpText {\n  padding: 8px 12px;\n  background-color: var(--theme-color-bg-3, rgba(255, 255, 255, 0.05));\n  border-radius: 4px;\n  font-size: 12px;\n  color: var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.6));\n\n  code {\n    background-color: var(--theme-color-bg-1, rgba(99, 102, 241, 0.2));\n    padding: 2px 4px;\n    border-radius: 2px;\n    font-family: 'Monaco', 'Menlo', monospace;\n    font-size: 11px;\n    color: var(--theme-color-primary, #6366f1);\n  }\n}\n\n.EditorWrapper {\n  flex: 1;\n  min-height: 300px;\n  border-radius: 4px;\n  overflow: hidden;\n}\n\n.Footer {\n  padding: 12px 20px;\n  border-top: 1px solid var(--theme-color-border-default, rgba(255, 255, 255, 0.1));\n  display: flex;\n  justify-content: flex-end;\n  gap: 8px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Overlay": `ExpressionEditorModal-module__Overlay--dhDxT`,
	"Modal": `ExpressionEditorModal-module__Modal--SYTYN`,
	"Header": `ExpressionEditorModal-module__Header--Z2_jO`,
	"Title": `ExpressionEditorModal-module__Title--qLd9C`,
	"Body": `ExpressionEditorModal-module__Body--dmoOp`,
	"HelpText": `ExpressionEditorModal-module__HelpText--rddOo`,
	"EditorWrapper": `ExpressionEditorModal-module__EditorWrapper--OR5v3`,
	"Footer": `ExpressionEditorModal-module__Footer--qyP2N`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 23442:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  MenuDialog: () => (/* reexport */ MenuDialog),
  MenuDialogWidth: () => (/* reexport */ MenuDialogWidth)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/BaseDialog/index.ts + 3 modules
var BaseDialog = __webpack_require__(65762);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/popups/Tooltip/index.ts + 2 modules
var Tooltip = __webpack_require__(87073);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Label/index.ts + 2 modules
var Label = __webpack_require__(91629);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/index.ts
var Text = __webpack_require__(93834);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/popups/MenuDialog/MenuDialog.module.scss
var MenuDialog_module = __webpack_require__(81246);
;// ../noodl-core-ui/src/components/popups/MenuDialog/MenuDialog.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(MenuDialog_module/* default */.A, options);




       /* harmony default export */ const MenuDialog_MenuDialog_module = (MenuDialog_module/* default */.A && MenuDialog_module/* default */.A.locals ? MenuDialog_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/popups/MenuDialog/MenuDialog.tsx








var MenuDialogWidth;
(function (MenuDialogWidth) {
    MenuDialogWidth["Small"] = "is-width-small";
    MenuDialogWidth["Default"] = "is-width-default";
    MenuDialogWidth["Medium"] = "is-width-medium";
    MenuDialogWidth["Large"] = "is-width-large";
})(MenuDialogWidth || (MenuDialogWidth = {}));
function MenuDialog({ items, title, width = MenuDialogWidth.Default, triggerRef, isVisible, renderDirection, UNSAFE_maxHeight, onClose }) {
    return (external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { isVisible: isVisible, onClose: onClose, triggerRef: triggerRef, title: title, renderDirection: renderDirection, isLockingScroll: true, hasArrow: true },
        external_react_default().createElement("div", { className: external_classnames_default()(MenuDialog_MenuDialog_module['Root'], MenuDialog_MenuDialog_module[width]), style: { maxHeight: UNSAFE_maxHeight } }, items.map((item, i) => {
            if (item === 'divider')
                return external_react_default().createElement("div", { className: MenuDialog_MenuDialog_module['Divider'], key: i });
            if (item === null || item === void 0 ? void 0 : item.isHidden)
                return null;
            const itemContent = (external_react_default().createElement("div", { className: external_classnames_default()(MenuDialog_MenuDialog_module['Item'], item.isDangerous && MenuDialog_MenuDialog_module['is-danger'], item.component && MenuDialog_MenuDialog_module['has-component'], item.isHighlighted && MenuDialog_MenuDialog_module['is-highlighted'], item.isDisabled && MenuDialog_MenuDialog_module['is-disabled']), onClick: (e) => {
                    if (item.isDisabled)
                        return;
                    if (!item.dontCloseMenuOnClick)
                        onClose();
                    if (!item.onClick)
                        return;
                    item.onClick(e);
                }, key: item.key || item.label, "data-test": item.testId },
                external_react_default().createElement("div", { className: external_classnames_default()(MenuDialog_MenuDialog_module['Label'], item.endSlot && MenuDialog_MenuDialog_module['has-bottom-spacing']) },
                    item.icon && external_react_default().createElement(Icon/* Icon */.In, { icon: item.icon, size: Icon/* IconSize */.lK.Tiny, UNSAFE_className: MenuDialog_MenuDialog_module['Icon'] }),
                    external_react_default().createElement(Label/* Label */.JU, { variant: Text/* TextType */.M2.DefaultContrast, hasTextWrap: true }, item.label)),
                item.component && (() => {
                    const component = item.component(() => onClose());
                    return (0,external_react_.isValidElement)(component) ? (0,external_react_.cloneElement)(component) : component;
                })(),
                external_react_default().createElement("div", { className: MenuDialog_MenuDialog_module['EndSlot'] },
                    item.endSlot && typeof item.endSlot === 'string' && external_react_default().createElement(Text/* Text */.EY, null, item.endSlot),
                    item.endSlot && typeof item.endSlot !== 'string' && item.endSlot)));
            return item.tooltip ? (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: item.tooltip, showAfterMs: item.tooltipShowAfterMs, key: item.key || item.label }, itemContent)) : (itemContent);
        }))));
}

;// ../noodl-core-ui/src/components/popups/MenuDialog/index.ts



/***/ }),

/***/ 23715:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgBorderAll = function SvgBorderAll(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M24.1928 5.74249H6.08057C5.80442 5.74249 5.58057 5.96635 5.58057 6.24249V24.3547C5.58057 24.6309 5.80442 24.8547 6.08057 24.8547H24.1928C24.4689 24.8547 24.6928 24.6309 24.6928 24.3547V6.24249C24.6928 5.96635 24.4689 5.74249 24.1928 5.74249ZM6.08057 4.24249C4.976 4.24249 4.08057 5.13792 4.08057 6.24249V24.3547C4.08057 25.4593 4.976 26.3547 6.08057 26.3547H24.1928C25.2974 26.3547 26.1928 25.4593 26.1928 24.3547V6.24249C26.1928 5.13792 25.2974 4.24249 24.1928 4.24249H6.08057Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgBorderAll);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "0d24ffab6c240dc60acf8138b80061ee.svg");

/***/ }),

/***/ 23776:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  VS: () => (/* binding */ CommentsBackground),
  KK: () => (/* binding */ CommentFillStyle),
  _6: () => (/* binding */ CommentsForeground)
});

// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
;// ./src/editor/src/views/CommentLayer/CommentBackground.tsx


function CommentBackground(props) {
    const transform = `translate(${props.x}px, ${props.y}px)`;
    const colorStyle = { backgroundColor: undefined, borderColor: undefined };
    const isFilled = props.fill === true || props.fill === CommentFillStyle.Filled || props.fill === CommentFillStyle.Transparent;
    let fillType;
    if (props.fill === true || props.fill === CommentFillStyle.Transparent) {
        fillType = CommentFillStyle.Transparent;
    }
    else {
        fillType = props.fill || CommentFillStyle.Outline;
    }
    if (isFilled) {
        //extract the hex value from the variable and append opacity
        const variableName = props.color.base.substring(4, props.color.base.length - 1);
        const color = getComputedStyle(document.documentElement).getPropertyValue(variableName).trim();
        const opacity = fillType === CommentFillStyle.Transparent ? Math.floor(props.color.darkerOpacity * 255).toString(16) : 'ff';
        colorStyle.backgroundColor = `${color}${opacity}`;
    }
    else {
        colorStyle.borderColor = props.color.base;
    }
    return (external_react_default().createElement("div", { className: `comment-layer-comment background
      ${props.selected ? 'selected' : ''}
      ${fillType}
      ${props.largeFont ? 'large-font' : ''}
      ${props.annotation ? 'has-annotation ' + props.annotation : ''}`, style: {
            ...colorStyle,
            width: props.width,
            height: props.height,
            transform
        } }, !props.showTextArea ? external_react_default().createElement("div", { className: "content" }, props.text) : null));
}
const MemoizedCommentBackground = external_react_default().memo(CommentBackground);


;// external "react-rnd"
const external_react_rnd_namespaceObject = require("react-rnd");
// EXTERNAL MODULE: ./src/editor/src/constants/FeedbackType.ts
var FeedbackType = __webpack_require__(30187);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/inputs/IconButton/index.ts + 2 modules
var IconButton = __webpack_require__(28208);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/BaseDialog/index.ts + 3 modules
var BaseDialog = __webpack_require__(65762);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/popups/ContextMenu/index.ts + 2 modules
var ContextMenu = __webpack_require__(93739);
// EXTERNAL MODULE: ./src/editor/src/views/popuplayer.js
var popuplayer = __webpack_require__(45653);
var popuplayer_default = /*#__PURE__*/__webpack_require__.n(popuplayer);
;// ./src/editor/src/views/CommentLayer/CommentForeground.tsx









function getColor(props) {
    const color = props.colors[props.color];
    return color ? color : props.colors[Object.keys(props.colors)[0]];
}
function setTextAreaToContentHeight(textArea) {
    //figure out max height by looking at parent. This will be the correct size with padding
    const maxHeight = textArea.parentNode.clientHeight;
    textArea.style.height = '';
    const newHeight = Math.min(maxHeight, textArea.scrollHeight);
    textArea.style.height = newHeight + 'px';
}
function useTextAreaInitOnMount() {
    return (0,external_react_.useCallback)((textArea) => {
        if (textArea === null) {
            return;
        }
        //auto focus
        textArea.focus();
        //and move cursor to the end
        textArea.setSelectionRange(textArea.value.length, textArea.value.length);
        //set the textarea height
        setTextAreaToContentHeight(textArea);
        //and scroll to end
        textArea.scrollTop = textArea.scrollHeight;
    }, []);
}
function CommentTextArea(props) {
    const textAreaCb = useTextAreaInitOnMount();
    const [text, setText] = (0,external_react_.useState)(props.text);
    const [textDirty, setTextDirty] = (0,external_react_.useState)(false);
    const textRef = (0,external_react_.useRef)(props.text);
    //commit the text to the comment model when this unmounts, and the text has changed
    //onBlur might not always get called for some reason, so let's rely on unmount instead (might be that onBlur doesn't happen if this component unmounts at the same time as the blur event is sent)
    //we need to save the text in a ref, since we don't want the effect to commit to the model every time the text updates, but we need the latest
    //text on unmount
    //This is all to make undo work like expected, so you don't undo one letter at a time
    (0,external_react_.useEffect)(() => {
        return () => {
            if (textDirty) {
                props.updateComment({ text: textRef.current }, { commit: true, label: 'change comment text' });
            }
        };
    }, [textDirty]);
    return (external_react_default().createElement("textarea", { rows: 1, onBlur: (e) => {
            props.setShowTextArea(false);
        }, spellCheck: false, onMouseDown: (e) => e.stopPropagation(), ref: textAreaCb, value: text, onChange: (e) => {
            setTextDirty(true);
            setTextAreaToContentHeight(e.target);
            setText(e.target.value);
            textRef.current = e.target.value;
        } }));
}
function CommentForeground(props) {
    const [dragStartFired, setDragStartFired] = (0,external_react_.useState)(false);
    const [hover, setHover] = (0,external_react_.useState)(false);
    const ref = (0,external_react_.useRef)(null);
    (0,external_react_.useEffect)(() => {
        if (!props.annotation) {
            return;
        }
        if (hover) {
            const text = props.annotation[0].toUpperCase() + props.annotation.slice(1);
            popuplayer_default().instance.showTooltip({
                attachTo: $(ref.current),
                position: 'bottom',
                content: text
            });
        }
        else {
            popuplayer_default().instance.hideTooltip();
        }
    }, [hover, props.annotation]);
    return (external_react_default().createElement(external_react_rnd_namespaceObject.Rnd, { enableResizing: !props.readOnly, disableDragging: props.readOnly, className: `comment-layer-comment foreground ${props.largeFont ? 'large-font' : ''}`, dragHandleClassName: "comment-drag-area", scale: props.scale, size: { width: props.width, height: props.height }, position: { x: props.x, y: props.y }, onDragStart: () => setDragStartFired(false), onDragStop: (e, d) => {
            //note: this get's called on mouse up, even if position hasn't changed
            props.updateComment({ x: d.x, y: d.y }, { commit: true, label: 'change comment position' });
            props.onResizeStop();
        }, onDrag: (e, d) => {
            if (!dragStartFired) {
                props.onResizeStart();
                setDragStartFired(true);
            }
            props.updateComment({ x: d.x, y: d.y });
            props.setActive(false);
        }, minWidth: 100, minHeight: 30, onResizeStart: props.onResizeStart, onResizeStop: (e, direction, ref, delta, pos) => {
            props.updateComment({ x: pos.x, y: pos.y }, { commit: true });
            props.updateComment({ width: Number(ref.style.width.slice(0, -2)), height: Number(ref.style.height.slice(0, -2)) }, { commit: true, label: 'change comment size' });
            props.onResizeStop();
        }, onResize: (e, direction, ref, delta, pos) => {
            props.updateComment({
                x: pos.x,
                y: pos.y,
                width: Number(ref.style.width.slice(0, -2)),
                height: Number(ref.style.height.slice(0, -2))
            });
        } },
        external_react_default().createElement("div", { ref: ref, onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false), className: "comment-drag-area", tabIndex: 1, onBlur: (event) => {
                // deselect the comment if the blir event isn't bubbling up from a child
                // or if a context menu is open
                if (event.currentTarget.contains(event.relatedTarget))
                    return;
                if (props.isContextOpen)
                    return;
                props.setActive(false);
            }, onClick: (e) => {
                if (props.readOnly) {
                    return;
                }
                if (e.shiftKey) {
                    props.toggleSelection();
                }
                else {
                    if (props.active) {
                        props.setShowTextArea(true);
                    }
                    else {
                        props.setActive(true);
                    }
                }
            } },
            props.active ? external_react_default().createElement(CommentControls, { ...props }) : null,
            props.showTextArea ? external_react_default().createElement(CommentTextArea, { ...props }) : null)));
}
function CommentControls(props) {
    const [showColorPicker, setShowColorPicker] = (0,external_react_.useState)(false);
    const colorPickerRef = (0,external_react_.useRef)(null);
    const color = getColor(props);
    return (external_react_default().createElement("div", { className: "comment-controls", onClick: (e) => e.stopPropagation(), onMouseDown: (e) => e.stopPropagation() },
        external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { hasArrow: true, isVisible: showColorPicker, background: BaseDialog/* DialogBackground */.$j.Bg3, triggerRef: colorPickerRef, onClose: () => {
                setShowColorPicker(false);
                props.setIsContextOpen(false);
            }, isLockingScroll: true },
            external_react_default().createElement(ColorPicker, { colors: props.colors, color: props.color, onColorSelected: (c) => props.updateComment({ color: c }, { commit: true, label: 'change comment color' }) })),
        external_react_default().createElement("div", { className: "comment-color-picker-icon-parent", ref: colorPickerRef, onFocus: () => {
                setShowColorPicker(true);
                props.setIsContextOpen(true);
            }, tabIndex: 3 },
            external_react_default().createElement("div", { className: "comment-color-picker-icon", style: { backgroundColor: color.base } })),
        external_react_default().createElement(ContextMenu/* ContextMenu */.t, { icon: Icon/* IconName */.$M.Square, size: Icon/* IconSize */.lK.Default, buttonSize: IconButton/* IconButtonSize */.Tp.Bigger, onOpen: () => props.setIsContextOpen(true), onClose: () => props.setIsContextOpen(false), menuItems: [
                {
                    label: 'Filled',
                    icon: Icon/* IconName */.$M.SquareFilled,
                    isDisabled: props.fill === CommentFillStyle.Filled,
                    dontCloseMenuOnClick: true,
                    onClick: (e) => {
                        props.updateComment({
                            fill: CommentFillStyle.Filled
                        }, { commit: true, label: 'change comment fill' });
                    }
                },
                {
                    label: 'Transparent',
                    icon: Icon/* IconName */.$M.SquareHalf,
                    isDisabled: props.fill === CommentFillStyle.Transparent,
                    dontCloseMenuOnClick: true,
                    onClick: () => props.updateComment({
                        fill: CommentFillStyle.Transparent
                    }, { commit: true, label: 'change comment fill' })
                },
                {
                    label: 'Outline',
                    icon: Icon/* IconName */.$M.Square,
                    isDisabled: props.fill === CommentFillStyle.Outline,
                    dontCloseMenuOnClick: true,
                    onClick: () => props.updateComment({
                        fill: CommentFillStyle.Outline
                    }, { commit: true, label: 'change comment fill' })
                }
            ] }),
        external_react_default().createElement(IconButton/* IconButton */.K0, { icon: Icon/* IconName */.$M.TextInBox, buttonSize: IconButton/* IconButtonSize */.Tp.Bigger, onClick: () => props.updateComment({ largeFont: props.largeFont ? false : true }, { commit: true, label: 'change comment font' }) }),
        external_react_default().createElement(IconButton/* IconButton */.K0, { icon: Icon/* IconName */.$M.Trash, iconVariant: FeedbackType/* FeedbackType */.M.Danger, buttonSize: IconButton/* IconButtonSize */.Tp.Bigger, onClick: props.removeComment })));
}
function ColorPicker(props) {
    return (external_react_default().createElement("div", { className: "comment-color-picker", tabIndex: 2, onBlur: props.onBlur }, Object.keys(props.colors).map((colorName) => {
        const color = props.colors[colorName];
        return (external_react_default().createElement("div", { key: colorName, className: props.color === colorName ? 'active' : undefined, style: { backgroundColor: color.base }, onClick: (e) => {
                e.stopPropagation();
                props.onColorSelected(colorName);
            } }));
    })));
}


// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!./src/editor/src/views/CommentLayer/CommentLayer.css
var CommentLayer = __webpack_require__(99682);
;// ./src/editor/src/views/CommentLayer/CommentLayer.css

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(CommentLayer/* default */.A, options);




       /* harmony default export */ const CommentLayer_CommentLayer = (CommentLayer/* default */.A && CommentLayer/* default */.A.locals ? CommentLayer/* default */.A.locals : undefined);

;// ./src/editor/src/views/CommentLayer/CommentLayerView.tsx




var CommentFillStyle;
(function (CommentFillStyle) {
    CommentFillStyle["Filled"] = "fill";
    CommentFillStyle["Transparent"] = "transparent";
    CommentFillStyle["Outline"] = "no-fill";
})(CommentFillStyle || (CommentFillStyle = {}));
const colors = {
    logic: { base: 'var(--theme-color-node-logic-3)', darkerOpacity: 0.3 },
    script: { base: 'var(--theme-color-node-custom-3)', darkerOpacity: 0.3 },
    data: { base: 'var(--theme-color-node-data-3)', darkerOpacity: 0.3 },
    visual: { base: 'var(--theme-color-node-visual-3)', darkerOpacity: 0.3 },
    component: {
        base: 'var(--theme-color-node-component-3)',
        darkerOpacity: 0.3
    },
    success: {
        base: 'var(--theme-color-success-dark)',
        darkerOpacity: 0.3
    },
    comment: {
        base: 'var(--theme-color-secondary-highlight)',
        darkerOpacity: 0.3
    },
    danger: {
        base: 'var(--theme-color-danger-dark)',
        darkerOpacity: 0.3
    },
    notice: {
        base: 'var(--theme-color-notice-dark)',
        darkerOpacity: 0.3
    }
};
const defaultColorName = Object.keys(colors)[0];
function CommentsForeground(props) {
    if (props.scale === undefined) {
        //react-dnd requires "scale" to be set when this mountes. It does special setup work on mount to figure out the realtion to any parent transform
        //and adding scale after mount breaks react-dnd
        return null;
    }
    return (external_react_default().createElement("div", { className: "comment-layer-comments" }, props.comments.map((c, i) => {
        const active = props.activeCommentId === c.id;
        const selected = props.selectedIds.includes(c.id);
        const colorName = c.color && colors[c.color] ? c.color : defaultColorName;
        return (external_react_default().createElement(CommentForeground, { key: c.id, ...c, readOnly: props.readOnly, scale: props.scale, color: colorName, colors: colors, updateComment: (changedProps, args) => props.updateComment(c.id, changedProps, args), onResizeStart: props.onResizeStart, onResizeStop: props.onResizeStop, removeComment: () => props.removeComment(c.id), selected: selected, active: active, showTextArea: active && props.showTextArea, toggleSelection: () => props.toggleSelection(c.id), setActive: (active) => {
                if (active) {
                    props.setActiveState(c.id, true);
                }
                else {
                    props.setActiveState(c.id, false);
                }
            }, setShowTextArea: props.setShowTextArea, isContextOpen: props.isContextOpen, setIsContextOpen: props.setIsContextOpen }));
    })));
}
function CommentsBackground(props) {
    return (external_react_default().createElement("div", { className: "comment-layer-comments" }, props.comments.map((c, i) => {
        const colorName = c.color && colors[c.color] ? c.color : defaultColorName;
        const active = props.activeCommentId === c.id;
        const selected = props.selectedIds.includes(c.id);
        return (external_react_default().createElement(MemoizedCommentBackground, { key: c.id, ...c, color: colors[colorName], selected: selected, showTextArea: active && props.showTextArea }));
    })));
}



/***/ }),

/***/ 23983:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgUi = function SvgUi(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.56282 5.25001C3.56282 5.14654 3.6467 5.06267 3.75016 5.06267H20.2502C20.3536 5.06267 20.4375 5.14654 20.4375 5.25001V9.18732H9.74967H3.56282V5.25001ZM2.4375 9.74998V5.25001C2.4375 4.52505 3.0252 3.93735 3.75016 3.93735H20.2502C20.9751 3.93735 21.5628 4.52505 21.5628 5.25001V9.74998V18.75C21.5628 19.475 20.9751 20.0627 20.2502 20.0627H3.75016C3.0252 20.0627 2.4375 19.475 2.4375 18.75V9.74998ZM20.4375 10.3126H10.3123V18.9373H20.2502C20.3536 18.9373 20.4375 18.8535 20.4375 18.75V10.3126ZM9.18701 18.9373H3.75016C3.6467 18.9373 3.56282 18.8535 3.56282 18.75V10.3126H9.18701V18.9373Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgUi);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "9d5d002cdf17c2ca5c2e29b8be7c063b.svg");

/***/ }),

/***/ 24004:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_pages_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(48418);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_pages_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_pages_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_pages_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_pages_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 24039:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.BudgetApprovalDialog-module__BudgetApprovalDialog--Ofw9O{display:flex;flex-direction:column;align-items:center;gap:24px;padding:32px 24px 24px;max-width:450px}.BudgetApprovalDialog-module__Icon--PcH68{display:flex;align-items:center;justify-content:center;width:64px;height:64px;border-radius:50%;background:var(--theme-color-primary);color:var(--theme-color-bg-1);opacity:.9}.BudgetApprovalDialog-module__Content--OkeTi{display:flex;flex-direction:column;gap:16px;width:100%;text-align:center}.BudgetApprovalDialog-module__Content--OkeTi h3{margin:0;font-size:18px;font-weight:600;color:var(--theme-color-fg-highlight)}.BudgetApprovalDialog-module__Content--OkeTi strong{color:var(--theme-color-fg-highlight);font-weight:600}.BudgetApprovalDialog-module__BudgetBar--FkvJH{margin:12px 0;width:100%}.BudgetApprovalDialog-module__BudgetBar__Track--iD5KC{position:relative;height:8px;background:var(--theme-color-bg-3);border-radius:4px;overflow:hidden}.BudgetApprovalDialog-module__BudgetBar__Spent--LHWGI{position:absolute;top:0;left:0;height:100%;background:var(--theme-color-primary);border-radius:4px;transition:width .3s ease}.BudgetApprovalDialog-module__BudgetBar__Pending--kMcmB{position:absolute;top:0;height:100%;background:var(--theme-color-warning);border-radius:4px;opacity:.6;transition:left .3s ease,width .3s ease}.BudgetApprovalDialog-module__BudgetLabels--VIwdD{display:flex;justify-content:space-between;align-items:center;font-size:12px;color:var(--theme-color-fg-muted)}.BudgetApprovalDialog-module__BudgetLabels--VIwdD .BudgetApprovalDialog-module__Current--Jz18d{color:var(--theme-color-primary);font-weight:600}.BudgetApprovalDialog-module__Actions--mU97r{display:flex;gap:12px;width:100%;justify-content:center}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/migration/BudgetApprovalDialog.module.scss"],"names":[],"mappings":"AAAA,0DACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,QAAA,CACA,sBAAA,CACA,eAAA,CAGF,0CACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,qCAAA,CACA,6BAAA,CACA,UAAA,CAGF,6CACE,YAAA,CACA,qBAAA,CACA,QAAA,CACA,UAAA,CACA,iBAAA,CAEA,gDACE,QAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CAGF,oDACE,qCAAA,CACA,eAAA,CAIJ,+CACE,aAAA,CACA,UAAA,CAGF,sDACE,iBAAA,CACA,UAAA,CACA,kCAAA,CACA,iBAAA,CACA,eAAA,CAGF,sDACE,iBAAA,CACA,KAAA,CACA,MAAA,CACA,WAAA,CACA,qCAAA,CACA,iBAAA,CACA,yBAAA,CAGF,wDACE,iBAAA,CACA,KAAA,CACA,WAAA,CACA,qCAAA,CACA,iBAAA,CACA,UAAA,CACA,uCAAA,CAGF,kDACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,cAAA,CACA,iCAAA,CAEA,+FACE,gCAAA,CACA,eAAA,CAIJ,6CACE,YAAA,CACA,QAAA,CACA,UAAA,CACA,sBAAA","sourcesContent":[".BudgetApprovalDialog {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 24px;\n  padding: 32px 24px 24px;\n  max-width: 450px;\n}\n\n.Icon {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 64px;\n  height: 64px;\n  border-radius: 50%;\n  background: var(--theme-color-primary);\n  color: var(--theme-color-bg-1);\n  opacity: 0.9;\n}\n\n.Content {\n  display: flex;\n  flex-direction: column;\n  gap: 16px;\n  width: 100%;\n  text-align: center;\n\n  h3 {\n    margin: 0;\n    font-size: 18px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n  }\n\n  strong {\n    color: var(--theme-color-fg-highlight);\n    font-weight: 600;\n  }\n}\n\n.BudgetBar {\n  margin: 12px 0;\n  width: 100%;\n}\n\n.BudgetBar__Track {\n  position: relative;\n  height: 8px;\n  background: var(--theme-color-bg-3);\n  border-radius: 4px;\n  overflow: hidden;\n}\n\n.BudgetBar__Spent {\n  position: absolute;\n  top: 0;\n  left: 0;\n  height: 100%;\n  background: var(--theme-color-primary);\n  border-radius: 4px;\n  transition: width 0.3s ease;\n}\n\n.BudgetBar__Pending {\n  position: absolute;\n  top: 0;\n  height: 100%;\n  background: var(--theme-color-warning);\n  border-radius: 4px;\n  opacity: 0.6;\n  transition: left 0.3s ease, width 0.3s ease;\n}\n\n.BudgetLabels {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  font-size: 12px;\n  color: var(--theme-color-fg-muted);\n\n  .Current {\n    color: var(--theme-color-primary);\n    font-weight: 600;\n  }\n}\n\n.Actions {\n  display: flex;\n  gap: 12px;\n  width: 100%;\n  justify-content: center;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"BudgetApprovalDialog": `BudgetApprovalDialog-module__BudgetApprovalDialog--Ofw9O`,
	"Icon": `BudgetApprovalDialog-module__Icon--PcH68`,
	"Content": `BudgetApprovalDialog-module__Content--OkeTi`,
	"BudgetBar": `BudgetApprovalDialog-module__BudgetBar--FkvJH`,
	"BudgetBar__Track": `BudgetApprovalDialog-module__BudgetBar__Track--iD5KC`,
	"BudgetBar__Spent": `BudgetApprovalDialog-module__BudgetBar__Spent--LHWGI`,
	"BudgetBar__Pending": `BudgetApprovalDialog-module__BudgetBar__Pending--kMcmB`,
	"BudgetLabels": `BudgetApprovalDialog-module__BudgetLabels--VIwdD`,
	"Current": `BudgetApprovalDialog-module__Current--Jz18d`,
	"Actions": `BudgetApprovalDialog-module__Actions--mU97r`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 24070:
/***/ ((module) => {

// Module
var code = "<div class=\"sidebar-panel\"> <div data-template=\"item\" class=\"component-ports-item sidebar-panel-item\"> <div class=\"show-on-edit name-edit-container\"> <input type=\"string\" class=\"sidebar-panel-dark-input name-edit\" data-val=\"label\"> </div> <span class=\"drop-target drag-handle hide-on-edit component-ports-label\" data-text=\"label\" data-bind=\"watch\" data-click=\"onRenameClicked\"></span> <div class=\"sidebar-panel-edit-bar hide-on-edit\"> <button type=\"button\" class=\"sidebar-panel-edit-button\" data-click=\"onRenameClicked\"><i class=\"fa fa-pencil-square-o\"></i></button> <button type=\"button\" class=\"sidebar-panel-edit-button\" data-click=\"onDeleteClicked\"><i class=\"fa fa-trash-o\"></i></button> </div> <div class=\"drop-indicator\" style=\"display:none;position:absolute;width:100%;height:3px;background-color:#6c6c6c;pointer-events:none\"/> </div> <div data-template=\"group\" class=\"component-ports-group-item sidebar-panel-item\"> <div style=\"position:relative;top:15px;height:35px\"> <div class=\"show-on-edit name-edit-container\"> <input type=\"string\" class=\"sidebar-panel-dark-input name-edit\" data-val=\"label\"> </div> <span class=\"drop-target drag-handle hide-on-edit component-ports-group-label\" data-text=\"label\" data-bind=\"watch\" data-click=\"onRenameClicked\"></span> <di class=\"sidebar-panel-edit-bar hide-on-edit\"> <button type=\"button\" class=\"component-ports-group-button sidebar-panel-edit-button\" data-click=\"onRenameGroupClicked\"><i class=\"fa fa-pencil-square-o\"></i></button> <button type=\"button\" class=\"component-ports-group-button sidebar-panel-edit-button\" data-click=\"onDeleteGroupClicked\"><i class=\"fa fa-trash-o\"></i></button> </di> </div> <div class=\"drop-indicator\" style=\"display:none;position:absolute;top:0;width:100%;height:3px;background-color:#6c6c6c;pointer-events:none\"/> </div> <div class=\"sidebar-panel-header\"> <span class=\"sidebar-panel-header-label\" data-text=\"title\"></span> </div> <div style=\"overflow-y:auto\"> <div class=\"ports\"> </div> </div> <div class=\"sidebar-panel-footer-placeholder\"> </div> <div class=\"sidebar-panel-footer\"> <button type=\"button\" class=\"sidebar-panel-footer-button\" data-click=\"onAddPortClicked\"><i class=\"fa fa-plus\"></i><span>Port</span></button> <button type=\"button\" class=\"add-group-button sidebar-panel-footer-button\" data-click=\"onAddGroupClicked\"><i class=\"fa fa-plus\"></i><span>Group</span></button> </div> </div> ";
// Exports
module.exports = code;

/***/ }),

/***/ 24445:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* unused harmony export ReactComponent */
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5, _path6, _path7, _path8, _path9, _path0, _path1, _path10, _path11, _path12;
var _excluded = (/* unused pure expression or super */ null && (["title", "titleId"]));
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgAiAssistantNodegraphOuter = function SvgAiAssistantNodegraphOuter(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/React.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/React.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/React.createElement("path", {
    d: "M10.9512 3.22576C11.5593 3.22576 12.0522 2.72751 12.0522 2.11288C12.0522 1.49825 11.5593 1 10.9512 1C10.3432 1 9.85022 1.49825 9.85022 2.11288C9.85022 2.72751 10.3432 3.22576 10.9512 3.22576Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/React.createElement("path", {
    d: "M6.68969 4.40009C7.22049 4.40009 7.65079 3.96515 7.65079 3.42863C7.65079 2.8921 7.22049 2.45716 6.68969 2.45716C6.15889 2.45716 5.72859 2.8921 5.72859 3.42863C5.72859 3.96515 6.15889 4.40009 6.68969 4.40009Z",
    fill: "#B8B8B8"
  })), _path3 || (_path3 = /*#__PURE__*/React.createElement("path", {
    d: "M3.82576 6.73112C4.26115 6.73112 4.61411 6.37436 4.61411 5.93428C4.61411 5.49419 4.26115 5.13743 3.82576 5.13743C3.39037 5.13743 3.03742 5.49419 3.03742 5.93428C3.03742 6.37436 3.39037 6.73112 3.82576 6.73112Z",
    fill: "#B8B8B8"
  })), _path4 || (_path4 = /*#__PURE__*/React.createElement("path", {
    d: "M2.11012 9.34882C2.44573 9.34882 2.7178 9.07382 2.7178 8.73459C2.7178 8.39535 2.44573 8.12035 2.11012 8.12035C1.77451 8.12035 1.50244 8.39535 1.50244 8.73459C1.50244 9.07382 1.77451 9.34882 2.11012 9.34882Z",
    fill: "#B8B8B8"
  })), _path5 || (_path5 = /*#__PURE__*/React.createElement("path", {
    d: "M1.46048 12.4432C1.71479 12.4432 1.92095 12.2348 1.92095 11.9778C1.92095 11.7207 1.71479 11.5123 1.46048 11.5123C1.20616 11.5123 1 11.7207 1 11.9778C1 12.2348 1.20616 12.4432 1.46048 12.4432Z",
    fill: "#B8B8B8"
  })), _path6 || (_path6 = /*#__PURE__*/React.createElement("path", {
    d: "M1.78458 15.2657C1.96431 15.2657 2.11001 15.1185 2.11001 14.9368C2.11001 14.7551 1.96431 14.6079 1.78458 14.6079C1.60485 14.6079 1.45914 14.7551 1.45914 14.9368C1.45914 15.1185 1.60485 15.2657 1.78458 15.2657Z",
    fill: "#B8B8B8"
  })), _path7 || (_path7 = /*#__PURE__*/React.createElement("path", {
    d: "M13.0506 23C13.6587 23 14.1516 22.5017 14.1516 21.8871C14.1516 21.2725 13.6587 20.7742 13.0506 20.7742C12.4426 20.7742 11.9496 21.2725 11.9496 21.8871C11.9496 22.5017 12.4426 23 13.0506 23Z",
    fill: "#B8B8B8"
  })), _path8 || (_path8 = /*#__PURE__*/React.createElement("path", {
    d: "M17.3074 21.5417C17.8382 21.5417 18.2685 21.1068 18.2685 20.5702C18.2685 20.0337 17.8382 19.5988 17.3074 19.5988C16.7766 19.5988 16.3463 20.0337 16.3463 20.5702C16.3463 21.1068 16.7766 21.5417 17.3074 21.5417Z",
    fill: "#B8B8B8"
  })), _path9 || (_path9 = /*#__PURE__*/React.createElement("path", {
    d: "M20.1722 18.8626C20.6076 18.8626 20.9605 18.5058 20.9605 18.0657C20.9605 17.6256 20.6076 17.2689 20.1722 17.2689C19.7368 17.2689 19.3839 17.6256 19.3839 18.0657C19.3839 18.5058 19.7368 18.8626 20.1722 18.8626Z",
    fill: "#B8B8B8"
  })), _path0 || (_path0 = /*#__PURE__*/React.createElement("path", {
    d: "M21.8873 15.8798C22.2229 15.8798 22.4949 15.6048 22.4949 15.2656C22.4949 14.9264 22.2229 14.6514 21.8873 14.6514C21.5516 14.6514 21.2796 14.9264 21.2796 15.2656C21.2796 15.6048 21.5516 15.8798 21.8873 15.8798Z",
    fill: "#B8B8B8"
  })), _path1 || (_path1 = /*#__PURE__*/React.createElement("path", {
    d: "M22.5395 12.4879C22.7938 12.4879 23 12.2795 23 12.0224C23 11.7654 22.7938 11.557 22.5395 11.557C22.2852 11.557 22.079 11.7654 22.079 12.0224C22.079 12.2795 22.2852 12.4879 22.5395 12.4879Z",
    fill: "#B8B8B8"
  })), _path10 || (_path10 = /*#__PURE__*/React.createElement("path", {
    d: "M22.2142 9.39194C22.3939 9.39194 22.5396 9.24467 22.5396 9.06299C22.5396 8.88132 22.3939 8.73405 22.2142 8.73405C22.0344 8.73405 21.8887 8.88132 21.8887 9.06299C21.8887 9.24467 22.0344 9.39194 22.2142 9.39194Z",
    fill: "#B8B8B8"
  })), _path11 || (_path11 = /*#__PURE__*/React.createElement("path", {
    d: "M21.1878 6.79557C21.2847 6.79557 21.3633 6.71613 21.3633 6.61815C21.3633 6.52016 21.2847 6.44073 21.1878 6.44073C21.0908 6.44073 21.0123 6.52016 21.0123 6.61815C21.0123 6.71613 21.0908 6.79557 21.1878 6.79557Z",
    fill: "#B8B8B8"
  })), _path12 || (_path12 = /*#__PURE__*/React.createElement("path", {
    d: "M2.81427 17.6774C2.91122 17.6774 2.98981 17.5979 2.98981 17.5C2.98981 17.402 2.91122 17.3225 2.81427 17.3225C2.71732 17.3225 2.63873 17.402 2.63873 17.5C2.63873 17.5979 2.71732 17.6774 2.81427 17.6774Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(/* unused pure expression or super */ null && (forwardRef(SvgAiAssistantNodegraphOuter)));

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "00871f410b0671a26490d825705b1179.svg");

/***/ }),

/***/ 24786:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPencil = function SvgPencil(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.63135 21.3983H8.82135V21.3883C9.02135 21.3883 9.21135 21.3483 9.39135 21.2783C9.57135 21.2083 9.74135 21.0983 9.88135 20.9583L18.6285 12.2111C18.6417 12.1997 18.6545 12.1877 18.667 12.1752C18.6796 12.1627 18.6915 12.1498 18.703 12.1367L21.1313 9.70833C21.2813 9.56833 21.3913 9.40833 21.4613 9.22833C21.5413 9.04833 21.5813 8.84833 21.5813 8.64833C21.5813 8.44833 21.5413 8.24833 21.4613 8.06833C21.3813 7.87833 21.2713 7.71833 21.1313 7.57833L16.9513 3.39833C16.8113 3.25833 16.6513 3.14833 16.4613 3.06833C16.0913 2.91833 15.6813 2.90833 15.3013 3.06833C15.1213 3.14833 14.9513 3.25833 14.8213 3.39833L3.57135 14.6483C3.42135 14.7883 3.31135 14.9583 3.24135 15.1383C3.17135 15.3183 3.13135 15.5183 3.13135 15.7083V19.8983C3.13135 20.2883 3.29135 20.6783 3.57135 20.9583C3.85135 21.2383 4.23135 21.3983 4.63135 21.3983ZM18.1361 10.5836L20.0713 8.64833L15.8813 4.45833L13.9461 6.39358L18.1361 10.5836ZM12.8854 7.45424L4.63135 15.7083V19.8983H8.82135L17.0754 11.6442L12.8854 7.45424Z",
    fill: "#b8b8b8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPencil);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "3144c4668626e2d874fd928737227f58.svg");

/***/ }),

/***/ 25044:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.AddColumnForm-module__Root--meI05{padding:8px 12px;background:var(--theme-color-bg-2);border-top:1px solid var(--theme-color-border-default)}.AddColumnForm-module__Row--GvXxE{display:grid;grid-template-columns:2fr 1.2fr .8fr 1.5fr auto;gap:8px;align-items:center}.AddColumnForm-module__Field--Bv5Zw{display:flex;align-items:center}.AddColumnForm-module__FieldSmall--MVF0I{display:flex;align-items:center;justify-content:center}.AddColumnForm-module__Actions--qUbdN{display:flex;align-items:center;gap:4px}.AddColumnForm-module__Input--JM4u0{width:100%;padding:6px 8px;background:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:3px;color:var(--theme-color-fg-default);font-size:12px}.AddColumnForm-module__Input--JM4u0::placeholder{color:var(--theme-color-fg-default-shy)}.AddColumnForm-module__Input--JM4u0:focus{outline:none;border-color:var(--theme-color-primary)}.AddColumnForm-module__Select--CVZJf{width:100%;padding:6px 8px;background:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:3px;color:var(--theme-color-fg-default);font-size:12px;cursor:pointer}.AddColumnForm-module__Select--CVZJf:focus{outline:none;border-color:var(--theme-color-primary)}.AddColumnForm-module__Error--M2EXW{display:flex;align-items:center;gap:8px;padding:8px 0 0 0;color:var(--theme-color-danger);font-size:12px}.AddColumnForm-module__RenameWrapper--R_xOX{position:relative}.AddColumnForm-module__RenameInput--jnaG3{width:100%;padding:4px 6px;background:var(--theme-color-bg-3);border:1px solid var(--theme-color-primary);border-radius:2px;color:var(--theme-color-fg-default);font-size:12px}.AddColumnForm-module__RenameInput--jnaG3:focus{outline:none}.AddColumnForm-module__RenameInput--jnaG3:disabled{opacity:.6}.AddColumnForm-module__RenameError--KXldq{position:absolute;top:100%;left:0;padding:4px 6px;background:var(--theme-color-danger);color:var(--theme-color-fg-default);font-size:10px;border-radius:2px;white-space:nowrap;z-index:10}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/schemamanager/AddColumnForm.module.scss"],"names":[],"mappings":"AAIA,mCACE,gBAAA,CACA,kCAAA,CACA,sDAAA,CAGF,kCACE,YAAA,CACA,+CAAA,CACA,OAAA,CACA,kBAAA,CAGF,oCACE,YAAA,CACA,kBAAA,CAGF,yCACE,YAAA,CACA,kBAAA,CACA,sBAAA,CAGF,sCACE,YAAA,CACA,kBAAA,CACA,OAAA,CAGF,oCACE,UAAA,CACA,eAAA,CACA,kCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CAEA,iDACE,uCAAA,CAGF,0CACE,YAAA,CACA,uCAAA,CAIJ,qCACE,UAAA,CACA,eAAA,CACA,kCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,cAAA,CAEA,2CACE,YAAA,CACA,uCAAA,CAIJ,oCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,iBAAA,CACA,+BAAA,CACA,cAAA,CAIF,4CACE,iBAAA,CAGF,0CACE,UAAA,CACA,eAAA,CACA,kCAAA,CACA,2CAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CAEA,gDACE,YAAA,CAGF,mDACE,UAAA,CAIJ,0CACE,iBAAA,CACA,QAAA,CACA,MAAA,CACA,eAAA,CACA,oCAAA,CACA,mCAAA,CACA,cAAA,CACA,iBAAA,CACA,kBAAA,CACA,UAAA","sourcesContent":["/**\n * AddColumnForm styles\n */\n\n.Root {\n  padding: 8px 12px;\n  background: var(--theme-color-bg-2);\n  border-top: 1px solid var(--theme-color-border-default);\n}\n\n.Row {\n  display: grid;\n  grid-template-columns: 2fr 1.2fr 0.8fr 1.5fr auto;\n  gap: 8px;\n  align-items: center;\n}\n\n.Field {\n  display: flex;\n  align-items: center;\n}\n\n.FieldSmall {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.Actions {\n  display: flex;\n  align-items: center;\n  gap: 4px;\n}\n\n.Input {\n  width: 100%;\n  padding: 6px 8px;\n  background: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 3px;\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n\n  &::placeholder {\n    color: var(--theme-color-fg-default-shy);\n  }\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.Select {\n  width: 100%;\n  padding: 6px 8px;\n  background: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 3px;\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n  cursor: pointer;\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.Error {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 8px 0 0 0;\n  color: var(--theme-color-danger);\n  font-size: 12px;\n}\n\n// Inline column rename styles\n.RenameWrapper {\n  position: relative;\n}\n\n.RenameInput {\n  width: 100%;\n  padding: 4px 6px;\n  background: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-primary);\n  border-radius: 2px;\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n\n  &:focus {\n    outline: none;\n  }\n\n  &:disabled {\n    opacity: 0.6;\n  }\n}\n\n.RenameError {\n  position: absolute;\n  top: 100%;\n  left: 0;\n  padding: 4px 6px;\n  background: var(--theme-color-danger);\n  color: var(--theme-color-fg-default);\n  font-size: 10px;\n  border-radius: 2px;\n  white-space: nowrap;\n  z-index: 10;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `AddColumnForm-module__Root--meI05`,
	"Row": `AddColumnForm-module__Row--GvXxE`,
	"Field": `AddColumnForm-module__Field--Bv5Zw`,
	"FieldSmall": `AddColumnForm-module__FieldSmall--MVF0I`,
	"Actions": `AddColumnForm-module__Actions--qUbdN`,
	"Input": `AddColumnForm-module__Input--JM4u0`,
	"Select": `AddColumnForm-module__Select--CVZJf`,
	"Error": `AddColumnForm-module__Error--M2EXW`,
	"RenameWrapper": `AddColumnForm-module__RenameWrapper--R_xOX`,
	"RenameInput": `AddColumnForm-module__RenameInput--jnaG3`,
	"RenameError": `AddColumnForm-module__RenameError--KXldq`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 25055:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgComponentsFill = function SvgComponentsFill(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 25,
    viewBox: "0 0 24 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.5 4.66052H4.5C4.08579 4.66052 3.75 4.99631 3.75 5.41052V11.4105C3.75 11.8247 4.08579 12.1605 4.5 12.1605H10.5C10.9142 12.1605 11.25 11.8247 11.25 11.4105V5.41052C11.25 4.99631 10.9142 4.66052 10.5 4.66052Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M19.9058 4.66052H13.9058C13.4915 4.66052 13.1558 4.99631 13.1558 5.41052V11.4105C13.1558 11.8247 13.4915 12.1605 13.9058 12.1605H19.9058C20.32 12.1605 20.6558 11.8247 20.6558 11.4105V5.41052C20.6558 4.99631 20.32 4.66052 19.9058 4.66052Z",
    fill: "#B8B8B8"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.5 13.9723H4.5C4.08579 13.9723 3.75 14.3081 3.75 14.7223V20.7223C3.75 21.1365 4.08579 21.4723 4.5 21.4723H10.5C10.9142 21.4723 11.25 21.1365 11.25 20.7223V14.7223C11.25 14.3081 10.9142 13.9723 10.5 13.9723Z",
    fill: "#B8B8B8"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M19.9058 13.9723H13.9058C13.4915 13.9723 13.1558 14.3081 13.1558 14.7223V20.7223C13.1558 21.1365 13.4915 21.4723 13.9058 21.4723H19.9058C20.32 21.4723 20.6558 21.1365 20.6558 20.7223V14.7223C20.6558 14.3081 20.32 13.9723 19.9058 13.9723Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgComponentsFill);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "29068c3fa822b46b0b9fd1d967c9795e.svg");

/***/ }),

/***/ 25155:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.clippy-layer{position:absolute;left:0;top:0;width:0;height:0;pointer-events:none;z-index:1}.Clippy-module__Root--mAb1u{margin-top:16px;margin-left:16px;display:inline-block;position:relative;pointer-events:all}.Clippy-module__ClippyContainer--shhpA{border-radius:4px;padding:1px;margin:-1px;cursor:pointer;display:inline-block;position:relative;overflow:hidden}.Clippy-module__ClippyContainer--shhpA::before{content:"";position:absolute;pointer-events:none;top:0px;left:0px;bottom:0px;right:0px;border-radius:4px;background:linear-gradient(45deg, var(--base-color-teal-500), var(--base-color-node-purple-500));z-index:1;filter:grayscale(30%) brightness(50%);transition:filter var(--speed-quick)}.Clippy-module__ClippyContainer--shhpA.Clippy-module____isFocused--SUSPI::before{filter:grayscale(0%) brightness(100%)}.Clippy-module__ClippyContainer--shhpA::after{content:"";position:absolute;pointer-events:none;border-radius:4px;background:var(--base-color-node-purple-200);z-index:2;animation:Clippy-module__rotate--uxybU 1.5s linear infinite;filter:blur(20px);width:100px;height:100px;box-shadow:0 0 30px 4px var(--base-color-node-purple-200);opacity:0;transition:opacity var(--speed-quick) linear}.Clippy-module__ClippyContainer--shhpA.Clippy-module____isThinking--t1l_g::after{opacity:1}@keyframes Clippy-module__rotate--uxybU{0%{top:calc(0% - 100px);left:calc(0% - 100px);transform:scale(3, 1) translate(3px, 3px);transform-origin:0% 100%}30%{top:calc(0% - 100px);left:100%;transform:scale(1, 0.05);transform-origin:0% 100%}50%{top:100%;left:100%;transform:scale(3, 1) translate(-3px, 3px);transform-origin:100% 0%}80%{top:100%;left:calc(0% - 100px);transform:scale(1, 0.05) translate(3px, -3px);transform-origin:100% 0%}100%{top:calc(0% - 100px);left:calc(0% - 100px);transform:scale(3, 1) translate(3px, 3px);transform-origin:0% 100%}}.Clippy-module__ClippyContent--zfL52{background-color:var(--theme-color-bg-2);align-items:center;display:inline-flex;position:relative;z-index:3;border-radius:4px;opacity:1;transition:background-color var(--speed-quick)}.Clippy-module__ClippyContainer--shhpA.Clippy-module____isFocused--SUSPI .Clippy-module__ClippyContent--zfL52{background-color:var(--theme-color-bg-3)}.Clippy-module__InputContainer--gNVCU{width:110px;transition:width var(--speed-quick) var(--easing-base) 100ms;overflow:hidden;margin-left:-8px}.Clippy-module__InputContainer--gNVCU.Clippy-module____isOpen--QNrrr{width:500px;transition:width var(--speed-quick) var(--easing-base)}.Clippy-module__InputWrapper--N19tp{width:500px;display:flex;align-items:center}.Clippy-module__ThinkingOverlay--VYt9X{position:absolute;z-index:4;top:1px;left:1px;bottom:1px;right:1px;background:var(--theme-color-bg-2);display:flex;align-items:center;justify-content:center;border-radius:4px;pointer-events:none;opacity:0;transition:opacity var(--speed-turbo)}.Clippy-module__ThinkingOverlay--VYt9X.Clippy-module____isVisible--Hx_ry{opacity:1;pointer-events:all}.Clippy-module__SendIcon--rJXDc{padding:8px;opacity:0;transition:opacity var(--speed-quick)}.Clippy-module__ClippyContainer--shhpA.Clippy-module____isFocused--SUSPI .Clippy-module__SendIcon--rJXDc{opacity:.5}.Clippy-module__SendIcon--rJXDc:hover{opacity:.8}.Clippy-module__UglySpacingHackPleaseLookAway--k4y0I{height:8px;width:100%}.Clippy-module__ClippyPopup--fK3FT{position:absolute;width:100%;background-color:var(--theme-color-bg-2);border-radius:4px;padding-bottom:8px;opacity:0;pointer-events:none;transition:opacity var(--speed-turbo)}.Clippy-module__ClippyPopup--fK3FT.Clippy-module____isVisible--Hx_ry{opacity:1;pointer-events:all;transition:opacity var(--speed-quick) 300ms}.Clippy-module__SectionTitle--jZad3{padding:16px 12px 8px 12px}.Clippy-module__PromptTagSuggestionRoot--CtJmw{box-sizing:border-box;padding:0 12px}.Clippy-module__PromptTagSuggestionRoot--CtJmw.Clippy-module____isDisabled--Ib1oO{opacity:.5;pointer-events:none}.Clippy-module__PromptTagSuggestionItem--dNvt9{display:flex;align-items:center;cursor:pointer;padding:8px;border-radius:4px}.Clippy-module__PromptTagSuggestionRoot--CtJmw:hover .Clippy-module__PromptTagSuggestionItem--dNvt9,.Clippy-module__PromptTagSuggestionRoot--CtJmw.Clippy-module____isHighlighted--qAoCR .Clippy-module__PromptTagSuggestionItem--dNvt9{background-color:var(--theme-color-bg-3)}.Clippy-module__PromptTagSuggestionAiIconContainer--p3fn8{mix-blend-mode:lighten}.Clippy-module__TagType--IYzI0{width:28px;height:28px;border-radius:50%;margin-right:8px;display:flex;align-items:center;justify-content:center}.Clippy-module__TagType--IYzI0.Clippy-module__is-visual--ghwe8{background-color:var(--base-color-node-blue-600)}.Clippy-module__TagType--IYzI0.Clippy-module__is-data--c2OOk{background-color:var(--base-color-node-green-600)}.Clippy-module__TagType--IYzI0.Clippy-module__is-custom--PBpqK{background-color:var(--base-color-node-pink-600)}.Clippy-module__PromptTagRoot--GiET9{display:flex;align-items:center;padding:4px 4px 4px 8px;border-radius:2px;margin-left:8px}.Clippy-module__PromptTagRoot--GiET9.Clippy-module__is-visual--ghwe8{background-color:var(--base-color-node-blue-600)}.Clippy-module__PromptTagRoot--GiET9.Clippy-module__is-data--c2OOk{background-color:var(--base-color-node-green-600)}.Clippy-module__PromptTagRoot--GiET9.Clippy-module__is-custom--PBpqK{background-color:var(--base-color-node-pink-600)}.Clippy-module__PromptTagRemove--Cxmj8{margin-left:4px}.Clippy-module__PromptTagRemove--Cxmj8:hover{background-color:var(--theme-color-fg-transparent)}.Clippy-module__ExamplePromptRoot--G3b3X{padding:6px 12px}.Clippy-module__ExamplePrompt--mce_I{border-radius:4px;padding:8px;border:1px solid var(--theme-color-bg-3);cursor:pointer}.Clippy-module__ExamplePrompt--mce_I:hover{background-color:var(--theme-color-bg-3)}.Clippy-module__IconContainer--QcSPF{mix-blend-mode:lighten;position:relative;z-index:10;align-self:flex-start;margin-top:2px}.Clippy-module____isHiddenInput--lLGNI{opacity:0;pointer-events:none}.Clippy-module__AiChatItem--pliEQ{display:flex;align-items:center;border-top:1px solid var(--theme-color-bg-1);padding-top:4px;padding-left:4px}.Clippy-module__ClippyIcon--IXs0k{transition:opacity var(--speed-quick)}.Clippy-module__ClippyIcon--IXs0k.Clippy-module____isHidden--niWyc{opacity:0}.Clippy-module__UserBadge--sNruA{position:absolute;top:0;left:0;margin:7px;transition:transform var(--speed-quick),opacity var(--speed-quick)}.Clippy-module__UserBadge--sNruA.Clippy-module____isHidden--niWyc{transform:scale(0);opacity:0}.Clippy-module__ClippyNoApiKey--c_cVX{padding:32px}.Clippy-module__CurrentActivities--HBgp_{position:absolute;top:-1px;left:calc(100% + 7px);display:flex;gap:5px;flex-direction:column;height:49px;flex-wrap:wrap}.Clippy-module__ActivityItem--IWYSX{background-color:var(--theme-color-bg-2);width:49px;height:49px;flex-shrink:0;border-radius:4px;box-sizing:border-box;position:relative;cursor:pointer;transition:background-color var(--speed-turbo);display:flex;align-items:center;justify-content:center;animation:Clippy-module__activity-appear--VAwn5 var(--speed-quick) var(--easing-base) var(--speed-base) both}.Clippy-module__ActivityItem--IWYSX:hover{background-color:var(--theme-color-bg-3)}.Clippy-module__ActivityItem--IWYSX:before{content:"";position:absolute;top:0;bottom:0;left:0;right:0;border-radius:4px}.Clippy-module__ActivityItem--IWYSX.Clippy-module__is-custom--PBpqK:before{border:1px solid var(--base-color-node-pink-700)}.Clippy-module__ActivityItem--IWYSX.Clippy-module__is-data--c2OOk:before{border:1px solid var(--base-color-node-green-700)}.Clippy-module__ActivityItem--IWYSX.Clippy-module__is-visual--ghwe8:before{border:1px solid var(--base-color-node-blue-700)}.Clippy-module__ActivityLogo--TxHSW{mix-blend-mode:lighten;pointer-events:none;margin-left:-2px}.Clippy-module__TextArea--PozE7{padding:0 32px 4px 7px;margin-top:-8px}@keyframes Clippy-module__activity-appear--VAwn5{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateX(0)}}.Clippy-module__LimitedBetaCard--Oqt_B{margin:16px 12px 4px 12px;padding:16px;background-color:var(--theme-color-bg-3);border-radius:4px}.Clippy-module__GptVersionDisplay--_Bg9b{position:absolute;top:16px;right:12px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/Clippy/Clippy.module.scss"],"names":[],"mappings":"AAAA,cACE,iBAAA,CACA,MAAA,CACA,KAAA,CACA,OAAA,CACA,QAAA,CACA,mBAAA,CACA,SAAA,CAGF,4BACE,eAAA,CACA,gBAAA,CACA,oBAAA,CACA,iBAAA,CACA,kBAAA,CAGF,uCACE,iBAAA,CACA,WAAA,CACA,WAAA,CACA,cAAA,CACA,oBAAA,CACA,iBAAA,CACA,eAAA,CAEA,+CACE,UAAA,CACA,iBAAA,CACA,mBAAA,CACA,OAAA,CACA,QAAA,CACA,UAAA,CACA,SAAA,CACA,iBAAA,CACA,gGAAA,CACA,SAAA,CACA,qCAAA,CACA,oCAAA,CAGF,iFACE,qCAAA,CAGF,8CACE,UAAA,CACA,iBAAA,CACA,mBAAA,CACA,iBAAA,CACA,4CAAA,CACA,SAAA,CACA,2DAAA,CACA,iBAAA,CACA,WAAA,CACA,YAAA,CACA,yDAAA,CACA,SAAA,CACA,4CAAA,CAGF,iFACE,SAAA,CAsCJ,wCACE,GACE,oBAAA,CACA,qBAAA,CACA,yCAAA,CACA,wBAAA,CAGF,IACE,oBAAA,CACA,SAAA,CACA,wBAAA,CACA,wBAAA,CAGF,IACE,QAAA,CACA,SAAA,CACA,0CAAA,CACA,wBAAA,CAGF,IACE,QAAA,CACA,qBAAA,CACA,6CAAA,CACA,wBAAA,CAGF,KACE,oBAAA,CACA,qBAAA,CACA,yCAAA,CACA,wBAAA,CAAA,CAIJ,qCACE,wCAAA,CACA,kBAAA,CACA,mBAAA,CACA,iBAAA,CACA,SAAA,CACA,iBAAA,CACA,SAAA,CACA,8CAAA,CAEA,8GACE,wCAAA,CAIJ,sCACE,WAAA,CACA,4DAAA,CACA,eAAA,CACA,gBAAA,CAEA,qEACE,WAAA,CACA,sDAAA,CAIJ,oCACE,WAAA,CACA,YAAA,CACA,kBAAA,CAGF,uCACE,iBAAA,CACA,SAAA,CACA,OAAA,CACA,QAAA,CACA,UAAA,CACA,SAAA,CACA,kCAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,mBAAA,CACA,SAAA,CACA,qCAAA,CAEA,yEACE,SAAA,CACA,kBAAA,CAIJ,gCACE,WAAA,CACA,SAAA,CACA,qCAAA,CAEA,yGACE,UAAA,CAGF,sCACE,UAAA,CAIJ,qDACE,UAAA,CACA,UAAA,CAGF,mCACE,iBAAA,CACA,UAAA,CACA,wCAAA,CACA,iBAAA,CACA,kBAAA,CACA,SAAA,CACA,mBAAA,CACA,qCAAA,CAEA,qEACE,SAAA,CACA,kBAAA,CACA,2CAAA,CAIJ,oCACE,0BAAA,CAGF,+CACE,qBAAA,CACA,cAAA,CAEA,kFACE,UAAA,CACA,mBAAA,CAIJ,+CACE,YAAA,CACA,kBAAA,CACA,cAAA,CACA,WAAA,CACA,iBAAA,CAEA,wOAEE,wCAAA,CAIJ,0DACE,sBAAA,CAGF,+BACE,UAAA,CACA,WAAA,CACA,iBAAA,CACA,gBAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CAEA,+DACE,gDAAA,CAGF,6DACE,iDAAA,CAGF,+DACE,gDAAA,CAIJ,qCACE,YAAA,CACA,kBAAA,CACA,uBAAA,CACA,iBAAA,CACA,eAAA,CAEA,qEACE,gDAAA,CAGF,mEACE,iDAAA,CAGF,qEACE,gDAAA,CAIJ,uCACE,eAAA,CACA,6CACE,kDAAA,CAIJ,yCACE,gBAAA,CAGF,qCACE,iBAAA,CACA,WAAA,CACA,wCAAA,CACA,cAAA,CAEA,2CACE,wCAAA,CAIJ,qCACE,sBAAA,CACA,iBAAA,CACA,UAAA,CACA,qBAAA,CACA,cAAA,CAGF,uCACE,SAAA,CACA,mBAAA,CAiHF,kCACE,YAAA,CACA,kBAAA,CACA,4CAAA,CACA,eAAA,CACA,gBAAA,CAGF,kCACE,qCAAA,CAEA,mEACE,SAAA,CAIJ,iCACE,iBAAA,CACA,KAAA,CACA,MAAA,CACA,UAAA,CACA,kEAAA,CAEA,kEACE,kBAAA,CACA,SAAA,CAIJ,sCACE,YAAA,CAGF,yCACE,iBAAA,CACA,QAAA,CACA,qBAAA,CACA,YAAA,CACA,OAAA,CACA,qBAAA,CACA,WAAA,CACA,cAAA,CAGF,oCACE,wCAAA,CACA,UAAA,CACA,WAAA,CACA,aAAA,CACA,iBAAA,CACA,qBAAA,CACA,iBAAA,CACA,cAAA,CACA,8CAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,4GAAA,CAEA,0CACE,wCAAA,CAGF,2CACE,UAAA,CACA,iBAAA,CACA,KAAA,CACA,QAAA,CACA,MAAA,CACA,OAAA,CACA,iBAAA,CAGF,2EACE,gDAAA,CAGF,yEACE,iDAAA,CAGF,2EACE,gDAAA,CAIJ,oCACE,sBAAA,CACA,mBAAA,CACA,gBAAA,CAGF,gCACE,sBAAA,CACA,eAAA,CAGF,iDACE,KACE,SAAA,CACA,0BAAA,CAGF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,uCACE,yBAAA,CACA,YAAA,CACA,wCAAA,CACA,iBAAA,CAGF,yCACE,iBAAA,CACA,QAAA,CACA,UAAA","sourcesContent":[":global(.clippy-layer) {\n  position: absolute;\n  left: 0;\n  top: 0;\n  width: 0;\n  height: 0;\n  pointer-events: none;\n  z-index: 1;\n}\n\n.Root {\n  margin-top: 16px;\n  margin-left: 16px;\n  display: inline-block;\n  position: relative;\n  pointer-events: all;\n}\n\n.ClippyContainer {\n  border-radius: 4px;\n  padding: 1px;\n  margin: -1px;\n  cursor: pointer;\n  display: inline-block;\n  position: relative;\n  overflow: hidden;\n\n  &::before {\n    content: '';\n    position: absolute;\n    pointer-events: none;\n    top: 0px;\n    left: 0px;\n    bottom: 0px;\n    right: 0px;\n    border-radius: 4px;\n    background: linear-gradient(45deg, var(--base-color-teal-500), var(--base-color-node-purple-500));\n    z-index: 1;\n    filter: grayscale(30%) brightness(50%);\n    transition: filter var(--speed-quick);\n  }\n\n  &.__isFocused::before {\n    filter: grayscale(0%) brightness(100%);\n  }\n\n  &::after {\n    content: '';\n    position: absolute;\n    pointer-events: none;\n    border-radius: 4px;\n    background: var(--base-color-node-purple-200);\n    z-index: 2;\n    animation: rotate 1.5s linear infinite;\n    filter: blur(20px);\n    width: 100px;\n    height: 100px;\n    box-shadow: 0 0 30px 4px var(--base-color-node-purple-200);\n    opacity: 0;\n    transition: opacity var(--speed-quick) linear;\n  }\n\n  &.__isThinking::after {\n    opacity: 1;\n  }\n\n  // &::after {\n  //     --angle: 0deg;\n  //     opacity: 0;\n  //     content: \"\";\n  //     position: absolute;\n  //     box-sizing: border-box;\n  //     top: -1px;\n  //     left: -1px;\n  //     bottom: -1px;\n  //     right: -1px;\n  //     pointer-events: none;\n  //     border-radius: 4px;\n  //     z-index: 2;\n  //     border: 4px solid transparent;\n  //     border-image: conic-gradient(from var(--angle), var(--base-color-node-purple-200) 5%, transparent 15%, transparent 85%, var(--base-color-node-purple-200)) 1;\n  //     animation: border-rotation 2s linear infinite;\n  // }\n}\n\n// @keyframes border-rotation {\n//     from {\n//         --angle: 0deg;\n//     }\n\n//     to {\n//         --angle: 360deg;\n//     }\n// }\n\n// @property --angle {\n//     syntax: '<angle>';\n//     initial-value: 0deg;\n//     inherits: false;\n// }\n\n@keyframes rotate {\n  0% {\n    top: calc(0% - 100px);\n    left: calc(0% - 100px);\n    transform: scale(3, 1) translate(3px, 3px);\n    transform-origin: 0% 100%;\n  }\n\n  30% {\n    top: calc(0% - 100px);\n    left: 100%;\n    transform: scale(1, 0.05);\n    transform-origin: 0% 100%;\n  }\n\n  50% {\n    top: 100%;\n    left: 100%;\n    transform: scale(3, 1) translate(-3px, 3px);\n    transform-origin: 100% 0%;\n  }\n\n  80% {\n    top: 100%;\n    left: calc(0% - 100px);\n    transform: scale(1, 0.05) translate(3px, -3px);\n    transform-origin: 100% 0%;\n  }\n\n  100% {\n    top: calc(0% - 100px);\n    left: calc(0% - 100px);\n    transform: scale(3, 1) translate(3px, 3px);\n    transform-origin: 0% 100%;\n  }\n}\n\n.ClippyContent {\n  background-color: var(--theme-color-bg-2);\n  align-items: center;\n  display: inline-flex;\n  position: relative;\n  z-index: 3;\n  border-radius: 4px;\n  opacity: 1;\n  transition: background-color var(--speed-quick);\n\n  .ClippyContainer.__isFocused & {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n.InputContainer {\n  width: 110px;\n  transition: width var(--speed-quick) var(--easing-base) 100ms;\n  overflow: hidden;\n  margin-left: -8px;\n\n  &.__isOpen {\n    width: 500px;\n    transition: width var(--speed-quick) var(--easing-base);\n  }\n}\n\n.InputWrapper {\n  width: 500px;\n  display: flex;\n  align-items: center;\n}\n\n.ThinkingOverlay {\n  position: absolute;\n  z-index: 4;\n  top: 1px;\n  left: 1px;\n  bottom: 1px;\n  right: 1px;\n  background: var(--theme-color-bg-2);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  border-radius: 4px;\n  pointer-events: none;\n  opacity: 0;\n  transition: opacity var(--speed-turbo);\n\n  &.__isVisible {\n    opacity: 1;\n    pointer-events: all;\n  }\n}\n\n.SendIcon {\n  padding: 8px;\n  opacity: 0;\n  transition: opacity var(--speed-quick);\n\n  .ClippyContainer.__isFocused & {\n    opacity: 0.5;\n  }\n\n  &:hover {\n    opacity: 0.8;\n  }\n}\n\n.UglySpacingHackPleaseLookAway {\n  height: 8px;\n  width: 100%;\n}\n\n.ClippyPopup {\n  position: absolute;\n  width: 100%;\n  background-color: var(--theme-color-bg-2);\n  border-radius: 4px;\n  padding-bottom: 8px;\n  opacity: 0;\n  pointer-events: none;\n  transition: opacity var(--speed-turbo);\n\n  &.__isVisible {\n    opacity: 1;\n    pointer-events: all;\n    transition: opacity var(--speed-quick) 300ms;\n  }\n}\n\n.SectionTitle {\n  padding: 16px 12px 8px 12px;\n}\n\n.PromptTagSuggestionRoot {\n  box-sizing: border-box;\n  padding: 0 12px;\n\n  &.__isDisabled {\n    opacity: 0.5;\n    pointer-events: none;\n  }\n}\n\n.PromptTagSuggestionItem {\n  display: flex;\n  align-items: center;\n  cursor: pointer;\n  padding: 8px;\n  border-radius: 4px;\n\n  .PromptTagSuggestionRoot:hover &,\n  .PromptTagSuggestionRoot.__isHighlighted & {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n.PromptTagSuggestionAiIconContainer {\n  mix-blend-mode: lighten;\n}\n\n.TagType {\n  width: 28px;\n  height: 28px;\n  border-radius: 50%;\n  margin-right: 8px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n\n  &.is-visual {\n    background-color: var(--base-color-node-blue-600);\n  }\n\n  &.is-data {\n    background-color: var(--base-color-node-green-600);\n  }\n\n  &.is-custom {\n    background-color: var(--base-color-node-pink-600);\n  }\n}\n\n.PromptTagRoot {\n  display: flex;\n  align-items: center;\n  padding: 4px 4px 4px 8px;\n  border-radius: 2px;\n  margin-left: 8px;\n\n  &.is-visual {\n    background-color: var(--base-color-node-blue-600);\n  }\n\n  &.is-data {\n    background-color: var(--base-color-node-green-600);\n  }\n\n  &.is-custom {\n    background-color: var(--base-color-node-pink-600);\n  }\n}\n\n.PromptTagRemove {\n  margin-left: 4px;\n  &:hover {\n    background-color: var(--theme-color-fg-transparent);\n  }\n}\n\n.ExamplePromptRoot {\n  padding: 6px 12px;\n}\n\n.ExamplePrompt {\n  border-radius: 4px;\n  padding: 8px;\n  border: 1px solid var(--theme-color-bg-3);\n  cursor: pointer;\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n.IconContainer {\n  mix-blend-mode: lighten;\n  position: relative;\n  z-index: 10;\n  align-self: flex-start;\n  margin-top: 2px;\n}\n\n.__isHiddenInput {\n  opacity: 0;\n  pointer-events: none;\n}\n\n// .StarBase {\n//     path:not(:nth-child(4)) {\n//         opacity: 0;\n//     }\n// }\n\n// .Star1Back,\n// .Star1Front,\n// .Star2Back,\n// .Star2Front,\n// .Star3Back,\n// .Star3Front {\n//     position: absolute;\n//     top: 7px;\n//     left: 6px;\n\n//     path {\n//         opacity: 0;\n//     }\n// }\n\n// .Star1Front,\n// .Star1Back {\n//     path:nth-child(1) {\n//         opacity: 1;\n//     }\n// }\n\n// .Star2Front,\n// .Star2Back {\n//     path:nth-child(2) {\n//         opacity: 1;\n//     }\n// }\n\n// .Star3Front,\n// .Star3Back {\n//     path:nth-child(3) {\n//         opacity: 1;\n//     }\n// }\n\n// .Star1Back {\n//     animation: star-blur 5s linear infinite 200ms both;\n// }\n\n// .Star1Front {\n//     animation: star-blink 5s linear infinite 200ms both;\n// }\n\n// .Star2Back {\n//     animation: star-blur 5s linear infinite 100ms both;\n// }\n\n// .Star2Front {\n//     animation: star-blink 5s linear infinite 100ms both;\n// }\n\n// .Star3Back {\n//     animation: star-blur 5s linear infinite both;\n// }\n\n// .Star3Front {\n//     animation: star-blink 5s linear infinite both;\n// }\n\n// @keyframes star-blur {\n//     0% {\n//         opacity: 1;\n//         filter: saturate(100%) blur(0px);\n//     }\n\n//     10% {\n//         opacity: 1;\n//         filter: saturate(150%) blur(3px);\n//     }\n\n//     20% {\n//         opacity: 1;\n//         filter: saturate(100%) blur(0px);\n//     }\n\n//     100% {\n//         opacity: 1;\n//         filter: saturate(100%) blur(0px);\n//     }\n// }\n\n// @keyframes star-blink {\n//     0% {\n//         opacity: 1;\n//         filter: brightness(100%);\n//     }\n\n//     10% {\n//         opacity: 0.4;\n//         filter: brightness(500%) blur(0.5px);\n//     }\n\n//     20% {\n//         opacity: 1;\n//         filter: brightness(100%);\n//     }\n\n//     100% {\n//         opacity: 1;\n//         filter: brightness(100%);\n//     }\n// }\n\n.AiChatItem {\n  display: flex;\n  align-items: center;\n  border-top: 1px solid var(--theme-color-bg-1);\n  padding-top: 4px;\n  padding-left: 4px;\n}\n\n.ClippyIcon {\n  transition: opacity var(--speed-quick);\n\n  &.__isHidden {\n    opacity: 0;\n  }\n}\n\n.UserBadge {\n  position: absolute;\n  top: 0;\n  left: 0;\n  margin: 7px;\n  transition: transform var(--speed-quick), opacity var(--speed-quick);\n\n  &.__isHidden {\n    transform: scale(0);\n    opacity: 0;\n  }\n}\n\n.ClippyNoApiKey {\n  padding: 32px;\n}\n\n.CurrentActivities {\n  position: absolute;\n  top: -1px;\n  left: calc(100% + 7px);\n  display: flex;\n  gap: 5px;\n  flex-direction: column;\n  height: 49px;\n  flex-wrap: wrap;\n}\n\n.ActivityItem {\n  background-color: var(--theme-color-bg-2);\n  width: 49px;\n  height: 49px;\n  flex-shrink: 0;\n  border-radius: 4px;\n  box-sizing: border-box;\n  position: relative;\n  cursor: pointer;\n  transition: background-color var(--speed-turbo);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  animation: activity-appear var(--speed-quick) var(--easing-base) var(--speed-base) both;\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &:before {\n    content: '';\n    position: absolute;\n    top: 0;\n    bottom: 0;\n    left: 0;\n    right: 0;\n    border-radius: 4px;\n  }\n\n  &.is-custom:before {\n    border: 1px solid var(--base-color-node-pink-700);\n  }\n\n  &.is-data:before {\n    border: 1px solid var(--base-color-node-green-700);\n  }\n\n  &.is-visual:before {\n    border: 1px solid var(--base-color-node-blue-700);\n  }\n}\n\n.ActivityLogo {\n  mix-blend-mode: lighten;\n  pointer-events: none;\n  margin-left: -2px;\n}\n\n.TextArea {\n  padding: 0 32px 4px 7px;\n  margin-top: -8px;\n}\n\n@keyframes activity-appear {\n  from {\n    opacity: 0;\n    transform: translateY(10px);\n  }\n\n  to {\n    opacity: 1;\n    transform: translateX(0);\n  }\n}\n\n.LimitedBetaCard {\n  margin: 16px 12px 4px 12px;\n  padding: 16px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 4px;\n}\n\n.GptVersionDisplay {\n  position: absolute;\n  top: 16px;\n  right: 12px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Clippy-module__Root--mAb1u`,
	"ClippyContainer": `Clippy-module__ClippyContainer--shhpA`,
	"__isFocused": `Clippy-module____isFocused--SUSPI`,
	"rotate": `Clippy-module__rotate--uxybU`,
	"__isThinking": `Clippy-module____isThinking--t1l_g`,
	"ClippyContent": `Clippy-module__ClippyContent--zfL52`,
	"InputContainer": `Clippy-module__InputContainer--gNVCU`,
	"__isOpen": `Clippy-module____isOpen--QNrrr`,
	"InputWrapper": `Clippy-module__InputWrapper--N19tp`,
	"ThinkingOverlay": `Clippy-module__ThinkingOverlay--VYt9X`,
	"__isVisible": `Clippy-module____isVisible--Hx_ry`,
	"SendIcon": `Clippy-module__SendIcon--rJXDc`,
	"UglySpacingHackPleaseLookAway": `Clippy-module__UglySpacingHackPleaseLookAway--k4y0I`,
	"ClippyPopup": `Clippy-module__ClippyPopup--fK3FT`,
	"SectionTitle": `Clippy-module__SectionTitle--jZad3`,
	"PromptTagSuggestionRoot": `Clippy-module__PromptTagSuggestionRoot--CtJmw`,
	"__isDisabled": `Clippy-module____isDisabled--Ib1oO`,
	"PromptTagSuggestionItem": `Clippy-module__PromptTagSuggestionItem--dNvt9`,
	"__isHighlighted": `Clippy-module____isHighlighted--qAoCR`,
	"PromptTagSuggestionAiIconContainer": `Clippy-module__PromptTagSuggestionAiIconContainer--p3fn8`,
	"TagType": `Clippy-module__TagType--IYzI0`,
	"is-visual": `Clippy-module__is-visual--ghwe8`,
	"is-data": `Clippy-module__is-data--c2OOk`,
	"is-custom": `Clippy-module__is-custom--PBpqK`,
	"PromptTagRoot": `Clippy-module__PromptTagRoot--GiET9`,
	"PromptTagRemove": `Clippy-module__PromptTagRemove--Cxmj8`,
	"ExamplePromptRoot": `Clippy-module__ExamplePromptRoot--G3b3X`,
	"ExamplePrompt": `Clippy-module__ExamplePrompt--mce_I`,
	"IconContainer": `Clippy-module__IconContainer--QcSPF`,
	"__isHiddenInput": `Clippy-module____isHiddenInput--lLGNI`,
	"AiChatItem": `Clippy-module__AiChatItem--pliEQ`,
	"ClippyIcon": `Clippy-module__ClippyIcon--IXs0k`,
	"__isHidden": `Clippy-module____isHidden--niWyc`,
	"UserBadge": `Clippy-module__UserBadge--sNruA`,
	"ClippyNoApiKey": `Clippy-module__ClippyNoApiKey--c_cVX`,
	"CurrentActivities": `Clippy-module__CurrentActivities--HBgp_`,
	"ActivityItem": `Clippy-module__ActivityItem--IWYSX`,
	"activity-appear": `Clippy-module__activity-appear--VAwn5`,
	"ActivityLogo": `Clippy-module__ActivityLogo--TxHSW`,
	"TextArea": `Clippy-module__TextArea--PozE7`,
	"LimitedBetaCard": `Clippy-module__LimitedBetaCard--Oqt_B`,
	"GptVersionDisplay": `Clippy-module__GptVersionDisplay--_Bg9b`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 25267:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.pop = exports.safeJSON = exports.maybeCoerceBoolean = exports.maybeCoerceFloat = exports.maybeCoerceInteger = exports.coerceBoolean = exports.coerceFloat = exports.coerceInteger = exports.validatePositiveInteger = exports.ensurePresent = exports.isReadonlyArray = exports.isArray = exports.isAbsoluteURL = void 0;
exports.maybeObj = maybeObj;
exports.isEmptyObj = isEmptyObj;
exports.hasOwn = hasOwn;
exports.isObj = isObj;
const error_1 = __webpack_require__(37015);
// https://url.spec.whatwg.org/#url-scheme-string
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
const isAbsoluteURL = (url) => {
    return startsWithSchemeRegexp.test(url);
};
exports.isAbsoluteURL = isAbsoluteURL;
let isArray = (val) => ((exports.isArray = Array.isArray), (0, exports.isArray)(val));
exports.isArray = isArray;
exports.isReadonlyArray = exports.isArray;
/** Returns an object if the given value isn't an object, otherwise returns as-is */
function maybeObj(x) {
    if (typeof x !== 'object') {
        return {};
    }
    return x ?? {};
}
// https://stackoverflow.com/a/34491287
function isEmptyObj(obj) {
    if (!obj)
        return true;
    for (const _k in obj)
        return false;
    return true;
}
// https://eslint.org/docs/latest/rules/no-prototype-builtins
function hasOwn(obj, key) {
    return Object.prototype.hasOwnProperty.call(obj, key);
}
function isObj(obj) {
    return obj != null && typeof obj === 'object' && !Array.isArray(obj);
}
const ensurePresent = (value) => {
    if (value == null) {
        throw new error_1.AnthropicError(`Expected a value to be given but received ${value} instead.`);
    }
    return value;
};
exports.ensurePresent = ensurePresent;
const validatePositiveInteger = (name, n) => {
    if (typeof n !== 'number' || !Number.isInteger(n)) {
        throw new error_1.AnthropicError(`${name} must be an integer`);
    }
    if (n < 0) {
        throw new error_1.AnthropicError(`${name} must be a positive integer`);
    }
    return n;
};
exports.validatePositiveInteger = validatePositiveInteger;
const coerceInteger = (value) => {
    if (typeof value === 'number')
        return Math.round(value);
    if (typeof value === 'string')
        return parseInt(value, 10);
    throw new error_1.AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
};
exports.coerceInteger = coerceInteger;
const coerceFloat = (value) => {
    if (typeof value === 'number')
        return value;
    if (typeof value === 'string')
        return parseFloat(value);
    throw new error_1.AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
};
exports.coerceFloat = coerceFloat;
const coerceBoolean = (value) => {
    if (typeof value === 'boolean')
        return value;
    if (typeof value === 'string')
        return value === 'true';
    return Boolean(value);
};
exports.coerceBoolean = coerceBoolean;
const maybeCoerceInteger = (value) => {
    if (value == null) {
        return undefined;
    }
    return (0, exports.coerceInteger)(value);
};
exports.maybeCoerceInteger = maybeCoerceInteger;
const maybeCoerceFloat = (value) => {
    if (value == null) {
        return undefined;
    }
    return (0, exports.coerceFloat)(value);
};
exports.maybeCoerceFloat = maybeCoerceFloat;
const maybeCoerceBoolean = (value) => {
    if (value == null) {
        return undefined;
    }
    return (0, exports.coerceBoolean)(value);
};
exports.maybeCoerceBoolean = maybeCoerceBoolean;
const safeJSON = (text) => {
    try {
        return JSON.parse(text);
    }
    catch (err) {
        return undefined;
    }
};
exports.safeJSON = safeJSON;
// Gets a value from an object, deletes the key, and returns the value (or undefined if not found)
const pop = (obj, key) => {
    const value = obj[key];
    delete obj[key];
    return value;
};
exports.pop = pop;
//# sourceMappingURL=values.js.map

/***/ }),

/***/ 25352:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ChainStats-module__ChainStats--kU3Ki{padding:16px;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:4px;margin-bottom:16px}.ChainStats-module__StatsTitle--Y35HO{display:flex;align-items:center;gap:8px;margin:0 0 16px;font-size:14px;font-weight:600;color:var(--theme-color-fg-default)}.ChainStats-module__StatGroup--y_oWh{margin-bottom:16px}.ChainStats-module__StatGroup--y_oWh:last-child{margin-bottom:0}.ChainStats-module__GroupTitle--ZUyn1{margin:0 0 8px;font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:var(--theme-color-fg-default-shy)}.ChainStats-module__StatItem--HsVyO{display:flex;justify-content:space-between;align-items:center;padding:6px 8px;background-color:var(--theme-color-bg-3);border-radius:3px;margin-bottom:4px;font-size:12px}.ChainStats-module__StatItem--HsVyO:last-child{margin-bottom:0}.ChainStats-module__StatLabel--G3BgX{color:var(--theme-color-fg-default)}.ChainStats-module__StatValue--CpP3F{font-weight:600;font-family:monospace;color:var(--theme-color-fg-highlight)}.ChainStats-module__ComponentList--gvmJA{display:flex;flex-wrap:wrap;gap:8px}.ChainStats-module__ComponentChip--hwpcT{display:flex;align-items:center;gap:4px;padding:4px 8px;background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:3px;font-size:11px;color:var(--theme-color-fg-default);transition:all .15s ease}.ChainStats-module__ComponentChip--hwpcT:hover{background-color:var(--theme-color-bg-4);border-color:var(--theme-color-primary)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/ChainStats.module.scss"],"names":[],"mappings":"AAMA,sCACE,YAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,kBAAA,CAOF,sCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,eAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAOF,qCACE,kBAAA,CAEA,gDACE,eAAA,CAIJ,sCACE,cAAA,CACA,cAAA,CACA,eAAA,CACA,wBAAA,CACA,mBAAA,CACA,uCAAA,CAOF,oCACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,eAAA,CACA,wCAAA,CACA,iBAAA,CACA,iBAAA,CACA,cAAA,CAEA,+CACE,eAAA,CAIJ,qCACE,mCAAA,CAGF,qCACE,eAAA,CACA,qBAAA,CACA,qCAAA,CAOF,yCACE,YAAA,CACA,cAAA,CACA,OAAA,CAGF,yCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,eAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,cAAA,CACA,mCAAA,CACA,wBAAA,CAEA,+CACE,wCAAA,CACA,uCAAA","sourcesContent":["/**\n * ChainStats Component Styles\n *\n * Uses design tokens from UI-STYLING-GUIDE.md\n */\n\n.ChainStats {\n  padding: 16px;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  margin-bottom: 16px;\n}\n\n/* =================================================================\n   Stats Title\n   ================================================================= */\n\n.StatsTitle {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin: 0 0 16px;\n  font-size: 14px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n}\n\n/* =================================================================\n   Stat Groups\n   ================================================================= */\n\n.StatGroup {\n  margin-bottom: 16px;\n\n  &:last-child {\n    margin-bottom: 0;\n  }\n}\n\n.GroupTitle {\n  margin: 0 0 8px;\n  font-size: 12px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.5px;\n  color: var(--theme-color-fg-default-shy);\n}\n\n/* =================================================================\n   Stat Items\n   ================================================================= */\n\n.StatItem {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 6px 8px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 3px;\n  margin-bottom: 4px;\n  font-size: 12px;\n\n  &:last-child {\n    margin-bottom: 0;\n  }\n}\n\n.StatLabel {\n  color: var(--theme-color-fg-default);\n}\n\n.StatValue {\n  font-weight: 600;\n  font-family: monospace;\n  color: var(--theme-color-fg-highlight);\n}\n\n/* =================================================================\n   Component List\n   ================================================================= */\n\n.ComponentList {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 8px;\n}\n\n.ComponentChip {\n  display: flex;\n  align-items: center;\n  gap: 4px;\n  padding: 4px 8px;\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 3px;\n  font-size: 11px;\n  color: var(--theme-color-fg-default);\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    border-color: var(--theme-color-primary);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"ChainStats": `ChainStats-module__ChainStats--kU3Ki`,
	"StatsTitle": `ChainStats-module__StatsTitle--Y35HO`,
	"StatGroup": `ChainStats-module__StatGroup--y_oWh`,
	"GroupTitle": `ChainStats-module__GroupTitle--ZUyn1`,
	"StatItem": `ChainStats-module__StatItem--HsVyO`,
	"StatLabel": `ChainStats-module__StatLabel--G3BgX`,
	"StatValue": `ChainStats-module__StatValue--CpP3F`,
	"ComponentList": `ChainStats-module__ComponentList--gvmJA`,
	"ComponentChip": `ChainStats-module__ComponentChip--hwpcT`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 25374:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getElectronBinding = void 0;
const getElectronBinding = (name) => {
    if (process._linkedBinding) {
        return process._linkedBinding('electron_common_' + name);
    }
    else if (process.electronBinding) {
        return process.electronBinding(name);
    }
    else {
        return null;
    }
};
exports.getElectronBinding = getElectronBinding;


/***/ }),

/***/ 25758:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   nU: () => (/* binding */ DEFAULT_BRANCH)
/* harmony export */ });
/* unused harmony exports DEFAULT_REMOTE, DEFAULT_REF */
const DEFAULT_REMOTE = 'origin';
const DEFAULT_BRANCH = 'main';
const DEFAULT_REF = (/* unused pure expression or super */ null && (`${DEFAULT_REMOTE}/${DEFAULT_BRANCH}`));


/***/ }),

/***/ 25840:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5, _path6, _path7, _path8, _path9;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgBorderRight = function SvgBorderRight(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.99023 25.6046C3.99023 25.1904 4.32602 24.8546 4.74023 24.8546C5.15445 24.8546 5.49023 25.1904 5.49023 25.6046C5.49023 26.0188 5.15445 26.3546 4.74023 26.3546C4.32602 26.3546 3.99023 26.0188 3.99023 25.6046Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.99023 11.8629C3.99023 11.4487 4.32602 11.1129 4.74023 11.1129C5.15445 11.1129 5.49023 11.4487 5.49023 11.8629C5.49023 12.2771 5.15445 12.6129 4.74023 12.6129C4.32602 12.6129 3.99023 12.2771 3.99023 11.8629Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.99023 18.734C3.99023 18.3198 4.32602 17.984 4.74023 17.984C5.15445 17.984 5.49023 18.3198 5.49023 18.734C5.49023 19.1482 5.15445 19.484 4.74023 19.484C4.32602 19.484 3.99023 19.1482 3.99023 18.734Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.99023 4.99207C3.99023 4.57785 4.32602 4.24207 4.74023 4.24207C5.15445 4.24207 5.49023 4.57785 5.49023 4.99207C5.49023 5.40628 5.15445 5.74207 4.74023 5.74207C4.32602 5.74207 3.99023 5.40628 3.99023 4.99207Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.7324 4.99158C17.7324 4.57736 18.0682 4.24158 18.4824 4.24158C18.8966 4.24158 19.2324 4.57736 19.2324 4.99158C19.2324 5.40579 18.8966 5.74158 18.4824 5.74158C18.0682 5.74158 17.7324 5.40579 17.7324 4.99158Z",
    fill: "#F5F5F5"
  })), _path6 || (_path6 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.7324 25.6044C17.7324 25.1902 18.0682 24.8544 18.4824 24.8544C18.8966 24.8544 19.2324 25.1902 19.2324 25.6044C19.2324 26.0186 18.8966 26.3544 18.4824 26.3544C18.0682 26.3544 17.7324 26.0186 17.7324 25.6044Z",
    fill: "#F5F5F5"
  })), _path7 || (_path7 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.8613 4.99182C10.8613 4.57761 11.1971 4.24182 11.6113 4.24182C12.0255 4.24182 12.3613 4.57761 12.3613 4.99182C12.3613 5.40603 12.0255 5.74182 11.6113 5.74182C11.1971 5.74182 10.8613 5.40603 10.8613 4.99182Z",
    fill: "#F5F5F5"
  })), _path8 || (_path8 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.8613 25.6046C10.8613 25.1904 11.1971 24.8546 11.6113 24.8546C12.0255 24.8546 12.3613 25.1904 12.3613 25.6046C12.3613 26.0188 12.0255 26.3546 11.6113 26.3546C11.1971 26.3546 10.8613 26.0188 10.8613 25.6046Z",
    fill: "#F5F5F5"
  })), _path9 || (_path9 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M25.5332 4.24146C25.9474 4.24146 26.2832 4.57724 26.2832 4.99146L26.2832 25.604C26.2832 26.0182 25.9474 26.354 25.5332 26.354C25.119 26.354 24.7832 26.0182 24.7832 25.604L24.7832 4.99145C24.7832 4.57724 25.119 4.24145 25.5332 4.24146Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgBorderRight);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "2e0f578b815a0a954439161112e9c83d.svg");

/***/ }),

/***/ 25873:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


function checkDCE() {
  /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
  if (
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
  ) {
    return;
  }
  if (false) // removed by dead control flow
{}
  try {
    // Verify that the code above has been dead code eliminated (DCE'd).
    __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
  } catch (err) {
    // DevTools shouldn't crash React, no matter what.
    // We should still report in case we break this code.
    console.error(err);
  }
}

if (true) {
  // DCE check should happen before ReactDOM bundle executes so that
  // DevTools can report bad minification during injection.
  checkDCE();
  module.exports = __webpack_require__(86974);
} else // removed by dead control flow
{}


/***/ }),

/***/ 26047:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.NodePickerNodeGroup-module__Root--tiLUD{display:flex;flex-direction:column;margin-block-end:0;position:relative;z-index:1;padding:0px 14px 10px}.NodePickerNodeGroup-module__ItemContainer--lAwbz{box-sizing:border-box;list-style-type:none;padding-bottom:8px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/NodePicker/components/NodePickerNodeGroup/NodePickerNodeGroup.module.scss"],"names":[],"mappings":"AAAA,yCACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,iBAAA,CACA,SAAA,CACA,qBAAA,CAGF,kDACE,qBAAA,CACA,oBAAA,CACA,kBAAA","sourcesContent":[".Root {\n  display: flex;\n  flex-direction: column;\n  margin-block-end: 0;\n  position: relative;\n  z-index: 1;\n  padding: 0px 14px 10px;\n}\n\n.ItemContainer {\n  box-sizing: border-box;\n  list-style-type: none;\n  padding-bottom: 8px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `NodePickerNodeGroup-module__Root--tiLUD`,
	"ItemContainer": `NodePickerNodeGroup-module__ItemContainer--lAwbz`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 26170:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCaretUp = function SvgCaretUp(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M13.392 10.2073C13.0991 9.91436 12.6242 9.91436 12.3313 10.2073L7.98547 14.5531C7.69257 14.846 7.69257 15.3209 7.98547 15.6138C8.27836 15.9067 8.75323 15.9067 9.04613 15.6138L12.8617 11.7982L16.6772 15.6138C16.9701 15.9067 17.445 15.9067 17.7378 15.6138C18.0307 15.3209 18.0307 14.846 17.7378 14.5531L13.392 10.2073Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCaretUp);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "1480663a3807ee286a897a092dc0e095.svg");

/***/ }),

/***/ 26225:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   X: () => (/* binding */ CustomPropertyAnimation),
/* harmony export */   l: () => (/* binding */ useCustomPropertyValue)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

var CustomPropertyAnimation;
(function (CustomPropertyAnimation) {
    CustomPropertyAnimation["EasingBase"] = "--easing-base";
    CustomPropertyAnimation["EasingEqual"] = "--easing-equal";
    CustomPropertyAnimation["SpeedQuick"] = "--speed-quick";
    CustomPropertyAnimation["SpeedBase"] = "--speed-base";
    CustomPropertyAnimation["SpeedSlow"] = "--speed-slow";
})(CustomPropertyAnimation || (CustomPropertyAnimation = {}));
function useCustomPropertyValue(propertyName) {
    const styles = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => getComputedStyle(document.documentElement), []);
    const style = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => {
        const temp = styles.getPropertyValue(propertyName);
        switch (propertyName) {
            case CustomPropertyAnimation.SpeedQuick:
            case CustomPropertyAnimation.SpeedBase:
            case CustomPropertyAnimation.SpeedSlow:
                return parseInt(temp);
            default:
                return temp;
        }
    }, [styles]);
    return style;
}


/***/ }),

/***/ 26454:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgImportLeft = function SvgImportLeft(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M10.6367 4.10107C10.6367 4.51529 10.3009 4.85107 9.88672 4.85107L4.63672 4.85108L4.63672 19.8511L9.88672 19.8511C10.3009 19.8511 10.6367 20.1869 10.6367 20.6011C10.6367 21.0153 10.3009 21.3511 9.88672 21.3511L4.63672 21.3511C4.2389 21.3511 3.85737 21.193 3.57606 20.9117C3.29475 20.6304 3.13672 20.2489 3.13672 19.8511L3.13672 4.85108C3.13672 4.45325 3.29475 4.07172 3.57606 3.79042C3.85736 3.50911 4.23889 3.35108 4.63672 3.35108L9.88672 3.35107C10.3009 3.35107 10.6367 3.68686 10.6367 4.10107Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M14.3567 16.8261C14.6467 16.5361 14.6467 16.0561 14.3567 15.7661L11.6967 13.1061L20.3867 13.1061C20.7967 13.1061 21.1367 12.7661 21.1367 12.3561C21.1367 11.9461 20.7967 11.6061 20.3867 11.6061L11.6967 11.6061L14.3567 8.94608C14.6467 8.65608 14.6467 8.17608 14.3567 7.88608C14.0667 7.59608 13.5867 7.59608 13.2967 7.88608L9.35672 11.8261C9.28672 11.8961 9.23672 11.9761 9.19672 12.0661C9.11672 12.2461 9.11672 12.4561 9.19672 12.6361C9.23672 12.7261 9.28672 12.8061 9.35672 12.8761L13.2967 16.8161C13.5867 17.1061 14.0667 17.1061 14.3567 16.8161L14.3567 16.8261Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgImportLeft);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "b36f66f703e5ed211e32169a53a1707c.svg");

/***/ }),

/***/ 26511:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.NodePickerOtherItem-module__Root--NbrRN::before{position:absolute;top:0;bottom:0;right:0;left:0}.NodePickerOtherItem-module__Root--NbrRN{padding:10px 0;position:relative;cursor:pointer}.NodePickerOtherItem-module__Root--NbrRN::before{content:"";opacity:0;pointer-events:none;background-color:var(--theme-color-node-logic-dim)}.NodePickerOtherItem-module__Root--is-highlighted--iA3qw::before{opacity:.2}.NodePickerOtherItem-module__Header--RWQl4{padding:5px 11px 4px;border:0px solid rgba(0,0,0,0);border-left-width:2px;cursor:pointer;height:40px;box-sizing:border-box;display:flex;position:relative;align-items:center}.NodePickerOtherItem-module__Title--wd_2C{font-size:12px;line-height:13px;letter-spacing:2%;padding:0;padding-bottom:1px;margin:0;color:var(--theme-color-fg-highlight);font-weight:600}.NodePickerOtherItem-module__Description--kj9et{padding:0;margin:0;color:var(--theme-color-fg-default);font-weight:400;font-size:11px;line-height:1;opacity:.65}`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/placeholders/util.scss","webpack://./src/editor/src/views/NodePicker/components/NodePickerOtherItem/NodePickerOtherItem.module.scss"],"names":[],"mappings":"AAAA,iDACE,iBAAA,CACA,KAAA,CACA,QAAA,CACA,OAAA,CACA,MAAA,CCHF,yCACE,cAAA,CACA,iBAAA,CACA,cAAA,CAEA,iDAEE,UAAA,CACA,SAAA,CACA,mBAAA,CACA,kDAAA,CAIA,iEACE,UAAA,CAKN,2CACE,oBAAA,CACA,8BAAA,CACA,qBAAA,CACA,cAAA,CACA,WAAA,CACA,qBAAA,CACA,YAAA,CACA,iBAAA,CACA,kBAAA,CAGF,0CACE,cAAA,CACA,gBAAA,CACA,iBAAA,CACA,SAAA,CACA,kBAAA,CACA,QAAA,CACA,qCAAA,CACA,eAAA,CAGF,gDACE,SAAA,CACA,QAAA,CACA,mCAAA,CACA,eAAA,CACA,cAAA,CACA,aAAA,CACA,WAAA","sourcesContent":["%overlay {\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  right: 0;\n  left: 0;\n}\n\n%reset-styles {\n  padding: 0;\n  margin: 0;\n  list-style: none;\n  border: none;\n  border-radius: 0;\n}\n","@use '@scss-placeholders/util';\n\n.Root {\n  padding: 10px 0;\n  position: relative;\n  cursor: pointer;\n\n  &::before {\n    @extend %overlay;\n    content: '';\n    opacity: 0;\n    pointer-events: none;\n    background-color: var(--theme-color-node-logic-dim);\n  }\n\n  &--is-highlighted {\n    &::before {\n      opacity: 0.2;\n    }\n  }\n}\n\n.Header {\n  padding: 5px 11px 4px;\n  border: 0px solid transparent;\n  border-left-width: 2px;\n  cursor: pointer;\n  height: 40px;\n  box-sizing: border-box;\n  display: flex;\n  position: relative;\n  align-items: center;\n}\n\n.Title {\n  font-size: 12px;\n  line-height: 13px;\n  letter-spacing: 2%;\n  padding: 0;\n  padding-bottom: 1px;\n  margin: 0;\n  color: var(--theme-color-fg-highlight);\n  font-weight: 600;\n}\n\n.Description {\n  padding: 0;\n  margin: 0;\n  color: var(--theme-color-fg-default);\n  font-weight: 400;\n  font-size: 11px;\n  line-height: 1;\n  opacity: 0.65;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `NodePickerOtherItem-module__Root--NbrRN`,
	"Root--is-highlighted": `NodePickerOtherItem-module__Root--is-highlighted--iA3qw`,
	"Header": `NodePickerOtherItem-module__Header--RWQl4`,
	"Title": `NodePickerOtherItem-module__Title--wd_2C`,
	"Description": `NodePickerOtherItem-module__Description--kj9et`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 26732:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const { Patches } = __webpack_require__(21977);

function _applyPatch(node, p) {
  if (p.typename) node.typename = p.typename;
  if (p.version) node.version = p.version;
  for (var name in p.params) {
    var value = p.params[name];
    if (value === null) node.parameters[name] = undefined;
    else node.parameters[name] = value;
  }
  if (p.portsToDelete) {
    for (const name of p.portsToDelete) {
      var idx = node.ports.findIndex((p) => p.name === name);
      if (idx !== -1) {
        node.ports.splice(idx, 1);
      }
    }
  }
}

function _applyPatches(node, patchSets) {
  for (const patchSet of patchSets) {
    for (const patch of patchSet.patches) {
      if (patch.condition(node)) {
        const patchData = patch.generatePatch(node);
        _applyPatch(node, patchData);
      }
    }
  }
}

function _applyPatchesRecursive(node, patchSets) {
  _applyPatches(node, patchSets);
  node.children &&
    node.children.forEach((child) => {
      _applyPatchesRecursive(child, patchSets);
    });
}

module.exports = {
  applyPatches: function (projectJSON, patchSets = Patches) {
    //iterate through all nodes
    projectJSON.components.forEach((component) => {
      component.graph &&
        component.graph.roots &&
        component.graph.roots.forEach((node) => {
          _applyPatchesRecursive(node, patchSets);
        });
    });
  }
};


/***/ }),

/***/ 26768:
/***/ ((module) => {

// Module
var code = "<div style=\"position:relative;height:170px\"> <div data-template=\"dim-input\" data-comp=\"width\" style=\"position:relative;width:50%;height:35px;display:inline-block\"> <label class=\"property-label\" style=\"left:3px;width:10px\" data-text=\"label\"></label> <div class=\"property-value\" style=\"left:20px;right:45px\"> <input type=\"string\" class=\"sidebar-panel-dark-input\" style=\"position:absolute;width:100%;height:100%\" data-val=\"value\" data-class=\"isConnected:property-input-connected,isFocused:property-input-focused,isDefault:property-input-default\" data-change=\"onPropertyChanged\"> </div> <div class=\"sidebar-panel-dark-input property-number-units\" style=\"position:absolute;right:10px;width:33px;top:1px;bottom:1px;padding:0\" data-click=\"onDropDownClicked\" tabindex=\"1\"> <span data-class=\"isFocused:property-input-focused,isDefault:property-input-default\" style=\"line-height:35px\" data-text=\"unit\"></span> <div style=\"position:absolute;top:35px;left:0;width:100%;display:none\" class=\"property-input-dropdown\" style=\"display:none\"> </div> </div> </div> <div class=\"marginpadding-border\" style=\"position:absolute;top:10px;left:20px;width:80px;height:80px\"> <div class=\"resizing-left resizing-hline\" style=\"position:absolute;left:5px;top:30px;width:10px;height:20px\" data-pin=\"pinLeft\" data-click=\"onPinClicked\"></div> <div class=\"resizing-right resizing-hline\" style=\"position:absolute;right:5px;top:30px;width:10px;height:20px\" data-pin=\"pinRight\" data-click=\"onPinClicked\"></div> <div class=\"resizing-top resizing-vline\" style=\"position:absolute;top:5px;left:30px;width:20px;height:10px\" data-pin=\"pinTop\" data-click=\"onPinClicked\"></div> <div class=\"resizing-bottom resizing-vline\" style=\"position:absolute;bottom:5px;left:30px;width:20px;height:10px\" data-pin=\"pinBottom\" data-click=\"onPinClicked\"></div> <div class=\"resizing-hline\" style=\"position:absolute;bottom:35px;left:20px;width:40px;height:10px\" data-pin=\"pinVCenter\" data-click=\"onPinClicked\"></div> <div class=\"resizing-vline\" style=\"position:absolute;left:35px;bottom:20px;height:40px;width:10px\" data-pin=\"pinHCenter\" data-click=\"onPinClicked\"></div> </div> <div class=\"resizing-label\" style=\"position:absolute;left:20px;top:100px;width:80px;height:10px\"> Pinning </div> <div class=\"marginpadding-border\" style=\"position:absolute;top:10px;right:20px;width:80px;height:80px\"> <div class=\"sizemode-v resizing-top resizing-bottom resizing-vline\" style=\"position:absolute;top:5px;left:30px;width:20px;height:70px\" data-pin=\"sizeHeight\" data-click=\"onPinClicked\"></div> <div class=\"sizemode-h resizing-left resizing-right resizing-hline\" style=\"position:absolute;top:30px;left:5px;width:70px;height:20px\" data-pin=\"sizeWidth\" data-click=\"onPinClicked\"></div> </div> <div class=\"resizing-label\" style=\"position:absolute;right:20px;top:100px;width:80px;height:10px\"> Sizing </div> <div class=\"dims\" style=\"position:absolute;left:10px;right:10px;top:130px;height:35px\"> </div> </div>";
// Exports
module.exports = code;

/***/ }),

/***/ 26864:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/* Find widget */
.monaco-editor .find-widget {
	position: absolute;
	z-index: 35;
	height: 33px;
	overflow: hidden;
	line-height: 19px;
	transition: transform 200ms linear;
	padding: 0 4px;
	box-sizing: border-box;
	transform: translateY(calc(-100% - 10px)); /* shadow (10px) */
}

.monaco-workbench.reduce-motion .monaco-editor .find-widget {
	transition: transform 0ms linear;
}

.monaco-editor .find-widget textarea {
	margin: 0px;
}

.monaco-editor .find-widget.hiddenEditor {
	display: none;
}

/* Find widget when replace is toggled on */
.monaco-editor .find-widget.replaceToggled > .replace-part {
	display: flex;
}

.monaco-editor .find-widget.visible  {
	transform: translateY(0);
}

.monaco-editor .find-widget .monaco-inputbox.synthetic-focus {
	outline: 1px solid -webkit-focus-ring-color;
	outline-offset: -1px;
}

.monaco-editor .find-widget .monaco-inputbox .input {
	background-color: transparent;
	min-height: 0;
}

.monaco-editor .find-widget .monaco-findInput .input {
	font-size: 13px;
}

.monaco-editor .find-widget > .find-part,
.monaco-editor .find-widget > .replace-part {
	margin: 4px 0 0 17px;
	font-size: 12px;
	display: flex;
}

.monaco-editor .find-widget > .find-part .monaco-inputbox,
.monaco-editor .find-widget > .replace-part .monaco-inputbox {
	min-height: 25px;
}


.monaco-editor .find-widget > .replace-part .monaco-inputbox > .ibwrapper > .mirror {
	padding-right: 22px;
}

.monaco-editor .find-widget > .find-part .monaco-inputbox > .ibwrapper > .input,
.monaco-editor .find-widget > .find-part .monaco-inputbox > .ibwrapper > .mirror,
.monaco-editor .find-widget > .replace-part .monaco-inputbox > .ibwrapper > .input,
.monaco-editor .find-widget > .replace-part .monaco-inputbox > .ibwrapper > .mirror {
	padding-top: 2px;
	padding-bottom: 2px;
}

.monaco-editor .find-widget > .find-part .find-actions {
	height: 25px;
	display: flex;
	align-items: center;
}

.monaco-editor .find-widget > .replace-part .replace-actions {
	height: 25px;
	display: flex;
	align-items: center;
}

.monaco-editor .find-widget .monaco-findInput {
	vertical-align: middle;
	display: flex;
	flex:1;
}

.monaco-editor .find-widget .monaco-findInput .monaco-scrollable-element {
	/* Make sure textarea inherits the width correctly */
	width: 100%;
}

.monaco-editor .find-widget .monaco-findInput .monaco-scrollable-element .scrollbar.vertical {
	/* Hide vertical scrollbar */
	opacity: 0;
}

.monaco-editor .find-widget .matchesCount {
	display: flex;
	flex: initial;
	margin: 0 0 0 3px;
	padding: 2px 0 0 2px;
	height: 25px;
	vertical-align: middle;
	box-sizing: border-box;
	text-align: center;
	line-height: 23px;
}

.monaco-editor .find-widget .button {
	width: 16px;
	height: 16px;
	padding: 3px;
	border-radius: 5px;
	display: flex;
	flex: initial;
	margin-left: 3px;
	background-position: center center;
	background-repeat: no-repeat;
	cursor: pointer;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* find in selection button */
.monaco-editor .find-widget .codicon-find-selection {
	width: 22px;
	height: 22px;
	padding: 3px;
	border-radius: 5px;
}

.monaco-editor .find-widget .button.left {
	margin-left: 0;
	margin-right: 3px;
}

.monaco-editor .find-widget .button.wide {
	width: auto;
	padding: 1px 6px;
	top: -1px;
}

.monaco-editor .find-widget .button.toggle {
	position: absolute;
	top: 0;
	left: 3px;
	width: 18px;
	height: 100%;
	border-radius: 0;
	box-sizing: border-box;
}

.monaco-editor .find-widget .button.toggle.disabled {
	display: none;
}

.monaco-editor .find-widget .disabled {
	color: var(--vscode-disabledForeground);
	cursor: default;
}

.monaco-editor .find-widget > .replace-part {
	display: none;
}

.monaco-editor .find-widget > .replace-part > .monaco-findInput {
	position: relative;
	display: flex;
	vertical-align: middle;
	flex: auto;
	flex-grow: 0;
	flex-shrink: 0;
}

.monaco-editor .find-widget > .replace-part > .monaco-findInput > .controls {
	position: absolute;
	top: 3px;
	right: 2px;
}

/* REDUCED */
.monaco-editor .find-widget.reduced-find-widget .matchesCount {
	display:none;
}

/* NARROW (SMALLER THAN REDUCED) */
.monaco-editor .find-widget.narrow-find-widget {
	max-width: 257px !important;
}

/* COLLAPSED (SMALLER THAN NARROW) */
.monaco-editor .find-widget.collapsed-find-widget {
	max-width: 170px !important;
}

.monaco-editor .find-widget.collapsed-find-widget .button.previous,
.monaco-editor .find-widget.collapsed-find-widget .button.next,
.monaco-editor .find-widget.collapsed-find-widget .button.replace,
.monaco-editor .find-widget.collapsed-find-widget .button.replace-all,
.monaco-editor .find-widget.collapsed-find-widget > .find-part .monaco-findInput .controls {
	display:none;
}

.monaco-editor .findMatch {
	animation-duration: 0;
	animation-name: inherit !important;
}

.monaco-editor .find-widget .monaco-sash {
	left: 0 !important;
}

.monaco-editor.hc-black .find-widget .button:before {
	position: relative;
	top: 1px;
	left: 2px;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/find/browser/findWidget.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F,gBAAgB;AAChB;CACC,kBAAkB;CAClB,WAAW;CACX,YAAY;CACZ,gBAAgB;CAChB,iBAAiB;CACjB,kCAAkC;CAClC,cAAc;CACd,sBAAsB;CACtB,yCAAyC,EAAE,kBAAkB;AAC9D;;AAEA;CACC,gCAAgC;AACjC;;AAEA;CACC,WAAW;AACZ;;AAEA;CACC,aAAa;AACd;;AAEA,2CAA2C;AAC3C;CACC,aAAa;AACd;;AAEA;CACC,wBAAwB;AACzB;;AAEA;CACC,2CAA2C;CAC3C,oBAAoB;AACrB;;AAEA;CACC,6BAA6B;CAC7B,aAAa;AACd;;AAEA;CACC,eAAe;AAChB;;AAEA;;CAEC,oBAAoB;CACpB,eAAe;CACf,aAAa;AACd;;AAEA;;CAEC,gBAAgB;AACjB;;;AAGA;CACC,mBAAmB;AACpB;;AAEA;;;;CAIC,gBAAgB;CAChB,mBAAmB;AACpB;;AAEA;CACC,YAAY;CACZ,aAAa;CACb,mBAAmB;AACpB;;AAEA;CACC,YAAY;CACZ,aAAa;CACb,mBAAmB;AACpB;;AAEA;CACC,sBAAsB;CACtB,aAAa;CACb,MAAM;AACP;;AAEA;CACC,oDAAoD;CACpD,WAAW;AACZ;;AAEA;CACC,4BAA4B;CAC5B,UAAU;AACX;;AAEA;CACC,aAAa;CACb,aAAa;CACb,iBAAiB;CACjB,oBAAoB;CACpB,YAAY;CACZ,sBAAsB;CACtB,sBAAsB;CACtB,kBAAkB;CAClB,iBAAiB;AAClB;;AAEA;CACC,WAAW;CACX,YAAY;CACZ,YAAY;CACZ,kBAAkB;CAClB,aAAa;CACb,aAAa;CACb,gBAAgB;CAChB,kCAAkC;CAClC,4BAA4B;CAC5B,eAAe;CACf,aAAa;CACb,mBAAmB;CACnB,uBAAuB;AACxB;;AAEA,6BAA6B;AAC7B;CACC,WAAW;CACX,YAAY;CACZ,YAAY;CACZ,kBAAkB;AACnB;;AAEA;CACC,cAAc;CACd,iBAAiB;AAClB;;AAEA;CACC,WAAW;CACX,gBAAgB;CAChB,SAAS;AACV;;AAEA;CACC,kBAAkB;CAClB,MAAM;CACN,SAAS;CACT,WAAW;CACX,YAAY;CACZ,gBAAgB;CAChB,sBAAsB;AACvB;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,uCAAuC;CACvC,eAAe;AAChB;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,kBAAkB;CAClB,aAAa;CACb,sBAAsB;CACtB,UAAU;CACV,YAAY;CACZ,cAAc;AACf;;AAEA;CACC,kBAAkB;CAClB,QAAQ;CACR,UAAU;AACX;;AAEA,YAAY;AACZ;CACC,YAAY;AACb;;AAEA,kCAAkC;AAClC;CACC,2BAA2B;AAC5B;;AAEA,oCAAoC;AACpC;CACC,2BAA2B;AAC5B;;AAEA;;;;;CAKC,YAAY;AACb;;AAEA;CACC,qBAAqB;CACrB,kCAAkC;AACnC;;AAEA;CACC,kBAAkB;AACnB;;AAEA;CACC,kBAAkB;CAClB,QAAQ;CACR,SAAS;AACV","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/* Find widget */\n.monaco-editor .find-widget {\n\tposition: absolute;\n\tz-index: 35;\n\theight: 33px;\n\toverflow: hidden;\n\tline-height: 19px;\n\ttransition: transform 200ms linear;\n\tpadding: 0 4px;\n\tbox-sizing: border-box;\n\ttransform: translateY(calc(-100% - 10px)); /* shadow (10px) */\n}\n\n.monaco-workbench.reduce-motion .monaco-editor .find-widget {\n\ttransition: transform 0ms linear;\n}\n\n.monaco-editor .find-widget textarea {\n\tmargin: 0px;\n}\n\n.monaco-editor .find-widget.hiddenEditor {\n\tdisplay: none;\n}\n\n/* Find widget when replace is toggled on */\n.monaco-editor .find-widget.replaceToggled > .replace-part {\n\tdisplay: flex;\n}\n\n.monaco-editor .find-widget.visible  {\n\ttransform: translateY(0);\n}\n\n.monaco-editor .find-widget .monaco-inputbox.synthetic-focus {\n\toutline: 1px solid -webkit-focus-ring-color;\n\toutline-offset: -1px;\n}\n\n.monaco-editor .find-widget .monaco-inputbox .input {\n\tbackground-color: transparent;\n\tmin-height: 0;\n}\n\n.monaco-editor .find-widget .monaco-findInput .input {\n\tfont-size: 13px;\n}\n\n.monaco-editor .find-widget > .find-part,\n.monaco-editor .find-widget > .replace-part {\n\tmargin: 4px 0 0 17px;\n\tfont-size: 12px;\n\tdisplay: flex;\n}\n\n.monaco-editor .find-widget > .find-part .monaco-inputbox,\n.monaco-editor .find-widget > .replace-part .monaco-inputbox {\n\tmin-height: 25px;\n}\n\n\n.monaco-editor .find-widget > .replace-part .monaco-inputbox > .ibwrapper > .mirror {\n\tpadding-right: 22px;\n}\n\n.monaco-editor .find-widget > .find-part .monaco-inputbox > .ibwrapper > .input,\n.monaco-editor .find-widget > .find-part .monaco-inputbox > .ibwrapper > .mirror,\n.monaco-editor .find-widget > .replace-part .monaco-inputbox > .ibwrapper > .input,\n.monaco-editor .find-widget > .replace-part .monaco-inputbox > .ibwrapper > .mirror {\n\tpadding-top: 2px;\n\tpadding-bottom: 2px;\n}\n\n.monaco-editor .find-widget > .find-part .find-actions {\n\theight: 25px;\n\tdisplay: flex;\n\talign-items: center;\n}\n\n.monaco-editor .find-widget > .replace-part .replace-actions {\n\theight: 25px;\n\tdisplay: flex;\n\talign-items: center;\n}\n\n.monaco-editor .find-widget .monaco-findInput {\n\tvertical-align: middle;\n\tdisplay: flex;\n\tflex:1;\n}\n\n.monaco-editor .find-widget .monaco-findInput .monaco-scrollable-element {\n\t/* Make sure textarea inherits the width correctly */\n\twidth: 100%;\n}\n\n.monaco-editor .find-widget .monaco-findInput .monaco-scrollable-element .scrollbar.vertical {\n\t/* Hide vertical scrollbar */\n\topacity: 0;\n}\n\n.monaco-editor .find-widget .matchesCount {\n\tdisplay: flex;\n\tflex: initial;\n\tmargin: 0 0 0 3px;\n\tpadding: 2px 0 0 2px;\n\theight: 25px;\n\tvertical-align: middle;\n\tbox-sizing: border-box;\n\ttext-align: center;\n\tline-height: 23px;\n}\n\n.monaco-editor .find-widget .button {\n\twidth: 16px;\n\theight: 16px;\n\tpadding: 3px;\n\tborder-radius: 5px;\n\tdisplay: flex;\n\tflex: initial;\n\tmargin-left: 3px;\n\tbackground-position: center center;\n\tbackground-repeat: no-repeat;\n\tcursor: pointer;\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n}\n\n/* find in selection button */\n.monaco-editor .find-widget .codicon-find-selection {\n\twidth: 22px;\n\theight: 22px;\n\tpadding: 3px;\n\tborder-radius: 5px;\n}\n\n.monaco-editor .find-widget .button.left {\n\tmargin-left: 0;\n\tmargin-right: 3px;\n}\n\n.monaco-editor .find-widget .button.wide {\n\twidth: auto;\n\tpadding: 1px 6px;\n\ttop: -1px;\n}\n\n.monaco-editor .find-widget .button.toggle {\n\tposition: absolute;\n\ttop: 0;\n\tleft: 3px;\n\twidth: 18px;\n\theight: 100%;\n\tborder-radius: 0;\n\tbox-sizing: border-box;\n}\n\n.monaco-editor .find-widget .button.toggle.disabled {\n\tdisplay: none;\n}\n\n.monaco-editor .find-widget .disabled {\n\tcolor: var(--vscode-disabledForeground);\n\tcursor: default;\n}\n\n.monaco-editor .find-widget > .replace-part {\n\tdisplay: none;\n}\n\n.monaco-editor .find-widget > .replace-part > .monaco-findInput {\n\tposition: relative;\n\tdisplay: flex;\n\tvertical-align: middle;\n\tflex: auto;\n\tflex-grow: 0;\n\tflex-shrink: 0;\n}\n\n.monaco-editor .find-widget > .replace-part > .monaco-findInput > .controls {\n\tposition: absolute;\n\ttop: 3px;\n\tright: 2px;\n}\n\n/* REDUCED */\n.monaco-editor .find-widget.reduced-find-widget .matchesCount {\n\tdisplay:none;\n}\n\n/* NARROW (SMALLER THAN REDUCED) */\n.monaco-editor .find-widget.narrow-find-widget {\n\tmax-width: 257px !important;\n}\n\n/* COLLAPSED (SMALLER THAN NARROW) */\n.monaco-editor .find-widget.collapsed-find-widget {\n\tmax-width: 170px !important;\n}\n\n.monaco-editor .find-widget.collapsed-find-widget .button.previous,\n.monaco-editor .find-widget.collapsed-find-widget .button.next,\n.monaco-editor .find-widget.collapsed-find-widget .button.replace,\n.monaco-editor .find-widget.collapsed-find-widget .button.replace-all,\n.monaco-editor .find-widget.collapsed-find-widget > .find-part .monaco-findInput .controls {\n\tdisplay:none;\n}\n\n.monaco-editor .findMatch {\n\tanimation-duration: 0;\n\tanimation-name: inherit !important;\n}\n\n.monaco-editor .find-widget .monaco-sash {\n\tleft: 0 !important;\n}\n\n.monaco-editor.hc-black .find-widget .button:before {\n\tposition: relative;\n\ttop: 1px;\n\tleft: 2px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 27183:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.AiIconAnimated-module__Root--_XK0U{filter:brightness(150%);padding:6px;transition:filter var(--speed-quick) var(--easing-base);width:30px;height:30px;mix-blend-mode:lighten}.AiIconAnimated-module__Root--_XK0U.AiIconAnimated-module____isDimmed--cTtV7{filter:brightness(110%)}.AiIconAnimated-module__Root--_XK0U span{font-family:var(--font-family);user-select:none}.AiIconAnimated-module__HeroLogoWrapper--uDG3Y{position:relative;overflow:hidden;background-color:inherit;opacity:1}.AiIconAnimated-module__HeroLogoWrapper--uDG3Y:after{content:"";position:absolute;top:-3px;left:-3px;right:-3px;bottom:-3px;background:linear-gradient(0deg, var(--base-color-teal-400) 0%, var(--base-color-node-purple-600)) 45%;animation:AiIconAnimated-module__circle--TzDZ1 3s linear infinite;filter:saturate(120%) brightness(120%)}@keyframes AiIconAnimated-module__circle--TzDZ1{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}.AiIconAnimated-module__HeroLogoWrapper--uDG3Y>.AiIconAnimated-module__LogoIdleCircle--H0prV{box-shadow:0 0 10px 10px #fff}.AiIconAnimated-module__HeroLogo--YVy4w{width:30px;height:30px;display:flex;align-items:center;justify-content:center;opacity:1;position:relative;z-index:1;background:#000;mix-blend-mode:multiply}.AiIconAnimated-module__HeroLogo--YVy4w>span{color:#fff;text-transform:uppercase;font-size:15px;font-weight:var(--font-weight-semibold)}.AiIconAnimated-module__LogoIdleCircleContainer--zXtfS{position:absolute;width:23px;height:23px;top:0;left:0;transform:scale(1);transition:transform var(--speed-quick) var(--easing-base)}.AiIconAnimated-module__Root--_XK0U.AiIconAnimated-module____isListening--GiWV4 .AiIconAnimated-module__LogoIdleCircleContainer--zXtfS{transform:scale(0)}.AiIconAnimated-module__LogoIdleCircleInner--MP0pf{position:absolute;top:0px;left:0px;width:23px;height:23px;animation:AiIconAnimated-module__shine--zZNbf 5s var(--easing-base) infinite}.AiIconAnimated-module__LogoIdleCircle--H0prV{position:absolute;border:4px dotted #fff;width:22px;height:22px;border-radius:50%;animation:AiIconAnimated-module__round--ZxHez 100s linear infinite reverse;opacity:.6}@keyframes AiIconAnimated-module__shine--zZNbf{0%,50%{transform:scale(1);filter:blur(0px) brightness(100%)}25%{transform:scale(0.95);filter:blur(0.5px) brightness(200%) saturate(200%)}}.AiIconAnimated-module__LogoLoader--ZYF8e{position:absolute;width:100%;height:100%;animation:AiIconAnimated-module__round--ZxHez 40s linear infinite}.AiIconAnimated-module__LogoLoaderInner--Heb4b{position:absolute;top:7px;left:7px;width:100%;height:100%;transform:scale(0);transition:transform var(--speed-quick) var(--easing-base)}.AiIconAnimated-module__Root--_XK0U.AiIconAnimated-module____isListening--GiWV4 .AiIconAnimated-module__LogoLoaderInner--Heb4b{transform:scale(1)}.AiIconAnimated-module__Circle1--y3K_C{position:absolute;transform:rotate(45deg)}.AiIconAnimated-module__Circle2--PCDHX{position:absolute;transform:rotate(225deg)}.AiIconAnimated-module__SpinningBalls--tWPYm{color:#fff;font-size:16px;text-indent:-9999em;overflow:hidden;width:1em;height:1em;border-radius:50%;position:relative;transform:translateZ(0);animation:AiIconAnimated-module__mltShdSpin--eyyZU 2.5s infinite ease,AiIconAnimated-module__round--ZxHez 2.5s infinite ease;display:block}@keyframes AiIconAnimated-module__mltShdSpin--eyyZU{0%{box-shadow:0 -0.83em 0 -4em,0 -0.83em 0 -0.42em,0 -0.83em 0 -0.44em,0 -0.83em 0 -0.46em,0 -0.83em 0 -0.477em}5%,95%{box-shadow:0 -0.83em 0 -0.4em,0 -0.83em 0 -0.42em,0 -0.83em 0 -0.44em,0 -0.83em 0 -0.46em,0 -0.83em 0 -0.477em}10%,59%{box-shadow:0 -0.83em 0 -0.4em,-0.087em -0.825em 0 -0.42em,-0.173em -0.812em 0 -0.44em,-0.256em -0.789em 0 -0.46em,-0.297em -0.775em 0 -0.477em}20%{box-shadow:0 -0.83em 0 -0.4em,-0.338em -0.758em 0 -0.42em,-0.555em -0.617em 0 -0.44em,-0.671em -0.488em 0 -0.46em,-0.749em -0.34em 0 -0.477em}38%{box-shadow:0 -0.83em 0 -0.4em,-0.377em -0.74em 0 -0.42em,-0.645em -0.522em 0 -0.44em,-0.775em -0.297em 0 -0.46em,-0.82em -0.09em 0 -0.477em}100%{box-shadow:0 -0.83em 0 -0.4em,0 -0.83em 0 -0.42em,0 -0.83em 0 -0.44em,0 -0.83em 0 -0.46em,0 -0.83em 0 -0.477em}}@keyframes AiIconAnimated-module__round-half--Ju6nP{0%{transform:rotate(0deg)}50%,100%{transform:rotate(360deg)}}@keyframes AiIconAnimated-module__round--ZxHez{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/ai/AiIconAnimated/AiIconAnimated.module.scss"],"names":[],"mappings":"AAAA,oCAGE,uBAAA,CACA,WAAA,CACA,uDAAA,CAEA,UAAA,CACA,WAAA,CACA,sBAAA,CAEA,6EACE,uBAAA,CAGF,yCACE,8BAAA,CACA,gBAAA,CAIJ,+CACE,iBAAA,CACA,eAAA,CACA,wBAAA,CACA,SAAA,CAEA,qDACE,UAAA,CACA,iBAAA,CACA,QAAA,CACA,SAAA,CACA,UAAA,CACA,WAAA,CACA,sGAAA,CACA,iEAAA,CACA,sCAAA,CAIJ,gDACE,KACE,sBAAA,CAGF,GACE,wBAAA,CAAA,CAIJ,6FACE,6BAAA,CAGF,wCACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,SAAA,CACA,iBAAA,CACA,SAAA,CACA,eAAA,CACA,uBAAA,CAEA,6CACE,UAAA,CACA,wBAAA,CACA,cAAA,CACA,uCAAA,CAIJ,uDACE,iBAAA,CACA,UAAA,CACA,WAAA,CACA,KAAA,CACA,MAAA,CACA,kBAAA,CACA,0DAAA,CAEA,uIACE,kBAAA,CAIJ,mDACE,iBAAA,CACA,OAAA,CACA,QAAA,CACA,UAAA,CACA,WAAA,CACA,4EAAA,CAGF,8CACE,iBAAA,CACA,sBAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,0EAAA,CACA,UAAA,CAGF,+CACE,OAEE,kBAAA,CACA,iCAAA,CAGF,IACE,qBAAA,CACA,kDAAA,CAAA,CAIJ,0CACE,iBAAA,CACA,UAAA,CACA,WAAA,CACA,iEAAA,CAGF,+CACE,iBAAA,CACA,OAAA,CACA,QAAA,CACA,UAAA,CACA,WAAA,CACA,kBAAA,CACA,0DAAA,CAEA,+HACE,kBAAA,CAIJ,uCACE,iBAAA,CACA,uBAAA,CAGF,uCACE,iBAAA,CACA,wBAAA,CAGF,6CACE,UAAA,CACA,cAAA,CACA,mBAAA,CACA,eAAA,CACA,SAAA,CACA,UAAA,CACA,iBAAA,CACA,iBAAA,CACA,uBAAA,CACA,4HAAA,CACA,aAAA,CAMF,oDACE,GACE,4GAAA,CAIF,OAEE,8GAAA,CAGF,QAEE,8IAAA,CAIF,IACE,6IAAA,CAIF,IACE,2IAAA,CAIF,KACE,8GAAA,CAAA,CAIJ,oDACE,GACE,sBAAA,CAGF,SAEE,wBAAA,CAAA,CAIJ,+CACE,GACE,sBAAA,CAGF,KACE,wBAAA,CAAA","sourcesContent":[".Root {\n  // MIX BLEND MODE LIGTHEN MUST BE SET ON THE PARENT\n  //mix-blend-mode: lighten;\n  filter: brightness(150%);\n  padding: 6px;\n  transition: filter var(--speed-quick) var(--easing-base);\n\n  width: 30px;\n  height: 30px;\n  mix-blend-mode: lighten;\n\n  &.__isDimmed {\n    filter: brightness(110%);\n  }\n\n  span {\n    font-family: var(--font-family);\n    user-select: none;\n  }\n}\n\n.HeroLogoWrapper {\n  position: relative;\n  overflow: hidden;\n  background-color: inherit;\n  opacity: 1;\n\n  &:after {\n    content: '';\n    position: absolute;\n    top: -3px;\n    left: -3px;\n    right: -3px;\n    bottom: -3px;\n    background: linear-gradient(0deg, var(--base-color-teal-400) 0%, var(--base-color-node-purple-600)) 45%;\n    animation: circle 3s linear infinite;\n    filter: saturate(120%) brightness(120%);\n  }\n}\n\n@keyframes circle {\n  from {\n    transform: rotate(0deg);\n  }\n\n  to {\n    transform: rotate(360deg);\n  }\n}\n\n.HeroLogoWrapper > .LogoIdleCircle {\n  box-shadow: 0 0 10px 10px white;\n}\n\n.HeroLogo {\n  width: 30px;\n  height: 30px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  opacity: 1;\n  position: relative;\n  z-index: 1;\n  background: black;\n  mix-blend-mode: multiply;\n\n  > span {\n    color: #ffffff;\n    text-transform: uppercase;\n    font-size: 15px;\n    font-weight: var(--font-weight-semibold);\n  }\n}\n\n.LogoIdleCircleContainer {\n  position: absolute;\n  width: 23px;\n  height: 23px;\n  top: 0;\n  left: 0;\n  transform: scale(1);\n  transition: transform var(--speed-quick) var(--easing-base);\n\n  .Root.__isListening & {\n    transform: scale(0);\n  }\n}\n\n.LogoIdleCircleInner {\n  position: absolute;\n  top: 0px;\n  left: 0px;\n  width: 23px;\n  height: 23px;\n  animation: shine 5s var(--easing-base) infinite;\n}\n\n.LogoIdleCircle {\n  position: absolute;\n  border: 4px dotted white;\n  width: 22px;\n  height: 22px;\n  border-radius: 50%;\n  animation: round 100s linear infinite reverse;\n  opacity: 0.6;\n}\n\n@keyframes shine {\n  0%,\n  50% {\n    transform: scale(1);\n    filter: blur(0px) brightness(100%);\n  }\n\n  25% {\n    transform: scale(0.95);\n    filter: blur(0.5px) brightness(200%) saturate(200%);\n  }\n}\n\n.LogoLoader {\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  animation: round 40s linear infinite;\n}\n\n.LogoLoaderInner {\n  position: absolute;\n  top: 7px;\n  left: 7px;\n  width: 100%;\n  height: 100%;\n  transform: scale(0);\n  transition: transform var(--speed-quick) var(--easing-base);\n\n  .Root.__isListening & {\n    transform: scale(1);\n  }\n}\n\n.Circle1 {\n  position: absolute;\n  transform: rotate(45deg);\n}\n\n.Circle2 {\n  position: absolute;\n  transform: rotate(225deg);\n}\n\n.SpinningBalls {\n  color: #ffffff;\n  font-size: 16px;\n  text-indent: -9999em;\n  overflow: hidden;\n  width: 1em;\n  height: 1em;\n  border-radius: 50%;\n  position: relative;\n  transform: translateZ(0);\n  animation: mltShdSpin 2.5s infinite ease, round 2.5s infinite ease;\n  display: block;\n}\n\n$_val1: calc(-0.83em * 1);\n$_ballSizeMod: 10;\n\n@keyframes mltShdSpin {\n  0% {\n    box-shadow: 0 $_val1 0 calc(-0.4em * $_ballSizeMod), 0 $_val1 0 -0.42em, 0 $_val1 0 -0.44em, 0 $_val1 0 -0.46em,\n      0 $_val1 0 -0.477em;\n  }\n\n  5%,\n  95% {\n    box-shadow: 0 $_val1 0 calc(-0.4em), 0 $_val1 0 -0.42em, 0 $_val1 0 -0.44em, 0 $_val1 0 -0.46em, 0 $_val1 0 -0.477em;\n  }\n\n  10%,\n  59% {\n    box-shadow: 0 $_val1 0 calc(-0.4em), -0.087em -0.825em 0 -0.42em, -0.173em -0.812em 0 -0.44em,\n      -0.256em -0.789em 0 -0.46em, -0.297em -0.775em 0 -0.477em;\n  }\n\n  20% {\n    box-shadow: 0 $_val1 0 calc(-0.4em), -0.338em -0.758em 0 -0.42em, -0.555em -0.617em 0 -0.44em,\n      -0.671em -0.488em 0 -0.46em, -0.749em -0.34em 0 -0.477em;\n  }\n\n  38% {\n    box-shadow: 0 $_val1 0 calc(-0.4em), -0.377em -0.74em 0 -0.42em, -0.645em -0.522em 0 -0.44em,\n      -0.775em -0.297em 0 -0.46em, -0.82em -0.09em 0 -0.477em;\n  }\n\n  100% {\n    box-shadow: 0 $_val1 0 calc(-0.4em), 0 $_val1 0 -0.42em, 0 $_val1 0 -0.44em, 0 $_val1 0 -0.46em, 0 $_val1 0 -0.477em;\n  }\n}\n\n@keyframes round-half {\n  0% {\n    transform: rotate(0deg);\n  }\n\n  50%,\n  100% {\n    transform: rotate(360deg);\n  }\n}\n\n@keyframes round {\n  0% {\n    transform: rotate(0deg);\n  }\n\n  100% {\n    transform: rotate(360deg);\n  }\n}\n\n// @keyframes mltShdSpin {\n//     0% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em * $_ballSizeMod),\n//             0 $_val1 0 -0.42em, 0 $_val1 0 -0.44em,\n//             0 $_val1 0 -0.46em, 0 $_val1 0 -0.477em;\n//     }\n\n//     2.5%,\n//     47.5% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em),\n//             0 $_val1 0 -0.42em, 0 $_val1 0 -0.44em,\n//             0 $_val1 0 -0.46em, 0 $_val1 0 -0.477em;\n//     }\n\n//     5%,\n//     29.5% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em),\n//             -0.087em -0.825em 0 -0.42em, -0.173em -0.812em 0 -0.44em,\n//             -0.256em -0.789em 0 -0.46em, -0.297em -0.775em 0 -0.477em;\n//     }\n\n//     10% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em), -0.338em -0.758em 0 -0.42em,\n//             -0.555em -0.617em 0 -0.44em, -0.671em -0.488em 0 -0.46em,\n//             -0.749em -0.34em 0 -0.477em;\n//     }\n\n//     19% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em), -0.377em -0.74em 0 -0.42em,\n//             -0.645em -0.522em 0 -0.44em, -0.775em -0.297em 0 -0.46em,\n//             -0.82em -0.09em 0 -0.477em;\n//     }\n\n//     50%, 100% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em), 0 $_val1 0 -0.42em,\n//             0 $_val1 0 -0.44em, 0 $_val1 0 -0.46em, 0 $_val1 0 -0.477em;\n//     }\n// }\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `AiIconAnimated-module__Root--_XK0U`,
	"__isDimmed": `AiIconAnimated-module____isDimmed--cTtV7`,
	"HeroLogoWrapper": `AiIconAnimated-module__HeroLogoWrapper--uDG3Y`,
	"circle": `AiIconAnimated-module__circle--TzDZ1`,
	"LogoIdleCircle": `AiIconAnimated-module__LogoIdleCircle--H0prV`,
	"HeroLogo": `AiIconAnimated-module__HeroLogo--YVy4w`,
	"LogoIdleCircleContainer": `AiIconAnimated-module__LogoIdleCircleContainer--zXtfS`,
	"__isListening": `AiIconAnimated-module____isListening--GiWV4`,
	"LogoIdleCircleInner": `AiIconAnimated-module__LogoIdleCircleInner--MP0pf`,
	"shine": `AiIconAnimated-module__shine--zZNbf`,
	"round": `AiIconAnimated-module__round--ZxHez`,
	"LogoLoader": `AiIconAnimated-module__LogoLoader--ZYF8e`,
	"LogoLoaderInner": `AiIconAnimated-module__LogoLoaderInner--Heb4b`,
	"Circle1": `AiIconAnimated-module__Circle1--y3K_C`,
	"Circle2": `AiIconAnimated-module__Circle2--PCDHX`,
	"SpinningBalls": `AiIconAnimated-module__SpinningBalls--tWPYm`,
	"mltShdSpin": `AiIconAnimated-module__mltShdSpin--eyyZU`,
	"round-half": `AiIconAnimated-module__round-half--Ju6nP`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 27252:
/***/ ((module) => {

// Module
var code = "<div class=\"popup confirm-modal\"> <label data-text=\"title\"></label> <p data-html=\"message\"></p> <div class=\"confirm-buttons\"> <button class=\"cancel-button\" data-click=\"onOkClicked\">OK</button> </div> </div>";
// Exports
module.exports = code;

/***/ }),

/***/ 27283:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/* =============================================================================
   NOODL DESIGN SYSTEM - COLORS
   Minimal palette: Red + Black + White
   ============================================================================= */

:root {
  /* ---------------------------------------------------------------------------
     BASE COLORS
     A deliberately minimal palette - one accent, pure neutrals
     --------------------------------------------------------------------------- */

  /* Primary - Noodl Red */
  --base-color-red-100: #fef2f3;
  --base-color-red-200: #fde3e5;
  --base-color-red-300: #fbc5c9;
  --base-color-red-400: #f7969e;
  --base-color-red-500: #ef5662;
  --base-color-red-600: #d21f3c;
  --base-color-red-700: #b91830;
  --base-color-red-800: #9a1729;
  --base-color-red-900: #801827;
  --base-color-red-950: #460a11;

  /* Neutrals - Pure black to white, no color tint */
  --base-color-neutral-0: #000000;
  --base-color-neutral-50: #0a0a0a;
  --base-color-neutral-100: #121212;
  --base-color-neutral-200: #1a1a1a;
  --base-color-neutral-300: #262626;
  --base-color-neutral-400: #333333;
  --base-color-neutral-500: #525252;
  --base-color-neutral-600: #737373;
  --base-color-neutral-700: #a3a3a3;
  --base-color-neutral-800: #d4d4d4;
  --base-color-neutral-900: #e5e5e5;
  --base-color-neutral-950: #f5f5f5;
  --base-color-neutral-1000: #ffffff;

  /* Transparent variants */
  --base-color-black-transparent-90: rgba(0, 0, 0, 0.9);
  --base-color-black-transparent-80: rgba(0, 0, 0, 0.8);
  --base-color-black-transparent-50: rgba(0, 0, 0, 0.5);
  --base-color-white-transparent-10: rgba(255, 255, 255, 0.1);
  --base-color-white-transparent-15: rgba(255, 255, 255, 0.15);
  --base-color-white-transparent-50: rgba(255, 255, 255, 0.5);

  /* ---------------------------------------------------------------------------
     SEMANTIC COLORS (Status indicators)
     --------------------------------------------------------------------------- */

  /* Success - Keeping a green for semantic meaning */
  --base-color-success-100: #ecfdf5;
  --base-color-success-200: #a7f3d0;
  --base-color-success-300: #6ee7b7;
  --base-color-success-400: #34d399;
  --base-color-success-500: #10b981;
  --base-color-success-600: #059669;
  --base-color-success-700: #047857;
  --base-color-success-800: #065f46;
  --base-color-success-900: #064e3b;
  --base-color-success-1000: #022c22;

  /* Error - Uses the brand red */
  --base-color-error-100: var(--base-color-red-100);
  --base-color-error-200: var(--base-color-red-200);
  --base-color-error-300: var(--base-color-red-300);
  --base-color-error-400: var(--base-color-red-400);
  --base-color-error-500: var(--base-color-red-500);
  --base-color-error-600: var(--base-color-red-600);
  --base-color-error-700: var(--base-color-red-700);
  --base-color-error-800: var(--base-color-red-800);
  --base-color-error-900: var(--base-color-red-900);
  --base-color-error-1000: var(--base-color-red-950);

  /* ---------------------------------------------------------------------------
     NODE TYPE COLORS
     Subtle variations to distinguish node types on canvas
     Using desaturated colors so they don't compete with the red accent
     --------------------------------------------------------------------------- */

  /* Node-Pink - For Custom/User nodes */
  --base-color-node-pink-100: #fdf2f8;
  --base-color-node-pink-200: #f5d0e5;
  --base-color-node-pink-300: #e8a8ca;
  --base-color-node-pink-400: #d87caa;
  --base-color-node-pink-500: #c2578a;
  --base-color-node-pink-600: #a63d6f;
  --base-color-node-pink-700: #862d56;
  --base-color-node-pink-800: #6b2445;
  --base-color-node-pink-900: #521c35;
  --base-color-node-pink-1000: #2d0e1c;

  /* Node-Purple - For Component nodes */
  --base-color-node-purple-100: #f8f5fa;
  --base-color-node-purple-200: #e8dff0;
  --base-color-node-purple-300: #d4c4e3;
  --base-color-node-purple-400: #b8a0cf;
  --base-color-node-purple-500: #9a7bb8;
  --base-color-node-purple-600: #7d5a9e;
  --base-color-node-purple-700: #624382;
  --base-color-node-purple-800: #4b3366;
  --base-color-node-purple-900: #37264b;
  --base-color-node-purple-1000: #1e1429;

  /* Node-Green - For Data nodes */
  --base-color-node-green-100: #f4f7f4;
  --base-color-node-green-200: #d8e5d8;
  --base-color-node-green-300: #b5cfb5;
  --base-color-node-green-400: #8eb58e;
  --base-color-node-green-500: #6a996a;
  --base-color-node-green-600: #4d7d4d;
  --base-color-node-green-700: #3a613a;
  --base-color-node-green-800: #2c4a2c;
  --base-color-node-green-900: #203520;
  --base-color-node-green-1000: #111c11;

  /* Node-Gray - For Logic nodes */
  --base-color-node-grey-100: #f5f5f5;
  --base-color-node-grey-200: #e0e0e0;
  --base-color-node-grey-300: #c2c2c2;
  --base-color-node-grey-400: #9e9e9e;
  --base-color-node-grey-500: #757575;
  --base-color-node-grey-600: #5c5c5c;
  --base-color-node-grey-700: #454545;
  --base-color-node-grey-800: #333333;
  --base-color-node-grey-900: #212121;
  --base-color-node-grey-1000: #0d0d0d;

  /* Node-Blue - For Visual nodes */
  --base-color-node-blue-100: #f4f6f8;
  --base-color-node-blue-200: #dce3eb;
  --base-color-node-blue-300: #bccad9;
  --base-color-node-blue-400: #96adc2;
  --base-color-node-blue-500: #7090a9;
  --base-color-node-blue-600: #53758f;
  --base-color-node-blue-700: #3e5a72;
  --base-color-node-blue-800: #2f4557;
  --base-color-node-blue-900: #22323f;
  --base-color-node-blue-1000: #121b22;

  /* ---------------------------------------------------------------------------
     LEGACY ALIASES - For backwards compatibility
     --------------------------------------------------------------------------- */
  
  /* Grey -> Neutral */
  --base-color-grey-100: var(--base-color-neutral-950);
  --base-color-grey-100-transparent: var(--base-color-white-transparent-10);
  --base-color-grey-200: var(--base-color-neutral-800);
  --base-color-grey-300: var(--base-color-neutral-700);
  --base-color-grey-400: var(--base-color-neutral-600);
  --base-color-grey-500: var(--base-color-neutral-500);
  --base-color-grey-600: var(--base-color-neutral-400);
  --base-color-grey-700: var(--base-color-neutral-300);
  --base-color-grey-800: var(--base-color-neutral-200);
  --base-color-grey-900: var(--base-color-neutral-100);
  --base-color-grey-1000: var(--base-color-neutral-50);
  --base-color-grey-1000-transparent: var(--base-color-black-transparent-80);
  --base-color-grey-1000-transparent-2: var(--base-color-black-transparent-50);

  /* Teal -> Neutral (secondary is now white/gray) */
  --base-color-teal-100: var(--base-color-neutral-1000);
  --base-color-teal-200: var(--base-color-neutral-900);
  --base-color-teal-300: var(--base-color-neutral-800);
  --base-color-teal-400: var(--base-color-neutral-700);
  --base-color-teal-500: var(--base-color-neutral-600);
  --base-color-teal-600: var(--base-color-neutral-500);
  --base-color-teal-700: var(--base-color-neutral-400);
  --base-color-teal-800: var(--base-color-neutral-300);
  --base-color-teal-900: var(--base-color-neutral-200);
  --base-color-teal-1000: var(--base-color-neutral-100);

  /* Yellow -> Red (primary is now red) */
  --base-color-yellow-100: var(--base-color-red-100);
  --base-color-yellow-200: var(--base-color-red-200);
  --base-color-yellow-300: var(--base-color-red-400);
  --base-color-yellow-400: var(--base-color-red-500);
  --base-color-yellow-500: var(--base-color-red-600);
  --base-color-yellow-600: var(--base-color-red-700);
  --base-color-yellow-700: var(--base-color-red-800);
  --base-color-yellow-800: var(--base-color-red-900);
  --base-color-yellow-900: var(--base-color-red-950);
  --base-color-yellow-1000: var(--base-color-red-950);
}


/* =============================================================================
   THEME COLOR TOKENS - USE THESE IN COMPONENTS
   ============================================================================= */

:root {
  /* ---------------------------------------------------------------------------
     BACKGROUNDS
     Pure blacks with subtle elevation through lightness
     --------------------------------------------------------------------------- */
  --theme-color-bg-0: #000000;
  --theme-color-bg-1: var(--base-color-neutral-50);
  --theme-color-bg-1-transparent: var(--base-color-black-transparent-80);
  --theme-color-bg-1-transparent-2: var(--base-color-black-transparent-50);
  --theme-color-bg-2: var(--base-color-neutral-100);
  --theme-color-bg-3: var(--base-color-neutral-200);
  --theme-color-bg-4: var(--base-color-neutral-300);
  --theme-color-bg-5: var(--base-color-neutral-400);
  --theme-color-bg-hover: var(--base-color-white-transparent-10);

  /* ---------------------------------------------------------------------------
     FOREGROUNDS
     Pure whites with subtle hierarchy
     --------------------------------------------------------------------------- */
  --theme-color-fg-highlight: #ffffff;
  --theme-color-fg-default-contrast: var(--base-color-neutral-900);
  --theme-color-fg-default: var(--base-color-neutral-800);
  --theme-color-fg-default-shy: var(--base-color-neutral-700);
  --theme-color-fg-muted: var(--base-color-neutral-600);
  --theme-color-fg-transparent: var(--base-color-white-transparent-15);

  /* ---------------------------------------------------------------------------
     PRIMARY - Noodl Red
     The one accent color - used sparingly for maximum impact
     --------------------------------------------------------------------------- */
  --theme-color-primary: #d21f3c;
  --theme-color-primary-highlight: var(--base-color-red-500);
  --theme-color-primary-dim: var(--base-color-red-800);
  --theme-color-on-primary: #ffffff;

  /* ---------------------------------------------------------------------------
     SECONDARY - White/Light
     For secondary actions, using white as the complement to red
     --------------------------------------------------------------------------- */
  --theme-color-secondary: #ffffff;
  --theme-color-secondary-dim: var(--base-color-neutral-700);
  --theme-color-secondary-highlight: #ffffff;
  --theme-color-secondary-bright: #ffffff;
  --theme-color-secondary-as-fg: var(--base-color-neutral-800);
  --theme-color-on-secondary: var(--base-color-neutral-100);

  /* ---------------------------------------------------------------------------
     NODE COLORS
     Muted, desaturated to not compete with the red accent
     --------------------------------------------------------------------------- */

  /* Data nodes - Muted Green */
  --theme-color-node-data-1: var(--base-color-node-green-700);
  --theme-color-node-data-2: var(--base-color-node-green-600);
  --theme-color-node-data-3: var(--base-color-node-green-500);
  --theme-color-node-data-dim: var(--base-color-node-green-900);

  /* Visual nodes - Muted Blue */
  --theme-color-node-visual-1: var(--base-color-node-blue-700);
  --theme-color-node-visual-2: var(--base-color-node-blue-600);
  --theme-color-node-visual-2-highlight: var(--base-color-node-blue-500);
  --theme-color-node-visual-highlight: var(--base-color-node-blue-200);
  --theme-color-node-visual-default: var(--base-color-node-blue-300);
  --theme-color-node-visual-shy: var(--base-color-node-blue-400);
  --theme-color-node-visual-dim: var(--base-color-node-blue-900);

  /* Custom nodes - Muted Pink */
  --theme-color-node-custom-1: var(--base-color-node-pink-700);
  --theme-color-node-custom-2: var(--base-color-node-pink-600);
  --theme-color-node-custom-dim: var(--base-color-node-pink-900);

  /* Logic nodes - Gray */
  --theme-color-node-logic-1: var(--base-color-node-grey-700);
  --theme-color-node-logic-2: var(--base-color-node-grey-600);
  --theme-color-node-logic-dim: var(--base-color-node-grey-900);

  /* Component nodes - Muted Purple */
  --theme-color-node-component-1: var(--base-color-node-purple-700);
  --theme-color-node-component-2: var(--base-color-node-purple-600);
  --theme-color-node-component-dim: var(--base-color-node-purple-900);

  /* ---------------------------------------------------------------------------
     STATUS COLORS
     Success stays green, everything else maps to the palette
     --------------------------------------------------------------------------- */
  --theme-color-success: var(--base-color-success-400);
  --theme-color-success-dim: var(--base-color-success-600);
  --theme-color-success-bg: var(--base-color-success-900);

  --theme-color-notice: var(--base-color-red-400);
  --theme-color-notice-dim: var(--base-color-red-600);
  --theme-color-notice-bg: var(--base-color-red-950);

  --theme-color-danger: var(--base-color-red-500);
  --theme-color-danger-light: var(--base-color-red-400);
  --theme-color-danger-dim: var(--base-color-red-700);
  --theme-color-danger-bg: var(--base-color-red-950);

  /* ---------------------------------------------------------------------------
     CONNECTION COLORS
     --------------------------------------------------------------------------- */
  --theme-color-signal: var(--base-color-red-500);
  --theme-color-data: var(--base-color-neutral-700);

  /* ---------------------------------------------------------------------------
     BORDERS
     Subtle white borders for dark backgrounds
     --------------------------------------------------------------------------- */
  --theme-color-border-default: var(--base-color-neutral-300);
  --theme-color-border-subtle: var(--base-color-neutral-200);
  --theme-color-border-strong: var(--base-color-neutral-400);

  /* ---------------------------------------------------------------------------
     FOCUS
     Red focus ring for accessibility
     --------------------------------------------------------------------------- */
  --theme-color-focus-ring: #d21f3c;
  --theme-color-focus-ring-offset: var(--base-color-neutral-50);
}


/* =============================================================================
   FUTURE: LIGHT THEME
   ============================================================================= 

.theme-light {
  --theme-color-bg-0: #ffffff;
  --theme-color-bg-1: var(--base-color-neutral-950);
  --theme-color-bg-1-transparent: rgba(255, 255, 255, 0.9);
  --theme-color-bg-1-transparent-2: rgba(255, 255, 255, 0.5);
  --theme-color-bg-2: #ffffff;
  --theme-color-bg-3: var(--base-color-neutral-900);
  --theme-color-bg-4: var(--base-color-neutral-800);
  --theme-color-bg-5: var(--base-color-neutral-700);
  --theme-color-bg-hover: rgba(0, 0, 0, 0.04);

  --theme-color-fg-highlight: #000000;
  --theme-color-fg-default-contrast: var(--base-color-neutral-100);
  --theme-color-fg-default: var(--base-color-neutral-200);
  --theme-color-fg-default-shy: var(--base-color-neutral-400);
  --theme-color-fg-muted: var(--base-color-neutral-500);

  --theme-color-primary: #d21f3c;
  --theme-color-on-primary: #ffffff;

  --theme-color-secondary: var(--base-color-neutral-100);
  --theme-color-on-secondary: #ffffff;

  --theme-color-border-default: var(--base-color-neutral-800);
  --theme-color-border-subtle: var(--base-color-neutral-900);
  --theme-color-border-strong: var(--base-color-neutral-700);
}

*/
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/custom-properties/colors.css"],"names":[],"mappings":"AAAA;;;kFAGkF;;AAElF;EACE;;;kFAGgF;;EAEhF,wBAAwB;EACxB,6BAA6B;EAC7B,6BAA6B;EAC7B,6BAA6B;EAC7B,6BAA6B;EAC7B,6BAA6B;EAC7B,6BAA6B;EAC7B,6BAA6B;EAC7B,6BAA6B;EAC7B,6BAA6B;EAC7B,6BAA6B;;EAE7B,kDAAkD;EAClD,+BAA+B;EAC/B,gCAAgC;EAChC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,kCAAkC;;EAElC,yBAAyB;EACzB,qDAAqD;EACrD,qDAAqD;EACrD,qDAAqD;EACrD,2DAA2D;EAC3D,4DAA4D;EAC5D,2DAA2D;;EAE3D;;kFAEgF;;EAEhF,mDAAmD;EACnD,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,iCAAiC;EACjC,kCAAkC;;EAElC,+BAA+B;EAC/B,iDAAiD;EACjD,iDAAiD;EACjD,iDAAiD;EACjD,iDAAiD;EACjD,iDAAiD;EACjD,iDAAiD;EACjD,iDAAiD;EACjD,iDAAiD;EACjD,iDAAiD;EACjD,kDAAkD;;EAElD;;;;kFAIgF;;EAEhF,sCAAsC;EACtC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,oCAAoC;;EAEpC,sCAAsC;EACtC,qCAAqC;EACrC,qCAAqC;EACrC,qCAAqC;EACrC,qCAAqC;EACrC,qCAAqC;EACrC,qCAAqC;EACrC,qCAAqC;EACrC,qCAAqC;EACrC,qCAAqC;EACrC,sCAAsC;;EAEtC,gCAAgC;EAChC,oCAAoC;EACpC,oCAAoC;EACpC,oCAAoC;EACpC,oCAAoC;EACpC,oCAAoC;EACpC,oCAAoC;EACpC,oCAAoC;EACpC,oCAAoC;EACpC,oCAAoC;EACpC,qCAAqC;;EAErC,gCAAgC;EAChC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,oCAAoC;;EAEpC,iCAAiC;EACjC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,mCAAmC;EACnC,oCAAoC;;EAEpC;;kFAEgF;;EAEhF,oBAAoB;EACpB,oDAAoD;EACpD,yEAAyE;EACzE,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,0EAA0E;EAC1E,4EAA4E;;EAE5E,kDAAkD;EAClD,qDAAqD;EACrD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,oDAAoD;EACpD,qDAAqD;;EAErD,uCAAuC;EACvC,kDAAkD;EAClD,kDAAkD;EAClD,kDAAkD;EAClD,kDAAkD;EAClD,kDAAkD;EAClD,kDAAkD;EAClD,kDAAkD;EAClD,kDAAkD;EAClD,kDAAkD;EAClD,mDAAmD;AACrD;;;AAGA;;kFAEkF;;AAElF;EACE;;;kFAGgF;EAChF,2BAA2B;EAC3B,gDAAgD;EAChD,sEAAsE;EACtE,wEAAwE;EACxE,iDAAiD;EACjD,iDAAiD;EACjD,iDAAiD;EACjD,iDAAiD;EACjD,8DAA8D;;EAE9D;;;kFAGgF;EAChF,mCAAmC;EACnC,gEAAgE;EAChE,uDAAuD;EACvD,2DAA2D;EAC3D,qDAAqD;EACrD,oEAAoE;;EAEpE;;;kFAGgF;EAChF,8BAA8B;EAC9B,0DAA0D;EAC1D,oDAAoD;EACpD,iCAAiC;;EAEjC;;;kFAGgF;EAChF,gCAAgC;EAChC,0DAA0D;EAC1D,0CAA0C;EAC1C,uCAAuC;EACvC,4DAA4D;EAC5D,yDAAyD;;EAEzD;;;kFAGgF;;EAEhF,6BAA6B;EAC7B,2DAA2D;EAC3D,2DAA2D;EAC3D,2DAA2D;EAC3D,6DAA6D;;EAE7D,8BAA8B;EAC9B,4DAA4D;EAC5D,4DAA4D;EAC5D,sEAAsE;EACtE,oEAAoE;EACpE,kEAAkE;EAClE,8DAA8D;EAC9D,8DAA8D;;EAE9D,8BAA8B;EAC9B,4DAA4D;EAC5D,4DAA4D;EAC5D,8DAA8D;;EAE9D,uBAAuB;EACvB,2DAA2D;EAC3D,2DAA2D;EAC3D,6DAA6D;;EAE7D,mCAAmC;EACnC,iEAAiE;EACjE,iEAAiE;EACjE,mEAAmE;;EAEnE;;;kFAGgF;EAChF,oDAAoD;EACpD,wDAAwD;EACxD,uDAAuD;;EAEvD,+CAA+C;EAC/C,mDAAmD;EACnD,kDAAkD;;EAElD,+CAA+C;EAC/C,qDAAqD;EACrD,mDAAmD;EACnD,kDAAkD;;EAElD;;kFAEgF;EAChF,+CAA+C;EAC/C,iDAAiD;;EAEjD;;;kFAGgF;EAChF,2DAA2D;EAC3D,0DAA0D;EAC1D,0DAA0D;;EAE1D;;;kFAGgF;EAChF,iCAAiC;EACjC,6DAA6D;AAC/D;;;AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC","sourcesContent":["/* =============================================================================\n   NOODL DESIGN SYSTEM - COLORS\n   Minimal palette: Red + Black + White\n   ============================================================================= */\n\n:root {\n  /* ---------------------------------------------------------------------------\n     BASE COLORS\n     A deliberately minimal palette - one accent, pure neutrals\n     --------------------------------------------------------------------------- */\n\n  /* Primary - Noodl Red */\n  --base-color-red-100: #fef2f3;\n  --base-color-red-200: #fde3e5;\n  --base-color-red-300: #fbc5c9;\n  --base-color-red-400: #f7969e;\n  --base-color-red-500: #ef5662;\n  --base-color-red-600: #d21f3c;\n  --base-color-red-700: #b91830;\n  --base-color-red-800: #9a1729;\n  --base-color-red-900: #801827;\n  --base-color-red-950: #460a11;\n\n  /* Neutrals - Pure black to white, no color tint */\n  --base-color-neutral-0: #000000;\n  --base-color-neutral-50: #0a0a0a;\n  --base-color-neutral-100: #121212;\n  --base-color-neutral-200: #1a1a1a;\n  --base-color-neutral-300: #262626;\n  --base-color-neutral-400: #333333;\n  --base-color-neutral-500: #525252;\n  --base-color-neutral-600: #737373;\n  --base-color-neutral-700: #a3a3a3;\n  --base-color-neutral-800: #d4d4d4;\n  --base-color-neutral-900: #e5e5e5;\n  --base-color-neutral-950: #f5f5f5;\n  --base-color-neutral-1000: #ffffff;\n\n  /* Transparent variants */\n  --base-color-black-transparent-90: rgba(0, 0, 0, 0.9);\n  --base-color-black-transparent-80: rgba(0, 0, 0, 0.8);\n  --base-color-black-transparent-50: rgba(0, 0, 0, 0.5);\n  --base-color-white-transparent-10: rgba(255, 255, 255, 0.1);\n  --base-color-white-transparent-15: rgba(255, 255, 255, 0.15);\n  --base-color-white-transparent-50: rgba(255, 255, 255, 0.5);\n\n  /* ---------------------------------------------------------------------------\n     SEMANTIC COLORS (Status indicators)\n     --------------------------------------------------------------------------- */\n\n  /* Success - Keeping a green for semantic meaning */\n  --base-color-success-100: #ecfdf5;\n  --base-color-success-200: #a7f3d0;\n  --base-color-success-300: #6ee7b7;\n  --base-color-success-400: #34d399;\n  --base-color-success-500: #10b981;\n  --base-color-success-600: #059669;\n  --base-color-success-700: #047857;\n  --base-color-success-800: #065f46;\n  --base-color-success-900: #064e3b;\n  --base-color-success-1000: #022c22;\n\n  /* Error - Uses the brand red */\n  --base-color-error-100: var(--base-color-red-100);\n  --base-color-error-200: var(--base-color-red-200);\n  --base-color-error-300: var(--base-color-red-300);\n  --base-color-error-400: var(--base-color-red-400);\n  --base-color-error-500: var(--base-color-red-500);\n  --base-color-error-600: var(--base-color-red-600);\n  --base-color-error-700: var(--base-color-red-700);\n  --base-color-error-800: var(--base-color-red-800);\n  --base-color-error-900: var(--base-color-red-900);\n  --base-color-error-1000: var(--base-color-red-950);\n\n  /* ---------------------------------------------------------------------------\n     NODE TYPE COLORS\n     Subtle variations to distinguish node types on canvas\n     Using desaturated colors so they don't compete with the red accent\n     --------------------------------------------------------------------------- */\n\n  /* Node-Pink - For Custom/User nodes */\n  --base-color-node-pink-100: #fdf2f8;\n  --base-color-node-pink-200: #f5d0e5;\n  --base-color-node-pink-300: #e8a8ca;\n  --base-color-node-pink-400: #d87caa;\n  --base-color-node-pink-500: #c2578a;\n  --base-color-node-pink-600: #a63d6f;\n  --base-color-node-pink-700: #862d56;\n  --base-color-node-pink-800: #6b2445;\n  --base-color-node-pink-900: #521c35;\n  --base-color-node-pink-1000: #2d0e1c;\n\n  /* Node-Purple - For Component nodes */\n  --base-color-node-purple-100: #f8f5fa;\n  --base-color-node-purple-200: #e8dff0;\n  --base-color-node-purple-300: #d4c4e3;\n  --base-color-node-purple-400: #b8a0cf;\n  --base-color-node-purple-500: #9a7bb8;\n  --base-color-node-purple-600: #7d5a9e;\n  --base-color-node-purple-700: #624382;\n  --base-color-node-purple-800: #4b3366;\n  --base-color-node-purple-900: #37264b;\n  --base-color-node-purple-1000: #1e1429;\n\n  /* Node-Green - For Data nodes */\n  --base-color-node-green-100: #f4f7f4;\n  --base-color-node-green-200: #d8e5d8;\n  --base-color-node-green-300: #b5cfb5;\n  --base-color-node-green-400: #8eb58e;\n  --base-color-node-green-500: #6a996a;\n  --base-color-node-green-600: #4d7d4d;\n  --base-color-node-green-700: #3a613a;\n  --base-color-node-green-800: #2c4a2c;\n  --base-color-node-green-900: #203520;\n  --base-color-node-green-1000: #111c11;\n\n  /* Node-Gray - For Logic nodes */\n  --base-color-node-grey-100: #f5f5f5;\n  --base-color-node-grey-200: #e0e0e0;\n  --base-color-node-grey-300: #c2c2c2;\n  --base-color-node-grey-400: #9e9e9e;\n  --base-color-node-grey-500: #757575;\n  --base-color-node-grey-600: #5c5c5c;\n  --base-color-node-grey-700: #454545;\n  --base-color-node-grey-800: #333333;\n  --base-color-node-grey-900: #212121;\n  --base-color-node-grey-1000: #0d0d0d;\n\n  /* Node-Blue - For Visual nodes */\n  --base-color-node-blue-100: #f4f6f8;\n  --base-color-node-blue-200: #dce3eb;\n  --base-color-node-blue-300: #bccad9;\n  --base-color-node-blue-400: #96adc2;\n  --base-color-node-blue-500: #7090a9;\n  --base-color-node-blue-600: #53758f;\n  --base-color-node-blue-700: #3e5a72;\n  --base-color-node-blue-800: #2f4557;\n  --base-color-node-blue-900: #22323f;\n  --base-color-node-blue-1000: #121b22;\n\n  /* ---------------------------------------------------------------------------\n     LEGACY ALIASES - For backwards compatibility\n     --------------------------------------------------------------------------- */\n  \n  /* Grey -> Neutral */\n  --base-color-grey-100: var(--base-color-neutral-950);\n  --base-color-grey-100-transparent: var(--base-color-white-transparent-10);\n  --base-color-grey-200: var(--base-color-neutral-800);\n  --base-color-grey-300: var(--base-color-neutral-700);\n  --base-color-grey-400: var(--base-color-neutral-600);\n  --base-color-grey-500: var(--base-color-neutral-500);\n  --base-color-grey-600: var(--base-color-neutral-400);\n  --base-color-grey-700: var(--base-color-neutral-300);\n  --base-color-grey-800: var(--base-color-neutral-200);\n  --base-color-grey-900: var(--base-color-neutral-100);\n  --base-color-grey-1000: var(--base-color-neutral-50);\n  --base-color-grey-1000-transparent: var(--base-color-black-transparent-80);\n  --base-color-grey-1000-transparent-2: var(--base-color-black-transparent-50);\n\n  /* Teal -> Neutral (secondary is now white/gray) */\n  --base-color-teal-100: var(--base-color-neutral-1000);\n  --base-color-teal-200: var(--base-color-neutral-900);\n  --base-color-teal-300: var(--base-color-neutral-800);\n  --base-color-teal-400: var(--base-color-neutral-700);\n  --base-color-teal-500: var(--base-color-neutral-600);\n  --base-color-teal-600: var(--base-color-neutral-500);\n  --base-color-teal-700: var(--base-color-neutral-400);\n  --base-color-teal-800: var(--base-color-neutral-300);\n  --base-color-teal-900: var(--base-color-neutral-200);\n  --base-color-teal-1000: var(--base-color-neutral-100);\n\n  /* Yellow -> Red (primary is now red) */\n  --base-color-yellow-100: var(--base-color-red-100);\n  --base-color-yellow-200: var(--base-color-red-200);\n  --base-color-yellow-300: var(--base-color-red-400);\n  --base-color-yellow-400: var(--base-color-red-500);\n  --base-color-yellow-500: var(--base-color-red-600);\n  --base-color-yellow-600: var(--base-color-red-700);\n  --base-color-yellow-700: var(--base-color-red-800);\n  --base-color-yellow-800: var(--base-color-red-900);\n  --base-color-yellow-900: var(--base-color-red-950);\n  --base-color-yellow-1000: var(--base-color-red-950);\n}\n\n\n/* =============================================================================\n   THEME COLOR TOKENS - USE THESE IN COMPONENTS\n   ============================================================================= */\n\n:root {\n  /* ---------------------------------------------------------------------------\n     BACKGROUNDS\n     Pure blacks with subtle elevation through lightness\n     --------------------------------------------------------------------------- */\n  --theme-color-bg-0: #000000;\n  --theme-color-bg-1: var(--base-color-neutral-50);\n  --theme-color-bg-1-transparent: var(--base-color-black-transparent-80);\n  --theme-color-bg-1-transparent-2: var(--base-color-black-transparent-50);\n  --theme-color-bg-2: var(--base-color-neutral-100);\n  --theme-color-bg-3: var(--base-color-neutral-200);\n  --theme-color-bg-4: var(--base-color-neutral-300);\n  --theme-color-bg-5: var(--base-color-neutral-400);\n  --theme-color-bg-hover: var(--base-color-white-transparent-10);\n\n  /* ---------------------------------------------------------------------------\n     FOREGROUNDS\n     Pure whites with subtle hierarchy\n     --------------------------------------------------------------------------- */\n  --theme-color-fg-highlight: #ffffff;\n  --theme-color-fg-default-contrast: var(--base-color-neutral-900);\n  --theme-color-fg-default: var(--base-color-neutral-800);\n  --theme-color-fg-default-shy: var(--base-color-neutral-700);\n  --theme-color-fg-muted: var(--base-color-neutral-600);\n  --theme-color-fg-transparent: var(--base-color-white-transparent-15);\n\n  /* ---------------------------------------------------------------------------\n     PRIMARY - Noodl Red\n     The one accent color - used sparingly for maximum impact\n     --------------------------------------------------------------------------- */\n  --theme-color-primary: #d21f3c;\n  --theme-color-primary-highlight: var(--base-color-red-500);\n  --theme-color-primary-dim: var(--base-color-red-800);\n  --theme-color-on-primary: #ffffff;\n\n  /* ---------------------------------------------------------------------------\n     SECONDARY - White/Light\n     For secondary actions, using white as the complement to red\n     --------------------------------------------------------------------------- */\n  --theme-color-secondary: #ffffff;\n  --theme-color-secondary-dim: var(--base-color-neutral-700);\n  --theme-color-secondary-highlight: #ffffff;\n  --theme-color-secondary-bright: #ffffff;\n  --theme-color-secondary-as-fg: var(--base-color-neutral-800);\n  --theme-color-on-secondary: var(--base-color-neutral-100);\n\n  /* ---------------------------------------------------------------------------\n     NODE COLORS\n     Muted, desaturated to not compete with the red accent\n     --------------------------------------------------------------------------- */\n\n  /* Data nodes - Muted Green */\n  --theme-color-node-data-1: var(--base-color-node-green-700);\n  --theme-color-node-data-2: var(--base-color-node-green-600);\n  --theme-color-node-data-3: var(--base-color-node-green-500);\n  --theme-color-node-data-dim: var(--base-color-node-green-900);\n\n  /* Visual nodes - Muted Blue */\n  --theme-color-node-visual-1: var(--base-color-node-blue-700);\n  --theme-color-node-visual-2: var(--base-color-node-blue-600);\n  --theme-color-node-visual-2-highlight: var(--base-color-node-blue-500);\n  --theme-color-node-visual-highlight: var(--base-color-node-blue-200);\n  --theme-color-node-visual-default: var(--base-color-node-blue-300);\n  --theme-color-node-visual-shy: var(--base-color-node-blue-400);\n  --theme-color-node-visual-dim: var(--base-color-node-blue-900);\n\n  /* Custom nodes - Muted Pink */\n  --theme-color-node-custom-1: var(--base-color-node-pink-700);\n  --theme-color-node-custom-2: var(--base-color-node-pink-600);\n  --theme-color-node-custom-dim: var(--base-color-node-pink-900);\n\n  /* Logic nodes - Gray */\n  --theme-color-node-logic-1: var(--base-color-node-grey-700);\n  --theme-color-node-logic-2: var(--base-color-node-grey-600);\n  --theme-color-node-logic-dim: var(--base-color-node-grey-900);\n\n  /* Component nodes - Muted Purple */\n  --theme-color-node-component-1: var(--base-color-node-purple-700);\n  --theme-color-node-component-2: var(--base-color-node-purple-600);\n  --theme-color-node-component-dim: var(--base-color-node-purple-900);\n\n  /* ---------------------------------------------------------------------------\n     STATUS COLORS\n     Success stays green, everything else maps to the palette\n     --------------------------------------------------------------------------- */\n  --theme-color-success: var(--base-color-success-400);\n  --theme-color-success-dim: var(--base-color-success-600);\n  --theme-color-success-bg: var(--base-color-success-900);\n\n  --theme-color-notice: var(--base-color-red-400);\n  --theme-color-notice-dim: var(--base-color-red-600);\n  --theme-color-notice-bg: var(--base-color-red-950);\n\n  --theme-color-danger: var(--base-color-red-500);\n  --theme-color-danger-light: var(--base-color-red-400);\n  --theme-color-danger-dim: var(--base-color-red-700);\n  --theme-color-danger-bg: var(--base-color-red-950);\n\n  /* ---------------------------------------------------------------------------\n     CONNECTION COLORS\n     --------------------------------------------------------------------------- */\n  --theme-color-signal: var(--base-color-red-500);\n  --theme-color-data: var(--base-color-neutral-700);\n\n  /* ---------------------------------------------------------------------------\n     BORDERS\n     Subtle white borders for dark backgrounds\n     --------------------------------------------------------------------------- */\n  --theme-color-border-default: var(--base-color-neutral-300);\n  --theme-color-border-subtle: var(--base-color-neutral-200);\n  --theme-color-border-strong: var(--base-color-neutral-400);\n\n  /* ---------------------------------------------------------------------------\n     FOCUS\n     Red focus ring for accessibility\n     --------------------------------------------------------------------------- */\n  --theme-color-focus-ring: #d21f3c;\n  --theme-color-focus-ring-offset: var(--base-color-neutral-50);\n}\n\n\n/* =============================================================================\n   FUTURE: LIGHT THEME\n   ============================================================================= \n\n.theme-light {\n  --theme-color-bg-0: #ffffff;\n  --theme-color-bg-1: var(--base-color-neutral-950);\n  --theme-color-bg-1-transparent: rgba(255, 255, 255, 0.9);\n  --theme-color-bg-1-transparent-2: rgba(255, 255, 255, 0.5);\n  --theme-color-bg-2: #ffffff;\n  --theme-color-bg-3: var(--base-color-neutral-900);\n  --theme-color-bg-4: var(--base-color-neutral-800);\n  --theme-color-bg-5: var(--base-color-neutral-700);\n  --theme-color-bg-hover: rgba(0, 0, 0, 0.04);\n\n  --theme-color-fg-highlight: #000000;\n  --theme-color-fg-default-contrast: var(--base-color-neutral-100);\n  --theme-color-fg-default: var(--base-color-neutral-200);\n  --theme-color-fg-default-shy: var(--base-color-neutral-400);\n  --theme-color-fg-muted: var(--base-color-neutral-500);\n\n  --theme-color-primary: #d21f3c;\n  --theme-color-on-primary: #ffffff;\n\n  --theme-color-secondary: var(--base-color-neutral-100);\n  --theme-color-on-secondary: #ffffff;\n\n  --theme-color-border-default: var(--base-color-neutral-800);\n  --theme-color-border-subtle: var(--base-color-neutral-900);\n  --theme-color-border-strong: var(--base-color-neutral-700);\n}\n\n*/\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 27339:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.TableRow-module__Root--Ab5HH{background-color:var(--theme-color-bg-3);border-radius:6px;margin-bottom:4px;overflow:hidden;transition:background-color .15s ease}.TableRow-module__Root--Ab5HH:hover{background-color:var(--theme-color-bg-4)}.TableRow-module__Root--Ab5HH[data-expanded=true]{background-color:var(--theme-color-bg-4)}.TableRow-module__Header--pG4Re{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;cursor:pointer;user-select:none}.TableRow-module__ExpandIcon--qHPA8{width:16px;height:16px;display:flex;align-items:center;justify-content:center}.TableRow-module__TableIcon--trryc{width:24px;height:24px;background-color:var(--theme-color-primary);border-radius:4px;display:flex;align-items:center;justify-content:center;color:#fff;font-size:12px;font-weight:600}.TableRow-module__TableName--O3ZP8{margin-left:4px}.TableRow-module__Stats--WwVIC{display:flex;align-items:center}.TableRow-module__Columns--yCCVp{padding:0 12px 12px 12px;border-top:1px solid var(--theme-color-border-default)}.TableRow-module__ColumnTable--MnLxv{width:100%;border-collapse:collapse;font-size:12px}.TableRow-module__ColumnTable--MnLxv th{text-align:left;padding:8px 12px;color:var(--theme-color-fg-default-shy);font-weight:500;border-bottom:1px solid var(--theme-color-border-default)}.TableRow-module__ColumnTable--MnLxv td{padding:6px 12px;color:var(--theme-color-fg-default)}.TableRow-module__ColumnTable--MnLxv tr:hover td{background-color:var(--theme-color-bg-3)}.TableRow-module__SystemColumn--Unvfl td{color:var(--theme-color-fg-default-shy);font-style:italic}.TableRow-module__TypeBadge--j7fuN{display:inline-block;padding:2px 6px;border-radius:3px;font-size:10px;font-weight:500;color:#fff;text-transform:capitalize}.TableRow-module__TargetClass--krbvU{color:var(--theme-color-fg-default-shy);font-size:10px;margin-left:4px}.TableRow-module__NoColumns--pYRMy{text-align:center;color:var(--theme-color-fg-default-shy);font-style:italic;padding:16px !important}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/schemamanager/TableRow.module.scss"],"names":[],"mappings":"AAKA,8BACE,wCAAA,CACA,iBAAA,CACA,iBAAA,CACA,eAAA,CACA,qCAAA,CAEA,oCACE,wCAAA,CAGF,kDACE,wCAAA,CAIJ,gCACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,gBAAA,CACA,cAAA,CACA,gBAAA,CAGF,oCACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CAGF,mCACE,UAAA,CACA,WAAA,CACA,2CAAA,CACA,iBAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CACA,cAAA,CACA,eAAA,CAGF,mCACE,eAAA,CAGF,+BACE,YAAA,CACA,kBAAA,CAGF,iCACE,wBAAA,CACA,sDAAA,CAGF,qCACE,UAAA,CACA,wBAAA,CACA,cAAA,CAEA,wCACE,eAAA,CACA,gBAAA,CACA,uCAAA,CACA,eAAA,CACA,yDAAA,CAGF,wCACE,gBAAA,CACA,mCAAA,CAGF,iDACE,wCAAA,CAKF,yCACE,uCAAA,CACA,iBAAA,CAIJ,mCACE,oBAAA,CACA,eAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,UAAA,CACA,yBAAA,CAGF,qCACE,uCAAA,CACA,cAAA,CACA,eAAA,CAGF,mCACE,iBAAA,CACA,uCAAA,CACA,iBAAA,CACA,uBAAA","sourcesContent":["/**\n * TableRow styles\n * Uses theme tokens from UI-STYLING-GUIDE.md\n */\n\n.Root {\n  background-color: var(--theme-color-bg-3);\n  border-radius: 6px;\n  margin-bottom: 4px;\n  overflow: hidden;\n  transition: background-color 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n  }\n\n  &[data-expanded='true'] {\n    background-color: var(--theme-color-bg-4);\n  }\n}\n\n.Header {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 8px 12px;\n  cursor: pointer;\n  user-select: none;\n}\n\n.ExpandIcon {\n  width: 16px;\n  height: 16px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.TableIcon {\n  width: 24px;\n  height: 24px;\n  background-color: var(--theme-color-primary);\n  border-radius: 4px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  color: white;\n  font-size: 12px;\n  font-weight: 600;\n}\n\n.TableName {\n  margin-left: 4px;\n}\n\n.Stats {\n  display: flex;\n  align-items: center;\n}\n\n.Columns {\n  padding: 0 12px 12px 12px;\n  border-top: 1px solid var(--theme-color-border-default);\n}\n\n.ColumnTable {\n  width: 100%;\n  border-collapse: collapse;\n  font-size: 12px;\n\n  th {\n    text-align: left;\n    padding: 8px 12px;\n    color: var(--theme-color-fg-default-shy);\n    font-weight: 500;\n    border-bottom: 1px solid var(--theme-color-border-default);\n  }\n\n  td {\n    padding: 6px 12px;\n    color: var(--theme-color-fg-default);\n  }\n\n  tr:hover td {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n.SystemColumn {\n  td {\n    color: var(--theme-color-fg-default-shy);\n    font-style: italic;\n  }\n}\n\n.TypeBadge {\n  display: inline-block;\n  padding: 2px 6px;\n  border-radius: 3px;\n  font-size: 10px;\n  font-weight: 500;\n  color: white;\n  text-transform: capitalize;\n}\n\n.TargetClass {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 10px;\n  margin-left: 4px;\n}\n\n.NoColumns {\n  text-align: center;\n  color: var(--theme-color-fg-default-shy);\n  font-style: italic;\n  padding: 16px !important;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `TableRow-module__Root--Ab5HH`,
	"Header": `TableRow-module__Header--pG4Re`,
	"ExpandIcon": `TableRow-module__ExpandIcon--qHPA8`,
	"TableIcon": `TableRow-module__TableIcon--trryc`,
	"TableName": `TableRow-module__TableName--O3ZP8`,
	"Stats": `TableRow-module__Stats--WwVIC`,
	"Columns": `TableRow-module__Columns--yCCVp`,
	"ColumnTable": `TableRow-module__ColumnTable--MnLxv`,
	"SystemColumn": `TableRow-module__SystemColumn--Unvfl`,
	"TypeBadge": `TableRow-module__TypeBadge--j7fuN`,
	"TargetClass": `TableRow-module__TargetClass--krbvU`,
	"NoColumns": `TableRow-module__NoColumns--pYRMy`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 27500:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/* -------------------------------------------------------------------
   Node Graph Editor
   ------------------------------------------------------------------- */
.nodegrapgeditor-bg {
  background-color: var(--theme-color-bg-1);
  cursor: default;
  overflow: hidden;
}

.nodegraph-component-trail-root {
  position: absolute;
  bottom: 0;
  left: 0;
  max-width: calc(100% - 68px);
}

#nodegraph-dom-layer {
  position: absolute;
  top: 0;
  left: 0;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/nodegrapheditor.css"],"names":[],"mappings":"AAAA;;wEAEwE;AACxE;EACE,yCAAyC;EACzC,eAAe;EACf,gBAAgB;AAClB;;AAEA;EACE,kBAAkB;EAClB,SAAS;EACT,OAAO;EACP,4BAA4B;AAC9B;;AAEA;EACE,kBAAkB;EAClB,MAAM;EACN,OAAO;AACT","sourcesContent":["/* -------------------------------------------------------------------\n   Node Graph Editor\n   ------------------------------------------------------------------- */\n.nodegrapgeditor-bg {\n  background-color: var(--theme-color-bg-1);\n  cursor: default;\n  overflow: hidden;\n}\n\n.nodegraph-component-trail-root {\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  max-width: calc(100% - 68px);\n}\n\n#nodegraph-dom-layer {\n  position: absolute;\n  top: 0;\n  left: 0;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 27650:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";

var bcrypt = __webpack_require__(58379);
var passport = __webpack_require__(58788);
var LocalStrategy = (__webpack_require__(90294).Strategy);
const OTPAuth = __webpack_require__(65621)

/**
 * Constructor for Authentication class
 *
 * @class Authentication
 * @param {Object[]} validUsers
 * @param {boolean} useEncryptedPasswords
 */
function Authentication(validUsers, useEncryptedPasswords, mountPath) {
  this.validUsers = validUsers;
  this.useEncryptedPasswords = useEncryptedPasswords || false;
  this.mountPath = mountPath;
}

function initialize(app, options) {
  options = options || {};
  var self = this;
  passport.use('local', new LocalStrategy(
    {passReqToCallback:true},
    function(req, username, password, cb) {
      var match = self.authenticate({
        name: username,
        pass: password,
        otpCode: req.body.otpCode
      });
      if (!match.matchingUsername) {
        return cb(null, false, { message: JSON.stringify({ text: 'Invalid username or password' }) });
      }
      if (!match.otpValid) {
        return cb(null, false, { message: JSON.stringify({ text: 'Invalid one-time password.', otpLength: match.otpMissingLength || 6}) });
      }
      if (match.otpMissingLength) {
        return cb(null, false, { message: JSON.stringify({ text: 'Please enter your one-time password.', otpLength: match.otpMissingLength || 6 })});
      }
      cb(null, match.matchingUsername);
    })
  );

  passport.serializeUser(function(username, cb) {
    cb(null, username);
  });

  passport.deserializeUser(function(username, cb) {
    var user = self.authenticate({
      name: username
    }, true);
    cb(null, user);
  });

  var cookieSessionSecret = options.cookieSessionSecret || (__webpack_require__(76982).randomBytes)(64).toString('hex');
  app.use(__webpack_require__(50795)());
  app.use((__webpack_require__(21410).urlencoded)({ extended: true }));
  app.use(__webpack_require__(17549)({
    key    : 'parse_dash',
    secret : cookieSessionSecret,
    cookie : {
      maxAge: (2 * 7 * 24 * 60 * 60 * 1000) // 2 weeks
    }
  }));
  app.use(passport.initialize());
  app.use(passport.session());

  app.post('/login',
    passport.authenticate('local', {
      successRedirect: `${self.mountPath}apps`,
      failureRedirect: `${self.mountPath}login`,
      failureFlash : true
    })
  );

  app.get('/logout', function(req, res){
    req.logout();
    res.redirect(`${self.mountPath}login`);
  });
}

/**
 * Authenticates the `userToTest`
 *
 * @param {Object} userToTest
 * @returns {Object} Object with `isAuthenticated` and `appsUserHasAccessTo` properties
 */
function authenticate(userToTest, usernameOnly) {
  let appsUserHasAccessTo = null;
  let matchingUsername = null;
  let isReadOnly = false;
  let otpMissingLength = false;
  let otpValid = true;

  //they provided auth
  let isAuthenticated = userToTest &&
    //there are configured users
    this.validUsers &&
    //the provided auth matches one of the users
    this.validUsers.find(user => {
      let isAuthenticated = false;
      let usernameMatches = userToTest.name == user.user;
      if (usernameMatches && user.mfa && !usernameOnly) {
        if (!userToTest.otpCode) {
          otpMissingLength = user.mfaDigits || 6;
        } else {
          const totp = new OTPAuth.TOTP({
            algorithm: user.mfaAlgorithm || 'SHA1',
            secret: OTPAuth.Secret.fromBase32(user.mfa),
            digits: user.mfaDigits,
            period: user.mfaPeriod,
          });
          const valid = totp.validate({
            token: userToTest.otpCode
          });
          if (valid === null) {
            otpValid = false;
            otpMissingLength = user.mfaDigits || 6;
          }
        }
      }
      let passwordMatches = this.useEncryptedPasswords && !usernameOnly ? bcrypt.compareSync(userToTest.pass, user.pass) : userToTest.pass == user.pass;
      if (usernameMatches && (usernameOnly || passwordMatches)) {
        isAuthenticated = true;
        matchingUsername = user.user;
        // User restricted apps
        appsUserHasAccessTo = user.apps || null;
        isReadOnly = !!user.readOnly; // make it true/false
      }
      return isAuthenticated;
    }) ? true : false;

  return {
    isAuthenticated,
    matchingUsername,
    otpMissingLength,
    otpValid,
    appsUserHasAccessTo,
    isReadOnly,
  };
}

Authentication.prototype.initialize = initialize;
Authentication.prototype.authenticate = authenticate;

module.exports = Authentication;


/***/ }),

/***/ 27694:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.property-editor-visual-states {
  border-bottom: 1px solid var(--theme-color-bg-1);
  box-sizing: border-box;
}

.property-editor-visual-state-item:not(:last-child) {
  border-bottom: 1px solid var(--theme-color-bg-2);
}

.property-editor-visual-state-item-label {
  margin: 8px;
  color: var(--theme-color-fg-default);
}

.property-editor-visual-state-item-label:hover {
  color: var(--theme-color-fg-highlight);
}

.property-editor-visual-state-item-label.selected {
  color: var(--theme-color-fg-highlight);
}

.visual-state-transition {
  padding: 5px;
  padding-left: 8px;
}

.visual-state-default-transition {
  margin-bottom: 3px;
  width: 230px;
}

.visual-state-default-transition .label {
  background-color: var(--theme-color-bg-4);
  padding: 2px 2px 2px 8px;
  color: rgba(255, 255, 255, 0.75);
  flex-grow: 1;
  display: flex;
  align-items: center;
  border: 1px solid transparent;
}

.visual-state-default-transition.default .label {
  color: rgba(255, 255, 255, 0.33);
}

.visual-state-default-transition.selected .label {
  border: 1px solid var(--theme-color-fg-highlight);
}

.visual-state-transition-curve-button {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  background-color: var(--theme-color-bg-3);
  padding: 2px 0;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.5);
  line-height: 17px;
  width: 52px;
  box-sizing: border-box;
}

.visual-state-transition-curve-button:hover {
  color: var(--theme-color-fg-highlight);
  background-color: var(--theme-color-bg-4);
}

.visual-state-transition-changed-dot {
  height: 16px;
  width: 16px;
  -webkit-mask-size: contain;
  -webkit-mask-image: url(../assets/icons/editor/reset-to-default.svg);
  background: var(--theme-color-fg-muted);
  margin-left: 8px;
}

.visual-states-group-header {
  color: var(--theme-color-fg-default);
  margin-bottom: 3px;
  margin-top: 15px;
}

.property-editor-visual-state-transition .label {
  color: var(--theme-color-fg-highlight);
}

.visual-states-popup {
  background-color: var(--theme-color-bg-3);
  width: 100px;
}

.visual-states-transition-popup {
  min-height: 400px;
  display: flex;
  flex-direction: column;
  background-color: var(--theme-color-bg-3);
}

.visual-states-transitions-header {
  background-color: var(--theme-color-bg-2);
  color: var(--theme-color-fg-default);
  padding: 4px;
  padding-left: 10px;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/propertyeditor/visualstates.css"],"names":[],"mappings":"AAAA;EACE,gDAAgD;EAChD,sBAAsB;AACxB;;AAEA;EACE,gDAAgD;AAClD;;AAEA;EACE,WAAW;EACX,oCAAoC;AACtC;;AAEA;EACE,sCAAsC;AACxC;;AAEA;EACE,sCAAsC;AACxC;;AAEA;EACE,YAAY;EACZ,iBAAiB;AACnB;;AAEA;EACE,kBAAkB;EAClB,YAAY;AACd;;AAEA;EACE,yCAAyC;EACzC,wBAAwB;EACxB,gCAAgC;EAChC,YAAY;EACZ,aAAa;EACb,mBAAmB;EACnB,6BAA6B;AAC/B;;AAEA;EACE,gCAAgC;AAClC;;AAEA;EACE,iDAAiD;AACnD;;AAEA;EACE,aAAa;EACb,mBAAmB;EACnB,uBAAuB;EACvB,eAAe;EACf,yCAAyC;EACzC,cAAc;EACd,gBAAgB;EAChB,+BAA+B;EAC/B,iBAAiB;EACjB,WAAW;EACX,sBAAsB;AACxB;;AAEA;EACE,sCAAsC;EACtC,yCAAyC;AAC3C;;AAEA;EACE,YAAY;EACZ,WAAW;EACX,0BAA0B;EAC1B,oEAAoE;EACpE,uCAAuC;EACvC,gBAAgB;AAClB;;AAEA;EACE,oCAAoC;EACpC,kBAAkB;EAClB,gBAAgB;AAClB;;AAEA;EACE,sCAAsC;AACxC;;AAEA;EACE,yCAAyC;EACzC,YAAY;AACd;;AAEA;EACE,iBAAiB;EACjB,aAAa;EACb,sBAAsB;EACtB,yCAAyC;AAC3C;;AAEA;EACE,yCAAyC;EACzC,oCAAoC;EACpC,YAAY;EACZ,kBAAkB;AACpB","sourcesContent":[".property-editor-visual-states {\n  border-bottom: 1px solid var(--theme-color-bg-1);\n  box-sizing: border-box;\n}\n\n.property-editor-visual-state-item:not(:last-child) {\n  border-bottom: 1px solid var(--theme-color-bg-2);\n}\n\n.property-editor-visual-state-item-label {\n  margin: 8px;\n  color: var(--theme-color-fg-default);\n}\n\n.property-editor-visual-state-item-label:hover {\n  color: var(--theme-color-fg-highlight);\n}\n\n.property-editor-visual-state-item-label.selected {\n  color: var(--theme-color-fg-highlight);\n}\n\n.visual-state-transition {\n  padding: 5px;\n  padding-left: 8px;\n}\n\n.visual-state-default-transition {\n  margin-bottom: 3px;\n  width: 230px;\n}\n\n.visual-state-default-transition .label {\n  background-color: var(--theme-color-bg-4);\n  padding: 2px 2px 2px 8px;\n  color: rgba(255, 255, 255, 0.75);\n  flex-grow: 1;\n  display: flex;\n  align-items: center;\n  border: 1px solid transparent;\n}\n\n.visual-state-default-transition.default .label {\n  color: rgba(255, 255, 255, 0.33);\n}\n\n.visual-state-default-transition.selected .label {\n  border: 1px solid var(--theme-color-fg-highlight);\n}\n\n.visual-state-transition-curve-button {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  font-size: 10px;\n  background-color: var(--theme-color-bg-3);\n  padding: 2px 0;\n  font-weight: 600;\n  color: rgba(255, 255, 255, 0.5);\n  line-height: 17px;\n  width: 52px;\n  box-sizing: border-box;\n}\n\n.visual-state-transition-curve-button:hover {\n  color: var(--theme-color-fg-highlight);\n  background-color: var(--theme-color-bg-4);\n}\n\n.visual-state-transition-changed-dot {\n  height: 16px;\n  width: 16px;\n  -webkit-mask-size: contain;\n  -webkit-mask-image: url(../assets/icons/editor/reset-to-default.svg);\n  background: var(--theme-color-fg-muted);\n  margin-left: 8px;\n}\n\n.visual-states-group-header {\n  color: var(--theme-color-fg-default);\n  margin-bottom: 3px;\n  margin-top: 15px;\n}\n\n.property-editor-visual-state-transition .label {\n  color: var(--theme-color-fg-highlight);\n}\n\n.visual-states-popup {\n  background-color: var(--theme-color-bg-3);\n  width: 100px;\n}\n\n.visual-states-transition-popup {\n  min-height: 400px;\n  display: flex;\n  flex-direction: column;\n  background-color: var(--theme-color-bg-3);\n}\n\n.visual-states-transitions-header {\n  background-color: var(--theme-color-bg-2);\n  color: var(--theme-color-fg-default);\n  padding: 4px;\n  padding-left: 10px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 27781:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.CollapsableSection-module__Root--QVuHu{display:flex;flex-direction:column;overflow:hidden}.CollapsableSection-module__Root--QVuHu.CollapsableSection-module__has-visible-overflow--a2plj{overflow:visible}.CollapsableSection-module__Root--QVuHu.CollapsableSection-module__is-variant-default--hBBGh{background-color:var(--theme-color-bg-2)}.CollapsableSection-module__Root--QVuHu.CollapsableSection-module__is-variant-default--hBBGh:not(:last-child){border-bottom:1px solid var(--theme-color-bg-1)}.CollapsableSection-module__Root--QVuHu.CollapsableSection-module__is-variant-default--hBBGh.CollapsableSection-module__has-top-divider--UYBls{border-top:1px solid var(--theme-color-bg-1)}.CollapsableSection-module__Root--QVuHu.CollapsableSection-module__is-variant-panel--J3HOT,.CollapsableSection-module__Root--QVuHu.CollapsableSection-module__is-variant-panel-shy--NIkWI{background-color:var(--theme-color-bg-2)}.CollapsableSection-module__Root--QVuHu.CollapsableSection-module__is-variant-panel-shy--NIkWI:not(:first-child),.CollapsableSection-module__Root--QVuHu.CollapsableSection-module__is-variant-panel-shy--NIkWI.CollapsableSection-module__has-top-divider--UYBls{border-top:1px solid var(--theme-color-bg-1)}.CollapsableSection-module__Root--QVuHu.CollapsableSection-module__is-variant-in-modal--RooNf{background-color:var(--theme-color-bg-4)}.CollapsableSection-module__Header--rKQ1W{display:flex;align-items:center;justify-content:space-between;flex:0 0 36px;min-height:36px;padding:0 10px 0 16px;user-select:none}.CollapsableSection-module__Header--rKQ1W.CollapsableSection-module__is-variant-panel--J3HOT{background-color:var(--theme-color-bg-3)}.CollapsableSection-module__Header--rKQ1W.CollapsableSection-module__is-variant-panel-shy--NIkWI{background-color:rgba(0,0,0,0)}.CollapsableSection-module__Header--rKQ1W.CollapsableSection-module__is-variant-in-modal--RooNf{background-color:var(--theme-color-bg-3)}.CollapsableSection-module__Header--rKQ1W.CollapsableSection-module__is-collapsable--r9DN5{padding-right:0;cursor:pointer}.CollapsableSection-module__Body--tSEQG{overflow:hidden overlay;padding-top:8px}.CollapsableSection-module__Body--tSEQG.CollapsableSection-module__is-variant-in-modal--RooNf{padding:0}.CollapsableSection-module__Body--tSEQG.CollapsableSection-module__has-visible-overflow--a2plj{overflow:visible}.CollapsableSection-module__Body--tSEQG.CollapsableSection-module__has-bottom-spacing--XBWn3{padding-bottom:12px}.CollapsableSection-module__Body--tSEQG.CollapsableSection-module__has-gutter--OJ0Wf{padding:15px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/sidebar/CollapsableSection/CollapsableSection.module.scss"],"names":[],"mappings":"AAAA,wCACE,YAAA,CACA,qBAAA,CACA,eAAA,CAEA,+FACE,gBAAA,CAGF,6FACE,wCAAA,CAEA,8GACE,+CAAA,CAGF,+IACE,4CAAA,CAIJ,0LAEE,wCAAA,CAIA,kQAEE,4CAAA,CAIJ,8FACE,wCAAA,CAIJ,0CACE,YAAA,CACA,kBAAA,CACA,6BAAA,CAGA,aAAA,CACA,eAAA,CACA,qBAAA,CAEA,gBAAA,CAEA,6FACE,wCAAA,CAGF,iGACE,8BAAA,CAGF,gGACE,wCAAA,CAGF,2FACE,eAAA,CACA,cAAA,CAIJ,wCAEE,uBAAA,CACA,eAAA,CAEA,8FACE,SAAA,CAGF,+FACE,gBAAA,CAGF,6FACE,mBAAA,CAGF,qFACE,YAAA","sourcesContent":[".Root {\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n\n  &.has-visible-overflow {\n    overflow: visible;\n  }\n\n  &.is-variant-default {\n    background-color: var(--theme-color-bg-2);\n\n    &:not(:last-child) {\n      border-bottom: 1px solid var(--theme-color-bg-1);\n    }\n\n    &.has-top-divider {\n      border-top: 1px solid var(--theme-color-bg-1);\n    }\n  }\n\n  &.is-variant-panel,\n  &.is-variant-panel-shy {\n    background-color: var(--theme-color-bg-2);\n  }\n\n  &.is-variant-panel-shy {\n    &:not(:first-child),\n    &.has-top-divider {\n      border-top: 1px solid var(--theme-color-bg-1);\n    }\n  }\n\n  &.is-variant-in-modal {\n    background-color: var(--theme-color-bg-4);\n  }\n}\n\n.Header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n\n  /* consistency */\n  flex: 0 0 36px;\n  min-height: 36px;\n  padding: 0 10px 0 16px;\n\n  user-select: none;\n\n  &.is-variant-panel {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.is-variant-panel-shy {\n    background-color: transparent;\n  }\n\n  &.is-variant-in-modal {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.is-collapsable {\n    padding-right: 0;\n    cursor: pointer;\n  }\n}\n\n.Body {\n  /* allow scrolling */\n  overflow: hidden overlay;\n  padding-top: 8px;\n\n  &.is-variant-in-modal {\n    padding: 0;\n  }\n\n  &.has-visible-overflow {\n    overflow: visible;\n  }\n\n  &.has-bottom-spacing {\n    padding-bottom: 12px;\n  }\n\n  &.has-gutter {\n    padding: 15px;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `CollapsableSection-module__Root--QVuHu`,
	"has-visible-overflow": `CollapsableSection-module__has-visible-overflow--a2plj`,
	"is-variant-default": `CollapsableSection-module__is-variant-default--hBBGh`,
	"has-top-divider": `CollapsableSection-module__has-top-divider--UYBls`,
	"is-variant-panel": `CollapsableSection-module__is-variant-panel--J3HOT`,
	"is-variant-panel-shy": `CollapsableSection-module__is-variant-panel-shy--NIkWI`,
	"is-variant-in-modal": `CollapsableSection-module__is-variant-in-modal--RooNf`,
	"Header": `CollapsableSection-module__Header--rKQ1W`,
	"is-collapsable": `CollapsableSection-module__is-collapsable--r9DN5`,
	"Body": `CollapsableSection-module__Body--tSEQG`,
	"has-bottom-spacing": `CollapsableSection-module__has-bottom-spacing--XBWn3`,
	"has-gutter": `CollapsableSection-module__has-gutter--OJ0Wf`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 27877:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.partialParse = void 0;
const tokenize = (input) => {
    let current = 0;
    let tokens = [];
    while (current < input.length) {
        let char = input[current];
        if (char === '\\') {
            current++;
            continue;
        }
        if (char === '{') {
            tokens.push({
                type: 'brace',
                value: '{',
            });
            current++;
            continue;
        }
        if (char === '}') {
            tokens.push({
                type: 'brace',
                value: '}',
            });
            current++;
            continue;
        }
        if (char === '[') {
            tokens.push({
                type: 'paren',
                value: '[',
            });
            current++;
            continue;
        }
        if (char === ']') {
            tokens.push({
                type: 'paren',
                value: ']',
            });
            current++;
            continue;
        }
        if (char === ':') {
            tokens.push({
                type: 'separator',
                value: ':',
            });
            current++;
            continue;
        }
        if (char === ',') {
            tokens.push({
                type: 'delimiter',
                value: ',',
            });
            current++;
            continue;
        }
        if (char === '"') {
            let value = '';
            let danglingQuote = false;
            char = input[++current];
            while (char !== '"') {
                if (current === input.length) {
                    danglingQuote = true;
                    break;
                }
                if (char === '\\') {
                    current++;
                    if (current === input.length) {
                        danglingQuote = true;
                        break;
                    }
                    value += char + input[current];
                    char = input[++current];
                }
                else {
                    value += char;
                    char = input[++current];
                }
            }
            char = input[++current];
            if (!danglingQuote) {
                tokens.push({
                    type: 'string',
                    value,
                });
            }
            continue;
        }
        let WHITESPACE = /\s/;
        if (char && WHITESPACE.test(char)) {
            current++;
            continue;
        }
        let NUMBERS = /[0-9]/;
        if ((char && NUMBERS.test(char)) || char === '-' || char === '.') {
            let value = '';
            if (char === '-') {
                value += char;
                char = input[++current];
            }
            while ((char && NUMBERS.test(char)) || char === '.') {
                value += char;
                char = input[++current];
            }
            tokens.push({
                type: 'number',
                value,
            });
            continue;
        }
        let LETTERS = /[a-z]/i;
        if (char && LETTERS.test(char)) {
            let value = '';
            while (char && LETTERS.test(char)) {
                if (current === input.length) {
                    break;
                }
                value += char;
                char = input[++current];
            }
            if (value == 'true' || value == 'false' || value === 'null') {
                tokens.push({
                    type: 'name',
                    value,
                });
            }
            else {
                // unknown token, e.g. `nul` which isn't quite `null`
                current++;
                continue;
            }
            continue;
        }
        current++;
    }
    return tokens;
}, strip = (tokens) => {
    if (tokens.length === 0) {
        return tokens;
    }
    let lastToken = tokens[tokens.length - 1];
    switch (lastToken.type) {
        case 'separator':
            tokens = tokens.slice(0, tokens.length - 1);
            return strip(tokens);
            // removed by dead control flow

        case 'number':
            let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
            if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {
                tokens = tokens.slice(0, tokens.length - 1);
                return strip(tokens);
            }
        case 'string':
            let tokenBeforeTheLastToken = tokens[tokens.length - 2];
            if (tokenBeforeTheLastToken?.type === 'delimiter') {
                tokens = tokens.slice(0, tokens.length - 1);
                return strip(tokens);
            }
            else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') {
                tokens = tokens.slice(0, tokens.length - 1);
                return strip(tokens);
            }
            break;
        case 'delimiter':
            tokens = tokens.slice(0, tokens.length - 1);
            return strip(tokens);
            // removed by dead control flow

    }
    return tokens;
}, unstrip = (tokens) => {
    let tail = [];
    tokens.map((token) => {
        if (token.type === 'brace') {
            if (token.value === '{') {
                tail.push('}');
            }
            else {
                tail.splice(tail.lastIndexOf('}'), 1);
            }
        }
        if (token.type === 'paren') {
            if (token.value === '[') {
                tail.push(']');
            }
            else {
                tail.splice(tail.lastIndexOf(']'), 1);
            }
        }
    });
    if (tail.length > 0) {
        tail.reverse().map((item) => {
            if (item === '}') {
                tokens.push({
                    type: 'brace',
                    value: '}',
                });
            }
            else if (item === ']') {
                tokens.push({
                    type: 'paren',
                    value: ']',
                });
            }
        });
    }
    return tokens;
}, generate = (tokens) => {
    let output = '';
    tokens.map((token) => {
        switch (token.type) {
            case 'string':
                output += '"' + token.value + '"';
                break;
            default:
                output += token.value;
                break;
        }
    });
    return output;
}, partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
exports.partialParse = partialParse;
//# sourceMappingURL=parser.js.map

/***/ }),

/***/ 28019:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgArrowLineUp = function SvgArrowLineUp(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.1367 4.17548C21.1367 3.76126 20.8009 3.42548 20.3867 3.42548L3.88672 3.42548C3.47251 3.42548 3.13672 3.76126 3.13672 4.17548C3.13672 4.58969 3.47251 4.92548 3.88672 4.92548L20.3867 4.92548C20.8009 4.92548 21.1367 4.58969 21.1367 4.17548Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.421 6.93824C12.5105 6.97485 12.5944 7.0295 12.6671 7.10218L16.3648 10.7999C16.6577 11.0928 16.6577 11.5676 16.3648 11.8605C16.0719 12.1534 15.597 12.1534 15.3041 11.8605L12.8868 9.44316L12.8868 21.7009C12.8868 22.1151 12.551 22.4509 12.1368 22.4509C11.7226 22.4509 11.3868 22.1151 11.3868 21.7009L11.3868 9.44318L8.96943 11.8605C8.67654 12.1534 8.20167 12.1534 7.90877 11.8605C7.61588 11.5676 7.61588 11.0928 7.90877 10.7999L11.6044 7.10426C11.6111 7.09751 11.6179 7.09088 11.6248 7.08439C11.7589 6.95916 11.9389 6.88251 12.1368 6.88251C12.2374 6.88251 12.3334 6.90231 12.421 6.93824Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgArrowLineUp);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "6ea8c2b117f2b66e67fbbf634ded00fb.svg");

/***/ }),

/***/ 28046:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/*
	Keeping name short for faster parsing.
	cmdr = core margin decorations rendering (div)
*/
.monaco-editor .margin-view-overlays .cmdr {
	position: absolute;
	left: 0;
	width: 100%;
	height: 100%;
}`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/marginDecorations/marginDecorations.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;;;CAGC;AACD;CACC,kBAAkB;CAClB,OAAO;CACP,WAAW;CACX,YAAY;AACb","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/*\n\tKeeping name short for faster parsing.\n\tcmdr = core margin decorations rendering (div)\n*/\n.monaco-editor .margin-view-overlays .cmdr {\n\tposition: absolute;\n\tleft: 0;\n\twidth: 100%;\n\theight: 100%;\n}"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 28208:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  K0: () => (/* reexport */ IconButton),
  Tp: () => (/* reexport */ IconButtonSize),
  Df: () => (/* reexport */ IconButtonState),
  nl: () => (/* reexport */ IconButtonVariant)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Label/index.ts + 2 modules
var Label = __webpack_require__(91629);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/IconButton/IconButton.module.scss
var IconButton_module = __webpack_require__(11244);
;// ../noodl-core-ui/src/components/inputs/IconButton/IconButton.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(IconButton_module/* default */.A, options);




       /* harmony default export */ const IconButton_IconButton_module = (IconButton_module/* default */.A && IconButton_module/* default */.A.locals ? IconButton_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/IconButton/IconButton.tsx





var IconButtonVariant;
(function (IconButtonVariant) {
    IconButtonVariant["Default"] = "is-variant-default";
    IconButtonVariant["Transparent"] = "is-variant-transparent";
    IconButtonVariant["SemiTransparent"] = "is-variant-semi-transparent";
    IconButtonVariant["OpaqueOnHover"] = "is-variant-opaque-on-hover";
})(IconButtonVariant || (IconButtonVariant = {}));
var IconButtonState;
(function (IconButtonState) {
    IconButtonState["Default"] = "is-state-default";
    IconButtonState["Active"] = "is-state-active";
    IconButtonState["Rotated"] = "is-state-rotated";
})(IconButtonState || (IconButtonState = {}));
var IconButtonSize;
(function (IconButtonSize) {
    IconButtonSize["Default"] = "is-button-size-default";
    IconButtonSize["Bigger"] = "is-button-size-bigger";
})(IconButtonSize || (IconButtonSize = {}));
function iconSizeToLabelSize(iconSize) {
    switch (iconSize) {
        case Icon/* IconSize */.lK.Large:
            return Label/* LabelSize */.IV.Big;
        case Icon/* IconSize */.lK.Small:
            return Label/* LabelSize */.IV.Small;
        case Icon/* IconSize */.lK.Tiny:
            return Label/* LabelSize */.IV.Small;
        default:
            return Label/* LabelSize */.IV.Default;
    }
}
const IconButton = external_react_default().forwardRef(({ icon, size = Icon/* IconSize */.lK.Default, buttonSize = IconButtonSize.Default, variant = IconButtonVariant.Default, state = IconButtonState.Default, iconVariant, isDisabled, label, testId, onClick, UNSAFE_className, UNSAFE_style, id }, ref) => {
    return (external_react_default().createElement("button", { ref: ref, id: id, className: external_classnames_default()(IconButton_IconButton_module['Root'], IconButton_IconButton_module[variant], IconButton_IconButton_module[state], IconButton_IconButton_module[buttonSize], IconButton_IconButton_module[`is-icon-variant-${iconVariant}`], UNSAFE_className), onClick: onClick, disabled: isDisabled, style: UNSAFE_style, "data-test": testId },
        external_react_default().createElement(Icon/* Icon */.In, { icon: icon, size: size, UNSAFE_className: IconButton_IconButton_module['Icon'], variant: iconVariant }),
        label && (external_react_default().createElement(Label/* Label */.JU, { size: iconSizeToLabelSize(size), variant: iconVariant, UNSAFE_className: IconButton_IconButton_module.Label }, label))));
});

;// ../noodl-core-ui/src/components/inputs/IconButton/index.ts



/***/ }),

/***/ 28286:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `@keyframes CompleteStep-module__slideInUp--Tx129{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes CompleteStep-module__successPulse--CK8w4{0%,100%{transform:scale(1);filter:drop-shadow(0 0 8px rgba(34, 197, 94, 0.4))}50%{transform:scale(1.1);filter:drop-shadow(0 0 16px rgba(34, 197, 94, 0.6))}}@keyframes CompleteStep-module__countUp--TOxuv{from{transform:scale(0.8);opacity:0}to{transform:scale(1);opacity:1}}.CompleteStep-module__Root--SKAs7{display:flex;flex-direction:column;height:100%;animation:CompleteStep-module__slideInUp--Tx129 300ms ease-out}.CompleteStep-module__Header--BLk39{display:flex;flex-direction:column;align-items:center;gap:16px;margin-bottom:24px;padding:20px;background:linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, transparent 100%);border-radius:12px}.CompleteStep-module__Header--BLk39 .CompleteStep-module__SuccessIcon--gOzH7{width:64px;height:64px;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg, rgba(34, 197, 94, 0.2) 0%, rgba(34, 197, 94, 0.1) 100%);border-radius:50%;animation:CompleteStep-module__successPulse--CK8w4 2s ease-in-out infinite}.CompleteStep-module__Header--BLk39 .CompleteStep-module__SuccessIcon--gOzH7 svg{width:36px;height:36px;color:var(--theme-color-success)}.CompleteStep-module__Header--BLk39 h2{font-size:24px;font-weight:700;color:var(--theme-color-fg-highlight);margin:0;text-align:center}.CompleteStep-module__Header--BLk39 p{font-size:14px;color:var(--theme-color-fg-default);margin:0;text-align:center}.CompleteStep-module__Stats--Z5m8m{display:grid;grid-template-columns:repeat(auto-fit, minmax(140px, 1fr));gap:16px;margin-bottom:24px}.CompleteStep-module__StatCard--Jdt7v{display:flex;flex-direction:column;align-items:center;gap:12px;padding:20px 16px;background:linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);border-radius:12px;text-align:center;border:1px solid var(--theme-color-bg-2);transition:all 250ms ease-in-out}.CompleteStep-module__StatCard--Jdt7v:hover{transform:translateY(-4px);box-shadow:0 8px 16px rgba(0,0,0,.15)}.CompleteStep-module__StatCardIcon--XGbSt{width:40px;height:40px;display:flex;align-items:center;justify-content:center;border-radius:50%;transition:all 200ms ease-in-out}.CompleteStep-module__StatCardIcon--XGbSt svg{width:22px;height:22px}.CompleteStep-module__StatCard--Jdt7v.CompleteStep-module__is-success--UkRmn .CompleteStep-module__StatCardIcon--XGbSt{color:var(--theme-color-success);background-color:rgba(34,197,94,.15)}.CompleteStep-module__StatCard--Jdt7v.CompleteStep-module__is-warning--yifEq .CompleteStep-module__StatCardIcon--XGbSt{color:var(--theme-color-warning);background-color:rgba(251,191,36,.15)}.CompleteStep-module__StatCard--Jdt7v.CompleteStep-module__is-error--QL3Pk .CompleteStep-module__StatCardIcon--XGbSt{color:var(--theme-color-danger);background-color:rgba(239,68,68,.15)}.CompleteStep-module__StatCard--Jdt7v:hover .CompleteStep-module__StatCardIcon--XGbSt{transform:scale(1.1) rotate(5deg)}.CompleteStep-module__StatCardValue--fWijz{font-size:32px;font-weight:700;color:var(--theme-color-fg-highlight);line-height:1;font-variant-numeric:tabular-nums;animation:CompleteStep-module__countUp--TOxuv 400ms ease-out}.CompleteStep-module__StatCardLabel--Ps_qP{font-size:11px;color:var(--theme-color-fg-default);text-transform:uppercase;letter-spacing:.8px;font-weight:600}.CompleteStep-module__MetaInfo--U9Xc0{display:flex;gap:20px;margin-bottom:20px;padding:16px;background:linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);border-radius:10px;flex-wrap:wrap}.CompleteStep-module__MetaItem--NdirR{display:flex;align-items:center;gap:8px;padding:8px 16px;background-color:var(--theme-color-bg-4);border-radius:20px;font-size:13px;font-weight:500;color:var(--theme-color-fg-highlight);border:1px solid var(--theme-color-bg-2)}.CompleteStep-module__MetaItem--NdirR svg{width:16px;height:16px;color:var(--theme-color-primary)}.CompleteStep-module__Paths--ocy9Z{padding:20px;background:linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);border-radius:12px;border:1px solid var(--theme-color-bg-2);margin-bottom:20px}.CompleteStep-module__Paths--ocy9Z h3{font-size:14px;font-weight:600;color:var(--theme-color-fg-highlight);margin:0 0 16px 0}.CompleteStep-module__PathItem--fxYmL{display:flex;gap:16px;padding:16px;background-color:var(--theme-color-bg-4);border-radius:8px;border:1px solid var(--theme-color-bg-3);transition:all 200ms ease-in-out}.CompleteStep-module__PathItem--fxYmL:not(:last-child){margin-bottom:12px}.CompleteStep-module__PathItem--fxYmL svg{width:20px;height:20px;color:var(--theme-color-primary);flex-shrink:0;margin-top:2px}.CompleteStep-module__PathItem--fxYmL:hover{background-color:var(--theme-color-bg-3);border-color:var(--theme-color-primary)}.CompleteStep-module__PathContent--cTaVg{display:flex;flex-direction:column;gap:6px;overflow:hidden;flex:1}.CompleteStep-module__PathContent--cTaVg .CompleteStep-module__PathLabel--gjNl8{font-size:12px;font-weight:600;color:var(--theme-color-fg-default);text-transform:uppercase;letter-spacing:.5px}.CompleteStep-module__PathContent--cTaVg .CompleteStep-module__PathValue--Z5WGg{font-family:monospace;font-size:12px;color:var(--theme-color-fg-highlight);word-break:break-all;background-color:var(--theme-color-bg-2);padding:8px 12px;border-radius:6px}.CompleteStep-module__NextSteps--r8KHt{padding:20px;background:linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);border-radius:12px;border:1px solid var(--theme-color-bg-2);margin-bottom:20px}.CompleteStep-module__NextSteps--r8KHt h3{font-size:14px;font-weight:600;color:var(--theme-color-fg-highlight);margin:0 0 16px 0;display:flex;align-items:center;gap:8px}.CompleteStep-module__NextSteps--r8KHt h3 svg{width:18px;height:18px;color:var(--theme-color-primary)}.CompleteStep-module__StepsList--uThlB{list-style:none;padding:0;margin:0}.CompleteStep-module__StepsList--uThlB li{display:flex;gap:16px;padding:16px;background-color:var(--theme-color-bg-4);border-radius:8px;font-size:14px;line-height:1.5;color:var(--theme-color-fg-default);transition:all 200ms ease-in-out}.CompleteStep-module__StepsList--uThlB li:not(:last-child){margin-bottom:10px}.CompleteStep-module__StepsList--uThlB li:hover{background-color:var(--theme-color-bg-3);transform:translateX(4px)}.CompleteStep-module__StepsList--uThlB li svg{width:20px;height:20px;flex-shrink:0;margin-top:2px;color:var(--theme-color-primary)}.CompleteStep-module__Actions--MnTVD{margin-top:auto;padding-top:24px;display:flex;justify-content:flex-end;gap:12px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/migration/steps/CompleteStep.module.scss"],"names":[],"mappings":"AAMA,iDACE,KACE,SAAA,CACA,0BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,oDACE,QAEE,kBAAA,CACA,kDAAA,CAEF,IACE,oBAAA,CACA,mDAAA,CAAA,CAIJ,+CACE,KACE,oBAAA,CACA,SAAA,CAEF,GACE,kBAAA,CACA,SAAA,CAAA,CAIJ,kCACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,8DAAA,CAGF,oCACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,QAAA,CACA,kBAAA,CACA,YAAA,CACA,+EAAA,CACA,kBAAA,CAEA,6EACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,0FAAA,CACA,iBAAA,CACA,0EAAA,CAEA,iFACE,UAAA,CACA,WAAA,CACA,gCAAA,CAIJ,uCACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,QAAA,CACA,iBAAA,CAGF,sCACE,cAAA,CACA,mCAAA,CACA,QAAA,CACA,iBAAA,CAIJ,mCACE,YAAA,CACA,0DAAA,CACA,QAAA,CACA,kBAAA,CAGF,sCACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,QAAA,CACA,iBAAA,CACA,4FAAA,CACA,kBAAA,CACA,iBAAA,CACA,wCAAA,CACA,gCAAA,CAEA,4CACE,0BAAA,CACA,qCAAA,CAIJ,0CACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,gCAAA,CAEA,8CACE,UAAA,CACA,WAAA,CAIJ,uHACE,gCAAA,CACA,oCAAA,CAGF,uHACE,gCAAA,CACA,qCAAA,CAGF,qHACE,+BAAA,CACA,oCAAA,CAGF,sFACE,iCAAA,CAGF,2CACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,aAAA,CACA,iCAAA,CACA,4DAAA,CAGF,2CACE,cAAA,CACA,mCAAA,CACA,wBAAA,CACA,mBAAA,CACA,eAAA,CAGF,sCACE,YAAA,CACA,QAAA,CACA,kBAAA,CACA,YAAA,CACA,4FAAA,CACA,kBAAA,CACA,cAAA,CAGF,sCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,gBAAA,CACA,wCAAA,CACA,kBAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CACA,wCAAA,CAEA,0CACE,UAAA,CACA,WAAA,CACA,gCAAA,CAIJ,mCACE,YAAA,CACA,4FAAA,CACA,kBAAA,CACA,wCAAA,CACA,kBAAA,CAEA,sCACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,iBAAA,CAIJ,sCACE,YAAA,CACA,QAAA,CACA,YAAA,CACA,wCAAA,CACA,iBAAA,CACA,wCAAA,CACA,gCAAA,CAEA,uDACE,kBAAA,CAGF,0CACE,UAAA,CACA,WAAA,CACA,gCAAA,CACA,aAAA,CACA,cAAA,CAGF,4CACE,wCAAA,CACA,uCAAA,CAIJ,yCACE,YAAA,CACA,qBAAA,CACA,OAAA,CACA,eAAA,CACA,MAAA,CAEA,gFACE,cAAA,CACA,eAAA,CACA,mCAAA,CACA,wBAAA,CACA,mBAAA,CAGF,gFACE,qBAAA,CACA,cAAA,CACA,qCAAA,CACA,oBAAA,CACA,wCAAA,CACA,gBAAA,CACA,iBAAA,CAIJ,uCACE,YAAA,CACA,4FAAA,CACA,kBAAA,CACA,wCAAA,CACA,kBAAA,CAEA,0CACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,iBAAA,CACA,YAAA,CACA,kBAAA,CACA,OAAA,CAEA,8CACE,UAAA,CACA,WAAA,CACA,gCAAA,CAKN,uCACE,eAAA,CACA,SAAA,CACA,QAAA,CAEA,0CACE,YAAA,CACA,QAAA,CACA,YAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CACA,gCAAA,CAEA,2DACE,kBAAA,CAGF,gDACE,wCAAA,CACA,yBAAA,CAGF,8CACE,UAAA,CACA,WAAA,CACA,aAAA,CACA,cAAA,CACA,gCAAA,CAKN,qCACE,eAAA,CACA,gBAAA,CACA,YAAA,CACA,wBAAA,CACA,QAAA","sourcesContent":["/**\n * CompleteStep Styles\n * \n * Enhanced final step with celebration and beautiful summary.\n */\n\n@keyframes slideInUp {\n  from {\n    opacity: 0;\n    transform: translateY(10px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n@keyframes successPulse {\n  0%,\n  100% {\n    transform: scale(1);\n    filter: drop-shadow(0 0 8px rgba(34, 197, 94, 0.4));\n  }\n  50% {\n    transform: scale(1.1);\n    filter: drop-shadow(0 0 16px rgba(34, 197, 94, 0.6));\n  }\n}\n\n@keyframes countUp {\n  from {\n    transform: scale(0.8);\n    opacity: 0;\n  }\n  to {\n    transform: scale(1);\n    opacity: 1;\n  }\n}\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  animation: slideInUp 300ms ease-out;\n}\n\n.Header {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 16px;\n  margin-bottom: 24px;\n  padding: 20px;\n  background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, transparent 100%);\n  border-radius: 12px;\n\n  .SuccessIcon {\n    width: 64px;\n    height: 64px;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    background: linear-gradient(135deg, rgba(34, 197, 94, 0.2) 0%, rgba(34, 197, 94, 0.1) 100%);\n    border-radius: 50%;\n    animation: successPulse 2s ease-in-out infinite;\n\n    svg {\n      width: 36px;\n      height: 36px;\n      color: var(--theme-color-success);\n    }\n  }\n\n  h2 {\n    font-size: 24px;\n    font-weight: 700;\n    color: var(--theme-color-fg-highlight);\n    margin: 0;\n    text-align: center;\n  }\n\n  p {\n    font-size: 14px;\n    color: var(--theme-color-fg-default);\n    margin: 0;\n    text-align: center;\n  }\n}\n\n.Stats {\n  display: grid;\n  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));\n  gap: 16px;\n  margin-bottom: 24px;\n}\n\n.StatCard {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 12px;\n  padding: 20px 16px;\n  background: linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);\n  border-radius: 12px;\n  text-align: center;\n  border: 1px solid var(--theme-color-bg-2);\n  transition: all 250ms ease-in-out;\n\n  &:hover {\n    transform: translateY(-4px);\n    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);\n  }\n}\n\n.StatCardIcon {\n  width: 40px;\n  height: 40px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  border-radius: 50%;\n  transition: all 200ms ease-in-out;\n\n  svg {\n    width: 22px;\n    height: 22px;\n  }\n}\n\n.StatCard.is-success .StatCardIcon {\n  color: var(--theme-color-success);\n  background-color: rgba(34, 197, 94, 0.15);\n}\n\n.StatCard.is-warning .StatCardIcon {\n  color: var(--theme-color-warning);\n  background-color: rgba(251, 191, 36, 0.15);\n}\n\n.StatCard.is-error .StatCardIcon {\n  color: var(--theme-color-danger);\n  background-color: rgba(239, 68, 68, 0.15);\n}\n\n.StatCard:hover .StatCardIcon {\n  transform: scale(1.1) rotate(5deg);\n}\n\n.StatCardValue {\n  font-size: 32px;\n  font-weight: 700;\n  color: var(--theme-color-fg-highlight);\n  line-height: 1;\n  font-variant-numeric: tabular-nums;\n  animation: countUp 400ms ease-out;\n}\n\n.StatCardLabel {\n  font-size: 11px;\n  color: var(--theme-color-fg-default);\n  text-transform: uppercase;\n  letter-spacing: 0.8px;\n  font-weight: 600;\n}\n\n.MetaInfo {\n  display: flex;\n  gap: 20px;\n  margin-bottom: 20px;\n  padding: 16px;\n  background: linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);\n  border-radius: 10px;\n  flex-wrap: wrap;\n}\n\n.MetaItem {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 8px 16px;\n  background-color: var(--theme-color-bg-4);\n  border-radius: 20px;\n  font-size: 13px;\n  font-weight: 500;\n  color: var(--theme-color-fg-highlight);\n  border: 1px solid var(--theme-color-bg-2);\n\n  svg {\n    width: 16px;\n    height: 16px;\n    color: var(--theme-color-primary);\n  }\n}\n\n.Paths {\n  padding: 20px;\n  background: linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);\n  border-radius: 12px;\n  border: 1px solid var(--theme-color-bg-2);\n  margin-bottom: 20px;\n\n  h3 {\n    font-size: 14px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    margin: 0 0 16px 0;\n  }\n}\n\n.PathItem {\n  display: flex;\n  gap: 16px;\n  padding: 16px;\n  background-color: var(--theme-color-bg-4);\n  border-radius: 8px;\n  border: 1px solid var(--theme-color-bg-3);\n  transition: all 200ms ease-in-out;\n\n  &:not(:last-child) {\n    margin-bottom: 12px;\n  }\n\n  svg {\n    width: 20px;\n    height: 20px;\n    color: var(--theme-color-primary);\n    flex-shrink: 0;\n    margin-top: 2px;\n  }\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.PathContent {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n  overflow: hidden;\n  flex: 1;\n\n  .PathLabel {\n    font-size: 12px;\n    font-weight: 600;\n    color: var(--theme-color-fg-default);\n    text-transform: uppercase;\n    letter-spacing: 0.5px;\n  }\n\n  .PathValue {\n    font-family: monospace;\n    font-size: 12px;\n    color: var(--theme-color-fg-highlight);\n    word-break: break-all;\n    background-color: var(--theme-color-bg-2);\n    padding: 8px 12px;\n    border-radius: 6px;\n  }\n}\n\n.NextSteps {\n  padding: 20px;\n  background: linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);\n  border-radius: 12px;\n  border: 1px solid var(--theme-color-bg-2);\n  margin-bottom: 20px;\n\n  h3 {\n    font-size: 14px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    margin: 0 0 16px 0;\n    display: flex;\n    align-items: center;\n    gap: 8px;\n\n    svg {\n      width: 18px;\n      height: 18px;\n      color: var(--theme-color-primary);\n    }\n  }\n}\n\n.StepsList {\n  list-style: none;\n  padding: 0;\n  margin: 0;\n\n  li {\n    display: flex;\n    gap: 16px;\n    padding: 16px;\n    background-color: var(--theme-color-bg-4);\n    border-radius: 8px;\n    font-size: 14px;\n    line-height: 1.5;\n    color: var(--theme-color-fg-default);\n    transition: all 200ms ease-in-out;\n\n    &:not(:last-child) {\n      margin-bottom: 10px;\n    }\n\n    &:hover {\n      background-color: var(--theme-color-bg-3);\n      transform: translateX(4px);\n    }\n\n    svg {\n      width: 20px;\n      height: 20px;\n      flex-shrink: 0;\n      margin-top: 2px;\n      color: var(--theme-color-primary);\n    }\n  }\n}\n\n.Actions {\n  margin-top: auto;\n  padding-top: 24px;\n  display: flex;\n  justify-content: flex-end;\n  gap: 12px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `CompleteStep-module__Root--SKAs7`,
	"slideInUp": `CompleteStep-module__slideInUp--Tx129`,
	"Header": `CompleteStep-module__Header--BLk39`,
	"SuccessIcon": `CompleteStep-module__SuccessIcon--gOzH7`,
	"successPulse": `CompleteStep-module__successPulse--CK8w4`,
	"Stats": `CompleteStep-module__Stats--Z5m8m`,
	"StatCard": `CompleteStep-module__StatCard--Jdt7v`,
	"StatCardIcon": `CompleteStep-module__StatCardIcon--XGbSt`,
	"is-success": `CompleteStep-module__is-success--UkRmn`,
	"is-warning": `CompleteStep-module__is-warning--yifEq`,
	"is-error": `CompleteStep-module__is-error--QL3Pk`,
	"StatCardValue": `CompleteStep-module__StatCardValue--fWijz`,
	"countUp": `CompleteStep-module__countUp--TOxuv`,
	"StatCardLabel": `CompleteStep-module__StatCardLabel--Ps_qP`,
	"MetaInfo": `CompleteStep-module__MetaInfo--U9Xc0`,
	"MetaItem": `CompleteStep-module__MetaItem--NdirR`,
	"Paths": `CompleteStep-module__Paths--ocy9Z`,
	"PathItem": `CompleteStep-module__PathItem--fxYmL`,
	"PathContent": `CompleteStep-module__PathContent--cTaVg`,
	"PathLabel": `CompleteStep-module__PathLabel--gjNl8`,
	"PathValue": `CompleteStep-module__PathValue--Z5WGg`,
	"NextSteps": `CompleteStep-module__NextSteps--r8KHt`,
	"StepsList": `CompleteStep-module__StepsList--uThlB`,
	"Actions": `CompleteStep-module__Actions--MnTVD`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 28354:
/***/ ((module) => {

"use strict";
module.exports = require("util");

/***/ }),

/***/ 28593:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   F: () => (/* binding */ BasicNodeType)
/* harmony export */ });
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47821);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_shared_model__WEBPACK_IMPORTED_MODULE_0__);

class BasicNodeType extends (_shared_model__WEBPACK_IMPORTED_MODULE_0___default()) {
    get localName() {
        return this.name;
    }
    get fullName() {
        return (this.category ? this.category + '/' : '') + this.name;
    }
    get displayName() {
        return this.displayNodeName ? this.displayNodeName : this.localName;
    }
    constructor(args) {
        super();
        // Set default variable
        this.runtimeTypes = [];
        this.searchTags = [];
        // Add anything...
        // TODO: Try to get rid of this args loop
        for (const i in args) {
            this[i] = args[i];
        }
        return this;
    }
    labelForNode(node) {
        // If usePortAsLabel is specified use that port value as label
        if (node.type.usePortAsLabel && node.parameters[node.type.usePortAsLabel]) {
            let labelName = node.parameters[node.type.usePortAsLabel];
            const truncationMode = node.type.portLabelTruncationMode;
            if (truncationMode === 'filename') {
                labelName = labelName.split('/').pop();
            }
            else if (truncationMode === 'length' && labelName.length > 36) {
                labelName = labelName.slice(0, 33) + '...';
            }
            return labelName;
        }
        else {
            return this.displayName;
        }
    }
    /**
     * Module is undefined for basic types
     */
    getModule() { }
}


/***/ }),

/***/ 28663:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/


/* Default standalone editor fonts */
.monaco-editor {
	font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", system-ui, "Ubuntu", "Droid Sans", sans-serif;
	--monaco-monospace-font: "SF Mono", Monaco, Menlo, Consolas, "Ubuntu Mono", "Liberation Mono", "DejaVu Sans Mono", "Courier New", monospace;
}

.monaco-menu .monaco-action-bar.vertical .action-item .action-menu-item:focus .action-label {
	stroke-width: 1.2px;
}

.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label,
.monaco-editor.hc-black .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label,
.monaco-editor.hc-light .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label {
	stroke-width: 1.2px;
}

.monaco-hover p {
	margin: 0;
}

/* See https://github.com/microsoft/monaco-editor/issues/2168#issuecomment-780078600 */
.monaco-aria-container {
	position: absolute !important;
	top: 0; /* avoid being placed underneath a sibling element */
	height: 1px;
	width: 1px;
	margin: -1px;
	overflow: hidden;
	padding: 0;
	clip: rect(1px, 1px, 1px, 1px);
	clip-path: inset(50%);
}

/* The hc-black theme is already high contrast optimized */
.monaco-editor.hc-black,
.monaco-editor.hc-light {
	-ms-high-contrast-adjust: none;
}
/* In case the browser goes into high contrast mode and the editor is not configured with the hc-black theme */
@media screen and (-ms-high-contrast:active) {

	/* current line highlight */
	.monaco-editor.vs .view-overlays .current-line,
	.monaco-editor.vs-dark .view-overlays .current-line {
		border-color: windowtext !important;
		border-left: 0;
		border-right: 0;
	}

	/* view cursors */
	.monaco-editor.vs .cursor,
	.monaco-editor.vs-dark .cursor {
		background-color: windowtext !important;
	}
	/* dnd target */
	.monaco-editor.vs .dnd-target,
	.monaco-editor.vs-dark .dnd-target {
		border-color: windowtext !important;
	}

	/* selected text background */
	.monaco-editor.vs .selected-text,
	.monaco-editor.vs-dark .selected-text {
		background-color: highlight !important;
	}

	/* allow the text to have a transparent background. */
	.monaco-editor.vs .view-line,
	.monaco-editor.vs-dark .view-line {
		-ms-high-contrast-adjust: none;
	}

	/* text color */
	.monaco-editor.vs .view-line span,
	.monaco-editor.vs-dark .view-line span {
		color: windowtext !important;
	}
	/* selected text color */
	.monaco-editor.vs .view-line span.inline-selected-text,
	.monaco-editor.vs-dark .view-line span.inline-selected-text {
		color: highlighttext !important;
	}

	/* allow decorations */
	.monaco-editor.vs .view-overlays,
	.monaco-editor.vs-dark .view-overlays {
		-ms-high-contrast-adjust: none;
	}

	/* various decorations */
	.monaco-editor.vs .selectionHighlight,
	.monaco-editor.vs-dark .selectionHighlight,
	.monaco-editor.vs .wordHighlight,
	.monaco-editor.vs-dark .wordHighlight,
	.monaco-editor.vs .wordHighlightStrong,
	.monaco-editor.vs-dark .wordHighlightStrong,
	.monaco-editor.vs .reference-decoration,
	.monaco-editor.vs-dark .reference-decoration {
		border: 2px dotted highlight !important;
		background: transparent !important;
		box-sizing: border-box;
	}
	.monaco-editor.vs .rangeHighlight,
	.monaco-editor.vs-dark .rangeHighlight {
		background: transparent !important;
		border: 1px dotted activeborder !important;
		box-sizing: border-box;
	}
	.monaco-editor.vs .bracket-match,
	.monaco-editor.vs-dark .bracket-match {
		border-color: windowtext !important;
		background: transparent !important;
	}

	/* find widget */
	.monaco-editor.vs .findMatch,
	.monaco-editor.vs-dark .findMatch,
	.monaco-editor.vs .currentFindMatch,
	.monaco-editor.vs-dark .currentFindMatch {
		border: 2px dotted activeborder !important;
		background: transparent !important;
		box-sizing: border-box;
	}
	.monaco-editor.vs .find-widget,
	.monaco-editor.vs-dark .find-widget {
		border: 1px solid windowtext;
	}

	/* list - used by suggest widget */
	.monaco-editor.vs .monaco-list .monaco-list-row,
	.monaco-editor.vs-dark .monaco-list .monaco-list-row {
		-ms-high-contrast-adjust: none;
		color: windowtext !important;
	}
	.monaco-editor.vs .monaco-list .monaco-list-row.focused,
	.monaco-editor.vs-dark .monaco-list .monaco-list-row.focused {
		color: highlighttext !important;
		background-color: highlight !important;
	}
	.monaco-editor.vs .monaco-list .monaco-list-row:hover,
	.monaco-editor.vs-dark .monaco-list .monaco-list-row:hover {
		background: transparent !important;
		border: 1px solid highlight;
		box-sizing: border-box;
	}

	/* scrollbars */
	.monaco-editor.vs .monaco-scrollable-element > .scrollbar,
	.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar {
		-ms-high-contrast-adjust: none;
		background: background !important;
		border: 1px solid windowtext;
		box-sizing: border-box;
	}
	.monaco-editor.vs .monaco-scrollable-element > .scrollbar > .slider,
	.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar > .slider {
		background: windowtext !important;
	}
	.monaco-editor.vs .monaco-scrollable-element > .scrollbar > .slider:hover,
	.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar > .slider:hover {
		background: highlight !important;
	}
	.monaco-editor.vs .monaco-scrollable-element > .scrollbar > .slider.active,
	.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar > .slider.active {
		background: highlight !important;
	}

	/* overview ruler */
	.monaco-editor.vs .decorationsOverviewRuler,
	.monaco-editor.vs-dark .decorationsOverviewRuler {
		opacity: 0;
	}

	/* minimap */
	.monaco-editor.vs .minimap,
	.monaco-editor.vs-dark .minimap {
		display: none;
	}

	/* squiggles */
	.monaco-editor.vs .squiggly-d-error,
	.monaco-editor.vs-dark .squiggly-d-error {
		background: transparent !important;
		border-bottom: 4px double #E47777;
	}
	.monaco-editor.vs .squiggly-c-warning,
	.monaco-editor.vs-dark .squiggly-c-warning {
		border-bottom: 4px double #71B771;
	}
	.monaco-editor.vs .squiggly-b-info,
	.monaco-editor.vs-dark .squiggly-b-info {
		border-bottom: 4px double #71B771;
	}
	.monaco-editor.vs .squiggly-a-hint,
	.monaco-editor.vs-dark .squiggly-a-hint {
		border-bottom: 4px double #6c6c6c;
	}

	/* contextmenu */
	.monaco-editor.vs .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label,
	.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label {
		-ms-high-contrast-adjust: none;
		color: highlighttext !important;
		background-color: highlight !important;
	}
	.monaco-editor.vs .monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .action-label,
	.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .action-label {
		-ms-high-contrast-adjust: none;
		background: transparent !important;
		border: 1px solid highlight;
		box-sizing: border-box;
	}

	/* diff editor */
	.monaco-diff-editor.vs .diffOverviewRuler,
	.monaco-diff-editor.vs-dark .diffOverviewRuler {
		display: none;
	}
	.monaco-editor.vs .line-insert,
	.monaco-editor.vs-dark .line-insert,
	.monaco-editor.vs .line-delete,
	.monaco-editor.vs-dark .line-delete {
		background: transparent !important;
		border: 1px solid highlight !important;
		box-sizing: border-box;
	}
	.monaco-editor.vs .char-insert,
	.monaco-editor.vs-dark .char-insert,
	.monaco-editor.vs .char-delete,
	.monaco-editor.vs-dark .char-delete {
		background: transparent !important;
	}
}

/*.monaco-editor.vs [tabindex="0"]:focus {
	outline: 1px solid rgba(0, 122, 204, 0.4);
	outline-offset: -1px;
	opacity: 1 !important;
}

.monaco-editor.vs-dark [tabindex="0"]:focus {
	outline: 1px solid rgba(14, 99, 156, 0.6);
	outline-offset: -1px;
	opacity: 1 !important;
}*/
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/standalone-tokens.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;;AAG/F,oCAAoC;AACpC;CACC,6IAA6I;CAC7I,2IAA2I;AAC5I;;AAEA;CACC,mBAAmB;AACpB;;AAEA;;;CAGC,mBAAmB;AACpB;;AAEA;CACC,SAAS;AACV;;AAEA,sFAAsF;AACtF;CACC,6BAA6B;CAC7B,MAAM,EAAE,oDAAoD;CAC5D,WAAW;CACX,UAAU;CACV,YAAY;CACZ,gBAAgB;CAChB,UAAU;CACV,8BAA8B;CAC9B,qBAAqB;AACtB;;AAEA,0DAA0D;AAC1D;;CAEC,8BAA8B;AAC/B;AACA,8GAA8G;AAC9G;;CAEC,2BAA2B;CAC3B;;EAEC,mCAAmC;EACnC,cAAc;EACd,eAAe;CAChB;;CAEA,iBAAiB;CACjB;;EAEC,uCAAuC;CACxC;CACA,eAAe;CACf;;EAEC,mCAAmC;CACpC;;CAEA,6BAA6B;CAC7B;;EAEC,sCAAsC;CACvC;;CAEA,qDAAqD;CACrD;;EAEC,8BAA8B;CAC/B;;CAEA,eAAe;CACf;;EAEC,4BAA4B;CAC7B;CACA,wBAAwB;CACxB;;EAEC,+BAA+B;CAChC;;CAEA,sBAAsB;CACtB;;EAEC,8BAA8B;CAC/B;;CAEA,wBAAwB;CACxB;;;;;;;;EAQC,uCAAuC;EACvC,kCAAkC;EAClC,sBAAsB;CACvB;CACA;;EAEC,kCAAkC;EAClC,0CAA0C;EAC1C,sBAAsB;CACvB;CACA;;EAEC,mCAAmC;EACnC,kCAAkC;CACnC;;CAEA,gBAAgB;CAChB;;;;EAIC,0CAA0C;EAC1C,kCAAkC;EAClC,sBAAsB;CACvB;CACA;;EAEC,4BAA4B;CAC7B;;CAEA,kCAAkC;CAClC;;EAEC,8BAA8B;EAC9B,4BAA4B;CAC7B;CACA;;EAEC,+BAA+B;EAC/B,sCAAsC;CACvC;CACA;;EAEC,kCAAkC;EAClC,2BAA2B;EAC3B,sBAAsB;CACvB;;CAEA,eAAe;CACf;;EAEC,8BAA8B;EAC9B,iCAAiC;EACjC,4BAA4B;EAC5B,sBAAsB;CACvB;CACA;;EAEC,iCAAiC;CAClC;CACA;;EAEC,gCAAgC;CACjC;CACA;;EAEC,gCAAgC;CACjC;;CAEA,mBAAmB;CACnB;;EAEC,UAAU;CACX;;CAEA,YAAY;CACZ;;EAEC,aAAa;CACd;;CAEA,cAAc;CACd;;EAEC,kCAAkC;EAClC,iCAAiC;CAClC;CACA;;EAEC,iCAAiC;CAClC;CACA;;EAEC,iCAAiC;CAClC;CACA;;EAEC,iCAAiC;CAClC;;CAEA,gBAAgB;CAChB;;EAEC,8BAA8B;EAC9B,+BAA+B;EAC/B,sCAAsC;CACvC;CACA;;EAEC,8BAA8B;EAC9B,kCAAkC;EAClC,2BAA2B;EAC3B,sBAAsB;CACvB;;CAEA,gBAAgB;CAChB;;EAEC,aAAa;CACd;CACA;;;;EAIC,kCAAkC;EAClC,sCAAsC;EACtC,sBAAsB;CACvB;CACA;;;;EAIC,kCAAkC;CACnC;AACD;;AAEA;;;;;;;;;;EAUE","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n\n/* Default standalone editor fonts */\n.monaco-editor {\n\tfont-family: -apple-system, BlinkMacSystemFont, \"Segoe WPC\", \"Segoe UI\", \"HelveticaNeue-Light\", system-ui, \"Ubuntu\", \"Droid Sans\", sans-serif;\n\t--monaco-monospace-font: \"SF Mono\", Monaco, Menlo, Consolas, \"Ubuntu Mono\", \"Liberation Mono\", \"DejaVu Sans Mono\", \"Courier New\", monospace;\n}\n\n.monaco-menu .monaco-action-bar.vertical .action-item .action-menu-item:focus .action-label {\n\tstroke-width: 1.2px;\n}\n\n.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label,\n.monaco-editor.hc-black .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label,\n.monaco-editor.hc-light .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label {\n\tstroke-width: 1.2px;\n}\n\n.monaco-hover p {\n\tmargin: 0;\n}\n\n/* See https://github.com/microsoft/monaco-editor/issues/2168#issuecomment-780078600 */\n.monaco-aria-container {\n\tposition: absolute !important;\n\ttop: 0; /* avoid being placed underneath a sibling element */\n\theight: 1px;\n\twidth: 1px;\n\tmargin: -1px;\n\toverflow: hidden;\n\tpadding: 0;\n\tclip: rect(1px, 1px, 1px, 1px);\n\tclip-path: inset(50%);\n}\n\n/* The hc-black theme is already high contrast optimized */\n.monaco-editor.hc-black,\n.monaco-editor.hc-light {\n\t-ms-high-contrast-adjust: none;\n}\n/* In case the browser goes into high contrast mode and the editor is not configured with the hc-black theme */\n@media screen and (-ms-high-contrast:active) {\n\n\t/* current line highlight */\n\t.monaco-editor.vs .view-overlays .current-line,\n\t.monaco-editor.vs-dark .view-overlays .current-line {\n\t\tborder-color: windowtext !important;\n\t\tborder-left: 0;\n\t\tborder-right: 0;\n\t}\n\n\t/* view cursors */\n\t.monaco-editor.vs .cursor,\n\t.monaco-editor.vs-dark .cursor {\n\t\tbackground-color: windowtext !important;\n\t}\n\t/* dnd target */\n\t.monaco-editor.vs .dnd-target,\n\t.monaco-editor.vs-dark .dnd-target {\n\t\tborder-color: windowtext !important;\n\t}\n\n\t/* selected text background */\n\t.monaco-editor.vs .selected-text,\n\t.monaco-editor.vs-dark .selected-text {\n\t\tbackground-color: highlight !important;\n\t}\n\n\t/* allow the text to have a transparent background. */\n\t.monaco-editor.vs .view-line,\n\t.monaco-editor.vs-dark .view-line {\n\t\t-ms-high-contrast-adjust: none;\n\t}\n\n\t/* text color */\n\t.monaco-editor.vs .view-line span,\n\t.monaco-editor.vs-dark .view-line span {\n\t\tcolor: windowtext !important;\n\t}\n\t/* selected text color */\n\t.monaco-editor.vs .view-line span.inline-selected-text,\n\t.monaco-editor.vs-dark .view-line span.inline-selected-text {\n\t\tcolor: highlighttext !important;\n\t}\n\n\t/* allow decorations */\n\t.monaco-editor.vs .view-overlays,\n\t.monaco-editor.vs-dark .view-overlays {\n\t\t-ms-high-contrast-adjust: none;\n\t}\n\n\t/* various decorations */\n\t.monaco-editor.vs .selectionHighlight,\n\t.monaco-editor.vs-dark .selectionHighlight,\n\t.monaco-editor.vs .wordHighlight,\n\t.monaco-editor.vs-dark .wordHighlight,\n\t.monaco-editor.vs .wordHighlightStrong,\n\t.monaco-editor.vs-dark .wordHighlightStrong,\n\t.monaco-editor.vs .reference-decoration,\n\t.monaco-editor.vs-dark .reference-decoration {\n\t\tborder: 2px dotted highlight !important;\n\t\tbackground: transparent !important;\n\t\tbox-sizing: border-box;\n\t}\n\t.monaco-editor.vs .rangeHighlight,\n\t.monaco-editor.vs-dark .rangeHighlight {\n\t\tbackground: transparent !important;\n\t\tborder: 1px dotted activeborder !important;\n\t\tbox-sizing: border-box;\n\t}\n\t.monaco-editor.vs .bracket-match,\n\t.monaco-editor.vs-dark .bracket-match {\n\t\tborder-color: windowtext !important;\n\t\tbackground: transparent !important;\n\t}\n\n\t/* find widget */\n\t.monaco-editor.vs .findMatch,\n\t.monaco-editor.vs-dark .findMatch,\n\t.monaco-editor.vs .currentFindMatch,\n\t.monaco-editor.vs-dark .currentFindMatch {\n\t\tborder: 2px dotted activeborder !important;\n\t\tbackground: transparent !important;\n\t\tbox-sizing: border-box;\n\t}\n\t.monaco-editor.vs .find-widget,\n\t.monaco-editor.vs-dark .find-widget {\n\t\tborder: 1px solid windowtext;\n\t}\n\n\t/* list - used by suggest widget */\n\t.monaco-editor.vs .monaco-list .monaco-list-row,\n\t.monaco-editor.vs-dark .monaco-list .monaco-list-row {\n\t\t-ms-high-contrast-adjust: none;\n\t\tcolor: windowtext !important;\n\t}\n\t.monaco-editor.vs .monaco-list .monaco-list-row.focused,\n\t.monaco-editor.vs-dark .monaco-list .monaco-list-row.focused {\n\t\tcolor: highlighttext !important;\n\t\tbackground-color: highlight !important;\n\t}\n\t.monaco-editor.vs .monaco-list .monaco-list-row:hover,\n\t.monaco-editor.vs-dark .monaco-list .monaco-list-row:hover {\n\t\tbackground: transparent !important;\n\t\tborder: 1px solid highlight;\n\t\tbox-sizing: border-box;\n\t}\n\n\t/* scrollbars */\n\t.monaco-editor.vs .monaco-scrollable-element > .scrollbar,\n\t.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar {\n\t\t-ms-high-contrast-adjust: none;\n\t\tbackground: background !important;\n\t\tborder: 1px solid windowtext;\n\t\tbox-sizing: border-box;\n\t}\n\t.monaco-editor.vs .monaco-scrollable-element > .scrollbar > .slider,\n\t.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar > .slider {\n\t\tbackground: windowtext !important;\n\t}\n\t.monaco-editor.vs .monaco-scrollable-element > .scrollbar > .slider:hover,\n\t.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar > .slider:hover {\n\t\tbackground: highlight !important;\n\t}\n\t.monaco-editor.vs .monaco-scrollable-element > .scrollbar > .slider.active,\n\t.monaco-editor.vs-dark .monaco-scrollable-element > .scrollbar > .slider.active {\n\t\tbackground: highlight !important;\n\t}\n\n\t/* overview ruler */\n\t.monaco-editor.vs .decorationsOverviewRuler,\n\t.monaco-editor.vs-dark .decorationsOverviewRuler {\n\t\topacity: 0;\n\t}\n\n\t/* minimap */\n\t.monaco-editor.vs .minimap,\n\t.monaco-editor.vs-dark .minimap {\n\t\tdisplay: none;\n\t}\n\n\t/* squiggles */\n\t.monaco-editor.vs .squiggly-d-error,\n\t.monaco-editor.vs-dark .squiggly-d-error {\n\t\tbackground: transparent !important;\n\t\tborder-bottom: 4px double #E47777;\n\t}\n\t.monaco-editor.vs .squiggly-c-warning,\n\t.monaco-editor.vs-dark .squiggly-c-warning {\n\t\tborder-bottom: 4px double #71B771;\n\t}\n\t.monaco-editor.vs .squiggly-b-info,\n\t.monaco-editor.vs-dark .squiggly-b-info {\n\t\tborder-bottom: 4px double #71B771;\n\t}\n\t.monaco-editor.vs .squiggly-a-hint,\n\t.monaco-editor.vs-dark .squiggly-a-hint {\n\t\tborder-bottom: 4px double #6c6c6c;\n\t}\n\n\t/* contextmenu */\n\t.monaco-editor.vs .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label,\n\t.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .action-label {\n\t\t-ms-high-contrast-adjust: none;\n\t\tcolor: highlighttext !important;\n\t\tbackground-color: highlight !important;\n\t}\n\t.monaco-editor.vs .monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .action-label,\n\t.monaco-editor.vs-dark .monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .action-label {\n\t\t-ms-high-contrast-adjust: none;\n\t\tbackground: transparent !important;\n\t\tborder: 1px solid highlight;\n\t\tbox-sizing: border-box;\n\t}\n\n\t/* diff editor */\n\t.monaco-diff-editor.vs .diffOverviewRuler,\n\t.monaco-diff-editor.vs-dark .diffOverviewRuler {\n\t\tdisplay: none;\n\t}\n\t.monaco-editor.vs .line-insert,\n\t.monaco-editor.vs-dark .line-insert,\n\t.monaco-editor.vs .line-delete,\n\t.monaco-editor.vs-dark .line-delete {\n\t\tbackground: transparent !important;\n\t\tborder: 1px solid highlight !important;\n\t\tbox-sizing: border-box;\n\t}\n\t.monaco-editor.vs .char-insert,\n\t.monaco-editor.vs-dark .char-insert,\n\t.monaco-editor.vs .char-delete,\n\t.monaco-editor.vs-dark .char-delete {\n\t\tbackground: transparent !important;\n\t}\n}\n\n/*.monaco-editor.vs [tabindex=\"0\"]:focus {\n\toutline: 1px solid rgba(0, 122, 204, 0.4);\n\toutline-offset: -1px;\n\topacity: 1 !important;\n}\n\n.monaco-editor.vs-dark [tabindex=\"0\"]:focus {\n\toutline: 1px solid rgba(14, 99, 156, 0.6);\n\toutline-offset: -1px;\n\topacity: 1 !important;\n}*/\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 28862:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ConnectToGitHub-module__ConnectView--P4QXs{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:48px 24px;text-align:center;color:var(--theme-color-fg-default-shy);min-height:300px}.ConnectToGitHub-module__ConnectView--P4QXs h3{margin:16px 0 8px;color:var(--theme-color-fg-default);font-size:18px;font-weight:600}.ConnectToGitHub-module__ConnectView--P4QXs p{margin:0 0 12px;font-size:13px;line-height:1.5;max-width:400px}.ConnectToGitHub-module__Icon--x9vc3{color:var(--theme-color-fg-default-shy);opacity:.7;margin-bottom:8px}.ConnectToGitHub-module__Icon--x9vc3 svg{display:block}.ConnectToGitHub-module__Actions--mDQsK{display:flex;flex-direction:column;gap:12px;margin-top:20px;width:100%;max-width:280px}.ConnectToGitHub-module__PrimaryButton--PQkuB{padding:12px 24px;background-color:var(--theme-color-primary);color:#fff;border:none;border-radius:6px;font-size:14px;font-weight:500;cursor:pointer;transition:all .2s ease;width:100%}.ConnectToGitHub-module__PrimaryButton--PQkuB:hover:not(:disabled){opacity:.9;transform:translateY(-1px)}.ConnectToGitHub-module__PrimaryButton--PQkuB:active:not(:disabled){opacity:.8;transform:translateY(0)}.ConnectToGitHub-module__PrimaryButton--PQkuB:disabled{opacity:.5;cursor:not-allowed}.ConnectToGitHub-module__SecondaryButton--oxMuD{padding:12px 24px;background-color:var(--theme-color-bg-3);color:var(--theme-color-fg-default);border:1px solid var(--theme-color-border-default);border-radius:6px;font-size:14px;font-weight:500;cursor:pointer;transition:all .2s ease}.ConnectToGitHub-module__SecondaryButton--oxMuD:hover:not(:disabled){background-color:var(--theme-color-bg-4);border-color:var(--theme-color-border-strong)}.ConnectToGitHub-module__SecondaryButton--oxMuD:disabled{opacity:.5;cursor:not-allowed}.ConnectToGitHub-module__RemoteUrl--IPHWC{display:inline-block;padding:4px 8px;margin-top:8px;background-color:var(--theme-color-bg-3);border-radius:4px;font-family:monospace;font-size:12px;word-break:break-all}.ConnectToGitHub-module__HintText--S1BB6{font-size:12px;color:var(--theme-color-fg-default-shy);opacity:.8}.ConnectToGitHub-module__ErrorMessage--BNRS8{padding:12px 16px;background-color:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);border-radius:6px;color:var(--theme-color-danger);font-size:13px;margin-top:16px;width:100%;max-width:400px;text-align:left}.ConnectToGitHub-module__ModalBackdrop--_ud95{position:fixed;inset:0;background-color:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;z-index:1000}.ConnectToGitHub-module__Modal--dZdDy{background-color:var(--theme-color-bg-2);border-radius:12px;box-shadow:0 20px 40px rgba(0,0,0,.3);width:100%;max-width:420px;max-height:90vh;display:flex;flex-direction:column;overflow:hidden}.ConnectToGitHub-module__ModalLarge--co5CR{max-width:560px}.ConnectToGitHub-module__ModalHeader--mc0GO{display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid var(--theme-color-border-default)}.ConnectToGitHub-module__ModalHeader--mc0GO h2{margin:0;font-size:16px;font-weight:600;color:var(--theme-color-fg-default)}.ConnectToGitHub-module__CloseButton--LW5Ti{background:none;border:none;font-size:24px;color:var(--theme-color-fg-default-shy);cursor:pointer;padding:0;line-height:1;transition:color .2s ease}.ConnectToGitHub-module__CloseButton--LW5Ti:hover:not(:disabled){color:var(--theme-color-fg-default)}.ConnectToGitHub-module__CloseButton--LW5Ti:disabled{opacity:.5;cursor:not-allowed}.ConnectToGitHub-module__ModalBody--RTONj{padding:20px;overflow-y:auto;flex:1}.ConnectToGitHub-module__ModalFooter--m9JLH{display:flex;justify-content:flex-end;gap:12px;padding:16px 20px;border-top:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-2)}.ConnectToGitHub-module__ModalFooter--m9JLH .ConnectToGitHub-module__PrimaryButton--PQkuB,.ConnectToGitHub-module__ModalFooter--m9JLH .ConnectToGitHub-module__SecondaryButton--oxMuD{width:auto;padding:10px 20px}.ConnectToGitHub-module__FormGroup--oiAZz{margin-bottom:20px}.ConnectToGitHub-module__FormGroup--oiAZz label{display:block;margin-bottom:6px;font-size:13px;font-weight:500;color:var(--theme-color-fg-default)}.ConnectToGitHub-module__Input--R01M2,.ConnectToGitHub-module__Select--UxLpz{width:100%;padding:10px 12px;background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:6px;color:var(--theme-color-fg-default);font-size:14px;transition:border-color .2s ease}.ConnectToGitHub-module__Input--R01M2::placeholder,.ConnectToGitHub-module__Select--UxLpz::placeholder{color:var(--theme-color-fg-default-shy)}.ConnectToGitHub-module__Input--R01M2:focus,.ConnectToGitHub-module__Select--UxLpz:focus{outline:none;border-color:var(--theme-color-primary)}.ConnectToGitHub-module__Input--R01M2:disabled,.ConnectToGitHub-module__Select--UxLpz:disabled{opacity:.6;cursor:not-allowed}.ConnectToGitHub-module__Select--UxLpz{cursor:pointer;appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23888' d='M3 4.5L6 7.5L9 4.5'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 12px center;padding-right:36px}.ConnectToGitHub-module__RadioGroup--T92z4{display:flex;gap:16px}.ConnectToGitHub-module__RadioLabel--RHGsC{display:flex;align-items:center;gap:8px;cursor:pointer;font-size:14px;color:var(--theme-color-fg-default)}.ConnectToGitHub-module__RadioLabel--RHGsC input[type=radio]{appearance:none;width:18px;height:18px;border:2px solid var(--theme-color-border-strong);border-radius:50%;cursor:pointer;position:relative}.ConnectToGitHub-module__RadioLabel--RHGsC input[type=radio]:checked{border-color:var(--theme-color-primary)}.ConnectToGitHub-module__RadioLabel--RHGsC input[type=radio]:checked::after{content:"";position:absolute;top:3px;left:3px;width:8px;height:8px;background-color:var(--theme-color-primary);border-radius:50%}.ConnectToGitHub-module__RadioLabel--RHGsC input[type=radio]:disabled{opacity:.5;cursor:not-allowed}.ConnectToGitHub-module__RadioIcon--NKs6J{font-size:14px}.ConnectToGitHub-module__SearchContainer--F6jnU{margin-bottom:16px}.ConnectToGitHub-module__SearchInput--b593v{width:100%;padding:10px 12px;background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:6px;color:var(--theme-color-fg-default);font-size:14px}.ConnectToGitHub-module__SearchInput--b593v::placeholder{color:var(--theme-color-fg-default-shy)}.ConnectToGitHub-module__SearchInput--b593v:focus{outline:none;border-color:var(--theme-color-primary)}.ConnectToGitHub-module__RepoList--UofyR{max-height:400px;overflow-y:auto;border:1px solid var(--theme-color-border-default);border-radius:8px}.ConnectToGitHub-module__RepoGroup--vhSvQ:not(:last-child){border-bottom:1px solid var(--theme-color-border-default)}.ConnectToGitHub-module__RepoGroupHeader--mNLQt{padding:10px 14px;font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.05em;color:var(--theme-color-fg-default-shy);background-color:var(--theme-color-bg-3);position:sticky;top:0}.ConnectToGitHub-module__RepoItem--VWlIH{padding:12px 14px;cursor:pointer;transition:background-color .15s ease;border-bottom:1px solid var(--theme-color-border-default)}.ConnectToGitHub-module__RepoItem--VWlIH:last-child{border-bottom:none}.ConnectToGitHub-module__RepoItem--VWlIH:hover{background-color:var(--theme-color-bg-3)}.ConnectToGitHub-module__RepoItem--VWlIH.ConnectToGitHub-module__RepoItemSelected--OFloo{background-color:rgba(var(--theme-color-primary-rgb, 59, 130, 246), 0.1);border-left:3px solid var(--theme-color-primary);padding-left:11px}.ConnectToGitHub-module__RepoInfo--o2SRX{display:flex;flex-direction:column;gap:4px}.ConnectToGitHub-module__RepoName--eOe3x{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:500;color:var(--theme-color-fg-default)}.ConnectToGitHub-module__PrivateBadge--GgCDh{padding:2px 6px;background-color:var(--theme-color-bg-4);border-radius:4px;font-size:11px;font-weight:400;color:var(--theme-color-fg-default-shy)}.ConnectToGitHub-module__RepoDescription--SGIPX{font-size:13px;color:var(--theme-color-fg-default-shy);line-height:1.4;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ConnectToGitHub-module__RepoMeta--LR7MI{font-size:12px;color:var(--theme-color-fg-default-shy);opacity:.8}.ConnectToGitHub-module__LoadingState--PeIIu{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:48px 24px;color:var(--theme-color-fg-default-shy)}.ConnectToGitHub-module__LoadingState--PeIIu p{margin-top:16px;font-size:13px}.ConnectToGitHub-module__Spinner--UHk84{width:32px;height:32px;border:3px solid var(--theme-color-bg-4);border-top-color:var(--theme-color-primary);border-radius:50%;animation:ConnectToGitHub-module__spin--2gEDC .8s linear infinite}@keyframes ConnectToGitHub-module__spin--2gEDC{to{transform:rotate(360deg)}}.ConnectToGitHub-module__EmptyState--JaFho{padding:32px 24px;text-align:center;color:var(--theme-color-fg-default-shy)}.ConnectToGitHub-module__EmptyState--JaFho p{margin:0;font-size:13px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/GitHubPanel/components/ConnectToGitHub/ConnectToGitHub.module.scss"],"names":[],"mappings":"AAMA,4CACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,iBAAA,CACA,uCAAA,CACA,gBAAA,CAEA,+CACE,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CAGF,8CACE,eAAA,CACA,cAAA,CACA,eAAA,CACA,eAAA,CAIJ,qCACE,uCAAA,CACA,UAAA,CACA,iBAAA,CAEA,yCACE,aAAA,CAIJ,wCACE,YAAA,CACA,qBAAA,CACA,QAAA,CACA,eAAA,CACA,UAAA,CACA,eAAA,CAGF,8CACE,iBAAA,CACA,2CAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,uBAAA,CACA,UAAA,CAEA,mEACE,UAAA,CACA,0BAAA,CAGF,oEACE,UAAA,CACA,uBAAA,CAGF,uDACE,UAAA,CACA,kBAAA,CAIJ,gDACE,iBAAA,CACA,wCAAA,CACA,mCAAA,CACA,kDAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,uBAAA,CAEA,qEACE,wCAAA,CACA,6CAAA,CAGF,yDACE,UAAA,CACA,kBAAA,CAIJ,0CACE,oBAAA,CACA,eAAA,CACA,cAAA,CACA,wCAAA,CACA,iBAAA,CACA,qBAAA,CACA,cAAA,CACA,oBAAA,CAGF,yCACE,cAAA,CACA,uCAAA,CACA,UAAA,CAGF,6CACE,iBAAA,CACA,mCAAA,CACA,mCAAA,CACA,iBAAA,CACA,+BAAA,CACA,cAAA,CACA,eAAA,CACA,UAAA,CACA,eAAA,CACA,eAAA,CAIF,8CACE,cAAA,CACA,OAAA,CACA,+BAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,YAAA,CAGF,sCACE,wCAAA,CACA,kBAAA,CACA,qCAAA,CACA,UAAA,CACA,eAAA,CACA,eAAA,CACA,YAAA,CACA,qBAAA,CACA,eAAA,CAGF,2CACE,eAAA,CAGF,4CACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,iBAAA,CACA,yDAAA,CAEA,+CACE,QAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAIJ,4CACE,eAAA,CACA,WAAA,CACA,cAAA,CACA,uCAAA,CACA,cAAA,CACA,SAAA,CACA,aAAA,CACA,yBAAA,CAEA,iEACE,mCAAA,CAGF,qDACE,UAAA,CACA,kBAAA,CAIJ,0CACE,YAAA,CACA,eAAA,CACA,MAAA,CAGF,4CACE,YAAA,CACA,wBAAA,CACA,QAAA,CACA,iBAAA,CACA,sDAAA,CACA,wCAAA,CAEA,sLAEE,UAAA,CACA,iBAAA,CAKJ,0CACE,kBAAA,CAEA,gDACE,aAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAIJ,6EAEE,UAAA,CACA,iBAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,gCAAA,CAEA,uGACE,uCAAA,CAGF,yFACE,YAAA,CACA,uCAAA,CAGF,+FACE,UAAA,CACA,kBAAA,CAIJ,uCACE,cAAA,CACA,eAAA,CACA,4LAAA,CACA,2BAAA,CACA,qCAAA,CACA,kBAAA,CAGF,2CACE,YAAA,CACA,QAAA,CAGF,2CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,cAAA,CACA,cAAA,CACA,mCAAA,CAEA,6DACE,eAAA,CACA,UAAA,CACA,WAAA,CACA,iDAAA,CACA,iBAAA,CACA,cAAA,CACA,iBAAA,CAEA,qEACE,uCAAA,CAEA,4EACE,UAAA,CACA,iBAAA,CACA,OAAA,CACA,QAAA,CACA,SAAA,CACA,UAAA,CACA,2CAAA,CACA,iBAAA,CAIJ,sEACE,UAAA,CACA,kBAAA,CAKN,0CACE,cAAA,CAIF,gDACE,kBAAA,CAGF,4CACE,UAAA,CACA,iBAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CAEA,yDACE,uCAAA,CAGF,kDACE,YAAA,CACA,uCAAA,CAIJ,yCACE,gBAAA,CACA,eAAA,CACA,kDAAA,CACA,iBAAA,CAIA,2DACE,yDAAA,CAIJ,gDACE,iBAAA,CACA,cAAA,CACA,eAAA,CACA,wBAAA,CACA,oBAAA,CACA,uCAAA,CACA,wCAAA,CACA,eAAA,CACA,KAAA,CAGF,yCACE,iBAAA,CACA,cAAA,CACA,qCAAA,CACA,yDAAA,CAEA,oDACE,kBAAA,CAGF,+CACE,wCAAA,CAGF,yFACE,wEAAA,CACA,gDAAA,CACA,iBAAA,CAIJ,yCACE,YAAA,CACA,qBAAA,CACA,OAAA,CAGF,yCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,6CACE,eAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,uCAAA,CAGF,gDACE,cAAA,CACA,uCAAA,CACA,eAAA,CACA,eAAA,CACA,sBAAA,CACA,kBAAA,CAGF,yCACE,cAAA,CACA,uCAAA,CACA,UAAA,CAIF,6CACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,uCAAA,CAEA,+CACE,eAAA,CACA,cAAA,CAIJ,wCACE,UAAA,CACA,WAAA,CACA,wCAAA,CACA,2CAAA,CACA,iBAAA,CACA,iEAAA,CAGF,+CACE,GACE,wBAAA,CAAA,CAKJ,2CACE,iBAAA,CACA,iBAAA,CACA,uCAAA,CAEA,6CACE,QAAA,CACA,cAAA","sourcesContent":["/**\n * ConnectToGitHub styles\n * Uses design tokens for theming\n */\n\n// Main view\n.ConnectView {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  padding: 48px 24px;\n  text-align: center;\n  color: var(--theme-color-fg-default-shy);\n  min-height: 300px;\n\n  h3 {\n    margin: 16px 0 8px;\n    color: var(--theme-color-fg-default);\n    font-size: 18px;\n    font-weight: 600;\n  }\n\n  p {\n    margin: 0 0 12px;\n    font-size: 13px;\n    line-height: 1.5;\n    max-width: 400px;\n  }\n}\n\n.Icon {\n  color: var(--theme-color-fg-default-shy);\n  opacity: 0.7;\n  margin-bottom: 8px;\n\n  svg {\n    display: block;\n  }\n}\n\n.Actions {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n  margin-top: 20px;\n  width: 100%;\n  max-width: 280px;\n}\n\n.PrimaryButton {\n  padding: 12px 24px;\n  background-color: var(--theme-color-primary);\n  color: white;\n  border: none;\n  border-radius: 6px;\n  font-size: 14px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: all 0.2s ease;\n  width: 100%;\n\n  &:hover:not(:disabled) {\n    opacity: 0.9;\n    transform: translateY(-1px);\n  }\n\n  &:active:not(:disabled) {\n    opacity: 0.8;\n    transform: translateY(0);\n  }\n\n  &:disabled {\n    opacity: 0.5;\n    cursor: not-allowed;\n  }\n}\n\n.SecondaryButton {\n  padding: 12px 24px;\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-default);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 6px;\n  font-size: 14px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: all 0.2s ease;\n\n  &:hover:not(:disabled) {\n    background-color: var(--theme-color-bg-4);\n    border-color: var(--theme-color-border-strong);\n  }\n\n  &:disabled {\n    opacity: 0.5;\n    cursor: not-allowed;\n  }\n}\n\n.RemoteUrl {\n  display: inline-block;\n  padding: 4px 8px;\n  margin-top: 8px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 4px;\n  font-family: monospace;\n  font-size: 12px;\n  word-break: break-all;\n}\n\n.HintText {\n  font-size: 12px;\n  color: var(--theme-color-fg-default-shy);\n  opacity: 0.8;\n}\n\n.ErrorMessage {\n  padding: 12px 16px;\n  background-color: rgba(239, 68, 68, 0.1);\n  border: 1px solid rgba(239, 68, 68, 0.3);\n  border-radius: 6px;\n  color: var(--theme-color-danger);\n  font-size: 13px;\n  margin-top: 16px;\n  width: 100%;\n  max-width: 400px;\n  text-align: left;\n}\n\n// Modal styles\n.ModalBackdrop {\n  position: fixed;\n  inset: 0;\n  background-color: rgba(0, 0, 0, 0.6);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 1000;\n}\n\n.Modal {\n  background-color: var(--theme-color-bg-2);\n  border-radius: 12px;\n  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);\n  width: 100%;\n  max-width: 420px;\n  max-height: 90vh;\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n\n.ModalLarge {\n  max-width: 560px;\n}\n\n.ModalHeader {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 16px 20px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n\n  h2 {\n    margin: 0;\n    font-size: 16px;\n    font-weight: 600;\n    color: var(--theme-color-fg-default);\n  }\n}\n\n.CloseButton {\n  background: none;\n  border: none;\n  font-size: 24px;\n  color: var(--theme-color-fg-default-shy);\n  cursor: pointer;\n  padding: 0;\n  line-height: 1;\n  transition: color 0.2s ease;\n\n  &:hover:not(:disabled) {\n    color: var(--theme-color-fg-default);\n  }\n\n  &:disabled {\n    opacity: 0.5;\n    cursor: not-allowed;\n  }\n}\n\n.ModalBody {\n  padding: 20px;\n  overflow-y: auto;\n  flex: 1;\n}\n\n.ModalFooter {\n  display: flex;\n  justify-content: flex-end;\n  gap: 12px;\n  padding: 16px 20px;\n  border-top: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-2);\n\n  .PrimaryButton,\n  .SecondaryButton {\n    width: auto;\n    padding: 10px 20px;\n  }\n}\n\n// Form styles\n.FormGroup {\n  margin-bottom: 20px;\n\n  label {\n    display: block;\n    margin-bottom: 6px;\n    font-size: 13px;\n    font-weight: 500;\n    color: var(--theme-color-fg-default);\n  }\n}\n\n.Input,\n.Select {\n  width: 100%;\n  padding: 10px 12px;\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 6px;\n  color: var(--theme-color-fg-default);\n  font-size: 14px;\n  transition: border-color 0.2s ease;\n\n  &::placeholder {\n    color: var(--theme-color-fg-default-shy);\n  }\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n\n  &:disabled {\n    opacity: 0.6;\n    cursor: not-allowed;\n  }\n}\n\n.Select {\n  cursor: pointer;\n  appearance: none;\n  background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23888' d='M3 4.5L6 7.5L9 4.5'/%3E%3C/svg%3E\");\n  background-repeat: no-repeat;\n  background-position: right 12px center;\n  padding-right: 36px;\n}\n\n.RadioGroup {\n  display: flex;\n  gap: 16px;\n}\n\n.RadioLabel {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  cursor: pointer;\n  font-size: 14px;\n  color: var(--theme-color-fg-default);\n\n  input[type='radio'] {\n    appearance: none;\n    width: 18px;\n    height: 18px;\n    border: 2px solid var(--theme-color-border-strong);\n    border-radius: 50%;\n    cursor: pointer;\n    position: relative;\n\n    &:checked {\n      border-color: var(--theme-color-primary);\n\n      &::after {\n        content: '';\n        position: absolute;\n        top: 3px;\n        left: 3px;\n        width: 8px;\n        height: 8px;\n        background-color: var(--theme-color-primary);\n        border-radius: 50%;\n      }\n    }\n\n    &:disabled {\n      opacity: 0.5;\n      cursor: not-allowed;\n    }\n  }\n}\n\n.RadioIcon {\n  font-size: 14px;\n}\n\n// Repository list styles\n.SearchContainer {\n  margin-bottom: 16px;\n}\n\n.SearchInput {\n  width: 100%;\n  padding: 10px 12px;\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 6px;\n  color: var(--theme-color-fg-default);\n  font-size: 14px;\n\n  &::placeholder {\n    color: var(--theme-color-fg-default-shy);\n  }\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.RepoList {\n  max-height: 400px;\n  overflow-y: auto;\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 8px;\n}\n\n.RepoGroup {\n  &:not(:last-child) {\n    border-bottom: 1px solid var(--theme-color-border-default);\n  }\n}\n\n.RepoGroupHeader {\n  padding: 10px 14px;\n  font-size: 12px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.05em;\n  color: var(--theme-color-fg-default-shy);\n  background-color: var(--theme-color-bg-3);\n  position: sticky;\n  top: 0;\n}\n\n.RepoItem {\n  padding: 12px 14px;\n  cursor: pointer;\n  transition: background-color 0.15s ease;\n  border-bottom: 1px solid var(--theme-color-border-default);\n\n  &:last-child {\n    border-bottom: none;\n  }\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.RepoItemSelected {\n    background-color: rgba(var(--theme-color-primary-rgb, 59, 130, 246), 0.1);\n    border-left: 3px solid var(--theme-color-primary);\n    padding-left: 11px;\n  }\n}\n\n.RepoInfo {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n}\n\n.RepoName {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  font-size: 14px;\n  font-weight: 500;\n  color: var(--theme-color-fg-default);\n}\n\n.PrivateBadge {\n  padding: 2px 6px;\n  background-color: var(--theme-color-bg-4);\n  border-radius: 4px;\n  font-size: 11px;\n  font-weight: 400;\n  color: var(--theme-color-fg-default-shy);\n}\n\n.RepoDescription {\n  font-size: 13px;\n  color: var(--theme-color-fg-default-shy);\n  line-height: 1.4;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n.RepoMeta {\n  font-size: 12px;\n  color: var(--theme-color-fg-default-shy);\n  opacity: 0.8;\n}\n\n// Loading state\n.LoadingState {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  padding: 48px 24px;\n  color: var(--theme-color-fg-default-shy);\n\n  p {\n    margin-top: 16px;\n    font-size: 13px;\n  }\n}\n\n.Spinner {\n  width: 32px;\n  height: 32px;\n  border: 3px solid var(--theme-color-bg-4);\n  border-top-color: var(--theme-color-primary);\n  border-radius: 50%;\n  animation: spin 0.8s linear infinite;\n}\n\n@keyframes spin {\n  to {\n    transform: rotate(360deg);\n  }\n}\n\n// Empty state\n.EmptyState {\n  padding: 32px 24px;\n  text-align: center;\n  color: var(--theme-color-fg-default-shy);\n\n  p {\n    margin: 0;\n    font-size: 13px;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"ConnectView": `ConnectToGitHub-module__ConnectView--P4QXs`,
	"Icon": `ConnectToGitHub-module__Icon--x9vc3`,
	"Actions": `ConnectToGitHub-module__Actions--mDQsK`,
	"PrimaryButton": `ConnectToGitHub-module__PrimaryButton--PQkuB`,
	"SecondaryButton": `ConnectToGitHub-module__SecondaryButton--oxMuD`,
	"RemoteUrl": `ConnectToGitHub-module__RemoteUrl--IPHWC`,
	"HintText": `ConnectToGitHub-module__HintText--S1BB6`,
	"ErrorMessage": `ConnectToGitHub-module__ErrorMessage--BNRS8`,
	"ModalBackdrop": `ConnectToGitHub-module__ModalBackdrop--_ud95`,
	"Modal": `ConnectToGitHub-module__Modal--dZdDy`,
	"ModalLarge": `ConnectToGitHub-module__ModalLarge--co5CR`,
	"ModalHeader": `ConnectToGitHub-module__ModalHeader--mc0GO`,
	"CloseButton": `ConnectToGitHub-module__CloseButton--LW5Ti`,
	"ModalBody": `ConnectToGitHub-module__ModalBody--RTONj`,
	"ModalFooter": `ConnectToGitHub-module__ModalFooter--m9JLH`,
	"FormGroup": `ConnectToGitHub-module__FormGroup--oiAZz`,
	"Input": `ConnectToGitHub-module__Input--R01M2`,
	"Select": `ConnectToGitHub-module__Select--UxLpz`,
	"RadioGroup": `ConnectToGitHub-module__RadioGroup--T92z4`,
	"RadioLabel": `ConnectToGitHub-module__RadioLabel--RHGsC`,
	"RadioIcon": `ConnectToGitHub-module__RadioIcon--NKs6J`,
	"SearchContainer": `ConnectToGitHub-module__SearchContainer--F6jnU`,
	"SearchInput": `ConnectToGitHub-module__SearchInput--b593v`,
	"RepoList": `ConnectToGitHub-module__RepoList--UofyR`,
	"RepoGroup": `ConnectToGitHub-module__RepoGroup--vhSvQ`,
	"RepoGroupHeader": `ConnectToGitHub-module__RepoGroupHeader--mNLQt`,
	"RepoItem": `ConnectToGitHub-module__RepoItem--VWlIH`,
	"RepoItemSelected": `ConnectToGitHub-module__RepoItemSelected--OFloo`,
	"RepoInfo": `ConnectToGitHub-module__RepoInfo--o2SRX`,
	"RepoName": `ConnectToGitHub-module__RepoName--eOe3x`,
	"PrivateBadge": `ConnectToGitHub-module__PrivateBadge--GgCDh`,
	"RepoDescription": `ConnectToGitHub-module__RepoDescription--SGIPX`,
	"RepoMeta": `ConnectToGitHub-module__RepoMeta--LR7MI`,
	"LoadingState": `ConnectToGitHub-module__LoadingState--PeIIu`,
	"Spinner": `ConnectToGitHub-module__Spinner--UHk84`,
	"spin": `ConnectToGitHub-module__spin--2gEDC`,
	"EmptyState": `ConnectToGitHub-module__EmptyState--JaFho`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 28873:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   showContextMenuInPopup: () => (/* binding */ showContextMenuInPopup)
/* harmony export */ });
/* harmony import */ var _electron_remote__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52391);
/* harmony import */ var _electron_remote__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_electron_remote__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react_dom_client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(25873);
/* harmony import */ var _noodl_core_ui_components_layout_BaseDialog__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(65762);
/* harmony import */ var _noodl_core_ui_components_popups_MenuDialog__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(23442);
/* harmony import */ var _popuplayer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(45653);
/* harmony import */ var _popuplayer__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_popuplayer__WEBPACK_IMPORTED_MODULE_5__);






function showContextMenuInPopup({ title, items, width, renderDirection = _noodl_core_ui_components_layout_BaseDialog__WEBPACK_IMPORTED_MODULE_3__/* .DialogRenderDirection */ .K1.Vertical }) {
    const container = document.createElement('div');
    const screenPoint = _electron_remote__WEBPACK_IMPORTED_MODULE_0__.screen.getCursorScreenPoint();
    const [winX, winY] = (0,_electron_remote__WEBPACK_IMPORTED_MODULE_0__.getCurrentWindow)().getPosition();
    const root = (0,react_dom_client__WEBPACK_IMPORTED_MODULE_2__.createRoot)(container);
    const popout = _popuplayer__WEBPACK_IMPORTED_MODULE_5___default().instance.showPopout({
        content: { el: $(container) },
        arrowColor: 'transparent',
        attachToPoint: {
            x: screenPoint.x - winX,
            y: screenPoint.y - winY
        },
        position: 'top',
        onClose: () => {
            root.unmount();
        }
    });
    root.render(react__WEBPACK_IMPORTED_MODULE_1___default().createElement(_noodl_core_ui_components_popups_MenuDialog__WEBPACK_IMPORTED_MODULE_4__.MenuDialog, { title: title, width: width || _noodl_core_ui_components_popups_MenuDialog__WEBPACK_IMPORTED_MODULE_4__.MenuDialogWidth.Large, isVisible: true, triggerRef: { current: container }, renderDirection: renderDirection, onClose: () => {
            _popuplayer__WEBPACK_IMPORTED_MODULE_5___default().instance.hidePopout(popout);
        }, items: items }));
}


/***/ }),

/***/ 28885:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.toFile = toFile;
const uploads_1 = __webpack_require__(76409);
const uploads_2 = __webpack_require__(76409);
/**
 * This check adds the arrayBuffer() method type because it is available and used at runtime
 */
const isBlobLike = (value) => value != null &&
    typeof value === 'object' &&
    typeof value.size === 'number' &&
    typeof value.type === 'string' &&
    typeof value.text === 'function' &&
    typeof value.slice === 'function' &&
    typeof value.arrayBuffer === 'function';
/**
 * This check adds the arrayBuffer() method type because it is available and used at runtime
 */
const isFileLike = (value) => value != null &&
    typeof value === 'object' &&
    typeof value.name === 'string' &&
    typeof value.lastModified === 'number' &&
    isBlobLike(value);
const isResponseLike = (value) => value != null &&
    typeof value === 'object' &&
    typeof value.url === 'string' &&
    typeof value.blob === 'function';
/**
 * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
 * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts
 * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
 * @param {Object=} options additional properties
 * @param {string=} options.type the MIME type of the content
 * @param {number=} options.lastModified the last modified timestamp
 * @returns a {@link File} with the given properties
 */
async function toFile(value, name, options) {
    (0, uploads_2.checkFileSupport)();
    // If it's a promise, resolve it.
    value = await value;
    name || (name = (0, uploads_1.getName)(value));
    // If we've been given a `File` we don't need to do anything if the name / options
    // have not been customised.
    if (isFileLike(value)) {
        if (value instanceof File && name == null && options == null) {
            return value;
        }
        return (0, uploads_1.makeFile)([await value.arrayBuffer()], name ?? value.name, {
            type: value.type,
            lastModified: value.lastModified,
            ...options,
        });
    }
    if (isResponseLike(value)) {
        const blob = await value.blob();
        name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
        return (0, uploads_1.makeFile)(await getBytes(blob), name, options);
    }
    const parts = await getBytes(value);
    if (!options?.type) {
        const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type);
        if (typeof type === 'string') {
            options = { ...options, type };
        }
    }
    return (0, uploads_1.makeFile)(parts, name, options);
}
async function getBytes(value) {
    let parts = [];
    if (typeof value === 'string' ||
        ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
        value instanceof ArrayBuffer) {
        parts.push(value);
    }
    else if (isBlobLike(value)) {
        parts.push(value instanceof Blob ? value : await value.arrayBuffer());
    }
    else if ((0, uploads_1.isAsyncIterable)(value) // includes Readable, ReadableStream, etc.
    ) {
        for await (const chunk of value) {
            parts.push(...(await getBytes(chunk))); // TODO, consider validating?
        }
    }
    else {
        const constructor = value?.constructor?.name;
        throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`);
    }
    return parts;
}
function propsForError(value) {
    if (typeof value !== 'object' || value === null)
        return '';
    const props = Object.getOwnPropertyNames(value);
    return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`;
}
//# sourceMappingURL=to-file.js.map

/***/ }),

/***/ 29668:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.TagButton-module__Root--XTnej{color:var(--theme-color-fg-default-shy);background-color:var(--theme-color-bg-1);padding:3px 18px;font-size:12px;font-weight:600;line-height:150%;border:0;cursor:pointer}.TagButton-module__Root--XTnej:hover{color:var(--theme-color-fg-highlight)}.TagButton-module__Root--XTnej.TagButton-module__is-active--zqDri{color:var(--theme-color-on-secondary);background-color:var(--theme-color-secondary)}.TagButton-module__Root--XTnej.TagButton-module__is-active--zqDri:hover{background-color:var(--theme-color-secondary-highlight)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/TagButton/TagButton.module.scss"],"names":[],"mappings":"AAAA,+BACE,uCAAA,CACA,wCAAA,CACA,gBAAA,CACA,cAAA,CACA,eAAA,CACA,gBAAA,CACA,QAAA,CACA,cAAA,CAEA,qCACE,qCAAA,CAGF,kEACE,qCAAA,CACA,6CAAA,CAEA,wEACE,uDAAA","sourcesContent":[".Root {\r\n  color: var(--theme-color-fg-default-shy);\r\n  background-color: var(--theme-color-bg-1);\r\n  padding: 3px 18px;\r\n  font-size: 12px;\r\n  font-weight: 600;\r\n  line-height: 150%;\r\n  border: 0;\r\n  cursor: pointer;\r\n\r\n  &:hover {\r\n    color: var(--theme-color-fg-highlight);\r\n  }\r\n\r\n  &.is-active {\r\n    color: var(--theme-color-on-secondary);\r\n    background-color: var(--theme-color-secondary);\r\n\r\n    &:hover {\r\n      background-color: var(--theme-color-secondary-highlight);\r\n    }\r\n  }\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `TagButton-module__Root--XTnej`,
	"is-active": `TagButton-module__is-active--zqDri`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 29820:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.castToError = void 0;
exports.isAbortError = isAbortError;
function isAbortError(err) {
    return (typeof err === 'object' &&
        err !== null &&
        // Spec-compliant fetch implementations
        (('name' in err && err.name === 'AbortError') ||
            // Expo fetch
            ('message' in err && String(err.message).includes('FetchRequestCanceledException'))));
}
const castToError = (err) => {
    if (err instanceof Error)
        return err;
    if (typeof err === 'object' && err !== null) {
        try {
            if (Object.prototype.toString.call(err) === '[object Error]') {
                // @ts-ignore - not all envs have native support for cause yet
                const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
                if (err.stack)
                    error.stack = err.stack;
                // @ts-ignore - not all envs have native support for cause yet
                if (err.cause && !error.cause)
                    error.cause = err.cause;
                if (err.name)
                    error.name = err.name;
                return error;
            }
        }
        catch { }
        try {
            return new Error(JSON.stringify(err));
        }
        catch { }
    }
    return new Error(err);
};
exports.castToError = castToError;
//# sourceMappingURL=errors.js.map

/***/ }),

/***/ 29902:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   o: () => (/* binding */ clone)
/* harmony export */ });
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85869);
/* harmony import */ var _progress__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51436);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(25758);
/* harmony import */ var _electron_remote__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(52391);
/* harmony import */ var _electron_remote__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_electron_remote__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(16928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_4__);





/**
 * Clones a repository from a given url into to the specified path.
 *
 * @param url     - The remote repository URL to clone from
 *
 * @param path    - The destination path for the cloned repository. If the
 *                  path does not exist it will be created. Cloning into an
 *                  existing directory is only allowed if the directory is
 *                  empty.
 *
 * @param options  - Options specific to the clone operation, see the
 *                   documentation for CloneOptions for more details.
 *
 * @param progressCallback - An optional function which will be invoked
 *                           with information about the current progress
 *                           of the clone operation. When provided this enables
 *                           the '--progress' command line flag for
 *                           'git clone'.
 *
 */
async function clone(url, path, options, progressCallback) {
    var _a;
    const networkArguments = await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .gitNetworkArguments */ .X)(null);
    const defaultBranch = (_a = options.defaultBranch) !== null && _a !== void 0 ? _a : _constants__WEBPACK_IMPORTED_MODULE_2__/* .DEFAULT_BRANCH */ .nU;
    const args = [...networkArguments, '-c', `init.defaultBranch=${defaultBranch}`, 'clone', '--recursive'];
    let opts = {};
    if (progressCallback) {
        args.push('--progress');
        const title = `Cloning into ${path}`;
        const kind = 'clone';
        opts = await (0,_progress__WEBPACK_IMPORTED_MODULE_1__/* .executionOptionsWithProgress */ .s_)({ ...opts }, new _progress__WEBPACK_IMPORTED_MODULE_1__/* .CloneProgressParser */ .gG(), (progress) => {
            const description = progress.kind === 'progress' ? progress.details.text : progress.text;
            const value = progress.percent;
            progressCallback({ kind, title, description, value });
        });
        // Initial progress
        progressCallback({ kind, title, value: 0 });
    }
    if (options.branch) {
        args.push('-b', options.branch);
    }
    else if (defaultBranch) {
        args.push('-b', defaultBranch);
    }
    if (options.singleBranch) {
        args.push('--single-branch');
    }
    args.push('--', url, path);
    const cwdPath = (0,path__WEBPACK_IMPORTED_MODULE_4__.join)(_electron_remote__WEBPACK_IMPORTED_MODULE_3__.app.getAppPath(), '..');
    return await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)(args, cwdPath, 'clone', opts);
}


/***/ }),

/***/ 29940:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDotsThree = function SvgDotsThree(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.1368 6.80722C13.0351 6.80722 13.7634 6.07898 13.7634 5.18066C13.7634 4.28233 13.0351 3.55409 12.1368 3.55409C11.2385 3.55409 10.5103 4.28233 10.5103 5.18066C10.5103 6.07898 11.2385 6.80722 12.1368 6.80722Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.1368 13.6266C13.0351 13.6266 13.7634 12.8983 13.7634 12C13.7634 11.1017 13.0351 10.3734 12.1368 10.3734C11.2385 10.3734 10.5103 11.1017 10.5103 12C10.5103 12.8983 11.2385 13.6266 12.1368 13.6266Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.1368 20.4459C13.0351 20.4459 13.7634 19.7177 13.7634 18.8193C13.7634 17.921 13.0351 17.1928 12.1368 17.1928C11.2385 17.1928 10.5103 17.921 10.5103 18.8193C10.5103 19.7177 11.2385 20.4459 12.1368 20.4459Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDotsThree);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "8c772f9f6ecc961319b9a40bc7d9e2b3.svg");

/***/ }),

/***/ 30149:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PanelHeader-module__Root--OwJbf{flex:0 0 36px;padding:0 16px;min-height:36px;display:flex;justify-content:space-between;align-items:center}.PanelHeader-module__Root--OwJbf:not(.PanelHeader-module___hasNoHeaderDivider--J7dtA){border-bottom:1px solid var(--theme-color-bg-1)}.PanelHeader-module__Children--XuzTg{display:flex}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/sidebar/PanelHeader/PanelHeader.module.scss"],"names":[],"mappings":"AAAA,iCACE,aAAA,CACA,cAAA,CACA,eAAA,CACA,YAAA,CACA,6BAAA,CACA,kBAAA,CAEA,sFACE,+CAAA,CAIJ,qCACE,YAAA","sourcesContent":[".Root {\n  flex: 0 0 36px;\n  padding: 0 16px;\n  min-height: 36px;\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n\n  &:not(._hasNoHeaderDivider) {\n    border-bottom: 1px solid var(--theme-color-bg-1);\n  }\n}\n\n.Children {\n  display: flex;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PanelHeader-module__Root--OwJbf`,
	"_hasNoHeaderDivider": `PanelHeader-module___hasNoHeaderDivider--J7dtA`,
	"Children": `PanelHeader-module__Children--XuzTg`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 30187:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   M: () => (/* binding */ FeedbackType)
/* harmony export */ });
var FeedbackType;
(function (FeedbackType) {
    FeedbackType["Success"] = "success";
    FeedbackType["Notice"] = "notice";
    FeedbackType["Danger"] = "danger";
})(FeedbackType || (FeedbackType = {}));


/***/ }),

/***/ 30278:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5, _path6, _path7, _path8, _path9, _path0;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRoundedCornerRightDown = function SvgRoundedCornerRightDown(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.93994 25.6045C3.93994 25.1903 4.27573 24.8545 4.68994 24.8545C5.10415 24.8545 5.43994 25.1903 5.43994 25.6045C5.43994 26.0187 5.10415 26.3545 4.68994 26.3545C4.27573 26.3545 3.93994 26.0187 3.93994 25.6045Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.93994 11.8628C3.93994 11.4486 4.27573 11.1128 4.68994 11.1128C5.10415 11.1128 5.43994 11.4486 5.43994 11.8628C5.43994 12.277 5.10415 12.6128 4.68994 12.6128C4.27573 12.6128 3.93994 12.277 3.93994 11.8628Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M24.8335 11.8628C24.8335 11.4486 25.1693 11.1128 25.5835 11.1128C25.9977 11.1128 26.3335 11.4486 26.3335 11.8628C26.3335 12.277 25.9977 12.6128 25.5835 12.6128C25.1693 12.6128 24.8335 12.277 24.8335 11.8628Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.93994 18.7339C3.93994 18.3197 4.27573 17.9839 4.68994 17.9839C5.10415 17.9839 5.43994 18.3197 5.43994 18.7339C5.43994 19.1481 5.10415 19.4839 4.68994 19.4839C4.27573 19.4839 3.93994 19.1481 3.93994 18.7339Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.93994 4.9917C3.93994 4.57749 4.27573 4.2417 4.68994 4.2417C5.10415 4.2417 5.43994 4.57749 5.43994 4.9917C5.43994 5.40591 5.10415 5.7417 4.68994 5.7417C4.27573 5.7417 3.93994 5.40591 3.93994 4.9917Z",
    fill: "#F5F5F5"
  })), _path6 || (_path6 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.6821 4.9917C17.6821 4.57749 18.0179 4.2417 18.4321 4.2417C18.8463 4.2417 19.1821 4.57749 19.1821 4.9917C19.1821 5.40591 18.8463 5.7417 18.4321 5.7417C18.0179 5.7417 17.6821 5.40591 17.6821 4.9917Z",
    fill: "#F5F5F5"
  })), _path7 || (_path7 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.811 4.9917C10.811 4.57749 11.1468 4.2417 11.561 4.2417C11.9752 4.2417 12.311 4.57749 12.311 4.9917C12.311 5.40591 11.9752 5.7417 11.561 5.7417C11.1468 5.7417 10.811 5.40591 10.811 4.9917Z",
    fill: "#F5F5F5"
  })), _path8 || (_path8 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.811 25.6045C10.811 25.1903 11.1468 24.8545 11.561 24.8545C11.9752 24.8545 12.311 25.1903 12.311 25.6045C12.311 26.0187 11.9752 26.3545 11.561 26.3545C11.1468 26.3545 10.811 26.0187 10.811 25.6045Z",
    fill: "#F5F5F5"
  })), _path9 || (_path9 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M24.5532 4.9917C24.5532 4.57749 24.889 4.2417 25.3032 4.2417C25.7174 4.2417 26.0532 4.57749 26.0532 4.9917C26.0532 5.40591 25.7174 5.7417 25.3032 5.7417C24.889 5.7417 24.5532 5.40591 24.5532 4.9917Z",
    fill: "#F5F5F5"
  })), _path0 || (_path0 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M24.5532 18.6043L24.5532 17.5883C24.5532 17.1741 24.889 16.8383 25.3032 16.8383C25.7174 16.8383 26.0532 17.1741 26.0532 17.5883L26.0532 18.6043C26.0532 22.8845 22.5834 26.3543 18.3032 26.3543L17.2872 26.3543C16.873 26.3543 16.5372 26.0185 16.5372 25.6043C16.5372 25.1901 16.873 24.8543 17.2872 24.8543L18.3032 24.8543C21.755 24.8543 24.5532 22.0561 24.5532 18.6043Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRoundedCornerRightDown);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "b5871a8f0f5fe2f4490eed803fd39878.svg");

/***/ }),

/***/ 30356:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   G: () => (/* binding */ PropertyPanelLengthUnitInput)
/* harmony export */ });
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12678);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _noodl_core_ui_components_property_panel_PropertyPanelBaseInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(98690);
/* harmony import */ var _noodl_core_ui_components_property_panel_PropertyPanelSelectInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(66095);
/* harmony import */ var _noodl_core_ui_utils_stripCssUnit__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(53106);
/* harmony import */ var _utils_extractLetters__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(38483);
/* harmony import */ var _utils_extractNumber__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(15601);
/* harmony import */ var _utils_normalizeAlphanumericString__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(67140);
/* harmony import */ var _PropertyPanelLengthUnitInput_module_scss__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(84071);









function PropertyPanelLengthUnitInput({ value, isChanged, isConnected, hasSmallText, onChange, onError }) {
    const [isFauxFocused, setIsFauxFocused] = (0,react__WEBPACK_IMPORTED_MODULE_1__.useState)(false);
    const cleanedValue = (0,_utils_normalizeAlphanumericString__WEBPACK_IMPORTED_MODULE_7__/* .normalizeAlphanumericString */ .i)(value);
    const numberValue = (0,_utils_extractNumber__WEBPACK_IMPORTED_MODULE_6__/* .extractNumber */ .T)(cleanedValue) || '';
    const unitValue = (0,_utils_extractLetters__WEBPACK_IMPORTED_MODULE_5__/* .extractLetters */ .V)(cleanedValue).replace(' ', '');
    const [displayedInputValue, setDisplayedInputValue] = (0,react__WEBPACK_IMPORTED_MODULE_1__.useState)(numberValue);
    (0,react__WEBPACK_IMPORTED_MODULE_1__.useEffect)(() => {
        handleInputUpdate(value);
    }, [value]);
    // FIXME: this is very temporary and should be fetched from the panel config
    const unitSelectProps = {
        options: [
            { label: 'px', value: 'px' },
            { label: 'em', value: 'em' },
            { label: 'vh', value: 'vh' },
            { label: '%', value: '%' }
        ]
    };
    function getUnit() {
        const unitOption = unitSelectProps.options.find((option) => option.value === unitValue);
        if (unitOption)
            return unitOption.value;
        return 'px'; // px as default for some reason
    }
    function handleInputUpdate(inputValue) {
        // TODO: increase/decrease with arrows
        // TODO: handle drag up/down to increase/decrease
        // TODO: handle Arithmetic Error nicer!
        var _a;
        if (inputValue === '') {
            onChange && onChange(inputValue + unitValue);
            return;
        }
        let strippedValue = (0,_noodl_core_ui_utils_stripCssUnit__WEBPACK_IMPORTED_MODULE_4__/* .stripCssUnit */ .I)(inputValue.toString());
        const unit = inputValue.toString().slice(strippedValue.length); // lol
        const newUnitValue = Boolean(unit) ? (_a = unitSelectProps.options.find((option) => option.label === unit)) === null || _a === void 0 ? void 0 : _a.value : null;
        if (isArithmeticExpression(strippedValue)) {
            try {
                strippedValue = eval(strippedValue);
            }
            catch (err) {
                console.log(err);
                onError && onError(err);
            }
        }
        const newNumber = roundCssLengthNumber(parseFloat(strippedValue));
        if (newNumber === 'Error') {
            const error = new Error('Arithmetic Error: Infinite or unsafe number.');
            onError && onError(error);
            console.log(error);
            setDisplayedInputValue(displayedInputValue);
        }
        else if (!isNaN(newNumber)) {
            const finalNumber = newNumber === 'Error' ? strippedValue : newNumber;
            const finalUnit = newUnitValue || unitValue;
            onChange && onChange(finalNumber + finalUnit);
            setDisplayedInputValue(finalNumber);
        }
    }
    function handleUnitUpdate(unit) {
        onChange && onChange(numberValue + unit);
    }
    return (react__WEBPACK_IMPORTED_MODULE_1___default().createElement("div", { className: classnames__WEBPACK_IMPORTED_MODULE_0___default()(_PropertyPanelLengthUnitInput_module_scss__WEBPACK_IMPORTED_MODULE_8__/* ["default"] */ .A['Root'], isFauxFocused && _PropertyPanelLengthUnitInput_module_scss__WEBPACK_IMPORTED_MODULE_8__/* ["default"] */ .A['is-faux-focused']) },
        react__WEBPACK_IMPORTED_MODULE_1___default().createElement(_noodl_core_ui_components_property_panel_PropertyPanelBaseInput__WEBPACK_IMPORTED_MODULE_2__/* .PropertyPanelBaseInput */ .Z, { value: displayedInputValue, type: "text", isChanged: isChanged, isConnected: isConnected, onChange: (value) => setDisplayedInputValue(value), isFauxFocused: isFauxFocused, onFocus: () => setIsFauxFocused(() => true), onKeyDown: (e) => e.key === 'Enter' && handleInputUpdate(displayedInputValue), onBlur: () => {
                setIsFauxFocused(() => false);
                handleInputUpdate(displayedInputValue);
            }, hasSmallText: hasSmallText }),
        react__WEBPACK_IMPORTED_MODULE_1___default().createElement("div", { className: classnames__WEBPACK_IMPORTED_MODULE_0___default()(_PropertyPanelLengthUnitInput_module_scss__WEBPACK_IMPORTED_MODULE_8__/* ["default"] */ .A['UnitContainer'], hasSmallText && _PropertyPanelLengthUnitInput_module_scss__WEBPACK_IMPORTED_MODULE_8__/* ["default"] */ .A['has-small-text']) },
            react__WEBPACK_IMPORTED_MODULE_1___default().createElement(_noodl_core_ui_components_property_panel_PropertyPanelSelectInput__WEBPACK_IMPORTED_MODULE_3__/* .PropertyPanelSelectInput */ .S, { value: getUnit(), properties: unitSelectProps, onChange: handleUnitUpdate, isFauxFocused: isFauxFocused, onFocus: () => setIsFauxFocused(() => true), onBlur: () => setIsFauxFocused(() => false), hasHiddenCaret: true, hasSmallText: hasSmallText }))));
}
function isArithmeticExpression(str) {
    const arithmeticRegex = /^[-+*/()\d\s.]+$/;
    return arithmeticRegex.test(str);
}
function roundCssLengthNumber(num) {
    if (isNaN(num)) {
        console.warn('Passed in NaN to PropertyPanelLengthInput. Changing it to empty string');
        return '';
    }
    if (!isFinite(num) || num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
        return 'Error';
    }
    else if (Number.isInteger(num)) {
        return num.toFixed(0); // Display the number without decimals
    }
    else {
        const roundedNum = num.toFixed(2); // Round the number to two decimal places
        const decimalPart = roundedNum.split('.')[1];
        if (decimalPart === '00') {
            return roundedNum.split('.')[0] + '.0'; // Show only one decimal if the second decimal is "0"
        }
        else if (decimalPart === null || decimalPart === void 0 ? void 0 : decimalPart.endsWith('0')) {
            return roundedNum.split('.')[0] + '.' + decimalPart[0]; // Show only one decimal if the second decimal is "0"
        }
        else {
            return roundedNum;
        }
    }
}


/***/ }),

/***/ 30418:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .view-overlays .current-line {
	display: block;
	position: absolute;
	left: 0;
	top: 0;
	box-sizing: border-box;
}

.monaco-editor .margin-view-overlays .current-line {
	display: block;
	position: absolute;
	left: 0;
	top: 0;
	box-sizing: border-box;
}

.monaco-editor .margin-view-overlays .current-line.current-line-margin.current-line-margin-both {
	border-right: 0;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,cAAc;CACd,kBAAkB;CAClB,OAAO;CACP,MAAM;CACN,sBAAsB;AACvB;;AAEA;CACC,cAAc;CACd,kBAAkB;CAClB,OAAO;CACP,MAAM;CACN,sBAAsB;AACvB;;AAEA;CACC,eAAe;AAChB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .view-overlays .current-line {\n\tdisplay: block;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 0;\n\tbox-sizing: border-box;\n}\n\n.monaco-editor .margin-view-overlays .current-line {\n\tdisplay: block;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 0;\n\tbox-sizing: border-box;\n}\n\n.monaco-editor .margin-view-overlays .current-line.current-line-margin.current-line-margin-both {\n\tborder-right: 0;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 30855:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


/* istanbul ignore next  */
function setAttributesWithoutAttributes(styleElement) {
  var nonce =  true ? __webpack_require__.nc : 0;
  if (nonce) {
    styleElement.setAttribute("nonce", nonce);
  }
}
module.exports = setAttributesWithoutAttributes;

/***/ }),

/***/ 30999:
/***/ ((module) => {

// Module
var code = "<div class=\"content-picker\"> <div data-template=\"item\" style=\"min-height:56px;position:relative;display:flex;align-items:center\" class=\"content-picker-list-item\" d> <div class=\"content-picker-item\" style=\"flex-grow:1\" data-text=\"name\"> </div> <div style=\"width:50px;height:50px;margin-right:10px;display:flex;align-items:center;justify-content:center\" class=\"image-picker-thumb-bg\"> <img style=\"width:46px;height:46px\" data-src=\"thumbnail\"> </div> </div> <label class=\"content-picker-header-label\">Choose image</label> <div class=\"imageItems content-picker-items\"> </div> </div>";
// Exports
module.exports = code;

/***/ }),

/***/ 31020:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .selection-anchor {
	background-color: #007ACC;
	width: 2px !important;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/anchorSelect/browser/anchorSelect.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,yBAAyB;CACzB,qBAAqB;AACtB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .selection-anchor {\n\tbackground-color: #007ACC;\n\twidth: 2px !important;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 31302:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  Z: () => (/* reexport */ Portal)
});

// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
// EXTERNAL MODULE: external "react-dom"
var external_react_dom_ = __webpack_require__(20180);
;// ../noodl-core-ui/src/components/layout/Portal/Portal.tsx


function Portal({ children, portalRoot }) {
    const elementRoot = document.createElement('div');
    (0,external_react_.useEffect)(() => {
        portalRoot.appendChild(elementRoot);
        return () => {
            portalRoot.removeChild(elementRoot);
        };
    }, [portalRoot, elementRoot]);
    return (0,external_react_dom_.createPortal)(children, portalRoot);
}

;// ../noodl-core-ui/src/components/layout/Portal/index.ts



/***/ }),

/***/ 31303:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.TabBar-module__Root--FrUsI{display:flex;align-items:center;gap:4px;padding:0;margin:0;background:rgba(0,0,0,0);border-bottom:1px solid var(--theme-color-border-default)}.TabBar-module__Tab--oT9t4{position:relative;display:flex;align-items:center;gap:8px;padding:12px 20px;background:rgba(0,0,0,0);border:none;cursor:pointer;color:var(--theme-color-fg-default-shy);font-size:14px;font-weight:500;line-height:1;transition:all .2s ease;white-space:nowrap;user-select:none}.TabBar-module__Tab--oT9t4::after{content:"";position:absolute;bottom:-1px;left:0;right:0;height:2px;background:rgba(0,0,0,0);transition:background .2s ease}.TabBar-module__Tab--oT9t4:hover:not(.TabBar-module__is-disabled--KvL6x){color:var(--theme-color-fg-default);background:var(--theme-color-bg-hover)}.TabBar-module__Tab--oT9t4:focus{outline:none;box-shadow:inset 0 0 0 2px var(--theme-color-primary)}.TabBar-module__Tab--oT9t4:focus:not(:focus-visible){box-shadow:none}.TabBar-module__Tab--oT9t4.TabBar-module__is-active--DLx2H{color:var(--theme-color-primary);font-weight:600}.TabBar-module__Tab--oT9t4.TabBar-module__is-active--DLx2H::after{background:var(--theme-color-primary)}.TabBar-module__Tab--oT9t4.TabBar-module__is-disabled--KvL6x{color:var(--theme-color-fg-disabled);cursor:not-allowed;opacity:.5}.TabBar-module__Tab-icon--U3I59{display:flex;align-items:center;justify-content:center;font-size:16px}.TabBar-module__Tab-label--ZkNud{display:flex;align-items:center}.TabBar-module__is-size-small--_YmqN .TabBar-module__Tab--oT9t4{padding:8px 16px;font-size:13px;gap:6px}.TabBar-module__is-size-small--_YmqN .TabBar-module__Tab-icon--U3I59{font-size:14px}.TabBar-module__is-size-medium--BVxZe .TabBar-module__Tab--oT9t4{padding:12px 20px;font-size:14px;gap:8px}.TabBar-module__is-size-medium--BVxZe .TabBar-module__Tab-icon--U3I59{font-size:16px}.TabBar-module__is-size-large--yalEw .TabBar-module__Tab--oT9t4{padding:16px 24px;font-size:15px;gap:10px}.TabBar-module__is-size-large--yalEw .TabBar-module__Tab-icon--U3I59{font-size:18px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/TabBar/TabBar.module.scss"],"names":[],"mappings":"AAIA,4BACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,SAAA,CACA,QAAA,CACA,wBAAA,CACA,yDAAA,CAGF,2BACE,iBAAA,CACA,YAAA,CACA,kBAAA,CACA,OAAA,CACA,iBAAA,CACA,wBAAA,CACA,WAAA,CACA,cAAA,CACA,uCAAA,CACA,cAAA,CACA,eAAA,CACA,aAAA,CACA,uBAAA,CACA,kBAAA,CACA,gBAAA,CAGA,kCACE,UAAA,CACA,iBAAA,CACA,WAAA,CACA,MAAA,CACA,OAAA,CACA,UAAA,CACA,wBAAA,CACA,8BAAA,CAGF,yEACE,mCAAA,CACA,sCAAA,CAGF,iCACE,YAAA,CACA,qDAAA,CAGF,qDACE,eAAA,CAGF,2DACE,gCAAA,CACA,eAAA,CAEA,kEACE,qCAAA,CAIJ,6DACE,oCAAA,CACA,kBAAA,CACA,UAAA,CAIJ,gCACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,cAAA,CAGF,iCACE,YAAA,CACA,kBAAA,CAKA,gEACE,gBAAA,CACA,cAAA,CACA,OAAA,CAGF,qEACE,cAAA,CAKF,iEACE,iBAAA,CACA,cAAA,CACA,OAAA,CAGF,sEACE,cAAA,CAKF,gEACE,iBAAA,CACA,cAAA,CACA,QAAA,CAGF,qEACE,cAAA","sourcesContent":["/**\n * TabBar - Modern, clean horizontal tab navigation\n */\n\n.Root {\n  display: flex;\n  align-items: center;\n  gap: 4px;\n  padding: 0;\n  margin: 0;\n  background: transparent;\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.Tab {\n  position: relative;\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 12px 20px;\n  background: transparent;\n  border: none;\n  cursor: pointer;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 14px;\n  font-weight: 500;\n  line-height: 1;\n  transition: all 0.2s ease;\n  white-space: nowrap;\n  user-select: none;\n\n  // Bottom border indicator\n  &::after {\n    content: '';\n    position: absolute;\n    bottom: -1px;\n    left: 0;\n    right: 0;\n    height: 2px;\n    background: transparent;\n    transition: background 0.2s ease;\n  }\n\n  &:hover:not(.is-disabled) {\n    color: var(--theme-color-fg-default);\n    background: var(--theme-color-bg-hover);\n  }\n\n  &:focus {\n    outline: none;\n    box-shadow: inset 0 0 0 2px var(--theme-color-primary);\n  }\n\n  &:focus:not(:focus-visible) {\n    box-shadow: none;\n  }\n\n  &.is-active {\n    color: var(--theme-color-primary);\n    font-weight: 600;\n\n    &::after {\n      background: var(--theme-color-primary);\n    }\n  }\n\n  &.is-disabled {\n    color: var(--theme-color-fg-disabled);\n    cursor: not-allowed;\n    opacity: 0.5;\n  }\n}\n\n.Tab-icon {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  font-size: 16px;\n}\n\n.Tab-label {\n  display: flex;\n  align-items: center;\n}\n\n// Size variants\n.is-size-small {\n  .Tab {\n    padding: 8px 16px;\n    font-size: 13px;\n    gap: 6px;\n  }\n\n  .Tab-icon {\n    font-size: 14px;\n  }\n}\n\n.is-size-medium {\n  .Tab {\n    padding: 12px 20px;\n    font-size: 14px;\n    gap: 8px;\n  }\n\n  .Tab-icon {\n    font-size: 16px;\n  }\n}\n\n.is-size-large {\n  .Tab {\n    padding: 16px 24px;\n    font-size: 15px;\n    gap: 10px;\n  }\n\n  .Tab-icon {\n    font-size: 18px;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `TabBar-module__Root--FrUsI`,
	"Tab": `TabBar-module__Tab--oT9t4`,
	"is-disabled": `TabBar-module__is-disabled--KvL6x`,
	"is-active": `TabBar-module__is-active--DLx2H`,
	"Tab-icon": `TabBar-module__Tab-icon--U3I59`,
	"Tab-label": `TabBar-module__Tab-label--ZkNud`,
	"is-size-small": `TabBar-module__is-size-small--_YmqN`,
	"is-size-medium": `TabBar-module__is-size-medium--BVxZe`,
	"is-size-large": `TabBar-module__is-size-large--yalEw`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 31325:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FallbackEncoder = void 0;
const FallbackEncoder = ({ headers, body }) => {
    return {
        bodyHeaders: {
            'content-type': 'application/json',
        },
        body: JSON.stringify(body),
    };
};
exports.FallbackEncoder = FallbackEncoder;
//# sourceMappingURL=request-options.js.map

/***/ }),

/***/ 31484:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/* =============================================================================
   NOODL DESIGN SYSTEM - SPACING
   ============================================================================= */

:root {
  /* ---------------------------------------------------------------------------
     SPACING SCALE
     4px base unit system
     --------------------------------------------------------------------------- */
  --spacing-0: 0;
  --spacing-px: 1px;
  --spacing-0-5: 2px;
  --spacing-1: 4px;
  --spacing-1-5: 6px;
  --spacing-2: 8px;
  --spacing-2-5: 10px;
  --spacing-3: 12px;
  --spacing-3-5: 14px;
  --spacing-4: 16px;
  --spacing-5: 20px;
  --spacing-6: 24px;
  --spacing-7: 28px;
  --spacing-8: 32px;
  --spacing-9: 36px;
  --spacing-10: 40px;
  --spacing-11: 44px;
  --spacing-12: 48px;
  --spacing-14: 56px;
  --spacing-16: 64px;
  --spacing-20: 80px;
  --spacing-24: 96px;

  /* ---------------------------------------------------------------------------
     SEMANTIC SPACING
     Component-specific spacing aliases
     --------------------------------------------------------------------------- */

  /* Panel spacing */
  --spacing-panel-padding: var(--spacing-4);
  --spacing-panel-gap: var(--spacing-3);

  /* Card spacing */
  --spacing-card-padding: var(--spacing-3);
  --spacing-card-gap: var(--spacing-2);

  /* Section spacing */
  --spacing-section-gap: var(--spacing-6);
  --spacing-section-padding: var(--spacing-4);

  /* Input spacing */
  --spacing-input-padding-x: var(--spacing-2);
  --spacing-input-padding-y: var(--spacing-1-5);
  --spacing-input-gap: var(--spacing-2);

  /* Button spacing */
  --spacing-button-padding-x: var(--spacing-3);
  --spacing-button-padding-y: var(--spacing-2);
  --spacing-button-gap: var(--spacing-2);

  /* Icon spacing */
  --spacing-icon-gap: var(--spacing-2);

  /* ---------------------------------------------------------------------------
     BORDER RADIUS
     --------------------------------------------------------------------------- */
  --radius-none: 0;
  --radius-sm: 2px;
  --radius-default: 4px;
  --radius-md: 6px;
  --radius-lg: 8px;
  --radius-xl: 12px;
  --radius-2xl: 16px;
  --radius-3xl: 24px;
  --radius-full: 9999px;

  /* ---------------------------------------------------------------------------
     SHADOWS
     --------------------------------------------------------------------------- */
  --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  --shadow-default: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1);
  --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
  --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
  --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
  --shadow-2xl: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  --shadow-inner: inset 0 2px 4px 0 rgba(0, 0, 0, 0.05);

  /* Dialog/popup shadow */
  --shadow-popup: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 10px 15px -3px rgba(0, 0, 0, 0.2),
    0 20px 25px -5px rgba(0, 0, 0, 0.15);

  /* ---------------------------------------------------------------------------
     TRANSITIONS
     --------------------------------------------------------------------------- */
  --transition-fast: 100ms;
  --transition-default: 150ms;
  --transition-slow: 300ms;
  --transition-ease: cubic-bezier(0.4, 0, 0.2, 1);
  --transition-ease-in: cubic-bezier(0.4, 0, 1, 1);
  --transition-ease-out: cubic-bezier(0, 0, 0.2, 1);
  --transition-ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);

  /* ---------------------------------------------------------------------------
     Z-INDEX SCALE
     --------------------------------------------------------------------------- */
  --z-base: 0;
  --z-dropdown: 100;
  --z-sticky: 200;
  --z-fixed: 300;
  --z-modal-backdrop: 400;
  --z-modal: 500;
  --z-popover: 600;
  --z-tooltip: 700;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/custom-properties/spacing.css"],"names":[],"mappings":"AAAA;;kFAEkF;;AAElF;EACE;;;kFAGgF;EAChF,cAAc;EACd,iBAAiB;EACjB,kBAAkB;EAClB,gBAAgB;EAChB,kBAAkB;EAClB,gBAAgB;EAChB,mBAAmB;EACnB,iBAAiB;EACjB,mBAAmB;EACnB,iBAAiB;EACjB,iBAAiB;EACjB,iBAAiB;EACjB,iBAAiB;EACjB,iBAAiB;EACjB,iBAAiB;EACjB,kBAAkB;EAClB,kBAAkB;EAClB,kBAAkB;EAClB,kBAAkB;EAClB,kBAAkB;EAClB,kBAAkB;EAClB,kBAAkB;;EAElB;;;kFAGgF;;EAEhF,kBAAkB;EAClB,yCAAyC;EACzC,qCAAqC;;EAErC,iBAAiB;EACjB,wCAAwC;EACxC,oCAAoC;;EAEpC,oBAAoB;EACpB,uCAAuC;EACvC,2CAA2C;;EAE3C,kBAAkB;EAClB,2CAA2C;EAC3C,6CAA6C;EAC7C,qCAAqC;;EAErC,mBAAmB;EACnB,4CAA4C;EAC5C,4CAA4C;EAC5C,sCAAsC;;EAEtC,iBAAiB;EACjB,oCAAoC;;EAEpC;;kFAEgF;EAChF,gBAAgB;EAChB,gBAAgB;EAChB,qBAAqB;EACrB,gBAAgB;EAChB,gBAAgB;EAChB,iBAAiB;EACjB,kBAAkB;EAClB,kBAAkB;EAClB,qBAAqB;;EAErB;;kFAEgF;EAChF,4CAA4C;EAC5C,mFAAmF;EACnF,iFAAiF;EACjF,mFAAmF;EACnF,oFAAoF;EACpF,mDAAmD;EACnD,qDAAqD;;EAErD,wBAAwB;EACxB;wCACsC;;EAEtC;;kFAEgF;EAChF,wBAAwB;EACxB,2BAA2B;EAC3B,wBAAwB;EACxB,+CAA+C;EAC/C,gDAAgD;EAChD,iDAAiD;EACjD,sDAAsD;;EAEtD;;kFAEgF;EAChF,WAAW;EACX,iBAAiB;EACjB,eAAe;EACf,cAAc;EACd,uBAAuB;EACvB,cAAc;EACd,gBAAgB;EAChB,gBAAgB;AAClB","sourcesContent":["/* =============================================================================\n   NOODL DESIGN SYSTEM - SPACING\n   ============================================================================= */\n\n:root {\n  /* ---------------------------------------------------------------------------\n     SPACING SCALE\n     4px base unit system\n     --------------------------------------------------------------------------- */\n  --spacing-0: 0;\n  --spacing-px: 1px;\n  --spacing-0-5: 2px;\n  --spacing-1: 4px;\n  --spacing-1-5: 6px;\n  --spacing-2: 8px;\n  --spacing-2-5: 10px;\n  --spacing-3: 12px;\n  --spacing-3-5: 14px;\n  --spacing-4: 16px;\n  --spacing-5: 20px;\n  --spacing-6: 24px;\n  --spacing-7: 28px;\n  --spacing-8: 32px;\n  --spacing-9: 36px;\n  --spacing-10: 40px;\n  --spacing-11: 44px;\n  --spacing-12: 48px;\n  --spacing-14: 56px;\n  --spacing-16: 64px;\n  --spacing-20: 80px;\n  --spacing-24: 96px;\n\n  /* ---------------------------------------------------------------------------\n     SEMANTIC SPACING\n     Component-specific spacing aliases\n     --------------------------------------------------------------------------- */\n\n  /* Panel spacing */\n  --spacing-panel-padding: var(--spacing-4);\n  --spacing-panel-gap: var(--spacing-3);\n\n  /* Card spacing */\n  --spacing-card-padding: var(--spacing-3);\n  --spacing-card-gap: var(--spacing-2);\n\n  /* Section spacing */\n  --spacing-section-gap: var(--spacing-6);\n  --spacing-section-padding: var(--spacing-4);\n\n  /* Input spacing */\n  --spacing-input-padding-x: var(--spacing-2);\n  --spacing-input-padding-y: var(--spacing-1-5);\n  --spacing-input-gap: var(--spacing-2);\n\n  /* Button spacing */\n  --spacing-button-padding-x: var(--spacing-3);\n  --spacing-button-padding-y: var(--spacing-2);\n  --spacing-button-gap: var(--spacing-2);\n\n  /* Icon spacing */\n  --spacing-icon-gap: var(--spacing-2);\n\n  /* ---------------------------------------------------------------------------\n     BORDER RADIUS\n     --------------------------------------------------------------------------- */\n  --radius-none: 0;\n  --radius-sm: 2px;\n  --radius-default: 4px;\n  --radius-md: 6px;\n  --radius-lg: 8px;\n  --radius-xl: 12px;\n  --radius-2xl: 16px;\n  --radius-3xl: 24px;\n  --radius-full: 9999px;\n\n  /* ---------------------------------------------------------------------------\n     SHADOWS\n     --------------------------------------------------------------------------- */\n  --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);\n  --shadow-default: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1);\n  --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);\n  --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);\n  --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);\n  --shadow-2xl: 0 25px 50px -12px rgba(0, 0, 0, 0.25);\n  --shadow-inner: inset 0 2px 4px 0 rgba(0, 0, 0, 0.05);\n\n  /* Dialog/popup shadow */\n  --shadow-popup: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 10px 15px -3px rgba(0, 0, 0, 0.2),\n    0 20px 25px -5px rgba(0, 0, 0, 0.15);\n\n  /* ---------------------------------------------------------------------------\n     TRANSITIONS\n     --------------------------------------------------------------------------- */\n  --transition-fast: 100ms;\n  --transition-default: 150ms;\n  --transition-slow: 300ms;\n  --transition-ease: cubic-bezier(0.4, 0, 0.2, 1);\n  --transition-ease-in: cubic-bezier(0.4, 0, 1, 1);\n  --transition-ease-out: cubic-bezier(0, 0, 0.2, 1);\n  --transition-ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);\n\n  /* ---------------------------------------------------------------------------\n     Z-INDEX SCALE\n     --------------------------------------------------------------------------- */\n  --z-base: 0;\n  --z-dropdown: 100;\n  --z-sticky: 200;\n  --z-fixed: 300;\n  --z-modal-backdrop: 400;\n  --z-modal: 500;\n  --z-popover: 600;\n  --z-tooltip: 700;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 31617:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.BaseDialog-module__Root--_Edkr{border:none;padding:0;background:rgba(0,0,0,0);box-sizing:border-box;position:fixed;top:0;left:0;right:0;bottom:0}.BaseDialog-module__Root--_Edkr.BaseDialog-module__has-backdrop--STAex{background-color:var(--theme-color-bg-1-transparent)}.BaseDialog-module__Root--_Edkr.BaseDialog-module__is-locking-scroll--s239t{background-color:rgba(0,0,0,0)}.BaseDialog-module__Root--_Edkr:not(.BaseDialog-module__has-backdrop--STAex):not(.BaseDialog-module__is-locking-scroll--s239t){pointer-events:none}.BaseDialog-module__VisibleDialog--RqXfa{box-shadow:var(--shadow-popup);border:1px solid var(--theme-color-border-subtle);border-radius:var(--radius-lg);overflow:hidden;max-height:90vh;max-width:90vw;position:absolute;width:var(--width);pointer-events:all}.BaseDialog-module__Root--_Edkr.BaseDialog-module__is-centered--ActN6 .BaseDialog-module__VisibleDialog--RqXfa{top:50%;left:50%;animation:BaseDialog-module__enter-centered--TDE89 var(--speed-quick) var(--easing-base) both}.BaseDialog-module__Root--_Edkr:not(.BaseDialog-module__is-centered--ActN6) .BaseDialog-module__VisibleDialog--RqXfa.BaseDialog-module__is-visible--cPEqG.BaseDialog-module__is-variant-default--myacE{animation:BaseDialog-module__enter--vOhhe var(--speed-quick) var(--easing-base) both}.BaseDialog-module__Root--_Edkr:not(.BaseDialog-module__is-centered--ActN6) .BaseDialog-module__VisibleDialog--RqXfa.BaseDialog-module__is-visible--cPEqG.BaseDialog-module__is-variant-select--qScND{transform:translate(var(--offsetX), var(--offsetY))}.BaseDialog-module__VisibleDialog--RqXfa::after{content:"";position:absolute;top:0;left:0;right:0;bottom:0;background-color:var(--background);border-radius:var(--radius-lg);overflow:hidden;pointer-events:none}.BaseDialog-module__VisibleDialog--RqXfa::-webkit-scrollbar{width:8px}.BaseDialog-module__VisibleDialog--RqXfa::-webkit-scrollbar-track{background:var(--theme-color-bg-3)}.BaseDialog-module__VisibleDialog--RqXfa::-webkit-scrollbar-thumb{background:var(--theme-color-bg-5);border-radius:var(--radius-full)}.BaseDialog-module__VisibleDialog--RqXfa::-webkit-scrollbar-thumb:hover{background:var(--theme-color-fg-muted)}.BaseDialog-module__Arrow--PitT7{position:absolute;width:0;height:0;top:var(--arrow-top);left:var(--arrow-left);pointer-events:none}.BaseDialog-module__Arrow--PitT7::after{content:"";display:block;width:11px;height:11px;transform:translate(-50%, -50%) rotate(45deg);background:var(--background)}.BaseDialog-module__Arrow--PitT7.BaseDialog-module__is-contrast--bkn7b::after{background:var(--backgroundContrast)}.BaseDialog-module__Title--jnZBr{background-color:var(--backgroundContrast);padding:12px}.BaseDialog-module__MeasuringContainer--ksRtY{pointer-events:none;height:0;overflow:visible;opacity:0}.BaseDialog-module__ChildContainer--tK422{position:relative;z-index:1}@keyframes BaseDialog-module__enter--vOhhe{from{opacity:0;transform:translate(calc(var(--animationStartOffsetX) + var(--offsetX)), calc(var(--animationStartOffsetY) + var(--offsetY)))}to{opacity:1;transform:translate(var(--offsetX), var(--offsetY))}}@keyframes BaseDialog-module__enter-centered--TDE89{from{opacity:0;transform:translate(-50%, calc(-50% + 16px))}to{opacity:1;transform:translate(-50%, -50%)}}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/BaseDialog/BaseDialog.module.scss"],"names":[],"mappings":"AAAA,gCACE,WAAA,CACA,SAAA,CACA,wBAAA,CACA,qBAAA,CACA,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CAEA,uEACE,oDAAA,CAQF,4EACE,8BAAA,CAGF,+HACE,mBAAA,CAIJ,yCAEE,8BAAA,CAGA,iDAAA,CAGA,8BAAA,CAGA,eAAA,CAGA,eAAA,CACA,cAAA,CAEA,iBAAA,CACA,kBAAA,CACA,kBAAA,CAEA,+GACE,OAAA,CACA,QAAA,CACA,6FAAA,CAIA,uMACE,oFAAA,CAGF,sMACE,mDAAA,CAIJ,gDACE,UAAA,CACA,iBAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,kCAAA,CACA,8BAAA,CACA,eAAA,CACA,mBAAA,CAIF,4DACE,SAAA,CAGF,kEACE,kCAAA,CAGF,kEACE,kCAAA,CACA,gCAAA,CAEA,wEACE,sCAAA,CAKN,iCACE,iBAAA,CACA,OAAA,CACA,QAAA,CACA,oBAAA,CACA,sBAAA,CACA,mBAAA,CAEA,wCACE,UAAA,CACA,aAAA,CACA,UAAA,CACA,WAAA,CACA,6CAAA,CACA,4BAAA,CAGF,8EACE,oCAAA,CAIJ,iCACE,0CAAA,CACA,YAAA,CAGF,8CACE,mBAAA,CACA,QAAA,CACA,gBAAA,CACA,SAAA,CAGF,0CACE,iBAAA,CACA,SAAA,CAGF,2CACE,KACE,SAAA,CACA,6HAAA,CAKF,GACE,SAAA,CACA,mDAAA,CAAA,CAIJ,oDACE,KACE,SAAA,CACA,4CAAA,CAEF,GACE,SAAA,CACA,+BAAA,CAAA","sourcesContent":[".Root {\n  border: none;\n  padding: 0;\n  background: transparent;\n  box-sizing: border-box;\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n\n  &.has-backdrop {\n    background-color: var(--theme-color-bg-1-transparent);\n\n    /* Optional: Subtle blur for modern feel */\n    /* Note: May have performance implications on older hardware */\n    /* backdrop-filter: blur(4px); */\n    /* -webkit-backdrop-filter: blur(4px); */\n  }\n\n  &.is-locking-scroll {\n    background-color: transparent;\n  }\n\n  &:not(.has-backdrop):not(.is-locking-scroll) {\n    pointer-events: none;\n  }\n}\n\n.VisibleDialog {\n  /* Modern elevated shadow */\n  box-shadow: var(--shadow-popup);\n\n  /* Border for definition against backdrop */\n  border: 1px solid var(--theme-color-border-subtle);\n\n  /* Modern rounded corners */\n  border-radius: var(--radius-lg);\n\n  /* Overflow handling */\n  overflow: hidden;\n\n  /* Size constraints */\n  max-height: 90vh;\n  max-width: 90vw;\n\n  position: absolute;\n  width: var(--width);\n  pointer-events: all;\n\n  .Root.is-centered & {\n    top: 50%;\n    left: 50%;\n    animation: enter-centered var(--speed-quick) var(--easing-base) both;\n  }\n\n  .Root:not(.is-centered) &.is-visible {\n    &.is-variant-default {\n      animation: enter var(--speed-quick) var(--easing-base) both;\n    }\n\n    &.is-variant-select {\n      transform: translate(var(--offsetX), var(--offsetY));\n    }\n  }\n\n  &::after {\n    content: '';\n    position: absolute;\n    top: 0;\n    left: 0;\n    right: 0;\n    bottom: 0;\n    background-color: var(--background);\n    border-radius: var(--radius-lg);\n    overflow: hidden;\n    pointer-events: none; // Allow clicks to pass through to content\n  }\n\n  /* Custom scrollbar styling for dialog content */\n  &::-webkit-scrollbar {\n    width: 8px;\n  }\n\n  &::-webkit-scrollbar-track {\n    background: var(--theme-color-bg-3);\n  }\n\n  &::-webkit-scrollbar-thumb {\n    background: var(--theme-color-bg-5);\n    border-radius: var(--radius-full);\n\n    &:hover {\n      background: var(--theme-color-fg-muted);\n    }\n  }\n}\n\n.Arrow {\n  position: absolute;\n  width: 0;\n  height: 0;\n  top: var(--arrow-top);\n  left: var(--arrow-left);\n  pointer-events: none;\n\n  &::after {\n    content: '';\n    display: block;\n    width: 11px;\n    height: 11px;\n    transform: translate(-50%, -50%) rotate(45deg);\n    background: var(--background);\n  }\n\n  &.is-contrast::after {\n    background: var(--backgroundContrast);\n  }\n}\n\n.Title {\n  background-color: var(--backgroundContrast);\n  padding: 12px;\n}\n\n.MeasuringContainer {\n  pointer-events: none;\n  height: 0;\n  overflow: visible;\n  opacity: 0;\n}\n\n.ChildContainer {\n  position: relative;\n  z-index: 1;\n}\n\n@keyframes enter {\n  from {\n    opacity: 0;\n    transform: translate(\n      calc(var(--animationStartOffsetX) + var(--offsetX)),\n      calc(var(--animationStartOffsetY) + var(--offsetY))\n    );\n  }\n  to {\n    opacity: 1;\n    transform: translate(var(--offsetX), var(--offsetY));\n  }\n}\n\n@keyframes enter-centered {\n  from {\n    opacity: 0;\n    transform: translate(-50%, calc(-50% + 16px));\n  }\n  to {\n    opacity: 1;\n    transform: translate(-50%, -50%);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `BaseDialog-module__Root--_Edkr`,
	"has-backdrop": `BaseDialog-module__has-backdrop--STAex`,
	"is-locking-scroll": `BaseDialog-module__is-locking-scroll--s239t`,
	"VisibleDialog": `BaseDialog-module__VisibleDialog--RqXfa`,
	"is-centered": `BaseDialog-module__is-centered--ActN6`,
	"enter-centered": `BaseDialog-module__enter-centered--TDE89`,
	"is-visible": `BaseDialog-module__is-visible--cPEqG`,
	"is-variant-default": `BaseDialog-module__is-variant-default--myacE`,
	"enter": `BaseDialog-module__enter--vOhhe`,
	"is-variant-select": `BaseDialog-module__is-variant-select--qScND`,
	"Arrow": `BaseDialog-module__Arrow--PitT7`,
	"is-contrast": `BaseDialog-module__is-contrast--bkn7b`,
	"Title": `BaseDialog-module__Title--jnZBr`,
	"MeasuringContainer": `BaseDialog-module__MeasuringContainer--ksRtY`,
	"ChildContainer": `BaseDialog-module__ChildContainer--tK422`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 31714:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.sleep = void 0;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
exports.sleep = sleep;
//# sourceMappingURL=sleep.js.map

/***/ }),

/***/ 31722:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgArrowLineRight = function SvgArrowLineRight(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M20.8994 21.9382C21.3136 21.9382 21.6494 21.6024 21.6494 21.1882L21.6494 4.68823C21.6494 4.27402 21.3136 3.93823 20.8994 3.93823C20.4852 3.93823 20.1494 4.27402 20.1494 4.68823L20.1494 21.1882C20.1494 21.6024 20.4852 21.9382 20.8994 21.9382Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M18.1366 13.2225C18.1 13.312 18.0454 13.3959 17.9727 13.4686L14.275 17.1663C13.9821 17.4591 13.5073 17.4591 13.2144 17.1663C12.9215 16.8734 12.9215 16.3985 13.2144 16.1056L15.6317 13.6882L3.37397 13.6882C2.95975 13.6882 2.62397 13.3524 2.62397 12.9382C2.62397 12.524 2.95975 12.1882 3.37397 12.1882L15.6317 12.1882L13.2144 9.77089C12.9215 9.47799 12.9215 9.00312 13.2144 8.71023C13.5073 8.41733 13.9821 8.41733 14.275 8.71023L17.9706 12.4058C17.9774 12.4125 17.984 12.4194 17.9905 12.4263C18.1157 12.5603 18.1924 12.7403 18.1924 12.9382C18.1924 13.0388 18.1726 13.1348 18.1366 13.2225Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgArrowLineRight);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "8590cd54c6e372b99ed69ed938a5df53.svg");

/***/ }),

/***/ 31890:
/***/ ((module) => {

"use strict";
module.exports = require("remarkable");

/***/ }),

/***/ 31957:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.TagPill-module__Root--L_5zL{display:inline-flex;align-items:center;gap:var(--spacing-2);border-radius:12px;transition:opacity .15s ease;user-select:none;flex-shrink:0}.TagPill-module__Root--L_5zL.TagPill-module__Clickable--rVCZ7{cursor:pointer}.TagPill-module__Root--L_5zL.TagPill-module__Clickable--rVCZ7:hover{opacity:.85}.TagPill-module__Root--L_5zL.TagPill-module__Clickable--rVCZ7:active{opacity:.7}.TagPill-module__Root--L_5zL.TagPill-module__Clickable--rVCZ7:focus-visible{outline:2px solid var(--theme-color-primary);outline-offset:2px}.TagPill-module__Size-small--rSBag{padding:2px 8px;min-height:20px}.TagPill-module__Size-medium--VlZBx{padding:4px 10px;min-height:24px}.TagPill-module__Label--vbIYE{color:#fff;font-weight:500;line-height:1;white-space:nowrap}.TagPill-module__RemoveButton--_7P4n{all:unset;display:inline-flex;align-items:center;justify-content:center;padding:0;margin-left:2px;cursor:pointer;color:#fff;opacity:.7;transition:opacity .15s ease;border-radius:4px}.TagPill-module__RemoveButton--_7P4n:hover{opacity:1}.TagPill-module__RemoveButton--_7P4n:active{opacity:.6}.TagPill-module__RemoveButton--_7P4n:focus-visible{outline:1px solid #fff;outline-offset:1px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/preview/launcher/Launcher/components/TagPill/TagPill.module.scss"],"names":[],"mappings":"AAOA,6BACE,mBAAA,CACA,kBAAA,CACA,oBAAA,CACA,kBAAA,CACA,4BAAA,CACA,gBAAA,CACA,aAAA,CAEA,8DACE,cAAA,CAEA,oEACE,WAAA,CAGF,qEACE,UAAA,CAGF,4EACE,4CAAA,CACA,kBAAA,CAMN,mCACE,eAAA,CACA,eAAA,CAGF,oCACE,gBAAA,CACA,eAAA,CAIF,8BACE,UAAA,CACA,eAAA,CACA,aAAA,CACA,kBAAA,CAIF,qCACE,SAAA,CACA,mBAAA,CACA,kBAAA,CACA,sBAAA,CACA,SAAA,CACA,eAAA,CACA,cAAA,CACA,UAAA,CACA,UAAA,CACA,4BAAA,CACA,iBAAA,CAEA,2CACE,SAAA,CAGF,4CACE,UAAA,CAGF,mDACE,sBAAA,CACA,kBAAA","sourcesContent":["/**\n * TagPill Styles\n *\n * Small colored pill displaying a tag name.\n * Uses tag.color for background, white text for readability.\n */\n\n.Root {\n  display: inline-flex;\n  align-items: center;\n  gap: var(--spacing-2);\n  border-radius: 12px;\n  transition: opacity 0.15s ease;\n  user-select: none;\n  flex-shrink: 0;\n\n  &.Clickable {\n    cursor: pointer;\n\n    &:hover {\n      opacity: 0.85;\n    }\n\n    &:active {\n      opacity: 0.7;\n    }\n\n    &:focus-visible {\n      outline: 2px solid var(--theme-color-primary);\n      outline-offset: 2px;\n    }\n  }\n}\n\n/* Size Variants */\n.Size-small {\n  padding: 2px 8px;\n  min-height: 20px;\n}\n\n.Size-medium {\n  padding: 4px 10px;\n  min-height: 24px;\n}\n\n/* Label */\n.Label {\n  color: #ffffff;\n  font-weight: 500;\n  line-height: 1;\n  white-space: nowrap;\n}\n\n/* Remove Button */\n.RemoveButton {\n  all: unset;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0;\n  margin-left: 2px;\n  cursor: pointer;\n  color: #ffffff;\n  opacity: 0.7;\n  transition: opacity 0.15s ease;\n  border-radius: 4px;\n\n  &:hover {\n    opacity: 1;\n  }\n\n  &:active {\n    opacity: 0.6;\n  }\n\n  &:focus-visible {\n    outline: 1px solid #ffffff;\n    outline-offset: 1px;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `TagPill-module__Root--L_5zL`,
	"Clickable": `TagPill-module__Clickable--rVCZ7`,
	"Size-small": `TagPill-module__Size-small--rSBag`,
	"Size-medium": `TagPill-module__Size-medium--VlZBx`,
	"Label": `TagPill-module__Label--vbIYE`,
	"RemoveButton": `TagPill-module__RemoveButton--_7P4n`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 32226:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _circle, _circle2, _circle3, _circle4, _circle5, _circle6, _circle7, _circle8, _circle9, _circle0, _circle1, _circle10, _circle11, _circle12, _circle13, _circle14;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgGroup = function SvgGroup(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _circle || (_circle = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 4.9624,
    cy: 25.383,
    r: 1,
    transform: "rotate(-180 4.9624 25.383)",
    fill: "#F5F5F5"
  })), _circle2 || (_circle2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 24.9785,
    cy: 25.383,
    r: 1,
    transform: "rotate(-180 24.9785 25.383)",
    fill: "#F5F5F5"
  })), _circle3 || (_circle3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 4.9624,
    cy: 15.3754,
    r: 1,
    transform: "rotate(-180 4.9624 15.3754)",
    fill: "#F5F5F5"
  })), _circle4 || (_circle4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 4.9624,
    cy: 10.3716,
    r: 1,
    transform: "rotate(-180 4.9624 10.3716)",
    fill: "#F5F5F5"
  })), _circle5 || (_circle5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 24.9785,
    cy: 10.3716,
    r: 1,
    transform: "rotate(-180 24.9785 10.3716)",
    fill: "#F5F5F5"
  })), _circle6 || (_circle6 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 4.9624,
    cy: 20.3792,
    r: 1,
    transform: "rotate(-180 4.9624 20.3792)",
    fill: "#F5F5F5"
  })), _circle7 || (_circle7 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 24.9785,
    cy: 20.3792,
    r: 1,
    transform: "rotate(-180 24.9785 20.3792)",
    fill: "#F5F5F5"
  })), _circle8 || (_circle8 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 24.9785,
    cy: 15.3754,
    r: 1,
    transform: "rotate(-180 24.9785 15.3754)",
    fill: "#F5F5F5"
  })), _circle9 || (_circle9 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 4.9624,
    cy: 5.36786,
    r: 1,
    transform: "rotate(-180 4.9624 5.36786)",
    fill: "#F5F5F5"
  })), _circle0 || (_circle0 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 24.9785,
    cy: 5.36786,
    r: 1,
    transform: "rotate(-180 24.9785 5.36786)",
    fill: "#F5F5F5"
  })), _circle1 || (_circle1 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 19.9746,
    cy: 5.36731,
    r: 1,
    transform: "rotate(-180 19.9746 5.36731)",
    fill: "#F5F5F5"
  })), _circle10 || (_circle10 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 19.9746,
    cy: 25.3827,
    r: 1,
    transform: "rotate(-180 19.9746 25.3827)",
    fill: "#F5F5F5"
  })), _circle11 || (_circle11 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 9.96631,
    cy: 5.36755,
    r: 1,
    transform: "rotate(-180 9.96631 5.36755)",
    fill: "#F5F5F5"
  })), _circle12 || (_circle12 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 14.9707,
    cy: 5.36755,
    r: 1,
    transform: "rotate(-180 14.9707 5.36755)",
    fill: "#F5F5F5"
  })), _circle13 || (_circle13 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 9.96631,
    cy: 25.383,
    r: 1,
    transform: "rotate(-180 9.96631 25.383)",
    fill: "#F5F5F5"
  })), _circle14 || (_circle14 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 14.9707,
    cy: 25.383,
    r: 1,
    transform: "rotate(-180 14.9707 25.383)",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgGroup);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "abb4bb2ca48b99c18e5a64b34c950e44.svg");

/***/ }),

/***/ 32263:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   IF: () => (/* binding */ typescriptDefaults)
/* harmony export */ });
/* unused harmony exports JsxEmit, ModuleKind, ModuleResolutionKind, NewLineKind, ScriptTarget, getJavaScriptWorker, getTypeScriptWorker, javascriptDefaults, typescriptVersion */
/* harmony import */ var _editor_editor_api_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15618);

/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));

// src/language/typescript/lib/typescriptServicesMetadata.ts
var typescriptVersion = "4.5.5";

// src/fillers/monaco-editor-core.ts
var monaco_editor_core_exports = {};
__reExport(monaco_editor_core_exports, _editor_editor_api_js__WEBPACK_IMPORTED_MODULE_0__);


// src/language/typescript/monaco.contribution.ts
var ModuleKind = /* @__PURE__ */ ((ModuleKind2) => {
  ModuleKind2[ModuleKind2["None"] = 0] = "None";
  ModuleKind2[ModuleKind2["CommonJS"] = 1] = "CommonJS";
  ModuleKind2[ModuleKind2["AMD"] = 2] = "AMD";
  ModuleKind2[ModuleKind2["UMD"] = 3] = "UMD";
  ModuleKind2[ModuleKind2["System"] = 4] = "System";
  ModuleKind2[ModuleKind2["ES2015"] = 5] = "ES2015";
  ModuleKind2[ModuleKind2["ESNext"] = 99] = "ESNext";
  return ModuleKind2;
})(ModuleKind || {});
var JsxEmit = /* @__PURE__ */ ((JsxEmit2) => {
  JsxEmit2[JsxEmit2["None"] = 0] = "None";
  JsxEmit2[JsxEmit2["Preserve"] = 1] = "Preserve";
  JsxEmit2[JsxEmit2["React"] = 2] = "React";
  JsxEmit2[JsxEmit2["ReactNative"] = 3] = "ReactNative";
  JsxEmit2[JsxEmit2["ReactJSX"] = 4] = "ReactJSX";
  JsxEmit2[JsxEmit2["ReactJSXDev"] = 5] = "ReactJSXDev";
  return JsxEmit2;
})(JsxEmit || {});
var NewLineKind = /* @__PURE__ */ ((NewLineKind2) => {
  NewLineKind2[NewLineKind2["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
  NewLineKind2[NewLineKind2["LineFeed"] = 1] = "LineFeed";
  return NewLineKind2;
})(NewLineKind || {});
var ScriptTarget = /* @__PURE__ */ ((ScriptTarget2) => {
  ScriptTarget2[ScriptTarget2["ES3"] = 0] = "ES3";
  ScriptTarget2[ScriptTarget2["ES5"] = 1] = "ES5";
  ScriptTarget2[ScriptTarget2["ES2015"] = 2] = "ES2015";
  ScriptTarget2[ScriptTarget2["ES2016"] = 3] = "ES2016";
  ScriptTarget2[ScriptTarget2["ES2017"] = 4] = "ES2017";
  ScriptTarget2[ScriptTarget2["ES2018"] = 5] = "ES2018";
  ScriptTarget2[ScriptTarget2["ES2019"] = 6] = "ES2019";
  ScriptTarget2[ScriptTarget2["ES2020"] = 7] = "ES2020";
  ScriptTarget2[ScriptTarget2["ESNext"] = 99] = "ESNext";
  ScriptTarget2[ScriptTarget2["JSON"] = 100] = "JSON";
  ScriptTarget2[ScriptTarget2["Latest"] = 99 /* ESNext */] = "Latest";
  return ScriptTarget2;
})(ScriptTarget || {});
var ModuleResolutionKind = /* @__PURE__ */ ((ModuleResolutionKind2) => {
  ModuleResolutionKind2[ModuleResolutionKind2["Classic"] = 1] = "Classic";
  ModuleResolutionKind2[ModuleResolutionKind2["NodeJs"] = 2] = "NodeJs";
  return ModuleResolutionKind2;
})(ModuleResolutionKind || {});
var LanguageServiceDefaultsImpl = class {
  _onDidChange = new monaco_editor_core_exports.Emitter();
  _onDidExtraLibsChange = new monaco_editor_core_exports.Emitter();
  _extraLibs;
  _removedExtraLibs;
  _eagerModelSync;
  _compilerOptions;
  _diagnosticsOptions;
  _workerOptions;
  _onDidExtraLibsChangeTimeout;
  _inlayHintsOptions;
  constructor(compilerOptions, diagnosticsOptions, workerOptions, inlayHintsOptions) {
    this._extraLibs = /* @__PURE__ */ Object.create(null);
    this._removedExtraLibs = /* @__PURE__ */ Object.create(null);
    this._eagerModelSync = false;
    this.setCompilerOptions(compilerOptions);
    this.setDiagnosticsOptions(diagnosticsOptions);
    this.setWorkerOptions(workerOptions);
    this.setInlayHintsOptions(inlayHintsOptions);
    this._onDidExtraLibsChangeTimeout = -1;
  }
  get onDidChange() {
    return this._onDidChange.event;
  }
  get onDidExtraLibsChange() {
    return this._onDidExtraLibsChange.event;
  }
  get workerOptions() {
    return this._workerOptions;
  }
  get inlayHintsOptions() {
    return this._inlayHintsOptions;
  }
  getExtraLibs() {
    return this._extraLibs;
  }
  addExtraLib(content, _filePath) {
    let filePath;
    if (typeof _filePath === "undefined") {
      filePath = `ts:extralib-${Math.random().toString(36).substring(2, 15)}`;
    } else {
      filePath = _filePath;
    }
    if (this._extraLibs[filePath] && this._extraLibs[filePath].content === content) {
      return {
        dispose: () => {
        }
      };
    }
    let myVersion = 1;
    if (this._removedExtraLibs[filePath]) {
      myVersion = this._removedExtraLibs[filePath] + 1;
    }
    if (this._extraLibs[filePath]) {
      myVersion = this._extraLibs[filePath].version + 1;
    }
    this._extraLibs[filePath] = {
      content,
      version: myVersion
    };
    this._fireOnDidExtraLibsChangeSoon();
    return {
      dispose: () => {
        let extraLib = this._extraLibs[filePath];
        if (!extraLib) {
          return;
        }
        if (extraLib.version !== myVersion) {
          return;
        }
        delete this._extraLibs[filePath];
        this._removedExtraLibs[filePath] = myVersion;
        this._fireOnDidExtraLibsChangeSoon();
      }
    };
  }
  setExtraLibs(libs) {
    for (const filePath in this._extraLibs) {
      this._removedExtraLibs[filePath] = this._extraLibs[filePath].version;
    }
    this._extraLibs = /* @__PURE__ */ Object.create(null);
    if (libs && libs.length > 0) {
      for (const lib of libs) {
        const filePath = lib.filePath || `ts:extralib-${Math.random().toString(36).substring(2, 15)}`;
        const content = lib.content;
        let myVersion = 1;
        if (this._removedExtraLibs[filePath]) {
          myVersion = this._removedExtraLibs[filePath] + 1;
        }
        this._extraLibs[filePath] = {
          content,
          version: myVersion
        };
      }
    }
    this._fireOnDidExtraLibsChangeSoon();
  }
  _fireOnDidExtraLibsChangeSoon() {
    if (this._onDidExtraLibsChangeTimeout !== -1) {
      return;
    }
    this._onDidExtraLibsChangeTimeout = window.setTimeout(() => {
      this._onDidExtraLibsChangeTimeout = -1;
      this._onDidExtraLibsChange.fire(void 0);
    }, 0);
  }
  getCompilerOptions() {
    return this._compilerOptions;
  }
  setCompilerOptions(options) {
    this._compilerOptions = options || /* @__PURE__ */ Object.create(null);
    this._onDidChange.fire(void 0);
  }
  getDiagnosticsOptions() {
    return this._diagnosticsOptions;
  }
  setDiagnosticsOptions(options) {
    this._diagnosticsOptions = options || /* @__PURE__ */ Object.create(null);
    this._onDidChange.fire(void 0);
  }
  setWorkerOptions(options) {
    this._workerOptions = options || /* @__PURE__ */ Object.create(null);
    this._onDidChange.fire(void 0);
  }
  setInlayHintsOptions(options) {
    this._inlayHintsOptions = options || /* @__PURE__ */ Object.create(null);
    this._onDidChange.fire(void 0);
  }
  setMaximumWorkerIdleTime(value) {
  }
  setEagerModelSync(value) {
    this._eagerModelSync = value;
  }
  getEagerModelSync() {
    return this._eagerModelSync;
  }
};
var typescriptVersion2 = typescriptVersion;
var typescriptDefaults = new LanguageServiceDefaultsImpl({ allowNonTsExtensions: true, target: 99 /* Latest */ }, { noSemanticValidation: false, noSyntaxValidation: false, onlyVisible: false }, {}, {});
var javascriptDefaults = new LanguageServiceDefaultsImpl({ allowNonTsExtensions: true, allowJs: true, target: 99 /* Latest */ }, { noSemanticValidation: true, noSyntaxValidation: false, onlyVisible: false }, {}, {});
var getTypeScriptWorker = () => {
  return getMode().then((mode) => mode.getTypeScriptWorker());
};
var getJavaScriptWorker = () => {
  return getMode().then((mode) => mode.getJavaScriptWorker());
};
monaco_editor_core_exports.languages.typescript = {
  ModuleKind,
  JsxEmit,
  NewLineKind,
  ScriptTarget,
  ModuleResolutionKind,
  typescriptVersion: typescriptVersion2,
  typescriptDefaults,
  javascriptDefaults,
  getTypeScriptWorker,
  getJavaScriptWorker
};
function getMode() {
  if (false) // removed by dead control flow
{} else {
    return __webpack_require__.e(/* import() */ 450).then(__webpack_require__.bind(__webpack_require__, 14450));
  }
}
monaco_editor_core_exports.languages.onLanguage("typescript", () => {
  return getMode().then((mode) => mode.setupTypeScript(typescriptDefaults));
});
monaco_editor_core_exports.languages.onLanguage("javascript", () => {
  return getMode().then((mode) => mode.setupJavaScript(javascriptDefaults));
});



/***/ }),

/***/ 32383:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .contentWidgets .codicon-light-bulb,
.monaco-editor .contentWidgets .codicon-lightbulb-autofix {
	display: flex;
	align-items: center;
	justify-content: center;
}

.monaco-editor .contentWidgets .codicon-light-bulb:hover,
.monaco-editor .contentWidgets .codicon-lightbulb-autofix:hover {
	cursor: pointer;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/lightBulbWidget.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;;CAEC,aAAa;CACb,mBAAmB;CACnB,uBAAuB;AACxB;;AAEA;;CAEC,eAAe;AAChB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .contentWidgets .codicon-light-bulb,\n.monaco-editor .contentWidgets .codicon-lightbulb-autofix {\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n}\n\n.monaco-editor .contentWidgets .codicon-light-bulb:hover,\n.monaco-editor .contentWidgets .codicon-lightbulb-autofix:hover {\n\tcursor: pointer;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 32917:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.LauncherFooter-module__Root--MzWxe{padding:16px 24px;border-top:1px solid var(--theme-color-border-default);background:var(--theme-color-bg-1)}.LauncherFooter-module__Content--BcH8n{display:flex;align-items:center;gap:16px;font-size:13px}.LauncherFooter-module__Label--GweHM{color:var(--theme-color-fg-default-shy);font-weight:500}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherFooter/LauncherFooter.module.scss"],"names":[],"mappings":"AAIA,oCACE,iBAAA,CACA,sDAAA,CACA,kCAAA,CAGF,uCACE,YAAA,CACA,kBAAA,CACA,QAAA,CACA,cAAA,CAGF,qCACE,uCAAA,CACA,eAAA","sourcesContent":["/**\n * LauncherFooter - Styling\n */\n\n.Root {\n  padding: 16px 24px;\n  border-top: 1px solid var(--theme-color-border-default);\n  background: var(--theme-color-bg-1);\n}\n\n.Content {\n  display: flex;\n  align-items: center;\n  gap: 16px;\n  font-size: 13px;\n}\n\n.Label {\n  color: var(--theme-color-fg-default-shy);\n  font-weight: 500;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `LauncherFooter-module__Root--MzWxe`,
	"Content": `LauncherFooter-module__Content--BcH8n`,
	"Label": `LauncherFooter-module__Label--GweHM`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 33252:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.codeActionMenuWidget {
	padding: 8px 0px 8px 0px;
	overflow: auto;
	font-size: 13px;
	border-radius: 5px;
	min-width: 160px;
	z-index: 40;
	display: block;
	/* flex-direction: column;
	flex: 0 1 auto; */
	width: 100%;
	border-width: 0px;
	border-color: none;
	background-color: var(--vscode-menu-background);
	color: var(--vscode-menu-foreground);
	box-shadow: rgb(0,0,0, 16%) 0px 2px 8px;
}

.codeActionMenuWidget .monaco-list:not(.element-focused):focus:before {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 5; /* make sure we are on top of the tree items */
	content: "";
	pointer-events: none; /* enable click through */
	outline: 0px solid !important; /* we still need to handle the empty tree or no focus item case */
	outline-width: 0px !important;
	outline-style: none !important;
	outline-offset: 0px !important;
}

.codeActionMenuWidget .monaco-list {
	user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
	border: none !important;
	border-width: 0px !important;
}

/* .codeActionMenuWidget .monaco-list:not(.element-focus) {
	border: none !important;
	border-width: 0px !important;
} */

.codeActionMenuWidget .monaco-list .monaco-scrollable-element .monaco-list-rows {
	height: 100% !important;
}

.codeActionMenuWidget .monaco-list .monaco-scrollable-element {
	overflow: visible;
}
/** Styles for each row in the list element **/

.codeActionMenuWidget .monaco-list .monaco-list-row:not(.separator) {
	display: flex;
	-mox-box-sizing: border-box;
	box-sizing: border-box;
	padding: 0px 26px 0px 26px;
	background-repeat: no-repeat;
	background-position: 2px 2px;
	white-space: nowrap;
	cursor: pointer;
	touch-action: none;
	width: 100%;
}


.codeActionMenuWidget .monaco-list .monaco-list-row:hover:not(.option-disabled),
.codeActionMenuWidget .monaco-list .moncao-list-row.focused:not(.option-disabled) {
	color: var(--vscode-menu-selectionForeground) !important;
	background-color: var(--vscode-menu-selectionBackground) !important;
}

.codeActionMenuWidget .monaco-list .option-disabled,
.codeActionMenuWidget .monaco-list .option-disabled .focused {
	pointer-events: none;
	-webkit-touch-callout: none;
	-webkit-user-select: none;
	-khtml-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
	color: var(--vscode-disabledForeground) !important;
}

.codeActionMenuWidget .monaco-list .separator {
	border-bottom: 1px solid var(--vscode-menu-separatorBackground);
	padding-top: 0px !important;
	/* padding: 30px; */
	width: 100%;
	height: 0px !important;
	opacity: 1;
	font-size: inherit;
	margin: 5px 0 !important;
	border-radius: 0;
	display: flex;
	-mox-box-sizing: border-box;
	box-sizing: border-box;
	background-repeat: no-repeat;
	background-position: 2px 2px;
	white-space: nowrap;
	cursor: pointer;
	touch-action: none;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/browser/media/action.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,wBAAwB;CACxB,cAAc;CACd,eAAe;CACf,kBAAkB;CAClB,gBAAgB;CAChB,WAAW;CACX,cAAc;CACd;kBACiB;CACjB,WAAW;CACX,iBAAiB;CACjB,kBAAkB;CAClB,+CAA+C;CAC/C,oCAAoC;CACpC,uCAAuC;AACxC;;AAEA;CACC,kBAAkB;CAClB,MAAM;CACN,OAAO;CACP,WAAW;CACX,YAAY;CACZ,UAAU,EAAE,8CAA8C;CAC1D,WAAW;CACX,oBAAoB,EAAE,yBAAyB;CAC/C,6BAA6B,EAAE,iEAAiE;CAChG,6BAA6B;CAC7B,8BAA8B;CAC9B,8BAA8B;AAC/B;;AAEA;CACC,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;CACrB,uBAAuB;CACvB,4BAA4B;AAC7B;;AAEA;;;GAGG;;AAEH;CACC,uBAAuB;AACxB;;AAEA;CACC,iBAAiB;AAClB;AACA,8CAA8C;;AAE9C;CACC,aAAa;CACb,2BAA2B;CAC3B,sBAAsB;CACtB,0BAA0B;CAC1B,4BAA4B;CAC5B,4BAA4B;CAC5B,mBAAmB;CACnB,eAAe;CACf,kBAAkB;CAClB,WAAW;AACZ;;;AAGA;;CAEC,wDAAwD;CACxD,mEAAmE;AACpE;;AAEA;;CAEC,oBAAoB;CACpB,2BAA2B;CAC3B,yBAAyB;CACzB,wBAAwB;CACxB,sBAAsB;CACtB,qBAAqB;CACrB,iBAAiB;CACjB,kDAAkD;AACnD;;AAEA;CACC,+DAA+D;CAC/D,2BAA2B;CAC3B,mBAAmB;CACnB,WAAW;CACX,sBAAsB;CACtB,UAAU;CACV,kBAAkB;CAClB,wBAAwB;CACxB,gBAAgB;CAChB,aAAa;CACb,2BAA2B;CAC3B,sBAAsB;CACtB,4BAA4B;CAC5B,4BAA4B;CAC5B,mBAAmB;CACnB,eAAe;CACf,kBAAkB;AACnB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.codeActionMenuWidget {\n\tpadding: 8px 0px 8px 0px;\n\toverflow: auto;\n\tfont-size: 13px;\n\tborder-radius: 5px;\n\tmin-width: 160px;\n\tz-index: 40;\n\tdisplay: block;\n\t/* flex-direction: column;\n\tflex: 0 1 auto; */\n\twidth: 100%;\n\tborder-width: 0px;\n\tborder-color: none;\n\tbackground-color: var(--vscode-menu-background);\n\tcolor: var(--vscode-menu-foreground);\n\tbox-shadow: rgb(0,0,0, 16%) 0px 2px 8px;\n}\n\n.codeActionMenuWidget .monaco-list:not(.element-focused):focus:before {\n\tposition: absolute;\n\ttop: 0;\n\tleft: 0;\n\twidth: 100%;\n\theight: 100%;\n\tz-index: 5; /* make sure we are on top of the tree items */\n\tcontent: \"\";\n\tpointer-events: none; /* enable click through */\n\toutline: 0px solid !important; /* we still need to handle the empty tree or no focus item case */\n\toutline-width: 0px !important;\n\toutline-style: none !important;\n\toutline-offset: 0px !important;\n}\n\n.codeActionMenuWidget .monaco-list {\n\tuser-select: none;\n\t-webkit-user-select: none;\n\t-ms-user-select: none;\n\tborder: none !important;\n\tborder-width: 0px !important;\n}\n\n/* .codeActionMenuWidget .monaco-list:not(.element-focus) {\n\tborder: none !important;\n\tborder-width: 0px !important;\n} */\n\n.codeActionMenuWidget .monaco-list .monaco-scrollable-element .monaco-list-rows {\n\theight: 100% !important;\n}\n\n.codeActionMenuWidget .monaco-list .monaco-scrollable-element {\n\toverflow: visible;\n}\n/** Styles for each row in the list element **/\n\n.codeActionMenuWidget .monaco-list .monaco-list-row:not(.separator) {\n\tdisplay: flex;\n\t-mox-box-sizing: border-box;\n\tbox-sizing: border-box;\n\tpadding: 0px 26px 0px 26px;\n\tbackground-repeat: no-repeat;\n\tbackground-position: 2px 2px;\n\twhite-space: nowrap;\n\tcursor: pointer;\n\ttouch-action: none;\n\twidth: 100%;\n}\n\n\n.codeActionMenuWidget .monaco-list .monaco-list-row:hover:not(.option-disabled),\n.codeActionMenuWidget .monaco-list .moncao-list-row.focused:not(.option-disabled) {\n\tcolor: var(--vscode-menu-selectionForeground) !important;\n\tbackground-color: var(--vscode-menu-selectionBackground) !important;\n}\n\n.codeActionMenuWidget .monaco-list .option-disabled,\n.codeActionMenuWidget .monaco-list .option-disabled .focused {\n\tpointer-events: none;\n\t-webkit-touch-callout: none;\n\t-webkit-user-select: none;\n\t-khtml-user-select: none;\n\t-moz-user-select: none;\n\t-ms-user-select: none;\n\tuser-select: none;\n\tcolor: var(--vscode-disabledForeground) !important;\n}\n\n.codeActionMenuWidget .monaco-list .separator {\n\tborder-bottom: 1px solid var(--vscode-menu-separatorBackground);\n\tpadding-top: 0px !important;\n\t/* padding: 30px; */\n\twidth: 100%;\n\theight: 0px !important;\n\topacity: 1;\n\tfont-size: inherit;\n\tmargin: 5px 0 !important;\n\tborder-radius: 0;\n\tdisplay: flex;\n\t-mox-box-sizing: border-box;\n\tbox-sizing: border-box;\n\tbackground-repeat: no-repeat;\n\tbackground-position: 2px 2px;\n\twhite-space: nowrap;\n\tcursor: pointer;\n\ttouch-action: none;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 33295:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.IssueItem-module__IssueItem--GwmL3{background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:4px;padding:12px;margin-bottom:8px;cursor:pointer;transition:all .15s ease}.IssueItem-module__IssueItem--GwmL3:hover{background-color:var(--theme-color-bg-4);border-color:var(--theme-color-border-hover)}.IssueItem-module__IssueItem--GwmL3:active{transform:scale(0.99)}.IssueItem-module__Header--GpnYG{display:flex;justify-content:space-between;align-items:flex-start;gap:8px;margin-bottom:8px}.IssueItem-module__TitleRow--r5y1W{flex:1;display:flex;align-items:flex-start;gap:8px;min-width:0}.IssueItem-module__Number--iKNqU{color:var(--theme-color-fg-default-shy);font-size:12px;font-weight:600;flex-shrink:0}.IssueItem-module__Title--zxKhi{color:var(--theme-color-fg-default);font-size:13px;font-weight:500;flex:1;word-break:break-word}.IssueItem-module__StatusBadge--rdbH3{flex-shrink:0;padding:2px 8px;border-radius:12px;font-size:11px;font-weight:600;text-transform:capitalize}.IssueItem-module__StatusBadge--rdbH3[data-state=open]{background-color:rgba(46,160,67,.15);color:#2ea043}.IssueItem-module__StatusBadge--rdbH3[data-state=closed]{background-color:rgba(177,24,24,.15);color:#da3633}.IssueItem-module__Meta--yGcg_{display:flex;align-items:center;gap:12px;margin-bottom:8px}.IssueItem-module__Author--GydiC{color:var(--theme-color-fg-default-shy);font-size:12px}.IssueItem-module__Comments--x10Na{color:var(--theme-color-fg-default-shy);font-size:12px;display:flex;align-items:center;gap:4px}.IssueItem-module__Labels--OCgbh{display:flex;flex-wrap:wrap;gap:6px;align-items:center}.IssueItem-module__Label--t3wMS{padding:2px 8px;border-radius:12px;font-size:11px;font-weight:600;display:inline-block}.IssueItem-module__MoreLabels--vWwnJ{color:var(--theme-color-fg-default-shy);font-size:11px;font-weight:600}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssueItem.module.scss"],"names":[],"mappings":"AAIA,oCACE,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,YAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CAEA,0CACE,wCAAA,CACA,4CAAA,CAGF,2CACE,qBAAA,CAIJ,iCACE,YAAA,CACA,6BAAA,CACA,sBAAA,CACA,OAAA,CACA,iBAAA,CAGF,mCACE,MAAA,CACA,YAAA,CACA,sBAAA,CACA,OAAA,CACA,WAAA,CAGF,iCACE,uCAAA,CACA,cAAA,CACA,eAAA,CACA,aAAA,CAGF,gCACE,mCAAA,CACA,cAAA,CACA,eAAA,CACA,MAAA,CACA,qBAAA,CAGF,sCACE,aAAA,CACA,eAAA,CACA,kBAAA,CACA,cAAA,CACA,eAAA,CACA,yBAAA,CAEA,uDACE,oCAAA,CACA,aAAA,CAGF,yDACE,oCAAA,CACA,aAAA,CAIJ,+BACE,YAAA,CACA,kBAAA,CACA,QAAA,CACA,iBAAA,CAGF,iCACE,uCAAA,CACA,cAAA,CAGF,mCACE,uCAAA,CACA,cAAA,CACA,YAAA,CACA,kBAAA,CACA,OAAA,CAGF,iCACE,YAAA,CACA,cAAA,CACA,OAAA,CACA,kBAAA,CAGF,gCACE,eAAA,CACA,kBAAA,CACA,cAAA,CACA,eAAA,CACA,oBAAA,CAGF,qCACE,uCAAA,CACA,cAAA,CACA,eAAA","sourcesContent":["/**\n * IssueItem Styles\n */\n\n.IssueItem {\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  padding: 12px;\n  margin-bottom: 8px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    border-color: var(--theme-color-border-hover);\n  }\n\n  &:active {\n    transform: scale(0.99);\n  }\n}\n\n.Header {\n  display: flex;\n  justify-content: space-between;\n  align-items: flex-start;\n  gap: 8px;\n  margin-bottom: 8px;\n}\n\n.TitleRow {\n  flex: 1;\n  display: flex;\n  align-items: flex-start;\n  gap: 8px;\n  min-width: 0;\n}\n\n.Number {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 12px;\n  font-weight: 600;\n  flex-shrink: 0;\n}\n\n.Title {\n  color: var(--theme-color-fg-default);\n  font-size: 13px;\n  font-weight: 500;\n  flex: 1;\n  word-break: break-word;\n}\n\n.StatusBadge {\n  flex-shrink: 0;\n  padding: 2px 8px;\n  border-radius: 12px;\n  font-size: 11px;\n  font-weight: 600;\n  text-transform: capitalize;\n\n  &[data-state='open'] {\n    background-color: rgba(46, 160, 67, 0.15);\n    color: #2ea043;\n  }\n\n  &[data-state='closed'] {\n    background-color: rgba(177, 24, 24, 0.15);\n    color: #da3633;\n  }\n}\n\n.Meta {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  margin-bottom: 8px;\n}\n\n.Author {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 12px;\n}\n\n.Comments {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 12px;\n  display: flex;\n  align-items: center;\n  gap: 4px;\n}\n\n.Labels {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 6px;\n  align-items: center;\n}\n\n.Label {\n  padding: 2px 8px;\n  border-radius: 12px;\n  font-size: 11px;\n  font-weight: 600;\n  display: inline-block;\n}\n\n.MoreLabels {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 11px;\n  font-weight: 600;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"IssueItem": `IssueItem-module__IssueItem--GwmL3`,
	"Header": `IssueItem-module__Header--GpnYG`,
	"TitleRow": `IssueItem-module__TitleRow--r5y1W`,
	"Number": `IssueItem-module__Number--iKNqU`,
	"Title": `IssueItem-module__Title--zxKhi`,
	"StatusBadge": `IssueItem-module__StatusBadge--rdbH3`,
	"Meta": `IssueItem-module__Meta--yGcg_`,
	"Author": `IssueItem-module__Author--GydiC`,
	"Comments": `IssueItem-module__Comments--x10Na`,
	"Labels": `IssueItem-module__Labels--OCgbh`,
	"Label": `IssueItem-module__Label--t3wMS`,
	"MoreLabels": `IssueItem-module__MoreLabels--vWwnJ`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 33532:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   c: () => (/* binding */ reset)
/* harmony export */ });
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85869);

function resetModeToArgs(mode, ref) {
    switch (mode) {
        case 0 /* GitResetMode.Hard */:
            return ["reset", "--hard", ref];
        case 2 /* GitResetMode.Mixed */:
            return ["reset", ref];
        case 1 /* GitResetMode.Soft */:
            return ["reset", "--soft", ref];
        default:
            throw new Error(`Unknown reset mode: ${mode}`);
    }
}
/** Reset with the mode to the ref. */
async function reset(repositoryDir, mode, ref, additionalArgs = []) {
    const args = resetModeToArgs(mode, ref).concat(additionalArgs);
    await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)(args, repositoryDir, "reset");
    return true;
}


/***/ }),

/***/ 33609:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgTrash = function SvgTrash(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M9.88672 1.76318C9.28998 1.76318 8.71769 2.00024 8.29573 2.42219C7.87377 2.84415 7.63672 3.41645 7.63672 4.01318V4.76318H5.85693H3.88672C3.47251 4.76318 3.13672 5.09897 3.13672 5.51318C3.13672 5.9274 3.47251 6.26318 3.88672 6.26318H5.10693V19.7632C5.10693 20.1442 5.24726 20.5196 5.51219 20.8044C5.77882 21.091 6.15252 21.2632 6.55468 21.2632H17.7186C18.1208 21.2632 18.4945 21.091 18.7611 20.8044C19.026 20.5196 19.1664 20.1442 19.1664 19.7632V6.26318H20.3867C20.8009 6.26318 21.1367 5.9274 21.1367 5.51318C21.1367 5.09897 20.8009 4.76318 20.3867 4.76318H18.4164H16.6367V4.01318C16.6367 3.41645 16.3997 2.84415 15.9777 2.42219C15.5558 2.00024 14.9835 1.76318 14.3867 1.76318H9.88672ZM15.1367 4.76318V4.01318C15.1367 3.81427 15.0577 3.62351 14.917 3.48285C14.7764 3.3422 14.5856 3.26318 14.3867 3.26318H9.88672C9.68781 3.26318 9.49704 3.3422 9.35639 3.48285C9.21574 3.62351 9.13672 3.81427 9.13672 4.01318V4.76318H15.1367ZM8.38672 6.26318H6.60693V19.7632H17.6664V6.26318H15.8867H8.38672ZM9.88672 9.26318C10.3009 9.26318 10.6367 9.59897 10.6367 10.0132V16.0132C10.6367 16.4274 10.3009 16.7632 9.88672 16.7632C9.47251 16.7632 9.13672 16.4274 9.13672 16.0132V10.0132C9.13672 9.59897 9.47251 9.26318 9.88672 9.26318ZM15.1367 16.0132V10.0132C15.1367 9.59897 14.8009 9.26318 14.3867 9.26318C13.9725 9.26318 13.6367 9.59897 13.6367 10.0132V16.0132C13.6367 16.4274 13.9725 16.7632 14.3867 16.7632C14.8009 16.7632 15.1367 16.4274 15.1367 16.0132Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgTrash);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "a47533ffb1d6f796a28d798e9ab1836f.svg");

/***/ }),

/***/ 33696:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* unused harmony export ReactComponent */
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = (/* unused pure expression or super */ null && (["title", "titleId"]));
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgHomeNodegraph = function SvgHomeNodegraph(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/React.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/React.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/React.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M11.1253 3.25613C11.4016 3.00376 11.7624 2.86382 12.1367 2.86382C12.511 2.86382 12.8718 3.00376 13.1482 3.25613C13.1485 3.25645 13.1489 3.25677 13.1492 3.25709L20.6474 10.071L20.6579 10.0808C20.8061 10.2208 20.9249 10.389 21.0071 10.5756C21.0893 10.7621 21.1333 10.9632 21.1366 11.1671L21.1368 11.1792L21.1367 19.8511C21.1367 20.2489 20.9787 20.6304 20.6974 20.9117C20.4161 21.193 20.0345 21.3511 19.6367 21.3511H15.1367C14.7389 21.3511 14.3574 21.193 14.0761 20.9117C13.7948 20.6304 13.6367 20.2489 13.6367 19.8511V15.3511L10.6367 15.3511V19.8511C10.6367 20.2489 10.4787 20.6304 10.1974 20.9117C9.91607 21.193 9.53454 21.3511 9.13672 21.3511H4.63672C4.2389 21.3511 3.85736 21.193 3.57606 20.9117C3.29475 20.6304 3.13672 20.2489 3.13672 19.8511V11.1671C3.14002 10.9632 3.18417 10.7621 3.26638 10.5756C3.34859 10.389 3.46729 10.2208 3.61551 10.0808L3.62607 10.071L11.1242 3.25709C11.1246 3.25677 11.1249 3.25645 11.1253 3.25613ZM4.64382 11.173L12.1349 4.3655L12.1367 4.36382L12.1386 4.3655L19.6296 11.173C19.6316 11.1752 19.6332 11.1777 19.6344 11.1804C19.6357 11.1833 19.6365 11.1863 19.6367 11.1894V19.8511H15.1367V15.3511C15.1367 14.9533 14.9787 14.5717 14.6974 14.2904C14.4161 14.0091 14.0345 13.8511 13.6367 13.8511H10.6367C10.2389 13.8511 9.85736 14.0091 9.57606 14.2904C9.29475 14.5717 9.13672 14.9533 9.13672 15.3511V19.8511H4.63672V11.1894C4.63698 11.1863 4.63775 11.1833 4.639 11.1804C4.64021 11.1777 4.64184 11.1752 4.64382 11.173Z",
    fill: "#cfd5de"
  })));
};
var ForwardRef = /*#__PURE__*/(/* unused pure expression or super */ null && (forwardRef(SvgHomeNodegraph)));

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "db7468c47af3418aec6c51e45c60e0d6.svg");

/***/ }),

/***/ 33705:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCloudCheck = function SvgCloudCheck(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M16.5434 6.17798C15.234 5.91753 13.8769 6.0512 12.6434 6.5621C11.41 7.07299 10.3558 7.93815 9.61414 9.04818C8.87244 10.1582 8.47656 11.4633 8.47656 12.7983C8.47656 13.2125 8.14078 13.5483 7.72656 13.5483C7.31235 13.5483 6.97656 13.2125 6.97656 12.7983C6.97656 12.0369 7.08192 11.2835 7.28642 10.5585C7.18344 10.5517 7.0802 10.5482 6.97684 10.5483H6.97656C5.78309 10.5483 4.6385 11.0224 3.79458 11.8663C2.95067 12.7102 2.47656 13.8548 2.47656 15.0483C2.47656 16.2418 2.95067 17.3863 3.79458 18.2303C4.6385 19.0742 5.78309 19.5483 6.97656 19.5483H15.2266C16.5616 19.5483 17.8666 19.1524 18.9767 18.4107C20.0867 17.669 20.9519 16.6148 21.4627 15.3814C21.9736 14.148 22.1073 12.7908 21.8469 11.4814C21.5864 10.1721 20.9435 8.96932 19.9995 8.02531C19.0555 7.08131 17.8528 6.43843 16.5434 6.17798ZM7.84692 9.10999C8.00079 8.80213 8.17432 8.5031 8.36694 8.21483C9.27346 6.85812 10.5619 5.8007 12.0694 5.17628C13.5769 4.55185 15.2357 4.38848 16.8361 4.7068C18.4364 5.02513 19.9064 5.81087 21.0602 6.96465C22.214 8.11843 22.9997 9.58844 23.318 11.1888C23.6364 12.7891 23.473 14.4479 22.8486 15.9554C22.2241 17.4629 21.1667 18.7514 19.81 19.6579C18.4533 20.5644 16.8583 21.0483 15.2266 21.0483H6.97656C5.38526 21.0483 3.85914 20.4161 2.73392 19.2909C1.6087 18.1657 0.976562 16.6396 0.976562 15.0483C0.976562 13.457 1.6087 11.9309 2.73392 10.8056C3.85907 9.68049 5.38508 9.04836 6.97628 9.04828M7.84692 9.10999C7.55889 9.06885 7.26804 9.04819 6.97656 9.04828L7.84692 9.10999Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M18.0804 11.0897C18.3733 11.3826 18.3733 11.8575 18.0804 12.1504L14.2036 16.0272C14.0629 16.1678 13.8722 16.2468 13.6733 16.2468C13.4744 16.2468 13.2836 16.1678 13.1429 16.0272L11.2045 14.0888C10.9116 13.7959 10.9116 13.321 11.2045 13.0281C11.4974 12.7352 11.9723 12.7352 12.2652 13.0281L13.6733 14.4362L17.0197 11.0897C17.3126 10.7968 17.7875 10.7968 18.0804 11.0897Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCloudCheck);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "5e5e66315d12cca5929903769651eb49.svg");

/***/ }),

/***/ 33757:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
if (process.type === 'browser')
    throw new Error(`"@electron/remote" cannot be required in the browser process. Instead require("@electron/remote/main").`);
__exportStar(__webpack_require__(99107), exports);


/***/ }),

/***/ 33874:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .view-ruler {
	position: absolute;
	top: 0;
}`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/rulers/rulers.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kBAAkB;CAClB,MAAM;AACP","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .view-ruler {\n\tposition: absolute;\n\ttop: 0;\n}"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 33994:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor.vs .dnd-target,
.monaco-editor.hc-light .dnd-target {
	border-right: 2px dotted black;
	color: white; /* opposite of black */
}
.monaco-editor.vs-dark .dnd-target {
	border-right: 2px dotted #AEAFAD;
	color: #51504f; /* opposite of #AEAFAD */
}
.monaco-editor.hc-black .dnd-target {
	border-right: 2px dotted #fff;
	color: #000; /* opposite of #fff */
}

.monaco-editor.mouse-default .view-lines,
.monaco-editor.vs-dark.mac.mouse-default .view-lines,
.monaco-editor.hc-black.mac.mouse-default .view-lines,
.monaco-editor.hc-light.mac.mouse-default .view-lines {
	cursor: default;
}
.monaco-editor.mouse-copy .view-lines,
.monaco-editor.vs-dark.mac.mouse-copy .view-lines,
.monaco-editor.hc-black.mac.mouse-copy .view-lines,
.monaco-editor.hc-light.mac.mouse-copy .view-lines {
	cursor: copy;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/dnd/browser/dnd.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;;CAEC,8BAA8B;CAC9B,YAAY,EAAE,sBAAsB;AACrC;AACA;CACC,gCAAgC;CAChC,cAAc,EAAE,wBAAwB;AACzC;AACA;CACC,6BAA6B;CAC7B,WAAW,EAAE,qBAAqB;AACnC;;AAEA;;;;CAIC,eAAe;AAChB;AACA;;;;CAIC,YAAY;AACb","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor.vs .dnd-target,\n.monaco-editor.hc-light .dnd-target {\n\tborder-right: 2px dotted black;\n\tcolor: white; /* opposite of black */\n}\n.monaco-editor.vs-dark .dnd-target {\n\tborder-right: 2px dotted #AEAFAD;\n\tcolor: #51504f; /* opposite of #AEAFAD */\n}\n.monaco-editor.hc-black .dnd-target {\n\tborder-right: 2px dotted #fff;\n\tcolor: #000; /* opposite of #fff */\n}\n\n.monaco-editor.mouse-default .view-lines,\n.monaco-editor.vs-dark.mac.mouse-default .view-lines,\n.monaco-editor.hc-black.mac.mouse-default .view-lines,\n.monaco-editor.hc-light.mac.mouse-default .view-lines {\n\tcursor: default;\n}\n.monaco-editor.mouse-copy .view-lines,\n.monaco-editor.vs-dark.mac.mouse-copy .view-lines,\n.monaco-editor.hc-black.mac.mouse-copy .view-lines,\n.monaco-editor.hc-light.mac.mouse-copy .view-lines {\n\tcursor: copy;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 34120:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   W: () => (/* binding */ NotifyType),
/* harmony export */   g: () => (/* binding */ PageType)
/* harmony export */ });
var PageType;
(function (PageType) {
    PageType["Static"] = "static-page";
    PageType["Dynamic"] = "dynamic-page";
})(PageType || (PageType = {}));
var NotifyType;
(function (NotifyType) {
    NotifyType["Notice"] = "notice";
    NotifyType["Success"] = "success";
    NotifyType["Error"] = "error";
})(NotifyType || (NotifyType = {}));


/***/ }),

/***/ 34276:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPauseCircle = function SvgPauseCircle(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.1369 4.63657C8.07016 4.63657 4.77344 7.93329 4.77344 12C4.77344 16.0667 8.07016 19.3634 12.1369 19.3634C16.2036 19.3634 19.5003 16.0667 19.5003 12C19.5003 7.93329 16.2036 4.63657 12.1369 4.63657ZM3.27344 12C3.27344 7.10486 7.24173 3.13657 12.1369 3.13657C17.032 3.13657 21.0003 7.10486 21.0003 12C21.0003 16.8951 17.032 20.8634 12.1369 20.8634C7.24173 20.8634 3.27344 16.8951 3.27344 12Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M14.2883 9.24828H9.98477C9.65339 9.24828 9.38477 9.51691 9.38477 9.84828V14.1518C9.38477 14.4832 9.6534 14.7518 9.98477 14.7518H14.2883C14.6197 14.7518 14.8883 14.4832 14.8883 14.1518V9.84828C14.8883 9.51691 14.6197 9.24828 14.2883 9.24828Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPauseCircle);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "e5ab71392886267ecd51fadd7ef35854.svg");

/***/ }),

/***/ 34523:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.NodeGraphComponentTrail-module__Root--Lqxh1{display:flex;box-shadow:0 0 15px 0 var(--theme-color-bg-1-transparent-2)}.NodeGraphComponentTrail-module__HistoryControls--zCK7N{display:flex;background-color:var(--theme-color-bg-2);align-items:center;border-right:1px solid var(--theme-color-bg-1)}.NodeGraphComponentTrail-module__HistoryButton--QVlwM{width:36px;height:36px;display:flex;align-items:center;justify-content:center}.NodeGraphComponentTrail-module__TrailContainer--RPfha{align-self:stretch;position:relative;overflow:hidden}.NodeGraphComponentTrail-module__TrailContainer--RPfha:before,.NodeGraphComponentTrail-module__TrailContainer--RPfha:after{content:"";position:absolute;height:80%;box-shadow:0 0 10px 10px var(--theme-color-bg-2),0 0 10px 0px var(--theme-color-bg-2);width:50px;border-radius:50%;top:10%}.NodeGraphComponentTrail-module__TrailContainer--RPfha:before{left:-50px}.NodeGraphComponentTrail-module__TrailContainer--RPfha:after{right:-50px}.NodeGraphComponentTrail-module__Trail--bfbN2{display:flex;align-items:stretch;overflow-y:hidden;overflow-x:overlay;scroll-behavior:smooth;z-index:0}.NodeGraphComponentTrail-module__Trail--bfbN2>*:last-child{border:none}.NodeGraphComponentTrail-module__ItemTrigger--AmDoi{flex-shrink:0;flex-grow:1}.NodeGraphComponentTrail-module__Item--uMIhJ{padding:12px 18px 12px 12px;background-color:var(--theme-color-bg-2);display:flex;align-items:center;align-self:stretch;flex-shrink:0;flex-grow:1;border-right:1px solid var(--theme-color-bg-1)}.NodeGraphComponentTrail-module__Item--uMIhJ.NodeGraphComponentTrail-module__is-component--w9pu6{cursor:pointer}.NodeGraphComponentTrail-module__Item--uMIhJ.NodeGraphComponentTrail-module__is-current--SY7SD{background-color:var(--theme-color-bg-4);position:relative;z-index:1}.NodeGraphComponentTrail-module__Label--M0eZf{flex-shrink:0;flex-grow:1}.NodeGraphComponentTrail-module__Item--uMIhJ.NodeGraphComponentTrail-module__is-current--SY7SD .NodeGraphComponentTrail-module__Label--M0eZf,.NodeGraphComponentTrail-module__Item--uMIhJ.NodeGraphComponentTrail-module__is-component--w9pu6:hover .NodeGraphComponentTrail-module__Label--M0eZf{color:var(--theme-color-fg-highlight)}.NodeGraphComponentTrail-module__Icon--aIBck{margin-right:4px;margin-top:-2px;margin-bottom:-2px;flex-shrink:0}.NodeGraphComponentTrail-module__Item--uMIhJ:not(.NodeGraphComponentTrail-module__is-current--SY7SD) .NodeGraphComponentTrail-module__Icon--aIBck path{fill:var(--theme-color-fg-default)}.NodeGraphComponentTrail-module__Item--uMIhJ.NodeGraphComponentTrail-module__is-current--SY7SD .NodeGraphComponentTrail-module__Icon--aIBck path{fill:var(--theme-color-fg-highlight)}.NodeGraphComponentTrail-module__Item--uMIhJ:not(.NodeGraphComponentTrail-module__is-folder--kVfNF):hover .NodeGraphComponentTrail-module__Icon--aIBck path{fill:var(--theme-color-fg-highlight)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/NodeGraphComponentTrail/NodeGraphComponentTrail.module.scss"],"names":[],"mappings":"AAAA,6CACE,YAAA,CACA,2DAAA,CAGF,wDACE,YAAA,CACA,wCAAA,CACA,kBAAA,CACA,8CAAA,CAGF,sDACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CAGF,uDACE,kBAAA,CACA,iBAAA,CACA,eAAA,CAEA,2HAEE,UAAA,CACA,iBAAA,CACA,UAAA,CACA,qFAAA,CACA,UAAA,CACA,iBAAA,CACA,OAAA,CAGF,8DACE,UAAA,CAGF,6DACE,WAAA,CAIJ,8CACE,YAAA,CACA,mBAAA,CACA,iBAAA,CACA,kBAAA,CACA,sBAAA,CACA,SAAA,CAEA,2DACE,WAAA,CAIJ,oDACE,aAAA,CACA,WAAA,CAGF,6CACE,2BAAA,CACA,wCAAA,CACA,YAAA,CACA,kBAAA,CACA,kBAAA,CACA,aAAA,CACA,WAAA,CACA,8CAAA,CAEA,iGACE,cAAA,CAGF,+FACE,wCAAA,CACA,iBAAA,CACA,SAAA,CAIJ,8CACE,aAAA,CACA,WAAA,CAEA,kSAEE,qCAAA,CAIJ,6CACE,gBAAA,CACA,eAAA,CACA,kBAAA,CACA,aAAA,CAGE,uJACE,kCAAA,CAKF,iJACE,oCAAA,CAKF,4JACE,oCAAA","sourcesContent":[".Root {\n  display: flex;\n  box-shadow: 0 0 15px 0 var(--theme-color-bg-1-transparent-2);\n}\n\n.HistoryControls {\n  display: flex;\n  background-color: var(--theme-color-bg-2);\n  align-items: center;\n  border-right: 1px solid var(--theme-color-bg-1);\n}\n\n.HistoryButton {\n  width: 36px;\n  height: 36px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.TrailContainer {\n  align-self: stretch;\n  position: relative;\n  overflow: hidden;\n\n  &:before,\n  &:after {\n    content: '';\n    position: absolute;\n    height: 80%;\n    box-shadow: 0 0 10px 10px var(--theme-color-bg-2), 0 0 10px 0px var(--theme-color-bg-2);\n    width: 50px;\n    border-radius: 50%;\n    top: 10%;\n  }\n\n  &:before {\n    left: -50px;\n  }\n\n  &:after {\n    right: -50px;\n  }\n}\n\n.Trail {\n  display: flex;\n  align-items: stretch;\n  overflow-y: hidden;\n  overflow-x: overlay;\n  scroll-behavior: smooth;\n  z-index: 0;\n\n  > *:last-child {\n    border: none;\n  }\n}\n\n.ItemTrigger {\n  flex-shrink: 0;\n  flex-grow: 1;\n}\n\n.Item {\n  padding: 12px 18px 12px 12px;\n  background-color: var(--theme-color-bg-2);\n  display: flex;\n  align-items: center;\n  align-self: stretch;\n  flex-shrink: 0;\n  flex-grow: 1;\n  border-right: 1px solid var(--theme-color-bg-1);\n\n  &.is-component {\n    cursor: pointer;\n  }\n\n  &.is-current {\n    background-color: var(--theme-color-bg-4);\n    position: relative;\n    z-index: 1;\n  }\n}\n\n.Label {\n  flex-shrink: 0;\n  flex-grow: 1;\n\n  .Item.is-current &,\n  .Item.is-component:hover & {\n    color: var(--theme-color-fg-highlight);\n  }\n}\n\n.Icon {\n  margin-right: 4px;\n  margin-top: -2px;\n  margin-bottom: -2px;\n  flex-shrink: 0;\n\n  .Item:not(.is-current) & {\n    path {\n      fill: var(--theme-color-fg-default);\n    }\n  }\n\n  .Item.is-current & {\n    path {\n      fill: var(--theme-color-fg-highlight);\n    }\n  }\n\n  .Item:not(.is-folder):hover & {\n    path {\n      fill: var(--theme-color-fg-highlight);\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `NodeGraphComponentTrail-module__Root--Lqxh1`,
	"HistoryControls": `NodeGraphComponentTrail-module__HistoryControls--zCK7N`,
	"HistoryButton": `NodeGraphComponentTrail-module__HistoryButton--QVlwM`,
	"TrailContainer": `NodeGraphComponentTrail-module__TrailContainer--RPfha`,
	"Trail": `NodeGraphComponentTrail-module__Trail--bfbN2`,
	"ItemTrigger": `NodeGraphComponentTrail-module__ItemTrigger--AmDoi`,
	"Item": `NodeGraphComponentTrail-module__Item--uMIhJ`,
	"is-component": `NodeGraphComponentTrail-module__is-component--w9pu6`,
	"is-current": `NodeGraphComponentTrail-module__is-current--SY7SD`,
	"Label": `NodeGraphComponentTrail-module__Label--M0eZf`,
	"Icon": `NodeGraphComponentTrail-module__Icon--aIBck`,
	"is-folder": `NodeGraphComponentTrail-module__is-folder--kVfNF`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 34676:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   k: () => (/* binding */ useDragHandler)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

function useDragHandler(options) {
    const [dragging, setDragging] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [dragState, setDragState] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({
        dragStartWidth: 0,
        dragStartHeight: 0,
        dragStartX: 0,
        dragStartY: 0
    });
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        function drag(event) {
            const deltaX = event.pageX - dragState.dragStartX;
            const deltaY = event.pageY - dragState.dragStartY;
            const newWidth = Math.max(options.minWidth, dragState.dragStartWidth + deltaX);
            const newHeight = Math.max(options.minHeight, dragState.dragStartHeight + deltaY);
            setDragState({
                dragStartX: event.pageX,
                dragStartY: event.pageY,
                dragStartWidth: newWidth,
                dragStartHeight: newHeight
            });
            options.onDrag && options.onDrag(newWidth, newHeight);
            return false;
        }
        function endDrag(_event) {
            setDragging(false);
            document.removeEventListener('mousemove', drag, true);
            document.removeEventListener('mouseup', endDrag, true);
            options.onEndDrag && options.onEndDrag();
            return false;
        }
        if (dragging) {
            document.addEventListener('mousemove', drag, true);
            document.addEventListener('mouseup', endDrag, true);
        }
        return function () {
            document.removeEventListener('mousemove', drag, true);
            document.removeEventListener('mouseup', endDrag, true);
        };
    }, [dragging]);
    const startDrag = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((event) => {
        setDragging(true);
        setDragState({
            dragStartX: event.pageX,
            dragStartY: event.pageY,
            dragStartWidth: options.root.current.offsetWidth,
            dragStartHeight: options.root.current.offsetHeight
        });
        options.onStartDrag && options.onStartDrag();
        return false;
    }, []);
    return {
        startDrag
    };
}


/***/ }),

/***/ 34741:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.CodeHistoryDropdown-module__Root--xXbMi{display:flex;flex-direction:column;max-height:500px}.CodeHistoryDropdown-module__Header--vLZ1L{display:flex;align-items:center;justify-content:space-between;padding:16px;border-bottom:1px solid var(--theme-color-border-default)}.CodeHistoryDropdown-module__Title--wnrlL{margin:0;font-size:15px;font-weight:600;color:var(--theme-color-fg-default)}.CodeHistoryDropdown-module__CloseButton--MRKK_{background:none;border:none;color:var(--theme-color-fg-default-shy);font-size:24px;line-height:1;cursor:pointer;padding:0;width:24px;height:24px;display:flex;align-items:center;justify-content:center;border-radius:4px;transition:all .15s ease}.CodeHistoryDropdown-module__CloseButton--MRKK_:hover{background:var(--theme-color-bg-3);color:var(--theme-color-fg-default)}.CodeHistoryDropdown-module__List--r0BEp{overflow-y:auto;max-height:400px;padding:8px}.CodeHistoryDropdown-module__Item--X_ETd{padding:12px;border-radius:6px;margin-bottom:4px;border:1px solid rgba(0,0,0,0);transition:all .15s ease}.CodeHistoryDropdown-module__Item--X_ETd:hover{background:var(--theme-color-bg-2);border-color:var(--theme-color-border-default)}.CodeHistoryDropdown-module__ItemCurrent--Nrbv4{background:var(--theme-color-primary);color:#fff;opacity:.9}.CodeHistoryDropdown-module__ItemCurrent--Nrbv4:hover{background:var(--theme-color-primary);opacity:1}.CodeHistoryDropdown-module__ItemCurrent--Nrbv4 .CodeHistoryDropdown-module__ItemIcon--M3yIn{color:#fff}.CodeHistoryDropdown-module__ItemCurrent--Nrbv4 .CodeHistoryDropdown-module__ItemTime--rGg90{color:#fff;font-weight:600}.CodeHistoryDropdown-module__ItemHeader--Rc3mA{display:flex;align-items:center;gap:8px;margin-bottom:4px}.CodeHistoryDropdown-module__ItemIcon--M3yIn{font-size:16px;width:20px;text-align:center;color:var(--theme-color-fg-default-shy)}.CodeHistoryDropdown-module__ItemTime--rGg90{font-size:13px;font-weight:500;color:var(--theme-color-fg-default)}.CodeHistoryDropdown-module__ItemSummary--ei0UC{font-size:12px;color:var(--theme-color-fg-default-shy);margin-left:28px;margin-bottom:8px}.CodeHistoryDropdown-module__ItemActions--x8ASU{display:flex;gap:8px;margin-left:28px}.CodeHistoryDropdown-module__PreviewButton--QkcnO{padding:4px 12px;background:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:4px;color:var(--theme-color-fg-default);font-size:12px;font-weight:500;cursor:pointer;transition:all .15s ease}.CodeHistoryDropdown-module__PreviewButton--QkcnO:hover{background:var(--theme-color-primary);border-color:var(--theme-color-primary);color:#fff}.CodeHistoryDropdown-module__Empty--I88ar{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:48px 24px;text-align:center}.CodeHistoryDropdown-module__EmptyIcon--yAy07{color:var(--theme-color-fg-default-shy);opacity:.5;margin-bottom:16px}.CodeHistoryDropdown-module__EmptyText--MR5VM{margin:0 0 8px 0;font-size:15px;font-weight:600;color:var(--theme-color-fg-default)}.CodeHistoryDropdown-module__EmptyHint--bDxL4{margin:0;font-size:13px;color:var(--theme-color-fg-default-shy);max-width:280px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryDropdown.module.scss"],"names":[],"mappings":"AAIA,yCACE,YAAA,CACA,qBAAA,CACA,gBAAA,CAGF,2CACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,YAAA,CACA,yDAAA,CAGF,0CACE,QAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,gDACE,eAAA,CACA,WAAA,CACA,uCAAA,CACA,cAAA,CACA,aAAA,CACA,cAAA,CACA,SAAA,CACA,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,wBAAA,CAEA,sDACE,kCAAA,CACA,mCAAA,CAIJ,yCACE,eAAA,CACA,gBAAA,CACA,WAAA,CAGF,yCACE,YAAA,CACA,iBAAA,CACA,iBAAA,CACA,8BAAA,CACA,wBAAA,CAEA,+CACE,kCAAA,CACA,8CAAA,CAIJ,gDACE,qCAAA,CACA,UAAA,CACA,UAAA,CAEA,sDACE,qCAAA,CACA,SAAA,CAGF,6FACE,UAAA,CAGF,6FACE,UAAA,CACA,eAAA,CAIJ,+CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,iBAAA,CAGF,6CACE,cAAA,CACA,UAAA,CACA,iBAAA,CACA,uCAAA,CAGF,6CACE,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,gDACE,cAAA,CACA,uCAAA,CACA,gBAAA,CACA,iBAAA,CAGF,gDACE,YAAA,CACA,OAAA,CACA,gBAAA,CAGF,kDACE,gBAAA,CACA,kCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,wBAAA,CAEA,wDACE,qCAAA,CACA,uCAAA,CACA,UAAA,CAKJ,0CACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,iBAAA,CAGF,8CACE,uCAAA,CACA,UAAA,CACA,kBAAA,CAGF,8CACE,gBAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,8CACE,QAAA,CACA,cAAA,CACA,uCAAA,CACA,eAAA","sourcesContent":["/**\n * CodeHistoryDropdown Styles\n */\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  max-height: 500px;\n}\n\n.Header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 16px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.Title {\n  margin: 0;\n  font-size: 15px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n}\n\n.CloseButton {\n  background: none;\n  border: none;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 24px;\n  line-height: 1;\n  cursor: pointer;\n  padding: 0;\n  width: 24px;\n  height: 24px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  border-radius: 4px;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background: var(--theme-color-bg-3);\n    color: var(--theme-color-fg-default);\n  }\n}\n\n.List {\n  overflow-y: auto;\n  max-height: 400px;\n  padding: 8px;\n}\n\n.Item {\n  padding: 12px;\n  border-radius: 6px;\n  margin-bottom: 4px;\n  border: 1px solid transparent;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background: var(--theme-color-bg-2);\n    border-color: var(--theme-color-border-default);\n  }\n}\n\n.ItemCurrent {\n  background: var(--theme-color-primary);\n  color: white;\n  opacity: 0.9;\n\n  &:hover {\n    background: var(--theme-color-primary);\n    opacity: 1;\n  }\n\n  .ItemIcon {\n    color: white;\n  }\n\n  .ItemTime {\n    color: white;\n    font-weight: 600;\n  }\n}\n\n.ItemHeader {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin-bottom: 4px;\n}\n\n.ItemIcon {\n  font-size: 16px;\n  width: 20px;\n  text-align: center;\n  color: var(--theme-color-fg-default-shy);\n}\n\n.ItemTime {\n  font-size: 13px;\n  font-weight: 500;\n  color: var(--theme-color-fg-default);\n}\n\n.ItemSummary {\n  font-size: 12px;\n  color: var(--theme-color-fg-default-shy);\n  margin-left: 28px;\n  margin-bottom: 8px;\n}\n\n.ItemActions {\n  display: flex;\n  gap: 8px;\n  margin-left: 28px;\n}\n\n.PreviewButton {\n  padding: 4px 12px;\n  background: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background: var(--theme-color-primary);\n    border-color: var(--theme-color-primary);\n    color: white;\n  }\n}\n\n/* Empty state */\n.Empty {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  padding: 48px 24px;\n  text-align: center;\n}\n\n.EmptyIcon {\n  color: var(--theme-color-fg-default-shy);\n  opacity: 0.5;\n  margin-bottom: 16px;\n}\n\n.EmptyText {\n  margin: 0 0 8px 0;\n  font-size: 15px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n}\n\n.EmptyHint {\n  margin: 0;\n  font-size: 13px;\n  color: var(--theme-color-fg-default-shy);\n  max-width: 280px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `CodeHistoryDropdown-module__Root--xXbMi`,
	"Header": `CodeHistoryDropdown-module__Header--vLZ1L`,
	"Title": `CodeHistoryDropdown-module__Title--wnrlL`,
	"CloseButton": `CodeHistoryDropdown-module__CloseButton--MRKK_`,
	"List": `CodeHistoryDropdown-module__List--r0BEp`,
	"Item": `CodeHistoryDropdown-module__Item--X_ETd`,
	"ItemCurrent": `CodeHistoryDropdown-module__ItemCurrent--Nrbv4`,
	"ItemIcon": `CodeHistoryDropdown-module__ItemIcon--M3yIn`,
	"ItemTime": `CodeHistoryDropdown-module__ItemTime--rGg90`,
	"ItemHeader": `CodeHistoryDropdown-module__ItemHeader--Rc3mA`,
	"ItemSummary": `CodeHistoryDropdown-module__ItemSummary--ei0UC`,
	"ItemActions": `CodeHistoryDropdown-module__ItemActions--x8ASU`,
	"PreviewButton": `CodeHistoryDropdown-module__PreviewButton--QkcnO`,
	"Empty": `CodeHistoryDropdown-module__Empty--I88ar`,
	"EmptyIcon": `CodeHistoryDropdown-module__EmptyIcon--yAy07`,
	"EmptyText": `CodeHistoryDropdown-module__EmptyText--MR5VM`,
	"EmptyHint": `CodeHistoryDropdown-module__EmptyHint--bDxL4`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 35062:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .glyph-margin {
	position: absolute;
	top: 0;
}

/*
	Keeping name short for faster parsing.
	cgmr = core glyph margin rendering (div)
*/
.monaco-editor .margin-view-overlays .cgmr {
	position: absolute;
	display: flex;
	align-items: center;
	justify-content: center;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/glyphMargin/glyphMargin.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kBAAkB;CAClB,MAAM;AACP;;AAEA;;;CAGC;AACD;CACC,kBAAkB;CAClB,aAAa;CACb,mBAAmB;CACnB,uBAAuB;AACxB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .glyph-margin {\n\tposition: absolute;\n\ttop: 0;\n}\n\n/*\n\tKeeping name short for faster parsing.\n\tcgmr = core glyph margin rendering (div)\n*/\n.monaco-editor .margin-view-overlays .cgmr {\n\tposition: absolute;\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 35203:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgArrowDown = function SvgArrowDown(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.7612 21.2292C12.8512 21.1892 12.9312 21.1392 13.0012 21.0692L19.7512 14.3192C20.0412 14.0292 20.0412 13.5492 19.7512 13.2592C19.4612 12.9692 18.9812 12.9692 18.6912 13.2592L13.2212 18.7292L13.2213 4.03918C13.2213 3.62918 12.8812 3.28918 12.4713 3.28918C12.0613 3.28918 11.7212 3.62918 11.7212 4.03918L11.7212 18.7292L6.25125 13.2592C5.96125 12.9692 5.48125 12.9692 5.19125 13.2592C5.04125 13.4092 4.97125 13.5992 4.97125 13.7892C4.97125 13.9792 5.04125 14.1692 5.19125 14.3192L11.9412 21.0692C12.0112 21.1392 12.0912 21.1892 12.1812 21.2292C12.3612 21.3092 12.5712 21.3092 12.7512 21.2292L12.7612 21.2292Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgArrowDown);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "3434541760db52ee483a8385591f5eae.svg");

/***/ }),

/***/ 35242:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.HighlightedConnection-module__highlightedConnection--nzyKW{position:absolute;pointer-events:none;overflow:visible;z-index:999}.HighlightedConnection-module__highlightedConnection--nzyKW .HighlightedConnection-module__pulsePath--CAoGC{animation:HighlightedConnection-module__connection-pulse--g8Ckm 1.5s ease-in-out infinite}.HighlightedConnection-module__glow--xEuuh{animation:HighlightedConnection-module__glow-breathe--CTQGs 2s ease-in-out infinite}@keyframes HighlightedConnection-module__glow-breathe--CTQGs{0%,100%{opacity:.8}50%{opacity:1}}@keyframes HighlightedConnection-module__connection-pulse--g8Ckm{0%,100%{stroke-dashoffset:0;opacity:.8}50%{stroke-dashoffset:10;opacity:1}}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightedConnection.module.scss"],"names":[],"mappings":"AAMA,4DACE,iBAAA,CACA,mBAAA,CACA,gBAAA,CACA,WAAA,CAGA,4GACE,yFAAA,CAWJ,2CAEE,mFAAA,CASF,6DACE,QAEE,UAAA,CAEF,IACE,SAAA,CAAA,CAKJ,iEACE,QAEE,mBAAA,CACA,UAAA,CAEF,IACE,oBAAA,CACA,SAAA,CAAA","sourcesContent":["/**\n * HighlightedConnection styles\n *\n * Styles for connection path highlight overlays with different visual effects.\n */\n\n.highlightedConnection {\n  position: absolute;\n  pointer-events: none;\n  overflow: visible;\n  z-index: 999; // Below nodes (1000) but above canvas\n\n  // Pulse path - animated overlay for pulse effect\n  .pulsePath {\n    animation: connection-pulse 1.5s ease-in-out infinite;\n  }\n}\n\n// Solid style - simple static path\n.solid {\n  // Base styles applied from .highlightedConnection\n  // No animations\n}\n\n// Glow style - constant glow via SVG filter\n.glow {\n  // Filter applied inline in component\n  animation: glow-breathe 2s ease-in-out infinite;\n}\n\n// Pulse style - animated path\n.pulse {\n  // Animation applied to .pulsePath child\n}\n\n// Glow breathing animation\n@keyframes glow-breathe {\n  0%,\n  100% {\n    opacity: 0.8;\n  }\n  50% {\n    opacity: 1;\n  }\n}\n\n// Connection pulse animation\n@keyframes connection-pulse {\n  0%,\n  100% {\n    stroke-dashoffset: 0;\n    opacity: 0.8;\n  }\n  50% {\n    stroke-dashoffset: 10;\n    opacity: 1;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"highlightedConnection": `HighlightedConnection-module__highlightedConnection--nzyKW`,
	"pulsePath": `HighlightedConnection-module__pulsePath--CAoGC`,
	"connection-pulse": `HighlightedConnection-module__connection-pulse--g8Ckm`,
	"glow": `HighlightedConnection-module__glow--xEuuh`,
	"glow-breathe": `HighlightedConnection-module__glow-breathe--CTQGs`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 35266:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   z: () => (/* binding */ verifyOpenAiApiKey)
/* harmony export */ });
/* unused harmony export AiAssistantApi */
async function verifyOpenAiApiKey(apiKey) {
    const response = await fetch(`https://api.openai.com/v1/models`, {
        method: 'GET',
        headers: {
            Authorization: 'Bearer ' + apiKey
        }
    });
    if (response.status !== 200) {
        return null;
    }
    const json = await response.json();
    const models = json.data.reduce((acc, item) => {
        acc[item.id] = item;
        return acc;
    }, {});
    return models;
}
var AiAssistantApi;
(function (AiAssistantApi) {
    async function getConfig() {
        return {
            version: '0.0.0',
            models: [
                {
                    name: 'gpt-4o-mini',
                    displayName: 'gpt-4 (8k context)',
                    promptTokenCost: 0.03,
                    completionTokenCost: 0.06
                },
                {
                    name: 'gpt-3.5-turbo',
                    displayName: 'gpt-3.5-turbo',
                    promptTokenCost: 0.002,
                    completionTokenCost: 0.03
                }
            ]
        };
    }
    AiAssistantApi.getConfig = getConfig;
})(AiAssistantApi || (AiAssistantApi = {}));


/***/ }),

/***/ 35313:
/***/ ((module) => {

module.exports = {
  type: 'dist',
  Tracker: {
    trackExceptions: true
  },
  PreviewServer: {
    port: 8574
  },

  apiEndpoint: 'https://api.noodlcloud.com',
  domainEndpoint: 'http://domains.noodlcloud.com',
  aiEndpoint: 'https://p2qsqhrh6xd6relfoaye4tf6nm0bibpm.lambda-url.us-east-1.on.aws'
};


/***/ }),

/***/ 35315:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  t: () => (/* reexport */ Tabs),
  _: () => (/* reexport */ TabsVariant)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/index.ts
var Text = __webpack_require__(93834);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/Tabs/Tabs.module.scss
var Tabs_module = __webpack_require__(35511);
;// ../noodl-core-ui/src/components/layout/Tabs/Tabs.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(Tabs_module/* default */.A, options);




       /* harmony default export */ const Tabs_Tabs_module = (Tabs_module/* default */.A && Tabs_module/* default */.A.locals ? Tabs_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/Tabs/Tabs.tsx




var TabsVariant;
(function (TabsVariant) {
    TabsVariant["Default"] = "is-variant-default";
    TabsVariant["Text"] = "is-variant-text";
    TabsVariant["Sidebar"] = "is-variant-sidebar";
})(TabsVariant || (TabsVariant = {}));
function getTabId(tab) {
    return tab.hasOwnProperty('id') ? tab.id : tab.label;
}
function Tabs({ tabs, initialActiveTab, activeTab, variant = TabsVariant.Default, keepTabsAlive = false, onChange, UNSAFE_className, UNSAFE_style }) {
    const [activeTabId, setActiveTabId] = (0,external_react_.useState)(() => initialActiveTab || getTabId(tabs[0]));
    (0,external_react_.useEffect)(() => {
        if (!activeTab)
            return;
        setActiveTabId(activeTab);
    }, [activeTab]);
    const tabWidth = `calc(${100 / tabs.length}% - 2px)`;
    function changeTab(tab) {
        const tabId = getTabId(tab);
        setActiveTabId(tabId);
        onChange && onChange(tabId);
    }
    return (external_react_default().createElement("div", { className: external_classnames_default()(Tabs_Tabs_module['Root'], Tabs_Tabs_module[variant], UNSAFE_className), style: UNSAFE_style },
        external_react_default().createElement("nav", { className: Tabs_Tabs_module['Buttons'] }, tabs.map((tab) => (external_react_default().createElement("button", { key: getTabId(tab), className: external_classnames_default()([
                Tabs_Tabs_module['Button'],
                activeTabId === getTabId(tab) && Tabs_Tabs_module['is-active']
            ]), onClick: () => changeTab(tab), style: { width: variant === TabsVariant.Text ? null : tabWidth }, "data-test": tab.testId },
            external_react_default().createElement(Text/* Text */.EY, null, tab.label))))),
        external_react_default().createElement("div", { className: Tabs_Tabs_module['TabContent'] }, Boolean(keepTabsAlive)
            ? tabs.map((tab) => {
                const tabId = getTabId(tab);
                return (external_react_default().createElement("div", { key: tabId, className: Tabs_Tabs_module['KeepAliveTab'], style: { display: tabId === activeTabId ? 'block' : 'none' } }, tab.content));
            })
            : tabs.find((tab) => getTabId(tab) === activeTabId).content)));
}

;// ../noodl-core-ui/src/components/layout/Tabs/index.ts



/***/ }),

/***/ 35381:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgComponentWithChildren = function SvgComponentWithChildren(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M11.2932 5.56691C11.6837 5.17639 12.3168 5.17639 12.7074 5.56691L18.7403 11.5999C19.1309 11.9904 19.1309 12.6236 18.7403 13.0141L12.7074 19.0471C12.3168 19.4376 11.6837 19.4376 11.2932 19.0471L5.26018 13.0141C4.86965 12.6236 4.86965 11.9904 5.26018 11.5999L11.2932 5.56691Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M10.7628 5.03658C11.4462 4.35316 12.5543 4.35316 13.2377 5.03658L19.2707 11.0696C19.9541 11.753 19.9541 12.861 19.2707 13.5444L13.2377 19.5774C12.5543 20.2608 11.4462 20.2608 10.7628 19.5774L4.72985 13.5444C4.04643 12.861 4.04643 11.753 4.72985 11.0696L10.7628 5.03658ZM12.177 6.09724C12.0794 5.99961 11.9211 5.99961 11.8235 6.09724L5.79051 12.1302C5.69288 12.2279 5.69288 12.3861 5.79051 12.4838L11.8235 18.5168C11.9211 18.6144 12.0794 18.6144 12.177 18.5168L18.21 12.4838C18.3077 12.3861 18.3077 12.2279 18.21 12.1302L12.177 6.09724Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgComponentWithChildren);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "82467376b217700a514726378f824952.svg");

/***/ }),

/***/ 35393:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PropertyPanelLengthUnitInput-module__Root--VuQsT{font-family:var(--font-family);color:var(--theme-color-fg-default);display:flex;position:relative}.PropertyPanelLengthUnitInput-module__Root--VuQsT.PropertyPanelLengthUnitInput-module__is-faux-focused--DD2RV{z-index:1}.PropertyPanelLengthUnitInput-module__UnitContainer--CIFrE{width:32px;margin-left:2px;flex-grow:0;flex-shrink:0;position:relative}.PropertyPanelLengthUnitInput-module__UnitContainer--CIFrE.PropertyPanelLengthUnitInput-module__has-small-text--fIg_C{width:24px;margin-left:-4px}.PropertyPanelLengthUnitInput-module__UnitContainer--CIFrE input{text-align:center}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/property-panel/PropertyPanelLengthUnitInput/PropertyPanelLengthUnitInput.module.scss"],"names":[],"mappings":"AAAA,kDACE,8BAAA,CACA,mCAAA,CACA,YAAA,CACA,iBAAA,CAEA,8GACE,SAAA,CAIJ,2DACE,UAAA,CACA,eAAA,CACA,WAAA,CACA,aAAA,CACA,iBAAA,CAEA,sHACE,UAAA,CACA,gBAAA,CAGF,iEACE,iBAAA","sourcesContent":[".Root {\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-default);\n  display: flex;\n  position: relative;\n\n  &.is-faux-focused {\n    z-index: 1;\n  }\n}\n\n.UnitContainer {\n  width: 32px;\n  margin-left: 2px;\n  flex-grow: 0;\n  flex-shrink: 0;\n  position: relative;\n\n  &.has-small-text {\n    width: 24px;\n    margin-left: -4px;\n  }\n\n  input {\n    text-align: center;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PropertyPanelLengthUnitInput-module__Root--VuQsT`,
	"is-faux-focused": `PropertyPanelLengthUnitInput-module__is-faux-focused--DD2RV`,
	"UnitContainer": `PropertyPanelLengthUnitInput-module__UnitContainer--CIFrE`,
	"has-small-text": `PropertyPanelLengthUnitInput-module__has-small-text--fIg_C`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 35511:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Tabs-module__Root--zasCH.Tabs-module__is-variant-text--mC8c1 .Tabs-module__Button--rruzp{padding:0;margin:0;list-style:none;border:none;border-radius:0}.Tabs-module__Root--zasCH{overflow:hidden;height:100%;display:flex;flex-direction:column}.Tabs-module__Root--zasCH.Tabs-module__is-variant-text--mC8c1{background-color:var(--theme-color-bg-2)}.Tabs-module__Buttons--LFutl{display:flex}.Tabs-module__Root--zasCH.Tabs-module__is-variant-default--A7bTA .Tabs-module__Buttons--LFutl{margin-left:-2px;padding:2px}.Tabs-module__Root--zasCH.Tabs-module__is-variant-text--mC8c1 .Tabs-module__Buttons--LFutl{padding:15px 15px 13px}.Tabs-module__Root--zasCH.Tabs-module__is-variant-sidebar--Er_Su .Tabs-module__Buttons--LFutl{margin-left:-2px}.Tabs-module__Button--rruzp{cursor:pointer;user-select:none}.Tabs-module__Root--zasCH.Tabs-module__is-variant-default--A7bTA .Tabs-module__Button--rruzp{background-color:var(--theme-color-bg-3);flex-grow:1;flex-shrink:0;flex-basis:1;border:none;padding:15px;margin-left:2px;transition:background-color var(--speed-quick) var(--easing-base);color:var(--theme-color-fg-default)}.Tabs-module__Root--zasCH.Tabs-module__is-variant-default--A7bTA .Tabs-module__Button--rruzp>p{transition:color var(--speed-quick) var(--easing-base)}.Tabs-module__Root--zasCH.Tabs-module__is-variant-default--A7bTA .Tabs-module__Button--rruzp.Tabs-module__is-active--ICtgE{background-color:var(--theme-color-bg-2) !important}.Tabs-module__Root--zasCH.Tabs-module__is-variant-default--A7bTA .Tabs-module__Button--rruzp.Tabs-module__is-active--ICtgE>p{color:var(--theme-color-fg-highlight)}.Tabs-module__Root--zasCH.Tabs-module__is-variant-default--A7bTA .Tabs-module__Button--rruzp:hover{background-color:var(--theme-color-bg-2)}.Tabs-module__Root--zasCH.Tabs-module__is-variant-text--mC8c1 .Tabs-module__Button--rruzp{font-weight:var(--font-weight-semibold);background-color:rgba(0,0,0,0);margin-right:32px}.Tabs-module__Root--zasCH.Tabs-module__is-variant-text--mC8c1 .Tabs-module__Button--rruzp>p{color:var(--theme-color-fg-default-shy);font-size:14px;position:relative;transition:color var(--speed-quick) var(--easing-base)}.Tabs-module__Root--zasCH.Tabs-module__is-variant-text--mC8c1 .Tabs-module__Button--rruzp>p:after{content:"";position:absolute;top:-15px;height:1px;background-color:var(--theme-color-fg-highlight);left:0;right:0;opacity:0;transition:opacity var(--speed-quick) var(--easing-base)}.Tabs-module__Root--zasCH.Tabs-module__is-variant-text--mC8c1 .Tabs-module__Button--rruzp.Tabs-module__is-active--ICtgE>p{color:var(--theme-color-fg-highlight)}.Tabs-module__Root--zasCH.Tabs-module__is-variant-text--mC8c1 .Tabs-module__Button--rruzp.Tabs-module__is-active--ICtgE>p:after{opacity:1}.Tabs-module__Root--zasCH.Tabs-module__is-variant-sidebar--Er_Su .Tabs-module__Button--rruzp{background-color:var(--theme-color-bg-3);flex-grow:1;flex-shrink:0;flex-basis:1;border:none;padding:12px 16px;margin-left:2px;color:var(--theme-color-fg-default);transition:color var(--speed-quick) var(--easing-base)}.Tabs-module__Root--zasCH.Tabs-module__is-variant-sidebar--Er_Su .Tabs-module__Button--rruzp.Tabs-module__is-active--ICtgE{background-color:var(--theme-color-bg-1)}.Tabs-module__Root--zasCH.Tabs-module__is-variant-sidebar--Er_Su .Tabs-module__Button--rruzp.Tabs-module__is-active--ICtgE>p{color:var(--theme-color-fg-highlight) !important}.Tabs-module__Root--zasCH.Tabs-module__is-variant-sidebar--Er_Su .Tabs-module__Button--rruzp:hover>p{color:var(--theme-color-fg-default-contrast)}.Tabs-module__TabContent--Pn4dm{flex:1;overflow:hidden overlay}.Tabs-module__KeepAliveTab--fakNO{width:100%;height:100%}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/styles/scss-utils/placeholder.scss","webpack://./../noodl-core-ui/src/components/layout/Tabs/Tabs.module.scss"],"names":[],"mappings":"AAQA,0FACE,SAAA,CACA,QAAA,CACA,eAAA,CACA,WAAA,CACA,eAAA,CCRF,0BACE,eAAA,CACA,WAAA,CACA,YAAA,CACA,qBAAA,CAEA,8DACE,wCAAA,CAIJ,6BACE,YAAA,CAEA,8FACE,gBAAA,CACA,WAAA,CAGF,2FACE,sBAAA,CAGF,8FACE,gBAAA,CAIJ,4BACE,cAAA,CACA,gBAAA,CAEA,6FACE,wCAAA,CACA,WAAA,CACA,aAAA,CACA,YAAA,CACA,WAAA,CACA,YAAA,CACA,eA1CM,CA2CN,iEAAA,CACA,mCAAA,CAEA,+FACE,sDAAA,CAGF,2HACE,mDAAA,CAEA,6HACE,qCAAA,CAIJ,mGACE,wCAAA,CAIJ,0FAEE,uCAAA,CACA,8BAAA,CACA,iBAAA,CAEA,4FACE,uCAAA,CACA,cAAA,CACA,iBAAA,CACA,sDAAA,CAEA,kGACE,UAAA,CACA,iBAAA,CACA,SAAA,CACA,UAAA,CACA,gDAAA,CACA,MAAA,CACA,OAAA,CACA,SAAA,CACA,wDAAA,CAIJ,0HACE,qCAAA,CAEA,gIACE,SAAA,CAKN,6FACE,wCAAA,CACA,WAAA,CACA,aAAA,CACA,YAAA,CACA,WAAA,CACA,iBAAA,CACA,eAxGM,CAyGN,mCAAA,CACA,sDAAA,CAEA,2HACE,wCAAA,CAEA,6HACE,gDAAA,CAIJ,qGACE,4CAAA,CAKN,gCACE,MAAA,CACA,uBAAA,CAGF,kCACE,UAAA,CACA,WAAA","sourcesContent":["%overlay {\r\n  position: absolute;\r\n  top: 0;\r\n  bottom: 0;\r\n  right: 0;\r\n  left: 0;\r\n}\r\n\r\n%reset-styles {\r\n  padding: 0;\r\n  margin: 0;\r\n  list-style: none;\r\n  border: none;\r\n  border-radius: 0;\r\n}\r\n","@use '../../../styles/scss-utils/placeholder.scss' as *;\r\n\r\n$_gutter: 2px;\r\n$_text-variant-top-padding: 15px;\r\n\r\n.Root {\r\n  overflow: hidden;\r\n  height: 100%;\r\n  display: flex;\r\n  flex-direction: column;\r\n\r\n  &.is-variant-text {\r\n    background-color: var(--theme-color-bg-2);\r\n  }\r\n}\r\n\r\n.Buttons {\r\n  display: flex;\r\n\r\n  .Root.is-variant-default & {\r\n    margin-left: -$_gutter;\r\n    padding: 2px;\r\n  }\r\n\r\n  .Root.is-variant-text & {\r\n    padding: $_text-variant-top-padding 15px 13px;\r\n  }\r\n\r\n  .Root.is-variant-sidebar & {\r\n    margin-left: -$_gutter;\r\n  }\r\n}\r\n\r\n.Button {\r\n  cursor: pointer;\r\n  user-select: none;\r\n\r\n  .Root.is-variant-default & {\r\n    background-color: var(--theme-color-bg-3);\r\n    flex-grow: 1;\r\n    flex-shrink: 0;\r\n    flex-basis: 1;\r\n    border: none;\r\n    padding: 15px;\r\n    margin-left: $_gutter;\r\n    transition: background-color var(--speed-quick) var(--easing-base);\r\n    color: var(--theme-color-fg-default);\r\n\r\n    > p {\r\n      transition: color var(--speed-quick) var(--easing-base);\r\n    }\r\n\r\n    &.is-active {\r\n      background-color: var(--theme-color-bg-2) !important;\r\n\r\n      > p {\r\n        color: var(--theme-color-fg-highlight);\r\n      }\r\n    }\r\n\r\n    &:hover {\r\n      background-color: var(--theme-color-bg-2);\r\n    }\r\n  }\r\n\r\n  .Root.is-variant-text & {\r\n    @extend %reset-styles;\r\n    font-weight: var(--font-weight-semibold);\r\n    background-color: transparent;\r\n    margin-right: 32px;\r\n\r\n    > p {\r\n      color: var(--theme-color-fg-default-shy);\r\n      font-size: 14px;\r\n      position: relative;\r\n      transition: color var(--speed-quick) var(--easing-base);\r\n\r\n      &:after {\r\n        content: '';\r\n        position: absolute;\r\n        top: -$_text-variant-top-padding;\r\n        height: 1px;\r\n        background-color: var(--theme-color-fg-highlight);\r\n        left: 0;\r\n        right: 0;\r\n        opacity: 0;\r\n        transition: opacity var(--speed-quick) var(--easing-base);\r\n      }\r\n    }\r\n\r\n    &.is-active > p {\r\n      color: var(--theme-color-fg-highlight);\r\n\r\n      &:after {\r\n        opacity: 1;\r\n      }\r\n    }\r\n  }\r\n\r\n  .Root.is-variant-sidebar & {\r\n    background-color: var(--theme-color-bg-3);\r\n    flex-grow: 1;\r\n    flex-shrink: 0;\r\n    flex-basis: 1;\r\n    border: none;\r\n    padding: 12px 16px;\r\n    margin-left: $_gutter;\r\n    color: var(--theme-color-fg-default);\r\n    transition: color var(--speed-quick) var(--easing-base);\r\n\r\n    &.is-active {\r\n      background-color: var(--theme-color-bg-1);\r\n\r\n      & > p {\r\n        color: var(--theme-color-fg-highlight) !important;\r\n      }\r\n    }\r\n\r\n    &:hover > p {\r\n      color: var(--theme-color-fg-default-contrast);\r\n    }\r\n  }\r\n}\r\n\r\n.TabContent {\r\n  flex: 1;\r\n  overflow: hidden overlay;\r\n}\r\n\r\n.KeepAliveTab {\r\n  width: 100%;\r\n  height: 100%;\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Tabs-module__Root--zasCH`,
	"is-variant-text": `Tabs-module__is-variant-text--mC8c1`,
	"Button": `Tabs-module__Button--rruzp`,
	"Buttons": `Tabs-module__Buttons--LFutl`,
	"is-variant-default": `Tabs-module__is-variant-default--A7bTA`,
	"is-variant-sidebar": `Tabs-module__is-variant-sidebar--Er_Su`,
	"is-active": `Tabs-module__is-active--ICtgE`,
	"TabContent": `Tabs-module__TabContent--Pn4dm`,
	"KeepAliveTab": `Tabs-module__KeepAliveTab--fakNO`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 35646:
/***/ ((module) => {

// Module
var code = "<div style=\"position:relative;height:150px\"> <div class=\"marginpadding-border\" style=\"position:absolute;top:39px;left:60px;right:60px;bottom:39px\"> </div> <div class=\"marginpadding-label drag-handle\" data-comp=\"margin-top\" style=\"position:absolute;left:50%;transform:translateX(-50%);top:10px\" data-click=\"onLabelClicked\"> </div> <div class=\"marginpadding-label drag-handle\" data-comp=\"margin-bottom\" style=\"position:absolute;left:50%;transform:translateX(-50%);bottom:10px\" data-click=\"onLabelClicked\"> </div> <div class=\"marginpadding-label drag-handle\" data-comp=\"margin-left\" style=\"position:absolute;top:50%;transform:translate(-50%,-50%);left:32px\" data-click=\"onLabelClicked\"> </div> <div class=\"marginpadding-label drag-handle\" data-comp=\"margin-right\" style=\"position:absolute;top:50%;transform:translate(50%,-50%);right:32px\" data-click=\"onLabelClicked\"> </div> <div class=\"marginpadding-label drag-handle\" data-comp=\"padding-top\" style=\"position:absolute;left:50%;transform:translateX(-50%);top:46px\" data-click=\"onLabelClicked\"> </div> <div class=\"marginpadding-label drag-handle\" data-comp=\"padding-bottom\" style=\"position:absolute;left:50%;transform:translateX(-50%);bottom:46px\" data-click=\"onLabelClicked\"> </div> <div class=\"marginpadding-label drag-handle\" data-comp=\"padding-left\" style=\"position:absolute;top:50%;transform:translate(-50%,-50%);left:90px\" data-click=\"onLabelClicked\"> </div> <div class=\"marginpadding-label drag-handle\" data-comp=\"padding-right\" style=\"position:absolute;top:50%;transform:translate(50%,-50%);right:90px\" data-click=\"onLabelClicked\"> </div> <div id=\"editbox\" style=\"display:none\" data-click=\"onHideEditBoxClicked\"> <div class=\"marginpadding-dim\" style=\"position:absolute;top:0;left:0;right:0;bottom:0\"></div> <div id=\"editbox-editor\" class=\"marginpadding-editbox\" style=\"position:absolute;top:15px;left:15px;width:110px;height:35px\"> <div class=\"property-value\" style=\"left:0;top:1px;bottom:1px;right:36px\"> <input type=\"string\" class=\"sidebar-panel-dark-input\" style=\"position:absolute;width:100%;height:100%\" data-class=\"isConnected:property-input-connected,isFocused:property-input-focused,isDefault:property-input-default\" data-val=\"value\" data-change=\"onPropertyChanged\"> </div> <div class=\"sidebar-panel-dark-input property-number-units\" style=\"position:absolute;right:1px;width:33px;top:1px;bottom:1px;padding:0\" data-click=\"onDropDownClicked\" tabindex=\"1\"> <span data-class=\"isFocused:property-input-focused,isDefault:property-input-default\" style=\"line-height:35px\" data-text=\"unit\"></span> <div style=\"position:absolute;top:35px;left:0;width:100%;display:none\" class=\"property-input-dropdown\" style=\"display:none\"> </div> </div> </div> </div> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> </div>";
// Exports
module.exports = code;

/***/ }),

/***/ 35658:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDropdownLines = function SvgDropdownLines(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M24.0504 17.4524C23.7557 17.7471 23.278 17.7471 22.9834 17.4524L20.3812 14.8503C20.0866 14.5556 20.0866 14.0779 20.3812 13.7832C20.6759 13.4886 21.1536 13.4886 21.4482 13.7832L23.5169 15.8519L25.5855 13.7832C25.8802 13.4886 26.3579 13.4886 26.6525 13.7832C26.9472 14.0779 26.9472 14.5556 26.6525 14.8503L24.0504 17.4524Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M17.2441 8.85429C17.2441 8.43759 16.9063 8.09979 16.4896 8.09979H4.12787C3.71117 8.09979 3.37336 8.43759 3.37336 8.85429C3.37336 9.27099 3.71117 9.60879 4.12787 9.60879H16.4896C16.9063 9.60879 17.2441 9.27099 17.2441 8.85429Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M17.2441 13.3633C17.2441 12.9466 16.9063 12.6088 16.4896 12.6088H4.12787C3.71117 12.6088 3.37336 12.9466 3.37336 13.3633C3.37336 13.78 3.71117 14.1178 4.12787 14.1178H16.4896C16.9063 14.1178 17.2441 13.78 17.2441 13.3633Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M17.2441 17.8722C17.2441 17.4555 16.9063 17.1177 16.4896 17.1177H4.12787C3.71117 17.1177 3.37336 17.4555 3.37336 17.8722C3.37336 18.2889 3.71117 18.6267 4.12787 18.6267H16.4896C16.9063 18.6267 17.2441 18.2889 17.2441 17.8722Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M17.2441 22.3812C17.2441 21.9645 16.9063 21.6267 16.4896 21.6267H4.12787C3.71117 21.6267 3.37336 21.9645 3.37336 22.3812C3.37336 22.7979 3.71117 23.1357 4.12787 23.1357H16.4896C16.9063 23.1357 17.2441 22.7979 17.2441 22.3812Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDropdownLines);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "2cdb0c25c164542473d4926abacf62a7.svg");

/***/ }),

/***/ 35665:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var View = __webpack_require__(92207),
  ErrorModalTemplate = __webpack_require__(27252);

function ErrorModal(args) {
  View.call(this);

  this.title = args.title || 'Error';
  this.message = args.message;

  this.onOk = args.onOk;
}

ErrorModal.prototype = Object.create(View.prototype);

ErrorModal.prototype.render = function () {
  var el = this.bindView($(ErrorModalTemplate), this);
  if (this.el) this.el.append(el);
  else this.el = el;

  return this.el;
};

ErrorModal.prototype.onOkClicked = function (scope, el, evt) {
  this.onOk && this.onOk();
  evt.stopPropagation();
};

module.exports = ErrorModal;


/***/ }),

/***/ 35682:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgComponentFill = function SvgComponentFill(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.6367 4.10107H4.63672C4.22251 4.10107 3.88672 4.43686 3.88672 4.85107V10.8511C3.88672 11.2653 4.22251 11.6011 4.63672 11.6011H10.6367C11.0509 11.6011 11.3867 11.2653 11.3867 10.8511V4.85107C11.3867 4.43686 11.0509 4.10107 10.6367 4.10107Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M20.0425 4.10107H14.0425C13.6283 4.10107 13.2925 4.43686 13.2925 4.85107V10.8511C13.2925 11.2653 13.6283 11.6011 14.0425 11.6011H20.0425C20.4567 11.6011 20.7925 11.2653 20.7925 10.8511V4.85107C20.7925 4.43686 20.4567 4.10107 20.0425 4.10107Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.6367 13.4129H4.63672C4.22251 13.4129 3.88672 13.7487 3.88672 14.1629V20.1629C3.88672 20.5771 4.22251 20.9129 4.63672 20.9129H10.6367C11.0509 20.9129 11.3867 20.5771 11.3867 20.1629V14.1629C11.3867 13.7487 11.0509 13.4129 10.6367 13.4129Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M20.0425 13.4129H14.0425C13.6283 13.4129 13.2925 13.7487 13.2925 14.1629V20.1629C13.2925 20.5771 13.6283 20.9129 14.0425 20.9129H20.0425C20.4567 20.9129 20.7925 20.5771 20.7925 20.1629V14.1629C20.7925 13.7487 20.4567 13.4129 20.0425 13.4129Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgComponentFill);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "defc92fb7627e5fff5c7c76e7a055893.svg");

/***/ }),

/***/ 35715:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _projectmodel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6203);

class NodeTypeAdapter {
    constructor(typename) {
        this.typename = typename;
    }
    findAllNodes() {
        return _projectmodel__WEBPACK_IMPORTED_MODULE_0__.ProjectModel.instance.getNodesWithType(this.typename);
    }
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (NodeTypeAdapter);


/***/ }),

/***/ 35742:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   B: () => (/* binding */ getBlobBinaryContents),
/* harmony export */   w: () => (/* binding */ getBlobContents)
/* harmony export */ });
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85869);

/**
 * Retrieve the contents of a file from the repository at a given
 * reference, commit, or tree.
 *
 * Returns a promise that will produce a string Buffer instance containing
 * the contents of the file or an error if the file doesn't
 * exists in the given revision.
 *
 * @param repositoryDir - The repository directory from where to read the file
 *
 * @param commitish  - A commit SHA or some other identifier that
 *                     ultimately dereferences to a commit/tree.
 *
 * @param path       - The file path, relative to the repository
 *                     root from where to read the blob contents
 */
async function getBlobContents(repositoryDir, commitish, path) {
    const args = ['show', `${commitish}:${path}`];
    const opts = {
        parseErrors: false
    };
    const { output } = await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)(args, repositoryDir, 'getBlobContents', opts);
    return output;
}
async function getBlobBinaryContents(repositoryDir, commitish, path) {
    const setBinaryEncoding = (cb) => {
        // If Node.js encounters a synchronous runtime error while spawning
        // `stdout` will be undefined and the error will be emitted asynchronously
        if (cb.stdout) {
            cb.stdout.setEncoding('binary');
        }
    };
    const args = ['show', `${commitish}:${path}`];
    const opts = {
        parseErrors: false,
        processCallback: setBinaryEncoding
    };
    const { output } = await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)(args, repositoryDir, 'getBlobBinaryContents', opts);
    return Buffer.from(output, 'binary');
}


/***/ }),

/***/ 36172:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `@keyframes WizardProgress-module__pulse--WVXv3{0%,100%{transform:scale(1);box-shadow:0 0 0 0 rgba(66,135,245,.7)}50%{transform:scale(1.05);box-shadow:0 0 0 8px rgba(66,135,245,0)}}@keyframes WizardProgress-module__checkmark--gyphu{0%{transform:scale(0) rotate(-45deg)}50%{transform:scale(1.2) rotate(-45deg)}100%{transform:scale(1) rotate(0deg)}}@keyframes WizardProgress-module__slideProgress--Y7ZX1{from{transform:scaleX(0);transform-origin:left}to{transform:scaleX(1);transform-origin:left}}.WizardProgress-module__Root--GQezK{display:flex;align-items:center;gap:0;padding:16px 0 24px;margin-bottom:8px}.WizardProgress-module__Step--bNwZ3{display:flex;flex-direction:column;align-items:center;gap:8px;flex:1;position:relative;z-index:1}.WizardProgress-module__StepCircle--uZFSB{width:36px;height:36px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:600;background-color:var(--theme-color-bg-2);color:var(--theme-color-fg-muted);border:2px solid var(--theme-color-bg-2);transition:all 300ms ease-in-out;position:relative;z-index:2}.WizardProgress-module__Step--bNwZ3.WizardProgress-module__is-completed--x8aId .WizardProgress-module__StepCircle--uZFSB{background-color:var(--theme-color-success);border-color:var(--theme-color-success);color:#fff;animation:WizardProgress-module__checkmark--gyphu 400ms ease-out}.WizardProgress-module__Step--bNwZ3.WizardProgress-module__is-active--axOOz .WizardProgress-module__StepCircle--uZFSB{background-color:var(--theme-color-primary);border-color:var(--theme-color-primary);color:#fff;animation:WizardProgress-module__pulse--WVXv3 2s ease-in-out infinite;box-shadow:0 0 0 0 rgba(66,135,245,.7)}.WizardProgress-module__StepLabel--u3_MI{font-size:11px;font-weight:500;color:var(--theme-color-fg-muted);text-align:center;max-width:80px;transition:color 200ms ease-in-out;line-height:1.3}.WizardProgress-module__Step--bNwZ3.WizardProgress-module__is-completed--x8aId .WizardProgress-module__StepLabel--u3_MI,.WizardProgress-module__Step--bNwZ3.WizardProgress-module__is-active--axOOz .WizardProgress-module__StepLabel--u3_MI{color:var(--theme-color-fg-highlight);font-weight:600}.WizardProgress-module__Connector--rnF2f{flex:1;height:2px;background-color:var(--theme-color-bg-2);margin:0 -4px;margin-bottom:28px;position:relative;z-index:0;overflow:hidden}.WizardProgress-module__Connector--rnF2f::after{content:"";position:absolute;top:0;left:0;width:100%;height:100%;background-color:var(--theme-color-success);transform:scaleX(0);transform-origin:left;transition:transform 400ms ease-in-out}.WizardProgress-module__Connector--rnF2f.WizardProgress-module__is-completed--x8aId::after{transform:scaleX(1);animation:WizardProgress-module__slideProgress--Y7ZX1 400ms ease-out}.WizardProgress-module__CheckIcon--Js_z5{display:flex;align-items:center;justify-content:center}.WizardProgress-module__CheckIcon--Js_z5 svg{width:18px;height:18px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/migration/components/WizardProgress.module.scss"],"names":[],"mappings":"AAMA,+CACE,QAEE,kBAAA,CACA,sCAAA,CAEF,IACE,qBAAA,CACA,uCAAA,CAAA,CAIJ,mDACE,GACE,iCAAA,CAEF,IACE,mCAAA,CAEF,KACE,+BAAA,CAAA,CAIJ,uDACE,KACE,mBAAA,CACA,qBAAA,CAEF,GACE,mBAAA,CACA,qBAAA,CAAA,CAIJ,oCACE,YAAA,CACA,kBAAA,CACA,KAAA,CACA,mBAAA,CACA,iBAAA,CAGF,oCACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,OAAA,CACA,MAAA,CACA,iBAAA,CACA,SAAA,CAGF,0CACE,UAAA,CACA,WAAA,CACA,iBAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,cAAA,CACA,eAAA,CACA,wCAAA,CACA,iCAAA,CACA,wCAAA,CACA,gCAAA,CACA,iBAAA,CACA,SAAA,CAGF,yHACE,2CAAA,CACA,uCAAA,CACA,UAAA,CACA,gEAAA,CAGF,sHACE,2CAAA,CACA,uCAAA,CACA,UAAA,CACA,qEAAA,CACA,sCAAA,CAGF,yCACE,cAAA,CACA,eAAA,CACA,iCAAA,CACA,iBAAA,CACA,cAAA,CACA,kCAAA,CACA,eAAA,CAGF,6OAEE,qCAAA,CACA,eAAA,CAGF,yCACE,MAAA,CACA,UAAA,CACA,wCAAA,CACA,aAAA,CACA,kBAAA,CACA,iBAAA,CACA,SAAA,CACA,eAAA,CAEA,gDACE,UAAA,CACA,iBAAA,CACA,KAAA,CACA,MAAA,CACA,UAAA,CACA,WAAA,CACA,2CAAA,CACA,mBAAA,CACA,qBAAA,CACA,sCAAA,CAIJ,2FACE,mBAAA,CACA,oEAAA,CAGF,yCACE,YAAA,CACA,kBAAA,CACA,sBAAA,CAEA,6CACE,UAAA,CACA,WAAA","sourcesContent":["/**\n * WizardProgress Styles\n * \n * Enhanced step progress indicator for migration wizard with animations and better visuals.\n */\n\n@keyframes pulse {\n  0%,\n  100% {\n    transform: scale(1);\n    box-shadow: 0 0 0 0 rgba(66, 135, 245, 0.7);\n  }\n  50% {\n    transform: scale(1.05);\n    box-shadow: 0 0 0 8px rgba(66, 135, 245, 0);\n  }\n}\n\n@keyframes checkmark {\n  0% {\n    transform: scale(0) rotate(-45deg);\n  }\n  50% {\n    transform: scale(1.2) rotate(-45deg);\n  }\n  100% {\n    transform: scale(1) rotate(0deg);\n  }\n}\n\n@keyframes slideProgress {\n  from {\n    transform: scaleX(0);\n    transform-origin: left;\n  }\n  to {\n    transform: scaleX(1);\n    transform-origin: left;\n  }\n}\n\n.Root {\n  display: flex;\n  align-items: center;\n  gap: 0;\n  padding: 16px 0 24px;\n  margin-bottom: 8px;\n}\n\n.Step {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 8px;\n  flex: 1;\n  position: relative;\n  z-index: 1;\n}\n\n.StepCircle {\n  width: 36px;\n  height: 36px;\n  border-radius: 50%;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  font-size: 13px;\n  font-weight: 600;\n  background-color: var(--theme-color-bg-2);\n  color: var(--theme-color-fg-muted);\n  border: 2px solid var(--theme-color-bg-2);\n  transition: all 300ms ease-in-out;\n  position: relative;\n  z-index: 2;\n}\n\n.Step.is-completed .StepCircle {\n  background-color: var(--theme-color-success);\n  border-color: var(--theme-color-success);\n  color: white;\n  animation: checkmark 400ms ease-out;\n}\n\n.Step.is-active .StepCircle {\n  background-color: var(--theme-color-primary);\n  border-color: var(--theme-color-primary);\n  color: white;\n  animation: pulse 2s ease-in-out infinite;\n  box-shadow: 0 0 0 0 rgba(66, 135, 245, 0.7);\n}\n\n.StepLabel {\n  font-size: 11px;\n  font-weight: 500;\n  color: var(--theme-color-fg-muted);\n  text-align: center;\n  max-width: 80px;\n  transition: color 200ms ease-in-out;\n  line-height: 1.3;\n}\n\n.Step.is-completed .StepLabel,\n.Step.is-active .StepLabel {\n  color: var(--theme-color-fg-highlight);\n  font-weight: 600;\n}\n\n.Connector {\n  flex: 1;\n  height: 2px;\n  background-color: var(--theme-color-bg-2);\n  margin: 0 -4px;\n  margin-bottom: 28px;\n  position: relative;\n  z-index: 0;\n  overflow: hidden;\n\n  &::after {\n    content: '';\n    position: absolute;\n    top: 0;\n    left: 0;\n    width: 100%;\n    height: 100%;\n    background-color: var(--theme-color-success);\n    transform: scaleX(0);\n    transform-origin: left;\n    transition: transform 400ms ease-in-out;\n  }\n}\n\n.Connector.is-completed::after {\n  transform: scaleX(1);\n  animation: slideProgress 400ms ease-out;\n}\n\n.CheckIcon {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n\n  svg {\n    width: 18px;\n    height: 18px;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `WizardProgress-module__Root--GQezK`,
	"Step": `WizardProgress-module__Step--bNwZ3`,
	"StepCircle": `WizardProgress-module__StepCircle--uZFSB`,
	"is-completed": `WizardProgress-module__is-completed--x8aId`,
	"checkmark": `WizardProgress-module__checkmark--gyphu`,
	"is-active": `WizardProgress-module__is-active--axOOz`,
	"pulse": `WizardProgress-module__pulse--WVXv3`,
	"StepLabel": `WizardProgress-module__StepLabel--u3_MI`,
	"Connector": `WizardProgress-module__Connector--rnF2f`,
	"slideProgress": `WizardProgress-module__slideProgress--Y7ZX1`,
	"CheckIcon": `WizardProgress-module__CheckIcon--Js_z5`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 36224:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDimenstionWidth = function SvgDimenstionWidth(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 30,
    viewBox: "0 0 31 30",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M18.4092 4.59467C18.6853 4.59467 18.9092 4.81852 18.9092 5.09467L18.9092 24.5738C18.9092 24.8499 18.6853 25.0738 18.4092 25.0738L11.8642 25.0738C11.5881 25.0738 11.3642 24.8499 11.3642 24.5738L11.3642 5.09466C11.3642 4.81852 11.5881 4.59467 11.8642 4.59467L18.4092 4.59467Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M28.3003 15.7358C28.7145 15.7358 29.0503 15.4001 29.0503 14.9858C29.0503 14.5716 28.7145 14.2358 28.3003 14.2358L23.85 14.2358L25.0308 13.055C25.3237 12.7622 25.3237 12.2873 25.0308 11.9944C24.7379 11.7015 24.2631 11.7015 23.9702 11.9944L21.512 14.4525C21.3745 14.5885 21.2894 14.7772 21.2894 14.9858C21.2894 15.2009 21.3799 15.3949 21.5249 15.5316L23.9702 17.9768C24.2631 18.2697 24.7379 18.2697 25.0308 17.9768C25.3237 17.684 25.3237 17.2091 25.0308 16.9162L23.8505 15.7358L28.3003 15.7358Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.24315 13.055C4.95025 12.7622 4.95025 12.2873 5.24315 11.9944C5.53604 11.7015 6.01091 11.7015 6.30381 11.9944L8.7647 14.4553C9.0576 14.7482 9.0576 15.2231 8.7647 15.5159L6.30381 17.9768C6.01091 18.2697 5.53604 18.2697 5.24315 17.9768C4.95025 17.684 4.95025 17.2091 5.24315 16.9162L6.42349 15.7358L1.97318 15.7358C1.55897 15.7358 1.22318 15.4001 1.22318 14.9858C1.22318 14.5716 1.55897 14.2358 1.97318 14.2358L6.42394 14.2358L5.24315 13.055Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDimenstionWidth);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "a1d0384053551a55e76cb119d3d779e3.svg");

/***/ }),

/***/ 36370:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.GeneratedCodeModal-module__Overlay--c758h{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;z-index:10000}.GeneratedCodeModal-module__Modal--cAZKh{background-color:var(--theme-color-bg-2, #1a1a1a);border-radius:8px;box-shadow:0 8px 32px rgba(0,0,0,.5);width:800px;max-width:90vw;max-height:90vh;display:flex;flex-direction:column;overflow:hidden}.GeneratedCodeModal-module__Header--ptClB{padding:16px 20px;border-bottom:1px solid var(--theme-color-border-default, rgba(255, 255, 255, 0.1));display:flex;align-items:center;justify-content:space-between}.GeneratedCodeModal-module__Title--maIFy{font-size:16px;font-weight:600;color:var(--theme-color-fg-highlight, #ffffff);margin:0}.GeneratedCodeModal-module__ReadOnlyBadge--jhCrR{font-size:11px;font-weight:500;padding:4px 8px;border-radius:4px;background-color:var(--theme-color-bg-3, rgba(255, 255, 255, 0.1));color:var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.6))}.GeneratedCodeModal-module__InfoBar--PzSeZ{padding:8px 20px;background-color:var(--theme-color-bg-3, rgba(255, 255, 255, 0.05));border-bottom:1px solid var(--theme-color-border-default, rgba(255, 255, 255, 0.1))}.GeneratedCodeModal-module__InfoText--sWBQF{font-size:12px;color:var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.6))}.GeneratedCodeModal-module__Body--vn1Us{padding:16px 20px;flex:1;overflow:auto;display:flex;flex-direction:column;gap:12px}.GeneratedCodeModal-module__EditorWrapper--lGZwI{flex:1;min-height:400px;border-radius:4px;overflow:hidden}.GeneratedCodeModal-module__Footer--dCyjh{padding:12px 20px;border-top:1px solid var(--theme-color-border-default, rgba(255, 255, 255, 0.1));display:flex;justify-content:flex-end;gap:8px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/propertyeditor/GeneratedCodeModal/GeneratedCodeModal.module.scss"],"names":[],"mappings":"AAAA,2CACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,+BAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,aAAA,CAGF,yCACE,iDAAA,CACA,iBAAA,CACA,oCAAA,CACA,WAAA,CACA,cAAA,CACA,eAAA,CACA,YAAA,CACA,qBAAA,CACA,eAAA,CAGF,0CACE,iBAAA,CACA,mFAAA,CACA,YAAA,CACA,kBAAA,CACA,6BAAA,CAGF,yCACE,cAAA,CACA,eAAA,CACA,8CAAA,CACA,QAAA,CAGF,iDACE,cAAA,CACA,eAAA,CACA,eAAA,CACA,iBAAA,CACA,kEAAA,CACA,iEAAA,CAGF,2CACE,gBAAA,CACA,mEAAA,CACA,mFAAA,CAGF,4CACE,cAAA,CACA,iEAAA,CAGF,wCACE,iBAAA,CACA,MAAA,CACA,aAAA,CACA,YAAA,CACA,qBAAA,CACA,QAAA,CAGF,iDACE,MAAA,CACA,gBAAA,CACA,iBAAA,CACA,eAAA,CAGF,0CACE,iBAAA,CACA,gFAAA,CACA,YAAA,CACA,wBAAA,CACA,OAAA","sourcesContent":[".Overlay {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.6);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 10000;\n}\n\n.Modal {\n  background-color: var(--theme-color-bg-2, #1a1a1a);\n  border-radius: 8px;\n  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);\n  width: 800px;\n  max-width: 90vw;\n  max-height: 90vh;\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n\n.Header {\n  padding: 16px 20px;\n  border-bottom: 1px solid var(--theme-color-border-default, rgba(255, 255, 255, 0.1));\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n}\n\n.Title {\n  font-size: 16px;\n  font-weight: 600;\n  color: var(--theme-color-fg-highlight, #ffffff);\n  margin: 0;\n}\n\n.ReadOnlyBadge {\n  font-size: 11px;\n  font-weight: 500;\n  padding: 4px 8px;\n  border-radius: 4px;\n  background-color: var(--theme-color-bg-3, rgba(255, 255, 255, 0.1));\n  color: var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.6));\n}\n\n.InfoBar {\n  padding: 8px 20px;\n  background-color: var(--theme-color-bg-3, rgba(255, 255, 255, 0.05));\n  border-bottom: 1px solid var(--theme-color-border-default, rgba(255, 255, 255, 0.1));\n}\n\n.InfoText {\n  font-size: 12px;\n  color: var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.6));\n}\n\n.Body {\n  padding: 16px 20px;\n  flex: 1;\n  overflow: auto;\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n}\n\n.EditorWrapper {\n  flex: 1;\n  min-height: 400px;\n  border-radius: 4px;\n  overflow: hidden;\n}\n\n.Footer {\n  padding: 12px 20px;\n  border-top: 1px solid var(--theme-color-border-default, rgba(255, 255, 255, 0.1));\n  display: flex;\n  justify-content: flex-end;\n  gap: 8px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Overlay": `GeneratedCodeModal-module__Overlay--c758h`,
	"Modal": `GeneratedCodeModal-module__Modal--cAZKh`,
	"Header": `GeneratedCodeModal-module__Header--ptClB`,
	"Title": `GeneratedCodeModal-module__Title--maIFy`,
	"ReadOnlyBadge": `GeneratedCodeModal-module__ReadOnlyBadge--jhCrR`,
	"InfoBar": `GeneratedCodeModal-module__InfoBar--PzSeZ`,
	"InfoText": `GeneratedCodeModal-module__InfoText--sWBQF`,
	"Body": `GeneratedCodeModal-module__Body--vn1Us`,
	"EditorWrapper": `GeneratedCodeModal-module__EditorWrapper--lGZwI`,
	"Footer": `GeneratedCodeModal-module__Footer--dCyjh`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 36377:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.VERSION = void 0;
exports.VERSION = '0.71.2'; // x-release-please-version
//# sourceMappingURL=version.js.map

/***/ }),

/***/ 36479:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   n: () => (/* binding */ checkoutBranch)
/* harmony export */ });
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85869);
/* harmony import */ var _models_branch__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16279);
/* harmony import */ var _progress__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(51436);
/* harmony import */ var _authentication__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(38495);




async function getCheckoutArgs(repositoryDir, branch, flags, progressCallback) {
    const networkArguments = await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .gitNetworkArguments */ .X)(repositoryDir);
    let baseArgs = progressCallback != null ? [...networkArguments, 'checkout', '--progress'] : [...networkArguments, 'checkout'];
    // Add the flags
    if (flags === null || flags === void 0 ? void 0 : flags.force)
        baseArgs.push('--force');
    if (branch.type === _models_branch__WEBPACK_IMPORTED_MODULE_1__/* .BranchType */ .Rk.Remote) {
        if (flags === null || flags === void 0 ? void 0 : flags.commitish) {
            return baseArgs.concat(branch.name, '-b', branch.nameWithoutRemote, flags.commitish, '--');
        }
        return baseArgs.concat(branch.name, '-b', branch.nameWithoutRemote, '--');
    }
    return baseArgs.concat(branch.name, '--');
}
/**
 * Check out the given branch.
 *
 * @param repository - The repository in which the branch checkout should
 *                     take place
 *
 * @param branch     - The branch name that should be checked out
 *
 * @param progressCallback - An optional function which will be invoked
 *                           with information about the current progress
 *                           of the checkout operation. When provided this
 *                           enables the '--progress' command line flag for
 *                           'git checkout'.
 */
async function checkoutBranch(repositoryDir, branch, flags, progressCallback) {
    let opts = {
        env: {},
        expectedErrors: _authentication__WEBPACK_IMPORTED_MODULE_3__/* .AuthenticationErrors */ .A
    };
    if (progressCallback) {
        const title = `Checking out branch ${branch.name}`;
        const kind = 'checkout';
        const targetBranch = branch.name;
        opts = await (0,_progress__WEBPACK_IMPORTED_MODULE_2__/* .executionOptionsWithProgress */ .s_)(opts, new _progress__WEBPACK_IMPORTED_MODULE_2__/* .CheckoutProgressParser */ .nd(), (progress) => {
            if (progress.kind === 'progress') {
                const description = progress.details.text;
                const value = progress.percent;
                progressCallback({ kind, title, description, value, targetBranch });
            }
        });
        // Initial progress
        progressCallback({ kind, title, value: 0, targetBranch });
    }
    const args = await getCheckoutArgs(repositoryDir, branch, flags, progressCallback);
    await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)(args, repositoryDir, 'checkoutBranch', opts);
    // we return `true` here so `GitStore.performFailableGitOperation`
    // will return _something_ differentiable from `undefined` if this succeeds
    return true;
}


/***/ }),

/***/ 36560:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.GitStashCard-module__Root--nFnlg{position:relative;transition:background-color var(--speed-turbo) var(--easing-base);border-bottom:1px solid var(--theme-color-bg-1)}.GitStashCard-module__Root--nFnlg:hover:not(.GitStashCard-module__is-open--jOBNs){background-color:var(--theme-color-bg-3)}.GitStashCard-module__Inner--_VPpV{padding:8px 16px 14px;display:flex;align-items:center;justify-content:space-between;padding-bottom:8px;cursor:pointer}.GitStashCard-module__IconContainer--jTFC7{flex-basis:40px}.GitStashCard-module__ToggleContainer--Nodix{transform:translateX(8px)}.GitStashCard-module__Drawer--oKHPT{display:flex;flex-direction:column}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/VersionControlPanel/components/GitStashCard/GitStashCard.module.scss"],"names":[],"mappings":"AAEA,kCACE,iBAAA,CACA,iEAAA,CACA,+CAAA,CAEA,kFACE,wCAAA,CAIJ,mCACE,qBAAA,CAEA,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,kBAAA,CACA,cAAA,CAGF,2CACE,eAAA,CAGF,6CACE,yBAAA,CAGF,oCACE,YAAA,CACA,qBAAA","sourcesContent":["@use '@scss-variables/animation';\n\n.Root {\n  position: relative;\n  transition: background-color var(--speed-turbo) var(--easing-base);\n  border-bottom: 1px solid var(--theme-color-bg-1);\n\n  &:hover:not(.is-open) {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n.Inner {\n  padding: 8px 16px 14px;\n\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding-bottom: 8px;\n  cursor: pointer;\n}\n\n.IconContainer {\n  flex-basis: 40px;\n}\n\n.ToggleContainer {\n  transform: translateX(8px);\n}\n\n.Drawer {\n  display: flex;\n  flex-direction: column;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `GitStashCard-module__Root--nFnlg`,
	"is-open": `GitStashCard-module__is-open--jOBNs`,
	"Inner": `GitStashCard-module__Inner--_VPpV`,
	"IconContainer": `GitStashCard-module__IconContainer--jTFC7`,
	"ToggleContainer": `GitStashCard-module__ToggleContainer--Nodix`,
	"Drawer": `GitStashCard-module__Drawer--oKHPT`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 36650:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .scroll-decoration {
	position: absolute;
	top: 0;
	left: 0;
	height: 6px;
}`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/scrollDecoration/scrollDecoration.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kBAAkB;CAClB,MAAM;CACN,OAAO;CACP,WAAW;AACZ","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .scroll-decoration {\n\tposition: absolute;\n\ttop: 0;\n\tleft: 0;\n\theight: 6px;\n}"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 36890:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Y: () => (/* binding */ AiUtils)
/* harmony export */ });
/* harmony import */ var _noodl_platform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37218);

// NOTE: Would be nice to have a text buffer class where we can write text blocks,
//       perhaps with streaming and then fake stream out the text as it becomes ready.
//       This will create a really nice UX flow while the LLM is processing.
//       Maybe call it something like StreamingTextBuffer?
var AiUtils;
(function (AiUtils) {
    function generateSnowflakeId() {
        const timestamp = Date.now().toString(16).padStart(12, '0');
        const randomString = Math.random().toString(36).substring(2, 8);
        return `${timestamp}-${randomString}`;
    }
    AiUtils.generateSnowflakeId = generateSnowflakeId;
    /**
     * Alias for fakeTokenStream, just with a smaller delay.
     *
     * @param inputString
     * @param callback
     * @param options
     * @returns
     */
    function fakeTokenStreamFast(inputString, callback, options) {
        return fakeTokenStream(inputString, callback, { delay: [10, 25], ...(options || {}) });
    }
    AiUtils.fakeTokenStreamFast = fakeTokenStreamFast;
    async function fakeTokenStream(inputString, callback, options) {
        var _a, _b, _c;
        // Split the input string into smaller chunks (tokens) of 2 to 3 characters
        const tokens = [];
        let tokenLength;
        for (let i = 0; i < inputString.length; i += tokenLength) {
            tokenLength = Math.floor(Math.random() * 2 + 2);
            tokens.push(inputString.slice(i, i + tokenLength));
        }
        const delayMin = ((_a = options === null || options === void 0 ? void 0 : options.delay) === null || _a === void 0 ? void 0 : _a.length) === 2 ? Number(options.delay[0]) : 50;
        const delayMax = ((_b = options === null || options === void 0 ? void 0 : options.delay) === null || _b === void 0 ? void 0 : _b.length) === 2 ? Number(options.delay[1]) : 100;
        let fullText = '';
        // Iterate through the tokens and call the callback function with each token
        for (let i = 0; i < tokens.length; i++) {
            if ((_c = options === null || options === void 0 ? void 0 : options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {
                return;
            }
            fullText += tokens[i];
            callback(tokens[i], fullText);
            await _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.PromiseUtils.sleep(_noodl_platform__WEBPACK_IMPORTED_MODULE_0__.RandomUtils.range(delayMin, delayMax));
        }
    }
    AiUtils.fakeTokenStream = fakeTokenStream;
})(AiUtils || (AiUtils = {}));


/***/ }),

/***/ 37015:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InternalServerError = exports.RateLimitError = exports.UnprocessableEntityError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.AuthenticationError = exports.BadRequestError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIUserAbortError = exports.APIError = exports.AnthropicError = void 0;
const errors_1 = __webpack_require__(29820);
class AnthropicError extends Error {
}
exports.AnthropicError = AnthropicError;
class APIError extends AnthropicError {
    constructor(status, error, message, headers) {
        super(`${APIError.makeMessage(status, error, message)}`);
        this.status = status;
        this.headers = headers;
        this.requestID = headers?.get('request-id');
        this.error = error;
    }
    static makeMessage(status, error, message) {
        const msg = error?.message ?
            typeof error.message === 'string' ?
                error.message
                : JSON.stringify(error.message)
            : error ? JSON.stringify(error)
                : message;
        if (status && msg) {
            return `${status} ${msg}`;
        }
        if (status) {
            return `${status} status code (no body)`;
        }
        if (msg) {
            return msg;
        }
        return '(no status code or body)';
    }
    static generate(status, errorResponse, message, headers) {
        if (!status || !headers) {
            return new APIConnectionError({ message, cause: (0, errors_1.castToError)(errorResponse) });
        }
        const error = errorResponse;
        if (status === 400) {
            return new BadRequestError(status, error, message, headers);
        }
        if (status === 401) {
            return new AuthenticationError(status, error, message, headers);
        }
        if (status === 403) {
            return new PermissionDeniedError(status, error, message, headers);
        }
        if (status === 404) {
            return new NotFoundError(status, error, message, headers);
        }
        if (status === 409) {
            return new ConflictError(status, error, message, headers);
        }
        if (status === 422) {
            return new UnprocessableEntityError(status, error, message, headers);
        }
        if (status === 429) {
            return new RateLimitError(status, error, message, headers);
        }
        if (status >= 500) {
            return new InternalServerError(status, error, message, headers);
        }
        return new APIError(status, error, message, headers);
    }
}
exports.APIError = APIError;
class APIUserAbortError extends APIError {
    constructor({ message } = {}) {
        super(undefined, undefined, message || 'Request was aborted.', undefined);
    }
}
exports.APIUserAbortError = APIUserAbortError;
class APIConnectionError extends APIError {
    constructor({ message, cause }) {
        super(undefined, undefined, message || 'Connection error.', undefined);
        // in some environments the 'cause' property is already declared
        // @ts-ignore
        if (cause)
            this.cause = cause;
    }
}
exports.APIConnectionError = APIConnectionError;
class APIConnectionTimeoutError extends APIConnectionError {
    constructor({ message } = {}) {
        super({ message: message ?? 'Request timed out.' });
    }
}
exports.APIConnectionTimeoutError = APIConnectionTimeoutError;
class BadRequestError extends APIError {
}
exports.BadRequestError = BadRequestError;
class AuthenticationError extends APIError {
}
exports.AuthenticationError = AuthenticationError;
class PermissionDeniedError extends APIError {
}
exports.PermissionDeniedError = PermissionDeniedError;
class NotFoundError extends APIError {
}
exports.NotFoundError = NotFoundError;
class ConflictError extends APIError {
}
exports.ConflictError = ConflictError;
class UnprocessableEntityError extends APIError {
}
exports.UnprocessableEntityError = UnprocessableEntityError;
class RateLimitError extends APIError {
}
exports.RateLimitError = RateLimitError;
class InternalServerError extends APIError {
}
exports.InternalServerError = InternalServerError;
//# sourceMappingURL=error.js.map

/***/ }),

/***/ 37149:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ListItem-module__Root--AOnMV{display:flex;flex-direction:row;align-items:center;cursor:pointer;user-select:none}.ListItem-module__Root--AOnMV.ListItem-module__is-hover--lSLwS,.ListItem-module__Root--AOnMV:hover:not(.ListItem-module__Root--AOnMV.ListItem-module__is-disabled--MlE7P){background-color:var(--theme-color-bg-3)}.ListItem-module__Root--AOnMV.ListItem-module__is-hover--lSLwS.ListItem-module__is-variant-highlighted--lNznQ,.ListItem-module__Root--AOnMV.ListItem-module__is-hover--lSLwS.ListItem-module__is-variant-highlighted-shy--t65Ga,.ListItem-module__Root--AOnMV:hover:not(.ListItem-module__Root--AOnMV.ListItem-module__is-disabled--MlE7P).ListItem-module__is-variant-highlighted--lNznQ,.ListItem-module__Root--AOnMV:hover:not(.ListItem-module__Root--AOnMV.ListItem-module__is-disabled--MlE7P).ListItem-module__is-variant-highlighted-shy--t65Ga{background-color:var(--theme-color-bg-4)}.ListItem-module__Root--AOnMV.ListItem-module__is-active--FzmHq{background-color:var(--theme-color-bg-1) !important}.ListItem-module__Root--AOnMV.ListItem-module__is-disabled--MlE7P{cursor:default}.ListItem-module__Root--AOnMV.ListItem-module__is-variant-shy--rMCg2 path,.ListItem-module__Root--AOnMV.ListItem-module__is-variant-highlighted-shy--t65Ga path{fill:var(--theme-color-fg-default-shy)}.ListItem-module__Root--AOnMV.ListItem-module__is-variant-default-contrast--bTAMi path,.ListItem-module__Root--AOnMV.ListItem-module__is-variant-default-contrast--bTAMi path{fill:var(--theme-color-fg-default-contrast)}.ListItem-module__Root--AOnMV.ListItem-module__is-showing-affix-on-hover--Q9BXL .ListItem-module__Affix--CP9Qg{opacity:0}.ListItem-module__Root--AOnMV.ListItem-module__is-showing-affix-on-hover--Q9BXL:hover .ListItem-module__Affix--CP9Qg{opacity:1}.ListItem-module__Root--AOnMV.ListItem-module__is-variant-active--gb3Aa{background-color:var(--theme-color-secondary) !important}.ListItem-module__Root--AOnMV.ListItem-module__is-variant-active--gb3Aa .ListItem-module__Prefix--vwuI5 path{fill:var(--theme-color-on-secondary) !important}.ListItem-module__Root--AOnMV.ListItem-module__is-variant-active--gb3Aa:hover{background-color:var(--theme-color-secondary-highlight) !important}.ListItem-module__Prefix--vwuI5,.ListItem-module__Affix--CP9Qg{flex-basis:40px;flex-grow:0;flex-shrink:0;display:flex;justify-content:center}.ListItem-module__Body--Nm5yU{flex:1 1;min-width:0;display:flex;align-items:center;padding-top:10px;padding-bottom:10px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/ListItem/ListItem.module.scss"],"names":[],"mappings":"AAAA,8BACE,YAAA,CACA,kBAAA,CACA,kBAAA,CACA,cAAA,CACA,gBAAA,CAEA,0KAEE,wCAAA,CAEA,whBAEE,wCAAA,CAIJ,gEACE,mDAAA,CAGF,kEACE,cAAA,CAKA,gKACE,sCAAA,CAMF,8KACE,2CAAA,CAKF,+GACE,SAAA,CAGF,qHACE,SAAA,CAIJ,wEACE,wDAAA,CAEA,6GACE,+CAAA,CAGF,8EACE,kEAAA,CAKN,+DAEE,eAAA,CACA,WAAA,CACA,aAAA,CACA,YAAA,CACA,sBAAA,CAGF,8BACE,QAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,gBAAA,CACA,mBAAA","sourcesContent":[".Root {\n  display: flex;\n  flex-direction: row;\n  align-items: center;\n  cursor: pointer;\n  user-select: none;\n\n  &.is-hover,\n  &:hover:not(&.is-disabled) {\n    background-color: var(--theme-color-bg-3);\n\n    &.is-variant-highlighted,\n    &.is-variant-highlighted-shy {\n      background-color: var(--theme-color-bg-4);\n    }\n  }\n\n  &.is-active {\n    background-color: var(--theme-color-bg-1) !important;\n  }\n\n  &.is-disabled {\n    cursor: default;\n  }\n\n  &.is-variant-shy,\n  &.is-variant-highlighted-shy {\n    path {\n      fill: var(--theme-color-fg-default-shy);\n    }\n  }\n\n  &.is-variant-default-contrast,\n  &.is-variant-default-contrast {\n    path {\n      fill: var(--theme-color-fg-default-contrast);\n    }\n  }\n\n  &.is-showing-affix-on-hover {\n    .Affix {\n      opacity: 0;\n    }\n\n    &:hover .Affix {\n      opacity: 1;\n    }\n  }\n\n  &.is-variant-active {\n    background-color: var(--theme-color-secondary) !important;\n\n    .Prefix path {\n      fill: var(--theme-color-on-secondary) !important;\n    }\n\n    &:hover {\n      background-color: var(--theme-color-secondary-highlight) !important;\n    }\n  }\n}\n\n.Prefix,\n.Affix {\n  flex-basis: 40px;\n  flex-grow: 0;\n  flex-shrink: 0;\n  display: flex;\n  justify-content: center;\n}\n\n.Body {\n  flex: 1 1;\n  min-width: 0;\n  display: flex;\n  align-items: center;\n  padding-top: 10px;\n  padding-bottom: 10px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ListItem-module__Root--AOnMV`,
	"is-hover": `ListItem-module__is-hover--lSLwS`,
	"is-disabled": `ListItem-module__is-disabled--MlE7P`,
	"is-variant-highlighted": `ListItem-module__is-variant-highlighted--lNznQ`,
	"is-variant-highlighted-shy": `ListItem-module__is-variant-highlighted-shy--t65Ga`,
	"is-active": `ListItem-module__is-active--FzmHq`,
	"is-variant-shy": `ListItem-module__is-variant-shy--rMCg2`,
	"is-variant-default-contrast": `ListItem-module__is-variant-default-contrast--bTAMi`,
	"is-showing-affix-on-hover": `ListItem-module__is-showing-affix-on-hover--Q9BXL`,
	"Affix": `ListItem-module__Affix--CP9Qg`,
	"is-variant-active": `ListItem-module__is-variant-active--gb3Aa`,
	"Prefix": `ListItem-module__Prefix--vwuI5`,
	"Body": `ListItem-module__Body--Nm5yU`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 37218:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  ConvertUtils: () => (/* reexport */ ConvertUtils),
  JSONStorage: () => (/* binding */ JSONStorage),
  PlatformOS: () => (/* reexport */ PlatformOS),
  PlatformWeb: () => (/* reexport */ PlatformWeb),
  PromiseUtils: () => (/* reexport */ PromiseUtils),
  RandomUtils: () => (/* reexport */ RandomUtils),
  StorageWeb: () => (/* reexport */ StorageWeb),
  addTrailingSlash: () => (/* reexport */ addTrailingSlash),
  filesystem: () => (/* binding */ filesystem),
  isElectron: () => (/* reexport */ isElectron),
  isNode: () => (/* reexport */ isNode),
  platform: () => (/* binding */ platform),
  setFileSystem: () => (/* binding */ setFileSystem),
  setPlatform: () => (/* binding */ setPlatform),
  setStorage: () => (/* binding */ setStorage)
});

;// ../noodl-platform/src/platform/common.ts
var PlatformOS;
(function (PlatformOS) {
    PlatformOS["Web"] = "web";
    PlatformOS["Windows"] = "windows";
    PlatformOS["MacOS"] = "macOS";
    PlatformOS["Linux"] = "linux";
    PlatformOS["Unknown"] = "unknown";
})(PlatformOS || (PlatformOS = {}));
// OSX and Windows add trailing slashes to the temp folder, Linux doesn't
function addTrailingSlash(path) {
    return path[path.length - 1] !== "/" ? path + "/" : path;
}

;// ../noodl-platform/src/platform/support.ts
/**
 * https://stackoverflow.com/a/61725416/3211243
 */
function isElectron() {
    // Renderer process
    // @ts-ignore window
    if (typeof window !== "undefined" &&
        typeof window.process === "object" &&
        // @ts-ignore
        window.process.type === "renderer") {
        return true;
    }
    // Main process
    if (typeof process !== "undefined" &&
        typeof process.versions === "object" &&
        !!process.versions.electron) {
        return true;
    }
    // Detect the user agent when the `nodeIntegration` option is set to true
    // @ts-ignore navigator
    if (typeof navigator === "object" &&
        typeof navigator.userAgent === "string" &&
        navigator.userAgent.indexOf("Electron") >= 0) {
        return true;
    }
    return false;
}
function isNode() {
    return (typeof process !== "undefined" &&
        process.release.name.search(/node|io.js/) !== -1);
}

;// ../noodl-platform/src/platform/platform-web.ts

class PlatformWeb {
    get name() {
        return 'Web';
    }
    get os() {
        return PlatformOS.Web;
    }
    constructor(_version, _versionTag, _buildNumber) {
        this._version = _version;
        this._versionTag = _versionTag;
        this._buildNumber = _buildNumber;
    }
    getBuildNumber() {
        return this._buildNumber;
    }
    getFullVersion() {
        return this._version + '-' + this._buildNumber;
    }
    getVersion() {
        return this._version;
    }
    getVersionWithTag() {
        return this._versionTag ? `${this._version}-${this._versionTag}` : this._version;
    }
    getUserDataPath() {
        return '/user';
    }
    getDocumentsPath() {
        return '/documents';
    }
    getTempPath() {
        return '/tmp';
    }
    getAppPath() {
        return '/app';
    }
    async openExternal(url) {
        window.open(url, '_blank').focus();
    }
    async copyToClipboard(value) {
        await navigator.clipboard.writeText(value);
    }
}

;// ../noodl-platform/src/platform/index.ts




;// ../noodl-platform/src/storage/storage-web.ts
class StorageWeb {
    get(key) {
        throw new Error("Method not implemented.");
    }
    set(key, data) {
        throw new Error("Method not implemented.");
    }
    remove(key) {
        throw new Error("Method not implemented.");
    }
}

;// ../noodl-platform/src/storage/index.ts



;// ../noodl-platform/src/utils/convert.ts
var ConvertUtils;
(function (ConvertUtils) {
    function bytesToKilobytes(bytes) {
        const kilobytes = bytes / 1024;
        return kilobytes;
    }
    ConvertUtils.bytesToKilobytes = bytesToKilobytes;
    function bytesToMegabytes(bytes) {
        const megabytes = bytes / (1024 * 1024);
        return megabytes;
    }
    ConvertUtils.bytesToMegabytes = bytesToMegabytes;
    function bytesToGigabytes(bytes) {
        const gigabytes = bytes / (1024 * 1024 * 1024);
        return gigabytes;
    }
    ConvertUtils.bytesToGigabytes = bytesToGigabytes;
    function bytesToMostSuitableSize(bytes) {
        if (bytes < 1024) {
            return bytes + ' bytes';
        }
        else if (bytes < 1024 * 1024) {
            return bytesToKilobytes(bytes).toFixed(2) + ' KB';
        }
        else if (bytes < 1024 * 1024 * 1024) {
            return bytesToMegabytes(bytes).toFixed(2) + ' MB';
        }
        else {
            return bytesToGigabytes(bytes).toFixed(2) + ' GB';
        }
    }
    ConvertUtils.bytesToMostSuitableSize = bytesToMostSuitableSize;
})(ConvertUtils || (ConvertUtils = {}));

;// ../noodl-platform/src/utils/promise.ts
var PromiseUtils;
(function (PromiseUtils) {
    async function allObjects(object) {
        return Object.fromEntries(await Promise.all(Object.entries(object).map(async ([key, promise]) => {
            return [key, await promise];
        })));
    }
    PromiseUtils.allObjects = allObjects;
    function sleep(ms) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }
    PromiseUtils.sleep = sleep;
})(PromiseUtils || (PromiseUtils = {}));

;// ../noodl-platform/src/utils/random.ts
var RandomUtils;
(function (RandomUtils) {
    function range(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }
    RandomUtils.range = range;
    function within(max) {
        return Math.floor(Math.random() * max);
    }
    RandomUtils.within = within;
})(RandomUtils || (RandomUtils = {}));

;// ../noodl-platform/src/utils/index.ts




;// ../noodl-platform/src/index.ts






let platform = new PlatformWeb('0.0.0', undefined, '0');
let filesystem;
let JSONStorage = new StorageWeb();

function setPlatform(value) {
    platform = value;
}
function setFileSystem(value) {
    filesystem = value;
}
function setStorage(value) {
    JSONStorage = value;
}


/***/ }),

/***/ 37664:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCloudUpload = function SvgCloudUpload(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 25,
    viewBox: "0 0 24 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M16.227 6.09906C14.9176 5.83861 13.5604 5.97229 12.327 6.48318C11.0936 6.99407 10.0394 7.85923 9.29774 8.96926C8.55604 10.0793 8.16016 11.3843 8.16016 12.7194C8.16016 13.1336 7.82437 13.4694 7.41016 13.4694C6.99594 13.4694 6.66016 13.1336 6.66016 12.7194C6.66016 11.958 6.76551 11.2045 6.97001 10.4796C6.86704 10.4727 6.76379 10.4693 6.66044 10.4694C5.46696 10.4694 4.32209 10.9435 3.47818 11.7874C2.63426 12.6313 2.16016 13.7759 2.16016 14.9694C2.16016 16.1628 2.63426 17.3074 3.47818 18.1513C4.32209 18.9953 5.46668 19.4694 6.66016 19.4694L14.9102 19.4694C16.2452 19.4694 17.5502 19.0735 18.6603 18.3318C19.7703 17.5901 20.6355 16.5359 21.1463 15.3025C21.6572 14.0691 21.7909 12.7119 21.5305 11.4025C21.27 10.0931 20.6271 8.8904 19.6831 7.94639C18.7391 7.00239 17.5364 6.35951 16.227 6.09906ZM7.53052 9.03107C7.68438 8.72321 7.85791 8.42418 8.05053 8.13591C8.95705 6.7792 10.2455 5.72178 11.753 5.09736C13.2605 4.47293 14.9193 4.30956 16.5197 4.62789C18.12 4.94621 19.59 5.73195 20.7438 6.88573C21.8976 8.03952 22.6833 9.50953 23.0016 11.1099C23.32 12.7102 23.1566 14.369 22.5322 15.8765C21.9077 17.384 20.8503 18.6725 19.4936 19.579C18.1369 20.4855 16.5419 20.9694 14.9102 20.9694L6.66016 20.9694C5.06886 20.9694 3.54273 20.3372 2.41752 19.212C1.2923 18.0868 0.660156 16.5607 0.660156 14.9694C0.660156 13.3781 1.2923 11.8519 2.41752 10.7267C3.54267 9.60157 5.06868 8.96944 6.65987 8.96936M7.53052 9.03107C7.24249 8.98993 6.95136 8.96927 6.65987 8.96936L7.53052 9.03107Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.5035 13.3806C12.2106 13.6735 11.7357 13.6735 11.4428 13.3806C11.1499 13.0877 11.1499 12.6129 11.4428 12.32L14.4196 9.34315C14.5227 9.2401 14.6483 9.1733 14.7805 9.14277C14.8083 9.13633 14.8367 9.13145 14.8657 9.1282C14.9016 9.12416 14.9379 9.12271 14.974 9.12387C15.1772 9.13021 15.36 9.21736 15.4914 9.35424L18.4571 12.32C18.75 12.6129 18.75 13.0877 18.4571 13.3806C18.1642 13.6735 17.6893 13.6735 17.3964 13.3806L15.7002 11.6844L15.7002 16.8984C15.7002 17.3126 15.3644 17.6484 14.9502 17.6484C14.536 17.6484 14.2002 17.3126 14.2002 16.8984L14.2002 11.6839L12.5035 13.3806Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCloudUpload);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "709e3beec24db358775492a4c74cb72e.svg");

/***/ }),

/***/ 37762:
/***/ ((module) => {

// Module
var code = "<div class=\"sidebar-panel\"> <div class=\"sidebar-property-editor\"> <div class=\"variants\"></div> <div class=\"visual-states\"></div> <div class=\"groups\"> </div> <div class=\"property-drop-down-padding\" style=\"position:relative;height:200px;visibility:hidden;width:100%;display:none\"> </div> </div> </div> ";
// Exports
module.exports = code;

/***/ }),

/***/ 37833:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Collapsible-module__Root--Jdq7_{display:block}.Collapsible-module__Inner--HqFar{display:flow-root;position:static}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/Collapsible/Collapsible.module.scss"],"names":[],"mappings":"AAAA,iCACE,aAAA,CAGF,kCACE,iBAAA,CACA,eAAA","sourcesContent":[".Root {\n  display: block;\n}\n\n.Inner {\n  display: flow-root;\n  position: static;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Collapsible-module__Root--Jdq7_`,
	"Inner": `Collapsible-module__Inner--HqFar`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 37837:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  d: () => (/* reexport */ PropertyPanelCheckbox)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/assets/icons/checkmark.svg
var checkmark = __webpack_require__(56182);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/property-panel/PropertyPanelCheckbox/PropertyPanelCheckbox.module.scss
var PropertyPanelCheckbox_module = __webpack_require__(78917);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelCheckbox/PropertyPanelCheckbox.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(PropertyPanelCheckbox_module/* default */.A, options);




       /* harmony default export */ const PropertyPanelCheckbox_PropertyPanelCheckbox_module = (PropertyPanelCheckbox_module/* default */.A && PropertyPanelCheckbox_module/* default */.A.locals ? PropertyPanelCheckbox_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelCheckbox/PropertyPanelCheckbox.tsx




function PropertyPanelCheckbox({ value, onChange, isConnected, isChanged }) {
    return (external_react_default().createElement("div", { className: PropertyPanelCheckbox_PropertyPanelCheckbox_module['Root'] },
        external_react_default().createElement("input", { type: "checkbox", checked: value, value: null, className: PropertyPanelCheckbox_PropertyPanelCheckbox_module['Checkbox'], onChange: () => onChange(!value) }),
        external_react_default().createElement("div", { className: external_classnames_default()(PropertyPanelCheckbox_PropertyPanelCheckbox_module['FauxCheckbox'], isChanged && PropertyPanelCheckbox_PropertyPanelCheckbox_module['is-changed'], isConnected && PropertyPanelCheckbox_PropertyPanelCheckbox_module['is-connected']) }, value && external_react_default().createElement(checkmark/* ReactComponent */.h, null))));
}

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelCheckbox/index.ts



/***/ }),

/***/ 37949:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   CodeHistoryManager: () => (/* binding */ CodeHistoryManager)
/* harmony export */ });
/* harmony import */ var _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6203);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47821);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_shared_model__WEBPACK_IMPORTED_MODULE_1__);
/**
 * CodeHistoryManager
 *
 * Manages automatic code snapshots for Expression, Function, and Script nodes.
 * Allows users to view history and restore previous versions.
 *
 * @module models
 */


/**
 * Manages code history for nodes
 */
class CodeHistoryManager extends (_shared_model__WEBPACK_IMPORTED_MODULE_1___default()) {
    constructor() {
        super(...arguments);
        this.MAX_SNAPSHOTS = 20;
    }
    /**
     * Save a code snapshot for a node
     * Only saves if code has actually changed (hash comparison)
     */
    saveSnapshot(nodeId, parameterName, code) {
        const node = this.getNode(nodeId);
        if (!node) {
            console.warn('CodeHistoryManager: Node not found:', nodeId);
            return;
        }
        // Don't save empty code
        if (!code || code.trim() === '') {
            return;
        }
        // Compute hash for deduplication
        const hash = this.hashCode(code);
        // Get existing history
        const history = this.getHistory(nodeId, parameterName);
        // Check if last snapshot is identical (deduplication)
        if (history.length > 0) {
            const lastSnapshot = history[history.length - 1];
            if (lastSnapshot.hash === hash) {
                // Code hasn't changed, don't create duplicate snapshot
                return;
            }
        }
        // Create new snapshot
        const snapshot = {
            code,
            timestamp: new Date().toISOString(),
            hash
        };
        // Add to history
        history.push(snapshot);
        // Prune old snapshots
        if (history.length > this.MAX_SNAPSHOTS) {
            history.splice(0, history.length - this.MAX_SNAPSHOTS);
        }
        // Save to node metadata
        this.saveHistory(node, parameterName, history);
        console.log(`📸 Code snapshot saved for node ${nodeId}, param ${parameterName} (${history.length} total)`);
    }
    /**
     * Get code history for a node parameter
     */
    getHistory(nodeId, parameterName) {
        const node = this.getNode(nodeId);
        if (!node) {
            return [];
        }
        const historyKey = this.getHistoryKey(parameterName);
        const metadata = node.metadata;
        if (!metadata || !metadata[historyKey]) {
            return [];
        }
        return metadata[historyKey];
    }
    /**
     * Restore a snapshot by timestamp
     * Returns the code from that snapshot
     */
    restoreSnapshot(nodeId, parameterName, timestamp) {
        const history = this.getHistory(nodeId, parameterName);
        const snapshot = history.find((s) => s.timestamp === timestamp);
        if (!snapshot) {
            console.warn('CodeHistoryManager: Snapshot not found:', timestamp);
            return undefined;
        }
        console.log(`↩️ Restoring snapshot from ${timestamp}`);
        return snapshot.code;
    }
    /**
     * Get a specific snapshot by timestamp
     */
    getSnapshot(nodeId, parameterName, timestamp) {
        const history = this.getHistory(nodeId, parameterName);
        return history.find((s) => s.timestamp === timestamp);
    }
    /**
     * Clear all history for a node parameter
     */
    clearHistory(nodeId, parameterName) {
        const node = this.getNode(nodeId);
        if (!node) {
            return;
        }
        const historyKey = this.getHistoryKey(parameterName);
        if (node.metadata) {
            delete node.metadata[historyKey];
        }
        console.log(`🗑️ Cleared history for node ${nodeId}, param ${parameterName}`);
    }
    /**
     * Get the node from the current project
     */
    getNode(nodeId) {
        const project = _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_0__.ProjectModel.instance;
        if (!project) {
            return undefined;
        }
        // Search all components for the node
        for (const component of project.getComponents()) {
            const graph = component.graph;
            if (!graph)
                continue;
            const node = graph.findNodeWithId(nodeId);
            if (node) {
                return node;
            }
        }
        return undefined;
    }
    /**
     * Save history to node metadata
     */
    saveHistory(node, parameterName, history) {
        const historyKey = this.getHistoryKey(parameterName);
        if (!node.metadata) {
            node.metadata = {};
        }
        node.metadata[historyKey] = history;
        // Notify that metadata changed (triggers project save)
        node.notifyListeners('metadataChanged');
    }
    /**
     * Get the metadata key for a parameter's history
     * Uses a prefix to avoid conflicts with other metadata
     */
    getHistoryKey(parameterName) {
        return `codeHistory_${parameterName}`;
    }
    /**
     * Compute a simple hash of code for deduplication
     * Not cryptographic, just for detecting changes
     */
    hashCode(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = (hash << 5) - hash + char;
            hash = hash & hash; // Convert to 32bit integer
        }
        return hash.toString(36);
    }
    /**
     * Format a timestamp for display
     * Returns human-readable relative time ("5 minutes ago", "Yesterday")
     */
    formatTimestamp(timestamp) {
        const now = new Date();
        const then = new Date(timestamp);
        const diffMs = now.getTime() - then.getTime();
        const diffSec = Math.floor(diffMs / 1000);
        const diffMin = Math.floor(diffSec / 60);
        const diffHour = Math.floor(diffMin / 60);
        const diffDay = Math.floor(diffHour / 24);
        if (diffSec < 60) {
            return 'just now';
        }
        else if (diffMin < 60) {
            return `${diffMin} minute${diffMin === 1 ? '' : 's'} ago`;
        }
        else if (diffHour < 24) {
            return `${diffHour} hour${diffHour === 1 ? '' : 's'} ago`;
        }
        else if (diffDay === 1) {
            return 'yesterday at ' + then.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        }
        else if (diffDay < 7) {
            return `${diffDay} days ago`;
        }
        else {
            // Full date for older snapshots
            return then.toLocaleDateString() + ' at ' + then.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        }
    }
}
CodeHistoryManager.instance = new CodeHistoryManager();


/***/ }),

/***/ 38332:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   W: () => (/* binding */ getBranchesOld),
/* harmony export */   p9: () => (/* binding */ getBranches)
/* harmony export */ });
/* unused harmony export getBranchesDifferingFromUpstream */
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85869);
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81882);
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(dugite__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _models_branch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(16279);
/* harmony import */ var _models_commit_identity__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(80760);
/* harmony import */ var _git_delimiter_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(40619);





/** Get all the branches. */
async function getBranches(repositoryDir, ...prefixes) {
    const { formatArgs, parse } = (0,_git_delimiter_parser__WEBPACK_IMPORTED_MODULE_4__/* .createForEachRefParser */ .n)({
        fullName: "%(refname)",
        shortName: "%(refname:short)",
        upstreamShortName: "%(upstream:short)",
        sha: "%(objectname)",
        author: "%(author)",
        symRef: "%(symref)",
    });
    if (!prefixes || !prefixes.length) {
        prefixes = ["refs/heads", "refs/remotes"];
    }
    const result = await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)(["for-each-ref", ...formatArgs, ...prefixes], repositoryDir, "getBranches", {
        expectedErrors: new Set([dugite__WEBPACK_IMPORTED_MODULE_1__.GitError.NotAGitRepository]),
    });
    if (result.gitError === dugite__WEBPACK_IMPORTED_MODULE_1__.GitError.NotAGitRepository) {
        return [];
    }
    const allBranches = [];
    const parsedLines = parse(result.output.toString());
    for (const ref of parsedLines) {
        // excude symbolic refs from the branch list
        if (ref.symRef.length > 0) {
            continue;
        }
        const author = _models_commit_identity__WEBPACK_IMPORTED_MODULE_3__/* .CommitIdentity */ .S.parseIdentity(ref.author);
        const tip = { sha: ref.sha, author };
        const type = ref.fullName.startsWith("refs/heads")
            ? _models_branch__WEBPACK_IMPORTED_MODULE_2__/* .BranchType */ .Rk.Local
            : _models_branch__WEBPACK_IMPORTED_MODULE_2__/* .BranchType */ .Rk.Remote;
        const upstream = ref.upstreamShortName.length > 0 ? ref.upstreamShortName : null;
        allBranches.push(new _models_branch__WEBPACK_IMPORTED_MODULE_2__/* .Branch */ .lg(ref.shortName, upstream, tip, type, ref.fullName));
    }
    // Combine into one array where "Branch.remote" will be the remote branch if it exists.
    const branches = [];
    for (const branch of allBranches) {
        const index = branches.findIndex((x) => x.upstream == branch.name);
        if (index !== -1) {
            branches[index] =
                branch.type === _models_branch__WEBPACK_IMPORTED_MODULE_2__/* .BranchType */ .Rk.Local
                    ? branch.withRemote(branches[index])
                    : branches[index].withRemote(branch);
        }
        else {
            branches.push(branch);
        }
    }
    return branches;
}
/** Get all the branches. */
async function getBranchesOld(repositoryDir, ...prefixes) {
    const { formatArgs, parse } = (0,_git_delimiter_parser__WEBPACK_IMPORTED_MODULE_4__/* .createForEachRefParser */ .n)({
        fullName: "%(refname)",
        shortName: "%(refname:short)",
        upstreamShortName: "%(upstream:short)",
        sha: "%(objectname)",
        author: "%(author)",
        symRef: "%(symref)",
    });
    if (!prefixes || !prefixes.length) {
        prefixes = ["refs/heads", "refs/remotes"];
    }
    const result = await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)(["for-each-ref", ...formatArgs, ...prefixes], repositoryDir, "getBranches", {
        expectedErrors: new Set([dugite__WEBPACK_IMPORTED_MODULE_1__.GitError.NotAGitRepository]),
    });
    if (result.gitError === dugite__WEBPACK_IMPORTED_MODULE_1__.GitError.NotAGitRepository) {
        return [];
    }
    const allBranches = [];
    const parsedLines = parse(result.output.toString());
    for (const ref of parsedLines) {
        // excude symbolic refs from the branch list
        if (ref.symRef.length > 0) {
            continue;
        }
        const author = _models_commit_identity__WEBPACK_IMPORTED_MODULE_3__/* .CommitIdentity */ .S.parseIdentity(ref.author);
        const tip = { sha: ref.sha, author };
        const type = ref.fullName.startsWith("refs/heads")
            ? _models_branch__WEBPACK_IMPORTED_MODULE_2__/* .BranchType */ .Rk.Local
            : _models_branch__WEBPACK_IMPORTED_MODULE_2__/* .BranchType */ .Rk.Remote;
        const upstream = ref.upstreamShortName.length > 0 ? ref.upstreamShortName : null;
        allBranches.push(new _models_branch__WEBPACK_IMPORTED_MODULE_2__/* .Branch */ .lg(ref.shortName, upstream, tip, type, ref.fullName));
    }
    return allBranches;
}
/**
 * Gets all branches that differ from their upstream (i.e. they're ahead,
 * behind or both), excluding the current branch.
 * Useful to narrow down a list of branches that could potentially be fast
 * forwarded.
 *
 * @param repositoryDir Repository to get the branches from.
 */
async function getBranchesDifferingFromUpstream(repositoryDir) {
    const { formatArgs, parse } = createForEachRefParser({
        fullName: "%(refname)",
        sha: "%(objectname)", // SHA
        upstream: "%(upstream)",
        symref: "%(symref)",
        head: "%(HEAD)",
    });
    const prefixes = ["refs/heads", "refs/remotes"];
    const result = await git(["for-each-ref", ...formatArgs, ...prefixes], repositoryDir, "getBranchesDifferingFromUpstream", { expectedErrors: new Set([GitError.NotAGitRepository]) });
    if (result.gitError === GitError.NotAGitRepository) {
        return [];
    }
    const localBranches = [];
    const remoteBranchShas = new Map();
    // First we need to collect the relevant info from the command output:
    // - For local branches with upstream: name, ref, SHA and the upstream.
    // - For remote branches we only need the sha (and the ref as key).
    for (const ref of parse(result.output.toString())) {
        if (ref.symref.length > 0 || ref.head === "*") {
            // Exclude symbolic refs and the current branch
            continue;
        }
        if (ref.fullName.startsWith("refs/heads")) {
            if (ref.upstream.length === 0) {
                // Exclude local branches without upstream
                continue;
            }
            localBranches.push({
                ref: ref.fullName,
                sha: ref.sha,
                upstream: ref.upstream,
            });
        }
        else {
            remoteBranchShas.set(ref.fullName, ref.sha);
        }
    }
    const eligibleBranches = new Array();
    // Compare the SHA of every local branch with the SHA of its upstream and
    // collect the names of local branches that differ from their upstream.
    for (const branch of localBranches) {
        const remoteSha = remoteBranchShas.get(branch.upstream);
        if (remoteSha !== undefined && remoteSha !== branch.sha) {
            eligibleBranches.push({
                ref: branch.ref,
                sha: branch.sha,
                upstreamRef: branch.upstream,
                upstreamSha: remoteSha,
            });
        }
    }
    return eligibleBranches;
}


/***/ }),

/***/ 38483:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   V: () => (/* binding */ extractLetters)
/* harmony export */ });
function extractLetters(string) {
    return string.replace(/[0-9]/g, '');
}


/***/ }),

/***/ 38495:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (/* binding */ AuthenticationErrors)
/* harmony export */ });
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81882);
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(dugite__WEBPACK_IMPORTED_MODULE_0__);

/** The set of errors which fit under the "authentication failed" umbrella. */
const AuthenticationErrors = new Set([
    dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.HTTPSAuthenticationFailed,
    dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.SSHAuthenticationFailed,
    dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.HTTPSRepositoryNotFound,
    dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.SSHRepositoryNotFound
]);


/***/ }),

/***/ 38656:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(80002),
  Path = __webpack_require__(16928);
var mkdirp = __webpack_require__(12055);
var JSZip = __webpack_require__(69856);
var fs = __webpack_require__(79896);
var md5File = __webpack_require__(69315);
var fse = __webpack_require__(59638);

const { dialog } = __webpack_require__(52391);

//OSX and Windows add trailing slashes to the temp folder, Linux doesn't
function addTrailingSlash(path) {
  return path[path.length - 1] !== '/' ? path + '/' : path;
}

var userDataPath = (__webpack_require__(52391).app).getPath('userData');
var documentsPath = (__webpack_require__(52391).app).getPath('documents');
var tempPath = addTrailingSlash((__webpack_require__(52391).app).getPath('temp'));
var appPath = addTrailingSlash((__webpack_require__(52391).app).getAppPath());

var FileSystem = new (function () {})();

FileSystem.instance = {
  promises: {
    readFile(path) {
      return fs.promises.readFile(path, 'utf8');
    },
    async readJSONFile(path) {
      const fileContent = await fs.promises.readFile(path, 'utf8');
      return JSON.parse(fileContent);
    },
    writeFile(path, content) {
      return fs.promises.writeFile(path, Buffer.from(content));
    },
    // TODO: This can be done with a flag?
    async writeFileOverride(path, content) {
      try {
        await this.removeFile(path);
      } catch (error) {
        // noop
      }

      await this.writeFile(path, content);
    },
    removeFile(path) {
      return fs.promises.unlink(path);
    }
  },

  getUserDataPath: function () {
    return userDataPath;
  },
  getDocumentsPath: function () {
    return Path.join(documentsPath, '/Noodl/');
  },
  getTempPath: function () {
    return tempPath;
  },
  getAppPath: function () {
    return appPath;
  },
  readJSONFile: function (path, callback) {
    fs.readFile(path, 'utf8', function (err, data) {
      if (err) {
        callback();
        return;
      }

      let json;
      try {
        json = JSON.parse(data);
      } catch (e) {
        callback();
      }

      if (json) {
        callback(json);
      }
    });
  },
  readTextFile: function (path, callback) {
    fs.readFile(path, 'utf8', function (err, data) {
      if (err) {
        callback();
        return;
      }

      callback(data);
    });
  },
  readFileSync: function (path, opts) {
    return fs.readFileSync(path, opts);
  },
  md5ForFileSync: function (path) {
    return md5File.sync(path);
  },
  writeJSONFile: function (path, json, callback) {
    try {
      fs.writeFileSync(path, JSON.stringify(json, null, 4));
      callback && callback({ result: 'success' });
    } catch (e) {
      console.log('Error writing json file', e);
      callback && callback({ result: 'failure', message: e.toString() });
    }
  },
  writeFileSync: function (path, content) {
    fs.writeFileSync(path, content);
  },
  writeFile: function (path, content, callback) {
    fs.writeFile(path, Buffer.from(content), function (err) {
      if (err) {
        callback({ result: 'failure' });
      } else {
        callback({ result: 'success' });
      }
    });
  },
  removeFile: function (path, callback) {
    fs.unlink(path, function (err) {
      if (err) {
        callback({ result: 'failure' });
      } else {
        callback({ result: 'success' });
      }
    });
  },
  removeFileSync: function (path) {
    return fs.unlinkSync(path);
  },
  getFileMetadata: function (path, callback) {
    fs.stat(path, function (err, stats) {
      if (err) callback();
      else {
        callback({
          modificationTime: stats.mtime
        });
      }
    });
  },
  getFileDirectoryName: function (path) {
    return Path.dirname(path);
  },
  downloadAsDataURI: function (url, callback, options) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    if (options && options.headers) {
      for (var key in options.headers) {
        xhr.setRequestHeader(key, options.headers[key]);
      }
    }
    xhr.responseType = 'blob';
    xhr.onload = function (e) {
      if (this.status === 200) {
        callback(URL.createObjectURL(this.response));
      } else callback();
    };
    xhr.onerror = function () {
      callback();
    };
    xhr.responseType = 'blob';
    xhr.send();
    /*datauri.encode(path, function(err, content) {
      if(err) callback();
      else callback(content);
    });*/
  },
  copyFile: function (source, target, callback) {
    var cbCalled = false;

    var rd = fs.createReadStream(source);
    rd.on('error', function (err) {
      done(err);
    });
    var wr = fs.createWriteStream(target);
    wr.on('error', function (err) {
      done(err);
    });
    wr.on('close', function (ex) {
      done();
    });
    rd.pipe(wr);

    function done(err) {
      if (!cbCalled) {
        if (err) callback({ result: 'failure' });
        else callback({ result: 'success' });
        cbCalled = true;
      }
    }
  },
  readDirectory: function (path, callback) {
    fs.readdir(path, function (err, files) {
      if (err) callback();
      else
        callback(
          files.map(function (f) {
            return {
              fullPath: path + '/' + f,
              name: f,
              isDirectory: fs.lstatSync(path + '/' + f).isDirectory()
            };
          })
        );
    });
  },
  readDirectorySync: function (path) {
    return fs.readdirSync(path).map(function (f) {
      return {
        fullPath: path + '/' + f,
        name: f,
        isDirectory: fs.lstatSync(path + '/' + f).isDirectory()
      };
    });
  },
  makeDirectory: function (path, callback) {
    if (path.length === 0 || fs.existsSync(path)) {
      callback({ result: 'success' });
      return;
    }

    mkdirp(path, function (err) {
      if (err) callback({ result: 'failure', err: err });
      else callback({ result: 'success' });
    });
  },
  /**
   * makeDirectoryAsync with promise
   * @param {string} path
   * @returns {Promise<void>}
   */
  makeDirectoryAsync(path) {
    if (path.length === 0 || fs.existsSync(path)) {
      return;
    }

    return new Promise((resolve, reject) => {
      mkdirp(path, function (err) {
        if (err) reject({ result: 'failure', err: err });
        else resolve({ result: 'success' });
      });
    });
  },
  makeDirectorySync: function (path, callback) {
    mkdirp.sync(path);
  },
  listFilesRecursiveSync: function (dir, _objects, _rootDir) {
    var objects = _objects || {};
    var rootDir = _rootDir || dir;

    if (!FileSystem.instance.fileExistsSync(dir)) return objects;

    var files = FileSystem.instance.readDirectorySync(dir);

    if (!files) {
      return objects;
    }

    const ignore = { '.DS_Store': true, '.git': true, __MACOSX: true };

    for (var i = 0; i < files.length; i++) {
      var f = files[i];

      if (ignore[f.name]) continue;

      var stats = FileSystem.instance.stat(f.fullPath);
      if (stats.isDirectory()) {
        FileSystem.instance.listFilesRecursiveSync(f.fullPath, objects, rootDir);
      } else {
        objects[f.fullPath.substring(rootDir.length)] = true;
      }
    }

    return objects;
  },
  syncDirsRecursiveSync: function (src, dst) {
    const srcFiles = FileSystem.instance.listFilesRecursiveSync(src);
    const dstFiles = FileSystem.instance.listFilesRecursiveSync(dst);
    const allFiles = {};
    for (var key in srcFiles) allFiles[key] = true;

    for (var key in dstFiles) allFiles[key] = true;

    var errors = [];
    for (var key in allFiles) {
      if (srcFiles[key] === undefined) {
        // Remove file
        try {
          FileSystem.instance.removeFileSync(Path.join(dst, key));
        } catch (e) {
          errors.push(e);
        }
      } else {
        try {
          FileSystem.instance.copyRecursiveSync(Path.join(src, key), Path.join(dst, key));
        } catch (e) {
          errors.push(e);
        }
      }
    }

    if (errors.length > 0) {
      const e = new Error('There were errors during sync');
      e.syncFileErrors = erros;
      throw e;
    }
  },
  copyRecursiveSync: function (src, dest, options) {
    /* var _this = this;

    if(src === dest) {
      callback();
      return;
    }

    var exists = fs.existsSync(src);
    var stats = exists && fs.statSync(src);
    var isDirectory = exists && stats.isDirectory();
    if (exists && isDirectory) {
      mkdirp.sync(dest);
      fs.readdirSync(src).forEach(function(childItemName) {
        _this.copyRecursive(Path.join(src, childItemName),
                          Path.join(dest, childItemName));
      });
    } else {
      fs.linkSync(src, dest);
    }*/

    fse.copySync(src, dest, options);
  },
  removeDirectoryRecursiveSync: function (path) {
    fse.removeSync(path);
  },
  removeDirectoryRecursive: function (path, callback) {
    var _this = this;
    if (fs.existsSync(path)) {
      fs.readdirSync(path).forEach(function (file, index) {
        var curPath = Path.join(path, file);
        if (fs.lstatSync(curPath).isDirectory()) {
          // recurse
          _this.removeDirectoryRecursive(curPath);
        } else {
          // delete file
          fs.unlinkSync(curPath);
        }
      });
      fs.rmdirSync(path);
    }
    callback && callback();
  },
  isPathDirectory: function (path) {
    return fs.lstatSync(path).isDirectory();
  },
  isDirectoryEmpty: function (path, callback) {
    this.readDirectory(path, function (files) {
      if (files.length === 0) callback(true);
      else callback(false);
    });
  },
  isDirectoryEmptySync: function (path) {
    const files = this.readDirectorySync(path);
    return files === undefined || files.length === 0;
  },
  unzipToFolder: function (path, blob, callback) {
    var _this = this;

    JSZip.loadAsync(blob)
      .then(function (zip) {
        var numFiles = Object.keys(zip.files).length;
        var err = false;
        function fileCompleted() {
          numFiles--;
          if (numFiles === 0) {
            if (err) callback({ result: 'failure' });
            else callback({ result: 'success' });
          }
        }

        Object.keys(zip.files).forEach(function (filename) {
          if (zip.files[filename].dir) {
            fileCompleted();
            return;
          } // Ignore dirs

          zip
            .file(filename)
            .async('nodebuffer')
            .then(
              function (buffer) {
                var dest = Path.join(path, filename);
                _this.makeDirectory(Path.dirname(dest), function (r) {
                  if (r.result !== 'success') fileCompleted(false);
                  else {
                    fs.writeFileSync(dest, buffer);
                    fileCompleted();
                  }
                });
              },
              function error(e) {
                err = e;
                fileCompleted(false);
              }
            );
        });
      })
      .catch(function (e) {
        callback({ result: 'failure' });
      });
  },
  fileExists: function (path, callback) {
    fs.exists(path, callback);
  },
  fileExistsSync: function (path) {
    return fs.existsSync(path);
  },
  makeUniquePath: function (path) {
    var _path = path;
    var count = 1;
    while (fs.existsSync(_path)) {
      _path = path + '-' + count;
      count++;
    }
    return _path;
  },
  rename: function (oldPath, newPath) {
    fs.renameSync(oldPath, newPath);
  },
  fileEntryFromPath: function (path) {
    return { fullPath: path, name: Path.basename(path), isDirectory: fs.lstatSync(path).isDirectory() };
  },
  stat: function (path) {
    return fs.lstatSync(path);
  },
  getFileCountAndTotalSize: function (dirPath) {
    const files = fs.readdirSync(dirPath);

    const info = { count: 0, size: 0 };

    files.forEach((file) => {
      const p = Path.join(dirPath, file);
      if (fs.statSync(p).isDirectory()) {
        const _info = this.getFileCountAndTotalSize(p);
        info.size += _info.size;
        info.count += _info.count;
      } else {
        info.count++;
        info.size += fs.statSync(p).size;
      }
    });

    return info;
  },
  chooseDirectory: function (callback, args) {
    const properties = ['openDirectory'];
    if (args && args.allowCreateDirectory) {
      properties.push('createDirectory');
    }

    dialog.showOpenDialog({ properties }).then((res) => {
      if (res.canceled) {
        callback();
      } else {
        callback(res.filePaths[0]);
      }
    });
  },
  chooseFile: function (callback, options) {
    $('#__hiddenFileInput__').remove();
    $('body').append('<input style="display:none" id="__hiddenFileInput__"  type="file" accept="application/json"  />');

    var hiddenFileInput = $('#__hiddenFileInput__');
    hiddenFileInput.one('change', function () {
      var files = _.pluck($('#__hiddenFileInput__')[0].files, 'path');
      $('#__hiddenFileInput__').remove();

      callback(files[0]);
    });
    hiddenFileInput.click();
  },
  forEachFileRecursive: function (startPath, callback) {
    if (!fs.existsSync(startPath)) return;

    var files = fs.readdirSync(startPath);
    for (var i = 0; i < files.length; i++) {
      var filename = Path.join(startPath, files[i]);
      var stat = fs.lstatSync(filename);
      if (stat.isDirectory()) {
        var abort = this.forEachFileRecursive(filename, callback); //recurse
        if (abort) return true;
      } else {
        var abort = callback(files[i], startPath);
        if (abort) return true;
      }
    }
  }
};

module.exports = FileSystem;


/***/ }),

/***/ 38770:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .inputarea {
	min-width: 0;
	min-height: 0;
	margin: 0;
	padding: 0;
	position: absolute;
	outline: none !important;
	resize: none;
	border: none;
	overflow: hidden;
	color: transparent;
	background-color: transparent;
}
/*.monaco-editor .inputarea {
	position: fixed !important;
	width: 800px !important;
	height: 500px !important;
	top: initial !important;
	left: initial !important;
	bottom: 0 !important;
	right: 0 !important;
	color: black !important;
	background: white !important;
	line-height: 15px !important;
	font-size: 14px !important;
}*/
.monaco-editor .inputarea.ime-input {
	z-index: 10;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/controller/textAreaHandler.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,YAAY;CACZ,aAAa;CACb,SAAS;CACT,UAAU;CACV,kBAAkB;CAClB,wBAAwB;CACxB,YAAY;CACZ,YAAY;CACZ,gBAAgB;CAChB,kBAAkB;CAClB,6BAA6B;AAC9B;AACA;;;;;;;;;;;;EAYE;AACF;CACC,WAAW;AACZ","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .inputarea {\n\tmin-width: 0;\n\tmin-height: 0;\n\tmargin: 0;\n\tpadding: 0;\n\tposition: absolute;\n\toutline: none !important;\n\tresize: none;\n\tborder: none;\n\toverflow: hidden;\n\tcolor: transparent;\n\tbackground-color: transparent;\n}\n/*.monaco-editor .inputarea {\n\tposition: fixed !important;\n\twidth: 800px !important;\n\theight: 500px !important;\n\ttop: initial !important;\n\tleft: initial !important;\n\tbottom: 0 !important;\n\tright: 0 !important;\n\tcolor: black !important;\n\tbackground: white !important;\n\tline-height: 15px !important;\n\tfont-size: 14px !important;\n}*/\n.monaco-editor .inputarea.ime-input {\n\tz-index: 10;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 38870:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.concatBytes = concatBytes;
exports.encodeUTF8 = encodeUTF8;
exports.decodeUTF8 = decodeUTF8;
function concatBytes(buffers) {
    let length = 0;
    for (const buffer of buffers) {
        length += buffer.length;
    }
    const output = new Uint8Array(length);
    let index = 0;
    for (const buffer of buffers) {
        output.set(buffer, index);
        index += buffer.length;
    }
    return output;
}
let encodeUTF8_;
function encodeUTF8(str) {
    let encoder;
    return (encodeUTF8_ ??
        ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str);
}
let decodeUTF8_;
function decodeUTF8(bytes) {
    let decoder;
    return (decodeUTF8_ ??
        ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes);
}
//# sourceMappingURL=bytes.js.map

/***/ }),

/***/ 38880:
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Do not edit this file; automatically generated.

/* eslint-disable */
;(function(root, factory) {
  if (true) { // AMD
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(15811)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
		__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
		(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else // removed by dead control flow
{}
}(this, function(__parent__) {
var $=__parent__.__namespace__;
var lists_create_empty$$module$build$src$generators$javascript$lists=function(a,b){return["[]",Order$$module$build$src$generators$javascript$javascript_generator.ATOMIC]},lists_create_with$$module$build$src$generators$javascript$lists=function(a,b){const c=Array(a.itemCount_);for(let d=0;d<a.itemCount_;d++)c[d]=b.valueToCode(a,"ADD"+d,Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"null";return["["+c.join(", ")+"]",Order$$module$build$src$generators$javascript$javascript_generator.ATOMIC]},
lists_repeat$$module$build$src$generators$javascript$lists=function(a,b){const c=b.provideFunction_("listsRepeat",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(value, n) {
  var array = [];
  for (var i = 0; i < n; i++) {
    array[i] = value;
  }
  return array;
}
`),d=b.valueToCode(a,"ITEM",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"null";a=b.valueToCode(a,"NUM",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"0";return[c+"("+d+", "+a+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},lists_length$$module$build$src$generators$javascript$lists=function(a,b){return[(b.valueToCode(a,"VALUE",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||
"[]")+".length",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER]},lists_isEmpty$$module$build$src$generators$javascript$lists=function(a,b){return["!"+(b.valueToCode(a,"VALUE",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"[]")+".length",Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_NOT]},lists_indexOf$$module$build$src$generators$javascript$lists=function(a,b){const c=a.getFieldValue("END")==="FIRST"?"indexOf":"lastIndexOf",
d=b.valueToCode(a,"FIND",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";b=(b.valueToCode(a,"VALUE",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"[]")+"."+c+"("+d+")";return a.workspace.options.oneBasedIndex?[b+" + 1",Order$$module$build$src$generators$javascript$javascript_generator.ADDITION]:[b,Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},lists_getIndex$$module$build$src$generators$javascript$lists=
function(a,b){const c=a.getFieldValue("MODE")||"GET",d=a.getFieldValue("WHERE")||"FROM_START";var e=b.valueToCode(a,"VALUE",d==="RANDOM"?Order$$module$build$src$generators$javascript$javascript_generator.NONE:Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"[]";switch(d){case "FIRST":if(c==="GET")return[e+"[0]",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER];if(c==="GET_REMOVE")return[e+".shift()",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER];
if(c==="REMOVE")return e+".shift();\n";break;case "LAST":if(c==="GET")return[e+".slice(-1)[0]",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER];if(c==="GET_REMOVE")return[e+".pop()",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER];if(c==="REMOVE")return e+".pop();\n";break;case "FROM_START":a=b.getAdjusted(a,"AT");if(c==="GET")return[e+"["+a+"]",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER];if(c==="GET_REMOVE")return[e+
".splice("+a+", 1)[0]",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL];if(c==="REMOVE")return e+".splice("+a+", 1);\n";break;case "FROM_END":a=b.getAdjusted(a,"AT",1,!0);if(c==="GET")return[e+".slice("+a+")[0]",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL];if(c==="GET_REMOVE")return[e+".splice("+a+", 1)[0]",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL];if(c==="REMOVE")return e+".splice("+a+", 1);";
break;case "RANDOM":e=b.provideFunction_("listsGetRandomItem",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(list, remove) {
  var x = Math.floor(Math.random() * list.length);
  if (remove) {
    return list.splice(x, 1)[0];
  } else {
    return list[x];
  }
}
`)+"("+e+", "+(c!=="GET")+")";if(c==="GET"||c==="GET_REMOVE")return[e,Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL];if(c==="REMOVE")return e+";\n"}throw Error("Unhandled combination (lists_getIndex).");},lists_setIndex$$module$build$src$generators$javascript$lists=function(a,b){function c(){if(d.match(/^\w+$/))return"";const h=b.nameDB_.getDistinctName("tmpList",$.NameType$$module$build$src$core$names.VARIABLE),k="var "+h+" = "+d+";\n";d=h;return k}let d=b.valueToCode(a,
"LIST",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"[]";const e=a.getFieldValue("MODE")||"GET";var f=a.getFieldValue("WHERE")||"FROM_START";const g=b.valueToCode(a,"TO",Order$$module$build$src$generators$javascript$javascript_generator.ASSIGNMENT)||"null";switch(f){case "FIRST":if(e==="SET")return d+"[0] = "+g+";\n";if(e==="INSERT")return d+".unshift("+g+");\n";break;case "LAST":if(e==="SET")return c()+(d+"["+d+".length - 1] = "+g+";\n");if(e==="INSERT")return d+".push("+
g+");\n";break;case "FROM_START":a=b.getAdjusted(a,"AT");if(e==="SET")return d+"["+a+"] = "+g+";\n";if(e==="INSERT")return d+".splice("+a+", 0, "+g+");\n";break;case "FROM_END":a=b.getAdjusted(a,"AT",1,!1,Order$$module$build$src$generators$javascript$javascript_generator.SUBTRACTION);f=c();if(e==="SET")return f+(d+"["+d+".length - "+a+"] = "+g+";\n");if(e==="INSERT")return f+(d+".splice("+d+".length - "+a+", 0, "+g+");\n");break;case "RANDOM":a=c();f=b.nameDB_.getDistinctName("tmpX",$.NameType$$module$build$src$core$names.VARIABLE);
a+="var "+f+" = Math.floor(Math.random() * "+d+".length);\n";if(e==="SET")return a+(d+"["+f+"] = "+g+";\n");if(e==="INSERT")return a+(d+".splice("+f+", 0, "+g+");\n")}throw Error("Unhandled combination (lists_setIndex).");},lists_getSublist$$module$build$src$generators$javascript$lists=function(a,b){var c={FIRST:"First",LAST:"Last",FROM_START:"FromStart",FROM_END:"FromEnd"},d=b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"[]";const e=a.getFieldValue("WHERE1"),
f=a.getFieldValue("WHERE2");if(e==="FIRST"&&f==="LAST")d+=".slice(0)";else if(d.match(/^\w+$/)||e!=="FROM_END"&&f==="FROM_START"){switch(e){case "FROM_START":c=b.getAdjusted(a,"AT1");break;case "FROM_END":c=b.getAdjusted(a,"AT1",1,!1,Order$$module$build$src$generators$javascript$javascript_generator.SUBTRACTION);c=d+".length - "+c;break;case "FIRST":c="0";break;default:throw Error("Unhandled option (lists_getSublist).");}switch(f){case "FROM_START":b=b.getAdjusted(a,"AT2",1);break;case "FROM_END":b=
b.getAdjusted(a,"AT2",0,!1,Order$$module$build$src$generators$javascript$javascript_generator.SUBTRACTION);b=d+".length - "+b;break;case "LAST":b=d+".length";break;default:throw Error("Unhandled option (lists_getSublist).");}d=d+".slice("+c+", "+b+")"}else{const g=b.getAdjusted(a,"AT1");a=b.getAdjusted(a,"AT2");d=b.provideFunction_("subsequence"+c[e]+c[f],`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(sequence${e==="FROM_END"||e==="FROM_START"?", at1":""}${f==="FROM_END"||f==="FROM_START"?", at2":""}) {
  var start = ${getSubstringIndex$$module$build$src$generators$javascript$lists("sequence",e,"at1")};
  var end = ${getSubstringIndex$$module$build$src$generators$javascript$lists("sequence",f,"at2")} + 1;
  return sequence.slice(start, end);
}
`)+"("+d+(e==="FROM_END"||e==="FROM_START"?", "+g:"")+(f==="FROM_END"||f==="FROM_START"?", "+a:"")+")"}return[d,Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},lists_sort$$module$build$src$generators$javascript$lists=function(a,b){const c=b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL)||"[]",d=a.getFieldValue("DIRECTION")==="1"?1:-1;a=a.getFieldValue("TYPE");b=b.provideFunction_("listsGetSortCompare",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(type, direction) {
  var compareFuncs = {
    'NUMERIC': function(a, b) {
        return Number(a) - Number(b); },
    'TEXT': function(a, b) {
        return String(a) > String(b) ? 1 : -1; },
    'IGNORE_CASE': function(a, b) {
        return String(a).toLowerCase() > String(b).toLowerCase() ? 1 : -1; },
  };
  var compare = compareFuncs[type];
  return function(a, b) { return compare(a, b) * direction; };
}
      `);return[c+".slice().sort("+b+'("'+a+'", '+d+"))",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},lists_split$$module$build$src$generators$javascript$lists=function(a,b){let c=b.valueToCode(a,"INPUT",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER);b=b.valueToCode(a,"DELIM",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";a=a.getFieldValue("MODE");if(a==="SPLIT")c||(c="''"),a="split";else if(a==="JOIN")c||
(c="[]"),a="join";else throw Error("Unknown mode: "+a);return[c+"."+a+"("+b+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},lists_reverse$$module$build$src$generators$javascript$lists=function(a,b){return[(b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL)||"[]")+".slice().reverse()",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},controls_if$$module$build$src$generators$javascript$logic=
function(a,b){var c=0;let d="";b.STATEMENT_PREFIX&&(d+=b.injectId(b.STATEMENT_PREFIX,a));do{const e=b.valueToCode(a,"IF"+c,Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"false";let f=b.statementToCode(a,"DO"+c);b.STATEMENT_SUFFIX&&(f=b.prefixLines(b.injectId(b.STATEMENT_SUFFIX,a),b.INDENT)+f);d+=(c>0?" else ":"")+"if ("+e+") {\n"+f+"}";c++}while(a.getInput("IF"+c));if(a.getInput("ELSE")||b.STATEMENT_SUFFIX)c=a.getInput("ELSE")?b.statementToCode(a,"ELSE"):"",b.STATEMENT_SUFFIX&&
(c=b.prefixLines(b.injectId(b.STATEMENT_SUFFIX,a),b.INDENT)+c),d+=" else {\n"+c+"}";return d+"\n"},logic_compare$$module$build$src$generators$javascript$logic=function(a,b){const c={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">="}[a.getFieldValue("OP")],d=c==="=="||c==="!="?Order$$module$build$src$generators$javascript$javascript_generator.EQUALITY:Order$$module$build$src$generators$javascript$javascript_generator.RELATIONAL,e=b.valueToCode(a,"A",d)||"0";a=b.valueToCode(a,"B",d)||"0";return[e+" "+
c+" "+a,d]},logic_operation$$module$build$src$generators$javascript$logic=function(a,b){const c=a.getFieldValue("OP")==="AND"?"&&":"||",d=c==="&&"?Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_AND:Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_OR;let e=b.valueToCode(a,"A",d);a=b.valueToCode(a,"B",d);e||a?(b=c==="&&"?"true":"false",e||(e=b),a||(a=b)):a=e="false";return[e+" "+c+" "+a,d]},logic_negate$$module$build$src$generators$javascript$logic=
function(a,b){const c=Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_NOT;return["!"+(b.valueToCode(a,"BOOL",c)||"true"),c]},logic_boolean$$module$build$src$generators$javascript$logic=function(a,b){return[a.getFieldValue("BOOL")==="TRUE"?"true":"false",Order$$module$build$src$generators$javascript$javascript_generator.ATOMIC]},logic_null$$module$build$src$generators$javascript$logic=function(a,b){return["null",Order$$module$build$src$generators$javascript$javascript_generator.ATOMIC]},
logic_ternary$$module$build$src$generators$javascript$logic=function(a,b){const c=b.valueToCode(a,"IF",Order$$module$build$src$generators$javascript$javascript_generator.CONDITIONAL)||"false",d=b.valueToCode(a,"THEN",Order$$module$build$src$generators$javascript$javascript_generator.CONDITIONAL)||"null";a=b.valueToCode(a,"ELSE",Order$$module$build$src$generators$javascript$javascript_generator.CONDITIONAL)||"null";return[c+" ? "+d+" : "+a,Order$$module$build$src$generators$javascript$javascript_generator.CONDITIONAL]},
controls_repeat_ext$$module$build$src$generators$javascript$loops=function(a,b){let c;c=a.getField("TIMES")?String(Number(a.getFieldValue("TIMES"))):b.valueToCode(a,"TIMES",Order$$module$build$src$generators$javascript$javascript_generator.ASSIGNMENT)||"0";let d=b.statementToCode(a,"DO");d=b.addLoopTrap(d,a);a="";const e=b.nameDB_.getDistinctName("count",$.NameType$$module$build$src$core$names.VARIABLE);let f=c;c.match(/^\w+$/)||$.isNumber$$module$build$src$core$utils$string(c)||(f=b.nameDB_.getDistinctName("repeat_end",
$.NameType$$module$build$src$core$names.VARIABLE),a+="var "+f+" = "+c+";\n");return a+("for (var "+e+" = 0; "+e+" < "+f+"; "+e+"++) {\n"+d+"}\n")},controls_whileUntil$$module$build$src$generators$javascript$loops=function(a,b){const c=a.getFieldValue("MODE")==="UNTIL";let d=b.valueToCode(a,"BOOL",c?Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_NOT:Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"false",e=b.statementToCode(a,"DO");e=b.addLoopTrap(e,
a);c&&(d="!"+d);return"while ("+d+") {\n"+e+"}\n"},controls_for$$module$build$src$generators$javascript$loops=function(a,b){var c=b.getVariableName(a.getFieldValue("VAR")),d=b.valueToCode(a,"FROM",Order$$module$build$src$generators$javascript$javascript_generator.ASSIGNMENT)||"0",e=b.valueToCode(a,"TO",Order$$module$build$src$generators$javascript$javascript_generator.ASSIGNMENT)||"0";const f=b.valueToCode(a,"BY",Order$$module$build$src$generators$javascript$javascript_generator.ASSIGNMENT)||"1";
let g=b.statementToCode(a,"DO");g=b.addLoopTrap(g,a);if($.isNumber$$module$build$src$core$utils$string(d)&&$.isNumber$$module$build$src$core$utils$string(e)&&$.isNumber$$module$build$src$core$utils$string(f))b=Number(d)<=Number(e),a="for ("+c+" = "+d+"; "+c+(b?" <= ":" >= ")+e+"; "+c,c=Math.abs(Number(f)),a=c===1?a+(b?"++":"--"):a+((b?" += ":" -= ")+c),a+=") {\n"+g+"}\n";else{a="";let h=d;d.match(/^\w+$/)||$.isNumber$$module$build$src$core$utils$string(d)||(h=b.nameDB_.getDistinctName(c+"_start",
$.NameType$$module$build$src$core$names.VARIABLE),a+="var "+h+" = "+d+";\n");d=e;e.match(/^\w+$/)||$.isNumber$$module$build$src$core$utils$string(e)||(d=b.nameDB_.getDistinctName(c+"_end",$.NameType$$module$build$src$core$names.VARIABLE),a+="var "+d+" = "+e+";\n");e=b.nameDB_.getDistinctName(c+"_inc",$.NameType$$module$build$src$core$names.VARIABLE);a+="var "+e+" = ";a=$.isNumber$$module$build$src$core$utils$string(f)?a+(Math.abs(Number(f))+";\n"):a+("Math.abs("+f+");\n");a+="if ("+h+" > "+d+") {\n";
a+=b.INDENT+e+" = -"+e+";\n";a=a+"}\nfor ("+(c+" = "+h+"; "+e+" >= 0 ? "+c+" <= "+d+" : "+c+" >= "+d+"; "+c+" += "+e+") {\n"+g+"}\n")}return a},controls_forEach$$module$build$src$generators$javascript$loops=function(a,b){const c=b.getVariableName(a.getFieldValue("VAR"));var d=b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.ASSIGNMENT)||"[]";let e=b.statementToCode(a,"DO");e=b.addLoopTrap(e,a);a="";let f=d;d.match(/^\w+$/)||(f=b.nameDB_.getDistinctName(c+"_list",
$.NameType$$module$build$src$core$names.VARIABLE),a+="var "+f+" = "+d+";\n");d=b.nameDB_.getDistinctName(c+"_index",$.NameType$$module$build$src$core$names.VARIABLE);e=b.INDENT+c+" = "+f+"["+d+"];\n"+e;return a+("for (var "+d+" in "+f+") {\n"+e+"}\n")},controls_flow_statements$$module$build$src$generators$javascript$loops=function(a,b){let c="";b.STATEMENT_PREFIX&&(c+=b.injectId(b.STATEMENT_PREFIX,a));b.STATEMENT_SUFFIX&&(c+=b.injectId(b.STATEMENT_SUFFIX,a));if(b.STATEMENT_PREFIX){const d=a.getSurroundLoop();
d&&!d.suppressPrefixSuffix&&(c+=b.injectId(b.STATEMENT_PREFIX,d))}switch(a.getFieldValue("FLOW")){case "BREAK":return c+"break;\n";case "CONTINUE":return c+"continue;\n"}throw Error("Unknown flow statement.");},math_number$$module$build$src$generators$javascript$math=function(a,b){a=Number(a.getFieldValue("NUM"));return[String(a),a>=0?Order$$module$build$src$generators$javascript$javascript_generator.ATOMIC:Order$$module$build$src$generators$javascript$javascript_generator.UNARY_NEGATION]},math_arithmetic$$module$build$src$generators$javascript$math=
function(a,b){var c={ADD:[" + ",Order$$module$build$src$generators$javascript$javascript_generator.ADDITION],MINUS:[" - ",Order$$module$build$src$generators$javascript$javascript_generator.SUBTRACTION],MULTIPLY:[" * ",Order$$module$build$src$generators$javascript$javascript_generator.MULTIPLICATION],DIVIDE:[" / ",Order$$module$build$src$generators$javascript$javascript_generator.DIVISION],POWER:[null,Order$$module$build$src$generators$javascript$javascript_generator.NONE]}[a.getFieldValue("OP")];
const d=c[0];c=c[1];const e=b.valueToCode(a,"A",c)||"0";a=b.valueToCode(a,"B",c)||"0";return d?[e+d+a,c]:["Math.pow("+e+", "+a+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},math_single$$module$build$src$generators$javascript$math=function(a,b){const c=a.getFieldValue("OP");let d;if(c==="NEG")return a=b.valueToCode(a,"NUM",Order$$module$build$src$generators$javascript$javascript_generator.UNARY_NEGATION)||"0",a[0]==="-"&&(a=" "+a),["-"+a,Order$$module$build$src$generators$javascript$javascript_generator.UNARY_NEGATION];
a=c==="SIN"||c==="COS"||c==="TAN"?b.valueToCode(a,"NUM",Order$$module$build$src$generators$javascript$javascript_generator.DIVISION)||"0":b.valueToCode(a,"NUM",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"0";switch(c){case "ABS":d="Math.abs("+a+")";break;case "ROOT":d="Math.sqrt("+a+")";break;case "LN":d="Math.log("+a+")";break;case "EXP":d="Math.exp("+a+")";break;case "POW10":d="Math.pow(10,"+a+")";break;case "ROUND":d="Math.round("+a+")";break;case "ROUNDUP":d="Math.ceil("+
a+")";break;case "ROUNDDOWN":d="Math.floor("+a+")";break;case "SIN":d="Math.sin("+a+" / 180 * Math.PI)";break;case "COS":d="Math.cos("+a+" / 180 * Math.PI)";break;case "TAN":d="Math.tan("+a+" / 180 * Math.PI)"}if(d)return[d,Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL];switch(c){case "LOG10":d="Math.log("+a+") / Math.log(10)";break;case "ASIN":d="Math.asin("+a+") / Math.PI * 180";break;case "ACOS":d="Math.acos("+a+") / Math.PI * 180";break;case "ATAN":d="Math.atan("+
a+") / Math.PI * 180";break;default:throw Error("Unknown math operator: "+c);}return[d,Order$$module$build$src$generators$javascript$javascript_generator.DIVISION]},math_constant$$module$build$src$generators$javascript$math=function(a,b){return{PI:["Math.PI",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER],E:["Math.E",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER],GOLDEN_RATIO:["(1 + Math.sqrt(5)) / 2",Order$$module$build$src$generators$javascript$javascript_generator.DIVISION],
SQRT2:["Math.SQRT2",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER],SQRT1_2:["Math.SQRT1_2",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER],INFINITY:["Infinity",Order$$module$build$src$generators$javascript$javascript_generator.ATOMIC]}[a.getFieldValue("CONSTANT")]},math_number_property$$module$build$src$generators$javascript$math=function(a,b){var c={EVEN:[" % 2 === 0",Order$$module$build$src$generators$javascript$javascript_generator.MODULUS,
Order$$module$build$src$generators$javascript$javascript_generator.EQUALITY],ODD:[" % 2 === 1",Order$$module$build$src$generators$javascript$javascript_generator.MODULUS,Order$$module$build$src$generators$javascript$javascript_generator.EQUALITY],WHOLE:[" % 1 === 0",Order$$module$build$src$generators$javascript$javascript_generator.MODULUS,Order$$module$build$src$generators$javascript$javascript_generator.EQUALITY],POSITIVE:[" > 0",Order$$module$build$src$generators$javascript$javascript_generator.RELATIONAL,
Order$$module$build$src$generators$javascript$javascript_generator.RELATIONAL],NEGATIVE:[" < 0",Order$$module$build$src$generators$javascript$javascript_generator.RELATIONAL,Order$$module$build$src$generators$javascript$javascript_generator.RELATIONAL],DIVISIBLE_BY:[null,Order$$module$build$src$generators$javascript$javascript_generator.MODULUS,Order$$module$build$src$generators$javascript$javascript_generator.EQUALITY],PRIME:[null,Order$$module$build$src$generators$javascript$javascript_generator.NONE,
Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]};const d=a.getFieldValue("PROPERTY"),[e,f,g]=c[d];c=b.valueToCode(a,"NUMBER_TO_CHECK",f)||"0";d==="PRIME"?a=b.provideFunction_("mathIsPrime",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(n) {
  // https://en.wikipedia.org/wiki/Primality_test#Naive_methods
  if (n == 2 || n == 3) {
    return true;
  }
  // False if n is NaN, negative, is 1, or not whole.
  // And false if n is divisible by 2 or 3.
  if (isNaN(n) || n <= 1 || n % 1 !== 0 || n % 2 === 0 || n % 3 === 0) {
    return false;
  }
  // Check all the numbers of form 6k +/- 1, up to sqrt(n).
  for (var x = 6; x <= Math.sqrt(n) + 1; x += 6) {
    if (n % (x - 1) === 0 || n % (x + 1) === 0) {
      return false;
    }
  }
  return true;
}
`)+"("+c+")":d==="DIVISIBLE_BY"?(a=b.valueToCode(a,"DIVISOR",Order$$module$build$src$generators$javascript$javascript_generator.MODULUS)||"0",a=c+" % "+a+" === 0"):a=c+e;return[a,g]},math_change$$module$build$src$generators$javascript$math=function(a,b){const c=b.valueToCode(a,"DELTA",Order$$module$build$src$generators$javascript$javascript_generator.ADDITION)||"0";a=b.getVariableName(a.getFieldValue("VAR"));return a+" = (typeof "+a+" === 'number' ? "+a+" : 0) + "+c+";\n"},math_on_list$$module$build$src$generators$javascript$math=
function(a,b){var c=a.getFieldValue("OP");switch(c){case "SUM":a=b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"[]";a+=".reduce(function(x, y) {return x + y;}, 0)";break;case "MIN":a=b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"[]";a="Math.min.apply(null, "+a+")";break;case "MAX":a=b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"[]";a="Math.max.apply(null, "+
a+")";break;case "AVERAGE":c=b.provideFunction_("mathMean",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(myList) {
  return myList.reduce(function(x, y) {return x + y;}, 0) / myList.length;
}
`);a=b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"[]";a=c+"("+a+")";break;case "MEDIAN":c=b.provideFunction_("mathMedian",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(myList) {
  var localList = myList.filter(function (x) {return typeof x === 'number';});
  if (!localList.length) return null;
  localList.sort(function(a, b) {return b - a;});
  if (localList.length % 2 === 0) {
    return (localList[localList.length / 2 - 1] + localList[localList.length / 2]) / 2;
  } else {
    return localList[(localList.length - 1) / 2];
  }
}
`);a=b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"[]";a=c+"("+a+")";break;case "MODE":c=b.provideFunction_("mathModes",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(values) {
  var modes = [];
  var counts = [];
  var maxCount = 0;
  for (var i = 0; i < values.length; i++) {
    var value = values[i];
    var found = false;
    var thisCount;
    for (var j = 0; j < counts.length; j++) {
      if (counts[j][0] === value) {
        thisCount = ++counts[j][1];
        found = true;
        break;
      }
    }
    if (!found) {
      counts.push([value, 1]);
      thisCount = 1;
    }
    maxCount = Math.max(thisCount, maxCount);
  }
  for (var j = 0; j < counts.length; j++) {
    if (counts[j][1] === maxCount) {
      modes.push(counts[j][0]);
    }
  }
  return modes;
}
`);a=b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"[]";a=c+"("+a+")";break;case "STD_DEV":c=b.provideFunction_("mathStandardDeviation",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(numbers) {
  var n = numbers.length;
  if (!n) return null;
  var mean = numbers.reduce(function(x, y) {return x + y;}) / n;
  var variance = 0;
  for (var j = 0; j < n; j++) {
    variance += Math.pow(numbers[j] - mean, 2);
  }
  variance /= n;
  return Math.sqrt(variance);
}
`);a=b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"[]";a=c+"("+a+")";break;case "RANDOM":c=b.provideFunction_("mathRandomList",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(list) {
  var x = Math.floor(Math.random() * list.length);
  return list[x];
}
`);a=b.valueToCode(a,"LIST",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"[]";a=c+"("+a+")";break;default:throw Error("Unknown operator: "+c);}return[a,Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},math_modulo$$module$build$src$generators$javascript$math=function(a,b){const c=b.valueToCode(a,"DIVIDEND",Order$$module$build$src$generators$javascript$javascript_generator.MODULUS)||"0";a=b.valueToCode(a,"DIVISOR",Order$$module$build$src$generators$javascript$javascript_generator.MODULUS)||
"0";return[c+" % "+a,Order$$module$build$src$generators$javascript$javascript_generator.MODULUS]},math_constrain$$module$build$src$generators$javascript$math=function(a,b){const c=b.valueToCode(a,"VALUE",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"0",d=b.valueToCode(a,"LOW",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"0";a=b.valueToCode(a,"HIGH",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"Infinity";return["Math.min(Math.max("+
c+", "+d+"), "+a+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},math_random_int$$module$build$src$generators$javascript$math=function(a,b){const c=b.valueToCode(a,"FROM",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"0";a=b.valueToCode(a,"TO",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"0";return[b.provideFunction_("mathRandomInt",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(a, b) {
  if (a > b) {
    // Swap a and b to ensure a is smaller.
    var c = a;
    a = b;
    b = c;
  }
  return Math.floor(Math.random() * (b - a + 1) + a);
}
`)+"("+c+", "+a+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},math_random_float$$module$build$src$generators$javascript$math=function(a,b){return["Math.random()",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},math_atan2$$module$build$src$generators$javascript$math=function(a,b){const c=b.valueToCode(a,"X",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"0";return["Math.atan2("+(b.valueToCode(a,"Y",
Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"0")+", "+c+") / Math.PI * 180",Order$$module$build$src$generators$javascript$javascript_generator.DIVISION]},procedures_defreturn$$module$build$src$generators$javascript$procedures=function(a,b){const c=b.getProcedureName(a.getFieldValue("NAME"));var d="";b.STATEMENT_PREFIX&&(d+=b.injectId(b.STATEMENT_PREFIX,a));b.STATEMENT_SUFFIX&&(d+=b.injectId(b.STATEMENT_SUFFIX,a));d&&(d=b.prefixLines(d,b.INDENT));let e="";b.INFINITE_LOOP_TRAP&&
(e=b.prefixLines(b.injectId(b.INFINITE_LOOP_TRAP,a),b.INDENT));let f="";a.getInput("STACK")&&(f=b.statementToCode(a,"STACK"));let g="";a.getInput("RETURN")&&(g=b.valueToCode(a,"RETURN",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"");let h="";f&&g&&(h=d);g&&(g=b.INDENT+"return "+g+";\n");const k=[],l=a.getVars();for(let m=0;m<l.length;m++)k[m]=b.getVariableName(l[m]);d="function "+c+"("+k.join(", ")+") {\n"+d+e+f+h+g+"}";d=b.scrub_(a,d);b.definitions_["%"+c]=d;return null},
procedures_callreturn$$module$build$src$generators$javascript$procedures=function(a,b){const c=b.getProcedureName(a.getFieldValue("NAME")),d=[],e=a.getVars();for(let f=0;f<e.length;f++)d[f]=b.valueToCode(a,"ARG"+f,Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"null";return[c+"("+d.join(", ")+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},procedures_callnoreturn$$module$build$src$generators$javascript$procedures=function(a,b){return b.forBlock.procedures_callreturn(a,
b)[0]+";\n"},procedures_ifreturn$$module$build$src$generators$javascript$procedures=function(a,b){let c="if ("+(b.valueToCode(a,"CONDITION",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"false")+") {\n";b.STATEMENT_SUFFIX&&(c+=b.prefixLines(b.injectId(b.STATEMENT_SUFFIX,a),b.INDENT));a.hasReturnValue_?(a=b.valueToCode(a,"VALUE",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"null",c+=b.INDENT+"return "+a+";\n"):c+=b.INDENT+"return;\n";return c+
"}\n"},text$$module$build$src$generators$javascript$text=function(a,b){return[b.quote_(a.getFieldValue("TEXT")),Order$$module$build$src$generators$javascript$javascript_generator.ATOMIC]},text_join$$module$build$src$generators$javascript$text=function(a,b){switch(a.itemCount_){case 0:return["''",Order$$module$build$src$generators$javascript$javascript_generator.ATOMIC];case 1:return a=b.valueToCode(a,"ADD0",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''",forceString$$module$build$src$generators$javascript$text(a);
case 2:var c=b.valueToCode(a,"ADD0",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";a=b.valueToCode(a,"ADD1",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";return[forceString$$module$build$src$generators$javascript$text(c)[0]+" + "+forceString$$module$build$src$generators$javascript$text(a)[0],Order$$module$build$src$generators$javascript$javascript_generator.ADDITION];default:c=Array(a.itemCount_);for(let d=0;d<a.itemCount_;d++)c[d]=
b.valueToCode(a,"ADD"+d,Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";return["["+c.join(",")+"].join('')",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]}},text_append$$module$build$src$generators$javascript$text=function(a,b){const c=b.getVariableName(a.getFieldValue("VAR"));a=b.valueToCode(a,"TEXT",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";return c+" += "+forceString$$module$build$src$generators$javascript$text(a)[0]+
";\n"},text_length$$module$build$src$generators$javascript$text=function(a,b){return[(b.valueToCode(a,"VALUE",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"''")+".length",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER]},text_isEmpty$$module$build$src$generators$javascript$text=function(a,b){return["!"+(b.valueToCode(a,"VALUE",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"''")+".length",Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_NOT]},
text_indexOf$$module$build$src$generators$javascript$text=function(a,b){const c=a.getFieldValue("END")==="FIRST"?"indexOf":"lastIndexOf",d=b.valueToCode(a,"FIND",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";b=(b.valueToCode(a,"VALUE",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"''")+"."+c+"("+d+")";return a.workspace.options.oneBasedIndex?[b+" + 1",Order$$module$build$src$generators$javascript$javascript_generator.ADDITION]:[b,Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},
text_charAt$$module$build$src$generators$javascript$text=function(a,b){const c=a.getFieldValue("WHERE")||"FROM_START",d=b.valueToCode(a,"VALUE",c==="RANDOM"?Order$$module$build$src$generators$javascript$javascript_generator.NONE:Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"''";switch(c){case "FIRST":return[d+".charAt(0)",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL];case "LAST":return[d+".slice(-1)",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL];
case "FROM_START":return a=b.getAdjusted(a,"AT"),[d+".charAt("+a+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL];case "FROM_END":return a=b.getAdjusted(a,"AT",1,!0),[d+".slice("+a+").charAt(0)",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL];case "RANDOM":return[b.provideFunction_("textRandomLetter",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(text) {
  var x = Math.floor(Math.random() * text.length);
  return text[x];
}
`)+"("+d+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]}throw Error("Unhandled option (text_charAt).");},text_getSubstring$$module$build$src$generators$javascript$text=function(a,b){var c={FIRST:"First",LAST:"Last",FROM_START:"FromStart",FROM_END:"FromEnd"};const d=a.getFieldValue("WHERE1"),e=a.getFieldValue("WHERE2");var f=d!=="FROM_END"&&d!=="LAST"&&e!=="FROM_END"&&e!=="LAST",g=b.valueToCode(a,"STRING",f?Order$$module$build$src$generators$javascript$javascript_generator.MEMBER:
Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";if(d==="FIRST"&&e==="LAST")return[g,Order$$module$build$src$generators$javascript$javascript_generator.NONE];if(g.match(/^'?\w+'?$/)||f){switch(d){case "FROM_START":c=b.getAdjusted(a,"AT1");break;case "FROM_END":c=b.getAdjusted(a,"AT1",1,!1,Order$$module$build$src$generators$javascript$javascript_generator.SUBTRACTION);c=g+".length - "+c;break;case "FIRST":c="0";break;default:throw Error("Unhandled option (text_getSubstring).");
}switch(e){case "FROM_START":b=b.getAdjusted(a,"AT2",1);break;case "FROM_END":b=b.getAdjusted(a,"AT2",0,!1,Order$$module$build$src$generators$javascript$javascript_generator.SUBTRACTION);b=g+".length - "+b;break;case "LAST":b=g+".length";break;default:throw Error("Unhandled option (text_getSubstring).");}g=g+".slice("+c+", "+b+")"}else f=b.getAdjusted(a,"AT1"),a=b.getAdjusted(a,"AT2"),g=b.provideFunction_("subsequence"+c[d]+c[e],`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(sequence${d==="FROM_END"||d==="FROM_START"?", at1":""}${e==="FROM_END"||e==="FROM_START"?", at2":""}) {
  var start = ${getSubstringIndex$$module$build$src$generators$javascript$text("sequence",d,"at1")};
  var end = ${getSubstringIndex$$module$build$src$generators$javascript$text("sequence",e,"at2")} + 1;
  return sequence.slice(start, end);
}
`)+"("+g+(d==="FROM_END"||d==="FROM_START"?", "+f:"")+(e==="FROM_END"||e==="FROM_START"?", "+a:"")+")";return[g,Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},text_changeCase$$module$build$src$generators$javascript$text=function(a,b){const c={UPPERCASE:".toUpperCase()",LOWERCASE:".toLowerCase()",TITLECASE:null}[a.getFieldValue("CASE")];a=b.valueToCode(a,"TEXT",c?Order$$module$build$src$generators$javascript$javascript_generator.MEMBER:Order$$module$build$src$generators$javascript$javascript_generator.NONE)||
"''";return[c?a+c:b.provideFunction_("textToTitleCase",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(str) {
  return str.replace(/\\S+/g,
      function(txt) {return txt[0].toUpperCase() + txt.substring(1).toLowerCase();});
}
`)+"("+a+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},text_trim$$module$build$src$generators$javascript$text=function(a,b){const c={LEFT:".replace(/^[\\s\\xa0]+/, '')",RIGHT:".replace(/[\\s\\xa0]+$/, '')",BOTH:".trim()"}[a.getFieldValue("MODE")];return[(b.valueToCode(a,"TEXT",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"''")+c,Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},text_print$$module$build$src$generators$javascript$text=
function(a,b){return"window.alert("+(b.valueToCode(a,"TEXT",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''")+");\n"},text_prompt_ext$$module$build$src$generators$javascript$text=function(a,b){b="window.prompt("+(a.getField("TEXT")?b.quote_(a.getFieldValue("TEXT")):b.valueToCode(a,"TEXT",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''")+")";a.getFieldValue("TYPE")==="NUMBER"&&(b="Number("+b+")");return[b,Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},
text_count$$module$build$src$generators$javascript$text=function(a,b){const c=b.valueToCode(a,"TEXT",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";a=b.valueToCode(a,"SUB",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";return[b.provideFunction_("textCount",`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle) {
  if (needle.length === 0) {
    return haystack.length + 1;
  } else {
    return haystack.split(needle).length - 1;
  }
}
`)+"("+c+", "+a+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},text_replace$$module$build$src$generators$javascript$text=function(a,b){const c=b.valueToCode(a,"TEXT",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''",d=b.valueToCode(a,"FROM",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";a=b.valueToCode(a,"TO",Order$$module$build$src$generators$javascript$javascript_generator.NONE)||"''";return[b.provideFunction_("textReplace",
`
function ${b.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle, replacement) {
  needle = needle.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1')
                 .replace(/\\x08/g, '\\\\x08');
  return haystack.replace(new RegExp(needle, 'g'), replacement);
}
`)+"("+c+", "+d+", "+a+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},text_reverse$$module$build$src$generators$javascript$text=function(a,b){return[(b.valueToCode(a,"TEXT",Order$$module$build$src$generators$javascript$javascript_generator.MEMBER)||"''")+".split('').reverse().join('')",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},variables_get$$module$build$src$generators$javascript$variables=function(a,b){return[b.getVariableName(a.getFieldValue("VAR")),
Order$$module$build$src$generators$javascript$javascript_generator.ATOMIC]},variables_set$$module$build$src$generators$javascript$variables=function(a,b){const c=b.valueToCode(a,"VALUE",Order$$module$build$src$generators$javascript$javascript_generator.ASSIGNMENT)||"0";return b.getVariableName(a.getFieldValue("VAR"))+" = "+c+";\n"},Order$$module$build$src$generators$javascript$javascript_generator;
(function(a){a[a.ATOMIC=0]="ATOMIC";a[a.NEW=1.1]="NEW";a[a.MEMBER=1.2]="MEMBER";a[a.FUNCTION_CALL=2]="FUNCTION_CALL";a[a.INCREMENT=3]="INCREMENT";a[a.DECREMENT=3]="DECREMENT";a[a.BITWISE_NOT=4.1]="BITWISE_NOT";a[a.UNARY_PLUS=4.2]="UNARY_PLUS";a[a.UNARY_NEGATION=4.3]="UNARY_NEGATION";a[a.LOGICAL_NOT=4.4]="LOGICAL_NOT";a[a.TYPEOF=4.5]="TYPEOF";a[a.VOID=4.6]="VOID";a[a.DELETE=4.7]="DELETE";a[a.AWAIT=4.8]="AWAIT";a[a.EXPONENTIATION=5]="EXPONENTIATION";a[a.MULTIPLICATION=5.1]="MULTIPLICATION";a[a.DIVISION=
5.2]="DIVISION";a[a.MODULUS=5.3]="MODULUS";a[a.SUBTRACTION=6.1]="SUBTRACTION";a[a.ADDITION=6.2]="ADDITION";a[a.BITWISE_SHIFT=7]="BITWISE_SHIFT";a[a.RELATIONAL=8]="RELATIONAL";a[a.IN=8]="IN";a[a.INSTANCEOF=8]="INSTANCEOF";a[a.EQUALITY=9]="EQUALITY";a[a.BITWISE_AND=10]="BITWISE_AND";a[a.BITWISE_XOR=11]="BITWISE_XOR";a[a.BITWISE_OR=12]="BITWISE_OR";a[a.LOGICAL_AND=13]="LOGICAL_AND";a[a.LOGICAL_OR=14]="LOGICAL_OR";a[a.CONDITIONAL=15]="CONDITIONAL";a[a.ASSIGNMENT=16]="ASSIGNMENT";a[a.YIELD=17]="YIELD";
a[a.COMMA=18]="COMMA";a[a.NONE=99]="NONE"})(Order$$module$build$src$generators$javascript$javascript_generator||(Order$$module$build$src$generators$javascript$javascript_generator={}));
var JavascriptGenerator$$module$build$src$generators$javascript$javascript_generator=class extends $.CodeGenerator$$module$build$src$core$generator{constructor(a="JavaScript"){super(a);this.ORDER_OVERRIDES=[[Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL,Order$$module$build$src$generators$javascript$javascript_generator.MEMBER],[Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL,Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL],
[Order$$module$build$src$generators$javascript$javascript_generator.MEMBER,Order$$module$build$src$generators$javascript$javascript_generator.MEMBER],[Order$$module$build$src$generators$javascript$javascript_generator.MEMBER,Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL],[Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_NOT,Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_NOT],[Order$$module$build$src$generators$javascript$javascript_generator.MULTIPLICATION,
Order$$module$build$src$generators$javascript$javascript_generator.MULTIPLICATION],[Order$$module$build$src$generators$javascript$javascript_generator.ADDITION,Order$$module$build$src$generators$javascript$javascript_generator.ADDITION],[Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_AND,Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_AND],[Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_OR,Order$$module$build$src$generators$javascript$javascript_generator.LOGICAL_OR]];
this.isInitialized=!1;for(const b in Order$$module$build$src$generators$javascript$javascript_generator)a=Order$$module$build$src$generators$javascript$javascript_generator[b],typeof a!=="string"&&(this["ORDER_"+b]=a);this.addReservedWords("break,case,catch,class,const,continue,debugger,default,delete,do,else,export,extends,finally,for,function,if,import,in,instanceof,new,return,super,switch,this,throw,try,typeof,var,void,while,with,yield,enum,implements,interface,let,package,private,protected,public,static,await,null,true,false,arguments,"+
Object.getOwnPropertyNames(globalThis).join(","))}init(a){super.init(a);this.nameDB_?this.nameDB_.reset():this.nameDB_=new $.Names$$module$build$src$core$names(this.RESERVED_WORDS_);this.nameDB_.setVariableMap(a.getVariableMap());this.nameDB_.populateVariables(a);this.nameDB_.populateProcedures(a);const b=[];var c=$.allDeveloperVariables$$module$build$src$core$variables(a);for(let d=0;d<c.length;d++)b.push(this.nameDB_.getName(c[d],$.NameType$$module$build$src$core$names.DEVELOPER_VARIABLE));a=$.allUsedVarModels$$module$build$src$core$variables(a);
for(c=0;c<a.length;c++)b.push(this.nameDB_.getName(a[c].getId(),$.NameType$$module$build$src$core$names.VARIABLE));b.length&&(this.definitions_.variables="var "+b.join(", ")+";");this.isInitialized=!0}finish(a){const b=Object.values(this.definitions_);super.finish(a);this.isInitialized=!1;this.nameDB_.reset();return b.join("\n\n")+"\n\n\n"+a}scrubNakedValue(a){return a+";\n"}quote_(a){a=a.replace(/\\/g,"\\\\").replace(/\n/g,"\\\n").replace(/'/g,"\\'");return"'"+a+"'"}multiline_quote_(a){return a.split(/\n/g).map(this.quote_).join(" + '\\n' +\n")}scrub_(a,
b,c=!1){let d="";if(!a.outputConnection||!a.outputConnection.targetConnection){var e=a.getCommentText();e&&(e=$.wrap$$module$build$src$core$utils$string(e,this.COMMENT_WRAP-3),d+=this.prefixLines(e+"\n","// "));for(let f=0;f<a.inputList.length;f++)a.inputList[f].type===$.inputTypes$$module$build$src$core$inputs$input_types.VALUE&&(e=a.inputList[f].connection.targetBlock())&&(e=this.allNestedComments(e))&&(d+=this.prefixLines(e,"// "))}a=a.nextConnection&&a.nextConnection.targetBlock();c=c?"":this.blockToCode(a);
return d+b+c}getAdjusted(a,b,c=0,d=!1,e=Order$$module$build$src$generators$javascript$javascript_generator.NONE){a.workspace.options.oneBasedIndex&&c--;const f=a.workspace.options.oneBasedIndex?"1":"0";let g=e;c>0?g=Order$$module$build$src$generators$javascript$javascript_generator.ADDITION:c<0?g=Order$$module$build$src$generators$javascript$javascript_generator.SUBTRACTION:d&&(g=Order$$module$build$src$generators$javascript$javascript_generator.UNARY_NEGATION);a=this.valueToCode(a,b,g)||f;if(c===
0&&!d)return a;if($.isNumber$$module$build$src$core$utils$string(a))return a=String(Number(a)+c),d&&(a=String(-Number(a))),a;c>0?a=`${a} + ${c}`:c<0&&(a=`${a} - ${-c}`);d&&(a=c?`-(${a})`:`-${a}`);Math.floor(e)>=Math.floor(g)&&(a=`(${a})`);return a}},module$build$src$generators$javascript$javascript_generator={};module$build$src$generators$javascript$javascript_generator.JavascriptGenerator=JavascriptGenerator$$module$build$src$generators$javascript$javascript_generator;
module$build$src$generators$javascript$javascript_generator.Order=Order$$module$build$src$generators$javascript$javascript_generator;var getSubstringIndex$$module$build$src$generators$javascript$lists=function(a,b,c){return b==="FIRST"?"0":b==="FROM_END"?a+".length - 1 - "+c:b==="LAST"?a+".length - 1":c},module$build$src$generators$javascript$lists={};module$build$src$generators$javascript$lists.lists_create_empty=lists_create_empty$$module$build$src$generators$javascript$lists;module$build$src$generators$javascript$lists.lists_create_with=lists_create_with$$module$build$src$generators$javascript$lists;
module$build$src$generators$javascript$lists.lists_getIndex=lists_getIndex$$module$build$src$generators$javascript$lists;module$build$src$generators$javascript$lists.lists_getSublist=lists_getSublist$$module$build$src$generators$javascript$lists;module$build$src$generators$javascript$lists.lists_indexOf=lists_indexOf$$module$build$src$generators$javascript$lists;module$build$src$generators$javascript$lists.lists_isEmpty=lists_isEmpty$$module$build$src$generators$javascript$lists;
module$build$src$generators$javascript$lists.lists_length=lists_length$$module$build$src$generators$javascript$lists;module$build$src$generators$javascript$lists.lists_repeat=lists_repeat$$module$build$src$generators$javascript$lists;module$build$src$generators$javascript$lists.lists_reverse=lists_reverse$$module$build$src$generators$javascript$lists;module$build$src$generators$javascript$lists.lists_setIndex=lists_setIndex$$module$build$src$generators$javascript$lists;
module$build$src$generators$javascript$lists.lists_sort=lists_sort$$module$build$src$generators$javascript$lists;module$build$src$generators$javascript$lists.lists_split=lists_split$$module$build$src$generators$javascript$lists;var controls_ifelse$$module$build$src$generators$javascript$logic=controls_if$$module$build$src$generators$javascript$logic,module$build$src$generators$javascript$logic={};module$build$src$generators$javascript$logic.controls_if=controls_if$$module$build$src$generators$javascript$logic;module$build$src$generators$javascript$logic.controls_ifelse=controls_if$$module$build$src$generators$javascript$logic;module$build$src$generators$javascript$logic.logic_boolean=logic_boolean$$module$build$src$generators$javascript$logic;
module$build$src$generators$javascript$logic.logic_compare=logic_compare$$module$build$src$generators$javascript$logic;module$build$src$generators$javascript$logic.logic_negate=logic_negate$$module$build$src$generators$javascript$logic;module$build$src$generators$javascript$logic.logic_null=logic_null$$module$build$src$generators$javascript$logic;module$build$src$generators$javascript$logic.logic_operation=logic_operation$$module$build$src$generators$javascript$logic;
module$build$src$generators$javascript$logic.logic_ternary=logic_ternary$$module$build$src$generators$javascript$logic;var controls_repeat$$module$build$src$generators$javascript$loops=controls_repeat_ext$$module$build$src$generators$javascript$loops,module$build$src$generators$javascript$loops={};module$build$src$generators$javascript$loops.controls_flow_statements=controls_flow_statements$$module$build$src$generators$javascript$loops;module$build$src$generators$javascript$loops.controls_for=controls_for$$module$build$src$generators$javascript$loops;module$build$src$generators$javascript$loops.controls_forEach=controls_forEach$$module$build$src$generators$javascript$loops;
module$build$src$generators$javascript$loops.controls_repeat=controls_repeat_ext$$module$build$src$generators$javascript$loops;module$build$src$generators$javascript$loops.controls_repeat_ext=controls_repeat_ext$$module$build$src$generators$javascript$loops;module$build$src$generators$javascript$loops.controls_whileUntil=controls_whileUntil$$module$build$src$generators$javascript$loops;var math_round$$module$build$src$generators$javascript$math=math_single$$module$build$src$generators$javascript$math,math_trig$$module$build$src$generators$javascript$math=math_single$$module$build$src$generators$javascript$math,module$build$src$generators$javascript$math={};module$build$src$generators$javascript$math.math_arithmetic=math_arithmetic$$module$build$src$generators$javascript$math;module$build$src$generators$javascript$math.math_atan2=math_atan2$$module$build$src$generators$javascript$math;
module$build$src$generators$javascript$math.math_change=math_change$$module$build$src$generators$javascript$math;module$build$src$generators$javascript$math.math_constant=math_constant$$module$build$src$generators$javascript$math;module$build$src$generators$javascript$math.math_constrain=math_constrain$$module$build$src$generators$javascript$math;module$build$src$generators$javascript$math.math_modulo=math_modulo$$module$build$src$generators$javascript$math;
module$build$src$generators$javascript$math.math_number=math_number$$module$build$src$generators$javascript$math;module$build$src$generators$javascript$math.math_number_property=math_number_property$$module$build$src$generators$javascript$math;module$build$src$generators$javascript$math.math_on_list=math_on_list$$module$build$src$generators$javascript$math;module$build$src$generators$javascript$math.math_random_float=math_random_float$$module$build$src$generators$javascript$math;
module$build$src$generators$javascript$math.math_random_int=math_random_int$$module$build$src$generators$javascript$math;module$build$src$generators$javascript$math.math_round=math_single$$module$build$src$generators$javascript$math;module$build$src$generators$javascript$math.math_single=math_single$$module$build$src$generators$javascript$math;module$build$src$generators$javascript$math.math_trig=math_single$$module$build$src$generators$javascript$math;var procedures_defnoreturn$$module$build$src$generators$javascript$procedures=procedures_defreturn$$module$build$src$generators$javascript$procedures,module$build$src$generators$javascript$procedures={};module$build$src$generators$javascript$procedures.procedures_callnoreturn=procedures_callnoreturn$$module$build$src$generators$javascript$procedures;module$build$src$generators$javascript$procedures.procedures_callreturn=procedures_callreturn$$module$build$src$generators$javascript$procedures;
module$build$src$generators$javascript$procedures.procedures_defnoreturn=procedures_defreturn$$module$build$src$generators$javascript$procedures;module$build$src$generators$javascript$procedures.procedures_defreturn=procedures_defreturn$$module$build$src$generators$javascript$procedures;module$build$src$generators$javascript$procedures.procedures_ifreturn=procedures_ifreturn$$module$build$src$generators$javascript$procedures;var strRegExp$$module$build$src$generators$javascript$text=/^\s*'([^']|\\')*'\s*$/,forceString$$module$build$src$generators$javascript$text=function(a){return strRegExp$$module$build$src$generators$javascript$text.test(a)?[a,Order$$module$build$src$generators$javascript$javascript_generator.ATOMIC]:["String("+a+")",Order$$module$build$src$generators$javascript$javascript_generator.FUNCTION_CALL]},getSubstringIndex$$module$build$src$generators$javascript$text=function(a,b,c){return b==="FIRST"?"0":
b==="FROM_END"?a+".length - 1 - "+c:b==="LAST"?a+".length - 1":c},text_prompt$$module$build$src$generators$javascript$text=text_prompt_ext$$module$build$src$generators$javascript$text,module$build$src$generators$javascript$text={};module$build$src$generators$javascript$text.text=text$$module$build$src$generators$javascript$text;module$build$src$generators$javascript$text.text_append=text_append$$module$build$src$generators$javascript$text;
module$build$src$generators$javascript$text.text_changeCase=text_changeCase$$module$build$src$generators$javascript$text;module$build$src$generators$javascript$text.text_charAt=text_charAt$$module$build$src$generators$javascript$text;module$build$src$generators$javascript$text.text_count=text_count$$module$build$src$generators$javascript$text;module$build$src$generators$javascript$text.text_getSubstring=text_getSubstring$$module$build$src$generators$javascript$text;
module$build$src$generators$javascript$text.text_indexOf=text_indexOf$$module$build$src$generators$javascript$text;module$build$src$generators$javascript$text.text_isEmpty=text_isEmpty$$module$build$src$generators$javascript$text;module$build$src$generators$javascript$text.text_join=text_join$$module$build$src$generators$javascript$text;module$build$src$generators$javascript$text.text_length=text_length$$module$build$src$generators$javascript$text;
module$build$src$generators$javascript$text.text_print=text_print$$module$build$src$generators$javascript$text;module$build$src$generators$javascript$text.text_prompt=text_prompt_ext$$module$build$src$generators$javascript$text;module$build$src$generators$javascript$text.text_prompt_ext=text_prompt_ext$$module$build$src$generators$javascript$text;module$build$src$generators$javascript$text.text_replace=text_replace$$module$build$src$generators$javascript$text;
module$build$src$generators$javascript$text.text_reverse=text_reverse$$module$build$src$generators$javascript$text;module$build$src$generators$javascript$text.text_trim=text_trim$$module$build$src$generators$javascript$text;var module$build$src$generators$javascript$variables={};module$build$src$generators$javascript$variables.variables_get=variables_get$$module$build$src$generators$javascript$variables;module$build$src$generators$javascript$variables.variables_set=variables_set$$module$build$src$generators$javascript$variables;var module$build$src$generators$javascript$variables_dynamic={};module$build$src$generators$javascript$variables_dynamic.variables_get_dynamic=variables_get$$module$build$src$generators$javascript$variables;module$build$src$generators$javascript$variables_dynamic.variables_set_dynamic=variables_set$$module$build$src$generators$javascript$variables;var javascriptGenerator$$module$build$src$generators$javascript=new JavascriptGenerator$$module$build$src$generators$javascript$javascript_generator,generators$$module$build$src$generators$javascript=Object.assign({},module$build$src$generators$javascript$lists,module$build$src$generators$javascript$logic,module$build$src$generators$javascript$loops,module$build$src$generators$javascript$math,module$build$src$generators$javascript$procedures,module$build$src$generators$javascript$text,module$build$src$generators$javascript$variables,
module$build$src$generators$javascript$variables_dynamic);for(const a in generators$$module$build$src$generators$javascript)javascriptGenerator$$module$build$src$generators$javascript.forBlock[a]=generators$$module$build$src$generators$javascript[a];var module$build$src$generators$javascript={};module$build$src$generators$javascript.JavascriptGenerator=JavascriptGenerator$$module$build$src$generators$javascript$javascript_generator;module$build$src$generators$javascript.Order=Order$$module$build$src$generators$javascript$javascript_generator;
module$build$src$generators$javascript.javascriptGenerator=javascriptGenerator$$module$build$src$generators$javascript;
module$build$src$generators$javascript.__namespace__=$;
return module$build$src$generators$javascript;
}));


//# sourceMappingURL=javascript_compressed.js.map


/***/ }),

/***/ 38943:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  dF: () => (/* binding */ NodePickerClearNews),
  $Q: () => (/* binding */ useDocs),
  i$: () => (/* binding */ useGetSliderNews),
  hd: () => (/* binding */ useKeyboardCursor),
  VK: () => (/* binding */ useSearchBar)
});

// UNUSED EXPORTS: useGetDefaultDocs

// EXTERNAL MODULE: ./src/editor/src/hooks/useCallAfterNextRender.ts
var useCallAfterNextRender = __webpack_require__(61113);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
;// ./src/editor/src/hooks/useFetch.ts

function useFetch_useFetch(url, options = {}) {
    const [response, setResponse] = (0,external_react_.useState)(null);
    const [error, setError] = (0,external_react_.useState)(null);
    (0,external_react_.useEffect)(() => {
        const fetchData = async () => {
            try {
                const res = await fetch(url, options);
                const json = await res.json();
                setResponse(json);
            }
            catch (error) {
                setError(error);
            }
        };
        fetchData();
    }, []);
    return { response, error };
}

// EXTERNAL MODULE: ./src/editor/src/hooks/useOnMount.ts
var useOnMount = __webpack_require__(13484);
// EXTERNAL MODULE: external "electron"
var external_electron_ = __webpack_require__(91288);
// EXTERNAL MODULE: ./src/editor/src/constants/KeyCode.ts
var KeyCode = __webpack_require__(76976);
// EXTERNAL MODULE: external "async"
var external_async_ = __webpack_require__(82626);
var external_async_default = /*#__PURE__*/__webpack_require__.n(external_async_);
;// external "highlight.js"
const external_highlight_js_namespaceObject = require("highlight.js");
var external_highlight_js_default = /*#__PURE__*/__webpack_require__.n(external_highlight_js_namespaceObject);
// EXTERNAL MODULE: external "remarkable"
var external_remarkable_ = __webpack_require__(31890);
;// ./src/editor/src/utils/docs-parser.ts



const docs_parser_getDocsEndpoint = (__webpack_require__(41160)/* ["default"] */ .A);
class DocsParser {
    dispose() { }
    parsePage(content, _options) {
        const _this = this;
        const endpoint = docs_parser_getDocsEndpoint();
        const md = new external_remarkable_.Remarkable({
            html: true,
            breaks: true,
            highlight: function (code) {
                return external_highlight_js_default().highlightAuto(code, ['javascript']).value;
            }
        });
        const regexMatch = content.match(/{\/\*##head##\*\/}([\s\S]*?){\/\*##head##\*\/}/);
        if (!regexMatch)
            return null;
        const el = $('<div>' + md.render(regexMatch[1]) + '</div>');
        // Iterate over all images and load the src as a dataurl
        el.find('img').each(function () {
            const _el = $(this);
            const url = _el.attr('src');
            if (!url.startsWith('/')) {
                _el.attr('src', _this.baseUrl.href.split('/').slice(0, -1).join('/') + '/' + url);
            }
            else {
                _el.attr('src', endpoint + url);
            }
        });
        el.find('a').each(function () {
            const _el = $(this);
            _el.attr('target', '_blank'); // Open external
            let url = _el.attr('href');
            if (url.startsWith('https://docs.noodl.net')) {
                //add version number
                url.replace('https://docs.noodl.net', endpoint);
            }
            else {
                url = endpoint + url;
            }
            _el.attr('href', url);
        });
        return el[0];
    }
    fetchPage(url, callback) {
        const _this = this;
        this.baseUrl = new URL(url);
        $.ajax({
            url: url,
            headers: {
                Accept: 'text/html'
            },
            success: function (html) {
                // Find all filename references
                const matches = html.matchAll(/@include\s\"(.*)\"/g);
                const refs = [];
                for (const m of matches) {
                    let ref = m[1];
                    if (ref !== undefined) {
                        ref = ref.trim();
                        const absoluteUrl = new URL(ref, url);
                        refs.push({ anchor: m[0], url: absoluteUrl.href });
                    }
                }
                external_async_default().each(refs, function (ref, cb) {
                    $.ajax({
                        url: ref.url,
                        headers: {
                            Accept: 'text/html'
                        },
                        success: function (refHtml) {
                            html = html.replace(ref.anchor, refHtml);
                            cb();
                        },
                        error: function () {
                            cb(); // Ignore error
                        }
                    });
                }, function () {
                    // All done
                    callback(_this.parsePage(html, {}));
                });
            },
            error: function (err) {
                if (err.status === 401) {
                    /* Access denied */
                }
                else {
                    console.warn(err);
                    callback();
                }
            }
        });
    }
}

// EXTERNAL MODULE: ./src/editor/src/utils/getDocsEndpoint.ts
var utils_getDocsEndpoint = __webpack_require__(41160);
;// ./src/editor/src/views/NodePicker/NodePicker.reducer.ts
var CursorContext;
(function (CursorContext) {
    CursorContext["Search"] = "search";
    CursorContext["Category"] = "category";
    CursorContext["Node"] = "node";
})(CursorContext || (CursorContext = {}));
var CursorActionType;
(function (CursorActionType) {
    CursorActionType["MoveCursor"] = "MOVE_CURSOR";
    CursorActionType["MoveCategoryCursor"] = "MOVE_CATEGORY_CURSOR";
    CursorActionType["MoveNodeCursor"] = "MOVE_NODE_CURSOR";
    CursorActionType["HandleEnter"] = "HANDLE_ENTER";
    CursorActionType["OpenAllCategories"] = "OPEN_ALL_CATEGORIES";
    CursorActionType["CloseAllCategories"] = "CLOSE_ALL_CATEGORIES";
    CursorActionType["UpdateAllCurrentCategories"] = "UPDATE_ALL_CURRENT_CATEGORIES";
    CursorActionType["HighlightFirstNode"] = "HIGHLIGHT_FIRST_NODE";
    CursorActionType["HandleSearchUpdate"] = "HANDLE_SEARCH_UPDATE";
    CursorActionType["AfterNodeCreation"] = "AFTER_NODE_CREATION";
    CursorActionType["EnterSearchContext"] = "ENTER_SEARCH_CONTEXT";
    CursorActionType["DisableCollapseTransition"] = "DISABLE_COLLAPSE_TRANSITION";
    CursorActionType["EnableCollapseTransition"] = "ENABLE_COLLAPSE_TRANSITION";
})(CursorActionType || (CursorActionType = {}));
function moveCategoryCursor(state, skip) {
    const calculatedValue = state.categoryCursor + skip;
    let targetValue;
    let targetNodeCursor = null;
    let targetCursorContext = CursorContext.Category;
    if (state.categoryCursor === null && skip > 0) {
        targetValue = 0;
    }
    else if (calculatedValue > state.allCategories.length - 1) {
        targetValue = state.allCategories.length - 1;
    }
    else if (calculatedValue < 0) {
        return enterSearchContext(state);
    }
    else {
        targetValue = calculatedValue;
        if (targetValue < state.categoryCursor) {
            const previousCategory = state.allCategories[targetValue];
            // enter node context if prev cat is not collapsed
            if (!previousCategory.isCollapsed) {
                const nodeCursorModifier = previousCategory.nodes.length % 2 ? 1 : 2; // wow, such mathematical
                targetNodeCursor = previousCategory.nodes.length - nodeCursorModifier;
                targetCursorContext = CursorContext.Node;
            }
        }
    }
    return {
        ...state,
        categoryCursor: targetValue,
        cursorContext: targetCursorContext,
        nodeCursor: targetNodeCursor
    };
}
function moveNodeCursor(state, skip, isHorizontal) {
    var _a, _b;
    const verticalModifier = 1; //isHorizontal ? 1 : 2;
    const modifiedSkip = skip * verticalModifier;
    const calculatedValue = state.nodeCursor + modifiedSkip;
    const currentNodes = (_b = (_a = state.allCategories) === null || _a === void 0 ? void 0 : _a[state.categoryCursor]) === null || _b === void 0 ? void 0 : _b.nodes;
    const maxNodeIndex = (currentNodes === null || currentNodes === void 0 ? void 0 : currentNodes.length) - 1;
    const maxCategoryIndex = state.allCategories.length;
    let targetValue;
    if (state.nodeCursor === null && skip > 0) {
        targetValue = 0;
    }
    else if (calculatedValue > maxNodeIndex) {
        if (state.categoryCursor + 1 <= maxCategoryIndex) {
            return moveCategoryCursor(state, 1);
        }
    }
    else if (calculatedValue < 0) {
        targetValue = null;
        return moveCategoryCursor(state, 0);
    }
    else if (typeof (currentNodes === null || currentNodes === void 0 ? void 0 : currentNodes[calculatedValue]) !== 'object') {
        targetValue = calculatedValue + modifiedSkip;
    }
    else {
        targetValue = calculatedValue;
    }
    return {
        ...state,
        cursorContext: CursorContext.Node,
        nodeCursor: targetValue
    };
}
function toggleCategory(state) {
    const categoryStateCopy = [...state.allCategories];
    categoryStateCopy[state.categoryCursor].isCollapsed = !categoryStateCopy[state.categoryCursor].isCollapsed;
    return {
        ...state,
        allCategories: categoryStateCopy
    };
}
function allowNodeCreation(state) {
    if (state.categoryCursor === null || state.nodeCursor === null)
        return state;
    return {
        ...state,
        allowNodeCreation: true
    };
}
function enterCategoryContext(state) {
    return {
        ...state,
        categoryCursor: 0,
        nodeCursor: null,
        cursorContext: CursorContext.Category,
        disableCollapseTransition: false
    };
}
function enterSearchContext(state) {
    return {
        ...state,
        categoryCursor: null,
        nodeCursor: null,
        cursorContext: CursorContext.Search,
        disableCollapseTransition: true
    };
}
function highlightFirstNode(state) {
    return {
        ...state,
        categoryCursor: 0,
        nodeCursor: 0
    };
}
function setAllCategoriesCollapsedState(state, isCollapsed) {
    const categoryStateCopy = [...state.allCategories];
    categoryStateCopy.forEach((category) => (category.isCollapsed = isCollapsed));
    return {
        ...state,
        allCategories: categoryStateCopy
    };
}
function enableCollapseTransition(state) {
    return {
        ...state,
        disableCollapseTransition: false
    };
}
function disableCollapseTransition(state) {
    return {
        ...state,
        disableCollapseTransition: true
    };
}
function cursorReducer(state, action) {
    const currentCategory = state.allCategories[state.categoryCursor];
    const isCurrentCategoryCollapsed = currentCategory ? currentCategory.isCollapsed : true;
    switch (action.type) {
        case CursorActionType.MoveCursor: {
            switch (state.cursorContext) {
                case CursorContext.Category:
                    if (isCurrentCategoryCollapsed) {
                        return moveCategoryCursor(state, action.skip);
                    }
                    else {
                        if (action.skip > 0) {
                            return moveNodeCursor(state, action.skip);
                        }
                        else {
                            return moveCategoryCursor(state, action.skip);
                        }
                    }
                case CursorContext.Search:
                    if (action.skip === -1)
                        return state;
                    if (state.nodeCursor !== null) {
                        return moveNodeCursor(state, action.skip);
                    }
                    return enterCategoryContext(state);
                case CursorContext.Node:
                    return moveNodeCursor(state, action.skip, action.isHorizontal);
                default:
                    console.warn('No cursor context provided in move cursor');
                    return state;
            }
        }
        case CursorActionType.HandleEnter:
            switch (state.cursorContext) {
                case CursorContext.Category:
                    return toggleCategory(state);
                case CursorContext.Node:
                case CursorContext.Search:
                    return allowNodeCreation(state);
                default:
                    console.warn('No cursor context provided in handle enter');
                    return state;
            }
        case CursorActionType.OpenAllCategories:
            return setAllCategoriesCollapsedState(state, false);
        case CursorActionType.CloseAllCategories:
            return setAllCategoriesCollapsedState(state, true);
        case CursorActionType.UpdateAllCurrentCategories: {
            const stateCopy = { ...state, allCategories: action.allCategories };
            if (typeof action.withCollapsedCategories === 'undefined') {
                return stateCopy;
            }
            return setAllCategoriesCollapsedState(state, action.withCollapsedCategories);
        }
        case CursorActionType.HighlightFirstNode:
            return highlightFirstNode(state);
        case CursorActionType.HandleSearchUpdate: {
            const stateCopy = { ...action.state };
            stateCopy.disableCollapseTransition = true;
            const stateCopyWithOpenCategories = setAllCategoriesCollapsedState(stateCopy, false);
            return highlightFirstNode(stateCopyWithOpenCategories);
        }
        case CursorActionType.AfterNodeCreation:
            return {
                ...state,
                allowNodeCreation: false
            };
        case CursorActionType.EnterSearchContext:
            return enterSearchContext(state);
        case CursorActionType.DisableCollapseTransition:
            return disableCollapseTransition(state);
        case CursorActionType.EnableCollapseTransition:
            return enableCollapseTransition(state);
        default:
            console.warn(`No action with type ${action.type} exists`);
            return state;
    }
}

;// ./src/editor/src/views/NodePicker/NodePicker.hooks.ts









/**
 * useSearchBar
 *
 * Features all search functionality.
 * Creates a copy of the allowed NodeIndex, mutates it
 * and sets it as the renderable items.
 */
function matchResults(items, searchTerm) {
    return {
        coreNodes: filterItems(items.coreNodes, searchTerm),
        customNodes: filterItems(items.customNodes, searchTerm)
    };
}
// sorry for this huge filtering function.
function filterItems(categories, searchTerm) {
    const result = categories
        .filter((category) => {
        // remove all categories without result items
        let containsChildren = false;
        category.subCategories.forEach((subCategory) => {
            const isInSearch = isItemInSearch(subCategory.items, searchTerm);
            if (!isInSearch)
                return false;
            containsChildren = true;
            return true;
        });
        return containsChildren;
    })
        .map((category) => {
        var _a;
        return ({
            ...category,
            subCategories: (_a = category === null || category === void 0 ? void 0 : category.subCategories) === null || _a === void 0 ? void 0 : _a.filter((subCategory) => {
                // remove all subCtegories without results
                const isInSearch = isItemInSearch(subCategory.items, searchTerm);
                if (!isInSearch)
                    return false;
                return true;
            }).map((subCategory) => {
                return {
                    ...subCategory,
                    items: subCategory.items
                        .map((type) => {
                        // add indices for how relevant the
                        // items are compared to the search term
                        const matchIndex = getMatchIndex(type, searchTerm);
                        return { type, matchIndex };
                    })
                        // remove all items that are irrelevant
                        .filter((type) => type.matchIndex !== -1)
                        // sort all items based on how relevant they are
                        .sort((a, b) => {
                        return sortResultsWithMatchIndex(a, b);
                    })
                };
            }).sort((a, b) => {
                var _a, _b;
                // sort all subCategories
                const firstItemA = (_a = a === null || a === void 0 ? void 0 : a.items) === null || _a === void 0 ? void 0 : _a[0];
                const firstItemB = (_b = b === null || b === void 0 ? void 0 : b.items) === null || _b === void 0 ? void 0 : _b[0];
                return sortResultsWithMatchIndex(firstItemA, firstItemB);
            })
        });
    })
        .sort((a, b) => {
        var _a, _b, _c, _d, _e, _f;
        // sort all categories based on their first items matchIndex
        const firstItemA = (_c = (_b = (_a = a.subCategories) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.items) === null || _c === void 0 ? void 0 : _c[0];
        const firstItemB = (_f = (_e = (_d = b.subCategories) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.items) === null || _f === void 0 ? void 0 : _f[0];
        return sortResultsWithMatchIndex(firstItemA, firstItemB);
    })
        .map((category) => ({
        // remove matchIndex from items
        ...category,
        subCategories: category.subCategories.map((subCategory) => ({
            ...subCategory,
            items: subCategory.items.map((item) => item.type)
        }))
    }));
    return result;
}
function sortResultsWithMatchIndex(a, b) {
    const match = a.matchIndex - b.matchIndex;
    if (match !== 0)
        return match;
    return a.type.name.length - b.type.name.length;
}
function getMatchIndex(item, searchTerm) {
    if (item.searchTags && item.searchTags.some((x) => x.toLowerCase().indexOf(searchTerm) !== -1)) {
        return true;
    }
    const name = item.displayName || item.displayNodeName || item.name;
    return name.toLowerCase().indexOf(searchTerm);
}
function isItemInSearch(items, searchTerm) {
    const searchTermLowerCase = searchTerm.toLowerCase();
    let isInSearch = false;
    items.forEach((type) => {
        const matchIndex = getMatchIndex(type, searchTermLowerCase);
        if (matchIndex !== -1) {
            isInSearch = true;
        }
    });
    return isInSearch;
}
function useSearchBar(searchInput, setRenderedNodes, items, cursorContext, openAllCategories, closeAllCategories, handleSearchUpdate) {
    (0,useOnMount/* default */.A)(() => {
        requestAnimationFrame(() => {
            var _a;
            // in rAF to avoid flushDiscreteUpdates error
            (_a = searchInput === null || searchInput === void 0 ? void 0 : searchInput.current) === null || _a === void 0 ? void 0 : _a.focus();
        });
    });
    (0,external_react_.useEffect)(() => {
        function onWindowFocus() {
            requestAnimationFrame(() => {
                var _a;
                (_a = searchInput === null || searchInput === void 0 ? void 0 : searchInput.current) === null || _a === void 0 ? void 0 : _a.focus();
            });
        }
        external_electron_.ipcRenderer.on('window-focused', onWindowFocus);
        return function () {
            external_electron_.ipcRenderer.off('window-focused', onWindowFocus);
        };
    }, []);
    if (cursorContext === CursorContext.Search) {
        requestAnimationFrame(() => {
            var _a;
            // in rAF to avoid flushDiscreteUpdates error
            (_a = searchInput === null || searchInput === void 0 ? void 0 : searchInput.current) === null || _a === void 0 ? void 0 : _a.focus();
        });
    }
    else {
        requestAnimationFrame(() => {
            var _a;
            // in rAF to avoid flushDiscreteUpdates error
            (_a = searchInput === null || searchInput === void 0 ? void 0 : searchInput.current) === null || _a === void 0 ? void 0 : _a.blur();
        });
    }
    const [searchTerm, setSearchTerm] = (0,external_react_.useState)('');
    const doAfterNextRender = (0,useCallAfterNextRender/* default */.A)();
    (0,external_react_.useEffect)(() => {
        doAfterNextRender(() => {
            if (searchTerm) {
                setRenderedNodes(() => matchResults(items, searchTerm.toLowerCase()));
                handleSearchUpdate();
                openAllCategories();
            }
            else {
                setRenderedNodes(items);
                closeAllCategories();
            }
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [searchTerm]);
    return setSearchTerm;
}
function useKeyboardCursor(renderedNodes) {
    const coreCategories = renderedNodes.coreNodes.map((category) => category.name);
    const customCategories = renderedNodes.customNodes.map((category) => category.name);
    function getAllNodesInCategory(categoryName) {
        const coreNodes = renderedNodes.coreNodes.find((category) => category.name === categoryName);
        const customNodes = renderedNodes.customNodes.find((catgegory) => catgegory.name === categoryName);
        let sourceNodes;
        let items = [];
        if (coreNodes)
            sourceNodes = coreNodes;
        if (customNodes)
            sourceNodes = customNodes;
        sourceNodes.subCategories.forEach((subCategory) => {
            if (items.length > 0 && items.length % 2 !== 0) {
                items.push('spacer');
            }
            items = [...items, ...subCategory.items];
        });
        return items;
    }
    function parseAllCurrentCategories() {
        return [...coreCategories, ...customCategories].map((categoryName) => ({
            name: categoryName,
            isCollapsed: true,
            nodes: getAllNodesInCategory(categoryName)
        }));
    }
    const initialCursorState = {
        categoryCursor: null,
        nodeCursor: null,
        cursorContext: CursorContext.Search,
        allowNodeCreation: false,
        disableCollapseTransition: true,
        allCategories: parseAllCurrentCategories()
    };
    const [cursorState, dispatch] = (0,external_react_.useReducer)(cursorReducer, initialCursorState);
    function handleEnter() {
        dispatch({ type: CursorActionType.HandleEnter });
    }
    function moveCursor(skip, isHorizontal) {
        dispatch({ type: CursorActionType.MoveCursor, skip, isHorizontal });
    }
    function openAllCategories() {
        dispatch({ type: CursorActionType.OpenAllCategories });
    }
    function closeAllCategories() {
        dispatch({ type: CursorActionType.CloseAllCategories });
    }
    function updateAllCurrentCategories(withCollapsedCategories) {
        dispatch({
            type: CursorActionType.UpdateAllCurrentCategories,
            allCategories: parseAllCurrentCategories(),
            withCollapsedCategories
        });
    }
    function focusSearch() {
        dispatch({ type: CursorActionType.EnterSearchContext });
    }
    function handleSearchUpdate() {
        dispatch({
            type: CursorActionType.HandleSearchUpdate,
            state: initialCursorState
        });
    }
    function enableCollapseTransition() {
        dispatch({
            type: CursorActionType.EnableCollapseTransition
        });
    }
    function disableCollapseTransition() {
        dispatch({
            type: CursorActionType.DisableCollapseTransition
        });
    }
    (0,external_react_.useEffect)(() => {
        updateAllCurrentCategories();
        const handleKeyDown = (event) => {
            switch (event.keyCode) {
                case KeyCode/* KeyCode */.D.Down:
                    moveCursor(1);
                    break;
                case KeyCode/* KeyCode */.D.Up:
                    moveCursor(-1);
                    break;
                // When we had the nodes in 2 columns this was necessary.
                // It is no longer, but keeping it here if we would
                // ever need to bring it back.
                //
                // Also check verticalModifier in moveNodeCursor()
                //
                // case KeyCode.Left:
                //   moveCursor(-1, true);
                //   break;
                //
                // case KeyCode.Right:
                //   moveCursor(1, true);
                //   break;
                case KeyCode/* KeyCode */.D.Enter:
                    handleEnter();
                    break;
            }
        };
        window.addEventListener('keydown', handleKeyDown);
        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        };
    }, [renderedNodes]);
    return {
        cursorState,
        openAllCategories,
        closeAllCategories,
        updateAllCurrentCategories,
        handleSearchUpdate,
        focusSearch,
        enableCollapseTransition,
        disableCollapseTransition
    };
}
/**
 * useDocs
 * Downloading docs, passing them through the DocsParser
 * and setting the result to a renderable state
 */
function useDocs() {
    const emptyCurrentDocsValue = { content: '', url: '' };
    const [currentDocs, setCurrentDocs] = (0,external_react_.useState)(emptyCurrentDocsValue);
    const timer = (0,external_react_.useRef)(null);
    function getDocs(type) {
        timer.current = setTimeout(() => {
            const docs = type.docs;
            if (!docs) {
                clearDocs();
                return;
            }
            let docsUrl = docs;
            // Update no version tag with version tag (and potentially switch to local docs)
            docsUrl = docsUrl.replace('https://docs.noodl.net', (0,utils_getDocsEndpoint/* default */.A)());
            docsUrl = docsUrl.replace('#/', '');
            const fullDocsUrl = docsUrl.replace('README', '').replace('.md', '');
            if (!docsUrl.endsWith('.md'))
                docsUrl = docsUrl += '.md';
            const dp = new DocsParser();
            dp.fetchPage(docsUrl, (el) => {
                setCurrentDocs({
                    content: el === null || el === void 0 ? void 0 : el.outerHTML,
                    url: (el === null || el === void 0 ? void 0 : el.outerHTML) ? fullDocsUrl : ''
                });
            });
        }, 300);
    }
    function cancelGetDocs() {
        clearTimeout(timer.current);
    }
    function clearDocs() {
        setCurrentDocs(emptyCurrentDocsValue);
    }
    return {
        getDocs,
        cancelGetDocs,
        clearDocs,
        currentDocs
    };
}
function useGetDefaultDocs() {
    const endpoint = getDocsEndpoint();
    const fullEndpoint = endpoint + '/nodepickerdefaults/index.json' + '?' + new Date().getTime();
    const [items, setItems] = useState([]);
    const res = useFetch(fullEndpoint);
    useEffect(() => {
        var _a;
        if ((_a = res.response) === null || _a === void 0 ? void 0 : _a.length) {
            setItems(res.response.map((t) => ({
                ...t,
                linkUrl: endpoint + '/' + t.linkUrl,
                imageUrl: t.imageUrl ? endpoint + '/nodepickerdefaults/' + t.imageUrl : undefined
            })));
        }
    }, [res.response]);
    return items;
}
const NODE_PICKER_NEWS_STATE_STORAGE_KEY = 'nodepicker_news_state';
/**
 * HACK: Clear the current node picker news state
 *       so the next time it will always show the first slide.
 */
function NodePickerClearNews() {
    localStorage.removeItem(NODE_PICKER_NEWS_STATE_STORAGE_KEY);
}
function getActiveIndex(items) {
    let activeIndex = 0;
    const storedData = localStorage.getItem(NODE_PICKER_NEWS_STATE_STORAGE_KEY);
    if (storedData) {
        const parsedData = JSON.parse(storedData);
        activeIndex = parsedData.activeIndex + 1;
        if (activeIndex >= items.length) {
            activeIndex = 0;
        }
    }
    localStorage.setItem(NODE_PICKER_NEWS_STATE_STORAGE_KEY, JSON.stringify({
        activeIndex
    }));
    return activeIndex;
}
function useGetSliderNews() {
    const endpoint = (0,utils_getDocsEndpoint/* default */.A)();
    const fullEndpoint = endpoint + '/nodepickerdefaults/news.json' + '?' + new Date().getTime();
    const [items, setItems] = (0,external_react_.useState)([]);
    const [activeIndex, setActiveIndex] = (0,external_react_.useState)(0);
    const res = useFetch_useFetch(fullEndpoint);
    (0,external_react_.useEffect)(() => {
        function parseAction(action) {
            switch (action.kind) {
                case 'link':
                    return {
                        kind: 'link',
                        linkUrl: String(action.linkUrl),
                        label: String(action.label)
                    };
                case 'action':
                    return {
                        kind: 'action',
                        action: String(action.action),
                        label: String(action.label)
                    };
            }
        }
        if (res.response && res.response.items.length) {
            const items = res.response.items.map((x) => ({
                supertitle: x.supertitle,
                title: x.title,
                text: x.text,
                action: typeof x.action === 'object' ? parseAction(x.action) : null,
                imageUrl: x.imageUrl ? endpoint + '/nodepickerdefaults/' + x.imageUrl : undefined
            }));
            setItems(items);
            setActiveIndex(getActiveIndex(items));
        }
    }, [res.response]);
    return { items, activeIndex };
}


/***/ }),

/***/ 38986:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  DummyTracker: () => (/* reexport */ DummyTracker),
  setTracker: () => (/* binding */ setTracker),
  tracker: () => (/* binding */ tracker)
});

;// ./src/editor/src/utils/tracker/tracker.ts
/**
 * I do nothin' da da da da da
 */
class DummyTracker {
    setUserInfo(info) { }
    track(name, args) { }
    increment(name, count) { }
    error(name, args) { }
}

;// ./src/editor/src/utils/tracker/index.ts


let tracker = new DummyTracker();
function setTracker(value) {
    tracker = value;
}



/***/ }),

/***/ 39015:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.BlocklyWorkspace-module__Root--oGlSB{display:flex;flex-direction:column;width:100%;height:100%;background-color:var(--theme-color-bg-1);overflow:hidden}.BlocklyWorkspace-module__BlocklyContainer--NrI0H{flex:1;width:100%;height:100%;position:relative}.BlocklyWorkspace-module__BlocklyContainer--NrI0H>.BlocklyWorkspace-module__injectionDiv--xcI3G{width:100% !important;height:100% !important}.blocklyToolboxDiv{background-color:var(--theme-color-bg-2) !important;border-right:1px solid var(--theme-color-border-default) !important}.blocklyTreeLabel{color:var(--theme-color-fg-default) !important;font-family:var(--theme-font-family) !important;font-size:13px !important}.blocklyTreeRow:hover{background-color:var(--theme-color-bg-3) !important}.blocklyTreeSelected{background-color:var(--theme-color-primary) !important}.blocklyFlyoutBackground{fill:var(--theme-color-bg-2) !important;fill-opacity:.95 !important}.blocklyZoom image{filter:brightness(0.8)}.blocklyTrash image{filter:brightness(0.8)}.blocklyContextMenu{background-color:var(--theme-color-bg-3) !important;border:1px solid var(--theme-color-border-default) !important;border-radius:4px !important;box-shadow:0 4px 12px rgba(0,0,0,.3) !important}.blocklyContextMenu .blocklyMenuItem{color:var(--theme-color-fg-default) !important;font-family:var(--theme-font-family) !important;font-size:13px !important;padding:6px 12px !important}.blocklyContextMenu .blocklyMenuItem:hover,.blocklyContextMenu .blocklyMenuItem:hover *{background-color:var(--theme-color-bg-4) !important;color:var(--theme-color-fg-default) !important}.blocklyContextMenu .blocklyMenuItem.blocklyMenuItemDisabled{color:var(--theme-color-fg-default-shy) !important;opacity:.5}.blocklyScrollbarHandle{fill:var(--theme-color-border-default) !important}.blocklyWidgetDiv,.blocklyDropDownDiv{z-index:10000 !important}.blocklyDropDownDiv,.blocklyDropDownDiv{background-color:var(--theme-color-bg-3) !important;max-height:400px !important;overflow-y:auto !important;overflow-x:hidden !important}.blocklyDropDownDiv>div,.blocklyDropDownDiv>div{background-color:var(--theme-color-bg-3) !important;max-height:400px !important;overflow-y:auto !important}.blocklyDropDownDiv svg,.blocklyDropDownDiv svg{background-color:var(--theme-color-bg-3) !important}.blocklyWidgetDiv input,.blocklyHtmlInput{background-color:var(--theme-color-bg-3) !important;color:var(--theme-color-fg-default) !important;border:1px solid var(--theme-color-border-default) !important;border-radius:4px !important;padding:4px 8px !important;font-family:var(--theme-font-family) !important}.goog-menu,.goog-menu{background-color:var(--theme-color-bg-3) !important;border:1px solid var(--theme-color-border-default) !important;border-radius:4px !important;box-shadow:0 4px 12px rgba(0,0,0,.3) !important;max-height:400px !important;overflow-y:auto !important;overflow-x:hidden !important;z-index:10001 !important}.blocklyDropDownDiv .blocklyMenuItem,.blocklyDropDownDiv .blocklyMenuItem{color:#fff !important;background-color:rgba(0,0,0,0) !important;padding:6px 12px !important;cursor:pointer !important;font-family:var(--theme-font-family) !important;font-size:13px !important}.blocklyDropDownDiv .blocklyMenuItem *,.blocklyDropDownDiv .blocklyMenuItem div,.blocklyDropDownDiv .blocklyMenuItem span,.blocklyDropDownDiv .blocklyMenuItem *,.blocklyDropDownDiv .blocklyMenuItem div,.blocklyDropDownDiv .blocklyMenuItem span{color:#fff !important}.blocklyDropDownDiv .blocklyMenuItem:hover,.blocklyDropDownDiv .blocklyMenuItem:hover *,.blocklyDropDownDiv .blocklyMenuItem:hover div,.blocklyDropDownDiv .blocklyMenuItem:hover span,.blocklyDropDownDiv .blocklyMenuItem:hover,.blocklyDropDownDiv .blocklyMenuItem:hover *,.blocklyDropDownDiv .blocklyMenuItem:hover div,.blocklyDropDownDiv .blocklyMenuItem:hover span{background-color:var(--theme-color-bg-4) !important;color:#fff !important}.blocklyDropDownDiv .blocklyMenuItem[aria-selected=true],.blocklyDropDownDiv .blocklyMenuItem[aria-selected=true] *,.blocklyDropDownDiv .blocklyMenuItem[aria-selected=true],.blocklyDropDownDiv .blocklyMenuItem[aria-selected=true] *{background-color:var(--theme-color-primary) !important;color:#fff !important}.blocklyDropDownDiv .blocklyMenuItem[aria-disabled=true],.blocklyDropDownDiv .blocklyMenuItem[aria-disabled=true] *,.blocklyDropDownDiv .blocklyMenuItem[aria-disabled=true],.blocklyDropDownDiv .blocklyMenuItem[aria-disabled=true] *{color:#999 !important;opacity:.5;cursor:not-allowed !important}.blocklyMenuItemContent,.blocklyMenuItemContent{color:#fff !important}.blocklyMenuItemContent *,.blocklyMenuItemContent div,.blocklyMenuItemContent span,.blocklyMenuItemContent *,.blocklyMenuItemContent div,.blocklyMenuItemContent span{color:#fff !important}.goog-menuitem,.goog-option,.goog-menuitem,.goog-option{color:#fff !important;background-color:rgba(0,0,0,0) !important;padding:6px 12px !important;font-family:var(--theme-font-family) !important;font-size:13px !important}.goog-menuitem *,.goog-menuitem div,.goog-menuitem span,.goog-option *,.goog-option div,.goog-option span,.goog-menuitem *,.goog-menuitem div,.goog-menuitem span,.goog-option *,.goog-option div,.goog-option span{color:#fff !important}.goog-menuitem:hover,.goog-menuitem:hover *,.goog-option:hover,.goog-option:hover *,.goog-menuitem:hover,.goog-menuitem:hover *,.goog-option:hover,.goog-option:hover *{background-color:var(--theme-color-bg-4) !important}.goog-menuitem-content,.goog-menuitem-content{color:#fff !important}.goog-menuitem-content *,.goog-menuitem-content *{color:#fff !important}.blocklyDropDownContent{max-height:400px !important;overflow-y:auto !important;overflow-x:hidden !important}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/BlocklyEditor/BlocklyWorkspace.module.scss"],"names":[],"mappings":"AAOA,sCACE,YAAA,CACA,qBAAA,CACA,UAAA,CACA,WAAA,CACA,wCAAA,CACA,eAAA,CAGF,kDACE,MAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CAGA,gGACE,qBAAA,CACA,sBAAA,CAOF,mBACE,mDAAA,CACA,mEAAA,CAGF,kBACE,8CAAA,CACA,+CAAA,CACA,yBAAA,CAGF,sBACE,mDAAA,CAGF,qBACE,sDAAA,CAIF,yBACE,uCAAA,CACA,2BAAA,CAQA,mBACE,sBAAA,CAMF,oBACE,sBAAA,CAKJ,oBACE,mDAAA,CACA,6DAAA,CACA,4BAAA,CACA,+CAAA,CAGF,qCACE,8CAAA,CACA,+CAAA,CACA,yBAAA,CACA,2BAAA,CAEA,wFAEE,mDAAA,CACA,8CAAA,CAGF,6DACE,kDAAA,CACA,UAAA,CAKJ,wBACE,iDAAA,CAKF,sCAEE,wBAAA,CAIF,wCAEE,mDAAA,CACA,2BAAA,CACA,0BAAA,CACA,4BAAA,CAGA,gDACE,mDAAA,CACA,2BAAA,CACA,0BAAA,CAIF,gDACE,mDAAA,CAKJ,0CAEE,mDAAA,CACA,8CAAA,CACA,6DAAA,CACA,4BAAA,CACA,0BAAA,CACA,+CAAA,CAMF,sBAEE,mDAAA,CACA,6DAAA,CACA,4BAAA,CACA,+CAAA,CACA,2BAAA,CACA,0BAAA,CACA,4BAAA,CACA,wBAAA,CAIF,0EAEE,qBAAA,CACA,yCAAA,CACA,2BAAA,CACA,yBAAA,CACA,+CAAA,CACA,yBAAA,CAGA,oPAGE,qBAAA,CAIF,8WAIE,mDAAA,CACA,qBAAA,CAGF,wOAEE,sDAAA,CACA,qBAAA,CAGF,wOAEE,qBAAA,CACA,UAAA,CACA,6BAAA,CAKJ,gDAEE,qBAAA,CAEA,sKAGE,qBAAA,CAKJ,wDAIE,qBAAA,CACA,yCAAA,CACA,2BAAA,CACA,+CAAA,CACA,yBAAA,CAEA,oNAGE,qBAAA,CAGF,wKAEE,mDAAA,CAIJ,8CAEE,qBAAA,CAEA,kDACE,qBAAA,CAKJ,wBACE,2BAAA,CACA,0BAAA,CACA,4BAAA","sourcesContent":["/**\n * BlocklyWorkspace Styles\n * \n * Styling for the Blockly visual programming workspace.\n * Uses theme tokens for consistent integration with Noodl editor.\n */\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  width: 100%;\n  height: 100%;\n  background-color: var(--theme-color-bg-1);\n  overflow: hidden;\n}\n\n.BlocklyContainer {\n  flex: 1;\n  width: 100%;\n  height: 100%;\n  position: relative;\n\n  /* Ensure Blockly SVG fills container */\n  & > .injectionDiv {\n    width: 100% !important;\n    height: 100% !important;\n  }\n}\n\n/* Override Blockly default styles to match Noodl theme */\n:global {\n  /* Toolbox styling */\n  .blocklyToolboxDiv {\n    background-color: var(--theme-color-bg-2) !important;\n    border-right: 1px solid var(--theme-color-border-default) !important;\n  }\n\n  .blocklyTreeLabel {\n    color: var(--theme-color-fg-default) !important;\n    font-family: var(--theme-font-family) !important;\n    font-size: 13px !important;\n  }\n\n  .blocklyTreeRow:hover {\n    background-color: var(--theme-color-bg-3) !important;\n  }\n\n  .blocklyTreeSelected {\n    background-color: var(--theme-color-primary) !important;\n  }\n\n  /* Flyout styling */\n  .blocklyFlyoutBackground {\n    fill: var(--theme-color-bg-2) !important;\n    fill-opacity: 0.95 !important;\n  }\n\n  /* Block styling - keep default Blockly colors for now */\n  /* May customize later to match Noodl node colors */\n\n  /* Zoom controls */\n  .blocklyZoom {\n    & image {\n      filter: brightness(0.8);\n    }\n  }\n\n  /* Trashcan */\n  .blocklyTrash {\n    & image {\n      filter: brightness(0.8);\n    }\n  }\n\n  /* Context menu */\n  .blocklyContextMenu {\n    background-color: var(--theme-color-bg-3) !important;\n    border: 1px solid var(--theme-color-border-default) !important;\n    border-radius: 4px !important;\n    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;\n  }\n\n  .blocklyContextMenu .blocklyMenuItem {\n    color: var(--theme-color-fg-default) !important;\n    font-family: var(--theme-font-family) !important;\n    font-size: 13px !important;\n    padding: 6px 12px !important;\n\n    &:hover,\n    &:hover * {\n      background-color: var(--theme-color-bg-4) !important;\n      color: var(--theme-color-fg-default) !important;\n    }\n\n    &.blocklyMenuItemDisabled {\n      color: var(--theme-color-fg-default-shy) !important;\n      opacity: 0.5;\n    }\n  }\n\n  /* Scrollbars */\n  .blocklyScrollbarHandle {\n    fill: var(--theme-color-border-default) !important;\n  }\n\n  /* Field editor backgrounds (dropdowns, text inputs, etc.) */\n  /* NOTE: blocklyWidgetDiv and blocklyDropDownDiv are rendered at document root! */\n  .blocklyWidgetDiv,\n  .blocklyDropDownDiv {\n    z-index: 10000 !important; /* Ensure it's above everything */\n  }\n\n  /* Blockly dropdown container - DARK BACKGROUND */\n  .blocklyDropDownDiv,\n  :global(.blocklyDropDownDiv) {\n    background-color: var(--theme-color-bg-3) !important; /* DARK background */\n    max-height: 400px !important;\n    overflow-y: auto !important;\n    overflow-x: hidden !important;\n\n    /* Inner scrollable container */\n    & > div {\n      background-color: var(--theme-color-bg-3) !important;\n      max-height: 400px !important;\n      overflow-y: auto !important;\n    }\n\n    /* SVG containers inside dropdown */\n    & svg {\n      background-color: var(--theme-color-bg-3) !important;\n    }\n  }\n\n  /* Text input fields */\n  .blocklyWidgetDiv input,\n  .blocklyHtmlInput {\n    background-color: var(--theme-color-bg-3) !important;\n    color: var(--theme-color-fg-default) !important;\n    border: 1px solid var(--theme-color-border-default) !important;\n    border-radius: 4px !important;\n    padding: 4px 8px !important;\n    font-family: var(--theme-font-family) !important;\n  }\n\n  /* Dropdown menus - DARK BACKGROUND with WHITE TEXT (matches Noodl theme) */\n  /* Target ACTUAL Blockly classes: .blocklyMenuItem not .goog-menuitem */\n\n  .goog-menu,\n  :global(.goog-menu) {\n    background-color: var(--theme-color-bg-3) !important; /* DARK background */\n    border: 1px solid var(--theme-color-border-default) !important;\n    border-radius: 4px !important;\n    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;\n    max-height: 400px !important;\n    overflow-y: auto !important;\n    overflow-x: hidden !important;\n    z-index: 10001 !important;\n  }\n\n  /* Target Blockly's ACTUAL menu item class - DROPDOWN MENUS */\n  .blocklyDropDownDiv .blocklyMenuItem,\n  :global(.blocklyDropDownDiv) :global(.blocklyMenuItem) {\n    color: #ffffff !important; /* WHITE text */\n    background-color: transparent !important;\n    padding: 6px 12px !important;\n    cursor: pointer !important;\n    font-family: var(--theme-font-family) !important;\n    font-size: 13px !important;\n\n    /* ALL children white */\n    & *,\n    & div,\n    & span {\n      color: #ffffff !important;\n    }\n\n    /* HOVER - Keep white text with lighter background */\n    &:hover,\n    &:hover *,\n    &:hover div,\n    &:hover span {\n      background-color: var(--theme-color-bg-4) !important;\n      color: #ffffff !important; /* WHITE on hover */\n    }\n\n    &[aria-selected='true'],\n    &[aria-selected='true'] * {\n      background-color: var(--theme-color-primary) !important;\n      color: #ffffff !important;\n    }\n\n    &[aria-disabled='true'],\n    &[aria-disabled='true'] * {\n      color: #999999 !important;\n      opacity: 0.5;\n      cursor: not-allowed !important;\n    }\n  }\n\n  /* Target Blockly's ACTUAL content class */\n  .blocklyMenuItemContent,\n  :global(.blocklyMenuItemContent) {\n    color: #ffffff !important;\n\n    & *,\n    & div,\n    & span {\n      color: #ffffff !important;\n    }\n  }\n\n  /* Fallback for goog- classes if they exist */\n  .goog-menuitem,\n  .goog-option,\n  :global(.goog-menuitem),\n  :global(.goog-option) {\n    color: #ffffff !important;\n    background-color: transparent !important;\n    padding: 6px 12px !important;\n    font-family: var(--theme-font-family) !important;\n    font-size: 13px !important;\n\n    & *,\n    & div,\n    & span {\n      color: #ffffff !important;\n    }\n\n    &:hover,\n    &:hover * {\n      background-color: var(--theme-color-bg-4) !important;\n    }\n  }\n\n  .goog-menuitem-content,\n  :global(.goog-menuitem-content) {\n    color: #ffffff !important;\n\n    & * {\n      color: #ffffff !important;\n    }\n  }\n\n  /* Blockly dropdown content container */\n  :global(.blocklyDropDownContent) {\n    max-height: 400px !important;\n    overflow-y: auto !important;\n    overflow-x: hidden !important;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `BlocklyWorkspace-module__Root--oGlSB`,
	"BlocklyContainer": `BlocklyWorkspace-module__BlocklyContainer--NrI0H`,
	"injectionDiv": `BlocklyWorkspace-module__injectionDiv--xcI3G`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 39357:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-text-button {
	box-sizing: border-box;
	display: flex;
	width: 100%;
	padding: 4px;
	text-align: center;
	cursor: pointer;
	justify-content: center;
	align-items: center;
}

.monaco-text-button:focus {
	outline-offset: 2px !important;
}

.monaco-text-button:hover {
	text-decoration: none !important;
}

.monaco-button.disabled:focus,
.monaco-button.disabled {
	opacity: 0.4 !important;
	cursor: default;
}

.monaco-text-button > .codicon {
	margin: 0 0.2em;
	color: inherit !important;
}

.monaco-button-dropdown {
	display: flex;
	cursor: pointer;
}

.monaco-button-dropdown.disabled {
	cursor: default;
}

.monaco-button-dropdown > .monaco-button:focus {
	outline-offset: -1px !important;
}

.monaco-button-dropdown.disabled > .monaco-button.disabled,
.monaco-button-dropdown.disabled > .monaco-button.disabled:focus,
.monaco-button-dropdown.disabled > .monaco-button-dropdown-separator {
	opacity: 0.4 !important;
}

.monaco-button-dropdown > .monaco-button.monaco-text-button {
	border-right-width: 0 !important;
}

.monaco-button-dropdown .monaco-button-dropdown-separator {
	padding: 4px 0;
	cursor: default;
}

.monaco-button-dropdown .monaco-button-dropdown-separator > div {
	height: 100%;
	width: 1px;
}

.monaco-button-dropdown > .monaco-button.monaco-dropdown-button {
	border-left-width: 0 !important;
}

.monaco-description-button {
	flex-direction: column;
}

.monaco-description-button .monaco-button-label {
	font-weight: 500;
}

.monaco-description-button .monaco-button-description {
	font-style: italic;
}

.monaco-description-button .monaco-button-label,
.monaco-description-button .monaco-button-description
{
	display: flex;
	justify-content: center;
	align-items: center;
}

.monaco-description-button .monaco-button-label > .codicon,
.monaco-description-button .monaco-button-description > .codicon
{
	margin: 0 0.2em;
	color: inherit !important;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/button/button.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,sBAAsB;CACtB,aAAa;CACb,WAAW;CACX,YAAY;CACZ,kBAAkB;CAClB,eAAe;CACf,uBAAuB;CACvB,mBAAmB;AACpB;;AAEA;CACC,8BAA8B;AAC/B;;AAEA;CACC,gCAAgC;AACjC;;AAEA;;CAEC,uBAAuB;CACvB,eAAe;AAChB;;AAEA;CACC,eAAe;CACf,yBAAyB;AAC1B;;AAEA;CACC,aAAa;CACb,eAAe;AAChB;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,+BAA+B;AAChC;;AAEA;;;CAGC,uBAAuB;AACxB;;AAEA;CACC,gCAAgC;AACjC;;AAEA;CACC,cAAc;CACd,eAAe;AAChB;;AAEA;CACC,YAAY;CACZ,UAAU;AACX;;AAEA;CACC,+BAA+B;AAChC;;AAEA;CACC,sBAAsB;AACvB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,kBAAkB;AACnB;;AAEA;;;CAGC,aAAa;CACb,uBAAuB;CACvB,mBAAmB;AACpB;;AAEA;;;CAGC,eAAe;CACf,yBAAyB;AAC1B","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-text-button {\n\tbox-sizing: border-box;\n\tdisplay: flex;\n\twidth: 100%;\n\tpadding: 4px;\n\ttext-align: center;\n\tcursor: pointer;\n\tjustify-content: center;\n\talign-items: center;\n}\n\n.monaco-text-button:focus {\n\toutline-offset: 2px !important;\n}\n\n.monaco-text-button:hover {\n\ttext-decoration: none !important;\n}\n\n.monaco-button.disabled:focus,\n.monaco-button.disabled {\n\topacity: 0.4 !important;\n\tcursor: default;\n}\n\n.monaco-text-button > .codicon {\n\tmargin: 0 0.2em;\n\tcolor: inherit !important;\n}\n\n.monaco-button-dropdown {\n\tdisplay: flex;\n\tcursor: pointer;\n}\n\n.monaco-button-dropdown.disabled {\n\tcursor: default;\n}\n\n.monaco-button-dropdown > .monaco-button:focus {\n\toutline-offset: -1px !important;\n}\n\n.monaco-button-dropdown.disabled > .monaco-button.disabled,\n.monaco-button-dropdown.disabled > .monaco-button.disabled:focus,\n.monaco-button-dropdown.disabled > .monaco-button-dropdown-separator {\n\topacity: 0.4 !important;\n}\n\n.monaco-button-dropdown > .monaco-button.monaco-text-button {\n\tborder-right-width: 0 !important;\n}\n\n.monaco-button-dropdown .monaco-button-dropdown-separator {\n\tpadding: 4px 0;\n\tcursor: default;\n}\n\n.monaco-button-dropdown .monaco-button-dropdown-separator > div {\n\theight: 100%;\n\twidth: 1px;\n}\n\n.monaco-button-dropdown > .monaco-button.monaco-dropdown-button {\n\tborder-left-width: 0 !important;\n}\n\n.monaco-description-button {\n\tflex-direction: column;\n}\n\n.monaco-description-button .monaco-button-label {\n\tfont-weight: 500;\n}\n\n.monaco-description-button .monaco-button-description {\n\tfont-style: italic;\n}\n\n.monaco-description-button .monaco-button-label,\n.monaco-description-button .monaco-button-description\n{\n\tdisplay: flex;\n\tjustify-content: center;\n\talign-items: center;\n}\n\n.monaco-description-button .monaco-button-label > .codicon,\n.monaco-description-button .monaco-button-description > .codicon\n{\n\tmargin: 0 0.2em;\n\tcolor: inherit !important;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 39540:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-action-bar .action-item.menu-entry .action-label.icon {
	width: 16px;
	height: 16px;
	background-repeat: no-repeat;
	background-position: 50%;
	background-size: 16px;
}


.monaco-dropdown-with-default {
	display: flex !important;
	flex-direction: row;
	border-radius: 5px;
}

.monaco-dropdown-with-default > .action-container > .action-label {
	margin-right: 0;
}

.monaco-dropdown-with-default > .action-container.menu-entry > .action-label.icon {
	width: 16px;
	height: 16px;
	background-repeat: no-repeat;
	background-position: 50%;
	background-size: 16px;
}

.monaco-dropdown-with-default > .dropdown-action-container > .monaco-dropdown > .dropdown-label .codicon[class*='codicon-'] {
	font-size: 12px;
	padding-left: 0px;
	padding-right: 0px;
	line-height: 16px;
	margin-left: -3px;
}

.monaco-dropdown-with-default > .dropdown-action-container > .monaco-dropdown > .dropdown-label > .action-label {
	display: block;
	background-size: 16px;
	background-position: center center;
	background-repeat: no-repeat;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/platform/actions/browser/menuEntryActionViewItem.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,WAAW;CACX,YAAY;CACZ,4BAA4B;CAC5B,wBAAwB;CACxB,qBAAqB;AACtB;;;AAGA;CACC,wBAAwB;CACxB,mBAAmB;CACnB,kBAAkB;AACnB;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,WAAW;CACX,YAAY;CACZ,4BAA4B;CAC5B,wBAAwB;CACxB,qBAAqB;AACtB;;AAEA;CACC,eAAe;CACf,iBAAiB;CACjB,kBAAkB;CAClB,iBAAiB;CACjB,iBAAiB;AAClB;;AAEA;CACC,cAAc;CACd,qBAAqB;CACrB,kCAAkC;CAClC,4BAA4B;AAC7B","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-action-bar .action-item.menu-entry .action-label.icon {\n\twidth: 16px;\n\theight: 16px;\n\tbackground-repeat: no-repeat;\n\tbackground-position: 50%;\n\tbackground-size: 16px;\n}\n\n\n.monaco-dropdown-with-default {\n\tdisplay: flex !important;\n\tflex-direction: row;\n\tborder-radius: 5px;\n}\n\n.monaco-dropdown-with-default > .action-container > .action-label {\n\tmargin-right: 0;\n}\n\n.monaco-dropdown-with-default > .action-container.menu-entry > .action-label.icon {\n\twidth: 16px;\n\theight: 16px;\n\tbackground-repeat: no-repeat;\n\tbackground-position: 50%;\n\tbackground-size: 16px;\n}\n\n.monaco-dropdown-with-default > .dropdown-action-container > .monaco-dropdown > .dropdown-label .codicon[class*='codicon-'] {\n\tfont-size: 12px;\n\tpadding-left: 0px;\n\tpadding-right: 0px;\n\tline-height: 16px;\n\tmargin-left: -3px;\n}\n\n.monaco-dropdown-with-default > .dropdown-action-container > .monaco-dropdown > .dropdown-label > .action-label {\n\tdisplay: block;\n\tbackground-size: 16px;\n\tbackground-position: center center;\n\tbackground-repeat: no-repeat;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 39704:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSlidersFilled = function SvgSlidersFilled(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M7.97489 8.51569C8.40425 6.99323 9.80344 5.8774 11.4633 5.8774C13.1231 5.8774 14.5223 6.99323 14.9516 8.51569L25.8241 8.51569C26.3648 8.51569 26.8032 8.95408 26.8032 9.49486C26.8032 10.0356 26.3648 10.474 25.8241 10.474L14.9553 10.474C14.5303 12.0032 13.1279 13.1255 11.4633 13.1255C9.79866 13.1255 8.39619 12.0032 7.9712 10.474L4.28239 10.474C3.74161 10.474 3.30322 10.0356 3.30322 9.49486C3.30322 8.95408 3.74161 8.51569 4.28239 8.51569L7.97489 8.51569Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M22.14 22.3947C21.7139 23.9229 20.3118 25.0441 18.6478 25.0441C16.9837 25.0441 15.5816 23.9229 15.1556 22.3947L4.28337 22.3947C3.74259 22.3947 3.3042 21.9563 3.3042 21.4155C3.3042 20.8747 3.74259 20.4363 4.28337 20.4363L15.1575 20.4363C15.5859 18.9118 16.9863 17.7941 18.6478 17.7941C20.3092 17.7941 21.7096 18.9118 22.138 20.4364L25.825 20.4364C26.3658 20.4364 26.8042 20.8747 26.8042 21.4155C26.8042 21.9563 26.3658 22.3947 25.825 22.3947L22.14 22.3947Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSlidersFilled);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "a48840ec1287739357aaef2f7a60c7fc.svg");

/***/ }),

/***/ 39773:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Files = void 0;
const resource_1 = __webpack_require__(39929);
const pagination_1 = __webpack_require__(92081);
const headers_1 = __webpack_require__(79973);
const uploads_1 = __webpack_require__(76409);
const path_1 = __webpack_require__(20854);
class Files extends resource_1.APIResource {
    /**
     * List Files
     *
     * @example
     * ```ts
     * // Automatically fetches more pages as needed.
     * for await (const fileMetadata of client.beta.files.list()) {
     *   // ...
     * }
     * ```
     */
    list(params = {}, options) {
        const { betas, ...query } = params ?? {};
        return this._client.getAPIList('/v1/files', (pagination_1.Page), {
            query,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * Delete File
     *
     * @example
     * ```ts
     * const deletedFile = await client.beta.files.delete(
     *   'file_id',
     * );
     * ```
     */
    delete(fileID, params = {}, options) {
        const { betas } = params ?? {};
        return this._client.delete((0, path_1.path) `/v1/files/${fileID}`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * Download File
     *
     * @example
     * ```ts
     * const response = await client.beta.files.download(
     *   'file_id',
     * );
     *
     * const content = await response.blob();
     * console.log(content);
     * ```
     */
    download(fileID, params = {}, options) {
        const { betas } = params ?? {};
        return this._client.get((0, path_1.path) `/v1/files/${fileID}/content`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                {
                    'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString(),
                    Accept: 'application/binary',
                },
                options?.headers,
            ]),
            __binaryResponse: true,
        });
    }
    /**
     * Get File Metadata
     *
     * @example
     * ```ts
     * const fileMetadata =
     *   await client.beta.files.retrieveMetadata('file_id');
     * ```
     */
    retrieveMetadata(fileID, params = {}, options) {
        const { betas } = params ?? {};
        return this._client.get((0, path_1.path) `/v1/files/${fileID}`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * Upload File
     *
     * @example
     * ```ts
     * const fileMetadata = await client.beta.files.upload({
     *   file: fs.createReadStream('path/to/file'),
     * });
     * ```
     */
    upload(params, options) {
        const { betas, ...body } = params;
        return this._client.post('/v1/files', (0, uploads_1.multipartFormRequestOptions)({
            body,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },
                options?.headers,
            ]),
        }, this._client));
    }
}
exports.Files = Files;
//# sourceMappingURL=files.js.map

/***/ }),

/***/ 39804:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   H: () => (/* binding */ EditorSettings)
/* harmony export */ });
/* harmony import */ var _noodl_platform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37218);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47821);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_shared_model__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(80002);
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(underscore__WEBPACK_IMPORTED_MODULE_2__);



function deepMerge(dest, source) {
    for (const prop in source) {
        const sourceVal = source[prop];
        const destVal = dest[prop];
        if (prop in dest && underscore__WEBPACK_IMPORTED_MODULE_2___default().isObject(sourceVal) && underscore__WEBPACK_IMPORTED_MODULE_2___default().isObject(destVal)) {
            deepMerge(destVal, sourceVal);
        }
        else {
            dest[prop] = sourceVal;
        }
    }
    return dest;
}
function debounce(func, timeout = 300) {
    let timer;
    return () => {
        clearTimeout(timer);
        timer = setTimeout(func, timeout);
    };
}
class EditorSettings extends (_shared_model__WEBPACK_IMPORTED_MODULE_1___default()) {
    constructor() {
        super();
        this.settings = {};
        this.fetch();
        this.debouncedStore = debounce(() => this.store(), 1000);
    }
    async fetch() {
        const local = await _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.JSONStorage.get('editorSettings');
        this.settings = local.settings || {};
    }
    async store() {
        await _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.JSONStorage.set('editorSettings', { settings: this.settings });
    }
    // @ts-expect-error Property 'set' in type 'EditorSettings' is not assignable to the same property in base type 'Model'.
    set(key, data) {
        this.settings[key] = data;
        this.debouncedStore();
        this.notifyListeners(`updated`, { key });
    }
    setMerge(key, data) {
        this.settings[key] = deepMerge(this.settings[key] || {}, data);
        this.debouncedStore();
    }
    get(key) {
        return this.settings[key];
    }
}
EditorSettings.instance = new EditorSettings();


/***/ }),

/***/ 39810:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.readEnv = void 0;
/**
 * Read an environment variable.
 *
 * Trims beginning and trailing whitespace.
 *
 * Will return undefined if the environment variable doesn't exist or cannot be accessed.
 */
const readEnv = (env) => {
    if (typeof globalThis.process !== 'undefined') {
        return globalThis.process.env?.[env]?.trim() ?? undefined;
    }
    if (typeof globalThis.Deno !== 'undefined') {
        return globalThis.Deno.env?.get?.(env)?.trim();
    }
    return undefined;
};
exports.readEnv = readEnv;
//# sourceMappingURL=env.js.map

/***/ }),

/***/ 39929:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.APIResource = void 0;
class APIResource {
    constructor(client) {
        this._client = client;
    }
}
exports.APIResource = APIResource;
//# sourceMappingURL=resource.js.map

/***/ }),

/***/ 39961:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.DataGrid-module__GridContainer--Gyzhy{width:100%;height:100%;overflow:auto}.DataGrid-module__Grid--Sx50P{width:100%;border-collapse:collapse;font-size:12px}.DataGrid-module__Grid--Sx50P thead{position:sticky;top:0;z-index:1;background-color:var(--theme-color-bg-3)}.DataGrid-module__Grid--Sx50P th,.DataGrid-module__Grid--Sx50P td{padding:8px 12px;text-align:left;border-bottom:1px solid var(--theme-color-border-default)}.DataGrid-module__HeaderCell--hYAMy{background-color:var(--theme-color-bg-3);font-weight:500;color:var(--theme-color-fg-default);white-space:nowrap}.DataGrid-module__HeaderContent--g7aKI{display:flex;align-items:center;gap:8px}.DataGrid-module__HeaderName--rLTxO{font-weight:500}.DataGrid-module__TypeBadge--zCneL{font-size:9px;padding:2px 6px;border-radius:4px;background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-default-shy);text-transform:uppercase;font-weight:600}.DataGrid-module__TypeString--dvtWE{background-color:var(--theme-color-primary);color:var(--theme-color-fg-on-primary)}.DataGrid-module__TypeNumber--fA7XD{background-color:var(--theme-color-success);color:#fff}.DataGrid-module__TypeBoolean--CbDi2{background-color:var(--theme-color-notice);color:#fff}.DataGrid-module__TypeDate--Fv_og{background-color:#8b5cf6;color:#fff}.DataGrid-module__TypeObject--yz5vw{background-color:#ec4899;color:#fff}.DataGrid-module__TypeArray--BGG11{background-color:#6366f1;color:#fff}.DataGrid-module__TypePointer--gGFTt{background-color:var(--theme-color-danger);color:#fff}.DataGrid-module__CheckboxCol--ONN6B{width:40px;text-align:center;padding:8px}.DataGrid-module__CheckboxCol--ONN6B input[type=checkbox]{cursor:pointer}.DataGrid-module__ActionsCol--HF9Tx{width:60px;text-align:center;padding:8px;color:var(--theme-color-fg-default)}.DataGrid-module__Cell--DE7Sw{max-width:250px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--theme-color-fg-default)}.DataGrid-module__CellValue--Cnj2C{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--theme-color-fg-default)}.DataGrid-module__EditableCell--GoVQN{cursor:pointer}.DataGrid-module__EditableCell--GoVQN:hover{background-color:var(--theme-color-bg-3)}.DataGrid-module__ReadOnlyCell--H1HEB{color:var(--theme-color-fg-default-shy);font-family:monospace;font-size:11px}.DataGrid-module__SelectedRow--c4k4O{background-color:var(--theme-color-primary-muted)}.DataGrid-module__SelectedRow--c4k4O:hover{background-color:var(--theme-color-primary-muted)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/databrowser/DataGrid.module.scss"],"names":[],"mappings":"AAIA,uCACE,UAAA,CACA,WAAA,CACA,aAAA,CAGF,8BACE,UAAA,CACA,wBAAA,CACA,cAAA,CAGF,oCACE,eAAA,CACA,KAAA,CACA,SAAA,CACA,wCAAA,CAGF,kEAEE,gBAAA,CACA,eAAA,CACA,yDAAA,CAGF,oCACE,wCAAA,CACA,eAAA,CACA,mCAAA,CACA,kBAAA,CAGF,uCACE,YAAA,CACA,kBAAA,CACA,OAAA,CAGF,oCACE,eAAA,CAGF,mCACE,aAAA,CACA,eAAA,CACA,iBAAA,CACA,wCAAA,CACA,uCAAA,CACA,wBAAA,CACA,eAAA,CAGF,oCACE,2CAAA,CACA,sCAAA,CAGF,oCACE,2CAAA,CACA,UAAA,CAGF,qCACE,0CAAA,CACA,UAAA,CAGF,kCACE,wBAAA,CACA,UAAA,CAGF,oCACE,wBAAA,CACA,UAAA,CAGF,mCACE,wBAAA,CACA,UAAA,CAGF,qCACE,0CAAA,CACA,UAAA,CAGF,qCACE,UAAA,CACA,iBAAA,CACA,WAAA,CAEA,0DACE,cAAA,CAIJ,oCACE,UAAA,CACA,iBAAA,CACA,WAAA,CACA,mCAAA,CAGF,8BACE,eAAA,CACA,eAAA,CACA,sBAAA,CACA,kBAAA,CACA,mCAAA,CAGF,mCACE,eAAA,CACA,sBAAA,CACA,kBAAA,CACA,mCAAA,CAGF,sCACE,cAAA,CAEA,4CACE,wCAAA,CAIJ,sCACE,uCAAA,CACA,qBAAA,CACA,cAAA,CAGF,qCACE,iDAAA,CAGF,2CACE,iDAAA","sourcesContent":["/**\n * DataGrid styles\n */\n\n.GridContainer {\n  width: 100%;\n  height: 100%;\n  overflow: auto;\n}\n\n.Grid {\n  width: 100%;\n  border-collapse: collapse;\n  font-size: 12px;\n}\n\n.Grid thead {\n  position: sticky;\n  top: 0;\n  z-index: 1;\n  background-color: var(--theme-color-bg-3);\n}\n\n.Grid th,\n.Grid td {\n  padding: 8px 12px;\n  text-align: left;\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.HeaderCell {\n  background-color: var(--theme-color-bg-3);\n  font-weight: 500;\n  color: var(--theme-color-fg-default);\n  white-space: nowrap;\n}\n\n.HeaderContent {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n.HeaderName {\n  font-weight: 500;\n}\n\n.TypeBadge {\n  font-size: 9px;\n  padding: 2px 6px;\n  border-radius: 4px;\n  background-color: var(--theme-color-bg-1);\n  color: var(--theme-color-fg-default-shy);\n  text-transform: uppercase;\n  font-weight: 600;\n}\n\n.TypeString {\n  background-color: var(--theme-color-primary);\n  color: var(--theme-color-fg-on-primary);\n}\n\n.TypeNumber {\n  background-color: var(--theme-color-success);\n  color: white;\n}\n\n.TypeBoolean {\n  background-color: var(--theme-color-notice);\n  color: white;\n}\n\n.TypeDate {\n  background-color: #8b5cf6;\n  color: white;\n}\n\n.TypeObject {\n  background-color: #ec4899;\n  color: white;\n}\n\n.TypeArray {\n  background-color: #6366f1;\n  color: white;\n}\n\n.TypePointer {\n  background-color: var(--theme-color-danger);\n  color: white;\n}\n\n.CheckboxCol {\n  width: 40px;\n  text-align: center;\n  padding: 8px;\n\n  input[type='checkbox'] {\n    cursor: pointer;\n  }\n}\n\n.ActionsCol {\n  width: 60px;\n  text-align: center;\n  padding: 8px;\n  color: var(--theme-color-fg-default);\n}\n\n.Cell {\n  max-width: 250px;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n  color: var(--theme-color-fg-default);\n}\n\n.CellValue {\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n  color: var(--theme-color-fg-default);\n}\n\n.EditableCell {\n  cursor: pointer;\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n.ReadOnlyCell {\n  color: var(--theme-color-fg-default-shy);\n  font-family: monospace;\n  font-size: 11px;\n}\n\n.SelectedRow {\n  background-color: var(--theme-color-primary-muted);\n}\n\n.SelectedRow:hover {\n  background-color: var(--theme-color-primary-muted);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"GridContainer": `DataGrid-module__GridContainer--Gyzhy`,
	"Grid": `DataGrid-module__Grid--Sx50P`,
	"HeaderCell": `DataGrid-module__HeaderCell--hYAMy`,
	"HeaderContent": `DataGrid-module__HeaderContent--g7aKI`,
	"HeaderName": `DataGrid-module__HeaderName--rLTxO`,
	"TypeBadge": `DataGrid-module__TypeBadge--zCneL`,
	"TypeString": `DataGrid-module__TypeString--dvtWE`,
	"TypeNumber": `DataGrid-module__TypeNumber--fA7XD`,
	"TypeBoolean": `DataGrid-module__TypeBoolean--CbDi2`,
	"TypeDate": `DataGrid-module__TypeDate--Fv_og`,
	"TypeObject": `DataGrid-module__TypeObject--yz5vw`,
	"TypeArray": `DataGrid-module__TypeArray--BGG11`,
	"TypePointer": `DataGrid-module__TypePointer--gGFTt`,
	"CheckboxCol": `DataGrid-module__CheckboxCol--ONN6B`,
	"ActionsCol": `DataGrid-module__ActionsCol--HF9Tx`,
	"Cell": `DataGrid-module__Cell--DE7Sw`,
	"CellValue": `DataGrid-module__CellValue--Cnj2C`,
	"EditableCell": `DataGrid-module__EditableCell--GoVQN`,
	"ReadOnlyCell": `DataGrid-module__ReadOnlyCell--H1HEB`,
	"SelectedRow": `DataGrid-module__SelectedRow--c4k4O`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 40343:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ProjectCard-module__Root--Jyjjg{display:flex;flex-direction:column;height:100%}.ProjectCard-module__ImageContainer--WViau{flex-grow:0;flex-shrink:0;position:relative;background-color:var(--theme-color-fg-muted)}.ProjectCard-module__ImageContainer--WViau::after{content:"";display:block;height:0;padding-bottom:56.4971751412%}.ProjectCard-module__Image--CL6tx{background-position:center;position:absolute;background-repeat:no-repeat;background-size:cover;top:0;bottom:0;left:0;right:0}.ProjectCard-module__Content--bweSI{position:relative;background-color:var(--theme-color-bg-1);flex-grow:1;display:flex;flex-direction:column;justify-content:space-between;padding:16px 24px}.ProjectCard-module__HoverOverlay--gLzIf,.ProjectCard-module__ImportIndicator--B955O,.ProjectCard-module__SuccessToast--iAdUt,.ProjectCard-module__CancelToast--qVANr{position:absolute;top:0;left:0;bottom:0;right:0;background-color:var(--theme-color-bg-1);display:flex;align-items:center;justify-content:center;opacity:0;transition:opacity var(--speed-quick) var(--easing-base)}.ProjectCard-module__Root--Jyjjg:hover .ProjectCard-module__HoverOverlay--gLzIf,.ProjectCard-module__Root--Jyjjg.ProjectCard-module__is-downloading--stNmy .ProjectCard-module__HoverOverlay--gLzIf{opacity:1}.ProjectCard-module__CtaContainer--efvkj{display:flex;align-items:stretch;flex-direction:column;padding:24px;width:100%;transition:transform var(--speed-quick) var(--easing-base),opacity var(--speed-quick) var(--easing-base) var(--speed-quick);transform:translateY(10px);opacity:1}.ProjectCard-module__Root--Jyjjg:hover .ProjectCard-module__CtaContainer--efvkj{transform:translateY(0)}.ProjectCard-module__Root--Jyjjg.ProjectCard-module__is-downloading--stNmy .ProjectCard-module__CtaContainer--efvkj{transition:opacity var(--speed-quick) var(--easing-base);opacity:0;transform:translateY(0);pointer-events:none}.ProjectCard-module__ImportIndicator--B955O{pointer-events:none;flex-direction:column}.ProjectCard-module__Root--Jyjjg.ProjectCard-module__is-downloading--stNmy .ProjectCard-module__ImportIndicator--B955O{opacity:1}.ProjectCard-module__SuccessToast--iAdUt{padding:12px;pointer-events:none;flex-direction:column}.ProjectCard-module__Root--Jyjjg.ProjectCard-module__is-finished--JayfJ .ProjectCard-module__SuccessToast--iAdUt{opacity:1}.ProjectCard-module__CancelToast--qVANr{pointer-events:none}.ProjectCard-module__Root--Jyjjg.ProjectCard-module__is-cancelled--nnL3x .ProjectCard-module__CancelToast--qVANr{opacity:1}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/NodePicker/components/ProjectCard/ProjectCard.module.scss","webpack://./src/editor/src/styles/mixins/layout.scss"],"names":[],"mappings":"AAGA,iCACE,YAAA,CACA,qBAAA,CACA,WAAA,CAGF,2CACE,WAAA,CACA,aAAA,CACA,iBAAA,CACA,4CAAA,CCoHA,kDAEI,UAAA,CAEF,aAAA,CACA,QAAA,CACA,6BAAA,CDrHJ,kCACE,0BAAA,CACA,iBAAA,CACA,2BAAA,CACA,qBAAA,CACA,KAAA,CACA,QAAA,CACA,MAAA,CACA,OAAA,CAGF,oCACE,iBAAA,CACA,wCAAA,CACA,WAAA,CACA,YAAA,CACA,qBAAA,CACA,6BAAA,CACA,iBAAA,CAEF,sKAIE,iBAAA,CACA,KAAA,CACA,MAAA,CACA,QAAA,CACA,OAAA,CACA,wCAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,SAAA,CACA,wDAAA,CAIA,oMAEE,SAAA,CAIJ,yCACE,YAAA,CACA,mBAAA,CACA,qBAAA,CACA,YAAA,CACA,UAAA,CACA,2HAAA,CAEA,0BAAA,CACA,SAAA,CAEA,gFACE,uBAAA,CAGF,oHACE,wDAAA,CACA,SAAA,CACA,uBAAA,CACA,mBAAA,CAIJ,4CACE,mBAAA,CACA,qBAAA,CAEA,uHACE,SAAA,CAIJ,yCACE,YAAA,CACA,mBAAA,CACA,qBAAA,CAEA,iHACE,SAAA,CAIJ,wCACE,mBAAA,CAEA,iHACE,SAAA","sourcesContent":["@use '@scss-mixins/layout' as *;\n@use '@scss-variables/animation';\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n}\n\n.ImageContainer {\n  flex-grow: 0;\n  flex-shrink: 0;\n  position: relative;\n  background-color: var(--theme-color-fg-muted);\n\n  @include aspect-ratio(354, 200);\n}\n\n.Image {\n  background-position: center;\n  position: absolute;\n  background-repeat: no-repeat;\n  background-size: cover;\n  top: 0;\n  bottom: 0;\n  left: 0;\n  right: 0;\n}\n\n.Content {\n  position: relative;\n  background-color: var(--theme-color-bg-1);\n  flex-grow: 1;\n  display: flex;\n  flex-direction: column;\n  justify-content: space-between;\n  padding: 16px 24px;\n}\n.HoverOverlay,\n.ImportIndicator,\n.SuccessToast,\n.CancelToast {\n  position: absolute;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n  background-color: var(--theme-color-bg-1);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  opacity: 0;\n  transition: opacity animation.$speed-quick animation.$easing-base;\n}\n\n.HoverOverlay {\n  .Root:hover &,\n  .Root.is-downloading & {\n    opacity: 1;\n  }\n}\n\n.CtaContainer {\n  display: flex;\n  align-items: stretch;\n  flex-direction: column;\n  padding: 24px;\n  width: 100%;\n  transition: transform animation.$speed-quick animation.$easing-base,\n    opacity animation.$speed-quick animation.$easing-base animation.$speed-quick;\n  transform: translateY(10px);\n  opacity: 1;\n\n  .Root:hover & {\n    transform: translateY(0);\n  }\n\n  .Root.is-downloading & {\n    transition: opacity animation.$speed-quick animation.$easing-base;\n    opacity: 0;\n    transform: translateY(0);\n    pointer-events: none;\n  }\n}\n\n.ImportIndicator {\n  pointer-events: none;\n  flex-direction: column;\n\n  .Root.is-downloading & {\n    opacity: 1;\n  }\n}\n\n.SuccessToast {\n  padding: 12px;\n  pointer-events: none;\n  flex-direction: column;\n\n  .Root.is-finished & {\n    opacity: 1;\n  }\n}\n\n.CancelToast {\n  pointer-events: none;\n\n  .Root.is-cancelled & {\n    opacity: 1;\n  }\n}\n","@function _format-gutters($value, $direction) {\n  $vertical-gutter: false;\n  $horizontal-gutter: false;\n\n  @if (type-of($value) == list) {\n    @if (nth($value, 1)) {\n      $vertical-gutter: (nth($value, 1));\n    }\n    @if (nth($value, 2)) {\n      $horizontal-gutter: (nth($value, 2));\n    }\n  } @else {\n    $vertical-gutter: $value;\n    $horizontal-gutter: $value;\n  }\n\n  @if ($direction == vertical) {\n    @return $vertical-gutter;\n  } @else {\n    @return $horizontal-gutter;\n  }\n}\n\n@mixin flex-layout($columns: false, $gutters: 16px) {\n  $items: length($columns);\n\n  @if (type-of($columns) == number) {\n    @include flex-row($gutters);\n\n    > * {\n      @include flex-column(calc(1 / $columns), $gutters);\n    }\n  } @else if (type-of($columns) == list and $items > 1) {\n    $column-count: 0;\n\n    @each $column in $columns {\n      $column-count: $column-count + $column;\n    }\n\n    @include flex-row($gutters);\n\n    @for $item from 1 through $items {\n      $width: nth($columns, $item) / $column-count;\n\n      & > *:nth-child(#{$items}n + #{$item}) {\n        @include flex-column($width, $gutters);\n      }\n    }\n  }\n}\n\n/**\n * flex-row()\n */\n\n@mixin flex-row($gutters) {\n  $horizontal-gutter: _format-gutters($gutters, horizontal);\n  $vertical-gutter: _format-gutters($gutters, vertical);\n\n  display: flex;\n  flex-wrap: wrap;\n\n  @if ($horizontal-gutter and $horizontal-gutter != 0) {\n    margin-left: -($horizontal-gutter);\n  }\n\n  @if ($vertical-gutter and $vertical-gutter != 0) {\n    margin-top: -($vertical-gutter);\n  }\n}\n\n/**\n * flex-column()\n */\n\n@mixin flex-column($width, $gutters) {\n  $horizontal-gutter: _format-gutters($gutters, horizontal);\n  $vertical-gutter: _format-gutters($gutters, vertical);\n\n  @if (type-of($width) == number and unitless($width)) {\n    $width: percentage($width);\n  }\n\n  @if ($horizontal-gutter and $horizontal-gutter != 0) {\n    margin-left: $horizontal-gutter;\n    width: calc(#{$width} - #{$horizontal-gutter});\n  } @else {\n    width: $width;\n  }\n\n  @if ($vertical-gutter and $vertical-gutter != 0) {\n    margin-top: $vertical-gutter;\n  }\n}\n\n@function _get-pseudo($pseudo) {\n  @if ($pseudo == false) {\n    $pseudo: '&::after';\n  } @else if (_contains(('after', ':after', '::after', '&:after', '&::after'), $pseudo)) {\n    $pseudo: '&::after';\n  } @else if (_contains(('before', ':before', '::before', '&:before', '&::before'), $pseudo)) {\n    $pseudo: '&::before';\n  }\n\n  @return $pseudo;\n}\n\n@function _is-pseudo($pseudo) {\n  @return ($pseudo == '&::after' or $pseudo == '&::before');\n}\n\n@function _contains($list, $item) {\n  @return index($list, $item) != null;\n}\n\n/**\n * aspect-ratio()\n *\n * Give a heightless element a height based on its width.\n * Always follows the set width:height ratio.\n *\n * @param {number} $width - Without CSS unit\n * @param {number} $height - Without CSS unit\n * @param {string} $pseudo - Optional selector to use insted of default pseudo-element\n */\n\n@mixin aspect-ratio($width, $height, $pseudo: false) {\n  $pseudo: _get-pseudo($pseudo);\n\n  #{$pseudo} {\n    @if (_is-pseudo($pseudo)) {\n      content: '';\n    }\n    display: block;\n    height: 0;\n    padding-bottom: calc((100% / $width) * $height);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ProjectCard-module__Root--Jyjjg`,
	"ImageContainer": `ProjectCard-module__ImageContainer--WViau`,
	"Image": `ProjectCard-module__Image--CL6tx`,
	"Content": `ProjectCard-module__Content--bweSI`,
	"HoverOverlay": `ProjectCard-module__HoverOverlay--gLzIf`,
	"ImportIndicator": `ProjectCard-module__ImportIndicator--B955O`,
	"SuccessToast": `ProjectCard-module__SuccessToast--iAdUt`,
	"CancelToast": `ProjectCard-module__CancelToast--qVANr`,
	"is-downloading": `ProjectCard-module__is-downloading--stNmy`,
	"CtaContainer": `ProjectCard-module__CtaContainer--efvkj`,
	"is-finished": `ProjectCard-module__is-finished--JayfJ`,
	"is-cancelled": `ProjectCard-module__is-cancelled--nnL3x`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 40525:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5, _path6, _path7, _path8, _path9;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgBorderLeft = function SvgBorderLeft(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.2832 4.99158C26.2832 5.40579 25.9474 5.74158 25.5332 5.74158C25.119 5.74158 24.7832 5.40579 24.7832 4.99158C24.7832 4.57736 25.119 4.24158 25.5332 4.24158C25.9474 4.24158 26.2832 4.57736 26.2832 4.99158Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.2832 18.7333C26.2832 19.1475 25.9474 19.4833 25.5332 19.4833C25.119 19.4833 24.7832 19.1475 24.7832 18.7333C24.7832 18.3191 25.119 17.9833 25.5332 17.9833C25.9474 17.9833 26.2832 18.3191 26.2832 18.7333Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.2832 11.8622C26.2832 12.2764 25.9474 12.6122 25.5332 12.6122C25.119 12.6122 24.7832 12.2764 24.7832 11.8622C24.7832 11.448 25.119 11.1122 25.5332 11.1122C25.9474 11.1122 26.2832 11.448 26.2832 11.8622Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.2832 25.6041C26.2832 26.0183 25.9474 26.3541 25.5332 26.3541C25.119 26.3541 24.7832 26.0183 24.7832 25.6041C24.7832 25.1899 25.119 24.8541 25.5332 24.8541C25.9474 24.8541 26.2832 25.1899 26.2832 25.6041Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.541 25.6046C12.541 26.0188 12.2052 26.3546 11.791 26.3546C11.3768 26.3546 11.041 26.0188 11.041 25.6046C11.041 25.1904 11.3768 24.8546 11.791 24.8546C12.2052 24.8546 12.541 25.1904 12.541 25.6046Z",
    fill: "#F5F5F5"
  })), _path6 || (_path6 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.541 4.99182C12.541 5.40603 12.2052 5.74182 11.791 5.74182C11.3768 5.74182 11.041 5.40603 11.041 4.99182C11.041 4.57761 11.3768 4.24182 11.791 4.24182C12.2052 4.24182 12.541 4.57761 12.541 4.99182Z",
    fill: "#F5F5F5"
  })), _path7 || (_path7 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M19.4121 25.6044C19.4121 26.0186 19.0763 26.3544 18.6621 26.3544C18.2479 26.3544 17.9121 26.0186 17.9121 25.6044C17.9121 25.1902 18.2479 24.8544 18.6621 24.8544C19.0763 24.8544 19.4121 25.1902 19.4121 25.6044Z",
    fill: "#F5F5F5"
  })), _path8 || (_path8 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M19.4121 4.99158C19.4121 5.40579 19.0763 5.74158 18.6621 5.74158C18.2479 5.74158 17.9121 5.40579 17.9121 4.99158C17.9121 4.57736 18.2479 4.24158 18.6621 4.24158C19.0763 4.24158 19.4121 4.57736 19.4121 4.99158Z",
    fill: "#F5F5F5"
  })), _path9 || (_path9 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.74023 26.3547C4.32602 26.3547 3.99023 26.0189 3.99023 25.6047L3.99024 4.99219C3.99024 4.57797 4.32602 4.24219 4.74024 4.24219C5.15445 4.24219 5.49024 4.57797 5.49024 4.99219L5.49023 25.6047C5.49023 26.0189 5.15445 26.3547 4.74023 26.3547Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgBorderLeft);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "d6ad1ac9517086ad89eb29b97c9220ae.svg");

/***/ }),

/***/ 40619:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   G: () => (/* binding */ createLogParser),
/* harmony export */   n: () => (/* binding */ createForEachRefParser)
/* harmony export */ });
/**
 * Create a new parser suitable for parsing --format output from commands such
 * as `git log`, `git stash`, and other commands that are not derived from
 * `ref-filter`.
 *
 * Returns an object with the arguments that need to be appended to the git
 * call and the parse function itself
 *
 * @param fields An object keyed on the friendly name of the value being
 *               parsed with the value being the format string of said value.
 *
 *               Example:
 *
 *               `const { args, parse } = createLogParser({ sha: '%H' })`
 *
 */
function createLogParser(fields) {
    const keys = Object.keys(fields);
    const format = Object.values(fields).join("%x00");
    const formatArgs = ["-z", `--format=${format}`];
    const parse = (value) => {
        const records = value.split("\0");
        const entries = [];
        for (let i = 0; i < records.length - keys.length; i += keys.length) {
            const entry = {};
            keys.forEach((key, ix) => (entry[key] = records[i + ix]));
            entries.push(entry);
        }
        return entries;
    };
    return { formatArgs, parse };
}
/**
 * Create a new parser suitable for parsing --format output from commands such
 * as `git for-each-ref`, `git branch`, and other commands that are not derived
 * from `git log`.
 *
 * Returns an object with the arguments that need to be appended to the git
 * call and the parse function itself
 *
 * @param fields An object keyed on the friendly name of the value being
 *               parsed with the value being the format string of said value.
 *
 *               Example:
 *
 *               `const { args, parse } = createForEachRefParser({ sha: '%(objectname)' })`
 *
 */
function createForEachRefParser(fields) {
    const keys = Object.keys(fields);
    const format = Object.values(fields).join("%00");
    const formatArgs = [`--format=%00${format}%00`];
    const parse = (value) => {
        const records = value.split("\0");
        const entries = new Array();
        let entry;
        let consumed = 0;
        // start at 1 to avoid 0 modulo X problem. The first record is guaranteed
        // to be empty anyway (due to %00 at the start of --format)
        for (let i = 1; i < records.length - 1; i++) {
            if (i % (keys.length + 1) === 0) {
                if (records[i] !== "\n") {
                    throw new Error("Expected newline");
                }
                continue;
            }
            entry = entry !== null && entry !== void 0 ? entry : {};
            const key = keys[consumed % keys.length];
            entry[key] = records[i];
            consumed++;
            if (consumed % keys.length === 0) {
                entries.push(entry);
                entry = undefined;
            }
        }
        return entries;
    };
    return { formatArgs, parse };
}


/***/ }),

/***/ 40935:
/***/ ((module) => {

"use strict";


/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Tobias Koppers @sokra
*/
module.exports = function (cssWithMappingToString) {
  var list = [];

  // return the list of modules as css string
  list.toString = function toString() {
    return this.map(function (item) {
      var content = "";
      var needLayer = typeof item[5] !== "undefined";
      if (item[4]) {
        content += "@supports (".concat(item[4], ") {");
      }
      if (item[2]) {
        content += "@media ".concat(item[2], " {");
      }
      if (needLayer) {
        content += "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {");
      }
      content += cssWithMappingToString(item);
      if (needLayer) {
        content += "}";
      }
      if (item[2]) {
        content += "}";
      }
      if (item[4]) {
        content += "}";
      }
      return content;
    }).join("");
  };

  // import a list of modules into the list
  list.i = function i(modules, media, dedupe, supports, layer) {
    if (typeof modules === "string") {
      modules = [[null, modules, undefined]];
    }
    var alreadyImportedModules = {};
    if (dedupe) {
      for (var k = 0; k < this.length; k++) {
        var id = this[k][0];
        if (id != null) {
          alreadyImportedModules[id] = true;
        }
      }
    }
    for (var _k = 0; _k < modules.length; _k++) {
      var item = [].concat(modules[_k]);
      if (dedupe && alreadyImportedModules[item[0]]) {
        continue;
      }
      if (typeof layer !== "undefined") {
        if (typeof item[5] === "undefined") {
          item[5] = layer;
        } else {
          item[1] = "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {").concat(item[1], "}");
          item[5] = layer;
        }
      }
      if (media) {
        if (!item[2]) {
          item[2] = media;
        } else {
          item[1] = "@media ".concat(item[2], " {").concat(item[1], "}");
          item[2] = media;
        }
      }
      if (supports) {
        if (!item[4]) {
          item[4] = "".concat(supports);
        } else {
          item[1] = "@supports (".concat(item[4], ") {").concat(item[1], "}");
          item[4] = supports;
        }
      }
      list.push(item);
    }
  };
  return list;
};

/***/ }),

/***/ 41160:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (/* binding */ getDocsEndpoint)
/* harmony export */ });
const remote = __webpack_require__(52391);
function getDocsEndpoint() {
    const localDocs = remote.getGlobal('useLocalDocs');
    return localDocs ? 'http://localhost:3000' : 'https://the-low-code-foundation.github.io/opennoodl-docs';
}


/***/ }),

/***/ 41176:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   JR: () => (/* binding */ getCommits),
/* harmony export */   bM: () => (/* binding */ parseChangedFiles),
/* harmony export */   cL: () => (/* binding */ getChangedFiles),
/* harmony export */   kO: () => (/* binding */ getCommit)
/* harmony export */ });
/* unused harmony export doMergeCommitsExistAfterCommit */
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85869);
/* harmony import */ var _models_status__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(45226);
/* harmony import */ var _models_snapshot__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(60629);
/* harmony import */ var _models_commit_identity__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(80760);
/* harmony import */ var _helpers_regex__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(51025);
/* harmony import */ var _git_delimiter_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(40619);
/* harmony import */ var _rev_list__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(65079);







/**
 * Map the raw status text from Git to an app-friendly value
 * shamelessly borrowed from GitHub Desktop (Windows)
 */
function mapStatus(rawStatus, oldPath) {
    const status = rawStatus.trim();
    if (status === "M") {
        return { kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.Modified };
    } // modified
    if (status === "A") {
        return { kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.New };
    } // added
    if (status === "?") {
        return { kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.Untracked };
    } // untracked
    if (status === "D") {
        return { kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.Deleted };
    } // deleted
    if (status === "R" && oldPath != null) {
        return { kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.Renamed, oldPath };
    } // renamed
    if (status === "C" && oldPath != null) {
        return { kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.Copied, oldPath };
    } // copied
    // git log -M --name-status will return a RXXX - where XXX is a percentage
    if (status.match(/R[0-9]+/) && oldPath != null) {
        return { kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.Renamed, oldPath };
    }
    // git log -C --name-status will return a CXXX - where XXX is a percentage
    if (status.match(/C[0-9]+/) && oldPath != null) {
        return { kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.Copied, oldPath };
    }
    return { kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.Modified };
}
/**
 * Get the repository's commits using `revisionRange` and limited to `limit`
 */
async function getCommits(repositoryDir, revisionRange, limit, skip, additionalArgs = []) {
    const { formatArgs, parse } = (0,_git_delimiter_parser__WEBPACK_IMPORTED_MODULE_5__/* .createLogParser */ .G)({
        sha: "%H", // SHA
        shortSha: "%h", // short SHA
        summary: "%s", // summary
        body: "%b", // body
        // author identity string, matching format of GIT_AUTHOR_IDENT.
        //   author name <author email> <author date>
        // author date format dependent on --date arg, should be raw
        author: "%an <%ae> %ad",
        committer: "%cn <%ce> %cd",
        parents: "%P", // parent SHAs,
        // trailers: '%(trailers:unfold,only)',
        refs: "%D",
    });
    const args = ["log"];
    if (revisionRange !== undefined) {
        args.push(revisionRange);
    }
    args.push("--date=raw");
    if (limit !== undefined) {
        args.push(`--max-count=${limit}`);
    }
    if (skip !== undefined) {
        args.push(`--skip=${skip}`);
    }
    args.push(...formatArgs, "--no-show-signature", "--no-color", ...additionalArgs, "--");
    const { exitCode, output } = await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)(args, repositoryDir, "getCommits", {
        successExitCodes: new Set([0, 128]),
    });
    // if the repository has an unborn HEAD, return an empty history of commits
    if (exitCode === 128) {
        return new Array();
    }
    const parsed = parse(output.toString());
    return parsed.map((commit) => {
        const tags = (0,_helpers_regex__WEBPACK_IMPORTED_MODULE_4__/* .getCaptures */ .En)(commit.refs, /tag: ([^\s,]+)/g)
            .filter((i) => i[0] !== undefined)
            .map((i) => i[0]);
        return new _models_snapshot__WEBPACK_IMPORTED_MODULE_2__/* .Commit */ .gn(repositoryDir, commit.sha, commit.shortSha, commit.summary, commit.body, _models_commit_identity__WEBPACK_IMPORTED_MODULE_3__/* .CommitIdentity */ .S.parseIdentity(commit.author), _models_commit_identity__WEBPACK_IMPORTED_MODULE_3__/* .CommitIdentity */ .S.parseIdentity(commit.committer), commit.parents.length > 0 ? commit.parents.split(" ") : [], tags);
    });
}
/** Get the files that were changed in the given commit. */
async function getChangedFiles(repositoryDir, sha) {
    // opt-in for rename detection (-M) and copies detection (-C)
    // this is equivalent to the user configuring 'diff.renames' to 'copies'
    // NOTE: order here matters - doing -M before -C means copies aren't detected
    const baseArgs = [
        "log",
        sha,
        "-C",
        "-M",
        "-m",
        "-1",
        "--no-show-signature",
        "--first-parent",
        "--format=format:",
        "-z",
    ];
    // Run `git log` to obtain the file names and their state
    const resultNameStatus = await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)([...baseArgs, "--name-status", "--"], repositoryDir, "getChangedFilesNameStatus");
    const files = parseChangedFiles(resultNameStatus.output.toString(), sha);
    // Run `git log` again, but this time to get the number of lines added/deleted
    // per file
    const resultNumStat = await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)([...baseArgs, "--numstat", "--"], repositoryDir, "getChangedFilesNumStats");
    const linesChanged = parseChangedFilesNumStat(resultNumStat.output.toString());
    return {
        files,
        ...linesChanged,
    };
}
function parseChangedFilesNumStat(stdout) {
    const lines = stdout.split("\0");
    let totalLinesAdded = 0;
    let totalLinesDeleted = 0;
    for (const line of lines) {
        const parts = line.split("\t");
        if (parts.length !== 3) {
            continue;
        }
        const [added, deleted] = parts;
        if (added === "-" || deleted === "-") {
            continue;
        }
        totalLinesAdded += parseInt(added, 10);
        totalLinesDeleted += parseInt(deleted, 10);
    }
    return { linesAdded: totalLinesAdded, linesDeleted: totalLinesDeleted };
}
/**
 * Parses git `log` or `diff` output into a list of changed files
 * (see `getChangedFiles` for an example of use)
 *
 * @param stdout raw output from a git `-z` and `--name-status` flags
 * @param committish commitish command was run against
 */
function parseChangedFiles(stdout, committish) {
    const lines = stdout.split("\0");
    // Remove the trailing empty line
    lines.splice(-1, 1);
    const files = [];
    for (let i = 0; i < lines.length; i++) {
        const statusText = lines[i];
        let oldPath = undefined;
        if (statusText.length > 0 &&
            (statusText[0] === "R" || statusText[0] === "C")) {
            oldPath = lines[++i];
        }
        const status = mapStatus(statusText, oldPath);
        const path = lines[++i];
        files.push(new _models_status__WEBPACK_IMPORTED_MODULE_1__/* .CommittedFileChange */ .Ls(path, status, committish));
    }
    return files;
}
/** Get the commit for the given ref. */
async function getCommit(repositoryDir, ref) {
    const commits = await getCommits(repositoryDir, ref, 1);
    if (commits.length < 1) {
        return null;
    }
    return commits[0];
}
/**
 * Determine if merge commits exist in history after given commit
 * If no commitRef is null, goes back to HEAD of branch.
 */
async function doMergeCommitsExistAfterCommit(repositoryDir, commitRef) {
    const commitRevRange = commitRef === null ? undefined : revRange(commitRef, "HEAD");
    const mergeCommits = await getCommits(repositoryDir, commitRevRange, undefined, undefined, ["--merges"]);
    return mergeCommits.length > 0;
}


/***/ }),

/***/ 41350:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Messages = void 0;
const tslib_1 = __webpack_require__(84499);
const resource_1 = __webpack_require__(39929);
const MessageStream_1 = __webpack_require__(56010);
const BatchesAPI = tslib_1.__importStar(__webpack_require__(18216));
const batches_1 = __webpack_require__(18216);
const constants_1 = __webpack_require__(66262);
class Messages extends resource_1.APIResource {
    constructor() {
        super(...arguments);
        this.batches = new BatchesAPI.Batches(this._client);
    }
    create(body, options) {
        if (body.model in DEPRECATED_MODELS) {
            console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
        }
        let timeout = this._client._options.timeout;
        if (!body.stream && timeout == null) {
            const maxNonstreamingTokens = constants_1.MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;
            timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
        }
        return this._client.post('/v1/messages', {
            body,
            timeout: timeout ?? 600000,
            ...options,
            stream: body.stream ?? false,
        });
    }
    /**
     * Create a Message stream
     */
    stream(body, options) {
        return MessageStream_1.MessageStream.createMessage(this, body, options);
    }
    /**
     * Count the number of tokens in a Message.
     *
     * The Token Count API can be used to count the number of tokens in a Message,
     * including tools, images, and documents, without creating it.
     *
     * Learn more about token counting in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
     *
     * @example
     * ```ts
     * const messageTokensCount =
     *   await client.messages.countTokens({
     *     messages: [{ content: 'string', role: 'user' }],
     *     model: 'claude-opus-4-5-20251101',
     *   });
     * ```
     */
    countTokens(body, options) {
        return this._client.post('/v1/messages/count_tokens', { body, ...options });
    }
}
exports.Messages = Messages;
const DEPRECATED_MODELS = {
    'claude-1.3': 'November 6th, 2024',
    'claude-1.3-100k': 'November 6th, 2024',
    'claude-instant-1.1': 'November 6th, 2024',
    'claude-instant-1.1-100k': 'November 6th, 2024',
    'claude-instant-1.2': 'November 6th, 2024',
    'claude-3-sonnet-20240229': 'July 21st, 2025',
    'claude-3-opus-20240229': 'January 5th, 2026',
    'claude-2.1': 'July 21st, 2025',
    'claude-2.0': 'July 21st, 2025',
    'claude-3-7-sonnet-latest': 'February 19th, 2026',
    'claude-3-7-sonnet-20250219': 'February 19th, 2026',
};
Messages.Batches = batches_1.Batches;
//# sourceMappingURL=messages.js.map

/***/ }),

/***/ 41453:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ConditionalContainer-module__Loader--Es_Vg{color:var(--theme-color-fg-muted);box-sizing:border-box}.ConditionalContainer-module__Loader--Es_Vg.ConditionalContainer-module__is-loader-type-block--hUhG4{width:100%;padding:16px}.ConditionalContainer-module__Loader--Es_Vg.ConditionalContainer-module__is-loader-type-inline--Ewh56{display:inline-block}.ConditionalContainer-module__Loader--Es_Vg .ConditionalContainer-module__LoaderInner--BXbtn{height:150px;background-color:hsla(0,0%,100%,.05);display:flex;justify-content:center;align-items:center;position:relative}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/ConditionalContainer/ConditionalContainer.module.scss"],"names":[],"mappings":"AAAA,4CACE,iCAAA,CACA,qBAAA,CAEA,qGACE,UAAA,CACA,YAAA,CAGF,sGACE,oBAAA,CAGF,6FACE,YAAA,CACA,oCAAA,CACA,YAAA,CACA,sBAAA,CACA,kBAAA,CACA,iBAAA","sourcesContent":[".Loader {\n  color: var(--theme-color-fg-muted);\n  box-sizing: border-box;\n\n  &.is-loader-type-block {\n    width: 100%;\n    padding: 16px;\n  }\n\n  &.is-loader-type-inline {\n    display: inline-block;\n  }\n\n  .LoaderInner {\n    height: 150px;\n    background-color: rgba(255, 255, 255, 0.05);\n    display: flex;\n    justify-content: center;\n    align-items: center;\n    position: relative;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Loader": `ConditionalContainer-module__Loader--Es_Vg`,
	"is-loader-type-block": `ConditionalContainer-module__is-loader-type-block--hUhG4`,
	"is-loader-type-inline": `ConditionalContainer-module__is-loader-type-inline--Ewh56`,
	"LoaderInner": `ConditionalContainer-module__LoaderInner--BXbtn`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 41554:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_propertyeditor_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(77504);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_propertyeditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_propertyeditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_propertyeditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_propertyeditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 41669:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   q: () => (/* binding */ SidebarModelEvent),
/* harmony export */   s: () => (/* binding */ SidebarModel)
/* harmony export */ });
/* harmony import */ var _noodl_contexts_NodeGraphContext_NodeGraphContext__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(18498);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(39804);
/* harmony import */ var _noodl_utils_model__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(81267);




/**
 * Returns the sidepanel we want to show for this node.
 *
 * @param node Node instance?
 * @returns The side panel name.
 */
function getNodePanelName(nodeModel) {
    if (!nodeModel.type.panels)
        return { id: 'PropertyEditor' };
    if (nodeModel.type.panels === 'none')
        return { id: 'none' };
    const registeredPanels = SidebarModel.instance.getItems();
    const valids = nodeModel.type.panels.filter((x) => registeredPanels.find((b) => b.id == x.name));
    if (valids.length > 0) {
        return {
            id: valids[0].name,
            args: valids[0]
        };
    }
    return { id: 'PropertyEditor' };
}
function createPanel(type, args) {
    const items = SidebarModel.instance.getItems();
    const item = items.find((x) => x.id === type);
    if (!item) {
        throw new Error(`Panel not found. (${type})`);
    }
    // eslint-disable-next-line react/display-name
    return () => react__WEBPACK_IMPORTED_MODULE_1___default().createElement(item.panel, { ...args, ...(item.panelProps || {}) });
}
const getExperimentalSettingsKey = (item) => `experimental.panel.${item.id}`;
var SidebarModelEvent;
(function (SidebarModelEvent) {
    /** Occurs when a new panel is added. */
    SidebarModelEvent["itemsChanged"] = "itemsChanged";
    /** Occurs when a panel is selected. */
    SidebarModelEvent["activeChanged"] = "activeChanged";
    SidebarModelEvent["nodeSelected"] = "nodeSelected";
    SidebarModelEvent["receivedCommand"] = "receivedCommand";
    SidebarModelEvent["HotReload"] = "HotReload";
})(SidebarModelEvent || (SidebarModelEvent = {}));
/**
 * The Sidebar Model.
 *
 * ## Nodes
 * Nodes can have custom panels when selected.
 *
 * Before telling a node to use a specific panel we have to register it with
 * SidebarModel. Which is done by calling register.
 *
 * To add a custom panel to a node, you have to add it to the **node definition**.
 * ```js
 *  {
 *    ...
 *    panels: [
 *      {
 *        name: "PortEditor",
 *      }
 *    ],
 *    ...
 *  }
 * ```
 *
 */
class SidebarModel extends _noodl_utils_model__WEBPACK_IMPORTED_MODULE_3__/* .Model */ .K {
    get ActiveId() {
        return this.activeId;
    }
    constructor() {
        super();
        this.items = [];
        this.experimentalItems = [];
        this.panels = {};
        this.groupRef = {};
        _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_2__/* .EditorSettings */ .H.instance.on('updated', ({ key }) => {
            // Check if the key is an experimental panel
            const experimentalKeys = this.experimentalItems.map(getExperimentalSettingsKey);
            if (!experimentalKeys.includes(key)) {
                return;
            }
            const enabled = _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_2__/* .EditorSettings */ .H.instance.get(key);
            const id = key.split('.').at(-1);
            if (enabled) {
                const experimentalItem = this.experimentalItems.find((x) => x.id === id);
                // Check if item exists
                if (!experimentalItem) {
                    return;
                }
                // Already enabled
                if (this.items.some((x) => x.id === id)) {
                    return;
                }
                // Enable the item
                this.items.push(experimentalItem);
                this.notifyListeners(SidebarModelEvent.itemsChanged);
            }
            else {
                const index = this.items.findIndex((x) => x.id === id);
                if (index >= 0) {
                    this.items.splice(index, 1);
                    this.notifyListeners(SidebarModelEvent.itemsChanged);
                }
            }
        }, this.groupRef);
    }
    reset() {
        this.activeId = undefined;
        this.previousActiveId = undefined;
        this.items = [];
        this.experimentalItems = [];
        this.panels = {};
    }
    // TODO: Rename to getActive()
    getCurrent() {
        return this.items.find((x) => x.id === this.activeId) || this.items[0];
    }
    getPanel(panelId) {
        return this.items.find((x) => x.id === panelId) || null;
    }
    getPanelComponent(panelId) {
        if (panelId) {
            return this.panels[panelId];
        }
        return null;
    }
    getActive() {
        if (this.activeId) {
            return this.panels[this.activeId];
        }
        return null;
    }
    getItems() {
        return this.items.sort((a, b) => a.order - b.order);
    }
    getVisibleItems() {
        return this.getItems().filter((x) => !x.transient);
    }
    getExperimentalItems() {
        return this.experimentalItems
            .filter((x) => !x.transient)
            .map((x) => ({
            id: x.id,
            settingsKey: getExperimentalSettingsKey(x),
            name: x.name,
            description: x.description,
            enabled: !!_noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_2__/* .EditorSettings */ .H.instance.get(getExperimentalSettingsKey(x))
        }));
    }
    register(item) {
        // Set default placement
        if (!item.placement) {
            item.placement = 'top';
        }
        if (item.experimental) {
            this.experimentalItems.push(item);
            if (_noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_2__/* .EditorSettings */ .H.instance.get(getExperimentalSettingsKey(item))) {
                this.items.push(item);
                this.notifyListeners(SidebarModelEvent.itemsChanged);
            }
        }
        else {
            this.items.push(item);
            this.notifyListeners(SidebarModelEvent.itemsChanged);
        }
    }
    /**
     *
     * @param id The panel id.
     * @returns
     */
    switch(id) {
        if (this.activeId === id) {
            return true;
        }
        // Debug info
        // let logText = `switch side panel to: '${id}'`;
        // if (this.activeId) logText += ` (from: ${this.activeId})`;
        // console.log(logText);
        try {
            if (this.panels[id]) {
                const lastActiveTab = this.items.find((x) => x.id === this.activeId);
                if (lastActiveTab) {
                    lastActiveTab.onClose && lastActiveTab.onClose();
                }
                this.activeId = id;
                this.notifyListeners(SidebarModelEvent.activeChanged, this.activeId, this.previousActiveId);
                const newActiveTab = this.items.find((x) => x.id === this.activeId);
                if (newActiveTab) {
                    newActiveTab.onOpen && newActiveTab.onOpen();
                }
                return true;
            }
            // Create the panel
            this.setActivePanel(id, false, createPanel(id, {}));
            return true;
        }
        catch (error) {
            // This is most likely caused by missing panel or some error creating
            // the panel. Lets try to select the first visible item, so the user
            // will have some panel.
            const visibleItems = this.getVisibleItems().filter((item) => item.panel);
            if (visibleItems.length > 0 && visibleItems[0].id === id) {
                this.switch(visibleItems[0].id);
                return;
            }
            // In case it fails we still continue since this can be
            // user created code too.
            console.error(error);
            return false;
        }
    }
    switchToNode(nodeModel) {
        var _a;
        const { id, args } = getNodePanelName(nodeModel);
        //remember what panel was active before we selected a node
        //but only if it was a visible icon in the sidebar (e.g. not another PropertyEditor or similar)
        if (!((_a = this.getCurrent()) === null || _a === void 0 ? void 0 : _a.transient)) {
            this.previousActiveId = this.activeId;
        }
        this.setActivePanel(id, true, createPanel(id, {
            model: nodeModel,
            ...args
        }));
        this.notifyListeners(SidebarModelEvent.nodeSelected, nodeModel.id);
    }
    /**
     * Used by "doubleClick"
     *
     * @param command
     */
    invokeActive(command, args) {
        this.notifyListeners(SidebarModelEvent.receivedCommand, this.activeId, command, args);
    }
    hidePanels() {
        if (this.previousActiveId) {
            this.switch(this.previousActiveId);
            this.previousActiveId = undefined;
        }
        else {
            const isFrontend = _noodl_contexts_NodeGraphContext_NodeGraphContext__WEBPACK_IMPORTED_MODULE_0__.NodeGraphContextTmp.active === 'frontend';
            const newPanel = isFrontend ? 'components' : 'cloud-functions';
            this.switch(newPanel);
        }
    }
    setActivePanel(id, force, component) {
        const lastActiveTab = this.items.find((x) => x.id === this.activeId);
        if (lastActiveTab) {
            lastActiveTab.onClose && lastActiveTab.onClose();
        }
        this.activeId = id;
        if (force || !this.panels[id]) {
            if (this.panels[id]) {
                delete this.panels[id];
            }
            this.panels[id] = component;
        }
        this.notifyListeners(SidebarModelEvent.activeChanged, this.activeId, this.previousActiveId);
        const newActiveTab = this.items.find((x) => x.id === this.activeId);
        if (newActiveTab) {
            newActiveTab.onOpen && newActiveTab.onOpen();
        }
    }
}
SidebarModel.instance = new SidebarModel();


/***/ }),

/***/ 41954:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  rp: () => (/* reexport */ buildChainFromEvents),
  G_: () => (/* reexport */ calculateStatistics),
  pI: () => (/* reexport */ calculateTiming),
  qF: () => (/* reexport */ triggerChainRecorder)
});

// UNUSED EXPORTS: TriggerChainRecorder, buildTree, groupByComponent

// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.ts + 4 modules
var projectmodel = __webpack_require__(6203);
;// ./src/editor/src/utils/triggerChain/TriggerChainRecorder.ts
/**
 * TriggerChainRecorder
 *
 * Singleton class that records runtime execution events for the
 * Trigger Chain Debugger. Captures node activations, signals,
 * and data flow as they happen in the preview.
 *
 * @module triggerChain
 */

/**
 * Singleton recorder for capturing runtime execution events
 */
class TriggerChainRecorder {
    /**
     * Private constructor - use getInstance() instead
     */
    constructor() {
        this.DUPLICATE_THRESHOLD_MS = 5; // Consider events within 5ms as duplicates
        this.state = {
            isRecording: false,
            events: [],
            maxEvents: 1000
        };
        this.recentEventKeys = new Map();
    }
    /**
     * Get the singleton instance
     */
    static getInstance() {
        if (!TriggerChainRecorder._instance) {
            TriggerChainRecorder._instance = new TriggerChainRecorder();
        }
        return TriggerChainRecorder._instance;
    }
    /**
     * Start recording events
     *
     * @param options - Recording configuration options
     */
    startRecording(options) {
        if (this.state.isRecording) {
            console.warn('TriggerChainRecorder: Already recording');
            return;
        }
        // Apply options
        if (options === null || options === void 0 ? void 0 : options.maxEvents) {
            this.state.maxEvents = options.maxEvents;
        }
        // Reset state and start
        this.state.events = [];
        this.recentEventKeys.clear(); // Clear deduplication map
        this.state.startTime = performance.now();
        this.state.isRecording = true;
        console.log('TriggerChainRecorder: Recording started');
        // Auto-stop if configured
        if (options === null || options === void 0 ? void 0 : options.autoStopAfter) {
            setTimeout(() => {
                this.stopRecording();
            }, options.autoStopAfter);
        }
    }
    /**
     * Stop recording and return captured events
     *
     * @returns Array of captured events
     */
    stopRecording() {
        if (!this.state.isRecording) {
            console.warn('TriggerChainRecorder: Not recording');
            return [];
        }
        this.state.isRecording = false;
        const events = [...this.state.events];
        console.log(`TriggerChainRecorder: Recording stopped. Captured ${events.length} events`);
        return events;
    }
    /**
     * Reset recorder state (clear all events)
     */
    reset() {
        this.state.events = [];
        this.state.startTime = undefined;
        this.state.isRecording = false;
        console.log('TriggerChainRecorder: Reset');
    }
    /**
     * Check if currently recording
     */
    isRecording() {
        return this.state.isRecording;
    }
    /**
     * Get current event count
     */
    getEventCount() {
        return this.state.events.length;
    }
    /**
     * Get all recorded events (without stopping)
     */
    getEvents() {
        return [...this.state.events];
    }
    /**
     * Get current recorder state
     */
    getState() {
        return { ...this.state };
    }
    /**
     * Capture a new event (internal method called from ViewerConnection)
     *
     * @param event - Event data from runtime
     */
    captureEvent(event) {
        // Only capture if recording
        if (!this.state.isRecording) {
            return;
        }
        // Check max events limit
        if (this.state.events.length >= this.state.maxEvents) {
            console.warn(`TriggerChainRecorder: Max events (${this.state.maxEvents}) reached. Oldest event will be dropped.`);
            this.state.events.shift(); // Remove oldest
        }
        // Add event to array
        this.state.events.push(event);
    }
    /**
     * Generate a unique event ID
     */
    generateEventId() {
        return `evt_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    }
    /**
     * Helper: Create and capture an event from connection pulse data
     * This bridges the existing DebugInspector connection pulse to our recorder
     *
     * @param connectionId - Connection ID from DebugInspector
     * @param data - Optional data flowing through connection
     */
    captureConnectionPulse(connectionId, data) {
        var _a, _b, _c, _d;
        if (!this.state.isRecording) {
            return;
        }
        const currentTime = performance.now();
        // Extract UUIDs from connectionId using regex
        // OpenNoodl uses standard UUID format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
        const uuidRegex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
        const uuids = connectionId.match(uuidRegex) || [];
        // Try to find a valid node from extracted UUIDs
        let targetNodeId;
        let foundNode = null;
        let nodeType = 'Unknown';
        let nodeLabel = 'Unknown';
        let componentName = 'Unknown';
        const componentPath = [];
        try {
            if (projectmodel.ProjectModel.instance && uuids.length > 0) {
                // Try each UUID until we find a valid node
                for (const uuid of uuids) {
                    const node = projectmodel.ProjectModel.instance.findNodeWithId(uuid);
                    if (node) {
                        targetNodeId = uuid;
                        foundNode = node;
                        break;
                    }
                }
                if (foundNode && typeof foundNode === 'object') {
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    const nodeObj = foundNode;
                    // Extract node type
                    nodeType = ((_a = nodeObj.type) === null || _a === void 0 ? void 0 : _a.name) || nodeObj.type || 'Unknown';
                    // Extract node label (try different properties)
                    nodeLabel = ((_b = nodeObj.parameters) === null || _b === void 0 ? void 0 : _b.label) || nodeObj.label || ((_c = nodeObj.parameters) === null || _c === void 0 ? void 0 : _c.name) || nodeType;
                    // Extract component name
                    if ((_d = nodeObj.owner) === null || _d === void 0 ? void 0 : _d.owner) {
                        componentName = nodeObj.owner.owner.name || 'Unknown';
                        componentPath.push(componentName);
                    }
                }
            }
        }
        catch (error) {
            console.warn('TriggerChainRecorder: Error looking up node:', error);
        }
        // Use first UUID as fallback if no node found
        if (!targetNodeId && uuids.length > 0) {
            targetNodeId = uuids[0];
        }
        // Deduplication: Create a unique key for this event
        // Using connectionId directly as it contains both node IDs and port info
        const eventKey = connectionId;
        // Check if we recently captured the same event
        const lastEventTime = this.recentEventKeys.get(eventKey);
        if (lastEventTime !== undefined) {
            const timeSinceLastEvent = currentTime - lastEventTime;
            if (timeSinceLastEvent < this.DUPLICATE_THRESHOLD_MS) {
                // This is a duplicate event - skip it
                return;
            }
        }
        // Update the timestamp for this event key
        this.recentEventKeys.set(eventKey, currentTime);
        // Clean up old entries periodically (keep map from growing too large)
        if (this.recentEventKeys.size > 100) {
            const cutoffTime = currentTime - this.DUPLICATE_THRESHOLD_MS * 2;
            for (const [key, timestamp] of this.recentEventKeys.entries()) {
                if (timestamp < cutoffTime) {
                    this.recentEventKeys.delete(key);
                }
            }
        }
        const event = {
            id: this.generateEventId(),
            timestamp: currentTime,
            type: 'signal',
            nodeId: targetNodeId,
            nodeType,
            nodeLabel,
            componentName,
            componentPath,
            port: undefined, // Port name extraction not yet implemented
            data
        };
        this.captureEvent(event);
    }
}
// Export singleton instance
const triggerChainRecorder = TriggerChainRecorder.getInstance();

;// ./src/editor/src/utils/triggerChain/chainBuilder.ts
/**
 * Chain Builder
 *
 * Transforms raw TriggerEvents into structured TriggerChain objects
 * that can be visualized in the timeline UI.
 *
 * @module triggerChain
 */
/**
 * Build a complete chain from an array of events
 *
 * @param events - Raw events from the recorder
 * @param name - Optional name for the chain (auto-generated if not provided)
 * @returns Structured trigger chain
 *
 * @example
 * ```typescript
 * const events = recorder.stopRecording();
 * const chain = buildChainFromEvents(events);
 * console.log(`Chain duration: ${chain.duration}ms`);
 * ```
 */
function buildChainFromEvents(events, name) {
    if (events.length === 0) {
        throw new Error('Cannot build chain from empty events array');
    }
    // Sort by timestamp
    const sortedEvents = [...events].sort((a, b) => a.timestamp - b.timestamp);
    const startTime = sortedEvents[0].timestamp;
    const endTime = sortedEvents[sortedEvents.length - 1].timestamp;
    const duration = endTime - startTime;
    // Build component grouping
    const byComponent = groupByComponent(sortedEvents);
    // Build tree structure
    const tree = buildTree(sortedEvents);
    // Generate name if not provided
    const chainName = name || generateChainName(sortedEvents);
    return {
        id: `chain_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
        name: chainName,
        startTime,
        endTime,
        duration,
        eventCount: sortedEvents.length,
        events: sortedEvents,
        byComponent,
        tree
    };
}
/**
 * Group events by component name
 *
 * @param events - Events to group
 * @returns Map of component name to events
 */
function groupByComponent(events) {
    const grouped = new Map();
    for (const event of events) {
        const componentName = event.componentName;
        if (!grouped.has(componentName)) {
            grouped.set(componentName, []);
        }
        grouped.get(componentName).push(event);
    }
    return grouped;
}
/**
 * Build hierarchical tree structure from flat event list
 *
 * @param events - Sorted events
 * @returns Root node of the tree
 */
function buildTree(events) {
    if (events.length === 0) {
        throw new Error('Cannot build tree from empty events array');
    }
    // For now, create a simple linear tree
    // TODO: In the future, use triggeredBy relationships to build proper tree
    const root = {
        event: events[0],
        children: [],
        depth: 0,
        deltaFromParent: 0
    };
    let currentNode = root;
    for (let i = 1; i < events.length; i++) {
        const node = {
            event: events[i],
            children: [],
            depth: i, // Simple linear depth for now
            deltaFromParent: events[i].timestamp - events[i - 1].timestamp
        };
        currentNode.children.push(node);
        currentNode = node;
    }
    return root;
}
/**
 * Calculate timing information for all events in a chain
 *
 * @param chain - The trigger chain
 * @returns Array of timing info for each event
 */
function calculateTiming(chain) {
    const timings = [];
    const startTime = chain.startTime;
    for (let i = 0; i < chain.events.length; i++) {
        const event = chain.events[i];
        const sinceStart = event.timestamp - startTime;
        const sincePrevious = i === 0 ? 0 : event.timestamp - chain.events[i - 1].timestamp;
        timings.push({
            eventId: event.id,
            sinceStart,
            sincePrevious,
            durationLabel: formatDuration(sincePrevious)
        });
    }
    return timings;
}
/**
 * Calculate statistics about a chain
 *
 * @param chain - The trigger chain
 * @returns Statistics object
 */
function calculateStatistics(chain) {
    const eventsByType = new Map();
    const eventsByComponent = new Map();
    const components = new Set();
    for (const event of chain.events) {
        // Count by type
        const typeCount = eventsByType.get(event.type) || 0;
        eventsByType.set(event.type, typeCount + 1);
        // Count by component
        const compCount = eventsByComponent.get(event.componentName) || 0;
        eventsByComponent.set(event.componentName, compCount + 1);
        components.add(event.componentName);
    }
    // Calculate gaps
    const gaps = [];
    for (let i = 1; i < chain.events.length; i++) {
        gaps.push(chain.events[i].timestamp - chain.events[i - 1].timestamp);
    }
    const averageEventGap = gaps.length > 0 ? gaps.reduce((a, b) => a + b, 0) / gaps.length : 0;
    const longestGap = gaps.length > 0 ? Math.max(...gaps) : 0;
    return {
        totalEvents: chain.events.length,
        eventsByType,
        eventsByComponent,
        averageEventGap,
        longestGap,
        componentsInvolved: Array.from(components)
    };
}
/**
 * Generate a descriptive name for a chain based on its events
 *
 * @param events - Events in the chain
 * @returns Generated name
 */
function generateChainName(events) {
    if (events.length === 0)
        return 'Empty Chain';
    const firstEvent = events[0];
    const eventCount = events.length;
    // Try to create meaningful name from first event
    if (firstEvent.nodeLabel && firstEvent.nodeLabel !== 'Unknown') {
        return `${firstEvent.nodeLabel} (${eventCount} events)`;
    }
    // Fallback to type-based name
    return `${firstEvent.type} chain (${eventCount} events)`;
}
/**
 * Format duration as human-readable string
 *
 * @param ms - Duration in milliseconds
 * @returns Formatted string (e.g., "2ms", "1.5s")
 */
function formatDuration(ms) {
    if (ms < 1)
        return '<1ms';
    if (ms < 1000)
        return `${Math.round(ms)}ms`;
    return `${(ms / 1000).toFixed(1)}s`;
}

;// ./src/editor/src/utils/triggerChain/index.ts
/**
 * Trigger Chain Debugger Module
 *
 * Exports recorder, chain builder, and types for the Trigger Chain Debugger feature.
 *
 * @module triggerChain
 */
// Recorder

// Chain Builder



/***/ }),

/***/ 41987:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_queryeditor_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(75189);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_queryeditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_queryeditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_queryeditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_queryeditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 42146:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   K: () => (/* binding */ NodeLibraryImporter)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80002);
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(underscore__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _noodl_models_nodelibrary_nodelibrary__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(15204);
/* harmony import */ var _noodl_models_nodelibrary_NodeLibraryData__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(68228);
/* harmony import */ var _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11138);




/**
 * Keep track of all the clients and their nodes.
 *
 * This is so we can make sure we always give the user the correct information
 * on what nodes are available to them.
 *
 * Because the viewers can connect/disconnect at any times, we keep a cache around to.
 * So when you get all the node names you will always get for all kinds of viewers runtimes.
 */
class ClientCollection {
    constructor() {
        // NOTE: Made public for labbing with ConnectionInspector
        this._clients = {};
        this._cache = {};
    }
    get count() {
        return Object.keys(this._clients).length;
    }
    getNodeNames() {
        const taken = new Set();
        // Get all the nodes of the viewers we have
        let nodes = Object.entries(this._clients).flatMap(([_clientId, item]) => {
            item.runtimeTypes.forEach((runtimeType) => taken.add(runtimeType));
            return [...item.nodes];
        });
        // Check if we are missing any runtime types
        if (taken.size !== _noodl_models_nodelibrary_NodeLibraryData__WEBPACK_IMPORTED_MODULE_2__/* .RuntimeTypes */ .C.length) {
            const missing = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.difference)(_noodl_models_nodelibrary_NodeLibraryData__WEBPACK_IMPORTED_MODULE_2__/* .RuntimeTypes */ .C, Array.from(taken.keys()));
            missing.forEach((runtimeType) => {
                if (this._cache[runtimeType]) {
                    nodes = nodes.concat(Array.from(this._cache[runtimeType].keys()));
                }
                else {
                    // console.error('[nodelib] Missing runtime type: ', runtimeType);
                }
            });
        }
        return new Set(nodes);
    }
    import(clientId, runtimeType, nodetypes) {
        if (!this._clients[clientId]) {
            this._clients[clientId] = {
                runtimeTypes: new Set(),
                nodes: new Set()
            };
        }
        this._clients[clientId].runtimeTypes.add(runtimeType);
        // Update the node set
        this._clients[clientId].nodes.clear();
        nodetypes.forEach((node) => {
            this._clients[clientId].nodes.add(node.name);
        });
        this._cache[runtimeType] = this._clients[clientId].nodes;
    }
    remove(clientId) {
        delete this._clients[clientId];
    }
    clear() {
        this._clients = {};
        this._cache = {};
    }
}
/**
 * Handle merging of node libraries between different runtimes.
 */
class NodeLibraryImporter {
    constructor() {
        this.currentNodeLibrary = null;
        this.clients = new ClientCollection();
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_3__.EventDispatcher.instance.on('ProjectModel.instanceWillChange', () => {
            this.clients.clear();
            this.currentNodeLibrary = null;
        }, this);
    }
    // NOTE: Made for labbing with ConnectionInspector
    clientsWithRuntime(runtimeType) {
        return Object.keys(this.clients._clients).filter((key) => this.clients._clients[key].runtimeTypes.has(runtimeType));
    }
    clear() {
        console.debug('[nodelib] Clear');
        this.clients.clear();
        this.currentNodeLibrary = null;
    }
    /**
     * Occurs when the client is disconnecting.
     *
     * @param clientId
     */
    onClientDisconnect(clientId) {
        this.clients.remove(clientId);
        this.updateIndex(false);
    }
    /**
     * Occurs when the client is sending their node library.
     *
     * @param clientId
     * @param runtimeType
     * @param library
     * @returns
     */
    onClientImport(clientId, runtimeType, library) {
        this.clients.import(clientId, runtimeType, library.nodetypes);
        console.debug('[nodelib] Received', runtimeType, ` (nodes: ${library.nodetypes.length})`);
        // Assign or update the new library into our current version.
        let updated = false;
        if (!this.currentNodeLibrary) {
            this.assignNewLibrary(runtimeType, library);
            updated = true;
        }
        else {
            if (this.mergeUpdates(runtimeType, library)) {
                updated = true;
            }
        }
        this.updateIndex(updated);
    }
    updateIndex(forceUpdate) {
        if (!this.currentNodeLibrary) {
            // @ts-ignore
            window.NodeLibraryData = {};
            return;
        }
        const nodeNames = this.clients.getNodeNames();
        // Remove all the nodes that we don't have anymore
        const removedNodes = [];
        this.currentNodeLibrary.nodetypes = this.currentNodeLibrary.nodetypes.filter((node) => {
            if (!nodeNames.has(node.name)) {
                removedNodes.push(node);
                return false;
            }
            return true;
        });
        if (forceUpdate || removedNodes.length > 0) {
            // Send the node library to our NodeLibrary
            const exportJSON = JSON.parse(JSON.stringify(this.currentNodeLibrary));
            // @ts-ignore
            window.NodeLibraryData = exportJSON;
            if (this.clients.count >= 2) {
                console.debug('[nodelib] Loaded new node library');
                if (removedNodes.length > 0)
                    console.debug('[nodelib] Removed nodes: ', removedNodes);
                _noodl_models_nodelibrary_nodelibrary__WEBPACK_IMPORTED_MODULE_1__/* .NodeLibrary */ .m.instance.reload();
            }
        }
    }
    assignNewLibrary(runtimeType, library) {
        // Use the new library if we have none already.
        this.currentNodeLibrary = library;
        // Add what runtime the nodes are from.
        this.currentNodeLibrary.nodetypes.forEach((node) => {
            node.runtimeTypes = [runtimeType];
        });
        // Make sure the data structure is what we expect
        if (!this.currentNodeLibrary.nodeIndex.coreNodes) {
            this.currentNodeLibrary.nodeIndex.coreNodes = [];
        }
        if (!this.currentNodeLibrary.nodeIndex.moduleNodes) {
            this.currentNodeLibrary.nodeIndex.moduleNodes = [];
        }
    }
    mergeUpdates(runtimeType, library) {
        let updated = false;
        // Loop over all the new node types
        library.nodetypes.forEach((node) => {
            const index = this.currentNodeLibrary.nodetypes.findIndex((x) => node.name === x.name);
            if (index === -1) {
                // Add the node, if it doesnt exist with the correct runtime
                node.runtimeTypes = [runtimeType];
                this.currentNodeLibrary.nodetypes.push(node);
                updated = true;
            }
            else {
                // TODO: Update the node data?
                // Create the array if it doesnt exist
                if (!this.currentNodeLibrary.nodetypes[index].runtimeTypes) {
                    this.currentNodeLibrary.nodetypes[index].runtimeTypes = [];
                }
                // Insert the new runtime if we dont have it.
                if (!this.currentNodeLibrary.nodetypes[index].runtimeTypes.includes(runtimeType)) {
                    this.currentNodeLibrary.nodetypes[index].runtimeTypes.push(runtimeType);
                    updated = true;
                }
            }
        });
        // Merge replace by name function
        function mergeInByName(inputArray, outputArray) {
            inputArray.forEach((inputItem) => {
                const index = outputArray.findIndex((_t) => inputItem.name === _t.name);
                if (index !== -1) {
                    outputArray[index] = inputItem;
                }
                else {
                    outputArray.push(inputItem);
                    updated = true;
                }
            });
            // if (inputArray.length > 0) {
            //   updated = true;
            // }
        }
        if (library.nodeIndex.coreNodes) {
            mergeInByName(library.nodeIndex.coreNodes, this.currentNodeLibrary.nodeIndex.coreNodes);
        }
        if (library.nodeIndex.moduleNodes) {
            mergeInByName(library.nodeIndex.moduleNodes, this.currentNodeLibrary.nodeIndex.moduleNodes);
        }
        // do the same for project settings ports
        mergeInByName(library.projectsettings.ports, this.currentNodeLibrary.projectsettings.ports);
        mergeInByName(library.projectsettings.dynamicports, this.currentNodeLibrary.projectsettings.dynamicports);
        return updated;
    }
}
NodeLibraryImporter.instance = new NodeLibraryImporter();


/***/ }),

/***/ 42533:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

//Note: this files has to be javascript and require until the main process uses webpack+typescript

const _ = __webpack_require__(42551);

const _nodesSoftEqualOmitProps = ['x', 'y', 'dynamicports', 'metadata', 'conflicts'];
const _nodesSoftEqualOmitPropsRootNodes = _nodesSoftEqualOmitProps.concat('_sort');

function nodesSoftEqual(a, b) {
  //_sort and _parent are extra attribute added by the diff code. _sort is the child index
  //we don't want to show root nodes as "Changed" if the _sort paramters differs, but we do for nodes with parents
  //(to cover the case where siblings have been rearranged without any other changes)
  const areRootNodes = !a._parent && !b._parent;

  const propsToOmit = areRootNodes ? _nodesSoftEqualOmitPropsRootNodes : _nodesSoftEqualOmitProps;

  return _.isEqual(_.omit(a, propsToOmit), _.omit(b, propsToOmit));
}

module.exports = {
  nodesSoftEqual
};


/***/ }),

/***/ 42551:
/***/ ((module) => {

"use strict";
module.exports = require("lodash");

/***/ }),

/***/ 42613:
/***/ ((module) => {

"use strict";
module.exports = require("assert");

/***/ }),

/***/ 42897:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgLink = function SvgLink(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M22.5011 11.1637L19.6264 11.1637C19.2122 11.1637 18.8764 10.8279 18.8764 10.4137C18.8764 9.99948 19.2122 9.6637 19.6264 9.6637L22.5193 9.6637C22.5308 9.6637 22.5424 9.66396 22.554 9.6645C23.9172 9.72766 25.2037 10.3137 26.1461 11.3007C27.0886 12.2878 27.6144 13.6001 27.6144 14.9648C27.6144 16.3295 27.0886 17.6418 26.1461 18.6288C25.2037 19.6159 23.9172 20.2019 22.554 20.2651C22.542 20.2656 22.5299 20.2659 22.5179 20.2659L18.3933 20.2586L18.3919 20.2586C17.6966 20.2597 17.0079 20.1236 16.3653 19.8582C15.7223 19.5925 15.1381 19.2025 14.6461 18.7106C14.1541 18.2186 13.7641 17.6343 13.4985 16.9913C13.2328 16.3483 13.0968 15.6591 13.0981 14.9634C13.0988 14.5492 13.4353 14.214 13.8495 14.2148C14.2637 14.2156 14.5988 14.552 14.5981 14.9662C14.5971 15.4645 14.6946 15.958 14.8848 16.4186C15.0751 16.8791 15.3544 17.2976 15.7067 17.6499C16.0591 18.0022 16.4775 18.2816 16.9381 18.4718C17.3986 18.6621 17.8922 18.7595 18.3905 18.7586H18.3932L22.5018 18.7659C23.4732 18.7165 24.3892 18.2969 25.0612 17.593C25.7372 16.885 26.1144 15.9437 26.1144 14.9648C26.1144 13.9859 25.7372 13.0446 25.0612 12.3366C24.389 11.6325 23.4728 11.213 22.5011 11.1637Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M16.1095 12.2795C15.7571 11.9272 15.3387 11.6479 14.8782 11.4576C14.4176 11.2673 13.9241 11.1699 13.4258 11.1708L13.423 11.1708L9.31448 11.1635C8.343 11.213 7.42703 11.6325 6.75501 12.3364C6.07902 13.0444 5.70183 13.9857 5.70183 14.9646C5.70183 15.9435 6.07902 16.8848 6.75501 17.5928C7.42718 18.2969 8.34339 18.7164 9.31511 18.7657L12.1898 18.7657C12.604 18.7657 12.9398 19.1015 12.9398 19.5157C12.9398 19.9299 12.604 20.2657 12.1898 20.2657L9.29697 20.2657C9.2854 20.2657 9.27382 20.2654 9.26226 20.2649C7.899 20.2017 6.61249 19.6157 5.67008 18.6287C4.72767 17.6416 4.20183 16.3293 4.20183 14.9646C4.20183 13.5999 4.72767 12.2876 5.67008 11.3006C6.61249 10.3135 7.899 9.72747 9.26226 9.66432C9.27426 9.66376 9.28628 9.66349 9.2983 9.66351L13.4244 9.67082C14.1196 9.6697 14.8083 9.80577 15.4509 10.0712C16.0939 10.3369 16.6782 10.7269 17.1701 11.2188C17.6621 11.7108 18.0521 12.2951 18.3177 12.9381C18.5834 13.5811 18.7195 14.2703 18.7182 14.966C18.7174 15.3802 18.381 15.7154 17.9668 15.7146C17.5525 15.7138 17.2174 15.3774 17.2182 14.9632C17.2191 14.4649 17.1216 13.9714 16.9314 13.5108C16.7411 13.0503 16.4618 12.6318 16.1095 12.2795Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgLink);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "dafa61aa7ede2c4ba608a80f6eb8d8fc.svg");

/***/ }),

/***/ 42927:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ExpressionToggle-module__Root--OvUcV{display:flex;align-items:center;justify-content:center}.ExpressionToggle-module__ExpressionActive--ntzk1{background-color:var(--theme-color-primary, #6366f1);color:#fff}.ExpressionToggle-module__ExpressionActive--ntzk1:hover{background-color:var(--theme-color-primary-hover, #4f46e5)}.ExpressionToggle-module__ExpressionActive--ntzk1:active{background-color:var(--theme-color-primary-active, #4338ca)}.ExpressionToggle-module__ConnectionIndicator--OI_aO{display:flex;align-items:center;justify-content:center;width:24px;height:24px;opacity:.5;cursor:default}.ExpressionToggle-module__FxButton--z97gm{display:flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:none;background:rgba(0,0,0,0);font-family:"Monaco","Menlo","Ubuntu Mono","Courier New",monospace;font-size:10px;font-weight:600;color:var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.5));cursor:pointer;border-radius:4px;transition:all .15s ease;flex-shrink:0}.ExpressionToggle-module__FxButton--z97gm:hover{background-color:var(--theme-color-bg-1, rgba(255, 255, 255, 0.1));color:var(--theme-color-primary, #6366f1)}.ExpressionToggle-module__FxButton--z97gm:focus{outline:none;background-color:var(--theme-color-bg-1, rgba(255, 255, 255, 0.1))}.ExpressionToggle-module__FxButton--z97gm.ExpressionToggle-module__is-disabled--oYUcV{opacity:.4;cursor:not-allowed}.ExpressionToggle-module__FxButton--z97gm.ExpressionToggle-module__is-disabled--oYUcV:hover{background:rgba(0,0,0,0);color:var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.5))}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/property-panel/ExpressionToggle/ExpressionToggle.module.scss"],"names":[],"mappings":"AAAA,sCACE,YAAA,CACA,kBAAA,CACA,sBAAA,CAGF,kDACE,oDAAA,CACA,UAAA,CAEA,wDACE,0DAAA,CAGF,yDACE,2DAAA,CAIJ,qDACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CACA,WAAA,CACA,UAAA,CACA,cAAA,CAGF,0CACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CACA,WAAA,CACA,SAAA,CACA,WAAA,CACA,wBAAA,CACA,kEAAA,CACA,cAAA,CACA,eAAA,CACA,iEAAA,CACA,cAAA,CACA,iBAAA,CACA,wBAAA,CACA,aAAA,CAEA,gDACE,kEAAA,CACA,yCAAA,CAGF,gDACE,YAAA,CACA,kEAAA,CAGF,sFACE,UAAA,CACA,kBAAA,CAEA,4FACE,wBAAA,CACA,iEAAA","sourcesContent":[".Root {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.ExpressionActive {\n  background-color: var(--theme-color-primary, #6366f1);\n  color: white;\n\n  &:hover {\n    background-color: var(--theme-color-primary-hover, #4f46e5);\n  }\n\n  &:active {\n    background-color: var(--theme-color-primary-active, #4338ca);\n  }\n}\n\n.ConnectionIndicator {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 24px;\n  height: 24px;\n  opacity: 0.5;\n  cursor: default;\n}\n\n.FxButton {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 24px;\n  height: 24px;\n  padding: 0;\n  border: none;\n  background: transparent;\n  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Courier New', monospace;\n  font-size: 10px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.5));\n  cursor: pointer;\n  border-radius: 4px;\n  transition: all 0.15s ease;\n  flex-shrink: 0;\n\n  &:hover {\n    background-color: var(--theme-color-bg-1, rgba(255, 255, 255, 0.1));\n    color: var(--theme-color-primary, #6366f1);\n  }\n\n  &:focus {\n    outline: none;\n    background-color: var(--theme-color-bg-1, rgba(255, 255, 255, 0.1));\n  }\n\n  &.is-disabled {\n    opacity: 0.4;\n    cursor: not-allowed;\n\n    &:hover {\n      background: transparent;\n      color: var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.5));\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ExpressionToggle-module__Root--OvUcV`,
	"ExpressionActive": `ExpressionToggle-module__ExpressionActive--ntzk1`,
	"ConnectionIndicator": `ExpressionToggle-module__ConnectionIndicator--OI_aO`,
	"FxButton": `ExpressionToggle-module__FxButton--z97gm`,
	"is-disabled": `ExpressionToggle-module__is-disabled--oYUcV`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 42980:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgImage = function SvgImage(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M18.2888 13.0822C17.3611 13.0822 16.6089 12.3301 16.6089 11.4023C16.6089 10.4745 17.3611 9.72241 18.2888 9.72241C19.2166 9.72241 19.9688 10.4745 19.9688 11.4023C19.9688 12.3301 19.2166 13.0822 18.2888 13.0822Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.8042 5.60229C4.8042 5.46422 4.91613 5.35229 5.0542 5.35229H25.0542C25.1923 5.35229 25.3042 5.46422 25.3042 5.60229V21.3411L22.2517 18.5885C21.9312 18.2995 21.4508 18.2786 21.1065 18.5387L18.2453 20.7004C17.9736 20.9056 17.5944 20.8884 17.3425 20.6595L10.7908 14.7068C10.439 14.3872 9.89938 14.3962 9.55847 14.7273L4.8042 19.3454V5.60229ZM5.0542 3.85229C4.0877 3.85229 3.3042 4.6358 3.3042 5.60229V25.6023C3.3042 26.5688 4.0877 27.3523 5.0542 27.3523H25.0542C26.0207 27.3523 26.8042 26.5688 26.8042 25.6023V5.60229C26.8042 4.6358 26.0207 3.85229 25.0542 3.85229H5.0542Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgImage);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "0230684fde02a1638fe909bb5cf33346.svg");

/***/ }),

/***/ 43337:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgTextInput = function SvgTextInput(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.30713 10.3201H25.8038C26.356 10.3201 26.8038 10.7678 26.8038 11.3201V18.693C26.8038 19.2453 26.356 19.7663 25.8038 19.7663H4.30713C3.75484 19.7663 3.30713 19.2453 3.30713 18.693V11.3201C3.30713 10.7678 3.75484 10.3201 4.30713 10.3201ZM7.08831 12.2277C7.08831 11.8134 6.75252 11.4777 6.33831 11.4777C5.92409 11.4777 5.58831 11.8134 5.58831 12.2277L5.58831 17.8586C5.58831 18.2729 5.92409 18.6086 6.33831 18.6086C6.75252 18.6086 7.08831 18.2729 7.08831 17.8586L7.08831 12.2277Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgTextInput);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "b0d0726694260bebfba5d5d65d0705c8.svg");

/***/ }),

/***/ 43725:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Stack-module__Root--EIzbi{display:flex}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/Stack/Stack.module.scss"],"names":[],"mappings":"AAAA,2BACE,YAAA","sourcesContent":[".Root {\n  display: flex;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Stack-module__Root--EIzbi`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 43948:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Title-module__Root--QXCd3{font-weight:600;margin-bottom:0;margin-top:0;font-family:var(--font-family)}.Title-module__Root--QXCd3.Title-module__has-bottom-spacing--kvT_3{margin-bottom:8px}.Title-module__Root--QXCd3.Title-module__is-size-default--wiYkD{font-size:14px}.Title-module__Root--QXCd3.Title-module__is-size-large--eKK2p{font-size:18px}.Title-module__Root--QXCd3.Title-module__is-size-medium--hui81{font-size:12px;-webkit-font-smoothing:antialiased}.Title-module__Root--QXCd3.Title-module__is-size-small--ZDDuJ{font-size:10px}.Title-module__Root--QXCd3.Title-module__is-centered--HlYi_{text-align:center}.Title-module__Root--QXCd3.Title-module__is-inline--kH9cn{display:inline-block}.Title-module__Root--QXCd3.Title-module__is-variant-default--rmOfY{color:var(--theme-color-fg-default)}.Title-module__Root--QXCd3.Title-module__is-variant-default-contrast--earGQ{color:var(--theme-color-fg-default-contrast)}.Title-module__Root--QXCd3.Title-module__is-variant-highlighted--FiHni{color:var(--theme-color-fg-highlight)}.Title-module__Root--QXCd3.Title-module__is-variant-danger--D63wc{color:var(--theme-color-danger)}.Title-module__Root--QXCd3.Title-module__is-variant-success--JMT3y{color:var(--theme-color-success)}.Title-module__Root--QXCd3.Title-module__is-variant-notice--RRgoY{color:var(--theme-color-primary)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/typography/Title/Title.module.scss"],"names":[],"mappings":"AAAA,2BACE,eAAA,CACA,eAAA,CACA,YAAA,CACA,8BAAA,CAEA,mEACE,iBAAA,CAGF,gEACE,cAAA,CAGF,8DACE,cAAA,CAGF,+DACE,cAAA,CACA,kCAAA,CAGF,8DACE,cAAA,CAGF,4DACE,iBAAA,CAGF,0DACE,oBAAA,CAGF,mEACE,mCAAA,CAGF,4EACE,4CAAA,CAGF,uEACE,qCAAA,CAGF,kEACE,+BAAA,CAGF,mEACE,gCAAA,CAGF,kEACE,gCAAA","sourcesContent":[".Root {\r\n  font-weight: 600;\r\n  margin-bottom: 0;\r\n  margin-top: 0;\r\n  font-family: var(--font-family);\r\n\r\n  &.has-bottom-spacing {\r\n    margin-bottom: 8px;\r\n  }\r\n\r\n  &.is-size-default {\r\n    font-size: 14px;\r\n  }\r\n\r\n  &.is-size-large {\r\n    font-size: 18px;\r\n  }\r\n\r\n  &.is-size-medium {\r\n    font-size: 12px;\r\n    -webkit-font-smoothing: antialiased;\r\n  }\r\n\r\n  &.is-size-small {\r\n    font-size: 10px;\r\n  }\r\n\r\n  &.is-centered {\r\n    text-align: center;\r\n  }\r\n\r\n  &.is-inline {\r\n    display: inline-block;\r\n  }\r\n\r\n  &.is-variant-default {\r\n    color: var(--theme-color-fg-default);\r\n  }\r\n\r\n  &.is-variant-default-contrast {\r\n    color: var(--theme-color-fg-default-contrast);\r\n  }\r\n\r\n  &.is-variant-highlighted {\r\n    color: var(--theme-color-fg-highlight);\r\n  }\r\n\r\n  &.is-variant-danger {\r\n    color: var(--theme-color-danger);\r\n  }\r\n\r\n  &.is-variant-success {\r\n    color: var(--theme-color-success);\r\n  }\r\n\r\n  &.is-variant-notice {\r\n    color: var(--theme-color-primary);\r\n  }\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Title-module__Root--QXCd3`,
	"has-bottom-spacing": `Title-module__has-bottom-spacing--kvT_3`,
	"is-size-default": `Title-module__is-size-default--wiYkD`,
	"is-size-large": `Title-module__is-size-large--eKK2p`,
	"is-size-medium": `Title-module__is-size-medium--hui81`,
	"is-size-small": `Title-module__is-size-small--ZDDuJ`,
	"is-centered": `Title-module__is-centered--HlYi_`,
	"is-inline": `Title-module__is-inline--kH9cn`,
	"is-variant-default": `Title-module__is-variant-default--rmOfY`,
	"is-variant-default-contrast": `Title-module__is-variant-default-contrast--earGQ`,
	"is-variant-highlighted": `Title-module__is-variant-highlighted--FiHni`,
	"is-variant-danger": `Title-module__is-variant-danger--D63wc`,
	"is-variant-success": `Title-module__is-variant-success--JMT3y`,
	"is-variant-notice": `Title-module__is-variant-notice--RRgoY`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 44075:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/* -------------------------------------------------------------------
   String list
   ------------------------------------------------------------------- */
.proplist-add-button-container {
  position: relative;
  padding-right: 0;
}

.proplist-default-label {
  color: var(--theme-color-fg-muted);
}

.proplist-item {
  cursor: default;
  color: var(--theme-color-fg-highlight);
  position: relative;
  line-height: 35px;
}

.proplist-header {
  background-color: var(--theme-color-bg-2);
  margin-bottom: 2px;
  margin-top: 2px;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/propertyeditor/proplist.css"],"names":[],"mappings":"AAAA;;wEAEwE;AACxE;EACE,kBAAkB;EAClB,gBAAgB;AAClB;;AAEA;EACE,kCAAkC;AACpC;;AAEA;EACE,eAAe;EACf,sCAAsC;EACtC,kBAAkB;EAClB,iBAAiB;AACnB;;AAEA;EACE,yCAAyC;EACzC,kBAAkB;EAClB,eAAe;AACjB","sourcesContent":["/* -------------------------------------------------------------------\n   String list\n   ------------------------------------------------------------------- */\n.proplist-add-button-container {\n  position: relative;\n  padding-right: 0;\n}\n\n.proplist-default-label {\n  color: var(--theme-color-fg-muted);\n}\n\n.proplist-item {\n  cursor: default;\n  color: var(--theme-color-fg-highlight);\n  position: relative;\n  line-height: 35px;\n}\n\n.proplist-header {\n  background-color: var(--theme-color-bg-2);\n  margin-bottom: 2px;\n  margin-top: 2px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 44351:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LineDecoder = void 0;
exports.findDoubleNewlineIndex = findDoubleNewlineIndex;
const tslib_1 = __webpack_require__(84499);
const bytes_1 = __webpack_require__(38870);
/**
 * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
 * reading lines from text.
 *
 * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
 */
class LineDecoder {
    constructor() {
        _LineDecoder_buffer.set(this, void 0);
        _LineDecoder_carriageReturnIndex.set(this, void 0);
        tslib_1.__classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f");
        tslib_1.__classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
    }
    decode(chunk) {
        if (chunk == null) {
            return [];
        }
        const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
            : typeof chunk === 'string' ? (0, bytes_1.encodeUTF8)(chunk)
                : chunk;
        tslib_1.__classPrivateFieldSet(this, _LineDecoder_buffer, (0, bytes_1.concatBytes)([tslib_1.__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f");
        const lines = [];
        let patternIndex;
        while ((patternIndex = findNewlineIndex(tslib_1.__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), tslib_1.__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
            if (patternIndex.carriage && tslib_1.__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) {
                // skip until we either get a corresponding `\n`, a new `\r` or nothing
                tslib_1.__classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
                continue;
            }
            // we got double \r or \rtext\n
            if (tslib_1.__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null &&
                (patternIndex.index !== tslib_1.__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
                lines.push((0, bytes_1.decodeUTF8)(tslib_1.__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, tslib_1.__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
                tslib_1.__classPrivateFieldSet(this, _LineDecoder_buffer, tslib_1.__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(tslib_1.__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f");
                tslib_1.__classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
                continue;
            }
            const endIndex = tslib_1.__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
            const line = (0, bytes_1.decodeUTF8)(tslib_1.__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex));
            lines.push(line);
            tslib_1.__classPrivateFieldSet(this, _LineDecoder_buffer, tslib_1.__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f");
            tslib_1.__classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
        }
        return lines;
    }
    flush() {
        if (!tslib_1.__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
            return [];
        }
        return this.decode('\n');
    }
}
exports.LineDecoder = LineDecoder;
_LineDecoder_buffer = new WeakMap(), _LineDecoder_carriageReturnIndex = new WeakMap();
// prettier-ignore
LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']);
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
/**
 * This function searches the buffer for the end patterns, (\r or \n)
 * and returns an object with the index preceding the matched newline and the
 * index after the newline char. `null` is returned if no new line is found.
 *
 * ```ts
 * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
 * ```
 */
function findNewlineIndex(buffer, startIndex) {
    const newline = 0x0a; // \n
    const carriage = 0x0d; // \r
    for (let i = startIndex ?? 0; i < buffer.length; i++) {
        if (buffer[i] === newline) {
            return { preceding: i, index: i + 1, carriage: false };
        }
        if (buffer[i] === carriage) {
            return { preceding: i, index: i + 1, carriage: true };
        }
    }
    return null;
}
function findDoubleNewlineIndex(buffer) {
    // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
    // and returns the index right after the first occurrence of any pattern,
    // or -1 if none of the patterns are found.
    const newline = 0x0a; // \n
    const carriage = 0x0d; // \r
    for (let i = 0; i < buffer.length - 1; i++) {
        if (buffer[i] === newline && buffer[i + 1] === newline) {
            // \n\n
            return i + 2;
        }
        if (buffer[i] === carriage && buffer[i + 1] === carriage) {
            // \r\r
            return i + 2;
        }
        if (buffer[i] === carriage &&
            buffer[i + 1] === newline &&
            i + 3 < buffer.length &&
            buffer[i + 2] === carriage &&
            buffer[i + 3] === newline) {
            // \r\n\r\n
            return i + 4;
        }
    }
    return -1;
}
//# sourceMappingURL=line.js.map

/***/ }),

/***/ 44736:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPageRouter = function SvgPageRouter(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M20.0938 5.5113C20.0938 5.06948 20.4519 4.7113 20.8937 4.7113H26.0037C26.4456 4.7113 26.8037 5.06948 26.8037 5.5113V10.6213C26.8037 11.0631 26.4456 11.4213 26.0037 11.4213H20.8937C20.4519 11.4213 20.0938 11.0631 20.0938 10.6213V8.65926H15.8667C15.755 8.65926 15.6645 8.74979 15.6645 8.86148V22.0219C15.6645 22.1336 15.755 22.2241 15.8667 22.2241H20.0938V20.2957C20.0938 19.8539 20.4519 19.4957 20.8937 19.4957H26.0037C26.4456 19.4957 26.8037 19.8539 26.8037 20.2957V25.4057C26.8037 25.8476 26.4456 26.2057 26.0037 26.2057H20.8937C20.4519 26.2057 20.0938 25.8476 20.0938 25.4057V23.4374H15.8667C15.0849 23.4374 14.4512 22.8037 14.4512 22.0219V16.0483H10.0137V17.9967C10.0137 18.4385 9.65554 18.7967 9.21371 18.7967H4.10371C3.66188 18.7967 3.30371 18.4385 3.30371 17.9967V12.8867C3.30371 12.4448 3.66188 12.0867 4.10371 12.0867H9.21371C9.65554 12.0867 10.0137 12.4448 10.0137 12.8867V14.835H14.4512V8.86148C14.4512 8.07969 15.0849 7.44592 15.8667 7.44592H20.0938V5.5113Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPageRouter);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "d4bae151de61ff76ab4c6f46cc35d0f8.svg");

/***/ }),

/***/ 45018:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
.monaco-editor .margin-view-overlays .codicon-folding-manual-collapsed,
.monaco-editor .margin-view-overlays .codicon-folding-manual-expanded,
.monaco-editor .margin-view-overlays .codicon-folding-expanded,
.monaco-editor .margin-view-overlays .codicon-folding-collapsed {
	cursor: pointer;
	opacity: 0;
	transition: opacity 0.5s;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 140%;
	margin-left: 2px;
}

.monaco-editor .margin-view-overlays:hover .codicon,
.monaco-editor .margin-view-overlays .codicon.codicon-folding-collapsed,
.monaco-editor .margin-view-overlays .codicon.codicon-folding-manual-collapsed,
.monaco-editor .margin-view-overlays .codicon.alwaysShowFoldIcons {
	opacity: 1;
}

.monaco-editor .inline-folded:after {
	color: grey;
	margin: 0.1em 0.2em 0 0.2em;
	content: "⋯";
	display: inline;
	line-height: 1em;
	cursor: pointer;
}

`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/folding/browser/folding.css"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;;;CAIC,eAAe;CACf,UAAU;CACV,wBAAwB;CACxB,aAAa;CACb,mBAAmB;CACnB,uBAAuB;CACvB,eAAe;CACf,gBAAgB;AACjB;;AAEA;;;;CAIC,UAAU;AACX;;AAEA;CACC,WAAW;CACX,2BAA2B;CAC3B,YAAY;CACZ,eAAe;CACf,gBAAgB;CAChB,eAAe;AAChB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n.monaco-editor .margin-view-overlays .codicon-folding-manual-collapsed,\n.monaco-editor .margin-view-overlays .codicon-folding-manual-expanded,\n.monaco-editor .margin-view-overlays .codicon-folding-expanded,\n.monaco-editor .margin-view-overlays .codicon-folding-collapsed {\n\tcursor: pointer;\n\topacity: 0;\n\ttransition: opacity 0.5s;\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n\tfont-size: 140%;\n\tmargin-left: 2px;\n}\n\n.monaco-editor .margin-view-overlays:hover .codicon,\n.monaco-editor .margin-view-overlays .codicon.codicon-folding-collapsed,\n.monaco-editor .margin-view-overlays .codicon.codicon-folding-manual-collapsed,\n.monaco-editor .margin-view-overlays .codicon.alwaysShowFoldIcons {\n\topacity: 1;\n}\n\n.monaco-editor .inline-folded:after {\n\tcolor: grey;\n\tmargin: 0.1em 0.2em 0 0.2em;\n\tcontent: \"⋯\";\n\tdisplay: inline;\n\tline-height: 1em;\n\tcursor: pointer;\n}\n\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 45217:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (/* binding */ usePrevious)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

function usePrevious(value) {
    const ref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(undefined);
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        ref.current = value;
    });
    return ref.current;
}


/***/ }),

/***/ 45226:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Av: () => (/* binding */ isFileImage),
/* harmony export */   FR: () => (/* binding */ GitStatusEntry),
/* harmony export */   HE: () => (/* binding */ FileChange),
/* harmony export */   Jb: () => (/* binding */ FileStatusKind),
/* harmony export */   Ls: () => (/* binding */ CommittedFileChange),
/* harmony export */   RI: () => (/* binding */ WorkingDirectoryStatus),
/* harmony export */   Tr: () => (/* binding */ getMediaType),
/* harmony export */   Y4: () => (/* binding */ UnmergedEntrySummary),
/* harmony export */   lY: () => (/* binding */ WorkingDirectoryFileChange)
/* harmony export */ });
/* unused harmony exports isConflictedFileStatus, isConflictWithMarkers, isManualConflict */
/* harmony import */ var _diff__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46553);

/**
 * The status entry code as reported by Git.
 */
var GitStatusEntry;
(function (GitStatusEntry) {
    GitStatusEntry["Modified"] = "M";
    GitStatusEntry["Added"] = "A";
    GitStatusEntry["Deleted"] = "D";
    GitStatusEntry["Renamed"] = "R";
    GitStatusEntry["Copied"] = "C";
    GitStatusEntry["Unchanged"] = ".";
    GitStatusEntry["Untracked"] = "?";
    GitStatusEntry["Ignored"] = "!";
    GitStatusEntry["UpdatedButUnmerged"] = "U";
})(GitStatusEntry || (GitStatusEntry = {}));
/** The enum representation of a Git file change */
var FileStatusKind;
(function (FileStatusKind) {
    FileStatusKind["New"] = "New";
    FileStatusKind["Modified"] = "Modified";
    FileStatusKind["Deleted"] = "Deleted";
    FileStatusKind["Copied"] = "Copied";
    FileStatusKind["Renamed"] = "Renamed";
    FileStatusKind["Conflicted"] = "Conflicted";
    FileStatusKind["Untracked"] = "Untracked";
})(FileStatusKind || (FileStatusKind = {}));
/** Custom typeguard to differentiate Conflict files from other types */
function isConflictedFileStatus(appFileStatus) {
    return appFileStatus.kind === FileStatusKind.Conflicted;
}
/** Custom typeguard to differentiate ConflictsWithMarkers from other Conflict types */
function isConflictWithMarkers(conflictedFileStatus) {
    return conflictedFileStatus.hasOwnProperty('conflictMarkerCount');
}
/** Custom typeguard to differentiate ManualConflict from other Conflict types */
function isManualConflict(conflictedFileStatus) {
    return !conflictedFileStatus.hasOwnProperty('conflictMarkerCount');
}
var UnmergedEntrySummary;
(function (UnmergedEntrySummary) {
    UnmergedEntrySummary["AddedByUs"] = "added-by-us";
    UnmergedEntrySummary["DeletedByUs"] = "deleted-by-us";
    UnmergedEntrySummary["AddedByThem"] = "added-by-them";
    UnmergedEntrySummary["DeletedByThem"] = "deleted-by-them";
    UnmergedEntrySummary["BothDeleted"] = "both-deleted";
    UnmergedEntrySummary["BothAdded"] = "both-added";
    UnmergedEntrySummary["BothModified"] = "both-modified";
})(UnmergedEntrySummary || (UnmergedEntrySummary = {}));
/** encapsulate changes to a file associated with a commit */
class FileChange {
    get extension() {
        const split = this.path.split('.');
        if (split.length > 0) {
            return '.' + split.at(-1);
        }
        else {
            return undefined;
        }
    }
    /**
     * @param path The relative path to the file in the repository.
     * @param status The status of the change to the file.
     */
    constructor(path, status) {
        this.path = path;
        this.status = status;
        if (status.kind === FileStatusKind.Renamed || status.kind === FileStatusKind.Copied) {
            this.id = `${status.kind}+${path}+${status.oldPath}`;
        }
        else {
            this.id = `${status.kind}+${path}`;
        }
    }
}
const imageFileExtensions = new Set(['.png', '.jpg', '.jpeg', '.gif', '.ico', '.webp', '.bmp', '.avif']);
function isFileImage(file) {
    return Array.from(imageFileExtensions).some((x) => file.extension === x);
}
/**
 * Map a given file extension to the related data URL media type
 */
function getMediaType(extension) {
    if (extension === '.png') {
        return 'image/png';
    }
    if (extension === '.jpg' || extension === '.jpeg') {
        return 'image/jpg';
    }
    if (extension === '.gif') {
        return 'image/gif';
    }
    if (extension === '.ico') {
        return 'image/x-icon';
    }
    if (extension === '.webp') {
        return 'image/webp';
    }
    if (extension === '.bmp') {
        return 'image/bmp';
    }
    if (extension === '.avif') {
        return 'image/avif';
    }
    // fallback value as per the spec
    return 'text/plain';
}
/** encapsulate the changes to a file in the working directory */
class WorkingDirectoryFileChange extends FileChange {
    /**
     * @param path The relative path to the file in the repository.
     * @param status The status of the change to the file.
     * @param selection Contains the selection details for this file - all, nothing or partial.
     * @param oldPath The original path in the case of a renamed file.
     */
    constructor(path, status, selection) {
        super(path, status);
        this.selection = selection;
    }
    /** Create a new WorkingDirectoryFileChange with the given includedness. */
    withIncludeAll(include) {
        const newSelection = include ? this.selection.withSelectAll() : this.selection.withSelectNone();
        return this.withSelection(newSelection);
    }
    /** Create a new WorkingDirectoryFileChange with the given diff selection. */
    withSelection(selection) {
        return new WorkingDirectoryFileChange(this.path, this.status, selection);
    }
}
/**
 * An object encapsulating the changes to a committed file.
 *
 * @param status A commit SHA or some other identifier that ultimately
 *               dereferences to a commit. This is the pointer to the
 *               'after' version of this change. I.e. the parent of this
 *               commit will contain the 'before' (or nothing, if the
 *               file change represents a new file).
 */
class CommittedFileChange extends FileChange {
    constructor(path, status, commitish) {
        super(path, status);
        this.commitish = commitish;
        this.commitish = commitish;
    }
}
/** the state of the working directory for a repository */
class WorkingDirectoryStatus {
    /** Create a new status with the given files. */
    static fromFiles(files) {
        return new WorkingDirectoryStatus(files, getIncludeAllState(files));
    }
    /**
     * @param files The list of changes in the repository's working directory.
     * @param includeAll Update the include checkbox state of the form.
     *                   NOTE: we need to track this separately to the file list selection
     *                         and perform two-way binding manually when this changes.
     */
    constructor(files, includeAll = true) {
        this.files = files;
        this.includeAll = includeAll;
        this.fileIxById = new Map();
        files.forEach((f, ix) => this.fileIxById.set(f.id, ix));
    }
    /**
     * Update the include state of all files in the working directory
     */
    withIncludeAllFiles(includeAll) {
        const newFiles = this.files.map((f) => f.withIncludeAll(includeAll));
        return new WorkingDirectoryStatus(newFiles, includeAll);
    }
    /** Find the file with the given ID. */
    findFileWithID(id) {
        const ix = this.fileIxById.get(id);
        return ix !== undefined ? this.files[ix] || null : null;
    }
    /** Find the index of the file with the given ID. Returns -1 if not found */
    findFileIndexByID(id) {
        const ix = this.fileIxById.get(id);
        return ix !== undefined ? ix : -1;
    }
}
function getIncludeAllState(files) {
    if (!files.length) {
        return true;
    }
    const allSelected = files.every((f) => f.selection.getSelectionType() === _diff__WEBPACK_IMPORTED_MODULE_0__/* .DiffSelectionType */ .i2.All);
    const noneSelected = files.every((f) => f.selection.getSelectionType() === _diff__WEBPACK_IMPORTED_MODULE_0__/* .DiffSelectionType */ .i2.None);
    let includeAll = null;
    if (allSelected) {
        includeAll = true;
    }
    else if (noneSelected) {
        includeAll = false;
    }
    return includeAll;
}


/***/ }),

/***/ 45288:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgStash = function SvgStash(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3 4.5C3 3.67157 3.67157 3 4.5 3H7.99518C8.40939 3 8.74518 3.33579 8.74518 3.75C8.74518 4.16421 8.40939 4.5 7.99518 4.5H4.5V19.5H19.5V4.5H15.9906C15.5764 4.5 15.2406 4.16421 15.2406 3.75C15.2406 3.33579 15.5764 3 15.9906 3H19.5C20.3284 3 21 3.67157 21 4.5V19.5C21 20.3284 20.3284 21 19.5 21H4.5C3.67157 21 3 20.3284 3 19.5V4.5Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M8.29145 11.0415C8.58434 10.7486 9.05921 10.7486 9.35211 11.0415L11.9999 13.6893L14.6477 11.0415C14.9406 10.7486 15.4155 10.7486 15.7084 11.0415C16.0013 11.3344 16.0013 11.8093 15.7084 12.1022L12.5302 15.2803C12.2373 15.5732 11.7625 15.5732 11.4696 15.2803L8.29145 12.1022C7.99855 11.8093 7.99855 11.3344 8.29145 11.0415Z",
    fill: "#B8B8B8"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12 6.5C12.4142 6.5 12.75 6.83579 12.75 7.25V14.75C12.75 15.1642 12.4142 15.5 12 15.5C11.5858 15.5 11.25 15.1642 11.25 14.75V7.25C11.25 6.83579 11.5858 6.5 12 6.5Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgStash);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "0aa2103be79d50f811513359c2645d5d.svg");

/***/ }),

/***/ 45330:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  A: () => (/* binding */ ColorPicker_colorpicker)
});

;// ../../node_modules/@jaames/iro/dist/iro.es.js
/*!
 * iro.js v5.5.2
 * 2016-2021 James Daniel
 * Licensed under MPL 2.0
 * github.com/jaames/iro.js
 */

var n,u,t,i,r,o,f={},e=[],c=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|^--/i;function s(n,l){for(var u in l){ n[u]=l[u]; }return n}function a(n){var l=n.parentNode;l&&l.removeChild(n);}function h(n,l,u){var t,i,r,o,f=arguments;if(l=s({},l),arguments.length>3){ for(u=[u],t=3;t<arguments.length;t++){ u.push(f[t]); } }if(null!=u&&(l.children=u),null!=n&&null!=n.defaultProps){ for(i in n.defaultProps){ void 0===l[i]&&(l[i]=n.defaultProps[i]); } }return o=l.key,null!=(r=l.ref)&&delete l.ref,null!=o&&delete l.key,v(n,l,o,r)}function v(l,u,t,i){var r={type:l,props:u,key:t,ref:i,__k:null,__p:null,__b:0,__e:null,l:null,__c:null,constructor:void 0};return n.vnode&&n.vnode(r),r}function d(n){return n.children}function y(n){if(null==n||"boolean"==typeof n){ return null; }if("string"==typeof n||"number"==typeof n){ return v(null,n,null,null); }if(null!=n.__e||null!=n.__c){var l=v(n.type,n.props,n.key,null);return l.__e=n.__e,l}return n}function m(n,l){this.props=n,this.context=l;}function w(n,l){if(null==l){ return n.__p?w(n.__p,n.__p.__k.indexOf(n)+1):null; }for(var u;l<n.__k.length;l++){ if(null!=(u=n.__k[l])&&null!=u.__e){ return u.__e; } }return "function"==typeof n.type?w(n):null}function g(n){var l,u;if(null!=(n=n.__p)&&null!=n.__c){for(n.__e=n.__c.base=null,l=0;l<n.__k.length;l++){ if(null!=(u=n.__k[l])&&null!=u.__e){n.__e=n.__c.base=u.__e;break} }return g(n)}}function k(l){(!l.__d&&(l.__d=!0)&&1===u.push(l)||i!==n.debounceRendering)&&(i=n.debounceRendering,(n.debounceRendering||t)(_));}function _(){var n,l,t,i,r,o,f,e;for(u.sort(function(n,l){return l.__v.__b-n.__v.__b});n=u.pop();){ n.__d&&(t=void 0,i=void 0,o=(r=(l=n).__v).__e,f=l.__P,e=l.u,l.u=!1,f&&(t=[],i=iro_es_$(f,r,s({},r),l.__n,void 0!==f.ownerSVGElement,null,t,e,null==o?w(r):o),j(t,r),i!=o&&g(r))); }}function b(n,l,u,t,i,r,o,c,s){var h,v,p,d,y,m,g,k=u&&u.__k||e,_=k.length;if(c==f&&(c=null!=r?r[0]:_?w(u,0):null),h=0,l.__k=x(l.__k,function(u){if(null!=u){if(u.__p=l,u.__b=l.__b+1,null===(p=k[h])||p&&u.key==p.key&&u.type===p.type){ k[h]=void 0; }else { for(v=0;v<_;v++){if((p=k[v])&&u.key==p.key&&u.type===p.type){k[v]=void 0;break}p=null;} }if(d=iro_es_$(n,u,p=p||f,t,i,r,o,null,c,s),(v=u.ref)&&p.ref!=v&&(g||(g=[])).push(v,u.__c||d,u),null!=d){if(null==m&&(m=d),null!=u.l){ d=u.l,u.l=null; }else if(r==p||d!=c||null==d.parentNode){n:if(null==c||c.parentNode!==n){ n.appendChild(d); }else{for(y=c,v=0;(y=y.nextSibling)&&v<_;v+=2){ if(y==d){ break n; } }n.insertBefore(d,c);}"option"==l.type&&(n.value="");}c=d.nextSibling,"function"==typeof l.type&&(l.l=d);}}return h++,u}),l.__e=m,null!=r&&"function"!=typeof l.type){ for(h=r.length;h--;){ null!=r[h]&&a(r[h]); } }for(h=_;h--;){ null!=k[h]&&D(k[h],k[h]); }if(g){ for(h=0;h<g.length;h++){ A(g[h],g[++h],g[++h]); } }}function x(n,l,u){if(null==u&&(u=[]),null==n||"boolean"==typeof n){ l&&u.push(l(null)); }else if(Array.isArray(n)){ for(var t=0;t<n.length;t++){ x(n[t],l,u); } }else { u.push(l?l(y(n)):n); }return u}function C(n,l,u,t,i){var r;for(r in u){ r in l||N(n,r,null,u[r],t); }for(r in l){ i&&"function"!=typeof l[r]||"value"===r||"checked"===r||u[r]===l[r]||N(n,r,l[r],u[r],t); }}function P(n,l,u){"-"===l[0]?n.setProperty(l,u):n[l]="number"==typeof u&&!1===c.test(l)?u+"px":null==u?"":u;}function N(n,l,u,t,i){var r,o,f,e,c;if("key"===(l=i?"className"===l?"class":l:"class"===l?"className":l)||"children"===l);else if("style"===l){ if(r=n.style,"string"==typeof u){ r.cssText=u; }else{if("string"==typeof t&&(r.cssText="",t=null),t){ for(o in t){ u&&o in u||P(r,o,""); } }if(u){ for(f in u){ t&&u[f]===t[f]||P(r,f,u[f]); } }} }else{ "o"===l[0]&&"n"===l[1]?(e=l!==(l=l.replace(/Capture$/,"")),c=l.toLowerCase(),l=(c in n?c:l).slice(2),u?(t||n.addEventListener(l,T,e),(n.t||(n.t={}))[l]=u):n.removeEventListener(l,T,e)):"list"!==l&&"tagName"!==l&&"form"!==l&&!i&&l in n?n[l]=null==u?"":u:"function"!=typeof u&&"dangerouslySetInnerHTML"!==l&&(l!==(l=l.replace(/^xlink:?/,""))?null==u||!1===u?n.removeAttributeNS("http://www.w3.org/1999/xlink",l.toLowerCase()):n.setAttributeNS("http://www.w3.org/1999/xlink",l.toLowerCase(),u):null==u||!1===u?n.removeAttribute(l):n.setAttribute(l,u)); }}function T(l){return this.t[l.type](n.event?n.event(l):l)}function iro_es_$(l,u,t,i,r,o,f,e,c,a){var h,v,p,y,w,g,k,_,C,P,N=u.type;if(void 0!==u.constructor){ return null; }(h=n.__b)&&h(u);try{n:if("function"==typeof N){if(_=u.props,C=(h=N.contextType)&&i[h.__c],P=h?C?C.props.value:h.__p:i,t.__c?k=(v=u.__c=t.__c).__p=v.__E:("prototype"in N&&N.prototype.render?u.__c=v=new N(_,P):(u.__c=v=new m(_,P),v.constructor=N,v.render=H),C&&C.sub(v),v.props=_,v.state||(v.state={}),v.context=P,v.__n=i,p=v.__d=!0,v.__h=[]),null==v.__s&&(v.__s=v.state),null!=N.getDerivedStateFromProps&&s(v.__s==v.state?v.__s=s({},v.__s):v.__s,N.getDerivedStateFromProps(_,v.__s)),p){ null==N.getDerivedStateFromProps&&null!=v.componentWillMount&&v.componentWillMount(),null!=v.componentDidMount&&f.push(v); }else{if(null==N.getDerivedStateFromProps&&null==e&&null!=v.componentWillReceiveProps&&v.componentWillReceiveProps(_,P),!e&&null!=v.shouldComponentUpdate&&!1===v.shouldComponentUpdate(_,v.__s,P)){for(v.props=_,v.state=v.__s,v.__d=!1,v.__v=u,u.__e=null!=c?c!==t.__e?c:t.__e:null,u.__k=t.__k,h=0;h<u.__k.length;h++){ u.__k[h]&&(u.__k[h].__p=u); }break n}null!=v.componentWillUpdate&&v.componentWillUpdate(_,v.__s,P);}for(y=v.props,w=v.state,v.context=P,v.props=_,v.state=v.__s,(h=n.__r)&&h(u),v.__d=!1,v.__v=u,v.__P=l,h=v.render(v.props,v.state,v.context),u.__k=x(null!=h&&h.type==d&&null==h.key?h.props.children:h),null!=v.getChildContext&&(i=s(s({},i),v.getChildContext())),p||null==v.getSnapshotBeforeUpdate||(g=v.getSnapshotBeforeUpdate(y,w)),b(l,u,t,i,r,o,f,c,a),v.base=u.__e;h=v.__h.pop();){ v.__s&&(v.state=v.__s),h.call(v); }p||null==y||null==v.componentDidUpdate||v.componentDidUpdate(y,w,g),k&&(v.__E=v.__p=null);}else { u.__e=z(t.__e,u,t,i,r,o,f,a); }(h=n.diffed)&&h(u);}catch(l){n.__e(l,u,t);}return u.__e}function j(l,u){for(var t;t=l.pop();){ try{t.componentDidMount();}catch(l){n.__e(l,t.__v);} }n.__c&&n.__c(u);}function z(n,l,u,t,i,r,o,c){var s,a,h,v,p=u.props,d=l.props;if(i="svg"===l.type||i,null==n&&null!=r){ for(s=0;s<r.length;s++){ if(null!=(a=r[s])&&(null===l.type?3===a.nodeType:a.localName===l.type)){n=a,r[s]=null;break} } }if(null==n){if(null===l.type){ return document.createTextNode(d); }n=i?document.createElementNS("http://www.w3.org/2000/svg",l.type):document.createElement(l.type),r=null;}return null===l.type?p!==d&&(null!=r&&(r[r.indexOf(n)]=null),n.data=d):l!==u&&(null!=r&&(r=e.slice.call(n.childNodes)),h=(p=u.props||f).dangerouslySetInnerHTML,v=d.dangerouslySetInnerHTML,c||(v||h)&&(v&&h&&v.__html==h.__html||(n.innerHTML=v&&v.__html||"")),C(n,d,p,i,c),l.__k=l.props.children,v||b(n,l,u,t,"foreignObject"!==l.type&&i,r,o,f,c),c||("value"in d&&void 0!==d.value&&d.value!==n.value&&(n.value=null==d.value?"":d.value),"checked"in d&&void 0!==d.checked&&d.checked!==n.checked&&(n.checked=d.checked))),n}function A(l,u,t){try{"function"==typeof l?l(u):l.current=u;}catch(l){n.__e(l,t);}}function D(l,u,t){var i,r,o;if(n.unmount&&n.unmount(l),(i=l.ref)&&A(i,null,u),t||"function"==typeof l.type||(t=null!=(r=l.__e)),l.__e=l.l=null,null!=(i=l.__c)){if(i.componentWillUnmount){ try{i.componentWillUnmount();}catch(l){n.__e(l,u);} }i.base=i.__P=null;}if(i=l.__k){ for(o=0;o<i.length;o++){ i[o]&&D(i[o],u,t); } }null!=r&&a(r);}function H(n,l,u){return this.constructor(n,u)}function I(l,u,t){var i,o,c;n.__p&&n.__p(l,u),o=(i=t===r)?null:t&&t.__k||u.__k,l=h(d,null,[l]),c=[],iro_es_$(u,i?u.__k=l:(t||u).__k=l,o||f,f,void 0!==u.ownerSVGElement,t&&!i?[t]:o?null:e.slice.call(u.childNodes),c,!1,t||f,i),j(c,l);}n={},m.prototype.setState=function(n,l){var u=this.__s!==this.state&&this.__s||(this.__s=s({},this.state));("function"!=typeof n||(n=n(u,this.props)))&&s(u,n),null!=n&&this.__v&&(this.u=!1,l&&this.__h.push(l),k(this));},m.prototype.forceUpdate=function(n){this.__v&&(n&&this.__h.push(n),this.u=!0,k(this));},m.prototype.render=d,u=[],t="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,i=n.debounceRendering,n.__e=function(n,l,u){for(var t;l=l.__p;){ if((t=l.__c)&&!t.__p){ try{if(t.constructor&&null!=t.constructor.getDerivedStateFromError){ t.setState(t.constructor.getDerivedStateFromError(n)); }else{if(null==t.componentDidCatch){ continue; }t.componentDidCatch(n);}return k(t.__E=t)}catch(l){n=l;} } }throw n},r=f,o=0;

function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) { descriptor.writable = true; }
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) { _defineProperties(Constructor.prototype, protoProps); }
  if (staticProps) { _defineProperties(Constructor, staticProps); }
  return Constructor;
}

function _extends() {
  _extends = Object.assign || function (target) {
    var arguments$1 = arguments;

    for (var i = 1; i < arguments.length; i++) {
      var source = arguments$1[i];

      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }

    return target;
  };

  return _extends.apply(this, arguments);
}

// Some regular expressions for rgb() and hsl() Colors are borrowed from tinyColor
// https://github.com/bgrins/TinyColor
// Kelvin temperature math borrowed from Neil Barlett's implementation
// from https://github.com/neilbartlett/color-temperature
// https://www.w3.org/TR/css3-values/#integers
var CSS_INTEGER = '[-\\+]?\\d+%?'; // http://www.w3.org/TR/css3-values/#number-value

var CSS_NUMBER = '[-\\+]?\\d*\\.\\d+%?'; // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome

var CSS_UNIT = '(?:' + CSS_NUMBER + ')|(?:' + CSS_INTEGER + ')'; // Parse function params
// Parens and commas are optional, and this also allows for whitespace between numbers

var PERMISSIVE_MATCH_3 = '[\\s|\\(]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')\\s*\\)?';
var PERMISSIVE_MATCH_4 = '[\\s|\\(]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')[,|\\s]+(' + CSS_UNIT + ')\\s*\\)?'; // Regex patterns for functional color strings

var REGEX_FUNCTIONAL_RGB = new RegExp('rgb' + PERMISSIVE_MATCH_3);
var REGEX_FUNCTIONAL_RGBA = new RegExp('rgba' + PERMISSIVE_MATCH_4);
var REGEX_FUNCTIONAL_HSL = new RegExp('hsl' + PERMISSIVE_MATCH_3);
var REGEX_FUNCTIONAL_HSLA = new RegExp('hsla' + PERMISSIVE_MATCH_4); // Color string parsing regex

var HEX_START = '^(?:#?|0x?)';
var HEX_INT_SINGLE = '([0-9a-fA-F]{1})';
var HEX_INT_DOUBLE = '([0-9a-fA-F]{2})';
var REGEX_HEX_3 = new RegExp(HEX_START + HEX_INT_SINGLE + HEX_INT_SINGLE + HEX_INT_SINGLE + '$');
var REGEX_HEX_4 = new RegExp(HEX_START + HEX_INT_SINGLE + HEX_INT_SINGLE + HEX_INT_SINGLE + HEX_INT_SINGLE + '$');
var REGEX_HEX_6 = new RegExp(HEX_START + HEX_INT_DOUBLE + HEX_INT_DOUBLE + HEX_INT_DOUBLE + '$');
var REGEX_HEX_8 = new RegExp(HEX_START + HEX_INT_DOUBLE + HEX_INT_DOUBLE + HEX_INT_DOUBLE + HEX_INT_DOUBLE + '$'); // Kelvin temperature bounds

var KELVIN_MIN = 2000;
var KELVIN_MAX = 40000; // Math shorthands

var log = Math.log,
    round = Math.round,
    floor = Math.floor;
/**
 * @desc Clamp a number between a min and max value
 * @param num - input value
 * @param min - min allowed value
 * @param max - max allowed value
 */

function clamp(num, min, max) {
  return Math.min(Math.max(num, min), max);
}
/**
 * @desc Parse a css unit string - either regular int or a percentage number
 * @param str - css unit string
 * @param max - max unit value, used for calculating percentages
 */


function parseUnit(str, max) {
  var isPercentage = str.indexOf('%') > -1;
  var num = parseFloat(str);
  return isPercentage ? max / 100 * num : num;
}
/**
 * @desc Parse hex str to an int
 * @param str - hex string to parse
 */


function parseHexInt(str) {
  return parseInt(str, 16);
}
/**
 * @desc Convert nunber into to 2-digit hex
 * @param int - number to convert
 */


function intToHex(_int) {
  return _int.toString(16).padStart(2, '0');
}

var IroColor =
/*#__PURE__*/
function () {
  /**
    * @constructor Color object
    * @param value - initial color value
  */
  function IroColor(value, onChange) {
    // The default Color value
    this.$ = {
      h: 0,
      s: 0,
      v: 0,
      a: 1
    };
    if (value) { this.set(value); } // The watch callback function for this Color will be stored here

    this.onChange = onChange;
    this.initialValue = _extends({}, this.$); // copy initial value
  }
  /**
    * @desc Set the Color from any valid value
    * @param value - new color value
  */


  var _proto = IroColor.prototype;

  _proto.set = function set(value) {
    if (typeof value === 'string') {
      if (/^(?:#?|0x?)[0-9a-fA-F]{3,8}$/.test(value)) {
        this.hexString = value;
      } else if (/^rgba?/.test(value)) {
        this.rgbString = value;
      } else if (/^hsla?/.test(value)) {
        this.hslString = value;
      }
    } else if (typeof value === 'object') {
      if (value instanceof IroColor) {
        this.hsva = value.hsva;
      } else if ('r' in value && 'g' in value && 'b' in value) {
        this.rgb = value;
      } else if ('h' in value && 's' in value && 'v' in value) {
        this.hsv = value;
      } else if ('h' in value && 's' in value && 'l' in value) {
        this.hsl = value;
      } else if ('kelvin' in value) {
        this.kelvin = value.kelvin;
      }
    } else {
      throw new Error('Invalid color value');
    }
  }
  /**
    * @desc Shortcut to set a specific channel value
    * @param format - hsv | hsl | rgb
    * @param channel - individual channel to set, for example if model = hsl, chanel = h | s | l
    * @param value - new value for the channel
  */
  ;

  _proto.setChannel = function setChannel(format, channel, value) {
    var _extends2;

    this[format] = _extends({}, this[format], (_extends2 = {}, _extends2[channel] = value, _extends2));
  }
  /**
   * @desc Reset color back to its initial value
   */
  ;

  _proto.reset = function reset() {
    this.hsva = this.initialValue;
  }
  /**
    * @desc make new Color instance with the same value as this one
  */
  ;

  _proto.clone = function clone() {
    return new IroColor(this);
  }
  /**
   * @desc remove color onChange
   */
  ;

  _proto.unbind = function unbind() {
    this.onChange = undefined;
  }
  /**
    * @desc Convert hsv object to rgb
    * @param hsv - hsv color object
  */
  ;

  IroColor.hsvToRgb = function hsvToRgb(hsv) {
    var h = hsv.h / 60;
    var s = hsv.s / 100;
    var v = hsv.v / 100;
    var i = floor(h);
    var f = h - i;
    var p = v * (1 - s);
    var q = v * (1 - f * s);
    var t = v * (1 - (1 - f) * s);
    var mod = i % 6;
    var r = [v, q, p, p, t, v][mod];
    var g = [t, v, v, q, p, p][mod];
    var b = [p, p, t, v, v, q][mod];
    return {
      r: clamp(r * 255, 0, 255),
      g: clamp(g * 255, 0, 255),
      b: clamp(b * 255, 0, 255)
    };
  }
  /**
    * @desc Convert rgb object to hsv
    * @param rgb - rgb object
  */
  ;

  IroColor.rgbToHsv = function rgbToHsv(rgb) {
    var r = rgb.r / 255;
    var g = rgb.g / 255;
    var b = rgb.b / 255;
    var max = Math.max(r, g, b);
    var min = Math.min(r, g, b);
    var delta = max - min;
    var hue = 0;
    var value = max;
    var saturation = max === 0 ? 0 : delta / max;

    switch (max) {
      case min:
        hue = 0; // achromatic

        break;

      case r:
        hue = (g - b) / delta + (g < b ? 6 : 0);
        break;

      case g:
        hue = (b - r) / delta + 2;
        break;

      case b:
        hue = (r - g) / delta + 4;
        break;
    }

    return {
      h: hue * 60 % 360,
      s: clamp(saturation * 100, 0, 100),
      v: clamp(value * 100, 0, 100)
    };
  }
  /**
    * @desc Convert hsv object to hsl
    * @param hsv - hsv object
  */
  ;

  IroColor.hsvToHsl = function hsvToHsl(hsv) {
    var s = hsv.s / 100;
    var v = hsv.v / 100;
    var l = (2 - s) * v;
    var divisor = l <= 1 ? l : 2 - l; // Avoid division by zero when lightness is close to zero

    var saturation = divisor < 1e-9 ? 0 : s * v / divisor;
    return {
      h: hsv.h,
      s: clamp(saturation * 100, 0, 100),
      l: clamp(l * 50, 0, 100)
    };
  }
  /**
    * @desc Convert hsl object to hsv
    * @param hsl - hsl object
  */
  ;

  IroColor.hslToHsv = function hslToHsv(hsl) {
    var l = hsl.l * 2;
    var s = hsl.s * (l <= 100 ? l : 200 - l) / 100; // Avoid division by zero when l + s is near 0

    var saturation = l + s < 1e-9 ? 0 : 2 * s / (l + s);
    return {
      h: hsl.h,
      s: clamp(saturation * 100, 0, 100),
      v: clamp((l + s) / 2, 0, 100)
    };
  }
  /**
    * @desc Convert a kelvin temperature to an approx, RGB value
    * @param kelvin - kelvin temperature
  */
  ;

  IroColor.kelvinToRgb = function kelvinToRgb(kelvin) {
    var temp = kelvin / 100;
    var r, g, b;

    if (temp < 66) {
      r = 255;
      g = -155.25485562709179 - 0.44596950469579133 * (g = temp - 2) + 104.49216199393888 * log(g);
      b = temp < 20 ? 0 : -254.76935184120902 + 0.8274096064007395 * (b = temp - 10) + 115.67994401066147 * log(b);
    } else {
      r = 351.97690566805693 + 0.114206453784165 * (r = temp - 55) - 40.25366309332127 * log(r);
      g = 325.4494125711974 + 0.07943456536662342 * (g = temp - 50) - 28.0852963507957 * log(g);
      b = 255;
    }

    return {
      r: clamp(floor(r), 0, 255),
      g: clamp(floor(g), 0, 255),
      b: clamp(floor(b), 0, 255)
    };
  }
  /**
   * @desc Convert an RGB color to an approximate kelvin temperature
   * @param kelvin - kelvin temperature
  */
  ;

  IroColor.rgbToKelvin = function rgbToKelvin(rgb) {
    var r = rgb.r,
        b = rgb.b;
    var eps = 0.4;
    var minTemp = KELVIN_MIN;
    var maxTemp = KELVIN_MAX;
    var temp;

    while (maxTemp - minTemp > eps) {
      temp = (maxTemp + minTemp) * 0.5;

      var _rgb = IroColor.kelvinToRgb(temp);

      if (_rgb.b / _rgb.r >= b / r) {
        maxTemp = temp;
      } else {
        minTemp = temp;
      }
    }

    return temp;
  };

  _createClass(IroColor, [{
    key: "hsv",
    get: function get() {
      // value is cloned to allow changes to be made to the values before passing them back
      var value = this.$;
      return {
        h: value.h,
        s: value.s,
        v: value.v
      };
    },
    set: function set(newValue) {
      var oldValue = this.$;
      newValue = _extends({}, oldValue, newValue); // If this Color is being watched for changes we need to compare the new and old values to check the difference
      // Otherwise we can just be lazy

      if (this.onChange) {
        // Compute changed values
        var changes = {
          h: false,
          v: false,
          s: false,
          a: false
        };

        for (var key in oldValue) {
          changes[key] = newValue[key] != oldValue[key];
        }

        this.$ = newValue; // If the value has changed, call hook callback

        if (changes.h || changes.s || changes.v || changes.a) { this.onChange(this, changes); }
      } else {
        this.$ = newValue;
      }
    }
  }, {
    key: "hsva",
    get: function get() {
      return _extends({}, this.$);
    },
    set: function set(value) {
      this.hsv = value;
    }
  }, {
    key: "hue",
    get: function get() {
      return this.$.h;
    },
    set: function set(value) {
      this.hsv = {
        h: value
      };
    }
  }, {
    key: "saturation",
    get: function get() {
      return this.$.s;
    },
    set: function set(value) {
      this.hsv = {
        s: value
      };
    }
  }, {
    key: "value",
    get: function get() {
      return this.$.v;
    },
    set: function set(value) {
      this.hsv = {
        v: value
      };
    }
  }, {
    key: "alpha",
    get: function get() {
      return this.$.a;
    },
    set: function set(value) {
      this.hsv = _extends({}, this.hsv, {
        a: value
      });
    }
  }, {
    key: "kelvin",
    get: function get() {
      return IroColor.rgbToKelvin(this.rgb);
    },
    set: function set(value) {
      this.rgb = IroColor.kelvinToRgb(value);
    }
  }, {
    key: "red",
    get: function get() {
      var rgb = this.rgb;
      return rgb.r;
    },
    set: function set(value) {
      this.rgb = _extends({}, this.rgb, {
        r: value
      });
    }
  }, {
    key: "green",
    get: function get() {
      var rgb = this.rgb;
      return rgb.g;
    },
    set: function set(value) {
      this.rgb = _extends({}, this.rgb, {
        g: value
      });
    }
  }, {
    key: "blue",
    get: function get() {
      var rgb = this.rgb;
      return rgb.b;
    },
    set: function set(value) {
      this.rgb = _extends({}, this.rgb, {
        b: value
      });
    }
  }, {
    key: "rgb",
    get: function get() {
      var _IroColor$hsvToRgb = IroColor.hsvToRgb(this.$),
          r = _IroColor$hsvToRgb.r,
          g = _IroColor$hsvToRgb.g,
          b = _IroColor$hsvToRgb.b;

      return {
        r: round(r),
        g: round(g),
        b: round(b)
      };
    },
    set: function set(value) {
      this.hsv = _extends({}, IroColor.rgbToHsv(value), {
        a: value.a === undefined ? 1 : value.a
      });
    }
  }, {
    key: "rgba",
    get: function get() {
      return _extends({}, this.rgb, {
        a: this.alpha
      });
    },
    set: function set(value) {
      this.rgb = value;
    }
  }, {
    key: "hsl",
    get: function get() {
      var _IroColor$hsvToHsl = IroColor.hsvToHsl(this.$),
          h = _IroColor$hsvToHsl.h,
          s = _IroColor$hsvToHsl.s,
          l = _IroColor$hsvToHsl.l;

      return {
        h: round(h),
        s: round(s),
        l: round(l)
      };
    },
    set: function set(value) {
      this.hsv = _extends({}, IroColor.hslToHsv(value), {
        a: value.a === undefined ? 1 : value.a
      });
    }
  }, {
    key: "hsla",
    get: function get() {
      return _extends({}, this.hsl, {
        a: this.alpha
      });
    },
    set: function set(value) {
      this.hsl = value;
    }
  }, {
    key: "rgbString",
    get: function get() {
      var rgb = this.rgb;
      return "rgb(" + rgb.r + ", " + rgb.g + ", " + rgb.b + ")";
    },
    set: function set(value) {
      var match;
      var r,
          g,
          b,
          a = 1;

      if (match = REGEX_FUNCTIONAL_RGB.exec(value)) {
        r = parseUnit(match[1], 255);
        g = parseUnit(match[2], 255);
        b = parseUnit(match[3], 255);
      } else if (match = REGEX_FUNCTIONAL_RGBA.exec(value)) {
        r = parseUnit(match[1], 255);
        g = parseUnit(match[2], 255);
        b = parseUnit(match[3], 255);
        a = parseUnit(match[4], 1);
      }

      if (match) {
        this.rgb = {
          r: r,
          g: g,
          b: b,
          a: a
        };
      } else {
        throw new Error('Invalid rgb string');
      }
    }
  }, {
    key: "rgbaString",
    get: function get() {
      var rgba = this.rgba;
      return "rgba(" + rgba.r + ", " + rgba.g + ", " + rgba.b + ", " + rgba.a + ")";
    },
    set: function set(value) {
      this.rgbString = value;
    }
  }, {
    key: "hexString",
    get: function get() {
      var rgb = this.rgb;
      return "#" + intToHex(rgb.r) + intToHex(rgb.g) + intToHex(rgb.b);
    },
    set: function set(value) {
      var match;
      var r,
          g,
          b,
          a = 255;

      if (match = REGEX_HEX_3.exec(value)) {
        r = parseHexInt(match[1]) * 17;
        g = parseHexInt(match[2]) * 17;
        b = parseHexInt(match[3]) * 17;
      } else if (match = REGEX_HEX_4.exec(value)) {
        r = parseHexInt(match[1]) * 17;
        g = parseHexInt(match[2]) * 17;
        b = parseHexInt(match[3]) * 17;
        a = parseHexInt(match[4]) * 17;
      } else if (match = REGEX_HEX_6.exec(value)) {
        r = parseHexInt(match[1]);
        g = parseHexInt(match[2]);
        b = parseHexInt(match[3]);
      } else if (match = REGEX_HEX_8.exec(value)) {
        r = parseHexInt(match[1]);
        g = parseHexInt(match[2]);
        b = parseHexInt(match[3]);
        a = parseHexInt(match[4]);
      }

      if (match) {
        this.rgb = {
          r: r,
          g: g,
          b: b,
          a: a / 255
        };
      } else {
        throw new Error('Invalid hex string');
      }
    }
  }, {
    key: "hex8String",
    get: function get() {
      var rgba = this.rgba;
      return "#" + intToHex(rgba.r) + intToHex(rgba.g) + intToHex(rgba.b) + intToHex(floor(rgba.a * 255));
    },
    set: function set(value) {
      this.hexString = value;
    }
  }, {
    key: "hslString",
    get: function get() {
      var hsl = this.hsl;
      return "hsl(" + hsl.h + ", " + hsl.s + "%, " + hsl.l + "%)";
    },
    set: function set(value) {
      var match;
      var h,
          s,
          l,
          a = 1;

      if (match = REGEX_FUNCTIONAL_HSL.exec(value)) {
        h = parseUnit(match[1], 360);
        s = parseUnit(match[2], 100);
        l = parseUnit(match[3], 100);
      } else if (match = REGEX_FUNCTIONAL_HSLA.exec(value)) {
        h = parseUnit(match[1], 360);
        s = parseUnit(match[2], 100);
        l = parseUnit(match[3], 100);
        a = parseUnit(match[4], 1);
      }

      if (match) {
        this.hsl = {
          h: h,
          s: s,
          l: l,
          a: a
        };
      } else {
        throw new Error('Invalid hsl string');
      }
    }
  }, {
    key: "hslaString",
    get: function get() {
      var hsla = this.hsla;
      return "hsla(" + hsla.h + ", " + hsla.s + "%, " + hsla.l + "%, " + hsla.a + ")";
    },
    set: function set(value) {
      this.hslString = value;
    }
  }]);

  return IroColor;
}();

var sliderDefaultOptions = {
  sliderShape: 'bar',
  sliderType: 'value',
  minTemperature: 2200,
  maxTemperature: 11000
};
/**
 * @desc Get the bounding dimensions of the slider
 * @param props - slider props
 */

function getSliderDimensions(props) {
  var _sliderSize;

  var width = props.width,
      sliderSize = props.sliderSize,
      borderWidth = props.borderWidth,
      handleRadius = props.handleRadius,
      padding = props.padding,
      sliderShape = props.sliderShape;
  var ishorizontal = props.layoutDirection === 'horizontal'; // automatically calculate sliderSize if its not defined

  sliderSize = (_sliderSize = sliderSize) != null ? _sliderSize : padding * 2 + handleRadius * 2;

  if (sliderShape === 'circle') {
    return {
      handleStart: props.padding + props.handleRadius,
      handleRange: width - padding * 2 - handleRadius * 2,
      width: width,
      height: width,
      cx: width / 2,
      cy: width / 2,
      radius: width / 2 - borderWidth / 2
    };
  } else {
    return {
      handleStart: sliderSize / 2,
      handleRange: width - sliderSize,
      radius: sliderSize / 2,
      x: 0,
      y: 0,
      width: ishorizontal ? sliderSize : width,
      height: ishorizontal ? width : sliderSize
    };
  }
}
/**
 * @desc Get the current slider value for a given color, as a percentage
 * @param props - slider props
 * @param color
 */

function getCurrentSliderValue(props, color) {
  var hsva = color.hsva;
  var rgb = color.rgb;

  switch (props.sliderType) {
    case 'red':
      return rgb.r / 2.55;

    case 'green':
      return rgb.g / 2.55;

    case 'blue':
      return rgb.b / 2.55;

    case 'alpha':
      return hsva.a * 100;

    case 'kelvin':
      var minTemperature = props.minTemperature,
          maxTemperature = props.maxTemperature;
      var temperatureRange = maxTemperature - minTemperature;
      var percent = (color.kelvin - minTemperature) / temperatureRange * 100; // clmap percentage

      return Math.max(0, Math.min(percent, 100));

    case 'hue':
      return hsva.h /= 3.6;

    case 'saturation':
      return hsva.s;

    case 'value':
    default:
      return hsva.v;
  }
}
/**
 * @desc Get the current slider value from user input
 * @param props - slider props
 * @param x - global input x position
 * @param y - global input y position
 */

function getSliderValueFromInput(props, x, y) {
  var _getSliderDimensions = getSliderDimensions(props),
      handleRange = _getSliderDimensions.handleRange,
      handleStart = _getSliderDimensions.handleStart;

  var handlePos;

  if (props.layoutDirection === 'horizontal') {
    handlePos = -1 * y + handleRange + handleStart;
  } else {
    handlePos = x - handleStart;
  } // clamp handle position


  handlePos = Math.max(Math.min(handlePos, handleRange), 0);
  var percent = Math.round(100 / handleRange * handlePos);

  switch (props.sliderType) {
    case 'kelvin':
      var minTemperature = props.minTemperature,
          maxTemperature = props.maxTemperature;
      var temperatureRange = maxTemperature - minTemperature;
      return minTemperature + temperatureRange * (percent / 100);

    case 'alpha':
      return percent / 100;

    case 'hue':
      return percent * 3.6;

    case 'red':
    case 'blue':
    case 'green':
      return percent * 2.55;

    default:
      return percent;
  }
}
/**
 * @desc Get the current handle position for a given color
 * @param props - slider props
 * @param color
 */

function getSliderHandlePosition(props, color) {
  var _getSliderDimensions2 = getSliderDimensions(props),
      width = _getSliderDimensions2.width,
      height = _getSliderDimensions2.height,
      handleRange = _getSliderDimensions2.handleRange,
      handleStart = _getSliderDimensions2.handleStart;

  var ishorizontal = props.layoutDirection === 'horizontal';
  var sliderValue = getCurrentSliderValue(props, color);
  var midPoint = ishorizontal ? width / 2 : height / 2;
  var handlePos = handleStart + sliderValue / 100 * handleRange;

  if (ishorizontal) {
    handlePos = -1 * handlePos + handleRange + handleStart * 2;
  }

  return {
    x: ishorizontal ? midPoint : handlePos,
    y: ishorizontal ? handlePos : midPoint
  };
}
/**
 * @desc Get the gradient stops for a slider
 * @param props - slider props
 * @param color
 */

function getSliderGradient(props, color) {
  var hsv = color.hsv;
  var rgb = color.rgb;

  switch (props.sliderType) {
    case 'red':
      return [[0, "rgb(" + 0 + "," + rgb.g + "," + rgb.b + ")"], [100, "rgb(" + 255 + "," + rgb.g + "," + rgb.b + ")"]];

    case 'green':
      return [[0, "rgb(" + rgb.r + "," + 0 + "," + rgb.b + ")"], [100, "rgb(" + rgb.r + "," + 255 + "," + rgb.b + ")"]];

    case 'blue':
      return [[0, "rgb(" + rgb.r + "," + rgb.g + "," + 0 + ")"], [100, "rgb(" + rgb.r + "," + rgb.g + "," + 255 + ")"]];

    case 'alpha':
      return [[0, "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + ",0)"], [100, "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")"]];

    case 'kelvin':
      var stops = [];
      var min = props.minTemperature;
      var max = props.maxTemperature;
      var numStops = 8;
      var range = max - min;

      for (var kelvin = min, stop = 0; kelvin < max; kelvin += range / numStops, stop += 1) {
        var _IroColor$kelvinToRgb = IroColor.kelvinToRgb(kelvin),
            r = _IroColor$kelvinToRgb.r,
            g = _IroColor$kelvinToRgb.g,
            b = _IroColor$kelvinToRgb.b;

        stops.push([100 / numStops * stop, "rgb(" + r + "," + g + "," + b + ")"]);
      }

      return stops;

    case 'hue':
      return [[0, '#f00'], [16.666, '#ff0'], [33.333, '#0f0'], [50, '#0ff'], [66.666, '#00f'], [83.333, '#f0f'], [100, '#f00']];

    case 'saturation':
      var noSat = IroColor.hsvToHsl({
        h: hsv.h,
        s: 0,
        v: hsv.v
      });
      var fullSat = IroColor.hsvToHsl({
        h: hsv.h,
        s: 100,
        v: hsv.v
      });
      return [[0, "hsl(" + noSat.h + "," + noSat.s + "%," + noSat.l + "%)"], [100, "hsl(" + fullSat.h + "," + fullSat.s + "%," + fullSat.l + "%)"]];

    case 'value':
    default:
      var hsl = IroColor.hsvToHsl({
        h: hsv.h,
        s: hsv.s,
        v: 100
      });
      return [[0, '#000'], [100, "hsl(" + hsl.h + "," + hsl.s + "%," + hsl.l + "%)"]];
  }
}

var TAU = Math.PI * 2; // javascript's modulo operator doesn't produce positive numbers with negative input
// https://dev.to/maurobringolf/a-neat-trick-to-compute-modulo-of-negative-numbers-111e

var mod = function mod(a, n) {
  return (a % n + n) % n;
}; // distance between points (x, y) and (0, 0)


var dist = function dist(x, y) {
  return Math.sqrt(x * x + y * y);
};
/**
 * @param props - wheel props
 * @internal
 */


function getHandleRange(props) {
  return props.width / 2 - props.padding - props.handleRadius - props.borderWidth;
}
/**
 * Returns true if point (x, y) lands inside the wheel
 * @param props - wheel props
 * @param x
 * @param y
 */


function isInputInsideWheel(props, x, y) {
  var _getWheelDimensions = getWheelDimensions(props),
      cx = _getWheelDimensions.cx,
      cy = _getWheelDimensions.cy;

  var r = props.width / 2;
  return dist(cx - x, cy - y) < r;
}
/**
 * @desc Get the point as the center of the wheel
 * @param props - wheel props
 */

function getWheelDimensions(props) {
  var r = props.width / 2;
  return {
    width: props.width,
    radius: r - props.borderWidth,
    cx: r,
    cy: r
  };
}
/**
 * @desc Translate an angle according to wheelAngle and wheelDirection
 * @param props - wheel props
 * @param angle - input angle
 */

function translateWheelAngle(props, angle, invert) {
  var wheelAngle = props.wheelAngle;
  var wheelDirection = props.wheelDirection; // inverted and clockwisee

  if (invert && wheelDirection === 'clockwise') { angle = wheelAngle + angle; } // clockwise (input handling)
  else if (wheelDirection === 'clockwise') { angle = 360 - wheelAngle + angle; } // inverted and anticlockwise
    else if (invert && wheelDirection === 'anticlockwise') { angle = wheelAngle + 180 - angle; } // anticlockwise (input handling)
      else if (wheelDirection === 'anticlockwise') { angle = wheelAngle - angle; }
  return mod(angle, 360);
}
/**
 * @desc Get the current handle position for a given color
 * @param props - wheel props
 * @param color
 */

function getWheelHandlePosition(props, color) {
  var hsv = color.hsv;

  var _getWheelDimensions2 = getWheelDimensions(props),
      cx = _getWheelDimensions2.cx,
      cy = _getWheelDimensions2.cy;

  var handleRange = getHandleRange(props);
  var handleAngle = (180 + translateWheelAngle(props, hsv.h, true)) * (TAU / 360);
  var handleDist = hsv.s / 100 * handleRange;
  var direction = props.wheelDirection === 'clockwise' ? -1 : 1;
  return {
    x: cx + handleDist * Math.cos(handleAngle) * direction,
    y: cy + handleDist * Math.sin(handleAngle) * direction
  };
}
/**
 * @desc Get the current wheel value from user input
 * @param props - wheel props
 * @param x - global input x position
 * @param y - global input y position
 */

function getWheelValueFromInput(props, x, y) {
  var _getWheelDimensions3 = getWheelDimensions(props),
      cx = _getWheelDimensions3.cx,
      cy = _getWheelDimensions3.cy;

  var handleRange = getHandleRange(props);
  x = cx - x;
  y = cy - y; // Calculate the hue by converting the angle to radians

  var hue = translateWheelAngle(props, Math.atan2(-y, -x) * (360 / TAU)); // Find the point's distance from the center of the wheel
  // This is used to show the saturation level

  var handleDist = Math.min(dist(x, y), handleRange);
  return {
    h: Math.round(hue),
    s: Math.round(100 / handleRange * handleDist)
  };
}
/**
 * @desc Get the bounding dimensions of the box
 * @param props - box props
 */

function getBoxDimensions(props) {
  var width = props.width,
      boxHeight = props.boxHeight,
      padding = props.padding,
      handleRadius = props.handleRadius;
  return {
    width: width,
    height: boxHeight != null ? boxHeight : width,
    radius: padding + handleRadius
  };
}
/**
 * @desc Get the current box value from user input
 * @param props - box props
 * @param x - global input x position
 * @param y - global input y position
 */

function getBoxValueFromInput(props, x, y) {
  var _getBoxDimensions = getBoxDimensions(props),
      width = _getBoxDimensions.width,
      height = _getBoxDimensions.height,
      radius = _getBoxDimensions.radius;

  var handleStart = radius;
  var handleRangeX = width - radius * 2;
  var handleRangeY = height - radius * 2;
  var percentX = (x - handleStart) / handleRangeX * 100;
  var percentY = (y - handleStart) / handleRangeY * 100;
  return {
    s: Math.max(0, Math.min(percentX, 100)),
    v: Math.max(0, Math.min(100 - percentY, 100))
  };
}
/**
 * @desc Get the current box handle position for a given color
 * @param props - box props
 * @param color
 */

function getBoxHandlePosition(props, color) {
  var _getBoxDimensions2 = getBoxDimensions(props),
      width = _getBoxDimensions2.width,
      height = _getBoxDimensions2.height,
      radius = _getBoxDimensions2.radius;

  var hsv = color.hsv;
  var handleStart = radius;
  var handleRangeX = width - radius * 2;
  var handleRangeY = height - radius * 2;
  return {
    x: handleStart + hsv.s / 100 * handleRangeX,
    y: handleStart + (handleRangeY - hsv.v / 100 * handleRangeY)
  };
}
/**
 * @desc Get the gradient stops for a box
 * @param props - box props
 * @param color
 */

function getBoxGradients(props, color) {
  var hue = color.hue;
  return [// saturation gradient
  [[0, '#fff'], [100, "hsl(" + hue + ",100%,50%)"]], // lightness gradient
  [[0, 'rgba(0,0,0,0)'], [100, '#000']]];
}

// Keep track of html <base> elements for resolveSvgUrl
// getElementsByTagName returns a live HTMLCollection, which stays in sync with the DOM tree
// So it only needs to be called once
var BASE_ELEMENTS;
/**
 * @desc Resolve an SVG reference URL
 * This is required to work around how Safari and iOS webviews handle gradient URLS under certain conditions
 * If a page is using a client-side routing library which makes use of the HTML <base> tag,
 * Safari won't be able to render SVG gradients properly (as they are referenced by URLs)
 * More info on the problem:
 * https://stackoverflow.com/questions/19742805/angular-and-svg-filters/19753427#19753427
 * https://github.com/jaames/iro.js/issues/18
 * https://github.com/jaames/iro.js/issues/45
 * https://github.com/jaames/iro.js/pull/89
 * @props url - SVG reference URL
 */

function resolveSvgUrl(url) {
  if (!BASE_ELEMENTS) { BASE_ELEMENTS = document.getElementsByTagName('base'); } // Sniff useragent string to check if the user is running Safari

  var ua = window.navigator.userAgent;
  var isSafari = /^((?!chrome|android).)*safari/i.test(ua);
  var isIos = /iPhone|iPod|iPad/i.test(ua);
  var location = window.location;
  return (isSafari || isIos) && BASE_ELEMENTS.length > 0 ? location.protocol + "//" + location.host + location.pathname + location.search + url : url;
}
/**
 * @desc Given a specifc (x, y) position, test if there's a handle there and return its index, else return null.
 *       This is used for components like the box and wheel which support multiple handles when multicolor is active
 * @props x - point x position
 * @props y - point y position
 * @props handlePositions - array of {x, y} coords for each handle
 */

function getHandleAtPoint(props, x, y, handlePositions) {
  for (var i = 0; i < handlePositions.length; i++) {
    var dX = handlePositions[i].x - x;
    var dY = handlePositions[i].y - y;
    var dist = Math.sqrt(dX * dX + dY * dY);

    if (dist < props.handleRadius) {
      return i;
    }
  }

  return null;
}

function cssBorderStyles(props) {
  return {
    boxSizing: 'border-box',
    border: props.borderWidth + "px solid " + props.borderColor
  };
}
function cssGradient(type, direction, stops) {
  return type + "-gradient(" + direction + ", " + stops.map(function (_ref) {
    var o = _ref[0],
        col = _ref[1];
    return col + " " + o + "%";
  }).join(',') + ")";
}
function cssValue(value) {
  if (typeof value === 'string') { return value; }
  return value + "px";
}

var iroColorPickerOptionDefaults = {
  width: 300,
  height: 300,
  color: '#fff',
  colors: [],
  padding: 6,
  layoutDirection: 'vertical',
  borderColor: '#fff',
  borderWidth: 0,
  handleRadius: 8,
  activeHandleRadius: null,
  handleSvg: null,
  handleProps: {
    x: 0,
    y: 0
  },
  wheelLightness: true,
  wheelAngle: 0,
  wheelDirection: 'anticlockwise',
  sliderSize: null,
  sliderMargin: 12,
  boxHeight: null
};

var SECONDARY_EVENTS = ["mousemove" /* MouseMove */, "touchmove" /* TouchMove */, "mouseup" /* MouseUp */, "touchend" /* TouchEnd */];
// Base component class for iro UI components
// This extends the Preact component class to allow them to react to mouse/touch input events by themselves
var IroComponentWrapper = /*@__PURE__*/(function (Component) {
    function IroComponentWrapper(props) {
        Component.call(this, props);
        // Generate unique ID for the component
        // This can be used to generate unique IDs for gradients, etc
        this.uid = (Math.random() + 1).toString(36).substring(5);
    }

    if ( Component ) IroComponentWrapper.__proto__ = Component;
    IroComponentWrapper.prototype = Object.create( Component && Component.prototype );
    IroComponentWrapper.prototype.constructor = IroComponentWrapper;
    IroComponentWrapper.prototype.render = function render (props) {
        var eventHandler = this.handleEvent.bind(this);
        var rootProps = {
            onMouseDown: eventHandler,
            // https://github.com/jaames/iro.js/issues/126
            // https://github.com/preactjs/preact/issues/2113#issuecomment-553408767
            ontouchstart: eventHandler,
        };
        var isHorizontal = props.layoutDirection === 'horizontal';
        var margin = props.margin === null ? props.sliderMargin : props.margin;
        var rootStyles = {
            overflow: 'visible',
            display: isHorizontal ? 'inline-block' : 'block'
        };
        // first component shouldn't have any margin
        if (props.index > 0) {
            rootStyles[isHorizontal ? 'marginLeft' : 'marginTop'] = margin;
        }
        return (h(d, null, props.children(this.uid, rootProps, rootStyles)));
    };
    // More info on handleEvent:
    // https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38
    // TL;DR this lets us have a single point of entry for multiple events, and we can avoid callback/binding hell
    IroComponentWrapper.prototype.handleEvent = function handleEvent (e) {
        var this$1 = this;

        var inputHandler = this.props.onInput;
        // Get the screen position of the component
        var bounds = this.base.getBoundingClientRect();
        // Prefect default browser action
        e.preventDefault();
        // Detect if the event is a touch event by checking if it has the `touches` property
        // If it is a touch event, use the first touch input
        var point = e.touches ? e.changedTouches[0] : e;
        var x = point.clientX - bounds.left;
        var y = point.clientY - bounds.top;
        switch (e.type) {
            case "mousedown" /* MouseDown */:
            case "touchstart" /* TouchStart */:
                var result = inputHandler(x, y, 0 /* Start */);
                if (result !== false) {
                    SECONDARY_EVENTS.forEach(function (event) {
                        document.addEventListener(event, this$1, { passive: false });
                    });
                }
                break;
            case "mousemove" /* MouseMove */:
            case "touchmove" /* TouchMove */:
                inputHandler(x, y, 1 /* Move */);
                break;
            case "mouseup" /* MouseUp */:
            case "touchend" /* TouchEnd */:
                inputHandler(x, y, 2 /* End */);
                SECONDARY_EVENTS.forEach(function (event) {
                    document.removeEventListener(event, this$1, { passive: false });
                });
                break;
        }
    };

    return IroComponentWrapper;
}(m));

function IroHandle(props) {
    var radius = props.r;
    var url = props.url;
    var cx = radius;
    var cy = radius;
    return (h("svg", { className: ("IroHandle IroHandle--" + (props.index) + " " + (props.isActive ? 'IroHandle--isActive' : '')), style: {
            '-webkit-tap-highlight-color': 'rgba(0, 0, 0, 0);',
            transform: ("translate(" + (cssValue(props.x)) + ", " + (cssValue(props.y)) + ")"),
            willChange: 'transform',
            top: cssValue(-radius),
            left: cssValue(-radius),
            width: cssValue(radius * 2),
            height: cssValue(radius * 2),
            position: 'absolute',
            overflow: 'visible'
        } },
        url && (h("use", Object.assign({ xlinkHref: resolveSvgUrl(url) }, props.props))),
        !url && (h("circle", { cx: cx, cy: cy, r: radius, fill: "none", "stroke-width": 2, stroke: "#000" })),
        !url && (h("circle", { cx: cx, cy: cy, r: radius - 2, fill: props.fill, "stroke-width": 2, stroke: "#fff" }))));
}
IroHandle.defaultProps = {
    fill: 'none',
    x: 0,
    y: 0,
    r: 8,
    url: null,
    props: { x: 0, y: 0 }
};

function IroSlider(props) {
    var activeIndex = props.activeIndex;
    var activeColor = (activeIndex !== undefined && activeIndex < props.colors.length) ? props.colors[activeIndex] : props.color;
    var ref = getSliderDimensions(props);
    var width = ref.width;
    var height = ref.height;
    var radius = ref.radius;
    var handlePos = getSliderHandlePosition(props, activeColor);
    var gradient = getSliderGradient(props, activeColor);
    function handleInput(x, y, type) {
        var value = getSliderValueFromInput(props, x, y);
        props.parent.inputActive = true;
        activeColor[props.sliderType] = value;
        props.onInput(type, props.id);
    }
    return (h(IroComponentWrapper, Object.assign({}, props, { onInput: handleInput }), function (uid, rootProps, rootStyles) { return (h("div", Object.assign({}, rootProps, { className: "IroSlider", style: Object.assign({}, {position: 'relative',
            width: cssValue(width),
            height: cssValue(height),
            borderRadius: cssValue(radius),
            // checkered bg to represent alpha
            background: "conic-gradient(#ccc 25%, #fff 0 50%, #ccc 0 75%, #fff 0)",
            backgroundSize: '8px 8px'},
            rootStyles) }),
        h("div", { className: "IroSliderGradient", style: Object.assign({}, {position: 'absolute',
                top: 0,
                left: 0,
                width: "100%",
                height: "100%",
                borderRadius: cssValue(radius),
                background: cssGradient('linear', props.layoutDirection === 'horizontal' ? 'to top' : 'to right', gradient)},
                cssBorderStyles(props)) }),
        h(IroHandle, { isActive: true, index: activeColor.index, r: props.handleRadius, url: props.handleSvg, props: props.handleProps, x: handlePos.x, y: handlePos.y }))); }));
}
IroSlider.defaultProps = Object.assign({}, sliderDefaultOptions);

function IroBox(props) {
    var ref = getBoxDimensions(props);
    var width = ref.width;
    var height = ref.height;
    var radius = ref.radius;
    var colors = props.colors;
    var colorPicker = props.parent;
    var activeIndex = props.activeIndex;
    var activeColor = (activeIndex !== undefined && activeIndex < props.colors.length) ? props.colors[activeIndex] : props.color;
    var gradients = getBoxGradients(props, activeColor);
    var handlePositions = colors.map(function (color) { return getBoxHandlePosition(props, color); });
    function handleInput(x, y, inputType) {
        if (inputType === 0 /* Start */) {
            // getHandleAtPoint() returns the index for the handle if the point 'hits' it, or null otherwise
            var activeHandle = getHandleAtPoint(props, x, y, handlePositions);
            // If the input hit a handle, set it as the active handle, but don't update the color
            if (activeHandle !== null) {
                colorPicker.setActiveColor(activeHandle);
            }
            // If the input didn't hit a handle, set the currently active handle to that position
            else {
                colorPicker.inputActive = true;
                activeColor.hsv = getBoxValueFromInput(props, x, y);
                props.onInput(inputType, props.id);
            }
        }
        // move is fired when the user has started dragging
        else if (inputType === 1 /* Move */) {
            colorPicker.inputActive = true;
            activeColor.hsv = getBoxValueFromInput(props, x, y);
        }
        // let the color picker fire input:start, input:move or input:end events
        props.onInput(inputType, props.id);
    }
    return (h(IroComponentWrapper, Object.assign({}, props, { onInput: handleInput }), function (uid, rootProps, rootStyles) { return (h("div", Object.assign({}, rootProps, { className: "IroBox", style: Object.assign({}, {width: cssValue(width),
            height: cssValue(height),
            position: 'relative'},
            rootStyles) }),
        h("div", { className: "IroBox", style: Object.assign({}, {width: '100%',
                height: '100%',
                borderRadius: cssValue(radius)},
                cssBorderStyles(props),
                {background: cssGradient('linear', 'to bottom', gradients[1])
                    + ',' +
                    cssGradient('linear', 'to right', gradients[0])}) }),
        colors.filter(function (color) { return color !== activeColor; }).map(function (color) { return (h(IroHandle, { isActive: false, index: color.index, fill: color.hslString, r: props.handleRadius, url: props.handleSvg, props: props.handleProps, x: handlePositions[color.index].x, y: handlePositions[color.index].y })); }),
        h(IroHandle, { isActive: true, index: activeColor.index, fill: activeColor.hslString, r: props.activeHandleRadius || props.handleRadius, url: props.handleSvg, props: props.handleProps, x: handlePositions[activeColor.index].x, y: handlePositions[activeColor.index].y }))); }));
}

var HUE_GRADIENT_CLOCKWISE = 'conic-gradient(red, yellow, lime, aqua, blue, magenta, red)';
var HUE_GRADIENT_ANTICLOCKWISE = 'conic-gradient(red, magenta, blue, aqua, lime, yellow, red)';
function IroWheel(props) {
    var ref = getWheelDimensions(props);
    var width = ref.width;
    var colors = props.colors;
    var borderWidth = props.borderWidth;
    var colorPicker = props.parent;
    var activeColor = props.color;
    var hsv = activeColor.hsv;
    var handlePositions = colors.map(function (color) { return getWheelHandlePosition(props, color); });
    var circleStyles = {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        borderRadius: '50%',
        boxSizing: 'border-box'
    };
    function handleInput(x, y, inputType) {
        if (inputType === 0 /* Start */) {
            // input hitbox is a square, 
            // so we want to ignore any initial clicks outside the circular shape of the wheel
            if (!isInputInsideWheel(props, x, y)) {
                // returning false will cease all event handling for this interaction
                return false;
            }
            // getHandleAtPoint() returns the index for the handle if the point 'hits' it, or null otherwise
            var activeHandle = getHandleAtPoint(props, x, y, handlePositions);
            // If the input hit a handle, set it as the active handle, but don't update the color
            if (activeHandle !== null) {
                colorPicker.setActiveColor(activeHandle);
            }
            // If the input didn't hit a handle, set the currently active handle to that position
            else {
                colorPicker.inputActive = true;
                activeColor.hsv = getWheelValueFromInput(props, x, y);
                props.onInput(inputType, props.id);
            }
        }
        // move is fired when the user has started dragging
        else if (inputType === 1 /* Move */) {
            colorPicker.inputActive = true;
            activeColor.hsv = getWheelValueFromInput(props, x, y);
        }
        // let the color picker fire input:start, input:move or input:end events
        props.onInput(inputType, props.id);
    }
    return (h(IroComponentWrapper, Object.assign({}, props, { onInput: handleInput }), function (uid, rootProps, rootStyles) { return (h("div", Object.assign({}, rootProps, { className: "IroWheel", style: Object.assign({}, {width: cssValue(width),
            height: cssValue(width),
            position: 'relative'},
            rootStyles) }),
        h("div", { className: "IroWheelHue", style: Object.assign({}, circleStyles,
                {transform: ("rotateZ(" + (props.wheelAngle + 90) + "deg)"),
                background: props.wheelDirection === 'clockwise' ? HUE_GRADIENT_CLOCKWISE : HUE_GRADIENT_ANTICLOCKWISE}) }),
        h("div", { className: "IroWheelSaturation", style: Object.assign({}, circleStyles,
                {background: 'radial-gradient(circle closest-side, #fff, transparent)'}) }),
        props.wheelLightness && (h("div", { className: "IroWheelLightness", style: Object.assign({}, circleStyles,
                {background: '#000',
                opacity: 1 - hsv.v / 100}) })),
        h("div", { className: "IroWheelBorder", style: Object.assign({}, circleStyles,
                cssBorderStyles(props)) }),
        colors.filter(function (color) { return color !== activeColor; }).map(function (color) { return (h(IroHandle, { isActive: false, index: color.index, fill: color.hslString, r: props.handleRadius, url: props.handleSvg, props: props.handleProps, x: handlePositions[color.index].x, y: handlePositions[color.index].y })); }),
        h(IroHandle, { isActive: true, index: activeColor.index, fill: activeColor.hslString, r: props.activeHandleRadius || props.handleRadius, url: props.handleSvg, props: props.handleProps, x: handlePositions[activeColor.index].x, y: handlePositions[activeColor.index].y }))); }));
}

function createWidget(WidgetComponent) {
    var widgetFactory = function (parent, props) {
        var widget; // will become an instance of the widget component class
        var widgetRoot = document.createElement('div');
        // Render widget into a temp DOM node
        I(h(WidgetComponent, Object.assign({}, {ref: function (ref) { return widget = ref; }},
            props)), widgetRoot);
        function mountWidget() {
            var container = parent instanceof Element ? parent : document.querySelector(parent);
            container.appendChild(widget.base);
            widget.onMount(container);
        }
        // Mount it into the DOM when the page document is ready
        if (document.readyState !== 'loading') {
            mountWidget();
        }
        else {
            document.addEventListener('DOMContentLoaded', mountWidget);
        }
        return widget;
    };
    // Allow the widget factory to inherit component prototype + static class methods
    // This makes it easier for plugin authors to extend the base widget component
    widgetFactory.prototype = WidgetComponent.prototype;
    Object.assign(widgetFactory, WidgetComponent);
    // Add reference to base component too
    widgetFactory.__component = WidgetComponent;
    return widgetFactory;
}

var IroColorPicker = /*@__PURE__*/(function (Component) {
    function IroColorPicker(props) {
        var this$1 = this;

        Component.call(this, props);
        this.colors = [];
        this.inputActive = false;
        this.events = {};
        this.activeEvents = {};
        this.deferredEvents = {};
        this.id = props.id;
        var colors = props.colors.length > 0 ? props.colors : [props.color];
        colors.forEach(function (colorValue) { return this$1.addColor(colorValue); });
        this.setActiveColor(0);
        // Pass all the props into the component's state,
        // Except we want to add the color object and make sure that refs aren't passed down to children
        this.state = Object.assign({}, props,
            {color: this.color,
            colors: this.colors,
            layout: props.layout});
    }

    if ( Component ) IroColorPicker.__proto__ = Component;
    IroColorPicker.prototype = Object.create( Component && Component.prototype );
    IroColorPicker.prototype.constructor = IroColorPicker;
    // Plubic multicolor API
    /**
    * @desc Add a color to the color picker
    * @param color new color to add
    * @param index optional color index
    */
    IroColorPicker.prototype.addColor = function addColor (color, index) {
        if ( index === void 0 ) index = this.colors.length;

        // Create a new iro.Color
        // Also bind it to onColorChange, so whenever the color changes it updates the color picker
        var newColor = new IroColor(color, this.onColorChange.bind(this));
        // Insert color @ the given index
        this.colors.splice(index, 0, newColor);
        // Reindex colors
        this.colors.forEach(function (color, index) { return color.index = index; });
        // Update picker state if necessary
        if (this.state) {
            this.setState({ colors: this.colors });
        }
        // Fire color init event
        this.deferredEmit('color:init', newColor);
    };
    /**
     * @desc Remove a color from the color picker
     * @param index color index
     */
    IroColorPicker.prototype.removeColor = function removeColor (index) {
        var color = this.colors.splice(index, 1)[0];
        // Destroy the color object -- this unbinds it from the color picker
        color.unbind();
        // Reindex colors
        this.colors.forEach(function (color, index) { return color.index = index; });
        // Update picker state if necessary
        if (this.state) {
            this.setState({ colors: this.colors });
        }
        // If the active color was removed, default active color to 0
        if (color.index === this.color.index) {
            this.setActiveColor(0);
        }
        // Fire color remove event
        this.emit('color:remove', color);
    };
    /**
     * @desc Set the currently active color
     * @param index color index
     */
    IroColorPicker.prototype.setActiveColor = function setActiveColor (index) {
        this.color = this.colors[index];
        if (this.state) {
            this.setState({ color: this.color });
        }
        // Fire color switch event
        this.emit('color:setActive', this.color);
    };
    /**
     * @desc Replace all of the current colorPicker colors
     * @param newColorValues list of new colors to add
     */
    IroColorPicker.prototype.setColors = function setColors (newColorValues, activeColorIndex) {
        var this$1 = this;
        if ( activeColorIndex === void 0 ) activeColorIndex = 0;

        // Unbind color events
        this.colors.forEach(function (color) { return color.unbind(); });
        // Destroy old colors
        this.colors = [];
        // Add new colors
        newColorValues.forEach(function (colorValue) { return this$1.addColor(colorValue); });
        // Reset active color
        this.setActiveColor(activeColorIndex);
        this.emit('color:setAll', this.colors);
    };
    // Public ColorPicker events API
    /**
     * @desc Set a callback function for an event
     * @param eventList event(s) to listen to
     * @param callback - Function called when the event is fired
     */
    IroColorPicker.prototype.on = function on (eventList, callback) {
        var this$1 = this;

        var events = this.events;
        // eventList can be an eventType string or an array of eventType strings
        (!Array.isArray(eventList) ? [eventList] : eventList).forEach(function (eventType) {
            // Add event callback
            (events[eventType] || (events[eventType] = [])).push(callback);
            // Call deferred events
            // These are events that can be stored until a listener for them is added
            if (this$1.deferredEvents[eventType]) {
                // Deffered events store an array of arguments from when the event was called
                this$1.deferredEvents[eventType].forEach(function (args) {
                    callback.apply(null, args);
                });
                // Clear deferred events
                this$1.deferredEvents[eventType] = [];
            }
        });
    };
    /**
     * @desc Remove a callback function for an event added with on()
     * @param eventList - event(s) to listen to
     * @param callback - original callback function to remove
     */
    IroColorPicker.prototype.off = function off (eventList, callback) {
        var this$1 = this;

        (!Array.isArray(eventList) ? [eventList] : eventList).forEach(function (eventType) {
            var callbackList = this$1.events[eventType];
            // this.emitHook('event:off', eventType, callback);
            if (callbackList)
                { callbackList.splice(callbackList.indexOf(callback), 1); }
        });
    };
    /**
     * @desc Emit an event
     * @param eventType event to emit
     */
    IroColorPicker.prototype.emit = function emit (eventType) {
        var this$1 = this;
        var args = [], len = arguments.length - 1;
        while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];

        var activeEvents = this.activeEvents;
        var isEventActive = activeEvents.hasOwnProperty(eventType) ? activeEvents[eventType] : false;
        // Prevent event callbacks from firing if the event is already active
        // This stops infinite loops if something in an event callback causes the same event to be fired again
        // (e.g. setting the color inside a color:change callback)
        if (!isEventActive) {
            activeEvents[eventType] = true;
            var callbackList = this.events[eventType] || [];
            callbackList.forEach(function (fn) { return fn.apply(this$1, args); });
            activeEvents[eventType] = false;
        }
    };
    /**
     * @desc Emit an event now, or save it for when the relevent event listener is added
     * @param eventType - The name of the event to emit
     */
    IroColorPicker.prototype.deferredEmit = function deferredEmit (eventType) {
        var ref;

        var args = [], len = arguments.length - 1;
        while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
        var deferredEvents = this.deferredEvents;
        (ref = this).emit.apply(ref, [ eventType ].concat( args ));
        (deferredEvents[eventType] || (deferredEvents[eventType] = [])).push(args);
    };
    // Public utility methods
    IroColorPicker.prototype.setOptions = function setOptions (newOptions) {
        this.setState(newOptions);
    };
    /**
     * @desc Resize the color picker
     * @param width - new width
     */
    IroColorPicker.prototype.resize = function resize (width) {
        this.setOptions({ width: width });
    };
    /**
     * @desc Reset the color picker to the initial color provided in the color picker options
     */
    IroColorPicker.prototype.reset = function reset () {
        this.colors.forEach(function (color) { return color.reset(); });
        this.setState({ colors: this.colors });
    };
    /**
     * @desc Called by the createWidget wrapper when the element is mounted into the page
     * @param container - the container element for this ColorPicker instance
     */
    IroColorPicker.prototype.onMount = function onMount (container) {
        this.el = container;
        this.deferredEmit('mount', this);
    };
    // Internal methods
    /**
     * @desc React to a color update
     * @param color - current color
     * @param changes - shows which h,s,v,a color channels changed
     */
    IroColorPicker.prototype.onColorChange = function onColorChange (color, changes) {
        this.setState({ color: this.color });
        if (this.inputActive) {
            this.inputActive = false;
            this.emit('input:change', color, changes);
        }
        this.emit('color:change', color, changes);
    };
    /**
     * @desc Handle input from a UI control element
     * @param type - event type
     */
    IroColorPicker.prototype.emitInputEvent = function emitInputEvent (type, originId) {
        if (type === 0 /* Start */) {
            this.emit('input:start', this.color, originId);
        }
        else if (type === 1 /* Move */) {
            this.emit('input:move', this.color, originId);
        }
        else if (type === 2 /* End */) {
            this.emit('input:end', this.color, originId);
        }
    };
    IroColorPicker.prototype.render = function render (props, state) {
        var this$1 = this;

        var layout = state.layout;
        // use layout shorthands
        if (!Array.isArray(layout)) {
            switch (layout) {
                // TODO: implement some?
                default:
                    layout = [
                        { component: IroWheel },
                        { component: IroSlider } ];
            }
            // add transparency slider to the layout
            if (state.transparency) {
                layout.push({
                    component: IroSlider,
                    options: {
                        sliderType: 'alpha'
                    }
                });
            }
        }
        return (h("div", { class: "IroColorPicker", id: state.id, style: {
                display: state.display
            } }, layout.map(function (ref, componentIndex) {
                var UiComponent = ref.component;
                var options = ref.options;

                return (h(UiComponent, Object.assign({}, state, options, { ref: undefined, onInput: this$1.emitInputEvent.bind(this$1), parent: this$1, index: componentIndex })));
        })));
    };

    return IroColorPicker;
}(m));
IroColorPicker.defaultProps = Object.assign({}, iroColorPickerOptionDefaults,
    {colors: [],
    display: 'block',
    id: null,
    layout: 'default',
    margin: null});
var IroColorPickerWidget = createWidget(IroColorPicker);

var iro;
(function (iro) {
    iro.version = "5.5.2"; // replaced by @rollup/plugin-replace; see rollup.config.js
    iro.Color = IroColor;
    iro.ColorPicker = IroColorPickerWidget;
    var ui;
    (function (ui) {
        ui.h = h;
        ui.ComponentBase = IroComponentWrapper;
        ui.Handle = IroHandle;
        ui.Slider = IroSlider;
        ui.Wheel = IroWheel;
        ui.Box = IroBox;
    })(ui = iro.ui || (iro.ui = {}));
})(iro || (iro = {}));
var iro$1 = iro;

/* harmony default export */ const iro_es = (iro$1);

// EXTERNAL MODULE: ./src/shared/view.js
var view = __webpack_require__(92207);
var view_default = /*#__PURE__*/__webpack_require__.n(view);
// EXTERNAL MODULE: ./src/editor/src/templates/propertyeditor/colorpicker.html
var colorpicker = __webpack_require__(80801);
var colorpicker_default = /*#__PURE__*/__webpack_require__.n(colorpicker);
;// ./src/editor/src/views/panels/propertyeditor/DataTypes/ColorPicker/colorpicker.js





function colorToHex(color) {
  const hex = color.alpha === 1 ? color.hexString : color.hex8String;
  return hex.toUpperCase();
}
function ColorPicker() {
  this.onColorChanged = (color) => {
    this._setInputFieldsToColor(color);
  };

  this.onInputMove = (color) => {
    this.colorChangedListener && this.colorChangedListener(colorToHex(color), false);
  };

  this.onInputEnd = (color) => {
    this.colorChangedListener && this.colorChangedListener(colorToHex(color), true);
  };

  this.onColorInit = (color) => this._setInputFieldsToColor(color);
}

ColorPicker.prototype = Object.create((view_default()).prototype);

ColorPicker.prototype.dispose = function () {
  this.colorChangedListener = undefined;
  this.colorPicker.off('color:change', this.onColorChanged);
  this.colorPicker.off('color:init', this.onColorInit);
  this.colorPicker.off('input:move', this.onInputMove);
  this.colorPicker.off('input:end', this.onInputEnd);
};

ColorPicker.prototype.render = function () {
  this.el = this.bindView($((colorpicker_default())), this);

  const pickerDiv = this.$('#ui-color-picker')[0];

  this.colorPicker = new iro_es.ColorPicker(pickerDiv, {
    width: 212,
    margin: 16,
    padding: 0,
    layout: [
      {
        component: iro_es.ui.Box
      },
      {
        component: iro_es.ui.Slider,
        options: { sliderType: 'hue' }
      },
      {
        component: iro_es.ui.Slider,
        options: { sliderType: 'alpha' }
      }
    ]
  });

  this.$('.IroBox').css({ 'border-radius': 0 }); //override the css style to remove the default corner radius

  this.colorPicker.on('color:change', this.onColorChanged);
  this.colorPicker.on('color:init', this.onColorInit);
  this.colorPicker.on('input:move', this.onInputMove);
  this.colorPicker.on('input:end', this.onInputEnd);

  this.$('#opacityInput').on('click', () => {
    this.$('#opacityInput').select();
  });

  this.$('#hexinput').on('click', () => {
    this.$('#hexinput').select();
  });
};

ColorPicker.prototype._setInputFieldsToColor = function (color) {
  this.$('#hexinput').val(color.hexString.toUpperCase());

  if (color.alpha === 1) {
    this.$('#opacityInput').val('');
  } else {
    this.$('#opacityInput').val(Math.floor(color.alpha * 100) + '%');
  }
};

ColorPicker.prototype.onHexInputFieldChanged = function (scope, el, event) {
  let color = event.target.value.toUpperCase();

  const isValid = /(^#{0,1}[0-9A-F]{6}$)|(^#{0,1}[0-9A-F]{3}$)/i.test(color);

  if (isValid) {
    if (color[0] !== '#') color = '#' + color;

    this.colorPicker.color.set(color);
    this.colorChangedListener && this.colorChangedListener(colorToHex(this.colorPicker.color), true);
  }

  //set fields again with the correct format
  this._setInputFieldsToColor(this.colorPicker.color);
  this.$('#hexinput').blur();
};

ColorPicker.prototype.onOpacityInputFieldChanged = function (scope, el, event) {
  let opacity = event.target.value.trim().replace('%', '');

  const isValid = !isNaN(opacity) && !isNaN(parseFloat(opacity));
  if (isValid) {
    this.colorPicker.color.alpha = opacity / 100;
    this.colorChangedListener && this.colorChangedListener(colorToHex(this.colorPicker.color), true);
  }

  this.$('#opacityInput').blur();
};

ColorPicker.prototype.setColorChangedListener = function (cb) {
  this.colorChangedListener = cb;
};

ColorPicker.prototype.setColor = function (color) {
  this.colorPicker.color.set(color || '#000000');
};

/* harmony default export */ const ColorPicker_colorpicker = (ColorPicker);


/***/ }),

/***/ 45625:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.LauncherHeader-module__Root--AlxM4{padding:20px 24px;border-bottom:1px solid var(--theme-color-border-default);background:var(--theme-color-bg-1)}.LauncherHeader-module__Content--yPXTr{display:flex;align-items:center;gap:16px}.LauncherHeader-module__VersionInfo--vzjLE{flex:1}.LauncherHeader-module__Actions--mpgqA{display:flex;align-items:center;gap:12px}.LauncherHeader-module__DataSourceToggle--SMnB6{display:flex;align-items:center}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherHeader/LauncherHeader.module.scss"],"names":[],"mappings":"AAIA,oCACE,iBAAA,CACA,yDAAA,CACA,kCAAA,CAGF,uCACE,YAAA,CACA,kBAAA,CACA,QAAA,CAGF,2CACE,MAAA,CAGF,uCACE,YAAA,CACA,kBAAA,CACA,QAAA,CAGF,gDACE,YAAA,CACA,kBAAA","sourcesContent":["/**\n * LauncherHeader - Styling\n */\n\n.Root {\n  padding: 20px 24px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  background: var(--theme-color-bg-1);\n}\n\n.Content {\n  display: flex;\n  align-items: center;\n  gap: 16px;\n}\n\n.VersionInfo {\n  flex: 1;\n}\n\n.Actions {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n}\n\n.DataSourceToggle {\n  display: flex;\n  align-items: center;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `LauncherHeader-module__Root--AlxM4`,
	"Content": `LauncherHeader-module__Content--yPXTr`,
	"VersionInfo": `LauncherHeader-module__VersionInfo--vzjLE`,
	"Actions": `LauncherHeader-module__Actions--mpgqA`,
	"DataSourceToggle": `LauncherHeader-module__DataSourceToggle--SMnB6`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 45653:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const KeyboardHandler = (__webpack_require__(70441)["default"]);
const { KeyCode } = __webpack_require__(7444);
const View = __webpack_require__(92207);
const PopupLayerTemplate = __webpack_require__(68160);
const StringInputPopupTemplate = __webpack_require__(92424);
const YesNoPopupTemplate = __webpack_require__(76849);
const FileSystem = __webpack_require__(38656);
const ConfirmModal = __webpack_require__(227);
const ErrorModal = __webpack_require__(35665);
const { ToastLayer } = __webpack_require__(80424);

const utils = __webpack_require__(93015);
const { platform, PlatformOS } = __webpack_require__(37218);

// Styles
__webpack_require__(99712);

// ---------------------------------------------------------------------
// PopupLayer
// ---------------------------------------------------------------------
function PopupLayer() {
  View.call(this);

  this.isShowingPopup = false;
  this.ignoreContextMenuEvent = false;

  this.isLocked = false; //locked means that a body click event won't close the popup
  this.contentId = '';
  this.popouts = [];
  this._dimLayerCount = 0;
  this.modals = [];

  KeyboardHandler.instance.registerCommands([
    {
      handler: () => {
        if (this.popup && this.isShowingPopup) {
          this.hidePopup();
        } else if (this.modals.length) {
          this.hideModal();
        } else if (this.popouts.length) {
          this.hidePopouts();
        }
      },
      keybinding: KeyCode.Escape
    }
  ]);
}

PopupLayer.prototype = Object.create(View.prototype);

PopupLayer.prototype.resize = function () {
  this.width = $(window).width();
  this.height = $(window).height();
};

PopupLayer.prototype.render = function () {
  var _this = this;

  var el = this.bindView($(PopupLayerTemplate), this);
  if (this.el) this.el.append(el);
  else this.el = el;

  this.resize();
  $(window).on('resize', () => this.resize());

  // Detect if you click outside of a popup, then it should be closed
  var shouldClosePopup = false;
  $('body')
    .on('click', function (e) {
      if (!$(e.target).parents().is(_this.$('.popup-layer-popup')) && shouldClosePopup && !_this.modals.length) {
        _this.hidePopup();
        _this.hideTooltip();
      }
    })
    .on('mousedown', function (e) {
      shouldClosePopup = !$(e.target).parents().is(_this.$('.popup-layer-popup')) && !_this.isLocked;
    });

  // Detect if you click outside of a popout and popup, then all popouts should be closed
  var shouldClosePopout = false;

  function onClick(e) {
    if (
      !(
        $(e.target).parents().is(_this.$('.popup-layer-popup')) ||
        $(e.target).parents().is(_this.$('.popup-layer-popouts'))
      ) &&
      shouldClosePopout &&
      !_this.modals.length
    ) {
      _this.hidePopouts();
    }
  }

  $('body')
    .on('click', onClick)
    .on('contextmenu', (e) => {
      if (!this.ignoreContextMenuEvent) {
        onClick(e);
      }
    })
    .on('mousedown', (e) => {
      shouldClosePopout =
        !(
          $(e.target).parents().is(this.$('.popup-layer-popup')) ||
          $(e.target).parents().is(this.$('.popup-layer-popouts'))
        ) && !this.isLocked;

      //On Windows contextmenu is sent after mousedown. This can cause popups that are opened through mousedown to close immediately.
      //So ignore the contextmenu event for 0.1 seconds to remedy this
      if (platform.os === PlatformOS.Windows) {
        this.ignoreContextMenuEvent = true;
        setTimeout(() => {
          this.ignoreContextMenuEvent = false;
        }, 100);
      }
    });

  // Check if should close modal
  _this.shouldCloseModal = false;
  _this.allowShouldCloseModal = false;

  $('body')
    .on('click', () => {
      if (_this.shouldCloseModal) {
        _this.hideModal();
        _this.shouldCloseModal = false;
        _this.allowShouldCloseModal = false;
      }
    })
    .on('mousedown', (e) => {
      if (_this.allowShouldCloseModal) {
        _this.shouldCloseModal = !$(e.target).parents().is(_this.$('.popup-layer-modal'));
      }
    });

  // Drop files on body to copy to project folder
  var isValid = function (dataTransfer) {
    return dataTransfer !== undefined && dataTransfer.types && dataTransfer.types.indexOf('Files') >= 0;
  };

  const { ProjectModel } = __webpack_require__(6203); //include here to fix circular dependency

  $('body')[0].addEventListener('dragover', function (evt) {
    // Indicate drop is OK
    if (ProjectModel.instance && isValid(evt.dataTransfer)) {
      _this.showFileDrop();

      evt.dataTransfer.dropEffect = 'copy';
    }

    evt.stopPropagation();
    evt.preventDefault();
  });

  $('body')[0].addEventListener('dragleave', function (evt) {
    _this.hideFileDrop();

    evt.stopPropagation();
    evt.preventDefault();
  });

  $('body')[0].addEventListener('drop', function (evt) {
    if (ProjectModel.instance && isValid(evt.dataTransfer)) {
      var files = evt.dataTransfer.files;

      var _files = [];
      function collectFiles(file, basedir) {
        if (FileSystem.instance.isPathDirectory(file.fullPath)) {
          var subfiles = FileSystem.instance.readDirectorySync(file.fullPath);
          subfiles.forEach((f) => {
            collectFiles({ fullPath: f.fullPath, name: f.fullPath.substring(basedir.length + 1) });
          });
        } else _files.push(file);
      }

      const toastActivityId = 'toast-drop-files-progress-id';
      try {
        for (var i = 0; i < files.length; i++) {
          collectFiles(
            { fullPath: files[i].path, name: files[i].name },
            FileSystem.instance.getFileDirectoryName(files[i].path)
          );
        }

        _files.forEach((f, index) => {
          ProjectModel.instance.copyFileToProjectDirectory(f);

          const progress = index / _files.length;
          ToastLayer.showProgress('Copying files to project folder.', progress, toastActivityId);
        });

        if (_files.length === 1) {
          ToastLayer.showSuccess('Successfully copied file to the project folder.');
        } else {
          ToastLayer.showSuccess(`Successfully copied ${_files.length} files to the project folder.`);
        }
      } catch (e) {
        console.error(e);
        ToastLayer.showError(
          'Failed to drop file. This is most likely caused by a temporary file, place the file in a normal folder and try again.'
        );
      } finally {
        ToastLayer.hideActivity(toastActivityId);
      }
    }

    _this.hideFileDrop();

    evt.stopPropagation();
    evt.preventDefault();
  });

  View.showTooltip = this.showTooltip.bind(this);
  View.hideTooltip = this.hideTooltip.bind(this);

  return this.el;
};

PopupLayer.prototype.getContentId = function () {
  return this.contentId;
};

PopupLayer.prototype._dimBakckground = function () {
  this._dimLayerCount++;
  this.$('.popup-layer').addClass('dim');
};

PopupLayer.prototype._undimBackground = function () {
  this._dimLayerCount--;

  if (this._dimLayerCount <= 0) {
    this.$('.popup-layer').removeClass('dim');
    this._dimLayerCount = 0;
  }
};

// Popups
PopupLayer.prototype.hidePopup = function (args) {
  if (this.popup && this.isShowingPopup) {
    this._undimBackground();
    this.popup && this.popup.content.el.detach();
    this.$('.popup-layer-popup').css({ visibility: 'hidden' });
    this.popup.onClose && this.popup.onClose();
    this.popup.content.onClose && this.popup.content.onClose();
    this.isShowingPopup = false;
    this.contentId = '';
    this._disablePopupAutoheight();
  }
  this.$('.popup-layer-blocker').css({ display: 'none' });
};

PopupLayer.prototype._enablePopupAutoheight = function () {
  this.$('.popup-layer-popup').css({ height: 'auto' });
  this.$('.popup-layer-popup-content').css({ position: 'relative' });
  this.$('.popup-layer-popup-content > *').css({ display: 'inline-block', verticalAlign: 'bottom' });
};

PopupLayer.prototype._disablePopupAutoheight = function () {
  this.$('.popup-layer-popup').css({ height: '' });
  this.$('.popup-layer-popup-content').css({ position: '' });
  this.$('.popup-layer-popup-content > *').css({ display: '', verticalAlign: '' });
};

PopupLayer.prototype.setContentSize = function (contentWidth, contentHeight) {
  this.$('.popup-layer-popup').css({
    width: contentWidth,
    height: contentHeight,
    transition: 'none'
  });
};

// Popup
PopupLayer.prototype.showPopup = function (args) {
  var arrowSize = 10;

  this.hidePopup();
  this.$('.popup-layer-blocker').css({ display: '' });

  var content = args.content.el;
  args.content.owner = this;

  this.$('.popup-layer-popup-content').append(content);

  // Force a reflow to ensure the element is measurable
  void this.$('.popup-layer-popup-content')[0].offsetHeight;

  // Query the actual appended element to measure dimensions
  var popupContent = this.$('.popup-layer-popup-content');
  var contentWidth = popupContent.children().first().outerWidth(true);
  var contentHeight = popupContent.children().first().outerHeight(true);

  if (args.position === 'screen-center') {
    if (args.isBackgroundDimmed) {
      this._dimBakckground();

      this.$('.popup-layer-popup').css({
        transition: '',
        transform: 'translateY(20px)',
        opacity: 0
      });

      setTimeout(() => {
        this.$('.popup-layer-popup').css({
          transition: 'all 200ms ease',
          transform: 'translateY(0)',
          opacity: 1
        });
      }, 100);
    }

    var x = this.width / 2 - contentWidth / 2,
      y = this.height / 2 - contentHeight / 2;

    this.$('.popup-layer-popup').css({
      position: 'absolute',
      left: x,
      top: y,
      width: contentWidth,
      height: contentHeight
    });
    this.$('.popup-layer-popup-arrow').css({ display: 'none' });
    this.$('.popup-layer-popup').css({ visibility: 'visible' });
  } else {
    var attachToLeft = args.attachTo ? args.attachTo.offset().left : args.attachToPoint.x;
    var attachToTop = args.attachTo ? args.attachTo.offset().top : args.attachToPoint.y;
    var attachToWidth = args.attachTo ? args.attachTo.outerWidth(true) : 0;
    var attachToHeight = args.attachTo ? args.attachTo.outerHeight(true) : 0;

    // Figure out the position of the popup
    var x, y;
    this.$('.popup-layer-popup-arrow')
      .removeClass('left')
      .removeClass('right')
      .removeClass('bottom')
      .removeClass('top');
    if (args.position === 'bottom') {
      x = attachToLeft + attachToWidth / 2 - contentWidth / 2;
      y = attachToHeight + attachToTop + arrowSize;
      this.$('.popup-layer-popup-arrow').addClass('top');
    } else if (args.position === 'top') {
      x = attachToLeft + attachToWidth / 2 - contentWidth / 2;
      y = attachToTop - contentHeight - arrowSize;
      this.$('.popup-layer-popup-arrow').addClass('bottom');
    } else if (args.position === 'left') {
      x = attachToLeft - contentWidth - arrowSize;
      y = attachToTop + attachToHeight / 2 - contentHeight / 2;
      this.$('.popup-layer-popup-arrow').addClass('right');
    } else if (args.position === 'right') {
      x = attachToWidth + attachToLeft + arrowSize;
      y = attachToTop + attachToHeight / 2 - contentHeight / 2;
      this.$('.popup-layer-popup-arrow').addClass('left');
    }

    // Make sure the popup is not outside of the screen
    var margin = 2;
    if (x + contentWidth > this.width - margin) x = this.width - margin - contentWidth;
    if (y + contentHeight > this.height - margin) y = this.height - margin - contentHeight;
    if (x < margin) x = margin;
    if (y < margin) y = margin;

    // Cannot cover to bar as that is used for moving window
    const topBarHeight = utils.windowTitleBarHeight();

    if (y < topBarHeight) y = topBarHeight;

    // Position the popup
    this.$('.popup-layer-popup').css({
      position: 'absolute',
      left: x,
      top: y,
      transition: 'none'
    });

    this.setContentSize(contentWidth, contentHeight);

    // Set the position of the arrow
    this.$('.popup-layer-popup-arrow').css({
      left:
        args.position === 'top' || args.position === 'bottom'
          ? Math.round(Math.abs(attachToLeft + attachToWidth / 2 - x)) + 'px'
          : '',
      top:
        args.position === 'left' || args.position === 'right'
          ? Math.round(Math.abs(attachToTop + attachToHeight / 2 - y)) + 'px'
          : ''
    });

    this.$('.popup-layer-popup-arrow').css({ display: 'initial' });
    this.$('.popup-layer-popup').css({ visibility: 'visible' });
  }

  if (args.hasDynamicHeight) {
    this._enablePopupAutoheight();
  }

  this.popup = args;
  this.popup.onOpen && this.popup.onOpen();
  this.popup.content.onOpen && this.popup.content.onOpen();
  this.isShowingPopup = true;
  this.contentId = args.contentId;
};

PopupLayer.prototype._resizePopout = function (popout, args) {
  const popoutEl = popout.el;
  const content = popoutEl.find('.popup-layer-popout-content');

  const contentWidth = content.outerWidth(true);
  const contentHeight = content.outerHeight(true);

  popoutEl.css({
    width: contentWidth,
    height: contentHeight,
    transition: 'none'
  });
};

PopupLayer.prototype._positionPopout = function (popout, args) {
  const popoutEl = popout.el;
  const position = popout.position;
  const attachRect = popout.attachToRect;

  const content = popoutEl.find('.popup-layer-popout-content');

  const arrowSize = 10;

  const contentWidth = content.outerWidth(true);
  const contentHeight = content.outerHeight(true);

  // Figure out the position of the popup
  let x, y;

  if (!args.disableCentering)
    popoutEl
      .find('.popup-layer-popout-arrow')
      .removeClass('left')
      .removeClass('right')
      .removeClass('bottom')
      .removeClass('top');
  if (position === 'bottom') {
    x = attachRect.left + attachRect.width / 2 - contentWidth / 2;
    y = attachRect.height + attachRect.top + arrowSize;
    popoutEl.find('.popup-layer-popout-arrow').addClass('top');
  } else if (position === 'top') {
    x = attachRect.left + attachRect.width / 2 - contentWidth / 2;
    y = attachRect.top - contentHeight - arrowSize;
    popoutEl.find('.popup-layer-popout-arrow').addClass('bottom');
  } else if (position === 'left') {
    x = attachRect.left - contentWidth - arrowSize;
    y = attachRect.top + attachRect.height / 2 - contentHeight / 2;
    popoutEl.find('.popup-layer-popout-arrow').addClass('right');
  } else if (position === 'right') {
    x = attachRect.width + attachRect.left + arrowSize;
    y = attachRect.top + attachRect.height / 2 - contentHeight / 2;
    popoutEl.find('.popup-layer-popout-arrow').addClass('left');
  }

  // Make sure the popup is not outside of the screen
  const margin = 10;
  if (args.offsetX) x += args.offsetX;
  if (args.offsetY) y += args.offsetY;

  if (x + contentWidth > this.width - margin) x = this.width - margin - contentWidth;
  if (y + contentHeight > this.height - margin) y = this.height - margin - contentHeight;
  if (x < margin) x = margin;
  if (y < margin) y = margin;

  // Cannot cover to bar as that is used for moving window
  const topBarHeight = utils.windowTitleBarHeight();

  if (y < topBarHeight) y = topBarHeight;

  // Position the popup
  popoutEl.css({
    position: 'absolute',
    left: x,
    top: y,
    transition: 'none'
  });

  // Set the position of the arrow
  popoutEl.find('.popup-layer-popout-arrow').css({
    left:
      position === 'top' || position === 'bottom'
        ? Math.round(Math.abs(attachRect.left + attachRect.width / 2 - x)) + 'px'
        : '',
    top:
      position === 'left' || position === 'right'
        ? Math.round(Math.abs(attachRect.top + attachRect.height / 2 - y)) + 'px'
        : ''
  });
};

// Popout
PopupLayer.prototype.showPopout = function (args) {
  this.$('.popup-layer-blocker').css({ display: '' });

  var content = args.content.el;
  args.content.owner = this;

  var popoutEl = this.cloneTemplate('popout');
  this.$('.popup-layer-popouts').append(popoutEl);

  popoutEl.find('.popup-layer-popout-content').append(content);
  popoutEl.find('.popup-layer-popout').css({ visibility: 'visible' });

  const resizeObserver = new ResizeObserver((entries) => {
    this._resizePopout(popout, args);
    if (!args.disableDynamicPositioning) {
      this._positionPopout(popout, args);
    }
  });

  //note: the dom element in attachTo can become invalid while the popout is open (when the property panel re-renders)
  //so we need to save the position now and hope the attach point doesn't move
  const popout = {
    el: popoutEl,
    onClose: args.onClose,
    position: args.position,
    animate: args.animate,
    manualClose: args.manualClose,
    attachToRect: {
      left: args.attachTo ? args.attachTo.offset().left : args.attachToPoint.x,
      top: args.attachTo ? args.attachTo.offset().top : args.attachToPoint.y,
      width: args.attachTo ? args.attachTo.outerWidth(true) : 0,
      height: args.attachTo ? args.attachTo.outerHeight(true) : 0
    },
    resizeObserver
  };
  this.setPopoutArrowColor(popout, args.arrowColor || '313131');

  this._resizePopout(popout, args);
  this._positionPopout(popout, args);
  resizeObserver.observe(content[0]);

  this.popouts.push(popout);

  // Enable pointer events for outside-click-to-close when popouts are active
  this.$('.popup-layer').addClass('has-popouts');

  if (args.animate) {
    popoutEl.css({
      transform: 'translateY(10px)',
      opacity: 0
    });

    setTimeout(() => {
      popoutEl.css({ transition: 'all 200ms ease-out', transform: 'translateY(0px)', opacity: 1 });
    }, 50);
  }

  return popout;
};

PopupLayer.prototype.setPopoutArrowColor = function (popout, color) {
  // Set the position of the arrow
  const _arrowColorCssAttr = {
    bottom: 'borderBottomColor',
    top: 'borderTopColor',
    left: 'borderLeftColor',
    right: 'borderRightColor'
  };
  const arrowColorCss = {};
  arrowColorCss[_arrowColorCssAttr[popout.position]] = color;
  popout.el.find('.popup-layer-popout-arrow').css(arrowColorCss);
};

PopupLayer.prototype.hidePopouts = function (manual) {
  const popouts = [...this.popouts]; //shallow copy since we'll modify the array in the loop
  popouts.forEach((p) => {
    if (!p.manualClose || manual === true) {
      this.hidePopout(p);
    }
  });
};

PopupLayer.prototype.hidePopout = function (popout) {
  if (!popout) return;

  const i = this.popouts.indexOf(popout);
  if (i !== -1) {
    this.popouts.splice(i, 1);
  }

  popout.resizeObserver.disconnect();
  popout.onClose && popout.onClose();

  const close = () => {
    popout.el.detach();

    if (this.popouts.length === 0) {
      this.$('.popup-layer-blocker').css({ display: 'none' });
      // Disable pointer events when no popouts are active
      this.$('.popup-layer').removeClass('has-popouts');
    }
  };

  if (popout.animate) {
    popout.el.css({ transition: 'all 200ms ease-out', transform: 'translateY(10px)', opacity: 0 });
    setTimeout(() => {
      close();
    }, 250);
  } else {
    close();
  }
};

// Modals
PopupLayer.prototype.showModal = function (args) {
  const content = args.content.el;
  args.content.owner = this;

  this.$('.popup-layer-modal-content').html(content);

  //If the previous popup is being hidden, cancel that timer
  this._hideTimeoutId && clearTimeout(this._hideTimeoutId);

  // Position the popup
  this.$('.popup-layer-modal').css({
    transform: 'translate(-50%, calc(-50% + -20px))',
    transition: 'none',
    opacity: 0
  });
  this.$('.popup-layer-modal').css({ visibility: 'visible' });

  this._dimBakckground();

  setTimeout(() => {
    this.$('.popup-layer-modal').css({ transition: 'all 200ms ease', transform: 'translate(-50%, -50%)', opacity: 1 });
  }, 100);

  const modal = args;

  modal.onOpen && modal.onOpen();
  modal.content.onOpen && modal.content.onOpen();
  this.modals.push(modal);

  return modal;
};

PopupLayer.prototype.hideModal = function (modal) {
  if (!modal) {
    modal = this.modals.pop();
  } else {
    const index = this.modals.indexOf(modal);
    if (index !== -1) {
      this.modals.splice(index, 1);
    }
  }

  if (modal) {
    this.$('.popup-layer-modal').css({ transform: 'translate(-50%, calc(-50% + -20px))', opacity: 0 });
    this._undimBackground();
    this._hideTimeoutId = setTimeout(() => {
      this.$('.popup-layer-modal').css({ visibility: 'hidden' });
      this.$('.popup-layer-modal-content').empty();
    }, 200);
    modal.onClose && modal.onClose();
  }
};

PopupLayer.prototype.hideAllModalsAndPopups = function () {
  const modals = this.modals.slice();
  modals.forEach((modal) => this.hideModal(modal));

  this.hidePopup();
  this.hidePopouts();
  this.hideTooltip();
};

PopupLayer.prototype.showConfirmModal = function ({ message, title, confirmLabel, cancelLabel, onConfirm, onCancel }) {
  var popup = new ConfirmModal({
    message: message,
    title: title,
    confirmLabel: confirmLabel,
    cancelLabel: cancelLabel,
    onCancel: () => {
      this.hideModal();
      onCancel && onCancel();
    },
    onConfirm: () => {
      this.hideModal();
      onConfirm && onConfirm();
    }
  });

  popup.render();

  this.showModal({
    content: popup,
    onClose: function () {},
    onOpen: function () {}
  });
};

PopupLayer.prototype.showErrorModal = function ({ message, title, onOk }) {
  //print error so it is logged to the debug log
  console.log('Showing error modal: ');
  console.log(` Title: ${title} Message:  ${message}`);

  var popup = new ErrorModal({
    message: message,
    title: title,
    onOk: () => {
      this.hideModal();
      onOk && onOk();
    }
  });

  popup.render();

  this.showModal({
    content: popup,
    onClose: function () {},
    onOpen: function () {}
  });
};

// ------------------ Drag and drop ---------------------
PopupLayer.prototype.startDragging = function (item) {
  var _this = this;

  this.$('.popup-layer-dragger-label').text(item.label);

  this.dragItem = item;

  function placeDragItem(x, y) {
    _this
      .$('.popup-layer-dragger')
      .css({ opacity: '1', '-webkit-transition': 'none', transform: 'translate3d(' + x + 'px,' + y + 'px,0px)' });
  }

  $('body').on('mousemove', function (e) {
    placeDragItem(e.pageX, e.pageY);
    e.preventDefault();
  });
  $('body').on('mouseup', function (e) {
    _this.dragCompleted();

    $('body').off('mousemove').off('mouseup');
    e.preventDefault();
  });
};

PopupLayer.prototype.isDragging = function () {
  return !!this.dragItem;
};

PopupLayer.prototype.indicateDropType = function (type) {
  var dropTypeClasses = {
    move: 'fa-share',
    add: 'fa-plus'
  };
  for (var i in dropTypeClasses) {
    this.$('.popup-layer-drop-type-indicator').removeClass(dropTypeClasses[i]);
  }

  if (type) this.$('.popup-layer-drop-type-indicator').addClass(dropTypeClasses[type]);
};

PopupLayer.prototype.setDragMessage = function (message) {
  if (message && message !== '') {
    this.$('.popup-layer-drag-message-text').text(message);
    this.$('.popup-layer-drag-message').show();
  } else {
    this.$('.popup-layer-drag-message').hide();
  }
};

PopupLayer.prototype.dragCompleted = function () {
  this.$('.popup-layer-dragger').css({ opacity: '0' });
  this.dragItem = undefined;
};

PopupLayer.prototype._setTooltipPosition = function (args) {
  if (args.offset && args.offset.x) {
    this.$('.popup-layer-tooltip-arrow').css({ transform: `translateX(-${args.offset.x}px)` });
  } else {
    this.$('.popup-layer-tooltip-arrow').css({ transform: '' });
  }

  this.$('.popup-layer-tooltip').css({ left: args.x, top: args.y, opacity: 1 });

  // Set arrow position
  this.$('.popup-layer-tooltip-arrow')
    .removeClass('left')
    .removeClass('right')
    .removeClass('top')
    .removeClass('bottom')
    .addClass(args.position);
};

PopupLayer.prototype._getTooltipPosition = function (args) {
  var contentWidth = this.$('.popup-layer-tooltip').outerWidth();
  var contentHeight = this.$('.popup-layer-tooltip').outerHeight();

  var attachToLeft = args.attachTo ? args.attachTo.offset().left : args.x;
  var attachToTop = args.attachTo ? args.attachTo.offset().top : args.y;
  var attachToWidth = args.attachTo ? args.attachTo[0].getBoundingClientRect().width : 0;
  var attachToHeight = args.attachTo ? args.attachTo[0].getBoundingClientRect().height : 0;

  if (args.offset && args.offset.x) {
    attachToLeft += args.offset.x;
  }

  var x, y;
  var arrowSize = 5;
  if (args.position === undefined || args.position === 'bottom') {
    x = attachToLeft + attachToWidth / 2 - contentWidth / 2;
    y = attachToHeight + attachToTop + arrowSize;
  } else if (args.position === 'top') {
    x = attachToLeft + attachToWidth / 2 - contentWidth / 2;
    y = attachToTop - contentHeight - arrowSize;
  } else if (args.position === 'left') {
    x = attachToLeft - contentWidth - arrowSize;
    y = attachToTop + attachToHeight / 2 - contentHeight / 2;
  } else if (args.position === 'right') {
    x = attachToWidth + attachToLeft + arrowSize;
    y = attachToTop + attachToHeight / 2 - contentHeight / 2;
  }

  return { x, y, contentWidth, contentHeight };
};

// -------------------------------- Tooltip ----------------------------------
PopupLayer.prototype.showTooltip = function (args) {
  if (this.isDragging()) return; // Don't show tooltip if a drag is in progress

  // Set text
  this.$('.popup-layer-tooltip-content').html(args.content);

  args.position = args.position || 'bottom'; //default to bottom

  //calculate tooltip position
  let rect = this._getTooltipPosition(args);

  //if the tooltip is attached to the bottom of an element, and gets placed outside
  //the screen, change position to top
  if (args.position === 'bottom' && rect.y + rect.contentHeight > window.innerHeight) {
    args.position = 'top';
    rect = this._getTooltipPosition(args);
  }

  //make sure the tooltip isn't rendered outside the screen, and that there's
  //a small amount of margin to the edge
  rect.x = Math.max(16, rect.x);

  this._setTooltipPosition({
    offset: args.offset,
    position: args.position,
    x: rect.x,
    y: rect.y
  });

  return rect;
};

PopupLayer.prototype.hideTooltip = function () {
  this.$('.popup-layer-tooltip').css({ opacity: 0 });
};

// ------------------ Toast ---------------------
PopupLayer.prototype.showToast = function (text) {
  var _this = this;

  this.$('.popup-layer-toast').text(text);
  var x = (this.width - this.$('.popup-layer-toast').width()) / 2;
  var y = (this.height - this.$('.popup-layer-toast').height()) / 2;

  this.$('.popup-layer-toast').css({ opacity: '1', transform: 'translate3d(' + x + 'px,' + y + 'px,0px)' });

  clearTimeout(this.toastHideTimeout);
  this.toastHideTimeout = setTimeout(function () {
    _this.$('.popup-layer-toast').css({ opacity: '0' });
  }, 2000);

  console.error(
    'showToast is deprecated. Use ToastLayer.showSuccess(), ToastLayer.showError() or ToastLayer.showInteraction() instead.'
  );
};

// ------------------ Toast ---------------------
PopupLayer.prototype.showActivity = function (text) {
  var _this = this;

  this.$('.popup-layer-activity-text').html(text);
  var x = (this.width - this.$('.popup-layer-activity').width()) / 2;
  var y = (this.height - this.$('.popup-layer-activity').height()) / 2;

  this.$('.popup-layer-activity').css({ opacity: '1', transform: 'translate3d(' + x + 'px,' + y + 'px,0px)' });

  this.$('.popup-layer-activity-progress').hide();
  this.$('.popup-layer-activity-progress-bar').css({ width: '0%' });

  console.error('showActivity is deprecated. Use ToastLayer.showActivity() instead.');
};

PopupLayer.prototype.hideActivity = function () {
  this.$('.popup-layer-activity').css({ opacity: '0', pointerEvents: 'none' });

  console.error('hideActivity is deprecated. Use ToastLayer.hideActivity() instead.');
};

/**
 *
 * @param {number} progress 0 to 100
 */
PopupLayer.prototype.showActivityProgress = function (progress) {
  this.$('.popup-layer-activity-progress').show();
  this.$('.popup-layer-activity-progress-bar').css({ width: progress + '%' });

  console.error('showActivityProgress is deprecated. Use ToastLayer.showProgress() instead.');
};

// ------------------ Indicate drop on ---------------------
PopupLayer.prototype.showFileDrop = function () {
  this.$('.popup-file-drop').show();
};

PopupLayer.prototype.hideFileDrop = function () {
  this.$('.popup-file-drop').hide();
};

// ---------------------------------------------------------------------
// PopupLayer.StringInputPopup
// ---------------------------------------------------------------------
PopupLayer.StringInputPopup = function (args) {
  for (var i in args) this[i] = args[i];
};
PopupLayer.StringInputPopup.prototype = Object.create(View.prototype);

PopupLayer.StringInputPopup.prototype.render = function () {
  this.el = this.bindView($(StringInputPopupTemplate), this);

  // Only close on Enter for single-line inputs, not textareas
  const input = this.$('.string-input-popup-input');
  const isTextarea = input.is('textarea');

  if (!isTextarea) {
    input.off('keypress').on('keypress', (e) => {
      if (e.which == 13) {
        this.onOkClicked();
      }
    });
  }

  return this.el;
};

PopupLayer.StringInputPopup.prototype.onOkClicked = function () {
  var val = this.$('.string-input-popup-input')
    .val()
    .split(',')
    .map((x) => x.trim())
    .join();

  this.owner.hidePopup();

  this.onOk && this.onOk(val);
};

PopupLayer.StringInputPopup.prototype.onCancelClicked = function () {
  this.onCancel && this.onCancel();
  this.owner.hidePopup();
};

PopupLayer.StringInputPopup.prototype.updateLineNumbers = function () {
  const textarea = this.$('.string-input-popup-input')[0];
  const lineNumbersEl = this.$('.string-input-popup-line-numbers')[0];

  if (!textarea || !lineNumbersEl) return;

  // Count lines based on textarea value
  const text = textarea.value;
  const lines = text ? text.split('\n').length : 1;

  // Always show at least 8 lines (matching rows="8")
  const displayLines = Math.max(8, lines);

  // Generate line numbers
  let lineNumbersHTML = '';
  for (let i = 1; i <= displayLines; i++) {
    lineNumbersHTML += i + '\n';
  }

  lineNumbersEl.textContent = lineNumbersHTML;

  // Sync scroll
  lineNumbersEl.scrollTop = textarea.scrollTop;
};

PopupLayer.StringInputPopup.prototype.onOpen = function () {
  const textarea = this.$('.string-input-popup-input');

  // Initial line numbers
  this.updateLineNumbers();

  // Update line numbers on input
  textarea.on('input', () => this.updateLineNumbers());

  // Sync scroll between textarea and line numbers
  textarea.on('scroll', () => {
    const lineNumbersEl = this.$('.string-input-popup-line-numbers')[0];
    if (lineNumbersEl) {
      lineNumbersEl.scrollTop = textarea[0].scrollTop;
    }
  });

  textarea.focus();
};

// ---------------------------------------------------------------------
// PopupLayer.YesNoPopup
// ---------------------------------------------------------------------
PopupLayer.YesNoPopup = function (args) {
  for (var i in args) this[i] = args[i];

  if (!this.yesLabel) this.yesLabel = 'Yes';
  if (!this.noLabel) this.noLabel = 'No';
};
PopupLayer.YesNoPopup.prototype = Object.create(View.prototype);

PopupLayer.YesNoPopup.prototype.render = function () {
  var _this = this;

  this.el = this.bindView($(YesNoPopupTemplate), this);

  return this.el;
};

PopupLayer.YesNoPopup.prototype.onYesClicked = function () {
  this.owner.hidePopup();

  this.onYes && this.onYes();
};

PopupLayer.YesNoPopup.prototype.onNoClicked = function () {
  this.owner.hidePopup();

  this.onNo && this.onNo();
};

module.exports = PopupLayer;


/***/ }),

/***/ 45977:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Y: () => (/* binding */ KeyCodeUtils)
/* harmony export */ });
/* harmony import */ var _KeyCode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7444);

class KeyCodeStrMap {
    constructor() {
        this._keyCodeToStr = [];
        this._strToKeyCode = 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()] || _KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Unknown;
    }
}
const uiMap = new KeyCodeStrMap();
(function () {
    function define(keyCode, uiLabel) {
        uiMap.define(keyCode, uiLabel);
    }
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Unknown, 'unknown');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Backspace, 'Backspace');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Tab, 'Tab');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Enter, 'Enter');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Shift, 'Shift');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Ctrl, 'Ctrl');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Alt, 'Alt');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.PauseBreak, 'PauseBreak');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.CapsLock, 'CapsLock');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Escape, 'Escape');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Space, 'Space');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.PageUp, 'PageUp');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.PageDown, 'PageDown');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.End, 'End');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Home, 'Home');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.LeftArrow, 'ArrowLeft');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.UpArrow, 'ArrowUp');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.RightArrow, 'ArrowRight');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.DownArrow, 'ArrowDown');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Insert, 'Insert');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Delete, 'Delete');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_0, '0');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_1, '1');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_2, '2');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_3, '3');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_4, '4');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_5, '5');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_6, '6');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_7, '7');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_8, '8');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_9, '9');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_A, 'A');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_B, 'B');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_C, 'C');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_D, 'D');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_E, 'E');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_F, 'F');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_G, 'G');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_H, 'H');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_I, 'I');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_J, 'J');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_K, 'K');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_L, 'L');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_M, 'M');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_N, 'N');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_O, 'O');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_P, 'P');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_Q, 'Q');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_R, 'R');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_S, 'S');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_T, 'T');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_U, 'U');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_V, 'V');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_W, 'W');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_X, 'X');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_Y, 'Y');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.KEY_Z, 'Z');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Meta, 'Meta');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.ContextMenu, 'ContextMenu');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F1, 'F1');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F2, 'F2');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F3, 'F3');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F4, 'F4');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F5, 'F5');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F6, 'F6');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F7, 'F7');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F8, 'F8');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F9, 'F9');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F10, 'F10');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F11, 'F11');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F12, 'F12');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F13, 'F13');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F14, 'F14');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F15, 'F15');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F16, 'F16');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F17, 'F17');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F18, 'F18');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.F19, 'F19');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NumLock, 'NumLock');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.ScrollLock, 'ScrollLock');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.US_SEMICOLON, ';');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.US_EQUAL, '=');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.US_COMMA, ',');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.US_MINUS, '-');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.US_DOT, '.');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.US_SLASH, '/');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.US_BACKTICK, '`');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.ABNT_C1, 'ABNT_C1');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.ABNT_C2, 'ABNT_C2');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.US_OPEN_SQUARE_BRACKET, '[');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.US_BACKSLASH, '\\');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.US_CLOSE_SQUARE_BRACKET, ']');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.US_QUOTE, "'");
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.OEM_8, 'OEM_8');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.OEM_102, 'OEM_102');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_0, 'NumPad0');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_1, 'NumPad1');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_2, 'NumPad2');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_3, 'NumPad3');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_4, 'NumPad4');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_5, 'NumPad5');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_6, 'NumPad6');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_7, 'NumPad7');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_8, 'NumPad8');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_9, 'NumPad9');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_MULTIPLY, 'NumPad_Multiply');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_ADD, 'NumPad_Add');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_SEPARATOR, 'NumPad_Separator');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_SUBTRACT, 'NumPad_Subtract');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_DECIMAL, 'NumPad_Decimal');
    define(_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.NUMPAD_DIVIDE, 'NumPad_Divide');
})();
var KeyCodeUtils;
(function (KeyCodeUtils) {
    function toString(keyCode) {
        return uiMap.keyCodeToStr(keyCode);
    }
    KeyCodeUtils.toString = toString;
    function fromString(key) {
        if (key === ' ') {
            return uiMap.strToKeyCode('Space');
        }
        return uiMap.strToKeyCode(key);
    }
    KeyCodeUtils.fromString = fromString;
})(KeyCodeUtils || (KeyCodeUtils = {}));


/***/ }),

/***/ 46054:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ConfirmationDialog-module__Root--C9YzB{max-width:300px;width:100vw}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/popups/ConfirmationDialog/ConfirmationDialog.module.scss"],"names":[],"mappings":"AAAA,wCACE,eAAA,CACA,WAAA","sourcesContent":[".Root {\r\n  max-width: 300px;\r\n  width: 100vw;\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ConfirmationDialog-module__Root--C9YzB`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 46055:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_variantseditor_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(46337);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_variantseditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_variantseditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_variantseditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_variantseditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 46172:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .codelens-decoration {
	overflow: hidden;
	display: inline-block;
	text-overflow: ellipsis;
	white-space: nowrap;
	color: var(--vscode-editorCodeLens-foreground)
}

.monaco-editor .codelens-decoration>span,
.monaco-editor .codelens-decoration>a {
	user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
	white-space: nowrap;
	vertical-align: sub;
}

.monaco-editor .codelens-decoration>a {
	text-decoration: none;
}

.monaco-editor .codelens-decoration>a:hover {
	cursor: pointer;
	color: var(--vscode-editorLink-activeForeground) !important;
}

.monaco-editor .codelens-decoration>a:hover .codicon {
	color: var(--vscode-editorLink-activeForeground) !important;
}

.monaco-editor .codelens-decoration .codicon {
	vertical-align: middle;
	color: currentColor !important;
	color: var(--vscode-editorCodeLens-foreground);
}

.monaco-editor .codelens-decoration>a:hover .codicon::before {
	cursor: pointer;
}

@keyframes fadein {
	0% {
		opacity: 0;
		visibility: visible;
	}

	100% {
		opacity: 1;
	}
}

.monaco-editor .codelens-decoration.fadein {
	animation: fadein 0.1s linear;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/codelens/browser/codelensWidget.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,gBAAgB;CAChB,qBAAqB;CACrB,uBAAuB;CACvB,mBAAmB;CACnB;AACD;;AAEA;;CAEC,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;CACrB,mBAAmB;CACnB,mBAAmB;AACpB;;AAEA;CACC,qBAAqB;AACtB;;AAEA;CACC,eAAe;CACf,2DAA2D;AAC5D;;AAEA;CACC,2DAA2D;AAC5D;;AAEA;CACC,sBAAsB;CACtB,8BAA8B;CAC9B,8CAA8C;AAC/C;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC;EACC,UAAU;EACV,mBAAmB;CACpB;;CAEA;EACC,UAAU;CACX;AACD;;AAEA;CACC,6BAA6B;AAC9B","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .codelens-decoration {\n\toverflow: hidden;\n\tdisplay: inline-block;\n\ttext-overflow: ellipsis;\n\twhite-space: nowrap;\n\tcolor: var(--vscode-editorCodeLens-foreground)\n}\n\n.monaco-editor .codelens-decoration>span,\n.monaco-editor .codelens-decoration>a {\n\tuser-select: none;\n\t-webkit-user-select: none;\n\t-ms-user-select: none;\n\twhite-space: nowrap;\n\tvertical-align: sub;\n}\n\n.monaco-editor .codelens-decoration>a {\n\ttext-decoration: none;\n}\n\n.monaco-editor .codelens-decoration>a:hover {\n\tcursor: pointer;\n\tcolor: var(--vscode-editorLink-activeForeground) !important;\n}\n\n.monaco-editor .codelens-decoration>a:hover .codicon {\n\tcolor: var(--vscode-editorLink-activeForeground) !important;\n}\n\n.monaco-editor .codelens-decoration .codicon {\n\tvertical-align: middle;\n\tcolor: currentColor !important;\n\tcolor: var(--vscode-editorCodeLens-foreground);\n}\n\n.monaco-editor .codelens-decoration>a:hover .codicon::before {\n\tcursor: pointer;\n}\n\n@keyframes fadein {\n\t0% {\n\t\topacity: 0;\n\t\tvisibility: visible;\n\t}\n\n\t100% {\n\t\topacity: 1;\n\t}\n}\n\n.monaco-editor .codelens-decoration.fadein {\n\tanimation: fadein 0.1s linear;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 46299:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgChat = function SvgChat(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M2.82608 3.76174C3.10739 3.48044 3.48892 3.3224 3.88674 3.3224H20.3867C20.7846 3.3224 21.1661 3.48044 21.4474 3.76174C21.7287 4.04305 21.8867 4.42458 21.8867 4.8224V16.8224C21.8867 17.2202 21.7287 17.6018 21.4474 17.8831C21.1661 18.1644 20.7846 18.3224 20.3867 18.3224H7.87828L7.87407 18.326L4.84588 20.8572L4.84302 20.8596C4.62449 21.0404 4.35917 21.1556 4.07782 21.1917C3.79648 21.2279 3.51066 21.1835 3.25353 21.0638C2.99639 20.944 2.77847 20.7538 2.62505 20.5153C2.47164 20.2767 2.38901 19.9995 2.38677 19.7158L2.38672 19.7099L2.38674 4.8224C2.38674 4.42458 2.54478 4.04305 2.82608 3.76174ZM20.3867 4.8224L3.88674 4.8224V19.7039L6.90803 17.1784C7.17624 16.9488 7.51771 16.8225 7.87093 16.8224H20.3867V4.8224Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.1367 11.7599C12.6545 11.7599 13.0742 11.3402 13.0742 10.8224C13.0742 10.3046 12.6545 9.8849 12.1367 9.8849C11.619 9.8849 11.1992 10.3046 11.1992 10.8224C11.1992 11.3402 11.619 11.7599 12.1367 11.7599Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M16.6367 11.7599C17.1545 11.7599 17.5742 11.3402 17.5742 10.8224C17.5742 10.3046 17.1545 9.8849 16.6367 9.8849C16.119 9.8849 15.6992 10.3046 15.6992 10.8224C15.6992 11.3402 16.119 11.7599 16.6367 11.7599Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M7.63672 11.7599C8.15449 11.7599 8.57422 11.3402 8.57422 10.8224C8.57422 10.3046 8.15449 9.8849 7.63672 9.8849C7.11895 9.8849 6.69922 10.3046 6.69922 10.8224C6.69922 11.3402 7.11895 11.7599 7.63672 11.7599Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgChat);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "827af16fbc92435f1453cadafa458d79.svg");

/***/ }),

/***/ 46337:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.variants-editor {
  border-bottom: 1px solid var(--theme-color-bg-1);
  position: relative;
  display: flex;
  align-items: center;
}

.variants-section {
  padding: 5px 10px;
  display: flex;
  flex-grow: 1;
  align-items: center;
  min-height: 50px;
  box-sizing: border-box;
}

.variants-name-section {
  display: flex;
  flex-grow: 1;
  align-items: center;
}

.variants-section label {
  display: block;
  color: var(--theme-color-fg-default);
}

.variants-name-section:hover label {
  color: var(--theme-color-fg-highlight);
}

.variants-add-icon {
  width: 16px;
  height: 16px;
  opacity: 0.56;
  margin-left: auto;
}

.variants-pick-icon {
  content: url('../assets/icons/editor/up-down-arrows.svg');
  margin-top: 2px;
  opacity: 0.7;
  margin-left: 4px;
}

.variants-input {
  border: none;
  outline: none;
  color: var(--theme-color-fg-default);
  padding: 0 0 0 10px;
  height: 33px;
  flex-grow: 1;
  flex-shrink: 1;
  min-width: 0; /* need to set this, otherwise the input will refuse to shrink beyond a certain size */
}

.variants-name-section:hover .variants-add-icon,
.variants-name-section:hover .variants-pick-icon {
  opacity: 1;
}

.variants-header {
  color: var(--theme-color-fg-default);
  background-color: var(--theme-color-bg-2);
  padding: 4px 4px 4px 16px;
  display: flex;
  align-items: center;
  min-height: 27px;
}

.variants-header span {
  margin-top: -1px;
  font-weight: var(--font-weight-semibold);
  font-size: 12px;
}

.variants-header .fa {
  padding-top: 2px;
}

.variants-add-header > i.fa {
  margin-left: auto;
  margin-right: 3px;
}

.variants-add-header .add-button {
  margin-left: auto;
  margin-right: 0px;
}

.variants-add-input {
  border: none;
  outline: none;
  background-color: var(--theme-color-bg-1);
  color: var(--theme-color-fg-default);
  padding: 2px;
  padding-left: 10px;
  width: 100%;
  height: 30px;
}

.variants-name {
  background-color: var(--theme-color-bg-1);
  color: --fg-def;
  padding: 5px;
  height: 20px;
  width: 100%;
}

.variants-name:hover {
  background-color: var(--theme-color-bg-5);
  color: var(--theme-color-fg-highlight);
}

.variants-input-container {
  position: relative;
  display: flex;
  align-items: center;
  padding: 8px;
  box-sizing: border-box;
}

.variants-input {
  background-color: var(--theme-color-bg-2);
  height: 27px;
  margin-right: 4px;
}

.variants-button {
  background-color: var(--theme-color-bg-3);
  color: var(--theme-color-fg-default);
  padding: 5px 8px;
  border-radius: 1px;
  font-size: 11px;
  line-height: 17px;
  border: none;
  align-items: center;
  justify-content: center;
  display: flex;
  min-width: 78px;
  box-sizing: border-box;
  cursor: pointer;
  font-weight: var(--font-weight-semibold);
}

.variants-button:hover {
  background-color: var(--theme-color-bg-1);
}

.variants-button.primary {
  background-color: var(--theme-color-primary);
  color: var(--theme-color-on-primary);
}

.variants-button.primary:hover {
  background-color: var(--theme-color-primary-highlight);
}

.variants-button.teal {
  background-color: var(--theme-color-secondary);
  color: var(--theme-color-on-secondary);
}

.variants-button.teal:hover {
  background-color: var(--theme-color-secondary-highlight);
}

.variants-pick-variant-item {
  --hover-bg-color: var(--theme-color-bg-3);
  color: var(--theme-color-fg-default-contrast);
  border-top: 1px solid var(--theme-color-bg-3);
  position: relative;
  display: flex;
  align-items: center;
  min-height: 33px;
  box-sizing: border-box;
  cursor: pointer;
}

.variants-pick-variant-item.is-page {
  padding: 4px;
}

.variants-pick-variant-inner {
  width: 100%;
  display: flex;
  align-items: center;
  border-radius: 2px;
}

.variants-pick-variant-item.is-page:hover .variants-pick-variant-inner {
  background-color: var(--hover-bg-color);
  color: var(--theme-color-fg-highlight);
  fill: var(--theme-color-fg-highlight);
}

.variant-item-name {
  flex-grow: 1;
  padding: 7px 0 7px 10px;
  overflow-wrap: anywhere; /* force words to break arbitrarily to always leave room for the icons next to the name */
}

.variants-pick-variant-item:not(.is-page):hover {
  color: var(--theme-color-fg-highlight);
  background-color: var(--hover-bg-color);
}

.variants-item-icon {
  color: var(--theme-color-fg-default-shy);
  visibility: hidden;
  width: 28px;
  height: 28px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.variants-pick-variant-item:hover .variants-item-icon {
  visibility: visible;
}

.variants-item-icon:hover {
  color: var(--theme-color-fg-highlight);
}

.variants-edit-mode-header {
  height: 33px;
  background-color: var(--theme-color-secondary);
  color: var(--theme-color-on-secondary);
  line-height: 33px;
  padding: 0px 10px;
  display: flex;
  align-items: center;
}

.variants-sidepanel-edit-mode:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 2px;
  bottom: 0;
  pointer-events: none;
  border: 2px solid var(--theme-color-secondary);
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/propertyeditor/variantseditor.css"],"names":[],"mappings":"AAAA;EACE,gDAAgD;EAChD,kBAAkB;EAClB,aAAa;EACb,mBAAmB;AACrB;;AAEA;EACE,iBAAiB;EACjB,aAAa;EACb,YAAY;EACZ,mBAAmB;EACnB,gBAAgB;EAChB,sBAAsB;AACxB;;AAEA;EACE,aAAa;EACb,YAAY;EACZ,mBAAmB;AACrB;;AAEA;EACE,cAAc;EACd,oCAAoC;AACtC;;AAEA;EACE,sCAAsC;AACxC;;AAEA;EACE,WAAW;EACX,YAAY;EACZ,aAAa;EACb,iBAAiB;AACnB;;AAEA;EACE,yDAAyD;EACzD,eAAe;EACf,YAAY;EACZ,gBAAgB;AAClB;;AAEA;EACE,YAAY;EACZ,aAAa;EACb,oCAAoC;EACpC,mBAAmB;EACnB,YAAY;EACZ,YAAY;EACZ,cAAc;EACd,YAAY,EAAE,sFAAsF;AACtG;;AAEA;;EAEE,UAAU;AACZ;;AAEA;EACE,oCAAoC;EACpC,yCAAyC;EACzC,yBAAyB;EACzB,aAAa;EACb,mBAAmB;EACnB,gBAAgB;AAClB;;AAEA;EACE,gBAAgB;EAChB,wCAAwC;EACxC,eAAe;AACjB;;AAEA;EACE,gBAAgB;AAClB;;AAEA;EACE,iBAAiB;EACjB,iBAAiB;AACnB;;AAEA;EACE,iBAAiB;EACjB,iBAAiB;AACnB;;AAEA;EACE,YAAY;EACZ,aAAa;EACb,yCAAyC;EACzC,oCAAoC;EACpC,YAAY;EACZ,kBAAkB;EAClB,WAAW;EACX,YAAY;AACd;;AAEA;EACE,yCAAyC;EACzC,eAAe;EACf,YAAY;EACZ,YAAY;EACZ,WAAW;AACb;;AAEA;EACE,yCAAyC;EACzC,sCAAsC;AACxC;;AAEA;EACE,kBAAkB;EAClB,aAAa;EACb,mBAAmB;EACnB,YAAY;EACZ,sBAAsB;AACxB;;AAEA;EACE,yCAAyC;EACzC,YAAY;EACZ,iBAAiB;AACnB;;AAEA;EACE,yCAAyC;EACzC,oCAAoC;EACpC,gBAAgB;EAChB,kBAAkB;EAClB,eAAe;EACf,iBAAiB;EACjB,YAAY;EACZ,mBAAmB;EACnB,uBAAuB;EACvB,aAAa;EACb,eAAe;EACf,sBAAsB;EACtB,eAAe;EACf,wCAAwC;AAC1C;;AAEA;EACE,yCAAyC;AAC3C;;AAEA;EACE,4CAA4C;EAC5C,oCAAoC;AACtC;;AAEA;EACE,sDAAsD;AACxD;;AAEA;EACE,8CAA8C;EAC9C,sCAAsC;AACxC;;AAEA;EACE,wDAAwD;AAC1D;;AAEA;EACE,yCAAyC;EACzC,6CAA6C;EAC7C,6CAA6C;EAC7C,kBAAkB;EAClB,aAAa;EACb,mBAAmB;EACnB,gBAAgB;EAChB,sBAAsB;EACtB,eAAe;AACjB;;AAEA;EACE,YAAY;AACd;;AAEA;EACE,WAAW;EACX,aAAa;EACb,mBAAmB;EACnB,kBAAkB;AACpB;;AAEA;EACE,uCAAuC;EACvC,sCAAsC;EACtC,qCAAqC;AACvC;;AAEA;EACE,YAAY;EACZ,uBAAuB;EACvB,uBAAuB,EAAE,yFAAyF;AACpH;;AAEA;EACE,sCAAsC;EACtC,uCAAuC;AACzC;;AAEA;EACE,wCAAwC;EACxC,kBAAkB;EAClB,WAAW;EACX,YAAY;EACZ,cAAc;EACd,aAAa;EACb,mBAAmB;EACnB,uBAAuB;AACzB;;AAEA;EACE,mBAAmB;AACrB;;AAEA;EACE,sCAAsC;AACxC;;AAEA;EACE,YAAY;EACZ,8CAA8C;EAC9C,sCAAsC;EACtC,iBAAiB;EACjB,iBAAiB;EACjB,aAAa;EACb,mBAAmB;AACrB;;AAEA;EACE,WAAW;EACX,kBAAkB;EAClB,MAAM;EACN,OAAO;EACP,UAAU;EACV,SAAS;EACT,oBAAoB;EACpB,8CAA8C;AAChD","sourcesContent":[".variants-editor {\n  border-bottom: 1px solid var(--theme-color-bg-1);\n  position: relative;\n  display: flex;\n  align-items: center;\n}\n\n.variants-section {\n  padding: 5px 10px;\n  display: flex;\n  flex-grow: 1;\n  align-items: center;\n  min-height: 50px;\n  box-sizing: border-box;\n}\n\n.variants-name-section {\n  display: flex;\n  flex-grow: 1;\n  align-items: center;\n}\n\n.variants-section label {\n  display: block;\n  color: var(--theme-color-fg-default);\n}\n\n.variants-name-section:hover label {\n  color: var(--theme-color-fg-highlight);\n}\n\n.variants-add-icon {\n  width: 16px;\n  height: 16px;\n  opacity: 0.56;\n  margin-left: auto;\n}\n\n.variants-pick-icon {\n  content: url('../assets/icons/editor/up-down-arrows.svg');\n  margin-top: 2px;\n  opacity: 0.7;\n  margin-left: 4px;\n}\n\n.variants-input {\n  border: none;\n  outline: none;\n  color: var(--theme-color-fg-default);\n  padding: 0 0 0 10px;\n  height: 33px;\n  flex-grow: 1;\n  flex-shrink: 1;\n  min-width: 0; /* need to set this, otherwise the input will refuse to shrink beyond a certain size */\n}\n\n.variants-name-section:hover .variants-add-icon,\n.variants-name-section:hover .variants-pick-icon {\n  opacity: 1;\n}\n\n.variants-header {\n  color: var(--theme-color-fg-default);\n  background-color: var(--theme-color-bg-2);\n  padding: 4px 4px 4px 16px;\n  display: flex;\n  align-items: center;\n  min-height: 27px;\n}\n\n.variants-header span {\n  margin-top: -1px;\n  font-weight: var(--font-weight-semibold);\n  font-size: 12px;\n}\n\n.variants-header .fa {\n  padding-top: 2px;\n}\n\n.variants-add-header > i.fa {\n  margin-left: auto;\n  margin-right: 3px;\n}\n\n.variants-add-header .add-button {\n  margin-left: auto;\n  margin-right: 0px;\n}\n\n.variants-add-input {\n  border: none;\n  outline: none;\n  background-color: var(--theme-color-bg-1);\n  color: var(--theme-color-fg-default);\n  padding: 2px;\n  padding-left: 10px;\n  width: 100%;\n  height: 30px;\n}\n\n.variants-name {\n  background-color: var(--theme-color-bg-1);\n  color: --fg-def;\n  padding: 5px;\n  height: 20px;\n  width: 100%;\n}\n\n.variants-name:hover {\n  background-color: var(--theme-color-bg-5);\n  color: var(--theme-color-fg-highlight);\n}\n\n.variants-input-container {\n  position: relative;\n  display: flex;\n  align-items: center;\n  padding: 8px;\n  box-sizing: border-box;\n}\n\n.variants-input {\n  background-color: var(--theme-color-bg-2);\n  height: 27px;\n  margin-right: 4px;\n}\n\n.variants-button {\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-default);\n  padding: 5px 8px;\n  border-radius: 1px;\n  font-size: 11px;\n  line-height: 17px;\n  border: none;\n  align-items: center;\n  justify-content: center;\n  display: flex;\n  min-width: 78px;\n  box-sizing: border-box;\n  cursor: pointer;\n  font-weight: var(--font-weight-semibold);\n}\n\n.variants-button:hover {\n  background-color: var(--theme-color-bg-1);\n}\n\n.variants-button.primary {\n  background-color: var(--theme-color-primary);\n  color: var(--theme-color-on-primary);\n}\n\n.variants-button.primary:hover {\n  background-color: var(--theme-color-primary-highlight);\n}\n\n.variants-button.teal {\n  background-color: var(--theme-color-secondary);\n  color: var(--theme-color-on-secondary);\n}\n\n.variants-button.teal:hover {\n  background-color: var(--theme-color-secondary-highlight);\n}\n\n.variants-pick-variant-item {\n  --hover-bg-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-default-contrast);\n  border-top: 1px solid var(--theme-color-bg-3);\n  position: relative;\n  display: flex;\n  align-items: center;\n  min-height: 33px;\n  box-sizing: border-box;\n  cursor: pointer;\n}\n\n.variants-pick-variant-item.is-page {\n  padding: 4px;\n}\n\n.variants-pick-variant-inner {\n  width: 100%;\n  display: flex;\n  align-items: center;\n  border-radius: 2px;\n}\n\n.variants-pick-variant-item.is-page:hover .variants-pick-variant-inner {\n  background-color: var(--hover-bg-color);\n  color: var(--theme-color-fg-highlight);\n  fill: var(--theme-color-fg-highlight);\n}\n\n.variant-item-name {\n  flex-grow: 1;\n  padding: 7px 0 7px 10px;\n  overflow-wrap: anywhere; /* force words to break arbitrarily to always leave room for the icons next to the name */\n}\n\n.variants-pick-variant-item:not(.is-page):hover {\n  color: var(--theme-color-fg-highlight);\n  background-color: var(--hover-bg-color);\n}\n\n.variants-item-icon {\n  color: var(--theme-color-fg-default-shy);\n  visibility: hidden;\n  width: 28px;\n  height: 28px;\n  flex-shrink: 0;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.variants-pick-variant-item:hover .variants-item-icon {\n  visibility: visible;\n}\n\n.variants-item-icon:hover {\n  color: var(--theme-color-fg-highlight);\n}\n\n.variants-edit-mode-header {\n  height: 33px;\n  background-color: var(--theme-color-secondary);\n  color: var(--theme-color-on-secondary);\n  line-height: 33px;\n  padding: 0px 10px;\n  display: flex;\n  align-items: center;\n}\n\n.variants-sidepanel-edit-mode:after {\n  content: '';\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 2px;\n  bottom: 0;\n  pointer-events: none;\n  border: 2px solid var(--theme-color-secondary);\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 46526:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRefresh = function SvgRefresh(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M6.10597 12.6071C6.10597 9.27605 8.80631 6.57571 12.1373 6.57571C14.294 6.57571 16.1873 7.70734 17.2542 9.41235H14.8667C14.4525 9.41235 14.1167 9.74814 14.1167 10.1624C14.1167 10.5766 14.4525 10.9124 14.8667 10.9124H18.9323C19.3465 10.9124 19.6823 10.5766 19.6823 10.1624V6.09679C19.6823 5.68257 19.3465 5.34679 18.9323 5.34679C18.5181 5.34679 18.1823 5.68257 18.1823 6.09679V8.11989C16.8111 6.27569 14.6143 5.07912 12.1373 5.07912C7.97976 5.07912 4.60938 8.4495 4.60938 12.6071C4.60938 16.7647 7.97976 20.1351 12.1373 20.1351C15.4161 20.1351 18.2034 18.0394 19.2366 15.1167C19.3744 14.7271 19.1702 14.2996 18.7805 14.1618C18.3909 14.0241 17.9633 14.2283 17.8256 14.6179C16.9972 16.9613 14.7622 18.6385 12.1373 18.6385C8.80631 18.6385 6.10597 15.9381 6.10597 12.6071Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRefresh);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "18275da221a0406aacecca6d3e529ee8.svg");

/***/ }),

/***/ 46553:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  MD: () => (/* reexport */ DiffSelection),
  i2: () => (/* reexport */ DiffSelectionType)
});

// UNUSED EXPORTS: DiffLine, DiffLineType, DiffType, Image

;// ../noodl-git/src/core/models/diff-selection.ts
/**
 * The state of a file's diff selection
 */
var DiffSelectionType;
(function (DiffSelectionType) {
    /** The entire file should be committed */
    DiffSelectionType["All"] = "All";
    /** A subset of lines in the file have been selected for committing */
    DiffSelectionType["Partial"] = "Partial";
    /** The file should be excluded from committing */
    DiffSelectionType["None"] = "None";
})(DiffSelectionType || (DiffSelectionType = {}));
/**
 * Utility function which determines whether a boolean selection state
 * matches the given DiffSelectionType. A true selection state matches
 * DiffSelectionType.All, a false selection state matches
 * DiffSelectionType.None and if the selection type is partial there's
 * never a match.
 */
function typeMatchesSelection(selectionType, selected) {
    switch (selectionType) {
        case DiffSelectionType.All:
            return selected;
        case DiffSelectionType.None:
            return !selected;
        case DiffSelectionType.Partial:
            return false;
        default:
            throw new Error(`Unknown selection type ${selectionType}`);
    }
}
/**
 * An immutable, efficient, storage object for tracking selections of indexable
 * lines. While general purpose by design this is currently used exclusively for
 * tracking selected lines in modified files in the working directory.
 *
 * This class starts out with an initial (or default) selection state, ie
 * either all lines are selected by default or no lines are selected by default.
 *
 * The selection can then be transformed by marking a line or a range of lines
 * as selected or not selected. Internally the class maintains a list of lines
 * whose selection state has diverged from the default selection state.
 */
class DiffSelection {
    /**
     * Initialize a new selection instance where either all lines are selected by default
     * or not lines are selected by default.
     */
    static fromInitialSelection(initialSelection) {
        if (initialSelection !== DiffSelectionType.All && initialSelection !== DiffSelectionType.None) {
            throw new Error('Can only instantiate a DiffSelection with All or None as the initial selection');
        }
        return new DiffSelection(initialSelection, null, null);
    }
    /**
     * @param divergingLines Any line numbers where the selection differs from the default state.
     * @param selectableLines Optional set of line numbers which can be selected.
     */
    constructor(defaultSelectionType, divergingLines = null, selectableLines = null) {
        this.defaultSelectionType = defaultSelectionType;
        this.divergingLines = divergingLines;
        this.selectableLines = selectableLines;
    }
    /** Returns a value indicating the computed overall state of the selection */
    getSelectionType() {
        const divergingLines = this.divergingLines;
        const selectableLines = this.selectableLines;
        // No diverging lines, happy path. Either all lines are selected or none are.
        if (!divergingLines) {
            return this.defaultSelectionType;
        }
        if (divergingLines.size === 0) {
            return this.defaultSelectionType;
        }
        // If we know which lines are selectable we need to check that
        // all lines are divergent and return the inverse of default selection.
        // To avoid looping through the set that often our happy path is
        // if there's a size mismatch.
        if (selectableLines && selectableLines.size === divergingLines.size) {
            const allSelectableLinesAreDivergent = [...selectableLines].every((i) => divergingLines.has(i));
            if (allSelectableLinesAreDivergent) {
                return this.defaultSelectionType === DiffSelectionType.All ? DiffSelectionType.None : DiffSelectionType.All;
            }
        }
        // Note that without any selectable lines we'll report partial selection
        // as long as we have any diverging lines since we have no way of knowing
        // if _all_ lines are divergent or not
        return DiffSelectionType.Partial;
    }
    /** Returns a value indicating wether the given line number is selected or not */
    isSelected(lineIndex) {
        const lineIsDivergent = !!this.divergingLines && this.divergingLines.has(lineIndex);
        if (this.defaultSelectionType === DiffSelectionType.All) {
            return !lineIsDivergent;
        }
        else if (this.defaultSelectionType === DiffSelectionType.None) {
            return lineIsDivergent;
        }
        else {
            throw new Error(`Unknown base selection type ${this.defaultSelectionType}`);
        }
    }
    /**
     * Returns a value indicating wether the given line number is selectable.
     * A line not being selectable usually means it's a hunk header or a context
     * line.
     */
    isSelectable(lineIndex) {
        return this.selectableLines ? this.selectableLines.has(lineIndex) : true;
    }
    /**
     * Returns a copy of this selection instance with the provided
     * line selection update.
     *
     * @param lineIndex The index (line number) of the line which should
     *                 be selected or unselected.
     *
     * @param selected Whether the given line number should be marked
     *                 as selected or not.
     */
    withLineSelection(lineIndex, selected) {
        return this.withRangeSelection(lineIndex, 1, selected);
    }
    /**
     * Returns a copy of this selection instance with the provided
     * line selection update. This is similar to the withLineSelection
     * method except that it allows updating the selection state of
     * a range of lines at once. Use this if you ever need to modify
     * the selection state of more than one line at a time as it's
     * more efficient.
     *
     * @param from     The line index (inclusive) from where to start
     *                 updating the line selection state.
     *
     * @param to       The number of lines for which to update the
     *                 selection state. A value of zero means no lines
     *                 are updated and a value of 1 means only the
     *                 line given by lineIndex will be updated.
     *
     * @param selected Whether the lines should be marked as selected
     *                 or not.
     */
    // Lower inclusive, upper exclusive. Same as substring
    withRangeSelection(from, length, selected) {
        const computedSelectionType = this.getSelectionType();
        const to = from + length;
        // Nothing for us to do here. This state is when all lines are already
        // selected and we're being asked to select more or when no lines are
        // selected and we're being asked to unselect something.
        if (typeMatchesSelection(computedSelectionType, selected)) {
            return this;
        }
        if (computedSelectionType === DiffSelectionType.Partial) {
            const newDivergingLines = new Set(this.divergingLines);
            if (typeMatchesSelection(this.defaultSelectionType, selected)) {
                for (let i = from; i < to; i++) {
                    newDivergingLines.delete(i);
                }
            }
            else {
                for (let i = from; i < to; i++) {
                    // Ensure it's selectable
                    if (this.isSelectable(i)) {
                        newDivergingLines.add(i);
                    }
                }
            }
            return new DiffSelection(this.defaultSelectionType, newDivergingLines.size === 0 ? null : newDivergingLines, this.selectableLines);
        }
        else {
            const newDivergingLines = new Set();
            for (let i = from; i < to; i++) {
                if (this.isSelectable(i)) {
                    newDivergingLines.add(i);
                }
            }
            return new DiffSelection(computedSelectionType, newDivergingLines, this.selectableLines);
        }
    }
    /**
     * Returns a copy of this selection instance where the selection state
     * of the specified line has been toggled (inverted).
     *
     * @param lineIndex The index (line number) of the line which should
     *                 be selected or unselected.
     */
    withToggleLineSelection(lineIndex) {
        return this.withLineSelection(lineIndex, !this.isSelected(lineIndex));
    }
    /**
     * Returns a copy of this selection instance with all lines selected.
     */
    withSelectAll() {
        return new DiffSelection(DiffSelectionType.All, null, this.selectableLines);
    }
    /**
     * Returns a copy of this selection instance with no lines selected.
     */
    withSelectNone() {
        return new DiffSelection(DiffSelectionType.None, null, this.selectableLines);
    }
    /**
     * Returns a copy of this selection instance with a specified set of
     * selectable lines. By default a DiffSelection instance allows selecting
     * all lines (in fact, it has no notion of how many lines exists or what
     * it is that is being selected).
     *
     * If the selection instance lacks a set of selectable lines it can not
     * supply an accurate value from getSelectionType when the selection of
     * all lines have diverged from the default state (since it doesn't know
     * what all lines mean).
     */
    withSelectableLines(selectableLines) {
        const divergingLines = this.divergingLines
            ? new Set([...this.divergingLines].filter((x) => selectableLines.has(x)))
            : null;
        return new DiffSelection(this.defaultSelectionType, divergingLines, selectableLines);
    }
}

// EXTERNAL MODULE: ../noodl-git/src/core/models/diff-data.ts
var diff_data = __webpack_require__(49264);
;// ../noodl-git/src/core/models/diff-line.ts
/** indicate what a line in the diff represents */
var DiffLineType;
(function (DiffLineType) {
    DiffLineType[DiffLineType["Context"] = 0] = "Context";
    DiffLineType[DiffLineType["Add"] = 1] = "Add";
    DiffLineType[DiffLineType["Delete"] = 2] = "Delete";
    DiffLineType[DiffLineType["Hunk"] = 3] = "Hunk";
})(DiffLineType || (DiffLineType = {}));
/** track details related to each line in the diff */
class DiffLine {
    constructor(text, type, 
    // Line number in the original diff patch (before expanding it), or null if
    // it was added as part of a diff expansion action.
    originalLineNumber, oldLineNumber, newLineNumber, noTrailingNewLine = false) {
        this.text = text;
        this.type = type;
        this.originalLineNumber = originalLineNumber;
        this.oldLineNumber = oldLineNumber;
        this.newLineNumber = newLineNumber;
        this.noTrailingNewLine = noTrailingNewLine;
    }
    withNoTrailingNewLine(noTrailingNewLine) {
        return new DiffLine(this.text, this.type, this.originalLineNumber, this.oldLineNumber, this.newLineNumber, noTrailingNewLine);
    }
    isIncludeableLine() {
        return this.type === DiffLineType.Add || this.type === DiffLineType.Delete;
    }
    /** The content of the line, i.e., without the line type marker. */
    get content() {
        return this.text.substr(1);
    }
}

;// ../noodl-git/src/core/models/diff.ts





/***/ }),

/***/ 46583:
/***/ ((module) => {

// Module
var code = "<div style=\"position:relative\"> <div data-template=\"item\" class=\"proplist-item drop-target\"> <div class=\"drop-above-indicator\" style=\"display:none;position:absolute;top:-1px;width:100%;height:2px;background-color:#6c6c6c;pointer-events:none\"> </div> <div class=\"drop-below-indicator\" style=\"display:none;position:absolute;bottom:-1px;width:100%;height:2px;background-color:#6c6c6c;pointer-events:none\"> </div> <div class=\"header proplist-header\"> <div class=\"show-on-edit\" style=\"height:35px;position:relative\"> <input type=\"string\" class=\"sidebar-panel-dark-input name-edit\" data-val=\"name\"> </div> <span data-class=\"isDefault:stringlist-default-label\" class=\"drag-handle component-ports-label hide-on-edit\" data-text=\"name\" data-bind=\"watch\" data-click=\"onRenameClicked\"></span> <div class=\"sidebar-panel-edit-bar hide-on-edit\"> <button type=\"button\" class=\"sidebar-panel-edit-button\" data-click=\"onRenameClicked\"><i class=\"fa fa-pencil-square-o\"></i></button> <button type=\"button\" data-class=\"isDefault:hidden\" class=\"sidebar-panel-edit-button\" data-click=\"onDeleteClicked\"><i class=\"fa fa-trash-o\"></i></button> </div> </div> <div class=\"props\"></div> </div> <button type=\"button\" style=\"position:absolute;right:5px;top:-30px\" class=\"components-panel-edit-button\" data-click=\"onAddPortClicked\"><i class=\"fa fa-plus\"></i></button> </div> <div class=\"items\"> </div> ";
// Exports
module.exports = code;

/***/ }),

/***/ 46709:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PropertyPanelTextRadioInput-module__Root--_kkm5{font-family:var(--font-family);color:var(--theme-color-fg-default);font-size:12px;display:flex}.PropertyPanelTextRadioInput-module__Option--Y0PHD{padding:6px 8px 7px;position:relative;cursor:pointer;background-color:var(--theme-color-bg-3);user-select:none;display:flex;flex-grow:1;justify-content:center}.PropertyPanelTextRadioInput-module__Option--Y0PHD:not(:last-child){border-right:2px solid var(--theme-color-bg-2)}.PropertyPanelTextRadioInput-module__Option--Y0PHD:hover{color:var(--theme-color-fg-highlight)}.PropertyPanelTextRadioInput-module__Option--Y0PHD.PropertyPanelTextRadioInput-module__is-selected--yKoqZ{background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-highlight)}.PropertyPanelTextRadioInput-module__Option--Y0PHD.PropertyPanelTextRadioInput-module__is-disabled--NuXE5{color:var(--theme-color-fg-muted);cursor:not-allowed}.PropertyPanelTextRadioInput-module__Input--HcNoF{position:absolute;opacity:0}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/property-panel/PropertyPanelTextRadioInput/PropertyPanelTextRadioInput.module.scss","webpack://./../noodl-core-ui/src/styles/scss-variables/length.scss"],"names":[],"mappings":"AAEA,iDACE,8BAAA,CACA,mCAAA,CACA,cAAA,CACA,YAAA,CAGF,mDACE,mBCV6B,CDW7B,iBAAA,CACA,cAAA,CACA,wCAAA,CACA,gBAAA,CACA,YAAA,CACA,WAAA,CACA,sBAAA,CAEA,oEACE,8CAAA,CAGF,yDACE,qCAAA,CAGF,0GACE,wCAAA,CACA,qCAAA,CAGF,0GACE,iCAAA,CACA,kBAAA,CAIJ,kDACE,iBAAA,CACA,SAAA","sourcesContent":["@use '../../../styles/scss-variables/length.scss';\n\n.Root {\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n  display: flex;\n}\n\n.Option {\n  padding: length.$property-panel-input-padding;\n  position: relative;\n  cursor: pointer;\n  background-color: var(--theme-color-bg-3);\n  user-select: none;\n  display: flex;\n  flex-grow: 1;\n  justify-content: center;\n\n  &:not(:last-child) {\n    border-right: 2px solid var(--theme-color-bg-2);\n  }\n\n  &:hover {\n    color: var(--theme-color-fg-highlight);\n  }\n\n  &.is-selected {\n    background-color: var(--theme-color-bg-1);\n    color: var(--theme-color-fg-highlight);\n  }\n\n  &.is-disabled {\n    color: var(--theme-color-fg-muted);\n    cursor: not-allowed;\n  }\n}\n\n.Input {\n  position: absolute;\n  opacity: 0;\n}\n","$property-panel-input-padding: 6px 8px 7px;\r\n$property-panel-input-size: 28px;\r\n$property-panel-small-xy-padding: 4px;\r\n\r\n$global-input-size: 36px;\r\n$global-input-size-small: 28px;\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PropertyPanelTextRadioInput-module__Root--_kkm5`,
	"Option": `PropertyPanelTextRadioInput-module__Option--Y0PHD`,
	"is-selected": `PropertyPanelTextRadioInput-module__is-selected--yKoqZ`,
	"is-disabled": `PropertyPanelTextRadioInput-module__is-disabled--NuXE5`,
	"Input": `PropertyPanelTextRadioInput-module__Input--HcNoF`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 46715:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDimensionHeight = function SvgDimensionHeight(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 30,
    viewBox: "0 0 31 30",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M4.86523 11.7159C4.86523 11.4397 5.08909 11.2159 5.36523 11.2159H24.9084C25.1846 11.2159 25.4084 11.4397 25.4084 11.7159V18.2844C25.4084 18.5606 25.1846 18.7844 24.9084 18.7844H5.36524C5.08909 18.7844 4.86523 18.5606 4.86523 18.2844V11.7159Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M16.0391 1.79535C16.0391 1.38114 15.7033 1.04535 15.2891 1.04535C14.8748 1.04535 14.5391 1.38114 14.5391 1.79535V6.26515L13.3506 5.07673C13.0577 4.78383 12.5829 4.78383 12.29 5.07673C11.9971 5.36962 11.9971 5.84449 12.29 6.13739L14.7529 8.60032C14.8891 8.7395 15.079 8.82587 15.2891 8.82587C15.5034 8.82587 15.6967 8.73597 15.8334 8.59182L18.2878 6.13739C18.5807 5.84449 18.5807 5.36962 18.2878 5.07673C17.9949 4.78383 17.5201 4.78383 17.2272 5.07673L16.0391 6.26483V1.79535Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M13.3506 24.9231C13.0577 25.2159 12.5829 25.2159 12.29 24.9231C11.9971 24.6302 11.9971 24.1553 12.29 23.8624L14.7586 21.3938C14.8564 21.296 14.9745 21.2308 15.0994 21.1984C15.132 21.1899 15.1654 21.1835 15.1996 21.1794C15.2439 21.1742 15.2885 21.1728 15.333 21.1754C15.5268 21.1866 15.7009 21.2714 15.8277 21.4023L18.2878 23.8624C18.5807 24.1553 18.5807 24.6302 18.2878 24.9231C17.9949 25.2159 17.5201 25.2159 17.2272 24.9231L16.0391 23.7349V28.2047C16.0391 28.6189 15.7033 28.9547 15.2891 28.9547C14.8748 28.9547 14.5391 28.6189 14.5391 28.2047V23.7346L13.3506 24.9231Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDimensionHeight);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "af827782b944ffe0ca1eea7c94b4f7e8.svg");

/***/ }),

/***/ 46740:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgArrowLeft = function SvgArrowLeft(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.19672 11.9979C3.23672 11.9079 3.28672 11.8279 3.35672 11.7579L10.1067 5.00794C10.3967 4.71794 10.8767 4.71794 11.1667 5.00794C11.4567 5.29794 11.4567 5.77794 11.1667 6.06794L5.69672 11.5379H20.3867C20.7967 11.5379 21.1367 11.8779 21.1367 12.2879C21.1367 12.6979 20.7967 13.0379 20.3867 13.0379H5.69672L11.1667 18.5079C11.4567 18.7979 11.4567 19.2779 11.1667 19.5679C11.0167 19.7179 10.8267 19.7879 10.6367 19.7879C10.4467 19.7879 10.2567 19.7179 10.1067 19.5679L3.35672 12.8179C3.28672 12.7479 3.23672 12.6679 3.19672 12.5779C3.11672 12.3979 3.11672 12.1879 3.19672 12.0079V11.9979Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgArrowLeft);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "903d2d6fd092dd9c46b647757a70d2f7.svg");

/***/ }),

/***/ 46901:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ useOnUnmount)
/* harmony export */ });
/* harmony import */ var _useOnMount__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13484);

function useOnUnmount(onUnmount) {
    (0,_useOnMount__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .A)(() => onUnmount);
}


/***/ }),

/***/ 46922:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDropdown = function SvgDropdown(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.30713 10.7355H25.8038C26.356 10.7355 26.8038 11.1832 26.8038 11.7355V19.1085C26.8038 19.6607 26.356 20.1817 25.8038 20.1817H4.30713C3.75484 20.1817 3.30713 19.6607 3.30713 19.1085V11.7355C3.30713 11.1832 3.75484 10.7355 4.30713 10.7355ZM24.6272 14.7051L22.0597 17.2726C21.7668 17.5655 21.2919 17.5655 20.999 17.2726L18.4315 14.7051C18.1386 14.4122 18.1386 13.9373 18.4315 13.6445C18.7244 13.3516 19.1993 13.3516 19.4922 13.6445L21.5294 15.6816L23.5666 13.6445C23.8595 13.3516 24.3343 13.3516 24.6272 13.6445C24.9201 13.9373 24.9201 14.4122 24.6272 14.7051Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDropdown);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "7e0ca39845c91e79bd3c53f7731f4109.svg");

/***/ }),

/***/ 46998:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   getCloudServices: () => (/* binding */ getCloudServices),
/* harmony export */   projectFromDirectory: () => (/* binding */ projectFromDirectory),
/* harmony export */   setCloudServices: () => (/* binding */ setCloudServices),
/* harmony export */   unzipIntoDirectory: () => (/* binding */ unzipIntoDirectory)
/* harmony export */ });
/* harmony import */ var _noodl_utils_bugtracker__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(90962);
/* harmony import */ var _noodl_utils_filesystem__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(38656);
/* harmony import */ var _noodl_utils_filesystem__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_noodl_utils_filesystem__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47821);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_shared_model__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _views_popuplayer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(45653);
/* harmony import */ var _views_popuplayer__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_views_popuplayer__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _views_ToastLayer_ToastLayer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(80424);
/* harmony import */ var _projectmodel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6203);
/* harmony import */ var _noodl_models_ProjectPatches_applypatches__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(26732);
/* harmony import */ var _noodl_models_ProjectPatches_applypatches__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_noodl_models_ProjectPatches_applypatches__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _noodl_platform__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(37218);








const supportedProjectVersion = 4;
function projectFromDirectory(projectdir, callback, args) {
    _noodl_utils_bugtracker__WEBPACK_IMPORTED_MODULE_0__/* .bugtracker */ .$.debug('ProjectModel.fromDirectory');
    _projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.readJSONFromDirectory(projectdir, function (content) {
        if (content) {
            const openProject = () => {
                // Before opening the project, we need to patch it, if necessary
                (0,_noodl_models_ProjectPatches_applypatches__WEBPACK_IMPORTED_MODULE_6__.applyPatches)(content);
                // Disable model listeners while loading project, otherwise this will bog down large projects
                (_shared_model__WEBPACK_IMPORTED_MODULE_2___default()._listenersEnabled) = false;
                const project = _projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.fromJSON(content);
                (_shared_model__WEBPACK_IMPORTED_MODULE_2___default()._listenersEnabled) = true;
                project._retainedProjectDirectory = projectdir;
                // Check if there are any packages
                project.readModules(() => {
                    callback(project);
                });
            };
            //is project version incompatible?
            if (content.version > supportedProjectVersion) {
                _views_ToastLayer_ToastLayer__WEBPACK_IMPORTED_MODULE_4__.ToastLayer.hideAll();
                _views_popuplayer__WEBPACK_IMPORTED_MODULE_3___default().instance.showErrorModal({
                    message: 'This project was saved with a newer version of Noodl.<br/><a href="https://noodl.net" target="_blank">Click here to download</a>',
                    title: 'Error opening project'
                });
                callback();
                return;
            }
            //do we need to upgrade the project?
            if (args && args.showUpgradeModal && content.version < supportedProjectVersion) {
                _views_ToastLayer_ToastLayer__WEBPACK_IMPORTED_MODULE_4__.ToastLayer.hideAll();
                _views_popuplayer__WEBPACK_IMPORTED_MODULE_3___default().instance.showConfirmModal({
                    message: 'This project was saved with an older version of Noodl.<br/>Projects saved with with this version of Noodl will be incompatible with older versions.<br/><br/>Do you want to open and upgrade the project?',
                    title: 'Upgrade project?',
                    confirmLabel: 'Upgrade',
                    cancelLabel: 'Cancel',
                    onConfirm: openProject,
                    onCancel: () => callback()
                });
            }
            else {
                openProject();
            }
        }
        else {
            _noodl_utils_bugtracker__WEBPACK_IMPORTED_MODULE_0__/* .bugtracker */ .$.track('ProjectModel.fromDirectory readJSONFromDirectory failed', {
                dir: projectdir,
                dirContent: _noodl_utils_filesystem__WEBPACK_IMPORTED_MODULE_1___default().instance.readDirectorySync(projectdir)
            });
            callback(); // Failed to read project
        }
    });
}
// Extracts a zip into a directory and returns the project in a callback
// TODO: Replace partly with Filesystem.instance.unzipIntoDirectory
async function unzipIntoDirectory(url, dirEntry, callback, args) {
    // Make sure the folder is empty
    const isEmpty = await _noodl_platform__WEBPACK_IMPORTED_MODULE_7__.filesystem.isDirectoryEmpty(dirEntry);
    if (!isEmpty) {
        callback({
            result: 'failure',
            message: 'Folder must be empty'
        });
        return;
    }
    // Load zip file from URL
    try {
        await _noodl_platform__WEBPACK_IMPORTED_MODULE_7__.filesystem.unzipUrl(url, dirEntry);
    }
    catch (e) {
        callback({
            result: 'failure',
            message: 'Failed to extract'
        });
        return;
    }
    if (args && args.skipLoad) {
        // Skip loading the project?
        callback({
            result: 'success',
            dirEntry: dirEntry
        });
        return;
    }
    // Project extracted successfully, load it
    projectFromDirectory(dirEntry, function (project) {
        if (!project) {
            callback({
                result: 'failure',
                message: 'Failed to load project'
            });
            return;
        }
        // Store the project again, this will make it a unique project by
        // forcing it to generate a project id
        project.id = undefined;
        //project.name = dirEntry.split('/').pop();
        project.toDirectory(project._retainedProjectDirectory, function (res) {
            if (res.result === 'success')
                callback({
                    result: 'success',
                    project: project
                });
            else
                callback({
                    result: 'failure',
                    message: 'Failed to clone project'
                });
        });
    });
}
function setCloudServices(project, b) {
    project.setMetaData('cloudservices', {
        instanceId: b.id,
        endpoint: b.endpoint || b.url,
        appId: b.appId
    });
    project.notifyListeners('cloudServicesChanged');
}
function getCloudServices(project) {
    const cloudServices = project.getMetaData('cloudservices');
    if (!cloudServices) {
        return {
            id: undefined,
            endpoint: undefined,
            appId: undefined
        };
    }
    return {
        id: cloudServices.instanceId,
        endpoint: cloudServices.endpoint,
        appId: cloudServices.appId
    };
}


/***/ }),

/***/ 47426:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  h: () => (/* binding */ LocalProjectsModel)
});

// EXTERNAL MODULE: external "node:path"
var external_node_path_ = __webpack_require__(76760);
var external_node_path_default = /*#__PURE__*/__webpack_require__.n(external_node_path_);
// EXTERNAL MODULE: ./src/editor/src/store/GitStore.ts + 1 modules
var GitStore = __webpack_require__(72316);
// EXTERNAL MODULE: external "electron-store"
var external_electron_store_ = __webpack_require__(49468);
var external_electron_store_default = /*#__PURE__*/__webpack_require__.n(external_electron_store_);
// EXTERNAL MODULE: external "underscore"
var external_underscore_ = __webpack_require__(80002);
// EXTERNAL MODULE: ../noodl-git/src/core/open.ts
var core_open = __webpack_require__(89523);
// EXTERNAL MODULE: ../noodl-git/src/core/trampoline/trampoline-askpass-handler.ts
var trampoline_askpass_handler = __webpack_require__(58848);
// EXTERNAL MODULE: ../noodl-platform/src/index.ts + 10 modules
var src = __webpack_require__(37218);
// EXTERNAL MODULE: ./src/editor/src/utils/getDocsEndpoint.ts
var getDocsEndpoint = __webpack_require__(41160);
;// ./src/editor/src/utils/forge/template/providers/http-template-provider.ts

/**
 * HttpTemplateProvider is only for downloading templates via HTTP.
 */
class HttpTemplateProvider {
    get name() {
        return 'Http';
    }
    list(_options) {
        return Promise.resolve([]);
    }
    canDownload(_url) {
        return Promise.resolve(true);
    }
    async download(url, destination, progress) {
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                Accept: 'application/zip'
            }
        });
        const arrayBuffer = await response.arrayBuffer();
        await src.filesystem.writeFile(destination, Buffer.from(arrayBuffer));
    }
}

;// ./src/editor/src/utils/forge/template/providers/noodl-docs-template-provider.ts
/**
 * List all templates from Noodl docs,
 * currently saved on GitHub and served via GitHub pages.
 */
class NoodlDocsTemplateProvider {
    get name() {
        return 'https://docs.noodl.net';
    }
    constructor(getDocsEndpoint) {
        this.getDocsEndpoint = getDocsEndpoint;
    }
    async list(_options) {
        const endpoint = this.getDocsEndpoint();
        const templates = await this.makeRequest(endpoint);
        templates.forEach((t) => {
            t.iconURL = endpoint + '/projecttemplates/' + t.iconURL;
            t.projectURL = endpoint + '/projecttemplates/' + t.projectURL;
            if (t.cloudServicesTemplateURL !== undefined && !t.cloudServicesTemplateURL.startsWith('http')) {
                t.cloudServicesTemplateURL = endpoint + '/projecttemplates/' + t.cloudServicesTemplateURL;
            }
        });
        return templates;
    }
    canDownload(_url) {
        return Promise.resolve(false);
    }
    download(_url, _destination, _progress) {
        throw new Error('Method not supported.');
    }
    async makeRequest(endpoint) {
        const url = endpoint + '/projecttemplates/index.json' + '?' + new Date().getTime();
        const response = await fetch(url);
        return (await response.json());
    }
}

;// ./src/editor/src/utils/forge/template/template-registry.ts

/**
 * @example List templates
 * ```ts
 *  const templates = await templateRegistry.list({});
 * ```
 *
 * @example Download a template
 * ```ts
 *  const templateUrl = "https:://my-template.url/template.zip";
 *  const zipPath = await templateRegistry.download({ templateUrl });
 * ```
 */
class TemplateRegistry {
    constructor(providers) {
        this.providers = providers;
    }
    async list(options) {
        let collection = [];
        for (let index = 0; index < this.providers.length; index++) {
            const provider = this.providers[index];
            try {
                const response = await provider.list(options);
                if (response.length > 0) {
                    collection = [...collection, ...response];
                }
            }
            catch (error) {
                console.error(`Error when listing templates via '${provider.name}' provider`);
                console.error(error);
            }
        }
        return collection;
    }
    /**
     * Download a project template.
     */
    async download({ templateUrl }) {
        const templateDir = src.platform.getUserDataPath() + '/projecttemplates';
        const templateName = templateUrl.replace(/[:\/?=]/g, '-');
        const templatePath = templateDir + '/' + templateName;
        const templateZipPath = templatePath + '-unzipped';
        if (!src.filesystem.exists(templateZipPath)) {
            // Make sure we have the template folder
            await src.filesystem.makeDirectory(templateDir);
            // Download the template
            await this.downloadViaProvider(templateUrl, templatePath);
            // Unzip
            await src.filesystem.makeDirectory(templateZipPath);
            await src.filesystem.unzipUrl(templatePath, templateZipPath);
        }
        return templateZipPath;
    }
    async downloadViaProvider(templateUrl, destination) {
        for (let index = 0; index < this.providers.length; index++) {
            const provider = this.providers[index];
            try {
                if (await provider.canDownload(templateUrl)) {
                    await provider.download(templateUrl, destination, () => {
                        // TODO: Handle progress (not something we did in the older version)
                    });
                    return;
                }
            }
            catch (error) {
                console.error(`Error when downloading template via '${provider.name}' provider`);
                console.error(error);
            }
        }
        throw new Error(`Cannot find a valid template provider for: '${templateUrl}'`);
    }
}

;// ./src/editor/src/utils/forge/index.ts




// The order of the providers matters,
// when looking for a template it will take the first one that allows it.
const templateRegistry = new TemplateRegistry([
    new NoodlDocsTemplateProvider(getDocsEndpoint/* default */.A),
    new HttpTemplateProvider()
]);


// EXTERNAL MODULE: ./src/shared/model.js
var model = __webpack_require__(47821);
var model_default = /*#__PURE__*/__webpack_require__.n(model);
// EXTERNAL MODULE: ./src/editor/src/models/migration/ProjectScanner.ts
var ProjectScanner = __webpack_require__(89911);
// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.editor.ts
var projectmodel_editor = __webpack_require__(46998);
// EXTERNAL MODULE: ./src/editor/src/services/GitHubOAuthService.ts
var GitHubOAuthService = __webpack_require__(5576);
// EXTERNAL MODULE: ./src/editor/src/utils/filesystem.js
var filesystem = __webpack_require__(38656);
var filesystem_default = /*#__PURE__*/__webpack_require__.n(filesystem);
// EXTERNAL MODULE: ./src/editor/src/utils/tracker/index.ts + 1 modules
var tracker = __webpack_require__(38986);
// EXTERNAL MODULE: ./src/editor/src/utils/utils.ts
var utils = __webpack_require__(93015);
;// ./src/editor/src/utils/LocalProjectsModel.ts















class LocalProjectsModel extends (model_default()) {
    constructor() {
        super(...arguments);
        this.projectEntries = [];
        this.recentProjectsStore = new (external_electron_store_default())({
            name: 'recently_opened_project'
        });
        /**
         * Persistent store for runtime version cache
         * Survives app restarts to avoid re-detecting runtime on every launch
         */
        this.runtimeCacheStore = new (external_electron_store_default())({
            name: 'project_runtime_cache'
        });
        /**
         * Cache for runtime version info - keyed by project directory path
         * Loaded from persistent store on init, saved on updates
         */
        this.runtimeInfoCache = new Map();
        /**
         * Set of project directories currently being detected
         */
        this.detectingProjects = new Set();
    }
    async fetch() {
        // Load runtime cache from persistent store
        this.loadRuntimeCache();
        // Fetch projects from local storage and verify project folders
        const folders = (this.recentProjectsStore.get('recentProjects') || []);
        const existingFolders = folders.filter((x) => src.filesystem.exists(x.retainedProjectDirectory));
        existingFolders.sort((a, b) => b.latestAccessed - a.latestAccessed);
        if (!this.projectEntries || (this.projectEntries && !(0,external_underscore_.isEqual)(this.projectEntries, existingFolders))) {
            this.projectEntries = existingFolders;
            this.store();
            this.notifyListeners('myProjectsChanged');
        }
    }
    // Store model to local storage
    store() {
        if (!this.projectEntries)
            return; // Don't store if projects are not loaded
        this.recentProjectsStore.set('recentProjects', this.projectEntries);
    }
    containsProjectWithId(id) {
        return !!this.projectEntries.find((p) => p.id === id);
    }
    // Get all project directories, sorted
    getProjects() {
        return this.projectEntries;
    }
    getProjectEntryWithId(id) {
        return this.projectEntries.find((p) => p.id === id);
    }
    // Update latests accessed time for project
    touchProject(projectEntry) {
        projectEntry.latestAccessed = Date.now();
        this.store();
        this.notifyListeners('myProjectsChanged');
    }
    // Load a project
    loadProject(projectEntry) {
        tracker.tracker.track('Load Local Project');
        return new Promise((resolve) => {
            (0,projectmodel_editor.projectFromDirectory)(projectEntry.retainedProjectDirectory, (project) => {
                if (!project) {
                    resolve(null);
                    return;
                }
                project.id = projectEntry.id; // Assign the project the id stored in the project dir entry
                project.name = projectEntry.name; // Also assign the name
                this.touchProject(projectEntry);
                this.bindProject(project);
                // Initialize Git authentication for this project
                this.setCurrentGlobalGitAuth(projectEntry.id);
                resolve(project);
            });
        });
    }
    // Bind to a loaded project, update model when renamed of when the thumbnail is updated
    bindProject(project) {
        project
            .off(this)
            .on('renamed', () => {
            const projectdir = this.getProjectEntryWithId(project.id);
            if (projectdir) {
                this.renameProject(project.id, project.name ? project.name : 'Untitled');
                project._retainedProjectDirectory = projectdir.retainedProjectDirectory;
            }
        }, this)
            .on('thumbnailChanged', () => {
            const projectdir = this.getProjectEntryWithId(project.id);
            if (projectdir)
                projectdir.thumbURI = project.getThumbnailURI();
            this.store();
        }, this);
    }
    renameProject(id, name) {
        const projectEntry = this.getProjectEntryWithId(id);
        if (!projectEntry)
            return;
        projectEntry.name = name;
        this.store();
        this.notifyListeners('myProjectsChanged');
    }
    // Create a new project dir entry
    _addProject(project) {
        if (!project._retainedProjectDirectory)
            return;
        // Push directory entry
        const id = (0,utils.guid)();
        this.projectEntries.push({
            retainedProjectDirectory: project._retainedProjectDirectory,
            latestAccessed: Date.now(),
            id: id, // Generate a new project id (will be used internally to store project specific local settings)
            name: project.name ? project.name : 'Untitled',
            thumbURI: project.getThumbnailURI()
        });
        project.id = id;
        // Store the project model
        this.bindProject(project);
        this.store();
        this.notifyListeners('myProjectsChanged');
    }
    removeProject(projectId) {
        const idx = this.projectEntries.findIndex((p) => p.id === projectId);
        if (idx !== -1) {
            this.projectEntries.splice(idx, 1);
            this.store();
            this.notifyListeners('myProjectsChanged');
        }
    }
    // Given a path to the project zip file locally, unzip it and launch the
    // editor
    _unzipAndLaunchProject(path, dirEntry, fn, options) {
        (0,projectmodel_editor.unzipIntoDirectory)(path, dirEntry, (r) => {
            if (r.result !== 'success') {
                fn(r);
                return;
            }
            // Project successfully created
            r.project.name = options.name || 'Untitled';
            this._addProject(r.project);
            fn(r.project);
        }, { noAuth: true });
    }
    async newProject(fn, options) {
        tracker.tracker.track('New Local Project');
        const name = (options === null || options === void 0 ? void 0 : options.name) || 'Untitled';
        const dirEntry = (options === null || options === void 0 ? void 0 : options.path) || src.filesystem.makeUniquePath(src.platform.getDocumentsPath() + name);
        await src.filesystem.makeDirectory(dirEntry);
        const projectTemplate = options === null || options === void 0 ? void 0 : options.projectTemplate;
        if (projectTemplate) {
            const templatePath = await templateRegistry.download({ templateUrl: projectTemplate });
            // Copy unzipped project template
            filesystem_default().instance.copyRecursiveSync(templatePath, dirEntry, {
                filter(src) {
                    //ignore all files in .git/
                    return !src.includes((external_node_path_default()).sep + '.git' + (external_node_path_default()).sep);
                }
            });
            // Project extracted successfully, load it
            (0,projectmodel_editor.projectFromDirectory)(dirEntry, (project) => {
                if (!project) {
                    fn();
                    return;
                }
                project.name = name; //update the name from the template
                project.runtimeVersion = 'react19'; // NEW projects default to React 19
                // Store the project, this will make it a unique project by
                // forcing it to generate a project id
                this._addProject(project);
                project.toDirectory(project._retainedProjectDirectory, (res) => {
                    if (res.result === 'success') {
                        fn(project);
                    }
                    else {
                        fn();
                    }
                });
            });
        }
        else {
            // Default template path
            const defaultTemplatePath = './external/projecttemplates/helloworld.zip';
            // Check if template exists, otherwise create an empty project
            if (src.filesystem.exists(defaultTemplatePath)) {
                this._unzipAndLaunchProject(defaultTemplatePath, dirEntry, fn, options);
            }
            else {
                console.warn('Default project template not found, creating empty project');
                // Create minimal project.json for empty project
                const minimalProject = {
                    name: name,
                    components: [],
                    settings: {},
                    runtimeVersion: 'react19' // NEW projects default to React 19
                };
                await src.filesystem.writeFile(src.filesystem.join(dirEntry, 'project.json'), JSON.stringify(minimalProject, null, 2));
                // Load the newly created empty project
                (0,projectmodel_editor.projectFromDirectory)(dirEntry, (project) => {
                    if (!project) {
                        fn();
                        return;
                    }
                    project.name = name;
                    project.runtimeVersion = 'react19'; // Ensure it's set
                    this._addProject(project);
                    fn(project);
                });
            }
        }
    }
    openProjectFromFolder(direntry) {
        //check if this project is already in the list and if so just open it
        const projectEntry = this.projectEntries.find((p) => p.retainedProjectDirectory === direntry);
        if (projectEntry) {
            return this.loadProject(projectEntry);
        }
        //project isn't in the list, add it
        return new Promise((resolve, reject) => {
            (0,projectmodel_editor.projectFromDirectory)(direntry, (project) => {
                if (!project) {
                    reject(null);
                    return;
                }
                this._addProject(project);
                resolve(project);
            });
        });
    }
    /**
     * Check if this project is in a git repository.
     *
     * @param project
     * @returns
     */
    async isGitProject(project) {
        const gitPath = await (0,core_open/* getTopLevelWorkingDirectory */.I)(project._retainedProjectDirectory);
        return gitPath !== null;
    }
    setCurrentGlobalGitAuth(projectId) {
        const func = async (endpoint) => {
            if (endpoint.includes('github.com')) {
                // Priority 1: Check for global OAuth token from GitHubOAuthService
                try {
                    const token = await GitHubOAuthService/* GitHubOAuthService */.W.instance.getToken();
                    const user = GitHubOAuthService/* GitHubOAuthService */.W.instance.getCurrentUser();
                    if (token) {
                        console.log('[Git Auth] Using GitHub OAuth token for:', endpoint, 'user:', user === null || user === void 0 ? void 0 : user.login);
                        return {
                            username: (user === null || user === void 0 ? void 0 : user.login) || 'oauth',
                            password: token
                        };
                    }
                }
                catch (err) {
                    console.warn('[Git Auth] Failed to get OAuth token:', err);
                }
                // Priority 2: Fall back to project-specific PAT
                const config = await GitStore/* GitStore */.W.get('github', projectId);
                if (config === null || config === void 0 ? void 0 : config.password) {
                    console.log('[Git Auth] Using project PAT for:', endpoint);
                    return {
                        username: 'noodl',
                        password: config.password
                    };
                }
                // No credentials available
                console.warn('[Git Auth] No GitHub credentials found for:', endpoint);
                return {
                    username: 'noodl',
                    password: ''
                };
            }
            else {
                // Non-GitHub providers use project-specific credentials only
                const config = await GitStore/* GitStore */.W.get('unknown', projectId);
                return {
                    username: config === null || config === void 0 ? void 0 : config.username,
                    password: config === null || config === void 0 ? void 0 : config.password
                };
            }
        };
        (0,trampoline_askpass_handler/* setRequestGitAccount */.x$)(func);
    }
    // =========================================================================
    // Runtime Version Detection Methods
    // =========================================================================
    /**
     * Load runtime cache from persistent store
     */
    loadRuntimeCache() {
        try {
            const cached = this.runtimeCacheStore.get('cache');
            if (cached) {
                this.runtimeInfoCache = new Map(Object.entries(cached));
            }
        }
        catch (error) {
            console.warn('Failed to load runtime cache:', error);
            this.runtimeInfoCache = new Map();
        }
    }
    /**
     * Save runtime cache to persistent store
     */
    saveRuntimeCache() {
        try {
            const cacheObject = Object.fromEntries(this.runtimeInfoCache.entries());
            this.runtimeCacheStore.set('cache', cacheObject);
        }
        catch (error) {
            console.error('Failed to save runtime cache:', error);
        }
    }
    /**
     * Get cached runtime info for a project, or null if not yet detected
     * @param projectPath - The project directory path
     */
    getRuntimeInfo(projectPath) {
        return this.runtimeInfoCache.get(projectPath) || null;
    }
    /**
     * Check if runtime detection is currently in progress for a project
     * @param projectPath - The project directory path
     */
    isDetectingRuntime(projectPath) {
        return this.detectingProjects.has(projectPath);
    }
    /**
     * Get projects with their runtime info (extended interface)
     * Returns projects enriched with cached runtime detection status
     */
    getProjectsWithRuntime() {
        return this.projectEntries.map((project) => ({
            ...project,
            runtimeInfo: this.getRuntimeInfo(project.retainedProjectDirectory),
            runtimeDetectionPending: this.isDetectingRuntime(project.retainedProjectDirectory)
        }));
    }
    /**
     * Detect runtime version for a single project.
     * Results are cached and listeners are notified.
     * @param projectPath - Path to the project directory
     * @returns The detected runtime version info
     */
    async detectProjectRuntime(projectPath) {
        // Return cached result if available
        const cached = this.runtimeInfoCache.get(projectPath);
        if (cached) {
            return cached;
        }
        // Skip if already detecting
        if (this.detectingProjects.has(projectPath)) {
            // Wait for existing detection to complete by polling
            return new Promise((resolve) => {
                const checkCached = () => {
                    const result = this.runtimeInfoCache.get(projectPath);
                    if (result) {
                        resolve(result);
                    }
                    else if (this.detectingProjects.has(projectPath)) {
                        setTimeout(checkCached, 100);
                    }
                    else {
                        // Detection finished but no result - return unknown
                        resolve({ version: 'unknown', confidence: 'low', indicators: ['Detection failed'] });
                    }
                };
                checkCached();
            });
        }
        // Mark as detecting
        this.detectingProjects.add(projectPath);
        this.notifyListeners('runtimeDetectionStarted', projectPath);
        try {
            const runtimeInfo = await (0,ProjectScanner/* detectRuntimeVersion */.Cb)(projectPath);
            this.runtimeInfoCache.set(projectPath, runtimeInfo);
            this.saveRuntimeCache(); // Persist to disk
            this.notifyListeners('runtimeDetectionComplete', projectPath, runtimeInfo);
            return runtimeInfo;
        }
        catch (error) {
            console.error(`Failed to detect runtime for ${projectPath}:`, error);
            const fallback = {
                version: 'unknown',
                confidence: 'low',
                indicators: ['Detection error: ' + (error instanceof Error ? error.message : 'Unknown error')]
            };
            this.runtimeInfoCache.set(projectPath, fallback);
            this.saveRuntimeCache(); // Persist to disk
            this.notifyListeners('runtimeDetectionComplete', projectPath, fallback);
            return fallback;
        }
        finally {
            this.detectingProjects.delete(projectPath);
        }
    }
    /**
     * Detect runtime version for all projects in the list (background)
     * Useful for pre-populating the cache when the projects view loads
     */
    async detectAllProjectRuntimes() {
        const projects = this.getProjects();
        // Detect in parallel but don't wait for all to complete
        // Instead, trigger detection and let events update the UI
        for (const project of projects) {
            // Don't await - let them run in background
            this.detectProjectRuntime(project.retainedProjectDirectory).catch(() => {
                // Errors are handled in detectProjectRuntime
            });
        }
    }
    /**
     * Check if a project is a legacy project (React 17)
     * @param projectPath - Path to the project directory
     * @returns True if project is detected as React 17
     */
    isLegacyProject(projectPath) {
        const info = this.getRuntimeInfo(projectPath);
        return (info === null || info === void 0 ? void 0 : info.version) === 'react17';
    }
    /**
     * Clear runtime cache for a specific project (e.g., after migration)
     * @param projectPath - Path to the project directory
     */
    clearRuntimeCache(projectPath) {
        this.runtimeInfoCache.delete(projectPath);
        this.saveRuntimeCache(); // Persist the change
        this.notifyListeners('runtimeCacheCleared', projectPath);
    }
    /**
     * Clear all runtime cache (useful for debugging or forcing re-detection)
     */
    clearAllRuntimeCache() {
        this.runtimeInfoCache.clear();
        this.saveRuntimeCache();
        this.notifyListeners('allRuntimeCacheCleared');
    }
}
LocalProjectsModel.instance = new LocalProjectsModel();


/***/ }),

/***/ 47511:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BetaToolRunner = exports.Messages = void 0;
const tslib_1 = __webpack_require__(84499);
const resource_1 = __webpack_require__(39929);
const constants_1 = __webpack_require__(66262);
const headers_1 = __webpack_require__(79973);
const beta_parser_1 = __webpack_require__(96047);
const BetaMessageStream_1 = __webpack_require__(97444);
const BetaToolRunner_1 = __webpack_require__(19679);
const BatchesAPI = tslib_1.__importStar(__webpack_require__(82519));
const batches_1 = __webpack_require__(82519);
const DEPRECATED_MODELS = {
    'claude-1.3': 'November 6th, 2024',
    'claude-1.3-100k': 'November 6th, 2024',
    'claude-instant-1.1': 'November 6th, 2024',
    'claude-instant-1.1-100k': 'November 6th, 2024',
    'claude-instant-1.2': 'November 6th, 2024',
    'claude-3-sonnet-20240229': 'July 21st, 2025',
    'claude-3-opus-20240229': 'January 5th, 2026',
    'claude-2.1': 'July 21st, 2025',
    'claude-2.0': 'July 21st, 2025',
    'claude-3-7-sonnet-latest': 'February 19th, 2026',
    'claude-3-7-sonnet-20250219': 'February 19th, 2026',
};
class Messages extends resource_1.APIResource {
    constructor() {
        super(...arguments);
        this.batches = new BatchesAPI.Batches(this._client);
    }
    create(params, options) {
        const { betas, ...body } = params;
        if (body.model in DEPRECATED_MODELS) {
            console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
        }
        let timeout = this._client._options.timeout;
        if (!body.stream && timeout == null) {
            const maxNonstreamingTokens = constants_1.MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;
            timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
        }
        return this._client.post('/v1/messages?beta=true', {
            body,
            timeout: timeout ?? 600000,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
                options?.headers,
            ]),
            stream: params.stream ?? false,
        });
    }
    /**
     * Send a structured list of input messages with text and/or image content, along with an expected `output_format` and
     * the response will be automatically parsed and available in the `parsed_output` property of the message.
     *
     * @example
     * ```ts
     * const message = await client.beta.messages.parse({
     *   model: 'claude-3-5-sonnet-20241022',
     *   max_tokens: 1024,
     *   messages: [{ role: 'user', content: 'What is 2+2?' }],
     *   output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'),
     * });
     *
     * console.log(message.parsed_output?.answer); // 4
     * ```
     */
    parse(params, options) {
        options = {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(params.betas ?? []), 'structured-outputs-2025-11-13'].toString() },
                options?.headers,
            ]),
        };
        return this.create(params, options).then((message) => (0, beta_parser_1.parseBetaMessage)(message, params, { logger: this._client.logger ?? console }));
    }
    /**
     * Create a Message stream
     */
    stream(body, options) {
        return BetaMessageStream_1.BetaMessageStream.createMessage(this, body, options);
    }
    /**
     * Count the number of tokens in a Message.
     *
     * The Token Count API can be used to count the number of tokens in a Message,
     * including tools, images, and documents, without creating it.
     *
     * Learn more about token counting in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
     *
     * @example
     * ```ts
     * const betaMessageTokensCount =
     *   await client.beta.messages.countTokens({
     *     messages: [{ content: 'string', role: 'user' }],
     *     model: 'claude-opus-4-5-20251101',
     *   });
     * ```
     */
    countTokens(params, options) {
        const { betas, ...body } = params;
        return this._client.post('/v1/messages/count_tokens?beta=true', {
            body,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() },
                options?.headers,
            ]),
        });
    }
    toolRunner(body, options) {
        return new BetaToolRunner_1.BetaToolRunner(this._client, body, options);
    }
}
exports.Messages = Messages;
var BetaToolRunner_2 = __webpack_require__(19679);
Object.defineProperty(exports, "BetaToolRunner", ({ enumerable: true, get: function () { return BetaToolRunner_2.BetaToolRunner; } }));
Messages.Batches = batches_1.Batches;
Messages.BetaToolRunner = BetaToolRunner_1.BetaToolRunner;
//# sourceMappingURL=messages.js.map

/***/ }),

/***/ 47539:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-split-view2 {
	position: relative;
	width: 100%;
	height: 100%;
}

.monaco-split-view2 > .sash-container {
	position: absolute;
	width: 100%;
	height: 100%;
	pointer-events: none;
}

.monaco-split-view2 > .sash-container > .monaco-sash {
	pointer-events: initial;
}

.monaco-split-view2 > .monaco-scrollable-element {
	width: 100%;
	height: 100%;
}

.monaco-split-view2 > .monaco-scrollable-element > .split-view-container {
	width: 100%;
	height: 100%;
	white-space: nowrap;
	position: relative;
}

.monaco-split-view2 > .monaco-scrollable-element > .split-view-container > .split-view-view {
	white-space: initial;
	position: absolute;
}

.monaco-split-view2 > .monaco-scrollable-element > .split-view-container > .split-view-view:not(.visible) {
	display: none;
}

.monaco-split-view2.vertical > .monaco-scrollable-element > .split-view-container > .split-view-view {
	width: 100%;
}

.monaco-split-view2.horizontal > .monaco-scrollable-element > .split-view-container > .split-view-view {
	height: 100%;
}

.monaco-split-view2.separator-border > .monaco-scrollable-element > .split-view-container > .split-view-view:not(:first-child)::before {
	content: ' ';
	position: absolute;
	top: 0;
	left: 0;
	z-index: 5;
	pointer-events: none;
	background-color: var(--separator-border);
}

.monaco-split-view2.separator-border.horizontal > .monaco-scrollable-element > .split-view-container > .split-view-view:not(:first-child)::before {
	height: 100%;
	width: 1px;
}

.monaco-split-view2.separator-border.vertical > .monaco-scrollable-element > .split-view-container > .split-view-view:not(:first-child)::before {
	height: 1px;
	width: 100%;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/splitview/splitview.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kBAAkB;CAClB,WAAW;CACX,YAAY;AACb;;AAEA;CACC,kBAAkB;CAClB,WAAW;CACX,YAAY;CACZ,oBAAoB;AACrB;;AAEA;CACC,uBAAuB;AACxB;;AAEA;CACC,WAAW;CACX,YAAY;AACb;;AAEA;CACC,WAAW;CACX,YAAY;CACZ,mBAAmB;CACnB,kBAAkB;AACnB;;AAEA;CACC,oBAAoB;CACpB,kBAAkB;AACnB;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,WAAW;AACZ;;AAEA;CACC,YAAY;AACb;;AAEA;CACC,YAAY;CACZ,kBAAkB;CAClB,MAAM;CACN,OAAO;CACP,UAAU;CACV,oBAAoB;CACpB,yCAAyC;AAC1C;;AAEA;CACC,YAAY;CACZ,UAAU;AACX;;AAEA;CACC,WAAW;CACX,WAAW;AACZ","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-split-view2 {\n\tposition: relative;\n\twidth: 100%;\n\theight: 100%;\n}\n\n.monaco-split-view2 > .sash-container {\n\tposition: absolute;\n\twidth: 100%;\n\theight: 100%;\n\tpointer-events: none;\n}\n\n.monaco-split-view2 > .sash-container > .monaco-sash {\n\tpointer-events: initial;\n}\n\n.monaco-split-view2 > .monaco-scrollable-element {\n\twidth: 100%;\n\theight: 100%;\n}\n\n.monaco-split-view2 > .monaco-scrollable-element > .split-view-container {\n\twidth: 100%;\n\theight: 100%;\n\twhite-space: nowrap;\n\tposition: relative;\n}\n\n.monaco-split-view2 > .monaco-scrollable-element > .split-view-container > .split-view-view {\n\twhite-space: initial;\n\tposition: absolute;\n}\n\n.monaco-split-view2 > .monaco-scrollable-element > .split-view-container > .split-view-view:not(.visible) {\n\tdisplay: none;\n}\n\n.monaco-split-view2.vertical > .monaco-scrollable-element > .split-view-container > .split-view-view {\n\twidth: 100%;\n}\n\n.monaco-split-view2.horizontal > .monaco-scrollable-element > .split-view-container > .split-view-view {\n\theight: 100%;\n}\n\n.monaco-split-view2.separator-border > .monaco-scrollable-element > .split-view-container > .split-view-view:not(:first-child)::before {\n\tcontent: ' ';\n\tposition: absolute;\n\ttop: 0;\n\tleft: 0;\n\tz-index: 5;\n\tpointer-events: none;\n\tbackground-color: var(--separator-border);\n}\n\n.monaco-split-view2.separator-border.horizontal > .monaco-scrollable-element > .split-view-container > .split-view-view:not(:first-child)::before {\n\theight: 100%;\n\twidth: 1px;\n}\n\n.monaco-split-view2.separator-border.vertical > .monaco-scrollable-element > .split-view-container > .split-view-view:not(:first-child)::before {\n\theight: 1px;\n\twidth: 100%;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 47821:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const { EventDispatcher } = __webpack_require__(11138);

var Model = function () {
  this.listeners = [];
  this.listenersOnce = [];
};

Model._listenersEnabled = true;

Model.prototype.on = function (event, listener, group) {
  this.listeners.push({
    event: event,
    listener: listener,
    group: group
  });

  if (this.listeners.length > 10000) {
    console.log('Warning: we have more that 10000 listeners on this model, is this sane?');
  }

  return this;
};

Model.prototype.once = function (event, listener) {
  this.listenersOnce.push({
    event: event,
    listener: listener
  });

  return this;
};

Model.prototype.set = function (args) {
  for (var i in args) this[i] = args[i];
  this.notifyListeners('change', {
    model: this
  });
};

function shouldNotify(l, event) {
  if (l.event.constructor == Array && l.event.indexOf(event) !== -1) {
    return true;
  } else if (l.event === event) {
    return true;
  } else if (l.event.indexOf !== undefined) {
    // Support for dot notation in subscription
    var index = l.event.indexOf(event);
    if (index > 0 && l.event[index - 1] === '.') {
      return true;
    }
  }
  return false;
}

Model.prototype.notifyListeners = function (event, args) {
  if (Model._listenersEnabled === false) return;

  for (let index = 0; index < this.listeners.length; index++) {
    const listener = this.listeners[index];
    if (shouldNotify(listener, event)) {
      listener.listener(args);
    }
  }

  if (this.listenersOnce.length > 0) {
    this.listenersOnce = this.listenersOnce.filter((listener) => {
      if (shouldNotify(listener, event)) {
        listener.listener(args);
        return false;
      }
      return true;
    });
  }

  // Dispatch global event
  EventDispatcher.instance.notifyListeners('Model.' + event, {
    model: this,
    args: args
  });

  return this;
};

Model.prototype.off = function (group) {
  for (var i = 0; i < this.listeners.length; i++) {
    if (this.listeners[i].group === group) {
      this.listeners.splice(i, 1);
      i--;
    }
  }

  return this;
};

Model.prototype.removeAllListeners = function () {
  this.listeners = [];
  this.listenersOnce = [];
};

module.exports = Model;


/***/ }),

/***/ 48032:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const { ProjectModel } = __webpack_require__(6203);

function isStyleUsedByNodeOrVariant(nodeOrVariant, portType, styleName) {
  const stylePortNames = nodeOrVariant
    .getPorts('input')
    .filter((p) => (p.type.name || p.type) === portType)
    .map((p) => p.name);

  return stylePortNames.some((portName) => {
    if (nodeOrVariant.parameters[portName] === styleName) return true;

    if (nodeOrVariant.stateParameters) {
      for (const state of Object.keys(nodeOrVariant.stateParameters)) {
        if (nodeOrVariant.stateParameters[state][portName] === styleName) return true;
      }
    }

    return false;
  });
}

function getStyleUsage(portType, styleName) {
  //check if any nodes are using the style
  //look in parameters, variants, and all visual states
  const components = ProjectModel.instance.getComponents();

  let nodeCount = 0;
  components.forEach((c) => {
    c.graph.forEachNode((node) => {
      if (isStyleUsedByNodeOrVariant(node, portType, styleName)) {
        nodeCount++;
      }
    });
  });

  const variants = ProjectModel.instance.getAllVariants();
  const variantCount = variants.filter((variant) => isStyleUsedByNodeOrVariant(variant, portType, styleName)).length;

  return { nodeCount, variantCount };
}

module.exports = {
  getStyleUsage
};


/***/ }),

/***/ 48153:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  CloudService: () => (/* reexport */ CloudService),
  CloudServiceEvent: () => (/* reexport */ CloudServiceEvent),
  Environment: () => (/* reexport */ Environment),
  ExternalCloudService: () => (/* reexport */ ExternalCloudService)
});

// EXTERNAL MODULE: ../noodl-platform/src/index.ts + 10 modules
var src = __webpack_require__(37218);
;// ./src/editor/src/models/CloudServices/ExternalCloudService.ts

class ExternalCloudService {
    async list() {
        const local = await src.JSONStorage.get('externalBrokers');
        return local.brokers || [];
    }
    async create(options) {
        const id = `${options.url}-${options.appId}`;
        const newBroker = {
            enabled: true,
            id,
            name: options.name,
            description: options.description,
            masterKey: options.masterKey,
            appId: options.appId,
            endpoint: options.url
        };
        const local = await src.JSONStorage.get('externalBrokers');
        const brokers = local.brokers || [];
        await src.JSONStorage.set('externalBrokers', { brokers: [...brokers, newBroker] });
        return {
            id: newBroker.id,
            appId: newBroker.appId,
            url: newBroker.endpoint,
            masterKey: newBroker.masterKey
        };
    }
    async update(options) {
        const local = await src.JSONStorage.get('externalBrokers');
        const brokers = local.brokers || [];
        // Find and update
        const broker = brokers.find((x) => x.id === options.id);
        if (!broker)
            return false;
        if (options.name)
            broker.name = options.name;
        if (options.description)
            broker.description = options.description;
        if (options.masterKey)
            broker.masterKey = options.masterKey;
        await src.JSONStorage.set('externalBrokers', { brokers });
        return true;
    }
    async delete(id) {
        const local = await src.JSONStorage.get('externalBrokers');
        const brokers = local.brokers || [];
        // Find the environment
        const found = brokers.find((b) => b.id === id);
        if (found) {
            // Delete the environment
            brokers.splice(brokers.indexOf(found), 1);
        }
        // Save the list
        await src.JSONStorage.set('externalBrokers', { brokers });
        return true;
    }
}
class Environment {
    constructor(item) {
        this.id = item.id;
        this.name = item.name;
        this.description = item.description;
        this.createdAt = '';
        this.masterKeyUpdatedAt = '';
        this.masterKey = item.masterKey;
        this.appId = item.appId;
        this.url = item.endpoint;
    }
}

;// ./src/editor/src/models/CloudServices/type.ts
var CloudServiceEvent;
(function (CloudServiceEvent) {
    CloudServiceEvent[CloudServiceEvent["ConfigUpdated"] = 0] = "ConfigUpdated";
    CloudServiceEvent[CloudServiceEvent["BackendUpdated"] = 1] = "BackendUpdated";
})(CloudServiceEvent || (CloudServiceEvent = {}));

// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.editor.ts
var projectmodel_editor = __webpack_require__(46998);
// EXTERNAL MODULE: ./src/editor/src/utils/model.ts
var model = __webpack_require__(81267);
;// ./src/editor/src/models/CloudServices/CloudService.ts




class CloudBackendService {
    get isLoading() {
        return this._isLoading;
    }
    get items() {
        return this._collection || [];
    }
    constructor(service) {
        this.service = service;
        this._isLoading = false;
        this._localExternal = new ExternalCloudService();
    }
    async fetch() {
        this._isLoading = true;
        try {
            // Fetch environments from local machine
            const localEnvironments = await this._localExternal.list();
            this._collection = localEnvironments.map((x) => new Environment(x));
        }
        finally {
            this._isLoading = false;
            this.service.notifyListeners(CloudServiceEvent.BackendUpdated);
        }
        return this._collection;
    }
    async fromProject(project) {
        const activeCloudServices = (0,projectmodel_editor.getCloudServices)(project);
        if (!this._collection) {
            await this.fetch();
        }
        return this.items.find((b) => {
            return b.url === activeCloudServices.endpoint && b.appId === activeCloudServices.appId;
        });
    }
    async create(options) {
        return await this._localExternal.create(options);
    }
    async update(options) {
        return await this._localExternal.update(options);
    }
    async delete(id) {
        return await this._localExternal.delete(id);
    }
}
class CloudService extends model/* Model */.K {
    get backend() {
        return this._backend;
    }
    constructor() {
        super();
        this._backend = new CloudBackendService(this);
    }
    reset() {
        this._backend = new CloudBackendService(this);
        this.notifyListeners(CloudServiceEvent.BackendUpdated);
    }
    /**
     * this should only be called when going between projects
     */
    async prefetch() {
        this.reset();
        await this.fetch();
    }
    async fetch() {
        await this.backend.fetch();
    }
    async getActiveEnvironment(project) {
        await this.backend.fetch();
        return this.backend.fromProject(project);
    }
}
CloudService.instance = new CloudService();

;// ./src/editor/src/models/CloudServices/index.ts





/***/ }),

/***/ 48237:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Is: () => (/* reexport safe */ _Title__WEBPACK_IMPORTED_MODULE_0__.Is),
/* harmony export */   hE: () => (/* reexport safe */ _Title__WEBPACK_IMPORTED_MODULE_0__.hE),
/* harmony export */   uM: () => (/* reexport safe */ _Title__WEBPACK_IMPORTED_MODULE_0__.uM)
/* harmony export */ });
/* harmony import */ var _Title__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(79015);



/***/ }),

/***/ 48418:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.router-pages-page {
  padding: 7px;
  margin: 2px;
  margin-right: 10px;
  margin-left: 10px;
  background-color: var(--theme-color-bg-2);
  display: flex;
  flex-grow: 1;
}

.router-pages-page:hover {
  background-color: var(--theme-color-bg-5);
}

.router-pages-component {
  color: var(--theme-color-fg-highlight);
}

.router-pages-path {
  color: var(--theme-color-fg-muted);
}

.router-pages-icon {
  content: url('../assets/icons/page.svg');
  width: 18px;
  opacity: 0.7;
  align-self: center;
  margin-right: 7px;
}

.router-pages-icon.start-page {
  content: url('../assets/icons/page-filled.svg');
}

.router-pages-label {
  color: var(--theme-color-fg-default-shy);
  margin: 5px;
  margin-right: 15px;
}

.router-pages-actions-icon {
  color: var(--theme-color-fg-default-shy);
  align-self: center;
  visibility: hidden;
  padding: 8px 15px;
}

.router-pages-page:hover .router-pages-actions-icon {
  visibility: visible;
}

.router-pages-actions-icon:hover {
  color: var(--theme-color-fg-highlight);
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/propertyeditor/pages.css"],"names":[],"mappings":"AAAA;EACE,YAAY;EACZ,WAAW;EACX,kBAAkB;EAClB,iBAAiB;EACjB,yCAAyC;EACzC,aAAa;EACb,YAAY;AACd;;AAEA;EACE,yCAAyC;AAC3C;;AAEA;EACE,sCAAsC;AACxC;;AAEA;EACE,kCAAkC;AACpC;;AAEA;EACE,wCAAwC;EACxC,WAAW;EACX,YAAY;EACZ,kBAAkB;EAClB,iBAAiB;AACnB;;AAEA;EACE,+CAA+C;AACjD;;AAEA;EACE,wCAAwC;EACxC,WAAW;EACX,kBAAkB;AACpB;;AAEA;EACE,wCAAwC;EACxC,kBAAkB;EAClB,kBAAkB;EAClB,iBAAiB;AACnB;;AAEA;EACE,mBAAmB;AACrB;;AAEA;EACE,sCAAsC;AACxC","sourcesContent":[".router-pages-page {\n  padding: 7px;\n  margin: 2px;\n  margin-right: 10px;\n  margin-left: 10px;\n  background-color: var(--theme-color-bg-2);\n  display: flex;\n  flex-grow: 1;\n}\n\n.router-pages-page:hover {\n  background-color: var(--theme-color-bg-5);\n}\n\n.router-pages-component {\n  color: var(--theme-color-fg-highlight);\n}\n\n.router-pages-path {\n  color: var(--theme-color-fg-muted);\n}\n\n.router-pages-icon {\n  content: url('../assets/icons/page.svg');\n  width: 18px;\n  opacity: 0.7;\n  align-self: center;\n  margin-right: 7px;\n}\n\n.router-pages-icon.start-page {\n  content: url('../assets/icons/page-filled.svg');\n}\n\n.router-pages-label {\n  color: var(--theme-color-fg-default-shy);\n  margin: 5px;\n  margin-right: 15px;\n}\n\n.router-pages-actions-icon {\n  color: var(--theme-color-fg-default-shy);\n  align-self: center;\n  visibility: hidden;\n  padding: 8px 15px;\n}\n\n.router-pages-page:hover .router-pages-actions-icon {\n  visibility: visible;\n}\n\n.router-pages-actions-icon:hover {\n  color: var(--theme-color-fg-highlight);\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 48541:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_proplist_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(44075);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_proplist_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_proplist_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_proplist_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_proplist_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 48968:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPlusCircle = function SvgPlusCircle(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.1367 3.75C7.58037 3.75 3.88672 7.44365 3.88672 12C3.88672 16.5563 7.58037 20.25 12.1367 20.25C16.6931 20.25 20.3867 16.5563 20.3867 12C20.3867 7.44365 16.6931 3.75 12.1367 3.75ZM2.38672 12C2.38672 6.61522 6.75194 2.25 12.1367 2.25C17.5215 2.25 21.8867 6.61522 21.8867 12C21.8867 17.3848 17.5215 21.75 12.1367 21.75C6.75194 21.75 2.38672 17.3848 2.38672 12Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.8867 8.25C12.8867 7.83579 12.5509 7.5 12.1367 7.5C11.7225 7.5 11.3867 7.83579 11.3867 8.25V11.25H8.38672C7.97251 11.25 7.63672 11.5858 7.63672 12C7.63672 12.4142 7.97251 12.75 8.38672 12.75H11.3867V15.75C11.3867 16.1642 11.7225 16.5 12.1367 16.5C12.5509 16.5 12.8867 16.1642 12.8867 15.75V12.75H15.8867C16.3009 12.75 16.6367 12.4142 16.6367 12C16.6367 11.5858 16.3009 11.25 15.8867 11.25H12.8867V8.25Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPlusCircle);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "86882f7730342f866439fac0f4b09e5e.svg");

/***/ }),

/***/ 49059:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCloudData = function SvgCloudData(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M15.6229 4.39038C14.706 4.08474 13.7296 4.00137 12.7741 4.14713C11.8186 4.29289 10.9115 4.66361 10.1274 5.22874C9.34332 5.79387 8.70476 6.53724 8.26434 7.39757C7.82391 8.25791 7.59424 9.21059 7.59424 10.1771C7.59424 10.5913 7.25845 10.9271 6.84424 10.9271C6.43002 10.9271 6.09424 10.5913 6.09424 10.1771C6.09424 9.50378 6.18371 8.83583 6.35852 8.19038C5.1808 8.09328 3.98352 8.50985 3.12945 9.35546C2.37945 10.1055 1.94945 11.1555 1.94945 12.2155C1.94945 13.2755 2.36945 14.3155 3.12945 15.0755C3.88945 15.8355 4.90945 16.2555 5.98945 16.2555H10.3447V15.4426V15.4426V12.2205V12.2205V12.2205C10.3447 10.9276 11.2951 9.92218 12.4658 9.28364C13.6648 8.62964 15.27 8.24832 17.002 8.24832C17.9064 8.24832 18.7763 8.3523 19.5718 8.54479C19.5543 8.4831 19.5358 8.42098 19.5163 8.35836C19.2281 7.43581 18.7248 6.59494 18.0479 5.90506C17.371 5.21517 16.5398 4.69602 15.6229 4.39038ZM10.3447 17.7655V18.6647C10.3447 19.9573 11.2952 20.9627 12.4658 21.6013C13.6648 22.2554 15.2699 22.6369 17.002 22.6369C18.734 22.6369 20.3392 22.2554 21.5382 21.6013C22.7087 20.9627 23.6592 19.9573 23.6592 18.6647V15.4426V15.4426V12.2236L23.6592 12.2205C23.6592 10.9276 22.7088 9.92218 21.5382 9.28364C21.4368 9.22834 21.3325 9.175 21.2255 9.12367C21.168 8.71746 21.0748 8.31687 20.948 7.91111C20.589 6.76169 19.9619 5.71405 19.1186 4.85451C18.2752 3.99498 17.2396 3.34816 16.0972 2.96736C14.9548 2.58656 13.7383 2.48268 12.5479 2.66428C11.3575 2.84588 10.2272 3.30777 9.25034 4.01187C8.27344 4.71598 7.47785 5.64215 6.92912 6.71405C6.92375 6.72454 6.91841 6.73503 6.9131 6.74554C5.1625 6.46709 3.33087 7.03326 2.05945 8.29546C1.01945 9.34546 0.439453 10.7455 0.439453 12.2255C0.439453 13.7055 1.00945 15.0955 2.05945 16.1455C3.10945 17.1855 4.49945 17.7655 5.97945 17.7655H10.3447ZM22.1592 14.7667V15.4426V15.4426C22.1592 15.9289 21.7873 16.5346 20.8198 17.0624C19.8808 17.5746 18.5324 17.9148 17.002 17.9148C15.4716 17.9148 14.1231 17.5746 13.1841 17.0624C12.2167 16.5346 11.8447 15.9289 11.8447 15.4426V15.4426V14.7667C12.0412 14.9091 12.2497 15.0394 12.4658 15.1573C13.6648 15.8113 15.27 16.1926 17.002 16.1926C18.734 16.1926 20.3392 15.8113 21.5382 15.1573C21.7542 15.0394 21.9628 14.9091 22.1592 14.7667ZM21.5382 18.3792C21.7542 18.2613 21.9628 18.131 22.1592 17.9886V18.6647C22.1592 19.151 21.7873 19.7567 20.8198 20.2845C19.8808 20.7967 18.5324 21.1369 17.002 21.1369C15.4716 21.1369 14.1231 20.7967 13.1841 20.2845C12.2167 19.7567 11.8447 19.151 11.8447 18.6647V17.9886C12.0412 18.131 12.2497 18.2613 12.4658 18.3792C13.6648 19.0333 15.2699 19.4148 17.002 19.4148C18.734 19.4148 20.3392 19.0333 21.5382 18.3792ZM22.1592 12.2192L22.1592 12.2205V12.2224C22.1582 12.7087 21.786 13.3135 20.8199 13.8404C19.8809 14.3526 18.5325 14.6926 17.002 14.6926C15.4715 14.6926 14.1231 14.3526 13.1841 13.8404C12.2167 13.3128 11.8447 12.7071 11.8447 12.2205C11.8447 11.7338 12.2167 11.1281 13.1841 10.6005C14.1231 10.0883 15.4715 9.74832 17.002 9.74832C18.5325 9.74832 19.8809 10.0883 20.8199 10.6005C21.7864 11.1277 22.1586 11.7328 22.1592 12.2192Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCloudData);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "ce5c9e2e855c86e43a9ae39d7d04abd4.svg");

/***/ }),

/***/ 49264:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   _: () => (/* binding */ Image),
/* harmony export */   s: () => (/* binding */ DiffType)
/* harmony export */ });
/* harmony import */ var _status__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(45226);

var DiffType;
(function (DiffType) {
    /** Changes to a text file, which may be partially selected for commit */
    DiffType[DiffType["Text"] = 0] = "Text";
    /** Changes to a file with a known extension, which can be viewed in the app */
    DiffType[DiffType["Image"] = 1] = "Image";
    /** Changes to an unknown file format, which Git is unable to present in a human-friendly format */
    DiffType[DiffType["Binary"] = 2] = "Binary";
    /** Change to a repository which is included as a submodule of this repository */
    DiffType[DiffType["Submodule"] = 3] = "Submodule";
    /** Diff that will not be rendered */
    DiffType[DiffType["Unrenderable"] = 4] = "Unrenderable";
    /** Changes to a large text file */
    DiffType[DiffType["LargeText"] = 5] = "LargeText";
})(DiffType || (DiffType = {}));
class Image {
    get dataSource() {
        return `data:${this.mediaType};base64,${this.contents}`;
    }
    /**
     * @param contents The base64 encoded contents of the image.
     * @param mediaType The data URI media type, so the browser can render the image correctly.
     * @param bytes Size of the file in bytes.
     */
    constructor(contents, mediaType, bytes) {
        this.contents = contents;
        this.mediaType = mediaType;
        this.bytes = bytes;
    }
    static fromBinary(file, buffer) {
        return new Image(buffer.toString('base64'), (0,_status__WEBPACK_IMPORTED_MODULE_0__/* .getMediaType */ .Tr)(file.extension), buffer.length);
    }
}


/***/ }),

/***/ 49408:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.TextInput-module__Root--VresN{flex-grow:1;font-family:var(--font-family);font-size:14px}.TextInput-module__Root--VresN.TextInput-module__has-bottom-spacing--X0_P0{margin-bottom:15px}.TextInput-module__Root--VresN .TextInput-module__Input--vYuu6,.TextInput-module__Root--VresN .TextInput-module__Sizer--YpoTf{padding:4px 5px}.TextInput-module__Root--VresN.TextInput-module__has-suffix--Zh4VU .TextInput-module__Input--vYuu6,.TextInput-module__Root--VresN.TextInput-module__has-suffix--Zh4VU .TextInput-module__Sizer--YpoTf{padding-right:0}.TextInput-module__Root--VresN *{box-sizing:border-box}.TextInput-module__InputArea--Xizyd{height:36px;padding:var(--spacing-input-padding-y) var(--spacing-input-padding-x);position:relative;display:flex;cursor:text;border:1px solid var(--theme-color-border-default);border-radius:var(--radius-default);transition:margin-bottom var(--speed-quick) var(--easing-base),background-color var(--transition-default) var(--transition-ease),border-color var(--transition-default) var(--transition-ease),box-shadow var(--transition-default) var(--transition-ease)}.TextInput-module__Root--VresN.TextInput-module__is-variant-default--v6xLP .TextInput-module__InputArea--Xizyd{background-color:var(--theme-color-bg-3)}.TextInput-module__Root--VresN.TextInput-module__is-variant-default--v6xLP .TextInput-module__InputArea--Xizyd.TextInput-module__is-readonly--aw_TF{background-color:var(--theme-color-bg-4)}.TextInput-module__Root--VresN.TextInput-module__is-variant-default--v6xLP .TextInput-module__InputArea--Xizyd:hover:not(.TextInput-module__is-focused--I_wGd):not(.TextInput-module__is-readonly--aw_TF){border-color:var(--theme-color-border-strong)}.TextInput-module__Root--VresN.TextInput-module__is-variant-default--v6xLP .TextInput-module__InputArea--Xizyd.TextInput-module__is-focused--I_wGd{background-color:var(--theme-color-bg-1);border-color:var(--theme-color-focus-ring);box-shadow:0 0 0 2px rgba(210,31,60,.15);outline:none}.TextInput-module__Root--VresN.TextInput-module__is-variant-in-modal--zJlft .TextInput-module__InputArea--Xizyd{background-color:var(--theme-color-bg-2)}.TextInput-module__Root--VresN.TextInput-module__is-variant-in-modal--zJlft .TextInput-module__InputArea--Xizyd.TextInput-module__is-readonly--aw_TF{background-color:var(--theme-color-bg-3)}.TextInput-module__Root--VresN.TextInput-module__is-variant-in-modal--zJlft .TextInput-module__InputArea--Xizyd.TextInput-module__is-focused--I_wGd{background-color:var(--theme-color-bg-1)}.TextInput-module__Root--VresN.TextInput-module__is-variant-opaque-on-hover--G6Gft .TextInput-module__InputArea--Xizyd{background:rgba(0,0,0,0);transition-duration:var(--speed-turbo)}.TextInput-module__Root--VresN.TextInput-module__is-variant-opaque-on-hover--G6Gft:hover .TextInput-module__InputArea--Xizyd,.TextInput-module__Root--VresN.TextInput-module__is-variant-opaque-on-hover--G6Gft .TextInput-module__InputArea--Xizyd.TextInput-module__is-focused--I_wGd{background-color:var(--theme-color-bg-3)}.TextInput-module__InputArea--Xizyd.TextInput-module__has-message--wAqni{margin-bottom:27px}.TextInput-module__Root--VresN.TextInput-module__is-variant-transparent--x5D9T:hover .TextInput-module__InputArea--Xizyd,.TextInput-module__Root--VresN.TextInput-module__is-variant-transparent--x5D9T .TextInput-module__InputArea--Xizyd.TextInput-module__is-focused--I_wGd{background-color:rgba(0,0,0,0)}.TextInput-module__TextStyle--purTP{font-family:var(--font-family-regular),"OpenSans",arial;font-size:14px}.TextInput-module__Sizer--YpoTf{position:absolute;top:0;left:0;visibility:hidden;height:0;overflow:hidden;white-space:pre}.TextInput-module__InputWrapper--sa1ZS{overflow-x:hidden;overflow-y:hidden;flex-grow:1;padding-top:1px}.TextInput-module__InputWrapperInner--JXXac{min-width:100%;min-width:fit-content;display:flex}.TextInput-module__Prefix--c969q,.TextInput-module__Suffix--v0j_N{color:var(--theme-color-fg-muted);white-space:nowrap}.TextInput-module__Suffix--v0j_N{padding:4px 0px}.TextInput-module__Input--vYuu6{color:var(--theme-color-fg-default);background-color:rgba(0,0,0,0);border:0;flex-shrink:0;min-width:100%}.TextInput-module__Input--vYuu6:focus{outline:none}.TextInput-module__Input--vYuu6[disabled],.TextInput-module__Input--vYuu6.TextInput-module__is-readonly--aw_TF,.TextInput-module__Input--vYuu6::placeholder{color:var(--theme-color-fg-muted)}.TextInput-module__Input--vYuu6.TextInput-module__has-suffix--Zh4VU{min-width:auto}.TextInput-module__Input--vYuu6.TextInput-module__is-div--CGXio{user-select:text;cursor:text;white-space:nowrap}.TextInput-module__InputArea--Xizyd.TextInput-module__is-focused--I_wGd .TextInput-module__Input--vYuu6{color:var(--theme-color-fg-highlight)}.TextInput-module__BeforeContainer--bWcqY,.TextInput-module__AfterContainer--k5xIY{flex-grow:0;flex-shrink:0;display:flex;align-items:center}.TextInput-module__ButtonContainer--tPNNA{margin-left:4px;height:auto;display:flex;flex-direction:column;align-items:center;cursor:pointer;transition:opacity var(--speed-turbo) linear}.TextInput-module__NotificationMessage--Sil2E{position:absolute;top:calc(100% + 2px);left:1px;right:1px;text-align:left}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/TextInput/TextInput.module.scss","webpack://./../noodl-core-ui/src/styles/scss-variables/length.scss"],"names":[],"mappings":"AAIA,+BACE,WAAA,CACA,8BAAA,CACA,cAAA,CAEA,2EACE,kBAAA,CAGF,8HAEE,eAAA,CAIA,sMAEE,eAAA,CAIJ,iCACE,qBAAA,CAIJ,oCACE,WC3BkB,CD4BlB,qEAAA,CACA,iBAAA,CACA,YAAA,CACA,WAAA,CACA,kDAAA,CACA,mCAAA,CACA,0PAAA,CAKA,+GACE,wCAAA,CAEA,oJACE,wCAAA,CAGF,0MACE,6CAAA,CAGF,mJACE,wCAAA,CACA,0CAAA,CACA,wCAAA,CACA,YAAA,CAIJ,gHACE,wCAAA,CAEA,qJACE,wCAAA,CAGF,oJACE,wCAAA,CAIJ,uHACE,wBAAA,CACA,sCAAA,CAGF,wRAEE,wCAAA,CAGF,yEACE,kBAAA,CAGF,gRAEE,8BAAA,CAIJ,oCACE,uDAAA,CACA,cAAA,CAGF,gCACE,iBAAA,CACA,KAAA,CACA,MAAA,CACA,iBAAA,CACA,QAAA,CACA,eAAA,CACA,eAAA,CAGF,uCACE,iBAAA,CACA,iBAAA,CACA,WAAA,CACA,eAAA,CAGF,4CACE,cAAA,CACA,qBAAA,CACA,YAAA,CAGF,kEAEE,iCAAA,CACA,kBAAA,CAGF,iCACE,eAAA,CAGF,gCACE,mCAAA,CACA,8BAAA,CACA,QAAA,CACA,aAAA,CACA,cAAA,CAEA,sCACE,YAAA,CAGF,4JAGE,iCAAA,CAGF,oEACE,cAAA,CAGF,gEACE,gBAAA,CACA,WAAA,CACA,kBAAA,CAGF,wGACE,qCAAA,CAIJ,mFAEE,WAAA,CACA,aAAA,CACA,YAAA,CACA,kBAAA,CAGF,0CACE,eAAA,CACA,WAAA,CACA,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,cAAA,CACA,4CAAA,CAGF,8CACE,iBAAA,CACA,oBAAA,CACA,QAAA,CACA,SAAA,CACA,eAAA","sourcesContent":["@use '../../../styles/scss-variables/length.scss';\n\n// TODO: make level 1 on focus\n\n.Root {\n  flex-grow: 1;\n  font-family: var(--font-family);\n  font-size: 14px;\n\n  &.has-bottom-spacing {\n    margin-bottom: 15px;\n  }\n\n  .Input,\n  .Sizer {\n    padding: 4px 5px;\n  }\n\n  &.has-suffix {\n    .Input,\n    .Sizer {\n      padding-right: 0;\n    }\n  }\n\n  * {\n    box-sizing: border-box;\n  }\n}\n\n.InputArea {\n  height: length.$global-input-size;\n  padding: var(--spacing-input-padding-y) var(--spacing-input-padding-x);\n  position: relative;\n  display: flex;\n  cursor: text;\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: var(--radius-default);\n  transition: margin-bottom var(--speed-quick) var(--easing-base),\n    background-color var(--transition-default) var(--transition-ease),\n    border-color var(--transition-default) var(--transition-ease),\n    box-shadow var(--transition-default) var(--transition-ease);\n\n  .Root.is-variant-default & {\n    background-color: var(--theme-color-bg-3);\n\n    &.is-readonly {\n      background-color: var(--theme-color-bg-4);\n    }\n\n    &:hover:not(.is-focused):not(.is-readonly) {\n      border-color: var(--theme-color-border-strong);\n    }\n\n    &.is-focused {\n      background-color: var(--theme-color-bg-1);\n      border-color: var(--theme-color-focus-ring);\n      box-shadow: 0 0 0 2px rgba(210, 31, 60, 0.15);\n      outline: none;\n    }\n  }\n\n  .Root.is-variant-in-modal & {\n    background-color: var(--theme-color-bg-2);\n\n    &.is-readonly {\n      background-color: var(--theme-color-bg-3);\n    }\n\n    &.is-focused {\n      background-color: var(--theme-color-bg-1);\n    }\n  }\n\n  .Root.is-variant-opaque-on-hover & {\n    background: transparent;\n    transition-duration: var(--speed-turbo);\n  }\n\n  .Root.is-variant-opaque-on-hover:hover &,\n  .Root.is-variant-opaque-on-hover &.is-focused {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.has-message {\n    margin-bottom: 27px;\n  }\n\n  .Root.is-variant-transparent:hover &,\n  .Root.is-variant-transparent &.is-focused {\n    background-color: transparent;\n  }\n}\n\n.TextStyle {\n  font-family: var(--font-family-regular), 'OpenSans', arial;\n  font-size: 14px;\n}\n\n.Sizer {\n  position: absolute;\n  top: 0;\n  left: 0;\n  visibility: hidden;\n  height: 0;\n  overflow: hidden;\n  white-space: pre;\n}\n\n.InputWrapper {\n  overflow-x: hidden;\n  overflow-y: hidden; // Prevent tiny vertical scrollbar on single-line inputs\n  flex-grow: 1;\n  padding-top: 1px;\n}\n\n.InputWrapperInner {\n  min-width: 100%;\n  min-width: fit-content;\n  display: flex;\n}\n\n.Prefix,\n.Suffix {\n  color: var(--theme-color-fg-muted);\n  white-space: nowrap;\n}\n\n.Suffix {\n  padding: 4px 0px;\n}\n\n.Input {\n  color: var(--theme-color-fg-default);\n  background-color: transparent;\n  border: 0;\n  flex-shrink: 0;\n  min-width: 100%;\n\n  &:focus {\n    outline: none;\n  }\n\n  &[disabled],\n  &.is-readonly,\n  &::placeholder {\n    color: var(--theme-color-fg-muted);\n  }\n\n  &.has-suffix {\n    min-width: auto;\n  }\n\n  &.is-div {\n    user-select: text;\n    cursor: text;\n    white-space: nowrap;\n  }\n\n  .InputArea.is-focused & {\n    color: var(--theme-color-fg-highlight);\n  }\n}\n\n.BeforeContainer,\n.AfterContainer {\n  flex-grow: 0;\n  flex-shrink: 0;\n  display: flex;\n  align-items: center;\n}\n\n.ButtonContainer {\n  margin-left: 4px;\n  height: auto;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  cursor: pointer;\n  transition: opacity var(--speed-turbo) linear;\n}\n\n.NotificationMessage {\n  position: absolute;\n  top: calc(100% + 2px);\n  left: 1px;\n  right: 1px;\n  text-align: left;\n}\n","$property-panel-input-padding: 6px 8px 7px;\r\n$property-panel-input-size: 28px;\r\n$property-panel-small-xy-padding: 4px;\r\n\r\n$global-input-size: 36px;\r\n$global-input-size-small: 28px;\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `TextInput-module__Root--VresN`,
	"has-bottom-spacing": `TextInput-module__has-bottom-spacing--X0_P0`,
	"Input": `TextInput-module__Input--vYuu6`,
	"Sizer": `TextInput-module__Sizer--YpoTf`,
	"has-suffix": `TextInput-module__has-suffix--Zh4VU`,
	"InputArea": `TextInput-module__InputArea--Xizyd`,
	"is-variant-default": `TextInput-module__is-variant-default--v6xLP`,
	"is-readonly": `TextInput-module__is-readonly--aw_TF`,
	"is-focused": `TextInput-module__is-focused--I_wGd`,
	"is-variant-in-modal": `TextInput-module__is-variant-in-modal--zJlft`,
	"is-variant-opaque-on-hover": `TextInput-module__is-variant-opaque-on-hover--G6Gft`,
	"has-message": `TextInput-module__has-message--wAqni`,
	"is-variant-transparent": `TextInput-module__is-variant-transparent--x5D9T`,
	"TextStyle": `TextInput-module__TextStyle--purTP`,
	"InputWrapper": `TextInput-module__InputWrapper--sa1ZS`,
	"InputWrapperInner": `TextInput-module__InputWrapperInner--JXXac`,
	"Prefix": `TextInput-module__Prefix--c969q`,
	"Suffix": `TextInput-module__Suffix--v0j_N`,
	"is-div": `TextInput-module__is-div--CGXio`,
	"BeforeContainer": `TextInput-module__BeforeContainer--bWcqY`,
	"AfterContainer": `TextInput-module__AfterContainer--k5xIY`,
	"ButtonContainer": `TextInput-module__ButtonContainer--tPNNA`,
	"NotificationMessage": `TextInput-module__NotificationMessage--Sil2E`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 49419:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgArrowsInLineHorizontal = function SvgArrowsInLineHorizontal(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M20.3867 12.9382H3.88672",
    stroke: "#F5F5F5",
    strokeWidth: 1.5,
    strokeLinecap: "round",
    strokeLinejoin: "round"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.1367 12.9382C21.1367 13.3524 20.8009 13.6882 20.3867 13.6882L3.88672 13.6882C3.47251 13.6882 3.13672 13.3524 3.13672 12.9382C3.13672 12.524 3.47251 12.1882 3.88672 12.1882L20.3867 12.1882C20.8009 12.1882 21.1367 12.524 21.1367 12.9382Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.4278 10.6282C12.5178 10.5882 12.5978 10.5382 12.6678 10.4682L15.6678 7.46823C15.9578 7.17823 15.9578 6.69823 15.6678 6.40823C15.3778 6.11823 14.8978 6.11823 14.6078 6.40823L12.8878 8.12823L12.8878 2.43823C12.8878 2.02823 12.5478 1.68823 12.1378 1.68823C11.7278 1.68823 11.3878 2.02823 11.3878 2.43823L11.3878 8.12823L9.66775 6.40823C9.37775 6.11823 8.89775 6.11823 8.60775 6.40823C8.45775 6.55823 8.38775 6.74823 8.38775 6.93823C8.38775 7.12823 8.45775 7.31823 8.60775 7.46823L11.6078 10.4682C11.6778 10.5382 11.7578 10.5882 11.8478 10.6282C11.9378 10.6682 12.0278 10.6882 12.1378 10.6882C12.2478 10.6882 12.3378 10.6682 12.4278 10.6282Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.4278 15.2482C12.5178 15.2882 12.5978 15.3382 12.6678 15.4082L15.6678 18.4082C15.9578 18.6982 15.9578 19.1782 15.6678 19.4682C15.3778 19.7582 14.8978 19.7582 14.6078 19.4682L12.8878 17.7482L12.8878 23.4382C12.8878 23.8482 12.5478 24.1882 12.1378 24.1882C11.7278 24.1882 11.3878 23.8482 11.3878 23.4382L11.3878 17.7482L9.66775 19.4682C9.37775 19.7582 8.89775 19.7582 8.60775 19.4682C8.45775 19.3182 8.38775 19.1282 8.38775 18.9382C8.38775 18.7482 8.45775 18.5582 8.60775 18.4082L11.6078 15.4082C11.6778 15.3382 11.7578 15.2882 11.8478 15.2482C11.9378 15.2082 12.0278 15.1882 12.1378 15.1882C12.2478 15.1882 12.3378 15.2082 12.4278 15.2482Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgArrowsInLineHorizontal);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "028f784e47b58d723f262d8900e68976.svg");

/***/ }),

/***/ 49449:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.GitHistoryItem-module__Root--s2tla{display:flex;overflow:hidden;border-bottom:1px solid var(--theme-color-bg-1);background-color:var(--theme-color-bg-2)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__can-selected--N9oqs{user-select:none}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__can-selected--N9oqs:hover{background-color:var(--theme-color-bg-3);cursor:pointer}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__is-selected--F1c9K{background-color:var(--theme-color-secondary)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__is-selected--F1c9K:hover{background-color:var(--theme-color-secondary-highlight)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__is-first-commit--DJQKb{border-bottom:0}.GitHistoryItem-module__Item--hbZ_W{display:flex;flex:0 0 auto;width:80px;position:relative;padding-left:16px;pointer-events:none}.GitHistoryItem-module__Item--hbZ_W svg{position:absolute;box-sizing:border-box;width:100%;height:calc(100% + 1px)}.GitHistoryItem-module__Branch--hJWmi{--branch-color-remote-ahead: var(--base-color-teal-800);--branch-color-remote-ahead-hover: var(--base-color-teal-700);--branch-color-remote-ahead-selected: var(--base-color-teal-600);--branch-color-remote-ahead-selected-hover: var(--base-color-teal-500);--branch-color-remote: var(--theme-color-secondary);--branch-color-remote-hover: var(--theme-color-secondary-highlight);--branch-color-remote-selected: var(--base-color-teal-600);--branch-color-remote-selected-hover: var(--base-color-teal-500);--branch-color-local: var(--theme-color-on-secondary);--branch-color-local-hover: var(--theme-color-on-secondary);--branch-color-local-selected: var(--theme-color-on-secondary);--branch-color-local-selected-hover: var(--theme-color-on-secondary);fill:var(--theme-color-secondary)}.GitHistoryItem-module__Branch--hJWmi .GitHistoryItem-module__BranchTop--xIhQP{stroke:var(--scoped-color)}.GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-remote_ahead--nqKTp{--scoped-color: var(--branch-color-remote-ahead)}.GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-remote--mDd0F{--scoped-color: var(--branch-color-remote)}.GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-local--xP1Ul{--scoped-color: var(--branch-color-local)}.GitHistoryItem-module__Branch--hJWmi circle,.GitHistoryItem-module__Branch--hJWmi line{stroke:var(--scoped-color)}.GitHistoryItem-module__Branch--hJWmi .GitHistoryItem-module__Head--_8HYM{fill:var(--scoped-color);stroke:none}.GitHistoryItem-module__Branch--hJWmi .GitHistoryItem-module__Circle--lfcFf{fill:var(--theme-color-bg-2)}.GitHistoryItem-module__Branch--hJWmi .GitHistoryItem-module__Circle--lfcFf.GitHistoryItem-module__is-head--G7hGb{fill:var(--theme-color-fg-highlight) !important}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__can-selected--N9oqs:hover .GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-remote_ahead--nqKTp{--scoped-color: var(--branch-color-remote-ahead-hover)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__can-selected--N9oqs:hover .GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-remote--mDd0F{--scoped-color: var(--branch-color-remote-hover)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__can-selected--N9oqs:hover .GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-local--xP1Ul{--scoped-color: var(--branch-color-local-hover)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__can-selected--N9oqs:hover .GitHistoryItem-module__Branch--hJWmi .GitHistoryItem-module__Circle--lfcFf{fill:var(--theme-color-bg-3)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__is-selected--F1c9K .GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-remote_ahead--nqKTp{--scoped-color: var(--branch-color-remote-ahead-selected)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__is-selected--F1c9K .GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-remote--mDd0F{--scoped-color: var(--branch-color-remote-selected)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__is-selected--F1c9K .GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-local--xP1Ul{--scoped-color: var(--branch-color-local-selected)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__is-selected--F1c9K .GitHistoryItem-module__Branch--hJWmi .GitHistoryItem-module__Circle--lfcFf{fill:var(--theme-color-secondary)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__is-selected--F1c9K:hover .GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-remote_ahead--nqKTp{--scoped-color: var(--branch-color-remote-ahead-selected-hover)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__is-selected--F1c9K:hover .GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-remote--mDd0F{--scoped-color: var(--branch-color-remote-selected-hover)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__is-selected--F1c9K:hover .GitHistoryItem-module__Branch--hJWmi.GitHistoryItem-module__is-variant-local--xP1Ul{--scoped-color: var(--branch-color-local-selected-hover)}.GitHistoryItem-module__Root--s2tla.GitHistoryItem-module__is-selected--F1c9K:hover .GitHistoryItem-module__Branch--hJWmi .GitHistoryItem-module__Circle--lfcFf{fill:var(--theme-color-secondary-highlight)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/version-control/GitHistoryItem/GitHistoryItem.module.scss"],"names":[],"mappings":"AAAA,oCACE,YAAA,CACA,eAAA,CAEA,+CAAA,CACA,wCAAA,CAEA,+EACE,gBAAA,CAEA,qFACE,wCAAA,CACA,cAAA,CAIJ,8EACE,6CAAA,CAEA,oFACE,uDAAA,CAIJ,kFACE,eAAA,CAIJ,oCACE,YAAA,CACA,aAAA,CACA,UAAA,CACA,iBAAA,CACA,iBAAA,CACA,mBAAA,CAEA,wCACE,iBAAA,CACA,qBAAA,CACA,UAAA,CACA,uBAAA,CAIJ,sCACE,uDAAA,CACA,6DAAA,CACA,gEAAA,CACA,sEAAA,CAEA,mDAAA,CACA,mEAAA,CACA,0DAAA,CACA,gEAAA,CAEA,qDAAA,CACA,2DAAA,CACA,8DAAA,CACA,oEAAA,CAGA,iCAAA,CAEA,+EACE,0BAAA,CAGF,4FACE,gDAAA,CAGF,sFACE,0CAAA,CAGF,qFACE,yCAAA,CAGF,wFAEE,0BAAA,CAGF,0EACE,wBAAA,CACA,WAAA,CAGF,4EACE,4BAAA,CAEA,kHACE,+CAAA,CAMJ,iLACE,sDAAA,CAGF,2KACE,gDAAA,CAGF,0KACE,+CAAA,CAGF,iKACE,4BAAA,CAKF,0KACE,yDAAA,CAGF,oKACE,mDAAA,CAGF,mKACE,kDAAA,CAGF,0JACE,iCAAA,CAKF,gLACE,+DAAA,CAGF,0KACE,yDAAA,CAGF,yKACE,wDAAA,CAGF,gKACE,2CAAA","sourcesContent":[".Root {\n  display: flex;\n  overflow: hidden;\n\n  border-bottom: 1px solid var(--theme-color-bg-1);\n  background-color: var(--theme-color-bg-2);\n\n  &.can-selected {\n    user-select: none;\n\n    &:hover {\n      background-color: var(--theme-color-bg-3);\n      cursor: pointer;\n    }\n  }\n\n  &.is-selected {\n    background-color: var(--theme-color-secondary);\n\n    &:hover {\n      background-color: var(--theme-color-secondary-highlight);\n    }\n  }\n\n  &.is-first-commit {\n    border-bottom: 0;\n  }\n}\n\n.Item {\n  display: flex;\n  flex: 0 0 auto;\n  width: 80px;\n  position: relative;\n  padding-left: 16px;\n  pointer-events: none;\n\n  svg {\n    position: absolute;\n    box-sizing: border-box;\n    width: 100%;\n    height: calc(100% + 1px); /* +1 to cover the black border line */\n  }\n}\n\n.Branch {\n  --branch-color-remote-ahead: var(--base-color-teal-800);\n  --branch-color-remote-ahead-hover: var(--base-color-teal-700);\n  --branch-color-remote-ahead-selected: var(--base-color-teal-600);\n  --branch-color-remote-ahead-selected-hover: var(--base-color-teal-500);\n\n  --branch-color-remote: var(--theme-color-secondary);\n  --branch-color-remote-hover: var(--theme-color-secondary-highlight);\n  --branch-color-remote-selected: var(--base-color-teal-600);\n  --branch-color-remote-selected-hover: var(--base-color-teal-500);\n\n  --branch-color-local: var(--theme-color-on-secondary);\n  --branch-color-local-hover: var(--theme-color-on-secondary);\n  --branch-color-local-selected: var(--theme-color-on-secondary);\n  --branch-color-local-selected-hover: var(--theme-color-on-secondary);\n\n  /* --- */\n  fill: var(--theme-color-secondary);\n\n  .BranchTop {\n    stroke: var(--scoped-color);\n  }\n\n  &.is-variant-remote_ahead {\n    --scoped-color: var(--branch-color-remote-ahead);\n  }\n\n  &.is-variant-remote {\n    --scoped-color: var(--branch-color-remote);\n  }\n\n  &.is-variant-local {\n    --scoped-color: var(--branch-color-local);\n  }\n\n  circle,\n  line {\n    stroke: var(--scoped-color);\n  }\n\n  .Head {\n    fill: var(--scoped-color);\n    stroke: none;\n  }\n\n  .Circle {\n    fill: var(--theme-color-bg-2);\n\n    &.is-head {\n      fill: var(--theme-color-fg-highlight) !important;\n    }\n  }\n}\n\n.Root.can-selected:hover .Branch {\n  &.is-variant-remote_ahead {\n    --scoped-color: var(--branch-color-remote-ahead-hover);\n  }\n\n  &.is-variant-remote {\n    --scoped-color: var(--branch-color-remote-hover);\n  }\n\n  &.is-variant-local {\n    --scoped-color: var(--branch-color-local-hover);\n  }\n\n  .Circle {\n    fill: var(--theme-color-bg-3);\n  }\n}\n\n.Root.is-selected .Branch {\n  &.is-variant-remote_ahead {\n    --scoped-color: var(--branch-color-remote-ahead-selected);\n  }\n\n  &.is-variant-remote {\n    --scoped-color: var(--branch-color-remote-selected);\n  }\n\n  &.is-variant-local {\n    --scoped-color: var(--branch-color-local-selected);\n  }\n\n  .Circle {\n    fill: var(--theme-color-secondary);\n  }\n}\n\n.Root.is-selected:hover .Branch {\n  &.is-variant-remote_ahead {\n    --scoped-color: var(--branch-color-remote-ahead-selected-hover);\n  }\n\n  &.is-variant-remote {\n    --scoped-color: var(--branch-color-remote-selected-hover);\n  }\n\n  &.is-variant-local {\n    --scoped-color: var(--branch-color-local-selected-hover);\n  }\n\n  .Circle {\n    fill: var(--theme-color-secondary-highlight);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `GitHistoryItem-module__Root--s2tla`,
	"can-selected": `GitHistoryItem-module__can-selected--N9oqs`,
	"is-selected": `GitHistoryItem-module__is-selected--F1c9K`,
	"is-first-commit": `GitHistoryItem-module__is-first-commit--DJQKb`,
	"Item": `GitHistoryItem-module__Item--hbZ_W`,
	"Branch": `GitHistoryItem-module__Branch--hJWmi`,
	"BranchTop": `GitHistoryItem-module__BranchTop--xIhQP`,
	"is-variant-remote_ahead": `GitHistoryItem-module__is-variant-remote_ahead--nqKTp`,
	"is-variant-remote": `GitHistoryItem-module__is-variant-remote--mDd0F`,
	"is-variant-local": `GitHistoryItem-module__is-variant-local--xP1Ul`,
	"Head": `GitHistoryItem-module__Head--_8HYM`,
	"Circle": `GitHistoryItem-module__Circle--lfcFf`,
	"is-head": `GitHistoryItem-module__is-head--G7hGb`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 49468:
/***/ ((module) => {

"use strict";
module.exports = require("electron-store");

/***/ }),

/***/ 49484:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (/* binding */ useParsedHref)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

function useParsedHref(href) {
    if (!href)
        return null;
    const parsedHref = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => {
        let newHref = href.trim().replace(/\s/g, '');
        if (/^(:\/\/)/.test(newHref)) {
            return `http${newHref}`;
        }
        if (!/^(f|ht)tps?:\/\//i.test(newHref)) {
            return `http://${newHref}`;
        }
        return newHref;
    }, [href]);
    return parsedHref;
}


/***/ }),

/***/ 49741:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.CanvasTabs-module__CanvasTabs--gpzzb{display:flex;flex-direction:column;height:100%;width:100%;pointer-events:all}.CanvasTabs-module__TabBar--twWwK{display:flex;gap:var(--spacing-1);padding:var(--spacing-2);background-color:var(--theme-color-bg-2);border-bottom:1px solid var(--theme-color-border-default);flex-shrink:0}.CanvasTabs-module__Tab--jOIP_{display:flex;align-items:center;gap:var(--spacing-2);padding:var(--spacing-2) var(--spacing-3);background-color:var(--theme-color-bg-3);color:var(--theme-color-fg-default);border-radius:var(--radius-default) var(--radius-default) 0 0;cursor:pointer;user-select:none;transition:background-color .15s ease;border:1px solid rgba(0,0,0,0);border-bottom:none}.CanvasTabs-module__Tab--jOIP_:hover{background-color:var(--theme-color-bg-4)}.CanvasTabs-module__Tab--jOIP_.CanvasTabs-module__isActive--Crc8_{background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-highlight);border-color:var(--theme-color-border-default);border-bottom-color:var(--theme-color-bg-1)}.CanvasTabs-module__Tab--jOIP_:focus-visible{outline:2px solid var(--theme-color-primary);outline-offset:-2px}.CanvasTabs-module__TabLabel--YV9W9{font-size:var(--theme-font-size-default);font-weight:500;white-space:nowrap}.CanvasTabs-module__TabCloseButton--mJ6YY{display:flex;align-items:center;justify-content:center;width:20px;height:20px;padding:0;border:none;background:rgba(0,0,0,0);color:var(--theme-color-fg-default-shy);font-size:18px;line-height:1;cursor:pointer;border-radius:var(--radius-s);transition:all .15s ease}.CanvasTabs-module__TabCloseButton--mJ6YY:hover{background-color:var(--theme-color-bg-5);color:var(--theme-color-fg-highlight)}.CanvasTabs-module__TabCloseButton--mJ6YY:active{background-color:var(--theme-color-bg-4)}.CanvasTabs-module__TabContent--OyBv4{flex:1;overflow:hidden;position:relative;background-color:var(--theme-color-bg-1)}.CanvasTabs-module__CanvasContainer--Y_Ewo{width:100%;height:100%;position:relative}.CanvasTabs-module__BlocklyContainer--kkfiS{width:100%;height:100%;overflow:hidden;background-color:var(--theme-color-bg-1)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/CanvasTabs/CanvasTabs.module.scss"],"names":[],"mappings":"AAMA,sCACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,UAAA,CACA,kBAAA,CAGF,kCACE,YAAA,CACA,oBAAA,CACA,wBAAA,CACA,wCAAA,CACA,yDAAA,CACA,aAAA,CAGF,+BACE,YAAA,CACA,kBAAA,CACA,oBAAA,CACA,yCAAA,CACA,wCAAA,CACA,mCAAA,CACA,6DAAA,CACA,cAAA,CACA,gBAAA,CACA,qCAAA,CACA,8BAAA,CACA,kBAAA,CAEA,qCACE,wCAAA,CAGF,kEACE,wCAAA,CACA,qCAAA,CACA,8CAAA,CACA,2CAAA,CAGF,6CACE,4CAAA,CACA,mBAAA,CAIJ,oCACE,wCAAA,CACA,eAAA,CACA,kBAAA,CAGF,0CACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CACA,WAAA,CACA,SAAA,CACA,WAAA,CACA,wBAAA,CACA,uCAAA,CACA,cAAA,CACA,aAAA,CACA,cAAA,CACA,6BAAA,CACA,wBAAA,CAEA,gDACE,wCAAA,CACA,qCAAA,CAGF,iDACE,wCAAA,CAIJ,sCACE,MAAA,CACA,eAAA,CACA,iBAAA,CACA,wCAAA,CAGF,2CACE,UAAA,CACA,WAAA,CACA,iBAAA,CAGF,4CACE,UAAA,CACA,WAAA,CACA,eAAA,CACA,wCAAA","sourcesContent":["/**\n * Canvas Tabs Styling\n *\n * Theme-aware styling for canvas/Blockly tab system\n */\n\n.CanvasTabs {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  width: 100%;\n  pointer-events: all; /* Enable clicks on tabs */\n}\n\n.TabBar {\n  display: flex;\n  gap: var(--spacing-1);\n  padding: var(--spacing-2);\n  background-color: var(--theme-color-bg-2);\n  border-bottom: 1px solid var(--theme-color-border-default);\n  flex-shrink: 0;\n}\n\n.Tab {\n  display: flex;\n  align-items: center;\n  gap: var(--spacing-2);\n  padding: var(--spacing-2) var(--spacing-3);\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-default);\n  border-radius: var(--radius-default) var(--radius-default) 0 0;\n  cursor: pointer;\n  user-select: none;\n  transition: background-color 0.15s ease;\n  border: 1px solid transparent;\n  border-bottom: none;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n  }\n\n  &.isActive {\n    background-color: var(--theme-color-bg-1);\n    color: var(--theme-color-fg-highlight);\n    border-color: var(--theme-color-border-default);\n    border-bottom-color: var(--theme-color-bg-1); // Hide bottom border\n  }\n\n  &:focus-visible {\n    outline: 2px solid var(--theme-color-primary);\n    outline-offset: -2px;\n  }\n}\n\n.TabLabel {\n  font-size: var(--theme-font-size-default);\n  font-weight: 500;\n  white-space: nowrap;\n}\n\n.TabCloseButton {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 20px;\n  height: 20px;\n  padding: 0;\n  border: none;\n  background: transparent;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 18px;\n  line-height: 1;\n  cursor: pointer;\n  border-radius: var(--radius-s);\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-5);\n    color: var(--theme-color-fg-highlight);\n  }\n\n  &:active {\n    background-color: var(--theme-color-bg-4);\n  }\n}\n\n.TabContent {\n  flex: 1;\n  overflow: hidden;\n  position: relative;\n  background-color: var(--theme-color-bg-1);\n}\n\n.CanvasContainer {\n  width: 100%;\n  height: 100%;\n  position: relative;\n}\n\n.BlocklyContainer {\n  width: 100%;\n  height: 100%;\n  overflow: hidden;\n  background-color: var(--theme-color-bg-1);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"CanvasTabs": `CanvasTabs-module__CanvasTabs--gpzzb`,
	"TabBar": `CanvasTabs-module__TabBar--twWwK`,
	"Tab": `CanvasTabs-module__Tab--jOIP_`,
	"isActive": `CanvasTabs-module__isActive--Crc8_`,
	"TabLabel": `CanvasTabs-module__TabLabel--YV9W9`,
	"TabCloseButton": `CanvasTabs-module__TabCloseButton--mJ6YY`,
	"TabContent": `CanvasTabs-module__TabContent--OyBv4`,
	"CanvasContainer": `CanvasTabs-module__CanvasContainer--Y_Ewo`,
	"BlocklyContainer": `CanvasTabs-module__BlocklyContainer--kkfiS`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 49825:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgBug = function SvgBug(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M14.2938 11.664C14.7193 11.664 15.0642 11.3191 15.0642 10.8936C15.0642 10.4681 14.7193 10.1232 14.2938 10.1232C13.8684 10.1232 13.5234 10.4681 13.5234 10.8936C13.5234 11.3191 13.8684 11.664 14.2938 11.664Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M9.97939 11.664C10.4049 11.664 10.7498 11.3191 10.7498 10.8936C10.7498 10.4681 10.4049 10.1232 9.97939 10.1232C9.55391 10.1232 9.20898 10.4681 9.20898 10.8936C9.20898 11.3191 9.55391 11.664 9.97939 11.664Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M10.0718 3.80285C9.87929 3.43606 9.42593 3.29475 9.05915 3.48722C8.69237 3.67968 8.55106 4.13304 8.74352 4.49983L9.54422 6.02572C8.69287 6.37014 7.91046 6.884 7.24847 7.54598C6.7412 8.05326 6.3209 8.63125 5.99718 9.25678L4.50796 8.39542C4.1494 8.18803 3.69061 8.31058 3.48322 8.66914C3.27584 9.02769 3.39838 9.48648 3.75694 9.69387L5.4515 10.674C5.30145 11.2438 5.22363 11.8351 5.22363 12.4344V12.917H3.2002C2.78598 12.917 2.4502 13.2528 2.4502 13.667C2.4502 14.0812 2.78598 14.417 3.2002 14.417H5.22363V14.8997C5.22363 15.499 5.30146 16.0903 5.45151 16.6601L3.75694 17.6402C3.39838 17.8476 3.27584 18.3064 3.48322 18.665C3.69061 19.0235 4.1494 19.1461 4.50796 18.9387L5.9972 18.0773C6.32092 18.7028 6.74121 19.2808 7.24847 19.7881C8.54496 21.0846 10.3034 21.8129 12.1369 21.8129C13.9704 21.8129 15.7288 21.0846 17.0253 19.7881C17.5325 19.2808 17.9528 18.7028 18.2766 18.0773L19.7659 18.9387C20.1244 19.1461 20.5832 19.0235 20.7906 18.665C20.998 18.3064 20.8754 17.8476 20.5169 17.6402L18.8222 16.6601C18.9723 16.0903 19.0501 15.499 19.0501 14.8997V14.417H21.0736C21.4878 14.417 21.8236 14.0812 21.8236 13.667C21.8236 13.2528 21.4878 12.917 21.0736 12.917H19.0501V12.4344C19.0501 11.8351 18.9723 11.2438 18.8223 10.674L20.5169 9.69387C20.8754 9.48648 20.998 9.02769 20.7906 8.66914C20.5832 8.31058 20.1244 8.18803 19.7659 8.39542L18.2766 9.25681C17.9529 8.63126 17.5326 8.05326 17.0253 7.54598C16.3632 6.88394 15.5807 6.37003 14.7293 6.02561L15.5299 4.49983C15.7224 4.13304 15.5811 3.67968 15.2143 3.48722C14.8475 3.29475 14.3941 3.43606 14.2017 3.80285L13.2525 5.61172C12.886 5.5518 12.513 5.52114 12.1369 5.52114C11.7606 5.52114 11.3876 5.55181 11.021 5.61177L10.0718 3.80285ZM8.30913 8.60664C9.32431 7.59147 10.7012 7.02114 12.1369 7.02114C13.5726 7.02114 14.9494 7.59147 15.9646 8.60664C16.9798 9.62182 17.5501 10.9987 17.5501 12.4344V12.917H6.72363V12.4344C6.72363 10.9987 7.29395 9.62182 8.30913 8.60664ZM17.5501 14.417V14.8997C17.5501 16.3354 16.9798 17.7122 15.9646 18.7274C14.9494 19.7426 13.5726 20.3129 12.1369 20.3129C10.7012 20.3129 9.32431 19.7426 8.30913 18.7274C7.29395 17.7122 6.72363 16.3354 6.72363 14.8997V14.417H17.5501Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgBug);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "acad21c036fe89b72868daea6e562914.svg");

/***/ }),

/***/ 50084:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgTextInBox = function SvgTextInBox(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.26204 3.7085H24.8454C25.9269 3.7085 26.8037 4.58527 26.8037 5.66683V25.2502C26.8037 26.3317 25.9269 27.2085 24.8454 27.2085H5.26204C4.18049 27.2085 3.30371 26.3317 3.30371 25.2502V5.66683C3.30371 4.58527 4.18049 3.7085 5.26204 3.7085ZM10.4307 12.0092V10.7823H14.1834V20.7632H12.5119C12.0312 20.7632 11.6416 21.1529 11.6416 21.6336C11.6416 22.1143 12.0312 22.5039 12.5119 22.5039H17.6179C18.0986 22.5039 18.4883 22.1143 18.4883 21.6336C18.4883 21.1529 18.0986 20.7632 17.6179 20.7632H15.9242V10.7823H19.677V12.0092C19.677 12.4899 20.0667 12.8796 20.5474 12.8796C21.028 12.8796 21.4177 12.4899 21.4177 12.0092V10.086C21.4177 9.50919 20.9501 9.04158 20.3733 9.04158H9.73436C9.15752 9.04158 8.68991 9.50919 8.68991 10.086V12.0092C8.68991 12.4899 9.07959 12.8796 9.56028 12.8796C10.041 12.8796 10.4307 12.4899 10.4307 12.0092Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgTextInBox);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "70deea7c2758f5e190c13c66cd3fd106.svg");

/***/ }),

/***/ 50243:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgJustifyContentEnd = function SvgJustifyContentEnd(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M8.26953 18.4106L17.457 18.4106C17.8195 18.4106 18.1133 18.1548 18.1133 17.8392L18.1133 14.9821C18.1133 14.6665 17.8195 14.4106 17.457 14.4106L8.26953 14.4106C7.90709 14.4106 7.61328 14.6665 7.61328 14.9821L7.61328 17.8392C7.61328 18.1548 7.90709 18.4106 8.26953 18.4106Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M8.26953 12.9106L17.457 12.9106C17.8195 12.9106 18.1133 12.6548 18.1133 12.3392L18.1133 9.48207C18.1133 9.16648 17.8195 8.91064 17.457 8.91064L8.26953 8.91064C7.90709 8.91064 7.61328 9.16648 7.61328 9.48207L7.61328 12.3392C7.61328 12.6548 7.90709 12.9106 8.26953 12.9106Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.8633 20.6606C21.8633 21.0749 21.5051 21.4106 21.0633 21.4106L4.66331 21.4106C4.22146 21.4106 3.86328 21.0749 3.86328 20.6606C3.86328 20.2464 4.22146 19.9106 4.66331 19.9106L21.0633 19.9106C21.5051 19.9106 21.8633 20.2464 21.8633 20.6606Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgJustifyContentEnd);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "75fc38b18e1bb4644e9076e65a313c8e.svg");

/***/ }),

/***/ 50303:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/* ---------- Icon label ---------- */

.monaco-icon-label {
	display: flex; /* required for icons support :before rule */
	overflow: hidden;
	text-overflow: ellipsis;
}

.monaco-icon-label::before {

	/* svg icons rendered as background image */
	background-size: 16px;
	background-position: left center;
	background-repeat: no-repeat;
	padding-right: 6px;
	width: 16px;
	height: 22px;
	line-height: inherit !important;
	display: inline-block;

	/* fonts icons */
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	vertical-align: top;

	flex-shrink: 0; /* fix for https://github.com/microsoft/vscode/issues/13787 */
}

.monaco-icon-label > .monaco-icon-label-container {
	min-width: 0;
	overflow: hidden;
	text-overflow: ellipsis;
	flex: 1;
}

.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-name-container > .label-name {
	color: inherit;
	white-space: pre; /* enable to show labels that include multiple whitespaces */
}

.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-name-container > .label-name > .label-separator {
	margin: 0 2px;
	opacity: 0.5;
}

.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {
	opacity: .7;
	margin-left: 0.5em;
	font-size: 0.9em;
	white-space: pre; /* enable to show labels that include multiple whitespaces */
}

.monaco-icon-label.nowrap > .monaco-icon-label-container > .monaco-icon-description-container > .label-description{
	white-space: nowrap
}

.vs .monaco-icon-label > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {
	opacity: .95;
}

.monaco-icon-label.italic > .monaco-icon-label-container > .monaco-icon-name-container > .label-name,
.monaco-icon-label.italic > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {
	font-style: italic;
}

.monaco-icon-label.deprecated {
	text-decoration: line-through;
	opacity: 0.66;
}

/* make sure apply italic font style to decorations as well */
.monaco-icon-label.italic::after {
	font-style: italic;
}

.monaco-icon-label.strikethrough > .monaco-icon-label-container > .monaco-icon-name-container > .label-name,
.monaco-icon-label.strikethrough > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {
	text-decoration: line-through;
}

.monaco-icon-label::after {
	opacity: 0.75;
	font-size: 90%;
	font-weight: 600;
	margin: auto 16px 0 5px; /* https://github.com/microsoft/vscode/issues/113223 */
	text-align: center;
}

/* make sure selection color wins when a label is being selected */
.monaco-list:focus .selected .monaco-icon-label, /* list */
.monaco-list:focus .selected .monaco-icon-label::after
{
	color: inherit !important;
}

.monaco-list-row.focused.selected .label-description,
.monaco-list-row.selected .label-description {
	opacity: .8;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/iconLabel/iconlabel.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F,qCAAqC;;AAErC;CACC,aAAa,EAAE,4CAA4C;CAC3D,gBAAgB;CAChB,uBAAuB;AACxB;;AAEA;;CAEC,2CAA2C;CAC3C,qBAAqB;CACrB,gCAAgC;CAChC,4BAA4B;CAC5B,kBAAkB;CAClB,WAAW;CACX,YAAY;CACZ,+BAA+B;CAC/B,qBAAqB;;CAErB,gBAAgB;CAChB,mCAAmC;CACnC,kCAAkC;CAClC,mBAAmB;;CAEnB,cAAc,EAAE,6DAA6D;AAC9E;;AAEA;CACC,YAAY;CACZ,gBAAgB;CAChB,uBAAuB;CACvB,OAAO;AACR;;AAEA;CACC,cAAc;CACd,gBAAgB,EAAE,4DAA4D;AAC/E;;AAEA;CACC,aAAa;CACb,YAAY;AACb;;AAEA;CACC,WAAW;CACX,kBAAkB;CAClB,gBAAgB;CAChB,gBAAgB,EAAE,4DAA4D;AAC/E;;AAEA;CACC;AACD;;AAEA;CACC,YAAY;AACb;;AAEA;;CAEC,kBAAkB;AACnB;;AAEA;CACC,6BAA6B;CAC7B,aAAa;AACd;;AAEA,6DAA6D;AAC7D;CACC,kBAAkB;AACnB;;AAEA;;CAEC,6BAA6B;AAC9B;;AAEA;CACC,aAAa;CACb,cAAc;CACd,gBAAgB;CAChB,uBAAuB,EAAE,sDAAsD;CAC/E,kBAAkB;AACnB;;AAEA,kEAAkE;AAClE;;;CAGC,yBAAyB;AAC1B;;AAEA;;CAEC,WAAW;AACZ","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/* ---------- Icon label ---------- */\n\n.monaco-icon-label {\n\tdisplay: flex; /* required for icons support :before rule */\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.monaco-icon-label::before {\n\n\t/* svg icons rendered as background image */\n\tbackground-size: 16px;\n\tbackground-position: left center;\n\tbackground-repeat: no-repeat;\n\tpadding-right: 6px;\n\twidth: 16px;\n\theight: 22px;\n\tline-height: inherit !important;\n\tdisplay: inline-block;\n\n\t/* fonts icons */\n\t-webkit-font-smoothing: antialiased;\n\t-moz-osx-font-smoothing: grayscale;\n\tvertical-align: top;\n\n\tflex-shrink: 0; /* fix for https://github.com/microsoft/vscode/issues/13787 */\n}\n\n.monaco-icon-label > .monaco-icon-label-container {\n\tmin-width: 0;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\tflex: 1;\n}\n\n.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-name-container > .label-name {\n\tcolor: inherit;\n\twhite-space: pre; /* enable to show labels that include multiple whitespaces */\n}\n\n.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-name-container > .label-name > .label-separator {\n\tmargin: 0 2px;\n\topacity: 0.5;\n}\n\n.monaco-icon-label > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {\n\topacity: .7;\n\tmargin-left: 0.5em;\n\tfont-size: 0.9em;\n\twhite-space: pre; /* enable to show labels that include multiple whitespaces */\n}\n\n.monaco-icon-label.nowrap > .monaco-icon-label-container > .monaco-icon-description-container > .label-description{\n\twhite-space: nowrap\n}\n\n.vs .monaco-icon-label > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {\n\topacity: .95;\n}\n\n.monaco-icon-label.italic > .monaco-icon-label-container > .monaco-icon-name-container > .label-name,\n.monaco-icon-label.italic > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {\n\tfont-style: italic;\n}\n\n.monaco-icon-label.deprecated {\n\ttext-decoration: line-through;\n\topacity: 0.66;\n}\n\n/* make sure apply italic font style to decorations as well */\n.monaco-icon-label.italic::after {\n\tfont-style: italic;\n}\n\n.monaco-icon-label.strikethrough > .monaco-icon-label-container > .monaco-icon-name-container > .label-name,\n.monaco-icon-label.strikethrough > .monaco-icon-label-container > .monaco-icon-description-container > .label-description {\n\ttext-decoration: line-through;\n}\n\n.monaco-icon-label::after {\n\topacity: 0.75;\n\tfont-size: 90%;\n\tfont-weight: 600;\n\tmargin: auto 16px 0 5px; /* https://github.com/microsoft/vscode/issues/113223 */\n\ttext-align: center;\n}\n\n/* make sure selection color wins when a label is being selected */\n.monaco-list:focus .selected .monaco-icon-label, /* list */\n.monaco-list:focus .selected .monaco-icon-label::after\n{\n\tcolor: inherit !important;\n}\n\n.monaco-list-row.focused.selected .label-description,\n.monaco-list-row.selected .label-description {\n\topacity: .8;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 50603:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgFile = function SvgFile(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.79688 4.30721V20.8072H18.2969V8.86787L13.7362 4.30719L5.79688 4.30721ZM5.74688 2.80721L14.0469 2.80719C14.2458 2.80719 14.4366 2.88621 14.5772 3.02686L19.5772 8.02689C19.7179 8.16754 19.7969 8.3583 19.7969 8.55721V20.8072C19.7969 21.189 19.6558 21.5646 19.3901 21.8493C19.1228 22.1357 18.7488 22.3072 18.3469 22.3072H5.74688C5.34496 22.3072 4.97091 22.1357 4.70361 21.8493C4.43794 21.5646 4.29688 21.189 4.29688 20.8072V4.30721C4.29688 3.92545 4.43794 3.54979 4.70361 3.26515C4.97091 2.97875 5.34496 2.80722 5.74687 2.80721L5.74688 3.55721",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M8.46973 11.5701C8.46973 11.1559 8.80551 10.8201 9.21973 10.8201H14.8735C15.2877 10.8201 15.6235 11.1559 15.6235 11.5701C15.6235 11.9843 15.2877 12.3201 14.8735 12.3201H9.21973C8.80551 12.3201 8.46973 11.9843 8.46973 11.5701Z",
    fill: "#B8B8B8"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M8.46973 15.5701C8.46973 15.1559 8.80551 14.8201 9.21973 14.8201H14.8735C15.2877 14.8201 15.6235 15.1559 15.6235 15.5701C15.6235 15.9843 15.2877 16.3201 14.8735 16.3201H9.21973C8.80551 16.3201 8.46973 15.9843 8.46973 15.5701Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgFile);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "27ed037609a4052713647c9ce3c871cc.svg");

/***/ }),

/***/ 50731:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCheck = function SvgCheck(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M20.917 6.21967C21.2099 6.51256 21.2099 6.98744 20.917 7.28033L10.417 17.7803C10.1242 18.0732 9.64928 18.0732 9.35639 17.7803L4.10639 12.5303C3.8135 12.2374 3.8135 11.7626 4.10639 11.4697C4.39928 11.1768 4.87416 11.1768 5.16705 11.4697L9.88672 16.1893L19.8564 6.21967C20.1493 5.92678 20.6242 5.92678 20.917 6.21967Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCheck);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "4f527e0afd4036ffa9892992916d8565.svg");

/***/ }),

/***/ 50795:
/***/ ((module) => {

"use strict";
module.exports = require("connect-flash");

/***/ }),

/***/ 50856:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Completions = void 0;
const resource_1 = __webpack_require__(39929);
const headers_1 = __webpack_require__(79973);
class Completions extends resource_1.APIResource {
    create(params, options) {
        const { betas, ...body } = params;
        return this._client.post('/v1/complete', {
            body,
            timeout: this._client._options.timeout ?? 600000,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
                options?.headers,
            ]),
            stream: params.stream ?? false,
        });
    }
}
exports.Completions = Completions;
//# sourceMappingURL=completions.js.map

/***/ }),

/***/ 50867:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   C: () => (/* binding */ UndoActionGroup),
/* harmony export */   g: () => (/* binding */ UndoQueue)
/* harmony export */ });
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47821);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_shared_model__WEBPACK_IMPORTED_MODULE_0__);

class UndoQueue extends (_shared_model__WEBPACK_IMPORTED_MODULE_0___default()) {
    constructor() {
        super();
        this.ptr = 0;
        this.queue = [];
    }
    getHistoryLocation() {
        return this.ptr;
    }
    getHistory() {
        return this.queue;
    }
    push(action) {
        this.ptr !== this.queue.length && this.queue.splice(this.ptr);
        this.queue.push(action);
        this.ptr = this.queue.length;
        this.notifyListeners('undoHistoryChanged');
    }
    pushAndDo(action) {
        this.push(action);
        action.do && action.do();
    }
    undo() {
        if (this.ptr > 0) {
            var action = this.queue[this.ptr - 1];
            action.undo && action.undo();
            this.ptr--;
            this.notifyListeners('undo');
            return action;
        }
    }
    redo() {
        if (this.queue.length > this.ptr) {
            var action = this.queue[this.ptr];
            action.do && action.do();
            this.ptr++;
            this.notifyListeners('redo');
            return action;
        }
    }
    clear() {
        this.ptr = 0;
        this.queue = [];
    }
}
UndoQueue.instance = new UndoQueue();
class UndoActionGroup {
    constructor(args) {
        this.ptr = 0;
        this.label = args.label;
        this.actions = [];
        // Push the initial action
        if (args.do || args.undo) {
            this.actions.push({
                do: args.do,
                undo: args.undo
            });
        }
    }
    push(a) {
        this.actions.push(a);
        this.ptr = this.actions.length;
    }
    pushAndDo(a) {
        this.push(a);
        a.do && a.do();
    }
    do() {
        for (var i = this.ptr; i < this.actions.length; i++) {
            var a = this.actions[i];
            a.do && a.do();
        }
        this.ptr = this.actions.length;
    }
    undo() {
        for (var i = this.ptr - 1; i >= 0; i--) {
            var a = this.actions[i];
            a.undo && a.undo();
        }
        this.ptr = 0;
    }
    isEmpty() {
        return this.actions.length === 0;
    }
}


/***/ }),

/***/ 50870:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgWarningTriangle = function SvgWarningTriangle(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.1367 9.29317C12.5509 9.29317 12.8867 9.62895 12.8867 10.0432L12.8867 13.8015C12.8867 14.2157 12.5509 14.5515 12.1367 14.5515C11.7225 14.5515 11.3867 14.2157 11.3867 13.8015L11.3867 10.0432C11.3867 9.62895 11.7225 9.29317 12.1367 9.29317Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M11.0215 3.02737C11.3603 2.8309 11.745 2.72743 12.1367 2.72743C12.5283 2.72743 12.913 2.8309 13.2518 3.02737C13.59 3.22349 13.8705 3.50535 14.065 3.84448C14.0653 3.84506 14.0656 3.84565 14.066 3.84623L22.216 17.9235C22.4116 18.2623 22.5152 18.6473 22.5155 19.0384C22.5159 19.4296 22.4134 19.814 22.2184 20.1531C22.0234 20.4922 21.7428 20.7741 21.4045 20.9706C21.0663 21.167 20.6824 21.2712 20.2912 21.2726L20.2886 21.2726H3.98476L3.98212 21.2726C3.59096 21.2712 3.20703 21.167 2.86879 20.9706C2.53055 20.7741 2.24988 20.4922 2.0549 20.1531C1.85992 19.814 1.75747 19.4296 1.75781 19.0384C1.75816 18.6473 1.86129 18.2631 2.05687 17.9243L10.2074 3.84623C10.2077 3.84562 10.2081 3.84501 10.2084 3.8444C10.4029 3.5053 10.6834 3.22348 11.0215 3.02737ZM10.8583 4.21874L11.5074 4.59453L3.35591 18.6743C3.35585 18.6744 3.35596 18.6742 3.35591 18.6743C3.29186 18.7854 3.25793 18.9116 3.25781 19.0398C3.2577 19.1681 3.2913 19.2941 3.35526 19.4054C3.41922 19.5166 3.51128 19.6091 3.62222 19.6735C3.7329 19.7378 3.85849 19.7719 3.98648 19.7726H20.2868C20.4148 19.7719 20.5404 19.7378 20.6511 19.6735C20.7621 19.6091 20.8541 19.5166 20.9181 19.4054C20.982 19.2941 21.0156 19.1681 21.0155 19.0398C21.0154 18.9116 20.9817 18.7858 20.9177 18.6748C20.9176 18.6746 20.9178 18.6749 20.9177 18.6748L12.7641 4.59128C12.7008 4.48073 12.6095 4.38886 12.4993 4.32497C12.3891 4.26108 12.264 4.22743 12.1367 4.22743C12.0093 4.22743 11.8842 4.26108 11.774 4.32497C11.6638 4.38886 11.5725 4.48073 11.5092 4.59127L10.8583 4.21874Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.843 16.8287C12.843 17.2188 12.5267 17.5351 12.1366 17.5351C11.7464 17.5351 11.4302 17.2188 11.4302 16.8287C11.4302 16.4386 11.7464 16.1223 12.1366 16.1223C12.5267 16.1223 12.843 16.4386 12.843 16.8287Z",
    fill: "#F5F5F5",
    stroke: "#F5F5F5",
    strokeWidth: 0.125
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgWarningTriangle);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "4283a91da777159d6f9dc3835d867995.svg");

/***/ }),

/***/ 50935:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Models = exports.Messages = exports.Completions = exports.Beta = void 0;
const tslib_1 = __webpack_require__(84499);
tslib_1.__exportStar(__webpack_require__(61730), exports);
var beta_1 = __webpack_require__(82306);
Object.defineProperty(exports, "Beta", ({ enumerable: true, get: function () { return beta_1.Beta; } }));
var completions_1 = __webpack_require__(50856);
Object.defineProperty(exports, "Completions", ({ enumerable: true, get: function () { return completions_1.Completions; } }));
var messages_1 = __webpack_require__(41350);
Object.defineProperty(exports, "Messages", ({ enumerable: true, get: function () { return messages_1.Messages; } }));
var models_1 = __webpack_require__(60193);
Object.defineProperty(exports, "Models", ({ enumerable: true, get: function () { return models_1.Models; } }));
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 51025:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  En: () => (/* binding */ getCaptures),
  qu: () => (/* binding */ getFileFromExceedsError)
});

// UNUSED EXPORTS: escapeRegExp, getMatches

;// external "string.prototype.matchall"
const external_string_prototype_matchall_namespaceObject = require("string.prototype.matchall");
var external_string_prototype_matchall_default = /*#__PURE__*/__webpack_require__.n(external_string_prototype_matchall_namespaceObject);
;// ../noodl-git/src/core/helpers/regex.ts

/**
 * Get all regex captures within a body of text
 *
 * @param text string to search
 * @param re regex to search with. must have global option and one capture
 *
 * @returns arrays of strings captured by supplied regex
 */
function getCaptures(text, re) {
    const matches = getMatches(text, re);
    const captures = matches.reduce((acc, match) => acc.concat([match.slice(1)]), new Array());
    return captures;
}
/**
 * Get all regex matches within a body of text
 *
 * @param text string to search
 * @param re regex to search with. must have global option
 * @returns set of strings captured by supplied regex
 */
function getMatches(text, re) {
    if (re.global === false) {
        throw new Error('A regex has been provided that is not marked as global, and has the potential to execute forever if it finds a match');
    }
    const matches = new Array();
    let match = re.exec(text);
    while (match !== null) {
        matches.push(match);
        match = re.exec(text);
    }
    return matches;
}
/**
 * Replaces characters that have a semantic meaning inside of a regexp with
 * their escaped equivalent (i.e. `*` becomes `\*` etc).
 *
 * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
 */
function escapeRegExp(expression) {
    return expression.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');
}
/*
 * Looks for the phrases "remote: error File " and " is (file size I.E. 106.5 MB); this exceeds GitHub's file size limit of 100.00 MB"
 * inside of a string containing errors and return an array of all the filenames and their sizes located between these two strings.
 *
 * example return [ "LargeFile.exe (150.00 MB)", "AlsoTooLargeOfAFile.txt (1.00 GB)" ]
 */
function getFileFromExceedsError(error) {
    const endRegex = /(;\sthis\sexceeds\sGitHub's\sfile\ssize\slimit\sof\s100.00\sMB)/gm;
    const beginRegex = /(^remote:\serror:\sFile\s)/gm;
    const beginMatches = Array.from(external_string_prototype_matchall_default()(error, beginRegex));
    const endMatches = Array.from(external_string_prototype_matchall_default()(error, endRegex));
    // Something went wrong and we didn't find the same amount of endings as we did beginnings
    // Just return an empty array as the output we'd give would look weird anyway
    if (beginMatches.length !== endMatches.length) {
        return [];
    }
    const files = [];
    for (let index = 0; index < beginMatches.length; index++) {
        const beginMatch = beginMatches[index];
        const endMatch = endMatches[index];
        if (beginMatch.index === undefined || endMatch.index === undefined) {
            continue;
        }
        const from = beginMatch.index + beginMatch[0].length;
        const to = endMatch.index;
        let file = error.slice(from, to);
        file = file.replace('is ', '(');
        file += ')';
        files.push(file);
    }
    return files;
}


/***/ }),

/***/ 51124:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSeo = function SvgSeo(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12 5.25C9.92893 5.25 8.25 6.92893 8.25 9C8.25 10.1195 8.74056 11.1244 9.51845 11.8115C7.71591 12.6752 6.43353 14.4507 6.2681 16.5409C6.21309 17.236 6.78133 17.75 7.4 17.75H16.6C17.2187 17.75 17.7869 17.236 17.7319 16.5409C17.5665 14.4507 16.2841 12.6752 14.4816 11.8115C15.2594 11.1244 15.75 10.1195 15.75 9C15.75 6.92893 14.0711 5.25 12 5.25ZM9.75 9C9.75 7.75736 10.7574 6.75 12 6.75C13.2426 6.75 14.25 7.75736 14.25 9C14.25 10.2426 13.2426 11.25 12 11.25C10.7574 11.25 9.75 10.2426 9.75 9ZM12 12.75C14.0912 12.75 15.8302 14.2608 16.1841 16.25H7.81587C8.16982 14.2608 9.9088 12.75 12 12.75Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M23.75 12C23.75 18.4893 18.4893 23.75 12 23.75C5.51065 23.75 0.25 18.4893 0.25 12C0.25 5.51065 5.51065 0.25 12 0.25C18.4893 0.25 23.75 5.51065 23.75 12ZM12.75 1.77702V4C12.75 4.41421 12.4142 4.75 12 4.75C11.5858 4.75 11.25 4.41421 11.25 4V1.77702C6.18691 2.14317 2.14317 6.18691 1.77702 11.25H4C4.41421 11.25 4.75 11.5858 4.75 12C4.75 12.4142 4.41421 12.75 4 12.75H1.77702C2.14317 17.8131 6.18691 21.8568 11.25 22.223V20C11.25 19.5858 11.5858 19.25 12 19.25C12.4142 19.25 12.75 19.5858 12.75 20V22.223C17.8131 21.8568 21.8568 17.8131 22.223 12.75H20C19.5858 12.75 19.25 12.4142 19.25 12C19.25 11.5858 19.5858 11.25 20 11.25H22.223C21.8568 6.18691 17.8131 2.14317 12.75 1.77702Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSeo);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "3cf1198228ca2c6c876725a0fb4269f0.svg");

/***/ }),

/***/ 51171:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.JavaScriptEditor-module__Root--O50JM{display:flex;flex-direction:column;width:100%;height:100%;background-color:var(--theme-color-bg-1);border:1px solid var(--theme-color-border-default);border-radius:6px;overflow:hidden}.JavaScriptEditor-module__Toolbar--CSbu8{display:flex;align-items:center;justify-content:space-between;padding:8px 12px;background-color:var(--theme-color-bg-2);border-bottom:1px solid var(--theme-color-border-default);min-height:36px}.JavaScriptEditor-module__ToolbarLeft--_lEsy,.JavaScriptEditor-module__ToolbarRight--Kbi4V{display:flex;align-items:center;gap:12px}.JavaScriptEditor-module__ModeLabel--BeHMo{font-size:12px;font-weight:600;color:var(--theme-color-fg-default);text-transform:uppercase;letter-spacing:.5px}.JavaScriptEditor-module__StatusValid--GE9EZ{font-size:12px;font-weight:500;color:var(--theme-color-success)}.JavaScriptEditor-module__StatusInvalid--XFXP6{font-size:12px;font-weight:500;color:var(--theme-color-error)}.JavaScriptEditor-module__FormatButton--lO4Qe,.JavaScriptEditor-module__SaveButton--hZmfX{padding:6px 12px;font-size:12px;font-weight:500;border:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-3);color:var(--theme-color-fg-default);border-radius:4px;cursor:pointer;transition:all .15s ease}.JavaScriptEditor-module__FormatButton--lO4Qe:hover:not(:disabled),.JavaScriptEditor-module__SaveButton--hZmfX:hover:not(:disabled){background-color:var(--theme-color-bg-4);border-color:var(--theme-color-primary)}.JavaScriptEditor-module__FormatButton--lO4Qe:active:not(:disabled),.JavaScriptEditor-module__SaveButton--hZmfX:active:not(:disabled){transform:translateY(1px)}.JavaScriptEditor-module__FormatButton--lO4Qe:disabled,.JavaScriptEditor-module__SaveButton--hZmfX:disabled{cursor:not-allowed;opacity:.5}.JavaScriptEditor-module__SaveButton--hZmfX{background-color:var(--theme-color-primary);color:#fff;border-color:var(--theme-color-primary)}.JavaScriptEditor-module__SaveButton--hZmfX:hover:not(:disabled){background-color:var(--theme-color-primary-hover, var(--theme-color-primary));border-color:var(--theme-color-primary-hover, var(--theme-color-primary))}.JavaScriptEditor-module__CloseButton--Cgjkz{padding:6px 12px;font-size:12px;font-weight:500;border:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-4);color:var(--theme-color-fg-default);border-radius:4px;cursor:pointer;transition:all .15s ease}.JavaScriptEditor-module__CloseButton--Cgjkz:hover{background-color:var(--theme-color-bg-5);border-color:var(--theme-color-fg-default-shy)}.JavaScriptEditor-module__CloseButton--Cgjkz:active{transform:translateY(1px)}.JavaScriptEditor-module__EditorContainer--Hhy58{flex:1;overflow:hidden;position:relative;background-color:var(--theme-color-bg-2)}.JavaScriptEditor-module__EditorContainer--Hhy58 .cm-editor{height:100%;font-family:var(--theme-font-mono, "Monaco", "Menlo", "Courier New", monospace)}.JavaScriptEditor-module__EditorContainer--Hhy58 .cm-scroller{overflow:auto}.JavaScriptEditor-module__ErrorPanel--6YBAO{padding:12px 16px;background-color:#fef2f2;border-top:1px solid #fecaca}.JavaScriptEditor-module__ErrorHeader--dB4ta{display:flex;align-items:center;gap:8px;margin-bottom:8px}.JavaScriptEditor-module__ErrorIcon--AhquA{font-size:18px;line-height:1}.JavaScriptEditor-module__ErrorTitle--SyOEN{font-size:13px;font-weight:600;color:#dc2626}.JavaScriptEditor-module__ErrorMessage--UCWVj{font-size:13px;color:#7c2d12;line-height:1.5;font-family:var(--theme-font-mono, "Monaco", "Menlo", "Courier New", monospace);padding:8px 12px;background-color:#fff;border:1px solid #fecaca;border-radius:4px;margin-bottom:8px}.JavaScriptEditor-module__ErrorSuggestion--V2I5d{font-size:12px;color:#7c2d12;line-height:1.4;padding:8px 12px;background-color:#fef3c7;border:1px solid #fde68a;border-radius:4px;margin-bottom:8px}.JavaScriptEditor-module__ErrorSuggestion--V2I5d strong{font-weight:600}.JavaScriptEditor-module__ErrorLocation--if401{font-size:11px;color:#92400e;font-family:var(--theme-font-mono, "Monaco", "Menlo", "Courier New", monospace);font-weight:500}.JavaScriptEditor-module__Footer--ocTgf{display:flex;align-items:center;justify-content:space-between;padding:4px 8px;background-color:var(--theme-color-bg-2);border-top:1px solid var(--theme-color-border-default);min-height:24px;flex-shrink:0}.JavaScriptEditor-module__FooterLeft--QuREu,.JavaScriptEditor-module__FooterRight--oTfxX{display:flex;align-items:center;gap:8px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/code-editor/JavaScriptEditor.module.scss"],"names":[],"mappings":"AAKA,sCACE,YAAA,CACA,qBAAA,CACA,UAAA,CACA,WAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,eAAA,CAIF,yCACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,gBAAA,CACA,wCAAA,CACA,yDAAA,CACA,eAAA,CAGF,2FAEE,YAAA,CACA,kBAAA,CACA,QAAA,CAGF,2CACE,cAAA,CACA,eAAA,CACA,mCAAA,CACA,wBAAA,CACA,mBAAA,CAGF,6CACE,cAAA,CACA,eAAA,CACA,gCAAA,CAGF,+CACE,cAAA,CACA,eAAA,CACA,8BAAA,CAGF,0FAEE,gBAAA,CACA,cAAA,CACA,eAAA,CACA,kDAAA,CACA,wCAAA,CACA,mCAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CAEA,oIACE,wCAAA,CACA,uCAAA,CAGF,sIACE,yBAAA,CAGF,4GACE,kBAAA,CACA,UAAA,CAIJ,4CACE,2CAAA,CACA,UAAA,CACA,uCAAA,CAEA,iEACE,6EAAA,CACA,yEAAA,CAIJ,6CACE,gBAAA,CACA,cAAA,CACA,eAAA,CACA,kDAAA,CACA,wCAAA,CACA,mCAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CAEA,mDACE,wCAAA,CACA,8CAAA,CAGF,oDACE,yBAAA,CAKJ,iDACE,MAAA,CACA,eAAA,CACA,iBAAA,CACA,wCAAA,CAGA,4DACE,WAAA,CACA,+EAAA,CAGF,8DACE,aAAA,CAKJ,4CACE,iBAAA,CACA,wBAAA,CACA,4BAAA,CAGF,6CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,iBAAA,CAGF,2CACE,cAAA,CACA,aAAA,CAGF,4CACE,cAAA,CACA,eAAA,CACA,aAAA,CAGF,8CACE,cAAA,CACA,aAAA,CACA,eAAA,CACA,+EAAA,CACA,gBAAA,CACA,qBAAA,CACA,wBAAA,CACA,iBAAA,CACA,iBAAA,CAGF,iDACE,cAAA,CACA,aAAA,CACA,eAAA,CACA,gBAAA,CACA,wBAAA,CACA,wBAAA,CACA,iBAAA,CACA,iBAAA,CAEA,wDACE,eAAA,CAIJ,+CACE,cAAA,CACA,aAAA,CACA,+EAAA,CACA,eAAA,CAIF,wCACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,eAAA,CACA,wCAAA,CACA,sDAAA,CACA,eAAA,CACA,aAAA,CAGF,yFAEE,YAAA,CACA,kBAAA,CACA,OAAA","sourcesContent":["/**\n * JavaScriptEditor Component Styles\n * Uses design tokens for consistency with OpenNoodl design system\n */\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  width: 100%;\n  height: 100%;\n  background-color: var(--theme-color-bg-1);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 6px;\n  overflow: hidden;\n}\n\n/* Toolbar */\n.Toolbar {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 8px 12px;\n  background-color: var(--theme-color-bg-2);\n  border-bottom: 1px solid var(--theme-color-border-default);\n  min-height: 36px;\n}\n\n.ToolbarLeft,\n.ToolbarRight {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n}\n\n.ModeLabel {\n  font-size: 12px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n  text-transform: uppercase;\n  letter-spacing: 0.5px;\n}\n\n.StatusValid {\n  font-size: 12px;\n  font-weight: 500;\n  color: var(--theme-color-success);\n}\n\n.StatusInvalid {\n  font-size: 12px;\n  font-weight: 500;\n  color: var(--theme-color-error);\n}\n\n.FormatButton,\n.SaveButton {\n  padding: 6px 12px;\n  font-size: 12px;\n  font-weight: 500;\n  border: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-default);\n  border-radius: 4px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover:not(:disabled) {\n    background-color: var(--theme-color-bg-4);\n    border-color: var(--theme-color-primary);\n  }\n\n  &:active:not(:disabled) {\n    transform: translateY(1px);\n  }\n\n  &:disabled {\n    cursor: not-allowed;\n    opacity: 0.5;\n  }\n}\n\n.SaveButton {\n  background-color: var(--theme-color-primary);\n  color: white;\n  border-color: var(--theme-color-primary);\n\n  &:hover:not(:disabled) {\n    background-color: var(--theme-color-primary-hover, var(--theme-color-primary));\n    border-color: var(--theme-color-primary-hover, var(--theme-color-primary));\n  }\n}\n\n.CloseButton {\n  padding: 6px 12px;\n  font-size: 12px;\n  font-weight: 500;\n  border: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-4);\n  color: var(--theme-color-fg-default);\n  border-radius: 4px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-5);\n    border-color: var(--theme-color-fg-default-shy);\n  }\n\n  &:active {\n    transform: translateY(1px);\n  }\n}\n\n/* Editor Container with CodeMirror */\n.EditorContainer {\n  flex: 1;\n  overflow: hidden;\n  position: relative;\n  background-color: var(--theme-color-bg-2);\n\n  /* CodeMirror will fill this container */\n  :global(.cm-editor) {\n    height: 100%;\n    font-family: var(--theme-font-mono, 'Monaco', 'Menlo', 'Courier New', monospace);\n  }\n\n  :global(.cm-scroller) {\n    overflow: auto;\n  }\n}\n\n/* Error Panel */\n.ErrorPanel {\n  padding: 12px 16px;\n  background-color: #fef2f2;\n  border-top: 1px solid #fecaca;\n}\n\n.ErrorHeader {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin-bottom: 8px;\n}\n\n.ErrorIcon {\n  font-size: 18px;\n  line-height: 1;\n}\n\n.ErrorTitle {\n  font-size: 13px;\n  font-weight: 600;\n  color: #dc2626;\n}\n\n.ErrorMessage {\n  font-size: 13px;\n  color: #7c2d12;\n  line-height: 1.5;\n  font-family: var(--theme-font-mono, 'Monaco', 'Menlo', 'Courier New', monospace);\n  padding: 8px 12px;\n  background-color: #fff;\n  border: 1px solid #fecaca;\n  border-radius: 4px;\n  margin-bottom: 8px;\n}\n\n.ErrorSuggestion {\n  font-size: 12px;\n  color: #7c2d12;\n  line-height: 1.4;\n  padding: 8px 12px;\n  background-color: #fef3c7;\n  border: 1px solid #fde68a;\n  border-radius: 4px;\n  margin-bottom: 8px;\n\n  strong {\n    font-weight: 600;\n  }\n}\n\n.ErrorLocation {\n  font-size: 11px;\n  color: #92400e;\n  font-family: var(--theme-font-mono, 'Monaco', 'Menlo', 'Courier New', monospace);\n  font-weight: 500;\n}\n\n/* Footer with resize grip */\n.Footer {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 4px 8px;\n  background-color: var(--theme-color-bg-2);\n  border-top: 1px solid var(--theme-color-border-default);\n  min-height: 24px;\n  flex-shrink: 0;\n}\n\n.FooterLeft,\n.FooterRight {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `JavaScriptEditor-module__Root--O50JM`,
	"Toolbar": `JavaScriptEditor-module__Toolbar--CSbu8`,
	"ToolbarLeft": `JavaScriptEditor-module__ToolbarLeft--_lEsy`,
	"ToolbarRight": `JavaScriptEditor-module__ToolbarRight--Kbi4V`,
	"ModeLabel": `JavaScriptEditor-module__ModeLabel--BeHMo`,
	"StatusValid": `JavaScriptEditor-module__StatusValid--GE9EZ`,
	"StatusInvalid": `JavaScriptEditor-module__StatusInvalid--XFXP6`,
	"FormatButton": `JavaScriptEditor-module__FormatButton--lO4Qe`,
	"SaveButton": `JavaScriptEditor-module__SaveButton--hZmfX`,
	"CloseButton": `JavaScriptEditor-module__CloseButton--Cgjkz`,
	"EditorContainer": `JavaScriptEditor-module__EditorContainer--Hhy58`,
	"ErrorPanel": `JavaScriptEditor-module__ErrorPanel--6YBAO`,
	"ErrorHeader": `JavaScriptEditor-module__ErrorHeader--dB4ta`,
	"ErrorIcon": `JavaScriptEditor-module__ErrorIcon--AhquA`,
	"ErrorTitle": `JavaScriptEditor-module__ErrorTitle--SyOEN`,
	"ErrorMessage": `JavaScriptEditor-module__ErrorMessage--UCWVj`,
	"ErrorSuggestion": `JavaScriptEditor-module__ErrorSuggestion--V2I5d`,
	"ErrorLocation": `JavaScriptEditor-module__ErrorLocation--if401`,
	"Footer": `JavaScriptEditor-module__Footer--ocTgf`,
	"FooterLeft": `JavaScriptEditor-module__FooterLeft--QuREu`,
	"FooterRight": `JavaScriptEditor-module__FooterRight--oTfxX`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 51178:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ChainTimeline-module__ChainTimeline--WDQpD{display:flex;flex-direction:column;gap:16px}.ChainTimeline-module__ChainHeader--PFW1t{padding:12px;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:4px}.ChainTimeline-module__ChainInfo--GFLVb h3{margin:0 0 8px;font-size:14px;font-weight:600;color:var(--theme-color-fg-highlight)}.ChainTimeline-module__ChainMeta--u4xQA{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--theme-color-fg-default-shy)}.ChainTimeline-module__ChainMeta--u4xQA span:nth-child(2){color:var(--theme-color-fg-default-shy)}.ChainTimeline-module__TimelineList--cFslL{display:flex;flex-direction:column}.ChainTimeline-module__EmptyTimeline--Ut5xt{padding:48px 24px;text-align:center;background-color:var(--theme-color-bg-2);border:1px dashed var(--theme-color-border-default);border-radius:4px;color:var(--theme-color-fg-default-shy)}.ChainTimeline-module__EmptyTimeline--Ut5xt p{margin:0;font-size:13px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/ChainTimeline.module.scss"],"names":[],"mappings":"AAMA,4CACE,YAAA,CACA,qBAAA,CACA,QAAA,CAOF,0CACE,YAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CAIA,2CACE,cAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CAIJ,wCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,cAAA,CACA,uCAAA,CAGE,0DACE,uCAAA,CASN,2CACE,YAAA,CACA,qBAAA,CAOF,4CACE,iBAAA,CACA,iBAAA,CACA,wCAAA,CACA,mDAAA,CACA,iBAAA,CACA,uCAAA,CAEA,8CACE,QAAA,CACA,cAAA","sourcesContent":["/**\n * ChainTimeline Component Styles\n *\n * Uses design tokens from UI-STYLING-GUIDE.md\n */\n\n.ChainTimeline {\n  display: flex;\n  flex-direction: column;\n  gap: 16px;\n}\n\n/* =================================================================\n   Chain Header\n   ================================================================= */\n\n.ChainHeader {\n  padding: 12px;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n}\n\n.ChainInfo {\n  h3 {\n    margin: 0 0 8px;\n    font-size: 14px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n  }\n}\n\n.ChainMeta {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  font-size: 12px;\n  color: var(--theme-color-fg-default-shy);\n\n  span {\n    &:nth-child(2) {\n      color: var(--theme-color-fg-default-shy);\n    }\n  }\n}\n\n/* =================================================================\n   Timeline List\n   ================================================================= */\n\n.TimelineList {\n  display: flex;\n  flex-direction: column;\n}\n\n/* =================================================================\n   Empty Timeline\n   ================================================================= */\n\n.EmptyTimeline {\n  padding: 48px 24px;\n  text-align: center;\n  background-color: var(--theme-color-bg-2);\n  border: 1px dashed var(--theme-color-border-default);\n  border-radius: 4px;\n  color: var(--theme-color-fg-default-shy);\n\n  p {\n    margin: 0;\n    font-size: 13px;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"ChainTimeline": `ChainTimeline-module__ChainTimeline--WDQpD`,
	"ChainHeader": `ChainTimeline-module__ChainHeader--PFW1t`,
	"ChainInfo": `ChainTimeline-module__ChainInfo--GFLVb`,
	"ChainMeta": `ChainTimeline-module__ChainMeta--u4xQA`,
	"TimelineList": `ChainTimeline-module__TimelineList--cFslL`,
	"EmptyTimeline": `ChainTimeline-module__EmptyTimeline--Ut5xt`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 51183:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  c: () => (/* reexport */ EditorNode)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/common/EditorNode/EditorNode.module.scss
var EditorNode_module = __webpack_require__(94168);
;// ../noodl-core-ui/src/components/common/EditorNode/EditorNode.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(EditorNode_module/* default */.A, options);




       /* harmony default export */ const EditorNode_EditorNode_module = (EditorNode_module/* default */.A && EditorNode_module/* default */.A.locals ? EditorNode_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/common/EditorNode/EditorNode.tsx




function nodeNameToIconName(itemName) {
    switch (itemName) {
        case 'Group':
            return Icon/* IconName */.$M.Group;
        case 'Text':
            return Icon/* IconName */.$M.TextInBox;
        case 'Image':
            return Icon/* IconName */.$M.Image;
        case 'Video':
            return Icon/* IconName */.$M.Video;
        case 'Circle':
            return Icon/* IconName */.$M.CircleOpen;
        case 'net.noodl.visual.icon':
            return Icon/* IconName */.$M.Icon;
        case 'net.noodl.controls.button':
            return Icon/* IconName */.$M.Button;
        case 'net.noodl.controls.checkbox':
            return Icon/* IconName */.$M.CheckboxFilled;
        case 'net.noodl.controls.options':
            return Icon/* IconName */.$M.DropdownLines;
        case 'net.noodl.controls.radiobutton':
            return Icon/* IconName */.$M.Radiobutton;
        case 'Radio Button Group':
            return Icon/* IconName */.$M.RadiobuttonGroup;
        case 'net.noodl.controls.range':
            return Icon/* IconName */.$M.SlidersFilled;
        case 'net.noodl.controls.textinput':
            return Icon/* IconName */.$M.TextInput;
        case 'net.noodl.visual.columns':
            return Icon/* IconName */.$M.Columns;
        default:
            return null;
    }
}
function EditorNode({ item, colors, isHighlighted }) {
    const iconName = nodeNameToIconName(item.name);
    return (external_react_default().createElement("div", { className: external_classnames_default()([EditorNode_EditorNode_module['Root'], isHighlighted && EditorNode_EditorNode_module['is-highlighted']]), style: {
            '--textColor': colors.text,
            '--baseColor': colors.headerHighlighted,
            '--highlightColor': colors.baseHighlighted
        } },
        iconName && external_react_default().createElement(Icon/* Icon */.In, { icon: iconName, size: Icon/* IconSize */.lK.Small }),
        external_react_default().createElement("span", { className: external_classnames_default()(EditorNode_EditorNode_module['Label'], iconName && EditorNode_EditorNode_module['is-after-icon']) }, item.displayName || item.displayNodeName || item.name)));
}

;// ../noodl-core-ui/src/components/common/EditorNode/index.ts



/***/ }),

/***/ 51251:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Carousel-module__Root--C4cUC{width:100%;height:100%;display:flex;flex-direction:column;justify-content:space-between}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/Carousel/Carousel.module.scss"],"names":[],"mappings":"AAAA,8BACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,qBAAA,CACA,6BAAA","sourcesContent":[".Root {\n  width: 100%;\n  height: 100%;\n  display: flex;\n  flex-direction: column;\n  justify-content: space-between;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Carousel-module__Root--C4cUC`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 51254:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
.monaco-editor .cursors-layer {
	position: absolute;
	top: 0;
}

.monaco-editor .cursors-layer > .cursor {
	position: absolute;
	overflow: hidden;
}

/* -- smooth-caret-animation -- */
.monaco-editor .cursors-layer.cursor-smooth-caret-animation > .cursor {
	transition: all 80ms;
}

/* -- block-outline-style -- */
.monaco-editor .cursors-layer.cursor-block-outline-style > .cursor {
	box-sizing: border-box;
	background: transparent !important;
	border-style: solid;
	border-width: 1px;
}

/* -- underline-style -- */
.monaco-editor .cursors-layer.cursor-underline-style > .cursor {
	border-bottom-width: 2px;
	border-bottom-style: solid;
	background: transparent !important;
	box-sizing: border-box;
}

/* -- underline-thin-style -- */
.monaco-editor .cursors-layer.cursor-underline-thin-style > .cursor {
	border-bottom-width: 1px;
	border-bottom-style: solid;
	background: transparent !important;
	box-sizing: border-box;
}

@keyframes monaco-cursor-smooth {
	0%,
	20% {
		opacity: 1;
	}
	60%,
	100% {
		opacity: 0;
	}
}

@keyframes monaco-cursor-phase {
	0%,
	20% {
		opacity: 1;
	}
	90%,
	100% {
		opacity: 0;
	}
}

@keyframes monaco-cursor-expand {
	0%,
	20% {
		transform: scaleY(1);
	}
	80%,
	100% {
		transform: scaleY(0);
	}
}

.cursor-smooth {
	animation: monaco-cursor-smooth 0.5s ease-in-out 0s 20 alternate;
}

.cursor-phase {
	animation: monaco-cursor-phase 0.5s ease-in-out 0s 20 alternate;
}

.cursor-expand > .cursor {
	animation: monaco-cursor-expand 0.5s ease-in-out 0s 20 alternate;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/viewCursors/viewCursors.css"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;CACC,kBAAkB;CAClB,MAAM;AACP;;AAEA;CACC,kBAAkB;CAClB,gBAAgB;AACjB;;AAEA,iCAAiC;AACjC;CACC,oBAAoB;AACrB;;AAEA,8BAA8B;AAC9B;CACC,sBAAsB;CACtB,kCAAkC;CAClC,mBAAmB;CACnB,iBAAiB;AAClB;;AAEA,0BAA0B;AAC1B;CACC,wBAAwB;CACxB,0BAA0B;CAC1B,kCAAkC;CAClC,sBAAsB;AACvB;;AAEA,+BAA+B;AAC/B;CACC,wBAAwB;CACxB,0BAA0B;CAC1B,kCAAkC;CAClC,sBAAsB;AACvB;;AAEA;CACC;;EAEC,UAAU;CACX;CACA;;EAEC,UAAU;CACX;AACD;;AAEA;CACC;;EAEC,UAAU;CACX;CACA;;EAEC,UAAU;CACX;AACD;;AAEA;CACC;;EAEC,oBAAoB;CACrB;CACA;;EAEC,oBAAoB;CACrB;AACD;;AAEA;CACC,gEAAgE;AACjE;;AAEA;CACC,+DAA+D;AAChE;;AAEA;CACC,gEAAgE;AACjE","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n.monaco-editor .cursors-layer {\n\tposition: absolute;\n\ttop: 0;\n}\n\n.monaco-editor .cursors-layer > .cursor {\n\tposition: absolute;\n\toverflow: hidden;\n}\n\n/* -- smooth-caret-animation -- */\n.monaco-editor .cursors-layer.cursor-smooth-caret-animation > .cursor {\n\ttransition: all 80ms;\n}\n\n/* -- block-outline-style -- */\n.monaco-editor .cursors-layer.cursor-block-outline-style > .cursor {\n\tbox-sizing: border-box;\n\tbackground: transparent !important;\n\tborder-style: solid;\n\tborder-width: 1px;\n}\n\n/* -- underline-style -- */\n.monaco-editor .cursors-layer.cursor-underline-style > .cursor {\n\tborder-bottom-width: 2px;\n\tborder-bottom-style: solid;\n\tbackground: transparent !important;\n\tbox-sizing: border-box;\n}\n\n/* -- underline-thin-style -- */\n.monaco-editor .cursors-layer.cursor-underline-thin-style > .cursor {\n\tborder-bottom-width: 1px;\n\tborder-bottom-style: solid;\n\tbackground: transparent !important;\n\tbox-sizing: border-box;\n}\n\n@keyframes monaco-cursor-smooth {\n\t0%,\n\t20% {\n\t\topacity: 1;\n\t}\n\t60%,\n\t100% {\n\t\topacity: 0;\n\t}\n}\n\n@keyframes monaco-cursor-phase {\n\t0%,\n\t20% {\n\t\topacity: 1;\n\t}\n\t90%,\n\t100% {\n\t\topacity: 0;\n\t}\n}\n\n@keyframes monaco-cursor-expand {\n\t0%,\n\t20% {\n\t\ttransform: scaleY(1);\n\t}\n\t80%,\n\t100% {\n\t\ttransform: scaleY(0);\n\t}\n}\n\n.cursor-smooth {\n\tanimation: monaco-cursor-smooth 0.5s ease-in-out 0s 20 alternate;\n}\n\n.cursor-phase {\n\tanimation: monaco-cursor-phase 0.5s ease-in-out 0s 20 alternate;\n}\n\n.cursor-expand > .cursor {\n\tanimation: monaco-cursor-expand 0.5s ease-in-out 0s 20 alternate;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 51436:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  nd: () => (/* reexport */ CheckoutProgressParser),
  gG: () => (/* reexport */ CloneProgressParser),
  Pm: () => (/* reexport */ FetchProgressParser),
  I8: () => (/* reexport */ PullProgressParser),
  LP: () => (/* reexport */ PushProgressParser),
  s_: () => (/* reexport */ executionOptionsWithProgress)
});

// UNUSED EXPORTS: GitProgressParser, parse

;// ../noodl-git/src/core/progress/common.ts
/**
 * A utility class for interpreting progress output from `git`
 * and turning that into a percentage value estimating the overall progress
 * of the an operation. An operation could be something like `git fetch`
 * which contains multiple steps, each individually reported by Git as
 * progress events between 0 and 100%.
 *
 * A parser cannot be reused, it's mean to parse a single stderr stream
 * for Git.
 */
class GitProgressParser {
    /**
     * Initialize a new instance of a Git progress parser.
     *
     * @param steps - A series of steps that could be present in the git
     *                output with relative weight between these steps. Note
     *                that order is significant here as once the parser sees
     *                a progress line that matches a step all previous steps
     *                are considered completed and overall progress is adjusted
     *                accordingly.
     */
    constructor(steps) {
        /* The provided steps should always occur in order but some
         * might not happen at all (like remote compression of objects) so
         * we keep track of the "highest" seen step so that we can fill in
         * progress with the assumption that we've already seen the previous
         * steps.
         */
        this.stepIndex = 0;
        this.lastPercent = 0;
        if (!steps.length) {
            throw new Error('must specify at least one step');
        }
        // Scale the step weight so that they're all a percentage
        // adjusted to the total weight of all steps.
        const totalStepWeight = steps.reduce((sum, step) => sum + step.weight, 0);
        this.steps = steps.map((step) => ({
            title: step.title,
            weight: step.weight / totalStepWeight
        }));
    }
    /**
     * Parse the given line of output from Git, returns either an `IGitProgress`
     * instance if the line could successfully be parsed as a Git progress
     * event whose title was registered with this parser or an `IGitOutput`
     * instance if the line couldn't be parsed or if the title wasn't
     * registered with the parser.
     */
    parse(line) {
        const progress = parse(line);
        if (!progress) {
            return { kind: 'context', text: line, percent: this.lastPercent };
        }
        let percent = 0;
        for (let i = 0; i < this.steps.length; i++) {
            const step = this.steps[i];
            if (i >= this.stepIndex && progress.title === step.title) {
                if (progress.total) {
                    percent += step.weight * (progress.value / progress.total);
                }
                this.stepIndex = i;
                this.lastPercent = percent;
                return { kind: 'progress', percent, details: progress };
            }
            else {
                percent += step.weight;
            }
        }
        return { kind: 'context', text: line, percent: this.lastPercent };
    }
}
const percentRe = /^(\d{1,3})% \((\d+)\/(\d+)\)$/;
const valueOnlyRe = /^\d+$/;
/**
 * Attempts to parse a single line of progress output from Git.
 *
 * For details about how Git formats progress see
 *
 *   https://github.com/git/git/blob/6a2c2f8d34fa1e8f3bb85d159d354810ed63692e/progress.c
 *
 * Some examples:
 *  remote: Counting objects: 123
 *  remote: Counting objects: 167587, done.
 *  Receiving objects:  99% (166741/167587), 272.10 MiB | 2.39 MiB/s
 *  Checking out files:  100% (728/728)
 *  Checking out files:  100% (728/728), done
 *
 * @returns An object containing well-structured information about the progress
 *          or null if the line could not be parsed as a Git progress line.
 */
function parse(line) {
    const titleLength = line.lastIndexOf(': ');
    if (titleLength === 0) {
        return null;
    }
    if (titleLength - 2 >= line.length) {
        return null;
    }
    const title = line.substring(0, titleLength);
    const progressText = line.substring(title.length + 2).trim();
    if (!progressText.length) {
        return null;
    }
    const progressParts = progressText.split(', ');
    if (!progressParts.length) {
        return null;
    }
    let value;
    let total = undefined;
    let percent = undefined;
    if (valueOnlyRe.test(progressParts[0])) {
        value = parseInt(progressParts[0], 10);
        if (isNaN(value)) {
            return null;
        }
    }
    else {
        const percentMatch = percentRe.exec(progressParts[0]);
        if (!percentMatch || percentMatch.length !== 4) {
            return null;
        }
        percent = parseInt(percentMatch[1], 10);
        value = parseInt(percentMatch[2], 10);
        total = parseInt(percentMatch[3], 10);
        if (isNaN(percent) || isNaN(value) || isNaN(total)) {
            return null;
        }
    }
    let done = false;
    // We don't parse throughput at the moment so let's just loop
    // through the remaining
    for (let i = 1; i < progressParts.length; i++) {
        if (progressParts[i] === 'done.') {
            done = true;
            break;
        }
    }
    return { title, value, percent, total, done, text: line };
}

;// ../noodl-git/src/core/progress/checkout.ts

const steps = [{ title: 'Checking out files', weight: 1 }];
/**
 * A class that parses output from `git checkout --progress` and provides
 * structured progress events.
 */
class CheckoutProgressParser extends GitProgressParser {
    constructor() {
        super(steps);
    }
}

;// ../noodl-git/src/core/progress/clone.ts

/**
 * Highly approximate (some would say outright inaccurate) division
 * of the individual progress reporting steps in a clone operation
 */
const clone_steps = [
    // NOTE: Accordning to GitHub Counting objects should take the same time
    //       as Compressing objects just I am not getting
    //       the other codes in my tests.
    { title: 'remote: Counting objects', weight: 0.9 },
    { title: 'remote: Compressing objects', weight: 0.1 },
    { title: 'Receiving objects', weight: 0.6 },
    { title: 'Resolving deltas', weight: 0.1 },
    { title: 'Checking out files', weight: 0.2 }
];
/**
 * A utility class for interpreting the output from `git clone --progress`
 * and turning that into a percentage value estimating the overall progress
 * of the clone.
 */
class CloneProgressParser extends GitProgressParser {
    constructor() {
        super(clone_steps);
    }
}

;// ../noodl-git/src/core/progress/push.ts

/**
 * Highly approximate (some would say outright inaccurate) division
 * of the individual progress reporting steps in a push operation
 */
const push_steps = [
    { title: 'Compressing objects', weight: 0.2 },
    { title: 'Writing objects', weight: 0.7 },
    { title: 'remote: Resolving deltas', weight: 0.1 }
];
/**
 * A utility class for interpreting the output from `git push --progress`
 * and turning that into a percentage value estimating the overall progress
 * of the clone.
 */
class PushProgressParser extends GitProgressParser {
    constructor() {
        super(push_steps);
    }
}

;// ../noodl-git/src/core/progress/fetch.ts

/**
 * Highly approximate (some would say outright inaccurate) division
 * of the individual progress reporting steps in a fetch operation
 */
const fetch_steps = [
    { title: 'remote: Compressing objects', weight: 0.1 },
    { title: 'Receiving objects', weight: 0.7 },
    { title: 'Resolving deltas', weight: 0.2 }
];
/**
 * A utility class for interpreting the output from `git fetch --progress`
 * and turning that into a percentage value estimating the overall progress
 * of the fetch.
 */
class FetchProgressParser extends GitProgressParser {
    constructor() {
        super(fetch_steps);
    }
}

;// ../noodl-git/src/core/progress/pull.ts

/**
 * Highly approximate (some would say outright inaccurate) division
 * of the individual progress reporting steps in a pull operation.
 *
 * Note: A pull is essentially the same as a fetch except we might
 * have to check out some files at the end. We assume that these
 * delta updates are fairly quick though.
 */
const pull_steps = [
    { title: 'remote: Compressing objects', weight: 0.1 },
    { title: 'Receiving objects', weight: 0.7 },
    { title: 'Resolving deltas', weight: 0.15 },
    { title: 'Checking out files', weight: 0.15 }
];
/**
 * A utility class for interpreting the output from `git pull --progress`
 * and turning that into a percentage value estimating the overall progress
 * of the pull.
 */
class PullProgressParser extends GitProgressParser {
    constructor() {
        super(pull_steps);
    }
}

;// ../noodl-git/src/core/helpers/object.ts
/** Create a copy of an object by merging it with a subset of its properties. */
function merge(obj, subset) {
    const copy = Object.assign({}, obj);
    for (const k in subset) {
        copy[k] = subset[k];
    }
    return copy;
}

;// ../noodl-git/src/core/progress/from-process.ts

/**
 * Merges an instance of GitExecutionOptions with a process callback provided
 * by createProgressProcessCallback.
 *
 * If the given options object already has a processCallback specified it will
 * be overwritten.
 */
async function executionOptionsWithProgress(options, parser, progressCallback) {
    let env = {};
    return merge(options, {
        spawn: true,
        /**
         * Returns a callback which can be passed along to the processCallback option
         * in IGitExecution. The callback then takes care of reading stderr of the
         * process and parsing its contents using the provided parser.
         */
        processDataCallback: (chunk) => {
            const lines = chunk.toString().split(/[\r\n]/g);
            lines.forEach((line) => {
                if (!line)
                    return;
                const progress = parser.parse(line);
                progressCallback(progress);
            });
        },
        // NOTE: This is we want to use spawn: false later
        //     processCallback: (process) => {
        //       console.log('pid', process.pid);
        //
        //       const callback = (line: Buffer) => {
        //         console.log(line.toString());
        //         const progress = parser.parse(line.toString());
        //         progressCallback(progress);
        //       }
        //
        //       byline(process.stdout).on("data", callback);
        //       byline(process.stderr).on("data", callback);
        //     },
        env: merge(options.env, env)
    });
}

;// ../noodl-git/src/core/progress/index.ts









/***/ }),

/***/ 51490:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ToastLayerContainer-module__Root--a9uBa{position:absolute;width:100%;height:100%;pointer-events:none}.ToastLayerContainer-module__Root--a9uBa>*{pointer-events:all}.ToastLayerContainer-module__Root--a9uBa>div>div>div>div{margin:0 !important}.ToastLayerContainer-module__ToastContainer--jhn1e{filter:drop-shadow(0px 0px 20px)}.ToastLayerContainer-module__Debugger--GOAsY{position:absolute;bottom:0;right:0;display:flex;flex-direction:column}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/ToastLayer/ToastLayerContainer.module.scss"],"names":[],"mappings":"AAAA,yCACE,iBAAA,CACA,UAAA,CACA,WAAA,CACA,mBAAA,CAEA,2CACE,kBAAA,CAGF,yDACE,mBAAA,CAIJ,mDACE,gCAAA,CAGF,6CACE,iBAAA,CACA,QAAA,CACA,OAAA,CACA,YAAA,CACA,qBAAA","sourcesContent":[".Root {\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  pointer-events: none;\n\n  > * {\n    pointer-events: all;\n  }\n\n  > div > div > div > div {\n    margin: 0 !important;\n  }\n}\n\n.ToastContainer {\n  filter: drop-shadow(0px 0px 20px);\n}\n\n.Debugger {\n  position: absolute;\n  bottom: 0;\n  right: 0;\n  display: flex;\n  flex-direction: column;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ToastLayerContainer-module__Root--a9uBa`,
	"ToastContainer": `ToastLayerContainer-module__ToastContainer--jhn1e`,
	"Debugger": `ToastLayerContainer-module__Debugger--GOAsY`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 51681:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.VisualCanvas-module__Background--K0Sdc{background-color:var(--theme-color-bg-1);background-image:linear-gradient(45deg, var(--theme-color-bg-0) 25%, transparent 25%),linear-gradient(-45deg, var(--theme-color-bg-0) 25%, transparent 25%),linear-gradient(45deg, transparent 75%, var(--theme-color-bg-0) 75%),linear-gradient(-45deg, transparent 75%, var(--theme-color-bg-0) 75%);background-size:20px 20px;background-position:0 0,0 10px,10px -10px,-10px 0px;width:100%;height:100%;display:flex;flex-direction:column;overflow:hidden}.VisualCanvas-module__ViewportInfo--gmCdy{color:var(--theme-color-fg-default);padding:8px;font-size:12px;line-height:1;position:absolute;background-color:var(--theme-color-bg-3);pointer-events:none}.VisualCanvas-module__WebviewContainer--EQ7Nl{display:flex;align-self:stretch;flex-grow:1;overflow:auto}.VisualCanvas-module__WebviewContainer--EQ7Nl::-webkit-scrollbar-thumb{background:var(--base-color-grey-500);border-radius:0px;border:none;border-left:6px solid rgba(0,0,0,0);border-top:6px solid rgba(0,0,0,0);background-clip:padding-box}.VisualCanvas-module__WebviewContainer--EQ7Nl::-webkit-scrollbar{width:12px;height:12px;cursor:pointer}.VisualCanvas-module__WebviewContainer--EQ7Nl::-webkit-scrollbar-button,.VisualCanvas-module__WebviewContainer--EQ7Nl::-webkit-scrollbar-track-piece,.VisualCanvas-module__WebviewContainer--EQ7Nl::-webkit-scrollbar-corner{display:none}.VisualCanvas-module__Webview--MlnpH{flex-shrink:0;flex-grow:0}.VisualCanvas-module__Crashed--r1Q67{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background-color:var(--theme-color-bg-2)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/VisualCanvas/VisualCanvas.module.scss"],"names":[],"mappings":"AAAA,wCACE,wCAAA,CACA,sSAAA,CAIA,yBAAA,CACA,mDAAA,CAEA,UAAA,CACA,WAAA,CAEA,YAAA,CACA,qBAAA,CACA,eAAA,CAGF,0CACE,mCAAA,CACA,WAAA,CACA,cAAA,CACA,aAAA,CACA,iBAAA,CACA,wCAAA,CACA,mBAAA,CAGF,8CACE,YAAA,CACA,kBAAA,CACA,WAAA,CACA,aAAA,CAEA,uEACE,qCAAA,CACA,iBAAA,CACA,WAAA,CACA,mCAAA,CACA,kCAAA,CACA,2BAAA,CAGF,iEACE,UAAA,CACA,WAAA,CACA,cAAA,CAGF,6NAGE,YAAA,CAIJ,qCACE,aAAA,CACA,WAAA,CAGF,qCACE,iBAAA,CACA,OAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,wCAAA","sourcesContent":[".Background {\n  background-color: var(--theme-color-bg-1);\n  background-image: linear-gradient(45deg, var(--theme-color-bg-0) 25%, transparent 25%),\n    linear-gradient(-45deg, var(--theme-color-bg-0) 25%, transparent 25%),\n    linear-gradient(45deg, transparent 75%, var(--theme-color-bg-0) 75%),\n    linear-gradient(-45deg, transparent 75%, var(--theme-color-bg-0) 75%);\n  background-size: 20px 20px;\n  background-position: 0 0, 0 10px, 10px -10px, -10px 0px;\n\n  width: 100%;\n  height: 100%;\n\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n\n.ViewportInfo {\n  color: var(--theme-color-fg-default);\n  padding: 8px;\n  font-size: 12px;\n  line-height: 1;\n  position: absolute;\n  background-color: var(--theme-color-bg-3);\n  pointer-events: none;\n}\n\n.WebviewContainer {\n  display: flex;\n  align-self: stretch;\n  flex-grow: 1;\n  overflow: auto;\n\n  &::-webkit-scrollbar-thumb {\n    background: var(--base-color-grey-500);\n    border-radius: 0px;\n    border: none;\n    border-left: 6px solid transparent;\n    border-top: 6px solid transparent;\n    background-clip: padding-box;\n  }\n\n  &::-webkit-scrollbar {\n    width: 12px;\n    height: 12px;\n    cursor: pointer;\n  }\n\n  &::-webkit-scrollbar-button,\n  &::-webkit-scrollbar-track-piece,\n  &::-webkit-scrollbar-corner {\n    display: none;\n  }\n}\n\n.Webview {\n  flex-shrink: 0;\n  flex-grow: 0;\n}\n\n.Crashed {\n  position: absolute;\n  inset: 0;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  background-color: var(--theme-color-bg-2);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Background": `VisualCanvas-module__Background--K0Sdc`,
	"ViewportInfo": `VisualCanvas-module__ViewportInfo--gmCdy`,
	"WebviewContainer": `VisualCanvas-module__WebviewContainer--EQ7Nl`,
	"Webview": `VisualCanvas-module__Webview--MlnpH`,
	"Crashed": `VisualCanvas-module__Crashed--r1Q67`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 51726:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
.monaco-editor .overlayWidgets {
	position: absolute;
	top: 0;
	left:0;
}`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/overlayWidgets/overlayWidgets.css"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;CACC,kBAAkB;CAClB,MAAM;CACN,MAAM;AACP","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n.monaco-editor .overlayWidgets {\n\tposition: absolute;\n\ttop: 0;\n\tleft:0;\n}"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 51766:
/***/ ((module) => {

// Module
var code = "<div class=\"popup confirm-modal\"> <label data-text=\"title\"></label> <p data-html=\"message\"></p> <div class=\"confirm-buttons\"> <button class=\"confirm-button\" data-click=\"onConfirmClicked\" data-text=\"confirmLabel\" data-test=\"confirm-button\"></button> <button class=\"cancel-button\" data-click=\"onCancelClicked\" data-text=\"cancelLabel\"></button> </div> </div> ";
// Exports
module.exports = code;

/***/ }),

/***/ 51794:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.CodeHistoryDiffModal-module__Overlay--Rv0Nt{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.7);display:flex;align-items:center;justify-content:center;z-index:10000;animation:CodeHistoryDiffModal-module__fadeIn--Od2TG .2s ease}.CodeHistoryDiffModal-module__Modal--GsAQf{background:var(--theme-color-bg-1);border:1px solid var(--theme-color-border-default);border-radius:12px;box-shadow:0 16px 48px rgba(0,0,0,.6);width:90vw;max-width:1200px;max-height:90vh;display:flex;flex-direction:column;animation:CodeHistoryDiffModal-module__scaleIn--I0aNs .2s ease}.CodeHistoryDiffModal-module__Header--W7mf0{display:flex;align-items:center;justify-content:space-between;padding:20px 24px;border-bottom:1px solid var(--theme-color-border-default)}.CodeHistoryDiffModal-module__Title--ZEIyS{margin:0;font-size:17px;font-weight:600;color:var(--theme-color-fg-default)}.CodeHistoryDiffModal-module__CloseButton--lsbVn{background:none;border:none;color:var(--theme-color-fg-default-shy);font-size:28px;line-height:1;cursor:pointer;padding:0;width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:6px;transition:all .15s ease}.CodeHistoryDiffModal-module__CloseButton--lsbVn:hover{background:var(--theme-color-bg-3);color:var(--theme-color-fg-default)}.CodeHistoryDiffModal-module__DiffContainer--Y7rlR{display:flex;gap:16px;padding:24px;overflow:hidden;flex:1;min-height:0}.CodeHistoryDiffModal-module__DiffSide--Q2HqX{flex:1;display:flex;flex-direction:column;min-width:0;background:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:8px;overflow:hidden}.CodeHistoryDiffModal-module__DiffHeader--b5aLE{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;background:var(--theme-color-bg-3);border-bottom:1px solid var(--theme-color-border-default)}.CodeHistoryDiffModal-module__DiffLabel--oytna{font-size:13px;font-weight:600;color:var(--theme-color-fg-default)}.CodeHistoryDiffModal-module__DiffInfo--jikz7{display:flex;gap:8px;font-size:12px;font-weight:600}.CodeHistoryDiffModal-module__Additions--Mme84{color:#4ade80}.CodeHistoryDiffModal-module__Deletions--e4tg0{color:#f87171}.CodeHistoryDiffModal-module__Modifications--fgfhv{color:#fbbf24}.CodeHistoryDiffModal-module__DiffCode--eFR9W{flex:1;overflow-y:auto;font-family:"SF Mono",Monaco,"Cascadia Code","Roboto Mono",Consolas,"Courier New",monospace;font-size:13px;line-height:1.6}.CodeHistoryDiffModal-module__DiffLine--DK8uo{display:flex;padding:2px 0;min-height:21px;transition:background .1s ease}.CodeHistoryDiffModal-module__DiffLine--DK8uo:hover{background:hsla(0,0%,100%,.03)}.CodeHistoryDiffModal-module__LineNumber--YtK1F{flex-shrink:0;width:50px;padding:0 12px;text-align:right;color:var(--theme-color-fg-default-shy);user-select:none;font-size:12px}.CodeHistoryDiffModal-module__LineContent--kF7zL{flex:1;padding-right:12px;white-space:pre;overflow-x:auto;color:var(--theme-color-fg-default)}.CodeHistoryDiffModal-module__DiffLineAdded--KbrWV{background:rgba(74,222,128,.15)}.CodeHistoryDiffModal-module__DiffLineAdded--KbrWV .CodeHistoryDiffModal-module__LineNumber--YtK1F{background:rgba(74,222,128,.2);color:#4ade80}.CodeHistoryDiffModal-module__DiffLineAdded--KbrWV .CodeHistoryDiffModal-module__LineContent--kF7zL{color:#d9f99d}.CodeHistoryDiffModal-module__DiffLineRemoved--DyDNY{background:rgba(248,113,113,.15)}.CodeHistoryDiffModal-module__DiffLineRemoved--DyDNY .CodeHistoryDiffModal-module__LineNumber--YtK1F{background:rgba(248,113,113,.2);color:#f87171}.CodeHistoryDiffModal-module__DiffLineRemoved--DyDNY .CodeHistoryDiffModal-module__LineContent--kF7zL{color:#fecaca;text-decoration:line-through;opacity:.8}.CodeHistoryDiffModal-module__DiffLineModified--WLXrn{background:rgba(251,191,36,.12)}.CodeHistoryDiffModal-module__DiffLineModified--WLXrn .CodeHistoryDiffModal-module__LineNumber--YtK1F{background:rgba(251,191,36,.2);color:#fbbf24}.CodeHistoryDiffModal-module__DiffLineModified--WLXrn .CodeHistoryDiffModal-module__LineContent--kF7zL{color:#fef3c7}.CodeHistoryDiffModal-module__DiffLineEmpty--UcRhR{background:hsla(0,0%,100%,.02);opacity:.3}.CodeHistoryDiffModal-module__DiffLineEmpty--UcRhR .CodeHistoryDiffModal-module__LineNumber--YtK1F{opacity:0}.CodeHistoryDiffModal-module__DiffLineEmpty--UcRhR .CodeHistoryDiffModal-module__LineContent--kF7zL{opacity:0}.CodeHistoryDiffModal-module__DiffSeparator--lAlL0{display:flex;align-items:center;justify-content:center;color:var(--theme-color-fg-default-shy);opacity:.6}.CodeHistoryDiffModal-module__Summary--uCdPO{padding:16px 24px;border-top:1px solid var(--theme-color-border-default);border-bottom:1px solid var(--theme-color-border-default);background:var(--theme-color-bg-2);display:flex;flex-direction:column;gap:6px;font-size:13px;color:var(--theme-color-fg-default-shy)}.CodeHistoryDiffModal-module__Footer--H5X8F{display:flex;align-items:center;justify-content:flex-end;gap:12px;padding:20px 24px}.CodeHistoryDiffModal-module__CancelButton--TkZg3{padding:10px 20px;background:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:6px;color:var(--theme-color-fg-default);font-size:14px;font-weight:500;cursor:pointer;transition:all .15s ease}.CodeHistoryDiffModal-module__CancelButton--TkZg3:hover{background:var(--theme-color-bg-3);border-color:var(--theme-color-border-highlight)}.CodeHistoryDiffModal-module__RestoreButton--Ytjsp{padding:10px 20px;background:var(--theme-color-primary);border:1px solid var(--theme-color-primary);border-radius:6px;color:#fff;font-size:14px;font-weight:600;cursor:pointer;transition:all .15s ease}.CodeHistoryDiffModal-module__RestoreButton--Ytjsp:hover{background:var(--theme-color-primary-highlight);border-color:var(--theme-color-primary-highlight);transform:translateY(-1px);box-shadow:0 4px 12px rgba(59,130,246,.4)}.CodeHistoryDiffModal-module__RestoreButton--Ytjsp:active{transform:translateY(0)}@keyframes CodeHistoryDiffModal-module__fadeIn--Od2TG{from{opacity:0}to{opacity:1}}@keyframes CodeHistoryDiffModal-module__scaleIn--I0aNs{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}.CodeHistoryDiffModal-module__DiffCode--eFR9W::-webkit-scrollbar{width:8px;height:8px}.CodeHistoryDiffModal-module__DiffCode--eFR9W::-webkit-scrollbar-track{background:var(--theme-color-bg-1)}.CodeHistoryDiffModal-module__DiffCode--eFR9W::-webkit-scrollbar-thumb{background:var(--theme-color-border-default);border-radius:4px}.CodeHistoryDiffModal-module__DiffCode--eFR9W::-webkit-scrollbar-thumb:hover{background:var(--theme-color-border-highlight)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryDiffModal.module.scss"],"names":[],"mappings":"AAKA,6CACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,yBAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,aAAA,CACA,6DAAA,CAGF,2CACE,kCAAA,CACA,kDAAA,CACA,kBAAA,CACA,qCAAA,CACA,UAAA,CACA,gBAAA,CACA,eAAA,CACA,YAAA,CACA,qBAAA,CACA,8DAAA,CAGF,4CACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,iBAAA,CACA,yDAAA,CAGF,2CACE,QAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,iDACE,eAAA,CACA,WAAA,CACA,uCAAA,CACA,cAAA,CACA,aAAA,CACA,cAAA,CACA,SAAA,CACA,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,wBAAA,CAEA,uDACE,kCAAA,CACA,mCAAA,CAKJ,mDACE,YAAA,CACA,QAAA,CACA,YAAA,CACA,eAAA,CACA,MAAA,CACA,YAAA,CAGF,8CACE,MAAA,CACA,YAAA,CACA,qBAAA,CACA,WAAA,CACA,kCAAA,CACA,kDAAA,CACA,iBAAA,CACA,eAAA,CAGF,gDACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,iBAAA,CACA,kCAAA,CACA,yDAAA,CAGF,+CACE,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,8CACE,YAAA,CACA,OAAA,CACA,cAAA,CACA,eAAA,CAGF,+CACE,aAAA,CAGF,+CACE,aAAA,CAGF,mDACE,aAAA,CAGF,8CACE,MAAA,CACA,eAAA,CACA,2FAAA,CACA,cAAA,CACA,eAAA,CAGF,8CACE,YAAA,CACA,aAAA,CACA,eAAA,CACA,8BAAA,CAEA,oDACE,8BAAA,CAIJ,gDACE,aAAA,CACA,UAAA,CACA,cAAA,CACA,gBAAA,CACA,uCAAA,CACA,gBAAA,CACA,cAAA,CAGF,iDACE,MAAA,CACA,kBAAA,CACA,eAAA,CACA,eAAA,CACA,mCAAA,CAIF,mDACE,+BAAA,CAEA,mGACE,8BAAA,CACA,aAAA,CAGF,oGACE,aAAA,CAIJ,qDACE,gCAAA,CAEA,qGACE,+BAAA,CACA,aAAA,CAGF,sGACE,aAAA,CACA,4BAAA,CACA,UAAA,CAIJ,sDACE,+BAAA,CAEA,sGACE,8BAAA,CACA,aAAA,CAGF,uGACE,aAAA,CAIJ,mDACE,8BAAA,CACA,UAAA,CAEA,mGACE,SAAA,CAGF,oGACE,SAAA,CAKJ,mDACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,uCAAA,CACA,UAAA,CAIF,6CACE,iBAAA,CACA,sDAAA,CACA,yDAAA,CACA,kCAAA,CACA,YAAA,CACA,qBAAA,CACA,OAAA,CACA,cAAA,CACA,uCAAA,CAIF,4CACE,YAAA,CACA,kBAAA,CACA,wBAAA,CACA,QAAA,CACA,iBAAA,CAGF,kDACE,iBAAA,CACA,kCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,wBAAA,CAEA,wDACE,kCAAA,CACA,gDAAA,CAIJ,mDACE,iBAAA,CACA,qCAAA,CACA,2CAAA,CACA,iBAAA,CACA,UAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,wBAAA,CAEA,yDACE,+CAAA,CACA,iDAAA,CACA,0BAAA,CACA,yCAAA,CAGF,0DACE,uBAAA,CAKJ,sDACE,KACE,SAAA,CAEF,GACE,SAAA,CAAA,CAIJ,uDACE,KACE,SAAA,CACA,qBAAA,CAEF,GACE,SAAA,CACA,kBAAA,CAAA,CAKJ,iEACE,SAAA,CACA,UAAA,CAGF,uEACE,kCAAA,CAGF,uEACE,4CAAA,CACA,iBAAA,CAEA,6EACE,8CAAA","sourcesContent":["/**\n * CodeHistoryDiffModal Styles\n * The KILLER feature - beautiful side-by-side diff comparison\n */\n\n.Overlay {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background: rgba(0, 0, 0, 0.7);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 10000;\n  animation: fadeIn 0.2s ease;\n}\n\n.Modal {\n  background: var(--theme-color-bg-1);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 12px;\n  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.6);\n  width: 90vw;\n  max-width: 1200px;\n  max-height: 90vh;\n  display: flex;\n  flex-direction: column;\n  animation: scaleIn 0.2s ease;\n}\n\n.Header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 20px 24px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.Title {\n  margin: 0;\n  font-size: 17px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n}\n\n.CloseButton {\n  background: none;\n  border: none;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 28px;\n  line-height: 1;\n  cursor: pointer;\n  padding: 0;\n  width: 32px;\n  height: 32px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  border-radius: 6px;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background: var(--theme-color-bg-3);\n    color: var(--theme-color-fg-default);\n  }\n}\n\n/* Diff Container */\n.DiffContainer {\n  display: flex;\n  gap: 16px;\n  padding: 24px;\n  overflow: hidden;\n  flex: 1;\n  min-height: 0;\n}\n\n.DiffSide {\n  flex: 1;\n  display: flex;\n  flex-direction: column;\n  min-width: 0;\n  background: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 8px;\n  overflow: hidden;\n}\n\n.DiffHeader {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 12px 16px;\n  background: var(--theme-color-bg-3);\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.DiffLabel {\n  font-size: 13px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n}\n\n.DiffInfo {\n  display: flex;\n  gap: 8px;\n  font-size: 12px;\n  font-weight: 600;\n}\n\n.Additions {\n  color: #4ade80;\n}\n\n.Deletions {\n  color: #f87171;\n}\n\n.Modifications {\n  color: #fbbf24;\n}\n\n.DiffCode {\n  flex: 1;\n  overflow-y: auto;\n  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;\n  font-size: 13px;\n  line-height: 1.6;\n}\n\n.DiffLine {\n  display: flex;\n  padding: 2px 0;\n  min-height: 21px;\n  transition: background 0.1s ease;\n\n  &:hover {\n    background: rgba(255, 255, 255, 0.03);\n  }\n}\n\n.LineNumber {\n  flex-shrink: 0;\n  width: 50px;\n  padding: 0 12px;\n  text-align: right;\n  color: var(--theme-color-fg-default-shy);\n  user-select: none;\n  font-size: 12px;\n}\n\n.LineContent {\n  flex: 1;\n  padding-right: 12px;\n  white-space: pre;\n  overflow-x: auto;\n  color: var(--theme-color-fg-default);\n}\n\n/* Diff line states */\n.DiffLineAdded {\n  background: rgba(74, 222, 128, 0.15);\n\n  .LineNumber {\n    background: rgba(74, 222, 128, 0.2);\n    color: #4ade80;\n  }\n\n  .LineContent {\n    color: #d9f99d;\n  }\n}\n\n.DiffLineRemoved {\n  background: rgba(248, 113, 113, 0.15);\n\n  .LineNumber {\n    background: rgba(248, 113, 113, 0.2);\n    color: #f87171;\n  }\n\n  .LineContent {\n    color: #fecaca;\n    text-decoration: line-through;\n    opacity: 0.8;\n  }\n}\n\n.DiffLineModified {\n  background: rgba(251, 191, 36, 0.12);\n\n  .LineNumber {\n    background: rgba(251, 191, 36, 0.2);\n    color: #fbbf24;\n  }\n\n  .LineContent {\n    color: #fef3c7;\n  }\n}\n\n.DiffLineEmpty {\n  background: rgba(255, 255, 255, 0.02);\n  opacity: 0.3;\n\n  .LineNumber {\n    opacity: 0;\n  }\n\n  .LineContent {\n    opacity: 0;\n  }\n}\n\n/* Separator */\n.DiffSeparator {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  color: var(--theme-color-fg-default-shy);\n  opacity: 0.6;\n}\n\n/* Summary */\n.Summary {\n  padding: 16px 24px;\n  border-top: 1px solid var(--theme-color-border-default);\n  border-bottom: 1px solid var(--theme-color-border-default);\n  background: var(--theme-color-bg-2);\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n  font-size: 13px;\n  color: var(--theme-color-fg-default-shy);\n}\n\n/* Footer */\n.Footer {\n  display: flex;\n  align-items: center;\n  justify-content: flex-end;\n  gap: 12px;\n  padding: 20px 24px;\n}\n\n.CancelButton {\n  padding: 10px 20px;\n  background: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 6px;\n  color: var(--theme-color-fg-default);\n  font-size: 14px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background: var(--theme-color-bg-3);\n    border-color: var(--theme-color-border-highlight);\n  }\n}\n\n.RestoreButton {\n  padding: 10px 20px;\n  background: var(--theme-color-primary);\n  border: 1px solid var(--theme-color-primary);\n  border-radius: 6px;\n  color: white;\n  font-size: 14px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background: var(--theme-color-primary-highlight);\n    border-color: var(--theme-color-primary-highlight);\n    transform: translateY(-1px);\n    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);\n  }\n\n  &:active {\n    transform: translateY(0);\n  }\n}\n\n/* Animations */\n@keyframes fadeIn {\n  from {\n    opacity: 0;\n  }\n  to {\n    opacity: 1;\n  }\n}\n\n@keyframes scaleIn {\n  from {\n    opacity: 0;\n    transform: scale(0.95);\n  }\n  to {\n    opacity: 1;\n    transform: scale(1);\n  }\n}\n\n/* Scrollbar styling */\n.DiffCode::-webkit-scrollbar {\n  width: 8px;\n  height: 8px;\n}\n\n.DiffCode::-webkit-scrollbar-track {\n  background: var(--theme-color-bg-1);\n}\n\n.DiffCode::-webkit-scrollbar-thumb {\n  background: var(--theme-color-border-default);\n  border-radius: 4px;\n\n  &:hover {\n    background: var(--theme-color-border-highlight);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Overlay": `CodeHistoryDiffModal-module__Overlay--Rv0Nt`,
	"fadeIn": `CodeHistoryDiffModal-module__fadeIn--Od2TG`,
	"Modal": `CodeHistoryDiffModal-module__Modal--GsAQf`,
	"scaleIn": `CodeHistoryDiffModal-module__scaleIn--I0aNs`,
	"Header": `CodeHistoryDiffModal-module__Header--W7mf0`,
	"Title": `CodeHistoryDiffModal-module__Title--ZEIyS`,
	"CloseButton": `CodeHistoryDiffModal-module__CloseButton--lsbVn`,
	"DiffContainer": `CodeHistoryDiffModal-module__DiffContainer--Y7rlR`,
	"DiffSide": `CodeHistoryDiffModal-module__DiffSide--Q2HqX`,
	"DiffHeader": `CodeHistoryDiffModal-module__DiffHeader--b5aLE`,
	"DiffLabel": `CodeHistoryDiffModal-module__DiffLabel--oytna`,
	"DiffInfo": `CodeHistoryDiffModal-module__DiffInfo--jikz7`,
	"Additions": `CodeHistoryDiffModal-module__Additions--Mme84`,
	"Deletions": `CodeHistoryDiffModal-module__Deletions--e4tg0`,
	"Modifications": `CodeHistoryDiffModal-module__Modifications--fgfhv`,
	"DiffCode": `CodeHistoryDiffModal-module__DiffCode--eFR9W`,
	"DiffLine": `CodeHistoryDiffModal-module__DiffLine--DK8uo`,
	"LineNumber": `CodeHistoryDiffModal-module__LineNumber--YtK1F`,
	"LineContent": `CodeHistoryDiffModal-module__LineContent--kF7zL`,
	"DiffLineAdded": `CodeHistoryDiffModal-module__DiffLineAdded--KbrWV`,
	"DiffLineRemoved": `CodeHistoryDiffModal-module__DiffLineRemoved--DyDNY`,
	"DiffLineModified": `CodeHistoryDiffModal-module__DiffLineModified--WLXrn`,
	"DiffLineEmpty": `CodeHistoryDiffModal-module__DiffLineEmpty--UcRhR`,
	"DiffSeparator": `CodeHistoryDiffModal-module__DiffSeparator--lAlL0`,
	"Summary": `CodeHistoryDiffModal-module__Summary--uCdPO`,
	"Footer": `CodeHistoryDiffModal-module__Footer--H5X8F`,
	"CancelButton": `CodeHistoryDiffModal-module__CancelButton--TkZg3`,
	"RestoreButton": `CodeHistoryDiffModal-module__RestoreButton--Ytjsp`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 51917:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  Ai: () => (/* binding */ Ai)
});

;// ../../node_modules/@microsoft/fetch-event-source/lib/esm/parse.js
async function getBytes(stream, onChunk) {
    const reader = stream.getReader();
    let result;
    while (!(result = await reader.read()).done) {
        onChunk(result.value);
    }
}
function getLines(onLine) {
    let buffer;
    let position;
    let fieldLength;
    let discardTrailingNewline = false;
    return function onChunk(arr) {
        if (buffer === undefined) {
            buffer = arr;
            position = 0;
            fieldLength = -1;
        }
        else {
            buffer = concat(buffer, arr);
        }
        const bufLength = buffer.length;
        let lineStart = 0;
        while (position < bufLength) {
            if (discardTrailingNewline) {
                if (buffer[position] === 10) {
                    lineStart = ++position;
                }
                discardTrailingNewline = false;
            }
            let lineEnd = -1;
            for (; position < bufLength && lineEnd === -1; ++position) {
                switch (buffer[position]) {
                    case 58:
                        if (fieldLength === -1) {
                            fieldLength = position - lineStart;
                        }
                        break;
                    case 13:
                        discardTrailingNewline = true;
                    case 10:
                        lineEnd = position;
                        break;
                }
            }
            if (lineEnd === -1) {
                break;
            }
            onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
            lineStart = position;
            fieldLength = -1;
        }
        if (lineStart === bufLength) {
            buffer = undefined;
        }
        else if (lineStart !== 0) {
            buffer = buffer.subarray(lineStart);
            position -= lineStart;
        }
    };
}
function getMessages(onId, onRetry, onMessage) {
    let message = newMessage();
    const decoder = new TextDecoder();
    return function onLine(line, fieldLength) {
        if (line.length === 0) {
            onMessage === null || onMessage === void 0 ? void 0 : onMessage(message);
            message = newMessage();
        }
        else if (fieldLength > 0) {
            const field = decoder.decode(line.subarray(0, fieldLength));
            const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1);
            const value = decoder.decode(line.subarray(valueOffset));
            switch (field) {
                case 'data':
                    message.data = message.data
                        ? message.data + '\n' + value
                        : value;
                    break;
                case 'event':
                    message.event = value;
                    break;
                case 'id':
                    onId(message.id = value);
                    break;
                case 'retry':
                    const retry = parseInt(value, 10);
                    if (!isNaN(retry)) {
                        onRetry(message.retry = retry);
                    }
                    break;
            }
        }
    };
}
function concat(a, b) {
    const res = new Uint8Array(a.length + b.length);
    res.set(a);
    res.set(b, a.length);
    return res;
}
function newMessage() {
    return {
        data: '',
        event: '',
        id: '',
        retry: undefined,
    };
}
//# sourceMappingURL=parse.js.map
;// ../../node_modules/@microsoft/fetch-event-source/lib/esm/fetch.js
var __rest = (undefined && undefined.__rest) || function (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;
};

const EventStreamContentType = 'text/event-stream';
const DefaultRetryInterval = 1000;
const LastEventId = 'last-event-id';
function fetchEventSource(input, _a) {
    var { signal: inputSignal, headers: inputHeaders, onopen: inputOnOpen, onmessage, onclose, onerror, openWhenHidden, fetch: inputFetch } = _a, rest = __rest(_a, ["signal", "headers", "onopen", "onmessage", "onclose", "onerror", "openWhenHidden", "fetch"]);
    return new Promise((resolve, reject) => {
        const headers = Object.assign({}, inputHeaders);
        if (!headers.accept) {
            headers.accept = EventStreamContentType;
        }
        let curRequestController;
        function onVisibilityChange() {
            curRequestController.abort();
            if (!document.hidden) {
                create();
            }
        }
        if (!openWhenHidden) {
            document.addEventListener('visibilitychange', onVisibilityChange);
        }
        let retryInterval = DefaultRetryInterval;
        let retryTimer = 0;
        function dispose() {
            document.removeEventListener('visibilitychange', onVisibilityChange);
            window.clearTimeout(retryTimer);
            curRequestController.abort();
        }
        inputSignal === null || inputSignal === void 0 ? void 0 : inputSignal.addEventListener('abort', () => {
            dispose();
            resolve();
        });
        const fetch = inputFetch !== null && inputFetch !== void 0 ? inputFetch : window.fetch;
        const onopen = inputOnOpen !== null && inputOnOpen !== void 0 ? inputOnOpen : defaultOnOpen;
        async function create() {
            var _a;
            curRequestController = new AbortController();
            try {
                const response = await fetch(input, Object.assign(Object.assign({}, rest), { headers, signal: curRequestController.signal }));
                await onopen(response);
                await getBytes(response.body, getLines(getMessages(id => {
                    if (id) {
                        headers[LastEventId] = id;
                    }
                    else {
                        delete headers[LastEventId];
                    }
                }, retry => {
                    retryInterval = retry;
                }, onmessage)));
                onclose === null || onclose === void 0 ? void 0 : onclose();
                dispose();
                resolve();
            }
            catch (err) {
                if (!curRequestController.signal.aborted) {
                    try {
                        const interval = (_a = onerror === null || onerror === void 0 ? void 0 : onerror(err)) !== null && _a !== void 0 ? _a : retryInterval;
                        window.clearTimeout(retryTimer);
                        retryTimer = window.setTimeout(create, interval);
                    }
                    catch (innerErr) {
                        dispose();
                        reject(innerErr);
                    }
                }
            }
        }
        create();
    });
}
function defaultOnOpen(response) {
    const contentType = response.headers.get('content-type');
    if (!(contentType === null || contentType === void 0 ? void 0 : contentType.startsWith(EventStreamContentType))) {
        throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
    }
}
//# sourceMappingURL=fetch.js.map
// EXTERNAL MODULE: ./src/editor/src/store/AiAssistantStore.ts
var AiAssistantStore = __webpack_require__(61231);
;// ./src/editor/src/models/AiAssistant/context/ai-api.ts


function toChatProvider(provider) {
    return {
        model: (provider === null || provider === void 0 ? void 0 : provider.model) || 'gpt-3.5-turbo',
        temperature: provider === null || provider === void 0 ? void 0 : provider.temperature,
        max_tokens: provider === null || provider === void 0 ? void 0 : provider.max_tokens
    };
}
async function directChatOpenAi({ messages, provider, abortController, onEnd, onStream }) {
    const OPENAI_API_KEY = AiAssistantStore/* OpenAiStore */.q.getApiKey();
    const controller = abortController || new AbortController();
    let endpoint = `https://api.openai.com/v1/chat/completions`;
    if (AiAssistantStore/* OpenAiStore */.q.getVersion() === 'enterprise') {
        endpoint = AiAssistantStore/* OpenAiStore */.q.getEndpoint();
    }
    let fullText = '';
    let completionTokenCount = 0;
    let tries = 2;
    await fetchEventSource(endpoint, {
        method: 'POST',
        openWhenHidden: true,
        headers: {
            Authorization: 'Bearer ' + OPENAI_API_KEY,
            'Content-Type': 'application/json'
        },
        signal: controller.signal,
        body: JSON.stringify({
            ...toChatProvider(provider),
            messages,
            stream: true
        }),
        async onopen(response) {
            const contentType = response.headers.get('content-type') || '';
            if (response.ok && contentType.includes('text/event-stream')) {
                return; // everything's good
            }
            else {
                // If status is not OK or content type is unexpected, throw the response body
                const errorMessage = await response.text(); // Await the response body text
                const errorDetails = `HTTP ${response.status} - ${response.statusText}: ${errorMessage}`;
                throw errorDetails; // Throw the raw error string
            }
        },
        onmessage(ev) {
            if (ev.data === '[DONE]') {
                controller.abort();
                return;
            }
            try {
                const json = JSON.parse(ev.data);
                const delta = json.choices[0].delta.content;
                if (delta) {
                    completionTokenCount++;
                    fullText += delta;
                    console.debug('[stream]', fullText);
                    onStream && onStream(fullText, delta);
                }
            }
            catch (error) {
                console.error(error);
            }
        },
        onclose() {
            onEnd && onEnd();
        },
        onerror(err) {
            if (tries <= 0) {
                throw err; // Just rethrow the error directly
            }
            tries--;
        }
    });
    return {
        fullText,
        completionTokenCount
    };
}
var Ai;
(function (Ai) {
    async function chatStream(args) {
        let fullText = '';
        const version = AiAssistantStore/* OpenAiStore */.q.getVersion();
        if (['full-beta', 'enterprise'].includes(version)) {
            const result = await directChatOpenAi(args);
            fullText = result.fullText;
        }
        else {
            throw 'Invalid AI version.';
        }
        return fullText;
    }
    Ai.chatStream = chatStream;
})(Ai || (Ai = {}));


/***/ }),

/***/ 52034:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   KV: () => (/* binding */ createExpressionParameter),
/* harmony export */   UC: () => (/* binding */ isExpressionParameter)
/* harmony export */ });
/* unused harmony exports getParameterDisplayValue, getParameterActualValue, toParameter */
/**
 * Expression Parameter Types
 *
 * Defines types and helper functions for expression-based property values.
 * Allows properties to be set to JavaScript expressions that evaluate at runtime.
 *
 * @module ExpressionParameter
 * @since 1.1.0
 */
/**
 * Type guard to check if a parameter value is an expression
 *
 * @param value - The parameter value to check
 * @returns True if value is an ExpressionParameter
 *
 * @example
 * ```typescript
 * const param = node.getParameter('marginLeft');
 * if (isExpressionParameter(param)) {
 *   console.log('Expression:', param.expression);
 * } else {
 *   console.log('Fixed value:', param);
 * }
 * ```
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isExpressionParameter(value) {
    return (value !== null &&
        value !== undefined &&
        typeof value === 'object' &&
        value.mode === 'expression' &&
        typeof value.expression === 'string');
}
/**
 * Get the display value for a parameter (for UI rendering)
 *
 * - For expression parameters: returns the expression string
 * - For simple values: returns the value as-is
 *
 * @param value - The parameter value
 * @returns Display value (expression string or simple value)
 *
 * @example
 * ```typescript
 * const expr = { mode: 'expression', expression: 'Variables.x * 2', fallback: 0 };
 * getParameterDisplayValue(expr); // Returns: 'Variables.x * 2'
 * getParameterDisplayValue(42);    // Returns: 42
 * ```
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getParameterDisplayValue(value) {
    if (isExpressionParameter(value)) {
        return value.expression;
    }
    return value;
}
/**
 * Get the actual value for a parameter (unwraps expression fallback)
 *
 * - For expression parameters: returns the fallback value
 * - For simple values: returns the value as-is
 *
 * This is useful when you need a concrete value for initialization
 * before the expression can be evaluated.
 *
 * @param value - The parameter value
 * @returns Actual value (fallback or simple value)
 *
 * @example
 * ```typescript
 * const expr = { mode: 'expression', expression: 'Variables.x', fallback: 100 };
 * getParameterActualValue(expr); // Returns: 100
 * getParameterActualValue(42);    // Returns: 42
 * ```
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getParameterActualValue(value) {
    if (isExpressionParameter(value)) {
        return value.fallback;
    }
    return value;
}
/**
 * Create an expression parameter
 *
 * @param expression - The JavaScript expression string
 * @param fallback - Optional fallback value if expression fails
 * @param version - Expression system version (default: 1)
 * @returns A new ExpressionParameter object
 *
 * @example
 * ```typescript
 * // Simple expression with fallback
 * const param = createExpressionParameter('Variables.count', 0);
 *
 * // Complex expression
 * const param = createExpressionParameter(
 *   'Variables.isAdmin ? "Admin" : "User"',
 *   'User'
 * );
 * ```
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createExpressionParameter(expression, 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fallback, version = 1) {
    return {
        mode: 'expression',
        expression,
        fallback,
        version
    };
}
/**
 * Convert a value to a parameter (for consistency)
 *
 * - Expression parameters are returned as-is
 * - Simple values are returned as-is
 *
 * This is mainly for type safety and consistency in parameter handling.
 *
 * @param value - The value to convert
 * @returns The value as a ParameterValue
 *
 * @example
 * ```typescript
 * const expr = createExpressionParameter('Variables.x');
 * toParameter(expr); // Returns: expr (unchanged)
 * toParameter(42);    // Returns: 42 (unchanged)
 * ```
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function toParameter(value) {
    return value;
}


/***/ }),

/***/ 52285:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSearch = function SvgSearch(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.40987 10.0134C5.40987 7.07147 7.79479 4.68656 10.7367 4.68656C13.6787 4.68656 16.0636 7.07147 16.0636 10.0134C16.0636 12.9553 13.6787 15.3403 10.7367 15.3403C7.79479 15.3403 5.40987 12.9553 5.40987 10.0134ZM10.7367 2.9759C6.85002 2.9759 3.69922 6.1267 3.69922 10.0134C3.69922 13.9001 6.85002 17.0509 10.7367 17.0509C12.0693 17.0509 13.3153 16.6806 14.3775 16.0372L19.114 20.7737C19.448 21.1077 19.9896 21.1077 20.3236 20.7737C20.6577 20.4397 20.6577 19.8981 20.3236 19.5641L15.7311 14.9715C16.994 13.6994 17.7742 11.9475 17.7742 10.0134C17.7742 6.1267 14.6234 2.9759 10.7367 2.9759Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSearch);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "4508276caf93e8b05738389f263f5417.svg");

/***/ }),

/***/ 52391:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

module.exports = __webpack_require__(33757)


/***/ }),

/***/ 52398:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-tl-row {
	display: flex;
	height: 100%;
	align-items: center;
	position: relative;
}

.monaco-tl-indent {
	height: 100%;
	position: absolute;
	top: 0;
	left: 16px;
	pointer-events: none;
}

.hide-arrows .monaco-tl-indent {
	left: 12px;
}

.monaco-tl-indent > .indent-guide {
	display: inline-block;
	box-sizing: border-box;
	height: 100%;
	border-left: 1px solid transparent;
}

.monaco-tl-indent > .indent-guide {
	transition: border-color 0.1s linear;
}

.monaco-tl-twistie,
.monaco-tl-contents {
	height: 100%;
}

.monaco-tl-twistie {
	font-size: 10px;
	text-align: right;
	padding-right: 6px;
	flex-shrink: 0;
	width: 16px;
	display: flex !important;
	align-items: center;
	justify-content: center;
	transform: translateX(3px);
}

.monaco-tl-contents {
	flex: 1;
	overflow: hidden;
}

.monaco-tl-twistie::before {
	border-radius: 20px;
}

.monaco-tl-twistie.collapsed::before {
	transform: rotate(-90deg);
}

.monaco-tl-twistie.codicon-tree-item-loading::before {
	/* Use steps to throttle FPS to reduce CPU usage */
	animation: codicon-spin 1.25s steps(30) infinite;
}

.monaco-tree-type-filter {
	position: absolute;
	top: 0;
	display: flex;
	padding: 3px;
	transition: top 0.3s;
	max-width: 200px;
	z-index: 100;
	margin: 0 6px;
}

.monaco-tree-type-filter.disabled {
	top: -40px;
}

.monaco-tree-type-filter-grab {
	display: flex !important;
	align-items: center;
	justify-content: center;
	cursor: grab;
	margin-right: 2px;
}

.monaco-tree-type-filter-grab.grabbing {
	cursor: grabbing;
}

.monaco-tree-type-filter-input {
	flex: 1;
}

.monaco-tree-type-filter-input .monaco-inputbox {
	height: 23px;
}

.monaco-tree-type-filter-input .monaco-inputbox > .ibwrapper > .input,
.monaco-tree-type-filter-input .monaco-inputbox > .ibwrapper > .mirror {
	padding: 2px 4px;
}

.monaco-tree-type-filter-input .monaco-findInput > .controls {
	top: 2px;
}

.monaco-tree-type-filter-actionbar {
	margin-left: 4px;
}

.monaco-tree-type-filter-actionbar .monaco-action-bar .action-label {
	padding: 2px;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/tree/media/tree.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,aAAa;CACb,YAAY;CACZ,mBAAmB;CACnB,kBAAkB;AACnB;;AAEA;CACC,YAAY;CACZ,kBAAkB;CAClB,MAAM;CACN,UAAU;CACV,oBAAoB;AACrB;;AAEA;CACC,UAAU;AACX;;AAEA;CACC,qBAAqB;CACrB,sBAAsB;CACtB,YAAY;CACZ,kCAAkC;AACnC;;AAEA;CACC,oCAAoC;AACrC;;AAEA;;CAEC,YAAY;AACb;;AAEA;CACC,eAAe;CACf,iBAAiB;CACjB,kBAAkB;CAClB,cAAc;CACd,WAAW;CACX,wBAAwB;CACxB,mBAAmB;CACnB,uBAAuB;CACvB,0BAA0B;AAC3B;;AAEA;CACC,OAAO;CACP,gBAAgB;AACjB;;AAEA;CACC,mBAAmB;AACpB;;AAEA;CACC,yBAAyB;AAC1B;;AAEA;CACC,kDAAkD;CAClD,gDAAgD;AACjD;;AAEA;CACC,kBAAkB;CAClB,MAAM;CACN,aAAa;CACb,YAAY;CACZ,oBAAoB;CACpB,gBAAgB;CAChB,YAAY;CACZ,aAAa;AACd;;AAEA;CACC,UAAU;AACX;;AAEA;CACC,wBAAwB;CACxB,mBAAmB;CACnB,uBAAuB;CACvB,YAAY;CACZ,iBAAiB;AAClB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,OAAO;AACR;;AAEA;CACC,YAAY;AACb;;AAEA;;CAEC,gBAAgB;AACjB;;AAEA;CACC,QAAQ;AACT;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,YAAY;AACb","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-tl-row {\n\tdisplay: flex;\n\theight: 100%;\n\talign-items: center;\n\tposition: relative;\n}\n\n.monaco-tl-indent {\n\theight: 100%;\n\tposition: absolute;\n\ttop: 0;\n\tleft: 16px;\n\tpointer-events: none;\n}\n\n.hide-arrows .monaco-tl-indent {\n\tleft: 12px;\n}\n\n.monaco-tl-indent > .indent-guide {\n\tdisplay: inline-block;\n\tbox-sizing: border-box;\n\theight: 100%;\n\tborder-left: 1px solid transparent;\n}\n\n.monaco-tl-indent > .indent-guide {\n\ttransition: border-color 0.1s linear;\n}\n\n.monaco-tl-twistie,\n.monaco-tl-contents {\n\theight: 100%;\n}\n\n.monaco-tl-twistie {\n\tfont-size: 10px;\n\ttext-align: right;\n\tpadding-right: 6px;\n\tflex-shrink: 0;\n\twidth: 16px;\n\tdisplay: flex !important;\n\talign-items: center;\n\tjustify-content: center;\n\ttransform: translateX(3px);\n}\n\n.monaco-tl-contents {\n\tflex: 1;\n\toverflow: hidden;\n}\n\n.monaco-tl-twistie::before {\n\tborder-radius: 20px;\n}\n\n.monaco-tl-twistie.collapsed::before {\n\ttransform: rotate(-90deg);\n}\n\n.monaco-tl-twistie.codicon-tree-item-loading::before {\n\t/* Use steps to throttle FPS to reduce CPU usage */\n\tanimation: codicon-spin 1.25s steps(30) infinite;\n}\n\n.monaco-tree-type-filter {\n\tposition: absolute;\n\ttop: 0;\n\tdisplay: flex;\n\tpadding: 3px;\n\ttransition: top 0.3s;\n\tmax-width: 200px;\n\tz-index: 100;\n\tmargin: 0 6px;\n}\n\n.monaco-tree-type-filter.disabled {\n\ttop: -40px;\n}\n\n.monaco-tree-type-filter-grab {\n\tdisplay: flex !important;\n\talign-items: center;\n\tjustify-content: center;\n\tcursor: grab;\n\tmargin-right: 2px;\n}\n\n.monaco-tree-type-filter-grab.grabbing {\n\tcursor: grabbing;\n}\n\n.monaco-tree-type-filter-input {\n\tflex: 1;\n}\n\n.monaco-tree-type-filter-input .monaco-inputbox {\n\theight: 23px;\n}\n\n.monaco-tree-type-filter-input .monaco-inputbox > .ibwrapper > .input,\n.monaco-tree-type-filter-input .monaco-inputbox > .ibwrapper > .mirror {\n\tpadding: 2px 4px;\n}\n\n.monaco-tree-type-filter-input .monaco-findInput > .controls {\n\ttop: 2px;\n}\n\n.monaco-tree-type-filter-actionbar {\n\tmargin-left: 4px;\n}\n\n.monaco-tree-type-filter-actionbar .monaco-action-bar .action-label {\n\tpadding: 2px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 52494:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
.monaco-editor .detected-link,
.monaco-editor .detected-link-active {
	text-decoration: underline;
	text-underline-position: under;
}

.monaco-editor .detected-link-active {
	cursor: pointer;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/links/browser/links.css"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;CAEC,0BAA0B;CAC1B,8BAA8B;AAC/B;;AAEA;CACC,eAAe;AAChB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n.monaco-editor .detected-link,\n.monaco-editor .detected-link-active {\n\ttext-decoration: underline;\n\ttext-underline-position: under;\n}\n\n.monaco-editor .detected-link-active {\n\tcursor: pointer;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 52501:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(80002),
  View = __webpack_require__(92207),
  ImportPopupTemplate = __webpack_require__(72498);

// --------------------------------------------------------------
// ComponentsPanel.Folder
// --------------------------------------------------------------
var ImportPopup = function (args) {
  View.call(this);

  this.template = ImportPopupTemplate;
  for (var i in args) this[i] = args[i];

  this.hasComponents = this.imports.components !== undefined && this.imports.components.length > 0;
  this.hasResources = this.imports.resources !== undefined && this.imports.resources.length > 0;
  this.hasModules = this.imports.modules !== undefined && this.imports.modules.length > 0;
  this.hasVariants = this.imports.variants !== undefined && this.imports.variants.length > 0;
  this.hasColorStyles = this.imports.styles.colors !== undefined && this.imports.styles.colors.length > 0;
  this.hasTextStyles = this.imports.styles.text !== undefined && this.imports.styles.text.length > 0;

  if (this.initAllAsImport === true) {
    this.imports.components.forEach((c) => (c.import = true));
    this.imports.resources.forEach((c) => (c.import = true));
    this.imports.modules.forEach((c) => (c.import = true));
    this.imports.variants.forEach((c) => (c.import = true));
    this.imports.styles.colors.forEach((c) => (c.import = true));
    this.imports.styles.text.forEach((c) => (c.import = true));
  }
  this.updateDependencies();
};
ImportPopup.prototype = Object.create(View.prototype);

ImportPopup.prototype.renderItems = function (items, appendTo) {
  if (!items) return;

  var folderCache = {};
  var _this = this;
  var indent = 12,
    offset = parseInt(this.el.attr('data-indent-offset'));

  function getFolderFromCache(path) {
    if (path === '') return { el: appendTo, appendTo: appendTo };

    var f = folderCache[path];
    if (!f) {
      var comps = path.split('/');
      var f = (folderCache[path] = {
        path: path,
        items: items,
        cache: folderCache,
        localName: comps[comps.length - 1],
        open: true
      });
      f.el = _this.bindView(_this.cloneTemplate('folder'), f);
      View.$(f.el, '.indent-me').css({ left: (comps.length - 1) * indent + offset + 'px' });

      f.appendTo = f.el.find('.content');

      var parent = getFolderFromCache(comps.slice(0, comps.length - 1).join('/'));
      parent.appendTo.append(f.el);
    }
    return f;
  }

  items.sort(function (a, b) {
    return a.name > b.name ? 1 : -1;
  });

  for (var i in items) {
    var item = items[i];
    var path = item.name[0] !== '/' ? '/' + item.name : item.name; // Prepend / if missing
    var comps = path.split('/');
    item.localName = comps[comps.length - 1];
    item.folder = comps.slice(0, comps.length - 1).join('/');
    var el = this.bindView(this.cloneTemplate('item'), item);

    var f = getFolderFromCache(item.folder);
    View.$(el, '.indent-me').css({ left: (comps.length - 1) * indent + offset + 'px' });
    f.appendTo.append(el);
  }
};

ImportPopup.prototype.render = function () {
  this.el = this.bindView($(this.template), this);

  this.renderItems(this.imports.components, this.$('.components'));

  this.renderItems(this.imports.resources, this.$('.resources'));

  this.renderItems(this.imports.modules, this.$('.modules'));

  this.renderItems(this.imports.variants, this.$('.variants'));

  this.renderItems(this.imports.styles.colors, this.$('.color-styles'));

  this.renderItems(this.imports.styles.text, this.$('.text-styles'));

  return this.el;
};

ImportPopup.prototype.updateDependencies = function () {
  // Update implicit import status for components
  const components = this.imports.components;
  const resources = this.imports.resources;
  const modules = this.imports.modules;
  const variants = this.imports.variants;
  const styles = this.imports.styles;

  // First unmark all
  components.forEach((c) => (c.implicit = false));
  resources.forEach((r) => (r.implicit = false));
  modules.forEach((m) => (m.implicit = false));
  variants.forEach((v) => (v.implicit = false));
  styles.colors.forEach((c) => (c.implicit = false));
  styles.text.forEach((t) => (t.implicit = false));

  if (this.ignoreDependencies !== true) {
    function _markComponent(name) {
      components.forEach((c) => {
        if (c.name === name) {
          c.implicit = true;
          c.fileDependencies.forEach((d) => _markResource(d));
          c.dependencies.forEach((d) => _markComponent(d));
          c.styleDependencies.colors.forEach((d) => _markColorStyle(d));
          c.styleDependencies.text.forEach((d) => _markTextStyle(d));
          c.variantDependencies.forEach((d) => _markVariant(d));
        }
      });
    }

    function _markResource(name) {
      resources.forEach((r) => {
        if (r.name === name) r.implicit = true;
      });
    }

    function _markColorStyle(name) {
      styles.colors.forEach((c) => {
        if (c.name === name) c.implicit = true;
      });
    }

    function _markTextStyle(name) {
      styles.text.forEach((t) => {
        if (t.name === name) {
          t.implicit = true;
          t.fileDependencies.forEach((d) => _markResource(d));
        }
      });
    }

    function _markVariant(_v) {
      variants.forEach((v) => {
        if (v.name === _v.name && v.typename === _v.typename) {
          v.implicit = true;
          v.fileDependencies.forEach((d) => _markResource(d));
          v.styleDependencies.colors.forEach((d) => _markColorStyle(d));
          v.styleDependencies.text.forEach((d) => _markTextStyle(d));
        }
      });
    }

    components.forEach((c) => {
      c.import && _markComponent(c.name);
    });
    variants.forEach((v) => {
      v.import && _markVariant(v);
    });
    styles.text.forEach((t) => {
      t.import && _markTextStyle(t.name);
    });
  }

  function _isChecked(c) {
    return c.implicit || c.import;
  }
  components.forEach((c) => (c.check = _isChecked(c)));
  resources.forEach((c) => (c.check = _isChecked(c)));
  variants.forEach((c) => (c.check = _isChecked(c)));
  modules.forEach((c) => (c.check = _isChecked(c)));
  styles.text.forEach((c) => (c.check = _isChecked(c)));
  styles.colors.forEach((c) => (c.check = _isChecked(c)));
};

ImportPopup.prototype.onFolderClicked = function (scope) {
  scope.open = !scope.open;
  scope.appendTo.css({ display: scope.open ? 'block' : 'none' });
};

ImportPopup.prototype.onFolderBoxClicked = function (scope) {
  scope.import = !scope.import;

  // Set all items (resouces or components) in this folder to the
  // folder import status
  for (var i in scope.items) {
    var item = scope.items[i];
    var path = item.name[0] !== '/' ? '/' + item.name : item.name;
    if (path.indexOf(scope.path) === 0) item.import = scope.import;
  }

  // Same for sub folders
  for (var i in scope.cache) {
    var f = scope.cache[i];
    var path = f.path[0] !== '/' ? '/' + f.path : f.path;
    if (path.indexOf(scope.path) === 0) f.import = scope.import;
  }

  this.updateDependencies();
};

ImportPopup.prototype.onBoxClicked = function (scope) {
  scope.import = !scope.import;

  this.updateDependencies();
};

ImportPopup.prototype.onOkClicked = function () {
  this.onOk && this.onOk();
};

ImportPopup.prototype.onCancelClicked = function () {
  // Timeout for tick reasons
  setTimeout(() => {
    this.onCancel && this.onCancel();
  }, 10);
};

ImportPopup.prototype.getSelectedImports = function () {
  const components = this.imports.components;
  const resources = this.imports.resources;
  const modules = this.imports.modules;
  const variants = this.imports.variants;
  const styles = this.imports.styles;

  const imports = {
    components: components.filter((c) => c.import || c.implicit),
    resources: resources.filter((c) => c.import || c.implicit),
    modules: modules.filter((c) => c.import || c.implicit),
    variants: variants.filter((c) => c.import || c.implicit),
    styles: {
      colors: styles.colors.filter((c) => c.import || c.implicit),
      text: styles.text.filter((c) => c.import || c.implicit)
    }
  };

  return imports;
};

ImportPopup.prototype.getUnselectedImports = function (imports) {
  const components = this.imports.components;
  const resources = this.imports.resources;
  const modules = this.imports.modules;
  const variants = this.imports.variants;
  const styles = this.imports.styles;

  const unselected = {
    components: components.filter((c) => c.import === false),
    resources: resources.filter((c) => c.import === false),
    modules: modules.filter((c) => c.import === false),
    variants: variants.filter((c) => c.import === false),
    styles: {
      colors: styles.colors.filter((c) => c.import === false),
      text: styles.text.filter((c) => c.import === false)
    }
  };

  return unselected;
};

module.exports = ImportPopup;


/***/ }),

/***/ 52767:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-aria-container {
	position: absolute; /* try to hide from window but not from screen readers */
	left:-999em;
}`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/aria/aria.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kBAAkB,EAAE,wDAAwD;CAC5E,WAAW;AACZ","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-aria-container {\n\tposition: absolute; /* try to hide from window but not from screen readers */\n\tleft:-999em;\n}"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 52838:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const {
  ipcRenderer
} = __webpack_require__(91288);
const {
  useEffect,
  useRef,
  useState
} = __webpack_require__(54953);
const React = __webpack_require__(54953);
const {
  default: useOnUnmount
} = __webpack_require__(46901);
const PopupLayer = __webpack_require__(45653);
function LessonItem({
  itemContent,
  popupContent,
  hasNextButton,
  isComplete,
  isSelected,
  showPopupWhenSelected,
  stepWidth,
  performActions
}) {
  const ref = useRef();
  const popoutRef = useRef();
  const [showPopup, setShowPopup] = useState(false);
  useEffect(() => {
    //scroll into view when selected, and check if popup should be shown
    const scrollIntoView = async () => {
      await scrollToElement(ref.current);
      showPopupWhenSelected && setShowPopup(true);
    };
    if (isSelected) {
      scrollIntoView();
      performActions();
    }
  }, [isSelected, popupContent]);

  //check if popup should be shown
  useEffect(() => {
    if (!showPopup || !popupContent) {
      return;
    }
    const container = document.createElement('div');
    container.className = 'lesson-item-popup';
    container.appendChild(popupContent);
    PopupLayer.instance.hidePopouts(); //hide all other popouts that might be showing

    popoutRef.current = PopupLayer.instance.showPopout({
      content: {
        el: $(container)
      },
      attachTo: $(ref.current),
      position: 'top',
      arrowColor: 'var(--theme-color-secondary)',
      animate: true,
      offsetY: -8,
      manualClose: hasNextButton,
      onClose: () => {
        setShowPopup(false);
        ipcRenderer.send('viewer-show');
      }
    });
    ipcRenderer.send('viewer-hide');

    //make sure any videos start playing
    const videos = container.querySelectorAll('video');
    videos.forEach(video => {
      video.play();
    });
    return () => {
      //pause videos, otherwise they run in the background and consume resources
      videos.forEach(video => {
        video.pause();
      });
      PopupLayer.instance.hidePopout(popoutRef.current);
    };
  }, [showPopup, popupContent]);

  //This solves an issue where popups aren't closed when using the debug keyboard shortcut to skip steps
  useEffect(() => {
    if (showPopup && popoutRef.current.manualClose && hasNextButton === false) {
      setShowPopup(false);
    }
  }, [showPopup, hasNextButton]);
  useOnUnmount(() => {
    /**
     * an ugly fix for an ugly edge case
     * where the popuplayer renders a step
     * with a "next" button on the projectspage
     * if you close the popout and exit the project
     *
     * right now it will show for a split second, and then
     * it will be removed. not the cleanest solution, but this
     * will probably happen pretty rarely, and the popuplayer
     * is scheduled to be replaced by the react dialoglayer
     * sometime in the near future anyways
     */
    setTimeout(() => {
      PopupLayer.instance.hidePopouts();
    }, 10);
  });
  const style = {};
  if (stepWidth) {
    style.width = stepWidth;
  }
  return /*#__PURE__*/React.createElement("div", {
    ref: ref,
    style: style,
    className: `lesson-item ${isSelected ? 'selected' : ''} ${isComplete ? 'completed' : ''}`,
    onClick: e => {
      e.stopPropagation();
      setShowPopup(true);
    },
    dangerouslySetInnerHTML: {
      __html: itemContent.innerHTML
    }
  });
}

//Scroll to this element
// - assumes the parent is the scroll container
// - leaves a margin of one item (left sibling)
// Returns a promise that resolves once the scrolling animation is done
async function scrollToElement(element) {
  const parent = element.parentElement;
  const parentPos = parent.getBoundingClientRect();
  const itemPosition = element.getBoundingClientRect();
  const scrollPos = itemPosition.left - parentPos.left + parent.scrollLeft;
  let scrollMargin = 0;
  if (element.previousElementSibling) {
    const siblingSize = element.previousElementSibling.getBoundingClientRect();
    scrollMargin = siblingSize.width;
  }
  const newScrollPos = scrollPos - scrollMargin;
  if (element.parentElement.scrollLeft !== newScrollPos) {
    element.parentElement.scrollTo({
      left: newScrollPos,
      behavior: 'smooth'
    });
    await asyncTimeout(500);
  }
}
function asyncTimeout(dur) {
  return new Promise(resolve => {
    setTimeout(resolve, dur);
  });
}
module.exports = LessonItem;

/***/ }),

/***/ 52877:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   $j: () => (/* binding */ getComponentModelRuntimeType),
/* harmony export */   dk: () => (/* binding */ isComponentModel_CloudRuntime),
/* harmony export */   lb: () => (/* binding */ getNodeGraphNodeRuntimeType),
/* harmony export */   qb: () => (/* binding */ isComponentModel_BrowserRuntime)
/* harmony export */ });
/* harmony import */ var _noodl_models_nodelibrary_NodeLibraryData__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(68228);

function getComponentModelRuntimeType(node) {
    const name = node.name;
    if (name.startsWith('/#__cloud__/')) {
        return _noodl_models_nodelibrary_NodeLibraryData__WEBPACK_IMPORTED_MODULE_0__/* .RuntimeType */ .r.Cloud;
    }
    return _noodl_models_nodelibrary_NodeLibraryData__WEBPACK_IMPORTED_MODULE_0__/* .RuntimeType */ .r.Browser;
}
const isComponentModel_BrowserRuntime = (node) => getComponentModelRuntimeType(node) === _noodl_models_nodelibrary_NodeLibraryData__WEBPACK_IMPORTED_MODULE_0__/* .RuntimeType */ .r.Browser;
const isComponentModel_CloudRuntime = (node) => getComponentModelRuntimeType(node) === _noodl_models_nodelibrary_NodeLibraryData__WEBPACK_IMPORTED_MODULE_0__/* .RuntimeType */ .r.Cloud;
function getNodeGraphNodeRuntimeType(node) {
    var _a, _b, _c;
    return ((_c = (_b = (_a = node === null || node === void 0 ? void 0 : node.owner) === null || _a === void 0 ? void 0 : _a.owner) === null || _b === void 0 ? void 0 : _b.name) === null || _c === void 0 ? void 0 : _c.startsWith('/#__cloud__')) ? _noodl_models_nodelibrary_NodeLibraryData__WEBPACK_IMPORTED_MODULE_0__/* .RuntimeType */ .r.Cloud : _noodl_models_nodelibrary_NodeLibraryData__WEBPACK_IMPORTED_MODULE_0__/* .RuntimeType */ .r.Browser;
}


/***/ }),

/***/ 53029:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ComponentsPanel-module__ComponentsPanel--LSnyD{display:flex;flex-direction:column;height:100%;overflow:visible}.ComponentsPanel-module__Header--TiriJ{display:flex;align-items:center;justify-content:space-between;height:36px;padding:0 10px;background-color:var(--theme-color-bg-3);border-bottom:1px solid var(--theme-color-bg-2);color:var(--theme-color-fg-highlight);font:12px var(--font-family-regular)}.ComponentsPanel-module__Title--iNlyg{font:12px var(--font-family-regular);color:var(--theme-color-fg-highlight)}.ComponentsPanel-module__AddButton--ADX7m{width:24px;height:24px;background-color:rgba(0,0,0,0);color:var(--theme-color-fg-default);border:none;border-radius:2px;cursor:pointer;font-size:18px;display:flex;align-items:center;justify-content:center;opacity:.6;transition:opacity var(--speed-turbo),background-color var(--speed-turbo)}.ComponentsPanel-module__AddButton--ADX7m:hover{background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-highlight);opacity:1}.ComponentsPanel-module__Tree--qYffO{flex:1;overflow:hidden overlay;display:flex;flex-direction:column}.ComponentsPanel-module__PlaceholderMessage--DwyVK{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:32px 16px;color:var(--theme-color-fg-default-shy);text-align:center;font:12px var(--font-family-regular)}.ComponentsPanel-module__PlaceholderMessage--DwyVK span{display:block}.ComponentsPanel-module__TreeItem--b5ygU{display:flex;align-items:center;padding:6px 10px;cursor:pointer;font:11px var(--font-family-regular);color:var(--theme-color-fg-default);user-select:none;transition:background-color .15s ease}.ComponentsPanel-module__TreeItem--b5ygU:hover{background-color:var(--theme-color-bg-3)}.ComponentsPanel-module__TreeItem--b5ygU.ComponentsPanel-module__Selected--nWwjN{background-color:var(--theme-color-primary-transparent);color:var(--theme-color-primary)}.ComponentsPanel-module__TreeItem--b5ygU.ComponentsPanel-module__DropTarget--X4xIa{background-color:var(--theme-color-primary-transparent);border:2px dashed var(--theme-color-primary);border-radius:4px;transition:all .15s ease}.ComponentsPanel-module__Caret--hBpcw{width:12px;height:12px;margin-right:4px;display:flex;align-items:center;justify-content:center;font-size:8px;color:var(--theme-color-fg-muted);transition:transform .15s ease}.ComponentsPanel-module__Caret--hBpcw.ComponentsPanel-module__Expanded--CIkmm{transform:rotate(90deg)}.ComponentsPanel-module__ItemContent--fvRBu{display:flex;align-items:center;flex:1;gap:6px}.ComponentsPanel-module__Icon--PRPQi{width:16px;height:16px;display:flex;align-items:center;justify-content:center;color:var(--theme-color-fg-default)}.ComponentsPanel-module__Label--N2ry2{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ComponentsPanel-module__Warning--bJv0X{width:16px;height:16px;display:flex;align-items:center;justify-content:center;background-color:var(--theme-color-warning);color:var(--theme-color-bg-1);border-radius:50%;font-size:10px;font-weight:bold}.ComponentsPanel-module__RenameContainer--asb_D{display:flex;align-items:center;padding:6px 10px;background-color:var(--theme-color-bg-3)}.ComponentsPanel-module__RenameInput--yHP19{flex:1;padding:4px 8px;font:11px var(--font-family-regular);color:var(--theme-color-fg-default);background-color:var(--theme-color-bg-1);border:1px solid var(--theme-color-primary);border-radius:4px;outline:none;transition:border-color var(--speed-turbo),box-shadow var(--speed-turbo)}.ComponentsPanel-module__RenameInput--yHP19:focus{border-color:var(--theme-color-primary);box-shadow:0 0 0 2px var(--theme-color-primary-transparent);background-color:var(--theme-color-bg-1)}.ComponentsPanel-module__RenameInput--yHP19::selection{background-color:var(--theme-color-primary);color:var(--theme-color-bg-1)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/ComponentsPanelNew/ComponentsPanel.module.scss"],"names":[],"mappings":"AAOA,gDACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,gBAAA,CAGF,uCACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,WAAA,CACA,cAAA,CACA,wCAAA,CACA,+CAAA,CACA,qCAAA,CACA,oCAAA,CAGF,sCACE,oCAAA,CACA,qCAAA,CAGF,0CACE,UAAA,CACA,WAAA,CACA,8BAAA,CACA,mCAAA,CACA,WAAA,CACA,iBAAA,CACA,cAAA,CACA,cAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CACA,yEAAA,CAEA,gDACE,wCAAA,CACA,qCAAA,CACA,SAAA,CAIJ,qCACE,MAAA,CACA,uBAAA,CACA,YAAA,CACA,qBAAA,CAGF,mDACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,uCAAA,CACA,iBAAA,CACA,oCAAA,CAEA,wDACE,aAAA,CAKJ,yCACE,YAAA,CACA,kBAAA,CACA,gBAAA,CACA,cAAA,CACA,oCAAA,CACA,mCAAA,CACA,gBAAA,CACA,qCAAA,CAEA,+CACE,wCAAA,CAGF,iFACE,uDAAA,CACA,gCAAA,CAGF,mFACE,uDAAA,CACA,4CAAA,CACA,iBAAA,CACA,wBAAA,CAIJ,sCACE,UAAA,CACA,WAAA,CACA,gBAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,aAAA,CACA,iCAAA,CACA,8BAAA,CAEA,8EACE,uBAAA,CAIJ,4CACE,YAAA,CACA,kBAAA,CACA,MAAA,CACA,OAAA,CAGF,qCACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,mCAAA,CAGF,sCACE,MAAA,CACA,eAAA,CACA,sBAAA,CACA,kBAAA,CAGF,wCACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,2CAAA,CACA,6BAAA,CACA,iBAAA,CACA,cAAA,CACA,gBAAA,CAIF,gDACE,YAAA,CACA,kBAAA,CACA,gBAAA,CACA,wCAAA,CAGF,4CACE,MAAA,CACA,eAAA,CACA,oCAAA,CACA,mCAAA,CACA,wCAAA,CACA,2CAAA,CACA,iBAAA,CACA,YAAA,CACA,wEAAA,CAEA,kDACE,uCAAA,CACA,2DAAA,CACA,wCAAA,CAGF,uDACE,2CAAA,CACA,6BAAA","sourcesContent":["/**\n * ComponentsPanel Styles\n * \n * Migrated from legacy componentspanel.css to CSS modules\n * Using design tokens for proper theming support\n */\n\n.ComponentsPanel {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  overflow: visible; /* Allow popups to extend outside panel */\n}\n\n.Header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  height: 36px;\n  padding: 0 10px;\n  background-color: var(--theme-color-bg-3);\n  border-bottom: 1px solid var(--theme-color-bg-2);\n  color: var(--theme-color-fg-highlight);\n  font: 12px var(--font-family-regular);\n}\n\n.Title {\n  font: 12px var(--font-family-regular);\n  color: var(--theme-color-fg-highlight);\n}\n\n.AddButton {\n  width: 24px;\n  height: 24px;\n  background-color: transparent;\n  color: var(--theme-color-fg-default);\n  border: none;\n  border-radius: 2px;\n  cursor: pointer;\n  font-size: 18px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  opacity: 0.6;\n  transition: opacity var(--speed-turbo), background-color var(--speed-turbo);\n\n  &:hover {\n    background-color: var(--theme-color-bg-1);\n    color: var(--theme-color-fg-highlight);\n    opacity: 1;\n  }\n}\n\n.Tree {\n  flex: 1;\n  overflow: hidden overlay;\n  display: flex;\n  flex-direction: column;\n}\n\n.PlaceholderMessage {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  padding: 32px 16px;\n  color: var(--theme-color-fg-default-shy);\n  text-align: center;\n  font: 12px var(--font-family-regular);\n\n  span {\n    display: block;\n  }\n}\n\n/* Tree items */\n.TreeItem {\n  display: flex;\n  align-items: center;\n  padding: 6px 10px;\n  cursor: pointer;\n  font: 11px var(--font-family-regular);\n  color: var(--theme-color-fg-default);\n  user-select: none;\n  transition: background-color 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.Selected {\n    background-color: var(--theme-color-primary-transparent);\n    color: var(--theme-color-primary);\n  }\n\n  &.DropTarget {\n    background-color: var(--theme-color-primary-transparent);\n    border: 2px dashed var(--theme-color-primary);\n    border-radius: 4px;\n    transition: all 0.15s ease;\n  }\n}\n\n.Caret {\n  width: 12px;\n  height: 12px;\n  margin-right: 4px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  font-size: 8px;\n  color: var(--theme-color-fg-muted);\n  transition: transform 0.15s ease;\n\n  &.Expanded {\n    transform: rotate(90deg);\n  }\n}\n\n.ItemContent {\n  display: flex;\n  align-items: center;\n  flex: 1;\n  gap: 6px;\n}\n\n.Icon {\n  width: 16px;\n  height: 16px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  color: var(--theme-color-fg-default);\n}\n\n.Label {\n  flex: 1;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n.Warning {\n  width: 16px;\n  height: 16px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  background-color: var(--theme-color-warning);\n  color: var(--theme-color-bg-1);\n  border-radius: 50%;\n  font-size: 10px;\n  font-weight: bold;\n}\n\n/* Rename Input */\n.RenameContainer {\n  display: flex;\n  align-items: center;\n  padding: 6px 10px;\n  background-color: var(--theme-color-bg-3);\n}\n\n.RenameInput {\n  flex: 1;\n  padding: 4px 8px;\n  font: 11px var(--font-family-regular);\n  color: var(--theme-color-fg-default);\n  background-color: var(--theme-color-bg-1);\n  border: 1px solid var(--theme-color-primary);\n  border-radius: 4px;\n  outline: none;\n  transition: border-color var(--speed-turbo), box-shadow var(--speed-turbo);\n\n  &:focus {\n    border-color: var(--theme-color-primary);\n    box-shadow: 0 0 0 2px var(--theme-color-primary-transparent);\n    background-color: var(--theme-color-bg-1);\n  }\n\n  &::selection {\n    background-color: var(--theme-color-primary);\n    color: var(--theme-color-bg-1);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"ComponentsPanel": `ComponentsPanel-module__ComponentsPanel--LSnyD`,
	"Header": `ComponentsPanel-module__Header--TiriJ`,
	"Title": `ComponentsPanel-module__Title--iNlyg`,
	"AddButton": `ComponentsPanel-module__AddButton--ADX7m`,
	"Tree": `ComponentsPanel-module__Tree--qYffO`,
	"PlaceholderMessage": `ComponentsPanel-module__PlaceholderMessage--DwyVK`,
	"TreeItem": `ComponentsPanel-module__TreeItem--b5ygU`,
	"Selected": `ComponentsPanel-module__Selected--nWwjN`,
	"DropTarget": `ComponentsPanel-module__DropTarget--X4xIa`,
	"Caret": `ComponentsPanel-module__Caret--hBpcw`,
	"Expanded": `ComponentsPanel-module__Expanded--CIkmm`,
	"ItemContent": `ComponentsPanel-module__ItemContent--fvRBu`,
	"Icon": `ComponentsPanel-module__Icon--PRPQi`,
	"Label": `ComponentsPanel-module__Label--N2ry2`,
	"Warning": `ComponentsPanel-module__Warning--bJv0X`,
	"RenameContainer": `ComponentsPanel-module__RenameContainer--asb_D`,
	"RenameInput": `ComponentsPanel-module__RenameInput--yHP19`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 53106:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   I: () => (/* binding */ stripCssUnit)
/* harmony export */ });
function stripCssUnit(string) {
    const cssUnitRegex = /^-?\d*\.?\d+(px|em|rem|vh|vw|%|ex|ch|cm|mm|in|pt|pc)$/i;
    if (cssUnitRegex.test(string)) {
        return string.slice(0, string.match(cssUnitRegex)[1].length * -1); // Remove the last characters representing the CSS unit
    }
    return string;
}


/***/ }),

/***/ 53353:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
const tslib_1 = __webpack_require__(84499);
/** @deprecated Import from ./core/streaming instead */
tslib_1.__exportStar(__webpack_require__(70973), exports);
//# sourceMappingURL=streaming.js.map

/***/ }),

/***/ 53482:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.EventStep-module__EventStep--XXGFo{display:flex;gap:12px;position:relative;padding-bottom:16px}.EventStep-module__EventStep--XXGFo:last-child .EventStep-module__TimelineLine--LACR2{display:none}.EventStep-module__TimelineConnector--KD6AD{display:flex;flex-direction:column;align-items:center;flex-shrink:0;padding-top:4px}.EventStep-module__TimelineDot--Eh4nQ{width:12px;height:12px;border-radius:50%;background-color:var(--theme-color-primary);border:2px solid var(--theme-color-bg-1);flex-shrink:0;z-index:1}.EventStep-module__TimelineLine--LACR2{width:2px;flex:1;background-color:var(--theme-color-border-default);margin-top:4px}.EventStep-module__EventCard--OXwOE{flex:1;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:4px;padding:12px;transition:all .15s ease}.EventStep-module__EventCard--OXwOE:hover{background-color:var(--theme-color-bg-3);border-color:var(--theme-color-primary)}.EventStep-module__EventHeader--HqOYM{display:flex;align-items:flex-start;gap:12px;margin-bottom:12px}.EventStep-module__EventIcon--gxLQQ{flex-shrink:0;padding:6px;background-color:var(--theme-color-bg-3);border-radius:4px;color:var(--theme-color-primary)}.EventStep-module__EventMeta--xghu6{flex:1;min-width:0}.EventStep-module__NodeInfo--ZHjDh{display:flex;align-items:center;gap:8px;margin-bottom:4px}.EventStep-module__NodeType--iaDX7{font-size:13px;font-weight:600;color:var(--theme-color-fg-default)}.EventStep-module__NodeLabel--s4Xx3{font-size:12px;color:var(--theme-color-fg-default-shy);font-style:italic}.EventStep-module__ComponentInfo--W0Dod{display:flex;align-items:center;gap:4px;font-size:11px;color:var(--theme-color-fg-default-shy)}.EventStep-module__EventType--yIlvE{flex-shrink:0}.EventStep-module__EventType--yIlvE span{padding:4px 8px;border-radius:3px;font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;background-color:var(--theme-color-bg-4);color:var(--theme-color-fg-default)}.EventStep-module__EventType--yIlvE span.EventStep-module__type-signal--tq6et{background-color:var(--theme-color-primary);color:#fff}.EventStep-module__EventType--yIlvE span.EventStep-module__type-value-change--UucPH{background-color:#3b82f6;color:#fff}.EventStep-module__EventType--yIlvE span.EventStep-module__type-error--MEzJU{background-color:#ef4444;color:#fff}.EventStep-module__EventTiming--BD0yE{display:flex;gap:16px;padding:8px;background-color:var(--theme-color-bg-3);border-radius:3px;margin-bottom:8px}.EventStep-module__TimingItem--FQ7bR{display:flex;gap:6px;font-size:11px}.EventStep-module__TimingLabel--CIFwh{color:var(--theme-color-fg-default-shy)}.EventStep-module__TimingValue--bOstx{font-weight:600;font-family:monospace;color:var(--theme-color-fg-highlight)}.EventStep-module__EventPort--D2mva{display:flex;gap:6px;padding:6px 8px;background-color:var(--theme-color-bg-3);border-radius:3px;font-size:11px;margin-bottom:8px}.EventStep-module__PortLabel--Ir9gF{color:var(--theme-color-fg-default-shy)}.EventStep-module__PortName--DZYtT{font-weight:600;font-family:monospace;color:var(--theme-color-fg-default)}.EventStep-module__EventData--jfIAj{display:flex;flex-direction:column;gap:4px;padding:8px;background-color:var(--theme-color-bg-3);border-radius:3px;margin-bottom:8px}.EventStep-module__DataLabel--QP1QV{font-size:11px;font-weight:600;color:var(--theme-color-fg-default-shy)}.EventStep-module__DataValue--ykIF5{font-size:11px;font-family:monospace;color:var(--theme-color-fg-default);white-space:pre-wrap;word-break:break-all;max-height:100px;overflow-y:auto;padding:4px;background-color:var(--theme-color-bg-1);border-radius:2px}.EventStep-module__EventError--lFIIX{display:flex;align-items:center;gap:6px;padding:8px;background-color:rgba(239,68,68,.1);border:1px solid #ef4444;border-radius:3px;color:#ef4444;font-size:12px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/EventStep.module.scss"],"names":[],"mappings":"AAMA,oCACE,YAAA,CACA,QAAA,CACA,iBAAA,CACA,mBAAA,CAGE,sFACE,YAAA,CASN,4CACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,aAAA,CACA,eAAA,CAGF,sCACE,UAAA,CACA,WAAA,CACA,iBAAA,CACA,2CAAA,CACA,wCAAA,CACA,aAAA,CACA,SAAA,CAGF,uCACE,SAAA,CACA,MAAA,CACA,kDAAA,CACA,cAAA,CAOF,oCACE,MAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,YAAA,CACA,wBAAA,CAEA,0CACE,wCAAA,CACA,uCAAA,CAQJ,sCACE,YAAA,CACA,sBAAA,CACA,QAAA,CACA,kBAAA,CAGF,oCACE,aAAA,CACA,WAAA,CACA,wCAAA,CACA,iBAAA,CACA,gCAAA,CAGF,oCACE,MAAA,CACA,WAAA,CAGF,mCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,iBAAA,CAGF,mCACE,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,oCACE,cAAA,CACA,uCAAA,CACA,iBAAA,CAGF,wCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,cAAA,CACA,uCAAA,CAGF,oCACE,aAAA,CAEA,yCACE,eAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,wBAAA,CACA,mBAAA,CACA,wCAAA,CACA,mCAAA,CAEA,8EACE,2CAAA,CACA,UAAA,CAGF,oFACE,wBAAA,CACA,UAAA,CAGF,6EACE,wBAAA,CACA,UAAA,CASN,sCACE,YAAA,CACA,QAAA,CACA,WAAA,CACA,wCAAA,CACA,iBAAA,CACA,iBAAA,CAGF,qCACE,YAAA,CACA,OAAA,CACA,cAAA,CAGF,sCACE,uCAAA,CAGF,sCACE,eAAA,CACA,qBAAA,CACA,qCAAA,CAOF,oCACE,YAAA,CACA,OAAA,CACA,eAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,iBAAA,CAGF,oCACE,uCAAA,CAGF,mCACE,eAAA,CACA,qBAAA,CACA,mCAAA,CAOF,oCACE,YAAA,CACA,qBAAA,CACA,OAAA,CACA,WAAA,CACA,wCAAA,CACA,iBAAA,CACA,iBAAA,CAGF,oCACE,cAAA,CACA,eAAA,CACA,uCAAA,CAGF,oCACE,cAAA,CACA,qBAAA,CACA,mCAAA,CACA,oBAAA,CACA,oBAAA,CACA,gBAAA,CACA,eAAA,CACA,WAAA,CACA,wCAAA,CACA,iBAAA,CAOF,qCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,WAAA,CACA,mCAAA,CACA,wBAAA,CACA,iBAAA,CACA,aAAA,CACA,cAAA","sourcesContent":["/**\n * EventStep Component Styles\n *\n * Uses design tokens from UI-STYLING-GUIDE.md\n */\n\n.EventStep {\n  display: flex;\n  gap: 12px;\n  position: relative;\n  padding-bottom: 16px;\n\n  &:last-child {\n    .TimelineLine {\n      display: none;\n    }\n  }\n}\n\n/* =================================================================\n   Timeline Connector\n   ================================================================= */\n\n.TimelineConnector {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  flex-shrink: 0;\n  padding-top: 4px;\n}\n\n.TimelineDot {\n  width: 12px;\n  height: 12px;\n  border-radius: 50%;\n  background-color: var(--theme-color-primary);\n  border: 2px solid var(--theme-color-bg-1);\n  flex-shrink: 0;\n  z-index: 1;\n}\n\n.TimelineLine {\n  width: 2px;\n  flex: 1;\n  background-color: var(--theme-color-border-default);\n  margin-top: 4px;\n}\n\n/* =================================================================\n   Event Card\n   ================================================================= */\n\n.EventCard {\n  flex: 1;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  padding: 12px;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n    border-color: var(--theme-color-primary);\n  }\n}\n\n/* =================================================================\n   Event Header\n   ================================================================= */\n\n.EventHeader {\n  display: flex;\n  align-items: flex-start;\n  gap: 12px;\n  margin-bottom: 12px;\n}\n\n.EventIcon {\n  flex-shrink: 0;\n  padding: 6px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 4px;\n  color: var(--theme-color-primary);\n}\n\n.EventMeta {\n  flex: 1;\n  min-width: 0;\n}\n\n.NodeInfo {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin-bottom: 4px;\n}\n\n.NodeType {\n  font-size: 13px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n}\n\n.NodeLabel {\n  font-size: 12px;\n  color: var(--theme-color-fg-default-shy);\n  font-style: italic;\n}\n\n.ComponentInfo {\n  display: flex;\n  align-items: center;\n  gap: 4px;\n  font-size: 11px;\n  color: var(--theme-color-fg-default-shy);\n}\n\n.EventType {\n  flex-shrink: 0;\n\n  span {\n    padding: 4px 8px;\n    border-radius: 3px;\n    font-size: 10px;\n    font-weight: 600;\n    text-transform: uppercase;\n    letter-spacing: 0.5px;\n    background-color: var(--theme-color-bg-4);\n    color: var(--theme-color-fg-default);\n\n    &.type-signal {\n      background-color: var(--theme-color-primary);\n      color: white;\n    }\n\n    &.type-value-change {\n      background-color: #3b82f6;\n      color: white;\n    }\n\n    &.type-error {\n      background-color: #ef4444;\n      color: white;\n    }\n  }\n}\n\n/* =================================================================\n   Event Timing\n   ================================================================= */\n\n.EventTiming {\n  display: flex;\n  gap: 16px;\n  padding: 8px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 3px;\n  margin-bottom: 8px;\n}\n\n.TimingItem {\n  display: flex;\n  gap: 6px;\n  font-size: 11px;\n}\n\n.TimingLabel {\n  color: var(--theme-color-fg-default-shy);\n}\n\n.TimingValue {\n  font-weight: 600;\n  font-family: monospace;\n  color: var(--theme-color-fg-highlight);\n}\n\n/* =================================================================\n   Port Info\n   ================================================================= */\n\n.EventPort {\n  display: flex;\n  gap: 6px;\n  padding: 6px 8px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 3px;\n  font-size: 11px;\n  margin-bottom: 8px;\n}\n\n.PortLabel {\n  color: var(--theme-color-fg-default-shy);\n}\n\n.PortName {\n  font-weight: 600;\n  font-family: monospace;\n  color: var(--theme-color-fg-default);\n}\n\n/* =================================================================\n   Data Preview\n   ================================================================= */\n\n.EventData {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n  padding: 8px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 3px;\n  margin-bottom: 8px;\n}\n\n.DataLabel {\n  font-size: 11px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default-shy);\n}\n\n.DataValue {\n  font-size: 11px;\n  font-family: monospace;\n  color: var(--theme-color-fg-default);\n  white-space: pre-wrap;\n  word-break: break-all;\n  max-height: 100px;\n  overflow-y: auto;\n  padding: 4px;\n  background-color: var(--theme-color-bg-1);\n  border-radius: 2px;\n}\n\n/* =================================================================\n   Error Info\n   ================================================================= */\n\n.EventError {\n  display: flex;\n  align-items: center;\n  gap: 6px;\n  padding: 8px;\n  background-color: rgba(239, 68, 68, 0.1);\n  border: 1px solid #ef4444;\n  border-radius: 3px;\n  color: #ef4444;\n  font-size: 12px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"EventStep": `EventStep-module__EventStep--XXGFo`,
	"TimelineLine": `EventStep-module__TimelineLine--LACR2`,
	"TimelineConnector": `EventStep-module__TimelineConnector--KD6AD`,
	"TimelineDot": `EventStep-module__TimelineDot--Eh4nQ`,
	"EventCard": `EventStep-module__EventCard--OXwOE`,
	"EventHeader": `EventStep-module__EventHeader--HqOYM`,
	"EventIcon": `EventStep-module__EventIcon--gxLQQ`,
	"EventMeta": `EventStep-module__EventMeta--xghu6`,
	"NodeInfo": `EventStep-module__NodeInfo--ZHjDh`,
	"NodeType": `EventStep-module__NodeType--iaDX7`,
	"NodeLabel": `EventStep-module__NodeLabel--s4Xx3`,
	"ComponentInfo": `EventStep-module__ComponentInfo--W0Dod`,
	"EventType": `EventStep-module__EventType--yIlvE`,
	"type-signal": `EventStep-module__type-signal--tq6et`,
	"type-value-change": `EventStep-module__type-value-change--UucPH`,
	"type-error": `EventStep-module__type-error--MEzJU`,
	"EventTiming": `EventStep-module__EventTiming--BD0yE`,
	"TimingItem": `EventStep-module__TimingItem--FQ7bR`,
	"TimingLabel": `EventStep-module__TimingLabel--CIFwh`,
	"TimingValue": `EventStep-module__TimingValue--bOstx`,
	"EventPort": `EventStep-module__EventPort--D2mva`,
	"PortLabel": `EventStep-module__PortLabel--Ir9gF`,
	"PortName": `EventStep-module__PortName--DZYtT`,
	"EventData": `EventStep-module__EventData--jfIAj`,
	"DataLabel": `EventStep-module__DataLabel--QP1QV`,
	"DataValue": `EventStep-module__DataValue--ykIF5`,
	"EventError": `EventStep-module__EventError--lFIIX`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 53612:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   s: () => (/* reexport safe */ _sidebarmodel__WEBPACK_IMPORTED_MODULE_0__.s)
/* harmony export */ });
/* harmony import */ var _sidebarmodel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(41669);



/***/ }),

/***/ 53767:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-keybinding {
	display: flex;
	align-items: center;
	line-height: 10px;
}

.monaco-keybinding > .monaco-keybinding-key {
	display: inline-block;
	border-style: solid;
	border-width: 1px;
	border-radius: 3px;
	vertical-align: middle;
	font-size: 11px;
	padding: 3px 5px;
	margin: 0 2px;
}

.monaco-keybinding > .monaco-keybinding-key:first-child {
	margin-left: 0;
}

.monaco-keybinding > .monaco-keybinding-key:last-child {
	margin-right: 0;
}

.monaco-keybinding > .monaco-keybinding-key-separator {
	display: inline-block;
}

.monaco-keybinding > .monaco-keybinding-key-chord-separator {
	width: 6px;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/keybindingLabel/keybindingLabel.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,aAAa;CACb,mBAAmB;CACnB,iBAAiB;AAClB;;AAEA;CACC,qBAAqB;CACrB,mBAAmB;CACnB,iBAAiB;CACjB,kBAAkB;CAClB,sBAAsB;CACtB,eAAe;CACf,gBAAgB;CAChB,aAAa;AACd;;AAEA;CACC,cAAc;AACf;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,qBAAqB;AACtB;;AAEA;CACC,UAAU;AACX","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-keybinding {\n\tdisplay: flex;\n\talign-items: center;\n\tline-height: 10px;\n}\n\n.monaco-keybinding > .monaco-keybinding-key {\n\tdisplay: inline-block;\n\tborder-style: solid;\n\tborder-width: 1px;\n\tborder-radius: 3px;\n\tvertical-align: middle;\n\tfont-size: 11px;\n\tpadding: 3px 5px;\n\tmargin: 0 2px;\n}\n\n.monaco-keybinding > .monaco-keybinding-key:first-child {\n\tmargin-left: 0;\n}\n\n.monaco-keybinding > .monaco-keybinding-key:last-child {\n\tmargin-right: 0;\n}\n\n.monaco-keybinding > .monaco-keybinding-key-separator {\n\tdisplay: inline-block;\n}\n\n.monaco-keybinding > .monaco-keybinding-key-chord-separator {\n\twidth: 6px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 53790:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PopupToolbar-module__Root--VxGec{position:relative;display:inline-flex;animation-duration:300ms;animation-name:PopupToolbar-module__slideup--EQgx5;filter:drop-shadow(0 4px 15px var(--theme-color-bg-1-transparent-2));box-shadow:0 0 10px -5px var(--theme-color-bg-1-transparent-2),0 0 2px -1px var(--theme-color-bg-1);border-radius:2px}.PopupToolbar-module__IconList--oG6_g{background-color:var(--base-color-grey-900);gap:1px;border-radius:2px}@keyframes PopupToolbar-module__slideup--EQgx5{from{top:10px;opacity:0}to{top:0px;opacity:1}}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/popups/PopupToolbar/PopupToolbar.module.scss"],"names":[],"mappings":"AAAA,kCACE,iBAAA,CACA,mBAAA,CACA,wBAAA,CACA,kDAAA,CACA,oEAAA,CACA,mGAAA,CACA,iBAAA,CAGF,sCACE,2CAAA,CACA,OAAA,CACA,iBAAA,CAGF,+CACE,KACE,QAAA,CACA,SAAA,CAGF,GACE,OAAA,CACA,SAAA,CAAA","sourcesContent":[".Root {\n  position: relative;\n  display: inline-flex;\n  animation-duration: 300ms;\n  animation-name: slideup;\n  filter: drop-shadow(0 4px 15px var(--theme-color-bg-1-transparent-2));\n  box-shadow: 0 0 10px -5px var(--theme-color-bg-1-transparent-2), 0 0 2px -1px var(--theme-color-bg-1);\n  border-radius: 2px;\n}\n\n.IconList {\n  background-color: var(--base-color-grey-900);\n  gap: 1px;\n  border-radius: 2px;\n}\n\n@keyframes slideup {\n  from {\n    top: 10px;\n    opacity: 0;\n  }\n\n  to {\n    top: 0px;\n    opacity: 1;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PopupToolbar-module__Root--VxGec`,
	"slideup": `PopupToolbar-module__slideup--EQgx5`,
	"IconList": `PopupToolbar-module__IconList--oG6_g`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 53823:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  O: () => (/* reexport */ getTheme),
  n: () => (/* binding */ registerActions)
});

;// ./src/editor/src/views/panels/propertyeditor/CodeEditor/actions/extra.ts
function registerExtraActions(editor) {
    editor.addAction({
        id: 'table-flip',
        label: 'Table flip',
        run(ed) {
            ed.trigger('keyboard', 'type', {
                text: '(╯°□°）╯︵ ┻━┻'
            });
        }
    });
    editor.addAction({
        id: 'table-unflip',
        label: 'Table unflip',
        run(ed) {
            ed.trigger('keyboard', 'type', {
                text: '┬─┬ ノ( ゜-゜ノ)'
            });
        }
    });
    editor.addAction({
        id: 'shrug',
        label: 'Shrug',
        run(ed) {
            ed.trigger('keyboard', 'type', {
                text: '¯\\\\_(ツ)_/¯'
            });
        }
    });
}

// EXTERNAL MODULE: include-loader!../../node_modules/monaco-editor/esm/vs/editor/editor.api.js + 669 modules
var editor_api = __webpack_require__(15618);
;// ./src/editor/src/views/panels/propertyeditor/CodeEditor/actions/theme.ts

function getTheme() {
    return localStorage.getItem('monaco-theme') || 'noodl-dark';
}
function setTheme(theme) {
    localStorage.setItem('monaco-theme', theme);
    editor_api.editor.setTheme(theme);
}
function registerThemeActions(editor) {
    editor.addAction({
        id: 'set-theme-noodl-dark',
        label: 'Set theme to Noodl dark',
        run(_ed) {
            setTheme('noodl-dark');
        }
    });
    editor.addAction({
        id: 'set-theme-dark',
        label: 'Set theme to default dark',
        run(_ed) {
            setTheme('dark');
        }
    });
}

;// ./src/editor/src/views/panels/propertyeditor/CodeEditor/actions/index.ts



function registerActions(editor) {
    registerThemeActions(editor);
    registerExtraActions(editor);
}


/***/ }),

/***/ 54597:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `@keyframes ReportStep-module__slideInUp--cqtSR{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes ReportStep-module__countUp--SZqSc{from{transform:scale(0.8);opacity:0}to{transform:scale(1);opacity:1}}@keyframes ReportStep-module__sparkle--L83L1{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.7;transform:scale(1.1)}}.ReportStep-module__Root--REVTo{display:flex;flex-direction:column;height:100%;animation:ReportStep-module__slideInUp--cqtSR 300ms ease-out}.ReportStep-module__Header--mvXxU{display:flex;align-items:center;gap:16px;margin-bottom:20px}.ReportStep-module__Header--mvXxU svg{width:24px;height:24px;color:var(--theme-color-primary)}.ReportStep-module__Header--mvXxU h2{font-size:20px;font-weight:600;color:var(--theme-color-fg-highlight);margin:0}.ReportStep-module__Header--mvXxU p{font-size:14px;color:var(--theme-color-fg-default);margin:4px 0 0 0}.ReportStep-module__StatsRow--ECs4j{display:grid;grid-template-columns:repeat(3, 1fr);gap:16px;margin-bottom:24px}.ReportStep-module__StatCard--xCEBS{display:flex;flex-direction:column;align-items:center;gap:12px;padding:20px 16px;background:linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);border-radius:12px;text-align:center;border:1px solid var(--theme-color-bg-2);transition:all 250ms ease-in-out;position:relative;overflow:hidden}.ReportStep-module__StatCard--xCEBS::before{content:"";position:absolute;top:0;left:0;right:0;height:3px;background:var(--theme-color-secondary-as-fg);opacity:0;transition:opacity 250ms ease-in-out}.ReportStep-module__StatCard--xCEBS:hover{transform:translateY(-4px);box-shadow:0 8px 16px rgba(0,0,0,.15)}.ReportStep-module__StatCard--xCEBS:hover::before{opacity:1}.ReportStep-module__StatCard--xCEBS.ReportStep-module__is-automatic--FggZy::before{background:var(--theme-color-success)}.ReportStep-module__StatCard--xCEBS.ReportStep-module__is-simpleFixes--w_Urn::before{background:var(--theme-color-warning)}.ReportStep-module__StatCard--xCEBS.ReportStep-module__is-needsReview--ShnUA::before{background:var(--theme-color-danger)}.ReportStep-module__StatCardIcon--tYpJJ{width:40px;height:40px;display:flex;align-items:center;justify-content:center;color:var(--theme-color-secondary-as-fg);background-color:var(--theme-color-bg-4);border-radius:50%;transition:all 200ms ease-in-out}.ReportStep-module__StatCardIcon--tYpJJ svg{width:22px;height:22px}.ReportStep-module__StatCard--xCEBS.ReportStep-module__is-automatic--FggZy .ReportStep-module__StatCardIcon--tYpJJ{color:var(--theme-color-success);background-color:rgba(34,197,94,.15)}.ReportStep-module__StatCard--xCEBS.ReportStep-module__is-simpleFixes--w_Urn .ReportStep-module__StatCardIcon--tYpJJ{color:var(--theme-color-warning);background-color:rgba(251,191,36,.15)}.ReportStep-module__StatCard--xCEBS.ReportStep-module__is-needsReview--ShnUA .ReportStep-module__StatCardIcon--tYpJJ{color:var(--theme-color-danger);background-color:rgba(239,68,68,.15)}.ReportStep-module__StatCard--xCEBS:hover .ReportStep-module__StatCardIcon--tYpJJ{transform:scale(1.1) rotate(5deg)}.ReportStep-module__StatCardValue--_Qvjh{font-size:32px;font-weight:700;color:var(--theme-color-fg-highlight);line-height:1;font-variant-numeric:tabular-nums;animation:ReportStep-module__countUp--SZqSc 400ms ease-out}.ReportStep-module__StatCardLabel--WCJEw{font-size:11px;color:var(--theme-color-fg-default);text-transform:uppercase;letter-spacing:.8px;font-weight:600}.ReportStep-module__Categories--mjgjt{flex:1;overflow-y:auto;display:flex;flex-direction:column;gap:12px}.ReportStep-module__CategorySection--buDXl{background-color:var(--theme-color-bg-3);border-radius:10px;overflow:hidden;border:1px solid var(--theme-color-bg-2);transition:all 250ms ease-in-out}.ReportStep-module__CategorySection--buDXl:hover{border-color:var(--theme-color-bg-1)}.ReportStep-module__CategorySection--buDXl.ReportStep-module__is-expanded--Bh9Ml{background-color:var(--theme-color-bg-2)}.ReportStep-module__CategoryHeader--rYphk{display:flex;align-items:center;gap:12px;padding:16px 20px;background-color:rgba(0,0,0,0);cursor:pointer;transition:all 200ms ease-in-out;user-select:none}.ReportStep-module__CategoryHeader--rYphk:hover{background-color:var(--theme-color-bg-2)}.ReportStep-module__CategoryHeader--rYphk:active{transform:scale(0.98)}.ReportStep-module__CategorySection--buDXl.ReportStep-module__is-expanded--Bh9Ml .ReportStep-module__CategoryHeader--rYphk{background-color:var(--theme-color-bg-1);border-bottom:1px solid var(--theme-color-bg-3)}.ReportStep-module__CategoryIcon--AjoGa{width:36px;height:36px;display:flex;align-items:center;justify-content:center;border-radius:8px;transition:all 200ms ease-in-out;flex-shrink:0}.ReportStep-module__CategoryIcon--AjoGa svg{width:18px;height:18px}.ReportStep-module__CategorySection--buDXl.ReportStep-module__is-automatic--FggZy .ReportStep-module__CategoryIcon--AjoGa{color:var(--theme-color-success);background-color:rgba(34,197,94,.15)}.ReportStep-module__CategorySection--buDXl.ReportStep-module__is-simpleFixes--w_Urn .ReportStep-module__CategoryIcon--AjoGa{color:var(--theme-color-warning);background-color:rgba(251,191,36,.15)}.ReportStep-module__CategorySection--buDXl.ReportStep-module__is-needsReview--ShnUA .ReportStep-module__CategoryIcon--AjoGa{color:var(--theme-color-danger);background-color:rgba(239,68,68,.15)}.ReportStep-module__CategoryHeader--rYphk:hover .ReportStep-module__CategoryIcon--AjoGa{transform:scale(1.1)}.ReportStep-module__CategoryInfo--Xq2y2{flex:1;display:flex;flex-direction:column;gap:2px}.ReportStep-module__CategoryTitle--fGJKX{font-size:15px;font-weight:600;color:var(--theme-color-fg-highlight)}.ReportStep-module__CategoryDescription--ObK3b{font-size:12px;color:var(--theme-color-fg-default)}.ReportStep-module__CategoryCount--SFVvk{background-color:var(--theme-color-bg-4);padding:4px 12px;border-radius:12px;font-size:13px;font-weight:600;color:var(--theme-color-fg-highlight);border:1px solid var(--theme-color-bg-1)}.ReportStep-module__ExpandIcon--k3q4Q{width:20px;height:20px;color:var(--theme-color-fg-muted);transition:transform 250ms ease-in-out;flex-shrink:0}.ReportStep-module__ExpandIcon--k3q4Q svg{width:100%;height:100%}.ReportStep-module__CategorySection--buDXl.ReportStep-module__is-expanded--Bh9Ml .ReportStep-module__ExpandIcon--k3q4Q{transform:rotate(180deg);color:var(--theme-color-primary)}.ReportStep-module__ComponentList--LSnCs{display:flex;flex-direction:column;gap:6px;padding:12px;max-height:250px;overflow-y:auto;animation:ReportStep-module__slideInUp--cqtSR 250ms ease-out}.ReportStep-module__ComponentList--LSnCs::-webkit-scrollbar{width:6px}.ReportStep-module__ComponentList--LSnCs::-webkit-scrollbar-track{background:var(--theme-color-bg-3);border-radius:3px}.ReportStep-module__ComponentList--LSnCs::-webkit-scrollbar-thumb{background:var(--theme-color-bg-1);border-radius:3px}.ReportStep-module__ComponentList--LSnCs::-webkit-scrollbar-thumb:hover{background:var(--theme-color-primary)}.ReportStep-module__ComponentItem--nNDur{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;background-color:var(--theme-color-bg-4);border-radius:8px;border:1px solid var(--theme-color-bg-3);transition:all 200ms ease-in-out;cursor:pointer}.ReportStep-module__ComponentItem--nNDur:hover{background-color:var(--theme-color-bg-3);border-color:var(--theme-color-primary);transform:translateX(4px)}.ReportStep-module__ComponentName--kLNHs{font-size:13px;font-weight:500;color:var(--theme-color-fg-highlight);display:flex;align-items:center;gap:8px}.ReportStep-module__ComponentName--kLNHs::before{content:"";width:6px;height:6px;border-radius:50%;background-color:var(--theme-color-primary)}.ReportStep-module__ComponentIssueCount--iEFj_{font-size:11px;color:var(--theme-color-fg-default);background-color:var(--theme-color-bg-2);padding:3px 8px;border-radius:10px;font-weight:500}.ReportStep-module__AiPromptSection--aXgMe{margin-top:20px;padding:24px;background:linear-gradient(135deg, rgba(139, 92, 246, 0.12) 0%, rgba(139, 92, 246, 0.08) 100%);border:2px solid rgba(139,92,246,.3);border-radius:12px;position:relative;overflow:hidden;transition:all 250ms ease-in-out}.ReportStep-module__AiPromptSection--aXgMe::before{content:"";position:absolute;top:-2px;left:-2px;right:-2px;bottom:-2px;background:linear-gradient(45deg, rgba(139, 92, 246, 0.3), rgba(168, 85, 247, 0.3), rgba(139, 92, 246, 0.3));background-size:200% 200%;animation:ReportStep-module__shimmer--kvnil 3s ease-in-out infinite;border-radius:12px;opacity:0;transition:opacity 250ms ease-in-out;z-index:-1}.ReportStep-module__AiPromptSection--aXgMe:hover::before{opacity:1}.ReportStep-module__AiPromptHeader--s0RqG{display:flex;align-items:center;gap:12px;margin-bottom:16px}.ReportStep-module__AiPromptHeader--s0RqG svg{width:28px;height:28px;color:#8b5cf6;animation:ReportStep-module__sparkle--L83L1 2s ease-in-out infinite;filter:drop-shadow(0 0 8px rgba(139, 92, 246, 0.4))}.ReportStep-module__AiPromptHeader--s0RqG h4{font-size:16px;font-weight:600;color:#8b5cf6;margin:0}.ReportStep-module__AiPromptContent--Qlz1S{display:flex;flex-direction:column;gap:12px}.ReportStep-module__AiPromptContent--Qlz1S p{font-size:13px;line-height:1.6;color:var(--theme-color-fg-default);margin:0}.ReportStep-module__AiPromptContent--Qlz1S strong{color:var(--theme-color-fg-highlight)}.ReportStep-module__AiPromptFeatures--l_RjW{display:flex;gap:12px;margin-top:12px;flex-wrap:wrap}.ReportStep-module__AiPromptFeature--aKulX{display:flex;align-items:center;gap:6px;padding:6px 12px;background-color:rgba(139,92,246,.15);border-radius:16px;font-size:12px;color:#8b5cf6;font-weight:500}.ReportStep-module__AiPromptFeature--aKulX svg{width:14px;height:14px}.ReportStep-module__AiPromptCost--HLJb3{display:inline-flex;align-items:center;gap:4px;font-weight:600;color:#8b5cf6}.ReportStep-module__AiPromptCost--HLJb3 svg{width:16px;height:16px}.ReportStep-module__AiPromptSection--aXgMe.ReportStep-module__is-disabled--LlaI5{opacity:.5;pointer-events:none;filter:grayscale(0.5)}.ReportStep-module__Actions--cYYnF{margin-top:auto;padding-top:24px;display:flex;justify-content:flex-end;gap:12px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/migration/steps/ReportStep.module.scss"],"names":[],"mappings":"AAMA,+CACE,KACE,SAAA,CACA,0BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,6CACE,KACE,oBAAA,CACA,SAAA,CAEF,GACE,kBAAA,CACA,SAAA,CAAA,CAIJ,6CACE,QAEE,SAAA,CACA,kBAAA,CAEF,IACE,UAAA,CACA,oBAAA,CAAA,CAIJ,gCACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,4DAAA,CAGF,kCACE,YAAA,CACA,kBAAA,CACA,QAAA,CACA,kBAAA,CAEA,sCACE,UAAA,CACA,WAAA,CACA,gCAAA,CAGF,qCACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,QAAA,CAGF,oCACE,cAAA,CACA,mCAAA,CACA,gBAAA,CAIJ,oCACE,YAAA,CACA,oCAAA,CACA,QAAA,CACA,kBAAA,CAGF,oCACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,QAAA,CACA,iBAAA,CACA,4FAAA,CACA,kBAAA,CACA,iBAAA,CACA,wCAAA,CACA,gCAAA,CACA,iBAAA,CACA,eAAA,CAEA,4CACE,UAAA,CACA,iBAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,UAAA,CACA,6CAAA,CACA,SAAA,CACA,oCAAA,CAGF,0CACE,0BAAA,CACA,qCAAA,CAEA,kDACE,SAAA,CAKN,mFACE,qCAAA,CAGF,qFACE,qCAAA,CAGF,qFACE,oCAAA,CAGF,wCACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,wCAAA,CACA,wCAAA,CACA,iBAAA,CACA,gCAAA,CAEA,4CACE,UAAA,CACA,WAAA,CAIJ,mHACE,gCAAA,CACA,oCAAA,CAGF,qHACE,gCAAA,CACA,qCAAA,CAGF,qHACE,+BAAA,CACA,oCAAA,CAGF,kFACE,iCAAA,CAGF,yCACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,aAAA,CACA,iCAAA,CACA,0DAAA,CAGF,yCACE,cAAA,CACA,mCAAA,CACA,wBAAA,CACA,mBAAA,CACA,eAAA,CAGF,sCACE,MAAA,CACA,eAAA,CACA,YAAA,CACA,qBAAA,CACA,QAAA,CAGF,2CACE,wCAAA,CACA,kBAAA,CACA,eAAA,CACA,wCAAA,CACA,gCAAA,CAEA,iDACE,oCAAA,CAIJ,iFACE,wCAAA,CAGF,0CACE,YAAA,CACA,kBAAA,CACA,QAAA,CACA,iBAAA,CACA,8BAAA,CACA,cAAA,CACA,gCAAA,CACA,gBAAA,CAEA,gDACE,wCAAA,CAGF,iDACE,qBAAA,CAIJ,2HACE,wCAAA,CACA,+CAAA,CAGF,wCACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,gCAAA,CACA,aAAA,CAEA,4CACE,UAAA,CACA,WAAA,CAIJ,0HACE,gCAAA,CACA,oCAAA,CAGF,4HACE,gCAAA,CACA,qCAAA,CAGF,4HACE,+BAAA,CACA,oCAAA,CAGF,wFACE,oBAAA,CAGF,wCACE,MAAA,CACA,YAAA,CACA,qBAAA,CACA,OAAA,CAGF,yCACE,cAAA,CACA,eAAA,CACA,qCAAA,CAGF,+CACE,cAAA,CACA,mCAAA,CAGF,yCACE,wCAAA,CACA,gBAAA,CACA,kBAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CACA,wCAAA,CAGF,sCACE,UAAA,CACA,WAAA,CACA,iCAAA,CACA,sCAAA,CACA,aAAA,CAEA,0CACE,UAAA,CACA,WAAA,CAIJ,uHACE,wBAAA,CACA,gCAAA,CAGF,yCACE,YAAA,CACA,qBAAA,CACA,OAAA,CACA,YAAA,CACA,gBAAA,CACA,eAAA,CACA,4DAAA,CAGA,4DACE,SAAA,CAGF,kEACE,kCAAA,CACA,iBAAA,CAGF,kEACE,kCAAA,CACA,iBAAA,CAEA,wEACE,qCAAA,CAKN,yCACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,iBAAA,CACA,wCAAA,CACA,iBAAA,CACA,wCAAA,CACA,gCAAA,CACA,cAAA,CAEA,+CACE,wCAAA,CACA,uCAAA,CACA,yBAAA,CAIJ,yCACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,YAAA,CACA,kBAAA,CACA,OAAA,CAEA,iDACE,UAAA,CACA,SAAA,CACA,UAAA,CACA,iBAAA,CACA,2CAAA,CAIJ,+CACE,cAAA,CACA,mCAAA,CACA,wCAAA,CACA,eAAA,CACA,kBAAA,CACA,eAAA,CAGF,2CACE,eAAA,CACA,YAAA,CACA,8FAAA,CACA,oCAAA,CACA,kBAAA,CACA,iBAAA,CACA,eAAA,CACA,gCAAA,CAEA,mDACE,UAAA,CACA,iBAAA,CACA,QAAA,CACA,SAAA,CACA,UAAA,CACA,WAAA,CACA,4GAAA,CACA,yBAAA,CACA,mEAAA,CACA,kBAAA,CACA,SAAA,CACA,oCAAA,CACA,UAAA,CAGF,yDACE,SAAA,CAIJ,0CACE,YAAA,CACA,kBAAA,CACA,QAAA,CACA,kBAAA,CAEA,8CACE,UAAA,CACA,WAAA,CACA,aAAA,CACA,mEAAA,CACA,mDAAA,CAGF,6CACE,cAAA,CACA,eAAA,CACA,aAAA,CACA,QAAA,CAIJ,2CACE,YAAA,CACA,qBAAA,CACA,QAAA,CAEA,6CACE,cAAA,CACA,eAAA,CACA,mCAAA,CACA,QAAA,CAGF,kDACE,qCAAA,CAIJ,4CACE,YAAA,CACA,QAAA,CACA,eAAA,CACA,cAAA,CAGF,2CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,gBAAA,CACA,qCAAA,CACA,kBAAA,CACA,cAAA,CACA,aAAA,CACA,eAAA,CAEA,+CACE,UAAA,CACA,WAAA,CAIJ,wCACE,mBAAA,CACA,kBAAA,CACA,OAAA,CACA,eAAA,CACA,aAAA,CAEA,4CACE,UAAA,CACA,WAAA,CAIJ,iFACE,UAAA,CACA,mBAAA,CACA,qBAAA,CAGF,mCACE,eAAA,CACA,gBAAA,CACA,YAAA,CACA,wBAAA,CACA,QAAA","sourcesContent":["/**\n * ReportStep Styles\n * \n * Enhanced scan results report with beautiful categories and AI options.\n */\n\n@keyframes slideInUp {\n  from {\n    opacity: 0;\n    transform: translateY(10px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n@keyframes countUp {\n  from {\n    transform: scale(0.8);\n    opacity: 0;\n  }\n  to {\n    transform: scale(1);\n    opacity: 1;\n  }\n}\n\n@keyframes sparkle {\n  0%,\n  100% {\n    opacity: 1;\n    transform: scale(1);\n  }\n  50% {\n    opacity: 0.7;\n    transform: scale(1.1);\n  }\n}\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  animation: slideInUp 300ms ease-out;\n}\n\n.Header {\n  display: flex;\n  align-items: center;\n  gap: 16px;\n  margin-bottom: 20px;\n\n  svg {\n    width: 24px;\n    height: 24px;\n    color: var(--theme-color-primary);\n  }\n\n  h2 {\n    font-size: 20px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    margin: 0;\n  }\n\n  p {\n    font-size: 14px;\n    color: var(--theme-color-fg-default);\n    margin: 4px 0 0 0;\n  }\n}\n\n.StatsRow {\n  display: grid;\n  grid-template-columns: repeat(3, 1fr);\n  gap: 16px;\n  margin-bottom: 24px;\n}\n\n.StatCard {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 12px;\n  padding: 20px 16px;\n  background: linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);\n  border-radius: 12px;\n  text-align: center;\n  border: 1px solid var(--theme-color-bg-2);\n  transition: all 250ms ease-in-out;\n  position: relative;\n  overflow: hidden;\n\n  &::before {\n    content: '';\n    position: absolute;\n    top: 0;\n    left: 0;\n    right: 0;\n    height: 3px;\n    background: var(--theme-color-secondary-as-fg);\n    opacity: 0;\n    transition: opacity 250ms ease-in-out;\n  }\n\n  &:hover {\n    transform: translateY(-4px);\n    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);\n\n    &::before {\n      opacity: 1;\n    }\n  }\n}\n\n.StatCard.is-automatic::before {\n  background: var(--theme-color-success);\n}\n\n.StatCard.is-simpleFixes::before {\n  background: var(--theme-color-warning);\n}\n\n.StatCard.is-needsReview::before {\n  background: var(--theme-color-danger);\n}\n\n.StatCardIcon {\n  width: 40px;\n  height: 40px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  color: var(--theme-color-secondary-as-fg);\n  background-color: var(--theme-color-bg-4);\n  border-radius: 50%;\n  transition: all 200ms ease-in-out;\n\n  svg {\n    width: 22px;\n    height: 22px;\n  }\n}\n\n.StatCard.is-automatic .StatCardIcon {\n  color: var(--theme-color-success);\n  background-color: rgba(34, 197, 94, 0.15);\n}\n\n.StatCard.is-simpleFixes .StatCardIcon {\n  color: var(--theme-color-warning);\n  background-color: rgba(251, 191, 36, 0.15);\n}\n\n.StatCard.is-needsReview .StatCardIcon {\n  color: var(--theme-color-danger);\n  background-color: rgba(239, 68, 68, 0.15);\n}\n\n.StatCard:hover .StatCardIcon {\n  transform: scale(1.1) rotate(5deg);\n}\n\n.StatCardValue {\n  font-size: 32px;\n  font-weight: 700;\n  color: var(--theme-color-fg-highlight);\n  line-height: 1;\n  font-variant-numeric: tabular-nums;\n  animation: countUp 400ms ease-out;\n}\n\n.StatCardLabel {\n  font-size: 11px;\n  color: var(--theme-color-fg-default);\n  text-transform: uppercase;\n  letter-spacing: 0.8px;\n  font-weight: 600;\n}\n\n.Categories {\n  flex: 1;\n  overflow-y: auto;\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n}\n\n.CategorySection {\n  background-color: var(--theme-color-bg-3);\n  border-radius: 10px;\n  overflow: hidden;\n  border: 1px solid var(--theme-color-bg-2);\n  transition: all 250ms ease-in-out;\n\n  &:hover {\n    border-color: var(--theme-color-bg-1);\n  }\n}\n\n.CategorySection.is-expanded {\n  background-color: var(--theme-color-bg-2);\n}\n\n.CategoryHeader {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  padding: 16px 20px;\n  background-color: transparent;\n  cursor: pointer;\n  transition: all 200ms ease-in-out;\n  user-select: none;\n\n  &:hover {\n    background-color: var(--theme-color-bg-2);\n  }\n\n  &:active {\n    transform: scale(0.98);\n  }\n}\n\n.CategorySection.is-expanded .CategoryHeader {\n  background-color: var(--theme-color-bg-1);\n  border-bottom: 1px solid var(--theme-color-bg-3);\n}\n\n.CategoryIcon {\n  width: 36px;\n  height: 36px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  border-radius: 8px;\n  transition: all 200ms ease-in-out;\n  flex-shrink: 0;\n\n  svg {\n    width: 18px;\n    height: 18px;\n  }\n}\n\n.CategorySection.is-automatic .CategoryIcon {\n  color: var(--theme-color-success);\n  background-color: rgba(34, 197, 94, 0.15);\n}\n\n.CategorySection.is-simpleFixes .CategoryIcon {\n  color: var(--theme-color-warning);\n  background-color: rgba(251, 191, 36, 0.15);\n}\n\n.CategorySection.is-needsReview .CategoryIcon {\n  color: var(--theme-color-danger);\n  background-color: rgba(239, 68, 68, 0.15);\n}\n\n.CategoryHeader:hover .CategoryIcon {\n  transform: scale(1.1);\n}\n\n.CategoryInfo {\n  flex: 1;\n  display: flex;\n  flex-direction: column;\n  gap: 2px;\n}\n\n.CategoryTitle {\n  font-size: 15px;\n  font-weight: 600;\n  color: var(--theme-color-fg-highlight);\n}\n\n.CategoryDescription {\n  font-size: 12px;\n  color: var(--theme-color-fg-default);\n}\n\n.CategoryCount {\n  background-color: var(--theme-color-bg-4);\n  padding: 4px 12px;\n  border-radius: 12px;\n  font-size: 13px;\n  font-weight: 600;\n  color: var(--theme-color-fg-highlight);\n  border: 1px solid var(--theme-color-bg-1);\n}\n\n.ExpandIcon {\n  width: 20px;\n  height: 20px;\n  color: var(--theme-color-fg-muted);\n  transition: transform 250ms ease-in-out;\n  flex-shrink: 0;\n\n  svg {\n    width: 100%;\n    height: 100%;\n  }\n}\n\n.CategorySection.is-expanded .ExpandIcon {\n  transform: rotate(180deg);\n  color: var(--theme-color-primary);\n}\n\n.ComponentList {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n  padding: 12px;\n  max-height: 250px;\n  overflow-y: auto;\n  animation: slideInUp 250ms ease-out;\n\n  /* Custom scrollbar */\n  &::-webkit-scrollbar {\n    width: 6px;\n  }\n\n  &::-webkit-scrollbar-track {\n    background: var(--theme-color-bg-3);\n    border-radius: 3px;\n  }\n\n  &::-webkit-scrollbar-thumb {\n    background: var(--theme-color-bg-1);\n    border-radius: 3px;\n\n    &:hover {\n      background: var(--theme-color-primary);\n    }\n  }\n}\n\n.ComponentItem {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 12px 16px;\n  background-color: var(--theme-color-bg-4);\n  border-radius: 8px;\n  border: 1px solid var(--theme-color-bg-3);\n  transition: all 200ms ease-in-out;\n  cursor: pointer;\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n    border-color: var(--theme-color-primary);\n    transform: translateX(4px);\n  }\n}\n\n.ComponentName {\n  font-size: 13px;\n  font-weight: 500;\n  color: var(--theme-color-fg-highlight);\n  display: flex;\n  align-items: center;\n  gap: 8px;\n\n  &::before {\n    content: '';\n    width: 6px;\n    height: 6px;\n    border-radius: 50%;\n    background-color: var(--theme-color-primary);\n  }\n}\n\n.ComponentIssueCount {\n  font-size: 11px;\n  color: var(--theme-color-fg-default);\n  background-color: var(--theme-color-bg-2);\n  padding: 3px 8px;\n  border-radius: 10px;\n  font-weight: 500;\n}\n\n.AiPromptSection {\n  margin-top: 20px;\n  padding: 24px;\n  background: linear-gradient(135deg, rgba(139, 92, 246, 0.12) 0%, rgba(139, 92, 246, 0.08) 100%);\n  border: 2px solid rgba(139, 92, 246, 0.3);\n  border-radius: 12px;\n  position: relative;\n  overflow: hidden;\n  transition: all 250ms ease-in-out;\n\n  &::before {\n    content: '';\n    position: absolute;\n    top: -2px;\n    left: -2px;\n    right: -2px;\n    bottom: -2px;\n    background: linear-gradient(45deg, rgba(139, 92, 246, 0.3), rgba(168, 85, 247, 0.3), rgba(139, 92, 246, 0.3));\n    background-size: 200% 200%;\n    animation: shimmer 3s ease-in-out infinite;\n    border-radius: 12px;\n    opacity: 0;\n    transition: opacity 250ms ease-in-out;\n    z-index: -1;\n  }\n\n  &:hover::before {\n    opacity: 1;\n  }\n}\n\n.AiPromptHeader {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  margin-bottom: 16px;\n\n  svg {\n    width: 28px;\n    height: 28px;\n    color: #8b5cf6;\n    animation: sparkle 2s ease-in-out infinite;\n    filter: drop-shadow(0 0 8px rgba(139, 92, 246, 0.4));\n  }\n\n  h4 {\n    font-size: 16px;\n    font-weight: 600;\n    color: #8b5cf6;\n    margin: 0;\n  }\n}\n\n.AiPromptContent {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n\n  p {\n    font-size: 13px;\n    line-height: 1.6;\n    color: var(--theme-color-fg-default);\n    margin: 0;\n  }\n\n  strong {\n    color: var(--theme-color-fg-highlight);\n  }\n}\n\n.AiPromptFeatures {\n  display: flex;\n  gap: 12px;\n  margin-top: 12px;\n  flex-wrap: wrap;\n}\n\n.AiPromptFeature {\n  display: flex;\n  align-items: center;\n  gap: 6px;\n  padding: 6px 12px;\n  background-color: rgba(139, 92, 246, 0.15);\n  border-radius: 16px;\n  font-size: 12px;\n  color: #8b5cf6;\n  font-weight: 500;\n\n  svg {\n    width: 14px;\n    height: 14px;\n  }\n}\n\n.AiPromptCost {\n  display: inline-flex;\n  align-items: center;\n  gap: 4px;\n  font-weight: 600;\n  color: #8b5cf6;\n\n  svg {\n    width: 16px;\n    height: 16px;\n  }\n}\n\n.AiPromptSection.is-disabled {\n  opacity: 0.5;\n  pointer-events: none;\n  filter: grayscale(0.5);\n}\n\n.Actions {\n  margin-top: auto;\n  padding-top: 24px;\n  display: flex;\n  justify-content: flex-end;\n  gap: 12px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ReportStep-module__Root--REVTo`,
	"slideInUp": `ReportStep-module__slideInUp--cqtSR`,
	"Header": `ReportStep-module__Header--mvXxU`,
	"StatsRow": `ReportStep-module__StatsRow--ECs4j`,
	"StatCard": `ReportStep-module__StatCard--xCEBS`,
	"is-automatic": `ReportStep-module__is-automatic--FggZy`,
	"is-simpleFixes": `ReportStep-module__is-simpleFixes--w_Urn`,
	"is-needsReview": `ReportStep-module__is-needsReview--ShnUA`,
	"StatCardIcon": `ReportStep-module__StatCardIcon--tYpJJ`,
	"StatCardValue": `ReportStep-module__StatCardValue--_Qvjh`,
	"countUp": `ReportStep-module__countUp--SZqSc`,
	"StatCardLabel": `ReportStep-module__StatCardLabel--WCJEw`,
	"Categories": `ReportStep-module__Categories--mjgjt`,
	"CategorySection": `ReportStep-module__CategorySection--buDXl`,
	"is-expanded": `ReportStep-module__is-expanded--Bh9Ml`,
	"CategoryHeader": `ReportStep-module__CategoryHeader--rYphk`,
	"CategoryIcon": `ReportStep-module__CategoryIcon--AjoGa`,
	"CategoryInfo": `ReportStep-module__CategoryInfo--Xq2y2`,
	"CategoryTitle": `ReportStep-module__CategoryTitle--fGJKX`,
	"CategoryDescription": `ReportStep-module__CategoryDescription--ObK3b`,
	"CategoryCount": `ReportStep-module__CategoryCount--SFVvk`,
	"ExpandIcon": `ReportStep-module__ExpandIcon--k3q4Q`,
	"ComponentList": `ReportStep-module__ComponentList--LSnCs`,
	"ComponentItem": `ReportStep-module__ComponentItem--nNDur`,
	"ComponentName": `ReportStep-module__ComponentName--kLNHs`,
	"ComponentIssueCount": `ReportStep-module__ComponentIssueCount--iEFj_`,
	"AiPromptSection": `ReportStep-module__AiPromptSection--aXgMe`,
	"shimmer": `ReportStep-module__shimmer--kvnil`,
	"AiPromptHeader": `ReportStep-module__AiPromptHeader--s0RqG`,
	"sparkle": `ReportStep-module__sparkle--L83L1`,
	"AiPromptContent": `ReportStep-module__AiPromptContent--Qlz1S`,
	"AiPromptFeatures": `ReportStep-module__AiPromptFeatures--l_RjW`,
	"AiPromptFeature": `ReportStep-module__AiPromptFeature--aKulX`,
	"AiPromptCost": `ReportStep-module__AiPromptCost--HLJb3`,
	"is-disabled": `ReportStep-module__is-disabled--LlaI5`,
	"Actions": `ReportStep-module__Actions--cYYnF`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 54743:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DEFAULT_APP_CONFIG: () => (/* binding */ DEFAULT_APP_CONFIG),
/* harmony export */   RESERVED_CONFIG_KEYS: () => (/* binding */ RESERVED_CONFIG_KEYS)
/* harmony export */ });
/**
 * App Configuration Types
 *
 * Defines the structure for app-wide configuration values accessible via Noodl.Config.
 * Config values are static and immutable at runtime.
 *
 * @module config/types
 */
/**
 * Default app configuration used when no config is defined.
 */
const DEFAULT_APP_CONFIG = {
    identity: {
        appName: 'My Noodl App',
        description: ''
    },
    seo: {},
    variables: []
};
/**
 * Reserved configuration keys that cannot be used for custom variables.
 * These are populated from identity, SEO, and PWA settings.
 */
const RESERVED_CONFIG_KEYS = [
    // Identity
    'appName',
    'description',
    'coverImage',
    // SEO
    'ogTitle',
    'ogDescription',
    'ogImage',
    'favicon',
    'themeColor',
    // PWA
    'pwaEnabled',
    'pwaShortName',
    'pwaDisplay',
    'pwaStartUrl',
    'pwaBackgroundColor'
];


/***/ }),

/***/ 54764:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var map = {
	"./align_item_center.svg": 87438,
	"./align_item_left.svg": 59474,
	"./align_item_right.svg": 12265,
	"./arrow_down.svg": 35203,
	"./arrow_left.svg": 46740,
	"./arrow_line_down.svg": 4480,
	"./arrow_line_left.svg": 79503,
	"./arrow_line_right.svg": 31722,
	"./arrow_line_up.svg": 28019,
	"./arrow_right.svg": 17947,
	"./arrow_up.svg": 85596,
	"./arrows_in_line_horizontal.svg": 49419,
	"./arrows_in_line_vertical.svg": 94705,
	"./border_all.svg": 23715,
	"./border_down.svg": 57286,
	"./border_left.svg": 40525,
	"./border_right.svg": 25840,
	"./border_up.svg": 72189,
	"./bug.svg": 49825,
	"./button.svg": 58237,
	"./cards.svg": 3386,
	"./caret_down.svg": 54773,
	"./caret_down_up.svg": 99503,
	"./caret_left.svg": 68334,
	"./caret_right.svg": 13837,
	"./caret_up.svg": 26170,
	"./chat.svg": 46299,
	"./chat_fill.svg": 74101,
	"./check.svg": 50731,
	"./checkbox.svg": 4346,
	"./checkbox_filled.svg": 58801,
	"./circle_dot.svg": 14061,
	"./circle_open.svg": 95184,
	"./close.svg": 2911,
	"./cloud_check.svg": 33705,
	"./cloud_data.svg": 49059,
	"./cloud_download.svg": 7615,
	"./cloud_function.svg": 63351,
	"./cloud_upload.svg": 37664,
	"./code.svg": 89674,
	"./collaboration.svg": 72400,
	"./columns.svg": 60886,
	"./component.svg": 60598,
	"./component_fill.svg": 35682,
	"./component_with_children.svg": 35381,
	"./components.svg": 70537,
	"./components_fill.svg": 25055,
	"./copy.svg": 75178,
	"./device_desktop.svg": 73010,
	"./device_laptop.svg": 63098,
	"./device_phone.svg": 2506,
	"./device_tablet.svg": 13614,
	"./dimension.svg": 66131,
	"./dimension_height.svg": 46715,
	"./dimension_width_height.svg": 14764,
	"./dimenstion_width.svg": 36224,
	"./dots_three.svg": 29940,
	"./dots_three_horizontal.svg": 93751,
	"./dropdown.svg": 46922,
	"./dropdown_lines.svg": 35658,
	"./external_link.svg": 90671,
	"./file.svg": 50603,
	"./file_fill.svg": 19781,
	"./file_filled.svg": 2258,
	"./folder_closed.svg": 89676,
	"./folder_open.svg": 68284,
	"./grip.svg": 88957,
	"./group.svg": 32226,
	"./home.svg": 90484,
	"./home_fill.svg": 76236,
	"./horizontal_split.svg": 112,
	"./icon.svg": 93130,
	"./image.svg": 42980,
	"./import_down.svg": 4205,
	"./import_left.svg": 26454,
	"./import_slanted.svg": 1644,
	"./justify_content_center.svg": 22391,
	"./justify_content_end.svg": 50243,
	"./justify_content_space_around.svg": 62230,
	"./justify_content_space_between.svg": 89147,
	"./justify_content_space_evenly.svg": 7412,
	"./justify_content_start.svg": 79480,
	"./link.svg": 42897,
	"./logo.svg": 77120,
	"./magic_wand.svg": 99003,
	"./minus.svg": 71279,
	"./navigate.svg": 72844,
	"./nested_component.svg": 21796,
	"./note_pencil.svg": 90175,
	"./page_input_arrow.svg": 84139,
	"./page_router.svg": 44736,
	"./palette.svg": 6386,
	"./palette_fill.svg": 58310,
	"./pause_circle.svg": 34276,
	"./pencil.svg": 24786,
	"./pencil_line.svg": 73979,
	"./play.svg": 7943,
	"./play_circle.svg": 6202,
	"./plus.svg": 67041,
	"./plus_circle.svg": 48968,
	"./plus_square.svg": 74897,
	"./question.svg": 5049,
	"./question_fill.svg": 78159,
	"./question_free.svg": 88382,
	"./radiobutton.svg": 79598,
	"./radiobutton_group.svg": 95162,
	"./radiobutton_group_line.svg": 86259,
	"./refresh.svg": 46526,
	"./reset.svg": 97546,
	"./rest_api.svg": 2730,
	"./rocket.svg": 13773,
	"./roll.svg": 73504,
	"./rounded_corner_all.svg": 14264,
	"./rounded_corner_left_down.svg": 95475,
	"./rounded_corner_left_up.svg": 22060,
	"./rounded_corner_right_down.svg": 30278,
	"./rounded_corner_right_up.svg": 60701,
	"./search.svg": 52285,
	"./search_corner.svg": 82263,
	"./search_grid.svg": 72864,
	"./search_square.svg": 16125,
	"./seo.svg": 51124,
	"./setting.svg": 81519,
	"./setting_fill.svg": 60529,
	"./sliders.svg": 86541,
	"./sliders_filled.svg": 39704,
	"./sliders_horizontal.svg": 66432,
	"./square.svg": 57768,
	"./square_filled.svg": 98867,
	"./square_half.svg": 55444,
	"./star.svg": 10785,
	"./stash.svg": 45288,
	"./structure_circle.svg": 74991,
	"./text_align_center.svg": 62306,
	"./text_align_left.svg": 64054,
	"./text_align_right.svg": 94389,
	"./text_in_box.svg": 50084,
	"./text_input.svg": 43337,
	"./trash.svg": 33609,
	"./ui.svg": 23983,
	"./user.svg": 84364,
	"./vertical_split.svg": 16806,
	"./video.svg": 1950,
	"./viewport_diagonal_arrow.svg": 21877,
	"./viewport_horizontal_arrow.svg": 18772,
	"./viewport_vertical_arrow.svg": 10774,
	"./warning_circle.svg": 64486,
	"./warning_circle_filled.svg": 20677,
	"./warning_triangle.svg": 50870
};


function webpackContext(req) {
	var id = webpackContextResolve(req);
	return __webpack_require__(id);
}
function webpackContextResolve(req) {
	if(!__webpack_require__.o(map, req)) {
		var e = new Error("Cannot find module '" + req + "'");
		e.code = 'MODULE_NOT_FOUND';
		throw e;
	}
	return map[req];
}
webpackContext.keys = function webpackContextKeys() {
	return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
module.exports = webpackContext;
webpackContext.id = 54764;

/***/ }),

/***/ 54773:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCaretDown = function SvgCaretDown(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M11.6061 15.0981C11.899 15.391 12.3738 15.391 12.6667 15.0981L17.0126 10.7523C17.3055 10.4594 17.3055 9.9845 17.0126 9.6916C16.7197 9.39871 16.2448 9.39871 15.9519 9.6916L12.1364 13.5071L8.32086 9.6916C8.02796 9.39871 7.55309 9.39871 7.2602 9.6916C6.9673 9.9845 6.9673 10.4594 7.2602 10.7523L11.6061 15.0981Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCaretDown);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "208f9abd6dd7806ead2b1caca3b06bc7.svg");

/***/ }),

/***/ 54953:
/***/ ((module) => {

"use strict";
module.exports = require("react");

/***/ }),

/***/ 55155:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.NewsModal-module__Background--hKtC2,.NewsModal-module__Root--qvFBF{background-color:var(--theme-color-secondary-bright)}.NewsModal-module__Root--qvFBF{width:480px}.NewsModal-module__Root--qvFBF h2,.NewsModal-module__Root--qvFBF h3,.NewsModal-module__Root--qvFBF p,.NewsModal-module__Root--qvFBF li{color:var(--theme-color-on-secondary)}.NewsModal-module__Root--qvFBF h2,.NewsModal-module__Root--qvFBF h3,.NewsModal-module__Root--qvFBF p,.NewsModal-module__Root--qvFBF ul{padding-left:24px;padding-right:24px}.NewsModal-module__Root--qvFBF img{margin-right:-24px;margin-left:-24px;width:calc(100% + 48px);max-width:none}.NewsModal-module__Root--qvFBF h2{margin-top:0}.NewsModal-module__Root--qvFBF p:first-child{margin-top:0}.NewsModal-module__Inner--Sml3o{padding:8px;padding-right:2px;max-height:calc(90vh - 40px);overflow-y:overlay;z-index:0}.NewsModal-module__Nav--BkkyF{display:flex;justify-content:flex-end;padding:24px}.NewsModal-module__Button--a6cto{min-width:128px}.NewsModal-module__Header--d7kif{background-color:var(--theme-color-secondary-highlight)}.NewsModal-module__Header--d7kif p{padding:8px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/NewsModal/NewsModal.module.scss"],"names":[],"mappings":"AAEA,oEAEE,oDAAA,CAGF,+BACE,WAAA,CAEA,uIAIE,qCAAA,CAGF,uIAIE,iBArBe,CAsBf,kBAtBe,CAyBjB,mCACE,kBAAA,CACA,iBAAA,CACA,uBAAA,CACA,cAAA,CAGF,kCACE,YAAA,CAGF,6CACE,YAAA,CAIJ,gCACE,WAAA,CACA,iBAAA,CACA,4BAAA,CACA,kBAAA,CACA,SAAA,CAGF,8BACE,YAAA,CACA,wBAAA,CACA,YApDiB,CAuDnB,iCACE,eAAA,CAGF,iCACE,uDAAA,CAEA,mCACE,WAAA","sourcesContent":["$_content-padding: 24px;\n\n.Background,\n.Root {\n  background-color: var(--theme-color-secondary-bright);\n}\n\n.Root {\n  width: 480px;\n\n  h2,\n  h3,\n  p,\n  li {\n    color: var(--theme-color-on-secondary);\n  }\n\n  h2,\n  h3,\n  p,\n  ul {\n    padding-left: $_content-padding;\n    padding-right: $_content-padding;\n  }\n\n  img {\n    margin-right: -$_content-padding;\n    margin-left: -$_content-padding;\n    width: calc(100% + calc($_content-padding * 2));\n    max-width: none;\n  }\n\n  h2 {\n    margin-top: 0;\n  }\n\n  p:first-child {\n    margin-top: 0;\n  }\n}\n\n.Inner {\n  padding: 8px;\n  padding-right: 2px;\n  max-height: calc(90vh - 40px);\n  overflow-y: overlay;\n  z-index: 0;\n}\n\n.Nav {\n  display: flex;\n  justify-content: flex-end;\n  padding: $_content-padding;\n}\n\n.Button {\n  min-width: 128px;\n}\n\n.Header {\n  background-color: var(--theme-color-secondary-highlight);\n\n  p {\n    padding: 8px;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Background": `NewsModal-module__Background--hKtC2`,
	"Root": `NewsModal-module__Root--qvFBF`,
	"Inner": `NewsModal-module__Inner--Sml3o`,
	"Nav": `NewsModal-module__Nav--BkkyF`,
	"Button": `NewsModal-module__Button--a6cto`,
	"Header": `NewsModal-module__Header--d7kif`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 55231:
/***/ ((module) => {

"use strict";
module.exports = require("rimraf");

/***/ }),

/***/ 55274:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/*
	Keeping name short for faster parsing.
	cdr = core decorations rendering (div)
*/
.monaco-editor .lines-content .cdr {
	position: absolute;
}`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/decorations/decorations.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;;;CAGC;AACD;CACC,kBAAkB;AACnB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/*\n\tKeeping name short for faster parsing.\n\tcdr = core decorations rendering (div)\n*/\n.monaco-editor .lines-content .cdr {\n\tposition: absolute;\n}"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 55444:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSquareHalf = function SvgSquareHalf(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M19.232 3.32147L4.76772 3.32147C4.3841 3.32147 4.0162 3.47386 3.74494 3.74512C3.47368 4.01638 3.32129 4.38428 3.32129 4.7679L3.32129 19.2322C3.32129 19.6158 3.47368 19.9837 3.74494 20.255C4.0162 20.5262 4.3841 20.6786 4.76772 20.6786L19.232 20.6786C19.6156 20.6786 19.9835 20.5262 20.2548 20.255C20.526 19.9837 20.6784 19.6158 20.6784 19.2322L20.6784 4.7679C20.6784 4.38428 20.526 4.01638 20.2548 3.74512C19.9835 3.47386 19.6156 3.32147 19.232 3.32147ZM11.9999 12L4.76772 19.2322L4.76772 4.7679L19.232 4.7679L11.9999 12Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSquareHalf);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "e7d774cf4facd02c9fc751eeeb98f958.svg");

/***/ }),

/***/ 55506:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  $: () => (/* reexport */ PropertyPanelTextInput)
});

// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelBaseInput/index.ts + 2 modules
var PropertyPanelBaseInput = __webpack_require__(98690);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelTextInput/PropertyPanelTextInput.tsx


function PropertyPanelTextInput({ value, isChanged, isConnected, onChange }) {
    const [displayedInputValue, setDisplayedInputValue] = (0,external_react_.useState)(value);
    function handleUpdate(inputValue) {
        onChange && onChange(inputValue);
        setDisplayedInputValue(inputValue);
    }
    (0,external_react_.useEffect)(() => {
        handleUpdate(value);
    }, [value]);
    return (external_react_default().createElement(PropertyPanelBaseInput/* PropertyPanelBaseInput */.Z, { value: displayedInputValue, type: "text", isChanged: isChanged, isConnected: isConnected, onChange: (value) => setDisplayedInputValue(String(value)), onBlur: (e) => handleUpdate(displayedInputValue), onKeyDown: (e) => e.key === 'Enter' && handleUpdate(displayedInputValue) }));
}

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelTextInput/index.ts



/***/ }),

/***/ 55654:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   $S: () => (/* binding */ popStashEntry),
/* harmony export */   At: () => (/* binding */ getStashes),
/* harmony export */   DE: () => (/* binding */ dropStashEntry),
/* harmony export */   OT: () => (/* binding */ createStashEntry),
/* harmony export */   yT: () => (/* binding */ popStashEntryToBranch)
/* harmony export */ });
/* unused harmony export getLastStashEntryForBranch */
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81882);
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(dugite__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(85869);
/* harmony import */ var _git_error__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(55952);
/* harmony import */ var _models_snapshot__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(60629);
/* harmony import */ var _models_commit_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(80760);
/* harmony import */ var _actions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(11058);






/**
 * RegEx for determining if a stash entry is created by Desktop
 *
 * This is done by looking for a magic string with the following
 * formats:
 * `On branchname: some message`
 * `WIP on branchname: some message` (git default when message is omitted)
 */
const desktopStashEntryMessageRe = /on (.+):/i;
/**
 * Get the list of stash entries created by Desktop in the current repository
 * using the default ordering of refs (which is LIFO ordering),
 * as well as the total amount of stash entries.
 */
async function getStashes(repositoryDir) {
    const delimiter = "1F";
    const delimiterString = String.fromCharCode(parseInt(delimiter, 16));
    const format = ["%gD", "%H", "%gs", "%an <%ae> %at +0000"].join(`%x${delimiter}`);
    const result = await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(["log", "-g", "-z", `--pretty=${format}`, "refs/stash"], repositoryDir, "getStashEntries", {
        successExitCodes: new Set([0, 128]),
    });
    // There's no refs/stashes reflog in the repository or it's not
    // even a repository. In either case we don't care
    if (result.exitCode === 128) {
        return { entries: [], stashEntryCount: 0 };
    }
    const desktopStashEntries = [];
    const files = {
        kind: _models_snapshot__WEBPACK_IMPORTED_MODULE_3__/* .StashedChangesLoadStates */ .qj.NotLoaded,
    };
    const entries = result.output
        .toString()
        .split("\0")
        .filter((s) => s !== "");
    for (const entry of entries) {
        const pieces = entry.split(delimiterString);
        if (pieces.length === 4) {
            const [name, stashSha, message, identity] = pieces;
            const branchName = extractBranchFromMessage(message);
            // Example: 'On main: !!Noodl<main>'
            const marker = message.split(":")[1].trim();
            if (branchName !== null) {
                desktopStashEntries.push(new _models_snapshot__WEBPACK_IMPORTED_MODULE_3__/* .Stash */ .el(repositoryDir, name, branchName, stashSha, marker, _models_commit_identity__WEBPACK_IMPORTED_MODULE_4__/* .CommitIdentity */ .S.parseIdentity(identity), files));
            }
        }
    }
    return {
        entries: desktopStashEntries,
        stashEntryCount: entries.length - 1,
    };
}
/**
 * Returns the last Desktop created stash entry for the given branch
 */
async function getLastStashEntryForBranch(repositoryDir, branch) {
    const stash = await getStashes(repositoryDir);
    const branchName = typeof branch === "string" ? branch : branch.name;
    // Since stash objects are returned in a LIFO manner, the first
    // entry found is guaranteed to be the last entry created
    return stash.entries.find((stash) => stash.branchName === branchName) || null;
}
/**
 * Stash the working directory changes for the current branch
 */
async function createStashEntry(repositoryDir, message) {
    const args = ["stash", "push", "-u", "-m", message];
    const result = await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(args, repositoryDir, "createStashEntry", {
        successExitCodes: new Set([0, 1]),
    });
    if (result.exitCode === 1) {
        // search for any line starting with `error:` -  /m here to ensure this is
        // applied to each line, without needing to split the text
        const errorPrefixRe = /^error: /m;
        const matches = errorPrefixRe.exec(result.error.toString());
        if (matches !== null && matches.length > 0) {
            // rethrow, because these messages should prevent the stash from being created
            throw new _git_error__WEBPACK_IMPORTED_MODULE_2__/* .GitError */ .XS(result, args);
        }
        // if no error messages were emitted by Git, we should log but continue because
        // a valid stash was created and this should not interfere with the checkout
        console.info(`[createStashEntry] a stash was created successfully but exit code ${result.exitCode} reported. stderr: ${result.error.toString()}`);
    }
    const response = result.output.toString();
    // Stash doesn't consider it an error that there aren't any local changes to save.
    if (response === "No local changes to save\n") {
        throw new _actions__WEBPACK_IMPORTED_MODULE_5__/* .GitActionError */ .v7(_actions__WEBPACK_IMPORTED_MODULE_5__/* .GitActionErrorCode */ .I7.StashNoLocalChanges);
    }
    // Fetch all the stashes and return the one we just created.
    const stashes = await getStashes(repositoryDir);
    return stashes.entries.find((x) => x.message === message);
}
/**
 * Removes the given stash entry if it exists
 *
 * @param marker
 */
async function dropStashEntry(repositoryDir, marker) {
    if (marker !== null) {
        const args = ["stash", "drop", marker];
        await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(args, repositoryDir, "dropStashEntry");
    }
}
/**
 * Pops the stash entry identified by matching `stashSha` to its commit hash.
 *
 * To see the commit hash of stash entry, run
 * `git log -g refs/stash --pretty="%nentry: %gd%nsubject: %gs%nhash: %H%n"`
 * in a repo with some stash entries.
 */
async function popStashEntry(repositoryDir, marker) {
    // ignoring these git errors for now, this will change when we start
    // implementing the stash conflict flow
    const expectedErrors = new Set([dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.MergeConflicts]);
    const successExitCodes = new Set([0, 1]);
    if (marker === null) {
        return;
    }
    const args = ["stash", "pop", "--quiet", `${marker}`];
    const result = await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(args, repositoryDir, "popStashEntry", {
        expectedErrors,
        successExitCodes,
        spawn: false,
    });
    // popping a stashes that create conflicts in the working directory
    // report an exit code of `1` and are not dropped after being applied.
    // so, we check for this case and drop them manually
    if (result.exitCode === 1) {
        if (result.error.toString().length > 0) {
            // rethrow, because anything in stderr should prevent the stash from being popped
            throw new _git_error__WEBPACK_IMPORTED_MODULE_2__/* .GitError */ .XS(result, args);
        }
        console.info(`[popStashEntry] a stash was popped successfully but exit code ${result.exitCode} reported.`);
        // bye bye
        await dropStashEntry(repositoryDir, marker);
    }
}
async function popStashEntryToBranch(repositoryDir, marker, branchName) {
    // ignoring these git errors for now, this will change when we start
    // implementing the stash conflict flow
    const expectedErrors = new Set([dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.MergeConflicts]);
    const successExitCodes = new Set([0, 1]);
    const args = ["stash", "branch", branchName, `${marker}`];
    const result = await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(args, repositoryDir, "popStashEntryToBranch", {
        expectedErrors,
        successExitCodes,
        spawn: false,
    });
    if (result.exitCode === 1) {
        throw new _git_error__WEBPACK_IMPORTED_MODULE_2__/* .GitError */ .XS(result, args);
    }
}
function extractBranchFromMessage(message) {
    const match = desktopStashEntryMessageRe.exec(message);
    return match === null || match[1].length === 0 ? null : match[1];
}


/***/ }),

/***/ 55655:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  In: () => (/* reexport */ Icon),
  $M: () => (/* reexport */ IconName),
  lK: () => (/* reexport */ IconSize)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/common/Icon/Icon.module.scss
var Icon_module = __webpack_require__(79872);
;// ../noodl-core-ui/src/components/common/Icon/Icon.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(Icon_module/* default */.A, options);




       /* harmony default export */ const Icon_Icon_module = (Icon_module/* default */.A && Icon_module/* default */.A.locals ? Icon_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/common/Icon/Icon.tsx



var IconName;
(function (IconName) {
    IconName["AlignItemCenter"] = "align_item_center";
    IconName["AlignItemLeft"] = "align_item_left";
    IconName["AlignItemRight"] = "align_item_right";
    IconName["ArrowDown"] = "arrow_down";
    IconName["ArrowLeft"] = "arrow_left";
    IconName["ArrowLineDown"] = "arrow_line_down";
    IconName["ArrowLineLeft"] = "arrow_line_left";
    IconName["ArrowLineRight"] = "arrow_line_right";
    IconName["ArrowLineUp"] = "arrow_line_up";
    IconName["ArrowRight"] = "arrow_right";
    IconName["ArrowUp"] = "arrow_up";
    IconName["ArrowsInLineHorizontal"] = "arrows_in_line_horizontal";
    IconName["ArrowsInLineVertical"] = "arrows_in_line_vertical";
    IconName["BorderAll"] = "border_all";
    IconName["BorderDown"] = "border_down";
    IconName["BorderLeft"] = "border_left";
    IconName["BorderRight"] = "border_right";
    IconName["BorderUp"] = "border_up";
    IconName["Bug"] = "bug";
    IconName["Cards"] = "cards";
    IconName["CaretUp"] = "caret_up";
    IconName["CaretDown"] = "caret_down";
    IconName["CaretDownUp"] = "caret_down_up";
    IconName["CaretLeft"] = "caret_left";
    IconName["CaretRight"] = "caret_right";
    IconName["Chat"] = "chat";
    IconName["ChatFill"] = "chat_fill";
    IconName["Check"] = "check";
    IconName["Close"] = "close";
    IconName["CloudCheck"] = "cloud_check";
    IconName["CloudData"] = "cloud_data";
    IconName["CloudDownload"] = "cloud_download";
    IconName["CloudUpload"] = "cloud_upload";
    IconName["CloudFunction"] = "cloud_function";
    IconName["Collaboration"] = "collaboration";
    IconName["Code"] = "code";
    IconName["Component"] = "component";
    IconName["ComponentWithChildren"] = "component_with_children";
    IconName["Components"] = "components";
    IconName["ComponentsFill"] = "components_fill";
    IconName["Copy"] = "copy";
    IconName["Columns"] = "columns";
    IconName["DeviceDesktop"] = "device_desktop";
    IconName["DeviceLaptop"] = "device_laptop";
    IconName["DevicePhone"] = "device_phone";
    IconName["DeviceTablet"] = "device_tablet";
    IconName["Dimension"] = "dimension";
    IconName["DimensionHeight"] = "dimension_height";
    IconName["DimensionWidthHeight"] = "dimension_width_height";
    IconName["DimenstionWidth"] = "dimenstion_width";
    IconName["DotsThree"] = "dots_three";
    IconName["DotsThreeHorizontal"] = "dots_three_horizontal";
    IconName["ExternalLink"] = "external_link";
    IconName["File"] = "file";
    IconName["FileFill"] = "file_fill";
    IconName["FolderOpen"] = "folder_open";
    IconName["FolderClosed"] = "folder_closed";
    IconName["Home"] = "home";
    IconName["HomeFill"] = "home_fill";
    IconName["HorizontalSplit"] = "horizontal_split";
    IconName["JustifyContentCenter"] = "justify_content_center";
    IconName["JustifyContentEnd"] = "justify_content_end";
    IconName["JustifyContentSpaceAround"] = "justify_content_space_around";
    IconName["JustifyContentSpaceBetween"] = "justify_content_space_between";
    IconName["JustifyContentSpaceEvenly"] = "justify_content_space_evenly";
    IconName["JustifyContentStart"] = "justify_content_start";
    IconName["Logo"] = "logo";
    IconName["MagicWand"] = "magic_wand";
    IconName["Minus"] = "minus";
    IconName["NestedComponent"] = "nested_component";
    IconName["NotePencil"] = "note_pencil";
    IconName["Palette"] = "palette";
    IconName["PaletteFill"] = "palette_fill";
    IconName["PauseCircle"] = "pause_circle";
    IconName["Pencil"] = "pencil";
    IconName["PencilLine"] = "pencil_line";
    IconName["Play"] = "play";
    IconName["PlayCircle"] = "play_circle";
    IconName["Plus"] = "plus";
    IconName["PlusSquare"] = "plus_square";
    IconName["PlusCircle"] = "plus_circle";
    IconName["Question"] = "question";
    IconName["QuestionFill"] = "question_fill";
    IconName["QuestionFree"] = "question_free";
    IconName["Refresh"] = "refresh";
    IconName["Reset"] = "reset";
    IconName["RestApi"] = "rest_api";
    IconName["Rocket"] = "rocket";
    IconName["Roll"] = "roll";
    IconName["RoundedCornerAll"] = "rounded_corner_all";
    IconName["RoundedCornerLeftDown"] = "rounded_corner_left_down";
    IconName["RoundedCornerLeftUp"] = "rounded_corner_left_up";
    IconName["RoundedCornerRightDown"] = "rounded_corner_right_down";
    IconName["RoundedCornerRightUp"] = "rounded_corner_right_up";
    IconName["Search"] = "search";
    IconName["SearchCorner"] = "search_corner";
    IconName["SearchGrid"] = "search_grid";
    IconName["SearchSquare"] = "search_square";
    IconName["Setting"] = "setting";
    IconName["SettingFill"] = "setting_fill";
    IconName["Sliders"] = "sliders";
    IconName["SlidersHorizontal"] = "sliders_horizontal";
    IconName["Stash"] = "stash";
    IconName["StructureCircle"] = "structure_circle";
    IconName["Square"] = "square";
    IconName["SquareFilled"] = "square_filled";
    IconName["SquareHalf"] = "square_half";
    IconName["TextAlignCenter"] = "text_align_center";
    IconName["TextAlignLeft"] = "text_align_left";
    IconName["TextAlignRight"] = "text_align_right";
    IconName["Trash"] = "trash";
    IconName["User"] = "user";
    IconName["UI"] = "ui";
    IconName["VerticalSplit"] = "vertical_split";
    IconName["ViewportDiagonalArrow"] = "viewport_diagonal_arrow";
    IconName["ViewportHorizontalArrow"] = "viewport_horizontal_arrow";
    IconName["ViewportVerticalArrow"] = "viewport_vertical_arrow";
    IconName["WarningCircle"] = "warning_circle";
    IconName["WarningCircleFilled"] = "warning_circle_filled";
    IconName["WarningTriangle"] = "warning_triangle";
    IconName["ImportDown"] = "import_down";
    IconName["ImportLeft"] = "import_left";
    IconName["ImportSlanted"] = "import_slanted";
    IconName["Grip"] = "grip";
    IconName["Group"] = "group";
    IconName["TextInBox"] = "text_in_box";
    IconName["Image"] = "image";
    IconName["Video"] = "video";
    IconName["CircleOpen"] = "circle_open";
    IconName["CircleDot"] = "circle_dot";
    IconName["Star"] = "star";
    IconName["Button"] = "button";
    IconName["Checkbox"] = "checkbox";
    IconName["CheckboxFilled"] = "checkbox_filled";
    IconName["Icon"] = "icon";
    IconName["Dropdown"] = "dropdown";
    IconName["DropdownLines"] = "dropdown_lines";
    IconName["TextInput"] = "text_input";
    IconName["PageRouter"] = "page_router";
    IconName["PageInputArrow"] = "page_input_arrow";
    IconName["Radiobutton"] = "radiobutton";
    IconName["RadiobuttonGroupLine"] = "radiobutton_group_line";
    IconName["RadiobuttonGroup"] = "radiobutton_group";
    IconName["SlidersFilled"] = "sliders_filled";
    IconName["Navigate"] = "navigate";
    IconName["Link"] = "link";
    IconName["SEO"] = "seo";
})(IconName || (IconName = {}));
var IconSize;
(function (IconSize) {
    IconSize["Default"] = "is-size-default";
    IconSize["Large"] = "is-size-large";
    IconSize["Small"] = "is-size-small";
    IconSize["Tiny"] = "is-size-tiny";
})(IconSize || (IconSize = {}));
/** Require all SVGs in folder so that we dont have to type them in manually */
const reqSvgs = __webpack_require__(54764);
/** Create object from all required SVGs so that we can access them */
const _IconObject = reqSvgs.keys().reduce((images, path) => {
    const key = path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
    images[key] = reqSvgs(path);
    return images;
}, {});
function Icon({ icon = IconName.BorderAll, size = IconSize.Default, variant, UNSAFE_className, UNSAFE_style }) {
    const [svg, setSvg] = (0,external_react_.useState)(null);
    (0,external_react_.useEffect)(() => {
        if (typeof _IconObject[icon] === 'object') {
            setSvg(_IconObject[icon].ReactComponent);
        }
        else {
            fetch(_IconObject[icon])
                .then((res) => res.text())
                .then(setSvg);
        }
    }, [icon]);
    if (typeof svg === 'string') {
        return (external_react_default().createElement("span", { className: external_classnames_default()(Icon_Icon_module['Root'], Icon_Icon_module[size], variant && Icon_Icon_module[`is-variant-${variant}`], UNSAFE_className), style: UNSAFE_style, dangerouslySetInnerHTML: { __html: svg } }));
    }
    else {
        const SvgTag = svg;
        return (external_react_default().createElement("span", { className: external_classnames_default()(Icon_Icon_module['Root'], Icon_Icon_module[size], variant && Icon_Icon_module[`is-variant-${variant}`], UNSAFE_className), style: UNSAFE_style }, SvgTag && external_react_default().createElement(SvgTag, null)));
    }
}

;// ../noodl-core-ui/src/components/common/Icon/index.ts



/***/ }),

/***/ 55836:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.LocalBackendCard-module__Root--g2EPA{background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:6px;padding:12px;margin-bottom:8px;transition:border-color .2s ease}.LocalBackendCard-module__Root--g2EPA:hover{border-color:var(--theme-color-border-hover)}.LocalBackendCard-module__Header--YNohJ{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:8px}.LocalBackendCard-module__TypeIcon--S84CH{width:32px;height:32px;border-radius:6px;background-color:var(--theme-color-success);display:flex;align-items:center;justify-content:center;flex-shrink:0}.LocalBackendCard-module__StatusBadge--j7Ea_{display:flex;align-items:center;padding:2px 6px;border-radius:4px;background-color:var(--theme-color-bg-2)}.LocalBackendCard-module__Endpoint--QcCdi{display:flex;align-items:center;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:4px;padding:6px 8px;margin-bottom:8px;cursor:pointer;transition:background-color .15s ease}.LocalBackendCard-module__Endpoint--QcCdi:hover{background-color:var(--theme-color-bg-1)}.LocalBackendCard-module__Info--W0JyT{margin-bottom:8px;padding-top:8px;border-top:1px solid var(--theme-color-border-default)}.LocalBackendCard-module__Actions--Y6avT{padding-top:8px;border-top:1px solid var(--theme-color-border-default)}.LocalBackendCard-module__SchemaPanelOverlay--WL0J6{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,.85);display:flex;align-items:center;justify-content:center;z-index:9999;padding:40px}.LocalBackendCard-module__SchemaPanelOverlay--WL0J6>div{width:100%;max-width:900px;max-height:calc(100vh - 80px);overflow:auto;background-color:var(--theme-color-bg-2);border-radius:8px;border:1px solid var(--theme-color-border-default);box-shadow:0 20px 60px rgba(0,0,0,.5)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/BackendServicesPanel/LocalBackendCard/LocalBackendCard.module.scss"],"names":[],"mappings":"AAAA,sCACE,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,YAAA,CACA,iBAAA,CACA,gCAAA,CAEA,4CACE,4CAAA,CAIJ,wCACE,YAAA,CACA,6BAAA,CACA,sBAAA,CACA,iBAAA,CAGF,0CACE,UAAA,CACA,WAAA,CACA,iBAAA,CACA,2CAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,aAAA,CAGF,6CACE,YAAA,CACA,kBAAA,CACA,eAAA,CACA,iBAAA,CACA,wCAAA,CAGF,0CACE,YAAA,CACA,kBAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,eAAA,CACA,iBAAA,CACA,cAAA,CACA,qCAAA,CAEA,gDACE,wCAAA,CAIJ,sCACE,iBAAA,CACA,eAAA,CACA,sDAAA,CAGF,yCACE,eAAA,CACA,sDAAA,CAGF,oDACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,gCAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,YAAA,CACA,YAAA,CAEA,wDACE,UAAA,CACA,eAAA,CACA,6BAAA,CACA,aAAA,CACA,wCAAA,CACA,iBAAA,CACA,kDAAA,CACA,qCAAA","sourcesContent":[".Root {\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 6px;\n  padding: 12px;\n  margin-bottom: 8px;\n  transition: border-color 0.2s ease;\n\n  &:hover {\n    border-color: var(--theme-color-border-hover);\n  }\n}\n\n.Header {\n  display: flex;\n  justify-content: space-between;\n  align-items: flex-start;\n  margin-bottom: 8px;\n}\n\n.TypeIcon {\n  width: 32px;\n  height: 32px;\n  border-radius: 6px;\n  background-color: var(--theme-color-success);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  flex-shrink: 0;\n}\n\n.StatusBadge {\n  display: flex;\n  align-items: center;\n  padding: 2px 6px;\n  border-radius: 4px;\n  background-color: var(--theme-color-bg-2);\n}\n\n.Endpoint {\n  display: flex;\n  align-items: center;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  padding: 6px 8px;\n  margin-bottom: 8px;\n  cursor: pointer;\n  transition: background-color 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-1);\n  }\n}\n\n.Info {\n  margin-bottom: 8px;\n  padding-top: 8px;\n  border-top: 1px solid var(--theme-color-border-default);\n}\n\n.Actions {\n  padding-top: 8px;\n  border-top: 1px solid var(--theme-color-border-default);\n}\n\n.SchemaPanelOverlay {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.85);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 9999;\n  padding: 40px;\n\n  > div {\n    width: 100%;\n    max-width: 900px;\n    max-height: calc(100vh - 80px);\n    overflow: auto;\n    background-color: var(--theme-color-bg-2);\n    border-radius: 8px;\n    border: 1px solid var(--theme-color-border-default);\n    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `LocalBackendCard-module__Root--g2EPA`,
	"Header": `LocalBackendCard-module__Header--YNohJ`,
	"TypeIcon": `LocalBackendCard-module__TypeIcon--S84CH`,
	"StatusBadge": `LocalBackendCard-module__StatusBadge--j7Ea_`,
	"Endpoint": `LocalBackendCard-module__Endpoint--QcCdi`,
	"Info": `LocalBackendCard-module__Info--W0JyT`,
	"Actions": `LocalBackendCard-module__Actions--Y6avT`,
	"SchemaPanelOverlay": `LocalBackendCard-module__SchemaPanelOverlay--WL0J6`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 55861:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   I7: () => (/* binding */ GitActionErrorCode),
/* harmony export */   gR: () => (/* binding */ createErrorFromMessage),
/* harmony export */   v7: () => (/* binding */ GitActionError)
/* harmony export */ });
var GitActionErrorCode;
(function (GitActionErrorCode) {
    GitActionErrorCode[GitActionErrorCode["LocalRepository"] = 0] = "LocalRepository";
    GitActionErrorCode[GitActionErrorCode["InvalidBranchName"] = 1] = "InvalidBranchName";
    GitActionErrorCode[GitActionErrorCode["BranchNotExisting"] = 2] = "BranchNotExisting";
    GitActionErrorCode[GitActionErrorCode["StashNoLocalChanges"] = 3] = "StashNoLocalChanges";
    GitActionErrorCode[GitActionErrorCode["AuthorizationFailed"] = 4] = "AuthorizationFailed";
})(GitActionErrorCode || (GitActionErrorCode = {}));
/**
 * GitActionError will be thrown from the action functions,
 * which are designed to be a higher level of interaction
 * with git than the other functions.
 */
class GitActionError extends Error {
    constructor(code) {
        super(getMessage(code));
        this.code = code;
    }
}
function getMessage(code) {
    switch (code) {
        case GitActionErrorCode.LocalRepository:
            return 'Repository is not published.';
        case GitActionErrorCode.InvalidBranchName:
            return 'Branch name contains invalid characters.';
        case GitActionErrorCode.BranchNotExisting:
            return 'Branch does not exist.';
        case GitActionErrorCode.StashNoLocalChanges:
            return 'No local changes to save.';
        case GitActionErrorCode.AuthorizationFailed:
            return 'Authorization failed.';
        default:
            return String(code);
    }
}
function createErrorFromMessage(message) {
    if (message.includes('Authentication failed')) {
        return new GitActionError(GitActionErrorCode.AuthorizationFailed);
    }
    else {
        return new Error(message);
    }
}


/***/ }),

/***/ 55952:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Bi: () => (/* binding */ parseCommitSHA),
/* harmony export */   QT: () => (/* binding */ getDescriptionForError),
/* harmony export */   XS: () => (/* binding */ GitError)
/* harmony export */ });
/* unused harmony export isAuthFailureError */
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81882);
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(dugite__WEBPACK_IMPORTED_MODULE_0__);

/**
 * Returns the SHA of the passed in IGitResult
 *
 * Git commit output format:
 * - Normal: "[main abc1234] Commit message"
 * - Root commit: "[main (root-commit) abc1234] Commit message"
 */
function parseCommitSHA(result) {
    const output = result.output.toString();
    const bracketContent = output.split(']')[0]; // "[main abc1234" or "[main (root-commit) abc1234"
    const parts = bracketContent.split(' ');
    // For root commit, the SHA is the last part before the closing bracket
    // For normal commit, it's the second part
    // Skip "(root-commit)" if present and get the actual SHA
    for (let i = parts.length - 1; i >= 0; i--) {
        const part = parts[i];
        // SHA is a hex string, not "(root-commit)" or branch name
        if (part && !part.startsWith('(') && !part.startsWith('[') && /^[a-f0-9]+$/.test(part)) {
            return part;
        }
    }
    // Fallback to original behavior
    return parts[1];
}
class GitError extends Error {
    constructor(result, args) {
        let rawMessage = true;
        let message;
        if (result.gitErrorDescription) {
            message = result.gitErrorDescription;
            rawMessage = false;
        }
        else if (result.error.length) {
            message = result.error.toString();
        }
        else if (result.output.length) {
            message = result.error.toString();
        }
        else {
            message = 'Unknown error';
            rawMessage = false;
        }
        super(message);
        this.name = 'GitError';
        this.result = result;
        this.args = args;
        this.isRawMessage = rawMessage;
    }
}
/**
 * Determine whether the provided `error` is an authentication failure
 * as per our definition. Note that this is not an exhaustive list of
 * authentication failures, only a collection of errors that we treat
 * equally in terms of error message and presentation to the user.
 */
function isAuthFailureError(error) {
    switch (error) {
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.SSHAuthenticationFailed:
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.SSHPermissionDenied:
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.HTTPSAuthenticationFailed:
            return true;
    }
    return false;
}
function getDescriptionForError(error) {
    if (isAuthFailureError(error)) {
        return `Authentication failed. Some common reasons include:
  
  - You are not logged in to your account
  - You may need to log out and log back in to refresh your token.
  - You do not have permission to access this repository.
  - The repository is archived on GitHub. Check the repository settings to confirm you are still permitted to push commits.
  - If you use SSH authentication, check that your key is added to the ssh-agent and associated with your account.
  - If you use SSH authentication, ensure the host key verification passes for your repository hosting service.
  - If you used username / password authentication, you might need to use a Personal Access Token instead of your account password. Check the documentation of your repository hosting service.`;
    }
    switch (error) {
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.SSHKeyAuditUnverified:
            return 'The SSH key is unverified.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.RemoteDisconnection:
            return 'The remote disconnected. Check your Internet connection and try again.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.HostDown:
            return 'The host is down. Check your Internet connection and try again.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.RebaseConflicts:
            return 'We found some conflicts while trying to rebase. Please resolve the conflicts before continuing.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.MergeConflicts:
            return 'We found some conflicts while trying to merge. Please resolve the conflicts and commit the changes.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.HTTPSRepositoryNotFound:
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.SSHRepositoryNotFound:
            return 'The repository does not seem to exist anymore. You may not have access, or it may have been deleted or renamed.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.PushNotFastForward:
            return 'The repository has been updated since you last pulled. Try pulling before pushing.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.BranchDeletionFailed:
            return 'Could not delete the branch. It was probably already deleted.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.DefaultBranchDeletionFailed:
            return `The branch is the repository's default branch and cannot be deleted.`;
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.RevertConflicts:
            return 'To finish reverting, please merge and commit the changes.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.EmptyRebasePatch:
            return 'There aren’t any changes left to apply.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.NoMatchingRemoteBranch:
            return 'There aren’t any remote branches that match the current branch.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.NothingToCommit:
            return 'There are no changes to commit.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.NoSubmoduleMapping:
            return 'A submodule was removed from .gitmodules, but the folder still exists in the repository. Delete the folder, commit the change, then try again.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.SubmoduleRepositoryDoesNotExist:
            return 'A submodule points to a location which does not exist.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.InvalidSubmoduleSHA:
            return 'A submodule points to a commit which does not exist.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.LocalPermissionDenied:
            return 'Permission denied.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.InvalidMerge:
            return 'This is not something we can merge.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.InvalidRebase:
            return 'This is not something we can rebase.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.NonFastForwardMergeIntoEmptyHead:
            return 'The merge you attempted is not a fast-forward, so it cannot be performed on an empty branch.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.PatchDoesNotApply:
            return 'The requested changes conflict with one or more files in the repository.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.BranchAlreadyExists:
            return 'A branch with that name already exists.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.BadRevision:
            return 'Bad revision.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.NotAGitRepository:
            return 'This is not a git repository.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.ProtectedBranchForcePush:
            return 'This branch is protected from force-push operations.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.ProtectedBranchRequiresReview:
            return 'This branch is protected and any changes requires an approved review. Open a pull request with changes targeting this branch instead.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.PushWithFileSizeExceedingLimit:
            return "The push operation includes a file which exceeds GitHub's file size restriction of 100MB. Please remove the file from history and try again.";
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.HexBranchNameRejected:
            return 'The branch name cannot be a 40-character string of hexadecimal characters, as this is the format that Git uses for representing objects.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.ForcePushRejected:
            return 'The force push has been rejected for the current branch.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.InvalidRefLength:
            return 'A ref cannot be longer than 255 characters.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.CannotMergeUnrelatedHistories:
            return 'Unable to merge unrelated histories in this repository.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.PushWithPrivateEmail:
            return 'Cannot push these commits as they contain an email address marked as private on GitHub. To push anyway, visit https://github.com/settings/emails, uncheck "Keep my email address private", then switch back to GitHub Desktop to push your commits. You can then enable the setting again.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.LFSAttributeDoesNotMatch:
            return 'Git LFS attribute found in global Git configuration does not match expected value.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.ProtectedBranchDeleteRejected:
            return 'This branch cannot be deleted from the remote repository because it is marked as protected.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.ProtectedBranchRequiredStatus:
            return 'The push was rejected by the remote server because a required status check has not been satisfied.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.BranchRenameFailed:
            return 'The branch could not be renamed.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.PathDoesNotExist:
            return 'The path does not exist on disk.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.InvalidObjectName:
            return 'The object was not found in the Git repository.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.OutsideRepository:
            return 'This path is not a valid path inside the repository.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.LockFileAlreadyExists:
            return 'A lock file already exists in the repository, which blocks this operation from completing.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.NoMergeToAbort:
            return 'There is no merge in progress, so there is nothing to abort.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.NoExistingRemoteBranch:
            return 'The remote branch does not exist.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.LocalChangesOverwritten:
            return 'Unable to switch branches as there are working directory changes which would be overwritten. Please commit or stash your changes.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.UnresolvedConflicts:
            return 'There are unresolved conflicts in the working directory.';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.ConfigLockFileAlreadyExists:
            // Added in dugite 1.88.0 (https://github.com/desktop/dugite/pull/386)
            // in support of https://github.com/desktop/desktop/issues/8675 but we're
            // not using it yet. Returning a null message here means the stderr will
            // be used as the error message (or stdout if stderr is empty), i.e. the
            // same behavior as before the ConfigLockFileAlreadyExists was added
            return null;
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.RemoteAlreadyExists:
            return null;
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.TagAlreadyExists:
            return 'A tag with that name already exists';
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.MergeWithLocalChanges:
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.RebaseWithLocalChanges:
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.GPGFailedToSignData:
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.ConflictModifyDeletedInBranch:
        case dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.MergeCommitNoMainlineOption:
            return null;
        default:
            throw new Error(`Unknown error: ${error}`);
    }
}


/***/ }),

/***/ 56010:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MessageStream = void 0;
const tslib_1 = __webpack_require__(84499);
const errors_1 = __webpack_require__(29820);
const error_1 = __webpack_require__(92651);
const streaming_1 = __webpack_require__(53353);
const parser_1 = __webpack_require__(27877);
const JSON_BUF_PROPERTY = '__json_buf';
function tracksToolInput(content) {
    return content.type === 'tool_use' || content.type === 'server_tool_use';
}
class MessageStream {
    constructor() {
        _MessageStream_instances.add(this);
        this.messages = [];
        this.receivedMessages = [];
        _MessageStream_currentMessageSnapshot.set(this, void 0);
        this.controller = new AbortController();
        _MessageStream_connectedPromise.set(this, void 0);
        _MessageStream_resolveConnectedPromise.set(this, () => { });
        _MessageStream_rejectConnectedPromise.set(this, () => { });
        _MessageStream_endPromise.set(this, void 0);
        _MessageStream_resolveEndPromise.set(this, () => { });
        _MessageStream_rejectEndPromise.set(this, () => { });
        _MessageStream_listeners.set(this, {});
        _MessageStream_ended.set(this, false);
        _MessageStream_errored.set(this, false);
        _MessageStream_aborted.set(this, false);
        _MessageStream_catchingPromiseCreated.set(this, false);
        _MessageStream_response.set(this, void 0);
        _MessageStream_request_id.set(this, void 0);
        _MessageStream_handleError.set(this, (error) => {
            tslib_1.__classPrivateFieldSet(this, _MessageStream_errored, true, "f");
            if ((0, errors_1.isAbortError)(error)) {
                error = new error_1.APIUserAbortError();
            }
            if (error instanceof error_1.APIUserAbortError) {
                tslib_1.__classPrivateFieldSet(this, _MessageStream_aborted, true, "f");
                return this._emit('abort', error);
            }
            if (error instanceof error_1.AnthropicError) {
                return this._emit('error', error);
            }
            if (error instanceof Error) {
                const anthropicError = new error_1.AnthropicError(error.message);
                // @ts-ignore
                anthropicError.cause = error;
                return this._emit('error', anthropicError);
            }
            return this._emit('error', new error_1.AnthropicError(String(error)));
        });
        tslib_1.__classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
            tslib_1.__classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f");
            tslib_1.__classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f");
        }), "f");
        tslib_1.__classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
            tslib_1.__classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f");
            tslib_1.__classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f");
        }), "f");
        // Don't let these promises cause unhandled rejection errors.
        // we will manually cause an unhandled rejection error later
        // if the user hasn't registered any error listener or called
        // any promise-returning method.
        tslib_1.__classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => { });
        tslib_1.__classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => { });
    }
    get response() {
        return tslib_1.__classPrivateFieldGet(this, _MessageStream_response, "f");
    }
    get request_id() {
        return tslib_1.__classPrivateFieldGet(this, _MessageStream_request_id, "f");
    }
    /**
     * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
     * returned vie the `request-id` header which is useful for debugging requests and resporting
     * issues to Anthropic.
     *
     * This is the same as the `APIPromise.withResponse()` method.
     *
     * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
     * as no `Response` is available.
     */
    async withResponse() {
        tslib_1.__classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
        const response = await tslib_1.__classPrivateFieldGet(this, _MessageStream_connectedPromise, "f");
        if (!response) {
            throw new Error('Could not resolve a `Response` object');
        }
        return {
            data: this,
            response,
            request_id: response.headers.get('request-id'),
        };
    }
    /**
     * Intended for use on the frontend, consuming a stream produced with
     * `.toReadableStream()` on the backend.
     *
     * Note that messages sent to the model do not appear in `.on('message')`
     * in this context.
     */
    static fromReadableStream(stream) {
        const runner = new MessageStream();
        runner._run(() => runner._fromReadableStream(stream));
        return runner;
    }
    static createMessage(messages, params, options) {
        const runner = new MessageStream();
        for (const message of params.messages) {
            runner._addMessageParam(message);
        }
        runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }));
        return runner;
    }
    _run(executor) {
        executor().then(() => {
            this._emitFinal();
            this._emit('end');
        }, tslib_1.__classPrivateFieldGet(this, _MessageStream_handleError, "f"));
    }
    _addMessageParam(message) {
        this.messages.push(message);
    }
    _addMessage(message, emit = true) {
        this.receivedMessages.push(message);
        if (emit) {
            this._emit('message', message);
        }
    }
    async _createMessage(messages, params, options) {
        const signal = options?.signal;
        let abortHandler;
        if (signal) {
            if (signal.aborted)
                this.controller.abort();
            abortHandler = this.controller.abort.bind(this.controller);
            signal.addEventListener('abort', abortHandler);
        }
        try {
            tslib_1.__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
            const { response, data: stream } = await messages
                .create({ ...params, stream: true }, { ...options, signal: this.controller.signal })
                .withResponse();
            this._connected(response);
            for await (const event of stream) {
                tslib_1.__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
            }
            if (stream.controller.signal?.aborted) {
                throw new error_1.APIUserAbortError();
            }
            tslib_1.__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
        }
        finally {
            if (signal && abortHandler) {
                signal.removeEventListener('abort', abortHandler);
            }
        }
    }
    _connected(response) {
        if (this.ended)
            return;
        tslib_1.__classPrivateFieldSet(this, _MessageStream_response, response, "f");
        tslib_1.__classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get('request-id'), "f");
        tslib_1.__classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response);
        this._emit('connect');
    }
    get ended() {
        return tslib_1.__classPrivateFieldGet(this, _MessageStream_ended, "f");
    }
    get errored() {
        return tslib_1.__classPrivateFieldGet(this, _MessageStream_errored, "f");
    }
    get aborted() {
        return tslib_1.__classPrivateFieldGet(this, _MessageStream_aborted, "f");
    }
    abort() {
        this.controller.abort();
    }
    /**
     * Adds the listener function to the end of the listeners array for the event.
     * No checks are made to see if the listener has already been added. Multiple calls passing
     * the same combination of event and listener will result in the listener being added, and
     * called, multiple times.
     * @returns this MessageStream, so that calls can be chained
     */
    on(event, listener) {
        const listeners = tslib_1.__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (tslib_1.__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []);
        listeners.push({ listener });
        return this;
    }
    /**
     * Removes the specified listener from the listener array for the event.
     * off() will remove, at most, one instance of a listener from the listener array. If any single
     * listener has been added multiple times to the listener array for the specified event, then
     * off() must be called multiple times to remove each instance.
     * @returns this MessageStream, so that calls can be chained
     */
    off(event, listener) {
        const listeners = tslib_1.__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event];
        if (!listeners)
            return this;
        const index = listeners.findIndex((l) => l.listener === listener);
        if (index >= 0)
            listeners.splice(index, 1);
        return this;
    }
    /**
     * Adds a one-time listener function for the event. The next time the event is triggered,
     * this listener is removed and then invoked.
     * @returns this MessageStream, so that calls can be chained
     */
    once(event, listener) {
        const listeners = tslib_1.__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (tslib_1.__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []);
        listeners.push({ listener, once: true });
        return this;
    }
    /**
     * This is similar to `.once()`, but returns a Promise that resolves the next time
     * the event is triggered, instead of calling a listener callback.
     * @returns a Promise that resolves the next time given event is triggered,
     * or rejects if an error is emitted.  (If you request the 'error' event,
     * returns a promise that resolves with the error).
     *
     * Example:
     *
     *   const message = await stream.emitted('message') // rejects if the stream errors
     */
    emitted(event) {
        return new Promise((resolve, reject) => {
            tslib_1.__classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
            if (event !== 'error')
                this.once('error', reject);
            this.once(event, resolve);
        });
    }
    async done() {
        tslib_1.__classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
        await tslib_1.__classPrivateFieldGet(this, _MessageStream_endPromise, "f");
    }
    get currentMessage() {
        return tslib_1.__classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
    }
    /**
     * @returns a promise that resolves with the the final assistant Message response,
     * or rejects if an error occurred or the stream ended prematurely without producing a Message.
     */
    async finalMessage() {
        await this.done();
        return tslib_1.__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
    }
    /**
     * @returns a promise that resolves with the the final assistant Message's text response, concatenated
     * together if there are more than one text blocks.
     * Rejects if an error occurred or the stream ended prematurely without producing a Message.
     */
    async finalText() {
        await this.done();
        return tslib_1.__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
    }
    _emit(event, ...args) {
        // make sure we don't emit any MessageStreamEvents after end
        if (tslib_1.__classPrivateFieldGet(this, _MessageStream_ended, "f"))
            return;
        if (event === 'end') {
            tslib_1.__classPrivateFieldSet(this, _MessageStream_ended, true, "f");
            tslib_1.__classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this);
        }
        const listeners = tslib_1.__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event];
        if (listeners) {
            tslib_1.__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
            listeners.forEach(({ listener }) => listener(...args));
        }
        if (event === 'abort') {
            const error = args[0];
            if (!tslib_1.__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
                Promise.reject(error);
            }
            tslib_1.__classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
            tslib_1.__classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error);
            this._emit('end');
            return;
        }
        if (event === 'error') {
            // NOTE: _emit('error', error) should only be called from #handleError().
            const error = args[0];
            if (!tslib_1.__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
                // Trigger an unhandled rejection if the user hasn't registered any error handlers.
                // If you are seeing stack traces here, make sure to handle errors via either:
                // - runner.on('error', () => ...)
                // - await runner.done()
                // - await runner.final...()
                // - etc.
                Promise.reject(error);
            }
            tslib_1.__classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
            tslib_1.__classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error);
            this._emit('end');
        }
    }
    _emitFinal() {
        const finalMessage = this.receivedMessages.at(-1);
        if (finalMessage) {
            this._emit('finalMessage', tslib_1.__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
        }
    }
    async _fromReadableStream(readableStream, options) {
        const signal = options?.signal;
        let abortHandler;
        if (signal) {
            if (signal.aborted)
                this.controller.abort();
            abortHandler = this.controller.abort.bind(this.controller);
            signal.addEventListener('abort', abortHandler);
        }
        try {
            tslib_1.__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
            this._connected(null);
            const stream = streaming_1.Stream.fromReadableStream(readableStream, this.controller);
            for await (const event of stream) {
                tslib_1.__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
            }
            if (stream.controller.signal?.aborted) {
                throw new error_1.APIUserAbortError();
            }
            tslib_1.__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
        }
        finally {
            if (signal && abortHandler) {
                signal.removeEventListener('abort', abortHandler);
            }
        }
    }
    [(_MessageStream_currentMessageSnapshot = new WeakMap(), _MessageStream_connectedPromise = new WeakMap(), _MessageStream_resolveConnectedPromise = new WeakMap(), _MessageStream_rejectConnectedPromise = new WeakMap(), _MessageStream_endPromise = new WeakMap(), _MessageStream_resolveEndPromise = new WeakMap(), _MessageStream_rejectEndPromise = new WeakMap(), _MessageStream_listeners = new WeakMap(), _MessageStream_ended = new WeakMap(), _MessageStream_errored = new WeakMap(), _MessageStream_aborted = new WeakMap(), _MessageStream_catchingPromiseCreated = new WeakMap(), _MessageStream_response = new WeakMap(), _MessageStream_request_id = new WeakMap(), _MessageStream_handleError = new WeakMap(), _MessageStream_instances = new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() {
        if (this.receivedMessages.length === 0) {
            throw new error_1.AnthropicError('stream ended without producing a Message with role=assistant');
        }
        return this.receivedMessages.at(-1);
    }, _MessageStream_getFinalText = function _MessageStream_getFinalText() {
        if (this.receivedMessages.length === 0) {
            throw new error_1.AnthropicError('stream ended without producing a Message with role=assistant');
        }
        const textBlocks = this.receivedMessages
            .at(-1)
            .content.filter((block) => block.type === 'text')
            .map((block) => block.text);
        if (textBlocks.length === 0) {
            throw new error_1.AnthropicError('stream ended without producing a content block with type=text');
        }
        return textBlocks.join(' ');
    }, _MessageStream_beginRequest = function _MessageStream_beginRequest() {
        if (this.ended)
            return;
        tslib_1.__classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f");
    }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) {
        if (this.ended)
            return;
        const messageSnapshot = tslib_1.__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
        this._emit('streamEvent', event, messageSnapshot);
        switch (event.type) {
            case 'content_block_delta': {
                const content = messageSnapshot.content.at(-1);
                switch (event.delta.type) {
                    case 'text_delta': {
                        if (content.type === 'text') {
                            this._emit('text', event.delta.text, content.text || '');
                        }
                        break;
                    }
                    case 'citations_delta': {
                        if (content.type === 'text') {
                            this._emit('citation', event.delta.citation, content.citations ?? []);
                        }
                        break;
                    }
                    case 'input_json_delta': {
                        if (tracksToolInput(content) && content.input) {
                            this._emit('inputJson', event.delta.partial_json, content.input);
                        }
                        break;
                    }
                    case 'thinking_delta': {
                        if (content.type === 'thinking') {
                            this._emit('thinking', event.delta.thinking, content.thinking);
                        }
                        break;
                    }
                    case 'signature_delta': {
                        if (content.type === 'thinking') {
                            this._emit('signature', content.signature);
                        }
                        break;
                    }
                    default:
                        checkNever(event.delta);
                }
                break;
            }
            case 'message_stop': {
                this._addMessageParam(messageSnapshot);
                this._addMessage(messageSnapshot, true);
                break;
            }
            case 'content_block_stop': {
                this._emit('contentBlock', messageSnapshot.content.at(-1));
                break;
            }
            case 'message_start': {
                tslib_1.__classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
                break;
            }
            case 'content_block_start':
            case 'message_delta':
                break;
        }
    }, _MessageStream_endRequest = function _MessageStream_endRequest() {
        if (this.ended) {
            throw new error_1.AnthropicError(`stream has ended, this shouldn't happen`);
        }
        const snapshot = tslib_1.__classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
        if (!snapshot) {
            throw new error_1.AnthropicError(`request ended without sending any chunks`);
        }
        tslib_1.__classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f");
        return snapshot;
    }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) {
        let snapshot = tslib_1.__classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
        if (event.type === 'message_start') {
            if (snapshot) {
                throw new error_1.AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
            }
            return event.message;
        }
        if (!snapshot) {
            throw new error_1.AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
        }
        switch (event.type) {
            case 'message_stop':
                return snapshot;
            case 'message_delta':
                snapshot.stop_reason = event.delta.stop_reason;
                snapshot.stop_sequence = event.delta.stop_sequence;
                snapshot.usage.output_tokens = event.usage.output_tokens;
                // Update other usage fields if they exist in the event
                if (event.usage.input_tokens != null) {
                    snapshot.usage.input_tokens = event.usage.input_tokens;
                }
                if (event.usage.cache_creation_input_tokens != null) {
                    snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
                }
                if (event.usage.cache_read_input_tokens != null) {
                    snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
                }
                if (event.usage.server_tool_use != null) {
                    snapshot.usage.server_tool_use = event.usage.server_tool_use;
                }
                return snapshot;
            case 'content_block_start':
                snapshot.content.push({ ...event.content_block });
                return snapshot;
            case 'content_block_delta': {
                const snapshotContent = snapshot.content.at(event.index);
                switch (event.delta.type) {
                    case 'text_delta': {
                        if (snapshotContent?.type === 'text') {
                            snapshot.content[event.index] = {
                                ...snapshotContent,
                                text: (snapshotContent.text || '') + event.delta.text,
                            };
                        }
                        break;
                    }
                    case 'citations_delta': {
                        if (snapshotContent?.type === 'text') {
                            snapshot.content[event.index] = {
                                ...snapshotContent,
                                citations: [...(snapshotContent.citations ?? []), event.delta.citation],
                            };
                        }
                        break;
                    }
                    case 'input_json_delta': {
                        if (snapshotContent && tracksToolInput(snapshotContent)) {
                            // we need to keep track of the raw JSON string as well so that we can
                            // re-parse it for each delta, for now we just store it as an untyped
                            // non-enumerable property on the snapshot
                            let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || '';
                            jsonBuf += event.delta.partial_json;
                            const newContent = { ...snapshotContent };
                            Object.defineProperty(newContent, JSON_BUF_PROPERTY, {
                                value: jsonBuf,
                                enumerable: false,
                                writable: true,
                            });
                            if (jsonBuf) {
                                newContent.input = (0, parser_1.partialParse)(jsonBuf);
                            }
                            snapshot.content[event.index] = newContent;
                        }
                        break;
                    }
                    case 'thinking_delta': {
                        if (snapshotContent?.type === 'thinking') {
                            snapshot.content[event.index] = {
                                ...snapshotContent,
                                thinking: snapshotContent.thinking + event.delta.thinking,
                            };
                        }
                        break;
                    }
                    case 'signature_delta': {
                        if (snapshotContent?.type === 'thinking') {
                            snapshot.content[event.index] = {
                                ...snapshotContent,
                                signature: event.delta.signature,
                            };
                        }
                        break;
                    }
                    default:
                        checkNever(event.delta);
                }
                return snapshot;
            }
            case 'content_block_stop':
                return snapshot;
        }
    }, Symbol.asyncIterator)]() {
        const pushQueue = [];
        const readQueue = [];
        let done = false;
        this.on('streamEvent', (event) => {
            const reader = readQueue.shift();
            if (reader) {
                reader.resolve(event);
            }
            else {
                pushQueue.push(event);
            }
        });
        this.on('end', () => {
            done = true;
            for (const reader of readQueue) {
                reader.resolve(undefined);
            }
            readQueue.length = 0;
        });
        this.on('abort', (err) => {
            done = true;
            for (const reader of readQueue) {
                reader.reject(err);
            }
            readQueue.length = 0;
        });
        this.on('error', (err) => {
            done = true;
            for (const reader of readQueue) {
                reader.reject(err);
            }
            readQueue.length = 0;
        });
        return {
            next: async () => {
                if (!pushQueue.length) {
                    if (done) {
                        return { value: undefined, done: true };
                    }
                    return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));
                }
                const chunk = pushQueue.shift();
                return { value: chunk, done: false };
            },
            return: async () => {
                this.abort();
                return { value: undefined, done: true };
            },
        };
    }
    toReadableStream() {
        const stream = new streaming_1.Stream(this[Symbol.asyncIterator].bind(this), this.controller);
        return stream.toReadableStream();
    }
}
exports.MessageStream = MessageStream;
// used to ensure exhaustive case matching without throwing a runtime error
function checkNever(x) { }
//# sourceMappingURL=MessageStream.js.map

/***/ }),

/***/ 56038:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var _a, _b;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.browserModuleNames = exports.commonModuleNames = void 0;
const get_electron_binding_1 = __webpack_require__(25374);
exports.commonModuleNames = [
    'clipboard',
    'nativeImage',
    'shell',
];
exports.browserModuleNames = [
    'app',
    'autoUpdater',
    'BaseWindow',
    'BrowserView',
    'BrowserWindow',
    'contentTracing',
    'crashReporter',
    'dialog',
    'globalShortcut',
    'ipcMain',
    'inAppPurchase',
    'Menu',
    'MenuItem',
    'nativeTheme',
    'net',
    'netLog',
    'MessageChannelMain',
    'Notification',
    'powerMonitor',
    'powerSaveBlocker',
    'protocol',
    'pushNotifications',
    'safeStorage',
    'screen',
    'session',
    'ServiceWorkerMain',
    'ShareMenu',
    'systemPreferences',
    'TopLevelWindow',
    'TouchBar',
    'Tray',
    'utilityProcess',
    'View',
    'webContents',
    'WebContentsView',
    'webFrameMain',
].concat(exports.commonModuleNames);
const features = get_electron_binding_1.getElectronBinding('features');
if (((_a = features === null || features === void 0 ? void 0 : features.isDesktopCapturerEnabled) === null || _a === void 0 ? void 0 : _a.call(features)) !== false) {
    exports.browserModuleNames.push('desktopCapturer');
}
if (((_b = features === null || features === void 0 ? void 0 : features.isViewApiEnabled) === null || _b === void 0 ? void 0 : _b.call(features)) !== false) {
    exports.browserModuleNames.push('ImageView');
}


/***/ }),

/***/ 56182:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   h: () => (/* binding */ ForwardRef)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCheckmark = function SvgCheckmark(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: "0 0 24 24",
    fill: "white",
    width: "18px",
    height: "18px",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCheckmark);

/* unused harmony default export */ var __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "545fe92889801a4023daa8ade33047f5.svg");

/***/ }),

/***/ 56353:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  S: () => (/* binding */ AI_ASSISTANT_ENABLED_SUGGESTIONS_KEY),
  z: () => (/* binding */ OpenAiSection)
});

// EXTERNAL MODULE: ./src/editor/src/store/AiAssistantStore.ts
var AiAssistantStore = __webpack_require__(61231);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-platform/src/index.ts + 10 modules
var src = __webpack_require__(37218);
// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/api.ts
var api = __webpack_require__(35266);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/inputs/PrimaryButton/index.ts + 2 modules
var PrimaryButton = __webpack_require__(76302);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Box/index.ts + 2 modules
var Box = __webpack_require__(22484);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Stack/index.ts + 2 modules
var Stack = __webpack_require__(86380);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelButton/index.ts + 2 modules
var PropertyPanelButton = __webpack_require__(60938);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelInput/index.ts + 21 modules
var PropertyPanelInput = __webpack_require__(83431);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelBaseInput/index.ts + 2 modules
var PropertyPanelBaseInput = __webpack_require__(98690);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelPasswordInput/PropertyPanelPasswordInput.tsx


function PropertyPanelPasswordInput({ value, isChanged, isConnected, onChange }) {
    const [displayedInputValue, setDisplayedInputValue] = (0,external_react_.useState)(value);
    const [focused, setFocused] = (0,external_react_.useState)(false);
    function handleUpdate(inputValue) {
        onChange && onChange(inputValue);
        setDisplayedInputValue(inputValue);
    }
    function handleBlur() {
        handleUpdate(displayedInputValue);
        setFocused(false);
    }
    function handleFocus() {
        setFocused(true);
    }
    (0,external_react_.useEffect)(() => {
        handleUpdate(value);
    }, [value]);
    return (external_react_default().createElement(PropertyPanelBaseInput/* PropertyPanelBaseInput */.Z, { value: displayedInputValue, type: focused ? 'text' : 'password', isChanged: isChanged, isConnected: isConnected, onChange: (value) => setDisplayedInputValue(String(value)), onBlur: handleBlur, onFocus: handleFocus, onKeyDown: (e) => e.key === 'Enter' && handleUpdate(displayedInputValue) }));
}

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelPasswordInput/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelSelectInput/index.ts + 3 modules
var PropertyPanelSelectInput = __webpack_require__(66095);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelTextInput/index.ts + 1 modules
var PropertyPanelTextInput = __webpack_require__(55506);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/sidebar/CollapsableSection/index.ts + 2 modules
var CollapsableSection = __webpack_require__(11603);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/index.ts
var Text = __webpack_require__(93834);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Title/index.ts
var Title = __webpack_require__(48237);
// EXTERNAL MODULE: ./src/editor/src/views/ToastLayer/ToastLayer.tsx
var ToastLayer = __webpack_require__(80424);
;// ./src/editor/src/views/panels/EditorSettingsPanel/sections/OpenAiSection.tsx
















const AI_ASSISTANT_ENABLED_SUGGESTIONS_KEY = 'aiAssistant.enabledSuggestions';
function OpenAiSection() {
    const [enabledState, setEnabledState] = (0,external_react_.useState)(AiAssistantStore/* OpenAiStore */.q.getVersion());
    const [apiKey, setApiKey] = (0,external_react_.useState)(AiAssistantStore/* OpenAiStore */.q.getApiKey());
    const [endpoint, setEndpoint] = (0,external_react_.useState)(AiAssistantStore/* OpenAiStore */.q.getEndpoint());
    const [model, setModel] = (0,external_react_.useState)(AiAssistantStore/* OpenAiStore */.q.getModel());
    async function onVerifyApiKey() {
        const models = await (0,api/* verifyOpenAiApiKey */.z)(apiKey);
        if (models) {
            const haveGpt4 = !!models['gpt-4o-mini'];
            if (haveGpt4) {
                AiAssistantStore/* OpenAiStore */.q.setIsAiApiKeyVerified(true);
                ToastLayer.ToastLayer.showSuccess('OpenAI API Key is valid with GPT-4!');
            }
            else {
                AiAssistantStore/* OpenAiStore */.q.setIsAiApiKeyVerified(false);
                ToastLayer.ToastLayer.showError('OpenAI API Key is missing gpt-4 model Support!');
            }
        }
        else {
            AiAssistantStore/* OpenAiStore */.q.setIsAiApiKeyVerified(false);
            ToastLayer.ToastLayer.showError('OpenAI API Key is invalid!');
        }
    }
    return (external_react_default().createElement(CollapsableSection/* CollapsableSection */.M, { title: "Noodl AI (Beta)" },
        external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true },
            external_react_default().createElement(Stack/* VStack */.Tk, null,
                external_react_default().createElement(PropertyPanelInput/* PropertyPanelRow */.eh, { label: "Version", isChanged: false },
                    external_react_default().createElement(PropertyPanelSelectInput/* PropertyPanelSelectInput */.S, { value: enabledState, properties: {
                            options: [
                                { label: 'Disabled', value: 'disabled' },
                                { label: 'OpenAI', value: 'full-beta' },
                                { label: 'Custom', value: 'enterprise' }
                            ]
                        }, onChange: (value) => {
                            setEnabledState(value);
                            AiAssistantStore/* OpenAiStore */.q.setVersion(value);
                        } })),
                enabledState === 'disabled' && (external_react_default().createElement(Box/* Box */.a, { hasYSpacing: true },
                    external_react_default().createElement(Text/* Text */.EY, null, "Noodl AI is currently disabled."))),
                enabledState === 'full-beta' && (external_react_default().createElement((external_react_default()).Fragment, null,
                    external_react_default().createElement(PropertyPanelInput/* PropertyPanelRow */.eh, { label: "Model", isChanged: false },
                        external_react_default().createElement(PropertyPanelSelectInput/* PropertyPanelSelectInput */.S, { value: model, properties: {
                                options: [
                                    { label: 'gpt-3', value: 'gpt-3' },
                                    { label: 'gpt-4', value: 'gpt-4o-mini' }
                                ]
                            }, onChange: (value) => {
                                setModel(value);
                                AiAssistantStore/* OpenAiStore */.q.setModel(value);
                            } })),
                    external_react_default().createElement(PropertyPanelInput/* PropertyPanelRow */.eh, { label: "API Key", isChanged: false },
                        external_react_default().createElement(PropertyPanelPasswordInput, { value: apiKey, onChange: (value) => {
                                setApiKey(value);
                                AiAssistantStore/* OpenAiStore */.q.setApiKey(value);
                            } })),
                    external_react_default().createElement(PropertyPanelInput/* PropertyPanelRow */.eh, { label: "API Key", isChanged: false },
                        external_react_default().createElement(PropertyPanelButton/* PropertyPanelButton */.S, { properties: {
                                isPrimary: true,
                                buttonLabel: 'Verify API Key',
                                onClick() {
                                    onVerifyApiKey();
                                }
                            } })),
                    external_react_default().createElement(Box/* Box */.a, { hasYSpacing: true },
                        external_react_default().createElement(Text/* Text */.EY, null, "Verify your OpenAI API key to start using AI Commands.")))),
                enabledState === 'enterprise' && (external_react_default().createElement((external_react_default()).Fragment, null,
                    external_react_default().createElement(PropertyPanelInput/* PropertyPanelRow */.eh, { label: "Model", isChanged: false },
                        external_react_default().createElement(PropertyPanelSelectInput/* PropertyPanelSelectInput */.S, { value: model, properties: {
                                options: [
                                    { label: 'gpt-3', value: 'gpt-3' },
                                    { label: 'gpt-4', value: 'gpt-4o-mini' }
                                ]
                            }, onChange: (value) => {
                                setModel(value);
                                AiAssistantStore/* OpenAiStore */.q.setModel(value);
                            } })),
                    external_react_default().createElement(PropertyPanelInput/* PropertyPanelRow */.eh, { label: "API Key", isChanged: false },
                        external_react_default().createElement(PropertyPanelPasswordInput, { value: apiKey, onChange: (value) => {
                                setApiKey(value);
                                AiAssistantStore/* OpenAiStore */.q.setApiKey(value);
                            } })),
                    external_react_default().createElement(PropertyPanelInput/* PropertyPanelRow */.eh, { label: "Endpoint", isChanged: false },
                        external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: endpoint, onChange: (value) => {
                                setEndpoint(value);
                                AiAssistantStore/* OpenAiStore */.q.setEndpoint(value);
                            } })))),
                external_react_default().createElement(Box/* Box */.a, { hasXSpacing: 3, hasYSpacing: 3, UNSAFE_style: { borderRadius: '2px', background: 'var(--theme-color-bg-3)' } },
                    external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Medium, hasBottomSpacing: true }, "Noodl AI docs"),
                    external_react_default().createElement(Text/* Text */.EY, { hasBottomSpacing: true }, "See setup instructions and guides for how to use Noodl AI on our docs."),
                    external_react_default().createElement(PrimaryButton/* PrimaryButton */.jn, { variant: PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, size: PrimaryButton/* PrimaryButtonSize */._S.Small, isGrowing: true, label: "Open docs", onClick: () => {
                            src.platform.openExternal('https://docs.noodl.net/#/docs/getting-started/noodl-ai/');
                        } }))))));
}


/***/ }),

/***/ 56937:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   J: () => (/* binding */ ComponentIconType),
/* harmony export */   N: () => (/* binding */ getComponentIconType)
/* harmony export */ });
var ComponentIconType;
(function (ComponentIconType) {
    ComponentIconType["Page"] = "file";
    ComponentIconType["CloudFunction"] = "cloud_function";
    ComponentIconType[ComponentIconType["Visual"] = 2] = "Visual";
})(ComponentIconType || (ComponentIconType = {}));
const typenames = {
    Page: ComponentIconType.Page,
    'noodl.cloud.request': ComponentIconType.CloudFunction
};
function getComponentIconType(component) {
    var _a;
    let icon = undefined;
    if ((_a = component === null || component === void 0 ? void 0 : component.graph) === null || _a === void 0 ? void 0 : _a.getVisualRootIds().length) {
        icon = ComponentIconType.Visual;
    }
    component === null || component === void 0 ? void 0 : component.graph.forEachNode((component) => {
        if (typenames[component.typename]) {
            icon = typenames[component.typename];
        }
    });
    return icon;
}


/***/ }),

/***/ 57002:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  Ym: () => (/* reexport */ HighlightManager)
});

// UNUSED EXPORTS: CHANNELS, getAvailableChannels, getChannelConfig, isValidChannel, noodlShowcase

// EXTERNAL MODULE: ./src/shared/utils/EventDispatcher.ts
var EventDispatcher = __webpack_require__(11138);
;// ./src/editor/src/services/HighlightManager/channels.ts
/**
 * Channel Configuration for Canvas Highlighting System
 *
 * Defines the visual appearance and behavior of each highlighting channel.
 * Channels are used to organize different types of highlights:
 * - lineage: Data flow traces (blue)
 * - impact: Change impact visualization (orange)
 * - selection: User selection state (white)
 * - warning: Errors and validation warnings (red)
 */
/**
 * Channel definitions with colors, styles, and metadata
 */
const CHANNELS = {
    /**
     * Data Lineage traces - shows how data flows through the graph
     * Blue color with glow effect for visibility without being distracting
     */
    lineage: {
        color: '#4A90D9',
        style: 'glow',
        description: 'Data flow traces showing how data propagates through nodes',
        zIndex: 10
    },
    /**
     * Impact Radar - shows which nodes would be affected by a change
     * Orange color with pulse effect to draw attention
     */
    impact: {
        color: '#F5A623',
        style: 'pulse',
        description: 'Downstream impact visualization for change analysis',
        zIndex: 15
    },
    /**
     * Selection state - temporary highlight for hover/focus states
     * White color with solid effect for clarity
     */
    selection: {
        color: '#FFFFFF',
        style: 'solid',
        description: 'Temporary selection and hover states',
        zIndex: 20
    },
    /**
     * Warnings and errors - highlights problematic nodes/connections
     * Red color with pulse effect for urgency
     */
    warning: {
        color: '#FF6B6B',
        style: 'pulse',
        description: 'Error and validation warning indicators',
        zIndex: 25
    }
};
/**
 * Get channel configuration by name
 * Returns default configuration if channel doesn't exist
 */
function getChannelConfig(channel) {
    return (CHANNELS[channel] || {
        color: '#FFFFFF',
        style: 'solid',
        description: 'Custom channel',
        zIndex: 5
    });
}
/**
 * Check if a channel exists
 */
function isValidChannel(channel) {
    return channel in CHANNELS;
}
/**
 * Get all available channel names
 */
function getAvailableChannels() {
    return Object.keys(CHANNELS);
}
/**
 * Default z-index for highlights when not specified
 */
const DEFAULT_HIGHLIGHT_Z_INDEX = 10;
/**
 * Animation durations for different styles (in milliseconds)
 */
const ANIMATION_DURATIONS = {
    glow: 1000,
    pulse: 1500,
    solid: 0
};

;// ./src/editor/src/services/HighlightManager/HighlightHandle.ts
/**
 * HighlightHandle - Control interface for individual highlights
 *
 * Provides methods to update, dismiss, and query highlights.
 * Handles are returned when creating highlights and should be kept
 * for later manipulation.
 */
/**
 * Implementation of the highlight control interface
 */
class HighlightHandle {
    constructor(id, channel, nodeIds, connections, label, onUpdate, onDismiss) {
        this.id = id;
        this.channel = channel;
        this._active = true;
        this._nodeIds = [...nodeIds];
        this._connections = [...connections];
        this._label = label;
        this.onUpdate = onUpdate;
        this.onDismiss = onDismiss;
    }
    /**
     * Update the highlighted nodes
     */
    update(nodeIds) {
        if (!this._active) {
            console.warn(`HighlightHandle: Cannot update inactive highlight ${this.id}`);
            return;
        }
        this._nodeIds = [...nodeIds];
        this.onUpdate(this);
    }
    /**
     * Update the label displayed near the highlight
     */
    setLabel(label) {
        if (!this._active) {
            console.warn(`HighlightHandle: Cannot update label on inactive highlight ${this.id}`);
            return;
        }
        this._label = label;
        this.onUpdate(this);
    }
    /**
     * Remove this highlight
     */
    dismiss() {
        if (!this._active) {
            return;
        }
        this._active = false;
        this.onDismiss(this);
    }
    /**
     * Check if this highlight is still active
     */
    isActive() {
        return this._active;
    }
    /**
     * Get the current node IDs
     */
    getNodeIds() {
        return [...this._nodeIds];
    }
    /**
     * Get the current connection refs
     */
    getConnections() {
        return [...this._connections];
    }
    /**
     * Get the current label
     * @internal Used by HighlightManager
     */
    getLabel() {
        return this._label;
    }
    /**
     * Update connections (internal method called by manager)
     * @internal
     */
    setConnections(connections) {
        this._connections = [...connections];
    }
    /**
     * Mark this handle as inactive (internal method called by manager)
     * @internal
     */
    deactivate() {
        this._active = false;
    }
}

;// ./src/editor/src/services/HighlightManager/HighlightManager.ts
/**
 * HighlightManager - Core service for canvas highlighting
 *
 * Singleton service that manages multi-channel highlights on the node graph canvas.
 * Extends EventDispatcher to notify listeners of highlight changes.
 *
 * Features:
 * - Multi-channel organization (lineage, impact, selection, warning)
 * - Persistent highlights that survive component navigation
 * - Path highlighting across multiple nodes/connections
 * - Event-based notifications for UI updates
 *
 * @example
 * ```typescript
 * const handle = HighlightManager.instance.highlightNodes(['node1', 'node2'], {
 *   channel: 'lineage',
 *   label: 'Data flow from Input'
 * });
 *
 * // Later...
 * handle.update(['node1', 'node2', 'node3']);
 * handle.dismiss();
 * ```
 */



/**
 * Main highlighting service - manages all highlights across all channels
 */
class HighlightManager extends EventDispatcher.EventDispatcher {
    /**
     * Get the singleton instance
     */
    static get instance() {
        if (!HighlightManager._instance) {
            HighlightManager._instance = new HighlightManager();
        }
        return HighlightManager._instance;
    }
    constructor() {
        super();
        /**
         * Internal state tracking all active highlights
         */
        this.highlights = new Map();
        /**
         * Counter for generating unique highlight IDs
         */
        this.nextId = 1;
        /**
         * Current component being viewed (for persistence tracking)
         * Set by NodeGraphEditor when navigating components
         */
        this.currentComponentId = null;
    }
    /**
     * Highlight specific nodes
     *
     * @param nodeIds - Array of node IDs to highlight
     * @param options - Highlight configuration
     * @returns Handle to control the highlight
     *
     * @example
     * ```typescript
     * const handle = HighlightManager.instance.highlightNodes(
     *   ['textNode', 'outputNode'],
     *   { channel: 'lineage', label: 'Text data flow' }
     * );
     * ```
     */
    highlightNodes(nodeIds, options) {
        if (!isValidChannel(options.channel)) {
            console.warn(`HighlightManager: Unknown channel "${options.channel}"`);
        }
        const id = `highlight-${this.nextId++}`;
        const channelConfig = getChannelConfig(options.channel);
        // Create the highlight state
        const state = {
            id,
            channel: options.channel,
            allNodeIds: [...nodeIds],
            allConnections: [],
            visibleNodeIds: [...nodeIds], // Will be filtered in Phase 3
            visibleConnections: [],
            options: {
                ...options,
                color: options.color || channelConfig.color,
                style: options.style || channelConfig.style,
                persistent: options.persistent !== false // Default to true
            },
            createdAt: new Date(),
            active: true
        };
        this.highlights.set(id, state);
        // Create the handle
        const handle = new HighlightHandle(id, options.channel, nodeIds, [], options.label, (h) => this.handleUpdate(h), (h) => this.handleDismiss(h));
        // Notify listeners
        this.notifyListeners('highlightAdded', {
            highlightId: id,
            channel: options.channel,
            highlight: this.getHighlightInfo(state)
        });
        return handle;
    }
    /**
     * Highlight specific connections between nodes
     *
     * @param connections - Array of connection references
     * @param options - Highlight configuration
     * @returns Handle to control the highlight
     *
     * @example
     * ```typescript
     * const handle = HighlightManager.instance.highlightConnections(
     *   [{ fromNodeId: 'a', fromPort: 'out', toNodeId: 'b', toPort: 'in' }],
     *   { channel: 'warning', label: 'Invalid connection' }
     * );
     * ```
     */
    highlightConnections(connections, options) {
        if (!isValidChannel(options.channel)) {
            console.warn(`HighlightManager: Unknown channel "${options.channel}"`);
        }
        const id = `highlight-${this.nextId++}`;
        const channelConfig = getChannelConfig(options.channel);
        // Extract unique node IDs from connections
        const nodeIds = new Set();
        connections.forEach((conn) => {
            nodeIds.add(conn.fromNodeId);
            nodeIds.add(conn.toNodeId);
        });
        const state = {
            id,
            channel: options.channel,
            allNodeIds: Array.from(nodeIds),
            allConnections: [...connections],
            visibleNodeIds: Array.from(nodeIds), // Will be filtered in Phase 3
            visibleConnections: [...connections], // Will be filtered in Phase 3
            options: {
                ...options,
                color: options.color || channelConfig.color,
                style: options.style || channelConfig.style,
                persistent: options.persistent !== false
            },
            createdAt: new Date(),
            active: true
        };
        this.highlights.set(id, state);
        const handle = new HighlightHandle(id, options.channel, Array.from(nodeIds), connections, options.label, (h) => this.handleUpdate(h), (h) => this.handleDismiss(h));
        this.notifyListeners('highlightAdded', {
            highlightId: id,
            channel: options.channel,
            highlight: this.getHighlightInfo(state)
        });
        return handle;
    }
    /**
     * Clear all highlights in a specific channel
     *
     * @param channel - Channel to clear
     *
     * @example
     * ```typescript
     * HighlightManager.instance.clearChannel('selection');
     * ```
     */
    clearChannel(channel) {
        const toRemove = [];
        this.highlights.forEach((state, id) => {
            if (state.channel === channel) {
                state.active = false;
                toRemove.push(id);
            }
        });
        toRemove.forEach((id) => this.highlights.delete(id));
        if (toRemove.length > 0) {
            this.notifyListeners('channelCleared', { channel });
        }
    }
    /**
     * Clear all highlights across all channels
     */
    clearAll() {
        this.highlights.clear();
        this.notifyListeners('allCleared', {});
    }
    /**
     * Get all active highlights, optionally filtered by channel
     *
     * @param channel - Optional channel filter
     * @returns Array of highlight information
     */
    getHighlights(channel) {
        const results = [];
        this.highlights.forEach((state) => {
            if (state.active && (!channel || state.channel === channel)) {
                results.push(this.getHighlightInfo(state));
            }
        });
        return results;
    }
    /**
     * Set the current component being viewed
     * Called by NodeGraphEditor when navigating
     * Filters highlights to show only nodes/connections in the current component
     *
     * @internal
     */
    setCurrentComponent(componentId) {
        if (this.currentComponentId === componentId) {
            return; // No change
        }
        this.currentComponentId = componentId;
        // Re-filter all active highlights for the new component
        this.highlights.forEach((state) => {
            this.filterVisibleElements(state);
        });
        // Notify listeners that highlights have changed
        this.notifyListeners('highlightUpdated', {
            channel: 'all'
        });
    }
    /**
     * Get the current component ID
     * @internal
     */
    getCurrentComponent() {
        return this.currentComponentId;
    }
    /**
     * Highlight a path through the node graph
     *
     * Supports cross-component paths with boundary detection.
     *
     * @param path - Path definition with nodes and connections
     * @param options - Highlight configuration
     * @returns Handle to control the highlight
     */
    highlightPath(path, options) {
        if (!isValidChannel(options.channel)) {
            console.warn(`HighlightManager: Unknown channel "${options.channel}"`);
        }
        const id = `highlight-${this.nextId++}`;
        const channelConfig = getChannelConfig(options.channel);
        // Detect component boundaries in the path
        const boundaries = path.componentBoundaries || this.detectComponentBoundaries(path);
        const state = {
            id,
            channel: options.channel,
            allNodeIds: [...path.nodes],
            allConnections: [...path.connections],
            visibleNodeIds: [...path.nodes], // Will be filtered
            visibleConnections: [...path.connections], // Will be filtered
            componentBoundaries: boundaries,
            options: {
                ...options,
                color: options.color || channelConfig.color,
                style: options.style || channelConfig.style,
                persistent: options.persistent !== false
            },
            createdAt: new Date(),
            active: true
        };
        // Filter for current component
        this.filterVisibleElements(state);
        this.highlights.set(id, state);
        const handle = new HighlightHandle(id, options.channel, path.nodes, path.connections, options.label, (h) => this.handleUpdate(h), (h) => this.handleDismiss(h));
        this.notifyListeners('highlightAdded', {
            highlightId: id,
            channel: options.channel,
            highlight: this.getHighlightInfo(state)
        });
        return handle;
    }
    /**
     * Get visible highlights for the current component
     * Returns only highlights with elements visible in the current component
     *
     * @internal
     */
    getVisibleHighlights() {
        return Array.from(this.highlights.values())
            .filter((s) => s.active)
            .filter((s) => s.visibleNodeIds.length > 0 || s.visibleConnections.length > 0);
    }
    /**
     * Handle highlight update from a HighlightHandle
     * @private
     */
    handleUpdate(handle) {
        const state = this.highlights.get(handle.id);
        if (!state)
            return;
        state.allNodeIds = handle.getNodeIds();
        state.allConnections = handle.getConnections();
        // Re-filter for current component
        this.filterVisibleElements(state);
        this.notifyListeners('highlightUpdated', {
            highlightId: handle.id,
            channel: handle.channel,
            highlight: this.getHighlightInfo(state)
        });
    }
    /**
     * Handle highlight dismissal from a HighlightHandle
     * @private
     */
    handleDismiss(handle) {
        const state = this.highlights.get(handle.id);
        if (!state)
            return;
        state.active = false;
        this.highlights.delete(handle.id);
        this.notifyListeners('highlightRemoved', {
            highlightId: handle.id,
            channel: handle.channel
        });
    }
    /**
     * Detect component boundaries in a path
     * Identifies where the path crosses between parent and child components
     *
     * @private
     */
    detectComponentBoundaries(_path) {
        // This is a simplified implementation
        // In a full implementation, we would:
        // 1. Get the component owner for each node from the model
        // 2. Detect transitions between different components
        // 3. Identify entry/exit nodes (Component Input/Output nodes)
        // For now, return empty array - will be enhanced when integrated with node models
        return [];
    }
    /**
     * Filter visible nodes and connections based on current component
     * Updates the state's visibleNodeIds and visibleConnections arrays
     *
     * @private
     */
    filterVisibleElements(state) {
        if (!this.currentComponentId) {
            // No component context - show everything
            state.visibleNodeIds = [...state.allNodeIds];
            state.visibleConnections = [...state.allConnections];
            return;
        }
        // Filter nodes - for now, show all (will be enhanced with component ownership checks)
        state.visibleNodeIds = [...state.allNodeIds];
        state.visibleConnections = [...state.allConnections];
        // TODO: When integrated with NodeGraphModel:
        // - Check node.model.owner to determine component
        // - Filter to only nodes belonging to currentComponentId
        // - Filter connections to only those where both nodes are visible
    }
    /**
     * Convert internal state to public HighlightInfo
     * @private
     */
    getHighlightInfo(state) {
        return {
            id: state.id,
            channel: state.channel,
            nodeIds: [...state.allNodeIds],
            connections: [...state.allConnections],
            options: { ...state.options },
            createdAt: state.createdAt
        };
    }
    /**
     * Subscribe to highlight events
     *
     * @example
     * ```typescript
     * const context = {};
     * HighlightManager.instance.on('highlightAdded', (data) => {
     *   console.log('New highlight:', data.highlightId);
     * }, context);
     * ```
     */
    on(event, callback, context) {
        // EventDispatcher expects a generic callback, cast to compatible type
        super.on(event, callback, context);
    }
    /**
     * Unsubscribe from highlight events
     */
    off(context) {
        super.off(context);
    }
}

;// ./src/editor/src/services/HighlightManager/community-showcase.ts
/**
 * 🎉 CANVAS HIGHLIGHTING API - COMMUNITY SHOWCASE
 *
 * Welcome back to Noodl! After a year of waiting, here's something special.
 *
 * USAGE:
 * 1. Open a component with nodes in the editor
 * 2. Open DevTools (View → Toggle Developer Tools)
 * 3. Paste this in the console:
 *
 *    noodlShowcase.start()
 *
 * Then sit back and enjoy! 🚀
 */

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function getNodes() {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const editor = window.__nodeGraphEditor;
    if (!(editor === null || editor === void 0 ? void 0 : editor.roots))
        return [];
    return editor.roots;
}
function log(emoji, msg) {
    console.log(`%c${emoji} ${msg}`, 'font-size: 14px; font-weight: bold;');
}
async function intro() {
    console.clear();
    log('🎬', 'NOODL CANVAS HIGHLIGHTING API');
    log('✨', "Worth the wait. Let's blow your mind.");
    await sleep(1500);
}
async function channelDemo() {
    const nodes = getNodes();
    if (nodes.length < 4) {
        log('⚠️', 'Need at least 4 nodes for full demo');
        return;
    }
    const channels = [
        { name: 'lineage', color: '#4A90D9', emoji: '🌊', label: 'Data Flow' },
        { name: 'impact', color: '#F5A623', emoji: '💥', label: 'Impact' },
        { name: 'selection', color: '#FFFFFF', emoji: '✨', label: 'Selection' },
        { name: 'warning', color: '#FF6B6B', emoji: '🔥', label: 'Warning' }
    ];
    for (let i = 0; i < channels.length; i++) {
        const ch = channels[i];
        log(ch.emoji, `Channel ${i + 1}: ${ch.label}`);
        HighlightManager.instance.highlightNodes([nodes[i].id], {
            channel: ch.name,
            color: ch.color,
            style: i % 2 === 0 ? 'glow' : 'pulse',
            label: ch.label
        });
        await sleep(800);
    }
    await sleep(2000);
    HighlightManager.instance.clearAll();
}
async function waveEffect() {
    const nodes = getNodes();
    if (nodes.length < 2)
        return;
    log('🌊', 'Wave Effect');
    const handles = [];
    for (let i = 0; i < Math.min(nodes.length, 8); i++) {
        handles.push(HighlightManager.instance.highlightNodes([nodes[i].id], {
            channel: 'lineage',
            color: `hsl(${i * 40}, 70%, 60%)`,
            style: 'glow'
        }));
        await sleep(150);
    }
    await sleep(1500);
    handles.forEach((h) => h.dismiss());
}
async function finale() {
    const nodes = getNodes();
    log('🎆', 'Grand Finale');
    const colors = ['#4A90D9', '#F5A623', '#9C27B0', '#FF6B6B'];
    const handles = [];
    nodes.forEach((node, i) => {
        handles.push(HighlightManager.instance.highlightNodes([node.id], {
            channel: 'impact',
            color: colors[i % colors.length],
            style: 'pulse'
        }));
    });
    await sleep(3000);
    log('✨', 'Fading out...');
    handles.forEach((h) => h.dismiss());
    await sleep(500);
}
async function start() {
    const nodes = getNodes();
    if (!nodes || nodes.length === 0) {
        console.error('❌ No nodes found. Open a component with nodes first!');
        return;
    }
    try {
        await intro();
        await channelDemo();
        await sleep(500);
        await waveEffect();
        await sleep(500);
        await finale();
        console.log('\n');
        log('🎉', 'Demo Complete!');
        log('📚', 'API Docs: Check HighlightManager.ts');
        log('💡', 'Try: HighlightManager.instance.highlightNodes([...])');
        log('🧹', 'Clear: HighlightManager.instance.clearAll()');
    }
    catch (error) {
        console.error('Demo error:', error);
    }
}
// Export for console access
const noodlShowcase = {
    start,
    clear: () => HighlightManager.instance.clearAll()
};
// Make globally available
if (typeof window !== 'undefined') {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    window.noodlShowcase = noodlShowcase;
    console.log('✅ Showcase loaded! Run: noodlShowcase.start()');
}

;// ./src/editor/src/services/HighlightManager/index.ts
/**
 * Canvas Highlighting API
 *
 * Public exports for the HighlightManager service.
 * Import from this file to use the highlighting system.
 *
 * @example
 * ```typescript
 * import { HighlightManager } from '@noodl/services/HighlightManager';
 *
 * const handle = HighlightManager.instance.highlightNodes(
 *   ['node1', 'node2'],
 *   { channel: 'lineage', label: 'Data flow' }
 * );
 * ```
 */
// Main service

// Channel utilities

// Community showcase demo



/***/ }),

/***/ 57286:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5, _path6, _path7, _path8, _path9;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgBorderDown = function SvgBorderDown(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M4.83008 4.15167C5.24429 4.15167 5.58008 4.48746 5.58008 4.90167C5.58008 5.31589 5.24429 5.65167 4.83008 5.65167C4.41586 5.65167 4.08008 5.31589 4.08008 4.90167C4.08008 4.48746 4.41586 4.15167 4.83008 4.15167Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M18.5718 4.15167C18.986 4.15167 19.3218 4.48746 19.3218 4.90167C19.3218 5.31589 18.986 5.65167 18.5718 5.65167C18.1576 5.65167 17.8218 5.31589 17.8218 4.90167C17.8218 4.48746 18.1576 4.15167 18.5718 4.15167Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M11.7007 4.15167C12.1149 4.15167 12.4507 4.48746 12.4507 4.90167C12.4507 5.31589 12.1149 5.65167 11.7007 5.65167C11.2865 5.65167 10.9507 5.31589 10.9507 4.90167C10.9507 4.48746 11.2865 4.15167 11.7007 4.15167Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M25.4429 4.15167C25.8571 4.15167 26.1929 4.48746 26.1929 4.90167C26.1929 5.31589 25.8571 5.65167 25.4429 5.65167C25.0287 5.65167 24.6929 5.31589 24.6929 4.90167C24.6929 4.48746 25.0287 4.15167 25.4429 4.15167Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M25.4434 17.8937C25.8576 17.8937 26.1934 18.2295 26.1934 18.6437C26.1934 19.058 25.8576 19.3937 25.4434 19.3937C25.0291 19.3937 24.6934 19.058 24.6934 18.6437C24.6934 18.2295 25.0291 17.8937 25.4434 17.8937Z",
    fill: "#F5F5F5"
  })), _path6 || (_path6 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M4.83057 17.8937C5.24478 17.8937 5.58057 18.2295 5.58057 18.6437C5.58057 19.058 5.24478 19.3937 4.83057 19.3937C4.41635 19.3937 4.08057 19.058 4.08057 18.6437C4.08057 18.2295 4.41635 17.8937 4.83057 17.8937Z",
    fill: "#F5F5F5"
  })), _path7 || (_path7 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M25.4429 11.0228C25.8571 11.0228 26.1929 11.3586 26.1929 11.7728C26.1929 12.187 25.8571 12.5228 25.4429 12.5228C25.0287 12.5228 24.6929 12.187 24.6929 11.7728C24.6929 11.3586 25.0287 11.0228 25.4429 11.0228Z",
    fill: "#F5F5F5"
  })), _path8 || (_path8 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M4.83008 11.0228C5.24429 11.0228 5.58008 11.3586 5.58008 11.7728C5.58008 12.187 5.24429 12.5228 4.83008 12.5228C4.41586 12.5228 4.08008 12.187 4.08008 11.7728C4.08008 11.3586 4.41586 11.0228 4.83008 11.0228Z",
    fill: "#F5F5F5"
  })), _path9 || (_path9 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M26.1934 25.6945C26.1934 26.1087 25.8576 26.4445 25.4434 26.4445L4.83081 26.4445C4.4166 26.4445 4.08081 26.1087 4.08081 25.6945C4.08081 25.2802 4.4166 24.9445 4.83081 24.9445L25.4434 24.9445C25.8576 24.9445 26.1934 25.2802 26.1934 25.6945Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgBorderDown);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "8c947e4ab327a07fc72cce1fd4ca3ecb.svg");

/***/ }),

/***/ 57534:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.HtmlRenderer-module__Root--p6ijJ *{color:var(--theme-color-fg-default);max-width:100%}.HtmlRenderer-module__Root--p6ijJ img{width:100%}.HtmlRenderer-module__Root--p6ijJ h1,.HtmlRenderer-module__Root--p6ijJ h2,.HtmlRenderer-module__Root--p6ijJ h3{font-weight:var(--font-weight-semibold)}.HtmlRenderer-module__Root--p6ijJ h1{color:var(--theme-color-fg-highlight)}.HtmlRenderer-module__Root--p6ijJ h2,.HtmlRenderer-module__Root--p6ijJ h3{padding-top:1em;color:var(--theme-color-fg-highlight)}.HtmlRenderer-module__Root--p6ijJ p{line-height:1.5}.HtmlRenderer-module__Root--p6ijJ strong,.HtmlRenderer-module__Root--p6ijJ .ndl-node{color:var(--theme-color-fg-highlight);font-weight:var(--font-weight-semibold)}.HtmlRenderer-module__Root--p6ijJ a{font-weight:var(--font-weight-semibold);text-decoration:underline;color:var(--theme-color-fg-highlight)}.HtmlRenderer-module__Root--p6ijJ a:hover{text-decoration:none;color:var(--theme-color-fg-highlight)}.HtmlRenderer-module__Root--p6ijJ .language-javascript{color:var(--theme-color-fg-highlight);background-color:var(--theme-color-bg-4);display:block;padding:5px;overflow:scroll}.HtmlRenderer-module__Root--p6ijJ .ndl-images{position:relative;text-align:center;display:flex;justify-content:center}.HtmlRenderer-module__Root--p6ijJ .ndl-image{height:auto;margin:5px;align-self:flex-start}.HtmlRenderer-module__Root--p6ijJ .ndl-image.small{width:30%}.HtmlRenderer-module__Root--p6ijJ .ndl-image.med{width:50%}.HtmlRenderer-module__Root--p6ijJ .ndl-image.large{width:100%}.HtmlRenderer-module__Root--p6ijJ .ndl-data{color:var(--theme-color-data)}.HtmlRenderer-module__Root--p6ijJ .ndl-signal{color:var(--theme-color-signal)}.HtmlRenderer-module__Root--p6ijJ code{color:var(--theme-color-bg-1);position:relative;overflow:hidden;border-radius:2px;padding:0px 4px 2px;margin:0px 2px;background-color:var(--theme-color-fg-muted);font-family:var(--font-family-code)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/common/HtmlRenderer/HtmlRenderer.module.scss"],"names":[],"mappings":"AAEI,oCACE,mCAAA,CACA,cAAA,CAGF,sCACE,UAAA,CAGF,+GAGE,uCAAA,CAGF,qCACE,qCAAA,CAGF,0EAEE,eAAA,CACA,qCAAA,CAGF,oCACE,eAAA,CAGF,qFAEE,qCAAA,CACA,uCAAA,CAGF,oCAEE,uCAAA,CACA,yBAAA,CACA,qCAAA,CAGF,0CAEE,oBAAA,CACA,qCAAA,CAGF,uDACE,qCAAA,CACA,wCAAA,CACA,aAAA,CACA,WAAA,CACA,eAAA,CAGF,8CACE,iBAAA,CACA,iBAAA,CACA,YAAA,CACA,sBAAA,CAGF,6CACE,WAAA,CACA,UAAA,CACA,qBAAA,CAGF,mDACE,SAAA,CAGF,iDACE,SAAA,CAGF,mDACE,UAAA,CAGF,4CACE,6BAAA,CAGF,8CACE,+BAAA,CAGF,uCACE,6BAAA,CACA,iBAAA,CACA,eAAA,CACA,iBAAA,CACA,mBAAA,CACA,cAAA,CACA,4CAAA,CACA,mCAAA","sourcesContent":[".Root {\n  :global {\n    * {\n      color: var(--theme-color-fg-default);\n      max-width: 100%;\n    }\n\n    img {\n      width: 100%;\n    }\n\n    h1,\n    h2,\n    h3 {\n      font-weight: var(--font-weight-semibold);\n    }\n\n    h1 {\n      color: var(--theme-color-fg-highlight);\n    }\n\n    h2,\n    h3 {\n      padding-top: 1em;\n      color: var(--theme-color-fg-highlight);\n    }\n\n    p {\n      line-height: 1.5;\n    }\n\n    strong,\n    .ndl-node {\n      color: var(--theme-color-fg-highlight);\n      font-weight: var(--font-weight-semibold);\n    }\n\n    a {\n      //color: #d49517;\n      font-weight: var(--font-weight-semibold);\n      text-decoration: underline;\n      color: var(--theme-color-fg-highlight);\n    }\n\n    a:hover {\n      //color: #fdb314;\n      text-decoration: none;\n      color: var(--theme-color-fg-highlight);\n    }\n\n    .language-javascript {\n      color: var(--theme-color-fg-highlight);\n      background-color: var(--theme-color-bg-4);\n      display: block;\n      padding: 5px;\n      overflow: scroll;\n    }\n\n    .ndl-images {\n      position: relative;\n      text-align: center;\n      display: flex;\n      justify-content: center;\n    }\n\n    .ndl-image {\n      height: auto;\n      margin: 5px;\n      align-self: flex-start;\n    }\n\n    .ndl-image.small {\n      width: 30%;\n    }\n\n    .ndl-image.med {\n      width: 50%;\n    }\n\n    .ndl-image.large {\n      width: 100%;\n    }\n\n    .ndl-data {\n      color: var(--theme-color-data);\n    }\n\n    .ndl-signal {\n      color: var(--theme-color-signal);\n    }\n\n    code {\n      color: var(--theme-color-bg-1);\n      position: relative;\n      overflow: hidden;\n      border-radius: 2px;\n      padding: 0px 4px 2px;\n      margin: 0px 2px;\n      background-color: var(--theme-color-fg-muted);\n      font-family: var(--font-family-code);\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `HtmlRenderer-module__Root--p6ijJ`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 57603:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  n: () => (/* binding */ createHash)
});

;// ./src/editor/src/utils/exporter/hash/wasm-hash.ts
/*
    MIT License http://www.opensource.org/licenses/mit-license.php
    Author Tobias Koppers @sokra
*/
// 65536 is the size of a wasm memory page
// 64 is the maximum chunk size for every possible wasm hash implementation
// 4 is the maximum number of bytes per char for string encoding (max is utf-8)
// ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
class WasmHash {
    /**
     * @param {WebAssembly.Instance} instance wasm instance
     * @param {WebAssembly.Instance[]} instancesPool pool of instances
     * @param {number} chunkSize size of data chunks passed to wasm
     * @param {number} digestSize size of digest returned by wasm
     */
    constructor(instance, instancesPool, chunkSize, digestSize) {
        const exports = /** @type {any} */ (instance.exports);
        exports.init();
        this.exports = exports;
        this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
        this.buffered = 0;
        this.instancesPool = instancesPool;
        this.chunkSize = chunkSize;
        this.digestSize = digestSize;
    }
    reset() {
        this.buffered = 0;
        this.exports.init();
    }
    /**
     * @param {Buffer | string} data data
     * @param {BufferEncoding=} encoding encoding
     * @returns {this} itself
     */
    update(data, encoding) {
        if (typeof data === "string") {
            while (data.length > MAX_SHORT_STRING) {
                this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
                data = data.slice(MAX_SHORT_STRING);
            }
            this._updateWithShortString(data, encoding);
            return this;
        }
        this._updateWithBuffer(data);
        return this;
    }
    /**
     * @param {string} data data
     * @param {BufferEncoding=} encoding encoding
     * @returns {void}
     */
    _updateWithShortString(data, encoding) {
        const { exports, buffered, mem, chunkSize } = this;
        let endPos;
        if (data.length < 70) {
            if (!encoding || encoding === "utf-8" || encoding === "utf8") {
                endPos = buffered;
                for (let i = 0; i < data.length; i++) {
                    const cc = data.charCodeAt(i);
                    if (cc < 0x80)
                        mem[endPos++] = cc;
                    else if (cc < 0x800) {
                        mem[endPos] = (cc >> 6) | 0xc0;
                        mem[endPos + 1] = (cc & 0x3f) | 0x80;
                        endPos += 2;
                    }
                    else {
                        // bail-out for weird chars
                        endPos += mem.write(data.slice(i), endPos, encoding);
                        break;
                    }
                }
            }
            else if (encoding === "latin1") {
                endPos = buffered;
                for (let i = 0; i < data.length; i++) {
                    const cc = data.charCodeAt(i);
                    mem[endPos++] = cc;
                }
            }
            else {
                endPos = buffered + mem.write(data, buffered, encoding);
            }
        }
        else {
            endPos = buffered + mem.write(data, buffered, encoding);
        }
        if (endPos < chunkSize) {
            this.buffered = endPos;
        }
        else {
            const l = endPos & ~(this.chunkSize - 1);
            exports.update(l);
            const newBuffered = endPos - l;
            this.buffered = newBuffered;
            if (newBuffered > 0)
                mem.copyWithin(0, l, endPos);
        }
    }
    /**
     * @param {Buffer} data data
     * @returns {void}
     */
    _updateWithBuffer(data) {
        const { exports, buffered, mem } = this;
        const length = data.length;
        if (buffered + length < this.chunkSize) {
            data.copy(mem, buffered, 0, length);
            this.buffered += length;
        }
        else {
            const l = (buffered + length) & ~(this.chunkSize - 1);
            if (l > 65536) {
                let i = 65536 - buffered;
                data.copy(mem, buffered, 0, i);
                exports.update(65536);
                const stop = l - buffered - 65536;
                while (i < stop) {
                    data.copy(mem, 0, i, i + 65536);
                    exports.update(65536);
                    i += 65536;
                }
                data.copy(mem, 0, i, l - buffered);
                exports.update(l - buffered - i);
            }
            else {
                data.copy(mem, buffered, 0, l - buffered);
                exports.update(l);
            }
            const newBuffered = length + buffered - l;
            this.buffered = newBuffered;
            if (newBuffered > 0)
                data.copy(mem, 0, length - newBuffered, length);
        }
    }
    digest(type) {
        const { exports, buffered, mem, digestSize } = this;
        exports.final(buffered);
        this.instancesPool.push(this);
        const hex = mem.toString("latin1", 0, digestSize);
        if (type === "hex")
            return hex;
        if (type === "binary" || !type)
            return Buffer.from(hex, "hex");
        return Buffer.from(hex, "hex").toString(type);
    }
}
function create(wasmModule, instancesPool, chunkSize, digestSize) {
    if (instancesPool.length > 0) {
        const old = instancesPool.pop();
        old.reset();
        return old;
    }
    else {
        return new WasmHash(new WebAssembly.Instance(wasmModule), instancesPool, chunkSize, digestSize);
    }
}
;

;// ./src/editor/src/utils/exporter/hash/xxhash64.ts
/*
    MIT License http://www.opensource.org/licenses/mit-license.php
    Author Tobias Koppers @sokra
*/

const xxhash64 = new WebAssembly.Module(Buffer.from(
// 1170 bytes
'AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrIIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqAYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEAgAiABNQIAQoeVr6+Ytt6bnn9+hUIXiULP1tO+0ser2UJ+Qvnz3fGZ9pmrFnwhAiABQQRqIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAkIdiCAChUL5893xmfaZqxZ+IgJCIIggAoUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL', 'base64'));
const createHash = create.bind(null, xxhash64, [], 32, 16);


/***/ }),

/***/ 57768:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSquare = function SvgSquare(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.00889 5.00895L5.00889 18.9911H18.991V5.00895L5.00889 5.00895ZM3.08032 4.76788C3.08032 3.8359 3.83584 3.08038 4.76782 3.08038L19.2321 3.08038C20.1641 3.08038 20.9196 3.8359 20.9196 4.76788L20.9196 19.2322C20.9196 20.1642 20.1641 20.9197 19.2321 20.9197L4.76782 20.9197C3.83584 20.9197 3.08032 20.1642 3.08032 19.2322L3.08032 4.76788Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSquare);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "cfe186ad2488aafd0f05d6c1b0e13ea6.svg");

/***/ }),

/***/ 57992:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   EY: () => (/* binding */ getRemoteURL),
/* harmony export */   K7: () => (/* binding */ getRemotes),
/* harmony export */   Uu: () => (/* binding */ addRemote),
/* harmony export */   gK: () => (/* binding */ setRemoteURL)
/* harmony export */ });
/* unused harmony export removeRemote */
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81882);
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(dugite__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(85869);


/**
 * List the remotes, sorted alphabetically by `name`, for a repository.
 */
async function getRemotes(basePath) {
    const result = await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(['remote', '-v'], basePath, 'getRemotes', {
        expectedErrors: new Set([dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.NotAGitRepository])
    });
    if (result.gitError === dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.NotAGitRepository) {
        return [];
    }
    const output = result.output.toString();
    const lines = output.split('\n');
    const remotes = lines
        .filter((x) => x.endsWith('(fetch)'))
        .map((x) => x.split(/\s+/))
        .map((x) => ({ name: x[0], url: x[1] }));
    return remotes;
}
/** Add a new remote with the given URL. */
async function addRemote(basePath, name, url) {
    await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(['remote', 'add', name, url], basePath, 'addRemote');
    return { url, name };
}
/** Removes an existing remote, or silently errors if it doesn't exist */
async function removeRemote(basePath, name) {
    const options = {
        successExitCodes: new Set([0, 2, 128])
    };
    await git(['remote', 'remove', name], basePath, 'removeRemote', options);
}
/** Changes the URL for the remote that matches the given name  */
async function setRemoteURL(basePath, name, url) {
    await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(['remote', 'set-url', name, url], basePath, 'setRemoteURL');
    return true;
}
/**
 * Get the URL for the remote that matches the given name.
 *
 * Returns null if the remote could not be found
 */
async function getRemoteURL(basePath, name) {
    const result = await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(['remote', 'get-url', name], basePath, 'getRemoteURL', {
        successExitCodes: new Set([0, 2, 128])
    });
    if (result.exitCode !== 0) {
        return null;
    }
    return result.output.toString();
}


/***/ }),

/***/ 58237:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgButton = function SvgButton(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.30713 10.7442H25.8038C26.356 10.7442 26.8038 11.1919 26.8038 11.7442V19.1172C26.8038 19.6695 26.356 20.1904 25.8038 20.1904H4.30713C3.75484 20.1904 3.30713 19.6695 3.30713 19.1172V11.7442C3.30713 11.1919 3.75484 10.7442 4.30713 10.7442ZM9.02148 16.6246C9.66549 16.6246 10.1876 16.1025 10.1876 15.4585C10.1876 14.8145 9.66549 14.2924 9.02148 14.2924C8.37747 14.2924 7.8554 14.8145 7.8554 15.4585C7.8554 16.1025 8.37747 16.6246 9.02148 16.6246ZM16.2198 15.4585C16.2198 16.1025 15.6977 16.6246 15.0537 16.6246C14.4097 16.6246 13.8876 16.1025 13.8876 15.4585C13.8876 14.8145 14.4097 14.2924 15.0537 14.2924C15.6977 14.2924 16.2198 14.8145 16.2198 15.4585ZM21.0859 16.6246C21.7299 16.6246 22.252 16.1025 22.252 15.4585C22.252 14.8145 21.7299 14.2924 21.0859 14.2924C20.4419 14.2924 19.9199 14.8145 19.9199 15.4585C19.9199 16.1025 20.4419 16.6246 21.0859 16.6246Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgButton);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "9aa3f713c8a3f314863df18b11527fdc.svg");

/***/ }),

/***/ 58310:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPaletteFill = function SvgPaletteFill(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.1401 3.51041C14.5038 3.50876 16.7726 4.44057 18.4528 6.10312C19.3025 6.92856 19.9794 7.91494 20.4439 9.00472C20.9084 10.0945 21.1512 11.2659 21.1582 12.4505C21.1662 13.1507 21.0905 13.8494 20.9328 14.5316C20.7976 15.1471 20.4551 15.6974 19.9626 16.0905C19.4701 16.4836 18.8575 16.6955 18.2274 16.6908L14.4204 16.3585C14.0524 16.3585 13.5197 16.6482 13.2596 16.9084C12.9994 17.1686 12.8338 17.7102 12.8338 18.0782V18.4164C12.8339 18.8598 12.7277 19.2968 12.5241 19.6908C12.3206 20.0847 12.0255 20.4242 11.6638 20.6806C11.302 20.9371 10.8841 21.1031 10.4449 21.1648C10.0058 21.2264 9.55826 21.182 9.13985 21.0351C7.13912 20.3312 5.45052 18.9446 4.37079 17.119C3.29107 15.2935 2.88933 13.1458 3.23616 11.0534C3.583 8.961 4.65622 7.0578 6.26721 5.67827C7.8782 4.29873 9.92388 3.53115 12.0447 3.51041H12.1401ZM8.57594 14.277C8.57594 15.1607 7.8596 15.877 6.97594 15.877C6.09228 15.877 5.37594 15.1607 5.37594 14.277C5.37594 13.3934 6.09228 12.677 6.97594 12.677C7.8596 12.677 8.57594 13.3934 8.57594 14.277ZM7.9206 10.4674C8.80426 10.4674 9.5206 9.7511 9.5206 8.86744C9.5206 7.98378 8.80426 7.26744 7.9206 7.26744C7.03695 7.26744 6.3206 7.98378 6.3206 8.86744C6.3206 9.7511 7.03695 10.4674 7.9206 10.4674ZM14.6854 6.96071C14.6854 7.84436 13.9691 8.56071 13.0854 8.56071C12.2018 8.56071 11.4854 7.84436 11.4854 6.96071C11.4854 6.07705 12.2018 5.36071 13.0854 5.36071C13.9691 5.36071 14.6854 6.07705 14.6854 6.96071ZM17.3841 12.1538C18.2678 12.1538 18.9841 11.4374 18.9841 10.5538C18.9841 9.67013 18.2678 8.95378 17.3841 8.95378C16.5005 8.95378 15.7841 9.67013 15.7841 10.5538C15.7841 11.4374 16.5005 12.1538 17.3841 12.1538Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPaletteFill);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "c7b433eb3ee48060954e5778d13a6fb3.svg");

/***/ }),

/***/ 58379:
/***/ ((module) => {

"use strict";
module.exports = require("bcryptjs");

/***/ }),

/***/ 58541:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (/* binding */ useWindowSize)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

function getWindowSize() {
    return {
        width: window.innerWidth,
        height: window.innerHeight
    };
}
function useWindowSize(debounceMs = 250) {
    const [size, setSize] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(getWindowSize());
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        let debounceTimeoutId;
        function onResize() {
            clearTimeout(debounceTimeoutId);
            debounceTimeoutId = setTimeout(() => setSize(getWindowSize()), debounceMs);
        }
        window.addEventListener('resize', onResize);
        return () => {
            window.removeEventListener('resize', onResize);
            clearTimeout(debounceTimeoutId);
        };
    }, [debounceMs]);
    return size;
}


/***/ }),

/***/ 58788:
/***/ ((module) => {

"use strict";
module.exports = require("passport");

/***/ }),

/***/ 58801:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCheckboxFilled = function SvgCheckboxFilled(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 30,
    height: 30,
    viewBox: "0 0 30 30",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.25 4.95909C3.25 4.01519 4.01519 3.25 4.95909 3.25H25.0409C25.9848 3.25 26.75 4.01519 26.75 4.95909V25.0409C26.75 25.9848 25.9848 26.75 25.0409 26.75H4.95909C4.01519 26.75 3.25 25.9848 3.25 25.0409V4.95909ZM21.8351 12.6168C22.3046 12.1689 22.3221 11.4251 21.8742 10.9556C21.4262 10.486 20.6825 10.4685 20.2129 10.9165L13.1938 17.6128L10.0961 14.6525C9.6269 14.2042 8.88313 14.2211 8.43479 14.6902C7.98645 15.1594 8.00332 15.9031 8.47248 16.3515L12.3813 20.0869C12.8352 20.5206 13.5499 20.5209 14.0041 20.0875L21.8351 12.6168Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCheckboxFilled);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "78e745da66f2527c36e195328eb514d8.svg");

/***/ }),

/***/ 58848:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   id: () => (/* binding */ clearCredentialsCache),
/* harmony export */   qM: () => (/* binding */ askpassTrampolineHandler),
/* harmony export */   x$: () => (/* binding */ setRequestGitAccount)
/* harmony export */ });
/* unused harmony export fetchAccount */
let requestGitAccount = undefined;
function setRequestGitAccount(func) {
    clearCredentialsCache();
    requestGitAccount = func;
}
function clearCredentialsCache() {
    accounts.clear();
}
const accounts = new Map();
const ACCOUNT_CACHE_TTL = 5 * 60 * 1000;
async function fetchAccount(endpoint, token) {
    const now = Date.now();
    if (accounts.has(endpoint)) {
        const account = accounts.get(endpoint);
        // Check if it has expired
        const expired = account.updatedAt + ACCOUNT_CACHE_TTL < now;
        if (!expired) {
            return account;
        }
    }
    if (!requestGitAccount) {
        throw new Error('Git Authentication is not configured');
    }
    // Fetch the account
    let account;
    try {
        account = await requestGitAccount(endpoint);
    }
    catch (e) {
        console.log('Failed to get git auth', e);
        return undefined;
    }
    // Create cache entry
    const entry = { ...account, updatedAt: now };
    accounts.set(endpoint, entry);
    return entry;
}
const endpointRegex = /\/\/(\w+@?(.+))'/;
const askpassTrampolineHandler = async (command) => {
    if (command.parameters.length !== 1) {
        return undefined;
    }
    // Example:
    // "Username for 'https://ngit1.noodlapp.com': "
    // "Password for 'https://a@ngit1.noodlapp.com': "
    const firstParameter = command.parameters[0];
    const askUsername = firstParameter.startsWith('Username');
    const askPassword = firstParameter.startsWith('Password');
    if (askUsername || askPassword) {
        const endpointMatch = firstParameter.match(endpointRegex);
        if (endpointMatch.length !== 3) {
            throw new Error('Unable to read the git endpoint.');
        }
        const endpoint = endpointMatch[1];
        // Fetch the account with
        const account = await fetchAccount(endpoint, command.trampolineToken);
        if (!account) {
            return undefined;
        }
        // Return the username or password based on request
        if (askUsername) {
            return account === null || account === void 0 ? void 0 : account.username;
        }
        else if (askPassword) {
            return account === null || account === void 0 ? void 0 : account.password;
        }
    }
    return undefined;
};


/***/ }),

/***/ 58973:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.AiChatboxError-module__Root--msw1c{height:100%;padding:32px;box-sizing:border-box;display:flex;justify-content:center;align-items:center;flex-direction:column}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/ai/AiChatboxError/AiChatboxError.module.scss"],"names":[],"mappings":"AAAA,oCACE,WAAA,CACA,YAAA,CACA,qBAAA,CACA,YAAA,CACA,sBAAA,CACA,kBAAA,CACA,qBAAA","sourcesContent":[".Root {\n  height: 100%;\n  padding: 32px;\n  box-sizing: border-box;\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  flex-direction: column;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `AiChatboxError-module__Root--msw1c`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 59048:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.AddBackendDialog-module__PresetGrid--Guvpx{display:grid;grid-template-columns:repeat(2, 1fr);gap:8px;margin-bottom:16px}.AddBackendDialog-module__PresetCard--y1Lfv{display:flex;flex-direction:column;align-items:center;gap:4px;padding:12px;background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:6px;cursor:pointer;transition:all .15s ease;text-align:center}.AddBackendDialog-module__PresetCard--y1Lfv:hover{background-color:var(--theme-color-bg-2);border-color:var(--theme-color-border-highlight)}.AddBackendDialog-module__PresetCard--y1Lfv.AddBackendDialog-module__Selected--bXyGZ{border-color:var(--theme-color-primary);background-color:var(--theme-color-primary-bg)}.AddBackendDialog-module__PresetIcon--Rzry0{width:36px;height:36px;display:flex;align-items:center;justify-content:center;background-color:var(--theme-color-bg-1);border-radius:8px;font-size:16px;font-weight:600;color:var(--theme-color-fg-highlight);margin-bottom:4px}.AddBackendDialog-module__TestResult--xY7BS{padding:8px 12px;border-radius:4px;border:1px solid}.AddBackendDialog-module__FieldNote--HP2dB{display:flex;align-items:center;gap:6px;margin-top:6px;padding:4px 0}.AddBackendDialog-module__LockIcon--fZdrh,.AddBackendDialog-module__WarningIcon--altnn{font-size:12px;line-height:1}.AddBackendDialog-module__HelpPopupOverlay--umMOE{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;z-index:10000}.AddBackendDialog-module__HelpPopup--AJPFw{background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:8px;max-width:480px;max-height:80vh;overflow:hidden;display:flex;flex-direction:column;box-shadow:0 8px 32px rgba(0,0,0,.4)}.AddBackendDialog-module__HelpPopupHeader--fwWAK{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-3)}.AddBackendDialog-module__HelpPopupContent--fSU7Q{padding:16px;overflow-y:auto;line-height:1.6}.AddBackendDialog-module__HelpPopupContent--fSU7Q p{margin:0 0 12px 0;color:var(--theme-color-fg-default);font-size:13px}.AddBackendDialog-module__HelpPopupContent--fSU7Q p:last-child{margin-bottom:0}.AddBackendDialog-module__HelpPopupContent--fSU7Q p:empty{margin-bottom:8px}.AddBackendDialog-module__HelpPopupContent--fSU7Q strong{color:var(--theme-color-fg-highlight);font-weight:600}.AddBackendDialog-module__HelpHeading--ng4uj{font-size:14px !important;margin-top:16px !important;margin-bottom:8px !important}.AddBackendDialog-module__HelpHeading--ng4uj:first-child{margin-top:0 !important}.AddBackendDialog-module__InlineCode--ywOnr{background-color:var(--theme-color-bg-1);color:var(--theme-color-primary);padding:2px 6px;border-radius:3px;font-family:"Monaco","Menlo",monospace;font-size:12px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/BackendServicesPanel/AddBackendDialog/AddBackendDialog.module.scss"],"names":[],"mappings":"AAMA,4CACE,YAAA,CACA,oCAAA,CACA,OAAA,CACA,kBAAA,CAGF,4CACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,OAAA,CACA,YAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CACA,iBAAA,CAEA,kDACE,wCAAA,CACA,gDAAA,CAGF,qFACE,uCAAA,CACA,8CAAA,CAIJ,4CACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CACA,iBAAA,CAGF,4CACE,gBAAA,CACA,iBAAA,CACA,gBAAA,CAIF,2CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,cAAA,CACA,aAAA,CAGF,uFAEE,cAAA,CACA,aAAA,CAIF,kDACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,+BAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,aAAA,CAIF,2CACE,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,eAAA,CACA,eAAA,CACA,eAAA,CACA,YAAA,CACA,qBAAA,CACA,oCAAA,CAGF,iDACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,iBAAA,CACA,yDAAA,CACA,wCAAA,CAGF,kDACE,YAAA,CACA,eAAA,CACA,eAAA,CAEA,oDACE,iBAAA,CACA,mCAAA,CACA,cAAA,CAEA,+DACE,eAAA,CAGF,0DACE,iBAAA,CAIJ,yDACE,qCAAA,CACA,eAAA,CAIJ,6CACE,yBAAA,CACA,0BAAA,CACA,4BAAA,CAEA,yDACE,uBAAA,CAIJ,4CACE,wCAAA,CACA,gCAAA,CACA,eAAA,CACA,iBAAA,CACA,sCAAA,CACA,cAAA","sourcesContent":["/**\n * Add Backend Dialog Styles\n * \n * @module BackendServicesPanel\n */\n\n.PresetGrid {\n  display: grid;\n  grid-template-columns: repeat(2, 1fr);\n  gap: 8px;\n  margin-bottom: 16px;\n}\n\n.PresetCard {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 4px;\n  padding: 12px;\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 6px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n  text-align: center;\n\n  &:hover {\n    background-color: var(--theme-color-bg-2);\n    border-color: var(--theme-color-border-highlight);\n  }\n\n  &.Selected {\n    border-color: var(--theme-color-primary);\n    background-color: var(--theme-color-primary-bg);\n  }\n}\n\n.PresetIcon {\n  width: 36px;\n  height: 36px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  background-color: var(--theme-color-bg-1);\n  border-radius: 8px;\n  font-size: 16px;\n  font-weight: 600;\n  color: var(--theme-color-fg-highlight);\n  margin-bottom: 4px;\n}\n\n.TestResult {\n  padding: 8px 12px;\n  border-radius: 4px;\n  border: 1px solid;\n}\n\n// Field note with icon\n.FieldNote {\n  display: flex;\n  align-items: center;\n  gap: 6px;\n  margin-top: 6px;\n  padding: 4px 0;\n}\n\n.LockIcon,\n.WarningIcon {\n  font-size: 12px;\n  line-height: 1;\n}\n\n// Help Popup Overlay\n.HelpPopupOverlay {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.6);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 10000;\n}\n\n// Help Popup Content\n.HelpPopup {\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 8px;\n  max-width: 480px;\n  max-height: 80vh;\n  overflow: hidden;\n  display: flex;\n  flex-direction: column;\n  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);\n}\n\n.HelpPopupHeader {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 12px 16px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-3);\n}\n\n.HelpPopupContent {\n  padding: 16px;\n  overflow-y: auto;\n  line-height: 1.6;\n\n  p {\n    margin: 0 0 12px 0;\n    color: var(--theme-color-fg-default);\n    font-size: 13px;\n\n    &:last-child {\n      margin-bottom: 0;\n    }\n\n    &:empty {\n      margin-bottom: 8px;\n    }\n  }\n\n  strong {\n    color: var(--theme-color-fg-highlight);\n    font-weight: 600;\n  }\n}\n\n.HelpHeading {\n  font-size: 14px !important;\n  margin-top: 16px !important;\n  margin-bottom: 8px !important;\n\n  &:first-child {\n    margin-top: 0 !important;\n  }\n}\n\n.InlineCode {\n  background-color: var(--theme-color-bg-1);\n  color: var(--theme-color-primary);\n  padding: 2px 6px;\n  border-radius: 3px;\n  font-family: 'Monaco', 'Menlo', monospace;\n  font-size: 12px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"PresetGrid": `AddBackendDialog-module__PresetGrid--Guvpx`,
	"PresetCard": `AddBackendDialog-module__PresetCard--y1Lfv`,
	"Selected": `AddBackendDialog-module__Selected--bXyGZ`,
	"PresetIcon": `AddBackendDialog-module__PresetIcon--Rzry0`,
	"TestResult": `AddBackendDialog-module__TestResult--xY7BS`,
	"FieldNote": `AddBackendDialog-module__FieldNote--HP2dB`,
	"LockIcon": `AddBackendDialog-module__LockIcon--fZdrh`,
	"WarningIcon": `AddBackendDialog-module__WarningIcon--altnn`,
	"HelpPopupOverlay": `AddBackendDialog-module__HelpPopupOverlay--umMOE`,
	"HelpPopup": `AddBackendDialog-module__HelpPopup--AJPFw`,
	"HelpPopupHeader": `AddBackendDialog-module__HelpPopupHeader--fwWAK`,
	"HelpPopupContent": `AddBackendDialog-module__HelpPopupContent--fSU7Q`,
	"HelpHeading": `AddBackendDialog-module__HelpHeading--ng4uj`,
	"InlineCode": `AddBackendDialog-module__InlineCode--ywOnr`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 59081:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getDefaultFetch = getDefaultFetch;
exports.makeReadableStream = makeReadableStream;
exports.ReadableStreamFrom = ReadableStreamFrom;
exports.ReadableStreamToAsyncIterable = ReadableStreamToAsyncIterable;
exports.CancelReadableStream = CancelReadableStream;
function getDefaultFetch() {
    if (typeof fetch !== 'undefined') {
        return fetch;
    }
    throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`');
}
function makeReadableStream(...args) {
    const ReadableStream = globalThis.ReadableStream;
    if (typeof ReadableStream === 'undefined') {
        // Note: All of the platforms / runtimes we officially support already define
        // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes.
        throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`');
    }
    return new ReadableStream(...args);
}
function ReadableStreamFrom(iterable) {
    let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
    return makeReadableStream({
        start() { },
        async pull(controller) {
            const { done, value } = await iter.next();
            if (done) {
                controller.close();
            }
            else {
                controller.enqueue(value);
            }
        },
        async cancel() {
            await iter.return?.();
        },
    });
}
/**
 * Most browsers don't yet have async iterable support for ReadableStream,
 * and Node has a very different way of reading bytes from its "ReadableStream".
 *
 * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
 */
function ReadableStreamToAsyncIterable(stream) {
    if (stream[Symbol.asyncIterator])
        return stream;
    const reader = stream.getReader();
    return {
        async next() {
            try {
                const result = await reader.read();
                if (result?.done)
                    reader.releaseLock(); // release lock when stream becomes closed
                return result;
            }
            catch (e) {
                reader.releaseLock(); // release lock when stream becomes errored
                throw e;
            }
        },
        async return() {
            const cancelPromise = reader.cancel();
            reader.releaseLock();
            await cancelPromise;
            return { done: true, value: undefined };
        },
        [Symbol.asyncIterator]() {
            return this;
        },
    };
}
/**
 * Cancels a ReadableStream we don't need to consume.
 * See https://undici.nodejs.org/#/?id=garbage-collection
 */
async function CancelReadableStream(stream) {
    if (stream === null || typeof stream !== 'object')
        return;
    if (stream[Symbol.asyncIterator]) {
        await stream[Symbol.asyncIterator]().return?.();
        return;
    }
    const reader = stream.getReader();
    const cancelPromise = reader.cancel();
    reader.releaseLock();
    await cancelPromise;
}
//# sourceMappingURL=shims.js.map

/***/ }),

/***/ 59089:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.codicon-wrench-subaction {
	opacity: 0.5;
}

@keyframes codicon-spin {
	100% {
		transform:rotate(360deg);
	}
}

.codicon-sync.codicon-modifier-spin,
.codicon-loading.codicon-modifier-spin,
.codicon-gear.codicon-modifier-spin,
.codicon-notebook-state-executing.codicon-modifier-spin {
	/* Use steps to throttle FPS to reduce CPU usage */
	animation: codicon-spin 1.5s steps(30) infinite;
}

.codicon-modifier-disabled {
	opacity: 0.4;
}

/* custom speed & easing for loading icon */
.codicon-loading,
.codicon-tree-item-loading::before {
	animation-duration: 1s !important;
	animation-timing-function: cubic-bezier(0.53, 0.21, 0.29, 0.67) !important;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/codicons/codicon/codicon-modifiers.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,YAAY;AACb;;AAEA;CACC;EACC,wBAAwB;CACzB;AACD;;AAEA;;;;CAIC,kDAAkD;CAClD,+CAA+C;AAChD;;AAEA;CACC,YAAY;AACb;;AAEA,2CAA2C;AAC3C;;CAEC,iCAAiC;CACjC,0EAA0E;AAC3E","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.codicon-wrench-subaction {\n\topacity: 0.5;\n}\n\n@keyframes codicon-spin {\n\t100% {\n\t\ttransform:rotate(360deg);\n\t}\n}\n\n.codicon-sync.codicon-modifier-spin,\n.codicon-loading.codicon-modifier-spin,\n.codicon-gear.codicon-modifier-spin,\n.codicon-notebook-state-executing.codicon-modifier-spin {\n\t/* Use steps to throttle FPS to reduce CPU usage */\n\tanimation: codicon-spin 1.5s steps(30) infinite;\n}\n\n.codicon-modifier-disabled {\n\topacity: 0.4;\n}\n\n/* custom speed & easing for loading icon */\n.codicon-loading,\n.codicon-tree-item-loading::before {\n\tanimation-duration: 1s !important;\n\tanimation-timing-function: cubic-bezier(0.53, 0.21, 0.29, 0.67) !important;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 59215:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Skills = void 0;
const tslib_1 = __webpack_require__(84499);
const resource_1 = __webpack_require__(39929);
const VersionsAPI = tslib_1.__importStar(__webpack_require__(67652));
const versions_1 = __webpack_require__(67652);
const pagination_1 = __webpack_require__(92081);
const headers_1 = __webpack_require__(79973);
const uploads_1 = __webpack_require__(76409);
const path_1 = __webpack_require__(20854);
class Skills extends resource_1.APIResource {
    constructor() {
        super(...arguments);
        this.versions = new VersionsAPI.Versions(this._client);
    }
    /**
     * Create Skill
     *
     * @example
     * ```ts
     * const skill = await client.beta.skills.create();
     * ```
     */
    create(params = {}, options) {
        const { betas, ...body } = params ?? {};
        return this._client.post('/v1/skills?beta=true', (0, uploads_1.multipartFormRequestOptions)({
            body,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
                options?.headers,
            ]),
        }, this._client));
    }
    /**
     * Get Skill
     *
     * @example
     * ```ts
     * const skill = await client.beta.skills.retrieve('skill_id');
     * ```
     */
    retrieve(skillID, params = {}, options) {
        const { betas } = params ?? {};
        return this._client.get((0, path_1.path) `/v1/skills/${skillID}?beta=true`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * List Skills
     *
     * @example
     * ```ts
     * // Automatically fetches more pages as needed.
     * for await (const skillListResponse of client.beta.skills.list()) {
     *   // ...
     * }
     * ```
     */
    list(params = {}, options) {
        const { betas, ...query } = params ?? {};
        return this._client.getAPIList('/v1/skills?beta=true', (pagination_1.PageCursor), {
            query,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * Delete Skill
     *
     * @example
     * ```ts
     * const skill = await client.beta.skills.delete('skill_id');
     * ```
     */
    delete(skillID, params = {}, options) {
        const { betas } = params ?? {};
        return this._client.delete((0, path_1.path) `/v1/skills/${skillID}?beta=true`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
                options?.headers,
            ]),
        });
    }
}
exports.Skills = Skills;
Skills.Versions = versions_1.Versions;
//# sourceMappingURL=skills.js.map

/***/ }),

/***/ 59303:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.code-editor__inline__error {
  text-decoration: underline;
  text-decoration-color: red;
}

.code-editor__line__error {
  background: #f00;
  width: 5px !important;
  margin-left: 3px;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/propertyeditor/CodeEditor/CodeEditor.css"],"names":[],"mappings":"AAAA;EACE,0BAA0B;EAC1B,0BAA0B;AAC5B;;AAEA;EACE,gBAAgB;EAChB,qBAAqB;EACrB,gBAAgB;AAClB","sourcesContent":[".code-editor__inline__error {\n  text-decoration: underline;\n  text-decoration-color: red;\n}\n\n.code-editor__line__error {\n  background: #f00;\n  width: 5px !important;\n  margin-left: 3px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 59347:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.formatRequestDetails = exports.parseLogLevel = void 0;
exports.loggerFor = loggerFor;
const values_1 = __webpack_require__(25267);
const levelNumbers = {
    off: 0,
    error: 200,
    warn: 300,
    info: 400,
    debug: 500,
};
const parseLogLevel = (maybeLevel, sourceName, client) => {
    if (!maybeLevel) {
        return undefined;
    }
    if ((0, values_1.hasOwn)(levelNumbers, maybeLevel)) {
        return maybeLevel;
    }
    loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
    return undefined;
};
exports.parseLogLevel = parseLogLevel;
function noop() { }
function makeLogFn(fnLevel, logger, logLevel) {
    if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
        return noop;
    }
    else {
        // Don't wrap logger functions, we want the stacktrace intact!
        return logger[fnLevel].bind(logger);
    }
}
const noopLogger = {
    error: noop,
    warn: noop,
    info: noop,
    debug: noop,
};
let cachedLoggers = /* @__PURE__ */ new WeakMap();
function loggerFor(client) {
    const logger = client.logger;
    const logLevel = client.logLevel ?? 'off';
    if (!logger) {
        return noopLogger;
    }
    const cachedLogger = cachedLoggers.get(logger);
    if (cachedLogger && cachedLogger[0] === logLevel) {
        return cachedLogger[1];
    }
    const levelLogger = {
        error: makeLogFn('error', logger, logLevel),
        warn: makeLogFn('warn', logger, logLevel),
        info: makeLogFn('info', logger, logLevel),
        debug: makeLogFn('debug', logger, logLevel),
    };
    cachedLoggers.set(logger, [logLevel, levelLogger]);
    return levelLogger;
}
const formatRequestDetails = (details) => {
    if (details.options) {
        details.options = { ...details.options };
        delete details.options['headers']; // redundant + leaks internals
    }
    if (details.headers) {
        details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
            name,
            (name.toLowerCase() === 'x-api-key' ||
                name.toLowerCase() === 'authorization' ||
                name.toLowerCase() === 'cookie' ||
                name.toLowerCase() === 'set-cookie') ?
                '***'
                : value,
        ]));
    }
    if ('retryOfRequestLogID' in details) {
        if (details.retryOfRequestLogID) {
            details.retryOf = details.retryOfRequestLogID;
        }
        delete details.retryOfRequestLogID;
    }
    return details;
};
exports.formatRequestDetails = formatRequestDetails;
//# sourceMappingURL=log.js.map

/***/ }),

/***/ 59474:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgAlignItemLeft = function SvgAlignItemLeft(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M8.24609 17.4261L17.4336 17.4261C17.796 17.4261 18.0898 17.1703 18.0898 16.8547L18.0898 13.9976C18.0898 13.682 17.796 13.4261 17.4336 13.4261L8.24609 13.4261C7.88366 13.4261 7.58984 13.682 7.58984 13.9976L7.58984 16.8547C7.58984 17.1703 7.88366 17.4261 8.24609 17.4261Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M8.15234 11.9261L16.0273 11.9261C16.338 11.9261 16.5898 11.6703 16.5898 11.3547L16.5898 8.49758C16.5898 8.18198 16.338 7.92615 16.0273 7.92615L8.15234 7.92615C7.84168 7.92615 7.58984 8.18198 7.58984 8.49757L7.58984 11.3547C7.58984 11.6703 7.84168 11.9261 8.15234 11.9261Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.33984 21.6761C4.92563 21.6761 4.58984 21.318 4.58984 20.8761L4.58985 4.47617C4.58985 4.03433 4.92563 3.67615 5.33985 3.67615C5.75406 3.67615 6.08985 4.03433 6.08985 4.47617L6.08984 20.8761C6.08984 21.318 5.75406 21.6761 5.33984 21.6761Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgAlignItemLeft);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "779a18fc9e84e6018811176ac9db98b8.svg");

/***/ }),

/***/ 59638:
/***/ ((module) => {

"use strict";
module.exports = require("fs-extra");

/***/ }),

/***/ 59734:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

class ProjectValidator {
  constructor() {
    this.errors = [];
  }

  expectNotUndefined(value, msg) {
    if (value === undefined) {
      this.error(msg);
    }
  }

  expectTrue(value, msg) {
    if (!value) {
      this.error(msg);
    }
  }

  error(msg, args) {
    this.errors.push({
      msg,
      args
    });
  }

  validateType(type) {
    this.expectTrue(type !== undefined, 'Node is missing type');
    this.expectTrue(typeof type === 'string' || typeof type === 'object', 'Type should be string or object');
  }

  validateNode(n) {
    this.validateType(n.type);

    this.expectTrue(typeof n.id === 'string', 'Node, id is not valid');
    this.expectTrue(typeof n.x === 'number' || typeof n.x === 'undefined', 'Node, x position should be number');
    this.expectTrue(typeof n.y === 'number' || typeof n.y === 'undefined', 'Node, y position should be number');
    this.expectTrue(typeof n.parameters === 'object', 'Node, invalid parameters');
  }

  validateComponent(c) {
    var _this = this;

    var graph = c.graph;

    this.expectTrue(typeof c.name === 'string', 'Component is missing name');
    this.expectTrue(graph !== undefined, 'Component does not have a graph ' + c.name);

    this.expectTrue(
      graph.roots !== undefined && Array.isArray(graph.roots),
      'Component does not have a roots array ' + c.name
    );

    this.expectTrue(
      graph.connections !== undefined && Array.isArray(graph.connections),
      'Component does not have a connections array ' + c.name
    );

    var nodes = {};

    function _collectNodes(ns) {
      ns.forEach((n) => {
        _this.validateNode(n);
        nodes[n.id] = n;
        if (n.children !== undefined) _collectNodes(n.children);
      });
    }
    graph.roots !== undefined && _collectNodes(graph.roots);

    graph.connections !== undefined &&
      graph.connections.forEach((con) => {
        if (nodes[con.fromId] === undefined || nodes[con.toId] === undefined) {
          // This connection is dangling
          var missing =
            (nodes[con.fromId] === undefined ? 'missing source ' : '') +
            (nodes[con.toId] === undefined ? 'missing target ' : '');
          this.error('Dangling connection at ' + c.name + ' ' + missing, {
            con,
            graph,
            fix: function () {
              var idx = this.graph.connections.indexOf(con);
              if (idx !== -1) this.graph.connections.splice(idx, 1);
            }
          });
        }
      });
  }

  validate(json) {
    if (!json) json = this.json;

    this.expectTrue(typeof json.name === 'string', 'Project is missing name');

    this.expectTrue(json.components !== undefined && Array.isArray(json.components), 'Project is missing components');

    json.components !== undefined &&
      json.components.forEach((c) => {
        this.validateComponent(c);
      });
  }

  validateProjectDirectory(dir) {
    const FileSystem = __webpack_require__(38656);

    try {
      var content = FileSystem.instance.readFileSync(dir + '/project.json');
      if (!content) return this.error('No project json');

      this.json = JSON.parse(content);
    } catch (e) {
      return this.error('Not valid json');
    }

    this.validate(this.json);
  }

  print() {
    if (this.errors.length === 0) console.log('No errors');
    this.errors.forEach((e) => {
      console.log(e.msg);
    });
  }

  clearErrors() {
    this.errors = [];
  }

  hasErrors() {
    return this.errors.length > 0;
  }

  fix() {
    this.errors.forEach((e) => {
      e.args && e.args.fix && e.args.fix();
    });
  }

  writeToProjectDirectory(dir) {
    if (!this.json) return;

    const FileSystem = __webpack_require__(38656);
    FileSystem.instance.writeFileSync(dir + '/project.json', JSON.stringify(this.json, null, 4));
  }
}

module.exports = ProjectValidator;


/***/ }),

/***/ 59838:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.UserBadge-module__Root--oOgjs{display:flex;justify-content:center;align-items:center;border-radius:50%;user-select:none;color:var(--theme-color-fg-highlight);font-family:var(--font-family);font-weight:var(--font-weight-semibold)}.UserBadge-module__Root--oOgjs.UserBadge-module__is-size-medium--dXwfd{width:28px;height:28px;font-size:12px}.UserBadge-module__Root--oOgjs.UserBadge-module__is-size-small--GswDn{width:24px;height:24px;font-size:10px;line-height:10px}.UserBadge-module__Root--oOgjs.UserBadge-module__is-size-tiny--ibkAF{width:18px;height:18px;font-size:8px;line-height:10px}.UserBadge-module__Root--oOgjs.UserBadge-module__has-right-spacing--QAmvM{margin-right:8px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/user/UserBadge/UserBadge.module.scss"],"names":[],"mappings":"AAAA,+BACE,YAAA,CACA,sBAAA,CACA,kBAAA,CACA,iBAAA,CACA,gBAAA,CAEA,qCAAA,CACA,8BAAA,CACA,uCAAA,CAEA,uEACE,UAAA,CACA,WAAA,CACA,cAAA,CAGF,sEACE,UAAA,CACA,WAAA,CACA,cAAA,CACA,gBAAA,CAGF,qEACE,UAAA,CACA,WAAA,CACA,aAAA,CACA,gBAAA,CAGF,0EACE,gBAAA","sourcesContent":[".Root {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  border-radius: 50%;\n  user-select: none;\n\n  color: var(--theme-color-fg-highlight);\n  font-family: var(--font-family);\n  font-weight: var(--font-weight-semibold);\n\n  &.is-size-medium {\n    width: 28px;\n    height: 28px;\n    font-size: 12px;\n  }\n\n  &.is-size-small {\n    width: 24px;\n    height: 24px;\n    font-size: 10px;\n    line-height: 10px;\n  }\n\n  &.is-size-tiny {\n    width: 18px;\n    height: 18px;\n    font-size: 8px;\n    line-height: 10px;\n  }\n\n  &.has-right-spacing {\n    margin-right: 8px;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `UserBadge-module__Root--oOgjs`,
	"is-size-medium": `UserBadge-module__is-size-medium--dXwfd`,
	"is-size-small": `UserBadge-module__is-size-small--GswDn`,
	"is-size-tiny": `UserBadge-module__is-size-tiny--ibkAF`,
	"has-right-spacing": `UserBadge-module__has-right-spacing--QAmvM`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 59988:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ToolbarGrip-module__Root--DHDp_{padding:0 2px 2px 0;border:0;background:rgba(0,0,0,0);width:24px;height:100%;cursor:nwse-resize;fill:var(--theme-color-fg-muted);display:flex;justify-content:flex-end;align-items:flex-end}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/toolbar/ToolbarGrip/ToolbarGrip.module.scss"],"names":[],"mappings":"AAAA,iCACE,mBAAA,CACA,QAAA,CACA,wBAAA,CACA,UAAA,CACA,WAAA,CACA,kBAAA,CAEA,gCAAA,CAEA,YAAA,CACA,wBAAA,CACA,oBAAA","sourcesContent":[".Root {\n  padding: 0 2px 2px 0;\n  border: 0;\n  background: transparent;\n  width: 24px;\n  height: 100%;\n  cursor: nwse-resize;\n\n  fill: var(--theme-color-fg-muted);\n\n  display: flex;\n  justify-content: flex-end;\n  align-items: flex-end;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ToolbarGrip-module__Root--DHDp_`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 60028:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  w: () => (/* reexport */ Section),
  $: () => (/* reexport */ SectionVariant)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Label/index.ts + 2 modules
var Label = __webpack_require__(91629);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/index.ts
var Text = __webpack_require__(93834);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/sidebar/Section/Section.module.scss
var Section_module = __webpack_require__(7349);
;// ../noodl-core-ui/src/components/sidebar/Section/Section.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(Section_module/* default */.A, options);




       /* harmony default export */ const Section_Section_module = (Section_module/* default */.A && Section_module/* default */.A.locals ? Section_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/sidebar/Section/Section.tsx





var SectionVariant;
(function (SectionVariant) {
    SectionVariant["Default"] = "default";
    SectionVariant["Panel"] = "panel";
    SectionVariant["PanelShy"] = "panel-shy";
    SectionVariant["InModal"] = "in-modal";
})(SectionVariant || (SectionVariant = {}));
function Section({ variant = SectionVariant.Default, title, hasGutter, hasBottomSpacing, hasVisibleOverflow, hasTopDivider, actions, children, UNSAFE_className, UNSAFE_style }) {
    return (external_react_default().createElement("section", { className: external_classnames_default()([
            Section_Section_module['Root'],
            Section_Section_module[`is-variant-${variant}`],
            hasVisibleOverflow && Section_Section_module['has-visible-overflow'],
            hasTopDivider && Section_Section_module['has-top-divider'],
            UNSAFE_className
        ]), style: UNSAFE_style },
        (Boolean(title) || Boolean(actions)) && (external_react_default().createElement("div", { className: external_classnames_default()(Section_Section_module['Header'], Section_Section_module[`is-variant-${variant}`]) },
            external_react_default().createElement(Label/* Label */.JU, { variant: Text/* TextType */.M2.Proud, size: Label/* LabelSize */.IV.Medium }, title),
            Boolean(actions) && external_react_default().createElement("div", null, actions))),
        external_react_default().createElement("div", { className: external_classnames_default()([
                Section_Section_module['Body'],
                Section_Section_module[`is-variant-${variant}`],
                hasGutter && Section_Section_module['has-gutter'],
                hasBottomSpacing && Section_Section_module['has-bottom-spacing'],
                hasVisibleOverflow && Section_Section_module['has-visible-overflow']
            ]) }, Boolean(children) && children)));
}

;// ../noodl-core-ui/src/components/sidebar/Section/index.ts



/***/ }),

/***/ 60193:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Models = void 0;
const resource_1 = __webpack_require__(39929);
const pagination_1 = __webpack_require__(92081);
const headers_1 = __webpack_require__(79973);
const path_1 = __webpack_require__(20854);
class Models extends resource_1.APIResource {
    /**
     * Get a specific model.
     *
     * The Models API response can be used to determine information about a specific
     * model or resolve a model alias to a model ID.
     */
    retrieve(modelID, params = {}, options) {
        const { betas } = params ?? {};
        return this._client.get((0, path_1.path) `/v1/models/${modelID}`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
                options?.headers,
            ]),
        });
    }
    /**
     * List available models.
     *
     * The Models API response can be used to determine which models are available for
     * use in the API. More recently released models are listed first.
     */
    list(params = {}, options) {
        const { betas, ...query } = params ?? {};
        return this._client.getAPIList('/v1/models', (pagination_1.Page), {
            query,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
                options?.headers,
            ]),
        });
    }
}
exports.Models = Models;
//# sourceMappingURL=models.js.map

/***/ }),

/***/ 60331:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-table {
	display: flex;
	flex-direction: column;
	position: relative;
	height: 100%;
	width: 100%;
	white-space: nowrap;
}

.monaco-table > .monaco-split-view2 {
	border-bottom: 1px solid transparent;
}

.monaco-table > .monaco-list {
	flex: 1;
}

.monaco-table-tr {
	display: flex;
	height: 100%;
}

.monaco-table-th {
	width: 100%;
	height: 100%;
	font-weight: bold;
	overflow: hidden;
	text-overflow: ellipsis;
}

.monaco-table-th,
.monaco-table-td {
	box-sizing: border-box;
	flex-shrink: 0;
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
}

.monaco-table > .monaco-split-view2 .monaco-sash.vertical::before {
	content: "";
	position: absolute;
	left: calc(var(--sash-size) / 2);
	width: 0;
	border-left: 1px solid transparent;
}

.monaco-table > .monaco-split-view2,
.monaco-table > .monaco-split-view2 .monaco-sash.vertical::before {
	transition: border-color 0.2s ease-out;
}
/*
.monaco-table:hover > .monaco-split-view2,
.monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before {
	border-color: rgba(204, 204, 204, 0.2);
} */
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/table/table.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,aAAa;CACb,sBAAsB;CACtB,kBAAkB;CAClB,YAAY;CACZ,WAAW;CACX,mBAAmB;AACpB;;AAEA;CACC,oCAAoC;AACrC;;AAEA;CACC,OAAO;AACR;;AAEA;CACC,aAAa;CACb,YAAY;AACb;;AAEA;CACC,WAAW;CACX,YAAY;CACZ,iBAAiB;CACjB,gBAAgB;CAChB,uBAAuB;AACxB;;AAEA;;CAEC,sBAAsB;CACtB,cAAc;CACd,gBAAgB;CAChB,mBAAmB;CACnB,uBAAuB;AACxB;;AAEA;CACC,WAAW;CACX,kBAAkB;CAClB,gCAAgC;CAChC,QAAQ;CACR,kCAAkC;AACnC;;AAEA;;CAEC,sCAAsC;AACvC;AACA;;;;GAIG","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-table {\n\tdisplay: flex;\n\tflex-direction: column;\n\tposition: relative;\n\theight: 100%;\n\twidth: 100%;\n\twhite-space: nowrap;\n}\n\n.monaco-table > .monaco-split-view2 {\n\tborder-bottom: 1px solid transparent;\n}\n\n.monaco-table > .monaco-list {\n\tflex: 1;\n}\n\n.monaco-table-tr {\n\tdisplay: flex;\n\theight: 100%;\n}\n\n.monaco-table-th {\n\twidth: 100%;\n\theight: 100%;\n\tfont-weight: bold;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.monaco-table-th,\n.monaco-table-td {\n\tbox-sizing: border-box;\n\tflex-shrink: 0;\n\toverflow: hidden;\n\twhite-space: nowrap;\n\ttext-overflow: ellipsis;\n}\n\n.monaco-table > .monaco-split-view2 .monaco-sash.vertical::before {\n\tcontent: \"\";\n\tposition: absolute;\n\tleft: calc(var(--sash-size) / 2);\n\twidth: 0;\n\tborder-left: 1px solid transparent;\n}\n\n.monaco-table > .monaco-split-view2,\n.monaco-table > .monaco-split-view2 .monaco-sash.vertical::before {\n\ttransition: border-color 0.2s ease-out;\n}\n/*\n.monaco-table:hover > .monaco-split-view2,\n.monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before {\n\tborder-color: rgba(204, 204, 204, 0.2);\n} */\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 60529:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSettingFill = function SvgSettingFill(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M21.1617 10.4402C21.1413 10.348 21.1012 10.2613 21.0444 10.1859C20.9875 10.1106 20.9151 10.0483 20.8321 10.0033L18.8705 8.91542C18.7661 8.70113 18.6507 8.49509 18.5243 8.29728L18.5573 6.05549C18.5581 5.96146 18.5394 5.86829 18.5025 5.78179C18.4657 5.69528 18.4114 5.61731 18.343 5.55274C17.3663 4.66721 16.2113 4.00116 14.9556 3.59942C14.8654 3.5713 14.7703 3.56264 14.6766 3.574C14.5828 3.58537 14.4925 3.6165 14.4116 3.66535L12.4913 4.81921C12.2523 4.81097 12.0215 4.81097 11.7825 4.81921L9.86213 3.66535C9.78129 3.6165 9.691 3.58537 9.59723 3.574C9.50346 3.56264 9.40834 3.5713 9.31817 3.59942C8.06084 4.00146 6.90531 4.6706 5.93076 5.56098C5.86181 5.62333 5.80701 5.69973 5.77005 5.78502C5.73309 5.87032 5.71482 5.96255 5.71647 6.05549L5.75768 8.29728C5.62581 8.49509 5.51043 8.70113 5.39504 8.91542L3.44172 10.0033C3.35766 10.047 3.28442 10.1088 3.22738 10.1844C3.17033 10.26 3.13092 10.3474 3.11204 10.4402C2.83179 11.7273 2.83179 13.0597 3.11204 14.3468C3.13252 14.439 3.17254 14.5257 3.22942 14.601C3.2863 14.6764 3.3587 14.7387 3.44172 14.7836L5.40328 15.8716C5.50844 16.0848 5.6268 16.2912 5.75768 16.4897L5.71647 18.7315C5.71572 18.8255 5.73436 18.9187 5.77123 19.0052C5.8081 19.0917 5.86241 19.1697 5.93076 19.2342C6.9088 20.1179 8.06343 20.7837 9.31817 21.1876C9.40834 21.2157 9.50346 21.2243 9.59723 21.213C9.691 21.2016 9.78129 21.1705 9.86213 21.1216L11.7825 19.9678H12.4913L14.4199 21.1216C14.5201 21.1876 14.6378 21.222 14.7578 21.2205C14.8248 21.2176 14.8913 21.2066 14.9556 21.1876C16.2129 20.7855 17.3685 20.1164 18.343 19.226C18.412 19.1636 18.4668 19.0873 18.5037 19.002C18.5407 18.9167 18.559 18.8244 18.5573 18.7315L18.5243 16.4897C18.648 16.2919 18.7634 16.0858 18.8787 15.8716L20.8403 14.7836C20.9221 14.7382 20.9932 14.6757 21.0487 14.6003C21.1041 14.5249 21.1427 14.4384 21.1617 14.3468C21.442 13.0597 21.442 11.7273 21.1617 10.4402ZM15.7633 12.3935C15.7633 13.1107 15.5506 13.8119 15.1521 14.4082C14.7537 15.0046 14.1873 15.4694 13.5247 15.7439C12.862 16.0183 12.1329 16.0902 11.4294 15.9502C10.726 15.8103 10.0798 15.4649 9.57262 14.9578C9.06546 14.4506 8.72007 13.8044 8.58015 13.101C8.44022 12.3975 8.51204 11.6684 8.78651 11.0057C9.06099 10.3431 9.52579 9.77671 10.1222 9.37823C10.7185 8.97975 11.4197 8.76707 12.1369 8.76707C13.0987 8.76707 14.0211 9.14914 14.7012 9.82922C15.3812 10.5093 15.7633 11.4317 15.7633 12.3935Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSettingFill);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "94b2f702ae8f2da71d82f18d19c38932.svg");

/***/ }),

/***/ 60535:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.JSONLDecoder = void 0;
const error_1 = __webpack_require__(37015);
const shims_1 = __webpack_require__(59081);
const line_1 = __webpack_require__(44351);
class JSONLDecoder {
    constructor(iterator, controller) {
        this.iterator = iterator;
        this.controller = controller;
    }
    async *decoder() {
        const lineDecoder = new line_1.LineDecoder();
        for await (const chunk of this.iterator) {
            for (const line of lineDecoder.decode(chunk)) {
                yield JSON.parse(line);
            }
        }
        for (const line of lineDecoder.flush()) {
            yield JSON.parse(line);
        }
    }
    [Symbol.asyncIterator]() {
        return this.decoder();
    }
    static fromResponse(response, controller) {
        if (!response.body) {
            controller.abort();
            if (typeof globalThis.navigator !== 'undefined' &&
                globalThis.navigator.product === 'ReactNative') {
                throw new error_1.AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
            }
            throw new error_1.AnthropicError(`Attempted to iterate over a response with no body`);
        }
        return new JSONLDecoder((0, shims_1.ReadableStreamToAsyncIterable)(response.body), controller);
    }
}
exports.JSONLDecoder = JSONLDecoder;
//# sourceMappingURL=jsonl.js.map

/***/ }),

/***/ 60598:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgComponent = function SvgComponent(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.73087 13.2163C4.05911 12.5445 4.05911 11.4554 4.73087 10.7837L10.7835 4.73102C11.4553 4.05926 12.5444 4.05927 13.2161 4.73102L19.2688 10.7837C19.9405 11.4554 19.9405 12.5445 19.2688 13.2163L13.2161 19.2689C12.5444 19.9407 11.4553 19.9407 10.7835 19.2689L4.73087 13.2163ZM5.77342 11.8262C5.67746 11.9222 5.67746 12.0778 5.77342 12.1737L11.8261 18.2264C11.922 18.3224 12.0776 18.3224 12.1736 18.2264L18.2262 12.1737C18.3222 12.0778 18.3222 11.9222 18.2262 11.8262L12.1736 5.77358C12.0776 5.67761 11.922 5.67761 11.8261 5.77358L5.77342 11.8262Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgComponent);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "1ce9d371f1aeb26872b76b83da980007.svg");

/***/ }),

/***/ 60629:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  gn: () => (/* binding */ Commit),
  el: () => (/* binding */ Stash),
  qj: () => (/* binding */ StashedChangesLoadStates)
});

// EXTERNAL MODULE: ../noodl-git/src/core/diff-tree.ts
var diff_tree = __webpack_require__(78285);
// EXTERNAL MODULE: ../noodl-git/src/core/show.ts
var show = __webpack_require__(35742);
// EXTERNAL MODULE: ../noodl-git/src/core/client.ts + 14 modules
var client = __webpack_require__(85869);
// EXTERNAL MODULE: ../noodl-git/src/core/logs.ts
var logs = __webpack_require__(41176);
;// ../noodl-git/src/core/stash-files.ts


/**
 * Get the files that were changed in the given stash commit.
 *
 * This is different than `getChangedFiles` because stashes
 * have _3 parents(!!!)_
 */
async function getStashedFiles(repositoryDir, stashSha) {
    const [trackedFiles, untrackedFiles] = await Promise.all([
        getChangedFilesWithinStash(repositoryDir, stashSha),
        getChangedFilesWithinStash(repositoryDir, `${stashSha}^3`),
    ]);
    const files = new Map();
    trackedFiles.forEach((x) => files.set(x.path, x));
    untrackedFiles.forEach((x) => files.set(x.path, x));
    return [...files.values()].sort((x, y) => x.path.localeCompare(y.path));
}
/**
 * Same thing as `getChangedFiles` but with extra handling for 128 exit code
 * (which happens if the commit's parent is not valid)
 */
async function getChangedFilesWithinStash(repositoryDir, sha) {
    // opt-in for rename detection (-M) and copies detection (-C)
    // this is equivalent to the user configuring 'diff.renames' to 'copies'
    // NOTE: order here matters - doing -M before -C means copies aren't detected
    const args = [
        "log",
        sha,
        "-C",
        "-M",
        "-m",
        "-1",
        "--no-show-signature",
        "--first-parent",
        "--name-status",
        "--format=format:",
        "-z",
        "--",
    ];
    const result = await (0,client/* git */.$)(args, repositoryDir, "getChangedFilesForStash", {
        // if this fails, its most likely
        // because there weren't any untracked files,
        // and that's okay!
        successExitCodes: new Set([0, 128]),
    });
    if (result.exitCode === 0 && result.output.toString().length > 0) {
        return (0,logs/* parseChangedFiles */.bM)(result.output.toString(), sha);
    }
    return [];
}

;// ../noodl-git/src/core/models/snapshot.ts



/** A git commit. */
class Commit {
    /**
     * @param sha The commit's SHA.
     * @param shortSha The commit's shortSHA.
     * @param summary The first line of the commit message.
     * @param body The commit message without the first line and CR.
     * @param author Information about the author of this commit.
     *               Includes name, email and date.
     * @param committer Information about the committer of this commit.
     *                  Includes name, email and date.
     * @param parentSHAs The SHAs for the parents of the commit.
     * @param tags Tags associated with this commit.
     */
    constructor(repositoryDir, sha, shortSha, summary, body, author, committer, parentSHAs, tags) {
        this.repositoryDir = repositoryDir;
        this.sha = sha;
        this.shortSha = shortSha;
        this.summary = summary;
        this.body = body;
        this.author = author;
        this.committer = committer;
        this.parentSHAs = parentSHAs;
        this.tags = tags;
        this.authoredByCommitter =
            this.author &&
                this.author.name === this.committer.name &&
                this.author.email === this.committer.email;
        this.isMergeCommit = parentSHAs.length > 1;
    }
    async getFileAsString(name) {
        return await (0,show/* getBlobContents */.w)(this.repositoryDir, this.sha, name);
    }
    getFiles() {
        return (0,diff_tree/* getCommitFiles */.R)(this.repositoryDir, this.sha);
    }
}
class Stash {
    /**
     *
     * @param repositoryDir
     * @param name The fully qualified name of the entry i.e., `refs/stash@{0}`
     * @param sha The SHA of the commit object created as a result of stashing.
     * @param branchName The name of the branch at the time the entry was created.
     * @param message
     * @param author
     * @param files The list of files this stash touches
     */
    constructor(repositoryDir, name, branchName, sha, message, author, files) {
        this.repositoryDir = repositoryDir;
        this.name = name;
        this.branchName = branchName;
        this.sha = sha;
        this.message = message;
        this.author = author;
        this.files = files;
    }
    async getFileAsString(name) {
        return await (0,show/* getBlobContents */.w)(this.repositoryDir, this.sha, name);
    }
    getFiles() {
        return getStashedFiles(this.repositoryDir, this.sha);
    }
}
/** Whether file changes for a stash entry are loaded or not */
var StashedChangesLoadStates;
(function (StashedChangesLoadStates) {
    StashedChangesLoadStates["NotLoaded"] = "NotLoaded";
    StashedChangesLoadStates["Loading"] = "Loading";
    StashedChangesLoadStates["Loaded"] = "Loaded";
})(StashedChangesLoadStates || (StashedChangesLoadStates = {}));


/***/ }),

/***/ 60701:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5, _path6, _path7, _path8, _path9, _path0;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRoundedCornerRightUp = function SvgRoundedCornerRightUp(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.93994 4.9917C3.93994 5.40591 4.27573 5.7417 4.68994 5.7417C5.10415 5.7417 5.43994 5.40591 5.43994 4.9917C5.43994 4.57749 5.10415 4.2417 4.68994 4.2417C4.27573 4.2417 3.93994 4.57749 3.93994 4.9917Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.93994 18.7334C3.93994 19.1476 4.27573 19.4834 4.68994 19.4834C5.10415 19.4834 5.43994 19.1476 5.43994 18.7334C5.43994 18.3192 5.10415 17.9834 4.68994 17.9834C4.27573 17.9834 3.93994 18.3192 3.93994 18.7334Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M24.8335 18.7334C24.8335 19.1476 25.1693 19.4834 25.5835 19.4834C25.9977 19.4834 26.3335 19.1476 26.3335 18.7334C26.3335 18.3192 25.9977 17.9834 25.5835 17.9834C25.1693 17.9834 24.8335 18.3192 24.8335 18.7334Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.93994 11.8623C3.93994 12.2765 4.27573 12.6123 4.68994 12.6123C5.10415 12.6123 5.43994 12.2765 5.43994 11.8623C5.43994 11.4481 5.10415 11.1123 4.68994 11.1123C4.27573 11.1123 3.93994 11.4481 3.93994 11.8623Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.93994 25.6045C3.93994 26.0187 4.27573 26.3545 4.68994 26.3545C5.10415 26.3545 5.43994 26.0187 5.43994 25.6045C5.43994 25.1903 5.10415 24.8545 4.68994 24.8545C4.27573 24.8545 3.93994 25.1903 3.93994 25.6045Z",
    fill: "#F5F5F5"
  })), _path6 || (_path6 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.6821 25.6045C17.6821 26.0187 18.0179 26.3545 18.4321 26.3545C18.8463 26.3545 19.1821 26.0187 19.1821 25.6045C19.1821 25.1903 18.8463 24.8545 18.4321 24.8545C18.0179 24.8545 17.6821 25.1903 17.6821 25.6045Z",
    fill: "#F5F5F5"
  })), _path7 || (_path7 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.811 25.6045C10.811 26.0187 11.1468 26.3545 11.561 26.3545C11.9752 26.3545 12.311 26.0187 12.311 25.6045C12.311 25.1903 11.9752 24.8545 11.561 24.8545C11.1468 24.8545 10.811 25.1903 10.811 25.6045Z",
    fill: "#F5F5F5"
  })), _path8 || (_path8 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.811 4.9917C10.811 5.40591 11.1468 5.7417 11.561 5.7417C11.9752 5.7417 12.311 5.40591 12.311 4.9917C12.311 4.57749 11.9752 4.2417 11.561 4.2417C11.1468 4.2417 10.811 4.57749 10.811 4.9917Z",
    fill: "#F5F5F5"
  })), _path9 || (_path9 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M24.5532 25.6045C24.5532 26.0187 24.889 26.3545 25.3032 26.3545C25.7174 26.3545 26.0532 26.0187 26.0532 25.6045C26.0532 25.1903 25.7174 24.8545 25.3032 24.8545C24.889 24.8545 24.5532 25.1903 24.5532 25.6045Z",
    fill: "#F5F5F5"
  })), _path0 || (_path0 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M24.5532 11.9919L24.5532 13.0079C24.5532 13.4221 24.889 13.7579 25.3032 13.7579C25.7174 13.7579 26.0532 13.4221 26.0532 13.0079L26.0532 11.9919C26.0532 7.71167 22.5834 4.24188 18.3032 4.24188L17.2872 4.24188C16.873 4.24188 16.5372 4.57767 16.5372 4.99188C16.5372 5.40609 16.873 5.74188 17.2872 5.74188L18.3032 5.74188C21.755 5.74188 24.5532 8.5401 24.5532 11.9919Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRoundedCornerRightUp);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "6b6b586d7399d96df56c5d0cf2496ffc.svg");

/***/ }),

/***/ 60886:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _circle, _circle2, _circle3, _circle4, _circle5, _circle6, _circle7, _circle8, _circle9, _circle0, _circle1, _circle10, _circle11, _circle12, _circle13, _circle14, _circle15, _circle16, _circle17;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgColumns = function SvgColumns(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 30,
    height: 31,
    viewBox: "0 0 30 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _circle || (_circle = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 4.99927,
    cy: 25.1427,
    r: 0.999268,
    transform: "rotate(-180 4.99927 25.1427)",
    fill: "#F5F5F5"
  })), _circle2 || (_circle2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 25.0007,
    cy: 25.1427,
    r: 0.999268,
    transform: "rotate(-180 25.0007 25.1427)",
    fill: "#F5F5F5"
  })), _circle3 || (_circle3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 4.99927,
    cy: 15.1423,
    r: 0.999268,
    transform: "rotate(-180 4.99927 15.1423)",
    fill: "#F5F5F5"
  })), _circle4 || (_circle4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 4.99927,
    cy: 10.1422,
    r: 0.999268,
    transform: "rotate(-180 4.99927 10.1422)",
    fill: "#F5F5F5"
  })), _circle5 || (_circle5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 25.0007,
    cy: 10.1422,
    r: 0.999268,
    transform: "rotate(-180 25.0007 10.1422)",
    fill: "#F5F5F5"
  })), _circle6 || (_circle6 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 15.0833,
    cy: 10.1422,
    r: 0.999268,
    transform: "rotate(-180 15.0833 10.1422)",
    fill: "#F5F5F5"
  })), _circle7 || (_circle7 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 4.99927,
    cy: 20.1425,
    r: 0.999268,
    transform: "rotate(-180 4.99927 20.1425)",
    fill: "#F5F5F5"
  })), _circle8 || (_circle8 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 25.0007,
    cy: 20.1426,
    r: 0.999268,
    transform: "rotate(-180 25.0007 20.1426)",
    fill: "#F5F5F5"
  })), _circle9 || (_circle9 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 15.0833,
    cy: 20.1426,
    r: 0.999268,
    transform: "rotate(-180 15.0833 20.1426)",
    fill: "#F5F5F5"
  })), _circle0 || (_circle0 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 25.0007,
    cy: 15.1423,
    r: 0.999268,
    transform: "rotate(-180 25.0007 15.1423)",
    fill: "#F5F5F5"
  })), _circle1 || (_circle1 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 15.0833,
    cy: 15.1423,
    r: 0.999268,
    transform: "rotate(-180 15.0833 15.1423)",
    fill: "#F5F5F5"
  })), _circle10 || (_circle10 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 4.99927,
    cy: 5.14209,
    r: 0.999268,
    transform: "rotate(-180 4.99927 5.14209)",
    fill: "#F5F5F5"
  })), _circle11 || (_circle11 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 25.0007,
    cy: 5.14209,
    r: 0.999268,
    transform: "rotate(-180 25.0007 5.14209)",
    fill: "#F5F5F5"
  })), _circle12 || (_circle12 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 20.0007,
    cy: 5.1416,
    r: 0.999268,
    transform: "rotate(-180 20.0007 5.1416)",
    fill: "#F5F5F5"
  })), _circle13 || (_circle13 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 20.0007,
    cy: 25.1423,
    r: 0.999268,
    transform: "rotate(-180 20.0007 25.1423)",
    fill: "#F5F5F5"
  })), _circle14 || (_circle14 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 9.99975,
    cy: 5.14184,
    r: 0.999268,
    transform: "rotate(-180 9.99975 5.14184)",
    fill: "#F5F5F5"
  })), _circle15 || (_circle15 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 15.0002,
    cy: 5.14184,
    r: 0.999268,
    transform: "rotate(-180 15.0002 5.14184)",
    fill: "#F5F5F5"
  })), _circle16 || (_circle16 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 9.99975,
    cy: 25.1427,
    r: 0.999268,
    transform: "rotate(-180 9.99975 25.1427)",
    fill: "#F5F5F5"
  })), _circle17 || (_circle17 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("circle", {
    cx: 15.0002,
    cy: 25.1427,
    r: 0.999268,
    transform: "rotate(-180 15.0002 25.1427)",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgColumns);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "873e831aa2153bbb750a64bff043a4dd.svg");

/***/ }),

/***/ 60893:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.JSONEditor-module__Root--m8CXD{display:flex;flex-direction:column;width:100%;background-color:var(--theme-color-bg-1);border:1px solid var(--theme-color-border-default);border-radius:6px;overflow:hidden}.JSONEditor-module__Header--rCmrn{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;background-color:var(--theme-color-bg-2);border-bottom:1px solid var(--theme-color-border-default)}.JSONEditor-module__Title--W6pYm{font-size:13px;font-weight:600;color:var(--theme-color-fg-default)}.JSONEditor-module__ModeToggle--ABZB_{display:flex;gap:4px;background-color:var(--theme-color-bg-1);border:1px solid var(--theme-color-border-default);border-radius:4px;padding:2px}.JSONEditor-module__ModeToggle--ABZB_ button{padding:6px 12px;font-size:12px;font-weight:500;border:none;background:rgba(0,0,0,0);color:var(--theme-color-fg-default);border-radius:3px;cursor:pointer;transition:all .15s ease}.JSONEditor-module__ModeToggle--ABZB_ button:hover:not(:disabled){background-color:var(--theme-color-bg-3)}.JSONEditor-module__ModeToggle--ABZB_ button:disabled{cursor:not-allowed;opacity:.5}.JSONEditor-module__ModeToggle--ABZB_ button.JSONEditor-module__Active--oiiSY{background-color:var(--theme-color-primary);color:#fff;font-weight:600}.JSONEditor-module__ModeToggle--ABZB_ button.JSONEditor-module__Active--oiiSY:hover{background-color:var(--theme-color-primary)}.JSONEditor-module__ValidationError--K72nY{display:flex;align-items:flex-start;gap:12px;padding:12px 16px;background-color:#fef2f2;border-bottom:1px solid #fecaca}.JSONEditor-module__ErrorIcon--z7enn{font-size:20px;flex-shrink:0;line-height:1}.JSONEditor-module__ErrorContent--UUxik{flex:1;display:flex;flex-direction:column;gap:4px}.JSONEditor-module__ErrorMessage--uTmxX{font-size:13px;font-weight:600;color:#dc2626;line-height:1.4}.JSONEditor-module__ErrorSuggestion--GYNNC{font-size:12px;color:#7c2d12;line-height:1.4;padding:8px 12px;background-color:#fef3c7;border:1px solid #fde68a;border-radius:4px;margin-top:4px}.JSONEditor-module__EditorContent--JFoni{flex:1;overflow:hidden;position:relative}.JSONEditor-module__AdvancedModePlaceholder--WiLSz{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:40px 24px;background-color:var(--theme-color-bg-2);text-align:center}.JSONEditor-module__PlaceholderIcon--b94PQ{font-size:64px;margin-bottom:16px;opacity:.5}.JSONEditor-module__PlaceholderText--UhHuI{font-size:16px;font-weight:600;color:var(--theme-color-fg-default);margin-bottom:8px}.JSONEditor-module__PlaceholderDetail--uUmvd{font-size:13px;color:var(--theme-color-fg-muted)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/json-editor/JSONEditor.module.scss"],"names":[],"mappings":"AAKA,gCACE,YAAA,CACA,qBAAA,CACA,UAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,eAAA,CAIF,kCACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,iBAAA,CACA,wCAAA,CACA,yDAAA,CAGF,iCACE,cAAA,CACA,eAAA,CACA,mCAAA,CAIF,sCACE,YAAA,CACA,OAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,WAAA,CAEA,6CACE,gBAAA,CACA,cAAA,CACA,eAAA,CACA,WAAA,CACA,wBAAA,CACA,mCAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CAEA,kEACE,wCAAA,CAGF,sDACE,kBAAA,CACA,UAAA,CAGF,8EACE,2CAAA,CACA,UAAA,CACA,eAAA,CAEA,oFACE,2CAAA,CAOR,2CACE,YAAA,CACA,sBAAA,CACA,QAAA,CACA,iBAAA,CACA,wBAAA,CACA,+BAAA,CAGF,qCACE,cAAA,CACA,aAAA,CACA,aAAA,CAGF,wCACE,MAAA,CACA,YAAA,CACA,qBAAA,CACA,OAAA,CAGF,wCACE,cAAA,CACA,eAAA,CACA,aAAA,CACA,eAAA,CAGF,2CACE,cAAA,CACA,aAAA,CACA,eAAA,CACA,gBAAA,CACA,wBAAA,CACA,wBAAA,CACA,iBAAA,CACA,cAAA,CAIF,yCACE,MAAA,CACA,eAAA,CACA,iBAAA,CAIF,mDACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,WAAA,CACA,iBAAA,CACA,wCAAA,CACA,iBAAA,CAGF,2CACE,cAAA,CACA,kBAAA,CACA,UAAA,CAGF,2CACE,cAAA,CACA,eAAA,CACA,mCAAA,CACA,iBAAA,CAGF,6CACE,cAAA,CACA,iCAAA","sourcesContent":["/**\n * JSONEditor Main Component Styles\n * Uses design tokens for consistency with OpenNoodl design system\n */\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  width: 100%;\n  background-color: var(--theme-color-bg-1);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 6px;\n  overflow: hidden;\n}\n\n/* Header */\n.Header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 12px 16px;\n  background-color: var(--theme-color-bg-2);\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.Title {\n  font-size: 13px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n}\n\n/* Mode Toggle */\n.ModeToggle {\n  display: flex;\n  gap: 4px;\n  background-color: var(--theme-color-bg-1);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  padding: 2px;\n\n  button {\n    padding: 6px 12px;\n    font-size: 12px;\n    font-weight: 500;\n    border: none;\n    background: transparent;\n    color: var(--theme-color-fg-default);\n    border-radius: 3px;\n    cursor: pointer;\n    transition: all 0.15s ease;\n\n    &:hover:not(:disabled) {\n      background-color: var(--theme-color-bg-3);\n    }\n\n    &:disabled {\n      cursor: not-allowed;\n      opacity: 0.5;\n    }\n\n    &.Active {\n      background-color: var(--theme-color-primary);\n      color: white;\n      font-weight: 600;\n\n      &:hover {\n        background-color: var(--theme-color-primary);\n      }\n    }\n  }\n}\n\n/* Validation Error Banner */\n.ValidationError {\n  display: flex;\n  align-items: flex-start;\n  gap: 12px;\n  padding: 12px 16px;\n  background-color: #fef2f2;\n  border-bottom: 1px solid #fecaca;\n}\n\n.ErrorIcon {\n  font-size: 20px;\n  flex-shrink: 0;\n  line-height: 1;\n}\n\n.ErrorContent {\n  flex: 1;\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n}\n\n.ErrorMessage {\n  font-size: 13px;\n  font-weight: 600;\n  color: #dc2626;\n  line-height: 1.4;\n}\n\n.ErrorSuggestion {\n  font-size: 12px;\n  color: #7c2d12;\n  line-height: 1.4;\n  padding: 8px 12px;\n  background-color: #fef3c7;\n  border: 1px solid #fde68a;\n  border-radius: 4px;\n  margin-top: 4px;\n}\n\n/* Editor Content */\n.EditorContent {\n  flex: 1;\n  overflow: hidden;\n  position: relative;\n}\n\n/* Advanced Mode Placeholder (temporary) */\n.AdvancedModePlaceholder {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  height: 100%;\n  padding: 40px 24px;\n  background-color: var(--theme-color-bg-2);\n  text-align: center;\n}\n\n.PlaceholderIcon {\n  font-size: 64px;\n  margin-bottom: 16px;\n  opacity: 0.5;\n}\n\n.PlaceholderText {\n  font-size: 16px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n  margin-bottom: 8px;\n}\n\n.PlaceholderDetail {\n  font-size: 13px;\n  color: var(--theme-color-fg-muted);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `JSONEditor-module__Root--m8CXD`,
	"Header": `JSONEditor-module__Header--rCmrn`,
	"Title": `JSONEditor-module__Title--W6pYm`,
	"ModeToggle": `JSONEditor-module__ModeToggle--ABZB_`,
	"Active": `JSONEditor-module__Active--oiiSY`,
	"ValidationError": `JSONEditor-module__ValidationError--K72nY`,
	"ErrorIcon": `JSONEditor-module__ErrorIcon--z7enn`,
	"ErrorContent": `JSONEditor-module__ErrorContent--UUxik`,
	"ErrorMessage": `JSONEditor-module__ErrorMessage--uTmxX`,
	"ErrorSuggestion": `JSONEditor-module__ErrorSuggestion--GYNNC`,
	"EditorContent": `JSONEditor-module__EditorContent--JFoni`,
	"AdvancedModePlaceholder": `JSONEditor-module__AdvancedModePlaceholder--WiLSz`,
	"PlaceholderIcon": `JSONEditor-module__PlaceholderIcon--b94PQ`,
	"PlaceholderText": `JSONEditor-module__PlaceholderText--UhHuI`,
	"PlaceholderDetail": `JSONEditor-module__PlaceholderDetail--uUmvd`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 60938:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  S: () => (/* reexport */ PropertyPanelButton)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/property-panel/PropertyPanelButton/PropertyPanelButton.module.scss
var PropertyPanelButton_module = __webpack_require__(74065);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelButton/PropertyPanelButton.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(PropertyPanelButton_module/* default */.A, options);




       /* harmony default export */ const PropertyPanelButton_PropertyPanelButton_module = (PropertyPanelButton_module/* default */.A && PropertyPanelButton_module/* default */.A.locals ? PropertyPanelButton_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelButton/PropertyPanelButton.tsx



function PropertyPanelButton({ properties }) {
    return (external_react_default().createElement("div", { className: PropertyPanelButton_PropertyPanelButton_module['Root'] },
        external_react_default().createElement("button", { className: external_classnames_default()([PropertyPanelButton_PropertyPanelButton_module['Button'], properties.isPrimary && PropertyPanelButton_PropertyPanelButton_module['is-primary']]), onClick: properties.onClick }, properties.buttonLabel)));
}

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelButton/index.ts



/***/ }),

/***/ 61113:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (/* binding */ useCallAfterNextRender)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _useOnUnmount__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(46901);


function useCallAfterNextRender() {
    const rafIdRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(-1);
    (0,_useOnUnmount__WEBPACK_IMPORTED_MODULE_1__["default"])(() => {
        cancelAnimationFrame(rafIdRef.current);
    });
    const callAfterNextRender = (0,react__WEBPACK_IMPORTED_MODULE_0__.useCallback)((callback) => {
        cancelAnimationFrame(rafIdRef.current);
        rafIdRef.current = requestAnimationFrame(() => {
            rafIdRef.current = requestAnimationFrame(() => {
                callback();
            });
        });
    }, []);
    return callAfterNextRender;
}


/***/ }),

/***/ 61211:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  M: () => (/* reexport */ ToolbarGrip)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/toolbar/ToolbarGrip/ToolbarGrip.module.scss
var ToolbarGrip_module = __webpack_require__(59988);
;// ../noodl-core-ui/src/components/toolbar/ToolbarGrip/ToolbarGrip.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(ToolbarGrip_module/* default */.A, options);




       /* harmony default export */ const ToolbarGrip_ToolbarGrip_module = (ToolbarGrip_module/* default */.A && ToolbarGrip_module/* default */.A.locals ? ToolbarGrip_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/toolbar/ToolbarGrip/ToolbarGrip.tsx




function ToolbarGrip({ onMouseDown }) {
    return (external_react_default().createElement("button", { className: external_classnames_default()([ToolbarGrip_ToolbarGrip_module['Root']]), onMouseDown: (e) => {
            if (onMouseDown)
                onMouseDown(e);
        } },
        external_react_default().createElement(Icon/* Icon */.In, { icon: Icon/* IconName */.$M.Grip, size: Icon/* IconSize */.lK.Default })));
}

;// ../noodl-core-ui/src/components/toolbar/ToolbarGrip/index.ts



/***/ }),

/***/ 61231:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   q: () => (/* binding */ OpenAiStore)
/* harmony export */ });
/* harmony import */ var _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(39804);
// import Store from 'electron-store';

// import { decryptString, encryptString } from './_internal/StorageApi';
// const store = new Store<Record<string, string>>({
//   name: 'AiAssistant',
//   encryptionKey: 'b4a5d3b3-5e3e-477e-a978-9d347bc8b834',
//   defaults: {
//     defaultModel: 'gpt-4'
//   }
// });
const AI_ASSISTANT_API_KEY = 'aiAssistant.temporaryApiKey';
const AI_ASSISTANT_VERSION_KEY = 'aiAssistant.version';
const AI_ASSISTANT_VERIFIED_KEY = 'aiAssistant.verified';
const AI_ASSISTANT_ENDPOINT_KEY = 'aiAssistant.endpoint';
const AI_ASSISTANT_MODEL_KEY = 'aiAssistant.model';
const OpenAiStore = {
    isEnabled() {
        const version = _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__/* .EditorSettings */ .H.instance.get(AI_ASSISTANT_VERSION_KEY);
        return version === 'full-beta';
    },
    getVersion() {
        return _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__/* .EditorSettings */ .H.instance.get(AI_ASSISTANT_VERSION_KEY) || 'full-beta';
    },
    getPrettyVersion() {
        switch (this.getVersion()) {
            case 'full-beta':
                return 'Full Beta';
            case 'enterprise':
                return 'Enterprise';
        }
        return null;
    },
    setVersion(value) {
        _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__/* .EditorSettings */ .H.instance.set(AI_ASSISTANT_VERSION_KEY, value);
    },
    getApiKey() {
        return _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__/* .EditorSettings */ .H.instance.get(AI_ASSISTANT_API_KEY);
    },
    async setApiKey(value) {
        _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__/* .EditorSettings */ .H.instance.set(AI_ASSISTANT_API_KEY, value);
    },
    setIsAiApiKeyVerified(value) {
        _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__/* .EditorSettings */ .H.instance.set(AI_ASSISTANT_VERIFIED_KEY, value);
    },
    getIsAiApiKeyVerified() {
        return !!_noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__/* .EditorSettings */ .H.instance.get(AI_ASSISTANT_VERIFIED_KEY);
    },
    setEndpoint(value) {
        _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__/* .EditorSettings */ .H.instance.set(AI_ASSISTANT_ENDPOINT_KEY, value);
    },
    getEndpoint() {
        return _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__/* .EditorSettings */ .H.instance.get(AI_ASSISTANT_ENDPOINT_KEY);
    },
    setModel(value) {
        _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__/* .EditorSettings */ .H.instance.set(AI_ASSISTANT_MODEL_KEY, value);
    },
    getModel() {
        return _noodl_utils_editorsettings__WEBPACK_IMPORTED_MODULE_0__/* .EditorSettings */ .H.instance.get(AI_ASSISTANT_MODEL_KEY) || 'gpt-3';
    }
};


/***/ }),

/***/ 61385:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .peekview-widget .head {
	box-sizing: border-box;
	display: flex;
	justify-content: space-between;
	flex-wrap: nowrap;
}

.monaco-editor .peekview-widget .head .peekview-title {
	display: flex;
	align-items: center;
	font-size: 13px;
	margin-left: 20px;
	min-width: 0;
	text-overflow: ellipsis;
	overflow: hidden;
}

.monaco-editor .peekview-widget .head .peekview-title.clickable {
	cursor: pointer;
}

.monaco-editor .peekview-widget .head .peekview-title .dirname:not(:empty) {
	font-size: 0.9em;
	margin-left: 0.5em;
	text-overflow: ellipsis;
	overflow: hidden;
}

.monaco-editor .peekview-widget .head .peekview-title .meta {
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.monaco-editor .peekview-widget .head .peekview-title .dirname {
	white-space: nowrap;
}

.monaco-editor .peekview-widget .head .peekview-title .filename {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.monaco-editor .peekview-widget .head .peekview-title .meta:not(:empty)::before {
	content: '-';
	padding: 0 0.3em;
}

.monaco-editor .peekview-widget .head .peekview-actions {
	flex: 1;
	text-align: right;
	padding-right: 2px;
}

.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar {
	display: inline-block;
}

.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar,
.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar > .actions-container {
	height: 100%;
}

.monaco-editor .peekview-widget > .body {
	border-top: 1px solid;
	position: relative;
}

.monaco-editor .peekview-widget .head .peekview-title .codicon {
	margin-right: 4px;
}

.monaco-editor .peekview-widget .monaco-list .monaco-list-row.focused .codicon {
	color: inherit !important;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/peekView/browser/media/peekViewWidget.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,sBAAsB;CACtB,aAAa;CACb,8BAA8B;CAC9B,iBAAiB;AAClB;;AAEA;CACC,aAAa;CACb,mBAAmB;CACnB,eAAe;CACf,iBAAiB;CACjB,YAAY;CACZ,uBAAuB;CACvB,gBAAgB;AACjB;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,gBAAgB;CAChB,kBAAkB;CAClB,uBAAuB;CACvB,gBAAgB;AACjB;;AAEA;CACC,mBAAmB;CACnB,gBAAgB;CAChB,uBAAuB;AACxB;;AAEA;CACC,mBAAmB;AACpB;;AAEA;CACC,gBAAgB;CAChB,uBAAuB;CACvB,mBAAmB;AACpB;;AAEA;CACC,YAAY;CACZ,gBAAgB;AACjB;;AAEA;CACC,OAAO;CACP,iBAAiB;CACjB,kBAAkB;AACnB;;AAEA;CACC,qBAAqB;AACtB;;AAEA;;CAEC,YAAY;AACb;;AAEA;CACC,qBAAqB;CACrB,kBAAkB;AACnB;;AAEA;CACC,iBAAiB;AAClB;;AAEA;CACC,yBAAyB;AAC1B","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .peekview-widget .head {\n\tbox-sizing: border-box;\n\tdisplay: flex;\n\tjustify-content: space-between;\n\tflex-wrap: nowrap;\n}\n\n.monaco-editor .peekview-widget .head .peekview-title {\n\tdisplay: flex;\n\talign-items: center;\n\tfont-size: 13px;\n\tmargin-left: 20px;\n\tmin-width: 0;\n\ttext-overflow: ellipsis;\n\toverflow: hidden;\n}\n\n.monaco-editor .peekview-widget .head .peekview-title.clickable {\n\tcursor: pointer;\n}\n\n.monaco-editor .peekview-widget .head .peekview-title .dirname:not(:empty) {\n\tfont-size: 0.9em;\n\tmargin-left: 0.5em;\n\ttext-overflow: ellipsis;\n\toverflow: hidden;\n}\n\n.monaco-editor .peekview-widget .head .peekview-title .meta {\n\twhite-space: nowrap;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n\n.monaco-editor .peekview-widget .head .peekview-title .dirname {\n\twhite-space: nowrap;\n}\n\n.monaco-editor .peekview-widget .head .peekview-title .filename {\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\twhite-space: nowrap;\n}\n\n.monaco-editor .peekview-widget .head .peekview-title .meta:not(:empty)::before {\n\tcontent: '-';\n\tpadding: 0 0.3em;\n}\n\n.monaco-editor .peekview-widget .head .peekview-actions {\n\tflex: 1;\n\ttext-align: right;\n\tpadding-right: 2px;\n}\n\n.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar {\n\tdisplay: inline-block;\n}\n\n.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar,\n.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar > .actions-container {\n\theight: 100%;\n}\n\n.monaco-editor .peekview-widget > .body {\n\tborder-top: 1px solid;\n\tposition: relative;\n}\n\n.monaco-editor .peekview-widget .head .peekview-title .codicon {\n\tmargin-right: 4px;\n}\n\n.monaco-editor .peekview-widget .monaco-list .monaco-list-row.focused .codicon {\n\tcolor: inherit !important;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 61730:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=shared.js.map

/***/ }),

/***/ 61825:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-custom-toggle {
	margin-left: 2px;
	float: left;
	cursor: pointer;
	overflow: hidden;
	width: 20px;
	height: 20px;
	border-radius: 3px;
	border: 1px solid transparent;
	padding: 1px;
	box-sizing:	border-box;
	user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}

.monaco-custom-toggle:hover {
	background-color: var(--vscode-inputOption-hoverBackground);
}

.hc-black .monaco-custom-toggle:hover,
.hc-light .monaco-custom-toggle:hover {
	border: 1px dashed var(--vscode-focusBorder);
}

.hc-black .monaco-custom-toggle,
.hc-light .monaco-custom-toggle {
	background: none;
}

.hc-black .monaco-custom-toggle:hover,
.hc-light .monaco-custom-toggle:hover {
	background: none;
}

.monaco-custom-toggle.monaco-checkbox {
	height: 18px;
	width: 18px;
	border: 1px solid transparent;
	border-radius: 3px;
	margin-right: 9px;
	margin-left: 0px;
	padding: 0px;
	opacity: 1;
	background-size: 16px !important;
}

/* hide check when unchecked */
.monaco-custom-toggle.monaco-checkbox:not(.checked)::before {
	visibility: hidden;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/toggle/toggle.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,gBAAgB;CAChB,WAAW;CACX,eAAe;CACf,gBAAgB;CAChB,WAAW;CACX,YAAY;CACZ,kBAAkB;CAClB,6BAA6B;CAC7B,YAAY;CACZ,sBAAsB;CACtB,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;AACtB;;AAEA;CACC,2DAA2D;AAC5D;;AAEA;;CAEC,4CAA4C;AAC7C;;AAEA;;CAEC,gBAAgB;AACjB;;AAEA;;CAEC,gBAAgB;AACjB;;AAEA;CACC,YAAY;CACZ,WAAW;CACX,6BAA6B;CAC7B,kBAAkB;CAClB,iBAAiB;CACjB,gBAAgB;CAChB,YAAY;CACZ,UAAU;CACV,gCAAgC;AACjC;;AAEA,8BAA8B;AAC9B;CACC,kBAAkB;AACnB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-custom-toggle {\n\tmargin-left: 2px;\n\tfloat: left;\n\tcursor: pointer;\n\toverflow: hidden;\n\twidth: 20px;\n\theight: 20px;\n\tborder-radius: 3px;\n\tborder: 1px solid transparent;\n\tpadding: 1px;\n\tbox-sizing:\tborder-box;\n\tuser-select: none;\n\t-webkit-user-select: none;\n\t-ms-user-select: none;\n}\n\n.monaco-custom-toggle:hover {\n\tbackground-color: var(--vscode-inputOption-hoverBackground);\n}\n\n.hc-black .monaco-custom-toggle:hover,\n.hc-light .monaco-custom-toggle:hover {\n\tborder: 1px dashed var(--vscode-focusBorder);\n}\n\n.hc-black .monaco-custom-toggle,\n.hc-light .monaco-custom-toggle {\n\tbackground: none;\n}\n\n.hc-black .monaco-custom-toggle:hover,\n.hc-light .monaco-custom-toggle:hover {\n\tbackground: none;\n}\n\n.monaco-custom-toggle.monaco-checkbox {\n\theight: 18px;\n\twidth: 18px;\n\tborder: 1px solid transparent;\n\tborder-radius: 3px;\n\tmargin-right: 9px;\n\tmargin-left: 0px;\n\tpadding: 0px;\n\topacity: 1;\n\tbackground-size: 16px !important;\n}\n\n/* hide check when unchecked */\n.monaco-custom-toggle.monaco-checkbox:not(.checked)::before {\n\tvisibility: hidden;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 62111:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   G: () => (/* binding */ HtmlProcessor)
/* harmony export */ });
/* harmony import */ var _shared_utils_projectmodules__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(90130);
/* harmony import */ var _shared_utils_projectmodules__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_shared_utils_projectmodules__WEBPACK_IMPORTED_MODULE_0__);

class HtmlProcessor {
    constructor(project) {
        this.project = project;
    }
    async process(content, parameters) {
        const settings = this.project.getSettings();
        let baseUrl = parameters.baseUrl || settings.baseUrl || '/';
        // Make sure the baseUrl always ends with a slash
        if (settings.baseUrl && !settings.baseUrl.endsWith('/')) {
            baseUrl = baseUrl + '/';
        }
        const title = parameters.title || settings.htmlTitle || 'Noodl Viewer';
        let headCode = settings.headCode || '';
        if (parameters.headCode) {
            headCode += parameters.headCode;
        }
        if (baseUrl !== '/') {
            headCode = `<base href="${baseUrl}" target="_blank" />\n` + headCode;
        }
        // Inject modules, title, head code
        let injected = await this.injectIntoHtml(content, baseUrl);
        injected = injected.replace('{{#title#}}', title);
        injected = injected.replace('{{#customHeadCode#}}', headCode);
        injected = injected.replace(/%baseUrl%/g, baseUrl);
        // Inject path to index.js
        const indexJsPath = parameters.indexJsPath || 'index.js';
        let indexCode = `<script src="${baseUrl}${indexJsPath}"></script>`;
        const envListCode = Object.entries(parameters.envVariables || {})
            .map(([name, variable]) => {
            return `  Noodl.Env['${name}'] = '${variable}';`;
        })
            .join('\n');
        let str = `Noodl.Env['BaseUrl'] = '${baseUrl}';`;
        if (envListCode) {
            str += '\n' + envListCode;
        }
        indexCode += `
<script>
(function () {
  ${str}
})();
</script>`;
        injected = injected.replace('<%index_js%>', indexCode);
        return injected;
    }
    injectIntoHtml(template, pathPrefix) {
        return new Promise((resolve) => {
            _shared_utils_projectmodules__WEBPACK_IMPORTED_MODULE_0___default().instance.injectIntoHtml(this.project._retainedProjectDirectory, template, pathPrefix, resolve);
        });
    }
}


/***/ }),

/***/ 62230:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgJustifyContentSpaceAround = function SvgJustifyContentSpaceAround(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.6643 7.17615H8.06277C7.68401 7.17615 7.37695 7.43198 7.37695 7.74758V10.6047C7.37695 10.9203 7.68401 11.1761 8.06277 11.1761H17.6643C18.043 11.1761 18.3501 10.9203 18.3501 10.6047V7.74758C18.3501 7.43198 18.043 7.17615 17.6643 7.17615Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M8.06231 18.1761L17.6638 18.1761C18.0426 18.1761 18.3496 17.9203 18.3496 17.6047L18.3496 14.7476C18.3496 14.432 18.0426 14.1761 17.6638 14.1761L8.06231 14.1761C7.68354 14.1761 7.37649 14.432 7.37649 14.7476L7.37649 17.6047C7.37649 17.9203 7.68354 18.1761 8.06231 18.1761Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.86328 3.42615C3.86328 3.01193 4.22146 2.67615 4.6633 2.67615H21.0633C21.5051 2.67615 21.8633 3.01193 21.8633 3.42615C21.8633 3.84036 21.5051 4.17615 21.0633 4.17615H4.6633C4.22146 4.17615 3.86328 3.84036 3.86328 3.42615Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.8633 21.9261C21.8633 22.3404 21.5051 22.6761 21.0633 22.6761L4.66331 22.6761C4.22147 22.6761 3.86328 22.3404 3.86328 21.9261C3.86328 21.5119 4.22147 21.1761 4.66331 21.1761L21.0633 21.1761C21.5051 21.1761 21.8633 21.5119 21.8633 21.9261Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgJustifyContentSpaceAround);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "2935d82d1a295f905052cb49fcf71f95.svg");

/***/ }),

/***/ 62306:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgTextAlignCenter = function SvgTextAlignCenter(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.13672 6.375C3.13672 5.96079 3.47251 5.625 3.88672 5.625H20.3867C20.8009 5.625 21.1367 5.96079 21.1367 6.375C21.1367 6.78921 20.8009 7.125 20.3867 7.125H3.88672C3.47251 7.125 3.13672 6.78921 3.13672 6.375Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.38672 10.125C5.38672 9.71079 5.72251 9.375 6.13672 9.375H18.1367C18.5509 9.375 18.8867 9.71079 18.8867 10.125C18.8867 10.5392 18.5509 10.875 18.1367 10.875H6.13672C5.72251 10.875 5.38672 10.5392 5.38672 10.125Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.13672 13.875C3.13672 13.4608 3.47251 13.125 3.88672 13.125H20.3867C20.8009 13.125 21.1367 13.4608 21.1367 13.875C21.1367 14.2892 20.8009 14.625 20.3867 14.625H3.88672C3.47251 14.625 3.13672 14.2892 3.13672 13.875Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.38672 17.625C5.38672 17.2108 5.72251 16.875 6.13672 16.875H18.1367C18.5509 16.875 18.8867 17.2108 18.8867 17.625C18.8867 18.0392 18.5509 18.375 18.1367 18.375H6.13672C5.72251 18.375 5.38672 18.0392 5.38672 17.625Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgTextAlignCenter);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "d322c4e3e1cd6ab4e3632adab3a979a2.svg");

/***/ }),

/***/ 62733:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `@keyframes AIConfigPanel-module__fadeInUp--t4_AF{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes AIConfigPanel-module__sparkle--ufb3d{0%,100%{opacity:.3;transform:scale(1)}50%{opacity:1;transform:scale(1.05)}}@keyframes AIConfigPanel-module__pulse--ERqqk{0%,100%{opacity:1}50%{opacity:.6}}@keyframes AIConfigPanel-module__shimmer--w9flL{0%{background-position:-200% center}100%{background-position:200% center}}@keyframes AIConfigPanel-module__checkBounce--P98RH{0%,100%{transform:scale(1)}50%{transform:scale(1.2)}}@keyframes AIConfigPanel-module__shake--fLIzC{0%,100%{transform:translateX(0)}10%,30%,50%,70%,90%{transform:translateX(-4px)}20%,40%,60%,80%{transform:translateX(4px)}}.AIConfigPanel-module__AIConfigPanel--vMUJp{display:flex;flex-direction:column;gap:24px;max-width:600px;padding:32px;animation:AIConfigPanel-module__fadeInUp--t4_AF .4s ease}.AIConfigPanel-module__Header--YNz1t{display:flex;gap:16px;align-items:flex-start;padding:24px;background:linear-gradient(135deg, rgba(139, 92, 246, 0.1) 0%, rgba(167, 139, 250, 0.05) 100%);border:1px solid rgba(139,92,246,.2);border-radius:8px;box-shadow:0 0 20px rgba(139,92,246,.15);animation:AIConfigPanel-module__sparkle--ufb3d 3s ease-in-out infinite}.AIConfigPanel-module__Header--YNz1t svg{flex-shrink:0;width:32px;height:32px;color:#8b5cf6;filter:drop-shadow(0 2px 4px rgba(139, 92, 246, 0.3));animation:AIConfigPanel-module__pulse--ERqqk 2s ease-in-out infinite}.AIConfigPanel-module__HeaderText--Jn3GK{display:flex;flex-direction:column;gap:8px;flex:1}.AIConfigPanel-module__HeaderText--Jn3GK h3{margin:0;font-size:18px;font-weight:600;color:var(--theme-color-fg-highlight);background:linear-gradient(135deg, #8b5cf6 0%, #a78bfa 100%);-webkit-background-clip:text;-webkit-text-fill-color:rgba(0,0,0,0);background-clip:text}.AIConfigPanel-module__HeaderText--Jn3GK p{margin:0;font-size:14px;line-height:1.5;color:var(--theme-color-fg-default);opacity:.9}.AIConfigPanel-module__Section--wbGMD{display:flex;flex-direction:column;gap:16px;padding:24px;background:var(--theme-color-bg-2);border:1px solid var(--theme-color-bg-3);border-radius:8px;transition:all 250ms ease}.AIConfigPanel-module__Section--wbGMD:hover{border-color:rgba(139,92,246,.3);box-shadow:0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.08)}.AIConfigPanel-module__Section--wbGMD h4{margin:0;font-size:15px;font-weight:600;color:var(--theme-color-fg-highlight);display:flex;align-items:center;gap:8px}.AIConfigPanel-module__Section--wbGMD h4::before{content:"";display:inline-block;width:3px;height:16px;background:linear-gradient(180deg, #8b5cf6 0%, #a78bfa 100%);border-radius:2px}.AIConfigPanel-module__Section--wbGMD a{color:#8b5cf6;text-decoration:none;font-weight:500;transition:all 150ms ease;position:relative}.AIConfigPanel-module__Section--wbGMD a::after{content:"";position:absolute;bottom:-2px;left:0;right:0;height:1px;background:#8b5cf6;transform:scaleX(0);transition:transform 150ms ease}.AIConfigPanel-module__Section--wbGMD a:hover{color:#7c3aed}.AIConfigPanel-module__Section--wbGMD a:hover::after{transform:scaleX(1)}.AIConfigPanel-module__InputGroup--LXXDx{display:flex;gap:12px;align-items:flex-start}.AIConfigPanel-module__InputGroup--LXXDx>:first-child{flex:1}.AIConfigPanel-module__InputGroup--LXXDx button{margin-top:24px;min-width:100px;transition:all 250ms ease}.AIConfigPanel-module__InputGroup--LXXDx button:hover{transform:translateY(-1px);box-shadow:0 4px 6px rgba(0,0,0,.1),0 2px 4px rgba(0,0,0,.06)}.AIConfigPanel-module__InputGroup--LXXDx button:active{transform:translateY(0)}.AIConfigPanel-module__ValidationSuccess--mQSn1{display:flex;gap:12px;align-items:center;padding:12px 16px;background:linear-gradient(135deg, rgba(16, 185, 129, 0.1) 0%, rgba(16, 185, 129, 0.05) 100%);border:1px solid rgba(16,185,129,.3);border-radius:6px;color:#10b981;font-size:13px;font-weight:500;animation:AIConfigPanel-module__checkBounce--P98RH .5s ease}.AIConfigPanel-module__ValidationSuccess--mQSn1 svg{flex-shrink:0;width:18px;height:18px;filter:drop-shadow(0 2px 4px rgba(16, 185, 129, 0.3))}.AIConfigPanel-module__ValidationError--5NZIZ{display:flex;gap:12px;align-items:center;padding:12px 16px;background:linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(239, 68, 68, 0.05) 100%);border:1px solid rgba(239,68,68,.3);border-radius:6px;color:#ef4444;font-size:13px;font-weight:500;animation:AIConfigPanel-module__shake--fLIzC .5s ease}.AIConfigPanel-module__ValidationError--5NZIZ svg{flex-shrink:0;width:18px;height:18px}.AIConfigPanel-module__SecurityNote--p2Wl0{display:flex;gap:12px;align-items:flex-start;padding:16px;background:linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);border-left:3px solid #8b5cf6;border-radius:6px;font-size:13px;line-height:1.6;box-shadow:0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.08)}.AIConfigPanel-module__SecurityNote--p2Wl0 svg{flex-shrink:0;width:20px;height:20px;margin-top:2px;color:#8b5cf6;opacity:.8}.AIConfigPanel-module__SecurityNote--p2Wl0 p{margin:0;color:var(--theme-color-fg-default);opacity:.9}.AIConfigPanel-module__SecurityNote--p2Wl0 strong{color:var(--theme-color-fg-highlight);font-weight:600}.AIConfigPanel-module__Field--oDv0s{display:flex;flex-direction:column;gap:12px}.AIConfigPanel-module__Field--oDv0s>label:first-child{font-size:13px;font-weight:600;color:var(--theme-color-fg-highlight);text-transform:uppercase;letter-spacing:.5px;display:flex;align-items:center;gap:8px}.AIConfigPanel-module__Field--oDv0s>label:first-child::before{content:"";display:inline-block;width:4px;height:4px;background:#8b5cf6;border-radius:50%}.AIConfigPanel-module__Field--oDv0s input[type=text],.AIConfigPanel-module__Field--oDv0s input[type=password]{width:100%;padding:10px 14px;background:var(--theme-color-bg-1);border:2px solid var(--theme-color-bg-3);border-radius:6px;color:var(--theme-color-fg-highlight);font-size:14px;font-family:"SF Mono","Monaco","Consolas",monospace;transition:all 250ms ease}.AIConfigPanel-module__Field--oDv0s input[type=text]::placeholder,.AIConfigPanel-module__Field--oDv0s input[type=password]::placeholder{color:var(--theme-color-fg-default);opacity:.5}.AIConfigPanel-module__Field--oDv0s input[type=text]:focus,.AIConfigPanel-module__Field--oDv0s input[type=password]:focus{outline:none;border-color:#8b5cf6;box-shadow:0 0 0 3px rgba(139,92,246,.1),0 4px 6px rgba(0,0,0,.1),0 2px 4px rgba(0,0,0,.06);transform:translateY(-1px)}.AIConfigPanel-module__Field--oDv0s input[type=text]:disabled,.AIConfigPanel-module__Field--oDv0s input[type=password]:disabled{opacity:.5;cursor:not-allowed}.AIConfigPanel-module__Field--oDv0s .AIConfigPanel-module__FieldDescription--QzFy_{font-size:12px;color:var(--theme-color-fg-default);opacity:.7;line-height:1.5}.AIConfigPanel-module__BudgetRow--nPRpv{display:flex;gap:12px;align-items:center;padding:16px;background:var(--theme-color-bg-3);border-radius:6px;transition:all 250ms ease}.AIConfigPanel-module__BudgetRow--nPRpv:hover{background:var(--theme-color-bg-2)}.AIConfigPanel-module__BudgetRow--nPRpv span{color:var(--theme-color-fg-default);font-size:14px;font-weight:500}.AIConfigPanel-module__BudgetRow--nPRpv .AIConfigPanel-module__BudgetValue--tMKbr{color:var(--theme-color-fg-highlight);font-weight:600;font-size:16px}.AIConfigPanel-module__BudgetInput--rTdcQ{width:90px;padding:8px 12px;background:var(--theme-color-bg-1);border:2px solid var(--theme-color-bg-3);border-radius:6px;color:var(--theme-color-fg-highlight);font-size:15px;font-weight:600;text-align:center;transition:all 250ms ease}.AIConfigPanel-module__BudgetInput--rTdcQ:focus{outline:none;border-color:#8b5cf6;box-shadow:0 0 0 3px rgba(139,92,246,.1);transform:scale(1.05)}.AIConfigPanel-module__BudgetInput--rTdcQ:hover:not(:focus){border-color:rgba(139,92,246,.3)}.AIConfigPanel-module__Checkbox--c2GOo{display:flex;gap:12px;align-items:center;padding:12px;cursor:pointer;font-size:13px;border-radius:6px;transition:all 150ms ease;user-select:none}.AIConfigPanel-module__Checkbox--c2GOo:hover{background:var(--theme-color-bg-3)}.AIConfigPanel-module__Checkbox--c2GOo input[type=checkbox]{cursor:pointer;width:18px;height:18px;accent-color:#8b5cf6;transition:all 150ms ease}.AIConfigPanel-module__Checkbox--c2GOo input[type=checkbox]:focus{outline:2px solid rgba(139,92,246,.3);outline-offset:2px}.AIConfigPanel-module__Checkbox--c2GOo span{color:var(--theme-color-fg-default);line-height:1.5}.AIConfigPanel-module__Actions--UJvSk{display:flex;gap:16px;justify-content:flex-end;margin-top:16px;padding-top:24px;border-top:1px solid var(--theme-color-bg-3)}.AIConfigPanel-module__Actions--UJvSk button{min-width:120px;transition:all 250ms ease}.AIConfigPanel-module__Actions--UJvSk button:hover{transform:translateY(-2px);box-shadow:0 4px 6px rgba(0,0,0,.1),0 2px 4px rgba(0,0,0,.06)}.AIConfigPanel-module__Actions--UJvSk button:active{transform:translateY(0)}.AIConfigPanel-module__Actions--UJvSk button:last-child{background:linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);position:relative;overflow:hidden}.AIConfigPanel-module__Actions--UJvSk button:last-child::before{content:"";position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);transition:left .5s ease}.AIConfigPanel-module__Actions--UJvSk button:last-child:hover::before{left:100%}.AIConfigPanel-module__BudgetWarning--TYPl_{display:flex;gap:12px;align-items:flex-start;padding:16px;background:linear-gradient(135deg, rgba(245, 158, 11, 0.1) 0%, rgba(245, 158, 11, 0.05) 100%);border:1px solid rgba(245,158,11,.3);border-left:3px solid #f59e0b;border-radius:6px;font-size:13px;line-height:1.6;animation:AIConfigPanel-module__pulse--ERqqk 2s ease-in-out infinite}.AIConfigPanel-module__BudgetWarning--TYPl_ svg{flex-shrink:0;width:18px;height:18px;color:#f59e0b;margin-top:2px}.AIConfigPanel-module__BudgetWarning--TYPl_ p{margin:0;color:var(--theme-color-fg-default)}.AIConfigPanel-module__BudgetWarning--TYPl_ strong{color:var(--theme-color-fg-highlight);font-weight:600}.AIConfigPanel-module__APIKeyPreview--Hkhqy{padding:16px;background:var(--theme-color-bg-1);border:1px solid var(--theme-color-bg-3);border-radius:6px;font-family:"SF Mono","Monaco","Consolas",monospace;font-size:13px;color:var(--theme-color-fg-default);letter-spacing:1px;display:flex;align-items:center;justify-content:space-between;gap:16px}.AIConfigPanel-module__APIKeyPreview--Hkhqy .AIConfigPanel-module__KeyText--GLh4u{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.AIConfigPanel-module__APIKeyPreview--Hkhqy button{flex-shrink:0;padding:4px 8px;font-size:11px;opacity:.7;transition:opacity 150ms ease}.AIConfigPanel-module__APIKeyPreview--Hkhqy button:hover{opacity:1}.AIConfigPanel-module__Loading--Eg0gN{display:flex;align-items:center;justify-content:center;gap:12px;padding:24px;color:var(--theme-color-fg-default);font-size:14px}.AIConfigPanel-module__Loading--Eg0gN svg{animation:AIConfigPanel-module__spin--fc4fi 1s linear infinite}@keyframes AIConfigPanel-module__spin--fc4fi{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}.AIConfigPanel-module__FeatureList--WlpqH{display:flex;flex-direction:column;gap:12px;padding:16px 0}.AIConfigPanel-module__FeatureList--WlpqH .AIConfigPanel-module__FeatureItem--bZlQh{display:flex;gap:12px;align-items:flex-start;padding:12px;border-radius:6px;transition:all 150ms ease}.AIConfigPanel-module__FeatureList--WlpqH .AIConfigPanel-module__FeatureItem--bZlQh:hover{background:var(--theme-color-bg-3);transform:translateX(4px)}.AIConfigPanel-module__FeatureList--WlpqH .AIConfigPanel-module__FeatureItem--bZlQh svg{flex-shrink:0;width:16px;height:16px;color:#10b981;margin-top:2px}.AIConfigPanel-module__FeatureList--WlpqH .AIConfigPanel-module__FeatureItem--bZlQh span{font-size:13px;color:var(--theme-color-fg-default);line-height:1.5}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/migration/AIConfigPanel.module.scss"],"names":[],"mappings":"AAoCA,iDACE,KACE,SAAA,CACA,0BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,gDACE,QAEE,UAAA,CACA,kBAAA,CAEF,IACE,SAAA,CACA,qBAAA,CAAA,CAIJ,8CACE,QAEE,SAAA,CAEF,IACE,UAAA,CAAA,CAIJ,gDACE,GACE,gCAAA,CAEF,KACE,+BAAA,CAAA,CAIJ,oDACE,QAEE,kBAAA,CAEF,IACE,oBAAA,CAAA,CAIJ,8CACE,QAEE,uBAAA,CAEF,oBAKE,0BAAA,CAEF,gBAIE,yBAAA,CAAA,CAKJ,4CACE,YAAA,CACA,qBAAA,CACA,QA9FW,CA+FX,eAAA,CACA,YA/FW,CAgGX,wDAAA,CAIF,qCACE,YAAA,CACA,QAxGW,CAyGX,sBAAA,CACA,YAzGW,CA0GX,8FAAA,CACA,oCAAA,CACA,iBAvGU,CAwGV,wCA9FU,CA+FV,sEAAA,CAEA,yCACE,aAAA,CACA,UAAA,CACA,WAAA,CACA,aA9HS,CA+HT,qDAAA,CACA,oEAAA,CAIJ,yCACE,YAAA,CACA,qBAAA,CACA,OAhIW,CAiIX,MAAA,CAEA,4CACE,QAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CACA,4DAAA,CACA,4BAAA,CACA,qCAAA,CACA,oBAAA,CAGF,2CACE,QAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CACA,UAAA,CAKJ,sCACE,YAAA,CACA,qBAAA,CACA,QAzJW,CA0JX,YAzJW,CA0JX,kCAAA,CACA,wCAAA,CACA,iBAvJU,CAwJV,yBAAA,CAEA,4CACE,gCAAA,CACA,8DArJQ,CAwJV,yCACE,QAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CACA,YAAA,CACA,kBAAA,CACA,OA9KS,CAgLT,iDACE,UAAA,CACA,oBAAA,CACA,SAAA,CACA,WAAA,CACA,4DAAA,CACA,iBAAA,CAIJ,wCACE,aAlMS,CAmMT,oBAAA,CACA,eAAA,CACA,yBAAA,CACA,iBAAA,CAEA,+CACE,UAAA,CACA,iBAAA,CACA,WAAA,CACA,MAAA,CACA,OAAA,CACA,UAAA,CACA,kBA/MO,CAgNP,mBAAA,CACA,+BAAA,CAGF,8CACE,aAnNY,CAqNZ,qDACE,mBAAA,CAOR,yCACE,YAAA,CACA,QAzNW,CA0NX,sBAAA,CAEA,sDACE,MAAA,CAGF,gDACE,eAAA,CACA,eAAA,CACA,yBAAA,CAEA,sDACE,0BAAA,CACA,6DAxNM,CA2NR,uDACE,uBAAA,CAMN,gDACE,YAAA,CACA,QAnPW,CAoPX,kBAAA,CACA,iBAAA,CACA,6FAAA,CACA,oCAAA,CACA,iBAlPU,CAmPV,aA9PQ,CA+PR,cAAA,CACA,eAAA,CACA,2DAAA,CAEA,oDACE,aAAA,CACA,UAAA,CACA,WAAA,CACA,qDAAA,CAIJ,8CACE,YAAA,CACA,QAxQW,CAyQX,kBAAA,CACA,iBAAA,CACA,2FAAA,CACA,mCAAA,CACA,iBAvQU,CAwQV,aAlRO,CAmRP,cAAA,CACA,eAAA,CACA,qDAAA,CAEA,kDACE,aAAA,CACA,UAAA,CACA,WAAA,CAKJ,2CACE,YAAA,CACA,QA7RW,CA8RX,sBAAA,CACA,YA9RW,CA+RX,4FAAA,CACA,6BAAA,CACA,iBA5RU,CA6RV,cAAA,CACA,eAAA,CACA,8DAvRU,CAyRV,+CACE,aAAA,CACA,UAAA,CACA,WAAA,CACA,cAAA,CACA,aApTS,CAqTT,UAAA,CAGF,6CACE,QAAA,CACA,mCAAA,CACA,UAAA,CAGF,kDACE,qCAAA,CACA,eAAA,CAKJ,oCACE,YAAA,CACA,qBAAA,CACA,QAhUW,CAkUX,sDACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,wBAAA,CACA,mBAAA,CACA,YAAA,CACA,kBAAA,CACA,OA3US,CA6UT,8DACE,UAAA,CACA,oBAAA,CACA,SAAA,CACA,UAAA,CACA,kBAzVO,CA0VP,iBAAA,CAIJ,8GAEE,UAAA,CACA,iBAAA,CACA,kCAAA,CACA,wCAAA,CACA,iBAtVQ,CAuVR,qCAAA,CACA,cAAA,CACA,mDAAA,CACA,yBAAA,CAEA,wIACE,mCAAA,CACA,UAAA,CAGF,0HACE,YAAA,CACA,oBAjXO,CAkXP,2FAAA,CACA,0BAAA,CAGF,gIACE,UAAA,CACA,kBAAA,CAIJ,mFACE,cAAA,CACA,mCAAA,CACA,UAAA,CACA,eAAA,CAKJ,wCACE,YAAA,CACA,QA/XW,CAgYX,kBAAA,CACA,YAhYW,CAiYX,kCAAA,CACA,iBA7XU,CA8XV,yBAAA,CAEA,8CACE,kCAAA,CAGF,6CACE,mCAAA,CACA,cAAA,CACA,eAAA,CAGF,kFACE,qCAAA,CACA,eAAA,CACA,cAAA,CAIJ,0CACE,UAAA,CACA,gBAAA,CACA,kCAAA,CACA,wCAAA,CACA,iBAtZU,CAuZV,qCAAA,CACA,cAAA,CACA,eAAA,CACA,iBAAA,CACA,yBAAA,CAEA,gDACE,YAAA,CACA,oBA7aS,CA8aT,wCAAA,CACA,qBAAA,CAGF,4DACE,gCAAA,CAKJ,uCACE,YAAA,CACA,QAlbW,CAmbX,kBAAA,CACA,YApbW,CAqbX,cAAA,CACA,cAAA,CACA,iBAjbU,CAkbV,yBAAA,CACA,gBAAA,CAEA,6CACE,kCAAA,CAGF,4DACE,cAAA,CACA,UAAA,CACA,WAAA,CACA,oBA3cS,CA4cT,yBAAA,CAEA,kEACE,qCAAA,CACA,kBAAA,CAIJ,4CACE,mCAAA,CACA,eAAA,CAKJ,sCACE,YAAA,CACA,QApdW,CAqdX,wBAAA,CACA,eAtdW,CAudX,gBAtdW,CAudX,4CAAA,CAEA,6CACE,eAAA,CACA,yBAAA,CAEA,mDACE,0BAAA,CACA,6DAldM,CAqdR,oDACE,uBAAA,CAIF,wDACE,4DAAA,CACA,iBAAA,CACA,eAAA,CAEA,gEACE,UAAA,CACA,iBAAA,CACA,KAAA,CACA,UAAA,CACA,UAAA,CACA,WAAA,CACA,qFAAA,CACA,wBAAA,CAGF,sEACE,SAAA,CAOR,4CACE,YAAA,CACA,QAngBW,CAogBX,sBAAA,CACA,YApgBW,CAqgBX,6FAAA,CACA,oCAAA,CACA,6BAAA,CACA,iBAngBU,CAogBV,cAAA,CACA,eAAA,CACA,oEAAA,CAEA,gDACE,aAAA,CACA,UAAA,CACA,WAAA,CACA,aArhBM,CAshBN,cAAA,CAGF,8CACE,QAAA,CACA,mCAAA,CAGF,mDACE,qCAAA,CACA,eAAA,CAKJ,4CACE,YAliBW,CAmiBX,kCAAA,CACA,wCAAA,CACA,iBAhiBU,CAiiBV,mDAAA,CACA,cAAA,CACA,mCAAA,CACA,kBAAA,CACA,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,QA7iBW,CA+iBX,kFACE,MAAA,CACA,eAAA,CACA,sBAAA,CACA,kBAAA,CAGF,mDACE,aAAA,CACA,eAAA,CACA,cAAA,CACA,UAAA,CACA,6BAAA,CAEA,yDACE,SAAA,CAMN,sCACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,QAzkBW,CA0kBX,YAxkBW,CAykBX,mCAAA,CACA,cAAA,CAEA,0CACE,8DAAA,CAIJ,6CACE,KACE,sBAAA,CAEF,GACE,wBAAA,CAAA,CAKJ,0CACE,YAAA,CACA,qBAAA,CACA,QAhmBW,CAimBX,cAAA,CAEA,oFACE,YAAA,CACA,QArmBS,CAsmBT,sBAAA,CACA,YAvmBS,CAwmBT,iBAlmBQ,CAmmBR,yBAAA,CAEA,0FACE,kCAAA,CACA,yBAAA,CAGF,wFACE,aAAA,CACA,UAAA,CACA,WAAA,CACA,aAznBI,CA0nBJ,cAAA,CAGF,yFACE,cAAA,CACA,mCAAA,CACA,eAAA","sourcesContent":["// =============================================================================\n// AI Configuration Panel\n// =============================================================================\n// Enhanced styling for AI setup: API key configuration, budget settings,\n// and security information. Uses purple AI theming with modern animations.\n// =============================================================================\n\n// Design System Variables\n$ai-primary: #8b5cf6;\n$ai-primary-light: #a78bfa;\n$ai-primary-dark: #7c3aed;\n$success: #10b981;\n$danger: #ef4444;\n$warning: #f59e0b;\n\n$spacing-xs: 8px;\n$spacing-sm: 12px;\n$spacing-md: 16px;\n$spacing-lg: 24px;\n$spacing-xl: 32px;\n\n$radius-sm: 4px;\n$radius-md: 6px;\n$radius-lg: 8px;\n$radius-xl: 12px;\n\n$transition-fast: 150ms ease;\n$transition-base: 250ms ease;\n$transition-slow: 400ms ease;\n\n$shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.08);\n$shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);\n$shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1), 0 4px 6px rgba(0, 0, 0, 0.05);\n$shadow-ai: 0 0 20px rgba(139, 92, 246, 0.15);\n\n// Animations\n@keyframes fadeInUp {\n  from {\n    opacity: 0;\n    transform: translateY(10px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n@keyframes sparkle {\n  0%,\n  100% {\n    opacity: 0.3;\n    transform: scale(1);\n  }\n  50% {\n    opacity: 1;\n    transform: scale(1.05);\n  }\n}\n\n@keyframes pulse {\n  0%,\n  100% {\n    opacity: 1;\n  }\n  50% {\n    opacity: 0.6;\n  }\n}\n\n@keyframes shimmer {\n  0% {\n    background-position: -200% center;\n  }\n  100% {\n    background-position: 200% center;\n  }\n}\n\n@keyframes checkBounce {\n  0%,\n  100% {\n    transform: scale(1);\n  }\n  50% {\n    transform: scale(1.2);\n  }\n}\n\n@keyframes shake {\n  0%,\n  100% {\n    transform: translateX(0);\n  }\n  10%,\n  30%,\n  50%,\n  70%,\n  90% {\n    transform: translateX(-4px);\n  }\n  20%,\n  40%,\n  60%,\n  80% {\n    transform: translateX(4px);\n  }\n}\n\n// Main Container\n.AIConfigPanel {\n  display: flex;\n  flex-direction: column;\n  gap: $spacing-lg;\n  max-width: 600px;\n  padding: $spacing-xl;\n  animation: fadeInUp 0.4s ease;\n}\n\n// Header Section\n.Header {\n  display: flex;\n  gap: $spacing-md;\n  align-items: flex-start;\n  padding: $spacing-lg;\n  background: linear-gradient(135deg, rgba(139, 92, 246, 0.1) 0%, rgba(167, 139, 250, 0.05) 100%);\n  border: 1px solid rgba(139, 92, 246, 0.2);\n  border-radius: $radius-lg;\n  box-shadow: $shadow-ai;\n  animation: sparkle 3s ease-in-out infinite;\n\n  svg {\n    flex-shrink: 0;\n    width: 32px;\n    height: 32px;\n    color: $ai-primary;\n    filter: drop-shadow(0 2px 4px rgba(139, 92, 246, 0.3));\n    animation: pulse 2s ease-in-out infinite;\n  }\n}\n\n.HeaderText {\n  display: flex;\n  flex-direction: column;\n  gap: $spacing-xs;\n  flex: 1;\n\n  h3 {\n    margin: 0;\n    font-size: 18px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    background: linear-gradient(135deg, $ai-primary 0%, $ai-primary-light 100%);\n    -webkit-background-clip: text;\n    -webkit-text-fill-color: transparent;\n    background-clip: text;\n  }\n\n  p {\n    margin: 0;\n    font-size: 14px;\n    line-height: 1.5;\n    color: var(--theme-color-fg-default);\n    opacity: 0.9;\n  }\n}\n\n// Section Container\n.Section {\n  display: flex;\n  flex-direction: column;\n  gap: $spacing-md;\n  padding: $spacing-lg;\n  background: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-bg-3);\n  border-radius: $radius-lg;\n  transition: all $transition-base;\n\n  &:hover {\n    border-color: rgba(139, 92, 246, 0.3);\n    box-shadow: $shadow-sm;\n  }\n\n  h4 {\n    margin: 0;\n    font-size: 15px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    display: flex;\n    align-items: center;\n    gap: $spacing-xs;\n\n    &::before {\n      content: '';\n      display: inline-block;\n      width: 3px;\n      height: 16px;\n      background: linear-gradient(180deg, $ai-primary 0%, $ai-primary-light 100%);\n      border-radius: 2px;\n    }\n  }\n\n  a {\n    color: $ai-primary;\n    text-decoration: none;\n    font-weight: 500;\n    transition: all $transition-fast;\n    position: relative;\n\n    &::after {\n      content: '';\n      position: absolute;\n      bottom: -2px;\n      left: 0;\n      right: 0;\n      height: 1px;\n      background: $ai-primary;\n      transform: scaleX(0);\n      transition: transform $transition-fast;\n    }\n\n    &:hover {\n      color: $ai-primary-dark;\n\n      &::after {\n        transform: scaleX(1);\n      }\n    }\n  }\n}\n\n// Input Group\n.InputGroup {\n  display: flex;\n  gap: $spacing-sm;\n  align-items: flex-start;\n\n  > :first-child {\n    flex: 1;\n  }\n\n  button {\n    margin-top: 24px; // Align with input field\n    min-width: 100px;\n    transition: all $transition-base;\n\n    &:hover {\n      transform: translateY(-1px);\n      box-shadow: $shadow-md;\n    }\n\n    &:active {\n      transform: translateY(0);\n    }\n  }\n}\n\n// Validation Messages\n.ValidationSuccess {\n  display: flex;\n  gap: $spacing-sm;\n  align-items: center;\n  padding: $spacing-sm $spacing-md;\n  background: linear-gradient(135deg, rgba(16, 185, 129, 0.1) 0%, rgba(16, 185, 129, 0.05) 100%);\n  border: 1px solid rgba(16, 185, 129, 0.3);\n  border-radius: $radius-md;\n  color: $success;\n  font-size: 13px;\n  font-weight: 500;\n  animation: checkBounce 0.5s ease;\n\n  svg {\n    flex-shrink: 0;\n    width: 18px;\n    height: 18px;\n    filter: drop-shadow(0 2px 4px rgba(16, 185, 129, 0.3));\n  }\n}\n\n.ValidationError {\n  display: flex;\n  gap: $spacing-sm;\n  align-items: center;\n  padding: $spacing-sm $spacing-md;\n  background: linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(239, 68, 68, 0.05) 100%);\n  border: 1px solid rgba(239, 68, 68, 0.3);\n  border-radius: $radius-md;\n  color: $danger;\n  font-size: 13px;\n  font-weight: 500;\n  animation: shake 0.5s ease;\n\n  svg {\n    flex-shrink: 0;\n    width: 18px;\n    height: 18px;\n  }\n}\n\n// Security Note\n.SecurityNote {\n  display: flex;\n  gap: $spacing-sm;\n  align-items: flex-start;\n  padding: $spacing-md;\n  background: linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);\n  border-left: 3px solid $ai-primary;\n  border-radius: $radius-md;\n  font-size: 13px;\n  line-height: 1.6;\n  box-shadow: $shadow-sm;\n\n  svg {\n    flex-shrink: 0;\n    width: 20px;\n    height: 20px;\n    margin-top: 2px;\n    color: $ai-primary;\n    opacity: 0.8;\n  }\n\n  p {\n    margin: 0;\n    color: var(--theme-color-fg-default);\n    opacity: 0.9;\n  }\n\n  strong {\n    color: var(--theme-color-fg-highlight);\n    font-weight: 600;\n  }\n}\n\n// Form Field\n.Field {\n  display: flex;\n  flex-direction: column;\n  gap: $spacing-sm;\n\n  > label:first-child {\n    font-size: 13px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    text-transform: uppercase;\n    letter-spacing: 0.5px;\n    display: flex;\n    align-items: center;\n    gap: $spacing-xs;\n\n    &::before {\n      content: '';\n      display: inline-block;\n      width: 4px;\n      height: 4px;\n      background: $ai-primary;\n      border-radius: 50%;\n    }\n  }\n\n  input[type='text'],\n  input[type='password'] {\n    width: 100%;\n    padding: 10px 14px;\n    background: var(--theme-color-bg-1);\n    border: 2px solid var(--theme-color-bg-3);\n    border-radius: $radius-md;\n    color: var(--theme-color-fg-highlight);\n    font-size: 14px;\n    font-family: 'SF Mono', 'Monaco', 'Consolas', monospace;\n    transition: all $transition-base;\n\n    &::placeholder {\n      color: var(--theme-color-fg-default);\n      opacity: 0.5;\n    }\n\n    &:focus {\n      outline: none;\n      border-color: $ai-primary;\n      box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1), $shadow-md;\n      transform: translateY(-1px);\n    }\n\n    &:disabled {\n      opacity: 0.5;\n      cursor: not-allowed;\n    }\n  }\n\n  .FieldDescription {\n    font-size: 12px;\n    color: var(--theme-color-fg-default);\n    opacity: 0.7;\n    line-height: 1.5;\n  }\n}\n\n// Budget Configuration\n.BudgetRow {\n  display: flex;\n  gap: $spacing-sm;\n  align-items: center;\n  padding: $spacing-md;\n  background: var(--theme-color-bg-3);\n  border-radius: $radius-md;\n  transition: all $transition-base;\n\n  &:hover {\n    background: var(--theme-color-bg-2);\n  }\n\n  span {\n    color: var(--theme-color-fg-default);\n    font-size: 14px;\n    font-weight: 500;\n  }\n\n  .BudgetValue {\n    color: var(--theme-color-fg-highlight);\n    font-weight: 600;\n    font-size: 16px;\n  }\n}\n\n.BudgetInput {\n  width: 90px;\n  padding: 8px 12px;\n  background: var(--theme-color-bg-1);\n  border: 2px solid var(--theme-color-bg-3);\n  border-radius: $radius-md;\n  color: var(--theme-color-fg-highlight);\n  font-size: 15px;\n  font-weight: 600;\n  text-align: center;\n  transition: all $transition-base;\n\n  &:focus {\n    outline: none;\n    border-color: $ai-primary;\n    box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1);\n    transform: scale(1.05);\n  }\n\n  &:hover:not(:focus) {\n    border-color: rgba(139, 92, 246, 0.3);\n  }\n}\n\n// Checkbox\n.Checkbox {\n  display: flex;\n  gap: $spacing-sm;\n  align-items: center;\n  padding: $spacing-sm;\n  cursor: pointer;\n  font-size: 13px;\n  border-radius: $radius-md;\n  transition: all $transition-fast;\n  user-select: none;\n\n  &:hover {\n    background: var(--theme-color-bg-3);\n  }\n\n  input[type='checkbox'] {\n    cursor: pointer;\n    width: 18px;\n    height: 18px;\n    accent-color: $ai-primary;\n    transition: all $transition-fast;\n\n    &:focus {\n      outline: 2px solid rgba(139, 92, 246, 0.3);\n      outline-offset: 2px;\n    }\n  }\n\n  span {\n    color: var(--theme-color-fg-default);\n    line-height: 1.5;\n  }\n}\n\n// Actions\n.Actions {\n  display: flex;\n  gap: $spacing-md;\n  justify-content: flex-end;\n  margin-top: $spacing-md;\n  padding-top: $spacing-lg;\n  border-top: 1px solid var(--theme-color-bg-3);\n\n  button {\n    min-width: 120px;\n    transition: all $transition-base;\n\n    &:hover {\n      transform: translateY(-2px);\n      box-shadow: $shadow-md;\n    }\n\n    &:active {\n      transform: translateY(0);\n    }\n\n    // Primary action (Continue button)\n    &:last-child {\n      background: linear-gradient(135deg, $ai-primary 0%, $ai-primary-dark 100%);\n      position: relative;\n      overflow: hidden;\n\n      &::before {\n        content: '';\n        position: absolute;\n        top: 0;\n        left: -100%;\n        width: 100%;\n        height: 100%;\n        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);\n        transition: left 0.5s ease;\n      }\n\n      &:hover::before {\n        left: 100%;\n      }\n    }\n  }\n}\n\n// Budget Warning (when close to limit)\n.BudgetWarning {\n  display: flex;\n  gap: $spacing-sm;\n  align-items: flex-start;\n  padding: $spacing-md;\n  background: linear-gradient(135deg, rgba(245, 158, 11, 0.1) 0%, rgba(245, 158, 11, 0.05) 100%);\n  border: 1px solid rgba(245, 158, 11, 0.3);\n  border-left: 3px solid $warning;\n  border-radius: $radius-md;\n  font-size: 13px;\n  line-height: 1.6;\n  animation: pulse 2s ease-in-out infinite;\n\n  svg {\n    flex-shrink: 0;\n    width: 18px;\n    height: 18px;\n    color: $warning;\n    margin-top: 2px;\n  }\n\n  p {\n    margin: 0;\n    color: var(--theme-color-fg-default);\n  }\n\n  strong {\n    color: var(--theme-color-fg-highlight);\n    font-weight: 600;\n  }\n}\n\n// API Key Preview (masked display)\n.APIKeyPreview {\n  padding: $spacing-md;\n  background: var(--theme-color-bg-1);\n  border: 1px solid var(--theme-color-bg-3);\n  border-radius: $radius-md;\n  font-family: 'SF Mono', 'Monaco', 'Consolas', monospace;\n  font-size: 13px;\n  color: var(--theme-color-fg-default);\n  letter-spacing: 1px;\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: $spacing-md;\n\n  .KeyText {\n    flex: 1;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n  }\n\n  button {\n    flex-shrink: 0;\n    padding: 4px 8px;\n    font-size: 11px;\n    opacity: 0.7;\n    transition: opacity $transition-fast;\n\n    &:hover {\n      opacity: 1;\n    }\n  }\n}\n\n// Loading State\n.Loading {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  gap: $spacing-sm;\n  padding: $spacing-lg;\n  color: var(--theme-color-fg-default);\n  font-size: 14px;\n\n  svg {\n    animation: spin 1s linear infinite;\n  }\n}\n\n@keyframes spin {\n  from {\n    transform: rotate(0deg);\n  }\n  to {\n    transform: rotate(360deg);\n  }\n}\n\n// Feature List (benefits of AI migration)\n.FeatureList {\n  display: flex;\n  flex-direction: column;\n  gap: $spacing-sm;\n  padding: $spacing-md 0;\n\n  .FeatureItem {\n    display: flex;\n    gap: $spacing-sm;\n    align-items: flex-start;\n    padding: $spacing-sm;\n    border-radius: $radius-md;\n    transition: all $transition-fast;\n\n    &:hover {\n      background: var(--theme-color-bg-3);\n      transform: translateX(4px);\n    }\n\n    svg {\n      flex-shrink: 0;\n      width: 16px;\n      height: 16px;\n      color: $success;\n      margin-top: 2px;\n    }\n\n    span {\n      font-size: 13px;\n      color: var(--theme-color-fg-default);\n      line-height: 1.5;\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"AIConfigPanel": `AIConfigPanel-module__AIConfigPanel--vMUJp`,
	"fadeInUp": `AIConfigPanel-module__fadeInUp--t4_AF`,
	"Header": `AIConfigPanel-module__Header--YNz1t`,
	"sparkle": `AIConfigPanel-module__sparkle--ufb3d`,
	"pulse": `AIConfigPanel-module__pulse--ERqqk`,
	"HeaderText": `AIConfigPanel-module__HeaderText--Jn3GK`,
	"Section": `AIConfigPanel-module__Section--wbGMD`,
	"InputGroup": `AIConfigPanel-module__InputGroup--LXXDx`,
	"ValidationSuccess": `AIConfigPanel-module__ValidationSuccess--mQSn1`,
	"checkBounce": `AIConfigPanel-module__checkBounce--P98RH`,
	"ValidationError": `AIConfigPanel-module__ValidationError--5NZIZ`,
	"shake": `AIConfigPanel-module__shake--fLIzC`,
	"SecurityNote": `AIConfigPanel-module__SecurityNote--p2Wl0`,
	"Field": `AIConfigPanel-module__Field--oDv0s`,
	"FieldDescription": `AIConfigPanel-module__FieldDescription--QzFy_`,
	"BudgetRow": `AIConfigPanel-module__BudgetRow--nPRpv`,
	"BudgetValue": `AIConfigPanel-module__BudgetValue--tMKbr`,
	"BudgetInput": `AIConfigPanel-module__BudgetInput--rTdcQ`,
	"Checkbox": `AIConfigPanel-module__Checkbox--c2GOo`,
	"Actions": `AIConfigPanel-module__Actions--UJvSk`,
	"BudgetWarning": `AIConfigPanel-module__BudgetWarning--TYPl_`,
	"APIKeyPreview": `AIConfigPanel-module__APIKeyPreview--Hkhqy`,
	"KeyText": `AIConfigPanel-module__KeyText--GLh4u`,
	"Loading": `AIConfigPanel-module__Loading--Eg0gN`,
	"spin": `AIConfigPanel-module__spin--fc4fi`,
	"FeatureList": `AIConfigPanel-module__FeatureList--WlpqH`,
	"FeatureItem": `AIConfigPanel-module__FeatureItem--bZlQh`,
	"shimmer": `AIConfigPanel-module__shimmer--w9flL`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 62877:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* unused harmony exports cssDefaults, lessDefaults, scssDefaults */
/* harmony import */ var _editor_editor_api_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15618);

/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));

// src/fillers/monaco-editor-core.ts
var monaco_editor_core_exports = {};
__reExport(monaco_editor_core_exports, _editor_editor_api_js__WEBPACK_IMPORTED_MODULE_0__);


// src/language/css/monaco.contribution.ts
var LanguageServiceDefaultsImpl = class {
  _onDidChange = new monaco_editor_core_exports.Emitter();
  _options;
  _modeConfiguration;
  _languageId;
  constructor(languageId, options, modeConfiguration) {
    this._languageId = languageId;
    this.setOptions(options);
    this.setModeConfiguration(modeConfiguration);
  }
  get onDidChange() {
    return this._onDidChange.event;
  }
  get languageId() {
    return this._languageId;
  }
  get modeConfiguration() {
    return this._modeConfiguration;
  }
  get diagnosticsOptions() {
    return this.options;
  }
  get options() {
    return this._options;
  }
  setOptions(options) {
    this._options = options || /* @__PURE__ */ Object.create(null);
    this._onDidChange.fire(this);
  }
  setDiagnosticsOptions(options) {
    this.setOptions(options);
  }
  setModeConfiguration(modeConfiguration) {
    this._modeConfiguration = modeConfiguration || /* @__PURE__ */ Object.create(null);
    this._onDidChange.fire(this);
  }
};
var optionsDefault = {
  validate: true,
  lint: {
    compatibleVendorPrefixes: "ignore",
    vendorPrefix: "warning",
    duplicateProperties: "warning",
    emptyRules: "warning",
    importStatement: "ignore",
    boxModel: "ignore",
    universalSelector: "ignore",
    zeroUnits: "ignore",
    fontFaceProperties: "warning",
    hexColorLength: "error",
    argumentsInColorFunction: "error",
    unknownProperties: "warning",
    ieHack: "ignore",
    unknownVendorSpecificProperties: "ignore",
    propertyIgnoredDueToDisplay: "warning",
    important: "ignore",
    float: "ignore",
    idSelector: "ignore"
  },
  data: { useDefaultDataProvider: true },
  format: {
    newlineBetweenSelectors: true,
    newlineBetweenRules: true,
    spaceAroundSelectorSeparator: false,
    braceStyle: "collapse",
    maxPreserveNewLines: void 0,
    preserveNewLines: true
  }
};
var modeConfigurationDefault = {
  completionItems: true,
  hovers: true,
  documentSymbols: true,
  definitions: true,
  references: true,
  documentHighlights: true,
  rename: true,
  colors: true,
  foldingRanges: true,
  diagnostics: true,
  selectionRanges: true,
  documentFormattingEdits: true,
  documentRangeFormattingEdits: true
};
var cssDefaults = new LanguageServiceDefaultsImpl("css", optionsDefault, modeConfigurationDefault);
var scssDefaults = new LanguageServiceDefaultsImpl("scss", optionsDefault, modeConfigurationDefault);
var lessDefaults = new LanguageServiceDefaultsImpl("less", optionsDefault, modeConfigurationDefault);
monaco_editor_core_exports.languages.css = { cssDefaults, lessDefaults, scssDefaults };
function getMode() {
  if (false) // removed by dead control flow
{} else {
    return __webpack_require__.e(/* import() */ 532).then(__webpack_require__.bind(__webpack_require__, 65532));
  }
}
monaco_editor_core_exports.languages.onLanguage("less", () => {
  getMode().then((mode) => mode.setupMode(lessDefaults));
});
monaco_editor_core_exports.languages.onLanguage("scss", () => {
  getMode().then((mode) => mode.setupMode(scssDefaults));
});
monaco_editor_core_exports.languages.onLanguage("css", () => {
  getMode().then((mode) => mode.setupMode(cssDefaults));
});



/***/ }),

/***/ 63065:
/***/ ((module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
exports = module.exports = function (...args) {
  return new exports.default(...args)
}
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.AnthropicError = exports.PagePromise = exports.AI_PROMPT = exports.HUMAN_PROMPT = exports.Anthropic = exports.BaseAnthropic = exports.APIPromise = exports.toFile = exports["default"] = void 0;
var client_1 = __webpack_require__(88514);
Object.defineProperty(exports, "default", ({ enumerable: true, get: function () { return client_1.Anthropic; } }));
var uploads_1 = __webpack_require__(89951);
Object.defineProperty(exports, "toFile", ({ enumerable: true, get: function () { return uploads_1.toFile; } }));
var api_promise_1 = __webpack_require__(15845);
Object.defineProperty(exports, "APIPromise", ({ enumerable: true, get: function () { return api_promise_1.APIPromise; } }));
var client_2 = __webpack_require__(88514);
Object.defineProperty(exports, "BaseAnthropic", ({ enumerable: true, get: function () { return client_2.BaseAnthropic; } }));
Object.defineProperty(exports, "Anthropic", ({ enumerable: true, get: function () { return client_2.Anthropic; } }));
Object.defineProperty(exports, "HUMAN_PROMPT", ({ enumerable: true, get: function () { return client_2.HUMAN_PROMPT; } }));
Object.defineProperty(exports, "AI_PROMPT", ({ enumerable: true, get: function () { return client_2.AI_PROMPT; } }));
var pagination_1 = __webpack_require__(92081);
Object.defineProperty(exports, "PagePromise", ({ enumerable: true, get: function () { return pagination_1.PagePromise; } }));
var error_1 = __webpack_require__(37015);
Object.defineProperty(exports, "AnthropicError", ({ enumerable: true, get: function () { return error_1.AnthropicError; } }));
Object.defineProperty(exports, "APIError", ({ enumerable: true, get: function () { return error_1.APIError; } }));
Object.defineProperty(exports, "APIConnectionError", ({ enumerable: true, get: function () { return error_1.APIConnectionError; } }));
Object.defineProperty(exports, "APIConnectionTimeoutError", ({ enumerable: true, get: function () { return error_1.APIConnectionTimeoutError; } }));
Object.defineProperty(exports, "APIUserAbortError", ({ enumerable: true, get: function () { return error_1.APIUserAbortError; } }));
Object.defineProperty(exports, "NotFoundError", ({ enumerable: true, get: function () { return error_1.NotFoundError; } }));
Object.defineProperty(exports, "ConflictError", ({ enumerable: true, get: function () { return error_1.ConflictError; } }));
Object.defineProperty(exports, "RateLimitError", ({ enumerable: true, get: function () { return error_1.RateLimitError; } }));
Object.defineProperty(exports, "BadRequestError", ({ enumerable: true, get: function () { return error_1.BadRequestError; } }));
Object.defineProperty(exports, "AuthenticationError", ({ enumerable: true, get: function () { return error_1.AuthenticationError; } }));
Object.defineProperty(exports, "InternalServerError", ({ enumerable: true, get: function () { return error_1.InternalServerError; } }));
Object.defineProperty(exports, "PermissionDeniedError", ({ enumerable: true, get: function () { return error_1.PermissionDeniedError; } }));
Object.defineProperty(exports, "UnprocessableEntityError", ({ enumerable: true, get: function () { return error_1.UnprocessableEntityError; } }));
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 63098:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDeviceLaptop = function SvgDeviceLaptop(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.06415 5.28364C4.22841 5.11938 4.45119 5.0271 4.68349 5.0271H19.3164C19.5487 5.0271 19.7714 5.11938 19.9357 5.28364C20.0999 5.4479 20.1922 5.67068 20.1922 5.90297V15.7211H3.80762V5.90297C3.80762 5.67068 3.8999 5.4479 4.06415 5.28364ZM3.05182 17.2211C3.05375 17.2211 3.05568 17.2212 3.05762 17.2212C3.05955 17.2212 3.06148 17.2211 3.06341 17.2211H20.9364C20.9384 17.2211 20.9403 17.2212 20.9422 17.2212C20.9442 17.2212 20.9461 17.2211 20.948 17.2211H21.818V18.097C21.818 18.3293 21.7257 18.5521 21.5615 18.7163C21.3972 18.8806 21.1744 18.9729 20.9421 18.9729H3.05751C2.82522 18.9729 2.60244 18.8806 2.43818 18.7163C2.27392 18.5521 2.18164 18.3293 2.18164 18.097V17.2211H3.05182ZM2.30762 15.7211V5.90297C2.30762 5.27285 2.55793 4.66854 3.00349 4.22298C3.44906 3.77741 4.05337 3.5271 4.68349 3.5271H19.3164C19.9465 3.5271 20.5508 3.77741 20.9963 4.22298C21.4419 4.66854 21.6922 5.27285 21.6922 5.90297V15.7211H22.568C22.9822 15.7211 23.318 16.0569 23.318 16.4711V18.097C23.318 18.7271 23.0677 19.3314 22.6221 19.777C22.1766 20.2226 21.5722 20.4729 20.9421 20.4729H3.05751C2.42739 20.4729 1.82308 20.2226 1.37752 19.777C0.931955 19.3314 0.681641 18.7271 0.681641 18.097V16.4711C0.681641 16.0569 1.01743 15.7211 1.43164 15.7211H2.30762Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDeviceLaptop);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "d64aed499d3b5ec267826248b94d1465.svg");

/***/ }),

/***/ 63351:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCloudFunction = function SvgCloudFunction(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M6.16495 9.7121C6.16495 10.1434 6.51455 10.493 6.9458 10.493C7.37706 10.493 7.72666 10.1434 7.72666 9.7121H6.16495ZM8.20978 5.54532L7.56052 5.1115L7.56052 5.1115L8.20978 5.54532ZM15.909 2.35621L16.0613 1.59036L16.0613 1.59036L15.909 2.35621ZM19.7491 4.4088L20.3012 3.85665L20.3012 3.85665L19.7491 4.4088ZM20.6535 12.2834C20.4884 12.6818 20.6776 13.1386 21.0761 13.3036C21.4745 13.4687 21.9313 13.2795 22.0963 12.881L20.6535 12.2834ZM2.48349 15.6744L1.93134 16.2266L1.93134 16.2266L2.48349 15.6744ZM2.48349 8.24979L1.93134 7.69764L1.93134 7.69764L2.48349 8.24979ZM6.1958 6.7121L6.1958 7.49296L6.19609 7.49296L6.1958 6.7121ZM7.31046 7.62924C7.72896 7.73333 8.15261 7.47845 8.25669 7.05995C8.36078 6.64144 8.1059 6.2178 7.6874 6.11371L7.31046 7.62924ZM7.48982 17.993C7.92108 17.993 8.27068 17.6434 8.27068 17.2121C8.27068 16.7808 7.92108 16.4312 7.48982 16.4312V17.993ZM12.3221 19.1264C12.3221 19.5577 12.6717 19.9073 13.1029 19.9073C13.5342 19.9073 13.8838 19.5577 13.8838 19.1264H12.3221ZM13.1029 10.9289L12.3251 10.8598L12.3221 10.8943V10.9289H13.1029ZM15.1309 9.00081L15.1309 9.78176L15.143 9.78157L15.1309 9.00081ZM16.3632 10.1673C16.7193 10.4106 17.2052 10.3192 17.4485 9.96309C17.6918 9.60702 17.6003 9.12114 17.2442 8.87785L16.3632 10.1673ZM11 12.9075C10.5687 12.9075 10.2191 13.2571 10.2191 13.6884C10.2191 14.1196 10.5687 14.4692 11 14.4692V12.9075ZM17 14.4692C17.4313 14.4692 17.7809 14.1196 17.7809 13.6884C17.7809 13.2571 17.4313 12.9075 17 12.9075V14.4692ZM7.72666 9.7121C7.72666 8.38318 8.12073 7.0841 8.85904 5.97914L7.56052 5.1115C6.65061 6.47328 6.16495 8.0743 6.16495 9.7121H7.72666ZM8.85904 5.97914C9.59735 4.87419 10.6467 4.01298 11.8745 3.50442L11.2769 2.06159C9.76373 2.68835 8.47043 3.74972 7.56052 5.1115L8.85904 5.97914ZM11.8745 3.50442C13.1023 2.99586 14.4533 2.8628 15.7566 3.12206L16.0613 1.59036C14.455 1.27084 12.79 1.43483 11.2769 2.06159L11.8745 3.50442ZM15.7566 3.12206C17.06 3.38132 18.2573 4.02126 19.197 4.96095L20.3012 3.85665C19.1432 2.69855 17.6676 1.90988 16.0613 1.59036L15.7566 3.12206ZM19.197 4.96095C20.1366 5.90064 20.7766 7.09787 21.0358 8.40126L22.5675 8.09659C22.248 6.49026 21.4593 5.01475 20.3012 3.85665L19.197 4.96095ZM21.0358 8.40126C21.2951 9.70465 21.162 11.0556 20.6535 12.2834L22.0963 12.881C22.7231 11.3679 22.8871 9.70292 22.5675 8.09659L21.0358 8.40126ZM6.1958 16.4312C5.01051 16.4312 3.87377 15.9604 3.03564 15.1223L1.93134 16.2266C3.06235 17.3576 4.59632 17.993 6.1958 17.993V16.4312ZM3.03564 15.1223C2.19751 14.2841 1.72666 13.1474 1.72666 11.9621H0.164946C0.164946 13.5616 0.800338 15.0956 1.93134 16.2266L3.03564 15.1223ZM1.72666 11.9621C1.72666 10.7768 2.19751 9.64007 3.03564 8.80194L1.93134 7.69764C0.800337 8.82865 0.164946 10.3626 0.164946 11.9621H1.72666ZM3.03564 8.80194C3.87377 7.96381 5.01051 7.49296 6.1958 7.49296V5.93125C4.59632 5.93125 3.06235 6.56664 1.93134 7.69764L3.03564 8.80194ZM6.19609 7.49296C6.57171 7.49281 6.94594 7.53858 7.31046 7.62924L7.6874 6.11371C7.19939 5.99233 6.69838 5.93106 6.19551 5.93125L6.19609 7.49296ZM7.48982 16.4312H6.1958V17.993H7.48982V16.4312ZM13.8838 19.1264V13.6884H12.3221V19.1264H13.8838ZM13.8838 13.6884V10.9289H12.3221V13.6884H13.8838ZM13.8807 10.9981C13.9215 10.5396 14.0001 10.2615 14.1349 10.0918C14.2312 9.97051 14.4554 9.78166 15.1309 9.78166V8.21995C14.1388 8.21995 13.3915 8.51685 12.912 9.12045C12.471 9.67566 12.3694 10.3616 12.3251 10.8598L13.8807 10.9981ZM15.143 9.78157C15.4023 9.77756 15.5773 9.79741 15.7385 9.84506C15.9011 9.89314 16.0924 9.98228 16.3632 10.1673L17.2442 8.87785C16.8831 8.6311 16.5439 8.45463 16.1811 8.3474C15.8169 8.23974 15.4714 8.21459 15.1188 8.22005L15.143 9.78157ZM11 14.4692H13.1029V12.9075H11V14.4692ZM13.1029 14.4692H17V12.9075H13.1029V14.4692Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCloudFunction);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "3ffb2b9aed739e709dffced8e633a02b.svg");

/***/ }),

/***/ 63520:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ActivityIndicator-module__Root--jL2Fv.ActivityIndicator-module__is-overlay--sKAmE{position:absolute;top:0;left:0;right:0;bottom:0;background-color:var(--theme-color-bg-1-transparent);display:flex;justify-content:center;align-items:center}.ActivityIndicator-module__Inner--r7S6h{text-align:center;display:flex}.ActivityIndicator-module__Inner--r7S6h.ActivityIndicator-module__is-size-small--X0qdF{transform:scale(0.7)}.ActivityIndicator-module__FirstDot--zITNg,.ActivityIndicator-module__SecondDot--GtMTf,.ActivityIndicator-module__ThirdDot--V4QDy{width:8px;height:8px;margin:3px;border-radius:100%;animation:ActivityIndicator-module__bouncedelay--Ft7_b 1.4s infinite var(--easing-base) both}.ActivityIndicator-module__FirstDot--zITNg.ActivityIndicator-module__is-color-light--wrVDT,.ActivityIndicator-module__SecondDot--GtMTf.ActivityIndicator-module__is-color-light--wrVDT,.ActivityIndicator-module__ThirdDot--V4QDy.ActivityIndicator-module__is-color-light--wrVDT{background-color:var(--theme-color-fg-highlight)}.ActivityIndicator-module__FirstDot--zITNg.ActivityIndicator-module__is-color-dark--noBtT,.ActivityIndicator-module__SecondDot--GtMTf.ActivityIndicator-module__is-color-dark--noBtT,.ActivityIndicator-module__ThirdDot--V4QDy.ActivityIndicator-module__is-color-dark--noBtT{background-color:var(--theme-color-bg-1)}.ActivityIndicator-module__FirstDot--zITNg{animation-delay:-0.32s}.ActivityIndicator-module__SecondDot--GtMTf{animation-delay:-0.16s}@keyframes ActivityIndicator-module__bouncedelay--Ft7_b{0%,80%,100%{transform:scale(0)}40%{transform:scale(1)}}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/common/ActivityIndicator/ActivityIndicator.module.scss"],"names":[],"mappings":"AACE,mFACE,iBAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,oDAAA,CACA,YAAA,CACA,sBAAA,CACA,kBAAA,CAIJ,wCACE,iBAAA,CACA,YAAA,CAEA,uFACE,oBAAA,CAIJ,kIAGE,SAAA,CACA,UAAA,CACA,UAAA,CAEA,kBAAA,CACA,4FAAA,CAEA,kRACE,gDAAA,CAGF,+QACE,wCAAA,CAIJ,2CACE,sBAAA,CAGF,4CACE,sBAAA,CAGF,wDACE,YAGE,kBAAA,CAEF,IACE,kBAAA,CAAA","sourcesContent":[".Root {\n  &.is-overlay {\n    position: absolute;\n    top: 0;\n    left: 0;\n    right: 0;\n    bottom: 0;\n    background-color: var(--theme-color-bg-1-transparent);\n    display: flex;\n    justify-content: center;\n    align-items: center;\n  }\n}\n\n.Inner {\n  text-align: center;\n  display: flex;\n\n  &.is-size-small {\n    transform: scale(0.7);\n  }\n}\n\n.FirstDot,\n.SecondDot,\n.ThirdDot {\n  width: 8px;\n  height: 8px;\n  margin: 3px;\n\n  border-radius: 100%;\n  animation: bouncedelay 1.4s infinite var(--easing-base) both;\n\n  &.is-color-light {\n    background-color: var(--theme-color-fg-highlight);\n  }\n\n  &.is-color-dark {\n    background-color: var(--theme-color-bg-1);\n  }\n}\n\n.FirstDot {\n  animation-delay: -0.32s;\n}\n\n.SecondDot {\n  animation-delay: -0.16s;\n}\n\n@keyframes bouncedelay {\n  0%,\n  80%,\n  100% {\n    transform: scale(0);\n  }\n  40% {\n    transform: scale(1);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ActivityIndicator-module__Root--jL2Fv`,
	"is-overlay": `ActivityIndicator-module__is-overlay--sKAmE`,
	"Inner": `ActivityIndicator-module__Inner--r7S6h`,
	"is-size-small": `ActivityIndicator-module__is-size-small--X0qdF`,
	"FirstDot": `ActivityIndicator-module__FirstDot--zITNg`,
	"SecondDot": `ActivityIndicator-module__SecondDot--GtMTf`,
	"ThirdDot": `ActivityIndicator-module__ThirdDot--V4QDy`,
	"bouncedelay": `ActivityIndicator-module__bouncedelay--Ft7_b`,
	"is-color-light": `ActivityIndicator-module__is-color-light--wrVDT`,
	"is-color-dark": `ActivityIndicator-module__is-color-dark--noBtT`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 63544:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80002);
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(underscore__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6203);
/* harmony import */ var _noodl_utils_filesystem__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(38656);
/* harmony import */ var _noodl_utils_filesystem__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_noodl_utils_filesystem__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _shared_view__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(92207);
/* harmony import */ var _shared_view__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_shared_view__WEBPACK_IMPORTED_MODULE_3__);







const ImagePickerTemplate = __webpack_require__(76665);

var FontPicker = function (args) {
  _shared_view__WEBPACK_IMPORTED_MODULE_3___default().call(this);

  this.items = [];
  this.onItemSelected = args.onItemSelected;
};
FontPicker.prototype = Object.create((_shared_view__WEBPACK_IMPORTED_MODULE_3___default().prototype));

FontPicker.prototype.resize = function (layout) {
  this.el.css({
    position: 'absolute',
    left: layout.x + 'px',
    top: layout.y + 'px',
    width: layout.width + 'px',
    height: layout.height + 'px'
  });
};

FontPicker.prototype.addCommonFont = function (name) {
  var el = this.bindView(this.cloneTemplate('item'), { name: name });
  el.css({ fontFamily: name });
  this.items.push({
    el: el,
    name: name,
    fullPath: name,
    folder: 'Common fonts'
  });
};

FontPicker.prototype.renderItems = function (appendTo) {
  var _this = this;

  if (!this.el) return;

  var appendTo = this.$('.fontItems');
  appendTo.html('');

  this.items.sort(function (a, b) {
    if (a.folder === '/' && b.folder !== '/') return -1;
    if (b.folder === '/' && a.folder !== '/') return 1;

    if (a.folder === 'Common fonts' && b.folder !== 'Common fonts') return 1;
    if (b.folder === 'Common fonts' && a.folder !== 'Common fonts') return -1;

    return a.fullPath < b.fullPath ? -1 : 1;
  });

  function append(item) {
    appendTo.append(item.el);
    item.el.on('click', function () {
      _this.itemClicked(item);
    });
  }

  // Render all that match filter
  var folder;
  for (var i in this.items) {
    var item = this.items[i];

    if (item.folder !== folder) {
      folder = item.folder;
      if (folder !== '/') appendTo.append('<div class="content-picker-group-label">' + folder + '</div>');
    }

    if (
      this.pathFilter === undefined ||
      this.pathFilter === '' ||
      item.fullPath.toLowerCase().indexOf(this.pathFilter) !== -1
    ) {
      append(item);
    }
  }
};

FontPicker.prototype.setFilter = function (filter) {
  this.pathFilter = filter.toLowerCase();
  this.renderItems();
};

var fontDataURLCache = {};
FontPicker.prototype.getFontDataURL = function (fileEntry, callback) {
  if (fontDataURLCache[fileEntry.name]) {
    callback(fontDataURLCache[fileEntry.name]);
    return;
  }

  _noodl_utils_filesystem__WEBPACK_IMPORTED_MODULE_2___default().instance.downloadAsDataURI(fileEntry.fullPath, function (content) {
    fontDataURLCache[fileEntry.name] = content;
    callback(content);
  });
};

FontPicker.prototype.render = function () {
  var _this = this;

  const el = this.bindView($(ImagePickerTemplate), this);
  if (this.el) this.el.append(el);
  else this.el = el;

  // Render image objects
  _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance.listFilesInProjectDirectory(
    function (files) {
      underscore__WEBPACK_IMPORTED_MODULE_0___default().each(files, function (fileEntry) {
        var filesLeft = 0;
        filesLeft++;
        function fileCompleted() {
          if (--filesLeft === 0) _this.renderItems();
        }

        _this.getFontDataURL(fileEntry, function (dataURL) {
          if (!dataURL) {
            fileCompleted();
            return;
          }

          var nameWithoutExtension = fileEntry.name.slice(0, -4);
          var pathInProjectFolder = fileEntry.fullPath.substring(
            _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance._retainedProjectDirectory.length + 1
          );
          var nameWithoutExtensionAndSpaces = nameWithoutExtension.replace(/\s/g, '');
          var el = _this.bindView(_this.cloneTemplate('item'), { name: nameWithoutExtension });
          _this.el.append(
            '<style>@font-face {font-family: "' +
              nameWithoutExtensionAndSpaces +
              '"; src: url(' +
              dataURL +
              ');}</style>'
          );
          el.css({ fontFamily: nameWithoutExtensionAndSpaces });

          // Extract folder for image
          var folder = pathInProjectFolder.split('/');
          if (folder.length === 1) folder = '/';
          else folder = folder.splice(0, folder.length - 1).join('/');

          _this.items.push({
            el: el,
            name: fileEntry.name,
            folder: folder,
            fullPath: pathInProjectFolder
          });
          fileCompleted();
        });
      });
    },
    ['otf', 'ttf', 'woff', 'woff2']
  );

  // Common fonts
  this.addCommonFont('Arial');
  this.addCommonFont('Helvetica');
  this.addCommonFont('Times New Roman');
  this.addCommonFont('Arial Black');
  this.addCommonFont('Impact');
  this.addCommonFont('Tahoma');
  this.addCommonFont('Courier New');
  this.addCommonFont('Lucida Console');
  this.renderItems();

  return this.el;
};

FontPicker.prototype.itemClicked = function (scope) {
  this.onItemSelected && this.onItemSelected(scope.fullPath);
};

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (FontPicker);


/***/ }),

/***/ 63618:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
.monaco-editor .zone-widget {
	position: absolute;
	z-index: 10;
}


.monaco-editor .zone-widget .zone-widget-container {
	border-top-style: solid;
	border-bottom-style: solid;
	border-top-width: 0;
	border-bottom-width: 0;
	position: relative;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/zoneWidget/browser/zoneWidget.css"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;CACC,kBAAkB;CAClB,WAAW;AACZ;;;AAGA;CACC,uBAAuB;CACvB,0BAA0B;CAC1B,mBAAmB;CACnB,sBAAsB;CACtB,kBAAkB;AACnB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n.monaco-editor .zone-widget {\n\tposition: absolute;\n\tz-index: 10;\n}\n\n\n.monaco-editor .zone-widget .zone-widget-container {\n\tborder-top-style: solid;\n\tborder-bottom-style: solid;\n\tborder-top-width: 0;\n\tborder-bottom-width: 0;\n\tposition: relative;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 64054:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgTextAlignLeft = function SvgTextAlignLeft(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.13672 6.375C3.13672 5.96079 3.47251 5.625 3.88672 5.625H20.3867C20.8009 5.625 21.1367 5.96079 21.1367 6.375C21.1367 6.78921 20.8009 7.125 20.3867 7.125H3.88672C3.47251 7.125 3.13672 6.78921 3.13672 6.375Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.13672 10.125C3.13672 9.71079 3.47251 9.375 3.88672 9.375H15.8867C16.3009 9.375 16.6367 9.71079 16.6367 10.125C16.6367 10.5392 16.3009 10.875 15.8867 10.875H3.88672C3.47251 10.875 3.13672 10.5392 3.13672 10.125Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.13672 13.875C3.13672 13.4608 3.47251 13.125 3.88672 13.125H20.3867C20.8009 13.125 21.1367 13.4608 21.1367 13.875C21.1367 14.2892 20.8009 14.625 20.3867 14.625H3.88672C3.47251 14.625 3.13672 14.2892 3.13672 13.875Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.13672 17.625C3.13672 17.2108 3.47251 16.875 3.88672 16.875H15.8867C16.3009 16.875 16.6367 17.2108 16.6367 17.625C16.6367 18.0392 16.3009 18.375 15.8867 18.375H3.88672C3.47251 18.375 3.13672 18.0392 3.13672 17.625Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgTextAlignLeft);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "5ba2f1b3a0be330d07611f401d6db5f4.svg");

/***/ }),

/***/ 64389:
/***/ ((module) => {

"use strict";
module.exports = require("react-hot-toast");

/***/ }),

/***/ 64486:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgWarningCircle = function SvgWarningCircle(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.1366 3.76872C7.59056 3.76872 3.90529 7.45399 3.90529 12C3.90529 16.546 7.59056 20.2313 12.1366 20.2313C16.6826 20.2313 20.3679 16.546 20.3679 12C20.3679 7.45399 16.6826 3.76872 12.1366 3.76872ZM2.40869 12C2.40869 6.62744 6.76401 2.27212 12.1366 2.27212C17.5091 2.27212 21.8645 6.62744 21.8645 12C21.8645 17.3726 17.5091 21.7279 12.1366 21.7279C6.76401 21.7279 2.40869 17.3726 2.40869 12Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.1992 6.75C12.6134 6.75 12.9492 7.08579 12.9492 7.5V12.75C12.9492 13.1642 12.6134 13.5 12.1992 13.5C11.785 13.5 11.4492 13.1642 11.4492 12.75V7.5C11.4492 7.08579 11.785 6.75 12.1992 6.75Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.1992 17.0625C12.717 17.0625 13.1367 16.6428 13.1367 16.125C13.1367 15.6072 12.717 15.1875 12.1992 15.1875C11.6815 15.1875 11.2617 15.6072 11.2617 16.125C11.2617 16.6428 11.6815 17.0625 12.1992 17.0625Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgWarningCircle);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "8c2bb2871a98445fbdbf40d601d19a35.svg");

/***/ }),

/***/ 64808:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ExternalLink-module__Root--rLN2l{color:var(--theme-color-fg-highlight);font-size:14px;display:flex;align-items:top;cursor:pointer;font-family:var(--font-family)}.ExternalLink-module__Root--rLN2l:hover{opacity:1;color:var(--theme-color-fg-highlight)}.ExternalLink-module__Icon--npRRf{margin-left:6px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/ExternalLink/ExternalLink.module.scss"],"names":[],"mappings":"AAAA,kCACE,qCAAA,CACA,cAAA,CACA,YAAA,CACA,eAAA,CACA,cAAA,CACA,8BAAA,CAEA,wCACE,SAAA,CACA,qCAAA,CAIJ,kCACE,eAAA","sourcesContent":[".Root {\r\n  color: var(--theme-color-fg-highlight);\r\n  font-size: 14px;\r\n  display: flex;\r\n  align-items: top;\r\n  cursor: pointer;\r\n  font-family: var(--font-family);\r\n\r\n  &:hover {\r\n    opacity: 1;\r\n    color: var(--theme-color-fg-highlight);\r\n  }\r\n}\r\n\r\n.Icon {\r\n  margin-left: 6px;\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ExternalLink-module__Root--rLN2l`,
	"Icon": `ExternalLink-module__Icon--npRRf`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 65079:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ID: () => (/* binding */ getAheadBehind),
/* harmony export */   QU: () => (/* binding */ revSymmetricDifference),
/* harmony export */   zg: () => (/* binding */ revRange)
/* harmony export */ });
/* unused harmony exports revRangeInclusive, getBranchAheadBehind, getCommitsBetweenCommits, getCommitsInRange */
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81882);
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(dugite__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(85869);
/* harmony import */ var _models_branch__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(16279);



/**
 * Convert two refs into the Git range syntax representing the set of commits
 * that are reachable from `to` but excluding those that are reachable from
 * `from`. This will not be inclusive to the `from` ref, see
 * `revRangeInclusive`.
 *
 * Each parameter can be the commit SHA or a ref name, or specify an empty
 * string to represent HEAD.
 *
 * @param from The start of the range
 * @param to The end of the range
 */
function revRange(from, to) {
    return `${from}..${to}`;
}
/**
 * Convert two refs into the Git range syntax representing the set of commits
 * that are reachable from `to` but excluding those that are reachable from
 * `from`. However as opposed to `revRange`, this will also include `from` ref.
 *
 * Each parameter can be the commit SHA or a ref name, or specify an empty
 * string to represent HEAD.
 *
 * @param from The start of the range
 * @param to The end of the range
 */
function revRangeInclusive(from, to) {
    return `${from}^..${to}`;
}
/**
 * Convert two refs into the Git symmetric difference syntax, which represents
 * the set of commits that are reachable from either `from` or `to` but not
 * from both.
 *
 * Each parameter can be the commit SHA or a ref name, or you can use an empty
 * string to represent HEAD.
 *
 * @param from The start of the range
 * @param to The end of the range
 */
function revSymmetricDifference(from, to) {
    return `${from}...${to}`;
}
/** Calculate the number of commits the range is ahead and behind. */
async function getAheadBehind(repositoryDir, range) {
    // `--left-right` annotates the list of commits in the range with which side
    // they're coming from. When used with `--count`, it tells us how many
    // commits we have from the two different sides of the range.
    const args = ["rev-list", "--left-right", "--count", range, "--"];
    const result = await (0,_client__WEBPACK_IMPORTED_MODULE_1__/* .git */ .$)(args, repositoryDir, "getAheadBehind", {
        expectedErrors: new Set([dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.BadRevision]),
    });
    // This means one of the refs (most likely the upstream branch) no longer
    // exists. In that case we can't be ahead/behind at all.
    if (result.gitError === dugite__WEBPACK_IMPORTED_MODULE_0__.GitError.BadRevision) {
        return null;
    }
    const stdout = result.output.toString();
    const pieces = stdout.split("\t");
    if (pieces.length !== 2) {
        return null;
    }
    const ahead = parseInt(pieces[0], 10);
    if (isNaN(ahead)) {
        return null;
    }
    const behind = parseInt(pieces[1], 10);
    if (isNaN(behind)) {
        return null;
    }
    return { ahead, behind };
}
/** Calculate the number of commits `branch` is ahead/behind its upstream. */
async function getBranchAheadBehind(repositoryDir, branch) {
    if (branch.type === BranchType.Remote) {
        return null;
    }
    const upstream = branch.upstream;
    if (!upstream) {
        return null;
    }
    // NB: The three dot form means we'll go all the way back to the merge base
    // of the branch and its upstream. Practically this is important for seeing
    // "through" merges.
    const range = revSymmetricDifference(branch.name, upstream);
    return getAheadBehind(repositoryDir, range);
}
/**
 * Get a list of commits from the target branch that do not exist on the base
 * branch, ordered how they will be applied to the base branch.
 * Therefore, this will not include the baseBranchSha commit.
 *
 * This emulates how `git rebase` initially determines what will be applied to
 * the repository.
 *
 * Returns `null` when the rebase is not possible to perform, because of a
 * missing commit ID
 */
async function getCommitsBetweenCommits(repositoryDir, baseBranchSha, targetBranchSha) {
    const range = revRange(baseBranchSha, targetBranchSha);
    return getCommitsInRange(repositoryDir, range);
}
/**
 * Get a list of commits inside the provided range.
 *
 * Returns `null` when it is not possible to perform because of a bad range.
 */
async function getCommitsInRange(repositoryDir, range) {
    const args = [
        "rev-list",
        range,
        "--reverse",
        // the combination of these two arguments means each line of the stdout
        // will contain the full commit sha and a commit summary
        `--oneline`,
        `--no-abbrev-commit`,
        "--",
    ];
    const options = {
        expectedErrors: new Set([GitError.BadRevision]),
    };
    const result = await git(args, repositoryDir, "getCommitsInRange", options);
    if (result.gitError === GitError.BadRevision) {
        return null;
    }
    const lines = result.output.toString().split("\n");
    const commits = new Array();
    const commitSummaryRe = /^([a-z0-9]{40}) (.*)$/;
    for (const line of lines) {
        const match = commitSummaryRe.exec(line);
        if (match !== null && match.length === 3) {
            const sha = match[1];
            const summary = match[2];
            commits.push({
                sha,
                summary,
            });
        }
    }
    return commits;
}


/***/ }),

/***/ 65601:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Launcher-module__Root--ylY83{display:flex;flex-direction:column;height:100vh;width:100vw;background:var(--theme-color-bg-1);color:var(--theme-color-fg-default);overflow:hidden}.Launcher-module__ContentArea--pLXXz{flex:1;overflow-y:auto;overflow-x:hidden;background:var(--theme-color-bg-2);scroll-behavior:smooth}.Launcher-module__ContentArea--pLXXz::-webkit-scrollbar{width:8px}.Launcher-module__ContentArea--pLXXz::-webkit-scrollbar-track{background:var(--theme-color-bg-1)}.Launcher-module__ContentArea--pLXXz::-webkit-scrollbar-thumb{background:var(--theme-color-border-default);border-radius:4px}.Launcher-module__ContentArea--pLXXz::-webkit-scrollbar-thumb:hover{background:var(--theme-color-fg-default-shy)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/preview/launcher/Launcher/Launcher.module.scss"],"names":[],"mappings":"AAIA,8BACE,YAAA,CACA,qBAAA,CACA,YAAA,CACA,WAAA,CACA,kCAAA,CACA,mCAAA,CACA,eAAA,CAGF,qCACE,MAAA,CACA,eAAA,CACA,iBAAA,CACA,kCAAA,CAGA,sBAAA,CAGA,wDACE,SAAA,CAGF,8DACE,kCAAA,CAGF,8DACE,4CAAA,CACA,iBAAA,CAEA,oEACE,4CAAA","sourcesContent":["/**\n * Launcher - Main layout styling\n */\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  height: 100vh;\n  width: 100vw;\n  background: var(--theme-color-bg-1);\n  color: var(--theme-color-fg-default);\n  overflow: hidden;\n}\n\n.ContentArea {\n  flex: 1;\n  overflow-y: auto;\n  overflow-x: hidden;\n  background: var(--theme-color-bg-2);\n\n  /* Smooth scrolling */\n  scroll-behavior: smooth;\n\n  /* Custom scrollbar styling */\n  &::-webkit-scrollbar {\n    width: 8px;\n  }\n\n  &::-webkit-scrollbar-track {\n    background: var(--theme-color-bg-1);\n  }\n\n  &::-webkit-scrollbar-thumb {\n    background: var(--theme-color-border-default);\n    border-radius: 4px;\n\n    &:hover {\n      background: var(--theme-color-fg-default-shy);\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Launcher-module__Root--ylY83`,
	"ContentArea": `Launcher-module__ContentArea--pLXXz`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 65621:
/***/ ((module) => {

"use strict";
module.exports = require("otpauth");

/***/ }),

/***/ 65762:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  mY: () => (/* reexport */ BaseDialog),
  TT: () => (/* reexport */ BaseDialogVariant),
  V9: () => (/* reexport */ CoreBaseDialog),
  $j: () => (/* reexport */ DialogBackground),
  K1: () => (/* reexport */ DialogRenderDirection)
});

// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
;// ./src/editor/src/hooks/useDocumentScrollTimestamp.ts

function useDocumentScrollTimestamp(isEnabled = true, debounceMs = 0) {
    const [timestamp, setTimestamp] = (0,external_react_.useState)(Date.now());
    (0,external_react_.useEffect)(() => {
        let debounceTimeoutId;
        function onResize() {
            clearTimeout(debounceTimeoutId);
            debounceTimeoutId = setTimeout(() => setTimestamp(Date.now()), debounceMs);
        }
        function cleanup() {
            document.removeEventListener('scroll', onResize, true);
            clearTimeout(debounceTimeoutId);
        }
        if (isEnabled) {
            document.addEventListener('scroll', onResize, true);
        }
        else {
            cleanup();
        }
        return () => {
            cleanup();
        };
    }, [isEnabled, debounceMs]);
    return timestamp;
}

// EXTERNAL MODULE: ./src/editor/src/hooks/useWindowSize.ts
var useWindowSize = __webpack_require__(58541);
// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Collapsible/index.ts + 2 modules
var Collapsible = __webpack_require__(20014);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Portal/index.ts + 1 modules
var Portal = __webpack_require__(31302);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Label/index.ts + 2 modules
var Label = __webpack_require__(91629);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/BaseDialog/BaseDialog.module.scss
var BaseDialog_module = __webpack_require__(31617);
;// ../noodl-core-ui/src/components/layout/BaseDialog/BaseDialog.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(BaseDialog_module/* default */.A, options);




       /* harmony default export */ const BaseDialog_BaseDialog_module = (BaseDialog_module/* default */.A && BaseDialog_module/* default */.A.locals ? BaseDialog_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/BaseDialog/BaseDialog.tsx








var DialogRenderDirection;
(function (DialogRenderDirection) {
    DialogRenderDirection[DialogRenderDirection["Vertical"] = 0] = "Vertical";
    DialogRenderDirection[DialogRenderDirection["Horizontal"] = 1] = "Horizontal";
    DialogRenderDirection[DialogRenderDirection["Above"] = 2] = "Above";
    DialogRenderDirection[DialogRenderDirection["Below"] = 3] = "Below";
})(DialogRenderDirection || (DialogRenderDirection = {}));
var BaseDialogVariant;
(function (BaseDialogVariant) {
    BaseDialogVariant["Default"] = "is-variant-default";
    BaseDialogVariant["Select"] = "is-variant-select";
})(BaseDialogVariant || (BaseDialogVariant = {}));
var DialogBackground;
(function (DialogBackground) {
    DialogBackground["Default"] = "is-background-default";
    DialogBackground["Bg1"] = "is-background-bg-1";
    DialogBackground["Bg2"] = "is-background-bg-2";
    DialogBackground["Bg3"] = "is-background-bg-3";
    DialogBackground["Secondary"] = "is-background-secondary";
    DialogBackground["Transparent"] = "is-background-transparent";
})(DialogBackground || (DialogBackground = {}));
function BaseDialog(props) {
    const [portalRoot] = (0,external_react_.useState)(document.querySelector('.dialog-layer-portal-target'));
    return (external_react_default().createElement(Portal/* Portal */.Z, { portalRoot: portalRoot },
        external_react_default().createElement(CoreBaseDialog, { ...props })));
}
function CoreBaseDialog({ triggerRef, renderDirection = DialogRenderDirection.Vertical, background = DialogBackground.Default, variant = BaseDialogVariant.Default, title, isLockingScroll, isVisible, hasBackdrop, hasArrow, children, onClose, UNSAFE_className, UNSAFE_style }) {
    const [isSelectOpen, setIsSelectOpen] = (0,external_react_.useState)(false);
    (0,external_react_.useEffect)(() => {
        if (!BaseDialogVariant.Select)
            return;
        // quick n dirty solution to make sure the
        // select doesnt render in an open state
        // without showing the animation
        setTimeout(() => {
            setIsSelectOpen(isVisible);
        }, 50);
    }, [isVisible]);
    const dialogRef = (0,external_react_.useRef)(null);
    const [dialogPosition, setDialogPosition] = (0,external_react_.useState)({
        x: 0,
        y: 0,
        arrowX: 0,
        arrowY: 0,
        animationStartOffsetX: 0,
        animationStartOffsetY: 0,
        width: 'auto',
        speed: 250
    });
    const windowSize = (0,useWindowSize/* default */.A)();
    const lastScroll = useDocumentScrollTimestamp(isVisible);
    const arrowCompensationOffset = variant === BaseDialogVariant.Select ? 0 : 12;
    const edgeOffset = 10;
    // calculate where to render the dialog
    (0,external_react_.useLayoutEffect)(() => {
        if (!(triggerRef === null || triggerRef === void 0 ? void 0 : triggerRef.current) || !(dialogRef === null || dialogRef === void 0 ? void 0 : dialogRef.current))
            return;
        const triggerRect = triggerRef.current.getBoundingClientRect();
        const dialogRect = dialogRef.current.getBoundingClientRect();
        let dialogX;
        let dialogY;
        let arrowX;
        let arrowY;
        let animationStartOffsetX = 0;
        let animationStartOffsetY = 0;
        let width = 'auto';
        let speed = Math.max(150, dialogRect.height);
        if (variant === BaseDialogVariant.Select)
            width = triggerRect.width + 'px';
        function checkAboveFirst() {
            // default position to trigger is x:centered y:above
            dialogX = triggerRect.left + triggerRect.width / 2 - dialogRect.width / 2;
            dialogY = triggerRect.top - (dialogRect.height + arrowCompensationOffset);
            arrowY = dialogRect.height;
            arrowX = dialogRect.width / 2;
            animationStartOffsetY = -10;
            // if x:centered renders the dialog outside of viewport
            // we tack it to the side of the viewport it clips
            if (dialogX < 0) {
                dialogX = edgeOffset;
                arrowX = triggerRect.width / 2 + triggerRect.left - edgeOffset;
            }
            else if (dialogX + dialogRect.width > windowSize.width) {
                dialogX = windowSize.width - dialogRect.width - edgeOffset;
                arrowX = dialogRect.width - (windowSize.width - triggerRect.right) - triggerRect.width / 2 + edgeOffset;
            }
            // if y:above is outside the viewport we do y:below
            if (dialogY - dialogRect.height - arrowCompensationOffset < 0) {
                dialogY = triggerRect.bottom + arrowCompensationOffset;
                arrowY = 0;
                animationStartOffsetY = 10;
            }
        }
        function checkBelowFirst() {
            // default position to trigger is x:centered y:below
            dialogX = triggerRect.left + triggerRect.width / 2 - dialogRect.width / 2;
            dialogY = triggerRect.bottom + arrowCompensationOffset;
            arrowY = 0;
            arrowX = dialogRect.width / 2;
            animationStartOffsetY = 10;
            // if x:centered renders the dialog outside of viewport
            // we tack it to the side of the viewport it clips
            if (dialogX < 0) {
                dialogX = edgeOffset;
                arrowX = triggerRect.width / 2 + triggerRect.left - edgeOffset;
            }
            else if (dialogX + dialogRect.width > windowSize.width) {
                dialogX = windowSize.width - dialogRect.width - edgeOffset;
                arrowX = dialogRect.width - (windowSize.width - triggerRect.right) - triggerRect.width / 2 + edgeOffset;
            }
            // if y:below is outside the viewport we do y:above
            if (dialogY + dialogRect.height > windowSize.height) {
                dialogY = triggerRect.top - dialogRect.height - arrowCompensationOffset;
                arrowY = dialogRect.height;
                animationStartOffsetY = -10;
            }
        }
        function checkRightFirst() {
            // default position to trigger is y:centered x:right
            dialogX = triggerRect.right + arrowCompensationOffset;
            dialogY = triggerRect.top + triggerRect.height / 2 - dialogRect.height / 2;
            arrowX = 0;
            arrowY = dialogRect.height / 2;
            animationStartOffsetX = 10;
            // if x:right is clipping outside viewport, render as x:left
            if (dialogX + dialogRect.width > windowSize.width) {
                dialogX = triggerRect.left - dialogRect.width - arrowCompensationOffset;
                arrowX = dialogRect.width;
                animationStartOffsetX = -10;
            }
            // if y:center clips outside viewport tack it to bottom or top
            if (dialogY + dialogRect.height > windowSize.height) {
                dialogY = windowSize.height - dialogRect.height;
                arrowY = dialogRect.height - (windowSize.height - triggerRect.top) + triggerRect.height / 2;
            }
            else if (dialogY < 0) {
                dialogY = 10;
                arrowY = triggerRect.top + triggerRect.height / 2;
            }
        }
        switch (renderDirection) {
            case DialogRenderDirection.Vertical:
            case DialogRenderDirection.Above:
                checkAboveFirst();
                break;
            case DialogRenderDirection.Below:
                checkBelowFirst();
                break;
            case DialogRenderDirection.Horizontal:
                checkRightFirst();
                break;
        }
        setDialogPosition({
            x: dialogX,
            y: dialogY,
            arrowX,
            arrowY,
            animationStartOffsetX,
            animationStartOffsetY,
            width,
            speed
        });
    }, [isVisible, windowSize, lastScroll, triggerRef === null || triggerRef === void 0 ? void 0 : triggerRef.current, dialogRef === null || dialogRef === void 0 ? void 0 : dialogRef.current]);
    const backgroundColor = (0,external_react_.useMemo)(() => {
        switch (background) {
            case DialogBackground.Bg1:
                return 'var(--theme-color-bg-1)';
            case DialogBackground.Bg2:
                return 'var(--theme-color-bg-2)';
            case DialogBackground.Bg3:
                return 'var(--theme-color-bg-3)';
            case DialogBackground.Transparent:
                return 'transparent';
            case DialogBackground.Secondary:
                return 'var(--theme-color-secondary)';
            default:
                return 'var(--theme-color-bg-4)';
        }
    }, [background]);
    const backgroundContrastColor = (0,external_react_.useMemo)(() => {
        switch (background) {
            case DialogBackground.Bg1:
                return 'var(--theme-color-bg-0)';
            case DialogBackground.Bg2:
                return 'var(--theme-color-bg-1)';
            case DialogBackground.Bg3:
                return 'var(--theme-color-bg-2)';
            case DialogBackground.Transparent:
                return 'transparent';
            case DialogBackground.Secondary:
                return 'var(--theme-color-secondary)';
            default:
                return 'var(--theme-color-bg-2)';
        }
    }, [background]);
    if (!isVisible)
        return null;
    return (external_react_default().createElement("div", { className: external_classnames_default()(BaseDialog_BaseDialog_module['Root'], hasBackdrop && BaseDialog_BaseDialog_module['has-backdrop'], isLockingScroll && BaseDialog_BaseDialog_module['is-locking-scroll'], typeof triggerRef === 'undefined' && BaseDialog_BaseDialog_module['is-centered'], BaseDialog_BaseDialog_module[variant]), onClick: onClose, style: {
            '--offsetY': `${Math.floor(dialogPosition.y)}px`,
            '--offsetX': `${Math.floor(dialogPosition.x)}px`,
            '--animationStartOffsetX': `${dialogPosition.animationStartOffsetX}px`,
            '--animationStartOffsetY': `${dialogPosition.animationStartOffsetY}px`,
            '--background': backgroundColor,
            '--backgroundContrast': backgroundContrastColor,
            '--width': dialogPosition.width
        } },
        external_react_default().createElement("div", { className: external_classnames_default()(BaseDialog_BaseDialog_module['VisibleDialog'], UNSAFE_className, isVisible && BaseDialog_BaseDialog_module['is-visible'], BaseDialog_BaseDialog_module[variant]), style: UNSAFE_style, onClick: (e) => e.stopPropagation() },
            external_react_default().createElement("div", { className: BaseDialog_BaseDialog_module['MeasuringContainer'] },
                external_react_default().createElement("div", { ref: dialogRef, style: {}, className: BaseDialog_BaseDialog_module['ChildContainer'] }, children)),
            hasArrow && (external_react_default().createElement("div", { className: external_classnames_default()(BaseDialog_BaseDialog_module['Arrow'], title && dialogPosition.arrowY === 0 && BaseDialog_BaseDialog_module['is-contrast']), style: {
                    '--arrow-top': `${dialogPosition.arrowY}px`,
                    '--arrow-left': `${dialogPosition.arrowX}px`
                } })),
            variant === BaseDialogVariant.Select ? (external_react_default().createElement(Collapsible/* Collapsible */.N, { isCollapsed: !isSelectOpen, transitionMs: dialogPosition.speed },
                external_react_default().createElement("div", { className: BaseDialog_BaseDialog_module['ChildContainer'] },
                    title && (external_react_default().createElement("div", { className: BaseDialog_BaseDialog_module['Title'] },
                        external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Medium }, title))),
                    children))) : (external_react_default().createElement("div", { className: BaseDialog_BaseDialog_module['ChildContainer'] },
                title && (external_react_default().createElement("div", { className: BaseDialog_BaseDialog_module['Title'] },
                    external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Medium }, title))),
                children)))));
}

;// ../noodl-core-ui/src/components/layout/BaseDialog/index.ts



/***/ }),

/***/ 65949:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PRItem-module__PRItem--rr_G6{background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:4px;padding:12px;margin-bottom:8px;cursor:pointer;transition:all .15s ease}.PRItem-module__PRItem--rr_G6:hover{background-color:var(--theme-color-bg-4);border-color:var(--theme-color-border-hover)}.PRItem-module__PRItem--rr_G6:active{transform:scale(0.99)}.PRItem-module__Header--jqPUy{display:flex;justify-content:space-between;align-items:flex-start;gap:8px;margin-bottom:8px}.PRItem-module__TitleRow--H2Hbw{flex:1;display:flex;align-items:flex-start;gap:8px;min-width:0}.PRItem-module__Number--uNqud{color:var(--theme-color-fg-default-shy);font-size:12px;font-weight:600;flex-shrink:0}.PRItem-module__Title--LWt4f{color:var(--theme-color-fg-default);font-size:13px;font-weight:500;flex:1;word-break:break-word}.PRItem-module__StatusBadge--paNEc{flex-shrink:0;padding:2px 8px;border-radius:12px;font-size:11px;font-weight:600;text-transform:capitalize}.PRItem-module__StatusBadge--paNEc[data-status=open]{background-color:rgba(46,160,67,.15);color:#2ea043}.PRItem-module__StatusBadge--paNEc[data-status=draft]{background-color:rgba(110,118,129,.15);color:#6e7681}.PRItem-module__StatusBadge--paNEc[data-status=merged]{background-color:rgba(137,87,229,.15);color:#8957e5}.PRItem-module__StatusBadge--paNEc[data-status=closed]{background-color:rgba(177,24,24,.15);color:#da3633}.PRItem-module__Meta--fR0qa{display:flex;flex-direction:column;gap:4px;margin-bottom:8px}.PRItem-module__Author--ujyoS{color:var(--theme-color-fg-default-shy);font-size:12px}.PRItem-module__Time--rGvwJ{color:var(--theme-color-fg-default-shy);font-size:11px}.PRItem-module__Stats--tNKwf{display:flex;align-items:center;gap:12px;margin-bottom:8px}.PRItem-module__Stat--yPbQO{color:var(--theme-color-fg-default-shy);font-size:12px;display:flex;align-items:center;gap:4px}.PRItem-module__Labels--kNHZt{display:flex;flex-wrap:wrap;gap:6px;align-items:center}.PRItem-module__Label--aAOIq{padding:2px 8px;border-radius:12px;font-size:11px;font-weight:600;display:inline-block}.PRItem-module__MoreLabels--yttIB{color:var(--theme-color-fg-default-shy);font-size:11px;font-weight:600}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRItem.module.scss"],"names":[],"mappings":"AAIA,8BACE,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,YAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CAEA,oCACE,wCAAA,CACA,4CAAA,CAGF,qCACE,qBAAA,CAIJ,8BACE,YAAA,CACA,6BAAA,CACA,sBAAA,CACA,OAAA,CACA,iBAAA,CAGF,gCACE,MAAA,CACA,YAAA,CACA,sBAAA,CACA,OAAA,CACA,WAAA,CAGF,8BACE,uCAAA,CACA,cAAA,CACA,eAAA,CACA,aAAA,CAGF,6BACE,mCAAA,CACA,cAAA,CACA,eAAA,CACA,MAAA,CACA,qBAAA,CAGF,mCACE,aAAA,CACA,eAAA,CACA,kBAAA,CACA,cAAA,CACA,eAAA,CACA,yBAAA,CAEA,qDACE,oCAAA,CACA,aAAA,CAGF,sDACE,sCAAA,CACA,aAAA,CAGF,uDACE,qCAAA,CACA,aAAA,CAGF,uDACE,oCAAA,CACA,aAAA,CAIJ,4BACE,YAAA,CACA,qBAAA,CACA,OAAA,CACA,iBAAA,CAGF,8BACE,uCAAA,CACA,cAAA,CAGF,4BACE,uCAAA,CACA,cAAA,CAGF,6BACE,YAAA,CACA,kBAAA,CACA,QAAA,CACA,iBAAA,CAGF,4BACE,uCAAA,CACA,cAAA,CACA,YAAA,CACA,kBAAA,CACA,OAAA,CAGF,8BACE,YAAA,CACA,cAAA,CACA,OAAA,CACA,kBAAA,CAGF,6BACE,eAAA,CACA,kBAAA,CACA,cAAA,CACA,eAAA,CACA,oBAAA,CAGF,kCACE,uCAAA,CACA,cAAA,CACA,eAAA","sourcesContent":["/**\n * PRItem Styles\n */\n\n.PRItem {\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  padding: 12px;\n  margin-bottom: 8px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    border-color: var(--theme-color-border-hover);\n  }\n\n  &:active {\n    transform: scale(0.99);\n  }\n}\n\n.Header {\n  display: flex;\n  justify-content: space-between;\n  align-items: flex-start;\n  gap: 8px;\n  margin-bottom: 8px;\n}\n\n.TitleRow {\n  flex: 1;\n  display: flex;\n  align-items: flex-start;\n  gap: 8px;\n  min-width: 0;\n}\n\n.Number {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 12px;\n  font-weight: 600;\n  flex-shrink: 0;\n}\n\n.Title {\n  color: var(--theme-color-fg-default);\n  font-size: 13px;\n  font-weight: 500;\n  flex: 1;\n  word-break: break-word;\n}\n\n.StatusBadge {\n  flex-shrink: 0;\n  padding: 2px 8px;\n  border-radius: 12px;\n  font-size: 11px;\n  font-weight: 600;\n  text-transform: capitalize;\n\n  &[data-status='open'] {\n    background-color: rgba(46, 160, 67, 0.15);\n    color: #2ea043;\n  }\n\n  &[data-status='draft'] {\n    background-color: rgba(110, 118, 129, 0.15);\n    color: #6e7681;\n  }\n\n  &[data-status='merged'] {\n    background-color: rgba(137, 87, 229, 0.15);\n    color: #8957e5;\n  }\n\n  &[data-status='closed'] {\n    background-color: rgba(177, 24, 24, 0.15);\n    color: #da3633;\n  }\n}\n\n.Meta {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n  margin-bottom: 8px;\n}\n\n.Author {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 12px;\n}\n\n.Time {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 11px;\n}\n\n.Stats {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  margin-bottom: 8px;\n}\n\n.Stat {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 12px;\n  display: flex;\n  align-items: center;\n  gap: 4px;\n}\n\n.Labels {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 6px;\n  align-items: center;\n}\n\n.Label {\n  padding: 2px 8px;\n  border-radius: 12px;\n  font-size: 11px;\n  font-weight: 600;\n  display: inline-block;\n}\n\n.MoreLabels {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 11px;\n  font-weight: 600;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"PRItem": `PRItem-module__PRItem--rr_G6`,
	"Header": `PRItem-module__Header--jqPUy`,
	"TitleRow": `PRItem-module__TitleRow--H2Hbw`,
	"Number": `PRItem-module__Number--uNqud`,
	"Title": `PRItem-module__Title--LWt4f`,
	"StatusBadge": `PRItem-module__StatusBadge--paNEc`,
	"Meta": `PRItem-module__Meta--fR0qa`,
	"Author": `PRItem-module__Author--ujyoS`,
	"Time": `PRItem-module__Time--rGvwJ`,
	"Stats": `PRItem-module__Stats--tNKwf`,
	"Stat": `PRItem-module__Stat--yPbQO`,
	"Labels": `PRItem-module__Labels--kNHZt`,
	"Label": `PRItem-module__Label--aAOIq`,
	"MoreLabels": `PRItem-module__MoreLabels--yttIB`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 66095:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  S: () => (/* reexport */ PropertyPanelSelectInput)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/BaseDialog/index.ts + 3 modules
var BaseDialog = __webpack_require__(65762);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelBaseInput/index.ts + 2 modules
var PropertyPanelBaseInput = __webpack_require__(98690);
;// ../noodl-core-ui/src/assets/icons/caret-down.svg
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCaretDown = function SvgCaretDown(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/external_react_.createElement("svg", _extends({
    width: 16,
    height: 16,
    viewBox: "0 0 16 16",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/external_react_.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/external_react_.createElement("path", {
    d: "M11.06 5.72656L8 8.77986L4.94 5.72656L4 6.66656L8 10.6666L12 6.66656L11.06 5.72656Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,external_react_.forwardRef)(SvgCaretDown);

/* harmony default export */ const caret_down = (__webpack_require__.p + "ce5f09b6b4a4c89c00ab3b65d5b9f9bd.svg");
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/property-panel/PropertyPanelSelectInput/PropertyPanelSelectInput.module.scss
var PropertyPanelSelectInput_module = __webpack_require__(16885);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelSelectInput/PropertyPanelSelectInput.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(PropertyPanelSelectInput_module/* default */.A, options);




       /* harmony default export */ const PropertyPanelSelectInput_PropertyPanelSelectInput_module = (PropertyPanelSelectInput_module/* default */.A && PropertyPanelSelectInput_module/* default */.A.locals ? PropertyPanelSelectInput_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelSelectInput/PropertyPanelSelectInput.tsx






function PropertyPanelSelectInput({ value, properties, isFauxFocused, onChange, onFocus, onBlur, hasHiddenCaret, hasSmallText }) {
    var _a, _b;
    const [isSelectCollapsed, setIsSelectCollapsed] = (0,external_react_.useState)(true);
    const rootRef = (0,external_react_.useRef)(null);
    const displayValue = (_a = properties === null || properties === void 0 ? void 0 : properties.options.find((option) => option.value === value)) === null || _a === void 0 ? void 0 : _a.label;
    return (external_react_default().createElement("div", { className: external_classnames_default()(PropertyPanelSelectInput_PropertyPanelSelectInput_module['Root'], !hasHiddenCaret && PropertyPanelSelectInput_PropertyPanelSelectInput_module['has-caret']), ref: rootRef },
        external_react_default().createElement(PropertyPanelBaseInput/* PropertyPanelBaseInput */.Z, { type: "text", value: displayValue, hasHiddenCaret: true, onClick: () => {
                setIsSelectCollapsed((prev) => !prev);
            }, onBlur: (e) => {
                setTimeout(() => {
                    setIsSelectCollapsed(true);
                }, 250);
                if (onBlur)
                    onBlur(e);
            }, onFocus: onFocus, isFauxFocused: isFauxFocused, hasSmallText: hasSmallText }),
        !hasHiddenCaret && (external_react_default().createElement("div", { className: external_classnames_default()(PropertyPanelSelectInput_PropertyPanelSelectInput_module['Caret'], !isSelectCollapsed && PropertyPanelSelectInput_PropertyPanelSelectInput_module['is-indicating-close']), onClick: () => {
                setIsSelectCollapsed((prev) => !prev);
            } },
            external_react_default().createElement(ForwardRef, null))),
        external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { isVisible: !isSelectCollapsed, triggerRef: rootRef, background: BaseDialog/* DialogBackground */.$j.Transparent, variant: BaseDialog/* BaseDialogVariant */.TT.Select },
            external_react_default().createElement("ul", { className: PropertyPanelSelectInput_PropertyPanelSelectInput_module['Options'] }, (_b = properties === null || properties === void 0 ? void 0 : properties.options) === null || _b === void 0 ? void 0 : _b.map((option) => {
                if (option.value === value)
                    return null;
                return (external_react_default().createElement("li", { key: option.value, className: external_classnames_default()(PropertyPanelSelectInput_PropertyPanelSelectInput_module['Option'], option.isDisabled && PropertyPanelSelectInput_PropertyPanelSelectInput_module['is-disabled'], hasSmallText && PropertyPanelSelectInput_PropertyPanelSelectInput_module['has-small-text']), onClick: () => {
                        setIsSelectCollapsed(true);
                        if (option.isDisabled)
                            return null;
                        onChange && onChange(option.value);
                    } }, option.label));
            })))));
}

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelSelectInput/index.ts



/***/ }),

/***/ 66131:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDimension = function SvgDimension(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 30,
    viewBox: "0 0 31 30",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M23.9805 3.94501H6.29254C5.07144 3.94501 4.08154 4.93491 4.08154 6.15601V23.844C4.08154 25.0651 5.07144 26.055 6.29254 26.055H23.9805C25.2016 26.055 26.1915 25.0651 26.1915 23.844V6.15601C26.1915 4.93491 25.2016 3.94501 23.9805 3.94501Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDimension);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "cdf30ca1306d2163468470f737ca6964.svg");

/***/ }),

/***/ 66262:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// File containing shared constants
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MODEL_NONSTREAMING_TOKENS = void 0;
/**
 * Model-specific timeout constraints for non-streaming requests
 */
exports.MODEL_NONSTREAMING_TOKENS = {
    'claude-opus-4-20250514': 8192,
    'claude-opus-4-0': 8192,
    'claude-4-opus-20250514': 8192,
    'anthropic.claude-opus-4-20250514-v1:0': 8192,
    'claude-opus-4@20250514': 8192,
    'claude-opus-4-1-20250805': 8192,
    'anthropic.claude-opus-4-1-20250805-v1:0': 8192,
    'claude-opus-4-1@20250805': 8192,
};
//# sourceMappingURL=constants.js.map

/***/ }),

/***/ 66321:
/***/ ((module) => {

"use strict";
module.exports = require("mkdirp-sync");

/***/ }),

/***/ 66432:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSlidersHorizontal = function SvgSlidersHorizontal(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M13.1199 16.9116C13.1199 15.8071 14.0154 14.9116 15.1199 14.9116C16.2245 14.9116 17.1199 15.8071 17.1199 16.9116C17.1199 18.0162 16.2245 18.9116 15.1199 18.9116C14.0154 18.9116 13.1199 18.0162 13.1199 16.9116ZM11.6993 16.167C12.0406 14.5917 13.4425 13.4116 15.1199 13.4116C16.7974 13.4116 18.1992 14.5917 18.5406 16.167L20.25 16.167C20.6642 16.167 21 16.5028 21 16.917C21 17.3312 20.6642 17.667 20.25 17.667L18.5382 17.667C18.1929 19.2369 16.7936 20.4116 15.1199 20.4116C13.4463 20.4116 12.047 19.2369 11.7016 17.667L3.75 17.667C3.33579 17.667 3 17.3312 3 16.917C3 16.5028 3.33579 16.167 3.75 16.167L11.6993 16.167ZM8.88007 9.08838C9.98464 9.08838 10.8801 8.19295 10.8801 7.08838C10.8801 5.98381 9.98464 5.08838 8.88007 5.08838C7.7755 5.08838 6.88007 5.98381 6.88007 7.08838C6.88007 8.19295 7.7755 9.08838 8.88007 9.08838ZM20.25 6.33301L12.2984 6.33301C11.953 4.76311 10.5537 3.58838 8.88007 3.58838C7.20642 3.58838 5.80714 4.76311 5.4618 6.33301L3.75 6.333C3.33579 6.333 3 6.66879 3 7.083C3 7.49722 3.33579 7.833 3.75 7.833L5.45945 7.83301C5.80077 9.40829 7.20261 10.5884 8.88007 10.5884C10.5575 10.5884 11.9594 9.40829 12.3007 7.83301L20.25 7.83301C20.6642 7.83301 21 7.49722 21 7.08301C21 6.66879 20.6642 6.33301 20.25 6.33301Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSlidersHorizontal);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "ee302eaaaaaa67470aacb7f798384269.svg");

/***/ }),

/***/ 66499:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PropertyPanelSliderInput-module__Root--nCbQo{display:flex}.PropertyPanelSliderInput-module__NumberContainer--W6z9N{width:56px;margin-right:16px;flex:0 0 auto}.PropertyPanelSliderInput-module__Input--IdX0o{flex:1 1 auto;width:calc(100% - 72px);background-color:rgba(0,0,0,0);-webkit-appearance:none}.PropertyPanelSliderInput-module__Input--IdX0o:focus{outline:none}.PropertyPanelSliderInput-module__Input--IdX0o::-moz-range-track{width:100%;height:2px;cursor:pointer;background:linear-gradient(90deg, var(--theme-color-secondary), calc(var(--thumb-percentage) * 1%), var(--theme-color-bg-4) calc(var(--thumb-percentage) * 1%))}.PropertyPanelSliderInput-module__Input--IdX0o::-webkit-slider-runnable-track{width:100%;height:2px;cursor:pointer;background:linear-gradient(90deg, var(--theme-color-secondary), calc(var(--thumb-percentage) * 1%), var(--theme-color-bg-4) calc(var(--thumb-percentage) * 1%))}.PropertyPanelSliderInput-module__Input--IdX0o::-moz-range-thumb{height:14px;width:14px;margin-top:-6px;border-radius:50%;cursor:pointer;-webkit-appearance:none;background-color:var(--theme-color-fg-highlight);border:none}.PropertyPanelSliderInput-module__Input--IdX0o::-webkit-slider-thumb{height:14px;width:14px;margin-top:-6px;border-radius:50%;cursor:pointer;-webkit-appearance:none;background-color:var(--theme-color-fg-highlight);border:none}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/property-panel/PropertyPanelSliderInput/PropertyPanelSliderInput.module.scss"],"names":[],"mappings":"AAAA,8CACE,YAAA,CAGF,yDACE,UAAA,CACA,iBAAA,CACA,aAAA,CAGF,+CACE,aAAA,CACA,uBAAA,CACA,8BAAA,CACA,uBAAA,CAEA,qDACE,YAAA,CAoBF,iEALE,UAAA,CACA,UAAA,CACA,cAAA,CAKA,+JAAA,CAQF,8EAfE,UAAA,CACA,UAAA,CACA,cAAA,CAeA,+JAAA,CAQF,iEApCE,WAAA,CACA,UAAA,CACA,eAAA,CACA,iBAAA,CACA,cAAA,CACA,uBAAA,CACA,gDAAA,CACA,WAAA,CAiCF,qEAxCE,WAAA,CACA,UAAA,CACA,eAAA,CACA,iBAAA,CACA,cAAA,CACA,uBAAA,CACA,gDAAA,CACA,WAAA","sourcesContent":[".Root {\n  display: flex;\n}\n\n.NumberContainer {\n  width: 56px;\n  margin-right: 16px;\n  flex: 0 0 auto;\n}\n\n.Input {\n  flex: 1 1 auto;\n  width: calc(100% - 72px); // .NumberContainer width+margin\n  background-color: transparent;\n  -webkit-appearance: none;\n\n  &:focus {\n    outline: none;\n  }\n\n  @mixin thumb {\n    height: 14px;\n    width: 14px;\n    margin-top: -6px;\n    border-radius: 50%;\n    cursor: pointer;\n    -webkit-appearance: none;\n    background-color: var(--theme-color-fg-highlight);\n    border: none;\n  }\n\n  @mixin track {\n    width: 100%;\n    height: 2px;\n    cursor: pointer;\n  }\n\n  &::-moz-range-track {\n    @include track;\n    background: linear-gradient(\n      90deg,\n      var(--theme-color-secondary),\n      calc(var(--thumb-percentage) * 1%),\n      var(--theme-color-bg-4) calc(var(--thumb-percentage) * 1%)\n    );\n  }\n\n  &::-webkit-slider-runnable-track {\n    @include track;\n    background: linear-gradient(\n      90deg,\n      var(--theme-color-secondary),\n      calc(var(--thumb-percentage) * 1%),\n      var(--theme-color-bg-4) calc(var(--thumb-percentage) * 1%)\n    );\n  }\n\n  &::-moz-range-thumb {\n    @include thumb;\n  }\n\n  &::-webkit-slider-thumb {\n    @include thumb;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PropertyPanelSliderInput-module__Root--nCbQo`,
	"NumberContainer": `PropertyPanelSliderInput-module__NumberContainer--W6z9N`,
	"Input": `PropertyPanelSliderInput-module__Input--IdX0o`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 66508:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.defaultParseResponse = defaultParseResponse;
exports.addRequestID = addRequestID;
const streaming_1 = __webpack_require__(70973);
const log_1 = __webpack_require__(59347);
async function defaultParseResponse(client, props) {
    const { response, requestLogID, retryOfRequestLogID, startTime } = props;
    const body = await (async () => {
        if (props.options.stream) {
            (0, log_1.loggerFor)(client).debug('response', response.status, response.url, response.headers, response.body);
            // Note: there is an invariant here that isn't represented in the type system
            // that if you set `stream: true` the response type must also be `Stream<T>`
            if (props.options.__streamClass) {
                return props.options.__streamClass.fromSSEResponse(response, props.controller);
            }
            return streaming_1.Stream.fromSSEResponse(response, props.controller);
        }
        // fetch refuses to read the body when the status code is 204.
        if (response.status === 204) {
            return null;
        }
        if (props.options.__binaryResponse) {
            return response;
        }
        const contentType = response.headers.get('content-type');
        const mediaType = contentType?.split(';')[0]?.trim();
        const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');
        if (isJSON) {
            const json = await response.json();
            return addRequestID(json, response);
        }
        const text = await response.text();
        return text;
    })();
    (0, log_1.loggerFor)(client).debug(`[${requestLogID}] response parsed`, (0, log_1.formatRequestDetails)({
        retryOfRequestLogID,
        url: response.url,
        status: response.status,
        body,
        durationMs: Date.now() - startTime,
    }));
    return body;
}
function addRequestID(value, response) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return value;
    }
    return Object.defineProperty(value, '_request_id', {
        value: response.headers.get('request-id'),
        enumerable: false,
    });
}
//# sourceMappingURL=parse.js.map

/***/ }),

/***/ 66534:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .goto-definition-link {
	text-decoration: underline;
	cursor: pointer;
}`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/link/goToDefinitionAtPosition.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,0BAA0B;CAC1B,eAAe;AAChB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .goto-definition-link {\n\ttext-decoration: underline;\n\tcursor: pointer;\n}"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 67033:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const { ProjectModel } = __webpack_require__(6203);
const FileSystem = __webpack_require__(38656);

class FontLoader {
  constructor() {
    this.loadedFonts = new Set();
  }

  loadFont(familyName, fontPath) {
    if (this.loadedFonts.has(fontPath)) {
      return;
    }

    this.loadedFonts.add(fontPath);

    const fullPath = ProjectModel.instance._retainedProjectDirectory + '/' + fontPath;
    FileSystem.instance.downloadAsDataURI(fullPath, (dataURL) => {
      $(document.head).append(
        '<style>@font-face {font-family: "' + familyName + '"; src: url(' + dataURL + ');}</style>'
      );
    });
  }
}

FontLoader.instance = new FontLoader();

module.exports = FontLoader;


/***/ }),

/***/ 67041:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPlus = function SvgPlus(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.8867 5.76829C12.8867 5.35407 12.5509 5.01829 12.1367 5.01829C11.7225 5.01829 11.3867 5.35407 11.3867 5.76829V11.25H5.86377C5.44956 11.25 5.11377 11.5858 5.11377 12C5.11377 12.4142 5.44956 12.75 5.86377 12.75H11.3867V18.2318C11.3867 18.646 11.7225 18.9818 12.1367 18.9818C12.5509 18.9818 12.8867 18.646 12.8867 18.2318V12.75H18.4092C18.8235 12.75 19.1592 12.4142 19.1592 12C19.1592 11.5858 18.8235 11.25 18.4092 11.25H12.8867V5.76829Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPlus);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "922db9e143e50a66b4f21acb8c5fd03d.svg");

/***/ }),

/***/ 67140:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   i: () => (/* binding */ normalizeAlphanumericString)
/* harmony export */ });
function normalizeAlphanumericString(value) {
    return value.toString().toLowerCase();
}


/***/ }),

/***/ 67609:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-count-badge {
	padding: 3px 6px;
	border-radius: 11px;
	font-size: 11px;
	min-width: 18px;
	min-height: 18px;
	line-height: 11px;
	font-weight: normal;
	text-align: center;
	display: inline-block;
	box-sizing: border-box;
}

.monaco-count-badge.long {
	padding: 2px 3px;
	border-radius: 2px;
	min-height: auto;
	line-height: normal;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/countBadge/countBadge.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,gBAAgB;CAChB,mBAAmB;CACnB,eAAe;CACf,eAAe;CACf,gBAAgB;CAChB,iBAAiB;CACjB,mBAAmB;CACnB,kBAAkB;CAClB,qBAAqB;CACrB,sBAAsB;AACvB;;AAEA;CACC,gBAAgB;CAChB,kBAAkB;CAClB,gBAAgB;CAChB,mBAAmB;AACpB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-count-badge {\n\tpadding: 3px 6px;\n\tborder-radius: 11px;\n\tfont-size: 11px;\n\tmin-width: 18px;\n\tmin-height: 18px;\n\tline-height: 11px;\n\tfont-weight: normal;\n\ttext-align: center;\n\tdisplay: inline-block;\n\tbox-sizing: border-box;\n}\n\n.monaco-count-badge.long {\n\tpadding: 2px 3px;\n\tborder-radius: 2px;\n\tmin-height: auto;\n\tline-height: normal;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 67652:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Versions = void 0;
const resource_1 = __webpack_require__(39929);
const pagination_1 = __webpack_require__(92081);
const headers_1 = __webpack_require__(79973);
const uploads_1 = __webpack_require__(76409);
const path_1 = __webpack_require__(20854);
class Versions extends resource_1.APIResource {
    /**
     * Create Skill Version
     *
     * @example
     * ```ts
     * const version = await client.beta.skills.versions.create(
     *   'skill_id',
     * );
     * ```
     */
    create(skillID, params = {}, options) {
        const { betas, ...body } = params ?? {};
        return this._client.post((0, path_1.path) `/v1/skills/${skillID}/versions?beta=true`, (0, uploads_1.multipartFormRequestOptions)({
            body,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
                options?.headers,
            ]),
        }, this._client));
    }
    /**
     * Get Skill Version
     *
     * @example
     * ```ts
     * const version = await client.beta.skills.versions.retrieve(
     *   'version',
     *   { skill_id: 'skill_id' },
     * );
     * ```
     */
    retrieve(version, params, options) {
        const { skill_id, betas } = params;
        return this._client.get((0, path_1.path) `/v1/skills/${skill_id}/versions/${version}?beta=true`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * List Skill Versions
     *
     * @example
     * ```ts
     * // Automatically fetches more pages as needed.
     * for await (const versionListResponse of client.beta.skills.versions.list(
     *   'skill_id',
     * )) {
     *   // ...
     * }
     * ```
     */
    list(skillID, params = {}, options) {
        const { betas, ...query } = params ?? {};
        return this._client.getAPIList((0, path_1.path) `/v1/skills/${skillID}/versions?beta=true`, (pagination_1.PageCursor), {
            query,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * Delete Skill Version
     *
     * @example
     * ```ts
     * const version = await client.beta.skills.versions.delete(
     *   'version',
     *   { skill_id: 'skill_id' },
     * );
     * ```
     */
    delete(version, params, options) {
        const { skill_id, betas } = params;
        return this._client.delete((0, path_1.path) `/v1/skills/${skill_id}/versions/${version}?beta=true`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
                options?.headers,
            ]),
        });
    }
}
exports.Versions = Versions;
//# sourceMappingURL=versions.js.map

/***/ }),

/***/ 67736:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  B: () => (/* binding */ CodeEditor_CodeEditor_CodeEditor)
});

// EXTERNAL MODULE: ./src/editor/src/hooks/useDragHandler.ts
var useDragHandler = __webpack_require__(34676);
// EXTERNAL MODULE: include-loader!../../node_modules/monaco-editor/esm/vs/editor/editor.api.js + 669 modules
var editor_api = __webpack_require__(15618);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ./src/editor/src/utils/getDocsEndpoint.ts
var getDocsEndpoint = __webpack_require__(41160);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/index.ts
var Text = __webpack_require__(93834);
// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/toolbar/ToolbarButton/ToolbarButton.module.scss
var ToolbarButton_module = __webpack_require__(96788);
;// ../noodl-core-ui/src/components/toolbar/ToolbarButton/ToolbarButton.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(ToolbarButton_module/* default */.A, options);




       /* harmony default export */ const ToolbarButton_ToolbarButton_module = (ToolbarButton_module/* default */.A && ToolbarButton_module/* default */.A.locals ? ToolbarButton_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/toolbar/ToolbarButton/ToolbarButton.tsx




function ToolbarButton({ label, prefix, onClick }) {
    return (external_react_default().createElement("button", { className: external_classnames_default()([ToolbarButton_ToolbarButton_module['Root'], onClick && ToolbarButton_ToolbarButton_module['actionable']]), onClick: (e) => {
            if (onClick)
                onClick(e);
        } },
        prefix,
        external_react_default().createElement(Text/* Text */.EY, { className: external_classnames_default()([ToolbarButton_ToolbarButton_module['Text'], onClick && ToolbarButton_ToolbarButton_module['actionable']]) }, label)));
}

;// ../noodl-core-ui/src/components/toolbar/ToolbarButton/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/toolbar/ToolbarGrip/index.ts + 2 modules
var ToolbarGrip = __webpack_require__(61211);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!./src/editor/src/views/panels/propertyeditor/CodeEditor/CodeEditor.css
var CodeEditor = __webpack_require__(59303);
;// ./src/editor/src/views/panels/propertyeditor/CodeEditor/CodeEditor.css

      
      
      
      
      
      
      
      
      

var CodeEditor_options = {};

CodeEditor_options.styleTagTransform = (styleTagTransform_default());
CodeEditor_options.setAttributes = (setAttributesWithoutAttributes_default());

      CodeEditor_options.insert = insertBySelector_default().bind(null, "head");
    
CodeEditor_options.domAPI = (styleDomAPI_default());
CodeEditor_options.insertStyleElement = (insertStyleElement_default());

var CodeEditor_update = injectStylesIntoStyleTag_default()(CodeEditor/* default */.A, CodeEditor_options);




       /* harmony default export */ const CodeEditor_CodeEditor = (CodeEditor/* default */.A && CodeEditor/* default */.A.locals ? CodeEditor/* default */.A.locals : undefined);

// EXTERNAL MODULE: ./src/editor/src/views/panels/propertyeditor/CodeEditor/actions/index.ts + 2 modules
var actions = __webpack_require__(53823);
;// ./src/editor/src/views/panels/propertyeditor/CodeEditor/Themes/dark.ts

editor_api.editor.defineTheme('dark', {
    base: 'vs-dark',
    inherit: true,
    rules: [],
    colors: {
        'editor.background': '#323232',
        'editorGutter.background': '#3b3b3b'
    }
});

;// ./src/editor/src/views/panels/propertyeditor/CodeEditor/Themes/noodl-dark.ts

editor_api.editor.defineTheme('noodl-dark', {
    base: 'vs-dark',
    inherit: true,
    rules: [
        {
            token: 'comment',
            fontStyle: 'italic',
            foreground: '#8b877f'
        },
        {
            token: 'constant.character',
            foreground: '#eaeaea'
        },
        {
            token: 'string',
            foreground: '#f7c967'
        },
        {
            token: 'number',
            foreground: '#77C9D4'
        },
        {
            token: 'constant.numeric',
            foreground: '#eaeaea'
        },
        {
            token: 'delimiter',
            foreground: '#b6b5bf'
        },
        {
            token: 'keyword',
            foreground: '#bcaffb'
        },
        {
            token: 'type.identifier',
            foreground: '#f7c967'
        },
        {
            token: 'string.css',
            foreground: '#f7c967'
        },
        {
            token: 'tag.css',
            foreground: '#bcaffb'
        },
        {
            token: 'attribute.name.css',
            foreground: '#eaeaea'
        },
        {
            token: 'attribute.value.css',
            foreground: '#f7c967'
        },
        {
            token: 'attribute.value.number.css',
            foreground: '#f7c967'
        },
        {
            token: 'attribute.value.unit.css',
            foreground: '#f7c967'
        }
    ],
    colors: {
        'editor.background': '#323232',
        'editorGutter.background': '#3b3b3b',
        'editor.selectionBackground': '#1b1607',
        'editor.selectionHighlightBackground': '#9B86F940', //'#8070af',
        'editor.foreground': '#eaeaea',
        'editor.wordHighlightStrongBackground': '#9B86F940',
        'editor.wordHighlightStrongBorder': '#795EF799'
    }
});

// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
;// ./src/editor/src/views/panels/propertyeditor/CodeEditor/CodeEditor.tsx











function CodeEditor_CodeEditor_CodeEditor({ model, initialSize, onSave, outEditor }) {
    var _a, _b;
    const rootRef = (0,external_react_.useRef)(null);
    const editorRef = (0,external_react_.useRef)(null);
    const [editor, setEditor] = (0,external_react_.useState)(null);
    const [size, setSize] = (0,external_react_.useState)({
        width: (_a = initialSize === null || initialSize === void 0 ? void 0 : initialSize.x) !== null && _a !== void 0 ? _a : 700,
        height: (_b = initialSize === null || initialSize === void 0 ? void 0 : initialSize.y) !== null && _b !== void 0 ? _b : 500
    });
    const [language, setLanguage] = (0,external_react_.useState)('');
    const [cursorPos, setCursorPos] = (0,external_react_.useState)('Ln 1, Col 1');
    const { startDrag } = (0,useDragHandler/* useDragHandler */.k)({
        root: rootRef,
        minHeight: 120,
        minWidth: 120,
        onDrag(contentWidth, contentHeight) {
            setSize({
                width: contentWidth,
                height: contentHeight
            });
        },
        onEndDrag() {
            editor === null || editor === void 0 ? void 0 : editor.focus();
        }
    });
    (0,external_react_.useLayoutEffect)(() => {
        const newEditor = editor_api.editor.create(editorRef.current, {
            model: model.model,
            language: model.model.getLanguageId(),
            theme: (0,actions/* getTheme */.O)(),
            glyphMargin: false,
            folding: false,
            autoDetectHighContrast: false,
            minimap: { enabled: false },
            suggest: {
                localityBonus: true,
                preview: true,
                showMethods: true,
                showFunctions: true,
                showConstructors: false,
                showDeprecated: false,
                showFields: true,
                showVariables: true,
                showClasses: true,
                showStructs: true,
                showInterfaces: false,
                showFiles: false,
                showUsers: true,
                showSnippets: true
            },
            quickSuggestions: true,
            inlineSuggest: {
                enabled: false
            },
            wordWrap: model.model.getLanguageId() === 'plaintext' ? 'on' : 'off',
            // lightbulb: {
            //   enabled: true
            // },
            accessibilityHelpUrl: (0,getDocsEndpoint/* default */.A)()
        });
        (0,actions/* registerActions */.n)(newEditor);
        // Solve the issue where it scrolls to line 2
        let firstLayoutChange = true;
        newEditor.onDidLayoutChange(() => {
            if (!firstLayoutChange)
                return;
            firstLayoutChange = false;
            newEditor.setSelection(new editor_api.Selection(0, 0, 0, 0));
            editorRef.current.scrollTop = 0;
        });
        // Add a save command,
        // this is not important when we have auto-save,
        // but important when we dont have it.
        newEditor.addAction({
            id: 'save',
            label: 'Save',
            keybindings: [editor_api.KeyMod.CtrlCmd | editor_api.KeyCode.KeyS],
            run() {
                onSave && onSave();
            }
        });
        newEditor.onDidChangeCursorSelection((e) => {
            const selectedCharacters = newEditor.getModel().getCharacterCountInRange(e.selection);
            const selectedText = selectedCharacters > 0
                ? `Ln ${e.selection.startLineNumber}, Col ${e.selection.startColumn} (${selectedCharacters} selected)`
                : `Ln ${e.selection.startLineNumber}, Col ${e.selection.startColumn}`;
            setCursorPos(selectedText);
        });
        // NOTE(auto-saving): Uncomment to enable auto saving
        // newEditor.onDidChangeModelContent((_evt) => onSave());
        model.attachEditor(newEditor);
        setLanguage(model.getPrettyLanguageName());
        setEditor(newEditor);
        outEditor && outEditor(newEditor);
    }, [editorRef]);
    (0,external_react_.useEffect)(() => {
        if (!editor)
            return;
        editor.layout({
            width: editorRef.current.offsetWidth,
            height: editorRef.current.offsetHeight
        });
    }, [editor, size]);
    const gutterSize = '48px';
    let testRunCodeLabel = 'TEST CODE';
    // When not a scripting language change the button label.
    if (['javascript', 'typescript'].includes(language.toLowerCase())) {
        testRunCodeLabel = 'TEST RUN CODE';
    }
    return (external_react_default().createElement("div", { ref: rootRef, style: {
            width: size.width,
            height: size.height,
            minWidth: 200,
            minHeight: 200,
            display: 'grid',
            gridTemplateRows: '24px auto 24px'
        } },
        external_react_default().createElement("div", { style: { display: 'flex', justifyContent: 'space-between', backgroundColor: '#3b3b3b' } }),
        external_react_default().createElement("div", { ref: editorRef, style: { overflow: 'hidden' } }),
        external_react_default().createElement("div", { style: { display: 'flex', justifyContent: 'space-between', backgroundColor: '#3b3b3b' } },
            external_react_default().createElement("div", { style: { display: 'flex', paddingLeft: gutterSize, alignItems: 'center' } },
                external_react_default().createElement(ToolbarButton, { prefix: external_react_default().createElement(Icon/* Icon */.In, { icon: Icon/* IconName */.$M.Play, size: Icon/* IconSize */.lK.Small, UNSAFE_style: { paddingRight: '8px' } }), label: testRunCodeLabel, onClick: () => {
                        onSave && onSave();
                    } })),
            external_react_default().createElement("div", { style: { display: 'flex', alignItems: 'center' } },
                external_react_default().createElement(ToolbarButton, { label: cursorPos }),
                external_react_default().createElement(ToolbarButton, { label: language }),
                external_react_default().createElement(ToolbarGrip/* ToolbarGrip */.M, { onMouseDown: startDrag })))));
}


/***/ }),

/***/ 68091:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   m: () => (/* reexport safe */ _nodelibrary__WEBPACK_IMPORTED_MODULE_0__.m)
/* harmony export */ });
/* harmony import */ var _nodelibrary__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15204);



/***/ }),

/***/ 68160:
/***/ ((module) => {

// Module
var code = "<div class=\"popup-layer\"> <div class=\"popup-layer-popout\" data-template=\"popout\"> <div class=\"popup-layer-popout-arrow\"></div> <div class=\"popup-layer-popout-content\"></div> </div> <div class=\"popup-small-docs\"> </div> <div class=\"popup-layer-popouts\"></div> <div class=\"popup-layer-popup\"> <div class=\"popup-layer-popup-arrow\"></div> <div class=\"popup-layer-popup-content\"></div> </div> <div class=\"popup-layer-modal\"> <div class=\"popup-layer-modal-content\"></div> </div> <div class=\"popup-layer-toast\"></div> <div class=\"popup-layer-dragger\"><i class=\"popup-layer-drop-type-indicator fa\"></i><span class=\"popup-layer-dragger-label\"></span> <div class=\"popup-layer-drag-message\" style=\"display:none\"> <i class=\"fa fa-exclamation-triangle\"></i> <small><span class=\"popup-layer-drag-message-text\"></span></small> </div> </div> <div class=\"popup-layer-tooltip\"> <div class=\"dark popup-layer-tooltip-arrow\"></div> <div class=\"popup-layer-tooltip-content\"></div> </div> <div class=\"popup-file-drop\" style=\"display:none\"> <div class=\"popup-file-drop-msg\"> Drop files here to copy to project folder. </div> </div> <div class=\"popup-layer-activity\"> <div class=\"popup-layer-activity-text\"></div> <div class=\"spinner popup-layer-activity-spinner\"> <div class=\"bounce1\"></div> <div class=\"bounce2\"></div> <div class=\"bounce3\"></div> </div> <div class=\"popup-layer-activity-progress\"> <div class=\"popup-layer-activity-progress-bar\"></div> </div> </div> <div class=\"popup-layer-blocker\" style=\"width:100%;height:100%;pointer-events:all;display:none\" data-test=\"popup-layer-blocker\"></div> </div>";
// Exports
module.exports = code;

/***/ }),

/***/ 68228:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   C: () => (/* binding */ RuntimeTypes),
/* harmony export */   r: () => (/* binding */ RuntimeType)
/* harmony export */ });
var RuntimeType;
(function (RuntimeType) {
    RuntimeType["Browser"] = "browser";
    RuntimeType["Cloud"] = "cloud";
})(RuntimeType || (RuntimeType = {}));
const RuntimeTypes = [RuntimeType.Browser, RuntimeType.Cloud];


/***/ }),

/***/ 68284:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgFolderOpen = function SvgFolderOpen(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.2819 5.85688C3.2819 5.83482 3.28948 5.81974 3.2948 5.81273L8.26721 5.81273L10.8693 7.87421L10.8711 7.87561C11.1295 8.07911 11.4486 8.19371 11.7818 8.19516L11.785 8.19517L18.269 8.19517C18.2743 8.20218 18.2819 8.21725 18.2819 8.23931L18.2819 10.6218C18.2819 10.6694 18.2864 10.7161 18.2949 10.7613L6.07219 10.7613C5.75219 10.7613 5.45219 10.8513 5.20219 11.0313C4.94219 11.2113 4.75219 11.4713 4.65219 11.7613L3.2819 15.7027L3.2819 5.85688ZM1.78259 20.184C1.79959 20.5831 2.12857 20.9015 2.5319 20.9015C2.53788 20.9015 2.54384 20.9014 2.54978 20.9013L19.0322 20.9013C19.3522 20.9013 19.6322 20.7013 19.7422 20.4013L22.4122 12.7013C22.4922 12.4813 22.5122 12.2413 22.4722 12.0013C22.4422 11.7713 22.3422 11.5513 22.2022 11.3613C22.0622 11.1813 21.8722 11.0213 21.6622 10.9213C21.4522 10.8113 21.2222 10.7613 20.9922 10.7613L19.7689 10.7613C19.7775 10.7161 19.7819 10.6694 19.7819 10.6218L19.7819 8.23931C19.7819 7.84318 19.6337 7.45525 19.3575 7.16281C19.0799 6.86891 18.694 6.69517 18.2819 6.69517L11.7966 6.69517L9.19451 4.63369L9.19274 4.63229C8.93428 4.42879 8.61522 4.31418 8.28204 4.31273L3.2819 4.31273C2.86978 4.31273 2.48386 4.48648 2.2063 4.78037C1.93012 5.07282 1.7819 5.46074 1.7819 5.85688L1.7819 20.1155C1.78107 20.1383 1.7813 20.1612 1.78259 20.184ZM18.5022 19.4013L3.59219 19.4013L6.08219 12.2613L21.0022 12.2113L18.5022 19.4013Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgFolderOpen);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "41f6b2ee86789277dd87e4e1230e9033.svg");

/***/ }),

/***/ 68334:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCaretLeft = function SvgCaretLeft(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M15.667 5.46967C15.9599 5.76256 15.9599 6.23744 15.667 6.53033L10.1974 12L15.667 17.4697C15.9599 17.7626 15.9599 18.2374 15.667 18.5303C15.3742 18.8232 14.8993 18.8232 14.6064 18.5303L8.60639 12.5303C8.3135 12.2374 8.3135 11.7626 8.60639 11.4697L14.6064 5.46967C14.8993 5.17678 15.3742 5.17678 15.667 5.46967Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCaretLeft);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "cd6ff3d29ae2fcf2c024923f22e923b7.svg");

/***/ }),

/***/ 68336:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Markdown-module__Root--ZtqqA{margin-block-start:0;margin-block-end:0;font-family:var(--font-family);font-size:12px;color:var(--theme-color-fg-default)}.Markdown-module__Root--ZtqqA h1,.Markdown-module__Root--ZtqqA h2,.Markdown-module__Root--ZtqqA h3,.Markdown-module__Root--ZtqqA h4,.Markdown-module__Root--ZtqqA h5,.Markdown-module__Root--ZtqqA h6{font-family:var(--font-family);color:var(--theme-color-fg-default);font-weight:600}.Markdown-module__Root--ZtqqA p{font-family:var(--font-family);color:var(--theme-color-fg-default);font-size:12px;margin:0 0 8px 0}.Markdown-module__Root--ZtqqA p:last-of-type{margin-bottom:0}.Markdown-module__Root--ZtqqA a{font-weight:700;color:var(--theme-color-primary);text-decoration:underline}.Markdown-module__Root--ZtqqA ul,.Markdown-module__Root--ZtqqA ol{padding-left:16px}.Markdown-module__Root--ZtqqA li{padding-bottom:8px}.Markdown-module__Root--ZtqqA blockquote{display:block;margin-block-start:1em;margin-block-end:1em;margin-inline-start:16px;margin-inline-end:16px}.Markdown-module__Root--ZtqqA img{max-width:100%}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/common/Markdown/Markdown.module.scss"],"names":[],"mappings":"AAAA,8BACE,oBAAA,CACA,kBAAA,CACA,8BAAA,CACA,cAAA,CACA,mCAAA,CAEA,sMAME,8BAAA,CACA,mCAAA,CACA,eAAA,CAGF,gCACE,8BAAA,CACA,mCAAA,CACA,cAAA,CAEA,gBAAA,CAGF,6CACE,eAAA,CAGF,gCACE,eAAA,CACA,gCAAA,CACA,yBAAA,CAGF,kEAEE,iBAAA,CAGF,iCACE,kBAAA,CAGF,yCACE,aAAA,CACA,sBAAA,CACA,oBAAA,CACA,wBAAA,CACA,sBAAA,CAGF,kCACE,cAAA","sourcesContent":[".Root {\n  margin-block-start: 0;\n  margin-block-end: 0;\n  font-family: var(--font-family);\n  font-size: 12px;\n  color: var(--theme-color-fg-default);\n\n  h1,\n  h2,\n  h3,\n  h4,\n  h5,\n  h6 {\n    font-family: var(--font-family);\n    color: var(--theme-color-fg-default);\n    font-weight: 600;\n  }\n\n  p {\n    font-family: var(--font-family);\n    color: var(--theme-color-fg-default);\n    font-size: 12px;\n\n    margin: 0 0 8px 0;\n  }\n\n  p:last-of-type {\n    margin-bottom: 0;\n  }\n\n  a {\n    font-weight: 700;\n    color: var(--theme-color-primary);\n    text-decoration: underline;\n  }\n\n  ul,\n  ol {\n    padding-left: 16px;\n  }\n\n  li {\n    padding-bottom: 8px;\n  }\n\n  blockquote {\n    display: block;\n    margin-block-start: 1em;\n    margin-block-end: 1em;\n    margin-inline-start: 16px;\n    margin-inline-end: 16px;\n  }\n\n  img {\n    max-width: 100%;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Markdown-module__Root--ZtqqA`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 68415:
/***/ ((module) => {

// Module
var code = "<div style=\"position:relative\"> <div data-template=\"item\" class=\"sidebar-panel-item component-ports-item\"> <div class=\"show-on-edit name-edit-container\"> <input type=\"string\" class=\"sidebar-panel-dark-input name-edit\" data-val=\"name\"> </div> <span data-class=\"isDefault:stringlist-default-label\" class=\"component-ports-label hide-on-edit\" data-text=\"name\" data-bind=\"watch\" data-click=\"onRenameClicked\"></span> <div class=\"sidebar-panel-edit-bar hide-on-edit\"> <button type=\"button\" class=\"sidebar-panel-edit-button\" data-click=\"onRenameClicked\"><i class=\"fa fa-pencil-square-o\"></i></button> <button type=\"button\" data-class=\"isDefault:hidden\" class=\"sidebar-panel-edit-button\" data-click=\"onDeleteClicked\"><i class=\"fa fa-trash-o\"></i></button> </div> </div> <div class=\"items\"> </div> <div class=\"sidebar-panel-edit-bar stringlist-add-button-container\"> <button type=\"button\" class=\"sidebar-panel-edit-button\" data-click=\"onAddPortClicked\"><i class=\"fa fa-plus\"></i></button> </div> </div> ";
// Exports
module.exports = code;

/***/ }),

/***/ 69019:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/* ---------- Find input ---------- */

.monaco-findInput {
	position: relative;
}

.monaco-findInput .monaco-inputbox {
	font-size: 13px;
	width: 100%;
}

.monaco-findInput > .controls {
	position: absolute;
	top: 3px;
	right: 2px;
}

.vs .monaco-findInput.disabled {
	background-color: #E1E1E1;
}

/* Theming */
.vs-dark .monaco-findInput.disabled {
	background-color: #333;
}

/* Highlighting */
.monaco-findInput.highlight-0 .controls,
.hc-light .monaco-findInput.highlight-0 .controls {
	animation: monaco-findInput-highlight-0 100ms linear 0s;
}

.monaco-findInput.highlight-1 .controls,
.hc-light .monaco-findInput.highlight-1 .controls {
	animation: monaco-findInput-highlight-1 100ms linear 0s;
}

.hc-black .monaco-findInput.highlight-0 .controls,
.vs-dark  .monaco-findInput.highlight-0 .controls {
	animation: monaco-findInput-highlight-dark-0 100ms linear 0s;
}

.hc-black .monaco-findInput.highlight-1 .controls,
.vs-dark  .monaco-findInput.highlight-1 .controls {
	animation: monaco-findInput-highlight-dark-1 100ms linear 0s;
}

@keyframes monaco-findInput-highlight-0 {
	0% { background: rgba(253, 255, 0, 0.8); }
	100% { background: transparent; }
}
@keyframes monaco-findInput-highlight-1 {
	0% { background: rgba(253, 255, 0, 0.8); }
	/* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/
	99% { background: transparent; }
}

@keyframes monaco-findInput-highlight-dark-0 {
	0% { background: rgba(255, 255, 255, 0.44); }
	100% { background: transparent; }
}
@keyframes monaco-findInput-highlight-dark-1 {
	0% { background: rgba(255, 255, 255, 0.44); }
	/* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/
	99% { background: transparent; }
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/findinput/findInput.css"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F,qCAAqC;;AAErC;CACC,kBAAkB;AACnB;;AAEA;CACC,eAAe;CACf,WAAW;AACZ;;AAEA;CACC,kBAAkB;CAClB,QAAQ;CACR,UAAU;AACX;;AAEA;CACC,yBAAyB;AAC1B;;AAEA,YAAY;AACZ;CACC,sBAAsB;AACvB;;AAEA,iBAAiB;AACjB;;CAEC,uDAAuD;AACxD;;AAEA;;CAEC,uDAAuD;AACxD;;AAEA;;CAEC,4DAA4D;AAC7D;;AAEA;;CAEC,4DAA4D;AAC7D;;AAEA;CACC,KAAK,kCAAkC,EAAE;CACzC,OAAO,uBAAuB,EAAE;AACjC;AACA;CACC,KAAK,kCAAkC,EAAE;CACzC,kHAAkH;CAClH,MAAM,uBAAuB,EAAE;AAChC;;AAEA;CACC,KAAK,qCAAqC,EAAE;CAC5C,OAAO,uBAAuB,EAAE;AACjC;AACA;CACC,KAAK,qCAAqC,EAAE;CAC5C,kHAAkH;CAClH,MAAM,uBAAuB,EAAE;AAChC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/* ---------- Find input ---------- */\n\n.monaco-findInput {\n\tposition: relative;\n}\n\n.monaco-findInput .monaco-inputbox {\n\tfont-size: 13px;\n\twidth: 100%;\n}\n\n.monaco-findInput > .controls {\n\tposition: absolute;\n\ttop: 3px;\n\tright: 2px;\n}\n\n.vs .monaco-findInput.disabled {\n\tbackground-color: #E1E1E1;\n}\n\n/* Theming */\n.vs-dark .monaco-findInput.disabled {\n\tbackground-color: #333;\n}\n\n/* Highlighting */\n.monaco-findInput.highlight-0 .controls,\n.hc-light .monaco-findInput.highlight-0 .controls {\n\tanimation: monaco-findInput-highlight-0 100ms linear 0s;\n}\n\n.monaco-findInput.highlight-1 .controls,\n.hc-light .monaco-findInput.highlight-1 .controls {\n\tanimation: monaco-findInput-highlight-1 100ms linear 0s;\n}\n\n.hc-black .monaco-findInput.highlight-0 .controls,\n.vs-dark  .monaco-findInput.highlight-0 .controls {\n\tanimation: monaco-findInput-highlight-dark-0 100ms linear 0s;\n}\n\n.hc-black .monaco-findInput.highlight-1 .controls,\n.vs-dark  .monaco-findInput.highlight-1 .controls {\n\tanimation: monaco-findInput-highlight-dark-1 100ms linear 0s;\n}\n\n@keyframes monaco-findInput-highlight-0 {\n\t0% { background: rgba(253, 255, 0, 0.8); }\n\t100% { background: transparent; }\n}\n@keyframes monaco-findInput-highlight-1 {\n\t0% { background: rgba(253, 255, 0, 0.8); }\n\t/* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/\n\t99% { background: transparent; }\n}\n\n@keyframes monaco-findInput-highlight-dark-0 {\n\t0% { background: rgba(255, 255, 255, 0.44); }\n\t100% { background: transparent; }\n}\n@keyframes monaco-findInput-highlight-dark-1 {\n\t0% { background: rgba(255, 255, 255, 0.44); }\n\t/* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/\n\t99% { background: transparent; }\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 69184:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .parameter-hints-widget {
	/* Must be higher than the sash's z-index and terminal canvases but lower than the suggest widget */
	z-index: 39;
	display: flex;
	flex-direction: column;
	line-height: 1.5em;
	cursor: default;
}

.monaco-editor .parameter-hints-widget > .phwrapper {
	max-width: 440px;
	display: flex;
	flex-direction: row;
}

.monaco-editor .parameter-hints-widget.multiple {
	min-height: 3.3em;
	padding: 0;
}

.monaco-editor .parameter-hints-widget.visible {
	transition: left .05s ease-in-out;
}

.monaco-editor .parameter-hints-widget p,
.monaco-editor .parameter-hints-widget ul {
	margin: 8px 0;
}

.monaco-editor .parameter-hints-widget .monaco-scrollable-element,
.monaco-editor .parameter-hints-widget .body {
	display: flex;
	flex: 1;
	flex-direction: column;
	min-height: 100%;
}

.monaco-editor .parameter-hints-widget .signature {
	padding: 4px 5px;
}

.monaco-editor .parameter-hints-widget .docs {
	padding: 0 10px 0 5px;
	white-space: pre-wrap;
}

.monaco-editor .parameter-hints-widget .docs.empty {
	display: none;
}

.monaco-editor .parameter-hints-widget .docs .markdown-docs {
	white-space: initial;
}

.monaco-editor .parameter-hints-widget .docs .markdown-docs a:hover {
	cursor: pointer;
}

.monaco-editor .parameter-hints-widget .docs .markdown-docs code {
	font-family: var(--monaco-monospace-font);
}

.monaco-editor .parameter-hints-widget .docs  .monaco-tokenized-source,
.monaco-editor .parameter-hints-widget .docs .code {
	white-space: pre-wrap;
}

.monaco-editor .parameter-hints-widget .docs code {
	border-radius: 3px;
	padding: 0 0.4em;
}

.monaco-editor .parameter-hints-widget .controls {
	display: none;
	flex-direction: column;
	align-items: center;
	min-width: 22px;
	justify-content: flex-end;
}

.monaco-editor .parameter-hints-widget.multiple .controls {
	display: flex;
	padding: 0 2px;
}

.monaco-editor .parameter-hints-widget.multiple .button {
	width: 16px;
	height: 16px;
	background-repeat: no-repeat;
	cursor: pointer;
}

.monaco-editor .parameter-hints-widget .button.previous {
	bottom: 24px;
}

.monaco-editor .parameter-hints-widget .overloads {
	text-align: center;
	height: 12px;
	line-height: 12px;
	font-family: var(--monaco-monospace-font);
}

.monaco-editor .parameter-hints-widget .signature .parameter.active {
	font-weight: bold;
}

.monaco-editor .parameter-hints-widget .documentation-parameter > .parameter {
	font-weight: bold;
	margin-right: 0.5em;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/parameterHints/browser/parameterHints.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,mGAAmG;CACnG,WAAW;CACX,aAAa;CACb,sBAAsB;CACtB,kBAAkB;CAClB,eAAe;AAChB;;AAEA;CACC,gBAAgB;CAChB,aAAa;CACb,mBAAmB;AACpB;;AAEA;CACC,iBAAiB;CACjB,UAAU;AACX;;AAEA;CACC,iCAAiC;AAClC;;AAEA;;CAEC,aAAa;AACd;;AAEA;;CAEC,aAAa;CACb,OAAO;CACP,sBAAsB;CACtB,gBAAgB;AACjB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,qBAAqB;CACrB,qBAAqB;AACtB;;AAEA;CACC,aAAa;AACd;;AAEA;CACC,oBAAoB;AACrB;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,yCAAyC;AAC1C;;AAEA;;CAEC,qBAAqB;AACtB;;AAEA;CACC,kBAAkB;CAClB,gBAAgB;AACjB;;AAEA;CACC,aAAa;CACb,sBAAsB;CACtB,mBAAmB;CACnB,eAAe;CACf,yBAAyB;AAC1B;;AAEA;CACC,aAAa;CACb,cAAc;AACf;;AAEA;CACC,WAAW;CACX,YAAY;CACZ,4BAA4B;CAC5B,eAAe;AAChB;;AAEA;CACC,YAAY;AACb;;AAEA;CACC,kBAAkB;CAClB,YAAY;CACZ,iBAAiB;CACjB,yCAAyC;AAC1C;;AAEA;CACC,iBAAiB;AAClB;;AAEA;CACC,iBAAiB;CACjB,mBAAmB;AACpB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .parameter-hints-widget {\n\t/* Must be higher than the sash's z-index and terminal canvases but lower than the suggest widget */\n\tz-index: 39;\n\tdisplay: flex;\n\tflex-direction: column;\n\tline-height: 1.5em;\n\tcursor: default;\n}\n\n.monaco-editor .parameter-hints-widget > .phwrapper {\n\tmax-width: 440px;\n\tdisplay: flex;\n\tflex-direction: row;\n}\n\n.monaco-editor .parameter-hints-widget.multiple {\n\tmin-height: 3.3em;\n\tpadding: 0;\n}\n\n.monaco-editor .parameter-hints-widget.visible {\n\ttransition: left .05s ease-in-out;\n}\n\n.monaco-editor .parameter-hints-widget p,\n.monaco-editor .parameter-hints-widget ul {\n\tmargin: 8px 0;\n}\n\n.monaco-editor .parameter-hints-widget .monaco-scrollable-element,\n.monaco-editor .parameter-hints-widget .body {\n\tdisplay: flex;\n\tflex: 1;\n\tflex-direction: column;\n\tmin-height: 100%;\n}\n\n.monaco-editor .parameter-hints-widget .signature {\n\tpadding: 4px 5px;\n}\n\n.monaco-editor .parameter-hints-widget .docs {\n\tpadding: 0 10px 0 5px;\n\twhite-space: pre-wrap;\n}\n\n.monaco-editor .parameter-hints-widget .docs.empty {\n\tdisplay: none;\n}\n\n.monaco-editor .parameter-hints-widget .docs .markdown-docs {\n\twhite-space: initial;\n}\n\n.monaco-editor .parameter-hints-widget .docs .markdown-docs a:hover {\n\tcursor: pointer;\n}\n\n.monaco-editor .parameter-hints-widget .docs .markdown-docs code {\n\tfont-family: var(--monaco-monospace-font);\n}\n\n.monaco-editor .parameter-hints-widget .docs  .monaco-tokenized-source,\n.monaco-editor .parameter-hints-widget .docs .code {\n\twhite-space: pre-wrap;\n}\n\n.monaco-editor .parameter-hints-widget .docs code {\n\tborder-radius: 3px;\n\tpadding: 0 0.4em;\n}\n\n.monaco-editor .parameter-hints-widget .controls {\n\tdisplay: none;\n\tflex-direction: column;\n\talign-items: center;\n\tmin-width: 22px;\n\tjustify-content: flex-end;\n}\n\n.monaco-editor .parameter-hints-widget.multiple .controls {\n\tdisplay: flex;\n\tpadding: 0 2px;\n}\n\n.monaco-editor .parameter-hints-widget.multiple .button {\n\twidth: 16px;\n\theight: 16px;\n\tbackground-repeat: no-repeat;\n\tcursor: pointer;\n}\n\n.monaco-editor .parameter-hints-widget .button.previous {\n\tbottom: 24px;\n}\n\n.monaco-editor .parameter-hints-widget .overloads {\n\ttext-align: center;\n\theight: 12px;\n\tline-height: 12px;\n\tfont-family: var(--monaco-monospace-font);\n}\n\n.monaco-editor .parameter-hints-widget .signature .parameter.active {\n\tfont-weight: bold;\n}\n\n.monaco-editor .parameter-hints-widget .documentation-parameter > .parameter {\n\tfont-weight: bold;\n\tmargin-right: 0.5em;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 69315:
/***/ ((module) => {

"use strict";
module.exports = require("md5-file");

/***/ }),

/***/ 69401:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   q: () => (/* binding */ AiCopilotContext)
/* harmony export */ });
/* harmony import */ var _noodl_models_AiAssistant_context_ai_api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(51917);
/* harmony import */ var _noodl_models_AiAssistant_context_ai_query__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3702);


class AiCopilotContext {
    constructor(template, chatHistory, node) {
        this.template = template;
        this.chatHistory = chatHistory;
        this.node = node;
        this.abortController = new AbortController();
    }
    chatStream(args) {
        if (!args.abortController) {
            args.abortController = this.abortController;
        }
        return _noodl_models_AiAssistant_context_ai_api__WEBPACK_IMPORTED_MODULE_0__.Ai.chatStream(args);
    }
    chatStreamXml(args) {
        if (!args.abortController) {
            args.abortController = this.abortController;
        }
        return _noodl_models_AiAssistant_context_ai_query__WEBPACK_IMPORTED_MODULE_1__/* .AiQuery */ .$.chatStreamXml(args);
    }
    toObject() {
        return {
            template: this.template,
            chatHistory: this.chatHistory,
            node: this.node,
            chatStream: this.chatStream.bind(this),
            chatStreamXml: this.chatStreamXml.bind(this)
        };
    }
}


/***/ }),

/***/ 69402:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   K: () => (/* binding */ getGitStats)
/* harmony export */ });
/* harmony import */ var _noodl_git__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7457);
/* harmony import */ var _noodl_utils_projectmerger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(78200);
/* harmony import */ var _noodl_utils_projectmerger__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_noodl_utils_projectmerger__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _projectmodel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6203);



/**
 * Git stats used for deployment of frontend.
 */
async function getGitStats() {
    try {
        const git = new _noodl_git__WEBPACK_IMPORTED_MODULE_0__/* .Git */ .TU(_noodl_utils_projectmerger__WEBPACK_IMPORTED_MODULE_1__.mergeProject);
        await git.openRepository(_projectmodel__WEBPACK_IMPORTED_MODULE_2__.ProjectModel.instance._retainedProjectDirectory);
        const gitBranch = await git.getCurrentBranchName();
        const gitSha = await git.getHeadCommitId();
        const gitLocalChanges = (await git.status()).length > 0;
        return { gitBranch, gitSha, gitLocalChanges };
    }
    catch (err) {
        console.error(err);
    }
    return {
        gitBranch: 'unknown',
        gitSha: 'unknown',
        gitLocalChanges: false
    };
}


/***/ }),

/***/ 69651:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.CarouselIndicatorDot-module__Root--deErS{border-radius:50%;background-color:var(--theme-color-bg-3);height:10px;width:10px;cursor:pointer;transition:background-color 100ms}.CarouselIndicatorDot-module__Root--deErS.CarouselIndicatorDot-module__is-active--w7ri_{background-color:var(--theme-color-fg-muted)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/CarouselIndicatorDot/CarouselIndicatorDot.module.scss"],"names":[],"mappings":"AAAA,0CACE,iBAAA,CACA,wCAAA,CACA,WAAA,CACA,UAAA,CACA,cAAA,CACA,iCAAA,CAEA,wFACE,4CAAA","sourcesContent":[".Root {\n  border-radius: 50%;\n  background-color: var(--theme-color-bg-3);\n  height: 10px;\n  width: 10px;\n  cursor: pointer;\n  transition: background-color 100ms;\n\n  &.is-active {\n    background-color: var(--theme-color-fg-muted);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `CarouselIndicatorDot-module__Root--deErS`,
	"is-active": `CarouselIndicatorDot-module__is-active--w7ri_`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 69820:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.BackendCard-module__Root--GDgZ5{background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:6px;padding:12px;margin-bottom:8px;transition:border-color .2s ease}.BackendCard-module__Root--GDgZ5:hover{border-color:var(--theme-color-border-hover)}.BackendCard-module__Root--GDgZ5.BackendCard-module__Active--nG2MN{border-color:var(--theme-color-primary);background-color:var(--theme-color-bg-2)}.BackendCard-module__Header--jafMq{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:8px}.BackendCard-module__TypeIcon--Qn5pY{width:32px;height:32px;border-radius:6px;background-color:var(--theme-color-primary);display:flex;align-items:center;justify-content:center;flex-shrink:0}.BackendCard-module__ActiveBadge--cXxjD{background-color:var(--theme-color-primary);color:var(--theme-color-fg-on-primary);padding:2px 6px;border-radius:4px;text-transform:uppercase;letter-spacing:.5px}.BackendCard-module__Status--M75U5{margin-bottom:8px;padding-top:8px;border-top:1px solid var(--theme-color-border-default)}.BackendCard-module__SchemaInfo--QWiPz{margin-bottom:8px}.BackendCard-module__Actions--PyYTj{padding-top:8px;border-top:1px solid var(--theme-color-border-default)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/BackendServicesPanel/BackendCard/BackendCard.module.scss"],"names":[],"mappings":"AAAA,iCACE,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,YAAA,CACA,iBAAA,CACA,gCAAA,CAEA,uCACE,4CAAA,CAGF,mEACE,uCAAA,CACA,wCAAA,CAIJ,mCACE,YAAA,CACA,6BAAA,CACA,sBAAA,CACA,iBAAA,CAGF,qCACE,UAAA,CACA,WAAA,CACA,iBAAA,CACA,2CAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,aAAA,CAGF,wCACE,2CAAA,CACA,sCAAA,CACA,eAAA,CACA,iBAAA,CACA,wBAAA,CACA,mBAAA,CAGF,mCACE,iBAAA,CACA,eAAA,CACA,sDAAA,CAGF,uCACE,iBAAA,CAGF,oCACE,eAAA,CACA,sDAAA","sourcesContent":[".Root {\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 6px;\n  padding: 12px;\n  margin-bottom: 8px;\n  transition: border-color 0.2s ease;\n\n  &:hover {\n    border-color: var(--theme-color-border-hover);\n  }\n\n  &.Active {\n    border-color: var(--theme-color-primary);\n    background-color: var(--theme-color-bg-2);\n  }\n}\n\n.Header {\n  display: flex;\n  justify-content: space-between;\n  align-items: flex-start;\n  margin-bottom: 8px;\n}\n\n.TypeIcon {\n  width: 32px;\n  height: 32px;\n  border-radius: 6px;\n  background-color: var(--theme-color-primary);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  flex-shrink: 0;\n}\n\n.ActiveBadge {\n  background-color: var(--theme-color-primary);\n  color: var(--theme-color-fg-on-primary);\n  padding: 2px 6px;\n  border-radius: 4px;\n  text-transform: uppercase;\n  letter-spacing: 0.5px;\n}\n\n.Status {\n  margin-bottom: 8px;\n  padding-top: 8px;\n  border-top: 1px solid var(--theme-color-border-default);\n}\n\n.SchemaInfo {\n  margin-bottom: 8px;\n}\n\n.Actions {\n  padding-top: 8px;\n  border-top: 1px solid var(--theme-color-border-default);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `BackendCard-module__Root--GDgZ5`,
	"Active": `BackendCard-module__Active--nG2MN`,
	"Header": `BackendCard-module__Header--jafMq`,
	"TypeIcon": `BackendCard-module__TypeIcon--Qn5pY`,
	"ActiveBadge": `BackendCard-module__ActiveBadge--cXxjD`,
	"Status": `BackendCard-module__Status--M75U5`,
	"SchemaInfo": `BackendCard-module__SchemaInfo--QWiPz`,
	"Actions": `BackendCard-module__Actions--PyYTj`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 69856:
/***/ ((module) => {

"use strict";
module.exports = require("jszip");

/***/ }),

/***/ 70441:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _keyboard_KeyCode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7444);
/* harmony import */ var _keyboard_KeyCodeMapper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(45977);


function getKeyMod(evt) {
    let modKey = 0;
    if (evt.metaKey || evt.ctrlKey)
        modKey |= _keyboard_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyMod.CtrlCmd; // | KeyMod.WinCtrl
    if (evt.shiftKey)
        modKey |= _keyboard_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyMod.Shift;
    if (evt.altKey)
        modKey |= _keyboard_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyMod.Alt;
    return modKey;
}
class KeyboardHandler {
    constructor() {
        this.commands = [];
        this.onKeyDown = (event) => {
            if (event.repeat) {
                return;
            }
            const code = getKeyMod(event) + _keyboard_KeyCodeMapper__WEBPACK_IMPORTED_MODULE_1__/* .KeyCodeUtils */ .Y.fromString(event.key);
            const focusedElements = $(':focus');
            if (code === _keyboard_KeyCode__WEBPACK_IMPORTED_MODULE_0__.KeyCode.Escape) {
                if (focusedElements.length > 0) {
                    focusedElements[0].blur();
                    return;
                }
            }
            if (focusedElements.length > 0) {
                //something else has focus, e.g. a text input or similar
                return;
            }
            this.executeCommandMatchingKeyEvent(event, 'down');
        };
        this.onKeyUp = (event) => {
            if (event.repeat) {
                return;
            }
            if ($(':focus').length > 0)
                return; // Only do this if no other element is currently focused
            this.executeCommandMatchingKeyEvent(event, 'up');
        };
        this.onMouseUp = (event) => {
            switch (event.button) {
                case 0:
                    // Left button
                    break;
                case 1:
                    // Middle button
                    break;
                case 2:
                    // Right button
                    break;
                case 3:
                    // Back button
                    break;
                case 4:
                    // Forward button
                    break;
            }
        };
        document.addEventListener('keydown', this.onKeyDown);
        document.addEventListener('keyup', this.onKeyUp);
        document.addEventListener('mouseup', this.onMouseUp);
    }
    dispose() {
        document.removeEventListener('keydown', this.onKeyDown);
        document.removeEventListener('keyup', this.onKeyUp);
        document.removeEventListener('mouseup', this.onMouseUp);
    }
    executeCommandMatchingKeyEvent(event, type) {
        const code = getKeyMod(event) + _keyboard_KeyCodeMapper__WEBPACK_IMPORTED_MODULE_1__/* .KeyCodeUtils */ .Y.fromString(event.key);
        const command = this.findCommand(code, type);
        command === null || command === void 0 ? void 0 : command.handler();
    }
    findCommand(code, type) {
        const matchingCommands = this.commands.filter((c) => c.keybinding === code && (c.type || 'down') === type);
        if (matchingCommands.length === 0) {
            return null;
        }
        return matchingCommands.reduce((prev, curr) => (prev.weight < curr.weight ? prev : curr));
    }
    registerCommands(commands) {
        commands.forEach((c) => this.commands.push(c));
    }
    deregisterCommands(commands) {
        commands.forEach((c) => this.deregisterCommand(c));
    }
    deregisterCommand(command) {
        const index = this.commands.indexOf(command);
        if (index !== -1) {
            this.commands.splice(index, 1);
        }
        else {
            console.error("KeyboardHandler: Trying to deregister a command that's not registered");
        }
    }
}
KeyboardHandler.instance = new KeyboardHandler();
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (KeyboardHandler);


/***/ }),

/***/ 70533:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `:root {
  --font-family: 'Inter';
  --font-family-regular: 'Inter-Regular';
  --font-family-bold: 'Inter-Bold';
  --font-family-light: 'Inter-Light';
  --font-family-semibold: 'Inter-SemiBold';

  --font-family-code: Menlo, Monaco, 'Courier New', monospace;

  --font-weight-light: 200;
  --font-weight-regular: 400;
  --font-weight-medium: 500;
  --font-weight-semibold: 600;
  --font-weight-bold: 700;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/custom-properties/fonts.css"],"names":[],"mappings":"AAAA;EACE,sBAAsB;EACtB,sCAAsC;EACtC,gCAAgC;EAChC,kCAAkC;EAClC,wCAAwC;;EAExC,2DAA2D;;EAE3D,wBAAwB;EACxB,0BAA0B;EAC1B,yBAAyB;EACzB,2BAA2B;EAC3B,uBAAuB;AACzB","sourcesContent":[":root {\n  --font-family: 'Inter';\n  --font-family-regular: 'Inter-Regular';\n  --font-family-bold: 'Inter-Bold';\n  --font-family-light: 'Inter-Light';\n  --font-family-semibold: 'Inter-SemiBold';\n\n  --font-family-code: Menlo, Monaco, 'Courier New', monospace;\n\n  --font-weight-light: 200;\n  --font-weight-regular: 400;\n  --font-weight-medium: 500;\n  --font-weight-semibold: 600;\n  --font-weight-bold: 700;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 70537:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgComponents = function SvgComponents(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 25,
    viewBox: "0 0 24 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.75 5.41052C3.75 4.99631 4.08579 4.66052 4.5 4.66052H10.5C10.9142 4.66052 11.25 4.99631 11.25 5.41052V11.4105C11.25 11.8247 10.9142 12.1605 10.5 12.1605H4.5C4.08579 12.1605 3.75 11.8247 3.75 11.4105V5.41052ZM5.25 6.16052V10.6605H9.75V6.16052H5.25Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.75 5.41052C12.75 4.99631 13.0858 4.66052 13.5 4.66052H19.5C19.9142 4.66052 20.25 4.99631 20.25 5.41052V11.4105C20.25 11.8247 19.9142 12.1605 19.5 12.1605H13.5C13.0858 12.1605 12.75 11.8247 12.75 11.4105V5.41052ZM14.25 6.16052V10.6605H18.75V6.16052H14.25Z",
    fill: "#B8B8B8"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.75 14.4105C3.75 13.9963 4.08579 13.6605 4.5 13.6605H10.5C10.9142 13.6605 11.25 13.9963 11.25 14.4105V20.4105C11.25 20.8247 10.9142 21.1605 10.5 21.1605H4.5C4.08579 21.1605 3.75 20.8247 3.75 20.4105V14.4105ZM5.25 15.1605V19.6605H9.75V15.1605H5.25Z",
    fill: "#B8B8B8"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.75 14.4105C12.75 13.9963 13.0858 13.6605 13.5 13.6605H19.5C19.9142 13.6605 20.25 13.9963 20.25 14.4105V20.4105C20.25 20.8247 19.9142 21.1605 19.5 21.1605H13.5C13.0858 21.1605 12.75 20.8247 12.75 20.4105V14.4105ZM14.25 15.1605V19.6605H18.75V15.1605H14.25Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgComponents);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "7182466a414e4eefc27d8ab625ef3140.svg");

/***/ }),

/***/ 70567:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.FolderTree-module__Root--mqqOy{display:flex;flex-direction:column;gap:var(--spacing-2);padding:var(--spacing-2);height:100%}.FolderTree-module__VirtualFolders--RQlxj{display:flex;flex-direction:column;gap:var(--spacing-1)}.FolderTree-module__Divider--QfLac{height:1px;background-color:var(--theme-color-border-default);margin:var(--spacing-2) 0}.FolderTree-module__UserFolders--gMG4W{display:flex;flex-direction:column;gap:var(--spacing-1);flex:1;overflow-y:auto}.FolderTree-module__RenameInput--lK1he{padding:var(--spacing-1) var(--spacing-2)}.FolderTree-module__RenameInputField--BoTyz{width:100%;padding:var(--spacing-2);background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:var(--radius-default);color:var(--theme-color-fg-default);font-size:var(--theme-font-size-default);outline:none}.FolderTree-module__RenameInputField--BoTyz:focus{border-color:var(--theme-color-primary)}.FolderTree-module__NewFolderButton--B2MPm{display:flex;align-items:center;gap:var(--spacing-2);padding:var(--spacing-2) var(--spacing-3);margin-bottom:var(--spacing-4);background:none;border:1px dashed var(--theme-color-border-default);border-radius:var(--radius-default);color:var(--theme-color-fg-default-shy);cursor:pointer;transition:all .15s ease;font-size:var(--theme-font-size-default)}.FolderTree-module__NewFolderButton--B2MPm:hover{background-color:var(--theme-color-bg-3);border-color:var(--theme-color-border-highlight);color:var(--theme-color-fg-default)}.FolderTree-module__NewFolderButton--B2MPm:active{background-color:var(--theme-color-bg-4)}.FolderTree-module__NewFolderIcon--r9qrC{display:flex;flex-shrink:0}.FolderTree-module__NewFolderLabel--IE8ZE{flex:1;text-align:left}.FolderTree-module__CreateFolderInput--FAX4K{padding:var(--spacing-1) var(--spacing-2)}.FolderTree-module__CreateFolderInputField--e1Gy6{width:100%;padding:var(--spacing-2);background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-primary);border-radius:var(--radius-default);color:var(--theme-color-fg-default);font-size:var(--theme-font-size-default);outline:none}.FolderTree-module__CreateFolderInputField--e1Gy6::placeholder{color:var(--theme-color-fg-default-shy)}.FolderTree-module__DeleteConfirmation--B6QK4{position:fixed;top:0;left:0;right:0;bottom:0;display:flex;align-items:center;justify-content:center;z-index:1000}.FolderTree-module__DeleteConfirmationBackdrop--c4B3q{position:absolute;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,.5)}.FolderTree-module__DeleteConfirmationDialog--N5SCJ{position:relative;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:var(--radius-lg);padding:var(--spacing-6);min-width:400px;max-width:500px;box-shadow:0 8px 32px rgba(0,0,0,.3);z-index:1001}.FolderTree-module__DeleteConfirmationTitle--u6fMO{font-size:20px;font-weight:600;color:var(--theme-color-fg-default);margin:0 0 var(--spacing-3) 0;line-height:1.3}.FolderTree-module__DeleteConfirmationMessage--u4YoV{font-size:var(--theme-font-size-default);color:var(--theme-color-fg-default);margin-bottom:var(--spacing-6);line-height:1.5}.FolderTree-module__DeleteConfirmationButtons--s4nay{display:flex;gap:var(--spacing-3);justify-content:flex-end}.FolderTree-module__DeleteConfirmationCancelButton--ZL6u9{padding:var(--spacing-2) var(--spacing-4);background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:var(--radius-default);color:var(--theme-color-fg-default);font-size:var(--theme-font-size-default);cursor:pointer;transition:all .15s ease}.FolderTree-module__DeleteConfirmationCancelButton--ZL6u9:hover{background-color:var(--theme-color-bg-4);border-color:var(--theme-color-border-highlight)}.FolderTree-module__DeleteConfirmationCancelButton--ZL6u9:active{transform:scale(0.98)}.FolderTree-module__DeleteConfirmationDeleteButton--W_VyW{padding:var(--spacing-2) var(--spacing-4);background-color:var(--theme-color-danger);border:1px solid var(--theme-color-danger);border-radius:var(--radius-default);color:#fff;font-size:var(--theme-font-size-default);font-weight:var(--theme-font-weight-medium);cursor:pointer;transition:all .15s ease}.FolderTree-module__DeleteConfirmationDeleteButton--W_VyW:hover{background-color:var(--theme-color-danger-hover);border-color:var(--theme-color-danger-hover)}.FolderTree-module__DeleteConfirmationDeleteButton--W_VyW:active{transform:scale(0.98)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/preview/launcher/Launcher/components/FolderTree/FolderTree.module.scss"],"names":[],"mappings":"AAIA,gCACE,YAAA,CACA,qBAAA,CACA,oBAAA,CACA,wBAAA,CACA,WAAA,CAGF,0CACE,YAAA,CACA,qBAAA,CACA,oBAAA,CAGF,mCACE,UAAA,CACA,kDAAA,CACA,yBAAA,CAGF,uCACE,YAAA,CACA,qBAAA,CACA,oBAAA,CACA,MAAA,CACA,eAAA,CAGF,uCACE,yCAAA,CAGF,4CACE,UAAA,CACA,wBAAA,CACA,wCAAA,CACA,kDAAA,CACA,mCAAA,CACA,mCAAA,CACA,wCAAA,CACA,YAAA,CAEA,kDACE,uCAAA,CAIJ,2CACE,YAAA,CACA,kBAAA,CACA,oBAAA,CACA,yCAAA,CACA,8BAAA,CACA,eAAA,CACA,mDAAA,CACA,mCAAA,CACA,uCAAA,CACA,cAAA,CACA,wBAAA,CACA,wCAAA,CAEA,iDACE,wCAAA,CACA,gDAAA,CACA,mCAAA,CAGF,kDACE,wCAAA,CAIJ,yCACE,YAAA,CACA,aAAA,CAGF,0CACE,MAAA,CACA,eAAA,CAGF,6CACE,yCAAA,CAGF,kDACE,UAAA,CACA,wBAAA,CACA,wCAAA,CACA,2CAAA,CACA,mCAAA,CACA,mCAAA,CACA,wCAAA,CACA,YAAA,CAEA,+DACE,uCAAA,CAKJ,8CACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,YAAA,CAGF,sDACE,iBAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,+BAAA,CAGF,oDACE,iBAAA,CACA,wCAAA,CACA,kDAAA,CACA,8BAAA,CACA,wBAAA,CACA,eAAA,CACA,eAAA,CACA,oCAAA,CACA,YAAA,CAGF,mDACE,cAAA,CACA,eAAA,CACA,mCAAA,CACA,6BAAA,CACA,eAAA,CAGF,qDACE,wCAAA,CACA,mCAAA,CACA,8BAAA,CACA,eAAA,CAGF,qDACE,YAAA,CACA,oBAAA,CACA,wBAAA,CAGF,0DACE,yCAAA,CACA,wCAAA,CACA,kDAAA,CACA,mCAAA,CACA,mCAAA,CACA,wCAAA,CACA,cAAA,CACA,wBAAA,CAEA,gEACE,wCAAA,CACA,gDAAA,CAGF,iEACE,qBAAA,CAIJ,0DACE,yCAAA,CACA,0CAAA,CACA,0CAAA,CACA,mCAAA,CACA,UAAA,CACA,wCAAA,CACA,2CAAA,CACA,cAAA,CACA,wBAAA,CAEA,gEACE,gDAAA,CACA,4CAAA,CAGF,iEACE,qBAAA","sourcesContent":["/**\n * FolderTree Styles\n */\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  gap: var(--spacing-2);\n  padding: var(--spacing-2);\n  height: 100%;\n}\n\n.VirtualFolders {\n  display: flex;\n  flex-direction: column;\n  gap: var(--spacing-1);\n}\n\n.Divider {\n  height: 1px;\n  background-color: var(--theme-color-border-default);\n  margin: var(--spacing-2) 0;\n}\n\n.UserFolders {\n  display: flex;\n  flex-direction: column;\n  gap: var(--spacing-1);\n  flex: 1;\n  overflow-y: auto;\n}\n\n.RenameInput {\n  padding: var(--spacing-1) var(--spacing-2);\n}\n\n.RenameInputField {\n  width: 100%;\n  padding: var(--spacing-2);\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: var(--radius-default);\n  color: var(--theme-color-fg-default);\n  font-size: var(--theme-font-size-default);\n  outline: none;\n\n  &:focus {\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.NewFolderButton {\n  display: flex;\n  align-items: center;\n  gap: var(--spacing-2);\n  padding: var(--spacing-2) var(--spacing-3);\n  margin-bottom: var(--spacing-4);\n  background: none;\n  border: 1px dashed var(--theme-color-border-default);\n  border-radius: var(--radius-default);\n  color: var(--theme-color-fg-default-shy);\n  cursor: pointer;\n  transition: all 0.15s ease;\n  font-size: var(--theme-font-size-default);\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n    border-color: var(--theme-color-border-highlight);\n    color: var(--theme-color-fg-default);\n  }\n\n  &:active {\n    background-color: var(--theme-color-bg-4);\n  }\n}\n\n.NewFolderIcon {\n  display: flex;\n  flex-shrink: 0;\n}\n\n.NewFolderLabel {\n  flex: 1;\n  text-align: left;\n}\n\n.CreateFolderInput {\n  padding: var(--spacing-1) var(--spacing-2);\n}\n\n.CreateFolderInputField {\n  width: 100%;\n  padding: var(--spacing-2);\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-primary);\n  border-radius: var(--radius-default);\n  color: var(--theme-color-fg-default);\n  font-size: var(--theme-font-size-default);\n  outline: none;\n\n  &::placeholder {\n    color: var(--theme-color-fg-default-shy);\n  }\n}\n\n/* Delete Confirmation Dialog */\n.DeleteConfirmation {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 1000;\n}\n\n.DeleteConfirmationBackdrop {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.5);\n}\n\n.DeleteConfirmationDialog {\n  position: relative;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: var(--radius-lg);\n  padding: var(--spacing-6);\n  min-width: 400px;\n  max-width: 500px;\n  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);\n  z-index: 1001;\n}\n\n.DeleteConfirmationTitle {\n  font-size: 20px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n  margin: 0 0 var(--spacing-3) 0;\n  line-height: 1.3;\n}\n\n.DeleteConfirmationMessage {\n  font-size: var(--theme-font-size-default);\n  color: var(--theme-color-fg-default);\n  margin-bottom: var(--spacing-6);\n  line-height: 1.5;\n}\n\n.DeleteConfirmationButtons {\n  display: flex;\n  gap: var(--spacing-3);\n  justify-content: flex-end;\n}\n\n.DeleteConfirmationCancelButton {\n  padding: var(--spacing-2) var(--spacing-4);\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: var(--radius-default);\n  color: var(--theme-color-fg-default);\n  font-size: var(--theme-font-size-default);\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    border-color: var(--theme-color-border-highlight);\n  }\n\n  &:active {\n    transform: scale(0.98);\n  }\n}\n\n.DeleteConfirmationDeleteButton {\n  padding: var(--spacing-2) var(--spacing-4);\n  background-color: var(--theme-color-danger);\n  border: 1px solid var(--theme-color-danger);\n  border-radius: var(--radius-default);\n  color: white;\n  font-size: var(--theme-font-size-default);\n  font-weight: var(--theme-font-weight-medium);\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-danger-hover);\n    border-color: var(--theme-color-danger-hover);\n  }\n\n  &:active {\n    transform: scale(0.98);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `FolderTree-module__Root--mqqOy`,
	"VirtualFolders": `FolderTree-module__VirtualFolders--RQlxj`,
	"Divider": `FolderTree-module__Divider--QfLac`,
	"UserFolders": `FolderTree-module__UserFolders--gMG4W`,
	"RenameInput": `FolderTree-module__RenameInput--lK1he`,
	"RenameInputField": `FolderTree-module__RenameInputField--BoTyz`,
	"NewFolderButton": `FolderTree-module__NewFolderButton--B2MPm`,
	"NewFolderIcon": `FolderTree-module__NewFolderIcon--r9qrC`,
	"NewFolderLabel": `FolderTree-module__NewFolderLabel--IE8ZE`,
	"CreateFolderInput": `FolderTree-module__CreateFolderInput--FAX4K`,
	"CreateFolderInputField": `FolderTree-module__CreateFolderInputField--e1Gy6`,
	"DeleteConfirmation": `FolderTree-module__DeleteConfirmation--B6QK4`,
	"DeleteConfirmationBackdrop": `FolderTree-module__DeleteConfirmationBackdrop--c4B3q`,
	"DeleteConfirmationDialog": `FolderTree-module__DeleteConfirmationDialog--N5SCJ`,
	"DeleteConfirmationTitle": `FolderTree-module__DeleteConfirmationTitle--u6fMO`,
	"DeleteConfirmationMessage": `FolderTree-module__DeleteConfirmationMessage--u4YoV`,
	"DeleteConfirmationButtons": `FolderTree-module__DeleteConfirmationButtons--s4nay`,
	"DeleteConfirmationCancelButton": `FolderTree-module__DeleteConfirmationCancelButton--ZL6u9`,
	"DeleteConfirmationDeleteButton": `FolderTree-module__DeleteConfirmationDeleteButton--W_VyW`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 70666:
/***/ ((module) => {

// Module
var code = "<div style=\"position:relative;display:flex\"> <span data-class=\"isDefault:hidden\" class=\"property-changed-dot\"></span> <div style=\"display:flex;position:relative;flex:1;padding-top:4px;padding-bottom:4px;margin-left:20px;align-items:center;justify-content:center\"> <div class=\"align-icon\" data-tooltip=\"Vertical align bottom\" data-comp=\"vertical\" data-value=\"bottom\"> <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"white\" width=\"25px\" height=\"25px\"> <path d=\"M16 13h-3V3h-2v10H8l4 4 4-4zM4 19v2h16v-2H4z\"/></svg> </div> <div class=\"align-icon\" data-tooltip=\"Vertical align center\" data-comp=\"vertical\" data-value=\"center\"> <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"white\" width=\"25px\" height=\"25px\"> <path d=\"M8 19h3v4h2v-4h3l-4-4-4 4zm8-14h-3V1h-2v4H8l4 4 4-4zM4 11v2h16v-2H4z\"/></svg> </div> <div class=\"align-icon\" data-tooltip=\"Vertical align top\" data-comp=\"vertical\" data-value=\"top\"> <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"white\" width=\"25px\" height=\"25px\"> <path d=\"M8 11h3v10h2V11h3l-4-4-4 4zM4 3v2h16V3H4z\"/></svg> </div> <div class=\"align-icon\" data-tooltip=\"Horizontal align left\" data-comp=\"horizontal\" data-value=\"left\"> <svg xmlns=\"http://www.w3.org/2000/svg\" transform=\"rotate(90)\" viewBox=\"0 0 24 24\" fill=\"white\" width=\"25px\" height=\"25px\"> <path d=\"M16 13h-3V3h-2v10H8l4 4 4-4zM4 19v2h16v-2H4z\"/></svg> </div> <div class=\"align-icon\" data-tooltip=\"Horizontal align center\" data-comp=\"horizontal\" data-value=\"center\"> <svg xmlns=\"http://www.w3.org/2000/svg\" transform=\"rotate(90)\" viewBox=\"0 0 24 24\" fill=\"white\" width=\"25px\" height=\"25px\"> <path d=\"M8 19h3v4h2v-4h3l-4-4-4 4zm8-14h-3V1h-2v4H8l4 4 4-4zM4 11v2h16v-2H4z\"/></svg> </div> <div class=\"align-icon\" data-tooltip=\"Horizontal align right\" data-comp=\"horizontal\" data-value=\"right\"> <svg xmlns=\"http://www.w3.org/2000/svg\" transform=\"rotate(90)\" viewBox=\"0 0 24 24\" fill=\"white\" width=\"25px\" height=\"25px\"> <path d=\"M8 11h3v10h2V11h3l-4-4-4 4zM4 3v2h16V3H4z\"/></svg> </div> <div class=\"align-icon\" data-tooltip=\"Justify left\" data-comp=\"justify\" data-value=\"left\"> <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"white\" width=\"25px\" height=\"25px\"><path d=\"M15 15H3v2h12v-2zm0-8H3v2h12V7zM3 13h18v-2H3v2zm0 8h18v-2H3v2zM3 3v2h18V3H3z\"/></svg> </div> <div class=\"align-icon\" data-tooltip=\"Justify center\" data-comp=\"justify\" data-value=\"center\"> <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"white\" width=\"25px\" height=\"25px\"><path d=\"M7 15v2h10v-2H7zm-4 6h18v-2H3v2zm0-8h18v-2H3v2zm4-6v2h10V7H7zM3 3v2h18V3H3z\"/></svg> </div> <div class=\"align-icon\" data-tooltip=\"Justify right\" data-comp=\"justify\" data-value=\"right\"> <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"white\" width=\"25px\" height=\"25px\"><path d=\"M3 21h18v-2H3v2zm6-4h12v-2H9v2zm-6-4h18v-2H3v2zm6-4h12V7H9v2zM3 3v2h18V3H3z\"/></svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate2\" data-tooltip=\"Align items start\" data-comp=\"align-items\" data-value=\"flex-start\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M3 8L3 6L21 6L21 8L3 8Z\" fill-opacity=\"0.5\"/> <rect x=\"7\" y=\"19\" width=\"10\" height=\"4\" transform=\"rotate(-90 7 19)\"/> <rect x=\"13\" y=\"17\" width=\"8\" height=\"4\" transform=\"rotate(-90 13 17)\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate\" data-tooltip=\"Align items center\" data-comp=\"align-items\" data-value=\"center\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M3 13L3 11L21 11L21 13L3 13Z\" fill-opacity=\"0.5\"/> <rect x=\"7\" y=\"17\" width=\"10\" height=\"4\" transform=\"rotate(-90 7 17)\"/> <rect x=\"13\" y=\"16\" width=\"8\" height=\"4\" transform=\"rotate(-90 13 16)\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate2\" data-tooltip=\"Align items end\" data-comp=\"align-items\" data-value=\"flex-end\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M21 16L21 18L3 18L3 16L21 16Z\" fill-opacity=\"0.5\"/> <rect x=\"17\" y=\"5\" width=\"10\" height=\"4\" transform=\"rotate(90 17 5)\"/> <rect x=\"11\" y=\"7\" width=\"8\" height=\"4\" transform=\"rotate(90 11 7)\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate\" data-tooltip=\"Justify content start\" data-comp=\"justify-content\" data-value=\"flex-start\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M3 21L1 21L0.999998 3L3 3L3 21Z\" fill-opacity=\"0.5\"/> <rect x=\"4\" y=\"17\" width=\"10\" height=\"4\" transform=\"rotate(-90 4 17)\"/> <rect x=\"10\" y=\"17\" width=\"10\" height=\"4\" transform=\"rotate(-90 10 17)\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate\" data-tooltip=\"Justify content center\" data-comp=\"justify-content\" data-value=\"center\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M11 3H13V21H11V3Z\" fill-opacity=\"0.5\"/> <rect x=\"19\" y=\"7\" width=\"10\" height=\"4\" transform=\"rotate(90 19 7)\"/> <rect x=\"9\" y=\"7\" width=\"10\" height=\"4\" transform=\"rotate(90 9 7)\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate\" data-tooltip=\"Justify content end\" data-comp=\"justify-content\" data-value=\"flex-end\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M21 3H23V21H21V3Z\" fill-opacity=\"0.5\"/> <rect x=\"20\" y=\"7\" width=\"10\" height=\"4\" transform=\"rotate(90 20 7)\"/> <rect x=\"14\" y=\"7\" width=\"10\" height=\"4\" transform=\"rotate(90 14 7)\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate\" data-tooltip=\"Justify content space between\" data-comp=\"justify-content\" data-value=\"space-between\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M3 21L1 21L0.999998 3L3 3L3 21Z\" fill-opacity=\"0.5\"/> <path d=\"M23 21L21 21L21 3L23 3L23 21Z\" fill-opacity=\"0.5\"/> <rect x=\"4\" y=\"17\" width=\"10\" height=\"4\" transform=\"rotate(-90 4 17)\"/> <rect x=\"16\" y=\"17\" width=\"10\" height=\"4\" transform=\"rotate(-90 16 17)\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate\" data-tooltip=\"Justify content space around\" data-comp=\"justify-content\" data-value=\"space-around\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M3 21L1 21L0.999998 3L3 3L3 21Z\" fill-opacity=\"0.5\"/> <path d=\"M23 21L21 21L21 3L23 3L23 21Z\" fill-opacity=\"0.5\"/> <rect x=\"6\" y=\"17\" width=\"10\" height=\"4\" transform=\"rotate(-90 6 17)\"/> <rect x=\"14\" y=\"17\" width=\"10\" height=\"4\" transform=\"rotate(-90 14 17)\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate\" data-tooltip=\"Justify content space evenly\" data-comp=\"justify-content\" data-value=\"space-evenly\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M3 21L1 21L0.999998 3L3 3L3 21Z\" fill-opacity=\"0.5\"/> <path d=\"M13 21L11 21L11 3L13 3L13 21Z\" fill-opacity=\"0.5\"/> <path d=\"M23 21L21 21L21 3L23 3L23 21Z\" fill-opacity=\"0.5\"/> <rect x=\"5\" y=\"17\" width=\"10\" height=\"4\" transform=\"rotate(-90 5 17)\"/> <rect x=\"15\" y=\"17\" width=\"10\" height=\"4\" transform=\"rotate(-90 15 17)\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate2\" data-tooltip=\"Align content start\" data-comp=\"align-content\" data-value=\"flex-start\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M3 3L3 1L21 0.999999L21 3L3 3Z\" fill-opacity=\"0.5\"/> <rect x=\"7\" y=\"4\" width=\"10\" height=\"4\"/> <rect x=\"7\" y=\"10\" width=\"10\" height=\"4\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate\" data-tooltip=\"Align content center\" data-comp=\"align-content\" data-value=\"center\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M21 11L21 13L3 13L3 11L21 11Z\" fill-opacity=\"0.5\"/> <rect x=\"17\" y=\"19\" width=\"10\" height=\"4\" transform=\"rotate(180 17 19)\"/> <rect x=\"17\" y=\"9\" width=\"10\" height=\"4\" transform=\"rotate(180 17 9)\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate2\" data-tooltip=\"Align content end\" data-comp=\"align-content\" data-value=\"flex-end\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M21 21L21 23L3 23L3 21L21 21Z\" fill-opacity=\"0.5\"/> <rect x=\"17\" y=\"20\" width=\"10\" height=\"4\" transform=\"rotate(180 17 20)\"/> <rect x=\"17\" y=\"14\" width=\"10\" height=\"4\" transform=\"rotate(180 17 14)\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate\" data-tooltip=\"Align content between\" data-comp=\"align-content\" data-value=\"space-between\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M3 3L3 1L21 0.999999L21 3L3 3Z\" fill-opacity=\"0.5\"/> <path d=\"M3 23L3 21L21 21L21 23L3 23Z\" fill-opacity=\"0.5\"/> <rect x=\"7\" y=\"4\" width=\"10\" height=\"4\"/> <rect x=\"7\" y=\"16\" width=\"10\" height=\"4\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate\" data-tooltip=\"Align content around\" data-comp=\"align-content\" data-value=\"space-around\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M3 3L3 1L21 0.999999L21 3L3 3Z\" fill-opacity=\"0.5\"/> <path d=\"M3 13L3 11L21 11L21 13L3 13Z\" fill-opacity=\"0.5\"/> <path d=\"M3 23L3 21L21 21L21 23L3 23Z\" fill-opacity=\"0.5\"/> <rect x=\"7\" y=\"5\" width=\"10\" height=\"4\"/> <rect x=\"7\" y=\"15\" width=\"10\" height=\"4\"/> </svg> </div> <div class=\"align-icon\" data-class=\"isVertical:align-icon-rotate\" data-tooltip=\"Align content evenly\" data-comp=\"align-content\" data-value=\"space-evenly\"> <svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M3 3L3 1L21 0.999999L21 3L3 3Z\" fill-opacity=\"0.5\"/> <path d=\"M3 23L3 21L21 21L21 23L3 23Z\" fill-opacity=\"0.5\"/> <rect x=\"7\" y=\"4\" width=\"10\" height=\"7\"/> <rect x=\"7\" y=\"13\" width=\"10\" height=\"7\"/> </svg> </div> </div> </div> ";
// Exports
module.exports = code;

/***/ }),

/***/ 70857:
/***/ ((module) => {

"use strict";
module.exports = require("os");

/***/ }),

/***/ 70900:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* unused harmony export ReactComponent */
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = (/* unused pure expression or super */ null && (["title", "titleId"]));
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgAiAssistantNodegraphInner = function SvgAiAssistantNodegraphInner(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/React.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/React.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/React.createElement("path", {
    d: "M11.9629 14.689C11.9521 14.6574 11.9227 14.6361 11.8896 14.6361H8.30032C8.26721 14.6361 8.23777 14.6574 8.22704 14.689L7.65067 16.3907C7.63995 16.4224 7.6105 16.4436 7.5774 16.4436H5.78601C5.7325 16.4436 5.69511 16.3901 5.71303 16.3391L8.9986 6.99597C9.00957 6.96476 9.0388 6.94391 9.07158 6.94391H11.1316C11.1644 6.94391 11.1936 6.96476 11.2046 6.99597L14.4902 16.3391C14.5081 16.3901 14.4707 16.4436 14.4172 16.4436H12.6125C12.5794 16.4436 12.55 16.4224 12.5392 16.3907L11.9629 14.689ZM11.3308 13.114C11.3839 13.114 11.4213 13.0611 11.4041 13.0103L10.1682 9.36189C10.1443 9.29132 10.0456 9.29132 10.0217 9.36189L8.78583 13.0103C8.76862 13.0611 8.80597 13.114 8.8591 13.114H11.3308Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/React.createElement("path", {
    d: "M17.5614 6.9575C17.6042 6.9575 17.6389 6.99255 17.6389 7.03578V16.3654C17.6389 16.4086 17.6042 16.4436 17.5614 16.4436H15.8531C15.8103 16.4436 15.7756 16.4086 15.7756 16.3654V7.03578C15.7756 6.99255 15.8103 6.9575 15.8531 6.9575H17.5614Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(/* unused pure expression or super */ null && (forwardRef(SvgAiAssistantNodegraphInner)));

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "ab84baaeb9cb76a45815463d9c6014cf.svg");

/***/ }),

/***/ 70903:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `@keyframes MigratingStep-module__slideInUp--a0lnd{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes MigratingStep-module__shimmer--ht789{0%{background-position:-1000px 0}100%{background-position:1000px 0}}@keyframes MigratingStep-module__budgetPulse--gvezi{0%,100%{box-shadow:0 0 0 0 rgba(251,191,36,.7)}50%{box-shadow:0 0 0 8px rgba(251,191,36,0)}}.MigratingStep-module__Root--ksbbf{display:flex;flex-direction:column;height:100%;gap:20px;animation:MigratingStep-module__slideInUp--a0lnd 300ms ease-out}.MigratingStep-module__Header--pluep{display:flex;align-items:center;gap:16px;margin-bottom:4px}.MigratingStep-module__Header--pluep svg{width:28px;height:28px;color:var(--theme-color-primary);animation:MigratingStep-module__spin--UK2BB 1.5s linear infinite;filter:drop-shadow(0 0 8px rgba(66, 135, 245, 0.3))}.MigratingStep-module__Header--pluep h2{font-size:20px;font-weight:600;color:var(--theme-color-fg-highlight);margin:0}.MigratingStep-module__Header--pluep p{font-size:14px;color:var(--theme-color-fg-default);margin:4px 0 0 0}@keyframes MigratingStep-module__spin--UK2BB{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}.MigratingStep-module__BudgetSection--B5D_M{padding:20px;background:linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);border-radius:12px;border:2px solid var(--theme-color-bg-2);transition:all 300ms ease-in-out}.MigratingStep-module__BudgetSection--B5D_M.MigratingStep-module__is-warning--grqby{border-color:var(--theme-color-warning);animation:MigratingStep-module__budgetPulse--gvezi 2s ease-in-out infinite}.MigratingStep-module__BudgetHeader--irOyJ{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px}.MigratingStep-module__BudgetHeader--irOyJ h3{font-size:14px;font-weight:600;color:var(--theme-color-fg-highlight);margin:0;display:flex;align-items:center;gap:8px}.MigratingStep-module__BudgetHeader--irOyJ h3 svg{width:16px;height:16px;color:var(--theme-color-primary)}.MigratingStep-module__BudgetHeader--irOyJ .MigratingStep-module__BudgetAmount--FDOK5{font-size:18px;font-weight:700;color:var(--theme-color-primary);font-variant-numeric:tabular-nums}.MigratingStep-module__BudgetHeader--irOyJ .MigratingStep-module__BudgetAmount--FDOK5.MigratingStep-module__is-warning--grqby{color:var(--theme-color-warning)}.MigratingStep-module__BudgetBar--aG0d_{height:10px;background-color:var(--theme-color-bg-1);border-radius:5px;overflow:hidden;position:relative;box-shadow:inset 0 1px 3px rgba(0,0,0,.2)}.MigratingStep-module__BudgetBar--aG0d_::after{content:"";position:absolute;top:0;left:0;right:0;height:50%;background:linear-gradient(to bottom, rgba(255, 255, 255, 0.2), transparent);pointer-events:none}.MigratingStep-module__BudgetFill--MrGt1{height:100%;background:linear-gradient(90deg, var(--theme-color-primary) 0%, rgba(66, 135, 245, 0.8) 50%, var(--theme-color-primary) 100%);background-size:200% 100%;border-radius:5px;transition:width 400ms ease-out,background 300ms ease-in-out;animation:MigratingStep-module__shimmer--ht789 2s linear infinite;position:relative}.MigratingStep-module__BudgetFill--MrGt1.MigratingStep-module__is-warning--grqby{background:linear-gradient(90deg, var(--theme-color-warning) 0%, rgba(251, 191, 36, 0.8) 50%, var(--theme-color-warning) 100%);background-size:200% 100%;animation:MigratingStep-module__shimmer--ht789 2s linear infinite}.MigratingStep-module__BudgetFill--MrGt1::after{content:"";position:absolute;top:0;right:0;width:20px;height:100%;background:linear-gradient(to right, transparent, rgba(255, 255, 255, 0.4));border-radius:0 5px 5px 0}.MigratingStep-module__BudgetWarning--mQS5K{display:flex;align-items:center;gap:8px;margin-top:12px;padding:8px 12px;background-color:rgba(251,191,36,.15);border-radius:6px;font-size:12px;color:var(--theme-color-warning)}.MigratingStep-module__BudgetWarning--mQS5K svg{width:14px;height:14px;flex-shrink:0}.MigratingStep-module__ProgressSection--vLJUm{display:flex;flex-direction:column;gap:8px}.MigratingStep-module__ProgressBar--ZwUjb{height:8px;background-color:var(--theme-color-bg-3);border-radius:4px;overflow:hidden}.MigratingStep-module__ProgressFill--LAIWh{height:100%;background-color:var(--theme-color-primary);border-radius:4px;transition:width .3s ease}.MigratingStep-module__CurrentComponent--YbKuZ{display:flex;align-items:center;gap:8px;padding:12px 16px;background-color:var(--theme-color-bg-3);border-radius:8px;border:1px solid var(--theme-color-primary);animation:MigratingStep-module__pulse--Wr2gi 2s ease-in-out infinite}@keyframes MigratingStep-module__pulse--Wr2gi{0%,100%{border-color:var(--theme-color-primary);background-color:var(--theme-color-bg-3)}50%{border-color:rgba(59,130,246,.5);background-color:rgba(59,130,246,.05)}}.MigratingStep-module__LogSection--vsSBc{display:flex;flex-direction:column;gap:8px;max-height:200px;overflow-y:auto}.MigratingStep-module__LogEntries--LpzS3{display:flex;flex-direction:column;gap:4px}.MigratingStep-module__LogEntry--BHoVO{display:flex;align-items:flex-start;gap:8px;padding:8px 12px;background-color:var(--theme-color-bg-3);border-radius:6px;font-size:13px;animation:MigratingStep-module__slideIn--MEVF6 .2s ease}.MigratingStep-module__LogEntry--BHoVO svg{margin-top:2px;flex-shrink:0}.MigratingStep-module__LogEntry--BHoVO.MigratingStep-module__is-info--zUTIu{border-left:3px solid var(--theme-color-secondary-as-fg)}.MigratingStep-module__LogEntry--BHoVO.MigratingStep-module__is-info--zUTIu svg{color:var(--theme-color-secondary-as-fg)}.MigratingStep-module__LogEntry--BHoVO.MigratingStep-module__is-success--mlDYQ{border-left:3px solid var(--theme-color-success)}.MigratingStep-module__LogEntry--BHoVO.MigratingStep-module__is-success--mlDYQ svg{color:var(--theme-color-success)}.MigratingStep-module__LogEntry--BHoVO.MigratingStep-module__is-warning--grqby{border-left:3px solid var(--theme-color-warning)}.MigratingStep-module__LogEntry--BHoVO.MigratingStep-module__is-warning--grqby svg{color:var(--theme-color-warning)}.MigratingStep-module__LogEntry--BHoVO.MigratingStep-module__is-error--n5FMQ{border-left:3px solid var(--theme-color-danger)}.MigratingStep-module__LogEntry--BHoVO.MigratingStep-module__is-error--n5FMQ svg{color:var(--theme-color-danger)}@keyframes MigratingStep-module__slideIn--MEVF6{from{opacity:0;transform:translateX(-8px)}to{opacity:1;transform:translateX(0)}}.MigratingStep-module__LogContent--AdRF6{flex:1;display:flex;flex-wrap:wrap;gap:4px}.MigratingStep-module__DecisionPanel--Ds9b8{display:flex;flex-direction:column;gap:12px;padding:16px;background-color:var(--theme-color-bg-3);border:2px solid var(--theme-color-warning);border-radius:8px;animation:MigratingStep-module__slideDown--iv59i .3s ease}@keyframes MigratingStep-module__slideDown--iv59i{from{opacity:0;transform:translateY(-16px)}to{opacity:1;transform:translateY(0)}}.MigratingStep-module__DecisionHeader--yX80L{display:flex;align-items:center;gap:12px}.MigratingStep-module__DecisionHeader--yX80L svg{color:var(--theme-color-warning);flex-shrink:0}.MigratingStep-module__AttemptHistory--bem3c{display:flex;flex-direction:column;gap:6px;padding:12px;background-color:var(--theme-color-bg-2);border-radius:6px}.MigratingStep-module__AttemptEntry--a9S6v{display:flex;gap:4px;font-size:13px}.MigratingStep-module__DecisionOptions--TwKQU{display:flex;gap:8px;margin-top:8px}.MigratingStep-module__Actions--Nvf3N{display:flex;justify-content:flex-end;gap:8px;padding-top:16px;border-top:1px solid var(--theme-color-bg-2)}.MigratingStep-module__DialogOverlay--ZilU7{position:fixed;top:0;left:0;right:0;bottom:0;display:flex;align-items:center;justify-content:center;background-color:rgba(0,0,0,.6);z-index:1000;animation:MigratingStep-module__fadeIn--qEDHh .2s ease}@keyframes MigratingStep-module__fadeIn--qEDHh{from{opacity:0}to{opacity:1}}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/migration/steps/MigratingStep.module.scss"],"names":[],"mappings":"AAMA,kDACE,KACE,SAAA,CACA,0BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,gDACE,GACE,6BAAA,CAEF,KACE,4BAAA,CAAA,CAIJ,oDACE,QAEE,sCAAA,CAEF,IACE,uCAAA,CAAA,CAIJ,mCACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,QAAA,CACA,+DAAA,CAGF,qCACE,YAAA,CACA,kBAAA,CACA,QAAA,CACA,iBAAA,CAEA,yCACE,UAAA,CACA,WAAA,CACA,gCAAA,CACA,gEAAA,CACA,mDAAA,CAGF,wCACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,QAAA,CAGF,uCACE,cAAA,CACA,mCAAA,CACA,gBAAA,CAIJ,6CACE,KACE,sBAAA,CAEF,GACE,wBAAA,CAAA,CAKJ,4CACE,YAAA,CACA,4FAAA,CACA,kBAAA,CACA,wCAAA,CACA,gCAAA,CAEA,oFACE,uCAAA,CACA,0EAAA,CAIJ,2CACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,kBAAA,CAEA,8CACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,QAAA,CACA,YAAA,CACA,kBAAA,CACA,OAAA,CAEA,kDACE,UAAA,CACA,WAAA,CACA,gCAAA,CAIJ,sFACE,cAAA,CACA,eAAA,CACA,gCAAA,CACA,iCAAA,CAEA,8HACE,gCAAA,CAKN,wCACE,WAAA,CACA,wCAAA,CACA,iBAAA,CACA,eAAA,CACA,iBAAA,CACA,yCAAA,CAEA,+CACE,UAAA,CACA,iBAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,UAAA,CACA,4EAAA,CACA,mBAAA,CAIJ,yCACE,WAAA,CACA,8HAAA,CAMA,yBAAA,CACA,iBAAA,CACA,4DAAA,CACA,iEAAA,CACA,iBAAA,CAEA,iFACE,8HAAA,CAMA,yBAAA,CACA,iEAAA,CAGF,gDACE,UAAA,CACA,iBAAA,CACA,KAAA,CACA,OAAA,CACA,UAAA,CACA,WAAA,CACA,2EAAA,CACA,yBAAA,CAIJ,4CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,eAAA,CACA,gBAAA,CACA,qCAAA,CACA,iBAAA,CACA,cAAA,CACA,gCAAA,CAEA,gDACE,UAAA,CACA,WAAA,CACA,aAAA,CAKJ,8CACE,YAAA,CACA,qBAAA,CACA,OAAA,CAGF,0CACE,UAAA,CACA,wCAAA,CACA,iBAAA,CACA,eAAA,CAGF,2CACE,WAAA,CACA,2CAAA,CACA,iBAAA,CACA,yBAAA,CAIF,+CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,iBAAA,CACA,wCAAA,CACA,iBAAA,CACA,2CAAA,CACA,oEAAA,CAGF,8CACE,QAEE,uCAAA,CACA,wCAAA,CAEF,IACE,gCAAA,CACA,qCAAA,CAAA,CAKJ,yCACE,YAAA,CACA,qBAAA,CACA,OAAA,CACA,gBAAA,CACA,eAAA,CAGF,yCACE,YAAA,CACA,qBAAA,CACA,OAAA,CAGF,uCACE,YAAA,CACA,sBAAA,CACA,OAAA,CACA,gBAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,uDAAA,CAEA,2CACE,cAAA,CACA,aAAA,CAGF,4EACE,wDAAA,CAEA,gFACE,wCAAA,CAIJ,+EACE,gDAAA,CAEA,mFACE,gCAAA,CAIJ,+EACE,gDAAA,CAEA,mFACE,gCAAA,CAIJ,6EACE,+CAAA,CAEA,iFACE,+BAAA,CAKN,gDACE,KACE,SAAA,CACA,0BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,yCACE,MAAA,CACA,YAAA,CACA,cAAA,CACA,OAAA,CAIF,4CACE,YAAA,CACA,qBAAA,CACA,QAAA,CACA,YAAA,CACA,wCAAA,CACA,2CAAA,CACA,iBAAA,CACA,yDAAA,CAGF,kDACE,KACE,SAAA,CACA,2BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,6CACE,YAAA,CACA,kBAAA,CACA,QAAA,CAEA,iDACE,gCAAA,CACA,aAAA,CAIJ,6CACE,YAAA,CACA,qBAAA,CACA,OAAA,CACA,YAAA,CACA,wCAAA,CACA,iBAAA,CAGF,2CACE,YAAA,CACA,OAAA,CACA,cAAA,CAGF,8CACE,YAAA,CACA,OAAA,CACA,cAAA,CAIF,sCACE,YAAA,CACA,wBAAA,CACA,OAAA,CACA,gBAAA,CACA,4CAAA,CAIF,4CACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,+BAAA,CACA,YAAA,CACA,sDAAA,CAGF,+CACE,KACE,SAAA,CAEF,GACE,SAAA,CAAA","sourcesContent":["/**\n * MigratingStep Styles\n *\n * Enhanced AI-assisted migration progress display with beautiful budget tracking and decision panels.\n */\n\n@keyframes slideInUp {\n  from {\n    opacity: 0;\n    transform: translateY(10px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n@keyframes shimmer {\n  0% {\n    background-position: -1000px 0;\n  }\n  100% {\n    background-position: 1000px 0;\n  }\n}\n\n@keyframes budgetPulse {\n  0%,\n  100% {\n    box-shadow: 0 0 0 0 rgba(251, 191, 36, 0.7);\n  }\n  50% {\n    box-shadow: 0 0 0 8px rgba(251, 191, 36, 0);\n  }\n}\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  gap: 20px;\n  animation: slideInUp 300ms ease-out;\n}\n\n.Header {\n  display: flex;\n  align-items: center;\n  gap: 16px;\n  margin-bottom: 4px;\n\n  svg {\n    width: 28px;\n    height: 28px;\n    color: var(--theme-color-primary);\n    animation: spin 1.5s linear infinite;\n    filter: drop-shadow(0 0 8px rgba(66, 135, 245, 0.3));\n  }\n\n  h2 {\n    font-size: 20px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    margin: 0;\n  }\n\n  p {\n    font-size: 14px;\n    color: var(--theme-color-fg-default);\n    margin: 4px 0 0 0;\n  }\n}\n\n@keyframes spin {\n  from {\n    transform: rotate(0deg);\n  }\n  to {\n    transform: rotate(360deg);\n  }\n}\n\n/* Budget Section */\n.BudgetSection {\n  padding: 20px;\n  background: linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);\n  border-radius: 12px;\n  border: 2px solid var(--theme-color-bg-2);\n  transition: all 300ms ease-in-out;\n\n  &.is-warning {\n    border-color: var(--theme-color-warning);\n    animation: budgetPulse 2s ease-in-out infinite;\n  }\n}\n\n.BudgetHeader {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  margin-bottom: 16px;\n\n  h3 {\n    font-size: 14px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    margin: 0;\n    display: flex;\n    align-items: center;\n    gap: 8px;\n\n    svg {\n      width: 16px;\n      height: 16px;\n      color: var(--theme-color-primary);\n    }\n  }\n\n  .BudgetAmount {\n    font-size: 18px;\n    font-weight: 700;\n    color: var(--theme-color-primary);\n    font-variant-numeric: tabular-nums;\n\n    &.is-warning {\n      color: var(--theme-color-warning);\n    }\n  }\n}\n\n.BudgetBar {\n  height: 10px;\n  background-color: var(--theme-color-bg-1);\n  border-radius: 5px;\n  overflow: hidden;\n  position: relative;\n  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2);\n\n  &::after {\n    content: '';\n    position: absolute;\n    top: 0;\n    left: 0;\n    right: 0;\n    height: 50%;\n    background: linear-gradient(to bottom, rgba(255, 255, 255, 0.2), transparent);\n    pointer-events: none;\n  }\n}\n\n.BudgetFill {\n  height: 100%;\n  background: linear-gradient(\n    90deg,\n    var(--theme-color-primary) 0%,\n    rgba(66, 135, 245, 0.8) 50%,\n    var(--theme-color-primary) 100%\n  );\n  background-size: 200% 100%;\n  border-radius: 5px;\n  transition: width 400ms ease-out, background 300ms ease-in-out;\n  animation: shimmer 2s linear infinite;\n  position: relative;\n\n  &.is-warning {\n    background: linear-gradient(\n      90deg,\n      var(--theme-color-warning) 0%,\n      rgba(251, 191, 36, 0.8) 50%,\n      var(--theme-color-warning) 100%\n    );\n    background-size: 200% 100%;\n    animation: shimmer 2s linear infinite;\n  }\n\n  &::after {\n    content: '';\n    position: absolute;\n    top: 0;\n    right: 0;\n    width: 20px;\n    height: 100%;\n    background: linear-gradient(to right, transparent, rgba(255, 255, 255, 0.4));\n    border-radius: 0 5px 5px 0;\n  }\n}\n\n.BudgetWarning {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin-top: 12px;\n  padding: 8px 12px;\n  background-color: rgba(251, 191, 36, 0.15);\n  border-radius: 6px;\n  font-size: 12px;\n  color: var(--theme-color-warning);\n\n  svg {\n    width: 14px;\n    height: 14px;\n    flex-shrink: 0;\n  }\n}\n\n/* Progress Section */\n.ProgressSection {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n}\n\n.ProgressBar {\n  height: 8px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 4px;\n  overflow: hidden;\n}\n\n.ProgressFill {\n  height: 100%;\n  background-color: var(--theme-color-primary);\n  border-radius: 4px;\n  transition: width 0.3s ease;\n}\n\n/* Current Component */\n.CurrentComponent {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 12px 16px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 8px;\n  border: 1px solid var(--theme-color-primary);\n  animation: pulse 2s ease-in-out infinite;\n}\n\n@keyframes pulse {\n  0%,\n  100% {\n    border-color: var(--theme-color-primary);\n    background-color: var(--theme-color-bg-3);\n  }\n  50% {\n    border-color: rgba(59, 130, 246, 0.5);\n    background-color: rgba(59, 130, 246, 0.05);\n  }\n}\n\n/* Log Section */\n.LogSection {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n  max-height: 200px;\n  overflow-y: auto;\n}\n\n.LogEntries {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n}\n\n.LogEntry {\n  display: flex;\n  align-items: flex-start;\n  gap: 8px;\n  padding: 8px 12px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 6px;\n  font-size: 13px;\n  animation: slideIn 0.2s ease;\n\n  svg {\n    margin-top: 2px;\n    flex-shrink: 0;\n  }\n\n  &.is-info {\n    border-left: 3px solid var(--theme-color-secondary-as-fg);\n\n    svg {\n      color: var(--theme-color-secondary-as-fg);\n    }\n  }\n\n  &.is-success {\n    border-left: 3px solid var(--theme-color-success);\n\n    svg {\n      color: var(--theme-color-success);\n    }\n  }\n\n  &.is-warning {\n    border-left: 3px solid var(--theme-color-warning);\n\n    svg {\n      color: var(--theme-color-warning);\n    }\n  }\n\n  &.is-error {\n    border-left: 3px solid var(--theme-color-danger);\n\n    svg {\n      color: var(--theme-color-danger);\n    }\n  }\n}\n\n@keyframes slideIn {\n  from {\n    opacity: 0;\n    transform: translateX(-8px);\n  }\n  to {\n    opacity: 1;\n    transform: translateX(0);\n  }\n}\n\n.LogContent {\n  flex: 1;\n  display: flex;\n  flex-wrap: wrap;\n  gap: 4px;\n}\n\n/* AI Decision Panel */\n.DecisionPanel {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n  padding: 16px;\n  background-color: var(--theme-color-bg-3);\n  border: 2px solid var(--theme-color-warning);\n  border-radius: 8px;\n  animation: slideDown 0.3s ease;\n}\n\n@keyframes slideDown {\n  from {\n    opacity: 0;\n    transform: translateY(-16px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n.DecisionHeader {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n\n  svg {\n    color: var(--theme-color-warning);\n    flex-shrink: 0;\n  }\n}\n\n.AttemptHistory {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n  padding: 12px;\n  background-color: var(--theme-color-bg-2);\n  border-radius: 6px;\n}\n\n.AttemptEntry {\n  display: flex;\n  gap: 4px;\n  font-size: 13px;\n}\n\n.DecisionOptions {\n  display: flex;\n  gap: 8px;\n  margin-top: 8px;\n}\n\n/* Actions */\n.Actions {\n  display: flex;\n  justify-content: flex-end;\n  gap: 8px;\n  padding-top: 16px;\n  border-top: 1px solid var(--theme-color-bg-2);\n}\n\n/* Dialog Overlay */\n.DialogOverlay {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  background-color: rgba(0, 0, 0, 0.6);\n  z-index: 1000;\n  animation: fadeIn 0.2s ease;\n}\n\n@keyframes fadeIn {\n  from {\n    opacity: 0;\n  }\n  to {\n    opacity: 1;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `MigratingStep-module__Root--ksbbf`,
	"slideInUp": `MigratingStep-module__slideInUp--a0lnd`,
	"Header": `MigratingStep-module__Header--pluep`,
	"spin": `MigratingStep-module__spin--UK2BB`,
	"BudgetSection": `MigratingStep-module__BudgetSection--B5D_M`,
	"is-warning": `MigratingStep-module__is-warning--grqby`,
	"budgetPulse": `MigratingStep-module__budgetPulse--gvezi`,
	"BudgetHeader": `MigratingStep-module__BudgetHeader--irOyJ`,
	"BudgetAmount": `MigratingStep-module__BudgetAmount--FDOK5`,
	"BudgetBar": `MigratingStep-module__BudgetBar--aG0d_`,
	"BudgetFill": `MigratingStep-module__BudgetFill--MrGt1`,
	"shimmer": `MigratingStep-module__shimmer--ht789`,
	"BudgetWarning": `MigratingStep-module__BudgetWarning--mQS5K`,
	"ProgressSection": `MigratingStep-module__ProgressSection--vLJUm`,
	"ProgressBar": `MigratingStep-module__ProgressBar--ZwUjb`,
	"ProgressFill": `MigratingStep-module__ProgressFill--LAIWh`,
	"CurrentComponent": `MigratingStep-module__CurrentComponent--YbKuZ`,
	"pulse": `MigratingStep-module__pulse--Wr2gi`,
	"LogSection": `MigratingStep-module__LogSection--vsSBc`,
	"LogEntries": `MigratingStep-module__LogEntries--LpzS3`,
	"LogEntry": `MigratingStep-module__LogEntry--BHoVO`,
	"slideIn": `MigratingStep-module__slideIn--MEVF6`,
	"is-info": `MigratingStep-module__is-info--zUTIu`,
	"is-success": `MigratingStep-module__is-success--mlDYQ`,
	"is-error": `MigratingStep-module__is-error--n5FMQ`,
	"LogContent": `MigratingStep-module__LogContent--AdRF6`,
	"DecisionPanel": `MigratingStep-module__DecisionPanel--Ds9b8`,
	"slideDown": `MigratingStep-module__slideDown--iv59i`,
	"DecisionHeader": `MigratingStep-module__DecisionHeader--yX80L`,
	"AttemptHistory": `MigratingStep-module__AttemptHistory--bem3c`,
	"AttemptEntry": `MigratingStep-module__AttemptEntry--a9S6v`,
	"DecisionOptions": `MigratingStep-module__DecisionOptions--TwKQU`,
	"Actions": `MigratingStep-module__Actions--Nvf3N`,
	"DialogOverlay": `MigratingStep-module__DialogOverlay--ZilU7`,
	"fadeIn": `MigratingStep-module__fadeIn--qEDHh`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 70914:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .unicode-highlight {
	border: 1px solid var(--vscode-editorUnicodeHighlight-border);
	background-color: var(--vscode-editorUnicodeHighlight-background);
	box-sizing: border-box;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/unicodeHighlighter/browser/unicodeHighlighter.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,6DAA6D;CAC7D,iEAAiE;CACjE,sBAAsB;AACvB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .unicode-highlight {\n\tborder: 1px solid var(--vscode-editorUnicodeHighlight-border);\n\tbackground-color: var(--vscode-editorUnicodeHighlight-background);\n\tbox-sizing: border-box;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 70973:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var _Stream_client;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Stream = void 0;
exports._iterSSEMessages = _iterSSEMessages;
const tslib_1 = __webpack_require__(84499);
const error_1 = __webpack_require__(37015);
const shims_1 = __webpack_require__(59081);
const line_1 = __webpack_require__(44351);
const shims_2 = __webpack_require__(59081);
const errors_1 = __webpack_require__(29820);
const values_1 = __webpack_require__(25267);
const bytes_1 = __webpack_require__(38870);
const log_1 = __webpack_require__(59347);
const error_2 = __webpack_require__(37015);
class Stream {
    constructor(iterator, controller, client) {
        this.iterator = iterator;
        _Stream_client.set(this, void 0);
        this.controller = controller;
        tslib_1.__classPrivateFieldSet(this, _Stream_client, client, "f");
    }
    static fromSSEResponse(response, controller, client) {
        let consumed = false;
        const logger = client ? (0, log_1.loggerFor)(client) : console;
        async function* iterator() {
            if (consumed) {
                throw new error_1.AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
            }
            consumed = true;
            let done = false;
            try {
                for await (const sse of _iterSSEMessages(response, controller)) {
                    if (sse.event === 'completion') {
                        try {
                            yield JSON.parse(sse.data);
                        }
                        catch (e) {
                            logger.error(`Could not parse message into JSON:`, sse.data);
                            logger.error(`From chunk:`, sse.raw);
                            throw e;
                        }
                    }
                    if (sse.event === 'message_start' ||
                        sse.event === 'message_delta' ||
                        sse.event === 'message_stop' ||
                        sse.event === 'content_block_start' ||
                        sse.event === 'content_block_delta' ||
                        sse.event === 'content_block_stop') {
                        try {
                            yield JSON.parse(sse.data);
                        }
                        catch (e) {
                            logger.error(`Could not parse message into JSON:`, sse.data);
                            logger.error(`From chunk:`, sse.raw);
                            throw e;
                        }
                    }
                    if (sse.event === 'ping') {
                        continue;
                    }
                    if (sse.event === 'error') {
                        throw new error_2.APIError(undefined, (0, values_1.safeJSON)(sse.data) ?? sse.data, undefined, response.headers);
                    }
                }
                done = true;
            }
            catch (e) {
                // If the user calls `stream.controller.abort()`, we should exit without throwing.
                if ((0, errors_1.isAbortError)(e))
                    return;
                throw e;
            }
            finally {
                // If the user `break`s, abort the ongoing request.
                if (!done)
                    controller.abort();
            }
        }
        return new Stream(iterator, controller, client);
    }
    /**
     * Generates a Stream from a newline-separated ReadableStream
     * where each item is a JSON value.
     */
    static fromReadableStream(readableStream, controller, client) {
        let consumed = false;
        async function* iterLines() {
            const lineDecoder = new line_1.LineDecoder();
            const iter = (0, shims_2.ReadableStreamToAsyncIterable)(readableStream);
            for await (const chunk of iter) {
                for (const line of lineDecoder.decode(chunk)) {
                    yield line;
                }
            }
            for (const line of lineDecoder.flush()) {
                yield line;
            }
        }
        async function* iterator() {
            if (consumed) {
                throw new error_1.AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
            }
            consumed = true;
            let done = false;
            try {
                for await (const line of iterLines()) {
                    if (done)
                        continue;
                    if (line)
                        yield JSON.parse(line);
                }
                done = true;
            }
            catch (e) {
                // If the user calls `stream.controller.abort()`, we should exit without throwing.
                if ((0, errors_1.isAbortError)(e))
                    return;
                throw e;
            }
            finally {
                // If the user `break`s, abort the ongoing request.
                if (!done)
                    controller.abort();
            }
        }
        return new Stream(iterator, controller, client);
    }
    [(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() {
        return this.iterator();
    }
    /**
     * Splits the stream into two streams which can be
     * independently read from at different speeds.
     */
    tee() {
        const left = [];
        const right = [];
        const iterator = this.iterator();
        const teeIterator = (queue) => {
            return {
                next: () => {
                    if (queue.length === 0) {
                        const result = iterator.next();
                        left.push(result);
                        right.push(result);
                    }
                    return queue.shift();
                },
            };
        };
        return [
            new Stream(() => teeIterator(left), this.controller, tslib_1.__classPrivateFieldGet(this, _Stream_client, "f")),
            new Stream(() => teeIterator(right), this.controller, tslib_1.__classPrivateFieldGet(this, _Stream_client, "f")),
        ];
    }
    /**
     * Converts this stream to a newline-separated ReadableStream of
     * JSON stringified values in the stream
     * which can be turned back into a Stream with `Stream.fromReadableStream()`.
     */
    toReadableStream() {
        const self = this;
        let iter;
        return (0, shims_1.makeReadableStream)({
            async start() {
                iter = self[Symbol.asyncIterator]();
            },
            async pull(ctrl) {
                try {
                    const { value, done } = await iter.next();
                    if (done)
                        return ctrl.close();
                    const bytes = (0, bytes_1.encodeUTF8)(JSON.stringify(value) + '\n');
                    ctrl.enqueue(bytes);
                }
                catch (err) {
                    ctrl.error(err);
                }
            },
            async cancel() {
                await iter.return?.();
            },
        });
    }
}
exports.Stream = Stream;
async function* _iterSSEMessages(response, controller) {
    if (!response.body) {
        controller.abort();
        if (typeof globalThis.navigator !== 'undefined' &&
            globalThis.navigator.product === 'ReactNative') {
            throw new error_1.AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
        }
        throw new error_1.AnthropicError(`Attempted to iterate over a response with no body`);
    }
    const sseDecoder = new SSEDecoder();
    const lineDecoder = new line_1.LineDecoder();
    const iter = (0, shims_2.ReadableStreamToAsyncIterable)(response.body);
    for await (const sseChunk of iterSSEChunks(iter)) {
        for (const line of lineDecoder.decode(sseChunk)) {
            const sse = sseDecoder.decode(line);
            if (sse)
                yield sse;
        }
    }
    for (const line of lineDecoder.flush()) {
        const sse = sseDecoder.decode(line);
        if (sse)
            yield sse;
    }
}
/**
 * Given an async iterable iterator, iterates over it and yields full
 * SSE chunks, i.e. yields when a double new-line is encountered.
 */
async function* iterSSEChunks(iterator) {
    let data = new Uint8Array();
    for await (const chunk of iterator) {
        if (chunk == null) {
            continue;
        }
        const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
            : typeof chunk === 'string' ? (0, bytes_1.encodeUTF8)(chunk)
                : chunk;
        let newData = new Uint8Array(data.length + binaryChunk.length);
        newData.set(data);
        newData.set(binaryChunk, data.length);
        data = newData;
        let patternIndex;
        while ((patternIndex = (0, line_1.findDoubleNewlineIndex)(data)) !== -1) {
            yield data.slice(0, patternIndex);
            data = data.slice(patternIndex);
        }
    }
    if (data.length > 0) {
        yield data;
    }
}
class SSEDecoder {
    constructor() {
        this.event = null;
        this.data = [];
        this.chunks = [];
    }
    decode(line) {
        if (line.endsWith('\r')) {
            line = line.substring(0, line.length - 1);
        }
        if (!line) {
            // empty line and we didn't previously encounter any messages
            if (!this.event && !this.data.length)
                return null;
            const sse = {
                event: this.event,
                data: this.data.join('\n'),
                raw: this.chunks,
            };
            this.event = null;
            this.data = [];
            this.chunks = [];
            return sse;
        }
        this.chunks.push(line);
        if (line.startsWith(':')) {
            return null;
        }
        let [fieldname, _, value] = partition(line, ':');
        if (value.startsWith(' ')) {
            value = value.substring(1);
        }
        if (fieldname === 'event') {
            this.event = value;
        }
        else if (fieldname === 'data') {
            this.data.push(value);
        }
        return null;
    }
}
function partition(str, delimiter) {
    const index = str.indexOf(delimiter);
    if (index !== -1) {
        return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
    }
    return [str, '', ''];
}
//# sourceMappingURL=streaming.js.map

/***/ }),

/***/ 71101:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.NodePicker-module__Root--DHzep{position:relative;background-color:var(--theme-color-bg-2);width:800px;height:600px;overflow:hidden}.NodePicker-module__Root--DHzep>*{height:100%}.NodePicker-module__ShadowWrapper--HU7TX{position:absolute;inset:0;pointer-events:none;overflow:hidden}.NodePicker-module__Shadow--bZZLf{height:40px;border-radius:100%;position:absolute;left:0;right:0;bottom:-40px;box-shadow:0 0 30px 5px var(--theme-color-bg-2),0 0 40px 0 var(--theme-color-bg-2),0 0 20px 0 var(--theme-color-bg-2);z-index:10;opacity:.8}.NodePicker-module__Blocker--YXPmr{position:absolute;top:0;left:0;right:0;bottom:-10px;background-color:var(--theme-color-bg-2);pointer-events:none;opacity:0;z-index:1;transition:opacity var(--speed-turbo) var(--easing-equal)}.NodePicker-module__Blocker--YXPmr.NodePicker-module__is-visible--G467Q{opacity:.5;pointer-events:all}.NodePicker-module__TabOverride--arLCZ>div{height:555px}.NodePicker-module__TabOverride--arLCZ>div>*{height:100%}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/NodePicker/NodePicker.module.scss"],"names":[],"mappings":"AAEA,gCACE,iBAAA,CACA,wCAAA,CACA,WAAA,CACA,YAAA,CACA,eAAA,CAEA,kCACE,WAAA,CAIJ,yCACE,iBAAA,CACA,OAAA,CACA,mBAAA,CACA,eAAA,CAGF,kCACE,WAAA,CACA,kBAAA,CACA,iBAAA,CACA,MAAA,CACA,OAAA,CACA,YAAA,CACA,qHAAA,CAEA,UAAA,CACA,UAAA,CAGF,mCACE,iBAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,YAAA,CACA,wCAAA,CACA,mBAAA,CACA,SAAA,CACA,SAAA,CACA,yDAAA,CAEA,wEACE,UAAA,CACA,kBAAA,CAKF,2CACE,YAAA,CAEA,6CACE,WAAA","sourcesContent":["@use '@scss-variables/animation';\n\n.Root {\n  position: relative;\n  background-color: var(--theme-color-bg-2);\n  width: 800px;\n  height: 600px;\n  overflow: hidden;\n\n  > * {\n    height: 100%;\n  }\n}\n\n.ShadowWrapper {\n  position: absolute;\n  inset: 0;\n  pointer-events: none;\n  overflow: hidden;\n}\n\n.Shadow {\n  height: 40px;\n  border-radius: 100%;\n  position: absolute;\n  left: 0;\n  right: 0;\n  bottom: -40px;\n  box-shadow: 0 0 30px 5px var(--theme-color-bg-2), 0 0 40px 0 var(--theme-color-bg-2),\n    0 0 20px 0 var(--theme-color-bg-2);\n  z-index: 10;\n  opacity: 0.8;\n}\n\n.Blocker {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: -10px;\n  background-color: var(--theme-color-bg-2);\n  pointer-events: none;\n  opacity: 0;\n  z-index: 1;\n  transition: opacity animation.$speed-turbo animation.$easing-equal;\n\n  &.is-visible {\n    opacity: 0.5;\n    pointer-events: all;\n  }\n}\n\n.TabOverride {\n  > div {\n    height: 555px; //yeah, this is a hack\n\n    > * {\n      height: 100%;\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `NodePicker-module__Root--DHzep`,
	"ShadowWrapper": `NodePicker-module__ShadowWrapper--HU7TX`,
	"Shadow": `NodePicker-module__Shadow--bZZLf`,
	"Blocker": `NodePicker-module__Blocker--YXPmr`,
	"is-visible": `NodePicker-module__is-visible--G467Q`,
	"TabOverride": `NodePicker-module__TabOverride--arLCZ`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 71217:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ModuleCard-module__Root--pnPcx{display:flex;flex-direction:column;height:100%;overflow:hidden}.ModuleCard-module__ImageContainer--LGtCA{flex-grow:0;flex-shrink:0;position:relative;background-color:var(--theme-color-fg-highlight)}.ModuleCard-module__ImageContainer--LGtCA::after{content:"";display:block;height:0;padding-bottom:56.4971751412%}.ModuleCard-module__Image--u_1W1{background-position:center;position:absolute;background-repeat:no-repeat;background-size:cover;top:0;bottom:0;left:0;right:0}.ModuleCard-module__TagContainer--PXSzO{display:block;color:var(--theme-color-secondary-highlight);font-weight:600;text-align:right;padding-top:5px}.ModuleCard-module__Content--VOJUw{position:relative;background-color:var(--theme-color-bg-1);flex-grow:1;display:flex;flex-direction:column;justify-content:space-between;padding:12px}.ModuleCard-module__HoverOverlay--Ucug9,.ModuleCard-module__ImportIndicator--PQvcK,.ModuleCard-module__SuccessToast--XPyJs,.ModuleCard-module__CancelToast--S5Vr5{position:absolute;top:0;left:0;bottom:0;right:0;background-color:var(--theme-color-bg-1);display:flex;align-items:center;justify-content:center;opacity:0;transition:opacity var(--speed-quick) var(--easing-base)}.ModuleCard-module__Root--pnPcx:hover .ModuleCard-module__HoverOverlay--Ucug9,.ModuleCard-module__Root--pnPcx.ModuleCard-module__is-downloading--ZQYAa .ModuleCard-module__HoverOverlay--Ucug9{opacity:1}.ModuleCard-module__CtaContainer--NU5rX{display:flex;width:calc(100% - 12px);margin-left:-12px;padding:24px;transition:transform var(--speed-quick) var(--easing-base),opacity var(--speed-quick) var(--easing-base) var(--speed-quick);transform:translateY(10px);opacity:1}.ModuleCard-module__Root--pnPcx:hover .ModuleCard-module__CtaContainer--NU5rX{transform:translateY(0)}.ModuleCard-module__Root--pnPcx.ModuleCard-module__is-downloading--ZQYAa .ModuleCard-module__CtaContainer--NU5rX{transition:opacity var(--speed-quick) var(--easing-base);opacity:0;transform:translateY(0);pointer-events:none}.ModuleCard-module__CtaContainer--NU5rX>*{width:50%}.ModuleCard-module__ImportIndicator--PQvcK{pointer-events:none;flex-direction:column}.ModuleCard-module__Root--pnPcx.ModuleCard-module__is-downloading--ZQYAa .ModuleCard-module__ImportIndicator--PQvcK{opacity:1}.ModuleCard-module__SuccessToast--XPyJs{padding:12px;pointer-events:none;flex-direction:column}.ModuleCard-module__Root--pnPcx.ModuleCard-module__is-finished--bGXNl .ModuleCard-module__SuccessToast--XPyJs{opacity:1}.ModuleCard-module__CancelToast--S5Vr5{pointer-events:none}.ModuleCard-module__Root--pnPcx.ModuleCard-module__is-cancelled--sUZGN .ModuleCard-module__CancelToast--S5Vr5{opacity:1}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/NodePicker/components/ModuleCard/ModuleCard.module.scss","webpack://./src/editor/src/styles/mixins/layout.scss"],"names":[],"mappings":"AAGA,gCACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,eAAA,CAGF,0CACE,WAAA,CACA,aAAA,CACA,iBAAA,CACA,gDAAA,CCmHA,iDAEI,UAAA,CAEF,aAAA,CACA,QAAA,CACA,6BAAA,CDrHJ,iCACE,0BAAA,CACA,iBAAA,CACA,2BAAA,CACA,qBAAA,CACA,KAAA,CACA,QAAA,CACA,MAAA,CACA,OAAA,CAGF,wCACE,aAAA,CACA,4CAAA,CACA,eAAA,CACA,gBAAA,CACA,eAAA,CAGF,mCACE,iBAAA,CACA,wCAAA,CACA,WAAA,CACA,YAAA,CACA,qBAAA,CACA,6BAAA,CACA,YAAA,CAGF,kKAIE,iBAAA,CACA,KAAA,CACA,MAAA,CACA,QAAA,CACA,OAAA,CACA,wCAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,SAAA,CACA,wDAAA,CAIA,+LAEE,SAAA,CAIJ,wCACE,YAAA,CACA,uBAAA,CACA,iBAAA,CACA,YAAA,CACA,2HAAA,CAEA,0BAAA,CACA,SAAA,CAEA,8EACE,uBAAA,CAGF,iHACE,wDAAA,CACA,SAAA,CACA,uBAAA,CACA,mBAAA,CAGF,0CACE,SAAA,CAIJ,2CACE,mBAAA,CACA,qBAAA,CAEA,oHACE,SAAA,CAIJ,wCACE,YAAA,CACA,mBAAA,CACA,qBAAA,CAEA,8GACE,SAAA,CAIJ,uCACE,mBAAA,CAEA,8GACE,SAAA","sourcesContent":["@use '@scss-variables/animation';\n@use '@scss-mixins/layout' as *;\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  overflow: hidden;\n}\n\n.ImageContainer {\n  flex-grow: 0;\n  flex-shrink: 0;\n  position: relative;\n  background-color: var(--theme-color-fg-highlight);\n  @include aspect-ratio(354, 200);\n}\n\n.Image {\n  background-position: center;\n  position: absolute;\n  background-repeat: no-repeat;\n  background-size: cover;\n  top: 0;\n  bottom: 0;\n  left: 0;\n  right: 0;\n}\n\n.TagContainer {\n  display: block;\n  color: var(--theme-color-secondary-highlight);\n  font-weight: 600;\n  text-align: right;\n  padding-top: 5px;\n}\n\n.Content {\n  position: relative;\n  background-color: var(--theme-color-bg-1);\n  flex-grow: 1;\n  display: flex;\n  flex-direction: column;\n  justify-content: space-between;\n  padding: 12px;\n}\n\n.HoverOverlay,\n.ImportIndicator,\n.SuccessToast,\n.CancelToast {\n  position: absolute;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n  background-color: var(--theme-color-bg-1);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  opacity: 0;\n  transition: opacity animation.$speed-quick animation.$easing-base;\n}\n\n.HoverOverlay {\n  .Root:hover &,\n  .Root.is-downloading & {\n    opacity: 1;\n  }\n}\n\n.CtaContainer {\n  display: flex;\n  width: calc(100% - 12px);\n  margin-left: -12px;\n  padding: 24px;\n  transition: transform animation.$speed-quick animation.$easing-base,\n    opacity animation.$speed-quick animation.$easing-base animation.$speed-quick;\n  transform: translateY(10px);\n  opacity: 1;\n\n  .Root:hover & {\n    transform: translateY(0);\n  }\n\n  .Root.is-downloading & {\n    transition: opacity animation.$speed-quick animation.$easing-base;\n    opacity: 0;\n    transform: translateY(0);\n    pointer-events: none;\n  }\n\n  > * {\n    width: 50%;\n  }\n}\n\n.ImportIndicator {\n  pointer-events: none;\n  flex-direction: column;\n\n  .Root.is-downloading & {\n    opacity: 1;\n  }\n}\n\n.SuccessToast {\n  padding: 12px;\n  pointer-events: none;\n  flex-direction: column;\n\n  .Root.is-finished & {\n    opacity: 1;\n  }\n}\n\n.CancelToast {\n  pointer-events: none;\n\n  .Root.is-cancelled & {\n    opacity: 1;\n  }\n}\n","@function _format-gutters($value, $direction) {\n  $vertical-gutter: false;\n  $horizontal-gutter: false;\n\n  @if (type-of($value) == list) {\n    @if (nth($value, 1)) {\n      $vertical-gutter: (nth($value, 1));\n    }\n    @if (nth($value, 2)) {\n      $horizontal-gutter: (nth($value, 2));\n    }\n  } @else {\n    $vertical-gutter: $value;\n    $horizontal-gutter: $value;\n  }\n\n  @if ($direction == vertical) {\n    @return $vertical-gutter;\n  } @else {\n    @return $horizontal-gutter;\n  }\n}\n\n@mixin flex-layout($columns: false, $gutters: 16px) {\n  $items: length($columns);\n\n  @if (type-of($columns) == number) {\n    @include flex-row($gutters);\n\n    > * {\n      @include flex-column(calc(1 / $columns), $gutters);\n    }\n  } @else if (type-of($columns) == list and $items > 1) {\n    $column-count: 0;\n\n    @each $column in $columns {\n      $column-count: $column-count + $column;\n    }\n\n    @include flex-row($gutters);\n\n    @for $item from 1 through $items {\n      $width: nth($columns, $item) / $column-count;\n\n      & > *:nth-child(#{$items}n + #{$item}) {\n        @include flex-column($width, $gutters);\n      }\n    }\n  }\n}\n\n/**\n * flex-row()\n */\n\n@mixin flex-row($gutters) {\n  $horizontal-gutter: _format-gutters($gutters, horizontal);\n  $vertical-gutter: _format-gutters($gutters, vertical);\n\n  display: flex;\n  flex-wrap: wrap;\n\n  @if ($horizontal-gutter and $horizontal-gutter != 0) {\n    margin-left: -($horizontal-gutter);\n  }\n\n  @if ($vertical-gutter and $vertical-gutter != 0) {\n    margin-top: -($vertical-gutter);\n  }\n}\n\n/**\n * flex-column()\n */\n\n@mixin flex-column($width, $gutters) {\n  $horizontal-gutter: _format-gutters($gutters, horizontal);\n  $vertical-gutter: _format-gutters($gutters, vertical);\n\n  @if (type-of($width) == number and unitless($width)) {\n    $width: percentage($width);\n  }\n\n  @if ($horizontal-gutter and $horizontal-gutter != 0) {\n    margin-left: $horizontal-gutter;\n    width: calc(#{$width} - #{$horizontal-gutter});\n  } @else {\n    width: $width;\n  }\n\n  @if ($vertical-gutter and $vertical-gutter != 0) {\n    margin-top: $vertical-gutter;\n  }\n}\n\n@function _get-pseudo($pseudo) {\n  @if ($pseudo == false) {\n    $pseudo: '&::after';\n  } @else if (_contains(('after', ':after', '::after', '&:after', '&::after'), $pseudo)) {\n    $pseudo: '&::after';\n  } @else if (_contains(('before', ':before', '::before', '&:before', '&::before'), $pseudo)) {\n    $pseudo: '&::before';\n  }\n\n  @return $pseudo;\n}\n\n@function _is-pseudo($pseudo) {\n  @return ($pseudo == '&::after' or $pseudo == '&::before');\n}\n\n@function _contains($list, $item) {\n  @return index($list, $item) != null;\n}\n\n/**\n * aspect-ratio()\n *\n * Give a heightless element a height based on its width.\n * Always follows the set width:height ratio.\n *\n * @param {number} $width - Without CSS unit\n * @param {number} $height - Without CSS unit\n * @param {string} $pseudo - Optional selector to use insted of default pseudo-element\n */\n\n@mixin aspect-ratio($width, $height, $pseudo: false) {\n  $pseudo: _get-pseudo($pseudo);\n\n  #{$pseudo} {\n    @if (_is-pseudo($pseudo)) {\n      content: '';\n    }\n    display: block;\n    height: 0;\n    padding-bottom: calc((100% / $width) * $height);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ModuleCard-module__Root--pnPcx`,
	"ImageContainer": `ModuleCard-module__ImageContainer--LGtCA`,
	"Image": `ModuleCard-module__Image--u_1W1`,
	"TagContainer": `ModuleCard-module__TagContainer--PXSzO`,
	"Content": `ModuleCard-module__Content--VOJUw`,
	"HoverOverlay": `ModuleCard-module__HoverOverlay--Ucug9`,
	"ImportIndicator": `ModuleCard-module__ImportIndicator--PQvcK`,
	"SuccessToast": `ModuleCard-module__SuccessToast--XPyJs`,
	"CancelToast": `ModuleCard-module__CancelToast--S5Vr5`,
	"is-downloading": `ModuleCard-module__is-downloading--ZQYAa`,
	"CtaContainer": `ModuleCard-module__CtaContainer--NU5rX`,
	"is-finished": `ModuleCard-module__is-finished--bGXNl`,
	"is-cancelled": `ModuleCard-module__is-cancelled--sUZGN`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 71279:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgMinus = function SvgMinus(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.11182 12C5.11182 11.5858 5.4476 11.25 5.86182 11.25H18.4118C18.826 11.25 19.1618 11.5858 19.1618 12C19.1618 12.4142 18.826 12.75 18.4118 12.75H5.86182C5.4476 12.75 5.11182 12.4142 5.11182 12Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgMinus);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "619cad1527a0a9df7c775b2f84025202.svg");

/***/ }),

/***/ 71287:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   B3: () => (/* binding */ copyDeployFilesToFolder),
/* harmony export */   Pw: () => (/* binding */ getExternalFolderPath),
/* harmony export */   e1: () => (/* binding */ loadDeployIndex)
/* harmony export */ });
/* harmony import */ var _noodl_platform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37218);
/* harmony import */ var _noodl_utils_exporter_hash_xxhash64__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(57603);
/* harmony import */ var _processors_html_processor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(62111);



/**
 * Gives the path to the "external" folder.
 * @returns
 */
function getExternalFolderPath() {
    return _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.join(_noodl_platform__WEBPACK_IMPORTED_MODULE_0__.platform.getAppPath(), 'src/external');
}
/**
 * Loads the deploy index file.
 *
 * This file includes information about which files are requried in the deploy.
 *
 * @param filePath
 * @returns
 */
function loadDeployIndex(filePath) {
    const indexPath = _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.join(getExternalFolderPath(), filePath);
    return _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.readJson(indexPath);
    // reject({ result: 'failure', message: 'Error exporting deploy files.' });
}
function addSuffix(url, suffix) {
    const parts = url.split('.');
    parts[parts.length - 2] = parts[parts.length - 2] + suffix;
    return parts.join('.');
}
async function _writeFileToFolder({ project, direntry, url, exportJson, injectHTML, indexJsPath, baseUrl, enableHash = true, envVariables, runtimeType }) {
    const fullPath = _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.join(getExternalFolderPath(), runtimeType, url);
    let content = await _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.readFile(fullPath);
    let filename = url;
    // Apply export if needed
    if (exportJson) {
        content = content.replace(/{{#export#}}/g, JSON.stringify(exportJson));
        if (enableHash) {
            const hash = (0,_noodl_utils_exporter_hash_xxhash64__WEBPACK_IMPORTED_MODULE_1__/* .createHash */ .n)();
            hash.update(content, 'utf8');
            const hex = hash.digest('hex');
            filename = addSuffix(url, '-' + hex);
        }
    }
    else if (injectHTML) {
        const htmlProcessor = new _processors_html_processor__WEBPACK_IMPORTED_MODULE_2__/* .HtmlProcessor */ .G(project);
        content = await htmlProcessor.process(content, {
            indexJsPath,
            baseUrl,
            envVariables
        });
    }
    await _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.writeFileOverride(direntry + '/' + filename, content);
    return filename;
}
async function writeIndexFiles({ project, direntry, exportJson, indexJsFile, indexHtmlFile, baseUrl, enableHash, envVariables, runtimeType }) {
    //write index.js file, with a hashed name
    const indexJsPath = await _writeFileToFolder({
        project,
        direntry,
        url: indexJsFile.url,
        exportJson,
        enableHash,
        runtimeType
    });
    if (indexHtmlFile) {
        //and write the index.html file with the correct path
        await _writeFileToFolder({
            project,
            direntry,
            url: indexHtmlFile.url,
            exportJson: undefined,
            injectHTML: true,
            indexJsPath,
            baseUrl,
            enableHash,
            runtimeType
        });
    }
}
async function copyDeployFilesToFolder({ project, direntry, files, exportJson, baseUrl, envVariables, runtimeType }) {
    const indexJsFile = files.find((file) => file.injectExport);
    const indexHtmlFile = files.find((file) => file.injectHTML);
    const otherFiles = files.filter((f) => f !== indexJsFile && f !== indexHtmlFile);
    const otherFilesPromises = otherFiles.map((file) => _writeFileToFolder({ project, direntry, url: file.url, envVariables, runtimeType }));
    await Promise.all([
        ...otherFilesPromises,
        writeIndexFiles({
            project,
            direntry,
            exportJson,
            indexJsFile,
            indexHtmlFile,
            baseUrl,
            // TODO: Make enableHash a global option? I dont want it for SSR
            enableHash: runtimeType === 'deploy',
            runtimeType
        })
    ]);
    // reject({ result: 'failure', message: 'Failed to copy deploy files.' });
}


/***/ }),

/***/ 71307:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ScrollArea-module__Root--Fodr3{flex:1;position:relative;width:100%;height:100%;overflow-y:auto;overflow-y:overlay;z-index:0}.ScrollArea-module__Container--dVnaJ{position:absolute;width:100%;min-height:100%;display:flex}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/ScrollArea/ScrollArea.module.scss"],"names":[],"mappings":"AAAA,gCACE,MAAA,CACA,iBAAA,CACA,UAAA,CACA,WAAA,CACA,eAAA,CACA,kBAAA,CACA,SAAA,CAGF,qCACE,iBAAA,CACA,UAAA,CACA,eAAA,CACA,YAAA","sourcesContent":[".Root {\n  flex: 1;\n  position: relative;\n  width: 100%;\n  height: 100%;\n  overflow-y: auto;\n  overflow-y: overlay;\n  z-index: 0;\n}\n\n.Container {\n  position: absolute;\n  width: 100%;\n  min-height: 100%;\n  display: flex;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ScrollArea-module__Root--Fodr3`,
	"Container": `ScrollArea-module__Container--dVnaJ`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 71336:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   t: () => (/* binding */ ViewerConnection)
/* harmony export */ });
/* harmony import */ var _noodl_models_nodelibrary_NodeLibraryImporter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(42146);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47821);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_shared_model__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11138);
/* harmony import */ var _shared_utils_projectmodules__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(90130);
/* harmony import */ var _shared_utils_projectmodules__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_shared_utils_projectmodules__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _models_nodelibrary__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(68091);
/* harmony import */ var _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6203);
/* harmony import */ var _models_warningsmodel__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(86105);
/* harmony import */ var _utils_debuginspector__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(20435);
/* harmony import */ var _utils_debuginspector__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_debuginspector__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils_exporter__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(87144);
/* harmony import */ var _utils_triggerChain__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(41954);










const port = process.env.NOODLPORT || 8574;
class ViewerConnection extends (_shared_model__WEBPACK_IMPORTED_MODULE_1___default()) {
    constructor() {
        super();
        // Connect to viewer server, wait a second to allow the server to start properly
        setTimeout(() => {
            this.connect();
        }, 1000);
        this.lastExports = {};
        this.clientsToExportTo = new Set();
        this.registeredRuntimeTypes = new Set();
        this.bindDebugInspectorEvents();
    }
    connect() {
        const _this = this;
        const protocol = process.env.ssl ? 'wss://' : 'ws://';
        const address = protocol + 'localhost:' + port;
        this.ws = new WebSocket(address);
        this.ws.addEventListener('open', function () {
            console.log('Connected to viewer server at ' + address);
            _this.send({ cmd: 'register', type: 'editor' });
            _this.watchAndExportModelChanges();
        });
        this.ws.addEventListener('close', function () {
            console.log('Connection to viewer server lost, attemtping to reconnect...');
            _this.stopWatchAndExportModelChanges();
            setTimeout(function () {
                _this.connect();
            }, 2000);
        });
        this.ws.addEventListener('message', async function (e) {
            // NOTE: When the data is too big it seems to change from string to a blob
            const text = typeof e.data === 'string' ? e.data : await e.data.text();
            const msg = JSON.parse(text);
            const messages = !Array.isArray(msg) ? [msg] : msg;
            for (const message of messages) {
                _this.processRequest(message);
            }
        });
        let totalWarnings;
        _models_warningsmodel__WEBPACK_IMPORTED_MODULE_6__/* .WarningsModel */ .l.instance.on('warningsChanged', function () {
            const newTotalWarnings = _models_warningsmodel__WEBPACK_IMPORTED_MODULE_6__/* .WarningsModel */ .l.instance.getTotalNumberOfWarnings({ levels: ['error'] });
            if (totalWarnings !== undefined && newTotalWarnings < totalWarnings) {
                // Warnings have been resolved, issue an export
                _this.export();
                console.log('Warnings have been resolved, doing full export');
            }
            totalWarnings = newTotalWarnings;
        });
    }
    processRequest(request) {
        if (!request)
            return;
        // A new viewer is connected
        if (request.cmd === 'registered' && request.type === 'viewer') {
            _models_warningsmodel__WEBPACK_IMPORTED_MODULE_6__/* .WarningsModel */ .l.instance.clearWarningsForRefMatching((ref) => ref.isFromViewer);
            this.sendDebugInspectorsEnabled();
        }
        //a viewer disconnected
        else if (request.cmd === 'disconnect') {
            this.clientsToExportTo.delete(request.clientId);
            _noodl_models_nodelibrary_NodeLibraryImporter__WEBPACK_IMPORTED_MODULE_0__/* .NodeLibraryImporter */ .K.instance.onClientDisconnect(request.clientId);
        }
        // A select node request
        else if (request.cmd === 'select' && request.type === 'viewer') {
            const content = JSON.parse(request.content);
            this.notifyListeners('select', content);
        }
        // Dynamic ports for a node is reported
        else if (request.cmd === 'instanceports' && request.type === 'viewer') {
            const content = JSON.parse(request.content);
            const node = _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance.findNodeWithId(content.nodeid);
            node && node.setDynamicPorts(content.ports, content.options);
        }
        else if (request.cmd === 'connectiondebugpulse' && request.type === 'viewer') {
            const content = JSON.parse(request.content);
            _utils_debuginspector__WEBPACK_IMPORTED_MODULE_7___default().instance.setConnectionsToPulse(content.connectionsToPulse);
            // Also capture for trigger chain recorder if recording
            if (_utils_triggerChain__WEBPACK_IMPORTED_MODULE_9__/* .triggerChainRecorder */ .qF.isRecording()) {
                content.connectionsToPulse.forEach((connectionId) => {
                    _utils_triggerChain__WEBPACK_IMPORTED_MODULE_9__/* .triggerChainRecorder */ .qF.captureConnectionPulse(connectionId);
                });
            }
        }
        else if (request.cmd === 'debuginspectorvalues' && request.type === 'viewer') {
            _utils_debuginspector__WEBPACK_IMPORTED_MODULE_7___default().instance.setInspectorValues(request.content.inspectors);
        }
        else if (request.cmd === 'connectionValue' && request.type === 'viewer') {
            _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.emit('ConnectionInspector', request.content);
        }
        else if (request.cmd === 'showwarning' && request.type === 'viewer') {
            const content = JSON.parse(request.content);
            if (_models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance !== undefined) {
                const ref = {
                    component: _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance.getComponentWithName(content.componentName),
                    node: _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance.findNodeWithId(content.nodeId),
                    key: content.key,
                    isFromViewer: true
                };
                if (ref.component && ref.node) {
                    _models_warningsmodel__WEBPACK_IMPORTED_MODULE_6__/* .WarningsModel */ .l.instance.setWarning(ref, content.warning);
                }
            }
        }
        else if (request.cmd === 'clearwarnings' && request.type === 'viewer') {
            const content = JSON.parse(request.content);
            const ref = {
                component: _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance.getComponentWithName(content.componentName),
                node: _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance.findNodeWithId(content.nodeId)
            };
            if (ref.component && ref.node) {
                _models_warningsmodel__WEBPACK_IMPORTED_MODULE_6__/* .WarningsModel */ .l.instance.clearWarningsForRef(ref);
            }
        }
        else if (request.cmd === 'nodelibrary' && request.type === 'viewer') {
            const content = JSON.parse(request.content);
            this.loadNodeLibrary(request.clientId, request.runtimeType, content);
        }
        else if (request.cmd === 'sendToOtherClients' && request.type === 'viewer') {
            this.send({
                cmd: 'messageFromOtherClient',
                clientId: request.clientId,
                content: request.content
            });
        }
        else if (request.cmd === 'getNoodlModules' && request.type === 'viewer') {
            _shared_utils_projectmodules__WEBPACK_IMPORTED_MODULE_3___default().instance.scanProjectModules(_models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance._retainedProjectDirectory, (modules) => {
                this.send({
                    cmd: 'noodlModules',
                    content: JSON.stringify(modules ? modules : [])
                });
            });
        }
        else if (request.cmd === 'componentMetadata' && request.type === 'viewer') {
            const content = JSON.parse(request.content);
            const component = _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance.getComponentWithName(content.componentName);
            component && component.setMetaData(content.key, content.data);
        }
        else if (request.cmd === 'projectMetadata' && request.type === 'viewer') {
            const content = JSON.parse(request.content);
            _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance.setMetaData(content.key, content.data);
        }
        else {
            console.log('Unknown request');
            console.log(request);
        }
    }
    _exportToClient(clientId, exportedJSON) {
        //don't send the same export twice
        if (exportedJSON === this.lastExports[clientId])
            return;
        this.send({
            cmd: 'export',
            type: 'full',
            content: exportedJSON,
            target: clientId
        });
        //send all inspectors
        if (_models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance) {
            const inspectorsModel = _utils_debuginspector__WEBPACK_IMPORTED_MODULE_7___default().InspectorsModel.instanceForProject(_models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance);
            this.sendDebugInspectors(inspectorsModel, clientId);
        }
        this.lastExports[clientId] = exportedJSON;
    }
    export(target) {
        if (!_models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance) {
            return;
        }
        let _export = _utils_exporter__WEBPACK_IMPORTED_MODULE_8__.exportToJSON(_models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance, {
            useBundles: false
        });
        //if there's no export (no root component), just send an empty export
        //so viewer can show an error
        if (!_export) {
            _export = {
                rootComponent: null,
                components: []
            };
        }
        const exportedJSON = JSON.stringify(_export);
        if (target) {
            this._exportToClient(target, exportedJSON);
        }
        else {
            for (const clientId of this.clientsToExportTo.values()) {
                this._exportToClient(clientId, exportedJSON);
            }
        }
    }
    send(request) {
        if (this.ws && this.ws.readyState == 1) {
            this.ws.send(JSON.stringify(request));
        }
    }
    sendNodeHighlighted(node, highlighted) {
        if (highlighted) {
            // Send and store this node as the highlighted node
            if (this.highlightedNode === node)
                return;
            if (this.highlightedNode) {
                // Cancel existing highlight
                this.send({
                    cmd: 'hoverEnd',
                    content: { id: this.highlightedNode.id }
                });
            }
            this.highlightedNode = node;
            this.send({
                cmd: 'hoverStart',
                content: { id: node.id }
            });
        }
        else {
            if (this.highlightedNode == node)
                this.highlightedNode = undefined;
            this.send({
                cmd: 'hoverEnd',
                content: { id: node.id }
            });
        }
    }
    sendRefresh() {
        this.send({ cmd: 'refresh' });
    }
    sendDebugInspectors(inspectorModel, target) {
        const inspectors = inspectorModel.inspectors.map((inspector) => {
            if (inspector.type === 'connection') {
                return {
                    type: 'connection',
                    connection: inspector.connection
                };
            }
            return {
                type: 'node',
                nodeId: inspector.nodeId
            };
        });
        this.send({
            cmd: 'debugInspectors',
            content: JSON.stringify({ inspectors }),
            target
        });
    }
    sendDebugInspectorsEnabled() {
        this.send({
            cmd: 'debuggingEnabled',
            content: JSON.stringify({
                enabled: _utils_debuginspector__WEBPACK_IMPORTED_MODULE_7___default().instance.isEnabled()
            })
        });
    }
    bindDebugInspectorEvents() {
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.inspectorAdded', (inspector) => {
            this.sendDebugInspectors(inspector.model);
        }, null);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.inspectorRemoved', (inspector) => {
            this.sendDebugInspectors(inspector.model);
        }, null);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('DebugInspectorEnabledChanged', () => {
            this.sendDebugInspectorsEnabled();
        }, null);
    }
    sendGetConnectionValue(clientId, connectionId) {
        this.send({
            cmd: 'getConnectionValue',
            content: JSON.stringify({ clientId, connectionId })
        });
    }
    /**
     * @param {string} clientId
     * @param {require('@noodl-models/nodelibrary/NodeLibraryData').RuntimeType} runtimeType
     * @param {require('@noodl-models/nodelibrary/NodeLibraryData').NodeLibraryData} newLibrary
     */
    loadNodeLibrary(clientId, runtimeType, newLibrary) {
        this.clientsToExportTo.add(clientId);
        this.registeredRuntimeTypes.add(runtimeType);
        _noodl_models_nodelibrary_NodeLibraryImporter__WEBPACK_IMPORTED_MODULE_0__/* .NodeLibraryImporter */ .K.instance.onClientImport(clientId, runtimeType, newLibrary);
        if (_models_nodelibrary__WEBPACK_IMPORTED_MODULE_4__/* .NodeLibrary */ .m.instance.isLoaded()) {
            this.export();
        }
    }
    stopWatchAndExportModelChanges() {
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.off(this.modelChangesListenerGroup);
        this.modelChangesListenerGroup = undefined;
    }
    watchAndExportModelChanges() {
        const _this = this;
        if (this.modelChangesListenerGroup) {
            //we're already listening, remove old listeners before adding new ones
            this.stopWatchAndExportModelChanges();
        }
        this.modelChangesListenerGroup = {};
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.settingsChanged', function (event) {
            if (_this.watchModelChangesDisabled)
                return;
            if (event.model instanceof _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel) {
                _this.send({
                    cmd: 'modelUpdate',
                    content: {
                        type: 'settingsChanged',
                        settings: event.model.settings
                    }
                });
            }
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.componentRenamed', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'componentRenamed',
                    oldName: e.args.oldName,
                    newName: e.args.model.name
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.nodeAdded', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (e.model.owner === undefined)
                return; // Not part of component
            if (e.model.owner.owner !== _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance)
                return; // Not part of current project
            if (!e.model.owner)
                return; //Model is being created, no owner yet. Viewer will use full export
            if (_models_nodelibrary__WEBPACK_IMPORTED_MODULE_4__/* .NodeLibrary */ .m.instance.typeIsMissing(e.args.model.type))
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'nodeAdded',
                    model: _utils_exporter__WEBPACK_IMPORTED_MODULE_8__.exportNode(e.args.model),
                    componentName: e.model.owner.name,
                    parentId: e.args.parent ? e.args.parent.id : undefined,
                    childIndex: e.args.index
                }
            });
            //notify viewer if this node is a root, but only if it's visual
            if (e.model.getRoots().indexOf(e.args.model) !== -1 && e.args.model.type.allowAsChild) {
                _this.send({
                    cmd: 'modelUpdate',
                    content: {
                        type: 'rootAdded',
                        nodeId: e.args.model.id,
                        componentName: e.model.owner.name
                    }
                });
            }
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.nodeRemoved', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            //Model.connectionRemoved events are sent before nodeRemoved
            //so no need to send affected connections
            if (!e.model.owner)
                return; //Model is being created, no owner yet. Viewer will use full export
            if (_models_nodelibrary__WEBPACK_IMPORTED_MODULE_4__/* .NodeLibrary */ .m.instance.typeIsMissing(e.args.model.type))
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'nodeRemoved',
                    model: _utils_exporter__WEBPACK_IMPORTED_MODULE_8__.exportNode(e.args.model),
                    componentName: e.model.owner.name
                }
            });
        }, this.modelChangesListenerGroup);
        function sendComponentPorts(componentModel) {
            const exportPorts = [];
            const ports = componentModel.getPorts();
            for (const i in ports) {
                const p = ports[i];
                // Only export types that are resolved
                if (p.type)
                    exportPorts.push(p);
            }
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'componentPortsUpdated',
                    ports: exportPorts,
                    componentName: componentModel.name
                }
            });
        }
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.connectionAdded', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (!e.model.owner)
                return; //Model is being created, no owner yet. Viewer will use full export
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'connectionAdded',
                    model: _utils_exporter__WEBPACK_IMPORTED_MODULE_8__.exportConnection(e.args.model),
                    componentName: e.model.owner.name
                }
            });
            sendComponentPorts(e.model.owner);
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.connectionRemoved', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (!e.model.owner)
                return; //Model is being created, no owner yet. Viewer will use full export
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'connectionRemoved',
                    model: _utils_exporter__WEBPACK_IMPORTED_MODULE_8__.exportConnection(e.args.model),
                    componentName: e.model.owner.name
                }
            });
            sendComponentPorts(e.model.owner);
        }, this.modelChangesListenerGroup);
        // A connection has changed it's from or to port
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.connectionPortChanged', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (!e.model.owner || !e.model.owner.owner)
                return; //Model is being created, no owner yet. Viewer will use full export
            const c = e.args.model;
            // First remove the old connection
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'connectionRemoved',
                    model: _utils_exporter__WEBPACK_IMPORTED_MODULE_8__.exportConnection({
                        fromId: c.fromId,
                        fromProperty: e.args.oldFromProperty !== undefined ? e.args.oldFromProperty : c.fromProperty,
                        toId: c.toId,
                        toProperty: e.args.oldToProperty !== undefined ? e.args.oldToProperty : c.toProperty
                    }),
                    componentName: e.model.owner.name
                }
            });
            // Then add the new connection
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'connectionAdded',
                    model: _utils_exporter__WEBPACK_IMPORTED_MODULE_8__.exportConnection(e.args.model),
                    componentName: e.model.owner.name
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.parametersChanged', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (!e.model.owner || !e.model.owner.owner)
                return; //Model is being created, no owner yet. Viewer will use full export
            const args = e.args || {};
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'parameterChanged',
                    nodeId: e.model.id,
                    componentName: e.model.owner.owner.name, //Node -> Graph -> Component
                    parameterName: args.name, // If only one
                    parameterValue: args.value,
                    state: args.state, // The state if any
                    // This is used if there are many parameters changed at once
                    parameters: args.parameters,
                    stateParameters: args.stateParameters,
                    oldParameters: args.oldParameters,
                    oldStateParameters: args.oldStateParameters
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.nodeAttached', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (!e.model.owner)
                return; //Model is being created, no owner yet. Viewer will use full export
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'nodeAttached',
                    nodeId: e.args.model.id,
                    parentId: e.args.parent.id,
                    childIndex: e.args.index,
                    componentName: e.model.owner.name
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.nodeDetached', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (!e.model.owner)
                return; //Model is being created, no owner yet. Viewer will use full export
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'nodeDetached',
                    nodeId: e.args.model.id,
                    componentName: e.model.owner.name
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.componentAdded', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (e.args.model.owner === undefined)
                return; // Not part of component
            if (e.args.model.owner !== _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance)
                return; // Not part of current project
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'componentAdded',
                    model: _utils_exporter__WEBPACK_IMPORTED_MODULE_8__.exportComponent(e.args.model)
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.componentRemoved', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'componentRemoved',
                    componentName: e.args.model.name
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.rootNodeChanged', function (e) {
            if (_this.watchModelChangesDisabled || !e.model)
                return;
            console.log('root node changed, library exporting...');
            _this.export();
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.portAdded', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'portAdded',
                    componentName: e.model.owner.owner.name,
                    nodeId: e.args.model.id,
                    port: e.args.port
                }
            });
            sendComponentPorts(e.model.owner.owner);
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.portRemoved', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'portRemoved',
                    componentName: e.model.owner.owner.name,
                    nodeId: e.args.model.id,
                    port: e.args.port
                }
            });
            sendComponentPorts(e.model.owner.owner);
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.nodePortRenamed', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'nodePortRenamed',
                    componentName: e.model.owner.name,
                    nodeId: e.args.model.id,
                    port: e.args.port,
                    oldName: e.args.oldName
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.instancePortsChanged', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (!e.model.owner.owner) {
                //node isn't assigned to a component yet
                //this can happen during specific cirumstances like the following:
                //1. ComponentModel.fromJSON is called
                //2. If it has navigation nodes the RouterNavigateAdapter will add dynamic ports to them, causing this callback to be called
                //3. Component owner is assigned
                return;
            }
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'instancePortsChanged',
                    componentName: e.model.owner.owner.name,
                    nodeId: e.model.id,
                    ports: _utils_exporter__WEBPACK_IMPORTED_MODULE_8__.exportPorts(e.model)
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.metadataChanged', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'componentMetadataChanged',
                    componentName: e.model.name,
                    key: e.args.key,
                    data: e.args.data
                }
            });
        }, this.modelChangesListenerGroup);
        // Variants
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.variantParametersChanged', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            const args = e.args || {};
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'variantParametersChanged',
                    variantName: e.model.name,
                    variantTypeName: e.model.typename,
                    parameterName: args.name, // If only one
                    parameterValue: args.value,
                    state: args.state,
                    // If many parameters, export entire variant
                    variant: args.name === undefined ? _utils_exporter__WEBPACK_IMPORTED_MODULE_8__.exportVariant(e.model) : undefined
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.variantDeleted', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'variantDeleted',
                    variantName: e.args.variant ? e.args.variant.name : undefined,
                    variantTypeName: e.args.variant ? e.args.variant.typename : undefined
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.variantChanged', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (!e.model.owner || !e.model.owner.owner)
                return; //Model is being created, no owner yet. Viewer will use full export
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'variantChanged',
                    nodeId: e.model.id,
                    componentName: e.model.owner.owner.name, //Node -> Graph -> Component
                    variantName: e.args.variant ? e.args.variant.name : undefined
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.variantStateTransitionsChanged', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            const args = e.args || {};
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'variantStateTransitionsChanged',
                    variantName: e.model.name,
                    variantTypeName: e.model.typename,
                    parameterName: args.parameterName, // If only one
                    curve: args.curve,
                    state: args.state,
                    // This is used if there are many parameters changed at once
                    stateTransitions: args.stateTransitions,
                    defaultStateTransitions: args.defaultStateTransitions,
                    oldStateTransitions: args.oldStateTransitons,
                    oldDefaultStateTransitions: args.oldDefaultStateTransitions
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.variantRenamed', (e) => {
            if (_this.watchModelChangesDisabled)
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'variantRenamed',
                    oldVariantName: e.args.oldName,
                    variantTypeName: e.args.variant.typename,
                    variantName: e.args.variant.name
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.variantDefaultStateTransitionChanged', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'variantDefaultStateTransitionChanged',
                    variantName: e.model.name,
                    variantTypeName: e.model.typename,
                    state: e.args.state,
                    curve: e.args.curve
                }
            });
        }, this.modelChangesListenerGroup);
        // State transitions
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.stateTransitionsChanged', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (!e.model.owner || !e.model.owner.owner)
                return; //Model is being created, no owner yet. Viewer will use full export
            const args = e.args || {};
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'stateTransitionsChanged',
                    nodeId: e.model.id,
                    componentName: e.model.owner.owner.name, //Node -> Graph -> Component
                    parameterName: args.parameterName, // If only one
                    curve: args.curve,
                    state: args.state,
                    // This is used if there are many parameters changed at once
                    stateTransitions: args.stateTransitions,
                    defaultStateTransitions: args.defaultStateTransitions,
                    oldStateTransitions: args.oldStateTransitons,
                    oldDefaultStateTransitions: args.oldDefaultStateTransitions
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.defaultStateTransitionChanged', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (!e.model.owner || !e.model.owner.owner)
                return; //Model is being created, no owner yet. Viewer will use full export
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'defaultStateTransitionChanged',
                    nodeId: e.model.id,
                    componentName: e.model.owner.owner.name, //Node -> Graph -> Component
                    state: e.args.state,
                    curve: e.args.curve
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('ProjectModel.instanceWillChange', () => {
            this.lastExports = {};
            this.registeredRuntimeTypes.clear();
            if (this.watchModelChangesDisabled)
                return;
            this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'projectInstanceChanged'
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('ProjectModel.metadataChanged', ({ key, data }) => {
            if (_this.watchModelChangesDisabled)
                return;
            _this.send({
                cmd: 'modelUpdate',
                content: {
                    type: 'metadataChanged',
                    key: key,
                    data: data
                }
            });
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('activeComponentChanged', ({ component }) => {
            if (component === undefined)
                return;
            _this.send({
                cmd: 'activeComponentChanged',
                component: component.fullName
            });
        }, this.modelChangesListenerGroup);
        let sendRouterIndexTimeout;
        function sendRouterIndex() {
            if (sendRouterIndexTimeout)
                return;
            sendRouterIndexTimeout = setTimeout(() => {
                sendRouterIndexTimeout = undefined;
                const allComponents = _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance.getComponents();
                _this.send({
                    cmd: 'modelUpdate',
                    content: {
                        type: 'routerIndexChanged',
                        data: _utils_exporter__WEBPACK_IMPORTED_MODULE_8__.getRouterIndex(allComponents)
                    }
                });
            }, 100);
        }
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on(['Model.parametersChanged'], (event) => {
            if (_this.watchModelChangesDisabled)
                return;
            const nodeType = event.model.type.name;
            if (['Router', 'PageInputs', 'Page'].includes(nodeType)) {
                sendRouterIndex();
            }
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.nodeAdded', (event) => {
            if (_this.watchModelChangesDisabled)
                return;
            const nodeType = event.args.model.type;
            if (['Router', 'PageInputs', 'Page'].includes(nodeType)) {
                sendRouterIndex();
            }
        }, this.modelChangesListenerGroup);
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_2__.EventDispatcher.instance.on('Model.componentAdded', function (e) {
            if (_this.watchModelChangesDisabled)
                return;
            if (e.args.model.owner === undefined)
                return; // Not part of component
            if (e.args.model.owner !== _models_projectmodel__WEBPACK_IMPORTED_MODULE_5__.ProjectModel.instance)
                return; // Not part of current project
            let doExport = false;
            e.args.model.forEachNode((node) => {
                if (['Router', 'PageInputs', 'Page'].includes(node.type.name)) {
                    doExport = true;
                }
            });
            if (doExport) {
                sendRouterIndex();
            }
        }, this.modelChangesListenerGroup);
    }
    setWatchModelChangesEnabled(enabled) {
        this.watchModelChangesDisabled = !enabled;
    }
}
if (process.env.devMode !== 'test') {
    ViewerConnection.instance = new ViewerConnection();
}


/***/ }),

/***/ 71497:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.IssueDetail-module__IssueDetailOverlay--rnGxw{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,.5);z-index:1000;display:flex;justify-content:flex-end;animation:IssueDetail-module__fadeIn--TKFa1 .2s ease}@keyframes IssueDetail-module__fadeIn--TKFa1{from{opacity:0}to{opacity:1}}.IssueDetail-module__IssueDetail--gT9Qd{width:600px;max-width:90vw;height:100%;background-color:var(--theme-color-bg-2);box-shadow:-2px 0 8px rgba(0,0,0,.2);display:flex;flex-direction:column;animation:IssueDetail-module__slideIn--lDy3Z .3s ease;overflow:hidden}@keyframes IssueDetail-module__slideIn--lDy3Z{from{transform:translateX(100%)}to{transform:translateX(0)}}.IssueDetail-module__Header--hK9xP{padding:20px;border-bottom:1px solid var(--theme-color-border-default);flex-shrink:0}.IssueDetail-module__TitleSection--APhpK{display:flex;align-items:flex-start;gap:12px;margin-bottom:12px}.IssueDetail-module__Title--DJCw5{flex:1;color:var(--theme-color-fg-default);font-size:18px;font-weight:600;margin:0;line-height:1.4}.IssueDetail-module__StatusBadge--aWp96{flex-shrink:0;padding:4px 12px;border-radius:12px;font-size:12px;font-weight:600;text-transform:capitalize}.IssueDetail-module__StatusBadge--aWp96[data-state=open]{background-color:rgba(46,160,67,.15);color:#2ea043}.IssueDetail-module__StatusBadge--aWp96[data-state=closed]{background-color:rgba(177,24,24,.15);color:#da3633}.IssueDetail-module__CloseButton--lHLHz{position:absolute;top:16px;right:16px;width:32px;height:32px;display:flex;align-items:center;justify-content:center;background-color:rgba(0,0,0,0);border:none;border-radius:4px;color:var(--theme-color-fg-default-shy);font-size:20px;cursor:pointer;transition:all .15s ease}.IssueDetail-module__CloseButton--lHLHz:hover{background-color:var(--theme-color-bg-4);color:var(--theme-color-fg-default)}.IssueDetail-module__Meta--gXDgN{display:flex;align-items:center;gap:8px;color:var(--theme-color-fg-default-shy);font-size:13px;margin-bottom:12px}.IssueDetail-module__Meta--gXDgN strong{color:var(--theme-color-fg-default);font-weight:600}.IssueDetail-module__Labels--n1abG{display:flex;flex-wrap:wrap;gap:6px}.IssueDetail-module__Label--j9A17{padding:3px 10px;border-radius:12px;font-size:12px;font-weight:600;display:inline-block}.IssueDetail-module__Body--HPgf7{flex:1;padding:20px;overflow-y:auto;color:var(--theme-color-fg-default);font-size:14px;line-height:1.6}.IssueDetail-module__MarkdownContent--PQ_T1{white-space:pre-wrap;word-break:break-word}.IssueDetail-module__NoDescription--j1dAL{color:var(--theme-color-fg-default-shy);font-style:italic}.IssueDetail-module__Footer--KwWvZ{padding:16px 20px;border-top:1px solid var(--theme-color-border-default);flex-shrink:0}.IssueDetail-module__ViewOnGitHub--PZvy0{display:inline-flex;align-items:center;gap:4px;padding:8px 16px;background-color:var(--theme-color-primary);color:#fff;text-decoration:none;border-radius:4px;font-size:13px;font-weight:500;transition:opacity .15s ease}.IssueDetail-module__ViewOnGitHub--PZvy0:hover{opacity:.9}.IssueDetail-module__ViewOnGitHub--PZvy0:active{opacity:.8}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssueDetail.module.scss"],"names":[],"mappings":"AAIA,+CACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,+BAAA,CACA,YAAA,CACA,YAAA,CACA,wBAAA,CACA,oDAAA,CAGF,6CACE,KACE,SAAA,CAEF,GACE,SAAA,CAAA,CAIJ,wCACE,WAAA,CACA,cAAA,CACA,WAAA,CACA,wCAAA,CACA,oCAAA,CACA,YAAA,CACA,qBAAA,CACA,qDAAA,CACA,eAAA,CAGF,8CACE,KACE,0BAAA,CAEF,GACE,uBAAA,CAAA,CAIJ,mCACE,YAAA,CACA,yDAAA,CACA,aAAA,CAGF,yCACE,YAAA,CACA,sBAAA,CACA,QAAA,CACA,kBAAA,CAGF,kCACE,MAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CACA,QAAA,CACA,eAAA,CAGF,wCACE,aAAA,CACA,gBAAA,CACA,kBAAA,CACA,cAAA,CACA,eAAA,CACA,yBAAA,CAEA,yDACE,oCAAA,CACA,aAAA,CAGF,2DACE,oCAAA,CACA,aAAA,CAIJ,wCACE,iBAAA,CACA,QAAA,CACA,UAAA,CACA,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,8BAAA,CACA,WAAA,CACA,iBAAA,CACA,uCAAA,CACA,cAAA,CACA,cAAA,CACA,wBAAA,CAEA,8CACE,wCAAA,CACA,mCAAA,CAIJ,iCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,uCAAA,CACA,cAAA,CACA,kBAAA,CAEA,wCACE,mCAAA,CACA,eAAA,CAIJ,mCACE,YAAA,CACA,cAAA,CACA,OAAA,CAGF,kCACE,gBAAA,CACA,kBAAA,CACA,cAAA,CACA,eAAA,CACA,oBAAA,CAGF,iCACE,MAAA,CACA,YAAA,CACA,eAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CAGF,4CACE,oBAAA,CACA,qBAAA,CAGF,0CACE,uCAAA,CACA,iBAAA,CAGF,mCACE,iBAAA,CACA,sDAAA,CACA,aAAA,CAGF,yCACE,mBAAA,CACA,kBAAA,CACA,OAAA,CACA,gBAAA,CACA,2CAAA,CACA,UAAA,CACA,oBAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,4BAAA,CAEA,+CACE,UAAA,CAGF,gDACE,UAAA","sourcesContent":["/**\n * IssueDetail Styles - Slide-out panel\n */\n\n.IssueDetailOverlay {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.5);\n  z-index: 1000;\n  display: flex;\n  justify-content: flex-end;\n  animation: fadeIn 0.2s ease;\n}\n\n@keyframes fadeIn {\n  from {\n    opacity: 0;\n  }\n  to {\n    opacity: 1;\n  }\n}\n\n.IssueDetail {\n  width: 600px;\n  max-width: 90vw;\n  height: 100%;\n  background-color: var(--theme-color-bg-2);\n  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.2);\n  display: flex;\n  flex-direction: column;\n  animation: slideIn 0.3s ease;\n  overflow: hidden;\n}\n\n@keyframes slideIn {\n  from {\n    transform: translateX(100%);\n  }\n  to {\n    transform: translateX(0);\n  }\n}\n\n.Header {\n  padding: 20px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  flex-shrink: 0;\n}\n\n.TitleSection {\n  display: flex;\n  align-items: flex-start;\n  gap: 12px;\n  margin-bottom: 12px;\n}\n\n.Title {\n  flex: 1;\n  color: var(--theme-color-fg-default);\n  font-size: 18px;\n  font-weight: 600;\n  margin: 0;\n  line-height: 1.4;\n}\n\n.StatusBadge {\n  flex-shrink: 0;\n  padding: 4px 12px;\n  border-radius: 12px;\n  font-size: 12px;\n  font-weight: 600;\n  text-transform: capitalize;\n\n  &[data-state='open'] {\n    background-color: rgba(46, 160, 67, 0.15);\n    color: #2ea043;\n  }\n\n  &[data-state='closed'] {\n    background-color: rgba(177, 24, 24, 0.15);\n    color: #da3633;\n  }\n}\n\n.CloseButton {\n  position: absolute;\n  top: 16px;\n  right: 16px;\n  width: 32px;\n  height: 32px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  background-color: transparent;\n  border: none;\n  border-radius: 4px;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 20px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    color: var(--theme-color-fg-default);\n  }\n}\n\n.Meta {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 13px;\n  margin-bottom: 12px;\n\n  strong {\n    color: var(--theme-color-fg-default);\n    font-weight: 600;\n  }\n}\n\n.Labels {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 6px;\n}\n\n.Label {\n  padding: 3px 10px;\n  border-radius: 12px;\n  font-size: 12px;\n  font-weight: 600;\n  display: inline-block;\n}\n\n.Body {\n  flex: 1;\n  padding: 20px;\n  overflow-y: auto;\n  color: var(--theme-color-fg-default);\n  font-size: 14px;\n  line-height: 1.6;\n}\n\n.MarkdownContent {\n  white-space: pre-wrap;\n  word-break: break-word;\n}\n\n.NoDescription {\n  color: var(--theme-color-fg-default-shy);\n  font-style: italic;\n}\n\n.Footer {\n  padding: 16px 20px;\n  border-top: 1px solid var(--theme-color-border-default);\n  flex-shrink: 0;\n}\n\n.ViewOnGitHub {\n  display: inline-flex;\n  align-items: center;\n  gap: 4px;\n  padding: 8px 16px;\n  background-color: var(--theme-color-primary);\n  color: white;\n  text-decoration: none;\n  border-radius: 4px;\n  font-size: 13px;\n  font-weight: 500;\n  transition: opacity 0.15s ease;\n\n  &:hover {\n    opacity: 0.9;\n  }\n\n  &:active {\n    opacity: 0.8;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"IssueDetailOverlay": `IssueDetail-module__IssueDetailOverlay--rnGxw`,
	"fadeIn": `IssueDetail-module__fadeIn--TKFa1`,
	"IssueDetail": `IssueDetail-module__IssueDetail--gT9Qd`,
	"slideIn": `IssueDetail-module__slideIn--lDy3Z`,
	"Header": `IssueDetail-module__Header--hK9xP`,
	"TitleSection": `IssueDetail-module__TitleSection--APhpK`,
	"Title": `IssueDetail-module__Title--DJCw5`,
	"StatusBadge": `IssueDetail-module__StatusBadge--aWp96`,
	"CloseButton": `IssueDetail-module__CloseButton--lHLHz`,
	"Meta": `IssueDetail-module__Meta--gXDgN`,
	"Labels": `IssueDetail-module__Labels--n1abG`,
	"Label": `IssueDetail-module__Label--j9A17`,
	"Body": `IssueDetail-module__Body--HPgf7`,
	"MarkdownContent": `IssueDetail-module__MarkdownContent--PQ_T1`,
	"NoDescription": `IssueDetail-module__NoDescription--j1dAL`,
	"Footer": `IssueDetail-module__Footer--KwWvZ`,
	"ViewOnGitHub": `IssueDetail-module__ViewOnGitHub--PZvy0`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 71594:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.UserBadgeList-module__Root--LutJq{display:flex;align-items:center}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/user/UserBadgeList/UserBadgeList.module.scss"],"names":[],"mappings":"AAAA,mCACE,YAAA,CACA,kBAAA","sourcesContent":[".Root {\n  display: flex;\n  align-items: center;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `UserBadgeList-module__Root--LutJq`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 72189:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5, _path6, _path7, _path8, _path9;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgBorderUp = function SvgBorderUp(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M25.4434 26.4445C25.0291 26.4445 24.6934 26.1087 24.6934 25.6945C24.6934 25.2803 25.0291 24.9445 25.4434 24.9445C25.8576 24.9445 26.1934 25.2803 26.1934 25.6945C26.1934 26.1087 25.8576 26.4445 25.4434 26.4445Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M11.7017 26.4445C11.2874 26.4445 10.9517 26.1087 10.9517 25.6945C10.9517 25.2803 11.2874 24.9445 11.7017 24.9445C12.1159 24.9445 12.4517 25.2803 12.4517 25.6945C12.4517 26.1087 12.1159 26.4445 11.7017 26.4445Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M18.5728 26.4445C18.1585 26.4445 17.8228 26.1087 17.8228 25.6945C17.8228 25.2803 18.1585 24.9445 18.5728 24.9445C18.987 24.9445 19.3228 25.2803 19.3228 25.6945C19.3228 26.1087 18.987 26.4445 18.5728 26.4445Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M4.83057 26.4445C4.41635 26.4445 4.08057 26.1087 4.08057 25.6945C4.08057 25.2803 4.41635 24.9445 4.83057 24.9445C5.24478 24.9445 5.58057 25.2803 5.58057 25.6945C5.58057 26.1087 5.24478 26.4445 4.83057 26.4445Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M4.83008 12.7025C4.41586 12.7025 4.08008 12.3667 4.08008 11.9525C4.08008 11.5382 4.41586 11.2025 4.83008 11.2025C5.24429 11.2025 5.58008 11.5382 5.58008 11.9525C5.58008 12.3667 5.24429 12.7025 4.83008 12.7025Z",
    fill: "#F5F5F5"
  })), _path6 || (_path6 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M25.4429 12.7025C25.0287 12.7025 24.6929 12.3667 24.6929 11.9525C24.6929 11.5382 25.0287 11.2025 25.4429 11.2025C25.8571 11.2025 26.1929 11.5382 26.1929 11.9525C26.1929 12.3667 25.8571 12.7025 25.4429 12.7025Z",
    fill: "#F5F5F5"
  })), _path7 || (_path7 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M4.83057 19.5734C4.41635 19.5734 4.08057 19.2376 4.08057 18.8234C4.08057 18.4092 4.41635 18.0734 4.83057 18.0734C5.24478 18.0734 5.58057 18.4092 5.58057 18.8234C5.58057 19.2376 5.24478 19.5734 4.83057 19.5734Z",
    fill: "#F5F5F5"
  })), _path8 || (_path8 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M25.4434 19.5734C25.0291 19.5734 24.6934 19.2376 24.6934 18.8234C24.6934 18.4092 25.0291 18.0734 25.4434 18.0734C25.8576 18.0734 26.1934 18.4092 26.1934 18.8234C26.1934 19.2376 25.8576 19.5734 25.4434 19.5734Z",
    fill: "#F5F5F5"
  })), _path9 || (_path9 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.08008 4.90173C4.08008 4.48752 4.41586 4.15173 4.83008 4.15173L25.4426 4.15173C25.8568 4.15173 26.1926 4.48752 26.1926 4.90173C26.1926 5.31595 25.8568 5.65173 25.4426 5.65173L4.83008 5.65173C4.41586 5.65173 4.08008 5.31595 4.08008 4.90173Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgBorderUp);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "29bb549eb831b2a303606981127ad1da.svg");

/***/ }),

/***/ 72301:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.NodePickerCategory-module__Root--elVrS{position:relative;border-bottom:1px solid var(--theme-color-bg-1)}.NodePickerCategory-module__Header--_plmL{padding:10px 12px;border:0px solid rgba(0,0,0,0);border-left-width:4px;cursor:pointer;box-sizing:border-box;display:flex;flex-direction:column;justify-content:center;position:relative}.NodePickerCategory-module__Header--is-theme-visual--7AH6W{border-left-color:var(--theme-color-node-visual-2)}.NodePickerCategory-module__Header--is-theme-logic--aFPw5{border-left-color:var(--theme-color-node-logic-2)}.NodePickerCategory-module__Header--is-theme-data--KdJ6l{border-left-color:var(--theme-color-node-data-2)}.NodePickerCategory-module__Header--is-theme-component--SEZr5{border-left-color:var(--theme-color-node-component-2)}.NodePickerCategory-module__Header--is-theme-javascript--JZg2Z{border-left-color:var(--theme-color-node-custom-2)}.NodePickerCategory-module__Root--is-highlighted--Sa_7n .NodePickerCategory-module__Header--_plmL{background-color:var(--theme-color-bg-3)}.NodePickerCategory-module__Title--tyLsO{font-size:12px;line-height:13px;letter-spacing:2%;padding:0;padding-bottom:1px;margin:0;color:var(--theme-color-fg-highlight);font-weight:600}.NodePickerCategory-module__Description--wvqc8{padding:0;margin:0;color:var(--theme-color-fg-default);font-weight:400;font-size:11px;line-height:1;opacity:.65}.NodePickerCategory-module__Arrow--Nqpwo{width:16px;height:16px;position:absolute;pointer-events:none;right:10px;top:50%;transition:transform 300ms var(--easing-equal);opacity:.65}.NodePickerCategory-module__Arrow--is-collapsed--kJv63{transform:translateY(-50%) rotate(90deg)}.NodePickerCategory-module__Arrow--is-not-collapsed--bdEB2{transform:translateY(-50%) rotate(-90deg)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/NodePicker/components/NodePickerCategory/NodePickerCategory.module.scss"],"names":[],"mappings":"AAGA,wCACE,iBAAA,CACA,+CAAA,CAGF,0CACE,iBAAA,CACA,8BAAA,CACA,qBAAA,CACA,cAAA,CACA,qBAAA,CACA,YAAA,CACA,qBAAA,CACA,sBAAA,CACA,iBAAA,CAEA,2DACE,kDAAA,CAGF,0DACE,iDAAA,CAGF,yDACE,gDAAA,CAGF,8DACE,qDAAA,CAGF,+DACE,kDAAA,CAGF,kGACE,wCAAA,CAIJ,yCACE,cAAA,CACA,gBAAA,CACA,iBAAA,CACA,SAAA,CACA,kBAAA,CACA,QAAA,CACA,qCAAA,CACA,eAAA,CAGF,+CACE,SAAA,CACA,QAAA,CACA,mCAAA,CACA,eAAA,CACA,cAAA,CACA,aAAA,CACA,WAAA,CAGF,yCACE,UAAA,CACA,WAAA,CACA,iBAAA,CACA,mBAAA,CACA,UAAA,CACA,OAAA,CACA,8CAAA,CACA,WAAA,CAEA,uDACE,wCAAA,CAGF,2DACE,yCAAA","sourcesContent":["@use '@scss-placeholders/util';\n@use '@scss-variables/animation';\n\n.Root {\n  position: relative;\n  border-bottom: 1px solid var(--theme-color-bg-1);\n}\n\n.Header {\n  padding: 10px 12px;\n  border: 0px solid transparent;\n  border-left-width: 4px;\n  cursor: pointer;\n  box-sizing: border-box;\n  display: flex;\n  flex-direction: column;\n  justify-content: center;\n  position: relative;\n\n  &--is-theme-visual {\n    border-left-color: var(--theme-color-node-visual-2);\n  }\n\n  &--is-theme-logic {\n    border-left-color: var(--theme-color-node-logic-2);\n  }\n\n  &--is-theme-data {\n    border-left-color: var(--theme-color-node-data-2);\n  }\n\n  &--is-theme-component {\n    border-left-color: var(--theme-color-node-component-2);\n  }\n\n  &--is-theme-javascript {\n    border-left-color: var(--theme-color-node-custom-2);\n  }\n\n  .Root--is-highlighted & {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n.Title {\n  font-size: 12px;\n  line-height: 13px;\n  letter-spacing: 2%;\n  padding: 0;\n  padding-bottom: 1px;\n  margin: 0;\n  color: var(--theme-color-fg-highlight);\n  font-weight: 600;\n}\n\n.Description {\n  padding: 0;\n  margin: 0;\n  color: var(--theme-color-fg-default);\n  font-weight: 400;\n  font-size: 11px;\n  line-height: 1;\n  opacity: 0.65;\n}\n\n.Arrow {\n  width: 16px;\n  height: 16px;\n  position: absolute;\n  pointer-events: none;\n  right: 10px;\n  top: 50%;\n  transition: transform 300ms animation.$easing-equal;\n  opacity: 0.65;\n\n  &--is-collapsed {\n    transform: translateY(-50%) rotate(90deg);\n  }\n\n  &--is-not-collapsed {\n    transform: translateY(-50%) rotate(-90deg);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `NodePickerCategory-module__Root--elVrS`,
	"Header": `NodePickerCategory-module__Header--_plmL`,
	"Header--is-theme-visual": `NodePickerCategory-module__Header--is-theme-visual--7AH6W`,
	"Header--is-theme-logic": `NodePickerCategory-module__Header--is-theme-logic--aFPw5`,
	"Header--is-theme-data": `NodePickerCategory-module__Header--is-theme-data--KdJ6l`,
	"Header--is-theme-component": `NodePickerCategory-module__Header--is-theme-component--SEZr5`,
	"Header--is-theme-javascript": `NodePickerCategory-module__Header--is-theme-javascript--JZg2Z`,
	"Root--is-highlighted": `NodePickerCategory-module__Root--is-highlighted--Sa_7n`,
	"Title": `NodePickerCategory-module__Title--tyLsO`,
	"Description": `NodePickerCategory-module__Description--wvqc8`,
	"Arrow": `NodePickerCategory-module__Arrow--Nqpwo`,
	"Arrow--is-collapsed": `NodePickerCategory-module__Arrow--is-collapsed--kJv63`,
	"Arrow--is-not-collapsed": `NodePickerCategory-module__Arrow--is-not-collapsed--bdEB2`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 72316:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  W: () => (/* binding */ GitStore)
});

// EXTERNAL MODULE: external "electron-store"
var external_electron_store_ = __webpack_require__(49468);
var external_electron_store_default = /*#__PURE__*/__webpack_require__.n(external_electron_store_);
// EXTERNAL MODULE: external "electron"
var external_electron_ = __webpack_require__(91288);
// EXTERNAL MODULE: ./src/editor/src/utils/utils.ts
var utils = __webpack_require__(93015);
;// ./src/editor/src/store/_internal/StorageApi.ts


const _responseHandlers = {};
external_electron_.ipcRenderer.on('storage-api', function (_, args) {
    const token = args.token;
    if (!_responseHandlers[token])
        return;
    _responseHandlers[token](args.data);
    delete _responseHandlers[token];
});
function send(method, ...args) {
    return new Promise((resolve) => {
        const token = (0,utils.guid)();
        _responseHandlers[token] = (args) => {
            resolve(args);
        };
        external_electron_.ipcRenderer.send('storage-api', { token, method, args });
    });
}
function isEncryptionAvailable() {
    return send('isEncryptionAvailable');
}
function decryptString(value) {
    return send('decryptString', value);
}
function encryptString(value) {
    return send('encryptString', value);
}

;// ./src/editor/src/store/GitStore.ts


const store = new (external_electron_store_default())({
    name: 'git_external',
    encryptionKey: 'b4a5d3b3-5e3e-477e-a978-9d347bc8b835'
});
const GitStore = {
    isAvailable() {
        return isEncryptionAvailable();
    },
    async get(provider, projectId) {
        if (projectId) {
            const key = `${provider}__${projectId}`;
            const encrypted = store.get(key);
            const decrypted = encrypted ? await decryptString(encrypted) : undefined;
            return decrypted ? JSON.parse(decrypted) : undefined;
        }
        return undefined;
    },
    async set(provider, projectId, value) {
        const key = `${provider}__${projectId}`;
        const encrypted = await encryptString(JSON.stringify(value));
        store.set(key, encrypted);
    }
};


/***/ }),

/***/ 72400:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCollaboration = function SvgCollaboration(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M4.42041 9.21582C4.42041 7.75708 5.60295 6.57454 7.06169 6.57454C8.52044 6.57454 9.70298 7.75708 9.70298 9.21582C9.70298 10.6746 8.52044 11.8571 7.06169 11.8571C5.60295 11.8571 4.42041 10.6746 4.42041 9.21582ZM7.06169 5.07454C4.77453 5.07454 2.92041 6.92866 2.92041 9.21582C2.92041 10.6749 3.675 11.9578 4.81523 12.6954C2.39082 13.5676 0.621011 15.8112 0.441134 18.4909C0.395088 19.1769 0.954465 19.6912 1.57607 19.6912H12.532H12.5474H22.6973C23.3189 19.6912 23.8783 19.1769 23.8323 18.4909C23.6524 15.8114 21.8828 13.5679 19.4587 12.6956C20.5991 11.958 21.3539 10.6751 21.3539 9.21582C21.3539 6.92866 19.4997 5.07454 17.2126 5.07454C14.9254 5.07454 13.0713 6.92866 13.0713 9.21582C13.0713 10.6748 13.8258 11.9576 14.9659 12.6953C13.8554 13.0947 12.8824 13.7818 12.1367 14.666C11.3909 13.7815 10.4182 13.0947 9.30817 12.6954C10.4484 11.9578 11.203 10.6749 11.203 9.21582C11.203 6.92866 9.34886 5.07454 7.06169 5.07454ZM22.293 18.1912H13.6554C13.5673 17.4086 13.3431 16.6672 13.0071 15.9913C13.9373 14.6681 15.4741 13.8056 17.2117 13.8056C19.7932 13.8056 21.9303 15.7107 22.293 18.1912ZM7.06172 13.8056C9.64324 13.8056 11.7804 15.7107 12.1431 18.1912H1.98036C2.34308 15.7107 4.4802 13.8056 7.06172 13.8056ZM14.5713 9.21582C14.5713 7.75708 15.7538 6.57454 17.2126 6.57454C18.6713 6.57454 19.8539 7.75708 19.8539 9.21582C19.8539 10.6746 18.6713 11.8571 17.2126 11.8571C15.7538 11.8571 14.5713 10.6746 14.5713 9.21582Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCollaboration);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "83f813226ec6421ddb828d67214108f9.svg");

/***/ }),

/***/ 72498:
/***/ ((module) => {

// Module
var code = "<div style=\"width:400px\" data-indent-offset=\"20\"> <div data-template=\"folder\" class=\"import-popup-folder\" style=\"width:100%;position:relative\"> <div style=\"width:100%;height:24px;position:relative\"> <div class=\"sidebar-panel-dark-input\" style=\"position:absolute;left:2px;width:24px;top:3px;bottom:3px\" data-click=\"onFolderBoxClicked\"> <i class=\"fa fa-check\" data-class=\"!import:hidden,implicit:import-popup-implicit-check,import:import-popup-import-check\" style=\"position:absolute;left:7px;top:5px\"></i> </div> <div class=\"indent-me\" style=\"width:100%;height:24px;position:absolute\" data-click=\"onFolderClicked\"> <div style=\"position:absolute;width:28px;top:4px;bottom:4px\"> <i class=\"fa\" data-class=\"open:fa-caret-down,!open:fa-caret-right\"></i> </div> <div style=\"line-height:20px;position:absolute;left:10px;top:3px;bottom:3px;right:3px\" data-text=\"localName\"> </div> </div> </div> <div class=\"content\" style=\"\"></div> </div> <div data-template=\"item\" class=\"import-popup-item\" style=\"width:100%;height:24px;position:relative\"> <div class=\"sidebar-panel-dark-input\" style=\"position:absolute;left:2px;width:24px;top:3px;bottom:3px\" data-click=\"onBoxClicked\"> <i class=\"fa fa-check\" data-class=\"!check:hidden,implicit:import-popup-implicit-check,import:import-popup-import-check\" style=\"position:absolute;left:7px;top:5px\"></i> </div> <div class=\"indent-me\" style=\"line-height:20px;position:absolute;top:3px;bottom:3px;right:3px\" data-text=\"localName\"> </div> </div> <div style=\"height:500px;overflow:hidden auto\"> <div data-class=\"!hasComponents:hidden\"> <label class=\"popup-group-label\">COMPONENTS</label> <div class=\"import-popup-text\"> Select which components to import from the project. </div> <div class=\"components\" style=\"margin-top:10px;width:100%\"></div> </div> <div data-class=\"!hasResources:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\">RESOURCES</label> <div class=\"import-popup-text\"> Select which resources to import from the project. </div> <div class=\"resources\" style=\"margin-top:10px;width:100%\"></div> </div> <div data-class=\"!hasModules:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\">MODULES</label> <div class=\"import-popup-text\"> Select which modules to import from the project. </div> <div class=\"modules\" style=\"margin-top:10px;width:100%\"></div> </div> <div data-class=\"!hasVariants:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\">VARIANTS</label> <div class=\"import-popup-text\"> Select which variants to import from the project. </div> <div class=\"variants\" style=\"margin-top:10px;width:100%\"></div> </div> <div data-class=\"!hasColorStyles:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\">COLOR STYLES</label> <div class=\"import-popup-text\"> Select which color styles to import from the project. </div> <div class=\"color-styles\" style=\"margin-top:10px;width:100%\"></div> </div> <div data-class=\"!hasTextStyles:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\">TEXT STYLES</label> <div class=\"import-popup-text\"> Select which text styles to import from the project. </div> <div class=\"text-styles\" style=\"margin-top:10px;width:100%\"></div> </div> <div style=\"height:30px;padding:5px;padding-bottom:10px;margin-top:20px\"> <button class=\"popup-button\" data-click=\"onOkClicked\">IMPORT</button> <button class=\"popup-button-grey\" data-click=\"onCancelClicked\">CANCEL</button> </div> </div> </div>";
// Exports
module.exports = code;

/***/ }),

/***/ 72591:
/***/ ((module) => {

"use strict";


var stylesInDOM = [];
function getIndexByIdentifier(identifier) {
  var result = -1;
  for (var i = 0; i < stylesInDOM.length; i++) {
    if (stylesInDOM[i].identifier === identifier) {
      result = i;
      break;
    }
  }
  return result;
}
function modulesToDom(list, options) {
  var idCountMap = {};
  var identifiers = [];
  for (var i = 0; i < list.length; i++) {
    var item = list[i];
    var id = options.base ? item[0] + options.base : item[0];
    var count = idCountMap[id] || 0;
    var identifier = "".concat(id, " ").concat(count);
    idCountMap[id] = count + 1;
    var indexByIdentifier = getIndexByIdentifier(identifier);
    var obj = {
      css: item[1],
      media: item[2],
      sourceMap: item[3],
      supports: item[4],
      layer: item[5]
    };
    if (indexByIdentifier !== -1) {
      stylesInDOM[indexByIdentifier].references++;
      stylesInDOM[indexByIdentifier].updater(obj);
    } else {
      var updater = addElementStyle(obj, options);
      options.byIndex = i;
      stylesInDOM.splice(i, 0, {
        identifier: identifier,
        updater: updater,
        references: 1
      });
    }
    identifiers.push(identifier);
  }
  return identifiers;
}
function addElementStyle(obj, options) {
  var api = options.domAPI(options);
  api.update(obj);
  var updater = function updater(newObj) {
    if (newObj) {
      if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap && newObj.supports === obj.supports && newObj.layer === obj.layer) {
        return;
      }
      api.update(obj = newObj);
    } else {
      api.remove();
    }
  };
  return updater;
}
module.exports = function (list, options) {
  options = options || {};
  list = list || [];
  var lastIdentifiers = modulesToDom(list, options);
  return function update(newList) {
    newList = newList || [];
    for (var i = 0; i < lastIdentifiers.length; i++) {
      var identifier = lastIdentifiers[i];
      var index = getIndexByIdentifier(identifier);
      stylesInDOM[index].references--;
    }
    var newLastIdentifiers = modulesToDom(newList, options);
    for (var _i = 0; _i < lastIdentifiers.length; _i++) {
      var _identifier = lastIdentifiers[_i];
      var _index = getIndexByIdentifier(_identifier);
      if (stylesInDOM[_index].references === 0) {
        stylesInDOM[_index].updater();
        stylesInDOM.splice(_index, 1);
      }
    }
    lastIdentifiers = newLastIdentifiers;
  };
};

/***/ }),

/***/ 72618:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .monaco-editor-overlaymessage {
	padding-bottom: 8px;
	z-index: 10000;
}

.monaco-editor .monaco-editor-overlaymessage.below {
	padding-bottom: 0;
	padding-top: 8px;
	z-index: 10000;
}

@keyframes fadeIn {
	from { opacity: 0; }
	to { opacity: 1; }
}
.monaco-editor .monaco-editor-overlaymessage.fadeIn {
	animation: fadeIn 150ms ease-out;
}

@keyframes fadeOut {
	from { opacity: 1; }
	to { opacity: 0; }
}
.monaco-editor .monaco-editor-overlaymessage.fadeOut {
	animation: fadeOut 100ms ease-out;
}

.monaco-editor .monaco-editor-overlaymessage .message {
	padding: 1px 4px;
	color: var(--vscode-inputValidation-infoForeground);
	background-color: var(--vscode-inputValidation-infoBackground);
	border: 1px solid var(--vscode-inputValidation-infoBorder);
}

.monaco-editor.hc-black .monaco-editor-overlaymessage .message,
.monaco-editor.hc-light .monaco-editor-overlaymessage .message {
	border-width: 2px;
}

.monaco-editor .monaco-editor-overlaymessage .anchor {
	width: 0 !important;
	height: 0 !important;
	border-color: transparent;
	border-style: solid;
	z-index: 1000;
	border-width: 8px;
	position: absolute;
}

.monaco-editor .monaco-editor-overlaymessage .anchor.top {
	border-bottom-color: var(--vscode-inputValidation-infoBorder);
}

.monaco-editor .monaco-editor-overlaymessage .anchor.below {
	border-top-color: var(--vscode-inputValidation-infoBorder);
}

.monaco-editor .monaco-editor-overlaymessage:not(.below) .anchor.top,
.monaco-editor .monaco-editor-overlaymessage.below .anchor.below {
	display: none;
}

.monaco-editor .monaco-editor-overlaymessage.below .anchor.top {
	display: inherit;
	top: -8px;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/message/browser/messageController.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,mBAAmB;CACnB,cAAc;AACf;;AAEA;CACC,iBAAiB;CACjB,gBAAgB;CAChB,cAAc;AACf;;AAEA;CACC,OAAO,UAAU,EAAE;CACnB,KAAK,UAAU,EAAE;AAClB;AACA;CACC,gCAAgC;AACjC;;AAEA;CACC,OAAO,UAAU,EAAE;CACnB,KAAK,UAAU,EAAE;AAClB;AACA;CACC,iCAAiC;AAClC;;AAEA;CACC,gBAAgB;CAChB,mDAAmD;CACnD,8DAA8D;CAC9D,0DAA0D;AAC3D;;AAEA;;CAEC,iBAAiB;AAClB;;AAEA;CACC,mBAAmB;CACnB,oBAAoB;CACpB,yBAAyB;CACzB,mBAAmB;CACnB,aAAa;CACb,iBAAiB;CACjB,kBAAkB;AACnB;;AAEA;CACC,6DAA6D;AAC9D;;AAEA;CACC,0DAA0D;AAC3D;;AAEA;;CAEC,aAAa;AACd;;AAEA;CACC,gBAAgB;CAChB,SAAS;AACV","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .monaco-editor-overlaymessage {\n\tpadding-bottom: 8px;\n\tz-index: 10000;\n}\n\n.monaco-editor .monaco-editor-overlaymessage.below {\n\tpadding-bottom: 0;\n\tpadding-top: 8px;\n\tz-index: 10000;\n}\n\n@keyframes fadeIn {\n\tfrom { opacity: 0; }\n\tto { opacity: 1; }\n}\n.monaco-editor .monaco-editor-overlaymessage.fadeIn {\n\tanimation: fadeIn 150ms ease-out;\n}\n\n@keyframes fadeOut {\n\tfrom { opacity: 1; }\n\tto { opacity: 0; }\n}\n.monaco-editor .monaco-editor-overlaymessage.fadeOut {\n\tanimation: fadeOut 100ms ease-out;\n}\n\n.monaco-editor .monaco-editor-overlaymessage .message {\n\tpadding: 1px 4px;\n\tcolor: var(--vscode-inputValidation-infoForeground);\n\tbackground-color: var(--vscode-inputValidation-infoBackground);\n\tborder: 1px solid var(--vscode-inputValidation-infoBorder);\n}\n\n.monaco-editor.hc-black .monaco-editor-overlaymessage .message,\n.monaco-editor.hc-light .monaco-editor-overlaymessage .message {\n\tborder-width: 2px;\n}\n\n.monaco-editor .monaco-editor-overlaymessage .anchor {\n\twidth: 0 !important;\n\theight: 0 !important;\n\tborder-color: transparent;\n\tborder-style: solid;\n\tz-index: 1000;\n\tborder-width: 8px;\n\tposition: absolute;\n}\n\n.monaco-editor .monaco-editor-overlaymessage .anchor.top {\n\tborder-bottom-color: var(--vscode-inputValidation-infoBorder);\n}\n\n.monaco-editor .monaco-editor-overlaymessage .anchor.below {\n\tborder-top-color: var(--vscode-inputValidation-infoBorder);\n}\n\n.monaco-editor .monaco-editor-overlaymessage:not(.below) .anchor.top,\n.monaco-editor .monaco-editor-overlaymessage.below .anchor.below {\n\tdisplay: none;\n}\n\n.monaco-editor .monaco-editor-overlaymessage.below .anchor.top {\n\tdisplay: inherit;\n\ttop: -8px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 72844:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgNavigate = function SvgNavigate(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.30371 10.8249C3.30371 10.3894 3.65682 10.0363 4.09241 10.0363H13.3596C13.7952 10.0363 14.1483 10.3894 14.1483 10.8249V20.0921C14.1483 20.5277 13.7952 20.8808 13.3596 20.8808H4.09241C3.65682 20.8808 3.30371 20.5277 3.30371 20.0921V10.8249ZM10.4483 13.1642C10.7533 12.8592 10.7533 12.3648 10.4483 12.0599C10.1434 11.755 9.64904 11.755 9.34411 12.0599L6.49756 14.9065C6.19263 15.2114 6.19263 15.7058 6.49756 16.0107L9.34411 18.8573C9.64904 19.1622 10.1434 19.1622 10.4483 18.8573C10.7533 18.5523 10.7533 18.058 10.4483 17.753L8.15391 15.4586L10.4483 13.1642Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M26.8037 20.0914C26.8037 20.5269 26.4506 20.88 26.0151 20.88L16.7495 20.88C16.314 20.88 15.9609 20.5269 15.9609 20.0914L15.9609 10.8258C15.9609 10.3903 16.314 10.0372 16.7495 10.0372L26.0151 10.0372C26.4506 10.0372 26.8037 10.3903 26.8037 10.8258L26.8037 20.0914ZM19.6602 17.7526C19.3554 18.0575 19.3554 18.5518 19.6602 18.8566C19.9651 19.1615 20.4594 19.1615 20.7643 18.8566L23.6103 16.0106C23.9152 15.7057 23.9152 15.2114 23.6103 14.9065L20.7643 12.0605C20.4594 11.7556 19.9651 11.7556 19.6602 12.0605C19.3554 12.3653 19.3554 12.8596 19.6602 13.1645L21.9543 15.4585L19.6602 17.7526Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgNavigate);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "6d5d9b5cdfc4352fb8a4f08899d0cd2a.svg");

/***/ }),

/***/ 72864:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSearchGrid = function SvgSearchGrid(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M9.35938 11.5605C9.35938 10.1868 10.473 9.07316 11.8467 9.07316C13.2205 9.07316 14.3341 10.1868 14.3341 11.5605C14.3341 12.9343 13.2205 14.0479 11.8467 14.0479C10.473 14.0479 9.35938 12.9343 9.35938 11.5605ZM11.8467 7.57316C9.64458 7.57316 7.85938 9.35836 7.85938 11.5605C7.85938 13.7627 9.64458 15.5479 11.8467 15.5479C12.5166 15.5479 13.1478 15.3827 13.702 15.0909L16.02 17.4089C16.3128 17.7018 16.7877 17.7018 17.0806 17.4089C17.3735 17.116 17.3735 16.6411 17.0806 16.3482L14.8805 14.1481C15.4751 13.4517 15.8341 12.548 15.8341 11.5605C15.8341 9.35836 14.0489 7.57316 11.8467 7.57316Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M2.87451 4.86534C2.87451 3.89884 3.65801 3.11534 4.62451 3.11534H19.4082C20.3747 3.11534 21.1582 3.89884 21.1582 4.86534V19.6491C21.1582 20.6156 20.3747 21.3991 19.4082 21.3991H4.62451C3.65801 21.3991 2.87451 20.6156 2.87451 19.6491V4.86534ZM4.62451 4.61534C4.48644 4.61534 4.37451 4.72727 4.37451 4.86534V11.4258H5.56974C5.98395 11.4258 6.31974 11.7615 6.31974 12.1758C6.31974 12.59 5.98395 12.9258 5.56974 12.9258H4.37451V19.6491C4.37451 19.7871 4.48644 19.8991 4.62451 19.8991H11.4097V18.7985C11.4097 18.3843 11.7455 18.0485 12.1597 18.0485C12.5739 18.0485 12.9097 18.3843 12.9097 18.7985V19.8991H19.4082C19.5463 19.8991 19.6582 19.7871 19.6582 19.6491V12.9258H18.7705C18.3563 12.9258 18.0205 12.59 18.0205 12.1758C18.0205 11.7616 18.3563 11.4258 18.7705 11.4258H19.6582V4.86534C19.6582 4.72727 19.5463 4.61534 19.4082 4.61534H12.9097V5.57296C12.9097 5.98717 12.5739 6.32296 12.1597 6.32296C11.7455 6.32296 11.4097 5.98717 11.4097 5.57296V4.61534H4.62451Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSearchGrid);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "ef75b1432076d1c51c1c86bbb66f57a8.svg");

/***/ }),

/***/ 72866:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   V: () => (/* binding */ getDefaultComponent)
/* harmony export */ });
/* harmony import */ var _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6203);
/* harmony import */ var _noodl_utils_NodeGraph__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(52877);


function getDefaultComponent(instance = _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_0__.ProjectModel.instance) {
    let component = instance.getComponentWithName('/Main') ||
        instance.getComponentWithName('/Start') ||
        instance.getComponentWithName('/Lesson');
    if (!component) {
        component = instance.getRootComponent();
    }
    if (!component) {
        component = instance.getComponents().find(_noodl_utils_NodeGraph__WEBPACK_IMPORTED_MODULE_1__/* .isComponentModel_BrowserRuntime */ .qb);
    }
    return component;
}


/***/ }),

/***/ 72915:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/* 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;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/scrollbar/media/scrollbars.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F,WAAW;AACX;CACC,eAAe;CACf,0BAA0B;AAC3B;;AAEA;CACC,UAAU;;CAEV,gEAAgE;CAChE,wBAAwB;;CAExB,gCAAgC;AACjC;AACA;CACC,UAAU;CACV,oBAAoB;AACrB;AACA;CACC,gCAAgC;AACjC;;AAEA,oCAAoC;AACpC;CACC,kBAAkB;CAClB,aAAa;AACd;AACA;CACC,cAAc;CACd,MAAM;CACN,SAAS;CACT,WAAW;CACX,WAAW;AACZ;AACA;CACC,cAAc;CACd,QAAQ;CACR,OAAO;CACP,YAAY;CACZ,UAAU;AACX;AACA;CACC,cAAc;CACd,MAAM;CACN,OAAO;CACP,WAAW;CACX,UAAU;AACX","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/* Arrows */\n.monaco-scrollable-element > .scrollbar > .scra {\n\tcursor: pointer;\n\tfont-size: 11px !important;\n}\n\n.monaco-scrollable-element > .visible {\n\topacity: 1;\n\n\t/* Background rule added for IE9 - to allow clicks on dom node */\n\tbackground:rgba(0,0,0,0);\n\n\ttransition: opacity 100ms linear;\n}\n.monaco-scrollable-element > .invisible {\n\topacity: 0;\n\tpointer-events: none;\n}\n.monaco-scrollable-element > .invisible.fade {\n\ttransition: opacity 800ms linear;\n}\n\n/* Scrollable Content Inset Shadow */\n.monaco-scrollable-element > .shadow {\n\tposition: absolute;\n\tdisplay: none;\n}\n.monaco-scrollable-element > .shadow.top {\n\tdisplay: block;\n\ttop: 0;\n\tleft: 3px;\n\theight: 3px;\n\twidth: 100%;\n}\n.monaco-scrollable-element > .shadow.left {\n\tdisplay: block;\n\ttop: 3px;\n\tleft: 0;\n\theight: 100%;\n\twidth: 3px;\n}\n.monaco-scrollable-element > .shadow.top-left-corner {\n\tdisplay: block;\n\ttop: 0;\n\tleft: 0;\n\theight: 3px;\n\twidth: 3px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 72927:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.FrameDivider-module__Root--VEp4y{position:relative;width:100%;height:100%}.FrameDivider-module__Container1--TcnP6{position:absolute;overflow:hidden}.FrameDivider-module__Container2--ejBF_{position:absolute;overflow:hidden}.FrameDivider-module__Divider--QHGvo{position:absolute;z-index:9;user-select:none;display:flex;justify-content:center;align-items:center}.FrameDivider-module__Divider--QHGvo.FrameDivider-module__is-horizontal--EqbJU{width:6px;top:0;bottom:0;cursor:col-resize}.FrameDivider-module__Divider--QHGvo.FrameDivider-module__is-horizontal--EqbJU .FrameDivider-module__DividerBorder--D0P5R{width:2px;height:100%}.FrameDivider-module__Divider--QHGvo.FrameDivider-module__is-vertical--bfPBx{height:6px;left:0;right:0;cursor:row-resize}.FrameDivider-module__Divider--QHGvo.FrameDivider-module__is-vertical--bfPBx .FrameDivider-module__DividerBorder--D0P5R{width:100%;height:2px}.FrameDivider-module__Divider--QHGvo:hover .FrameDivider-module__DividerHighlight--cf6hq{background-color:#fff;opacity:.5}.FrameDivider-module__DividerHighlight--cf6hq{position:absolute;width:100%;height:100%}.FrameDivider-module__DividerBorder--D0P5R{position:absolute;background-color:#000}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/FrameDivider/FrameDivider.module.scss"],"names":[],"mappings":"AAAA,kCACE,iBAAA,CACA,UAAA,CACA,WAAA,CAGF,wCACE,iBAAA,CACA,eAAA,CAGF,wCACE,iBAAA,CACA,eAAA,CAGF,qCACE,iBAAA,CACA,SAAA,CACA,gBAAA,CAEA,YAAA,CACA,sBAAA,CACA,kBAAA,CAEA,+EACE,SAAA,CACA,KAAA,CACA,QAAA,CACA,iBAAA,CAEA,0HACE,SAAA,CACA,WAAA,CAIJ,6EACE,UAAA,CACA,MAAA,CACA,OAAA,CACA,iBAAA,CAEA,wHACE,UAAA,CACA,UAAA,CAIJ,yFACE,qBAAA,CACA,UAAA,CAIJ,8CACE,iBAAA,CACA,UAAA,CACA,WAAA,CAGF,2CACE,iBAAA,CACA,qBAAA","sourcesContent":[".Root {\n  position: relative;\n  width: 100%;\n  height: 100%;\n}\n\n.Container1 {\n  position: absolute;\n  overflow: hidden;\n}\n\n.Container2 {\n  position: absolute;\n  overflow: hidden;\n}\n\n.Divider {\n  position: absolute;\n  z-index: 9;\n  user-select: none;\n\n  display: flex;\n  justify-content: center;\n  align-items: center;\n\n  &.is-horizontal {\n    width: 6px;\n    top: 0;\n    bottom: 0;\n    cursor: col-resize;\n\n    .DividerBorder {\n      width: 2px;\n      height: 100%;\n    }\n  }\n\n  &.is-vertical {\n    height: 6px;\n    left: 0;\n    right: 0;\n    cursor: row-resize;\n\n    .DividerBorder {\n      width: 100%;\n      height: 2px;\n    }\n  }\n\n  &:hover .DividerHighlight {\n    background-color: white;\n    opacity: 0.5;\n  }\n}\n\n.DividerHighlight {\n  position: absolute;\n  width: 100%;\n  height: 100%;\n}\n\n.DividerBorder {\n  position: absolute;\n  background-color: black;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `FrameDivider-module__Root--VEp4y`,
	"Container1": `FrameDivider-module__Container1--TcnP6`,
	"Container2": `FrameDivider-module__Container2--ejBF_`,
	"Divider": `FrameDivider-module__Divider--QHGvo`,
	"is-horizontal": `FrameDivider-module__is-horizontal--EqbJU`,
	"DividerBorder": `FrameDivider-module__DividerBorder--D0P5R`,
	"is-vertical": `FrameDivider-module__is-vertical--bfPBx`,
	"DividerHighlight": `FrameDivider-module__DividerHighlight--cf6hq`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 73010:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDeviceDesktop = function SvgDeviceDesktop(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.4858 16.2648C21.4858 16.7927 21.0579 17.2207 20.5299 17.2207H12H3.4707C2.94276 17.2207 2.51478 16.7927 2.51478 16.2648V14.4559H21.4858V16.2648ZM12.75 18.7207H20.5299C21.8863 18.7207 22.9858 17.6212 22.9858 16.2648V4.32335C22.9858 2.96698 21.8863 1.86743 20.5299 1.86743H3.4707C2.11433 1.86743 1.01478 2.96698 1.01478 4.32335V13.6751C1.01437 13.6853 1.01416 13.6956 1.01416 13.7059C1.01416 13.7162 1.01437 13.7265 1.01478 13.7367V16.2648C1.01478 17.6212 2.11433 18.7207 3.4707 18.7207H11.25V20.6326H8.58838C8.17417 20.6326 7.83838 20.9683 7.83838 21.3826C7.83838 21.7968 8.17417 22.1326 8.58838 22.1326H11.9966C11.9977 22.1326 11.9989 22.1326 12 22.1326C12.0011 22.1326 12.0023 22.1326 12.0034 22.1326H15.4121C15.8263 22.1326 16.1621 21.7968 16.1621 21.3826C16.1621 20.9683 15.8263 20.6326 15.4121 20.6326H12.75V18.7207ZM2.51478 4.32335V12.9559H21.4858V4.32335C21.4858 3.79541 21.0579 3.36743 20.5299 3.36743H3.4707C2.94276 3.36743 2.51478 3.79541 2.51478 4.32335Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDeviceDesktop);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "5cd15182be57c13dda0102f8c9135c1d.svg");

/***/ }),

/***/ 73186:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Select-module__Root--_9Nre{position:relative;flex-grow:1}.Select-module__Root--_9Nre.Select-module__is-color-theme-transparent--CsaDU{background-color:rgba(0,0,0,0)}.Select-module__Root--_9Nre.Select-module__is-color-theme-dark--kEwQV{background-color:var(--theme-color-bg-2)}.Select-module__Root--_9Nre.Select-module__is-color-theme-dark-lighter--_fz1g{background-color:var(--theme-color-bg-3)}.Select-module__Root--_9Nre.Select-module__has-bottom-spacing--v_8Xq{margin-bottom:15px}.Select-module__Root--_9Nre.Select-module__is-focused--BhtLy{background-color:var(--theme-color-bg-1)}.Select-module__DisplayContainer--cPhRP{display:flex;justify-content:space-between;transition:opacity var(--speed-turbo);cursor:pointer;padding:10px 10px 9px;align-items:center}.Select-module__DisplayText--qx_Nj{font-family:var(--font-family);color:var(--theme-color-fg-default);font-size:14px;margin-top:-1px}.Select-module__DisplayText--qx_Nj.Select-module__is-size-small--JWgGd{font-size:12px}.Select-module__DisplayContainer--cPhRP:hover .Select-module__DisplayText--qx_Nj{color:var(--theme-color-fg-default-contrast)}.Select-module__DisplayText--qx_Nj.Select-module__is-placeholder--R4fgf{color:var(--theme-color-fg-default-shy)}.Select-module__Root--_9Nre.Select-module__is-focused--BhtLy .Select-module__DisplayText--qx_Nj{color:var(--theme-color-fg-highlight)}.Select-module__Icon--TgrVC{margin-top:-4px;margin-bottom:-4px;margin-right:-6px}.Select-module__Icon--TgrVC path{fill:var(--theme-color-fg-default)}.Select-module__DisplayContainer--cPhRP:hover .Select-module__Icon--TgrVC path{fill:var(--theme-color-fg-default-contrast)}.Select-module__OptionsContainer--A3VAB.Select-module__is-options-pushing-siblings--EfcQJ{position:relative}.Select-module__OptionsContainer--A3VAB.Select-module__is-options-overlaid--tiZP4{position:absolute;left:0;right:0;top:100%;z-index:1}.Select-module__OptionsList--Qoofa{padding:10px;max-height:200px;overflow-y:overlay;text-align:left}.Select-module__OptionsList--Qoofa.Select-module__is-color-theme-dark--kEwQV{background-color:var(--theme-color-bg-2);border-top:1px solid var(--theme-color-bg-3)}.Select-module__OptionsList--Qoofa.Select-module__is-color-theme-dark-lighter--_fz1g{background-color:var(--theme-color-bg-3);border-top:1px solid var(--theme-color-fg-muted)}.Select-module__Option--HS1ux{color:var(--theme-color-fg-default);opacity:.9;transition:color var(--speed-turbo);font-family:var(--font-family);font-size:14px;cursor:pointer}.Select-module__Option--HS1ux.Select-module__is-size-small--JWgGd{font-size:12px}.Select-module__Option--HS1ux:not(:last-child){padding-bottom:8px}.Select-module__Option--HS1ux.Select-module__is-disabled--rFzPv{color:var(--theme-color-fg-muted);cursor:not-allowed}.Select-module__Option--HS1ux.Select-module__is-disabled--rFzPv:active{color:var(--theme-color-danger)}.Select-module__Option--HS1ux.Select-module__is-selected--Yny4R:after{content:"⚈";display:inline-block;padding-left:10px;color:var(--theme-color-primary)}.Select-module__Option--HS1ux:hover:not(.Select-module__is-disabled--rFzPv){opacity:1;color:var(--theme-color-primary)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/Select/Select.module.scss"],"names":[],"mappings":"AAAA,4BAGA,iBACE,CAAA,WACA,CAAA,6EAEA,8BACE,CAAA,sEAGF,wCACE,CAAA,8EAGF,wCACE,CAAA,qEAGF,kBACE,CAAA,6DAGF,wCACE,CAAA,wCAIJ,YACE,CAAA,6BACA,CAAA,qCACA,CAAA,cACA,CAAA,qBACA,CAAA,kBACA,CAAA,mCAGF,8BACE,CAAA,mCACA,CAAA,cACA,CAAA,eACA,CAAA,uEAEA,cACE,CAAA,iFAGF,4CACE,CAAA,wEAGF,uCACE,CAAA,gGAGF,qCACE,CAAA,4BAIJ,eACE,CAAA,kBACA,CAAA,iBACA,CAAA,iCAEA,kCACE,CAAA,+EAEA,2CACE,CAAA,0FAMJ,iBACE,CAAA,kFAGF,iBACE,CAAA,MACA,CAAA,OACA,CAAA,QACA,CAAA,SACA,CAAA,mCAIJ,YAxFa,CAAA,gBA0FX,CAAA,kBACA,CAAA,eACA,CAAA,6EAEA,wCACE,CAAA,4CACA,CAAA,qFAGF,wCACE,CAAA,gDACA,CAAA,8BAIJ,mCACE,CAAA,UACA,CAAA,mCACA,CAAA,8BACA,CAAA,cACA,CAAA,cACA,CAAA,kEAEA,cACE,CAAA,+CAGF,kBACE,CAAA,gEAGF,iCACE,CAAA,kBACA,CAAA,uEAEA,+BACE,CAAA,sEAKF,WACE,CAAA,oBACA,CAAA,iBACA,CAAA,gCACA,CAAA,4EAIJ,SACE,CAAA,gCACA","sourcesContent":["$_x-padding: 10px;\n$_y-padding: 8px;\n\n.Root {\n  position: relative;\n  flex-grow: 1;\n\n  &.is-color-theme-transparent {\n    background-color: transparent;\n  }\n\n  &.is-color-theme-dark {\n    background-color: var(--theme-color-bg-2);\n  }\n\n  &.is-color-theme-dark-lighter {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.has-bottom-spacing {\n    margin-bottom: 15px;\n  }\n\n  &.is-focused {\n    background-color: var(--theme-color-bg-1);\n  }\n}\n\n.DisplayContainer {\n  display: flex;\n  justify-content: space-between;\n  transition: opacity var(--speed-turbo);\n  cursor: pointer;\n  padding: 10px $_x-padding 9px;\n  align-items: center;\n}\n\n.DisplayText {\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-default);\n  font-size: 14px;\n  margin-top: -1px;\n\n  &.is-size-small {\n    font-size: 12px;\n  }\n\n  .DisplayContainer:hover & {\n    color: var(--theme-color-fg-default-contrast);\n  }\n\n  &.is-placeholder {\n    color: var(--theme-color-fg-default-shy);\n  }\n\n  .Root.is-focused & {\n    color: var(--theme-color-fg-highlight);\n  }\n}\n\n.Icon {\n  margin-top: calc($_y-padding * -0.5);\n  margin-bottom: calc($_y-padding * -0.5);\n  margin-right: calc($_x-padding * -0.6);\n\n  path {\n    fill: var(--theme-color-fg-default);\n\n    .DisplayContainer:hover & {\n      fill: var(--theme-color-fg-default-contrast);\n    }\n  }\n}\n\n.OptionsContainer {\n  &.is-options-pushing-siblings {\n    position: relative;\n  }\n\n  &.is-options-overlaid {\n    position: absolute;\n    left: 0;\n    right: 0;\n    top: 100%;\n    z-index: 1;\n  }\n}\n\n.OptionsList {\n  padding: $_x-padding;\n  max-height: 200px;\n  overflow-y: overlay;\n  text-align: left;\n\n  &.is-color-theme-dark {\n    background-color: var(--theme-color-bg-2);\n    border-top: 1px solid var(--theme-color-bg-3);\n  }\n\n  &.is-color-theme-dark-lighter {\n    background-color: var(--theme-color-bg-3);\n    border-top: 1px solid var(--theme-color-fg-muted);\n  }\n}\n\n.Option {\n  color: var(--theme-color-fg-default);\n  opacity: 0.9;\n  transition: color var(--speed-turbo);\n  font-family: var(--font-family);\n  font-size: 14px;\n  cursor: pointer;\n\n  &.is-size-small {\n    font-size: 12px;\n  }\n\n  &:not(:last-child) {\n    padding-bottom: 8px;\n  }\n\n  &.is-disabled {\n    color: var(--theme-color-fg-muted);\n    cursor: not-allowed;\n\n    &:active {\n      color: var(--theme-color-danger);\n    }\n  }\n\n  &.is-selected {\n    &:after {\n      content: '⚈';\n      display: inline-block;\n      padding-left: 10px;\n      color: var(--theme-color-primary);\n    }\n  }\n\n  &:hover:not(.is-disabled) {\n    opacity: 1;\n    color: var(--theme-color-primary);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Select-module__Root--_9Nre`,
	"is-color-theme-transparent": `Select-module__is-color-theme-transparent--CsaDU`,
	"is-color-theme-dark": `Select-module__is-color-theme-dark--kEwQV`,
	"is-color-theme-dark-lighter": `Select-module__is-color-theme-dark-lighter--_fz1g`,
	"has-bottom-spacing": `Select-module__has-bottom-spacing--v_8Xq`,
	"is-focused": `Select-module__is-focused--BhtLy`,
	"DisplayContainer": `Select-module__DisplayContainer--cPhRP`,
	"DisplayText": `Select-module__DisplayText--qx_Nj`,
	"is-size-small": `Select-module__is-size-small--JWgGd`,
	"is-placeholder": `Select-module__is-placeholder--R4fgf`,
	"Icon": `Select-module__Icon--TgrVC`,
	"OptionsContainer": `Select-module__OptionsContainer--A3VAB`,
	"is-options-pushing-siblings": `Select-module__is-options-pushing-siblings--EfcQJ`,
	"is-options-overlaid": `Select-module__is-options-overlaid--tiZP4`,
	"OptionsList": `Select-module__OptionsList--Qoofa`,
	"Option": `Select-module__Option--HS1ux`,
	"is-disabled": `Select-module__is-disabled--rFzPv`,
	"is-selected": `Select-module__is-selected--Yny4R`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 73504:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRoll = function SvgRoll(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M6.75011 4.75V6.5C6.75011 6.91421 6.41433 7.25 6.00011 7.25C5.5859 7.25 5.25011 6.91421 5.25011 6.5V4.75C5.25011 4.41627 5.34477 4.0653 5.55332 3.77854C5.76451 3.48816 6.11095 3.25 6.54557 3.25L17.4547 3.25C17.8893 3.25 18.2357 3.48816 18.4469 3.77854C18.6555 4.0653 18.7501 4.41627 18.7501 4.75V11.226L20.4643 9.47528C20.7541 9.17932 21.229 9.17432 21.525 9.46412C21.8209 9.75391 21.8259 10.2288 21.5361 10.5247L18.5986 13.5247C18.4594 13.6669 18.2695 13.7479 18.0705 13.75C17.8716 13.752 17.68 13.675 17.5379 13.5358L14.4753 10.5358C14.1794 10.2459 14.1745 9.77108 14.4643 9.47518C14.7542 9.17927 15.229 9.17437 15.5249 9.46422L17.2501 11.1541L17.2501 4.75L6.75011 4.75ZM5.92968 10.25C6.12861 10.248 6.32021 10.325 6.46233 10.4642L9.52494 13.4642C9.82084 13.7541 9.82575 14.2289 9.53589 14.5248C9.24604 14.8207 8.77119 14.8256 8.47529 14.5358L6.75011 12.8459V19.25H17.2501V17.5C17.2501 17.0858 17.5859 16.75 18.0001 16.75C18.4143 16.75 18.7501 17.0858 18.7501 17.5V19.25C18.7501 19.5837 18.6555 19.9347 18.4469 20.2215C18.2357 20.5118 17.8893 20.75 17.4547 20.75H6.54557C6.11095 20.75 5.76451 20.5118 5.55332 20.2215C5.34477 19.9347 5.25011 19.5837 5.25011 19.25V12.774L3.53588 14.5247C3.24609 14.8207 2.77124 14.8257 2.47528 14.5359C2.17932 14.2461 2.17432 13.7712 2.46412 13.4753L5.40162 10.4753C5.5408 10.3331 5.73075 10.2521 5.92968 10.25Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRoll);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "7cb7233f2a967e8847fd40b32a21d074.svg");

/***/ }),

/***/ 73622:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  sT: () => (/* binding */ getMergeBase),
  X: () => (/* binding */ isMergeHeadSet),
  h1: () => (/* binding */ merge),
  pR: () => (/* binding */ mergeTree),
  sw: () => (/* binding */ mergeTreeCommit)
});

// UNUSED EXPORTS: MergeResult, abortMerge, isSquashMsgSet

// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(79896);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
// EXTERNAL MODULE: external "path"
var external_path_ = __webpack_require__(16928);
// EXTERNAL MODULE: ../noodl-git/src/core/client.ts + 14 modules
var client = __webpack_require__(85869);
// EXTERNAL MODULE: external "dugite"
var external_dugite_ = __webpack_require__(81882);
// EXTERNAL MODULE: ../noodl-git/src/core/models/computed-action.ts
var computed_action = __webpack_require__(89642);
;// ../noodl-git/src/core/merge-tree-parser.ts

function updateCurrentMergeEntry(entry, context, blobSource) {
    const currentMergeEntry = entry || {
        context,
        diff: ''
    };
    const blob = {
        sha: blobSource.sha,
        mode: blobSource.mode,
        path: blobSource.path
    };
    switch (blobSource.type) {
        case 'base':
            return {
                ...currentMergeEntry,
                base: blob
            };
        case 'result':
            return {
                ...currentMergeEntry,
                result: blob
            };
        case 'our':
            return {
                ...currentMergeEntry,
                our: blob
            };
        case 'their':
            return {
                ...currentMergeEntry,
                their: blob
            };
        default:
            return currentMergeEntry;
    }
}
// the merge-tree output is a collection of entries like this
//
// changed in both
//  base   100644 f69fbc5c40409a1db7a3f8353bfffe46a21d6054 atom/browser/resources/mac/Info.plist
//  our    100644 9094f0f7335edf833d51f688851e6a105de60433 atom/browser/resources/mac/Info.plist
//  their  100644 2dd8bc646cff3869557549a39477e30022e6cfdd atom/browser/resources/mac/Info.plist
// @@ -17,9 +17,15 @@
// <key>CFBundleIconFile</key>
// <string>electron.icns</string>
// <key>CFBundleVersion</key>
// +<<<<<<< .our
// <string>4.0.0</string>
// <key>CFBundleShortVersionString</key>
// <string>4.0.0</string>
// +=======
// +  <string>1.4.16</string>
// +  <key>CFBundleShortVersionString</key>
// +  <string>1.4.16</string>
// +>>>>>>> .their
// <key>LSApplicationCategoryType</key>
//<string>public.app-category.developer-tools</string>
// <key>LSMinimumSystemVersion</key>
// The first line for each entry is what I'm referring to as the the header
// This regex filters on the known entries that can appear
const contextHeaderRe = /^(merged|added in remote|removed in remote|changed in both|removed in local|added in both)$/;
// the rest of the header is made up of a number of entries formatted like this
//
//  base   100644 f69fbc5c40409a1db7a3f8353bfffe46a21d6054 atom/browser/resources/mac/Info.plist
//
// this regex let's us extract the blob details - the filename may also change
// as part of the merge if files are moved or renamed
const blobEntryRe = /^\s{2}(result|our|their|base)\s+(\d{6})\s([0-9a-f]{40})\s(.+)$/;
/**
 * Parse the Git output of a merge-tree command to identify whether it
 * has detected any conflicts between the branches to be merged
 *
 * @param text the stdout from a `git merge-tree` command
 *
 */
function parseMergeTreeResult(text) {
    const entries = new Array();
    const lines = text.split('\n');
    let mergeEntryHeader;
    let currentMergeEntry;
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        const headerMatch = contextHeaderRe.exec(line);
        if (headerMatch != null) {
            mergeEntryHeader = headerMatch[1];
            // push the previous entry, if defined, into the array
            if (currentMergeEntry != null) {
                entries.push(currentMergeEntry);
                currentMergeEntry = undefined;
            }
            continue;
        }
        // the next lines are a number of merge result entries
        // pointing to blobs representing the source blob
        // and the resulting blob generated by the merge
        const blobMatch = blobEntryRe.exec(line);
        if (blobMatch != null) {
            const type = blobMatch[1];
            const mode = blobMatch[2];
            const sha = blobMatch[3];
            const path = blobMatch[4];
            const blob = {
                type,
                mode,
                sha,
                path
            };
            if (mergeEntryHeader == null) {
                console.warn(`An unknown header was set while trying to parse the blob on line ${i}`);
                continue;
            }
            switch (type) {
                case 'base':
                case 'result':
                case 'our':
                case 'their':
                    currentMergeEntry = updateCurrentMergeEntry(currentMergeEntry, mergeEntryHeader, blob);
                    break;
                default:
                    throw new Error(`invalid state - unexpected entry ${type} found when parsing rows`);
            }
            continue;
        }
        if (currentMergeEntry == null) {
            throw new Error(`invalid state - trying to append the diff to a merge entry that isn't defined on line ${i}`);
        }
        else {
            const currentDiff = currentMergeEntry.diff;
            const newDiff = currentDiff + line + '\n';
            currentMergeEntry = {
                ...currentMergeEntry,
                diff: newDiff
            };
            const lineHasConflictMarker = line.startsWith('+<<<<<<<') || line.startsWith('+=======') || line.startsWith('+>>>>>>>');
            if (lineHasConflictMarker) {
                currentMergeEntry = {
                    ...currentMergeEntry,
                    hasConflicts: true
                };
            }
        }
    }
    // ensure the last entry is pushed onto the array
    if (currentMergeEntry != null) {
        entries.push(currentMergeEntry);
        currentMergeEntry = undefined;
    }
    const entriesWithConflicts = entries.filter((e) => e.hasConflicts || false);
    if (entriesWithConflicts.length > 0) {
        return {
            kind: computed_action/* ComputedAction */.Y.Conflicts,
            conflictedFiles: entriesWithConflicts.length,
            conflictedEntries: entriesWithConflicts
        };
    }
    else {
        return { kind: computed_action/* ComputedAction */.Y.Clean, entries };
    }
}

;// ../noodl-git/src/core/merge.ts






var MergeResult;
(function (MergeResult) {
    /** The merge completed successfully */
    MergeResult[MergeResult["Success"] = 0] = "Success";
    /**
     * The merge was a noop since the current branch
     * was already up to date with the target branch.
     */
    MergeResult[MergeResult["AlreadyUpToDate"] = 1] = "AlreadyUpToDate";
    /**
     * The merge failed, likely due to conflicts.
     */
    MergeResult[MergeResult["Failed"] = 2] = "Failed";
})(MergeResult || (MergeResult = {}));
/** Merge the named branch into the current branch. */
async function merge(repositoryDir, branch, options) {
    const args = ['merge'];
    if (options.message) {
        args.push('-m', options.message);
    }
    if (options.isSquash) {
        args.push('--squash');
    }
    else if (options.noFastForward) {
        // No Fast Forward, meaning that there will always be a merge commit.
        args.push('--no-ff');
    }
    if (options.strategy) {
        args.push('--strategy', options.strategy);
    }
    if (options.strategyOption) {
        args.push('--strategy-option', options.strategyOption);
    }
    args.push(branch);
    const { exitCode, output } = await (0,client/* git */.$)(args, repositoryDir, 'merge', {
        expectedErrors: new Set([external_dugite_.GitError.MergeConflicts])
    });
    if (exitCode !== 0) {
        return MergeResult.Failed;
    }
    if (options.isSquash && !options.squashNoCommit) {
        const squashArgs = ['commit', '--no-edit'];
        if (options.message) {
            squashArgs.push('-m', options.message);
        }
        const { exitCode } = await (0,client/* git */.$)(squashArgs, repositoryDir, 'merge');
        if (exitCode !== 0) {
            return MergeResult.Failed;
        }
    }
    return output.toString() === noopMergeMessage ? MergeResult.AlreadyUpToDate : MergeResult.Success;
}
const noopMergeMessage = 'Already up to date.\n';
/**
 * Find the base commit between two commit-ish identifiers
 *
 * @returns the commit id of the merge base, or null if the two commit-ish
 *          identifiers do not have a common base
 */
async function getMergeBase(repositoryDir, firstCommitish, secondCommitish) {
    const process = await (0,client/* git */.$)(['merge-base', firstCommitish, secondCommitish], repositoryDir, 'merge-base', {
        // - 1 is returned if a common ancestor cannot be resolved
        // - 128 is returned if a ref cannot be found
        //   "warning: ignoring broken ref refs/remotes/origin/main."
        successExitCodes: new Set([0, 1, 128])
    });
    if (process.exitCode === 1 || process.exitCode === 128) {
        return null;
    }
    return process.output.toString().trim();
}
/**
 * Generate the merge result from two branches in a repository
 *
 * @param repository The repository containing the branches to merge
 * @param ours The current branch
 * @param theirs Another branch to merge into the current branch
 */
async function mergeTree(repositoryDir, ours, theirs) {
    const mergeBase = await getMergeBase(repositoryDir, ours.tip.sha, theirs.tip.sha);
    if (mergeBase === null) {
        return { kind: computed_action/* ComputedAction */.Y.Invalid };
    }
    if (mergeBase === ours.tip.sha || mergeBase === theirs.tip.sha) {
        return { kind: computed_action/* ComputedAction */.Y.Clean, entries: [] };
    }
    const result = await (0,client/* git */.$)(['merge-tree', mergeBase, ours.tip.sha, theirs.tip.sha], repositoryDir, 'mergeTree');
    const output = result.output.toString();
    if (output.length === 0) {
        // the merge commit will be empty - this is fine!
        return { kind: computed_action/* ComputedAction */.Y.Clean, entries: [] };
    }
    return parseMergeTreeResult(output);
}
async function mergeTreeCommit(repositoryDir, oursCommitish, theirsCommitish) {
    const mergeBase = await getMergeBase(repositoryDir, oursCommitish, theirsCommitish);
    if (mergeBase === null) {
        return { kind: computed_action/* ComputedAction */.Y.Invalid };
    }
    if (mergeBase === oursCommitish || mergeBase === theirsCommitish) {
        return { kind: computed_action/* ComputedAction */.Y.Clean, entries: [] };
    }
    const result = await (0,client/* git */.$)(['merge-tree', mergeBase, oursCommitish, theirsCommitish], repositoryDir, 'mergeTree');
    const output = result.output.toString();
    if (output.length === 0) {
        // the merge commit will be empty - this is fine!
        return { kind: computed_action/* ComputedAction */.Y.Clean, entries: [] };
    }
    return parseMergeTreeResult(output);
}
/**
 * Abort a mid-flight (conflicted) merge
 *
 * @param repository where to abort the merge
 */
async function abortMerge(repositoryDir) {
    await git(['merge', '--abort'], repositoryDir, 'abortMerge');
}
/**
 * Check the `.git/MERGE_HEAD` file exists in a repository to confirm
 * that it is in a conflicted state.
 */
async function isMergeHeadSet(repositoryDir) {
    const path = external_path_.join(repositoryDir, '.git', 'MERGE_HEAD');
    // NOTE: access calls reject, which causes issues with devtools.
    return new Promise((resolve) => {
        resolve(external_fs_default().existsSync(path));
    });
}
/**
 * Check the `.git/SQUASH_MSG` file exists in a repository
 * This would indicate we did a merge --squash and have not committed.. indicating
 * we have detected a conflict.
 *
 * Note: If we abort the merge, this doesn't get cleared automatically which
 * could lead to this being erroneously available in a non merge --squashing scenario.
 */
async function isSquashMsgSet(repositoryDir) {
    const path = Path.join(repositoryDir, '.git', 'SQUASH_MSG');
    // NOTE: access calls reject, which causes issues with devtools.
    return new Promise((resolve) => {
        resolve(fs.existsSync(path));
    });
}


/***/ }),

/***/ 73656:
/***/ ((module) => {

"use strict";


/* istanbul ignore next  */
function styleTagTransform(css, styleElement) {
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = css;
  } else {
    while (styleElement.firstChild) {
      styleElement.removeChild(styleElement.firstChild);
    }
    styleElement.appendChild(document.createTextNode(css));
  }
}
module.exports = styleTagTransform;

/***/ }),

/***/ 73979:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPencilLine = function SvgPencilLine(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M8.82135 21.3983H4.63135C4.23135 21.3983 3.85135 21.2383 3.57135 20.9583C3.29135 20.6783 3.13135 20.2883 3.13135 19.8983V15.7083C3.13135 15.5183 3.17135 15.3183 3.24135 15.1383C3.31135 14.9583 3.42135 14.7883 3.57135 14.6483L14.8213 3.39833C14.9513 3.25833 15.1213 3.14833 15.3013 3.06833C15.6813 2.90833 16.0913 2.91833 16.4613 3.06833C16.6513 3.14833 16.8113 3.25833 16.9513 3.39833L21.1313 7.57833C21.2713 7.71833 21.3813 7.87833 21.4613 8.06833C21.5413 8.24833 21.5813 8.44833 21.5813 8.64833C21.5813 8.84833 21.5413 9.04833 21.4613 9.22833C21.3913 9.40833 21.2813 9.56833 21.1313 9.70833L18.703 12.1367C18.6915 12.1498 18.6796 12.1627 18.667 12.1752C18.6545 12.1877 18.6417 12.1997 18.6285 12.2111L9.88135 20.9583C9.76154 21.0781 9.61976 21.176 9.46854 21.2456C9.38507 21.2945 9.29417 21.3258 9.20117 21.3397C9.07885 21.3712 8.95224 21.3883 8.82135 21.3883V21.3983ZM7.32952 19.8983H4.63135V17.2002L5.98103 18.5498L5.98139 18.5502L5.98175 18.5506L7.32952 19.8983ZM9.13609 19.5836L17.0754 11.6442L15.5117 10.0805L7.57238 18.0199L9.13609 19.5836ZM14.4511 9.01987L6.51172 16.9592L4.94609 15.3936L12.8854 7.45424L14.4511 9.01987ZM16.042 8.48954L18.1361 10.5836L20.0713 8.64833L15.8813 4.45833L13.9461 6.39358L16.042 8.48954Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPencilLine);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "67e56c358555030611320fa69f26e95d.svg");

/***/ }),

/***/ 74065:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PropertyPanelButton-module__Root--xPI2A{display:flex;flex-direction:column}.PropertyPanelButton-module__Button--ajncO{font-family:var(--font-family);color:var(--theme-color-fg-default);font-size:12px;text-align:center;background-color:var(--theme-color-bg-3);padding:6px 8px 7px;border:none;cursor:pointer}.PropertyPanelButton-module__Button--ajncO:hover{background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-highlight)}.PropertyPanelButton-module__Button--ajncO.PropertyPanelButton-module__is-primary--NKnCk{font-weight:600;color:var(--theme-color-bg-1);background-color:var(--theme-color-primary)}.PropertyPanelButton-module__Button--ajncO.PropertyPanelButton-module__is-primary--NKnCk:hover{background-color:var(--theme-color-primary-highlight)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/property-panel/PropertyPanelButton/PropertyPanelButton.module.scss","webpack://./../noodl-core-ui/src/styles/scss-variables/length.scss"],"names":[],"mappings":"AAEA,yCACE,YAAA,CACA,qBAAA,CAGF,2CACE,8BAAA,CACA,mCAAA,CACA,cAAA,CACA,iBAAA,CACA,wCAAA,CACA,mBCb6B,CDc7B,WAAA,CACA,cAAA,CAEA,iDACE,wCAAA,CACA,qCAAA,CAGF,yFACE,eAAA,CACA,6BAAA,CACA,2CAAA,CAEA,+FACE,qDAAA","sourcesContent":["@use '../../../styles/scss-variables/length.scss';\n\n.Root {\n  display: flex;\n  flex-direction: column;\n}\n\n.Button {\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n  text-align: center;\n  background-color: var(--theme-color-bg-3);\n  padding: length.$property-panel-input-padding;\n  border: none;\n  cursor: pointer;\n\n  &:hover {\n    background-color: var(--theme-color-bg-1);\n    color: var(--theme-color-fg-highlight);\n  }\n\n  &.is-primary {\n    font-weight: 600;\n    color: var(--theme-color-bg-1);\n    background-color: var(--theme-color-primary);\n\n    &:hover {\n      background-color: var(--theme-color-primary-highlight);\n    }\n  }\n}\n","$property-panel-input-padding: 6px 8px 7px;\r\n$property-panel-input-size: 28px;\r\n$property-panel-small-xy-padding: 4px;\r\n\r\n$global-input-size: 36px;\r\n$global-input-size-small: 28px;\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PropertyPanelButton-module__Root--xPI2A`,
	"Button": `PropertyPanelButton-module__Button--ajncO`,
	"is-primary": `PropertyPanelButton-module__is-primary--NKnCk`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 74082:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.HighlightedNode-module__highlightedNode--XJqFJ{position:absolute;pointer-events:none;border:3px solid;border-radius:8px;box-sizing:border-box;z-index:1000}.HighlightedNode-module__highlightedNode--XJqFJ .HighlightedNode-module__label--q5tcJ{position:absolute;top:-24px;left:50%;transform:translateX(-50%);padding:4px 8px;background:rgba(0,0,0,.8);color:#fff;font-size:11px;font-weight:600;border-radius:4px;white-space:nowrap;pointer-events:none}.HighlightedNode-module__glow--ApMP4{animation:HighlightedNode-module__glow-breathe--DZ3aL 2s ease-in-out infinite}.HighlightedNode-module__pulse--gjRES{animation:HighlightedNode-module__pulse-scale--vP4Gl 1.5s ease-in-out infinite}@keyframes HighlightedNode-module__glow-breathe--DZ3aL{0%,100%{opacity:.8}50%{opacity:1}}@keyframes HighlightedNode-module__pulse-scale--vP4Gl{0%,100%{transform:scale(1);opacity:.9}50%{transform:scale(1.02);opacity:1}}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightedNode.module.scss"],"names":[],"mappings":"AAMA,gDACE,iBAAA,CACA,mBAAA,CACA,gBAAA,CACA,iBAAA,CACA,qBAAA,CACA,YAAA,CAGA,sFACE,iBAAA,CACA,SAAA,CACA,QAAA,CACA,0BAAA,CACA,eAAA,CACA,yBAAA,CACA,UAAA,CACA,cAAA,CACA,eAAA,CACA,iBAAA,CACA,kBAAA,CACA,mBAAA,CAWJ,qCAEE,6EAAA,CAIF,sCACE,8EAAA,CAIF,uDACE,QAEE,UAAA,CAEF,IACE,SAAA,CAAA,CAKJ,sDACE,QAEE,kBAAA,CACA,UAAA,CAEF,IACE,qBAAA,CACA,SAAA,CAAA","sourcesContent":["/**\n * HighlightedNode styles\n *\n * Styles for node highlight overlays with different visual effects.\n */\n\n.highlightedNode {\n  position: absolute;\n  pointer-events: none;\n  border: 3px solid;\n  border-radius: 8px;\n  box-sizing: border-box;\n  z-index: 1000;\n\n  // Label styling\n  .label {\n    position: absolute;\n    top: -24px;\n    left: 50%;\n    transform: translateX(-50%);\n    padding: 4px 8px;\n    background: rgba(0, 0, 0, 0.8);\n    color: white;\n    font-size: 11px;\n    font-weight: 600;\n    border-radius: 4px;\n    white-space: nowrap;\n    pointer-events: none;\n  }\n}\n\n// Solid style - simple static border\n.solid {\n  // Base styles applied from .highlightedNode\n  // No animations\n}\n\n// Glow style - constant glow effect\n.glow {\n  // Box-shadow applied inline via style prop for dynamic color\n  animation: glow-breathe 2s ease-in-out infinite;\n}\n\n// Pulse style - animated scaling effect\n.pulse {\n  animation: pulse-scale 1.5s ease-in-out infinite;\n}\n\n// Glow breathing animation\n@keyframes glow-breathe {\n  0%,\n  100% {\n    opacity: 0.8;\n  }\n  50% {\n    opacity: 1;\n  }\n}\n\n// Pulse scaling animation\n@keyframes pulse-scale {\n  0%,\n  100% {\n    transform: scale(1);\n    opacity: 0.9;\n  }\n  50% {\n    transform: scale(1.02);\n    opacity: 1;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"highlightedNode": `HighlightedNode-module__highlightedNode--XJqFJ`,
	"label": `HighlightedNode-module__label--q5tcJ`,
	"glow": `HighlightedNode-module__glow--ApMP4`,
	"glow-breathe": `HighlightedNode-module__glow-breathe--DZ3aL`,
	"pulse": `HighlightedNode-module__pulse--gjRES`,
	"pulse-scale": `HighlightedNode-module__pulse-scale--vP4Gl`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 74101:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgChatFill = function SvgChatFill(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M20.5402 3.14819H3.73308C3.32785 3.14819 2.93922 3.30917 2.65268 3.59571C2.36614 3.88225 2.20516 4.27088 2.20516 4.67611V19.8407C2.20212 20.1329 2.28456 20.4197 2.44235 20.6657C2.60013 20.9117 2.82638 21.1063 3.09326 21.2254C3.29142 21.3263 3.51071 21.3786 3.73308 21.3782C4.09348 21.377 4.44187 21.2485 4.71668 21.0153L7.75341 18.4656L20.5402 18.4274C20.9454 18.4274 21.334 18.2664 21.6206 17.9799C21.9071 17.6933 22.0681 17.3047 22.0681 16.8995V4.67611C22.0681 4.27088 21.9071 3.88225 21.6206 3.59571C21.334 3.30917 20.9454 3.14819 20.5402 3.14819ZM7.55287 11.9337C7.32623 11.9337 7.10467 11.8665 6.91622 11.7406C6.72778 11.6147 6.5809 11.4357 6.49416 11.2263C6.40743 11.0169 6.38474 10.7865 6.42895 10.5642C6.47317 10.3419 6.58231 10.1377 6.74257 9.97748C6.90283 9.81722 7.10702 9.70808 7.32931 9.66387C7.5516 9.61965 7.78201 9.64234 7.99141 9.72908C8.2008 9.81581 8.37977 9.96269 8.50569 10.1511C8.6316 10.3396 8.69881 10.5611 8.69881 10.7878C8.69881 11.0917 8.57808 11.3832 8.36317 11.5981C8.14827 11.813 7.8568 11.9337 7.55287 11.9337ZM12.1366 11.9337C11.91 11.9337 11.6884 11.8665 11.5 11.7406C11.3115 11.6147 11.1647 11.4357 11.0779 11.2263C10.9912 11.0169 10.9685 10.7865 11.0127 10.5642C11.0569 10.3419 11.1661 10.1377 11.3263 9.97748C11.4866 9.81722 11.6908 9.70808 11.9131 9.66387C12.1354 9.61965 12.3658 9.64234 12.5752 9.72908C12.7846 9.81581 12.9635 9.96269 13.0894 10.1511C13.2154 10.3396 13.2826 10.5611 13.2826 10.7878C13.2826 11.0917 13.1618 11.3832 12.9469 11.5981C12.732 11.813 12.4406 11.9337 12.1366 11.9337ZM16.7204 11.9337C16.4937 11.9337 16.2722 11.8665 16.0837 11.7406C15.8953 11.6147 15.7484 11.4357 15.6617 11.2263C15.5749 11.0169 15.5522 10.7865 15.5965 10.5642C15.6407 10.3419 15.7498 10.1377 15.9101 9.97748C16.0703 9.81722 16.2745 9.70808 16.4968 9.66387C16.7191 9.61965 16.9495 9.64234 17.1589 9.72908C17.3683 9.81581 17.5473 9.96269 17.6732 10.1511C17.7991 10.3396 17.8663 10.5611 17.8663 10.7878C17.8663 11.0917 17.7456 11.3832 17.5307 11.5981C17.3158 11.813 17.0243 11.9337 16.7204 11.9337Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgChatFill);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "b8f9315b69b32a8fa9c1d7b9a2929f17.svg");

/***/ }),

/***/ 74740:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .snippet-placeholder {
	min-width: 2px;
	outline-style: solid;
	outline-width: 1px;
	background-color: var(--vscode-editor-snippetTabstopHighlightBackground, transparent);
	outline-color: var(--vscode-editor-snippetTabstopHighlightBorder, transparent);
}

.monaco-editor .finish-snippet-placeholder {
	outline-style: solid;
	outline-width: 1px;
	background-color: var(--vscode-editor-snippetFinalTabstopHighlightBackground, transparent);
	outline-color: var(--vscode-editor-snippetFinalTabstopHighlightBorder, transparent);
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/snippet/browser/snippetSession.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,cAAc;CACd,oBAAoB;CACpB,kBAAkB;CAClB,qFAAqF;CACrF,8EAA8E;AAC/E;;AAEA;CACC,oBAAoB;CACpB,kBAAkB;CAClB,0FAA0F;CAC1F,mFAAmF;AACpF","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .snippet-placeholder {\n\tmin-width: 2px;\n\toutline-style: solid;\n\toutline-width: 1px;\n\tbackground-color: var(--vscode-editor-snippetTabstopHighlightBackground, transparent);\n\toutline-color: var(--vscode-editor-snippetTabstopHighlightBorder, transparent);\n}\n\n.monaco-editor .finish-snippet-placeholder {\n\toutline-style: solid;\n\toutline-width: 1px;\n\tbackground-color: var(--vscode-editor-snippetFinalTabstopHighlightBackground, transparent);\n\toutline-color: var(--vscode-editor-snippetFinalTabstopHighlightBorder, transparent);\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 74880:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.AdvancedMode-module__Root--Bd87V{width:100%;height:100%;display:flex;flex-direction:column;background-color:var(--theme-color-bg-2);border-radius:4px;overflow:hidden}.AdvancedMode-module__Toolbar--ztWAM{display:flex;align-items:center;justify-content:space-between;padding:8px 12px;background-color:var(--theme-color-bg-3);border-bottom:1px solid var(--theme-color-border-default)}.AdvancedMode-module__ToolbarLeft--UXteB,.AdvancedMode-module__ToolbarRight--soWlN{display:flex;align-items:center;gap:12px}.AdvancedMode-module__StatusValid--pVjMs{font-size:13px;font-weight:500;color:#10b981}.AdvancedMode-module__StatusInvalid--WMBWB{font-size:13px;font-weight:500;color:#ef4444}.AdvancedMode-module__FormatButton--yvMGm{padding:4px 12px;font-size:12px;font-weight:500;background-color:var(--theme-color-primary);color:#fff;border:none;border-radius:3px;cursor:pointer;transition:all .15s ease}.AdvancedMode-module__FormatButton--yvMGm:hover:not(:disabled){opacity:.9}.AdvancedMode-module__FormatButton--yvMGm:disabled{opacity:.5;cursor:not-allowed}.AdvancedMode-module__Editor--H1P3U{flex:1;padding:12px;font-size:13px;font-family:"Menlo","Monaco","Courier New",monospace;line-height:1.6;background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-default);border:none;outline:none;resize:none;overflow-y:auto}.AdvancedMode-module__Editor--H1P3U::placeholder{color:var(--theme-color-fg-muted);opacity:.5}.AdvancedMode-module__Editor--H1P3U:disabled{opacity:.6;cursor:not-allowed}.AdvancedMode-module__ErrorPanel--MOleC{padding:12px;background-color:rgba(239,68,68,.1019607843);border-top:2px solid #ef4444;animation:AdvancedMode-module__slideDown--WQREP .2s ease-out}@keyframes AdvancedMode-module__slideDown--WQREP{from{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}.AdvancedMode-module__ErrorHeader--aWhBN{display:flex;align-items:center;gap:8px;margin-bottom:8px}.AdvancedMode-module__ErrorIcon--UPyo8{font-size:16px}.AdvancedMode-module__ErrorTitle--OSUOS{font-size:14px;font-weight:600;color:#ef4444}.AdvancedMode-module__ErrorMessage--HvfUh{font-size:13px;font-family:"Menlo","Monaco","Courier New",monospace;color:var(--theme-color-fg-default);margin-bottom:8px;padding:8px;background-color:var(--theme-color-bg-2);border-radius:3px;border-left:3px solid #ef4444}.AdvancedMode-module__ErrorSuggestion--TCmmS{font-size:13px;color:var(--theme-color-fg-default);padding:8px;background-color:rgba(59,130,246,.1019607843);border-radius:3px;border-left:3px solid #3b82f6;margin-bottom:8px}.AdvancedMode-module__ErrorSuggestion--TCmmS strong{color:#3b82f6}.AdvancedMode-module__ErrorLocation--YM3dk{font-size:12px;font-weight:500;color:var(--theme-color-fg-muted)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/json-editor/modes/AdvancedMode/AdvancedMode.module.scss"],"names":[],"mappings":"AAKA,kCACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,qBAAA,CACA,wCAAA,CACA,iBAAA,CACA,eAAA,CAIF,qCACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,gBAAA,CACA,wCAAA,CACA,yDAAA,CAGF,mFAEE,YAAA,CACA,kBAAA,CACA,QAAA,CAGF,yCACE,cAAA,CACA,eAAA,CACA,aAAA,CAGF,2CACE,cAAA,CACA,eAAA,CACA,aAAA,CAGF,0CACE,gBAAA,CACA,cAAA,CACA,eAAA,CACA,2CAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CAEA,+DACE,UAAA,CAGF,mDACE,UAAA,CACA,kBAAA,CAKJ,oCACE,MAAA,CACA,YAAA,CACA,cAAA,CACA,oDAAA,CACA,eAAA,CACA,wCAAA,CACA,mCAAA,CACA,WAAA,CACA,YAAA,CACA,WAAA,CACA,eAAA,CAEA,iDACE,iCAAA,CACA,UAAA,CAGF,6CACE,UAAA,CACA,kBAAA,CAKJ,wCACE,YAAA,CACA,4CAAA,CACA,4BAAA,CACA,4DAAA,CAGF,iDACE,KACE,SAAA,CACA,2BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,yCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,iBAAA,CAGF,uCACE,cAAA,CAGF,wCACE,cAAA,CACA,eAAA,CACA,aAAA,CAGF,0CACE,cAAA,CACA,oDAAA,CACA,mCAAA,CACA,iBAAA,CACA,WAAA,CACA,wCAAA,CACA,iBAAA,CACA,6BAAA,CAGF,6CACE,cAAA,CACA,mCAAA,CACA,WAAA,CACA,6CAAA,CACA,iBAAA,CACA,6BAAA,CACA,iBAAA,CAEA,oDACE,aAAA,CAIJ,2CACE,cAAA,CACA,eAAA,CACA,iCAAA","sourcesContent":["/**\n * Advanced Mode Styles\n * Text editor for power users\n */\n\n.Root {\n  width: 100%;\n  height: 100%;\n  display: flex;\n  flex-direction: column;\n  background-color: var(--theme-color-bg-2);\n  border-radius: 4px;\n  overflow: hidden;\n}\n\n/* Toolbar */\n.Toolbar {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: 8px 12px;\n  background-color: var(--theme-color-bg-3);\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.ToolbarLeft,\n.ToolbarRight {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n}\n\n.StatusValid {\n  font-size: 13px;\n  font-weight: 500;\n  color: #10b981;\n}\n\n.StatusInvalid {\n  font-size: 13px;\n  font-weight: 500;\n  color: #ef4444;\n}\n\n.FormatButton {\n  padding: 4px 12px;\n  font-size: 12px;\n  font-weight: 500;\n  background-color: var(--theme-color-primary);\n  color: white;\n  border: none;\n  border-radius: 3px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover:not(:disabled) {\n    opacity: 0.9;\n  }\n\n  &:disabled {\n    opacity: 0.5;\n    cursor: not-allowed;\n  }\n}\n\n/* Text Editor */\n.Editor {\n  flex: 1;\n  padding: 12px;\n  font-size: 13px;\n  font-family: 'Menlo', 'Monaco', 'Courier New', monospace;\n  line-height: 1.6;\n  background-color: var(--theme-color-bg-1);\n  color: var(--theme-color-fg-default);\n  border: none;\n  outline: none;\n  resize: none;\n  overflow-y: auto;\n\n  &::placeholder {\n    color: var(--theme-color-fg-muted);\n    opacity: 0.5;\n  }\n\n  &:disabled {\n    opacity: 0.6;\n    cursor: not-allowed;\n  }\n}\n\n/* Error Panel */\n.ErrorPanel {\n  padding: 12px;\n  background-color: #ef44441a;\n  border-top: 2px solid #ef4444;\n  animation: slideDown 0.2s ease-out;\n}\n\n@keyframes slideDown {\n  from {\n    opacity: 0;\n    transform: translateY(-10px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n.ErrorHeader {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin-bottom: 8px;\n}\n\n.ErrorIcon {\n  font-size: 16px;\n}\n\n.ErrorTitle {\n  font-size: 14px;\n  font-weight: 600;\n  color: #ef4444;\n}\n\n.ErrorMessage {\n  font-size: 13px;\n  font-family: 'Menlo', 'Monaco', 'Courier New', monospace;\n  color: var(--theme-color-fg-default);\n  margin-bottom: 8px;\n  padding: 8px;\n  background-color: var(--theme-color-bg-2);\n  border-radius: 3px;\n  border-left: 3px solid #ef4444;\n}\n\n.ErrorSuggestion {\n  font-size: 13px;\n  color: var(--theme-color-fg-default);\n  padding: 8px;\n  background-color: #3b82f61a;\n  border-radius: 3px;\n  border-left: 3px solid #3b82f6;\n  margin-bottom: 8px;\n\n  strong {\n    color: #3b82f6;\n  }\n}\n\n.ErrorLocation {\n  font-size: 12px;\n  font-weight: 500;\n  color: var(--theme-color-fg-muted);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `AdvancedMode-module__Root--Bd87V`,
	"Toolbar": `AdvancedMode-module__Toolbar--ztWAM`,
	"ToolbarLeft": `AdvancedMode-module__ToolbarLeft--UXteB`,
	"ToolbarRight": `AdvancedMode-module__ToolbarRight--soWlN`,
	"StatusValid": `AdvancedMode-module__StatusValid--pVjMs`,
	"StatusInvalid": `AdvancedMode-module__StatusInvalid--WMBWB`,
	"FormatButton": `AdvancedMode-module__FormatButton--yvMGm`,
	"Editor": `AdvancedMode-module__Editor--H1P3U`,
	"ErrorPanel": `AdvancedMode-module__ErrorPanel--MOleC`,
	"slideDown": `AdvancedMode-module__slideDown--WQREP`,
	"ErrorHeader": `AdvancedMode-module__ErrorHeader--aWhBN`,
	"ErrorIcon": `AdvancedMode-module__ErrorIcon--UPyo8`,
	"ErrorTitle": `AdvancedMode-module__ErrorTitle--OSUOS`,
	"ErrorMessage": `AdvancedMode-module__ErrorMessage--HvfUh`,
	"ErrorSuggestion": `AdvancedMode-module__ErrorSuggestion--TCmmS`,
	"ErrorLocation": `AdvancedMode-module__ErrorLocation--YM3dk`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 74897:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPlusSquare = function SvgPlusSquare(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.8867 8.25C12.8867 7.83579 12.5509 7.5 12.1367 7.5C11.7225 7.5 11.3867 7.83579 11.3867 8.25V11.25H8.38672C7.97251 11.25 7.63672 11.5858 7.63672 12C7.63672 12.4142 7.97251 12.75 8.38672 12.75H11.3867V15.75C11.3867 16.1642 11.7225 16.5 12.1367 16.5C12.5509 16.5 12.8867 16.1642 12.8867 15.75V12.75H15.8867C16.3009 12.75 16.6367 12.4142 16.6367 12C16.6367 11.5858 16.3009 11.25 15.8867 11.25H12.8867V8.25Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.37598 4.98911C3.37598 4.02261 4.15948 3.23911 5.12598 3.23911H19.1478C20.1143 3.23911 20.8978 4.02261 20.8978 4.98911V19.0109C20.8978 19.9774 20.1143 20.7609 19.1478 20.7609H5.12598C4.15948 20.7609 3.37598 19.9774 3.37598 19.0109V4.98911ZM5.12598 4.73911C4.98791 4.73911 4.87598 4.85104 4.87598 4.98911V19.0109C4.87598 19.149 4.98791 19.2609 5.12598 19.2609H19.1478C19.2858 19.2609 19.3978 19.149 19.3978 19.0109V4.98911C19.3978 4.85104 19.2858 4.73911 19.1478 4.73911H5.12598Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPlusSquare);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "f0cc86786f44e61e8b39632e66dc1586.svg");

/***/ }),

/***/ 74986:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `@keyframes ScanningStep-module__spin--apzXK{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}@keyframes ScanningStep-module__shimmer--D5KXS{0%{background-position:-1000px 0}100%{background-position:1000px 0}}@keyframes ScanningStep-module__slideInUp--hNCzi{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes ScanningStep-module__fadeInSlide--RzqJJ{from{opacity:0;transform:translateX(-10px)}to{opacity:1;transform:translateX(0)}}@keyframes ScanningStep-module__pulse--ibxQg{0%,100%{opacity:1}50%{opacity:.7}}.ScanningStep-module__Root--PzcKm{display:flex;flex-direction:column;height:100%;gap:24px;animation:ScanningStep-module__slideInUp--hNCzi 300ms ease-out}.ScanningStep-module__Header--mdF2F{display:flex;align-items:center;gap:16px;margin-bottom:4px}.ScanningStep-module__Header--mdF2F svg{width:28px;height:28px;color:var(--theme-color-primary);animation:ScanningStep-module__spin--apzXK 1.5s linear infinite;filter:drop-shadow(0 0 8px rgba(66, 135, 245, 0.3))}.ScanningStep-module__Header--mdF2F h2{font-size:20px;font-weight:600;color:var(--theme-color-fg-highlight);margin:0}.ScanningStep-module__Header--mdF2F p{font-size:14px;color:var(--theme-color-fg-default);margin:4px 0 0 0}.ScanningStep-module__ProgressSection--Y48Em{padding:24px;background:linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,.1);border:1px solid var(--theme-color-bg-2)}.ScanningStep-module__ProgressHeader--b_3br{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px}.ScanningStep-module__ProgressHeader--b_3br h3{font-size:14px;font-weight:600;color:var(--theme-color-fg-highlight);margin:0}.ScanningStep-module__ProgressHeader--b_3br span{font-size:16px;font-weight:700;color:var(--theme-color-primary);font-variant-numeric:tabular-nums}.ScanningStep-module__ProgressBar--Zt4Fq{height:12px;background-color:var(--theme-color-bg-1);border-radius:6px;overflow:hidden;position:relative;box-shadow:inset 0 1px 3px rgba(0,0,0,.2)}.ScanningStep-module__ProgressBar--Zt4Fq::after{content:"";position:absolute;top:0;left:0;right:0;height:50%;background:linear-gradient(to bottom, rgba(255, 255, 255, 0.2), transparent);pointer-events:none}.ScanningStep-module__ProgressFill--ws3n9{height:100%;background:linear-gradient(90deg, var(--theme-color-primary) 0%, rgba(66, 135, 245, 0.8) 50%, var(--theme-color-primary) 100%);background-size:200% 100%;border-radius:6px;transition:width 400ms ease-out;animation:ScanningStep-module__shimmer--D5KXS 2s linear infinite;position:relative}.ScanningStep-module__ProgressFill--ws3n9::after{content:"";position:absolute;top:0;right:0;width:20px;height:100%;background:linear-gradient(to right, transparent, rgba(255, 255, 255, 0.4));border-radius:0 6px 6px 0}.ScanningStep-module__CurrentFile--YVJyP{margin-top:12px;display:flex;align-items:center;gap:8px;font-size:12px;color:var(--theme-color-fg-default);animation:ScanningStep-module__pulse--ibxQg 1.5s ease-in-out infinite}.ScanningStep-module__CurrentFile--YVJyP svg{width:14px;height:14px;color:var(--theme-color-primary)}.ScanningStep-module__CurrentFile--YVJyP span{font-family:monospace;color:var(--theme-color-fg-highlight)}.ScanningStep-module__StatsGrid--xkcAh{display:grid;grid-template-columns:repeat(3, 1fr);gap:12px;margin-top:20px}.ScanningStep-module__StatCard--zRd6d{display:flex;flex-direction:column;align-items:center;padding:16px;background-color:var(--theme-color-bg-4);border-radius:8px;border:1px solid var(--theme-color-bg-2);transition:all 200ms ease-in-out}.ScanningStep-module__StatCard--zRd6d:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,.15)}.ScanningStep-module__StatIcon--SXX8P{width:32px;height:32px;display:flex;align-items:center;justify-content:center;margin-bottom:8px;color:var(--theme-color-primary)}.ScanningStep-module__StatIcon--SXX8P svg{width:20px;height:20px}.ScanningStep-module__StatValue--BFlNj{font-size:24px;font-weight:700;color:var(--theme-color-fg-highlight);line-height:1;margin-bottom:4px;font-variant-numeric:tabular-nums}.ScanningStep-module__StatLabel--grkKv{font-size:11px;color:var(--theme-color-fg-default);text-transform:uppercase;letter-spacing:.5px;font-weight:500}.ScanningStep-module__ActivityLog--ErKAi{flex:1;display:flex;flex-direction:column;background-color:var(--theme-color-bg-3);border-radius:8px;overflow:hidden}.ScanningStep-module__ActivityHeader--Pj_O2{padding:12px 16px;border-bottom:1px solid var(--theme-color-bg-2);display:flex;align-items:center;gap:8px}.ScanningStep-module__ActivityList--_J7NF{flex:1;overflow-y:auto;padding:8px;max-height:200px}.ScanningStep-module__ActivityItem--tzmbh{display:flex;gap:8px;padding:6px 8px;font-size:12px;border-radius:4px;animation:ScanningStep-module__fadeIn--B8Sy9 .2s ease}.ScanningStep-module__ActivityItem--tzmbh.ScanningStep-module__is-info--etDrY{color:var(--theme-color-secondary-as-fg)}.ScanningStep-module__ActivityItem--tzmbh.ScanningStep-module__is-success--cQGHU{color:var(--theme-color-success)}.ScanningStep-module__ActivityItem--tzmbh.ScanningStep-module__is-warning--LLm6f{color:var(--theme-color-warning)}.ScanningStep-module__ActivityItem--tzmbh.ScanningStep-module__is-error--CkiJj{color:var(--theme-color-danger)}@keyframes ScanningStep-module__fadeIn--B8Sy9{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}.ScanningStep-module__ActivityTime--Gpjmr{color:var(--theme-color-secondary-as-fg);font-family:monospace;flex-shrink:0}.ScanningStep-module__ActivityMessage--vQtTv{flex:1}.ScanningStep-module__EmptyActivity--pW3wT{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100px;color:var(--theme-color-secondary-as-fg)}.ScanningStep-module__InfoBox--orKFl{display:flex;gap:12px;padding:12px 16px;background-color:rgba(59,130,246,.1);border:1px solid rgba(59,130,246,.3);border-radius:8px}.ScanningStep-module__InfoBox--orKFl svg{width:16px;height:16px;flex-shrink:0;color:var(--theme-color-primary)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/migration/steps/ScanningStep.module.scss"],"names":[],"mappings":"AAMA,4CACE,KACE,sBAAA,CAEF,GACE,wBAAA,CAAA,CAIJ,+CACE,GACE,6BAAA,CAEF,KACE,4BAAA,CAAA,CAIJ,iDACE,KACE,SAAA,CACA,0BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,mDACE,KACE,SAAA,CACA,2BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,6CACE,QAEE,SAAA,CAEF,IACE,UAAA,CAAA,CAIJ,kCACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,QAAA,CACA,8DAAA,CAGF,oCACE,YAAA,CACA,kBAAA,CACA,QAAA,CACA,iBAAA,CAEA,wCACE,UAAA,CACA,WAAA,CACA,gCAAA,CACA,+DAAA,CACA,mDAAA,CAGF,uCACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,QAAA,CAGF,sCACE,cAAA,CACA,mCAAA,CACA,gBAAA,CAIJ,6CACE,YAAA,CACA,4FAAA,CACA,kBAAA,CACA,mCAAA,CACA,wCAAA,CAGF,4CACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,kBAAA,CAEA,+CACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,QAAA,CAGF,iDACE,cAAA,CACA,eAAA,CACA,gCAAA,CACA,iCAAA,CAIJ,yCACE,WAAA,CACA,wCAAA,CACA,iBAAA,CACA,eAAA,CACA,iBAAA,CACA,yCAAA,CAEA,gDACE,UAAA,CACA,iBAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,UAAA,CACA,4EAAA,CACA,mBAAA,CAIJ,0CACE,WAAA,CACA,8HAAA,CAMA,yBAAA,CACA,iBAAA,CACA,+BAAA,CACA,gEAAA,CACA,iBAAA,CAEA,iDACE,UAAA,CACA,iBAAA,CACA,KAAA,CACA,OAAA,CACA,UAAA,CACA,WAAA,CACA,2EAAA,CACA,yBAAA,CAIJ,yCACE,eAAA,CACA,YAAA,CACA,kBAAA,CACA,OAAA,CACA,cAAA,CACA,mCAAA,CACA,qEAAA,CAEA,6CACE,UAAA,CACA,WAAA,CACA,gCAAA,CAGF,8CACE,qBAAA,CACA,qCAAA,CAIJ,uCACE,YAAA,CACA,oCAAA,CACA,QAAA,CACA,eAAA,CAGF,sCACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,YAAA,CACA,wCAAA,CACA,iBAAA,CACA,wCAAA,CACA,gCAAA,CAEA,4CACE,0BAAA,CACA,qCAAA,CAIJ,sCACE,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,gCAAA,CAEA,0CACE,UAAA,CACA,WAAA,CAIJ,uCACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,aAAA,CACA,iBAAA,CACA,iCAAA,CAGF,uCACE,cAAA,CACA,mCAAA,CACA,wBAAA,CACA,mBAAA,CACA,eAAA,CAGF,yCACE,MAAA,CACA,YAAA,CACA,qBAAA,CACA,wCAAA,CACA,iBAAA,CACA,eAAA,CAGF,4CACE,iBAAA,CACA,+CAAA,CACA,YAAA,CACA,kBAAA,CACA,OAAA,CAGF,0CACE,MAAA,CACA,eAAA,CACA,WAAA,CACA,gBAAA,CAGF,0CACE,YAAA,CACA,OAAA,CACA,eAAA,CACA,cAAA,CACA,iBAAA,CACA,qDAAA,CAEA,8EACE,wCAAA,CAGF,iFACE,gCAAA,CAGF,iFACE,gCAAA,CAGF,+EACE,+BAAA,CAIJ,8CACE,KACE,SAAA,CACA,0BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,0CACE,wCAAA,CACA,qBAAA,CACA,aAAA,CAGF,6CACE,MAAA,CAGF,2CACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,YAAA,CACA,wCAAA,CAGF,qCACE,YAAA,CACA,QAAA,CACA,iBAAA,CACA,oCAAA,CACA,oCAAA,CACA,iBAAA,CAEA,yCACE,UAAA,CACA,WAAA,CACA,aAAA,CACA,gCAAA","sourcesContent":["/**\n * ScanningStep Styles\n * \n * Enhanced scanning/migrating progress display with animations and better visualization.\n */\n\n@keyframes spin {\n  from {\n    transform: rotate(0deg);\n  }\n  to {\n    transform: rotate(360deg);\n  }\n}\n\n@keyframes shimmer {\n  0% {\n    background-position: -1000px 0;\n  }\n  100% {\n    background-position: 1000px 0;\n  }\n}\n\n@keyframes slideInUp {\n  from {\n    opacity: 0;\n    transform: translateY(10px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n@keyframes fadeInSlide {\n  from {\n    opacity: 0;\n    transform: translateX(-10px);\n  }\n  to {\n    opacity: 1;\n    transform: translateX(0);\n  }\n}\n\n@keyframes pulse {\n  0%,\n  100% {\n    opacity: 1;\n  }\n  50% {\n    opacity: 0.7;\n  }\n}\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  gap: 24px;\n  animation: slideInUp 300ms ease-out;\n}\n\n.Header {\n  display: flex;\n  align-items: center;\n  gap: 16px;\n  margin-bottom: 4px;\n\n  svg {\n    width: 28px;\n    height: 28px;\n    color: var(--theme-color-primary);\n    animation: spin 1.5s linear infinite;\n    filter: drop-shadow(0 0 8px rgba(66, 135, 245, 0.3));\n  }\n\n  h2 {\n    font-size: 20px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    margin: 0;\n  }\n\n  p {\n    font-size: 14px;\n    color: var(--theme-color-fg-default);\n    margin: 4px 0 0 0;\n  }\n}\n\n.ProgressSection {\n  padding: 24px;\n  background: linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);\n  border-radius: 12px;\n  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n  border: 1px solid var(--theme-color-bg-2);\n}\n\n.ProgressHeader {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  margin-bottom: 16px;\n\n  h3 {\n    font-size: 14px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    margin: 0;\n  }\n\n  span {\n    font-size: 16px;\n    font-weight: 700;\n    color: var(--theme-color-primary);\n    font-variant-numeric: tabular-nums;\n  }\n}\n\n.ProgressBar {\n  height: 12px;\n  background-color: var(--theme-color-bg-1);\n  border-radius: 6px;\n  overflow: hidden;\n  position: relative;\n  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2);\n\n  &::after {\n    content: '';\n    position: absolute;\n    top: 0;\n    left: 0;\n    right: 0;\n    height: 50%;\n    background: linear-gradient(to bottom, rgba(255, 255, 255, 0.2), transparent);\n    pointer-events: none;\n  }\n}\n\n.ProgressFill {\n  height: 100%;\n  background: linear-gradient(\n    90deg,\n    var(--theme-color-primary) 0%,\n    rgba(66, 135, 245, 0.8) 50%,\n    var(--theme-color-primary) 100%\n  );\n  background-size: 200% 100%;\n  border-radius: 6px;\n  transition: width 400ms ease-out;\n  animation: shimmer 2s linear infinite;\n  position: relative;\n\n  &::after {\n    content: '';\n    position: absolute;\n    top: 0;\n    right: 0;\n    width: 20px;\n    height: 100%;\n    background: linear-gradient(to right, transparent, rgba(255, 255, 255, 0.4));\n    border-radius: 0 6px 6px 0;\n  }\n}\n\n.CurrentFile {\n  margin-top: 12px;\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  font-size: 12px;\n  color: var(--theme-color-fg-default);\n  animation: pulse 1.5s ease-in-out infinite;\n\n  svg {\n    width: 14px;\n    height: 14px;\n    color: var(--theme-color-primary);\n  }\n\n  span {\n    font-family: monospace;\n    color: var(--theme-color-fg-highlight);\n  }\n}\n\n.StatsGrid {\n  display: grid;\n  grid-template-columns: repeat(3, 1fr);\n  gap: 12px;\n  margin-top: 20px;\n}\n\n.StatCard {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  padding: 16px;\n  background-color: var(--theme-color-bg-4);\n  border-radius: 8px;\n  border: 1px solid var(--theme-color-bg-2);\n  transition: all 200ms ease-in-out;\n\n  &:hover {\n    transform: translateY(-2px);\n    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n  }\n}\n\n.StatIcon {\n  width: 32px;\n  height: 32px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  margin-bottom: 8px;\n  color: var(--theme-color-primary);\n\n  svg {\n    width: 20px;\n    height: 20px;\n  }\n}\n\n.StatValue {\n  font-size: 24px;\n  font-weight: 700;\n  color: var(--theme-color-fg-highlight);\n  line-height: 1;\n  margin-bottom: 4px;\n  font-variant-numeric: tabular-nums;\n}\n\n.StatLabel {\n  font-size: 11px;\n  color: var(--theme-color-fg-default);\n  text-transform: uppercase;\n  letter-spacing: 0.5px;\n  font-weight: 500;\n}\n\n.ActivityLog {\n  flex: 1;\n  display: flex;\n  flex-direction: column;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 8px;\n  overflow: hidden;\n}\n\n.ActivityHeader {\n  padding: 12px 16px;\n  border-bottom: 1px solid var(--theme-color-bg-2);\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n.ActivityList {\n  flex: 1;\n  overflow-y: auto;\n  padding: 8px;\n  max-height: 200px;\n}\n\n.ActivityItem {\n  display: flex;\n  gap: 8px;\n  padding: 6px 8px;\n  font-size: 12px;\n  border-radius: 4px;\n  animation: fadeIn 0.2s ease;\n\n  &.is-info {\n    color: var(--theme-color-secondary-as-fg);\n  }\n\n  &.is-success {\n    color: var(--theme-color-success);\n  }\n\n  &.is-warning {\n    color: var(--theme-color-warning);\n  }\n\n  &.is-error {\n    color: var(--theme-color-danger);\n  }\n}\n\n@keyframes fadeIn {\n  from {\n    opacity: 0;\n    transform: translateY(-4px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n.ActivityTime {\n  color: var(--theme-color-secondary-as-fg);\n  font-family: monospace;\n  flex-shrink: 0;\n}\n\n.ActivityMessage {\n  flex: 1;\n}\n\n.EmptyActivity {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  height: 100px;\n  color: var(--theme-color-secondary-as-fg);\n}\n\n.InfoBox {\n  display: flex;\n  gap: 12px;\n  padding: 12px 16px;\n  background-color: rgba(59, 130, 246, 0.1);\n  border: 1px solid rgba(59, 130, 246, 0.3);\n  border-radius: 8px;\n\n  svg {\n    width: 16px;\n    height: 16px;\n    flex-shrink: 0;\n    color: var(--theme-color-primary);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ScanningStep-module__Root--PzcKm`,
	"slideInUp": `ScanningStep-module__slideInUp--hNCzi`,
	"Header": `ScanningStep-module__Header--mdF2F`,
	"spin": `ScanningStep-module__spin--apzXK`,
	"ProgressSection": `ScanningStep-module__ProgressSection--Y48Em`,
	"ProgressHeader": `ScanningStep-module__ProgressHeader--b_3br`,
	"ProgressBar": `ScanningStep-module__ProgressBar--Zt4Fq`,
	"ProgressFill": `ScanningStep-module__ProgressFill--ws3n9`,
	"shimmer": `ScanningStep-module__shimmer--D5KXS`,
	"CurrentFile": `ScanningStep-module__CurrentFile--YVJyP`,
	"pulse": `ScanningStep-module__pulse--ibxQg`,
	"StatsGrid": `ScanningStep-module__StatsGrid--xkcAh`,
	"StatCard": `ScanningStep-module__StatCard--zRd6d`,
	"StatIcon": `ScanningStep-module__StatIcon--SXX8P`,
	"StatValue": `ScanningStep-module__StatValue--BFlNj`,
	"StatLabel": `ScanningStep-module__StatLabel--grkKv`,
	"ActivityLog": `ScanningStep-module__ActivityLog--ErKAi`,
	"ActivityHeader": `ScanningStep-module__ActivityHeader--Pj_O2`,
	"ActivityList": `ScanningStep-module__ActivityList--_J7NF`,
	"ActivityItem": `ScanningStep-module__ActivityItem--tzmbh`,
	"fadeIn": `ScanningStep-module__fadeIn--B8Sy9`,
	"is-info": `ScanningStep-module__is-info--etDrY`,
	"is-success": `ScanningStep-module__is-success--cQGHU`,
	"is-warning": `ScanningStep-module__is-warning--LLm6f`,
	"is-error": `ScanningStep-module__is-error--CkiJj`,
	"ActivityTime": `ScanningStep-module__ActivityTime--Gpjmr`,
	"ActivityMessage": `ScanningStep-module__ActivityMessage--vQtTv`,
	"EmptyActivity": `ScanningStep-module__EmptyActivity--pW3wT`,
	"InfoBox": `ScanningStep-module__InfoBox--orKFl`,
	"fadeInSlide": `ScanningStep-module__fadeInSlide--RzqJJ`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 74991:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgStructureCircle = function SvgStructureCircle(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M8.22266 7.39608C9.26139 7.08256 10.0178 6.11823 10.0178 4.97724C10.0178 3.58203 8.88679 2.45099 7.49158 2.45099C6.09637 2.45099 4.96533 3.58203 4.96533 4.97724C4.96533 6.10433 5.70344 7.05903 6.72266 7.38433V17.3117C5.69335 17.631 4.9458 18.5906 4.9458 19.7249C4.9458 21.1201 6.07684 22.2512 7.47205 22.2512C8.86725 22.2512 9.99829 21.1201 9.99829 19.7249C9.99829 18.5911 9.25133 17.6317 8.22266 17.3121V16.4337C8.23512 16.3795 8.2417 16.3231 8.2417 16.2651V14.6337C8.2417 14.4956 8.35363 14.3837 8.4917 14.3837H15.8208C16.7873 14.3837 17.5708 13.6002 17.5708 12.6337V10.5658C18.5896 10.2403 19.3274 9.28576 19.3274 8.15894C19.3274 6.76373 18.1964 5.63269 16.8011 5.63269C15.4059 5.63269 14.2749 6.76373 14.2749 8.15894C14.2749 9.3002 15.0317 10.2647 16.0708 10.578V12.6337C16.0708 12.7717 15.9589 12.8837 15.8208 12.8837H8.4917C8.40021 12.8837 8.31036 12.8907 8.22266 12.9042V7.39608Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgStructureCircle);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "acfd8de5868047df12fe5ed01519aebd.svg");

/***/ }),

/***/ 75178:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCopy = function SvgCopy(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M8.38672 2.26318C7.97251 2.26318 7.63672 2.59897 7.63672 3.01318V6.76318H3.88672C3.47251 6.76318 3.13672 7.09897 3.13672 7.51318V21.5132C3.13672 21.9274 3.47251 22.2632 3.88672 22.2632H15.8867C16.3009 22.2632 16.6367 21.9274 16.6367 21.5132V17.7632H20.3867C20.8009 17.7632 21.1367 17.4274 21.1367 17.0132V3.01318C21.1367 2.59897 20.8009 2.26318 20.3867 2.26318H8.38672ZM16.6367 16.2632H19.6367V3.76318H9.13672V6.76318H15.8867C16.3009 6.76318 16.6367 7.09897 16.6367 7.51318V16.2632ZM4.63672 20.7632V8.26318H15.1367V17.0132V20.7632H4.63672Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCopy);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "659f7beed6deaa9f30862dbef04fd027.svg");

/***/ }),

/***/ 75189:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.queryeditor-popup {
  background-color: var(--theme-color-bg-5);
  padding: 8px;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
}

.queryeditor-content {
  display: flex;
  flex-shrink: 0;
}

.queryeditor-add-filter-group {
  margin: 5px;
  border: 1px solid var(--theme-color-border-default);
  padding: 3px;
}

.queryeditor-add-filter-group-inner {
  background-color: var(--theme-color-bg-2);
  color: var(--theme-color-fg-default-shy);
  padding: 10px;
  text-align: center;
  flex-grow: 1;
}

.queryeditor-add-filter-group-inner:hover {
  background-color: var(--theme-color-bg-5);
  color: var(--theme-color-fg-default);
}

.queryeditor-group {
  display: flex;
  flex-direction: column;
  border: 1px solid var(--theme-color-border-default);
  padding: 5px;
  margin-right: 3px;
  margin-left: 2px;
}

.queryeditor-group.toplevel {
  border: none;
  padding: 0px;
}

.queryeditor-group-children {
  display: flex;
  flex-direction: column;
}

.queryeditor-group-row {
  display: flex;
  align-items: center;
}

.queryeditor-remove-icon {
  margin-left: 10px;
  color: var(--theme-color-fg-default-shy);
  width: 20px;
  height: 20px;
}

.queryeditor-remove-icon:hover {
  color: var(--theme-color-fg-default);
}

.queryeditor-and-toggle {
  color: var(--theme-color-fg-default-shy);
  background-color: var(--theme-color-bg-5);
  border-left: 1px solid var(--theme-color-fg-default-shy);
  border-top: 1px solid var(--theme-color-fg-default-shy);
  border-bottom: 1px solid var(--theme-color-fg-default-shy);
  border-radius: 5px 0px 0px 5px;
  padding: 3px;
  padding-left: 5px;
  padding-right: 5px;
}

.queryeditor-and-toggle:hover {
  color: var(--theme-color-fg-highlight);
}

.queryeditor-and-toggle.selected {
  background-color: var(--theme-color-fg-muted);
  color: var(--theme-color-fg-highlight);
}

.queryeditor-or-toggle {
  color: var(--theme-color-fg-default-shy);
  background-color: var(--theme-color-bg-5);
  border-right: 1px solid var(--theme-color-fg-default-shy);
  border-top: 1px solid var(--theme-color-fg-default-shy);
  border-bottom: 1px solid var(--theme-color-fg-default-shy);
  border-radius: 0px 5px 5px 0px;
  padding: 3px;
  padding-right: 5px;
  padding-left: 5px;
}

.queryeditor-or-toggle.selected {
  background-color: var(--theme-color-fg-muted);
  color: var(--theme-color-fg-highlight);
}

.queryeditor-or-toggle:hover {
  color: var(--theme-color-fg-highlight);
}

.queryeditor-add-rule {
  display: flex;
  color: var(--theme-color-fg-default-shy);
  align-items: center;
  margin-right: 10px;
}

.queryeditor-add-rule:hover {
  color: var(--theme-color-fg-default);
}

.queryeditor-add-icon {
  padding: 2px;
  width: 12px;
  height: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.queryeditor-add-group {
  display: flex;
  color: var(--theme-color-fg-default-shy);
  align-items: center;
}

.queryeditor-add-group:hover {
  color: var(--theme-color-fg-default);
}

.queryeditor-rule {
  display: flex;
  padding: 10px;
  align-items: flex-start;
  background-color: var(--theme-color-bg-2);
  flex-shrink: 0;
}

.queryeditor-rule > * {
  margin-right: 10px;
}

.queryeditor-rule > *:last-child {
  margin-right: 0px;
}

.queryeditor-component {
  position: relative;
  background-color: var(--theme-color-bg-5);
  padding: 5px;
  padding-left: 10px;
  padding-right: 10px;
  color: var(--theme-color-fg-default);
  display: flex;
  align-items: flex-start;
  min-height: 32px;
  min-width: 100px;
  flex-shrink: 0;
}

.queryeditor-component.hoverable:hover {
  color: var(--theme-color-fg-highlight);
}

.queryeditor-property-inner {
  display: flex;
  flex-direction: column;
  align-items: top;
  white-space: nowrap;
}

.queryeditor-property-label {
  color: var(--theme-color-fg-default-shy);
  font-size: 10px;
  font-weight: bold;
}

.queryeditor-value-input {
  width: 100%;
  height: 100%;
  outline: none;
  border: none;
  background-color: transparent;
  color: var(--theme-color-fg-highlight);
}

.queryeditor-caret-icon {
  margin-left: auto;
  align-self: center;
  padding-left: 15px;
}

.queryeditor-dropdown {
  position: absolute;
  top: 47px;
  background-color: var(--theme-color-bg-2);
  color: var(--theme-color-fg-default);
  border-radius: 3px;
  margin-left: -10px;
  z-index: 10;
  max-height: 400px;
  overflow: auto;
}

.queryeditor-dropdown-item {
  padding: 4px;
  padding-right: 5px;
  padding-left: 5px;
}

.queryeditor-dropdown-item:hover {
  color: var(--theme-color-fg-highlight);
  background-color: var(--theme-color-bg-5);
}

.queryeditor-value-type-icon {
  padding: 5px;
  padding-left: 10px;
  padding-right: 10px;
  color: var(--theme-color-fg-default);
  margin-right: 10px;
}

.queryeditor-value-type-icon:hover {
  color: var(--theme-color-fg-highlight);
}

.queryeditor-header {
  display: flex;
  font-size: 12px;
  color: var(--theme-color-fg-default-shy);
  margin-left: 5px;
  margin-bottom: 8px;
}

.queryeditor-desc {
  color: var(--theme-color-fg-default-shy);
  margin-right: 10px;
  line-height: 12px;
  flex-grow: 0;
}

.queryeditor-combinator-label {
  padding: 5px;
  color: var(--theme-color-fg-default-shy);
}

.queryeditor-combinator-label:hover {
  color: var(--theme-color-fg-default);
}

.queryeditor-add-button {
  background-color: var(--theme-color-bg-2);
  color: var(--theme-color-fg-default);
  padding: 3px;
  padding-left: 7px;
  padding-right: 7px;
  justify-self: center;
}

.queryeditor-add-button:hover {
  background-color: var(--theme-color-bg-4);
  color: var(--theme-color-fg-highlight);
}

.queryeditor-sorting {
  display: flex;
  flex-direction: column;
  border: 1px solid var(--theme-color-border-strong);
  padding: 5px;
}

.queryeditor-sorting-rules {
  display: flex;
  flex-direction: column;
  margin-bottom: 5px;
}

.queryeditor-span {
  color: var(--theme-color-fg-default-shy);
}

.queryeditor-strong {
  color: var(--theme-color-fg-default);
  font-weight: bold;
}

.queryeditor-span-strong {
  color: var(--theme-color-fg-default);
  font-weight: bold;
  margin-left: 5px;
  margin-right: 5px;
}

.queryeditor-text-rule {
  background-color: var(--theme-color-bg-2);
  padding: 3px;
}

.queryeditor-text-rule:hover {
  background-color: var(--theme-color-bg-5);
}

.queryeditor-trash-icon {
  content: url('../assets/icons/queryeditor-trash.svg');
  width: 20px;
  height: 20px;
  opacity: 0.6;
  margin-left: 10px;
  align-self: center;
  margin-right: 5px;
}

.queryeditor-trash-icon:hover {
  opacity: 0.8;
}

.queryeditor-sorting-rules {
  display: flex;
  flex-direction: column;
  border: 1px solid var(--theme-color-border-default);
  padding: 5px;
  margin-right: 3px;
  margin-left: 2px;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/propertyeditor/queryeditor.css"],"names":[],"mappings":"AAAA;EACE,yCAAyC;EACzC,YAAY;EACZ,aAAa;EACb,sBAAsB;EACtB,cAAc;AAChB;;AAEA;EACE,aAAa;EACb,cAAc;AAChB;;AAEA;EACE,WAAW;EACX,mDAAmD;EACnD,YAAY;AACd;;AAEA;EACE,yCAAyC;EACzC,wCAAwC;EACxC,aAAa;EACb,kBAAkB;EAClB,YAAY;AACd;;AAEA;EACE,yCAAyC;EACzC,oCAAoC;AACtC;;AAEA;EACE,aAAa;EACb,sBAAsB;EACtB,mDAAmD;EACnD,YAAY;EACZ,iBAAiB;EACjB,gBAAgB;AAClB;;AAEA;EACE,YAAY;EACZ,YAAY;AACd;;AAEA;EACE,aAAa;EACb,sBAAsB;AACxB;;AAEA;EACE,aAAa;EACb,mBAAmB;AACrB;;AAEA;EACE,iBAAiB;EACjB,wCAAwC;EACxC,WAAW;EACX,YAAY;AACd;;AAEA;EACE,oCAAoC;AACtC;;AAEA;EACE,wCAAwC;EACxC,yCAAyC;EACzC,wDAAwD;EACxD,uDAAuD;EACvD,0DAA0D;EAC1D,8BAA8B;EAC9B,YAAY;EACZ,iBAAiB;EACjB,kBAAkB;AACpB;;AAEA;EACE,sCAAsC;AACxC;;AAEA;EACE,6CAA6C;EAC7C,sCAAsC;AACxC;;AAEA;EACE,wCAAwC;EACxC,yCAAyC;EACzC,yDAAyD;EACzD,uDAAuD;EACvD,0DAA0D;EAC1D,8BAA8B;EAC9B,YAAY;EACZ,kBAAkB;EAClB,iBAAiB;AACnB;;AAEA;EACE,6CAA6C;EAC7C,sCAAsC;AACxC;;AAEA;EACE,sCAAsC;AACxC;;AAEA;EACE,aAAa;EACb,wCAAwC;EACxC,mBAAmB;EACnB,kBAAkB;AACpB;;AAEA;EACE,oCAAoC;AACtC;;AAEA;EACE,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,aAAa;EACb,mBAAmB;EACnB,uBAAuB;AACzB;;AAEA;EACE,aAAa;EACb,wCAAwC;EACxC,mBAAmB;AACrB;;AAEA;EACE,oCAAoC;AACtC;;AAEA;EACE,aAAa;EACb,aAAa;EACb,uBAAuB;EACvB,yCAAyC;EACzC,cAAc;AAChB;;AAEA;EACE,kBAAkB;AACpB;;AAEA;EACE,iBAAiB;AACnB;;AAEA;EACE,kBAAkB;EAClB,yCAAyC;EACzC,YAAY;EACZ,kBAAkB;EAClB,mBAAmB;EACnB,oCAAoC;EACpC,aAAa;EACb,uBAAuB;EACvB,gBAAgB;EAChB,gBAAgB;EAChB,cAAc;AAChB;;AAEA;EACE,sCAAsC;AACxC;;AAEA;EACE,aAAa;EACb,sBAAsB;EACtB,gBAAgB;EAChB,mBAAmB;AACrB;;AAEA;EACE,wCAAwC;EACxC,eAAe;EACf,iBAAiB;AACnB;;AAEA;EACE,WAAW;EACX,YAAY;EACZ,aAAa;EACb,YAAY;EACZ,6BAA6B;EAC7B,sCAAsC;AACxC;;AAEA;EACE,iBAAiB;EACjB,kBAAkB;EAClB,kBAAkB;AACpB;;AAEA;EACE,kBAAkB;EAClB,SAAS;EACT,yCAAyC;EACzC,oCAAoC;EACpC,kBAAkB;EAClB,kBAAkB;EAClB,WAAW;EACX,iBAAiB;EACjB,cAAc;AAChB;;AAEA;EACE,YAAY;EACZ,kBAAkB;EAClB,iBAAiB;AACnB;;AAEA;EACE,sCAAsC;EACtC,yCAAyC;AAC3C;;AAEA;EACE,YAAY;EACZ,kBAAkB;EAClB,mBAAmB;EACnB,oCAAoC;EACpC,kBAAkB;AACpB;;AAEA;EACE,sCAAsC;AACxC;;AAEA;EACE,aAAa;EACb,eAAe;EACf,wCAAwC;EACxC,gBAAgB;EAChB,kBAAkB;AACpB;;AAEA;EACE,wCAAwC;EACxC,kBAAkB;EAClB,iBAAiB;EACjB,YAAY;AACd;;AAEA;EACE,YAAY;EACZ,wCAAwC;AAC1C;;AAEA;EACE,oCAAoC;AACtC;;AAEA;EACE,yCAAyC;EACzC,oCAAoC;EACpC,YAAY;EACZ,iBAAiB;EACjB,kBAAkB;EAClB,oBAAoB;AACtB;;AAEA;EACE,yCAAyC;EACzC,sCAAsC;AACxC;;AAEA;EACE,aAAa;EACb,sBAAsB;EACtB,kDAAkD;EAClD,YAAY;AACd;;AAEA;EACE,aAAa;EACb,sBAAsB;EACtB,kBAAkB;AACpB;;AAEA;EACE,wCAAwC;AAC1C;;AAEA;EACE,oCAAoC;EACpC,iBAAiB;AACnB;;AAEA;EACE,oCAAoC;EACpC,iBAAiB;EACjB,gBAAgB;EAChB,iBAAiB;AACnB;;AAEA;EACE,yCAAyC;EACzC,YAAY;AACd;;AAEA;EACE,yCAAyC;AAC3C;;AAEA;EACE,qDAAqD;EACrD,WAAW;EACX,YAAY;EACZ,YAAY;EACZ,iBAAiB;EACjB,kBAAkB;EAClB,iBAAiB;AACnB;;AAEA;EACE,YAAY;AACd;;AAEA;EACE,aAAa;EACb,sBAAsB;EACtB,mDAAmD;EACnD,YAAY;EACZ,iBAAiB;EACjB,gBAAgB;AAClB","sourcesContent":[".queryeditor-popup {\n  background-color: var(--theme-color-bg-5);\n  padding: 8px;\n  display: flex;\n  flex-direction: column;\n  flex-shrink: 0;\n}\n\n.queryeditor-content {\n  display: flex;\n  flex-shrink: 0;\n}\n\n.queryeditor-add-filter-group {\n  margin: 5px;\n  border: 1px solid var(--theme-color-border-default);\n  padding: 3px;\n}\n\n.queryeditor-add-filter-group-inner {\n  background-color: var(--theme-color-bg-2);\n  color: var(--theme-color-fg-default-shy);\n  padding: 10px;\n  text-align: center;\n  flex-grow: 1;\n}\n\n.queryeditor-add-filter-group-inner:hover {\n  background-color: var(--theme-color-bg-5);\n  color: var(--theme-color-fg-default);\n}\n\n.queryeditor-group {\n  display: flex;\n  flex-direction: column;\n  border: 1px solid var(--theme-color-border-default);\n  padding: 5px;\n  margin-right: 3px;\n  margin-left: 2px;\n}\n\n.queryeditor-group.toplevel {\n  border: none;\n  padding: 0px;\n}\n\n.queryeditor-group-children {\n  display: flex;\n  flex-direction: column;\n}\n\n.queryeditor-group-row {\n  display: flex;\n  align-items: center;\n}\n\n.queryeditor-remove-icon {\n  margin-left: 10px;\n  color: var(--theme-color-fg-default-shy);\n  width: 20px;\n  height: 20px;\n}\n\n.queryeditor-remove-icon:hover {\n  color: var(--theme-color-fg-default);\n}\n\n.queryeditor-and-toggle {\n  color: var(--theme-color-fg-default-shy);\n  background-color: var(--theme-color-bg-5);\n  border-left: 1px solid var(--theme-color-fg-default-shy);\n  border-top: 1px solid var(--theme-color-fg-default-shy);\n  border-bottom: 1px solid var(--theme-color-fg-default-shy);\n  border-radius: 5px 0px 0px 5px;\n  padding: 3px;\n  padding-left: 5px;\n  padding-right: 5px;\n}\n\n.queryeditor-and-toggle:hover {\n  color: var(--theme-color-fg-highlight);\n}\n\n.queryeditor-and-toggle.selected {\n  background-color: var(--theme-color-fg-muted);\n  color: var(--theme-color-fg-highlight);\n}\n\n.queryeditor-or-toggle {\n  color: var(--theme-color-fg-default-shy);\n  background-color: var(--theme-color-bg-5);\n  border-right: 1px solid var(--theme-color-fg-default-shy);\n  border-top: 1px solid var(--theme-color-fg-default-shy);\n  border-bottom: 1px solid var(--theme-color-fg-default-shy);\n  border-radius: 0px 5px 5px 0px;\n  padding: 3px;\n  padding-right: 5px;\n  padding-left: 5px;\n}\n\n.queryeditor-or-toggle.selected {\n  background-color: var(--theme-color-fg-muted);\n  color: var(--theme-color-fg-highlight);\n}\n\n.queryeditor-or-toggle:hover {\n  color: var(--theme-color-fg-highlight);\n}\n\n.queryeditor-add-rule {\n  display: flex;\n  color: var(--theme-color-fg-default-shy);\n  align-items: center;\n  margin-right: 10px;\n}\n\n.queryeditor-add-rule:hover {\n  color: var(--theme-color-fg-default);\n}\n\n.queryeditor-add-icon {\n  padding: 2px;\n  width: 12px;\n  height: 12px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.queryeditor-add-group {\n  display: flex;\n  color: var(--theme-color-fg-default-shy);\n  align-items: center;\n}\n\n.queryeditor-add-group:hover {\n  color: var(--theme-color-fg-default);\n}\n\n.queryeditor-rule {\n  display: flex;\n  padding: 10px;\n  align-items: flex-start;\n  background-color: var(--theme-color-bg-2);\n  flex-shrink: 0;\n}\n\n.queryeditor-rule > * {\n  margin-right: 10px;\n}\n\n.queryeditor-rule > *:last-child {\n  margin-right: 0px;\n}\n\n.queryeditor-component {\n  position: relative;\n  background-color: var(--theme-color-bg-5);\n  padding: 5px;\n  padding-left: 10px;\n  padding-right: 10px;\n  color: var(--theme-color-fg-default);\n  display: flex;\n  align-items: flex-start;\n  min-height: 32px;\n  min-width: 100px;\n  flex-shrink: 0;\n}\n\n.queryeditor-component.hoverable:hover {\n  color: var(--theme-color-fg-highlight);\n}\n\n.queryeditor-property-inner {\n  display: flex;\n  flex-direction: column;\n  align-items: top;\n  white-space: nowrap;\n}\n\n.queryeditor-property-label {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 10px;\n  font-weight: bold;\n}\n\n.queryeditor-value-input {\n  width: 100%;\n  height: 100%;\n  outline: none;\n  border: none;\n  background-color: transparent;\n  color: var(--theme-color-fg-highlight);\n}\n\n.queryeditor-caret-icon {\n  margin-left: auto;\n  align-self: center;\n  padding-left: 15px;\n}\n\n.queryeditor-dropdown {\n  position: absolute;\n  top: 47px;\n  background-color: var(--theme-color-bg-2);\n  color: var(--theme-color-fg-default);\n  border-radius: 3px;\n  margin-left: -10px;\n  z-index: 10;\n  max-height: 400px;\n  overflow: auto;\n}\n\n.queryeditor-dropdown-item {\n  padding: 4px;\n  padding-right: 5px;\n  padding-left: 5px;\n}\n\n.queryeditor-dropdown-item:hover {\n  color: var(--theme-color-fg-highlight);\n  background-color: var(--theme-color-bg-5);\n}\n\n.queryeditor-value-type-icon {\n  padding: 5px;\n  padding-left: 10px;\n  padding-right: 10px;\n  color: var(--theme-color-fg-default);\n  margin-right: 10px;\n}\n\n.queryeditor-value-type-icon:hover {\n  color: var(--theme-color-fg-highlight);\n}\n\n.queryeditor-header {\n  display: flex;\n  font-size: 12px;\n  color: var(--theme-color-fg-default-shy);\n  margin-left: 5px;\n  margin-bottom: 8px;\n}\n\n.queryeditor-desc {\n  color: var(--theme-color-fg-default-shy);\n  margin-right: 10px;\n  line-height: 12px;\n  flex-grow: 0;\n}\n\n.queryeditor-combinator-label {\n  padding: 5px;\n  color: var(--theme-color-fg-default-shy);\n}\n\n.queryeditor-combinator-label:hover {\n  color: var(--theme-color-fg-default);\n}\n\n.queryeditor-add-button {\n  background-color: var(--theme-color-bg-2);\n  color: var(--theme-color-fg-default);\n  padding: 3px;\n  padding-left: 7px;\n  padding-right: 7px;\n  justify-self: center;\n}\n\n.queryeditor-add-button:hover {\n  background-color: var(--theme-color-bg-4);\n  color: var(--theme-color-fg-highlight);\n}\n\n.queryeditor-sorting {\n  display: flex;\n  flex-direction: column;\n  border: 1px solid var(--theme-color-border-strong);\n  padding: 5px;\n}\n\n.queryeditor-sorting-rules {\n  display: flex;\n  flex-direction: column;\n  margin-bottom: 5px;\n}\n\n.queryeditor-span {\n  color: var(--theme-color-fg-default-shy);\n}\n\n.queryeditor-strong {\n  color: var(--theme-color-fg-default);\n  font-weight: bold;\n}\n\n.queryeditor-span-strong {\n  color: var(--theme-color-fg-default);\n  font-weight: bold;\n  margin-left: 5px;\n  margin-right: 5px;\n}\n\n.queryeditor-text-rule {\n  background-color: var(--theme-color-bg-2);\n  padding: 3px;\n}\n\n.queryeditor-text-rule:hover {\n  background-color: var(--theme-color-bg-5);\n}\n\n.queryeditor-trash-icon {\n  content: url('../assets/icons/queryeditor-trash.svg');\n  width: 20px;\n  height: 20px;\n  opacity: 0.6;\n  margin-left: 10px;\n  align-self: center;\n  margin-right: 5px;\n}\n\n.queryeditor-trash-icon:hover {\n  opacity: 0.8;\n}\n\n.queryeditor-sorting-rules {\n  display: flex;\n  flex-direction: column;\n  border: 1px solid var(--theme-color-border-default);\n  padding: 5px;\n  margin-right: 3px;\n  margin-left: 2px;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 75232:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.SchemaPanel-module__Root--gSyIs{display:flex;flex-direction:column;height:100%;background-color:var(--theme-color-bg-2);border-radius:8px;overflow:hidden}.SchemaPanel-module__Header--PY0L6{display:flex;justify-content:space-between;align-items:flex-start;padding:16px;border-bottom:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-3)}.SchemaPanel-module__TableList--cVp2q{flex:1;overflow-y:auto;padding:8px}.SchemaPanel-module__Loading--Zz1YG,.SchemaPanel-module__Error--p510O{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:32px;gap:16px}.SchemaPanel-module__EmptyState--LhvwX{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:48px 24px;text-align:center}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/schemamanager/SchemaPanel.module.scss"],"names":[],"mappings":"AAKA,iCACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,wCAAA,CACA,iBAAA,CACA,eAAA,CAGF,mCACE,YAAA,CACA,6BAAA,CACA,sBAAA,CACA,YAAA,CACA,yDAAA,CACA,wCAAA,CAGF,sCACE,MAAA,CACA,eAAA,CACA,WAAA,CAGF,sEAEE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,YAAA,CACA,QAAA,CAGF,uCACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,iBAAA","sourcesContent":["/**\n * SchemaPanel styles\n * Uses theme tokens from UI-STYLING-GUIDE.md\n */\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  background-color: var(--theme-color-bg-2);\n  border-radius: 8px;\n  overflow: hidden;\n}\n\n.Header {\n  display: flex;\n  justify-content: space-between;\n  align-items: flex-start;\n  padding: 16px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-3);\n}\n\n.TableList {\n  flex: 1;\n  overflow-y: auto;\n  padding: 8px;\n}\n\n.Loading,\n.Error {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  padding: 32px;\n  gap: 16px;\n}\n\n.EmptyState {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  padding: 48px 24px;\n  text-align: center;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `SchemaPanel-module__Root--gSyIs`,
	"Header": `SchemaPanel-module__Header--PY0L6`,
	"TableList": `SchemaPanel-module__TableList--cVp2q`,
	"Loading": `SchemaPanel-module__Loading--Zz1YG`,
	"Error": `SchemaPanel-module__Error--p510O`,
	"EmptyState": `SchemaPanel-module__EmptyState--LhvwX`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 75252:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.GrowingTextArea-module__Root--h8yjZ{background:rgba(0,0,0,0);color:var(--theme-color-fg-highlight);font-family:var(--font-family-regular);font-size:14px;border:none;width:100%;max-height:150px;overflow-x:hidden;overflow-y:auto;resize:none}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/Clippy/components/GrowingTextArea/GrowingTextArea.module.scss"],"names":[],"mappings":"AAAA,qCACI,wBAAA,CACA,qCAAA,CACA,sCAAA,CACA,cAAA,CACA,WAAA,CACA,UAAA,CACA,gBAAA,CACA,iBAAA,CACA,eAAA,CACA,WAAA","sourcesContent":[".Root {\n    background: transparent;\n    color: var(--theme-color-fg-highlight);\n    font-family: var(--font-family-regular);\n    font-size: 14px;\n    border: none;\n    width: 100%;\n    max-height: 150px;\n    overflow-x: hidden;\n    overflow-y: auto;\n    resize: none;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `GrowingTextArea-module__Root--h8yjZ`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 75851:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_propertyeditors_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(82433);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_propertyeditors_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_propertyeditors_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_propertyeditors_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_propertyeditors_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 75864:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  EY: () => (/* binding */ Text),
  $C: () => (/* binding */ TextSize),
  M2: () => (/* binding */ TextType)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/typography/Text/Text.module.scss
var Text_module = __webpack_require__(15836);
;// ../noodl-core-ui/src/components/typography/Text/Text.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(Text_module/* default */.A, options);




       /* harmony default export */ const Text_Text_module = (Text_module/* default */.A && Text_module/* default */.A.locals ? Text_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/typography/Text/Text.tsx



var TextType;
(function (TextType) {
    TextType["Default"] = "default";
    TextType["DefaultContrast"] = "default-contrast";
    TextType["Disabled"] = "disabled";
    TextType["Shy"] = "shy";
    TextType["Proud"] = "proud";
    TextType["Secondary"] = "secondary";
})(TextType || (TextType = {}));
var TextSize;
(function (TextSize) {
    TextSize["Default"] = "default";
    TextSize["Small"] = "small";
    TextSize["Medium"] = "medium";
})(TextSize || (TextSize = {}));
function Text({ children, textType = TextType.Default, size = TextSize.Default, style, className, hasBottomSpacing, isSpan, isCentered, testId }) {
    const Tag = isSpan ? 'span' : 'p';
    return (external_react_default().createElement(Tag, { className: external_classnames_default()([
            Text_Text_module['Root'],
            Text_Text_module[`is-type-${textType}`],
            Text_Text_module[`is-size-${size}`],
            isSpan && Text_Text_module['is-inline'],
            isCentered && Text_Text_module['is-centered'],
            hasBottomSpacing && Text_Text_module['has-bottom-spacing'],
            className
        ]), style: style, "data-test": testId }, children));
}


/***/ }),

/***/ 75928:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DJ: () => (/* binding */ ChatHistory),
/* harmony export */   Pw: () => (/* binding */ ChatHistoryEvent),
/* harmony export */   _J: () => (/* binding */ ChatMessageType)
/* harmony export */ });
/* unused harmony export ChatHistoryState */
/* harmony import */ var _noodl_models_AiAssistant_AiAssistantModel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77510);
/* harmony import */ var _noodl_models_AiAssistant_context_ai_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(36890);
/* harmony import */ var _noodl_utils_model__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(81267);



var ChatMessageType;
(function (ChatMessageType) {
    ChatMessageType["User"] = "user";
    ChatMessageType["Assistant"] = "assistant";
})(ChatMessageType || (ChatMessageType = {}));
var ChatHistoryState;
(function (ChatHistoryState) {
    ChatHistoryState[ChatHistoryState["Idle"] = 0] = "Idle";
    ChatHistoryState[ChatHistoryState["Processing"] = 1] = "Processing";
})(ChatHistoryState || (ChatHistoryState = {}));
var ChatHistoryEvent;
(function (ChatHistoryEvent) {
    ChatHistoryEvent[ChatHistoryEvent["MessagesChanged"] = 0] = "MessagesChanged";
    ChatHistoryEvent[ChatHistoryEvent["ActivitiesChanged"] = 1] = "ActivitiesChanged";
    ChatHistoryEvent[ChatHistoryEvent["MetadataChanged"] = 2] = "MetadataChanged";
})(ChatHistoryEvent || (ChatHistoryEvent = {}));
class ChatHistory extends _noodl_utils_model__WEBPACK_IMPORTED_MODULE_2__/* .Model */ .K {
    get messages() {
        return this._messages;
    }
    get metadata() {
        return this._metadata;
    }
    get activities() {
        return this._activities;
    }
    get suggestions() {
        if (this._messages.length > 0) {
            const metadata = this._messages[this._messages.length - 1].metadata;
            return metadata.suggestions || [];
        }
        // When there are no messages,
        // show a list of example suggestions
        const template = _noodl_models_AiAssistant_AiAssistantModel__WEBPACK_IMPORTED_MODULE_0__/* .AiAssistantModel */ .g.instance.templates.find((x) => x.templateId === this.metadata.templateId);
        if (template) {
            return template.examples.map((x) => ({
                id: x,
                text: x
            }));
        }
        return [];
    }
    constructor(items, metadata = {}) {
        super();
        this._messages = [];
        this._activities = [];
        this._messages = items || [];
        this._metadata = metadata || {};
    }
    addActivity(activity) {
        this._activities.push(activity);
        this.notifyListeners(ChatHistoryEvent.ActivitiesChanged, this._activities);
    }
    removeActivity(activityId) {
        const length = this._activities.length;
        this._activities = this._activities.filter((x) => x.id !== activityId);
        if (this._activities.length !== length) {
            this.notifyListeners(ChatHistoryEvent.ActivitiesChanged, this._activities);
        }
    }
    clearActivities() {
        if (this._activities.length === 0)
            return;
        this._activities.length = 0;
        this.notifyListeners(ChatHistoryEvent.ActivitiesChanged, this._activities);
    }
    add(message) {
        if (!message) {
            throw new Error();
        }
        message.snowflakeId = _noodl_models_AiAssistant_context_ai_utils__WEBPACK_IMPORTED_MODULE_1__/* .AiUtils */ .Y.generateSnowflakeId();
        if (!message.type)
            message.type = ChatMessageType.User;
        if (!message.metadata)
            message.metadata = {};
        this.messages.push(message);
        this.notifyListeners(ChatHistoryEvent.MessagesChanged);
        return message.snowflakeId;
    }
    updateLast(data) {
        if (data.content) {
            this.messages[this.messages.length - 1].content = data.content;
        }
        if (data.metadata) {
            this.messages[this.messages.length - 1].metadata = {
                ...this.messages[this.messages.length - 1].metadata,
                ...data.metadata
            };
        }
        this.notifyListeners(ChatHistoryEvent.MessagesChanged);
    }
    clear() {
        this._messages.length = 0;
        // this.copilot.notifyListeners(CopilotEvent.MessagesChanged);
    }
    removeLast() {
        this._messages.pop();
    }
    toJSON() {
        return {
            history: this._messages,
            metadata: this._metadata
        };
    }
    static fromJSON(json) {
        return new ChatHistory(json === null || json === void 0 ? void 0 : json.history, json === null || json === void 0 ? void 0 : json.metadata);
    }
}


/***/ }),

/***/ 76010:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.CodeHistoryButton-module__Root--PqPEy{position:relative}.CodeHistoryButton-module__Button--ImRV1{display:flex;align-items:center;gap:6px;padding:6px 12px;background:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:4px;color:var(--theme-color-fg-default);font-size:13px;font-weight:500;cursor:pointer;transition:all .15s ease}.CodeHistoryButton-module__Button--ImRV1:hover{background:var(--theme-color-bg-3);border-color:var(--theme-color-border-highlight);color:var(--theme-color-fg-highlight)}.CodeHistoryButton-module__Button--ImRV1:active{transform:translateY(1px)}.CodeHistoryButton-module__Icon--iSGR1{width:16px;height:16px;opacity:.8}.CodeHistoryButton-module__Label--z2qjs{line-height:1}.CodeHistoryButton-module__Dropdown--JZzdC{position:absolute;top:calc(100% + 8px);right:0;z-index:1000;min-width:350px;max-width:450px;background:var(--theme-color-bg-1);border:1px solid var(--theme-color-border-default);border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,.4);animation:CodeHistoryButton-module__slideDown--HMC31 .15s ease}@keyframes CodeHistoryButton-module__slideDown--HMC31{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryButton.module.scss"],"names":[],"mappings":"AAIA,uCACE,iBAAA,CAGF,yCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,gBAAA,CACA,kCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,wBAAA,CAEA,+CACE,kCAAA,CACA,gDAAA,CACA,qCAAA,CAGF,gDACE,yBAAA,CAIJ,uCACE,UAAA,CACA,WAAA,CACA,UAAA,CAGF,wCACE,aAAA,CAGF,2CACE,iBAAA,CACA,oBAAA,CACA,OAAA,CACA,YAAA,CACA,eAAA,CACA,eAAA,CACA,kCAAA,CACA,kDAAA,CACA,iBAAA,CACA,oCAAA,CACA,8DAAA,CAGF,sDACE,KACE,SAAA,CACA,0BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA","sourcesContent":["/**\n * CodeHistoryButton Styles\n */\n\n.Root {\n  position: relative;\n}\n\n.Button {\n  display: flex;\n  align-items: center;\n  gap: 6px;\n  padding: 6px 12px;\n  background: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  color: var(--theme-color-fg-default);\n  font-size: 13px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background: var(--theme-color-bg-3);\n    border-color: var(--theme-color-border-highlight);\n    color: var(--theme-color-fg-highlight);\n  }\n\n  &:active {\n    transform: translateY(1px);\n  }\n}\n\n.Icon {\n  width: 16px;\n  height: 16px;\n  opacity: 0.8;\n}\n\n.Label {\n  line-height: 1;\n}\n\n.Dropdown {\n  position: absolute;\n  top: calc(100% + 8px);\n  right: 0;\n  z-index: 1000;\n  min-width: 350px;\n  max-width: 450px;\n  background: var(--theme-color-bg-1);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 8px;\n  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);\n  animation: slideDown 0.15s ease;\n}\n\n@keyframes slideDown {\n  from {\n    opacity: 0;\n    transform: translateY(-8px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `CodeHistoryButton-module__Root--PqPEy`,
	"Button": `CodeHistoryButton-module__Button--ImRV1`,
	"Icon": `CodeHistoryButton-module__Icon--iSGR1`,
	"Label": `CodeHistoryButton-module__Label--z2qjs`,
	"Dropdown": `CodeHistoryButton-module__Dropdown--JZzdC`,
	"slideDown": `CodeHistoryButton-module__slideDown--HMC31`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 76157:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CallbacksRegistry = void 0;
class CallbacksRegistry {
    constructor() {
        this.nextId = 0;
        this.callbacks = {};
        this.callbackIds = new WeakMap();
        this.locationInfo = new WeakMap();
    }
    add(callback) {
        // The callback is already added.
        let id = this.callbackIds.get(callback);
        if (id != null)
            return id;
        id = this.nextId += 1;
        this.callbacks[id] = callback;
        this.callbackIds.set(callback, id);
        // Capture the location of the function and put it in the ID string,
        // so that release errors can be tracked down easily.
        const regexp = /at (.*)/gi;
        const stackString = (new Error()).stack;
        if (!stackString)
            return id;
        let filenameAndLine;
        let match;
        while ((match = regexp.exec(stackString)) !== null) {
            const location = match[1];
            if (location.includes('(native)'))
                continue;
            if (location.includes('(<anonymous>)'))
                continue;
            if (location.includes('callbacks-registry.js'))
                continue;
            if (location.includes('remote.js'))
                continue;
            if (location.includes('@electron/remote/dist'))
                continue;
            const ref = /([^/^)]*)\)?$/gi.exec(location);
            if (ref)
                filenameAndLine = ref[1];
            break;
        }
        this.locationInfo.set(callback, filenameAndLine);
        return id;
    }
    get(id) {
        return this.callbacks[id] || function () { };
    }
    getLocation(callback) {
        return this.locationInfo.get(callback);
    }
    apply(id, ...args) {
        return this.get(id).apply(global, ...args);
    }
    remove(id) {
        const callback = this.callbacks[id];
        if (callback) {
            this.callbackIds.delete(callback);
            delete this.callbacks[id];
        }
    }
}
exports.CallbacksRegistry = CallbacksRegistry;


/***/ }),

/***/ 76236:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgHomeFill = function SvgHomeFill(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M14.4707 20.141V15.4725C14.4707 15.2662 14.3888 15.0682 14.2428 14.9223C14.0969 14.7764 13.899 14.6944 13.6927 14.6944H10.5803C10.374 14.6944 10.1761 14.7764 10.0302 14.9223C9.88424 15.0682 9.80227 15.2662 9.80227 15.4725V20.141C9.80227 20.3473 9.72029 20.5453 9.57437 20.6912C9.42846 20.8371 9.23055 20.9191 9.02419 20.9191H4.35572C4.14936 20.9191 3.95145 20.8371 3.80553 20.6912C3.65961 20.5453 3.57764 20.3473 3.57764 20.141V11.1444C3.57938 11.0368 3.60265 10.9305 3.64608 10.832C3.68951 10.7334 3.75222 10.6446 3.83051 10.5706L11.6113 3.49982C11.7547 3.3686 11.9421 3.29582 12.1365 3.29582C12.3309 3.29582 12.5183 3.3686 12.6617 3.49982L20.4425 10.5706C20.5208 10.6446 20.5835 10.7334 20.6269 10.832C20.6704 10.9305 20.6936 11.0368 20.6954 11.1444V20.141C20.6954 20.3473 20.6134 20.5453 20.4675 20.6912C20.3216 20.8371 20.1237 20.9191 19.9173 20.9191H15.2488C15.0425 20.9191 14.8446 20.8371 14.6986 20.6912C14.5527 20.5453 14.4707 20.3473 14.4707 20.141Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgHomeFill);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "9211467282173ddf35d9244467ac2faf.svg");

/***/ }),

/***/ 76302:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  jn: () => (/* reexport */ PrimaryButton),
  _S: () => (/* reexport */ PrimaryButtonSize),
  Mw: () => (/* reexport */ PrimaryButtonVariant)
});

// EXTERNAL MODULE: ./src/editor/src/hooks/useParsedHref.ts
var useParsedHref = __webpack_require__(49484);
// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-platform/src/index.ts + 10 modules
var src = __webpack_require__(37218);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/ActivityIndicator/index.ts + 2 modules
var ActivityIndicator = __webpack_require__(12093);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/PrimaryButton/PrimaryButton.module.scss
var PrimaryButton_module = __webpack_require__(22456);
;// ../noodl-core-ui/src/components/inputs/PrimaryButton/PrimaryButton.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(PrimaryButton_module/* default */.A, options);




       /* harmony default export */ const PrimaryButton_PrimaryButton_module = (PrimaryButton_module/* default */.A && PrimaryButton_module/* default */.A.locals ? PrimaryButton_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/PrimaryButton/PrimaryButton.tsx







var PrimaryButtonVariant;
(function (PrimaryButtonVariant) {
    PrimaryButtonVariant["Cta"] = "cta";
    PrimaryButtonVariant["Muted"] = "muted";
    PrimaryButtonVariant["MutedOnLowBg"] = "muted-on-low-bg";
    PrimaryButtonVariant["Ghost"] = "ghost";
    PrimaryButtonVariant["Danger"] = "danger";
})(PrimaryButtonVariant || (PrimaryButtonVariant = {}));
var PrimaryButtonSize;
(function (PrimaryButtonSize) {
    PrimaryButtonSize["Default"] = "default";
    PrimaryButtonSize["Small"] = "small";
})(PrimaryButtonSize || (PrimaryButtonSize = {}));
function PrimaryButton({ label, variant = PrimaryButtonVariant.Cta, size = PrimaryButtonSize.Default, href, icon, isDisabled, isLoading, isFitContent, isGrowing, hasLeftSpacing, hasRightSpacing, hasBottomSpacing, hasTopSpacing, hasXSpacing, onClick, onMouseEnter, onMouseLeave, onFocus, onBlur, testId, UNSAFE_className, UNSAFE_style }) {
    const activityColor = (0,external_react_.useMemo)(() => {
        switch (variant) {
            case PrimaryButtonVariant.Cta:
                return ActivityIndicator/* ActivityIndicatorColor */.Iz.Dark;
            case PrimaryButtonVariant.Muted:
                return ActivityIndicator/* ActivityIndicatorColor */.Iz.Light;
            case PrimaryButtonVariant.Danger:
                return ActivityIndicator/* ActivityIndicatorColor */.Iz.Dark;
            default:
                return ActivityIndicator/* ActivityIndicatorColor */.Iz.Dark;
        }
    }, [variant]);
    const parsedHref = (0,useParsedHref/* default */.A)(href);
    return (external_react_default().createElement("button", { className: external_classnames_default()([
            PrimaryButton_PrimaryButton_module['Root'],
            (hasXSpacing || hasLeftSpacing) && PrimaryButton_PrimaryButton_module['has-left-spacing'],
            (hasXSpacing || hasRightSpacing) && PrimaryButton_PrimaryButton_module['has-right-spacing'],
            hasBottomSpacing && PrimaryButton_PrimaryButton_module['has-bottom-spacing'],
            hasTopSpacing && PrimaryButton_PrimaryButton_module['has-top-spacing'],
            isFitContent && PrimaryButton_PrimaryButton_module['is-fit-content'],
            isGrowing && PrimaryButton_PrimaryButton_module['is-growing'],
            PrimaryButton_PrimaryButton_module[`is-variant-${variant}`],
            PrimaryButton_PrimaryButton_module[`is-size-${size}`],
            UNSAFE_className
        ]), onClick: (e) => {
            if (isLoading)
                return;
            if (parsedHref)
                src.platform.openExternal(parsedHref);
            if (onClick)
                onClick(e);
        }, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, onFocus: onFocus, onBlur: onBlur, disabled: isDisabled, "data-test": testId, style: UNSAFE_style },
        external_react_default().createElement("span", { className: external_classnames_default()([PrimaryButton_PrimaryButton_module['Label'], isLoading && PrimaryButton_PrimaryButton_module['is-loading']]) },
            icon && (external_react_default().createElement(Icon/* Icon */.In, { icon: icon, size: size === PrimaryButtonSize.Small ? Icon/* IconSize */.lK.Small : undefined, UNSAFE_className: PrimaryButton_PrimaryButton_module['Icon'] })),
            label),
        external_react_default().createElement("div", { className: external_classnames_default()([PrimaryButton_PrimaryButton_module['Spinner'], isLoading && PrimaryButton_PrimaryButton_module['is-loading']]) },
            external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, { color: activityColor }))));
}

;// ../noodl-core-ui/src/components/inputs/PrimaryButton/index.ts



/***/ }),

/***/ 76339:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.NodePickerSearchView-module__Grid--n3muq{padding:0;margin:0;list-style:none;border:none;border-radius:0}.NodePickerSearchView-module__Root--JDttn{display:flex;flex-direction:column;overflow:hidden}.NodePickerSearchView-module__SearchContainer--j9xsq{padding:0 15px}.NodePickerSearchView-module__TagList--rkm1V{padding-left:15px;padding-bottom:20px;padding-top:12px;display:flex}.NodePickerSearchView-module__TagList--rkm1V>*{margin-right:5px}.NodePickerSearchView-module__GridContainer--TOHhG{flex-grow:1;flex-shrink:1;overflow-y:overlay;z-index:0}.NodePickerSearchView-module__Grid--n3muq{display:flex;flex-wrap:wrap;margin-left:-16px;margin-top:-16px}.NodePickerSearchView-module__Grid--n3muq>*{margin-left:16px;width:calc(33.3333333333% - 16px);margin-top:16px}.NodePickerSearchView-module__Grid--n3muq{align-items:stretch;padding:5px 10px 16px 15px}`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/placeholders/util.scss","webpack://./src/editor/src/views/NodePicker/tabs/NodePickerSearchView/NodePickerSearchView.module.scss","webpack://./src/editor/src/styles/mixins/layout.scss"],"names":[],"mappings":"AAQA,0CACE,SAAA,CACA,QAAA,CACA,eAAA,CACA,WAAA,CACA,eAAA,CCVF,0CACE,YAAA,CACA,qBAAA,CACA,eAAA,CAGF,qDACE,cAAA,CAGF,6CACE,iBAAA,CACA,mBAAA,CACA,gBAAA,CACA,YAAA,CAEA,+CACE,gBAAA,CAIJ,mDACE,WAAA,CACA,aAAA,CACA,kBAAA,CACA,SAAA,CAGF,0CC4BE,YAAA,CACA,cAAA,CAGE,iBAAA,CAIA,gBAAA,CAtCA,4CAuDA,gBARkB,CASlB,iCAAA,CAMA,eAdgB,CD9CpB,0CAGE,mBAAA,CACA,0BAAA","sourcesContent":["%overlay {\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  right: 0;\n  left: 0;\n}\n\n%reset-styles {\n  padding: 0;\n  margin: 0;\n  list-style: none;\n  border: none;\n  border-radius: 0;\n}\n","@use '@scss-mixins/layout' as *;\n@use '@scss-placeholders/util' as *;\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n\n.SearchContainer {\n  padding: 0 15px;\n}\n\n.TagList {\n  padding-left: 15px;\n  padding-bottom: 20px;\n  padding-top: 12px;\n  display: flex;\n\n  > * {\n    margin-right: 5px;\n  }\n}\n\n.GridContainer {\n  flex-grow: 1;\n  flex-shrink: 1;\n  overflow-y: overlay;\n  z-index: 0;\n}\n\n.Grid {\n  @extend %reset-styles;\n  @include flex-layout(3);\n  align-items: stretch;\n  padding: 5px 10px 16px 15px;\n}\n","@function _format-gutters($value, $direction) {\n  $vertical-gutter: false;\n  $horizontal-gutter: false;\n\n  @if (type-of($value) == list) {\n    @if (nth($value, 1)) {\n      $vertical-gutter: (nth($value, 1));\n    }\n    @if (nth($value, 2)) {\n      $horizontal-gutter: (nth($value, 2));\n    }\n  } @else {\n    $vertical-gutter: $value;\n    $horizontal-gutter: $value;\n  }\n\n  @if ($direction == vertical) {\n    @return $vertical-gutter;\n  } @else {\n    @return $horizontal-gutter;\n  }\n}\n\n@mixin flex-layout($columns: false, $gutters: 16px) {\n  $items: length($columns);\n\n  @if (type-of($columns) == number) {\n    @include flex-row($gutters);\n\n    > * {\n      @include flex-column(calc(1 / $columns), $gutters);\n    }\n  } @else if (type-of($columns) == list and $items > 1) {\n    $column-count: 0;\n\n    @each $column in $columns {\n      $column-count: $column-count + $column;\n    }\n\n    @include flex-row($gutters);\n\n    @for $item from 1 through $items {\n      $width: nth($columns, $item) / $column-count;\n\n      & > *:nth-child(#{$items}n + #{$item}) {\n        @include flex-column($width, $gutters);\n      }\n    }\n  }\n}\n\n/**\n * flex-row()\n */\n\n@mixin flex-row($gutters) {\n  $horizontal-gutter: _format-gutters($gutters, horizontal);\n  $vertical-gutter: _format-gutters($gutters, vertical);\n\n  display: flex;\n  flex-wrap: wrap;\n\n  @if ($horizontal-gutter and $horizontal-gutter != 0) {\n    margin-left: -($horizontal-gutter);\n  }\n\n  @if ($vertical-gutter and $vertical-gutter != 0) {\n    margin-top: -($vertical-gutter);\n  }\n}\n\n/**\n * flex-column()\n */\n\n@mixin flex-column($width, $gutters) {\n  $horizontal-gutter: _format-gutters($gutters, horizontal);\n  $vertical-gutter: _format-gutters($gutters, vertical);\n\n  @if (type-of($width) == number and unitless($width)) {\n    $width: percentage($width);\n  }\n\n  @if ($horizontal-gutter and $horizontal-gutter != 0) {\n    margin-left: $horizontal-gutter;\n    width: calc(#{$width} - #{$horizontal-gutter});\n  } @else {\n    width: $width;\n  }\n\n  @if ($vertical-gutter and $vertical-gutter != 0) {\n    margin-top: $vertical-gutter;\n  }\n}\n\n@function _get-pseudo($pseudo) {\n  @if ($pseudo == false) {\n    $pseudo: '&::after';\n  } @else if (_contains(('after', ':after', '::after', '&:after', '&::after'), $pseudo)) {\n    $pseudo: '&::after';\n  } @else if (_contains(('before', ':before', '::before', '&:before', '&::before'), $pseudo)) {\n    $pseudo: '&::before';\n  }\n\n  @return $pseudo;\n}\n\n@function _is-pseudo($pseudo) {\n  @return ($pseudo == '&::after' or $pseudo == '&::before');\n}\n\n@function _contains($list, $item) {\n  @return index($list, $item) != null;\n}\n\n/**\n * aspect-ratio()\n *\n * Give a heightless element a height based on its width.\n * Always follows the set width:height ratio.\n *\n * @param {number} $width - Without CSS unit\n * @param {number} $height - Without CSS unit\n * @param {string} $pseudo - Optional selector to use insted of default pseudo-element\n */\n\n@mixin aspect-ratio($width, $height, $pseudo: false) {\n  $pseudo: _get-pseudo($pseudo);\n\n  #{$pseudo} {\n    @if (_is-pseudo($pseudo)) {\n      content: '';\n    }\n    display: block;\n    height: 0;\n    padding-bottom: calc((100% / $width) * $height);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Grid": `NodePickerSearchView-module__Grid--n3muq`,
	"Root": `NodePickerSearchView-module__Root--JDttn`,
	"SearchContainer": `NodePickerSearchView-module__SearchContainer--j9xsq`,
	"TagList": `NodePickerSearchView-module__TagList--rkm1V`,
	"GridContainer": `NodePickerSearchView-module__GridContainer--TOHhG`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 76409:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createForm = exports.multipartFormRequestOptions = exports.maybeMultipartFormRequestOptions = exports.isAsyncIterable = exports.checkFileSupport = void 0;
exports.makeFile = makeFile;
exports.getName = getName;
const shims_1 = __webpack_require__(59081);
const checkFileSupport = () => {
    if (typeof File === 'undefined') {
        const { process } = globalThis;
        const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20;
        throw new Error('`File` is not defined as a global, which is required for file uploads.' +
            (isOldNode ?
                " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`."
                : ''));
    }
};
exports.checkFileSupport = checkFileSupport;
/**
 * Construct a `File` instance. This is used to ensure a helpful error is thrown
 * for environments that don't define a global `File` yet.
 */
function makeFile(fileBits, fileName, options) {
    (0, exports.checkFileSupport)();
    return new File(fileBits, fileName ?? 'unknown_file', options);
}
function getName(value) {
    return (((typeof value === 'object' &&
        value !== null &&
        (('name' in value && value.name && String(value.name)) ||
            ('url' in value && value.url && String(value.url)) ||
            ('filename' in value && value.filename && String(value.filename)) ||
            ('path' in value && value.path && String(value.path)))) ||
        '')
        .split(/[\\/]/)
        .pop() || undefined);
}
const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';
exports.isAsyncIterable = isAsyncIterable;
/**
 * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.
 * Otherwise returns the request as is.
 */
const maybeMultipartFormRequestOptions = async (opts, fetch) => {
    if (!hasUploadableValue(opts.body))
        return opts;
    return { ...opts, body: await (0, exports.createForm)(opts.body, fetch) };
};
exports.maybeMultipartFormRequestOptions = maybeMultipartFormRequestOptions;
const multipartFormRequestOptions = async (opts, fetch) => {
    return { ...opts, body: await (0, exports.createForm)(opts.body, fetch) };
};
exports.multipartFormRequestOptions = multipartFormRequestOptions;
const supportsFormDataMap = /* @__PURE__ */ new WeakMap();
/**
 * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending
 * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]".
 * This function detects if the fetch function provided supports the global FormData object to avoid
 * confusing error messages later on.
 */
function supportsFormData(fetchObject) {
    const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch;
    const cached = supportsFormDataMap.get(fetch);
    if (cached)
        return cached;
    const promise = (async () => {
        try {
            const FetchResponse = ('Response' in fetch ?
                fetch.Response
                : (await fetch('data:,')).constructor);
            const data = new FormData();
            if (data.toString() === (await new FetchResponse(data).text())) {
                return false;
            }
            return true;
        }
        catch {
            // avoid false negatives
            return true;
        }
    })();
    supportsFormDataMap.set(fetch, promise);
    return promise;
}
const createForm = async (body, fetch) => {
    if (!(await supportsFormData(fetch))) {
        throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.');
    }
    const form = new FormData();
    await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
    return form;
};
exports.createForm = createForm;
// We check for Blob not File because Bun.File doesn't inherit from File,
// but they both inherit from Blob and have a `name` property at runtime.
const isNamedBlob = (value) => value instanceof Blob && 'name' in value;
const isUploadable = (value) => typeof value === 'object' &&
    value !== null &&
    (value instanceof Response || (0, exports.isAsyncIterable)(value) || isNamedBlob(value));
const hasUploadableValue = (value) => {
    if (isUploadable(value))
        return true;
    if (Array.isArray(value))
        return value.some(hasUploadableValue);
    if (value && typeof value === 'object') {
        for (const k in value) {
            if (hasUploadableValue(value[k]))
                return true;
        }
    }
    return false;
};
const addFormValue = async (form, key, value) => {
    if (value === undefined)
        return;
    if (value == null) {
        throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
    }
    // TODO: make nested formats configurable
    if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
        form.append(key, String(value));
    }
    else if (value instanceof Response) {
        let options = {};
        const contentType = value.headers.get('Content-Type');
        if (contentType) {
            options = { type: contentType };
        }
        form.append(key, makeFile([await value.blob()], getName(value), options));
    }
    else if ((0, exports.isAsyncIterable)(value)) {
        form.append(key, makeFile([await new Response((0, shims_1.ReadableStreamFrom)(value)).blob()], getName(value)));
    }
    else if (isNamedBlob(value)) {
        form.append(key, makeFile([value], getName(value), { type: value.type }));
    }
    else if (Array.isArray(value)) {
        await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry)));
    }
    else if (typeof value === 'object') {
        await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
    }
    else {
        throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
    }
};
//# sourceMappingURL=uploads.js.map

/***/ }),

/***/ 76665:
/***/ ((module) => {

// Module
var code = "<div class=\"content-picker\"> <div data-template=\"item\" class=\"font-picker-list-item content-picker-list-item\" data-click=\"itemClicked\"> <div class=\"content-picker-item\" data-text=\"name\"> </div> </div> <label class=\"content-picker-header-label\">Choose font</label> <div class=\"fontItems content-picker-items\"> </div></div>";
// Exports
module.exports = code;

/***/ }),

/***/ 76750:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   M: () => (/* binding */ useEventListener)
/* harmony export */ });
/* unused harmony export useEventListenerMultiple */
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

/**
 * useEventListener
 *
 * React hook for subscribing to EventDispatcher events.
 *
 * This hook solves the incompatibility between React's closure-based
 * lifecycle and EventDispatcher's context-object-based cleanup pattern.
 *
 * @example
 * ```tsx
 * useEventListener(ProjectModel.instance, 'componentRenamed', (data) => {
 *   console.log('Component renamed:', data);
 *   setUpdateCounter(c => c + 1);
 * });
 * ```
 *
 * @see dev-docs/tasks/phase-2/TASK-008-eventdispatcher-react-investigation/
 */
// 🔥 MODULE LOAD MARKER - If you see this, the new useEventListener code is loaded!
console.log('🔥🔥🔥 useEventListener.ts MODULE LOADED WITH DEBUG LOGS - Version 2.0 🔥🔥🔥');
/**
 * Subscribe to an EventDispatcher event with proper React lifecycle handling.
 *
 * Key features:
 * - Prevents stale closures by using useRef for the callback
 * - Creates stable group reference for proper cleanup
 * - Automatically unsubscribes on unmount or when dependencies change
 *
 * @param dispatcher - The EventDispatcher instance to subscribe to
 * @param eventName - Name of the event to listen for (or array of event names)
 * @param callback - Function to call when event is emitted
 * @param deps - Optional dependency array (like useEffect). If provided, re-subscribes when deps change
 */
function useEventListener(dispatcher, eventName, callback, deps) {
    // Store callback in ref to avoid stale closures
    const callbackRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(callback);
    // Update ref whenever callback changes
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        callbackRef.current = callback;
    });
    // Set up subscription
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        if (!dispatcher) {
            return;
        }
        // Create wrapper that calls the current callback ref
        const wrapper = (data, emittedEventName) => {
            callbackRef.current(data, emittedEventName);
        };
        // Create stable group object for cleanup
        // Using a unique object ensures proper unsubscription
        const group = { id: `useEventListener_${Math.random()}` };
        // Subscribe to event(s)
        dispatcher.on(eventName, wrapper, group);
        // Cleanup: unsubscribe when unmounting or dependencies change
        return () => {
            dispatcher.off(group);
        };
    }, 
    // CRITICAL: Always spread eventName array into dependencies, never pass array directly
    // React's Object.is() comparison fails with arrays, causing useEffect to never run
    deps
        ? [dispatcher, ...(Array.isArray(eventName) ? eventName : [eventName]), ...deps]
        : [dispatcher, ...(Array.isArray(eventName) ? eventName : [eventName])]);
}
/**
 * Subscribe to multiple events from the same dispatcher.
 *
 * This is a convenience wrapper around useEventListener for cases where
 * you need to subscribe to multiple events with the same callback.
 *
 * @example
 * ```tsx
 * useEventListenerMultiple(
 *   ProjectModel.instance,
 *   ['componentAdded', 'componentRemoved', 'componentRenamed'],
 *   () => setUpdateCounter(c => c + 1)
 * );
 * ```
 */
function useEventListenerMultiple(dispatcher, eventNames, callback, deps) {
    useEventListener(dispatcher, eventNames, callback, deps);
}


/***/ }),

/***/ 76760:
/***/ ((module) => {

"use strict";
module.exports = require("node:path");

/***/ }),

/***/ 76789:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PropertyPanelIconRadioInput-module__Root--Zh363{display:flex;margin-left:-3px}.PropertyPanelIconRadioInput-module__Option--a9_iA{position:relative;cursor:pointer;user-select:none;display:block;margin-left:2px;background-color:var(--theme-color-bg-3);display:flex;align-items:center;justify-content:center;padding:2px}.PropertyPanelIconRadioInput-module__Option--a9_iA:hover svg path{fill:var(--theme-color-fg-highlight)}.PropertyPanelIconRadioInput-module__Option--a9_iA svg{display:block;pointer-events:none}.PropertyPanelIconRadioInput-module__Option--a9_iA svg path{fill:var(--theme-color-fg-default)}.PropertyPanelIconRadioInput-module__Option--a9_iA.PropertyPanelIconRadioInput-module__is-selected--HCf_r{background-color:var(--theme-color-bg-1)}.PropertyPanelIconRadioInput-module__Option--a9_iA.PropertyPanelIconRadioInput-module__is-selected--HCf_r svg path{fill:var(--theme-color-fg-highlight)}.PropertyPanelIconRadioInput-module__Option--a9_iA.PropertyPanelIconRadioInput-module__is-disabled--YJFMM{cursor:not-allowed;background-color:var(--theme-color-bg-2)}.PropertyPanelIconRadioInput-module__Option--a9_iA.PropertyPanelIconRadioInput-module__is-disabled--YJFMM svg path{fill:var(--theme-color-fg-muted)}.PropertyPanelIconRadioInput-module__Input--toqIR{position:absolute;opacity:0;height:0}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/property-panel/PropertyPanelIconRadioInput/PropertyPanelIconRadioInput.module.scss"],"names":[],"mappings":"AAAA,iDACE,YAAA,CACA,gBAAA,CAGF,mDACE,iBAAA,CACA,cAAA,CACA,gBAAA,CACA,aAAA,CACA,eAAA,CACA,wCAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,WAAA,CAGE,kEACE,oCAAA,CAIJ,uDACE,aAAA,CACA,mBAAA,CAEA,4DACE,kCAAA,CAIJ,0GACE,wCAAA,CAGE,mHACE,oCAAA,CAKN,0GACE,kBAAA,CACA,wCAAA,CAGE,mHACE,gCAAA,CAMR,kDACE,iBAAA,CACA,SAAA,CACA,QAAA","sourcesContent":[".Root {\n  display: flex;\n  margin-left: -3px; // using -3 for visual compensation\n}\n\n.Option {\n  position: relative;\n  cursor: pointer;\n  user-select: none;\n  display: block;\n  margin-left: 2px;\n  background-color: var(--theme-color-bg-3);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  padding: 2px;\n\n  &:hover {\n    svg path {\n      fill: var(--theme-color-fg-highlight);\n    }\n  }\n\n  svg {\n    display: block;\n    pointer-events: none;\n\n    path {\n      fill: var(--theme-color-fg-default);\n    }\n  }\n\n  &.is-selected {\n    background-color: var(--theme-color-bg-1);\n\n    svg {\n      path {\n        fill: var(--theme-color-fg-highlight);\n      }\n    }\n  }\n\n  &.is-disabled {\n    cursor: not-allowed;\n    background-color: var(--theme-color-bg-2);\n\n    svg {\n      path {\n        fill: var(--theme-color-fg-muted);\n      }\n    }\n  }\n}\n\n.Input {\n  position: absolute;\n  opacity: 0;\n  height: 0;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PropertyPanelIconRadioInput-module__Root--Zh363`,
	"Option": `PropertyPanelIconRadioInput-module__Option--a9_iA`,
	"is-selected": `PropertyPanelIconRadioInput-module__is-selected--HCf_r`,
	"is-disabled": `PropertyPanelIconRadioInput-module__is-disabled--YJFMM`,
	"Input": `PropertyPanelIconRadioInput-module__Input--toqIR`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 76817:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ValueEditor-module__InputEditor--_LC9U{display:flex;align-items:center;gap:6px;flex:1}.ValueEditor-module__Input--VZrXU{flex:1;padding:4px 8px;font-size:13px;font-family:"Menlo","Monaco","Courier New",monospace;background-color:var(--theme-color-bg-1);border:1px solid var(--theme-color-primary);border-radius:3px;color:var(--theme-color-fg-default);outline:none;box-shadow:0 0 0 2px rgba(59,130,246,.1)}.ValueEditor-module__Input--VZrXU:focus{border-color:var(--theme-color-primary);box-shadow:0 0 0 2px rgba(59,130,246,.2)}.ValueEditor-module__Input--VZrXU::placeholder{color:var(--theme-color-fg-muted);opacity:.6}.ValueEditor-module__ButtonGroup--NWe3P{display:flex;gap:4px}.ValueEditor-module__SaveButton--U3yBa,.ValueEditor-module__CancelButton--OUcZR,.ValueEditor-module__CloseButton--aYBYd{padding:4px 8px;font-size:14px;font-weight:bold;border:none;border-radius:3px;cursor:pointer;transition:all .15s ease;line-height:1}.ValueEditor-module__SaveButton--U3yBa{background-color:var(--theme-color-primary);color:#fff}.ValueEditor-module__SaveButton--U3yBa:hover{opacity:.9}.ValueEditor-module__CancelButton--OUcZR,.ValueEditor-module__CloseButton--aYBYd{background-color:var(--theme-color-bg-3);color:var(--theme-color-fg-default)}.ValueEditor-module__CancelButton--OUcZR:hover,.ValueEditor-module__CloseButton--aYBYd:hover{background-color:var(--theme-color-bg-2)}.ValueEditor-module__BooleanEditor--gkKoo{display:flex;align-items:center}.ValueEditor-module__BooleanToggle--QQVyj{display:flex;align-items:center;gap:8px;cursor:pointer;padding:4px 8px;border-radius:3px;background-color:var(--theme-color-bg-3);transition:background-color .15s ease}.ValueEditor-module__BooleanToggle--QQVyj:hover{background-color:var(--theme-color-bg-2)}.ValueEditor-module__BooleanToggle--QQVyj input[type=checkbox]{width:16px;height:16px;cursor:pointer}.ValueEditor-module__ToggleLabel--WrUeS{font-size:13px;font-weight:500;color:var(--theme-color-fg-default);user-select:none}.ValueEditor-module__NullEditor--pNe7N{display:flex;align-items:center;gap:8px;padding:4px 8px;background-color:var(--theme-color-bg-3);border-radius:3px}.ValueEditor-module__NullValue--Ow2sL{font-size:13px;font-style:italic;color:#6b7280}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/json-editor/modes/EasyMode/ValueEditor.module.scss"],"names":[],"mappings":"AAKA,wCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,MAAA,CAGF,kCACE,MAAA,CACA,eAAA,CACA,cAAA,CACA,oDAAA,CACA,wCAAA,CACA,2CAAA,CACA,iBAAA,CACA,mCAAA,CACA,YAAA,CACA,wCAAA,CAEA,wCACE,uCAAA,CACA,wCAAA,CAGF,+CACE,iCAAA,CACA,UAAA,CAIJ,wCACE,YAAA,CACA,OAAA,CAGF,wHAGE,eAAA,CACA,cAAA,CACA,gBAAA,CACA,WAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CACA,aAAA,CAGF,uCACE,2CAAA,CACA,UAAA,CAEA,6CACE,UAAA,CAIJ,iFAEE,wCAAA,CACA,mCAAA,CAEA,6FACE,wCAAA,CAKJ,0CACE,YAAA,CACA,kBAAA,CAGF,0CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,cAAA,CACA,eAAA,CACA,iBAAA,CACA,wCAAA,CACA,qCAAA,CAEA,gDACE,wCAAA,CAGF,+DACE,UAAA,CACA,WAAA,CACA,cAAA,CAIJ,wCACE,cAAA,CACA,eAAA,CACA,mCAAA,CACA,gBAAA,CAIF,uCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,eAAA,CACA,wCAAA,CACA,iBAAA,CAGF,sCACE,cAAA,CACA,iBAAA,CACA,aAAA","sourcesContent":["/**\n * ValueEditor Styles\n */\n\n/* Input Editor (String/Number) */\n.InputEditor {\n  display: flex;\n  align-items: center;\n  gap: 6px;\n  flex: 1;\n}\n\n.Input {\n  flex: 1;\n  padding: 4px 8px;\n  font-size: 13px;\n  font-family: 'Menlo', 'Monaco', 'Courier New', monospace;\n  background-color: var(--theme-color-bg-1);\n  border: 1px solid var(--theme-color-primary);\n  border-radius: 3px;\n  color: var(--theme-color-fg-default);\n  outline: none;\n  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);\n\n  &:focus {\n    border-color: var(--theme-color-primary);\n    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);\n  }\n\n  &::placeholder {\n    color: var(--theme-color-fg-muted);\n    opacity: 0.6;\n  }\n}\n\n.ButtonGroup {\n  display: flex;\n  gap: 4px;\n}\n\n.SaveButton,\n.CancelButton,\n.CloseButton {\n  padding: 4px 8px;\n  font-size: 14px;\n  font-weight: bold;\n  border: none;\n  border-radius: 3px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n  line-height: 1;\n}\n\n.SaveButton {\n  background-color: var(--theme-color-primary);\n  color: white;\n\n  &:hover {\n    opacity: 0.9;\n  }\n}\n\n.CancelButton,\n.CloseButton {\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-default);\n\n  &:hover {\n    background-color: var(--theme-color-bg-2);\n  }\n}\n\n/* Boolean Editor */\n.BooleanEditor {\n  display: flex;\n  align-items: center;\n}\n\n.BooleanToggle {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  cursor: pointer;\n  padding: 4px 8px;\n  border-radius: 3px;\n  background-color: var(--theme-color-bg-3);\n  transition: background-color 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-2);\n  }\n\n  input[type='checkbox'] {\n    width: 16px;\n    height: 16px;\n    cursor: pointer;\n  }\n}\n\n.ToggleLabel {\n  font-size: 13px;\n  font-weight: 500;\n  color: var(--theme-color-fg-default);\n  user-select: none;\n}\n\n/* Null Editor */\n.NullEditor {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 4px 8px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 3px;\n}\n\n.NullValue {\n  font-size: 13px;\n  font-style: italic;\n  color: #6b7280;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"InputEditor": `ValueEditor-module__InputEditor--_LC9U`,
	"Input": `ValueEditor-module__Input--VZrXU`,
	"ButtonGroup": `ValueEditor-module__ButtonGroup--NWe3P`,
	"SaveButton": `ValueEditor-module__SaveButton--U3yBa`,
	"CancelButton": `ValueEditor-module__CancelButton--OUcZR`,
	"CloseButton": `ValueEditor-module__CloseButton--aYBYd`,
	"BooleanEditor": `ValueEditor-module__BooleanEditor--gkKoo`,
	"BooleanToggle": `ValueEditor-module__BooleanToggle--QQVyj`,
	"ToggleLabel": `ValueEditor-module__ToggleLabel--WrUeS`,
	"NullEditor": `ValueEditor-module__NullEditor--pNe7N`,
	"NullValue": `ValueEditor-module__NullValue--Ow2sL`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 76849:
/***/ ((module) => {

// Module
var code = "<div class=\"yes-no-popup\"> <label class=\"yes-no-popup-label\" data-html=\"label\"></label> <div class=\"yes-no-popup-buttons\"> <button class=\"yes-no-popup-button-yes\" data-click=\"onYesClicked\" data-text=\"yesLabel\"></button> <button class=\"yes-no-popup-button-no\" data-click=\"onNoClicked\" data-text=\"noLabel\"></button> </div> </div>";
// Exports
module.exports = code;

/***/ }),

/***/ 76976:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   D: () => (/* binding */ KeyCode)
/* harmony export */ });
var KeyCode;
(function (KeyCode) {
    KeyCode[KeyCode["Up"] = 38] = "Up";
    KeyCode[KeyCode["Down"] = 40] = "Down";
    KeyCode[KeyCode["Left"] = 37] = "Left";
    KeyCode[KeyCode["Right"] = 39] = "Right";
    KeyCode[KeyCode["ESC"] = 27] = "ESC";
    KeyCode[KeyCode["Enter"] = 13] = "Enter";
    KeyCode[KeyCode["Space"] = 32] = "Space";
})(KeyCode || (KeyCode = {}));


/***/ }),

/***/ 76982:
/***/ ((module) => {

"use strict";
module.exports = require("crypto");

/***/ }),

/***/ 77120:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _metadata, _g;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgLogo = function SvgLogo(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    xmlns: "http://www.w3.org/2000/svg",
    width: "30px",
    height: "30px",
    viewBox: "0 0 512 512",
    preserveAspectRatio: "xMidYMid meet",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _metadata || (_metadata = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("metadata", null, "\nCreated by potrace 1.10, written by Peter Selinger 2001-2011\n")), _g || (_g = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("g", {
    transform: "scale(0.16, -0.16) translate(0, -3200)",
    fill: "#ffffff",
    stroke: "none"
  }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M1345 3084 c-122 -18 -294 -61 -305 -76 -3 -4 -39 -21 -79 -38 -140 -57 -290 -156 -436 -286 -173 -155 -350 -399 -422 -583 -114 -292 -133 -639 -51 -961 21 -86 90 -254 139 -344 444 -805 1454 -1042 2175 -511 316 233 531 574 606 962 34 176 32 438 -4 614 -43 205 -134 416 -247 565 -71 95 -338 356 -421 411 -264 175 -467 241 -765 248 -88 2 -173 1 -190 -1z m304 -207 c108 -67 238 -259 320 -472 17 -43 29 -80 28 -82 -2 -1 -39 -9 -82 -18 -43 -8 -86 -17 -96 -20 -14 -5 -20 2 -29 36 -25 93 -99 169 -189 196 -151 44 -312 -39 -358 -184 -14 -44 -20 -52 -37 -48 -12 2 -54 10 -94 16 -41 7 -76 18 -78 24 -14 35 121 310 209 427 124 165 268 209 406 125z m-539 -52 c0 -3 -23 -40 -52 -82 -55 -82 -124 -224 -153 -313 -23 -73 -21 -70 -58 -58 -55 18 -234 105 -241 116 -8 14 58 79 158 153 94 71 179 122 266 160 67 29 80 33 80 24z m913 -40 c109 -54 243 -148 335 -235 l66 -62 -59 -31 c-73 -37 -194 -87 -209 -87 -6 0 -24 35 -40 78 -40 108 -110 247 -154 307 -70 93 -68 94 61 30z m-1458 -449 c43 -25 112 -57 154 -72 42 -15 87 -31 100 -36 17 -6 21 -13 16 -26 -14 -35 -53 -200 -65 -274 l-12 -76 -52 5 c-85 9 -158 -18 -221 -81 -34 -34 -58 -68 -66 -95 -15 -50 -24 -53 -139 -49 l-85 3 3 55 c5 90 66 310 116 412 37 77 160 278 170 278 1 0 38 -20 81 -44z m1020 10 c54 -35 74 -128 39 -181 -36 -55 -120 -72 -179 -35 -37 23 -57 63 -57 115 0 97 114 155 197 101z m992 -42 c61 -85 148 -266 176 -364 31 -107 61 -275 53 -295 -4 -12 -24 -15 -95 -15 l-90 0 -31 64 c-51 107 -130 158 -249 162 l-75 3 -18 108 c-16 93 -37 190 -53 243 -4 12 16 22 78 43 45 16 118 48 162 71 44 24 85 42 90 41 6 -1 29 -28 52 -61z m-1479 -149 c46 -8 96 -15 111 -15 21 0 31 -10 53 -50 30 -53 95 -108 140 -117 39 -8 50 -25 46 -74 -3 -40 -5 -43 -45 -56 -63 -21 -138 -93 -161 -156 l-20 -52 -122 0 -122 0 -12 37 c-7 20 -27 56 -44 79 -20 26 -30 50 -27 63 51 235 78 353 82 359 3 5 12 6 20 3 9 -4 54 -13 101 -21z m965 -32 c14 -51 46 -209 60 -298 4 -23 -2 -38 -29 -68 -18 -22 -39 -58 -47 -81 l-14 -41 -111 -3 -112 -3 -24 55 c-29 66 -92 129 -152 152 l-44 17 0 53 0 53 53 24 c58 27 119 84 137 128 9 21 19 29 39 29 14 1 67 9 116 19 50 10 95 19 101 20 6 0 19 -25 27 -56z m-1313 -438 c75 -39 92 -148 32 -207 -79 -80 -222 -21 -222 92 0 93 107 158 190 115z m821 0 c65 -34 91 -135 48 -189 -61 -78 -165 -73 -220 10 -37 56 -13 134 53 174 40 24 79 25 119 5z m842 -24 c87 -86 27 -221 -98 -221 -42 0 -52 4 -81 35 -57 61 -55 132 4 188 33 31 55 37 107 31 26 -3 50 -15 68 -33z m-1992 -216 c60 -115 150 -169 271 -164 l62 3 18 -120 c10 -65 29 -163 42 -217 21 -89 22 -99 7 -104 -61 -21 -208 -88 -257 -117 -32 -20 -62 -36 -66 -36 -12 0 -115 163 -161 255 -51 104 -80 185 -108 303 -22 91 -40 232 -32 245 2 4 48 6 101 5 l97 -3 26 -50z m808 24 c6 -17 27 -53 47 -80 28 -38 52 -57 105 -82 l69 -32 0 -51 0 -51 -65 -32 c-72 -36 -128 -98 -145 -161 -10 -36 -11 -37 -82 -49 -40 -7 -96 -19 -125 -26 -47 -12 -53 -11 -57 4 -13 45 -58 266 -70 344 l-13 87 33 48 c19 26 34 50 34 54 0 4 4 18 10 32 9 26 10 26 129 26 l119 0 11 -31z m811 -1 c7 -18 28 -54 47 -81 18 -26 33 -59 33 -75 0 -43 -28 -218 -51 -319 -22 -101 -23 -101 -89 -84 -19 5 -67 15 -106 21 l-72 11 -16 44 c-30 77 -69 121 -141 155 -70 33 -71 36 -59 112 5 28 12 38 31 43 63 15 128 77 172 163 l21 42 109 0 109 0 12 -32z m770 -5 c0 -121 -66 -377 -136 -530 -26 -58 -110 -203 -139 -241 -1 -1 -49 22 -106 52 -57 30 -134 67 -171 81 -38 15 -68 30 -68 34 0 3 7 29 16 56 15 52 54 290 54 338 0 27 1 27 63 27 35 0 84 7 110 16 64 22 135 87 163 151 l24 53 95 0 95 0 0 -37z m-1246 -467 c50 -21 76 -60 76 -116 0 -138 -185 -180 -244 -55 -31 65 -10 124 59 166 36 23 64 24 109 5z m-314 -247 c32 -61 99 -123 155 -142 147 -50 292 4 371 139 14 24 29 44 32 44 4 0 46 -7 95 -17 55 -10 87 -21 87 -29 0 -48 -105 -278 -171 -375 -88 -130 -170 -186 -286 -196 -128 -10 -228 50 -323 195 -68 103 -180 338 -180 378 0 7 32 18 78 27 119 22 119 22 142 -24z m-341 -121 c34 -86 103 -226 150 -307 30 -51 31 -52 9 -46 -42 13 -206 96 -270 137 -72 46 -198 147 -198 158 0 12 268 145 276 137 1 -1 16 -37 33 -79z m1469 -30 c17 -11 32 -25 32 -32 0 -18 -175 -156 -261 -206 -71 -42 -209 -103 -216 -96 -2 2 13 27 33 57 48 72 99 173 141 284 19 49 37 93 39 97 5 7 177 -70 232 -104z"
  }))));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgLogo);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "1edbeb8826034ee05327d63b1587f77e.svg");

/***/ }),

/***/ 77504:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/* -------------------------------------------------------------------
   Property editor
   ------------------------------------------------------------------- */

.sidebar-property-editor {
  overflow: hidden auto;
  height: 100%;
}

.property-changed-dot {
  position: absolute;
  top: 9px;
  left: 4px;
  height: 16px;
  width: 16px;
  -webkit-mask-size: contain;
  -webkit-mask-image: url(../assets/icons/editor/reset-to-default.svg);
  background: var(--theme-color-fg-default);
}

.property-changed-dot:hover {
  background-color: var(--theme-color-fg-highlight);
  cursor: pointer;
}

.property-changed-dot-noreset {
  position: absolute;
  left: 5px;
  top: 12px;
  height: 10px;
  width: 10px;
  background-color: var(--theme-color-fg-muted);
  border-radius: 50%;
}

.property-label {
  line-height: 35px;
  padding-right: 10px;
  color: var(--theme-color-fg-default);
  text-align: right;
  white-space: nowrap;
  width: 150px;
  position: absolute;
}

.property-value {
  position: absolute;
  left: 160px;
  right: 10px;
  top: 1px;
  bottom: 1px;
}

.property-input-dropdown {
  position: absolute;
  z-index: 10;
  /* overflow:scroll;*/
}

.property-input-dropdown-arrow {
  color: var(--theme-color-fg-muted);
}

.property-input-dropdown-arrow:hover {
  color: var(--theme-color-fg-highlight);
}

.property-input-enum:hover {
  background-color: var(--theme-color-border-strong);
  cursor: pointer;
}

.property-input-enum {
  background-color: var(--theme-color-bg-0);
  color: var(--theme-color-fg-highlight);
  min-height: 30px;
  line-height: 30px;
  padding-left: 10px;
}

.property-input-enum + .property-input-enum {
  border-top: 1px solid var(--theme-color-border-subtle);
}

.property-input-connected {
  border: 1px solid var(--theme-color-primary-dim);
}

.property-input-default {
  color: var(--theme-color-fg-default);
  font-weight: var(--font-weight-regular);
}

.property-input-focused {
  color: var(--theme-color-fg-highlight);
  background-color: var(--theme-color-bg-0);
}

.property-input-color {
  background-color: var(--theme-color-bg-2);
}

.property-input-color-hidden {
  opacity: 0;
  display: block;
  border: none;
  padding: 0;
}

.property-input-textarea {
  resize: vertical;
  padding-top: 10px;
  min-height: 35px;
  font-size: 12px;
}

.property-input-textarea:focus {
  color: var(--theme-color-fg-highlight);
  background-color: var(--theme-color-bg-0);
}

.property-input-textarea-bg {
  margin-bottom: 1px;
  flex-grow: 1;
  margin-right: 10px;
}

.property-group-label {
  padding: 12px 6px;
  display: block;
  color: var(--theme-color-fg-highlight);
  font-weight: var(--font-weight-semibold);
}

.property-group:not(:last-child) {
  border-bottom: 1px solid var(--theme-color-bg-1);
}

.property-header-bar {
  background-color: var(--theme-color-bg-2);
  border-bottom: 1px solid var(--theme-color-bg-1);
  position: relative;
  display: flex;
  align-items: center;
}

.header-name-edit-container {
  min-height: 35px;
  font: bold 12px var(--font-family-regular);
}

.property-header-bar-label {
  color: var(--theme-color-fg-highlight);
  font: 12px var(--font-family-regular);
  padding: 10px 0 10px 10px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.property-panel-header-edit-bar {
  padding-right: 0;
  right: 0;
}

.property-panel-header-edit-button {
  width: 35px;
  height: 35px;
}

.property-editor-highlight {
  color: var(--theme-color-notice);
}

.property-editor-highlight:hover {
  background-color: var(--theme-color-notice);
  color: var(--theme-color-fg-highlight);
}

.property-codeeditor-button {
  background-color: var(--theme-color-bg-3);
  border: none;
  color: var(--theme-color-fg-default);
  margin: 0px;
}

.property-codeeditor-button:hover {
  background-color: var(--theme-color-bg-1);
  color: var(--theme-color-fg-highlight);
}

.property-number-units {
  text-align: center;
  cursor: default;
}

.property-number-unit-enum {
  background-color: var(--theme-color-bg-0);
  color: var(--theme-color-fg-highlight);
  height: 30px;
  line-height: 30px;
  cursor: default;
}

.property-number-unit-enum + .property-number-unit-enum {
  border-top: 1px solid var(--theme-color-border-subtle);
}

.property-number-unit-enum:hover {
  background-color: var(--theme-color-border-strong);
}

.property-dimension-fixed-disabled {
  pointer-events: none;
  opacity: 0.3;
}

.property-tab {
  opacity: 0.25;
  margin-left: 5px;
  margin-right: 5px;
}

.property-tab.selected {
  opacity: 1;
}

.property-tab-icon {
  width: 32px;
  height: 32px;
}

.property-tab-icon.borders-all {
  content: url('../assets/icons/property-tab-borders-all.svg');
}

.property-tab-icon.borders-left {
  content: url('../assets/icons/property-tab-borders-left.svg');
}

.property-tab-icon.borders-right {
  content: url('../assets/icons/property-tab-borders-right.svg');
}

.property-tab-icon.borders-bottom {
  content: url('../assets/icons/property-tab-borders-bottom.svg');
}

.property-tab-icon.borders-top {
  content: url('../assets/icons/property-tab-borders-top.svg');
}

.property-tab-icon.corners-all {
  content: url('../assets/icons/property-tab-corners-all.svg');
}

.property-tab-icon.corners-top-left {
  content: url('../assets/icons/property-tab-corners-top-left.svg');
}

.property-tab-icon.corners-top-right {
  content: url('../assets/icons/property-tab-corners-top-right.svg');
}

.property-tab-icon.corners-bottom-left {
  content: url('../assets/icons/property-tab-corners-bottom-left.svg');
}

.property-tab-icon.corners-bottom-right {
  content: url('../assets/icons/property-tab-corners-bottom-right.svg');
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/propertyeditor/propertyeditor.css"],"names":[],"mappings":"AAAA;;wEAEwE;;AAExE;EACE,qBAAqB;EACrB,YAAY;AACd;;AAEA;EACE,kBAAkB;EAClB,QAAQ;EACR,SAAS;EACT,YAAY;EACZ,WAAW;EACX,0BAA0B;EAC1B,oEAAoE;EACpE,yCAAyC;AAC3C;;AAEA;EACE,iDAAiD;EACjD,eAAe;AACjB;;AAEA;EACE,kBAAkB;EAClB,SAAS;EACT,SAAS;EACT,YAAY;EACZ,WAAW;EACX,6CAA6C;EAC7C,kBAAkB;AACpB;;AAEA;EACE,iBAAiB;EACjB,mBAAmB;EACnB,oCAAoC;EACpC,iBAAiB;EACjB,mBAAmB;EACnB,YAAY;EACZ,kBAAkB;AACpB;;AAEA;EACE,kBAAkB;EAClB,WAAW;EACX,WAAW;EACX,QAAQ;EACR,WAAW;AACb;;AAEA;EACE,kBAAkB;EAClB,WAAW;EACX,oBAAoB;AACtB;;AAEA;EACE,kCAAkC;AACpC;;AAEA;EACE,sCAAsC;AACxC;;AAEA;EACE,kDAAkD;EAClD,eAAe;AACjB;;AAEA;EACE,yCAAyC;EACzC,sCAAsC;EACtC,gBAAgB;EAChB,iBAAiB;EACjB,kBAAkB;AACpB;;AAEA;EACE,sDAAsD;AACxD;;AAEA;EACE,gDAAgD;AAClD;;AAEA;EACE,oCAAoC;EACpC,uCAAuC;AACzC;;AAEA;EACE,sCAAsC;EACtC,yCAAyC;AAC3C;;AAEA;EACE,yCAAyC;AAC3C;;AAEA;EACE,UAAU;EACV,cAAc;EACd,YAAY;EACZ,UAAU;AACZ;;AAEA;EACE,gBAAgB;EAChB,iBAAiB;EACjB,gBAAgB;EAChB,eAAe;AACjB;;AAEA;EACE,sCAAsC;EACtC,yCAAyC;AAC3C;;AAEA;EACE,kBAAkB;EAClB,YAAY;EACZ,kBAAkB;AACpB;;AAEA;EACE,iBAAiB;EACjB,cAAc;EACd,sCAAsC;EACtC,wCAAwC;AAC1C;;AAEA;EACE,gDAAgD;AAClD;;AAEA;EACE,yCAAyC;EACzC,gDAAgD;EAChD,kBAAkB;EAClB,aAAa;EACb,mBAAmB;AACrB;;AAEA;EACE,gBAAgB;EAChB,0CAA0C;AAC5C;;AAEA;EACE,sCAAsC;EACtC,qCAAqC;EACrC,yBAAyB;EACzB,uBAAuB;EACvB,mBAAmB;EACnB,gBAAgB;AAClB;;AAEA;EACE,gBAAgB;EAChB,QAAQ;AACV;;AAEA;EACE,WAAW;EACX,YAAY;AACd;;AAEA;EACE,gCAAgC;AAClC;;AAEA;EACE,2CAA2C;EAC3C,sCAAsC;AACxC;;AAEA;EACE,yCAAyC;EACzC,YAAY;EACZ,oCAAoC;EACpC,WAAW;AACb;;AAEA;EACE,yCAAyC;EACzC,sCAAsC;AACxC;;AAEA;EACE,kBAAkB;EAClB,eAAe;AACjB;;AAEA;EACE,yCAAyC;EACzC,sCAAsC;EACtC,YAAY;EACZ,iBAAiB;EACjB,eAAe;AACjB;;AAEA;EACE,sDAAsD;AACxD;;AAEA;EACE,kDAAkD;AACpD;;AAEA;EACE,oBAAoB;EACpB,YAAY;AACd;;AAEA;EACE,aAAa;EACb,gBAAgB;EAChB,iBAAiB;AACnB;;AAEA;EACE,UAAU;AACZ;;AAEA;EACE,WAAW;EACX,YAAY;AACd;;AAEA;EACE,4DAA4D;AAC9D;;AAEA;EACE,6DAA6D;AAC/D;;AAEA;EACE,8DAA8D;AAChE;;AAEA;EACE,+DAA+D;AACjE;;AAEA;EACE,4DAA4D;AAC9D;;AAEA;EACE,4DAA4D;AAC9D;;AAEA;EACE,iEAAiE;AACnE;;AAEA;EACE,kEAAkE;AACpE;;AAEA;EACE,oEAAoE;AACtE;;AAEA;EACE,qEAAqE;AACvE","sourcesContent":["/* -------------------------------------------------------------------\n   Property editor\n   ------------------------------------------------------------------- */\n\n.sidebar-property-editor {\n  overflow: hidden auto;\n  height: 100%;\n}\n\n.property-changed-dot {\n  position: absolute;\n  top: 9px;\n  left: 4px;\n  height: 16px;\n  width: 16px;\n  -webkit-mask-size: contain;\n  -webkit-mask-image: url(../assets/icons/editor/reset-to-default.svg);\n  background: var(--theme-color-fg-default);\n}\n\n.property-changed-dot:hover {\n  background-color: var(--theme-color-fg-highlight);\n  cursor: pointer;\n}\n\n.property-changed-dot-noreset {\n  position: absolute;\n  left: 5px;\n  top: 12px;\n  height: 10px;\n  width: 10px;\n  background-color: var(--theme-color-fg-muted);\n  border-radius: 50%;\n}\n\n.property-label {\n  line-height: 35px;\n  padding-right: 10px;\n  color: var(--theme-color-fg-default);\n  text-align: right;\n  white-space: nowrap;\n  width: 150px;\n  position: absolute;\n}\n\n.property-value {\n  position: absolute;\n  left: 160px;\n  right: 10px;\n  top: 1px;\n  bottom: 1px;\n}\n\n.property-input-dropdown {\n  position: absolute;\n  z-index: 10;\n  /* overflow:scroll;*/\n}\n\n.property-input-dropdown-arrow {\n  color: var(--theme-color-fg-muted);\n}\n\n.property-input-dropdown-arrow:hover {\n  color: var(--theme-color-fg-highlight);\n}\n\n.property-input-enum:hover {\n  background-color: var(--theme-color-border-strong);\n  cursor: pointer;\n}\n\n.property-input-enum {\n  background-color: var(--theme-color-bg-0);\n  color: var(--theme-color-fg-highlight);\n  min-height: 30px;\n  line-height: 30px;\n  padding-left: 10px;\n}\n\n.property-input-enum + .property-input-enum {\n  border-top: 1px solid var(--theme-color-border-subtle);\n}\n\n.property-input-connected {\n  border: 1px solid var(--theme-color-primary-dim);\n}\n\n.property-input-default {\n  color: var(--theme-color-fg-default);\n  font-weight: var(--font-weight-regular);\n}\n\n.property-input-focused {\n  color: var(--theme-color-fg-highlight);\n  background-color: var(--theme-color-bg-0);\n}\n\n.property-input-color {\n  background-color: var(--theme-color-bg-2);\n}\n\n.property-input-color-hidden {\n  opacity: 0;\n  display: block;\n  border: none;\n  padding: 0;\n}\n\n.property-input-textarea {\n  resize: vertical;\n  padding-top: 10px;\n  min-height: 35px;\n  font-size: 12px;\n}\n\n.property-input-textarea:focus {\n  color: var(--theme-color-fg-highlight);\n  background-color: var(--theme-color-bg-0);\n}\n\n.property-input-textarea-bg {\n  margin-bottom: 1px;\n  flex-grow: 1;\n  margin-right: 10px;\n}\n\n.property-group-label {\n  padding: 12px 6px;\n  display: block;\n  color: var(--theme-color-fg-highlight);\n  font-weight: var(--font-weight-semibold);\n}\n\n.property-group:not(:last-child) {\n  border-bottom: 1px solid var(--theme-color-bg-1);\n}\n\n.property-header-bar {\n  background-color: var(--theme-color-bg-2);\n  border-bottom: 1px solid var(--theme-color-bg-1);\n  position: relative;\n  display: flex;\n  align-items: center;\n}\n\n.header-name-edit-container {\n  min-height: 35px;\n  font: bold 12px var(--font-family-regular);\n}\n\n.property-header-bar-label {\n  color: var(--theme-color-fg-highlight);\n  font: 12px var(--font-family-regular);\n  padding: 10px 0 10px 10px;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n  overflow: hidden;\n}\n\n.property-panel-header-edit-bar {\n  padding-right: 0;\n  right: 0;\n}\n\n.property-panel-header-edit-button {\n  width: 35px;\n  height: 35px;\n}\n\n.property-editor-highlight {\n  color: var(--theme-color-notice);\n}\n\n.property-editor-highlight:hover {\n  background-color: var(--theme-color-notice);\n  color: var(--theme-color-fg-highlight);\n}\n\n.property-codeeditor-button {\n  background-color: var(--theme-color-bg-3);\n  border: none;\n  color: var(--theme-color-fg-default);\n  margin: 0px;\n}\n\n.property-codeeditor-button:hover {\n  background-color: var(--theme-color-bg-1);\n  color: var(--theme-color-fg-highlight);\n}\n\n.property-number-units {\n  text-align: center;\n  cursor: default;\n}\n\n.property-number-unit-enum {\n  background-color: var(--theme-color-bg-0);\n  color: var(--theme-color-fg-highlight);\n  height: 30px;\n  line-height: 30px;\n  cursor: default;\n}\n\n.property-number-unit-enum + .property-number-unit-enum {\n  border-top: 1px solid var(--theme-color-border-subtle);\n}\n\n.property-number-unit-enum:hover {\n  background-color: var(--theme-color-border-strong);\n}\n\n.property-dimension-fixed-disabled {\n  pointer-events: none;\n  opacity: 0.3;\n}\n\n.property-tab {\n  opacity: 0.25;\n  margin-left: 5px;\n  margin-right: 5px;\n}\n\n.property-tab.selected {\n  opacity: 1;\n}\n\n.property-tab-icon {\n  width: 32px;\n  height: 32px;\n}\n\n.property-tab-icon.borders-all {\n  content: url('../assets/icons/property-tab-borders-all.svg');\n}\n\n.property-tab-icon.borders-left {\n  content: url('../assets/icons/property-tab-borders-left.svg');\n}\n\n.property-tab-icon.borders-right {\n  content: url('../assets/icons/property-tab-borders-right.svg');\n}\n\n.property-tab-icon.borders-bottom {\n  content: url('../assets/icons/property-tab-borders-bottom.svg');\n}\n\n.property-tab-icon.borders-top {\n  content: url('../assets/icons/property-tab-borders-top.svg');\n}\n\n.property-tab-icon.corners-all {\n  content: url('../assets/icons/property-tab-corners-all.svg');\n}\n\n.property-tab-icon.corners-top-left {\n  content: url('../assets/icons/property-tab-corners-top-left.svg');\n}\n\n.property-tab-icon.corners-top-right {\n  content: url('../assets/icons/property-tab-corners-top-right.svg');\n}\n\n.property-tab-icon.corners-bottom-left {\n  content: url('../assets/icons/property-tab-corners-bottom-left.svg');\n}\n\n.property-tab-icon.corners-bottom-right {\n  content: url('../assets/icons/property-tab-corners-bottom-right.svg');\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 77510:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  z: () => (/* binding */ AiAssistantEvent),
  g: () => (/* binding */ AiAssistantModel)
});

// EXTERNAL MODULE: ./src/editor/src/contexts/NodeGraphContext/NodeGraphContext.tsx
var NodeGraphContext = __webpack_require__(18498);
// EXTERNAL MODULE: ../noodl-platform/src/index.ts + 10 modules
var src = __webpack_require__(37218);
// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/AiCopilotContext.ts
var AiCopilotContext = __webpack_require__(69401);
// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/ChatHistory.ts
var ChatHistory = __webpack_require__(75928);
// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/context/ai-utils.ts
var ai_utils = __webpack_require__(36890);
;// ./src/editor/src/models/AiAssistant/templates/helper.ts
function extractCodeBlock(text) {
    if (text.includes('```javascript')) {
        const a = text.indexOf('```javascript');
        const b = text.indexOf('```', a + 13);
        if (b === -1) {
            throw new Error('Failed to parse');
        }
        return text.substring(a + 13, b);
    }
    else if (text.includes('```xml')) {
        const a = text.indexOf('```xml');
        const b = text.indexOf('```', a + 6);
        if (b === -1) {
            throw new Error('Failed to parse');
        }
        return text.substring(a + 6, b);
    }
    else if (text.includes('```')) {
        const a = text.indexOf('```');
        const b = text.indexOf('```', a + 3);
        if (b === -1) {
            throw new Error('Failed to parse');
        }
        return text.substring(a + 3, b);
    }
    return text;
}
function extractCodeBlockWithText(text, replaceCodeBlock = '{current-code}') {
    const codeBlockRegex = /```[\s\S]*?```/g;
    const codeContentRegex = /```.*\n([\s\S]*?)```/;
    const codeBlocks = [];
    let match;
    while ((match = codeBlockRegex.exec(text)) !== null) {
        const contentMatch = codeContentRegex.exec(match[0]);
        if (contentMatch) {
            codeBlocks.push(contentMatch[1]);
        }
    }
    return { codeBlocks, cleanedText: text.replaceAll(codeBlockRegex, replaceCodeBlock) };
}
// --base-color-yellow-400
// --base-color-teal-400
function wrapInput(text) {
    return ` <span style="color: var(--base-color-yellow-400);">Inputs.${text}</span>`;
}
function wrapOutput(text) {
    return ` <span style="color: var(--base-color-yellow-400);">Outputs.${text}</span>`;
}

// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/NodeLibraryImporter.ts
var NodeLibraryImporter = __webpack_require__(42146);
// EXTERNAL MODULE: ./src/editor/src/utils/NodeGraph/index.ts
var NodeGraph = __webpack_require__(52877);
// EXTERNAL MODULE: ./src/shared/utils/EventDispatcher.ts
var EventDispatcher = __webpack_require__(11138);
// EXTERNAL MODULE: ./src/editor/src/ViewerConnection.ts
var ViewerConnection = __webpack_require__(71336);
;// ./src/editor/src/utils/connectionInspector.ts




class ConnectionInspector {
    getConnectionValue(node, type, property, timeout = 250) {
        return new Promise((resolve, reject) => {
            const runtimeType = (0,NodeGraph/* getNodeGraphNodeRuntimeType */.lb)(node);
            const clients = NodeLibraryImporter/* NodeLibraryImporter */.K.instance.clientsWithRuntime(runtimeType);
            if (clients.length === 0) {
                return reject('no available client');
            }
            const connection = node
                .getConnectionsOnThisNode()
                .find((x) => (type === 'input' && x.toProperty === property) || (type === 'output' && x.fromProperty === property));
            const connectionId = type === 'input'
                ? `${connection.fromId}${connection.fromProperty}`
                : `${connection.toId}${connection.toProperty}`;
            const group = {};
            const timeoutHandler = setTimeout(() => {
                EventDispatcher.EventDispatcher.instance.off(group);
                reject('timeout');
            }, timeout);
            EventDispatcher.EventDispatcher.instance.on('ConnectionInspector', (data) => {
                if (data.connectionId === connectionId) {
                    clearTimeout(timeoutHandler);
                    resolve(data.value);
                    EventDispatcher.EventDispatcher.instance.off(group);
                }
            }, group);
            // NOTE: Pick the first client hoping that is the editor preview
            ViewerConnection/* ViewerConnection */.t.instance.sendGetConnectionValue(clients[0], connectionId);
        });
    }
}
ConnectionInspector.instance = new ConnectionInspector();

;// ./src/editor/src/models/AiAssistant/templates/chart.ts




const template = {
    type: 'blue',
    name: 'noodl.chart-js.chart',
    onMessage: async ({ node, chatHistory, chatStream, chatStreamXml }) => {
        const activityId = 'processing';
        const activityCodeGenId = 'code-generation';
        chatHistory.addActivity({
            id: activityId,
            name: 'Processing'
        });
        // ---
        // Generate the code
        chatHistory.addActivity({
            id: activityCodeGenId,
            name: 'Generating code...'
        });
        const history = chatHistory.messages.map((x) => ({
            role: String(x.type),
            content: x.content
        }));
        const data = await ConnectionInspector.instance.getConnectionValue(node, 'input', 'data');
        console.log('fullData', data);
        const shortData = Array.isArray(data) ? data.slice(0, 3) : data;
        const shortDataJson = JSON.stringify(shortData);
        console.log('data', shortDataJson);
        const currentScript = node.getParameter('functionScript');
        const messages = currentScript
            ? [
                {
                    role: 'system',
                    content: CONTEXT_EDIT.replace('%{code}%', currentScript).replace('%{data}%', shortDataJson)
                },
                history.at(-1)
            ]
            : [{ role: 'system', content: CONTEXT.replace('%{data}%', shortDataJson) }, ...history];
        const fullCodeText = await chatStream({
            provider: {
                model: 'gpt-4o-mini',
                temperature: 0.0,
                max_tokens: 2048
            },
            messages,
            onStream(fullText) {
                console.log('code:', fullText);
            }
        });
        const codeText = extractCodeBlock(fullCodeText);
        // ---
        // Evaluate the code if it is valid.
        try {
            // Allow async/await
            const wrappedCode = `async function validateCode() { ${codeText} }`;
            new Function(wrappedCode);
        }
        catch (error) {
            console.error(error);
            chatHistory.removeActivity(activityCodeGenId);
            chatHistory.add({
                type: ChatHistory/* ChatMessageType */._J.Assistant,
                content: ''
            });
            await ai_utils/* AiUtils */.Y.fakeTokenStream(`I'm sorry. I'm afraid I can't do that.`, (delta, fullText) => {
                chatHistory.updateLast({
                    content: fullText
                });
            });
            chatHistory.removeActivity(activityId);
            return;
        }
        // Set the parameter
        node.setParameter('scriptSetup', codeText);
        // Save it in the history, so it will be possible to go back and forth.
        chatHistory.updateLast({
            metadata: {
                code: codeText
            }
        });
        chatHistory.removeActivity(activityCodeGenId);
        // ---
        // Explain the code
        const snowflakeId = chatHistory.add({
            type: ChatHistory/* ChatMessageType */._J.Assistant,
            content: ''
        });
        const result = [''];
        const fullText = await chatStreamXml({
            messages: [
                {
                    role: 'system',
                    content: CONTEXT_EXPLAIN
                },
                { role: 'user', content: codeText }
            ],
            provider: {
                model: 'gpt-3.5-turbo',
                temperature: 0.0,
                max_tokens: 2048
            },
            onStream(tagName, text) {
                // TODO: It calls an empty string at the end, why?
                if (text.length === 0) {
                    return;
                }
                console.log('stream', tagName, text);
                switch (tagName) {
                    case 'explain': {
                        result[result.length - 1] = text;
                        break;
                    }
                    case 'Input': {
                        result[result.length - 1] = wrapInput(text);
                        break;
                    }
                    case 'Output': {
                        result[result.length - 1] = wrapOutput(text);
                        break;
                    }
                }
                if (['explain', 'Input', 'Output'].includes(tagName)) {
                    chatHistory.updateLast({
                        content: result.join('')
                    });
                }
            },
            onTagOpen(tagName) {
                switch (tagName) {
                    case 'Input':
                    case 'Output': {
                        result.push('');
                        break;
                    }
                }
            },
            onTagEnd(tagName, fullText) {
                console.log('[done]', tagName, fullText);
                switch (tagName) {
                    case 'label': {
                        node.setLabel(fullText);
                        break;
                    }
                    case 'explain': {
                        result[result.length - 1] = fullText;
                        result.push('');
                        break;
                    }
                    case 'Input': {
                        result[result.length - 1] = wrapInput(fullText);
                        result.push('');
                        break;
                    }
                    case 'Output': {
                        result[result.length - 1] = wrapOutput(fullText);
                        result.push('');
                        break;
                    }
                }
                if (['explain', 'Input', 'Output'].includes(tagName)) {
                    chatHistory.updateLast({
                        content: result.join('')
                    });
                }
            }
        });
        console.log('fullText', fullText);
        chatHistory.removeActivity(activityId);
    }
};
const CONTEXT = `###Instructions###
- You will be creating javascript config objects for the chartjs library.
- You ONLY need to provide the config object.
- An input in the javascript code must follow the format "Inputs.InputName".
- An input in the javascript code is only read, never written to.
- Don't use features that require external libraries, like date adapters.

### Examples ###
A chart showing number of votes for different colors:
\`\`\`
if (!Inputs.data) return;

config  = {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
}
\`\`\`

Here is my input data:
\`\`\`
Inputs.data = %{data}%
\`\`\`

###Task###
ONLY respond with javascript code following the instructions and starting and ending with \`\`\`
`;
const CONTEXT_EDIT = `###Instructions###
- You will be creating javascript config objects for the chartjs library.
- You ONLY need to provide the config object.
- An input in the javascript code must follow the format "Inputs.InputName".
- An input in the javascript code is only read, never written to.
- Don't use features that require external libraries, like date adapters.

Here is my input data:
\`\`\`
Inputs.data = %{data}%
\`\`\`

We are starting from this code and will only modify it:
\`\`\`
%{code}%
\`\`\`

###Task###
ONLY respond with javascript code following the instructions and starting and ending with \`\`\`
`;
const CONTEXT_EXPLAIN = `###Context###
- This is a Chart node in Noodl using Chart.js.
- We are currently inside a Component with this node created, the node have the function inside.

###Instructions###
Analyse the function and create an explanation related to the code.

###Explanation###
Explain with 2-5 sentences what the function does.
- Always include the property names of the Inputs and Outputs objects.
- Always format the property names of the Inputs like this: <Input>input name</Input>
- Always format the property names of the Outputs like this: <Output>output name</Output>

###Label###
Create a label that summarises what the function does.

###Example###
<label>Show a bar chart of cars</label>
<explain></explain>`;

// EXTERNAL MODULE: ./src/editor/src/store/AiAssistantStore.ts
var AiAssistantStore = __webpack_require__(61231);
// EXTERNAL MODULE: ./src/editor/src/utils/utils.ts
var utils = __webpack_require__(93015);
;// ./src/editor/src/models/AiAssistant/templates/function/gpt-3-version.ts





async function execute({ node, chatHistory, chatStream, chatStreamXml }) {
    const activityCodeGenId = 'code-generation';
    const currentScript = node.getParameter('functionScript');
    // ---
    // Generate the code
    chatHistory.addActivity({
        id: activityCodeGenId,
        name: 'Generating code...'
    });
    const history = chatHistory.messages.map((x) => ({
        role: String(x.type),
        content: x.content
    }));
    const messages = currentScript
        ? [
            // TODO: Enable this again later, ...history.slice(0, -1),
            {
                role: 'system',
                content: FUNCTION_CODE_CONTEXT_EDIT.replace('%{code}%', currentScript)
            },
            history.at(-1)
        ]
        : [{ role: 'system', content: FUNCTION_CODE_CONTEXT }, ...history];
    const fullCodeText = await chatStream({
        provider: {
            model: 'gpt-3.5-turbo',
            temperature: 0.0,
            max_tokens: 2048
        },
        messages,
        onStream(fullText) {
            console.log('code:', fullText);
        }
    });
    const codeText = extractCodeBlock(fullCodeText);
    // ---
    // Evaluate the code if it is valid.
    try {
        // Allow async/await
        const wrappedCode = `async function validateCode() { ${codeText} }`;
        new Function(wrappedCode);
    }
    catch (error) {
        console.error(error);
        chatHistory.add({
            type: ChatHistory/* ChatMessageType */._J.Assistant,
            content: ''
        });
        await ai_utils/* AiUtils */.Y.fakeTokenStream(`I'm sorry. I'm afraid I can't do that.`, (delta, fullText) => {
            chatHistory.updateLast({
                content: fullText
            });
        });
        chatHistory.clearActivities();
        return;
    }
    // Set the parameter
    node.setParameter('functionScript', codeText);
    // Save it in the history, so it will be possible to go back and forth.
    chatHistory.updateLast({
        metadata: {
            code: codeText
        }
    });
    chatHistory.removeActivity(activityCodeGenId);
    // ---
    // Explain the code
    chatHistory.add({
        type: ChatHistory/* ChatMessageType */._J.Assistant,
        content: ''
    });
    let questionIndex = 0;
    const result = [''];
    await chatStreamXml({
        messages: [
            {
                role: 'system',
                content: FUNCTION_CODE_EXPLAIN(false)
            },
            { role: 'user', content: codeText }
        ],
        provider: {
            model: 'gpt-3.5-turbo',
            temperature: 0.0,
            max_tokens: 2048
        },
        onStream(tagName, text) {
            // TODO: It calls an empty string at the end, why?
            if (text.length === 0) {
                return;
            }
            console.log('stream', tagName, text);
            switch (tagName) {
                case 'explain': {
                    result[result.length - 1] = text;
                    break;
                }
                case 'Input': {
                    result[result.length - 1] = wrapInput(text);
                    break;
                }
                case 'Output': {
                    result[result.length - 1] = wrapOutput(text);
                    break;
                }
            }
            if (['explain', 'Input', 'Output'].includes(tagName)) {
                chatHistory.updateLast({
                    content: result.join('')
                });
            }
        },
        onTagOpen(tagName) {
            switch (tagName) {
                case 'Input':
                case 'Output': {
                    result.push('');
                    break;
                }
            }
        },
        onTagEnd(tagName, fullText) {
            console.log('[done]', tagName, fullText);
            switch (tagName) {
                case 'label': {
                    node.setLabel(fullText);
                    break;
                }
                case 'explain': {
                    result[result.length - 1] = fullText;
                    result.push('');
                    break;
                }
                case 'Input': {
                    result[result.length - 1] = wrapInput(fullText);
                    result.push('');
                    break;
                }
                case 'Output': {
                    result[result.length - 1] = wrapOutput(fullText);
                    result.push('');
                    break;
                }
                case 'question': {
                    const suggestions = chatHistory.messages[chatHistory.messages.length - 1].metadata.suggestions || [];
                    suggestions[questionIndex] = {
                        id: (0,utils.guid)(),
                        text: fullText.endsWith('?') ? fullText : fullText + '?'
                    };
                    chatHistory.updateLast({
                        metadata: {
                            suggestions
                        }
                    });
                    questionIndex++;
                    break;
                }
            }
            if (['explain', 'Input', 'Output'].includes(tagName)) {
                chatHistory.updateLast({
                    content: result.join('')
                });
            }
        }
    });
}

// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/context/ai-query.ts + 3 modules
var ai_query = __webpack_require__(3702);
;// ./src/editor/src/models/AiAssistant/templates/function/gpt-4-version.ts






async function gpt_4_version_execute({ node, chatHistory, chatStream, chatStreamXml }) {
    const activityCodeGenId = 'code-generation';
    const currentScript = node.getParameter('functionScript');
    let questionPrompt = `Group the question into FUNCTION or QUESTION

${currentScript ? '- The user have a function that they want answers to or to change it.' : ''}       

Q["Get the current location of the device"]
A["FUNCTION"]

Q["What can you do?"]
A["QUESTION"]

Q["Output the color red"]
A["FUNCTION"]`;
    if (currentScript) {
        questionPrompt += `
Q["How does it work?"]
A["QUESTION"]

Q["Can we change it to blue?"]
A["FUNCTION"]

Q["Can we do it without an api?"]
A["FUNCTION"]`;
    }
    const question = await ai_query/* AiQuery */.$.chatReAct({
        messages: [
            {
                role: 'system',
                content: questionPrompt
            },
            {
                role: 'user',
                content: `Q["${chatHistory.messages.at(-1).content}"]`
            }
        ],
        provider: {
            // NOTE: Tried with GPT 3.5 here before.
            //       Then this question doesnt work: "Can you make a function that starts recording from the microphone when it gets a start signal and stops recording when it gets a stop signal"
            model: 'gpt-4o-mini',
            temperature: 0.0
        }
    });
    if (question.commands.length === 0) {
        chatHistory.add({
            type: ChatHistory/* ChatMessageType */._J.Assistant,
            content: ''
        });
        await ai_utils/* AiUtils */.Y.fakeTokenStream(`Could you explain a little bit more what you would like?`, (_, fullText) => {
            chatHistory.updateLast({
                content: fullText
            });
        });
        return;
    }
    if (question.commands[0].args[0] === 'QUESTION') {
        const lastMessage = chatHistory.messages.at(-1).content;
        let suggestions = [];
        const lastAssistantMessage = chatHistory.messages.at(-2);
        if (lastAssistantMessage && lastAssistantMessage.metadata.suggestions) {
            const lastSuggestions = lastAssistantMessage.metadata.suggestions || [];
            const suggestionIndex = lastSuggestions.findIndex((x) => x.text === lastMessage);
            if (suggestionIndex !== -1) {
                suggestions = [...lastSuggestions].filter((_, index) => index !== suggestionIndex);
            }
        }
        chatHistory.add({
            type: ChatHistory/* ChatMessageType */._J.Assistant,
            content: '',
            metadata: {
                suggestions
            }
        });
        const fullText = await chatStream({
            provider: {
                model: 'gpt-4o-mini',
                temperature: 0.0,
                max_tokens: 2048
            },
            messages: [
                {
                    role: 'system',
                    content: FUNCTION_CODE_QUESTION().replace('%{code}%', currentScript)
                },
                {
                    role: 'user',
                    content: lastMessage
                }
            ],
            onStream(fullText) {
                chatHistory.updateLast({
                    content: fullText
                });
            }
        });
        chatHistory.updateLast({
            content: fullText
        });
        // TODO: If zero suggestions generate a new suggestions?
        return;
    }
    // ---
    // Generate the code
    chatHistory.addActivity({
        id: activityCodeGenId,
        name: 'Generating code...'
    });
    const history = chatHistory.messages.map((x) => ({
        role: String(x.type),
        content: x.content
    }));
    const messages = currentScript
        ? [
            // TODO: Enable this again later, ...history.slice(0, -1),
            {
                role: 'system',
                content: FUNCTION_CODE_CONTEXT_EDIT.replace('%{code}%', currentScript)
            },
            history.at(-1)
        ]
        : [{ role: 'system', content: FUNCTION_CODE_CONTEXT }, ...history];
    const fullCodeText = await chatStream({
        provider: {
            model: 'gpt-4o-mini',
            temperature: 0.0,
            max_tokens: 2048
        },
        messages,
        onStream(fullText) {
            console.log('code:', fullText);
        }
    });
    // Not sure if it will just reply with the code or with backticks,
    // would be nice to make a better prompt to handle it.
    const { codeBlocks, cleanedText } = extractCodeBlockWithText(fullCodeText);
    const codeText = codeBlocks.length > 0 ? codeBlocks[0] : '';
    if (codeBlocks.length === 0) {
        chatHistory.add({
            type: ChatHistory/* ChatMessageType */._J.Assistant,
            content: ''
        });
        chatHistory.removeActivity(activityCodeGenId);
        await ai_utils/* AiUtils */.Y.fakeTokenStreamFast(fullCodeText, (delta, fullText) => {
            chatHistory.updateLast({
                content: fullText
            });
        });
        chatHistory.clearActivities();
        return;
    }
    // ---
    // Evaluate the code if it is valid.
    try {
        // Allow async/await
        const wrappedCode = `async function validateCode() { ${codeText} }`;
        new Function(wrappedCode);
    }
    catch (error) {
        console.error(error);
        chatHistory.removeActivity(activityCodeGenId);
        chatHistory.add({
            type: ChatHistory/* ChatMessageType */._J.Assistant,
            content: ''
        });
        await ai_utils/* AiUtils */.Y.fakeTokenStreamFast(fullCodeText, (delta, fullText) => {
            chatHistory.updateLast({
                content: fullText
            });
        });
        chatHistory.clearActivities();
        return;
    }
    // Set the parameter
    node.setParameter('functionScript', codeText);
    // Save it in the history, so it will be possible to go back and forth.
    chatHistory.updateLast({
        metadata: {
            code: codeText
        }
    });
    chatHistory.removeActivity(activityCodeGenId);
    // ---
    // Explain the code
    chatHistory.add({
        type: ChatHistory/* ChatMessageType */._J.Assistant,
        content: ''
    });
    let questionIndex = 0;
    const result = [''];
    await chatStreamXml({
        messages: [
            {
                role: 'system',
                content: FUNCTION_CODE_EXPLAIN(false)
            },
            {
                role: 'user',
                content: FUNCTION_CODE_EXPLAIN_PROMPT(chatHistory.messages.at(-2).content, cleanedText, codeText)
            }
        ],
        provider: {
            model: 'gpt-4o-mini',
            temperature: 0.0,
            max_tokens: 2048
        },
        onStream(tagName, text) {
            // TODO: It calls an empty string at the end, why?
            if (text.length === 0) {
                return;
            }
            console.log('stream', tagName, text);
            switch (tagName) {
                case 'explain': {
                    result[result.length - 1] = text;
                    break;
                }
                case 'Input': {
                    result[result.length - 1] = wrapInput(text);
                    break;
                }
                case 'Output': {
                    result[result.length - 1] = wrapOutput(text);
                    break;
                }
            }
            if (['explain', 'Input', 'Output'].includes(tagName)) {
                chatHistory.updateLast({
                    content: result.join('')
                });
            }
        },
        onTagOpen(tagName) {
            switch (tagName) {
                case 'Input':
                case 'Output': {
                    result.push('');
                    break;
                }
            }
        },
        onTagEnd(tagName, fullText) {
            console.log('[done]', tagName, fullText);
            switch (tagName) {
                case 'label': {
                    node.setLabel(fullText);
                    break;
                }
                case 'explain': {
                    result[result.length - 1] = fullText;
                    result.push('');
                    break;
                }
                case 'Input': {
                    result[result.length - 1] = wrapInput(fullText);
                    result.push('');
                    break;
                }
                case 'Output': {
                    result[result.length - 1] = wrapOutput(fullText);
                    result.push('');
                    break;
                }
                case 'question': {
                    const suggestions = chatHistory.messages[chatHistory.messages.length - 1].metadata.suggestions || [];
                    suggestions[questionIndex] = {
                        id: (0,utils.guid)(),
                        text: fullText.endsWith('?') ? fullText : fullText + '?'
                    };
                    chatHistory.updateLast({
                        metadata: {
                            suggestions
                        }
                    });
                    questionIndex++;
                    break;
                }
            }
            if (['explain', 'Input', 'Output'].includes(tagName)) {
                chatHistory.updateLast({
                    content: result.join('')
                });
            }
        }
    });
}

// EXTERNAL MODULE: ./src/editor/src/views/ToastLayer/ToastLayer.tsx
var ToastLayer = __webpack_require__(80424);
;// ./src/editor/src/models/AiAssistant/templates/function.ts




const function_template = {
    type: 'pink',
    name: 'JavaScriptFunction',
    onMessage: async (context) => {
        const version = AiAssistantStore/* OpenAiStore */.q.getVersion();
        const activityId = 'processing';
        context.chatHistory.addActivity({
            id: activityId,
            name: 'Processing'
        });
        // ---
        console.log('using version: ', version);
        try {
            if ((version === 'enterprise' && AiAssistantStore/* OpenAiStore */.q.getModel() === 'gpt-4o-mini') || version === 'full-beta') {
                await gpt_4_version_execute(context);
            }
            else {
                await execute(context);
            }
            context.chatHistory.removeActivity(activityId);
        }
        catch (error) {
            ToastLayer.ToastLayer.showError(error);
            context.chatHistory.clearActivities();
        }
    }
};
const FUNCTION_CODE_CONTEXT = `###Instructions###
You are writing Noodl Javascript functions with the following rules:
Inputs follow "Inputs[InputName]" format and are read-only. 

Outputs follow "Outputs[OutputName] = value" format, and variables don't store outputs. 

Signals are sent using "Outputs.SignalName()" without passing values. 

Inputs and Outputs are global, and const should use Noodl inputs with OR operator and default value. 

Call "Success" or "Failure" output signals accordingly. 

Inputs and outputs can have human-readable string names. 

Do not explain each input and output outside the code block.

Functions can use resources from a CDN and access APIs with "fetch." For API handling, make API keys inputs, throw an error for invalid keys, add queries as inputs, and send primitive values to outputs.

Write helpful comments in the code block, so anyone can understand the code.

###Example###
\`\`\`javascript
const city = Inputs.City || 'Malmö';
if (!city) return;

const apiKey = Inputs.ApiKey || '';
if (!apiKey) throw new Error('Invalid API key');
const url = \`https://api.openweathermap.org/data/2.5/weather?q=\${city}&appid=\${apiKey}\`;

try {
  const response = await fetch(url);
  const data = await response.json();
  Outputs.Temperature = data.main.temp;
  Outputs.Success();
} catch (error) {
  Outputs.error = error;
  Outputs.Failure();
}
\`\`\`

###Task###
ONLY respond with javascript code following the instructions and starting and ending with \`\`\`
`;
const FUNCTION_CODE_CONTEXT_EDIT = `###Instructions###
You are writing Noodl Javascript functions with the following rules:
Inputs follow "Inputs[InputName]" format and are read-only. 

Outputs follow "Outputs[OutputName] = value" format, and variables don't store outputs. 

Signals are sent using "Outputs.SignalName()" without passing values. 

Inputs and Outputs are global, and const should use Noodl inputs with OR operator and default value. 

Call "Success" or "Failure" output signals accordingly. 

Inputs and outputs can have human-readable string names. 

Do not explain each input and output outside the code block.

Functions can use resources from a CDN and access APIs with "fetch." For API handling, make API keys inputs, throw an error for invalid keys, add queries as inputs, and send primitive values to outputs.

Write helpful comments in the code block, so anyone can understand the code.

We are starting from this code and will only modify it:
\`\`\`
%{code}%
\`\`\`

###Task###
ONLY respond with javascript code following the instructions and starting and ending with \`\`\`
`;
const FUNCTION_CODE_EXPLAIN = (enableSuggestions) => {
    return `###Context###
- This function is a Function node in Noodl.
- We are currently inside a Component with this node created, the node have the function inside.
- All the variables from the Inputs object is defined on the node as inputs which can be set via the properties on input connection.
- All the variables on the Outputs object is defined on the node as outputs which can be connected to another node.
- Do not show code blocks.

###Instructions###
Analyse the function and create an explanation${enableSuggestions ? ' and a maximum of 3 follow-up questions related to the code' : ''}.

###Explanation###
Explain with 2-5 sentences what the function does.
- Always include the property names of the Inputs and Outputs objects.
- Always format the property names of the Inputs like this: <Input>input name</Input>
- Always format the property names of the Outputs like this: <Output>output name</Output>

###Label###
Create a label that summarises what the function does.

###Example###
<label>Data To Excel</label>
<explain>
This function converts a JSON data array to an Excel file and initiates a download.

It takes <Input>Data</Input> and <Input>FileName</Input> as inputs, creates a new workbook and worksheet using the XLSX library, converts the JSON data to a sheet, and appends the sheet to the workbook.

It then converts the workbook to a binary string, creates a Blob, and generates a download link. Finally, it triggers the <Output>Success</Output> output signal after the download is initiated.

If the request is successful, it triggers the Outputs.Success output signal.

If there's an error, it sets the Outputs.error output and triggers the Outputs.Failure output signal.
</explain>
${enableSuggestions
        ? `<question>What is the format of the required JSON data array?</question>
<question>How do I connect this node to other nodes in my Noodl project?</question>
<question>Are there any limitations or required libraries for this function to work properly?</question>`
        : ''}

###Task###
Respond only with this specific format, and nothing else:
<label>The label</label>
<explain>
Markdown text.
</explain>
${enableSuggestions ? '<question>Maximum of 3 follow-up questions</question>' : ''}`;
};
const FUNCTION_CODE_EXPLAIN_PROMPT = (question, answer, code) => {
    return `I got this information with the code, is there something important here that I should think about? Include this in the <explain> element, starting with a new paragraph.

user: ""${question}""
assistant: ""
${answer}
""

###Current code###
\`\`\`
${code}
\`\`\`
`;
};
const FUNCTION_CODE_QUESTION = () => {
    return `###Context###
- This function is a Function node in Noodl.
- We are currently inside a Component with this node created, the node have the function inside.
- All the variables from the Inputs object is defined on the node as inputs which can be set via the properties on input connection.
- All the variables on the Outputs object is defined on the node as outputs which can be connected to another node.

###Current code###
\`\`\`
%{code}%
\`\`\`
`;
};

// EXTERNAL MODULE: ./src/editor/src/utils/schemahandler.ts
var schemahandler = __webpack_require__(96543);
;// ./src/editor/src/models/AiAssistant/DatabaseSchemaExtractor.ts

async function extractDatabaseSchema() {
    const schema = schemahandler/* default */.A.instance;
    if (typeof schema.haveCloudServices === 'undefined') {
        console.error('Missing database schema');
        try {
            await schema._fetch();
        }
        catch (error) {
            // lets ignore it then...
            console.error(error);
        }
    }
    const dbCollectionsSource = schema.dbCollections
        .map((collection) => {
        let str = `${collection.name}\n`;
        Object.keys(collection.schema.properties).forEach((name) => {
            const property = collection.schema.properties[name];
            switch (property.type) {
                case 'Pointer': {
                    str += `- ${name}:Pointer ${property.targetClass}\n`;
                    break;
                }
                case 'Relation': {
                    str += `- ${name}:Relation ${property.targetClass}\n`;
                    break;
                }
                default: {
                    str += `- ${name}:${property.type}\n`;
                    break;
                }
            }
        });
        return str;
    })
        .join('\n') + '\n';
    return dbCollectionsSource;
}
async function extractDatabaseSchemaJSON() {
    const schema = SchemaHandler.instance;
    if (typeof schema.haveCloudServices === 'undefined') {
        console.error('Missing database schema');
        try {
            await schema._fetch();
        }
        catch (error) {
            // lets ignore it then...
            console.error(error);
        }
    }
    return Object.keys(schema.dbCollections).map((key) => schema.dbCollections[key]);
}
function databaseSchemaCompact(schema) {
    return schema.map((x) => ({
        name: x.name,
        compact: Object.keys(x.schema.properties).join(',')
    }));
}

;// ./src/editor/src/models/AiAssistant/templates/function-crud.ts


const function_crud_template = {
    type: 'green',
    name: 'JavaScriptFunction',
    nodeDisplayName: 'Write Database',
    onMessage: async ({ node, chatHistory, chatStreamXml }) => {
        const activityId = 'processing';
        const activityCodeGenId = 'code-generation';
        chatHistory.addActivity({
            id: activityId,
            name: 'Processing'
        });
        chatHistory.addActivity({
            id: activityCodeGenId,
            name: 'Generating code...'
        });
        // ---
        // Database
        const dbCollectionsSource = await extractDatabaseSchema();
        console.log('database schema', dbCollectionsSource);
        // Set the parameter
        // node.setParameter('functionScript', codeText);
        // Save it in the history, so it will be possible to go back and forth.
        // chatHistory.updateLast({
        //   metadata: {
        //     code: codeText
        //   }
        // });
        // ---
        // Explain the code
        // const snowflakeId = chatHistory.add({
        //   type: ChatMessageType.Assistant,
        //   content: ''
        // });
        const history = chatHistory.messages.map((x) => ({
            role: String(x.type),
            content: x.content
        }));
        const currentScript = node.getParameter('functionScript');
        const messages = currentScript
            ? [
                // TODO: Enable this again later, ...history.slice(0, -1),
                {
                    role: 'system',
                    content: FUNCTION_CRUD_CONTEXT_EDIT.replace('%{database-schema}%', dbCollectionsSource).replace('%{code}%', currentScript)
                },
                history.at(-1)
            ]
            : [
                {
                    role: 'system',
                    content: FUNCTION_CRUD_CONTEXT.replace('%{database-schema}%', dbCollectionsSource)
                },
                ...history
            ];
        const fullText = await chatStreamXml({
            messages,
            provider: {
                model: 'gpt-4o-mini',
                // model: 'gpt-3.5-turbo',
                // The next context doesnt work with GPT-3.5
                temperature: 0.5,
                max_tokens: 2048
            },
            onStream(tagName, text) {
                // TODO: It calls an empty string at the end, why?
                if (text.length === 0) {
                    return;
                }
                console.log('[stream]', tagName, text);
                switch (tagName) {
                    case 'explain': {
                        chatHistory.updateLast({
                            content: text
                        });
                        break;
                    }
                }
            },
            onTagOpen(tagName) {
                console.log('[open]', tagName);
                switch (tagName) {
                    case 'explain': {
                        chatHistory.add({
                            type: ChatHistory/* ChatMessageType */._J.Assistant,
                            content: ''
                        });
                        break;
                    }
                }
            },
            onTagEnd(tagName, fullText) {
                console.log('[done]', tagName, fullText);
                switch (tagName) {
                    case 'function': {
                        const prefix = 'const Records = Noodl.Records;';
                        const fullCode = fullText.includes(prefix) ? fullText : prefix + '\n\n' + fullText;
                        // Set the parameter
                        node.setParameter('functionScript', fullCode);
                        // Save it in the history, so it will be possible to go back and forth.
                        chatHistory.updateLast({
                            metadata: {
                                code: fullCode
                            }
                        });
                        chatHistory.removeActivity(activityCodeGenId);
                        break;
                    }
                    case 'explain': {
                        chatHistory.updateLast({
                            content: fullText
                        });
                        break;
                    }
                }
            }
        });
        console.log('fullText', fullText);
        chatHistory.removeActivity(activityCodeGenId);
        chatHistory.removeActivity(activityId);
    }
};
const FUNCTION_CRUD_CONTEXT = `
With these functions you can read, write and delete records in the cloud database. All functions are async and will throw an exception if they fail.

- An input in a Noodl function must follow the format "Inputs.InputName".
- An input in a Noodl function is only read, never written to.
- An output in a Noodl function must follow the format "Outputs.OutputName = value".
- A variable in a Noodl function never stores an output.
- Sending a signal from a Noodl function must follow the format "Outputs.SignalName()".
- Signals can not be passed values. All output values must be set as a Noodl function output.
- Inputs and Outputs in a Noodl function are global.
- Noodl functions do not use import statements.
- Noodl functions do not use export statements.
- Noodl functions can use recources from a CDN.
- Noodl functions can access API endpoints with "fetch".
- Define constants as Noodl function inputs.
- All const should be using Noodl inputs with an OR operator to a default value.
- When the request is successful call "Success" output signal.
- When something fails in the code the "Failure" output signal.

Examples:
\`\`\`js
const inputName = Inputs.InputName;

// Check if the input has a value, otherwise return
if (!inputName) return;

// Perform the function logic
\`\`\`

Create a new Car record, with price set to 50:
\`\`\`js
const recordId = Inputs.RecordId;
const newPrice = Inputs.NewPrice || 50;

if (!recordId) return;

try {
  const results = await Record.save(recordId, {
    price: newPrice,
  }, { className: "Car" });

  Outputs.Success();
} catch (error) {
  console.error("Error:", error);
  Outputs.Failure();
}
\`\`\`

Records.fetch(objectOrId,options)
Use this function to fetch the latest properties of a specific record from the cloud database. It will return the object / record.

\`\`\`
// If you use the a record ID you must also specify the class
const myRecord = await Records.fetch(myRecordId, {
  className: "myClass",
});

// You can also fetch a record you have previously fetched or received from a
// query, to get the latest properties from the backend
await Records.fetch(myRecord);
\`\`\`

By default fetch will return pointer properties as the string Id of the object pointed to. But you can use the \`include\` option to specify that you want the content of the object to be returned instead.

\`\`\`
// By using include the request will return the pointed to object with all properties instead of
// just the string Id
const res = await Records.fetch(myRecord,{
  include:["Customer","Author"]
});

res.Customer.id // Now Customer is an object and not a string
\`\`\`

Records.save(objectOrId,properties,options)
Use this function to write an existing record to the cloud database. It will attempt to save all properties of the record / object if you don't specify the optional properties argument, if so it will set and save those properties.

\`\`\`
Objects[myRecordId].SomeProperty = "hello";

// If you use the record id to save, you need to specify the classname explicitly
// by specfiying null or undefinded for properties it will save all proporties in
// the record
await Records.save(myRecordId, null, { className: "myClass" });

// Or use the object directly
await Records.save(Objects[myRecordId]);

// Set specified properties and save only those to the backned
await Records.save(myRecord, {
  SomeProperty: "hello",
});
\`\`\`

Records.increment(objectOrId,properties,options)
This function will increment (or decrease) propertis of a certain record saving it to the cloud database in a race condition safe way. That is, normally you would have to first read the current value, modify it and save it to the database. Here you can do it with one operation.

\`\`\`
// Modify the specified numbers in the cloud
await Records.increment(myRecord, {
  Score: 10,
  Life: -1,
});

// Like save, you can use a record Id and class
await Records.increment(myRecordId, { Likes: 1 }, { className: "myClass" });
\`\`\`

Using the options you can also specify access control, this let's you control which users can access a specific record. The access control is specified as below:

\`\`\`
await Records.save(myRecord, null, {
  acl: {
    "*": { read: true, write: false }, // "*" means everyone, this rules gives everyone read access but not write
    "a-user-id": { read: true, write: true }, // give a specific user write access
    "role:a-role-name": { read: true, write: true }, // give a specific role write access
  },
});
\`\`\`

Records.create(className,properties,options)
This function will create a new record in the cloud database and return the object of the newly created record. If it's unsuccessful it will throw an exception.

\`\`\`
const myNewRecord = await Records.create("myClass", {
  SomeProperty: "Hello",
});

console.log(myNewRecord.SomeProperty);
\`\`\`

You can use the \`options\` agrument to specify access control rules as detailed under **Records.save** above.

Records.delete(objectOrId,options)
Use this function to delete an existing record from the cloud database.

\`\`\`
// If you specify the id of a record to be deleted, you must also provide the
// class name in the options
await Records.delete(myRecordId, { className: "myClass" });

// Or use the object directly (provided it was previously fetched or received via a query)
await Records.delete(Objects[myRecordId]);
\`\`\`

Records.addRelation(options)
Use this function to add a relation between two records.

\`\`\`
// You can either specify the Ids and classes directly
await Noodl.Records.addRelation({
  className: "myClass",
  recordId: "owning-record-id",
  key: "the-relation-key-on-the-owning-record",
  targetRecordId: "the-id-of-the-record-to-add-a-relation-to",
  targetClassName: "the-class-of-the-target-record",
});

// Or if you already have two records that have been previously fetched or returned from a
// query
await Records.addRelation({
  record: myRecord,
  key: "relation-key",
  targetRecord: theTargetRecord,
});
\`\`\`

Records.removeRelation(options)
Use this function to remove a relation between two records.

\`\`\`
// You can either specify the Ids and classes directly
await Records.removeRelation({
  className: "myClass",
  recordId: "owning-record-id",
  key: "the-relation-key-on-the-owning-record",
  targetRecordId: "the-id-of-the-record-to-remove-a-relation-to",
  targetClassName: "the-class-of-the-target-record",
});

// Or if you already have two records that have been previously fetched or returned from a
// query
await Records.removeRelation({
  record: myRecord,
  key: "relation-key",
  targetRecord: theTargetRecord,
});
\`\`\`

Here is the schema of the database:
%{database-schema}%

Respond only with this specific format, and nothing else:
<function>output the code</function>
<explain>short description</explain>`;
const FUNCTION_CRUD_CONTEXT_EDIT = `
With these functions you can read, write and delete records in the cloud database. All functions are async and will throw an exception if they fail.

- An input in a Noodl function must follow the format "Inputs.InputName".
- An input in a Noodl function is only read, never written to.
- An output in a Noodl function must follow the format "Outputs.OutputName = value".
- A variable in a Noodl function never stores an output.
- Sending a signal from a Noodl function must follow the format "Outputs.SignalName()".
- Signals can not be passed values. All output values must be set as a Noodl function output.
- Inputs and Outputs in a Noodl function are global.
- Noodl functions do not use import statements.
- Noodl functions do not use export statements.
- Noodl functions can use recources from a CDN.
- Noodl functions can access API endpoints with "fetch".
- Define constants as Noodl function inputs.
- All const should be using Noodl inputs with an OR operator to a default value.
- When the request is successful call "Success" output signal.
- When something fails in the code the "Failure" output signal.

Records.fetch(objectOrId,options)
Use this function to fetch the latest properties of a specific record from the cloud database. It will return the object / record.

\`\`\`
// If you use the a record ID you must also specify the class
const myRecord = await Records.fetch(myRecordId, {
  className: "myClass",
});

// You can also fetch a record you have previously fetched or received from a
// query, to get the latest properties from the backend
await Records.fetch(myRecord);
\`\`\`

By default fetch will return pointer properties as the string Id of the object pointed to. But you can use the \`include\` option to specify that you want the content of the object to be returned instead.

\`\`\`
// By using include the request will return the pointed to object with all properties instead of
// just the string Id
const res = await Records.fetch(myRecord,{
  include:["Customer","Author"]
});

res.Customer.id // Now Customer is an object and not a string
\`\`\`

Records.save(objectOrId,properties,options)
Use this function to write an existing record to the cloud database. It will attempt to save all properties of the record / object if you don't specify the optional properties argument, if so it will set and save those properties.

\`\`\`
Objects[myRecordId].SomeProperty = "hello";

// If you use the record id to save, you need to specify the classname explicitly
// by specfiying null or undefinded for properties it will save all proporties in
// the record
await Records.save(myRecordId, null, { className: "myClass" });

// Or use the object directly
await Records.save(Objects[myRecordId]);

// Set specified properties and save only those to the backned
await Records.save(myRecord, {
  SomeProperty: "hello",
});
\`\`\`

Records.increment(objectOrId,properties,options)
This function will increment (or decrease) propertis of a certain record saving it to the cloud database in a race condition safe way. That is, normally you would have to first read the current value, modify it and save it to the database. Here you can do it with one operation.

\`\`\`
// Modify the specified numbers in the cloud
await Records.increment(myRecord, {
  Score: 10,
  Life: -1,
});

// Like save, you can use a record Id and class
await Records.increment(myRecordId, { Likes: 1 }, { className: "myClass" });
\`\`\`

Using the options you can also specify access control, this let's you control which users can access a specific record. The access control is specified as below:

\`\`\`
await Records.save(myRecord, null, {
  acl: {
    "*": { read: true, write: false }, // "*" means everyone, this rules gives everyone read access but not write
    "a-user-id": { read: true, write: true }, // give a specific user write access
    "role:a-role-name": { read: true, write: true }, // give a specific role write access
  },
});
\`\`\`

Records.create(className,properties,options)
This function will create a new record in the cloud database and return the object of the newly created record. If it's unsuccessful it will throw an exception.

\`\`\`
const myNewRecord = await Records.create("myClass", {
  SomeProperty: "Hello",
});

console.log(myNewRecord.SomeProperty);
\`\`\`

You can use the \`options\` agrument to specify access control rules as detailed under **Records.save** above.

Records.delete(objectOrId,options)
Use this function to delete an existing record from the cloud database.

\`\`\`
// If you specify the id of a record to be deleted, you must also provide the
// class name in the options
await Records.delete(myRecordId, { className: "myClass" });

// Or use the object directly (provided it was previously fetched or received via a query)
await Records.delete(Objects[myRecordId]);
\`\`\`

Records.addRelation(options)
Use this function to add a relation between two records.

\`\`\`
// You can either specify the Ids and classes directly
await Noodl.Records.addRelation({
  className: "myClass",
  recordId: "owning-record-id",
  key: "the-relation-key-on-the-owning-record",
  targetRecordId: "the-id-of-the-record-to-add-a-relation-to",
  targetClassName: "the-class-of-the-target-record",
});

// Or if you already have two records that have been previously fetched or returned from a
// query
await Records.addRelation({
  record: myRecord,
  key: "relation-key",
  targetRecord: theTargetRecord,
});
\`\`\`

Records.removeRelation(options)
Use this function to remove a relation between two records.

\`\`\`
// You can either specify the Ids and classes directly
await Records.removeRelation({
  className: "myClass",
  recordId: "owning-record-id",
  key: "the-relation-key-on-the-owning-record",
  targetRecordId: "the-id-of-the-record-to-remove-a-relation-to",
  targetClassName: "the-class-of-the-target-record",
});

// Or if you already have two records that have been previously fetched or returned from a
// query
await Records.removeRelation({
  record: myRecord,
  key: "relation-key",
  targetRecord: theTargetRecord,
});
\`\`\`

Here is the schema of the database:
%{database-schema}%

We are starting from this code and will only modify it:
\`\`\`
%{code}%
\`\`\`

Respond only with this specific format, and nothing else:
<function>output the code</function>
<explain>short description</explain>`;

// EXTERNAL MODULE: ./src/editor/src/utils/editorsettings.ts
var editorsettings = __webpack_require__(39804);
// EXTERNAL MODULE: ./src/editor/src/views/panels/EditorSettingsPanel/sections/OpenAiSection.tsx + 2 modules
var OpenAiSection = __webpack_require__(56353);
;// ./src/editor/src/models/AiAssistant/templates/function-query-database/gpt-4-version.ts






async function function_query_database_gpt_4_version_execute({ node, chatHistory, chatStream, chatStreamXml }, dbCollectionsSource) {
    const history = chatHistory.messages.map((x) => ({
        role: String(x.type),
        content: x.content
    }));
    const currentScript = node.getParameter('functionScript');
    // ---
    // Generate code
    const messages = currentScript
        ? [
            {
                role: 'system',
                content: QUERY_CONTEXT_EDIT.replace('%{database-schema}%', dbCollectionsSource).replace('%{code}%', currentScript)
            },
            history.at(-1)
        ]
        : [
            {
                role: 'system',
                content: QUERY_CONTEXT_CREATE.replace('%{database-schema}%', dbCollectionsSource)
            },
            ...history
        ];
    const fullCodeText = await chatStream({
        provider: {
            model: 'gpt-4o-mini',
            temperature: 0.0,
            max_tokens: 2048
        },
        messages
    });
    let codeText = extractCodeBlock(fullCodeText);
    if (!codeText.includes('const query = Noodl.Records.query;')) {
        codeText = 'const query = Noodl.Records.query;\n' + codeText;
    }
    // ---
    // Evaluate the code if it is valid.
    try {
        // Allow async/await
        const wrappedCode = `async function validateCode() { ${codeText} }`;
        new Function(wrappedCode);
    }
    catch (error) {
        console.error(error);
        const activityCodeGenId = 'code-generation';
        chatHistory.removeActivity(activityCodeGenId);
        chatHistory.add({
            type: ChatHistory/* ChatMessageType */._J.Assistant,
            content: ''
        });
        await ai_utils/* AiUtils */.Y.fakeTokenStream(`I'm sorry. I'm afraid I can't do that.`, (delta, fullText) => {
            chatHistory.updateLast({
                content: fullText
            });
        });
        const activityId = 'processing';
        chatHistory.removeActivity(activityId);
        return;
    }
    // Set the parameter
    node.setParameter('functionScript', codeText);
    // Save it in the history, so it will be possible to go back and forth.
    chatHistory.updateLast({
        metadata: {
            code: codeText
        }
    });
    // ---
    // Explain the code
    chatHistory.add({
        type: ChatHistory/* ChatMessageType */._J.Assistant,
        content: ''
    });
    let questionIndex = 0;
    const result = [''];
    await chatStreamXml({
        messages: [
            {
                role: 'system',
                content: QUERY_CONTEXT_EXPLAINER()
            },
            { role: 'user', content: codeText }
        ],
        provider: {
            model: 'gpt-4o-mini',
            temperature: 0.0,
            max_tokens: 2048
        },
        onStream(tagName, text) {
            // TODO: It calls an empty string at the end, why?
            if (text.length === 0) {
                return;
            }
            console.log('[stream]', tagName, text);
            switch (tagName) {
                case 'explain': {
                    result[result.length - 1] = text;
                    break;
                }
                case 'Input': {
                    result[result.length - 1] = wrapInput(text);
                    break;
                }
                case 'Output': {
                    result[result.length - 1] = wrapOutput(text);
                    break;
                }
            }
            if (['explain', 'Input', 'Output'].includes(tagName)) {
                chatHistory.updateLast({
                    content: result.join('')
                });
            }
        },
        onTagOpen(tagName) {
            switch (tagName) {
                case 'Input':
                case 'Output': {
                    result.push('');
                    break;
                }
            }
        },
        onTagEnd(tagName, fullText) {
            console.log('[done]', tagName, fullText);
            switch (tagName) {
                case 'label': {
                    node.setLabel(fullText);
                    break;
                }
                case 'explain': {
                    result[result.length - 1] = fullText;
                    result.push('');
                    break;
                }
                case 'Input': {
                    result[result.length - 1] = wrapInput(fullText);
                    result.push('');
                    break;
                }
                case 'Output': {
                    result[result.length - 1] = wrapOutput(fullText);
                    result.push('');
                    break;
                }
                case 'question': {
                    const suggestions = chatHistory.messages[chatHistory.messages.length - 1].metadata.suggestions || [];
                    suggestions[questionIndex] = {
                        id: (0,utils.guid)(),
                        text: fullText.endsWith('?') ? fullText : fullText + '?'
                    };
                    chatHistory.updateLast({
                        metadata: {
                            suggestions
                        }
                    });
                    questionIndex++;
                    break;
                }
            }
            if (['explain', 'Input', 'Output'].includes(tagName)) {
                chatHistory.updateLast({
                    content: result.join('')
                });
            }
        }
    });
}
const QUERY_CONTEXT_GENERAL_RULES = `###Instructions###
- You will be writing Noodl javascript functions that make database queries and return the result.
- An input in a Noodl function must follow the format "Inputs.InputName".
- An input in a Noodl function is only read, never written to.
- An output in a Noodl function must follow the format "Outputs.OutputName = value".
- A variable in a Noodl function never stores an output.
- Sending a signal from a Noodl function must follow the format "Outputs.SignalName()".
- Signals can not be passed values. All output values must be set as a Noodl function output.
- Inputs and Outputs in a Noodl function are global.
- Noodl functions do not use import statements.
- Noodl functions do not use export statements.
- Noodl functions can use recources from a CDN.
- Noodl functions can access API endpoints with "fetch".
- Define constants as Noodl function inputs.
- All const should be using Noodl inputs with an OR operator to a default value.
- When the request is successful call "Success" output signal.
- When something fails in the code the "Failure" output signal.

###Query API###
query(className, query, options) A async function that queries the database with the provided query parameter, returning the result or throwing an exception upon failure.`;
const QUERY_CONTEXT_GENERAL_BACKGROUND = `###Available Operators###
lessThan: Less Than
lessThanOrEqualTo: Less Than Or Equal To
greaterThan: Greater Than
greaterThanOrEqualTo: Greater Than Or Equal To
equalTo: Not Equal To
notEqualTo: Not Equal To
containedIn: Contained In
notContainedIn: Not Contained in
exists: A value is set for the key
matchesRegex: Check if a value matches a regex pattern
text: Text search in one or several columns using a text index
idEqualTo: Match the id of the item to a specific id
idContainedIn: Check if the id of the item matches an id in an array of ids
pointsTo: Check if the id of the item matches an id in an array of ids
relatedTo: Checks if the item is related to another item, through a relation

###Condition Examples###
{
  Letter: { containedIn: ["A", "B", "C"] },
}

{
  Letter: { exists: true },
}

{
  and: [{ ZipCode: { exists: true } }, { Score: { greaterThan: 10 } }],
}

{
  SomeString: { matchesRegex: "pattern", options: "i" },
}

{
  SomeDate: { equalTo: new Date() },
}

{
  SomeString: { equalTo: Inputs.MyStringInput },
}

{
  SomeString: { text: { search: Inputs.MyStringInput } },
}

{
  SomeString: {
    text: {
      search: {
        term: Inputs.MyStringInput,
        caseSensitive: true,
      },
    },
  },
}

{
  idEqualTo: Inputs.TheRecordId,
}

{
  idContainedIn: [Inputs.FirstObjectId, Inputs.SecondObjectId],
}

{
  Owner: { pointsTo: Inputs.MyPostId },
}

{
  Owner: { pointsTo: [Inputs.MyFirstPostId, Inputs.MySecondPost] },
}

{
  relatedTo: { id: Inputs.MyRecordWithARelation, key: "the-relation-key" },
}

{
  Location: {
    nearSphere: {
      latitude: 48.0,
      longitude: -110.1,
    },
  },
}

{
  Location: {
    nearSphere: {
      latitude: 48.0,
      longitude: -110.1,
      maxDistanceInKilometers: 100,
    },
  },
}

{
  Location: {
    withinBox: [
      {
        latitude: 37.71,
        longitude: -122.53,
      },
      {
        latitude: 30.82,
        longitude: -122.37,
      },
    ],
  },
}

{
  Location: {
    withinPolygon: [
      {
        latitude: 25.774,
        longitude: -80.19,
      },
      {
        latitude: 18.466,
        longitude: -66.118,
      },
      {
        latitude: 32.321,
        longitude: -64.757,
      },
    ],
  },
}

const results = await query(
  "myClass",
  {
    Completed: { equalTo: true },
  },
  {
    sort: ["createdAt"],
  }
);

sort: ["-Age", "createdAt"]

const results = await query(
  "myClass",
  {
    Completed: { equalTo: true },
  },
  {
    sort: ["-createdAt"], // use - to sort descending
    skip: 50,
    limit: 200,
  }
);

const res = await query(
  "myClass",
  {
    Completed: { equalTo: true },
  },
  {
    sort: ["-createdAt"], // use - to sort descending
    skip: 50,
    limit: 200,
    count:true,
  }
);

const results = await query(
  "myClass",
  {},
  {
    include: "Customer",
  }
);

const results = await query(
  "myClass",
  {},
  {
    include: "Customer,Author.Location",
  }
);

const results = await query(
  "myClass",
  {
    Completed: { equalTo: true },
  },
  {
    select: "Title,Body",
  }
);`;
const QUERY_CONTEXT_CREATE = `${QUERY_CONTEXT_GENERAL_RULES}

###Query Example###
\`\`\`
const query = Noodl.Records.query;
const articleId = Inputs.ArticleId;
const likesThreshold = Inputs.LikesThreshold || 4;

if (!articleId) return;

try {
  const results = await query("Comment", {
    article_id: { pointsTo: articleId },
    likes: { greaterThan: likesThreshold },
  });

  Outputs.Articles = results;
  Outputs.Success();
} catch (error) {
  console.error("Error:", error);
  Outputs.Failure();
  Outputs.error = error
}
\`\`\`

${QUERY_CONTEXT_GENERAL_BACKGROUND}

###schema###
Here is the schema of the database:
%{database-schema}%

##Task###
Make a query from the given task and return only code.`;
const QUERY_CONTEXT_EDIT = `${QUERY_CONTEXT_GENERAL_RULES}
${QUERY_CONTEXT_GENERAL_BACKGROUND}

Here is the schema of the database:
%{database-schema}%

We are starting from this code and will only modify it:
\`\`\`
%{code}%
\`\`\`

##Task###
Make a query from the given task and return only code.`;
const QUERY_CONTEXT_EXPLAINER = () => {
    const enableSuggestions = !!editorsettings/* EditorSettings */.H.instance.get(OpenAiSection/* AI_ASSISTANT_ENABLED_SUGGESTIONS_KEY */.S);
    return `###Context###
- This function is specialized in querying records from a database in Noodl
- We are currently inside a Component with this node created, the node have the function inside.
- All the variables from the Inputs object is defined on the node as inputs which can be set via the properties on input connection.
- All the variables on the Outputs object is defined on the node as outputs which can be connected to another node.
###Instructions###
Analyse the function and create a label, an explanation, and some follow-up questions

###Label###
Create a label that summarises what the function does.

###Explanation###
Explain with 2-5 sentences what the function does after the line with the Noodl.Records.query.
- Always include the property names of the Inputs and Outputs objects in the explanation.
- Always format the property names of the Inputs like this: <Input>input name</Input>
- Always format the property names of the Outputs like this: <Output>output name</Output>

###Follow-up questions###
Maximum of 3 follow-up questions related to the code.

###Examples###
<label>Data To Excel</label>
<explain>This function converts a JSON array input called <Input>Data</Input> to an Excel file and initiates a download. It takes a string called  <Input>FileName</Input> as an input, creates a new workbook and worksheet using the XLSX library, converts the JSON data to a sheet, and appends the sheet to the workbook. It then converts the workbook to a binary string, creates a Blob, and generates a download link. Finally, it triggers the <Output>Success</Output> output signal after the download is initiated.</explain>
${enableSuggestions
        ? `<question>What is the format of the required JSON data array?</question>
<question>How do I connect this node to other nodes in my Noodl project?</question>
<question>Are there any limitations or required libraries for this function to work properly?</question>`
        : ''}

###Task###
Respond only with this specific format, and nothing else:
<label>The label</label>
<explain>The explanation</explain>
${enableSuggestions ? '<question>Maximum of 3 follow-up questions</question>' : ''}`;
};

;// ./src/editor/src/models/AiAssistant/templates/function-query-database.ts




const function_query_database_template = {
    type: 'green',
    name: 'JavaScriptFunction',
    nodeDisplayName: 'Read Database',
    onMessage: async (context) => {
        const version = AiAssistantStore/* OpenAiStore */.q.getVersion();
        const activityId = 'processing';
        const activityCodeGenId = 'code-generation';
        context.chatHistory.addActivity({
            id: activityId,
            name: 'Processing'
        });
        context.chatHistory.addActivity({
            id: activityCodeGenId,
            name: 'Generating code...'
        });
        // ---
        // Database
        const dbCollectionsSource = await extractDatabaseSchema();
        console.log('database schema', dbCollectionsSource);
        // ---
        console.log('using version: ', version);
        if (['full-beta', 'enterprise'].includes(version)) {
            await function_query_database_gpt_4_version_execute(context, dbCollectionsSource);
        }
        else {
            await function_query_database_gpt_4_version_execute(context, dbCollectionsSource);
        }
        context.chatHistory.removeActivity(activityCodeGenId);
        context.chatHistory.removeActivity(activityId);
    }
};

;// ./src/editor/src/models/AiAssistant/AiTemplates.ts




const aiNodeTemplates = {
    ['function-crud']: function_crud_template,
    ['function-query-database']: function_query_database_template,
    function: function_template,
    chart: template
};

// EXTERNAL MODULE: ./src/editor/src/models/nodegraphmodel/index.ts + 4 modules
var nodegraphmodel = __webpack_require__(87844);
// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.ts + 4 modules
var projectmodel = __webpack_require__(6203);
// EXTERNAL MODULE: ./src/editor/src/utils/model.ts
var model = __webpack_require__(81267);
;// ./src/editor/src/models/AiAssistant/AiAssistantModel.ts











const docsTemplates = [
    {
        label: 'Read from database',
        desc: 'Create a node that queries the database, filters and returns the results.',
        examples: [
            'Get all users that belong to the "Vendor" group',
            'Get all products, sort from lowest to highest price',
            'Get all unread messages for the currently logged in user'
        ],
        primer: 'query.md',
        prefix: 'const query = Noodl.Records.query;\n',
        template: 'function-query-database'
    },
    {
        label: 'Fetch REST API',
        desc: 'Create a node that connects to an external REST API via a HTTP request and performs an action.',
        examples: ['Get the main image from a wikipedia page', 'List the songs in a playlist in spotify'],
        primer: 'rest.md',
        template: 'rest'
    },
    {
        label: 'Form Validation',
        desc: 'Specify inputs and how you want them validated, the outputs are any validations and errors.',
        examples: ['Validate a phone number and email'],
        primer: 'validation.md',
        template: 'function-form-validation'
    },
    {
        label: 'AI Function',
        desc: 'Create a function node that performs a task when you trigger Run, it can have inputs and outputs.',
        examples: [
            'Create inputs for Array1 and Array2 and output all items with the same ID',
            'Get a random number between the min and max inputs',
            'Get the current location of the device'
        ],
        primer: 'function.md',
        template: 'function'
    },
    {
        label: 'Write to database',
        desc: '',
        examples: [],
        template: 'function-crud'
    },
    {
        label: '',
        desc: '',
        examples: [],
        template: 'chart'
    }
];
var AiAssistantEvent;
(function (AiAssistantEvent) {
    AiAssistantEvent[AiAssistantEvent["ProcessingUpdated"] = 0] = "ProcessingUpdated";
    AiAssistantEvent[AiAssistantEvent["ActivityUpdated"] = 1] = "ActivityUpdated";
})(AiAssistantEvent || (AiAssistantEvent = {}));
async function deprecated_getAiDirPath() {
    const relative = '.noodl/ai';
    const path = src.filesystem.resolve(projectmodel.ProjectModel.instance._retainedProjectDirectory, relative);
    if (!src.filesystem.exists(path)) {
        await src.filesystem.makeDirectory(path);
    }
    return path;
}
class AiAssistantModel extends model/* Model */.K {
    constructor() {
        super();
        this.templates = docsTemplates.map((x) => {
            var _a, _b;
            return ({
                id: x.label,
                type: (_a = aiNodeTemplates[x.template]) === null || _a === void 0 ? void 0 : _a.type,
                nodeName: (_b = aiNodeTemplates[x.template]) === null || _b === void 0 ? void 0 : _b.name,
                templateId: x.template,
                template: aiNodeTemplates[x.template],
                name: x.label,
                description: x.desc,
                examples: x.examples || [],
                promptUrl: null
            });
        });
        this._contexts = {};
        this.activities = [];
        const _self = this;
        EventDispatcher.EventDispatcher.instance.on(['Model.nodeRemoved'], function ({ args }) {
            const nodeId = args.model.id;
            if (_self._contexts[nodeId]) {
                _self._contexts[nodeId].abortController.abort('node deleted');
                delete _self._contexts[nodeId];
            }
        }, this);
    }
    addActivity({ id, type, title, prompt, node, graph }) {
        this.activities.push({ id, type, title, prompt, node, graph });
        this.notifyListeners(AiAssistantEvent.ActivityUpdated);
    }
    removeActivity(id) {
        const activityTitle = this.activities.find((item) => item.id === id).title;
        this.activities = this.activities.filter((item) => item.id !== id);
        this.notifyListeners(AiAssistantEvent.ActivityUpdated);
        ToastLayer.ToastLayer.showInteraction(`AI finished the ${activityTitle} activity`);
    }
    /**
     * @returns A list of all Node ids that are currently getting processed.
     */
    getProcessingNodeIds() {
        return Object.keys(this._contexts).filter((x) => this._contexts[x].chatHistory.activities.length > 0);
    }
    async createContext(node) {
        const aiAssistant = node.metadata.AiAssistant;
        if (!aiAssistant) {
            throw 'This node is not an AI node.';
        }
        if (this._contexts[node.id]) {
            return this._contexts[node.id];
        }
        const chatHistory = ChatHistory/* ChatHistory */.DJ.fromJSON(node.metadata.prompt);
        // Backwards compatibility, load the AI file and fetch the template.
        if (node.metadata.AiAssistant && !node.metadata.prompt) {
            try {
                const path = await deprecated_getAiDirPath();
                const filePath = src.filesystem.resolve(path, node.metadata.AiAssistant);
                if (src.filesystem.exists(filePath)) {
                    const json = await src.filesystem.readJson(filePath);
                    const messages = json.history || [];
                    messages.forEach((message) => {
                        chatHistory.add(message);
                    });
                    chatHistory.metadata.templateId = json.metadata.templateId;
                    // NOTE: Keeping this since it is used in other places to define it as AI node
                    node.metadata.AiAssistant = 'moved';
                    node.metadata.prompt = chatHistory.toJSON();
                    node.notifyListeners('metadataChanged', { key: 'prompt', data: node.metadata.prompt });
                    await src.filesystem.removeFile(filePath);
                }
            }
            catch (error) {
                console.error('Failed to load old AI file.', error);
            }
        }
        // HACK: It is loading it twice...
        if (this._contexts[node.id]) {
            return this._contexts[node.id];
        }
        chatHistory.on(ChatHistory/* ChatHistoryEvent */.Pw.ActivitiesChanged, () => {
            this.notifyListeners(AiAssistantEvent.ProcessingUpdated, node.id);
        });
        const template = this.templates.find((x) => x.templateId === chatHistory.metadata.templateId);
        if (!template) {
            throw 'Template not found';
        }
        const context = new AiCopilotContext/* AiCopilotContext */.q(template, chatHistory, node);
        this._contexts[node.id] = context;
        return context;
    }
    async send(context) {
        await context.template.template.onMessage(
        // Send it as an object so the methods are bound to this class.
        context.toObject(), context.chatHistory.messages.length > 0
            ? context.chatHistory.messages[context.chatHistory.messages.length - 1]
            : null);
        // Save the chat history
        context.node.metadata.prompt = context.chatHistory.toJSON();
    }
    async createNode(templateId, parentModel, pos) {
        function createNodes(nodeset, pos, parentModel, toastMessage) {
            const nodes = [];
            if (parentModel) {
                for (const node of nodeset.nodes) {
                    parentModel.addChild(node);
                    nodes.push(node);
                }
            }
            else {
                const nodeGraph = NodeGraphContext.NodeGraphContextTmp.nodeGraph;
                const insertedNodeset = nodeGraph.insertNodeSet({
                    nodeset: nodeset,
                    x: pos.x,
                    y: pos.y,
                    toastMessage
                });
                for (const node of insertedNodeset.nodes) {
                    nodes.push(node);
                }
            }
            return nodes;
        }
        const template = this.templates.find((x) => x.templateId === templateId);
        if (!template) {
            throw 'Template not found';
        }
        const metadata = {
            prompt: new ChatHistory/* ChatHistory */.DJ([], { templateId }).toJSON(),
            AiAssistant: 'old'
        };
        //hack: nodes that are of type 'green' will get a color override to the node color theme 'data'
        let color;
        switch (template.type) {
            case 'green':
                color = 'data';
                break;
        }
        if (color) {
            metadata.colorOverride = color;
        }
        if (template.template.nodeDisplayName) {
            metadata.typeLabelOverride = template.template.nodeDisplayName;
        }
        const nodeset = new nodegraphmodel/* NodeGraphNodeSet */.bn({
            nodes: [
                nodegraphmodel/* NodeGraphNode */.dF.fromJSON({
                    id: (0,utils.guid)(),
                    label: template.name,
                    type: template.nodeName,
                    x: 0,
                    y: 0,
                    metadata
                })
            ],
            connections: []
        });
        // NOTE: This will create a clone of the nodeset, so the ids will be changed
        const insertedNodes = createNodes(nodeset, pos, parentModel, `Created AI Node`);
        // HACK: Expect only one node back
        return this.createContext(insertedNodes[0]);
    }
    //clears all the context, important when closing a project
    resetContexts() {
        this._contexts = {};
    }
}
AiAssistantModel.instance = new AiAssistantModel();


/***/ }),

/***/ 77649:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const fs = __webpack_require__(79896);

const isRenderer = process && process.type === 'renderer';

// TODO: Remove electron
const app = isRenderer ? (__webpack_require__(52391).app) : (__webpack_require__(91288).app);
const tmpFolder = app.getPath('temp');

const driverOptionsPath = tmpFolder + 'noodl-merge-driver-options.json';

/**
 *
 * @param {{ reversed: boolean; }} options
 * @returns
 */

module.exports = {
  /**
   * @param {{
   *    reversed: boolean;
   * }} options
   * @returns
   */
  writeMergeDriverOptions(options) {
    if (typeof options !== 'object') throw new Error('options is not an object');
    return fs.promises.writeFile(driverOptionsPath, JSON.stringify(options));
  },

  cleanMergeDriverOptionsSync() {
    if (fs.existsSync(driverOptionsPath)) {
      fs.unlinkSync(driverOptionsPath);
    }
  },

  /**
   *
   * @returns {{
   *    reversed: boolean;
   * }}
   */
  readMergeDriverOptionsSync() {
    try {
      if (fs.existsSync(driverOptionsPath)) {
        const options = fs.readFileSync(driverOptionsPath);
        return JSON.parse(options);
      }
    } catch (error) {
      console.error(error);
    }

    return {};
  }
};


/***/ }),

/***/ 77863:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/* -- zone widget */
.monaco-editor .zone-widget .zone-widget-container.reference-zone-widget {
	border-top-width: 1px;
	border-bottom-width: 1px;
}

.monaco-editor .reference-zone-widget .inline {
	display: inline-block;
	vertical-align: top;
}

.monaco-editor .reference-zone-widget .messages {
	height: 100%;
	width: 100%;
	text-align: center;
	padding: 3em 0;
}

.monaco-editor .reference-zone-widget .ref-tree {
	line-height: 23px;
	background-color: var(--vscode-peekViewResult-background);
	color: var(--vscode-peekViewResult-lineForeground);
}

.monaco-editor .reference-zone-widget .ref-tree .reference {
	text-overflow: ellipsis;
	overflow: hidden;
}

.monaco-editor .reference-zone-widget .ref-tree .reference-file {
	display: inline-flex;
	width: 100%;
	height: 100%;
	color: var(--vscode-peekViewResult-fileForeground);
}

.monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .selected .reference-file {
	color: inherit !important;
}

.monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .monaco-list-rows > .monaco-list-row.selected:not(.highlighted) {
	background-color: var(--vscode-peekViewResult-selectionBackground);
	color: var(--vscode-peekViewResult-selectionForeground) !important;
}

.monaco-editor .reference-zone-widget .ref-tree .reference-file .count {
	margin-right: 12px;
	margin-left: auto;
}

.monaco-editor .reference-zone-widget .ref-tree .referenceMatch .highlight {
	background-color: var(--vscode-peekViewResult-matchHighlightBackground);
}

.monaco-editor .reference-zone-widget .preview .reference-decoration {
	background-color: var(--vscode-peekViewEditor-matchHighlightBackground);
	border: 2px solid var(--vscode-peekViewEditor-matchHighlightBorder);
	box-sizing: border-box;
}

.monaco-editor .reference-zone-widget .preview .monaco-editor .monaco-editor-background,
.monaco-editor .reference-zone-widget .preview .monaco-editor .inputarea.ime-input {
	background-color: var(--vscode-peekViewEditor-background);
}

.monaco-editor .reference-zone-widget .preview .monaco-editor .margin {
	background-color: var(--vscode-peekViewEditorGutter-background);
}

/* High Contrast Theming */

.monaco-editor.hc-black .reference-zone-widget .ref-tree .reference-file,
.monaco-editor.hc-light .reference-zone-widget .ref-tree .reference-file {
	font-weight: bold;
}

.monaco-editor.hc-black .reference-zone-widget .ref-tree .referenceMatch .highlight,
.monaco-editor.hc-light .reference-zone-widget .ref-tree .referenceMatch .highlight {
	border: 1px dotted var(--vscode-contrastActiveBorder, transparent);
	box-sizing: border-box;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/browser/peek/referencesWidget.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F,mBAAmB;AACnB;CACC,qBAAqB;CACrB,wBAAwB;AACzB;;AAEA;CACC,qBAAqB;CACrB,mBAAmB;AACpB;;AAEA;CACC,YAAY;CACZ,WAAW;CACX,kBAAkB;CAClB,cAAc;AACf;;AAEA;CACC,iBAAiB;CACjB,yDAAyD;CACzD,kDAAkD;AACnD;;AAEA;CACC,uBAAuB;CACvB,gBAAgB;AACjB;;AAEA;CACC,oBAAoB;CACpB,WAAW;CACX,YAAY;CACZ,kDAAkD;AACnD;;AAEA;CACC,yBAAyB;AAC1B;;AAEA;CACC,kEAAkE;CAClE,kEAAkE;AACnE;;AAEA;CACC,kBAAkB;CAClB,iBAAiB;AAClB;;AAEA;CACC,uEAAuE;AACxE;;AAEA;CACC,uEAAuE;CACvE,mEAAmE;CACnE,sBAAsB;AACvB;;AAEA;;CAEC,yDAAyD;AAC1D;;AAEA;CACC,+DAA+D;AAChE;;AAEA,0BAA0B;;AAE1B;;CAEC,iBAAiB;AAClB;;AAEA;;CAEC,kEAAkE;CAClE,sBAAsB;AACvB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/* -- zone widget */\n.monaco-editor .zone-widget .zone-widget-container.reference-zone-widget {\n\tborder-top-width: 1px;\n\tborder-bottom-width: 1px;\n}\n\n.monaco-editor .reference-zone-widget .inline {\n\tdisplay: inline-block;\n\tvertical-align: top;\n}\n\n.monaco-editor .reference-zone-widget .messages {\n\theight: 100%;\n\twidth: 100%;\n\ttext-align: center;\n\tpadding: 3em 0;\n}\n\n.monaco-editor .reference-zone-widget .ref-tree {\n\tline-height: 23px;\n\tbackground-color: var(--vscode-peekViewResult-background);\n\tcolor: var(--vscode-peekViewResult-lineForeground);\n}\n\n.monaco-editor .reference-zone-widget .ref-tree .reference {\n\ttext-overflow: ellipsis;\n\toverflow: hidden;\n}\n\n.monaco-editor .reference-zone-widget .ref-tree .reference-file {\n\tdisplay: inline-flex;\n\twidth: 100%;\n\theight: 100%;\n\tcolor: var(--vscode-peekViewResult-fileForeground);\n}\n\n.monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .selected .reference-file {\n\tcolor: inherit !important;\n}\n\n.monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .monaco-list-rows > .monaco-list-row.selected:not(.highlighted) {\n\tbackground-color: var(--vscode-peekViewResult-selectionBackground);\n\tcolor: var(--vscode-peekViewResult-selectionForeground) !important;\n}\n\n.monaco-editor .reference-zone-widget .ref-tree .reference-file .count {\n\tmargin-right: 12px;\n\tmargin-left: auto;\n}\n\n.monaco-editor .reference-zone-widget .ref-tree .referenceMatch .highlight {\n\tbackground-color: var(--vscode-peekViewResult-matchHighlightBackground);\n}\n\n.monaco-editor .reference-zone-widget .preview .reference-decoration {\n\tbackground-color: var(--vscode-peekViewEditor-matchHighlightBackground);\n\tborder: 2px solid var(--vscode-peekViewEditor-matchHighlightBorder);\n\tbox-sizing: border-box;\n}\n\n.monaco-editor .reference-zone-widget .preview .monaco-editor .monaco-editor-background,\n.monaco-editor .reference-zone-widget .preview .monaco-editor .inputarea.ime-input {\n\tbackground-color: var(--vscode-peekViewEditor-background);\n}\n\n.monaco-editor .reference-zone-widget .preview .monaco-editor .margin {\n\tbackground-color: var(--vscode-peekViewEditorGutter-background);\n}\n\n/* High Contrast Theming */\n\n.monaco-editor.hc-black .reference-zone-widget .ref-tree .reference-file,\n.monaco-editor.hc-light .reference-zone-widget .ref-tree .reference-file {\n\tfont-weight: bold;\n}\n\n.monaco-editor.hc-black .reference-zone-widget .ref-tree .referenceMatch .highlight,\n.monaco-editor.hc-light .reference-zone-widget .ref-tree .referenceMatch .highlight {\n\tborder: 1px dotted var(--vscode-contrastActiveBorder, transparent);\n\tbox-sizing: border-box;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 78052:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.SearchInput-module__Root--cRK4C{position:relative;display:flex;background-color:var(--theme-color-bg-1)}.SearchInput-module__SearchInputIcon--ibQ_5{position:absolute;width:22px;height:22px;top:50%;transform:translateY(-50%);left:10px;pointer-events:none;opacity:.6;transition:opacity 200ms ease-in-out 1000ms}.SearchInput-module__SearchInput--BSjKb:focus+.SearchInput-module__SearchInputIcon--ibQ_5{transition:opacity 200ms ease-in-out;opacity:1}.SearchInput-module__SearchInput--BSjKb{background-color:rgba(0,0,0,0);color:var(--theme-color-fg-highlight);font-size:14px;font-weight:500;height:45px;line-height:45px;border:none;flex-grow:1;padding-left:40px}.SearchInput-module__SearchInput--BSjKb::placeholder{color:var(--theme-color-fg-default-shy);padding-left:5px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/SearchInput/SearchInput.module.scss"],"names":[],"mappings":"AAEA,iCACE,iBAAA,CACA,YAAA,CACA,wCAAA,CAGF,4CACE,iBAAA,CACA,UAAA,CACA,WAAA,CACA,OAAA,CACA,0BAAA,CACA,SAAA,CACA,mBAAA,CACA,UAAA,CACA,2CAAA,CAEA,0FACE,oCAAA,CACA,SAAA,CAIJ,wCACE,8BAAA,CACA,qCAAA,CACA,cAAA,CACA,eAAA,CACA,WA9BmB,CA+BnB,gBA/BmB,CAgCnB,WAAA,CACA,WAAA,CACA,iBAAA,CAEA,qDACE,uCAAA,CACA,gBAAA","sourcesContent":["$_search-bar-height: 45px;\r\n\r\n.Root {\r\n  position: relative;\r\n  display: flex;\r\n  background-color: var(--theme-color-bg-1);\r\n}\r\n\r\n.SearchInputIcon {\r\n  position: absolute;\r\n  width: 22px;\r\n  height: 22px;\r\n  top: 50%;\r\n  transform: translateY(-50%);\r\n  left: 10px;\r\n  pointer-events: none;\r\n  opacity: 0.6;\r\n  transition: opacity 200ms ease-in-out 1000ms; // we lose focus for short amounts of time, make it less noticable\r\n\r\n  .SearchInput:focus + & {\r\n    transition: opacity 200ms ease-in-out;\r\n    opacity: 1;\r\n  }\r\n}\r\n\r\n.SearchInput {\r\n  background-color: transparent;\r\n  color: var(--theme-color-fg-highlight);\r\n  font-size: 14px;\r\n  font-weight: 500;\r\n  height: $_search-bar-height;\r\n  line-height: $_search-bar-height;\r\n  border: none;\r\n  flex-grow: 1;\r\n  padding-left: 40px;\r\n\r\n  &::placeholder {\r\n    color: var(--theme-color-fg-default-shy);\r\n    padding-left: 5px;\r\n  }\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `SearchInput-module__Root--cRK4C`,
	"SearchInputIcon": `SearchInput-module__SearchInputIcon--ibQ_5`,
	"SearchInput": `SearchInput-module__SearchInput--BSjKb`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 78133:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const path = __webpack_require__(16928);
const mkdir = __webpack_require__(66321);
const fs = __webpack_require__(79896);
const rimraf = __webpack_require__(55231);
const electron = __webpack_require__(91288);
const app = electron.app || (__webpack_require__(52391).app);

function fileNameForKey(key) {
  const keyFileName = path.basename(key, '.json') + '.json';

  // Prevent ENOENT and other similar errors when using
  // reserved characters in Windows filenames.
  // See: https://en.wikipedia.org/wiki/Filename#Reserved%5Fcharacters%5Fand%5Fwords
  const escapedFileName = encodeURIComponent(keyFileName);

  const userDataPath = app.getPath('userData');
  return path.join(userDataPath, escapedFileName);
}

/**
 * @depracted This implementation is not cross-platform use this instead:
 * ```ts
 * import { JSONStorage } from '@noodl/platform';
 * ```
 * 
 * Can't remove this file because it's called from main thread,
 * where the platform code is not setup.
 */
module.exports = {
  get: function (key, callback) {
    var filename = fileNameForKey(key);
    fs.readFile(filename, { encoding: 'utf8' }, function (error, object) {
      if (!error) {
        var objectJSON = {};
        try {
          objectJSON = JSON.parse(object);
        } catch (error) {
          return callback(); //new Error('Invalid data'));
        }
        return callback(objectJSON);
      }

      if (error.code === 'ENOENT') {
        return callback(JSON.stringify({}));
      }

      return callback();
    });

    /*storage.get(path, function(error, data) {
      if (error) { callback(); return }
      callback(data);
    });*/
  },
  set: function (key, data) {
    var filename = fileNameForKey(key);
    const json = JSON.stringify(data);

    mkdir(path.dirname(filename));
    fs.writeFileSync(filename, json);
  },
  remove: function (key, callback) {
    var filename = fileNameForKey(key);
    rimraf(filename, callback);

    // storage.remove(path,callback);
  }
};


/***/ }),

/***/ 78159:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgQuestionFill = function SvgQuestionFill(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 25,
    viewBox: "0 0 24 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.6455 12.8324C21.6455 18.2061 17.2893 22.5624 11.9155 22.5624C6.54182 22.5624 2.18555 18.2061 2.18555 12.8324C2.18555 7.45869 6.54182 3.10242 11.9155 3.10242C17.2893 3.10242 21.6455 7.45869 21.6455 12.8324ZM12.6571 7.37275C12.0039 7.24282 11.3268 7.3095 10.7115 7.56437C10.0962 7.81924 9.57032 8.25084 9.20031 8.80459C8.8303 9.35835 8.63281 10.0094 8.63281 10.6754C8.63281 11.0887 8.96784 11.4237 9.38111 11.4237C9.79438 11.4237 10.1294 11.0887 10.1294 10.6754C10.1294 10.3054 10.2391 9.9437 10.4447 9.63606C10.6502 9.32842 10.9424 9.08864 11.2843 8.94705C11.6261 8.80545 12.0022 8.76841 12.3651 8.84059C12.728 8.91277 13.0613 9.09094 13.323 9.35257C13.5846 9.6142 13.7628 9.94754 13.835 10.3104C13.9071 10.6733 13.8701 11.0495 13.7285 11.3913C13.5869 11.7331 13.3471 12.0253 13.0395 12.2309C12.7318 12.4364 12.3702 12.5461 12.0002 12.5461C11.8017 12.5461 11.6114 12.625 11.471 12.7653C11.3307 12.9056 11.2519 13.096 11.2519 13.2944V15.031C11.2519 15.4443 11.5869 15.7793 12.0002 15.7793C12.4134 15.7793 12.7485 15.4443 12.7485 15.031V13.9585C13.1469 13.8677 13.5276 13.7046 13.871 13.4752C14.4247 13.1052 14.8563 12.5793 15.1112 11.964C15.366 11.3487 15.4327 10.6717 15.3028 10.0185C15.1729 9.36525 14.8522 8.76525 14.3812 8.29432C13.9103 7.82339 13.3103 7.50268 12.6571 7.37275ZM13.1223 17.9185C13.1223 18.5384 12.6198 19.0409 11.9999 19.0409C11.38 19.0409 10.8774 18.5384 10.8774 17.9185C10.8774 17.2986 11.38 16.7961 11.9999 16.7961C12.6198 16.7961 13.1223 17.2986 13.1223 17.9185Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgQuestionFill);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "64bc462e41a6fa9c78572090d4d25133.svg");

/***/ }),

/***/ 78200:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

//Note: this files has to be javascript and require until the main process uses webpack+typescript

const { nodesSoftEqual } = __webpack_require__(42533);

const _ = __webpack_require__(42551);
const diff3 = __webpack_require__(11530);
const ProjectValidator = __webpack_require__(59734);

function mergeSourceCode(ancestor, ours, theirs) {
  var _o = ours.split(/\r?\n/);
  var _a = ancestor.split(/\r?\n/);
  var _t = theirs.split(/\r?\n/);

  //diff3 takes these arguments: A, O, B
  //A and B are independently derived from O
  //So we set A=ours, O=ancestor, B=theirs
  var diff = diff3(_o, _a, _t);
  let hasConflicts = false;

  var merged = '';
  for (var j = 0; j < diff.length; j++) {
    var d = diff[j];
    if (d.ok) {
      merged += d.ok.join('\n');
    } else if (d.conflict) {
      merged += '\n------------- Original -------------\n';
      merged += d.conflict.o.join('\n');
      merged += '\n------------- Ours -------------\n';
      merged += d.conflict.a.join('\n');
      merged += '\n------------- Theirs -------------\n';
      merged += d.conflict.b.join('\n');
      merged += '\n-------------\n';

      hasConflicts = true;
    }
  }

  return { merged, hasConflicts };
}

function merge(ancestors, ours, theirs, key, mergefunc) {
  // Create lookup tables for components based on name
  var a = {},
    o = {},
    t = {};
  for (var i in ancestors) a[key(ancestors[i])] = ancestors[i];

  for (var i in ours) o[key(ours[i])] = ours[i];

  for (var i in theirs) t[key(theirs[i])] = theirs[i];

  // Collect all names
  var names = {};
  for (var i in ours) names[key(ours[i])] = true;

  for (var i in theirs) names[key(theirs[i])] = true;

  // Loop over all component names
  for (var name in names) {
    // Components doesn't match, there is a change
    if (!_.isEqual(o[name], t[name])) {
      // Their have not changed, use ours
      if (_.isEqual(t[name], a[name])) {
        continue;
      }
      // Ours have not changed, use theirs
      else if (_.isEqual(o[name], a[name])) {
        o[name] = t[name];
      }
      // Both have change merge
      else {
        o[name] = mergefunc(a[name], o[name], t[name], name);
      }
    }
  }

  var res = [];
  for (var i in o) if (o[i]) res.push(o[i]);

  return res;
}

function mergeSingle(a, o, t, mergefunc) {
  if (!_.isEqual(o, t)) {
    if (_.isEqual(t, a)) {
      return o;
    }

    if (_.isEqual(o, a)) {
      return t;
    }

    return mergefunc(a, o, t);
  }
  return o;
}

// Merges JSON but does not handle conflicts, in that case "our" value will prevail
function mergeJSON(_ancestor_node, _our_node, _their_node) {
  var ancestor_node = _ancestor_node || {};
  var our_node = _our_node || {};
  var their_node = _their_node || {};

  var keys = {};
  for (var key in our_node) keys[key] = true;
  for (var key in their_node) keys[key] = true;

  //Go through each key...
  for (var key in keys) {
    //Get the values at that key for the three objects
    var ancestor_value = ancestor_node[key];
    var our_value = our_node[key];
    var their_value = their_node[key];

    //If there's a discrepency...
    if (our_value != their_value)
      if (_.isEqual(their_value, ancestor_value))
        //if theirs matches the ancestor, go with ours
        //no action is needed in this case
        continue;
      //if ours matches the ancestor, go with theirs
      else if (_.isEqual(our_value, ancestor_value))
        //We write the value to our_node since we're going to overwrite
        //our version with the merged version
        our_node[key] = their_value;
      //if both ours and theirs are objects, recurse into them
      else if (our_value && their_value && typeof our_value === 'object' && typeof their_value === 'object')
        mergeJSON(ancestor_value, our_value, their_value);
  }
}

// Merge connections in a component
function mergeConnections(ancestors, ours, theirs) {
  function key(c) {
    return c.fromId + ':' + c.fromProperty + '-' + c.toId + ':' + c.toProperty;
  }

  function mergeFunc(a, o, t) {
    return o;
  }

  return merge(ancestors, ours, theirs, key, mergeFunc);
}

// Merge node
function _mergeParameters(a, o, t, mergeFunc) {
  var names = {};
  for (var i in o) names[i] = true;

  for (var i in t) names[i] = true;

  // Loop over all parameter names
  for (var name in names) {
    // Components doesn't match, there is a change
    if (!_.isEqual(o[name], t[name])) {
      // Their have not changed, use ours
      if (_.isEqual(t[name], a[name])) {
        continue;
      }
      // Ours have not changed, use theirs
      else if (_.isEqual(o[name], a[name])) {
        o[name] = t[name];
      }
      // Both have changed report conflict
      else {
        o[name] = mergeFunc(a[name], o[name], t[name], name);
      }
    }
  }

  return o;
}

function mergeNode(ancestors, ours, theirs) {
  if (ours === undefined) {
    // Ours have been deleted, see if they have any changes
    if (nodesSoftEqual(ancestors, theirs)) return undefined;
    // They don't have any changes worth keeping, remove it
    else return theirs; // Ours is deleted, but theirs have changes, use theirs
  }

  if (theirs === undefined) {
    // Theirs have been deleted, make sure we have changes other than (x,y) to keep our node
    if (nodesSoftEqual(ancestors, ours)) return undefined;
    // We are equal to ancestor, e.g. no change, let the node delete
    else return ours; // We have changes, keep our node
  }

  var conflicts = [];

  function isSourceCodePort(name) {
    if (
      ours.metadata?.merge?.soureCodePorts?.includes(name) ||
      theirs.metadata?.merge?.soureCodePorts?.includes(name)
    ) {
      return true;
    }

    return false;
  }

  // Merge parameters
  ours.parameters = _mergeParameters(
    ancestors ? ancestors.parameters : {},
    ours.parameters,
    theirs.parameters,
    (a, o, t, name) => {
      if (isSourceCodePort(name)) {
        if (!a) {
          console.warn('No ancestor when merging source code in node', ours.id);
          return o; //ours will overwrite their changes
        }

        // Attempt to merge source code
        const { merged, hasConflicts } = mergeSourceCode(a, o, t);
        o = merged;

        if (hasConflicts) {
          conflicts.push({
            type: 'sourceCode',
            name: name,
            oursDisplayName: '[Source code]',
            theirsDisplayName: '[Source code]',
            ours: o,
            theirs: t
          });
        }
      } else
        conflicts.push({
          type: 'parameter',
          name: name,
          ours: o,
          theirs: t
        });

      return o;
    }
  );

  // Any of the nodes have state paramters
  if (ours.stateParameters || theirs.stateParameters || (ancestors && ancestors.stateParameters)) {
    ours.stateParameters = _mergeParameters(
      ancestors && ancestors.stateParameters ? ancestors.stateParameters : {},
      ours.stateParameters || {},
      theirs.stateParameters || {},
      (a, o, t, state) => {
        return _mergeParameters(a || {}, o || {}, t || {}, (a, o, t, name) => {
          conflicts.push({
            type: 'stateParameter',
            state: state,
            name: name,
            ours: o,
            theirs: t
          });

          return o;
        });
      }
    );
  }

  // Merge any state transitions
  if (ours.stateTransitions || theirs.stateTransitions || (ancestors && ancestors.stateTransitions)) {
    ours.stateTransitions = _mergeParameters(
      ancestors && ancestors.stateTransitions ? ancestors.stateTransitions : {},
      ours.stateTransitions || {},
      theirs.stateTransitions || {},
      (a, o, t, state) => {
        return _mergeParameters(a || {}, o || {}, t || {}, (a, o, t, name) => {
          conflicts.push({
            type: 'stateTransition',
            state: state,
            name: name,
            ours: o,
            theirs: t
          });

          return o;
        });
      }
    );
  }

  // Merge default state transition
  if (
    ours.defaultStateTransitions ||
    theirs.defaultStateTransitions ||
    (ancestors && ancestors.defaultStateTransitions)
  ) {
    ours.defaultStateTransitions = _mergeParameters(
      ancestors && ancestors.defaultStateTransitions ? ancestors.defaultStateTransitions : {},
      ours.defaultStateTransitions || {},
      theirs.defaultStateTransitions || {},
      (a, o, t, state) => {
        conflicts.push({
          type: 'defaultStateTransition',
          state: state,
          ours: o,
          theirs: t
        });
        return o;
      }
    );
  }

  // Merge variant
  if (ours.variant || theirs.variant || (ancestors && ancestors.variant)) {
    ours.variant = mergeSingle(ancestors ? ancestors.variant : undefined, ours.variant, theirs.variant, (a, o, t) => {
      conflicts.push({
        type: 'variant',
        ours: o,
        theirs: t
      });
      return o;
    });
  }

  // Merge type
  ours.type = mergeSingle(ancestors ? ancestors.type : undefined, ours.type, theirs.type, (a, o, t) => {
    conflicts.push({
      type: 'typename',
      ours: ours.type,
      theirs: theirs.type
    });
    return o;
  });

  // Finally we must merge ports
  function key(o) {
    return o.name;
  }

  // Merge ports by using ours
  function mergePort(a, o, t) {
    return o;
  }

  ours.ports = merge(ancestors ? ancestors.ports : [], ours.ports, theirs.ports, key, mergePort);

  if (conflicts.length > 0) ours.conflicts = conflicts;
  else delete ours.conflicts;

  return ours;
}

// Merge nodes
function mergeNodes(ancestors, ours, theirs) {
  // Flatten node heirarchy (store parent reference)
  function collectNodes(nodes, parent, list) {
    if (!nodes) return;
    if (!list) list = [];

    for (var i = 0; i < nodes.length; i++) {
      var n = nodes[i];
      if (parent) n._parent = parent.id;
      n._sort = i;

      list.push(n);
      collectNodes(n.children, n, list);
      delete n.children; // Remove children, creating a flattened list
    }
    return list;
  }
  var ancestorsFlattened = collectNodes(ancestors);
  var oursFlattened = collectNodes(ours);
  var theirsFlattened = collectNodes(theirs);

  // Merge all nodes
  function key(o) {
    return o.id;
  }

  var res = merge(ancestorsFlattened, oursFlattened, theirsFlattened, key, mergeNode);

  // Recreate the hierarchy
  function collectChildren(node) {
    var id = node.id;
    var children = [];
    for (var i in res) {
      if (res[i]._parent === id) children.push(res[i]);
    }
    children.sort(function (a, b) {
      return a._sort > b._sort ? 1 : -1;
    });
    return children.length > 0 ? children : undefined;
  }

  for (var i in res) {
    var n = res[i];
    n.children = collectChildren(n);
  }

  // Delete temporary keys and store all roots
  var roots = [];
  for (var i in res) {
    if (!res[i]._parent) roots.push(res[i]);

    delete res[i]._parent;
    delete res[i]._sort;
  }

  return roots;
}

// Compare comments by only looking at the text
function _commentSoftEqual(a, b) {
  return a.text === b.text;
}

function mergeComment(ancestors, ours, theirs) {
  if (ours === undefined) {
    // Ours have been deleted, see if they have any changes
    if (_commentSoftEqual(ancestors, theirs)) return undefined;
    // They don't have any changes worth keeping, remove it
    else return theirs; // Ours is deleted, but theirs have changes, use theirs
  }

  if (theirs === undefined) {
    // Theirs have been deleted, see if we have any interesting changes
    if (_commentSoftEqual(ancestors, ours)) {
      return undefined; // We are equal to ancestor, e.g. no change, so delete the comment
    } else {
      return ours; // We have changes, keep our comment
    }
  }

  //is there a difference between ours and theirs?
  if (!_commentSoftEqual(ours, theirs)) {
    if (_commentSoftEqual(ours, ancestors)) {
      //Our hasn't changed, use theirs
      return theirs;
    } else if (_commentSoftEqual(theirs, ancestors)) {
      //Their hasn't changed, so use ours
      return ours;
    } else {
      // Both have changed. Just use ours.
      return ours;
    }
  }

  return ours;
}

function mergeComments(ancestors, ours, theirs) {
  function key(o) {
    return o.id;
  }

  return merge(ancestors, ours, theirs, key, mergeComment);
}

// Merge a component, returns a merged component
function mergeComponent(ancestors, ours, theirs) {
  if (ours === undefined) {
    // Ours have been deleted, see if they have any changes
    if (_.isEqual(ancestors, theirs)) return undefined;
    // They don't have any changes, remove it
    else return theirs; // Ours is deleted, but theirs have changes, use theirs
  }

  if (theirs === undefined) {
    // Theirs have been deleted, do  we have changes ?
    if (_.isEqual(ancestors, ours)) return undefined;
    // We are equal to ancestor, e.g. no change, let the component delete
    else return ours; // We have changes, keep our node
  }

  // Merge connections
  ours.graph.connections = mergeConnections(
    ancestors ? ancestors.graph.connections : [],
    ours.graph.connections,
    theirs.graph.connections
  );

  // Merge nodes
  ours.graph.roots = mergeNodes(ancestors ? ancestors.graph.roots : [], ours.graph.roots, theirs.graph.roots);

  // Merge comments
  ours.graph.comments = mergeComments(
    ancestors ? ancestors.graph.comments : [],
    ours.graph.comments,
    theirs.graph.comments
  );

  if (ours.name !== theirs.name) {
    // Check if the component have been renamed
    // TODO: Conflic if both changes
    if (ancestors && ancestors.name === ours.name) ours.name = theirs.name;
  }

  // Merge metadata
  mergeJSON(ancestors === undefined ? {} : ancestors.metadata, ours.metadata, theirs.metadata);

  return ours;
}

// Merge an array of components, returns a new merged array
function mergeComponents(ancestors, ours, theirs) {
  function key(o) {
    return o.id || o.name;
  }

  return merge(ancestors, ours, theirs, key, mergeComponent);
}

// Merge variants
function mergeVariant(ancestors, ours, theirs) {
  if (ours === undefined) {
    // Ours have been deleted, see if they have any changes
    if (_.isEqual(ancestors, theirs)) return undefined;
    // They don't have any changes worth keeping, remove it
    else return theirs; // Ours is deleted, but theirs have changes, use theirs
  }

  if (theirs === undefined) {
    // Theirs have been deleted, make sure we have changes other than (x,y) to keep our node
    if (_.isEqual(ancestors, ours)) return undefined;
    // We are equal to ancestor, e.g. no change, let the node delete
    else return ours; // We have changes, keep our node
  }

  var conflicts = [];

  // Merge parameters
  ours.parameters = _mergeParameters(
    ancestors ? ancestors.parameters : {},
    ours.parameters,
    theirs.parameters,
    (a, o, t, name) => {
      conflicts.push({
        type: 'parameter',
        name: name,
        ours: o,
        theirs: t
      });

      return o;
    }
  );

  // Any of the nodes have state paramters
  if (ours.stateParameters || theirs.stateParameters || (ancestors && ancestors.stateParameters)) {
    ours.stateParameters = _mergeParameters(
      ancestors && ancestors.stateParameters ? ancestors.stateParameters : {},
      ours.stateParameters || {},
      theirs.stateParameters || {},
      (a, o, t, state) => {
        return _mergeParameters(a || {}, o || {}, t || {}, (a, o, t, name) => {
          conflicts.push({
            type: 'stateParameter',
            state: state,
            name: name,
            ours: o,
            theirs: t
          });

          return o;
        });
      }
    );
  }

  // Merge any state transitions
  if (ours.stateTransitions || theirs.stateTransitions || (ancestors && ancestors.stateTransitions)) {
    ours.stateTransitions = _mergeParameters(
      ancestors && ancestors.stateTransitions ? ancestors.stateTransitions : {},
      ours.stateTransitions || {},
      theirs.stateTransitions || {},
      (a, o, t, state) => {
        return _mergeParameters(a || {}, o || {}, t || {}, (a, o, t, name) => {
          conflicts.push({
            type: 'stateTransition',
            state: state,
            name: name,
            ours: o,
            theirs: t
          });

          return o;
        });
      }
    );
  }

  // Merge default state transition
  if (
    ours.defaultStateTransitions ||
    theirs.defaultStateTransitions ||
    (ancestors && ancestors.defaultStateTransitions)
  ) {
    ours.defaultStateTransitions = _mergeParameters(
      ancestors && ancestors.defaultStateTransitions ? ancestors.defaultStateTransitions : {},
      ours.defaultStateTransitions || {},
      theirs.defaultStateTransitions || {},
      (a, o, t, state) => {
        conflicts.push({
          type: 'defaultStateTransition',
          state: state,
          ours: o,
          theirs: t
        });
        return o;
      }
    );
  }

  if (conflicts.length > 0) ours.conflicts = conflicts;
  else delete ours.conflicts;

  return ours;
}

// Merge an array of variants, returns a new merged array
function mergeVariants(ancestors, ours, theirs) {
  function key(o) {
    return o.typename + '/' + o.name;
  }

  return merge(ancestors, ours, theirs, key, mergeVariant);
}

function mergeProject(ancestors, ours, theirs) {
  // Detach components
  var ancestorComponents = ancestors.components;
  ancestors.components = undefined;

  var ourComponents = ours.components;
  ours.components = undefined;

  var theirComponents = theirs.components;
  theirs.components = undefined;

  // Detach variants
  var ancestorVariants = ancestors.variants;
  ancestors.variants = undefined;

  var ourVariants = ours.variants;
  ours.variants = undefined;

  var theirVariants = theirs.variants;
  theirs.variants = undefined;

  // Merge project without components
  mergeJSON(ancestors, ours, theirs);

  // Merge components
  ours.components = mergeComponents(ancestorComponents, ourComponents, theirComponents);

  // Merge variants
  ours.variants = mergeVariants(ancestorVariants, ourVariants, theirVariants);
  if (ours.variants !== undefined && ours.variants.length === 0) delete ours.variants;

  // Validate project
  const validator = new ProjectValidator();
  validator.validate(ours);

  if (validator.hasErrors()) {
    validator.fix();
  }

  return ours;
}

module.exports = {
  mergeProject
};


/***/ }),

/***/ 78285:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   R: () => (/* binding */ getCommitFiles)
/* harmony export */ });
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85869);
/* harmony import */ var _models_status__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(45226);


/**
 *
 * $ git show --format="" --name-status -z --no-color c0bfb14
 *
 * @param repositoryDir
 * @param commitish
 */
async function getCommitFiles(repositoryDir, commitish) {
    const args = [
        "show",
        "--format=oneline",
        "--name-status",
        "-z",
        "--no-color",
        commitish,
    ];
    const { output } = await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)(args, repositoryDir, "getCommitFiles");
    const segments = output
        .toString()
        .split("\u0000")
        .filter((s) => s.length > 0);
    const result = [];
    // Possible status letters are:
    //
    // A: addition of a file
    // C: copy of a file into a new one
    // D: deletion of a file
    // M: modification of the contents or mode of a file
    // R: renaming of a file
    // T: change in the type of the file (regular file, symbolic link or submodule)
    // U: file is unmerged (you must complete the merge before it can be committed)
    // X: "unknown" change type (most probably a bug, please report it)
    //
    // TODO: Add support for C, T, U codes
    //
    for (let index = 1; index < segments.length;) {
        const modifier = segments[index];
        if (/^[a-z0-9]{40}/.test(modifier)) {
            index += 1;
        }
        else {
            const filePath = segments[index + 1];
            if (modifier.startsWith("A")) {
                result.push(new _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileChange */ .HE(filePath, {
                    kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.New,
                }));
            }
            else if (modifier.startsWith("M")) {
                result.push(new _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileChange */ .HE(filePath, {
                    kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.Modified,
                }));
            }
            else if (modifier.startsWith("D")) {
                result.push(new _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileChange */ .HE(filePath, {
                    kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.Deleted,
                }));
            }
            else if (modifier.startsWith("R")) {
                const newFilePath = segments[index + 1];
                result.push(new _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileChange */ .HE(newFilePath, {
                    kind: _models_status__WEBPACK_IMPORTED_MODULE_1__/* .FileStatusKind */ .Jb.Renamed,
                    oldPath: filePath,
                }));
                index += 1;
            }
            index += 2;
        }
    }
    //Rev ranges might have duplicates, so naively just dedupe based on the path
    return [...new Map(result.map((r) => [r.path, r])).values()];
}


/***/ }),

/***/ 78318:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ActionButton-module__Root--R8u31{width:100%;padding:0;margin:0;height:64px;flex-grow:0;flex-shrink:0;display:flex;align-items:center;justify-content:space-between;border:0;background-color:var(--theme-color-bg-2);text-align:left;cursor:pointer;user-select:none;font-family:var(--font-family)}.ActionButton-module__Root--R8u31:not(.ActionButton-module__has-no-bottom-border--MRnZM){border-bottom:1px solid var(--theme-color-bg-1)}.ActionButton-module__Root--R8u31 .ActionButton-module__Label--iUkzB{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;color:var(--theme-color-fg-default)}.ActionButton-module__Root--R8u31 small{color:var(--theme-color-fg-default-shy)}.ActionButton-module__Root--R8u31.ActionButton-module__is-inactive--ZO2PG{cursor:default}.ActionButton-module__Root--R8u31.ActionButton-module__has-top-divider--mLE32{border-top:1px solid var(--theme-color-bg-1)}.ActionButton-module__Root--R8u31:hover:not(.ActionButton-module__Root--R8u31.ActionButton-module__is-inactive--ZO2PG){background-color:var(--theme-color-bg-3)}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-background--nCOcX{padding-right:18px;cursor:progress;background-color:var(--theme-color-bg-2)}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-background--nCOcX:hover{background-color:var(--theme-color-bg-2)}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-background-action--rQeuJ{padding-right:18px;cursor:progress;background-color:var(--theme-color-bg-3)}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-background-action--rQeuJ:hover{background-color:var(--theme-color-bg-4) !important}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-user-action--uWLT6{background-color:var(--theme-color-primary)}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-user-action--uWLT6:hover{background-color:var(--theme-color-primary-highlight) !important}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-user-action--uWLT6 path{fill:var(--theme-color-on-primary)}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-user-action--uWLT6 p,.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-user-action--uWLT6 small{color:var(--theme-color-on-primary)}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-downloading--c0um_:hover{background-color:var(--theme-color-secondary-highlight)}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-proud--HsOXV{background-color:var(--theme-color-bg-3)}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-on-bg-2--Re9CP{background-color:var(--theme-color-bg-3)}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-on-bg-2--Re9CP:hover{background-color:var(--theme-color-bg-4) !important}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-secondary--d6txf{background-color:var(--theme-color-secondary-dim)}.ActionButton-module__Root--R8u31.ActionButton-module__is-variant-secondary--d6txf:hover{background-color:var(--theme-color-secondary) !important}.ActionButton-module__Container--XnBBA{width:100%;display:flex;align-items:center}.ActionButton-module__Icon--dufet{display:flex;justify-content:center;padding:16px}.ActionButton-module__Icon--dufet.ActionButton-module__is-disabled--TEaHd{opacity:.5}.ActionButton-module__Text--GegOT{flex:1;display:flex;flex-direction:column;align-items:flex-start;padding-right:8px}.ActionButton-module__Text--GegOT p{margin:0;padding:0;font-weight:var(--font-weight-semibold);font-size:12px;line-height:14px}.ActionButton-module__Text--GegOT small{margin:0;padding:0;font-weight:var(--font-weight-regular);font-size:12px;line-height:14px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/ActionButton/ActionButton.module.scss"],"names":[],"mappings":"AAAA,kCACE,UAAA,CACA,SAAA,CACA,QAAA,CACA,WAAA,CACA,WAAA,CACA,aAAA,CACA,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,QAAA,CACA,wCAAA,CACA,eAAA,CAEA,cAAA,CACA,gBAAA,CAEA,8BAAA,CAEA,yFACE,+CAAA,CAGF,qEACE,mBAAA,CACA,oBAAA,CACA,2BAAA,CACA,eAAA,CACA,mCAAA,CAGF,wCACE,uCAAA,CAGF,0EACE,cAAA,CAGF,8EACE,4CAAA,CAGF,uHACE,wCAAA,CAGF,oFACE,kBAAA,CACA,eAAA,CACA,wCAAA,CAEA,0FACE,wCAAA,CAIJ,2FACE,kBAAA,CACA,eAAA,CACA,wCAAA,CAEA,iGACE,mDAAA,CAIJ,qFACE,2CAAA,CAEA,2FACE,gEAAA,CAGF,0FACE,kCAAA,CAGF,kLAEE,mCAAA,CAKF,2FACE,uDAAA,CAIJ,+EACE,wCAAA,CAGF,iFACE,wCAAA,CAEA,uFACE,mDAAA,CAIJ,mFACE,iDAAA,CAEA,yFACE,wDAAA,CAKN,uCACE,UAAA,CACA,YAAA,CACA,kBAAA,CAGF,kCACE,YAAA,CACA,sBAAA,CAEA,YAAA,CAEA,0EACE,UAAA,CAIJ,kCACE,MAAA,CACA,YAAA,CACA,qBAAA,CACA,sBAAA,CACA,iBAAA,CAEA,oCACE,QAAA,CACA,SAAA,CACA,uCAAA,CACA,cAAA,CACA,gBAAA,CAGF,wCACE,QAAA,CACA,SAAA,CACA,sCAAA,CACA,cAAA,CACA,gBAAA","sourcesContent":[".Root {\n  width: 100%;\n  padding: 0;\n  margin: 0;\n  height: 64px;\n  flex-grow: 0;\n  flex-shrink: 0;\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  border: 0;\n  background-color: var(--theme-color-bg-2);\n  text-align: left;\n\n  cursor: pointer;\n  user-select: none;\n\n  font-family: var(--font-family);\n\n  &:not(.has-no-bottom-border) {\n    border-bottom: 1px solid var(--theme-color-bg-1);\n  }\n\n  .Label {\n    display: -webkit-box;\n    -webkit-line-clamp: 3;\n    -webkit-box-orient: vertical;\n    overflow: hidden;\n    color: var(--theme-color-fg-default);\n  }\n\n  small {\n    color: var(--theme-color-fg-default-shy);\n  }\n\n  &.is-inactive {\n    cursor: default;\n  }\n\n  &.has-top-divider {\n    border-top: 1px solid var(--theme-color-bg-1);\n  }\n\n  &:hover:not(&.is-inactive) {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.is-variant-background {\n    padding-right: 18px;\n    cursor: progress;\n    background-color: var(--theme-color-bg-2);\n\n    &:hover {\n      background-color: var(--theme-color-bg-2);\n    }\n  }\n\n  &.is-variant-background-action {\n    padding-right: 18px;\n    cursor: progress;\n    background-color: var(--theme-color-bg-3);\n\n    &:hover {\n      background-color: var(--theme-color-bg-4) !important;\n    }\n  }\n\n  &.is-variant-user-action {\n    background-color: var(--theme-color-primary);\n\n    &:hover {\n      background-color: var(--theme-color-primary-highlight) !important;\n    }\n\n    path {\n      fill: var(--theme-color-on-primary);\n    }\n\n    p,\n    small {\n      color: var(--theme-color-on-primary);\n    }\n  }\n\n  &.is-variant-downloading {\n    &:hover {\n      background-color: var(--theme-color-secondary-highlight);\n    }\n  }\n\n  &.is-variant-proud {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.is-variant-on-bg-2 {\n    background-color: var(--theme-color-bg-3);\n\n    &:hover {\n      background-color: var(--theme-color-bg-4) !important;\n    }\n  }\n\n  &.is-variant-secondary {\n    background-color: var(--theme-color-secondary-dim);\n\n    &:hover {\n      background-color: var(--theme-color-secondary) !important;\n    }\n  }\n}\n\n.Container {\n  width: 100%;\n  display: flex;\n  align-items: center;\n}\n\n.Icon {\n  display: flex;\n  justify-content: center;\n\n  padding: 16px;\n\n  &.is-disabled {\n    opacity: 0.5;\n  }\n}\n\n.Text {\n  flex: 1;\n  display: flex;\n  flex-direction: column;\n  align-items: flex-start;\n  padding-right: 8px;\n\n  p {\n    margin: 0;\n    padding: 0;\n    font-weight: var(--font-weight-semibold);\n    font-size: 12px;\n    line-height: 14px;\n  }\n\n  small {\n    margin: 0;\n    padding: 0;\n    font-weight: var(--font-weight-regular);\n    font-size: 12px;\n    line-height: 14px;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ActionButton-module__Root--R8u31`,
	"has-no-bottom-border": `ActionButton-module__has-no-bottom-border--MRnZM`,
	"Label": `ActionButton-module__Label--iUkzB`,
	"is-inactive": `ActionButton-module__is-inactive--ZO2PG`,
	"has-top-divider": `ActionButton-module__has-top-divider--mLE32`,
	"is-variant-background": `ActionButton-module__is-variant-background--nCOcX`,
	"is-variant-background-action": `ActionButton-module__is-variant-background-action--rQeuJ`,
	"is-variant-user-action": `ActionButton-module__is-variant-user-action--uWLT6`,
	"is-variant-downloading": `ActionButton-module__is-variant-downloading--c0um_`,
	"is-variant-proud": `ActionButton-module__is-variant-proud--HsOXV`,
	"is-variant-on-bg-2": `ActionButton-module__is-variant-on-bg-2--Re9CP`,
	"is-variant-secondary": `ActionButton-module__is-variant-secondary--d6txf`,
	"Container": `ActionButton-module__Container--XnBBA`,
	"Icon": `ActionButton-module__Icon--dufet`,
	"is-disabled": `ActionButton-module__is-disabled--TEaHd`,
	"Text": `ActionButton-module__Text--GegOT`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 78447:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_iconpicker_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(13777);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_iconpicker_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_iconpicker_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_iconpicker_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_iconpicker_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 78879:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.LineagePath-module__LineagePath--IN877{display:flex;flex-direction:column;gap:var(--theme-spacing-1)}.LineagePath-module__Step--CTmI0{display:flex;flex-direction:column;gap:var(--theme-spacing-1)}.LineagePath-module__Step-node--Cr8AH{display:flex;align-items:center;gap:var(--theme-spacing-2);padding:var(--theme-spacing-2);background-color:var(--theme-color-bg-2);border-radius:var(--theme-border-radius-1);cursor:pointer;transition:background-color .15s}.LineagePath-module__Step-node--Cr8AH:hover{background-color:var(--theme-color-bg-3)}.LineagePath-module__Step-icon--rqXwa{font-size:14px}.LineagePath-module__Step-label--KAaKF{font-size:14px;font-weight:500}.LineagePath-module__Step-port--ZZAlh{font-size:12px;color:var(--theme-color-fg-default-shy);font-family:monospace}.LineagePath-module__Step-transformation--ITcPg{padding:var(--theme-spacing-1) var(--theme-spacing-2);margin-left:var(--theme-spacing-4);font-size:12px;color:var(--theme-color-fg-default-shy);background-color:var(--theme-color-bg-3);border-radius:var(--theme-border-radius-1);font-style:italic}.LineagePath-module__Step-badge--rbdL8{display:inline-block;padding:2px var(--theme-spacing-2);margin-left:var(--theme-spacing-4);font-size:10px;font-weight:600;background-color:var(--theme-color-primary);color:var(--theme-color-bg-1);border-radius:var(--theme-border-radius-1);text-transform:uppercase}.LineagePath-module__Step-arrow--rXcIe{text-align:center;font-size:16px;color:var(--theme-color-fg-default-shy);opacity:.5}.LineagePath-module__Crossings--S6L6A{margin-top:var(--theme-spacing-2);padding:var(--theme-spacing-2);background-color:var(--theme-color-bg-3);border-radius:var(--theme-border-radius-1);border-left:3px solid var(--theme-color-primary)}.LineagePath-module__Crossings-label--DOgvE{font-size:12px;color:var(--theme-color-fg-default-shy);font-weight:500}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/DataLineagePanel/components/LineagePath.module.scss"],"names":[],"mappings":"AAEA,wCACE,YAAA,CACA,qBAAA,CACA,0BAAA,CAGF,iCACE,YAAA,CACA,qBAAA,CACA,0BAAA,CAEA,sCACE,YAAA,CACA,kBAAA,CACA,0BAAA,CACA,8BAAA,CACA,wCAAA,CACA,0CAAA,CACA,cAAA,CACA,gCAAA,CAEA,4CACE,wCAAA,CAIJ,sCACE,cAAA,CAGF,uCACE,cAAA,CACA,eAAA,CAGF,sCACE,cAAA,CACA,uCAAA,CACA,qBAAA,CAGF,gDACE,qDAAA,CACA,kCAAA,CACA,cAAA,CACA,uCAAA,CACA,wCAAA,CACA,0CAAA,CACA,iBAAA,CAGF,uCACE,oBAAA,CACA,kCAAA,CACA,kCAAA,CACA,cAAA,CACA,eAAA,CACA,2CAAA,CACA,6BAAA,CACA,0CAAA,CACA,wBAAA,CAGF,uCACE,iBAAA,CACA,cAAA,CACA,uCAAA,CACA,UAAA,CAIJ,sCACE,iCAAA,CACA,8BAAA,CACA,wCAAA,CACA,0CAAA,CACA,gDAAA,CAEA,4CACE,cAAA,CACA,uCAAA,CACA,eAAA","sourcesContent":["// LineagePath Component Styles\n\n.LineagePath {\n  display: flex;\n  flex-direction: column;\n  gap: var(--theme-spacing-1);\n}\n\n.Step {\n  display: flex;\n  flex-direction: column;\n  gap: var(--theme-spacing-1);\n\n  &-node {\n    display: flex;\n    align-items: center;\n    gap: var(--theme-spacing-2);\n    padding: var(--theme-spacing-2);\n    background-color: var(--theme-color-bg-2);\n    border-radius: var(--theme-border-radius-1);\n    cursor: pointer;\n    transition: background-color 0.15s;\n\n    &:hover {\n      background-color: var(--theme-color-bg-3);\n    }\n  }\n\n  &-icon {\n    font-size: 14px;\n  }\n\n  &-label {\n    font-size: 14px;\n    font-weight: 500;\n  }\n\n  &-port {\n    font-size: 12px;\n    color: var(--theme-color-fg-default-shy);\n    font-family: monospace;\n  }\n\n  &-transformation {\n    padding: var(--theme-spacing-1) var(--theme-spacing-2);\n    margin-left: var(--theme-spacing-4);\n    font-size: 12px;\n    color: var(--theme-color-fg-default-shy);\n    background-color: var(--theme-color-bg-3);\n    border-radius: var(--theme-border-radius-1);\n    font-style: italic;\n  }\n\n  &-badge {\n    display: inline-block;\n    padding: 2px var(--theme-spacing-2);\n    margin-left: var(--theme-spacing-4);\n    font-size: 10px;\n    font-weight: 600;\n    background-color: var(--theme-color-primary);\n    color: var(--theme-color-bg-1);\n    border-radius: var(--theme-border-radius-1);\n    text-transform: uppercase;\n  }\n\n  &-arrow {\n    text-align: center;\n    font-size: 16px;\n    color: var(--theme-color-fg-default-shy);\n    opacity: 0.5;\n  }\n}\n\n.Crossings {\n  margin-top: var(--theme-spacing-2);\n  padding: var(--theme-spacing-2);\n  background-color: var(--theme-color-bg-3);\n  border-radius: var(--theme-border-radius-1);\n  border-left: 3px solid var(--theme-color-primary);\n\n  &-label {\n    font-size: 12px;\n    color: var(--theme-color-fg-default-shy);\n    font-weight: 500;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"LineagePath": `LineagePath-module__LineagePath--IN877`,
	"Step": `LineagePath-module__Step--CTmI0`,
	"Step-node": `LineagePath-module__Step-node--Cr8AH`,
	"Step-icon": `LineagePath-module__Step-icon--rqXwa`,
	"Step-label": `LineagePath-module__Step-label--KAaKF`,
	"Step-port": `LineagePath-module__Step-port--ZZAlh`,
	"Step-transformation": `LineagePath-module__Step-transformation--ITcPg`,
	"Step-badge": `LineagePath-module__Step-badge--rbdL8`,
	"Step-arrow": `LineagePath-module__Step-arrow--rXcIe`,
	"Crossings": `LineagePath-module__Crossings--S6L6A`,
	"Crossings-label": `LineagePath-module__Crossings-label--DOgvE`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 78917:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PropertyPanelCheckbox-module__Root--G9p_F{display:flex;position:relative}.PropertyPanelCheckbox-module__Checkbox--Z8XCz{position:absolute;width:28px;height:28px;opacity:0;cursor:pointer}.PropertyPanelCheckbox-module__FauxCheckbox--XkFxE{display:flex;justify-content:center;align-items:center;width:28px;height:28px;background-color:var(--theme-color-bg-3);cursor:pointer}.PropertyPanelCheckbox-module__FauxCheckbox--XkFxE svg{pointer-events:none}.PropertyPanelCheckbox-module__FauxCheckbox--XkFxE svg path{stroke:var(--theme-color-fg-default)}.PropertyPanelCheckbox-module__FauxCheckbox--XkFxE.PropertyPanelCheckbox-module__is-connected--EW2yk{outline:1px solid var(--theme-color-primary-dim)}.PropertyPanelCheckbox-module__FauxCheckbox--XkFxE.PropertyPanelCheckbox-module__is-changed--Myhg9 svg path,.PropertyPanelCheckbox-module__FauxCheckbox--XkFxE:hover svg path{stroke:var(--theme-color-fg-highlight)}.PropertyPanelCheckbox-module__Checkbox--Z8XCz:focus+.PropertyPanelCheckbox-module__FauxCheckbox--XkFxE{background-color:var(--theme-color-bg-1)}.PropertyPanelCheckbox-module__Checkbox--Z8XCz:focus+.PropertyPanelCheckbox-module__FauxCheckbox--XkFxE svg path{stroke:var(--theme-color-fg-highlight)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/property-panel/PropertyPanelCheckbox/PropertyPanelCheckbox.module.scss","webpack://./../noodl-core-ui/src/styles/scss-variables/length.scss"],"names":[],"mappings":"AAEA,2CACE,YAAA,CACA,iBAAA,CAGF,+CACE,iBAAA,CACA,UCR0B,CDS1B,WCT0B,CDU1B,SAAA,CACA,cAAA,CAGF,mDACE,YAAA,CACA,sBAAA,CACA,kBAAA,CACA,UClB0B,CDmB1B,WCnB0B,CDoB1B,wCAAA,CACA,cAAA,CAEA,uDACE,mBAAA,CAEA,4DACE,oCAAA,CAIJ,qGACE,gDAAA,CAKA,8KACE,sCAAA,CAIJ,wGACE,wCAAA,CAEA,iHACE,sCAAA","sourcesContent":["@use '../../../styles/scss-variables/length.scss';\n\n.Root {\n  display: flex;\n  position: relative;\n}\n\n.Checkbox {\n  position: absolute;\n  width: length.$property-panel-input-size;\n  height: length.$property-panel-input-size;\n  opacity: 0;\n  cursor: pointer;\n}\n\n.FauxCheckbox {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  width: length.$property-panel-input-size;\n  height: length.$property-panel-input-size;\n  background-color: var(--theme-color-bg-3);\n  cursor: pointer;\n\n  svg {\n    pointer-events: none;\n\n    path {\n      stroke: var(--theme-color-fg-default);\n    }\n  }\n\n  &.is-connected {\n    outline: 1px solid var(--theme-color-primary-dim);\n  }\n\n  &.is-changed,\n  &:hover {\n    svg path {\n      stroke: var(--theme-color-fg-highlight);\n    }\n  }\n\n  .Checkbox:focus + & {\n    background-color: var(--theme-color-bg-1);\n\n    svg path {\n      stroke: var(--theme-color-fg-highlight);\n    }\n  }\n}\n","$property-panel-input-padding: 6px 8px 7px;\r\n$property-panel-input-size: 28px;\r\n$property-panel-small-xy-padding: 4px;\r\n\r\n$global-input-size: 36px;\r\n$global-input-size-small: 28px;\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PropertyPanelCheckbox-module__Root--G9p_F`,
	"Checkbox": `PropertyPanelCheckbox-module__Checkbox--Z8XCz`,
	"FauxCheckbox": `PropertyPanelCheckbox-module__FauxCheckbox--XkFxE`,
	"is-connected": `PropertyPanelCheckbox-module__is-connected--EW2yk`,
	"is-changed": `PropertyPanelCheckbox-module__is-changed--Myhg9`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 79015:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  hE: () => (/* binding */ Title),
  uM: () => (/* binding */ TitleSize),
  Is: () => (/* binding */ TitleVariant)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/typography/Title/Title.module.scss
var Title_module = __webpack_require__(43948);
;// ../noodl-core-ui/src/components/typography/Title/Title.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(Title_module/* default */.A, options);




       /* harmony default export */ const Title_Title_module = (Title_module/* default */.A && Title_module/* default */.A.locals ? Title_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/typography/Title/Title.tsx



var TitleSize;
(function (TitleSize) {
    TitleSize["Default"] = "default";
    TitleSize["Large"] = "large";
    TitleSize["Medium"] = "medium";
    TitleSize["Small"] = "small";
})(TitleSize || (TitleSize = {}));
var TitleVariant;
(function (TitleVariant) {
    TitleVariant["Default"] = "default";
    TitleVariant["Highlighted"] = "highlighted";
    TitleVariant["DefaultContrast"] = "default-contrast";
    TitleVariant["Danger"] = "danger";
    TitleVariant["Notice"] = "notice";
    TitleVariant["Success"] = "success";
})(TitleVariant || (TitleVariant = {}));
function Title({ children, size = TitleSize.Default, variant = TitleVariant.Default, hasBottomSpacing, isCentered }) {
    return (external_react_default().createElement("h2", { className: external_classnames_default()([
            Title_Title_module['Root'],
            Title_Title_module[`is-size-${size}`],
            Title_Title_module[`is-variant-${variant}`],
            isCentered && Title_Title_module['is-centered'],
            hasBottomSpacing && Title_Title_module['has-bottom-spacing']
        ]) }, children));
}


/***/ }),

/***/ 79114:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_nodegrapheditor_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(27500);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_nodegrapheditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_nodegrapheditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_nodegrapheditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_nodegrapheditor_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 79162:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .rename-box {
	z-index: 100;
	color: inherit;
}

.monaco-editor .rename-box.preview {
	padding: 3px 3px 0 3px;
}

.monaco-editor .rename-box .rename-input {
	padding: 3px;
	width: calc(100% - 6px);
}

.monaco-editor .rename-box .rename-label {
	display: none;
	opacity: .8;
}

.monaco-editor .rename-box.preview .rename-label {
	display: inherit;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/rename/browser/renameInputField.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,YAAY;CACZ,cAAc;AACf;;AAEA;CACC,sBAAsB;AACvB;;AAEA;CACC,YAAY;CACZ,uBAAuB;AACxB;;AAEA;CACC,aAAa;CACb,WAAW;AACZ;;AAEA;CACC,gBAAgB;AACjB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .rename-box {\n\tz-index: 100;\n\tcolor: inherit;\n}\n\n.monaco-editor .rename-box.preview {\n\tpadding: 3px 3px 0 3px;\n}\n\n.monaco-editor .rename-box .rename-input {\n\tpadding: 3px;\n\twidth: calc(100% - 6px);\n}\n\n.monaco-editor .rename-box .rename-label {\n\tdisplay: none;\n\topacity: .8;\n}\n\n.monaco-editor .rename-box.preview .rename-label {\n\tdisplay: inherit;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 79210:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PathSummary-module__PathSummary--XkBGp{padding:var(--theme-spacing-2);background-color:var(--theme-color-bg-2);border-radius:var(--theme-border-radius-1);margin-bottom:var(--theme-spacing-3);border-left:3px solid var(--theme-color-primary)}.PathSummary-module__PathSummary-title--kbH_b{font-size:12px;font-weight:600;text-transform:uppercase;color:var(--theme-color-fg-default-shy);margin-bottom:var(--theme-spacing-2)}.PathSummary-module__PathSummary-content--zGh7J{display:flex;flex-direction:column;gap:var(--theme-spacing-1);font-size:13px}.PathSummary-module__Path--KzY_1{display:flex;align-items:center;gap:var(--theme-spacing-2);flex-wrap:wrap}.PathSummary-module__Path-segment--SJAnu{color:var(--theme-color-fg-default);font-family:monospace;font-size:12px}.PathSummary-module__Path-arrow--lGMtD{color:var(--theme-color-fg-default-shy);font-size:14px}.PathSummary-module__Path-selected--ACyJ7{padding:var(--theme-spacing-1) var(--theme-spacing-2);background-color:var(--theme-color-primary);color:var(--theme-color-bg-1);border-radius:var(--theme-border-radius-1);font-weight:600}.PathSummary-module__Path-branch--145Gk{font-size:11px;color:var(--theme-color-fg-default-shy);font-style:italic;margin-left:var(--theme-spacing-1)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/DataLineagePanel/components/PathSummary.module.scss"],"names":[],"mappings":"AAEA,wCACE,8BAAA,CACA,wCAAA,CACA,0CAAA,CACA,oCAAA,CACA,gDAAA,CAEA,8CACE,cAAA,CACA,eAAA,CACA,wBAAA,CACA,uCAAA,CACA,oCAAA,CAGF,gDACE,YAAA,CACA,qBAAA,CACA,0BAAA,CACA,cAAA,CAIJ,iCACE,YAAA,CACA,kBAAA,CACA,0BAAA,CACA,cAAA,CAEA,yCACE,mCAAA,CACA,qBAAA,CACA,cAAA,CAGF,uCACE,uCAAA,CACA,cAAA,CAGF,0CACE,qDAAA,CACA,2CAAA,CACA,6BAAA,CACA,0CAAA,CACA,eAAA,CAGF,wCACE,cAAA,CACA,uCAAA,CACA,iBAAA,CACA,kCAAA","sourcesContent":["// PathSummary Component Styles\n\n.PathSummary {\n  padding: var(--theme-spacing-2);\n  background-color: var(--theme-color-bg-2);\n  border-radius: var(--theme-border-radius-1);\n  margin-bottom: var(--theme-spacing-3);\n  border-left: 3px solid var(--theme-color-primary);\n\n  &-title {\n    font-size: 12px;\n    font-weight: 600;\n    text-transform: uppercase;\n    color: var(--theme-color-fg-default-shy);\n    margin-bottom: var(--theme-spacing-2);\n  }\n\n  &-content {\n    display: flex;\n    flex-direction: column;\n    gap: var(--theme-spacing-1);\n    font-size: 13px;\n  }\n}\n\n.Path {\n  display: flex;\n  align-items: center;\n  gap: var(--theme-spacing-2);\n  flex-wrap: wrap;\n\n  &-segment {\n    color: var(--theme-color-fg-default);\n    font-family: monospace;\n    font-size: 12px;\n  }\n\n  &-arrow {\n    color: var(--theme-color-fg-default-shy);\n    font-size: 14px;\n  }\n\n  &-selected {\n    padding: var(--theme-spacing-1) var(--theme-spacing-2);\n    background-color: var(--theme-color-primary);\n    color: var(--theme-color-bg-1);\n    border-radius: var(--theme-border-radius-1);\n    font-weight: 600;\n  }\n\n  &-branch {\n    font-size: 11px;\n    color: var(--theme-color-fg-default-shy);\n    font-style: italic;\n    margin-left: var(--theme-spacing-1);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"PathSummary": `PathSummary-module__PathSummary--XkBGp`,
	"PathSummary-title": `PathSummary-module__PathSummary-title--kbH_b`,
	"PathSummary-content": `PathSummary-module__PathSummary-content--zGh7J`,
	"Path": `PathSummary-module__Path--KzY_1`,
	"Path-segment": `PathSummary-module__Path-segment--SJAnu`,
	"Path-arrow": `PathSummary-module__Path-arrow--lGMtD`,
	"Path-selected": `PathSummary-module__Path-selected--ACyJ7`,
	"Path-branch": `PathSummary-module__Path-branch--145Gk`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 79435:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ColorListView-module__DraggableItem--ba5XG.ColorListView-module__is-active--PrEoe{background-color:var(--theme-color-secondary)}.ColorListView-module__DraggableItem--ba5XG:hover{background-color:var(--theme-color-bg-3)}.ColorListView-module__Item--H22wg{display:flex;align-items:center;justify-content:space-between;height:38px}.ColorListView-module__ItemText--QCuLZ{padding-left:4px;flex:1}.ColorListView-module__EndSlotContainer--pK_Tn{opacity:0;padding-right:6px}.ColorListView-module__EndSlotContainer--pK_Tn,.ColorListView-module__EndSlotContainer--pK_Tn *{pointer-events:all !important}.ColorListView-module__DraggableItem--ba5XG:hover .ColorListView-module__EndSlotContainer--pK_Tn,.ColorListView-module__EndSlotContainer--pK_Tn:hover{opacity:1}.ColorListView-module__ColorItem--hbV1E{height:28px;flex:0 0 28px;margin-right:8px;background:conic-gradient(rgb(204, 204, 204) 25%, rgb(255, 255, 255) 0deg, rgb(255, 255, 255) 50%, rgb(204, 204, 204) 0deg, rgb(204, 204, 204) 75%, rgb(255, 255, 255) 0deg) 0% 0%/8px 8px}.ColorListView-module__ColorItem_Block--Ebwp3{width:100%;height:100%;border:1px solid var(--theme-color-bg-3)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/tree-view/ColorListView/ColorListView.module.scss"],"names":[],"mappings":"AACE,mFACE,6CAAA,CAGF,kDACE,wCAAA,CAIJ,mCACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,WAAA,CAGF,uCACE,gBAAA,CACA,MAAA,CAGF,+CACE,SAAA,CACA,iBAAA,CAEA,gGAEE,6BAAA,CAGF,sJAEE,SAAA,CAIJ,wCACE,WAAA,CACA,aAAA,CACA,gBAAA,CACA,0LAAA,CAWF,8CACE,UAAA,CACA,WAAA,CACA,wCAAA","sourcesContent":[".DraggableItem {\n  &.is-active {\n    background-color: var(--theme-color-secondary);\n  }\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n.Item {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  height: 38px;\n}\n\n.ItemText {\n  padding-left: 4px;\n  flex: 1;\n}\n\n.EndSlotContainer {\n  opacity: 0;\n  padding-right: 6px;\n\n  &,\n  * {\n    pointer-events: all !important;\n  }\n\n  .DraggableItem:hover &,\n  &:hover {\n    opacity: 1;\n  }\n}\n\n.ColorItem {\n  height: 28px;\n  flex: 0 0 28px;\n  margin-right: 8px;\n  background: conic-gradient(\n      rgb(204, 204, 204) 25%,\n      rgb(255, 255, 255) 0deg,\n      rgb(255, 255, 255) 50%,\n      rgb(204, 204, 204) 0deg,\n      rgb(204, 204, 204) 75%,\n      rgb(255, 255, 255) 0deg\n    )\n    0% 0% / 8px 8px;\n}\n\n.ColorItem_Block {\n  width: 100%;\n  height: 100%;\n  border: 1px solid var(--theme-color-bg-3);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"DraggableItem": `ColorListView-module__DraggableItem--ba5XG`,
	"is-active": `ColorListView-module__is-active--PrEoe`,
	"Item": `ColorListView-module__Item--H22wg`,
	"ItemText": `ColorListView-module__ItemText--QCuLZ`,
	"EndSlotContainer": `ColorListView-module__EndSlotContainer--pK_Tn`,
	"ColorItem": `ColorListView-module__ColorItem--hbV1E`,
	"ColorItem_Block": `ColorListView-module__ColorItem_Block--Ebwp3`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 79480:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgJustifyContentStart = function SvgJustifyContentStart(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.457 7.03613H8.26953C7.90709 7.03613 7.61328 7.29197 7.61328 7.60756V10.4647C7.61328 10.7803 7.90709 11.0361 8.26953 11.0361H17.457C17.8195 11.0361 18.1133 10.7803 18.1133 10.4647V7.60756C18.1133 7.29197 17.8195 7.03613 17.457 7.03613Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.457 12.5361H8.26953C7.90709 12.5361 7.61328 12.792 7.61328 13.1076V15.9647C7.61328 16.2803 7.90709 16.5361 8.26953 16.5361H17.457C17.8195 16.5361 18.1133 16.2803 18.1133 15.9647V13.1076C18.1133 12.792 17.8195 12.5361 17.457 12.5361Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.86328 4.78613C3.86328 4.37192 4.22146 4.03613 4.6633 4.03613H21.0633C21.5051 4.03613 21.8633 4.37192 21.8633 4.78613C21.8633 5.20035 21.5051 5.53613 21.0633 5.53613H4.6633C4.22146 5.53613 3.86328 5.20035 3.86328 4.78613Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgJustifyContentStart);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "8bc60596d0e5a7e0fb820100d9816b21.svg");

/***/ }),

/***/ 79486:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ComponentDiffTopbar-module__Root--niEtJ{height:36px;background-color:var(--theme-color-bg-2);border-bottom:2px solid var(--theme-color-bg-1);display:flex;align-items:center}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/documents/ComponentDiffDocument/ComponentDiffTopbar/ComponentDiffTopbar.module.scss"],"names":[],"mappings":"AAAA,yCACE,WAAA,CACA,wCAAA,CACA,+CAAA,CACA,YAAA,CAEA,kBAAA","sourcesContent":[".Root {\n  height: 36px;\n  background-color: var(--theme-color-bg-2);\n  border-bottom: 2px solid var(--theme-color-bg-1);\n  display: flex;\n  \n  align-items: center;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ComponentDiffTopbar-module__Root--niEtJ`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 79503:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgArrowLineLeft = function SvgArrowLineLeft(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.37402 21.9382C2.95981 21.9382 2.62402 21.6024 2.62402 21.1882L2.62402 4.68823C2.62402 4.27402 2.95981 3.93823 3.37402 3.93823C3.78824 3.93823 4.12402 4.27402 4.12402 4.68823L4.12402 21.1882C4.12402 21.6024 3.78824 21.9382 3.37402 21.9382Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M6.13679 13.2225C6.1734 13.312 6.22804 13.3959 6.30072 13.4686L9.99841 17.1663C10.2913 17.4591 10.7662 17.4591 11.0591 17.1663C11.352 16.8734 11.352 16.3985 11.0591 16.1056L8.64171 13.6882L20.8995 13.6882C21.3137 13.6882 21.6495 13.3524 21.6495 12.9382C21.6495 12.524 21.3137 12.1882 20.8995 12.1882L8.64172 12.1882L11.0591 9.77089C11.352 9.47799 11.352 9.00312 11.0591 8.71023C10.7662 8.41733 10.2913 8.41733 9.99841 8.71023L6.3028 12.4058C6.29605 12.4125 6.28943 12.4194 6.28294 12.4263C6.15771 12.5603 6.08105 12.7403 6.08105 12.9382C6.08105 13.0388 6.10086 13.1348 6.13679 13.2225Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgArrowLineLeft);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "23c093cd1e197efb50712f7f9a87cdf3.svg");

/***/ }),

/***/ 79598:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRadiobutton = function SvgRadiobutton(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M15.0537 25.7085C20.7146 25.7085 25.3037 21.1194 25.3037 15.4585C25.3037 9.79758 20.7146 5.2085 15.0537 5.2085C9.39279 5.2085 4.80371 9.79758 4.80371 15.4585C4.80371 21.1194 9.39279 25.7085 15.0537 25.7085ZM26.8037 15.4585C26.8037 21.9478 21.5431 27.2085 15.0537 27.2085C8.56436 27.2085 3.30371 21.9478 3.30371 15.4585C3.30371 8.96915 8.56436 3.7085 15.0537 3.7085C21.5431 3.7085 26.8037 8.96915 26.8037 15.4585Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M15.054 18.8826C16.9451 18.8826 18.4782 17.3495 18.4782 15.4584C18.4782 13.5673 16.9451 12.0343 15.054 12.0343C13.1629 12.0343 11.6299 13.5673 11.6299 15.4584C11.6299 17.3495 13.1629 18.8826 15.054 18.8826Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRadiobutton);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "15011cf3513db959c44f6da0c0d8ac16.svg");

/***/ }),

/***/ 79624:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const { ProjectModel } = __webpack_require__(6203);
const _ = __webpack_require__(80002);
const assert = __webpack_require__(42613);
const { NodeGraphContextTmp } = __webpack_require__(18498);

function splitAndTrim(stringList) {
  if (!stringList) return [];

  return stringList.split(',').map((s) => s.trim());
}

//modified version of underscores isMatch to support arrays
function isMatch(object, attrs) {
  var _keys = Object.keys(attrs),
    length = _keys.length;
  if (object == null) return !length;
  var obj = Object(object);
  for (var i = 0; i < length; i++) {
    var key = _keys[i];
    if (!(key in obj)) return false;

    if (Array.isArray(attrs[key]) && Array.isArray(obj[key])) {
      const a = attrs[key];
      const b = obj[key];
      return a.length == b.length && _.difference(a, b).length == 0;
    }
    if (attrs[key] !== obj[key] || !(key in obj)) return false;
  }
  return true;
}

function getPortType(node, paramName) {
  const port = node.getPort(paramName, 'input');
  return port?.type?.name || port?.type;
}

function evalConditions(conditions) {
  const currentViewerPath = window.noodlEditorPreviewRoute;

  for (var i in conditions) {
    var cond = conditions[i];

    if (cond['hastype'] !== undefined) {
      // Check that a node exists and have correct type
      var node = findNodeWithPath(cond['path']);
      if (node && node.type && node.type.name.toLowerCase() === cond['hastype'].toLowerCase()) cond.completed = true;
    } else if (cond['hasport'] !== undefined) {
      var node = findNodeWithPath(cond['path']);
      if (!node) continue;

      _.each(node.ports, function (p) {
        if (p.name.toLowerCase() === cond['hasport'].toLowerCase()) cond.completed = true;
      });
    } else if (cond['haslabel'] !== undefined) {
      // Make sure a node has correct label
      var node = findNodeWithPath(cond['path']);
      if (node && node.label.toLowerCase() === cond['haslabel'].toLowerCase()) cond.completed = true;
    } else if (cond['exists'] !== undefined) {
      // Make sure a node or component exist
      var node = findNodeWithPath(cond['path']);
      if (cond['exists'] === true && node !== undefined) cond.completed = true;
      if (cond['exists'] === false && node === undefined) cond.completed = true;
    } else if (cond['isvisualroot'] !== undefined) {
      // Make sure a node or component exist
      var node = findNodeWithPath(cond['path']);
      if (cond['isvisualroot'] === true && node === ProjectModel.instance.getRootNode()) cond.completed = true;
      if (cond['isvisualroot'] === false && node !== ProjectModel.instance.getRootNode()) cond.completed = true;
    } else if (cond['hasparams'] !== undefined) {
      // Make sure a node has parameters
      var node = findNodeWithPath(cond['path']);
      if (!node) continue;

      // Must compare case insensitive
      function hasParam(name) {
        for (var i in node.parameters) if (i.toLowerCase() === name.toLowerCase()) return true;

        return false;
      }

      var params = splitAndTrim(cond['hasparams']);
      cond.completed = true;
      for (var i in params) {
        if (!hasParam(params[i])) cond.completed = false;
      }
    } else if (cond['paramseq'] !== undefined) {
      // Make sure params equals specified params
      var node = findNodeWithPath(cond['path']);
      if (!node) continue;

      function isParamEqual(paramName, paramValue) {
        for (var i in node.parameters) {
          // Parameter name is case insensitive
          if (i.toLowerCase() === paramName.toLowerCase()) {
            //is the paramter an object? do a isMatch comparison (objA has all properties in objB)
            if (typeof node.parameters[i] === 'object' && isMatch(node.parameters[i], paramValue)) {
              return true;
            } else if (getPortType(node, paramName) === 'array') {
              //parse as js and check for equality
              try {
                const nodeVal = eval(node.parameters[i]);
                const paramVal = eval(paramValue);
                assert.deepStrictEqual(nodeVal, paramVal); //throws if not equal
                return true;
              } catch (_) {
                return false;
              }
            } else if (getPortType(node, paramName) === 'stringlist') {
              //string lists have the form "a,b,c" and the order shouldn't matter
              const nodeVal = (node.parameters[i] || '').split(',');
              const paramVal = (paramValue || '').split(',');

              //bit of a trick, but if we sort the arrays and join them they should be idential if all the elements are the same
              return nodeVal.sort().join(',') === paramVal.sort().join(',');
            }
            //are both paramters strings? compare case insensitive
            else if (
              node.parameters[i].toLowerCase &&
              paramValue.toLowerCase &&
              node.parameters[i].toLowerCase() === paramValue.toLowerCase()
            ) {
              return true;
            }
            //otherwise just a standard compare
            else if (node.parameters[i] === paramValue) {
              return true;
            }
          }
        }
      }

      cond.completed = true;
      var params = cond['paramseq'];
      for (var i in params) {
        if (!isParamEqual(i, params[i])) cond.completed = false;
      }
    } else if (cond['hasconnection'] !== undefined) {
      if (!cond['to']) throw new Error("'hasconnection' condition is missing a 'to' property");
      if (!cond['from']) throw new Error("'hasconnection' condition is missing a 'from' property");

      // Make sure that a connection exist in the direction
      var from = findNodeWithPath(cond['from']);
      if (!from) continue;

      var to = findNodeWithPath(cond['to']);
      if (!to) continue;

      var ports = splitAndTrim(cond['hasconnection']);
      from.forAllConnectionsOnThisNode(function (c) {
        if (
          c.fromId === from.id &&
          c.toId === to.id &&
          c.fromProperty.toLowerCase() === ports[0].toLowerCase() &&
          c.toProperty.toLowerCase() === ports[1].toLowerCase()
        ) {
          cond.completed = true;
        }
      });
    } else if (cond['metadata'] !== undefined) {
      var path = cond['metadata'].split(':');
      var data = ProjectModel.instance.getMetaData(path[0]);
      if (data && data[path[1]] === cond['equals']) cond.completed = true;
    } else if (cond['viewerpatheq'] !== undefined) {
      if (cond['viewerpatheq'] === currentViewerPath) cond.completed = true;
    } else if (cond['activecomponentnameeq'] !== undefined) {
      const activeComponent = NodeGraphContextTmp.nodeGraph.getActiveComponent();
      if (cond['activecomponentnameeq'] === activeComponent.name) cond.completed = true;
    }
  }

  // Are all conditions met?
  var res = true;
  for (var i in conditions) res = res && conditions[i].completed === true;

  return res;
}

function findNodeWithPath(path) {
  var tokens = path.split(':');

  function findNodeThatMatches(nodes, tokens, index) {
    var ref = tokens[index];
    var lastToken = index === tokens.length - 1;

    if (ref[0] === '#') {
      var label = ref.substring(1);

      for (var i in nodes)
        if (nodes[i].label.toLowerCase() === label.toLowerCase())
          return lastToken ? nodes[i] : findNodeThatMatches(nodes[i].children, tokens, index + 1);
    } else if (ref[0] === '%') {
      var typename = ref.substring(1);

      for (var i in nodes)
        if (nodes[i].type && nodes[i].type.name.toLowerCase() === typename.toLowerCase())
          return lastToken ? nodes[i] : findNodeThatMatches(nodes[i].children, tokens, index + 1);
    } else {
      var idx = parseFloat(ref);

      return lastToken ? nodes[idx] : findNodeThatMatches(nodes[idx].children, tokens, index + 1);
    }
  }

  var component;
  _.each(ProjectModel.instance.components, function (c) {
    if (c.name.toLowerCase() === tokens[0].toLowerCase()) component = c;
  });
  if (!component) return;

  return tokens.length === 1 ? component : findNodeThatMatches(component.graph.roots, tokens, 1);
}

module.exports = evalConditions;


/***/ }),

/***/ 79872:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Icon-module__Root--OBnR1{display:block}.Icon-module__Root--OBnR1 path{transition:fill var(--speed-turbo) var(--easing-base)}.Icon-module__Root--OBnR1.Icon-module__is-size-default--dIwzo{width:24px;height:24px}.Icon-module__Root--OBnR1.Icon-module__is-size-large--nzcEs{width:28px;height:28px}.Icon-module__Root--OBnR1.Icon-module__is-size-small--hhv1i{width:20px;height:20px}.Icon-module__Root--OBnR1.Icon-module__is-size-tiny--zyhFt{width:16px;height:16px}.Icon-module__Root--OBnR1.Icon-module__is-variant-default--A8T4t path{fill:var(--theme-color-fg-default)}.Icon-module__Root--OBnR1.Icon-module__is-variant-default-contrast--Z7vbM path{fill:var(--theme-color-fg-default-contrast) !important}.Icon-module__Root--OBnR1.Icon-module__is-variant-proud--UDPik path{fill:var(--theme-color-fg-highlight) !important}.Icon-module__Root--OBnR1.Icon-module__is-variant-shy--eAcuk path{fill:var(--theme-color-fg-muted) !important}.Icon-module__Root--OBnR1.Icon-module__is-variant-success--t8080 path{fill:var(--theme-color-success) !important}.Icon-module__Root--OBnR1.Icon-module__is-variant-notice--dKMTR path{fill:var(--theme-color-notice) !important}.Icon-module__Root--OBnR1.Icon-module__is-variant-danger--MoKNj path{fill:var(--theme-color-danger) !important}.Icon-module__Root--OBnR1.Icon-module__is-variant-secondary--YvOJI path{fill:var(--theme-color-secondary-as-fg) !important}.Icon-module__Root--OBnR1 svg{width:100%;height:100%}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/common/Icon/Icon.module.scss"],"names":[],"mappings":"AAAA,0BACE,aAAA,CAEA,+BACE,qDAAA,CAGF,8DACE,UAAA,CACA,WAAA,CAGF,4DACE,UAAA,CACA,WAAA,CAGF,4DACE,UAAA,CACA,WAAA,CAGF,2DACE,UAAA,CACA,WAAA,CAIA,sEACE,kCAAA,CAGF,+EACE,sDAAA,CAGF,oEACE,+CAAA,CAGF,kEACE,2CAAA,CAGF,sEACE,0CAAA,CAGF,qEACE,yCAAA,CAGF,qEACE,yCAAA,CAGF,wEACE,kDAAA,CAIJ,8BACE,UAAA,CACA,WAAA","sourcesContent":[".Root {\r\n  display: block;\r\n\r\n  path {\r\n    transition: fill var(--speed-turbo) var(--easing-base);\r\n  }\r\n\r\n  &.is-size-default {\r\n    width: 24px;\r\n    height: 24px;\r\n  }\r\n\r\n  &.is-size-large {\r\n    width: 28px;\r\n    height: 28px;\r\n  }\r\n\r\n  &.is-size-small {\r\n    width: 20px;\r\n    height: 20px;\r\n  }\r\n\r\n  &.is-size-tiny {\r\n    width: 16px;\r\n    height: 16px;\r\n  }\r\n\r\n  &.is-variant {\r\n    &-default path {\r\n      fill: var(--theme-color-fg-default);\r\n    }\r\n\r\n    &-default-contrast path {\r\n      fill: var(--theme-color-fg-default-contrast) !important;\r\n    }\r\n\r\n    &-proud path {\r\n      fill: var(--theme-color-fg-highlight) !important;\r\n    }\r\n\r\n    &-shy path {\r\n      fill: var(--theme-color-fg-muted) !important;\r\n    }\r\n\r\n    &-success path {\r\n      fill: var(--theme-color-success) !important;\r\n    }\r\n\r\n    &-notice path {\r\n      fill: var(--theme-color-notice) !important;\r\n    }\r\n\r\n    &-danger path {\r\n      fill: var(--theme-color-danger) !important;\r\n    }\r\n\r\n    &-secondary path {\r\n      fill: var(--theme-color-secondary-as-fg) !important;\r\n    }\r\n  }\r\n\r\n  svg {\r\n    width: 100%;\r\n    height: 100%;\r\n  }\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Icon-module__Root--OBnR1`,
	"is-size-default": `Icon-module__is-size-default--dIwzo`,
	"is-size-large": `Icon-module__is-size-large--nzcEs`,
	"is-size-small": `Icon-module__is-size-small--hhv1i`,
	"is-size-tiny": `Icon-module__is-size-tiny--zyhFt`,
	"is-variant-default": `Icon-module__is-variant-default--A8T4t`,
	"is-variant-default-contrast": `Icon-module__is-variant-default-contrast--Z7vbM`,
	"is-variant-proud": `Icon-module__is-variant-proud--UDPik`,
	"is-variant-shy": `Icon-module__is-variant-shy--eAcuk`,
	"is-variant-success": `Icon-module__is-variant-success--t8080`,
	"is-variant-notice": `Icon-module__is-variant-notice--dKMTR`,
	"is-variant-danger": `Icon-module__is-variant-danger--MoKNj`,
	"is-variant-secondary": `Icon-module__is-variant-secondary--YvOJI`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 79896:
/***/ ((module) => {

"use strict";
module.exports = require("fs");

/***/ }),

/***/ 79934:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Tooltip-module__Root--ws47V{font-family:var(--font-family);font-size:var(--font-size-sm);line-height:var(--line-height-normal);background-color:var(--theme-color-bg-4);color:var(--theme-color-fg-default);padding:var(--spacing-3-5);border-radius:var(--radius-default);box-shadow:var(--shadow-md);border:1px solid var(--theme-color-border-default);z-index:var(--z-tooltip);max-width:250px}.Tooltip-module__Root--ws47V span{text-align:center;white-space:break-spaces}.Tooltip-module__FineType--YVSlV{padding:0 var(--spacing-2) var(--spacing-2);margin-top:calc(-1*var(--spacing-1-5));text-align:center;font-size:var(--font-size-xs);color:var(--theme-color-fg-default-shy)}.Tooltip-module__Trigger--Ux7c4.Tooltip-module__is-block--b9Og2{display:block}.Tooltip-module__Trigger--Ux7c4.Tooltip-module__is-inline--FVegj{display:inline-block}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/popups/Tooltip/Tooltip.module.scss"],"names":[],"mappings":"AAAA,6BAEE,8BAAA,CACA,6BAAA,CACA,qCAAA,CAGA,wCAAA,CACA,mCAAA,CAGA,0BAAA,CACA,mCAAA,CAGA,2BAAA,CACA,kDAAA,CAGA,wBAAA,CAGA,eAAA,CAEA,kCACE,iBAAA,CACA,wBAAA,CAIJ,iCACE,2CAAA,CACA,sCAAA,CACA,iBAAA,CACA,6BAAA,CACA,uCAAA,CAIA,gEACE,aAAA,CAGF,iEACE,oBAAA","sourcesContent":[".Root {\n  /* Typography */\n  font-family: var(--font-family);\n  font-size: var(--font-size-sm);\n  line-height: var(--line-height-normal);\n\n  /* Background and styling */\n  background-color: var(--theme-color-bg-4);\n  color: var(--theme-color-fg-default);\n\n  /* Spacing */\n  padding: var(--spacing-3-5);\n  border-radius: var(--radius-default);\n\n  /* Elevated appearance */\n  box-shadow: var(--shadow-md);\n  border: 1px solid var(--theme-color-border-default);\n\n  /* Ensure tooltip is above everything */\n  z-index: var(--z-tooltip);\n\n  /* Size constraint */\n  max-width: 250px;\n\n  span {\n    text-align: center;\n    white-space: break-spaces;\n  }\n}\n\n.FineType {\n  padding: 0 var(--spacing-2) var(--spacing-2);\n  margin-top: calc(-1 * var(--spacing-1-5));\n  text-align: center;\n  font-size: var(--font-size-xs);\n  color: var(--theme-color-fg-default-shy);\n}\n\n.Trigger {\n  &.is-block {\n    display: block;\n  }\n\n  &.is-inline {\n    display: inline-block;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Tooltip-module__Root--ws47V`,
	"FineType": `Tooltip-module__FineType--YVSlV`,
	"Trigger": `Tooltip-module__Trigger--Ux7c4`,
	"is-block": `Tooltip-module__is-block--b9Og2`,
	"is-inline": `Tooltip-module__is-inline--FVegj`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 79973:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isEmptyHeaders = exports.buildHeaders = void 0;
const values_1 = __webpack_require__(25267);
const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders');
function* iterateHeaders(headers) {
    if (!headers)
        return;
    if (brand_privateNullableHeaders in headers) {
        const { values, nulls } = headers;
        yield* values.entries();
        for (const name of nulls) {
            yield [name, null];
        }
        return;
    }
    let shouldClear = false;
    let iter;
    if (headers instanceof Headers) {
        iter = headers.entries();
    }
    else if ((0, values_1.isReadonlyArray)(headers)) {
        iter = headers;
    }
    else {
        shouldClear = true;
        iter = Object.entries(headers ?? {});
    }
    for (let row of iter) {
        const name = row[0];
        if (typeof name !== 'string')
            throw new TypeError('expected header name to be a string');
        const values = (0, values_1.isReadonlyArray)(row[1]) ? row[1] : [row[1]];
        let didClear = false;
        for (const value of values) {
            if (value === undefined)
                continue;
            // Objects keys always overwrite older headers, they never append.
            // Yield a null to clear the header before adding the new values.
            if (shouldClear && !didClear) {
                didClear = true;
                yield [name, null];
            }
            yield [name, value];
        }
    }
}
const buildHeaders = (newHeaders) => {
    const targetHeaders = new Headers();
    const nullHeaders = new Set();
    for (const headers of newHeaders) {
        const seenHeaders = new Set();
        for (const [name, value] of iterateHeaders(headers)) {
            const lowerName = name.toLowerCase();
            if (!seenHeaders.has(lowerName)) {
                targetHeaders.delete(name);
                seenHeaders.add(lowerName);
            }
            if (value === null) {
                targetHeaders.delete(name);
                nullHeaders.add(lowerName);
            }
            else {
                targetHeaders.append(name, value);
                nullHeaders.delete(lowerName);
            }
        }
    }
    return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
};
exports.buildHeaders = buildHeaders;
const isEmptyHeaders = (headers) => {
    for (const _ of iterateHeaders(headers))
        return false;
    return true;
};
exports.isEmptyHeaders = isEmptyHeaders;
//# sourceMappingURL=headers.js.map

/***/ }),

/***/ 80002:
/***/ ((module) => {

"use strict";
module.exports = require("underscore");

/***/ }),

/***/ 80218:
/***/ ((module) => {

// Module
var code = "<div class=\"nodegrapgeditor-bg nodegrapheditor-canvas\" style=\"width:100%;height:100%\"> <div id=\"editor-banner-root\" style=\"position:absolute;width:100%;z-index:1001\"></div> <div id=\"canvas-tabs-root\" style=\"position:absolute;width:100%;height:100%;z-index:100;pointer-events:none\"></div> <div style=\"position:absolute;overflow:hidden;width:100%;height:100%\"> <div id=\"comment-layer-bg\"></div> </div> <canvas id=\"nodegraphcanvas\" width=\"1000\" height=\"600\" style=\"position:absolute;width:100%;height:100%\"></canvas> <div style=\"position:absolute;overflow:hidden;width:100%;height:100%;pointer-events:none\"> <div id=\"highlight-overlay-layer\"></div> </div> <div style=\"position:absolute;overflow:hidden;width:100%;height:100%;pointer-events:none\"> <div id=\"comment-layer-fg\" style=\"pointer-events:all\"></div> </div> <div style=\"position:relative\"> <div id=\"nodegraph-dom-layer\"></div> </div> <div class=\"nodegraph-component-trail-root\"></div> <div class=\"help-center-layer\"></div> <div style=\"position:absolute;overflow:hidden;width:100%;height:100%;pointer-events:none\"> <div class=\"clippy-layer\"></div> </div> </div> ";
// Exports
module.exports = code;

/***/ }),

/***/ 80222:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `@keyframes MigrationWizard-module__fadeIn--mINp5{from{opacity:0;transform:scale(0.95)}to{opacity:1;transform:scale(1)}}@keyframes MigrationWizard-module__slideIn--IAEgr{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}:root{--wizard-space-xs: 4px;--wizard-space-sm: 8px;--wizard-space-md: 16px;--wizard-space-lg: 24px;--wizard-space-xl: 32px;--wizard-space-xxl: 48px;--wizard-transition-fast: 150ms ease-out;--wizard-transition-base: 250ms ease-in-out;--wizard-transition-slow: 400ms ease-in-out;--wizard-radius-sm: 4px;--wizard-radius-md: 8px;--wizard-radius-lg: 12px;--wizard-shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.12);--wizard-shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);--wizard-shadow-lg: 0 10px 25px rgba(0, 0, 0, 0.15)}.MigrationWizard-module__WizardContainer--SYyvz{position:relative;width:750px;max-width:92vw;max-height:85vh;display:flex;flex-direction:column;background-color:var(--theme-color-bg-4);border-radius:var(--wizard-radius-lg);overflow:hidden;box-shadow:var(--wizard-shadow-lg);animation:MigrationWizard-module__fadeIn--mINp5 var(--wizard-transition-base)}.MigrationWizard-module__CloseButton--BCcth{position:absolute;top:var(--wizard-space-md);right:var(--wizard-space-md);z-index:10;transition:transform var(--wizard-transition-fast)}.MigrationWizard-module__CloseButton--BCcth:hover{transform:scale(1.1)}.MigrationWizard-module__CloseButton--BCcth:active{transform:scale(0.95)}.MigrationWizard-module__WizardHeader--R8UHT{padding:var(--wizard-space-xl) var(--wizard-space-xl) var(--wizard-space-lg);padding-right:var(--wizard-space-xxl);border-bottom:1px solid var(--theme-color-bg-3)}.MigrationWizard-module__WizardContent--mOpzF{display:flex;flex-direction:column;padding:0 var(--wizard-space-xl) var(--wizard-space-xl);gap:var(--wizard-space-lg);flex:1;min-height:0;overflow-y:auto;animation:MigrationWizard-module__slideIn--IAEgr var(--wizard-transition-base)}.MigrationWizard-module__WizardContent--mOpzF::-webkit-scrollbar{width:8px}.MigrationWizard-module__WizardContent--mOpzF::-webkit-scrollbar-track{background:var(--theme-color-bg-3);border-radius:var(--wizard-radius-sm)}.MigrationWizard-module__WizardContent--mOpzF::-webkit-scrollbar-thumb{background:var(--theme-color-bg-1);border-radius:var(--wizard-radius-sm)}.MigrationWizard-module__WizardContent--mOpzF::-webkit-scrollbar-thumb:hover{background:var(--theme-color-primary)}.MigrationWizard-module__StepContainer--CVHs_{flex:1;min-height:300px;animation:MigrationWizard-module__slideIn--IAEgr var(--wizard-transition-base)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/migration/MigrationWizard.module.scss"],"names":[],"mappings":"AAQA,iDACE,KACE,SAAA,CACA,qBAAA,CAEF,GACE,SAAA,CACA,kBAAA,CAAA,CAIJ,kDACE,KACE,SAAA,CACA,0BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAKJ,MACE,sBAAA,CACA,sBAAA,CACA,uBAAA,CACA,uBAAA,CACA,uBAAA,CACA,wBAAA,CAEA,wCAAA,CACA,2CAAA,CACA,2CAAA,CAEA,uBAAA,CACA,uBAAA,CACA,wBAAA,CAEA,iDAAA,CACA,gDAAA,CACA,mDAAA,CAGF,gDACE,iBAAA,CACA,WAAA,CACA,cAAA,CACA,eAAA,CACA,YAAA,CACA,qBAAA,CACA,wCAAA,CACA,qCAAA,CACA,eAAA,CACA,kCAAA,CACA,6EAAA,CAGF,4CACE,iBAAA,CACA,0BAAA,CACA,4BAAA,CACA,UAAA,CACA,kDAAA,CAEA,kDACE,oBAAA,CAGF,mDACE,qBAAA,CAIJ,6CACE,4EAAA,CACA,qCAAA,CACA,+CAAA,CAGF,8CACE,YAAA,CACA,qBAAA,CACA,uDAAA,CACA,0BAAA,CACA,MAAA,CACA,YAAA,CACA,eAAA,CACA,8EAAA,CAGA,iEACE,SAAA,CAGF,uEACE,kCAAA,CACA,qCAAA,CAGF,uEACE,kCAAA,CACA,qCAAA,CAEA,6EACE,qCAAA,CAKN,8CACE,MAAA,CACA,gBAAA,CACA,8EAAA","sourcesContent":["/**\n * MigrationWizard Styles\n * \n * Main container for the migration wizard using CoreBaseDialog.\n * Enhanced with modern visual design, animations, and better spacing.\n */\n\n/* Animation definitions */\n@keyframes fadeIn {\n  from {\n    opacity: 0;\n    transform: scale(0.95);\n  }\n  to {\n    opacity: 1;\n    transform: scale(1);\n  }\n}\n\n@keyframes slideIn {\n  from {\n    opacity: 0;\n    transform: translateY(10px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n/* Design system variables */\n:root {\n  --wizard-space-xs: 4px;\n  --wizard-space-sm: 8px;\n  --wizard-space-md: 16px;\n  --wizard-space-lg: 24px;\n  --wizard-space-xl: 32px;\n  --wizard-space-xxl: 48px;\n\n  --wizard-transition-fast: 150ms ease-out;\n  --wizard-transition-base: 250ms ease-in-out;\n  --wizard-transition-slow: 400ms ease-in-out;\n\n  --wizard-radius-sm: 4px;\n  --wizard-radius-md: 8px;\n  --wizard-radius-lg: 12px;\n\n  --wizard-shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.12);\n  --wizard-shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);\n  --wizard-shadow-lg: 0 10px 25px rgba(0, 0, 0, 0.15);\n}\n\n.WizardContainer {\n  position: relative;\n  width: 750px;\n  max-width: 92vw;\n  max-height: 85vh;\n  display: flex;\n  flex-direction: column;\n  background-color: var(--theme-color-bg-4);\n  border-radius: var(--wizard-radius-lg);\n  overflow: hidden;\n  box-shadow: var(--wizard-shadow-lg);\n  animation: fadeIn var(--wizard-transition-base);\n}\n\n.CloseButton {\n  position: absolute;\n  top: var(--wizard-space-md);\n  right: var(--wizard-space-md);\n  z-index: 10;\n  transition: transform var(--wizard-transition-fast);\n\n  &:hover {\n    transform: scale(1.1);\n  }\n\n  &:active {\n    transform: scale(0.95);\n  }\n}\n\n.WizardHeader {\n  padding: var(--wizard-space-xl) var(--wizard-space-xl) var(--wizard-space-lg);\n  padding-right: var(--wizard-space-xxl); // Space for close button\n  border-bottom: 1px solid var(--theme-color-bg-3);\n}\n\n.WizardContent {\n  display: flex;\n  flex-direction: column;\n  padding: 0 var(--wizard-space-xl) var(--wizard-space-xl);\n  gap: var(--wizard-space-lg);\n  flex: 1;\n  min-height: 0;\n  overflow-y: auto;\n  animation: slideIn var(--wizard-transition-base);\n\n  /* Custom scrollbar styling */\n  &::-webkit-scrollbar {\n    width: 8px;\n  }\n\n  &::-webkit-scrollbar-track {\n    background: var(--theme-color-bg-3);\n    border-radius: var(--wizard-radius-sm);\n  }\n\n  &::-webkit-scrollbar-thumb {\n    background: var(--theme-color-bg-1);\n    border-radius: var(--wizard-radius-sm);\n\n    &:hover {\n      background: var(--theme-color-primary);\n    }\n  }\n}\n\n.StepContainer {\n  flex: 1;\n  min-height: 300px;\n  animation: slideIn var(--wizard-transition-base);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"WizardContainer": `MigrationWizard-module__WizardContainer--SYyvz`,
	"fadeIn": `MigrationWizard-module__fadeIn--mINp5`,
	"CloseButton": `MigrationWizard-module__CloseButton--BCcth`,
	"WizardHeader": `MigrationWizard-module__WizardHeader--R8UHT`,
	"WizardContent": `MigrationWizard-module__WizardContent--mOpzF`,
	"slideIn": `MigrationWizard-module__slideIn--IAEgr`,
	"StepContainer": `MigrationWizard-module__StepContainer--CVHs_`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 80424:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ToastLayer: () => (/* binding */ ToastLayer)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react_hot_toast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(64389);
/* harmony import */ var react_hot_toast__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_hot_toast__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _components_ToastCard__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(20749);



const ToastLayer = {
    showInteraction(message) {
        react_hot_toast__WEBPACK_IMPORTED_MODULE_1___default().success(react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_ToastCard__WEBPACK_IMPORTED_MODULE_2__/* .ToastCard */ .S, { type: _components_ToastCard__WEBPACK_IMPORTED_MODULE_2__/* .ToastType */ .C.Neutral, message: message }));
    },
    showActivity(message, toastId = 'no-id') {
        react_hot_toast__WEBPACK_IMPORTED_MODULE_1___default().promise(new Promise(() => {
            // noop
        }), {
            loading: react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_ToastCard__WEBPACK_IMPORTED_MODULE_2__/* .ToastCard */ .S, { type: _components_ToastCard__WEBPACK_IMPORTED_MODULE_2__/* .ToastType */ .C.Pending, message: message, hasActivity: true }),
            success: '',
            error: ''
        }, { id: toastId, duration: 1000000 });
    },
    hideActivity(toastId = 'no-id') {
        react_hot_toast__WEBPACK_IMPORTED_MODULE_1___default().dismiss(toastId);
    },
    hideAll() {
        react_hot_toast__WEBPACK_IMPORTED_MODULE_1___default().dismiss();
    },
    showSuccess(message) {
        react_hot_toast__WEBPACK_IMPORTED_MODULE_1___default().success(react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_ToastCard__WEBPACK_IMPORTED_MODULE_2__/* .ToastCard */ .S, { type: _components_ToastCard__WEBPACK_IMPORTED_MODULE_2__/* .ToastType */ .C.Success, message: message }));
    },
    showError(message, duration = Infinity) {
        // Don't pass onClose callback - makes toast permanent with no close button
        react_hot_toast__WEBPACK_IMPORTED_MODULE_1___default().error(react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_ToastCard__WEBPACK_IMPORTED_MODULE_2__/* .ToastCard */ .S, { type: _components_ToastCard__WEBPACK_IMPORTED_MODULE_2__/* .ToastType */ .C.Danger, message: message }), {
            duration
        });
    },
    showProgress(message, progress, toastId) {
        if (progress) {
            react_hot_toast__WEBPACK_IMPORTED_MODULE_1___default().loading(react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_components_ToastCard__WEBPACK_IMPORTED_MODULE_2__/* .ToastCard */ .S, { type: _components_ToastCard__WEBPACK_IMPORTED_MODULE_2__/* .ToastType */ .C.Pending, message: message, progress: progress, hasActivity: true }), {
                id: toastId
            });
        }
    },
    hideProgress(toastId) {
        react_hot_toast__WEBPACK_IMPORTED_MODULE_1___default().dismiss(toastId);
    }
};


/***/ }),

/***/ 80730:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.uuid4 = void 0;
/**
 * https://stackoverflow.com/a/2117523
 */
let uuid4 = function () {
    const { crypto } = globalThis;
    if (crypto?.randomUUID) {
        exports.uuid4 = crypto.randomUUID.bind(crypto);
        return crypto.randomUUID();
    }
    const u8 = new Uint8Array(1);
    const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff;
    return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16));
};
exports.uuid4 = uuid4;
//# sourceMappingURL=uuid.js.map

/***/ }),

/***/ 80760:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   S: () => (/* binding */ CommitIdentity)
/* harmony export */ });
/**
 * A tuple of name, email, and date for the author or commit
 * info in a commit.
 */
class CommitIdentity {
    /**
     * Parses a Git ident string (GIT_AUTHOR_IDENT or GIT_COMMITTER_IDENT)
     * into a commit identity. Throws an error if identify string is invalid.
     */
    static parseIdentity(identity) {
        // See fmt_ident in ident.c:
        //  https://github.com/git/git/blob/3ef7618e6/ident.c#L346
        //
        // Format is "NAME <EMAIL> DATE"
        //  Markus Olsson <j.markus.olsson@gmail.com> 1475670580 +0200
        //
        // Note that `git var` will strip any < and > from the name and email, see:
        //  https://github.com/git/git/blob/3ef7618e6/ident.c#L396
        //
        // Note also that this expects a date formatted with the RAW option in git see:
        //  https://github.com/git/git/blob/35f6318d4/date.c#L191
        //
        const m = identity.match(/^(.*?) <(.*?)> (\d+) (\+|-)?(\d{2})(\d{2})/);
        if (!m) {
            throw new Error(`Couldn't parse identity ${identity}`);
        }
        const name = m[1];
        const email = m[2];
        // The date is specified as seconds from the epoch,
        // Date() expects milliseconds since the epoch.
        const date = new Date(parseInt(m[3], 10) * 1000);
        if (isNaN(date.valueOf())) {
            throw new Error(`Couldn't parse identity ${identity}, invalid date`);
        }
        // The RAW option never uses alphanumeric timezone identifiers and in my
        // testing I've never found it to omit the leading + for a positive offset
        // but the docs for strprintf seems to suggest it might on some systems so
        // we're playing it safe.
        const tzSign = m[4] === '-' ? '-' : '+';
        const tzHH = m[5];
        const tzmm = m[6];
        const tzMinutes = parseInt(tzHH, 10) * 60 + parseInt(tzmm, 10);
        const tzOffset = tzMinutes * (tzSign === '-' ? -1 : 1);
        return new CommitIdentity(name, email, date, tzOffset);
    }
    constructor(name, email, date, tzOffset = new Date().getTimezoneOffset()) {
        this.name = name;
        this.email = email;
        this.date = date;
        this.tzOffset = tzOffset;
    }
}


/***/ }),

/***/ 80786:
/***/ ((module) => {

"use strict";
module.exports = require("archiver");

/***/ }),

/***/ 80801:
/***/ ((module) => {

// Module
var code = "<div class=\"color-picker-popup\"> <div id=\"ui-color-picker\" class=\"ui-color-picker\"></div> <div style=\"display:flex;align-items:center;color:#f8f8f8;margin-top:16px\"> Hex <div style=\"display:flex;margin-left:8px;height:35px\"> <div style=\"height:100%;flex-grow:1\"> <input id=\"hexinput\" type=\"string\" style=\"width:100%;height:100%\" class=\"sidebar-panel-dark-input\" data-change=\"onHexInputFieldChanged\"> </div> <input id=\"opacityInput\" type=\"string\" placeholder=\"100%\" style=\"width:50px;height:100%\" class=\"sidebar-panel-dark-input\" data-change=\"onOpacityInputFieldChanged\"> </div> </div> </div> ";
// Exports
module.exports = code;

/***/ }),

/***/ 80953:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ByobFilterBuilder-module__ByobFilterBuilder--I61fW{display:flex;flex-direction:column;background-color:var(--theme-color-bg-2);border-radius:4px;overflow:hidden}.ByobFilterBuilder-module__ByobFilterBuilderHeader--tAGUE{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;background-color:var(--theme-color-bg-3);border-bottom:1px solid var(--theme-color-border-default)}.ByobFilterBuilder-module__ByobFilterBuilderActions--ULEMB{display:flex;gap:4px}.ByobFilterBuilder-module__ByobFilterBuilderContent--ydHQ9{padding:8px}.ByobFilterBuilder-module__FilterGroup--QlcCI{background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:4px;overflow:hidden}.ByobFilterBuilder-module__FilterGroupRoot--xn6AK{border:none;background:rgba(0,0,0,0)}.ByobFilterBuilder-module__FilterGroup--QlcCI[data-depth="1"]{background-color:var(--theme-color-bg-2)}.ByobFilterBuilder-module__FilterGroup--QlcCI[data-depth="2"]{background-color:var(--theme-color-bg-1)}.ByobFilterBuilder-module__FilterGroupHeader--dQ2Pw{display:flex;justify-content:space-between;align-items:center;padding:6px 8px;background-color:var(--theme-color-bg-4);border-bottom:1px solid var(--theme-color-border-default)}.ByobFilterBuilder-module__FilterGroupHeaderLeft--Sgwhh{display:flex;align-items:center;gap:8px}.ByobFilterBuilder-module__FilterGroupDragHandle--uVyGc{cursor:grab;padding:2px 4px;border-radius:2px;opacity:.5;transition:opacity .15s ease,background-color .15s ease}.ByobFilterBuilder-module__FilterGroupDragHandle--uVyGc:hover{opacity:1;background-color:var(--theme-color-bg-2)}.ByobFilterBuilder-module__FilterGroupDragHandle--uVyGc:active{cursor:grabbing}.ByobFilterBuilder-module__FilterGroupDragging--mWUm3{opacity:.5;border-style:dashed !important}.ByobFilterBuilder-module__FilterGroupDragOver--TMDfA{border-color:var(--theme-color-primary) !important;box-shadow:0 0 0 2px var(--theme-color-primary-25)}.ByobFilterBuilder-module__FilterGroupDropIndicator--bnHNK{background-color:var(--theme-color-primary-10);color:var(--theme-color-primary);padding:8px 12px;text-align:center;font-size:12px;font-weight:500;border-bottom:1px solid var(--theme-color-primary-25)}.ByobFilterBuilder-module__FilterGroupCombinator--jQMjx{background-color:var(--theme-color-primary);color:var(--theme-color-fg-on-primary);border:none;padding:4px 12px;border-radius:4px;font-size:11px;font-weight:600;cursor:pointer;transition:background-color .15s ease;text-transform:uppercase;letter-spacing:.5px}.ByobFilterBuilder-module__FilterGroupCombinator--jQMjx:hover{background-color:var(--theme-color-primary-highlight)}.ByobFilterBuilder-module__FilterGroupDelete--OEaEA{opacity:.6}.ByobFilterBuilder-module__FilterGroupDelete--OEaEA:hover{opacity:1}.ByobFilterBuilder-module__FilterGroupConditions--m_6LP{padding:8px}.ByobFilterBuilder-module__FilterGroupCombinatorLabel--DJuJ9{text-align:center;font-size:10px;font-weight:600;color:var(--theme-color-fg-default-shy);text-transform:uppercase;letter-spacing:.5px;padding:4px 0}.ByobFilterBuilder-module__FilterGroupEmpty--i3vHS{padding:16px;text-align:center;color:var(--theme-color-fg-default-shy);font-size:12px;font-style:italic}.ByobFilterBuilder-module__FilterGroupActions--OtFDs{display:flex;gap:8px}.ByobFilterBuilder-module__FilterCondition--YE_5O{background-color:var(--theme-color-bg-2);border-radius:4px;padding:4px;border:1px solid rgba(0,0,0,0);transition:opacity .15s ease,border-color .15s ease}.ByobFilterBuilder-module__FilterConditionDragging--eeh5l{opacity:.5;border-style:dashed !important;border-color:var(--theme-color-border-default) !important}.ByobFilterBuilder-module__FilterConditionDragHandle--DKIpm{cursor:grab;padding:2px 4px;border-radius:2px;opacity:.4;flex-shrink:0;transition:opacity .15s ease,background-color .15s ease}.ByobFilterBuilder-module__FilterConditionDragHandle--DKIpm:hover{opacity:1;background-color:var(--theme-color-bg-3)}.ByobFilterBuilder-module__FilterConditionDragHandle--DKIpm:active{cursor:grabbing}.ByobFilterBuilder-module__FilterConditionFields--x2kPE{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.ByobFilterBuilder-module__FilterConditionField--qcGDv{flex:1;min-width:120px;max-width:200px}.ByobFilterBuilder-module__FilterConditionOperator--L1ehu{flex:1;min-width:100px;max-width:180px}.ByobFilterBuilder-module__FilterConditionValue--dK_ir{flex:2;min-width:100px}.ByobFilterBuilder-module__FilterConditionValueSmall--PqUM8{flex:1;min-width:60px;max-width:120px}.ByobFilterBuilder-module__FilterConditionBetweenLabel--rsVxl{color:var(--theme-color-fg-default-shy);font-size:12px;padding:0 4px}.ByobFilterBuilder-module__FilterConditionDelete--O8M94{opacity:.5;flex-shrink:0}.ByobFilterBuilder-module__FilterConditionDelete--O8M94:hover{opacity:1}.ByobFilterBuilder-module__FilterConditionConnectToggle--yrVe1{flex-shrink:0;opacity:.6;transition:opacity .15s ease,color .15s ease}.ByobFilterBuilder-module__FilterConditionConnectToggle--yrVe1:hover{opacity:1}.ByobFilterBuilder-module__FilterConditionPortIndicator--no6el{display:flex;align-items:center;gap:6px;flex:2;min-width:100px;padding:6px 10px;background-color:var(--theme-color-primary-10);border:1px solid var(--theme-color-primary-25);border-radius:4px;color:var(--theme-color-primary)}.ByobFilterBuilder-module__FilterConditionPortDot--ODN1Z{color:var(--theme-color-primary)}.ByobFilterBuilder-module__FilterConditionPortName--Vy4m9{font-family:"Fira Code","Monaco","Consolas",monospace;font-size:11px;font-weight:500}.ByobFilterBuilder-module__ByobFilterBuilderJson--UuJQ6{border-top:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-1)}.ByobFilterBuilder-module__ByobFilterBuilderJsonHeader--vrDgx{display:flex;justify-content:space-between;align-items:center;padding:6px 12px;background-color:var(--theme-color-bg-2);border-bottom:1px solid var(--theme-color-border-default)}.ByobFilterBuilder-module__ByobFilterBuilderJsonActions--qsmlH{display:flex;gap:4px}.ByobFilterBuilder-module__ByobFilterBuilderJsonPreview--K598G{margin:0;padding:12px;font-family:"Fira Code","Monaco","Consolas",monospace;font-size:11px;color:var(--theme-color-fg-default);overflow-x:auto;white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto}.ByobFilterBuilder-module__ByobFilterBuilderJsonEditor--mAA5A{width:100%;min-height:150px;padding:12px;font-family:"Fira Code","Monaco","Consolas",monospace;font-size:11px;color:var(--theme-color-fg-default);background-color:var(--theme-color-bg-1);border:none;resize:vertical;outline:none}.ByobFilterBuilder-module__ByobFilterBuilderJsonEditor--mAA5A:focus{outline:1px solid var(--theme-color-primary)}.ByobFilterBuilder-module__ByobFilterBuilderJsonError--xLVoT{color:var(--theme-color-danger);font-size:12px}.ByobFilterBuilder-module__FilterBuilderButton--_IzZ1{display:flex;align-items:center;justify-content:space-between;background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:4px;padding:8px 12px;cursor:pointer;transition:all .15s ease}.ByobFilterBuilder-module__FilterBuilderButton--_IzZ1:hover{background-color:var(--theme-color-bg-2);border-color:var(--theme-color-border-highlight)}.ByobFilterBuilder-module__FilterBuilderButtonContent--cw3Bz{display:flex;align-items:center;gap:8px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/ByobFilterBuilder.module.scss"],"names":[],"mappings":"AAMA,oDACE,YAAA,CACA,qBAAA,CACA,wCAAA,CACA,iBAAA,CACA,eAAA,CAGF,0DACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,gBAAA,CACA,wCAAA,CACA,yDAAA,CAGF,2DACE,YAAA,CACA,OAAA,CAGF,2DACE,WAAA,CAIF,8CACE,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,eAAA,CAEA,kDACE,WAAA,CACA,wBAAA,CAIF,8DACE,wCAAA,CAGF,8DACE,wCAAA,CAIJ,oDACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,eAAA,CACA,wCAAA,CACA,yDAAA,CAGF,wDACE,YAAA,CACA,kBAAA,CACA,OAAA,CAGF,wDACE,WAAA,CACA,eAAA,CACA,iBAAA,CACA,UAAA,CACA,uDAAA,CAEA,8DACE,SAAA,CACA,wCAAA,CAGF,+DACE,eAAA,CAIJ,sDACE,UAAA,CACA,8BAAA,CAGF,sDACE,kDAAA,CACA,kDAAA,CAGF,2DACE,8CAAA,CACA,gCAAA,CACA,gBAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,qDAAA,CAGF,wDACE,2CAAA,CACA,sCAAA,CACA,WAAA,CACA,gBAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,qCAAA,CACA,wBAAA,CACA,mBAAA,CAEA,8DACE,qDAAA,CAIJ,oDACE,UAAA,CAEA,0DACE,SAAA,CAIJ,wDACE,WAAA,CAGF,6DACE,iBAAA,CACA,cAAA,CACA,eAAA,CACA,uCAAA,CACA,wBAAA,CACA,mBAAA,CACA,aAAA,CAGF,mDACE,YAAA,CACA,iBAAA,CACA,uCAAA,CACA,cAAA,CACA,iBAAA,CAGF,qDACE,YAAA,CACA,OAAA,CAIF,kDACE,wCAAA,CACA,iBAAA,CACA,WAAA,CACA,8BAAA,CACA,mDAAA,CAGF,0DACE,UAAA,CACA,8BAAA,CACA,yDAAA,CAGF,4DACE,WAAA,CACA,eAAA,CACA,iBAAA,CACA,UAAA,CACA,aAAA,CACA,uDAAA,CAEA,kEACE,SAAA,CACA,wCAAA,CAGF,mEACE,eAAA,CAIJ,wDACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,cAAA,CAGF,uDACE,MAAA,CACA,eAAA,CACA,eAAA,CAGF,0DACE,MAAA,CACA,eAAA,CACA,eAAA,CAGF,uDACE,MAAA,CACA,eAAA,CAGF,4DACE,MAAA,CACA,cAAA,CACA,eAAA,CAGF,8DACE,uCAAA,CACA,cAAA,CACA,aAAA,CAGF,wDACE,UAAA,CACA,aAAA,CAEA,8DACE,SAAA,CAKJ,+DACE,aAAA,CACA,UAAA,CACA,4CAAA,CAEA,qEACE,SAAA,CAKJ,+DACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,MAAA,CACA,eAAA,CACA,gBAAA,CACA,8CAAA,CACA,8CAAA,CACA,iBAAA,CACA,gCAAA,CAGF,yDACE,gCAAA,CAGF,0DACE,qDAAA,CACA,cAAA,CACA,eAAA,CAIF,wDACE,sDAAA,CACA,wCAAA,CAGF,8DACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,gBAAA,CACA,wCAAA,CACA,yDAAA,CAGF,+DACE,YAAA,CACA,OAAA,CAGF,+DACE,QAAA,CACA,YAAA,CACA,qDAAA,CACA,cAAA,CACA,mCAAA,CACA,eAAA,CACA,oBAAA,CACA,qBAAA,CACA,gBAAA,CACA,eAAA,CAGF,8DACE,UAAA,CACA,gBAAA,CACA,YAAA,CACA,qDAAA,CACA,cAAA,CACA,mCAAA,CACA,wCAAA,CACA,WAAA,CACA,eAAA,CACA,YAAA,CAEA,oEACE,4CAAA,CAIJ,6DACE,+BAAA,CACA,cAAA,CAIF,sDACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,gBAAA,CACA,cAAA,CACA,wBAAA,CAEA,4DACE,wCAAA,CACA,gDAAA,CAIJ,6DACE,YAAA,CACA,kBAAA,CACA,OAAA","sourcesContent":["/**\n * BYOB Filter Builder Styles\n *\n * Uses design tokens from theme variables\n */\n\n.ByobFilterBuilder {\n  display: flex;\n  flex-direction: column;\n  background-color: var(--theme-color-bg-2);\n  border-radius: 4px;\n  overflow: hidden;\n}\n\n.ByobFilterBuilderHeader {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 8px 12px;\n  background-color: var(--theme-color-bg-3);\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.ByobFilterBuilderActions {\n  display: flex;\n  gap: 4px;\n}\n\n.ByobFilterBuilderContent {\n  padding: 8px;\n}\n\n// Filter Group Styles\n.FilterGroup {\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  overflow: hidden;\n\n  &Root {\n    border: none;\n    background: transparent;\n  }\n\n  // Nested groups get progressively lighter borders\n  &[data-depth='1'] {\n    background-color: var(--theme-color-bg-2);\n  }\n\n  &[data-depth='2'] {\n    background-color: var(--theme-color-bg-1);\n  }\n}\n\n.FilterGroupHeader {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 6px 8px;\n  background-color: var(--theme-color-bg-4);\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.FilterGroupHeaderLeft {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n.FilterGroupDragHandle {\n  cursor: grab;\n  padding: 2px 4px;\n  border-radius: 2px;\n  opacity: 0.5;\n  transition: opacity 0.15s ease, background-color 0.15s ease;\n\n  &:hover {\n    opacity: 1;\n    background-color: var(--theme-color-bg-2);\n  }\n\n  &:active {\n    cursor: grabbing;\n  }\n}\n\n.FilterGroupDragging {\n  opacity: 0.5;\n  border-style: dashed !important;\n}\n\n.FilterGroupDragOver {\n  border-color: var(--theme-color-primary) !important;\n  box-shadow: 0 0 0 2px var(--theme-color-primary-25);\n}\n\n.FilterGroupDropIndicator {\n  background-color: var(--theme-color-primary-10);\n  color: var(--theme-color-primary);\n  padding: 8px 12px;\n  text-align: center;\n  font-size: 12px;\n  font-weight: 500;\n  border-bottom: 1px solid var(--theme-color-primary-25);\n}\n\n.FilterGroupCombinator {\n  background-color: var(--theme-color-primary);\n  color: var(--theme-color-fg-on-primary);\n  border: none;\n  padding: 4px 12px;\n  border-radius: 4px;\n  font-size: 11px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: background-color 0.15s ease;\n  text-transform: uppercase;\n  letter-spacing: 0.5px;\n\n  &:hover {\n    background-color: var(--theme-color-primary-highlight);\n  }\n}\n\n.FilterGroupDelete {\n  opacity: 0.6;\n\n  &:hover {\n    opacity: 1;\n  }\n}\n\n.FilterGroupConditions {\n  padding: 8px;\n}\n\n.FilterGroupCombinatorLabel {\n  text-align: center;\n  font-size: 10px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default-shy);\n  text-transform: uppercase;\n  letter-spacing: 0.5px;\n  padding: 4px 0;\n}\n\n.FilterGroupEmpty {\n  padding: 16px;\n  text-align: center;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 12px;\n  font-style: italic;\n}\n\n.FilterGroupActions {\n  display: flex;\n  gap: 8px;\n}\n\n// Filter Condition Styles\n.FilterCondition {\n  background-color: var(--theme-color-bg-2);\n  border-radius: 4px;\n  padding: 4px;\n  border: 1px solid transparent;\n  transition: opacity 0.15s ease, border-color 0.15s ease;\n}\n\n.FilterConditionDragging {\n  opacity: 0.5;\n  border-style: dashed !important;\n  border-color: var(--theme-color-border-default) !important;\n}\n\n.FilterConditionDragHandle {\n  cursor: grab;\n  padding: 2px 4px;\n  border-radius: 2px;\n  opacity: 0.4;\n  flex-shrink: 0;\n  transition: opacity 0.15s ease, background-color 0.15s ease;\n\n  &:hover {\n    opacity: 1;\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &:active {\n    cursor: grabbing;\n  }\n}\n\n.FilterConditionFields {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  flex-wrap: wrap;\n}\n\n.FilterConditionField {\n  flex: 1;\n  min-width: 120px;\n  max-width: 200px;\n}\n\n.FilterConditionOperator {\n  flex: 1;\n  min-width: 100px;\n  max-width: 180px;\n}\n\n.FilterConditionValue {\n  flex: 2;\n  min-width: 100px;\n}\n\n.FilterConditionValueSmall {\n  flex: 1;\n  min-width: 60px;\n  max-width: 120px;\n}\n\n.FilterConditionBetweenLabel {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 12px;\n  padding: 0 4px;\n}\n\n.FilterConditionDelete {\n  opacity: 0.5;\n  flex-shrink: 0;\n\n  &:hover {\n    opacity: 1;\n  }\n}\n\n// Connect toggle button - switches between static and connected mode\n.FilterConditionConnectToggle {\n  flex-shrink: 0;\n  opacity: 0.6;\n  transition: opacity 0.15s ease, color 0.15s ease;\n\n  &:hover {\n    opacity: 1;\n  }\n}\n\n// Port indicator for connected mode\n.FilterConditionPortIndicator {\n  display: flex;\n  align-items: center;\n  gap: 6px;\n  flex: 2;\n  min-width: 100px;\n  padding: 6px 10px;\n  background-color: var(--theme-color-primary-10);\n  border: 1px solid var(--theme-color-primary-25);\n  border-radius: 4px;\n  color: var(--theme-color-primary);\n}\n\n.FilterConditionPortDot {\n  color: var(--theme-color-primary);\n}\n\n.FilterConditionPortName {\n  font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;\n  font-size: 11px;\n  font-weight: 500;\n}\n\n// JSON Preview Styles\n.ByobFilterBuilderJson {\n  border-top: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-1);\n}\n\n.ByobFilterBuilderJsonHeader {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 6px 12px;\n  background-color: var(--theme-color-bg-2);\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.ByobFilterBuilderJsonActions {\n  display: flex;\n  gap: 4px;\n}\n\n.ByobFilterBuilderJsonPreview {\n  margin: 0;\n  padding: 12px;\n  font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;\n  font-size: 11px;\n  color: var(--theme-color-fg-default);\n  overflow-x: auto;\n  white-space: pre-wrap;\n  word-break: break-word;\n  max-height: 200px;\n  overflow-y: auto;\n}\n\n.ByobFilterBuilderJsonEditor {\n  width: 100%;\n  min-height: 150px;\n  padding: 12px;\n  font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;\n  font-size: 11px;\n  color: var(--theme-color-fg-default);\n  background-color: var(--theme-color-bg-1);\n  border: none;\n  resize: vertical;\n  outline: none;\n\n  &:focus {\n    outline: 1px solid var(--theme-color-primary);\n  }\n}\n\n.ByobFilterBuilderJsonError {\n  color: var(--theme-color-danger);\n  font-size: 12px;\n}\n\n// Filter Builder Button (compact property panel view)\n.FilterBuilderButton {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  padding: 8px 12px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-2);\n    border-color: var(--theme-color-border-highlight);\n  }\n}\n\n.FilterBuilderButtonContent {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"ByobFilterBuilder": `ByobFilterBuilder-module__ByobFilterBuilder--I61fW`,
	"ByobFilterBuilderHeader": `ByobFilterBuilder-module__ByobFilterBuilderHeader--tAGUE`,
	"ByobFilterBuilderActions": `ByobFilterBuilder-module__ByobFilterBuilderActions--ULEMB`,
	"ByobFilterBuilderContent": `ByobFilterBuilder-module__ByobFilterBuilderContent--ydHQ9`,
	"FilterGroup": `ByobFilterBuilder-module__FilterGroup--QlcCI`,
	"FilterGroupRoot": `ByobFilterBuilder-module__FilterGroupRoot--xn6AK`,
	"FilterGroupHeader": `ByobFilterBuilder-module__FilterGroupHeader--dQ2Pw`,
	"FilterGroupHeaderLeft": `ByobFilterBuilder-module__FilterGroupHeaderLeft--Sgwhh`,
	"FilterGroupDragHandle": `ByobFilterBuilder-module__FilterGroupDragHandle--uVyGc`,
	"FilterGroupDragging": `ByobFilterBuilder-module__FilterGroupDragging--mWUm3`,
	"FilterGroupDragOver": `ByobFilterBuilder-module__FilterGroupDragOver--TMDfA`,
	"FilterGroupDropIndicator": `ByobFilterBuilder-module__FilterGroupDropIndicator--bnHNK`,
	"FilterGroupCombinator": `ByobFilterBuilder-module__FilterGroupCombinator--jQMjx`,
	"FilterGroupDelete": `ByobFilterBuilder-module__FilterGroupDelete--OEaEA`,
	"FilterGroupConditions": `ByobFilterBuilder-module__FilterGroupConditions--m_6LP`,
	"FilterGroupCombinatorLabel": `ByobFilterBuilder-module__FilterGroupCombinatorLabel--DJuJ9`,
	"FilterGroupEmpty": `ByobFilterBuilder-module__FilterGroupEmpty--i3vHS`,
	"FilterGroupActions": `ByobFilterBuilder-module__FilterGroupActions--OtFDs`,
	"FilterCondition": `ByobFilterBuilder-module__FilterCondition--YE_5O`,
	"FilterConditionDragging": `ByobFilterBuilder-module__FilterConditionDragging--eeh5l`,
	"FilterConditionDragHandle": `ByobFilterBuilder-module__FilterConditionDragHandle--DKIpm`,
	"FilterConditionFields": `ByobFilterBuilder-module__FilterConditionFields--x2kPE`,
	"FilterConditionField": `ByobFilterBuilder-module__FilterConditionField--qcGDv`,
	"FilterConditionOperator": `ByobFilterBuilder-module__FilterConditionOperator--L1ehu`,
	"FilterConditionValue": `ByobFilterBuilder-module__FilterConditionValue--dK_ir`,
	"FilterConditionValueSmall": `ByobFilterBuilder-module__FilterConditionValueSmall--PqUM8`,
	"FilterConditionBetweenLabel": `ByobFilterBuilder-module__FilterConditionBetweenLabel--rsVxl`,
	"FilterConditionDelete": `ByobFilterBuilder-module__FilterConditionDelete--O8M94`,
	"FilterConditionConnectToggle": `ByobFilterBuilder-module__FilterConditionConnectToggle--yrVe1`,
	"FilterConditionPortIndicator": `ByobFilterBuilder-module__FilterConditionPortIndicator--no6el`,
	"FilterConditionPortDot": `ByobFilterBuilder-module__FilterConditionPortDot--ODN1Z`,
	"FilterConditionPortName": `ByobFilterBuilder-module__FilterConditionPortName--Vy4m9`,
	"ByobFilterBuilderJson": `ByobFilterBuilder-module__ByobFilterBuilderJson--UuJQ6`,
	"ByobFilterBuilderJsonHeader": `ByobFilterBuilder-module__ByobFilterBuilderJsonHeader--vrDgx`,
	"ByobFilterBuilderJsonActions": `ByobFilterBuilder-module__ByobFilterBuilderJsonActions--qsmlH`,
	"ByobFilterBuilderJsonPreview": `ByobFilterBuilder-module__ByobFilterBuilderJsonPreview--K598G`,
	"ByobFilterBuilderJsonEditor": `ByobFilterBuilder-module__ByobFilterBuilderJsonEditor--mAA5A`,
	"ByobFilterBuilderJsonError": `ByobFilterBuilder-module__ByobFilterBuilderJsonError--xLVoT`,
	"FilterBuilderButton": `ByobFilterBuilder-module__FilterBuilderButton--_IzZ1`,
	"FilterBuilderButtonContent": `ByobFilterBuilder-module__FilterBuilderButtonContent--cw3Bz`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 81246:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.MenuDialog-module__Root--erBwi{padding:4px;max-height:400px;overflow:hidden overlay}.MenuDialog-module__Root--erBwi.MenuDialog-module__is-width-small--r19s_{width:140px}.MenuDialog-module__Root--erBwi.MenuDialog-module__is-width-default--qBHFw{width:200px}.MenuDialog-module__Root--erBwi.MenuDialog-module__is-width-medium--QlgdT{width:250px}.MenuDialog-module__Root--erBwi.MenuDialog-module__is-width-large--YKtIL{width:400px}.MenuDialog-module__Item--Ol7jI{padding:8px;cursor:pointer;border-radius:1px;transition:background-color var(--speed-turbo) var(--easing-base)}.MenuDialog-module__Item--Ol7jI.MenuDialog-module__is-highlighted--hk9aS:not(.MenuDialog-module__is-disabled--wLDII){background-color:var(--theme-color-primary)}.MenuDialog-module__Item--Ol7jI.MenuDialog-module__is-highlighted--hk9aS:not(.MenuDialog-module__is-disabled--wLDII) h2{color:var(--theme-color-on-primary)}.MenuDialog-module__Item--Ol7jI.MenuDialog-module__is-highlighted--hk9aS:not(.MenuDialog-module__is-disabled--wLDII) .MenuDialog-module__Label--WBYRk span{color:var(--theme-color-on-primary)}.MenuDialog-module__Item--Ol7jI.MenuDialog-module__is-highlighted--hk9aS:not(.MenuDialog-module__is-disabled--wLDII) .MenuDialog-module__Icon--Y2TTO path{fill:var(--theme-color-on-primary)}.MenuDialog-module__Item--Ol7jI.MenuDialog-module__is-danger--GLepq .MenuDialog-module__Icon--Y2TTO path{fill:var(--theme-color-danger) !important}.MenuDialog-module__Item--Ol7jI.MenuDialog-module__is-disabled--wLDII .MenuDialog-module__Icon--Y2TTO path{fill:var(--theme-color-fg-muted)}.MenuDialog-module__Item--Ol7jI.MenuDialog-module__is-disabled--wLDII .MenuDialog-module__Label--WBYRk span{color:var(--theme-color-fg-muted)}.MenuDialog-module__Item--Ol7jI:not(.MenuDialog-module__has-component--TJCD4):not(.MenuDialog-module__is-highlighted--hk9aS):not(.MenuDialog-module__is-disabled--wLDII):hover{background-color:var(--theme-color-bg-3)}.MenuDialog-module__Item--Ol7jI:not(.MenuDialog-module__has-component--TJCD4):not(.MenuDialog-module__is-highlighted--hk9aS):not(.MenuDialog-module__is-disabled--wLDII):hover .MenuDialog-module__Label--WBYRk span{color:var(--theme-color-fg-highlight)}.MenuDialog-module__Item--Ol7jI:not(.MenuDialog-module__has-component--TJCD4):not(.MenuDialog-module__is-highlighted--hk9aS):not(.MenuDialog-module__is-disabled--wLDII):hover.MenuDialog-module__is-danger--GLepq .MenuDialog-module__Label--WBYRk span{color:var(--theme-color-danger)}.MenuDialog-module__Label--WBYRk{display:flex;align-items:center}.MenuDialog-module__Label--WBYRk.MenuDialog-module__has-bottom-spacing--udHKw{padding-bottom:8px}.MenuDialog-module__Icon--Y2TTO{margin:-4px 8px -4px 0}.MenuDialog-module__Icon--Y2TTO path{fill:var(--theme-color-fg-default-contrast)}.MenuDialog-module__Item--Ol7jI:not(.MenuDialog-module__has-component--TJCD4):not(.MenuDialog-module__is-disabled--wLDII):hover .MenuDialog-module__Icon--Y2TTO path{fill:var(--theme-color-fg-highlight)}.MenuDialog-module__Divider--PPzpE{width:calc(100% + 8px);height:1px;background-color:var(--theme-color-bg-3);margin:4px -4px}.MenuDialog-module__EndSlot--y0LPe{display:flex;align-items:center}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/popups/MenuDialog/MenuDialog.module.scss"],"names":[],"mappings":"AAAA,gCACE,WAAA,CACA,gBAAA,CACA,uBAAA,CAEA,yEACE,WAAA,CAGF,2EACE,WAAA,CAGF,0EACE,WAAA,CAGF,yEACE,WAAA,CAIJ,gCACE,WAAA,CACA,cAAA,CACA,iBAAA,CACA,iEAAA,CAEA,qHACE,2CAAA,CAEA,wHACE,mCAAA,CAGF,2JACE,mCAAA,CAGF,0JACE,kCAAA,CAKF,yGACE,yCAAA,CAKF,2GACE,gCAAA,CAGF,4GACE,iCAAA,CAIJ,+KACE,wCAAA,CAEA,qNACE,qCAAA,CAGF,yPACE,+BAAA,CAKN,iCACE,YAAA,CACA,kBAAA,CAEA,8EACE,kBAAA,CAIJ,gCACE,sBAAA,CAEA,qCACE,2CAAA,CAEA,qKACE,oCAAA,CAKN,mCACE,sBAAA,CACA,UAAA,CACA,wCAAA,CACA,eAAA,CAGF,mCACE,YAAA,CACA,kBAAA","sourcesContent":[".Root {\n  padding: 4px;\n  max-height: 400px;\n  overflow: hidden overlay;\n\n  &.is-width-small {\n    width: 140px;\n  }\n\n  &.is-width-default {\n    width: 200px;\n  }\n\n  &.is-width-medium {\n    width: 250px;\n  }\n\n  &.is-width-large {\n    width: 400px;\n  }\n}\n\n.Item {\n  padding: 8px;\n  cursor: pointer;\n  border-radius: 1px;\n  transition: background-color var(--speed-turbo) var(--easing-base);\n\n  &.is-highlighted:not(.is-disabled) {\n    background-color: var(--theme-color-primary);\n\n    h2 {\n      color: var(--theme-color-on-primary);\n    }\n\n    .Label span {\n      color: var(--theme-color-on-primary);\n    }\n\n    .Icon path {\n      fill: var(--theme-color-on-primary);\n    }\n  }\n\n  &.is-danger {\n    .Icon path {\n      fill: var(--theme-color-danger) !important;\n    }\n  }\n\n  &.is-disabled {\n    .Icon path {\n      fill: var(--theme-color-fg-muted);\n    }\n\n    .Label span {\n      color: var(--theme-color-fg-muted);\n    }\n  }\n\n  &:not(.has-component):not(.is-highlighted):not(.is-disabled):hover {\n    background-color: var(--theme-color-bg-3);\n\n    .Label span {\n      color: var(--theme-color-fg-highlight);\n    }\n\n    &.is-danger .Label span {\n      color: var(--theme-color-danger);\n    }\n  }\n}\n\n.Label {\n  display: flex;\n  align-items: center;\n\n  &.has-bottom-spacing {\n    padding-bottom: 8px;\n  }\n}\n\n.Icon {\n  margin: -4px 8px -4px 0;\n\n  path {\n    fill: var(--theme-color-fg-default-contrast);\n\n    .Item:not(.has-component):not(.is-disabled):hover & {\n      fill: var(--theme-color-fg-highlight);\n    }\n  }\n}\n\n.Divider {\n  width: calc(100% + 8px);\n  height: 1px;\n  background-color: var(--theme-color-bg-3);\n  margin: 4px -4px;\n}\n\n.EndSlot {\n  display: flex;\n  align-items: center;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `MenuDialog-module__Root--erBwi`,
	"is-width-small": `MenuDialog-module__is-width-small--r19s_`,
	"is-width-default": `MenuDialog-module__is-width-default--qBHFw`,
	"is-width-medium": `MenuDialog-module__is-width-medium--QlgdT`,
	"is-width-large": `MenuDialog-module__is-width-large--YKtIL`,
	"Item": `MenuDialog-module__Item--Ol7jI`,
	"is-highlighted": `MenuDialog-module__is-highlighted--hk9aS`,
	"is-disabled": `MenuDialog-module__is-disabled--wLDII`,
	"Label": `MenuDialog-module__Label--WBYRk`,
	"Icon": `MenuDialog-module__Icon--Y2TTO`,
	"is-danger": `MenuDialog-module__is-danger--GLepq`,
	"has-component": `MenuDialog-module__has-component--TJCD4`,
	"has-bottom-spacing": `MenuDialog-module__has-bottom-spacing--udHKw`,
	"Divider": `MenuDialog-module__Divider--PPzpE`,
	"EndSlot": `MenuDialog-module__EndSlot--y0LPe`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 81267:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   K: () => (/* binding */ Model)
/* harmony export */ });
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(47821);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_shared_model__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11138);


function shouldNotify(l, event) {
    if (l.event.constructor == Array && l.event.indexOf(event) !== -1) {
        return true;
    }
    else if (l.event === '*') {
        return true;
    }
    else if (l.event === event) {
        return true;
    }
    else if (l.event.indexOf !== undefined) {
        // Support for dot notation in subscription
        const index = l.event.indexOf(event);
        if (index > 0 && l.event[index - 1] === '.') {
            return true;
        }
    }
    return false;
}
class Model {
    constructor() {
        this.listeners = [];
        this.listenersOnce = [];
    }
    on(event, listener, group) {
        this.listeners.push({
            event: event,
            listener: listener,
            group: group
        });
        if (this.listeners.length > 10000) {
            console.log('Warning: we have more that 10000 listeners on this model, is this sane?');
        }
        return this;
    }
    once(event, listener) {
        this.listenersOnce.push({
            event: event,
            listener: listener
        });
        return this;
    }
    off(group) {
        for (let i = 0; i < this.listeners.length; i++) {
            if (this.listeners[i].group === group) {
                this.listeners.splice(i, 1);
                i--;
            }
        }
        return this;
    }
    notifyListeners(event, ...args) {
        if ((_shared_model__WEBPACK_IMPORTED_MODULE_0___default()._listenersEnabled) === false)
            return;
        for (let index = 0; index < this.listeners.length; index++) {
            const listener = this.listeners[index];
            if (shouldNotify(listener, event)) {
                listener.listener(...args);
            }
        }
        if (this.listenersOnce.length > 0) {
            this.listenersOnce = this.listenersOnce.filter((listener) => {
                if (shouldNotify(listener, event)) {
                    listener.listener(...args);
                    return false;
                }
                return true;
            });
        }
        // Dispatch global event
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_1__.EventDispatcher.instance.notifyListeners('Model.' + event.toString(), {
            model: this,
            args: args
        });
        return this;
    }
    removeAllListeners() {
        this.listeners = [];
        this.listenersOnce = [];
    }
}


/***/ }),

/***/ 81519:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSetting = function SvgSetting(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M11.8963 9.77684C10.4288 9.77684 9.23926 10.9664 9.23926 12.4339C9.23926 13.9013 10.4288 15.0909 11.8963 15.0909C13.3637 15.0909 14.5533 13.9013 14.5533 12.4339C14.5533 10.9664 13.3637 9.77684 11.8963 9.77684ZM7.73926 12.4339C7.73926 10.138 9.60042 8.27684 11.8963 8.27684C14.1921 8.27684 16.0533 10.138 16.0533 12.4339C16.0533 14.7297 14.1921 16.5909 11.8963 16.5909C9.60042 16.5909 7.73926 14.7297 7.73926 12.4339Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M9.08922 4.55168C9.02092 4.5107 8.95929 4.51255 8.92238 4.52652C8.05667 4.85401 7.25068 5.32167 6.53673 5.91074C6.50641 5.93576 6.47432 5.98803 6.47565 6.06726L6.50679 7.91672C6.51309 8.29108 6.39742 8.63701 6.21902 8.92164C6.14599 9.03814 6.07716 9.15723 6.01266 9.27867C5.85508 9.57535 5.61305 9.84826 5.2855 10.0297L3.66674 10.9262C3.59716 10.9648 3.56822 11.0186 3.56186 11.0568C3.41006 11.9689 3.41237 12.9 3.56869 13.8112C3.5752 13.8492 3.60407 13.9026 3.67304 13.9409L5.28882 14.8392C5.61351 15.0198 5.85517 15.2908 6.0124 15.5882C6.07949 15.7151 6.15089 15.8397 6.22646 15.9618C6.40175 16.2449 6.51307 16.5865 6.50686 16.9542L6.47568 18.8005C6.47434 18.8798 6.50646 18.9318 6.53646 18.9566C7.25199 19.5462 8.0611 20.012 8.93026 20.3348C8.96658 20.3483 9.02744 20.35 9.09525 20.3095L10.6839 19.3588C10.9961 19.1719 11.3449 19.0967 11.6775 19.107C11.8231 19.1115 11.9689 19.1115 12.1145 19.107C12.4477 19.0967 12.7971 19.1723 13.1098 19.3599L14.7033 20.316C14.7716 20.357 14.8332 20.3551 14.8702 20.3412C15.7359 20.0137 16.5419 19.546 17.2558 18.957C17.2861 18.9319 17.3182 18.8797 17.3169 18.8004L17.2858 16.951C17.2795 16.5766 17.3951 16.2307 17.5735 15.9461C17.6466 15.8295 17.7154 15.7105 17.7799 15.589C17.9375 15.2923 18.1795 15.0194 18.507 14.838L20.1258 13.9415C20.1954 13.9029 20.2243 13.849 20.2307 13.8108C20.3825 12.8988 20.3802 11.9677 20.2238 11.0564C20.2173 11.0185 20.1885 10.9651 20.1195 10.9268L18.5049 10.0291C18.1785 9.84764 17.9374 9.5753 17.7803 9.27937C17.7156 9.15769 17.6467 9.03837 17.5735 8.92164C17.3951 8.63701 17.2795 8.29108 17.2858 7.91672L17.3169 6.06724C17.3182 5.9879 17.2861 5.93587 17.2561 5.91115C16.5406 5.32153 15.7314 4.85567 14.8623 4.53286C14.826 4.51938 14.7651 4.51765 14.6973 4.55823L13.1087 5.50889C12.7964 5.69575 12.4476 5.771 12.1151 5.76068C11.9694 5.75616 11.8237 5.75615 11.678 5.76066C11.3449 5.77097 10.9954 5.69539 10.6828 5.5078L9.08922 4.55168ZM8.39163 3.12355C8.8946 2.93328 9.4343 3.00945 9.86096 3.26544L11.4545 4.22156C11.4944 4.24548 11.5539 4.26379 11.6316 4.26138C11.8082 4.25591 11.985 4.25592 12.1616 4.2614C12.2392 4.26381 12.2986 4.24559 12.3384 4.22176L13.927 3.2711C14.3501 3.01792 14.8846 2.94103 15.3845 3.12671C16.4104 3.50772 17.3654 4.0576 18.21 4.75354C18.6233 5.09409 18.825 5.59754 18.8167 6.09249L18.7855 7.94197C18.7848 7.98869 18.7992 8.05276 18.8445 8.12498C18.9367 8.27213 19.0236 8.42255 19.1051 8.57595C19.1449 8.65102 19.1931 8.69546 19.2338 8.71811L20.8484 9.61579C21.2784 9.85489 21.6122 10.278 21.7023 10.8028C21.8869 11.8795 21.8897 12.9796 21.7103 14.0571C21.6222 14.5864 21.2862 15.0135 20.8526 15.2537L19.2338 16.1502C19.1929 16.1728 19.1446 16.2174 19.1046 16.2926C19.0233 16.4457 18.9365 16.5958 18.8445 16.7427C18.7992 16.8149 18.7848 16.879 18.7855 16.9257L18.8167 18.7752C18.825 19.2703 18.6232 19.7734 18.2104 20.114C17.3696 20.8077 16.4204 21.3585 15.4009 21.7441C14.8979 21.9344 14.3582 21.8582 13.9316 21.6022L12.338 20.6461C12.2982 20.6222 12.2386 20.6039 12.1609 20.6063C11.9843 20.6118 11.8076 20.6118 11.6309 20.6063C11.5534 20.6039 11.4939 20.6221 11.4541 20.6459L9.8655 21.5966C9.44244 21.8498 8.90797 21.9267 8.40803 21.741C7.38213 21.36 6.42712 20.8101 5.58256 20.1142C5.16926 19.7736 4.96753 19.2701 4.97589 18.7751L5.00708 16.9288C5.00786 16.8825 4.99382 16.8203 4.95112 16.7514C4.85764 16.6004 4.76933 16.4463 4.68633 16.2893C4.64801 16.2168 4.60086 16.173 4.55992 16.1502L2.94414 15.2519C2.5141 15.0128 2.18031 14.5896 2.09029 14.0648C1.90559 12.9882 1.90287 11.8881 2.08222 10.8106C2.17031 10.2813 2.50632 9.85422 2.93999 9.61404L4.55875 8.71749C4.59963 8.69485 4.64794 8.65033 4.68792 8.57506C4.76923 8.42197 4.856 8.27185 4.94806 8.12498C4.99332 8.05276 5.00779 7.98869 5.007 7.94196L4.97586 6.09251C4.96753 5.59743 5.16937 5.09426 5.5821 4.75372C6.4229 4.05999 7.37211 3.50924 8.39163 3.12355Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSetting);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "c6e926c8ee9c48c56ff71d14023d27d1.svg");

/***/ }),

/***/ 81616:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* unused harmony export ReactComponent */
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = (/* unused pure expression or super */ null && (["title", "titleId"]));
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgWarningTriangle = function SvgWarningTriangle(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/React.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/React.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/React.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.1367 9.29317C12.5509 9.29317 12.8867 9.62895 12.8867 10.0432L12.8867 13.8015C12.8867 14.2157 12.5509 14.5515 12.1367 14.5515C11.7225 14.5515 11.3867 14.2157 11.3867 13.8015L11.3867 10.0432C11.3867 9.62895 11.7225 9.29317 12.1367 9.29317Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/React.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M11.0215 3.02737C11.3603 2.8309 11.745 2.72743 12.1367 2.72743C12.5283 2.72743 12.913 2.8309 13.2518 3.02737C13.59 3.22349 13.8705 3.50535 14.065 3.84448C14.0653 3.84506 14.0656 3.84565 14.066 3.84623L22.216 17.9235C22.4116 18.2623 22.5152 18.6473 22.5155 19.0384C22.5159 19.4296 22.4134 19.814 22.2184 20.1531C22.0234 20.4922 21.7428 20.7741 21.4045 20.9706C21.0663 21.167 20.6824 21.2712 20.2912 21.2726L20.2886 21.2726H3.98476L3.98212 21.2726C3.59096 21.2712 3.20703 21.167 2.86879 20.9706C2.53055 20.7741 2.24988 20.4922 2.0549 20.1531C1.85992 19.814 1.75747 19.4296 1.75781 19.0384C1.75816 18.6473 1.86129 18.2631 2.05687 17.9243L10.2074 3.84623C10.2077 3.84562 10.2081 3.84501 10.2084 3.8444C10.4029 3.5053 10.6834 3.22348 11.0215 3.02737ZM10.8583 4.21874L11.5074 4.59453L3.35591 18.6743C3.35585 18.6744 3.35596 18.6742 3.35591 18.6743C3.29186 18.7854 3.25793 18.9116 3.25781 19.0398C3.2577 19.1681 3.2913 19.2941 3.35526 19.4054C3.41922 19.5166 3.51128 19.6091 3.62222 19.6735C3.7329 19.7378 3.85849 19.7719 3.98648 19.7726H20.2868C20.4148 19.7719 20.5404 19.7378 20.6511 19.6735C20.7621 19.6091 20.8541 19.5166 20.9181 19.4054C20.982 19.2941 21.0156 19.1681 21.0155 19.0398C21.0154 18.9116 20.9817 18.7858 20.9177 18.6748C20.9176 18.6746 20.9178 18.6749 20.9177 18.6748L12.7641 4.59128C12.7008 4.48073 12.6095 4.38886 12.4993 4.32497C12.3891 4.26108 12.264 4.22743 12.1367 4.22743C12.0093 4.22743 11.8842 4.26108 11.774 4.32497C11.6638 4.38886 11.5725 4.48073 11.5092 4.59127L10.8583 4.21874Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/React.createElement("path", {
    d: "M12.843 16.8287C12.843 17.2188 12.5267 17.5351 12.1366 17.5351C11.7464 17.5351 11.4302 17.2188 11.4302 16.8287C11.4302 16.4386 11.7464 16.1223 12.1366 16.1223C12.5267 16.1223 12.843 16.4386 12.843 16.8287Z",
    fill: "#F5F5F5",
    stroke: "#F5F5F5",
    strokeWidth: 0.125
  })));
};
var ForwardRef = /*#__PURE__*/(/* unused pure expression or super */ null && (forwardRef(SvgWarningTriangle)));

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "4283a91da777159d6f9dc3835d867995.svg");

/***/ }),

/***/ 81882:
/***/ ((module) => {

"use strict";
module.exports = require("dugite");

/***/ }),

/***/ 82001:
/***/ ((module) => {

"use strict";


module.exports = function (item) {
  var content = item[1];
  var cssMapping = item[3];
  if (!cssMapping) {
    return content;
  }
  if (typeof btoa === "function") {
    var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(cssMapping))));
    var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
    var sourceMapping = "/*# ".concat(data, " */");
    return [content].concat([sourceMapping]).join("\n");
  }
  return [content].join("\n");
};

/***/ }),

/***/ 82045:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.GitHubConnectButton-module__Root--KonIy{display:flex;flex-direction:row;align-items:center;gap:var(--spacing-8)}.GitHubConnectButton-module__Description--xPCfW{display:none}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/preview/launcher/Launcher/components/GitHubConnectButton/GitHubConnectButton.module.scss"],"names":[],"mappings":"AAAA,yCACE,YAAA,CACA,kBAAA,CACA,kBAAA,CACA,oBAAA,CAGF,gDACE,YAAA","sourcesContent":[".Root {\n  display: flex;\n  flex-direction: row;\n  align-items: center;\n  gap: var(--spacing-8);\n}\n\n.Description {\n  display: none; /* Hide description to keep header compact */\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `GitHubConnectButton-module__Root--KonIy`,
	"Description": `GitHubConnectButton-module__Description--xPCfW`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 82171:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/* marker zone */

.monaco-editor .peekview-widget .head .peekview-title .severity-icon {
	display: inline-block;
	vertical-align: text-top;
	margin-right: 4px;
}

.monaco-editor .marker-widget {
	text-overflow: ellipsis;
	white-space: nowrap;
}

.monaco-editor .marker-widget > .stale {
	opacity: 0.6;
	font-style: italic;
}

.monaco-editor .marker-widget .title {
	display: inline-block;
	padding-right: 5px;
}

.monaco-editor .marker-widget .descriptioncontainer {
	position: absolute;
	white-space: pre;
	user-select: text;
	-webkit-user-select: text;
	-ms-user-select: text;
	padding: 8px 12px 0 20px;
}

.monaco-editor .marker-widget .descriptioncontainer .message {
	display: flex;
	flex-direction: column;
}

.monaco-editor .marker-widget .descriptioncontainer .message .details {
	padding-left: 6px;
}

.monaco-editor .marker-widget .descriptioncontainer .message .source,
.monaco-editor .marker-widget .descriptioncontainer .message span.code {
	opacity: 0.6;
}

.monaco-editor .marker-widget .descriptioncontainer .message a.code-link {
	opacity: 0.6;
	color: inherit;
}

.monaco-editor .marker-widget .descriptioncontainer .message a.code-link:before {
	content: '(';
}

.monaco-editor .marker-widget .descriptioncontainer .message a.code-link:after {
	content: ')';
}

.monaco-editor .marker-widget .descriptioncontainer .message a.code-link > span {
	text-decoration: underline;
	/** Hack to force underline to show **/
	border-bottom: 1px solid transparent;
	text-underline-position: under;
	color: var(--vscode-textLink-foreground);
}

.monaco-editor .marker-widget .descriptioncontainer .message a.code-link > span {
	color: var(--vscode-textLink-activeForeground);
}

.monaco-editor .marker-widget .descriptioncontainer .filename {
	cursor: pointer;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoError/browser/media/gotoErrorWidget.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F,gBAAgB;;AAEhB;CACC,qBAAqB;CACrB,wBAAwB;CACxB,iBAAiB;AAClB;;AAEA;CACC,uBAAuB;CACvB,mBAAmB;AACpB;;AAEA;CACC,YAAY;CACZ,kBAAkB;AACnB;;AAEA;CACC,qBAAqB;CACrB,kBAAkB;AACnB;;AAEA;CACC,kBAAkB;CAClB,gBAAgB;CAChB,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;CACrB,wBAAwB;AACzB;;AAEA;CACC,aAAa;CACb,sBAAsB;AACvB;;AAEA;CACC,iBAAiB;AAClB;;AAEA;;CAEC,YAAY;AACb;;AAEA;CACC,YAAY;CACZ,cAAc;AACf;;AAEA;CACC,YAAY;AACb;;AAEA;CACC,YAAY;AACb;;AAEA;CACC,0BAA0B;CAC1B,sCAAsC;CACtC,oCAAoC;CACpC,8BAA8B;CAC9B,wCAAwC;AACzC;;AAEA;CACC,8CAA8C;AAC/C;;AAEA;CACC,eAAe;AAChB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/* marker zone */\n\n.monaco-editor .peekview-widget .head .peekview-title .severity-icon {\n\tdisplay: inline-block;\n\tvertical-align: text-top;\n\tmargin-right: 4px;\n}\n\n.monaco-editor .marker-widget {\n\ttext-overflow: ellipsis;\n\twhite-space: nowrap;\n}\n\n.monaco-editor .marker-widget > .stale {\n\topacity: 0.6;\n\tfont-style: italic;\n}\n\n.monaco-editor .marker-widget .title {\n\tdisplay: inline-block;\n\tpadding-right: 5px;\n}\n\n.monaco-editor .marker-widget .descriptioncontainer {\n\tposition: absolute;\n\twhite-space: pre;\n\tuser-select: text;\n\t-webkit-user-select: text;\n\t-ms-user-select: text;\n\tpadding: 8px 12px 0 20px;\n}\n\n.monaco-editor .marker-widget .descriptioncontainer .message {\n\tdisplay: flex;\n\tflex-direction: column;\n}\n\n.monaco-editor .marker-widget .descriptioncontainer .message .details {\n\tpadding-left: 6px;\n}\n\n.monaco-editor .marker-widget .descriptioncontainer .message .source,\n.monaco-editor .marker-widget .descriptioncontainer .message span.code {\n\topacity: 0.6;\n}\n\n.monaco-editor .marker-widget .descriptioncontainer .message a.code-link {\n\topacity: 0.6;\n\tcolor: inherit;\n}\n\n.monaco-editor .marker-widget .descriptioncontainer .message a.code-link:before {\n\tcontent: '(';\n}\n\n.monaco-editor .marker-widget .descriptioncontainer .message a.code-link:after {\n\tcontent: ')';\n}\n\n.monaco-editor .marker-widget .descriptioncontainer .message a.code-link > span {\n\ttext-decoration: underline;\n\t/** Hack to force underline to show **/\n\tborder-bottom: 1px solid transparent;\n\ttext-underline-position: under;\n\tcolor: var(--vscode-textLink-foreground);\n}\n\n.monaco-editor .marker-widget .descriptioncontainer .message a.code-link > span {\n\tcolor: var(--vscode-textLink-activeForeground);\n}\n\n.monaco-editor .marker-widget .descriptioncontainer .filename {\n\tcursor: pointer;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 82263:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSearchCorner = function SvgSearchCorner(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M8.9165 11.057C8.9165 9.68322 10.0301 8.5696 11.4039 8.5696C12.7776 8.5696 13.8912 9.68322 13.8912 11.057C13.8912 12.4307 12.7776 13.5443 11.4039 13.5443C10.0301 13.5443 8.9165 12.4307 8.9165 11.057ZM11.4039 7.0696C9.20171 7.0696 7.4165 8.8548 7.4165 11.057C7.4165 13.2591 9.20171 15.0443 11.4039 15.0443C12.0737 15.0443 12.7049 14.8792 13.2591 14.5873L15.5771 16.9053C15.87 17.1982 16.3448 17.1982 16.6377 16.9053C16.9306 16.6124 16.9306 16.1376 16.6377 15.8447L14.4376 13.6446C15.0322 12.9481 15.3912 12.0445 15.3912 11.057C15.3912 8.8548 13.606 7.0696 11.4039 7.0696Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M15.5381 4.6525C15.5381 4.23828 15.8739 3.9025 16.2881 3.9025H19.7475C20.1617 3.9025 20.4975 4.23828 20.4975 4.6525V8.1119C20.4975 8.52612 20.1617 8.8619 19.7475 8.8619C19.3333 8.8619 18.9975 8.52612 18.9975 8.1119V5.4025H16.2881C15.8739 5.4025 15.5381 5.06671 15.5381 4.6525Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M19.7475 15.6645C20.1617 15.6645 20.4975 16.0002 20.4975 16.4145V19.8739C20.4975 20.2881 20.1617 20.6239 19.7475 20.6239H16.2881C15.8739 20.6239 15.5381 20.2881 15.5381 19.8739C15.5381 19.4597 15.8739 19.1239 16.2881 19.1239H18.9975V16.4145C18.9975 16.0002 19.3333 15.6645 19.7475 15.6645Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.77588 4.6525C3.77588 4.23828 4.11167 3.9025 4.52588 3.9025H7.98529C8.3995 3.9025 8.73529 4.23828 8.73529 4.6525C8.73529 5.06671 8.3995 5.4025 7.98529 5.4025H5.27588V8.1119C5.27588 8.52612 4.94009 8.8619 4.52588 8.8619C4.11167 8.8619 3.77588 8.52612 3.77588 8.1119V4.6525Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.77588 19.8738C3.77588 20.288 4.11167 20.6238 4.52588 20.6238H7.98529C8.3995 20.6238 8.73529 20.288 8.73529 19.8738C8.73529 19.4596 8.3995 19.1238 7.98529 19.1238H5.27588V16.4144C5.27588 16.0002 4.94009 15.6644 4.52588 15.6644C4.11167 15.6644 3.77588 16.0002 3.77588 16.4144V19.8738Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSearchCorner);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "77d39c726ea04ad274f6f995f44ae197.svg");

/***/ }),

/***/ 82306:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Beta = void 0;
const tslib_1 = __webpack_require__(84499);
const resource_1 = __webpack_require__(39929);
const FilesAPI = tslib_1.__importStar(__webpack_require__(39773));
const files_1 = __webpack_require__(39773);
const ModelsAPI = tslib_1.__importStar(__webpack_require__(98058));
const models_1 = __webpack_require__(98058);
const MessagesAPI = tslib_1.__importStar(__webpack_require__(47511));
const messages_1 = __webpack_require__(47511);
const SkillsAPI = tslib_1.__importStar(__webpack_require__(59215));
const skills_1 = __webpack_require__(59215);
class Beta extends resource_1.APIResource {
    constructor() {
        super(...arguments);
        this.models = new ModelsAPI.Models(this._client);
        this.messages = new MessagesAPI.Messages(this._client);
        this.files = new FilesAPI.Files(this._client);
        this.skills = new SkillsAPI.Skills(this._client);
    }
}
exports.Beta = Beta;
Beta.Models = models_1.Models;
Beta.Messages = messages_1.Messages;
Beta.Files = files_1.Files;
Beta.Skills = skills_1.Skills;
//# sourceMappingURL=beta.js.map

/***/ }),

/***/ 82433:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.propertyeditor-item {
    color: #f8f8f8;
    min-height: 33px;
    display: flex;
    align-items: center;
    margin-top: 1px;
    margin-bottom: 1px;
}

.propertyeditor-item-input {
    background-color: #222222;
    color: #dddddd;
    border: none;
    display: block;
    padding:0 0 0 10px;
    box-sizing: border-box;
    font-size: 12px;
    align-self: stretch;
    margin-left: 10px;
    min-width: 10px;
}

.propertyeditor-color-preview {
    width: 33px;
    align-self: stretch;
    flex-shrink: 0;
}

.propertyeditor-enums-dropdown {
    left: 0;
    right: 0;
    top: 33px;
    align-items: stretch;
    display: flex;
    flex-direction: column;
    flex-shrink: 0
}

.propertyeditor-unit-dropdown {
    margin-top: 1px;
    width: 33px;
    height: 33px;
    align-self: stretch;
    position: relative;
    line-height: 33px;
    margin-left: 2px;
    padding-left: 0;
    align-items: center;
    display: flex;
    flex-direction: column;
    flex-shrink: 0
}

.propertyeditor-unit-dropdown-list {
    width: 100%;
    top: 33px;
    right: 0;
    line-height: 33px;
}

.propertyeditor-unit-dropdown-list > div {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
}`, "",{"version":3,"sources":["webpack://./src/editor/src/reactcomponents/propertyeditors.css"],"names":[],"mappings":"AAAA;IACI,cAAc;IACd,gBAAgB;IAChB,aAAa;IACb,mBAAmB;IACnB,eAAe;IACf,kBAAkB;AACtB;;AAEA;IACI,yBAAyB;IACzB,cAAc;IACd,YAAY;IACZ,cAAc;IACd,kBAAkB;IAClB,sBAAsB;IACtB,eAAe;IACf,mBAAmB;IACnB,iBAAiB;IACjB,eAAe;AACnB;;AAEA;IACI,WAAW;IACX,mBAAmB;IACnB,cAAc;AAClB;;AAEA;IACI,OAAO;IACP,QAAQ;IACR,SAAS;IACT,oBAAoB;IACpB,aAAa;IACb,sBAAsB;IACtB;AACJ;;AAEA;IACI,eAAe;IACf,WAAW;IACX,YAAY;IACZ,mBAAmB;IACnB,kBAAkB;IAClB,iBAAiB;IACjB,gBAAgB;IAChB,eAAe;IACf,mBAAmB;IACnB,aAAa;IACb,sBAAsB;IACtB;AACJ;;AAEA;IACI,WAAW;IACX,SAAS;IACT,QAAQ;IACR,iBAAiB;AACrB;;AAEA;IACI,aAAa;IACb,mBAAmB;IACnB,uBAAuB;IACvB,UAAU;AACd","sourcesContent":[".propertyeditor-item {\n    color: #f8f8f8;\n    min-height: 33px;\n    display: flex;\n    align-items: center;\n    margin-top: 1px;\n    margin-bottom: 1px;\n}\n\n.propertyeditor-item-input {\n    background-color: #222222;\n    color: #dddddd;\n    border: none;\n    display: block;\n    padding:0 0 0 10px;\n    box-sizing: border-box;\n    font-size: 12px;\n    align-self: stretch;\n    margin-left: 10px;\n    min-width: 10px;\n}\n\n.propertyeditor-color-preview {\n    width: 33px;\n    align-self: stretch;\n    flex-shrink: 0;\n}\n\n.propertyeditor-enums-dropdown {\n    left: 0;\n    right: 0;\n    top: 33px;\n    align-items: stretch;\n    display: flex;\n    flex-direction: column;\n    flex-shrink: 0\n}\n\n.propertyeditor-unit-dropdown {\n    margin-top: 1px;\n    width: 33px;\n    height: 33px;\n    align-self: stretch;\n    position: relative;\n    line-height: 33px;\n    margin-left: 2px;\n    padding-left: 0;\n    align-items: center;\n    display: flex;\n    flex-direction: column;\n    flex-shrink: 0\n}\n\n.propertyeditor-unit-dropdown-list {\n    width: 100%;\n    top: 33px;\n    right: 0;\n    line-height: 33px;\n}\n\n.propertyeditor-unit-dropdown-list > div {\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    padding: 0;\n}"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 82470:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Card-module__Root--HLlkd{border-radius:2px}.Card-module__Root--HLlkd.Card-module__is-bg-1--ir1gD,.Card-module__Root--HLlkd.Card-module__is-bg-1-on-hover--rvmKZ:hover{background-color:var(--theme-color-bg-1)}.Card-module__Root--HLlkd.Card-module__is-bg-2--pT2pd,.Card-module__Root--HLlkd.Card-module__is-bg-2-on-hover--wTBiR:hover{background-color:var(--theme-color-bg-2)}.Card-module__Root--HLlkd.Card-module__is-bg-3--XBwUa,.Card-module__Root--HLlkd.Card-module__is-bg-3-on-hover--LCc0z:hover{background-color:var(--theme-color-bg-3)}.Card-module__Root--HLlkd.Card-module__is-bg-4--VcCUe,.Card-module__Root--HLlkd.Card-module__is-bg-4-on-hover--_4pEi:hover{background-color:var(--theme-color-bg-4)}.Card-module__Root--HLlkd.Card-module__has-hover-state--tTt06{cursor:pointer}.Card-module__Root--HLlkd.Card-module__is-padding-small--BCQ1U{padding:8px}.Card-module__Root--HLlkd.Card-module__is-padding-default--eHTV7{padding:16px}.Card-module__Root--HLlkd.Card-module__is-padding-large--P6HLM{padding:32px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/common/Card/Card.module.scss"],"names":[],"mappings":"AAAA,0BACE,iBAAA,CAGE,2HAEE,wCAAA,CAGF,2HAEE,wCAAA,CAGF,2HAEE,wCAAA,CAGF,2HAEE,wCAAA,CAIJ,8DACE,cAAA,CAIA,+DACE,WAAA,CAGF,iEACE,YAAA,CAGF,+DACE,YAAA","sourcesContent":[".Root {\n  border-radius: 2px;\n\n  &.is-bg {\n    &-1,\n    &-1-on-hover:hover {\n      background-color: var(--theme-color-bg-1);\n    }\n\n    &-2,\n    &-2-on-hover:hover {\n      background-color: var(--theme-color-bg-2);\n    }\n\n    &-3,\n    &-3-on-hover:hover {\n      background-color: var(--theme-color-bg-3);\n    }\n\n    &-4,\n    &-4-on-hover:hover {\n      background-color: var(--theme-color-bg-4);\n    }\n  }\n\n  &.has-hover-state {\n    cursor: pointer;\n  }\n\n  &.is-padding {\n    &-small {\n      padding: 8px;\n    }\n\n    &-default {\n      padding: 16px;\n    }\n\n    &-large {\n      padding: 32px;\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Card-module__Root--HLlkd`,
	"is-bg-1": `Card-module__is-bg-1--ir1gD`,
	"is-bg-1-on-hover": `Card-module__is-bg-1-on-hover--rvmKZ`,
	"is-bg-2": `Card-module__is-bg-2--pT2pd`,
	"is-bg-2-on-hover": `Card-module__is-bg-2-on-hover--wTBiR`,
	"is-bg-3": `Card-module__is-bg-3--XBwUa`,
	"is-bg-3-on-hover": `Card-module__is-bg-3-on-hover--LCc0z`,
	"is-bg-4": `Card-module__is-bg-4--VcCUe`,
	"is-bg-4-on-hover": `Card-module__is-bg-4-on-hover--_4pEi`,
	"has-hover-state": `Card-module__has-hover-state--tTt06`,
	"is-padding-small": `Card-module__is-padding-small--BCQ1U`,
	"is-padding-default": `Card-module__is-padding-default--eHTV7`,
	"is-padding-large": `Card-module__is-padding-large--P6HLM`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 82519:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Batches = void 0;
const resource_1 = __webpack_require__(39929);
const pagination_1 = __webpack_require__(92081);
const headers_1 = __webpack_require__(79973);
const jsonl_1 = __webpack_require__(60535);
const error_1 = __webpack_require__(92651);
const path_1 = __webpack_require__(20854);
class Batches extends resource_1.APIResource {
    /**
     * Send a batch of Message creation requests.
     *
     * The Message Batches API can be used to process multiple Messages API requests at
     * once. Once a Message Batch is created, it begins processing immediately. Batches
     * can take up to 24 hours to complete.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * const betaMessageBatch =
     *   await client.beta.messages.batches.create({
     *     requests: [
     *       {
     *         custom_id: 'my-custom-id-1',
     *         params: {
     *           max_tokens: 1024,
     *           messages: [
     *             { content: 'Hello, world', role: 'user' },
     *           ],
     *           model: 'claude-sonnet-4-5-20250929',
     *         },
     *       },
     *     ],
     *   });
     * ```
     */
    create(params, options) {
        const { betas, ...body } = params;
        return this._client.post('/v1/messages/batches?beta=true', {
            body,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * This endpoint is idempotent and can be used to poll for Message Batch
     * completion. To access the results of a Message Batch, make a request to the
     * `results_url` field in the response.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * const betaMessageBatch =
     *   await client.beta.messages.batches.retrieve(
     *     'message_batch_id',
     *   );
     * ```
     */
    retrieve(messageBatchID, params = {}, options) {
        const { betas } = params ?? {};
        return this._client.get((0, path_1.path) `/v1/messages/batches/${messageBatchID}?beta=true`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * List all Message Batches within a Workspace. Most recently created batches are
     * returned first.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * // Automatically fetches more pages as needed.
     * for await (const betaMessageBatch of client.beta.messages.batches.list()) {
     *   // ...
     * }
     * ```
     */
    list(params = {}, options) {
        const { betas, ...query } = params ?? {};
        return this._client.getAPIList('/v1/messages/batches?beta=true', (pagination_1.Page), {
            query,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * Delete a Message Batch.
     *
     * Message Batches can only be deleted once they've finished processing. If you'd
     * like to delete an in-progress batch, you must first cancel it.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * const betaDeletedMessageBatch =
     *   await client.beta.messages.batches.delete(
     *     'message_batch_id',
     *   );
     * ```
     */
    delete(messageBatchID, params = {}, options) {
        const { betas } = params ?? {};
        return this._client.delete((0, path_1.path) `/v1/messages/batches/${messageBatchID}?beta=true`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * Batches may be canceled any time before processing ends. Once cancellation is
     * initiated, the batch enters a `canceling` state, at which time the system may
     * complete any in-progress, non-interruptible requests before finalizing
     * cancellation.
     *
     * The number of canceled requests is specified in `request_counts`. To determine
     * which requests were canceled, check the individual results within the batch.
     * Note that cancellation may not result in any canceled requests if they were
     * non-interruptible.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * const betaMessageBatch =
     *   await client.beta.messages.batches.cancel(
     *     'message_batch_id',
     *   );
     * ```
     */
    cancel(messageBatchID, params = {}, options) {
        const { betas } = params ?? {};
        return this._client.post((0, path_1.path) `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
                options?.headers,
            ]),
        });
    }
    /**
     * Streams the results of a Message Batch as a `.jsonl` file.
     *
     * Each line in the file is a JSON object containing the result of a single request
     * in the Message Batch. Results are not guaranteed to be in the same order as
     * requests. Use the `custom_id` field to match results to requests.
     *
     * Learn more about the Message Batches API in our
     * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
     *
     * @example
     * ```ts
     * const betaMessageBatchIndividualResponse =
     *   await client.beta.messages.batches.results(
     *     'message_batch_id',
     *   );
     * ```
     */
    async results(messageBatchID, params = {}, options) {
        const batch = await this.retrieve(messageBatchID);
        if (!batch.results_url) {
            throw new error_1.AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
        }
        const { betas } = params ?? {};
        return this._client
            .get(batch.results_url, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                {
                    'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),
                    Accept: 'application/binary',
                },
                options?.headers,
            ]),
            stream: true,
            __binaryResponse: true,
        })
            ._thenUnwrap((_, props) => jsonl_1.JSONLDecoder.fromResponse(props.response, props.controller));
    }
}
exports.Batches = Batches;
//# sourceMappingURL=batches.js.map

/***/ }),

/***/ 82579:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.NodeLibrary-module__Root--NmgOn{display:flex;flex-direction:column}.NodeLibrary-module__SearchContainer--n2sN1{flex:0 0 45px;padding:0 15px 16px}.NodeLibrary-module__Content--o4Qnm{display:flex;align-items:stretch;flex-grow:1;max-height:calc(100% - 63px);background-color:var(--theme-color-bg-2);position:relative;border-top:1px solid var(--theme-color-bg-1);box-sizing:border-box}.NodeLibrary-module__Content--o4Qnm:after{content:"";position:absolute;width:1px;left:280px;top:0;bottom:0;background-color:var(--theme-color-bg-1);z-index:20}.NodeLibrary-module__Navbar--ccsAD{flex:0 0 35%;overflow-y:overlay;overflow-x:hidden;z-index:0;height:100%;display:flex;flex-direction:column;scroll-behavior:smooth;position:relative}.NodeLibrary-module__NavbarInner--uLhdo{align-items:stretch;flex-grow:1;display:flex;flex-direction:column;background-color:var(--theme-color-bg-2);justify-content:space-between}.NodeLibrary-module__ScrollbarContainer--RL3th::-webkit-scrollbar{width:4px;height:6px;cursor:pointer}.NodeLibrary-module__ScrollbarContainer--RL3th::-webkit-scrollbar-thumb{background-color:var(--theme-color-bg-5)}.NodeLibrary-module__FullDocsButton--t7GNx{display:inline-block;position:absolute;right:32px}.NodeLibrary-module__Docs--LRJcs{flex-grow:1;padding:20px 32px;overflow-x:hidden;overflow-y:overlay;z-index:0;background-color:var(--theme-color-bg-2);position:relative}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/NodePicker/tabs/NodeLibrary/NodeLibrary.module.scss"],"names":[],"mappings":"AAIA,iCACE,YAAA,CACA,qBAAA,CAGF,4CACE,aAAA,CACA,mBAAA,CAGF,oCACE,YAAA,CACA,mBAAA,CACA,WAAA,CACA,4BAAA,CACA,wCAAA,CACA,iBAAA,CACA,4CAAA,CACA,qBAAA,CAEA,0CACE,UAAA,CACA,iBAAA,CACA,SAAA,CACA,UAAA,CACA,KAAA,CACA,QAAA,CACA,wCAAA,CACA,UAAA,CAIJ,mCACE,YAAA,CACA,kBAAA,CACA,iBAAA,CACA,SAAA,CACA,WAAA,CACA,YAAA,CACA,qBAAA,CACA,sBAAA,CACA,iBAAA,CAGF,wCACE,mBAAA,CACA,WAAA,CACA,YAAA,CACA,qBAAA,CACA,wCAAA,CACA,6BAAA,CAIA,kEACE,SAzDgB,CA0DhB,UAAA,CACA,cAAA,CAGF,wEACE,wCAAA,CAIJ,2CACE,oBAAA,CACA,iBAAA,CACA,UAAA,CAGF,iCACE,WAAA,CACA,iBAAA,CACA,iBAAA,CACA,kBAAA,CACA,SAAA,CACA,wCAAA,CACA,iBAAA","sourcesContent":["$_search-bar-height: 45px;\n$_header-height: 63px;\n$_scroll-bar-width: 4px;\n\n.Root {\n  display: flex;\n  flex-direction: column;\n}\n\n.SearchContainer {\n  flex: 0 0 $_search-bar-height;\n  padding: 0 15px 16px;\n}\n\n.Content {\n  display: flex;\n  align-items: stretch;\n  flex-grow: 1;\n  max-height: calc(100% - #{$_header-height});\n  background-color: var(--theme-color-bg-2);\n  position: relative;\n  border-top: 1px solid var(--theme-color-bg-1);\n  box-sizing: border-box;\n\n  &:after {\n    content: '';\n    position: absolute;\n    width: 1px;\n    left: 280px; // TODO: make this dynamic in the future maybe\n    top: 0;\n    bottom: 0;\n    background-color: var(--theme-color-bg-1);\n    z-index: 20;\n  }\n}\n\n.Navbar {\n  flex: 0 0 35%;\n  overflow-y: overlay;\n  overflow-x: hidden;\n  z-index: 0;\n  height: 100%;\n  display: flex;\n  flex-direction: column;\n  scroll-behavior: smooth;\n  position: relative;\n}\n\n.NavbarInner {\n  align-items: stretch;\n  flex-grow: 1;\n  display: flex;\n  flex-direction: column;\n  background-color: var(--theme-color-bg-2);\n  justify-content: space-between;\n}\n\n.ScrollbarContainer {\n  &::-webkit-scrollbar {\n    width: $_scroll-bar-width;\n    height: 6px;\n    cursor: pointer;\n  }\n\n  &::-webkit-scrollbar-thumb {\n    background-color: var(--theme-color-bg-5);\n  }\n}\n\n.FullDocsButton {\n  display: inline-block;\n  position: absolute;\n  right: 32px;\n}\n\n.Docs {\n  flex-grow: 1;\n  padding: 20px 32px;\n  overflow-x: hidden;\n  overflow-y: overlay;\n  z-index: 0;\n  background-color: var(--theme-color-bg-2);\n  position: relative;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `NodeLibrary-module__Root--NmgOn`,
	"SearchContainer": `NodeLibrary-module__SearchContainer--n2sN1`,
	"Content": `NodeLibrary-module__Content--o4Qnm`,
	"Navbar": `NodeLibrary-module__Navbar--ccsAD`,
	"NavbarInner": `NodeLibrary-module__NavbarInner--uLhdo`,
	"ScrollbarContainer": `NodeLibrary-module__ScrollbarContainer--RL3th`,
	"FullDocsButton": `NodeLibrary-module__FullDocsButton--t7GNx`,
	"Docs": `NodeLibrary-module__Docs--LRJcs`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 82626:
/***/ ((module) => {

"use strict";
module.exports = require("async");

/***/ }),

/***/ 82700:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
.monaco-editor .lines-decorations {
	position: absolute;
	top: 0;
	background: white;
}

/*
	Keeping name short for faster parsing.
	cldr = core lines decorations rendering (div)
*/
.monaco-editor .margin-view-overlays .cldr {
	position: absolute;
	height: 100%;
}`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/linesDecorations/linesDecorations.css"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;CACC,kBAAkB;CAClB,MAAM;CACN,iBAAiB;AAClB;;AAEA;;;CAGC;AACD;CACC,kBAAkB;CAClB,YAAY;AACb","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n.monaco-editor .lines-decorations {\n\tposition: absolute;\n\ttop: 0;\n\tbackground: white;\n}\n\n/*\n\tKeeping name short for faster parsing.\n\tcldr = core lines decorations rendering (div)\n*/\n.monaco-editor .margin-view-overlays .cldr {\n\tposition: absolute;\n\theight: 100%;\n}"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 83171:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.search-panel-module__SearchResultItem--Y3rGm{padding:18px;transition:background-color var(--speed-turbo) var(--easing-base);cursor:pointer}.search-panel-module__SearchResultItem--Y3rGm:not(:first-child){border-top:1px solid var(--theme-color-bg-1)}.search-panel-module__SearchResultItem--Y3rGm:hover{background-color:var(--theme-color-bg-4)}.search-panel-module__SearchResultItem--Y3rGm:hover p,.search-panel-module__SearchResultItem--Y3rGm:hover h2{color:var(--theme-color-on-secondary)}.search-panel-module__SearchResultItem--Y3rGm.search-panel-module__is-active--B8z_A{background-color:var(--theme-color-bg-4)}.search-panel-module__SearchResultItem--Y3rGm.search-panel-module__is-active--B8z_A:hover{background-color:var(--theme-color-bg-5)}.search-panel-module__SearchInput--IyXZ9{position:sticky;top:0;border-bottom:1px solid var(--theme-color-bg-1)}.search-panel-module__SearchResults--rkC8z{overflow:hidden overlay}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/search-panel/search-panel.module.scss"],"names":[],"mappings":"AAAA,8CACE,YAAA,CACA,iEAAA,CACA,cAAA,CAEA,gEACE,4CAAA,CAGF,oDACE,wCAAA,CAEA,6GAEE,qCAAA,CAIJ,oFACE,wCAAA,CAEA,0FACE,wCAAA,CAKN,yCACE,eAAA,CACA,KAAA,CACA,+CAAA,CAGF,2CACE,uBAAA","sourcesContent":[".SearchResultItem {\n  padding: 18px;\n  transition: background-color var(--speed-turbo) var(--easing-base);\n  cursor: pointer;\n\n  &:not(:first-child) {\n    border-top: 1px solid var(--theme-color-bg-1);\n  }\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n\n    p,\n    h2 {\n      color: var(--theme-color-on-secondary);\n    }\n  }\n\n  &.is-active {\n    background-color: var(--theme-color-bg-4);\n\n    &:hover {\n      background-color: var(--theme-color-bg-5);\n    }\n  }\n}\n\n.SearchInput {\n  position: sticky;\n  top: 0;\n  border-bottom: 1px solid var(--theme-color-bg-1);\n}\n\n.SearchResults {\n  overflow: hidden overlay;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"SearchResultItem": `search-panel-module__SearchResultItem--Y3rGm`,
	"is-active": `search-panel-module__is-active--B8z_A`,
	"SearchInput": `search-panel-module__SearchInput--IyXZ9`,
	"SearchResults": `search-panel-module__SearchResults--rkC8z`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 83431:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  mR: () => (/* reexport */ PropertyPanelInput),
  A2: () => (/* reexport */ PropertyPanelInputType),
  eh: () => (/* reexport */ PropertyPanelRow)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/popups/Tooltip/index.ts + 2 modules
var Tooltip = __webpack_require__(87073);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/property-panel/ExpressionInput/ExpressionInput.module.scss
var ExpressionInput_module = __webpack_require__(97217);
;// ../noodl-core-ui/src/components/property-panel/ExpressionInput/ExpressionInput.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(ExpressionInput_module/* default */.A, options);




       /* harmony default export */ const ExpressionInput_ExpressionInput_module = (ExpressionInput_module/* default */.A && ExpressionInput_module/* default */.A.locals ? ExpressionInput_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/property-panel/ExpressionInput/ExpressionInput.tsx




/**
 * ExpressionInput
 *
 * A specialized input field for entering JavaScript expressions.
 * Features monospace font, "fx" badge, and error indication.
 *
 * @example
 * ```tsx
 * <ExpressionInput
 *   expression="Variables.x * 2"
 *   onChange={(expr) => updateExpression(expr)}
 *   hasError={false}
 * />
 * ```
 */
function ExpressionInput({ expression, onChange, onBlur, hasError = false, errorMessage, placeholder = 'Enter expression...', testId, debounceMs = 300, onExpand, UNSAFE_className, UNSAFE_style }) {
    const [localValue, setLocalValue] = (0,external_react_.useState)(expression);
    const debounceTimerRef = (0,external_react_.useRef)(null);
    // Update local value when prop changes
    (0,external_react_.useEffect)(() => {
        setLocalValue(expression);
    }, [expression]);
    // Debounced onChange handler
    const debouncedOnChange = (0,external_react_.useCallback)((value) => {
        if (debounceTimerRef.current) {
            clearTimeout(debounceTimerRef.current);
        }
        debounceTimerRef.current = setTimeout(() => {
            onChange(value);
        }, debounceMs);
    }, [onChange, debounceMs]);
    // Cleanup timer on unmount
    (0,external_react_.useEffect)(() => {
        return () => {
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }
        };
    }, []);
    const handleChange = (e) => {
        const newValue = e.target.value;
        setLocalValue(newValue);
        debouncedOnChange(newValue);
    };
    const handleBlur = () => {
        // Cancel debounce and apply immediately on blur
        if (debounceTimerRef.current) {
            clearTimeout(debounceTimerRef.current);
        }
        if (localValue !== expression) {
            onChange(localValue);
        }
        onBlur === null || onBlur === void 0 ? void 0 : onBlur();
    };
    const handleKeyDown = (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            // Apply immediately on Enter
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }
            onChange(localValue);
            e.currentTarget.blur();
        }
    };
    return (external_react_default().createElement("div", { className: `${ExpressionInput_ExpressionInput_module['Root']} ${hasError ? ExpressionInput_ExpressionInput_module['HasError'] : ''} ${UNSAFE_className || ''}`, style: UNSAFE_style, "data-test": testId },
        external_react_default().createElement("span", { className: ExpressionInput_ExpressionInput_module['Badge'] }, "fx"),
        external_react_default().createElement("input", { type: "text", className: ExpressionInput_ExpressionInput_module['Input'], value: localValue, onChange: handleChange, onBlur: handleBlur, onKeyDown: handleKeyDown, placeholder: placeholder, spellCheck: false, autoComplete: "off" }),
        hasError && errorMessage && (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: errorMessage },
            external_react_default().createElement("div", { className: ExpressionInput_ExpressionInput_module['ErrorIndicator'] },
                external_react_default().createElement(Icon/* Icon */.In, { icon: Icon/* IconName */.$M.WarningCircle, size: Icon/* IconSize */.lK.Tiny })))),
        onExpand && (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Edit in code editor" },
            external_react_default().createElement("button", { type: "button", className: ExpressionInput_ExpressionInput_module['ExpandButton'], onClick: onExpand, "aria-label": "Edit in code editor" },
                external_react_default().createElement(Icon/* Icon */.In, { icon: Icon/* IconName */.$M.Code, size: Icon/* IconSize */.lK.Tiny }))))));
}

;// ../noodl-core-ui/src/components/property-panel/ExpressionInput/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/inputs/IconButton/index.ts + 2 modules
var IconButton = __webpack_require__(28208);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/property-panel/ExpressionToggle/ExpressionToggle.module.scss
var ExpressionToggle_module = __webpack_require__(42927);
;// ../noodl-core-ui/src/components/property-panel/ExpressionToggle/ExpressionToggle.module.scss

      
      
      
      
      
      
      
      
      

var ExpressionToggle_module_options = {};

ExpressionToggle_module_options.styleTagTransform = (styleTagTransform_default());
ExpressionToggle_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ExpressionToggle_module_options.insert = insertBySelector_default().bind(null, "head");
    
ExpressionToggle_module_options.domAPI = (styleDomAPI_default());
ExpressionToggle_module_options.insertStyleElement = (insertStyleElement_default());

var ExpressionToggle_module_update = injectStylesIntoStyleTag_default()(ExpressionToggle_module/* default */.A, ExpressionToggle_module_options);




       /* harmony default export */ const ExpressionToggle_ExpressionToggle_module = (ExpressionToggle_module/* default */.A && ExpressionToggle_module/* default */.A.locals ? ExpressionToggle_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/property-panel/ExpressionToggle/ExpressionToggle.tsx





/**
 * ExpressionToggle
 *
 * Toggle button that switches a property between fixed value mode and expression mode.
 * Shows a connection indicator when the port is connected via cable.
 *
 * @example
 * ```tsx
 * <ExpressionToggle
 *   mode="fixed"
 *   onToggle={() => setMode(mode === 'fixed' ? 'expression' : 'fixed')}
 * />
 * ```
 */
function ExpressionToggle({ mode, isConnected = false, onToggle, isDisabled = false, testId, UNSAFE_className, UNSAFE_style }) {
    // If connected via cable, show connection indicator instead of toggle
    if (isConnected) {
        return (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Connected via cable" },
            external_react_default().createElement("div", { className: ExpressionToggle_ExpressionToggle_module['ConnectionIndicator'], "data-test": testId, style: UNSAFE_style },
                external_react_default().createElement(Icon/* Icon */.In, { icon: Icon/* IconName */.$M.Link, size: Icon/* IconSize */.lK.Tiny }))));
    }
    const isExpressionMode = mode === 'expression';
    const tooltipContent = isExpressionMode ? 'Switch to fixed value' : 'Switch to expression';
    // When in expression mode, show TextInBox icon (switch to fixed value)
    // When in fixed mode, show "fx" text button (switch to expression)
    if (isExpressionMode) {
        return (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: tooltipContent },
            external_react_default().createElement("div", { className: ExpressionToggle_ExpressionToggle_module['Root'], style: UNSAFE_style },
                external_react_default().createElement(IconButton/* IconButton */.K0, { icon: Icon/* IconName */.$M.TextInBox, size: Icon/* IconSize */.lK.Tiny, variant: IconButton/* IconButtonVariant */.nl.Default, onClick: onToggle, isDisabled: isDisabled, testId: testId, UNSAFE_className: ExpressionToggle_ExpressionToggle_module['ExpressionActive'] }))));
    }
    // Fixed mode - show "fx" text button
    return (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: tooltipContent },
        external_react_default().createElement("button", { type: "button", className: `${ExpressionToggle_ExpressionToggle_module['FxButton']} ${isDisabled ? ExpressionToggle_ExpressionToggle_module['is-disabled'] : ''} ${UNSAFE_className || ''}`, style: UNSAFE_style, onClick: isDisabled ? undefined : onToggle, disabled: isDisabled, "data-test": testId }, "fx")));
}

;// ../noodl-core-ui/src/components/property-panel/ExpressionToggle/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelButton/index.ts + 2 modules
var PropertyPanelButton = __webpack_require__(60938);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelCheckbox/index.ts + 2 modules
var PropertyPanelCheckbox = __webpack_require__(37837);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/property-panel/PropertyPanelIconRadioInput/PropertyPanelIconRadioInput.module.scss
var PropertyPanelIconRadioInput_module = __webpack_require__(76789);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelIconRadioInput/PropertyPanelIconRadioInput.module.scss

      
      
      
      
      
      
      
      
      

var PropertyPanelIconRadioInput_module_options = {};

PropertyPanelIconRadioInput_module_options.styleTagTransform = (styleTagTransform_default());
PropertyPanelIconRadioInput_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      PropertyPanelIconRadioInput_module_options.insert = insertBySelector_default().bind(null, "head");
    
PropertyPanelIconRadioInput_module_options.domAPI = (styleDomAPI_default());
PropertyPanelIconRadioInput_module_options.insertStyleElement = (insertStyleElement_default());

var PropertyPanelIconRadioInput_module_update = injectStylesIntoStyleTag_default()(PropertyPanelIconRadioInput_module/* default */.A, PropertyPanelIconRadioInput_module_options);




       /* harmony default export */ const PropertyPanelIconRadioInput_PropertyPanelIconRadioInput_module = (PropertyPanelIconRadioInput_module/* default */.A && PropertyPanelIconRadioInput_module/* default */.A.locals ? PropertyPanelIconRadioInput_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelIconRadioInput/PropertyPanelIconRadioInput.tsx



var PropertyPanelIconRadioSize;
(function (PropertyPanelIconRadioSize) {
    PropertyPanelIconRadioSize["Default"] = "default";
    PropertyPanelIconRadioSize["Large"] = "large";
})(PropertyPanelIconRadioSize || (PropertyPanelIconRadioSize = {}));
function PropertyPanelIconRadioInput({ value, properties, onChange }) {
    const timestamp = (0,external_react_.useMemo)(() => Date.now().toString(), []);
    return (external_react_default().createElement("div", { className: PropertyPanelIconRadioInput_PropertyPanelIconRadioInput_module['Root'] }, properties === null || properties === void 0 ? void 0 : properties.options.map((option) => (external_react_default().createElement("label", { className: external_classnames_default()(PropertyPanelIconRadioInput_PropertyPanelIconRadioInput_module['Option'], value === option.value && PropertyPanelIconRadioInput_PropertyPanelIconRadioInput_module['is-selected'], option.isDisabled && PropertyPanelIconRadioInput_PropertyPanelIconRadioInput_module['is-disabled']) },
        external_react_default().createElement("input", { className: PropertyPanelIconRadioInput_PropertyPanelIconRadioInput_module['Input'], type: "radio", name: timestamp, value: option.value, checked: value === option.value, onClick: () => onChange && onChange(option.value), disabled: option.isDisabled }),
        option.icon)))));
}

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelIconRadioInput/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelLengthUnitInput/PropertyPanelLengthUnitInput.tsx
var PropertyPanelLengthUnitInput = __webpack_require__(30356);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelLengthUnitInput/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelBaseInput/index.ts + 2 modules
var PropertyPanelBaseInput = __webpack_require__(98690);
// EXTERNAL MODULE: ../noodl-core-ui/src/utils/extractNumber.ts
var extractNumber = __webpack_require__(15601);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelNumberInput/PropertyPanelNumberInput.tsx



function PropertyPanelNumberInput({ value, isChanged, isConnected, onChange, onFocus, onBlur, onKeyDown }) {
    // TODO: This component doesnt handle the value types correct
    const [displayedInputValue, setDisplayedInputValue] = (0,external_react_.useState)((value === null || value === void 0 ? void 0 : value.toString()) || '');
    (0,external_react_.useEffect)(() => {
        handleUpdate((value === null || value === void 0 ? void 0 : value.toString()) || '');
    }, [value]);
    function handleUpdate(inputValue) {
        // TODO: increase/decrease with arrows
        // TODO: handle drag up/down to increase/decrease
        // TODO: add basic arithmetic
        if (inputValue === '') {
            onChange && onChange(inputValue);
            return;
        }
        const newNumber = (0,extractNumber/* extractNumber */.T)(inputValue);
        if (!isNaN(newNumber)) {
            onChange && onChange(newNumber);
            setDisplayedInputValue(newNumber.toString());
        }
    }
    return (external_react_default().createElement(PropertyPanelBaseInput/* PropertyPanelBaseInput */.Z, { value: displayedInputValue, type: "text", isChanged: isChanged, isConnected: isConnected, onChange: (value) => setDisplayedInputValue(String(value)), onFocus: onFocus, onBlur: (e) => {
            handleUpdate(displayedInputValue);
            onBlur && onBlur(e);
        }, onKeyDown: (e) => {
            if (e.key === 'Enter') {
                handleUpdate(displayedInputValue);
            }
            onKeyDown && onKeyDown(e);
        } }));
}

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelNumberInput/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelSelectInput/index.ts + 3 modules
var PropertyPanelSelectInput = __webpack_require__(66095);
;// ../noodl-core-ui/src/utils/linearMap.ts
function linearMap(currentValue, currentMin, currentMax, newMin, newMax) {
    const newSize = newMax - newMin;
    const oldSize = currentMax - currentMin;
    const oldScale = currentValue - currentMin;
    return (newSize * oldScale) / oldSize + newMin;
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/property-panel/PropertyPanelSliderInput/PropertyPanelSliderInput.module.scss
var PropertyPanelSliderInput_module = __webpack_require__(66499);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelSliderInput/PropertyPanelSliderInput.module.scss

      
      
      
      
      
      
      
      
      

var PropertyPanelSliderInput_module_options = {};

PropertyPanelSliderInput_module_options.styleTagTransform = (styleTagTransform_default());
PropertyPanelSliderInput_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      PropertyPanelSliderInput_module_options.insert = insertBySelector_default().bind(null, "head");
    
PropertyPanelSliderInput_module_options.domAPI = (styleDomAPI_default());
PropertyPanelSliderInput_module_options.insertStyleElement = (insertStyleElement_default());

var PropertyPanelSliderInput_module_update = injectStylesIntoStyleTag_default()(PropertyPanelSliderInput_module/* default */.A, PropertyPanelSliderInput_module_options);




       /* harmony default export */ const PropertyPanelSliderInput_PropertyPanelSliderInput_module = (PropertyPanelSliderInput_module/* default */.A && PropertyPanelSliderInput_module/* default */.A.locals ? PropertyPanelSliderInput_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelSliderInput/PropertyPanelSliderInput.tsx




function PropertyPanelSliderInput({ value, onChange, isChanged, isConnected, properties }) {
    const [numberInputValue, setNumberInputValue] = (0,external_react_.useState)(value);
    (0,external_react_.useEffect)(() => {
        setNumberInputValue(value);
    }, [value]);
    function handleNumberUpdate() {
        let value = numberInputValue;
        if (numberInputValue > properties.max) {
            value = properties.max;
        }
        if (numberInputValue < properties.min) {
            value = properties.min;
        }
        onChange(value);
        setNumberInputValue(value);
    }
    function handleSliderChange(value) {
        onChange(value);
        setNumberInputValue(value);
    }
    const thumbPercentage = (0,external_react_.useMemo)(() => linearMap(parseInt(value.toString()), Number(properties.min), Number(properties.max), 0, 100), [value, properties]);
    return (external_react_default().createElement("div", { className: PropertyPanelSliderInput_PropertyPanelSliderInput_module['Root'] },
        external_react_default().createElement("div", { className: PropertyPanelSliderInput_PropertyPanelSliderInput_module['NumberContainer'] },
            external_react_default().createElement(PropertyPanelBaseInput/* PropertyPanelBaseInput */.Z, { type: "text", value: numberInputValue, onChange: setNumberInputValue, onBlur: handleNumberUpdate, isConnected: isConnected, isChanged: isChanged, onKeyDown: (e) => e.key === 'Enter' && handleNumberUpdate() })),
        external_react_default().createElement("input", { style: {
                '--thumb-percentage': thumbPercentage
            }, className: PropertyPanelSliderInput_PropertyPanelSliderInput_module['Input'], type: "range", value: value, onChange: (e) => handleSliderChange(e.target.value), min: properties.min, max: properties.max, step: properties.step })));
}

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelSliderInput/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelTextInput/index.ts + 1 modules
var PropertyPanelTextInput = __webpack_require__(55506);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/property-panel/PropertyPanelTextRadioInput/PropertyPanelTextRadioInput.module.scss
var PropertyPanelTextRadioInput_module = __webpack_require__(46709);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelTextRadioInput/PropertyPanelTextRadioInput.module.scss

      
      
      
      
      
      
      
      
      

var PropertyPanelTextRadioInput_module_options = {};

PropertyPanelTextRadioInput_module_options.styleTagTransform = (styleTagTransform_default());
PropertyPanelTextRadioInput_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      PropertyPanelTextRadioInput_module_options.insert = insertBySelector_default().bind(null, "head");
    
PropertyPanelTextRadioInput_module_options.domAPI = (styleDomAPI_default());
PropertyPanelTextRadioInput_module_options.insertStyleElement = (insertStyleElement_default());

var PropertyPanelTextRadioInput_module_update = injectStylesIntoStyleTag_default()(PropertyPanelTextRadioInput_module/* default */.A, PropertyPanelTextRadioInput_module_options);




       /* harmony default export */ const PropertyPanelTextRadioInput_PropertyPanelTextRadioInput_module = (PropertyPanelTextRadioInput_module/* default */.A && PropertyPanelTextRadioInput_module/* default */.A.locals ? PropertyPanelTextRadioInput_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelTextRadioInput/PropertyPanelTextRadioInput.tsx



function PropertyPanelTextRadioInput({ value, properties, onChange }) {
    const timestamp = (0,external_react_.useMemo)(() => Date.now().toString(), []);
    return (external_react_default().createElement("div", { className: PropertyPanelTextRadioInput_PropertyPanelTextRadioInput_module['Root'] }, properties === null || properties === void 0 ? void 0 : properties.options.map((option) => (external_react_default().createElement("label", { className: external_classnames_default()(PropertyPanelTextRadioInput_PropertyPanelTextRadioInput_module['Option'], value === option.value && PropertyPanelTextRadioInput_PropertyPanelTextRadioInput_module['is-selected'], option.isDisabled && PropertyPanelTextRadioInput_PropertyPanelTextRadioInput_module['is-disabled']) },
        external_react_default().createElement("input", { className: PropertyPanelTextRadioInput_PropertyPanelTextRadioInput_module['Input'], type: "radio", name: timestamp, value: option.value, checked: value === option.value, onClick: () => onChange(option.value), disabled: option.isDisabled }),
        option.label)))));
}

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelTextRadioInput/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/property-panel/PropertyPanelInput/PropertyPanelInput.module.scss
var PropertyPanelInput_module = __webpack_require__(9621);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelInput/PropertyPanelInput.module.scss

      
      
      
      
      
      
      
      
      

var PropertyPanelInput_module_options = {};

PropertyPanelInput_module_options.styleTagTransform = (styleTagTransform_default());
PropertyPanelInput_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      PropertyPanelInput_module_options.insert = insertBySelector_default().bind(null, "head");
    
PropertyPanelInput_module_options.domAPI = (styleDomAPI_default());
PropertyPanelInput_module_options.insertStyleElement = (insertStyleElement_default());

var PropertyPanelInput_module_update = injectStylesIntoStyleTag_default()(PropertyPanelInput_module/* default */.A, PropertyPanelInput_module_options);




       /* harmony default export */ const PropertyPanelInput_PropertyPanelInput_module = (PropertyPanelInput_module/* default */.A && PropertyPanelInput_module/* default */.A.locals ? PropertyPanelInput_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelInput/PropertyPanelInput.tsx














var PropertyPanelInputType;
(function (PropertyPanelInputType) {
    PropertyPanelInputType["Text"] = "text";
    PropertyPanelInputType["Number"] = "number";
    PropertyPanelInputType["LengthUnit"] = "length-unit";
    PropertyPanelInputType["Slider"] = "slider";
    PropertyPanelInputType["Select"] = "select";
    PropertyPanelInputType["Color"] = "color";
    PropertyPanelInputType["TextRadio"] = "text-radio";
    PropertyPanelInputType["IconRadio"] = "icon-radio";
    PropertyPanelInputType["Checkbox"] = "checkbox";
    PropertyPanelInputType["Button"] = "button";
    // MarginPadding = 'margin-padding',
    // SizeMode = 'size-mode',
})(PropertyPanelInputType || (PropertyPanelInputType = {}));
function PropertyPanelInput({ label, value, inputType = PropertyPanelInputType.Text, properties, isChanged, isConnected, onChange, 
// Expression props
supportsExpression = true, expressionMode = 'fixed', expression = '', onExpressionModeChange, onExpressionChange, expressionError, onExpressionExpand }) {
    const Input = (0,external_react_.useMemo)(() => {
        switch (inputType) {
            case PropertyPanelInputType.Text:
                return PropertyPanelTextInput/* PropertyPanelTextInput */.$;
            case PropertyPanelInputType.Number:
                return PropertyPanelNumberInput;
            case PropertyPanelInputType.LengthUnit:
                return PropertyPanelLengthUnitInput/* PropertyPanelLengthUnitInput */.G;
            case PropertyPanelInputType.Select:
                return PropertyPanelSelectInput/* PropertyPanelSelectInput */.S;
            case PropertyPanelInputType.Slider:
                return PropertyPanelSliderInput;
            case PropertyPanelInputType.TextRadio:
                return PropertyPanelTextRadioInput;
            case PropertyPanelInputType.IconRadio:
                return PropertyPanelIconRadioInput;
            case PropertyPanelInputType.Checkbox:
                return PropertyPanelCheckbox/* PropertyPanelCheckbox */.d;
            case PropertyPanelInputType.Button:
                return PropertyPanelButton/* PropertyPanelButton */.S;
        }
    }, [inputType]);
    // Determine if we should show expression UI
    const showExpressionToggle = supportsExpression && !isConnected;
    const isExpressionMode = expressionMode === 'expression';
    // Handle toggle between fixed and expression modes
    const handleToggleMode = () => {
        if (onExpressionModeChange) {
            const newMode = isExpressionMode ? 'fixed' : 'expression';
            onExpressionModeChange(newMode);
        }
    };
    // Render the appropriate input based on mode
    const renderInput = () => {
        if (isExpressionMode && onExpressionChange) {
            return (external_react_default().createElement(ExpressionInput, { expression: expression, onChange: onExpressionChange, hasError: !!expressionError, errorMessage: expressionError, onExpand: onExpressionExpand, UNSAFE_style: { flex: 1 } }));
        }
        // Standard input rendering
        return (
        // FIXME: fix below ts-ignore with better typing
        // this is caused by PropertyPanelBaseInputProps having a generic for "value"
        // i want to pass a boolan to the checkbox value that will be used in checked for a better API
        external_react_default().createElement(Input
        // @ts-expect-error
        , { 
            // @ts-expect-error
            value: value, 
            // @ts-expect-error
            onChange: onChange, 
            // @ts-expect-error
            isChanged: isChanged, 
            // @ts-expect-error
            isConnected: isConnected, 
            // @ts-expect-error
            properties: properties }));
    };
    return (external_react_default().createElement("div", { className: PropertyPanelInput_PropertyPanelInput_module['Root'] },
        external_react_default().createElement("div", { className: external_classnames_default()(PropertyPanelInput_PropertyPanelInput_module['Label'], isChanged && PropertyPanelInput_PropertyPanelInput_module['is-changed']) }, label),
        external_react_default().createElement("div", { className: PropertyPanelInput_PropertyPanelInput_module['InputContainer'] },
            external_react_default().createElement("div", { style: { display: 'flex', gap: '4px', alignItems: 'center', minWidth: 0 } },
                renderInput(),
                showExpressionToggle && (external_react_default().createElement(ExpressionToggle, { mode: expressionMode, isConnected: isConnected, onToggle: handleToggleMode }))))));
}
function PropertyPanelRow({ isChanged, label, children }) {
    return (external_react_default().createElement("div", { className: PropertyPanelInput_PropertyPanelInput_module['Root'] },
        external_react_default().createElement("div", { className: external_classnames_default()(PropertyPanelInput_PropertyPanelInput_module['Label'], isChanged && PropertyPanelInput_PropertyPanelInput_module['is-changed']) }, label),
        external_react_default().createElement("div", { className: PropertyPanelInput_PropertyPanelInput_module['InputContainer'] }, children)));
}

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelInput/index.ts



/***/ }),

/***/ 83623:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.TriggerChainDebuggerPanel-module__TriggerChainDebuggerPanel--H4mBY{display:flex;flex-direction:column;height:100%;background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-default);overflow:hidden}.TriggerChainDebuggerPanel-module__Header--Cq_ho{flex-shrink:0;display:flex;justify-content:space-between;align-items:center;padding:16px;border-bottom:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-2)}.TriggerChainDebuggerPanel-module__Title--bwfss{display:flex;align-items:center;gap:8px}.TriggerChainDebuggerPanel-module__Title--bwfss h2{margin:0;font-size:14px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:var(--theme-color-fg-default-shy)}.TriggerChainDebuggerPanel-module__RecordingIndicator--ll50q{display:flex;align-items:center;gap:8px;padding:6px 12px;background-color:var(--theme-color-bg-3);border-radius:4px;font-size:13px;font-weight:500;color:var(--theme-color-fg-highlight)}.TriggerChainDebuggerPanel-module__RecordingDot--lQRMY{width:8px;height:8px;border-radius:50%;background-color:#ef4444;animation:TriggerChainDebuggerPanel-module__pulse--bZODl 1.5s ease-in-out infinite}@keyframes TriggerChainDebuggerPanel-module__pulse--bZODl{0%,100%{opacity:1}50%{opacity:.5}}.TriggerChainDebuggerPanel-module__Controls--llXfI{flex-shrink:0;display:flex;align-items:center;gap:12px;padding:16px;border-bottom:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-2)}.TriggerChainDebuggerPanel-module__EventCount--hIyUB{margin-left:auto;padding:6px 12px;background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:4px;font-size:13px;font-weight:500;color:var(--theme-color-fg-default)}.TriggerChainDebuggerPanel-module__EventCount--hIyUB span{color:var(--theme-color-fg-highlight)}.TriggerChainDebuggerPanel-module__Content--rmLo8{flex:1;overflow-y:auto;padding:16px}.TriggerChainDebuggerPanel-module__EmptyState--S41R9{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:24px;text-align:center;color:var(--theme-color-fg-default-shy)}.TriggerChainDebuggerPanel-module__EmptyState--S41R9 h3{margin:16px 0 8px;font-size:16px;font-weight:500;color:var(--theme-color-fg-default)}.TriggerChainDebuggerPanel-module__EmptyState--S41R9 p{margin:0;font-size:13px}.TriggerChainDebuggerPanel-module__RecordingState--T3Jdq{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:24px;text-align:center;color:var(--theme-color-fg-default-shy)}.TriggerChainDebuggerPanel-module__RecordingState--T3Jdq h3{margin:16px 0 8px;font-size:16px;font-weight:500;color:var(--theme-color-fg-highlight)}.TriggerChainDebuggerPanel-module__RecordingState--T3Jdq p{margin:0;font-size:13px}.TriggerChainDebuggerPanel-module__TimelineContainer--het4H{display:flex;flex-direction:column;gap:16px}.TriggerChainDebuggerPanel-module__Placeholder--vupys{padding:48px 24px;text-align:center;background-color:var(--theme-color-bg-2);border:1px dashed var(--theme-color-border-default);border-radius:4px;color:var(--theme-color-fg-default-shy)}.TriggerChainDebuggerPanel-module__Placeholder--vupys p{margin:0 0 8px;font-size:14px}.TriggerChainDebuggerPanel-module__SmallText--zLuJC{font-size:12px !important;font-style:italic;color:var(--theme-color-fg-default-shy)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/TriggerChainDebuggerPanel/TriggerChainDebuggerPanel.module.scss"],"names":[],"mappings":"AAMA,oEACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,wCAAA,CACA,mCAAA,CACA,eAAA,CAOF,iDACE,aAAA,CACA,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,YAAA,CACA,yDAAA,CACA,wCAAA,CAGF,gDACE,YAAA,CACA,kBAAA,CACA,OAAA,CAEA,mDACE,QAAA,CACA,cAAA,CACA,eAAA,CACA,wBAAA,CACA,mBAAA,CACA,uCAAA,CAIJ,6DACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,gBAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CAGF,uDACE,SAAA,CACA,UAAA,CACA,iBAAA,CACA,wBAAA,CACA,kFAAA,CAGF,0DACE,QAEE,SAAA,CAEF,IACE,UAAA,CAAA,CAQJ,mDACE,aAAA,CACA,YAAA,CACA,kBAAA,CACA,QAAA,CACA,YAAA,CACA,yDAAA,CACA,wCAAA,CAGF,qDACE,gBAAA,CACA,gBAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAEA,0DACE,qCAAA,CAQJ,kDACE,MAAA,CACA,eAAA,CACA,YAAA,CAOF,qDACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,WAAA,CACA,YAAA,CACA,iBAAA,CACA,uCAAA,CAEA,wDACE,iBAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,uDACE,QAAA,CACA,cAAA,CAQJ,yDACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,WAAA,CACA,YAAA,CACA,iBAAA,CACA,uCAAA,CAEA,4DACE,iBAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CAGF,2DACE,QAAA,CACA,cAAA,CAQJ,4DACE,YAAA,CACA,qBAAA,CACA,QAAA,CAGF,sDACE,iBAAA,CACA,iBAAA,CACA,wCAAA,CACA,mDAAA,CACA,iBAAA,CACA,uCAAA,CAEA,wDACE,cAAA,CACA,cAAA,CAIJ,oDACE,yBAAA,CACA,iBAAA,CACA,uCAAA","sourcesContent":["/**\n * Trigger Chain Debugger Panel Styles\n *\n * Uses design tokens from UI-STYLING-GUIDE.md\n */\n\n.TriggerChainDebuggerPanel {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  background-color: var(--theme-color-bg-1);\n  color: var(--theme-color-fg-default);\n  overflow: hidden;\n}\n\n/* =================================================================\n   Header\n   ================================================================= */\n\n.Header {\n  flex-shrink: 0;\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 16px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-2);\n}\n\n.Title {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n\n  h2 {\n    margin: 0;\n    font-size: 14px;\n    font-weight: 600;\n    text-transform: uppercase;\n    letter-spacing: 0.5px;\n    color: var(--theme-color-fg-default-shy);\n  }\n}\n\n.RecordingIndicator {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 6px 12px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 4px;\n  font-size: 13px;\n  font-weight: 500;\n  color: var(--theme-color-fg-highlight);\n}\n\n.RecordingDot {\n  width: 8px;\n  height: 8px;\n  border-radius: 50%;\n  background-color: #ef4444; /* Red for recording indicator */\n  animation: pulse 1.5s ease-in-out infinite;\n}\n\n@keyframes pulse {\n  0%,\n  100% {\n    opacity: 1;\n  }\n  50% {\n    opacity: 0.5;\n  }\n}\n\n/* =================================================================\n   Controls\n   ================================================================= */\n\n.Controls {\n  flex-shrink: 0;\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  padding: 16px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-2);\n}\n\n.EventCount {\n  margin-left: auto;\n  padding: 6px 12px;\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  font-size: 13px;\n  font-weight: 500;\n  color: var(--theme-color-fg-default);\n\n  span {\n    color: var(--theme-color-fg-highlight);\n  }\n}\n\n/* =================================================================\n   Content - Scrollable Area\n   ================================================================= */\n\n.Content {\n  flex: 1;\n  overflow-y: auto;\n  padding: 16px;\n}\n\n/* =================================================================\n   Empty State\n   ================================================================= */\n\n.EmptyState {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  height: 100%;\n  padding: 24px;\n  text-align: center;\n  color: var(--theme-color-fg-default-shy);\n\n  h3 {\n    margin: 16px 0 8px;\n    font-size: 16px;\n    font-weight: 500;\n    color: var(--theme-color-fg-default);\n  }\n\n  p {\n    margin: 0;\n    font-size: 13px;\n  }\n}\n\n/* =================================================================\n   Recording State\n   ================================================================= */\n\n.RecordingState {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  height: 100%;\n  padding: 24px;\n  text-align: center;\n  color: var(--theme-color-fg-default-shy);\n\n  h3 {\n    margin: 16px 0 8px;\n    font-size: 16px;\n    font-weight: 500;\n    color: var(--theme-color-fg-highlight);\n  }\n\n  p {\n    margin: 0;\n    font-size: 13px;\n  }\n}\n\n/* =================================================================\n   Timeline Container\n   ================================================================= */\n\n.TimelineContainer {\n  display: flex;\n  flex-direction: column;\n  gap: 16px;\n}\n\n.Placeholder {\n  padding: 48px 24px;\n  text-align: center;\n  background-color: var(--theme-color-bg-2);\n  border: 1px dashed var(--theme-color-border-default);\n  border-radius: 4px;\n  color: var(--theme-color-fg-default-shy);\n\n  p {\n    margin: 0 0 8px;\n    font-size: 14px;\n  }\n}\n\n.SmallText {\n  font-size: 12px !important;\n  font-style: italic;\n  color: var(--theme-color-fg-default-shy);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"TriggerChainDebuggerPanel": `TriggerChainDebuggerPanel-module__TriggerChainDebuggerPanel--H4mBY`,
	"Header": `TriggerChainDebuggerPanel-module__Header--Cq_ho`,
	"Title": `TriggerChainDebuggerPanel-module__Title--bwfss`,
	"RecordingIndicator": `TriggerChainDebuggerPanel-module__RecordingIndicator--ll50q`,
	"RecordingDot": `TriggerChainDebuggerPanel-module__RecordingDot--lQRMY`,
	"pulse": `TriggerChainDebuggerPanel-module__pulse--bZODl`,
	"Controls": `TriggerChainDebuggerPanel-module__Controls--llXfI`,
	"EventCount": `TriggerChainDebuggerPanel-module__EventCount--hIyUB`,
	"Content": `TriggerChainDebuggerPanel-module__Content--rmLo8`,
	"EmptyState": `TriggerChainDebuggerPanel-module__EmptyState--S41R9`,
	"RecordingState": `TriggerChainDebuggerPanel-module__RecordingState--T3Jdq`,
	"TimelineContainer": `TriggerChainDebuggerPanel-module__TimelineContainer--het4H`,
	"Placeholder": `TriggerChainDebuggerPanel-module__Placeholder--vupys`,
	"SmallText": `TriggerChainDebuggerPanel-module__SmallText--zLuJC`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 83770:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.SyncToolbar-module__SyncToolbar--Wc3V4{display:flex;flex-direction:column;padding:10px 12px;background-color:var(--theme-color-bg-3);border-bottom:1px solid var(--theme-color-border-default)}.SyncToolbar-module__RepoInfo--uC0RN{display:flex;align-items:center;gap:8px;margin-bottom:8px}.SyncToolbar-module__RepoName--NMb5a{font-size:13px;font-weight:500;color:var(--theme-color-fg-default)}.SyncToolbar-module__StatusText--rV9Cx{font-size:12px;color:var(--theme-color-fg-default-shy)}.SyncToolbar-module__ChangesIndicator--nS38N{color:var(--theme-color-warning)}.SyncToolbar-module__SyncedIndicator--ts9bs{color:var(--theme-color-success)}.SyncToolbar-module__Actions--xPvWl{display:flex;gap:8px}.SyncToolbar-module__SyncButton--XB9Dc{display:flex;align-items:center;gap:6px;padding:6px 12px;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:4px;color:var(--theme-color-fg-default);font-size:12px;font-weight:500;cursor:pointer;transition:all .15s ease}.SyncToolbar-module__SyncButton--XB9Dc:hover:not(:disabled){background-color:var(--theme-color-bg-4);border-color:var(--theme-color-border-strong)}.SyncToolbar-module__SyncButton--XB9Dc:disabled{opacity:.5;cursor:not-allowed}.SyncToolbar-module__SyncButton--XB9Dc.SyncToolbar-module__HasChanges--TsMrD{background-color:rgba(var(--theme-color-primary-rgb, 59, 130, 246), 0.1);border-color:var(--theme-color-primary);color:var(--theme-color-primary)}.SyncToolbar-module__SyncButton--XB9Dc.SyncToolbar-module__HasChanges--TsMrD:hover:not(:disabled){background-color:rgba(var(--theme-color-primary-rgb, 59, 130, 246), 0.2)}.SyncToolbar-module__SyncButton--XB9Dc svg{flex-shrink:0}.SyncToolbar-module__Badge--bWIYb{display:inline-flex;align-items:center;justify-content:center;min-width:18px;height:18px;padding:0 5px;background-color:var(--theme-color-primary);border-radius:9px;color:#fff;font-size:11px;font-weight:600}.SyncToolbar-module__RefreshButton--cGtp_{display:flex;align-items:center;justify-content:center;width:32px;height:32px;padding:0;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:4px;color:var(--theme-color-fg-default-shy);cursor:pointer;transition:all .15s ease}.SyncToolbar-module__RefreshButton--cGtp_:hover:not(:disabled){background-color:var(--theme-color-bg-4);color:var(--theme-color-fg-default)}.SyncToolbar-module__RefreshButton--cGtp_:disabled{opacity:.5;cursor:not-allowed}.SyncToolbar-module__Spinning--Qm63j{animation:SyncToolbar-module__spin--Xt7r5 1s linear infinite}@keyframes SyncToolbar-module__spin--Xt7r5{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}.SyncToolbar-module__ErrorBar--Nh8Cx{display:flex;align-items:center;justify-content:space-between;margin-top:8px;padding:8px 10px;background-color:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);border-radius:4px;color:var(--theme-color-danger);font-size:12px}.SyncToolbar-module__ErrorBar--Nh8Cx button{background:none;border:none;color:var(--theme-color-danger);font-size:16px;cursor:pointer;padding:0 0 0 8px;line-height:1}.SyncToolbar-module__ErrorBar--Nh8Cx button:hover{opacity:.7}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/GitHubPanel/components/SyncToolbar/SyncToolbar.module.scss"],"names":[],"mappings":"AAKA,wCACE,YAAA,CACA,qBAAA,CACA,iBAAA,CACA,wCAAA,CACA,yDAAA,CAGF,qCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,iBAAA,CAGF,qCACE,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,uCACE,cAAA,CACA,uCAAA,CAGF,6CACE,gCAAA,CAGF,4CACE,gCAAA,CAGF,oCACE,YAAA,CACA,OAAA,CAGF,uCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,gBAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,wBAAA,CAEA,4DACE,wCAAA,CACA,6CAAA,CAGF,gDACE,UAAA,CACA,kBAAA,CAGF,6EACE,wEAAA,CACA,uCAAA,CACA,gCAAA,CAEA,kGACE,wEAAA,CAIJ,2CACE,aAAA,CAIJ,kCACE,mBAAA,CACA,kBAAA,CACA,sBAAA,CACA,cAAA,CACA,WAAA,CACA,aAAA,CACA,2CAAA,CACA,iBAAA,CACA,UAAA,CACA,cAAA,CACA,eAAA,CAGF,0CACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CACA,WAAA,CACA,SAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,uCAAA,CACA,cAAA,CACA,wBAAA,CAEA,+DACE,wCAAA,CACA,mCAAA,CAGF,mDACE,UAAA,CACA,kBAAA,CAIJ,qCACE,4DAAA,CAGF,2CACE,KACE,sBAAA,CAEF,GACE,wBAAA,CAAA,CAIJ,qCACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,cAAA,CACA,gBAAA,CACA,mCAAA,CACA,mCAAA,CACA,iBAAA,CACA,+BAAA,CACA,cAAA,CAEA,4CACE,eAAA,CACA,WAAA,CACA,+BAAA,CACA,cAAA,CACA,cAAA,CACA,iBAAA,CACA,aAAA,CAEA,kDACE,UAAA","sourcesContent":["/**\n * SyncToolbar styles\n * Uses design tokens for theming\n */\n\n.SyncToolbar {\n  display: flex;\n  flex-direction: column;\n  padding: 10px 12px;\n  background-color: var(--theme-color-bg-3);\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.RepoInfo {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin-bottom: 8px;\n}\n\n.RepoName {\n  font-size: 13px;\n  font-weight: 500;\n  color: var(--theme-color-fg-default);\n}\n\n.StatusText {\n  font-size: 12px;\n  color: var(--theme-color-fg-default-shy);\n}\n\n.ChangesIndicator {\n  color: var(--theme-color-warning);\n}\n\n.SyncedIndicator {\n  color: var(--theme-color-success);\n}\n\n.Actions {\n  display: flex;\n  gap: 8px;\n}\n\n.SyncButton {\n  display: flex;\n  align-items: center;\n  gap: 6px;\n  padding: 6px 12px;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover:not(:disabled) {\n    background-color: var(--theme-color-bg-4);\n    border-color: var(--theme-color-border-strong);\n  }\n\n  &:disabled {\n    opacity: 0.5;\n    cursor: not-allowed;\n  }\n\n  &.HasChanges {\n    background-color: rgba(var(--theme-color-primary-rgb, 59, 130, 246), 0.1);\n    border-color: var(--theme-color-primary);\n    color: var(--theme-color-primary);\n\n    &:hover:not(:disabled) {\n      background-color: rgba(var(--theme-color-primary-rgb, 59, 130, 246), 0.2);\n    }\n  }\n\n  svg {\n    flex-shrink: 0;\n  }\n}\n\n.Badge {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  min-width: 18px;\n  height: 18px;\n  padding: 0 5px;\n  background-color: var(--theme-color-primary);\n  border-radius: 9px;\n  color: white;\n  font-size: 11px;\n  font-weight: 600;\n}\n\n.RefreshButton {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 32px;\n  height: 32px;\n  padding: 0;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  color: var(--theme-color-fg-default-shy);\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover:not(:disabled) {\n    background-color: var(--theme-color-bg-4);\n    color: var(--theme-color-fg-default);\n  }\n\n  &:disabled {\n    opacity: 0.5;\n    cursor: not-allowed;\n  }\n}\n\n.Spinning {\n  animation: spin 1s linear infinite;\n}\n\n@keyframes spin {\n  from {\n    transform: rotate(0deg);\n  }\n  to {\n    transform: rotate(360deg);\n  }\n}\n\n.ErrorBar {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  margin-top: 8px;\n  padding: 8px 10px;\n  background-color: rgba(239, 68, 68, 0.1);\n  border: 1px solid rgba(239, 68, 68, 0.3);\n  border-radius: 4px;\n  color: var(--theme-color-danger);\n  font-size: 12px;\n\n  button {\n    background: none;\n    border: none;\n    color: var(--theme-color-danger);\n    font-size: 16px;\n    cursor: pointer;\n    padding: 0 0 0 8px;\n    line-height: 1;\n\n    &:hover {\n      opacity: 0.7;\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"SyncToolbar": `SyncToolbar-module__SyncToolbar--Wc3V4`,
	"RepoInfo": `SyncToolbar-module__RepoInfo--uC0RN`,
	"RepoName": `SyncToolbar-module__RepoName--NMb5a`,
	"StatusText": `SyncToolbar-module__StatusText--rV9Cx`,
	"ChangesIndicator": `SyncToolbar-module__ChangesIndicator--nS38N`,
	"SyncedIndicator": `SyncToolbar-module__SyncedIndicator--ts9bs`,
	"Actions": `SyncToolbar-module__Actions--xPvWl`,
	"SyncButton": `SyncToolbar-module__SyncButton--XB9Dc`,
	"HasChanges": `SyncToolbar-module__HasChanges--TsMrD`,
	"Badge": `SyncToolbar-module__Badge--bWIYb`,
	"RefreshButton": `SyncToolbar-module__RefreshButton--cGtp_`,
	"Spinning": `SyncToolbar-module__Spinning--Qm63j`,
	"spin": `SyncToolbar-module__spin--Xt7r5`,
	"ErrorBar": `SyncToolbar-module__ErrorBar--Nh8Cx`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 83790:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ContextMenu-module__Root--RvjZ6{position:relative}.ContextMenu-module__Root--RvjZ6.ContextMenu-module__is-visible--VzAnQ{display:block !important}.ContextMenu-module__OptionsDrawer--j5mRY{width:210px;filter:drop-shadow(0px 4px 4px rgba(0, 0, 0, 0.25))}.ContextMenu-module__Option--QT46H{width:100%;color:var(--theme-color-fg-highlight);transition:opacity var(--speed-turbo);padding:8px;cursor:pointer;display:flex;box-sizing:border-box;background-color:var(--theme-color-bg-2)}.ContextMenu-module__Option--QT46H .ContextMenu-module__OptionInner--BFNsG{opacity:.75;width:100%}.ContextMenu-module__Option--QT46H:hover .ContextMenu-module__OptionInner--BFNsG{opacity:1}.ContextMenu-module__Option--QT46H:not(:last-child){border-bottom:1px solid var(--theme-color-bg-3)}.ContextMenu-module__Option--QT46H.ContextMenu-module__is-disabled--siqjS{cursor:not-allowed}.ContextMenu-module__Option--QT46H.ContextMenu-module__is-disabled--siqjS .ContextMenu-module__OptionInner--BFNsG{opacity:.65 !important}.ContextMenu-module__Option--QT46H.ContextMenu-module__is-hidden--zK9D9{display:none}.ContextMenu-module__OptionLabel--eGGzF{flex-grow:1}.ContextMenu-module__OptionHelpText--DOfDi{font-size:10px;color:var(--theme-color-fg-muted);margin:0;padding:0}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/popups/ContextMenu/ContextMenu.module.scss"],"names":[],"mappings":"AAAA,iCACE,iBAAA,CAEA,uEACE,wBAAA,CAIJ,0CACE,WAAA,CACA,mDAAA,CAGF,mCACE,UAAA,CACA,qCAAA,CACA,qCAAA,CACA,WAAA,CACA,cAAA,CACA,YAAA,CACA,qBAAA,CACA,wCAAA,CAEA,2EACE,WAAA,CACA,UAAA,CAIA,iFACE,SAAA,CAIJ,oDACE,+CAAA,CAGF,0EACE,kBAAA,CAEA,kHACE,sBAAA,CAIJ,wEACE,YAAA,CAIJ,wCACE,WAAA,CAGF,2CACE,cAAA,CACA,iCAAA,CACA,QAAA,CACA,SAAA","sourcesContent":[".Root {\r\n  position: relative;\r\n\r\n  &.is-visible {\r\n    display: block !important;\r\n  }\r\n}\r\n\r\n.OptionsDrawer {\r\n  width: 210px;\r\n  filter: drop-shadow(0px 4px 4px rgba(0, 0, 0, 0.25));\r\n}\r\n\r\n.Option {\r\n  width: 100%;\r\n  color: var(--theme-color-fg-highlight);\r\n  transition: opacity var(--speed-turbo);\r\n  padding: 8px;\r\n  cursor: pointer;\r\n  display: flex;\r\n  box-sizing: border-box;\r\n  background-color: var(--theme-color-bg-2);\r\n\r\n  .OptionInner {\r\n    opacity: 0.75;\r\n    width: 100%;\r\n  }\r\n\r\n  &:hover {\r\n    .OptionInner {\r\n      opacity: 1;\r\n    }\r\n  }\r\n\r\n  &:not(:last-child) {\r\n    border-bottom: 1px solid var(--theme-color-bg-3);\r\n  }\r\n\r\n  &.is-disabled {\r\n    cursor: not-allowed;\r\n\r\n    .OptionInner {\r\n      opacity: 0.65 !important;\r\n    }\r\n  }\r\n\r\n  &.is-hidden {\r\n    display: none;\r\n  }\r\n}\r\n\r\n.OptionLabel {\r\n  flex-grow: 1;\r\n}\r\n\r\n.OptionHelpText {\r\n  font-size: 10px;\r\n  color: var(--theme-color-fg-muted);\r\n  margin: 0;\r\n  padding: 0;\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ContextMenu-module__Root--RvjZ6`,
	"is-visible": `ContextMenu-module__is-visible--VzAnQ`,
	"OptionsDrawer": `ContextMenu-module__OptionsDrawer--j5mRY`,
	"Option": `ContextMenu-module__Option--QT46H`,
	"OptionInner": `ContextMenu-module__OptionInner--BFNsG`,
	"is-disabled": `ContextMenu-module__is-disabled--siqjS`,
	"is-hidden": `ContextMenu-module__is-hidden--zK9D9`,
	"OptionLabel": `ContextMenu-module__OptionLabel--eGGzF`,
	"OptionHelpText": `ContextMenu-module__OptionHelpText--DOfDi`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 84071:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_4_use_1_node_modules_sass_loader_dist_cjs_js_PropertyPanelLengthUnitInput_module_scss__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(35393);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_4_use_1_node_modules_sass_loader_dist_cjs_js_PropertyPanelLengthUnitInput_module_scss__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_4_use_1_node_modules_sass_loader_dist_cjs_js_PropertyPanelLengthUnitInput_module_scss__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_4_use_1_node_modules_sass_loader_dist_cjs_js_PropertyPanelLengthUnitInput_module_scss__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_4_use_1_node_modules_sass_loader_dist_cjs_js_PropertyPanelLengthUnitInput_module_scss__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 84139:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgPageInputArrow = function SvgPageInputArrow(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M18.4091 3.96843L24.736 10.2953C24.9038 10.4675 24.9972 10.6988 24.9958 10.9393V25.4008C24.9958 25.8802 24.8054 26.34 24.4664 26.679C24.1274 27.018 23.6676 27.2085 23.1882 27.2085H15.4572V18.1174C15.4572 17.7838 15.3246 17.4638 15.0887 17.2279C14.8528 16.9919 14.5328 16.8594 14.1992 16.8594H5.11133V5.51625C5.11133 5.03683 5.30178 4.57704 5.64079 4.23803C5.97979 3.89902 6.43958 3.70857 6.91901 3.70857H17.7651C18.0056 3.70722 18.2369 3.80056 18.4091 3.96843ZM17.7651 5.96818V10.9393H22.7362L17.7651 5.96818Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M7.17395 19.3807C6.73211 19.3807 6.37392 19.7389 6.37392 20.1808C6.37392 20.6226 6.73211 20.9808 7.17395 20.9808H10.204L5.46381 25.7209C5.15138 26.0334 5.15138 26.5399 5.46381 26.8524C5.77624 27.1648 6.28279 27.1648 6.59522 26.8524L11.3349 22.1127V25.1418C11.3349 25.5836 11.6931 25.9418 12.1349 25.9418C12.5768 25.9418 12.935 25.5836 12.935 25.1418V20.2066C12.9418 19.9934 12.8638 19.7779 12.7011 19.6151C12.5995 19.5135 12.4773 19.4449 12.348 19.4094C12.2802 19.3907 12.2087 19.3807 12.1349 19.3807H7.17395Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgPageInputArrow);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "831a8c98ebacaf9d19c4f19f0455de51.svg");

/***/ }),

/***/ 84364:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgUser = function SvgUser(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.8624 3.66061C7.7533 3.66061 3.61154 7.80237 3.61154 12.9115C3.61154 15.2316 4.46564 17.3522 5.87657 18.9761C6.54981 17.9035 7.46295 16.9973 8.54791 16.3314C8.99048 16.0597 9.45573 15.8317 9.93713 15.6491C8.72904 14.7534 7.94601 13.3169 7.94601 11.6975C7.94601 8.98251 10.1469 6.78158 12.8619 6.78158C15.5769 6.78158 17.7778 8.98251 17.7778 11.6975C17.7778 13.3166 16.9951 14.7529 15.7874 15.6486C16.2693 15.8313 16.735 16.0595 17.178 16.3314C18.2627 16.9972 19.1757 17.9031 19.8489 18.9754C21.2594 17.3516 22.1133 15.2313 22.1133 12.9115C22.1133 7.80237 17.9715 3.66061 12.8624 3.66061ZM18.7444 20.0519C18.182 19.0525 17.3733 18.2113 16.3933 17.6098C15.3488 16.9687 14.1498 16.6243 12.925 16.613C12.904 16.6133 12.883 16.6134 12.8619 16.6134C12.8412 16.6134 12.8204 16.6133 12.7997 16.613C11.5754 16.6245 10.3768 16.9689 9.33259 17.6098C8.35234 18.2115 7.54352 19.0528 6.98114 20.0525C8.57978 21.3706 10.6286 22.1624 12.8624 22.1624C15.0965 22.1624 17.1457 21.3704 18.7444 20.0519ZM12.9201 15.1129C14.7798 15.0819 16.2778 13.5646 16.2778 11.6975C16.2778 9.81094 14.7485 8.28158 12.8619 8.28158C10.9754 8.28158 9.44601 9.81094 9.44601 11.6975C9.44601 13.5648 10.9444 15.0822 12.8044 15.1129C12.8239 15.1128 12.8434 15.1127 12.8629 15.1127C12.882 15.1127 12.901 15.1128 12.9201 15.1129ZM2.11154 12.9115C2.11154 6.97394 6.92487 2.16061 12.8624 2.16061C18.8 2.16061 23.6133 6.97394 23.6133 12.9115C23.6133 18.849 18.8 23.6624 12.8624 23.6624C6.92487 23.6624 2.11154 18.849 2.11154 12.9115Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgUser);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "3082040a25d7aae39ccde7cd98e027d7.svg");

/***/ }),

/***/ 84379:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.EditorBanner-module__EditorBanner--kupEl{position:fixed;top:var(--topbar-height, 40px);left:0;right:0;z-index:1000;display:flex;align-items:center;gap:16px;padding:12px 20px;background:#1a1a1a;border-bottom:2px solid var(--theme-color-warning, #ffc107);box-shadow:0 2px 8px rgba(0,0,0,.1);pointer-events:none}.EditorBanner-module__Icon--M_bdW{flex-shrink:0;display:flex;align-items:center;justify-content:center;color:var(--theme-color-warning)}.EditorBanner-module__Content--WQA2l{flex:1;display:flex;flex-direction:column;gap:4px;pointer-events:all}.EditorBanner-module__Title--gJIAA{color:var(--theme-color-fg-default);font-weight:600}.EditorBanner-module__Description--HwK2H{color:var(--theme-color-fg-default-shy)}.EditorBanner-module__Actions--SMzH2{flex-shrink:0;display:flex;align-items:center;gap:8px;pointer-events:all}.EditorBanner-module__CloseButton--w_QsA{flex-shrink:0;margin-left:8px;pointer-events:all}@media(max-width: 900px){.EditorBanner-module__EditorBanner--kupEl{flex-wrap:wrap}.EditorBanner-module__Content--WQA2l{flex-basis:100%;order:1}.EditorBanner-module__Actions--SMzH2{order:2;margin-top:8px}.EditorBanner-module__CloseButton--w_QsA{order:0;margin-left:auto}}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/EditorBanner/EditorBanner.module.scss"],"names":[],"mappings":"AAOA,0CACE,cAAA,CACA,8BAAA,CACA,MAAA,CACA,OAAA,CACA,YAAA,CAEA,YAAA,CACA,kBAAA,CACA,QAAA,CAEA,iBAAA,CAEA,kBAAA,CACA,2DAAA,CAGA,mCAAA,CAIA,mBAAA,CAGF,kCACE,aAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CAEA,gCAAA,CAGF,qCACE,MAAA,CACA,YAAA,CACA,qBAAA,CACA,OAAA,CAGA,kBAAA,CAGF,mCACE,mCAAA,CACA,eAAA,CAGF,yCACE,uCAAA,CAGF,qCACE,aAAA,CACA,YAAA,CACA,kBAAA,CACA,OAAA,CAGA,kBAAA,CAGF,yCACE,aAAA,CACA,eAAA,CAGA,kBAAA,CAIF,yBACE,0CACE,cAAA,CAGF,qCACE,eAAA,CACA,OAAA,CAGF,qCACE,OAAA,CACA,cAAA,CAGF,yCACE,OAAA,CACA,gBAAA,CAAA","sourcesContent":["/**\n * EditorBanner Styles\n *\n * Warning banner for legacy projects in read-only mode.\n * Uses design tokens exclusively - NO hardcoded colors!\n */\n\n.EditorBanner {\n  position: fixed;\n  top: var(--topbar-height, 40px);\n  left: 0;\n  right: 0;\n  z-index: 1000;\n\n  display: flex;\n  align-items: center;\n  gap: 16px;\n\n  padding: 12px 20px;\n  /* Solid dark background for maximum visibility */\n  background: #1a1a1a;\n  border-bottom: 2px solid var(--theme-color-warning, #ffc107);\n\n  /* Subtle shadow for depth */\n  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n\n  /* CRITICAL: Allow clicks through banner to editor below */\n  /* Only interactive elements (buttons) should capture clicks */\n  pointer-events: none;\n}\n\n.Icon {\n  flex-shrink: 0;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n\n  color: var(--theme-color-warning);\n}\n\n.Content {\n  flex: 1;\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n\n  /* Re-enable pointer events for text content */\n  pointer-events: all;\n}\n\n.Title {\n  color: var(--theme-color-fg-default);\n  font-weight: 600;\n}\n\n.Description {\n  color: var(--theme-color-fg-default-shy);\n}\n\n.Actions {\n  flex-shrink: 0;\n  display: flex;\n  align-items: center;\n  gap: 8px;\n\n  /* Re-enable pointer events for interactive buttons */\n  pointer-events: all;\n}\n\n.CloseButton {\n  flex-shrink: 0;\n  margin-left: 8px;\n\n  /* Re-enable pointer events for close button */\n  pointer-events: all;\n}\n\n/* Responsive adjustments */\n@media (max-width: 900px) {\n  .EditorBanner {\n    flex-wrap: wrap;\n  }\n\n  .Content {\n    flex-basis: 100%;\n    order: 1;\n  }\n\n  .Actions {\n    order: 2;\n    margin-top: 8px;\n  }\n\n  .CloseButton {\n    order: 0;\n    margin-left: auto;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"EditorBanner": `EditorBanner-module__EditorBanner--kupEl`,
	"Icon": `EditorBanner-module__Icon--M_bdW`,
	"Content": `EditorBanner-module__Content--WQA2l`,
	"Title": `EditorBanner-module__Title--gJIAA`,
	"Description": `EditorBanner-module__Description--HwK2H`,
	"Actions": `EditorBanner-module__Actions--SMzH2`,
	"CloseButton": `EditorBanner-module__CloseButton--w_QsA`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 84499:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.__setModuleDefault = exports.__createBinding = void 0;
exports.__classPrivateFieldSet = __classPrivateFieldSet;
exports.__classPrivateFieldGet = __classPrivateFieldGet;
exports.__exportStar = __exportStar;
exports.__importStar = __importStar;
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;
}
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);
}
var __createBinding = Object.create
    ? function (o, m, k, k2) {
        if (k2 === void 0)
            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 === void 0)
            k2 = k;
        o[k2] = m[k];
    };
exports.__createBinding = __createBinding;
function __exportStar(m, o) {
    for (var p in m)
        if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
            __createBinding(o, m, p);
}
var __setModuleDefault = Object.create
    ? function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }
    : function (o, v) {
        o["default"] = v;
    };
exports.__setModuleDefault = __setModuleDefault;
var ownKeys = function (o) {
    ownKeys =
        Object.getOwnPropertyNames ||
            function (o2) {
                var ar = [];
                for (var k in o2)
                    if (Object.prototype.hasOwnProperty.call(o2, k))
                        ar[ar.length] = k;
                return ar;
            };
    return ownKeys(o);
};
function __importStar(mod) {
    if (mod && mod.__esModule)
        return mod;
    var result = {};
    if (mod != null) {
        for (var k = ownKeys(mod), i = 0; i < k.length; i++)
            if (k[i] !== "default")
                __createBinding(result, mod, k[i]);
    }
    __setModuleDefault(result, mod);
    return result;
}


/***/ }),

/***/ 84607:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/* Uncomment to see lines flashing when they're painted */
/*.monaco-editor .view-lines > .view-line {
	background-color: none;
	animation-name: flash-background;
	animation-duration: 800ms;
}
@keyframes flash-background {
	0%   { background-color: lightgreen; }
	100% { background-color: none }
}*/

.mtkcontrol {
	color: rgb(255, 255, 255) !important;
	background: rgb(150, 0, 0) !important;
}

.monaco-editor.no-user-select .lines-content,
.monaco-editor.no-user-select .view-line,
.monaco-editor.no-user-select .view-lines {
	user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}

.monaco-editor.enable-user-select {
	user-select: initial;
	-webkit-user-select: initial;
	-ms-user-select: initial;
}

.monaco-editor .view-lines {
	white-space: nowrap;
}

.monaco-editor .view-line {
	position: absolute;
	width: 100%;
}

.monaco-editor .mtkz {
	display: inline-block;
}

/* TODO@tokenization bootstrap fix */
/*.monaco-editor .view-line > span > span {
	float: none;
	min-height: inherit;
	margin-left: inherit;
}*/
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/lines/viewLines.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F,yDAAyD;AACzD;;;;;;;;EAQE;;AAEF;CACC,oCAAoC;CACpC,qCAAqC;AACtC;;AAEA;;;CAGC,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;AACtB;;AAEA;CACC,oBAAoB;CACpB,4BAA4B;CAC5B,wBAAwB;AACzB;;AAEA;CACC,mBAAmB;AACpB;;AAEA;CACC,kBAAkB;CAClB,WAAW;AACZ;;AAEA;CACC,qBAAqB;AACtB;;AAEA,oCAAoC;AACpC;;;;EAIE","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/* Uncomment to see lines flashing when they're painted */\n/*.monaco-editor .view-lines > .view-line {\n\tbackground-color: none;\n\tanimation-name: flash-background;\n\tanimation-duration: 800ms;\n}\n@keyframes flash-background {\n\t0%   { background-color: lightgreen; }\n\t100% { background-color: none }\n}*/\n\n.mtkcontrol {\n\tcolor: rgb(255, 255, 255) !important;\n\tbackground: rgb(150, 0, 0) !important;\n}\n\n.monaco-editor.no-user-select .lines-content,\n.monaco-editor.no-user-select .view-line,\n.monaco-editor.no-user-select .view-lines {\n\tuser-select: none;\n\t-webkit-user-select: none;\n\t-ms-user-select: none;\n}\n\n.monaco-editor.enable-user-select {\n\tuser-select: initial;\n\t-webkit-user-select: initial;\n\t-ms-user-select: initial;\n}\n\n.monaco-editor .view-lines {\n\twhite-space: nowrap;\n}\n\n.monaco-editor .view-line {\n\tposition: absolute;\n\twidth: 100%;\n}\n\n.monaco-editor .mtkz {\n\tdisplay: inline-block;\n}\n\n/* TODO@tokenization bootstrap fix */\n/*.monaco-editor .view-line > span > span {\n\tfloat: none;\n\tmin-height: inherit;\n\tmargin-left: inherit;\n}*/\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 84755:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.DataBrowser-module__Root--GWAk_{display:flex;flex-direction:column;height:100%;max-height:80vh;width:100%;max-width:1200px;background-color:var(--theme-color-bg-2);border-radius:8px;overflow:hidden}.DataBrowser-module__Header--XtiDv{display:flex;justify-content:space-between;align-items:center;padding:16px;border-bottom:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-3)}.DataBrowser-module__HeaderIcon--pBwQo{display:flex;align-items:center;justify-content:center;width:32px;height:32px;background-color:var(--theme-color-primary);border-radius:6px;color:var(--theme-color-fg-on-primary)}.DataBrowser-module__Toolbar--eFLGW{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid var(--theme-color-border-default);gap:12px}.DataBrowser-module__TableSelect--iXb0s{padding:6px 12px;border:1px solid var(--theme-color-border-default);border-radius:4px;background-color:var(--theme-color-bg-3);color:var(--theme-color-fg-default);font-size:13px;min-width:150px}.DataBrowser-module__TableSelect--iXb0s:focus{outline:none;border-color:var(--theme-color-primary)}.DataBrowser-module__TableSelect--iXb0s option{background-color:var(--theme-color-bg-2);color:var(--theme-color-fg-default)}.DataBrowser-module__SearchInput--ZvXeX{padding:6px 12px;border:1px solid var(--theme-color-border-default);border-radius:4px;background-color:var(--theme-color-bg-3);color:var(--theme-color-fg-default);font-size:13px;min-width:200px}.DataBrowser-module__SearchInput--ZvXeX:focus{outline:none;border-color:var(--theme-color-primary)}.DataBrowser-module__SearchInput--ZvXeX::placeholder{color:var(--theme-color-fg-default-shy)}.DataBrowser-module__BulkActions--vcmne{display:flex;justify-content:space-between;align-items:center;padding:8px 16px;background-color:var(--theme-color-notice-bg);border-bottom:1px solid var(--theme-color-border-default)}.DataBrowser-module__Error--Q5sNL{padding:12px 16px;background-color:var(--theme-color-danger-bg);border-bottom:1px solid var(--theme-color-border-default);color:var(--theme-color-danger)}.DataBrowser-module__Content--xYWt_{flex:1;overflow:auto;min-height:300px}.DataBrowser-module__Loading--xKZ8F,.DataBrowser-module__EmptyState--Y2hZA{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;min-height:200px;padding:40px}.DataBrowser-module__Pagination--Oeclk{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-top:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-3)}.DataBrowser-module__PageControls--Od3jK{display:flex;align-items:center;gap:4px}.DataBrowser-module__PageButton--FL9nN{padding:4px 8px;border:1px solid var(--theme-color-border-default);border-radius:4px;background-color:var(--theme-color-bg-2);color:var(--theme-color-fg-default);font-size:12px;cursor:pointer}.DataBrowser-module__PageButton--FL9nN:hover:not(:disabled){background-color:var(--theme-color-bg-3);border-color:var(--theme-color-primary)}.DataBrowser-module__PageButton--FL9nN:disabled{opacity:.5;cursor:not-allowed}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/databrowser/DataBrowser.module.scss"],"names":[],"mappings":"AAKA,iCACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,eAAA,CACA,UAAA,CACA,gBAAA,CACA,wCAAA,CACA,iBAAA,CACA,eAAA,CAGF,mCACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,YAAA,CACA,yDAAA,CACA,wCAAA,CAGF,uCACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CACA,WAAA,CACA,2CAAA,CACA,iBAAA,CACA,sCAAA,CAGF,oCACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,iBAAA,CACA,yDAAA,CACA,QAAA,CAGF,wCACE,gBAAA,CACA,kDAAA,CACA,iBAAA,CACA,wCAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CAEA,8CACE,YAAA,CACA,uCAAA,CAGF,+CACE,wCAAA,CACA,mCAAA,CAIJ,wCACE,gBAAA,CACA,kDAAA,CACA,iBAAA,CACA,wCAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CAEA,8CACE,YAAA,CACA,uCAAA,CAGF,qDACE,uCAAA,CAIJ,wCACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,gBAAA,CACA,6CAAA,CACA,yDAAA,CAGF,kCACE,iBAAA,CACA,6CAAA,CACA,yDAAA,CACA,+BAAA,CAGF,oCACE,MAAA,CACA,aAAA,CACA,gBAAA,CAGF,2EAEE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,WAAA,CACA,gBAAA,CACA,YAAA,CAGF,uCACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,iBAAA,CACA,sDAAA,CACA,wCAAA,CAGF,yCACE,YAAA,CACA,kBAAA,CACA,OAAA,CAGF,uCACE,eAAA,CACA,kDAAA,CACA,iBAAA,CACA,wCAAA,CACA,mCAAA,CACA,cAAA,CACA,cAAA,CAEA,4DACE,wCAAA,CACA,uCAAA,CAGF,gDACE,UAAA,CACA,kBAAA","sourcesContent":["/**\n * DataBrowser styles\n * Uses theme tokens per UI-STYLING-GUIDE.md\n */\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  max-height: 80vh;\n  width: 100%;\n  max-width: 1200px;\n  background-color: var(--theme-color-bg-2);\n  border-radius: 8px;\n  overflow: hidden;\n}\n\n.Header {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 16px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-3);\n}\n\n.HeaderIcon {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 32px;\n  height: 32px;\n  background-color: var(--theme-color-primary);\n  border-radius: 6px;\n  color: var(--theme-color-fg-on-primary);\n}\n\n.Toolbar {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 12px 16px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  gap: 12px;\n}\n\n.TableSelect {\n  padding: 6px 12px;\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-default);\n  font-size: 13px;\n  min-width: 150px;\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n\n  option {\n    background-color: var(--theme-color-bg-2);\n    color: var(--theme-color-fg-default);\n  }\n}\n\n.SearchInput {\n  padding: 6px 12px;\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  background-color: var(--theme-color-bg-3);\n  color: var(--theme-color-fg-default);\n  font-size: 13px;\n  min-width: 200px;\n\n  &:focus {\n    outline: none;\n    border-color: var(--theme-color-primary);\n  }\n\n  &::placeholder {\n    color: var(--theme-color-fg-default-shy);\n  }\n}\n\n.BulkActions {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 8px 16px;\n  background-color: var(--theme-color-notice-bg);\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.Error {\n  padding: 12px 16px;\n  background-color: var(--theme-color-danger-bg);\n  border-bottom: 1px solid var(--theme-color-border-default);\n  color: var(--theme-color-danger);\n}\n\n.Content {\n  flex: 1;\n  overflow: auto;\n  min-height: 300px;\n}\n\n.Loading,\n.EmptyState {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  height: 100%;\n  min-height: 200px;\n  padding: 40px;\n}\n\n.Pagination {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 12px 16px;\n  border-top: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-3);\n}\n\n.PageControls {\n  display: flex;\n  align-items: center;\n  gap: 4px;\n}\n\n.PageButton {\n  padding: 4px 8px;\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  background-color: var(--theme-color-bg-2);\n  color: var(--theme-color-fg-default);\n  font-size: 12px;\n  cursor: pointer;\n\n  &:hover:not(:disabled) {\n    background-color: var(--theme-color-bg-3);\n    border-color: var(--theme-color-primary);\n  }\n\n  &:disabled {\n    opacity: 0.5;\n    cursor: not-allowed;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `DataBrowser-module__Root--GWAk_`,
	"Header": `DataBrowser-module__Header--XtiDv`,
	"HeaderIcon": `DataBrowser-module__HeaderIcon--pBwQo`,
	"Toolbar": `DataBrowser-module__Toolbar--eFLGW`,
	"TableSelect": `DataBrowser-module__TableSelect--iXb0s`,
	"SearchInput": `DataBrowser-module__SearchInput--ZvXeX`,
	"BulkActions": `DataBrowser-module__BulkActions--vcmne`,
	"Error": `DataBrowser-module__Error--Q5sNL`,
	"Content": `DataBrowser-module__Content--xYWt_`,
	"Loading": `DataBrowser-module__Loading--xKZ8F`,
	"EmptyState": `DataBrowser-module__EmptyState--Y2hZA`,
	"Pagination": `DataBrowser-module__Pagination--Oeclk`,
	"PageControls": `DataBrowser-module__PageControls--Od3jK`,
	"PageButton": `DataBrowser-module__PageButton--FL9nN`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 85130:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const Model = __webpack_require__(47821);
const getDocsEndpoint = (__webpack_require__(41160)/* ["default"] */ .A);

const indexFile = 'index.json';

class LessonTemplatesModel extends Model {
  constructor() {
    super();
    this.templates = [];
  }

  _makeRequest(path, options) {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        var json;
        try {
          json = JSON.parse(xhr.response);
        } catch (e) {}

        if (xhr.status === 200 || xhr.status === 201) {
          options.success(json);
        } else {
          options.error(json);
        }
      }
    };

    xhr.open(options.method || 'GET', path, true);

    xhr.send();
  }

  // List public modules
  _list(fn) {
    const endpoint = getDocsEndpoint();

    this._makeRequest(endpoint + '/lessons/' + indexFile + '?' + new Date().getTime(), {
      success: (lessons) => {
        lessons.forEach((t) => {
          if (t.url.endsWith('.zip')) {
            // Url is reference to zip file
            t.baseURL = endpoint + '/lessons/' + t.url.split('/').slice(0, -1).join('/') + '/'; // Base Url, e.g. location of project zip file
          } else {
            // Url is assumed to be reference to folder containing the lesson
            t.baseURL = endpoint + '/lessons/' + (t.url.endsWith('/') ? t.url : t.url + '/');
            t.url = t.baseURL + 'project.zip' + (t.version ? '?v=' + t.version : '');
          }

          if (!t.name) t.name = t.url.replace(/:/g, '-').replace(/\//g, '-').replace(/\./g, '-');
        });

        fn(lessons);
      },
      error: () => {
        fn();
      }
    });
  }

  getCategories() {
    return Array.from(new Set(this.templates.map((t) => t.category)));
  }

  fetch() {
    this._list((res) => {
      if (!res) return;

      this.templates = res;

      this.notifyListeners('templatesChanged');
    });
  }

  getTemplates() {
    return this.templates;
  }
}

LessonTemplatesModel.instance = new LessonTemplatesModel();

module.exports = LessonTemplatesModel;


/***/ }),

/***/ 85596:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgArrowUp = function SvgArrowUp(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.9278 3.26032C13.0178 3.30032 13.0978 3.35032 13.1678 3.42032L19.9178 10.1703C20.2078 10.4603 20.2078 10.9403 19.9178 11.2303C19.6278 11.5203 19.1478 11.5203 18.8578 11.2303L13.3878 5.76032L13.3878 20.4503C13.3878 20.8603 13.0478 21.2003 12.6378 21.2003C12.2278 21.2003 11.8878 20.8603 11.8878 20.4503L11.8878 5.76032L6.41775 11.2303C6.12775 11.5203 5.64775 11.5203 5.35775 11.2303C5.20775 11.0803 5.13775 10.8903 5.13775 10.7003C5.13775 10.5103 5.20775 10.3203 5.35775 10.1703L12.1078 3.42032C12.1778 3.35032 12.2578 3.30032 12.3478 3.26032C12.5278 3.18032 12.7378 3.18032 12.9178 3.26032L12.9278 3.26032Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgArrowUp);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "cb8ba43ae50ccb1edb21f456a709f730.svg");

/***/ }),

/***/ 85755:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   e: () => (/* binding */ useModernModel),
/* harmony export */   f: () => (/* binding */ useModel)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

/**
 * const hosting = useModel(HostingModel.instance) // rerenders on all value updates
 * const hosting = useModel(HostingModel.instance, ['FrontendsFetched']) // rerender on FrontendsFetched event only
 *
 * useModelCallback(HostingModel.instance, (data) => console.log(data)) // runs on all value updates
 * useModelCallback(HostingModel.instance, (data) => console.log(data), ['FrontendsFetched']) // runs on FrontendsFetched event only
 */
function useModel(model, subscribedEvents) {
    // set and update timestamp to force a component reload
    const [, setTimestamp] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(`${Date.now()}`);
    const [group] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({});
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        function attachListener(event) {
            model.on('Model.' + event, () => {
                setTimestamp(`Model.${event}: ${Date.now()}`);
            }, group);
        }
        if (!subscribedEvents) {
            for (const event in model.events) {
                attachListener(event);
            }
        }
        else if (Array.isArray(subscribedEvents)) {
            subscribedEvents.forEach((event) => attachListener(event));
        }
        return () => {
            model.off(group);
        };
    }, []);
    return model;
}
function useModernModel(model, subscribedEvents) {
    // set and update timestamp to force a component reload
    const [, setTimestamp] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(`${Date.now()}`);
    const [group] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({});
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        function attachListener(event) {
            model.on(event, () => {
                setTimestamp(`${event}: ${Date.now()}`);
            }, group);
        }
        if (!subscribedEvents) {
            attachListener('*');
        }
        else if (Array.isArray(subscribedEvents)) {
            subscribedEvents.forEach((event) => attachListener(event));
        }
        return () => {
            model.off(group);
        };
    }, []);
    return model;
}


/***/ }),

/***/ 85869:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  $: () => (/* binding */ git),
  X: () => (/* binding */ gitNetworkArguments)
});

// EXTERNAL MODULE: external "path"
var external_path_ = __webpack_require__(16928);
var external_path_default = /*#__PURE__*/__webpack_require__.n(external_path_);
;// external "desktop-trampoline"
const external_desktop_trampoline_namespaceObject = require("desktop-trampoline");
;// ../noodl-git/src/paths.ts


let cache_desktopTrampolinePath = null;
/**
 * Returns and caches the desktop trampoline path,
 * via "desktop-trampoline"'s helper method.
 *
 * @returns
 */
function getDesktopTrampolinePathHelper() {
    if (cache_desktopTrampolinePath !== null)
        return cache_desktopTrampolinePath;
    // getDesktopTrampolinePath takes about 5ms, caching it removes the time.
    cache_desktopTrampolinePath = desktopGetDesktopTrampolinePath();
    //this is required due to this limitation in electron: https://github.com/electron/electron/issues/8206
    //only affects production builds
    cache_desktopTrampolinePath = cache_desktopTrampolinePath.replace("asar", "asar.unpacked");
    return cache_desktopTrampolinePath;
}
/**
 * Returns the desktop trampoline path, where we expect it to be.
 *
 * @returns
 */
function getDesktopTrampolinePath() {
    if (process.env.LOCAL_GIT_TRAMPOLINE_DIRECTORY) {
        return process.env.LOCAL_GIT_TRAMPOLINE_DIRECTORY;
    }
    return external_path_default().resolve(__dirname, "..", "..", "node_modules", "desktop-trampoline", "build", "Release", "desktop-trampoline")
        .replace(/[\\\/]app.asar[\\\/]/, "/app.asar.unpacked/");
}
function getGitPath() {
    // This is required because dugite is not imported as external package.
    // Where __dirname would otherwise be the package path.
    return external_path_default().resolve(__dirname, "..", "..", "node_modules", "dugite", "git")
        .replace(/[\\\/]app.asar[\\\/]/, "/app.asar.unpacked/");
}

// EXTERNAL MODULE: external "dugite"
var external_dugite_ = __webpack_require__(81882);
// EXTERNAL MODULE: ../noodl-git/src/core/git-error.ts
var git_error = __webpack_require__(55952);
// EXTERNAL MODULE: ../noodl-git/src/core/helpers/regex.ts + 1 modules
var regex = __webpack_require__(51025);
;// ../noodl-git/src/core/client/common.ts


function rejectLog(args, { output, error, exitCode, gitError, gitErrorDescription }) {
    // The caller should either handle this error, or expect that exit code.
    const errorMessage = new Array();
    errorMessage.push(`\`git ${args.join(' ')}\` exited with an unexpected code: ${exitCode}.`);
    if (output) {
        errorMessage.push('stdout:');
        errorMessage.push(output.toString());
    }
    if (error) {
        errorMessage.push('stderr:');
        errorMessage.push(error.toString());
    }
    if (gitError) {
        errorMessage.push(`(The error was parsed as ${gitError}: ${gitErrorDescription})`);
    }
    if (gitError === external_dugite_.GitError.PushWithFileSizeExceedingLimit) {
        const result = (0,regex/* getFileFromExceedsError */.qu)(errorMessage.join());
        const files = result.join('\n');
        if (files !== '') {
            errorMessage.push('\n\nFile causing error:\n\n' + files);
        }
    }
    console.error(errorMessage.join('\n'));
    console.error(`Git returned an unexpected exit code '${exitCode}' which should be handled by the caller.'`);
}

;// ../noodl-git/src/core/client/client-exec.ts



function execute({ name, path, args, enableLogging, options, }) {
    return new Promise(async (resolve, reject) => {
        var _a;
        const gitResult = await external_dugite_.GitProcess.exec(args, path, {
            env: options.env,
            stdin: options === null || options === void 0 ? void 0 : options.stdin,
            stdinEncoding: options === null || options === void 0 ? void 0 : options.stdinEncoding,
            processCallback: options === null || options === void 0 ? void 0 : options.processCallback,
        });
        const exitCodes = (options === null || options === void 0 ? void 0 : options.successExitCodes) || new Set([0]);
        const acceptableExitCode = gitResult.exitCode !== null && exitCodes.has(gitResult.exitCode);
        const shouldParseErrors = !((options === null || options === void 0 ? void 0 : options.parseErrors) === false);
        // Parse the error if acceptable exit code
        const gitError = shouldParseErrors
            ? acceptableExitCode
                ? (_a = external_dugite_.GitProcess.parseError(gitResult.stderr)) !== null && _a !== void 0 ? _a : external_dugite_.GitProcess.parseError(gitResult.stdout)
                : null
            : null;
        const gitErrorDescription = gitError
            ? (0,git_error/* getDescriptionForError */.QT)(gitError)
            : null;
        // Return the result
        const result = {
            output: gitResult.stdout,
            error: gitResult.stderr,
            exitCode: gitResult.exitCode,
            gitError,
            gitErrorDescription,
            path,
        };
        if (enableLogging) {
            console.log(`[${name}] stdout: ${result.output.toString()}`);
            console.log(`[${name}] stderr: ${result.error.toString()}`);
        }
        // Check if the error is acceptable
        const acceptableError = gitError && (options === null || options === void 0 ? void 0 : options.expectedErrors)
            ? options.expectedErrors.has(gitError)
            : false;
        if ((gitError && acceptableError) || acceptableExitCode) {
            return resolve(result);
        }
        rejectLog(args, result);
        reject(new git_error/* GitError */.XS(result, args));
    });
}

;// ../noodl-git/src/core/errno-exception.ts
/**
 * Determine whether the given object conforms to the shape of an
 * internal Node.js low-level exception, see IErrnoException for
 * more details.
 */
function isErrnoException(err) {
    return err instanceof Error && typeof err.code === 'string' && typeof err.syscall === 'string';
}

;// ../noodl-git/src/core/client/client-spawn.ts




function client_spawn_execute({ name, path, args, enableLogging, options, }) {
    const spawnOptions = {
        ...(options !== null && options !== void 0 ? options : {}),
        // Explicitly set TERM to 'dumb' so that if Desktop was launched
        // from a terminal or if the system environment variables
        // have TERM set Git won't consider us as a smart terminal.
        // See https://github.com/git/git/blob/a7312d1a2/editor.c#L11-L15
        env: {
            TERM: "dumb",
            ...(options !== null && options !== void 0 ? options : {}).env,
        },
    };
    return new Promise(async (resolve, reject) => {
        var _a;
        const process = external_dugite_.GitProcess.spawn(args, path, spawnOptions);
        // Send the stdin
        if (options === null || options === void 0 ? void 0 : options.stdin) {
            const stdinEncoding = (_a = options.stdinEncoding) !== null && _a !== void 0 ? _a : "utf-8";
            const stdinEncoded = Buffer.from(options.stdin).toString(stdinEncoding);
            process.stdin.write(stdinEncoded);
            process.stdin.end();
        }
        //
        if (options === null || options === void 0 ? void 0 : options.processCallback) {
            options.processCallback(process);
        }
        process.on("error", (err) => {
            // If this is an exception thrown by Node.js while attempting to
            // spawn let's keep the salient details but include the name of
            // the operation.
            if (isErrnoException(err)) {
                reject(new Error(`Failed to execute ${name}: ${err.code}`));
            }
            else {
                // for unhandled errors raised by the process, let's surface this in the
                // promise and make the caller handle it
                reject(err);
            }
        });
        let totalStdoutLength = 0;
        let killSignalSent = false;
        const stdoutChunks = new Array();
        // If Node.js encounters a synchronous runtime error while spawning
        // `stdout` will be undefined and the error will be emitted asynchronously
        if (process.stdout) {
            process.stdout.on("data", (chunk) => {
                if (enableLogging) {
                    console.log(`[${name}] stdout: ${chunk.toString()}`);
                }
                if (options === null || options === void 0 ? void 0 : options.processDataCallback) {
                    options === null || options === void 0 ? void 0 : options.processDataCallback(chunk);
                }
                if ((options === null || options === void 0 ? void 0 : options.maxBuffer) === undefined ||
                    ((options === null || options === void 0 ? void 0 : options.maxBuffer) &&
                        (!options.maxBuffer || totalStdoutLength < options.maxBuffer))) {
                    stdoutChunks.push(chunk);
                    totalStdoutLength += chunk.length;
                }
                if ((options === null || options === void 0 ? void 0 : options.maxBuffer) === undefined ||
                    ((options === null || options === void 0 ? void 0 : options.maxBuffer) &&
                        totalStdoutLength >= options.maxBuffer &&
                        !killSignalSent)) {
                    process.kill();
                    killSignalSent = true;
                }
            });
        }
        const stderrChunks = new Array();
        // See comment above about stdout and asynchronous errors.
        if (process.stderr) {
            process.stderr.on("data", (chunk) => {
                if (enableLogging) {
                    console.log(`[${name}] stderr: ${chunk.toString()}`);
                }
                if (options === null || options === void 0 ? void 0 : options.processDataCallback) {
                    options === null || options === void 0 ? void 0 : options.processDataCallback(chunk);
                }
                stderrChunks.push(chunk);
            });
        }
        process.on("close", (code, signal) => {
            var _a;
            const stdout = Buffer.concat(stdoutChunks, (options === null || options === void 0 ? void 0 : options.maxBuffer)
                ? Math.min(options === null || options === void 0 ? void 0 : options.maxBuffer, totalStdoutLength)
                : totalStdoutLength);
            const stderr = Buffer.concat(stderrChunks);
            // mimic the experience of GitProcess.exec for handling known codes when
            // the process terminates
            const exitCodes = (options === null || options === void 0 ? void 0 : options.successExitCodes) || new Set([0]);
            const acceptableExitCode = code !== null && exitCodes.has(code);
            const shouldParseErrors = !((options === null || options === void 0 ? void 0 : options.parseErrors) === false);
            // Parse the error if acceptable exit code
            const gitError = shouldParseErrors
                ? acceptableExitCode
                    ? (_a = external_dugite_.GitProcess.parseError(stderr.toString())) !== null && _a !== void 0 ? _a : external_dugite_.GitProcess.parseError(stdout.toString())
                    : null
                : null;
            const gitErrorDescription = gitError
                ? (0,git_error/* getDescriptionForError */.QT)(gitError)
                : null;
            // Check if the error is acceptable
            const acceptableError = gitError && (options === null || options === void 0 ? void 0 : options.expectedErrors)
                ? options.expectedErrors.has(gitError)
                : false;
            // Return the result
            const result = {
                output: stdout.toString("utf8"),
                error: stderr.toString("utf8"),
                exitCode: code,
                gitError,
                gitErrorDescription,
                path,
            };
            if ((gitError && acceptableError) || acceptableExitCode || signal) {
                return resolve(result);
            }
            rejectLog(args, result);
            reject(new git_error/* GitError */.XS(result, args));
        });
    });
}

;// external "net"
const external_net_namespaceObject = require("net");
;// external "split2"
const external_split2_namespaceObject = require("split2");
var external_split2_default = /*#__PURE__*/__webpack_require__.n(external_split2_namespaceObject);
;// ../noodl-git/src/core/trampoline/non-fatal-exception.ts
/**
 * Send a caught (ie. non-fatal) exception to the non-fatal error bucket
 *
 * The intended use of this message is for getting insight into areas of the
 * code where we suspect alternate failure modes other than those accounted for.
 *
 * Example: In the Desktop tutorial creation logic we handle all errors and our
 * initial belief was that the only two failure modes we would have to account
 * for were either the repo existing on disk or on the user's account. We now
 * suspect that there might be other reasons why the creation logic is failing
 * and therefore want to send all errors encountered during creation to central
 * where we can determine if there are additional failure modes for us to
 * consider.
 *
 * @param kind - a grouping key that allows us to group all errors originating
 * in the same area of the code base or relating to the same kind of failure
 * (recommend a single non-hyphenated word) Example: tutorialRepoCreation
 *
 * @param error - the caught error
 */
let lastNonFatalException = undefined;
/** Max one non fatal exeception per minute */
const minIntervalBetweenNonFatalExceptions = 60 * 1000;
function sendNonFatalException(kind, error) {
    const now = Date.now();
    if (lastNonFatalException !== undefined && now - lastNonFatalException < minIntervalBetweenNonFatalExceptions) {
        return;
    }
    lastNonFatalException = now;
    // NOTE: Update BugTracker with more functions to support this there instead
    console.error(kind, error);
}

// EXTERNAL MODULE: ../noodl-git/src/core/trampoline/trampoline-askpass-handler.ts
var trampoline_askpass_handler = __webpack_require__(58848);
;// ../noodl-git/src/core/trampoline/trampoline-command.ts
var TrampolineCommandIdentifier;
(function (TrampolineCommandIdentifier) {
    TrampolineCommandIdentifier["AskPass"] = "ASKPASS";
})(TrampolineCommandIdentifier || (TrampolineCommandIdentifier = {}));

;// ../noodl-git/src/core/trampoline/trampoline-command-parser.ts


/**
 * Parse a string into the given (string) enum type. Returns undefined if the
 * enum type provided did not match any of the keys in the enum.
 */
function parseEnumValue(enumObj, value) {
    return Object.values(enumObj).find((v) => v === value);
}
var TrampolineCommandParserState;
(function (TrampolineCommandParserState) {
    TrampolineCommandParserState[TrampolineCommandParserState["ParameterCount"] = 0] = "ParameterCount";
    TrampolineCommandParserState[TrampolineCommandParserState["Parameters"] = 1] = "Parameters";
    TrampolineCommandParserState[TrampolineCommandParserState["EnvironmentVariablesCount"] = 2] = "EnvironmentVariablesCount";
    TrampolineCommandParserState[TrampolineCommandParserState["EnvironmentVariables"] = 3] = "EnvironmentVariables";
    TrampolineCommandParserState[TrampolineCommandParserState["Finished"] = 4] = "Finished";
})(TrampolineCommandParserState || (TrampolineCommandParserState = {}));
/**
 * The purpose of this class is to process the data received from the trampoline
 * client and build a command from it.
 */
class TrampolineCommandParser {
    constructor() {
        this.parameterCount = 0;
        this.parameters = [];
        this.environmentVariablesCount = 0;
        this.environmentVariables = new Map();
        this.state = TrampolineCommandParserState.ParameterCount;
    }
    /** Whether or not it has finished parsing the command. */
    hasFinished() {
        return this.state === TrampolineCommandParserState.Finished;
    }
    /**
     * Takes a chunk of data and processes it depending on the current state.
     *
     * Throws an error if it's invoked after the parser has finished, or if
     * anything unexpected is received.
     **/
    processValue(value) {
        switch (this.state) {
            case TrampolineCommandParserState.ParameterCount:
                this.parameterCount = parseInt(value);
                if (this.parameterCount > 0) {
                    this.state = TrampolineCommandParserState.Parameters;
                }
                else {
                    this.state = TrampolineCommandParserState.EnvironmentVariablesCount;
                }
                break;
            case TrampolineCommandParserState.Parameters:
                this.parameters.push(value);
                if (this.parameters.length === this.parameterCount) {
                    this.state = TrampolineCommandParserState.EnvironmentVariablesCount;
                }
                break;
            case TrampolineCommandParserState.EnvironmentVariablesCount:
                this.environmentVariablesCount = parseInt(value);
                if (this.environmentVariablesCount > 0) {
                    this.state = TrampolineCommandParserState.EnvironmentVariables;
                }
                else {
                    this.state = TrampolineCommandParserState.Finished;
                }
                break;
            case TrampolineCommandParserState.EnvironmentVariables:
                // Split after the first '='
                const match = /([^=]+)=(.*)/.exec(value);
                if (match === null ||
                    // Length must be 3: the 2 groups + the whole string
                    match.length !== 3) {
                    throw new Error(`Unexpected environment variable format: ${value}`);
                }
                const variableKey = match[1];
                const variableValue = match[2];
                this.environmentVariables.set(variableKey, variableValue);
                if (this.environmentVariables.size === this.environmentVariablesCount) {
                    this.state = TrampolineCommandParserState.Finished;
                }
                break;
            default:
                throw new Error(`Received value during invalid state: ${this.state}`);
        }
    }
    /**
     * Returns a command.
     *
     * It will return null if the parser hasn't finished yet, or if the identifier
     * is missing or invalid.
     **/
    toCommand() {
        if (this.hasFinished() === false) {
            const error = new Error('The command cannot be generated if parsing is not finished');
            this.logCommandCreationError(error);
            return null;
        }
        const identifierString = this.environmentVariables.get('DESKTOP_TRAMPOLINE_IDENTIFIER');
        if (identifierString === undefined) {
            const error = new Error(`The command identifier is missing. Env variables received: ${Array.from(this.environmentVariables.keys())}`);
            this.logCommandCreationError(error);
            return null;
        }
        const identifier = parseEnumValue(TrampolineCommandIdentifier, identifierString);
        if (identifier === undefined) {
            const error = new Error(`The command identifier ${identifierString} is not supported`);
            this.logCommandCreationError(error);
            return null;
        }
        const trampolineToken = this.environmentVariables.get('DESKTOP_TRAMPOLINE_TOKEN');
        if (trampolineToken === undefined) {
            const error = new Error(`The trampoline token is missing`);
            this.logCommandCreationError(error);
            return null;
        }
        return {
            identifier,
            trampolineToken,
            parameters: this.parameters,
            environmentVariables: this.environmentVariables
        };
    }
    logCommandCreationError(error) {
        console.error('Error creating trampoline command:', error);
        sendNonFatalException('trampolineCommandParser', error);
    }
}

;// ../noodl-git/src/core/trampoline/trampoline-tokens.ts
// TODO: Move to platform package
function guid() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return (s4() +
        s4() +
        "-" +
        s4() +
        "-" +
        s4() +
        "-" +
        s4() +
        "-" +
        s4() +
        s4() +
        s4());
}
const trampolineTokens = new Set();
/** Checks if a given trampoline token is valid. */
function isValidTrampolineToken(token) {
    return trampolineTokens.has(token);
}
/**
 * Allows invoking a function with a short-lived trampoline token that will be
 * revoked right after the function finishes.
 *
 * @param fn Function to invoke with the trampoline token.
 */
async function withTrampolineToken(fn) {
    let result;
    // Create a unique token for this request
    const token = guid();
    trampolineTokens.add(token);
    try {
        result = await fn(token);
    }
    finally {
        trampolineTokens.delete(token);
    }
    return result;
}

;// ../noodl-git/src/core/trampoline/trampoline-server.ts







/**
 * This class represents the "trampoline server". The trampoline is something
 * we'll hand to git in order to communicate with the App without noticing. A
 * notable example of this would be GIT_ASKPASS.
 *
 * This server is designed so that it will start lazily when the app performs a
 * remote git operation. At that point, the app will try to retrieve the
 * server's port, which will run the server first if needed.
 *
 * The idea behind this is to simplify the retry approach in case of error:
 * instead of reacting to errors with an immediate retry, the server will remain
 * closed until the next time the app needs it (i.e. in the next git remote
 * operation).
 */
class TrampolineServer {
    constructor() {
        this.listeningPromise = null;
        this.commandHandlers = new Map();
        this.onServerError = (error) => {
            sendNonFatalException('trampolineServer', error);
            this.close();
        };
        this.onClientError = (error) => {
            console.error('Trampoline client error', error);
        };
        this.server = (0,external_net_namespaceObject.createServer)((socket) => this.onNewConnection(socket));
        // Make sure the server is always unref'ed, so it doesn't keep the app alive
        // for longer than needed. Not having this made the CI tasks on Windows
        // timeout because the unit tests completed in about 7min, but the test
        // suite runner would never finish, hitting a 45min timeout for the whole
        // GitHub Action.
        this.server.unref();
        this.registerCommandHandler(TrampolineCommandIdentifier.AskPass, trampoline_askpass_handler/* askpassTrampolineHandler */.qM);
    }
    async listen() {
        this.listeningPromise = new Promise((resolve, reject) => {
            // Observe errors while trying to start the server
            this.server.on('error', (error) => {
                console.error(error);
                reject(error);
                this.close();
            });
            this.server.listen(0, '127.0.0.1', async () => {
                // Replace the error handler
                this.server.removeAllListeners('error');
                this.server.on('error', this.onServerError);
                resolve();
            });
        });
        return this.listeningPromise;
    }
    async close() {
        // Make sure the server is not trying to start
        if (this.listeningPromise !== null) {
            await this.listeningPromise;
        }
        // Reset the server, it will be restarted lazily the next time it's needed
        this.server.close();
        this.server.removeAllListeners('error');
        this.listeningPromise = null;
    }
    /**
     * This function will retrieve the port of the server, or null if the server
     * is not running.
     *
     * In order to get the server port, it might need to start the server if it's
     * not running already.
     */
    async getPort() {
        if (this.port !== null) {
            return this.port;
        }
        if (this.listeningPromise !== null) {
            await this.listeningPromise;
        }
        else {
            await this.listen();
        }
        return this.port;
    }
    get port() {
        const address = this.server.address();
        if (address && address.port) {
            return address.port;
        }
        return null;
    }
    onNewConnection(socket) {
        const parser = new TrampolineCommandParser();
        // Messages coming from the trampoline client will be separated by \0
        socket.pipe(external_split2_default()(/\0/)).on('data', (data) => {
            this.onDataReceived(socket, parser, data);
        });
        socket.on('error', this.onClientError);
    }
    onDataReceived(socket, parser, data) {
        const value = data.toString('utf8');
        parser.processValue(value);
        if (!parser.hasFinished()) {
            return;
        }
        const command = parser.toCommand();
        if (command === null) {
            socket.end();
            return;
        }
        this.processCommand(socket, command);
    }
    /**
     * Registers a handler for commands with a specific identifier. This will be
     * invoked when the server receives a command with the given identifier.
     *
     * @param identifier Identifier of the command.
     * @param handler Handler to register.
     */
    registerCommandHandler(identifier, handler) {
        this.commandHandlers.set(identifier, handler);
    }
    async processCommand(socket, command) {
        if (!isValidTrampolineToken(command.trampolineToken)) {
            throw new Error('Tried to use invalid trampoline token');
        }
        const handler = this.commandHandlers.get(command.identifier);
        if (handler === undefined) {
            socket.end();
            return;
        }
        const result = await handler(command);
        if (result !== undefined) {
            socket.end(result);
        }
        else {
            socket.end();
        }
    }
}
const trampolineServer = new TrampolineServer();

;// ../noodl-git/src/core/trampoline/trampoline-environment.ts




/**
 * Allows invoking a function with a set of environment variables to use when
 * invoking a Git subcommand that needs to use the trampoline (mainly git
 * operations requiring an askpass script) and with a token to use in the
 * trampoline server.
 *
 * @param fn        Function to invoke with all the necessary environment
 *                  variables.
 */
async function withTrampolineEnv(fn) {
    return withTrampolineToken(async (token) => {
        const desktopTrampolinePath = getDesktopTrampolinePath();
        const desktopPort = await trampolineServer.getPort();
        const result = await fn({
            GIT_ASKPASS: desktopTrampolinePath,
            DESKTOP_PORT: desktopPort,
            DESKTOP_TRAMPOLINE_TOKEN: token,
            DESKTOP_TRAMPOLINE_IDENTIFIER: TrampolineCommandIdentifier.AskPass,
        });
        return result;
    });
}

;// ../noodl-git/src/core/client.ts




/**
 * Return an array of command line arguments for network operation that override
 * the default git configuration values provided by local, global, or system
 * level git configs.
 *
 * These arguments should be inserted before the subcommand, i.e in
 * the case of `git pull` these arguments needs to go before the `pull`
 * argument.
 *
 * This should be used on the commands where we want to use
 * the trampoline server.
 *
 * @param repository the local repository associated with the command, to check
 *                   local, global and system config for an existing value.
 *                   If `null` if provided (for example, when cloning a new
 *                   repository), this function will check global and system
 *                   config for an existing `protocol.version` setting
 */
async function gitNetworkArguments(_repositoryDir) {
    const baseArgs = [
        // Explicitly unset any defined credential helper, we rely on our
        // own askpass for authentication.
        '-c',
        'credential.helper='
    ];
    return baseArgs;
}
/**
 * Shell out to git with the given arguments, at the given path.
 *
 * @param args             The arguments to pass to `git`.
 *
 * @param path             The working directory path for the execution of the
 *                         command.
 *
 * @param name             The name for the command based on its caller's
 *                         context. This will be used for performance
 *                         measurements and debugging.
 *
 * @param options          Configuration options for the execution of git,
 *                         see GitExecutionOptions for more information.
 *
 * Returns the result. If the command exits with a code not in
 * `successExitCodes` or an error not in `expectedErrors`, a `GitError` will be
 * thrown.
 */
async function git(args, path, name, options) {
    return withTrampolineEnv(async (env) => {
        const enableLogging = !!localStorage.getItem('git-output');
        const enableTraceLogging = !!localStorage.getItem('git-trace');
        if (enableLogging) {
            console.groupCollapsed(`[${name}] git ${args.join(' ')}`);
            console.log('path', path);
            console.log('args', args);
            console.log('options', options);
            console.groupEnd();
        }
        if (!process.env.LOCAL_GIT_DIRECTORY) {
            process.env.LOCAL_GIT_DIRECTORY = getGitPath();
        }
        const runOptions = {
            name,
            path,
            args,
            enableLogging,
            options: {
                ...(options || {}),
                env: {
                    // Add the input envs
                    ...((options === null || options === void 0 ? void 0 : options.env) || {}),
                    // Add the trampoline env
                    ...env,
                    // Add extra envs
                    GIT_TERMINAL_PROMPT: '0',
                    GIT_TRACE: enableTraceLogging ? '1' : '0'
                }
            }
        };
        if (options === null || options === void 0 ? void 0 : options.spawn) {
            return await client_spawn_execute(runOptions);
        }
        return await execute(runOptions);
    });
}


/***/ }),

/***/ 86105:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   l: () => (/* binding */ WarningsModel)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80002);
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(underscore__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47821);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_shared_model__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _nodelibrary__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(68091);



class WarningsModel extends (_shared_model__WEBPACK_IMPORTED_MODULE_1___default()) {
    constructor() {
        super();
        this.warnings = {};
        this.notifyChangedScheduled = false;
        // Clear all warnings if a new module (e.g. project) is loaded or unloaded
        _nodelibrary__WEBPACK_IMPORTED_MODULE_2__/* .NodeLibrary */ .m.instance.on(['moduleRegistered', 'moduleUnregistered'], () => {
            this.clearAllWarnings();
        });
    }
    setWarning(ref, warning) {
        var w = this.getWarningsForRef(ref, warning !== undefined);
        if (!warning) {
            if (w)
                delete w[ref.key];
        }
        else {
            warning.level = warning.level || 'warning';
            w[ref.key] = { ref: ref, warning: warning };
        }
        this.scheduleNotifyChanged();
    }
    clearWarningsForRef(ref) {
        var w = this.getWarningsForRef(ref);
        if (!w)
            return;
        for (var i in w)
            delete w[i];
        this.scheduleNotifyChanged();
    }
    clearAllWarningsForComponent(component) {
        const warnings = this.warnings[component.name];
        if (!warnings)
            return;
        for (let i in warnings)
            delete warnings[i];
        this.scheduleNotifyChanged();
    }
    clearWarningsForRefMatching(matchCb) {
        for (const cw of Object.values(this.warnings)) {
            for (const ws of Object.values(cw)) {
                for (const key in ws) {
                    const w = ws[key];
                    if (matchCb(w.ref)) {
                        delete ws[key];
                    }
                }
            }
        }
        this.scheduleNotifyChanged();
    }
    clearAllWarnings() {
        this.warnings = {};
        this.scheduleNotifyChanged();
    }
    getWarnings(ref) {
        var w = this.getWarningsForRef(ref);
        if (!w)
            return;
        if (Object.keys(w).length === 0)
            return;
        // Create short message for hover
        var messages = [];
        for (var k in w) {
            if (w[k].warning)
                messages.push(w[k].warning.message);
        }
        return {
            shortMessage: messages.join('<br>'),
            warnings: (0,underscore__WEBPACK_IMPORTED_MODULE_0__.toArray)(w)
        };
    }
    forEachWarningInComponent(c, callback, args) {
        var cw = this.warnings[c ? c.name : '/'];
        if (!cw)
            return;
        for (var ref in cw) {
            var ws = cw[ref];
            for (var w in ws) {
                if (!args || !args.levels || args.levels.indexOf(ws[w].warning.level) !== -1) {
                    callback(ws[w]);
                }
            }
        }
    }
    getAllWarningsForComponent(c, args) {
        var warnings = [];
        this.forEachWarningInComponent(c, function (warning) {
            warnings.push(warning);
        }, args);
        return warnings;
    }
    getNumberOfWarningsForComponent(c, args) {
        const cw = this.warnings[c ? c.name : '/'];
        if (cw) {
            let warnings = 0;
            for (const i in cw) {
                const ws = cw[i];
                for (const w in ws) {
                    const matchesLevel = !args || !args.levels || args.levels.indexOf(ws[w].warning.level) !== -1;
                    const excludeGlobal = args && args.excludeGlobal && ws[w].warning.showGlobally;
                    if (matchesLevel && !excludeGlobal) {
                        warnings++;
                    }
                }
            }
            return warnings;
        }
        return 0;
    }
    getTotalNumberOfWarnings(args) {
        var total = 0;
        for (var key in this.warnings) {
            total += this.getNumberOfWarningsForComponent({ name: key }, args);
        }
        return total;
    }
    getTotalNumberOfWarningsMatching(matchCb) {
        var total = 0;
        this.forEachWarning((c, ref, key, warning) => {
            if (matchCb(key, ref, warning))
                total++;
        });
        return total;
    }
    forEachWarning(callback) {
        var w = this.warnings;
        for (const c in w) {
            // Loop over all components
            var _w = w[c];
            for (const ref in _w) {
                // Loop over all refs
                var __w = _w[ref];
                for (const key in __w) {
                    // Loop over all keys
                    var warning = __w[key];
                    callback(c, ref, key, warning);
                }
            }
        }
    }
    hasComponentWarnings(c, args) {
        return this.getNumberOfWarningsForComponent(c, args) > 0;
    }
    // Warnings references MUST contain component and key
    // Can optionally contain node and connection (but need one of them)
    // {component: componentRef,
    //    node: nodeRef,
    //    connection: connectionRef,
    //    key: key of warning as string}
    getWarningsForRef(ref, create) {
        var componentName = ref.component ? ref.component.name : '/';
        if (!this.warnings[componentName])
            this.warnings[componentName] = {};
        var cw = this.warnings[componentName];
        var key;
        if (ref.node)
            key = 'node/' + ref.node.id;
        else if (ref.connection)
            key =
                'con/' +
                    ref.connection.fromId +
                    ':' +
                    ref.connection.fromProperty +
                    ':' +
                    ref.connection.toId +
                    ':' +
                    ref.connection.toProperty;
        else
            key = '/'; // Component wide warnings is filed under /
        if (!cw[key] && create)
            cw[key] = {};
        return cw[key];
    }
    /** Batch changed notifications so listeners don't get peppered */
    scheduleNotifyChanged() {
        var _this = this;
        if (this.notifyChangedScheduled)
            return;
        this.notifyChangedScheduled = true;
        setTimeout(function () {
            _this.notifyChangedScheduled && _this.notifyListeners('warningsChanged');
            _this.notifyChangedScheduled = false;
        }, 1);
    }
}
WarningsModel.instance = new WarningsModel();


/***/ }),

/***/ 86259:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRadiobuttonGroupLine = function SvgRadiobuttonGroupLine(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M8.18335 25.1716C9.9982 25.1716 11.4694 23.7003 11.4694 21.8855C11.4694 20.0706 9.9982 18.5994 8.18335 18.5994C6.36849 18.5994 4.89727 20.0706 4.89727 21.8855C4.89727 23.7003 6.36849 25.1716 8.18335 25.1716ZM12.6694 21.8855C12.6694 24.3631 10.6609 26.3716 8.18335 26.3716C5.70575 26.3716 3.69727 24.3631 3.69727 21.8855C3.69727 19.4079 5.70575 17.3994 8.18335 17.3994C10.6609 17.3994 12.6694 19.4079 12.6694 21.8855Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M8.18357 22.9173C8.75337 22.9173 9.21528 22.4554 9.21528 21.8856C9.21528 21.3158 8.75337 20.8539 8.18357 20.8539C7.61377 20.8539 7.15186 21.3158 7.15186 21.8856C7.15186 22.4554 7.61377 22.9173 8.18357 22.9173Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M8.18335 12.3176C9.9982 12.3176 11.4694 10.8463 11.4694 9.03149C11.4694 7.21664 9.9982 5.74541 8.18335 5.74541C6.36849 5.74541 4.89727 7.21664 4.89727 9.03149C4.89727 10.8463 6.36849 12.3176 8.18335 12.3176ZM12.6694 9.03149C12.6694 11.5091 10.6609 13.5176 8.18335 13.5176C5.70575 13.5176 3.69727 11.5091 3.69727 9.03149C3.69727 6.5539 5.70575 4.54541 8.18335 4.54541C10.6609 4.54541 12.6694 6.5539 12.6694 9.03149Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M15.8379 9.03149C15.8379 8.47921 16.2856 8.03149 16.8379 8.03149H26.4095C26.9618 8.03149 27.4095 8.47921 27.4095 9.03149C27.4095 9.58378 26.9618 10.0315 26.4095 10.0315H16.8379C16.2856 10.0315 15.8379 9.58378 15.8379 9.03149Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M15.8379 21.8856C15.8379 21.3333 16.2856 20.8856 16.8379 20.8856H26.4095C26.9618 20.8856 27.4095 21.3333 27.4095 21.8856C27.4095 22.4379 26.9618 22.8856 26.4095 22.8856H16.8379C16.2856 22.8856 15.8379 22.4379 15.8379 21.8856Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRadiobuttonGroupLine);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "735fa3b1dde02d25bce8d06bce283cdd.svg");

/***/ }),

/***/ 86373:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.LauncherProjectCard-module__Image--MicwP{width:100px;margin:-16px;margin-right:16px;border-radius:2px 0 0 2px;background-size:cover}.LauncherProjectCard-module__Details--xKRCL{width:100%}.LauncherProjectCard-module__TypeDisplay--jycvH{margin-bottom:8px}.LauncherProjectCard-module__VersionControlTooltip--ZufM1{cursor:default}.LauncherProjectCard-module__LegacyCard--_AgvH{border-color:var(--theme-color-border-danger) !important}.LauncherProjectCard-module__LegacyCard--_AgvH:hover{border-color:var(--theme-color-border-danger) !important}.LauncherProjectCard-module__LegacyBanner--jhBfa{display:flex;align-items:center;justify-content:space-between;gap:var(--spacing-2);margin-top:var(--spacing-3);padding:var(--spacing-2) var(--spacing-3);background-color:var(--theme-color-bg-danger-subtle);border:1px solid var(--theme-color-border-danger);border-radius:var(--border-radius-medium)}.LauncherProjectCard-module__LegacyDetails--XqYSR{margin-top:var(--spacing-2);padding:var(--spacing-3);background-color:var(--theme-color-bg-2);border-radius:var(--border-radius-medium);border:1px solid var(--theme-color-border-default)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherProjectCard/LauncherProjectCard.module.scss"],"names":[],"mappings":"AAAA,0CACE,WAAA,CACA,YAAA,CACA,iBAAA,CACA,yBAAA,CACA,qBAAA,CAGF,4CACE,UAAA,CAGF,gDACE,iBAAA,CAGF,0DACE,cAAA,CAIF,+CACE,wDAAA,CAEA,qDACE,wDAAA,CAIJ,iDACE,YAAA,CACA,kBAAA,CACA,6BAAA,CACA,oBAAA,CACA,2BAAA,CACA,yCAAA,CACA,oDAAA,CACA,iDAAA,CACA,yCAAA,CAGF,kDACE,2BAAA,CACA,wBAAA,CACA,wCAAA,CACA,yCAAA,CACA,kDAAA","sourcesContent":[".Image {\n  width: 100px;\n  margin: -16px;\n  margin-right: 16px;\n  border-radius: 2px 0 0 2px;\n  background-size: cover;\n}\n\n.Details {\n  width: 100%;\n}\n\n.TypeDisplay {\n  margin-bottom: 8px;\n}\n\n.VersionControlTooltip {\n  cursor: default;\n}\n\n// Legacy project styles\n.LegacyCard {\n  border-color: var(--theme-color-border-danger) !important;\n\n  &:hover {\n    border-color: var(--theme-color-border-danger) !important;\n  }\n}\n\n.LegacyBanner {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: var(--spacing-2);\n  margin-top: var(--spacing-3);\n  padding: var(--spacing-2) var(--spacing-3);\n  background-color: var(--theme-color-bg-danger-subtle);\n  border: 1px solid var(--theme-color-border-danger);\n  border-radius: var(--border-radius-medium);\n}\n\n.LegacyDetails {\n  margin-top: var(--spacing-2);\n  padding: var(--spacing-3);\n  background-color: var(--theme-color-bg-2);\n  border-radius: var(--border-radius-medium);\n  border: 1px solid var(--theme-color-border-default);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Image": `LauncherProjectCard-module__Image--MicwP`,
	"Details": `LauncherProjectCard-module__Details--xKRCL`,
	"TypeDisplay": `LauncherProjectCard-module__TypeDisplay--jycvH`,
	"VersionControlTooltip": `LauncherProjectCard-module__VersionControlTooltip--ZufM1`,
	"LegacyCard": `LauncherProjectCard-module__LegacyCard--_AgvH`,
	"LegacyBanner": `LauncherProjectCard-module__LegacyBanner--jhBfa`,
	"LegacyDetails": `LauncherProjectCard-module__LegacyDetails--XqYSR`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 86380:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  zt: () => (/* reexport */ HStack),
  BJ: () => (/* reexport */ Stack),
  Tk: () => (/* reexport */ VStack)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/Stack/Stack.module.scss
var Stack_module = __webpack_require__(43725);
;// ../noodl-core-ui/src/components/layout/Stack/Stack.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(Stack_module/* default */.A, options);




       /* harmony default export */ const Stack_Stack_module = (Stack_module/* default */.A && Stack_module/* default */.A.locals ? Stack_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/Stack/Stack.tsx



function convertSpacing(options, ...values) {
    for (const value of values) {
        if (typeof value === 'boolean' && value) {
            return options.default;
        }
        if (typeof value === 'number') {
            return value * 4 + 'px';
        }
    }
    return undefined;
}
const Stack = external_react_default().forwardRef(({ direction, hasSpacing, UNSAFE_style, UNSAFE_className, children }, ref) => {
    const style = {
        ...UNSAFE_style,
        flexDirection: direction
    };
    if (direction === 'column') {
        if (!style.width)
            style.width = '100%';
    }
    else if (direction === 'row') {
        if (!style.height)
            style.height = '100%';
    }
    if (hasSpacing) {
        style.gap = convertSpacing({ default: '16px' }, hasSpacing);
    }
    return (external_react_default().createElement("div", { ref: ref, className: external_classnames_default()([Stack_Stack_module['Root'], UNSAFE_className]), style: style }, children));
});
const HStack = external_react_default().forwardRef((props, ref) => {
    return external_react_default().createElement(Stack, { ref: ref, ...props, direction: "row" });
});
const VStack = external_react_default().forwardRef((props, ref) => {
    return external_react_default().createElement(Stack, { ref: ref, ...props, direction: "column" });
});

;// ../noodl-core-ui/src/components/layout/Stack/index.ts



/***/ }),

/***/ 86521:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.BasePanel-module__Root--xwq36{display:flex;flex-direction:column;height:100%;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-subtle);border-radius:var(--radius-md);padding:var(--spacing-panel-padding);gap:var(--spacing-panel-gap)}.BasePanel-module__Inner--MF3oV{position:relative;display:flex;flex-direction:column;justify-content:space-between;flex-grow:1;overflow:hidden}.BasePanel-module__ChildrenContainer--i4uZD{overflow:hidden;display:flex;flex-direction:column}.BasePanel-module__ChildrenContainer--i4uZD.BasePanel-module__has-content-scroll--bDz7v{overflow-y:overlay;z-index:0}.BasePanel-module__ChildrenContainer--i4uZD.BasePanel-module__has-content-scroll--bDz7v::-webkit-scrollbar{width:8px}.BasePanel-module__ChildrenContainer--i4uZD.BasePanel-module__has-content-scroll--bDz7v::-webkit-scrollbar-track{background:var(--theme-color-bg-3)}.BasePanel-module__ChildrenContainer--i4uZD.BasePanel-module__has-content-scroll--bDz7v::-webkit-scrollbar-thumb{background:var(--theme-color-bg-5);border-radius:var(--radius-full)}.BasePanel-module__ChildrenContainer--i4uZD.BasePanel-module__has-content-scroll--bDz7v::-webkit-scrollbar-thumb:hover{background:var(--theme-color-fg-muted)}.BasePanel-module__ChildrenContainer--i4uZD.BasePanel-module__is-fill--ey3me{flex:1}.BasePanel-module__Footer--HMLok{position:sticky;bottom:0}.BasePanel-module__Footer--HMLok::before{z-index:-1;content:"";position:absolute;top:var(--spacing-1);left:0;right:0;height:10px;border-radius:50%;box-shadow:var(--shadow-sm) var(--theme-color-bg-2);pointer-events:none}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/sidebar/BasePanel/BasePanel.module.scss"],"names":[],"mappings":"AAAA,+BACE,YAAA,CACA,qBAAA,CACA,WAAA,CAGA,wCAAA,CAGA,iDAAA,CACA,8BAAA,CAGA,oCAAA,CAGA,4BAAA,CAGF,gCACE,iBAAA,CACA,YAAA,CACA,qBAAA,CACA,6BAAA,CACA,WAAA,CACA,eAAA,CAGF,4CACE,eAAA,CACA,YAAA,CACA,qBAAA,CAEA,wFACE,kBAAA,CACA,SAAA,CAGA,2GACE,SAAA,CAGF,iHACE,kCAAA,CAGF,iHACE,kCAAA,CACA,gCAAA,CAEA,uHACE,sCAAA,CAKN,6EACE,MAAA,CAIJ,iCACE,eAAA,CACA,QAAA,CAEA,yCACE,UAAA,CACA,UAAA,CACA,iBAAA,CACA,oBAAA,CACA,MAAA,CACA,OAAA,CACA,WAAA,CACA,iBAAA,CACA,mDAAA,CACA,mBAAA","sourcesContent":[".Root {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n\n  /* Background */\n  background-color: var(--theme-color-bg-2);\n\n  /* Subtle border for definition */\n  border: 1px solid var(--theme-color-border-subtle);\n  border-radius: var(--radius-md);\n\n  /* Consistent padding */\n  padding: var(--spacing-panel-padding);\n\n  /* Panel gap between children */\n  gap: var(--spacing-panel-gap);\n}\n\n.Inner {\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  justify-content: space-between;\n  flex-grow: 1;\n  overflow: hidden;\n}\n\n.ChildrenContainer {\n  overflow: hidden;\n  display: flex;\n  flex-direction: column;\n\n  &.has-content-scroll {\n    overflow-y: overlay;\n    z-index: 0;\n\n    /* Custom scrollbar styling */\n    &::-webkit-scrollbar {\n      width: 8px;\n    }\n\n    &::-webkit-scrollbar-track {\n      background: var(--theme-color-bg-3);\n    }\n\n    &::-webkit-scrollbar-thumb {\n      background: var(--theme-color-bg-5);\n      border-radius: var(--radius-full);\n\n      &:hover {\n        background: var(--theme-color-fg-muted);\n      }\n    }\n  }\n\n  &.is-fill {\n    flex: 1;\n  }\n}\n\n.Footer {\n  position: sticky;\n  bottom: 0;\n\n  &::before {\n    z-index: -1;\n    content: '';\n    position: absolute;\n    top: var(--spacing-1);\n    left: 0;\n    right: 0;\n    height: 10px;\n    border-radius: 50%;\n    box-shadow: var(--shadow-sm) var(--theme-color-bg-2);\n    pointer-events: none;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `BasePanel-module__Root--xwq36`,
	"Inner": `BasePanel-module__Inner--MF3oV`,
	"ChildrenContainer": `BasePanel-module__ChildrenContainer--i4uZD`,
	"has-content-scroll": `BasePanel-module__has-content-scroll--bDz7v`,
	"is-fill": `BasePanel-module__is-fill--ey3me`,
	"Footer": `BasePanel-module__Footer--HMLok`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 86541:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSliders = function SvgSliders(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M17.0483 11.1433C15.9438 11.1433 15.0483 10.2478 15.0483 9.14326C15.0483 8.03869 15.9438 7.14326 17.0483 7.14326C18.1529 7.14326 19.0483 8.03869 19.0483 9.14326C19.0483 10.2478 18.1529 11.1433 17.0483 11.1433ZM16.3037 12.5639C14.7284 12.2226 13.5483 10.8207 13.5483 9.14326C13.5483 7.46579 14.7284 6.06395 16.3037 5.72263L16.3037 4.01318C16.3037 3.59897 16.6395 3.26318 17.0537 3.26318C17.4679 3.26318 17.8037 3.59897 17.8037 4.01318L17.8037 5.72498C19.3736 6.07033 20.5483 7.46961 20.5483 9.14326C20.5483 10.8169 19.3736 12.2162 17.8037 12.5615L17.8037 20.5132C17.8037 20.9274 17.4679 21.2632 17.0537 21.2632C16.6395 21.2632 16.3037 20.9274 16.3037 20.5132L16.3037 12.5639ZM9.2251 15.3831C9.2251 14.2785 8.32967 13.3831 7.2251 13.3831C6.12053 13.3831 5.2251 14.2785 5.2251 15.3831C5.2251 16.4877 6.12053 17.3831 7.2251 17.3831C8.32967 17.3831 9.2251 16.4877 9.2251 15.3831ZM6.46973 4.01318L6.46973 11.9648C4.89983 12.3102 3.7251 13.7095 3.7251 15.3831C3.7251 17.0568 4.89983 18.456 6.46972 18.8014L6.46972 20.5132C6.46972 20.9274 6.80551 21.2632 7.21972 21.2632C7.63394 21.2632 7.96972 20.9274 7.96972 20.5132L7.96972 18.8037C9.54501 18.4624 10.7251 17.0606 10.7251 15.3831C10.7251 13.7056 9.54501 12.3038 7.96973 11.9625L7.96973 4.01318C7.96973 3.59897 7.63394 3.26318 7.21973 3.26318C6.80551 3.26318 6.46973 3.59897 6.46973 4.01318Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSliders);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "9603faa07174baa49c45427fbc5a8e8a.svg");

/***/ }),

/***/ 86543:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.deserialize = exports.serialize = exports.isSerializableObject = exports.isPromise = void 0;
const electron_1 = __webpack_require__(91288);
function isPromise(val) {
    return (val &&
        val.then &&
        val.then instanceof Function &&
        val.constructor &&
        val.constructor.reject &&
        val.constructor.reject instanceof Function &&
        val.constructor.resolve &&
        val.constructor.resolve instanceof Function);
}
exports.isPromise = isPromise;
const serializableTypes = [
    Boolean,
    Number,
    String,
    Date,
    Error,
    RegExp,
    ArrayBuffer
];
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#Supported_types
function isSerializableObject(value) {
    return value === null || ArrayBuffer.isView(value) || serializableTypes.some(type => value instanceof type);
}
exports.isSerializableObject = isSerializableObject;
const objectMap = function (source, mapper) {
    const sourceEntries = Object.entries(source);
    const targetEntries = sourceEntries.map(([key, val]) => [key, mapper(val)]);
    return Object.fromEntries(targetEntries);
};
function serializeNativeImage(image) {
    const representations = [];
    const scaleFactors = image.getScaleFactors();
    // Use Buffer when there's only one representation for better perf.
    // This avoids compressing to/from PNG where it's not necessary to
    // ensure uniqueness of dataURLs (since there's only one).
    if (scaleFactors.length === 1) {
        const scaleFactor = scaleFactors[0];
        const size = image.getSize(scaleFactor);
        const buffer = image.toBitmap({ scaleFactor });
        representations.push({ scaleFactor, size, buffer });
    }
    else {
        // Construct from dataURLs to ensure that they are not lost in creation.
        for (const scaleFactor of scaleFactors) {
            const size = image.getSize(scaleFactor);
            const dataURL = image.toDataURL({ scaleFactor });
            representations.push({ scaleFactor, size, dataURL });
        }
    }
    return { __ELECTRON_SERIALIZED_NativeImage__: true, representations };
}
function deserializeNativeImage(value) {
    const image = electron_1.nativeImage.createEmpty();
    // Use Buffer when there's only one representation for better perf.
    // This avoids compressing to/from PNG where it's not necessary to
    // ensure uniqueness of dataURLs (since there's only one).
    if (value.representations.length === 1) {
        const { buffer, size, scaleFactor } = value.representations[0];
        const { width, height } = size;
        image.addRepresentation({ buffer, scaleFactor, width, height });
    }
    else {
        // Construct from dataURLs to ensure that they are not lost in creation.
        for (const rep of value.representations) {
            const { dataURL, size, scaleFactor } = rep;
            const { width, height } = size;
            image.addRepresentation({ dataURL, scaleFactor, width, height });
        }
    }
    return image;
}
function serialize(value) {
    if (value && value.constructor && value.constructor.name === 'NativeImage') {
        return serializeNativeImage(value);
    }
    if (Array.isArray(value)) {
        return value.map(serialize);
    }
    else if (isSerializableObject(value)) {
        return value;
    }
    else if (value instanceof Object) {
        return objectMap(value, serialize);
    }
    else {
        return value;
    }
}
exports.serialize = serialize;
function deserialize(value) {
    if (value && value.__ELECTRON_SERIALIZED_NativeImage__) {
        return deserializeNativeImage(value);
    }
    else if (Array.isArray(value)) {
        return value.map(deserialize);
    }
    else if (isSerializableObject(value)) {
        return value;
    }
    else if (value instanceof Object) {
        return objectMap(value, deserialize);
    }
    else {
        return value;
    }
}
exports.deserialize = deserialize;


/***/ }),

/***/ 86716:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Checkbox-module__Root--IDiQI{font-family:var(--font-family);cursor:pointer;display:flex;align-items:center}.Checkbox-module__Root--IDiQI.Checkbox-module__has-bottom-spacing--KzklB{margin-bottom:15px}.Checkbox-module__Checkbox--D_Ulb{display:none}.Checkbox-module__FauxCheckbox--M_Hs1{background-color:var(--theme-color-bg-2);display:flex;align-items:center;justify-content:center}.Checkbox-module__FauxCheckbox--M_Hs1.Checkbox-module__is-size-small--ybYJv{width:20px;height:20px}.Checkbox-module__FauxCheckbox--M_Hs1.Checkbox-module__is-size-large--PUSu6{width:33px;height:33px}.Checkbox-module__FauxCheckbox--M_Hs1.Checkbox-module__has-right-margin--nuCCD{margin-right:10px}.Checkbox-module__Root--IDiQI.Checkbox-module__is-variant-sidebar--S0ZIS .Checkbox-module__FauxCheckbox--M_Hs1{background-color:var(--theme-color-bg-1)}.Checkbox-module__Root--IDiQI.Checkbox-module__is-variant-light--H5vdT .Checkbox-module__FauxCheckbox--M_Hs1{background-color:var(--theme-color-bg-4)}.Checkbox-module__CheckMark--cCfkf{transition:opacity var(--speed-turbo);pointer-events:none}.Checkbox-module__CheckMark--cCfkf.Checkbox-module__is-checked--wG6rr{opacity:1}.Checkbox-module__CheckMark--cCfkf.Checkbox-module__is-unchecked--GbYix{opacity:0}.Checkbox-module__Label--DKlJv{padding-left:16px;font-size:14px;color:var(--theme-color-fg-default);transition:color var(--speed-turbo)}.Checkbox-module__Root--IDiQI:hover .Checkbox-module__Label--DKlJv{color:var(--theme-color-fg-highlight)}.Checkbox-module__ChildContainer--zy1m3{padding-left:16px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/Checkbox/Checkbox.module.scss"],"names":[],"mappings":"AAAA,8BACE,8BAAA,CACA,cAAA,CACA,YAAA,CACA,kBAAA,CAEA,yEACE,kBAAA,CAIJ,kCACE,YAAA,CAGF,sCACE,wCAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CAEA,4EACE,UAAA,CACA,WAAA,CAGF,4EAEE,UAAA,CACA,WAAA,CAGF,+EACE,iBAAA,CAGF,+GACE,wCAAA,CAGF,6GACE,wCAAA,CAIJ,mCACE,qCAAA,CACA,mBAAA,CAEA,sEACE,SAAA,CAGF,wEACE,SAAA,CAIJ,+BACE,iBAAA,CACA,cAAA,CACA,mCAAA,CACA,mCAAA,CAEA,mEACE,qCAAA,CAIJ,wCACE,iBAAA","sourcesContent":[".Root {\n  font-family: var(--font-family);\n  cursor: pointer;\n  display: flex;\n  align-items: center;\n\n  &.has-bottom-spacing {\n    margin-bottom: 15px;\n  }\n}\n\n.Checkbox {\n  display: none;\n}\n\n.FauxCheckbox {\n  background-color: var(--theme-color-bg-2);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n\n  &.is-size-small {\n    width: 20px;\n    height: 20px;\n  }\n\n  &.is-size-large {\n    // Placeholder styles here atm, should match the look of checkboxes in the Property Panel\n    width: 33px;\n    height: 33px;\n  }\n\n  &.has-right-margin {\n    margin-right: 10px;\n  }\n\n  .Root.is-variant-sidebar & {\n    background-color: var(--theme-color-bg-1);\n  }\n\n  .Root.is-variant-light & {\n    background-color: var(--theme-color-bg-4);\n  }\n}\n\n.CheckMark {\n  transition: opacity var(--speed-turbo);\n  pointer-events: none;\n\n  &.is-checked {\n    opacity: 1;\n  }\n\n  &.is-unchecked {\n    opacity: 0;\n  }\n}\n\n.Label {\n  padding-left: 16px;\n  font-size: 14px;\n  color: var(--theme-color-fg-default);\n  transition: color var(--speed-turbo);\n\n  .Root:hover & {\n    color: var(--theme-color-fg-highlight);\n  }\n}\n\n.ChildContainer {\n  padding-left: 16px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Checkbox-module__Root--IDiQI`,
	"has-bottom-spacing": `Checkbox-module__has-bottom-spacing--KzklB`,
	"Checkbox": `Checkbox-module__Checkbox--D_Ulb`,
	"FauxCheckbox": `Checkbox-module__FauxCheckbox--M_Hs1`,
	"is-size-small": `Checkbox-module__is-size-small--ybYJv`,
	"is-size-large": `Checkbox-module__is-size-large--PUSu6`,
	"has-right-margin": `Checkbox-module__has-right-margin--nuCCD`,
	"is-variant-sidebar": `Checkbox-module__is-variant-sidebar--S0ZIS`,
	"is-variant-light": `Checkbox-module__is-variant-light--H5vdT`,
	"CheckMark": `Checkbox-module__CheckMark--cCfkf`,
	"is-checked": `Checkbox-module__is-checked--wG6rr`,
	"is-unchecked": `Checkbox-module__is-unchecked--GbYix`,
	"Label": `Checkbox-module__Label--DKlJv`,
	"ChildContainer": `Checkbox-module__ChildContainer--zy1m3`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 86919:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   K: () => (/* binding */ registerLanguage)
/* harmony export */ });
/* unused harmony export loadLanguage */
/* harmony import */ var _editor_editor_api_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15618);
/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));

// src/fillers/monaco-editor-core.ts
var monaco_editor_core_exports = {};
__reExport(monaco_editor_core_exports, _editor_editor_api_js__WEBPACK_IMPORTED_MODULE_0__);


// src/basic-languages/_.contribution.ts
var languageDefinitions = {};
var lazyLanguageLoaders = {};
var LazyLanguageLoader = class {
  static getOrCreate(languageId) {
    if (!lazyLanguageLoaders[languageId]) {
      lazyLanguageLoaders[languageId] = new LazyLanguageLoader(languageId);
    }
    return lazyLanguageLoaders[languageId];
  }
  _languageId;
  _loadingTriggered;
  _lazyLoadPromise;
  _lazyLoadPromiseResolve;
  _lazyLoadPromiseReject;
  constructor(languageId) {
    this._languageId = languageId;
    this._loadingTriggered = false;
    this._lazyLoadPromise = new Promise((resolve, reject) => {
      this._lazyLoadPromiseResolve = resolve;
      this._lazyLoadPromiseReject = reject;
    });
  }
  load() {
    if (!this._loadingTriggered) {
      this._loadingTriggered = true;
      languageDefinitions[this._languageId].loader().then((mod) => this._lazyLoadPromiseResolve(mod), (err) => this._lazyLoadPromiseReject(err));
    }
    return this._lazyLoadPromise;
  }
};
async function loadLanguage(languageId) {
  await LazyLanguageLoader.getOrCreate(languageId).load();
  const model = monaco_editor_core_exports.editor.createModel("", languageId);
  model.dispose();
}
function registerLanguage(def) {
  const languageId = def.id;
  languageDefinitions[languageId] = def;
  monaco_editor_core_exports.languages.register(def);
  const lazyLanguageLoader = LazyLanguageLoader.getOrCreate(languageId);
  monaco_editor_core_exports.languages.registerTokensProviderFactory(languageId, {
    create: async () => {
      const mod = await lazyLanguageLoader.load();
      return mod.language;
    }
  });
  monaco_editor_core_exports.languages.onLanguage(languageId, async () => {
    const mod = await lazyLanguageLoader.load();
    monaco_editor_core_exports.languages.setLanguageConfiguration(languageId, mod.conf);
  });
}



/***/ }),

/***/ 86974:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
/**
 * @license React
 * react-dom-client.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/*
 Modernizr 3.0.0pre (Custom Build) | MIT
*/

var Scheduler = __webpack_require__(7603),
  React = __webpack_require__(54953),
  ReactDOM = __webpack_require__(20180);
function formatProdErrorMessage(code) {
  var url = "https://react.dev/errors/" + code;
  if (1 < arguments.length) {
    url += "?args[]=" + encodeURIComponent(arguments[1]);
    for (var i = 2; i < arguments.length; i++)
      url += "&args[]=" + encodeURIComponent(arguments[i]);
  }
  return (
    "Minified React error #" +
    code +
    "; visit " +
    url +
    " for the full message or use the non-minified dev environment for full errors and additional helpful warnings."
  );
}
function isValidContainer(node) {
  return !(
    !node ||
    (1 !== node.nodeType && 9 !== node.nodeType && 11 !== node.nodeType)
  );
}
var REACT_LEGACY_ELEMENT_TYPE = Symbol.for("react.element"),
  REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"),
  REACT_PORTAL_TYPE = Symbol.for("react.portal"),
  REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"),
  REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"),
  REACT_PROFILER_TYPE = Symbol.for("react.profiler"),
  REACT_PROVIDER_TYPE = Symbol.for("react.provider"),
  REACT_CONSUMER_TYPE = Symbol.for("react.consumer"),
  REACT_CONTEXT_TYPE = Symbol.for("react.context"),
  REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"),
  REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"),
  REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"),
  REACT_MEMO_TYPE = Symbol.for("react.memo"),
  REACT_LAZY_TYPE = Symbol.for("react.lazy");
Symbol.for("react.scope");
Symbol.for("react.debug_trace_mode");
var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
Symbol.for("react.legacy_hidden");
Symbol.for("react.tracing_marker");
var REACT_MEMO_CACHE_SENTINEL = Symbol.for("react.memo_cache_sentinel"),
  MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
function getIteratorFn(maybeIterable) {
  if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
  maybeIterable =
    (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) ||
    maybeIterable["@@iterator"];
  return "function" === typeof maybeIterable ? maybeIterable : null;
}
var REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference");
function getComponentNameFromType(type) {
  if (null == type) return null;
  if ("function" === typeof type)
    return type.$$typeof === REACT_CLIENT_REFERENCE
      ? null
      : type.displayName || type.name || null;
  if ("string" === typeof type) return type;
  switch (type) {
    case REACT_FRAGMENT_TYPE:
      return "Fragment";
    case REACT_PORTAL_TYPE:
      return "Portal";
    case REACT_PROFILER_TYPE:
      return "Profiler";
    case REACT_STRICT_MODE_TYPE:
      return "StrictMode";
    case REACT_SUSPENSE_TYPE:
      return "Suspense";
    case REACT_SUSPENSE_LIST_TYPE:
      return "SuspenseList";
  }
  if ("object" === typeof type)
    switch (type.$$typeof) {
      case REACT_CONTEXT_TYPE:
        return (type.displayName || "Context") + ".Provider";
      case REACT_CONSUMER_TYPE:
        return (type._context.displayName || "Context") + ".Consumer";
      case REACT_FORWARD_REF_TYPE:
        var innerType = type.render;
        type = type.displayName;
        type ||
          ((type = innerType.displayName || innerType.name || ""),
          (type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef"));
        return type;
      case REACT_MEMO_TYPE:
        return (
          (innerType = type.displayName || null),
          null !== innerType
            ? innerType
            : getComponentNameFromType(type.type) || "Memo"
        );
      case REACT_LAZY_TYPE:
        innerType = type._payload;
        type = type._init;
        try {
          return getComponentNameFromType(type(innerType));
        } catch (x) {}
    }
  return null;
}
var ReactSharedInternals =
    React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,
  assign = Object.assign,
  prefix,
  suffix;
function describeBuiltInComponentFrame(name) {
  if (void 0 === prefix)
    try {
      throw Error();
    } catch (x) {
      var match = x.stack.trim().match(/\n( *(at )?)/);
      prefix = (match && match[1]) || "";
      suffix =
        -1 < x.stack.indexOf("\n    at")
          ? " (<anonymous>)"
          : -1 < x.stack.indexOf("@")
            ? "@unknown:0:0"
            : "";
    }
  return "\n" + prefix + name + suffix;
}
var reentry = !1;
function describeNativeComponentFrame(fn, construct) {
  if (!fn || reentry) return "";
  reentry = !0;
  var previousPrepareStackTrace = Error.prepareStackTrace;
  Error.prepareStackTrace = void 0;
  try {
    var RunInRootFrame = {
      DetermineComponentFrameRoot: function () {
        try {
          if (construct) {
            var Fake = function () {
              throw Error();
            };
            Object.defineProperty(Fake.prototype, "props", {
              set: function () {
                throw Error();
              }
            });
            if ("object" === typeof Reflect && Reflect.construct) {
              try {
                Reflect.construct(Fake, []);
              } catch (x) {
                var control = x;
              }
              Reflect.construct(fn, [], Fake);
            } else {
              try {
                Fake.call();
              } catch (x$0) {
                control = x$0;
              }
              fn.call(Fake.prototype);
            }
          } else {
            try {
              throw Error();
            } catch (x$1) {
              control = x$1;
            }
            (Fake = fn()) &&
              "function" === typeof Fake.catch &&
              Fake.catch(function () {});
          }
        } catch (sample) {
          if (sample && control && "string" === typeof sample.stack)
            return [sample.stack, control.stack];
        }
        return [null, null];
      }
    };
    RunInRootFrame.DetermineComponentFrameRoot.displayName =
      "DetermineComponentFrameRoot";
    var namePropDescriptor = Object.getOwnPropertyDescriptor(
      RunInRootFrame.DetermineComponentFrameRoot,
      "name"
    );
    namePropDescriptor &&
      namePropDescriptor.configurable &&
      Object.defineProperty(
        RunInRootFrame.DetermineComponentFrameRoot,
        "name",
        { value: "DetermineComponentFrameRoot" }
      );
    var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(),
      sampleStack = _RunInRootFrame$Deter[0],
      controlStack = _RunInRootFrame$Deter[1];
    if (sampleStack && controlStack) {
      var sampleLines = sampleStack.split("\n"),
        controlLines = controlStack.split("\n");
      for (
        namePropDescriptor = RunInRootFrame = 0;
        RunInRootFrame < sampleLines.length &&
        !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot");

      )
        RunInRootFrame++;
      for (
        ;
        namePropDescriptor < controlLines.length &&
        !controlLines[namePropDescriptor].includes(
          "DetermineComponentFrameRoot"
        );

      )
        namePropDescriptor++;
      if (
        RunInRootFrame === sampleLines.length ||
        namePropDescriptor === controlLines.length
      )
        for (
          RunInRootFrame = sampleLines.length - 1,
            namePropDescriptor = controlLines.length - 1;
          1 <= RunInRootFrame &&
          0 <= namePropDescriptor &&
          sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor];

        )
          namePropDescriptor--;
      for (
        ;
        1 <= RunInRootFrame && 0 <= namePropDescriptor;
        RunInRootFrame--, namePropDescriptor--
      )
        if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
          if (1 !== RunInRootFrame || 1 !== namePropDescriptor) {
            do
              if (
                (RunInRootFrame--,
                namePropDescriptor--,
                0 > namePropDescriptor ||
                  sampleLines[RunInRootFrame] !==
                    controlLines[namePropDescriptor])
              ) {
                var frame =
                  "\n" +
                  sampleLines[RunInRootFrame].replace(" at new ", " at ");
                fn.displayName &&
                  frame.includes("<anonymous>") &&
                  (frame = frame.replace("<anonymous>", fn.displayName));
                return frame;
              }
            while (1 <= RunInRootFrame && 0 <= namePropDescriptor);
          }
          break;
        }
    }
  } finally {
    (reentry = !1), (Error.prepareStackTrace = previousPrepareStackTrace);
  }
  return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "")
    ? describeBuiltInComponentFrame(previousPrepareStackTrace)
    : "";
}
function describeFiber(fiber) {
  switch (fiber.tag) {
    case 26:
    case 27:
    case 5:
      return describeBuiltInComponentFrame(fiber.type);
    case 16:
      return describeBuiltInComponentFrame("Lazy");
    case 13:
      return describeBuiltInComponentFrame("Suspense");
    case 19:
      return describeBuiltInComponentFrame("SuspenseList");
    case 0:
    case 15:
      return (fiber = describeNativeComponentFrame(fiber.type, !1)), fiber;
    case 11:
      return (
        (fiber = describeNativeComponentFrame(fiber.type.render, !1)), fiber
      );
    case 1:
      return (fiber = describeNativeComponentFrame(fiber.type, !0)), fiber;
    default:
      return "";
  }
}
function getStackByFiberInDevAndProd(workInProgress) {
  try {
    var info = "";
    do
      (info += describeFiber(workInProgress)),
        (workInProgress = workInProgress.return);
    while (workInProgress);
    return info;
  } catch (x) {
    return "\nError generating stack: " + x.message + "\n" + x.stack;
  }
}
function getNearestMountedFiber(fiber) {
  var node = fiber,
    nearestMounted = fiber;
  if (fiber.alternate) for (; node.return; ) node = node.return;
  else {
    fiber = node;
    do
      (node = fiber),
        0 !== (node.flags & 4098) && (nearestMounted = node.return),
        (fiber = node.return);
    while (fiber);
  }
  return 3 === node.tag ? nearestMounted : null;
}
function getSuspenseInstanceFromFiber(fiber) {
  if (13 === fiber.tag) {
    var suspenseState = fiber.memoizedState;
    null === suspenseState &&
      ((fiber = fiber.alternate),
      null !== fiber && (suspenseState = fiber.memoizedState));
    if (null !== suspenseState) return suspenseState.dehydrated;
  }
  return null;
}
function assertIsMounted(fiber) {
  if (getNearestMountedFiber(fiber) !== fiber)
    throw Error(formatProdErrorMessage(188));
}
function findCurrentFiberUsingSlowPath(fiber) {
  var alternate = fiber.alternate;
  if (!alternate) {
    alternate = getNearestMountedFiber(fiber);
    if (null === alternate) throw Error(formatProdErrorMessage(188));
    return alternate !== fiber ? null : fiber;
  }
  for (var a = fiber, b = alternate; ; ) {
    var parentA = a.return;
    if (null === parentA) break;
    var parentB = parentA.alternate;
    if (null === parentB) {
      b = parentA.return;
      if (null !== b) {
        a = b;
        continue;
      }
      break;
    }
    if (parentA.child === parentB.child) {
      for (parentB = parentA.child; parentB; ) {
        if (parentB === a) return assertIsMounted(parentA), fiber;
        if (parentB === b) return assertIsMounted(parentA), alternate;
        parentB = parentB.sibling;
      }
      throw Error(formatProdErrorMessage(188));
    }
    if (a.return !== b.return) (a = parentA), (b = parentB);
    else {
      for (var didFindChild = !1, child$2 = parentA.child; child$2; ) {
        if (child$2 === a) {
          didFindChild = !0;
          a = parentA;
          b = parentB;
          break;
        }
        if (child$2 === b) {
          didFindChild = !0;
          b = parentA;
          a = parentB;
          break;
        }
        child$2 = child$2.sibling;
      }
      if (!didFindChild) {
        for (child$2 = parentB.child; child$2; ) {
          if (child$2 === a) {
            didFindChild = !0;
            a = parentB;
            b = parentA;
            break;
          }
          if (child$2 === b) {
            didFindChild = !0;
            b = parentB;
            a = parentA;
            break;
          }
          child$2 = child$2.sibling;
        }
        if (!didFindChild) throw Error(formatProdErrorMessage(189));
      }
    }
    if (a.alternate !== b) throw Error(formatProdErrorMessage(190));
  }
  if (3 !== a.tag) throw Error(formatProdErrorMessage(188));
  return a.stateNode.current === a ? fiber : alternate;
}
function findCurrentHostFiberImpl(node) {
  var tag = node.tag;
  if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return node;
  for (node = node.child; null !== node; ) {
    tag = findCurrentHostFiberImpl(node);
    if (null !== tag) return tag;
    node = node.sibling;
  }
  return null;
}
var isArrayImpl = Array.isArray,
  ReactDOMSharedInternals =
    ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,
  sharedNotPendingObject = {
    pending: !1,
    data: null,
    method: null,
    action: null
  },
  valueStack = [],
  index = -1;
function createCursor(defaultValue) {
  return { current: defaultValue };
}
function pop(cursor) {
  0 > index ||
    ((cursor.current = valueStack[index]), (valueStack[index] = null), index--);
}
function push(cursor, value) {
  index++;
  valueStack[index] = cursor.current;
  cursor.current = value;
}
var contextStackCursor = createCursor(null),
  contextFiberStackCursor = createCursor(null),
  rootInstanceStackCursor = createCursor(null),
  hostTransitionProviderCursor = createCursor(null);
function pushHostContainer(fiber, nextRootInstance) {
  push(rootInstanceStackCursor, nextRootInstance);
  push(contextFiberStackCursor, fiber);
  push(contextStackCursor, null);
  fiber = nextRootInstance.nodeType;
  switch (fiber) {
    case 9:
    case 11:
      nextRootInstance = (nextRootInstance = nextRootInstance.documentElement)
        ? (nextRootInstance = nextRootInstance.namespaceURI)
          ? getOwnHostContext(nextRootInstance)
          : 0
        : 0;
      break;
    default:
      if (
        ((fiber = 8 === fiber ? nextRootInstance.parentNode : nextRootInstance),
        (nextRootInstance = fiber.tagName),
        (fiber = fiber.namespaceURI))
      )
        (fiber = getOwnHostContext(fiber)),
          (nextRootInstance = getChildHostContextProd(fiber, nextRootInstance));
      else
        switch (nextRootInstance) {
          case "svg":
            nextRootInstance = 1;
            break;
          case "math":
            nextRootInstance = 2;
            break;
          default:
            nextRootInstance = 0;
        }
  }
  pop(contextStackCursor);
  push(contextStackCursor, nextRootInstance);
}
function popHostContainer() {
  pop(contextStackCursor);
  pop(contextFiberStackCursor);
  pop(rootInstanceStackCursor);
}
function pushHostContext(fiber) {
  null !== fiber.memoizedState && push(hostTransitionProviderCursor, fiber);
  var context = contextStackCursor.current;
  var JSCompiler_inline_result = getChildHostContextProd(context, fiber.type);
  context !== JSCompiler_inline_result &&
    (push(contextFiberStackCursor, fiber),
    push(contextStackCursor, JSCompiler_inline_result));
}
function popHostContext(fiber) {
  contextFiberStackCursor.current === fiber &&
    (pop(contextStackCursor), pop(contextFiberStackCursor));
  hostTransitionProviderCursor.current === fiber &&
    (pop(hostTransitionProviderCursor),
    (HostTransitionContext._currentValue = sharedNotPendingObject));
}
var hasOwnProperty = Object.prototype.hasOwnProperty,
  scheduleCallback$3 = Scheduler.unstable_scheduleCallback,
  cancelCallback$1 = Scheduler.unstable_cancelCallback,
  shouldYield = Scheduler.unstable_shouldYield,
  requestPaint = Scheduler.unstable_requestPaint,
  now = Scheduler.unstable_now,
  getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel,
  ImmediatePriority = Scheduler.unstable_ImmediatePriority,
  UserBlockingPriority = Scheduler.unstable_UserBlockingPriority,
  NormalPriority$1 = Scheduler.unstable_NormalPriority,
  LowPriority = Scheduler.unstable_LowPriority,
  IdlePriority = Scheduler.unstable_IdlePriority,
  log$1 = Scheduler.log,
  unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue,
  rendererID = null,
  injectedHook = null;
function onCommitRoot(root) {
  if (injectedHook && "function" === typeof injectedHook.onCommitFiberRoot)
    try {
      injectedHook.onCommitFiberRoot(
        rendererID,
        root,
        void 0,
        128 === (root.current.flags & 128)
      );
    } catch (err) {}
}
function setIsStrictModeForDevtools(newIsStrictMode) {
  "function" === typeof log$1 && unstable_setDisableYieldValue(newIsStrictMode);
  if (injectedHook && "function" === typeof injectedHook.setStrictMode)
    try {
      injectedHook.setStrictMode(rendererID, newIsStrictMode);
    } catch (err) {}
}
var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback,
  log = Math.log,
  LN2 = Math.LN2;
function clz32Fallback(x) {
  x >>>= 0;
  return 0 === x ? 32 : (31 - ((log(x) / LN2) | 0)) | 0;
}
var nextTransitionLane = 128,
  nextRetryLane = 4194304;
function getHighestPriorityLanes(lanes) {
  var pendingSyncLanes = lanes & 42;
  if (0 !== pendingSyncLanes) return pendingSyncLanes;
  switch (lanes & -lanes) {
    case 1:
      return 1;
    case 2:
      return 2;
    case 4:
      return 4;
    case 8:
      return 8;
    case 16:
      return 16;
    case 32:
      return 32;
    case 64:
      return 64;
    case 128:
    case 256:
    case 512:
    case 1024:
    case 2048:
    case 4096:
    case 8192:
    case 16384:
    case 32768:
    case 65536:
    case 131072:
    case 262144:
    case 524288:
    case 1048576:
    case 2097152:
      return lanes & 4194176;
    case 4194304:
    case 8388608:
    case 16777216:
    case 33554432:
      return lanes & 62914560;
    case 67108864:
      return 67108864;
    case 134217728:
      return 134217728;
    case 268435456:
      return 268435456;
    case 536870912:
      return 536870912;
    case 1073741824:
      return 0;
    default:
      return lanes;
  }
}
function getNextLanes(root, wipLanes) {
  var pendingLanes = root.pendingLanes;
  if (0 === pendingLanes) return 0;
  var nextLanes = 0,
    suspendedLanes = root.suspendedLanes,
    pingedLanes = root.pingedLanes,
    warmLanes = root.warmLanes;
  root = 0 !== root.finishedLanes;
  var nonIdlePendingLanes = pendingLanes & 134217727;
  0 !== nonIdlePendingLanes
    ? ((pendingLanes = nonIdlePendingLanes & ~suspendedLanes),
      0 !== pendingLanes
        ? (nextLanes = getHighestPriorityLanes(pendingLanes))
        : ((pingedLanes &= nonIdlePendingLanes),
          0 !== pingedLanes
            ? (nextLanes = getHighestPriorityLanes(pingedLanes))
            : root ||
              ((warmLanes = nonIdlePendingLanes & ~warmLanes),
              0 !== warmLanes &&
                (nextLanes = getHighestPriorityLanes(warmLanes)))))
    : ((nonIdlePendingLanes = pendingLanes & ~suspendedLanes),
      0 !== nonIdlePendingLanes
        ? (nextLanes = getHighestPriorityLanes(nonIdlePendingLanes))
        : 0 !== pingedLanes
          ? (nextLanes = getHighestPriorityLanes(pingedLanes))
          : root ||
            ((warmLanes = pendingLanes & ~warmLanes),
            0 !== warmLanes &&
              (nextLanes = getHighestPriorityLanes(warmLanes))));
  return 0 === nextLanes
    ? 0
    : 0 !== wipLanes &&
        wipLanes !== nextLanes &&
        0 === (wipLanes & suspendedLanes) &&
        ((suspendedLanes = nextLanes & -nextLanes),
        (warmLanes = wipLanes & -wipLanes),
        suspendedLanes >= warmLanes ||
          (32 === suspendedLanes && 0 !== (warmLanes & 4194176)))
      ? wipLanes
      : nextLanes;
}
function checkIfRootIsPrerendering(root, renderLanes) {
  return (
    0 ===
    (root.pendingLanes &
      ~(root.suspendedLanes & ~root.pingedLanes) &
      renderLanes)
  );
}
function computeExpirationTime(lane, currentTime) {
  switch (lane) {
    case 1:
    case 2:
    case 4:
    case 8:
      return currentTime + 250;
    case 16:
    case 32:
    case 64:
    case 128:
    case 256:
    case 512:
    case 1024:
    case 2048:
    case 4096:
    case 8192:
    case 16384:
    case 32768:
    case 65536:
    case 131072:
    case 262144:
    case 524288:
    case 1048576:
    case 2097152:
      return currentTime + 5e3;
    case 4194304:
    case 8388608:
    case 16777216:
    case 33554432:
      return -1;
    case 67108864:
    case 134217728:
    case 268435456:
    case 536870912:
    case 1073741824:
      return -1;
    default:
      return -1;
  }
}
function claimNextTransitionLane() {
  var lane = nextTransitionLane;
  nextTransitionLane <<= 1;
  0 === (nextTransitionLane & 4194176) && (nextTransitionLane = 128);
  return lane;
}
function claimNextRetryLane() {
  var lane = nextRetryLane;
  nextRetryLane <<= 1;
  0 === (nextRetryLane & 62914560) && (nextRetryLane = 4194304);
  return lane;
}
function createLaneMap(initial) {
  for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial);
  return laneMap;
}
function markRootUpdated$1(root, updateLane) {
  root.pendingLanes |= updateLane;
  268435456 !== updateLane &&
    ((root.suspendedLanes = 0), (root.pingedLanes = 0), (root.warmLanes = 0));
}
function markRootFinished(
  root,
  finishedLanes,
  remainingLanes,
  spawnedLane,
  updatedLanes,
  suspendedRetryLanes
) {
  var previouslyPendingLanes = root.pendingLanes;
  root.pendingLanes = remainingLanes;
  root.suspendedLanes = 0;
  root.pingedLanes = 0;
  root.warmLanes = 0;
  root.expiredLanes &= remainingLanes;
  root.entangledLanes &= remainingLanes;
  root.errorRecoveryDisabledLanes &= remainingLanes;
  root.shellSuspendCounter = 0;
  var entanglements = root.entanglements,
    expirationTimes = root.expirationTimes,
    hiddenUpdates = root.hiddenUpdates;
  for (
    remainingLanes = previouslyPendingLanes & ~remainingLanes;
    0 < remainingLanes;

  ) {
    var index$7 = 31 - clz32(remainingLanes),
      lane = 1 << index$7;
    entanglements[index$7] = 0;
    expirationTimes[index$7] = -1;
    var hiddenUpdatesForLane = hiddenUpdates[index$7];
    if (null !== hiddenUpdatesForLane)
      for (
        hiddenUpdates[index$7] = null, index$7 = 0;
        index$7 < hiddenUpdatesForLane.length;
        index$7++
      ) {
        var update = hiddenUpdatesForLane[index$7];
        null !== update && (update.lane &= -536870913);
      }
    remainingLanes &= ~lane;
  }
  0 !== spawnedLane && markSpawnedDeferredLane(root, spawnedLane, 0);
  0 !== suspendedRetryLanes &&
    0 === updatedLanes &&
    0 !== root.tag &&
    (root.suspendedLanes |=
      suspendedRetryLanes & ~(previouslyPendingLanes & ~finishedLanes));
}
function markSpawnedDeferredLane(root, spawnedLane, entangledLanes) {
  root.pendingLanes |= spawnedLane;
  root.suspendedLanes &= ~spawnedLane;
  var spawnedLaneIndex = 31 - clz32(spawnedLane);
  root.entangledLanes |= spawnedLane;
  root.entanglements[spawnedLaneIndex] =
    root.entanglements[spawnedLaneIndex] |
    1073741824 |
    (entangledLanes & 4194218);
}
function markRootEntangled(root, entangledLanes) {
  var rootEntangledLanes = (root.entangledLanes |= entangledLanes);
  for (root = root.entanglements; rootEntangledLanes; ) {
    var index$8 = 31 - clz32(rootEntangledLanes),
      lane = 1 << index$8;
    (lane & entangledLanes) | (root[index$8] & entangledLanes) &&
      (root[index$8] |= entangledLanes);
    rootEntangledLanes &= ~lane;
  }
}
function lanesToEventPriority(lanes) {
  lanes &= -lanes;
  return 2 < lanes
    ? 8 < lanes
      ? 0 !== (lanes & 134217727)
        ? 32
        : 268435456
      : 8
    : 2;
}
function resolveUpdatePriority() {
  var updatePriority = ReactDOMSharedInternals.p;
  if (0 !== updatePriority) return updatePriority;
  updatePriority = window.event;
  return void 0 === updatePriority ? 32 : getEventPriority(updatePriority.type);
}
function runWithPriority(priority, fn) {
  var previousPriority = ReactDOMSharedInternals.p;
  try {
    return (ReactDOMSharedInternals.p = priority), fn();
  } finally {
    ReactDOMSharedInternals.p = previousPriority;
  }
}
var randomKey = Math.random().toString(36).slice(2),
  internalInstanceKey = "__reactFiber$" + randomKey,
  internalPropsKey = "__reactProps$" + randomKey,
  internalContainerInstanceKey = "__reactContainer$" + randomKey,
  internalEventHandlersKey = "__reactEvents$" + randomKey,
  internalEventHandlerListenersKey = "__reactListeners$" + randomKey,
  internalEventHandlesSetKey = "__reactHandles$" + randomKey,
  internalRootNodeResourcesKey = "__reactResources$" + randomKey,
  internalHoistableMarker = "__reactMarker$" + randomKey;
function detachDeletedInstance(node) {
  delete node[internalInstanceKey];
  delete node[internalPropsKey];
  delete node[internalEventHandlersKey];
  delete node[internalEventHandlerListenersKey];
  delete node[internalEventHandlesSetKey];
}
function getClosestInstanceFromNode(targetNode) {
  var targetInst = targetNode[internalInstanceKey];
  if (targetInst) return targetInst;
  for (var parentNode = targetNode.parentNode; parentNode; ) {
    if (
      (targetInst =
        parentNode[internalContainerInstanceKey] ||
        parentNode[internalInstanceKey])
    ) {
      parentNode = targetInst.alternate;
      if (
        null !== targetInst.child ||
        (null !== parentNode && null !== parentNode.child)
      )
        for (
          targetNode = getParentSuspenseInstance(targetNode);
          null !== targetNode;

        ) {
          if ((parentNode = targetNode[internalInstanceKey])) return parentNode;
          targetNode = getParentSuspenseInstance(targetNode);
        }
      return targetInst;
    }
    targetNode = parentNode;
    parentNode = targetNode.parentNode;
  }
  return null;
}
function getInstanceFromNode(node) {
  if (
    (node = node[internalInstanceKey] || node[internalContainerInstanceKey])
  ) {
    var tag = node.tag;
    if (
      5 === tag ||
      6 === tag ||
      13 === tag ||
      26 === tag ||
      27 === tag ||
      3 === tag
    )
      return node;
  }
  return null;
}
function getNodeFromInstance(inst) {
  var tag = inst.tag;
  if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return inst.stateNode;
  throw Error(formatProdErrorMessage(33));
}
function getResourcesFromRoot(root) {
  var resources = root[internalRootNodeResourcesKey];
  resources ||
    (resources = root[internalRootNodeResourcesKey] =
      { hoistableStyles: new Map(), hoistableScripts: new Map() });
  return resources;
}
function markNodeAsHoistable(node) {
  node[internalHoistableMarker] = !0;
}
var allNativeEvents = new Set(),
  registrationNameDependencies = {};
function registerTwoPhaseEvent(registrationName, dependencies) {
  registerDirectEvent(registrationName, dependencies);
  registerDirectEvent(registrationName + "Capture", dependencies);
}
function registerDirectEvent(registrationName, dependencies) {
  registrationNameDependencies[registrationName] = dependencies;
  for (
    registrationName = 0;
    registrationName < dependencies.length;
    registrationName++
  )
    allNativeEvents.add(dependencies[registrationName]);
}
var canUseDOM = !(
    "undefined" === typeof window ||
    "undefined" === typeof window.document ||
    "undefined" === typeof window.document.createElement
  ),
  VALID_ATTRIBUTE_NAME_REGEX = RegExp(
    "^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
  ),
  illegalAttributeNameCache = {},
  validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
  if (hasOwnProperty.call(validatedAttributeNameCache, attributeName))
    return !0;
  if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) return !1;
  if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName))
    return (validatedAttributeNameCache[attributeName] = !0);
  illegalAttributeNameCache[attributeName] = !0;
  return !1;
}
function setValueForAttribute(node, name, value) {
  if (isAttributeNameSafe(name))
    if (null === value) node.removeAttribute(name);
    else {
      switch (typeof value) {
        case "undefined":
        case "function":
        case "symbol":
          node.removeAttribute(name);
          return;
        case "boolean":
          var prefix$10 = name.toLowerCase().slice(0, 5);
          if ("data-" !== prefix$10 && "aria-" !== prefix$10) {
            node.removeAttribute(name);
            return;
          }
      }
      node.setAttribute(name, "" + value);
    }
}
function setValueForKnownAttribute(node, name, value) {
  if (null === value) node.removeAttribute(name);
  else {
    switch (typeof value) {
      case "undefined":
      case "function":
      case "symbol":
      case "boolean":
        node.removeAttribute(name);
        return;
    }
    node.setAttribute(name, "" + value);
  }
}
function setValueForNamespacedAttribute(node, namespace, name, value) {
  if (null === value) node.removeAttribute(name);
  else {
    switch (typeof value) {
      case "undefined":
      case "function":
      case "symbol":
      case "boolean":
        node.removeAttribute(name);
        return;
    }
    node.setAttributeNS(namespace, name, "" + value);
  }
}
function getToStringValue(value) {
  switch (typeof value) {
    case "bigint":
    case "boolean":
    case "number":
    case "string":
    case "undefined":
      return value;
    case "object":
      return value;
    default:
      return "";
  }
}
function isCheckable(elem) {
  var type = elem.type;
  return (
    (elem = elem.nodeName) &&
    "input" === elem.toLowerCase() &&
    ("checkbox" === type || "radio" === type)
  );
}
function trackValueOnNode(node) {
  var valueField = isCheckable(node) ? "checked" : "value",
    descriptor = Object.getOwnPropertyDescriptor(
      node.constructor.prototype,
      valueField
    ),
    currentValue = "" + node[valueField];
  if (
    !node.hasOwnProperty(valueField) &&
    "undefined" !== typeof descriptor &&
    "function" === typeof descriptor.get &&
    "function" === typeof descriptor.set
  ) {
    var get = descriptor.get,
      set = descriptor.set;
    Object.defineProperty(node, valueField, {
      configurable: !0,
      get: function () {
        return get.call(this);
      },
      set: function (value) {
        currentValue = "" + value;
        set.call(this, value);
      }
    });
    Object.defineProperty(node, valueField, {
      enumerable: descriptor.enumerable
    });
    return {
      getValue: function () {
        return currentValue;
      },
      setValue: function (value) {
        currentValue = "" + value;
      },
      stopTracking: function () {
        node._valueTracker = null;
        delete node[valueField];
      }
    };
  }
}
function track(node) {
  node._valueTracker || (node._valueTracker = trackValueOnNode(node));
}
function updateValueIfChanged(node) {
  if (!node) return !1;
  var tracker = node._valueTracker;
  if (!tracker) return !0;
  var lastValue = tracker.getValue();
  var value = "";
  node &&
    (value = isCheckable(node)
      ? node.checked
        ? "true"
        : "false"
      : node.value);
  node = value;
  return node !== lastValue ? (tracker.setValue(node), !0) : !1;
}
function getActiveElement(doc) {
  doc = doc || ("undefined" !== typeof document ? document : void 0);
  if ("undefined" === typeof doc) return null;
  try {
    return doc.activeElement || doc.body;
  } catch (e) {
    return doc.body;
  }
}
var escapeSelectorAttributeValueInsideDoubleQuotesRegex = /[\n"\\]/g;
function escapeSelectorAttributeValueInsideDoubleQuotes(value) {
  return value.replace(
    escapeSelectorAttributeValueInsideDoubleQuotesRegex,
    function (ch) {
      return "\\" + ch.charCodeAt(0).toString(16) + " ";
    }
  );
}
function updateInput(
  element,
  value,
  defaultValue,
  lastDefaultValue,
  checked,
  defaultChecked,
  type,
  name
) {
  element.name = "";
  null != type &&
  "function" !== typeof type &&
  "symbol" !== typeof type &&
  "boolean" !== typeof type
    ? (element.type = type)
    : element.removeAttribute("type");
  if (null != value)
    if ("number" === type) {
      if ((0 === value && "" === element.value) || element.value != value)
        element.value = "" + getToStringValue(value);
    } else
      element.value !== "" + getToStringValue(value) &&
        (element.value = "" + getToStringValue(value));
  else
    ("submit" !== type && "reset" !== type) || element.removeAttribute("value");
  null != value
    ? setDefaultValue(element, type, getToStringValue(value))
    : null != defaultValue
      ? setDefaultValue(element, type, getToStringValue(defaultValue))
      : null != lastDefaultValue && element.removeAttribute("value");
  null == checked &&
    null != defaultChecked &&
    (element.defaultChecked = !!defaultChecked);
  null != checked &&
    (element.checked =
      checked && "function" !== typeof checked && "symbol" !== typeof checked);
  null != name &&
  "function" !== typeof name &&
  "symbol" !== typeof name &&
  "boolean" !== typeof name
    ? (element.name = "" + getToStringValue(name))
    : element.removeAttribute("name");
}
function initInput(
  element,
  value,
  defaultValue,
  checked,
  defaultChecked,
  type,
  name,
  isHydrating
) {
  null != type &&
    "function" !== typeof type &&
    "symbol" !== typeof type &&
    "boolean" !== typeof type &&
    (element.type = type);
  if (null != value || null != defaultValue) {
    if (
      !(
        ("submit" !== type && "reset" !== type) ||
        (void 0 !== value && null !== value)
      )
    )
      return;
    defaultValue =
      null != defaultValue ? "" + getToStringValue(defaultValue) : "";
    value = null != value ? "" + getToStringValue(value) : defaultValue;
    isHydrating || value === element.value || (element.value = value);
    element.defaultValue = value;
  }
  checked = null != checked ? checked : defaultChecked;
  checked =
    "function" !== typeof checked && "symbol" !== typeof checked && !!checked;
  element.checked = isHydrating ? element.checked : !!checked;
  element.defaultChecked = !!checked;
  null != name &&
    "function" !== typeof name &&
    "symbol" !== typeof name &&
    "boolean" !== typeof name &&
    (element.name = name);
}
function setDefaultValue(node, type, value) {
  ("number" === type && getActiveElement(node.ownerDocument) === node) ||
    node.defaultValue === "" + value ||
    (node.defaultValue = "" + value);
}
function updateOptions(node, multiple, propValue, setDefaultSelected) {
  node = node.options;
  if (multiple) {
    multiple = {};
    for (var i = 0; i < propValue.length; i++)
      multiple["$" + propValue[i]] = !0;
    for (propValue = 0; propValue < node.length; propValue++)
      (i = multiple.hasOwnProperty("$" + node[propValue].value)),
        node[propValue].selected !== i && (node[propValue].selected = i),
        i && setDefaultSelected && (node[propValue].defaultSelected = !0);
  } else {
    propValue = "" + getToStringValue(propValue);
    multiple = null;
    for (i = 0; i < node.length; i++) {
      if (node[i].value === propValue) {
        node[i].selected = !0;
        setDefaultSelected && (node[i].defaultSelected = !0);
        return;
      }
      null !== multiple || node[i].disabled || (multiple = node[i]);
    }
    null !== multiple && (multiple.selected = !0);
  }
}
function updateTextarea(element, value, defaultValue) {
  if (
    null != value &&
    ((value = "" + getToStringValue(value)),
    value !== element.value && (element.value = value),
    null == defaultValue)
  ) {
    element.defaultValue !== value && (element.defaultValue = value);
    return;
  }
  element.defaultValue =
    null != defaultValue ? "" + getToStringValue(defaultValue) : "";
}
function initTextarea(element, value, defaultValue, children) {
  if (null == value) {
    if (null != children) {
      if (null != defaultValue) throw Error(formatProdErrorMessage(92));
      if (isArrayImpl(children)) {
        if (1 < children.length) throw Error(formatProdErrorMessage(93));
        children = children[0];
      }
      defaultValue = children;
    }
    null == defaultValue && (defaultValue = "");
    value = defaultValue;
  }
  defaultValue = getToStringValue(value);
  element.defaultValue = defaultValue;
  children = element.textContent;
  children === defaultValue &&
    "" !== children &&
    null !== children &&
    (element.value = children);
}
function setTextContent(node, text) {
  if (text) {
    var firstChild = node.firstChild;
    if (
      firstChild &&
      firstChild === node.lastChild &&
      3 === firstChild.nodeType
    ) {
      firstChild.nodeValue = text;
      return;
    }
  }
  node.textContent = text;
}
var unitlessNumbers = new Set(
  "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(
    " "
  )
);
function setValueForStyle(style, styleName, value) {
  var isCustomProperty = 0 === styleName.indexOf("--");
  null == value || "boolean" === typeof value || "" === value
    ? isCustomProperty
      ? style.setProperty(styleName, "")
      : "float" === styleName
        ? (style.cssFloat = "")
        : (style[styleName] = "")
    : isCustomProperty
      ? style.setProperty(styleName, value)
      : "number" !== typeof value ||
          0 === value ||
          unitlessNumbers.has(styleName)
        ? "float" === styleName
          ? (style.cssFloat = value)
          : (style[styleName] = ("" + value).trim())
        : (style[styleName] = value + "px");
}
function setValueForStyles(node, styles, prevStyles) {
  if (null != styles && "object" !== typeof styles)
    throw Error(formatProdErrorMessage(62));
  node = node.style;
  if (null != prevStyles) {
    for (var styleName in prevStyles)
      !prevStyles.hasOwnProperty(styleName) ||
        (null != styles && styles.hasOwnProperty(styleName)) ||
        (0 === styleName.indexOf("--")
          ? node.setProperty(styleName, "")
          : "float" === styleName
            ? (node.cssFloat = "")
            : (node[styleName] = ""));
    for (var styleName$16 in styles)
      (styleName = styles[styleName$16]),
        styles.hasOwnProperty(styleName$16) &&
          prevStyles[styleName$16] !== styleName &&
          setValueForStyle(node, styleName$16, styleName);
  } else
    for (var styleName$17 in styles)
      styles.hasOwnProperty(styleName$17) &&
        setValueForStyle(node, styleName$17, styles[styleName$17]);
}
function isCustomElement(tagName) {
  if (-1 === tagName.indexOf("-")) return !1;
  switch (tagName) {
    case "annotation-xml":
    case "color-profile":
    case "font-face":
    case "font-face-src":
    case "font-face-uri":
    case "font-face-format":
    case "font-face-name":
    case "missing-glyph":
      return !1;
    default:
      return !0;
  }
}
var aliases = new Map([
    ["acceptCharset", "accept-charset"],
    ["htmlFor", "for"],
    ["httpEquiv", "http-equiv"],
    ["crossOrigin", "crossorigin"],
    ["accentHeight", "accent-height"],
    ["alignmentBaseline", "alignment-baseline"],
    ["arabicForm", "arabic-form"],
    ["baselineShift", "baseline-shift"],
    ["capHeight", "cap-height"],
    ["clipPath", "clip-path"],
    ["clipRule", "clip-rule"],
    ["colorInterpolation", "color-interpolation"],
    ["colorInterpolationFilters", "color-interpolation-filters"],
    ["colorProfile", "color-profile"],
    ["colorRendering", "color-rendering"],
    ["dominantBaseline", "dominant-baseline"],
    ["enableBackground", "enable-background"],
    ["fillOpacity", "fill-opacity"],
    ["fillRule", "fill-rule"],
    ["floodColor", "flood-color"],
    ["floodOpacity", "flood-opacity"],
    ["fontFamily", "font-family"],
    ["fontSize", "font-size"],
    ["fontSizeAdjust", "font-size-adjust"],
    ["fontStretch", "font-stretch"],
    ["fontStyle", "font-style"],
    ["fontVariant", "font-variant"],
    ["fontWeight", "font-weight"],
    ["glyphName", "glyph-name"],
    ["glyphOrientationHorizontal", "glyph-orientation-horizontal"],
    ["glyphOrientationVertical", "glyph-orientation-vertical"],
    ["horizAdvX", "horiz-adv-x"],
    ["horizOriginX", "horiz-origin-x"],
    ["imageRendering", "image-rendering"],
    ["letterSpacing", "letter-spacing"],
    ["lightingColor", "lighting-color"],
    ["markerEnd", "marker-end"],
    ["markerMid", "marker-mid"],
    ["markerStart", "marker-start"],
    ["overlinePosition", "overline-position"],
    ["overlineThickness", "overline-thickness"],
    ["paintOrder", "paint-order"],
    ["panose-1", "panose-1"],
    ["pointerEvents", "pointer-events"],
    ["renderingIntent", "rendering-intent"],
    ["shapeRendering", "shape-rendering"],
    ["stopColor", "stop-color"],
    ["stopOpacity", "stop-opacity"],
    ["strikethroughPosition", "strikethrough-position"],
    ["strikethroughThickness", "strikethrough-thickness"],
    ["strokeDasharray", "stroke-dasharray"],
    ["strokeDashoffset", "stroke-dashoffset"],
    ["strokeLinecap", "stroke-linecap"],
    ["strokeLinejoin", "stroke-linejoin"],
    ["strokeMiterlimit", "stroke-miterlimit"],
    ["strokeOpacity", "stroke-opacity"],
    ["strokeWidth", "stroke-width"],
    ["textAnchor", "text-anchor"],
    ["textDecoration", "text-decoration"],
    ["textRendering", "text-rendering"],
    ["transformOrigin", "transform-origin"],
    ["underlinePosition", "underline-position"],
    ["underlineThickness", "underline-thickness"],
    ["unicodeBidi", "unicode-bidi"],
    ["unicodeRange", "unicode-range"],
    ["unitsPerEm", "units-per-em"],
    ["vAlphabetic", "v-alphabetic"],
    ["vHanging", "v-hanging"],
    ["vIdeographic", "v-ideographic"],
    ["vMathematical", "v-mathematical"],
    ["vectorEffect", "vector-effect"],
    ["vertAdvY", "vert-adv-y"],
    ["vertOriginX", "vert-origin-x"],
    ["vertOriginY", "vert-origin-y"],
    ["wordSpacing", "word-spacing"],
    ["writingMode", "writing-mode"],
    ["xmlnsXlink", "xmlns:xlink"],
    ["xHeight", "x-height"]
  ]),
  isJavaScriptProtocol =
    /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;
function sanitizeURL(url) {
  return isJavaScriptProtocol.test("" + url)
    ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')"
    : url;
}
var currentReplayingEvent = null;
function getEventTarget(nativeEvent) {
  nativeEvent = nativeEvent.target || nativeEvent.srcElement || window;
  nativeEvent.correspondingUseElement &&
    (nativeEvent = nativeEvent.correspondingUseElement);
  return 3 === nativeEvent.nodeType ? nativeEvent.parentNode : nativeEvent;
}
var restoreTarget = null,
  restoreQueue = null;
function restoreStateOfTarget(target) {
  var internalInstance = getInstanceFromNode(target);
  if (internalInstance && (target = internalInstance.stateNode)) {
    var props = target[internalPropsKey] || null;
    a: switch (((target = internalInstance.stateNode), internalInstance.type)) {
      case "input":
        updateInput(
          target,
          props.value,
          props.defaultValue,
          props.defaultValue,
          props.checked,
          props.defaultChecked,
          props.type,
          props.name
        );
        internalInstance = props.name;
        if ("radio" === props.type && null != internalInstance) {
          for (props = target; props.parentNode; ) props = props.parentNode;
          props = props.querySelectorAll(
            'input[name="' +
              escapeSelectorAttributeValueInsideDoubleQuotes(
                "" + internalInstance
              ) +
              '"][type="radio"]'
          );
          for (
            internalInstance = 0;
            internalInstance < props.length;
            internalInstance++
          ) {
            var otherNode = props[internalInstance];
            if (otherNode !== target && otherNode.form === target.form) {
              var otherProps = otherNode[internalPropsKey] || null;
              if (!otherProps) throw Error(formatProdErrorMessage(90));
              updateInput(
                otherNode,
                otherProps.value,
                otherProps.defaultValue,
                otherProps.defaultValue,
                otherProps.checked,
                otherProps.defaultChecked,
                otherProps.type,
                otherProps.name
              );
            }
          }
          for (
            internalInstance = 0;
            internalInstance < props.length;
            internalInstance++
          )
            (otherNode = props[internalInstance]),
              otherNode.form === target.form && updateValueIfChanged(otherNode);
        }
        break a;
      case "textarea":
        updateTextarea(target, props.value, props.defaultValue);
        break a;
      case "select":
        (internalInstance = props.value),
          null != internalInstance &&
            updateOptions(target, !!props.multiple, internalInstance, !1);
    }
  }
}
var isInsideEventHandler = !1;
function batchedUpdates$1(fn, a, b) {
  if (isInsideEventHandler) return fn(a, b);
  isInsideEventHandler = !0;
  try {
    var JSCompiler_inline_result = fn(a);
    return JSCompiler_inline_result;
  } finally {
    if (
      ((isInsideEventHandler = !1),
      null !== restoreTarget || null !== restoreQueue)
    )
      if (
        (flushSyncWork$1(),
        restoreTarget &&
          ((a = restoreTarget),
          (fn = restoreQueue),
          (restoreQueue = restoreTarget = null),
          restoreStateOfTarget(a),
          fn))
      )
        for (a = 0; a < fn.length; a++) restoreStateOfTarget(fn[a]);
  }
}
function getListener(inst, registrationName) {
  var stateNode = inst.stateNode;
  if (null === stateNode) return null;
  var props = stateNode[internalPropsKey] || null;
  if (null === props) return null;
  stateNode = props[registrationName];
  a: switch (registrationName) {
    case "onClick":
    case "onClickCapture":
    case "onDoubleClick":
    case "onDoubleClickCapture":
    case "onMouseDown":
    case "onMouseDownCapture":
    case "onMouseMove":
    case "onMouseMoveCapture":
    case "onMouseUp":
    case "onMouseUpCapture":
    case "onMouseEnter":
      (props = !props.disabled) ||
        ((inst = inst.type),
        (props = !(
          "button" === inst ||
          "input" === inst ||
          "select" === inst ||
          "textarea" === inst
        )));
      inst = !props;
      break a;
    default:
      inst = !1;
  }
  if (inst) return null;
  if (stateNode && "function" !== typeof stateNode)
    throw Error(
      formatProdErrorMessage(231, registrationName, typeof stateNode)
    );
  return stateNode;
}
var passiveBrowserEventsSupported = !1;
if (canUseDOM)
  try {
    var options = {};
    Object.defineProperty(options, "passive", {
      get: function () {
        passiveBrowserEventsSupported = !0;
      }
    });
    window.addEventListener("test", options, options);
    window.removeEventListener("test", options, options);
  } catch (e) {
    passiveBrowserEventsSupported = !1;
  }
var root = null,
  startText = null,
  fallbackText = null;
function getData() {
  if (fallbackText) return fallbackText;
  var start,
    startValue = startText,
    startLength = startValue.length,
    end,
    endValue = "value" in root ? root.value : root.textContent,
    endLength = endValue.length;
  for (
    start = 0;
    start < startLength && startValue[start] === endValue[start];
    start++
  );
  var minEnd = startLength - start;
  for (
    end = 1;
    end <= minEnd &&
    startValue[startLength - end] === endValue[endLength - end];
    end++
  );
  return (fallbackText = endValue.slice(start, 1 < end ? 1 - end : void 0));
}
function getEventCharCode(nativeEvent) {
  var keyCode = nativeEvent.keyCode;
  "charCode" in nativeEvent
    ? ((nativeEvent = nativeEvent.charCode),
      0 === nativeEvent && 13 === keyCode && (nativeEvent = 13))
    : (nativeEvent = keyCode);
  10 === nativeEvent && (nativeEvent = 13);
  return 32 <= nativeEvent || 13 === nativeEvent ? nativeEvent : 0;
}
function functionThatReturnsTrue() {
  return !0;
}
function functionThatReturnsFalse() {
  return !1;
}
function createSyntheticEvent(Interface) {
  function SyntheticBaseEvent(
    reactName,
    reactEventType,
    targetInst,
    nativeEvent,
    nativeEventTarget
  ) {
    this._reactName = reactName;
    this._targetInst = targetInst;
    this.type = reactEventType;
    this.nativeEvent = nativeEvent;
    this.target = nativeEventTarget;
    this.currentTarget = null;
    for (var propName in Interface)
      Interface.hasOwnProperty(propName) &&
        ((reactName = Interface[propName]),
        (this[propName] = reactName
          ? reactName(nativeEvent)
          : nativeEvent[propName]));
    this.isDefaultPrevented = (
      null != nativeEvent.defaultPrevented
        ? nativeEvent.defaultPrevented
        : !1 === nativeEvent.returnValue
    )
      ? functionThatReturnsTrue
      : functionThatReturnsFalse;
    this.isPropagationStopped = functionThatReturnsFalse;
    return this;
  }
  assign(SyntheticBaseEvent.prototype, {
    preventDefault: function () {
      this.defaultPrevented = !0;
      var event = this.nativeEvent;
      event &&
        (event.preventDefault
          ? event.preventDefault()
          : "unknown" !== typeof event.returnValue && (event.returnValue = !1),
        (this.isDefaultPrevented = functionThatReturnsTrue));
    },
    stopPropagation: function () {
      var event = this.nativeEvent;
      event &&
        (event.stopPropagation
          ? event.stopPropagation()
          : "unknown" !== typeof event.cancelBubble &&
            (event.cancelBubble = !0),
        (this.isPropagationStopped = functionThatReturnsTrue));
    },
    persist: function () {},
    isPersistent: functionThatReturnsTrue
  });
  return SyntheticBaseEvent;
}
var EventInterface = {
    eventPhase: 0,
    bubbles: 0,
    cancelable: 0,
    timeStamp: function (event) {
      return event.timeStamp || Date.now();
    },
    defaultPrevented: 0,
    isTrusted: 0
  },
  SyntheticEvent = createSyntheticEvent(EventInterface),
  UIEventInterface = assign({}, EventInterface, { view: 0, detail: 0 }),
  SyntheticUIEvent = createSyntheticEvent(UIEventInterface),
  lastMovementX,
  lastMovementY,
  lastMouseEvent,
  MouseEventInterface = assign({}, UIEventInterface, {
    screenX: 0,
    screenY: 0,
    clientX: 0,
    clientY: 0,
    pageX: 0,
    pageY: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    getModifierState: getEventModifierState,
    button: 0,
    buttons: 0,
    relatedTarget: function (event) {
      return void 0 === event.relatedTarget
        ? event.fromElement === event.srcElement
          ? event.toElement
          : event.fromElement
        : event.relatedTarget;
    },
    movementX: function (event) {
      if ("movementX" in event) return event.movementX;
      event !== lastMouseEvent &&
        (lastMouseEvent && "mousemove" === event.type
          ? ((lastMovementX = event.screenX - lastMouseEvent.screenX),
            (lastMovementY = event.screenY - lastMouseEvent.screenY))
          : (lastMovementY = lastMovementX = 0),
        (lastMouseEvent = event));
      return lastMovementX;
    },
    movementY: function (event) {
      return "movementY" in event ? event.movementY : lastMovementY;
    }
  }),
  SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface),
  DragEventInterface = assign({}, MouseEventInterface, { dataTransfer: 0 }),
  SyntheticDragEvent = createSyntheticEvent(DragEventInterface),
  FocusEventInterface = assign({}, UIEventInterface, { relatedTarget: 0 }),
  SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface),
  AnimationEventInterface = assign({}, EventInterface, {
    animationName: 0,
    elapsedTime: 0,
    pseudoElement: 0
  }),
  SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface),
  ClipboardEventInterface = assign({}, EventInterface, {
    clipboardData: function (event) {
      return "clipboardData" in event
        ? event.clipboardData
        : window.clipboardData;
    }
  }),
  SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface),
  CompositionEventInterface = assign({}, EventInterface, { data: 0 }),
  SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface),
  normalizeKey = {
    Esc: "Escape",
    Spacebar: " ",
    Left: "ArrowLeft",
    Up: "ArrowUp",
    Right: "ArrowRight",
    Down: "ArrowDown",
    Del: "Delete",
    Win: "OS",
    Menu: "ContextMenu",
    Apps: "ContextMenu",
    Scroll: "ScrollLock",
    MozPrintableKey: "Unidentified"
  },
  translateToKey = {
    8: "Backspace",
    9: "Tab",
    12: "Clear",
    13: "Enter",
    16: "Shift",
    17: "Control",
    18: "Alt",
    19: "Pause",
    20: "CapsLock",
    27: "Escape",
    32: " ",
    33: "PageUp",
    34: "PageDown",
    35: "End",
    36: "Home",
    37: "ArrowLeft",
    38: "ArrowUp",
    39: "ArrowRight",
    40: "ArrowDown",
    45: "Insert",
    46: "Delete",
    112: "F1",
    113: "F2",
    114: "F3",
    115: "F4",
    116: "F5",
    117: "F6",
    118: "F7",
    119: "F8",
    120: "F9",
    121: "F10",
    122: "F11",
    123: "F12",
    144: "NumLock",
    145: "ScrollLock",
    224: "Meta"
  },
  modifierKeyToProp = {
    Alt: "altKey",
    Control: "ctrlKey",
    Meta: "metaKey",
    Shift: "shiftKey"
  };
function modifierStateGetter(keyArg) {
  var nativeEvent = this.nativeEvent;
  return nativeEvent.getModifierState
    ? nativeEvent.getModifierState(keyArg)
    : (keyArg = modifierKeyToProp[keyArg])
      ? !!nativeEvent[keyArg]
      : !1;
}
function getEventModifierState() {
  return modifierStateGetter;
}
var KeyboardEventInterface = assign({}, UIEventInterface, {
    key: function (nativeEvent) {
      if (nativeEvent.key) {
        var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
        if ("Unidentified" !== key) return key;
      }
      return "keypress" === nativeEvent.type
        ? ((nativeEvent = getEventCharCode(nativeEvent)),
          13 === nativeEvent ? "Enter" : String.fromCharCode(nativeEvent))
        : "keydown" === nativeEvent.type || "keyup" === nativeEvent.type
          ? translateToKey[nativeEvent.keyCode] || "Unidentified"
          : "";
    },
    code: 0,
    location: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    repeat: 0,
    locale: 0,
    getModifierState: getEventModifierState,
    charCode: function (event) {
      return "keypress" === event.type ? getEventCharCode(event) : 0;
    },
    keyCode: function (event) {
      return "keydown" === event.type || "keyup" === event.type
        ? event.keyCode
        : 0;
    },
    which: function (event) {
      return "keypress" === event.type
        ? getEventCharCode(event)
        : "keydown" === event.type || "keyup" === event.type
          ? event.keyCode
          : 0;
    }
  }),
  SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface),
  PointerEventInterface = assign({}, MouseEventInterface, {
    pointerId: 0,
    width: 0,
    height: 0,
    pressure: 0,
    tangentialPressure: 0,
    tiltX: 0,
    tiltY: 0,
    twist: 0,
    pointerType: 0,
    isPrimary: 0
  }),
  SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface),
  TouchEventInterface = assign({}, UIEventInterface, {
    touches: 0,
    targetTouches: 0,
    changedTouches: 0,
    altKey: 0,
    metaKey: 0,
    ctrlKey: 0,
    shiftKey: 0,
    getModifierState: getEventModifierState
  }),
  SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface),
  TransitionEventInterface = assign({}, EventInterface, {
    propertyName: 0,
    elapsedTime: 0,
    pseudoElement: 0
  }),
  SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface),
  WheelEventInterface = assign({}, MouseEventInterface, {
    deltaX: function (event) {
      return "deltaX" in event
        ? event.deltaX
        : "wheelDeltaX" in event
          ? -event.wheelDeltaX
          : 0;
    },
    deltaY: function (event) {
      return "deltaY" in event
        ? event.deltaY
        : "wheelDeltaY" in event
          ? -event.wheelDeltaY
          : "wheelDelta" in event
            ? -event.wheelDelta
            : 0;
    },
    deltaZ: 0,
    deltaMode: 0
  }),
  SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface),
  ToggleEventInterface = assign({}, EventInterface, {
    newState: 0,
    oldState: 0
  }),
  SyntheticToggleEvent = createSyntheticEvent(ToggleEventInterface),
  END_KEYCODES = [9, 13, 27, 32],
  canUseCompositionEvent = canUseDOM && "CompositionEvent" in window,
  documentMode = null;
canUseDOM &&
  "documentMode" in document &&
  (documentMode = document.documentMode);
var canUseTextInputEvent = canUseDOM && "TextEvent" in window && !documentMode,
  useFallbackCompositionData =
    canUseDOM &&
    (!canUseCompositionEvent ||
      (documentMode && 8 < documentMode && 11 >= documentMode)),
  SPACEBAR_CHAR = String.fromCharCode(32),
  hasSpaceKeypress = !1;
function isFallbackCompositionEnd(domEventName, nativeEvent) {
  switch (domEventName) {
    case "keyup":
      return -1 !== END_KEYCODES.indexOf(nativeEvent.keyCode);
    case "keydown":
      return 229 !== nativeEvent.keyCode;
    case "keypress":
    case "mousedown":
    case "focusout":
      return !0;
    default:
      return !1;
  }
}
function getDataFromCustomEvent(nativeEvent) {
  nativeEvent = nativeEvent.detail;
  return "object" === typeof nativeEvent && "data" in nativeEvent
    ? nativeEvent.data
    : null;
}
var isComposing = !1;
function getNativeBeforeInputChars(domEventName, nativeEvent) {
  switch (domEventName) {
    case "compositionend":
      return getDataFromCustomEvent(nativeEvent);
    case "keypress":
      if (32 !== nativeEvent.which) return null;
      hasSpaceKeypress = !0;
      return SPACEBAR_CHAR;
    case "textInput":
      return (
        (domEventName = nativeEvent.data),
        domEventName === SPACEBAR_CHAR && hasSpaceKeypress ? null : domEventName
      );
    default:
      return null;
  }
}
function getFallbackBeforeInputChars(domEventName, nativeEvent) {
  if (isComposing)
    return "compositionend" === domEventName ||
      (!canUseCompositionEvent &&
        isFallbackCompositionEnd(domEventName, nativeEvent))
      ? ((domEventName = getData()),
        (fallbackText = startText = root = null),
        (isComposing = !1),
        domEventName)
      : null;
  switch (domEventName) {
    case "paste":
      return null;
    case "keypress":
      if (
        !(nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) ||
        (nativeEvent.ctrlKey && nativeEvent.altKey)
      ) {
        if (nativeEvent.char && 1 < nativeEvent.char.length)
          return nativeEvent.char;
        if (nativeEvent.which) return String.fromCharCode(nativeEvent.which);
      }
      return null;
    case "compositionend":
      return useFallbackCompositionData && "ko" !== nativeEvent.locale
        ? null
        : nativeEvent.data;
    default:
      return null;
  }
}
var supportedInputTypes = {
  color: !0,
  date: !0,
  datetime: !0,
  "datetime-local": !0,
  email: !0,
  month: !0,
  number: !0,
  password: !0,
  range: !0,
  search: !0,
  tel: !0,
  text: !0,
  time: !0,
  url: !0,
  week: !0
};
function isTextInputElement(elem) {
  var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
  return "input" === nodeName
    ? !!supportedInputTypes[elem.type]
    : "textarea" === nodeName
      ? !0
      : !1;
}
function createAndAccumulateChangeEvent(
  dispatchQueue,
  inst,
  nativeEvent,
  target
) {
  restoreTarget
    ? restoreQueue
      ? restoreQueue.push(target)
      : (restoreQueue = [target])
    : (restoreTarget = target);
  inst = accumulateTwoPhaseListeners(inst, "onChange");
  0 < inst.length &&
    ((nativeEvent = new SyntheticEvent(
      "onChange",
      "change",
      null,
      nativeEvent,
      target
    )),
    dispatchQueue.push({ event: nativeEvent, listeners: inst }));
}
var activeElement$1 = null,
  activeElementInst$1 = null;
function runEventInBatch(dispatchQueue) {
  processDispatchQueue(dispatchQueue, 0);
}
function getInstIfValueChanged(targetInst) {
  var targetNode = getNodeFromInstance(targetInst);
  if (updateValueIfChanged(targetNode)) return targetInst;
}
function getTargetInstForChangeEvent(domEventName, targetInst) {
  if ("change" === domEventName) return targetInst;
}
var isInputEventSupported = !1;
if (canUseDOM) {
  var JSCompiler_inline_result$jscomp$283;
  if (canUseDOM) {
    var isSupported$jscomp$inline_418 = "oninput" in document;
    if (!isSupported$jscomp$inline_418) {
      var element$jscomp$inline_419 = document.createElement("div");
      element$jscomp$inline_419.setAttribute("oninput", "return;");
      isSupported$jscomp$inline_418 =
        "function" === typeof element$jscomp$inline_419.oninput;
    }
    JSCompiler_inline_result$jscomp$283 = isSupported$jscomp$inline_418;
  } else JSCompiler_inline_result$jscomp$283 = !1;
  isInputEventSupported =
    JSCompiler_inline_result$jscomp$283 &&
    (!document.documentMode || 9 < document.documentMode);
}
function stopWatchingForValueChange() {
  activeElement$1 &&
    (activeElement$1.detachEvent("onpropertychange", handlePropertyChange),
    (activeElementInst$1 = activeElement$1 = null));
}
function handlePropertyChange(nativeEvent) {
  if (
    "value" === nativeEvent.propertyName &&
    getInstIfValueChanged(activeElementInst$1)
  ) {
    var dispatchQueue = [];
    createAndAccumulateChangeEvent(
      dispatchQueue,
      activeElementInst$1,
      nativeEvent,
      getEventTarget(nativeEvent)
    );
    batchedUpdates$1(runEventInBatch, dispatchQueue);
  }
}
function handleEventsForInputEventPolyfill(domEventName, target, targetInst) {
  "focusin" === domEventName
    ? (stopWatchingForValueChange(),
      (activeElement$1 = target),
      (activeElementInst$1 = targetInst),
      activeElement$1.attachEvent("onpropertychange", handlePropertyChange))
    : "focusout" === domEventName && stopWatchingForValueChange();
}
function getTargetInstForInputEventPolyfill(domEventName) {
  if (
    "selectionchange" === domEventName ||
    "keyup" === domEventName ||
    "keydown" === domEventName
  )
    return getInstIfValueChanged(activeElementInst$1);
}
function getTargetInstForClickEvent(domEventName, targetInst) {
  if ("click" === domEventName) return getInstIfValueChanged(targetInst);
}
function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
  if ("input" === domEventName || "change" === domEventName)
    return getInstIfValueChanged(targetInst);
}
function is(x, y) {
  return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
}
var objectIs = "function" === typeof Object.is ? Object.is : is;
function shallowEqual(objA, objB) {
  if (objectIs(objA, objB)) return !0;
  if (
    "object" !== typeof objA ||
    null === objA ||
    "object" !== typeof objB ||
    null === objB
  )
    return !1;
  var keysA = Object.keys(objA),
    keysB = Object.keys(objB);
  if (keysA.length !== keysB.length) return !1;
  for (keysB = 0; keysB < keysA.length; keysB++) {
    var currentKey = keysA[keysB];
    if (
      !hasOwnProperty.call(objB, currentKey) ||
      !objectIs(objA[currentKey], objB[currentKey])
    )
      return !1;
  }
  return !0;
}
function getLeafNode(node) {
  for (; node && node.firstChild; ) node = node.firstChild;
  return node;
}
function getNodeForCharacterOffset(root, offset) {
  var node = getLeafNode(root);
  root = 0;
  for (var nodeEnd; node; ) {
    if (3 === node.nodeType) {
      nodeEnd = root + node.textContent.length;
      if (root <= offset && nodeEnd >= offset)
        return { node: node, offset: offset - root };
      root = nodeEnd;
    }
    a: {
      for (; node; ) {
        if (node.nextSibling) {
          node = node.nextSibling;
          break a;
        }
        node = node.parentNode;
      }
      node = void 0;
    }
    node = getLeafNode(node);
  }
}
function containsNode(outerNode, innerNode) {
  return outerNode && innerNode
    ? outerNode === innerNode
      ? !0
      : outerNode && 3 === outerNode.nodeType
        ? !1
        : innerNode && 3 === innerNode.nodeType
          ? containsNode(outerNode, innerNode.parentNode)
          : "contains" in outerNode
            ? outerNode.contains(innerNode)
            : outerNode.compareDocumentPosition
              ? !!(outerNode.compareDocumentPosition(innerNode) & 16)
              : !1
    : !1;
}
function getActiveElementDeep(containerInfo) {
  containerInfo =
    null != containerInfo &&
    null != containerInfo.ownerDocument &&
    null != containerInfo.ownerDocument.defaultView
      ? containerInfo.ownerDocument.defaultView
      : window;
  for (
    var element = getActiveElement(containerInfo.document);
    element instanceof containerInfo.HTMLIFrameElement;

  ) {
    try {
      var JSCompiler_inline_result =
        "string" === typeof element.contentWindow.location.href;
    } catch (err) {
      JSCompiler_inline_result = !1;
    }
    if (JSCompiler_inline_result) containerInfo = element.contentWindow;
    else break;
    element = getActiveElement(containerInfo.document);
  }
  return element;
}
function hasSelectionCapabilities(elem) {
  var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
  return (
    nodeName &&
    (("input" === nodeName &&
      ("text" === elem.type ||
        "search" === elem.type ||
        "tel" === elem.type ||
        "url" === elem.type ||
        "password" === elem.type)) ||
      "textarea" === nodeName ||
      "true" === elem.contentEditable)
  );
}
function restoreSelection(priorSelectionInformation, containerInfo) {
  var curFocusedElem = getActiveElementDeep(containerInfo);
  containerInfo = priorSelectionInformation.focusedElem;
  var priorSelectionRange = priorSelectionInformation.selectionRange;
  if (
    curFocusedElem !== containerInfo &&
    containerInfo &&
    containerInfo.ownerDocument &&
    containsNode(containerInfo.ownerDocument.documentElement, containerInfo)
  ) {
    if (null !== priorSelectionRange && hasSelectionCapabilities(containerInfo))
      if (
        ((priorSelectionInformation = priorSelectionRange.start),
        (curFocusedElem = priorSelectionRange.end),
        void 0 === curFocusedElem &&
          (curFocusedElem = priorSelectionInformation),
        "selectionStart" in containerInfo)
      )
        (containerInfo.selectionStart = priorSelectionInformation),
          (containerInfo.selectionEnd = Math.min(
            curFocusedElem,
            containerInfo.value.length
          ));
      else if (
        ((curFocusedElem =
          ((priorSelectionInformation =
            containerInfo.ownerDocument || document) &&
            priorSelectionInformation.defaultView) ||
          window),
        curFocusedElem.getSelection)
      ) {
        curFocusedElem = curFocusedElem.getSelection();
        var length = containerInfo.textContent.length,
          start = Math.min(priorSelectionRange.start, length);
        priorSelectionRange =
          void 0 === priorSelectionRange.end
            ? start
            : Math.min(priorSelectionRange.end, length);
        !curFocusedElem.extend &&
          start > priorSelectionRange &&
          ((length = priorSelectionRange),
          (priorSelectionRange = start),
          (start = length));
        length = getNodeForCharacterOffset(containerInfo, start);
        var endMarker = getNodeForCharacterOffset(
          containerInfo,
          priorSelectionRange
        );
        length &&
          endMarker &&
          (1 !== curFocusedElem.rangeCount ||
            curFocusedElem.anchorNode !== length.node ||
            curFocusedElem.anchorOffset !== length.offset ||
            curFocusedElem.focusNode !== endMarker.node ||
            curFocusedElem.focusOffset !== endMarker.offset) &&
          ((priorSelectionInformation =
            priorSelectionInformation.createRange()),
          priorSelectionInformation.setStart(length.node, length.offset),
          curFocusedElem.removeAllRanges(),
          start > priorSelectionRange
            ? (curFocusedElem.addRange(priorSelectionInformation),
              curFocusedElem.extend(endMarker.node, endMarker.offset))
            : (priorSelectionInformation.setEnd(
                endMarker.node,
                endMarker.offset
              ),
              curFocusedElem.addRange(priorSelectionInformation)));
      }
    priorSelectionInformation = [];
    for (
      curFocusedElem = containerInfo;
      (curFocusedElem = curFocusedElem.parentNode);

    )
      1 === curFocusedElem.nodeType &&
        priorSelectionInformation.push({
          element: curFocusedElem,
          left: curFocusedElem.scrollLeft,
          top: curFocusedElem.scrollTop
        });
    "function" === typeof containerInfo.focus && containerInfo.focus();
    for (
      containerInfo = 0;
      containerInfo < priorSelectionInformation.length;
      containerInfo++
    )
      (curFocusedElem = priorSelectionInformation[containerInfo]),
        (curFocusedElem.element.scrollLeft = curFocusedElem.left),
        (curFocusedElem.element.scrollTop = curFocusedElem.top);
  }
}
var skipSelectionChangeEvent =
    canUseDOM && "documentMode" in document && 11 >= document.documentMode,
  activeElement = null,
  activeElementInst = null,
  lastSelection = null,
  mouseDown = !1;
function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
  var doc =
    nativeEventTarget.window === nativeEventTarget
      ? nativeEventTarget.document
      : 9 === nativeEventTarget.nodeType
        ? nativeEventTarget
        : nativeEventTarget.ownerDocument;
  mouseDown ||
    null == activeElement ||
    activeElement !== getActiveElement(doc) ||
    ((doc = activeElement),
    "selectionStart" in doc && hasSelectionCapabilities(doc)
      ? (doc = { start: doc.selectionStart, end: doc.selectionEnd })
      : ((doc = (
          (doc.ownerDocument && doc.ownerDocument.defaultView) ||
          window
        ).getSelection()),
        (doc = {
          anchorNode: doc.anchorNode,
          anchorOffset: doc.anchorOffset,
          focusNode: doc.focusNode,
          focusOffset: doc.focusOffset
        })),
    (lastSelection && shallowEqual(lastSelection, doc)) ||
      ((lastSelection = doc),
      (doc = accumulateTwoPhaseListeners(activeElementInst, "onSelect")),
      0 < doc.length &&
        ((nativeEvent = new SyntheticEvent(
          "onSelect",
          "select",
          null,
          nativeEvent,
          nativeEventTarget
        )),
        dispatchQueue.push({ event: nativeEvent, listeners: doc }),
        (nativeEvent.target = activeElement))));
}
function makePrefixMap(styleProp, eventName) {
  var prefixes = {};
  prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
  prefixes["Webkit" + styleProp] = "webkit" + eventName;
  prefixes["Moz" + styleProp] = "moz" + eventName;
  return prefixes;
}
var vendorPrefixes = {
    animationend: makePrefixMap("Animation", "AnimationEnd"),
    animationiteration: makePrefixMap("Animation", "AnimationIteration"),
    animationstart: makePrefixMap("Animation", "AnimationStart"),
    transitionrun: makePrefixMap("Transition", "TransitionRun"),
    transitionstart: makePrefixMap("Transition", "TransitionStart"),
    transitioncancel: makePrefixMap("Transition", "TransitionCancel"),
    transitionend: makePrefixMap("Transition", "TransitionEnd")
  },
  prefixedEventNames = {},
  style = {};
canUseDOM &&
  ((style = document.createElement("div").style),
  "AnimationEvent" in window ||
    (delete vendorPrefixes.animationend.animation,
    delete vendorPrefixes.animationiteration.animation,
    delete vendorPrefixes.animationstart.animation),
  "TransitionEvent" in window ||
    delete vendorPrefixes.transitionend.transition);
function getVendorPrefixedEventName(eventName) {
  if (prefixedEventNames[eventName]) return prefixedEventNames[eventName];
  if (!vendorPrefixes[eventName]) return eventName;
  var prefixMap = vendorPrefixes[eventName],
    styleProp;
  for (styleProp in prefixMap)
    if (prefixMap.hasOwnProperty(styleProp) && styleProp in style)
      return (prefixedEventNames[eventName] = prefixMap[styleProp]);
  return eventName;
}
var ANIMATION_END = getVendorPrefixedEventName("animationend"),
  ANIMATION_ITERATION = getVendorPrefixedEventName("animationiteration"),
  ANIMATION_START = getVendorPrefixedEventName("animationstart"),
  TRANSITION_RUN = getVendorPrefixedEventName("transitionrun"),
  TRANSITION_START = getVendorPrefixedEventName("transitionstart"),
  TRANSITION_CANCEL = getVendorPrefixedEventName("transitioncancel"),
  TRANSITION_END = getVendorPrefixedEventName("transitionend"),
  topLevelEventsToReactNames = new Map(),
  simpleEventPluginEvents =
    "abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll scrollEnd toggle touchMove waiting wheel".split(
      " "
    );
function registerSimpleEvent(domEventName, reactName) {
  topLevelEventsToReactNames.set(domEventName, reactName);
  registerTwoPhaseEvent(reactName, [domEventName]);
}
var concurrentQueues = [],
  concurrentQueuesIndex = 0,
  concurrentlyUpdatedLanes = 0;
function finishQueueingConcurrentUpdates() {
  for (
    var endIndex = concurrentQueuesIndex,
      i = (concurrentlyUpdatedLanes = concurrentQueuesIndex = 0);
    i < endIndex;

  ) {
    var fiber = concurrentQueues[i];
    concurrentQueues[i++] = null;
    var queue = concurrentQueues[i];
    concurrentQueues[i++] = null;
    var update = concurrentQueues[i];
    concurrentQueues[i++] = null;
    var lane = concurrentQueues[i];
    concurrentQueues[i++] = null;
    if (null !== queue && null !== update) {
      var pending = queue.pending;
      null === pending
        ? (update.next = update)
        : ((update.next = pending.next), (pending.next = update));
      queue.pending = update;
    }
    0 !== lane && markUpdateLaneFromFiberToRoot(fiber, update, lane);
  }
}
function enqueueUpdate$1(fiber, queue, update, lane) {
  concurrentQueues[concurrentQueuesIndex++] = fiber;
  concurrentQueues[concurrentQueuesIndex++] = queue;
  concurrentQueues[concurrentQueuesIndex++] = update;
  concurrentQueues[concurrentQueuesIndex++] = lane;
  concurrentlyUpdatedLanes |= lane;
  fiber.lanes |= lane;
  fiber = fiber.alternate;
  null !== fiber && (fiber.lanes |= lane);
}
function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
  enqueueUpdate$1(fiber, queue, update, lane);
  return getRootForUpdatedFiber(fiber);
}
function enqueueConcurrentRenderForLane(fiber, lane) {
  enqueueUpdate$1(fiber, null, null, lane);
  return getRootForUpdatedFiber(fiber);
}
function markUpdateLaneFromFiberToRoot(sourceFiber, update, lane) {
  sourceFiber.lanes |= lane;
  var alternate = sourceFiber.alternate;
  null !== alternate && (alternate.lanes |= lane);
  for (var isHidden = !1, parent = sourceFiber.return; null !== parent; )
    (parent.childLanes |= lane),
      (alternate = parent.alternate),
      null !== alternate && (alternate.childLanes |= lane),
      22 === parent.tag &&
        ((sourceFiber = parent.stateNode),
        null === sourceFiber || sourceFiber._visibility & 1 || (isHidden = !0)),
      (sourceFiber = parent),
      (parent = parent.return);
  isHidden &&
    null !== update &&
    3 === sourceFiber.tag &&
    ((parent = sourceFiber.stateNode),
    (isHidden = 31 - clz32(lane)),
    (parent = parent.hiddenUpdates),
    (sourceFiber = parent[isHidden]),
    null === sourceFiber
      ? (parent[isHidden] = [update])
      : sourceFiber.push(update),
    (update.lane = lane | 536870912));
}
function getRootForUpdatedFiber(sourceFiber) {
  if (50 < nestedUpdateCount)
    throw (
      ((nestedUpdateCount = 0),
      (rootWithNestedUpdates = null),
      Error(formatProdErrorMessage(185)))
    );
  for (var parent = sourceFiber.return; null !== parent; )
    (sourceFiber = parent), (parent = sourceFiber.return);
  return 3 === sourceFiber.tag ? sourceFiber.stateNode : null;
}
var emptyContextObject = {},
  CapturedStacks = new WeakMap();
function createCapturedValueAtFiber(value, source) {
  if ("object" === typeof value && null !== value) {
    var existing = CapturedStacks.get(value);
    if (void 0 !== existing) return existing;
    source = {
      value: value,
      source: source,
      stack: getStackByFiberInDevAndProd(source)
    };
    CapturedStacks.set(value, source);
    return source;
  }
  return {
    value: value,
    source: source,
    stack: getStackByFiberInDevAndProd(source)
  };
}
var forkStack = [],
  forkStackIndex = 0,
  treeForkProvider = null,
  treeForkCount = 0,
  idStack = [],
  idStackIndex = 0,
  treeContextProvider = null,
  treeContextId = 1,
  treeContextOverflow = "";
function pushTreeFork(workInProgress, totalChildren) {
  forkStack[forkStackIndex++] = treeForkCount;
  forkStack[forkStackIndex++] = treeForkProvider;
  treeForkProvider = workInProgress;
  treeForkCount = totalChildren;
}
function pushTreeId(workInProgress, totalChildren, index) {
  idStack[idStackIndex++] = treeContextId;
  idStack[idStackIndex++] = treeContextOverflow;
  idStack[idStackIndex++] = treeContextProvider;
  treeContextProvider = workInProgress;
  var baseIdWithLeadingBit = treeContextId;
  workInProgress = treeContextOverflow;
  var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
  baseIdWithLeadingBit &= ~(1 << baseLength);
  index += 1;
  var length = 32 - clz32(totalChildren) + baseLength;
  if (30 < length) {
    var numberOfOverflowBits = baseLength - (baseLength % 5);
    length = (
      baseIdWithLeadingBit &
      ((1 << numberOfOverflowBits) - 1)
    ).toString(32);
    baseIdWithLeadingBit >>= numberOfOverflowBits;
    baseLength -= numberOfOverflowBits;
    treeContextId =
      (1 << (32 - clz32(totalChildren) + baseLength)) |
      (index << baseLength) |
      baseIdWithLeadingBit;
    treeContextOverflow = length + workInProgress;
  } else
    (treeContextId =
      (1 << length) | (index << baseLength) | baseIdWithLeadingBit),
      (treeContextOverflow = workInProgress);
}
function pushMaterializedTreeId(workInProgress) {
  null !== workInProgress.return &&
    (pushTreeFork(workInProgress, 1), pushTreeId(workInProgress, 1, 0));
}
function popTreeContext(workInProgress) {
  for (; workInProgress === treeForkProvider; )
    (treeForkProvider = forkStack[--forkStackIndex]),
      (forkStack[forkStackIndex] = null),
      (treeForkCount = forkStack[--forkStackIndex]),
      (forkStack[forkStackIndex] = null);
  for (; workInProgress === treeContextProvider; )
    (treeContextProvider = idStack[--idStackIndex]),
      (idStack[idStackIndex] = null),
      (treeContextOverflow = idStack[--idStackIndex]),
      (idStack[idStackIndex] = null),
      (treeContextId = idStack[--idStackIndex]),
      (idStack[idStackIndex] = null);
}
var hydrationParentFiber = null,
  nextHydratableInstance = null,
  isHydrating = !1,
  hydrationErrors = null,
  rootOrSingletonContext = !1,
  HydrationMismatchException = Error(formatProdErrorMessage(519));
function throwOnHydrationMismatch(fiber) {
  var error = Error(formatProdErrorMessage(418, ""));
  queueHydrationError(createCapturedValueAtFiber(error, fiber));
  throw HydrationMismatchException;
}
function prepareToHydrateHostInstance(fiber) {
  var instance = fiber.stateNode,
    type = fiber.type,
    props = fiber.memoizedProps;
  instance[internalInstanceKey] = fiber;
  instance[internalPropsKey] = props;
  switch (type) {
    case "dialog":
      listenToNonDelegatedEvent("cancel", instance);
      listenToNonDelegatedEvent("close", instance);
      break;
    case "iframe":
    case "object":
    case "embed":
      listenToNonDelegatedEvent("load", instance);
      break;
    case "video":
    case "audio":
      for (type = 0; type < mediaEventTypes.length; type++)
        listenToNonDelegatedEvent(mediaEventTypes[type], instance);
      break;
    case "source":
      listenToNonDelegatedEvent("error", instance);
      break;
    case "img":
    case "image":
    case "link":
      listenToNonDelegatedEvent("error", instance);
      listenToNonDelegatedEvent("load", instance);
      break;
    case "details":
      listenToNonDelegatedEvent("toggle", instance);
      break;
    case "input":
      listenToNonDelegatedEvent("invalid", instance);
      initInput(
        instance,
        props.value,
        props.defaultValue,
        props.checked,
        props.defaultChecked,
        props.type,
        props.name,
        !0
      );
      track(instance);
      break;
    case "select":
      listenToNonDelegatedEvent("invalid", instance);
      break;
    case "textarea":
      listenToNonDelegatedEvent("invalid", instance),
        initTextarea(instance, props.value, props.defaultValue, props.children),
        track(instance);
  }
  type = props.children;
  ("string" !== typeof type &&
    "number" !== typeof type &&
    "bigint" !== typeof type) ||
  instance.textContent === "" + type ||
  !0 === props.suppressHydrationWarning ||
  checkForUnmatchedText(instance.textContent, type)
    ? (null != props.popover &&
        (listenToNonDelegatedEvent("beforetoggle", instance),
        listenToNonDelegatedEvent("toggle", instance)),
      null != props.onScroll && listenToNonDelegatedEvent("scroll", instance),
      null != props.onScrollEnd &&
        listenToNonDelegatedEvent("scrollend", instance),
      null != props.onClick && (instance.onclick = noop$1),
      (instance = !0))
    : (instance = !1);
  instance || throwOnHydrationMismatch(fiber);
}
function popToNextHostParent(fiber) {
  for (hydrationParentFiber = fiber.return; hydrationParentFiber; )
    switch (hydrationParentFiber.tag) {
      case 3:
      case 27:
        rootOrSingletonContext = !0;
        return;
      case 5:
      case 13:
        rootOrSingletonContext = !1;
        return;
      default:
        hydrationParentFiber = hydrationParentFiber.return;
    }
}
function popHydrationState(fiber) {
  if (fiber !== hydrationParentFiber) return !1;
  if (!isHydrating) return popToNextHostParent(fiber), (isHydrating = !0), !1;
  var shouldClear = !1,
    JSCompiler_temp;
  if ((JSCompiler_temp = 3 !== fiber.tag && 27 !== fiber.tag)) {
    if ((JSCompiler_temp = 5 === fiber.tag))
      (JSCompiler_temp = fiber.type),
        (JSCompiler_temp =
          !("form" !== JSCompiler_temp && "button" !== JSCompiler_temp) ||
          shouldSetTextContent(fiber.type, fiber.memoizedProps));
    JSCompiler_temp = !JSCompiler_temp;
  }
  JSCompiler_temp && (shouldClear = !0);
  shouldClear && nextHydratableInstance && throwOnHydrationMismatch(fiber);
  popToNextHostParent(fiber);
  if (13 === fiber.tag) {
    fiber = fiber.memoizedState;
    fiber = null !== fiber ? fiber.dehydrated : null;
    if (!fiber) throw Error(formatProdErrorMessage(317));
    a: {
      fiber = fiber.nextSibling;
      for (shouldClear = 0; fiber; ) {
        if (8 === fiber.nodeType)
          if (((JSCompiler_temp = fiber.data), "/$" === JSCompiler_temp)) {
            if (0 === shouldClear) {
              nextHydratableInstance = getNextHydratable(fiber.nextSibling);
              break a;
            }
            shouldClear--;
          } else
            ("$" !== JSCompiler_temp &&
              "$!" !== JSCompiler_temp &&
              "$?" !== JSCompiler_temp) ||
              shouldClear++;
        fiber = fiber.nextSibling;
      }
      nextHydratableInstance = null;
    }
  } else
    nextHydratableInstance = hydrationParentFiber
      ? getNextHydratable(fiber.stateNode.nextSibling)
      : null;
  return !0;
}
function resetHydrationState() {
  nextHydratableInstance = hydrationParentFiber = null;
  isHydrating = !1;
}
function queueHydrationError(error) {
  null === hydrationErrors
    ? (hydrationErrors = [error])
    : hydrationErrors.push(error);
}
var SuspenseException = Error(formatProdErrorMessage(460)),
  SuspenseyCommitException = Error(formatProdErrorMessage(474)),
  noopSuspenseyCommitThenable = { then: function () {} };
function isThenableResolved(thenable) {
  thenable = thenable.status;
  return "fulfilled" === thenable || "rejected" === thenable;
}
function noop$3() {}
function trackUsedThenable(thenableState, thenable, index) {
  index = thenableState[index];
  void 0 === index
    ? thenableState.push(thenable)
    : index !== thenable && (thenable.then(noop$3, noop$3), (thenable = index));
  switch (thenable.status) {
    case "fulfilled":
      return thenable.value;
    case "rejected":
      thenableState = thenable.reason;
      if (thenableState === SuspenseException)
        throw Error(formatProdErrorMessage(483));
      throw thenableState;
    default:
      if ("string" === typeof thenable.status) thenable.then(noop$3, noop$3);
      else {
        thenableState = workInProgressRoot;
        if (null !== thenableState && 100 < thenableState.shellSuspendCounter)
          throw Error(formatProdErrorMessage(482));
        thenableState = thenable;
        thenableState.status = "pending";
        thenableState.then(
          function (fulfilledValue) {
            if ("pending" === thenable.status) {
              var fulfilledThenable = thenable;
              fulfilledThenable.status = "fulfilled";
              fulfilledThenable.value = fulfilledValue;
            }
          },
          function (error) {
            if ("pending" === thenable.status) {
              var rejectedThenable = thenable;
              rejectedThenable.status = "rejected";
              rejectedThenable.reason = error;
            }
          }
        );
      }
      switch (thenable.status) {
        case "fulfilled":
          return thenable.value;
        case "rejected":
          thenableState = thenable.reason;
          if (thenableState === SuspenseException)
            throw Error(formatProdErrorMessage(483));
          throw thenableState;
      }
      suspendedThenable = thenable;
      throw SuspenseException;
  }
}
var suspendedThenable = null;
function getSuspendedThenable() {
  if (null === suspendedThenable) throw Error(formatProdErrorMessage(459));
  var thenable = suspendedThenable;
  suspendedThenable = null;
  return thenable;
}
var thenableState$1 = null,
  thenableIndexCounter$1 = 0;
function unwrapThenable(thenable) {
  var index = thenableIndexCounter$1;
  thenableIndexCounter$1 += 1;
  null === thenableState$1 && (thenableState$1 = []);
  return trackUsedThenable(thenableState$1, thenable, index);
}
function coerceRef(workInProgress, element) {
  element = element.props.ref;
  workInProgress.ref = void 0 !== element ? element : null;
}
function throwOnInvalidObjectType(returnFiber, newChild) {
  if (newChild.$$typeof === REACT_LEGACY_ELEMENT_TYPE)
    throw Error(formatProdErrorMessage(525));
  returnFiber = Object.prototype.toString.call(newChild);
  throw Error(
    formatProdErrorMessage(
      31,
      "[object Object]" === returnFiber
        ? "object with keys {" + Object.keys(newChild).join(", ") + "}"
        : returnFiber
    )
  );
}
function resolveLazy(lazyType) {
  var init = lazyType._init;
  return init(lazyType._payload);
}
function createChildReconciler(shouldTrackSideEffects) {
  function deleteChild(returnFiber, childToDelete) {
    if (shouldTrackSideEffects) {
      var deletions = returnFiber.deletions;
      null === deletions
        ? ((returnFiber.deletions = [childToDelete]), (returnFiber.flags |= 16))
        : deletions.push(childToDelete);
    }
  }
  function deleteRemainingChildren(returnFiber, currentFirstChild) {
    if (!shouldTrackSideEffects) return null;
    for (; null !== currentFirstChild; )
      deleteChild(returnFiber, currentFirstChild),
        (currentFirstChild = currentFirstChild.sibling);
    return null;
  }
  function mapRemainingChildren(currentFirstChild) {
    for (var existingChildren = new Map(); null !== currentFirstChild; )
      null !== currentFirstChild.key
        ? existingChildren.set(currentFirstChild.key, currentFirstChild)
        : existingChildren.set(currentFirstChild.index, currentFirstChild),
        (currentFirstChild = currentFirstChild.sibling);
    return existingChildren;
  }
  function useFiber(fiber, pendingProps) {
    fiber = createWorkInProgress(fiber, pendingProps);
    fiber.index = 0;
    fiber.sibling = null;
    return fiber;
  }
  function placeChild(newFiber, lastPlacedIndex, newIndex) {
    newFiber.index = newIndex;
    if (!shouldTrackSideEffects)
      return (newFiber.flags |= 1048576), lastPlacedIndex;
    newIndex = newFiber.alternate;
    if (null !== newIndex)
      return (
        (newIndex = newIndex.index),
        newIndex < lastPlacedIndex
          ? ((newFiber.flags |= 33554434), lastPlacedIndex)
          : newIndex
      );
    newFiber.flags |= 33554434;
    return lastPlacedIndex;
  }
  function placeSingleChild(newFiber) {
    shouldTrackSideEffects &&
      null === newFiber.alternate &&
      (newFiber.flags |= 33554434);
    return newFiber;
  }
  function updateTextNode(returnFiber, current, textContent, lanes) {
    if (null === current || 6 !== current.tag)
      return (
        (current = createFiberFromText(textContent, returnFiber.mode, lanes)),
        (current.return = returnFiber),
        current
      );
    current = useFiber(current, textContent);
    current.return = returnFiber;
    return current;
  }
  function updateElement(returnFiber, current, element, lanes) {
    var elementType = element.type;
    if (elementType === REACT_FRAGMENT_TYPE)
      return updateFragment(
        returnFiber,
        current,
        element.props.children,
        lanes,
        element.key
      );
    if (
      null !== current &&
      (current.elementType === elementType ||
        ("object" === typeof elementType &&
          null !== elementType &&
          elementType.$$typeof === REACT_LAZY_TYPE &&
          resolveLazy(elementType) === current.type))
    )
      return (
        (current = useFiber(current, element.props)),
        coerceRef(current, element),
        (current.return = returnFiber),
        current
      );
    current = createFiberFromTypeAndProps(
      element.type,
      element.key,
      element.props,
      null,
      returnFiber.mode,
      lanes
    );
    coerceRef(current, element);
    current.return = returnFiber;
    return current;
  }
  function updatePortal(returnFiber, current, portal, lanes) {
    if (
      null === current ||
      4 !== current.tag ||
      current.stateNode.containerInfo !== portal.containerInfo ||
      current.stateNode.implementation !== portal.implementation
    )
      return (
        (current = createFiberFromPortal(portal, returnFiber.mode, lanes)),
        (current.return = returnFiber),
        current
      );
    current = useFiber(current, portal.children || []);
    current.return = returnFiber;
    return current;
  }
  function updateFragment(returnFiber, current, fragment, lanes, key) {
    if (null === current || 7 !== current.tag)
      return (
        (current = createFiberFromFragment(
          fragment,
          returnFiber.mode,
          lanes,
          key
        )),
        (current.return = returnFiber),
        current
      );
    current = useFiber(current, fragment);
    current.return = returnFiber;
    return current;
  }
  function createChild(returnFiber, newChild, lanes) {
    if (
      ("string" === typeof newChild && "" !== newChild) ||
      "number" === typeof newChild ||
      "bigint" === typeof newChild
    )
      return (
        (newChild = createFiberFromText(
          "" + newChild,
          returnFiber.mode,
          lanes
        )),
        (newChild.return = returnFiber),
        newChild
      );
    if ("object" === typeof newChild && null !== newChild) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          return (
            (lanes = createFiberFromTypeAndProps(
              newChild.type,
              newChild.key,
              newChild.props,
              null,
              returnFiber.mode,
              lanes
            )),
            coerceRef(lanes, newChild),
            (lanes.return = returnFiber),
            lanes
          );
        case REACT_PORTAL_TYPE:
          return (
            (newChild = createFiberFromPortal(
              newChild,
              returnFiber.mode,
              lanes
            )),
            (newChild.return = returnFiber),
            newChild
          );
        case REACT_LAZY_TYPE:
          var init = newChild._init;
          newChild = init(newChild._payload);
          return createChild(returnFiber, newChild, lanes);
      }
      if (isArrayImpl(newChild) || getIteratorFn(newChild))
        return (
          (newChild = createFiberFromFragment(
            newChild,
            returnFiber.mode,
            lanes,
            null
          )),
          (newChild.return = returnFiber),
          newChild
        );
      if ("function" === typeof newChild.then)
        return createChild(returnFiber, unwrapThenable(newChild), lanes);
      if (newChild.$$typeof === REACT_CONTEXT_TYPE)
        return createChild(
          returnFiber,
          readContextDuringReconciliation(returnFiber, newChild),
          lanes
        );
      throwOnInvalidObjectType(returnFiber, newChild);
    }
    return null;
  }
  function updateSlot(returnFiber, oldFiber, newChild, lanes) {
    var key = null !== oldFiber ? oldFiber.key : null;
    if (
      ("string" === typeof newChild && "" !== newChild) ||
      "number" === typeof newChild ||
      "bigint" === typeof newChild
    )
      return null !== key
        ? null
        : updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
    if ("object" === typeof newChild && null !== newChild) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          return newChild.key === key
            ? updateElement(returnFiber, oldFiber, newChild, lanes)
            : null;
        case REACT_PORTAL_TYPE:
          return newChild.key === key
            ? updatePortal(returnFiber, oldFiber, newChild, lanes)
            : null;
        case REACT_LAZY_TYPE:
          return (
            (key = newChild._init),
            (newChild = key(newChild._payload)),
            updateSlot(returnFiber, oldFiber, newChild, lanes)
          );
      }
      if (isArrayImpl(newChild) || getIteratorFn(newChild))
        return null !== key
          ? null
          : updateFragment(returnFiber, oldFiber, newChild, lanes, null);
      if ("function" === typeof newChild.then)
        return updateSlot(
          returnFiber,
          oldFiber,
          unwrapThenable(newChild),
          lanes
        );
      if (newChild.$$typeof === REACT_CONTEXT_TYPE)
        return updateSlot(
          returnFiber,
          oldFiber,
          readContextDuringReconciliation(returnFiber, newChild),
          lanes
        );
      throwOnInvalidObjectType(returnFiber, newChild);
    }
    return null;
  }
  function updateFromMap(
    existingChildren,
    returnFiber,
    newIdx,
    newChild,
    lanes
  ) {
    if (
      ("string" === typeof newChild && "" !== newChild) ||
      "number" === typeof newChild ||
      "bigint" === typeof newChild
    )
      return (
        (existingChildren = existingChildren.get(newIdx) || null),
        updateTextNode(returnFiber, existingChildren, "" + newChild, lanes)
      );
    if ("object" === typeof newChild && null !== newChild) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          return (
            (existingChildren =
              existingChildren.get(
                null === newChild.key ? newIdx : newChild.key
              ) || null),
            updateElement(returnFiber, existingChildren, newChild, lanes)
          );
        case REACT_PORTAL_TYPE:
          return (
            (existingChildren =
              existingChildren.get(
                null === newChild.key ? newIdx : newChild.key
              ) || null),
            updatePortal(returnFiber, existingChildren, newChild, lanes)
          );
        case REACT_LAZY_TYPE:
          var init = newChild._init;
          newChild = init(newChild._payload);
          return updateFromMap(
            existingChildren,
            returnFiber,
            newIdx,
            newChild,
            lanes
          );
      }
      if (isArrayImpl(newChild) || getIteratorFn(newChild))
        return (
          (existingChildren = existingChildren.get(newIdx) || null),
          updateFragment(returnFiber, existingChildren, newChild, lanes, null)
        );
      if ("function" === typeof newChild.then)
        return updateFromMap(
          existingChildren,
          returnFiber,
          newIdx,
          unwrapThenable(newChild),
          lanes
        );
      if (newChild.$$typeof === REACT_CONTEXT_TYPE)
        return updateFromMap(
          existingChildren,
          returnFiber,
          newIdx,
          readContextDuringReconciliation(returnFiber, newChild),
          lanes
        );
      throwOnInvalidObjectType(returnFiber, newChild);
    }
    return null;
  }
  function reconcileChildrenArray(
    returnFiber,
    currentFirstChild,
    newChildren,
    lanes
  ) {
    for (
      var resultingFirstChild = null,
        previousNewFiber = null,
        oldFiber = currentFirstChild,
        newIdx = (currentFirstChild = 0),
        nextOldFiber = null;
      null !== oldFiber && newIdx < newChildren.length;
      newIdx++
    ) {
      oldFiber.index > newIdx
        ? ((nextOldFiber = oldFiber), (oldFiber = null))
        : (nextOldFiber = oldFiber.sibling);
      var newFiber = updateSlot(
        returnFiber,
        oldFiber,
        newChildren[newIdx],
        lanes
      );
      if (null === newFiber) {
        null === oldFiber && (oldFiber = nextOldFiber);
        break;
      }
      shouldTrackSideEffects &&
        oldFiber &&
        null === newFiber.alternate &&
        deleteChild(returnFiber, oldFiber);
      currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
      null === previousNewFiber
        ? (resultingFirstChild = newFiber)
        : (previousNewFiber.sibling = newFiber);
      previousNewFiber = newFiber;
      oldFiber = nextOldFiber;
    }
    if (newIdx === newChildren.length)
      return (
        deleteRemainingChildren(returnFiber, oldFiber),
        isHydrating && pushTreeFork(returnFiber, newIdx),
        resultingFirstChild
      );
    if (null === oldFiber) {
      for (; newIdx < newChildren.length; newIdx++)
        (oldFiber = createChild(returnFiber, newChildren[newIdx], lanes)),
          null !== oldFiber &&
            ((currentFirstChild = placeChild(
              oldFiber,
              currentFirstChild,
              newIdx
            )),
            null === previousNewFiber
              ? (resultingFirstChild = oldFiber)
              : (previousNewFiber.sibling = oldFiber),
            (previousNewFiber = oldFiber));
      isHydrating && pushTreeFork(returnFiber, newIdx);
      return resultingFirstChild;
    }
    for (
      oldFiber = mapRemainingChildren(oldFiber);
      newIdx < newChildren.length;
      newIdx++
    )
      (nextOldFiber = updateFromMap(
        oldFiber,
        returnFiber,
        newIdx,
        newChildren[newIdx],
        lanes
      )),
        null !== nextOldFiber &&
          (shouldTrackSideEffects &&
            null !== nextOldFiber.alternate &&
            oldFiber.delete(
              null === nextOldFiber.key ? newIdx : nextOldFiber.key
            ),
          (currentFirstChild = placeChild(
            nextOldFiber,
            currentFirstChild,
            newIdx
          )),
          null === previousNewFiber
            ? (resultingFirstChild = nextOldFiber)
            : (previousNewFiber.sibling = nextOldFiber),
          (previousNewFiber = nextOldFiber));
    shouldTrackSideEffects &&
      oldFiber.forEach(function (child) {
        return deleteChild(returnFiber, child);
      });
    isHydrating && pushTreeFork(returnFiber, newIdx);
    return resultingFirstChild;
  }
  function reconcileChildrenIterator(
    returnFiber,
    currentFirstChild,
    newChildren,
    lanes
  ) {
    if (null == newChildren) throw Error(formatProdErrorMessage(151));
    for (
      var resultingFirstChild = null,
        previousNewFiber = null,
        oldFiber = currentFirstChild,
        newIdx = (currentFirstChild = 0),
        nextOldFiber = null,
        step = newChildren.next();
      null !== oldFiber && !step.done;
      newIdx++, step = newChildren.next()
    ) {
      oldFiber.index > newIdx
        ? ((nextOldFiber = oldFiber), (oldFiber = null))
        : (nextOldFiber = oldFiber.sibling);
      var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
      if (null === newFiber) {
        null === oldFiber && (oldFiber = nextOldFiber);
        break;
      }
      shouldTrackSideEffects &&
        oldFiber &&
        null === newFiber.alternate &&
        deleteChild(returnFiber, oldFiber);
      currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
      null === previousNewFiber
        ? (resultingFirstChild = newFiber)
        : (previousNewFiber.sibling = newFiber);
      previousNewFiber = newFiber;
      oldFiber = nextOldFiber;
    }
    if (step.done)
      return (
        deleteRemainingChildren(returnFiber, oldFiber),
        isHydrating && pushTreeFork(returnFiber, newIdx),
        resultingFirstChild
      );
    if (null === oldFiber) {
      for (; !step.done; newIdx++, step = newChildren.next())
        (step = createChild(returnFiber, step.value, lanes)),
          null !== step &&
            ((currentFirstChild = placeChild(step, currentFirstChild, newIdx)),
            null === previousNewFiber
              ? (resultingFirstChild = step)
              : (previousNewFiber.sibling = step),
            (previousNewFiber = step));
      isHydrating && pushTreeFork(returnFiber, newIdx);
      return resultingFirstChild;
    }
    for (
      oldFiber = mapRemainingChildren(oldFiber);
      !step.done;
      newIdx++, step = newChildren.next()
    )
      (step = updateFromMap(oldFiber, returnFiber, newIdx, step.value, lanes)),
        null !== step &&
          (shouldTrackSideEffects &&
            null !== step.alternate &&
            oldFiber.delete(null === step.key ? newIdx : step.key),
          (currentFirstChild = placeChild(step, currentFirstChild, newIdx)),
          null === previousNewFiber
            ? (resultingFirstChild = step)
            : (previousNewFiber.sibling = step),
          (previousNewFiber = step));
    shouldTrackSideEffects &&
      oldFiber.forEach(function (child) {
        return deleteChild(returnFiber, child);
      });
    isHydrating && pushTreeFork(returnFiber, newIdx);
    return resultingFirstChild;
  }
  function reconcileChildFibersImpl(
    returnFiber,
    currentFirstChild,
    newChild,
    lanes
  ) {
    "object" === typeof newChild &&
      null !== newChild &&
      newChild.type === REACT_FRAGMENT_TYPE &&
      null === newChild.key &&
      (newChild = newChild.props.children);
    if ("object" === typeof newChild && null !== newChild) {
      switch (newChild.$$typeof) {
        case REACT_ELEMENT_TYPE:
          a: {
            for (var key = newChild.key; null !== currentFirstChild; ) {
              if (currentFirstChild.key === key) {
                key = newChild.type;
                if (key === REACT_FRAGMENT_TYPE) {
                  if (7 === currentFirstChild.tag) {
                    deleteRemainingChildren(
                      returnFiber,
                      currentFirstChild.sibling
                    );
                    lanes = useFiber(
                      currentFirstChild,
                      newChild.props.children
                    );
                    lanes.return = returnFiber;
                    returnFiber = lanes;
                    break a;
                  }
                } else if (
                  currentFirstChild.elementType === key ||
                  ("object" === typeof key &&
                    null !== key &&
                    key.$$typeof === REACT_LAZY_TYPE &&
                    resolveLazy(key) === currentFirstChild.type)
                ) {
                  deleteRemainingChildren(
                    returnFiber,
                    currentFirstChild.sibling
                  );
                  lanes = useFiber(currentFirstChild, newChild.props);
                  coerceRef(lanes, newChild);
                  lanes.return = returnFiber;
                  returnFiber = lanes;
                  break a;
                }
                deleteRemainingChildren(returnFiber, currentFirstChild);
                break;
              } else deleteChild(returnFiber, currentFirstChild);
              currentFirstChild = currentFirstChild.sibling;
            }
            newChild.type === REACT_FRAGMENT_TYPE
              ? ((lanes = createFiberFromFragment(
                  newChild.props.children,
                  returnFiber.mode,
                  lanes,
                  newChild.key
                )),
                (lanes.return = returnFiber),
                (returnFiber = lanes))
              : ((lanes = createFiberFromTypeAndProps(
                  newChild.type,
                  newChild.key,
                  newChild.props,
                  null,
                  returnFiber.mode,
                  lanes
                )),
                coerceRef(lanes, newChild),
                (lanes.return = returnFiber),
                (returnFiber = lanes));
          }
          return placeSingleChild(returnFiber);
        case REACT_PORTAL_TYPE:
          a: {
            for (key = newChild.key; null !== currentFirstChild; ) {
              if (currentFirstChild.key === key)
                if (
                  4 === currentFirstChild.tag &&
                  currentFirstChild.stateNode.containerInfo ===
                    newChild.containerInfo &&
                  currentFirstChild.stateNode.implementation ===
                    newChild.implementation
                ) {
                  deleteRemainingChildren(
                    returnFiber,
                    currentFirstChild.sibling
                  );
                  lanes = useFiber(currentFirstChild, newChild.children || []);
                  lanes.return = returnFiber;
                  returnFiber = lanes;
                  break a;
                } else {
                  deleteRemainingChildren(returnFiber, currentFirstChild);
                  break;
                }
              else deleteChild(returnFiber, currentFirstChild);
              currentFirstChild = currentFirstChild.sibling;
            }
            lanes = createFiberFromPortal(newChild, returnFiber.mode, lanes);
            lanes.return = returnFiber;
            returnFiber = lanes;
          }
          return placeSingleChild(returnFiber);
        case REACT_LAZY_TYPE:
          return (
            (key = newChild._init),
            (newChild = key(newChild._payload)),
            reconcileChildFibersImpl(
              returnFiber,
              currentFirstChild,
              newChild,
              lanes
            )
          );
      }
      if (isArrayImpl(newChild))
        return reconcileChildrenArray(
          returnFiber,
          currentFirstChild,
          newChild,
          lanes
        );
      if (getIteratorFn(newChild)) {
        key = getIteratorFn(newChild);
        if ("function" !== typeof key) throw Error(formatProdErrorMessage(150));
        newChild = key.call(newChild);
        return reconcileChildrenIterator(
          returnFiber,
          currentFirstChild,
          newChild,
          lanes
        );
      }
      if ("function" === typeof newChild.then)
        return reconcileChildFibersImpl(
          returnFiber,
          currentFirstChild,
          unwrapThenable(newChild),
          lanes
        );
      if (newChild.$$typeof === REACT_CONTEXT_TYPE)
        return reconcileChildFibersImpl(
          returnFiber,
          currentFirstChild,
          readContextDuringReconciliation(returnFiber, newChild),
          lanes
        );
      throwOnInvalidObjectType(returnFiber, newChild);
    }
    return ("string" === typeof newChild && "" !== newChild) ||
      "number" === typeof newChild ||
      "bigint" === typeof newChild
      ? ((newChild = "" + newChild),
        null !== currentFirstChild && 6 === currentFirstChild.tag
          ? (deleteRemainingChildren(returnFiber, currentFirstChild.sibling),
            (lanes = useFiber(currentFirstChild, newChild)),
            (lanes.return = returnFiber),
            (returnFiber = lanes))
          : (deleteRemainingChildren(returnFiber, currentFirstChild),
            (lanes = createFiberFromText(newChild, returnFiber.mode, lanes)),
            (lanes.return = returnFiber),
            (returnFiber = lanes)),
        placeSingleChild(returnFiber))
      : deleteRemainingChildren(returnFiber, currentFirstChild);
  }
  return function (returnFiber, currentFirstChild, newChild, lanes) {
    try {
      thenableIndexCounter$1 = 0;
      var firstChildFiber = reconcileChildFibersImpl(
        returnFiber,
        currentFirstChild,
        newChild,
        lanes
      );
      thenableState$1 = null;
      return firstChildFiber;
    } catch (x) {
      if (x === SuspenseException) throw x;
      var fiber = createFiberImplClass(29, x, null, returnFiber.mode);
      fiber.lanes = lanes;
      fiber.return = returnFiber;
      return fiber;
    } finally {
    }
  };
}
var reconcileChildFibers = createChildReconciler(!0),
  mountChildFibers = createChildReconciler(!1),
  currentTreeHiddenStackCursor = createCursor(null),
  prevEntangledRenderLanesCursor = createCursor(0);
function pushHiddenContext(fiber, context) {
  fiber = entangledRenderLanes;
  push(prevEntangledRenderLanesCursor, fiber);
  push(currentTreeHiddenStackCursor, context);
  entangledRenderLanes = fiber | context.baseLanes;
}
function reuseHiddenContextOnStack() {
  push(prevEntangledRenderLanesCursor, entangledRenderLanes);
  push(currentTreeHiddenStackCursor, currentTreeHiddenStackCursor.current);
}
function popHiddenContext() {
  entangledRenderLanes = prevEntangledRenderLanesCursor.current;
  pop(currentTreeHiddenStackCursor);
  pop(prevEntangledRenderLanesCursor);
}
var suspenseHandlerStackCursor = createCursor(null),
  shellBoundary = null;
function pushPrimaryTreeSuspenseHandler(handler) {
  var current = handler.alternate;
  push(suspenseStackCursor, suspenseStackCursor.current & 1);
  push(suspenseHandlerStackCursor, handler);
  null === shellBoundary &&
    (null === current || null !== currentTreeHiddenStackCursor.current
      ? (shellBoundary = handler)
      : null !== current.memoizedState && (shellBoundary = handler));
}
function pushOffscreenSuspenseHandler(fiber) {
  if (22 === fiber.tag) {
    if (
      (push(suspenseStackCursor, suspenseStackCursor.current),
      push(suspenseHandlerStackCursor, fiber),
      null === shellBoundary)
    ) {
      var current = fiber.alternate;
      null !== current &&
        null !== current.memoizedState &&
        (shellBoundary = fiber);
    }
  } else reuseSuspenseHandlerOnStack(fiber);
}
function reuseSuspenseHandlerOnStack() {
  push(suspenseStackCursor, suspenseStackCursor.current);
  push(suspenseHandlerStackCursor, suspenseHandlerStackCursor.current);
}
function popSuspenseHandler(fiber) {
  pop(suspenseHandlerStackCursor);
  shellBoundary === fiber && (shellBoundary = null);
  pop(suspenseStackCursor);
}
var suspenseStackCursor = createCursor(0);
function findFirstSuspended(row) {
  for (var node = row; null !== node; ) {
    if (13 === node.tag) {
      var state = node.memoizedState;
      if (
        null !== state &&
        ((state = state.dehydrated),
        null === state || "$?" === state.data || "$!" === state.data)
      )
        return node;
    } else if (19 === node.tag && void 0 !== node.memoizedProps.revealOrder) {
      if (0 !== (node.flags & 128)) return node;
    } else if (null !== node.child) {
      node.child.return = node;
      node = node.child;
      continue;
    }
    if (node === row) break;
    for (; null === node.sibling; ) {
      if (null === node.return || node.return === row) return null;
      node = node.return;
    }
    node.sibling.return = node.return;
    node = node.sibling;
  }
  return null;
}
var AbortControllerLocal =
    "undefined" !== typeof AbortController
      ? AbortController
      : function () {
          var listeners = [],
            signal = (this.signal = {
              aborted: !1,
              addEventListener: function (type, listener) {
                listeners.push(listener);
              }
            });
          this.abort = function () {
            signal.aborted = !0;
            listeners.forEach(function (listener) {
              return listener();
            });
          };
        },
  scheduleCallback$2 = Scheduler.unstable_scheduleCallback,
  NormalPriority = Scheduler.unstable_NormalPriority,
  CacheContext = {
    $$typeof: REACT_CONTEXT_TYPE,
    Consumer: null,
    Provider: null,
    _currentValue: null,
    _currentValue2: null,
    _threadCount: 0
  };
function createCache() {
  return {
    controller: new AbortControllerLocal(),
    data: new Map(),
    refCount: 0
  };
}
function releaseCache(cache) {
  cache.refCount--;
  0 === cache.refCount &&
    scheduleCallback$2(NormalPriority, function () {
      cache.controller.abort();
    });
}
var currentEntangledListeners = null,
  currentEntangledPendingCount = 0,
  currentEntangledLane = 0,
  currentEntangledActionThenable = null;
function entangleAsyncAction(transition, thenable) {
  if (null === currentEntangledListeners) {
    var entangledListeners = (currentEntangledListeners = []);
    currentEntangledPendingCount = 0;
    currentEntangledLane = requestTransitionLane();
    currentEntangledActionThenable = {
      status: "pending",
      value: void 0,
      then: function (resolve) {
        entangledListeners.push(resolve);
      }
    };
  }
  currentEntangledPendingCount++;
  thenable.then(pingEngtangledActionScope, pingEngtangledActionScope);
  return thenable;
}
function pingEngtangledActionScope() {
  if (
    0 === --currentEntangledPendingCount &&
    null !== currentEntangledListeners
  ) {
    null !== currentEntangledActionThenable &&
      (currentEntangledActionThenable.status = "fulfilled");
    var listeners = currentEntangledListeners;
    currentEntangledListeners = null;
    currentEntangledLane = 0;
    currentEntangledActionThenable = null;
    for (var i = 0; i < listeners.length; i++) (0, listeners[i])();
  }
}
function chainThenableValue(thenable, result) {
  var listeners = [],
    thenableWithOverride = {
      status: "pending",
      value: null,
      reason: null,
      then: function (resolve) {
        listeners.push(resolve);
      }
    };
  thenable.then(
    function () {
      thenableWithOverride.status = "fulfilled";
      thenableWithOverride.value = result;
      for (var i = 0; i < listeners.length; i++) (0, listeners[i])(result);
    },
    function (error) {
      thenableWithOverride.status = "rejected";
      thenableWithOverride.reason = error;
      for (error = 0; error < listeners.length; error++)
        (0, listeners[error])(void 0);
    }
  );
  return thenableWithOverride;
}
var prevOnStartTransitionFinish = ReactSharedInternals.S;
ReactSharedInternals.S = function (transition, returnValue) {
  "object" === typeof returnValue &&
    null !== returnValue &&
    "function" === typeof returnValue.then &&
    entangleAsyncAction(transition, returnValue);
  null !== prevOnStartTransitionFinish &&
    prevOnStartTransitionFinish(transition, returnValue);
};
var resumedCache = createCursor(null);
function peekCacheFromPool() {
  var cacheResumedFromPreviousRender = resumedCache.current;
  return null !== cacheResumedFromPreviousRender
    ? cacheResumedFromPreviousRender
    : workInProgressRoot.pooledCache;
}
function pushTransition(offscreenWorkInProgress, prevCachePool) {
  null === prevCachePool
    ? push(resumedCache, resumedCache.current)
    : push(resumedCache, prevCachePool.pool);
}
function getSuspendedCache() {
  var cacheFromPool = peekCacheFromPool();
  return null === cacheFromPool
    ? null
    : { parent: CacheContext._currentValue, pool: cacheFromPool };
}
var renderLanes = 0,
  currentlyRenderingFiber$1 = null,
  currentHook = null,
  workInProgressHook = null,
  didScheduleRenderPhaseUpdate = !1,
  didScheduleRenderPhaseUpdateDuringThisPass = !1,
  shouldDoubleInvokeUserFnsInHooksDEV = !1,
  localIdCounter = 0,
  thenableIndexCounter = 0,
  thenableState = null,
  globalClientIdCounter = 0;
function throwInvalidHookError() {
  throw Error(formatProdErrorMessage(321));
}
function areHookInputsEqual(nextDeps, prevDeps) {
  if (null === prevDeps) return !1;
  for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++)
    if (!objectIs(nextDeps[i], prevDeps[i])) return !1;
  return !0;
}
function renderWithHooks(
  current,
  workInProgress,
  Component,
  props,
  secondArg,
  nextRenderLanes
) {
  renderLanes = nextRenderLanes;
  currentlyRenderingFiber$1 = workInProgress;
  workInProgress.memoizedState = null;
  workInProgress.updateQueue = null;
  workInProgress.lanes = 0;
  ReactSharedInternals.H =
    null === current || null === current.memoizedState
      ? HooksDispatcherOnMount
      : HooksDispatcherOnUpdate;
  shouldDoubleInvokeUserFnsInHooksDEV = !1;
  nextRenderLanes = Component(props, secondArg);
  shouldDoubleInvokeUserFnsInHooksDEV = !1;
  didScheduleRenderPhaseUpdateDuringThisPass &&
    (nextRenderLanes = renderWithHooksAgain(
      workInProgress,
      Component,
      props,
      secondArg
    ));
  finishRenderingHooks(current);
  return nextRenderLanes;
}
function finishRenderingHooks(current) {
  ReactSharedInternals.H = ContextOnlyDispatcher;
  var didRenderTooFewHooks = null !== currentHook && null !== currentHook.next;
  renderLanes = 0;
  workInProgressHook = currentHook = currentlyRenderingFiber$1 = null;
  didScheduleRenderPhaseUpdate = !1;
  thenableIndexCounter = 0;
  thenableState = null;
  if (didRenderTooFewHooks) throw Error(formatProdErrorMessage(300));
  null === current ||
    didReceiveUpdate ||
    ((current = current.dependencies),
    null !== current &&
      checkIfContextChanged(current) &&
      (didReceiveUpdate = !0));
}
function renderWithHooksAgain(workInProgress, Component, props, secondArg) {
  currentlyRenderingFiber$1 = workInProgress;
  var numberOfReRenders = 0;
  do {
    didScheduleRenderPhaseUpdateDuringThisPass && (thenableState = null);
    thenableIndexCounter = 0;
    didScheduleRenderPhaseUpdateDuringThisPass = !1;
    if (25 <= numberOfReRenders) throw Error(formatProdErrorMessage(301));
    numberOfReRenders += 1;
    workInProgressHook = currentHook = null;
    if (null != workInProgress.updateQueue) {
      var children = workInProgress.updateQueue;
      children.lastEffect = null;
      children.events = null;
      children.stores = null;
      null != children.memoCache && (children.memoCache.index = 0);
    }
    ReactSharedInternals.H = HooksDispatcherOnRerender;
    children = Component(props, secondArg);
  } while (didScheduleRenderPhaseUpdateDuringThisPass);
  return children;
}
function TransitionAwareHostComponent() {
  var dispatcher = ReactSharedInternals.H,
    maybeThenable = dispatcher.useState()[0];
  maybeThenable =
    "function" === typeof maybeThenable.then
      ? useThenable(maybeThenable)
      : maybeThenable;
  dispatcher = dispatcher.useState()[0];
  (null !== currentHook ? currentHook.memoizedState : null) !== dispatcher &&
    (currentlyRenderingFiber$1.flags |= 1024);
  return maybeThenable;
}
function checkDidRenderIdHook() {
  var didRenderIdHook = 0 !== localIdCounter;
  localIdCounter = 0;
  return didRenderIdHook;
}
function bailoutHooks(current, workInProgress, lanes) {
  workInProgress.updateQueue = current.updateQueue;
  workInProgress.flags &= -2053;
  current.lanes &= ~lanes;
}
function resetHooksOnUnwind(workInProgress) {
  if (didScheduleRenderPhaseUpdate) {
    for (
      workInProgress = workInProgress.memoizedState;
      null !== workInProgress;

    ) {
      var queue = workInProgress.queue;
      null !== queue && (queue.pending = null);
      workInProgress = workInProgress.next;
    }
    didScheduleRenderPhaseUpdate = !1;
  }
  renderLanes = 0;
  workInProgressHook = currentHook = currentlyRenderingFiber$1 = null;
  didScheduleRenderPhaseUpdateDuringThisPass = !1;
  thenableIndexCounter = localIdCounter = 0;
  thenableState = null;
}
function mountWorkInProgressHook() {
  var hook = {
    memoizedState: null,
    baseState: null,
    baseQueue: null,
    queue: null,
    next: null
  };
  null === workInProgressHook
    ? (currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook)
    : (workInProgressHook = workInProgressHook.next = hook);
  return workInProgressHook;
}
function updateWorkInProgressHook() {
  if (null === currentHook) {
    var nextCurrentHook = currentlyRenderingFiber$1.alternate;
    nextCurrentHook =
      null !== nextCurrentHook ? nextCurrentHook.memoizedState : null;
  } else nextCurrentHook = currentHook.next;
  var nextWorkInProgressHook =
    null === workInProgressHook
      ? currentlyRenderingFiber$1.memoizedState
      : workInProgressHook.next;
  if (null !== nextWorkInProgressHook)
    (workInProgressHook = nextWorkInProgressHook),
      (currentHook = nextCurrentHook);
  else {
    if (null === nextCurrentHook) {
      if (null === currentlyRenderingFiber$1.alternate)
        throw Error(formatProdErrorMessage(467));
      throw Error(formatProdErrorMessage(310));
    }
    currentHook = nextCurrentHook;
    nextCurrentHook = {
      memoizedState: currentHook.memoizedState,
      baseState: currentHook.baseState,
      baseQueue: currentHook.baseQueue,
      queue: currentHook.queue,
      next: null
    };
    null === workInProgressHook
      ? (currentlyRenderingFiber$1.memoizedState = workInProgressHook =
          nextCurrentHook)
      : (workInProgressHook = workInProgressHook.next = nextCurrentHook);
  }
  return workInProgressHook;
}
var createFunctionComponentUpdateQueue;
createFunctionComponentUpdateQueue = function () {
  return { lastEffect: null, events: null, stores: null, memoCache: null };
};
function useThenable(thenable) {
  var index = thenableIndexCounter;
  thenableIndexCounter += 1;
  null === thenableState && (thenableState = []);
  thenable = trackUsedThenable(thenableState, thenable, index);
  index = currentlyRenderingFiber$1;
  null ===
    (null === workInProgressHook
      ? index.memoizedState
      : workInProgressHook.next) &&
    ((index = index.alternate),
    (ReactSharedInternals.H =
      null === index || null === index.memoizedState
        ? HooksDispatcherOnMount
        : HooksDispatcherOnUpdate));
  return thenable;
}
function use(usable) {
  if (null !== usable && "object" === typeof usable) {
    if ("function" === typeof usable.then) return useThenable(usable);
    if (usable.$$typeof === REACT_CONTEXT_TYPE) return readContext(usable);
  }
  throw Error(formatProdErrorMessage(438, String(usable)));
}
function useMemoCache(size) {
  var memoCache = null,
    updateQueue = currentlyRenderingFiber$1.updateQueue;
  null !== updateQueue && (memoCache = updateQueue.memoCache);
  if (null == memoCache) {
    var current = currentlyRenderingFiber$1.alternate;
    null !== current &&
      ((current = current.updateQueue),
      null !== current &&
        ((current = current.memoCache),
        null != current &&
          (memoCache = {
            data: current.data.map(function (array) {
              return array.slice();
            }),
            index: 0
          })));
  }
  null == memoCache && (memoCache = { data: [], index: 0 });
  null === updateQueue &&
    ((updateQueue = createFunctionComponentUpdateQueue()),
    (currentlyRenderingFiber$1.updateQueue = updateQueue));
  updateQueue.memoCache = memoCache;
  updateQueue = memoCache.data[memoCache.index];
  if (void 0 === updateQueue)
    for (
      updateQueue = memoCache.data[memoCache.index] = Array(size), current = 0;
      current < size;
      current++
    )
      updateQueue[current] = REACT_MEMO_CACHE_SENTINEL;
  memoCache.index++;
  return updateQueue;
}
function basicStateReducer(state, action) {
  return "function" === typeof action ? action(state) : action;
}
function updateReducer(reducer) {
  var hook = updateWorkInProgressHook();
  return updateReducerImpl(hook, currentHook, reducer);
}
function updateReducerImpl(hook, current, reducer) {
  var queue = hook.queue;
  if (null === queue) throw Error(formatProdErrorMessage(311));
  queue.lastRenderedReducer = reducer;
  var baseQueue = hook.baseQueue,
    pendingQueue = queue.pending;
  if (null !== pendingQueue) {
    if (null !== baseQueue) {
      var baseFirst = baseQueue.next;
      baseQueue.next = pendingQueue.next;
      pendingQueue.next = baseFirst;
    }
    current.baseQueue = baseQueue = pendingQueue;
    queue.pending = null;
  }
  pendingQueue = hook.baseState;
  if (null === baseQueue) hook.memoizedState = pendingQueue;
  else {
    current = baseQueue.next;
    var newBaseQueueFirst = (baseFirst = null),
      newBaseQueueLast = null,
      update = current,
      didReadFromEntangledAsyncAction$54 = !1;
    do {
      var updateLane = update.lane & -536870913;
      if (
        updateLane !== update.lane
          ? (workInProgressRootRenderLanes & updateLane) === updateLane
          : (renderLanes & updateLane) === updateLane
      ) {
        var revertLane = update.revertLane;
        if (0 === revertLane)
          null !== newBaseQueueLast &&
            (newBaseQueueLast = newBaseQueueLast.next =
              {
                lane: 0,
                revertLane: 0,
                action: update.action,
                hasEagerState: update.hasEagerState,
                eagerState: update.eagerState,
                next: null
              }),
            updateLane === currentEntangledLane &&
              (didReadFromEntangledAsyncAction$54 = !0);
        else if ((renderLanes & revertLane) === revertLane) {
          update = update.next;
          revertLane === currentEntangledLane &&
            (didReadFromEntangledAsyncAction$54 = !0);
          continue;
        } else
          (updateLane = {
            lane: 0,
            revertLane: update.revertLane,
            action: update.action,
            hasEagerState: update.hasEagerState,
            eagerState: update.eagerState,
            next: null
          }),
            null === newBaseQueueLast
              ? ((newBaseQueueFirst = newBaseQueueLast = updateLane),
                (baseFirst = pendingQueue))
              : (newBaseQueueLast = newBaseQueueLast.next = updateLane),
            (currentlyRenderingFiber$1.lanes |= revertLane),
            (workInProgressRootSkippedLanes |= revertLane);
        updateLane = update.action;
        shouldDoubleInvokeUserFnsInHooksDEV &&
          reducer(pendingQueue, updateLane);
        pendingQueue = update.hasEagerState
          ? update.eagerState
          : reducer(pendingQueue, updateLane);
      } else
        (revertLane = {
          lane: updateLane,
          revertLane: update.revertLane,
          action: update.action,
          hasEagerState: update.hasEagerState,
          eagerState: update.eagerState,
          next: null
        }),
          null === newBaseQueueLast
            ? ((newBaseQueueFirst = newBaseQueueLast = revertLane),
              (baseFirst = pendingQueue))
            : (newBaseQueueLast = newBaseQueueLast.next = revertLane),
          (currentlyRenderingFiber$1.lanes |= updateLane),
          (workInProgressRootSkippedLanes |= updateLane);
      update = update.next;
    } while (null !== update && update !== current);
    null === newBaseQueueLast
      ? (baseFirst = pendingQueue)
      : (newBaseQueueLast.next = newBaseQueueFirst);
    if (
      !objectIs(pendingQueue, hook.memoizedState) &&
      ((didReceiveUpdate = !0),
      didReadFromEntangledAsyncAction$54 &&
        ((reducer = currentEntangledActionThenable), null !== reducer))
    )
      throw reducer;
    hook.memoizedState = pendingQueue;
    hook.baseState = baseFirst;
    hook.baseQueue = newBaseQueueLast;
    queue.lastRenderedState = pendingQueue;
  }
  null === baseQueue && (queue.lanes = 0);
  return [hook.memoizedState, queue.dispatch];
}
function rerenderReducer(reducer) {
  var hook = updateWorkInProgressHook(),
    queue = hook.queue;
  if (null === queue) throw Error(formatProdErrorMessage(311));
  queue.lastRenderedReducer = reducer;
  var dispatch = queue.dispatch,
    lastRenderPhaseUpdate = queue.pending,
    newState = hook.memoizedState;
  if (null !== lastRenderPhaseUpdate) {
    queue.pending = null;
    var update = (lastRenderPhaseUpdate = lastRenderPhaseUpdate.next);
    do (newState = reducer(newState, update.action)), (update = update.next);
    while (update !== lastRenderPhaseUpdate);
    objectIs(newState, hook.memoizedState) || (didReceiveUpdate = !0);
    hook.memoizedState = newState;
    null === hook.baseQueue && (hook.baseState = newState);
    queue.lastRenderedState = newState;
  }
  return [newState, dispatch];
}
function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
  var fiber = currentlyRenderingFiber$1,
    hook = updateWorkInProgressHook(),
    isHydrating$jscomp$0 = isHydrating;
  if (isHydrating$jscomp$0) {
    if (void 0 === getServerSnapshot) throw Error(formatProdErrorMessage(407));
    getServerSnapshot = getServerSnapshot();
  } else getServerSnapshot = getSnapshot();
  var snapshotChanged = !objectIs(
    (currentHook || hook).memoizedState,
    getServerSnapshot
  );
  snapshotChanged &&
    ((hook.memoizedState = getServerSnapshot), (didReceiveUpdate = !0));
  hook = hook.queue;
  updateEffect(subscribeToStore.bind(null, fiber, hook, subscribe), [
    subscribe
  ]);
  if (
    hook.getSnapshot !== getSnapshot ||
    snapshotChanged ||
    (null !== workInProgressHook && workInProgressHook.memoizedState.tag & 1)
  ) {
    fiber.flags |= 2048;
    pushEffect(
      9,
      updateStoreInstance.bind(
        null,
        fiber,
        hook,
        getServerSnapshot,
        getSnapshot
      ),
      { destroy: void 0 },
      null
    );
    if (null === workInProgressRoot) throw Error(formatProdErrorMessage(349));
    isHydrating$jscomp$0 ||
      0 !== (renderLanes & 60) ||
      pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
  }
  return getServerSnapshot;
}
function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
  fiber.flags |= 16384;
  fiber = { getSnapshot: getSnapshot, value: renderedSnapshot };
  getSnapshot = currentlyRenderingFiber$1.updateQueue;
  null === getSnapshot
    ? ((getSnapshot = createFunctionComponentUpdateQueue()),
      (currentlyRenderingFiber$1.updateQueue = getSnapshot),
      (getSnapshot.stores = [fiber]))
    : ((renderedSnapshot = getSnapshot.stores),
      null === renderedSnapshot
        ? (getSnapshot.stores = [fiber])
        : renderedSnapshot.push(fiber));
}
function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
  inst.value = nextSnapshot;
  inst.getSnapshot = getSnapshot;
  checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
}
function subscribeToStore(fiber, inst, subscribe) {
  return subscribe(function () {
    checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
  });
}
function checkIfSnapshotChanged(inst) {
  var latestGetSnapshot = inst.getSnapshot;
  inst = inst.value;
  try {
    var nextValue = latestGetSnapshot();
    return !objectIs(inst, nextValue);
  } catch (error) {
    return !0;
  }
}
function forceStoreRerender(fiber) {
  var root = enqueueConcurrentRenderForLane(fiber, 2);
  null !== root && scheduleUpdateOnFiber(root, fiber, 2);
}
function mountStateImpl(initialState) {
  var hook = mountWorkInProgressHook();
  if ("function" === typeof initialState) {
    var initialStateInitializer = initialState;
    initialState = initialStateInitializer();
    if (shouldDoubleInvokeUserFnsInHooksDEV) {
      setIsStrictModeForDevtools(!0);
      try {
        initialStateInitializer();
      } finally {
        setIsStrictModeForDevtools(!1);
      }
    }
  }
  hook.memoizedState = hook.baseState = initialState;
  hook.queue = {
    pending: null,
    lanes: 0,
    dispatch: null,
    lastRenderedReducer: basicStateReducer,
    lastRenderedState: initialState
  };
  return hook;
}
function updateOptimisticImpl(hook, current, passthrough, reducer) {
  hook.baseState = passthrough;
  return updateReducerImpl(
    hook,
    currentHook,
    "function" === typeof reducer ? reducer : basicStateReducer
  );
}
function dispatchActionState(
  fiber,
  actionQueue,
  setPendingState,
  setState,
  payload
) {
  if (isRenderPhaseUpdate(fiber)) throw Error(formatProdErrorMessage(485));
  fiber = actionQueue.action;
  if (null !== fiber) {
    var actionNode = {
      payload: payload,
      action: fiber,
      next: null,
      isTransition: !0,
      status: "pending",
      value: null,
      reason: null,
      listeners: [],
      then: function (listener) {
        actionNode.listeners.push(listener);
      }
    };
    null !== ReactSharedInternals.T
      ? setPendingState(!0)
      : (actionNode.isTransition = !1);
    setState(actionNode);
    setPendingState = actionQueue.pending;
    null === setPendingState
      ? ((actionNode.next = actionQueue.pending = actionNode),
        runActionStateAction(actionQueue, actionNode))
      : ((actionNode.next = setPendingState.next),
        (actionQueue.pending = setPendingState.next = actionNode));
  }
}
function runActionStateAction(actionQueue, node) {
  var action = node.action,
    payload = node.payload,
    prevState = actionQueue.state;
  if (node.isTransition) {
    var prevTransition = ReactSharedInternals.T,
      currentTransition = {};
    ReactSharedInternals.T = currentTransition;
    try {
      var returnValue = action(prevState, payload),
        onStartTransitionFinish = ReactSharedInternals.S;
      null !== onStartTransitionFinish &&
        onStartTransitionFinish(currentTransition, returnValue);
      handleActionReturnValue(actionQueue, node, returnValue);
    } catch (error) {
      onActionError(actionQueue, node, error);
    } finally {
      ReactSharedInternals.T = prevTransition;
    }
  } else
    try {
      (prevTransition = action(prevState, payload)),
        handleActionReturnValue(actionQueue, node, prevTransition);
    } catch (error$60) {
      onActionError(actionQueue, node, error$60);
    }
}
function handleActionReturnValue(actionQueue, node, returnValue) {
  null !== returnValue &&
  "object" === typeof returnValue &&
  "function" === typeof returnValue.then
    ? returnValue.then(
        function (nextState) {
          onActionSuccess(actionQueue, node, nextState);
        },
        function (error) {
          return onActionError(actionQueue, node, error);
        }
      )
    : onActionSuccess(actionQueue, node, returnValue);
}
function onActionSuccess(actionQueue, actionNode, nextState) {
  actionNode.status = "fulfilled";
  actionNode.value = nextState;
  notifyActionListeners(actionNode);
  actionQueue.state = nextState;
  actionNode = actionQueue.pending;
  null !== actionNode &&
    ((nextState = actionNode.next),
    nextState === actionNode
      ? (actionQueue.pending = null)
      : ((nextState = nextState.next),
        (actionNode.next = nextState),
        runActionStateAction(actionQueue, nextState)));
}
function onActionError(actionQueue, actionNode, error) {
  var last = actionQueue.pending;
  actionQueue.pending = null;
  if (null !== last) {
    last = last.next;
    do
      (actionNode.status = "rejected"),
        (actionNode.reason = error),
        notifyActionListeners(actionNode),
        (actionNode = actionNode.next);
    while (actionNode !== last);
  }
  actionQueue.action = null;
}
function notifyActionListeners(actionNode) {
  actionNode = actionNode.listeners;
  for (var i = 0; i < actionNode.length; i++) (0, actionNode[i])();
}
function actionStateReducer(oldState, newState) {
  return newState;
}
function mountActionState(action, initialStateProp) {
  if (isHydrating) {
    var ssrFormState = workInProgressRoot.formState;
    if (null !== ssrFormState) {
      a: {
        var JSCompiler_inline_result = currentlyRenderingFiber$1;
        if (isHydrating) {
          if (nextHydratableInstance) {
            b: {
              var JSCompiler_inline_result$jscomp$0 = nextHydratableInstance;
              for (
                var inRootOrSingleton = rootOrSingletonContext;
                8 !== JSCompiler_inline_result$jscomp$0.nodeType;

              ) {
                if (!inRootOrSingleton) {
                  JSCompiler_inline_result$jscomp$0 = null;
                  break b;
                }
                JSCompiler_inline_result$jscomp$0 = getNextHydratable(
                  JSCompiler_inline_result$jscomp$0.nextSibling
                );
                if (null === JSCompiler_inline_result$jscomp$0) {
                  JSCompiler_inline_result$jscomp$0 = null;
                  break b;
                }
              }
              inRootOrSingleton = JSCompiler_inline_result$jscomp$0.data;
              JSCompiler_inline_result$jscomp$0 =
                "F!" === inRootOrSingleton || "F" === inRootOrSingleton
                  ? JSCompiler_inline_result$jscomp$0
                  : null;
            }
            if (JSCompiler_inline_result$jscomp$0) {
              nextHydratableInstance = getNextHydratable(
                JSCompiler_inline_result$jscomp$0.nextSibling
              );
              JSCompiler_inline_result =
                "F!" === JSCompiler_inline_result$jscomp$0.data;
              break a;
            }
          }
          throwOnHydrationMismatch(JSCompiler_inline_result);
        }
        JSCompiler_inline_result = !1;
      }
      JSCompiler_inline_result && (initialStateProp = ssrFormState[0]);
    }
  }
  ssrFormState = mountWorkInProgressHook();
  ssrFormState.memoizedState = ssrFormState.baseState = initialStateProp;
  JSCompiler_inline_result = {
    pending: null,
    lanes: 0,
    dispatch: null,
    lastRenderedReducer: actionStateReducer,
    lastRenderedState: initialStateProp
  };
  ssrFormState.queue = JSCompiler_inline_result;
  ssrFormState = dispatchSetState.bind(
    null,
    currentlyRenderingFiber$1,
    JSCompiler_inline_result
  );
  JSCompiler_inline_result.dispatch = ssrFormState;
  JSCompiler_inline_result = mountStateImpl(!1);
  inRootOrSingleton = dispatchOptimisticSetState.bind(
    null,
    currentlyRenderingFiber$1,
    !1,
    JSCompiler_inline_result.queue
  );
  JSCompiler_inline_result = mountWorkInProgressHook();
  JSCompiler_inline_result$jscomp$0 = {
    state: initialStateProp,
    dispatch: null,
    action: action,
    pending: null
  };
  JSCompiler_inline_result.queue = JSCompiler_inline_result$jscomp$0;
  ssrFormState = dispatchActionState.bind(
    null,
    currentlyRenderingFiber$1,
    JSCompiler_inline_result$jscomp$0,
    inRootOrSingleton,
    ssrFormState
  );
  JSCompiler_inline_result$jscomp$0.dispatch = ssrFormState;
  JSCompiler_inline_result.memoizedState = action;
  return [initialStateProp, ssrFormState, !1];
}
function updateActionState(action) {
  var stateHook = updateWorkInProgressHook();
  return updateActionStateImpl(stateHook, currentHook, action);
}
function updateActionStateImpl(stateHook, currentStateHook, action) {
  currentStateHook = updateReducerImpl(
    stateHook,
    currentStateHook,
    actionStateReducer
  )[0];
  stateHook = updateReducer(basicStateReducer)[0];
  currentStateHook =
    "object" === typeof currentStateHook &&
    null !== currentStateHook &&
    "function" === typeof currentStateHook.then
      ? useThenable(currentStateHook)
      : currentStateHook;
  var actionQueueHook = updateWorkInProgressHook(),
    actionQueue = actionQueueHook.queue,
    dispatch = actionQueue.dispatch;
  action !== actionQueueHook.memoizedState &&
    ((currentlyRenderingFiber$1.flags |= 2048),
    pushEffect(
      9,
      actionStateActionEffect.bind(null, actionQueue, action),
      { destroy: void 0 },
      null
    ));
  return [currentStateHook, dispatch, stateHook];
}
function actionStateActionEffect(actionQueue, action) {
  actionQueue.action = action;
}
function rerenderActionState(action) {
  var stateHook = updateWorkInProgressHook(),
    currentStateHook = currentHook;
  if (null !== currentStateHook)
    return updateActionStateImpl(stateHook, currentStateHook, action);
  updateWorkInProgressHook();
  stateHook = stateHook.memoizedState;
  currentStateHook = updateWorkInProgressHook();
  var dispatch = currentStateHook.queue.dispatch;
  currentStateHook.memoizedState = action;
  return [stateHook, dispatch, !1];
}
function pushEffect(tag, create, inst, deps) {
  tag = { tag: tag, create: create, inst: inst, deps: deps, next: null };
  create = currentlyRenderingFiber$1.updateQueue;
  null === create &&
    ((create = createFunctionComponentUpdateQueue()),
    (currentlyRenderingFiber$1.updateQueue = create));
  inst = create.lastEffect;
  null === inst
    ? (create.lastEffect = tag.next = tag)
    : ((deps = inst.next),
      (inst.next = tag),
      (tag.next = deps),
      (create.lastEffect = tag));
  return tag;
}
function updateRef() {
  return updateWorkInProgressHook().memoizedState;
}
function mountEffectImpl(fiberFlags, hookFlags, create, deps) {
  var hook = mountWorkInProgressHook();
  currentlyRenderingFiber$1.flags |= fiberFlags;
  hook.memoizedState = pushEffect(
    1 | hookFlags,
    create,
    { destroy: void 0 },
    void 0 === deps ? null : deps
  );
}
function updateEffectImpl(fiberFlags, hookFlags, create, deps) {
  var hook = updateWorkInProgressHook();
  deps = void 0 === deps ? null : deps;
  var inst = hook.memoizedState.inst;
  null !== currentHook &&
  null !== deps &&
  areHookInputsEqual(deps, currentHook.memoizedState.deps)
    ? (hook.memoizedState = pushEffect(hookFlags, create, inst, deps))
    : ((currentlyRenderingFiber$1.flags |= fiberFlags),
      (hook.memoizedState = pushEffect(1 | hookFlags, create, inst, deps)));
}
function mountEffect(create, deps) {
  mountEffectImpl(8390656, 8, create, deps);
}
function updateEffect(create, deps) {
  updateEffectImpl(2048, 8, create, deps);
}
function updateInsertionEffect(create, deps) {
  return updateEffectImpl(4, 2, create, deps);
}
function updateLayoutEffect(create, deps) {
  return updateEffectImpl(4, 4, create, deps);
}
function imperativeHandleEffect(create, ref) {
  if ("function" === typeof ref) {
    create = create();
    var refCleanup = ref(create);
    return function () {
      "function" === typeof refCleanup ? refCleanup() : ref(null);
    };
  }
  if (null !== ref && void 0 !== ref)
    return (
      (create = create()),
      (ref.current = create),
      function () {
        ref.current = null;
      }
    );
}
function updateImperativeHandle(ref, create, deps) {
  deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
  updateEffectImpl(4, 4, imperativeHandleEffect.bind(null, create, ref), deps);
}
function mountDebugValue() {}
function updateCallback(callback, deps) {
  var hook = updateWorkInProgressHook();
  deps = void 0 === deps ? null : deps;
  var prevState = hook.memoizedState;
  if (null !== deps && areHookInputsEqual(deps, prevState[1]))
    return prevState[0];
  hook.memoizedState = [callback, deps];
  return callback;
}
function updateMemo(nextCreate, deps) {
  var hook = updateWorkInProgressHook();
  deps = void 0 === deps ? null : deps;
  var prevState = hook.memoizedState;
  if (null !== deps && areHookInputsEqual(deps, prevState[1]))
    return prevState[0];
  prevState = nextCreate();
  if (shouldDoubleInvokeUserFnsInHooksDEV) {
    setIsStrictModeForDevtools(!0);
    try {
      nextCreate();
    } finally {
      setIsStrictModeForDevtools(!1);
    }
  }
  hook.memoizedState = [prevState, deps];
  return prevState;
}
function mountDeferredValueImpl(hook, value, initialValue) {
  if (void 0 === initialValue || 0 !== (renderLanes & 1073741824))
    return (hook.memoizedState = value);
  hook.memoizedState = initialValue;
  hook = requestDeferredLane();
  currentlyRenderingFiber$1.lanes |= hook;
  workInProgressRootSkippedLanes |= hook;
  return initialValue;
}
function updateDeferredValueImpl(hook, prevValue, value, initialValue) {
  if (objectIs(value, prevValue)) return value;
  if (null !== currentTreeHiddenStackCursor.current)
    return (
      (hook = mountDeferredValueImpl(hook, value, initialValue)),
      objectIs(hook, prevValue) || (didReceiveUpdate = !0),
      hook
    );
  if (0 === (renderLanes & 42))
    return (didReceiveUpdate = !0), (hook.memoizedState = value);
  hook = requestDeferredLane();
  currentlyRenderingFiber$1.lanes |= hook;
  workInProgressRootSkippedLanes |= hook;
  return prevValue;
}
function startTransition(fiber, queue, pendingState, finishedState, callback) {
  var previousPriority = ReactDOMSharedInternals.p;
  ReactDOMSharedInternals.p =
    0 !== previousPriority && 8 > previousPriority ? previousPriority : 8;
  var prevTransition = ReactSharedInternals.T,
    currentTransition = {};
  ReactSharedInternals.T = currentTransition;
  dispatchOptimisticSetState(fiber, !1, queue, pendingState);
  try {
    var returnValue = callback(),
      onStartTransitionFinish = ReactSharedInternals.S;
    null !== onStartTransitionFinish &&
      onStartTransitionFinish(currentTransition, returnValue);
    if (
      null !== returnValue &&
      "object" === typeof returnValue &&
      "function" === typeof returnValue.then
    ) {
      var thenableForFinishedState = chainThenableValue(
        returnValue,
        finishedState
      );
      dispatchSetStateInternal(
        fiber,
        queue,
        thenableForFinishedState,
        requestUpdateLane(fiber)
      );
    } else
      dispatchSetStateInternal(
        fiber,
        queue,
        finishedState,
        requestUpdateLane(fiber)
      );
  } catch (error) {
    dispatchSetStateInternal(
      fiber,
      queue,
      { then: function () {}, status: "rejected", reason: error },
      requestUpdateLane()
    );
  } finally {
    (ReactDOMSharedInternals.p = previousPriority),
      (ReactSharedInternals.T = prevTransition);
  }
}
function noop$2() {}
function startHostTransition(formFiber, pendingState, action, formData) {
  if (5 !== formFiber.tag) throw Error(formatProdErrorMessage(476));
  var queue = ensureFormComponentIsStateful(formFiber).queue;
  startTransition(
    formFiber,
    queue,
    pendingState,
    sharedNotPendingObject,
    null === action
      ? noop$2
      : function () {
          requestFormReset$1(formFiber);
          return action(formData);
        }
  );
}
function ensureFormComponentIsStateful(formFiber) {
  var existingStateHook = formFiber.memoizedState;
  if (null !== existingStateHook) return existingStateHook;
  existingStateHook = {
    memoizedState: sharedNotPendingObject,
    baseState: sharedNotPendingObject,
    baseQueue: null,
    queue: {
      pending: null,
      lanes: 0,
      dispatch: null,
      lastRenderedReducer: basicStateReducer,
      lastRenderedState: sharedNotPendingObject
    },
    next: null
  };
  var initialResetState = {};
  existingStateHook.next = {
    memoizedState: initialResetState,
    baseState: initialResetState,
    baseQueue: null,
    queue: {
      pending: null,
      lanes: 0,
      dispatch: null,
      lastRenderedReducer: basicStateReducer,
      lastRenderedState: initialResetState
    },
    next: null
  };
  formFiber.memoizedState = existingStateHook;
  formFiber = formFiber.alternate;
  null !== formFiber && (formFiber.memoizedState = existingStateHook);
  return existingStateHook;
}
function requestFormReset$1(formFiber) {
  var resetStateQueue = ensureFormComponentIsStateful(formFiber).next.queue;
  dispatchSetStateInternal(formFiber, resetStateQueue, {}, requestUpdateLane());
}
function useHostTransitionStatus() {
  return readContext(HostTransitionContext);
}
function updateId() {
  return updateWorkInProgressHook().memoizedState;
}
function updateRefresh() {
  return updateWorkInProgressHook().memoizedState;
}
function refreshCache(fiber) {
  for (var provider = fiber.return; null !== provider; ) {
    switch (provider.tag) {
      case 24:
      case 3:
        var lane = requestUpdateLane();
        fiber = createUpdate(lane);
        var root$63 = enqueueUpdate(provider, fiber, lane);
        null !== root$63 &&
          (scheduleUpdateOnFiber(root$63, provider, lane),
          entangleTransitions(root$63, provider, lane));
        provider = { cache: createCache() };
        fiber.payload = provider;
        return;
    }
    provider = provider.return;
  }
}
function dispatchReducerAction(fiber, queue, action) {
  var lane = requestUpdateLane();
  action = {
    lane: lane,
    revertLane: 0,
    action: action,
    hasEagerState: !1,
    eagerState: null,
    next: null
  };
  isRenderPhaseUpdate(fiber)
    ? enqueueRenderPhaseUpdate(queue, action)
    : ((action = enqueueConcurrentHookUpdate(fiber, queue, action, lane)),
      null !== action &&
        (scheduleUpdateOnFiber(action, fiber, lane),
        entangleTransitionUpdate(action, queue, lane)));
}
function dispatchSetState(fiber, queue, action) {
  var lane = requestUpdateLane();
  dispatchSetStateInternal(fiber, queue, action, lane);
}
function dispatchSetStateInternal(fiber, queue, action, lane) {
  var update = {
    lane: lane,
    revertLane: 0,
    action: action,
    hasEagerState: !1,
    eagerState: null,
    next: null
  };
  if (isRenderPhaseUpdate(fiber)) enqueueRenderPhaseUpdate(queue, update);
  else {
    var alternate = fiber.alternate;
    if (
      0 === fiber.lanes &&
      (null === alternate || 0 === alternate.lanes) &&
      ((alternate = queue.lastRenderedReducer), null !== alternate)
    )
      try {
        var currentState = queue.lastRenderedState,
          eagerState = alternate(currentState, action);
        update.hasEagerState = !0;
        update.eagerState = eagerState;
        if (objectIs(eagerState, currentState))
          return (
            enqueueUpdate$1(fiber, queue, update, 0),
            null === workInProgressRoot && finishQueueingConcurrentUpdates(),
            !1
          );
      } catch (error) {
      } finally {
      }
    action = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
    if (null !== action)
      return (
        scheduleUpdateOnFiber(action, fiber, lane),
        entangleTransitionUpdate(action, queue, lane),
        !0
      );
  }
  return !1;
}
function dispatchOptimisticSetState(fiber, throwIfDuringRender, queue, action) {
  action = {
    lane: 2,
    revertLane: requestTransitionLane(),
    action: action,
    hasEagerState: !1,
    eagerState: null,
    next: null
  };
  if (isRenderPhaseUpdate(fiber)) {
    if (throwIfDuringRender) throw Error(formatProdErrorMessage(479));
  } else
    (throwIfDuringRender = enqueueConcurrentHookUpdate(
      fiber,
      queue,
      action,
      2
    )),
      null !== throwIfDuringRender &&
        scheduleUpdateOnFiber(throwIfDuringRender, fiber, 2);
}
function isRenderPhaseUpdate(fiber) {
  var alternate = fiber.alternate;
  return (
    fiber === currentlyRenderingFiber$1 ||
    (null !== alternate && alternate === currentlyRenderingFiber$1)
  );
}
function enqueueRenderPhaseUpdate(queue, update) {
  didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate =
    !0;
  var pending = queue.pending;
  null === pending
    ? (update.next = update)
    : ((update.next = pending.next), (pending.next = update));
  queue.pending = update;
}
function entangleTransitionUpdate(root, queue, lane) {
  if (0 !== (lane & 4194176)) {
    var queueLanes = queue.lanes;
    queueLanes &= root.pendingLanes;
    lane |= queueLanes;
    queue.lanes = lane;
    markRootEntangled(root, lane);
  }
}
var ContextOnlyDispatcher = {
  readContext: readContext,
  use: use,
  useCallback: throwInvalidHookError,
  useContext: throwInvalidHookError,
  useEffect: throwInvalidHookError,
  useImperativeHandle: throwInvalidHookError,
  useLayoutEffect: throwInvalidHookError,
  useInsertionEffect: throwInvalidHookError,
  useMemo: throwInvalidHookError,
  useReducer: throwInvalidHookError,
  useRef: throwInvalidHookError,
  useState: throwInvalidHookError,
  useDebugValue: throwInvalidHookError,
  useDeferredValue: throwInvalidHookError,
  useTransition: throwInvalidHookError,
  useSyncExternalStore: throwInvalidHookError,
  useId: throwInvalidHookError
};
ContextOnlyDispatcher.useCacheRefresh = throwInvalidHookError;
ContextOnlyDispatcher.useMemoCache = throwInvalidHookError;
ContextOnlyDispatcher.useHostTransitionStatus = throwInvalidHookError;
ContextOnlyDispatcher.useFormState = throwInvalidHookError;
ContextOnlyDispatcher.useActionState = throwInvalidHookError;
ContextOnlyDispatcher.useOptimistic = throwInvalidHookError;
var HooksDispatcherOnMount = {
  readContext: readContext,
  use: use,
  useCallback: function (callback, deps) {
    mountWorkInProgressHook().memoizedState = [
      callback,
      void 0 === deps ? null : deps
    ];
    return callback;
  },
  useContext: readContext,
  useEffect: mountEffect,
  useImperativeHandle: function (ref, create, deps) {
    deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
    mountEffectImpl(
      4194308,
      4,
      imperativeHandleEffect.bind(null, create, ref),
      deps
    );
  },
  useLayoutEffect: function (create, deps) {
    return mountEffectImpl(4194308, 4, create, deps);
  },
  useInsertionEffect: function (create, deps) {
    mountEffectImpl(4, 2, create, deps);
  },
  useMemo: function (nextCreate, deps) {
    var hook = mountWorkInProgressHook();
    deps = void 0 === deps ? null : deps;
    var nextValue = nextCreate();
    if (shouldDoubleInvokeUserFnsInHooksDEV) {
      setIsStrictModeForDevtools(!0);
      try {
        nextCreate();
      } finally {
        setIsStrictModeForDevtools(!1);
      }
    }
    hook.memoizedState = [nextValue, deps];
    return nextValue;
  },
  useReducer: function (reducer, initialArg, init) {
    var hook = mountWorkInProgressHook();
    if (void 0 !== init) {
      var initialState = init(initialArg);
      if (shouldDoubleInvokeUserFnsInHooksDEV) {
        setIsStrictModeForDevtools(!0);
        try {
          init(initialArg);
        } finally {
          setIsStrictModeForDevtools(!1);
        }
      }
    } else initialState = initialArg;
    hook.memoizedState = hook.baseState = initialState;
    reducer = {
      pending: null,
      lanes: 0,
      dispatch: null,
      lastRenderedReducer: reducer,
      lastRenderedState: initialState
    };
    hook.queue = reducer;
    reducer = reducer.dispatch = dispatchReducerAction.bind(
      null,
      currentlyRenderingFiber$1,
      reducer
    );
    return [hook.memoizedState, reducer];
  },
  useRef: function (initialValue) {
    var hook = mountWorkInProgressHook();
    initialValue = { current: initialValue };
    return (hook.memoizedState = initialValue);
  },
  useState: function (initialState) {
    initialState = mountStateImpl(initialState);
    var queue = initialState.queue,
      dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue);
    queue.dispatch = dispatch;
    return [initialState.memoizedState, dispatch];
  },
  useDebugValue: mountDebugValue,
  useDeferredValue: function (value, initialValue) {
    var hook = mountWorkInProgressHook();
    return mountDeferredValueImpl(hook, value, initialValue);
  },
  useTransition: function () {
    var stateHook = mountStateImpl(!1);
    stateHook = startTransition.bind(
      null,
      currentlyRenderingFiber$1,
      stateHook.queue,
      !0,
      !1
    );
    mountWorkInProgressHook().memoizedState = stateHook;
    return [!1, stateHook];
  },
  useSyncExternalStore: function (subscribe, getSnapshot, getServerSnapshot) {
    var fiber = currentlyRenderingFiber$1,
      hook = mountWorkInProgressHook();
    if (isHydrating) {
      if (void 0 === getServerSnapshot)
        throw Error(formatProdErrorMessage(407));
      getServerSnapshot = getServerSnapshot();
    } else {
      getServerSnapshot = getSnapshot();
      if (null === workInProgressRoot) throw Error(formatProdErrorMessage(349));
      0 !== (workInProgressRootRenderLanes & 60) ||
        pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
    }
    hook.memoizedState = getServerSnapshot;
    var inst = { value: getServerSnapshot, getSnapshot: getSnapshot };
    hook.queue = inst;
    mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [
      subscribe
    ]);
    fiber.flags |= 2048;
    pushEffect(
      9,
      updateStoreInstance.bind(
        null,
        fiber,
        inst,
        getServerSnapshot,
        getSnapshot
      ),
      { destroy: void 0 },
      null
    );
    return getServerSnapshot;
  },
  useId: function () {
    var hook = mountWorkInProgressHook(),
      identifierPrefix = workInProgressRoot.identifierPrefix;
    if (isHydrating) {
      var JSCompiler_inline_result = treeContextOverflow;
      var idWithLeadingBit = treeContextId;
      JSCompiler_inline_result =
        (
          idWithLeadingBit & ~(1 << (32 - clz32(idWithLeadingBit) - 1))
        ).toString(32) + JSCompiler_inline_result;
      identifierPrefix =
        ":" + identifierPrefix + "R" + JSCompiler_inline_result;
      JSCompiler_inline_result = localIdCounter++;
      0 < JSCompiler_inline_result &&
        (identifierPrefix += "H" + JSCompiler_inline_result.toString(32));
      identifierPrefix += ":";
    } else
      (JSCompiler_inline_result = globalClientIdCounter++),
        (identifierPrefix =
          ":" +
          identifierPrefix +
          "r" +
          JSCompiler_inline_result.toString(32) +
          ":");
    return (hook.memoizedState = identifierPrefix);
  },
  useCacheRefresh: function () {
    return (mountWorkInProgressHook().memoizedState = refreshCache.bind(
      null,
      currentlyRenderingFiber$1
    ));
  }
};
HooksDispatcherOnMount.useMemoCache = useMemoCache;
HooksDispatcherOnMount.useHostTransitionStatus = useHostTransitionStatus;
HooksDispatcherOnMount.useFormState = mountActionState;
HooksDispatcherOnMount.useActionState = mountActionState;
HooksDispatcherOnMount.useOptimistic = function (passthrough) {
  var hook = mountWorkInProgressHook();
  hook.memoizedState = hook.baseState = passthrough;
  var queue = {
    pending: null,
    lanes: 0,
    dispatch: null,
    lastRenderedReducer: null,
    lastRenderedState: null
  };
  hook.queue = queue;
  hook = dispatchOptimisticSetState.bind(
    null,
    currentlyRenderingFiber$1,
    !0,
    queue
  );
  queue.dispatch = hook;
  return [passthrough, hook];
};
var HooksDispatcherOnUpdate = {
  readContext: readContext,
  use: use,
  useCallback: updateCallback,
  useContext: readContext,
  useEffect: updateEffect,
  useImperativeHandle: updateImperativeHandle,
  useInsertionEffect: updateInsertionEffect,
  useLayoutEffect: updateLayoutEffect,
  useMemo: updateMemo,
  useReducer: updateReducer,
  useRef: updateRef,
  useState: function () {
    return updateReducer(basicStateReducer);
  },
  useDebugValue: mountDebugValue,
  useDeferredValue: function (value, initialValue) {
    var hook = updateWorkInProgressHook();
    return updateDeferredValueImpl(
      hook,
      currentHook.memoizedState,
      value,
      initialValue
    );
  },
  useTransition: function () {
    var booleanOrThenable = updateReducer(basicStateReducer)[0],
      start = updateWorkInProgressHook().memoizedState;
    return [
      "boolean" === typeof booleanOrThenable
        ? booleanOrThenable
        : useThenable(booleanOrThenable),
      start
    ];
  },
  useSyncExternalStore: updateSyncExternalStore,
  useId: updateId
};
HooksDispatcherOnUpdate.useCacheRefresh = updateRefresh;
HooksDispatcherOnUpdate.useMemoCache = useMemoCache;
HooksDispatcherOnUpdate.useHostTransitionStatus = useHostTransitionStatus;
HooksDispatcherOnUpdate.useFormState = updateActionState;
HooksDispatcherOnUpdate.useActionState = updateActionState;
HooksDispatcherOnUpdate.useOptimistic = function (passthrough, reducer) {
  var hook = updateWorkInProgressHook();
  return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
};
var HooksDispatcherOnRerender = {
  readContext: readContext,
  use: use,
  useCallback: updateCallback,
  useContext: readContext,
  useEffect: updateEffect,
  useImperativeHandle: updateImperativeHandle,
  useInsertionEffect: updateInsertionEffect,
  useLayoutEffect: updateLayoutEffect,
  useMemo: updateMemo,
  useReducer: rerenderReducer,
  useRef: updateRef,
  useState: function () {
    return rerenderReducer(basicStateReducer);
  },
  useDebugValue: mountDebugValue,
  useDeferredValue: function (value, initialValue) {
    var hook = updateWorkInProgressHook();
    return null === currentHook
      ? mountDeferredValueImpl(hook, value, initialValue)
      : updateDeferredValueImpl(
          hook,
          currentHook.memoizedState,
          value,
          initialValue
        );
  },
  useTransition: function () {
    var booleanOrThenable = rerenderReducer(basicStateReducer)[0],
      start = updateWorkInProgressHook().memoizedState;
    return [
      "boolean" === typeof booleanOrThenable
        ? booleanOrThenable
        : useThenable(booleanOrThenable),
      start
    ];
  },
  useSyncExternalStore: updateSyncExternalStore,
  useId: updateId
};
HooksDispatcherOnRerender.useCacheRefresh = updateRefresh;
HooksDispatcherOnRerender.useMemoCache = useMemoCache;
HooksDispatcherOnRerender.useHostTransitionStatus = useHostTransitionStatus;
HooksDispatcherOnRerender.useFormState = rerenderActionState;
HooksDispatcherOnRerender.useActionState = rerenderActionState;
HooksDispatcherOnRerender.useOptimistic = function (passthrough, reducer) {
  var hook = updateWorkInProgressHook();
  if (null !== currentHook)
    return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
  hook.baseState = passthrough;
  return [passthrough, hook.queue.dispatch];
};
function applyDerivedStateFromProps(
  workInProgress,
  ctor,
  getDerivedStateFromProps,
  nextProps
) {
  ctor = workInProgress.memoizedState;
  getDerivedStateFromProps = getDerivedStateFromProps(nextProps, ctor);
  getDerivedStateFromProps =
    null === getDerivedStateFromProps || void 0 === getDerivedStateFromProps
      ? ctor
      : assign({}, ctor, getDerivedStateFromProps);
  workInProgress.memoizedState = getDerivedStateFromProps;
  0 === workInProgress.lanes &&
    (workInProgress.updateQueue.baseState = getDerivedStateFromProps);
}
var classComponentUpdater = {
  isMounted: function (component) {
    return (component = component._reactInternals)
      ? getNearestMountedFiber(component) === component
      : !1;
  },
  enqueueSetState: function (inst, payload, callback) {
    inst = inst._reactInternals;
    var lane = requestUpdateLane(),
      update = createUpdate(lane);
    update.payload = payload;
    void 0 !== callback && null !== callback && (update.callback = callback);
    payload = enqueueUpdate(inst, update, lane);
    null !== payload &&
      (scheduleUpdateOnFiber(payload, inst, lane),
      entangleTransitions(payload, inst, lane));
  },
  enqueueReplaceState: function (inst, payload, callback) {
    inst = inst._reactInternals;
    var lane = requestUpdateLane(),
      update = createUpdate(lane);
    update.tag = 1;
    update.payload = payload;
    void 0 !== callback && null !== callback && (update.callback = callback);
    payload = enqueueUpdate(inst, update, lane);
    null !== payload &&
      (scheduleUpdateOnFiber(payload, inst, lane),
      entangleTransitions(payload, inst, lane));
  },
  enqueueForceUpdate: function (inst, callback) {
    inst = inst._reactInternals;
    var lane = requestUpdateLane(),
      update = createUpdate(lane);
    update.tag = 2;
    void 0 !== callback && null !== callback && (update.callback = callback);
    callback = enqueueUpdate(inst, update, lane);
    null !== callback &&
      (scheduleUpdateOnFiber(callback, inst, lane),
      entangleTransitions(callback, inst, lane));
  }
};
function checkShouldComponentUpdate(
  workInProgress,
  ctor,
  oldProps,
  newProps,
  oldState,
  newState,
  nextContext
) {
  workInProgress = workInProgress.stateNode;
  return "function" === typeof workInProgress.shouldComponentUpdate
    ? workInProgress.shouldComponentUpdate(newProps, newState, nextContext)
    : ctor.prototype && ctor.prototype.isPureReactComponent
      ? !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState)
      : !0;
}
function callComponentWillReceiveProps(
  workInProgress,
  instance,
  newProps,
  nextContext
) {
  workInProgress = instance.state;
  "function" === typeof instance.componentWillReceiveProps &&
    instance.componentWillReceiveProps(newProps, nextContext);
  "function" === typeof instance.UNSAFE_componentWillReceiveProps &&
    instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
  instance.state !== workInProgress &&
    classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
}
function resolveClassComponentProps(Component, baseProps) {
  var newProps = baseProps;
  if ("ref" in baseProps) {
    newProps = {};
    for (var propName in baseProps)
      "ref" !== propName && (newProps[propName] = baseProps[propName]);
  }
  if ((Component = Component.defaultProps)) {
    newProps === baseProps && (newProps = assign({}, newProps));
    for (var propName$67 in Component)
      void 0 === newProps[propName$67] &&
        (newProps[propName$67] = Component[propName$67]);
  }
  return newProps;
}
var reportGlobalError =
  "function" === typeof reportError
    ? reportError
    : function (error) {
        if (
          "object" === typeof window &&
          "function" === typeof window.ErrorEvent
        ) {
          var event = new window.ErrorEvent("error", {
            bubbles: !0,
            cancelable: !0,
            message:
              "object" === typeof error &&
              null !== error &&
              "string" === typeof error.message
                ? String(error.message)
                : String(error),
            error: error
          });
          if (!window.dispatchEvent(event)) return;
        } else if (
          "object" === typeof process &&
          "function" === typeof process.emit
        ) {
          process.emit("uncaughtException", error);
          return;
        }
        console.error(error);
      };
function defaultOnUncaughtError(error) {
  reportGlobalError(error);
}
function defaultOnCaughtError(error) {
  console.error(error);
}
function defaultOnRecoverableError(error) {
  reportGlobalError(error);
}
function logUncaughtError(root, errorInfo) {
  try {
    var onUncaughtError = root.onUncaughtError;
    onUncaughtError(errorInfo.value, { componentStack: errorInfo.stack });
  } catch (e$68) {
    setTimeout(function () {
      throw e$68;
    });
  }
}
function logCaughtError(root, boundary, errorInfo) {
  try {
    var onCaughtError = root.onCaughtError;
    onCaughtError(errorInfo.value, {
      componentStack: errorInfo.stack,
      errorBoundary: 1 === boundary.tag ? boundary.stateNode : null
    });
  } catch (e$69) {
    setTimeout(function () {
      throw e$69;
    });
  }
}
function createRootErrorUpdate(root, errorInfo, lane) {
  lane = createUpdate(lane);
  lane.tag = 3;
  lane.payload = { element: null };
  lane.callback = function () {
    logUncaughtError(root, errorInfo);
  };
  return lane;
}
function createClassErrorUpdate(lane) {
  lane = createUpdate(lane);
  lane.tag = 3;
  return lane;
}
function initializeClassErrorUpdate(update, root, fiber, errorInfo) {
  var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
  if ("function" === typeof getDerivedStateFromError) {
    var error = errorInfo.value;
    update.payload = function () {
      return getDerivedStateFromError(error);
    };
    update.callback = function () {
      logCaughtError(root, fiber, errorInfo);
    };
  }
  var inst = fiber.stateNode;
  null !== inst &&
    "function" === typeof inst.componentDidCatch &&
    (update.callback = function () {
      logCaughtError(root, fiber, errorInfo);
      "function" !== typeof getDerivedStateFromError &&
        (null === legacyErrorBoundariesThatAlreadyFailed
          ? (legacyErrorBoundariesThatAlreadyFailed = new Set([this]))
          : legacyErrorBoundariesThatAlreadyFailed.add(this));
      var stack = errorInfo.stack;
      this.componentDidCatch(errorInfo.value, {
        componentStack: null !== stack ? stack : ""
      });
    });
}
function throwException(
  root,
  returnFiber,
  sourceFiber,
  value,
  rootRenderLanes
) {
  sourceFiber.flags |= 32768;
  if (
    null !== value &&
    "object" === typeof value &&
    "function" === typeof value.then
  ) {
    returnFiber = sourceFiber.alternate;
    null !== returnFiber &&
      propagateParentContextChanges(
        returnFiber,
        sourceFiber,
        rootRenderLanes,
        !0
      );
    sourceFiber = suspenseHandlerStackCursor.current;
    if (null !== sourceFiber) {
      switch (sourceFiber.tag) {
        case 13:
          return (
            null === shellBoundary
              ? renderDidSuspendDelayIfPossible()
              : null === sourceFiber.alternate &&
                0 === workInProgressRootExitStatus &&
                (workInProgressRootExitStatus = 3),
            (sourceFiber.flags &= -257),
            (sourceFiber.flags |= 65536),
            (sourceFiber.lanes = rootRenderLanes),
            value === noopSuspenseyCommitThenable
              ? (sourceFiber.flags |= 16384)
              : ((returnFiber = sourceFiber.updateQueue),
                null === returnFiber
                  ? (sourceFiber.updateQueue = new Set([value]))
                  : returnFiber.add(value),
                attachPingListener(root, value, rootRenderLanes)),
            !1
          );
        case 22:
          return (
            (sourceFiber.flags |= 65536),
            value === noopSuspenseyCommitThenable
              ? (sourceFiber.flags |= 16384)
              : ((returnFiber = sourceFiber.updateQueue),
                null === returnFiber
                  ? ((returnFiber = {
                      transitions: null,
                      markerInstances: null,
                      retryQueue: new Set([value])
                    }),
                    (sourceFiber.updateQueue = returnFiber))
                  : ((sourceFiber = returnFiber.retryQueue),
                    null === sourceFiber
                      ? (returnFiber.retryQueue = new Set([value]))
                      : sourceFiber.add(value)),
                attachPingListener(root, value, rootRenderLanes)),
            !1
          );
      }
      throw Error(formatProdErrorMessage(435, sourceFiber.tag));
    }
    attachPingListener(root, value, rootRenderLanes);
    renderDidSuspendDelayIfPossible();
    return !1;
  }
  if (isHydrating)
    return (
      (returnFiber = suspenseHandlerStackCursor.current),
      null !== returnFiber
        ? (0 === (returnFiber.flags & 65536) && (returnFiber.flags |= 256),
          (returnFiber.flags |= 65536),
          (returnFiber.lanes = rootRenderLanes),
          value !== HydrationMismatchException &&
            ((root = Error(formatProdErrorMessage(422), { cause: value })),
            queueHydrationError(createCapturedValueAtFiber(root, sourceFiber))))
        : (value !== HydrationMismatchException &&
            ((returnFiber = Error(formatProdErrorMessage(423), {
              cause: value
            })),
            queueHydrationError(
              createCapturedValueAtFiber(returnFiber, sourceFiber)
            )),
          (root = root.current.alternate),
          (root.flags |= 65536),
          (rootRenderLanes &= -rootRenderLanes),
          (root.lanes |= rootRenderLanes),
          (value = createCapturedValueAtFiber(value, sourceFiber)),
          (rootRenderLanes = createRootErrorUpdate(
            root.stateNode,
            value,
            rootRenderLanes
          )),
          enqueueCapturedUpdate(root, rootRenderLanes),
          4 !== workInProgressRootExitStatus &&
            (workInProgressRootExitStatus = 2)),
      !1
    );
  var wrapperError = Error(formatProdErrorMessage(520), { cause: value });
  wrapperError = createCapturedValueAtFiber(wrapperError, sourceFiber);
  null === workInProgressRootConcurrentErrors
    ? (workInProgressRootConcurrentErrors = [wrapperError])
    : workInProgressRootConcurrentErrors.push(wrapperError);
  4 !== workInProgressRootExitStatus && (workInProgressRootExitStatus = 2);
  if (null === returnFiber) return !0;
  value = createCapturedValueAtFiber(value, sourceFiber);
  sourceFiber = returnFiber;
  do {
    switch (sourceFiber.tag) {
      case 3:
        return (
          (sourceFiber.flags |= 65536),
          (root = rootRenderLanes & -rootRenderLanes),
          (sourceFiber.lanes |= root),
          (root = createRootErrorUpdate(sourceFiber.stateNode, value, root)),
          enqueueCapturedUpdate(sourceFiber, root),
          !1
        );
      case 1:
        if (
          ((returnFiber = sourceFiber.type),
          (wrapperError = sourceFiber.stateNode),
          0 === (sourceFiber.flags & 128) &&
            ("function" === typeof returnFiber.getDerivedStateFromError ||
              (null !== wrapperError &&
                "function" === typeof wrapperError.componentDidCatch &&
                (null === legacyErrorBoundariesThatAlreadyFailed ||
                  !legacyErrorBoundariesThatAlreadyFailed.has(wrapperError)))))
        )
          return (
            (sourceFiber.flags |= 65536),
            (rootRenderLanes &= -rootRenderLanes),
            (sourceFiber.lanes |= rootRenderLanes),
            (rootRenderLanes = createClassErrorUpdate(rootRenderLanes)),
            initializeClassErrorUpdate(
              rootRenderLanes,
              root,
              sourceFiber,
              value
            ),
            enqueueCapturedUpdate(sourceFiber, rootRenderLanes),
            !1
          );
    }
    sourceFiber = sourceFiber.return;
  } while (null !== sourceFiber);
  return !1;
}
var SelectiveHydrationException = Error(formatProdErrorMessage(461)),
  didReceiveUpdate = !1;
function reconcileChildren(current, workInProgress, nextChildren, renderLanes) {
  workInProgress.child =
    null === current
      ? mountChildFibers(workInProgress, null, nextChildren, renderLanes)
      : reconcileChildFibers(
          workInProgress,
          current.child,
          nextChildren,
          renderLanes
        );
}
function updateForwardRef(
  current,
  workInProgress,
  Component,
  nextProps,
  renderLanes
) {
  Component = Component.render;
  var ref = workInProgress.ref;
  if ("ref" in nextProps) {
    var propsWithoutRef = {};
    for (var key in nextProps)
      "ref" !== key && (propsWithoutRef[key] = nextProps[key]);
  } else propsWithoutRef = nextProps;
  prepareToReadContext(workInProgress);
  nextProps = renderWithHooks(
    current,
    workInProgress,
    Component,
    propsWithoutRef,
    ref,
    renderLanes
  );
  key = checkDidRenderIdHook();
  if (null !== current && !didReceiveUpdate)
    return (
      bailoutHooks(current, workInProgress, renderLanes),
      bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes)
    );
  isHydrating && key && pushMaterializedTreeId(workInProgress);
  workInProgress.flags |= 1;
  reconcileChildren(current, workInProgress, nextProps, renderLanes);
  return workInProgress.child;
}
function updateMemoComponent(
  current,
  workInProgress,
  Component,
  nextProps,
  renderLanes
) {
  if (null === current) {
    var type = Component.type;
    if (
      "function" === typeof type &&
      !shouldConstruct(type) &&
      void 0 === type.defaultProps &&
      null === Component.compare
    )
      return (
        (workInProgress.tag = 15),
        (workInProgress.type = type),
        updateSimpleMemoComponent(
          current,
          workInProgress,
          type,
          nextProps,
          renderLanes
        )
      );
    current = createFiberFromTypeAndProps(
      Component.type,
      null,
      nextProps,
      workInProgress,
      workInProgress.mode,
      renderLanes
    );
    current.ref = workInProgress.ref;
    current.return = workInProgress;
    return (workInProgress.child = current);
  }
  type = current.child;
  if (!checkScheduledUpdateOrContext(current, renderLanes)) {
    var prevProps = type.memoizedProps;
    Component = Component.compare;
    Component = null !== Component ? Component : shallowEqual;
    if (Component(prevProps, nextProps) && current.ref === workInProgress.ref)
      return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
  }
  workInProgress.flags |= 1;
  current = createWorkInProgress(type, nextProps);
  current.ref = workInProgress.ref;
  current.return = workInProgress;
  return (workInProgress.child = current);
}
function updateSimpleMemoComponent(
  current,
  workInProgress,
  Component,
  nextProps,
  renderLanes
) {
  if (null !== current) {
    var prevProps = current.memoizedProps;
    if (
      shallowEqual(prevProps, nextProps) &&
      current.ref === workInProgress.ref
    )
      if (
        ((didReceiveUpdate = !1),
        (workInProgress.pendingProps = nextProps = prevProps),
        checkScheduledUpdateOrContext(current, renderLanes))
      )
        0 !== (current.flags & 131072) && (didReceiveUpdate = !0);
      else
        return (
          (workInProgress.lanes = current.lanes),
          bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes)
        );
  }
  return updateFunctionComponent(
    current,
    workInProgress,
    Component,
    nextProps,
    renderLanes
  );
}
function updateOffscreenComponent(current, workInProgress, renderLanes) {
  var nextProps = workInProgress.pendingProps,
    nextChildren = nextProps.children,
    nextIsDetached = 0 !== (workInProgress.stateNode._pendingVisibility & 2),
    prevState = null !== current ? current.memoizedState : null;
  markRef(current, workInProgress);
  if ("hidden" === nextProps.mode || nextIsDetached) {
    if (0 !== (workInProgress.flags & 128)) {
      nextProps =
        null !== prevState ? prevState.baseLanes | renderLanes : renderLanes;
      if (null !== current) {
        nextChildren = workInProgress.child = current.child;
        for (nextIsDetached = 0; null !== nextChildren; )
          (nextIsDetached =
            nextIsDetached | nextChildren.lanes | nextChildren.childLanes),
            (nextChildren = nextChildren.sibling);
        workInProgress.childLanes = nextIsDetached & ~nextProps;
      } else (workInProgress.childLanes = 0), (workInProgress.child = null);
      return deferHiddenOffscreenComponent(
        current,
        workInProgress,
        nextProps,
        renderLanes
      );
    }
    if (0 !== (renderLanes & 536870912))
      (workInProgress.memoizedState = { baseLanes: 0, cachePool: null }),
        null !== current &&
          pushTransition(
            workInProgress,
            null !== prevState ? prevState.cachePool : null
          ),
        null !== prevState
          ? pushHiddenContext(workInProgress, prevState)
          : reuseHiddenContextOnStack(),
        pushOffscreenSuspenseHandler(workInProgress);
    else
      return (
        (workInProgress.lanes = workInProgress.childLanes = 536870912),
        deferHiddenOffscreenComponent(
          current,
          workInProgress,
          null !== prevState ? prevState.baseLanes | renderLanes : renderLanes,
          renderLanes
        )
      );
  } else
    null !== prevState
      ? (pushTransition(workInProgress, prevState.cachePool),
        pushHiddenContext(workInProgress, prevState),
        reuseSuspenseHandlerOnStack(workInProgress),
        (workInProgress.memoizedState = null))
      : (null !== current && pushTransition(workInProgress, null),
        reuseHiddenContextOnStack(),
        reuseSuspenseHandlerOnStack(workInProgress));
  reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  return workInProgress.child;
}
function deferHiddenOffscreenComponent(
  current,
  workInProgress,
  nextBaseLanes,
  renderLanes
) {
  var JSCompiler_inline_result = peekCacheFromPool();
  JSCompiler_inline_result =
    null === JSCompiler_inline_result
      ? null
      : { parent: CacheContext._currentValue, pool: JSCompiler_inline_result };
  workInProgress.memoizedState = {
    baseLanes: nextBaseLanes,
    cachePool: JSCompiler_inline_result
  };
  null !== current && pushTransition(workInProgress, null);
  reuseHiddenContextOnStack();
  pushOffscreenSuspenseHandler(workInProgress);
  null !== current &&
    propagateParentContextChanges(current, workInProgress, renderLanes, !0);
  return null;
}
function markRef(current, workInProgress) {
  var ref = workInProgress.ref;
  if (null === ref)
    null !== current &&
      null !== current.ref &&
      (workInProgress.flags |= 2097664);
  else {
    if ("function" !== typeof ref && "object" !== typeof ref)
      throw Error(formatProdErrorMessage(284));
    if (null === current || current.ref !== ref)
      workInProgress.flags |= 2097664;
  }
}
function updateFunctionComponent(
  current,
  workInProgress,
  Component,
  nextProps,
  renderLanes
) {
  prepareToReadContext(workInProgress);
  Component = renderWithHooks(
    current,
    workInProgress,
    Component,
    nextProps,
    void 0,
    renderLanes
  );
  nextProps = checkDidRenderIdHook();
  if (null !== current && !didReceiveUpdate)
    return (
      bailoutHooks(current, workInProgress, renderLanes),
      bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes)
    );
  isHydrating && nextProps && pushMaterializedTreeId(workInProgress);
  workInProgress.flags |= 1;
  reconcileChildren(current, workInProgress, Component, renderLanes);
  return workInProgress.child;
}
function replayFunctionComponent(
  current,
  workInProgress,
  nextProps,
  Component,
  secondArg,
  renderLanes
) {
  prepareToReadContext(workInProgress);
  workInProgress.updateQueue = null;
  nextProps = renderWithHooksAgain(
    workInProgress,
    Component,
    nextProps,
    secondArg
  );
  finishRenderingHooks(current);
  Component = checkDidRenderIdHook();
  if (null !== current && !didReceiveUpdate)
    return (
      bailoutHooks(current, workInProgress, renderLanes),
      bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes)
    );
  isHydrating && Component && pushMaterializedTreeId(workInProgress);
  workInProgress.flags |= 1;
  reconcileChildren(current, workInProgress, nextProps, renderLanes);
  return workInProgress.child;
}
function updateClassComponent(
  current,
  workInProgress,
  Component,
  nextProps,
  renderLanes
) {
  prepareToReadContext(workInProgress);
  if (null === workInProgress.stateNode) {
    var context = emptyContextObject,
      contextType = Component.contextType;
    "object" === typeof contextType &&
      null !== contextType &&
      (context = readContext(contextType));
    context = new Component(nextProps, context);
    workInProgress.memoizedState =
      null !== context.state && void 0 !== context.state ? context.state : null;
    context.updater = classComponentUpdater;
    workInProgress.stateNode = context;
    context._reactInternals = workInProgress;
    context = workInProgress.stateNode;
    context.props = nextProps;
    context.state = workInProgress.memoizedState;
    context.refs = {};
    initializeUpdateQueue(workInProgress);
    contextType = Component.contextType;
    context.context =
      "object" === typeof contextType && null !== contextType
        ? readContext(contextType)
        : emptyContextObject;
    context.state = workInProgress.memoizedState;
    contextType = Component.getDerivedStateFromProps;
    "function" === typeof contextType &&
      (applyDerivedStateFromProps(
        workInProgress,
        Component,
        contextType,
        nextProps
      ),
      (context.state = workInProgress.memoizedState));
    "function" === typeof Component.getDerivedStateFromProps ||
      "function" === typeof context.getSnapshotBeforeUpdate ||
      ("function" !== typeof context.UNSAFE_componentWillMount &&
        "function" !== typeof context.componentWillMount) ||
      ((contextType = context.state),
      "function" === typeof context.componentWillMount &&
        context.componentWillMount(),
      "function" === typeof context.UNSAFE_componentWillMount &&
        context.UNSAFE_componentWillMount(),
      contextType !== context.state &&
        classComponentUpdater.enqueueReplaceState(context, context.state, null),
      processUpdateQueue(workInProgress, nextProps, context, renderLanes),
      suspendIfUpdateReadFromEntangledAsyncAction(),
      (context.state = workInProgress.memoizedState));
    "function" === typeof context.componentDidMount &&
      (workInProgress.flags |= 4194308);
    nextProps = !0;
  } else if (null === current) {
    context = workInProgress.stateNode;
    var unresolvedOldProps = workInProgress.memoizedProps,
      oldProps = resolveClassComponentProps(Component, unresolvedOldProps);
    context.props = oldProps;
    var oldContext = context.context,
      contextType$jscomp$0 = Component.contextType;
    contextType = emptyContextObject;
    "object" === typeof contextType$jscomp$0 &&
      null !== contextType$jscomp$0 &&
      (contextType = readContext(contextType$jscomp$0));
    var getDerivedStateFromProps = Component.getDerivedStateFromProps;
    contextType$jscomp$0 =
      "function" === typeof getDerivedStateFromProps ||
      "function" === typeof context.getSnapshotBeforeUpdate;
    unresolvedOldProps = workInProgress.pendingProps !== unresolvedOldProps;
    contextType$jscomp$0 ||
      ("function" !== typeof context.UNSAFE_componentWillReceiveProps &&
        "function" !== typeof context.componentWillReceiveProps) ||
      ((unresolvedOldProps || oldContext !== contextType) &&
        callComponentWillReceiveProps(
          workInProgress,
          context,
          nextProps,
          contextType
        ));
    hasForceUpdate = !1;
    var oldState = workInProgress.memoizedState;
    context.state = oldState;
    processUpdateQueue(workInProgress, nextProps, context, renderLanes);
    suspendIfUpdateReadFromEntangledAsyncAction();
    oldContext = workInProgress.memoizedState;
    unresolvedOldProps || oldState !== oldContext || hasForceUpdate
      ? ("function" === typeof getDerivedStateFromProps &&
          (applyDerivedStateFromProps(
            workInProgress,
            Component,
            getDerivedStateFromProps,
            nextProps
          ),
          (oldContext = workInProgress.memoizedState)),
        (oldProps =
          hasForceUpdate ||
          checkShouldComponentUpdate(
            workInProgress,
            Component,
            oldProps,
            nextProps,
            oldState,
            oldContext,
            contextType
          ))
          ? (contextType$jscomp$0 ||
              ("function" !== typeof context.UNSAFE_componentWillMount &&
                "function" !== typeof context.componentWillMount) ||
              ("function" === typeof context.componentWillMount &&
                context.componentWillMount(),
              "function" === typeof context.UNSAFE_componentWillMount &&
                context.UNSAFE_componentWillMount()),
            "function" === typeof context.componentDidMount &&
              (workInProgress.flags |= 4194308))
          : ("function" === typeof context.componentDidMount &&
              (workInProgress.flags |= 4194308),
            (workInProgress.memoizedProps = nextProps),
            (workInProgress.memoizedState = oldContext)),
        (context.props = nextProps),
        (context.state = oldContext),
        (context.context = contextType),
        (nextProps = oldProps))
      : ("function" === typeof context.componentDidMount &&
          (workInProgress.flags |= 4194308),
        (nextProps = !1));
  } else {
    context = workInProgress.stateNode;
    cloneUpdateQueue(current, workInProgress);
    contextType = workInProgress.memoizedProps;
    contextType$jscomp$0 = resolveClassComponentProps(Component, contextType);
    context.props = contextType$jscomp$0;
    getDerivedStateFromProps = workInProgress.pendingProps;
    oldState = context.context;
    oldContext = Component.contextType;
    oldProps = emptyContextObject;
    "object" === typeof oldContext &&
      null !== oldContext &&
      (oldProps = readContext(oldContext));
    unresolvedOldProps = Component.getDerivedStateFromProps;
    (oldContext =
      "function" === typeof unresolvedOldProps ||
      "function" === typeof context.getSnapshotBeforeUpdate) ||
      ("function" !== typeof context.UNSAFE_componentWillReceiveProps &&
        "function" !== typeof context.componentWillReceiveProps) ||
      ((contextType !== getDerivedStateFromProps || oldState !== oldProps) &&
        callComponentWillReceiveProps(
          workInProgress,
          context,
          nextProps,
          oldProps
        ));
    hasForceUpdate = !1;
    oldState = workInProgress.memoizedState;
    context.state = oldState;
    processUpdateQueue(workInProgress, nextProps, context, renderLanes);
    suspendIfUpdateReadFromEntangledAsyncAction();
    var newState = workInProgress.memoizedState;
    contextType !== getDerivedStateFromProps ||
    oldState !== newState ||
    hasForceUpdate ||
    (null !== current &&
      null !== current.dependencies &&
      checkIfContextChanged(current.dependencies))
      ? ("function" === typeof unresolvedOldProps &&
          (applyDerivedStateFromProps(
            workInProgress,
            Component,
            unresolvedOldProps,
            nextProps
          ),
          (newState = workInProgress.memoizedState)),
        (contextType$jscomp$0 =
          hasForceUpdate ||
          checkShouldComponentUpdate(
            workInProgress,
            Component,
            contextType$jscomp$0,
            nextProps,
            oldState,
            newState,
            oldProps
          ) ||
          (null !== current &&
            null !== current.dependencies &&
            checkIfContextChanged(current.dependencies)))
          ? (oldContext ||
              ("function" !== typeof context.UNSAFE_componentWillUpdate &&
                "function" !== typeof context.componentWillUpdate) ||
              ("function" === typeof context.componentWillUpdate &&
                context.componentWillUpdate(nextProps, newState, oldProps),
              "function" === typeof context.UNSAFE_componentWillUpdate &&
                context.UNSAFE_componentWillUpdate(
                  nextProps,
                  newState,
                  oldProps
                )),
            "function" === typeof context.componentDidUpdate &&
              (workInProgress.flags |= 4),
            "function" === typeof context.getSnapshotBeforeUpdate &&
              (workInProgress.flags |= 1024))
          : ("function" !== typeof context.componentDidUpdate ||
              (contextType === current.memoizedProps &&
                oldState === current.memoizedState) ||
              (workInProgress.flags |= 4),
            "function" !== typeof context.getSnapshotBeforeUpdate ||
              (contextType === current.memoizedProps &&
                oldState === current.memoizedState) ||
              (workInProgress.flags |= 1024),
            (workInProgress.memoizedProps = nextProps),
            (workInProgress.memoizedState = newState)),
        (context.props = nextProps),
        (context.state = newState),
        (context.context = oldProps),
        (nextProps = contextType$jscomp$0))
      : ("function" !== typeof context.componentDidUpdate ||
          (contextType === current.memoizedProps &&
            oldState === current.memoizedState) ||
          (workInProgress.flags |= 4),
        "function" !== typeof context.getSnapshotBeforeUpdate ||
          (contextType === current.memoizedProps &&
            oldState === current.memoizedState) ||
          (workInProgress.flags |= 1024),
        (nextProps = !1));
  }
  context = nextProps;
  markRef(current, workInProgress);
  nextProps = 0 !== (workInProgress.flags & 128);
  context || nextProps
    ? ((context = workInProgress.stateNode),
      (Component =
        nextProps && "function" !== typeof Component.getDerivedStateFromError
          ? null
          : context.render()),
      (workInProgress.flags |= 1),
      null !== current && nextProps
        ? ((workInProgress.child = reconcileChildFibers(
            workInProgress,
            current.child,
            null,
            renderLanes
          )),
          (workInProgress.child = reconcileChildFibers(
            workInProgress,
            null,
            Component,
            renderLanes
          )))
        : reconcileChildren(current, workInProgress, Component, renderLanes),
      (workInProgress.memoizedState = context.state),
      (current = workInProgress.child))
    : (current = bailoutOnAlreadyFinishedWork(
        current,
        workInProgress,
        renderLanes
      ));
  return current;
}
function mountHostRootWithoutHydrating(
  current,
  workInProgress,
  nextChildren,
  renderLanes
) {
  resetHydrationState();
  workInProgress.flags |= 256;
  reconcileChildren(current, workInProgress, nextChildren, renderLanes);
  return workInProgress.child;
}
var SUSPENDED_MARKER = { dehydrated: null, treeContext: null, retryLane: 0 };
function mountSuspenseOffscreenState(renderLanes) {
  return { baseLanes: renderLanes, cachePool: getSuspendedCache() };
}
function getRemainingWorkInPrimaryTree(
  current,
  primaryTreeDidDefer,
  renderLanes
) {
  current = null !== current ? current.childLanes & ~renderLanes : 0;
  primaryTreeDidDefer && (current |= workInProgressDeferredLane);
  return current;
}
function updateSuspenseComponent(current, workInProgress, renderLanes) {
  var nextProps = workInProgress.pendingProps,
    showFallback = !1,
    didSuspend = 0 !== (workInProgress.flags & 128),
    JSCompiler_temp;
  (JSCompiler_temp = didSuspend) ||
    (JSCompiler_temp =
      null !== current && null === current.memoizedState
        ? !1
        : 0 !== (suspenseStackCursor.current & 2));
  JSCompiler_temp && ((showFallback = !0), (workInProgress.flags &= -129));
  JSCompiler_temp = 0 !== (workInProgress.flags & 32);
  workInProgress.flags &= -33;
  if (null === current) {
    if (isHydrating) {
      showFallback
        ? pushPrimaryTreeSuspenseHandler(workInProgress)
        : reuseSuspenseHandlerOnStack(workInProgress);
      if (isHydrating) {
        var nextInstance = nextHydratableInstance,
          JSCompiler_temp$jscomp$0;
        if ((JSCompiler_temp$jscomp$0 = nextInstance)) {
          c: {
            JSCompiler_temp$jscomp$0 = nextInstance;
            for (
              nextInstance = rootOrSingletonContext;
              8 !== JSCompiler_temp$jscomp$0.nodeType;

            ) {
              if (!nextInstance) {
                nextInstance = null;
                break c;
              }
              JSCompiler_temp$jscomp$0 = getNextHydratable(
                JSCompiler_temp$jscomp$0.nextSibling
              );
              if (null === JSCompiler_temp$jscomp$0) {
                nextInstance = null;
                break c;
              }
            }
            nextInstance = JSCompiler_temp$jscomp$0;
          }
          null !== nextInstance
            ? ((workInProgress.memoizedState = {
                dehydrated: nextInstance,
                treeContext:
                  null !== treeContextProvider
                    ? { id: treeContextId, overflow: treeContextOverflow }
                    : null,
                retryLane: 536870912
              }),
              (JSCompiler_temp$jscomp$0 = createFiberImplClass(
                18,
                null,
                null,
                0
              )),
              (JSCompiler_temp$jscomp$0.stateNode = nextInstance),
              (JSCompiler_temp$jscomp$0.return = workInProgress),
              (workInProgress.child = JSCompiler_temp$jscomp$0),
              (hydrationParentFiber = workInProgress),
              (nextHydratableInstance = null),
              (JSCompiler_temp$jscomp$0 = !0))
            : (JSCompiler_temp$jscomp$0 = !1);
        }
        JSCompiler_temp$jscomp$0 || throwOnHydrationMismatch(workInProgress);
      }
      nextInstance = workInProgress.memoizedState;
      if (
        null !== nextInstance &&
        ((nextInstance = nextInstance.dehydrated), null !== nextInstance)
      )
        return (
          "$!" === nextInstance.data
            ? (workInProgress.lanes = 16)
            : (workInProgress.lanes = 536870912),
          null
        );
      popSuspenseHandler(workInProgress);
    }
    nextInstance = nextProps.children;
    nextProps = nextProps.fallback;
    if (showFallback)
      return (
        reuseSuspenseHandlerOnStack(workInProgress),
        (showFallback = workInProgress.mode),
        (nextInstance = mountWorkInProgressOffscreenFiber(
          { mode: "hidden", children: nextInstance },
          showFallback
        )),
        (nextProps = createFiberFromFragment(
          nextProps,
          showFallback,
          renderLanes,
          null
        )),
        (nextInstance.return = workInProgress),
        (nextProps.return = workInProgress),
        (nextInstance.sibling = nextProps),
        (workInProgress.child = nextInstance),
        (showFallback = workInProgress.child),
        (showFallback.memoizedState = mountSuspenseOffscreenState(renderLanes)),
        (showFallback.childLanes = getRemainingWorkInPrimaryTree(
          current,
          JSCompiler_temp,
          renderLanes
        )),
        (workInProgress.memoizedState = SUSPENDED_MARKER),
        nextProps
      );
    pushPrimaryTreeSuspenseHandler(workInProgress);
    return mountSuspensePrimaryChildren(workInProgress, nextInstance);
  }
  JSCompiler_temp$jscomp$0 = current.memoizedState;
  if (
    null !== JSCompiler_temp$jscomp$0 &&
    ((nextInstance = JSCompiler_temp$jscomp$0.dehydrated),
    null !== nextInstance)
  ) {
    if (didSuspend)
      workInProgress.flags & 256
        ? (pushPrimaryTreeSuspenseHandler(workInProgress),
          (workInProgress.flags &= -257),
          (workInProgress = retrySuspenseComponentWithoutHydrating(
            current,
            workInProgress,
            renderLanes
          )))
        : null !== workInProgress.memoizedState
          ? (reuseSuspenseHandlerOnStack(workInProgress),
            (workInProgress.child = current.child),
            (workInProgress.flags |= 128),
            (workInProgress = null))
          : (reuseSuspenseHandlerOnStack(workInProgress),
            (showFallback = nextProps.fallback),
            (nextInstance = workInProgress.mode),
            (nextProps = mountWorkInProgressOffscreenFiber(
              { mode: "visible", children: nextProps.children },
              nextInstance
            )),
            (showFallback = createFiberFromFragment(
              showFallback,
              nextInstance,
              renderLanes,
              null
            )),
            (showFallback.flags |= 2),
            (nextProps.return = workInProgress),
            (showFallback.return = workInProgress),
            (nextProps.sibling = showFallback),
            (workInProgress.child = nextProps),
            reconcileChildFibers(
              workInProgress,
              current.child,
              null,
              renderLanes
            ),
            (nextProps = workInProgress.child),
            (nextProps.memoizedState =
              mountSuspenseOffscreenState(renderLanes)),
            (nextProps.childLanes = getRemainingWorkInPrimaryTree(
              current,
              JSCompiler_temp,
              renderLanes
            )),
            (workInProgress.memoizedState = SUSPENDED_MARKER),
            (workInProgress = showFallback));
    else if (
      (pushPrimaryTreeSuspenseHandler(workInProgress),
      "$!" === nextInstance.data)
    ) {
      JSCompiler_temp =
        nextInstance.nextSibling && nextInstance.nextSibling.dataset;
      if (JSCompiler_temp) var digest = JSCompiler_temp.dgst;
      JSCompiler_temp = digest;
      nextProps = Error(formatProdErrorMessage(419));
      nextProps.stack = "";
      nextProps.digest = JSCompiler_temp;
      queueHydrationError({ value: nextProps, source: null, stack: null });
      workInProgress = retrySuspenseComponentWithoutHydrating(
        current,
        workInProgress,
        renderLanes
      );
    } else if (
      (didReceiveUpdate ||
        propagateParentContextChanges(current, workInProgress, renderLanes, !1),
      (JSCompiler_temp = 0 !== (renderLanes & current.childLanes)),
      didReceiveUpdate || JSCompiler_temp)
    ) {
      JSCompiler_temp = workInProgressRoot;
      if (null !== JSCompiler_temp) {
        nextProps = renderLanes & -renderLanes;
        if (0 !== (nextProps & 42)) nextProps = 1;
        else
          switch (nextProps) {
            case 2:
              nextProps = 1;
              break;
            case 8:
              nextProps = 4;
              break;
            case 32:
              nextProps = 16;
              break;
            case 128:
            case 256:
            case 512:
            case 1024:
            case 2048:
            case 4096:
            case 8192:
            case 16384:
            case 32768:
            case 65536:
            case 131072:
            case 262144:
            case 524288:
            case 1048576:
            case 2097152:
            case 4194304:
            case 8388608:
            case 16777216:
            case 33554432:
              nextProps = 64;
              break;
            case 268435456:
              nextProps = 134217728;
              break;
            default:
              nextProps = 0;
          }
        nextProps =
          0 !== (nextProps & (JSCompiler_temp.suspendedLanes | renderLanes))
            ? 0
            : nextProps;
        if (0 !== nextProps && nextProps !== JSCompiler_temp$jscomp$0.retryLane)
          throw (
            ((JSCompiler_temp$jscomp$0.retryLane = nextProps),
            enqueueConcurrentRenderForLane(current, nextProps),
            scheduleUpdateOnFiber(JSCompiler_temp, current, nextProps),
            SelectiveHydrationException)
          );
      }
      "$?" === nextInstance.data || renderDidSuspendDelayIfPossible();
      workInProgress = retrySuspenseComponentWithoutHydrating(
        current,
        workInProgress,
        renderLanes
      );
    } else
      "$?" === nextInstance.data
        ? ((workInProgress.flags |= 128),
          (workInProgress.child = current.child),
          (workInProgress = retryDehydratedSuspenseBoundary.bind(
            null,
            current
          )),
          (nextInstance._reactRetry = workInProgress),
          (workInProgress = null))
        : ((current = JSCompiler_temp$jscomp$0.treeContext),
          (nextHydratableInstance = getNextHydratable(
            nextInstance.nextSibling
          )),
          (hydrationParentFiber = workInProgress),
          (isHydrating = !0),
          (hydrationErrors = null),
          (rootOrSingletonContext = !1),
          null !== current &&
            ((idStack[idStackIndex++] = treeContextId),
            (idStack[idStackIndex++] = treeContextOverflow),
            (idStack[idStackIndex++] = treeContextProvider),
            (treeContextId = current.id),
            (treeContextOverflow = current.overflow),
            (treeContextProvider = workInProgress)),
          (workInProgress = mountSuspensePrimaryChildren(
            workInProgress,
            nextProps.children
          )),
          (workInProgress.flags |= 4096));
    return workInProgress;
  }
  if (showFallback)
    return (
      reuseSuspenseHandlerOnStack(workInProgress),
      (showFallback = nextProps.fallback),
      (nextInstance = workInProgress.mode),
      (JSCompiler_temp$jscomp$0 = current.child),
      (digest = JSCompiler_temp$jscomp$0.sibling),
      (nextProps = createWorkInProgress(JSCompiler_temp$jscomp$0, {
        mode: "hidden",
        children: nextProps.children
      })),
      (nextProps.subtreeFlags =
        JSCompiler_temp$jscomp$0.subtreeFlags & 31457280),
      null !== digest
        ? (showFallback = createWorkInProgress(digest, showFallback))
        : ((showFallback = createFiberFromFragment(
            showFallback,
            nextInstance,
            renderLanes,
            null
          )),
          (showFallback.flags |= 2)),
      (showFallback.return = workInProgress),
      (nextProps.return = workInProgress),
      (nextProps.sibling = showFallback),
      (workInProgress.child = nextProps),
      (nextProps = showFallback),
      (showFallback = workInProgress.child),
      (nextInstance = current.child.memoizedState),
      null === nextInstance
        ? (nextInstance = mountSuspenseOffscreenState(renderLanes))
        : ((JSCompiler_temp$jscomp$0 = nextInstance.cachePool),
          null !== JSCompiler_temp$jscomp$0
            ? ((digest = CacheContext._currentValue),
              (JSCompiler_temp$jscomp$0 =
                JSCompiler_temp$jscomp$0.parent !== digest
                  ? { parent: digest, pool: digest }
                  : JSCompiler_temp$jscomp$0))
            : (JSCompiler_temp$jscomp$0 = getSuspendedCache()),
          (nextInstance = {
            baseLanes: nextInstance.baseLanes | renderLanes,
            cachePool: JSCompiler_temp$jscomp$0
          })),
      (showFallback.memoizedState = nextInstance),
      (showFallback.childLanes = getRemainingWorkInPrimaryTree(
        current,
        JSCompiler_temp,
        renderLanes
      )),
      (workInProgress.memoizedState = SUSPENDED_MARKER),
      nextProps
    );
  pushPrimaryTreeSuspenseHandler(workInProgress);
  renderLanes = current.child;
  current = renderLanes.sibling;
  renderLanes = createWorkInProgress(renderLanes, {
    mode: "visible",
    children: nextProps.children
  });
  renderLanes.return = workInProgress;
  renderLanes.sibling = null;
  null !== current &&
    ((JSCompiler_temp = workInProgress.deletions),
    null === JSCompiler_temp
      ? ((workInProgress.deletions = [current]), (workInProgress.flags |= 16))
      : JSCompiler_temp.push(current));
  workInProgress.child = renderLanes;
  workInProgress.memoizedState = null;
  return renderLanes;
}
function mountSuspensePrimaryChildren(workInProgress, primaryChildren) {
  primaryChildren = mountWorkInProgressOffscreenFiber(
    { mode: "visible", children: primaryChildren },
    workInProgress.mode
  );
  primaryChildren.return = workInProgress;
  return (workInProgress.child = primaryChildren);
}
function mountWorkInProgressOffscreenFiber(offscreenProps, mode) {
  return createFiberFromOffscreen(offscreenProps, mode, 0, null);
}
function retrySuspenseComponentWithoutHydrating(
  current,
  workInProgress,
  renderLanes
) {
  reconcileChildFibers(workInProgress, current.child, null, renderLanes);
  current = mountSuspensePrimaryChildren(
    workInProgress,
    workInProgress.pendingProps.children
  );
  current.flags |= 2;
  workInProgress.memoizedState = null;
  return current;
}
function scheduleSuspenseWorkOnFiber(fiber, renderLanes, propagationRoot) {
  fiber.lanes |= renderLanes;
  var alternate = fiber.alternate;
  null !== alternate && (alternate.lanes |= renderLanes);
  scheduleContextWorkOnParentPath(fiber.return, renderLanes, propagationRoot);
}
function initSuspenseListRenderState(
  workInProgress,
  isBackwards,
  tail,
  lastContentRow,
  tailMode
) {
  var renderState = workInProgress.memoizedState;
  null === renderState
    ? (workInProgress.memoizedState = {
        isBackwards: isBackwards,
        rendering: null,
        renderingStartTime: 0,
        last: lastContentRow,
        tail: tail,
        tailMode: tailMode
      })
    : ((renderState.isBackwards = isBackwards),
      (renderState.rendering = null),
      (renderState.renderingStartTime = 0),
      (renderState.last = lastContentRow),
      (renderState.tail = tail),
      (renderState.tailMode = tailMode));
}
function updateSuspenseListComponent(current, workInProgress, renderLanes) {
  var nextProps = workInProgress.pendingProps,
    revealOrder = nextProps.revealOrder,
    tailMode = nextProps.tail;
  reconcileChildren(current, workInProgress, nextProps.children, renderLanes);
  nextProps = suspenseStackCursor.current;
  if (0 !== (nextProps & 2))
    (nextProps = (nextProps & 1) | 2), (workInProgress.flags |= 128);
  else {
    if (null !== current && 0 !== (current.flags & 128))
      a: for (current = workInProgress.child; null !== current; ) {
        if (13 === current.tag)
          null !== current.memoizedState &&
            scheduleSuspenseWorkOnFiber(current, renderLanes, workInProgress);
        else if (19 === current.tag)
          scheduleSuspenseWorkOnFiber(current, renderLanes, workInProgress);
        else if (null !== current.child) {
          current.child.return = current;
          current = current.child;
          continue;
        }
        if (current === workInProgress) break a;
        for (; null === current.sibling; ) {
          if (null === current.return || current.return === workInProgress)
            break a;
          current = current.return;
        }
        current.sibling.return = current.return;
        current = current.sibling;
      }
    nextProps &= 1;
  }
  push(suspenseStackCursor, nextProps);
  switch (revealOrder) {
    case "forwards":
      renderLanes = workInProgress.child;
      for (revealOrder = null; null !== renderLanes; )
        (current = renderLanes.alternate),
          null !== current &&
            null === findFirstSuspended(current) &&
            (revealOrder = renderLanes),
          (renderLanes = renderLanes.sibling);
      renderLanes = revealOrder;
      null === renderLanes
        ? ((revealOrder = workInProgress.child), (workInProgress.child = null))
        : ((revealOrder = renderLanes.sibling), (renderLanes.sibling = null));
      initSuspenseListRenderState(
        workInProgress,
        !1,
        revealOrder,
        renderLanes,
        tailMode
      );
      break;
    case "backwards":
      renderLanes = null;
      revealOrder = workInProgress.child;
      for (workInProgress.child = null; null !== revealOrder; ) {
        current = revealOrder.alternate;
        if (null !== current && null === findFirstSuspended(current)) {
          workInProgress.child = revealOrder;
          break;
        }
        current = revealOrder.sibling;
        revealOrder.sibling = renderLanes;
        renderLanes = revealOrder;
        revealOrder = current;
      }
      initSuspenseListRenderState(
        workInProgress,
        !0,
        renderLanes,
        null,
        tailMode
      );
      break;
    case "together":
      initSuspenseListRenderState(workInProgress, !1, null, null, void 0);
      break;
    default:
      workInProgress.memoizedState = null;
  }
  return workInProgress.child;
}
function bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes) {
  null !== current && (workInProgress.dependencies = current.dependencies);
  workInProgressRootSkippedLanes |= workInProgress.lanes;
  if (0 === (renderLanes & workInProgress.childLanes))
    if (null !== current) {
      if (
        (propagateParentContextChanges(
          current,
          workInProgress,
          renderLanes,
          !1
        ),
        0 === (renderLanes & workInProgress.childLanes))
      )
        return null;
    } else return null;
  if (null !== current && workInProgress.child !== current.child)
    throw Error(formatProdErrorMessage(153));
  if (null !== workInProgress.child) {
    current = workInProgress.child;
    renderLanes = createWorkInProgress(current, current.pendingProps);
    workInProgress.child = renderLanes;
    for (renderLanes.return = workInProgress; null !== current.sibling; )
      (current = current.sibling),
        (renderLanes = renderLanes.sibling =
          createWorkInProgress(current, current.pendingProps)),
        (renderLanes.return = workInProgress);
    renderLanes.sibling = null;
  }
  return workInProgress.child;
}
function checkScheduledUpdateOrContext(current, renderLanes) {
  if (0 !== (current.lanes & renderLanes)) return !0;
  current = current.dependencies;
  return null !== current && checkIfContextChanged(current) ? !0 : !1;
}
function attemptEarlyBailoutIfNoScheduledUpdate(
  current,
  workInProgress,
  renderLanes
) {
  switch (workInProgress.tag) {
    case 3:
      pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
      pushProvider(workInProgress, CacheContext, current.memoizedState.cache);
      resetHydrationState();
      break;
    case 27:
    case 5:
      pushHostContext(workInProgress);
      break;
    case 4:
      pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
      break;
    case 10:
      pushProvider(
        workInProgress,
        workInProgress.type,
        workInProgress.memoizedProps.value
      );
      break;
    case 13:
      var state = workInProgress.memoizedState;
      if (null !== state) {
        if (null !== state.dehydrated)
          return (
            pushPrimaryTreeSuspenseHandler(workInProgress),
            (workInProgress.flags |= 128),
            null
          );
        if (0 !== (renderLanes & workInProgress.child.childLanes))
          return updateSuspenseComponent(current, workInProgress, renderLanes);
        pushPrimaryTreeSuspenseHandler(workInProgress);
        current = bailoutOnAlreadyFinishedWork(
          current,
          workInProgress,
          renderLanes
        );
        return null !== current ? current.sibling : null;
      }
      pushPrimaryTreeSuspenseHandler(workInProgress);
      break;
    case 19:
      var didSuspendBefore = 0 !== (current.flags & 128);
      state = 0 !== (renderLanes & workInProgress.childLanes);
      state ||
        (propagateParentContextChanges(
          current,
          workInProgress,
          renderLanes,
          !1
        ),
        (state = 0 !== (renderLanes & workInProgress.childLanes)));
      if (didSuspendBefore) {
        if (state)
          return updateSuspenseListComponent(
            current,
            workInProgress,
            renderLanes
          );
        workInProgress.flags |= 128;
      }
      didSuspendBefore = workInProgress.memoizedState;
      null !== didSuspendBefore &&
        ((didSuspendBefore.rendering = null),
        (didSuspendBefore.tail = null),
        (didSuspendBefore.lastEffect = null));
      push(suspenseStackCursor, suspenseStackCursor.current);
      if (state) break;
      else return null;
    case 22:
    case 23:
      return (
        (workInProgress.lanes = 0),
        updateOffscreenComponent(current, workInProgress, renderLanes)
      );
    case 24:
      pushProvider(workInProgress, CacheContext, current.memoizedState.cache);
  }
  return bailoutOnAlreadyFinishedWork(current, workInProgress, renderLanes);
}
function beginWork(current, workInProgress, renderLanes) {
  if (null !== current)
    if (current.memoizedProps !== workInProgress.pendingProps)
      didReceiveUpdate = !0;
    else {
      if (
        !checkScheduledUpdateOrContext(current, renderLanes) &&
        0 === (workInProgress.flags & 128)
      )
        return (
          (didReceiveUpdate = !1),
          attemptEarlyBailoutIfNoScheduledUpdate(
            current,
            workInProgress,
            renderLanes
          )
        );
      didReceiveUpdate = 0 !== (current.flags & 131072) ? !0 : !1;
    }
  else
    (didReceiveUpdate = !1),
      isHydrating &&
        0 !== (workInProgress.flags & 1048576) &&
        pushTreeId(workInProgress, treeForkCount, workInProgress.index);
  workInProgress.lanes = 0;
  switch (workInProgress.tag) {
    case 16:
      a: {
        current = workInProgress.pendingProps;
        var lazyComponent = workInProgress.elementType,
          init = lazyComponent._init;
        lazyComponent = init(lazyComponent._payload);
        workInProgress.type = lazyComponent;
        if ("function" === typeof lazyComponent)
          shouldConstruct(lazyComponent)
            ? ((current = resolveClassComponentProps(lazyComponent, current)),
              (workInProgress.tag = 1),
              (workInProgress = updateClassComponent(
                null,
                workInProgress,
                lazyComponent,
                current,
                renderLanes
              )))
            : ((workInProgress.tag = 0),
              (workInProgress = updateFunctionComponent(
                null,
                workInProgress,
                lazyComponent,
                current,
                renderLanes
              )));
        else {
          if (void 0 !== lazyComponent && null !== lazyComponent)
            if (
              ((init = lazyComponent.$$typeof), init === REACT_FORWARD_REF_TYPE)
            ) {
              workInProgress.tag = 11;
              workInProgress = updateForwardRef(
                null,
                workInProgress,
                lazyComponent,
                current,
                renderLanes
              );
              break a;
            } else if (init === REACT_MEMO_TYPE) {
              workInProgress.tag = 14;
              workInProgress = updateMemoComponent(
                null,
                workInProgress,
                lazyComponent,
                current,
                renderLanes
              );
              break a;
            }
          workInProgress =
            getComponentNameFromType(lazyComponent) || lazyComponent;
          throw Error(formatProdErrorMessage(306, workInProgress, ""));
        }
      }
      return workInProgress;
    case 0:
      return updateFunctionComponent(
        current,
        workInProgress,
        workInProgress.type,
        workInProgress.pendingProps,
        renderLanes
      );
    case 1:
      return (
        (lazyComponent = workInProgress.type),
        (init = resolveClassComponentProps(
          lazyComponent,
          workInProgress.pendingProps
        )),
        updateClassComponent(
          current,
          workInProgress,
          lazyComponent,
          init,
          renderLanes
        )
      );
    case 3:
      a: {
        pushHostContainer(
          workInProgress,
          workInProgress.stateNode.containerInfo
        );
        if (null === current) throw Error(formatProdErrorMessage(387));
        var nextProps = workInProgress.pendingProps;
        init = workInProgress.memoizedState;
        lazyComponent = init.element;
        cloneUpdateQueue(current, workInProgress);
        processUpdateQueue(workInProgress, nextProps, null, renderLanes);
        var nextState = workInProgress.memoizedState;
        nextProps = nextState.cache;
        pushProvider(workInProgress, CacheContext, nextProps);
        nextProps !== init.cache &&
          propagateContextChanges(
            workInProgress,
            [CacheContext],
            renderLanes,
            !0
          );
        suspendIfUpdateReadFromEntangledAsyncAction();
        nextProps = nextState.element;
        if (init.isDehydrated)
          if (
            ((init = {
              element: nextProps,
              isDehydrated: !1,
              cache: nextState.cache
            }),
            (workInProgress.updateQueue.baseState = init),
            (workInProgress.memoizedState = init),
            workInProgress.flags & 256)
          ) {
            workInProgress = mountHostRootWithoutHydrating(
              current,
              workInProgress,
              nextProps,
              renderLanes
            );
            break a;
          } else if (nextProps !== lazyComponent) {
            lazyComponent = createCapturedValueAtFiber(
              Error(formatProdErrorMessage(424)),
              workInProgress
            );
            queueHydrationError(lazyComponent);
            workInProgress = mountHostRootWithoutHydrating(
              current,
              workInProgress,
              nextProps,
              renderLanes
            );
            break a;
          } else
            for (
              nextHydratableInstance = getNextHydratable(
                workInProgress.stateNode.containerInfo.firstChild
              ),
                hydrationParentFiber = workInProgress,
                isHydrating = !0,
                hydrationErrors = null,
                rootOrSingletonContext = !0,
                renderLanes = mountChildFibers(
                  workInProgress,
                  null,
                  nextProps,
                  renderLanes
                ),
                workInProgress.child = renderLanes;
              renderLanes;

            )
              (renderLanes.flags = (renderLanes.flags & -3) | 4096),
                (renderLanes = renderLanes.sibling);
        else {
          resetHydrationState();
          if (nextProps === lazyComponent) {
            workInProgress = bailoutOnAlreadyFinishedWork(
              current,
              workInProgress,
              renderLanes
            );
            break a;
          }
          reconcileChildren(current, workInProgress, nextProps, renderLanes);
        }
        workInProgress = workInProgress.child;
      }
      return workInProgress;
    case 26:
      return (
        markRef(current, workInProgress),
        null === current
          ? (renderLanes = getResource(
              workInProgress.type,
              null,
              workInProgress.pendingProps,
              null
            ))
            ? (workInProgress.memoizedState = renderLanes)
            : isHydrating ||
              ((renderLanes = workInProgress.type),
              (current = workInProgress.pendingProps),
              (lazyComponent = getOwnerDocumentFromRootContainer(
                rootInstanceStackCursor.current
              ).createElement(renderLanes)),
              (lazyComponent[internalInstanceKey] = workInProgress),
              (lazyComponent[internalPropsKey] = current),
              setInitialProperties(lazyComponent, renderLanes, current),
              markNodeAsHoistable(lazyComponent),
              (workInProgress.stateNode = lazyComponent))
          : (workInProgress.memoizedState = getResource(
              workInProgress.type,
              current.memoizedProps,
              workInProgress.pendingProps,
              current.memoizedState
            )),
        null
      );
    case 27:
      return (
        pushHostContext(workInProgress),
        null === current &&
          isHydrating &&
          ((lazyComponent = workInProgress.stateNode =
            resolveSingletonInstance(
              workInProgress.type,
              workInProgress.pendingProps,
              rootInstanceStackCursor.current
            )),
          (hydrationParentFiber = workInProgress),
          (rootOrSingletonContext = !0),
          (nextHydratableInstance = getNextHydratable(
            lazyComponent.firstChild
          ))),
        (lazyComponent = workInProgress.pendingProps.children),
        null !== current || isHydrating
          ? reconcileChildren(
              current,
              workInProgress,
              lazyComponent,
              renderLanes
            )
          : (workInProgress.child = reconcileChildFibers(
              workInProgress,
              null,
              lazyComponent,
              renderLanes
            )),
        markRef(current, workInProgress),
        workInProgress.child
      );
    case 5:
      if (null === current && isHydrating) {
        if ((init = lazyComponent = nextHydratableInstance))
          (lazyComponent = canHydrateInstance(
            lazyComponent,
            workInProgress.type,
            workInProgress.pendingProps,
            rootOrSingletonContext
          )),
            null !== lazyComponent
              ? ((workInProgress.stateNode = lazyComponent),
                (hydrationParentFiber = workInProgress),
                (nextHydratableInstance = getNextHydratable(
                  lazyComponent.firstChild
                )),
                (rootOrSingletonContext = !1),
                (init = !0))
              : (init = !1);
        init || throwOnHydrationMismatch(workInProgress);
      }
      pushHostContext(workInProgress);
      init = workInProgress.type;
      nextProps = workInProgress.pendingProps;
      nextState = null !== current ? current.memoizedProps : null;
      lazyComponent = nextProps.children;
      shouldSetTextContent(init, nextProps)
        ? (lazyComponent = null)
        : null !== nextState &&
          shouldSetTextContent(init, nextState) &&
          (workInProgress.flags |= 32);
      null !== workInProgress.memoizedState &&
        ((init = renderWithHooks(
          current,
          workInProgress,
          TransitionAwareHostComponent,
          null,
          null,
          renderLanes
        )),
        (HostTransitionContext._currentValue = init));
      markRef(current, workInProgress);
      reconcileChildren(current, workInProgress, lazyComponent, renderLanes);
      return workInProgress.child;
    case 6:
      if (null === current && isHydrating) {
        if ((current = renderLanes = nextHydratableInstance))
          (renderLanes = canHydrateTextInstance(
            renderLanes,
            workInProgress.pendingProps,
            rootOrSingletonContext
          )),
            null !== renderLanes
              ? ((workInProgress.stateNode = renderLanes),
                (hydrationParentFiber = workInProgress),
                (nextHydratableInstance = null),
                (current = !0))
              : (current = !1);
        current || throwOnHydrationMismatch(workInProgress);
      }
      return null;
    case 13:
      return updateSuspenseComponent(current, workInProgress, renderLanes);
    case 4:
      return (
        pushHostContainer(
          workInProgress,
          workInProgress.stateNode.containerInfo
        ),
        (lazyComponent = workInProgress.pendingProps),
        null === current
          ? (workInProgress.child = reconcileChildFibers(
              workInProgress,
              null,
              lazyComponent,
              renderLanes
            ))
          : reconcileChildren(
              current,
              workInProgress,
              lazyComponent,
              renderLanes
            ),
        workInProgress.child
      );
    case 11:
      return updateForwardRef(
        current,
        workInProgress,
        workInProgress.type,
        workInProgress.pendingProps,
        renderLanes
      );
    case 7:
      return (
        reconcileChildren(
          current,
          workInProgress,
          workInProgress.pendingProps,
          renderLanes
        ),
        workInProgress.child
      );
    case 8:
      return (
        reconcileChildren(
          current,
          workInProgress,
          workInProgress.pendingProps.children,
          renderLanes
        ),
        workInProgress.child
      );
    case 12:
      return (
        reconcileChildren(
          current,
          workInProgress,
          workInProgress.pendingProps.children,
          renderLanes
        ),
        workInProgress.child
      );
    case 10:
      return (
        (lazyComponent = workInProgress.pendingProps),
        pushProvider(workInProgress, workInProgress.type, lazyComponent.value),
        reconcileChildren(
          current,
          workInProgress,
          lazyComponent.children,
          renderLanes
        ),
        workInProgress.child
      );
    case 9:
      return (
        (init = workInProgress.type._context),
        (lazyComponent = workInProgress.pendingProps.children),
        prepareToReadContext(workInProgress),
        (init = readContext(init)),
        (lazyComponent = lazyComponent(init)),
        (workInProgress.flags |= 1),
        reconcileChildren(current, workInProgress, lazyComponent, renderLanes),
        workInProgress.child
      );
    case 14:
      return updateMemoComponent(
        current,
        workInProgress,
        workInProgress.type,
        workInProgress.pendingProps,
        renderLanes
      );
    case 15:
      return updateSimpleMemoComponent(
        current,
        workInProgress,
        workInProgress.type,
        workInProgress.pendingProps,
        renderLanes
      );
    case 19:
      return updateSuspenseListComponent(current, workInProgress, renderLanes);
    case 22:
      return updateOffscreenComponent(current, workInProgress, renderLanes);
    case 24:
      return (
        prepareToReadContext(workInProgress),
        (lazyComponent = readContext(CacheContext)),
        null === current
          ? ((init = peekCacheFromPool()),
            null === init &&
              ((init = workInProgressRoot),
              (nextProps = createCache()),
              (init.pooledCache = nextProps),
              nextProps.refCount++,
              null !== nextProps && (init.pooledCacheLanes |= renderLanes),
              (init = nextProps)),
            (workInProgress.memoizedState = {
              parent: lazyComponent,
              cache: init
            }),
            initializeUpdateQueue(workInProgress),
            pushProvider(workInProgress, CacheContext, init))
          : (0 !== (current.lanes & renderLanes) &&
              (cloneUpdateQueue(current, workInProgress),
              processUpdateQueue(workInProgress, null, null, renderLanes),
              suspendIfUpdateReadFromEntangledAsyncAction()),
            (init = current.memoizedState),
            (nextProps = workInProgress.memoizedState),
            init.parent !== lazyComponent
              ? ((init = { parent: lazyComponent, cache: lazyComponent }),
                (workInProgress.memoizedState = init),
                0 === workInProgress.lanes &&
                  (workInProgress.memoizedState =
                    workInProgress.updateQueue.baseState =
                      init),
                pushProvider(workInProgress, CacheContext, lazyComponent))
              : ((lazyComponent = nextProps.cache),
                pushProvider(workInProgress, CacheContext, lazyComponent),
                lazyComponent !== init.cache &&
                  propagateContextChanges(
                    workInProgress,
                    [CacheContext],
                    renderLanes,
                    !0
                  ))),
        reconcileChildren(
          current,
          workInProgress,
          workInProgress.pendingProps.children,
          renderLanes
        ),
        workInProgress.child
      );
    case 29:
      throw workInProgress.pendingProps;
  }
  throw Error(formatProdErrorMessage(156, workInProgress.tag));
}
var valueCursor = createCursor(null),
  currentlyRenderingFiber = null,
  lastContextDependency = null;
function pushProvider(providerFiber, context, nextValue) {
  push(valueCursor, context._currentValue);
  context._currentValue = nextValue;
}
function popProvider(context) {
  context._currentValue = valueCursor.current;
  pop(valueCursor);
}
function scheduleContextWorkOnParentPath(parent, renderLanes, propagationRoot) {
  for (; null !== parent; ) {
    var alternate = parent.alternate;
    (parent.childLanes & renderLanes) !== renderLanes
      ? ((parent.childLanes |= renderLanes),
        null !== alternate && (alternate.childLanes |= renderLanes))
      : null !== alternate &&
        (alternate.childLanes & renderLanes) !== renderLanes &&
        (alternate.childLanes |= renderLanes);
    if (parent === propagationRoot) break;
    parent = parent.return;
  }
}
function propagateContextChanges(
  workInProgress,
  contexts,
  renderLanes,
  forcePropagateEntireTree
) {
  var fiber = workInProgress.child;
  null !== fiber && (fiber.return = workInProgress);
  for (; null !== fiber; ) {
    var list = fiber.dependencies;
    if (null !== list) {
      var nextFiber = fiber.child;
      list = list.firstContext;
      a: for (; null !== list; ) {
        var dependency = list;
        list = fiber;
        for (var i = 0; i < contexts.length; i++)
          if (dependency.context === contexts[i]) {
            list.lanes |= renderLanes;
            dependency = list.alternate;
            null !== dependency && (dependency.lanes |= renderLanes);
            scheduleContextWorkOnParentPath(
              list.return,
              renderLanes,
              workInProgress
            );
            forcePropagateEntireTree || (nextFiber = null);
            break a;
          }
        list = dependency.next;
      }
    } else if (18 === fiber.tag) {
      nextFiber = fiber.return;
      if (null === nextFiber) throw Error(formatProdErrorMessage(341));
      nextFiber.lanes |= renderLanes;
      list = nextFiber.alternate;
      null !== list && (list.lanes |= renderLanes);
      scheduleContextWorkOnParentPath(nextFiber, renderLanes, workInProgress);
      nextFiber = null;
    } else nextFiber = fiber.child;
    if (null !== nextFiber) nextFiber.return = fiber;
    else
      for (nextFiber = fiber; null !== nextFiber; ) {
        if (nextFiber === workInProgress) {
          nextFiber = null;
          break;
        }
        fiber = nextFiber.sibling;
        if (null !== fiber) {
          fiber.return = nextFiber.return;
          nextFiber = fiber;
          break;
        }
        nextFiber = nextFiber.return;
      }
    fiber = nextFiber;
  }
}
function propagateParentContextChanges(
  current,
  workInProgress,
  renderLanes,
  forcePropagateEntireTree
) {
  current = null;
  for (
    var parent = workInProgress, isInsidePropagationBailout = !1;
    null !== parent;

  ) {
    if (!isInsidePropagationBailout)
      if (0 !== (parent.flags & 524288)) isInsidePropagationBailout = !0;
      else if (0 !== (parent.flags & 262144)) break;
    if (10 === parent.tag) {
      var currentParent = parent.alternate;
      if (null === currentParent) throw Error(formatProdErrorMessage(387));
      currentParent = currentParent.memoizedProps;
      if (null !== currentParent) {
        var context = parent.type;
        objectIs(parent.pendingProps.value, currentParent.value) ||
          (null !== current ? current.push(context) : (current = [context]));
      }
    } else if (parent === hostTransitionProviderCursor.current) {
      currentParent = parent.alternate;
      if (null === currentParent) throw Error(formatProdErrorMessage(387));
      currentParent.memoizedState.memoizedState !==
        parent.memoizedState.memoizedState &&
        (null !== current
          ? current.push(HostTransitionContext)
          : (current = [HostTransitionContext]));
    }
    parent = parent.return;
  }
  null !== current &&
    propagateContextChanges(
      workInProgress,
      current,
      renderLanes,
      forcePropagateEntireTree
    );
  workInProgress.flags |= 262144;
}
function checkIfContextChanged(currentDependencies) {
  for (
    currentDependencies = currentDependencies.firstContext;
    null !== currentDependencies;

  ) {
    if (
      !objectIs(
        currentDependencies.context._currentValue,
        currentDependencies.memoizedValue
      )
    )
      return !0;
    currentDependencies = currentDependencies.next;
  }
  return !1;
}
function prepareToReadContext(workInProgress) {
  currentlyRenderingFiber = workInProgress;
  lastContextDependency = null;
  workInProgress = workInProgress.dependencies;
  null !== workInProgress && (workInProgress.firstContext = null);
}
function readContext(context) {
  return readContextForConsumer(currentlyRenderingFiber, context);
}
function readContextDuringReconciliation(consumer, context) {
  null === currentlyRenderingFiber && prepareToReadContext(consumer);
  return readContextForConsumer(consumer, context);
}
function readContextForConsumer(consumer, context) {
  var value = context._currentValue;
  context = { context: context, memoizedValue: value, next: null };
  if (null === lastContextDependency) {
    if (null === consumer) throw Error(formatProdErrorMessage(308));
    lastContextDependency = context;
    consumer.dependencies = { lanes: 0, firstContext: context };
    consumer.flags |= 524288;
  } else lastContextDependency = lastContextDependency.next = context;
  return value;
}
var hasForceUpdate = !1;
function initializeUpdateQueue(fiber) {
  fiber.updateQueue = {
    baseState: fiber.memoizedState,
    firstBaseUpdate: null,
    lastBaseUpdate: null,
    shared: { pending: null, lanes: 0, hiddenCallbacks: null },
    callbacks: null
  };
}
function cloneUpdateQueue(current, workInProgress) {
  current = current.updateQueue;
  workInProgress.updateQueue === current &&
    (workInProgress.updateQueue = {
      baseState: current.baseState,
      firstBaseUpdate: current.firstBaseUpdate,
      lastBaseUpdate: current.lastBaseUpdate,
      shared: current.shared,
      callbacks: null
    });
}
function createUpdate(lane) {
  return { lane: lane, tag: 0, payload: null, callback: null, next: null };
}
function enqueueUpdate(fiber, update, lane) {
  var updateQueue = fiber.updateQueue;
  if (null === updateQueue) return null;
  updateQueue = updateQueue.shared;
  if (0 !== (executionContext & 2)) {
    var pending = updateQueue.pending;
    null === pending
      ? (update.next = update)
      : ((update.next = pending.next), (pending.next = update));
    updateQueue.pending = update;
    update = getRootForUpdatedFiber(fiber);
    markUpdateLaneFromFiberToRoot(fiber, null, lane);
    return update;
  }
  enqueueUpdate$1(fiber, updateQueue, update, lane);
  return getRootForUpdatedFiber(fiber);
}
function entangleTransitions(root, fiber, lane) {
  fiber = fiber.updateQueue;
  if (null !== fiber && ((fiber = fiber.shared), 0 !== (lane & 4194176))) {
    var queueLanes = fiber.lanes;
    queueLanes &= root.pendingLanes;
    lane |= queueLanes;
    fiber.lanes = lane;
    markRootEntangled(root, lane);
  }
}
function enqueueCapturedUpdate(workInProgress, capturedUpdate) {
  var queue = workInProgress.updateQueue,
    current = workInProgress.alternate;
  if (
    null !== current &&
    ((current = current.updateQueue), queue === current)
  ) {
    var newFirst = null,
      newLast = null;
    queue = queue.firstBaseUpdate;
    if (null !== queue) {
      do {
        var clone = {
          lane: queue.lane,
          tag: queue.tag,
          payload: queue.payload,
          callback: null,
          next: null
        };
        null === newLast
          ? (newFirst = newLast = clone)
          : (newLast = newLast.next = clone);
        queue = queue.next;
      } while (null !== queue);
      null === newLast
        ? (newFirst = newLast = capturedUpdate)
        : (newLast = newLast.next = capturedUpdate);
    } else newFirst = newLast = capturedUpdate;
    queue = {
      baseState: current.baseState,
      firstBaseUpdate: newFirst,
      lastBaseUpdate: newLast,
      shared: current.shared,
      callbacks: current.callbacks
    };
    workInProgress.updateQueue = queue;
    return;
  }
  workInProgress = queue.lastBaseUpdate;
  null === workInProgress
    ? (queue.firstBaseUpdate = capturedUpdate)
    : (workInProgress.next = capturedUpdate);
  queue.lastBaseUpdate = capturedUpdate;
}
var didReadFromEntangledAsyncAction = !1;
function suspendIfUpdateReadFromEntangledAsyncAction() {
  if (didReadFromEntangledAsyncAction) {
    var entangledActionThenable = currentEntangledActionThenable;
    if (null !== entangledActionThenable) throw entangledActionThenable;
  }
}
function processUpdateQueue(
  workInProgress$jscomp$0,
  props,
  instance$jscomp$0,
  renderLanes
) {
  didReadFromEntangledAsyncAction = !1;
  var queue = workInProgress$jscomp$0.updateQueue;
  hasForceUpdate = !1;
  var firstBaseUpdate = queue.firstBaseUpdate,
    lastBaseUpdate = queue.lastBaseUpdate,
    pendingQueue = queue.shared.pending;
  if (null !== pendingQueue) {
    queue.shared.pending = null;
    var lastPendingUpdate = pendingQueue,
      firstPendingUpdate = lastPendingUpdate.next;
    lastPendingUpdate.next = null;
    null === lastBaseUpdate
      ? (firstBaseUpdate = firstPendingUpdate)
      : (lastBaseUpdate.next = firstPendingUpdate);
    lastBaseUpdate = lastPendingUpdate;
    var current = workInProgress$jscomp$0.alternate;
    null !== current &&
      ((current = current.updateQueue),
      (pendingQueue = current.lastBaseUpdate),
      pendingQueue !== lastBaseUpdate &&
        (null === pendingQueue
          ? (current.firstBaseUpdate = firstPendingUpdate)
          : (pendingQueue.next = firstPendingUpdate),
        (current.lastBaseUpdate = lastPendingUpdate)));
  }
  if (null !== firstBaseUpdate) {
    var newState = queue.baseState;
    lastBaseUpdate = 0;
    current = firstPendingUpdate = lastPendingUpdate = null;
    pendingQueue = firstBaseUpdate;
    do {
      var updateLane = pendingQueue.lane & -536870913,
        isHiddenUpdate = updateLane !== pendingQueue.lane;
      if (
        isHiddenUpdate
          ? (workInProgressRootRenderLanes & updateLane) === updateLane
          : (renderLanes & updateLane) === updateLane
      ) {
        0 !== updateLane &&
          updateLane === currentEntangledLane &&
          (didReadFromEntangledAsyncAction = !0);
        null !== current &&
          (current = current.next =
            {
              lane: 0,
              tag: pendingQueue.tag,
              payload: pendingQueue.payload,
              callback: null,
              next: null
            });
        a: {
          var workInProgress = workInProgress$jscomp$0,
            update = pendingQueue;
          updateLane = props;
          var instance = instance$jscomp$0;
          switch (update.tag) {
            case 1:
              workInProgress = update.payload;
              if ("function" === typeof workInProgress) {
                newState = workInProgress.call(instance, newState, updateLane);
                break a;
              }
              newState = workInProgress;
              break a;
            case 3:
              workInProgress.flags = (workInProgress.flags & -65537) | 128;
            case 0:
              workInProgress = update.payload;
              updateLane =
                "function" === typeof workInProgress
                  ? workInProgress.call(instance, newState, updateLane)
                  : workInProgress;
              if (null === updateLane || void 0 === updateLane) break a;
              newState = assign({}, newState, updateLane);
              break a;
            case 2:
              hasForceUpdate = !0;
          }
        }
        updateLane = pendingQueue.callback;
        null !== updateLane &&
          ((workInProgress$jscomp$0.flags |= 64),
          isHiddenUpdate && (workInProgress$jscomp$0.flags |= 8192),
          (isHiddenUpdate = queue.callbacks),
          null === isHiddenUpdate
            ? (queue.callbacks = [updateLane])
            : isHiddenUpdate.push(updateLane));
      } else
        (isHiddenUpdate = {
          lane: updateLane,
          tag: pendingQueue.tag,
          payload: pendingQueue.payload,
          callback: pendingQueue.callback,
          next: null
        }),
          null === current
            ? ((firstPendingUpdate = current = isHiddenUpdate),
              (lastPendingUpdate = newState))
            : (current = current.next = isHiddenUpdate),
          (lastBaseUpdate |= updateLane);
      pendingQueue = pendingQueue.next;
      if (null === pendingQueue)
        if (((pendingQueue = queue.shared.pending), null === pendingQueue))
          break;
        else
          (isHiddenUpdate = pendingQueue),
            (pendingQueue = isHiddenUpdate.next),
            (isHiddenUpdate.next = null),
            (queue.lastBaseUpdate = isHiddenUpdate),
            (queue.shared.pending = null);
    } while (1);
    null === current && (lastPendingUpdate = newState);
    queue.baseState = lastPendingUpdate;
    queue.firstBaseUpdate = firstPendingUpdate;
    queue.lastBaseUpdate = current;
    null === firstBaseUpdate && (queue.shared.lanes = 0);
    workInProgressRootSkippedLanes |= lastBaseUpdate;
    workInProgress$jscomp$0.lanes = lastBaseUpdate;
    workInProgress$jscomp$0.memoizedState = newState;
  }
}
function callCallback(callback, context) {
  if ("function" !== typeof callback)
    throw Error(formatProdErrorMessage(191, callback));
  callback.call(context);
}
function commitCallbacks(updateQueue, context) {
  var callbacks = updateQueue.callbacks;
  if (null !== callbacks)
    for (
      updateQueue.callbacks = null, updateQueue = 0;
      updateQueue < callbacks.length;
      updateQueue++
    )
      callCallback(callbacks[updateQueue], context);
}
function commitHookEffectListMount(flags, finishedWork) {
  try {
    var updateQueue = finishedWork.updateQueue,
      lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
    if (null !== lastEffect) {
      var firstEffect = lastEffect.next;
      updateQueue = firstEffect;
      do {
        if ((updateQueue.tag & flags) === flags) {
          lastEffect = void 0;
          var create = updateQueue.create,
            inst = updateQueue.inst;
          lastEffect = create();
          inst.destroy = lastEffect;
        }
        updateQueue = updateQueue.next;
      } while (updateQueue !== firstEffect);
    }
  } catch (error) {
    captureCommitPhaseError(finishedWork, finishedWork.return, error);
  }
}
function commitHookEffectListUnmount(
  flags,
  finishedWork,
  nearestMountedAncestor$jscomp$0
) {
  try {
    var updateQueue = finishedWork.updateQueue,
      lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
    if (null !== lastEffect) {
      var firstEffect = lastEffect.next;
      updateQueue = firstEffect;
      do {
        if ((updateQueue.tag & flags) === flags) {
          var inst = updateQueue.inst,
            destroy = inst.destroy;
          if (void 0 !== destroy) {
            inst.destroy = void 0;
            lastEffect = finishedWork;
            var nearestMountedAncestor = nearestMountedAncestor$jscomp$0;
            try {
              destroy();
            } catch (error) {
              captureCommitPhaseError(
                lastEffect,
                nearestMountedAncestor,
                error
              );
            }
          }
        }
        updateQueue = updateQueue.next;
      } while (updateQueue !== firstEffect);
    }
  } catch (error) {
    captureCommitPhaseError(finishedWork, finishedWork.return, error);
  }
}
function commitClassCallbacks(finishedWork) {
  var updateQueue = finishedWork.updateQueue;
  if (null !== updateQueue) {
    var instance = finishedWork.stateNode;
    try {
      commitCallbacks(updateQueue, instance);
    } catch (error) {
      captureCommitPhaseError(finishedWork, finishedWork.return, error);
    }
  }
}
function safelyCallComponentWillUnmount(
  current,
  nearestMountedAncestor,
  instance
) {
  instance.props = resolveClassComponentProps(
    current.type,
    current.memoizedProps
  );
  instance.state = current.memoizedState;
  try {
    instance.componentWillUnmount();
  } catch (error) {
    captureCommitPhaseError(current, nearestMountedAncestor, error);
  }
}
function safelyAttachRef(current, nearestMountedAncestor) {
  try {
    var ref = current.ref;
    if (null !== ref) {
      var instance = current.stateNode;
      switch (current.tag) {
        case 26:
        case 27:
        case 5:
          var instanceToUse = instance;
          break;
        default:
          instanceToUse = instance;
      }
      "function" === typeof ref
        ? (current.refCleanup = ref(instanceToUse))
        : (ref.current = instanceToUse);
    }
  } catch (error) {
    captureCommitPhaseError(current, nearestMountedAncestor, error);
  }
}
function safelyDetachRef(current, nearestMountedAncestor) {
  var ref = current.ref,
    refCleanup = current.refCleanup;
  if (null !== ref)
    if ("function" === typeof refCleanup)
      try {
        refCleanup();
      } catch (error) {
        captureCommitPhaseError(current, nearestMountedAncestor, error);
      } finally {
        (current.refCleanup = null),
          (current = current.alternate),
          null != current && (current.refCleanup = null);
      }
    else if ("function" === typeof ref)
      try {
        ref(null);
      } catch (error$112) {
        captureCommitPhaseError(current, nearestMountedAncestor, error$112);
      }
    else ref.current = null;
}
function commitHostMount(finishedWork) {
  var type = finishedWork.type,
    props = finishedWork.memoizedProps,
    instance = finishedWork.stateNode;
  try {
    a: switch (type) {
      case "button":
      case "input":
      case "select":
      case "textarea":
        props.autoFocus && instance.focus();
        break a;
      case "img":
        props.src
          ? (instance.src = props.src)
          : props.srcSet && (instance.srcset = props.srcSet);
    }
  } catch (error) {
    captureCommitPhaseError(finishedWork, finishedWork.return, error);
  }
}
function commitHostUpdate(finishedWork, newProps, oldProps) {
  try {
    var domElement = finishedWork.stateNode;
    updateProperties(domElement, finishedWork.type, oldProps, newProps);
    domElement[internalPropsKey] = newProps;
  } catch (error) {
    captureCommitPhaseError(finishedWork, finishedWork.return, error);
  }
}
function isHostParent(fiber) {
  return (
    5 === fiber.tag ||
    3 === fiber.tag ||
    26 === fiber.tag ||
    27 === fiber.tag ||
    4 === fiber.tag
  );
}
function getHostSibling(fiber) {
  a: for (;;) {
    for (; null === fiber.sibling; ) {
      if (null === fiber.return || isHostParent(fiber.return)) return null;
      fiber = fiber.return;
    }
    fiber.sibling.return = fiber.return;
    for (
      fiber = fiber.sibling;
      5 !== fiber.tag &&
      6 !== fiber.tag &&
      27 !== fiber.tag &&
      18 !== fiber.tag;

    ) {
      if (fiber.flags & 2) continue a;
      if (null === fiber.child || 4 === fiber.tag) continue a;
      else (fiber.child.return = fiber), (fiber = fiber.child);
    }
    if (!(fiber.flags & 2)) return fiber.stateNode;
  }
}
function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
  var tag = node.tag;
  if (5 === tag || 6 === tag)
    (node = node.stateNode),
      before
        ? 8 === parent.nodeType
          ? parent.parentNode.insertBefore(node, before)
          : parent.insertBefore(node, before)
        : (8 === parent.nodeType
            ? ((before = parent.parentNode), before.insertBefore(node, parent))
            : ((before = parent), before.appendChild(node)),
          (parent = parent._reactRootContainer),
          (null !== parent && void 0 !== parent) ||
            null !== before.onclick ||
            (before.onclick = noop$1));
  else if (4 !== tag && 27 !== tag && ((node = node.child), null !== node))
    for (
      insertOrAppendPlacementNodeIntoContainer(node, before, parent),
        node = node.sibling;
      null !== node;

    )
      insertOrAppendPlacementNodeIntoContainer(node, before, parent),
        (node = node.sibling);
}
function insertOrAppendPlacementNode(node, before, parent) {
  var tag = node.tag;
  if (5 === tag || 6 === tag)
    (node = node.stateNode),
      before ? parent.insertBefore(node, before) : parent.appendChild(node);
  else if (4 !== tag && 27 !== tag && ((node = node.child), null !== node))
    for (
      insertOrAppendPlacementNode(node, before, parent), node = node.sibling;
      null !== node;

    )
      insertOrAppendPlacementNode(node, before, parent), (node = node.sibling);
}
var offscreenSubtreeIsHidden = !1,
  offscreenSubtreeWasHidden = !1,
  needsFormReset = !1,
  PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set,
  nextEffect = null,
  shouldFireAfterActiveInstanceBlur = !1;
function commitBeforeMutationEffects(root, firstChild) {
  root = root.containerInfo;
  eventsEnabled = _enabled;
  root = getActiveElementDeep(root);
  if (hasSelectionCapabilities(root)) {
    if ("selectionStart" in root)
      var JSCompiler_temp = {
        start: root.selectionStart,
        end: root.selectionEnd
      };
    else
      a: {
        JSCompiler_temp =
          ((JSCompiler_temp = root.ownerDocument) &&
            JSCompiler_temp.defaultView) ||
          window;
        var selection =
          JSCompiler_temp.getSelection && JSCompiler_temp.getSelection();
        if (selection && 0 !== selection.rangeCount) {
          JSCompiler_temp = selection.anchorNode;
          var anchorOffset = selection.anchorOffset,
            focusNode = selection.focusNode;
          selection = selection.focusOffset;
          try {
            JSCompiler_temp.nodeType, focusNode.nodeType;
          } catch (e$20) {
            JSCompiler_temp = null;
            break a;
          }
          var length = 0,
            start = -1,
            end = -1,
            indexWithinAnchor = 0,
            indexWithinFocus = 0,
            node = root,
            parentNode = null;
          b: for (;;) {
            for (var next; ; ) {
              node !== JSCompiler_temp ||
                (0 !== anchorOffset && 3 !== node.nodeType) ||
                (start = length + anchorOffset);
              node !== focusNode ||
                (0 !== selection && 3 !== node.nodeType) ||
                (end = length + selection);
              3 === node.nodeType && (length += node.nodeValue.length);
              if (null === (next = node.firstChild)) break;
              parentNode = node;
              node = next;
            }
            for (;;) {
              if (node === root) break b;
              parentNode === JSCompiler_temp &&
                ++indexWithinAnchor === anchorOffset &&
                (start = length);
              parentNode === focusNode &&
                ++indexWithinFocus === selection &&
                (end = length);
              if (null !== (next = node.nextSibling)) break;
              node = parentNode;
              parentNode = node.parentNode;
            }
            node = next;
          }
          JSCompiler_temp =
            -1 === start || -1 === end ? null : { start: start, end: end };
        } else JSCompiler_temp = null;
      }
    JSCompiler_temp = JSCompiler_temp || { start: 0, end: 0 };
  } else JSCompiler_temp = null;
  selectionInformation = { focusedElem: root, selectionRange: JSCompiler_temp };
  _enabled = !1;
  for (nextEffect = firstChild; null !== nextEffect; )
    if (
      ((firstChild = nextEffect),
      (root = firstChild.child),
      0 !== (firstChild.subtreeFlags & 1028) && null !== root)
    )
      (root.return = firstChild), (nextEffect = root);
    else
      for (; null !== nextEffect; ) {
        firstChild = nextEffect;
        focusNode = firstChild.alternate;
        root = firstChild.flags;
        switch (firstChild.tag) {
          case 0:
            break;
          case 11:
          case 15:
            break;
          case 1:
            if (0 !== (root & 1024) && null !== focusNode) {
              root = void 0;
              JSCompiler_temp = firstChild;
              anchorOffset = focusNode.memoizedProps;
              focusNode = focusNode.memoizedState;
              selection = JSCompiler_temp.stateNode;
              try {
                var resolvedPrevProps = resolveClassComponentProps(
                  JSCompiler_temp.type,
                  anchorOffset,
                  JSCompiler_temp.elementType === JSCompiler_temp.type
                );
                root = selection.getSnapshotBeforeUpdate(
                  resolvedPrevProps,
                  focusNode
                );
                selection.__reactInternalSnapshotBeforeUpdate = root;
              } catch (error) {
                captureCommitPhaseError(
                  JSCompiler_temp,
                  JSCompiler_temp.return,
                  error
                );
              }
            }
            break;
          case 3:
            if (0 !== (root & 1024))
              if (
                ((root = firstChild.stateNode.containerInfo),
                (JSCompiler_temp = root.nodeType),
                9 === JSCompiler_temp)
              )
                clearContainerSparingly(root);
              else if (1 === JSCompiler_temp)
                switch (root.nodeName) {
                  case "HEAD":
                  case "HTML":
                  case "BODY":
                    clearContainerSparingly(root);
                    break;
                  default:
                    root.textContent = "";
                }
            break;
          case 5:
          case 26:
          case 27:
          case 6:
          case 4:
          case 17:
            break;
          default:
            if (0 !== (root & 1024)) throw Error(formatProdErrorMessage(163));
        }
        root = firstChild.sibling;
        if (null !== root) {
          root.return = firstChild.return;
          nextEffect = root;
          break;
        }
        nextEffect = firstChild.return;
      }
  resolvedPrevProps = shouldFireAfterActiveInstanceBlur;
  shouldFireAfterActiveInstanceBlur = !1;
  return resolvedPrevProps;
}
function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) {
  var flags = finishedWork.flags;
  switch (finishedWork.tag) {
    case 0:
    case 11:
    case 15:
      recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
      flags & 4 && commitHookEffectListMount(5, finishedWork);
      break;
    case 1:
      recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
      if (flags & 4)
        if (((finishedRoot = finishedWork.stateNode), null === current))
          try {
            finishedRoot.componentDidMount();
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        else {
          var prevProps = resolveClassComponentProps(
            finishedWork.type,
            current.memoizedProps
          );
          current = current.memoizedState;
          try {
            finishedRoot.componentDidUpdate(
              prevProps,
              current,
              finishedRoot.__reactInternalSnapshotBeforeUpdate
            );
          } catch (error$111) {
            captureCommitPhaseError(
              finishedWork,
              finishedWork.return,
              error$111
            );
          }
        }
      flags & 64 && commitClassCallbacks(finishedWork);
      flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
      break;
    case 3:
      recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
      if (flags & 64 && ((flags = finishedWork.updateQueue), null !== flags)) {
        finishedRoot = null;
        if (null !== finishedWork.child)
          switch (finishedWork.child.tag) {
            case 27:
            case 5:
              finishedRoot = finishedWork.child.stateNode;
              break;
            case 1:
              finishedRoot = finishedWork.child.stateNode;
          }
        try {
          commitCallbacks(flags, finishedRoot);
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      break;
    case 26:
      recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
      flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
      break;
    case 27:
    case 5:
      recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
      null === current && flags & 4 && commitHostMount(finishedWork);
      flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
      break;
    case 12:
      recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
      break;
    case 13:
      recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
      flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
      break;
    case 22:
      prevProps =
        null !== finishedWork.memoizedState || offscreenSubtreeIsHidden;
      if (!prevProps) {
        current =
          (null !== current && null !== current.memoizedState) ||
          offscreenSubtreeWasHidden;
        var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden,
          prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
        offscreenSubtreeIsHidden = prevProps;
        (offscreenSubtreeWasHidden = current) && !prevOffscreenSubtreeWasHidden
          ? recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              0 !== (finishedWork.subtreeFlags & 8772)
            )
          : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
        offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
        offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
      }
      flags & 512 &&
        ("manual" === finishedWork.memoizedProps.mode
          ? safelyAttachRef(finishedWork, finishedWork.return)
          : safelyDetachRef(finishedWork, finishedWork.return));
      break;
    default:
      recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
  }
}
function detachFiberAfterEffects(fiber) {
  var alternate = fiber.alternate;
  null !== alternate &&
    ((fiber.alternate = null), detachFiberAfterEffects(alternate));
  fiber.child = null;
  fiber.deletions = null;
  fiber.sibling = null;
  5 === fiber.tag &&
    ((alternate = fiber.stateNode),
    null !== alternate && detachDeletedInstance(alternate));
  fiber.stateNode = null;
  fiber.return = null;
  fiber.dependencies = null;
  fiber.memoizedProps = null;
  fiber.memoizedState = null;
  fiber.pendingProps = null;
  fiber.stateNode = null;
  fiber.updateQueue = null;
}
var hostParent = null,
  hostParentIsContainer = !1;
function recursivelyTraverseDeletionEffects(
  finishedRoot,
  nearestMountedAncestor,
  parent
) {
  for (parent = parent.child; null !== parent; )
    commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent),
      (parent = parent.sibling);
}
function commitDeletionEffectsOnFiber(
  finishedRoot,
  nearestMountedAncestor,
  deletedFiber
) {
  if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount)
    try {
      injectedHook.onCommitFiberUnmount(rendererID, deletedFiber);
    } catch (err) {}
  switch (deletedFiber.tag) {
    case 26:
      offscreenSubtreeWasHidden ||
        safelyDetachRef(deletedFiber, nearestMountedAncestor);
      recursivelyTraverseDeletionEffects(
        finishedRoot,
        nearestMountedAncestor,
        deletedFiber
      );
      deletedFiber.memoizedState
        ? deletedFiber.memoizedState.count--
        : deletedFiber.stateNode &&
          ((deletedFiber = deletedFiber.stateNode),
          deletedFiber.parentNode.removeChild(deletedFiber));
      break;
    case 27:
      offscreenSubtreeWasHidden ||
        safelyDetachRef(deletedFiber, nearestMountedAncestor);
      var prevHostParent = hostParent,
        prevHostParentIsContainer = hostParentIsContainer;
      hostParent = deletedFiber.stateNode;
      recursivelyTraverseDeletionEffects(
        finishedRoot,
        nearestMountedAncestor,
        deletedFiber
      );
      deletedFiber = deletedFiber.stateNode;
      for (
        nearestMountedAncestor = deletedFiber.attributes;
        nearestMountedAncestor.length;

      )
        deletedFiber.removeAttributeNode(nearestMountedAncestor[0]);
      detachDeletedInstance(deletedFiber);
      hostParent = prevHostParent;
      hostParentIsContainer = prevHostParentIsContainer;
      break;
    case 5:
      offscreenSubtreeWasHidden ||
        safelyDetachRef(deletedFiber, nearestMountedAncestor);
    case 6:
      prevHostParentIsContainer = hostParent;
      var prevHostParentIsContainer$119 = hostParentIsContainer;
      hostParent = null;
      recursivelyTraverseDeletionEffects(
        finishedRoot,
        nearestMountedAncestor,
        deletedFiber
      );
      hostParent = prevHostParentIsContainer;
      hostParentIsContainer = prevHostParentIsContainer$119;
      if (null !== hostParent)
        if (hostParentIsContainer)
          try {
            (finishedRoot = hostParent),
              (prevHostParent = deletedFiber.stateNode),
              8 === finishedRoot.nodeType
                ? finishedRoot.parentNode.removeChild(prevHostParent)
                : finishedRoot.removeChild(prevHostParent);
          } catch (error) {
            captureCommitPhaseError(
              deletedFiber,
              nearestMountedAncestor,
              error
            );
          }
        else
          try {
            hostParent.removeChild(deletedFiber.stateNode);
          } catch (error) {
            captureCommitPhaseError(
              deletedFiber,
              nearestMountedAncestor,
              error
            );
          }
      break;
    case 18:
      null !== hostParent &&
        (hostParentIsContainer
          ? ((nearestMountedAncestor = hostParent),
            (deletedFiber = deletedFiber.stateNode),
            8 === nearestMountedAncestor.nodeType
              ? clearSuspenseBoundary(
                  nearestMountedAncestor.parentNode,
                  deletedFiber
                )
              : 1 === nearestMountedAncestor.nodeType &&
                clearSuspenseBoundary(nearestMountedAncestor, deletedFiber),
            retryIfBlockedOn(nearestMountedAncestor))
          : clearSuspenseBoundary(hostParent, deletedFiber.stateNode));
      break;
    case 4:
      prevHostParent = hostParent;
      prevHostParentIsContainer = hostParentIsContainer;
      hostParent = deletedFiber.stateNode.containerInfo;
      hostParentIsContainer = !0;
      recursivelyTraverseDeletionEffects(
        finishedRoot,
        nearestMountedAncestor,
        deletedFiber
      );
      hostParent = prevHostParent;
      hostParentIsContainer = prevHostParentIsContainer;
      break;
    case 0:
    case 11:
    case 14:
    case 15:
      offscreenSubtreeWasHidden ||
        commitHookEffectListUnmount(2, deletedFiber, nearestMountedAncestor);
      offscreenSubtreeWasHidden ||
        commitHookEffectListUnmount(4, deletedFiber, nearestMountedAncestor);
      recursivelyTraverseDeletionEffects(
        finishedRoot,
        nearestMountedAncestor,
        deletedFiber
      );
      break;
    case 1:
      offscreenSubtreeWasHidden ||
        (safelyDetachRef(deletedFiber, nearestMountedAncestor),
        (prevHostParent = deletedFiber.stateNode),
        "function" === typeof prevHostParent.componentWillUnmount &&
          safelyCallComponentWillUnmount(
            deletedFiber,
            nearestMountedAncestor,
            prevHostParent
          ));
      recursivelyTraverseDeletionEffects(
        finishedRoot,
        nearestMountedAncestor,
        deletedFiber
      );
      break;
    case 21:
      recursivelyTraverseDeletionEffects(
        finishedRoot,
        nearestMountedAncestor,
        deletedFiber
      );
      break;
    case 22:
      offscreenSubtreeWasHidden ||
        safelyDetachRef(deletedFiber, nearestMountedAncestor);
      offscreenSubtreeWasHidden =
        (prevHostParent = offscreenSubtreeWasHidden) ||
        null !== deletedFiber.memoizedState;
      recursivelyTraverseDeletionEffects(
        finishedRoot,
        nearestMountedAncestor,
        deletedFiber
      );
      offscreenSubtreeWasHidden = prevHostParent;
      break;
    default:
      recursivelyTraverseDeletionEffects(
        finishedRoot,
        nearestMountedAncestor,
        deletedFiber
      );
  }
}
function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
  if (
    null === finishedWork.memoizedState &&
    ((finishedRoot = finishedWork.alternate),
    null !== finishedRoot &&
      ((finishedRoot = finishedRoot.memoizedState),
      null !== finishedRoot &&
        ((finishedRoot = finishedRoot.dehydrated), null !== finishedRoot)))
  )
    try {
      retryIfBlockedOn(finishedRoot);
    } catch (error) {
      captureCommitPhaseError(finishedWork, finishedWork.return, error);
    }
}
function getRetryCache(finishedWork) {
  switch (finishedWork.tag) {
    case 13:
    case 19:
      var retryCache = finishedWork.stateNode;
      null === retryCache &&
        (retryCache = finishedWork.stateNode = new PossiblyWeakSet());
      return retryCache;
    case 22:
      return (
        (finishedWork = finishedWork.stateNode),
        (retryCache = finishedWork._retryCache),
        null === retryCache &&
          (retryCache = finishedWork._retryCache = new PossiblyWeakSet()),
        retryCache
      );
    default:
      throw Error(formatProdErrorMessage(435, finishedWork.tag));
  }
}
function attachSuspenseRetryListeners(finishedWork, wakeables) {
  var retryCache = getRetryCache(finishedWork);
  wakeables.forEach(function (wakeable) {
    var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
    retryCache.has(wakeable) ||
      (retryCache.add(wakeable), wakeable.then(retry, retry));
  });
}
function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) {
  var deletions = parentFiber.deletions;
  if (null !== deletions)
    for (var i = 0; i < deletions.length; i++) {
      var childToDelete = deletions[i],
        root = root$jscomp$0,
        returnFiber = parentFiber,
        parent = returnFiber;
      a: for (; null !== parent; ) {
        switch (parent.tag) {
          case 27:
          case 5:
            hostParent = parent.stateNode;
            hostParentIsContainer = !1;
            break a;
          case 3:
            hostParent = parent.stateNode.containerInfo;
            hostParentIsContainer = !0;
            break a;
          case 4:
            hostParent = parent.stateNode.containerInfo;
            hostParentIsContainer = !0;
            break a;
        }
        parent = parent.return;
      }
      if (null === hostParent) throw Error(formatProdErrorMessage(160));
      commitDeletionEffectsOnFiber(root, returnFiber, childToDelete);
      hostParent = null;
      hostParentIsContainer = !1;
      root = childToDelete.alternate;
      null !== root && (root.return = null);
      childToDelete.return = null;
    }
  if (parentFiber.subtreeFlags & 13878)
    for (parentFiber = parentFiber.child; null !== parentFiber; )
      commitMutationEffectsOnFiber(parentFiber, root$jscomp$0),
        (parentFiber = parentFiber.sibling);
}
var currentHoistableRoot = null;
function commitMutationEffectsOnFiber(finishedWork, root) {
  var current = finishedWork.alternate,
    flags = finishedWork.flags;
  switch (finishedWork.tag) {
    case 0:
    case 11:
    case 14:
    case 15:
      recursivelyTraverseMutationEffects(root, finishedWork);
      commitReconciliationEffects(finishedWork);
      flags & 4 &&
        (commitHookEffectListUnmount(3, finishedWork, finishedWork.return),
        commitHookEffectListMount(3, finishedWork),
        commitHookEffectListUnmount(5, finishedWork, finishedWork.return));
      break;
    case 1:
      recursivelyTraverseMutationEffects(root, finishedWork);
      commitReconciliationEffects(finishedWork);
      flags & 512 &&
        (offscreenSubtreeWasHidden ||
          null === current ||
          safelyDetachRef(current, current.return));
      flags & 64 &&
        offscreenSubtreeIsHidden &&
        ((finishedWork = finishedWork.updateQueue),
        null !== finishedWork &&
          ((flags = finishedWork.callbacks),
          null !== flags &&
            ((current = finishedWork.shared.hiddenCallbacks),
            (finishedWork.shared.hiddenCallbacks =
              null === current ? flags : current.concat(flags)))));
      break;
    case 26:
      var hoistableRoot = currentHoistableRoot;
      recursivelyTraverseMutationEffects(root, finishedWork);
      commitReconciliationEffects(finishedWork);
      flags & 512 &&
        (offscreenSubtreeWasHidden ||
          null === current ||
          safelyDetachRef(current, current.return));
      if (flags & 4) {
        var currentResource = null !== current ? current.memoizedState : null;
        flags = finishedWork.memoizedState;
        if (null === current)
          if (null === flags)
            if (null === finishedWork.stateNode) {
              a: {
                flags = finishedWork.type;
                current = finishedWork.memoizedProps;
                hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
                b: switch (flags) {
                  case "title":
                    currentResource =
                      hoistableRoot.getElementsByTagName("title")[0];
                    if (
                      !currentResource ||
                      currentResource[internalHoistableMarker] ||
                      currentResource[internalInstanceKey] ||
                      "http://www.w3.org/2000/svg" ===
                        currentResource.namespaceURI ||
                      currentResource.hasAttribute("itemprop")
                    )
                      (currentResource = hoistableRoot.createElement(flags)),
                        hoistableRoot.head.insertBefore(
                          currentResource,
                          hoistableRoot.querySelector("head > title")
                        );
                    setInitialProperties(currentResource, flags, current);
                    currentResource[internalInstanceKey] = finishedWork;
                    markNodeAsHoistable(currentResource);
                    flags = currentResource;
                    break a;
                  case "link":
                    var maybeNodes = getHydratableHoistableCache(
                      "link",
                      "href",
                      hoistableRoot
                    ).get(flags + (current.href || ""));
                    if (maybeNodes)
                      for (var i = 0; i < maybeNodes.length; i++)
                        if (
                          ((currentResource = maybeNodes[i]),
                          currentResource.getAttribute("href") ===
                            (null == current.href ? null : current.href) &&
                            currentResource.getAttribute("rel") ===
                              (null == current.rel ? null : current.rel) &&
                            currentResource.getAttribute("title") ===
                              (null == current.title ? null : current.title) &&
                            currentResource.getAttribute("crossorigin") ===
                              (null == current.crossOrigin
                                ? null
                                : current.crossOrigin))
                        ) {
                          maybeNodes.splice(i, 1);
                          break b;
                        }
                    currentResource = hoistableRoot.createElement(flags);
                    setInitialProperties(currentResource, flags, current);
                    hoistableRoot.head.appendChild(currentResource);
                    break;
                  case "meta":
                    if (
                      (maybeNodes = getHydratableHoistableCache(
                        "meta",
                        "content",
                        hoistableRoot
                      ).get(flags + (current.content || "")))
                    )
                      for (i = 0; i < maybeNodes.length; i++)
                        if (
                          ((currentResource = maybeNodes[i]),
                          currentResource.getAttribute("content") ===
                            (null == current.content
                              ? null
                              : "" + current.content) &&
                            currentResource.getAttribute("name") ===
                              (null == current.name ? null : current.name) &&
                            currentResource.getAttribute("property") ===
                              (null == current.property
                                ? null
                                : current.property) &&
                            currentResource.getAttribute("http-equiv") ===
                              (null == current.httpEquiv
                                ? null
                                : current.httpEquiv) &&
                            currentResource.getAttribute("charset") ===
                              (null == current.charSet
                                ? null
                                : current.charSet))
                        ) {
                          maybeNodes.splice(i, 1);
                          break b;
                        }
                    currentResource = hoistableRoot.createElement(flags);
                    setInitialProperties(currentResource, flags, current);
                    hoistableRoot.head.appendChild(currentResource);
                    break;
                  default:
                    throw Error(formatProdErrorMessage(468, flags));
                }
                currentResource[internalInstanceKey] = finishedWork;
                markNodeAsHoistable(currentResource);
                flags = currentResource;
              }
              finishedWork.stateNode = flags;
            } else
              mountHoistable(
                hoistableRoot,
                finishedWork.type,
                finishedWork.stateNode
              );
          else
            finishedWork.stateNode = acquireResource(
              hoistableRoot,
              flags,
              finishedWork.memoizedProps
            );
        else
          currentResource !== flags
            ? (null === currentResource
                ? null !== current.stateNode &&
                  ((current = current.stateNode),
                  current.parentNode.removeChild(current))
                : currentResource.count--,
              null === flags
                ? mountHoistable(
                    hoistableRoot,
                    finishedWork.type,
                    finishedWork.stateNode
                  )
                : acquireResource(
                    hoistableRoot,
                    flags,
                    finishedWork.memoizedProps
                  ))
            : null === flags &&
              null !== finishedWork.stateNode &&
              commitHostUpdate(
                finishedWork,
                finishedWork.memoizedProps,
                current.memoizedProps
              );
      }
      break;
    case 27:
      if (flags & 4 && null === finishedWork.alternate) {
        hoistableRoot = finishedWork.stateNode;
        currentResource = finishedWork.memoizedProps;
        try {
          for (var node = hoistableRoot.firstChild; node; ) {
            var nextNode = node.nextSibling,
              nodeName = node.nodeName;
            node[internalHoistableMarker] ||
              "HEAD" === nodeName ||
              "BODY" === nodeName ||
              "SCRIPT" === nodeName ||
              "STYLE" === nodeName ||
              ("LINK" === nodeName &&
                "stylesheet" === node.rel.toLowerCase()) ||
              hoistableRoot.removeChild(node);
            node = nextNode;
          }
          for (
            var type = finishedWork.type, attributes = hoistableRoot.attributes;
            attributes.length;

          )
            hoistableRoot.removeAttributeNode(attributes[0]);
          setInitialProperties(hoistableRoot, type, currentResource);
          hoistableRoot[internalInstanceKey] = finishedWork;
          hoistableRoot[internalPropsKey] = currentResource;
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
    case 5:
      recursivelyTraverseMutationEffects(root, finishedWork);
      commitReconciliationEffects(finishedWork);
      flags & 512 &&
        (offscreenSubtreeWasHidden ||
          null === current ||
          safelyDetachRef(current, current.return));
      if (finishedWork.flags & 32) {
        hoistableRoot = finishedWork.stateNode;
        try {
          setTextContent(hoistableRoot, "");
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      flags & 4 &&
        null != finishedWork.stateNode &&
        ((hoistableRoot = finishedWork.memoizedProps),
        commitHostUpdate(
          finishedWork,
          hoistableRoot,
          null !== current ? current.memoizedProps : hoistableRoot
        ));
      flags & 1024 && (needsFormReset = !0);
      break;
    case 6:
      recursivelyTraverseMutationEffects(root, finishedWork);
      commitReconciliationEffects(finishedWork);
      if (flags & 4) {
        if (null === finishedWork.stateNode)
          throw Error(formatProdErrorMessage(162));
        flags = finishedWork.memoizedProps;
        current = finishedWork.stateNode;
        try {
          current.nodeValue = flags;
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      break;
    case 3:
      tagCaches = null;
      hoistableRoot = currentHoistableRoot;
      currentHoistableRoot = getHoistableRoot(root.containerInfo);
      recursivelyTraverseMutationEffects(root, finishedWork);
      currentHoistableRoot = hoistableRoot;
      commitReconciliationEffects(finishedWork);
      if (flags & 4 && null !== current && current.memoizedState.isDehydrated)
        try {
          retryIfBlockedOn(root.containerInfo);
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      needsFormReset &&
        ((needsFormReset = !1), recursivelyResetForms(finishedWork));
      break;
    case 4:
      flags = currentHoistableRoot;
      currentHoistableRoot = getHoistableRoot(
        finishedWork.stateNode.containerInfo
      );
      recursivelyTraverseMutationEffects(root, finishedWork);
      commitReconciliationEffects(finishedWork);
      currentHoistableRoot = flags;
      break;
    case 12:
      recursivelyTraverseMutationEffects(root, finishedWork);
      commitReconciliationEffects(finishedWork);
      break;
    case 13:
      recursivelyTraverseMutationEffects(root, finishedWork);
      commitReconciliationEffects(finishedWork);
      finishedWork.child.flags & 8192 &&
        (null !== finishedWork.memoizedState) !==
          (null !== current && null !== current.memoizedState) &&
        (globalMostRecentFallbackTime = now());
      flags & 4 &&
        ((flags = finishedWork.updateQueue),
        null !== flags &&
          ((finishedWork.updateQueue = null),
          attachSuspenseRetryListeners(finishedWork, flags)));
      break;
    case 22:
      flags & 512 &&
        (offscreenSubtreeWasHidden ||
          null === current ||
          safelyDetachRef(current, current.return));
      node = null !== finishedWork.memoizedState;
      nextNode = null !== current && null !== current.memoizedState;
      nodeName = offscreenSubtreeIsHidden;
      type = offscreenSubtreeWasHidden;
      offscreenSubtreeIsHidden = nodeName || node;
      offscreenSubtreeWasHidden = type || nextNode;
      recursivelyTraverseMutationEffects(root, finishedWork);
      offscreenSubtreeWasHidden = type;
      offscreenSubtreeIsHidden = nodeName;
      commitReconciliationEffects(finishedWork);
      root = finishedWork.stateNode;
      root._current = finishedWork;
      root._visibility &= -3;
      root._visibility |= root._pendingVisibility & 2;
      if (
        flags & 8192 &&
        ((root._visibility = node
          ? root._visibility & -2
          : root._visibility | 1),
        node &&
          ((root = offscreenSubtreeIsHidden || offscreenSubtreeWasHidden),
          null === current ||
            nextNode ||
            root ||
            recursivelyTraverseDisappearLayoutEffects(finishedWork)),
        null === finishedWork.memoizedProps ||
          "manual" !== finishedWork.memoizedProps.mode)
      )
        a: for (current = null, root = finishedWork; ; ) {
          if (5 === root.tag || 26 === root.tag || 27 === root.tag) {
            if (null === current) {
              nextNode = current = root;
              try {
                if (((hoistableRoot = nextNode.stateNode), node))
                  (currentResource = hoistableRoot.style),
                    "function" === typeof currentResource.setProperty
                      ? currentResource.setProperty(
                          "display",
                          "none",
                          "important"
                        )
                      : (currentResource.display = "none");
                else {
                  maybeNodes = nextNode.stateNode;
                  i = nextNode.memoizedProps.style;
                  var display =
                    void 0 !== i && null !== i && i.hasOwnProperty("display")
                      ? i.display
                      : null;
                  maybeNodes.style.display =
                    null == display || "boolean" === typeof display
                      ? ""
                      : ("" + display).trim();
                }
              } catch (error) {
                captureCommitPhaseError(nextNode, nextNode.return, error);
              }
            }
          } else if (6 === root.tag) {
            if (null === current) {
              nextNode = root;
              try {
                nextNode.stateNode.nodeValue = node
                  ? ""
                  : nextNode.memoizedProps;
              } catch (error) {
                captureCommitPhaseError(nextNode, nextNode.return, error);
              }
            }
          } else if (
            ((22 !== root.tag && 23 !== root.tag) ||
              null === root.memoizedState ||
              root === finishedWork) &&
            null !== root.child
          ) {
            root.child.return = root;
            root = root.child;
            continue;
          }
          if (root === finishedWork) break a;
          for (; null === root.sibling; ) {
            if (null === root.return || root.return === finishedWork) break a;
            current === root && (current = null);
            root = root.return;
          }
          current === root && (current = null);
          root.sibling.return = root.return;
          root = root.sibling;
        }
      flags & 4 &&
        ((flags = finishedWork.updateQueue),
        null !== flags &&
          ((current = flags.retryQueue),
          null !== current &&
            ((flags.retryQueue = null),
            attachSuspenseRetryListeners(finishedWork, current))));
      break;
    case 19:
      recursivelyTraverseMutationEffects(root, finishedWork);
      commitReconciliationEffects(finishedWork);
      flags & 4 &&
        ((flags = finishedWork.updateQueue),
        null !== flags &&
          ((finishedWork.updateQueue = null),
          attachSuspenseRetryListeners(finishedWork, flags)));
      break;
    case 21:
      break;
    default:
      recursivelyTraverseMutationEffects(root, finishedWork),
        commitReconciliationEffects(finishedWork);
  }
}
function commitReconciliationEffects(finishedWork) {
  var flags = finishedWork.flags;
  if (flags & 2) {
    try {
      if (27 !== finishedWork.tag) {
        a: {
          for (var parent = finishedWork.return; null !== parent; ) {
            if (isHostParent(parent)) {
              var JSCompiler_inline_result = parent;
              break a;
            }
            parent = parent.return;
          }
          throw Error(formatProdErrorMessage(160));
        }
        switch (JSCompiler_inline_result.tag) {
          case 27:
            var parent$jscomp$0 = JSCompiler_inline_result.stateNode,
              before = getHostSibling(finishedWork);
            insertOrAppendPlacementNode(finishedWork, before, parent$jscomp$0);
            break;
          case 5:
            var parent$113 = JSCompiler_inline_result.stateNode;
            JSCompiler_inline_result.flags & 32 &&
              (setTextContent(parent$113, ""),
              (JSCompiler_inline_result.flags &= -33));
            var before$114 = getHostSibling(finishedWork);
            insertOrAppendPlacementNode(finishedWork, before$114, parent$113);
            break;
          case 3:
          case 4:
            var parent$115 = JSCompiler_inline_result.stateNode.containerInfo,
              before$116 = getHostSibling(finishedWork);
            insertOrAppendPlacementNodeIntoContainer(
              finishedWork,
              before$116,
              parent$115
            );
            break;
          default:
            throw Error(formatProdErrorMessage(161));
        }
      }
    } catch (error) {
      captureCommitPhaseError(finishedWork, finishedWork.return, error);
    }
    finishedWork.flags &= -3;
  }
  flags & 4096 && (finishedWork.flags &= -4097);
}
function recursivelyResetForms(parentFiber) {
  if (parentFiber.subtreeFlags & 1024)
    for (parentFiber = parentFiber.child; null !== parentFiber; ) {
      var fiber = parentFiber;
      recursivelyResetForms(fiber);
      5 === fiber.tag && fiber.flags & 1024 && fiber.stateNode.reset();
      parentFiber = parentFiber.sibling;
    }
}
function recursivelyTraverseLayoutEffects(root, parentFiber) {
  if (parentFiber.subtreeFlags & 8772)
    for (parentFiber = parentFiber.child; null !== parentFiber; )
      commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber),
        (parentFiber = parentFiber.sibling);
}
function recursivelyTraverseDisappearLayoutEffects(parentFiber) {
  for (parentFiber = parentFiber.child; null !== parentFiber; ) {
    var finishedWork = parentFiber;
    switch (finishedWork.tag) {
      case 0:
      case 11:
      case 14:
      case 15:
        commitHookEffectListUnmount(4, finishedWork, finishedWork.return);
        recursivelyTraverseDisappearLayoutEffects(finishedWork);
        break;
      case 1:
        safelyDetachRef(finishedWork, finishedWork.return);
        var instance = finishedWork.stateNode;
        "function" === typeof instance.componentWillUnmount &&
          safelyCallComponentWillUnmount(
            finishedWork,
            finishedWork.return,
            instance
          );
        recursivelyTraverseDisappearLayoutEffects(finishedWork);
        break;
      case 26:
      case 27:
      case 5:
        safelyDetachRef(finishedWork, finishedWork.return);
        recursivelyTraverseDisappearLayoutEffects(finishedWork);
        break;
      case 22:
        safelyDetachRef(finishedWork, finishedWork.return);
        null === finishedWork.memoizedState &&
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
        break;
      default:
        recursivelyTraverseDisappearLayoutEffects(finishedWork);
    }
    parentFiber = parentFiber.sibling;
  }
}
function recursivelyTraverseReappearLayoutEffects(
  finishedRoot$jscomp$0,
  parentFiber,
  includeWorkInProgressEffects
) {
  includeWorkInProgressEffects =
    includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772);
  for (parentFiber = parentFiber.child; null !== parentFiber; ) {
    var current = parentFiber.alternate,
      finishedRoot = finishedRoot$jscomp$0,
      finishedWork = parentFiber,
      flags = finishedWork.flags;
    switch (finishedWork.tag) {
      case 0:
      case 11:
      case 15:
        recursivelyTraverseReappearLayoutEffects(
          finishedRoot,
          finishedWork,
          includeWorkInProgressEffects
        );
        commitHookEffectListMount(4, finishedWork);
        break;
      case 1:
        recursivelyTraverseReappearLayoutEffects(
          finishedRoot,
          finishedWork,
          includeWorkInProgressEffects
        );
        current = finishedWork;
        finishedRoot = current.stateNode;
        if ("function" === typeof finishedRoot.componentDidMount)
          try {
            finishedRoot.componentDidMount();
          } catch (error) {
            captureCommitPhaseError(current, current.return, error);
          }
        current = finishedWork;
        finishedRoot = current.updateQueue;
        if (null !== finishedRoot) {
          var instance = current.stateNode;
          try {
            var hiddenCallbacks = finishedRoot.shared.hiddenCallbacks;
            if (null !== hiddenCallbacks)
              for (
                finishedRoot.shared.hiddenCallbacks = null, finishedRoot = 0;
                finishedRoot < hiddenCallbacks.length;
                finishedRoot++
              )
                callCallback(hiddenCallbacks[finishedRoot], instance);
          } catch (error) {
            captureCommitPhaseError(current, current.return, error);
          }
        }
        includeWorkInProgressEffects &&
          flags & 64 &&
          commitClassCallbacks(finishedWork);
        safelyAttachRef(finishedWork, finishedWork.return);
        break;
      case 26:
      case 27:
      case 5:
        recursivelyTraverseReappearLayoutEffects(
          finishedRoot,
          finishedWork,
          includeWorkInProgressEffects
        );
        includeWorkInProgressEffects &&
          null === current &&
          flags & 4 &&
          commitHostMount(finishedWork);
        safelyAttachRef(finishedWork, finishedWork.return);
        break;
      case 12:
        recursivelyTraverseReappearLayoutEffects(
          finishedRoot,
          finishedWork,
          includeWorkInProgressEffects
        );
        break;
      case 13:
        recursivelyTraverseReappearLayoutEffects(
          finishedRoot,
          finishedWork,
          includeWorkInProgressEffects
        );
        includeWorkInProgressEffects &&
          flags & 4 &&
          commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
        break;
      case 22:
        null === finishedWork.memoizedState &&
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
        safelyAttachRef(finishedWork, finishedWork.return);
        break;
      default:
        recursivelyTraverseReappearLayoutEffects(
          finishedRoot,
          finishedWork,
          includeWorkInProgressEffects
        );
    }
    parentFiber = parentFiber.sibling;
  }
}
function commitOffscreenPassiveMountEffects(current, finishedWork) {
  var previousCache = null;
  null !== current &&
    null !== current.memoizedState &&
    null !== current.memoizedState.cachePool &&
    (previousCache = current.memoizedState.cachePool.pool);
  current = null;
  null !== finishedWork.memoizedState &&
    null !== finishedWork.memoizedState.cachePool &&
    (current = finishedWork.memoizedState.cachePool.pool);
  current !== previousCache &&
    (null != current && current.refCount++,
    null != previousCache && releaseCache(previousCache));
}
function commitCachePassiveMountEffect(current, finishedWork) {
  current = null;
  null !== finishedWork.alternate &&
    (current = finishedWork.alternate.memoizedState.cache);
  finishedWork = finishedWork.memoizedState.cache;
  finishedWork !== current &&
    (finishedWork.refCount++, null != current && releaseCache(current));
}
function recursivelyTraversePassiveMountEffects(
  root,
  parentFiber,
  committedLanes,
  committedTransitions
) {
  if (parentFiber.subtreeFlags & 10256)
    for (parentFiber = parentFiber.child; null !== parentFiber; )
      commitPassiveMountOnFiber(
        root,
        parentFiber,
        committedLanes,
        committedTransitions
      ),
        (parentFiber = parentFiber.sibling);
}
function commitPassiveMountOnFiber(
  finishedRoot,
  finishedWork,
  committedLanes,
  committedTransitions
) {
  var flags = finishedWork.flags;
  switch (finishedWork.tag) {
    case 0:
    case 11:
    case 15:
      recursivelyTraversePassiveMountEffects(
        finishedRoot,
        finishedWork,
        committedLanes,
        committedTransitions
      );
      flags & 2048 && commitHookEffectListMount(9, finishedWork);
      break;
    case 3:
      recursivelyTraversePassiveMountEffects(
        finishedRoot,
        finishedWork,
        committedLanes,
        committedTransitions
      );
      flags & 2048 &&
        ((finishedRoot = null),
        null !== finishedWork.alternate &&
          (finishedRoot = finishedWork.alternate.memoizedState.cache),
        (finishedWork = finishedWork.memoizedState.cache),
        finishedWork !== finishedRoot &&
          (finishedWork.refCount++,
          null != finishedRoot && releaseCache(finishedRoot)));
      break;
    case 12:
      if (flags & 2048) {
        recursivelyTraversePassiveMountEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions
        );
        finishedRoot = finishedWork.stateNode;
        try {
          var _finishedWork$memoize2 = finishedWork.memoizedProps,
            id = _finishedWork$memoize2.id,
            onPostCommit = _finishedWork$memoize2.onPostCommit;
          "function" === typeof onPostCommit &&
            onPostCommit(
              id,
              null === finishedWork.alternate ? "mount" : "update",
              finishedRoot.passiveEffectDuration,
              -0
            );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      } else
        recursivelyTraversePassiveMountEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions
        );
      break;
    case 23:
      break;
    case 22:
      _finishedWork$memoize2 = finishedWork.stateNode;
      null !== finishedWork.memoizedState
        ? _finishedWork$memoize2._visibility & 4
          ? recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            )
          : recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork)
        : _finishedWork$memoize2._visibility & 4
          ? recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            )
          : ((_finishedWork$memoize2._visibility |= 4),
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              0 !== (finishedWork.subtreeFlags & 10256)
            ));
      flags & 2048 &&
        commitOffscreenPassiveMountEffects(
          finishedWork.alternate,
          finishedWork
        );
      break;
    case 24:
      recursivelyTraversePassiveMountEffects(
        finishedRoot,
        finishedWork,
        committedLanes,
        committedTransitions
      );
      flags & 2048 &&
        commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
      break;
    default:
      recursivelyTraversePassiveMountEffects(
        finishedRoot,
        finishedWork,
        committedLanes,
        committedTransitions
      );
  }
}
function recursivelyTraverseReconnectPassiveEffects(
  finishedRoot$jscomp$0,
  parentFiber,
  committedLanes$jscomp$0,
  committedTransitions$jscomp$0,
  includeWorkInProgressEffects
) {
  includeWorkInProgressEffects =
    includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 10256);
  for (parentFiber = parentFiber.child; null !== parentFiber; ) {
    var finishedRoot = finishedRoot$jscomp$0,
      finishedWork = parentFiber,
      committedLanes = committedLanes$jscomp$0,
      committedTransitions = committedTransitions$jscomp$0,
      flags = finishedWork.flags;
    switch (finishedWork.tag) {
      case 0:
      case 11:
      case 15:
        recursivelyTraverseReconnectPassiveEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions,
          includeWorkInProgressEffects
        );
        commitHookEffectListMount(8, finishedWork);
        break;
      case 23:
        break;
      case 22:
        var instance = finishedWork.stateNode;
        null !== finishedWork.memoizedState
          ? instance._visibility & 4
            ? recursivelyTraverseReconnectPassiveEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions,
                includeWorkInProgressEffects
              )
            : recursivelyTraverseAtomicPassiveEffects(
                finishedRoot,
                finishedWork
              )
          : ((instance._visibility |= 4),
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            ));
        includeWorkInProgressEffects &&
          flags & 2048 &&
          commitOffscreenPassiveMountEffects(
            finishedWork.alternate,
            finishedWork
          );
        break;
      case 24:
        recursivelyTraverseReconnectPassiveEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions,
          includeWorkInProgressEffects
        );
        includeWorkInProgressEffects &&
          flags & 2048 &&
          commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
        break;
      default:
        recursivelyTraverseReconnectPassiveEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions,
          includeWorkInProgressEffects
        );
    }
    parentFiber = parentFiber.sibling;
  }
}
function recursivelyTraverseAtomicPassiveEffects(
  finishedRoot$jscomp$0,
  parentFiber
) {
  if (parentFiber.subtreeFlags & 10256)
    for (parentFiber = parentFiber.child; null !== parentFiber; ) {
      var finishedRoot = finishedRoot$jscomp$0,
        finishedWork = parentFiber,
        flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 22:
          recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
          flags & 2048 &&
            commitOffscreenPassiveMountEffects(
              finishedWork.alternate,
              finishedWork
            );
          break;
        case 24:
          recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
          flags & 2048 &&
            commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
          break;
        default:
          recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
      }
      parentFiber = parentFiber.sibling;
    }
}
var suspenseyCommitFlag = 8192;
function recursivelyAccumulateSuspenseyCommit(parentFiber) {
  if (parentFiber.subtreeFlags & suspenseyCommitFlag)
    for (parentFiber = parentFiber.child; null !== parentFiber; )
      accumulateSuspenseyCommitOnFiber(parentFiber),
        (parentFiber = parentFiber.sibling);
}
function accumulateSuspenseyCommitOnFiber(fiber) {
  switch (fiber.tag) {
    case 26:
      recursivelyAccumulateSuspenseyCommit(fiber);
      fiber.flags & suspenseyCommitFlag &&
        null !== fiber.memoizedState &&
        suspendResource(
          currentHoistableRoot,
          fiber.memoizedState,
          fiber.memoizedProps
        );
      break;
    case 5:
      recursivelyAccumulateSuspenseyCommit(fiber);
      break;
    case 3:
    case 4:
      var previousHoistableRoot = currentHoistableRoot;
      currentHoistableRoot = getHoistableRoot(fiber.stateNode.containerInfo);
      recursivelyAccumulateSuspenseyCommit(fiber);
      currentHoistableRoot = previousHoistableRoot;
      break;
    case 22:
      null === fiber.memoizedState &&
        ((previousHoistableRoot = fiber.alternate),
        null !== previousHoistableRoot &&
        null !== previousHoistableRoot.memoizedState
          ? ((previousHoistableRoot = suspenseyCommitFlag),
            (suspenseyCommitFlag = 16777216),
            recursivelyAccumulateSuspenseyCommit(fiber),
            (suspenseyCommitFlag = previousHoistableRoot))
          : recursivelyAccumulateSuspenseyCommit(fiber));
      break;
    default:
      recursivelyAccumulateSuspenseyCommit(fiber);
  }
}
function detachAlternateSiblings(parentFiber) {
  var previousFiber = parentFiber.alternate;
  if (
    null !== previousFiber &&
    ((parentFiber = previousFiber.child), null !== parentFiber)
  ) {
    previousFiber.child = null;
    do
      (previousFiber = parentFiber.sibling),
        (parentFiber.sibling = null),
        (parentFiber = previousFiber);
    while (null !== parentFiber);
  }
}
function recursivelyTraversePassiveUnmountEffects(parentFiber) {
  var deletions = parentFiber.deletions;
  if (0 !== (parentFiber.flags & 16)) {
    if (null !== deletions)
      for (var i = 0; i < deletions.length; i++) {
        var childToDelete = deletions[i];
        nextEffect = childToDelete;
        commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
          childToDelete,
          parentFiber
        );
      }
    detachAlternateSiblings(parentFiber);
  }
  if (parentFiber.subtreeFlags & 10256)
    for (parentFiber = parentFiber.child; null !== parentFiber; )
      commitPassiveUnmountOnFiber(parentFiber),
        (parentFiber = parentFiber.sibling);
}
function commitPassiveUnmountOnFiber(finishedWork) {
  switch (finishedWork.tag) {
    case 0:
    case 11:
    case 15:
      recursivelyTraversePassiveUnmountEffects(finishedWork);
      finishedWork.flags & 2048 &&
        commitHookEffectListUnmount(9, finishedWork, finishedWork.return);
      break;
    case 3:
      recursivelyTraversePassiveUnmountEffects(finishedWork);
      break;
    case 12:
      recursivelyTraversePassiveUnmountEffects(finishedWork);
      break;
    case 22:
      var instance = finishedWork.stateNode;
      null !== finishedWork.memoizedState &&
      instance._visibility & 4 &&
      (null === finishedWork.return || 13 !== finishedWork.return.tag)
        ? ((instance._visibility &= -5),
          recursivelyTraverseDisconnectPassiveEffects(finishedWork))
        : recursivelyTraversePassiveUnmountEffects(finishedWork);
      break;
    default:
      recursivelyTraversePassiveUnmountEffects(finishedWork);
  }
}
function recursivelyTraverseDisconnectPassiveEffects(parentFiber) {
  var deletions = parentFiber.deletions;
  if (0 !== (parentFiber.flags & 16)) {
    if (null !== deletions)
      for (var i = 0; i < deletions.length; i++) {
        var childToDelete = deletions[i];
        nextEffect = childToDelete;
        commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
          childToDelete,
          parentFiber
        );
      }
    detachAlternateSiblings(parentFiber);
  }
  for (parentFiber = parentFiber.child; null !== parentFiber; ) {
    deletions = parentFiber;
    switch (deletions.tag) {
      case 0:
      case 11:
      case 15:
        commitHookEffectListUnmount(8, deletions, deletions.return);
        recursivelyTraverseDisconnectPassiveEffects(deletions);
        break;
      case 22:
        i = deletions.stateNode;
        i._visibility & 4 &&
          ((i._visibility &= -5),
          recursivelyTraverseDisconnectPassiveEffects(deletions));
        break;
      default:
        recursivelyTraverseDisconnectPassiveEffects(deletions);
    }
    parentFiber = parentFiber.sibling;
  }
}
function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
  deletedSubtreeRoot,
  nearestMountedAncestor
) {
  for (; null !== nextEffect; ) {
    var fiber = nextEffect;
    switch (fiber.tag) {
      case 0:
      case 11:
      case 15:
        commitHookEffectListUnmount(8, fiber, nearestMountedAncestor);
        break;
      case 23:
      case 22:
        if (
          null !== fiber.memoizedState &&
          null !== fiber.memoizedState.cachePool
        ) {
          var cache = fiber.memoizedState.cachePool.pool;
          null != cache && cache.refCount++;
        }
        break;
      case 24:
        releaseCache(fiber.memoizedState.cache);
    }
    cache = fiber.child;
    if (null !== cache) (cache.return = fiber), (nextEffect = cache);
    else
      a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) {
        cache = nextEffect;
        var sibling = cache.sibling,
          returnFiber = cache.return;
        detachFiberAfterEffects(cache);
        if (cache === fiber) {
          nextEffect = null;
          break a;
        }
        if (null !== sibling) {
          sibling.return = returnFiber;
          nextEffect = sibling;
          break a;
        }
        nextEffect = returnFiber;
      }
  }
}
function FiberNode(tag, pendingProps, key, mode) {
  this.tag = tag;
  this.key = key;
  this.sibling =
    this.child =
    this.return =
    this.stateNode =
    this.type =
    this.elementType =
      null;
  this.index = 0;
  this.refCleanup = this.ref = null;
  this.pendingProps = pendingProps;
  this.dependencies =
    this.memoizedState =
    this.updateQueue =
    this.memoizedProps =
      null;
  this.mode = mode;
  this.subtreeFlags = this.flags = 0;
  this.deletions = null;
  this.childLanes = this.lanes = 0;
  this.alternate = null;
}
function createFiberImplClass(tag, pendingProps, key, mode) {
  return new FiberNode(tag, pendingProps, key, mode);
}
function shouldConstruct(Component) {
  Component = Component.prototype;
  return !(!Component || !Component.isReactComponent);
}
function createWorkInProgress(current, pendingProps) {
  var workInProgress = current.alternate;
  null === workInProgress
    ? ((workInProgress = createFiberImplClass(
        current.tag,
        pendingProps,
        current.key,
        current.mode
      )),
      (workInProgress.elementType = current.elementType),
      (workInProgress.type = current.type),
      (workInProgress.stateNode = current.stateNode),
      (workInProgress.alternate = current),
      (current.alternate = workInProgress))
    : ((workInProgress.pendingProps = pendingProps),
      (workInProgress.type = current.type),
      (workInProgress.flags = 0),
      (workInProgress.subtreeFlags = 0),
      (workInProgress.deletions = null));
  workInProgress.flags = current.flags & 31457280;
  workInProgress.childLanes = current.childLanes;
  workInProgress.lanes = current.lanes;
  workInProgress.child = current.child;
  workInProgress.memoizedProps = current.memoizedProps;
  workInProgress.memoizedState = current.memoizedState;
  workInProgress.updateQueue = current.updateQueue;
  pendingProps = current.dependencies;
  workInProgress.dependencies =
    null === pendingProps
      ? null
      : { lanes: pendingProps.lanes, firstContext: pendingProps.firstContext };
  workInProgress.sibling = current.sibling;
  workInProgress.index = current.index;
  workInProgress.ref = current.ref;
  workInProgress.refCleanup = current.refCleanup;
  return workInProgress;
}
function resetWorkInProgress(workInProgress, renderLanes) {
  workInProgress.flags &= 31457282;
  var current = workInProgress.alternate;
  null === current
    ? ((workInProgress.childLanes = 0),
      (workInProgress.lanes = renderLanes),
      (workInProgress.child = null),
      (workInProgress.subtreeFlags = 0),
      (workInProgress.memoizedProps = null),
      (workInProgress.memoizedState = null),
      (workInProgress.updateQueue = null),
      (workInProgress.dependencies = null),
      (workInProgress.stateNode = null))
    : ((workInProgress.childLanes = current.childLanes),
      (workInProgress.lanes = current.lanes),
      (workInProgress.child = current.child),
      (workInProgress.subtreeFlags = 0),
      (workInProgress.deletions = null),
      (workInProgress.memoizedProps = current.memoizedProps),
      (workInProgress.memoizedState = current.memoizedState),
      (workInProgress.updateQueue = current.updateQueue),
      (workInProgress.type = current.type),
      (renderLanes = current.dependencies),
      (workInProgress.dependencies =
        null === renderLanes
          ? null
          : {
              lanes: renderLanes.lanes,
              firstContext: renderLanes.firstContext
            }));
  return workInProgress;
}
function createFiberFromTypeAndProps(
  type,
  key,
  pendingProps,
  owner,
  mode,
  lanes
) {
  var fiberTag = 0;
  owner = type;
  if ("function" === typeof type) shouldConstruct(type) && (fiberTag = 1);
  else if ("string" === typeof type)
    fiberTag = isHostHoistableType(
      type,
      pendingProps,
      contextStackCursor.current
    )
      ? 26
      : "html" === type || "head" === type || "body" === type
        ? 27
        : 5;
  else
    a: switch (type) {
      case REACT_FRAGMENT_TYPE:
        return createFiberFromFragment(pendingProps.children, mode, lanes, key);
      case REACT_STRICT_MODE_TYPE:
        fiberTag = 8;
        mode |= 24;
        break;
      case REACT_PROFILER_TYPE:
        return (
          (type = createFiberImplClass(12, pendingProps, key, mode | 2)),
          (type.elementType = REACT_PROFILER_TYPE),
          (type.lanes = lanes),
          type
        );
      case REACT_SUSPENSE_TYPE:
        return (
          (type = createFiberImplClass(13, pendingProps, key, mode)),
          (type.elementType = REACT_SUSPENSE_TYPE),
          (type.lanes = lanes),
          type
        );
      case REACT_SUSPENSE_LIST_TYPE:
        return (
          (type = createFiberImplClass(19, pendingProps, key, mode)),
          (type.elementType = REACT_SUSPENSE_LIST_TYPE),
          (type.lanes = lanes),
          type
        );
      case REACT_OFFSCREEN_TYPE:
        return createFiberFromOffscreen(pendingProps, mode, lanes, key);
      default:
        if ("object" === typeof type && null !== type)
          switch (type.$$typeof) {
            case REACT_PROVIDER_TYPE:
            case REACT_CONTEXT_TYPE:
              fiberTag = 10;
              break a;
            case REACT_CONSUMER_TYPE:
              fiberTag = 9;
              break a;
            case REACT_FORWARD_REF_TYPE:
              fiberTag = 11;
              break a;
            case REACT_MEMO_TYPE:
              fiberTag = 14;
              break a;
            case REACT_LAZY_TYPE:
              fiberTag = 16;
              owner = null;
              break a;
          }
        fiberTag = 29;
        pendingProps = Error(
          formatProdErrorMessage(130, null === type ? "null" : typeof type, "")
        );
        owner = null;
    }
  key = createFiberImplClass(fiberTag, pendingProps, key, mode);
  key.elementType = type;
  key.type = owner;
  key.lanes = lanes;
  return key;
}
function createFiberFromFragment(elements, mode, lanes, key) {
  elements = createFiberImplClass(7, elements, key, mode);
  elements.lanes = lanes;
  return elements;
}
function createFiberFromOffscreen(pendingProps, mode, lanes, key) {
  pendingProps = createFiberImplClass(22, pendingProps, key, mode);
  pendingProps.elementType = REACT_OFFSCREEN_TYPE;
  pendingProps.lanes = lanes;
  var primaryChildInstance = {
    _visibility: 1,
    _pendingVisibility: 1,
    _pendingMarkers: null,
    _retryCache: null,
    _transitions: null,
    _current: null,
    detach: function () {
      var fiber = primaryChildInstance._current;
      if (null === fiber) throw Error(formatProdErrorMessage(456));
      if (0 === (primaryChildInstance._pendingVisibility & 2)) {
        var root = enqueueConcurrentRenderForLane(fiber, 2);
        null !== root &&
          ((primaryChildInstance._pendingVisibility |= 2),
          scheduleUpdateOnFiber(root, fiber, 2));
      }
    },
    attach: function () {
      var fiber = primaryChildInstance._current;
      if (null === fiber) throw Error(formatProdErrorMessage(456));
      if (0 !== (primaryChildInstance._pendingVisibility & 2)) {
        var root = enqueueConcurrentRenderForLane(fiber, 2);
        null !== root &&
          ((primaryChildInstance._pendingVisibility &= -3),
          scheduleUpdateOnFiber(root, fiber, 2));
      }
    }
  };
  pendingProps.stateNode = primaryChildInstance;
  return pendingProps;
}
function createFiberFromText(content, mode, lanes) {
  content = createFiberImplClass(6, content, null, mode);
  content.lanes = lanes;
  return content;
}
function createFiberFromPortal(portal, mode, lanes) {
  mode = createFiberImplClass(
    4,
    null !== portal.children ? portal.children : [],
    portal.key,
    mode
  );
  mode.lanes = lanes;
  mode.stateNode = {
    containerInfo: portal.containerInfo,
    pendingChildren: null,
    implementation: portal.implementation
  };
  return mode;
}
function markUpdate(workInProgress) {
  workInProgress.flags |= 4;
}
function preloadResourceAndSuspendIfNeeded(workInProgress, resource) {
  if ("stylesheet" !== resource.type || 0 !== (resource.state.loading & 4))
    workInProgress.flags &= -16777217;
  else if (((workInProgress.flags |= 16777216), !preloadResource(resource))) {
    resource = suspenseHandlerStackCursor.current;
    if (
      null !== resource &&
      ((workInProgressRootRenderLanes & 4194176) ===
      workInProgressRootRenderLanes
        ? null !== shellBoundary
        : ((workInProgressRootRenderLanes & 62914560) !==
            workInProgressRootRenderLanes &&
            0 === (workInProgressRootRenderLanes & 536870912)) ||
          resource !== shellBoundary)
    )
      throw (
        ((suspendedThenable = noopSuspenseyCommitThenable),
        SuspenseyCommitException)
      );
    workInProgress.flags |= 8192;
  }
}
function scheduleRetryEffect(workInProgress, retryQueue) {
  null !== retryQueue && (workInProgress.flags |= 4);
  workInProgress.flags & 16384 &&
    ((retryQueue =
      22 !== workInProgress.tag ? claimNextRetryLane() : 536870912),
    (workInProgress.lanes |= retryQueue),
    (workInProgressSuspendedRetryLanes |= retryQueue));
}
function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
  if (!isHydrating)
    switch (renderState.tailMode) {
      case "hidden":
        hasRenderedATailFallback = renderState.tail;
        for (var lastTailNode = null; null !== hasRenderedATailFallback; )
          null !== hasRenderedATailFallback.alternate &&
            (lastTailNode = hasRenderedATailFallback),
            (hasRenderedATailFallback = hasRenderedATailFallback.sibling);
        null === lastTailNode
          ? (renderState.tail = null)
          : (lastTailNode.sibling = null);
        break;
      case "collapsed":
        lastTailNode = renderState.tail;
        for (var lastTailNode$131 = null; null !== lastTailNode; )
          null !== lastTailNode.alternate && (lastTailNode$131 = lastTailNode),
            (lastTailNode = lastTailNode.sibling);
        null === lastTailNode$131
          ? hasRenderedATailFallback || null === renderState.tail
            ? (renderState.tail = null)
            : (renderState.tail.sibling = null)
          : (lastTailNode$131.sibling = null);
    }
}
function bubbleProperties(completedWork) {
  var didBailout =
      null !== completedWork.alternate &&
      completedWork.alternate.child === completedWork.child,
    newChildLanes = 0,
    subtreeFlags = 0;
  if (didBailout)
    for (var child$132 = completedWork.child; null !== child$132; )
      (newChildLanes |= child$132.lanes | child$132.childLanes),
        (subtreeFlags |= child$132.subtreeFlags & 31457280),
        (subtreeFlags |= child$132.flags & 31457280),
        (child$132.return = completedWork),
        (child$132 = child$132.sibling);
  else
    for (child$132 = completedWork.child; null !== child$132; )
      (newChildLanes |= child$132.lanes | child$132.childLanes),
        (subtreeFlags |= child$132.subtreeFlags),
        (subtreeFlags |= child$132.flags),
        (child$132.return = completedWork),
        (child$132 = child$132.sibling);
  completedWork.subtreeFlags |= subtreeFlags;
  completedWork.childLanes = newChildLanes;
  return didBailout;
}
function completeWork(current, workInProgress, renderLanes) {
  var newProps = workInProgress.pendingProps;
  popTreeContext(workInProgress);
  switch (workInProgress.tag) {
    case 16:
    case 15:
    case 0:
    case 11:
    case 7:
    case 8:
    case 12:
    case 9:
    case 14:
      return bubbleProperties(workInProgress), null;
    case 1:
      return bubbleProperties(workInProgress), null;
    case 3:
      renderLanes = workInProgress.stateNode;
      newProps = null;
      null !== current && (newProps = current.memoizedState.cache);
      workInProgress.memoizedState.cache !== newProps &&
        (workInProgress.flags |= 2048);
      popProvider(CacheContext);
      popHostContainer();
      renderLanes.pendingContext &&
        ((renderLanes.context = renderLanes.pendingContext),
        (renderLanes.pendingContext = null));
      if (null === current || null === current.child)
        popHydrationState(workInProgress)
          ? markUpdate(workInProgress)
          : null === current ||
            (current.memoizedState.isDehydrated &&
              0 === (workInProgress.flags & 256)) ||
            ((workInProgress.flags |= 1024),
            null !== hydrationErrors &&
              (queueRecoverableErrors(hydrationErrors),
              (hydrationErrors = null)));
      bubbleProperties(workInProgress);
      return null;
    case 26:
      return (
        (renderLanes = workInProgress.memoizedState),
        null === current
          ? (markUpdate(workInProgress),
            null !== renderLanes
              ? (bubbleProperties(workInProgress),
                preloadResourceAndSuspendIfNeeded(workInProgress, renderLanes))
              : (bubbleProperties(workInProgress),
                (workInProgress.flags &= -16777217)))
          : renderLanes
            ? renderLanes !== current.memoizedState
              ? (markUpdate(workInProgress),
                bubbleProperties(workInProgress),
                preloadResourceAndSuspendIfNeeded(workInProgress, renderLanes))
              : (bubbleProperties(workInProgress),
                (workInProgress.flags &= -16777217))
            : (current.memoizedProps !== newProps && markUpdate(workInProgress),
              bubbleProperties(workInProgress),
              (workInProgress.flags &= -16777217)),
        null
      );
    case 27:
      popHostContext(workInProgress);
      renderLanes = rootInstanceStackCursor.current;
      var type = workInProgress.type;
      if (null !== current && null != workInProgress.stateNode)
        current.memoizedProps !== newProps && markUpdate(workInProgress);
      else {
        if (!newProps) {
          if (null === workInProgress.stateNode)
            throw Error(formatProdErrorMessage(166));
          bubbleProperties(workInProgress);
          return null;
        }
        current = contextStackCursor.current;
        popHydrationState(workInProgress)
          ? prepareToHydrateHostInstance(workInProgress, current)
          : ((current = resolveSingletonInstance(type, newProps, renderLanes)),
            (workInProgress.stateNode = current),
            markUpdate(workInProgress));
      }
      bubbleProperties(workInProgress);
      return null;
    case 5:
      popHostContext(workInProgress);
      renderLanes = workInProgress.type;
      if (null !== current && null != workInProgress.stateNode)
        current.memoizedProps !== newProps && markUpdate(workInProgress);
      else {
        if (!newProps) {
          if (null === workInProgress.stateNode)
            throw Error(formatProdErrorMessage(166));
          bubbleProperties(workInProgress);
          return null;
        }
        current = contextStackCursor.current;
        if (popHydrationState(workInProgress))
          prepareToHydrateHostInstance(workInProgress, current);
        else {
          type = getOwnerDocumentFromRootContainer(
            rootInstanceStackCursor.current
          );
          switch (current) {
            case 1:
              current = type.createElementNS(
                "http://www.w3.org/2000/svg",
                renderLanes
              );
              break;
            case 2:
              current = type.createElementNS(
                "http://www.w3.org/1998/Math/MathML",
                renderLanes
              );
              break;
            default:
              switch (renderLanes) {
                case "svg":
                  current = type.createElementNS(
                    "http://www.w3.org/2000/svg",
                    renderLanes
                  );
                  break;
                case "math":
                  current = type.createElementNS(
                    "http://www.w3.org/1998/Math/MathML",
                    renderLanes
                  );
                  break;
                case "script":
                  current = type.createElement("div");
                  current.innerHTML = "<script>\x3c/script>";
                  current = current.removeChild(current.firstChild);
                  break;
                case "select":
                  current =
                    "string" === typeof newProps.is
                      ? type.createElement("select", { is: newProps.is })
                      : type.createElement("select");
                  newProps.multiple
                    ? (current.multiple = !0)
                    : newProps.size && (current.size = newProps.size);
                  break;
                default:
                  current =
                    "string" === typeof newProps.is
                      ? type.createElement(renderLanes, { is: newProps.is })
                      : type.createElement(renderLanes);
              }
          }
          current[internalInstanceKey] = workInProgress;
          current[internalPropsKey] = newProps;
          a: for (type = workInProgress.child; null !== type; ) {
            if (5 === type.tag || 6 === type.tag)
              current.appendChild(type.stateNode);
            else if (4 !== type.tag && 27 !== type.tag && null !== type.child) {
              type.child.return = type;
              type = type.child;
              continue;
            }
            if (type === workInProgress) break a;
            for (; null === type.sibling; ) {
              if (null === type.return || type.return === workInProgress)
                break a;
              type = type.return;
            }
            type.sibling.return = type.return;
            type = type.sibling;
          }
          workInProgress.stateNode = current;
          a: switch (
            (setInitialProperties(current, renderLanes, newProps), renderLanes)
          ) {
            case "button":
            case "input":
            case "select":
            case "textarea":
              current = !!newProps.autoFocus;
              break a;
            case "img":
              current = !0;
              break a;
            default:
              current = !1;
          }
          current && markUpdate(workInProgress);
        }
      }
      bubbleProperties(workInProgress);
      workInProgress.flags &= -16777217;
      return null;
    case 6:
      if (current && null != workInProgress.stateNode)
        current.memoizedProps !== newProps && markUpdate(workInProgress);
      else {
        if ("string" !== typeof newProps && null === workInProgress.stateNode)
          throw Error(formatProdErrorMessage(166));
        current = rootInstanceStackCursor.current;
        if (popHydrationState(workInProgress)) {
          current = workInProgress.stateNode;
          renderLanes = workInProgress.memoizedProps;
          newProps = null;
          type = hydrationParentFiber;
          if (null !== type)
            switch (type.tag) {
              case 27:
              case 5:
                newProps = type.memoizedProps;
            }
          current[internalInstanceKey] = workInProgress;
          current =
            current.nodeValue === renderLanes ||
            (null !== newProps && !0 === newProps.suppressHydrationWarning) ||
            checkForUnmatchedText(current.nodeValue, renderLanes)
              ? !0
              : !1;
          current || throwOnHydrationMismatch(workInProgress);
        } else
          (current =
            getOwnerDocumentFromRootContainer(current).createTextNode(
              newProps
            )),
            (current[internalInstanceKey] = workInProgress),
            (workInProgress.stateNode = current);
      }
      bubbleProperties(workInProgress);
      return null;
    case 13:
      newProps = workInProgress.memoizedState;
      if (
        null === current ||
        (null !== current.memoizedState &&
          null !== current.memoizedState.dehydrated)
      ) {
        type = popHydrationState(workInProgress);
        if (null !== newProps && null !== newProps.dehydrated) {
          if (null === current) {
            if (!type) throw Error(formatProdErrorMessage(318));
            type = workInProgress.memoizedState;
            type = null !== type ? type.dehydrated : null;
            if (!type) throw Error(formatProdErrorMessage(317));
            type[internalInstanceKey] = workInProgress;
          } else
            resetHydrationState(),
              0 === (workInProgress.flags & 128) &&
                (workInProgress.memoizedState = null),
              (workInProgress.flags |= 4);
          bubbleProperties(workInProgress);
          type = !1;
        } else
          null !== hydrationErrors &&
            (queueRecoverableErrors(hydrationErrors), (hydrationErrors = null)),
            (type = !0);
        if (!type) {
          if (workInProgress.flags & 256)
            return popSuspenseHandler(workInProgress), workInProgress;
          popSuspenseHandler(workInProgress);
          return null;
        }
      }
      popSuspenseHandler(workInProgress);
      if (0 !== (workInProgress.flags & 128))
        return (workInProgress.lanes = renderLanes), workInProgress;
      renderLanes = null !== newProps;
      current = null !== current && null !== current.memoizedState;
      if (renderLanes) {
        newProps = workInProgress.child;
        type = null;
        null !== newProps.alternate &&
          null !== newProps.alternate.memoizedState &&
          null !== newProps.alternate.memoizedState.cachePool &&
          (type = newProps.alternate.memoizedState.cachePool.pool);
        var cache$144 = null;
        null !== newProps.memoizedState &&
          null !== newProps.memoizedState.cachePool &&
          (cache$144 = newProps.memoizedState.cachePool.pool);
        cache$144 !== type && (newProps.flags |= 2048);
      }
      renderLanes !== current &&
        renderLanes &&
        (workInProgress.child.flags |= 8192);
      scheduleRetryEffect(workInProgress, workInProgress.updateQueue);
      bubbleProperties(workInProgress);
      return null;
    case 4:
      return (
        popHostContainer(),
        null === current &&
          listenToAllSupportedEvents(workInProgress.stateNode.containerInfo),
        bubbleProperties(workInProgress),
        null
      );
    case 10:
      return (
        popProvider(workInProgress.type), bubbleProperties(workInProgress), null
      );
    case 19:
      pop(suspenseStackCursor);
      type = workInProgress.memoizedState;
      if (null === type) return bubbleProperties(workInProgress), null;
      newProps = 0 !== (workInProgress.flags & 128);
      cache$144 = type.rendering;
      if (null === cache$144)
        if (newProps) cutOffTailIfNeeded(type, !1);
        else {
          if (
            0 !== workInProgressRootExitStatus ||
            (null !== current && 0 !== (current.flags & 128))
          )
            for (current = workInProgress.child; null !== current; ) {
              cache$144 = findFirstSuspended(current);
              if (null !== cache$144) {
                workInProgress.flags |= 128;
                cutOffTailIfNeeded(type, !1);
                current = cache$144.updateQueue;
                workInProgress.updateQueue = current;
                scheduleRetryEffect(workInProgress, current);
                workInProgress.subtreeFlags = 0;
                current = renderLanes;
                for (renderLanes = workInProgress.child; null !== renderLanes; )
                  resetWorkInProgress(renderLanes, current),
                    (renderLanes = renderLanes.sibling);
                push(
                  suspenseStackCursor,
                  (suspenseStackCursor.current & 1) | 2
                );
                return workInProgress.child;
              }
              current = current.sibling;
            }
          null !== type.tail &&
            now() > workInProgressRootRenderTargetTime &&
            ((workInProgress.flags |= 128),
            (newProps = !0),
            cutOffTailIfNeeded(type, !1),
            (workInProgress.lanes = 4194304));
        }
      else {
        if (!newProps)
          if (((current = findFirstSuspended(cache$144)), null !== current)) {
            if (
              ((workInProgress.flags |= 128),
              (newProps = !0),
              (current = current.updateQueue),
              (workInProgress.updateQueue = current),
              scheduleRetryEffect(workInProgress, current),
              cutOffTailIfNeeded(type, !0),
              null === type.tail &&
                "hidden" === type.tailMode &&
                !cache$144.alternate &&
                !isHydrating)
            )
              return bubbleProperties(workInProgress), null;
          } else
            2 * now() - type.renderingStartTime >
              workInProgressRootRenderTargetTime &&
              536870912 !== renderLanes &&
              ((workInProgress.flags |= 128),
              (newProps = !0),
              cutOffTailIfNeeded(type, !1),
              (workInProgress.lanes = 4194304));
        type.isBackwards
          ? ((cache$144.sibling = workInProgress.child),
            (workInProgress.child = cache$144))
          : ((current = type.last),
            null !== current
              ? (current.sibling = cache$144)
              : (workInProgress.child = cache$144),
            (type.last = cache$144));
      }
      if (null !== type.tail)
        return (
          (workInProgress = type.tail),
          (type.rendering = workInProgress),
          (type.tail = workInProgress.sibling),
          (type.renderingStartTime = now()),
          (workInProgress.sibling = null),
          (current = suspenseStackCursor.current),
          push(suspenseStackCursor, newProps ? (current & 1) | 2 : current & 1),
          workInProgress
        );
      bubbleProperties(workInProgress);
      return null;
    case 22:
    case 23:
      return (
        popSuspenseHandler(workInProgress),
        popHiddenContext(),
        (newProps = null !== workInProgress.memoizedState),
        null !== current
          ? (null !== current.memoizedState) !== newProps &&
            (workInProgress.flags |= 8192)
          : newProps && (workInProgress.flags |= 8192),
        newProps
          ? 0 !== (renderLanes & 536870912) &&
            0 === (workInProgress.flags & 128) &&
            (bubbleProperties(workInProgress),
            workInProgress.subtreeFlags & 6 && (workInProgress.flags |= 8192))
          : bubbleProperties(workInProgress),
        (renderLanes = workInProgress.updateQueue),
        null !== renderLanes &&
          scheduleRetryEffect(workInProgress, renderLanes.retryQueue),
        (renderLanes = null),
        null !== current &&
          null !== current.memoizedState &&
          null !== current.memoizedState.cachePool &&
          (renderLanes = current.memoizedState.cachePool.pool),
        (newProps = null),
        null !== workInProgress.memoizedState &&
          null !== workInProgress.memoizedState.cachePool &&
          (newProps = workInProgress.memoizedState.cachePool.pool),
        newProps !== renderLanes && (workInProgress.flags |= 2048),
        null !== current && pop(resumedCache),
        null
      );
    case 24:
      return (
        (renderLanes = null),
        null !== current && (renderLanes = current.memoizedState.cache),
        workInProgress.memoizedState.cache !== renderLanes &&
          (workInProgress.flags |= 2048),
        popProvider(CacheContext),
        bubbleProperties(workInProgress),
        null
      );
    case 25:
      return null;
  }
  throw Error(formatProdErrorMessage(156, workInProgress.tag));
}
function unwindWork(current, workInProgress) {
  popTreeContext(workInProgress);
  switch (workInProgress.tag) {
    case 1:
      return (
        (current = workInProgress.flags),
        current & 65536
          ? ((workInProgress.flags = (current & -65537) | 128), workInProgress)
          : null
      );
    case 3:
      return (
        popProvider(CacheContext),
        popHostContainer(),
        (current = workInProgress.flags),
        0 !== (current & 65536) && 0 === (current & 128)
          ? ((workInProgress.flags = (current & -65537) | 128), workInProgress)
          : null
      );
    case 26:
    case 27:
    case 5:
      return popHostContext(workInProgress), null;
    case 13:
      popSuspenseHandler(workInProgress);
      current = workInProgress.memoizedState;
      if (null !== current && null !== current.dehydrated) {
        if (null === workInProgress.alternate)
          throw Error(formatProdErrorMessage(340));
        resetHydrationState();
      }
      current = workInProgress.flags;
      return current & 65536
        ? ((workInProgress.flags = (current & -65537) | 128), workInProgress)
        : null;
    case 19:
      return pop(suspenseStackCursor), null;
    case 4:
      return popHostContainer(), null;
    case 10:
      return popProvider(workInProgress.type), null;
    case 22:
    case 23:
      return (
        popSuspenseHandler(workInProgress),
        popHiddenContext(),
        null !== current && pop(resumedCache),
        (current = workInProgress.flags),
        current & 65536
          ? ((workInProgress.flags = (current & -65537) | 128), workInProgress)
          : null
      );
    case 24:
      return popProvider(CacheContext), null;
    case 25:
      return null;
    default:
      return null;
  }
}
function unwindInterruptedWork(current, interruptedWork) {
  popTreeContext(interruptedWork);
  switch (interruptedWork.tag) {
    case 3:
      popProvider(CacheContext);
      popHostContainer();
      break;
    case 26:
    case 27:
    case 5:
      popHostContext(interruptedWork);
      break;
    case 4:
      popHostContainer();
      break;
    case 13:
      popSuspenseHandler(interruptedWork);
      break;
    case 19:
      pop(suspenseStackCursor);
      break;
    case 10:
      popProvider(interruptedWork.type);
      break;
    case 22:
    case 23:
      popSuspenseHandler(interruptedWork);
      popHiddenContext();
      null !== current && pop(resumedCache);
      break;
    case 24:
      popProvider(CacheContext);
  }
}
var DefaultAsyncDispatcher = {
    getCacheForType: function (resourceType) {
      var cache = readContext(CacheContext),
        cacheForType = cache.data.get(resourceType);
      void 0 === cacheForType &&
        ((cacheForType = resourceType()),
        cache.data.set(resourceType, cacheForType));
      return cacheForType;
    }
  },
  PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map,
  executionContext = 0,
  workInProgressRoot = null,
  workInProgress = null,
  workInProgressRootRenderLanes = 0,
  workInProgressSuspendedReason = 0,
  workInProgressThrownValue = null,
  workInProgressRootDidSkipSuspendedSiblings = !1,
  workInProgressRootIsPrerendering = !1,
  workInProgressRootDidAttachPingListener = !1,
  entangledRenderLanes = 0,
  workInProgressRootExitStatus = 0,
  workInProgressRootSkippedLanes = 0,
  workInProgressRootInterleavedUpdatedLanes = 0,
  workInProgressRootPingedLanes = 0,
  workInProgressDeferredLane = 0,
  workInProgressSuspendedRetryLanes = 0,
  workInProgressRootConcurrentErrors = null,
  workInProgressRootRecoverableErrors = null,
  workInProgressRootDidIncludeRecursiveRenderUpdate = !1,
  globalMostRecentFallbackTime = 0,
  workInProgressRootRenderTargetTime = Infinity,
  workInProgressTransitions = null,
  legacyErrorBoundariesThatAlreadyFailed = null,
  rootDoesHavePassiveEffects = !1,
  rootWithPendingPassiveEffects = null,
  pendingPassiveEffectsLanes = 0,
  pendingPassiveEffectsRemainingLanes = 0,
  pendingPassiveTransitions = null,
  nestedUpdateCount = 0,
  rootWithNestedUpdates = null;
function requestUpdateLane() {
  if (0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes)
    return workInProgressRootRenderLanes & -workInProgressRootRenderLanes;
  if (null !== ReactSharedInternals.T) {
    var actionScopeLane = currentEntangledLane;
    return 0 !== actionScopeLane ? actionScopeLane : requestTransitionLane();
  }
  return resolveUpdatePriority();
}
function requestDeferredLane() {
  0 === workInProgressDeferredLane &&
    (workInProgressDeferredLane =
      0 === (workInProgressRootRenderLanes & 536870912) || isHydrating
        ? claimNextTransitionLane()
        : 536870912);
  var suspenseHandler = suspenseHandlerStackCursor.current;
  null !== suspenseHandler && (suspenseHandler.flags |= 32);
  return workInProgressDeferredLane;
}
function scheduleUpdateOnFiber(root, fiber, lane) {
  if (
    (root === workInProgressRoot && 2 === workInProgressSuspendedReason) ||
    null !== root.cancelPendingCommit
  )
    prepareFreshStack(root, 0),
      markRootSuspended(
        root,
        workInProgressRootRenderLanes,
        workInProgressDeferredLane,
        !1
      );
  markRootUpdated$1(root, lane);
  if (0 === (executionContext & 2) || root !== workInProgressRoot)
    root === workInProgressRoot &&
      (0 === (executionContext & 2) &&
        (workInProgressRootInterleavedUpdatedLanes |= lane),
      4 === workInProgressRootExitStatus &&
        markRootSuspended(
          root,
          workInProgressRootRenderLanes,
          workInProgressDeferredLane,
          !1
        )),
      ensureRootIsScheduled(root);
}
function performWorkOnRoot(root$jscomp$0, lanes, forceSync) {
  if (0 !== (executionContext & 6)) throw Error(formatProdErrorMessage(327));
  var shouldTimeSlice =
      (!forceSync &&
        0 === (lanes & 60) &&
        0 === (lanes & root$jscomp$0.expiredLanes)) ||
      checkIfRootIsPrerendering(root$jscomp$0, lanes),
    exitStatus = shouldTimeSlice
      ? renderRootConcurrent(root$jscomp$0, lanes)
      : renderRootSync(root$jscomp$0, lanes, !0),
    renderWasConcurrent = shouldTimeSlice;
  do {
    if (0 === exitStatus) {
      workInProgressRootIsPrerendering &&
        !shouldTimeSlice &&
        markRootSuspended(root$jscomp$0, lanes, 0, !1);
      break;
    } else if (6 === exitStatus)
      markRootSuspended(
        root$jscomp$0,
        lanes,
        0,
        !workInProgressRootDidSkipSuspendedSiblings
      );
    else {
      forceSync = root$jscomp$0.current.alternate;
      if (
        renderWasConcurrent &&
        !isRenderConsistentWithExternalStores(forceSync)
      ) {
        exitStatus = renderRootSync(root$jscomp$0, lanes, !1);
        renderWasConcurrent = !1;
        continue;
      }
      if (2 === exitStatus) {
        renderWasConcurrent = lanes;
        if (root$jscomp$0.errorRecoveryDisabledLanes & renderWasConcurrent)
          var JSCompiler_inline_result = 0;
        else
          (JSCompiler_inline_result = root$jscomp$0.pendingLanes & -536870913),
            (JSCompiler_inline_result =
              0 !== JSCompiler_inline_result
                ? JSCompiler_inline_result
                : JSCompiler_inline_result & 536870912
                  ? 536870912
                  : 0);
        if (0 !== JSCompiler_inline_result) {
          lanes = JSCompiler_inline_result;
          a: {
            var root = root$jscomp$0;
            exitStatus = workInProgressRootConcurrentErrors;
            var wasRootDehydrated = root.current.memoizedState.isDehydrated;
            wasRootDehydrated &&
              (prepareFreshStack(root, JSCompiler_inline_result).flags |= 256);
            JSCompiler_inline_result = renderRootSync(
              root,
              JSCompiler_inline_result,
              !1
            );
            if (2 !== JSCompiler_inline_result) {
              if (
                workInProgressRootDidAttachPingListener &&
                !wasRootDehydrated
              ) {
                root.errorRecoveryDisabledLanes |= renderWasConcurrent;
                workInProgressRootInterleavedUpdatedLanes |=
                  renderWasConcurrent;
                exitStatus = 4;
                break a;
              }
              renderWasConcurrent = workInProgressRootRecoverableErrors;
              workInProgressRootRecoverableErrors = exitStatus;
              null !== renderWasConcurrent &&
                queueRecoverableErrors(renderWasConcurrent);
            }
            exitStatus = JSCompiler_inline_result;
          }
          renderWasConcurrent = !1;
          if (2 !== exitStatus) continue;
        }
      }
      if (1 === exitStatus) {
        prepareFreshStack(root$jscomp$0, 0);
        markRootSuspended(root$jscomp$0, lanes, 0, !0);
        break;
      }
      a: {
        shouldTimeSlice = root$jscomp$0;
        switch (exitStatus) {
          case 0:
          case 1:
            throw Error(formatProdErrorMessage(345));
          case 4:
            if ((lanes & 4194176) === lanes) {
              markRootSuspended(
                shouldTimeSlice,
                lanes,
                workInProgressDeferredLane,
                !workInProgressRootDidSkipSuspendedSiblings
              );
              break a;
            }
            break;
          case 2:
            workInProgressRootRecoverableErrors = null;
            break;
          case 3:
          case 5:
            break;
          default:
            throw Error(formatProdErrorMessage(329));
        }
        shouldTimeSlice.finishedWork = forceSync;
        shouldTimeSlice.finishedLanes = lanes;
        if (
          (lanes & 62914560) === lanes &&
          ((renderWasConcurrent = globalMostRecentFallbackTime + 300 - now()),
          10 < renderWasConcurrent)
        ) {
          markRootSuspended(
            shouldTimeSlice,
            lanes,
            workInProgressDeferredLane,
            !workInProgressRootDidSkipSuspendedSiblings
          );
          if (0 !== getNextLanes(shouldTimeSlice, 0)) break a;
          shouldTimeSlice.timeoutHandle = scheduleTimeout(
            commitRootWhenReady.bind(
              null,
              shouldTimeSlice,
              forceSync,
              workInProgressRootRecoverableErrors,
              workInProgressTransitions,
              workInProgressRootDidIncludeRecursiveRenderUpdate,
              lanes,
              workInProgressDeferredLane,
              workInProgressRootInterleavedUpdatedLanes,
              workInProgressSuspendedRetryLanes,
              workInProgressRootDidSkipSuspendedSiblings,
              2,
              -0,
              0
            ),
            renderWasConcurrent
          );
          break a;
        }
        commitRootWhenReady(
          shouldTimeSlice,
          forceSync,
          workInProgressRootRecoverableErrors,
          workInProgressTransitions,
          workInProgressRootDidIncludeRecursiveRenderUpdate,
          lanes,
          workInProgressDeferredLane,
          workInProgressRootInterleavedUpdatedLanes,
          workInProgressSuspendedRetryLanes,
          workInProgressRootDidSkipSuspendedSiblings,
          0,
          -0,
          0
        );
      }
    }
    break;
  } while (1);
  ensureRootIsScheduled(root$jscomp$0);
}
function queueRecoverableErrors(errors) {
  null === workInProgressRootRecoverableErrors
    ? (workInProgressRootRecoverableErrors = errors)
    : workInProgressRootRecoverableErrors.push.apply(
        workInProgressRootRecoverableErrors,
        errors
      );
}
function commitRootWhenReady(
  root,
  finishedWork,
  recoverableErrors,
  transitions,
  didIncludeRenderPhaseUpdate,
  lanes,
  spawnedLane,
  updatedLanes,
  suspendedRetryLanes,
  didSkipSuspendedSiblings,
  suspendedCommitReason,
  completedRenderStartTime,
  completedRenderEndTime
) {
  var subtreeFlags = finishedWork.subtreeFlags;
  if (subtreeFlags & 8192 || 16785408 === (subtreeFlags & 16785408))
    if (
      ((suspendedState = { stylesheets: null, count: 0, unsuspend: noop }),
      accumulateSuspenseyCommitOnFiber(finishedWork),
      (finishedWork = waitForCommitToBeReady()),
      null !== finishedWork)
    ) {
      root.cancelPendingCommit = finishedWork(
        commitRoot.bind(
          null,
          root,
          recoverableErrors,
          transitions,
          didIncludeRenderPhaseUpdate,
          spawnedLane,
          updatedLanes,
          suspendedRetryLanes,
          1,
          completedRenderStartTime,
          completedRenderEndTime
        )
      );
      markRootSuspended(root, lanes, spawnedLane, !didSkipSuspendedSiblings);
      return;
    }
  commitRoot(
    root,
    recoverableErrors,
    transitions,
    didIncludeRenderPhaseUpdate,
    spawnedLane,
    updatedLanes,
    suspendedRetryLanes,
    suspendedCommitReason,
    completedRenderStartTime,
    completedRenderEndTime
  );
}
function isRenderConsistentWithExternalStores(finishedWork) {
  for (var node = finishedWork; ; ) {
    var tag = node.tag;
    if (
      (0 === tag || 11 === tag || 15 === tag) &&
      node.flags & 16384 &&
      ((tag = node.updateQueue),
      null !== tag && ((tag = tag.stores), null !== tag))
    )
      for (var i = 0; i < tag.length; i++) {
        var check = tag[i],
          getSnapshot = check.getSnapshot;
        check = check.value;
        try {
          if (!objectIs(getSnapshot(), check)) return !1;
        } catch (error) {
          return !1;
        }
      }
    tag = node.child;
    if (node.subtreeFlags & 16384 && null !== tag)
      (tag.return = node), (node = tag);
    else {
      if (node === finishedWork) break;
      for (; null === node.sibling; ) {
        if (null === node.return || node.return === finishedWork) return !0;
        node = node.return;
      }
      node.sibling.return = node.return;
      node = node.sibling;
    }
  }
  return !0;
}
function markRootSuspended(
  root,
  suspendedLanes,
  spawnedLane,
  didAttemptEntireTree
) {
  suspendedLanes &= ~workInProgressRootPingedLanes;
  suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes;
  root.suspendedLanes |= suspendedLanes;
  root.pingedLanes &= ~suspendedLanes;
  didAttemptEntireTree && (root.warmLanes |= suspendedLanes);
  didAttemptEntireTree = root.expirationTimes;
  for (var lanes = suspendedLanes; 0 < lanes; ) {
    var index$6 = 31 - clz32(lanes),
      lane = 1 << index$6;
    didAttemptEntireTree[index$6] = -1;
    lanes &= ~lane;
  }
  0 !== spawnedLane &&
    markSpawnedDeferredLane(root, spawnedLane, suspendedLanes);
}
function flushSyncWork$1() {
  return 0 === (executionContext & 6)
    ? (flushSyncWorkAcrossRoots_impl(0, !1), !1)
    : !0;
}
function resetWorkInProgressStack() {
  if (null !== workInProgress) {
    if (0 === workInProgressSuspendedReason)
      var interruptedWork = workInProgress.return;
    else
      (interruptedWork = workInProgress),
        (lastContextDependency = currentlyRenderingFiber = null),
        resetHooksOnUnwind(interruptedWork),
        (thenableState$1 = null),
        (thenableIndexCounter$1 = 0),
        (interruptedWork = workInProgress);
    for (; null !== interruptedWork; )
      unwindInterruptedWork(interruptedWork.alternate, interruptedWork),
        (interruptedWork = interruptedWork.return);
    workInProgress = null;
  }
}
function prepareFreshStack(root, lanes) {
  root.finishedWork = null;
  root.finishedLanes = 0;
  var timeoutHandle = root.timeoutHandle;
  -1 !== timeoutHandle &&
    ((root.timeoutHandle = -1), cancelTimeout(timeoutHandle));
  timeoutHandle = root.cancelPendingCommit;
  null !== timeoutHandle &&
    ((root.cancelPendingCommit = null), timeoutHandle());
  resetWorkInProgressStack();
  workInProgressRoot = root;
  workInProgress = timeoutHandle = createWorkInProgress(root.current, null);
  workInProgressRootRenderLanes = lanes;
  workInProgressSuspendedReason = 0;
  workInProgressThrownValue = null;
  workInProgressRootDidSkipSuspendedSiblings = !1;
  workInProgressRootIsPrerendering = checkIfRootIsPrerendering(root, lanes);
  workInProgressRootDidAttachPingListener = !1;
  workInProgressSuspendedRetryLanes =
    workInProgressDeferredLane =
    workInProgressRootPingedLanes =
    workInProgressRootInterleavedUpdatedLanes =
    workInProgressRootSkippedLanes =
    workInProgressRootExitStatus =
      0;
  workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors =
    null;
  workInProgressRootDidIncludeRecursiveRenderUpdate = !1;
  0 !== (lanes & 8) && (lanes |= lanes & 32);
  var allEntangledLanes = root.entangledLanes;
  if (0 !== allEntangledLanes)
    for (
      root = root.entanglements, allEntangledLanes &= lanes;
      0 < allEntangledLanes;

    ) {
      var index$4 = 31 - clz32(allEntangledLanes),
        lane = 1 << index$4;
      lanes |= root[index$4];
      allEntangledLanes &= ~lane;
    }
  entangledRenderLanes = lanes;
  finishQueueingConcurrentUpdates();
  return timeoutHandle;
}
function handleThrow(root, thrownValue) {
  currentlyRenderingFiber$1 = null;
  ReactSharedInternals.H = ContextOnlyDispatcher;
  thrownValue === SuspenseException
    ? ((thrownValue = getSuspendedThenable()),
      (workInProgressSuspendedReason = 3))
    : thrownValue === SuspenseyCommitException
      ? ((thrownValue = getSuspendedThenable()),
        (workInProgressSuspendedReason = 4))
      : (workInProgressSuspendedReason =
          thrownValue === SelectiveHydrationException
            ? 8
            : null !== thrownValue &&
                "object" === typeof thrownValue &&
                "function" === typeof thrownValue.then
              ? 6
              : 1);
  workInProgressThrownValue = thrownValue;
  null === workInProgress &&
    ((workInProgressRootExitStatus = 1),
    logUncaughtError(
      root,
      createCapturedValueAtFiber(thrownValue, root.current)
    ));
}
function pushDispatcher() {
  var prevDispatcher = ReactSharedInternals.H;
  ReactSharedInternals.H = ContextOnlyDispatcher;
  return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher;
}
function pushAsyncDispatcher() {
  var prevAsyncDispatcher = ReactSharedInternals.A;
  ReactSharedInternals.A = DefaultAsyncDispatcher;
  return prevAsyncDispatcher;
}
function renderDidSuspendDelayIfPossible() {
  workInProgressRootExitStatus = 4;
  workInProgressRootDidSkipSuspendedSiblings ||
    ((workInProgressRootRenderLanes & 4194176) !==
      workInProgressRootRenderLanes &&
      null !== suspenseHandlerStackCursor.current) ||
    (workInProgressRootIsPrerendering = !0);
  (0 === (workInProgressRootSkippedLanes & 134217727) &&
    0 === (workInProgressRootInterleavedUpdatedLanes & 134217727)) ||
    null === workInProgressRoot ||
    markRootSuspended(
      workInProgressRoot,
      workInProgressRootRenderLanes,
      workInProgressDeferredLane,
      !1
    );
}
function renderRootSync(root, lanes, shouldYieldForPrerendering) {
  var prevExecutionContext = executionContext;
  executionContext |= 2;
  var prevDispatcher = pushDispatcher(),
    prevAsyncDispatcher = pushAsyncDispatcher();
  if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes)
    (workInProgressTransitions = null), prepareFreshStack(root, lanes);
  lanes = !1;
  var exitStatus = workInProgressRootExitStatus;
  a: do
    try {
      if (0 !== workInProgressSuspendedReason && null !== workInProgress) {
        var unitOfWork = workInProgress,
          thrownValue = workInProgressThrownValue;
        switch (workInProgressSuspendedReason) {
          case 8:
            resetWorkInProgressStack();
            exitStatus = 6;
            break a;
          case 3:
          case 2:
          case 6:
            null === suspenseHandlerStackCursor.current && (lanes = !0);
            var reason = workInProgressSuspendedReason;
            workInProgressSuspendedReason = 0;
            workInProgressThrownValue = null;
            throwAndUnwindWorkLoop(root, unitOfWork, thrownValue, reason);
            if (
              shouldYieldForPrerendering &&
              workInProgressRootIsPrerendering
            ) {
              exitStatus = 0;
              break a;
            }
            break;
          default:
            (reason = workInProgressSuspendedReason),
              (workInProgressSuspendedReason = 0),
              (workInProgressThrownValue = null),
              throwAndUnwindWorkLoop(root, unitOfWork, thrownValue, reason);
        }
      }
      workLoopSync();
      exitStatus = workInProgressRootExitStatus;
      break;
    } catch (thrownValue$164) {
      handleThrow(root, thrownValue$164);
    }
  while (1);
  lanes && root.shellSuspendCounter++;
  lastContextDependency = currentlyRenderingFiber = null;
  executionContext = prevExecutionContext;
  ReactSharedInternals.H = prevDispatcher;
  ReactSharedInternals.A = prevAsyncDispatcher;
  null === workInProgress &&
    ((workInProgressRoot = null),
    (workInProgressRootRenderLanes = 0),
    finishQueueingConcurrentUpdates());
  return exitStatus;
}
function workLoopSync() {
  for (; null !== workInProgress; ) performUnitOfWork(workInProgress);
}
function renderRootConcurrent(root, lanes) {
  var prevExecutionContext = executionContext;
  executionContext |= 2;
  var prevDispatcher = pushDispatcher(),
    prevAsyncDispatcher = pushAsyncDispatcher();
  workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes
    ? ((workInProgressTransitions = null),
      (workInProgressRootRenderTargetTime = now() + 500),
      prepareFreshStack(root, lanes))
    : (workInProgressRootIsPrerendering = checkIfRootIsPrerendering(
        root,
        lanes
      ));
  a: do
    try {
      if (0 !== workInProgressSuspendedReason && null !== workInProgress) {
        lanes = workInProgress;
        var thrownValue = workInProgressThrownValue;
        b: switch (workInProgressSuspendedReason) {
          case 1:
            workInProgressSuspendedReason = 0;
            workInProgressThrownValue = null;
            throwAndUnwindWorkLoop(root, lanes, thrownValue, 1);
            break;
          case 2:
            if (isThenableResolved(thrownValue)) {
              workInProgressSuspendedReason = 0;
              workInProgressThrownValue = null;
              replaySuspendedUnitOfWork(lanes);
              break;
            }
            lanes = function () {
              2 === workInProgressSuspendedReason &&
                workInProgressRoot === root &&
                (workInProgressSuspendedReason = 7);
              ensureRootIsScheduled(root);
            };
            thrownValue.then(lanes, lanes);
            break a;
          case 3:
            workInProgressSuspendedReason = 7;
            break a;
          case 4:
            workInProgressSuspendedReason = 5;
            break a;
          case 7:
            isThenableResolved(thrownValue)
              ? ((workInProgressSuspendedReason = 0),
                (workInProgressThrownValue = null),
                replaySuspendedUnitOfWork(lanes))
              : ((workInProgressSuspendedReason = 0),
                (workInProgressThrownValue = null),
                throwAndUnwindWorkLoop(root, lanes, thrownValue, 7));
            break;
          case 5:
            var resource = null;
            switch (workInProgress.tag) {
              case 26:
                resource = workInProgress.memoizedState;
              case 5:
              case 27:
                var hostFiber = workInProgress;
                if (resource ? preloadResource(resource) : 1) {
                  workInProgressSuspendedReason = 0;
                  workInProgressThrownValue = null;
                  var sibling = hostFiber.sibling;
                  if (null !== sibling) workInProgress = sibling;
                  else {
                    var returnFiber = hostFiber.return;
                    null !== returnFiber
                      ? ((workInProgress = returnFiber),
                        completeUnitOfWork(returnFiber))
                      : (workInProgress = null);
                  }
                  break b;
                }
            }
            workInProgressSuspendedReason = 0;
            workInProgressThrownValue = null;
            throwAndUnwindWorkLoop(root, lanes, thrownValue, 5);
            break;
          case 6:
            workInProgressSuspendedReason = 0;
            workInProgressThrownValue = null;
            throwAndUnwindWorkLoop(root, lanes, thrownValue, 6);
            break;
          case 8:
            resetWorkInProgressStack();
            workInProgressRootExitStatus = 6;
            break a;
          default:
            throw Error(formatProdErrorMessage(462));
        }
      }
      workLoopConcurrent();
      break;
    } catch (thrownValue$166) {
      handleThrow(root, thrownValue$166);
    }
  while (1);
  lastContextDependency = currentlyRenderingFiber = null;
  ReactSharedInternals.H = prevDispatcher;
  ReactSharedInternals.A = prevAsyncDispatcher;
  executionContext = prevExecutionContext;
  if (null !== workInProgress) return 0;
  workInProgressRoot = null;
  workInProgressRootRenderLanes = 0;
  finishQueueingConcurrentUpdates();
  return workInProgressRootExitStatus;
}
function workLoopConcurrent() {
  for (; null !== workInProgress && !shouldYield(); )
    performUnitOfWork(workInProgress);
}
function performUnitOfWork(unitOfWork) {
  var next = beginWork(unitOfWork.alternate, unitOfWork, entangledRenderLanes);
  unitOfWork.memoizedProps = unitOfWork.pendingProps;
  null === next ? completeUnitOfWork(unitOfWork) : (workInProgress = next);
}
function replaySuspendedUnitOfWork(unitOfWork) {
  var next = unitOfWork;
  var current = next.alternate;
  switch (next.tag) {
    case 15:
    case 0:
      next = replayFunctionComponent(
        current,
        next,
        next.pendingProps,
        next.type,
        void 0,
        workInProgressRootRenderLanes
      );
      break;
    case 11:
      next = replayFunctionComponent(
        current,
        next,
        next.pendingProps,
        next.type.render,
        next.ref,
        workInProgressRootRenderLanes
      );
      break;
    case 5:
      resetHooksOnUnwind(next);
    default:
      unwindInterruptedWork(current, next),
        (next = workInProgress =
          resetWorkInProgress(next, entangledRenderLanes)),
        (next = beginWork(current, next, entangledRenderLanes));
  }
  unitOfWork.memoizedProps = unitOfWork.pendingProps;
  null === next ? completeUnitOfWork(unitOfWork) : (workInProgress = next);
}
function throwAndUnwindWorkLoop(
  root,
  unitOfWork,
  thrownValue,
  suspendedReason
) {
  lastContextDependency = currentlyRenderingFiber = null;
  resetHooksOnUnwind(unitOfWork);
  thenableState$1 = null;
  thenableIndexCounter$1 = 0;
  var returnFiber = unitOfWork.return;
  try {
    if (
      throwException(
        root,
        returnFiber,
        unitOfWork,
        thrownValue,
        workInProgressRootRenderLanes
      )
    ) {
      workInProgressRootExitStatus = 1;
      logUncaughtError(
        root,
        createCapturedValueAtFiber(thrownValue, root.current)
      );
      workInProgress = null;
      return;
    }
  } catch (error) {
    if (null !== returnFiber) throw ((workInProgress = returnFiber), error);
    workInProgressRootExitStatus = 1;
    logUncaughtError(
      root,
      createCapturedValueAtFiber(thrownValue, root.current)
    );
    workInProgress = null;
    return;
  }
  if (unitOfWork.flags & 32768) {
    if (isHydrating || 1 === suspendedReason) root = !0;
    else if (
      workInProgressRootIsPrerendering ||
      0 !== (workInProgressRootRenderLanes & 536870912)
    )
      root = !1;
    else if (
      ((workInProgressRootDidSkipSuspendedSiblings = root = !0),
      2 === suspendedReason || 3 === suspendedReason || 6 === suspendedReason)
    )
      (suspendedReason = suspenseHandlerStackCursor.current),
        null !== suspendedReason &&
          13 === suspendedReason.tag &&
          (suspendedReason.flags |= 16384);
    unwindUnitOfWork(unitOfWork, root);
  } else completeUnitOfWork(unitOfWork);
}
function completeUnitOfWork(unitOfWork) {
  var completedWork = unitOfWork;
  do {
    if (0 !== (completedWork.flags & 32768)) {
      unwindUnitOfWork(
        completedWork,
        workInProgressRootDidSkipSuspendedSiblings
      );
      return;
    }
    unitOfWork = completedWork.return;
    var next = completeWork(
      completedWork.alternate,
      completedWork,
      entangledRenderLanes
    );
    if (null !== next) {
      workInProgress = next;
      return;
    }
    completedWork = completedWork.sibling;
    if (null !== completedWork) {
      workInProgress = completedWork;
      return;
    }
    workInProgress = completedWork = unitOfWork;
  } while (null !== completedWork);
  0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5);
}
function unwindUnitOfWork(unitOfWork, skipSiblings) {
  do {
    var next = unwindWork(unitOfWork.alternate, unitOfWork);
    if (null !== next) {
      next.flags &= 32767;
      workInProgress = next;
      return;
    }
    next = unitOfWork.return;
    null !== next &&
      ((next.flags |= 32768), (next.subtreeFlags = 0), (next.deletions = null));
    if (
      !skipSiblings &&
      ((unitOfWork = unitOfWork.sibling), null !== unitOfWork)
    ) {
      workInProgress = unitOfWork;
      return;
    }
    workInProgress = unitOfWork = next;
  } while (null !== unitOfWork);
  workInProgressRootExitStatus = 6;
  workInProgress = null;
}
function commitRoot(
  root,
  recoverableErrors,
  transitions,
  didIncludeRenderPhaseUpdate,
  spawnedLane,
  updatedLanes,
  suspendedRetryLanes,
  suspendedCommitReason,
  completedRenderStartTime,
  completedRenderEndTime
) {
  var prevTransition = ReactSharedInternals.T,
    previousUpdateLanePriority = ReactDOMSharedInternals.p;
  try {
    (ReactDOMSharedInternals.p = 2),
      (ReactSharedInternals.T = null),
      commitRootImpl(
        root,
        recoverableErrors,
        transitions,
        didIncludeRenderPhaseUpdate,
        previousUpdateLanePriority,
        spawnedLane,
        updatedLanes,
        suspendedRetryLanes,
        suspendedCommitReason,
        completedRenderStartTime,
        completedRenderEndTime
      );
  } finally {
    (ReactSharedInternals.T = prevTransition),
      (ReactDOMSharedInternals.p = previousUpdateLanePriority);
  }
}
function commitRootImpl(
  root,
  recoverableErrors,
  transitions,
  didIncludeRenderPhaseUpdate,
  renderPriorityLevel,
  spawnedLane,
  updatedLanes,
  suspendedRetryLanes
) {
  do flushPassiveEffects();
  while (null !== rootWithPendingPassiveEffects);
  if (0 !== (executionContext & 6)) throw Error(formatProdErrorMessage(327));
  var finishedWork = root.finishedWork;
  didIncludeRenderPhaseUpdate = root.finishedLanes;
  if (null === finishedWork) return null;
  root.finishedWork = null;
  root.finishedLanes = 0;
  if (finishedWork === root.current) throw Error(formatProdErrorMessage(177));
  root.callbackNode = null;
  root.callbackPriority = 0;
  root.cancelPendingCommit = null;
  var remainingLanes = finishedWork.lanes | finishedWork.childLanes;
  remainingLanes |= concurrentlyUpdatedLanes;
  markRootFinished(
    root,
    didIncludeRenderPhaseUpdate,
    remainingLanes,
    spawnedLane,
    updatedLanes,
    suspendedRetryLanes
  );
  root === workInProgressRoot &&
    ((workInProgress = workInProgressRoot = null),
    (workInProgressRootRenderLanes = 0));
  (0 === (finishedWork.subtreeFlags & 10256) &&
    0 === (finishedWork.flags & 10256)) ||
    rootDoesHavePassiveEffects ||
    ((rootDoesHavePassiveEffects = !0),
    (pendingPassiveEffectsRemainingLanes = remainingLanes),
    (pendingPassiveTransitions = transitions),
    scheduleCallback$1(NormalPriority$1, function () {
      flushPassiveEffects(!0);
      return null;
    }));
  transitions = 0 !== (finishedWork.flags & 15990);
  0 !== (finishedWork.subtreeFlags & 15990) || transitions
    ? ((transitions = ReactSharedInternals.T),
      (ReactSharedInternals.T = null),
      (spawnedLane = ReactDOMSharedInternals.p),
      (ReactDOMSharedInternals.p = 2),
      (updatedLanes = executionContext),
      (executionContext |= 4),
      commitBeforeMutationEffects(root, finishedWork),
      commitMutationEffectsOnFiber(finishedWork, root),
      restoreSelection(selectionInformation, root.containerInfo),
      (_enabled = !!eventsEnabled),
      (selectionInformation = eventsEnabled = null),
      (root.current = finishedWork),
      commitLayoutEffectOnFiber(root, finishedWork.alternate, finishedWork),
      requestPaint(),
      (executionContext = updatedLanes),
      (ReactDOMSharedInternals.p = spawnedLane),
      (ReactSharedInternals.T = transitions))
    : (root.current = finishedWork);
  rootDoesHavePassiveEffects
    ? ((rootDoesHavePassiveEffects = !1),
      (rootWithPendingPassiveEffects = root),
      (pendingPassiveEffectsLanes = didIncludeRenderPhaseUpdate))
    : releaseRootPooledCache(root, remainingLanes);
  remainingLanes = root.pendingLanes;
  0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null);
  onCommitRoot(finishedWork.stateNode, renderPriorityLevel);
  ensureRootIsScheduled(root);
  if (null !== recoverableErrors)
    for (
      renderPriorityLevel = root.onRecoverableError, finishedWork = 0;
      finishedWork < recoverableErrors.length;
      finishedWork++
    )
      (remainingLanes = recoverableErrors[finishedWork]),
        renderPriorityLevel(remainingLanes.value, {
          componentStack: remainingLanes.stack
        });
  0 !== (pendingPassiveEffectsLanes & 3) && flushPassiveEffects();
  remainingLanes = root.pendingLanes;
  0 !== (didIncludeRenderPhaseUpdate & 4194218) && 0 !== (remainingLanes & 42)
    ? root === rootWithNestedUpdates
      ? nestedUpdateCount++
      : ((nestedUpdateCount = 0), (rootWithNestedUpdates = root))
    : (nestedUpdateCount = 0);
  flushSyncWorkAcrossRoots_impl(0, !1);
  return null;
}
function releaseRootPooledCache(root, remainingLanes) {
  0 === (root.pooledCacheLanes &= remainingLanes) &&
    ((remainingLanes = root.pooledCache),
    null != remainingLanes &&
      ((root.pooledCache = null), releaseCache(remainingLanes)));
}
function flushPassiveEffects() {
  if (null !== rootWithPendingPassiveEffects) {
    var root$170 = rootWithPendingPassiveEffects,
      remainingLanes = pendingPassiveEffectsRemainingLanes;
    pendingPassiveEffectsRemainingLanes = 0;
    var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes),
      prevTransition = ReactSharedInternals.T,
      previousPriority = ReactDOMSharedInternals.p;
    try {
      ReactDOMSharedInternals.p = 32 > renderPriority ? 32 : renderPriority;
      ReactSharedInternals.T = null;
      if (null === rootWithPendingPassiveEffects)
        var JSCompiler_inline_result = !1;
      else {
        renderPriority = pendingPassiveTransitions;
        pendingPassiveTransitions = null;
        var root = rootWithPendingPassiveEffects,
          lanes = pendingPassiveEffectsLanes;
        rootWithPendingPassiveEffects = null;
        pendingPassiveEffectsLanes = 0;
        if (0 !== (executionContext & 6))
          throw Error(formatProdErrorMessage(331));
        var prevExecutionContext = executionContext;
        executionContext |= 4;
        commitPassiveUnmountOnFiber(root.current);
        commitPassiveMountOnFiber(root, root.current, lanes, renderPriority);
        executionContext = prevExecutionContext;
        flushSyncWorkAcrossRoots_impl(0, !1);
        if (
          injectedHook &&
          "function" === typeof injectedHook.onPostCommitFiberRoot
        )
          try {
            injectedHook.onPostCommitFiberRoot(rendererID, root);
          } catch (err) {}
        JSCompiler_inline_result = !0;
      }
      return JSCompiler_inline_result;
    } finally {
      (ReactDOMSharedInternals.p = previousPriority),
        (ReactSharedInternals.T = prevTransition),
        releaseRootPooledCache(root$170, remainingLanes);
    }
  }
  return !1;
}
function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
  sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
  sourceFiber = createRootErrorUpdate(rootFiber.stateNode, sourceFiber, 2);
  rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2);
  null !== rootFiber &&
    (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber));
}
function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) {
  if (3 === sourceFiber.tag)
    captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
  else
    for (; null !== nearestMountedAncestor; ) {
      if (3 === nearestMountedAncestor.tag) {
        captureCommitPhaseErrorOnRoot(
          nearestMountedAncestor,
          sourceFiber,
          error
        );
        break;
      } else if (1 === nearestMountedAncestor.tag) {
        var instance = nearestMountedAncestor.stateNode;
        if (
          "function" ===
            typeof nearestMountedAncestor.type.getDerivedStateFromError ||
          ("function" === typeof instance.componentDidCatch &&
            (null === legacyErrorBoundariesThatAlreadyFailed ||
              !legacyErrorBoundariesThatAlreadyFailed.has(instance)))
        ) {
          sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
          error = createClassErrorUpdate(2);
          instance = enqueueUpdate(nearestMountedAncestor, error, 2);
          null !== instance &&
            (initializeClassErrorUpdate(
              error,
              instance,
              nearestMountedAncestor,
              sourceFiber
            ),
            markRootUpdated$1(instance, 2),
            ensureRootIsScheduled(instance));
          break;
        }
      }
      nearestMountedAncestor = nearestMountedAncestor.return;
    }
}
function attachPingListener(root, wakeable, lanes) {
  var pingCache = root.pingCache;
  if (null === pingCache) {
    pingCache = root.pingCache = new PossiblyWeakMap();
    var threadIDs = new Set();
    pingCache.set(wakeable, threadIDs);
  } else
    (threadIDs = pingCache.get(wakeable)),
      void 0 === threadIDs &&
        ((threadIDs = new Set()), pingCache.set(wakeable, threadIDs));
  threadIDs.has(lanes) ||
    ((workInProgressRootDidAttachPingListener = !0),
    threadIDs.add(lanes),
    (root = pingSuspendedRoot.bind(null, root, wakeable, lanes)),
    wakeable.then(root, root));
}
function pingSuspendedRoot(root, wakeable, pingedLanes) {
  var pingCache = root.pingCache;
  null !== pingCache && pingCache.delete(wakeable);
  root.pingedLanes |= root.suspendedLanes & pingedLanes;
  root.warmLanes &= ~pingedLanes;
  workInProgressRoot === root &&
    (workInProgressRootRenderLanes & pingedLanes) === pingedLanes &&
    (4 === workInProgressRootExitStatus ||
    (3 === workInProgressRootExitStatus &&
      (workInProgressRootRenderLanes & 62914560) ===
        workInProgressRootRenderLanes &&
      300 > now() - globalMostRecentFallbackTime)
      ? 0 === (executionContext & 2) && prepareFreshStack(root, 0)
      : (workInProgressRootPingedLanes |= pingedLanes),
    workInProgressSuspendedRetryLanes === workInProgressRootRenderLanes &&
      (workInProgressSuspendedRetryLanes = 0));
  ensureRootIsScheduled(root);
}
function retryTimedOutBoundary(boundaryFiber, retryLane) {
  0 === retryLane && (retryLane = claimNextRetryLane());
  boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
  null !== boundaryFiber &&
    (markRootUpdated$1(boundaryFiber, retryLane),
    ensureRootIsScheduled(boundaryFiber));
}
function retryDehydratedSuspenseBoundary(boundaryFiber) {
  var suspenseState = boundaryFiber.memoizedState,
    retryLane = 0;
  null !== suspenseState && (retryLane = suspenseState.retryLane);
  retryTimedOutBoundary(boundaryFiber, retryLane);
}
function resolveRetryWakeable(boundaryFiber, wakeable) {
  var retryLane = 0;
  switch (boundaryFiber.tag) {
    case 13:
      var retryCache = boundaryFiber.stateNode;
      var suspenseState = boundaryFiber.memoizedState;
      null !== suspenseState && (retryLane = suspenseState.retryLane);
      break;
    case 19:
      retryCache = boundaryFiber.stateNode;
      break;
    case 22:
      retryCache = boundaryFiber.stateNode._retryCache;
      break;
    default:
      throw Error(formatProdErrorMessage(314));
  }
  null !== retryCache && retryCache.delete(wakeable);
  retryTimedOutBoundary(boundaryFiber, retryLane);
}
function scheduleCallback$1(priorityLevel, callback) {
  return scheduleCallback$3(priorityLevel, callback);
}
var firstScheduledRoot = null,
  lastScheduledRoot = null,
  didScheduleMicrotask = !1,
  mightHavePendingSyncWork = !1,
  isFlushingWork = !1,
  currentEventTransitionLane = 0;
function ensureRootIsScheduled(root) {
  root !== lastScheduledRoot &&
    null === root.next &&
    (null === lastScheduledRoot
      ? (firstScheduledRoot = lastScheduledRoot = root)
      : (lastScheduledRoot = lastScheduledRoot.next = root));
  mightHavePendingSyncWork = !0;
  didScheduleMicrotask ||
    ((didScheduleMicrotask = !0),
    scheduleImmediateTask(processRootScheduleInMicrotask));
}
function flushSyncWorkAcrossRoots_impl(syncTransitionLanes, onlyLegacy) {
  if (!isFlushingWork && mightHavePendingSyncWork) {
    isFlushingWork = !0;
    do {
      var didPerformSomeWork = !1;
      for (var root$172 = firstScheduledRoot; null !== root$172; ) {
        if (!onlyLegacy)
          if (0 !== syncTransitionLanes) {
            var pendingLanes = root$172.pendingLanes;
            if (0 === pendingLanes) var JSCompiler_inline_result = 0;
            else {
              var suspendedLanes = root$172.suspendedLanes,
                pingedLanes = root$172.pingedLanes;
              JSCompiler_inline_result =
                (1 << (31 - clz32(42 | syncTransitionLanes) + 1)) - 1;
              JSCompiler_inline_result &=
                pendingLanes & ~(suspendedLanes & ~pingedLanes);
              JSCompiler_inline_result =
                JSCompiler_inline_result & 201326677
                  ? (JSCompiler_inline_result & 201326677) | 1
                  : JSCompiler_inline_result
                    ? JSCompiler_inline_result | 2
                    : 0;
            }
            0 !== JSCompiler_inline_result &&
              ((didPerformSomeWork = !0),
              performSyncWorkOnRoot(root$172, JSCompiler_inline_result));
          } else
            (JSCompiler_inline_result = workInProgressRootRenderLanes),
              (JSCompiler_inline_result = getNextLanes(
                root$172,
                root$172 === workInProgressRoot ? JSCompiler_inline_result : 0
              )),
              0 === (JSCompiler_inline_result & 3) ||
                checkIfRootIsPrerendering(root$172, JSCompiler_inline_result) ||
                ((didPerformSomeWork = !0),
                performSyncWorkOnRoot(root$172, JSCompiler_inline_result));
        root$172 = root$172.next;
      }
    } while (didPerformSomeWork);
    isFlushingWork = !1;
  }
}
function processRootScheduleInMicrotask() {
  mightHavePendingSyncWork = didScheduleMicrotask = !1;
  var syncTransitionLanes = 0;
  0 !== currentEventTransitionLane &&
    (shouldAttemptEagerTransition() &&
      (syncTransitionLanes = currentEventTransitionLane),
    (currentEventTransitionLane = 0));
  for (
    var currentTime = now(), prev = null, root = firstScheduledRoot;
    null !== root;

  ) {
    var next = root.next,
      nextLanes = scheduleTaskForRootDuringMicrotask(root, currentTime);
    if (0 === nextLanes)
      (root.next = null),
        null === prev ? (firstScheduledRoot = next) : (prev.next = next),
        null === next && (lastScheduledRoot = prev);
    else if (
      ((prev = root), 0 !== syncTransitionLanes || 0 !== (nextLanes & 3))
    )
      mightHavePendingSyncWork = !0;
    root = next;
  }
  flushSyncWorkAcrossRoots_impl(syncTransitionLanes, !1);
}
function scheduleTaskForRootDuringMicrotask(root, currentTime) {
  for (
    var suspendedLanes = root.suspendedLanes,
      pingedLanes = root.pingedLanes,
      expirationTimes = root.expirationTimes,
      lanes = root.pendingLanes & -62914561;
    0 < lanes;

  ) {
    var index$5 = 31 - clz32(lanes),
      lane = 1 << index$5,
      expirationTime = expirationTimes[index$5];
    if (-1 === expirationTime) {
      if (0 === (lane & suspendedLanes) || 0 !== (lane & pingedLanes))
        expirationTimes[index$5] = computeExpirationTime(lane, currentTime);
    } else expirationTime <= currentTime && (root.expiredLanes |= lane);
    lanes &= ~lane;
  }
  currentTime = workInProgressRoot;
  suspendedLanes = workInProgressRootRenderLanes;
  suspendedLanes = getNextLanes(
    root,
    root === currentTime ? suspendedLanes : 0
  );
  pingedLanes = root.callbackNode;
  if (
    0 === suspendedLanes ||
    (root === currentTime && 2 === workInProgressSuspendedReason) ||
    null !== root.cancelPendingCommit
  )
    return (
      null !== pingedLanes &&
        null !== pingedLanes &&
        cancelCallback$1(pingedLanes),
      (root.callbackNode = null),
      (root.callbackPriority = 0)
    );
  if (
    0 === (suspendedLanes & 3) ||
    checkIfRootIsPrerendering(root, suspendedLanes)
  ) {
    currentTime = suspendedLanes & -suspendedLanes;
    if (currentTime === root.callbackPriority) return currentTime;
    null !== pingedLanes && cancelCallback$1(pingedLanes);
    switch (lanesToEventPriority(suspendedLanes)) {
      case 2:
      case 8:
        suspendedLanes = UserBlockingPriority;
        break;
      case 32:
        suspendedLanes = NormalPriority$1;
        break;
      case 268435456:
        suspendedLanes = IdlePriority;
        break;
      default:
        suspendedLanes = NormalPriority$1;
    }
    pingedLanes = performWorkOnRootViaSchedulerTask.bind(null, root);
    suspendedLanes = scheduleCallback$3(suspendedLanes, pingedLanes);
    root.callbackPriority = currentTime;
    root.callbackNode = suspendedLanes;
    return currentTime;
  }
  null !== pingedLanes && null !== pingedLanes && cancelCallback$1(pingedLanes);
  root.callbackPriority = 2;
  root.callbackNode = null;
  return 2;
}
function performWorkOnRootViaSchedulerTask(root, didTimeout) {
  var originalCallbackNode = root.callbackNode;
  if (flushPassiveEffects() && root.callbackNode !== originalCallbackNode)
    return null;
  var workInProgressRootRenderLanes$jscomp$0 = workInProgressRootRenderLanes;
  workInProgressRootRenderLanes$jscomp$0 = getNextLanes(
    root,
    root === workInProgressRoot ? workInProgressRootRenderLanes$jscomp$0 : 0
  );
  if (0 === workInProgressRootRenderLanes$jscomp$0) return null;
  performWorkOnRoot(root, workInProgressRootRenderLanes$jscomp$0, didTimeout);
  scheduleTaskForRootDuringMicrotask(root, now());
  return null != root.callbackNode && root.callbackNode === originalCallbackNode
    ? performWorkOnRootViaSchedulerTask.bind(null, root)
    : null;
}
function performSyncWorkOnRoot(root, lanes) {
  if (flushPassiveEffects()) return null;
  performWorkOnRoot(root, lanes, !0);
}
function scheduleImmediateTask(cb) {
  scheduleMicrotask(function () {
    0 !== (executionContext & 6)
      ? scheduleCallback$3(ImmediatePriority, cb)
      : cb();
  });
}
function requestTransitionLane() {
  0 === currentEventTransitionLane &&
    (currentEventTransitionLane = claimNextTransitionLane());
  return currentEventTransitionLane;
}
function coerceFormActionProp(actionProp) {
  return null == actionProp ||
    "symbol" === typeof actionProp ||
    "boolean" === typeof actionProp
    ? null
    : "function" === typeof actionProp
      ? actionProp
      : sanitizeURL("" + actionProp);
}
function createFormDataWithSubmitter(form, submitter) {
  var temp = submitter.ownerDocument.createElement("input");
  temp.name = submitter.name;
  temp.value = submitter.value;
  form.id && temp.setAttribute("form", form.id);
  submitter.parentNode.insertBefore(temp, submitter);
  form = new FormData(form);
  temp.parentNode.removeChild(temp);
  return form;
}
function extractEvents$1(
  dispatchQueue,
  domEventName,
  maybeTargetInst,
  nativeEvent,
  nativeEventTarget
) {
  if (
    "submit" === domEventName &&
    maybeTargetInst &&
    maybeTargetInst.stateNode === nativeEventTarget
  ) {
    var action = coerceFormActionProp(
        (nativeEventTarget[internalPropsKey] || null).action
      ),
      submitter = nativeEvent.submitter;
    submitter &&
      ((domEventName = (domEventName = submitter[internalPropsKey] || null)
        ? coerceFormActionProp(domEventName.formAction)
        : submitter.getAttribute("formAction")),
      null !== domEventName && ((action = domEventName), (submitter = null)));
    var event = new SyntheticEvent(
      "action",
      "action",
      null,
      nativeEvent,
      nativeEventTarget
    );
    dispatchQueue.push({
      event: event,
      listeners: [
        {
          instance: null,
          listener: function () {
            if (nativeEvent.defaultPrevented) {
              if (0 !== currentEventTransitionLane) {
                var formData = submitter
                  ? createFormDataWithSubmitter(nativeEventTarget, submitter)
                  : new FormData(nativeEventTarget);
                startHostTransition(
                  maybeTargetInst,
                  {
                    pending: !0,
                    data: formData,
                    method: nativeEventTarget.method,
                    action: action
                  },
                  null,
                  formData
                );
              }
            } else
              "function" === typeof action &&
                (event.preventDefault(),
                (formData = submitter
                  ? createFormDataWithSubmitter(nativeEventTarget, submitter)
                  : new FormData(nativeEventTarget)),
                startHostTransition(
                  maybeTargetInst,
                  {
                    pending: !0,
                    data: formData,
                    method: nativeEventTarget.method,
                    action: action
                  },
                  action,
                  formData
                ));
          },
          currentTarget: nativeEventTarget
        }
      ]
    });
  }
}
for (
  var i$jscomp$inline_1439 = 0;
  i$jscomp$inline_1439 < simpleEventPluginEvents.length;
  i$jscomp$inline_1439++
) {
  var eventName$jscomp$inline_1440 =
      simpleEventPluginEvents[i$jscomp$inline_1439],
    domEventName$jscomp$inline_1441 =
      eventName$jscomp$inline_1440.toLowerCase(),
    capitalizedEvent$jscomp$inline_1442 =
      eventName$jscomp$inline_1440[0].toUpperCase() +
      eventName$jscomp$inline_1440.slice(1);
  registerSimpleEvent(
    domEventName$jscomp$inline_1441,
    "on" + capitalizedEvent$jscomp$inline_1442
  );
}
registerSimpleEvent(ANIMATION_END, "onAnimationEnd");
registerSimpleEvent(ANIMATION_ITERATION, "onAnimationIteration");
registerSimpleEvent(ANIMATION_START, "onAnimationStart");
registerSimpleEvent("dblclick", "onDoubleClick");
registerSimpleEvent("focusin", "onFocus");
registerSimpleEvent("focusout", "onBlur");
registerSimpleEvent(TRANSITION_RUN, "onTransitionRun");
registerSimpleEvent(TRANSITION_START, "onTransitionStart");
registerSimpleEvent(TRANSITION_CANCEL, "onTransitionCancel");
registerSimpleEvent(TRANSITION_END, "onTransitionEnd");
registerDirectEvent("onMouseEnter", ["mouseout", "mouseover"]);
registerDirectEvent("onMouseLeave", ["mouseout", "mouseover"]);
registerDirectEvent("onPointerEnter", ["pointerout", "pointerover"]);
registerDirectEvent("onPointerLeave", ["pointerout", "pointerover"]);
registerTwoPhaseEvent(
  "onChange",
  "change click focusin focusout input keydown keyup selectionchange".split(" ")
);
registerTwoPhaseEvent(
  "onSelect",
  "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(
    " "
  )
);
registerTwoPhaseEvent("onBeforeInput", [
  "compositionend",
  "keypress",
  "textInput",
  "paste"
]);
registerTwoPhaseEvent(
  "onCompositionEnd",
  "compositionend focusout keydown keypress keyup mousedown".split(" ")
);
registerTwoPhaseEvent(
  "onCompositionStart",
  "compositionstart focusout keydown keypress keyup mousedown".split(" ")
);
registerTwoPhaseEvent(
  "onCompositionUpdate",
  "compositionupdate focusout keydown keypress keyup mousedown".split(" ")
);
var mediaEventTypes =
    "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(
      " "
    ),
  nonDelegatedEvents = new Set(
    "beforetoggle cancel close invalid load scroll scrollend toggle"
      .split(" ")
      .concat(mediaEventTypes)
  );
function processDispatchQueue(dispatchQueue, eventSystemFlags) {
  eventSystemFlags = 0 !== (eventSystemFlags & 4);
  for (var i = 0; i < dispatchQueue.length; i++) {
    var _dispatchQueue$i = dispatchQueue[i],
      event = _dispatchQueue$i.event;
    _dispatchQueue$i = _dispatchQueue$i.listeners;
    a: {
      var previousInstance = void 0;
      if (eventSystemFlags)
        for (
          var i$jscomp$0 = _dispatchQueue$i.length - 1;
          0 <= i$jscomp$0;
          i$jscomp$0--
        ) {
          var _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0],
            instance = _dispatchListeners$i.instance,
            currentTarget = _dispatchListeners$i.currentTarget;
          _dispatchListeners$i = _dispatchListeners$i.listener;
          if (instance !== previousInstance && event.isPropagationStopped())
            break a;
          previousInstance = _dispatchListeners$i;
          event.currentTarget = currentTarget;
          try {
            previousInstance(event);
          } catch (error) {
            reportGlobalError(error);
          }
          event.currentTarget = null;
          previousInstance = instance;
        }
      else
        for (
          i$jscomp$0 = 0;
          i$jscomp$0 < _dispatchQueue$i.length;
          i$jscomp$0++
        ) {
          _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0];
          instance = _dispatchListeners$i.instance;
          currentTarget = _dispatchListeners$i.currentTarget;
          _dispatchListeners$i = _dispatchListeners$i.listener;
          if (instance !== previousInstance && event.isPropagationStopped())
            break a;
          previousInstance = _dispatchListeners$i;
          event.currentTarget = currentTarget;
          try {
            previousInstance(event);
          } catch (error) {
            reportGlobalError(error);
          }
          event.currentTarget = null;
          previousInstance = instance;
        }
    }
  }
}
function listenToNonDelegatedEvent(domEventName, targetElement) {
  var JSCompiler_inline_result = targetElement[internalEventHandlersKey];
  void 0 === JSCompiler_inline_result &&
    (JSCompiler_inline_result = targetElement[internalEventHandlersKey] =
      new Set());
  var listenerSetKey = domEventName + "__bubble";
  JSCompiler_inline_result.has(listenerSetKey) ||
    (addTrappedEventListener(targetElement, domEventName, 2, !1),
    JSCompiler_inline_result.add(listenerSetKey));
}
function listenToNativeEvent(domEventName, isCapturePhaseListener, target) {
  var eventSystemFlags = 0;
  isCapturePhaseListener && (eventSystemFlags |= 4);
  addTrappedEventListener(
    target,
    domEventName,
    eventSystemFlags,
    isCapturePhaseListener
  );
}
var listeningMarker = "_reactListening" + Math.random().toString(36).slice(2);
function listenToAllSupportedEvents(rootContainerElement) {
  if (!rootContainerElement[listeningMarker]) {
    rootContainerElement[listeningMarker] = !0;
    allNativeEvents.forEach(function (domEventName) {
      "selectionchange" !== domEventName &&
        (nonDelegatedEvents.has(domEventName) ||
          listenToNativeEvent(domEventName, !1, rootContainerElement),
        listenToNativeEvent(domEventName, !0, rootContainerElement));
    });
    var ownerDocument =
      9 === rootContainerElement.nodeType
        ? rootContainerElement
        : rootContainerElement.ownerDocument;
    null === ownerDocument ||
      ownerDocument[listeningMarker] ||
      ((ownerDocument[listeningMarker] = !0),
      listenToNativeEvent("selectionchange", !1, ownerDocument));
  }
}
function addTrappedEventListener(
  targetContainer,
  domEventName,
  eventSystemFlags,
  isCapturePhaseListener
) {
  switch (getEventPriority(domEventName)) {
    case 2:
      var listenerWrapper = dispatchDiscreteEvent;
      break;
    case 8:
      listenerWrapper = dispatchContinuousEvent;
      break;
    default:
      listenerWrapper = dispatchEvent;
  }
  eventSystemFlags = listenerWrapper.bind(
    null,
    domEventName,
    eventSystemFlags,
    targetContainer
  );
  listenerWrapper = void 0;
  !passiveBrowserEventsSupported ||
    ("touchstart" !== domEventName &&
      "touchmove" !== domEventName &&
      "wheel" !== domEventName) ||
    (listenerWrapper = !0);
  isCapturePhaseListener
    ? void 0 !== listenerWrapper
      ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
          capture: !0,
          passive: listenerWrapper
        })
      : targetContainer.addEventListener(domEventName, eventSystemFlags, !0)
    : void 0 !== listenerWrapper
      ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
          passive: listenerWrapper
        })
      : targetContainer.addEventListener(domEventName, eventSystemFlags, !1);
}
function dispatchEventForPluginEventSystem(
  domEventName,
  eventSystemFlags,
  nativeEvent,
  targetInst$jscomp$0,
  targetContainer
) {
  var ancestorInst = targetInst$jscomp$0;
  if (
    0 === (eventSystemFlags & 1) &&
    0 === (eventSystemFlags & 2) &&
    null !== targetInst$jscomp$0
  )
    a: for (;;) {
      if (null === targetInst$jscomp$0) return;
      var nodeTag = targetInst$jscomp$0.tag;
      if (3 === nodeTag || 4 === nodeTag) {
        var container = targetInst$jscomp$0.stateNode.containerInfo;
        if (
          container === targetContainer ||
          (8 === container.nodeType && container.parentNode === targetContainer)
        )
          break;
        if (4 === nodeTag)
          for (nodeTag = targetInst$jscomp$0.return; null !== nodeTag; ) {
            var grandTag = nodeTag.tag;
            if (3 === grandTag || 4 === grandTag)
              if (
                ((grandTag = nodeTag.stateNode.containerInfo),
                grandTag === targetContainer ||
                  (8 === grandTag.nodeType &&
                    grandTag.parentNode === targetContainer))
              )
                return;
            nodeTag = nodeTag.return;
          }
        for (; null !== container; ) {
          nodeTag = getClosestInstanceFromNode(container);
          if (null === nodeTag) return;
          grandTag = nodeTag.tag;
          if (
            5 === grandTag ||
            6 === grandTag ||
            26 === grandTag ||
            27 === grandTag
          ) {
            targetInst$jscomp$0 = ancestorInst = nodeTag;
            continue a;
          }
          container = container.parentNode;
        }
      }
      targetInst$jscomp$0 = targetInst$jscomp$0.return;
    }
  batchedUpdates$1(function () {
    var targetInst = ancestorInst,
      nativeEventTarget = getEventTarget(nativeEvent),
      dispatchQueue = [];
    a: {
      var reactName = topLevelEventsToReactNames.get(domEventName);
      if (void 0 !== reactName) {
        var SyntheticEventCtor = SyntheticEvent,
          reactEventType = domEventName;
        switch (domEventName) {
          case "keypress":
            if (0 === getEventCharCode(nativeEvent)) break a;
          case "keydown":
          case "keyup":
            SyntheticEventCtor = SyntheticKeyboardEvent;
            break;
          case "focusin":
            reactEventType = "focus";
            SyntheticEventCtor = SyntheticFocusEvent;
            break;
          case "focusout":
            reactEventType = "blur";
            SyntheticEventCtor = SyntheticFocusEvent;
            break;
          case "beforeblur":
          case "afterblur":
            SyntheticEventCtor = SyntheticFocusEvent;
            break;
          case "click":
            if (2 === nativeEvent.button) break a;
          case "auxclick":
          case "dblclick":
          case "mousedown":
          case "mousemove":
          case "mouseup":
          case "mouseout":
          case "mouseover":
          case "contextmenu":
            SyntheticEventCtor = SyntheticMouseEvent;
            break;
          case "drag":
          case "dragend":
          case "dragenter":
          case "dragexit":
          case "dragleave":
          case "dragover":
          case "dragstart":
          case "drop":
            SyntheticEventCtor = SyntheticDragEvent;
            break;
          case "touchcancel":
          case "touchend":
          case "touchmove":
          case "touchstart":
            SyntheticEventCtor = SyntheticTouchEvent;
            break;
          case ANIMATION_END:
          case ANIMATION_ITERATION:
          case ANIMATION_START:
            SyntheticEventCtor = SyntheticAnimationEvent;
            break;
          case TRANSITION_END:
            SyntheticEventCtor = SyntheticTransitionEvent;
            break;
          case "scroll":
          case "scrollend":
            SyntheticEventCtor = SyntheticUIEvent;
            break;
          case "wheel":
            SyntheticEventCtor = SyntheticWheelEvent;
            break;
          case "copy":
          case "cut":
          case "paste":
            SyntheticEventCtor = SyntheticClipboardEvent;
            break;
          case "gotpointercapture":
          case "lostpointercapture":
          case "pointercancel":
          case "pointerdown":
          case "pointermove":
          case "pointerout":
          case "pointerover":
          case "pointerup":
            SyntheticEventCtor = SyntheticPointerEvent;
            break;
          case "toggle":
          case "beforetoggle":
            SyntheticEventCtor = SyntheticToggleEvent;
        }
        var inCapturePhase = 0 !== (eventSystemFlags & 4),
          accumulateTargetOnly =
            !inCapturePhase &&
            ("scroll" === domEventName || "scrollend" === domEventName),
          reactEventName = inCapturePhase
            ? null !== reactName
              ? reactName + "Capture"
              : null
            : reactName;
        inCapturePhase = [];
        for (
          var instance = targetInst, lastHostComponent;
          null !== instance;

        ) {
          var _instance = instance;
          lastHostComponent = _instance.stateNode;
          _instance = _instance.tag;
          (5 !== _instance && 26 !== _instance && 27 !== _instance) ||
            null === lastHostComponent ||
            null === reactEventName ||
            ((_instance = getListener(instance, reactEventName)),
            null != _instance &&
              inCapturePhase.push(
                createDispatchListener(instance, _instance, lastHostComponent)
              ));
          if (accumulateTargetOnly) break;
          instance = instance.return;
        }
        0 < inCapturePhase.length &&
          ((reactName = new SyntheticEventCtor(
            reactName,
            reactEventType,
            null,
            nativeEvent,
            nativeEventTarget
          )),
          dispatchQueue.push({ event: reactName, listeners: inCapturePhase }));
      }
    }
    if (0 === (eventSystemFlags & 7)) {
      a: {
        reactName =
          "mouseover" === domEventName || "pointerover" === domEventName;
        SyntheticEventCtor =
          "mouseout" === domEventName || "pointerout" === domEventName;
        if (
          reactName &&
          nativeEvent !== currentReplayingEvent &&
          (reactEventType =
            nativeEvent.relatedTarget || nativeEvent.fromElement) &&
          (getClosestInstanceFromNode(reactEventType) ||
            reactEventType[internalContainerInstanceKey])
        )
          break a;
        if (SyntheticEventCtor || reactName) {
          reactName =
            nativeEventTarget.window === nativeEventTarget
              ? nativeEventTarget
              : (reactName = nativeEventTarget.ownerDocument)
                ? reactName.defaultView || reactName.parentWindow
                : window;
          if (SyntheticEventCtor) {
            if (
              ((reactEventType =
                nativeEvent.relatedTarget || nativeEvent.toElement),
              (SyntheticEventCtor = targetInst),
              (reactEventType = reactEventType
                ? getClosestInstanceFromNode(reactEventType)
                : null),
              null !== reactEventType &&
                ((accumulateTargetOnly =
                  getNearestMountedFiber(reactEventType)),
                (inCapturePhase = reactEventType.tag),
                reactEventType !== accumulateTargetOnly ||
                  (5 !== inCapturePhase &&
                    27 !== inCapturePhase &&
                    6 !== inCapturePhase)))
            )
              reactEventType = null;
          } else (SyntheticEventCtor = null), (reactEventType = targetInst);
          if (SyntheticEventCtor !== reactEventType) {
            inCapturePhase = SyntheticMouseEvent;
            _instance = "onMouseLeave";
            reactEventName = "onMouseEnter";
            instance = "mouse";
            if ("pointerout" === domEventName || "pointerover" === domEventName)
              (inCapturePhase = SyntheticPointerEvent),
                (_instance = "onPointerLeave"),
                (reactEventName = "onPointerEnter"),
                (instance = "pointer");
            accumulateTargetOnly =
              null == SyntheticEventCtor
                ? reactName
                : getNodeFromInstance(SyntheticEventCtor);
            lastHostComponent =
              null == reactEventType
                ? reactName
                : getNodeFromInstance(reactEventType);
            reactName = new inCapturePhase(
              _instance,
              instance + "leave",
              SyntheticEventCtor,
              nativeEvent,
              nativeEventTarget
            );
            reactName.target = accumulateTargetOnly;
            reactName.relatedTarget = lastHostComponent;
            _instance = null;
            getClosestInstanceFromNode(nativeEventTarget) === targetInst &&
              ((inCapturePhase = new inCapturePhase(
                reactEventName,
                instance + "enter",
                reactEventType,
                nativeEvent,
                nativeEventTarget
              )),
              (inCapturePhase.target = lastHostComponent),
              (inCapturePhase.relatedTarget = accumulateTargetOnly),
              (_instance = inCapturePhase));
            accumulateTargetOnly = _instance;
            if (SyntheticEventCtor && reactEventType)
              b: {
                inCapturePhase = SyntheticEventCtor;
                reactEventName = reactEventType;
                instance = 0;
                for (
                  lastHostComponent = inCapturePhase;
                  lastHostComponent;
                  lastHostComponent = getParent(lastHostComponent)
                )
                  instance++;
                lastHostComponent = 0;
                for (
                  _instance = reactEventName;
                  _instance;
                  _instance = getParent(_instance)
                )
                  lastHostComponent++;
                for (; 0 < instance - lastHostComponent; )
                  (inCapturePhase = getParent(inCapturePhase)), instance--;
                for (; 0 < lastHostComponent - instance; )
                  (reactEventName = getParent(reactEventName)),
                    lastHostComponent--;
                for (; instance--; ) {
                  if (
                    inCapturePhase === reactEventName ||
                    (null !== reactEventName &&
                      inCapturePhase === reactEventName.alternate)
                  )
                    break b;
                  inCapturePhase = getParent(inCapturePhase);
                  reactEventName = getParent(reactEventName);
                }
                inCapturePhase = null;
              }
            else inCapturePhase = null;
            null !== SyntheticEventCtor &&
              accumulateEnterLeaveListenersForEvent(
                dispatchQueue,
                reactName,
                SyntheticEventCtor,
                inCapturePhase,
                !1
              );
            null !== reactEventType &&
              null !== accumulateTargetOnly &&
              accumulateEnterLeaveListenersForEvent(
                dispatchQueue,
                accumulateTargetOnly,
                reactEventType,
                inCapturePhase,
                !0
              );
          }
        }
      }
      a: {
        reactName = targetInst ? getNodeFromInstance(targetInst) : window;
        SyntheticEventCtor =
          reactName.nodeName && reactName.nodeName.toLowerCase();
        if (
          "select" === SyntheticEventCtor ||
          ("input" === SyntheticEventCtor && "file" === reactName.type)
        )
          var getTargetInstFunc = getTargetInstForChangeEvent;
        else if (isTextInputElement(reactName))
          if (isInputEventSupported)
            getTargetInstFunc = getTargetInstForInputOrChangeEvent;
          else {
            getTargetInstFunc = getTargetInstForInputEventPolyfill;
            var handleEventFunc = handleEventsForInputEventPolyfill;
          }
        else
          (SyntheticEventCtor = reactName.nodeName),
            !SyntheticEventCtor ||
            "input" !== SyntheticEventCtor.toLowerCase() ||
            ("checkbox" !== reactName.type && "radio" !== reactName.type)
              ? targetInst &&
                isCustomElement(targetInst.elementType) &&
                (getTargetInstFunc = getTargetInstForChangeEvent)
              : (getTargetInstFunc = getTargetInstForClickEvent);
        if (
          getTargetInstFunc &&
          (getTargetInstFunc = getTargetInstFunc(domEventName, targetInst))
        ) {
          createAndAccumulateChangeEvent(
            dispatchQueue,
            getTargetInstFunc,
            nativeEvent,
            nativeEventTarget
          );
          break a;
        }
        handleEventFunc && handleEventFunc(domEventName, reactName, targetInst);
        "focusout" === domEventName &&
          targetInst &&
          "number" === reactName.type &&
          null != targetInst.memoizedProps.value &&
          setDefaultValue(reactName, "number", reactName.value);
      }
      handleEventFunc = targetInst ? getNodeFromInstance(targetInst) : window;
      switch (domEventName) {
        case "focusin":
          if (
            isTextInputElement(handleEventFunc) ||
            "true" === handleEventFunc.contentEditable
          )
            (activeElement = handleEventFunc),
              (activeElementInst = targetInst),
              (lastSelection = null);
          break;
        case "focusout":
          lastSelection = activeElementInst = activeElement = null;
          break;
        case "mousedown":
          mouseDown = !0;
          break;
        case "contextmenu":
        case "mouseup":
        case "dragend":
          mouseDown = !1;
          constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
          break;
        case "selectionchange":
          if (skipSelectionChangeEvent) break;
        case "keydown":
        case "keyup":
          constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
      }
      var fallbackData;
      if (canUseCompositionEvent)
        b: {
          switch (domEventName) {
            case "compositionstart":
              var eventType = "onCompositionStart";
              break b;
            case "compositionend":
              eventType = "onCompositionEnd";
              break b;
            case "compositionupdate":
              eventType = "onCompositionUpdate";
              break b;
          }
          eventType = void 0;
        }
      else
        isComposing
          ? isFallbackCompositionEnd(domEventName, nativeEvent) &&
            (eventType = "onCompositionEnd")
          : "keydown" === domEventName &&
            229 === nativeEvent.keyCode &&
            (eventType = "onCompositionStart");
      eventType &&
        (useFallbackCompositionData &&
          "ko" !== nativeEvent.locale &&
          (isComposing || "onCompositionStart" !== eventType
            ? "onCompositionEnd" === eventType &&
              isComposing &&
              (fallbackData = getData())
            : ((root = nativeEventTarget),
              (startText = "value" in root ? root.value : root.textContent),
              (isComposing = !0))),
        (handleEventFunc = accumulateTwoPhaseListeners(targetInst, eventType)),
        0 < handleEventFunc.length &&
          ((eventType = new SyntheticCompositionEvent(
            eventType,
            domEventName,
            null,
            nativeEvent,
            nativeEventTarget
          )),
          dispatchQueue.push({ event: eventType, listeners: handleEventFunc }),
          fallbackData
            ? (eventType.data = fallbackData)
            : ((fallbackData = getDataFromCustomEvent(nativeEvent)),
              null !== fallbackData && (eventType.data = fallbackData))));
      if (
        (fallbackData = canUseTextInputEvent
          ? getNativeBeforeInputChars(domEventName, nativeEvent)
          : getFallbackBeforeInputChars(domEventName, nativeEvent))
      )
        (eventType = accumulateTwoPhaseListeners(targetInst, "onBeforeInput")),
          0 < eventType.length &&
            ((handleEventFunc = new SyntheticCompositionEvent(
              "onBeforeInput",
              "beforeinput",
              null,
              nativeEvent,
              nativeEventTarget
            )),
            dispatchQueue.push({
              event: handleEventFunc,
              listeners: eventType
            }),
            (handleEventFunc.data = fallbackData));
      extractEvents$1(
        dispatchQueue,
        domEventName,
        targetInst,
        nativeEvent,
        nativeEventTarget
      );
    }
    processDispatchQueue(dispatchQueue, eventSystemFlags);
  });
}
function createDispatchListener(instance, listener, currentTarget) {
  return {
    instance: instance,
    listener: listener,
    currentTarget: currentTarget
  };
}
function accumulateTwoPhaseListeners(targetFiber, reactName) {
  for (
    var captureName = reactName + "Capture", listeners = [];
    null !== targetFiber;

  ) {
    var _instance2 = targetFiber,
      stateNode = _instance2.stateNode;
    _instance2 = _instance2.tag;
    (5 !== _instance2 && 26 !== _instance2 && 27 !== _instance2) ||
      null === stateNode ||
      ((_instance2 = getListener(targetFiber, captureName)),
      null != _instance2 &&
        listeners.unshift(
          createDispatchListener(targetFiber, _instance2, stateNode)
        ),
      (_instance2 = getListener(targetFiber, reactName)),
      null != _instance2 &&
        listeners.push(
          createDispatchListener(targetFiber, _instance2, stateNode)
        ));
    targetFiber = targetFiber.return;
  }
  return listeners;
}
function getParent(inst) {
  if (null === inst) return null;
  do inst = inst.return;
  while (inst && 5 !== inst.tag && 27 !== inst.tag);
  return inst ? inst : null;
}
function accumulateEnterLeaveListenersForEvent(
  dispatchQueue,
  event,
  target,
  common,
  inCapturePhase
) {
  for (
    var registrationName = event._reactName, listeners = [];
    null !== target && target !== common;

  ) {
    var _instance3 = target,
      alternate = _instance3.alternate,
      stateNode = _instance3.stateNode;
    _instance3 = _instance3.tag;
    if (null !== alternate && alternate === common) break;
    (5 !== _instance3 && 26 !== _instance3 && 27 !== _instance3) ||
      null === stateNode ||
      ((alternate = stateNode),
      inCapturePhase
        ? ((stateNode = getListener(target, registrationName)),
          null != stateNode &&
            listeners.unshift(
              createDispatchListener(target, stateNode, alternate)
            ))
        : inCapturePhase ||
          ((stateNode = getListener(target, registrationName)),
          null != stateNode &&
            listeners.push(
              createDispatchListener(target, stateNode, alternate)
            )));
    target = target.return;
  }
  0 !== listeners.length &&
    dispatchQueue.push({ event: event, listeners: listeners });
}
var NORMALIZE_NEWLINES_REGEX = /\r\n?/g,
  NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
function normalizeMarkupForTextOrAttribute(markup) {
  return ("string" === typeof markup ? markup : "" + markup)
    .replace(NORMALIZE_NEWLINES_REGEX, "\n")
    .replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, "");
}
function checkForUnmatchedText(serverText, clientText) {
  clientText = normalizeMarkupForTextOrAttribute(clientText);
  return normalizeMarkupForTextOrAttribute(serverText) === clientText ? !0 : !1;
}
function noop$1() {}
function setProp(domElement, tag, key, value, props, prevValue) {
  switch (key) {
    case "children":
      "string" === typeof value
        ? "body" === tag ||
          ("textarea" === tag && "" === value) ||
          setTextContent(domElement, value)
        : ("number" === typeof value || "bigint" === typeof value) &&
          "body" !== tag &&
          setTextContent(domElement, "" + value);
      break;
    case "className":
      setValueForKnownAttribute(domElement, "class", value);
      break;
    case "tabIndex":
      setValueForKnownAttribute(domElement, "tabindex", value);
      break;
    case "dir":
    case "role":
    case "viewBox":
    case "width":
    case "height":
      setValueForKnownAttribute(domElement, key, value);
      break;
    case "style":
      setValueForStyles(domElement, value, prevValue);
      break;
    case "data":
      if ("object" !== tag) {
        setValueForKnownAttribute(domElement, "data", value);
        break;
      }
    case "src":
    case "href":
      if ("" === value && ("a" !== tag || "href" !== key)) {
        domElement.removeAttribute(key);
        break;
      }
      if (
        null == value ||
        "function" === typeof value ||
        "symbol" === typeof value ||
        "boolean" === typeof value
      ) {
        domElement.removeAttribute(key);
        break;
      }
      value = sanitizeURL("" + value);
      domElement.setAttribute(key, value);
      break;
    case "action":
    case "formAction":
      if ("function" === typeof value) {
        domElement.setAttribute(
          key,
          "javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')"
        );
        break;
      } else
        "function" === typeof prevValue &&
          ("formAction" === key
            ? ("input" !== tag &&
                setProp(domElement, tag, "name", props.name, props, null),
              setProp(
                domElement,
                tag,
                "formEncType",
                props.formEncType,
                props,
                null
              ),
              setProp(
                domElement,
                tag,
                "formMethod",
                props.formMethod,
                props,
                null
              ),
              setProp(
                domElement,
                tag,
                "formTarget",
                props.formTarget,
                props,
                null
              ))
            : (setProp(domElement, tag, "encType", props.encType, props, null),
              setProp(domElement, tag, "method", props.method, props, null),
              setProp(domElement, tag, "target", props.target, props, null)));
      if (
        null == value ||
        "symbol" === typeof value ||
        "boolean" === typeof value
      ) {
        domElement.removeAttribute(key);
        break;
      }
      value = sanitizeURL("" + value);
      domElement.setAttribute(key, value);
      break;
    case "onClick":
      null != value && (domElement.onclick = noop$1);
      break;
    case "onScroll":
      null != value && listenToNonDelegatedEvent("scroll", domElement);
      break;
    case "onScrollEnd":
      null != value && listenToNonDelegatedEvent("scrollend", domElement);
      break;
    case "dangerouslySetInnerHTML":
      if (null != value) {
        if ("object" !== typeof value || !("__html" in value))
          throw Error(formatProdErrorMessage(61));
        key = value.__html;
        if (null != key) {
          if (null != props.children) throw Error(formatProdErrorMessage(60));
          domElement.innerHTML = key;
        }
      }
      break;
    case "multiple":
      domElement.multiple =
        value && "function" !== typeof value && "symbol" !== typeof value;
      break;
    case "muted":
      domElement.muted =
        value && "function" !== typeof value && "symbol" !== typeof value;
      break;
    case "suppressContentEditableWarning":
    case "suppressHydrationWarning":
    case "defaultValue":
    case "defaultChecked":
    case "innerHTML":
    case "ref":
      break;
    case "autoFocus":
      break;
    case "xlinkHref":
      if (
        null == value ||
        "function" === typeof value ||
        "boolean" === typeof value ||
        "symbol" === typeof value
      ) {
        domElement.removeAttribute("xlink:href");
        break;
      }
      key = sanitizeURL("" + value);
      domElement.setAttributeNS(
        "http://www.w3.org/1999/xlink",
        "xlink:href",
        key
      );
      break;
    case "contentEditable":
    case "spellCheck":
    case "draggable":
    case "value":
    case "autoReverse":
    case "externalResourcesRequired":
    case "focusable":
    case "preserveAlpha":
      null != value && "function" !== typeof value && "symbol" !== typeof value
        ? domElement.setAttribute(key, "" + value)
        : domElement.removeAttribute(key);
      break;
    case "inert":
    case "allowFullScreen":
    case "async":
    case "autoPlay":
    case "controls":
    case "default":
    case "defer":
    case "disabled":
    case "disablePictureInPicture":
    case "disableRemotePlayback":
    case "formNoValidate":
    case "hidden":
    case "loop":
    case "noModule":
    case "noValidate":
    case "open":
    case "playsInline":
    case "readOnly":
    case "required":
    case "reversed":
    case "scoped":
    case "seamless":
    case "itemScope":
      value && "function" !== typeof value && "symbol" !== typeof value
        ? domElement.setAttribute(key, "")
        : domElement.removeAttribute(key);
      break;
    case "capture":
    case "download":
      !0 === value
        ? domElement.setAttribute(key, "")
        : !1 !== value &&
            null != value &&
            "function" !== typeof value &&
            "symbol" !== typeof value
          ? domElement.setAttribute(key, value)
          : domElement.removeAttribute(key);
      break;
    case "cols":
    case "rows":
    case "size":
    case "span":
      null != value &&
      "function" !== typeof value &&
      "symbol" !== typeof value &&
      !isNaN(value) &&
      1 <= value
        ? domElement.setAttribute(key, value)
        : domElement.removeAttribute(key);
      break;
    case "rowSpan":
    case "start":
      null == value ||
      "function" === typeof value ||
      "symbol" === typeof value ||
      isNaN(value)
        ? domElement.removeAttribute(key)
        : domElement.setAttribute(key, value);
      break;
    case "popover":
      listenToNonDelegatedEvent("beforetoggle", domElement);
      listenToNonDelegatedEvent("toggle", domElement);
      setValueForAttribute(domElement, "popover", value);
      break;
    case "xlinkActuate":
      setValueForNamespacedAttribute(
        domElement,
        "http://www.w3.org/1999/xlink",
        "xlink:actuate",
        value
      );
      break;
    case "xlinkArcrole":
      setValueForNamespacedAttribute(
        domElement,
        "http://www.w3.org/1999/xlink",
        "xlink:arcrole",
        value
      );
      break;
    case "xlinkRole":
      setValueForNamespacedAttribute(
        domElement,
        "http://www.w3.org/1999/xlink",
        "xlink:role",
        value
      );
      break;
    case "xlinkShow":
      setValueForNamespacedAttribute(
        domElement,
        "http://www.w3.org/1999/xlink",
        "xlink:show",
        value
      );
      break;
    case "xlinkTitle":
      setValueForNamespacedAttribute(
        domElement,
        "http://www.w3.org/1999/xlink",
        "xlink:title",
        value
      );
      break;
    case "xlinkType":
      setValueForNamespacedAttribute(
        domElement,
        "http://www.w3.org/1999/xlink",
        "xlink:type",
        value
      );
      break;
    case "xmlBase":
      setValueForNamespacedAttribute(
        domElement,
        "http://www.w3.org/XML/1998/namespace",
        "xml:base",
        value
      );
      break;
    case "xmlLang":
      setValueForNamespacedAttribute(
        domElement,
        "http://www.w3.org/XML/1998/namespace",
        "xml:lang",
        value
      );
      break;
    case "xmlSpace":
      setValueForNamespacedAttribute(
        domElement,
        "http://www.w3.org/XML/1998/namespace",
        "xml:space",
        value
      );
      break;
    case "is":
      setValueForAttribute(domElement, "is", value);
      break;
    case "innerText":
    case "textContent":
      break;
    default:
      if (
        !(2 < key.length) ||
        ("o" !== key[0] && "O" !== key[0]) ||
        ("n" !== key[1] && "N" !== key[1])
      )
        (key = aliases.get(key) || key),
          setValueForAttribute(domElement, key, value);
  }
}
function setPropOnCustomElement(domElement, tag, key, value, props, prevValue) {
  switch (key) {
    case "style":
      setValueForStyles(domElement, value, prevValue);
      break;
    case "dangerouslySetInnerHTML":
      if (null != value) {
        if ("object" !== typeof value || !("__html" in value))
          throw Error(formatProdErrorMessage(61));
        key = value.__html;
        if (null != key) {
          if (null != props.children) throw Error(formatProdErrorMessage(60));
          domElement.innerHTML = key;
        }
      }
      break;
    case "children":
      "string" === typeof value
        ? setTextContent(domElement, value)
        : ("number" === typeof value || "bigint" === typeof value) &&
          setTextContent(domElement, "" + value);
      break;
    case "onScroll":
      null != value && listenToNonDelegatedEvent("scroll", domElement);
      break;
    case "onScrollEnd":
      null != value && listenToNonDelegatedEvent("scrollend", domElement);
      break;
    case "onClick":
      null != value && (domElement.onclick = noop$1);
      break;
    case "suppressContentEditableWarning":
    case "suppressHydrationWarning":
    case "innerHTML":
    case "ref":
      break;
    case "innerText":
    case "textContent":
      break;
    default:
      if (!registrationNameDependencies.hasOwnProperty(key))
        a: {
          if (
            "o" === key[0] &&
            "n" === key[1] &&
            ((props = key.endsWith("Capture")),
            (tag = key.slice(2, props ? key.length - 7 : void 0)),
            (prevValue = domElement[internalPropsKey] || null),
            (prevValue = null != prevValue ? prevValue[key] : null),
            "function" === typeof prevValue &&
              domElement.removeEventListener(tag, prevValue, props),
            "function" === typeof value)
          ) {
            "function" !== typeof prevValue &&
              null !== prevValue &&
              (key in domElement
                ? (domElement[key] = null)
                : domElement.hasAttribute(key) &&
                  domElement.removeAttribute(key));
            domElement.addEventListener(tag, value, props);
            break a;
          }
          key in domElement
            ? (domElement[key] = value)
            : !0 === value
              ? domElement.setAttribute(key, "")
              : setValueForAttribute(domElement, key, value);
        }
  }
}
function setInitialProperties(domElement, tag, props) {
  switch (tag) {
    case "div":
    case "span":
    case "svg":
    case "path":
    case "a":
    case "g":
    case "p":
    case "li":
      break;
    case "img":
      listenToNonDelegatedEvent("error", domElement);
      listenToNonDelegatedEvent("load", domElement);
      var hasSrc = !1,
        hasSrcSet = !1,
        propKey;
      for (propKey in props)
        if (props.hasOwnProperty(propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "src":
                hasSrc = !0;
                break;
              case "srcSet":
                hasSrcSet = !0;
                break;
              case "children":
              case "dangerouslySetInnerHTML":
                throw Error(formatProdErrorMessage(137, tag));
              default:
                setProp(domElement, tag, propKey, propValue, props, null);
            }
        }
      hasSrcSet &&
        setProp(domElement, tag, "srcSet", props.srcSet, props, null);
      hasSrc && setProp(domElement, tag, "src", props.src, props, null);
      return;
    case "input":
      listenToNonDelegatedEvent("invalid", domElement);
      var defaultValue = (propKey = propValue = hasSrcSet = null),
        checked = null,
        defaultChecked = null;
      for (hasSrc in props)
        if (props.hasOwnProperty(hasSrc)) {
          var propValue$186 = props[hasSrc];
          if (null != propValue$186)
            switch (hasSrc) {
              case "name":
                hasSrcSet = propValue$186;
                break;
              case "type":
                propValue = propValue$186;
                break;
              case "checked":
                checked = propValue$186;
                break;
              case "defaultChecked":
                defaultChecked = propValue$186;
                break;
              case "value":
                propKey = propValue$186;
                break;
              case "defaultValue":
                defaultValue = propValue$186;
                break;
              case "children":
              case "dangerouslySetInnerHTML":
                if (null != propValue$186)
                  throw Error(formatProdErrorMessage(137, tag));
                break;
              default:
                setProp(domElement, tag, hasSrc, propValue$186, props, null);
            }
        }
      initInput(
        domElement,
        propKey,
        defaultValue,
        checked,
        defaultChecked,
        propValue,
        hasSrcSet,
        !1
      );
      track(domElement);
      return;
    case "select":
      listenToNonDelegatedEvent("invalid", domElement);
      hasSrc = propValue = propKey = null;
      for (hasSrcSet in props)
        if (
          props.hasOwnProperty(hasSrcSet) &&
          ((defaultValue = props[hasSrcSet]), null != defaultValue)
        )
          switch (hasSrcSet) {
            case "value":
              propKey = defaultValue;
              break;
            case "defaultValue":
              propValue = defaultValue;
              break;
            case "multiple":
              hasSrc = defaultValue;
            default:
              setProp(domElement, tag, hasSrcSet, defaultValue, props, null);
          }
      tag = propKey;
      props = propValue;
      domElement.multiple = !!hasSrc;
      null != tag
        ? updateOptions(domElement, !!hasSrc, tag, !1)
        : null != props && updateOptions(domElement, !!hasSrc, props, !0);
      return;
    case "textarea":
      listenToNonDelegatedEvent("invalid", domElement);
      propKey = hasSrcSet = hasSrc = null;
      for (propValue in props)
        if (
          props.hasOwnProperty(propValue) &&
          ((defaultValue = props[propValue]), null != defaultValue)
        )
          switch (propValue) {
            case "value":
              hasSrc = defaultValue;
              break;
            case "defaultValue":
              hasSrcSet = defaultValue;
              break;
            case "children":
              propKey = defaultValue;
              break;
            case "dangerouslySetInnerHTML":
              if (null != defaultValue) throw Error(formatProdErrorMessage(91));
              break;
            default:
              setProp(domElement, tag, propValue, defaultValue, props, null);
          }
      initTextarea(domElement, hasSrc, hasSrcSet, propKey);
      track(domElement);
      return;
    case "option":
      for (checked in props)
        if (
          props.hasOwnProperty(checked) &&
          ((hasSrc = props[checked]), null != hasSrc)
        )
          switch (checked) {
            case "selected":
              domElement.selected =
                hasSrc &&
                "function" !== typeof hasSrc &&
                "symbol" !== typeof hasSrc;
              break;
            default:
              setProp(domElement, tag, checked, hasSrc, props, null);
          }
      return;
    case "dialog":
      listenToNonDelegatedEvent("cancel", domElement);
      listenToNonDelegatedEvent("close", domElement);
      break;
    case "iframe":
    case "object":
      listenToNonDelegatedEvent("load", domElement);
      break;
    case "video":
    case "audio":
      for (hasSrc = 0; hasSrc < mediaEventTypes.length; hasSrc++)
        listenToNonDelegatedEvent(mediaEventTypes[hasSrc], domElement);
      break;
    case "image":
      listenToNonDelegatedEvent("error", domElement);
      listenToNonDelegatedEvent("load", domElement);
      break;
    case "details":
      listenToNonDelegatedEvent("toggle", domElement);
      break;
    case "embed":
    case "source":
    case "link":
      listenToNonDelegatedEvent("error", domElement),
        listenToNonDelegatedEvent("load", domElement);
    case "area":
    case "base":
    case "br":
    case "col":
    case "hr":
    case "keygen":
    case "meta":
    case "param":
    case "track":
    case "wbr":
    case "menuitem":
      for (defaultChecked in props)
        if (
          props.hasOwnProperty(defaultChecked) &&
          ((hasSrc = props[defaultChecked]), null != hasSrc)
        )
          switch (defaultChecked) {
            case "children":
            case "dangerouslySetInnerHTML":
              throw Error(formatProdErrorMessage(137, tag));
            default:
              setProp(domElement, tag, defaultChecked, hasSrc, props, null);
          }
      return;
    default:
      if (isCustomElement(tag)) {
        for (propValue$186 in props)
          props.hasOwnProperty(propValue$186) &&
            ((hasSrc = props[propValue$186]),
            void 0 !== hasSrc &&
              setPropOnCustomElement(
                domElement,
                tag,
                propValue$186,
                hasSrc,
                props,
                void 0
              ));
        return;
      }
  }
  for (defaultValue in props)
    props.hasOwnProperty(defaultValue) &&
      ((hasSrc = props[defaultValue]),
      null != hasSrc &&
        setProp(domElement, tag, defaultValue, hasSrc, props, null));
}
function updateProperties(domElement, tag, lastProps, nextProps) {
  switch (tag) {
    case "div":
    case "span":
    case "svg":
    case "path":
    case "a":
    case "g":
    case "p":
    case "li":
      break;
    case "input":
      var name = null,
        type = null,
        value = null,
        defaultValue = null,
        lastDefaultValue = null,
        checked = null,
        defaultChecked = null;
      for (propKey in lastProps) {
        var lastProp = lastProps[propKey];
        if (lastProps.hasOwnProperty(propKey) && null != lastProp)
          switch (propKey) {
            case "checked":
              break;
            case "value":
              break;
            case "defaultValue":
              lastDefaultValue = lastProp;
            default:
              nextProps.hasOwnProperty(propKey) ||
                setProp(domElement, tag, propKey, null, nextProps, lastProp);
          }
      }
      for (var propKey$203 in nextProps) {
        var propKey = nextProps[propKey$203];
        lastProp = lastProps[propKey$203];
        if (
          nextProps.hasOwnProperty(propKey$203) &&
          (null != propKey || null != lastProp)
        )
          switch (propKey$203) {
            case "type":
              type = propKey;
              break;
            case "name":
              name = propKey;
              break;
            case "checked":
              checked = propKey;
              break;
            case "defaultChecked":
              defaultChecked = propKey;
              break;
            case "value":
              value = propKey;
              break;
            case "defaultValue":
              defaultValue = propKey;
              break;
            case "children":
            case "dangerouslySetInnerHTML":
              if (null != propKey)
                throw Error(formatProdErrorMessage(137, tag));
              break;
            default:
              propKey !== lastProp &&
                setProp(
                  domElement,
                  tag,
                  propKey$203,
                  propKey,
                  nextProps,
                  lastProp
                );
          }
      }
      updateInput(
        domElement,
        value,
        defaultValue,
        lastDefaultValue,
        checked,
        defaultChecked,
        type,
        name
      );
      return;
    case "select":
      propKey = value = defaultValue = propKey$203 = null;
      for (type in lastProps)
        if (
          ((lastDefaultValue = lastProps[type]),
          lastProps.hasOwnProperty(type) && null != lastDefaultValue)
        )
          switch (type) {
            case "value":
              break;
            case "multiple":
              propKey = lastDefaultValue;
            default:
              nextProps.hasOwnProperty(type) ||
                setProp(
                  domElement,
                  tag,
                  type,
                  null,
                  nextProps,
                  lastDefaultValue
                );
          }
      for (name in nextProps)
        if (
          ((type = nextProps[name]),
          (lastDefaultValue = lastProps[name]),
          nextProps.hasOwnProperty(name) &&
            (null != type || null != lastDefaultValue))
        )
          switch (name) {
            case "value":
              propKey$203 = type;
              break;
            case "defaultValue":
              defaultValue = type;
              break;
            case "multiple":
              value = type;
            default:
              type !== lastDefaultValue &&
                setProp(
                  domElement,
                  tag,
                  name,
                  type,
                  nextProps,
                  lastDefaultValue
                );
          }
      tag = defaultValue;
      lastProps = value;
      nextProps = propKey;
      null != propKey$203
        ? updateOptions(domElement, !!lastProps, propKey$203, !1)
        : !!nextProps !== !!lastProps &&
          (null != tag
            ? updateOptions(domElement, !!lastProps, tag, !0)
            : updateOptions(domElement, !!lastProps, lastProps ? [] : "", !1));
      return;
    case "textarea":
      propKey = propKey$203 = null;
      for (defaultValue in lastProps)
        if (
          ((name = lastProps[defaultValue]),
          lastProps.hasOwnProperty(defaultValue) &&
            null != name &&
            !nextProps.hasOwnProperty(defaultValue))
        )
          switch (defaultValue) {
            case "value":
              break;
            case "children":
              break;
            default:
              setProp(domElement, tag, defaultValue, null, nextProps, name);
          }
      for (value in nextProps)
        if (
          ((name = nextProps[value]),
          (type = lastProps[value]),
          nextProps.hasOwnProperty(value) && (null != name || null != type))
        )
          switch (value) {
            case "value":
              propKey$203 = name;
              break;
            case "defaultValue":
              propKey = name;
              break;
            case "children":
              break;
            case "dangerouslySetInnerHTML":
              if (null != name) throw Error(formatProdErrorMessage(91));
              break;
            default:
              name !== type &&
                setProp(domElement, tag, value, name, nextProps, type);
          }
      updateTextarea(domElement, propKey$203, propKey);
      return;
    case "option":
      for (var propKey$219 in lastProps)
        if (
          ((propKey$203 = lastProps[propKey$219]),
          lastProps.hasOwnProperty(propKey$219) &&
            null != propKey$203 &&
            !nextProps.hasOwnProperty(propKey$219))
        )
          switch (propKey$219) {
            case "selected":
              domElement.selected = !1;
              break;
            default:
              setProp(
                domElement,
                tag,
                propKey$219,
                null,
                nextProps,
                propKey$203
              );
          }
      for (lastDefaultValue in nextProps)
        if (
          ((propKey$203 = nextProps[lastDefaultValue]),
          (propKey = lastProps[lastDefaultValue]),
          nextProps.hasOwnProperty(lastDefaultValue) &&
            propKey$203 !== propKey &&
            (null != propKey$203 || null != propKey))
        )
          switch (lastDefaultValue) {
            case "selected":
              domElement.selected =
                propKey$203 &&
                "function" !== typeof propKey$203 &&
                "symbol" !== typeof propKey$203;
              break;
            default:
              setProp(
                domElement,
                tag,
                lastDefaultValue,
                propKey$203,
                nextProps,
                propKey
              );
          }
      return;
    case "img":
    case "link":
    case "area":
    case "base":
    case "br":
    case "col":
    case "embed":
    case "hr":
    case "keygen":
    case "meta":
    case "param":
    case "source":
    case "track":
    case "wbr":
    case "menuitem":
      for (var propKey$224 in lastProps)
        (propKey$203 = lastProps[propKey$224]),
          lastProps.hasOwnProperty(propKey$224) &&
            null != propKey$203 &&
            !nextProps.hasOwnProperty(propKey$224) &&
            setProp(domElement, tag, propKey$224, null, nextProps, propKey$203);
      for (checked in nextProps)
        if (
          ((propKey$203 = nextProps[checked]),
          (propKey = lastProps[checked]),
          nextProps.hasOwnProperty(checked) &&
            propKey$203 !== propKey &&
            (null != propKey$203 || null != propKey))
        )
          switch (checked) {
            case "children":
            case "dangerouslySetInnerHTML":
              if (null != propKey$203)
                throw Error(formatProdErrorMessage(137, tag));
              break;
            default:
              setProp(
                domElement,
                tag,
                checked,
                propKey$203,
                nextProps,
                propKey
              );
          }
      return;
    default:
      if (isCustomElement(tag)) {
        for (var propKey$229 in lastProps)
          (propKey$203 = lastProps[propKey$229]),
            lastProps.hasOwnProperty(propKey$229) &&
              void 0 !== propKey$203 &&
              !nextProps.hasOwnProperty(propKey$229) &&
              setPropOnCustomElement(
                domElement,
                tag,
                propKey$229,
                void 0,
                nextProps,
                propKey$203
              );
        for (defaultChecked in nextProps)
          (propKey$203 = nextProps[defaultChecked]),
            (propKey = lastProps[defaultChecked]),
            !nextProps.hasOwnProperty(defaultChecked) ||
              propKey$203 === propKey ||
              (void 0 === propKey$203 && void 0 === propKey) ||
              setPropOnCustomElement(
                domElement,
                tag,
                defaultChecked,
                propKey$203,
                nextProps,
                propKey
              );
        return;
      }
  }
  for (var propKey$234 in lastProps)
    (propKey$203 = lastProps[propKey$234]),
      lastProps.hasOwnProperty(propKey$234) &&
        null != propKey$203 &&
        !nextProps.hasOwnProperty(propKey$234) &&
        setProp(domElement, tag, propKey$234, null, nextProps, propKey$203);
  for (lastProp in nextProps)
    (propKey$203 = nextProps[lastProp]),
      (propKey = lastProps[lastProp]),
      !nextProps.hasOwnProperty(lastProp) ||
        propKey$203 === propKey ||
        (null == propKey$203 && null == propKey) ||
        setProp(domElement, tag, lastProp, propKey$203, nextProps, propKey);
}
var eventsEnabled = null,
  selectionInformation = null;
function getOwnerDocumentFromRootContainer(rootContainerElement) {
  return 9 === rootContainerElement.nodeType
    ? rootContainerElement
    : rootContainerElement.ownerDocument;
}
function getOwnHostContext(namespaceURI) {
  switch (namespaceURI) {
    case "http://www.w3.org/2000/svg":
      return 1;
    case "http://www.w3.org/1998/Math/MathML":
      return 2;
    default:
      return 0;
  }
}
function getChildHostContextProd(parentNamespace, type) {
  if (0 === parentNamespace)
    switch (type) {
      case "svg":
        return 1;
      case "math":
        return 2;
      default:
        return 0;
    }
  return 1 === parentNamespace && "foreignObject" === type
    ? 0
    : parentNamespace;
}
function shouldSetTextContent(type, props) {
  return (
    "textarea" === type ||
    "noscript" === type ||
    "string" === typeof props.children ||
    "number" === typeof props.children ||
    "bigint" === typeof props.children ||
    ("object" === typeof props.dangerouslySetInnerHTML &&
      null !== props.dangerouslySetInnerHTML &&
      null != props.dangerouslySetInnerHTML.__html)
  );
}
var currentPopstateTransitionEvent = null;
function shouldAttemptEagerTransition() {
  var event = window.event;
  if (event && "popstate" === event.type) {
    if (event === currentPopstateTransitionEvent) return !1;
    currentPopstateTransitionEvent = event;
    return !0;
  }
  currentPopstateTransitionEvent = null;
  return !1;
}
var scheduleTimeout = "function" === typeof setTimeout ? setTimeout : void 0,
  cancelTimeout = "function" === typeof clearTimeout ? clearTimeout : void 0,
  localPromise = "function" === typeof Promise ? Promise : void 0,
  scheduleMicrotask =
    "function" === typeof queueMicrotask
      ? queueMicrotask
      : "undefined" !== typeof localPromise
        ? function (callback) {
            return localPromise
              .resolve(null)
              .then(callback)
              .catch(handleErrorInNextTick);
          }
        : scheduleTimeout;
function handleErrorInNextTick(error) {
  setTimeout(function () {
    throw error;
  });
}
function clearSuspenseBoundary(parentInstance, suspenseInstance) {
  var node = suspenseInstance,
    depth = 0;
  do {
    var nextNode = node.nextSibling;
    parentInstance.removeChild(node);
    if (nextNode && 8 === nextNode.nodeType)
      if (((node = nextNode.data), "/$" === node)) {
        if (0 === depth) {
          parentInstance.removeChild(nextNode);
          retryIfBlockedOn(suspenseInstance);
          return;
        }
        depth--;
      } else ("$" !== node && "$?" !== node && "$!" !== node) || depth++;
    node = nextNode;
  } while (node);
  retryIfBlockedOn(suspenseInstance);
}
function clearContainerSparingly(container) {
  var nextNode = container.firstChild;
  nextNode && 10 === nextNode.nodeType && (nextNode = nextNode.nextSibling);
  for (; nextNode; ) {
    var node = nextNode;
    nextNode = nextNode.nextSibling;
    switch (node.nodeName) {
      case "HTML":
      case "HEAD":
      case "BODY":
        clearContainerSparingly(node);
        detachDeletedInstance(node);
        continue;
      case "SCRIPT":
      case "STYLE":
        continue;
      case "LINK":
        if ("stylesheet" === node.rel.toLowerCase()) continue;
    }
    container.removeChild(node);
  }
}
function canHydrateInstance(instance, type, props, inRootOrSingleton) {
  for (; 1 === instance.nodeType; ) {
    var anyProps = props;
    if (instance.nodeName.toLowerCase() !== type.toLowerCase()) {
      if (
        !inRootOrSingleton &&
        ("INPUT" !== instance.nodeName || "hidden" !== instance.type)
      )
        break;
    } else if (!inRootOrSingleton)
      if ("input" === type && "hidden" === instance.type) {
        var name = null == anyProps.name ? null : "" + anyProps.name;
        if (
          "hidden" === anyProps.type &&
          instance.getAttribute("name") === name
        )
          return instance;
      } else return instance;
    else if (!instance[internalHoistableMarker])
      switch (type) {
        case "meta":
          if (!instance.hasAttribute("itemprop")) break;
          return instance;
        case "link":
          name = instance.getAttribute("rel");
          if ("stylesheet" === name && instance.hasAttribute("data-precedence"))
            break;
          else if (
            name !== anyProps.rel ||
            instance.getAttribute("href") !==
              (null == anyProps.href ? null : anyProps.href) ||
            instance.getAttribute("crossorigin") !==
              (null == anyProps.crossOrigin ? null : anyProps.crossOrigin) ||
            instance.getAttribute("title") !==
              (null == anyProps.title ? null : anyProps.title)
          )
            break;
          return instance;
        case "style":
          if (instance.hasAttribute("data-precedence")) break;
          return instance;
        case "script":
          name = instance.getAttribute("src");
          if (
            (name !== (null == anyProps.src ? null : anyProps.src) ||
              instance.getAttribute("type") !==
                (null == anyProps.type ? null : anyProps.type) ||
              instance.getAttribute("crossorigin") !==
                (null == anyProps.crossOrigin ? null : anyProps.crossOrigin)) &&
            name &&
            instance.hasAttribute("async") &&
            !instance.hasAttribute("itemprop")
          )
            break;
          return instance;
        default:
          return instance;
      }
    instance = getNextHydratable(instance.nextSibling);
    if (null === instance) break;
  }
  return null;
}
function canHydrateTextInstance(instance, text, inRootOrSingleton) {
  if ("" === text) return null;
  for (; 3 !== instance.nodeType; ) {
    if (
      (1 !== instance.nodeType ||
        "INPUT" !== instance.nodeName ||
        "hidden" !== instance.type) &&
      !inRootOrSingleton
    )
      return null;
    instance = getNextHydratable(instance.nextSibling);
    if (null === instance) return null;
  }
  return instance;
}
function getNextHydratable(node) {
  for (; null != node; node = node.nextSibling) {
    var nodeType = node.nodeType;
    if (1 === nodeType || 3 === nodeType) break;
    if (8 === nodeType) {
      nodeType = node.data;
      if (
        "$" === nodeType ||
        "$!" === nodeType ||
        "$?" === nodeType ||
        "F!" === nodeType ||
        "F" === nodeType
      )
        break;
      if ("/$" === nodeType) return null;
    }
  }
  return node;
}
function getParentSuspenseInstance(targetInstance) {
  targetInstance = targetInstance.previousSibling;
  for (var depth = 0; targetInstance; ) {
    if (8 === targetInstance.nodeType) {
      var data = targetInstance.data;
      if ("$" === data || "$!" === data || "$?" === data) {
        if (0 === depth) return targetInstance;
        depth--;
      } else "/$" === data && depth++;
    }
    targetInstance = targetInstance.previousSibling;
  }
  return null;
}
function resolveSingletonInstance(type, props, rootContainerInstance) {
  props = getOwnerDocumentFromRootContainer(rootContainerInstance);
  switch (type) {
    case "html":
      type = props.documentElement;
      if (!type) throw Error(formatProdErrorMessage(452));
      return type;
    case "head":
      type = props.head;
      if (!type) throw Error(formatProdErrorMessage(453));
      return type;
    case "body":
      type = props.body;
      if (!type) throw Error(formatProdErrorMessage(454));
      return type;
    default:
      throw Error(formatProdErrorMessage(451));
  }
}
var preloadPropsMap = new Map(),
  preconnectsSet = new Set();
function getHoistableRoot(container) {
  return "function" === typeof container.getRootNode
    ? container.getRootNode()
    : container.ownerDocument;
}
var previousDispatcher = ReactDOMSharedInternals.d;
ReactDOMSharedInternals.d = {
  f: flushSyncWork,
  r: requestFormReset,
  D: prefetchDNS,
  C: preconnect,
  L: preload,
  m: preloadModule,
  X: preinitScript,
  S: preinitStyle,
  M: preinitModuleScript
};
function flushSyncWork() {
  var previousWasRendering = previousDispatcher.f(),
    wasRendering = flushSyncWork$1();
  return previousWasRendering || wasRendering;
}
function requestFormReset(form) {
  var formInst = getInstanceFromNode(form);
  null !== formInst && 5 === formInst.tag && "form" === formInst.type
    ? requestFormReset$1(formInst)
    : previousDispatcher.r(form);
}
var globalDocument = "undefined" === typeof document ? null : document;
function preconnectAs(rel, href, crossOrigin) {
  var ownerDocument = globalDocument;
  if (ownerDocument && "string" === typeof href && href) {
    var limitedEscapedHref =
      escapeSelectorAttributeValueInsideDoubleQuotes(href);
    limitedEscapedHref =
      'link[rel="' + rel + '"][href="' + limitedEscapedHref + '"]';
    "string" === typeof crossOrigin &&
      (limitedEscapedHref += '[crossorigin="' + crossOrigin + '"]');
    preconnectsSet.has(limitedEscapedHref) ||
      (preconnectsSet.add(limitedEscapedHref),
      (rel = { rel: rel, crossOrigin: crossOrigin, href: href }),
      null === ownerDocument.querySelector(limitedEscapedHref) &&
        ((href = ownerDocument.createElement("link")),
        setInitialProperties(href, "link", rel),
        markNodeAsHoistable(href),
        ownerDocument.head.appendChild(href)));
  }
}
function prefetchDNS(href) {
  previousDispatcher.D(href);
  preconnectAs("dns-prefetch", href, null);
}
function preconnect(href, crossOrigin) {
  previousDispatcher.C(href, crossOrigin);
  preconnectAs("preconnect", href, crossOrigin);
}
function preload(href, as, options) {
  previousDispatcher.L(href, as, options);
  var ownerDocument = globalDocument;
  if (ownerDocument && href && as) {
    var preloadSelector =
      'link[rel="preload"][as="' +
      escapeSelectorAttributeValueInsideDoubleQuotes(as) +
      '"]';
    "image" === as
      ? options && options.imageSrcSet
        ? ((preloadSelector +=
            '[imagesrcset="' +
            escapeSelectorAttributeValueInsideDoubleQuotes(
              options.imageSrcSet
            ) +
            '"]'),
          "string" === typeof options.imageSizes &&
            (preloadSelector +=
              '[imagesizes="' +
              escapeSelectorAttributeValueInsideDoubleQuotes(
                options.imageSizes
              ) +
              '"]'))
        : (preloadSelector +=
            '[href="' +
            escapeSelectorAttributeValueInsideDoubleQuotes(href) +
            '"]')
      : (preloadSelector +=
          '[href="' +
          escapeSelectorAttributeValueInsideDoubleQuotes(href) +
          '"]');
    var key = preloadSelector;
    switch (as) {
      case "style":
        key = getStyleKey(href);
        break;
      case "script":
        key = getScriptKey(href);
    }
    preloadPropsMap.has(key) ||
      ((href = assign(
        {
          rel: "preload",
          href:
            "image" === as && options && options.imageSrcSet ? void 0 : href,
          as: as
        },
        options
      )),
      preloadPropsMap.set(key, href),
      null !== ownerDocument.querySelector(preloadSelector) ||
        ("style" === as &&
          ownerDocument.querySelector(getStylesheetSelectorFromKey(key))) ||
        ("script" === as &&
          ownerDocument.querySelector(getScriptSelectorFromKey(key))) ||
        ((as = ownerDocument.createElement("link")),
        setInitialProperties(as, "link", href),
        markNodeAsHoistable(as),
        ownerDocument.head.appendChild(as)));
  }
}
function preloadModule(href, options) {
  previousDispatcher.m(href, options);
  var ownerDocument = globalDocument;
  if (ownerDocument && href) {
    var as = options && "string" === typeof options.as ? options.as : "script",
      preloadSelector =
        'link[rel="modulepreload"][as="' +
        escapeSelectorAttributeValueInsideDoubleQuotes(as) +
        '"][href="' +
        escapeSelectorAttributeValueInsideDoubleQuotes(href) +
        '"]',
      key = preloadSelector;
    switch (as) {
      case "audioworklet":
      case "paintworklet":
      case "serviceworker":
      case "sharedworker":
      case "worker":
      case "script":
        key = getScriptKey(href);
    }
    if (
      !preloadPropsMap.has(key) &&
      ((href = assign({ rel: "modulepreload", href: href }, options)),
      preloadPropsMap.set(key, href),
      null === ownerDocument.querySelector(preloadSelector))
    ) {
      switch (as) {
        case "audioworklet":
        case "paintworklet":
        case "serviceworker":
        case "sharedworker":
        case "worker":
        case "script":
          if (ownerDocument.querySelector(getScriptSelectorFromKey(key)))
            return;
      }
      as = ownerDocument.createElement("link");
      setInitialProperties(as, "link", href);
      markNodeAsHoistable(as);
      ownerDocument.head.appendChild(as);
    }
  }
}
function preinitStyle(href, precedence, options) {
  previousDispatcher.S(href, precedence, options);
  var ownerDocument = globalDocument;
  if (ownerDocument && href) {
    var styles = getResourcesFromRoot(ownerDocument).hoistableStyles,
      key = getStyleKey(href);
    precedence = precedence || "default";
    var resource = styles.get(key);
    if (!resource) {
      var state = { loading: 0, preload: null };
      if (
        (resource = ownerDocument.querySelector(
          getStylesheetSelectorFromKey(key)
        ))
      )
        state.loading = 5;
      else {
        href = assign(
          { rel: "stylesheet", href: href, "data-precedence": precedence },
          options
        );
        (options = preloadPropsMap.get(key)) &&
          adoptPreloadPropsForStylesheet(href, options);
        var link = (resource = ownerDocument.createElement("link"));
        markNodeAsHoistable(link);
        setInitialProperties(link, "link", href);
        link._p = new Promise(function (resolve, reject) {
          link.onload = resolve;
          link.onerror = reject;
        });
        link.addEventListener("load", function () {
          state.loading |= 1;
        });
        link.addEventListener("error", function () {
          state.loading |= 2;
        });
        state.loading |= 4;
        insertStylesheet(resource, precedence, ownerDocument);
      }
      resource = {
        type: "stylesheet",
        instance: resource,
        count: 1,
        state: state
      };
      styles.set(key, resource);
    }
  }
}
function preinitScript(src, options) {
  previousDispatcher.X(src, options);
  var ownerDocument = globalDocument;
  if (ownerDocument && src) {
    var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts,
      key = getScriptKey(src),
      resource = scripts.get(key);
    resource ||
      ((resource = ownerDocument.querySelector(getScriptSelectorFromKey(key))),
      resource ||
        ((src = assign({ src: src, async: !0 }, options)),
        (options = preloadPropsMap.get(key)) &&
          adoptPreloadPropsForScript(src, options),
        (resource = ownerDocument.createElement("script")),
        markNodeAsHoistable(resource),
        setInitialProperties(resource, "link", src),
        ownerDocument.head.appendChild(resource)),
      (resource = {
        type: "script",
        instance: resource,
        count: 1,
        state: null
      }),
      scripts.set(key, resource));
  }
}
function preinitModuleScript(src, options) {
  previousDispatcher.M(src, options);
  var ownerDocument = globalDocument;
  if (ownerDocument && src) {
    var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts,
      key = getScriptKey(src),
      resource = scripts.get(key);
    resource ||
      ((resource = ownerDocument.querySelector(getScriptSelectorFromKey(key))),
      resource ||
        ((src = assign({ src: src, async: !0, type: "module" }, options)),
        (options = preloadPropsMap.get(key)) &&
          adoptPreloadPropsForScript(src, options),
        (resource = ownerDocument.createElement("script")),
        markNodeAsHoistable(resource),
        setInitialProperties(resource, "link", src),
        ownerDocument.head.appendChild(resource)),
      (resource = {
        type: "script",
        instance: resource,
        count: 1,
        state: null
      }),
      scripts.set(key, resource));
  }
}
function getResource(type, currentProps, pendingProps, currentResource) {
  var JSCompiler_inline_result = (JSCompiler_inline_result =
    rootInstanceStackCursor.current)
    ? getHoistableRoot(JSCompiler_inline_result)
    : null;
  if (!JSCompiler_inline_result) throw Error(formatProdErrorMessage(446));
  switch (type) {
    case "meta":
    case "title":
      return null;
    case "style":
      return "string" === typeof pendingProps.precedence &&
        "string" === typeof pendingProps.href
        ? ((currentProps = getStyleKey(pendingProps.href)),
          (pendingProps = getResourcesFromRoot(
            JSCompiler_inline_result
          ).hoistableStyles),
          (currentResource = pendingProps.get(currentProps)),
          currentResource ||
            ((currentResource = {
              type: "style",
              instance: null,
              count: 0,
              state: null
            }),
            pendingProps.set(currentProps, currentResource)),
          currentResource)
        : { type: "void", instance: null, count: 0, state: null };
    case "link":
      if (
        "stylesheet" === pendingProps.rel &&
        "string" === typeof pendingProps.href &&
        "string" === typeof pendingProps.precedence
      ) {
        type = getStyleKey(pendingProps.href);
        var styles$242 = getResourcesFromRoot(
            JSCompiler_inline_result
          ).hoistableStyles,
          resource$243 = styles$242.get(type);
        resource$243 ||
          ((JSCompiler_inline_result =
            JSCompiler_inline_result.ownerDocument || JSCompiler_inline_result),
          (resource$243 = {
            type: "stylesheet",
            instance: null,
            count: 0,
            state: { loading: 0, preload: null }
          }),
          styles$242.set(type, resource$243),
          (styles$242 = JSCompiler_inline_result.querySelector(
            getStylesheetSelectorFromKey(type)
          )) &&
            !styles$242._p &&
            ((resource$243.instance = styles$242),
            (resource$243.state.loading = 5)),
          preloadPropsMap.has(type) ||
            ((pendingProps = {
              rel: "preload",
              as: "style",
              href: pendingProps.href,
              crossOrigin: pendingProps.crossOrigin,
              integrity: pendingProps.integrity,
              media: pendingProps.media,
              hrefLang: pendingProps.hrefLang,
              referrerPolicy: pendingProps.referrerPolicy
            }),
            preloadPropsMap.set(type, pendingProps),
            styles$242 ||
              preloadStylesheet(
                JSCompiler_inline_result,
                type,
                pendingProps,
                resource$243.state
              )));
        if (currentProps && null === currentResource)
          throw Error(formatProdErrorMessage(528, ""));
        return resource$243;
      }
      if (currentProps && null !== currentResource)
        throw Error(formatProdErrorMessage(529, ""));
      return null;
    case "script":
      return (
        (currentProps = pendingProps.async),
        (pendingProps = pendingProps.src),
        "string" === typeof pendingProps &&
        currentProps &&
        "function" !== typeof currentProps &&
        "symbol" !== typeof currentProps
          ? ((currentProps = getScriptKey(pendingProps)),
            (pendingProps = getResourcesFromRoot(
              JSCompiler_inline_result
            ).hoistableScripts),
            (currentResource = pendingProps.get(currentProps)),
            currentResource ||
              ((currentResource = {
                type: "script",
                instance: null,
                count: 0,
                state: null
              }),
              pendingProps.set(currentProps, currentResource)),
            currentResource)
          : { type: "void", instance: null, count: 0, state: null }
      );
    default:
      throw Error(formatProdErrorMessage(444, type));
  }
}
function getStyleKey(href) {
  return 'href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"';
}
function getStylesheetSelectorFromKey(key) {
  return 'link[rel="stylesheet"][' + key + "]";
}
function stylesheetPropsFromRawProps(rawProps) {
  return assign({}, rawProps, {
    "data-precedence": rawProps.precedence,
    precedence: null
  });
}
function preloadStylesheet(ownerDocument, key, preloadProps, state) {
  ownerDocument.querySelector('link[rel="preload"][as="style"][' + key + "]")
    ? (state.loading = 1)
    : ((key = ownerDocument.createElement("link")),
      (state.preload = key),
      key.addEventListener("load", function () {
        return (state.loading |= 1);
      }),
      key.addEventListener("error", function () {
        return (state.loading |= 2);
      }),
      setInitialProperties(key, "link", preloadProps),
      markNodeAsHoistable(key),
      ownerDocument.head.appendChild(key));
}
function getScriptKey(src) {
  return '[src="' + escapeSelectorAttributeValueInsideDoubleQuotes(src) + '"]';
}
function getScriptSelectorFromKey(key) {
  return "script[async]" + key;
}
function acquireResource(hoistableRoot, resource, props) {
  resource.count++;
  if (null === resource.instance)
    switch (resource.type) {
      case "style":
        var instance = hoistableRoot.querySelector(
          'style[data-href~="' +
            escapeSelectorAttributeValueInsideDoubleQuotes(props.href) +
            '"]'
        );
        if (instance)
          return (
            (resource.instance = instance),
            markNodeAsHoistable(instance),
            instance
          );
        var styleProps = assign({}, props, {
          "data-href": props.href,
          "data-precedence": props.precedence,
          href: null,
          precedence: null
        });
        instance = (hoistableRoot.ownerDocument || hoistableRoot).createElement(
          "style"
        );
        markNodeAsHoistable(instance);
        setInitialProperties(instance, "style", styleProps);
        insertStylesheet(instance, props.precedence, hoistableRoot);
        return (resource.instance = instance);
      case "stylesheet":
        styleProps = getStyleKey(props.href);
        var instance$248 = hoistableRoot.querySelector(
          getStylesheetSelectorFromKey(styleProps)
        );
        if (instance$248)
          return (
            (resource.state.loading |= 4),
            (resource.instance = instance$248),
            markNodeAsHoistable(instance$248),
            instance$248
          );
        instance = stylesheetPropsFromRawProps(props);
        (styleProps = preloadPropsMap.get(styleProps)) &&
          adoptPreloadPropsForStylesheet(instance, styleProps);
        instance$248 = (
          hoistableRoot.ownerDocument || hoistableRoot
        ).createElement("link");
        markNodeAsHoistable(instance$248);
        var linkInstance = instance$248;
        linkInstance._p = new Promise(function (resolve, reject) {
          linkInstance.onload = resolve;
          linkInstance.onerror = reject;
        });
        setInitialProperties(instance$248, "link", instance);
        resource.state.loading |= 4;
        insertStylesheet(instance$248, props.precedence, hoistableRoot);
        return (resource.instance = instance$248);
      case "script":
        instance$248 = getScriptKey(props.src);
        if (
          (styleProps = hoistableRoot.querySelector(
            getScriptSelectorFromKey(instance$248)
          ))
        )
          return (
            (resource.instance = styleProps),
            markNodeAsHoistable(styleProps),
            styleProps
          );
        instance = props;
        if ((styleProps = preloadPropsMap.get(instance$248)))
          (instance = assign({}, props)),
            adoptPreloadPropsForScript(instance, styleProps);
        hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
        styleProps = hoistableRoot.createElement("script");
        markNodeAsHoistable(styleProps);
        setInitialProperties(styleProps, "link", instance);
        hoistableRoot.head.appendChild(styleProps);
        return (resource.instance = styleProps);
      case "void":
        return null;
      default:
        throw Error(formatProdErrorMessage(443, resource.type));
    }
  else
    "stylesheet" === resource.type &&
      0 === (resource.state.loading & 4) &&
      ((instance = resource.instance),
      (resource.state.loading |= 4),
      insertStylesheet(instance, props.precedence, hoistableRoot));
  return resource.instance;
}
function insertStylesheet(instance, precedence, root) {
  for (
    var nodes = root.querySelectorAll(
        'link[rel="stylesheet"][data-precedence],style[data-precedence]'
      ),
      last = nodes.length ? nodes[nodes.length - 1] : null,
      prior = last,
      i = 0;
    i < nodes.length;
    i++
  ) {
    var node = nodes[i];
    if (node.dataset.precedence === precedence) prior = node;
    else if (prior !== last) break;
  }
  prior
    ? prior.parentNode.insertBefore(instance, prior.nextSibling)
    : ((precedence = 9 === root.nodeType ? root.head : root),
      precedence.insertBefore(instance, precedence.firstChild));
}
function adoptPreloadPropsForStylesheet(stylesheetProps, preloadProps) {
  null == stylesheetProps.crossOrigin &&
    (stylesheetProps.crossOrigin = preloadProps.crossOrigin);
  null == stylesheetProps.referrerPolicy &&
    (stylesheetProps.referrerPolicy = preloadProps.referrerPolicy);
  null == stylesheetProps.title && (stylesheetProps.title = preloadProps.title);
}
function adoptPreloadPropsForScript(scriptProps, preloadProps) {
  null == scriptProps.crossOrigin &&
    (scriptProps.crossOrigin = preloadProps.crossOrigin);
  null == scriptProps.referrerPolicy &&
    (scriptProps.referrerPolicy = preloadProps.referrerPolicy);
  null == scriptProps.integrity &&
    (scriptProps.integrity = preloadProps.integrity);
}
var tagCaches = null;
function getHydratableHoistableCache(type, keyAttribute, ownerDocument) {
  if (null === tagCaches) {
    var cache = new Map();
    var caches = (tagCaches = new Map());
    caches.set(ownerDocument, cache);
  } else
    (caches = tagCaches),
      (cache = caches.get(ownerDocument)),
      cache || ((cache = new Map()), caches.set(ownerDocument, cache));
  if (cache.has(type)) return cache;
  cache.set(type, null);
  ownerDocument = ownerDocument.getElementsByTagName(type);
  for (caches = 0; caches < ownerDocument.length; caches++) {
    var node = ownerDocument[caches];
    if (
      !(
        node[internalHoistableMarker] ||
        node[internalInstanceKey] ||
        ("link" === type && "stylesheet" === node.getAttribute("rel"))
      ) &&
      "http://www.w3.org/2000/svg" !== node.namespaceURI
    ) {
      var nodeKey = node.getAttribute(keyAttribute) || "";
      nodeKey = type + nodeKey;
      var existing = cache.get(nodeKey);
      existing ? existing.push(node) : cache.set(nodeKey, [node]);
    }
  }
  return cache;
}
function mountHoistable(hoistableRoot, type, instance) {
  hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
  hoistableRoot.head.insertBefore(
    instance,
    "title" === type ? hoistableRoot.querySelector("head > title") : null
  );
}
function isHostHoistableType(type, props, hostContext) {
  if (1 === hostContext || null != props.itemProp) return !1;
  switch (type) {
    case "meta":
    case "title":
      return !0;
    case "style":
      if (
        "string" !== typeof props.precedence ||
        "string" !== typeof props.href ||
        "" === props.href
      )
        break;
      return !0;
    case "link":
      if (
        "string" !== typeof props.rel ||
        "string" !== typeof props.href ||
        "" === props.href ||
        props.onLoad ||
        props.onError
      )
        break;
      switch (props.rel) {
        case "stylesheet":
          return (
            (type = props.disabled),
            "string" === typeof props.precedence && null == type
          );
        default:
          return !0;
      }
    case "script":
      if (
        props.async &&
        "function" !== typeof props.async &&
        "symbol" !== typeof props.async &&
        !props.onLoad &&
        !props.onError &&
        props.src &&
        "string" === typeof props.src
      )
        return !0;
  }
  return !1;
}
function preloadResource(resource) {
  return "stylesheet" === resource.type && 0 === (resource.state.loading & 3)
    ? !1
    : !0;
}
var suspendedState = null;
function noop() {}
function suspendResource(hoistableRoot, resource, props) {
  if (null === suspendedState) throw Error(formatProdErrorMessage(475));
  var state = suspendedState;
  if (
    "stylesheet" === resource.type &&
    ("string" !== typeof props.media ||
      !1 !== matchMedia(props.media).matches) &&
    0 === (resource.state.loading & 4)
  ) {
    if (null === resource.instance) {
      var key = getStyleKey(props.href),
        instance = hoistableRoot.querySelector(
          getStylesheetSelectorFromKey(key)
        );
      if (instance) {
        hoistableRoot = instance._p;
        null !== hoistableRoot &&
          "object" === typeof hoistableRoot &&
          "function" === typeof hoistableRoot.then &&
          (state.count++,
          (state = onUnsuspend.bind(state)),
          hoistableRoot.then(state, state));
        resource.state.loading |= 4;
        resource.instance = instance;
        markNodeAsHoistable(instance);
        return;
      }
      instance = hoistableRoot.ownerDocument || hoistableRoot;
      props = stylesheetPropsFromRawProps(props);
      (key = preloadPropsMap.get(key)) &&
        adoptPreloadPropsForStylesheet(props, key);
      instance = instance.createElement("link");
      markNodeAsHoistable(instance);
      var linkInstance = instance;
      linkInstance._p = new Promise(function (resolve, reject) {
        linkInstance.onload = resolve;
        linkInstance.onerror = reject;
      });
      setInitialProperties(instance, "link", props);
      resource.instance = instance;
    }
    null === state.stylesheets && (state.stylesheets = new Map());
    state.stylesheets.set(resource, hoistableRoot);
    (hoistableRoot = resource.state.preload) &&
      0 === (resource.state.loading & 3) &&
      (state.count++,
      (resource = onUnsuspend.bind(state)),
      hoistableRoot.addEventListener("load", resource),
      hoistableRoot.addEventListener("error", resource));
  }
}
function waitForCommitToBeReady() {
  if (null === suspendedState) throw Error(formatProdErrorMessage(475));
  var state = suspendedState;
  state.stylesheets &&
    0 === state.count &&
    insertSuspendedStylesheets(state, state.stylesheets);
  return 0 < state.count
    ? function (commit) {
        var stylesheetTimer = setTimeout(function () {
          state.stylesheets &&
            insertSuspendedStylesheets(state, state.stylesheets);
          if (state.unsuspend) {
            var unsuspend = state.unsuspend;
            state.unsuspend = null;
            unsuspend();
          }
        }, 6e4);
        state.unsuspend = commit;
        return function () {
          state.unsuspend = null;
          clearTimeout(stylesheetTimer);
        };
      }
    : null;
}
function onUnsuspend() {
  this.count--;
  if (0 === this.count)
    if (this.stylesheets) insertSuspendedStylesheets(this, this.stylesheets);
    else if (this.unsuspend) {
      var unsuspend = this.unsuspend;
      this.unsuspend = null;
      unsuspend();
    }
}
var precedencesByRoot = null;
function insertSuspendedStylesheets(state, resources) {
  state.stylesheets = null;
  null !== state.unsuspend &&
    (state.count++,
    (precedencesByRoot = new Map()),
    resources.forEach(insertStylesheetIntoRoot, state),
    (precedencesByRoot = null),
    onUnsuspend.call(state));
}
function insertStylesheetIntoRoot(root, resource) {
  if (!(resource.state.loading & 4)) {
    var precedences = precedencesByRoot.get(root);
    if (precedences) var last = precedences.get(null);
    else {
      precedences = new Map();
      precedencesByRoot.set(root, precedences);
      for (
        var nodes = root.querySelectorAll(
            "link[data-precedence],style[data-precedence]"
          ),
          i = 0;
        i < nodes.length;
        i++
      ) {
        var node = nodes[i];
        if (
          "LINK" === node.nodeName ||
          "not all" !== node.getAttribute("media")
        )
          precedences.set(node.dataset.precedence, node), (last = node);
      }
      last && precedences.set(null, last);
    }
    nodes = resource.instance;
    node = nodes.getAttribute("data-precedence");
    i = precedences.get(node) || last;
    i === last && precedences.set(null, nodes);
    precedences.set(node, nodes);
    this.count++;
    last = onUnsuspend.bind(this);
    nodes.addEventListener("load", last);
    nodes.addEventListener("error", last);
    i
      ? i.parentNode.insertBefore(nodes, i.nextSibling)
      : ((root = 9 === root.nodeType ? root.head : root),
        root.insertBefore(nodes, root.firstChild));
    resource.state.loading |= 4;
  }
}
var HostTransitionContext = {
  $$typeof: REACT_CONTEXT_TYPE,
  Provider: null,
  Consumer: null,
  _currentValue: sharedNotPendingObject,
  _currentValue2: sharedNotPendingObject,
  _threadCount: 0
};
function FiberRootNode(
  containerInfo,
  tag,
  hydrate,
  identifierPrefix,
  onUncaughtError,
  onCaughtError,
  onRecoverableError,
  formState
) {
  this.tag = 1;
  this.containerInfo = containerInfo;
  this.finishedWork =
    this.pingCache =
    this.current =
    this.pendingChildren =
      null;
  this.timeoutHandle = -1;
  this.callbackNode =
    this.next =
    this.pendingContext =
    this.context =
    this.cancelPendingCommit =
      null;
  this.callbackPriority = 0;
  this.expirationTimes = createLaneMap(-1);
  this.entangledLanes =
    this.shellSuspendCounter =
    this.errorRecoveryDisabledLanes =
    this.finishedLanes =
    this.expiredLanes =
    this.warmLanes =
    this.pingedLanes =
    this.suspendedLanes =
    this.pendingLanes =
      0;
  this.entanglements = createLaneMap(0);
  this.hiddenUpdates = createLaneMap(null);
  this.identifierPrefix = identifierPrefix;
  this.onUncaughtError = onUncaughtError;
  this.onCaughtError = onCaughtError;
  this.onRecoverableError = onRecoverableError;
  this.pooledCache = null;
  this.pooledCacheLanes = 0;
  this.formState = formState;
  this.incompleteTransitions = new Map();
}
function createFiberRoot(
  containerInfo,
  tag,
  hydrate,
  initialChildren,
  hydrationCallbacks,
  isStrictMode,
  identifierPrefix,
  onUncaughtError,
  onCaughtError,
  onRecoverableError,
  transitionCallbacks,
  formState
) {
  containerInfo = new FiberRootNode(
    containerInfo,
    tag,
    hydrate,
    identifierPrefix,
    onUncaughtError,
    onCaughtError,
    onRecoverableError,
    formState
  );
  tag = 1;
  !0 === isStrictMode && (tag |= 24);
  isStrictMode = createFiberImplClass(3, null, null, tag);
  containerInfo.current = isStrictMode;
  isStrictMode.stateNode = containerInfo;
  tag = createCache();
  tag.refCount++;
  containerInfo.pooledCache = tag;
  tag.refCount++;
  isStrictMode.memoizedState = {
    element: initialChildren,
    isDehydrated: hydrate,
    cache: tag
  };
  initializeUpdateQueue(isStrictMode);
  return containerInfo;
}
function getContextForSubtree(parentComponent) {
  if (!parentComponent) return emptyContextObject;
  parentComponent = emptyContextObject;
  return parentComponent;
}
function updateContainerImpl(
  rootFiber,
  lane,
  element,
  container,
  parentComponent,
  callback
) {
  parentComponent = getContextForSubtree(parentComponent);
  null === container.context
    ? (container.context = parentComponent)
    : (container.pendingContext = parentComponent);
  container = createUpdate(lane);
  container.payload = { element: element };
  callback = void 0 === callback ? null : callback;
  null !== callback && (container.callback = callback);
  element = enqueueUpdate(rootFiber, container, lane);
  null !== element &&
    (scheduleUpdateOnFiber(element, rootFiber, lane),
    entangleTransitions(element, rootFiber, lane));
}
function markRetryLaneImpl(fiber, retryLane) {
  fiber = fiber.memoizedState;
  if (null !== fiber && null !== fiber.dehydrated) {
    var a = fiber.retryLane;
    fiber.retryLane = 0 !== a && a < retryLane ? a : retryLane;
  }
}
function markRetryLaneIfNotHydrated(fiber, retryLane) {
  markRetryLaneImpl(fiber, retryLane);
  (fiber = fiber.alternate) && markRetryLaneImpl(fiber, retryLane);
}
function attemptContinuousHydration(fiber) {
  if (13 === fiber.tag) {
    var root = enqueueConcurrentRenderForLane(fiber, 67108864);
    null !== root && scheduleUpdateOnFiber(root, fiber, 67108864);
    markRetryLaneIfNotHydrated(fiber, 67108864);
  }
}
var _enabled = !0;
function dispatchDiscreteEvent(
  domEventName,
  eventSystemFlags,
  container,
  nativeEvent
) {
  var prevTransition = ReactSharedInternals.T;
  ReactSharedInternals.T = null;
  var previousPriority = ReactDOMSharedInternals.p;
  try {
    (ReactDOMSharedInternals.p = 2),
      dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
  } finally {
    (ReactDOMSharedInternals.p = previousPriority),
      (ReactSharedInternals.T = prevTransition);
  }
}
function dispatchContinuousEvent(
  domEventName,
  eventSystemFlags,
  container,
  nativeEvent
) {
  var prevTransition = ReactSharedInternals.T;
  ReactSharedInternals.T = null;
  var previousPriority = ReactDOMSharedInternals.p;
  try {
    (ReactDOMSharedInternals.p = 8),
      dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
  } finally {
    (ReactDOMSharedInternals.p = previousPriority),
      (ReactSharedInternals.T = prevTransition);
  }
}
function dispatchEvent(
  domEventName,
  eventSystemFlags,
  targetContainer,
  nativeEvent
) {
  if (_enabled) {
    var blockedOn = findInstanceBlockingEvent(nativeEvent);
    if (null === blockedOn)
      dispatchEventForPluginEventSystem(
        domEventName,
        eventSystemFlags,
        nativeEvent,
        return_targetInst,
        targetContainer
      ),
        clearIfContinuousEvent(domEventName, nativeEvent);
    else if (
      queueIfContinuousEvent(
        blockedOn,
        domEventName,
        eventSystemFlags,
        targetContainer,
        nativeEvent
      )
    )
      nativeEvent.stopPropagation();
    else if (
      (clearIfContinuousEvent(domEventName, nativeEvent),
      eventSystemFlags & 4 &&
        -1 < discreteReplayableEvents.indexOf(domEventName))
    ) {
      for (; null !== blockedOn; ) {
        var fiber = getInstanceFromNode(blockedOn);
        if (null !== fiber)
          switch (fiber.tag) {
            case 3:
              fiber = fiber.stateNode;
              if (fiber.current.memoizedState.isDehydrated) {
                var lanes = getHighestPriorityLanes(fiber.pendingLanes);
                if (0 !== lanes) {
                  var root = fiber;
                  root.pendingLanes |= 2;
                  for (root.entangledLanes |= 2; lanes; ) {
                    var lane = 1 << (31 - clz32(lanes));
                    root.entanglements[1] |= lane;
                    lanes &= ~lane;
                  }
                  ensureRootIsScheduled(fiber);
                  0 === (executionContext & 6) &&
                    ((workInProgressRootRenderTargetTime = now() + 500),
                    flushSyncWorkAcrossRoots_impl(0, !1));
                }
              }
              break;
            case 13:
              (root = enqueueConcurrentRenderForLane(fiber, 2)),
                null !== root && scheduleUpdateOnFiber(root, fiber, 2),
                flushSyncWork$1(),
                markRetryLaneIfNotHydrated(fiber, 2);
          }
        fiber = findInstanceBlockingEvent(nativeEvent);
        null === fiber &&
          dispatchEventForPluginEventSystem(
            domEventName,
            eventSystemFlags,
            nativeEvent,
            return_targetInst,
            targetContainer
          );
        if (fiber === blockedOn) break;
        blockedOn = fiber;
      }
      null !== blockedOn && nativeEvent.stopPropagation();
    } else
      dispatchEventForPluginEventSystem(
        domEventName,
        eventSystemFlags,
        nativeEvent,
        null,
        targetContainer
      );
  }
}
function findInstanceBlockingEvent(nativeEvent) {
  nativeEvent = getEventTarget(nativeEvent);
  return findInstanceBlockingTarget(nativeEvent);
}
var return_targetInst = null;
function findInstanceBlockingTarget(targetNode) {
  return_targetInst = null;
  targetNode = getClosestInstanceFromNode(targetNode);
  if (null !== targetNode) {
    var nearestMounted = getNearestMountedFiber(targetNode);
    if (null === nearestMounted) targetNode = null;
    else {
      var tag = nearestMounted.tag;
      if (13 === tag) {
        targetNode = getSuspenseInstanceFromFiber(nearestMounted);
        if (null !== targetNode) return targetNode;
        targetNode = null;
      } else if (3 === tag) {
        if (nearestMounted.stateNode.current.memoizedState.isDehydrated)
          return 3 === nearestMounted.tag
            ? nearestMounted.stateNode.containerInfo
            : null;
        targetNode = null;
      } else nearestMounted !== targetNode && (targetNode = null);
    }
  }
  return_targetInst = targetNode;
  return null;
}
function getEventPriority(domEventName) {
  switch (domEventName) {
    case "beforetoggle":
    case "cancel":
    case "click":
    case "close":
    case "contextmenu":
    case "copy":
    case "cut":
    case "auxclick":
    case "dblclick":
    case "dragend":
    case "dragstart":
    case "drop":
    case "focusin":
    case "focusout":
    case "input":
    case "invalid":
    case "keydown":
    case "keypress":
    case "keyup":
    case "mousedown":
    case "mouseup":
    case "paste":
    case "pause":
    case "play":
    case "pointercancel":
    case "pointerdown":
    case "pointerup":
    case "ratechange":
    case "reset":
    case "resize":
    case "seeked":
    case "submit":
    case "toggle":
    case "touchcancel":
    case "touchend":
    case "touchstart":
    case "volumechange":
    case "change":
    case "selectionchange":
    case "textInput":
    case "compositionstart":
    case "compositionend":
    case "compositionupdate":
    case "beforeblur":
    case "afterblur":
    case "beforeinput":
    case "blur":
    case "fullscreenchange":
    case "focus":
    case "hashchange":
    case "popstate":
    case "select":
    case "selectstart":
      return 2;
    case "drag":
    case "dragenter":
    case "dragexit":
    case "dragleave":
    case "dragover":
    case "mousemove":
    case "mouseout":
    case "mouseover":
    case "pointermove":
    case "pointerout":
    case "pointerover":
    case "scroll":
    case "touchmove":
    case "wheel":
    case "mouseenter":
    case "mouseleave":
    case "pointerenter":
    case "pointerleave":
      return 8;
    case "message":
      switch (getCurrentPriorityLevel()) {
        case ImmediatePriority:
          return 2;
        case UserBlockingPriority:
          return 8;
        case NormalPriority$1:
        case LowPriority:
          return 32;
        case IdlePriority:
          return 268435456;
        default:
          return 32;
      }
    default:
      return 32;
  }
}
var hasScheduledReplayAttempt = !1,
  queuedFocus = null,
  queuedDrag = null,
  queuedMouse = null,
  queuedPointers = new Map(),
  queuedPointerCaptures = new Map(),
  queuedExplicitHydrationTargets = [],
  discreteReplayableEvents =
    "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(
      " "
    );
function clearIfContinuousEvent(domEventName, nativeEvent) {
  switch (domEventName) {
    case "focusin":
    case "focusout":
      queuedFocus = null;
      break;
    case "dragenter":
    case "dragleave":
      queuedDrag = null;
      break;
    case "mouseover":
    case "mouseout":
      queuedMouse = null;
      break;
    case "pointerover":
    case "pointerout":
      queuedPointers.delete(nativeEvent.pointerId);
      break;
    case "gotpointercapture":
    case "lostpointercapture":
      queuedPointerCaptures.delete(nativeEvent.pointerId);
  }
}
function accumulateOrCreateContinuousQueuedReplayableEvent(
  existingQueuedEvent,
  blockedOn,
  domEventName,
  eventSystemFlags,
  targetContainer,
  nativeEvent
) {
  if (
    null === existingQueuedEvent ||
    existingQueuedEvent.nativeEvent !== nativeEvent
  )
    return (
      (existingQueuedEvent = {
        blockedOn: blockedOn,
        domEventName: domEventName,
        eventSystemFlags: eventSystemFlags,
        nativeEvent: nativeEvent,
        targetContainers: [targetContainer]
      }),
      null !== blockedOn &&
        ((blockedOn = getInstanceFromNode(blockedOn)),
        null !== blockedOn && attemptContinuousHydration(blockedOn)),
      existingQueuedEvent
    );
  existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
  blockedOn = existingQueuedEvent.targetContainers;
  null !== targetContainer &&
    -1 === blockedOn.indexOf(targetContainer) &&
    blockedOn.push(targetContainer);
  return existingQueuedEvent;
}
function queueIfContinuousEvent(
  blockedOn,
  domEventName,
  eventSystemFlags,
  targetContainer,
  nativeEvent
) {
  switch (domEventName) {
    case "focusin":
      return (
        (queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(
          queuedFocus,
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          nativeEvent
        )),
        !0
      );
    case "dragenter":
      return (
        (queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(
          queuedDrag,
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          nativeEvent
        )),
        !0
      );
    case "mouseover":
      return (
        (queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(
          queuedMouse,
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          nativeEvent
        )),
        !0
      );
    case "pointerover":
      var pointerId = nativeEvent.pointerId;
      queuedPointers.set(
        pointerId,
        accumulateOrCreateContinuousQueuedReplayableEvent(
          queuedPointers.get(pointerId) || null,
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          nativeEvent
        )
      );
      return !0;
    case "gotpointercapture":
      return (
        (pointerId = nativeEvent.pointerId),
        queuedPointerCaptures.set(
          pointerId,
          accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedPointerCaptures.get(pointerId) || null,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          )
        ),
        !0
      );
  }
  return !1;
}
function attemptExplicitHydrationTarget(queuedTarget) {
  var targetInst = getClosestInstanceFromNode(queuedTarget.target);
  if (null !== targetInst) {
    var nearestMounted = getNearestMountedFiber(targetInst);
    if (null !== nearestMounted)
      if (((targetInst = nearestMounted.tag), 13 === targetInst)) {
        if (
          ((targetInst = getSuspenseInstanceFromFiber(nearestMounted)),
          null !== targetInst)
        ) {
          queuedTarget.blockedOn = targetInst;
          runWithPriority(queuedTarget.priority, function () {
            if (13 === nearestMounted.tag) {
              var lane = requestUpdateLane(),
                root = enqueueConcurrentRenderForLane(nearestMounted, lane);
              null !== root &&
                scheduleUpdateOnFiber(root, nearestMounted, lane);
              markRetryLaneIfNotHydrated(nearestMounted, lane);
            }
          });
          return;
        }
      } else if (
        3 === targetInst &&
        nearestMounted.stateNode.current.memoizedState.isDehydrated
      ) {
        queuedTarget.blockedOn =
          3 === nearestMounted.tag
            ? nearestMounted.stateNode.containerInfo
            : null;
        return;
      }
  }
  queuedTarget.blockedOn = null;
}
function attemptReplayContinuousQueuedEvent(queuedEvent) {
  if (null !== queuedEvent.blockedOn) return !1;
  for (
    var targetContainers = queuedEvent.targetContainers;
    0 < targetContainers.length;

  ) {
    var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.nativeEvent);
    if (null === nextBlockedOn) {
      nextBlockedOn = queuedEvent.nativeEvent;
      var nativeEventClone = new nextBlockedOn.constructor(
        nextBlockedOn.type,
        nextBlockedOn
      );
      currentReplayingEvent = nativeEventClone;
      nextBlockedOn.target.dispatchEvent(nativeEventClone);
      currentReplayingEvent = null;
    } else
      return (
        (targetContainers = getInstanceFromNode(nextBlockedOn)),
        null !== targetContainers &&
          attemptContinuousHydration(targetContainers),
        (queuedEvent.blockedOn = nextBlockedOn),
        !1
      );
    targetContainers.shift();
  }
  return !0;
}
function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
  attemptReplayContinuousQueuedEvent(queuedEvent) && map.delete(key);
}
function replayUnblockedEvents() {
  hasScheduledReplayAttempt = !1;
  null !== queuedFocus &&
    attemptReplayContinuousQueuedEvent(queuedFocus) &&
    (queuedFocus = null);
  null !== queuedDrag &&
    attemptReplayContinuousQueuedEvent(queuedDrag) &&
    (queuedDrag = null);
  null !== queuedMouse &&
    attemptReplayContinuousQueuedEvent(queuedMouse) &&
    (queuedMouse = null);
  queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
  queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
}
function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
  queuedEvent.blockedOn === unblocked &&
    ((queuedEvent.blockedOn = null),
    hasScheduledReplayAttempt ||
      ((hasScheduledReplayAttempt = !0),
      Scheduler.unstable_scheduleCallback(
        Scheduler.unstable_NormalPriority,
        replayUnblockedEvents
      )));
}
var lastScheduledReplayQueue = null;
function scheduleReplayQueueIfNeeded(formReplayingQueue) {
  lastScheduledReplayQueue !== formReplayingQueue &&
    ((lastScheduledReplayQueue = formReplayingQueue),
    Scheduler.unstable_scheduleCallback(
      Scheduler.unstable_NormalPriority,
      function () {
        lastScheduledReplayQueue === formReplayingQueue &&
          (lastScheduledReplayQueue = null);
        for (var i = 0; i < formReplayingQueue.length; i += 3) {
          var form = formReplayingQueue[i],
            submitterOrAction = formReplayingQueue[i + 1],
            formData = formReplayingQueue[i + 2];
          if ("function" !== typeof submitterOrAction)
            if (null === findInstanceBlockingTarget(submitterOrAction || form))
              continue;
            else break;
          var formInst = getInstanceFromNode(form);
          null !== formInst &&
            (formReplayingQueue.splice(i, 3),
            (i -= 3),
            startHostTransition(
              formInst,
              {
                pending: !0,
                data: formData,
                method: form.method,
                action: submitterOrAction
              },
              submitterOrAction,
              formData
            ));
        }
      }
    ));
}
function retryIfBlockedOn(unblocked) {
  function unblock(queuedEvent) {
    return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
  }
  null !== queuedFocus && scheduleCallbackIfUnblocked(queuedFocus, unblocked);
  null !== queuedDrag && scheduleCallbackIfUnblocked(queuedDrag, unblocked);
  null !== queuedMouse && scheduleCallbackIfUnblocked(queuedMouse, unblocked);
  queuedPointers.forEach(unblock);
  queuedPointerCaptures.forEach(unblock);
  for (var i = 0; i < queuedExplicitHydrationTargets.length; i++) {
    var queuedTarget = queuedExplicitHydrationTargets[i];
    queuedTarget.blockedOn === unblocked && (queuedTarget.blockedOn = null);
  }
  for (
    ;
    0 < queuedExplicitHydrationTargets.length &&
    ((i = queuedExplicitHydrationTargets[0]), null === i.blockedOn);

  )
    attemptExplicitHydrationTarget(i),
      null === i.blockedOn && queuedExplicitHydrationTargets.shift();
  i = (unblocked.ownerDocument || unblocked).$$reactFormReplay;
  if (null != i)
    for (queuedTarget = 0; queuedTarget < i.length; queuedTarget += 3) {
      var form = i[queuedTarget],
        submitterOrAction = i[queuedTarget + 1],
        formProps = form[internalPropsKey] || null;
      if ("function" === typeof submitterOrAction)
        formProps || scheduleReplayQueueIfNeeded(i);
      else if (formProps) {
        var action = null;
        if (submitterOrAction && submitterOrAction.hasAttribute("formAction"))
          if (
            ((form = submitterOrAction),
            (formProps = submitterOrAction[internalPropsKey] || null))
          )
            action = formProps.formAction;
          else {
            if (null !== findInstanceBlockingTarget(form)) continue;
          }
        else action = formProps.action;
        "function" === typeof action
          ? (i[queuedTarget + 1] = action)
          : (i.splice(queuedTarget, 3), (queuedTarget -= 3));
        scheduleReplayQueueIfNeeded(i);
      }
    }
}
function ReactDOMRoot(internalRoot) {
  this._internalRoot = internalRoot;
}
ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render =
  function (children) {
    var root = this._internalRoot;
    if (null === root) throw Error(formatProdErrorMessage(409));
    var current = root.current,
      lane = requestUpdateLane();
    updateContainerImpl(current, lane, children, root, null, null);
  };
ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount =
  function () {
    var root = this._internalRoot;
    if (null !== root) {
      this._internalRoot = null;
      var container = root.containerInfo;
      0 === root.tag && flushPassiveEffects();
      updateContainerImpl(root.current, 2, null, root, null, null);
      flushSyncWork$1();
      container[internalContainerInstanceKey] = null;
    }
  };
function ReactDOMHydrationRoot(internalRoot) {
  this._internalRoot = internalRoot;
}
ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = function (target) {
  if (target) {
    var updatePriority = resolveUpdatePriority();
    target = { blockedOn: null, target: target, priority: updatePriority };
    for (
      var i = 0;
      i < queuedExplicitHydrationTargets.length &&
      0 !== updatePriority &&
      updatePriority < queuedExplicitHydrationTargets[i].priority;
      i++
    );
    queuedExplicitHydrationTargets.splice(i, 0, target);
    0 === i && attemptExplicitHydrationTarget(target);
  }
};
var isomorphicReactPackageVersion$jscomp$inline_1686 = React.version;
if (
  "19.0.0" !==
  isomorphicReactPackageVersion$jscomp$inline_1686
)
  throw Error(
    formatProdErrorMessage(
      527,
      isomorphicReactPackageVersion$jscomp$inline_1686,
      "19.0.0"
    )
  );
ReactDOMSharedInternals.findDOMNode = function (componentOrElement) {
  var fiber = componentOrElement._reactInternals;
  if (void 0 === fiber) {
    if ("function" === typeof componentOrElement.render)
      throw Error(formatProdErrorMessage(188));
    componentOrElement = Object.keys(componentOrElement).join(",");
    throw Error(formatProdErrorMessage(268, componentOrElement));
  }
  componentOrElement = findCurrentFiberUsingSlowPath(fiber);
  componentOrElement =
    null !== componentOrElement
      ? findCurrentHostFiberImpl(componentOrElement)
      : null;
  componentOrElement =
    null === componentOrElement ? null : componentOrElement.stateNode;
  return componentOrElement;
};
var internals$jscomp$inline_2165 = {
  bundleType: 0,
  version: "19.0.0",
  rendererPackageName: "react-dom",
  currentDispatcherRef: ReactSharedInternals,
  findFiberByHostInstance: getClosestInstanceFromNode,
  reconcilerVersion: "19.0.0"
};
if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) {
  var hook$jscomp$inline_2166 = __REACT_DEVTOOLS_GLOBAL_HOOK__;
  if (
    !hook$jscomp$inline_2166.isDisabled &&
    hook$jscomp$inline_2166.supportsFiber
  )
    try {
      (rendererID = hook$jscomp$inline_2166.inject(
        internals$jscomp$inline_2165
      )),
        (injectedHook = hook$jscomp$inline_2166);
    } catch (err) {}
}
exports.createRoot = function (container, options) {
  if (!isValidContainer(container)) throw Error(formatProdErrorMessage(299));
  var isStrictMode = !1,
    identifierPrefix = "",
    onUncaughtError = defaultOnUncaughtError,
    onCaughtError = defaultOnCaughtError,
    onRecoverableError = defaultOnRecoverableError,
    transitionCallbacks = null;
  null !== options &&
    void 0 !== options &&
    (!0 === options.unstable_strictMode && (isStrictMode = !0),
    void 0 !== options.identifierPrefix &&
      (identifierPrefix = options.identifierPrefix),
    void 0 !== options.onUncaughtError &&
      (onUncaughtError = options.onUncaughtError),
    void 0 !== options.onCaughtError && (onCaughtError = options.onCaughtError),
    void 0 !== options.onRecoverableError &&
      (onRecoverableError = options.onRecoverableError),
    void 0 !== options.unstable_transitionCallbacks &&
      (transitionCallbacks = options.unstable_transitionCallbacks));
  options = createFiberRoot(
    container,
    1,
    !1,
    null,
    null,
    isStrictMode,
    identifierPrefix,
    onUncaughtError,
    onCaughtError,
    onRecoverableError,
    transitionCallbacks,
    null
  );
  container[internalContainerInstanceKey] = options.current;
  listenToAllSupportedEvents(
    8 === container.nodeType ? container.parentNode : container
  );
  return new ReactDOMRoot(options);
};
exports.hydrateRoot = function (container, initialChildren, options) {
  if (!isValidContainer(container)) throw Error(formatProdErrorMessage(299));
  var isStrictMode = !1,
    identifierPrefix = "",
    onUncaughtError = defaultOnUncaughtError,
    onCaughtError = defaultOnCaughtError,
    onRecoverableError = defaultOnRecoverableError,
    transitionCallbacks = null,
    formState = null;
  null !== options &&
    void 0 !== options &&
    (!0 === options.unstable_strictMode && (isStrictMode = !0),
    void 0 !== options.identifierPrefix &&
      (identifierPrefix = options.identifierPrefix),
    void 0 !== options.onUncaughtError &&
      (onUncaughtError = options.onUncaughtError),
    void 0 !== options.onCaughtError && (onCaughtError = options.onCaughtError),
    void 0 !== options.onRecoverableError &&
      (onRecoverableError = options.onRecoverableError),
    void 0 !== options.unstable_transitionCallbacks &&
      (transitionCallbacks = options.unstable_transitionCallbacks),
    void 0 !== options.formState && (formState = options.formState));
  initialChildren = createFiberRoot(
    container,
    1,
    !0,
    initialChildren,
    null != options ? options : null,
    isStrictMode,
    identifierPrefix,
    onUncaughtError,
    onCaughtError,
    onRecoverableError,
    transitionCallbacks,
    formState
  );
  initialChildren.context = getContextForSubtree(null);
  options = initialChildren.current;
  isStrictMode = requestUpdateLane();
  identifierPrefix = createUpdate(isStrictMode);
  identifierPrefix.callback = null;
  enqueueUpdate(options, identifierPrefix, isStrictMode);
  initialChildren.current.lanes = isStrictMode;
  markRootUpdated$1(initialChildren, isStrictMode);
  ensureRootIsScheduled(initialChildren);
  container[internalContainerInstanceKey] = initialChildren.current;
  listenToAllSupportedEvents(container);
  return new ReactDOMHydrationRoot(initialChildren);
};
exports.version = "19.0.0";


/***/ }),

/***/ 87073:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  m: () => (/* reexport */ Tooltip)
});

// EXTERNAL MODULE: ./src/editor/src/hooks/useTimeout.ts
var useTimeout = __webpack_require__(98849);
// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/BaseDialog/index.ts + 3 modules
var BaseDialog = __webpack_require__(65762);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Label/index.ts + 2 modules
var Label = __webpack_require__(91629);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/index.ts
var Text = __webpack_require__(93834);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/popups/Tooltip/Tooltip.module.scss
var Tooltip_module = __webpack_require__(79934);
;// ../noodl-core-ui/src/components/popups/Tooltip/Tooltip.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(Tooltip_module/* default */.A, options);




       /* harmony default export */ const Tooltip_Tooltip_module = (Tooltip_module/* default */.A && Tooltip_module/* default */.A.locals ? Tooltip_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/popups/Tooltip/Tooltip.tsx







function Tooltip({ content, fineType, children, renderDirection, isNotHiddenOnClick, isInline, showAfterMs = 900, UNSAFE_tooltipMaxWidth, UNSAFE_style, UNSAFE_className, UNSAFE_triggerClassName }) {
    const [isTooltipVisible, setIsTooltipVisible] = (0,external_react_.useState)(false);
    const [isTimeoutRunning, setIsTimeoutRunning] = (0,external_react_.useState)(false);
    const triggerRef = (0,external_react_.useRef)(null);
    // hovering the trigger sets triggers a timeout flag and not
    // tooltip visibility flag. this way we can cancel the timeout
    // if the user has stopped hovering before 500ms has passed
    (0,useTimeout/* default */.A)(() => setIsTooltipVisible(true), isTimeoutRunning ? showAfterMs : null);
    function reset() {
        setIsTimeoutRunning(false);
        setIsTooltipVisible(false);
    }
    if (!content)
        return external_react_default().createElement((external_react_default()).Fragment, null, children);
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { isVisible: isTooltipVisible, triggerRef: triggerRef, renderDirection: renderDirection, hasArrow: true, background: BaseDialog/* DialogBackground */.$j.Secondary },
            external_react_default().createElement("div", { className: Tooltip_Tooltip_module['Root'], style: { maxWidth: UNSAFE_tooltipMaxWidth } }, typeof content === 'string' ? (external_react_default().createElement(Label/* Label */.JU, { variant: Text/* TextType */.M2.Proud, size: Label/* LabelSize */.IV.Medium }, content)) : (content)),
            fineType && (external_react_default().createElement("div", { className: Tooltip_Tooltip_module['FineType'] },
                external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Small, variant: Text/* TextType */.M2.Secondary }, fineType)))),
        external_react_default().createElement("div", { ref: triggerRef, className: external_classnames_default()(Tooltip_Tooltip_module['Trigger'], isInline && Tooltip_Tooltip_module['is-inline'], !isInline && Tooltip_Tooltip_module['is-block'], UNSAFE_triggerClassName, UNSAFE_className), style: UNSAFE_style, onMouseOver: () => setIsTimeoutRunning(true), onMouseOut: () => reset(), onClick: () => !isNotHiddenOnClick && reset() }, children)));
}

;// ../noodl-core-ui/src/components/popups/Tooltip/index.ts



/***/ }),

/***/ 87082:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/* START cover the case that slider is visible on mouseover */
.monaco-editor .minimap.slider-mouseover .minimap-slider {
	opacity: 0;
	transition: opacity 100ms linear;
}
.monaco-editor .minimap.slider-mouseover:hover .minimap-slider {
	opacity: 1;
}
.monaco-editor .minimap.slider-mouseover .minimap-slider.active {
	opacity: 1;
}
/* END cover the case that slider is visible on mouseover */

.monaco-editor .minimap-shadow-hidden {
	position: absolute;
	width: 0;
}
.monaco-editor .minimap-shadow-visible {
	position: absolute;
	left: -6px;
	width: 6px;
}
.monaco-editor.no-minimap-shadow .minimap-shadow-visible {
	position: absolute;
	left: -1px;
	width: 1px;
}

/* 0.5s fade in/out for the minimap */
.minimap.autohide {
	opacity: 0.0;
	transition: opacity 0.5s;
}
.minimap.autohide:hover {
	opacity: 1.0;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/minimap/minimap.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F,6DAA6D;AAC7D;CACC,UAAU;CACV,gCAAgC;AACjC;AACA;CACC,UAAU;AACX;AACA;CACC,UAAU;AACX;AACA,2DAA2D;;AAE3D;CACC,kBAAkB;CAClB,QAAQ;AACT;AACA;CACC,kBAAkB;CAClB,UAAU;CACV,UAAU;AACX;AACA;CACC,kBAAkB;CAClB,UAAU;CACV,UAAU;AACX;;AAEA,qCAAqC;AACrC;CACC,YAAY;CACZ,wBAAwB;AACzB;AACA;CACC,YAAY;AACb","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/* START cover the case that slider is visible on mouseover */\n.monaco-editor .minimap.slider-mouseover .minimap-slider {\n\topacity: 0;\n\ttransition: opacity 100ms linear;\n}\n.monaco-editor .minimap.slider-mouseover:hover .minimap-slider {\n\topacity: 1;\n}\n.monaco-editor .minimap.slider-mouseover .minimap-slider.active {\n\topacity: 1;\n}\n/* END cover the case that slider is visible on mouseover */\n\n.monaco-editor .minimap-shadow-hidden {\n\tposition: absolute;\n\twidth: 0;\n}\n.monaco-editor .minimap-shadow-visible {\n\tposition: absolute;\n\tleft: -6px;\n\twidth: 6px;\n}\n.monaco-editor.no-minimap-shadow .minimap-shadow-visible {\n\tposition: absolute;\n\tleft: -1px;\n\twidth: 1px;\n}\n\n/* 0.5s fade in/out for the minimap */\n.minimap.autohide {\n\topacity: 0.0;\n\ttransition: opacity 0.5s;\n}\n.minimap.autohide:hover {\n\topacity: 1.0;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 87135:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   U: () => (/* binding */ deployCloudFunctionBuildScript)
/* harmony export */ });
/* harmony import */ var _noodl_platform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37218);
/* harmony import */ var _noodl_utils_compilation_build_context__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34120);
/* harmony import */ var _noodl_utils_exporter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(87144);



/**
 * Gives the path to the "external" folder.
 * @returns
 */
function getExternalFolderPath() {
    return _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.join(_noodl_platform__WEBPACK_IMPORTED_MODULE_0__.platform.getAppPath(), 'src/external');
}
/**
 * Loads the cloud runtime manifest file.
 * @returns
 */
function loadCloudRutimeManifest() {
    const indexPath = _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.join(getExternalFolderPath(), 'cloudruntime/manifest.json');
    return _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.readJson(indexPath);
}
const deployCloudFunctionBuildScript = {
    // Called Pre Build
    async onPreBuild(context) {
        // Extract all the __cloud__ components
        const components = context.project.getComponents().filter((x) => x.name.startsWith('/#__cloud__/'));
        if (components.length === 0) {
            return;
        }
        // Check if we are deploying with a cloud service
        const environment = context.environment;
        if (!environment) {
            context.notify(_noodl_utils_compilation_build_context__WEBPACK_IMPORTED_MODULE_1__/* .NotifyType */ .W.Error, 'No cloud service to deploy cloud functions to.');
            return;
        }
        await context.activity({
            message: `Deploying Cloud functions to ${environment.name}.`,
            successMessage: `Successfully deployed Cloud functions to ${environment.name}.`
        }, async () => {
            const exportedComponents = (0,_noodl_utils_exporter__WEBPACK_IMPORTED_MODULE_2__.exportComponentsToJSON)(context.project, components, {
                useBundles: false,
                environment: context.environment
            });
            // Delete some data we don't care about on the backend.
            if (exportedComponents.metadata) {
                delete exportedComponents.metadata.variants;
                delete exportedComponents.metadata.styles;
            }
            delete exportedComponents.componentIndex;
            const json = JSON.stringify(exportedComponents);
            // Deploy functions to the backend
            console.log('Deploying cloud functions to:' + environment.url);
            const manifest = await loadCloudRutimeManifest();
            console.log(' - Using cloud runtime version: ' + manifest.version);
            try {
                const response = await fetch(environment.url + '/functions-admin/deploy', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Parse-Application-Id': environment.appId,
                        'X-Parse-Master-Key': environment.masterKey
                    },
                    body: JSON.stringify({ deploy: json, runtime: manifest.version })
                });
                // NOTE: Expecting that we always get a JSON response
                const responseContent = await response.json();
                if (responseContent.status !== 'success') {
                    throw new Error('Error while deploying: ' + JSON.stringify(responseContent));
                }
                const version = responseContent.version;
                // NOTE: We cannot change "cloudservices" since that is updated exportToJSON
                context.project.metadata.cloudfunctions = {
                    version
                };
            }
            catch (e) {
                console.log('Error while deploying: ', e);
                throw e;
            }
        });
    }
};


/***/ }),

/***/ 87144:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  _calculateBundles: () => (/* reexport */ _calculateBundles),
  _collectDependencyGraph: () => (/* reexport */ _collectDependencyGraph),
  _flattenDependencyGraph: () => (/* reexport */ _flattenDependencyGraph),
  exportComponent: () => (/* reexport */ exportComponent),
  exportComponentBundle: () => (/* reexport */ exportComponentBundle),
  exportComponentsToJSON: () => (/* reexport */ exportComponentsToJSON),
  exportConnection: () => (/* reexport */ exportConnection),
  exportNode: () => (/* reexport */ exportNode),
  exportPorts: () => (/* reexport */ exportPorts),
  exportSettings: () => (/* reexport */ exportSettings),
  exportToJSON: () => (/* reexport */ exportToJSON),
  exportVariant: () => (/* reexport */ exportVariant),
  getComponentIndex: () => (/* reexport */ getComponentIndex),
  getFirstLevelDependencyMap: () => (/* reexport */ getFirstLevelDependencyMap),
  getNodesWithType: () => (/* reexport */ getNodesWithType),
  getRouterComponents: () => (/* reexport */ getRouterComponents),
  getRouterIndex: () => (/* reexport */ getRouterIndex),
  removeBundlesFromIndex: () => (/* reexport */ removeBundlesFromIndex)
});

// EXTERNAL MODULE: ./src/editor/src/models/componentmodel.ts
var componentmodel = __webpack_require__(16163);
// EXTERNAL MODULE: external "underscore"
var external_underscore_ = __webpack_require__(80002);
// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/index.ts
var nodelibrary = __webpack_require__(68091);
;// ./src/editor/src/utils/exporter/util.ts


function exportConnection(other) {
    return {
        sourceId: other.fromId,
        sourcePort: other.fromProperty,
        targetId: other.toId,
        targetPort: other.toProperty
    };
}
function exportPorts(node) {
    const exports = [];
    const ports = node.getPorts();
    for (const i in ports) {
        const p = ports[i];
        // Ignore ports with types that are not resolved
        if (nodelibrary/* NodeLibrary */.m.nameForPortType(p.type) === '=')
            continue;
        // Only instances ports are exported. Export the port if it is not a type port
        if (node.type.exportDynamicPorts &&
            !(0,external_underscore_.find)(node.type.ports, function (_p) {
                return _p.name === p.name;
            })) {
            exports.push(p);
        }
    }
    return exports;
}
function exportNode(node) {
    const json = {
        id: node.id,
        type: node.type.name,
        version: node.version,
        variant: node.variant ? node.variant.name : undefined,
        parameters: (0,external_underscore_.clone)(node.parameters),
        stateParameters: node.stateParameters ? (0,external_underscore_.clone)(node.stateParameters) : undefined,
        stateTransitions: node.stateTransitions ? (0,external_underscore_.clone)(node.stateTransitions) : undefined,
        defaultStateTransitions: node.defaultStateTransitions ? (0,external_underscore_.clone)(node.defaultStateTransitions) : undefined,
        ports: exportPorts(node),
        children: []
    };
    for (const i in node.children) {
        const child = node.children[i];
        json.children.push(exportNode(child));
    }
    return json;
}
function exportComponent(comp) {
    const json = { name: comp.name };
    json.nodes = [];
    json.connections = [];
    json.ports = [];
    json.roots = [];
    json.metadata = comp.metadata;
    // Export roots
    for (const i in comp.graph.roots) {
        const n = comp.graph.roots[i];
        json.nodes.push(exportNode(n));
        // Add nodes that may be children to the root array
        if (n.type.allowAsChild)
            json.roots.push(n.id);
    }
    // Export connections
    for (const i in comp.graph.connections) {
        const c = comp.graph.connections[i];
        const health = comp.graph.getConnectionHealth({
            sourceId: c.fromId,
            sourcePort: c.fromProperty,
            targetId: c.toId,
            targetPort: c.toProperty
        });
        if (health.healthy) {
            json.connections.push(exportConnection(c));
        }
    }
    // Export component ports
    const ports = comp.getPorts();
    for (const i in ports) {
        const p = ports[i];
        // Only export types that are resolved
        if (p.type)
            json.ports.push(p);
    }
    return json;
}
/** TODO: Where is this used? */
function getNodesWithType(type, allComponents) {
    const result = [];
    allComponents.forEach((c) => {
        c.forEachNode((n) => {
            if (n.type.name === type) {
                result.push(n);
            }
        });
    });
    return result;
}
function exportSettings(project) {
    const settings = project ? project.getSettings() : {};
    const result = {};
    const p = nodelibrary/* NodeLibrary */.m.instance.getProjectSettingsPorts();
    const settingsPorts = (p.ports || []).concat(p.dynamicports || []);
    for (const prop in settings) {
        const port = settingsPorts.find((p) => p.name === prop);
        if (!port || !port.ignoreInExport) {
            result[prop] = settings[prop];
        }
    }
    return result;
}
function exportVariant(variant) {
    return {
        name: variant.name,
        typename: variant.typename,
        parameters: variant.parameters,
        stateParameters: variant.stateParameters,
        stateTransitions: variant.stateTransitions,
        defaultStateTransitions: variant.defaultStateTransitions
    };
}

;// ./src/editor/src/utils/exporter/router.ts

function getRouterComponents(allComponents) {
    const routers = getNodesWithType('Router', allComponents);
    let pageComponents = [];
    for (const router of routers) {
        if (router.parameters.pages && router.parameters.pages.routes) {
            pageComponents = pageComponents.concat(router.parameters.pages.routes.map((componentName) => allComponents.find((c) => c.name === componentName)));
        }
    }
    return pageComponents.filter((c) => c !== undefined);
}
function _getPageInfo(allComponents) {
    const pages = getNodesWithType('Page', allComponents);
    const pageInfo = pages.map((page) => {
        const component = page.owner.owner;
        let title = page.parameters.title;
        if (title === undefined) {
            const titleParts = component.name.split('/');
            title = titleParts[titleParts.length - 1];
        }
        let urlPath = page.parameters['urlPath'] || title.replace(/\s+/g, '-').toLowerCase();
        // // Make sure all path parameters are in the path
        const pageInputs = component.getNodesWithType('PageInputs');
        const pathParams = [];
        pageInputs.forEach((pi) => {
            if (pi.parameters['pathParams'])
                pi.parameters['pathParams'].split(',').forEach((p) => pathParams.indexOf(p) === -1 && pathParams.push(p));
        });
        pathParams.forEach((p) => {
            if (urlPath.indexOf('{' + p + '}') === -1)
                urlPath = urlPath + '/{' + p + '}';
        });
        return {
            path: urlPath,
            title: title,
            component: component.name
        };
    });
    return pageInfo;
}
function getRouterIndex(allComponents) {
    //build an index with all routers and pages so the viewer know what components to load without
    //having load the entire graph at once
    const routers = getNodesWithType('Router', allComponents).filter((router) => router.parameters.name);
    const routerInfo = routers.map((router) => ({ ...router.parameters }));
    return {
        routers: routerInfo,
        pages: _getPageInfo(allComponents)
    };
}

;// ./src/editor/src/utils/exporter/bundler.ts



function getComponentStackComponents(allComponents) {
    const navigationStacks = getNodesWithType('Page Stack', allComponents);
    const pageComponents = navigationStacks.flatMap((stack) => {
        if (!stack.parameters.pages)
            return [];
        return stack.parameters.pages
            .map((page) => stack.parameters['pageComp-' + page.id])
            .map((componentName) => allComponents.find((c) => c.name === componentName));
    });
    return pageComponents.filter((c) => c !== undefined);
}
function getComponentIndex(rootComponent, allComponents) {
    const componentStackRoots = getComponentStackComponents(allComponents);
    const pages = getRouterComponents(allComponents);
    const roots = [rootComponent].concat(pages).concat(componentStackRoots);
    const bundles = _calculateBundles(roots, allComponents);
    const index = {};
    // Some components will not be reached by the dependency search:
    //   - dynamic for each nodes where the component name is generated in code
    //   - unused components
    // Add an extra bundle that contains all of them
    const discoveredComponents = bundles.map((b) => b.components).flat();
    if (discoveredComponents.length !== allComponents.length) {
        const remainingComponents = allComponents.map((c) => c.name).filter((c) => !discoveredComponents.includes(c));
        bundles.push({
            components: remainingComponents,
            dependencies: []
        });
    }
    //convert from bundles and dependencies from indices to names so it's easier to modify
    //without having to re-calculate all indices
    for (let i = 0; i < bundles.length; i++) {
        index['b' + i] = {
            components: bundles[i].components,
            dependencies: bundles[i].dependencies.map((d) => 'b' + d)
        };
    }
    return index;
}
function removeBundlesFromIndex(componentIndex, bundlesToRemove) {
    for (const name of bundlesToRemove) {
        delete componentIndex[name];
    }
    //and remove them as dependencies from other bundles
    for (const name of bundlesToRemove) {
        for (const bundle in componentIndex) {
            componentIndex[bundle].dependencies = componentIndex[bundle].dependencies.filter((d) => d !== name);
        }
    }
}
function _collectDependencyGraph(root, allComponents) {
    const graph = {};
    function collect(node) {
        node.comp.graph.forEachNode((n) => {
            //follow component instances and for each nodes
            let dep;
            if (n.type instanceof componentmodel/* ComponentModel */.j) {
                dep = n.type;
            }
            else if (n.type.name === 'For Each' && n.parameters.template && n.parameters.templateType !== 'dynamic') {
                dep = allComponents.find((c) => c.name === n.parameters.template);
            }
            else if (n.type.name === 'NavigationShowPopup' && n.parameters.target) {
                dep = allComponents.find((c) => c.name === n.parameters.target);
            }
            if (dep && !node.deps.find((d) => d.comp === dep)) {
                if (graph[dep.name]) {
                    node.deps.push(graph[dep.name]);
                }
                else {
                    graph[dep.name] = { comp: dep, deps: [] };
                    node.deps.push(graph[dep.name]);
                    collect(graph[dep.name]);
                }
            }
        });
    }
    const node = {
        comp: root,
        deps: []
    };
    collect(node);
    return node;
}
function _flattenDependencyGraph(root) {
    const components = new Set();
    function depthFirst(node) {
        if (!components.has(node.comp)) {
            components.add(node.comp);
            node.deps.forEach(depthFirst);
        }
    }
    depthFirst(root);
    return Array.from(components);
}
function getFirstLevelDependencyMap(rootGraphs) {
    const firstLevelDeps = new Map();
    function storeDeps(node) {
        if (firstLevelDeps.has(node.comp))
            return;
        firstLevelDeps.set(node.comp, node.deps);
        node.deps.forEach(storeDeps);
    }
    for (const graph of rootGraphs) {
        storeDeps(graph);
    }
    return firstLevelDeps;
}
function _calculateBundles(roots, allComponents) {
    //calculate a dependency graph for every root
    const rootGraphs = roots.map((root) => _collectDependencyGraph(root, allComponents));
    //flatten all the root graphs so we get one array per root
    //that has ALL dependencies at all levels in just a flat array
    const componentArrays = rootGraphs.map((graph) => _flattenDependencyGraph(graph));
    //Create a map, where every components is marked with what root it's used by
    // Example with 3 roots and 4 components
    // compA: [0,1] (compA is used by root 0 and 1)
    // compB: [0,1] (compB is used by root 0 and 1)
    // compC: [2] (compC is used by root 2)
    // compD: [0,1,2] (compD is used by all roots)
    const map = new Map();
    for (let i = 0; i < componentArrays.length; i++) {
        const components = componentArrays[i];
        for (const c of components) {
            if (!map.has(c)) {
                map.set(c, [i]);
            }
            else if (map.get(c).includes(i) === false) {
                map.get(c).push(i);
            }
        }
    }
    // Extract bundles from the set of root indices that each component use
    // "0,1": [compA, compB]
    // "2": [compC]
    // "0,1,2": [compD]
    const b = new Map();
    for (const [key, value] of map.entries()) {
        const flag = value.join(',');
        if (!b.has(flag))
            b.set(flag, new Set());
        b.get(flag).add(key);
    }
    // Now loose the key in the map from the previous step so we're just left with a
    // list of bundles
    // [ [compA, compB], [compC], [compD] ]
    const bundles = Array.from(b.values()).map((componentSet) => Array.from(componentSet));
    //now we have bundles with unique components in each. One bundle can depend on components
    //from another bundle, so let's calculate what those are so the viewer can prefetch
    //all bundles at once in parallel
    //this will create bundles like the following:
    // [
    //   {components: [compA, compB], dependencies: [2]}] //bundle 0
    //   {components: [compC], dependencies: [2]}] //bundle 1
    //   {components: [compD], dependencies: []}] //bundle 2
    //]
    //create a map that maps a components to a list of its direct dependencies (first level of dependencies)
    const firstLevelDependencies = getFirstLevelDependencyMap(rootGraphs);
    const bundlesWithDependencies = bundles.map((comps, i) => {
        //get one level of dependencies for all components in this bundle
        let oneLevelDeps = comps.flatMap((c) => firstLevelDependencies.get(c)).filter((x) => !!x);
        //feed components through a set set so we get rid of duplicates
        oneLevelDeps = Array.from(new Set(oneLevelDeps).values());
        //get indices for all bundles that the components belong to
        const bundleIndices = new Set(oneLevelDeps.map((node) => bundles.findIndex((b) => b.includes(node.comp))));
        //and we'll likely get components that belong to the current bundle, so remove it since it's not a dependency
        bundleIndices.delete(i);
        return {
            // @ts-expect-error
            components: comps.map((c) => c.name), //return the name, not the entire component
            dependencies: Array.from(bundleIndices.values())
        };
    });
    return bundlesWithDependencies;
}

// EXTERNAL MODULE: ./src/editor/src/utils/exporter/hash/xxhash64.ts + 1 modules
var xxhash64 = __webpack_require__(57603);
;// ./src/editor/src/utils/exporter/json.ts




function exportComponentsToJSON(projectModel, components, args) {
    var _a;
    if (!projectModel)
        throw new Error('projectModel is null');
    const json = {};
    // Find visual root and the component that contains it
    const root = projectModel.getRootNode();
    if (!root)
        return;
    const rootComponent = root.owner.owner;
    const project = rootComponent.owner;
    json.settings = exportSettings(project);
    json.components = components.map((component) => exportComponent(component));
    json.componentIndex = {};
    json.metadata = project ? project.metadata : undefined;
    // Take a copy of metadata so that it can be modified without affecting the original
    json.metadata = (project === null || project === void 0 ? void 0 : project.metadata) ? JSON.parse(JSON.stringify(project.metadata)) : {};
    // Override the cloud services metadata
    if ((args === null || args === void 0 ? void 0 : args.environment) === null) {
        json.metadata['cloudservices'] = {
            instanceId: undefined,
            endpoint: undefined,
            appId: undefined
        };
    }
    else if (args === null || args === void 0 ? void 0 : args.environment) {
        json.metadata['cloudservices'] = {
            instanceId: args.environment.id,
            endpoint: args.environment.url,
            appId: args.environment.appId,
            deployVersion: (_a = json.metadata['cloudfunctions']) === null || _a === void 0 ? void 0 : _a.version
        };
    }
    return json;
}
function exportToJSON(projectModel, args) {
    var _a;
    if (!projectModel)
        throw new Error('projectModel is null');
    const json = {};
    let allComponents = projectModel.getComponents();
    if (args === null || args === void 0 ? void 0 : args.ignoreComponentFilter) {
        allComponents = allComponents.filter(args.ignoreComponentFilter);
    }
    // Find visual root and the component that contains it
    const root = projectModel.getRootNode();
    if (!root)
        return;
    const rootComponent = root.owner.owner;
    if (!rootComponent || !allComponents.find((c) => c.name === rootComponent.name)) {
        //the root component is not part of the project (probably got deleted)
        return;
    }
    const project = rootComponent.owner;
    json.settings = exportSettings(project);
    if ((args === null || args === void 0 ? void 0 : args.useBundles) === false) {
        json.components = allComponents.map((component) => exportComponent(component));
        json.componentIndex = {};
    }
    else {
        const componentIndex = getComponentIndex(rootComponent, allComponents);
        // to reduce initial load time, remove the root bundle
        // and export it, with dependencies, directly into the JSON
        // note: the first bundle always contain the root component
        //name of root bundle and all bundle dependencies
        const rootBundleNames = ['b0', ...componentIndex.b0.dependencies];
        //get all those bundles and extract the components from each
        const rootComponents = rootBundleNames.map((name) => componentIndex[name].components).flat();
        //remove bundles from the index since they're now "burnt" into the export and will
        //always be present
        removeBundlesFromIndex(componentIndex, rootBundleNames);
        json.components = rootComponents.map((name) => exportComponent(allComponents.find((c) => c.name === name)));
        json.componentIndex = (args === null || args === void 0 ? void 0 : args.useBundleHashes)
            ? createIndexWithHashedNames(componentIndex, allComponents)
            : componentIndex;
    }
    json.routerIndex = getRouterIndex(allComponents);
    json.rootComponent = rootComponent.name;
    json.rootNode = root.id;
    json.metadata = project ? project.metadata : undefined;
    // Take a copy of metadata so that it can be modified without affecting the original
    json.metadata = (project === null || project === void 0 ? void 0 : project.metadata) ? JSON.parse(JSON.stringify(project.metadata)) : {};
    // Override the cloud services metadata
    if ((args === null || args === void 0 ? void 0 : args.environment) === null) {
        json.metadata['cloudservices'] = {
            instanceId: undefined,
            endpoint: undefined,
            appId: undefined
        };
    }
    else if (args === null || args === void 0 ? void 0 : args.environment) {
        json.metadata['cloudservices'] = {
            instanceId: args.environment.id,
            endpoint: args.environment.url,
            appId: args.environment.appId,
            deployVersion: (_a = json.metadata['cloudfunctions']) === null || _a === void 0 ? void 0 : _a.version
        };
    }
    json.variants = projectModel.variants.map((v) => exportVariant(v));
    return json;
}
function exportComponentBundle(project, id, componentIndex) {
    const allComponents = project.getComponents();
    return componentIndex[id].components.map((name) => exportComponent(allComponents.find((c) => c.name === name)));
}
//calculate new names for the bundles based on the contents of them so we get new file names everytime the contents change to avoid browser caching issues
function createIndexWithHashedNames(componentIndex, allComponents) {
    const oldToNewNames = new Map();
    const allComponentsExported = allComponents.map((component) => exportComponent(component));
    for (const name of Object.keys(componentIndex)) {
        const bundle = componentIndex[name];
        const components = bundle.components
            .map((componentName) => allComponentsExported.find((c) => c.name === componentName))
            .filter((c) => !!c);
        const hash = (0,xxhash64/* createHash */.n)();
        hash.update(JSON.stringify(components), 'utf8');
        const hex = hash.digest('hex');
        const newName = name + '-' + hex;
        oldToNewNames.set(name, newName);
    }
    const newComponentIndex = {};
    for (const name of Object.keys(componentIndex)) {
        const bundle = JSON.parse(JSON.stringify(componentIndex[name]));
        bundle.dependencies = bundle.dependencies.map((d) => oldToNewNames.get(d));
        newComponentIndex[oldToNewNames.get(name)] = bundle;
    }
    return newComponentIndex;
}

;// ./src/editor/src/utils/exporter/index.ts






/***/ }),

/***/ 87162:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ClippyLogo-module__Root--ad5cq{filter:brightness(150%);padding:6px;transition:filter var(--speed-quick) var(--easing-base);position:relative;display:inline-block}.ClippyLogo-module__Root--ad5cq.ClippyLogo-module____isDimmed--hqisX{filter:brightness(110%)}.ClippyLogo-module__HeroLogoWrapper--ucp_c{position:relative;overflow:hidden;background-color:inherit;opacity:1}.ClippyLogo-module__Root--ad5cq.ClippyLogo-module____isListening--YM8ZQ .ClippyLogo-module__HeroLogoWrapper--ucp_c{animation:ClippyLogo-module__breathe--ECYFR 3s var(--easing-base) infinite}.ClippyLogo-module__HeroLogoWrapper--ucp_c:after{content:"";position:absolute;top:-3px;left:-3px;right:-3px;bottom:-3px;background:linear-gradient(0deg, var(--base-color-teal-400) 0%, var(--base-color-node-purple-600)) 45%;animation:ClippyLogo-module__circle--I0xnZ 3s linear infinite;filter:saturate(120%) brightness(120%)}@keyframes ClippyLogo-module__breathe--ECYFR{0%,100%{filter:saturate(100%)}50%{filter:saturate(120%)}}@keyframes ClippyLogo-module__circle--I0xnZ{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}.ClippyLogo-module__HeroLogoWrapper--ucp_c>.ClippyLogo-module__LogoIdleCircle--FUbrf{box-shadow:0 0 10px 10px #fff}.ClippyLogo-module__HeroLogo--JRBef{width:30px;height:30px;display:flex;align-items:center;justify-content:center;opacity:1;position:relative;z-index:1;background:#000;mix-blend-mode:multiply}.ClippyLogo-module__HeroLogo--JRBef>span{color:#fff;text-transform:uppercase;font-size:15px;font-weight:var(--font-weight-semibold)}.ClippyLogo-module__LogoIdleCircleContainer--G1zLh{position:absolute;width:23px;height:23px;top:0;left:0;transform:scale(1);transition:transform var(--speed-quick) var(--easing-base)}.ClippyLogo-module__Root--ad5cq.ClippyLogo-module____isThinking--WPMnm .ClippyLogo-module__LogoIdleCircleContainer--G1zLh,.ClippyLogo-module__Root--ad5cq.ClippyLogo-module____isListening--YM8ZQ .ClippyLogo-module__LogoIdleCircleContainer--G1zLh{transform:scale(0)}.ClippyLogo-module__LogoIdleCircleInner--Z51Ja{position:absolute;top:0px;left:0px;width:23px;height:23px;animation:ClippyLogo-module__shine--tVlN6 5s var(--easing-base) infinite}.ClippyLogo-module__LogoIdleCircle--FUbrf{position:absolute;border:4px dotted #fff;width:22px;height:22px;border-radius:50%;animation:ClippyLogo-module__round--qwvzv 90s linear infinite reverse;opacity:.6}@keyframes ClippyLogo-module__shine--tVlN6{0%,50%{transform:scale(1);filter:blur(0px) brightness(100%)}25%{transform:scale(0.95);filter:blur(0.5px) brightness(200%) saturate(200%)}}.ClippyLogo-module__LogoListeningCircleContainer--2jR1K{position:absolute;width:23px;height:23px;top:1px;left:0;transform:scale(0);transition:transform var(--speed-quick) var(--easing-base)}.ClippyLogo-module__Root--ad5cq.ClippyLogo-module____isListening--YM8ZQ .ClippyLogo-module__LogoListeningCircleContainer--2jR1K{transform:scale(1)}.ClippyLogo-module__Root--ad5cq.ClippyLogo-module____isThinking--WPMnm .ClippyLogo-module__LogoListeningCircleContainer--2jR1K{transform:scale(0)}.ClippyLogo-module__LogoListeningCircleInner--iNTI3{position:absolute;top:-1px;left:0px;width:23px;height:23px;animation:ClippyLogo-module__listening-shine--aYoDN 3s var(--easing-base) infinite;perspective:70px}.ClippyLogo-module__LogoListeningCircle--xlzce{position:absolute;border:4px dotted #fff;width:22px;height:22px;border-radius:50%;animation:ClippyLogo-module__listening-round--_okN_ 15s linear infinite;opacity:.6}@keyframes ClippyLogo-module__listening-shine--aYoDN{0%,50%{transform:scale(1);filter:blur(0px) brightness(100%) saturate(100%)}25%{transform:scale(0.95);filter:blur(0.8px) brightness(200%) saturate(200%)}}@keyframes ClippyLogo-module__listening-round--_okN_{0%{transform:scale(0.95) rotateX(0deg) rotateY(-25deg) rotateZ(0deg)}20%{transform:scale(0.95) rotateX(-25deg) rotateY(25deg) rotateZ(72deg)}40%{transform:scale(0.95) rotateX(0deg) rotateY(0deg) rotateZ(144deg)}60%{transform:scale(0.95) rotateX(25deg) rotateY(25deg) rotateZ(216deg)}80%{transform:scale(0.95) rotateX(25deg) rotateY(0deg) rotateZ(288deg)}100%{transform:scale(0.95) rotateX(0deg) rotateY(-25deg) rotateZ(360deg)}}.ClippyLogo-module__LogoLoader--cF_5B{position:absolute;width:100%;height:100%;animation:ClippyLogo-module__round--qwvzv 40s linear infinite}.ClippyLogo-module__LogoLoaderInner--eK2Em{position:absolute;top:7px;left:7px;width:100%;height:100%;transform:scale(0);transition:transform var(--speed-quick) var(--easing-base)}.ClippyLogo-module__Root--ad5cq.ClippyLogo-module____isThinking--WPMnm .ClippyLogo-module__LogoLoaderInner--eK2Em{transform:scale(1)}.ClippyLogo-module__Circle1--w6nTd{position:absolute;transform:rotate(45deg)}.ClippyLogo-module__Circle2--IPbUI{position:absolute;transform:rotate(225deg)}.ClippyLogo-module__SpinningBalls--mBa8X{color:#fff;font-size:16px;text-indent:-9999em;overflow:hidden;width:1em;height:1em;border-radius:50%;position:relative;transform:translateZ(0);animation:ClippyLogo-module__mltShdSpin--tGzdC 3s infinite ease,ClippyLogo-module__round--qwvzv 3s infinite ease;display:block}@keyframes ClippyLogo-module__mltShdSpin--tGzdC{0%{box-shadow:0 -0.83em 0 -4em,0 -0.83em 0 -0.42em,0 -0.83em 0 -0.44em,0 -0.83em 0 -0.46em,0 -0.83em 0 -0.477em}5%,95%{box-shadow:0 -0.83em 0 -0.4em,0 -0.83em 0 -0.42em,0 -0.83em 0 -0.44em,0 -0.83em 0 -0.46em,0 -0.83em 0 -0.477em}10%,59%{box-shadow:0 -0.83em 0 -0.4em,-0.087em -0.825em 0 -0.42em,-0.173em -0.812em 0 -0.44em,-0.256em -0.789em 0 -0.46em,-0.297em -0.775em 0 -0.477em}20%{box-shadow:0 -0.83em 0 -0.4em,-0.338em -0.758em 0 -0.42em,-0.555em -0.617em 0 -0.44em,-0.671em -0.488em 0 -0.46em,-0.749em -0.34em 0 -0.477em}38%{box-shadow:0 -0.83em 0 -0.4em,-0.377em -0.74em 0 -0.42em,-0.645em -0.522em 0 -0.44em,-0.775em -0.297em 0 -0.46em,-0.82em -0.09em 0 -0.477em}100%{box-shadow:0 -0.83em 0 -0.4em,0 -0.83em 0 -0.42em,0 -0.83em 0 -0.44em,0 -0.83em 0 -0.46em,0 -0.83em 0 -0.477em}}@keyframes ClippyLogo-module__round-half--DY_pe{0%{transform:rotate(0deg)}50%,100%{transform:rotate(360deg)}}@keyframes ClippyLogo-module__round--qwvzv{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/Clippy/components/ClippyLogo/ClippyLogo.module.scss"],"names":[],"mappings":"AAAA,gCAGI,uBAAA,CACA,WAAA,CACA,uDAAA,CACA,iBAAA,CACA,oBAAA,CAEA,qEACI,uBAAA,CAIR,2CACI,iBAAA,CACA,eAAA,CACA,wBAAA,CACA,SAAA,CAEA,mHACI,0EAAA,CAGJ,iDACI,UAAA,CACA,iBAAA,CACA,QAAA,CACA,SAAA,CACA,UAAA,CACA,WAAA,CACA,sGAAA,CAGA,6DAAA,CACA,sCAAA,CAIR,6CACI,QACI,qBAAA,CAGJ,IACI,qBAAA,CAAA,CAIR,4CACI,KACI,sBAAA,CAGJ,GACI,wBAAA,CAAA,CAIR,qFACI,6BAAA,CAKJ,oCACI,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,SAAA,CACA,iBAAA,CACA,SAAA,CACA,eAAA,CACA,uBAAA,CAGA,yCACI,UAAA,CACA,wBAAA,CACA,cAAA,CACA,uCAAA,CAIR,mDACI,iBAAA,CACA,UAAA,CACA,WAAA,CACA,KAAA,CACA,MAAA,CACA,kBAAA,CACA,0DAAA,CAEA,qPAEI,kBAAA,CAIR,+CACI,iBAAA,CACA,OAAA,CACA,QAAA,CACA,UAAA,CACA,WAAA,CACA,wEAAA,CAIJ,0CACI,iBAAA,CACA,sBAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,qEAAA,CACA,UAAA,CAGJ,2CACI,OAEI,kBAAA,CACA,iCAAA,CAGJ,IACI,qBAAA,CACA,kDAAA,CAAA,CAIR,wDACI,iBAAA,CACA,UAAA,CACA,WAAA,CACA,OAAA,CACA,MAAA,CACA,kBAAA,CACA,0DAAA,CAEA,gIACI,kBAAA,CAGJ,+HACI,kBAAA,CAIR,oDACI,iBAAA,CACA,QAAA,CACA,QAAA,CACA,UAAA,CACA,WAAA,CACA,kFAAA,CACA,gBAAA,CAGJ,+CACI,iBAAA,CACA,sBAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,uEAAA,CACA,UAAA,CAGJ,qDAEI,OAEI,kBAAA,CACA,gDAAA,CAGJ,IACI,qBAAA,CACA,kDAAA,CAAA,CAKR,qDACI,GACI,iEAAA,CAGJ,IACI,mEAAA,CAGJ,IACI,iEAAA,CAGJ,IACI,mEAAA,CAGJ,IACI,kEAAA,CAGJ,KACI,mEAAA,CAAA,CAIR,sCACI,iBAAA,CACA,UAAA,CACA,WAAA,CACA,6DAAA,CAGJ,2CACI,iBAAA,CACA,OAAA,CACA,QAAA,CACA,UAAA,CACA,WAAA,CACA,kBAAA,CACA,0DAAA,CAEA,kHACI,kBAAA,CAIR,mCACI,iBAAA,CACA,uBAAA,CAGJ,mCACI,iBAAA,CACA,wBAAA,CAGJ,yCACI,UAAA,CACA,cAAA,CACA,mBAAA,CACA,eAAA,CACA,SAAA,CACA,UAAA,CACA,iBAAA,CACA,iBAAA,CACA,uBAAA,CACA,gHAAA,CACA,aAAA,CAOJ,gDACI,GACI,4GAAA,CAKJ,OAEI,8GAAA,CAKJ,QAEI,8IAAA,CAKJ,IACI,6IAAA,CAKJ,IACI,2IAAA,CAKJ,KACI,8GAAA,CAAA,CAKR,gDACI,GACI,sBAAA,CAGJ,SAEI,wBAAA,CAAA,CAIR,2CACI,GACI,sBAAA,CAGJ,KACI,wBAAA,CAAA","sourcesContent":[".Root {\n    // MIX BLEND MODE LIGTHEN MUST BE SET ON THE PARENT\n    //mix-blend-mode: lighten;\n    filter: brightness(150%);\n    padding: 6px;\n    transition: filter var(--speed-quick) var(--easing-base);\n    position: relative;\n    display: inline-block;\n\n    &.__isDimmed {\n        filter: brightness(110%);\n    }\n}\n\n.HeroLogoWrapper {\n    position: relative;\n    overflow: hidden;\n    background-color: inherit;\n    opacity: 1;\n\n    .Root.__isListening & {\n        animation: breathe 3s var(--easing-base) infinite;\n    }\n\n    &:after {\n        content: \"\";\n        position: absolute;\n        top: -3px;\n        left: -3px;\n        right: -3px;\n        bottom: -3px;\n        background: linear-gradient(0deg,\n                var(--base-color-teal-400) 0%,\n                var(--base-color-node-purple-600)) 45%;\n        animation: circle 3s linear infinite;\n        filter: saturate(120%) brightness(120%);\n    }\n}\n\n@keyframes breathe {\n    0%, 100% {\n        filter: saturate(100%);\n    }\n\n    50% {\n        filter: saturate(120%);\n    }\n}\n\n@keyframes circle {\n    from {\n        transform: rotate(0deg)\n    }\n\n    to {\n        transform: rotate(360deg)\n    }\n}\n\n.HeroLogoWrapper > .LogoIdleCircle {\n    box-shadow: 0 0 10px 10px white;\n}\n\n\n\n.HeroLogo {\n    width: 30px;\n    height: 30px;\n    display: flex;\n    align-items: center;\n    justify-content: center;\n    opacity: 1;\n    position: relative;\n    z-index: 1;\n    background: black;\n    mix-blend-mode: multiply;\n\n\n    >span {\n        color: #ffffff;\n        text-transform: uppercase;\n        font-size: 15px;\n        font-weight: var(--font-weight-semibold);\n    }\n}\n\n.LogoIdleCircleContainer {\n    position: absolute;\n    width: 23px;\n    height: 23px;\n    top: 0;\n    left: 0;\n    transform: scale(1);\n    transition: transform var(--speed-quick) var(--easing-base);\n\n    .Root.__isThinking &,\n    .Root.__isListening & {\n        transform: scale(0);\n    }\n}\n\n.LogoIdleCircleInner {\n    position: absolute;\n    top: 0px;\n    left: 0px;\n    width: 23px;\n    height: 23px;\n    animation: shine 5s var(--easing-base) infinite;\n}\n\n\n.LogoIdleCircle {\n    position: absolute;\n    border: 4px dotted white;\n    width: 22px;\n    height: 22px;\n    border-radius: 50%;\n    animation: round 90s linear infinite reverse;\n    opacity: 0.6;\n}\n\n@keyframes shine {\n    0%,\n    50% {\n        transform: scale(1);\n        filter: blur(0px) brightness(100%);\n    }\n\n    25% {\n        transform: scale(0.95);\n        filter: blur(0.5px) brightness(200%) saturate(200%);\n    }\n}\n\n.LogoListeningCircleContainer {\n    position: absolute;\n    width: 23px;\n    height: 23px;\n    top: 1px;\n    left: 0;\n    transform: scale(0);\n    transition: transform var(--speed-quick) var(--easing-base);\n\n    .Root.__isListening & {\n        transform: scale(1);\n    }\n\n    .Root.__isThinking & {\n        transform: scale(0);\n    }\n}\n\n.LogoListeningCircleInner {\n    position: absolute;\n    top: -1px;\n    left: 0px;\n    width: 23px;\n    height: 23px;\n    animation: listening-shine 3s var(--easing-base) infinite;\n    perspective: 70px;\n}\n\n.LogoListeningCircle {\n    position: absolute;\n    border: 4px dotted white;\n    width: 22px;\n    height: 22px;\n    border-radius: 50%;\n    animation: listening-round 15s linear infinite;\n    opacity: 0.6;\n}\n\n@keyframes listening-shine {\n\n    0%,\n    50% {\n        transform: scale(1);\n        filter: blur(0px) brightness(100%) saturate(100%);\n    }\n\n    25% {\n        transform: scale(0.95);\n        filter: blur(0.8px) brightness(200%) saturate(200%);\n    }\n}\n\n\n@keyframes listening-round {\n    0% {\n        transform: scale(0.95) rotateX(0deg) rotateY(-25deg) rotateZ(0deg);\n    }\n\n    20% {\n        transform: scale(0.95)  rotateX(-25deg) rotateY(25deg) rotateZ(72deg);\n    }\n\n    40% {\n        transform: scale(0.95)  rotateX(0deg) rotateY(0deg) rotateZ(144deg);\n    }\n\n    60% {\n        transform: scale(0.95)  rotateX(25deg) rotateY(25deg) rotateZ(216deg);\n    }\n\n    80% {\n        transform: scale(0.95)  rotateX(25deg) rotateY(0deg) rotateZ(288deg);\n    }\n\n    100% {\n        transform: scale(0.95)  rotateX(0deg) rotateY(-25deg) rotateZ(360deg);\n    }\n}\n\n.LogoLoader {\n    position: absolute;\n    width: 100%;\n    height: 100%;\n    animation: round 40s linear infinite;\n}\n\n.LogoLoaderInner {\n    position: absolute;\n    top: 7px;\n    left: 7px;\n    width: 100%;\n    height: 100%;\n    transform: scale(0);\n    transition: transform var(--speed-quick) var(--easing-base);\n\n    .Root.__isThinking & {\n        transform: scale(1);\n    }\n}\n\n.Circle1 {\n    position: absolute;\n    transform: rotate(45deg);\n}\n\n.Circle2 {\n    position: absolute;\n    transform: rotate(225deg);\n}\n\n.SpinningBalls {\n    color: #ffffff;\n    font-size: 16px;\n    text-indent: -9999em;\n    overflow: hidden;\n    width: 1em;\n    height: 1em;\n    border-radius: 50%;\n    position: relative;\n    transform: translateZ(0);\n    animation: mltShdSpin 3s infinite ease, round 3s infinite ease;\n    display: block;\n}\n\n$_val1: calc(-0.83em * 1);\n$_ballSizeMod: 10;\n\n\n@keyframes mltShdSpin {\n    0% {\n        box-shadow: 0 $_val1 0 calc(-0.4em * $_ballSizeMod),\n            0 $_val1 0 -0.42em, 0 $_val1 0 -0.44em,\n            0 $_val1 0 -0.46em, 0 $_val1 0 -0.477em;\n    }\n\n    5%,\n    95% {\n        box-shadow: 0 $_val1 0 calc(-0.4em),\n            0 $_val1 0 -0.42em, 0 $_val1 0 -0.44em,\n            0 $_val1 0 -0.46em, 0 $_val1 0 -0.477em;\n    }\n\n    10%,\n    59% {\n        box-shadow: 0 $_val1 0 calc(-0.4em),\n            -0.087em -0.825em 0 -0.42em, -0.173em -0.812em 0 -0.44em,\n            -0.256em -0.789em 0 -0.46em, -0.297em -0.775em 0 -0.477em;\n    }\n\n    20% {\n        box-shadow: 0 $_val1 0 calc(-0.4em), -0.338em -0.758em 0 -0.42em,\n            -0.555em -0.617em 0 -0.44em, -0.671em -0.488em 0 -0.46em,\n            -0.749em -0.34em 0 -0.477em;\n    }\n\n    38% {\n        box-shadow: 0 $_val1 0 calc(-0.4em), -0.377em -0.74em 0 -0.42em,\n            -0.645em -0.522em 0 -0.44em, -0.775em -0.297em 0 -0.46em,\n            -0.82em -0.09em 0 -0.477em;\n    }\n\n    100% {\n        box-shadow: 0 $_val1 0 calc(-0.4em), 0 $_val1 0 -0.42em,\n            0 $_val1 0 -0.44em, 0 $_val1 0 -0.46em, 0 $_val1 0 -0.477em;\n    }\n}\n\n@keyframes round-half {\n    0% {\n        transform: rotate(0deg)\n    }\n\n    50%,\n    100% {\n        transform: rotate(360deg)\n    }\n}\n\n@keyframes round {\n    0% {\n        transform: rotate(0deg)\n    }\n\n    100% {\n        transform: rotate(360deg)\n    }\n}\n\n// @keyframes mltShdSpin {\n//     0% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em * $_ballSizeMod),\n//             0 $_val1 0 -0.42em, 0 $_val1 0 -0.44em,\n//             0 $_val1 0 -0.46em, 0 $_val1 0 -0.477em;\n//     }\n\n//     2.5%,\n//     47.5% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em),\n//             0 $_val1 0 -0.42em, 0 $_val1 0 -0.44em,\n//             0 $_val1 0 -0.46em, 0 $_val1 0 -0.477em;\n//     }\n\n//     5%,\n//     29.5% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em),\n//             -0.087em -0.825em 0 -0.42em, -0.173em -0.812em 0 -0.44em,\n//             -0.256em -0.789em 0 -0.46em, -0.297em -0.775em 0 -0.477em;\n//     }\n\n//     10% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em), -0.338em -0.758em 0 -0.42em,\n//             -0.555em -0.617em 0 -0.44em, -0.671em -0.488em 0 -0.46em,\n//             -0.749em -0.34em 0 -0.477em;\n//     }\n\n//     19% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em), -0.377em -0.74em 0 -0.42em,\n//             -0.645em -0.522em 0 -0.44em, -0.775em -0.297em 0 -0.46em,\n//             -0.82em -0.09em 0 -0.477em;\n//     }\n\n//     50%, 100% {\n//         box-shadow: 0 $_val1 0 calc(-0.4em), 0 $_val1 0 -0.42em,\n//             0 $_val1 0 -0.44em, 0 $_val1 0 -0.46em, 0 $_val1 0 -0.477em;\n//     }\n// }\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ClippyLogo-module__Root--ad5cq`,
	"__isDimmed": `ClippyLogo-module____isDimmed--hqisX`,
	"HeroLogoWrapper": `ClippyLogo-module__HeroLogoWrapper--ucp_c`,
	"__isListening": `ClippyLogo-module____isListening--YM8ZQ`,
	"breathe": `ClippyLogo-module__breathe--ECYFR`,
	"circle": `ClippyLogo-module__circle--I0xnZ`,
	"LogoIdleCircle": `ClippyLogo-module__LogoIdleCircle--FUbrf`,
	"HeroLogo": `ClippyLogo-module__HeroLogo--JRBef`,
	"LogoIdleCircleContainer": `ClippyLogo-module__LogoIdleCircleContainer--G1zLh`,
	"__isThinking": `ClippyLogo-module____isThinking--WPMnm`,
	"LogoIdleCircleInner": `ClippyLogo-module__LogoIdleCircleInner--Z51Ja`,
	"shine": `ClippyLogo-module__shine--tVlN6`,
	"round": `ClippyLogo-module__round--qwvzv`,
	"LogoListeningCircleContainer": `ClippyLogo-module__LogoListeningCircleContainer--2jR1K`,
	"LogoListeningCircleInner": `ClippyLogo-module__LogoListeningCircleInner--iNTI3`,
	"listening-shine": `ClippyLogo-module__listening-shine--aYoDN`,
	"LogoListeningCircle": `ClippyLogo-module__LogoListeningCircle--xlzce`,
	"listening-round": `ClippyLogo-module__listening-round--_okN_`,
	"LogoLoader": `ClippyLogo-module__LogoLoader--cF_5B`,
	"LogoLoaderInner": `ClippyLogo-module__LogoLoaderInner--eK2Em`,
	"Circle1": `ClippyLogo-module__Circle1--w6nTd`,
	"Circle2": `ClippyLogo-module__Circle2--IPbUI`,
	"SpinningBalls": `ClippyLogo-module__SpinningBalls--mBa8X`,
	"mltShdSpin": `ClippyLogo-module__mltShdSpin--tGzdC`,
	"round-half": `ClippyLogo-module__round-half--DY_pe`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 87329:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   H: () => (/* binding */ SitemapBuildScript)
/* harmony export */ });
/* harmony import */ var _noodl_platform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37218);
/* harmony import */ var _noodl_utils_compilation_build_context__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34120);


function generateSitemapXml(urls) {
    let xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset
  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" 
  xmlns:xhtml="http://www.w3.org/1999/xhtml"
  xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" 
  xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"
>\n`;
    xml += urls
        .map((item) => {
        let entry = `  <url>\n`;
        Object.keys(item).forEach((key) => {
            entry += `    <${key}>${item[key]}</${key}>\n`;
        });
        return entry + `  </url>\n`;
    })
        .join('');
    return xml + `</urlset>`;
}
function encodeXml(value) {
    return value.replace(/[<>&'"]/g, function (match) {
        switch (match) {
            case '<':
                return '&lt;';
            case '>':
                return '&gt;';
            case '&':
                return '&amp;';
            case "'":
                return '&apos;';
            case '"':
                return '&quot;';
        }
    });
}
const SitemapBuildScript = {
    async onPostBuild(context) {
        const enabled = !!context.project.settings['sitemap.enabled'];
        if (!enabled) {
            return;
        }
        const baseUrl = context.getHostname() || '/';
        // ---
        // Create the metadata required to know about all the pages.
        const pages = await context.getPages({});
        const metadata = {
            __comment: 'This is required for SSR to quickly understand what pages exist.',
            pages
        };
        await _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.writeJson(context.outputPath + '/.sitemap.metadata.json', metadata);
        // ---
        // Build the sitemap
        const urls = [];
        for (const page of pages) {
            const component = context.project.getComponentWithName(page.componentName);
            const pageNode = component.graph.roots.find((x) => x.typename === 'Page');
            // ---
            // Push the page
            if (pageNode.parameters.sitemapIncluded === undefined || pageNode.parameters.sitemapIncluded === true) {
                const loc = encodeXml(page.path);
                urls.push({
                    loc: baseUrl + loc,
                    changefreq: pageNode.parameters.sitemapChangefreq || 'weekly',
                    priority: pageNode.parameters.sitemapPriority || 0.5
                });
            }
            // ---
            // Push the dynamic pages
            const codeText = pageNode.parameters.sitemapScript;
            if (!codeText) {
                continue;
            }
            try {
                const func = new Function(codeText);
                // TODO: Make this parallel later
                // TODO: Noodl API?
                // TODO: Verify the result?
                const newUrls = await func.apply(null);
                if (!Array.isArray(newUrls)) {
                    continue;
                }
                newUrls.forEach((x) => {
                    let loc = encodeXml(x.loc);
                    if (!loc.startsWith('http') && !loc.startsWith('/')) {
                        loc = '/' + loc;
                    }
                    if (!loc.startsWith('http')) {
                        loc = baseUrl + loc;
                    }
                    urls.push({
                        loc,
                        changefreq: x.changefreq || 'weekly',
                        priority: x.priority || 0.5
                    });
                });
            }
            catch (error) {
                console.error(error);
                context.notify(_noodl_utils_compilation_build_context__WEBPACK_IMPORTED_MODULE_1__/* .NotifyType */ .W.Error, `Sitemap failed on '${component.name}' component with:` + error);
            }
        }
        const sitemap = generateSitemapXml(urls);
        await _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.writeFile(context.outputPath + '/sitemap.xml', sitemap);
    }
};


/***/ }),

/***/ 87354:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .lines-content .core-guide {
	position: absolute;
	box-sizing: border-box;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/viewParts/indentGuides/indentGuides.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kBAAkB;CAClB,sBAAsB;AACvB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .lines-content .core-guide {\n\tposition: absolute;\n\tbox-sizing: border-box;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 87438:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgAlignItemCenter = function SvgAlignItemCenter(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.457 7.92615H8.26953C7.90709 7.92615 7.61328 8.18198 7.61328 8.49758V11.3547C7.61328 11.6703 7.90709 11.9261 8.26953 11.9261H17.457C17.8195 11.9261 18.1133 11.6703 18.1133 11.3547V8.49758C18.1133 8.18198 17.8195 7.92615 17.457 7.92615Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M16.8008 13.4261H8.92578C8.61512 13.4261 8.36328 13.682 8.36328 13.9976V16.8547C8.36328 17.1703 8.61512 17.4261 8.92578 17.4261H16.8008C17.1114 17.4261 17.3633 17.1703 17.3633 16.8547V13.9976C17.3633 13.682 17.1114 13.4261 16.8008 13.4261Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.8633 3.67615C13.2775 3.67615 13.6133 4.03433 13.6133 4.47617L13.6133 20.8761C13.6133 21.318 13.2775 21.6761 12.8633 21.6761C12.4491 21.6761 12.1133 21.318 12.1133 20.8761L12.1133 4.47617C12.1133 4.03433 12.4491 3.67615 12.8633 3.67615Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgAlignItemCenter);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "73c04bf0bf34c1ede66a2d8d527b9214.svg");

/***/ }),

/***/ 87827:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ImportFromProject-module__Grid--AFLeB{padding:0;margin:0;list-style:none;border:none;border-radius:0}.ImportFromProject-module__Grid--AFLeB{display:flex;flex-wrap:wrap;margin-left:-16px;margin-top:-16px}.ImportFromProject-module__Grid--AFLeB>*{margin-left:16px;width:calc(33.3333333333% - 16px);margin-top:16px}.ImportFromProject-module__Grid--AFLeB{align-items:stretch;padding:5px 10px 16px 15px}`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/placeholders/util.scss","webpack://./src/editor/src/views/NodePicker/tabs/ImportFromProject/ImportFromProject.module.scss","webpack://./src/editor/src/styles/mixins/layout.scss"],"names":[],"mappings":"AAQA,uCACE,SAAA,CACA,QAAA,CACA,eAAA,CACA,WAAA,CACA,eAAA,CCVF,uCCwDE,YAAA,CACA,cAAA,CAGE,iBAAA,CAIA,gBAAA,CAtCA,yCAuDA,gBARkB,CASlB,iCAAA,CAMA,eAdgB,CD1EpB,uCAGE,mBAAA,CACA,0BAAA","sourcesContent":["%overlay {\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  right: 0;\n  left: 0;\n}\n\n%reset-styles {\n  padding: 0;\n  margin: 0;\n  list-style: none;\n  border: none;\n  border-radius: 0;\n}\n","@use '@scss-mixins/layout' as *;\n@use '@scss-placeholders/util' as *;\n\n.Grid {\n  @extend %reset-styles;\n  @include flex-layout(3);\n  align-items: stretch;\n  padding: 5px 10px 16px 15px;\n}\n","@function _format-gutters($value, $direction) {\n  $vertical-gutter: false;\n  $horizontal-gutter: false;\n\n  @if (type-of($value) == list) {\n    @if (nth($value, 1)) {\n      $vertical-gutter: (nth($value, 1));\n    }\n    @if (nth($value, 2)) {\n      $horizontal-gutter: (nth($value, 2));\n    }\n  } @else {\n    $vertical-gutter: $value;\n    $horizontal-gutter: $value;\n  }\n\n  @if ($direction == vertical) {\n    @return $vertical-gutter;\n  } @else {\n    @return $horizontal-gutter;\n  }\n}\n\n@mixin flex-layout($columns: false, $gutters: 16px) {\n  $items: length($columns);\n\n  @if (type-of($columns) == number) {\n    @include flex-row($gutters);\n\n    > * {\n      @include flex-column(calc(1 / $columns), $gutters);\n    }\n  } @else if (type-of($columns) == list and $items > 1) {\n    $column-count: 0;\n\n    @each $column in $columns {\n      $column-count: $column-count + $column;\n    }\n\n    @include flex-row($gutters);\n\n    @for $item from 1 through $items {\n      $width: nth($columns, $item) / $column-count;\n\n      & > *:nth-child(#{$items}n + #{$item}) {\n        @include flex-column($width, $gutters);\n      }\n    }\n  }\n}\n\n/**\n * flex-row()\n */\n\n@mixin flex-row($gutters) {\n  $horizontal-gutter: _format-gutters($gutters, horizontal);\n  $vertical-gutter: _format-gutters($gutters, vertical);\n\n  display: flex;\n  flex-wrap: wrap;\n\n  @if ($horizontal-gutter and $horizontal-gutter != 0) {\n    margin-left: -($horizontal-gutter);\n  }\n\n  @if ($vertical-gutter and $vertical-gutter != 0) {\n    margin-top: -($vertical-gutter);\n  }\n}\n\n/**\n * flex-column()\n */\n\n@mixin flex-column($width, $gutters) {\n  $horizontal-gutter: _format-gutters($gutters, horizontal);\n  $vertical-gutter: _format-gutters($gutters, vertical);\n\n  @if (type-of($width) == number and unitless($width)) {\n    $width: percentage($width);\n  }\n\n  @if ($horizontal-gutter and $horizontal-gutter != 0) {\n    margin-left: $horizontal-gutter;\n    width: calc(#{$width} - #{$horizontal-gutter});\n  } @else {\n    width: $width;\n  }\n\n  @if ($vertical-gutter and $vertical-gutter != 0) {\n    margin-top: $vertical-gutter;\n  }\n}\n\n@function _get-pseudo($pseudo) {\n  @if ($pseudo == false) {\n    $pseudo: '&::after';\n  } @else if (_contains(('after', ':after', '::after', '&:after', '&::after'), $pseudo)) {\n    $pseudo: '&::after';\n  } @else if (_contains(('before', ':before', '::before', '&:before', '&::before'), $pseudo)) {\n    $pseudo: '&::before';\n  }\n\n  @return $pseudo;\n}\n\n@function _is-pseudo($pseudo) {\n  @return ($pseudo == '&::after' or $pseudo == '&::before');\n}\n\n@function _contains($list, $item) {\n  @return index($list, $item) != null;\n}\n\n/**\n * aspect-ratio()\n *\n * Give a heightless element a height based on its width.\n * Always follows the set width:height ratio.\n *\n * @param {number} $width - Without CSS unit\n * @param {number} $height - Without CSS unit\n * @param {string} $pseudo - Optional selector to use insted of default pseudo-element\n */\n\n@mixin aspect-ratio($width, $height, $pseudo: false) {\n  $pseudo: _get-pseudo($pseudo);\n\n  #{$pseudo} {\n    @if (_is-pseudo($pseudo)) {\n      content: '';\n    }\n    display: block;\n    height: 0;\n    padding-bottom: calc((100% / $width) * $height);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Grid": `ImportFromProject-module__Grid--AFLeB`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 87844:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  W2: () => (/* reexport */ NodeGraphModel),
  dF: () => (/* reexport */ NodeGraphNode),
  bn: () => (/* reexport */ NodeGraphNodeSet)
});

// EXTERNAL MODULE: external "underscore"
var external_underscore_ = __webpack_require__(80002);
// EXTERNAL MODULE: ./src/editor/src/models/undo-queue-model.ts
var undo_queue_model = __webpack_require__(50867);
// EXTERNAL MODULE: ./src/shared/model.js
var model = __webpack_require__(47821);
var model_default = /*#__PURE__*/__webpack_require__.n(model);
// EXTERNAL MODULE: ./src/editor/src/utils/utils.ts
var utils = __webpack_require__(93015);
;// ./src/editor/src/models/commentsmodel.ts




class CommentsModel extends (model_default()) {
    constructor(args) {
        super();
        this.comments = args.comments || [];
    }
    addComment(comment, args) {
        if (!comment.id) {
            comment.id = (0,utils.guid)();
        }
        this.comments.push(comment);
        this.notifyListeners('commentsChanged');
        this.notifyListeners('commentAdded', { comment, args });
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: args.label,
                do: () => {
                    this.addComment(comment);
                },
                undo: () => {
                    this.removeComment(comment.id);
                }
            });
        }
    }
    removeComment(commentId, args) {
        const index = this.comments.findIndex((c) => c.id === commentId);
        if (index === -1) {
            console.log('CommentsModel::delete', 'comment with id', commentId, "doesn't exist");
            return;
        }
        const removedComment = this.comments[index];
        this.comments.splice(index, 1);
        this.notifyListeners('commentsChanged');
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: args.label,
                do: () => {
                    this.removeComment(commentId);
                },
                undo: () => {
                    this.addComment(removedComment);
                }
            });
        }
    }
    setComment(commentId, commentData, args) {
        const index = this.comments.findIndex((c) => c.id === commentId);
        if (index === -1) {
            console.log('CommentsModel::setComment', 'comment with id', commentId, "doesn't exist");
            return;
        }
        const oldComment = { ...this.comments[index] };
        const comment = { ...commentData };
        //save some disk space by rounding these looong numbers
        comment.x = Math.round(comment.x);
        comment.y = Math.round(comment.y);
        if ((0,external_underscore_.isEqual)(oldComment, comment)) {
            //there was no change, just return
            return;
        }
        this.comments[index] = comment;
        this.notifyListeners('commentsChanged');
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: args.label,
                do: () => {
                    this.setComment(commentId, comment);
                },
                undo: () => {
                    this.setComment(commentId, oldComment);
                }
            });
        }
    }
    getComments() {
        //return a copy so caller is free to modify their array
        return [...this.comments];
    }
    dispose() {
        // noop
    }
}

// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/index.ts
var nodelibrary = __webpack_require__(68091);
// EXTERNAL MODULE: ./src/editor/src/models/warningsmodel.ts
var warningsmodel = __webpack_require__(86105);
// EXTERNAL MODULE: ./src/shared/utils/EventDispatcher.ts
var EventDispatcher = __webpack_require__(11138);
;// ./src/editor/src/models/nodegraphmodel/NodeGraphModel.ts









class NodeGraphModel extends (model_default()) {
    constructor(args) {
        super();
        this.roots = [];
        this.connections = [];
        this.commentsModel = new CommentsModel({ comments: args ? args.comments : [] });
        //keep track of all nodes in a an id=>model map for better findNodeWithId() performance
        this.nodeMap = new Map();
        this.bindModels();
    }
    static fromJSON(json) {
        const _this = new NodeGraphModel({ comments: json.comments });
        for (const i in json.roots) {
            _this.addRoot(NodeGraphNode.fromJSON(json.roots[i]));
        }
        for (const i in json.connections) {
            _this.addConnection(json.connections[i]);
        }
        return _this;
    }
    dispose() {
        var _a;
        EventDispatcher.EventDispatcher.instance.off(this);
        nodelibrary/* NodeLibrary */.m.instance.off(this);
        (_a = this.typeModel) === null || _a === void 0 ? void 0 : _a.off(this);
        this.removeAllListeners();
    }
    scheduleUpdateTypes() {
        if (this.updateTypesScheduled) {
            return;
        }
        this.updateTypesScheduled = true;
        setTimeout(() => {
            this.updateTypesScheduled = false;
            this.updateTypes();
        }, 1);
    }
    bindModels() {
        // Whenever the node library is modified such that types may be added or removed
        // reset the types of all nodes so that they are re evaluated
        nodelibrary/* NodeLibrary */.m.instance.on(['typeAdded', 'typeRemoved', 'typeRenamed'], () => this.scheduleUpdateTypes(), this);
        // Globally if a connection is added or removed this can effect inferred port types etc
        // so update types globally
        EventDispatcher.EventDispatcher.instance.on([
            'Model.connectionAdded',
            'Model.connectionRemoved',
            'Model.portRenamed',
            'Model.parametersChanged',
            'Model.portAdded',
            'Model.portRemoved',
            'Model.instancePortsChanged',
            'Model.portRearranged'
        ], () => this.scheduleUpdateTypes(), this);
        // When a type is renamed, check for port references to that type and update
        nodelibrary/* NodeLibrary */.m.instance.on(['typeRenamed'], (args) => {
            this.forEachNode(function (n) {
                (0,external_underscore_.each)(n.getPorts(), function (p) {
                    // If the node has a reference to that type, update the name
                    if (nodelibrary/* NodeLibrary */.m.nameForPortType(p.type) === 'component' && n.parameters[p.name] === args.oldName) {
                        n.parameters[p.name] = args.model.name;
                    }
                });
            });
            this.scheduleEvaluateHealth();
        }, this);
        // Must evaluate healths if a new module is registered
        nodelibrary/* NodeLibrary */.m.instance.on(['moduleRegistered', 'moduleUnregistered', 'libraryUpdated'], () => this.scheduleUpdateTypes(), this);
        // Must update variant
        nodelibrary/* NodeLibrary */.m.instance.on(['Model.variantAdded', 'Model.variantDeleted', 'Model.variantRenamed'], () => this.updateVariantRefs(), this);
    }
    updateTypes() {
        if (this.owner && this.owner.owner && !nodelibrary/* NodeLibrary */.m.instance.isModuleRegistered(this.owner.owner))
            return; // No need to evaluate if we are not part of a registered module
        this.forEachNode(function (n) {
            n.updateType();
        });
        this.scheduleEvaluateHealth();
    }
    updateVariantRefs() {
        if (this.owner && this.owner.owner && !nodelibrary/* NodeLibrary */.m.instance.isModuleRegistered(this.owner.owner))
            return; // No need to evaluate if we are not part of a registered module
        this.forEachNode(function (n) {
            n.updateVariantRef();
        });
        this.scheduleEvaluateHealth();
    }
    // When a node instances of a ceratain type is used the type
    // is bound, if port names are changed both connections and
    // parameters must be updated
    bindTypeModel(type) {
        const _this = this;
        if (this.typeModel) {
            this.typeModel.off(this);
            this.typeModel = null;
        }
        if (!type)
            return;
        this.typeModel = type;
        this.typeModel.on('portRenamed', function (args) {
            // Rename all parameters for all nodes referencing
            // the component
            const oldName = args.oldName;
            const newName = args.port.name;
            const type = args.model;
            _this.forEachNode(function (n) {
                if (n.type === type) {
                    n.parameters[newName] = n.parameters[oldName];
                    delete n.parameters[oldName];
                }
            });
            // Loop over all connections in graph
            for (const j in _this.connections) {
                const c = _this.connections[j];
                // This connection is connected to a property of the
                // name that is being changed
                if (c.fromProperty === args.oldName) {
                    const fromNode = _this.findNodeWithId(c.fromId);
                    if (fromNode.type === type)
                        c.fromProperty = args.port.name;
                }
                if (c.toProperty === args.oldName) {
                    const toNode = _this.findNodeWithId(c.toId);
                    if (toNode.type === type)
                        c.toProperty = args.port.name;
                }
            }
        }, this);
    }
    rekeyAllIds() {
        const map = {};
        this.nodeMap.clear();
        const rekeyNodes = (nodes) => {
            nodes !== undefined &&
                nodes.forEach((n) => {
                    const newId = (0,utils.guid)();
                    map[n.id] = newId;
                    n.id = newId;
                    this.nodeMap.set(n.id, n);
                    rekeyNodes(n.children);
                });
        };
        rekeyNodes(this.roots);
        this.connections.forEach((con) => {
            con.fromId = map[con.fromId];
            con.toId = map[con.toId];
        });
    }
    rerouteComponentRefs(oldPathPrefix, newPathPrefix) {
        this.forEachNode((n) => {
            n.getPorts().forEach((p) => {
                if (nodelibrary/* NodeLibrary */.m.nameForPortType(p.type) === 'component' && n.parameters[p.name].startsWith(oldPathPrefix)) {
                    const oldPath = n.parameters[p.name];
                    n.parameters[p.name] = newPathPrefix + oldPath.substring(oldPathPrefix.length);
                }
            });
        });
    }
    getRoots() {
        return this.roots;
    }
    addRoot(model, args) {
        const _this = this;
        // Make sure the graph listens to type changes for all types in the sub tree that is added
        model.forEach((m) => {
            this.bindTypeModel(m.type);
            m.owner = this;
            this.nodeMap.set(m.id, m);
        });
        this.roots.push(model);
        this.nodeMap.set(model.id, model);
        this.notifyListeners('nodeAdded', { model: model, disableSelect: args === null || args === void 0 ? void 0 : args.disableSelect });
        // Support for undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: args.label,
                do: function () {
                    _this.addRoot(model);
                },
                undo: function () {
                    _this.removeNode(model);
                }
            });
        }
    }
    removeNode(model, args) {
        const _this = this;
        // Start by removing all connections to/from this node
        this.removeConnectionsForNode(model, args);
        // When the node is free, remove the node
        const parent = model.parent;
        const index = parent ? parent.children.indexOf(model) : 0;
        if (model.parent) {
            const idx = model.parent.children.indexOf(model);
            if (idx !== -1) {
                model.parent.children.splice(idx, 1);
                model.parent = undefined;
                this.nodeMap.delete(model.id);
                model.forEach((child) => {
                    this.nodeMap.delete(child.id);
                });
                this.notifyListeners('nodeRemoved', { model: model });
            }
        }
        else {
            const idx = this.roots.indexOf(model);
            if (idx !== -1) {
                this.roots.splice(idx, 1);
                this.nodeMap.delete(model.id);
                model.forEach((child) => {
                    this.nodeMap.delete(child.id);
                });
                this.notifyListeners('nodeRemoved', { model: model });
            }
        }
        this.owner && warningsmodel/* WarningsModel */.l.instance.clearWarningsForRef({ component: this.owner, node: model });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: args.label,
                do: function () {
                    _this.removeNode(model);
                },
                undo: function () {
                    if (parent)
                        parent.insertChild(model, index);
                    else
                        _this.addRoot(model);
                }
            });
        }
    }
    removeAllNodes(args) {
        while (this.roots.length > 0) {
            this.removeNode(this.roots[0], args);
        }
    }
    removeConnectionsForNode(model, args) {
        // Remove all connections to and from this node
        for (let i = 0; i < this.connections.length; i++) {
            const con = this.connections[i];
            if (con.fromId === model.id || con.toId === model.id) {
                this.removeConnection(con, args);
                i--;
            }
        }
        // Recurse to children
        for (const i in model.children) {
            this.removeConnectionsForNode(model.children[i], args);
        }
    }
    addConnection(model, args) {
        const _this = this;
        this.connections.push(model);
        this.notifyListeners('connectionAdded', { model: model });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: args.label,
                do: function () {
                    _this.addConnection(model);
                },
                undo: function () {
                    _this.removeConnection(model);
                }
            });
        }
    }
    removeConnection(model, args) {
        const _this = this;
        const idx = this.connections.indexOf(model);
        if (idx !== -1) {
            this.connections.splice(idx, 1);
            this.notifyListeners('connectionRemoved', { model: model });
            this.owner && warningsmodel/* WarningsModel */.l.instance.clearWarningsForRef({ component: this.owner, connection: model });
            // Undo
            if (args && args.undo) {
                const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
                undo.push({
                    label: args.label,
                    do: function () {
                        _this.removeConnection(model);
                    },
                    undo: function () {
                        _this.addConnection(model);
                    }
                });
            }
        }
    }
    getConnectionStatus(args) {
        const _this = this;
        const targetNode = args.targetNode;
        const targetPort = targetNode.getPort(args.targetPort);
        const sourceNode = args.sourceNode;
        const sourcePort = sourceNode.getPort(args.sourcePort);
        // Make sure types are compatible
        if (sourcePort && targetPort) {
            const typesCompatible = nodelibrary/* NodeLibrary */.m.instance.canCastPortTypes(sourcePort.type, targetPort.type);
            if (!typesCompatible) {
                return {
                    connectable: false,
                    message: 'Type mismatch a source port of type <strong>' +
                        nodelibrary/* NodeLibrary */.m.nameForPortType(sourcePort.type) +
                        '</strong> cannot be connected to a target port with type <strong>' +
                        nodelibrary/* NodeLibrary */.m.nameForPortType(targetPort.type) +
                        '</strong>.'
                };
            }
        }
        // Duplicate connection
        if (sourcePort && targetPort && sourceNode && sourcePort) {
            // TODO: Change "some" to JS equivalent
            const isDuplicate = !!(0,external_underscore_.some)(this.connections, function (c) {
                return (c.toId === targetNode.id &&
                    c.toProperty === targetPort.name &&
                    c.fromId === sourceNode.id &&
                    c.fromProperty === sourcePort.name);
            });
            if (isDuplicate) {
                return {
                    connectable: false,
                    message: 'These ports are already connected in this direction'
                };
            }
        }
        return {
            connectable: true
        };
    }
    getConnectionHealth(c) {
        const sourceId = c.sourceId ? c.sourceId : c.sourceNode.id;
        const targetId = c.targetId ? c.targetId : c.targetNode.id;
        const warnings = warningsmodel/* WarningsModel */.l.instance.getWarnings({
            component: this.owner,
            connection: {
                fromId: sourceId,
                fromProperty: c.sourcePort,
                toId: targetId,
                toProperty: c.targetPort
            }
        });
        if (warnings) {
            return { healthy: false, message: warnings.shortMessage };
        }
        return { healthy: true };
    }
    scheduleEvaluateHealth() {
        const _this = this;
        if (this.evaluatehealthScheduled)
            return;
        this.evaluatehealthScheduled = true;
        setTimeout(function () {
            _this.evaluatehealthScheduled && _this.evaluateHealth();
            _this.evaluatehealthScheduled = false;
        }, 2000);
    }
    evaluateHealth() {
        const _this = this;
        if (!nodelibrary/* NodeLibrary */.m.instance.isLoaded())
            return;
        if (!this.owner)
            return;
        if (!this.owner.owner)
            return;
        if (!nodelibrary/* NodeLibrary */.m.instance.isModuleRegistered(this.owner.owner))
            return; // This module is not registered in the node library, no need to eval health
        // Nodes
        this.forEachNode(function (n) {
            n.evaluateHealth();
        });
        // Connections
        this.forEachConnection(function (c) {
            _this.evaluateConnectionHealth(c);
        });
    }
    evaluateConnectionHealth(c) {
        if (!this.owner)
            return; // Not in component
        const sourceNode = this.findNodeWithId(c.fromId);
        const targetNode = this.findNodeWithId(c.toId);
        // Make sure the source and target ports exist
        const sourcePort = sourceNode && c.fromProperty ? sourceNode.getPort(c.fromProperty) : undefined;
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: this.owner, connection: c, key: 'con-no-source-port' }, !sourcePort
            ? {
                message: "Source port doesn't exist.",
                showGlobally: true,
                level: 'error'
            }
            : undefined);
        const targetPort = targetNode && c.toProperty ? targetNode.getPort(c.toProperty) : undefined;
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: this.owner, connection: c, key: 'con-no-target-port' }, !targetPort || !nodelibrary/* NodeLibrary */.m.instance.isConditionalPortValid(targetNode, c.toProperty, ['extended'])
            ? {
                message: "Target port doesn't exist.",
                showGlobally: true,
                level: 'error'
            }
            : undefined);
        // Make sure the ports are connected internally
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: this.owner, connection: c, key: 'con-no-source-port-type' }, sourcePort && !sourcePort.type
            ? {
                message: 'The source port is missing type.',
                level: 'error'
            }
            : undefined);
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: this.owner, connection: c, key: 'con-no-target-port-type' }, targetPort && !targetPort.type
            ? {
                message: 'The target port is missing type.',
                level: 'error'
            }
            : undefined);
        // Make sure target and source ports have the same type
        const w = targetNode &&
            targetPort &&
            sourceNode &&
            sourcePort &&
            sourcePort.type &&
            targetPort.type &&
            !nodelibrary/* NodeLibrary */.m.instance.canCastPortTypes(sourcePort.type, targetPort.type);
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: this.owner, connection: c, key: 'con-type-mismatch' }, w
            ? {
                message: 'Target port of type <strong>' +
                    nodelibrary/* NodeLibrary */.m.nameForPortType(targetPort.type) +
                    '</strong> cannot be connected to a source port of type <strong>' +
                    nodelibrary/* NodeLibrary */.m.nameForPortType(sourcePort.type) +
                    '</strong>',
                level: 'error'
            }
            : undefined);
    }
    // Detaches a node from its parent
    detachNode(node, args) {
        const _this = this;
        const idx = node.parent.children.indexOf(node);
        const parent = node.parent;
        if (idx !== -1) {
            node.parent.children.splice(idx, 1);
            node.parent = undefined;
            this.roots.push(node);
            this.notifyListeners('nodeDetached', { model: node });
            // Undo
            if (args && args.undo) {
                const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
                undo.push({
                    label: args.label,
                    do: function () {
                        _this.detachNode(node);
                    },
                    undo: function () {
                        _this.attachNode(parent, node, idx);
                    }
                });
            }
        }
    }
    // Attaches a node to a parent node at a given index
    attachNode(parent, child, index, args) {
        const _this = this;
        const idx = this.roots.indexOf(child);
        if (idx !== -1) {
            this.roots.splice(idx, 1);
            child.parent = parent;
            parent.children.splice(index, 0, child);
            this.notifyListeners('nodeAttached', { parent, model: child, index: index });
            // Undo
            if (args && args.undo) {
                const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
                undo.push({
                    label: args.label,
                    do: function () {
                        _this.attachNode(parent, child, index);
                    },
                    undo: function () {
                        _this.detachNode(child);
                    }
                });
            }
        }
    }
    // Loop over all nodes (roots and children) of the graph
    forEachNode(callback) {
        for (const i in this.roots) {
            if (this.roots[i].forEach(callback)) {
                return true;
            }
        }
        return false;
    }
    forEachNodeRecursive(callback) {
        for (const i in this.roots) {
            if (this.roots[i].forEachRecursive(callback)) {
                return true;
            }
        }
        return false;
    }
    // Loop over all connections of the graph
    forEachConnection(callback) {
        for (const i in this.connections) {
            callback(this.connections[i]);
        }
    }
    // Check if the graph has nodes with the specific type
    hasNodesWithType(type) {
        let res = false;
        this.forEachNode(function (n) {
            if (type === n.type) {
                res = true;
                return true;
            }
        });
        return res;
    }
    // Find a node with the specified id
    findNodeWithId(id) {
        return this.nodeMap.get(id);
    }
    // Return a set of nodes (only the roots that span the specified list of nodes)
    // and internal connections
    getNodeSetWithNodes(nodes) {
        // Generate ID map
        const idMap = {};
        const set = [];
        for (var i in nodes) {
            const n = nodes[i];
            // Only include nodes that are either root nodes or
            // where the parent is not part of the nodes to be included (in this case the node will be included as child)
            if (n.parent === undefined || nodes.indexOf(n.parent) === -1) {
                n.forEach(function (node) {
                    idMap[node.id] = true;
                });
                set.push(n);
            }
        }
        // Get all connections that are within the node group
        const connections = [];
        for (var i in this.connections) {
            const c = this.connections[i];
            if (idMap[c.fromId] && idMap[c.toId]) {
                connections.push(c);
            }
        }
        return new NodeGraphNodeSet({ nodes: set, connections: connections });
    }
    // Insert a node set (roots and connections)
    insertNodeSet(nodeset, args) {
        // Add root nodes and children
        for (var i in nodeset.nodes) {
            const n = nodeset.nodes[i];
            this.addRoot(n, args);
        }
        // Add connections
        for (var i in nodeset.connections) {
            const c = nodeset.connections[i];
            this.addConnection(c, args);
        }
        //add comments
        for (const comment of nodeset.comments) {
            this.commentsModel.addComment(comment, args);
        }
    }
    // Remove all nodes and comments in a node set
    // NOTE: This will also remove all connections between any node in the node set and other nodes
    removeNodeSet(nodeset, args) {
        nodeset.parents = [];
        // Simply remove all roots, connections and children will follow
        for (const i in nodeset.nodes) {
            const n = nodeset.nodes[i];
            this.removeNode(n, args);
        }
        for (const comment of nodeset.comments) {
            this.commentsModel.removeComment(comment.id, args);
        }
    }
    getVisualRootIds() {
        return this.roots.filter((root) => root.type.allowAsChild).map((x) => x.id);
    }
    toJSON() {
        const json = {
            connections: this.connections,
            roots: this.roots.map((x) => x.toJSON()),
            // Add all the visual nodes to another list,
            // so when we export the project we have all the data we need.
            visualRoots: this.getVisualRootIds(),
            comments: undefined
        };
        const comments = this.commentsModel.getComments();
        if (comments.length) {
            json.comments = comments;
        }
        return json;
    }
}

// EXTERNAL MODULE: ./src/editor/src/models/componentmodel.ts
var componentmodel = __webpack_require__(16163);
// EXTERNAL MODULE: ./src/editor/src/utils/ParameterValueResolver.ts
var ParameterValueResolver = __webpack_require__(87934);
;// ./src/editor/src/models/nodegraphmodel/NodeGraphNode.ts







class NodeGraphNode extends (model_default()) {
    get variant() {
        if (!this._variant) {
            this._variant = nodelibrary/* NodeLibrary */.m.instance.findVariant(this.variantName, this.type);
        }
        return this._variant;
    }
    set variant(value) {
        if (typeof value === 'string')
            this.variantName = value;
        else if (value !== undefined) {
            this._variant = value;
            this.variantName = value.name;
        }
        else {
            this._variant = this.variantName = undefined;
        }
        this.notifyListeners('variantChanged', { variant: this._variant });
    }
    /** Get the type for this node */
    get type() {
        if (!this._type) {
            this._type = nodelibrary/* NodeLibrary */.m.instance.getNodeTypeWithName(this.typename);
            this.owner && this.owner.bindTypeModel(this._type);
        }
        // If no type is found return an "unkown node type" instead of undefined
        return this._type ? this._type : nodelibrary/* NodeLibrary */.m.instance.getUnknownNodeType(this.typename);
    }
    set type(value) {
        if (typeof value === 'string')
            this.typename = value;
        else
            this._type = value;
    }
    /** Get the label of the node */
    get label() {
        if (!this._label)
            return this.type.labelForNode(this);
        return this._label;
    }
    /** Set the label of the node */
    set label(value) {
        this._label = value;
        this.notifyListeners('labelChanged');
    }
    constructor(args) {
        super();
        for (const i in args)
            this[i] = args[i];
        if (!this.parameters)
            this.parameters = {};
        if (!this.children)
            this.children = [];
        if (!this.ports)
            this.ports = [];
        if (!this.dynamicports)
            this.dynamicports = [];
    }
    static fromJSON(json) {
        const node = new NodeGraphNode({
            id: json.id,
            x: json.x,
            y: json.y,
            label: json.label,
            type: json.type,
            variant: json.variant,
            version: json.version,
            parameters: json.parameters,
            stateParameters: json.stateParameters,
            stateTransitions: json.stateTransitions,
            defaultStateTransitions: json.defaultStateTransitions,
            ports: json.ports,
            dynamicports: json.dynamicports,
            conflicts: json.conflicts,
            annotation: json.annotation,
            metadata: json.metadata,
            diffData: json.diffData
        });
        for (const i in json.children) {
            const child = NodeGraphNode.fromJSON(json.children[i]);
            node.addChild(child);
        }
        return node;
    }
    // Return the module that this node belongs to
    getModule() {
        if (this.owner && this.owner.owner)
            return this.owner.owner.owner; // graph->component->project
    }
    // This method is called by the graph when a potential change in available node
    // types occurs
    updateType() {
        const newType = nodelibrary/* NodeLibrary */.m.instance.getNodeTypeWithName(this.typename);
        if (newType !== undefined && this._type !== newType) {
            // There is a new type for the type name, use it instead
            this._type = newType;
            this.owner && this.owner.bindTypeModel(this._type); // Register the new type
        }
        // The node type may have changed location in the project
        if (!nodelibrary/* NodeLibrary */.m.instance.typeIsMissing(this._type)) {
            // If the type is healthy make sure to keep the type name up to date
            this.typename = this._type.name;
        }
        // Reset ports cache so they will be reloaded
        this._ports = undefined;
    }
    // Loop over this node and all children
    forEach(callback) {
        if (callback(this)) {
            return true;
        }
        for (const i in this.children) {
            if (this.children[i].forEach(callback)) {
                return true;
            }
        }
        return false;
    }
    forEachRecursive(callback) {
        if (callback(this)) {
            return true;
        }
        if (this.type instanceof componentmodel/* ComponentModel */.j) {
            const res = this.type.forEachNodeRecursive(callback);
            if (res) {
                return true;
            }
        }
        for (const i in this.children) {
            if (this.children[i].forEachRecursive(callback)) {
                return true;
            }
        }
        return false;
    }
    // Checks if the port with the given name of this node is connected from/to in
    // the graph
    isPortConnected(portname, type) {
        const _this = this;
        return !!(0,external_underscore_.some)(this.owner.connections, function (c) {
            return (((!type || type === 'source') && c.fromId === _this.id && c.fromProperty === portname) ||
                ((!type || type === 'target') && c.toId === _this.id && c.toProperty === portname));
        });
    }
    // Iterates over all connections to or from this node
    forAllConnectionsOnThisNode(callback) {
        const _this = this;
        (0,external_underscore_.each)(this.owner.connections, function (c) {
            if (c.fromId === _this.id || c.toId === _this.id)
                callback(c);
        });
    }
    getConnectionsOnThisNode() {
        return this.owner.connections.filter((c) => c.fromId === this.id || c.toId === this.id);
    }
    // A node may have instance ports
    // Add a port to the component
    addPort(port, args) {
        const _this = this;
        if ((0,external_underscore_.find)(this.ports, function (p) {
            return p.name === port.name;
        }))
            return false;
        this._ports = undefined; // Clear cache
        this.ports.push(port);
        this.notifyListeners('portAdded', { model: this, port: port });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            const portname = port.name;
            undo.push({
                label: args.label,
                do: function () {
                    _this.addPort(port);
                },
                undo: function () {
                    _this.removePortWithName(portname);
                }
            });
        }
    }
    findPortWithName(portname) {
        return this.getPort(portname);
    }
    // Arrange port index and group
    arrangePort(portname, index, group, args) {
        const _this = this;
        const port = (0,external_underscore_.find)(this.ports, function (p) {
            return p.name === portname;
        });
        if (!port)
            return;
        if (port.group === group && port.index === index)
            return;
        const oldGroup = port.group;
        const oldIndex = port.index;
        port.group = group;
        port.index = index;
        // Notify
        this.notifyListeners('portRearranged', { model: this, port: port, oldIndex: oldIndex, oldGroup: oldGroup });
        this.owner &&
            this.owner.notifyListeners('nodePortRearranged', {
                model: this,
                port: port,
                oldIndex: oldIndex,
                oldGroup: oldGroup
            });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: args.label,
                do: function () {
                    _this.arrangePort(portname, index, group);
                },
                undo: function () {
                    _this.arrangePort(portname, oldIndex, oldGroup);
                }
            });
        }
        this._ports = undefined; // Clear cache
    }
    // Rename a port
    renamePortWithName(portname, newname, args) {
        const _this = this;
        if ((0,external_underscore_.find)(this.ports, function (p) {
            return p.name === newname;
        }))
            return false;
        const port = (0,external_underscore_.find)(this.ports, function (p) {
            return p.name === portname;
        });
        // Dynamic ports before the rename was made
        //var before = NodeLibrary.instance.getDynamicPortsForNode(this);
        this._ports = undefined; // Clear cache
        port.name = newname;
        // Dynamic ports after
        //var after = NodeLibrary.instance.getDynamicPortsForNode(this);
        // Find all dynamic ports that have been renamed and copy parameter values
        /*function findPortWithNameInList(list,name) {
          for(var i = 0; i < list.length; i++)
            if(list[i].name === name) return true;
        }
      
        if(before && after) {
          for(var i = 0; i < before.length; i++) {
            var oldPortname = before[i].name;
           if(oldPortname.indexOf(portname)===0 && !findPortWithNameInList(after,oldPortname)) {
              // A dynamic port have been removed, has it been renamed?
              var newPortname = newname + oldPortname.substring(portname.length);
              if(findPortWithNameInList(after,newPortname)) {
                // It has been renamed, we need to copy the values
                this.parameters[newPortname] = this.parameters[oldPortname];
                delete this.parameters[oldPortname];
              }
            }
          }
        }*/
        // Find all connections that use this port
        // and rename them
        const graph = this.owner;
        for (const i in graph.connections) {
            const c = graph.connections[i];
            if (c.fromProperty === portname && c.fromId === this.id) {
                var oldProperty = c.fromProperty;
                c.fromProperty = newname;
                graph.notifyListeners('connectionPortChanged', { model: c, oldFromProperty: oldProperty });
            }
            else if (c.toProperty === portname && c.toId === this.id) {
                var oldProperty = c.toProperty;
                c.toProperty = newname;
                graph.notifyListeners('connectionPortChanged', { model: c, oldToProperty: oldProperty });
            }
        }
        // Notify
        this.notifyListeners('portRenamed', { model: this, port: port, oldName: portname });
        this.owner && this.owner.notifyListeners('nodePortRenamed', { model: this, port: port, oldName: portname });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: args.label,
                do: function () {
                    _this.renamePortWithName(portname, newname);
                },
                undo: function () {
                    _this.renamePortWithName(newname, portname);
                }
            });
        }
        return true;
    }
    // Remove the port with the specified name
    // The port cannot be removed if it is connected internally
    removePortWithName(portname, args) {
        const _this = this;
        if (this.isPortConnected(portname) && !(args === null || args === void 0 ? void 0 : args.force))
            return false;
        this._ports = undefined; // Clear cache
        const port = (0,external_underscore_.find)(this.ports, function (p) {
            return p.name === portname;
        });
        const idx = this.ports.indexOf(port);
        if (idx !== -1) {
            this.ports.splice(idx, 1);
            this.notifyListeners('portRemoved', { model: this, port: port });
            // Undo
            if (args && args.undo) {
                const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
                undo.push({
                    label: args.label,
                    do: function () {
                        _this.removePortWithName(portname);
                    },
                    undo: function () {
                        _this.addPort(port);
                    }
                });
            }
            return true;
        }
    }
    // Returns a port with the given name
    getPort(portname, filter) {
        const ports = this.getPorts(filter);
        for (const i in ports) {
            if (ports[i].name === portname) {
                return ports[i];
            }
        }
        return undefined;
    }
    // Return all ports, filter is optional and can be 'input' or 'output'
    getPorts(filters) {
        var ports;
        if (!this._ports) {
            // Start with type ports
            var ports = this.type.ports ? this.type.ports : [];
            // Add instance ports from type
            // var instanceports = NodeLibrary.instance.getDynamicPortsForNode(this);
            // if(instanceports) ports = ports.concat(instanceports);
            // Any user defined ports
            if (this.ports)
                ports = ports.concat(this.ports);
            // Dynamic instance ports on this instance
            if (this.dynamicports)
                ports = ports.concat(this.dynamicports);
            // Sort on index (assign index in order if not present)
            (0,external_underscore_.each)(ports, function (p, index) {
                if (p.index === undefined)
                    p.index = index;
            });
            ports.sort(function (a, b) {
                return a.index > b.index ? 1 : -1;
            });
            this._ports = ports;
        }
        else
            ports = this._ports;
        return filters
            ? (0,external_underscore_.filter)(ports, function (p) {
                return p.plug && p.plug.indexOf(filters) !== -1;
            })
            : ports;
    }
    // Add a child as the last child node of this node
    addChild(child, args) {
        const _this = this;
        this.children.push(child);
        child.parent = this;
        // Set the owner of all children
        child.forEach(function (m) {
            _this.owner && _this.owner.bindTypeModel(m.type);
            m.owner = _this.owner;
        });
        if (this.owner) {
            this.owner.nodeMap.set(child.id, child);
            this.owner.notifyListeners('nodeAdded', { model: child, parent: this, disableSelect: args === null || args === void 0 ? void 0 : args.disableSelect });
        }
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            const graph = this.owner;
            undo.push({
                label: args.label,
                do: function () {
                    _this.addChild(child);
                },
                undo: function () {
                    graph.removeNode(child);
                }
            });
        }
    }
    // Insert a child at a specific index
    insertChild(child, index, args) {
        const _this = this;
        this.children.splice(index, 0, child);
        child.parent = this;
        //iterate through children and register them to the owner (which is a NodeGraphModel)
        child.forEach((m) => {
            var _a, _b;
            (_a = this.owner) === null || _a === void 0 ? void 0 : _a.bindTypeModel(m.type);
            (_b = this.owner) === null || _b === void 0 ? void 0 : _b.nodeMap.set(m.id, m);
            m.owner = this.owner;
        });
        if (this.owner) {
            this.owner.nodeMap.set(child.id, child);
            this.owner.notifyListeners('nodeAdded', { model: child, parent: this, index: index });
        }
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            const graph = this.owner;
            undo.push({
                label: args.label,
                do: function () {
                    _this.insertChild(child, index);
                },
                undo: function () {
                    graph.removeNode(child);
                }
            });
        }
    }
    canAcceptChildren(models) {
        if (!this.type.allowChildrenWithCategory)
            return false;
        for (const i in models) {
            const m = models[i];
            if ((!m.type.allowAsChild && !m.type.category) ||
                this.type.allowChildrenWithCategory.indexOf(m.type.category) === -1)
                return false;
        }
        return true;
    }
    canBeDeleted() {
        return !this.type.singleton; // Singleton nodes cannot be deleted
    }
    canBeCopied() {
        return !this.type.singleton; // Singleton nodes cannot be copied
    }
    // Set the label for the node, supports undo
    setLabel(label, args) {
        const _this = this;
        const oldLabel = this.label;
        this.label = label;
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: args.label,
                do: function () {
                    _this.setLabel(label);
                    _this.notifyListeners('modelParameterRedo');
                },
                undo: function () {
                    _this.setLabel(oldLabel);
                    _this.notifyListeners('modelParameterUndo');
                }
            });
        }
    }
    // Get the comment text for this node
    getComment() {
        var _a;
        return (_a = this.metadata) === null || _a === void 0 ? void 0 : _a.comment;
    }
    // Check if this node has a comment
    hasComment() {
        var _a, _b;
        return !!((_b = (_a = this.metadata) === null || _a === void 0 ? void 0 : _a.comment) === null || _b === void 0 ? void 0 : _b.trim());
    }
    // Set or clear the comment for this node, supports undo
    setComment(comment, args) {
        const _this = this;
        const oldComment = this.getComment();
        if (!this.metadata)
            this.metadata = {};
        // Store trimmed comment or undefined if empty
        this.metadata.comment = (comment === null || comment === void 0 ? void 0 : comment.trim()) || undefined;
        // Notify listeners of the change
        this.notifyListeners('commentChanged', { comment: this.metadata.comment });
        // Undo support
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: args.label || 'Edit node comment',
                do: function () {
                    _this.setComment(comment);
                },
                undo: function () {
                    _this.setComment(oldComment);
                }
            });
        }
    }
    // Set a parameter for the node instance
    setParameter(name, value, args) {
        const _this = this;
        if (args && args.undo && typeof args.undo !== 'object')
            // Create undo group if none is provided already
            var undoGroup = (args.undo = new undo_queue_model/* UndoActionGroup */.C({ label: args.label || 'set parameter' }));
        // Changing parameters may lead to new instance ports
        const oldPorts = this.getPorts();
        this._ports = undefined;
        const oldLabel = this.label;
        let oldValue = undefined;
        if (args && args.state !== undefined && args.state !== 'neutral') {
            // Set the parameter for a specific interaction state
            if (this.stateParameters === undefined)
                this.stateParameters = {};
            if (this.stateParameters[args.state] === undefined)
                this.stateParameters[args.state] = {};
            oldValue = this.stateParameters[args.state][name];
            if (value === undefined) {
                delete this.stateParameters[args.state][name];
            }
            else {
                this.stateParameters[args.state][name] = value;
            }
            this.notifyListeners('parametersChanged', {
                name: name,
                oldValue: oldValue,
                value: value,
                state: args.state,
                undo: args ? args.undo : undefined
            });
        }
        else {
            oldValue = this.parameters[name];
            if (value === undefined) {
                delete this.parameters[name];
            }
            else {
                this.parameters[name] = value;
            }
            this.notifyListeners('parametersChanged', {
                name: name,
                oldValue: oldValue,
                value: value,
                undo: args ? args.undo : undefined
            });
        }
        // If the ports have changed
        if (!(0,external_underscore_.isEqual)(oldPorts, this.getPorts())) {
            this.notifyListeners('instancePortsChanged');
        }
        // Also the label may change
        if (this.label !== oldLabel) {
            this.notifyListeners('labelChanged');
        }
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            if (args.oldValue) {
                oldValue = args.oldValue;
            }
            undo.push({
                label: args.label,
                do: function () {
                    _this.setParameter(name, value);
                    _this.notifyListeners('modelParameterRedo');
                },
                undo: function () {
                    _this.setParameter(name, oldValue);
                    _this.notifyListeners('modelParameterUndo');
                }
            });
            undoGroup && undo_queue_model/* UndoQueue */.g.instance.push(undoGroup); // Push undo group if it was created
        }
    }
    // Returns the parameter for the given port name
    getParameter(name, args) {
        let value;
        if (args && args.state !== undefined && args.state !== 'neutral') {
            // Look for the parameter value in the state parameters
            if (this.stateParameters && this.stateParameters[args.state] !== undefined)
                value = this.stateParameters[args.state][name];
            // No value in state parameters? try neutral state
            if (value === undefined)
                value = this.parameters[name];
        }
        else {
            // Look for the value in the neutral state / base parameters
            value = this.parameters[name];
        }
        if (value !== undefined)
            return value;
        // No value was found, let's get the correct default value
        if (this.variant) {
            // This model has a varient, default should come from it
            value = this.variant.getParameter(name, args);
        }
        if (value !== undefined)
            return value;
        // Get the default value from the port
        const port = this.getPort(name, 'input');
        if (!port)
            return value;
        if (port.type.parentPort) {
            const parentPort = this.getPort(port.type.parentPort, 'input');
            if (parentPort && parentPort.type.name === 'textStyle') {
                const styles = nodelibrary/* NodeLibrary */.m.instance.getStyles('text');
                const textStyle = this.getParameter(port.type.parentPort, args);
                if (styles[textStyle]) {
                    const style = styles[textStyle];
                    const childPortPrefix = parentPort.type.childPortPrefix || '';
                    const stylePropertyName = name.substring(childPortPrefix.length);
                    if (style.hasOwnProperty(stylePropertyName)) {
                        return style[stylePropertyName];
                    }
                }
            }
        }
        return port ? port.default : undefined;
    }
    /**
     * Get a parameter value formatted as a display string.
     * Handles expression parameter objects by resolving them to strings.
     *
     * @param name - The parameter name
     * @param args - Optional args (same as getParameter)
     * @returns A string representation of the parameter value, safe for UI display
     *
     * @example
     * ```ts
     * // Regular value
     * node.getParameterDisplayValue('width') // '100'
     *
     * // Expression parameter object
     * node.getParameterDisplayValue('height') // '{height * 2}' (not '[object Object]')
     * ```
     */
    getParameterDisplayValue(name, args) {
        const value = this.getParameter(name, args);
        return ParameterValueResolver/* ParameterValueResolver */.L.toString(value);
    }
    // Sets the dynamic instance ports for this node
    setDynamicPorts(ports, options) {
        if (portsEqual(ports, this.dynamicports)) {
            return;
        }
        this._ports = undefined;
        this.dynamicports = ports;
        if (options && options.renamed) {
            // Some of the ports are renamed from before
            const renamed = options.renamed.length ? options.renamed : [options.renamed];
            (0,external_underscore_.each)(renamed, (r) => {
                if (!r.plug || r.plug === 'input') {
                    // Move parameter values (inputs only)
                    (0,external_underscore_.each)(r.patterns, (p) => {
                        const after = p.replace('{{*}}', r.after);
                        const before = p.replace('{{*}}', r.before);
                        this.parameters[after] = this.parameters[before];
                        delete this.parameters[before];
                    });
                }
                // Move connections to renamed ports
                (0,external_underscore_.each)(r.patterns, (p) => {
                    const portname = p.replace('{{*}}', r.before);
                    const newname = p.replace('{{*}}', r.after);
                    const graph = this.owner;
                    for (const i in graph.connections) {
                        const c = graph.connections[i];
                        if (c.fromProperty === portname && c.fromId === this.id) {
                            const oldProperty = c.fromProperty;
                            c.fromProperty = newname;
                            graph.notifyListeners('connectionPortChanged', { model: c, oldFromProperty: oldProperty });
                        }
                        else if (c.toProperty === portname && c.toId === this.id) {
                            const oldProperty = c.toProperty;
                            c.toProperty = newname;
                            graph.notifyListeners('connectionPortChanged', { model: c, oldToProperty: oldProperty });
                        }
                    }
                });
            });
        }
        this.notifyListeners('instancePortsChanged');
    }
    // Apply a patch to this node
    /*NodeGraphModelNode.prototype.applyPatch = function (p) {
      if (p.typename) this.typename = p.typename;
      if (p.version) this.version = p.version;
      for (var name in p.params) {
        var value = p.params[name];
        if (value === null) this.setParameter(name, undefined);
        else this.setParameter(name, value);
      }
      if(p.portsToDelete) {
        for(const name of p.portsToDelete) {
          this.removePortWithName(name, {force: true});
        }
      }
      this._type = undefined;
      this.updateType();
      this.evaluateHealth();
    };*/
    getHealth() {
        const warnings = warningsmodel/* WarningsModel */.l.instance.getWarnings({ component: this.owner.owner, node: this });
        if (warnings) {
            return { healthy: false, message: warnings.shortMessage };
        }
        return { healthy: true };
    }
    evaluateHealth() {
        const _this = this;
        if (!this.owner)
            return; // Not in graph
        if (!this.owner.owner)
            return; // Not in a component
        // Missing type
        const missingType = nodelibrary/* NodeLibrary */.m.instance.typeIsMissing(this.type);
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: this.owner.owner, node: this, key: 'node-missing-type' }, missingType
            ? {
                message: 'The node type of this instance <strong>' + this.typename + '</strong> is missing.',
                showGlobally: true,
                level: 'error'
            }
            : undefined);
        // Cannot be a child
        var w = this.parent && !this.type.allowAsChild;
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: this.owner.owner, node: this, key: 'node-not-child' }, !missingType && w //don't show this warning if type is missing since it's a bit superfluous
            ? {
                message: 'This node cannot be a child in a hierarchy',
                showGlobally: true,
                level: 'error'
            }
            : undefined);
        // Parent cannot have children
        var w = this.type &&
            this.parent &&
            this.parent.type &&
            (!this.parent.type.allowChildrenWithCategory ||
                !this.type.category ||
                this.parent.type.allowChildrenWithCategory.indexOf(this.type.category) === -1);
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: this.owner.owner, node: this, key: 'node-invalid-child' }, w
            ? {
                message: 'This node is a child of a node that doesnt support this type of child nodes.',
                level: 'error'
            }
            : undefined);
        // Cannot have children
        w = !this.type.allowChildrenWithCategory && this.children && this.children.length > 0;
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: this.owner.owner, node: this, key: 'node-no-children' }, !missingType && w //don't show this warning if type is missing since it's a bit superfluous
            ? {
                message: 'This node cannot have children.',
                showGlobally: true,
                level: 'error'
            }
            : undefined);
        // Singleton
        w = this.type.allowSingleInstanceOnly && this.owner.hasNodesWithType(this.type);
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: this.owner.owner, node: this, key: 'node-singleton' }, w
            ? {
                message: 'There can only be one instance of this type in a component. Multiple instances may lead to unexpected behavior.',
                level: 'error',
                showGlobally: true
            }
            : undefined);
        // Roots must have same category
        var w = !this.parent &&
            this.type.allowAsChild &&
            !!(0,external_underscore_.find)(this.owner.roots, function (n) {
                return n !== _this && n.type.allowAsChild && n.type.category !== _this.type.category;
            });
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: this.owner.owner, node: this, key: 'node-child-cat' }, w
            ? {
                message: 'All roots of a component that may be children must have the same category.',
                level: 'error'
            }
            : undefined);
        // Merge conflicts
        if (this.conflicts) {
            function clearConflict(c) {
                const idx = _this.conflicts.indexOf(c);
                idx !== -1 && _this.conflicts.splice(idx, 1);
                let key;
                if (c.type === 'parameter' || c.type === 'sourceCode')
                    key = 'node-param-conflict-' + c.name;
                else if (c.type === 'stateParameter')
                    key = 'node-state-param-conflict-' + c.state + '-' + c.name;
                else if (c.type === 'stateTransition')
                    key = 'node-state-trans-conflict-' + c.state + '-' + c.name;
                else if (c.type === 'variant')
                    key = 'node-variant-conflict';
                else if (c.type === 'defaultStateTransition')
                    key = 'node-dfs-conflict-' + c.state;
                else if (c.type === 'typename')
                    key = 'node-type-conflict';
                warningsmodel/* WarningsModel */.l.instance.setWarning({ component: _this.owner.owner, node: _this, key }, undefined);
            }
            (0,external_underscore_.each)(this.conflicts, function (c) {
                if (c.type === 'parameter') {
                    var port = _this.getPort(c.name);
                    var ourValue = nodelibrary/* NodeLibrary */.m.instance.formatParameterValue(c.oursDisplayName || c.ours, port);
                    var theirValue = nodelibrary/* NodeLibrary */.m.instance.formatParameterValue(c.theirsDisplayName || c.theirs, port);
                    var portName = port !== undefined && port.displayName ? port.displayName : c.name;
                    warningsmodel/* WarningsModel */.l.instance.setWarning({ component: _this.owner.owner, node: _this, key: 'node-param-conflict-' + c.name }, {
                        type: 'conflict',
                        conflictMetadata: {
                            parameter: portName,
                            ours: ourValue,
                            theirs: theirValue
                        },
                        message: `Merge conflict at parameter ${portName}`,
                        showGlobally: true,
                        onDismiss: function () {
                            clearConflict(c);
                        },
                        onUseTheirs: function () {
                            clearConflict(c);
                            _this.setParameter(c.name, c.theirs);
                        }
                    });
                }
                else if (c.type === 'sourceCode') {
                    var port = _this.getPort(c.name);
                    var ourValue = nodelibrary/* NodeLibrary */.m.instance.formatParameterValue(c.oursDisplayName || c.ours, port);
                    var theirValue = nodelibrary/* NodeLibrary */.m.instance.formatParameterValue(c.theirsDisplayName || c.theirs, port);
                    var portName = port !== undefined && port.displayName ? port.displayName : c.name;
                    warningsmodel/* WarningsModel */.l.instance.setWarning({ component: _this.owner.owner, node: _this, key: 'node-param-conflict-' + c.name }, {
                        type: 'conflict-source-code',
                        conflictMetadata: {
                            parameter: portName,
                            ours: ourValue,
                            theirs: theirValue
                        },
                        message: `Merge conflict at parameter ${portName}. Edit the code to see a diff, then mark as resolved. Or use theirs to discard your changes.`,
                        showGlobally: true,
                        onDismiss: function () {
                            clearConflict(c);
                        },
                        onUseTheirs: function () {
                            clearConflict(c);
                            _this.setParameter(c.name, c.theirs);
                        }
                    });
                }
                else if (c.type === 'stateParameter') {
                    var state = _this.type.visualStates !== undefined ? _this.type.visualStates.find((s) => s.name === c.state) : undefined;
                    var stateName = state !== undefined ? state.label : c.state;
                    var port = _this.getPort(c.name);
                    var ourValue = nodelibrary/* NodeLibrary */.m.instance.formatParameterValue(c.oursDisplayName || c.ours, port);
                    var theirValue = nodelibrary/* NodeLibrary */.m.instance.formatParameterValue(c.theirsDisplayName || c.theirs, port);
                    var portName = port !== undefined && port.displayName ? port.displayName : c.name;
                    warningsmodel/* WarningsModel */.l.instance.setWarning({ component: _this.owner.owner, node: _this, key: 'node-state-param-conflict-' + c.state + '-' + c.name }, {
                        type: 'conflict',
                        conflictMetadata: {
                            parameter: portName,
                            ours: ourValue,
                            theirs: theirValue
                        },
                        message: `Merge conflict in visual state parameter ${portName} for state ${stateName}`,
                        showGlobally: true,
                        onDismiss: function () {
                            clearConflict(c);
                        },
                        onUseTheirs: function () {
                            clearConflict(c);
                            _this.setParameter(c.name, c.theirs, { state: c.state });
                        }
                    });
                }
                else if (c.type === 'stateTransition') {
                    var state = _this.type.visualStates !== undefined ? _this.type.visualStates.find((s) => s.name === c.state) : undefined;
                    var stateName = state !== undefined ? state.label : c.state;
                    var port = _this.getPort(c.name);
                    var portName = port !== undefined && port.displayName ? port.displayName : c.name;
                    warningsmodel/* WarningsModel */.l.instance.setWarning({ component: _this.owner.owner, node: _this, key: 'node-state-trans-conflict-' + c.state + '-' + c.name }, {
                        type: 'conflict',
                        conflictMetadata: {
                            parameter: portName,
                            ours: ourValue,
                            theirs: theirValue
                        },
                        message: `Merge conflict in visual state transition ${portName} for state ${stateName}`,
                        showGlobally: true,
                        onDismiss: function () {
                            clearConflict(c);
                        },
                        onUseTheirs: function () {
                            clearConflict(c);
                            _this.setStateTransition(c.state, c.name, c.theirs);
                        }
                    });
                }
                else if (c.type === 'variant') {
                    warningsmodel/* WarningsModel */.l.instance.setWarning({ component: _this.owner.owner, node: _this, key: 'node-variant-conflict' }, {
                        type: 'conflict',
                        level: 'error',
                        showGlobally: true,
                        message: 'There is a variant conflict, your variant is <strong>' +
                            c.ours +
                            '</strong> and their is <strong>' +
                            c.theirs +
                            '</strong>.',
                        onDismiss: function () {
                            clearConflict(c);
                        },
                        onUseTheirs: function () {
                            clearConflict(c);
                            _this.variant = c.theirs;
                        }
                    });
                }
                else if (c.type === 'defaultStateTransition') {
                    var state = _this.type.visualStates !== undefined ? _this.type.visualStates.find((s) => s.name === c.state) : undefined;
                    var stateName = state !== undefined ? state.label : c.state;
                    warningsmodel/* WarningsModel */.l.instance.setWarning({ component: _this.owner.owner, node: _this, key: 'node-dfs-conflict-' + c.state }, {
                        type: 'conflict',
                        level: 'error',
                        showGlobally: true,
                        message: 'There is a conflict in the default state transition for state <strong>' + stateName + '</strong',
                        onDismiss: function () {
                            clearConflict(c);
                        },
                        onUseTheirs: function () {
                            clearConflict(c);
                            _this.setDefaultStateTransition(c.state, c.theirs);
                        }
                    });
                }
                else if (c.type === 'typename') {
                    warningsmodel/* WarningsModel */.l.instance.setWarning({ component: _this.owner.owner, node: _this, key: 'node-type-conflict' }, {
                        type: 'conflict',
                        level: 'error',
                        showGlobally: true,
                        message: 'There is a type conflict your type is <strong>' +
                            c.ours +
                            '</strong> and their is <strong>' +
                            c.theirs +
                            '</strong>.',
                        onDismiss: function () {
                            clearConflict(c);
                        },
                        onUseTheirs: function () {
                            clearConflict(c);
                            _this.typename = c.theirs;
                            _this._type = undefined;
                            _this.updateType();
                            _this.evaluateHealth();
                        }
                    });
                }
            });
        }
    }
    updateVariantRef() {
        this._variant = nodelibrary/* NodeLibrary */.m.instance.findVariant(this.variantName, this.type);
        this.variantName = this._variant !== undefined ? this._variant.name : undefined;
    }
    setVariant(variant, args) {
        const _oldVariant = this.variant;
        this.variant = variant;
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: 'Change variant',
                do: () => {
                    this.setVariant(variant);
                },
                undo: () => {
                    this.setVariant(_oldVariant);
                }
            });
        }
    }
    // Replaces entire parameters structures and notifies listeners
    _setParameters(parameters) {
        // Changing parameters may lead to new instance ports
        const oldPorts = this.getPorts();
        this._ports = undefined;
        const oldLabel = this.label;
        const _oldParameters = this.parameters;
        const _oldStateParameters = this.stateParameters;
        this.parameters = parameters.parameters;
        this.stateParameters = parameters.stateParameters;
        this.notifyListeners('parametersChanged', {
            oldParameters: _oldParameters,
            oldStateParameters: _oldStateParameters,
            parameters: this.parameters,
            stateParameters: this.stateParameters
        });
        // If the ports have changed
        if (!(0,external_underscore_.isEqual)(oldPorts, this.getPorts())) {
            this.notifyListeners('instancePortsChanged');
        }
        // Also the label may change
        if (this.label !== oldLabel) {
            this.notifyListeners('labelChanged');
        }
    }
    createNewVariant(variantName, args) {
        try {
            var project = this.owner.owner.owner;
        }
        catch (e) { }
        if (project === undefined)
            return; // This node is not currently in a project
        // Create the variation
        const variant = project.createNewVariant(variantName, this);
        if (variant === undefined)
            return; // Did not success creating variant
        // Reset all parameters on this node
        const _oldParameters = this.parameters;
        const _oldStateParameters = this.stateParameters;
        const _oldStateTransitions = this.stateTransitions;
        const _oldDefaultStateTransitions = this.defaultStateTransitions;
        const _oldVariant = this.variant;
        this.variant = variant;
        this._setParameters({ parameters: {}, stateParameters: {} });
        this._setStateTransitions({ stateTransitions: {}, defaultStateTransitions: {} });
        this.notifyListeners('variantCreated', { variant: this.variant });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            const type = this.type;
            undo.push({
                label: 'Create new variant',
                do: () => {
                    this.createNewVariant(variantName, this);
                },
                undo: () => {
                    project.deleteVariant(variantName, type);
                    this._setParameters({ parameters: _oldParameters, stateParameters: _oldStateParameters });
                    this._setStateTransitions({
                        stateTransitions: _oldStateTransitions,
                        defaultStateTransitions: _oldDefaultStateTransitions
                    });
                    this.variant = _oldVariant;
                }
            });
        }
    }
    updateVariant(args) {
        try {
            var project = this.owner.owner.owner;
        }
        catch (e) { }
        if (project === undefined)
            return; // This node is not currently in a project
        if (this.variant === undefined)
            return; // have no variant
        // Push parameters to variant
        const _oldVariantParameters = JSON.parse(JSON.stringify(this.variant.parameters));
        const _oldVariantStateParameters = this.variant.stateParameters
            ? JSON.parse(JSON.stringify(this.variant.stateParameters))
            : undefined;
        const _oldVariantStateTransitions = this.variant.stateTransitions
            ? JSON.parse(JSON.stringify(this.variant.stateTransitions))
            : undefined;
        const _oldVariantDefaultStateTransitions = this.variant.defaultStateTransitions
            ? JSON.parse(JSON.stringify(this.variant.defaultStateTransitions))
            : undefined;
        this.variant.updateFromNode(this);
        // Reset parameters
        const _oldParameters = this.parameters;
        const _oldStateParameters = this.stateParameters;
        const _oldStateTransitions = this.stateTransitions;
        const _oldDefaultStateTransitions = this.defaultStateTransitions;
        this._setParameters({ parameters: {}, stateParameters: {} });
        this._setStateTransitions({ stateTransitions: {}, defaultStateTransitions: {} });
        this.notifyListeners('variantUpdated', { variant: this.variant });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: 'Update variant',
                do: () => {
                    this.updateVariant(args);
                },
                undo: () => {
                    // Revert to old variant parameters
                    this.variant.setParameters({
                        parameters: _oldVariantParameters,
                        stateParameters: _oldVariantStateParameters,
                        stateTransitions: _oldVariantStateTransitions,
                        defaultStateTransitions: _oldVariantDefaultStateTransitions
                    });
                    // Revert to old node parameters
                    this._setParameters({ parameters: _oldParameters, stateParameters: _oldStateParameters });
                    this._setStateTransitions({
                        stateTransitions: _oldStateTransitions,
                        defaultStateTransitions: _oldDefaultStateTransitions
                    });
                    this.notifyListeners('variantUpdated', { variant: this.variant });
                }
            });
        }
    }
    getStateTransition(state, parameterName) {
        state = state || 'neutral';
        if (this.stateTransitions !== undefined &&
            this.stateTransitions[state] !== undefined &&
            this.stateTransitions[state][parameterName] !== undefined) {
            return this.stateTransitions[state][parameterName];
        }
        if (this.variant &&
            this.variant.stateTransitions !== undefined &&
            this.variant.stateTransitions[state] !== undefined)
            return this.variant.stateTransitions[state][parameterName];
    }
    _setStateTransitions(transitions) {
        const _oldStateTransitions = this.stateTransitions;
        const _oldDefaultStateTransitions = this.defaultStateTransitions;
        this.stateTransitions = transitions.stateTransitions;
        this.defaultStateTransitions = transitions.defaultStateTransitions;
        this.notifyListeners('stateTransitionsChanged', {
            oldStateTransitions: _oldStateTransitions,
            oldDefaultStateTransitions: _oldDefaultStateTransitions,
            stateTransitions: this.stateTransitions,
            defaultStateTransitions: this.defaultStateTransitions
        });
    }
    setStateTransition(state, parameterName, curve, args) {
        state = state || 'neutral';
        if (this.stateTransitions === undefined)
            this.stateTransitions = {};
        if (this.stateTransitions[state] === undefined)
            this.stateTransitions[state] = {};
        const _oldStateTransition = this.stateTransitions[state][parameterName];
        this.stateTransitions[state][parameterName] = curve;
        this.notifyListeners('stateTransitionsChanged', { state: state, parameterName: parameterName, curve: curve });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: 'set state transition',
                do: () => {
                    this.setStateTransition(state, parameterName, curve, args);
                },
                undo: () => {
                    this.stateTransitions[state][parameterName] = _oldStateTransition;
                    this.notifyListeners('stateTransitionsChanged', {
                        state: state,
                        parameterName: parameterName,
                        curve: _oldStateTransition
                    });
                }
            });
        }
    }
    getDefaultStateTransition(state = 'neutral') {
        if (this.defaultStateTransitions !== undefined && this.defaultStateTransitions[state] !== undefined)
            return this.defaultStateTransitions[state];
        if (this.variant !== undefined)
            return this.variant.getDefaultStateTransition(state);
    }
    setDefaultStateTransition(state = 'neutral', curve, args) {
        if (this.defaultStateTransitions === undefined)
            this.defaultStateTransitions = {};
        const _oldDefaultStateTransition = this.defaultStateTransitions[state];
        this.defaultStateTransitions[state] = curve;
        this.notifyListeners('defaultStateTransitionChanged', { state, curve });
        // Undo
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo.push({
                label: 'set default state transition',
                do: () => {
                    this.setDefaultStateTransition(state, curve, args);
                },
                undo: () => {
                    this.defaultStateTransitions[state] = _oldDefaultStateTransition;
                    this.notifyListeners('defaultStateTransitionChanged', { state, curve: _oldDefaultStateTransition });
                }
            });
        }
    }
    getPossibleTransitionsForState(state) {
        const _this = this;
        const transitions = {};
        function _addTransitions(stateParameters) {
            for (const parameterName in stateParameters) {
                const port = _this.getPort(parameterName);
                if (nodelibrary/* NodeLibrary */.m.instance.canPortHaveTransition(port))
                    transitions[parameterName] = {
                        name: parameterName,
                        displayName: port ? port.displayName : undefined,
                        group: port ? port.group : undefined
                    };
            }
        }
        if (state !== undefined && state !== 'neutral') {
            // Find all properties that have a value set for this state
            if (this.stateParameters && this.stateParameters[state])
                _addTransitions(this.stateParameters[state]);
            // Also check the variant for state parameters
            if (this.variant !== undefined && this.variant.stateParameters && this.variant.stateParameters[state])
                _addTransitions(this.variant.stateParameters[state]);
            return Object.keys(transitions).map((t) => transitions[t]);
        }
        else {
            // This is the neutral state, it should contain all properties for all states
            this.type.visualStates &&
                this.type.visualStates.forEach((state) => {
                    // Add state parameters from this node
                    if (this.stateParameters && this.stateParameters[state.name])
                        _addTransitions(this.stateParameters[state.name]);
                    // and also add any from the variant
                    if (this.variant !== undefined && this.variant.stateParameters && this.variant.stateParameters[state.name])
                        _addTransitions(this.variant.stateParameters[state.name]);
                });
            return Object.keys(transitions).map((t) => transitions[t]);
        }
    }
    toJSON() {
        const json = {
            id: this.id,
            type: this.typename,
            variant: this.variant ? this.variant.name : undefined,
            version: this.version,
            label: this._label,
            x: this.x,
            y: this.y,
            parameters: JSON.parse(JSON.stringify(this.parameters)),
            stateParameters: this.stateParameters ? JSON.parse(JSON.stringify(this.stateParameters)) : undefined,
            stateTransitions: this.stateTransitions ? JSON.parse(JSON.stringify(this.stateTransitions)) : undefined,
            defaultStateTransitions: this.defaultStateTransitions
                ? JSON.parse(JSON.stringify(this.defaultStateTransitions))
                : undefined,
            ports: this.ports ? JSON.parse(JSON.stringify(this.ports)) : undefined,
            dynamicports: this.dynamicports ? JSON.parse(JSON.stringify(this.dynamicports)) : undefined,
            conflicts: this.conflicts ? JSON.parse(JSON.stringify(this.conflicts)) : undefined,
            children: [],
            metadata: this.metadata
        };
        for (const parameterName in json.parameters) {
            try {
                if (isSourceCodePort(json.type, parameterName)) {
                    json.metadata = json.metadata || {};
                    json.metadata.merge = json.metadata.merge || { soureCodePorts: [] };
                    json.metadata.merge.soureCodePorts.push(parameterName);
                    //fixes a bug where the soureCodePortss contained duplicated entries
                    json.metadata.merge.soureCodePorts = [...new Set(json.metadata.merge.soureCodePorts)];
                }
            }
            catch (e) {
                console.log('error saving node metadata', e);
            }
        }
        for (const i in this.children) {
            json.children.push(this.children[i].toJSON());
        }
        return json;
    }
}
function portsEqual(a, b) {
    function objectEquals(x, y) {
        if (x === null || x === undefined || y === null || y === undefined) {
            return x === y;
        }
        if (x === y) {
            return true;
        }
        if (Array.isArray(x) && x.length !== y.length) {
            return false;
        }
        // if they are strictly equal, they both need to be object at least
        if (!(x instanceof Object))
            return false;
        if (!(y instanceof Object))
            return false;
        //recursive object equality check
        //but skip the 'index' parameter, the viewer will never send that for dynamic ports
        const p = Object.keys(x);
        return (Object.keys(y).every((i) => {
            if (i === 'index')
                return true;
            return p.indexOf(i) !== -1;
        }) && p.every((i) => objectEquals(x[i], y[i])));
    }
    const bPorts = {};
    for (const port of b) {
        bPorts[port.name] = port;
    }
    if (a.length !== b.length)
        return false;
    return a.every((port) => {
        return objectEquals(port, bPorts[port.name]);
    });
}
const _sourceCodePortCache = new Map();
function _isSourceCodePort(typename, parameterName) {
    var _a;
    const type = nodelibrary/* NodeLibrary */.m.instance.getNodeTypeWithName(typename); // all should have same type, type cannot be changed
    if (!type)
        return false;
    let port;
    if (type.ports) {
        port = type.ports.find((p) => p.name === parameterName);
    }
    if (!port && type.dynamicports) {
        for (let j = 0; j < type.dynamicports.length && !port; j++) {
            if (type.dynamicports[j].ports) {
                port = type.dynamicports[j].ports.find((p) => p.name === parameterName);
            }
        }
    }
    let language = (_a = port === null || port === void 0 ? void 0 : port.type) === null || _a === void 0 ? void 0 : _a.codeeditor;
    if (!language)
        return false;
    language = language.toLowerCase();
    if (language === 'javascript' || language === 'json' || language === 'css') {
        return true;
    }
    return false;
}
function isSourceCodePort(typename, parameterName) {
    const hash = typename + '-' + parameterName;
    if (!_sourceCodePortCache.has(hash)) {
        _sourceCodePortCache.set(hash, _isSourceCodePort(typename, parameterName));
    }
    return _sourceCodePortCache.get(hash);
}

;// ./src/editor/src/models/nodegraphmodel/NodeGraphNodeSet.ts


class NodeGraphNodeSet {
    constructor(args) {
        this.nodes = args.nodes;
        this.connections = args.connections;
        this.comments = args.comments || [];
    }
    static fromJSON(json) {
        const nodes = [];
        for (const i in json.nodes)
            nodes.push(NodeGraphNode.fromJSON(json.nodes[i]));
        return new NodeGraphNodeSet({ nodes: nodes, connections: json.connections, comments: json.comments });
    }
    clone() {
        // Clone all nodes
        const clones = [];
        for (var i in this.nodes) {
            clones.push(NodeGraphNode.fromJSON(this.nodes[i].toJSON()));
        }
        // Generate new IDs and remap
        const idMap = {};
        for (var i in clones) {
            clones[i].forEach(function (node) {
                idMap[node.id] = (0,utils.guid)();
                node.id = idMap[node.id];
            });
        }
        // Clone all connections, and remap IDs
        const connections = [];
        for (var i in this.connections) {
            const c = this.connections[i];
            connections.push({
                fromId: idMap[c.fromId],
                fromProperty: c.fromProperty,
                toId: idMap[c.toId],
                toProperty: c.toProperty
            });
        }
        //clone comments with new IDs
        const commentClones = JSON.parse(JSON.stringify(this.comments));
        for (const comment of commentClones) {
            comment.id = (0,utils.guid)();
        }
        return new NodeGraphNodeSet({ nodes: clones, connections, comments: commentClones });
    }
    toJSON() {
        const json = {
            nodes: [],
            connections: this.connections,
            comments: this.comments
        };
        for (const i in this.nodes) {
            json.nodes.push(this.nodes[i].toJSON());
        }
        return json;
    }
    // Remove unnecessary stuff for clipboard
    strip() {
        function _strip(nodes) {
            for (const i in nodes) {
                delete nodes[i].dynamicports;
                _strip(nodes[i].children);
            }
        }
        _strip(this.nodes);
    }
    //Moves the entire graph so the position of the top left node is x,y
    setOriginPosition(newOrigin) {
        const origin = this.getOriginPosition();
        const nodesAndComments = this.nodes.concat(this.comments);
        for (const n of nodesAndComments) {
            n.x = Math.round(n.x - origin.x + newOrigin.x);
            n.y = Math.round(n.y - origin.y + newOrigin.y);
        }
    }
    //get position of top left node
    getOriginPosition() {
        let minX = Number.MAX_VALUE;
        let minY = Number.MAX_VALUE;
        const nodesAndComments = this.nodes.concat(this.comments);
        for (const n of nodesAndComments) {
            if (n.x < minX) {
                minX = n.x;
            }
            if (n.y < minY) {
                minY = n.y;
            }
        }
        return { x: minX, y: minY };
    }
}

;// ./src/editor/src/models/nodegraphmodel/index.ts





/***/ }),

/***/ 87934:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   L: () => (/* binding */ ParameterValueResolver)
/* harmony export */ });
/* unused harmony export ValueContext */
/* harmony import */ var _noodl_models_ExpressionParameter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(52034);
/**
 * ParameterValueResolver
 *
 * Centralized utility for resolving parameter values from storage to their display/runtime values.
 * Handles the conversion of expression parameter objects to primitive values based on context.
 *
 * This is necessary because parameters can be stored as either:
 * 1. Primitive values (string, number, boolean)
 * 2. Expression parameter objects: { mode: 'expression', expression: '...', fallback: '...', version: 1 }
 *
 * Consumers need different values based on their context:
 * - Display (UI, canvas): Use fallback value
 * - Runtime: Use evaluated expression (handled separately by runtime)
 * - Serialization: Use raw value as-is
 *
 * @module noodl-editor/utils
 * @since TASK-006B
 */

/**
 * Context in which a parameter value is being used
 */
var ValueContext;
(function (ValueContext) {
    /**
     * Display context - for UI rendering (property panel, canvas)
     * Returns the fallback value from expression parameters
     */
    ValueContext["Display"] = "display";
    /**
     * Runtime context - for runtime evaluation
     * Returns the fallback value (actual evaluation happens in runtime)
     */
    ValueContext["Runtime"] = "runtime";
    /**
     * Serialization context - for saving/loading
     * Returns the raw value unchanged
     */
    ValueContext["Serialization"] = "serialization";
})(ValueContext || (ValueContext = {}));
/**
 * ParameterValueResolver class
 *
 * Provides static methods to safely extract primitive values from parameters
 * that may be either primitives or expression parameter objects.
 */
class ParameterValueResolver {
    /**
     * Resolves a parameter value to a primitive based on context.
     *
     * @param paramValue - The raw parameter value (could be primitive or expression object)
     * @param context - The context in which the value is being used
     * @returns A primitive value appropriate for the context
     *
     * @example
     * ```typescript
     * // Primitive value passes through
     * resolve('hello', ValueContext.Display) // => 'hello'
     *
     * // Expression parameter returns fallback
     * const expr = { mode: 'expression', expression: 'Variables.x', fallback: 'default', version: 1 };
     * resolve(expr, ValueContext.Display) // => 'default'
     * ```
     */
    static resolve(paramValue, context) {
        var _a, _b, _c;
        // If not an expression parameter, return as-is (assuming it's a primitive)
        if (!(0,_noodl_models_ExpressionParameter__WEBPACK_IMPORTED_MODULE_0__/* .isExpressionParameter */ .UC)(paramValue)) {
            return paramValue;
        }
        // Handle expression parameters based on context
        switch (context) {
            case ValueContext.Display:
                // For display contexts (UI, canvas), use the fallback value
                return (_a = paramValue.fallback) !== null && _a !== void 0 ? _a : '';
            case ValueContext.Runtime:
                // For runtime, return fallback (actual evaluation happens in node runtime)
                // This prevents display code from trying to evaluate expressions
                return (_b = paramValue.fallback) !== null && _b !== void 0 ? _b : '';
            case ValueContext.Serialization:
                // For serialization, return the whole object unchanged
                return paramValue;
            default:
                // Default to fallback value for safety
                return (_c = paramValue.fallback) !== null && _c !== void 0 ? _c : '';
        }
    }
    /**
     * Safely converts any parameter value to a string for display.
     * Always returns a string, never an object.
     *
     * @param paramValue - The raw parameter value
     * @returns A string representation safe for display
     *
     * @example
     * ```typescript
     * toString('hello') // => 'hello'
     * toString(42) // => '42'
     * toString(null) // => ''
     * toString(undefined) // => ''
     * toString({ mode: 'expression', expression: '', fallback: 'test', version: 1 }) // => 'test'
     * ```
     */
    static toString(paramValue) {
        const resolved = this.resolve(paramValue, ValueContext.Display);
        // If resolved is still an object (shouldn't happen, but defensive)
        if (typeof resolved === 'object' && resolved !== null) {
            return '';
        }
        return String(resolved !== null && resolved !== void 0 ? resolved : '');
    }
    /**
     * Safely converts any parameter value to a number for display.
     * Returns undefined if the value cannot be converted to a valid number.
     *
     * @param paramValue - The raw parameter value
     * @returns A number, or undefined if conversion fails
     *
     * @example
     * ```typescript
     * toNumber(42) // => 42
     * toNumber('42') // => 42
     * toNumber('hello') // => undefined
     * toNumber(null) // => undefined
     * toNumber({ mode: 'expression', expression: '', fallback: 123, version: 1 }) // => 123
     * ```
     */
    static toNumber(paramValue) {
        const resolved = this.resolve(paramValue, ValueContext.Display);
        // If resolved is still an object (shouldn't happen, but defensive)
        if (typeof resolved === 'object' && resolved !== null) {
            return undefined;
        }
        const num = Number(resolved);
        return isNaN(num) ? undefined : num;
    }
    /**
     * Safely converts any parameter value to a boolean for display.
     * Uses JavaScript truthiness rules.
     *
     * @param paramValue - The raw parameter value
     * @returns A boolean value
     *
     * @example
     * ```typescript
     * toBoolean(true) // => true
     * toBoolean('hello') // => true
     * toBoolean('') // => false
     * toBoolean(0) // => false
     * toBoolean({ mode: 'expression', expression: '', fallback: true, version: 1 }) // => true
     * ```
     */
    static toBoolean(paramValue) {
        const resolved = this.resolve(paramValue, ValueContext.Display);
        // If resolved is still an object (shouldn't happen, but defensive)
        if (typeof resolved === 'object' && resolved !== null) {
            return false;
        }
        return Boolean(resolved);
    }
    /**
     * Checks if a parameter value is an expression parameter.
     * Convenience method that delegates to the ExpressionParameter module.
     *
     * @param paramValue - The value to check
     * @returns True if the value is an expression parameter object
     */
    static isExpression(paramValue) {
        return (0,_noodl_models_ExpressionParameter__WEBPACK_IMPORTED_MODULE_0__/* .isExpressionParameter */ .UC)(paramValue);
    }
}


/***/ }),

/***/ 88007:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PropertyPanelBaseInput-module__Root--fKd55{font-family:var(--font-family);color:var(--theme-color-fg-default);background-color:var(--theme-color-bg-3);line-height:1;border:none;padding:6px 8px 7px;width:100%;box-sizing:border-box;font-size:12px;transition:background-color var(--speed-turbo),color var(--speed-turbo)}.PropertyPanelBaseInput-module__Root--fKd55:hover{color:var(--theme-color-fg-highlight)}.PropertyPanelBaseInput-module__Root--fKd55:focus,.PropertyPanelBaseInput-module__Root--fKd55.PropertyPanelBaseInput-module__is-faux-focused--d_8gG{background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-highlight);outline:none}.PropertyPanelBaseInput-module__Root--fKd55.PropertyPanelBaseInput-module__is-changed--ev1sv{color:var(--theme-color-fg-highlight)}.PropertyPanelBaseInput-module__Root--fKd55.PropertyPanelBaseInput-module__is-connected--AYzwn{outline:1px solid var(--theme-color-primary-dim)}.PropertyPanelBaseInput-module__Root--fKd55.PropertyPanelBaseInput-module__has-hidden-caret--oTasu{caret-color:rgba(0,0,0,0)}.PropertyPanelBaseInput-module__Root--fKd55[type=number]{-moz-appearance:textfield}.PropertyPanelBaseInput-module__Root--fKd55[type=number]::-webkit-outer-spin-button,.PropertyPanelBaseInput-module__Root--fKd55[type=number]::-webkit-inner-spin-button{appearance:none;margin:0}.PropertyPanelBaseInput-module__Root--fKd55.PropertyPanelBaseInput-module__has-small-text--JHavQ{font-size:10px;padding-left:4px;padding-right:4px;text-align:center}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/property-panel/PropertyPanelBaseInput/PropertyPanelBaseInput.module.scss","webpack://./../noodl-core-ui/src/styles/scss-variables/length.scss"],"names":[],"mappings":"AAEA,4CACE,8BAAA,CACA,mCAAA,CACA,wCAAA,CACA,aAAA,CACA,WAAA,CACA,mBCR6B,CDS7B,UAAA,CACA,qBAAA,CACA,cAAA,CACA,uEAAA,CAEA,kDACE,qCAAA,CAGF,oJAEE,wCAAA,CACA,qCAAA,CACA,YAAA,CAGF,6FACE,qCAAA,CAGF,+FACE,gDAAA,CAGF,mGACE,yBAAA,CAGF,yDACE,yBAAA,CAEA,wKAEE,eAAA,CACA,QAAA,CAIJ,iGACE,cAAA,CACA,gBC/C8B,CDgD9B,iBChD8B,CDiD9B,iBAAA","sourcesContent":["@use '../../../styles/scss-variables/length.scss';\n\n.Root {\n  font-family: var(--font-family);\n  color: var(--theme-color-fg-default);\n  background-color: var(--theme-color-bg-3);\n  line-height: 1;\n  border: none;\n  padding: length.$property-panel-input-padding;\n  width: 100%;\n  box-sizing: border-box;\n  font-size: 12px;\n  transition: background-color var(--speed-turbo), color var(--speed-turbo);\n\n  &:hover {\n    color: var(--theme-color-fg-highlight);\n  }\n\n  &:focus,\n  &.is-faux-focused {\n    background-color: var(--theme-color-bg-1);\n    color: var(--theme-color-fg-highlight);\n    outline: none;\n  }\n\n  &.is-changed {\n    color: var(--theme-color-fg-highlight);\n  }\n\n  &.is-connected {\n    outline: 1px solid var(--theme-color-primary-dim);\n  }\n\n  &.has-hidden-caret {\n    caret-color: transparent;\n  }\n\n  &[type='number'] {\n    -moz-appearance: textfield;\n\n    &::-webkit-outer-spin-button,\n    &::-webkit-inner-spin-button {\n      appearance: none;\n      margin: 0;\n    }\n  }\n\n  &.has-small-text {\n    font-size: 10px;\n    padding-left: length.$property-panel-small-xy-padding;\n    padding-right: length.$property-panel-small-xy-padding;\n    text-align: center;\n  }\n}\n","$property-panel-input-padding: 6px 8px 7px;\r\n$property-panel-input-size: 28px;\r\n$property-panel-small-xy-padding: 4px;\r\n\r\n$global-input-size: 36px;\r\n$global-input-size-small: 28px;\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `PropertyPanelBaseInput-module__Root--fKd55`,
	"is-faux-focused": `PropertyPanelBaseInput-module__is-faux-focused--d_8gG`,
	"is-changed": `PropertyPanelBaseInput-module__is-changed--ev1sv`,
	"is-connected": `PropertyPanelBaseInput-module__is-connected--AYzwn`,
	"has-hidden-caret": `PropertyPanelBaseInput-module__has-hidden-caret--oTasu`,
	"has-small-text": `PropertyPanelBaseInput-module__has-small-text--JHavQ`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 88128:
/***/ ((module) => {

"use strict";


var memo = {};

/* istanbul ignore next  */
function getTarget(target) {
  if (typeof memo[target] === "undefined") {
    var styleTarget = document.querySelector(target);

    // Special case to return head of iframe instead of iframe itself
    if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
      try {
        // This will throw an exception if access to iframe is blocked
        // due to cross-origin restrictions
        styleTarget = styleTarget.contentDocument.head;
      } catch (e) {
        // istanbul ignore next
        styleTarget = null;
      }
    }
    memo[target] = styleTarget;
  }
  return memo[target];
}

/* istanbul ignore next  */
function insertBySelector(insert, style) {
  var target = getTarget(insert);
  if (!target) {
    throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
  }
  target.appendChild(style);
}
module.exports = insertBySelector;

/***/ }),

/***/ 88159:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DEFAULT_SUMMARY_PROMPT = exports.DEFAULT_TOKEN_THRESHOLD = void 0;
exports.DEFAULT_TOKEN_THRESHOLD = 100000;
exports.DEFAULT_SUMMARY_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
1. Task Overview
The user's core request and success criteria
Any clarifications or constraints they specified
2. Current State
What has been completed so far
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.`;
//# sourceMappingURL=CompactionControl.js.map

/***/ }),

/***/ 88382:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgQuestionFree = function SvgQuestionFree(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M11.9999 18.1304C12.6198 18.1304 13.1223 17.6279 13.1223 17.008C13.1223 16.3881 12.6198 15.8855 11.9999 15.8855C11.38 15.8855 10.8774 16.3881 10.8774 17.008C10.8774 17.6279 11.38 18.1304 11.9999 18.1304Z",
    fill: "#B8B8B8"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M10.7115 6.65385C11.3268 6.39898 12.0039 6.3323 12.6571 6.46223C13.3103 6.59216 13.9103 6.91286 14.3812 7.3838C14.8522 7.85473 15.1729 8.45473 15.3028 9.10793C15.4327 9.76113 15.366 10.4382 15.1112 11.0535C14.8563 11.6688 14.4247 12.1947 13.871 12.5647C13.5276 12.7941 13.1469 12.9572 12.7485 13.048V14.1205C12.7485 14.5338 12.4134 14.8688 12.0002 14.8688C11.5869 14.8688 11.2519 14.5338 11.2519 14.1205V12.3839C11.2519 12.1855 11.3307 11.9951 11.471 11.8548C11.6114 11.7145 11.8017 11.6356 12.0002 11.6356C12.3702 11.6356 12.7318 11.5259 13.0395 11.3203C13.3471 11.1148 13.5869 10.8226 13.7285 10.4808C13.8701 10.1389 13.9071 9.76279 13.835 9.3999C13.7628 9.03701 13.5846 8.70368 13.323 8.44205C13.0613 8.18042 12.728 8.00225 12.3651 7.93007C12.0022 7.85788 11.6261 7.89493 11.2843 8.03652C10.9424 8.17812 10.6502 8.41789 10.4447 8.72554C10.2391 9.03318 10.1294 9.39487 10.1294 9.76487C10.1294 10.1781 9.79439 10.5132 9.38111 10.5132C8.96784 10.5132 8.63281 10.1781 8.63281 9.76487C8.63281 9.09887 8.8303 8.44783 9.20031 7.89407C9.57032 7.34031 10.0962 6.90871 10.7115 6.65385Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgQuestionFree);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "3071641a506ded9e18d6bba0acc46aaa.svg");

/***/ }),

/***/ 88514:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _BaseAnthropic_instances, _a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Anthropic = exports.BaseAnthropic = exports.AI_PROMPT = exports.HUMAN_PROMPT = void 0;
const tslib_1 = __webpack_require__(84499);
const uuid_1 = __webpack_require__(80730);
const values_1 = __webpack_require__(25267);
const sleep_1 = __webpack_require__(31714);
const errors_1 = __webpack_require__(29820);
const detect_platform_1 = __webpack_require__(9638);
const Shims = tslib_1.__importStar(__webpack_require__(59081));
const Opts = tslib_1.__importStar(__webpack_require__(31325));
const version_1 = __webpack_require__(36377);
const Errors = tslib_1.__importStar(__webpack_require__(37015));
const Pagination = tslib_1.__importStar(__webpack_require__(92081));
const Uploads = tslib_1.__importStar(__webpack_require__(89951));
const API = tslib_1.__importStar(__webpack_require__(50935));
const api_promise_1 = __webpack_require__(15845);
const completions_1 = __webpack_require__(50856);
const models_1 = __webpack_require__(60193);
const beta_1 = __webpack_require__(82306);
const messages_1 = __webpack_require__(41350);
const detect_platform_2 = __webpack_require__(9638);
const headers_1 = __webpack_require__(79973);
const env_1 = __webpack_require__(39810);
const log_1 = __webpack_require__(59347);
const values_2 = __webpack_require__(25267);
exports.HUMAN_PROMPT = '\\n\\nHuman:';
exports.AI_PROMPT = '\\n\\nAssistant:';
/**
 * Base class for Anthropic API clients.
 */
class BaseAnthropic {
    /**
     * API Client for interfacing with the Anthropic API.
     *
     * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
     * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
     * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
     * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
     * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
     * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
     * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
     * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
     * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
     * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
     */
    constructor({ baseURL = (0, env_1.readEnv)('ANTHROPIC_BASE_URL'), apiKey = (0, env_1.readEnv)('ANTHROPIC_API_KEY') ?? null, authToken = (0, env_1.readEnv)('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) {
        _BaseAnthropic_instances.add(this);
        _BaseAnthropic_encoder.set(this, void 0);
        const options = {
            apiKey,
            authToken,
            ...opts,
            baseURL: baseURL || `https://api.anthropic.com`,
        };
        if (!options.dangerouslyAllowBrowser && (0, detect_platform_2.isRunningInBrowser)()) {
            throw new Errors.AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
        }
        this.baseURL = options.baseURL;
        this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;
        this.logger = options.logger ?? console;
        const defaultLogLevel = 'warn';
        // Set default logLevel early so that we can log a warning in parseLogLevel.
        this.logLevel = defaultLogLevel;
        this.logLevel =
            (0, log_1.parseLogLevel)(options.logLevel, 'ClientOptions.logLevel', this) ??
                (0, log_1.parseLogLevel)((0, env_1.readEnv)('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ??
                defaultLogLevel;
        this.fetchOptions = options.fetchOptions;
        this.maxRetries = options.maxRetries ?? 2;
        this.fetch = options.fetch ?? Shims.getDefaultFetch();
        tslib_1.__classPrivateFieldSet(this, _BaseAnthropic_encoder, Opts.FallbackEncoder, "f");
        this._options = options;
        this.apiKey = typeof apiKey === 'string' ? apiKey : null;
        this.authToken = authToken;
    }
    /**
     * Create a new client instance re-using the same options given to the current client with optional overriding.
     */
    withOptions(options) {
        const client = new this.constructor({
            ...this._options,
            baseURL: this.baseURL,
            maxRetries: this.maxRetries,
            timeout: this.timeout,
            logger: this.logger,
            logLevel: this.logLevel,
            fetch: this.fetch,
            fetchOptions: this.fetchOptions,
            apiKey: this.apiKey,
            authToken: this.authToken,
            ...options,
        });
        return client;
    }
    defaultQuery() {
        return this._options.defaultQuery;
    }
    validateHeaders({ values, nulls }) {
        if (values.get('x-api-key') || values.get('authorization')) {
            return;
        }
        if (this.apiKey && values.get('x-api-key')) {
            return;
        }
        if (nulls.has('x-api-key')) {
            return;
        }
        if (this.authToken && values.get('authorization')) {
            return;
        }
        if (nulls.has('authorization')) {
            return;
        }
        throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
    }
    async authHeaders(opts) {
        return (0, headers_1.buildHeaders)([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
    }
    async apiKeyAuth(opts) {
        if (this.apiKey == null) {
            return undefined;
        }
        return (0, headers_1.buildHeaders)([{ 'X-Api-Key': this.apiKey }]);
    }
    async bearerAuth(opts) {
        if (this.authToken == null) {
            return undefined;
        }
        return (0, headers_1.buildHeaders)([{ Authorization: `Bearer ${this.authToken}` }]);
    }
    /**
     * Basic re-implementation of `qs.stringify` for primitive types.
     */
    stringifyQuery(query) {
        return Object.entries(query)
            .filter(([_, value]) => typeof value !== 'undefined')
            .map(([key, value]) => {
            if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
                return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
            }
            if (value === null) {
                return `${encodeURIComponent(key)}=`;
            }
            throw new Errors.AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
        })
            .join('&');
    }
    getUserAgent() {
        return `${this.constructor.name}/JS ${version_1.VERSION}`;
    }
    defaultIdempotencyKey() {
        return `stainless-node-retry-${(0, uuid_1.uuid4)()}`;
    }
    makeStatusError(status, error, message, headers) {
        return Errors.APIError.generate(status, error, message, headers);
    }
    buildURL(path, query, defaultBaseURL) {
        const baseURL = (!tslib_1.__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
        const url = (0, values_1.isAbsoluteURL)(path) ?
            new URL(path)
            : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
        const defaultQuery = this.defaultQuery();
        if (!(0, values_2.isEmptyObj)(defaultQuery)) {
            query = { ...defaultQuery, ...query };
        }
        if (typeof query === 'object' && query && !Array.isArray(query)) {
            url.search = this.stringifyQuery(query);
        }
        return url.toString();
    }
    _calculateNonstreamingTimeout(maxTokens) {
        const defaultTimeout = 10 * 60;
        const expectedTimeout = (60 * 60 * maxTokens) / 128000;
        if (expectedTimeout > defaultTimeout) {
            throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' +
                'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details');
        }
        return defaultTimeout * 1000;
    }
    /**
     * Used as a callback for mutating the given `FinalRequestOptions` object.
     */
    async prepareOptions(options) { }
    /**
     * Used as a callback for mutating the given `RequestInit` object.
     *
     * This is useful for cases where you want to add certain headers based off of
     * the request properties, e.g. `method` or `url`.
     */
    async prepareRequest(request, { url, options }) { }
    get(path, opts) {
        return this.methodRequest('get', path, opts);
    }
    post(path, opts) {
        return this.methodRequest('post', path, opts);
    }
    patch(path, opts) {
        return this.methodRequest('patch', path, opts);
    }
    put(path, opts) {
        return this.methodRequest('put', path, opts);
    }
    delete(path, opts) {
        return this.methodRequest('delete', path, opts);
    }
    methodRequest(method, path, opts) {
        return this.request(Promise.resolve(opts).then((opts) => {
            return { method, path, ...opts };
        }));
    }
    request(options, remainingRetries = null) {
        return new api_promise_1.APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
    }
    async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
        const options = await optionsInput;
        const maxRetries = options.maxRetries ?? this.maxRetries;
        if (retriesRemaining == null) {
            retriesRemaining = maxRetries;
        }
        await this.prepareOptions(options);
        const { req, url, timeout } = await this.buildRequest(options, {
            retryCount: maxRetries - retriesRemaining,
        });
        await this.prepareRequest(req, { url, options });
        /** Not an API request ID, just for correlating local log entries. */
        const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
        const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
        const startTime = Date.now();
        (0, log_1.loggerFor)(this).debug(`[${requestLogID}] sending request`, (0, log_1.formatRequestDetails)({
            retryOfRequestLogID,
            method: options.method,
            url,
            options,
            headers: req.headers,
        }));
        if (options.signal?.aborted) {
            throw new Errors.APIUserAbortError();
        }
        const controller = new AbortController();
        const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(errors_1.castToError);
        const headersTime = Date.now();
        if (response instanceof globalThis.Error) {
            const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
            if (options.signal?.aborted) {
                throw new Errors.APIUserAbortError();
            }
            // detect native connection timeout errors
            // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
            // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
            // others do not provide enough information to distinguish timeouts from other connection errors
            const isTimeout = (0, errors_1.isAbortError)(response) ||
                /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
            if (retriesRemaining) {
                (0, log_1.loggerFor)(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
                (0, log_1.loggerFor)(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, (0, log_1.formatRequestDetails)({
                    retryOfRequestLogID,
                    url,
                    durationMs: headersTime - startTime,
                    message: response.message,
                }));
                return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
            }
            (0, log_1.loggerFor)(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
            (0, log_1.loggerFor)(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, (0, log_1.formatRequestDetails)({
                retryOfRequestLogID,
                url,
                durationMs: headersTime - startTime,
                message: response.message,
            }));
            if (isTimeout) {
                throw new Errors.APIConnectionTimeoutError();
            }
            throw new Errors.APIConnectionError({ cause: response });
        }
        const specialHeaders = [...response.headers.entries()]
            .filter(([name]) => name === 'request-id')
            .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))
            .join('');
        const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
        if (!response.ok) {
            const shouldRetry = await this.shouldRetry(response);
            if (retriesRemaining && shouldRetry) {
                const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
                // We don't need the body of this response.
                await Shims.CancelReadableStream(response.body);
                (0, log_1.loggerFor)(this).info(`${responseInfo} - ${retryMessage}`);
                (0, log_1.loggerFor)(this).debug(`[${requestLogID}] response error (${retryMessage})`, (0, log_1.formatRequestDetails)({
                    retryOfRequestLogID,
                    url: response.url,
                    status: response.status,
                    headers: response.headers,
                    durationMs: headersTime - startTime,
                }));
                return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
            }
            const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
            (0, log_1.loggerFor)(this).info(`${responseInfo} - ${retryMessage}`);
            const errText = await response.text().catch((err) => (0, errors_1.castToError)(err).message);
            const errJSON = (0, values_1.safeJSON)(errText);
            const errMessage = errJSON ? undefined : errText;
            (0, log_1.loggerFor)(this).debug(`[${requestLogID}] response error (${retryMessage})`, (0, log_1.formatRequestDetails)({
                retryOfRequestLogID,
                url: response.url,
                status: response.status,
                headers: response.headers,
                message: errMessage,
                durationMs: Date.now() - startTime,
            }));
            const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
            throw err;
        }
        (0, log_1.loggerFor)(this).info(responseInfo);
        (0, log_1.loggerFor)(this).debug(`[${requestLogID}] response start`, (0, log_1.formatRequestDetails)({
            retryOfRequestLogID,
            url: response.url,
            status: response.status,
            headers: response.headers,
            durationMs: headersTime - startTime,
        }));
        return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
    }
    getAPIList(path, Page, opts) {
        return this.requestAPIList(Page, { method: 'get', path, ...opts });
    }
    requestAPIList(Page, options) {
        const request = this.makeRequest(options, null, undefined);
        return new Pagination.PagePromise(this, request, Page);
    }
    async fetchWithTimeout(url, init, ms, controller) {
        const { signal, method, ...options } = init || {};
        if (signal)
            signal.addEventListener('abort', () => controller.abort());
        const timeout = setTimeout(() => controller.abort(), ms);
        const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
            (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
        const fetchOptions = {
            signal: controller.signal,
            ...(isReadableBody ? { duplex: 'half' } : {}),
            method: 'GET',
            ...options,
        };
        if (method) {
            // Custom methods like 'patch' need to be uppercased
            // See https://github.com/nodejs/undici/issues/2294
            fetchOptions.method = method.toUpperCase();
        }
        try {
            // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
            return await this.fetch.call(undefined, url, fetchOptions);
        }
        finally {
            clearTimeout(timeout);
        }
    }
    async shouldRetry(response) {
        // Note this is not a standard header.
        const shouldRetryHeader = response.headers.get('x-should-retry');
        // If the server explicitly says whether or not to retry, obey.
        if (shouldRetryHeader === 'true')
            return true;
        if (shouldRetryHeader === 'false')
            return false;
        // Retry on request timeouts.
        if (response.status === 408)
            return true;
        // Retry on lock timeouts.
        if (response.status === 409)
            return true;
        // Retry on rate limits.
        if (response.status === 429)
            return true;
        // Retry internal errors.
        if (response.status >= 500)
            return true;
        return false;
    }
    async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
        let timeoutMillis;
        // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
        const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
        if (retryAfterMillisHeader) {
            const timeoutMs = parseFloat(retryAfterMillisHeader);
            if (!Number.isNaN(timeoutMs)) {
                timeoutMillis = timeoutMs;
            }
        }
        // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
        const retryAfterHeader = responseHeaders?.get('retry-after');
        if (retryAfterHeader && !timeoutMillis) {
            const timeoutSeconds = parseFloat(retryAfterHeader);
            if (!Number.isNaN(timeoutSeconds)) {
                timeoutMillis = timeoutSeconds * 1000;
            }
            else {
                timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
            }
        }
        // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
        // just do what it says, but otherwise calculate a default
        if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
            const maxRetries = options.maxRetries ?? this.maxRetries;
            timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
        }
        await (0, sleep_1.sleep)(timeoutMillis);
        return this.makeRequest(options, retriesRemaining - 1, requestLogID);
    }
    calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
        const initialRetryDelay = 0.5;
        const maxRetryDelay = 8.0;
        const numRetries = maxRetries - retriesRemaining;
        // Apply exponential backoff, but not more than the max.
        const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
        // Apply some jitter, take up to at most 25 percent of the retry time.
        const jitter = 1 - Math.random() * 0.25;
        return sleepSeconds * jitter * 1000;
    }
    calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
        const maxTime = 60 * 60 * 1000; // 60 minutes
        const defaultTime = 60 * 10 * 1000; // 10 minutes
        const expectedTime = (maxTime * maxTokens) / 128000;
        if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) {
            throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details');
        }
        return defaultTime;
    }
    async buildRequest(inputOptions, { retryCount = 0 } = {}) {
        const options = { ...inputOptions };
        const { method, path, query, defaultBaseURL } = options;
        const url = this.buildURL(path, query, defaultBaseURL);
        if ('timeout' in options)
            (0, values_1.validatePositiveInteger)('timeout', options.timeout);
        options.timeout = options.timeout ?? this.timeout;
        const { bodyHeaders, body } = this.buildBody({ options });
        const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
        const req = {
            method,
            headers: reqHeaders,
            ...(options.signal && { signal: options.signal }),
            ...(globalThis.ReadableStream &&
                body instanceof globalThis.ReadableStream && { duplex: 'half' }),
            ...(body && { body }),
            ...(this.fetchOptions ?? {}),
            ...(options.fetchOptions ?? {}),
        };
        return { req, url, timeout: options.timeout };
    }
    async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
        let idempotencyHeaders = {};
        if (this.idempotencyHeader && method !== 'get') {
            if (!options.idempotencyKey)
                options.idempotencyKey = this.defaultIdempotencyKey();
            idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
        }
        const headers = (0, headers_1.buildHeaders)([
            idempotencyHeaders,
            {
                Accept: 'application/json',
                'User-Agent': this.getUserAgent(),
                'X-Stainless-Retry-Count': String(retryCount),
                ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
                ...(0, detect_platform_1.getPlatformHeaders)(),
                ...(this._options.dangerouslyAllowBrowser ?
                    { 'anthropic-dangerous-direct-browser-access': 'true' }
                    : undefined),
                'anthropic-version': '2023-06-01',
            },
            await this.authHeaders(options),
            this._options.defaultHeaders,
            bodyHeaders,
            options.headers,
        ]);
        this.validateHeaders(headers);
        return headers.values;
    }
    buildBody({ options: { body, headers: rawHeaders } }) {
        if (!body) {
            return { bodyHeaders: undefined, body: undefined };
        }
        const headers = (0, headers_1.buildHeaders)([rawHeaders]);
        if (
        // Pass raw type verbatim
        ArrayBuffer.isView(body) ||
            body instanceof ArrayBuffer ||
            body instanceof DataView ||
            (typeof body === 'string' &&
                // Preserve legacy string encoding behavior for now
                headers.values.has('content-type')) ||
            // `Blob` is superset of `File`
            (globalThis.Blob && body instanceof globalThis.Blob) ||
            // `FormData` -> `multipart/form-data`
            body instanceof FormData ||
            // `URLSearchParams` -> `application/x-www-form-urlencoded`
            body instanceof URLSearchParams ||
            // Send chunked stream (each chunk has own `length`)
            (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
            return { bodyHeaders: undefined, body: body };
        }
        else if (typeof body === 'object' &&
            (Symbol.asyncIterator in body ||
                (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
            return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };
        }
        else {
            return tslib_1.__classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
        }
    }
}
exports.BaseAnthropic = BaseAnthropic;
_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() {
    return this.baseURL !== 'https://api.anthropic.com';
};
BaseAnthropic.Anthropic = _a;
BaseAnthropic.HUMAN_PROMPT = exports.HUMAN_PROMPT;
BaseAnthropic.AI_PROMPT = exports.AI_PROMPT;
BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes
BaseAnthropic.AnthropicError = Errors.AnthropicError;
BaseAnthropic.APIError = Errors.APIError;
BaseAnthropic.APIConnectionError = Errors.APIConnectionError;
BaseAnthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
BaseAnthropic.APIUserAbortError = Errors.APIUserAbortError;
BaseAnthropic.NotFoundError = Errors.NotFoundError;
BaseAnthropic.ConflictError = Errors.ConflictError;
BaseAnthropic.RateLimitError = Errors.RateLimitError;
BaseAnthropic.BadRequestError = Errors.BadRequestError;
BaseAnthropic.AuthenticationError = Errors.AuthenticationError;
BaseAnthropic.InternalServerError = Errors.InternalServerError;
BaseAnthropic.PermissionDeniedError = Errors.PermissionDeniedError;
BaseAnthropic.UnprocessableEntityError = Errors.UnprocessableEntityError;
BaseAnthropic.toFile = Uploads.toFile;
/**
 * API Client for interfacing with the Anthropic API.
 */
class Anthropic extends BaseAnthropic {
    constructor() {
        super(...arguments);
        this.completions = new API.Completions(this);
        this.messages = new API.Messages(this);
        this.models = new API.Models(this);
        this.beta = new API.Beta(this);
    }
}
exports.Anthropic = Anthropic;
Anthropic.Completions = completions_1.Completions;
Anthropic.Messages = messages_1.Messages;
Anthropic.Models = models_1.Models;
Anthropic.Beta = beta_1.Beta;
//# sourceMappingURL=client.js.map

/***/ }),

/***/ 88569:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  j: () => (/* reexport */ HtmlRenderer)
});

// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/common/HtmlRenderer/HtmlRenderer.module.scss
var HtmlRenderer_module = __webpack_require__(57534);
;// ../noodl-core-ui/src/components/common/HtmlRenderer/HtmlRenderer.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(HtmlRenderer_module/* default */.A, options);




       /* harmony default export */ const HtmlRenderer_HtmlRenderer_module = (HtmlRenderer_module/* default */.A && HtmlRenderer_module/* default */.A.locals ? HtmlRenderer_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/common/HtmlRenderer/HtmlRenderer.tsx


function HtmlRenderer({ html }) {
    return external_react_default().createElement("div", { className: HtmlRenderer_HtmlRenderer_module['Root'], dangerouslySetInnerHTML: { __html: html } });
}

;// ../noodl-core-ui/src/components/common/HtmlRenderer/index.ts



/***/ }),

/***/ 88575:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const {
  ipcRenderer
} = __webpack_require__(91288);
const {
  useEffect
} = __webpack_require__(54953);
const React = __webpack_require__(54953);
const PopupLayer = __webpack_require__(45653);
const LessonItem = __webpack_require__(52838);
const {
  EventDispatcher
} = __webpack_require__(11138);
__webpack_require__(8717);
function LessonLayerView({
  steps,
  currentStepIndex
}) {
  if (!steps) return null; //steps are probably still being fetched

  const currentStep = steps && steps[currentStepIndex];
  useEffect(() => {
    //the first step has no item in the bottom bar, it's just a popup. Show it when selected
    const showPopupStep = currentStep && !currentStep.itemContent && currentStep.popupContent;
    if (!showPopupStep) return;
    const popupContainer = document.createElement('div');
    popupContainer.className = 'lesson-item-popup';
    popupContainer.appendChild(currentStep.popupContent);
    let videos = [];
    PopupLayer.instance.showModal({
      content: {
        el: $(popupContainer)
      },
      position: 'screen-center',
      onClose() {
        ipcRenderer.send('viewer-show');
        //pause videos, otherwise they run in the background and consume resources
        videos.forEach(video => {
          video.stop();
        });
      }
    });

    //make sure any videos start playing
    videos = popupContainer.querySelectorAll('video');
    videos.forEach(video => {
      video.play();
    });
    ipcRenderer.send('viewer-hide');
  }, [currentStep]);
  const errors = steps.filter(step => step.error).map(step => step.error);
  let errorMsg = null;
  if (errors.length) {
    errorMsg = /*#__PURE__*/React.createElement("div", {
      style: {
        padding: '5px',
        backgroundColor: 'red',
        color: 'white',
        fontSize: '14px'
      }
    }, errors.map((e, i) => /*#__PURE__*/React.createElement("div", {
      key: i,
      style: {
        userSelect: 'text',
        cursor: 'text'
      }
    }, e)));
  }
  return /*#__PURE__*/React.createElement("div", {
    className: "lesson-bottombar"
  }, errorMsg, /*#__PURE__*/React.createElement("div", {
    className: "lesson-steps"
  }, steps.map((step, i) => {
    if (!step.itemContent) return null;
    const hasConditions = step.conditions && step.conditions.length ? true : false;
    return /*#__PURE__*/React.createElement(LessonItem, {
      key: i,
      itemContent: step.itemContent,
      hasNextButton: step.hasNextButton,
      popupContent: step.popupContent,
      isSelected: currentStepIndex === i,
      isComplete: step.isComplete,
      stepWidth: step.width,
      showPopupWhenSelected: hasConditions === false,
      performActions: () => performActions(step.actions)
    });
  })), /*#__PURE__*/React.createElement("div", {
    className: "lesson-layer-progressbar"
  }, /*#__PURE__*/React.createElement("div", {
    className: "lesson-layer-progressbar-fill",
    style: {
      width: calculateProgress(steps, currentStepIndex) * 100 + '%'
    }
  })));
}

//For the progress bar we're only concered with items in the bar, not steps that only show a popup and no item.
//Calculate progress by just excluding them
function calculateProgress(steps, currentStepIndex) {
  const progressTotalSteps = steps.filter(step => step.itemContent ? true : false).length;
  let progressCurrentStep = currentStepIndex;
  for (let i = 0; i < currentStepIndex; i++) {
    if (!steps[i].itemContent) {
      progressCurrentStep--;
    }
  }
  return progressCurrentStep / (progressTotalSteps - 1); //Minus one so the last step will result in progress being 1
}
function performActions(actions) {
  if (!actions?.length) return;
  for (const action of actions) {
    performAction(action);
  }
}
function performAction(action) {
  switch (action.action) {
    case 'selectNode':
      EventDispatcher.instance.emit('inspectNodes', {
        nodeIds: [action.nodeId]
      });
      break;
    case 'navigatePreview':
      EventDispatcher.instance.emit('setPreviewRoute', {
        url: action.url
      });
      break;
    case 'selectComponent':
      EventDispatcher.instance.emit('selectComponent', {
        componentName: action.componentName
      });
      break;
  }
}
module.exports = LessonLayerView;

/***/ }),

/***/ 88612:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_visualstates_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(27694);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_visualstates_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_visualstates_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_visualstates_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_visualstates_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 88957:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgGrip = function SvgGrip(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 30,
    height: 30,
    viewBox: "0 0 30 30",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M28 29.2929L29.2929 28",
    stroke: "#9F9F9F"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M24 29.2929L29.2929 24",
    stroke: "#9F9F9F"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M20 29.2929L29.2929 20",
    stroke: "#9F9F9F"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgGrip);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "752829ee13d1ee3bafca96fe095b1a96.svg");

/***/ }),

/***/ 89147:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgJustifyContentSpaceBetween = function SvgJustifyContentSpaceBetween(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.457 5.61365H8.26953C7.90709 5.61365 7.61328 5.86948 7.61328 6.18508V9.04222C7.61328 9.35781 7.90709 9.61365 8.26953 9.61365H17.457C17.8195 9.61365 18.1133 9.35781 18.1133 9.04222V6.18508C18.1133 5.86948 17.8195 5.61365 17.457 5.61365Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M8.26953 19.7386L17.457 19.7386C17.8195 19.7386 18.1133 19.4828 18.1133 19.1672L18.1133 16.3101C18.1133 15.9945 17.8195 15.7386 17.457 15.7386L8.26953 15.7386C7.90709 15.7386 7.61328 15.9945 7.61328 16.3101L7.61328 19.1672C7.61328 19.4828 7.90709 19.7386 8.26953 19.7386Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.86328 3.36365C3.86328 2.94943 4.22146 2.61365 4.6633 2.61365H21.0633C21.5051 2.61365 21.8633 2.94943 21.8633 3.36365C21.8633 3.77786 21.5051 4.11365 21.0633 4.11365H4.6633C4.22146 4.11365 3.86328 3.77786 3.86328 3.36365Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.8633 21.9886C21.8633 22.4029 21.5051 22.7386 21.0633 22.7386L4.66331 22.7386C4.22147 22.7386 3.86328 22.4029 3.86328 21.9886C3.86328 21.5744 4.22147 21.2386 4.66331 21.2386L21.0633 21.2386C21.5051 21.2386 21.8633 21.5744 21.8633 21.9886Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgJustifyContentSpaceBetween);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "ac8247c0be05fcb8950ee4fe89bcec89.svg");

/***/ }),

/***/ 89330:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const React = __webpack_require__(54953);
const {
  useState,
  useEffect
} = React;
const {
  propertyFromPort
} = __webpack_require__(11793);
function TextStylePopup(props) {
  const [styleName, setStyleName] = useState(props.style.name);
  const [style, setStyle] = useState(props.style.style);
  const stylesModel = props.stylesModel;
  useEffect(() => {
    const eventGroup = {};
    stylesModel.on('styleRenamed', event => {
      if (event.oldName === styleName) {
        setStyleName(event.name);
      }
    }, eventGroup);
    stylesModel.on('styleChanged', event => {
      if (event.name === styleName) {
        setStyle(event.style);
      }
    }, eventGroup);
    return () => {
      stylesModel.off(eventGroup);
    };
  }, [styleName]);

  //TODO: get from node library
  const properties = [{
    name: 'fontFamily',
    displayName: 'Font Family',
    type: 'font'
  }, {
    name: 'fontSize',
    displayName: 'Font Size',
    type: {
      name: 'number',
      units: ['px']
    }
  }, {
    name: 'color',
    displayName: 'Color',
    type: 'color'
  }, {
    name: 'letterSpacing',
    displayName: 'Letter Spacing',
    type: {
      name: 'number',
      units: ['px', 'em']
    }
  }, {
    name: 'lineHeight',
    displayName: 'Line Height',
    type: {
      name: 'number',
      units: ['', 'px', '%']
    }
  }, {
    name: 'textTransform',
    displayName: 'Case',
    type: {
      name: 'enum',
      enums: [{
        label: 'None',
        value: 'none'
      }, {
        label: 'Uppercase',
        value: 'uppercase'
      }, {
        label: 'Lowercase',
        value: 'lowercase'
      }, {
        label: 'Capitalize',
        value: 'capitalize'
      }]
    }
  }];
  const setStyleProperty = (name, value) => {
    const newStyle = {
      ...style
    };
    if (value === '') {
      delete newStyle[name];
    } else {
      newStyle[name] = value;
    }
    stylesModel.setStyle('text', styleName, newStyle, {
      undo: true,
      label: 'change text style'
    });
  };
  return /*#__PURE__*/React.createElement("div", {
    style: {
      padding: '10px'
    }
  }, properties.map(prop => propertyFromPort(prop, style[prop.name], newValue => setStyleProperty(prop.name, newValue))));
}
module.exports = TextStylePopup;

/***/ }),

/***/ 89398:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   c: () => (/* binding */ TitleBar)
/* harmony export */ });
/* harmony import */ var _noodl_models_warningsmodel__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(86105);

class TitleBar {
    constructor() {
        this.warningsAmount = 0;
        this.allWarnings = [];
        var _this = this;
        // Watch for the project changed on file system and ask user to reload
        /* EventDispatcher.instance.on('ProjectModel.changedOnFileSystem',function() {
          _this.projectChangedOnFileSystem();
        }); */
        _noodl_models_warningsmodel__WEBPACK_IMPORTED_MODULE_0__/* .WarningsModel */ .l.instance.on('warningsChanged', function () {
            if (!_this.warningsComponent)
                return;
            _this.getWarningsAmount(_this.warningsComponent);
            _this.allWarnings = _this.getAllWarnings();
        });
    }
    getWarningsAmount(c) {
        this.warningsComponent = c;
        var warnings = _noodl_models_warningsmodel__WEBPACK_IMPORTED_MODULE_0__/* .WarningsModel */ .l.instance.getNumberOfWarningsForComponent(c, {
            levels: ['error', 'warning'],
            excludeGlobal: true
        });
        warnings += _noodl_models_warningsmodel__WEBPACK_IMPORTED_MODULE_0__/* .WarningsModel */ .l.instance.getNumberOfWarningsForComponent(undefined, { levels: ['error', 'warning'] }); // Include warnings for the project level
        warnings += _noodl_models_warningsmodel__WEBPACK_IMPORTED_MODULE_0__/* .WarningsModel */ .l.instance.getTotalNumberOfWarningsMatching((key, ref, warning) => warning.warning.showGlobally);
        this.warningsAmount = warnings;
    }
    getWarningsForComponent(component) {
        const warnings = [];
        // Get all warnings for this selector
        _noodl_models_warningsmodel__WEBPACK_IMPORTED_MODULE_0__/* .WarningsModel */ .l.instance.forEachWarningInComponent(component, (warning) => {
            //don't render conflicts since they're rendered separately
            if (!warning.warning.showGlobally) {
                warnings.push(warning);
            }
        }, { levels: ['error', 'warning'] });
        return warnings;
    }
    getAllWarnings() {
        if (!this.warningsComponent)
            return [];
        const projectWideWarnings = this.getWarningsForComponent();
        const componentSpecificWarnings = [];
        _noodl_models_warningsmodel__WEBPACK_IMPORTED_MODULE_0__/* .WarningsModel */ .l.instance.forEachWarning((c, ref, key, warning) => {
            if (warning.warning.showGlobally) {
                componentSpecificWarnings.push(warning);
            }
        });
        const componentWarnings = this.getWarningsForComponent(this.warningsComponent);
        return [...projectWideWarnings, ...componentSpecificWarnings, ...componentWarnings];
    }
}
TitleBar.instance = new TitleBar();


/***/ }),

/***/ 89523:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   I: () => (/* binding */ getTopLevelWorkingDirectory),
/* harmony export */   ho: () => (/* binding */ open)
/* harmony export */ });
/* unused harmony export isGitRepository */
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16928);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81882);
/* harmony import */ var dugite__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(dugite__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(85869);



async function open(basePath) {
    // const path = await NodeGit.Repository.discover(this._baseDir, 0, '')
    // this.repository = await NodeGit.Repository.open(path)
    // await this._setupRepository();
    //
    // // Check for conflicts
    // try {
    //   let index = await this.repository.index();
    //   if (index.hasConflicts()) {
    //     //just guess what's "ours" and "theirs", we don't really know what state the repo is in
    //     const filePaths = await this._solveConflicts(index, INDEX_STAGE_OURS, INDEX_STAGE_THEIRS);
    //     await Promise.all(filePaths.map(path => index.addByPath(path)));
    //     await index.write();
    //     await index.writeTree();
    //   }
    // } catch (e) {
    //   console.log("VCS error when opening project: " + e);
    // }
    // Find the relative git repository path
    const repositoryPath = await getTopLevelWorkingDirectory(basePath);
    return repositoryPath;
}
/**
 * Get the absolute path to the top level working directory.
 *
 * @param path The path to a presumptive Git repository, either the root
 *             of the repository or any path within that repository.
 *
 * @returns null if the path provided doesn't reside within a Git repository.
 */
async function getTopLevelWorkingDirectory(path) {
    let result;
    try {
        // Note, we use --show-cdup here instead of --show-toplevel because show-toplevel
        // dereferences symlinks and we want to resolve a path as closely as possible to
        // what the user gave us.
        result = await (0,_client__WEBPACK_IMPORTED_MODULE_2__/* .git */ .$)(['rev-parse', '--show-cdup'], path, 'getTopLevelWorkingDirectory', {
            successExitCodes: new Set([0, 128])
        });
    }
    catch (err) {
        if (err.code === dugite__WEBPACK_IMPORTED_MODULE_1__.RepositoryDoesNotExistErrorCode) {
            return null;
        }
        throw err;
    }
    // Exit code 128 means it was run in a directory that's not a git
    // repository.
    if (result.exitCode === 128) {
        return null;
    }
    const relativePath = result.output.toString().trim();
    // No output means we're already at the root
    if (!relativePath) {
        return path;
    }
    return path__WEBPACK_IMPORTED_MODULE_0__.resolve(path, relativePath);
}
/** Is the path a git repository? */
async function isGitRepository(path) {
    return (await getTopLevelWorkingDirectory(path)) !== null;
}


/***/ }),

/***/ 89587:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.DecisionDialog-module__DecisionDialog--Sojru{display:flex;flex-direction:column;align-items:center;gap:24px;padding:32px 24px 24px;max-width:550px;max-height:80vh}.DecisionDialog-module__Icon--SJEi0{display:flex;align-items:center;justify-content:center;width:64px;height:64px;border-radius:50%;color:var(--theme-color-bg-1);opacity:.9}.DecisionDialog-module__Icon--SJEi0[data-type=warning]{background:var(--theme-color-warning)}.DecisionDialog-module__Icon--SJEi0[data-type=help]{background:var(--theme-color-primary)}.DecisionDialog-module__Content--ctL7_{display:flex;flex-direction:column;gap:16px;width:100%;text-align:center;overflow-y:auto;max-height:calc(80vh - 200px)}.DecisionDialog-module__Content--ctL7_ h3{margin:0;font-size:18px;font-weight:600;color:var(--theme-color-fg-highlight)}.DecisionDialog-module__Content--ctL7_ h4{margin:0 0 8px 0;font-size:14px;font-weight:600;color:var(--theme-color-fg-highlight);text-align:left}.DecisionDialog-module__Content--ctL7_ strong{color:var(--theme-color-fg-highlight);font-weight:600}.DecisionDialog-module__CostInfo--IOJ2n{padding:12px;background:var(--theme-color-bg-3);border-radius:8px;border-left:3px solid var(--theme-color-warning)}.DecisionDialog-module__AttemptHistory--rnHch{display:flex;flex-direction:column;gap:8px;text-align:left}.DecisionDialog-module__Attempts--FDYTJ{display:flex;flex-direction:column;gap:8px;max-height:200px;overflow-y:auto}.DecisionDialog-module__Attempt--Sj6gU{padding:12px;background:var(--theme-color-bg-3);border-radius:6px;border:1px solid var(--theme-color-border-default)}.DecisionDialog-module__Attempt__Header--k31Lj{display:flex;justify-content:space-between;align-items:center;margin-bottom:6px}.DecisionDialog-module__Attempt__Number--nq3Hh{font-size:12px;font-weight:600;color:var(--theme-color-fg-default)}.DecisionDialog-module__Attempt__Cost--ukBcf{font-size:11px;font-weight:500;color:var(--theme-color-fg-default-shy);font-family:"SF Mono",Monaco,"Cascadia Code","Roboto Mono",Consolas,"Courier New",monospace}.DecisionDialog-module__Attempt__Error--EJ0i4{font-size:12px;line-height:1.4}.DecisionDialog-module__Options--yIuk6{margin-top:8px}.DecisionDialog-module__HelpContent--OZEBf{display:flex;flex-direction:column;gap:20px;text-align:left;padding:16px;background:var(--theme-color-bg-2);border-radius:8px;max-height:400px;overflow-y:auto}.DecisionDialog-module__HelpSection--apRQl{display:flex;flex-direction:column;gap:12px}.DecisionDialog-module__HelpSection--apRQl ul,.DecisionDialog-module__HelpSection--apRQl ol{margin:0;padding-left:20px;color:var(--theme-color-fg-default);font-size:13px;line-height:1.6}.DecisionDialog-module__HelpSection--apRQl ul li,.DecisionDialog-module__HelpSection--apRQl ol li{margin-bottom:8px}.DecisionDialog-module__HelpSection--apRQl ul li:last-child,.DecisionDialog-module__HelpSection--apRQl ol li:last-child{margin-bottom:0}.DecisionDialog-module__HelpSection--apRQl ul{list-style-type:disc}.DecisionDialog-module__HelpSection--apRQl ol{list-style-type:decimal}.DecisionDialog-module__AttemptSummary--TPPlJ{display:flex;flex-direction:column;gap:4px;padding:8px 12px;background:var(--theme-color-bg-3);border-radius:4px;border-left:2px solid var(--theme-color-danger)}.DecisionDialog-module__AttemptSummary--TPPlJ strong{font-size:12px}.DecisionDialog-module__Actions--Zh8iQ{display:flex;flex-direction:column;gap:12px;width:100%}.DecisionDialog-module__Actions__Row--Zf337{display:flex;gap:12px;width:100%;justify-content:center}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/migration/DecisionDialog.module.scss"],"names":[],"mappings":"AAAA,8CACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,QAAA,CACA,sBAAA,CACA,eAAA,CACA,eAAA,CAGF,oCACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,6BAAA,CACA,UAAA,CAEA,uDACE,qCAAA,CAGF,oDACE,qCAAA,CAIJ,uCACE,YAAA,CACA,qBAAA,CACA,QAAA,CACA,UAAA,CACA,iBAAA,CACA,eAAA,CACA,6BAAA,CAEA,0CACE,QAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CAGF,0CACE,gBAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CACA,eAAA,CAGF,8CACE,qCAAA,CACA,eAAA,CAIJ,wCACE,YAAA,CACA,kCAAA,CACA,iBAAA,CACA,gDAAA,CAGF,8CACE,YAAA,CACA,qBAAA,CACA,OAAA,CACA,eAAA,CAGF,wCACE,YAAA,CACA,qBAAA,CACA,OAAA,CACA,gBAAA,CACA,eAAA,CAGF,uCACE,YAAA,CACA,kCAAA,CACA,iBAAA,CACA,kDAAA,CAGF,+CACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,iBAAA,CAGF,+CACE,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,6CACE,cAAA,CACA,eAAA,CACA,uCAAA,CACA,2FAAA,CAGF,8CACE,cAAA,CACA,eAAA,CAGF,uCACE,cAAA,CAGF,2CACE,YAAA,CACA,qBAAA,CACA,QAAA,CACA,eAAA,CACA,YAAA,CACA,kCAAA,CACA,iBAAA,CACA,gBAAA,CACA,eAAA,CAGF,2CACE,YAAA,CACA,qBAAA,CACA,QAAA,CAEA,4FAEE,QAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CAEA,kGACE,iBAAA,CAEA,wHACE,eAAA,CAKN,8CACE,oBAAA,CAGF,8CACE,uBAAA,CAIJ,8CACE,YAAA,CACA,qBAAA,CACA,OAAA,CACA,gBAAA,CACA,kCAAA,CACA,iBAAA,CACA,+CAAA,CAEA,qDACE,cAAA,CAIJ,uCACE,YAAA,CACA,qBAAA,CACA,QAAA,CACA,UAAA,CAGF,4CACE,YAAA,CACA,QAAA,CACA,UAAA,CACA,sBAAA","sourcesContent":[".DecisionDialog {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 24px;\n  padding: 32px 24px 24px;\n  max-width: 550px;\n  max-height: 80vh;\n}\n\n.Icon {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 64px;\n  height: 64px;\n  border-radius: 50%;\n  color: var(--theme-color-bg-1);\n  opacity: 0.9;\n\n  &[data-type='warning'] {\n    background: var(--theme-color-warning);\n  }\n\n  &[data-type='help'] {\n    background: var(--theme-color-primary);\n  }\n}\n\n.Content {\n  display: flex;\n  flex-direction: column;\n  gap: 16px;\n  width: 100%;\n  text-align: center;\n  overflow-y: auto;\n  max-height: calc(80vh - 200px);\n\n  h3 {\n    margin: 0;\n    font-size: 18px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n  }\n\n  h4 {\n    margin: 0 0 8px 0;\n    font-size: 14px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    text-align: left;\n  }\n\n  strong {\n    color: var(--theme-color-fg-highlight);\n    font-weight: 600;\n  }\n}\n\n.CostInfo {\n  padding: 12px;\n  background: var(--theme-color-bg-3);\n  border-radius: 8px;\n  border-left: 3px solid var(--theme-color-warning);\n}\n\n.AttemptHistory {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n  text-align: left;\n}\n\n.Attempts {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n  max-height: 200px;\n  overflow-y: auto;\n}\n\n.Attempt {\n  padding: 12px;\n  background: var(--theme-color-bg-3);\n  border-radius: 6px;\n  border: 1px solid var(--theme-color-border-default);\n}\n\n.Attempt__Header {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  margin-bottom: 6px;\n}\n\n.Attempt__Number {\n  font-size: 12px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n}\n\n.Attempt__Cost {\n  font-size: 11px;\n  font-weight: 500;\n  color: var(--theme-color-fg-default-shy);\n  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;\n}\n\n.Attempt__Error {\n  font-size: 12px;\n  line-height: 1.4;\n}\n\n.Options {\n  margin-top: 8px;\n}\n\n.HelpContent {\n  display: flex;\n  flex-direction: column;\n  gap: 20px;\n  text-align: left;\n  padding: 16px;\n  background: var(--theme-color-bg-2);\n  border-radius: 8px;\n  max-height: 400px;\n  overflow-y: auto;\n}\n\n.HelpSection {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n\n  ul,\n  ol {\n    margin: 0;\n    padding-left: 20px;\n    color: var(--theme-color-fg-default);\n    font-size: 13px;\n    line-height: 1.6;\n\n    li {\n      margin-bottom: 8px;\n\n      &:last-child {\n        margin-bottom: 0;\n      }\n    }\n  }\n\n  ul {\n    list-style-type: disc;\n  }\n\n  ol {\n    list-style-type: decimal;\n  }\n}\n\n.AttemptSummary {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n  padding: 8px 12px;\n  background: var(--theme-color-bg-3);\n  border-radius: 4px;\n  border-left: 2px solid var(--theme-color-danger);\n\n  strong {\n    font-size: 12px;\n  }\n}\n\n.Actions {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n  width: 100%;\n}\n\n.Actions__Row {\n  display: flex;\n  gap: 12px;\n  width: 100%;\n  justify-content: center;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"DecisionDialog": `DecisionDialog-module__DecisionDialog--Sojru`,
	"Icon": `DecisionDialog-module__Icon--SJEi0`,
	"Content": `DecisionDialog-module__Content--ctL7_`,
	"CostInfo": `DecisionDialog-module__CostInfo--IOJ2n`,
	"AttemptHistory": `DecisionDialog-module__AttemptHistory--rnHch`,
	"Attempts": `DecisionDialog-module__Attempts--FDYTJ`,
	"Attempt": `DecisionDialog-module__Attempt--Sj6gU`,
	"Attempt__Header": `DecisionDialog-module__Attempt__Header--k31Lj`,
	"Attempt__Number": `DecisionDialog-module__Attempt__Number--nq3Hh`,
	"Attempt__Cost": `DecisionDialog-module__Attempt__Cost--ukBcf`,
	"Attempt__Error": `DecisionDialog-module__Attempt__Error--EJ0i4`,
	"Options": `DecisionDialog-module__Options--yIuk6`,
	"HelpContent": `DecisionDialog-module__HelpContent--OZEBf`,
	"HelpSection": `DecisionDialog-module__HelpSection--apRQl`,
	"AttemptSummary": `DecisionDialog-module__AttemptSummary--TPPlJ`,
	"Actions": `DecisionDialog-module__Actions--Zh8iQ`,
	"Actions__Row": `DecisionDialog-module__Actions__Row--Zf337`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 89642:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Y: () => (/* binding */ ComputedAction)
/* harmony export */ });
/**
 * An action being computed in the background on behalf of the user
 */
var ComputedAction;
(function (ComputedAction) {
    /** The action is being computed in the background */
    ComputedAction["Loading"] = "loading";
    /** The action should complete without any additional work required by the user */
    ComputedAction["Clean"] = "clean";
    /** The action requires additional work by the user to complete successfully */
    ComputedAction["Conflicts"] = "conflicts";
    /** The action cannot be completed, for reasons the app should explain */
    ComputedAction["Invalid"] = "invalid";
})(ComputedAction || (ComputedAction = {}));


/***/ }),

/***/ 89674:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCode = function SvgCode(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M15.705 4.0063C15.8466 3.61702 15.6458 3.1867 15.2565 3.04515C14.8672 2.90359 14.4369 3.10441 14.2954 3.49368L8.29536 19.9937C8.1538 20.383 8.35462 20.8133 8.7439 20.9548C9.13317 21.0964 9.56349 20.8956 9.70505 20.5063L15.705 4.0063ZM6.87939 7.76985C7.14456 8.08806 7.10157 8.56098 6.78336 8.82615L2.97476 12L6.78336 15.1738C7.10157 15.439 7.14456 15.9119 6.87939 16.2301C6.61422 16.5483 6.14129 16.5913 5.82308 16.3262L1.32308 12.5762C1.15209 12.4337 1.05322 12.2226 1.05322 12C1.05322 11.7774 1.15209 11.5663 1.32308 11.4238L5.82308 7.67382C6.14129 7.40865 6.61422 7.45164 6.87939 7.76985ZM17.1211 7.76985C17.3863 7.45164 17.8592 7.40865 18.1774 7.67382L22.6774 11.4238C22.8484 11.5663 22.9473 11.7774 22.9473 12C22.9473 12.2226 22.8484 12.4337 22.6774 12.5762L18.1774 16.3262C17.8592 16.5913 17.3863 16.5483 17.1211 16.2301C16.8559 15.9119 16.8989 15.439 17.2171 15.1738L21.0257 12L17.2171 8.82615C16.8989 8.56098 16.8559 8.08806 17.1211 7.76985Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCode);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "5ddc1ff1bd0ffc8df8e6b7602f238782.svg");

/***/ }),

/***/ 89676:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgFolderClosed = function SvgFolderClosed(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M22.3129 7.93609C22.0329 7.65609 21.6429 7.49609 21.2529 7.49609H13.3129L10.7429 4.92609C10.6029 4.78609 10.4429 4.67609 10.2629 4.60609C10.0829 4.53609 9.88293 4.51609 9.69293 4.49609H4.75293C4.35293 4.49609 3.97293 4.65609 3.69293 4.93609C3.41293 5.21609 3.25293 5.59609 3.25293 5.99609V19.5561C3.25293 19.7461 3.29293 19.9361 3.36293 20.1161C3.43293 20.2861 3.54293 20.4461 3.67293 20.5761C3.80293 20.7061 3.97293 20.8161 4.14293 20.8861C4.32293 20.9561 4.50293 20.9961 4.69293 20.9961H21.3329C21.7129 20.9961 22.0629 20.8461 22.3329 20.5861C22.6029 20.3261 22.7429 19.9561 22.7429 19.5861V8.99609C22.7429 8.59609 22.5829 8.21609 22.3029 7.93609H22.3129ZM9.69293 5.99609L11.1929 7.49609H4.75293V5.99609H9.69293ZM4.75293 19.5561V8.99609H21.2529L21.2829 19.4961L4.76293 19.5561H4.75293Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgFolderClosed);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "780093277962bc5b396c9c7446efd8dc.svg");

/***/ }),

/***/ 89818:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

/* -------------------- IE10 remove auto clear button -------------------- */

::-ms-clear {
	display: none;
}

/* All widgets */
/* I am not a big fan of this rule */
.monaco-editor .editor-widget input {
	color: inherit;
}

/* -------------------- Editor -------------------- */

.monaco-editor {
	position: relative;
	overflow: visible;
	-webkit-text-size-adjust: 100%;
}

/* -------------------- Misc -------------------- */

.monaco-editor .overflow-guard {
	position: relative;
	overflow: hidden;
}

.monaco-editor .view-overlays {
	position: absolute;
	top: 0;
}

/*
.monaco-editor .auto-closed-character {
	opacity: 0.3;
}
*/
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/widget/media/editor.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F,4EAA4E;;AAE5E;CACC,aAAa;AACd;;AAEA,gBAAgB;AAChB,oCAAoC;AACpC;CACC,cAAc;AACf;;AAEA,qDAAqD;;AAErD;CACC,kBAAkB;CAClB,iBAAiB;CACjB,8BAA8B;AAC/B;;AAEA,mDAAmD;;AAEnD;CACC,kBAAkB;CAClB,gBAAgB;AACjB;;AAEA;CACC,kBAAkB;CAClB,MAAM;AACP;;AAEA;;;;CAIC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n/* -------------------- IE10 remove auto clear button -------------------- */\n\n::-ms-clear {\n\tdisplay: none;\n}\n\n/* All widgets */\n/* I am not a big fan of this rule */\n.monaco-editor .editor-widget input {\n\tcolor: inherit;\n}\n\n/* -------------------- Editor -------------------- */\n\n.monaco-editor {\n\tposition: relative;\n\toverflow: visible;\n\t-webkit-text-size-adjust: 100%;\n}\n\n/* -------------------- Misc -------------------- */\n\n.monaco-editor .overflow-guard {\n\tposition: relative;\n\toverflow: hidden;\n}\n\n.monaco-editor .view-overlays {\n\tposition: absolute;\n\ttop: 0;\n}\n\n/*\n.monaco-editor .auto-closed-character {\n\topacity: 0.3;\n}\n*/\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 89856:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-diff-editor .diff-review-line-number {
	text-align: right;
	display: inline-block;
}

.monaco-diff-editor .diff-review {
	position: absolute;
	user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}

.monaco-diff-editor .diff-review-summary {
	padding-left: 10px;
}

.monaco-diff-editor .diff-review-shadow {
	position: absolute;
}

.monaco-diff-editor .diff-review-row {
	white-space: pre;
}

.monaco-diff-editor .diff-review-table {
	display: table;
	min-width: 100%;
}

.monaco-diff-editor .diff-review-row {
	display: table-row;
	width: 100%;
}

.monaco-diff-editor .diff-review-spacer {
	display: inline-block;
	width: 10px;
	vertical-align: middle;
}

.monaco-diff-editor .diff-review-spacer > .codicon {
	font-size: 9px !important;
}

.monaco-diff-editor .diff-review-actions {
	display: inline-block;
	position: absolute;
	right: 10px;
	top: 2px;
}

.monaco-diff-editor .diff-review-actions .action-label {
	width: 16px;
	height: 16px;
	margin: 2px 0;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/widget/media/diffReview.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,iBAAiB;CACjB,qBAAqB;AACtB;;AAEA;CACC,kBAAkB;CAClB,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;AACtB;;AAEA;CACC,kBAAkB;AACnB;;AAEA;CACC,kBAAkB;AACnB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,cAAc;CACd,eAAe;AAChB;;AAEA;CACC,kBAAkB;CAClB,WAAW;AACZ;;AAEA;CACC,qBAAqB;CACrB,WAAW;CACX,sBAAsB;AACvB;;AAEA;CACC,yBAAyB;AAC1B;;AAEA;CACC,qBAAqB;CACrB,kBAAkB;CAClB,WAAW;CACX,QAAQ;AACT;;AAEA;CACC,WAAW;CACX,YAAY;CACZ,aAAa;AACd","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-diff-editor .diff-review-line-number {\n\ttext-align: right;\n\tdisplay: inline-block;\n}\n\n.monaco-diff-editor .diff-review {\n\tposition: absolute;\n\tuser-select: none;\n\t-webkit-user-select: none;\n\t-ms-user-select: none;\n}\n\n.monaco-diff-editor .diff-review-summary {\n\tpadding-left: 10px;\n}\n\n.monaco-diff-editor .diff-review-shadow {\n\tposition: absolute;\n}\n\n.monaco-diff-editor .diff-review-row {\n\twhite-space: pre;\n}\n\n.monaco-diff-editor .diff-review-table {\n\tdisplay: table;\n\tmin-width: 100%;\n}\n\n.monaco-diff-editor .diff-review-row {\n\tdisplay: table-row;\n\twidth: 100%;\n}\n\n.monaco-diff-editor .diff-review-spacer {\n\tdisplay: inline-block;\n\twidth: 10px;\n\tvertical-align: middle;\n}\n\n.monaco-diff-editor .diff-review-spacer > .codicon {\n\tfont-size: 9px !important;\n}\n\n.monaco-diff-editor .diff-review-actions {\n\tdisplay: inline-block;\n\tposition: absolute;\n\tright: 10px;\n\ttop: 2px;\n}\n\n.monaco-diff-editor .diff-review-actions .action-label {\n\twidth: 16px;\n\theight: 16px;\n\tmargin: 2px 0;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 89911:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   Cb: () => (/* binding */ detectRuntimeVersion),
/* harmony export */   OA: () => (/* binding */ scanProjectForMigration)
/* harmony export */ });
/* unused harmony exports scanForLegacyPatterns, LEGACY_PATTERNS, REACT19_MIN_VERSION, OPENNOODL_FORK_DATE, readProjectJson, compareVersions */
/* harmony import */ var _noodl_platform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37218);
/**
 * ProjectScanner
 *
 * Handles detection of project runtime versions and scanning for legacy React patterns
 * that need migration. Uses a 5-tier detection system with confidence levels.
 *
 * @module noodl-editor/models/migration
 * @since 1.2.0
 */

// =============================================================================
// Constants
// =============================================================================
/**
 * OpenNoodl version number that introduced React 19
 * Projects created with this version or later use React 19
 */
const REACT19_MIN_VERSION = '1.2.0';
/**
 * Date when OpenNoodl fork was created
 * Projects before this date are assumed to be legacy React 17
 */
const OPENNOODL_FORK_DATE = new Date('2024-01-01');
/**
 * Patterns to detect legacy React code that needs migration
 */
const LEGACY_PATTERNS = [
    {
        regex: /componentWillMount\s*\(/,
        name: 'componentWillMount',
        type: 'componentWillMount',
        description: 'componentWillMount lifecycle method (removed in React 19)',
        autoFixable: false
    },
    {
        regex: /componentWillReceiveProps\s*\(/,
        name: 'componentWillReceiveProps',
        type: 'componentWillReceiveProps',
        description: 'componentWillReceiveProps lifecycle method (removed in React 19)',
        autoFixable: false
    },
    {
        regex: /componentWillUpdate\s*\(/,
        name: 'componentWillUpdate',
        type: 'componentWillUpdate',
        description: 'componentWillUpdate lifecycle method (removed in React 19)',
        autoFixable: false
    },
    {
        regex: /UNSAFE_componentWillMount/,
        name: 'UNSAFE_componentWillMount',
        type: 'unsafeLifecycle',
        description: 'UNSAFE_componentWillMount lifecycle method (removed in React 19)',
        autoFixable: false
    },
    {
        regex: /UNSAFE_componentWillReceiveProps/,
        name: 'UNSAFE_componentWillReceiveProps',
        type: 'unsafeLifecycle',
        description: 'UNSAFE_componentWillReceiveProps lifecycle method (removed in React 19)',
        autoFixable: false
    },
    {
        regex: /UNSAFE_componentWillUpdate/,
        name: 'UNSAFE_componentWillUpdate',
        type: 'unsafeLifecycle',
        description: 'UNSAFE_componentWillUpdate lifecycle method (removed in React 19)',
        autoFixable: false
    },
    {
        regex: /ref\s*=\s*["'][^"']+["']/,
        name: 'String ref',
        type: 'stringRef',
        description: 'String refs are removed in React 19, use createRef() or useRef()',
        autoFixable: true
    },
    {
        regex: /contextTypes\s*=/,
        name: 'Legacy contextTypes',
        type: 'legacyContext',
        description: 'Legacy contextTypes API is removed in React 19',
        autoFixable: false
    },
    {
        regex: /childContextTypes\s*=/,
        name: 'Legacy childContextTypes',
        type: 'legacyContext',
        description: 'Legacy childContextTypes API is removed in React 19',
        autoFixable: false
    },
    {
        regex: /getChildContext\s*\(/,
        name: 'getChildContext',
        type: 'legacyContext',
        description: 'getChildContext method is removed in React 19',
        autoFixable: false
    },
    {
        regex: /React\.createFactory/,
        name: 'createFactory',
        type: 'createFactory',
        description: 'React.createFactory is removed in React 19',
        autoFixable: true
    },
    {
        regex: /ReactDOM\.findDOMNode/,
        name: 'findDOMNode',
        type: 'findDOMNode',
        description: 'ReactDOM.findDOMNode is removed in React 19',
        autoFixable: false
    },
    {
        regex: /ReactDOM\.render\s*\(/,
        name: 'ReactDOM.render',
        type: 'reactDomRender',
        description: 'ReactDOM.render is removed in React 19, use createRoot',
        autoFixable: true
    }
];
// =============================================================================
// Version Detection
// =============================================================================
/**
 * Compares two semantic version strings
 * @returns -1 if a < b, 0 if a == b, 1 if a > b
 */
function compareVersions(a, b) {
    const partsA = a.split('.').map(Number);
    const partsB = b.split('.').map(Number);
    for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
        const numA = partsA[i] || 0;
        const numB = partsB[i] || 0;
        if (numA < numB)
            return -1;
        if (numA > numB)
            return 1;
    }
    return 0;
}
/**
 * Reads the project.json file from a project directory
 */
async function readProjectJson(projectPath) {
    try {
        const projectJsonPath = `${projectPath}/project.json`;
        const content = await _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.readJson(projectJsonPath);
        return content;
    }
    catch (error) {
        console.warn(`Could not read project.json from ${projectPath}:`, error);
        return null;
    }
}
/**
 * Gets the creation date of a project from filesystem metadata
 * Note: The IFileSystem interface doesn't expose birthtime, so this returns null
 * and relies on other detection methods. Could be enhanced in platform-electron.
 */
async function getProjectCreationDate(_projectPath) {
    // IFileSystem doesn't have stat or birthtime access
    // This would need platform-specific implementation
    return null;
}
/**
 * Detects the runtime version of a project using a 5-tier detection system.
 *
 * Detection order:
 * 1. Explicit runtimeVersion field in project.json (highest confidence)
 * 2. migratedFrom metadata (indicates already migrated)
 * 3. Editor version number comparison
 * 4. Legacy code pattern scanning
 * 5. Project creation date heuristic (lowest confidence)
 *
 * @param projectPath - Path to the project directory
 * @returns Runtime version info with confidence level
 */
async function detectRuntimeVersion(projectPath) {
    const indicators = [];
    console.log('🔍 [detectRuntimeVersion] Starting detection for:', projectPath);
    // Read project.json
    const projectJson = await readProjectJson(projectPath);
    if (!projectJson) {
        console.log('❌ [detectRuntimeVersion] Could not read project.json');
        return {
            version: 'unknown',
            confidence: 'low',
            indicators: ['Could not read project.json']
        };
    }
    console.log('📄 [detectRuntimeVersion] Project JSON loaded:', {
        name: projectJson.name,
        version: projectJson.version,
        editorVersion: projectJson.editorVersion,
        runtimeVersion: projectJson.runtimeVersion,
        migratedFrom: projectJson.migratedFrom,
        createdAt: projectJson.createdAt
    });
    // ==========================================================================
    // Check 1: Explicit runtimeVersion field (most reliable)
    // ==========================================================================
    if (projectJson.runtimeVersion) {
        return {
            version: projectJson.runtimeVersion,
            confidence: 'high',
            indicators: ['Explicit runtimeVersion field in project.json']
        };
    }
    // ==========================================================================
    // Check 2: Look for migratedFrom field (indicates already migrated)
    // ==========================================================================
    if (projectJson.migratedFrom) {
        return {
            version: 'react19',
            confidence: 'high',
            indicators: ['Project has migratedFrom metadata - already migrated']
        };
    }
    // ==========================================================================
    // Check 3: Check editor version number
    // OpenNoodl 1.2+ = React 19, earlier = React 17
    // ==========================================================================
    const editorVersion = projectJson.editorVersion || projectJson.version;
    if (editorVersion && typeof editorVersion === 'string') {
        // Clean up version string (remove 'v' prefix if present)
        const cleanVersion = editorVersion.replace(/^v/, '');
        // Check if it's a valid semver-like string
        if (/^\d+\.\d+/.test(cleanVersion)) {
            const comparison = compareVersions(cleanVersion, REACT19_MIN_VERSION);
            if (comparison >= 0) {
                indicators.push(`Editor version ${editorVersion} >= ${REACT19_MIN_VERSION}`);
                return {
                    version: 'react19',
                    confidence: 'high',
                    indicators
                };
            }
            else {
                indicators.push(`Editor version ${editorVersion} < ${REACT19_MIN_VERSION}`);
                return {
                    version: 'react17',
                    confidence: 'high',
                    indicators
                };
            }
        }
    }
    // ==========================================================================
    // Check 4: Heuristic - scan for React 17 specific patterns in custom code
    // ==========================================================================
    const legacyPatterns = await scanForLegacyPatterns(projectPath);
    if (legacyPatterns.found) {
        indicators.push(`Found legacy React patterns: ${legacyPatterns.patterns.join(', ')}`);
        return {
            version: 'react17',
            confidence: 'medium',
            indicators
        };
    }
    // ==========================================================================
    // Check 5: Project creation date heuristic
    // Projects created before OpenNoodl fork are assumed React 17
    // ==========================================================================
    const createdAt = projectJson.createdAt ? new Date(projectJson.createdAt) : await getProjectCreationDate(projectPath);
    if (createdAt && createdAt < OPENNOODL_FORK_DATE) {
        indicators.push(`Project created ${createdAt.toISOString()} (before OpenNoodl fork)`);
        return {
            version: 'react17',
            confidence: 'medium',
            indicators
        };
    }
    // ==========================================================================
    // Default: Assume React 17 for older projects without explicit markers
    // Any project without runtimeVersion, migratedFrom, or a recent editorVersion
    // is most likely a legacy project from before OpenNoodl
    // ==========================================================================
    console.log('✅ [detectRuntimeVersion] FINAL: Assuming React 17 (no markers found)');
    return {
        version: 'react17',
        confidence: 'low',
        indicators: ['No React 19 markers found - assuming legacy React 17 project']
    };
}
// =============================================================================
// Legacy Pattern Scanning
// =============================================================================
/**
 * Scans a project directory for legacy React patterns in JavaScript files.
 * Looks for componentWillMount, string refs, legacy context, etc.
 *
 * @param projectPath - Path to the project directory
 * @returns Object containing found patterns and file locations
 */
async function scanForLegacyPatterns(projectPath) {
    const result = {
        found: false,
        patterns: [],
        files: []
    };
    try {
        // List all files in the project directory
        const allFiles = await listFilesRecursively(projectPath);
        // Filter to JS/JSX/TS/TSX files, excluding node_modules
        const jsFiles = allFiles.filter((file) => {
            const isJsFile = /\.(js|jsx|ts|tsx)$/.test(file);
            const isNotNodeModules = !file.includes('node_modules');
            return isJsFile && isNotNodeModules;
        });
        // Scan each file for legacy patterns
        for (const file of jsFiles) {
            try {
                const content = await _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.readFile(file);
                const lines = content.split('\n');
                for (const pattern of LEGACY_PATTERNS) {
                    lines.forEach((line, index) => {
                        if (pattern.regex.test(line)) {
                            result.found = true;
                            if (!result.patterns.includes(pattern.name)) {
                                result.patterns.push(pattern.name);
                            }
                            result.files.push({
                                path: file,
                                line: index + 1,
                                pattern: pattern.name,
                                content: line.trim()
                            });
                        }
                    });
                }
            }
            catch (readError) {
                // Skip files we can't read
                console.warn(`Could not read file ${file}:`, readError);
            }
        }
    }
    catch (error) {
        console.error('Error scanning for legacy patterns:', error);
    }
    return result;
}
/**
 * Recursively lists all files in a directory
 */
async function listFilesRecursively(dirPath) {
    const files = [];
    try {
        const entries = await _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.listDirectory(dirPath);
        for (const entry of entries) {
            if (entry.isDirectory) {
                // Skip node_modules and hidden directories
                if (entry.name.startsWith('.') || entry.name === 'node_modules') {
                    continue;
                }
                const subFiles = await listFilesRecursively(entry.fullPath);
                files.push(...subFiles);
            }
            else {
                files.push(entry.fullPath);
            }
        }
    }
    catch (error) {
        console.warn(`Could not list directory ${dirPath}:`, error);
    }
    return files;
}
// =============================================================================
// Full Project Scan
// =============================================================================
/**
 * Counter for generating unique issue IDs
 */
let issueIdCounter = 0;
/**
 * Generates a unique issue ID
 */
function generateIssueId() {
    return `issue-${Date.now()}-${++issueIdCounter}`;
}
/**
 * Performs a full migration scan of a project.
 * Analyzes all components and JS files for migration needs.
 *
 * @param projectPath - Path to the project directory
 * @param onProgress - Optional callback for progress updates
 * @returns Full migration scan results
 */
async function scanProjectForMigration(projectPath, onProgress) {
    const projectJson = await readProjectJson(projectPath);
    const stats = {
        components: 0,
        nodes: 0,
        jsFiles: 0
    };
    const categories = {
        automatic: [],
        simpleFixes: [],
        needsReview: []
    };
    // Count components from project.json
    if (projectJson === null || projectJson === void 0 ? void 0 : projectJson.components) {
        stats.components = projectJson.components.length;
        // Count total nodes across all components
        projectJson.components.forEach((component) => {
            if (component.graph && typeof component.graph === 'object') {
                const graph = component.graph;
                if (graph.roots) {
                    stats.nodes += countNodesInRoots(graph.roots);
                }
            }
        });
    }
    // Scan JavaScript files for issues
    const allFiles = await listFilesRecursively(projectPath);
    const jsFiles = allFiles.filter((file) => /\.(js|jsx|ts|tsx)$/.test(file) && !file.includes('node_modules'));
    stats.jsFiles = jsFiles.length;
    // Group issues by file/component
    const fileIssues = new Map();
    for (let i = 0; i < jsFiles.length; i++) {
        const file = jsFiles[i];
        const relativePath = file.replace(projectPath, '').replace(/^\//, '');
        onProgress === null || onProgress === void 0 ? void 0 : onProgress((i / jsFiles.length) * 100, relativePath, stats);
        try {
            const content = await _noodl_platform__WEBPACK_IMPORTED_MODULE_0__.filesystem.readFile(file);
            const lines = content.split('\n');
            const issues = [];
            for (const pattern of LEGACY_PATTERNS) {
                lines.forEach((line, lineIndex) => {
                    if (pattern.regex.test(line)) {
                        issues.push({
                            id: generateIssueId(),
                            type: pattern.type,
                            description: pattern.description,
                            location: {
                                file: relativePath,
                                line: lineIndex + 1
                            },
                            autoFixable: pattern.autoFixable,
                            fix: pattern.autoFixable
                                ? { type: 'automatic', description: `Auto-fix ${pattern.name}` }
                                : { type: 'ai-required', description: `AI assistance needed for ${pattern.name}` }
                        });
                    }
                });
            }
            if (issues.length > 0) {
                fileIssues.set(relativePath, issues);
            }
        }
        catch {
            // Skip files we can't read
        }
    }
    // Categorize files by issue severity
    for (const [filePath, issues] of fileIssues.entries()) {
        const hasAutoFixableOnly = issues.every((issue) => issue.autoFixable);
        const estimatedCost = estimateAICost(issues.length);
        const componentInfo = {
            id: filePath.replace(/[^a-zA-Z0-9]/g, '-'),
            name: filePath.split('/').pop() || filePath,
            path: filePath,
            issues,
            estimatedCost: hasAutoFixableOnly ? 0 : estimatedCost
        };
        if (hasAutoFixableOnly) {
            categories.simpleFixes.push(componentInfo);
        }
        else {
            categories.needsReview.push(componentInfo);
        }
    }
    // All components without issues are automatic
    if (projectJson === null || projectJson === void 0 ? void 0 : projectJson.components) {
        const filesWithIssues = new Set(fileIssues.keys());
        projectJson.components.forEach((component) => {
            // Check if this component has any JS with issues
            // For now, assume all components without explicit issues are automatic
            const componentPath = component.name.replace(/\//g, '-');
            if (!filesWithIssues.has(componentPath)) {
                categories.automatic.push({
                    id: component.id,
                    name: component.name,
                    path: component.name,
                    issues: [],
                    estimatedCost: 0
                });
            }
        });
    }
    return {
        completedAt: new Date().toISOString(),
        totalComponents: stats.components,
        totalNodes: stats.nodes,
        customJsFiles: stats.jsFiles,
        categories
    };
}
/**
 * Counts nodes in a graph roots array
 */
function countNodesInRoots(roots) {
    let count = 0;
    function countRecursive(nodes) {
        for (const node of nodes) {
            count++;
            if (node && typeof node === 'object' && 'children' in node) {
                const children = node.children;
                if (Array.isArray(children)) {
                    countRecursive(children);
                }
            }
        }
    }
    countRecursive(roots);
    return count;
}
/**
 * Estimates AI cost for migrating issues
 * Based on ~$0.01 per simple issue, ~$0.05 per complex issue
 */
function estimateAICost(issueCount) {
    // Rough estimate: $0.03 per issue on average
    return issueCount * 0.03;
}
// =============================================================================
// Exports
// =============================================================================



/***/ }),

/***/ 89951:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.toFile = void 0;
var to_file_1 = __webpack_require__(28885);
Object.defineProperty(exports, "toFile", ({ enumerable: true, get: function () { return to_file_1.toFile; } }));
//# sourceMappingURL=uploads.js.map

/***/ }),

/***/ 90006:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .accessibilityHelpWidget {
	padding: 10px;
	vertical-align: middle;
	overflow: scroll;
}`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,aAAa;CACb,sBAAsB;CACtB,gBAAgB;AACjB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .accessibilityHelpWidget {\n\tpadding: 10px;\n\tvertical-align: middle;\n\toverflow: scroll;\n}"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 90130:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const fs = __webpack_require__(79896);

class ProjectModules {
  constructor() {}
  scanProjectModules(projectDirectory, callback) {
    if (projectDirectory === undefined) {
      callback(); // No project directory, no modules
      return;
    }

    var modulesPath = projectDirectory + '/noodl_modules';
    fs.readdir(modulesPath, function (err, files) {
      if (err) {
        callback();
        return;
      }

      //we only care about directories
      const directories = files.filter((f) => {
        var stats = fs.lstatSync(modulesPath + '/' + f);
        return stats.isDirectory() || stats.isSymbolicLink();
      });

      if (directories.length === 0) {
        callback();
      } else {
        // For each subfolder in noodl_modules
        var modules = [];
        var modulesLeft = 0;

        function completeModule(path, manifest) {
          if (path && manifest) {
            // Module manifest is fetched, resolve local paths
            var m = {
              dependencies: [],
              browser: manifest.browser,
              runtimes: manifest.runtimes || ['browser'] //default to browser
            };

            if (manifest.main) {
              m.index = path + '/' + manifest.main;
            }

            if (manifest.dependencies) {
              for (var j = 0; j < manifest.dependencies.length; j++) {
                var d = manifest.dependencies[j];
                if (!d.startsWith['http']) d = path + '/' + d;

                m.dependencies.push(d);
              }
            }

            modules.push(m);
          }

          modulesLeft--;
          if (modulesLeft === 0) {
            //sort modules so the order is deterministics
            //helps the editor understand when node libraries change, or are the same
            const modulesWithIndexFile = modules.filter((m) => m.index);
            const modulesWithoutIndexFile = modules.filter((m) => !m.index);

            modulesWithIndexFile.sort((a, b) => a.index.localeCompare(b.index));

            callback(modulesWithIndexFile.concat(modulesWithoutIndexFile));
          }
        }

        for (var i = 0; i < directories.length; i++) {
          const dir = directories[i];
          modulesLeft++;
          // Read manifest
          fs.readFile(
            modulesPath + '/' + dir + '/manifest.json',
            'utf8',
            (function () {
              const _dir = dir;
              return function (err, data) {
                if (err) {
                  completeModule(); // Module load failed
                  return;
                }

                try {
                  completeModule('noodl_modules/' + _dir, JSON.parse(data));
                } catch (e) {
                  // JSON not valid
                  completeModule(); // Module load failed
                }
              };
            })()
          );
        }
      }
    });
  }
  injectIntoHtml(projectDirectory, template, pathPrefix, callback) {
    this.scanProjectModules(projectDirectory, function (modules) {
      var dependencies = '';
      var modulesMain = '';
      if (modules) {
        const browserModules = modules.filter((m) => m.runtimes.indexOf('browser') !== -1);
        for (var i = 0; i < browserModules.length; i++) {
          var m = browserModules[i];
          if (m.index) {
            modulesMain += '<script type="text/javascript" src="' + pathPrefix + m.index + '"></script>\n';
          }

          // Module javascript dependencies
          if (m.dependencies) {
            for (var j = 0; j < m.dependencies.length; j++) {
              var d = m.dependencies[j];
              var dTag = '<script type="text/javascript" src="' + pathPrefix + d + '"></script>\n';
              if (dependencies.indexOf(dTag) === -1) dependencies += dTag;
            }
          }

          // Browser modules
          if (m.browser) {
            if (m.browser.head) {
              var head = m.browser.head;
              for (var j = 0; j < head.length; j++) {
                dependencies += head[j] + '\n';
              }
            }

            if (m.browser.styles) {
              var styles = m.browser.styles;
              for (var j = 0; j < styles.length; j++) {
                dependencies += '<style>' + styles[j] + '</style>' + '\n';
              }
            }

            if (m.browser.stylesheets) {
              var sheets = m.browser.stylesheets;
              for (var j = 0; j < sheets.length; j++) {
                if (typeof sheets[j] === 'string') {
                  let path = sheets[j];
                  if (!path.startsWith('http')) {
                    path = pathPrefix + path;
                  }

                  dependencies += '<link href="' + path + '" rel="stylesheet">';
                }
              }
            }
          }
        }
      }

      var injected = template.replace('<%modules_dependencies%>', dependencies);
      injected = injected.replace('<%modules_main%>', modulesMain);

      callback(injected);
    });
  }
}

ProjectModules.instance = new ProjectModules();

module.exports = ProjectModules;


/***/ }),

/***/ 90175:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgNotePencil = function SvgNotePencil(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M18.667 2.86454C18.3742 2.57164 17.8993 2.57164 17.6064 2.86454L15.357 5.11395C15.3568 5.11415 15.3566 5.11434 15.3564 5.11454C15.3562 5.11473 15.356 5.11493 15.3558 5.11512L8.60639 11.8645C8.46574 12.0052 8.38672 12.196 8.38672 12.3949V15.3949C8.38672 15.8091 8.72251 16.1449 9.13672 16.1449H12.1367C12.3356 16.1449 12.5264 16.0658 12.667 15.9252L19.4163 9.17591C19.4166 9.17568 19.4168 9.17544 19.417 9.1752C19.4173 9.17496 19.4175 9.17472 19.4178 9.17448L21.667 6.9252C21.9599 6.6323 21.9599 6.15743 21.667 5.86454L18.667 2.86454ZM18.8867 7.58421L20.0761 6.39487L18.1367 4.45553L16.9474 5.64487L18.8867 7.58421ZM15.8867 6.70553L9.88672 12.7055V14.6449H11.8261L17.8261 8.64487L15.8867 6.70553Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.57606 3.83421C3.85736 3.5529 4.23889 3.39487 4.63672 3.39487H12.8867C13.3009 3.39487 13.6367 3.73065 13.6367 4.14487C13.6367 4.55908 13.3009 4.89487 12.8867 4.89487L4.63672 4.89487L4.63672 19.8949H19.6367V11.6449C19.6367 11.2307 19.9725 10.8949 20.3867 10.8949C20.8009 10.8949 21.1367 11.2307 21.1367 11.6449V19.8949C21.1367 20.2927 20.9787 20.6742 20.6974 20.9555C20.4161 21.2368 20.0345 21.3949 19.6367 21.3949H4.63672C4.2389 21.3949 3.85736 21.2368 3.57606 20.9555C3.29475 20.6742 3.13672 20.2927 3.13672 19.8949V4.89487C3.13672 4.49704 3.29475 4.11551 3.57606 3.83421Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgNotePencil);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "fa27f718be978c50fcb99927277db50c.svg");

/***/ }),

/***/ 90294:
/***/ ((module) => {

"use strict";
module.exports = require("passport-local");

/***/ }),

/***/ 90484:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgHome = function SvgHome(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M11.1253 3.25613C11.4016 3.00376 11.7624 2.86382 12.1367 2.86382C12.511 2.86382 12.8718 3.00376 13.1482 3.25613C13.1485 3.25645 13.1489 3.25677 13.1492 3.25709L20.6474 10.071L20.6579 10.0808C20.8061 10.2208 20.9249 10.389 21.0071 10.5756C21.0893 10.7621 21.1333 10.9632 21.1366 11.1671L21.1368 11.1792L21.1367 19.8511C21.1367 20.2489 20.9787 20.6304 20.6974 20.9117C20.4161 21.193 20.0345 21.3511 19.6367 21.3511H15.1367C14.7389 21.3511 14.3574 21.193 14.0761 20.9117C13.7948 20.6304 13.6367 20.2489 13.6367 19.8511V15.3511L10.6367 15.3511V19.8511C10.6367 20.2489 10.4787 20.6304 10.1974 20.9117C9.91607 21.193 9.53454 21.3511 9.13672 21.3511H4.63672C4.2389 21.3511 3.85736 21.193 3.57606 20.9117C3.29475 20.6304 3.13672 20.2489 3.13672 19.8511V11.1671C3.14002 10.9632 3.18417 10.7621 3.26638 10.5756C3.34859 10.389 3.46729 10.2208 3.61551 10.0808L3.62607 10.071L11.1242 3.25709C11.1246 3.25677 11.1249 3.25645 11.1253 3.25613ZM4.64382 11.173L12.1349 4.3655L12.1367 4.36382L12.1386 4.3655L19.6296 11.173C19.6316 11.1752 19.6332 11.1777 19.6344 11.1804C19.6357 11.1833 19.6365 11.1863 19.6367 11.1894V19.8511H15.1367V15.3511C15.1367 14.9533 14.9787 14.5717 14.6974 14.2904C14.4161 14.0091 14.0345 13.8511 13.6367 13.8511H10.6367C10.2389 13.8511 9.85736 14.0091 9.57606 14.2904C9.29475 14.5717 9.13672 14.9533 9.13672 15.3511V19.8511H4.63672V11.1894C4.63698 11.1863 4.63775 11.1833 4.639 11.1804C4.64021 11.1777 4.64184 11.1752 4.64382 11.173Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgHome);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "be758e12c999ba388b07ca5ead124ae2.svg");

/***/ }),

/***/ 90671:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgExternalLink = function SvgExternalLink(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M3.43934 3.43934C3.72064 3.15804 4.10217 3 4.5 3H10C10.4142 3 10.75 3.33579 10.75 3.75C10.75 4.16421 10.4142 4.5 10 4.5L4.5 4.5L4.5 19.5H19.5V14C19.5 13.5858 19.8358 13.25 20.25 13.25C20.6642 13.25 21 13.5858 21 14V19.5C21 19.8978 20.842 20.2794 20.5607 20.5607C20.2794 20.842 19.8978 21 19.5 21H4.5C4.10218 21 3.72065 20.842 3.43934 20.5607C3.15804 20.2794 3 19.8978 3 19.5V4.5C3 4.10217 3.15804 3.72064 3.43934 3.43934ZM14.6563 3.03423L20.2248 3.03423C20.4237 3.03423 20.6145 3.11324 20.7551 3.2539C20.8958 3.39455 20.9748 3.58531 20.9748 3.78423V9.35269C20.9748 9.76691 20.639 10.1027 20.2248 10.1027C19.8106 10.1027 19.4748 9.76691 19.4748 9.35269V5.59348L12.53 12.5306C12.237 12.8234 11.7621 12.8231 11.4694 12.53C11.1766 12.237 11.1769 11.7621 11.47 11.4694L18.4127 4.53423L14.6563 4.53423C14.2421 4.53423 13.9063 4.19844 13.9063 3.78423C13.9063 3.37001 14.2421 3.03423 14.6563 3.03423Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgExternalLink);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "b4cfb9c0b1651b56d2859b176843c3dd.svg");

/***/ }),

/***/ 90939:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.CreateProjectModal-module__Backdrop--EjO3D{position:fixed;top:0;left:0;right:0;bottom:0;display:flex;align-items:center;justify-content:center;background-color:rgba(0,0,0,.5);z-index:1000}.CreateProjectModal-module__Modal--_O_w2{background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:var(--radius-lg);min-width:500px;max-width:600px;box-shadow:0 8px 32px rgba(0,0,0,.3);z-index:1001}.CreateProjectModal-module__Header--VReI2{padding:var(--spacing-5) var(--spacing-6);border-bottom:1px solid var(--theme-color-border-default)}.CreateProjectModal-module__Title--Ir_Gb{font-size:20px;font-weight:600;color:var(--theme-color-fg-default);margin:0;line-height:1.3}.CreateProjectModal-module__Content--C1ZwR{padding:var(--spacing-6)}.CreateProjectModal-module__Field--YpGz5{margin-bottom:var(--spacing-5)}.CreateProjectModal-module__Field--YpGz5:last-child{margin-bottom:0}.CreateProjectModal-module__LocationRow--iH7e2{display:flex;align-items:center;margin-top:var(--spacing-2)}.CreateProjectModal-module__PathPreview--vKXHA{margin-top:var(--spacing-4);padding:var(--spacing-3);background-color:var(--theme-color-bg-3);border-radius:var(--radius-default);border:1px solid var(--theme-color-border-default)}.CreateProjectModal-module__PathText--JzbY6{font-size:13px;color:var(--theme-color-fg-default-shy);line-height:1.4}.CreateProjectModal-module__Footer--hGfvP{padding:var(--spacing-4) var(--spacing-6);border-top:1px solid var(--theme-color-border-default);display:flex;justify-content:flex-end}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/preview/launcher/Launcher/components/CreateProjectModal/CreateProjectModal.module.scss"],"names":[],"mappings":"AAAA,4CACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,+BAAA,CACA,YAAA,CAGF,yCACE,wCAAA,CACA,kDAAA,CACA,8BAAA,CACA,eAAA,CACA,eAAA,CACA,oCAAA,CACA,YAAA,CAGF,0CACE,yCAAA,CACA,yDAAA,CAGF,yCACE,cAAA,CACA,eAAA,CACA,mCAAA,CACA,QAAA,CACA,eAAA,CAGF,2CACE,wBAAA,CAGF,yCACE,8BAAA,CAEA,oDACE,eAAA,CAIJ,+CACE,YAAA,CACA,kBAAA,CACA,2BAAA,CAGF,+CACE,2BAAA,CACA,wBAAA,CACA,wCAAA,CACA,mCAAA,CACA,kDAAA,CAGF,4CACE,cAAA,CACA,uCAAA,CACA,eAAA,CAGF,0CACE,yCAAA,CACA,sDAAA,CACA,YAAA,CACA,wBAAA","sourcesContent":[".Backdrop {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  background-color: rgba(0, 0, 0, 0.5);\n  z-index: 1000;\n}\n\n.Modal {\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: var(--radius-lg);\n  min-width: 500px;\n  max-width: 600px;\n  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);\n  z-index: 1001;\n}\n\n.Header {\n  padding: var(--spacing-5) var(--spacing-6);\n  border-bottom: 1px solid var(--theme-color-border-default);\n}\n\n.Title {\n  font-size: 20px;\n  font-weight: 600;\n  color: var(--theme-color-fg-default);\n  margin: 0;\n  line-height: 1.3;\n}\n\n.Content {\n  padding: var(--spacing-6);\n}\n\n.Field {\n  margin-bottom: var(--spacing-5);\n\n  &:last-child {\n    margin-bottom: 0;\n  }\n}\n\n.LocationRow {\n  display: flex;\n  align-items: center;\n  margin-top: var(--spacing-2);\n}\n\n.PathPreview {\n  margin-top: var(--spacing-4);\n  padding: var(--spacing-3);\n  background-color: var(--theme-color-bg-3);\n  border-radius: var(--radius-default);\n  border: 1px solid var(--theme-color-border-default);\n}\n\n.PathText {\n  font-size: 13px;\n  color: var(--theme-color-fg-default-shy);\n  line-height: 1.4;\n}\n\n.Footer {\n  padding: var(--spacing-4) var(--spacing-6);\n  border-top: 1px solid var(--theme-color-border-default);\n  display: flex;\n  justify-content: flex-end;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Backdrop": `CreateProjectModal-module__Backdrop--EjO3D`,
	"Modal": `CreateProjectModal-module__Modal--_O_w2`,
	"Header": `CreateProjectModal-module__Header--VReI2`,
	"Title": `CreateProjectModal-module__Title--Ir_Gb`,
	"Content": `CreateProjectModal-module__Content--C1ZwR`,
	"Field": `CreateProjectModal-module__Field--YpGz5`,
	"LocationRow": `CreateProjectModal-module__LocationRow--iH7e2`,
	"PathPreview": `CreateProjectModal-module__PathPreview--vKXHA`,
	"PathText": `CreateProjectModal-module__PathText--JzbY6`,
	"Footer": `CreateProjectModal-module__Footer--hGfvP`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 90962:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   $: () => (/* binding */ bugtracker)
/* harmony export */ });
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(79896);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _noodl_platform__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(37218);
/* harmony import */ var _shared_config_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(35313);
/* harmony import */ var _shared_config_config__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_shared_config_config__WEBPACK_IMPORTED_MODULE_2__);
// TODO: Replace all fs here



let bugtracker;
class EmptyBugTracker {
    identify(email) { }
    track(error, data) { }
    debug(info, data) { }
}
class BugTracker {
    constructor() {
        // @ts-expect-error
        console.stdlog = console.log.bind(console);
        console.log = function () {
            bugtracker.debug('Console log', arguments);
            // @ts-expect-error
            console.stdlog.apply(console, arguments);
        };
        if (typeof window !== 'undefined') {
            window.onerror = function (message, file, line, col, error) {
                const text = typeof message === 'string' ? message : message.toString();
                bugtracker.track(text, {
                    file: file,
                    line: line,
                    col: col,
                    error: error
                });
                return false;
            };
        }
    }
    identify(email) {
        /*  const TrackJS = require('trackjs').TrackJS;
        TrackJS.configure({
            userId: email,
        })*/
    }
    track(error, data) {
        if (!_noodl_platform__WEBPACK_IMPORTED_MODULE_1__.filesystem.exists(logFilePath)) {
            fs__WEBPACK_IMPORTED_MODULE_0___default().writeFileSync(logFilePath, '');
        }
        //   if(data) TrackJS.console.debug(error,data);
        // TrackJS.track(error);
        fs__WEBPACK_IMPORTED_MODULE_0___default().appendFileSync(logFilePath, 'Error: ' + error + '\n');
        const err = new Error();
        fs__WEBPACK_IMPORTED_MODULE_0___default().appendFileSync(logFilePath, 'Stack: ' + err.stack + '\n');
        if (data) {
            const dataStr = JSON.stringify(data, null, 2).slice(0, 10000);
            fs__WEBPACK_IMPORTED_MODULE_0___default().appendFileSync(logFilePath, dataStr + '\n');
        }
    }
    debug(info, data) {
        if (!_noodl_platform__WEBPACK_IMPORTED_MODULE_1__.filesystem.exists(logFilePath)) {
            fs__WEBPACK_IMPORTED_MODULE_0___default().writeFileSync(logFilePath, '');
        }
        //       TrackJS.console.debug(info, data);
        fs__WEBPACK_IMPORTED_MODULE_0___default().appendFileSync(logFilePath, 'Info: ' + info + '\n');
        if (data) {
            try {
                const dataStr = JSON.stringify(data, null, 2).slice(0, 10000);
                fs__WEBPACK_IMPORTED_MODULE_0___default().appendFileSync(logFilePath, dataStr + '\n');
            }
            catch (error) {
                // TypeError: Converting circular structure to JSON
                // TODO: How do we want to handle this error?
                console.error(error);
            }
        }
    }
}
function datePathExt(date) {
    return date.toUTCString().replace(/[:\ ,]/g, '-');
}
const logFileDir = _noodl_platform__WEBPACK_IMPORTED_MODULE_1__.filesystem.join(_noodl_platform__WEBPACK_IMPORTED_MODULE_1__.platform.getUserDataPath(), 'debug');
const logFilePath = _noodl_platform__WEBPACK_IMPORTED_MODULE_1__.filesystem.join(logFileDir, `log-${datePathExt(new Date())}.txt`);
_noodl_platform__WEBPACK_IMPORTED_MODULE_1__.filesystem.makeDirectory(logFileDir);
const enabled = !(_shared_config_config__WEBPACK_IMPORTED_MODULE_2___default().devMode);
bugtracker = enabled ? new BugTracker() : new EmptyBugTracker();



/***/ }),

/***/ 91102:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

/*! For license information please see index.js.LICENSE.txt */
!function(e,o){if(true)module.exports=o(__webpack_require__(5435));else // removed by dead control flow
{ var t, r; }}(this,e=>(()=>{"use strict";var o={370:o=>{o.exports=e}},r={};function t(e){var l=r[e];if(void 0!==l)return l.exports;var n=r[e]={exports:{}};return o[e](n,n.exports,t),n.exports}t.n=e=>{var o=e&&e.__esModule?()=>e.default:()=>e;return t.d(o,{a:o}),o},t.d=(e,o)=>{for(var r in o)t.o(o,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:o[r]})},t.o=(e,o)=>Object.prototype.hasOwnProperty.call(e,o),t.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var l={};t.r(l),t.d(l,{default:()=>u});var n=t(370);const u=n.Theme.defineTheme("dark",{name:"dark",base:n.Themes.Classic,componentStyles:{workspaceBackgroundColour:"#1e1e1e",toolboxBackgroundColour:"#333",toolboxForegroundColour:"#fff",flyoutBackgroundColour:"#252526",flyoutForegroundColour:"#ccc",flyoutOpacity:1,scrollbarColour:"#797979",insertionMarkerColour:"#fff",insertionMarkerOpacity:.3,scrollbarOpacity:.4,cursorColour:"#d0d0d0"}});return l})());
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 91288:
/***/ ((module) => {

"use strict";
module.exports = require("electron");

/***/ }),

/***/ 91559:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  F: () => (/* binding */ CreateNewNodePanel)
});

// EXTERNAL MODULE: external "electron"
var external_electron_ = __webpack_require__(91288);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/react-dom/client.js
var client = __webpack_require__(25873);
// EXTERNAL MODULE: ./src/shared/view.js
var view = __webpack_require__(92207);
var view_default = /*#__PURE__*/__webpack_require__.n(view);
// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/index.ts
var nodelibrary = __webpack_require__(68091);
// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Tabs/index.ts + 2 modules
var Tabs = __webpack_require__(35315);
;// ./src/editor/src/views/NodePicker/NodePicker.context.tsx

const NodePickerContext = (0,external_react_.createContext)({
    isBlocked: false,
    doBlockPicker: null,
    doUnblockPicker: null,
    activeTab: null,
    setActiveTab: null
});
function NodePickerContextProvider({ children }) {
    const [isBlocked, setIsBlocked] = (0,external_react_.useState)(false);
    const [activeTab, setActiveTab] = (0,external_react_.useState)('Nodes');
    return (external_react_default().createElement(NodePickerContext.Provider, { value: {
            isBlocked: isBlocked,
            doBlockPicker: () => setIsBlocked(true),
            doUnblockPicker: () => setIsBlocked(false),
            activeTab,
            setActiveTab
        } }, children));
}
function useNodePickerContext() {
    const context = (0,external_react_.useContext)(NodePickerContext);
    if (context === undefined) {
        throw new Error('useNodePickerContext must be a child of WorkspaceContextProvider');
    }
    return context;
}

// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NodePicker/NodePicker.module.scss
var NodePicker_module = __webpack_require__(71101);
;// ./src/editor/src/views/NodePicker/NodePicker.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(NodePicker_module/* default */.A, options);




       /* harmony default export */ const NodePicker_NodePicker_module = (NodePicker_module/* default */.A && NodePicker_module/* default */.A.locals ? NodePicker_module/* default */.A.locals : undefined);

// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.ts + 4 modules
var projectmodel = __webpack_require__(6203);
// EXTERNAL MODULE: ./src/editor/src/utils/LocalProjectsModel.ts + 4 modules
var LocalProjectsModel = __webpack_require__(47426);
// EXTERNAL MODULE: ./src/editor/src/utils/projectimporter.js
var projectimporter = __webpack_require__(11684);
var projectimporter_default = /*#__PURE__*/__webpack_require__.n(projectimporter);
// EXTERNAL MODULE: ./src/shared/model.js
var model = __webpack_require__(47821);
var model_default = /*#__PURE__*/__webpack_require__.n(model);
// EXTERNAL MODULE: ./src/shared/utils/EventDispatcher.ts
var EventDispatcher = __webpack_require__(11138);
// EXTERNAL MODULE: ./src/editor/src/ViewerConnection.ts
var ViewerConnection = __webpack_require__(71336);
// EXTERNAL MODULE: ./src/editor/src/views/importpopup.js
var importpopup = __webpack_require__(52501);
var importpopup_default = /*#__PURE__*/__webpack_require__.n(importpopup);
// EXTERNAL MODULE: ./src/editor/src/views/popuplayer.js
var popuplayer = __webpack_require__(45653);
var popuplayer_default = /*#__PURE__*/__webpack_require__.n(popuplayer);
// EXTERNAL MODULE: ./src/editor/src/views/ToastLayer/ToastLayer.tsx
var ToastLayer = __webpack_require__(80424);
;// ./src/editor/src/models/projectlibrarymodel.ts








const ImportOverwritePopupTemplate = __webpack_require__(94047);
const ImportPopupTemplate = __webpack_require__(72498);
class ProjectLibraryModel extends (model_default()) {
    constructor() {
        super();
    }
    async importProject(projectEntry, onBeforePopup, onAfterPopup) {
        const dirEntry = await this.getProjectRootDir(projectEntry)
            .then((project) => project)
            .catch(console.log);
        // project._retainedProjectDirectory
        const activityId = 'import-activity';
        ToastLayer.ToastLayer.showActivity('Importing...', activityId);
        return new Promise((resolve, reject) => {
            projectimporter_default().instance.listComponentsAndDependencies(dirEntry, async (imports) => {
                function doImport(selectedImports) {
                    ViewerConnection/* ViewerConnection */.t.instance.setWatchModelChangesEnabled(false);
                    projectimporter_default().instance.import(dirEntry, selectedImports, function (r) {
                        ViewerConnection/* ViewerConnection */.t.instance.setWatchModelChangesEnabled(true);
                        ToastLayer.ToastLayer.hideActivity(activityId);
                        if (r.result !== 'success') {
                            reject({ message: r.message });
                            popuplayer_default().instance.hideAllModalsAndPopups();
                        }
                        // Reload the viewer
                        EventDispatcher.EventDispatcher.instance.emit('viewer-refresh');
                        EventDispatcher.EventDispatcher.instance.emit('ProjectModel.importComplete');
                        resolve(true);
                        popuplayer_default().instance.hideAllModalsAndPopups();
                    });
                }
                onBeforePopup && onBeforePopup();
                const chooseImportsPopup = new (importpopup_default())({
                    template: ImportPopupTemplate,
                    imports,
                    onOk: function () {
                        // User have made choice of what to import, check if there are any collisions
                        const selectedImports = chooseImportsPopup.getSelectedImports();
                        projectimporter_default().instance.checkForCollisions(selectedImports, function (collisions) {
                            if (collisions === undefined) {
                                // No collisions
                                doImport(selectedImports);
                            }
                            else {
                                ToastLayer.ToastLayer.hideActivity(activityId);
                                // There is a collision for import, promt user if we should overwrite
                                var overwritePopup = new (importpopup_default())({
                                    template: ImportOverwritePopupTemplate,
                                    initAllAsImport: true,
                                    ignoreDependencies: true,
                                    imports: collisions,
                                    onOk: function () {
                                        onAfterPopup && onAfterPopup();
                                        projectimporter_default().instance.filterImports(selectedImports, {
                                            remove: overwritePopup.getUnselectedImports()
                                        });
                                        doImport(selectedImports);
                                    },
                                    onCancel: function () {
                                        onAfterPopup && onAfterPopup();
                                        popuplayer_default().instance.hideModal(undefined);
                                        reject({ message: 'Cancelled import' });
                                    }
                                });
                                overwritePopup.render();
                                popuplayer_default().instance.showModal({
                                    content: overwritePopup
                                });
                            }
                        });
                    },
                    onCancel: function () {
                        onAfterPopup && onAfterPopup();
                        popuplayer_default().instance.hideModal(undefined);
                        reject({ message: 'Cancelled import' });
                    }
                });
                chooseImportsPopup.render();
                ToastLayer.ToastLayer.hideActivity(activityId);
                popuplayer_default().instance.showModal({
                    content: chooseImportsPopup
                });
            });
        });
    }
    async getProjectRootDir(projectItem) {
        console.log(projectItem);
        const activityId = 'getting-root';
        ToastLayer.ToastLayer.showActivity('Loading project', activityId);
        const project = await LocalProjectsModel/* LocalProjectsModel */.h.instance.loadProject(projectItem);
        ToastLayer.ToastLayer.hideProgress(activityId);
        if (project) {
            return project._retainedProjectDirectory;
        }
        else {
            throw new Error('Couldnt load project');
        }
    }
}
ProjectLibraryModel.instance = new ProjectLibraryModel();

// EXTERNAL MODULE: ./src/editor/src/utils/utils.ts
var utils = __webpack_require__(93015);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/ActivityIndicator/index.ts + 2 modules
var ActivityIndicator = __webpack_require__(12093);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/inputs/PrimaryButton/index.ts + 2 modules
var PrimaryButton = __webpack_require__(76302);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/index.ts
var Text = __webpack_require__(93834);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/Text.tsx + 1 modules
var Text_Text = __webpack_require__(75864);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Title/index.ts
var Title = __webpack_require__(48237);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Title/Title.tsx + 1 modules
var Title_Title = __webpack_require__(79015);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NodePicker/components/ProjectCard/ProjectCard.module.scss
var ProjectCard_module = __webpack_require__(40343);
;// ./src/editor/src/views/NodePicker/components/ProjectCard/ProjectCard.module.scss

      
      
      
      
      
      
      
      
      

var ProjectCard_module_options = {};

ProjectCard_module_options.styleTagTransform = (styleTagTransform_default());
ProjectCard_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ProjectCard_module_options.insert = insertBySelector_default().bind(null, "head");
    
ProjectCard_module_options.domAPI = (styleDomAPI_default());
ProjectCard_module_options.insertStyleElement = (insertStyleElement_default());

var ProjectCard_module_update = injectStylesIntoStyleTag_default()(ProjectCard_module/* default */.A, ProjectCard_module_options);




       /* harmony default export */ const ProjectCard_ProjectCard_module = (ProjectCard_module/* default */.A && ProjectCard_module/* default */.A.locals ? ProjectCard_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/NodePicker/components/ProjectCard/ProjectCard.tsx












var CardState;
(function (CardState) {
    CardState["Idle"] = "is-idle";
    CardState["Downloading"] = "is-downloading";
    CardState["Finished"] = "is-finished";
    CardState["Cancelled"] = "is-cancelled";
})(CardState || (CardState = {}));
function ProjectCard({ project }) {
    const context = useNodePickerContext();
    const [cardState, setCardState] = (0,external_react_.useState)(CardState.Idle);
    const [cancelMessage, setCancelMessage] = (0,external_react_.useState)('');
    function handleDownload() {
        setCardState(CardState.Downloading);
        ProjectLibraryModel.instance
            .importProject(project, context.doBlockPicker, context.doUnblockPicker)
            .then(() => setCardState(CardState.Finished))
            .catch((error) => {
            setCardState(CardState.Cancelled);
            setCancelMessage(error.message);
        })
            .finally(() => setTimeout(() => setCardState(CardState.Idle), 3000));
    }
    return (external_react_default().createElement("article", { className: external_classnames_default()(ProjectCard_ProjectCard_module['Root'], ProjectCard_ProjectCard_module[cardState]) },
        external_react_default().createElement("div", { className: ProjectCard_ProjectCard_module['ImageContainer'] },
            external_react_default().createElement("div", { className: ProjectCard_ProjectCard_module['Image'], style: { backgroundImage: `url(${project.thumbURI})` } })),
        external_react_default().createElement("div", { className: ProjectCard_ProjectCard_module['Content'] },
            external_react_default().createElement("div", null,
                external_react_default().createElement("header", null,
                    external_react_default().createElement(Title/* Title */.hE, { hasBottomSpacing: true }, project.name),
                    project.latestAccessed && (external_react_default().createElement(Text/* Text */.EY, { textType: Text_Text/* TextType */.M2.Shy },
                        "Last accessed ",
                        (0,utils.timeSince)(project.latestAccessed),
                        " ago")))),
            external_react_default().createElement("div", { className: ProjectCard_ProjectCard_module['HoverOverlay'] },
                external_react_default().createElement("div", { className: ProjectCard_ProjectCard_module['CtaContainer'] },
                    external_react_default().createElement(PrimaryButton/* PrimaryButton */.jn, { label: "Import", onClick: () => handleDownload() }))),
            external_react_default().createElement("div", { className: ProjectCard_ProjectCard_module['ImportIndicator'] },
                external_react_default().createElement(Title/* Title */.hE, { isCentered: true, hasBottomSpacing: true }, "Importing module"),
                external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null)),
            external_react_default().createElement("div", { className: ProjectCard_ProjectCard_module['SuccessToast'] },
                external_react_default().createElement(Title/* Title */.hE, { variant: Title_Title/* TitleVariant */.Is.Success, isCentered: true, hasBottomSpacing: true }, "Successfully imported"),
                external_react_default().createElement(Text/* Text */.EY, null, project.name)),
            external_react_default().createElement("div", { className: ProjectCard_ProjectCard_module['CancelToast'] },
                external_react_default().createElement(Title/* Title */.hE, { variant: Title_Title/* TitleVariant */.Is.Danger, isCentered: true }, cancelMessage)))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NodePicker/tabs/ImportFromProject/ImportFromProject.module.scss
var ImportFromProject_module = __webpack_require__(87827);
;// ./src/editor/src/views/NodePicker/tabs/ImportFromProject/ImportFromProject.module.scss

      
      
      
      
      
      
      
      
      

var ImportFromProject_module_options = {};

ImportFromProject_module_options.styleTagTransform = (styleTagTransform_default());
ImportFromProject_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ImportFromProject_module_options.insert = insertBySelector_default().bind(null, "head");
    
ImportFromProject_module_options.domAPI = (styleDomAPI_default());
ImportFromProject_module_options.insertStyleElement = (insertStyleElement_default());

var ImportFromProject_module_update = injectStylesIntoStyleTag_default()(ImportFromProject_module/* default */.A, ImportFromProject_module_options);




       /* harmony default export */ const ImportFromProject_ImportFromProject_module = (ImportFromProject_module/* default */.A && ImportFromProject_module/* default */.A.locals ? ImportFromProject_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/NodePicker/tabs/ImportFromProject/ImportFromProject.tsx





// eslint-disable-next-line no-empty-pattern
function ImportFromProject({}) {
    const projects = (0,external_react_.useMemo)(() => LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects(), []);
    const currentProjectId = projectmodel.ProjectModel.instance.id;
    return (external_react_default().createElement("div", { style: { overflowY: 'scroll' } }, Boolean(projects.length) && (external_react_default().createElement("ul", { className: ImportFromProject_ImportFromProject_module['Grid'] }, projects.map((project) => {
        if (project.id === currentProjectId)
            return null;
        return (external_react_default().createElement("li", { key: project.id, className: ImportFromProject_ImportFromProject_module['GridItem'] },
            external_react_default().createElement(ProjectCard, { project: project })));
    })))));
}

// EXTERNAL MODULE: ../noodl-platform/src/index.ts + 10 modules
var src = __webpack_require__(37218);
// EXTERNAL MODULE: ./src/editor/src/models/sidebar/index.ts
var sidebar = __webpack_require__(53612);
// EXTERNAL MODULE: ./src/editor/src/constants/NodeType.ts
var NodeType = __webpack_require__(20396);
// EXTERNAL MODULE: ./src/editor/src/utils/NodeGraph/index.ts
var NodeGraph = __webpack_require__(52877);
;// ./src/editor/src/utils/createnodeindex.ts



function createNodeIndex(model, parentModel, runtimeType) {
    function isNodeCreatable(nodeType) {
        // @ts-expect-error Wrong to be both NodeLibraryNodeType and ComponentModel
        if (runtimeType && nodeType.runtimeTypes && !nodeType.runtimeTypes.includes(runtimeType)) {
            return false;
        }
        // Check if node can be created with the current parent
        const status = model.owner.getCreateStatus({
            parent: parentModel,
            type: nodeType
        });
        return status.creatable;
    }
    function getNodes(names) {
        return names
            .map((name) => {
            const nodeType = nodelibrary/* NodeLibrary */.m.instance.getNodeTypeWithName(name);
            if (!nodeType)
                return undefined;
            if (isNodeCreatable(nodeType))
                return nodeType;
        })
            .filter(Boolean); // filter out all empty
    }
    // parse core nodes
    const coreNodes = nodelibrary/* NodeLibrary */.m.instance.library.nodeIndex.coreNodes
        .map((category) => {
        const subCategories = (category === null || category === void 0 ? void 0 : category.subCategories)
            ? category.subCategories.map((subCategory) => {
                // Fetch all the subCategories items (nodes)
                return {
                    name: subCategory.name,
                    items: getNodes(subCategory.items)
                };
            })
            : [];
        // Fetch all the top category items (nodes)
        const items = (category === null || category === void 0 ? void 0 : category.items) ? getNodes(category.items) : [];
        return {
            ...category,
            subCategories,
            items
        };
    })
        .filter((category) => {
        let shouldKeepCategory = false;
        category.subCategories.forEach((subCategory) => {
            if (subCategory.items.length) {
                shouldKeepCategory = true;
            }
        });
        if (category.items.length) {
            shouldKeepCategory = true;
        }
        return shouldKeepCategory;
    });
    // build custom nodes
    const customNodes = [];
    const componentNodes = nodelibrary/* NodeLibrary */.m.instance
        .getComponents()
        .filter(isNodeCreatable)
        .filter((nodeModel) => {
        const nodeModelRuntimeType = (0,NodeGraph/* getComponentModelRuntimeType */.$j)(nodeModel);
        return runtimeType === nodeModelRuntimeType;
    });
    if (componentNodes === null || componentNodes === void 0 ? void 0 : componentNodes.length) {
        customNodes.push({
            name: 'Project components',
            description: 'Custom components in the project',
            type: NodeType/* NodeType */.Z.None,
            subCategories: [
                {
                    name: '',
                    items: componentNodes
                }
            ]
        });
    }
    const moduleNodes = nodelibrary/* NodeLibrary */.m.instance.library.nodeIndex.moduleNodes;
    if (moduleNodes === null || moduleNodes === void 0 ? void 0 : moduleNodes.length) {
        const subCategories = moduleNodes
            .map((subCategory) => ({
            name: subCategory.name,
            items: getNodes(subCategory.items)
        }))
            .filter((subCategory) => Boolean(subCategory.items.length));
        if (subCategories.length > 0) {
            customNodes.push({
                name: 'External libraries',
                description: 'Third party Noodl integrations',
                type: NodeType/* NodeType */.Z.None,
                subCategories
            });
        }
    }
    return {
        coreNodes,
        customNodes
    };
}

// EXTERNAL MODULE: ./src/editor/src/utils/tracker/index.ts + 1 modules
var tracker = __webpack_require__(38986);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/HtmlRenderer/index.ts + 2 modules
var HtmlRenderer = __webpack_require__(88569);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/inputs/SearchInput/index.ts + 2 modules
var SearchInput = __webpack_require__(16202);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Box/index.ts + 2 modules
var Box = __webpack_require__(22484);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Center/index.ts + 2 modules
var Center = __webpack_require__(92394);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Stack/index.ts + 2 modules
var Stack = __webpack_require__(86380);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/Carousel/Carousel.module.scss
var Carousel_module = __webpack_require__(51251);
;// ../noodl-core-ui/src/components/layout/Carousel/Carousel.module.scss

      
      
      
      
      
      
      
      
      

var Carousel_module_options = {};

Carousel_module_options.styleTagTransform = (styleTagTransform_default());
Carousel_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      Carousel_module_options.insert = insertBySelector_default().bind(null, "head");
    
Carousel_module_options.domAPI = (styleDomAPI_default());
Carousel_module_options.insertStyleElement = (insertStyleElement_default());

var Carousel_module_update = injectStylesIntoStyleTag_default()(Carousel_module/* default */.A, Carousel_module_options);




       /* harmony default export */ const Carousel_Carousel_module = (Carousel_module/* default */.A && Carousel_module/* default */.A.locals ? Carousel_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/Carousel/Carousel.tsx





function Carousel({ activeIndex, items, indicator }) {
    const sliderRefs = (0,external_react_.useRef)([]);
    const [currentIndex, setCurrentIndex] = (0,external_react_.useState)(activeIndex || 0);
    (0,external_react_.useEffect)(() => {
        setCurrentIndex(activeIndex);
        if (sliderRefs.current[activeIndex]) {
            sliderRefs.current[activeIndex].scrollIntoView({
                behavior: 'auto'
            });
        }
    }, [activeIndex]);
    if (typeof currentIndex === 'number' && sliderRefs.current[currentIndex]) {
        sliderRefs.current[currentIndex].scrollIntoView({
            behavior: 'smooth'
        });
    }
    return (external_react_default().createElement("div", { className: Carousel_Carousel_module['Root'] },
        external_react_default().createElement("div", { style: { overflow: 'hidden' } },
            external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { width: items.length * 100 + '%' } }, items.map((item, index) => (external_react_default().createElement(Stack/* VStack */.Tk, { key: index, ref: (ref) => { sliderRefs.current[index] = ref; }, UNSAFE_style: { width: '100%' } }, item.slot))))),
        indicator && (external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
            external_react_default().createElement(Center/* Center */.o, null,
                external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: 2 }, items.map((_, index) => external_react_default().createElement(indicator, {
                    key: index,
                    isActive: index === currentIndex,
                    onClick() {
                        setCurrentIndex(index);
                    }
                }))))))));
}

;// ../noodl-core-ui/src/components/layout/Carousel/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/CarouselIndicatorDot/CarouselIndicatorDot.module.scss
var CarouselIndicatorDot_module = __webpack_require__(69651);
;// ../noodl-core-ui/src/components/layout/CarouselIndicatorDot/CarouselIndicatorDot.module.scss

      
      
      
      
      
      
      
      
      

var CarouselIndicatorDot_module_options = {};

CarouselIndicatorDot_module_options.styleTagTransform = (styleTagTransform_default());
CarouselIndicatorDot_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      CarouselIndicatorDot_module_options.insert = insertBySelector_default().bind(null, "head");
    
CarouselIndicatorDot_module_options.domAPI = (styleDomAPI_default());
CarouselIndicatorDot_module_options.insertStyleElement = (insertStyleElement_default());

var CarouselIndicatorDot_module_update = injectStylesIntoStyleTag_default()(CarouselIndicatorDot_module/* default */.A, CarouselIndicatorDot_module_options);




       /* harmony default export */ const CarouselIndicatorDot_CarouselIndicatorDot_module = (CarouselIndicatorDot_module/* default */.A && CarouselIndicatorDot_module/* default */.A.locals ? CarouselIndicatorDot_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/CarouselIndicatorDot/CarouselIndicatorDot.tsx



function CarouselIndicatorDot({ isActive, onClick }) {
    return external_react_default().createElement("div", { className: external_classnames_default()([CarouselIndicatorDot_CarouselIndicatorDot_module['Root'], isActive && CarouselIndicatorDot_CarouselIndicatorDot_module['is-active']]), onClick: onClick });
}

;// ../noodl-core-ui/src/components/layout/CarouselIndicatorDot/index.ts


// EXTERNAL MODULE: ./src/editor/src/hooks/useCustomPropertyValue.ts
var useCustomPropertyValue = __webpack_require__(26225);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Collapsible/index.ts + 2 modules
var Collapsible = __webpack_require__(20014);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NodePicker/components/NodePickerCategory/NodePickerCategory.module.scss
var NodePickerCategory_module = __webpack_require__(72301);
;// ./src/editor/src/views/NodePicker/components/NodePickerCategory/NodePickerCategory.module.scss

      
      
      
      
      
      
      
      
      

var NodePickerCategory_module_options = {};

NodePickerCategory_module_options.styleTagTransform = (styleTagTransform_default());
NodePickerCategory_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      NodePickerCategory_module_options.insert = insertBySelector_default().bind(null, "head");
    
NodePickerCategory_module_options.domAPI = (styleDomAPI_default());
NodePickerCategory_module_options.insertStyleElement = (insertStyleElement_default());

var NodePickerCategory_module_update = injectStylesIntoStyleTag_default()(NodePickerCategory_module/* default */.A, NodePickerCategory_module_options);




       /* harmony default export */ const NodePickerCategory_NodePickerCategory_module = (NodePickerCategory_module/* default */.A && NodePickerCategory_module/* default */.A.locals ? NodePickerCategory_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/NodePicker/components/NodePickerCategory/NodePickerCategory.tsx









function NodePickerCategory({ title, description, children, type = NodeType/* NodeType */.Z.Visual, isKeyboardCursored, isCollapsed, disableTransition }) {
    const transitionSpeed = (0,useCustomPropertyValue/* useCustomPropertyValue */.l)(useCustomPropertyValue/* CustomPropertyAnimation */.X.SpeedQuick);
    const descriptionEasingFunction = (0,useCustomPropertyValue/* useCustomPropertyValue */.l)(useCustomPropertyValue/* CustomPropertyAnimation */.X.EasingEqual);
    const [isCollapsedState, setIsCollapsedState] = (0,external_react_.useState)(isCollapsed);
    const [isHighlightedState, setIsHighlightedState] = (0,external_react_.useState)(isKeyboardCursored);
    (0,external_react_.useEffect)(() => {
        setIsHighlightedState(isKeyboardCursored);
    }, [isKeyboardCursored]);
    (0,external_react_.useEffect)(() => {
        setIsCollapsedState(isCollapsed);
    }, [isCollapsed]);
    function addHighlight() {
        setIsHighlightedState(true);
    }
    function removeHighlight() {
        setIsHighlightedState(false);
    }
    return (external_react_default().createElement("section", { className: external_classnames_default()(NodePickerCategory_NodePickerCategory_module['Root'], NodePickerCategory_NodePickerCategory_module[`Root--is-theme-${type}`], isHighlightedState && NodePickerCategory_NodePickerCategory_module['Root--is-highlighted']), onMouseEnter: addHighlight, onMouseLeave: removeHighlight },
        external_react_default().createElement("header", { className: external_classnames_default()([NodePickerCategory_NodePickerCategory_module['Header'], NodePickerCategory_NodePickerCategory_module[`Header--is-theme-${type}`]]), onClick: () => setIsCollapsedState(!isCollapsedState) },
            external_react_default().createElement(Title/* Title */.hE, { variant: Title/* TitleVariant */.Is.Highlighted, size: Title/* TitleSize */.uM.Medium }, title),
            external_react_default().createElement(Collapsible/* Collapsible */.N, { isCollapsed: !isCollapsedState, transitionMs: transitionSpeed * 0.5, disableTransition: disableTransition, easingFunction: descriptionEasingFunction },
                external_react_default().createElement(Text/* Text */.EY, { textType: Text/* TextType */.M2.Default, size: Text/* TextSize */.$C.Medium }, description)),
            external_react_default().createElement(Icon/* Icon */.In, { icon: Icon/* IconName */.$M.CaretRight, size: Icon/* IconSize */.lK.Small, UNSAFE_className: external_classnames_default()([
                    NodePickerCategory_NodePickerCategory_module['Arrow'],
                    isCollapsedState ? NodePickerCategory_NodePickerCategory_module['Arrow--is-collapsed'] : NodePickerCategory_NodePickerCategory_module['Arrow--is-not-collapsed']
                ]) })),
        external_react_default().createElement(Collapsible/* Collapsible */.N, { isCollapsed: isCollapsedState, transitionMs: transitionSpeed, disableTransition: disableTransition },
            external_react_default().createElement("div", null, children))));
}

;// ./src/editor/src/views/NodePicker/components/NodePickerCategory/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/EditorNode/index.ts + 2 modules
var EditorNode = __webpack_require__(51183);
;// ./src/editor/src/views/NodePicker/components/NodePickerNode/NodePickerNode.tsx



function NodePickerNode({ item, isKeyboardCursored, doCreateSelectedNode, onClick, onGetDocs, onMouseLeave }) {
    const [isHighlightedState, setIsHighlightedState] = (0,external_react_.useState)(isKeyboardCursored);
    const rootRef = (0,external_react_.useRef)(null);
    (0,external_react_.useEffect)(() => {
        var _a;
        setIsHighlightedState(isKeyboardCursored);
        if (isKeyboardCursored) {
            (_a = rootRef === null || rootRef === void 0 ? void 0 : rootRef.current) === null || _a === void 0 ? void 0 : _a.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
            });
        }
    }, [isKeyboardCursored]);
    (0,external_react_.useEffect)(() => {
        if (isHighlightedState) {
            onGetDocs(item);
        }
    }, [isHighlightedState]);
    (0,external_react_.useEffect)(() => {
        if (isHighlightedState && doCreateSelectedNode && isKeyboardCursored) {
            handleClick();
        }
    }, [doCreateSelectedNode]);
    function handleMouseEnter() {
        setIsHighlightedState(true);
    }
    function handleMouseLeave() {
        setIsHighlightedState(false);
        onMouseLeave();
    }
    function handleClick() {
        onClick(item);
    }
    const colors = (0,external_react_.useMemo)(() => nodelibrary/* NodeLibrary */.m.instance.colorSchemeForNodeType(item), [item]);
    return (external_react_default().createElement("div", { onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, onClick: handleClick, ref: rootRef },
        external_react_default().createElement(EditorNode/* EditorNode */.c, { item: item, colors: colors, isHighlighted: isHighlightedState })));
}

;// ./src/editor/src/views/NodePicker/components/NodePickerNode/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NodePicker/components/NodePickerNodeGroup/NodePickerNodeGroup.module.scss
var NodePickerNodeGroup_module = __webpack_require__(26047);
;// ./src/editor/src/views/NodePicker/components/NodePickerNodeGroup/NodePickerNodeGroup.module.scss

      
      
      
      
      
      
      
      
      

var NodePickerNodeGroup_module_options = {};

NodePickerNodeGroup_module_options.styleTagTransform = (styleTagTransform_default());
NodePickerNodeGroup_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      NodePickerNodeGroup_module_options.insert = insertBySelector_default().bind(null, "head");
    
NodePickerNodeGroup_module_options.domAPI = (styleDomAPI_default());
NodePickerNodeGroup_module_options.insertStyleElement = (insertStyleElement_default());

var NodePickerNodeGroup_module_update = injectStylesIntoStyleTag_default()(NodePickerNodeGroup_module/* default */.A, NodePickerNodeGroup_module_options);




       /* harmony default export */ const NodePickerNodeGroup_NodePickerNodeGroup_module = (NodePickerNodeGroup_module/* default */.A && NodePickerNodeGroup_module/* default */.A.locals ? NodePickerNodeGroup_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/NodePicker/components/NodePickerNodeGroup/NodePickerNodeGroup.tsx



function NodePickerNodeGroup({ items, parentCategoryName, doCreateSelectedNode, cursorState, nodeCursorMatcher, onGetDocs, onMouseLeaveNode, onCreateNode }) {
    if (!items.length)
        return null;
    return (external_react_default().createElement("ul", { className: NodePickerNodeGroup_NodePickerNodeGroup_module['Root'] }, items.map((item) => (external_react_default().createElement("li", { key: item.name, className: NodePickerNodeGroup_NodePickerNodeGroup_module['ItemContainer'] },
        external_react_default().createElement(NodePickerNode, { item: item, isKeyboardCursored: nodeCursorMatcher(cursorState, parentCategoryName, item.name), doCreateSelectedNode: doCreateSelectedNode, onClick: onCreateNode, onGetDocs: onGetDocs, onMouseLeave: onMouseLeaveNode }))))));
}

;// ./src/editor/src/views/NodePicker/components/NodePickerNodeGroup/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NodePicker/components/NodePickerOtherItem/NodePickerOtherItem.module.scss
var NodePickerOtherItem_module = __webpack_require__(26511);
;// ./src/editor/src/views/NodePicker/components/NodePickerOtherItem/NodePickerOtherItem.module.scss

      
      
      
      
      
      
      
      
      

var NodePickerOtherItem_module_options = {};

NodePickerOtherItem_module_options.styleTagTransform = (styleTagTransform_default());
NodePickerOtherItem_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      NodePickerOtherItem_module_options.insert = insertBySelector_default().bind(null, "head");
    
NodePickerOtherItem_module_options.domAPI = (styleDomAPI_default());
NodePickerOtherItem_module_options.insertStyleElement = (insertStyleElement_default());

var NodePickerOtherItem_module_update = injectStylesIntoStyleTag_default()(NodePickerOtherItem_module/* default */.A, NodePickerOtherItem_module_options);




       /* harmony default export */ const NodePickerOtherItem_NodePickerOtherItem_module = (NodePickerOtherItem_module/* default */.A && NodePickerOtherItem_module/* default */.A.locals ? NodePickerOtherItem_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/NodePicker/components/NodePickerOtherItem/NodePickerOtherItem.tsx





function NodePickerOtherItem({ title, description, icon, onClick }) {
    const [isHighlightedState, setIsHighlightedState] = (0,external_react_.useState)(false);
    function addHighlight() {
        setIsHighlightedState(true);
    }
    function removeHighlight() {
        setIsHighlightedState(false);
    }
    return (external_react_default().createElement("section", { className: external_classnames_default()(NodePickerOtherItem_NodePickerOtherItem_module['Root'], isHighlightedState && NodePickerOtherItem_NodePickerOtherItem_module['Root--is-highlighted']), onMouseEnter: addHighlight, onMouseLeave: removeHighlight },
        external_react_default().createElement("header", { className: external_classnames_default()(NodePickerOtherItem_NodePickerOtherItem_module['Header']), onClick: onClick },
            icon ? icon : null,
            external_react_default().createElement("div", { style: { marginLeft: icon ? '10px' : 0 } },
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Medium }, title),
                external_react_default().createElement(Text/* Text */.EY, { textType: Text/* TextType */.M2.Shy, size: Text/* TextSize */.$C.Medium }, description)))));
}

;// ./src/editor/src/views/NodePicker/components/NodePickerOtherItem/index.ts


;// ./src/editor/src/views/NodePicker/components/NodePickerSection/NodePickerSection.tsx

function NodePickerSection({ title, children }) {
    return (external_react_default().createElement("div", null,
        external_react_default().createElement("div", null, children)));
}

;// ./src/editor/src/views/NodePicker/components/NodePickerSection/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NodePicker/components/NodePickerSubCategory/NodePickerSubCategory.module.scss
var NodePickerSubCategory_module = __webpack_require__(95715);
;// ./src/editor/src/views/NodePicker/components/NodePickerSubCategory/NodePickerSubCategory.module.scss

      
      
      
      
      
      
      
      
      

var NodePickerSubCategory_module_options = {};

NodePickerSubCategory_module_options.styleTagTransform = (styleTagTransform_default());
NodePickerSubCategory_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      NodePickerSubCategory_module_options.insert = insertBySelector_default().bind(null, "head");
    
NodePickerSubCategory_module_options.domAPI = (styleDomAPI_default());
NodePickerSubCategory_module_options.insertStyleElement = (insertStyleElement_default());

var NodePickerSubCategory_module_update = injectStylesIntoStyleTag_default()(NodePickerSubCategory_module/* default */.A, NodePickerSubCategory_module_options);




       /* harmony default export */ const NodePickerSubCategory_NodePickerSubCategory_module = (NodePickerSubCategory_module/* default */.A && NodePickerSubCategory_module/* default */.A.locals ? NodePickerSubCategory_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/NodePicker/components/NodePickerSubCategory/NodePickerSubCategory.tsx



function NodePickerSubCategory({ title, children }) {
    return (external_react_default().createElement("div", null,
        title !== '' && (external_react_default().createElement("div", { className: NodePickerSubCategory_NodePickerSubCategory_module['Title'] },
            external_react_default().createElement(Text/* Text */.EY, { textType: Text/* TextType */.M2.Shy, size: Text/* TextSize */.$C.Small }, title))),
        external_react_default().createElement("div", null, children)));
}

;// ./src/editor/src/views/NodePicker/components/NodePickerSubCategory/index.ts


// EXTERNAL MODULE: ./src/editor/src/views/NodePicker/NodePicker.hooks.ts + 4 modules
var NodePicker_hooks = __webpack_require__(38943);
;// ./src/editor/src/views/NodePicker/NodePicker.selectors.ts
function getCursoredCategory(cursorState) {
    var _a;
    return (_a = cursorState === null || cursorState === void 0 ? void 0 : cursorState.allCategories) === null || _a === void 0 ? void 0 : _a[cursorState.categoryCursor];
}
function getCursoredNode(cursorState) {
    var _a, _b, _c;
    return (_c = (_b = (_a = cursorState === null || cursorState === void 0 ? void 0 : cursorState.allCategories) === null || _a === void 0 ? void 0 : _a[cursorState.categoryCursor]) === null || _b === void 0 ? void 0 : _b.nodes) === null || _c === void 0 ? void 0 : _c[cursorState.nodeCursor];
}
function getIsCategoryCursorMatchingCategory(cursorState, categoryName) {
    var _a;
    return ((_a = getCursoredCategory(cursorState)) === null || _a === void 0 ? void 0 : _a.name) === categoryName;
}
function getIsNodeCursorMatchingNode(cursorState, categoryName, nodeName) {
    var _a;
    return (getIsCategoryCursorMatchingCategory(cursorState, categoryName) && ((_a = getCursoredNode(cursorState)) === null || _a === void 0 ? void 0 : _a.name) === nodeName);
}
function getIsCategoryCollapsed(cursorState, categoryName) {
    const category = cursorState === null || cursorState === void 0 ? void 0 : cursorState.allCategories.find((category) => category.name === categoryName);
    return category ? category.isCollapsed : true;
}

// EXTERNAL MODULE: ./src/editor/src/models/nodegraphmodel/index.ts + 4 modules
var nodegraphmodel = __webpack_require__(87844);
// EXTERNAL MODULE: ./src/editor/src/views/CommentLayer/CommentLayerView.tsx + 4 modules
var CommentLayerView = __webpack_require__(23776);
;// ./src/editor/src/views/NodePicker/NodePicker.utils.ts



function parseNodeObject(nodeTypes, model, parentModel) {
    var _a, _b;
    const resultTree = [];
    for (const i in nodeTypes) {
        const nodeType = nodeTypes[i];
        // Check if node can be created with the current parent
        const status = model.owner.getCreateStatus({
            parent: parentModel,
            type: nodeType
        });
        if (!status.creatable)
            continue;
        // Add to result if allowed, build the tree if necessary
        let currentCategoryInTree = resultTree === null || resultTree === void 0 ? void 0 : resultTree.find((item) => item.name === nodeType.category);
        if (!currentCategoryInTree) {
            resultTree.push({
                name: nodeType.category,
                type: nodeType.color,
                description: 'TODO',
                subCategories: [],
                items: []
            });
            currentCategoryInTree = resultTree.find((item) => item.name === nodeType.category);
        }
        let currentSubCategoryInTree = (_a = currentCategoryInTree === null || currentCategoryInTree === void 0 ? void 0 : currentCategoryInTree.subCategories) === null || _a === void 0 ? void 0 : _a.find((subCategory) => subCategory.name === (nodeType === null || nodeType === void 0 ? void 0 : nodeType.subCategory));
        if (typeof nodeType.subCategory !== 'undefined') {
            if (!currentSubCategoryInTree) {
                currentCategoryInTree.subCategories.push({
                    name: nodeType.subCategory,
                    items: []
                });
                currentSubCategoryInTree = (_b = currentCategoryInTree.subCategories) === null || _b === void 0 ? void 0 : _b.find((subCategory) => subCategory.name === (nodeType === null || nodeType === void 0 ? void 0 : nodeType.subCategory));
            }
            currentSubCategoryInTree.items.push(nodeType);
        }
        else {
            currentCategoryInTree.items.push(nodeType);
        }
    }
    return resultTree;
}
function createNodeFunction(model, parentModel, pos, attachToRoot) {
    return (type) => {
        const node = nodegraphmodel/* NodeGraphNode */.dF.fromJSON({
            type: type.name,
            version: type.version,
            x: pos.x,
            y: pos.y,
            id: (0,utils.guid)()
        });
        if (parentModel) {
            parentModel.addChild(node, { undo: true, label: 'create' });
        }
        else if (attachToRoot) {
            for (const root of model.roots) {
                if (root.canAcceptChildren([node])) {
                    root.addChild(node, { undo: true, label: 'create' });
                }
            }
            if (node.parent === undefined)
                // Couldn't find compatiable root
                model.addRoot(node, { undo: true, label: 'create' });
        }
        else {
            model.addRoot(node, { undo: true, label: 'create' });
        }
    };
}
function createNewComment(model, pos) {
    const comment = {
        text: '',
        width: 150,
        height: 100,
        fill: CommentLayerView/* CommentFillStyle */.KK.Transparent,
        x: pos.x,
        y: pos.y
    };
    model.commentsModel.addComment(comment, { undo: true, label: 'add comment', focusComment: true });
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NodePicker/tabs/NodeLibrary/NodeLibrary.module.scss
var NodeLibrary_module = __webpack_require__(82579);
;// ./src/editor/src/views/NodePicker/tabs/NodeLibrary/NodeLibrary.module.scss

      
      
      
      
      
      
      
      
      

var NodeLibrary_module_options = {};

NodeLibrary_module_options.styleTagTransform = (styleTagTransform_default());
NodeLibrary_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      NodeLibrary_module_options.insert = insertBySelector_default().bind(null, "head");
    
NodeLibrary_module_options.domAPI = (styleDomAPI_default());
NodeLibrary_module_options.insertStyleElement = (insertStyleElement_default());

var NodeLibrary_module_update = injectStylesIntoStyleTag_default()(NodeLibrary_module/* default */.A, NodeLibrary_module_options);




       /* harmony default export */ const NodeLibrary_NodeLibrary_module = (NodeLibrary_module/* default */.A && NodeLibrary_module/* default */.A.locals ? NodeLibrary_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/NodePicker/tabs/NodeLibrary/NodeLibrary.tsx


























function NodeLibrary({ model, parentModel, pos, attachToRoot, runtimeType }) {
    var _a, _b;
    // const defaultDocsCards = useGetDefaultDocs();
    const news = (0,NodePicker_hooks/* useGetSliderNews */.i$)();
    const { getDocs, cancelGetDocs, currentDocs } = (0,NodePicker_hooks/* useDocs */.$Q)();
    const [items] = (0,external_react_.useState)(createNodeIndex(model, parentModel, runtimeType));
    const [renderedNodes, setRenderedNodes] = (0,external_react_.useState)(items);
    const { cursorState, openAllCategories, closeAllCategories, handleSearchUpdate, focusSearch, enableCollapseTransition, disableCollapseTransition } = (0,NodePicker_hooks/* useKeyboardCursor */.hd)(renderedNodes);
    const createNode = createNodeFunction(model, parentModel, pos, attachToRoot);
    const searchInput = (0,external_react_.useRef)(null);
    const setSearchTerm = (0,NodePicker_hooks/* useSearchBar */.VK)(searchInput, setRenderedNodes, items, cursorState.cursorContext, openAllCategories, closeAllCategories, handleSearchUpdate);
    //TODO: make this fit better into the NodePicker structure
    let showCommentAction = true;
    if (searchInput.current && searchInput.current.value.length > 0) {
        showCommentAction = 'comments'.includes(searchInput.current.value.toLowerCase());
    }
    return (external_react_default().createElement("div", { className: NodeLibrary_NodeLibrary_module['Root'] },
        external_react_default().createElement("div", { className: NodeLibrary_NodeLibrary_module['SearchContainer'] },
            external_react_default().createElement(SearchInput/* SearchInput */.D, { placeholder: "Search for nodes and components", inputRef: searchInput, onChange: setSearchTerm, onClick: () => focusSearch() })),
        external_react_default().createElement("div", { className: NodeLibrary_NodeLibrary_module['Content'] },
            external_react_default().createElement("nav", { className: external_classnames_default()([NodeLibrary_NodeLibrary_module['Navbar'], NodeLibrary_NodeLibrary_module['ScrollableContainer']]), onMouseOver: enableCollapseTransition, onMouseLeave: disableCollapseTransition },
                external_react_default().createElement("div", { className: NodeLibrary_NodeLibrary_module['NavbarInner'] },
                    external_react_default().createElement("div", null,
                        external_react_default().createElement(NodePickerSection, { key: "Core nodes", title: "Core nodes" }, (_a = renderedNodes.coreNodes) === null || _a === void 0 ? void 0 : _a.map((category) => {
                            var _a;
                            return (external_react_default().createElement(NodePickerCategory, { key: category.name, title: category.name, description: category.description, disableTransition: cursorState.disableCollapseTransition, isCollapsed: getIsCategoryCollapsed(cursorState, category.name), type: category.type, isKeyboardCursored: getIsCategoryCursorMatchingCategory(cursorState, category.name) }, (_a = category === null || category === void 0 ? void 0 : category.subCategories) === null || _a === void 0 ? void 0 : _a.map((subCategory) => {
                                var _a;
                                return !!((_a = subCategory === null || subCategory === void 0 ? void 0 : subCategory.items) === null || _a === void 0 ? void 0 : _a.length) && (external_react_default().createElement(NodePickerSubCategory, { key: subCategory.name, title: subCategory.name },
                                    external_react_default().createElement(NodePickerNodeGroup, { items: subCategory.items, parentCategoryName: category.name, cursorState: cursorState, nodeCursorMatcher: getIsNodeCursorMatchingNode, doCreateSelectedNode: cursorState === null || cursorState === void 0 ? void 0 : cursorState.allowNodeCreation, onGetDocs: getDocs, onMouseLeaveNode: cancelGetDocs, onCreateNode: createNode })));
                            })));
                        })),
                        renderedNodes.customNodes.length ? (external_react_default().createElement(NodePickerSection, { key: "Custom nodes", title: "Custom nodes" }, (_b = renderedNodes.customNodes) === null || _b === void 0 ? void 0 : _b.map((category) => {
                            var _a, _b;
                            return (external_react_default().createElement(NodePickerCategory, { key: category.name, title: category.name, description: category.description, disableTransition: cursorState.disableCollapseTransition ||
                                    //disable the collapse transition if a category has more than 50 items. This addresses
                                    //a performance issue when the "Project Components" category has a lot of components since the
                                    //Collapsible component will render _all_ of them to be able to perform a transition
                                    ((_a = category.subCategories) === null || _a === void 0 ? void 0 : _a.reduce((prev, x) => prev + x.items.length, 0)) > 50, isCollapsed: getIsCategoryCollapsed(cursorState, category.name), isKeyboardCursored: getIsCategoryCursorMatchingCategory(cursorState, category.name) }, (_b = category === null || category === void 0 ? void 0 : category.subCategories) === null || _b === void 0 ? void 0 : _b.map((subCategory) => {
                                var _a;
                                return !!((_a = subCategory === null || subCategory === void 0 ? void 0 : subCategory.items) === null || _a === void 0 ? void 0 : _a.length) && (external_react_default().createElement(NodePickerSubCategory, { key: subCategory.name, title: subCategory.name },
                                    external_react_default().createElement(NodePickerNodeGroup, { items: subCategory.items, parentCategoryName: category.name, cursorState: cursorState, nodeCursorMatcher: getIsNodeCursorMatchingNode, doCreateSelectedNode: cursorState === null || cursorState === void 0 ? void 0 : cursorState.allowNodeCreation, onGetDocs: getDocs, onMouseLeaveNode: cancelGetDocs, onCreateNode: createNode })));
                            })));
                        }))) : null),
                    showCommentAction ? (external_react_default().createElement(NodePickerSection, { key: "Other", title: "Other" },
                        external_react_default().createElement(NodePickerOtherItem, { title: "Comment", description: "Place a comment in the node graph", onClick: (e) => {
                                createNewComment(model, pos);
                                e.stopPropagation();
                            }, icon: external_react_default().createElement(Icon/* Icon */.In, { icon: Icon/* IconName */.$M.Chat, size: Icon/* IconSize */.lK.Default }) }))) : null)),
            external_react_default().createElement("article", { className: NodeLibrary_NodeLibrary_module['Docs'] },
                currentDocs.url ? (external_react_default().createElement("div", { className: NodeLibrary_NodeLibrary_module['FullDocsButton'] },
                    external_react_default().createElement(PrimaryButton/* PrimaryButton */.jn, { size: PrimaryButton/* PrimaryButtonSize */._S.Small, variant: PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, label: "Open full docs", onClick: () => {
                            tracker.tracker.track('Open Node Docs Clicked', { url: currentDocs.url });
                            src.platform.openExternal(currentDocs.url);
                        } }))) : (external_react_default().createElement(Carousel, { items: news.items.map((x) => ({
                        slot: external_react_default().createElement(NodePickerSlider, { ...x })
                    })), indicator: CarouselIndicatorDot, activeIndex: news.activeIndex })),
                external_react_default().createElement(HtmlRenderer/* HtmlRenderer */.j, { html: currentDocs.content })))));
}
function NodePickerSlider({ supertitle, title, text, action, imageUrl }) {
    return (external_react_default().createElement("div", { style: { display: 'flex', flexDirection: 'column', justifyContent: 'space-between', height: '100%' } },
        external_react_default().createElement(Box/* Box */.a, null,
            external_react_default().createElement(Title/* Title */.hE, { isCentered: true, variant: Title/* TitleVariant */.Is.Default }, supertitle),
            external_react_default().createElement(Title/* Title */.hE, { isCentered: true, variant: Title/* TitleVariant */.Is.Highlighted, size: Title/* TitleSize */.uM.Large }, title),
            external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasYSpacing: true },
                external_react_default().createElement(Text/* Text */.EY, { isCentered: true }, text)),
            action && external_react_default().createElement(NodePickerSliderAction, { ...action })),
        external_react_default().createElement("img", { style: { pointerEvents: 'none', userSelect: 'none' }, draggable: "false", srcSet: imageUrl })));
}
function NodePickerSliderAction(action) {
    const context = useNodePickerContext();
    switch (action.kind) {
        default:
        case 'link':
            return (external_react_default().createElement(Center/* Center */.o, null,
                external_react_default().createElement(PrimaryButton/* PrimaryButton */.jn, { label: action.label, size: PrimaryButton/* PrimaryButtonSize */._S.Small, variant: PrimaryButton/* PrimaryButtonVariant */.Mw.Ghost, hasBottomSpacing: true, onClick: () => {
                        src.platform.openExternal(action.linkUrl);
                    } })));
        case 'action':
            return (external_react_default().createElement(Center/* Center */.o, null,
                external_react_default().createElement(PrimaryButton/* PrimaryButton */.jn, { label: action.label, size: PrimaryButton/* PrimaryButtonSize */._S.Small, variant: PrimaryButton/* PrimaryButtonVariant */.Mw.Ghost, hasBottomSpacing: true, onClick: () => {
                        const command = action.action.split(':');
                        switch (command[0]) {
                            case 'panel': {
                                sidebar/* SidebarModel */.s.instance.switch(command[1]);
                                break;
                            }
                            case 'tab': {
                                context.setActiveTab(command[1]);
                                break;
                            }
                        }
                    } })));
    }
}

// EXTERNAL MODULE: ./src/editor/src/hooks/useModel.ts
var useModel = __webpack_require__(85755);
;// ./src/editor/src/hooks/useTogglableArray.ts

function useTogglableArray() {
    const [items, setItems] = (0,external_react_.useState)([]);
    function toggleItem(item) {
        setItems((prev) => {
            if (prev.includes(item)) {
                return [...prev].filter((arrValue) => arrValue !== item);
            }
            else {
                return [...prev, item];
            }
        });
    }
    function isItemInArray(item) {
        return items.includes(item);
    }
    function clearArray() {
        setItems([]);
    }
    return [items, toggleItem, isItemInArray, clearArray];
}

;// ./src/editor/src/utils/addHashToUrl.ts
function addHashToUrl(url) {
    return `${url}?${new Date().getTime()}`;
}

// EXTERNAL MODULE: ./src/editor/src/utils/filesystem.js
var filesystem = __webpack_require__(38656);
var filesystem_default = /*#__PURE__*/__webpack_require__.n(filesystem);
// EXTERNAL MODULE: ./src/editor/src/utils/getDocsEndpoint.ts
var getDocsEndpoint = __webpack_require__(41160);
// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.editor.ts
var projectmodel_editor = __webpack_require__(46998);
;// ./src/editor/src/models/modulelibrarymodel.ts











const modulelibrarymodel_ImportOverwritePopupTemplate = __webpack_require__(94047);
class ModuleLibraryModel extends (model_default()) {
    static get instance() {
        if (!this._instance) {
            this._instance = new ModuleLibraryModel();
        }
        return this._instance;
    }
    constructor() {
        super();
        this.fetchModules('modules').then((modules) => {
            this.modules = modules;
            this.notifyListeners('libraryUpdated');
        });
        this.fetchModules('prefabs').then((prefabs) => {
            this.prefabs = prefabs;
            this.notifyListeners('libraryUpdated');
        });
        this.notifyListeners('libraryUpdated');
    }
    /**
     * Resolves with items for immidiate use, but
     * also sets them to this.modules for future use
     */
    async fetchModules(type) {
        const endpoint = (0,getDocsEndpoint/* default */.A)();
        const urlPath = addHashToUrl(`${endpoint}/library/${type}/index.json`);
        const response = await fetch(urlPath);
        if (response.ok) {
            return await response.json();
        }
        else {
            return [];
        }
    }
    async installModule(modulePath, onBeforePopup, onAfterPopup) {
        const moduleRootPath = await this.getModuleTemplateRoot(modulePath);
        const imports = await new Promise((resolve, reject) => projectimporter_default().instance.listComponentsAndDependencies(moduleRootPath, resolve));
        const collisions = await new Promise((resolve, reject) => projectimporter_default().instance.checkForCollisions(imports, (result) => result && result.message ? reject(result.message) : resolve(result)));
        let componentsToImport = imports;
        // Show overwrite popup if collisions
        if (typeof collisions !== 'undefined') {
            componentsToImport = await this._showImportPopup({ imports, collisions, onBeforePopup, onAfterPopup });
        }
        await this._doImport(moduleRootPath, componentsToImport);
    }
    async installPrefab(modulePath, onBeforePopup, onAfterPopup) {
        const moduleRootPath = await this.getModuleTemplateRoot(modulePath);
        const imports = await new Promise((resolve, reject) => projectimporter_default().instance.listComponentsAndDependencies(moduleRootPath, resolve));
        const collisions = await new Promise((resolve, reject) => projectimporter_default().instance.checkForCollisions(imports, (result) => result && result.message ? reject(result.message) : resolve(result)));
        let itemsToImport = imports;
        if (typeof collisions !== 'undefined') {
            const collisionsToImport = JSON.parse(JSON.stringify(collisions));
            //remove all collisions that aren't components since we shouldn't overwrite those
            collisionsToImport.styles = { colors: [], text: [] };
            collisionsToImport.resources = [];
            collisionsToImport.variants = [];
            collisionsToImport.modules = [];
            if (projectimporter_default().instance.hasCollisions(collisionsToImport)) {
                itemsToImport = await this._showImportPopup({
                    imports,
                    collisions: collisionsToImport,
                    onBeforePopup,
                    onAfterPopup
                });
            }
            else {
                //we have collisions in styles variants or resources. Let's remove those from the import
                function removeItemWithName(array, itemsToRemove) {
                    for (const item of itemsToRemove) {
                        array = array.filter((s) => s.name !== item.name);
                    }
                    return array;
                }
                itemsToImport.styles.colors = removeItemWithName(itemsToImport.styles.colors, collisions.styles.colors);
                itemsToImport.styles.text = removeItemWithName(itemsToImport.styles.text, collisions.styles.text);
                itemsToImport.variants = removeItemWithName(itemsToImport.variants, collisions.variants);
                itemsToImport.modules = removeItemWithName(itemsToImport.modules, collisions.modules);
            }
        }
        await this._doImport(moduleRootPath, itemsToImport);
    }
    async _doImport(moduleRootPath, imports) {
        ViewerConnection/* ViewerConnection */.t.instance.setWatchModelChangesEnabled(false);
        return new Promise((resolve, reject) => {
            projectimporter_default().instance.import(moduleRootPath, imports, (response) => {
                ViewerConnection/* ViewerConnection */.t.instance.setWatchModelChangesEnabled(true);
                if (response.result !== 'success') {
                    reject({ message: response.message });
                    popuplayer_default().instance.hideAllModalsAndPopups();
                }
                EventDispatcher.EventDispatcher.instance.emit('viewer-refresh');
                EventDispatcher.EventDispatcher.instance.emit('ProjectModel.importComplete');
                resolve(true);
                popuplayer_default().instance.hideAllModalsAndPopups();
            });
        });
    }
    async _showImportPopup({ imports, collisions, onBeforePopup, onAfterPopup }) {
        return new Promise((resolve, reject) => {
            const overwritePopup = new (importpopup_default())({
                template: modulelibrarymodel_ImportOverwritePopupTemplate,
                imports: collisions,
                initAllAsImport: true,
                ignoreDependencies: true,
                onOk: () => {
                    onAfterPopup && onAfterPopup();
                    projectimporter_default().instance.filterImports(imports, { remove: overwritePopup.getUnselectedImports() });
                    resolve(imports);
                },
                onCancel: () => {
                    onAfterPopup && onAfterPopup();
                    popuplayer_default().instance.hideModal(undefined);
                    reject({ message: 'Import cancelled' });
                }
            });
            overwritePopup.render();
            onBeforePopup && onBeforePopup();
            popuplayer_default().instance.showModal({
                content: overwritePopup
            });
        });
    }
    getModuleTemplateRoot(templateUrl) {
        return new Promise((resolve, reject) => {
            function findProjectRoot(path) {
                // Find the folder containing a project.json (it may not be the root folder)
                let root;
                filesystem_default().instance.forEachFileRecursive(path, (filename, path) => {
                    if (filename === 'project.json') {
                        root = path;
                        resolve(path);
                        return;
                    }
                });
                if (!root)
                    reject({ message: 'Not a valid component' });
            }
            const name = templateUrl.replace(/:/g, '-').replace(/\//g, '-').replace('/./g', '-');
            const path = src.platform.getUserDataPath() + '/library/' + name;
            filesystem_default().instance.makeDirectory(path, (response) => {
                if (response.result !== 'success') {
                    reject({ message: 'Failed to create template directory' });
                    return;
                }
                filesystem_default().instance.isDirectoryEmpty(path, (isEmpty) => {
                    if (isEmpty) {
                        (0,projectmodel_editor.unzipIntoDirectory)(templateUrl, path, (response) => {
                            if (response.result !== 'success') {
                                reject({ message: 'Failed to download component' });
                                return;
                            }
                            findProjectRoot(response.dirEntry);
                        }, { skipLoad: true });
                    }
                    else
                        findProjectRoot(path);
                });
            });
        });
    }
}
ModuleLibraryModel._instance = undefined;

;// ./src/editor/src/utils/common.ts
function getMatchIndex(targetName, searchTerm) {
    return targetName.toLowerCase().indexOf(searchTerm.toLowerCase());
}
function arrayIntersection(array1, array2) {
    return [...new Set(array1.filter((value) => array2.includes(value)))];
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/TagButton/TagButton.module.scss
var TagButton_module = __webpack_require__(29668);
;// ../noodl-core-ui/src/components/inputs/TagButton/TagButton.module.scss

      
      
      
      
      
      
      
      
      

var TagButton_module_options = {};

TagButton_module_options.styleTagTransform = (styleTagTransform_default());
TagButton_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      TagButton_module_options.insert = insertBySelector_default().bind(null, "head");
    
TagButton_module_options.domAPI = (styleDomAPI_default());
TagButton_module_options.insertStyleElement = (insertStyleElement_default());

var TagButton_module_update = injectStylesIntoStyleTag_default()(TagButton_module/* default */.A, TagButton_module_options);




       /* harmony default export */ const TagButton_TagButton_module = (TagButton_module/* default */.A && TagButton_module/* default */.A.locals ? TagButton_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/TagButton/TagButton.tsx



function TagButton({ label, onClick, isActive, UNSAFE_className, UNSAFE_style }) {
    return (external_react_default().createElement("button", { className: external_classnames_default()(TagButton_TagButton_module['Root'], isActive && TagButton_TagButton_module['is-active'], UNSAFE_className), onClick: onClick, style: UNSAFE_style }, label));
}

;// ../noodl-core-ui/src/components/inputs/TagButton/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NodePicker/components/ModuleCard/ModuleCard.module.scss
var ModuleCard_module = __webpack_require__(71217);
;// ./src/editor/src/views/NodePicker/components/ModuleCard/ModuleCard.module.scss

      
      
      
      
      
      
      
      
      

var ModuleCard_module_options = {};

ModuleCard_module_options.styleTagTransform = (styleTagTransform_default());
ModuleCard_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ModuleCard_module_options.insert = insertBySelector_default().bind(null, "head");
    
ModuleCard_module_options.domAPI = (styleDomAPI_default());
ModuleCard_module_options.insertStyleElement = (insertStyleElement_default());

var ModuleCard_module_update = injectStylesIntoStyleTag_default()(ModuleCard_module/* default */.A, ModuleCard_module_options);




       /* harmony default export */ const ModuleCard_ModuleCard_module = (ModuleCard_module/* default */.A && ModuleCard_module/* default */.A.locals ? ModuleCard_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/NodePicker/components/ModuleCard/ModuleCard.tsx













var ModuleCard_CardState;
(function (CardState) {
    CardState["Idle"] = "is-idle";
    CardState["Downloading"] = "is-downloading";
    CardState["Finished"] = "is-finished";
    CardState["Cancelled"] = "is-cancelled";
})(ModuleCard_CardState || (ModuleCard_CardState = {}));
const endpoint = (0,getDocsEndpoint/* default */.A)();
function ModuleCard({ label, desc, icon, project, docs, tags }) {
    const context = useNodePickerContext();
    const [cardState, setCardState] = (0,external_react_.useState)(ModuleCard_CardState.Idle);
    const [cancelMessage, setCancelMessage] = (0,external_react_.useState)('');
    const isPrefab = (0,external_react_.useMemo)(() => project.includes('/prefab'), [project]);
    function handleDownload(url) {
        setCardState(ModuleCard_CardState.Downloading);
        const fullUrl = url.startsWith('http') ? url : endpoint + '/' + url;
        const installFunc = isPrefab
            ? ModuleLibraryModel.instance.installPrefab.bind(ModuleLibraryModel.instance)
            : ModuleLibraryModel.instance.installModule.bind(ModuleLibraryModel.instance);
        installFunc(fullUrl, context.doBlockPicker, context.doUnblockPicker)
            .then(() => setCardState(ModuleCard_CardState.Finished))
            .then(() => {
            tracker.tracker.track(isPrefab ? 'Prefab imported' : 'Module Imported', {
                label: label,
                url: url
            });
            ToastLayer.ToastLayer.showSuccess(isPrefab ? `Prefab ${label} cloned` : `Module ${label} installed`);
        })
            .catch((error) => {
            setCardState(ModuleCard_CardState.Cancelled);
            setCancelMessage(error.message);
        })
            .finally(() => setTimeout(() => {
            setCardState(ModuleCard_CardState.Idle);
        }, 3000));
    }
    return (external_react_default().createElement("article", { className: external_classnames_default()(ModuleCard_ModuleCard_module['Root'], ModuleCard_ModuleCard_module[cardState]) },
        external_react_default().createElement("div", { className: ModuleCard_ModuleCard_module['ImageContainer'] },
            external_react_default().createElement("div", { className: ModuleCard_ModuleCard_module['Image'], style: { backgroundImage: icon.startsWith('http') ? `url(${icon})` : `url(${endpoint}/${icon})` } })),
        external_react_default().createElement("div", { className: ModuleCard_ModuleCard_module['Content'] },
            external_react_default().createElement("div", null,
                external_react_default().createElement("header", { className: ModuleCard_ModuleCard_module['Header'] },
                    external_react_default().createElement(Title/* Title */.hE, { hasBottomSpacing: true, isInline: true }, label)),
                external_react_default().createElement(Text/* Text */.EY, { textType: Text_Text/* TextType */.M2.Shy }, desc)),
            external_react_default().createElement("div", { className: ModuleCard_ModuleCard_module['TagContainer'] }, Boolean(tags === null || tags === void 0 ? void 0 : tags.length) && tags.join(', ')),
            external_react_default().createElement("div", { className: ModuleCard_ModuleCard_module['HoverOverlay'] },
                external_react_default().createElement("div", { className: ModuleCard_ModuleCard_module['CtaContainer'] },
                    external_react_default().createElement(PrimaryButton/* PrimaryButton */.jn, { label: isPrefab ? 'Clone' : 'Install', onClick: () => handleDownload(project), hasRightSpacing: true }),
                    external_react_default().createElement(PrimaryButton/* PrimaryButton */.jn, { variant: PrimaryButton/* PrimaryButtonVariant */.Mw.Ghost, label: "Read docs", href: endpoint + docs }))),
            external_react_default().createElement("div", { className: ModuleCard_ModuleCard_module['ImportIndicator'] },
                external_react_default().createElement(Title/* Title */.hE, { isCentered: true, hasBottomSpacing: true }, isPrefab ? 'Cloning prefab' : 'Installing module'),
                external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null)),
            external_react_default().createElement("div", { className: ModuleCard_ModuleCard_module['SuccessToast'] },
                external_react_default().createElement(Title/* Title */.hE, { variant: Title/* TitleVariant */.Is.Success, isCentered: true, hasBottomSpacing: true },
                    "Successfully ",
                    isPrefab ? 'cloned' : 'installed'),
                external_react_default().createElement(Text/* Text */.EY, null, label)),
            external_react_default().createElement("div", { className: ModuleCard_ModuleCard_module['CancelToast'] },
                external_react_default().createElement(Title/* Title */.hE, { variant: Title/* TitleVariant */.Is.Danger, isCentered: true }, cancelMessage)))));
}

;// ./src/editor/src/views/NodePicker/components/ModuleCard/index.ts


;// ./src/editor/src/views/NodePicker/components/ModuleCard/MuduleCard.utils.ts
const baseval = 'data:image/jpeg;base64, ';
const tempcard = {
    label: 'Kotte was here',
    desc: 'You found my secret!',
    project: null,
    docs: '',
    tags: ['Easter egg'],
    icon: '1021'
};
const tempterm = 'kottewashere';

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NodePicker/tabs/NodePickerSearchView/NodePickerSearchView.module.scss
var NodePickerSearchView_module = __webpack_require__(76339);
;// ./src/editor/src/views/NodePicker/tabs/NodePickerSearchView/NodePickerSearchView.module.scss

      
      
      
      
      
      
      
      
      

var NodePickerSearchView_module_options = {};

NodePickerSearchView_module_options.styleTagTransform = (styleTagTransform_default());
NodePickerSearchView_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      NodePickerSearchView_module_options.insert = insertBySelector_default().bind(null, "head");
    
NodePickerSearchView_module_options.domAPI = (styleDomAPI_default());
NodePickerSearchView_module_options.insertStyleElement = (insertStyleElement_default());

var NodePickerSearchView_module_update = injectStylesIntoStyleTag_default()(NodePickerSearchView_module/* default */.A, NodePickerSearchView_module_options);




       /* harmony default export */ const NodePickerSearchView_NodePickerSearchView_module = (NodePickerSearchView_module/* default */.A && NodePickerSearchView_module/* default */.A.locals ? NodePickerSearchView_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/NodePicker/tabs/NodePickerSearchView/NodePickerSearchView.tsx










function NodePickerSearchView({ itemType, searchInputPlaceholder }) {
    const moduleLibraryModel = (0,useModel/* useModel */.f)(ModuleLibraryModel.instance, ['libraryUpdated']);
    const modules = itemType === 'prefab' ? moduleLibraryModel.prefabs : moduleLibraryModel.modules;
    const [searchTerm, setSearchTerm] = (0,external_react_.useState)('');
    const [selectedTags, toggleTag, isTagSelected] = useTogglableArray();
    const allTags = (0,external_react_.useMemo)(() => {
        if (!Array.isArray(modules))
            return [];
        return [
            ...new Set(modules.reduce((prev, curr) => {
                var _a;
                if ((_a = curr === null || curr === void 0 ? void 0 : curr.tags) === null || _a === void 0 ? void 0 : _a.length)
                    return [...prev, ...curr.tags];
                return prev;
            }, []))
        ]; // FIXME: prone to error
    }, [modules]);
    const filteredModules = (0,external_react_.useMemo)(() => {
        if (!Array.isArray(modules))
            return [];
        let tempModules = [...modules];
        if (selectedTags.length) {
            tempModules = tempModules.filter((module) => Boolean(arrayIntersection(module.tags, selectedTags).length));
        }
        if (searchTerm) {
            tempModules = tempModules
                .filter((module) => getMatchIndex(module.label, searchTerm) >= 0)
                .map((module) => ({
                module: module,
                matchIndex: getMatchIndex(module.label, searchTerm)
            }))
                .sort((a, b) => a.matchIndex - b.matchIndex)
                .map((module) => module.module);
        }
        if (searchTerm.toLowerCase() === tempterm) {
            tempModules = new Array(6).fill(tempcard);
        }
        return tempModules;
    }, [modules, searchTerm, selectedTags]);
    return (external_react_default().createElement("div", { className: NodePickerSearchView_NodePickerSearchView_module['Root'] },
        external_react_default().createElement("div", { className: NodePickerSearchView_NodePickerSearchView_module['SearchContainer'] },
            external_react_default().createElement(SearchInput/* SearchInput */.D, { placeholder: searchInputPlaceholder, onChange: setSearchTerm })),
        external_react_default().createElement("div", { className: NodePickerSearchView_NodePickerSearchView_module['TagList'] }, allTags.map((tag) => (external_react_default().createElement(TagButton, { key: tag, label: tag, onClick: () => toggleTag(tag), isActive: isTagSelected(tag) })))),
        external_react_default().createElement("div", { className: NodePickerSearchView_NodePickerSearchView_module['GridContainer'] },
            external_react_default().createElement("ul", { className: NodePickerSearchView_NodePickerSearchView_module['Grid'] }, Array.isArray(modules) &&
                filteredModules.map((module) => (external_react_default().createElement("li", { key: module.label, className: NodePickerSearchView_NodePickerSearchView_module['ModuleContainer'] },
                    external_react_default().createElement(ModuleCard, { ...module }))))))));
}

;// ./src/editor/src/views/NodePicker/tabs/NodePickerSearchView/index.ts


;// ./src/editor/src/views/NodePicker/NodePicker.tsx








const NODE_LIBRARY_LABEL = 'Nodes';
const PREFAB_LIBRARY_LABEL = 'Prefabs';
const MODULE_LIBRARY_LABEL = 'Modules';
const PROJECT_IMPORT_LABEL = 'Import from project';
function NodePickerWithoutContext({ model, parentModel, pos, attachToRoot, runtimeType }) {
    const context = useNodePickerContext();
    const tabs = [
        {
            label: NODE_LIBRARY_LABEL,
            content: (external_react_default().createElement(NodeLibrary, { model: model, parentModel: parentModel, pos: pos, attachToRoot: attachToRoot, runtimeType: runtimeType }))
        }
    ];
    tabs.push({
        label: PREFAB_LIBRARY_LABEL,
        content: external_react_default().createElement(NodePickerSearchView, { key: "prefabs", itemType: "prefab", searchInputPlaceholder: "Search for a prefab" })
    });
    tabs.push({
        label: MODULE_LIBRARY_LABEL,
        content: (external_react_default().createElement(NodePickerSearchView, { key: "modules", itemType: "module", searchInputPlaceholder: "Search for an external library" }))
    });
    tabs.push({
        label: PROJECT_IMPORT_LABEL,
        content: external_react_default().createElement(ImportFromProject, null)
    });
    return (external_react_default().createElement("div", { className: NodePicker_NodePicker_module['Root'] },
        external_react_default().createElement(Tabs/* Tabs */.t, { UNSAFE_className: NodePicker_NodePicker_module['TabOverride'], variant: Tabs/* TabsVariant */._.Text, tabs: tabs, activeTab: context.activeTab, onChange: (activeTab) => {
                context.setActiveTab(activeTab);
            } }),
        external_react_default().createElement("div", { className: external_classnames_default()(NodePicker_NodePicker_module['Blocker'], context.isBlocked && NodePicker_NodePicker_module['is-visible']) }),
        external_react_default().createElement("div", { className: NodePicker_NodePicker_module['ShadowWrapper'] },
            external_react_default().createElement("div", { className: NodePicker_NodePicker_module['Shadow'] }))));
}
function NodePicker(props) {
    return (external_react_default().createElement(NodePickerContextProvider, null,
        external_react_default().createElement(NodePickerWithoutContext, { ...props })));
}

;// ./src/editor/src/views/createnewnodepanel.ts






class CreateNewNodePanel extends (view_default()) {
    static shouldShow(context) {
        const nodeTypes = nodelibrary/* NodeLibrary */.m.instance.getNodeTypes();
        const componentTypes = nodelibrary/* NodeLibrary */.m.instance.getComponents();
        const allTypes = nodeTypes.concat(componentTypes);
        const creatableTypes = allTypes.filter((t) => {
            const status = context.component.getCreateStatus({
                parent: context.parentModel,
                type: t
            });
            return status.creatable;
        });
        return creatableTypes.length > 0;
    }
    constructor(args) {
        super();
        this.root = null;
        this.model = args.model;
        this.parentModel = args.parentModel;
        this.attachToRoot = !!args.attachToRoot;
        this.pos = args.pos;
        this.runtimeType = args.runtimeType;
        // console.log(`Debug: Open Node Picker (runtime: ${args.runtimeType})`);
    }
    dispose() {
        if (this.root) {
            this.root.unmount();
            this.root = null;
        }
        external_electron_.ipcRenderer.send('viewer-show');
    }
    renderReact(div) {
        const props = {
            model: this.model,
            parentModel: this.parentModel,
            pos: this.pos,
            attachToRoot: this.attachToRoot,
            runtimeType: this.runtimeType
        };
        // hide viwer first...
        external_electron_.ipcRenderer.send('viewer-hide');
        // ... then render the picker
        if (!this.root) {
            this.root = (0,client.createRoot)(div);
        }
        this.root.render(external_react_default().createElement(NodePicker, props));
    }
    render() {
        const div = document.createElement('div');
        // Set explicit dimensions so PopupLayer can measure correctly
        // before React 18's async rendering completes
        // These dimensions match NodePicker.module.scss: width: 800px, height: 600px
        div.style.width = '800px';
        div.style.height = '600px';
        this.renderReact(div);
        this.el = $(div);
        return this.el;
    }
}


/***/ }),

/***/ 91629:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  JU: () => (/* reexport */ Label),
  IV: () => (/* reexport */ LabelSize),
  Zt: () => (/* reexport */ LabelSpacingSize)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/index.ts
var Text = __webpack_require__(93834);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/typography/Label/Label.module.scss
var Label_module = __webpack_require__(93220);
;// ../noodl-core-ui/src/components/typography/Label/Label.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(Label_module/* default */.A, options);




       /* harmony default export */ const Label_Label_module = (Label_module/* default */.A && Label_module/* default */.A.locals ? Label_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/typography/Label/Label.tsx




var LabelSize;
(function (LabelSize) {
    LabelSize["Small"] = "is-size-small";
    LabelSize["Default"] = "is-size-default";
    LabelSize["Medium"] = "is-size-medium";
    LabelSize["Big"] = "is-size-big";
})(LabelSize || (LabelSize = {}));
var LabelSpacingSize;
(function (LabelSpacingSize) {
    LabelSpacingSize["Small"] = "small";
    LabelSpacingSize["Default"] = "default";
    LabelSpacingSize["Large"] = "large";
})(LabelSpacingSize || (LabelSpacingSize = {}));
function Label({ children, size = LabelSize.Default, variant = Text/* TextType */.M2.Default, hasBottomSpacing, hasLeftSpacing, hasTopSpacing, hasRightSpacing, isInline, hasTextWrap, UNSAFE_className, UNSAFE_style }) {
    return (external_react_default().createElement("span", { style: UNSAFE_style, className: external_classnames_default()(Label_Label_module['Root'], Label_Label_module[`is-variant-${variant}`], Label_Label_module[size], hasBottomSpacing && Label_Label_module[`has-bottom-spacing-${getSpacing(hasBottomSpacing, size)}`], hasLeftSpacing && Label_Label_module[`has-left-spacing-${getSpacing(hasLeftSpacing, size)}`], hasTopSpacing && Label_Label_module[`has-top-spacing-${getSpacing(hasTopSpacing, size)}`], hasRightSpacing && Label_Label_module[`has-right-spacing-${getSpacing(hasRightSpacing, size)}`], isInline && Label_Label_module['is-inline'], hasTextWrap && Label_Label_module['has-text-wrap'], UNSAFE_className) }, children));
}
function getSpacing(hasSpacing, size) {
    if (hasSpacing === true) {
        switch (size) {
            case LabelSize.Small:
                return LabelSpacingSize.Small;
            default:
                return LabelSpacingSize.Default;
        }
    }
    else {
        return hasSpacing;
    }
}

;// ../noodl-core-ui/src/components/typography/Label/index.ts



/***/ }),

/***/ 91885:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, ``, "",{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 92081:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _AbstractPage_client;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.PageCursor = exports.TokenPage = exports.Page = exports.PagePromise = exports.AbstractPage = void 0;
const tslib_1 = __webpack_require__(84499);
const error_1 = __webpack_require__(37015);
const parse_1 = __webpack_require__(66508);
const api_promise_1 = __webpack_require__(15845);
const values_1 = __webpack_require__(25267);
class AbstractPage {
    constructor(client, response, body, options) {
        _AbstractPage_client.set(this, void 0);
        tslib_1.__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
        this.options = options;
        this.response = response;
        this.body = body;
    }
    hasNextPage() {
        const items = this.getPaginatedItems();
        if (!items.length)
            return false;
        return this.nextPageRequestOptions() != null;
    }
    async getNextPage() {
        const nextOptions = this.nextPageRequestOptions();
        if (!nextOptions) {
            throw new error_1.AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
        }
        return await tslib_1.__classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
    }
    async *iterPages() {
        let page = this;
        yield page;
        while (page.hasNextPage()) {
            page = await page.getNextPage();
            yield page;
        }
    }
    async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
        for await (const page of this.iterPages()) {
            for (const item of page.getPaginatedItems()) {
                yield item;
            }
        }
    }
}
exports.AbstractPage = AbstractPage;
/**
 * This subclass of Promise will resolve to an instantiated Page once the request completes.
 *
 * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
 *
 *    for await (const item of client.items.list()) {
 *      console.log(item)
 *    }
 */
class PagePromise extends api_promise_1.APIPromise {
    constructor(client, request, Page) {
        super(client, request, async (client, props) => new Page(client, props.response, await (0, parse_1.defaultParseResponse)(client, props), props.options));
    }
    /**
     * Allow auto-paginating iteration on an unawaited list call, eg:
     *
     *    for await (const item of client.items.list()) {
     *      console.log(item)
     *    }
     */
    async *[Symbol.asyncIterator]() {
        const page = await this;
        for await (const item of page) {
            yield item;
        }
    }
}
exports.PagePromise = PagePromise;
class Page extends AbstractPage {
    constructor(client, response, body, options) {
        super(client, response, body, options);
        this.data = body.data || [];
        this.has_more = body.has_more || false;
        this.first_id = body.first_id || null;
        this.last_id = body.last_id || null;
    }
    getPaginatedItems() {
        return this.data ?? [];
    }
    hasNextPage() {
        if (this.has_more === false) {
            return false;
        }
        return super.hasNextPage();
    }
    nextPageRequestOptions() {
        if (this.options.query?.['before_id']) {
            // in reverse
            const first_id = this.first_id;
            if (!first_id) {
                return null;
            }
            return {
                ...this.options,
                query: {
                    ...(0, values_1.maybeObj)(this.options.query),
                    before_id: first_id,
                },
            };
        }
        const cursor = this.last_id;
        if (!cursor) {
            return null;
        }
        return {
            ...this.options,
            query: {
                ...(0, values_1.maybeObj)(this.options.query),
                after_id: cursor,
            },
        };
    }
}
exports.Page = Page;
class TokenPage extends AbstractPage {
    constructor(client, response, body, options) {
        super(client, response, body, options);
        this.data = body.data || [];
        this.has_more = body.has_more || false;
        this.next_page = body.next_page || null;
    }
    getPaginatedItems() {
        return this.data ?? [];
    }
    hasNextPage() {
        if (this.has_more === false) {
            return false;
        }
        return super.hasNextPage();
    }
    nextPageRequestOptions() {
        const cursor = this.next_page;
        if (!cursor) {
            return null;
        }
        return {
            ...this.options,
            query: {
                ...(0, values_1.maybeObj)(this.options.query),
                page_token: cursor,
            },
        };
    }
}
exports.TokenPage = TokenPage;
class PageCursor extends AbstractPage {
    constructor(client, response, body, options) {
        super(client, response, body, options);
        this.data = body.data || [];
        this.has_more = body.has_more || false;
        this.next_page = body.next_page || null;
    }
    getPaginatedItems() {
        return this.data ?? [];
    }
    hasNextPage() {
        if (this.has_more === false) {
            return false;
        }
        return super.hasNextPage();
    }
    nextPageRequestOptions() {
        const cursor = this.next_page;
        if (!cursor) {
            return null;
        }
        return {
            ...this.options,
            query: {
                ...(0, values_1.maybeObj)(this.options.query),
                page: cursor,
            },
        };
    }
}
exports.PageCursor = PageCursor;
//# sourceMappingURL=pagination.js.map

/***/ }),

/***/ 92207:
/***/ ((module) => {

const watch = function (obj, prop, handler) {
  var value = obj[prop],
    oldsetter = obj.__lookupSetter__(prop),
    oldgetter = obj.__lookupGetter__(prop),
    getter = function () {
      return value;
    },
    setter = function (val) {
      value = handler.call(obj, prop, value, val);

      if (oldsetter) return oldsetter(value);
      return value;
    };
  if (oldsetter || delete obj[prop]) {
    // can't watch constants
    if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) {
      // legacy
      Object.prototype.__defineGetter__.call(obj, prop, getter);
      Object.prototype.__defineSetter__.call(obj, prop, setter);
    }
  }
};

const unwatch = function (obj, prop) {
  var val = obj[prop];
  delete obj[prop]; // remove accessors
  obj[prop] = val;
};

var View = function () {
  this.templates = {};
  this.listeners = [];
};

View.$ = function (el, selector) {
  return el.filter(selector).add(el.find(selector));
};

View.showTooltip = function (args) {
  // Will be overridden externally
};

View.hideTooltip = function (el) {
  // Will be overridden externally
};

View.prototype.$ = function (selector) {
  const other = this.el.find(selector);
  return this.el.filter(selector).add(other);
};

View.prototype.on = function (event, listener, group) {
  this.listeners.push({
    event: event,
    listener: listener,
    group
  });

  return this;
};

View.prototype.off = function (group) {
  for (var i = 0; i < this.listeners.length; i++) {
    if (this.listeners[i].group === group) {
      this.listeners.splice(i, 1);
      i--;
    }
  }
  return this;
};

View.prototype.notifyListeners = function (event, args) {
  for (var i in this.listeners) {
    if (this.listeners[i].event === event) this.listeners[i].listener(args);
  }
};

View.prototype.cloneTemplate = function (tmpl) {
  return this.templates[tmpl].clone();
};

View.prototype.bindView = function (el, obj) {
  var _this = this;

  // Collect templates
  el.find('[data-template]').each(function () {
    var _el = $(this);
    _el.remove();
    _this.templates[_el.attr('data-template')] = _el;
  });

  var resolvePathOnObject = function (path, obj) {
    var cmp = path.split('.');
    for (var i = 0; i < cmp.length - 1; i++) {
      obj = obj[cmp[i]];
    }
    return {
      prop: cmp[cmp.length - 1],
      obj: obj
    };
  };

  var getObjectFromPath = function (path, obj) {
    var resolved = resolvePathOnObject(path, obj);
    return resolved.obj[resolved.prop];
  };

  function resolveStaticOrFromPath(attribute, obj) {
    if (attribute.startsWith('path:')) {
      const path = attribute.split('path:')[1];
      const resolved = resolvePathOnObject(path, obj);
      return resolved.obj[resolved.prop];
    }

    return attribute;
  }

  // Change events
  View.$(el, '[data-change]').each(function () {
    $(this).on('change', function (evt) {
      _this[$(this).attr('data-change')].apply(_this, [obj, $(this), evt]);
    });
  });

  // On click events
  View.$(el, '[data-click]').each(function () {
    $(this).on('click', function (evt) {
      _this[$(this).attr('data-click')].apply(_this, [obj, $(this), evt]);
    });
  });

  // On tooltip
  var tooltipTimeout;
  View.$(el, '[data-tooltip]').each(function () {
    $(this)
      .on('mouseenter', function (evt) {
        var el = $(this);

        let tooltip = resolveStaticOrFromPath(el.attr('data-tooltip'), obj);
        if (!tooltip) return;

        let content, extendedContent;

        if (typeof tooltip === 'object') {
          content = tooltip.standard;
          extendedContent = tooltip.extended;
        } else {
          content = tooltip;
        }

        const position = el.attr('data-tooltip-position');

        tooltipTimeout = setTimeout(() => {
          const dimensions = View.showTooltip({
            attachTo: el,
            content,
            position
          });

          if (extendedContent) {
            tooltipTimeout = setTimeout(() => {
              const offset = {
                x: (300 - dimensions.contentWidth) / 2 //a hack to try to keep the arrow in the same position. Assumes the expanded popup is 300px wide.
              };

              View.showTooltip({
                attachTo: el,
                content: extendedContent,
                position,
                offset
              });
            }, 1500);
          }
        }, 500);
      })
      .on('mouseleave mousedown', function (evt) {
        View.hideTooltip($(this));
        clearTimeout(tooltipTimeout);
      });
  });

  // Data text
  View.$(el, '[data-text]').each(function () {
    var _el = $(this);
    var resolved = resolvePathOnObject($(this).attr('data-text'), obj);
    _el.text(resolved.obj[resolved.prop]);
    var bind = _el.attr('data-bind');
    if (bind === 'watch') {
      watch(resolved.obj, resolved.prop, function (prop, oldVal, newVal) {
        _el.text(newVal);
        return newVal;
      });
    }
  });

  // Data html
  View.$(el, '[data-html]').each(function () {
    var _el = $(this);
    var resolved = resolvePathOnObject($(this).attr('data-html'), obj);
    _el.html(resolved.obj[resolved.prop]);
    var bind = _el.attr('data-bind');
    if (bind === 'watch') {
      watch(resolved.obj, resolved.prop, function (prop, oldVal, newVal) {
        _el.html(newVal);
        return newVal;
      });
    }
  });

  // Identifier (for easier input targeting)
  View.$(el, '[data-identifier]').each(function () {
    $(this).attr('data-identifier', obj?.name);
  });

  // Data val
  View.$(el, '[data-val]').each(function () {
    $(this).val(getObjectFromPath($(this).attr('data-val'), obj));
  });

  // Data src
  View.$(el, '[data-src]').each(function () {
    $(this).attr('src', getObjectFromPath($(this).attr('data-src'), obj));
  });

  // Data checked
  View.$(el, '[data-checked]').each(function () {
    $(this).prop('checked', getObjectFromPath($(this).attr('data-checked'), obj));
  });

  // Data class
  View.$(el, '[data-class]').each(function () {
    var _el = $(this);
    var decl = $(this).attr('data-class');
    var conds = decl.split(',');
    for (var i in conds) {
      var terms = conds[i].split(':');
      var cls = terms[1];
      var path = terms[0];
      var invert = false;
      if (path[0] === '!') {
        invert = true;
        path = path.substring(1);
      }
      var resolved = resolvePathOnObject(path, obj);
      var check = invert ? !resolved.obj[resolved.prop] : resolved.obj[resolved.prop];
      if (check) _el.addClass(cls);
      else _el.removeClass(cls);

      // bind with a watch, if the property changes
      // update the class
      watch(
        resolved.obj,
        resolved.prop,
        (function () {
          var _cls = cls;
          var _invert = invert;
          return function (prop, oldVal, newVal) {
            if (oldVal !== newVal) {
              var check = _invert ? !newVal : newVal;
              if (check) _el.addClass(_cls);
              else _el.removeClass(_cls);
            }
            return newVal;
          };
        })()
      );
    }
  });

  // Prevent buttons from focusing
  View.$(el, 'button').on('focus', function () {
    $(this).blur();
  });

  return el;
};

module.exports = View;


/***/ }),

/***/ 92394:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  o: () => (/* reexport */ Center)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/Center/Center.module.scss
var Center_module = __webpack_require__(98373);
;// ../noodl-core-ui/src/components/layout/Center/Center.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(Center_module/* default */.A, options);




       /* harmony default export */ const Center_Center_module = (Center_module/* default */.A && Center_module/* default */.A.locals ? Center_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/Center/Center.tsx



const Center = external_react_default().forwardRef(({ children, UNSAFE_className, UNSAFE_style }, ref) => {
    return (external_react_default().createElement("div", { ref: ref, className: external_classnames_default()(Center_Center_module['Root'], UNSAFE_className), style: UNSAFE_style }, children));
});

;// ../noodl-core-ui/src/components/layout/Center/index.ts



/***/ }),

/***/ 92424:
/***/ ((module) => {

// Module
var code = " <div class=\"string-input-popup\"> <label class=\"string-input-popup-label\" data-text=\"label\"></label> <div class=\"string-input-popup-editor-wrapper\"> <div class=\"string-input-popup-line-numbers\" aria-hidden=\"true\"></div> <textarea class=\"string-input-popup-input string-input-popup-textarea sidebar-input\" rows=\"8\" placeholder=\"// Add your comment here...\" spellcheck=\"false\"></textarea> </div> <div class=\"string-input-popup-buttons\"> <button class=\"string-input-popup-button-ok\" data-click=\"onOkClicked\" data-text=\"okLabel\"></button> <button class=\"string-input-popup-button-cancel\" data-click=\"onCancelClicked\" data-text=\"cancelLabel\"></button> </div> </div> ";
// Exports
module.exports = code;

/***/ }),

/***/ 92651:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
const tslib_1 = __webpack_require__(84499);
/** @deprecated Import from ./core/error instead */
tslib_1.__exportStar(__webpack_require__(37015), exports);
//# sourceMappingURL=error.js.map

/***/ }),

/***/ 92937:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ToastCard-module__Root--U7yOm{padding:6px 12px;position:relative;display:flex;justify-content:space-between;align-items:center;animation:ToastCard-module__show--Hqhth 300ms var(--easing-base) both;min-width:250px;max-width:50vw;line-height:12px;background-color:var(--theme-color-fg-highlight);color:var(--theme-color-bg-1)}.ToastCard-module__Root--U7yOm.ToastCard-module__is-danger--WnNS8{background-color:var(--theme-color-danger);padding-right:6px}.ToastCard-module__Root--U7yOm.ToastCard-module__is-success--Gyx_H{background-color:var(--theme-color-success)}.ToastCard-module__Message--F2_Td{font-weight:600;position:relative;z-index:1;padding:6px 0;padding-right:4px}.ToastCard-module__ProgressBar--aiSsm{position:absolute;top:0;bottom:0;left:0;background-color:var(--theme-color-primary);transition:width var(--speed-turbo) var(--easing-base)}.ToastCard-module__ActivityIndicatorContainer--N58bL{padding-left:30px}@keyframes ToastCard-module__show--Hqhth{from{opacity:0;transform:translateY(100%)}to{opacity:1;transform:translateY(0)}}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/ToastLayer/components/ToastCard/ToastCard.module.scss"],"names":[],"mappings":"AAEA,+BACE,gBAAA,CACA,iBAAA,CACA,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,qEAAA,CACA,eAAA,CACA,cAAA,CACA,gBAAA,CACA,gDAAA,CACA,6BAAA,CAEA,kEACE,0CAAA,CACA,iBAAA,CAGF,mEACE,2CAAA,CAIJ,kCACE,eAAA,CACA,iBAAA,CACA,SAAA,CACA,aAAA,CACA,iBAAA,CAGF,sCACE,iBAAA,CACA,KAAA,CACA,QAAA,CACA,MAAA,CACA,2CAAA,CACA,sDAAA,CAGF,qDACE,iBAAA,CAGF,yCACE,KACE,SAAA,CACA,0BAAA,CAGF,GACE,SAAA,CACA,uBAAA,CAAA","sourcesContent":["@use '@scss-variables/animation';\n\n.Root {\n  padding: 6px 12px;\n  position: relative;\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  animation: show 300ms animation.$easing-base both;\n  min-width: 250px;\n  max-width: 50vw;\n  line-height: 12px;\n  background-color: var(--theme-color-fg-highlight);\n  color: var(--theme-color-bg-1);\n\n  &.is-danger {\n    background-color: var(--theme-color-danger);\n    padding-right: 6px;\n  }\n\n  &.is-success {\n    background-color: var(--theme-color-success);\n  }\n}\n\n.Message {\n  font-weight: 600;\n  position: relative;\n  z-index: 1;\n  padding: 6px 0;\n  padding-right: 4px;\n}\n\n.ProgressBar {\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  left: 0;\n  background-color: var(--theme-color-primary);\n  transition: width animation.$speed-turbo animation.$easing-base;\n}\n\n.ActivityIndicatorContainer {\n  padding-left: 30px;\n}\n\n@keyframes show {\n  from {\n    opacity: 0;\n    transform: translateY(100%);\n  }\n\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ToastCard-module__Root--U7yOm`,
	"show": `ToastCard-module__show--Hqhth`,
	"is-danger": `ToastCard-module__is-danger--WnNS8`,
	"is-success": `ToastCard-module__is-success--Gyx_H`,
	"Message": `ToastCard-module__Message--F2_Td`,
	"ProgressBar": `ToastCard-module__ProgressBar--aiSsm`,
	"ActivityIndicatorContainer": `ToastCard-module__ActivityIndicatorContainer--N58bL`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 93015:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   getFileExtension: () => (/* binding */ getFileExtension),
/* harmony export */   guid: () => (/* binding */ guid),
/* harmony export */   isFilenameImage: () => (/* binding */ isFilenameImage),
/* harmony export */   objectsArrayToCsv: () => (/* binding */ objectsArrayToCsv),
/* harmony export */   pointInsideRectangle: () => (/* binding */ pointInsideRectangle),
/* harmony export */   rectanglesOverlap: () => (/* binding */ rectanglesOverlap),
/* harmony export */   timeSince: () => (/* binding */ timeSince),
/* harmony export */   windowTitleBarHeight: () => (/* binding */ windowTitleBarHeight)
/* harmony export */ });
function guid() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
function timeSince(date) {
    const date_unix = typeof date === 'number' ? date : date.getTime();
    const seconds = Math.floor((new Date().getTime() - date_unix) / 1000);
    let interval = Math.floor(seconds / 31536000);
    if (interval > 1) {
        return interval + ' years';
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
        return interval + ' months';
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
        return interval + ' days';
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
        return interval + ' hours';
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
        return interval + ' minutes';
    }
    return Math.floor(seconds) + ' seconds';
}
function windowTitleBarHeight() {
    let height = 28; //windows or linux
    if (process.platform === 'darwin') {
        const isBigSurOrAbove = (__webpack_require__(70857).release)().split('.')[0] >= 20;
        height = isBigSurOrAbove ? 28 : 22;
    }
    return height + 2; //add 2 pixels for the black border
}
function rectanglesOverlap(a, b) {
    const corners = [
        [a.x, a.y],
        [a.x + a.width, a.y],
        [a.x + a.width, a.y + a.height],
        [a.x, a.y + a.height]
    ];
    const x = b.x;
    const x2 = b.x + b.width;
    const y = b.y;
    const y2 = b.y + b.height;
    return corners.some((c, i) => {
        const inside = c[0] >= x && c[0] <= x2 && c[1] >= y && c[1] <= y2;
        if (inside)
            return true;
        // Check for line intersection
        const c2 = corners[(i + 1) & 3];
        return ((c[0] === c2[0] && x <= c[0] && x2 >= c[0] && y >= Math.min(c[1], c2[1]) && y2 <= Math.max(c[1], c2[1])) ||
            (c[1] === c2[1] && y <= c[1] && y2 >= c[1] && x >= Math.min(c[0], c2[0]) && x2 <= Math.max(c[0], c2[0])));
    });
}
function pointInsideRectangle(point, rect) {
    return point.x >= rect.x && point.x <= rect.x + rect.width && point.y >= rect.y && point.y <= rect.y + rect.height;
}
// Converting an array of objects into CSV text.
// Expects all objects to have the same properties
function objectsArrayToCsv(objectsArray) {
    const headers = Object.keys(objectsArray[0]);
    const csvData = [headers.join(',')];
    for (const obj of objectsArray) {
        const values = headers.map((header) => obj[header]);
        csvData.push(values.join(','));
    }
    return csvData.join('\n');
}
function getFileExtension(filename) {
    return filename.toLowerCase().slice(((filename.lastIndexOf('.') - 1) >>> 0) + 2);
}
// Check if string ends in an image file extension
function isFilenameImage(filename) {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp'];
    const fileExtension = getFileExtension(filename);
    return imageExtensions.includes(`.${fileExtension}`);
}
/** @deprecated Skip default import */
const Utils = {
    guid,
    timeSince,
    windowTitleBarHeight,
    rectanglesOverlap
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Utils);


/***/ }),

/***/ 93051:
/***/ ((module) => {

"use strict";


/* istanbul ignore next  */
function insertStyleElement(options) {
  var element = document.createElement("style");
  options.setAttributes(element, options.attributes);
  options.insert(element, options.options);
  return element;
}
module.exports = insertStyleElement;

/***/ }),

/***/ 93125:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   B: () => (/* binding */ getRemote),
/* harmony export */   g: () => (/* binding */ setRemoteURL)
/* harmony export */ });
/* harmony import */ var _core_remotes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57992);
/* harmony import */ var _git_action_error__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(55861);


/**
 * Returns a single remote.
 *
 * @param repositoryDir
 * @throws {GitHelperError}
 * @returns A single remote.
 */
async function getRemote(repositoryDir) {
    const remotes = await (0,_core_remotes__WEBPACK_IMPORTED_MODULE_0__/* .getRemotes */ .K7)(repositoryDir);
    if (remotes.length === 0) {
        // When there are no remotes, we assume that the repository is local only.
        // This might not always be the case,
        // but ideally a remote branch should have been created.
        throw new _git_action_error__WEBPACK_IMPORTED_MODULE_1__/* .GitActionError */ .v7(_git_action_error__WEBPACK_IMPORTED_MODULE_1__/* .GitActionErrorCode */ .I7.LocalRepository);
    }
    // TODO: It would be nice if the git client selects a default remote
    //       and then we work from that remote, so you can
    //       technically have many different remotes at once.
    return remotes[0];
}
async function setRemoteURL(repositoryDir, remoteName, url) {
    await (0,_core_remotes__WEBPACK_IMPORTED_MODULE_0__/* .setRemoteURL */ .gK)(repositoryDir, remoteName, url);
}


/***/ }),

/***/ 93130:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgIcon = function SvgIcon(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M24.7994 8.9579L15.8915 3.93135C15.6365 3.78532 15.3477 3.7085 15.0538 3.7085C14.7599 3.7085 14.4711 3.78532 14.216 3.93135L5.30819 8.9579C5.04749 9.10842 4.83092 9.32479 4.68016 9.58535C4.52941 9.84591 4.44977 10.1415 4.44922 10.4425V20.4745C4.44977 20.7755 4.52941 21.0711 4.68016 21.3316C4.83092 21.5922 5.04749 21.8086 5.30819 21.9591L14.216 26.9856C14.4711 27.1317 14.7599 27.2085 15.0538 27.2085C15.3477 27.2085 15.6365 27.1317 15.8915 26.9856L24.7994 21.9591C25.0601 21.8086 25.2766 21.5922 25.4274 21.3316C25.5781 21.0711 25.6578 20.7755 25.6583 20.4745V10.4425C25.6578 10.1415 25.5781 9.84591 25.4274 9.58535C25.2766 9.32479 25.0601 9.10842 24.7994 8.9579Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgIcon);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "b7b55dc5622b2cbcb29fc2822e6716cd.svg");

/***/ }),

/***/ 93158:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ToggleSwitch-module__Track--QDN7v{box-sizing:border-box;height:24px;width:42px;border-radius:12px;background-color:var(--theme-color-bg-3);cursor:pointer;display:flex;align-items:center;padding:3px;margin-left:8px;margin-right:8px;border:1px solid var(--theme-color-border-default)}.ToggleSwitch-module__Indicator--dtLQa{width:18px;height:18px;border-radius:50%;background-color:var(--theme-color-bg-3);transition:transform var(--speed-quick) var(--easing-base),background-color var(--speed-quick) var(--easing-base)}.ToggleSwitch-module__Indicator--dtLQa.ToggleSwitch-module__is-checked--DI_6j{transform:translateX(100%)}.ToggleSwitch-module__Indicator--dtLQa.ToggleSwitch-module__is-always-active-color--YTDB4,.ToggleSwitch-module__Indicator--dtLQa.ToggleSwitch-module__is-checked--DI_6j{background-color:var(--theme-color-secondary-bright)}.ToggleSwitch-module__Input--pII4e{display:none}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/inputs/ToggleSwitch/ToggleSwitch.module.scss"],"names":[],"mappings":"AAGA,mCACE,qBAAA,CACA,WAAA,CACA,UAAA,CACA,kBAAA,CACA,wCAAA,CACA,cAAA,CACA,YAAA,CACA,kBAAA,CACA,WAAA,CACA,eAAA,CACA,gBAAA,CACA,kDAAA,CAGF,uCACE,UAAA,CACA,WAAA,CACA,iBAAA,CACA,wCAAA,CACA,iHAAA,CAEA,8EACE,0BAAA,CAGF,wKAEE,oDAAA,CAIJ,mCACE,YAAA","sourcesContent":[".Root {\n}\n\n.Track {\n  box-sizing: border-box;\n  height: 24px;\n  width: 42px;\n  border-radius: 12px;\n  background-color: var(--theme-color-bg-3);\n  cursor: pointer;\n  display: flex;\n  align-items: center;\n  padding: 3px;\n  margin-left: 8px;\n  margin-right: 8px;\n  border: 1px solid var(--theme-color-border-default);\n}\n\n.Indicator {\n  width: 18px;\n  height: 18px;\n  border-radius: 50%;\n  background-color: var(--theme-color-bg-3);\n  transition: transform var(--speed-quick) var(--easing-base), background-color var(--speed-quick) var(--easing-base);\n\n  &.is-checked {\n    transform: translateX(100%);\n  }\n\n  &.is-always-active-color,\n  &.is-checked {\n    background-color: var(--theme-color-secondary-bright);\n  }\n}\n\n.Input {\n  display: none;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Track": `ToggleSwitch-module__Track--QDN7v`,
	"Indicator": `ToggleSwitch-module__Indicator--dtLQa`,
	"is-checked": `ToggleSwitch-module__is-checked--DI_6j`,
	"is-always-active-color": `ToggleSwitch-module__is-always-active-color--YTDB4`,
	"Input": `ToggleSwitch-module__Input--pII4e`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 93193:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   O: () => (/* binding */ Compilation)
/* harmony export */ });
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80002);
/* harmony import */ var underscore__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(underscore__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _noodl_platform__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(37218);
/* harmony import */ var _noodl_models_CloudServices_GitStats__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(69402);
/* harmony import */ var _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6203);
/* harmony import */ var _noodl_utils_compilation_passes_sitemap__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(87329);
/* harmony import */ var _noodl_utils_node_graph_traverser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6056);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(47821);
/* harmony import */ var _shared_model__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_shared_model__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _build_context__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(34120);
/* harmony import */ var _build_deployer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(4073);
/* harmony import */ var _context_pages__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(3567);
/* harmony import */ var _passes_deploy_cloud_functions__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(87135);











/**
 * Compilation is a class that can be used to compile a project.
 *
 * @example
 * ```typescript
 * const compilation = createEditorCompilation(ProjectModel.instance)
 *   .addProjectBuildScripts()
 *   .addBuildScript({
 *     async onPostDeploy({ status }) {
 *       if (status === 'success') {
 *         PopupLayer.instance.hideActivity();
 *         PopupLayer.instance.showToast('Project deployed successfully!');
 *       } else {
 *         PopupLayer.instance.hideActivity();
 *         PopupLayer.instance.showToast('Could not upload deploy content.');
 *       }
 *     },
 *     onDeployProgress({ progress, progressTotal }) {
 *       PopupLayer.instance.showActivity('Deploying project');
 *       PopupLayer.instance.showActivityProgress((progress / progressTotal) * 100);
 *     }
 *   });
 *
 * compilation.deployToFolder("filepath", { environment: undefined });
 * ```
 */
class Compilation {
    constructor(project, feedback, options) {
        this.project = project;
        this.feedback = feedback;
        this.options = options;
        this.buildScripts = [];
        this.doLoadProjectBuildScripts = false;
        this.doLoadProjectBuildScriptsDone = false;
        if (!project)
            throw 'ProjectModel is not defined';
        // Add our build scripts
        this.addBuildScript(_passes_deploy_cloud_functions__WEBPACK_IMPORTED_MODULE_10__/* .deployCloudFunctionBuildScript */ .U);
        this.addBuildScript(_noodl_utils_compilation_passes_sitemap__WEBPACK_IMPORTED_MODULE_4__/* .SitemapBuildScript */ .H);
    }
    createCoreContext(environment) {
        let projectClone = this.project;
        if (this.options.cloneProject) {
            // Clone the project model so that the build scripts can modify it however they like.
            (_shared_model__WEBPACK_IMPORTED_MODULE_6___default()._listenersEnabled) = false; // Disable model listeners while loading project, otherwise this will bog down large projects
            projectClone = _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_3__.ProjectModel.fromJSON(this.project.toJSON());
            (_shared_model__WEBPACK_IMPORTED_MODULE_6___default()._listenersEnabled) = true;
            projectClone.modules = JSON.parse(JSON.stringify(this.project.modules));
            projectClone._retainedProjectDirectory = this.project._retainedProjectDirectory;
        }
        return {
            project: projectClone,
            environment,
            getHostname() {
                let hostname = projectClone.settings.baseUrl;
                if (hostname) {
                    if (!hostname.endsWith('/')) {
                        hostname = hostname + '/';
                    }
                    // TODO: Not sure if we want this:
                    // if (!hostname.startsWith('http')) {
                    //   hostname = 'https://' + hostname;
                    // }
                }
                return hostname;
            },
            activity: async (options, callback) => {
                const activityId = 'build-script-context-activity';
                this.feedback.showActivity(options.message, activityId);
                try {
                    await callback();
                    this.feedback.showSuccess(options.successMessage || options.message);
                }
                catch (error) {
                    this.feedback.showError(error);
                }
                this.feedback.hideActivity(activityId);
            },
            notify: (type, message) => {
                switch (type) {
                    default:
                    case _build_context__WEBPACK_IMPORTED_MODULE_7__/* .NotifyType */ .W.Notice:
                        this.feedback.showInteraction(message);
                        break;
                    case _build_context__WEBPACK_IMPORTED_MODULE_7__/* .NotifyType */ .W.Success:
                        this.feedback.showSuccess(message);
                        break;
                    case _build_context__WEBPACK_IMPORTED_MODULE_7__/* .NotifyType */ .W.Error:
                        this.feedback.showError(message);
                        break;
                }
            },
            graphTraverse(selector, options = {}) {
                return new _noodl_utils_node_graph_traverser__WEBPACK_IMPORTED_MODULE_5__/* .NodeGraphTraverser */ .r(this.project, selector, options);
            },
            getPages(options) {
                return (0,_context_pages__WEBPACK_IMPORTED_MODULE_9__/* .getIndexedPages */ .g)(this.project, options);
            },
            createIndexPage(parameters) {
                return (0,_build_deployer__WEBPACK_IMPORTED_MODULE_8__/* .createIndexPage */ .m)(this.project, parameters);
            }
        };
    }
    /**
     * Add the build scripts in the project folder.
     *
     * @returns
     */
    addProjectBuildScripts() {
        // Mark that we want to load the project build scripts,
        // and we will do that async once the build starts.
        this.doLoadProjectBuildScripts = true;
        return this;
    }
    /**
     * Add a custom build script.
     *
     * @param buildScript
     * @returns
     */
    addBuildScript(buildScript) {
        this.buildScripts.push(buildScript);
        return this;
    }
    /**
     * Deploy the project to a folder.
     *
     * @param filePath
     * @param options
     * @returns
     */
    deployToFolder(filePath, options) {
        return this.deployToFolderWithContext(filePath, options, this.createCoreContext(options.environment));
    }
    /**
     * Reuse the same core context when building.
     *
     * @param filePath
     * @param options
     * @param coreContext
     */
    async deployToFolderWithContext(filePath, options, coreContext) {
        await this.loadProjectBuildScripts();
        const projectSettings = this.project.getSettings();
        const common = {
            ...coreContext,
            outputPath: filePath
        };
        await this.callBuildScripts('onPreBuild', common);
        const envVariables = {};
        if (projectSettings.deployEnvDate) {
            envVariables['DeployedAt'] = new Date().toUTCString();
        }
        if (projectSettings.deployEnvGitStats) {
            const stats = await (0,_noodl_models_CloudServices_GitStats__WEBPACK_IMPORTED_MODULE_2__/* .getGitStats */ .K)();
            envVariables['GitBranch'] = stats.gitBranch;
            envVariables['GitSha'] = stats.gitSha;
        }
        try {
            await (0,_build_deployer__WEBPACK_IMPORTED_MODULE_8__/* .deployToFolder */ .H)({
                project: coreContext.project,
                direntry: filePath,
                environment: options.environment,
                baseUrl: coreContext.getHostname(),
                runtimeType: options.runtimeType,
                envVariables
            });
            await this.callBuildScripts('onPostBuild', { ...common, status: 'success' });
        }
        catch (error) {
            await this.callBuildScripts('onPostBuild', { ...common, status: 'failure' });
            throw error;
        }
    }
    // Since moving the filesystem to async we have to load this just before the build
    // starts, to make sure that the files are loaded when starting to build.
    async loadProjectBuildScripts() {
        if (!this.doLoadProjectBuildScripts)
            return;
        if (this.doLoadProjectBuildScriptsDone)
            return;
        // Create the path where the build scripts are located.
        const buildScriptLocation = _noodl_platform__WEBPACK_IMPORTED_MODULE_1__.filesystem.join(this.project._retainedProjectDirectory, '.noodl', 'build-scripts');
        // Build script folder doesn't exist.
        if (!_noodl_platform__WEBPACK_IMPORTED_MODULE_1__.filesystem.exists(buildScriptLocation)) {
            return this;
        }
        // Read all the files in that directory
        // TODO: Add all the build script without a fire-n-forget
        const files = await _noodl_platform__WEBPACK_IMPORTED_MODULE_1__.filesystem.listDirectory(buildScriptLocation);
        // - Select what files we want to load as build scripts.
        // - And order them by alphabetical order.
        let scriptFiles = files
            .filter((x) => !x.isDirectory)
            // TOOD: Should we check fullPath here?
            .map((x) => _noodl_platform__WEBPACK_IMPORTED_MODULE_1__.filesystem.join(buildScriptLocation, x.name))
            .filter((x) => x.endsWith('.build.js'));
        scriptFiles = (0,underscore__WEBPACK_IMPORTED_MODULE_0__.sortBy)(scriptFiles);
        // Parse all the files
        const readTasks = scriptFiles.map(async (filePath) => {
            // TODO: Add all the build script without a fire-n-forget
            const fileContent = await _noodl_platform__WEBPACK_IMPORTED_MODULE_1__.filesystem.readFile(filePath);
            try {
                const buildScript = eval(fileContent);
                if (buildScript) {
                    this.addBuildScript(buildScript);
                    console.log(`Add build script: '${filePath}'`);
                }
            }
            catch (error) {
                console.error(`Failed to execute build script '${filePath}'`);
                console.error(error);
            }
        });
        await Promise.all(readTasks);
        this.doLoadProjectBuildScriptsDone = true;
    }
    /**
     * Call a build script function in a safe environment.
     *
     * @param code
     * @param args
     */
    async callBuildScripts(code, ...args) {
        for (const buildScript of this.buildScripts) {
            if (buildScript[code]) {
                try {
                    await buildScript[code].apply(null, args);
                }
                catch (error) {
                    // This can be an external script, so we don't want to crash the whole compilation.
                    // Therefor we will only log the error.
                    console.error(`Failed to execute build script ${code}`);
                    console.error(error);
                }
            }
        }
    }
}


/***/ }),

/***/ 93220:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Label-module__Root--GYY_J{display:block;font-family:var(--font-family);line-height:1;margin-block-start:0;margin-block-end:0;transition:color var(--speed-turbo) var(--easing-base);white-space:pre}.Label-module__Root--GYY_J.Label-module__is-inline--JUku7{display:inline}.Label-module__Root--GYY_J.Label-module__is-size-small--Tybtp{font-size:10px;font-weight:var(--font-weight-medium)}.Label-module__Root--GYY_J.Label-module__is-size-default--r5yMf{font-size:12px;font-weight:var(--font-weight-medium)}.Label-module__Root--GYY_J.Label-module__is-size-medium--ULoNh{font-size:12px;font-weight:var(--font-weight-semibold)}.Label-module__Root--GYY_J.Label-module__is-size-big--uoa7q{font-size:14px;font-weight:var(--font-weight-semibold)}.Label-module__Root--GYY_J.Label-module__is-variant-default--KIb7h{color:var(--theme-color-fg-default)}.Label-module__Root--GYY_J.Label-module__is-variant-default-contrast--SlZ8R{color:var(--theme-color-fg-default-contrast)}.Label-module__Root--GYY_J.Label-module__is-variant-proud--l9GpQ{color:var(--theme-color-fg-highlight)}.Label-module__Root--GYY_J.Label-module__is-variant-shy--LpAHc{color:var(--theme-color-fg-muted)}.Label-module__Root--GYY_J.Label-module__is-variant-secondary--zn21_{color:var(--theme-color-secondary-as-fg)}.Label-module__Root--GYY_J.Label-module__is-variant-success--seBkq{color:var(--theme-color-success)}.Label-module__Root--GYY_J.Label-module__is-variant-notice--YDJNJ{color:var(--theme-color-notice)}.Label-module__Root--GYY_J.Label-module__is-variant-danger--qGr1u{color:var(--theme-color-danger)}.Label-module__Root--GYY_J.Label-module__has-bottom-spacing-small--X4jef{padding-bottom:4px}.Label-module__Root--GYY_J.Label-module__has-bottom-spacing-default--t8Qr6{padding-bottom:8px}.Label-module__Root--GYY_J.Label-module__has-bottom-spacing-large--RD7Nu{padding-bottom:16px}.Label-module__Root--GYY_J.Label-module__has-top-spacing-small--mfkUa{padding-top:4px}.Label-module__Root--GYY_J.Label-module__has-top-spacing-default--NlnO3{padding-top:8px}.Label-module__Root--GYY_J.Label-module__has-top-spacing-large--iujxm{padding-top:16px}.Label-module__Root--GYY_J.Label-module__has-left-spacing-small--vtYCK{padding-left:4px}.Label-module__Root--GYY_J.Label-module__has-left-spacing-default--VkR94{padding-left:8px}.Label-module__Root--GYY_J.Label-module__has-left-spacing-large--pUsxx{padding-left:16px}.Label-module__Root--GYY_J.Label-module__has-right-spacing-small--hYIks{padding-right:4px}.Label-module__Root--GYY_J.Label-module__has-right-spacing-default--OAHKf{padding-right:8px}.Label-module__Root--GYY_J.Label-module__has-right-spacing-large--AbhCl{padding-right:16px}.Label-module__Root--GYY_J.Label-module__has-text-wrap--XyHkp{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.1}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/typography/Label/Label.module.scss"],"names":[],"mappings":"AAAA,2BACE,aAAA,CACA,8BAAA,CACA,aAAA,CACA,oBAAA,CACA,kBAAA,CACA,sDAAA,CACA,eAAA,CAEA,0DACE,cAAA,CAGF,8DACE,cAAA,CACA,qCAAA,CAGF,gEACE,cAAA,CACA,qCAAA,CAGF,+DACE,cAAA,CACA,uCAAA,CAGF,4DACE,cAAA,CACA,uCAAA,CAIA,mEACE,mCAAA,CAGF,4EACE,4CAAA,CAGF,iEACE,qCAAA,CAGF,+DACE,iCAAA,CAGF,qEACE,wCAAA,CAGF,mEACE,gCAAA,CAGF,kEACE,+BAAA,CAGF,kEACE,+BAAA,CAKF,yEACE,kBAAA,CAGF,2EACE,kBAAA,CAGF,yEACE,mBAAA,CAKF,sEACE,eAAA,CAGF,wEACE,eAAA,CAGF,sEACE,gBAAA,CAKF,uEACE,gBAAA,CAGF,yEACE,gBAAA,CAGF,uEACE,iBAAA,CAKF,wEACE,iBAAA,CAGF,0EACE,iBAAA,CAGF,wEACE,kBAAA,CAIJ,8DACE,oBAAA,CACA,sBAAA,CACA,eAAA","sourcesContent":[".Root {\n  display: block;\n  font-family: var(--font-family);\n  line-height: 1;\n  margin-block-start: 0;\n  margin-block-end: 0;\n  transition: color var(--speed-turbo) var(--easing-base);\n  white-space: pre;\n\n  &.is-inline {\n    display: inline;\n  }\n\n  &.is-size-small {\n    font-size: 10px;\n    font-weight: var(--font-weight-medium);\n  }\n\n  &.is-size-default {\n    font-size: 12px;\n    font-weight: var(--font-weight-medium);\n  }\n\n  &.is-size-medium {\n    font-size: 12px;\n    font-weight: var(--font-weight-semibold);\n  }\n\n  &.is-size-big {\n    font-size: 14px;\n    font-weight: var(--font-weight-semibold);\n  }\n\n  &.is-variant {\n    &-default {\n      color: var(--theme-color-fg-default);\n    }\n\n    &-default-contrast {\n      color: var(--theme-color-fg-default-contrast);\n    }\n\n    &-proud {\n      color: var(--theme-color-fg-highlight);\n    }\n\n    &-shy {\n      color: var(--theme-color-fg-muted);\n    }\n\n    &-secondary {\n      color: var(--theme-color-secondary-as-fg);\n    }\n\n    &-success {\n      color: var(--theme-color-success);\n    }\n\n    &-notice {\n      color: var(--theme-color-notice);\n    }\n\n    &-danger {\n      color: var(--theme-color-danger);\n    }\n  }\n\n  &.has-bottom-spacing {\n    &-small {\n      padding-bottom: 4px;\n    }\n\n    &-default {\n      padding-bottom: 8px;\n    }\n\n    &-large {\n      padding-bottom: 16px;\n    }\n  }\n\n  &.has-top-spacing {\n    &-small {\n      padding-top: 4px;\n    }\n\n    &-default {\n      padding-top: 8px;\n    }\n\n    &-large {\n      padding-top: 16px;\n    }\n  }\n\n  &.has-left-spacing {\n    &-small {\n      padding-left: 4px;\n    }\n\n    &-default {\n      padding-left: 8px;\n    }\n\n    &-large {\n      padding-left: 16px;\n    }\n  }\n\n  &.has-right-spacing {\n    &-small {\n      padding-right: 4px;\n    }\n\n    &-default {\n      padding-right: 8px;\n    }\n\n    &-large {\n      padding-right: 16px;\n    }\n  }\n\n  &.has-text-wrap {\n    white-space: pre-wrap;\n    overflow-wrap: anywhere;\n    line-height: 1.1;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Label-module__Root--GYY_J`,
	"is-inline": `Label-module__is-inline--JUku7`,
	"is-size-small": `Label-module__is-size-small--Tybtp`,
	"is-size-default": `Label-module__is-size-default--r5yMf`,
	"is-size-medium": `Label-module__is-size-medium--ULoNh`,
	"is-size-big": `Label-module__is-size-big--uoa7q`,
	"is-variant-default": `Label-module__is-variant-default--KIb7h`,
	"is-variant-default-contrast": `Label-module__is-variant-default-contrast--SlZ8R`,
	"is-variant-proud": `Label-module__is-variant-proud--l9GpQ`,
	"is-variant-shy": `Label-module__is-variant-shy--LpAHc`,
	"is-variant-secondary": `Label-module__is-variant-secondary--zn21_`,
	"is-variant-success": `Label-module__is-variant-success--seBkq`,
	"is-variant-notice": `Label-module__is-variant-notice--YDJNJ`,
	"is-variant-danger": `Label-module__is-variant-danger--qGr1u`,
	"has-bottom-spacing-small": `Label-module__has-bottom-spacing-small--X4jef`,
	"has-bottom-spacing-default": `Label-module__has-bottom-spacing-default--t8Qr6`,
	"has-bottom-spacing-large": `Label-module__has-bottom-spacing-large--RD7Nu`,
	"has-top-spacing-small": `Label-module__has-top-spacing-small--mfkUa`,
	"has-top-spacing-default": `Label-module__has-top-spacing-default--NlnO3`,
	"has-top-spacing-large": `Label-module__has-top-spacing-large--iujxm`,
	"has-left-spacing-small": `Label-module__has-left-spacing-small--vtYCK`,
	"has-left-spacing-default": `Label-module__has-left-spacing-default--VkR94`,
	"has-left-spacing-large": `Label-module__has-left-spacing-large--pUsxx`,
	"has-right-spacing-small": `Label-module__has-right-spacing-small--hYIks`,
	"has-right-spacing-default": `Label-module__has-right-spacing-default--OAHKf`,
	"has-right-spacing-large": `Label-module__has-right-spacing-large--AbhCl`,
	"has-text-wrap": `Label-module__has-text-wrap--XyHkp`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 93447:
/***/ ((module) => {

// Module
var code = "<div class=\"content-picker\"> <div data-template=\"item\" class=\"content-picker-list-item\"> <div class=\"content-picker-item\" data-text=\"name\"> </div> </div> <label class=\"content-picker-header-label\" data-text=\"title\"></label> <div class=\"identifierItems content-picker-items\" style=\"overflow-y:auto\"> </div> </div>";
// Exports
module.exports = code;

/***/ }),

/***/ 93739:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  t: () => (/* reexport */ ContextMenu)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/inputs/IconButton/index.ts + 2 modules
var IconButton = __webpack_require__(28208);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/popups/MenuDialog/index.ts + 2 modules
var MenuDialog = __webpack_require__(23442);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/popups/ContextMenu/ContextMenu.module.scss
var ContextMenu_module = __webpack_require__(83790);
;// ../noodl-core-ui/src/components/popups/ContextMenu/ContextMenu.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(ContextMenu_module/* default */.A, options);




       /* harmony default export */ const ContextMenu_ContextMenu_module = (ContextMenu_module/* default */.A && ContextMenu_module/* default */.A.locals ? ContextMenu_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/popups/ContextMenu/ContextMenu.tsx






function ContextMenu({ menuItems, title, icon, size = Icon/* IconSize */.lK.Tiny, buttonSize = IconButton/* IconButtonSize */.Tp.Default, menuWidth, onOpen, onClose, variant, testId, renderDirection }) {
    const [isContextMenuVisible, setIsContextMenuVisible] = (0,external_react_.useState)(false);
    const toggleRef = (0,external_react_.useRef)(null);
    (0,external_react_.useEffect)(() => {
        if (isContextMenuVisible) {
            onOpen && onOpen();
        }
        else {
            onClose && onClose();
        }
        // not including onOpen in deps as it
        // should not cause a component rerender
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isContextMenuVisible]);
    return (external_react_default().createElement("div", { tabIndex: 1, className: external_classnames_default()(ContextMenu_ContextMenu_module['Root'], isContextMenuVisible && ContextMenu_ContextMenu_module['is-visible']), onFocus: () => setIsContextMenuVisible(true), "data-test": testId, onClick: (e) => {
            e.stopPropagation();
        } },
        external_react_default().createElement("div", { ref: toggleRef },
            external_react_default().createElement(IconButton/* IconButton */.K0, { icon: icon || Icon/* IconName */.$M.DotsThreeHorizontal, onClick: (e) => {
                    setIsContextMenuVisible(true);
                }, variant: variant, size: size, buttonSize: buttonSize })),
        external_react_default().createElement(MenuDialog.MenuDialog, { items: menuItems, title: title, isVisible: isContextMenuVisible, onClose: () => setIsContextMenuVisible(false), triggerRef: toggleRef, width: menuWidth, renderDirection: renderDirection })));
}

;// ../noodl-core-ui/src/components/popups/ContextMenu/index.ts



/***/ }),

/***/ 93751:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgDotsThreeHorizontal = function SvgDotsThreeHorizontal(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M17.1927 12C17.1927 12.8983 17.9209 13.6266 18.8192 13.6266C19.7176 13.6266 20.4458 12.8983 20.4458 12C20.4458 11.1017 19.7176 10.3734 18.8192 10.3734C17.9209 10.3734 17.1927 11.1017 17.1927 12Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M10.3733 12C10.3733 12.8983 11.1016 13.6266 11.9999 13.6266C12.8982 13.6266 13.6265 12.8983 13.6265 12C13.6265 11.1017 12.8982 10.3734 11.9999 10.3734C11.1016 10.3734 10.3733 11.1017 10.3733 12Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M3.554 12C3.554 12.8983 4.28224 13.6266 5.18056 13.6266C6.07889 13.6266 6.80713 12.8983 6.80713 12C6.80713 11.1017 6.07889 10.3734 5.18056 10.3734C4.28224 10.3734 3.554 11.1017 3.554 12Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgDotsThreeHorizontal);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "26d445bd322be1b3e4313983cded63a6.svg");

/***/ }),

/***/ 93774:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.SheetSelector-module__SheetSelector--VvVpi{position:relative;display:flex;align-items:center}.SheetSelector-module__TriggerButton--MZkTN{display:flex;align-items:center;gap:4px;padding:4px 8px;background-color:rgba(0,0,0,0);border:1px solid rgba(0,0,0,0);border-radius:4px;color:var(--theme-color-fg-default);font:11px var(--font-family-regular);cursor:pointer;transition:all var(--speed-turbo)}.SheetSelector-module__TriggerButton--MZkTN:hover{background-color:var(--theme-color-bg-2);border-color:var(--theme-color-border-default)}.SheetSelector-module__TriggerButton--MZkTN.SheetSelector-module__Open--hzji0{background-color:var(--theme-color-bg-2);border-color:var(--theme-color-primary)}.SheetSelector-module__SheetName--CdKo4{max-width:100px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.SheetSelector-module__ChevronIcon--FwqTs{width:10px;height:10px;transition:transform var(--speed-turbo)}.SheetSelector-module__ChevronIcon--FwqTs.SheetSelector-module__Open--hzji0{transform:rotate(180deg)}.SheetSelector-module__Dropdown--oXkdq{position:absolute;top:calc(100% + 4px);right:0;min-width:160px;max-width:200px;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:6px;box-shadow:0 4px 12px rgba(0,0,0,.3);z-index:1000;overflow:hidden}.SheetSelector-module__SheetList--eJSFn{max-height:200px;overflow-y:auto;padding:4px 0}.SheetSelector-module__SheetItem--Gd9sk{display:flex;align-items:center;gap:8px;padding:8px 12px;cursor:pointer;font:11px var(--font-family-regular);color:var(--theme-color-fg-default);transition:background-color var(--speed-turbo)}.SheetSelector-module__SheetItem--Gd9sk:hover{background-color:var(--theme-color-bg-3)}.SheetSelector-module__SheetItem--Gd9sk.SheetSelector-module__Selected--VHrh5{background-color:var(--theme-color-primary-transparent);color:var(--theme-color-primary)}.SheetSelector-module__SheetItem--Gd9sk.SheetSelector-module__AllSheets--SDk1v{color:var(--theme-color-fg-default-shy);font-style:italic}.SheetSelector-module__RadioIndicator--_GCFh{width:12px;height:12px;border:1px solid var(--theme-color-border-default);border-radius:50%;display:flex;align-items:center;justify-content:center}.SheetSelector-module__RadioIndicator--_GCFh.SheetSelector-module__Selected--VHrh5{border-color:var(--theme-color-primary)}.SheetSelector-module__RadioIndicator--_GCFh.SheetSelector-module__Selected--VHrh5::after{content:"";width:6px;height:6px;background-color:var(--theme-color-primary);border-radius:50%}.SheetSelector-module__SheetLabel--qqJbd{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.SheetSelector-module__SheetCount--AAuCu{color:var(--theme-color-fg-muted);font-size:10px}.SheetSelector-module__Divider--SIxC3{height:1px;background-color:var(--theme-color-border-default);margin:4px 0}.SheetSelector-module__AddSheetButton--yvWCJ{display:flex;align-items:center;gap:8px;width:100%;padding:8px 12px;background-color:rgba(0,0,0,0);border:none;cursor:pointer;font:11px var(--font-family-regular);color:var(--theme-color-fg-default);transition:background-color var(--speed-turbo)}.SheetSelector-module__AddSheetButton--yvWCJ:hover{background-color:var(--theme-color-bg-3)}.SheetSelector-module__AddIcon--d_GRQ{width:12px;height:12px;color:var(--theme-color-fg-default)}.SheetSelector-module__SheetActions--_mOAt{position:relative;margin-left:auto;opacity:0;transition:opacity var(--speed-turbo)}.SheetSelector-module__SheetActions--_mOAt.SheetSelector-module__Visible--Sx0La{opacity:1}.SheetSelector-module__SheetItem--Gd9sk.SheetSelector-module__HasActions--mLDh1:hover .SheetSelector-module__SheetActions--_mOAt{opacity:1}.SheetSelector-module__ActionButton--UUBVw{display:flex;align-items:center;justify-content:center;width:20px;height:20px;padding:0;background-color:rgba(0,0,0,0);border:none;border-radius:4px;cursor:pointer;color:var(--theme-color-fg-default);transition:background-color var(--speed-turbo)}.SheetSelector-module__ActionButton--UUBVw:hover{background-color:var(--theme-color-bg-3)}.SheetSelector-module__ActionMenu--IMj9I{position:absolute;bottom:100%;right:0;min-width:100px;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:4px;box-shadow:0 2px 8px rgba(0,0,0,.3);z-index:1001;overflow:hidden}.SheetSelector-module__ActionMenuItem--p6Io4{display:block;width:100%;padding:6px 12px;background-color:rgba(0,0,0,0);border:none;text-align:left;cursor:pointer;font:11px var(--font-family-regular);color:var(--theme-color-fg-default);transition:background-color var(--speed-turbo)}.SheetSelector-module__ActionMenuItem--p6Io4:hover{background-color:var(--theme-color-bg-3)}.SheetSelector-module__ActionMenuItem--p6Io4.SheetSelector-module__Danger--zh44L{color:var(--theme-color-danger)}.SheetSelector-module__ActionMenuItem--p6Io4.SheetSelector-module__Danger--zh44L:hover{background-color:var(--theme-color-danger-transparent)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/ComponentsPanelNew/components/SheetSelector.module.scss"],"names":[],"mappings":"AAOA,4CACE,iBAAA,CACA,YAAA,CACA,kBAAA,CAGF,4CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,eAAA,CACA,8BAAA,CACA,8BAAA,CACA,iBAAA,CACA,mCAAA,CACA,oCAAA,CACA,cAAA,CACA,iCAAA,CAEA,kDACE,wCAAA,CACA,8CAAA,CAGF,8EACE,wCAAA,CACA,uCAAA,CAIJ,wCACE,eAAA,CACA,eAAA,CACA,sBAAA,CACA,kBAAA,CAGF,0CACE,UAAA,CACA,WAAA,CACA,uCAAA,CAEA,4EACE,wBAAA,CAIJ,uCACE,iBAAA,CACA,oBAAA,CACA,OAAA,CACA,eAAA,CACA,eAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,oCAAA,CACA,YAAA,CACA,eAAA,CAGF,wCACE,gBAAA,CACA,eAAA,CACA,aAAA,CAGF,wCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,gBAAA,CACA,cAAA,CACA,oCAAA,CACA,mCAAA,CACA,8CAAA,CAEA,8CACE,wCAAA,CAGF,8EACE,uDAAA,CACA,gCAAA,CAGF,+EACE,uCAAA,CACA,iBAAA,CAIJ,6CACE,UAAA,CACA,WAAA,CACA,kDAAA,CACA,iBAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CAEA,mFACE,uCAAA,CAEA,0FACE,UAAA,CACA,SAAA,CACA,UAAA,CACA,2CAAA,CACA,iBAAA,CAKN,yCACE,MAAA,CACA,eAAA,CACA,sBAAA,CACA,kBAAA,CAGF,yCACE,iCAAA,CACA,cAAA,CAGF,sCACE,UAAA,CACA,kDAAA,CACA,YAAA,CAGF,6CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,UAAA,CACA,gBAAA,CACA,8BAAA,CACA,WAAA,CACA,cAAA,CACA,oCAAA,CACA,mCAAA,CACA,8CAAA,CAEA,mDACE,wCAAA,CAIJ,sCACE,UAAA,CACA,WAAA,CACA,mCAAA,CAIF,2CACE,iBAAA,CACA,gBAAA,CACA,SAAA,CACA,qCAAA,CAEA,gFACE,SAAA,CAIJ,iIACE,SAAA,CAGF,2CACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,UAAA,CACA,WAAA,CACA,SAAA,CACA,8BAAA,CACA,WAAA,CACA,iBAAA,CACA,cAAA,CACA,mCAAA,CACA,8CAAA,CAEA,iDACE,wCAAA,CAIJ,yCACE,iBAAA,CACA,WAAA,CACA,OAAA,CACA,eAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,YAAA,CACA,eAAA,CAGF,6CACE,aAAA,CACA,UAAA,CACA,gBAAA,CACA,8BAAA,CACA,WAAA,CACA,eAAA,CACA,cAAA,CACA,oCAAA,CACA,mCAAA,CACA,8CAAA,CAEA,mDACE,wCAAA,CAGF,iFACE,+BAAA,CAEA,uFACE,sDAAA","sourcesContent":["/**\n * SheetSelector Styles\n * \n * Dropdown selector for switching between component sheets\n * Using design tokens for proper theming support\n */\n\n.SheetSelector {\n  position: relative;\n  display: flex;\n  align-items: center;\n}\n\n.TriggerButton {\n  display: flex;\n  align-items: center;\n  gap: 4px;\n  padding: 4px 8px;\n  background-color: transparent;\n  border: 1px solid transparent;\n  border-radius: 4px;\n  color: var(--theme-color-fg-default);\n  font: 11px var(--font-family-regular);\n  cursor: pointer;\n  transition: all var(--speed-turbo);\n\n  &:hover {\n    background-color: var(--theme-color-bg-2);\n    border-color: var(--theme-color-border-default);\n  }\n\n  &.Open {\n    background-color: var(--theme-color-bg-2);\n    border-color: var(--theme-color-primary);\n  }\n}\n\n.SheetName {\n  max-width: 100px;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n.ChevronIcon {\n  width: 10px;\n  height: 10px;\n  transition: transform var(--speed-turbo);\n\n  &.Open {\n    transform: rotate(180deg);\n  }\n}\n\n.Dropdown {\n  position: absolute;\n  top: calc(100% + 4px);\n  right: 0;\n  min-width: 160px;\n  max-width: 200px;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 6px;\n  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);\n  z-index: 1000;\n  overflow: hidden;\n}\n\n.SheetList {\n  max-height: 200px;\n  overflow-y: auto;\n  padding: 4px 0;\n}\n\n.SheetItem {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 8px 12px;\n  cursor: pointer;\n  font: 11px var(--font-family-regular);\n  color: var(--theme-color-fg-default);\n  transition: background-color var(--speed-turbo);\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.Selected {\n    background-color: var(--theme-color-primary-transparent);\n    color: var(--theme-color-primary);\n  }\n\n  &.AllSheets {\n    color: var(--theme-color-fg-default-shy);\n    font-style: italic;\n  }\n}\n\n.RadioIndicator {\n  width: 12px;\n  height: 12px;\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 50%;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n\n  &.Selected {\n    border-color: var(--theme-color-primary);\n\n    &::after {\n      content: '';\n      width: 6px;\n      height: 6px;\n      background-color: var(--theme-color-primary);\n      border-radius: 50%;\n    }\n  }\n}\n\n.SheetLabel {\n  flex: 1;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n.SheetCount {\n  color: var(--theme-color-fg-muted);\n  font-size: 10px;\n}\n\n.Divider {\n  height: 1px;\n  background-color: var(--theme-color-border-default);\n  margin: 4px 0;\n}\n\n.AddSheetButton {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  width: 100%;\n  padding: 8px 12px;\n  background-color: transparent;\n  border: none;\n  cursor: pointer;\n  font: 11px var(--font-family-regular);\n  color: var(--theme-color-fg-default);\n  transition: background-color var(--speed-turbo);\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n.AddIcon {\n  width: 12px;\n  height: 12px;\n  color: var(--theme-color-fg-default);\n}\n\n/* Sheet Actions (three-dot menu) */\n.SheetActions {\n  position: relative;\n  margin-left: auto;\n  opacity: 0;\n  transition: opacity var(--speed-turbo);\n\n  &.Visible {\n    opacity: 1;\n  }\n}\n\n.SheetItem.HasActions:hover .SheetActions {\n  opacity: 1;\n}\n\n.ActionButton {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 20px;\n  height: 20px;\n  padding: 0;\n  background-color: transparent;\n  border: none;\n  border-radius: 4px;\n  cursor: pointer;\n  color: var(--theme-color-fg-default);\n  transition: background-color var(--speed-turbo);\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n}\n\n.ActionMenu {\n  position: absolute;\n  bottom: 100%;\n  right: 0;\n  min-width: 100px;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n  z-index: 1001;\n  overflow: hidden;\n}\n\n.ActionMenuItem {\n  display: block;\n  width: 100%;\n  padding: 6px 12px;\n  background-color: transparent;\n  border: none;\n  text-align: left;\n  cursor: pointer;\n  font: 11px var(--font-family-regular);\n  color: var(--theme-color-fg-default);\n  transition: background-color var(--speed-turbo);\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &.Danger {\n    color: var(--theme-color-danger);\n\n    &:hover {\n      background-color: var(--theme-color-danger-transparent);\n    }\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"SheetSelector": `SheetSelector-module__SheetSelector--VvVpi`,
	"TriggerButton": `SheetSelector-module__TriggerButton--MZkTN`,
	"Open": `SheetSelector-module__Open--hzji0`,
	"SheetName": `SheetSelector-module__SheetName--CdKo4`,
	"ChevronIcon": `SheetSelector-module__ChevronIcon--FwqTs`,
	"Dropdown": `SheetSelector-module__Dropdown--oXkdq`,
	"SheetList": `SheetSelector-module__SheetList--eJSFn`,
	"SheetItem": `SheetSelector-module__SheetItem--Gd9sk`,
	"Selected": `SheetSelector-module__Selected--VHrh5`,
	"AllSheets": `SheetSelector-module__AllSheets--SDk1v`,
	"RadioIndicator": `SheetSelector-module__RadioIndicator--_GCFh`,
	"SheetLabel": `SheetSelector-module__SheetLabel--qqJbd`,
	"SheetCount": `SheetSelector-module__SheetCount--AAuCu`,
	"Divider": `SheetSelector-module__Divider--SIxC3`,
	"AddSheetButton": `SheetSelector-module__AddSheetButton--yvWCJ`,
	"AddIcon": `SheetSelector-module__AddIcon--d_GRQ`,
	"SheetActions": `SheetSelector-module__SheetActions--_mOAt`,
	"Visible": `SheetSelector-module__Visible--Sx0La`,
	"HasActions": `SheetSelector-module__HasActions--mLDh1`,
	"ActionButton": `SheetSelector-module__ActionButton--UUBVw`,
	"ActionMenu": `SheetSelector-module__ActionMenu--IMj9I`,
	"ActionMenuItem": `SheetSelector-module__ActionMenuItem--p6Io4`,
	"Danger": `SheetSelector-module__Danger--zh44L`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 93834:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   $C: () => (/* reexport safe */ _Text__WEBPACK_IMPORTED_MODULE_0__.$C),
/* harmony export */   EY: () => (/* reexport safe */ _Text__WEBPACK_IMPORTED_MODULE_0__.EY),
/* harmony export */   M2: () => (/* reexport safe */ _Text__WEBPACK_IMPORTED_MODULE_0__.M2)
/* harmony export */ });
/* harmony import */ var _Text__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(75864);



/***/ }),

/***/ 93837:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `@keyframes ConfirmStep-module__arrowBounce--F57KW{0%,100%{transform:translateY(0)}50%{transform:translateY(4px)}}@keyframes ConfirmStep-module__slideInUp--xcab9{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.ConfirmStep-module__Root--V2ggm{display:flex;flex-direction:column;height:100%;animation:ConfirmStep-module__slideInUp--xcab9 300ms ease-out}.ConfirmStep-module__Header--OstsX{display:flex;align-items:center;gap:12px;margin-bottom:20px}.ConfirmStep-module__Header--OstsX svg{color:var(--theme-color-primary);width:24px;height:24px}.ConfirmStep-module__Header--OstsX h2{font-size:20px;font-weight:600;color:var(--theme-color-fg-highlight);margin:0}.ConfirmStep-module__PathSection--DWOwb{display:flex;flex-direction:column;gap:12px;padding:20px;background-color:var(--theme-color-bg-3);border-radius:8px;border:1px solid rgba(0,0,0,0);transition:all 250ms ease-in-out}.ConfirmStep-module__PathSection--DWOwb:hover{background-color:var(--theme-color-bg-2)}.ConfirmStep-module__PathSection--locked--BUhQI{background-color:var(--theme-color-bg-2);border-color:var(--theme-color-bg-1);opacity:.9}.ConfirmStep-module__PathSection--locked--BUhQI .ConfirmStep-module__PathValue--H2Daz{background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-default-shy);border:1px dashed var(--theme-color-bg-1)}.ConfirmStep-module__PathSection--editable--kBhwb{border-color:var(--theme-color-primary);border-width:2px;box-shadow:0 0 0 3px rgba(66,135,245,.1)}.ConfirmStep-module__PathSection--editable--kBhwb:hover{box-shadow:0 0 0 4px rgba(66,135,245,.15)}.ConfirmStep-module__PathHeader--mHDhh{display:flex;align-items:center;gap:10px}.ConfirmStep-module__PathHeader--mHDhh h3{font-size:14px;font-weight:600;color:var(--theme-color-fg-highlight);margin:0}.ConfirmStep-module__LockIcon--ezfjh{color:var(--theme-color-fg-muted);width:16px;height:16px}.ConfirmStep-module__FolderIcon--n5alG{color:var(--theme-color-primary);width:16px;height:16px}.ConfirmStep-module__PathFields--LAB9v{display:flex;flex-direction:column;gap:20px;margin-top:0}.ConfirmStep-module__PathField--PYsIC{display:flex;flex-direction:column;gap:8px}.ConfirmStep-module__PathLabel--JrdK4{display:flex;align-items:center;gap:8px;color:var(--theme-color-secondary-as-fg)}.ConfirmStep-module__PathLabel--JrdK4 svg{width:14px;height:14px}.ConfirmStep-module__PathDisplay--ojXGa{display:flex;flex-direction:column;gap:4px}.ConfirmStep-module__PathText--HaA7s{font-family:monospace;font-size:12px;word-break:break-all;color:var(--theme-color-fg-highlight)}.ConfirmStep-module__ProjectName--cOOrh{font-size:11px;color:var(--theme-color-secondary-as-fg)}.ConfirmStep-module__PathValue--H2Daz{padding:8px 12px;background-color:var(--theme-color-bg-2);border-radius:4px;font-family:monospace;font-size:12px;color:var(--theme-color-fg-highlight);word-break:break-all}.ConfirmStep-module__PathInput--eqNvU input{font-family:monospace;font-size:12px}.ConfirmStep-module__PathError--svdtl{display:flex;align-items:center;gap:8px;margin-top:8px}.ConfirmStep-module__Arrow--pDHrr{display:flex;align-items:center;justify-content:center;gap:12px;padding:16px 0;margin:8px 0;color:var(--theme-color-primary);font-size:13px;font-weight:500}.ConfirmStep-module__Arrow--pDHrr svg{width:20px;height:20px;animation:ConfirmStep-module__arrowBounce--F57KW 2s ease-in-out infinite}.ConfirmStep-module__InfoBox--Tsm8Q{padding:20px;background:linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);border-radius:8px;border-left:3px solid var(--theme-color-primary);box-shadow:0 2px 8px rgba(0,0,0,.1)}.ConfirmStep-module__InfoBox--Tsm8Q h4{font-size:14px;font-weight:600;color:var(--theme-color-fg-highlight);margin:0 0 12px 0;display:flex;align-items:center;gap:8px}.ConfirmStep-module__InfoBox--Tsm8Q h4 svg{width:16px;height:16px;color:var(--theme-color-primary)}.ConfirmStep-module__InfoBox--Tsm8Q p{font-size:13px;line-height:1.5;color:var(--theme-color-fg-default);margin:0 0 12px 0}.ConfirmStep-module__StepsList--Yaiks{margin:0;padding-left:24px;color:var(--theme-color-fg-default);font-size:13px;line-height:1.6}.ConfirmStep-module__StepsList--Yaiks li{margin-bottom:8px;padding-left:4px}.ConfirmStep-module__StepsList--Yaiks li::marker{color:var(--theme-color-primary);font-weight:600}.ConfirmStep-module__WarningBox--k6tjd{display:flex;gap:12px;padding:12px 16px;background-color:rgba(251,191,36,.1);border:1px solid rgba(251,191,36,.3);border-radius:8px;margin-top:16px}.ConfirmStep-module__WarningBox--k6tjd svg{width:20px;height:20px;flex-shrink:0;color:var(--theme-color-warning)}.ConfirmStep-module__WarningContent--zftzk{display:flex;flex-direction:column;gap:4px}.ConfirmStep-module__WarningTitle--PtZO6{font-weight:500;color:var(--theme-color-warning)}.ConfirmStep-module__Actions--CmZMi{margin-top:auto;padding-top:24px;display:flex;justify-content:flex-end}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/migration/steps/ConfirmStep.module.scss"],"names":[],"mappings":"AAOA,kDACE,QAEE,uBAAA,CAEF,IACE,yBAAA,CAAA,CAIJ,gDACE,KACE,SAAA,CACA,0BAAA,CAEF,GACE,SAAA,CACA,uBAAA,CAAA,CAIJ,iCACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,6DAAA,CAGF,mCACE,YAAA,CACA,kBAAA,CACA,QAAA,CACA,kBAAA,CAEA,uCACE,gCAAA,CACA,UAAA,CACA,WAAA,CAGF,sCACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,QAAA,CAIJ,wCACE,YAAA,CACA,qBAAA,CACA,QAAA,CACA,YAAA,CACA,wCAAA,CACA,iBAAA,CACA,8BAAA,CACA,gCAAA,CAEA,8CACE,wCAAA,CAIJ,gDACE,wCAAA,CACA,oCAAA,CACA,UAAA,CAEA,sFACE,wCAAA,CACA,uCAAA,CACA,yCAAA,CAIJ,kDACE,uCAAA,CACA,gBAAA,CACA,wCAAA,CAEA,wDACE,yCAAA,CAIJ,uCACE,YAAA,CACA,kBAAA,CACA,QAAA,CAEA,0CACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,QAAA,CAIJ,qCACE,iCAAA,CACA,UAAA,CACA,WAAA,CAGF,uCACE,gCAAA,CACA,UAAA,CACA,WAAA,CAGF,uCACE,YAAA,CACA,qBAAA,CACA,QAAA,CACA,YAAA,CAGF,sCACE,YAAA,CACA,qBAAA,CACA,OAAA,CAGF,sCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,wCAAA,CAEA,0CACE,UAAA,CACA,WAAA,CAIJ,wCACE,YAAA,CACA,qBAAA,CACA,OAAA,CAGF,qCACE,qBAAA,CACA,cAAA,CACA,oBAAA,CACA,qCAAA,CAGF,wCACE,cAAA,CACA,wCAAA,CAGF,sCACE,gBAAA,CACA,wCAAA,CACA,iBAAA,CACA,qBAAA,CACA,cAAA,CACA,qCAAA,CACA,oBAAA,CAIA,4CACE,qBAAA,CACA,cAAA,CAIJ,sCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,cAAA,CAGF,kCACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,QAAA,CACA,cAAA,CACA,YAAA,CACA,gCAAA,CACA,cAAA,CACA,eAAA,CAEA,sCACE,UAAA,CACA,WAAA,CACA,wEAAA,CAIJ,oCACE,YAAA,CACA,4FAAA,CACA,iBAAA,CACA,gDAAA,CACA,mCAAA,CAEA,uCACE,cAAA,CACA,eAAA,CACA,qCAAA,CACA,iBAAA,CACA,YAAA,CACA,kBAAA,CACA,OAAA,CAEA,2CACE,UAAA,CACA,WAAA,CACA,gCAAA,CAIJ,sCACE,cAAA,CACA,eAAA,CACA,mCAAA,CACA,iBAAA,CAIJ,sCACE,QAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CAEA,yCACE,iBAAA,CACA,gBAAA,CAEA,iDACE,gCAAA,CACA,eAAA,CAKN,uCACE,YAAA,CACA,QAAA,CACA,iBAAA,CACA,oCAAA,CACA,oCAAA,CACA,iBAAA,CACA,eAAA,CAEA,2CACE,UAAA,CACA,WAAA,CACA,aAAA,CACA,gCAAA,CAIJ,2CACE,YAAA,CACA,qBAAA,CACA,OAAA,CAGF,yCACE,eAAA,CACA,gCAAA,CAGF,oCACE,eAAA,CACA,gBAAA,CACA,YAAA,CACA,wBAAA","sourcesContent":["/**\n * ConfirmStep Styles\n * \n * First step of migration wizard - confirm source and target paths.\n * Enhanced with better visual hierarchy and animations.\n */\n\n@keyframes arrowBounce {\n  0%,\n  100% {\n    transform: translateY(0);\n  }\n  50% {\n    transform: translateY(4px);\n  }\n}\n\n@keyframes slideInUp {\n  from {\n    opacity: 0;\n    transform: translateY(10px);\n  }\n  to {\n    opacity: 1;\n    transform: translateY(0);\n  }\n}\n\n.Root {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  animation: slideInUp 300ms ease-out;\n}\n\n.Header {\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  margin-bottom: 20px;\n\n  svg {\n    color: var(--theme-color-primary);\n    width: 24px;\n    height: 24px;\n  }\n\n  h2 {\n    font-size: 20px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    margin: 0;\n  }\n}\n\n.PathSection {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n  padding: 20px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 8px;\n  border: 1px solid transparent;\n  transition: all 250ms ease-in-out;\n\n  &:hover {\n    background-color: var(--theme-color-bg-2);\n  }\n}\n\n.PathSection--locked {\n  background-color: var(--theme-color-bg-2);\n  border-color: var(--theme-color-bg-1);\n  opacity: 0.9;\n\n  .PathValue {\n    background-color: var(--theme-color-bg-1);\n    color: var(--theme-color-fg-default-shy);\n    border: 1px dashed var(--theme-color-bg-1);\n  }\n}\n\n.PathSection--editable {\n  border-color: var(--theme-color-primary);\n  border-width: 2px;\n  box-shadow: 0 0 0 3px rgba(66, 135, 245, 0.1);\n\n  &:hover {\n    box-shadow: 0 0 0 4px rgba(66, 135, 245, 0.15);\n  }\n}\n\n.PathHeader {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n\n  h3 {\n    font-size: 14px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    margin: 0;\n  }\n}\n\n.LockIcon {\n  color: var(--theme-color-fg-muted);\n  width: 16px;\n  height: 16px;\n}\n\n.FolderIcon {\n  color: var(--theme-color-primary);\n  width: 16px;\n  height: 16px;\n}\n\n.PathFields {\n  display: flex;\n  flex-direction: column;\n  gap: 20px;\n  margin-top: 0;\n}\n\n.PathField {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n}\n\n.PathLabel {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  color: var(--theme-color-secondary-as-fg);\n\n  svg {\n    width: 14px;\n    height: 14px;\n  }\n}\n\n.PathDisplay {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n}\n\n.PathText {\n  font-family: monospace;\n  font-size: 12px;\n  word-break: break-all;\n  color: var(--theme-color-fg-highlight);\n}\n\n.ProjectName {\n  font-size: 11px;\n  color: var(--theme-color-secondary-as-fg);\n}\n\n.PathValue {\n  padding: 8px 12px;\n  background-color: var(--theme-color-bg-2);\n  border-radius: 4px;\n  font-family: monospace;\n  font-size: 12px;\n  color: var(--theme-color-fg-highlight);\n  word-break: break-all;\n}\n\n.PathInput {\n  input {\n    font-family: monospace;\n    font-size: 12px;\n  }\n}\n\n.PathError {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin-top: 8px;\n}\n\n.Arrow {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  gap: 12px;\n  padding: 16px 0;\n  margin: 8px 0;\n  color: var(--theme-color-primary);\n  font-size: 13px;\n  font-weight: 500;\n\n  svg {\n    width: 20px;\n    height: 20px;\n    animation: arrowBounce 2s ease-in-out infinite;\n  }\n}\n\n.InfoBox {\n  padding: 20px;\n  background: linear-gradient(135deg, var(--theme-color-bg-3) 0%, var(--theme-color-bg-2) 100%);\n  border-radius: 8px;\n  border-left: 3px solid var(--theme-color-primary);\n  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n\n  h4 {\n    font-size: 14px;\n    font-weight: 600;\n    color: var(--theme-color-fg-highlight);\n    margin: 0 0 12px 0;\n    display: flex;\n    align-items: center;\n    gap: 8px;\n\n    svg {\n      width: 16px;\n      height: 16px;\n      color: var(--theme-color-primary);\n    }\n  }\n\n  p {\n    font-size: 13px;\n    line-height: 1.5;\n    color: var(--theme-color-fg-default);\n    margin: 0 0 12px 0;\n  }\n}\n\n.StepsList {\n  margin: 0;\n  padding-left: 24px;\n  color: var(--theme-color-fg-default);\n  font-size: 13px;\n  line-height: 1.6;\n\n  li {\n    margin-bottom: 8px;\n    padding-left: 4px;\n\n    &::marker {\n      color: var(--theme-color-primary);\n      font-weight: 600;\n    }\n  }\n}\n\n.WarningBox {\n  display: flex;\n  gap: 12px;\n  padding: 12px 16px;\n  background-color: rgba(251, 191, 36, 0.1);\n  border: 1px solid rgba(251, 191, 36, 0.3);\n  border-radius: 8px;\n  margin-top: 16px;\n\n  svg {\n    width: 20px;\n    height: 20px;\n    flex-shrink: 0;\n    color: var(--theme-color-warning);\n  }\n}\n\n.WarningContent {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n}\n\n.WarningTitle {\n  font-weight: 500;\n  color: var(--theme-color-warning);\n}\n\n.Actions {\n  margin-top: auto;\n  padding-top: 24px;\n  display: flex;\n  justify-content: flex-end;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ConfirmStep-module__Root--V2ggm`,
	"slideInUp": `ConfirmStep-module__slideInUp--xcab9`,
	"Header": `ConfirmStep-module__Header--OstsX`,
	"PathSection": `ConfirmStep-module__PathSection--DWOwb`,
	"PathSection--locked": `ConfirmStep-module__PathSection--locked--BUhQI`,
	"PathValue": `ConfirmStep-module__PathValue--H2Daz`,
	"PathSection--editable": `ConfirmStep-module__PathSection--editable--kBhwb`,
	"PathHeader": `ConfirmStep-module__PathHeader--mHDhh`,
	"LockIcon": `ConfirmStep-module__LockIcon--ezfjh`,
	"FolderIcon": `ConfirmStep-module__FolderIcon--n5alG`,
	"PathFields": `ConfirmStep-module__PathFields--LAB9v`,
	"PathField": `ConfirmStep-module__PathField--PYsIC`,
	"PathLabel": `ConfirmStep-module__PathLabel--JrdK4`,
	"PathDisplay": `ConfirmStep-module__PathDisplay--ojXGa`,
	"PathText": `ConfirmStep-module__PathText--HaA7s`,
	"ProjectName": `ConfirmStep-module__ProjectName--cOOrh`,
	"PathInput": `ConfirmStep-module__PathInput--eqNvU`,
	"PathError": `ConfirmStep-module__PathError--svdtl`,
	"Arrow": `ConfirmStep-module__Arrow--pDHrr`,
	"arrowBounce": `ConfirmStep-module__arrowBounce--F57KW`,
	"InfoBox": `ConfirmStep-module__InfoBox--Tsm8Q`,
	"StepsList": `ConfirmStep-module__StepsList--Yaiks`,
	"WarningBox": `ConfirmStep-module__WarningBox--k6tjd`,
	"WarningContent": `ConfirmStep-module__WarningContent--zftzk`,
	"WarningTitle": `ConfirmStep-module__WarningTitle--PtZO6`,
	"Actions": `ConfirmStep-module__Actions--CmZMi`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 93938:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .bracket-match {
	box-sizing: border-box;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/bracketMatching/browser/bracketMatching.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,sBAAsB;AACvB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .bracket-match {\n\tbox-sizing: border-box;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 94047:
/***/ ((module) => {

// Module
var code = "<div style=\"width:400px\" data-indent-offset=\"20\"> <div data-template=\"folder\" class=\"import-popup-folder\" style=\"width:100%;position:relative\"> <div style=\"width:100%;height:24px;position:relative\"> <div class=\"sidebar-panel-dark-input\" style=\"position:absolute;left:2px;width:24px;top:3px;bottom:3px\" data-click=\"onFolderBoxClicked\"> <i class=\"fa fa-check\" data-class=\"!import:hidden,implicit:import-popup-implicit-check,import:import-popup-import-check\" style=\"position:absolute;left:7px;top:5px\"></i> </div> <div class=\"indent-me\" style=\"width:100%;height:24px;position:absolute\" data-click=\"onFolderClicked\"> <div style=\"position:absolute;width:28px;top:4px;bottom:4px\"> <i class=\"fa\" data-class=\"open:fa-caret-down,!open:fa-caret-right\"></i> </div> <div style=\"line-height:20px;position:absolute;left:10px;top:3px;bottom:3px;right:3px\" data-text=\"localName\"> </div> </div> </div> <div class=\"content\" style=\"\"></div> </div> <div data-template=\"item\" class=\"import-popup-item\" style=\"width:100%;height:24px;position:relative\"> <div class=\"sidebar-panel-dark-input\" style=\"position:absolute;left:2px;width:24px;top:3px;bottom:3px\" data-click=\"onBoxClicked\"> <i class=\"fa fa-check\" data-class=\"!check:hidden,implicit:import-popup-implicit-check,import:import-popup-import-check\" style=\"position:absolute;left:7px;top:5px\"></i> </div> <div class=\"indent-me\" style=\"line-height:20px;position:absolute;top:3px;bottom:3px;right:3px\" data-text=\"localName\"> </div> </div> <div style=\"height:500px;overflow:hidden auto\"> <label class=\"popup-group-label\">COLLISIONS</label> <div class=\"import-popup-text\"> There are collisions when importing, you may select what to import (current project will be overwritten) and what to leave as is. </div> <div data-class=\"!hasComponents:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\">COMPONENTS</label> <div class=\"import-popup-text\"> Choose which components that will be imported and overwrite your current components. </div> <div class=\"components import-popup-item\" style=\"margin-top:10px\"></div> </div> <div data-class=\"!hasResources:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\">RESOURCES</label> <div class=\"import-popup-text\"> Choose which resources that will be imported and overwrite your current resources. </div> <div class=\"resources import-popup-item\" style=\"margin-top:10px\"></div> </div> <div data-class=\"!hasModules:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\">MODULES</label> <div class=\"import-popup-text\"> Choose which modules that will be imported and overwrite your current modules. </div> <div class=\"modules import-popup-item\" style=\"margin-top:10px\"></div> </div> <div data-class=\"!hasVariants:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\">VARIANTS</label> <div class=\"import-popup-text\"> Choose which variants that will be imported and overwrite your current variants. </div> <div class=\"variants import-popup-item\" style=\"margin-top:10px\"></div> </div> <div data-class=\"!hasTextStyles:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\">TEXT STYLES</label> <div class=\"import-popup-text\"> Choose which text styles that will be imported and overwrite your current text styles. </div> <div class=\"text-styles import-popup-item\" style=\"margin-top:10px\"></div> </div> <div data-class=\"!hasColorStyles:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\">COLOR STYLES</label> <div class=\"import-popup-text\"> Choose which color styles that will be imported and overwrite your current color styles. </div> <div class=\"color-styles import-popup-item\" style=\"margin-top:10px\"></div> </div> <div class=\"import-popup-text\" style=\"margin-top:20px\"> <strong>Warning</strong> this operation cannot be undone! Would you like to proceed? </div> <div style=\"height:30px;padding:5px;padding-bottom:10px;margin-top:20px\"> <button class=\"popup-button\" data-click=\"onOkClicked\">Overwrite</button> <button class=\"popup-button-grey\" data-click=\"onCancelClicked\">Cancel</button> </div> </div> </div>";
// Exports
module.exports = code;

/***/ }),

/***/ 94168:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.EditorNode-module__Root--m0rOs{padding:8px 12px;font-size:12px;font-weight:500;cursor:pointer;box-sizing:border-box;height:100%;word-break:break-word;background-color:var(--baseColor);display:flex;flex-wrap:nowrap;align-items:center;min-height:36px}.EditorNode-module__Root--m0rOs.EditorNode-module__is-highlighted--_ARMT{background-color:var(--highlightColor)}.EditorNode-module__Label--HlFRK{color:var(--textColor);display:block;font-family:var(--font-family);font-weight:var(--font-weight-medium)}.EditorNode-module__Label--HlFRK.EditorNode-module__is-after-icon--euV54{margin-left:8px}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/common/EditorNode/EditorNode.module.scss"],"names":[],"mappings":"AAAA,gCACE,gBAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,qBAAA,CACA,WAAA,CACA,qBAAA,CACA,iCAAA,CACA,YAAA,CACA,gBAAA,CACA,kBAAA,CACA,eAAA,CAEA,yEACE,sCAAA,CAIJ,iCACE,sBAAA,CACA,aAAA,CACA,8BAAA,CACA,qCAAA,CAEA,yEACE,eAAA","sourcesContent":[".Root {\r\n  padding: 8px 12px;\r\n  font-size: 12px;\r\n  font-weight: 500;\r\n  cursor: pointer;\r\n  box-sizing: border-box;\r\n  height: 100%;\r\n  word-break: break-word;\r\n  background-color: var(--baseColor);\r\n  display: flex;\r\n  flex-wrap: nowrap;\r\n  align-items: center;\r\n  min-height: 36px;\r\n\r\n  &.is-highlighted {\r\n    background-color: var(--highlightColor);\r\n  }\r\n}\r\n\r\n.Label {\r\n  color: var(--textColor);\r\n  display: block;\r\n  font-family: var(--font-family);\r\n  font-weight: var(--font-weight-medium);\r\n\r\n  &.is-after-icon {\r\n    margin-left: 8px;\r\n  }\r\n}\r\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `EditorNode-module__Root--m0rOs`,
	"is-highlighted": `EditorNode-module__is-highlighted--_ARMT`,
	"Label": `EditorNode-module__Label--HlFRK`,
	"is-after-icon": `EditorNode-module__is-after-icon--euV54`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 94389:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgTextAlignRight = function SvgTextAlignRight(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 24,
    viewBox: "0 0 25 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.1367 17.625C21.1367 18.0392 20.8009 18.375 20.3867 18.375L3.88672 18.375C3.47251 18.375 3.13672 18.0392 3.13672 17.625C3.13672 17.2108 3.47251 16.875 3.88672 16.875L20.3867 16.875C20.8009 16.875 21.1367 17.2108 21.1367 17.625Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.1367 13.875C21.1367 14.2892 20.8009 14.625 20.3867 14.625L8.38672 14.625C7.97251 14.625 7.63672 14.2892 7.63672 13.875C7.63672 13.4608 7.97251 13.125 8.38672 13.125L20.3867 13.125C20.8009 13.125 21.1367 13.4608 21.1367 13.875Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.1367 10.125C21.1367 10.5392 20.8009 10.875 20.3867 10.875L3.88672 10.875C3.47251 10.875 3.13672 10.5392 3.13672 10.125C3.13672 9.71078 3.47251 9.375 3.88672 9.375L20.3867 9.375C20.8009 9.375 21.1367 9.71079 21.1367 10.125Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M21.1367 6.375C21.1367 6.78921 20.8009 7.125 20.3867 7.125L8.38672 7.125C7.97251 7.125 7.63672 6.78921 7.63672 6.375C7.63672 5.96079 7.97251 5.625 8.38672 5.625L20.3867 5.625C20.8009 5.625 21.1367 5.96079 21.1367 6.375Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgTextAlignRight);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "00f5cc93babf966813bda591dec57f62.svg");

/***/ }),

/***/ 94417:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.IssuesList-module__IssuesList--ZXibC{padding:8px;overflow-y:auto;flex:1}.IssuesList-module__LoadingState--kLPED,.IssuesList-module__ErrorState--PqkhZ,.IssuesList-module__EmptyState--Da9nn{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:40px 20px;text-align:center;color:var(--theme-color-fg-default-shy)}.IssuesList-module__Spinner--bhjmf{width:32px;height:32px;border:3px solid var(--theme-color-border-default);border-top-color:var(--theme-color-primary);border-radius:50%;animation:IssuesList-module__spin--m_zOw 1s linear infinite;margin-bottom:16px}@keyframes IssuesList-module__spin--m_zOw{to{transform:rotate(360deg)}}.IssuesList-module__LoadingState--kLPED p{color:var(--theme-color-fg-default-shy);font-size:13px}.IssuesList-module__ErrorState--PqkhZ{color:var(--theme-color-fg-error)}.IssuesList-module__ErrorIcon--n0iUk{font-size:48px;margin-bottom:16px}.IssuesList-module__ErrorState--PqkhZ h3{color:var(--theme-color-fg-default);font-size:15px;font-weight:600;margin-bottom:8px}.IssuesList-module__ErrorState--PqkhZ p{color:var(--theme-color-fg-default-shy);font-size:13px;margin-bottom:16px}.IssuesList-module__RetryButton--lQatc{padding:8px 16px;background-color:var(--theme-color-primary);color:#fff;border:none;border-radius:4px;font-size:13px;font-weight:500;cursor:pointer;transition:opacity .15s ease}.IssuesList-module__RetryButton--lQatc:hover{opacity:.9}.IssuesList-module__RetryButton--lQatc:active{opacity:.8}.IssuesList-module__EmptyIcon--oaJTU{font-size:48px;margin-bottom:16px}.IssuesList-module__EmptyState--Da9nn h3{color:var(--theme-color-fg-default);font-size:15px;font-weight:600;margin-bottom:8px}.IssuesList-module__EmptyState--Da9nn p{color:var(--theme-color-fg-default-shy);font-size:13px}.IssuesList-module__LoadMoreButton--yTfSl{width:100%;padding:10px;margin-top:8px;background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:4px;color:var(--theme-color-fg-default);font-size:13px;font-weight:500;cursor:pointer;transition:all .15s ease;display:flex;align-items:center;justify-content:center;gap:8px}.IssuesList-module__LoadMoreButton--yTfSl:hover:not(:disabled){background-color:var(--theme-color-bg-4);border-color:var(--theme-color-border-hover)}.IssuesList-module__LoadMoreButton--yTfSl:disabled{opacity:.6;cursor:not-allowed}.IssuesList-module__SmallSpinner--miChF{width:14px;height:14px;border:2px solid var(--theme-color-border-default);border-top-color:var(--theme-color-primary);border-radius:50%;animation:IssuesList-module__spin--m_zOw 1s linear infinite}.IssuesList-module__EndMessage--i9vf_{text-align:center;padding:16px;color:var(--theme-color-fg-default-shy);font-size:12px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssuesList.module.scss"],"names":[],"mappings":"AAIA,sCACE,WAAA,CACA,eAAA,CACA,MAAA,CAGF,oHAGE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,iBAAA,CACA,uCAAA,CAGF,mCACE,UAAA,CACA,WAAA,CACA,kDAAA,CACA,2CAAA,CACA,iBAAA,CACA,2DAAA,CACA,kBAAA,CAGF,0CACE,GACE,wBAAA,CAAA,CAIJ,0CACE,uCAAA,CACA,cAAA,CAGF,sCACE,iCAAA,CAGF,qCACE,cAAA,CACA,kBAAA,CAGF,yCACE,mCAAA,CACA,cAAA,CACA,eAAA,CACA,iBAAA,CAGF,wCACE,uCAAA,CACA,cAAA,CACA,kBAAA,CAGF,uCACE,gBAAA,CACA,2CAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,4BAAA,CAEA,6CACE,UAAA,CAGF,8CACE,UAAA,CAIJ,qCACE,cAAA,CACA,kBAAA,CAGF,yCACE,mCAAA,CACA,cAAA,CACA,eAAA,CACA,iBAAA,CAGF,wCACE,uCAAA,CACA,cAAA,CAGF,0CACE,UAAA,CACA,YAAA,CACA,cAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,wBAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,OAAA,CAEA,+DACE,wCAAA,CACA,4CAAA,CAGF,mDACE,UAAA,CACA,kBAAA,CAIJ,wCACE,UAAA,CACA,WAAA,CACA,kDAAA,CACA,2CAAA,CACA,iBAAA,CACA,2DAAA,CAGF,sCACE,iBAAA,CACA,YAAA,CACA,uCAAA,CACA,cAAA","sourcesContent":["/**\n * IssuesList Styles\n */\n\n.IssuesList {\n  padding: 8px;\n  overflow-y: auto;\n  flex: 1;\n}\n\n.LoadingState,\n.ErrorState,\n.EmptyState {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  padding: 40px 20px;\n  text-align: center;\n  color: var(--theme-color-fg-default-shy);\n}\n\n.Spinner {\n  width: 32px;\n  height: 32px;\n  border: 3px solid var(--theme-color-border-default);\n  border-top-color: var(--theme-color-primary);\n  border-radius: 50%;\n  animation: spin 1s linear infinite;\n  margin-bottom: 16px;\n}\n\n@keyframes spin {\n  to {\n    transform: rotate(360deg);\n  }\n}\n\n.LoadingState p {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 13px;\n}\n\n.ErrorState {\n  color: var(--theme-color-fg-error);\n}\n\n.ErrorIcon {\n  font-size: 48px;\n  margin-bottom: 16px;\n}\n\n.ErrorState h3 {\n  color: var(--theme-color-fg-default);\n  font-size: 15px;\n  font-weight: 600;\n  margin-bottom: 8px;\n}\n\n.ErrorState p {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 13px;\n  margin-bottom: 16px;\n}\n\n.RetryButton {\n  padding: 8px 16px;\n  background-color: var(--theme-color-primary);\n  color: white;\n  border: none;\n  border-radius: 4px;\n  font-size: 13px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: opacity 0.15s ease;\n\n  &:hover {\n    opacity: 0.9;\n  }\n\n  &:active {\n    opacity: 0.8;\n  }\n}\n\n.EmptyIcon {\n  font-size: 48px;\n  margin-bottom: 16px;\n}\n\n.EmptyState h3 {\n  color: var(--theme-color-fg-default);\n  font-size: 15px;\n  font-weight: 600;\n  margin-bottom: 8px;\n}\n\n.EmptyState p {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 13px;\n}\n\n.LoadMoreButton {\n  width: 100%;\n  padding: 10px;\n  margin-top: 8px;\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  color: var(--theme-color-fg-default);\n  font-size: 13px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: all 0.15s ease;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  gap: 8px;\n\n  &:hover:not(:disabled) {\n    background-color: var(--theme-color-bg-4);\n    border-color: var(--theme-color-border-hover);\n  }\n\n  &:disabled {\n    opacity: 0.6;\n    cursor: not-allowed;\n  }\n}\n\n.SmallSpinner {\n  width: 14px;\n  height: 14px;\n  border: 2px solid var(--theme-color-border-default);\n  border-top-color: var(--theme-color-primary);\n  border-radius: 50%;\n  animation: spin 1s linear infinite;\n}\n\n.EndMessage {\n  text-align: center;\n  padding: 16px;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 12px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"IssuesList": `IssuesList-module__IssuesList--ZXibC`,
	"LoadingState": `IssuesList-module__LoadingState--kLPED`,
	"ErrorState": `IssuesList-module__ErrorState--PqkhZ`,
	"EmptyState": `IssuesList-module__EmptyState--Da9nn`,
	"Spinner": `IssuesList-module__Spinner--bhjmf`,
	"spin": `IssuesList-module__spin--m_zOw`,
	"ErrorIcon": `IssuesList-module__ErrorIcon--n0iUk`,
	"RetryButton": `IssuesList-module__RetryButton--lQatc`,
	"EmptyIcon": `IssuesList-module__EmptyIcon--oaJTU`,
	"LoadMoreButton": `IssuesList-module__LoadMoreButton--yTfSl`,
	"SmallSpinner": `IssuesList-module__SmallSpinner--miChF`,
	"EndMessage": `IssuesList-module__EndMessage--i9vf_`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 94705:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgArrowsInLineVertical = function SvgArrowsInLineVertical(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M12.1367 3.93823C12.5509 3.93823 12.8867 4.27402 12.8867 4.68823L12.8867 21.1882C12.8867 21.6024 12.5509 21.9382 12.1367 21.9382C11.7225 21.9382 11.3867 21.6024 11.3867 21.1882L11.3867 4.68823C11.3867 4.27402 11.7225 3.93823 12.1367 3.93823Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M9.82672 12.647C9.78672 12.557 9.73672 12.477 9.66672 12.407L6.66672 9.40698C6.37672 9.11698 5.89672 9.11698 5.60672 9.40698C5.31672 9.69698 5.31672 10.177 5.60672 10.467L7.32672 12.187H1.63672C1.22672 12.187 0.886719 12.527 0.886719 12.937C0.886719 13.347 1.22672 13.687 1.63672 13.687H7.32672L5.60672 15.407C5.31672 15.697 5.31672 16.177 5.60672 16.467C5.75672 16.617 5.94672 16.687 6.13672 16.687C6.32672 16.687 6.51672 16.617 6.66672 16.467L9.66672 13.467C9.73672 13.397 9.78672 13.317 9.82672 13.227C9.86672 13.137 9.88672 13.047 9.88672 12.937C9.88672 12.827 9.86672 12.737 9.82672 12.647Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M14.4467 12.647C14.4867 12.557 14.5367 12.477 14.6067 12.407L17.6067 9.40698C17.8967 9.11698 18.3767 9.11698 18.6667 9.40698C18.9567 9.69698 18.9567 10.177 18.6667 10.467L16.9467 12.187H22.6367C23.0467 12.187 23.3867 12.527 23.3867 12.937C23.3867 13.347 23.0467 13.687 22.6367 13.687H16.9467L18.6667 15.407C18.9567 15.697 18.9567 16.177 18.6667 16.467C18.5167 16.617 18.3267 16.687 18.1367 16.687C17.9467 16.687 17.7567 16.617 17.6067 16.467L14.6067 13.467C14.5367 13.397 14.4867 13.317 14.4467 13.227C14.4067 13.137 14.3867 13.047 14.3867 12.937C14.3867 12.827 14.4067 12.737 14.4467 12.647Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgArrowsInLineVertical);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "845229aae44285450c56363c8efc0945.svg");

/***/ }),

/***/ 94715:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ComponentXRayPanel-module__ComponentXRayPanel--mHZJQ{display:flex;flex-direction:column;height:100%;background-color:var(--theme-color-bg-1);color:var(--theme-color-fg-default);overflow:hidden}.ComponentXRayPanel-module__EmptyState--wE_pr{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:24px;text-align:center;color:var(--theme-color-fg-default-shy)}.ComponentXRayPanel-module__EmptyState--wE_pr h3{margin:16px 0 8px;font-size:16px;font-weight:500;color:var(--theme-color-fg-default)}.ComponentXRayPanel-module__EmptyState--wE_pr p{margin:0;font-size:13px}.ComponentXRayPanel-module__Header--bd8Jt{flex-shrink:0;padding:16px;border-bottom:1px solid var(--theme-color-border-default);background-color:var(--theme-color-bg-2)}.ComponentXRayPanel-module__Title--FNLao{display:flex;align-items:center;gap:8px;margin-bottom:12px}.ComponentXRayPanel-module__Title--FNLao h2{margin:0;font-size:14px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:var(--theme-color-fg-default-shy)}.ComponentXRayPanel-module__ComponentName--bkFHC{display:flex;align-items:center;gap:8px;padding:8px 12px;background-color:var(--theme-color-bg-3);border-radius:4px;font-size:14px;font-weight:500;color:var(--theme-color-fg-highlight)}.ComponentXRayPanel-module__Content--xAgld{flex:1;overflow-y:auto;padding:16px}.ComponentXRayPanel-module__SummaryStats--T4t1x{display:grid;grid-template-columns:repeat(2, 1fr);gap:12px;margin-bottom:24px}.ComponentXRayPanel-module__Stat--i4HlU{display:flex;flex-direction:column;padding:12px;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:4px}.ComponentXRayPanel-module__StatLabel--ZME9V{font-size:11px;text-transform:uppercase;letter-spacing:.5px;color:var(--theme-color-fg-default-shy);margin-bottom:4px}.ComponentXRayPanel-module__StatValue--gPQMB{font-size:20px;font-weight:600;color:var(--theme-color-fg-highlight)}.ComponentXRayPanel-module__Section--DERbG{margin-bottom:24px}.ComponentXRayPanel-module__SectionTitle--jhShV{display:flex;align-items:center;gap:8px;margin:0 0 12px;font-size:13px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:var(--theme-color-fg-default);cursor:pointer;user-select:none;transition:color .15s ease}.ComponentXRayPanel-module__SectionTitle--jhShV:hover{color:var(--theme-color-fg-highlight)}.ComponentXRayPanel-module__SectionContent--yV8Te{padding:12px;background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:4px}.ComponentXRayPanel-module__NoData--XBqjC{padding:12px;text-align:center;font-size:13px;font-style:italic;color:var(--theme-color-fg-default-shy);background-color:var(--theme-color-bg-2);border:1px solid var(--theme-color-border-default);border-radius:4px}.ComponentXRayPanel-module__UsageItem--BnRyF{display:flex;align-items:center;gap:8px;padding:8px;font-size:13px;color:var(--theme-color-fg-default);border-radius:3px;cursor:pointer;transition:all .15s ease;border-left:2px solid rgba(0,0,0,0)}.ComponentXRayPanel-module__UsageItem--BnRyF:hover{background-color:var(--theme-color-bg-4);color:var(--theme-color-fg-highlight);border-left-color:var(--theme-color-primary)}.ComponentXRayPanel-module__UsageItem--BnRyF:not(:last-child){margin-bottom:4px}.ComponentXRayPanel-module__InterfaceGrid--YNSlY{display:grid;grid-template-columns:1fr 1fr;gap:16px}.ComponentXRayPanel-module__InterfaceColumn--E_wCy h4{margin:0 0 8px;font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:var(--theme-color-fg-default-shy)}.ComponentXRayPanel-module__PortItem--LN8rp{display:flex;justify-content:space-between;align-items:center;padding:6px 8px;margin-bottom:4px;background-color:var(--theme-color-bg-3);border-radius:3px;font-size:12px}.ComponentXRayPanel-module__PortName--xZtvo{font-weight:500;color:var(--theme-color-fg-default)}.ComponentXRayPanel-module__PortType--kvKRH{font-size:11px;padding:2px 6px;background-color:var(--theme-color-bg-1);border-radius:2px;color:var(--theme-color-fg-default-shy)}.ComponentXRayPanel-module__Subsection--zk9NY:not(:last-child){margin-bottom:16px;padding-bottom:16px;border-bottom:1px solid var(--theme-color-border-default)}.ComponentXRayPanel-module__Subsection--zk9NY h4{margin:0 0 8px;font-size:12px;font-weight:600;color:var(--theme-color-fg-default)}.ComponentXRayPanel-module__SubcomponentItem--ksfYN{display:flex;align-items:center;gap:8px;padding:6px 8px;font-size:13px;color:var(--theme-color-fg-default);background-color:var(--theme-color-bg-3);border-radius:3px;cursor:pointer;transition:all .15s ease;border-left:2px solid rgba(0,0,0,0)}.ComponentXRayPanel-module__SubcomponentItem--ksfYN:hover{background-color:var(--theme-color-bg-4);color:var(--theme-color-fg-highlight);border-left-color:var(--theme-color-primary)}.ComponentXRayPanel-module__SubcomponentItem--ksfYN:not(:last-child){margin-bottom:4px}.ComponentXRayPanel-module__BreakdownItem--VPNxR{display:flex;justify-content:space-between;align-items:center;padding:6px 8px;margin-bottom:4px;background-color:var(--theme-color-bg-3);border-radius:3px;font-size:12px;cursor:pointer;transition:all .15s ease;border-left:2px solid rgba(0,0,0,0)}.ComponentXRayPanel-module__BreakdownItem--VPNxR:hover{background-color:var(--theme-color-bg-4);border-left-color:var(--theme-color-primary)}.ComponentXRayPanel-module__BreakdownItem--VPNxR:hover .ComponentXRayPanel-module__CategoryName--TUiWB{color:var(--theme-color-fg-highlight)}.ComponentXRayPanel-module__BreakdownItem--VPNxR.ComponentXRayPanel-module__active--C4F4P{background-color:var(--theme-color-bg-4);border-left-color:var(--theme-color-primary)}.ComponentXRayPanel-module__BreakdownItem--VPNxR.ComponentXRayPanel-module__active--C4F4P .ComponentXRayPanel-module__CategoryName--TUiWB{color:var(--theme-color-fg-highlight)}.ComponentXRayPanel-module__CategoryName--TUiWB{font-weight:500;color:var(--theme-color-fg-default);text-transform:capitalize}.ComponentXRayPanel-module__CategoryCount--ivwG2{font-weight:600;padding:2px 8px;background-color:var(--theme-color-bg-1);border-radius:2px;color:var(--theme-color-fg-highlight)}.ComponentXRayPanel-module__DependencyItem--DpXvg{display:flex;align-items:center;gap:8px;padding:6px 8px;margin-bottom:4px;background-color:var(--theme-color-bg-3);border-radius:3px;font-size:12px;cursor:pointer;transition:all .15s ease;border-left:2px solid rgba(0,0,0,0)}.ComponentXRayPanel-module__DependencyItem--DpXvg:hover{background-color:var(--theme-color-bg-4);border-left-color:var(--theme-color-primary)}.ComponentXRayPanel-module__DependencyItem--DpXvg:hover .ComponentXRayPanel-module__Endpoint--Hn3cX{color:var(--theme-color-fg-highlight)}.ComponentXRayPanel-module__Method--Cm0O2{font-weight:600;padding:2px 6px;background-color:var(--theme-color-primary);color:#fff;border-radius:2px;font-size:10px;text-transform:uppercase}.ComponentXRayPanel-module__Endpoint--Hn3cX{flex:1;color:var(--theme-color-fg-default);font-family:monospace;font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ComponentXRayPanel-module__EventItem--PocNb,.ComponentXRayPanel-module__FunctionItem--wxAAd{padding:6px 8px;margin-bottom:4px;background-color:var(--theme-color-bg-3);border-radius:3px;font-size:12px;color:var(--theme-color-fg-default);font-family:monospace;cursor:pointer;transition:all .15s ease;border-left:2px solid rgba(0,0,0,0)}.ComponentXRayPanel-module__EventItem--PocNb:hover,.ComponentXRayPanel-module__FunctionItem--wxAAd:hover{background-color:var(--theme-color-bg-4);color:var(--theme-color-fg-highlight);border-left-color:var(--theme-color-primary)}.ComponentXRayPanel-module__StateItem--HOlgD{display:flex;align-items:center;gap:8px;padding:6px 8px;margin-bottom:4px;background-color:var(--theme-color-bg-3);border-radius:3px;font-size:12px;cursor:pointer;transition:all .15s ease;border-left:2px solid rgba(0,0,0,0)}.ComponentXRayPanel-module__StateItem--HOlgD:hover{background-color:var(--theme-color-bg-4);border-left-color:var(--theme-color-primary)}.ComponentXRayPanel-module__StateItem--HOlgD:hover .ComponentXRayPanel-module__StateName--HpOQd{color:var(--theme-color-fg-highlight)}.ComponentXRayPanel-module__StateType--HKQ6K{font-weight:600;padding:2px 6px;background-color:var(--theme-color-bg-4);color:var(--theme-color-fg-default-shy);border-radius:2px;font-size:10px;text-transform:uppercase}.ComponentXRayPanel-module__StateName--HpOQd{color:var(--theme-color-fg-default);font-family:monospace}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/ComponentXRayPanel/ComponentXRayPanel.module.scss"],"names":[],"mappings":"AAMA,sDACE,YAAA,CACA,qBAAA,CACA,WAAA,CACA,wCAAA,CACA,mCAAA,CACA,eAAA,CAOF,8CACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,WAAA,CACA,YAAA,CACA,iBAAA,CACA,uCAAA,CAEA,iDACE,iBAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAGF,gDACE,QAAA,CACA,cAAA,CAQJ,0CACE,aAAA,CACA,YAAA,CACA,yDAAA,CACA,wCAAA,CAGF,yCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,kBAAA,CAEA,4CACE,QAAA,CACA,cAAA,CACA,eAAA,CACA,wBAAA,CACA,mBAAA,CACA,uCAAA,CAIJ,iDACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,gBAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,qCAAA,CAOF,2CACE,MAAA,CACA,eAAA,CACA,YAAA,CAOF,gDACE,YAAA,CACA,oCAAA,CACA,QAAA,CACA,kBAAA,CAGF,wCACE,YAAA,CACA,qBAAA,CACA,YAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CAGF,6CACE,cAAA,CACA,wBAAA,CACA,mBAAA,CACA,uCAAA,CACA,iBAAA,CAGF,6CACE,cAAA,CACA,eAAA,CACA,qCAAA,CAOF,2CACE,kBAAA,CAGF,gDACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,eAAA,CACA,cAAA,CACA,eAAA,CACA,wBAAA,CACA,mBAAA,CACA,mCAAA,CACA,cAAA,CACA,gBAAA,CACA,0BAAA,CAEA,sDACE,qCAAA,CAIJ,kDACE,YAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CAGF,0CACE,YAAA,CACA,iBAAA,CACA,cAAA,CACA,iBAAA,CACA,uCAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CAOF,6CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,WAAA,CACA,cAAA,CACA,mCAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CACA,mCAAA,CAEA,mDACE,wCAAA,CACA,qCAAA,CACA,4CAAA,CAGF,8DACE,iBAAA,CAQJ,iDACE,YAAA,CACA,6BAAA,CACA,QAAA,CAIA,sDACE,cAAA,CACA,cAAA,CACA,eAAA,CACA,wBAAA,CACA,mBAAA,CACA,uCAAA,CAIJ,4CACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,eAAA,CACA,iBAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CAGF,4CACE,eAAA,CACA,mCAAA,CAGF,4CACE,cAAA,CACA,eAAA,CACA,wCAAA,CACA,iBAAA,CACA,uCAAA,CAQA,+DACE,kBAAA,CACA,mBAAA,CACA,yDAAA,CAGF,iDACE,cAAA,CACA,cAAA,CACA,eAAA,CACA,mCAAA,CAQJ,oDACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,eAAA,CACA,cAAA,CACA,mCAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CACA,mCAAA,CAEA,0DACE,wCAAA,CACA,qCAAA,CACA,4CAAA,CAGF,qEACE,iBAAA,CAQJ,iDACE,YAAA,CACA,6BAAA,CACA,kBAAA,CACA,eAAA,CACA,iBAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,cAAA,CACA,wBAAA,CACA,mCAAA,CAEA,uDACE,wCAAA,CACA,4CAAA,CAEA,uGACE,qCAAA,CAIJ,0FACE,wCAAA,CACA,4CAAA,CAEA,0IACE,qCAAA,CAKN,gDACE,eAAA,CACA,mCAAA,CACA,yBAAA,CAGF,iDACE,eAAA,CACA,eAAA,CACA,wCAAA,CACA,iBAAA,CACA,qCAAA,CAOF,kDACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,eAAA,CACA,iBAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,cAAA,CACA,wBAAA,CACA,mCAAA,CAEA,wDACE,wCAAA,CACA,4CAAA,CAEA,oGACE,qCAAA,CAKN,0CACE,eAAA,CACA,eAAA,CACA,2CAAA,CACA,UAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CAGF,4CACE,MAAA,CACA,mCAAA,CACA,qBAAA,CACA,cAAA,CACA,eAAA,CACA,sBAAA,CACA,kBAAA,CAGF,6FAEE,eAAA,CACA,iBAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,mCAAA,CACA,qBAAA,CACA,cAAA,CACA,wBAAA,CACA,mCAAA,CAEA,yGACE,wCAAA,CACA,qCAAA,CACA,4CAAA,CAQJ,6CACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,eAAA,CACA,iBAAA,CACA,wCAAA,CACA,iBAAA,CACA,cAAA,CACA,cAAA,CACA,wBAAA,CACA,mCAAA,CAEA,mDACE,wCAAA,CACA,4CAAA,CAEA,gGACE,qCAAA,CAKN,6CACE,eAAA,CACA,eAAA,CACA,wCAAA,CACA,uCAAA,CACA,iBAAA,CACA,cAAA,CACA,wBAAA,CAGF,6CACE,mCAAA,CACA,qBAAA","sourcesContent":["/**\n * Component X-Ray Panel Styles\n *\n * Uses design tokens from UI-STYLING-GUIDE.md\n */\n\n.ComponentXRayPanel {\n  display: flex;\n  flex-direction: column;\n  height: 100%;\n  background-color: var(--theme-color-bg-1);\n  color: var(--theme-color-fg-default);\n  overflow: hidden;\n}\n\n/* =================================================================\n   Empty State\n   ================================================================= */\n\n.EmptyState {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  height: 100%;\n  padding: 24px;\n  text-align: center;\n  color: var(--theme-color-fg-default-shy);\n\n  h3 {\n    margin: 16px 0 8px;\n    font-size: 16px;\n    font-weight: 500;\n    color: var(--theme-color-fg-default);\n  }\n\n  p {\n    margin: 0;\n    font-size: 13px;\n  }\n}\n\n/* =================================================================\n   Header\n   ================================================================= */\n\n.Header {\n  flex-shrink: 0;\n  padding: 16px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  background-color: var(--theme-color-bg-2);\n}\n\n.Title {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin-bottom: 12px;\n\n  h2 {\n    margin: 0;\n    font-size: 14px;\n    font-weight: 600;\n    text-transform: uppercase;\n    letter-spacing: 0.5px;\n    color: var(--theme-color-fg-default-shy);\n  }\n}\n\n.ComponentName {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 8px 12px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 4px;\n  font-size: 14px;\n  font-weight: 500;\n  color: var(--theme-color-fg-highlight);\n}\n\n/* =================================================================\n   Content - Scrollable Area\n   ================================================================= */\n\n.Content {\n  flex: 1;\n  overflow-y: auto;\n  padding: 16px;\n}\n\n/* =================================================================\n   Summary Stats\n   ================================================================= */\n\n.SummaryStats {\n  display: grid;\n  grid-template-columns: repeat(2, 1fr);\n  gap: 12px;\n  margin-bottom: 24px;\n}\n\n.Stat {\n  display: flex;\n  flex-direction: column;\n  padding: 12px;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n}\n\n.StatLabel {\n  font-size: 11px;\n  text-transform: uppercase;\n  letter-spacing: 0.5px;\n  color: var(--theme-color-fg-default-shy);\n  margin-bottom: 4px;\n}\n\n.StatValue {\n  font-size: 20px;\n  font-weight: 600;\n  color: var(--theme-color-fg-highlight);\n}\n\n/* =================================================================\n   Sections\n   ================================================================= */\n\n.Section {\n  margin-bottom: 24px;\n}\n\n.SectionTitle {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  margin: 0 0 12px;\n  font-size: 13px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.5px;\n  color: var(--theme-color-fg-default);\n  cursor: pointer;\n  user-select: none;\n  transition: color 0.15s ease;\n\n  &:hover {\n    color: var(--theme-color-fg-highlight);\n  }\n}\n\n.SectionContent {\n  padding: 12px;\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n}\n\n.NoData {\n  padding: 12px;\n  text-align: center;\n  font-size: 13px;\n  font-style: italic;\n  color: var(--theme-color-fg-default-shy);\n  background-color: var(--theme-color-bg-2);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n}\n\n/* =================================================================\n   Usage Items\n   ================================================================= */\n\n.UsageItem {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 8px;\n  font-size: 13px;\n  color: var(--theme-color-fg-default);\n  border-radius: 3px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n  border-left: 2px solid transparent;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    color: var(--theme-color-fg-highlight);\n    border-left-color: var(--theme-color-primary);\n  }\n\n  &:not(:last-child) {\n    margin-bottom: 4px;\n  }\n}\n\n/* =================================================================\n   Interface Grid\n   ================================================================= */\n\n.InterfaceGrid {\n  display: grid;\n  grid-template-columns: 1fr 1fr;\n  gap: 16px;\n}\n\n.InterfaceColumn {\n  h4 {\n    margin: 0 0 8px;\n    font-size: 12px;\n    font-weight: 600;\n    text-transform: uppercase;\n    letter-spacing: 0.5px;\n    color: var(--theme-color-fg-default-shy);\n  }\n}\n\n.PortItem {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 6px 8px;\n  margin-bottom: 4px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 3px;\n  font-size: 12px;\n}\n\n.PortName {\n  font-weight: 500;\n  color: var(--theme-color-fg-default);\n}\n\n.PortType {\n  font-size: 11px;\n  padding: 2px 6px;\n  background-color: var(--theme-color-bg-1);\n  border-radius: 2px;\n  color: var(--theme-color-fg-default-shy);\n}\n\n/* =================================================================\n   Subsections\n   ================================================================= */\n\n.Subsection {\n  &:not(:last-child) {\n    margin-bottom: 16px;\n    padding-bottom: 16px;\n    border-bottom: 1px solid var(--theme-color-border-default);\n  }\n\n  h4 {\n    margin: 0 0 8px;\n    font-size: 12px;\n    font-weight: 600;\n    color: var(--theme-color-fg-default);\n  }\n}\n\n/* =================================================================\n   Subcomponent Items\n   ================================================================= */\n\n.SubcomponentItem {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 6px 8px;\n  font-size: 13px;\n  color: var(--theme-color-fg-default);\n  background-color: var(--theme-color-bg-3);\n  border-radius: 3px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n  border-left: 2px solid transparent;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    color: var(--theme-color-fg-highlight);\n    border-left-color: var(--theme-color-primary);\n  }\n\n  &:not(:last-child) {\n    margin-bottom: 4px;\n  }\n}\n\n/* =================================================================\n   Node Breakdown\n   ================================================================= */\n\n.BreakdownItem {\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  padding: 6px 8px;\n  margin-bottom: 4px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 3px;\n  font-size: 12px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n  border-left: 2px solid transparent;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    border-left-color: var(--theme-color-primary);\n\n    .CategoryName {\n      color: var(--theme-color-fg-highlight);\n    }\n  }\n\n  &.active {\n    background-color: var(--theme-color-bg-4);\n    border-left-color: var(--theme-color-primary);\n\n    .CategoryName {\n      color: var(--theme-color-fg-highlight);\n    }\n  }\n}\n\n.CategoryName {\n  font-weight: 500;\n  color: var(--theme-color-fg-default);\n  text-transform: capitalize;\n}\n\n.CategoryCount {\n  font-weight: 600;\n  padding: 2px 8px;\n  background-color: var(--theme-color-bg-1);\n  border-radius: 2px;\n  color: var(--theme-color-fg-highlight);\n}\n\n/* =================================================================\n   External Dependencies\n   ================================================================= */\n\n.DependencyItem {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 6px 8px;\n  margin-bottom: 4px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 3px;\n  font-size: 12px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n  border-left: 2px solid transparent;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    border-left-color: var(--theme-color-primary);\n\n    .Endpoint {\n      color: var(--theme-color-fg-highlight);\n    }\n  }\n}\n\n.Method {\n  font-weight: 600;\n  padding: 2px 6px;\n  background-color: var(--theme-color-primary);\n  color: white;\n  border-radius: 2px;\n  font-size: 10px;\n  text-transform: uppercase;\n}\n\n.Endpoint {\n  flex: 1;\n  color: var(--theme-color-fg-default);\n  font-family: monospace;\n  font-size: 11px;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n.EventItem,\n.FunctionItem {\n  padding: 6px 8px;\n  margin-bottom: 4px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 3px;\n  font-size: 12px;\n  color: var(--theme-color-fg-default);\n  font-family: monospace;\n  cursor: pointer;\n  transition: all 0.15s ease;\n  border-left: 2px solid transparent;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    color: var(--theme-color-fg-highlight);\n    border-left-color: var(--theme-color-primary);\n  }\n}\n\n/* =================================================================\n   Internal State\n   ================================================================= */\n\n.StateItem {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 6px 8px;\n  margin-bottom: 4px;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 3px;\n  font-size: 12px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n  border-left: 2px solid transparent;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    border-left-color: var(--theme-color-primary);\n\n    .StateName {\n      color: var(--theme-color-fg-highlight);\n    }\n  }\n}\n\n.StateType {\n  font-weight: 600;\n  padding: 2px 6px;\n  background-color: var(--theme-color-bg-4);\n  color: var(--theme-color-fg-default-shy);\n  border-radius: 2px;\n  font-size: 10px;\n  text-transform: uppercase;\n}\n\n.StateName {\n  color: var(--theme-color-fg-default);\n  font-family: monospace;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"ComponentXRayPanel": `ComponentXRayPanel-module__ComponentXRayPanel--mHZJQ`,
	"EmptyState": `ComponentXRayPanel-module__EmptyState--wE_pr`,
	"Header": `ComponentXRayPanel-module__Header--bd8Jt`,
	"Title": `ComponentXRayPanel-module__Title--FNLao`,
	"ComponentName": `ComponentXRayPanel-module__ComponentName--bkFHC`,
	"Content": `ComponentXRayPanel-module__Content--xAgld`,
	"SummaryStats": `ComponentXRayPanel-module__SummaryStats--T4t1x`,
	"Stat": `ComponentXRayPanel-module__Stat--i4HlU`,
	"StatLabel": `ComponentXRayPanel-module__StatLabel--ZME9V`,
	"StatValue": `ComponentXRayPanel-module__StatValue--gPQMB`,
	"Section": `ComponentXRayPanel-module__Section--DERbG`,
	"SectionTitle": `ComponentXRayPanel-module__SectionTitle--jhShV`,
	"SectionContent": `ComponentXRayPanel-module__SectionContent--yV8Te`,
	"NoData": `ComponentXRayPanel-module__NoData--XBqjC`,
	"UsageItem": `ComponentXRayPanel-module__UsageItem--BnRyF`,
	"InterfaceGrid": `ComponentXRayPanel-module__InterfaceGrid--YNSlY`,
	"InterfaceColumn": `ComponentXRayPanel-module__InterfaceColumn--E_wCy`,
	"PortItem": `ComponentXRayPanel-module__PortItem--LN8rp`,
	"PortName": `ComponentXRayPanel-module__PortName--xZtvo`,
	"PortType": `ComponentXRayPanel-module__PortType--kvKRH`,
	"Subsection": `ComponentXRayPanel-module__Subsection--zk9NY`,
	"SubcomponentItem": `ComponentXRayPanel-module__SubcomponentItem--ksfYN`,
	"BreakdownItem": `ComponentXRayPanel-module__BreakdownItem--VPNxR`,
	"CategoryName": `ComponentXRayPanel-module__CategoryName--TUiWB`,
	"active": `ComponentXRayPanel-module__active--C4F4P`,
	"CategoryCount": `ComponentXRayPanel-module__CategoryCount--ivwG2`,
	"DependencyItem": `ComponentXRayPanel-module__DependencyItem--DpXvg`,
	"Endpoint": `ComponentXRayPanel-module__Endpoint--Hn3cX`,
	"Method": `ComponentXRayPanel-module__Method--Cm0O2`,
	"EventItem": `ComponentXRayPanel-module__EventItem--PocNb`,
	"FunctionItem": `ComponentXRayPanel-module__FunctionItem--wxAAd`,
	"StateItem": `ComponentXRayPanel-module__StateItem--HOlgD`,
	"StateName": `ComponentXRayPanel-module__StateName--HpOQd`,
	"StateType": `ComponentXRayPanel-module__StateType--HKQ6K`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 94755:
/***/ ((module) => {

const NavigationModeMouse = 'mouse';
const NavigationModeTouchPad = 'touchpad';

class MouseWheelModeDetector {
  constructor() {
    this.firstWheelDeltaYInTimeFrame = null;
    this.endTimeFrame = this.endTimeFrameHandler.bind(this);
    this.mode = NavigationModeMouse;
  }

  dispose() {
    clearTimeout(this.checkTimeFrameEndedID);
  }

  changeMode(e) {
    this.startTimeFrame();
    this.mode = this.getModeByWheelEvent(e);
    return this.mode;
  }

  startTimeFrame() {
    this.startFrameTime = Date.now();
    clearTimeout(this.checkTimeFrameEndedID);
    this.checkTimeFrameEndedID = setTimeout(this.endTimeFrame, 100);
  }

  endTimeFrameHandler() {
    this.startFrameTime = 0;
    this.firstWheelDeltaYInTimeFrame = null;
  }

  getModeByWheelEvent(e) {
    var t = this.mode;
    switch (t) {
      case NavigationModeMouse:
        return this.detectTouchpad(e) ? NavigationModeTouchPad : t;
      case NavigationModeTouchPad:
        return this.detectMouse(e) ? NavigationModeMouse : t;
      default:
        return t;
    }
  }

  detectMouse(e) {
    //panning events from a trackpad always have ctrlKey set to true. Just assume it's a trackpad
    if (e.ctrlKey) {
      return false;
    }

    if (e.wheelDeltaY !== 0 && e.wheelDeltaY !== null && this.firstWheelDeltaYInTimeFrame === null) {
      this.firstWheelDeltaYInTimeFrame = Math.abs(e.wheelDeltaY);

      //after some testing it appears that mice always report a deltaY of 120, 240 etc in the very first wheel event.
      //Trackpads are more "smooth" with lower values.
      const mouseDetected = this.firstWheelDeltaYInTimeFrame % 120 === 0;
      return mouseDetected;
    }

    return false;
  }

  detectTouchpad(e) {
    //panning events from a trackpad always have ctrlKey set to true. Just assume it's a trackpad
    if (e.ctrlKey) {
      return true;
    }

    if (e.deltaX === 0 || e.shiftKey) {
      return false;
    }

    return true;
  }
}

module.exports = MouseWheelModeDetector;


/***/ }),

/***/ 95162:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRadiobuttonGroup = function SvgRadiobuttonGroup(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M15.0536 25.6553C17.2185 25.6553 18.9735 23.9003 18.9735 21.7354C18.9735 19.5705 17.2185 17.8154 15.0536 17.8154C12.8887 17.8154 11.1337 19.5705 11.1337 21.7354C11.1337 23.9003 12.8887 25.6553 15.0536 25.6553ZM20.5266 21.7354C20.5266 24.758 18.0763 27.2084 15.0536 27.2084C12.0309 27.2084 9.58057 24.758 9.58057 21.7354C9.58057 18.7127 12.0309 16.2623 15.0536 16.2623C18.0763 16.2623 20.5266 18.7127 20.5266 21.7354Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M15.0535 22.9509C15.7249 22.9509 16.2692 22.4067 16.2692 21.7353C16.2692 21.0639 15.7249 20.5197 15.0535 20.5197C14.3822 20.5197 13.8379 21.0639 13.8379 21.7353C13.8379 22.4067 14.3822 22.9509 15.0535 22.9509Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M15.06 13.1048C17.2256 13.1048 18.9813 11.3492 18.9813 9.1835C18.9813 7.01781 17.2256 5.26217 15.06 5.26217C12.8943 5.26217 11.1386 7.01781 11.1386 9.1835C11.1386 11.3492 12.8943 13.1048 15.06 13.1048ZM20.535 9.1835C20.535 12.2073 18.0837 14.6585 15.06 14.6585C12.0362 14.6585 9.58496 12.2073 9.58496 9.1835C9.58496 6.15974 12.0362 3.7085 15.06 3.7085C18.0837 3.7085 20.535 6.15974 20.535 9.1835Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRadiobuttonGroup);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "88a9788bd53db728db9be97637ecc084.svg");

/***/ }),

/***/ 95184:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCircleOpen = function SvgCircleOpen(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M18.2969 5.8189C18.1876 6.37096 17.6515 6.72993 17.0995 6.62068C15.0525 6.21559 12.9286 6.52271 11.0802 7.49106C9.23182 8.45941 7.7702 10.0308 6.93794 11.9443C6.10568 13.8578 5.95284 15.9983 6.50477 18.0107C7.05671 20.023 8.28024 21.7861 9.97226 23.0072C11.6643 24.2284 13.723 24.8342 15.8068 24.724C17.8905 24.6139 19.874 23.7945 21.4278 22.4018C22.9817 21.009 24.0126 19.1268 24.3493 17.0675C24.5646 15.7505 24.4878 14.4117 24.1352 13.1428C23.9845 12.6006 24.3019 12.0389 24.8441 11.8882C25.3863 11.7375 25.948 12.0549 26.0987 12.5971C26.5299 14.1487 26.6239 15.7858 26.3605 17.3964C25.9488 19.9146 24.6882 22.2163 22.788 23.9194C20.8879 25.6224 18.4625 26.6245 15.9144 26.7592C13.3662 26.8938 10.8487 26.1531 8.77961 24.6598C6.71052 23.1665 5.21433 21.0105 4.53939 18.5497C3.86446 16.0889 4.05136 13.4713 5.06909 11.1314C6.08682 8.79149 7.87417 6.86998 10.1344 5.68583C12.3947 4.50169 14.992 4.12613 17.4951 4.62149C18.0472 4.73074 18.4061 5.26684 18.2969 5.8189Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCircleOpen);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "90734839eac6fcfe4832bae96784abc5.svg");

/***/ }),

/***/ 95219:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ConnectionPopup-module__listElement--FnUNc.ConnectionPopup-module__selected--yAX3R::before,.ConnectionPopup-module__selected--yAX3R.ConnectionPopup-module__listElementPort--Y5Y3U::before,.ConnectionPopup-module__bar--hQR3X.ConnectionPopup-module__disabled--yqA80::after{content:"";position:absolute;top:0;left:0;right:0;bottom:0}.ConnectionPopup-module__signalIcon--IggGl{content:url("../assets/icons/flash.svg");width:15px;height:15px;margin-right:3px}.ConnectionPopup-module__popup--YmyCQ{width:200px;height:400px;outline:2px solid var(--theme-color-bg-3);background-color:var(--theme-color-bg-2);display:flex;flex-direction:column;position:relative}.ConnectionPopup-module__popupHeader--EKZqM{padding:12px 16px;color:var(--theme-color-fg-highlight);background-color:var(--theme-color-bg-3);padding-left:10px;padding-right:10px;font-weight:var(--font-weight-semibold);position:relative}.ConnectionPopup-module__popupHeader--EKZqM.ConnectionPopup-module__disabled--yqA80{color:hsla(0,0%,100%,.5)}.ConnectionPopup-module__popupScroll--KtAuC{background-color:var(--theme-color-bg-2);padding:2px;margin-right:2px;display:flex;flex-direction:column;overflow:hidden auto;position:relative;flex-grow:1}.ConnectionPopup-module__popupScroll--KtAuC::-webkit-scrollbar{width:2px;background-color:var(--theme-color-bg-2)}.ConnectionPopup-module__popupScroll--KtAuC::-webkit-scrollbar-thumb{background-color:var(--theme-color-fg-muted)}.ConnectionPopup-module__bar--hQR3X{flex-grow:1;width:100%;position:relative}.ConnectionPopup-module__bar--hQR3X.ConnectionPopup-module__disabled--yqA80::after{background-color:rgba(0,0,0,.4)}.ConnectionPopup-module__noPortsMessage--rVpJp{padding:10px;color:var(--theme-color-fg-default-contrast)}.ConnectionPopup-module__listElement--FnUNc,.ConnectionPopup-module__listElementPort--Y5Y3U{font-size:12px;padding:5px 10px 5px 10px;display:flex;align-items:center;position:relative}.ConnectionPopup-module__listElement--FnUNc.ConnectionPopup-module__enabled--cokJQ,.ConnectionPopup-module__enabled--cokJQ.ConnectionPopup-module__listElementPort--Y5Y3U{cursor:pointer}.ConnectionPopup-module__listElement--FnUNc.ConnectionPopup-module__enabled--cokJQ:hover,.ConnectionPopup-module__enabled--cokJQ.ConnectionPopup-module__listElementPort--Y5Y3U:hover{color:var(--theme-color-fg-highlight)}.ConnectionPopup-module__listElement--FnUNc.ConnectionPopup-module__enabled--cokJQ:hover .ConnectionPopup-module__signalIcon--IggGl,.ConnectionPopup-module__enabled--cokJQ.ConnectionPopup-module__listElementPort--Y5Y3U:hover .ConnectionPopup-module__signalIcon--IggGl{opacity:1}.ConnectionPopup-module__listElement--FnUNc.ConnectionPopup-module__disabled--yqA80,.ConnectionPopup-module__disabled--yqA80.ConnectionPopup-module__listElementPort--Y5Y3U{color:hsla(0,0%,100%,.25)}.ConnectionPopup-module__listElement--FnUNc.ConnectionPopup-module__disabled--yqA80 .ConnectionPopup-module__signalIcon--IggGl,.ConnectionPopup-module__disabled--yqA80.ConnectionPopup-module__listElementPort--Y5Y3U .ConnectionPopup-module__signalIcon--IggGl{opacity:.3}.ConnectionPopup-module__listElement--FnUNc.ConnectionPopup-module__selected--yAX3R,.ConnectionPopup-module__selected--yAX3R.ConnectionPopup-module__listElementPort--Y5Y3U{color:var(--theme-color-fg-highlight)}.ConnectionPopup-module__listElement--FnUNc.ConnectionPopup-module__selected--yAX3R::before,.ConnectionPopup-module__selected--yAX3R.ConnectionPopup-module__listElementPort--Y5Y3U::before{background-color:hsla(0,0%,100%,.2)}.ConnectionPopup-module__listElementPort--Y5Y3U{color:var(--theme-color-fg-highlight);opacity:.7}.ConnectionPopup-module__listElementPort--Y5Y3U.ConnectionPopup-module__enabled--cokJQ:hover{background-color:var(--local--port-hover-color)}.ConnectionPopup-module__listElementPort--Y5Y3U .ConnectionPopup-module__signalIcon--IggGl{opacity:.75}.ConnectionPopup-module__listElementGroup--FBP7N{font-size:12px;padding:5px 10px 5px 10px;display:flex;align-items:center;position:relative;color:hsla(0,0%,100%,.67)}.ConnectionPopup-module__groupLabel--Xupas{flex-grow:1}.ConnectionPopup-module__docs--NgoJx{height:300px;margin-top:2px}.ConnectionPopup-module__docsPopup--n3v62{width:300px;background-color:var(--theme-color-bg-2);padding:10px;color:var(--theme-color-fg-highlight)}.ConnectionPopup-module__docsType--Nu8TN{margin-left:5px;color:var(--theme-color-primary)}.ConnectionPopup-module__docsHeader--oCm12{margin-bottom:5px}.ConnectionPopup-module__docsBody--ZnrA1{color:var(--theme-color-fg-default-contrast)}.ConnectionPopup-module__docsEnumValue--YSNSF{margin-left:5px;margin-right:5px}.ConnectionPopup-module__searchContainer--sQQGK{display:flex;align-items:center;padding:8px 0 8px 8px}.ConnectionPopup-module__searchInput--TksQy{border:none;background-color:rgba(0,0,0,0);font-size:12px}.ConnectionPopup-module__searchInput--TksQy,.ConnectionPopup-module__searchInput--TksQy::placeholder{color:hsla(0,0%,100%,.6)}.ConnectionPopup-module__searchIcon--hAymk{opacity:.6}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/ConnectionPopup/ConnectionPopup.module.scss"],"names":[],"mappings":"AAEA,+QACE,UAAA,CACA,iBAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CAGF,2CACE,wCAAA,CACA,UAAA,CACA,WAAA,CACA,gBAAA,CAGF,sCACE,WAAA,CACA,YAAA,CACA,yCAAA,CACA,wCAAA,CACA,YAAA,CACA,qBAAA,CACA,iBAAA,CAGF,4CACE,iBAAA,CACA,qCAAA,CACA,wCAAA,CACA,iBAAA,CACA,kBAAA,CACA,uCAAA,CACA,iBAAA,CAEA,oFACE,wBAAA,CAIJ,4CACE,wCAAA,CACA,WAAA,CACA,gBAAA,CACA,YAAA,CACA,qBAAA,CACA,oBAAA,CACA,iBAAA,CACA,WAAA,CAEA,+DACE,SAAA,CACA,wCAAA,CAGF,qEACE,4CAAA,CAIJ,oCACE,WAAA,CACA,UAAA,CACA,iBAAA,CAEA,mFAEE,+BAAA,CAIJ,+CACE,YAAA,CACA,4CAAA,CAGF,4FACE,cAAA,CACA,yBAAA,CACA,YAAA,CACA,kBAAA,CACA,iBAAA,CAEA,0KACE,cAAA,CAEA,sLACE,qCAAA,CAGF,4QACE,SAAA,CAIJ,4KACE,yBAAA,CAEA,kQACE,UAAA,CAIJ,4KACE,qCAAA,CAEA,4LAEE,mCAAA,CAKN,gDAGE,qCAAA,CACA,UAAA,CAEA,6FACE,+CAAA,CAGF,2FACE,WAAA,CAIJ,iDACE,cAAA,CACA,yBAAA,CACA,YAAA,CACA,kBAAA,CACA,iBAAA,CACA,yBAAA,CAGF,2CACE,WAAA,CAGF,qCACE,YAAA,CACA,cAAA,CAGF,0CACE,WAAA,CACA,wCAAA,CACA,YAAA,CACA,qCAAA,CAGF,yCACE,eAAA,CACA,gCAAA,CAGF,2CACE,iBAAA,CAGF,yCACE,4CAAA,CAGF,8CACE,eAAA,CACA,gBAAA,CAGF,gDACE,YAAA,CACA,kBAAA,CACA,qBAAA,CAGF,4CACE,WAAA,CACA,8BAAA,CACA,cAAA,CAEA,qGAEE,wBAAA,CAIJ,2CACE,UAAA","sourcesContent":["@use '@scss-variables/color';\n\n%overlay {\n  content: '';\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n}\n\n.signalIcon {\n  content: url('../assets/icons/flash.svg');\n  width: 15px;\n  height: 15px;\n  margin-right: 3px;\n}\n\n.popup {\n  width: 200px;\n  height: 400px;\n  outline: 2px solid var(--theme-color-bg-3);\n  background-color: var(--theme-color-bg-2);\n  display: flex;\n  flex-direction: column;\n  position: relative;\n}\n\n.popupHeader {\n  padding: 12px 16px;\n  color: var(--theme-color-fg-highlight);\n  background-color: var(--theme-color-bg-3);\n  padding-left: 10px;\n  padding-right: 10px;\n  font-weight: var(--font-weight-semibold);\n  position: relative;\n\n  &.disabled {\n    color: rgba(255, 255, 255, 0.5);\n  }\n}\n\n.popupScroll {\n  background-color: var(--theme-color-bg-2);\n  padding: 2px;\n  margin-right: 2px;\n  display: flex;\n  flex-direction: column;\n  overflow: hidden auto;\n  position: relative;\n  flex-grow: 1;\n\n  &::-webkit-scrollbar {\n    width: 2px;\n    background-color: var(--theme-color-bg-2);\n  }\n\n  &::-webkit-scrollbar-thumb {\n    background-color: var(--theme-color-fg-muted);\n  }\n}\n\n.bar {\n  flex-grow: 1;\n  width: 100%;\n  position: relative;\n\n  &.disabled::after {\n    @extend %overlay;\n    background-color: rgba(0, 0, 0, 0.4);\n  }\n}\n\n.noPortsMessage {\n  padding: 10px;\n  color: var(--theme-color-fg-default-contrast);\n}\n\n.listElement {\n  font-size: 12px;\n  padding: 5px 10px 5px 10px;\n  display: flex;\n  align-items: center;\n  position: relative;\n\n  &.enabled {\n    cursor: pointer;\n\n    &:hover {\n      color: var(--theme-color-fg-highlight);\n    }\n\n    &:hover .signalIcon {\n      opacity: 1;\n    }\n  }\n\n  &.disabled {\n    color: rgba(255, 255, 255, 0.25);\n\n    .signalIcon {\n      opacity: 0.3;\n    }\n  }\n\n  &.selected {\n    color: var(--theme-color-fg-highlight);\n\n    &::before {\n      @extend %overlay;\n      background-color: rgba(255, 255, 255, 0.2);\n    }\n  }\n}\n\n.listElementPort {\n  @extend .listElement;\n  //background-color: #ffffff33;\n  color: var(--theme-color-fg-highlight);\n  opacity: 0.7;\n\n  &.enabled:hover {\n    background-color: var(--local--port-hover-color);\n  }\n\n  .signalIcon {\n    opacity: 0.75;\n  }\n}\n\n.listElementGroup {\n  font-size: 12px;\n  padding: 5px 10px 5px 10px;\n  display: flex;\n  align-items: center;\n  position: relative;\n  color: rgba(255, 255, 255, 0.67);\n}\n\n.groupLabel {\n  flex-grow: 1;\n}\n\n.docs {\n  height: 300px;\n  margin-top: 2px;\n}\n\n.docsPopup {\n  width: 300px;\n  background-color: var(--theme-color-bg-2);\n  padding: 10px;\n  color: var(--theme-color-fg-highlight);\n}\n\n.docsType {\n  margin-left: 5px;\n  color: var(--theme-color-primary);\n}\n\n.docsHeader {\n  margin-bottom: 5px;\n}\n\n.docsBody {\n  color: var(--theme-color-fg-default-contrast);\n}\n\n.docsEnumValue {\n  margin-left: 5px;\n  margin-right: 5px;\n}\n\n.searchContainer {\n  display: flex;\n  align-items: center;\n  padding: 8px 0 8px 8px;\n}\n\n.searchInput {\n  border: none;\n  background-color: transparent;\n  font-size: 12px;\n\n  &,\n  &::placeholder {\n    color: rgba(255, 255, 255, 0.6);\n  }\n}\n\n.searchIcon {\n  opacity: 0.6;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"listElement": `ConnectionPopup-module__listElement--FnUNc`,
	"selected": `ConnectionPopup-module__selected--yAX3R`,
	"listElementPort": `ConnectionPopup-module__listElementPort--Y5Y3U`,
	"bar": `ConnectionPopup-module__bar--hQR3X`,
	"disabled": `ConnectionPopup-module__disabled--yqA80`,
	"signalIcon": `ConnectionPopup-module__signalIcon--IggGl`,
	"popup": `ConnectionPopup-module__popup--YmyCQ`,
	"popupHeader": `ConnectionPopup-module__popupHeader--EKZqM`,
	"popupScroll": `ConnectionPopup-module__popupScroll--KtAuC`,
	"noPortsMessage": `ConnectionPopup-module__noPortsMessage--rVpJp`,
	"enabled": `ConnectionPopup-module__enabled--cokJQ`,
	"listElementGroup": `ConnectionPopup-module__listElementGroup--FBP7N`,
	"groupLabel": `ConnectionPopup-module__groupLabel--Xupas`,
	"docs": `ConnectionPopup-module__docs--NgoJx`,
	"docsPopup": `ConnectionPopup-module__docsPopup--n3v62`,
	"docsType": `ConnectionPopup-module__docsType--Nu8TN`,
	"docsHeader": `ConnectionPopup-module__docsHeader--oCm12`,
	"docsBody": `ConnectionPopup-module__docsBody--ZnrA1`,
	"docsEnumValue": `ConnectionPopup-module__docsEnumValue--YSNSF`,
	"searchContainer": `ConnectionPopup-module__searchContainer--sQQGK`,
	"searchInput": `ConnectionPopup-module__searchInput--TksQy`,
	"searchIcon": `ConnectionPopup-module__searchIcon--hAymk`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 95475:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2, _path3, _path4, _path5, _path6, _path7, _path8, _path9, _path0;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgRoundedCornerLeftDown = function SvgRoundedCornerLeftDown(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 31,
    height: 31,
    viewBox: "0 0 31 31",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.3335 25.6045C26.3335 25.1903 25.9977 24.8545 25.5835 24.8545C25.1693 24.8545 24.8335 25.1903 24.8335 25.6045C24.8335 26.0187 25.1693 26.3545 25.5835 26.3545C25.9977 26.3545 26.3335 26.0187 26.3335 25.6045Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.3335 11.8628C26.3335 11.4486 25.9977 11.1128 25.5835 11.1128C25.1693 11.1128 24.8335 11.4486 24.8335 11.8628C24.8335 12.277 25.1693 12.6128 25.5835 12.6128C25.9977 12.6128 26.3335 12.277 26.3335 11.8628Z",
    fill: "#F5F5F5"
  })), _path3 || (_path3 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M5.43994 11.8628C5.43994 11.4486 5.10415 11.1128 4.68994 11.1128C4.27573 11.1128 3.93994 11.4486 3.93994 11.8628C3.93994 12.277 4.27573 12.6128 4.68994 12.6128C5.10415 12.6128 5.43994 12.277 5.43994 11.8628Z",
    fill: "#F5F5F5"
  })), _path4 || (_path4 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.3335 18.7339C26.3335 18.3197 25.9977 17.9839 25.5835 17.9839C25.1693 17.9839 24.8335 18.3197 24.8335 18.7339C24.8335 19.1481 25.1693 19.4839 25.5835 19.4839C25.9977 19.4839 26.3335 19.1481 26.3335 18.7339Z",
    fill: "#F5F5F5"
  })), _path5 || (_path5 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M26.3335 4.9917C26.3335 4.57749 25.9977 4.2417 25.5835 4.2417C25.1693 4.2417 24.8335 4.57749 24.8335 4.9917C24.8335 5.40591 25.1693 5.7417 25.5835 5.7417C25.9977 5.7417 26.3335 5.40591 26.3335 4.9917Z",
    fill: "#F5F5F5"
  })), _path6 || (_path6 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M12.5913 4.9917C12.5913 4.57749 12.2555 4.2417 11.8413 4.2417C11.4271 4.2417 11.0913 4.57749 11.0913 4.9917C11.0913 5.40591 11.4271 5.7417 11.8413 5.7417C12.2555 5.7417 12.5913 5.40591 12.5913 4.9917Z",
    fill: "#F5F5F5"
  })), _path7 || (_path7 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M19.4624 4.9917C19.4624 4.57749 19.1266 4.2417 18.7124 4.2417C18.2982 4.2417 17.9624 4.57749 17.9624 4.9917C17.9624 5.40591 18.2982 5.7417 18.7124 5.7417C19.1266 5.7417 19.4624 5.40591 19.4624 4.9917Z",
    fill: "#F5F5F5"
  })), _path8 || (_path8 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M19.4624 25.6045C19.4624 25.1903 19.1266 24.8545 18.7124 24.8545C18.2982 24.8545 17.9624 25.1903 17.9624 25.6045C17.9624 26.0187 18.2982 26.3545 18.7124 26.3545C19.1266 26.3545 19.4624 26.0187 19.4624 25.6045Z",
    fill: "#F5F5F5"
  })), _path9 || (_path9 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M5.72021 4.9917C5.72021 4.57749 5.38443 4.2417 4.97021 4.2417C4.556 4.2417 4.22021 4.57749 4.22021 4.9917C4.22021 5.40591 4.556 5.7417 4.97021 5.7417C5.38443 5.7417 5.72021 5.40591 5.72021 4.9917Z",
    fill: "#F5F5F5"
  })), _path0 || (_path0 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M5.72021 18.6043L5.72021 17.5883C5.72021 17.1741 5.38443 16.8383 4.97021 16.8383C4.556 16.8383 4.22021 17.1741 4.22021 17.5883L4.22021 18.6043C4.22021 22.8845 7.69001 26.3543 11.9702 26.3543L12.9862 26.3543C13.4004 26.3543 13.7362 26.0185 13.7362 25.6043C13.7362 25.1901 13.4004 24.8543 12.9862 24.8543L11.9702 24.8543C8.51844 24.8543 5.72021 22.0561 5.72021 18.6043Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgRoundedCornerLeftDown);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "41534c1ab61ee8cd15950a6aeafdfec8.svg");

/***/ }),

/***/ 95586:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .tokens-inspect-widget {
	z-index: 50;
	user-select: text;
	-webkit-user-select: text;
	-ms-user-select: text;
	padding: 10px;
}

.tokens-inspect-separator {
	height: 1px;
	border: 0;
}

.monaco-editor .tokens-inspect-widget .tm-token {
	font-family: var(--monaco-monospace-font);
}

.monaco-editor .tokens-inspect-widget .tm-token-length {
	font-weight: normal;
	font-size: 60%;
	float: right;
}

.monaco-editor .tokens-inspect-widget .tm-metadata-table {
	width: 100%;
}

.monaco-editor .tokens-inspect-widget .tm-metadata-value {
	font-family: var(--monaco-monospace-font);
	text-align: right;
}

.monaco-editor .tokens-inspect-widget .tm-token-type {
	font-family: var(--monaco-monospace-font);
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/inspectTokens/inspectTokens.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,WAAW;CACX,iBAAiB;CACjB,yBAAyB;CACzB,qBAAqB;CACrB,aAAa;AACd;;AAEA;CACC,WAAW;CACX,SAAS;AACV;;AAEA;CACC,yCAAyC;AAC1C;;AAEA;CACC,mBAAmB;CACnB,cAAc;CACd,YAAY;AACb;;AAEA;CACC,WAAW;AACZ;;AAEA;CACC,yCAAyC;CACzC,iBAAiB;AAClB;;AAEA;CACC,yCAAyC;AAC1C","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .tokens-inspect-widget {\n\tz-index: 50;\n\tuser-select: text;\n\t-webkit-user-select: text;\n\t-ms-user-select: text;\n\tpadding: 10px;\n}\n\n.tokens-inspect-separator {\n\theight: 1px;\n\tborder: 0;\n}\n\n.monaco-editor .tokens-inspect-widget .tm-token {\n\tfont-family: var(--monaco-monospace-font);\n}\n\n.monaco-editor .tokens-inspect-widget .tm-token-length {\n\tfont-weight: normal;\n\tfont-size: 60%;\n\tfloat: right;\n}\n\n.monaco-editor .tokens-inspect-widget .tm-metadata-table {\n\twidth: 100%;\n}\n\n.monaco-editor .tokens-inspect-widget .tm-metadata-value {\n\tfont-family: var(--monaco-monospace-font);\n\ttext-align: right;\n}\n\n.monaco-editor .tokens-inspect-widget .tm-token-type {\n\tfont-family: var(--monaco-monospace-font);\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 95670:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.quick-input-widget {
	position: absolute;
	width: 600px;
	z-index: 2550;
	left: 50%;
	margin-left: -300px;
	-webkit-app-region: no-drag;
}

.quick-input-titlebar {
	display: flex;
	align-items: center;
}

.quick-input-left-action-bar {
	display: flex;
	margin-left: 4px;
	flex: 1;
}

.quick-input-title {
	padding: 3px 0px;
	text-align: center;
	text-overflow: ellipsis;
	overflow: hidden;
}

.quick-input-right-action-bar {
	display: flex;
	margin-right: 4px;
	flex: 1;
}

.quick-input-right-action-bar > .actions-container {
	justify-content: flex-end;
}

.quick-input-titlebar .monaco-action-bar .action-label.codicon {
	background-position: center;
	background-repeat: no-repeat;
	padding: 2px;
}

.quick-input-description {
	margin: 6px;
}

.quick-input-header .quick-input-description {
	margin: 4px 2px;
}

.quick-input-header {
	display: flex;
	padding: 6px 6px 0px 6px;
	margin-bottom: -2px;
}

.quick-input-widget.hidden-input .quick-input-header {
	/* reduce margins and paddings when input box hidden */
	padding: 0;
	margin-bottom: 0;
}

.quick-input-and-message {
	display: flex;
	flex-direction: column;
	flex-grow: 1;
	min-width: 0;
	position: relative;
}

.quick-input-check-all {
	align-self: center;
	margin: 0;
}

.quick-input-filter {
	flex-grow: 1;
	display: flex;
	position: relative;
}

.quick-input-box {
	flex-grow: 1;
}

.quick-input-widget.show-checkboxes .quick-input-box,
.quick-input-widget.show-checkboxes .quick-input-message {
	margin-left: 5px;
}

.quick-input-visible-count {
	position: absolute;
	left: -10000px;
}

.quick-input-count {
	align-self: center;
	position: absolute;
	right: 4px;
	display: flex;
	align-items: center;
}

.quick-input-count .monaco-count-badge {
	vertical-align: middle;
	padding: 2px 4px;
	border-radius: 2px;
	min-height: auto;
	line-height: normal;
}

.quick-input-action {
	margin-left: 6px;
}

.quick-input-action .monaco-text-button {
	font-size: 11px;
	padding: 0 6px;
	display: flex;
	height: 27.5px;
	align-items: center;
}

.quick-input-message {
	margin-top: -1px;
	padding: 5px;
	overflow-wrap: break-word;
}

.quick-input-message > .codicon {
	margin: 0 0.2em;
	vertical-align: text-bottom;
}

.quick-input-progress.monaco-progress-container {
	position: relative;
}

.quick-input-progress.monaco-progress-container,
.quick-input-progress.monaco-progress-container .progress-bit {
	height: 2px;
}

.quick-input-list {
	line-height: 22px;
	margin-top: 6px;
	padding: 0px 1px 1px 1px;
}

.quick-input-widget.hidden-input .quick-input-list {
	margin-top: 0; /* reduce margins when input box hidden */
}

.quick-input-list .monaco-list {
	overflow: hidden;
	max-height: calc(20 * 22px);
}

.quick-input-list .quick-input-list-entry {
	box-sizing: border-box;
	overflow: hidden;
	display: flex;
	height: 100%;
	padding: 0 6px;
}

.quick-input-list .quick-input-list-entry.quick-input-list-separator-border {
	border-top-width: 1px;
	border-top-style: solid;
}

.quick-input-list .monaco-list-row[data-index="0"] .quick-input-list-entry.quick-input-list-separator-border {
	border-top-style: none;
}

.quick-input-list .quick-input-list-label {
	overflow: hidden;
	display: flex;
	height: 100%;
	flex: 1;
}

.quick-input-list .quick-input-list-checkbox {
	align-self: center;
	margin: 0;
}

.quick-input-list .quick-input-list-rows {
	overflow: hidden;
	text-overflow: ellipsis;
	display: flex;
	flex-direction: column;
	height: 100%;
	flex: 1;
	margin-left: 5px;
}

.quick-input-widget.show-checkboxes .quick-input-list .quick-input-list-rows {
	margin-left: 10px;
}

.quick-input-widget .quick-input-list .quick-input-list-checkbox {
	display: none;
}
.quick-input-widget.show-checkboxes .quick-input-list .quick-input-list-checkbox {
	display: inline;
}

.quick-input-list .quick-input-list-rows > .quick-input-list-row {
	display: flex;
	align-items: center;
}

.quick-input-list .quick-input-list-rows > .quick-input-list-row .monaco-icon-label,
.quick-input-list .quick-input-list-rows > .quick-input-list-row .monaco-icon-label .monaco-icon-label-container > .monaco-icon-name-container {
	flex: 1; /* make sure the icon label grows within the row */
}

.quick-input-list .quick-input-list-rows > .quick-input-list-row .codicon[class*='codicon-'] {
	vertical-align: text-bottom;
}

.quick-input-list .quick-input-list-rows .monaco-highlighted-label span {
	opacity: 1;
}

.quick-input-list .quick-input-list-entry .quick-input-list-entry-keybinding {
	margin-right: 8px; /* separate from the separator label or scrollbar if any */
}

.quick-input-list .quick-input-list-label-meta {
	opacity: 0.7;
	line-height: normal;
	text-overflow: ellipsis;
	overflow: hidden;
}

.quick-input-list .monaco-highlighted-label .highlight {
	font-weight: bold;
}

.quick-input-list .quick-input-list-entry .quick-input-list-separator {
	margin-right: 8px; /* separate from keybindings or actions */
}

.quick-input-list .quick-input-list-entry-action-bar {
	display: flex;
	flex: 0;
	overflow: visible;
}

.quick-input-list .quick-input-list-entry-action-bar .action-label {
	/*
	 * By default, actions in the quick input action bar are hidden
	 * until hovered over them or selected.
	 */
	display: none;
}

.quick-input-list .quick-input-list-entry-action-bar .action-label.codicon {
	margin-right: 4px;
	padding: 0px 2px 2px 2px;
}

.quick-input-list .quick-input-list-entry-action-bar {
	margin-top: 1px;
}

.quick-input-list .quick-input-list-entry-action-bar {
	margin-right: 4px; /* separate from scrollbar */
}

.quick-input-list .quick-input-list-entry .quick-input-list-entry-action-bar .action-label.always-visible,
.quick-input-list .quick-input-list-entry:hover .quick-input-list-entry-action-bar .action-label,
.quick-input-list .monaco-list-row.focused .quick-input-list-entry-action-bar .action-label {
	display: flex;
}

/* focused items in quick pick */
.quick-input-list .monaco-list-row.focused .monaco-keybinding-key,
.quick-input-list .monaco-list-row.focused .quick-input-list-entry .quick-input-list-separator {
	color: inherit
}
.quick-input-list .monaco-list-row.focused .monaco-keybinding-key {
	background: none;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/parts/quickinput/browser/media/quickInput.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,kBAAkB;CAClB,YAAY;CACZ,aAAa;CACb,SAAS;CACT,mBAAmB;CACnB,2BAA2B;AAC5B;;AAEA;CACC,aAAa;CACb,mBAAmB;AACpB;;AAEA;CACC,aAAa;CACb,gBAAgB;CAChB,OAAO;AACR;;AAEA;CACC,gBAAgB;CAChB,kBAAkB;CAClB,uBAAuB;CACvB,gBAAgB;AACjB;;AAEA;CACC,aAAa;CACb,iBAAiB;CACjB,OAAO;AACR;;AAEA;CACC,yBAAyB;AAC1B;;AAEA;CACC,2BAA2B;CAC3B,4BAA4B;CAC5B,YAAY;AACb;;AAEA;CACC,WAAW;AACZ;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,aAAa;CACb,wBAAwB;CACxB,mBAAmB;AACpB;;AAEA;CACC,sDAAsD;CACtD,UAAU;CACV,gBAAgB;AACjB;;AAEA;CACC,aAAa;CACb,sBAAsB;CACtB,YAAY;CACZ,YAAY;CACZ,kBAAkB;AACnB;;AAEA;CACC,kBAAkB;CAClB,SAAS;AACV;;AAEA;CACC,YAAY;CACZ,aAAa;CACb,kBAAkB;AACnB;;AAEA;CACC,YAAY;AACb;;AAEA;;CAEC,gBAAgB;AACjB;;AAEA;CACC,kBAAkB;CAClB,cAAc;AACf;;AAEA;CACC,kBAAkB;CAClB,kBAAkB;CAClB,UAAU;CACV,aAAa;CACb,mBAAmB;AACpB;;AAEA;CACC,sBAAsB;CACtB,gBAAgB;CAChB,kBAAkB;CAClB,gBAAgB;CAChB,mBAAmB;AACpB;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,eAAe;CACf,cAAc;CACd,aAAa;CACb,cAAc;CACd,mBAAmB;AACpB;;AAEA;CACC,gBAAgB;CAChB,YAAY;CACZ,yBAAyB;AAC1B;;AAEA;CACC,eAAe;CACf,2BAA2B;AAC5B;;AAEA;CACC,kBAAkB;AACnB;;AAEA;;CAEC,WAAW;AACZ;;AAEA;CACC,iBAAiB;CACjB,eAAe;CACf,wBAAwB;AACzB;;AAEA;CACC,aAAa,EAAE,yCAAyC;AACzD;;AAEA;CACC,gBAAgB;CAChB,2BAA2B;AAC5B;;AAEA;CACC,sBAAsB;CACtB,gBAAgB;CAChB,aAAa;CACb,YAAY;CACZ,cAAc;AACf;;AAEA;CACC,qBAAqB;CACrB,uBAAuB;AACxB;;AAEA;CACC,sBAAsB;AACvB;;AAEA;CACC,gBAAgB;CAChB,aAAa;CACb,YAAY;CACZ,OAAO;AACR;;AAEA;CACC,kBAAkB;CAClB,SAAS;AACV;;AAEA;CACC,gBAAgB;CAChB,uBAAuB;CACvB,aAAa;CACb,sBAAsB;CACtB,YAAY;CACZ,OAAO;CACP,gBAAgB;AACjB;;AAEA;CACC,iBAAiB;AAClB;;AAEA;CACC,aAAa;AACd;AACA;CACC,eAAe;AAChB;;AAEA;CACC,aAAa;CACb,mBAAmB;AACpB;;AAEA;;CAEC,OAAO,EAAE,kDAAkD;AAC5D;;AAEA;CACC,2BAA2B;AAC5B;;AAEA;CACC,UAAU;AACX;;AAEA;CACC,iBAAiB,EAAE,0DAA0D;AAC9E;;AAEA;CACC,YAAY;CACZ,mBAAmB;CACnB,uBAAuB;CACvB,gBAAgB;AACjB;;AAEA;CACC,iBAAiB;AAClB;;AAEA;CACC,iBAAiB,EAAE,yCAAyC;AAC7D;;AAEA;CACC,aAAa;CACb,OAAO;CACP,iBAAiB;AAClB;;AAEA;CACC;;;GAGE;CACF,aAAa;AACd;;AAEA;CACC,iBAAiB;CACjB,wBAAwB;AACzB;;AAEA;CACC,eAAe;AAChB;;AAEA;CACC,iBAAiB,EAAE,4BAA4B;AAChD;;AAEA;;;CAGC,aAAa;AACd;;AAEA,gCAAgC;AAChC;;CAEC;AACD;AACA;CACC,gBAAgB;AACjB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.quick-input-widget {\n\tposition: absolute;\n\twidth: 600px;\n\tz-index: 2550;\n\tleft: 50%;\n\tmargin-left: -300px;\n\t-webkit-app-region: no-drag;\n}\n\n.quick-input-titlebar {\n\tdisplay: flex;\n\talign-items: center;\n}\n\n.quick-input-left-action-bar {\n\tdisplay: flex;\n\tmargin-left: 4px;\n\tflex: 1;\n}\n\n.quick-input-title {\n\tpadding: 3px 0px;\n\ttext-align: center;\n\ttext-overflow: ellipsis;\n\toverflow: hidden;\n}\n\n.quick-input-right-action-bar {\n\tdisplay: flex;\n\tmargin-right: 4px;\n\tflex: 1;\n}\n\n.quick-input-right-action-bar > .actions-container {\n\tjustify-content: flex-end;\n}\n\n.quick-input-titlebar .monaco-action-bar .action-label.codicon {\n\tbackground-position: center;\n\tbackground-repeat: no-repeat;\n\tpadding: 2px;\n}\n\n.quick-input-description {\n\tmargin: 6px;\n}\n\n.quick-input-header .quick-input-description {\n\tmargin: 4px 2px;\n}\n\n.quick-input-header {\n\tdisplay: flex;\n\tpadding: 6px 6px 0px 6px;\n\tmargin-bottom: -2px;\n}\n\n.quick-input-widget.hidden-input .quick-input-header {\n\t/* reduce margins and paddings when input box hidden */\n\tpadding: 0;\n\tmargin-bottom: 0;\n}\n\n.quick-input-and-message {\n\tdisplay: flex;\n\tflex-direction: column;\n\tflex-grow: 1;\n\tmin-width: 0;\n\tposition: relative;\n}\n\n.quick-input-check-all {\n\talign-self: center;\n\tmargin: 0;\n}\n\n.quick-input-filter {\n\tflex-grow: 1;\n\tdisplay: flex;\n\tposition: relative;\n}\n\n.quick-input-box {\n\tflex-grow: 1;\n}\n\n.quick-input-widget.show-checkboxes .quick-input-box,\n.quick-input-widget.show-checkboxes .quick-input-message {\n\tmargin-left: 5px;\n}\n\n.quick-input-visible-count {\n\tposition: absolute;\n\tleft: -10000px;\n}\n\n.quick-input-count {\n\talign-self: center;\n\tposition: absolute;\n\tright: 4px;\n\tdisplay: flex;\n\talign-items: center;\n}\n\n.quick-input-count .monaco-count-badge {\n\tvertical-align: middle;\n\tpadding: 2px 4px;\n\tborder-radius: 2px;\n\tmin-height: auto;\n\tline-height: normal;\n}\n\n.quick-input-action {\n\tmargin-left: 6px;\n}\n\n.quick-input-action .monaco-text-button {\n\tfont-size: 11px;\n\tpadding: 0 6px;\n\tdisplay: flex;\n\theight: 27.5px;\n\talign-items: center;\n}\n\n.quick-input-message {\n\tmargin-top: -1px;\n\tpadding: 5px;\n\toverflow-wrap: break-word;\n}\n\n.quick-input-message > .codicon {\n\tmargin: 0 0.2em;\n\tvertical-align: text-bottom;\n}\n\n.quick-input-progress.monaco-progress-container {\n\tposition: relative;\n}\n\n.quick-input-progress.monaco-progress-container,\n.quick-input-progress.monaco-progress-container .progress-bit {\n\theight: 2px;\n}\n\n.quick-input-list {\n\tline-height: 22px;\n\tmargin-top: 6px;\n\tpadding: 0px 1px 1px 1px;\n}\n\n.quick-input-widget.hidden-input .quick-input-list {\n\tmargin-top: 0; /* reduce margins when input box hidden */\n}\n\n.quick-input-list .monaco-list {\n\toverflow: hidden;\n\tmax-height: calc(20 * 22px);\n}\n\n.quick-input-list .quick-input-list-entry {\n\tbox-sizing: border-box;\n\toverflow: hidden;\n\tdisplay: flex;\n\theight: 100%;\n\tpadding: 0 6px;\n}\n\n.quick-input-list .quick-input-list-entry.quick-input-list-separator-border {\n\tborder-top-width: 1px;\n\tborder-top-style: solid;\n}\n\n.quick-input-list .monaco-list-row[data-index=\"0\"] .quick-input-list-entry.quick-input-list-separator-border {\n\tborder-top-style: none;\n}\n\n.quick-input-list .quick-input-list-label {\n\toverflow: hidden;\n\tdisplay: flex;\n\theight: 100%;\n\tflex: 1;\n}\n\n.quick-input-list .quick-input-list-checkbox {\n\talign-self: center;\n\tmargin: 0;\n}\n\n.quick-input-list .quick-input-list-rows {\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n\tdisplay: flex;\n\tflex-direction: column;\n\theight: 100%;\n\tflex: 1;\n\tmargin-left: 5px;\n}\n\n.quick-input-widget.show-checkboxes .quick-input-list .quick-input-list-rows {\n\tmargin-left: 10px;\n}\n\n.quick-input-widget .quick-input-list .quick-input-list-checkbox {\n\tdisplay: none;\n}\n.quick-input-widget.show-checkboxes .quick-input-list .quick-input-list-checkbox {\n\tdisplay: inline;\n}\n\n.quick-input-list .quick-input-list-rows > .quick-input-list-row {\n\tdisplay: flex;\n\talign-items: center;\n}\n\n.quick-input-list .quick-input-list-rows > .quick-input-list-row .monaco-icon-label,\n.quick-input-list .quick-input-list-rows > .quick-input-list-row .monaco-icon-label .monaco-icon-label-container > .monaco-icon-name-container {\n\tflex: 1; /* make sure the icon label grows within the row */\n}\n\n.quick-input-list .quick-input-list-rows > .quick-input-list-row .codicon[class*='codicon-'] {\n\tvertical-align: text-bottom;\n}\n\n.quick-input-list .quick-input-list-rows .monaco-highlighted-label span {\n\topacity: 1;\n}\n\n.quick-input-list .quick-input-list-entry .quick-input-list-entry-keybinding {\n\tmargin-right: 8px; /* separate from the separator label or scrollbar if any */\n}\n\n.quick-input-list .quick-input-list-label-meta {\n\topacity: 0.7;\n\tline-height: normal;\n\ttext-overflow: ellipsis;\n\toverflow: hidden;\n}\n\n.quick-input-list .monaco-highlighted-label .highlight {\n\tfont-weight: bold;\n}\n\n.quick-input-list .quick-input-list-entry .quick-input-list-separator {\n\tmargin-right: 8px; /* separate from keybindings or actions */\n}\n\n.quick-input-list .quick-input-list-entry-action-bar {\n\tdisplay: flex;\n\tflex: 0;\n\toverflow: visible;\n}\n\n.quick-input-list .quick-input-list-entry-action-bar .action-label {\n\t/*\n\t * By default, actions in the quick input action bar are hidden\n\t * until hovered over them or selected.\n\t */\n\tdisplay: none;\n}\n\n.quick-input-list .quick-input-list-entry-action-bar .action-label.codicon {\n\tmargin-right: 4px;\n\tpadding: 0px 2px 2px 2px;\n}\n\n.quick-input-list .quick-input-list-entry-action-bar {\n\tmargin-top: 1px;\n}\n\n.quick-input-list .quick-input-list-entry-action-bar {\n\tmargin-right: 4px; /* separate from scrollbar */\n}\n\n.quick-input-list .quick-input-list-entry .quick-input-list-entry-action-bar .action-label.always-visible,\n.quick-input-list .quick-input-list-entry:hover .quick-input-list-entry-action-bar .action-label,\n.quick-input-list .monaco-list-row.focused .quick-input-list-entry-action-bar .action-label {\n\tdisplay: flex;\n}\n\n/* focused items in quick pick */\n.quick-input-list .monaco-list-row.focused .monaco-keybinding-key,\n.quick-input-list .monaco-list-row.focused .quick-input-list-entry .quick-input-list-separator {\n\tcolor: inherit\n}\n.quick-input-list .monaco-list-row.focused .monaco-keybinding-key {\n\tbackground: none;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 95715:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.NodePickerSubCategory-module__Title--qVQ1U{font-weight:500;font-size:11px;line-height:13.31px;letter-spacing:3%;padding:10px 13px 0;margin-block-end:0;color:var(--theme-color-fg-muted);position:relative;z-index:2}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/NodePicker/components/NodePickerSubCategory/NodePickerSubCategory.module.scss"],"names":[],"mappings":"AAAA,4CACE,eAAA,CACA,cAAA,CACA,mBAAA,CACA,iBAAA,CACA,mBAAA,CACA,kBAAA,CACA,iCAAA,CACA,iBAAA,CACA,SAAA","sourcesContent":[".Title {\n  font-weight: 500;\n  font-size: 11px;\n  line-height: 13.31px;\n  letter-spacing: 3%;\n  padding: 10px 13px 0;\n  margin-block-end: 0;\n  color: var(--theme-color-fg-muted);\n  position: relative;\n  z-index: 2;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Title": `NodePickerSubCategory-module__Title--qVQ1U`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 96039:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PRDetail-module__PRDetailOverlay--anXR0{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,.5);z-index:1000;display:flex;justify-content:flex-end;animation:PRDetail-module__fadeIn--Irou7 .2s ease}@keyframes PRDetail-module__fadeIn--Irou7{from{opacity:0}to{opacity:1}}.PRDetail-module__PRDetail--CaLn2{width:600px;max-width:90vw;height:100%;background-color:var(--theme-color-bg-2);box-shadow:-2px 0 8px rgba(0,0,0,.2);display:flex;flex-direction:column;animation:PRDetail-module__slideIn--tC6R3 .3s ease;overflow:hidden}@keyframes PRDetail-module__slideIn--tC6R3{from{transform:translateX(100%)}to{transform:translateX(0)}}.PRDetail-module__Header--Xn4A4{padding:20px;border-bottom:1px solid var(--theme-color-border-default);flex-shrink:0}.PRDetail-module__TitleSection--xH4sB{display:flex;align-items:flex-start;gap:12px;margin-bottom:12px}.PRDetail-module__Title--Rz0Vi{flex:1;color:var(--theme-color-fg-default);font-size:18px;font-weight:600;margin:0;line-height:1.4}.PRDetail-module__StatusBadge--YasmJ{flex-shrink:0;padding:4px 12px;border-radius:12px;font-size:12px;font-weight:600;text-transform:capitalize}.PRDetail-module__StatusBadge--YasmJ[data-status=open]{background-color:rgba(46,160,67,.15);color:#2ea043}.PRDetail-module__StatusBadge--YasmJ[data-status=draft]{background-color:rgba(110,118,129,.15);color:#6e7681}.PRDetail-module__StatusBadge--YasmJ[data-status=merged]{background-color:rgba(137,87,229,.15);color:#8957e5}.PRDetail-module__StatusBadge--YasmJ[data-status=closed]{background-color:rgba(177,24,24,.15);color:#da3633}.PRDetail-module__CloseButton--Eb_Gd{position:absolute;top:16px;right:16px;width:32px;height:32px;display:flex;align-items:center;justify-content:center;background-color:rgba(0,0,0,0);border:none;border-radius:4px;color:var(--theme-color-fg-default-shy);font-size:20px;cursor:pointer;transition:all .15s ease}.PRDetail-module__CloseButton--Eb_Gd:hover{background-color:var(--theme-color-bg-4);color:var(--theme-color-fg-default)}.PRDetail-module__Meta--Yruo6{display:flex;flex-direction:column;gap:4px;color:var(--theme-color-fg-default-shy);font-size:13px;margin-bottom:12px}.PRDetail-module__Meta--Yruo6 strong{color:var(--theme-color-fg-default);font-weight:600}.PRDetail-module__Branch--vstUq{background-color:var(--theme-color-bg-4);padding:2px 6px;border-radius:3px;font-family:monospace;font-size:12px;color:var(--theme-color-fg-default)}.PRDetail-module__Labels--I1gna{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:12px}.PRDetail-module__Label--y_dxe{padding:3px 10px;border-radius:12px;font-size:12px;font-weight:600;display:inline-block}.PRDetail-module__Stats--2Djp6{display:flex;gap:20px;padding:12px 0;border-top:1px solid var(--theme-color-border-default);border-bottom:1px solid var(--theme-color-border-default);margin-bottom:12px}.PRDetail-module__StatItem--UPuVH{display:flex;flex-direction:column;gap:4px}.PRDetail-module__StatLabel--x0fZd{color:var(--theme-color-fg-default-shy);font-size:11px;text-transform:uppercase;letter-spacing:.5px}.PRDetail-module__StatValue--ixmSM{color:var(--theme-color-fg-default);font-size:18px;font-weight:600}.PRDetail-module__Body--GWS8m{flex:1;padding:20px;overflow-y:auto;color:var(--theme-color-fg-default);font-size:14px;line-height:1.6}.PRDetail-module__MarkdownContent--WnbJS{white-space:pre-wrap;word-break:break-word}.PRDetail-module__NoDescription--JyZiQ{color:var(--theme-color-fg-default-shy);font-style:italic}.PRDetail-module__MergeInfo--GRCFn,.PRDetail-module__DraftInfo--hQ2c_,.PRDetail-module__ClosedInfo--ifTJ0{display:flex;align-items:center;gap:8px;padding:12px 20px;background-color:var(--theme-color-bg-3);border-top:1px solid var(--theme-color-border-default);font-size:13px;color:var(--theme-color-fg-default-shy)}.PRDetail-module__MergeIcon--IoVQn,.PRDetail-module__DraftIcon--yUyVs,.PRDetail-module__ClosedIcon--iSU87{font-size:16px}.PRDetail-module__Footer--Ynual{padding:16px 20px;border-top:1px solid var(--theme-color-border-default);flex-shrink:0}.PRDetail-module__ViewOnGitHub--BOBfs{display:inline-flex;align-items:center;gap:4px;padding:8px 16px;background-color:var(--theme-color-primary);color:#fff;text-decoration:none;border-radius:4px;font-size:13px;font-weight:500;transition:opacity .15s ease}.PRDetail-module__ViewOnGitHub--BOBfs:hover{opacity:.9}.PRDetail-module__ViewOnGitHub--BOBfs:active{opacity:.8}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRDetail.module.scss"],"names":[],"mappings":"AAIA,yCACE,cAAA,CACA,KAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CACA,+BAAA,CACA,YAAA,CACA,YAAA,CACA,wBAAA,CACA,iDAAA,CAGF,0CACE,KACE,SAAA,CAEF,GACE,SAAA,CAAA,CAIJ,kCACE,WAAA,CACA,cAAA,CACA,WAAA,CACA,wCAAA,CACA,oCAAA,CACA,YAAA,CACA,qBAAA,CACA,kDAAA,CACA,eAAA,CAGF,2CACE,KACE,0BAAA,CAEF,GACE,uBAAA,CAAA,CAIJ,gCACE,YAAA,CACA,yDAAA,CACA,aAAA,CAGF,sCACE,YAAA,CACA,sBAAA,CACA,QAAA,CACA,kBAAA,CAGF,+BACE,MAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CACA,QAAA,CACA,eAAA,CAGF,qCACE,aAAA,CACA,gBAAA,CACA,kBAAA,CACA,cAAA,CACA,eAAA,CACA,yBAAA,CAEA,uDACE,oCAAA,CACA,aAAA,CAGF,wDACE,sCAAA,CACA,aAAA,CAGF,yDACE,qCAAA,CACA,aAAA,CAGF,yDACE,oCAAA,CACA,aAAA,CAIJ,qCACE,iBAAA,CACA,QAAA,CACA,UAAA,CACA,UAAA,CACA,WAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,8BAAA,CACA,WAAA,CACA,iBAAA,CACA,uCAAA,CACA,cAAA,CACA,cAAA,CACA,wBAAA,CAEA,2CACE,wCAAA,CACA,mCAAA,CAIJ,8BACE,YAAA,CACA,qBAAA,CACA,OAAA,CACA,uCAAA,CACA,cAAA,CACA,kBAAA,CAEA,qCACE,mCAAA,CACA,eAAA,CAIJ,gCACE,wCAAA,CACA,eAAA,CACA,iBAAA,CACA,qBAAA,CACA,cAAA,CACA,mCAAA,CAGF,gCACE,YAAA,CACA,cAAA,CACA,OAAA,CACA,kBAAA,CAGF,+BACE,gBAAA,CACA,kBAAA,CACA,cAAA,CACA,eAAA,CACA,oBAAA,CAGF,+BACE,YAAA,CACA,QAAA,CACA,cAAA,CACA,sDAAA,CACA,yDAAA,CACA,kBAAA,CAGF,kCACE,YAAA,CACA,qBAAA,CACA,OAAA,CAGF,mCACE,uCAAA,CACA,cAAA,CACA,wBAAA,CACA,mBAAA,CAGF,mCACE,mCAAA,CACA,cAAA,CACA,eAAA,CAGF,8BACE,MAAA,CACA,YAAA,CACA,eAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CAGF,yCACE,oBAAA,CACA,qBAAA,CAGF,uCACE,uCAAA,CACA,iBAAA,CAGF,0GAGE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,iBAAA,CACA,wCAAA,CACA,sDAAA,CACA,cAAA,CACA,uCAAA,CAGF,0GAGE,cAAA,CAGF,gCACE,iBAAA,CACA,sDAAA,CACA,aAAA,CAGF,sCACE,mBAAA,CACA,kBAAA,CACA,OAAA,CACA,gBAAA,CACA,2CAAA,CACA,UAAA,CACA,oBAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,4BAAA,CAEA,4CACE,UAAA,CAGF,6CACE,UAAA","sourcesContent":["/**\n * PRDetail Styles - Slide-out panel\n */\n\n.PRDetailOverlay {\n  position: fixed;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  background-color: rgba(0, 0, 0, 0.5);\n  z-index: 1000;\n  display: flex;\n  justify-content: flex-end;\n  animation: fadeIn 0.2s ease;\n}\n\n@keyframes fadeIn {\n  from {\n    opacity: 0;\n  }\n  to {\n    opacity: 1;\n  }\n}\n\n.PRDetail {\n  width: 600px;\n  max-width: 90vw;\n  height: 100%;\n  background-color: var(--theme-color-bg-2);\n  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.2);\n  display: flex;\n  flex-direction: column;\n  animation: slideIn 0.3s ease;\n  overflow: hidden;\n}\n\n@keyframes slideIn {\n  from {\n    transform: translateX(100%);\n  }\n  to {\n    transform: translateX(0);\n  }\n}\n\n.Header {\n  padding: 20px;\n  border-bottom: 1px solid var(--theme-color-border-default);\n  flex-shrink: 0;\n}\n\n.TitleSection {\n  display: flex;\n  align-items: flex-start;\n  gap: 12px;\n  margin-bottom: 12px;\n}\n\n.Title {\n  flex: 1;\n  color: var(--theme-color-fg-default);\n  font-size: 18px;\n  font-weight: 600;\n  margin: 0;\n  line-height: 1.4;\n}\n\n.StatusBadge {\n  flex-shrink: 0;\n  padding: 4px 12px;\n  border-radius: 12px;\n  font-size: 12px;\n  font-weight: 600;\n  text-transform: capitalize;\n\n  &[data-status='open'] {\n    background-color: rgba(46, 160, 67, 0.15);\n    color: #2ea043;\n  }\n\n  &[data-status='draft'] {\n    background-color: rgba(110, 118, 129, 0.15);\n    color: #6e7681;\n  }\n\n  &[data-status='merged'] {\n    background-color: rgba(137, 87, 229, 0.15);\n    color: #8957e5;\n  }\n\n  &[data-status='closed'] {\n    background-color: rgba(177, 24, 24, 0.15);\n    color: #da3633;\n  }\n}\n\n.CloseButton {\n  position: absolute;\n  top: 16px;\n  right: 16px;\n  width: 32px;\n  height: 32px;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  background-color: transparent;\n  border: none;\n  border-radius: 4px;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 20px;\n  cursor: pointer;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-4);\n    color: var(--theme-color-fg-default);\n  }\n}\n\n.Meta {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 13px;\n  margin-bottom: 12px;\n\n  strong {\n    color: var(--theme-color-fg-default);\n    font-weight: 600;\n  }\n}\n\n.Branch {\n  background-color: var(--theme-color-bg-4);\n  padding: 2px 6px;\n  border-radius: 3px;\n  font-family: monospace;\n  font-size: 12px;\n  color: var(--theme-color-fg-default);\n}\n\n.Labels {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 6px;\n  margin-bottom: 12px;\n}\n\n.Label {\n  padding: 3px 10px;\n  border-radius: 12px;\n  font-size: 12px;\n  font-weight: 600;\n  display: inline-block;\n}\n\n.Stats {\n  display: flex;\n  gap: 20px;\n  padding: 12px 0;\n  border-top: 1px solid var(--theme-color-border-default);\n  border-bottom: 1px solid var(--theme-color-border-default);\n  margin-bottom: 12px;\n}\n\n.StatItem {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n}\n\n.StatLabel {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 11px;\n  text-transform: uppercase;\n  letter-spacing: 0.5px;\n}\n\n.StatValue {\n  color: var(--theme-color-fg-default);\n  font-size: 18px;\n  font-weight: 600;\n}\n\n.Body {\n  flex: 1;\n  padding: 20px;\n  overflow-y: auto;\n  color: var(--theme-color-fg-default);\n  font-size: 14px;\n  line-height: 1.6;\n}\n\n.MarkdownContent {\n  white-space: pre-wrap;\n  word-break: break-word;\n}\n\n.NoDescription {\n  color: var(--theme-color-fg-default-shy);\n  font-style: italic;\n}\n\n.MergeInfo,\n.DraftInfo,\n.ClosedInfo {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 12px 20px;\n  background-color: var(--theme-color-bg-3);\n  border-top: 1px solid var(--theme-color-border-default);\n  font-size: 13px;\n  color: var(--theme-color-fg-default-shy);\n}\n\n.MergeIcon,\n.DraftIcon,\n.ClosedIcon {\n  font-size: 16px;\n}\n\n.Footer {\n  padding: 16px 20px;\n  border-top: 1px solid var(--theme-color-border-default);\n  flex-shrink: 0;\n}\n\n.ViewOnGitHub {\n  display: inline-flex;\n  align-items: center;\n  gap: 4px;\n  padding: 8px 16px;\n  background-color: var(--theme-color-primary);\n  color: white;\n  text-decoration: none;\n  border-radius: 4px;\n  font-size: 13px;\n  font-weight: 500;\n  transition: opacity 0.15s ease;\n\n  &:hover {\n    opacity: 0.9;\n  }\n\n  &:active {\n    opacity: 0.8;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"PRDetailOverlay": `PRDetail-module__PRDetailOverlay--anXR0`,
	"fadeIn": `PRDetail-module__fadeIn--Irou7`,
	"PRDetail": `PRDetail-module__PRDetail--CaLn2`,
	"slideIn": `PRDetail-module__slideIn--tC6R3`,
	"Header": `PRDetail-module__Header--Xn4A4`,
	"TitleSection": `PRDetail-module__TitleSection--xH4sB`,
	"Title": `PRDetail-module__Title--Rz0Vi`,
	"StatusBadge": `PRDetail-module__StatusBadge--YasmJ`,
	"CloseButton": `PRDetail-module__CloseButton--Eb_Gd`,
	"Meta": `PRDetail-module__Meta--Yruo6`,
	"Branch": `PRDetail-module__Branch--vstUq`,
	"Labels": `PRDetail-module__Labels--I1gna`,
	"Label": `PRDetail-module__Label--y_dxe`,
	"Stats": `PRDetail-module__Stats--2Djp6`,
	"StatItem": `PRDetail-module__StatItem--UPuVH`,
	"StatLabel": `PRDetail-module__StatLabel--x0fZd`,
	"StatValue": `PRDetail-module__StatValue--ixmSM`,
	"Body": `PRDetail-module__Body--GWS8m`,
	"MarkdownContent": `PRDetail-module__MarkdownContent--WnbJS`,
	"NoDescription": `PRDetail-module__NoDescription--JyZiQ`,
	"MergeInfo": `PRDetail-module__MergeInfo--GRCFn`,
	"DraftInfo": `PRDetail-module__DraftInfo--hQ2c_`,
	"ClosedInfo": `PRDetail-module__ClosedInfo--ifTJ0`,
	"MergeIcon": `PRDetail-module__MergeIcon--IoVQn`,
	"DraftIcon": `PRDetail-module__DraftIcon--yUyVs`,
	"ClosedIcon": `PRDetail-module__ClosedIcon--iSU87`,
	"Footer": `PRDetail-module__Footer--Ynual`,
	"ViewOnGitHub": `PRDetail-module__ViewOnGitHub--BOBfs`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 96047:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.maybeParseBetaMessage = maybeParseBetaMessage;
exports.parseBetaMessage = parseBetaMessage;
const error_1 = __webpack_require__(37015);
function maybeParseBetaMessage(message, params, opts) {
    if (!params || !('parse' in (params.output_format ?? {}))) {
        return {
            ...message,
            content: message.content.map((block) => {
                if (block.type === 'text') {
                    const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {
                        value: null,
                        enumerable: false,
                    });
                    return Object.defineProperty(parsedBlock, 'parsed', {
                        get() {
                            opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.');
                            return null;
                        },
                        enumerable: false,
                    });
                }
                return block;
            }),
            parsed_output: null,
        };
    }
    return parseBetaMessage(message, params, opts);
}
function parseBetaMessage(message, params, opts) {
    let firstParsedOutput = null;
    const content = message.content.map((block) => {
        if (block.type === 'text') {
            const parsedOutput = parseBetaOutputFormat(params, block.text);
            if (firstParsedOutput === null) {
                firstParsedOutput = parsedOutput;
            }
            const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {
                value: parsedOutput,
                enumerable: false,
            });
            return Object.defineProperty(parsedBlock, 'parsed', {
                get() {
                    opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.');
                    return parsedOutput;
                },
                enumerable: false,
            });
        }
        return block;
    });
    return {
        ...message,
        content,
        parsed_output: firstParsedOutput,
    };
}
function parseBetaOutputFormat(params, content) {
    if (params.output_format?.type !== 'json_schema') {
        return null;
    }
    try {
        if ('parse' in params.output_format) {
            return params.output_format.parse(content);
        }
        return JSON.parse(content);
    }
    catch (error) {
        throw new error_1.AnthropicError(`Failed to parse structured output: ${error}`);
    }
}
//# sourceMappingURL=beta-parser.js.map

/***/ }),

/***/ 96061:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.AiChatMessage-module__Root--dhSzq{border-top:1px solid var(--theme-color-bg-1)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/ai/AiChatMessage/AiChatMessage.module.scss"],"names":[],"mappings":"AAAA,mCACE,4CAAA","sourcesContent":[".Root {\n  border-top: 1px solid var(--theme-color-bg-1);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `AiChatMessage-module__Root--dhSzq`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 96157:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.help-center-layer{position:absolute;left:0;right:0;bottom:0}.HelpCenter-module__Root--C0O4j{position:absolute;bottom:16px;right:16px;width:36px;height:36px;background-color:var(--theme-color-bg-4);border-radius:50%;display:flex;align-items:center;justify-content:center;box-shadow:0 0 10px var(--theme-color-bg-1-transparent);border-radius:50%;overflow:hidden}.HelpCenter-module__SearchHit--hvS5U{padding:16px;background-color:var(--theme-color-bg-2);margin-bottom:16px}.HelpCenter-module__HitTitle--n6RyH{display:flex;justify-content:space-between;align-items:flex-start}.HelpCenter-module__MessageContainer--ThwQE{display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;height:40vh;background-color:var(--theme-color-bg-2);margin-top:32px}.HelpCenter-module__Buttons--ZUU6F{padding-top:32px;display:flex;justify-content:center}.ais-InfiniteHits-list,.ais-Hits-list{padding-left:0;list-style:none;margin:0}.ais-InfiniteHits-list>:first-child,.ais-Hits-list>:first-child{padding-top:16px}.ais-Highlight-highlighted{background:rgba(0,0,0,0);color:var(--theme-color-primary)}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/HelpCenter/HelpCenter.module.scss"],"names":[],"mappings":"AAAA,mBACE,iBAAA,CACA,MAAA,CACA,OAAA,CACA,QAAA,CAGF,gCACE,iBAAA,CACA,WAAA,CACA,UAAA,CACA,UAAA,CACA,WAAA,CACA,wCAAA,CACA,iBAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,uDAAA,CACA,iBAAA,CACA,eAAA,CAGF,qCACE,YAAA,CACA,wCAAA,CACA,kBAAA,CAGF,oCACE,YAAA,CACA,6BAAA,CACA,sBAAA,CAGF,4CACE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,WAAA,CACA,wCAAA,CACA,eAAA,CAGF,mCACE,gBAAA,CACA,YAAA,CACA,sBAAA,CAGF,sCAEE,cAAA,CACA,eAAA,CACA,QAAA,CAEA,gEACE,gBAAA,CAIJ,2BACE,wBAAA,CACA,gCAAA","sourcesContent":[":global(.help-center-layer) {\n  position: absolute;\n  left: 0;\n  right: 0;\n  bottom: 0;\n}\n\n.Root {\n  position: absolute;\n  bottom: 16px;\n  right: 16px;\n  width: 36px;\n  height: 36px;\n  background-color: var(--theme-color-bg-4);\n  border-radius: 50%;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  box-shadow: 0 0 10px var(--theme-color-bg-1-transparent);\n  border-radius: 50%;\n  overflow: hidden;\n}\n\n.SearchHit {\n  padding: 16px;\n  background-color: var(--theme-color-bg-2);\n  margin-bottom: 16px;\n}\n\n.HitTitle {\n  display: flex;\n  justify-content: space-between;\n  align-items: flex-start;\n}\n\n.MessageContainer {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  text-align: center;\n  height: 40vh;\n  background-color: var(--theme-color-bg-2);\n  margin-top: 32px;\n}\n\n.Buttons {\n  padding-top: 32px;\n  display: flex;\n  justify-content: center;\n}\n\n:global(.ais-InfiniteHits-list),\n:global(.ais-Hits-list) {\n  padding-left: 0;\n  list-style: none;\n  margin: 0;\n\n  > :first-child {\n    padding-top: 16px;\n  }\n}\n\n:global(.ais-Highlight-highlighted) {\n  background: transparent;\n  color: var(--theme-color-primary);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `HelpCenter-module__Root--C0O4j`,
	"SearchHit": `HelpCenter-module__SearchHit--hvS5U`,
	"HitTitle": `HelpCenter-module__HitTitle--n6RyH`,
	"MessageContainer": `HelpCenter-module__MessageContainer--ThwQE`,
	"Buttons": `HelpCenter-module__Buttons--ZUU6F`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 96293:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.FolderTreeItem-module__Root--ONbUN{display:flex;align-items:center;gap:var(--spacing-2);padding:var(--spacing-1-5) var(--spacing-2);border-radius:var(--radius-default);cursor:pointer;transition:background-color .15s ease;min-height:32px;user-select:none}.FolderTreeItem-module__Root--ONbUN:hover{background-color:var(--theme-color-bg-3)}.FolderTreeItem-module__Root--selected--yxEgn{background-color:var(--theme-color-bg-4)}.FolderTreeItem-module__Root--selected--yxEgn:hover{background-color:var(--theme-color-bg-4)}.FolderTreeItem-module__Chevron--DvuPH{display:flex;align-items:center;justify-content:center;padding:0;background:none;border:none;cursor:pointer;color:var(--theme-color-fg-default-shy);transition:color .15s ease;flex-shrink:0}.FolderTreeItem-module__Chevron--DvuPH:hover{color:var(--theme-color-fg-default)}.FolderTreeItem-module__ChevronIcon--vls8l{display:flex}.FolderTreeItem-module__FolderIcon--OKImJ{display:flex;align-items:center;justify-content:center;color:var(--theme-color-fg-default-shy);flex-shrink:0}.FolderTreeItem-module__Icon--woPJn{display:flex}.FolderTreeItem-module__FolderName--xW3ie{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.FolderTreeItem-module__Badge--tC1Ix{display:flex;align-items:center;justify-content:center;padding:0 var(--spacing-1-5);background-color:var(--theme-color-bg-3);border-radius:var(--radius-full);min-width:20px;height:18px;flex-shrink:0}.FolderTreeItem-module__ContextMenuTrigger--UAwdp{display:flex;align-items:center;margin-left:auto;flex-shrink:0}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/preview/launcher/Launcher/components/FolderTreeItem/FolderTreeItem.module.scss"],"names":[],"mappings":"AAIA,oCACE,YAAA,CACA,kBAAA,CACA,oBAAA,CACA,2CAAA,CACA,mCAAA,CACA,cAAA,CACA,qCAAA,CACA,eAAA,CACA,gBAAA,CAEA,0CACE,wCAAA,CAGF,8CACE,wCAAA,CAEA,oDACE,wCAAA,CAKN,uCACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,SAAA,CACA,eAAA,CACA,WAAA,CACA,cAAA,CACA,uCAAA,CACA,0BAAA,CACA,aAAA,CAEA,6CACE,mCAAA,CAIJ,2CACE,YAAA,CAGF,0CACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,uCAAA,CACA,aAAA,CAGF,oCACE,YAAA,CAGF,0CACE,MAAA,CACA,WAAA,CACA,eAAA,CACA,sBAAA,CACA,kBAAA,CAGF,qCACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,4BAAA,CACA,wCAAA,CACA,gCAAA,CACA,cAAA,CACA,WAAA,CACA,aAAA,CAGF,kDACE,YAAA,CACA,kBAAA,CACA,gBAAA,CACA,aAAA","sourcesContent":["/**\n * FolderTreeItem Styles\n */\n\n.Root {\n  display: flex;\n  align-items: center;\n  gap: var(--spacing-2);\n  padding: var(--spacing-1-5) var(--spacing-2);\n  border-radius: var(--radius-default);\n  cursor: pointer;\n  transition: background-color 0.15s ease;\n  min-height: 32px;\n  user-select: none;\n\n  &:hover {\n    background-color: var(--theme-color-bg-3);\n  }\n\n  &--selected {\n    background-color: var(--theme-color-bg-4);\n\n    &:hover {\n      background-color: var(--theme-color-bg-4);\n    }\n  }\n}\n\n.Chevron {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0;\n  background: none;\n  border: none;\n  cursor: pointer;\n  color: var(--theme-color-fg-default-shy);\n  transition: color 0.15s ease;\n  flex-shrink: 0;\n\n  &:hover {\n    color: var(--theme-color-fg-default);\n  }\n}\n\n.ChevronIcon {\n  display: flex;\n}\n\n.FolderIcon {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  color: var(--theme-color-fg-default-shy);\n  flex-shrink: 0;\n}\n\n.Icon {\n  display: flex;\n}\n\n.FolderName {\n  flex: 1;\n  min-width: 0; /* Allow text truncation */\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n.Badge {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 var(--spacing-1-5);\n  background-color: var(--theme-color-bg-3);\n  border-radius: var(--radius-full);\n  min-width: 20px;\n  height: 18px;\n  flex-shrink: 0;\n}\n\n.ContextMenuTrigger {\n  display: flex;\n  align-items: center;\n  margin-left: auto;\n  flex-shrink: 0;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `FolderTreeItem-module__Root--ONbUN`,
	"Root--selected": `FolderTreeItem-module__Root--selected--yxEgn`,
	"Chevron": `FolderTreeItem-module__Chevron--DvuPH`,
	"ChevronIcon": `FolderTreeItem-module__ChevronIcon--vls8l`,
	"FolderIcon": `FolderTreeItem-module__FolderIcon--OKImJ`,
	"Icon": `FolderTreeItem-module__Icon--woPJn`,
	"FolderName": `FolderTreeItem-module__FolderName--xW3ie`,
	"Badge": `FolderTreeItem-module__Badge--tC1Ix`,
	"ContextMenuTrigger": `FolderTreeItem-module__ContextMenuTrigger--UAwdp`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 96397:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var FileSystem = __webpack_require__(38656);

var ThumbnailCache = function () {
  this.thumbnails = {};
  this.thumbnailSize = { width: 50, height: 50 };
};

ThumbnailCache.prototype.getThumbnailForFile = function (fileEntry, callback) {
  var _this = this;

  FileSystem.instance.getFileMetadata(
    fileEntry.fullPath,
    function (metadata) {
      if (
        _this.thumbnails[fileEntry.fullPath] === undefined ||
        +_this.thumbnails[fileEntry.fullPath].modified !== +new Date(metadata.modificationTime)
      ) {
        _this.createThumbnailForFile(fileEntry, metadata, callback);
      } else {
        callback(_this.thumbnails[fileEntry.fullPath]);
      }
    },
    function () {
      // Error loading metadata
      callback && callback();
    }
  );
};

/*ThumbnailCache.prototype.getThumbnailCanvas = function() {
  var el = $('#tnumbnailCacheCanvas');
  if(el.length === 0) {
    $('body').append('<canvas id="tnumbnailCacheCanvas"></canvas>');
    el = $('#tnumbnailCacheCanvas');
  }

  return el;
}*/

ThumbnailCache.prototype.createThumbnailForFile = function (fileEntry, metadata, callback) {
  var _this = this;

  FileSystem.instance.downloadAsDataURI(fileEntry.fullPath, function (content) {
    var img = new Image();
    img.onload = function () {
      var canvas1 = document.createElement('canvas');
      var canvas2 = document.createElement('canvas');
      var target = canvas1;
      var source = img;

      // Halve the image in size until we can do a final scale
      // otherwise the scaling quality is too poor
      while (true) {
        var newWidth = Math.round(source.width * 0.5);
        var newHeight = Math.round(source.height * 0.5);
        if (newWidth <= _this.thumbnailSize.width || newHeight <= _this.thumbnailSize.height) {
          if (source.width > source.height) {
            newHeight = _this.thumbnailSize.height;
            newWidth = (source.width / source.height) * newHeight;
          } else {
            newWidth = _this.thumbnailSize.width;
            newHeight = (source.height / source.width) * newWidth;
          }
          target.width = _this.thumbnailSize.width;
          target.height = _this.thumbnailSize.height;
          var ctx = target.getContext('2d');
          ctx.clearRect(0, 0, target.width, target.height);
          ctx.drawImage(
            source,
            (_this.thumbnailSize.width - newWidth) / 2,
            (_this.thumbnailSize.height - newHeight) / 2,
            newWidth,
            newHeight
          );
          try {
            _this.thumbnails[fileEntry.fullPath] = {
              dataUrl: target.toDataURL(),
              modified: new Date(metadata.modificationTime)
            };
            callback && callback(_this.thumbnails[fileEntry.fullPath]);
          } catch (e) {
            console.log('Error creating thumbnail for', fileEntry.fullPath, e.message);
            callback && callback();
          }
          return;
        } else {
          target.width = newWidth;
          target.height = newHeight;
          var ctx = target.getContext('2d');
          ctx.clearRect(0, 0, target.width, target.height);
          ctx.drawImage(source, 0, 0, target.width, target.height);
        }

        // swap
        target = target === canvas1 ? canvas2 : canvas1;
        source = target == canvas1 ? canvas2 : canvas1;
      }
    };
    img.onerror = function () {
      callback && callback();
    };
    img.src = content;
  });
};

ThumbnailCache.instance = new ThumbnailCache();

module.exports = ThumbnailCache;


/***/ }),

/***/ 96419:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-mouse-cursor-text {
	cursor: text;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/mouseCursor/mouseCursor.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,YAAY;AACb","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-mouse-cursor-text {\n\tcursor: text;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 96543:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (/* binding */ SchemaHandler)
/* harmony export */ });
/* harmony import */ var _noodl_models_CloudServices__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(48153);
/* harmony import */ var _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6203);
/* harmony import */ var _noodl_models_projectmodel_editor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(46998);
/* harmony import */ var _noodl_models_schemamodel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(98424);
/* harmony import */ var _noodl_models_schemamodel__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_noodl_models_schemamodel__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(11138);





class SchemaHandler {
    constructor() {
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_4__.EventDispatcher.instance.on(['window-focused', 'Model.cloudServicesChanged'], () => {
            if (_noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance) {
                this._fetch();
            }
        }, this);
    }
    dispose() {
        _shared_utils_EventDispatcher__WEBPACK_IMPORTED_MODULE_4__.EventDispatcher.instance.off(this);
    }
    _fetch() {
        return new Promise((resolve) => {
            this.dbCollections = [];
            const activeBroker = (0,_noodl_models_projectmodel_editor__WEBPACK_IMPORTED_MODULE_2__.getCloudServices)(_noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance);
            if (!activeBroker || activeBroker.id === undefined) {
                this.haveCloudServices = false;
                this._store();
                return; // No project broker
            }
            _noodl_models_CloudServices__WEBPACK_IMPORTED_MODULE_0__.CloudService.instance.backend.fetch().then((collection) => {
                // Find by the Url / Endpoint and app id
                let environment = collection.find((b) => {
                    return b.url === activeBroker.endpoint && b.appId === activeBroker.appId;
                });
                // Backwards compatibility:
                //    Make sure that the URL is the same as the one in the database.
                if (!environment) {
                    // Find by the ID
                    environment = collection.find((b) => b.id === activeBroker.id);
                    // Update the stored cloud service
                    if (environment) {
                        (0,_noodl_models_projectmodel_editor__WEBPACK_IMPORTED_MODULE_2__.setCloudServices)(_noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance, {
                            id: environment.id,
                            endpoint: environment.url,
                            appId: environment.appId
                        });
                    }
                }
                this.haveCloudServices = environment !== undefined;
                if (environment === undefined) {
                    this._store();
                    return;
                }
                const opts = {
                    endpoint: environment.url,
                    instanceId: environment.id,
                    masterKey: environment.masterKey,
                    appId: environment.appId
                };
                this.schemaModel = new (_noodl_models_schemamodel__WEBPACK_IMPORTED_MODULE_3___default())(opts);
                const ignoreCollections = ['Ndl_CF']; // Ignore the Ndl_CF collection, containing cloud function deploys
                this.schemaModel.listSchemas({
                    success: (schemas) => {
                        this.dbCollections = schemas
                            .filter((r) => r.name[0] !== '_' && ignoreCollections.indexOf(r.name) == -1)
                            .map((schema) => {
                            return {
                                name: schema.name,
                                schema: {
                                    properties: schema.fields
                                }
                            };
                        });
                        this.systemCollections = schemas
                            .filter((r) => r.name[0] === '_' && ignoreCollections.indexOf(r.name) == -1)
                            .map((schema) => {
                            return {
                                name: schema.name,
                                schema: {
                                    properties: schema.fields
                                }
                            };
                        });
                        // Get the config schema
                        this.schemaModel.getConfigSchema({
                            success: (configSchema) => {
                                this.configSchema = configSchema;
                                this._store();
                                resolve();
                            },
                            error: (e) => {
                                console.log(e);
                            }
                        });
                    },
                    error: (e) => {
                        console.log(e);
                    }
                });
                // Get Parse Server Version & Supported features
                fetch(environment.url + '/serverInfo', {
                    method: 'POST',
                    body: JSON.stringify({
                        "_method": "GET",
                        "_ApplicationId": environment.appId,
                        "_MasterKey": environment.masterKey,
                    })
                })
                    .then((response) => response.json())
                    .then((json) => {
                    this.parseServerVersion = json.parseServerVersion;
                });
            });
        });
    }
    _store() {
        var _a;
        if (_noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance) {
            if (this.haveCloudServices) {
                _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance.setMetaData('dbCollections', this.dbCollections);
                _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance.setMetaData('systemCollections', this.systemCollections);
                _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance.setMetaData('dbConfigSchema', this.configSchema);
                const versionNumbers = (_a = this.parseServerVersion) === null || _a === void 0 ? void 0 : _a.split(".");
                if (versionNumbers && versionNumbers.length > 0) {
                    // Let's only save the major version number,
                    // since this will be used to determine which verison of the API to use.
                    _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance.setMetaData('dbVersionMajor', versionNumbers[0]);
                }
                else {
                    _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance.setMetaData('dbVersionMajor', undefined);
                }
            }
            else {
                _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance.setMetaData('dbCollections', undefined);
                _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance.setMetaData('systemCollections', undefined);
                _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance.setMetaData('dbConfigSchema', undefined);
                _noodl_models_projectmodel__WEBPACK_IMPORTED_MODULE_1__.ProjectModel.instance.setMetaData('dbVersionMajor', undefined);
            }
        }
    }
}


/***/ }),

/***/ 96788:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ToolbarButton-module__Root--We_kX{background:rgba(0,0,0,0);border:none;height:100%;padding-left:6px;padding-right:6px;display:flex;align-items:center;white-space:nowrap;cursor:default}.ToolbarButton-module__Root--We_kX.ToolbarButton-module__actionable--qY42Z{color:var(--theme-color-fg-default) !important;cursor:pointer}.ToolbarButton-module__Root--We_kX.ToolbarButton-module__actionable--qY42Z:hover{background-color:rgba(0,0,0,.2)}.ToolbarButton-module__Text--lEfJ0{color:var(--theme-color-fg-muted);font-family:"OpenSans"}.ToolbarButton-module__Text--lEfJ0.ToolbarButton-module__actionable--qY42Z{color:var(--theme-color-fg-default) !important}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/toolbar/ToolbarButton/ToolbarButton.module.scss"],"names":[],"mappings":"AAAA,mCACE,wBAAA,CACA,WAAA,CACA,WAAA,CACA,gBAAA,CACA,iBAAA,CACA,YAAA,CACA,kBAAA,CACA,kBAAA,CACA,cAAA,CAEA,2EACE,8CAAA,CACA,cAAA,CAEA,iFACE,+BAAA,CAKN,mCAEE,iCAAA,CAGA,sBAAA,CAEA,2EACE,8CAAA","sourcesContent":[".Root {\n  background: transparent;\n  border: none;\n  height: 100%;\n  padding-left: 6px;\n  padding-right: 6px;\n  display: flex;\n  align-items: center;\n  white-space: nowrap;\n  cursor: default;\n\n  &.actionable {\n    color: var(--theme-color-fg-default) !important;\n    cursor: pointer;\n\n    &:hover {\n      background-color: rgba(0, 0, 0, 0.2);\n    }\n  }\n}\n\n.Text {\n  /* Color is slightly different in the popout */\n  color: var(--theme-color-fg-muted);\n\n  /* TODO: Bug there Text doesnt have a font family */\n  font-family: 'OpenSans';\n\n  &.actionable {\n    color: var(--theme-color-fg-default) !important;\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ToolbarButton-module__Root--We_kX`,
	"actionable": `ToolbarButton-module__actionable--qY42Z`,
	"Text": `ToolbarButton-module__Text--lEfJ0`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 97217:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.ExpressionInput-module__Root--S3msm{display:flex;align-items:center;gap:6px;background-color:var(--theme-color-bg-3, rgba(99, 102, 241, 0.05));border:1px solid var(--theme-color-border-default, rgba(99, 102, 241, 0.2));border-radius:4px;padding:4px 8px;flex:1;min-width:0;overflow:hidden;transition:all .15s ease}.ExpressionInput-module__Root--S3msm:focus-within{border-color:var(--theme-color-primary, #6366f1);background-color:var(--theme-color-bg-2, rgba(99, 102, 241, 0.08))}.ExpressionInput-module__Root--S3msm.ExpressionInput-module__HasError--MDgUv{border-color:var(--theme-color-error, #ef4444);background-color:var(--theme-color-bg-2, rgba(239, 68, 68, 0.05))}.ExpressionInput-module__Badge--cQrC2{font-family:"Monaco","Menlo","Ubuntu Mono","Courier New",monospace;font-size:10px;font-weight:600;color:var(--theme-color-primary, #6366f1);padding:2px 4px;background-color:var(--theme-color-bg-2, rgba(99, 102, 241, 0.15));border-radius:2px;flex-shrink:0;user-select:none}.ExpressionInput-module__Input--XfUGO{flex:1;background:rgba(0,0,0,0);border:none;outline:none;font-family:"Monaco","Menlo","Ubuntu Mono","Courier New",monospace;font-size:12px;color:var(--theme-color-fg-default, #ffffff);padding:0;min-width:0}.ExpressionInput-module__Input--XfUGO::placeholder{color:var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.4));opacity:1}.ExpressionInput-module__Input--XfUGO:disabled{opacity:.5;cursor:not-allowed}.ExpressionInput-module__ErrorIndicator--ndF4o{display:flex;align-items:center;justify-content:center;flex-shrink:0;color:var(--theme-color-error, #ef4444);cursor:help}.ExpressionInput-module__ExpandButton--AVFK5{display:flex;align-items:center;justify-content:center;flex-shrink:0;width:20px;height:20px;padding:0;border:none;background:rgba(0,0,0,0);color:var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.5));cursor:pointer;border-radius:2px;transition:all .15s ease}.ExpressionInput-module__ExpandButton--AVFK5:hover{background-color:var(--theme-color-bg-1, rgba(255, 255, 255, 0.1));color:var(--theme-color-primary, #6366f1)}.ExpressionInput-module__ExpandButton--AVFK5:focus{outline:none;background-color:var(--theme-color-bg-1, rgba(255, 255, 255, 0.1))}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/property-panel/ExpressionInput/ExpressionInput.module.scss"],"names":[],"mappings":"AAAA,qCACE,YAAA,CACA,kBAAA,CACA,OAAA,CACA,kEAAA,CACA,2EAAA,CACA,iBAAA,CACA,eAAA,CACA,MAAA,CACA,WAAA,CACA,eAAA,CACA,wBAAA,CAEA,kDACE,gDAAA,CACA,kEAAA,CAGF,6EACE,8CAAA,CACA,iEAAA,CAIJ,sCACE,kEAAA,CACA,cAAA,CACA,eAAA,CACA,yCAAA,CACA,eAAA,CACA,kEAAA,CACA,iBAAA,CACA,aAAA,CACA,gBAAA,CAGF,sCACE,MAAA,CACA,wBAAA,CACA,WAAA,CACA,YAAA,CACA,kEAAA,CACA,cAAA,CACA,4CAAA,CACA,SAAA,CACA,WAAA,CAEA,mDACE,iEAAA,CACA,SAAA,CAGF,+CACE,UAAA,CACA,kBAAA,CAIJ,+CACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,aAAA,CACA,uCAAA,CACA,WAAA,CAGF,6CACE,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,aAAA,CACA,UAAA,CACA,WAAA,CACA,SAAA,CACA,WAAA,CACA,wBAAA,CACA,iEAAA,CACA,cAAA,CACA,iBAAA,CACA,wBAAA,CAEA,mDACE,kEAAA,CACA,yCAAA,CAGF,mDACE,YAAA,CACA,kEAAA","sourcesContent":[".Root {\n  display: flex;\n  align-items: center;\n  gap: 6px;\n  background-color: var(--theme-color-bg-3, rgba(99, 102, 241, 0.05));\n  border: 1px solid var(--theme-color-border-default, rgba(99, 102, 241, 0.2));\n  border-radius: 4px;\n  padding: 4px 8px;\n  flex: 1;\n  min-width: 0; // Allow flex item to shrink below content size\n  overflow: hidden; // Prevent content overflow\n  transition: all 0.15s ease;\n\n  &:focus-within {\n    border-color: var(--theme-color-primary, #6366f1);\n    background-color: var(--theme-color-bg-2, rgba(99, 102, 241, 0.08));\n  }\n\n  &.HasError {\n    border-color: var(--theme-color-error, #ef4444);\n    background-color: var(--theme-color-bg-2, rgba(239, 68, 68, 0.05));\n  }\n}\n\n.Badge {\n  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Courier New', monospace;\n  font-size: 10px;\n  font-weight: 600;\n  color: var(--theme-color-primary, #6366f1);\n  padding: 2px 4px;\n  background-color: var(--theme-color-bg-2, rgba(99, 102, 241, 0.15));\n  border-radius: 2px;\n  flex-shrink: 0;\n  user-select: none;\n}\n\n.Input {\n  flex: 1;\n  background: transparent;\n  border: none;\n  outline: none;\n  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Courier New', monospace;\n  font-size: 12px;\n  color: var(--theme-color-fg-default, #ffffff);\n  padding: 0;\n  min-width: 0;\n\n  &::placeholder {\n    color: var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.4));\n    opacity: 1;\n  }\n\n  &:disabled {\n    opacity: 0.5;\n    cursor: not-allowed;\n  }\n}\n\n.ErrorIndicator {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  flex-shrink: 0;\n  color: var(--theme-color-error, #ef4444);\n  cursor: help;\n}\n\n.ExpandButton {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  flex-shrink: 0;\n  width: 20px;\n  height: 20px;\n  padding: 0;\n  border: none;\n  background: transparent;\n  color: var(--theme-color-fg-default-shy, rgba(255, 255, 255, 0.5));\n  cursor: pointer;\n  border-radius: 2px;\n  transition: all 0.15s ease;\n\n  &:hover {\n    background-color: var(--theme-color-bg-1, rgba(255, 255, 255, 0.1));\n    color: var(--theme-color-primary, #6366f1);\n  }\n\n  &:focus {\n    outline: none;\n    background-color: var(--theme-color-bg-1, rgba(255, 255, 255, 0.1));\n  }\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `ExpressionInput-module__Root--S3msm`,
	"HasError": `ExpressionInput-module__HasError--MDgUv`,
	"Badge": `ExpressionInput-module__Badge--cQrC2`,
	"Input": `ExpressionInput-module__Input--XfUGO`,
	"ErrorIndicator": `ExpressionInput-module__ErrorIndicator--ndF4o`,
	"ExpandButton": `ExpressionInput-module__ExpandButton--AVFK5`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 97444:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_params, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_logger, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.BetaMessageStream = void 0;
const tslib_1 = __webpack_require__(84499);
const parser_1 = __webpack_require__(27877);
const error_1 = __webpack_require__(92651);
const errors_1 = __webpack_require__(29820);
const streaming_1 = __webpack_require__(53353);
const beta_parser_1 = __webpack_require__(96047);
const JSON_BUF_PROPERTY = '__json_buf';
function tracksToolInput(content) {
    return content.type === 'tool_use' || content.type === 'server_tool_use' || content.type === 'mcp_tool_use';
}
class BetaMessageStream {
    constructor(params, opts) {
        _BetaMessageStream_instances.add(this);
        this.messages = [];
        this.receivedMessages = [];
        _BetaMessageStream_currentMessageSnapshot.set(this, void 0);
        _BetaMessageStream_params.set(this, null);
        this.controller = new AbortController();
        _BetaMessageStream_connectedPromise.set(this, void 0);
        _BetaMessageStream_resolveConnectedPromise.set(this, () => { });
        _BetaMessageStream_rejectConnectedPromise.set(this, () => { });
        _BetaMessageStream_endPromise.set(this, void 0);
        _BetaMessageStream_resolveEndPromise.set(this, () => { });
        _BetaMessageStream_rejectEndPromise.set(this, () => { });
        _BetaMessageStream_listeners.set(this, {});
        _BetaMessageStream_ended.set(this, false);
        _BetaMessageStream_errored.set(this, false);
        _BetaMessageStream_aborted.set(this, false);
        _BetaMessageStream_catchingPromiseCreated.set(this, false);
        _BetaMessageStream_response.set(this, void 0);
        _BetaMessageStream_request_id.set(this, void 0);
        _BetaMessageStream_logger.set(this, void 0);
        _BetaMessageStream_handleError.set(this, (error) => {
            tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f");
            if ((0, errors_1.isAbortError)(error)) {
                error = new error_1.APIUserAbortError();
            }
            if (error instanceof error_1.APIUserAbortError) {
                tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f");
                return this._emit('abort', error);
            }
            if (error instanceof error_1.AnthropicError) {
                return this._emit('error', error);
            }
            if (error instanceof Error) {
                const anthropicError = new error_1.AnthropicError(error.message);
                // @ts-ignore
                anthropicError.cause = error;
                return this._emit('error', anthropicError);
            }
            return this._emit('error', new error_1.AnthropicError(String(error)));
        });
        tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => {
            tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f");
            tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f");
        }), "f");
        tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => {
            tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f");
            tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f");
        }), "f");
        // Don't let these promises cause unhandled rejection errors.
        // we will manually cause an unhandled rejection error later
        // if the user hasn't registered any error listener or called
        // any promise-returning method.
        tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => { });
        tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => { });
        tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_params, params, "f");
        tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_logger, opts?.logger ?? console, "f");
    }
    get response() {
        return tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_response, "f");
    }
    get request_id() {
        return tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_request_id, "f");
    }
    /**
     * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
     * returned vie the `request-id` header which is useful for debugging requests and resporting
     * issues to Anthropic.
     *
     * This is the same as the `APIPromise.withResponse()` method.
     *
     * This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
     * as no `Response` is available.
     */
    async withResponse() {
        tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
        const response = await tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f");
        if (!response) {
            throw new Error('Could not resolve a `Response` object');
        }
        return {
            data: this,
            response,
            request_id: response.headers.get('request-id'),
        };
    }
    /**
     * Intended for use on the frontend, consuming a stream produced with
     * `.toReadableStream()` on the backend.
     *
     * Note that messages sent to the model do not appear in `.on('message')`
     * in this context.
     */
    static fromReadableStream(stream) {
        const runner = new BetaMessageStream(null);
        runner._run(() => runner._fromReadableStream(stream));
        return runner;
    }
    static createMessage(messages, params, options, { logger } = {}) {
        const runner = new BetaMessageStream(params, { logger });
        for (const message of params.messages) {
            runner._addMessageParam(message);
        }
        tslib_1.__classPrivateFieldSet(runner, _BetaMessageStream_params, { ...params, stream: true }, "f");
        runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }));
        return runner;
    }
    _run(executor) {
        executor().then(() => {
            this._emitFinal();
            this._emit('end');
        }, tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_handleError, "f"));
    }
    _addMessageParam(message) {
        this.messages.push(message);
    }
    _addMessage(message, emit = true) {
        this.receivedMessages.push(message);
        if (emit) {
            this._emit('message', message);
        }
    }
    async _createMessage(messages, params, options) {
        const signal = options?.signal;
        let abortHandler;
        if (signal) {
            if (signal.aborted)
                this.controller.abort();
            abortHandler = this.controller.abort.bind(this.controller);
            signal.addEventListener('abort', abortHandler);
        }
        try {
            tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
            const { response, data: stream } = await messages
                .create({ ...params, stream: true }, { ...options, signal: this.controller.signal })
                .withResponse();
            this._connected(response);
            for await (const event of stream) {
                tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
            }
            if (stream.controller.signal?.aborted) {
                throw new error_1.APIUserAbortError();
            }
            tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
        }
        finally {
            if (signal && abortHandler) {
                signal.removeEventListener('abort', abortHandler);
            }
        }
    }
    _connected(response) {
        if (this.ended)
            return;
        tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_response, response, "f");
        tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get('request-id'), "f");
        tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response);
        this._emit('connect');
    }
    get ended() {
        return tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_ended, "f");
    }
    get errored() {
        return tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_errored, "f");
    }
    get aborted() {
        return tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_aborted, "f");
    }
    abort() {
        this.controller.abort();
    }
    /**
     * Adds the listener function to the end of the listeners array for the event.
     * No checks are made to see if the listener has already been added. Multiple calls passing
     * the same combination of event and listener will result in the listener being added, and
     * called, multiple times.
     * @returns this MessageStream, so that calls can be chained
     */
    on(event, listener) {
        const listeners = tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []);
        listeners.push({ listener });
        return this;
    }
    /**
     * Removes the specified listener from the listener array for the event.
     * off() will remove, at most, one instance of a listener from the listener array. If any single
     * listener has been added multiple times to the listener array for the specified event, then
     * off() must be called multiple times to remove each instance.
     * @returns this MessageStream, so that calls can be chained
     */
    off(event, listener) {
        const listeners = tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event];
        if (!listeners)
            return this;
        const index = listeners.findIndex((l) => l.listener === listener);
        if (index >= 0)
            listeners.splice(index, 1);
        return this;
    }
    /**
     * Adds a one-time listener function for the event. The next time the event is triggered,
     * this listener is removed and then invoked.
     * @returns this MessageStream, so that calls can be chained
     */
    once(event, listener) {
        const listeners = tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []);
        listeners.push({ listener, once: true });
        return this;
    }
    /**
     * This is similar to `.once()`, but returns a Promise that resolves the next time
     * the event is triggered, instead of calling a listener callback.
     * @returns a Promise that resolves the next time given event is triggered,
     * or rejects if an error is emitted.  (If you request the 'error' event,
     * returns a promise that resolves with the error).
     *
     * Example:
     *
     *   const message = await stream.emitted('message') // rejects if the stream errors
     */
    emitted(event) {
        return new Promise((resolve, reject) => {
            tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
            if (event !== 'error')
                this.once('error', reject);
            this.once(event, resolve);
        });
    }
    async done() {
        tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
        await tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f");
    }
    get currentMessage() {
        return tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
    }
    /**
     * @returns a promise that resolves with the the final assistant Message response,
     * or rejects if an error occurred or the stream ended prematurely without producing a Message.
     * If structured outputs were used, this will be a ParsedMessage with a `parsed` field.
     */
    async finalMessage() {
        await this.done();
        return tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this);
    }
    /**
     * @returns a promise that resolves with the the final assistant Message's text response, concatenated
     * together if there are more than one text blocks.
     * Rejects if an error occurred or the stream ended prematurely without producing a Message.
     */
    async finalText() {
        await this.done();
        return tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this);
    }
    _emit(event, ...args) {
        // make sure we don't emit any MessageStreamEvents after end
        if (tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_ended, "f"))
            return;
        if (event === 'end') {
            tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f");
            tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this);
        }
        const listeners = tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event];
        if (listeners) {
            tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
            listeners.forEach(({ listener }) => listener(...args));
        }
        if (event === 'abort') {
            const error = args[0];
            if (!tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
                Promise.reject(error);
            }
            tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
            tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
            this._emit('end');
            return;
        }
        if (event === 'error') {
            // NOTE: _emit('error', error) should only be called from #handleError().
            const error = args[0];
            if (!tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
                // Trigger an unhandled rejection if the user hasn't registered any error handlers.
                // If you are seeing stack traces here, make sure to handle errors via either:
                // - runner.on('error', () => ...)
                // - await runner.done()
                // - await runner.final...()
                // - etc.
                Promise.reject(error);
            }
            tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
            tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
            this._emit('end');
        }
    }
    _emitFinal() {
        const finalMessage = this.receivedMessages.at(-1);
        if (finalMessage) {
            this._emit('finalMessage', tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this));
        }
    }
    async _fromReadableStream(readableStream, options) {
        const signal = options?.signal;
        let abortHandler;
        if (signal) {
            if (signal.aborted)
                this.controller.abort();
            abortHandler = this.controller.abort.bind(this.controller);
            signal.addEventListener('abort', abortHandler);
        }
        try {
            tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
            this._connected(null);
            const stream = streaming_1.Stream.fromReadableStream(readableStream, this.controller);
            for await (const event of stream) {
                tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
            }
            if (stream.controller.signal?.aborted) {
                throw new error_1.APIUserAbortError();
            }
            tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
        }
        finally {
            if (signal && abortHandler) {
                signal.removeEventListener('abort', abortHandler);
            }
        }
    }
    [(_BetaMessageStream_currentMessageSnapshot = new WeakMap(), _BetaMessageStream_params = new WeakMap(), _BetaMessageStream_connectedPromise = new WeakMap(), _BetaMessageStream_resolveConnectedPromise = new WeakMap(), _BetaMessageStream_rejectConnectedPromise = new WeakMap(), _BetaMessageStream_endPromise = new WeakMap(), _BetaMessageStream_resolveEndPromise = new WeakMap(), _BetaMessageStream_rejectEndPromise = new WeakMap(), _BetaMessageStream_listeners = new WeakMap(), _BetaMessageStream_ended = new WeakMap(), _BetaMessageStream_errored = new WeakMap(), _BetaMessageStream_aborted = new WeakMap(), _BetaMessageStream_catchingPromiseCreated = new WeakMap(), _BetaMessageStream_response = new WeakMap(), _BetaMessageStream_request_id = new WeakMap(), _BetaMessageStream_logger = new WeakMap(), _BetaMessageStream_handleError = new WeakMap(), _BetaMessageStream_instances = new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() {
        if (this.receivedMessages.length === 0) {
            throw new error_1.AnthropicError('stream ended without producing a Message with role=assistant');
        }
        return this.receivedMessages.at(-1);
    }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText() {
        if (this.receivedMessages.length === 0) {
            throw new error_1.AnthropicError('stream ended without producing a Message with role=assistant');
        }
        const textBlocks = this.receivedMessages
            .at(-1)
            .content.filter((block) => block.type === 'text')
            .map((block) => block.text);
        if (textBlocks.length === 0) {
            throw new error_1.AnthropicError('stream ended without producing a content block with type=text');
        }
        return textBlocks.join(' ');
    }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest() {
        if (this.ended)
            return;
        tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f");
    }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent(event) {
        if (this.ended)
            return;
        const messageSnapshot = tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event);
        this._emit('streamEvent', event, messageSnapshot);
        switch (event.type) {
            case 'content_block_delta': {
                const content = messageSnapshot.content.at(-1);
                switch (event.delta.type) {
                    case 'text_delta': {
                        if (content.type === 'text') {
                            this._emit('text', event.delta.text, content.text || '');
                        }
                        break;
                    }
                    case 'citations_delta': {
                        if (content.type === 'text') {
                            this._emit('citation', event.delta.citation, content.citations ?? []);
                        }
                        break;
                    }
                    case 'input_json_delta': {
                        if (tracksToolInput(content) && content.input) {
                            this._emit('inputJson', event.delta.partial_json, content.input);
                        }
                        break;
                    }
                    case 'thinking_delta': {
                        if (content.type === 'thinking') {
                            this._emit('thinking', event.delta.thinking, content.thinking);
                        }
                        break;
                    }
                    case 'signature_delta': {
                        if (content.type === 'thinking') {
                            this._emit('signature', content.signature);
                        }
                        break;
                    }
                    default:
                        checkNever(event.delta);
                }
                break;
            }
            case 'message_stop': {
                this._addMessageParam(messageSnapshot);
                this._addMessage((0, beta_parser_1.maybeParseBetaMessage)(messageSnapshot, tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }), true);
                break;
            }
            case 'content_block_stop': {
                this._emit('contentBlock', messageSnapshot.content.at(-1));
                break;
            }
            case 'message_start': {
                tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f");
                break;
            }
            case 'content_block_start':
            case 'message_delta':
                break;
        }
    }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest() {
        if (this.ended) {
            throw new error_1.AnthropicError(`stream has ended, this shouldn't happen`);
        }
        const snapshot = tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
        if (!snapshot) {
            throw new error_1.AnthropicError(`request ended without sending any chunks`);
        }
        tslib_1.__classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f");
        return (0, beta_parser_1.maybeParseBetaMessage)(snapshot, tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_logger, "f") });
    }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage(event) {
        let snapshot = tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
        if (event.type === 'message_start') {
            if (snapshot) {
                throw new error_1.AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
            }
            return event.message;
        }
        if (!snapshot) {
            throw new error_1.AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
        }
        switch (event.type) {
            case 'message_stop':
                return snapshot;
            case 'message_delta':
                snapshot.container = event.delta.container;
                snapshot.stop_reason = event.delta.stop_reason;
                snapshot.stop_sequence = event.delta.stop_sequence;
                snapshot.usage.output_tokens = event.usage.output_tokens;
                snapshot.context_management = event.context_management;
                if (event.usage.input_tokens != null) {
                    snapshot.usage.input_tokens = event.usage.input_tokens;
                }
                if (event.usage.cache_creation_input_tokens != null) {
                    snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
                }
                if (event.usage.cache_read_input_tokens != null) {
                    snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
                }
                if (event.usage.server_tool_use != null) {
                    snapshot.usage.server_tool_use = event.usage.server_tool_use;
                }
                return snapshot;
            case 'content_block_start':
                snapshot.content.push(event.content_block);
                return snapshot;
            case 'content_block_delta': {
                const snapshotContent = snapshot.content.at(event.index);
                switch (event.delta.type) {
                    case 'text_delta': {
                        if (snapshotContent?.type === 'text') {
                            snapshot.content[event.index] = {
                                ...snapshotContent,
                                text: (snapshotContent.text || '') + event.delta.text,
                            };
                        }
                        break;
                    }
                    case 'citations_delta': {
                        if (snapshotContent?.type === 'text') {
                            snapshot.content[event.index] = {
                                ...snapshotContent,
                                citations: [...(snapshotContent.citations ?? []), event.delta.citation],
                            };
                        }
                        break;
                    }
                    case 'input_json_delta': {
                        if (snapshotContent && tracksToolInput(snapshotContent)) {
                            // we need to keep track of the raw JSON string as well so that we can
                            // re-parse it for each delta, for now we just store it as an untyped
                            // non-enumerable property on the snapshot
                            let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || '';
                            jsonBuf += event.delta.partial_json;
                            const newContent = { ...snapshotContent };
                            Object.defineProperty(newContent, JSON_BUF_PROPERTY, {
                                value: jsonBuf,
                                enumerable: false,
                                writable: true,
                            });
                            if (jsonBuf) {
                                try {
                                    newContent.input = (0, parser_1.partialParse)(jsonBuf);
                                }
                                catch (err) {
                                    const error = new error_1.AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`);
                                    tslib_1.__classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error);
                                }
                            }
                            snapshot.content[event.index] = newContent;
                        }
                        break;
                    }
                    case 'thinking_delta': {
                        if (snapshotContent?.type === 'thinking') {
                            snapshot.content[event.index] = {
                                ...snapshotContent,
                                thinking: snapshotContent.thinking + event.delta.thinking,
                            };
                        }
                        break;
                    }
                    case 'signature_delta': {
                        if (snapshotContent?.type === 'thinking') {
                            snapshot.content[event.index] = {
                                ...snapshotContent,
                                signature: event.delta.signature,
                            };
                        }
                        break;
                    }
                    default:
                        checkNever(event.delta);
                }
                return snapshot;
            }
            case 'content_block_stop':
                return snapshot;
        }
    }, Symbol.asyncIterator)]() {
        const pushQueue = [];
        const readQueue = [];
        let done = false;
        this.on('streamEvent', (event) => {
            const reader = readQueue.shift();
            if (reader) {
                reader.resolve(event);
            }
            else {
                pushQueue.push(event);
            }
        });
        this.on('end', () => {
            done = true;
            for (const reader of readQueue) {
                reader.resolve(undefined);
            }
            readQueue.length = 0;
        });
        this.on('abort', (err) => {
            done = true;
            for (const reader of readQueue) {
                reader.reject(err);
            }
            readQueue.length = 0;
        });
        this.on('error', (err) => {
            done = true;
            for (const reader of readQueue) {
                reader.reject(err);
            }
            readQueue.length = 0;
        });
        return {
            next: async () => {
                if (!pushQueue.length) {
                    if (done) {
                        return { value: undefined, done: true };
                    }
                    return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));
                }
                const chunk = pushQueue.shift();
                return { value: chunk, done: false };
            },
            return: async () => {
                this.abort();
                return { value: undefined, done: true };
            },
        };
    }
    toReadableStream() {
        const stream = new streaming_1.Stream(this[Symbol.asyncIterator].bind(this), this.controller);
        return stream.toReadableStream();
    }
}
exports.BetaMessageStream = BetaMessageStream;
// used to ensure exhaustive case matching without throwing a runtime error
function checkNever(x) { }
//# sourceMappingURL=BetaMessageStream.js.map

/***/ }),

/***/ 97467:
/***/ ((module) => {

// Module
var code = "<div style=\"width:400px\" data-indent-offset=\"20\"> <div data-template=\"folder\" class=\"import-popup-folder\" style=\"width:100%;position:relative\"> <div style=\"width:100%;height:24px;position:relative\"> <div class=\"sidebar-panel-dark-input\" style=\"position:absolute;left:2px;width:24px;top:3px;bottom:3px\" data-click=\"onFolderBoxClicked\"> <i class=\"fa fa-check\" data-class=\"!import:hidden,implicit:import-popup-implicit-check,import:import-popup-import-check\" style=\"position:absolute;left:7px;top:5px\"></i> </div> <div class=\"indent-me\" style=\"width:100%;height:24px;position:absolute\" data-click=\"onFolderClicked\"> <div style=\"position:absolute;width:28px;top:4px;bottom:4px\"> <i class=\"fa\" data-class=\"open:fa-caret-down,!open:fa-caret-right\"></i> </div> <div style=\"line-height:20px;position:absolute;left:10px;top:3px;bottom:3px;right:3px\" data-text=\"localName\"></div> </div> </div> <div class=\"content\" style=\"\"></div> </div> <div data-template=\"item\" class=\"import-popup-item\" style=\"width:100%;height:24px;position:relative\"> <div class=\"sidebar-panel-dark-input\" style=\"position:absolute;left:2px;width:24px;top:3px;bottom:3px\" data-click=\"onBoxClicked\"> <i class=\"fa fa-check\" data-class=\"!check:hidden,implicit:import-popup-implicit-check,import:import-popup-import-check\" style=\"position:absolute;left:7px;top:5px\"></i> </div> <div class=\"indent-me\" style=\"line-height:20px;position:absolute;top:3px;bottom:3px;right:3px\" data-text=\"localName\"></div> </div> <div style=\"height:700px;overflow:hidden;overflow-y:overlay\"> <div data-class=\"!hasComponents:hidden\"> <label class=\"popup-group-label\" style=\"position:sticky;z-index:1;top:0\">COMPONENTS</label> <div class=\"import-popup-text\">Select which components to export from the project.</div> <div class=\"components\" style=\"margin-top:10px\"></div> </div> <div data-class=\"!hasResources:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\" style=\"position:sticky;z-index:1;top:0\">RESOURCES</label> <div class=\"import-popup-text\">Select which resources to export from the project.</div> <div class=\"resources\" style=\"margin-top:10px\"></div> </div> <div data-class=\"!hasModules:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\" style=\"position:sticky;z-index:1;top:0\">MODULES</label> <div class=\"import-popup-text\">Select which modules to export from the project.</div> <div class=\"modules\" style=\"margin-top:10px\"></div> </div> <div data-class=\"!hasVariants:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\" style=\"position:sticky;z-index:1;top:0\">VARIANTS</label> <div class=\"import-popup-text\">Select which variants to export from the project.</div> <div class=\"variants\" style=\"margin-top:10px\"></div> </div> <div data-class=\"!hasColorStyles:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\" style=\"position:sticky;z-index:1;top:0\">COLOR STYLES</label> <div class=\"import-popup-text\">Select which color styles to export from the project.</div> <div class=\"color-styles\" style=\"margin-top:10px\"></div> </div> <div data-class=\"!hasTextStyles:hidden\" style=\"margin-top:20px\"> <label class=\"popup-group-label\" style=\"position:sticky;z-index:1;top:0\">TEXT STYLES</label> <div class=\"import-popup-text\">Select which text styles to export from the project.</div> <div class=\"text-styles\" style=\"margin-top:10px\"></div> </div> <div style=\"height:30px;padding:5px;padding-bottom:10px;margin-top:20px\"> <button class=\"popup-button\" data-click=\"onOkClicked\">EXPORT</button> <button class=\"popup-button-grey\" data-click=\"onCancelClicked\">CANCEL</button> </div> </div> </div> ";
// Exports
module.exports = code;

/***/ }),

/***/ 97478:
/***/ ((__unused_webpack_module, __unused_webpack___webpack_exports__, __webpack_require__) => {

"use strict";

// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/index.ts
var nodelibrary = __webpack_require__(68091);
// EXTERNAL MODULE: ./src/editor/src/models/NodeTypeAdapters/NodeTypeAdapter.ts
var NodeTypeAdapter = __webpack_require__(35715);
;// ./src/editor/src/models/NodeTypeAdapters/AggregateRecordsAdapter.ts

class AggregateRecordsAdapter extends NodeTypeAdapter/* default */.A {
    constructor() {
        super('noodl.cloud.aggregate');
        this.events = {
            'parametersChanged:noodl.cloud.aggregate': this.parametersChanged.bind(this)
        };
    }
    parametersChanged(e) {
        const node = e.model;
        // Only reset if the class has changed and there is an undo group
        if (e.args.name === 'collectionName' && e.args.oldValue !== e.args.value && e.args.undo) {
            // The Class of the query records node has changed
            // clear the visual filter
            node.setParameter('visualFilter', undefined, { undo: e.args.undo });
        }
    }
}

// EXTERNAL MODULE: ./src/editor/src/models/componentmodel.ts
var componentmodel = __webpack_require__(16163);
// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.ts + 4 modules
var projectmodel = __webpack_require__(6203);
;// ./src/editor/src/models/NodeTypeAdapters/CloudFunctionAdapter.ts



class CloudFunctionAdapter extends NodeTypeAdapter/* default */.A {
    constructor() {
        super('CloudFunction2');
        this.events = {
            componentAdded: this.componentAddedOrRemoved.bind(this),
            componentRemoved: this.componentAddedOrRemoved.bind(this),
            componentRenamed: this.componentRenamed.bind(this),
            nodeAdded: this.nodeAddedOrRemoved.bind(this),
            nodeRemoved: this.nodeAddedOrRemoved.bind(this),
            'nodeAdded:CloudFunction2': this.functionNodeAdded.bind(this),
            'nodeAdded:noodl.cloud.request': this.updateAllFunctionsPorts.bind(this),
            'nodeRemoved:noodl.cloud.request': this.updateAllFunctionsPorts.bind(this),
            'nodeAdded:noodl.cloud.response': this.updateAllFunctionsPorts.bind(this),
            'nodeRemoved:noodl.cloud.response': this.updateAllFunctionsPorts.bind(this),
            projectLoaded: this.updateAllFunctionsPorts.bind(this),
            'parametersChanged:noodl.cloud.request': this.updateAllFunctionsPorts.bind(this),
            'parametersChanged:noodl.cloud.response': this.updateAllFunctionsPorts.bind(this),
            'parametersChanged:CloudFunction2': this.functionParametersChanged.bind(this) //update if a router name has changed
        };
    }
    componentAddedOrRemoved(e) {
        const componentName = e.model.fullName;
        if (componentName.startsWith('/#__cloud__/')) {
            // A cloud function node is possibly removed, update all functions
            this.updateAllFunctionsPorts();
        }
    }
    componentRenamed(e) {
        const before = e.oldName;
        const after = e.model.fullName;
        // Note: No need to handle undo here as it will simply revert back to a new renamne
        // Find all functions that have this component as it's function and change
        const functionNodes = this.findAllNodes();
        functionNodes.forEach((f) => {
            if ('/#__cloud__/' + f.parameters['function'] === before) {
                f.setParameter('function', after.replace('/#__cloud__/', ''));
            }
        });
        this.updateAllFunctionsPorts();
    }
    updatePortsForNode(node) {
        const ports = [];
        // Collect all cloud function components
        const functionRequestNodes = projectmodel.ProjectModel.instance.getNodesWithType('noodl.cloud.request');
        const functions = functionRequestNodes.map((r) => {
            const component = r.owner.owner;
            return component.fullName;
        });
        ports.push({
            plug: 'input',
            type: {
                name: 'component',
                components: functions,
                ignoreSheetName: true,
                allowEditOnly: true
            },
            group: 'General',
            displayName: 'Function',
            name: 'function'
        });
        if (node.parameters['function'] !== undefined) {
            const component = projectmodel.ProjectModel.instance.getComponentWithName('/#__cloud__/' + node.parameters['function']);
            if (component !== undefined) {
                // Collect inputs from request nodes
                const functionRequests = component.getNodesWithType('noodl.cloud.request');
                if (functionRequests !== undefined) {
                    const uniqueNames = {};
                    functionRequests.forEach((pi) => {
                        if (pi.parameters['params'] !== undefined)
                            pi.parameters['params'].split(',').forEach((p) => (uniqueNames[p] = true));
                    });
                    Object.keys(uniqueNames).forEach((inputName) => {
                        ports.push({
                            name: 'in-' + inputName,
                            displayName: inputName,
                            type: '*',
                            plug: 'input',
                            group: 'Parameters'
                        });
                    });
                }
                // Collect outputs from response nodes
                const functionResponses = component.getNodesWithTypeRecursive('noodl.cloud.response');
                const uniqueNames = {};
                functionResponses.forEach((pi) => {
                    if (pi.parameters['params'] !== undefined)
                        pi.parameters['params'].split(',').forEach((p) => (uniqueNames[p] = true));
                });
                Object.keys(uniqueNames).forEach((inputName) => {
                    ports.push({
                        name: 'out-' + inputName,
                        displayName: inputName,
                        type: '*',
                        plug: 'output',
                        group: 'Results'
                    });
                });
            }
        }
        node.setDynamicPorts(ports);
    }
    functionNodeAdded(e) {
        this.updatePortsForNode(e.args.model);
    }
    nodeAddedOrRemoved(e) {
        const type = e.args.model.type;
        if (type instanceof componentmodel/* ComponentModel */.j && //is this node an instance of a component?
            type.fullName.startsWith('/#__cloud__/') && //...in a cloud function?
            type.graph.forEachNodeRecursive((n) => n.type.name === 'noodl.cloud.response') //...and has a response node?
        ) {
            this.updateAllFunctionsPorts();
        }
    }
    updateAllFunctionsPorts() {
        // We need to update all function nodes
        const functionNodes = this.findAllNodes();
        functionNodes.forEach((node) => {
            this.updatePortsForNode(node);
        });
    }
    functionParametersChanged(e) {
        this.updatePortsForNode(e.model);
    }
}

;// ./src/editor/src/models/NodeTypeAdapters/FilterRecordsAdapter.ts

class FilterRecordsAdapter extends NodeTypeAdapter/* default */.A {
    constructor() {
        super('FilterDBModels');
        this.events = {
            'parametersChanged:FilterDBModels': this.parametersChanged.bind(this)
        };
    }
    parametersChanged(e) {
        const node = e.model;
        // Only reset if the class has changed and there is an undo group
        if (e.args.name === 'collectionName' && e.args.oldValue !== e.args.value && e.args.undo) {
            // The Class of the query records node has changed
            // clear the visual filter and sorting
            node.setParameter('visualFilter', undefined, { undo: e.args.undo });
            node.setParameter('visualSorting', undefined, { undo: e.args.undo });
        }
    }
}

;// ./src/editor/src/models/NodeTypeAdapters/PageInputsAdapter.ts

class PageInputsAdapter extends NodeTypeAdapter/* default */.A {
    constructor() {
        super('PageInputs');
        this.events = {
            'nodeAdded:PageInputs': this.nodeAdded.bind(this),
            projectLoaded: this.updateAllNodes.bind(this),
            'parametersChanged:PageInputs': this.parametersChanged.bind(this)
        };
    }
    updatePortsForNode(node) {
        const ports = [];
        const uniqueNames = {};
        if (node.parameters['pathParams'] !== undefined) {
            node.parameters['pathParams'].split(',').forEach((p) => {
                uniqueNames[p] = true;
            });
        }
        if (node.parameters['queryParams'] !== undefined) {
            node.parameters['queryParams'].split(',').forEach((p) => {
                uniqueNames[p] = true;
            });
        }
        Object.keys(uniqueNames).forEach((outputName) => {
            ports.push({
                name: 'pm-' + outputName,
                displayName: outputName,
                type: '*',
                plug: 'output',
                group: 'Parameters'
            });
        });
        node.setDynamicPorts(ports);
    }
    nodeAdded(e) {
        const node = e.args.model;
        const component = node.owner.owner;
        if (component !== undefined) {
            const pageInputs = component.getNodesWithType('PageInputs');
            for (const pi of pageInputs) {
                if (pi !== node) {
                    node.parameters['queryParams'] = pi.parameters['queryParams'];
                    node.parameters['pathParams'] = pi.parameters['pathParams'];
                    break;
                }
            }
        }
        this.updatePortsForNode(node);
    }
    parametersChanged(e) {
        const node = e.model;
        if (this._copyParamsScheduled)
            return;
        this._copyParamsScheduled = true;
        // Copy parameters from this node to all other to keep in sync
        const component = node.owner.owner;
        if (component !== undefined) {
            const pageInputs = component.getNodesWithType('PageInputs');
            pageInputs.forEach((pi) => {
                if (pi !== node) {
                    pi.setParameter('queryParams', node.parameters['queryParams'], { undo: e.args.undo });
                    pi.setParameter('pathParams', node.parameters['pathParams'], { undo: e.args.undo });
                }
                this.updatePortsForNode(pi);
            });
        }
        this._copyParamsScheduled = false;
    }
    updateAllNodes(e) {
        // We need to update all navigation nodes
        const pageInputs = this.findAllNodes();
        pageInputs.forEach((node) => {
            this.updatePortsForNode(node);
        });
    }
}

;// ./src/editor/src/models/NodeTypeAdapters/QueryRecordsAdapter.ts

class QueryRecordsAdapter extends NodeTypeAdapter/* default */.A {
    constructor() {
        super('DbCollection2');
        this.events = {
            'parametersChanged:DbCollection2': this.parametersChanged.bind(this)
        };
    }
    parametersChanged(e) {
        const node = e.model;
        // Only reset if the class has changed and there is an undo group
        if (e.args.name === 'collectionName' && e.args.oldValue !== e.args.value && e.args.undo) {
            // The Class of the query records node has changed
            // clear the visual filter and sorting
            node.setParameter('visualFilter', undefined, { undo: e.args.undo });
            node.setParameter('visualSort', undefined, { undo: e.args.undo });
        }
    }
}

// EXTERNAL MODULE: ./src/editor/src/models/NodeTypeAdapters/RouterAdapter.ts
var RouterAdapter = __webpack_require__(5604);
// EXTERNAL MODULE: ./src/editor/src/models/warningsmodel.ts
var warningsmodel = __webpack_require__(86105);
;// ./src/editor/src/models/NodeTypeAdapters/RouterNavigateAdapter.ts



class RouterNavigateAdapter extends NodeTypeAdapter/* default */.A {
    constructor() {
        super('RouterNavigate');
        this.events = {
            'nodeAdded:RouterNavigate': this.navigateNodeAdded.bind(this),
            'nodeAdded:Router': this.updateAllRouterPorts.bind(this),
            'nodeRemoved:Router': this.updateAllRouterPorts.bind(this),
            projectLoaded: this.updateAllRouterPorts.bind(this),
            'parametersChanged:RouterNavigate': this.updateRouterPorts.bind(this),
            'parametersChanged:PageInputs': this.updateAllRouterPorts.bind(this),
            'parametersChanged:Router': this.routerParametersChanged.bind(this) //update if a router name has changed
        };
    }
    updatePortsForNode(node) {
        const ports = [];
        const routers = projectmodel.ProjectModel.instance.getNodesWithType('Router').filter((r) => r.parameters['name'] !== undefined);
        if (routers.length > 1) {
            ports.push({
                plug: 'input',
                type: {
                    name: 'enum',
                    enums: routers.map((r) => ({ label: r.parameters['name'], value: r.parameters['name'] })),
                    allowEditOnly: true
                },
                group: 'General',
                displayName: 'Router',
                name: 'router'
            });
        }
        let routerName = node.parameters['router'];
        if (routerName === undefined && routers.length > 0) {
            // No router selected, just pick the first one
            routerName = routers[0].parameters['name'];
            node.setParameter('router', routerName);
        }
        // Router is selected find all pages and show in pages enum
        const pageComponents = [];
        routers
            .filter((r) => r.parameters['name'] === routerName)
            .forEach((r) => {
            if (r.parameters['pages'] !== undefined && r.parameters['pages'].routes !== undefined) {
                r.parameters['pages'].routes.forEach((pc) => {
                    if (pageComponents.indexOf(pc) === -1)
                        pageComponents.push(pc);
                });
            }
        });
        ports.push({
            plug: 'input',
            type: { name: 'component', title: 'Choose page component', components: pageComponents, allowEditOnly: true },
            group: 'General',
            displayName: 'Target Page',
            name: 'target'
        });
        if (node.parameters['target'] !== undefined) {
            const component = projectmodel.ProjectModel.instance.getComponentWithName(node.parameters['target']);
            if (component !== undefined) {
                const pageInputs = component.getNodesWithType('PageInputs');
                if (pageInputs !== undefined) {
                    const uniqueNames = {};
                    pageInputs.forEach((pi) => {
                        if (pi.parameters['pathParams'] !== undefined)
                            pi.parameters['pathParams'].split(',').forEach((p) => (uniqueNames[p] = true));
                        if (pi.parameters['queryParams'] !== undefined)
                            pi.parameters['queryParams'].split(',').forEach((p) => (uniqueNames[p] = true));
                    });
                    Object.keys(uniqueNames).forEach((inputName) => {
                        ports.push({
                            name: 'pm-' + inputName,
                            displayName: inputName,
                            type: 'string',
                            plug: 'input',
                            group: 'Parameters'
                        });
                    });
                }
            }
        }
        this.evaluateHealth(node, pageComponents);
        node.setDynamicPorts(ports);
    }
    evaluateHealth(node, pageComponents) {
        const target = node.parameters['target'];
        const hasValidTarget = target && pageComponents.includes(target);
        const warning = hasValidTarget === false
            ? {
                message: "The target page doesn't belong to the target router",
                level: 'error',
                showGlobally: true
            }
            : undefined;
        const componentModel = node.owner.owner;
        warningsmodel/* WarningsModel */.l.instance.setWarning({ component: componentModel, node, key: 'routernav-target-not-in-router' }, warning);
    }
    navigateNodeAdded(e) {
        this.updatePortsForNode(e.args.model);
    }
    updateRouterPorts(e) {
        this.updatePortsForNode(e.model);
    }
    updateAllRouterPorts() {
        // We need to update all navigation nodes
        const navigateNodes = this.findAllNodes();
        navigateNodes.forEach((node) => {
            this.updatePortsForNode(node);
        });
    }
    routerParametersChanged(e) {
        // The name of a router has changed, update all navigate nodes with that name
        // No need for an undo here, the value will just changed back when the router renamed is "undone"
        if (e.args.name === 'name' && e.args.oldValue !== e.args.value) {
            const navigateNodes = this.findAllNodes();
            navigateNodes.forEach((node) => {
                if (node.parameters['router'] === e.args.oldValue) {
                    node.parameters['router'] = e.args.value;
                }
            });
        }
        this.updateAllRouterPorts();
    }
}

// EXTERNAL MODULE: ./src/shared/utils/EventDispatcher.ts
var EventDispatcher = __webpack_require__(11138);
;// ./src/editor/src/models/NodeTypeAdapters/registeradapters.ts










const _adapters = {
    Router: () => RouterAdapter/* RouterAdapter */.F,
    RouterNavigate: () => RouterNavigateAdapter,
    PageInputs: () => PageInputsAdapter,
    DbCollection2: () => QueryRecordsAdapter,
    FilterDBModels: () => FilterRecordsAdapter,
    CloudFunction2: () => CloudFunctionAdapter,
    AggregateRecords: () => AggregateRecordsAdapter
};
const _listeners = {
    componentAdded: [],
    componentRemoved: [],
    componentRenamed: [],
    componentDuplicated: [],
    nodeAdded: [],
    nodeRemoved: [],
    parametersChanged: [],
    projectLoaded: []
};
EventDispatcher.EventDispatcher.instance.on('Model.componentAdded', (e) => {
    _listeners.componentAdded.forEach((l) => {
        l(e.args);
    });
}, null);
EventDispatcher.EventDispatcher.instance.on('Model.componentRemoved', (e) => {
    _listeners.componentRemoved.forEach((l) => {
        l(e.args);
    });
}, null);
EventDispatcher.EventDispatcher.instance.on('Model.componentRenamed', (e) => {
    _listeners.componentRenamed.forEach((l) => {
        l(e.args);
    });
}, null);
EventDispatcher.EventDispatcher.instance.on('Model.componentDuplicated', (e) => {
    _listeners.componentDuplicated.forEach((l) => {
        l(e.args);
    });
}, null);
EventDispatcher.EventDispatcher.instance.on('Model.nodeAdded', (e) => {
    const typename = e.args.model.type.name;
    _listeners.nodeAdded.forEach((l) => {
        l(e);
    });
    if (_listeners['nodeAdded:' + typename])
        _listeners['nodeAdded:' + typename].forEach((l) => {
            l(e);
        });
}, null);
EventDispatcher.EventDispatcher.instance.on('Model.nodeRemoved', (e) => {
    const typename = e.args.model.type.name;
    _listeners.nodeRemoved.forEach((l) => {
        l(e);
    });
    if (_listeners['nodeRemoved:' + typename])
        _listeners['nodeRemoved:' + typename].forEach((l) => {
            l(e);
        });
}, null);
EventDispatcher.EventDispatcher.instance.on('Model.parametersChanged', function (e) {
    const typename = e.model.type.name;
    _listeners.parametersChanged.forEach((l) => {
        l(e);
    });
    if (_listeners['parametersChanged:' + typename])
        _listeners['parametersChanged:' + typename].forEach((l) => {
            l(e);
        });
}, null);
nodelibrary/* NodeLibrary */.m.instance.on('libraryUpdated', () => {
    onProjectAndNodeLibraryLoaded();
});
//Trigger the "projectLoaded" event when a project is loaded AND the node library is ready
//keep track of when the event has fired so it doesn't get triggered multiple times
let projectLoaded = false;
EventDispatcher.EventDispatcher.instance.on('ProjectModel.instanceHasChanged', () => {
    projectLoaded = false;
    onProjectAndNodeLibraryLoaded();
}, null);
function onProjectAndNodeLibraryLoaded() {
    if (!projectLoaded && nodelibrary/* NodeLibrary */.m.instance.isLoaded() && projectmodel.ProjectModel.instance) {
        projectLoaded = true;
        _listeners.projectLoaded.forEach((l) => l());
    }
}
function _registerNewAdapter(adapter) {
    const a = new adapter();
    Object.keys(a.events).forEach((key) => {
        if (_listeners[key] === undefined)
            _listeners[key] = [];
        _listeners[key].push(a.events[key]);
    });
    return a;
}
const _adapterInstances = {};
Object.keys(_adapters).forEach((adapterName) => {
    _adapterInstances[adapterName] = _registerNewAdapter(_adapters[adapterName]());
});


/***/ }),

/***/ 97546:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgReset = function SvgReset(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M18.1675 12.6071C18.1675 9.27605 15.4671 6.57571 12.1361 6.57571C9.97943 6.57571 8.08618 7.70734 7.01925 9.41235H9.40674C9.82095 9.41235 10.1567 9.74814 10.1567 10.1624C10.1567 10.5766 9.82095 10.9124 9.40674 10.9124H5.34117C4.92696 10.9124 4.59117 10.5766 4.59117 10.1624V6.09679C4.59117 5.68257 4.92696 5.34679 5.34117 5.34679C5.75538 5.34679 6.09117 5.68257 6.09117 6.09679V8.11989C7.46236 6.27569 9.65912 5.07912 12.1361 5.07912C16.2937 5.07912 19.6641 8.4495 19.6641 12.6071C19.6641 16.7647 16.2937 20.1351 12.1361 20.1351C8.85735 20.1351 6.07 18.0394 5.03682 15.1167C4.89907 14.7271 5.10328 14.2996 5.49292 14.1618C5.88257 14.0241 6.3101 14.2283 6.44784 14.6179C7.27627 16.9613 9.51129 18.6385 12.1361 18.6385C15.4671 18.6385 18.1675 15.9381 18.1675 12.6071Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgReset);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "6395801ee80fcaf3f23f85aeedbc0550.svg");

/***/ }),

/***/ 98058:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Models = void 0;
const resource_1 = __webpack_require__(39929);
const pagination_1 = __webpack_require__(92081);
const headers_1 = __webpack_require__(79973);
const path_1 = __webpack_require__(20854);
class Models extends resource_1.APIResource {
    /**
     * Get a specific model.
     *
     * The Models API response can be used to determine information about a specific
     * model or resolve a model alias to a model ID.
     *
     * @example
     * ```ts
     * const betaModelInfo = await client.beta.models.retrieve(
     *   'model_id',
     * );
     * ```
     */
    retrieve(modelID, params = {}, options) {
        const { betas } = params ?? {};
        return this._client.get((0, path_1.path) `/v1/models/${modelID}?beta=true`, {
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
                options?.headers,
            ]),
        });
    }
    /**
     * List available models.
     *
     * The Models API response can be used to determine which models are available for
     * use in the API. More recently released models are listed first.
     *
     * @example
     * ```ts
     * // Automatically fetches more pages as needed.
     * for await (const betaModelInfo of client.beta.models.list()) {
     *   // ...
     * }
     * ```
     */
    list(params = {}, options) {
        const { betas, ...query } = params ?? {};
        return this._client.getAPIList('/v1/models?beta=true', (pagination_1.Page), {
            query,
            ...options,
            headers: (0, headers_1.buildHeaders)([
                { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
                options?.headers,
            ]),
        });
    }
}
exports.Models = Models;
//# sourceMappingURL=models.js.map

/***/ }),

/***/ 98096:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.SideNavigation-module__Root--lBtE1{height:100%;border-right:1px solid var(--theme-color-bg-1);display:flex;position:relative;overflow:hidden;min-width:380px;max-width:55vw;transition:width .3s ease-in-out}.SideNavigation-module__Root--expanded--hkydv{width:55vw}.SideNavigation-module__Toolbar--Zevyy{position:absolute;display:flex;flex-direction:column;min-width:40px;height:100%;border-right:2px solid var(--theme-color-bg-1);background-color:var(--theme-color-bg-2);transition:box-shadow var(--speed-quick) var(--easing-base)}.SideNavigation-module__Toolbar--Zevyy:has(.SideNavigation-module__Label--KdjRq.SideNavigation-module__is-tooltip-visible--p1pV3){transition:box-shadow var(--speed-quick) var(--easing-base) 250ms;box-shadow:0 0 30px 5px var(--theme-color-bg-1-transparent)}.SideNavigation-module__Logo--mcx5S{padding-top:4px}.SideNavigation-module__ToolbarIcon--tAAJ0{width:25px;height:25px;position:relative;left:8px;margin-bottom:20px;vertical-align:middle;filter:grayscale(100%) brightness(150%);opacity:.7;cursor:pointer}.SideNavigation-module__ToolbarIcon--tAAJ0:hover{opacity:1}.SideNavigation-module__ToolbarIcon--tAAJ0.SideNavigation-module__is-active--XMpbY{opacity:1}.SideNavigation-module__Panel--mwLQf{flex:1;min-height:100%;position:relative;margin-left:40px;overflow:hidden;display:flex;flex-direction:column;background-color:var(--theme-color-bg-2);border-left:2px solid var(--theme-color-bg-1)}.SideNavigation-module__SideNavigationButton--XjN5s{display:flex;align-items:center;padding-top:2px;padding-bottom:2px;margin-left:4px;cursor:pointer}.SideNavigation-module__SideNavigationButton--XjN5s:hover path{fill:var(--theme-color-fg-highlight)}.SideNavigation-module__Label--KdjRq{max-width:0;overflow:hidden;transition:max-width var(--speed-quick) var(--easing-base);cursor:pointer}.SideNavigation-module__Label--KdjRq.SideNavigation-module__is-tooltip-visible--p1pV3{transition:max-width var(--speed-quick) var(--easing-base) 250ms;max-width:120px}.SideNavigation-module__LabelInner--lWHz3{padding-left:8px;padding-right:16px}.SideNavigation-module__SideNavigationButton--XjN5s:hover .SideNavigation-module__LabelInner--lWHz3:not(.SideNavigation-module__is-active--XMpbY) p{color:var(--theme-color-fg-default)}.SideNavigation-module__LabelInner--lWHz3 p{white-space:nowrap}.SideNavigation-module__Command--o5Sei{height:0;transition:height var(--speed-quick) var(--easing-base)}.SideNavigation-module__SideNavigationButton--XjN5s:hover .SideNavigation-module__Command--o5Sei{height:10px}.SideNavigation-module__IconButtonContainer--O1fNi{position:relative}.SideNavigation-module__NotificationBadge--LgTsH{position:absolute;bottom:0;right:0;padding:2px 5px;border-radius:8px;background-color:var(--theme-color-secondary-bright);font-size:10px;font-weight:700;font-family:var(--font-family);color:var(--theme-color-on-secondary)}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/app/SideNavigation/SideNavigation.module.scss"],"names":[],"mappings":"AAEA,oCACE,WAAA,CACA,8CAAA,CACA,YAAA,CACA,iBAAA,CACA,eAAA,CACA,eAAA,CACA,cAAA,CACA,gCAAA,CAEA,8CACE,UAAA,CAIJ,uCACE,iBAAA,CACA,YAAA,CACA,qBAAA,CACA,cAAA,CACA,WAAA,CACA,8CAAA,CACA,wCAAA,CACA,2DAAA,CAEA,kIACE,iEAAA,CACA,2DAAA,CAIJ,oCACE,eAAA,CAGF,2CACE,UAAA,CACA,WAAA,CACA,iBAAA,CACA,QAAA,CACA,kBAAA,CACA,qBAAA,CACA,uCAAA,CACA,UAAA,CACA,cAAA,CAEA,iDACE,SAAA,CAGF,mFACE,SAAA,CAIJ,qCACE,MAAA,CACA,eAAA,CACA,iBAAA,CACA,gBAAA,CACA,eAAA,CAEA,YAAA,CACA,qBAAA,CAEA,wCAAA,CACA,6CAAA,CAGF,oDACE,YAAA,CACA,kBAAA,CACA,eAAA,CACA,kBAAA,CACA,eAAA,CACA,cAAA,CAGE,+DACE,oCAAA,CAKN,qCACE,WAAA,CACA,eAAA,CACA,0DAAA,CACA,cAAA,CAEA,sFACE,gEAAA,CACA,eAAA,CAIJ,0CACE,gBAAA,CACA,kBAAA,CAGE,oJACE,mCAAA,CAIJ,4CACE,kBAAA,CAIJ,uCACE,QAAA,CACA,uDAAA,CAEA,iGACE,WAAA,CAIJ,mDACE,iBAAA,CAGF,iDACE,iBAAA,CACA,QAAA,CACA,OAAA,CACA,eAAA,CACA,iBAAA,CACA,oDAAA,CACA,cAAA,CACA,eAAA,CACA,8BAAA,CACA,qCAAA","sourcesContent":["$_sidebar-hover-enter-offset: 250ms;\n\n.Root {\n  height: 100%;\n  border-right: 1px solid var(--theme-color-bg-1);\n  display: flex;\n  position: relative;\n  overflow: hidden;\n  min-width: 380px;\n  max-width: 55vw;\n  transition: width 0.3s ease-in-out;\n\n  &--expanded {\n    width: 55vw;\n  }\n}\n\n.Toolbar {\n  position: absolute;\n  display: flex;\n  flex-direction: column;\n  min-width: 40px;\n  height: 100%;\n  border-right: 2px solid var(--theme-color-bg-1);\n  background-color: var(--theme-color-bg-2);\n  transition: box-shadow var(--speed-quick) var(--easing-base);\n\n  &:has(.Label.is-tooltip-visible) {\n    transition: box-shadow var(--speed-quick) var(--easing-base) $_sidebar-hover-enter-offset;\n    box-shadow: 0 0 30px 5px var(--theme-color-bg-1-transparent);\n  }\n}\n\n.Logo {\n  padding-top: 4px;\n}\n\n.ToolbarIcon {\n  width: 25px;\n  height: 25px;\n  position: relative;\n  left: 8px;\n  margin-bottom: 20px;\n  vertical-align: middle;\n  filter: grayscale(100%) brightness(150%);\n  opacity: 0.7;\n  cursor: pointer;\n\n  &:hover {\n    opacity: 1;\n  }\n\n  &.is-active {\n    opacity: 1;\n  }\n}\n\n.Panel {\n  flex: 1;\n  min-height: 100%;\n  position: relative;\n  margin-left: 40px;\n  overflow: hidden;\n\n  display: flex;\n  flex-direction: column;\n\n  background-color: var(--theme-color-bg-2);\n  border-left: 2px solid var(--theme-color-bg-1);\n}\n\n.SideNavigationButton {\n  display: flex;\n  align-items: center;\n  padding-top: 2px;\n  padding-bottom: 2px;\n  margin-left: 4px;\n  cursor: pointer;\n\n  &:hover {\n    path {\n      fill: var(--theme-color-fg-highlight);\n    }\n  }\n}\n\n.Label {\n  max-width: 0;\n  overflow: hidden;\n  transition: max-width var(--speed-quick) var(--easing-base);\n  cursor: pointer;\n\n  &.is-tooltip-visible {\n    transition: max-width var(--speed-quick) var(--easing-base) $_sidebar-hover-enter-offset;\n    max-width: 120px;\n  }\n}\n\n.LabelInner {\n  padding-left: 8px;\n  padding-right: 16px;\n\n  .SideNavigationButton:hover &:not(.is-active) {\n    p {\n      color: var(--theme-color-fg-default);\n    }\n  }\n\n  p {\n    white-space: nowrap;\n  }\n}\n\n.Command {\n  height: 0;\n  transition: height var(--speed-quick) var(--easing-base);\n\n  .SideNavigationButton:hover & {\n    height: 10px;\n  }\n}\n\n.IconButtonContainer {\n  position: relative;\n}\n\n.NotificationBadge {\n  position: absolute;\n  bottom: 0;\n  right: 0;\n  padding: 2px 5px;\n  border-radius: 8px;\n  background-color: var(--theme-color-secondary-bright);\n  font-size: 10px;\n  font-weight: 700;\n  font-family: var(--font-family);\n  color: var(--theme-color-on-secondary);\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `SideNavigation-module__Root--lBtE1`,
	"Root--expanded": `SideNavigation-module__Root--expanded--hkydv`,
	"Toolbar": `SideNavigation-module__Toolbar--Zevyy`,
	"Label": `SideNavigation-module__Label--KdjRq`,
	"is-tooltip-visible": `SideNavigation-module__is-tooltip-visible--p1pV3`,
	"Logo": `SideNavigation-module__Logo--mcx5S`,
	"ToolbarIcon": `SideNavigation-module__ToolbarIcon--tAAJ0`,
	"is-active": `SideNavigation-module__is-active--XMpbY`,
	"Panel": `SideNavigation-module__Panel--mwLQf`,
	"SideNavigationButton": `SideNavigation-module__SideNavigationButton--XjN5s`,
	"LabelInner": `SideNavigation-module__LabelInner--lWHz3`,
	"Command": `SideNavigation-module__Command--o5Sei`,
	"IconButtonContainer": `SideNavigation-module__IconButtonContainer--O1fNi`,
	"NotificationBadge": `SideNavigation-module__NotificationBadge--LgTsH`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 98222:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-editor .suggest-preview-additional-widget {
	white-space: nowrap;
}

.monaco-editor .suggest-preview-additional-widget .content-spacer {
	color: transparent;
	white-space: pre;
}

.monaco-editor .suggest-preview-additional-widget .button {
	display: inline-block;
	cursor: pointer;
	text-decoration: underline;
	text-underline-position: under;
}

.monaco-editor .ghost-text-hidden {
	opacity: 0;
	font-size: 0;
}

.monaco-editor .ghost-text-decoration {
	font-style: italic;
}

.monaco-editor .suggest-preview-text {
	font-style: italic;
}

.monaco-editor .inline-completion-text-to-replace {
	text-decoration: underline;
	text-underline-position: under;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/browser/ghostText.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,mBAAmB;AACpB;;AAEA;CACC,kBAAkB;CAClB,gBAAgB;AACjB;;AAEA;CACC,qBAAqB;CACrB,eAAe;CACf,0BAA0B;CAC1B,8BAA8B;AAC/B;;AAEA;CACC,UAAU;CACV,YAAY;AACb;;AAEA;CACC,kBAAkB;AACnB;;AAEA;CACC,kBAAkB;AACnB;;AAEA;CACC,0BAA0B;CAC1B,8BAA8B;AAC/B","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-editor .suggest-preview-additional-widget {\n\twhite-space: nowrap;\n}\n\n.monaco-editor .suggest-preview-additional-widget .content-spacer {\n\tcolor: transparent;\n\twhite-space: pre;\n}\n\n.monaco-editor .suggest-preview-additional-widget .button {\n\tdisplay: inline-block;\n\tcursor: pointer;\n\ttext-decoration: underline;\n\ttext-underline-position: under;\n}\n\n.monaco-editor .ghost-text-hidden {\n\topacity: 0;\n\tfont-size: 0;\n}\n\n.monaco-editor .ghost-text-decoration {\n\tfont-style: italic;\n}\n\n.monaco-editor .suggest-preview-text {\n\tfont-style: italic;\n}\n\n.monaco-editor .inline-completion-text-to-replace {\n\ttext-decoration: underline;\n\ttext-underline-position: under;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 98278:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  v: () => (/* binding */ CenterToFitMode),
  _: () => (/* binding */ NodeGraphEditor)
});

// EXTERNAL MODULE: external "electron"
var external_electron_ = __webpack_require__(91288);
// EXTERNAL MODULE: external "underscore"
var external_underscore_ = __webpack_require__(80002);
var external_underscore_default = /*#__PURE__*/__webpack_require__.n(external_underscore_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/react-dom/client.js
var client = __webpack_require__(25873);
;// ./src/editor/src/constants/NodeGraphColors.ts
const NodeGraphColors = {
    yellow: '#ffa300',
    darkyellow: '#916311',
    orange: '#df691a',
    red: '#dc322f',
    magenta: '#d33682',
    violet: '#6c71c4',
    blue: '#268bd2',
    cyan: '#2aa198',
    green: '#859900',
    multiSelect: '#aaaaaa',
    base2: undefined
};

// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/AiAssistantModel.ts + 11 modules
var AiAssistantModel = __webpack_require__(77510);
// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/BasicNodeType.ts
var BasicNodeType = __webpack_require__(28593);
// EXTERNAL MODULE: ./src/editor/src/models/sidebar/index.ts
var sidebar = __webpack_require__(53612);
// EXTERNAL MODULE: ./src/editor/src/models/sidebar/sidebarmodel.tsx
var sidebarmodel = __webpack_require__(41669);
// EXTERNAL MODULE: ./src/editor/src/models/undo-queue-model.ts
var undo_queue_model = __webpack_require__(50867);
// EXTERNAL MODULE: ./src/editor/src/utils/editorsettings.ts
var editorsettings = __webpack_require__(39804);
// EXTERNAL MODULE: ./src/editor/src/models/componentmodel.ts
var componentmodel = __webpack_require__(16163);
// EXTERNAL MODULE: ./src/editor/src/models/nodegraphmodel/index.ts + 4 modules
var nodegraphmodel = __webpack_require__(87844);
// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/index.ts
var AiAssistant = __webpack_require__(10142);
// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/index.ts
var nodelibrary = __webpack_require__(68091);
// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.ts + 4 modules
var projectmodel = __webpack_require__(6203);
// EXTERNAL MODULE: ./src/editor/src/ViewerConnection.ts
var ViewerConnection = __webpack_require__(71336);
// EXTERNAL MODULE: ./src/editor/src/views/popuplayer.js
var popuplayer = __webpack_require__(45653);
var popuplayer_default = /*#__PURE__*/__webpack_require__.n(popuplayer);
;// ./src/editor/src/views/nodegrapheditor/canvasHelpers.ts
/**
 * Canvas Helper Utilities for Node Graph Rendering
 *
 * Provides utility functions for drawing rounded rectangles and text truncation
 * on HTML5 Canvas. Used primarily for modernizing node appearance in the graph editor.
 *
 * @module canvasHelpers
 * @since TASK-000I-A
 */
/**
 * Draw a rounded rectangle path (does not fill or stroke)
 *
 * Uses arcTo() for drawing rounded corners. This method only creates the path;
 * you must call ctx.fill() or ctx.stroke() afterwards.
 *
 * @param ctx - Canvas rendering context
 * @param x - X coordinate of top-left corner
 * @param y - Y coordinate of top-left corner
 * @param width - Width of rectangle
 * @param height - Height of rectangle
 * @param radius - Corner radius (number for all corners, or object for individual corners)
 *
 * @example
 * ```typescript
 * roundRect(ctx, 10, 10, 100, 50, 6);
 * ctx.fill();
 * ```
 */
function roundRect(ctx, x, y, width, height, radius) {
    // Normalize radius to object format
    const r = typeof radius === 'number' ? { tl: radius, tr: radius, br: radius, bl: radius } : radius;
    // Clamp radius to reasonable values (can't be larger than half the smallest dimension)
    const maxRadius = Math.min(width, height) / 2;
    const tl = Math.min(r.tl, maxRadius);
    const tr = Math.min(r.tr, maxRadius);
    const br = Math.min(r.br, maxRadius);
    const bl = Math.min(r.bl, maxRadius);
    ctx.beginPath();
    ctx.moveTo(x + tl, y);
    // Top edge and top-right corner
    ctx.lineTo(x + width - tr, y);
    ctx.arcTo(x + width, y, x + width, y + tr, tr);
    // Right edge and bottom-right corner
    ctx.lineTo(x + width, y + height - br);
    ctx.arcTo(x + width, y + height, x + width - br, y + height, br);
    // Bottom edge and bottom-left corner
    ctx.lineTo(x + bl, y + height);
    ctx.arcTo(x, y + height, x, y + height - bl, bl);
    // Left edge and top-left corner
    ctx.lineTo(x, y + tl);
    ctx.arcTo(x, y, x + tl, y, tl);
    ctx.closePath();
}
/**
 * Fill a rounded rectangle
 *
 * Convenience wrapper that creates a rounded rectangle path and fills it.
 *
 * @param ctx - Canvas rendering context
 * @param x - X coordinate of top-left corner
 * @param y - Y coordinate of top-left corner
 * @param width - Width of rectangle
 * @param height - Height of rectangle
 * @param radius - Corner radius
 *
 * @example
 * ```typescript
 * ctx.fillStyle = '#333';
 * fillRoundRect(ctx, 10, 10, 100, 50, 6);
 * ```
 */
function fillRoundRect(ctx, x, y, width, height, radius) {
    roundRect(ctx, x, y, width, height, radius);
    ctx.fill();
}
/**
 * Stroke a rounded rectangle
 *
 * Convenience wrapper that creates a rounded rectangle path and strokes it.
 *
 * @param ctx - Canvas rendering context
 * @param x - X coordinate of top-left corner
 * @param y - Y coordinate of top-left corner
 * @param width - Width of rectangle
 * @param height - Height of rectangle
 * @param radius - Corner radius
 *
 * @example
 * ```typescript
 * ctx.strokeStyle = '#fff';
 * ctx.lineWidth = 2;
 * strokeRoundRect(ctx, 10, 10, 100, 50, 6);
 * ```
 */
function strokeRoundRect(ctx, x, y, width, height, radius) {
    roundRect(ctx, x, y, width, height, radius);
    ctx.stroke();
}
/**
 * Truncate text to fit within a maximum width, adding ellipsis if needed
 *
 * Efficiently truncates text by measuring progressively shorter strings
 * until one fits within the specified width. Uses the context's current font settings.
 *
 * @param ctx - Canvas rendering context (with font already set)
 * @param text - Text to truncate
 * @param maxWidth - Maximum width in pixels
 * @returns Truncated text with '…' appended if truncation occurred
 *
 * @example
 * ```typescript
 * ctx.font = '12px Inter-Regular';
 * const displayText = truncateText(ctx, 'Very Long Port Name', 80);
 * // Returns "Very Long Po…" if it doesn't fit
 * ctx.fillText(displayText, x, y);
 * ```
 */
function truncateText(ctx, text, maxWidth) {
    // If the text already fits, return it as-is
    if (ctx.measureText(text).width <= maxWidth) {
        return text;
    }
    const ellipsis = '…';
    const ellipsisWidth = ctx.measureText(ellipsis).width;
    // If even the ellipsis doesn't fit, just return it
    if (ellipsisWidth > maxWidth) {
        return ellipsis;
    }
    // Binary search for the optimal truncation point
    let left = 0;
    let right = text.length;
    let result = '';
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        const truncated = text.slice(0, mid);
        const width = ctx.measureText(truncated + ellipsis).width;
        if (width <= maxWidth) {
            result = truncated;
            left = mid + 1;
        }
        else {
            right = mid - 1;
        }
    }
    return result + ellipsis;
}

;// ./src/editor/src/views/nodegrapheditor/NodeGraphEditorNode.ts








function _getColorForAnnotation(annotation) {
    if (annotation === 'Deleted')
        return '#F57569';
    else if (annotation === 'Changed')
        return '#83B8BA';
    else if (annotation === 'Created')
        return '#5BF59E';
}
function measureTextHeight(text, font, lineHeight, maxWidth) {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    ctx.font = font;
    ctx.textBaseline = 'top';
    // Defensive: convert to string (handles expression objects, numbers, etc.)
    const textString = typeof text === 'string' ? text : String(text || '');
    return textWordWrap(ctx, textString, 0, 0, lineHeight, maxWidth);
}
function textWordWrap(context, text, x, y, lineHeight, maxWidth, cb) {
    // Defensive: ensure we have a string
    const textString = typeof text === 'string' ? text : String(text || '');
    // Empty string still has height (return lineHeight, not undefined)
    if (!textString) {
        return lineHeight;
    }
    let words = textString.split(' ');
    let currentLine = 0;
    let idx = 1;
    while (words.length > 0 && idx <= words.length) {
        const str = words.slice(0, idx).join(' ');
        const w = context.measureText(str).width;
        if (w > maxWidth) {
            if (idx == 1) {
                idx = 2;
            }
            cb && cb(words.slice(0, idx - 1).join(' '), x, y + lineHeight * currentLine);
            currentLine++;
            words = words.splice(idx - 1);
            idx = 1;
        }
        else {
            idx++;
        }
    }
    if (idx > 0) {
        cb && cb(words.slice(0, idx - 1).join(' '), x, y + lineHeight * currentLine);
    }
    return lineHeight * currentLine + lineHeight;
}
function nodeShouldAttach(root, mousePos, nodesToAttach) {
    const potentialAttachPoints = [];
    //Gather a list of potential positions to do the drop at
    //Start with the root and recurse down
    _nodeShouldAttachRecurse(mousePos, root, nodesToAttach, potentialAttachPoints);
    // window._debugNodeGraphAttachPoints = potentialAttachPoints;
    if (potentialAttachPoints.length === 0) {
        return;
    }
    function distSquared(a, b) {
        const dx = a.x - b.x;
        const dy = a.y - b.y;
        return dx * dx + dy * dy;
    }
    //find closest attach point
    let index = 0;
    let minDist = distSquared(mousePos, potentialAttachPoints[0].anchorPoint);
    for (let i = 1; i < potentialAttachPoints.length; i++) {
        const d = distSquared(mousePos, potentialAttachPoints[i].anchorPoint);
        if (d < minDist) {
            minDist = d;
            index = i;
        }
    }
    return potentialAttachPoints[index].attachInfo;
}
//There are 4 different valid locations to drop a node in a hierarchy:
//1. Directly at the parent, node will be added as last child
//2. In the space directly above a node. Node will become a sibling
//3. In the space directly below a node. Node will become a sibling
//4. In the space directly below a node, but offset a bit to the right. Node will become first child
//5. In the space below a node subgraph, offset a bit to the right. Node will become last child
function _nodeShouldAttachRecurse(pos, node, nodesToAttach, result) {
    const hitPadding = 10;
    const { x, y } = node.global;
    const hierarchyHeight = node.measure().height;
    const { width, height } = node.nodeSize;
    const intersectX = pos.x >= x - hitPadding && pos.x <= x + width + hitPadding;
    const intersectY = pos.y >= y - hitPadding && pos.y <= y + height + hitPadding;
    const nodeCanAcceptChildNodes = canAcceptChildNodes(node, nodesToAttach);
    //1. Directly at the parent, node will be added as last child
    if (intersectX && intersectY && nodeCanAcceptChildNodes) {
        result.push(getAttachPointOnNode(node));
    }
    if (intersectX && node.parent && canAcceptChildNodes(node.parent, nodesToAttach)) {
        //2. In the space directly above a node. Node will become a sibling
        if (pos.y >= y - NodeGraphEditorNode.childSpacing + hitPadding && pos.y <= y + height / 2 + hitPadding) {
            result.push(getAttachPointAboveNode(node));
        }
        //3. In the space directly below a node. Node will become a sibling.
        //The hit areas are slightly different depending on if the node has children:
        // - No children: hit area starts at the middle of the node
        // - Children: hit area starts after last child
        const hasChildren = node.children.length > 0;
        if (hasChildren &&
            pos.y >= y + hierarchyHeight - hitPadding &&
            pos.y <= y + hierarchyHeight + NodeGraphEditorNode.childSpacing + hitPadding) {
            result.push(getAttachPointBelowNode(node));
        }
        else if (!hasChildren &&
            pos.y >= y + height / 2 - hitPadding &&
            pos.y <= y + height + NodeGraphEditorNode.childSpacing + hitPadding) {
            result.push(getAttachPointBelowNode(node));
        }
    }
    for (let i = 0; i < node.children.length; i++) {
        const child = node.children[i];
        if (pos.y >= child.global.y - hitPadding) {
            _nodeShouldAttachRecurse(pos, child, nodesToAttach, result);
        }
    }
    //4. In the space directly below a node, but offset a bit to the right. Node will become first child
    if (nodeCanAcceptChildNodes &&
        pos.x >= x - hitPadding &&
        pos.x <= x + node.nodeSize.width + NodeGraphEditorNode.childMargin + hitPadding &&
        pos.y >= y + node.nodeSize.height - hitPadding &&
        pos.y <= y + node.nodeSize.height + NodeGraphEditorNode.childSpacing + hitPadding) {
        result.push(getAttachPointBelowRightNode(node));
    }
    //5. In the space below a node subgraph, offset a bit to the right. Node will become last child
    if (node.children.length &&
        nodeCanAcceptChildNodes &&
        pos.x >= x - hitPadding &&
        pos.x <= x + node.nodeSize.width + NodeGraphEditorNode.childMargin + hitPadding &&
        pos.y >= y + hierarchyHeight - hitPadding &&
        pos.y <= y + hierarchyHeight + NodeGraphEditorNode.childSpacing + hitPadding) {
        result.push(getAttachPointBelowRightSubgraph(node));
    }
}
function canAcceptChildNodes(node, nodes) {
    return node.model.canAcceptChildren(external_underscore_default().pluck(nodes, 'model'));
}
function getAttachPointBelowRightNode(node) {
    const { x, y } = node.global;
    return {
        anchorPoint: {
            x: x + node.nodeSize.width / 2 + NodeGraphEditorNode.childMargin,
            y: y + node.nodeSize.height + NodeGraphEditorNode.childSpacing / 2
        },
        attachInfo: {
            parent: node,
            index: 0,
            pos: {
                x: x + NodeGraphEditorNode.childMargin,
                y: y + node.nodeSize.height
            }
        }
    };
}
function getAttachPointOnNode(node) {
    const { x, y } = node.global;
    const hierarchyHeight = node.measure().height;
    return {
        anchorPoint: {
            x: x + node.nodeSize.width / 2,
            y: y + node.nodeSize.height / 2
        },
        attachInfo: {
            parent: node,
            index: node.children.length,
            pos: {
                x: x + NodeGraphEditorNode.childMargin,
                y: y + hierarchyHeight
            }
        }
    };
}
function getAttachPointBelowRightSubgraph(node) {
    const { x, y } = node.global;
    const hierarchyHeight = node.measure().height;
    return {
        anchorPoint: {
            x: x + node.nodeSize.width / 2 + NodeGraphEditorNode.childMargin,
            y: y + hierarchyHeight + NodeGraphEditorNode.childSpacing / 2
        },
        attachInfo: {
            parent: node,
            index: node.children.length,
            pos: {
                x: x + NodeGraphEditorNode.childMargin,
                y: y + hierarchyHeight
            }
        }
    };
}
function getAttachPointAboveNode(node) {
    const { x, y } = node.global;
    const parent = node.parent;
    const index = parent.children.indexOf(node);
    return {
        anchorPoint: {
            x: x + node.nodeSize.width / 2,
            y: y - NodeGraphEditorNode.childSpacing / 2
        },
        attachInfo: {
            parent,
            index: index,
            pos: {
                x: x,
                y: y - NodeGraphEditorNode.childSpacing
            }
        }
    };
}
function getAttachPointBelowNode(node) {
    const { x, y } = node.global;
    const parent = node.parent;
    const index = parent.children.indexOf(node);
    const hierarchyHeight = node.measure().height;
    return {
        anchorPoint: {
            x: x + node.nodeSize.width / 2,
            y: y + hierarchyHeight + NodeGraphEditorNode.childSpacing / 2
        },
        attachInfo: {
            parent,
            index: index + 1,
            pos: {
                x: x,
                y: y + hierarchyHeight
            }
        }
    };
}
class NodeGraphEditorNode {
    constructor(model) {
        this.model = model;
        this.x = model.x || 0;
        this.y = model.y || 0;
        this.global = { x: 0, y: 0 };
        this.id = model.id;
        this.children = [];
        this.connections = [];
        this.nodeSize = NodeGraphEditorNode.size;
        this.iconRotation = 0;
        this.bindModel();
        return this;
    }
    static createFromModel(model, owner, parent) {
        const node = new NodeGraphEditorNode(model);
        node.owner = owner;
        node.parent = parent;
        external_underscore_default().each(model.children, function (child) {
            node.children.push(NodeGraphEditorNode.createFromModel(child, owner, node));
        });
        return node;
    }
    updateIcon() {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        const health = this.model.getHealth();
        this.iconSize = 18;
        this.rotatingIcon = null;
        if (!health.healthy) {
            this.icon = (_a = this.owner) === null || _a === void 0 ? void 0 : _a.warningIcon;
        }
        else if (this.model.type instanceof componentmodel/* ComponentModel */.j && ((_b = this.owner) === null || _b === void 0 ? void 0 : _b.componentIcon)) {
            this.icon = (_c = this.owner) === null || _c === void 0 ? void 0 : _c.componentIcon;
        }
        else if (this.id === ((_d = projectmodel.ProjectModel.instance.getRootNode()) === null || _d === void 0 ? void 0 : _d.id)) {
            this.icon = (_e = this.owner) === null || _e === void 0 ? void 0 : _e.homeIcon;
        }
        else if ((_f = this.model.metadata) === null || _f === void 0 ? void 0 : _f.AiAssistant) {
            this.icon = (_g = this.owner) === null || _g === void 0 ? void 0 : _g.aiAssistantInnerIcon;
            this.rotatingIcon = (_h = this.owner) === null || _h === void 0 ? void 0 : _h.aiAssistantOuterIcon;
            this.iconSize = 25;
            if (AiAssistant/* AiAssistantModel */.g.instance.getProcessingNodeIds().includes(this.id)) {
                this.iconRotation = performance.now() / 400;
            }
            else {
                this.iconRotation = 0;
            }
        }
        else {
            this.icon = undefined;
        }
    }
    bindModel() {
        const _this = this;
        this.model.on('change', function (args) {
            _this.owner.relayout();
            _this.owner.repaint();
        }, this);
        this.model.on('instancePortsChanged', function () {
            _this.connections.forEach(function (c) {
                c.resolvePorts();
            });
            _this.owner.relayout();
            _this.owner.repaint();
        }, this);
    }
    destruct() {
        this.model.off(this);
        for (const child of this.children) {
            child.destruct();
        }
    }
    updateModel() {
        this.model.set({ x: this.x, y: this.y });
    }
    forEach(callback) {
        if (callback(this)) {
            return true;
        }
        for (const i in this.children) {
            if (this.children[i].forEach(callback)) {
                return false;
            }
        }
    }
    pointInside(pos) {
        const bw = NodeGraphEditorNode.borderSize;
        const inside = pos.x >= this.x - bw &&
            pos.x <= this.x + this.nodeSize.width + bw &&
            pos.y >= this.y - bw &&
            pos.y <= this.y + this.nodeSize.height + bw;
        return inside;
    }
    propagateMouse(type, pos, evt) {
        // Propagate mouse event to children
        for (const child of this.children) {
            child.propagateMouse(type, { x: pos.x - this.x, y: pos.y - this.y }, evt);
        }
        // Enlarge the hit area with the border size
        if (this.pointInside(pos) && type !== 'out') {
            if (type === 'move' && !this.isTrackingMove) {
                // If this is a move event and this node is not tracking move events
                // generate a move in first
                this.mouse('move-in', { x: pos.x - this.x, y: pos.y - this.y }, evt);
                this.isTrackingMove = true;
            }
            this.mouse(type, { x: pos.x - this.x, y: pos.y - this.y }, evt);
        }
        else if (this.isTrackingMove) {
            // The mouse exited the node, if it was tracking generate a move out event
            this.isTrackingMove = false;
            this.mouse('move-out', { x: pos.x - this.x, y: pos.y - this.y }, evt);
        }
    }
    mouse(type, pos, evt) {
        if (evt.button !== 0)
            return; //only interact with left mouse button
        evt.consumed = true;
        switch (type) {
            case 'move':
            case 'move-in':
                // Is the mouse hovering the border or body of the node?
                var bw = NodeGraphEditorNode.borderSize;
                if (pos.x < bw || pos.x > this.nodeSize.width - bw || pos.y < bw || pos.y > this.nodeSize.height - bw) {
                    this.borderHighlighted = true;
                }
                else {
                    this.borderHighlighted = false;
                }
                // Send node highlighted to viewer if this node is being highligted
                if (!this.borderHighlighted)
                    ViewerConnection/* ViewerConnection */.t.instance.sendNodeHighlighted(this.model, true);
                this.owner.setHighlightedNode(this, pos);
                // Show tooltop if this node is annotated
                if (this.model.annotation) {
                    popuplayer_default().instance.showTooltip({
                        x: evt.pageX,
                        y: evt.pageY,
                        position: 'bottom',
                        content: this.model.annotation
                    });
                }
                else {
                    // Show tooltip if the connection is unhealthy
                    const health = this.model.getHealth();
                    if (!health.healthy) {
                        popuplayer_default().instance.showTooltip({
                            x: evt.pageX,
                            y: evt.pageY,
                            position: 'bottom',
                            content: health.message
                        });
                    }
                }
                this.connectionDragAreaHighlighted = pos.x > this.nodeSize.width - 20 && pos.y < 20;
                const showCrosshairCursor = this.connectionDragAreaHighlighted || this.borderHighlighted;
                this.owner.el.css({
                    cursor: showCrosshairCursor ? 'crosshair' : 'initial'
                });
                this.owner.repaint();
                break;
            case 'move-out':
                popuplayer_default().instance.hideTooltip();
                this.owner.el.css({ cursor: 'initial' });
                // Clear highlight on move out
                if (this.owner.highlighted === this) {
                    this.owner.setHighlightedNode(undefined);
                }
                this.connectionDragAreaHighlighted = false;
                this.borderHighlighted = false;
                this.owner.repaint();
                ViewerConnection/* ViewerConnection */.t.instance.sendNodeHighlighted(this.model, false);
                break;
            case 'down':
                popuplayer_default().instance.hideTooltip();
                if (this.owner.highlighted === this) {
                    // Check if clicking on comment icon
                    const inCommentIcon = this.commentIconBounds && this.isPointInCommentIcon(pos);
                    if (inCommentIcon) {
                        // Show comment edit prompt
                        this.showCommentEditPopup();
                        evt.stopPropagation && evt.stopPropagation();
                        return;
                    }
                    if (this.borderHighlighted || this.connectionDragAreaHighlighted) {
                        // User starts dragging from the border or connection area with circle icon
                        this.owner.startDraggingConnection(this);
                    }
                    else {
                        if (evt.shiftKey) {
                            this.owner.addNodeToSelection(this);
                        }
                        else {
                            this.owner.startDraggingNode(this);
                        }
                    }
                }
                break;
            case 'up':
                {
                    const hasModifierKey = evt.metaKey || evt.ctrlKey || evt.shiftKey;
                    if (!hasModifierKey) {
                        this.owner.selectNode(this);
                    }
                }
                break;
        }
    }
    isProjectRoot() {
        return projectmodel.ProjectModel.instance.getRootNode() === this.model;
    }
    isComponent() {
        return this.model.type instanceof componentmodel/* ComponentModel */.j;
    }
    titlebarLabelHeight() {
        const cacheKey = this.model.label + (this.icon ? 'icon' : '');
        if (cacheKey !== this._cachedLabelHeightTextKey) {
            const connectionDragAreaWidth = 10;
            const horizontalSpacing = 10;
            const iconOffset = this.icon ? 12 : 0;
            const maxWidth = this.nodeSize.width - 2 * horizontalSpacing - connectionDragAreaWidth - iconOffset;
            this._cachedLabelHeight = measureTextHeight(this.model.label, '12px Inter-Regular', 14, maxWidth);
            this._cachedLabelHeightTextKey = cacheKey;
        }
        return this._cachedLabelHeight;
    }
    titlebarSublabelHeight() {
        if (this.typeDisplayName() !== this._cachedSublabelHeightText) {
            const connectionDragAreaWidth = 10;
            const horizontalSpacing = 10;
            const maxWidth = this.nodeSize.width - 2 * horizontalSpacing - connectionDragAreaWidth;
            this._cachedSublabelHeight = measureTextHeight(this.typeDisplayName(), '12px Inter-Regular', 14, maxWidth);
            this._cachedSublabelHeightText = this.typeDisplayName();
        }
        return this._cachedSublabelHeight;
    }
    titlebarHeight() {
        const labelExtraHeight = this.model.label !== this.typeDisplayName() ? this.titlebarSublabelHeight() : 0;
        return this.titlebarLabelHeight() + labelExtraHeight + 22;
    }
    typeDisplayName() {
        var _a;
        return ((_a = this.model.metadata) === null || _a === void 0 ? void 0 : _a.typeLabelOverride) || this.model.type.displayName;
    }
    paint(ctx, paintRect, options) {
        var _a;
        const _this = this;
        const x = this.global.x;
        const y = this.global.y;
        const isOutsidePaintArea = x > paintRect.maxX ||
            y > paintRect.maxY ||
            x + this.nodeSize.width < paintRect.minX ||
            y + this.nodeSize.height < paintRect.minY;
        if (isOutsidePaintArea === false) {
            this.updateIcon();
            const nc = ((_a = this.model.metadata) === null || _a === void 0 ? void 0 : _a.colorOverride)
                ? nodelibrary/* NodeLibrary */.m.instance.colorSchemeForNodeColorName(this.model.metadata.colorOverride)
                : nodelibrary/* NodeLibrary */.m.instance.colorSchemeForNodeType(this.model.type);
            const isHighligthed = this.owner.isHighlighted(this);
            const horizontalSpacing = 10, connectionDragAreaWidth = 10; //the circle icon where you can drag connection from
            ctx.textAlign = 'left';
            ctx.textBaseline = 'middle';
            ctx.save();
            // Clip to rounded rectangle
            roundRect(ctx, x, y, this.nodeSize.width, this.nodeSize.height, NodeGraphEditorNode.cornerRadius);
            ctx.clip();
            // Bg - Use rounded rectangle for modern appearance
            ctx.fillStyle = nc.header;
            fillRoundRect(ctx, x, y, this.nodeSize.width, this.nodeSize.height, NodeGraphEditorNode.cornerRadius);
            const titlebarHeight = this.titlebarHeight();
            // Darken plate (body area below title)
            ctx.fillStyle = nc.base;
            ctx.fillRect(x, y + titlebarHeight, this.nodeSize.width, this.nodeSize.height - titlebarHeight);
            // Highlight plate
            if (isHighligthed || this.selected) {
                const prevCompOperation = ctx.globalCompositeOperation;
                ctx.globalCompositeOperation = 'hard-light'; // additive blending looks better
                ctx.globalAlpha = 0.19;
                ctx.fillStyle = nc.text;
                fillRoundRect(ctx, x, y, this.nodeSize.width, this.nodeSize.height, NodeGraphEditorNode.cornerRadius);
                ctx.globalCompositeOperation = prevCompOperation;
                ctx.globalAlpha = 1;
            }
            if (this.icon && this.icon.complete && this.icon.naturalWidth > 0) {
                ctx.imageSmoothingEnabled = true;
                ctx.imageSmoothingQuality = 'high';
                const offset = Math.abs(this.iconSize - 18);
                try {
                    ctx.drawImage(this.icon, x + horizontalSpacing + this.nodeSize.width - horizontalSpacing - connectionDragAreaWidth - 16 - offset, y + NodeGraphEditorNode.verticalSpacing + 1 - offset / 2, this.iconSize, this.iconSize);
                }
                catch (e) {
                    // Icon failed to load, skip drawing
                    console.warn('Failed to draw node icon:', e);
                }
                if (this.rotatingIcon && this.rotatingIcon.complete && this.rotatingIcon.naturalWidth > 0) {
                    ctx.save();
                    ctx.translate(x +
                        horizontalSpacing +
                        this.nodeSize.width -
                        horizontalSpacing -
                        connectionDragAreaWidth -
                        16 -
                        offset +
                        this.iconSize / 2, y + NodeGraphEditorNode.verticalSpacing + 1 - offset / 2 + this.iconSize / 2);
                    ctx.rotate(this.iconRotation);
                    try {
                        ctx.drawImage(this.rotatingIcon, -this.iconSize / 2, -this.iconSize / 2, this.iconSize, this.iconSize);
                    }
                    catch (e) {
                        // Rotating icon failed to load, skip drawing
                        console.warn('Failed to draw rotating icon:', e);
                    }
                    ctx.restore();
                }
            }
            const iconOffset = this.icon ? 12 : 0;
            const hasUserLabel = this.typeDisplayName() && this.model.label !== this.typeDisplayName();
            // Title
            ctx.fillStyle = nc.text;
            ctx.font = '12px Inter-Medium';
            ctx.textBaseline = 'top';
            textWordWrap(ctx, this.model.label, x + horizontalSpacing, y + NodeGraphEditorNode.verticalSpacing + 5, 14, this.nodeSize.width - 2 * horizontalSpacing - connectionDragAreaWidth - iconOffset, (text, x, y) => ctx.fillText(text, x, y));
            //If this node has a label set by the user, render the type name as a sub label
            if (hasUserLabel) {
                ctx.save();
                ctx.fillStyle = nc.text;
                ctx.globalAlpha = 0.65;
                ctx.font = '12px Inter-Medium';
                ctx.textBaseline = 'top';
                textWordWrap(ctx, this.typeDisplayName(), x + horizontalSpacing, y + this.titlebarLabelHeight() + 14, 14, this.nodeSize.width - 2 * horizontalSpacing - connectionDragAreaWidth, (text, x, y) => ctx.fillText(text, x, y));
                ctx.globalAlpha = 1;
                ctx.restore();
            }
            // Draw comment icon (if node has comment OR is highlighted)
            // Position on right side, before the node icon area if present
            const hasComment = this.model.hasComment();
            if (hasComment || isHighligthed) {
                const commentIconSize = 14;
                // Adjust offset based on whether node icon is present
                // If icon exists, offset more to avoid overlap; if not, position closer to edge
                const commentIconRightOffset = this.icon ? 30 : 10;
                const commentIconX = x + this.nodeSize.width - connectionDragAreaWidth - commentIconSize - commentIconRightOffset;
                const commentIconY = y + titlebarHeight / 2 - commentIconSize / 2;
                // Store bounds for click detection
                this.commentIconBounds = {
                    x: commentIconX,
                    y: commentIconY,
                    width: commentIconSize,
                    height: commentIconSize
                };
                ctx.save();
                // Set opacity based on whether comment exists
                ctx.globalAlpha = hasComment ? 1.0 : 0.4;
                ctx.fillStyle = nc.text;
                ctx.strokeStyle = nc.text;
                ctx.lineWidth = 1.5;
                // Draw speech bubble (rounded rectangle)
                const bubbleWidth = commentIconSize;
                const bubbleHeight = commentIconSize * 0.8;
                const bubbleRadius = 2;
                // Main bubble body
                ctx.beginPath();
                ctx.moveTo(commentIconX + bubbleRadius, commentIconY);
                ctx.lineTo(commentIconX + bubbleWidth - bubbleRadius, commentIconY);
                ctx.quadraticCurveTo(commentIconX + bubbleWidth, commentIconY, commentIconX + bubbleWidth, commentIconY + bubbleRadius);
                ctx.lineTo(commentIconX + bubbleWidth, commentIconY + bubbleHeight - bubbleRadius);
                ctx.quadraticCurveTo(commentIconX + bubbleWidth, commentIconY + bubbleHeight, commentIconX + bubbleWidth - bubbleRadius, commentIconY + bubbleHeight);
                // Draw tail (small triangle at bottom)
                const tailWidth = 3;
                const tailHeight = 3;
                const tailX = commentIconX + bubbleWidth * 0.7;
                ctx.lineTo(tailX + tailWidth, commentIconY + bubbleHeight);
                ctx.lineTo(tailX, commentIconY + bubbleHeight + tailHeight);
                ctx.lineTo(tailX - tailWidth / 2, commentIconY + bubbleHeight);
                // Complete the bubble
                ctx.lineTo(commentIconX + bubbleRadius, commentIconY + bubbleHeight);
                ctx.quadraticCurveTo(commentIconX, commentIconY + bubbleHeight, commentIconX, commentIconY + bubbleHeight - bubbleRadius);
                ctx.lineTo(commentIconX, commentIconY + bubbleRadius);
                ctx.quadraticCurveTo(commentIconX, commentIconY, commentIconX + bubbleRadius, commentIconY);
                ctx.closePath();
                ctx.stroke();
                ctx.restore();
            }
            else {
                // Clear bounds when not visible
                this.commentIconBounds = undefined;
            }
            ctx.restore(); // Restore clip so we can draw border
            if (isHighligthed) {
                ctx.fillStyle = this.borderHighlighted ? '#ffffff' : nc.text;
                ctx.globalAlpha = 1;
                ctx.beginPath();
                ctx.arc(x + this.nodeSize.width, y + titlebarHeight / 2, 4, 0, 2 * Math.PI, false);
                ctx.fill();
                // ctx.font = '10px FontAwesome';
                // ctx.fillText(
                //   // @ts-expect-error
                //   String.fromCharCode('0xf111'),
                //   x + this.nodeSize.width - 5,
                //   y + titlebarHeight / 2
                // );
            }
            // Border - Use rounded rectangles for modern appearance
            const health = this.model.getHealth();
            if (!health.healthy) {
                ctx.setLineDash([5]);
                ctx.lineWidth = 1;
                ctx.strokeStyle = '#F57569';
                ctx.globalAlpha = 0.7;
                strokeRoundRect(ctx, x - 1, y - 1, this.nodeSize.width + 2, this.nodeSize.height + 2, NodeGraphEditorNode.cornerRadius + 1);
                ctx.setLineDash([]); // Restore line dash
                ctx.globalAlpha = 1;
            }
            if (this.selected || this.borderHighlighted || this.connectionDragAreaHighlighted) {
                ctx.strokeStyle = '#ffffff';
                ctx.lineWidth = 2;
                strokeRoundRect(ctx, x, y, this.nodeSize.width, this.nodeSize.height, NodeGraphEditorNode.cornerRadius);
            }
            if (this.model.annotation) {
                if (this.model.annotation === 'Deleted')
                    ctx.strokeStyle = '#F57569';
                else if (this.model.annotation === 'Changed')
                    ctx.strokeStyle = '#83B8BA';
                else if (this.model.annotation === 'Created')
                    ctx.strokeStyle = '#5BF59E';
                ctx.lineWidth = 2;
                strokeRoundRect(ctx, x, y, this.nodeSize.width, this.nodeSize.height, NodeGraphEditorNode.cornerRadius);
            }
            // Paint plugs
            let tx, ty;
            function arrow(side, color) {
                const dx = side === 'left' ? 4 : -4;
                const cx = x + (side === 'left' ? 0 : _this.nodeSize.width);
                ctx.fillStyle = color;
                ctx.beginPath();
                ctx.moveTo(cx - dx, ty - 4);
                ctx.lineTo(cx + dx, ty);
                ctx.lineTo(cx - dx, ty + 4);
                ctx.fill();
            }
            function dot(side, color) {
                const cx = x + (side === 'left' ? 0 : _this.nodeSize.width);
                const radius = 6; // Back to normal size
                // Draw main port indicator
                ctx.fillStyle = color;
                ctx.beginPath();
                ctx.arc(cx, ty, radius, 0, 2 * Math.PI, false);
                ctx.fill();
                // Add subtle inner highlight for depth
                ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
                ctx.beginPath();
                ctx.arc(cx - 0.5, ty - 0.5, radius * 0.4, 0, 2 * Math.PI, false);
                ctx.fill();
            }
            function drawPlugs(plugs, offset) {
                var _a, _b;
                ctx.font = '11px Inter-Medium';
                ctx.textBaseline = 'middle';
                ctx.globalAlpha = 1;
                for (const i in plugs) {
                    const p = plugs[i];
                    // Calculate Y position for this port
                    ty = p.index * NodeGraphEditorNode.propertyConnectionHeight + offset;
                    // Draw labels at normal positions
                    if (p.loc === 'left' || p.loc === 'middle') {
                        // Left-aligned labels
                        tx = x + horizontalSpacing;
                    }
                    else if (p.loc === 'right') {
                        // Right-aligned labels
                        tx = x + _this.nodeSize.width - horizontalSpacing;
                    }
                    else {
                        tx = x + _this.nodeSize.width / 2;
                    }
                    ctx.fillStyle = nc.text;
                    ctx.textAlign = p.loc === 'right' ? 'right' : 'left';
                    // Truncate port labels to prevent overflow
                    const label = p.displayName ? p.displayName : p.property;
                    const portAreaWidth = p.loc === 'middle'
                        ? _this.nodeSize.width - 2 * horizontalSpacing
                        : _this.nodeSize.width - horizontalSpacing - 8;
                    const truncatedLabel = truncateText(ctx, label, portAreaWidth);
                    ctx.fillText(truncatedLabel, tx, ty);
                    // Plug - Left side
                    if (p.leftCons.length || p.leftIcon) {
                        var connectionColors = nodelibrary/* NodeLibrary */.m.instance.colorSchemeForConnectionType(nodelibrary/* NodeLibrary */.m.nameForPortType(((_a = p.leftCons[0]) === null || _a === void 0 ? void 0 : _a.fromPort) ? p.leftCons[0].fromPort.type : undefined));
                        var color = external_underscore_default().find(p.leftCons, function (p) {
                            return p.isHighlighted();
                        })
                            ? connectionColors.highlighted
                            : connectionColors.normal;
                        var topConnection = external_underscore_default().find(p.leftCons, function (p) {
                            return p.isHighlighted();
                        }) || p.leftCons[p.leftCons.length - 1];
                        if (topConnection && topConnection.model.annotation) {
                            color = _getColorForAnnotation(topConnection.model.annotation);
                        }
                        if (p.leftIcon === 'from') {
                            dot('left', color);
                        }
                        else if (p.leftIcon === 'to' || p.leftIcon === 'both') {
                            arrow('left', color);
                        }
                    }
                    // Plug - Right side
                    if (p.rightCons.length || p.rightIcon) {
                        connectionColors = nodelibrary/* NodeLibrary */.m.instance.colorSchemeForConnectionType(nodelibrary/* NodeLibrary */.m.nameForPortType(((_b = p.rightCons[0]) === null || _b === void 0 ? void 0 : _b.fromPort) ? p.rightCons[0].fromPort.type : undefined));
                        color = external_underscore_default().find(p.rightCons, function (p) {
                            return p.isHighlighted();
                        })
                            ? connectionColors.highlighted
                            : connectionColors.normal;
                        var topConnection = external_underscore_default().find(p.rightCons, function (p) {
                            return p.isHighlighted();
                        }) || p.rightCons[p.rightCons.length - 1];
                        if (topConnection && topConnection.model.annotation) {
                            color = _getColorForAnnotation(topConnection.model.annotation);
                        }
                        if (p.rightIcon === 'from') {
                            dot('right', color);
                        }
                        else if (p.rightIcon === 'to' || p.rightIcon === 'both') {
                            arrow('right', color);
                        }
                    }
                }
            }
            // If there is only one 'Other' group, draw just plugs
            drawPlugs(this.plugs, y + titlebarHeight + NodeGraphEditorNode.propertyConnectionHeight / 2 + NodeGraphEditorNode.verticalSpacing);
            ctx.textBaseline = 'middle';
        }
        // Paint children
        if (!(options && options.dontPaintChildren)) {
            for (const i in this.children) {
                this.children[i].paint(ctx, paintRect);
            }
        }
    }
    setPosition(x, y) {
        this.x = x;
        this.y = y;
        this.global.x = x + (this.parent ? this.parent.global.x : 0);
        this.global.y = y + (this.parent ? this.parent.global.y : 0);
    }
    layout() {
        let y = this.nodeSize.height + NodeGraphEditorNode.childSpacing;
        external_underscore_default().each(this.children, function (child) {
            const size = child.measure();
            child.setPosition(NodeGraphEditorNode.childMargin, y);
            child.layout(); // Recurse to layout children
            y += size.height + NodeGraphEditorNode.childSpacing;
        });
    }
    sortConnections() {
        const _this = this;
        this.connections.sort(function (a, b) {
            return a.getPropertyFor(_this) < b.getPropertyFor(_this) ? -1 : 1;
        });
    }
    measure() {
        if (this.measuredSize)
            return this.measuredSize;
        if (!this.children) {
            this.measuredSize = NodeGraphEditorNode.size;
        }
        else {
            const size = {
                width: NodeGraphEditorNode.size.width,
                height: NodeGraphEditorNode.size.height
            };
            // Collect all connections into plugs and groups
            const plugs = (this.plugs = []);
            /*  var groups = this.plugGroups = {};
            function addPlugToGroup(p,group) {
              var name = group?group:'Other';
              if(!groups[name]) groups[name] = {name:name,leftCons:0,rightCons:0,plugs:[]};
              groups[name].plugs.push(p);
              return groups[name];
            }*/
            for (const i in this.connections) {
                const con = this.connections[i];
                const prop = con.getPropertyFor(this);
                const loc = con.getLocationRelativeTo(this) === 'left' ? 'right' : 'left';
                let p = plugs[plugs.length - 1];
                // Connections are sorted alphabetically, so if there are multiple connections
                // to this port they will be directly after each other in the array
                if (p && p.property === prop) {
                    p.loc = p.loc === loc ? loc : 'middle'; // have connection on multiple side, center the plug
                    con.setPlugFor(this, p);
                }
                else {
                    plugs.push({
                        property: prop,
                        displayName: con.getPortDisplayNameFor(this),
                        loc: loc,
                        dir: con.getDirectionFor(this),
                        leftCons: [],
                        rightCons: [],
                        index: con.getPortIndexFor(this)
                    });
                    p = plugs[plugs.length - 1];
                    con.setPlugFor(this, p);
                    //addPlugToGroup(p,con.getPortGroupNameFor(this));
                }
                // Store the connections based on where they are coming from
                if (loc === 'left')
                    p.leftCons.push(con);
                else
                    p.rightCons.push(con);
                // Set the icon for the left or right side of the plug
                p[loc + 'Icon'] =
                    p[loc + 'Icon'] === undefined || p[loc + 'Icon'] === con.getDirectionFor(this)
                        ? con.getDirectionFor(this)
                        : 'both';
            }
            plugs.sort((a, b) => a.index - b.index);
            // Layout and measure connections
            const rowBreakPortNameLength = 10;
            let offset = 0;
            function layoutPlugs(plugs, g) {
                for (const p of plugs) {
                    // Measure and place the plugs
                    const label = p.displayName ? p.displayName : p.property;
                    if (p.loc === 'middle' || label.length > rowBreakPortNameLength) {
                        // p.col is 'middle' or string to long to share line
                        p.index = Math.max(g.rightCons, g.leftCons) + offset;
                        g.rightCons = g.leftCons = p.index + 1 - offset;
                    }
                    else if (p.loc === 'left') {
                        p.index = g.leftCons + offset;
                        g.leftCons++;
                    }
                    else if (p.loc === 'right') {
                        p.index = g.rightCons + offset;
                        g.rightCons++;
                    }
                }
                return Math.max(g.rightCons, g.leftCons);
            }
            // Don't show group title if there is only and Other group
            offset = layoutPlugs(plugs, { leftCons: 0, rightCons: 0 });
            this.updateIcon(); //make sure we have the right icon when measuring
            if (offset === 0) {
                // No plugs
                size.height = Math.max(NodeGraphEditorNode.size.height, this.titlebarHeight());
            }
            else {
                size.height =
                    offset * NodeGraphEditorNode.propertyConnectionHeight +
                        this.titlebarHeight() +
                        NodeGraphEditorNode.verticalSpacing * 2;
            }
            this.nodeSize = { width: size.width, height: size.height };
            external_underscore_default().each(this.children, function (child) {
                const childSize = child.measure();
                size.height += childSize.height + NodeGraphEditorNode.childSpacing;
                size.width = Math.max(NodeGraphEditorNode.childMargin + childSize.width, size.width);
            });
            this.measuredSize = size;
        }
        return this.measuredSize;
    }
    shouldConnect(pos, fromNode, origin) {
        const x = (origin ? origin.x : 0) + this.x;
        const y = (origin ? origin.y : 0) + this.y;
        if (pos.x > x && pos.x < x + this.nodeSize.width && pos.y > y && pos.y < y + this.nodeSize.height) {
            return this;
        }
        // Recurse to children
        for (const i in this.children) {
            const node = this.children[i].shouldConnect(pos, fromNode, { x: x, y: y });
            if (node)
                return node;
        }
    }
    isVisual() {
        return this.model.type.visual;
    }
    canHaveVisualChildren() {
        return this.model.type.canHaveVisualChildren;
    }
    shouldAttach(pos, nodes) {
        return nodeShouldAttach(this, pos, nodes);
    }
    insertChild(child, index) {
        // Move child position into local coords
        const global = this.global;
        child.x -= global.x;
        child.y -= global.y;
        // Insert child in hierarchy
        child.parent = this;
        this.children.splice(index, 0, child);
    }
    addChild(child) {
        this.children.push(child);
        child.parent = this;
    }
    removeChild(child) {
        const idx = this.children.indexOf(child);
        idx !== -1 && this.children.splice(idx, 1);
    }
    detach() {
        if (this.parent) {
            // Find my position in global space
            const global = this.global;
            this.x = global.x;
            this.y = global.y;
            // Detatch
            const idx = this.parent.children.indexOf(this);
            this.parent.children.splice(idx, 1);
            this.parent = undefined;
        }
    }
    /**
     * Check if a point (in local node coordinates) is within the comment icon bounds
     */
    isPointInCommentIcon(pos) {
        if (!this.commentIconBounds)
            return false;
        // Convert local pos to global for comparison with commentIconBounds (which are in global coords)
        const globalX = pos.x + this.global.x;
        const globalY = pos.y + this.global.y;
        const bounds = this.commentIconBounds;
        const padding = 4; // Extra hit area padding for easier clicking
        return (globalX >= bounds.x - padding &&
            globalX <= bounds.x + bounds.width + padding &&
            globalY >= bounds.y - padding &&
            globalY <= bounds.y + bounds.height + padding);
    }
    /**
     * Show a popup for editing the node comment
     */
    showCommentEditPopup() {
        const currentComment = this.model.getComment() || '';
        const nodeLabel = this.model.label || 'Node';
        const model = this.model;
        const owner = this.owner;
        // Use PopupLayer.StringInputPopup for Electron compatibility
        const popup = new (popuplayer_default()).StringInputPopup({
            label: `Comment for "${nodeLabel}"`,
            okLabel: 'Save',
            cancelLabel: 'Cancel',
            onOk: (newComment) => {
                // Set comment with undo support
                model.setComment(newComment || undefined, {
                    undo: true,
                    label: newComment ? 'Edit node comment' : 'Remove node comment'
                });
                // Repaint to update the icon appearance
                owner.repaint();
                popuplayer_default().instance.hidePopup();
            },
            onCancel: () => {
                popuplayer_default().instance.hidePopup();
            }
        });
        // Render popup BEFORE showing it
        popup.render();
        // Set initial value after render
        popup.$('.string-input-popup-input').val(currentComment);
        // Use requestAnimationFrame + setTimeout to ensure we're past both the current
        // event cycle AND any pending DOM updates. This prevents the PopupLayer's body
        // click handler from immediately closing the popup.
        requestAnimationFrame(() => {
            setTimeout(() => {
                popuplayer_default().instance.showPopup({
                    content: popup,
                    position: 'screen-center',
                    isBackgroundDimmed: true
                });
            }, 100); // 100ms delay to be extra safe
        });
    }
}
NodeGraphEditorNode.size = { width: 150, height: 36 };
NodeGraphEditorNode.childMargin = 20;
NodeGraphEditorNode.childSpacing = 10;
NodeGraphEditorNode.borderSize = 7;
NodeGraphEditorNode.attachedThreshold = 20;
NodeGraphEditorNode.propertyConnectionHeight = 20;
NodeGraphEditorNode.verticalSpacing = 8;
NodeGraphEditorNode.cornerRadius = 6;

// EXTERNAL MODULE: ./src/editor/src/utils/utils.ts
var utils = __webpack_require__(93015);
;// ./src/editor/src/utils/ExtractToComponent.ts





function flattenTree(roots) {
    const nodes = new Set();
    function addSubtree(node) {
        nodes.add(node);
        for (const child of node.children) {
            addSubtree(child);
        }
    }
    roots.forEach(addSubtree);
    return Array.from(nodes);
}
function extractToComponent(projectModel, nodeGraphModel, nodeset, selectedNodes, newNodePosition) {
    const undoGroup = new undo_queue_model/* UndoActionGroup */.C({ label: 'extract to component' });
    const name = generateName(projectModel, nodeGraphModel);
    const component = new componentmodel/* ComponentModel */.j({
        name,
        graph: new nodegraphmodel/* NodeGraphModel */.W2(),
        id: (0,utils.guid)()
    });
    //get the parent of one of the visual nodes so we know where to place the new component instace
    const firstNodeWithParent = getFirstNodeWithExternalParent(selectedNodes);
    const parent = firstNodeWithParent === null || firstNodeWithParent === void 0 ? void 0 : firstNodeWithParent.parent;
    const childIndex = parent === null || parent === void 0 ? void 0 : parent.children.indexOf(firstNodeWithParent);
    //get all nodes, including children
    const selectedNodesAndChildren = flattenTree(selectedNodes);
    //figure out which connections needs to move to component inputs and outputs
    const [componentInputs, componentOutputs] = collectComponentInputsAndOutputs(nodeGraphModel, selectedNodesAndChildren);
    //remove the nodes we're extracting
    nodeGraphModel.removeNodeSet(nodeset, { undo: undoGroup });
    //set the origin of the nodes to 0,0
    const originalOrigin = nodeset.getOriginPosition();
    undoGroup.pushAndDo({
        do() {
            nodeset.setOriginPosition({ x: 0, y: 0 });
        },
        undo() {
            nodeset.setOriginPosition(originalOrigin);
        }
    });
    //and add them to the new component
    component.graph.insertNodeSet(nodeset, { undo: undoGroup });
    //connect the component input and output nodes
    connectComponentInputsAndOutputs(component, componentInputs, componentOutputs, undoGroup);
    //add the new component to the project
    projectModel.addComponent(component, { undo: undoGroup });
    //create an instance of the new component...
    const node = nodegraphmodel/* NodeGraphNode */.dF.fromJSON({
        type: name,
        id: (0,utils.guid)(),
        x: newNodePosition.x,
        y: newNodePosition.y
    });
    if (parent) {
        parent.model.insertChild(node, childIndex, { undo: undoGroup });
    }
    else {
        nodeGraphModel.addRoot(node, { undo: undoGroup });
    }
    connectExternalInputsAndOutputs(nodeGraphModel, node, componentInputs, componentOutputs, undoGroup);
    undo_queue_model/* UndoQueue */.g.instance.push(undoGroup);
}
function canExtractToComponent(nodeGraphModel, selectedNodes) {
    //can't extract siblings since they would require a new parent which could change behavior, so don't allow it
    const parents = getParents(selectedNodes);
    if (parents.length > 1) {
        return { allow: false, reason: 'Nodes that are siblings must have have their parent selected' };
    }
    //extracting component and outputs nodes aren't implemented (but would be fairly straight forward to do)
    const hasComponentInputs = selectedNodes.some((node) => node.model.typename === 'Component Inputs');
    if (hasComponentInputs) {
        return { allow: false, reason: 'Extracting a Component Inputs node is unsupported' };
    }
    const hasComponentOutputs = selectedNodes.some((node) => node.model.typename === 'Component Outputs');
    if (hasComponentOutputs) {
        return { allow: false, reason: 'Extracting a Component Outputs node is unsupported' };
    }
    return { allow: true };
}
//Get all parents. Exclude parents that are part of the nodes array (so a hiererachy of nodes won't include "internal" parents)
function getParents(nodes) {
    const parents = [];
    for (const node of nodes) {
        if (node.parent && !nodes.includes(node.parent)) {
            parents.push(node.parent);
        }
    }
    return parents;
}
function getFirstNodeWithExternalParent(nodes) {
    for (const node of nodes) {
        if (node.parent && !nodes.includes(node.parent)) {
            return node;
        }
    }
    return null;
}
function collectComponentInputsAndOutputs(nodeGraphModel, nodes) {
    const inputs = [];
    const outputs = [];
    const extractedNodeIds = new Set(Array.from(nodes.values()).map((node) => node.id));
    nodeGraphModel.forEachConnection((c) => {
        if (extractedNodeIds.has(c.fromId) && !extractedNodeIds.has(c.toId)) {
            //get the display name of the port to make the component port names nicer
            const port = nodeGraphModel.findNodeWithId(c.toId).findPortWithName(c.toProperty);
            const portName = port.displayName || c.toProperty;
            outputs.push({ connection: c, portName });
        }
        else if (!extractedNodeIds.has(c.fromId) && extractedNodeIds.has(c.toId)) {
            const port = nodeGraphModel.findNodeWithId(c.toId).findPortWithName(c.toProperty);
            const portName = port.displayName || c.toProperty;
            inputs.push({ connection: c, portName });
        }
    });
    //group all connection that can share one conneciton
    //e.g. two connection that both trigger the same output should have one component output and not two
    const inputGroups = {};
    for (const input of inputs) {
        const id = input.connection.fromId + input.connection.fromProperty;
        if (!inputGroups[id]) {
            inputGroups[id] = [];
        }
        inputGroups[id].push(input);
    }
    const outputGroups = {};
    for (const output of outputs) {
        const id = output.connection.toId + output.connection.toProperty;
        if (!outputGroups[id]) {
            outputGroups[id] = [];
        }
        outputGroups[id].push(output);
    }
    //make sure connection groups doesn't have name collisions
    resolveNameCollisions(Object.values(inputGroups));
    resolveNameCollisions(Object.values(outputGroups));
    return [inputs, outputs];
}
function resolveNameCollisions(groups) {
    const nameCounter = {};
    for (const group of groups) {
        const portName = group[0].portName;
        if (!nameCounter[portName]) {
            nameCounter[portName] = 1;
        }
        else {
            nameCounter[portName]++;
        }
        const count = nameCounter[portName];
        if (count > 1) {
            group.forEach((connectionInfo) => (connectionInfo.portName = portName + ' ' + count));
        }
    }
}
function connectComponentInputsAndOutputs(component, inputs, outputs, undoGroup) {
    if (inputs.length) {
        const componentInput = nodegraphmodel/* NodeGraphNode */.dF.fromJSON({
            type: 'Component Inputs',
            id: (0,utils.guid)(),
            ...getComponentInputsPosition(component, inputs.length),
            ports: inputs.map((input) => ({
                name: input.portName,
                plug: 'output',
                type: {
                    name: '*'
                }
            }))
        });
        component.graph.addRoot(componentInput, { args: undoGroup });
        for (const input of inputs) {
            const c = {
                fromId: componentInput.id,
                fromProperty: input.portName,
                toId: input.connection.toId,
                toProperty: input.connection.toProperty
            };
            component.graph.addConnection(c, { undo: undoGroup });
        }
    }
    //outputs
    if (outputs.length) {
        const componentOutput = nodegraphmodel/* NodeGraphNode */.dF.fromJSON({
            type: 'Component Outputs',
            id: (0,utils.guid)(),
            ...getComponentOutputsPosition(component, outputs.length),
            ports: outputs.map((output) => ({
                name: output.portName,
                plug: 'input',
                type: {
                    name: '*'
                }
            }))
        });
        component.graph.addRoot(componentOutput, { args: undoGroup });
        for (const output of outputs) {
            const c = {
                fromId: output.connection.fromId,
                fromProperty: output.connection.fromProperty,
                toId: componentOutput.id,
                toProperty: output.portName
            };
            component.graph.addConnection(c, { undo: undoGroup });
        }
    }
}
function connectExternalInputsAndOutputs(nodeGraphModel, node, inputs, outputs, undoGroup) {
    //add connections to component inputs
    for (const input of inputs) {
        nodeGraphModel.addConnection({
            fromId: input.connection.fromId,
            fromProperty: input.connection.fromProperty,
            toId: node.id,
            toProperty: input.portName
        }, { undo: undoGroup });
    }
    //and outputs
    for (const output of outputs) {
        nodeGraphModel.addConnection({
            fromId: node.id,
            fromProperty: output.portName,
            toId: output.connection.toId,
            toProperty: output.connection.toProperty
        }, { undo: undoGroup });
    }
}
function generateName(projectModel, nodeGraphModel) {
    let name;
    let i = 1;
    do {
        name = nodeGraphModel.owner.fullName + '/Extracted component' + (i > 1 ? ' ' + i : '');
        i++;
    } while (projectModel.getComponentWithName(name));
    return name;
}
function getComponentInputsPosition(component, numOutputs) {
    const aabb = getAABBForNodesAndCommentsIntersecting(component, 0, 200 + numOutputs * NodeGraphEditorNode.propertyConnectionHeight);
    return { x: aabb.minX - NodeGraphEditorNode.size.width - 100, y: 100 };
}
function getComponentOutputsPosition(component, numInputs) {
    const aabb = getAABBForNodesAndCommentsIntersecting(component, 0, 200 + numInputs * NodeGraphEditorNode.propertyConnectionHeight);
    return { x: aabb.maxX + 100, y: 100 };
}
function getAABBForNodesAndCommentsIntersecting(component, minY, maxY) {
    const comments = component.graph.commentsModel.getComments();
    const nodes = component.getNodes();
    const rects = comments.concat(nodes.map((node) => {
        const nodeSize = NodeGraphEditorNode.size; //this is just the start size so height is likely incorrect. Good enough for our purposes here
        return {
            x: node.x,
            y: node.y,
            width: nodeSize.width,
            height: nodeSize.height
        };
    }));
    const aabb = {
        minX: Number.MAX_VALUE,
        maxX: -Number.MAX_VALUE,
        minY: Number.MAX_VALUE,
        maxY: -Number.MAX_VALUE
    };
    const rectsInBounds = rects.filter((r) => (r.y >= minY && r.y <= maxY) || (r.y + r.height >= minY && r.y + r.height <= maxY));
    for (const rect of rectsInBounds) {
        if (rect.x < aabb.minX) {
            aabb.minX = rect.x;
        }
        if (rect.x + rect.width > aabb.maxX) {
            aabb.maxX = rect.x + rect.width;
        }
        if (rect.y < aabb.minY) {
            aabb.minY = rect.y;
        }
        if (rect.y + rect.height > aabb.maxY) {
            aabb.maxY = rect.y + rect.height;
        }
    }
    return aabb;
}

// EXTERNAL MODULE: ./src/editor/src/utils/keyboard/KeyCode.ts
var KeyCode = __webpack_require__(7444);
// EXTERNAL MODULE: ./src/editor/src/utils/keyboardhandler.ts
var keyboardhandler = __webpack_require__(70441);
// EXTERNAL MODULE: ./src/editor/src/utils/NodeGraph/index.ts
var NodeGraph = __webpack_require__(52877);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/BaseDialog/index.ts + 3 modules
var BaseDialog = __webpack_require__(65762);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/popups/MenuDialog/index.ts + 2 modules
var MenuDialog = __webpack_require__(23442);
// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/inputs/IconButton/index.ts + 2 modules
var IconButton = __webpack_require__(28208);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Stack/index.ts + 2 modules
var Stack = __webpack_require__(86380);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/popups/ContextMenu/index.ts + 2 modules
var ContextMenu = __webpack_require__(93739);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/popups/Tooltip/index.ts + 2 modules
var Tooltip = __webpack_require__(87073);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/popups/PopupToolbar/PopupToolbar.module.scss
var PopupToolbar_module = __webpack_require__(53790);
;// ../noodl-core-ui/src/components/popups/PopupToolbar/PopupToolbar.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(PopupToolbar_module/* default */.A, options);




       /* harmony default export */ const PopupToolbar_PopupToolbar_module = (PopupToolbar_module/* default */.A && PopupToolbar_module/* default */.A.locals ? PopupToolbar_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/popups/PopupToolbar/PopupToolbar.tsx









function PopupToolbar({ menuItems, contextMenuItems }) {
    return (external_react_default().createElement("div", { tabIndex: 1, className: external_classnames_default()(PopupToolbar_PopupToolbar_module['Root']) },
        external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_className: external_classnames_default()(PopupToolbar_PopupToolbar_module['IconList']) },
            menuItems.map((item) => (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: item.tooltip, showAfterMs: 300 },
                external_react_default().createElement(IconButton/* IconButton */.K0, { variant: IconButton/* IconButtonVariant */.nl.SemiTransparent, icon: item.icon, onClick: item.onClick, size: Icon/* IconSize */.lK.Default })))),
            Boolean(contextMenuItems === null || contextMenuItems === void 0 ? void 0 : contextMenuItems.length) && (external_react_default().createElement(ContextMenu/* ContextMenu */.t, { menuItems: contextMenuItems, size: Icon/* IconSize */.lK.Default, variant: IconButton/* IconButtonVariant */.nl.SemiTransparent, renderDirection: BaseDialog/* DialogRenderDirection */.K1.Horizontal })))));
}

;// ../noodl-core-ui/src/components/popups/PopupToolbar/index.ts


// EXTERNAL MODULE: ./src/shared/utils/EventDispatcher.ts
var EventDispatcher = __webpack_require__(11138);
// EXTERNAL MODULE: ./src/shared/view.js
var view = __webpack_require__(92207);
var view_default = /*#__PURE__*/__webpack_require__.n(view);
;// ./src/editor/src/contexts/CanvasTabsContext.tsx


const CanvasTabsContext = (0,external_react_.createContext)(undefined);
/**
 * Hook to access canvas tabs context
 */
function useCanvasTabs() {
    const context = (0,external_react_.useContext)(CanvasTabsContext);
    if (!context) {
        throw new Error('useCanvasTabs must be used within a CanvasTabsProvider');
    }
    return context;
}
/**
 * Provider for canvas tabs state
 */
function CanvasTabsProvider({ children }) {
    // Start with no tabs - Logic Builder tabs are opened on demand
    const [tabs, setTabs] = (0,external_react_.useState)([]);
    const [activeTabId, setActiveTabId] = (0,external_react_.useState)(undefined);
    /**
     * Open a new tab or switch to existing one
     */
    const openTab = (0,external_react_.useCallback)((newTab) => {
        // Generate ID if not provided
        const tabId = newTab.id || `${newTab.type}-${newTab.nodeId || Date.now()}`;
        setTabs((prevTabs) => {
            // Check if tab already exists
            const existingTab = prevTabs.find((t) => t.id === tabId);
            if (existingTab) {
                // Tab exists, just switch to it
                setActiveTabId(tabId);
                return prevTabs;
            }
            // Add new tab
            const tab = {
                ...newTab,
                id: tabId
            };
            const newTabs = [...prevTabs, tab];
            // Emit event that a Logic Builder tab was opened (first tab)
            if (prevTabs.length === 0) {
                EventDispatcher.EventDispatcher.instance.emit('LogicBuilder.TabOpened');
            }
            return newTabs;
        });
        // Switch to the new/existing tab
        setActiveTabId(tabId);
    }, []);
    /**
     * Listen for Logic Builder tab open requests from property panel
     */
    (0,external_react_.useEffect)(() => {
        const context = {};
        const handleOpenTab = (data) => {
            console.log('[CanvasTabsContext] Received LogicBuilder.OpenTab event:', data);
            openTab({
                type: 'logic-builder',
                nodeId: data.nodeId,
                nodeName: data.nodeName,
                workspace: data.workspace
            });
        };
        EventDispatcher.EventDispatcher.instance.on('LogicBuilder.OpenTab', handleOpenTab, context);
        return () => {
            EventDispatcher.EventDispatcher.instance.off(context);
        };
    }, [openTab]);
    /**
     * Close a tab by ID
     */
    const closeTab = (0,external_react_.useCallback)((tabId) => {
        setTabs((prevTabs) => {
            const tabIndex = prevTabs.findIndex((t) => t.id === tabId);
            if (tabIndex === -1) {
                return prevTabs;
            }
            const newTabs = prevTabs.filter((t) => t.id !== tabId);
            // If closing the active tab, switch to another tab or clear active
            if (activeTabId === tabId) {
                if (newTabs.length > 0) {
                    setActiveTabId(newTabs[newTabs.length - 1].id);
                }
                else {
                    setActiveTabId(undefined);
                    // Emit event that all Logic Builder tabs are closed
                    EventDispatcher.EventDispatcher.instance.emit('LogicBuilder.AllTabsClosed');
                }
            }
            return newTabs;
        });
    }, [activeTabId]);
    /**
     * Switch to a different tab
     */
    const switchTab = (0,external_react_.useCallback)((tabId) => {
        setTabs((prevTabs) => {
            // Verify tab exists
            const tab = prevTabs.find((t) => t.id === tabId);
            if (!tab) {
                console.warn(`[CanvasTabs] Tab ${tabId} not found`);
                return prevTabs;
            }
            setActiveTabId(tabId);
            return prevTabs;
        });
    }, []);
    /**
     * Update tab data
     */
    const updateTab = (0,external_react_.useCallback)((tabId, updates) => {
        setTabs((prevTabs) => {
            return prevTabs.map((tab) => {
                if (tab.id === tabId) {
                    return { ...tab, ...updates };
                }
                return tab;
            });
        });
    }, []);
    /**
     * Get tab by ID
     */
    const getTab = (0,external_react_.useCallback)((tabId) => {
        return tabs.find((t) => t.id === tabId);
    }, [tabs]);
    const value = {
        tabs,
        activeTabId,
        openTab,
        closeTab,
        switchTab,
        updateTab,
        getTab
    };
    return external_react_default().createElement(CanvasTabsContext.Provider, { value: value }, children);
}

// EXTERNAL MODULE: ./src/editor/src/models/warningsmodel.ts
var warningsmodel = __webpack_require__(86105);
// EXTERNAL MODULE: ./src/editor/src/services/HighlightManager/index.ts + 4 modules
var HighlightManager = __webpack_require__(57002);
// EXTERNAL MODULE: ../../node_modules/blockly/javascript_compressed.js
var javascript_compressed = __webpack_require__(38880);
;// ../../node_modules/blockly/javascript.mjs

const {
  JavascriptGenerator,
  Order,
  javascriptGenerator,
} = javascript_compressed;

;// ./src/editor/src/views/BlocklyEditor/NoodlGenerators.ts
/**
 * Noodl Code Generators for Blockly
 *
 * Converts Blockly blocks into executable JavaScript code for the Noodl runtime.
 * Generated code has access to:
 * - Inputs: Input values from connections
 * - Outputs: Output values to connections
 * - Noodl.Variables: Global variables
 * - Noodl.Objects: Global objects
 * - Noodl.Arrays: Global arrays
 *
 * @module BlocklyEditor
 */

/**
 * Initialize all Noodl code generators
 */
function initNoodlGenerators() {
    console.log('🔧 [Blockly] Initializing Noodl code generators');
    // Input/Output generators
    initInputOutputGenerators();
    // Variable generators
    initVariableGenerators();
    // Object generators
    initObjectGenerators();
    // Array generators
    initArrayGenerators();
    console.log('✅ [Blockly] Noodl generators initialized');
}
/**
 * Input/Output Generators
 */
function initInputOutputGenerators() {
    // Define Input - no runtime code (used for I/O detection only)
    javascriptGenerator.forBlock['noodl_define_input'] = function () {
        return '';
    };
    // Get Input - generates: Inputs["name"]
    javascriptGenerator.forBlock['noodl_get_input'] = function (block) {
        const name = block.getFieldValue('NAME');
        const code = `Inputs["${name}"]`;
        return [code, Order.MEMBER];
    };
    // Define Output - no runtime code (used for I/O detection only)
    javascriptGenerator.forBlock['noodl_define_output'] = function () {
        return '';
    };
    // Set Output - generates: Outputs["name"] = value;
    javascriptGenerator.forBlock['noodl_set_output'] = function (block) {
        const name = block.getFieldValue('NAME');
        const value = javascriptGenerator.valueToCode(block, 'VALUE', Order.ASSIGNMENT) || 'null';
        return `Outputs["${name}"] = ${value};\n`;
    };
    // Define Signal Input - no runtime code
    javascriptGenerator.forBlock['noodl_define_signal_input'] = function () {
        return '';
    };
    // Define Signal Output - no runtime code
    javascriptGenerator.forBlock['noodl_define_signal_output'] = function () {
        return '';
    };
    // Send Signal - generates: this.sendSignalOnOutput("name");
    javascriptGenerator.forBlock['noodl_send_signal'] = function (block) {
        const name = block.getFieldValue('NAME');
        return `this.sendSignalOnOutput("${name}");\n`;
    };
}
/**
 * Variable Generators
 */
function initVariableGenerators() {
    // Get Variable - generates: Noodl.Variables["name"]
    javascriptGenerator.forBlock['noodl_get_variable'] = function (block) {
        const name = block.getFieldValue('NAME');
        const code = `Noodl.Variables["${name}"]`;
        return [code, Order.MEMBER];
    };
    // Set Variable - generates: Noodl.Variables["name"] = value;
    javascriptGenerator.forBlock['noodl_set_variable'] = function (block) {
        const name = block.getFieldValue('NAME');
        const value = javascriptGenerator.valueToCode(block, 'VALUE', Order.ASSIGNMENT) || 'null';
        return `Noodl.Variables["${name}"] = ${value};\n`;
    };
}
/**
 * Object Generators
 */
function initObjectGenerators() {
    // Get Object - generates: Noodl.Objects[id]
    javascriptGenerator.forBlock['noodl_get_object'] = function (block) {
        const id = javascriptGenerator.valueToCode(block, 'ID', Order.NONE) || '""';
        const code = `Noodl.Objects[${id}]`;
        return [code, Order.MEMBER];
    };
    // Get Object Property - generates: object["property"]
    javascriptGenerator.forBlock['noodl_get_object_property'] = function (block) {
        const property = block.getFieldValue('PROPERTY');
        const object = javascriptGenerator.valueToCode(block, 'OBJECT', Order.MEMBER) || '{}';
        const code = `${object}["${property}"]`;
        return [code, Order.MEMBER];
    };
    // Set Object Property - generates: object["property"] = value;
    javascriptGenerator.forBlock['noodl_set_object_property'] = function (block) {
        const property = block.getFieldValue('PROPERTY');
        const object = javascriptGenerator.valueToCode(block, 'OBJECT', Order.MEMBER) || '{}';
        const value = javascriptGenerator.valueToCode(block, 'VALUE', Order.ASSIGNMENT) || 'null';
        return `${object}["${property}"] = ${value};\n`;
    };
}
/**
 * Array Generators
 */
function initArrayGenerators() {
    // Get Array - generates: Noodl.Arrays["name"]
    javascriptGenerator.forBlock['noodl_get_array'] = function (block) {
        const name = block.getFieldValue('NAME');
        const code = `Noodl.Arrays["${name}"]`;
        return [code, Order.MEMBER];
    };
    // Array Length - generates: array.length
    javascriptGenerator.forBlock['noodl_array_length'] = function (block) {
        const array = javascriptGenerator.valueToCode(block, 'ARRAY', Order.MEMBER) || '[]';
        const code = `${array}.length`;
        return [code, Order.MEMBER];
    };
    // Array Add - generates: array.push(item);
    javascriptGenerator.forBlock['noodl_array_add'] = function (block) {
        const item = javascriptGenerator.valueToCode(block, 'ITEM', Order.NONE) || 'null';
        const array = javascriptGenerator.valueToCode(block, 'ARRAY', Order.MEMBER) || '[]';
        return `${array}.push(${item});\n`;
    };
}
/**
 * Generate complete JavaScript code from workspace
 *
 * @param workspace - The Blockly workspace
 * @returns Generated JavaScript code
 */
function generateCode(workspace) {
    return javascriptGenerator.workspaceToCode(workspace);
}

;// ./src/editor/src/utils/IODetector.ts
/**
 * IODetector
 *
 * Utility for detecting inputs, outputs, and signals from Blockly workspaces.
 * Scans workspace JSON to find Input/Output definition blocks and extracts their configuration.
 *
 * @module utils
 */
/**
 * Detect all I/O from a Blockly workspace JSON
 *
 * @param workspaceJson - Serialized Blockly workspace (JSON string or object)
 * @returns Detected inputs, outputs, and signals
 */
function detectIO(workspaceJson) {
    const result = {
        inputs: [],
        outputs: [],
        signalInputs: [],
        signalOutputs: []
    };
    try {
        const workspace = typeof workspaceJson === 'string' ? JSON.parse(workspaceJson) : workspaceJson;
        if (!workspace || !workspace.blocks || !workspace.blocks.blocks) {
            return result;
        }
        const blocks = workspace.blocks.blocks;
        for (const block of blocks) {
            processBlock(block, result);
        }
    }
    catch (error) {
        console.error('[IODetector] Failed to parse workspace:', error);
    }
    // Remove duplicates
    result.inputs = uniqueBy(result.inputs, 'name');
    result.outputs = uniqueBy(result.outputs, 'name');
    result.signalInputs = Array.from(new Set(result.signalInputs));
    result.signalOutputs = Array.from(new Set(result.signalOutputs));
    return result;
}
/**
 * Recursively process a block and its children
 */
function processBlock(block, result) {
    if (!block || !block.type)
        return;
    switch (block.type) {
        case 'noodl_define_input':
            // Extract input definition
            if (block.fields && block.fields.NAME && block.fields.TYPE) {
                result.inputs.push({
                    name: block.fields.NAME,
                    type: block.fields.TYPE
                });
            }
            break;
        case 'noodl_get_input':
            // Auto-detect input from usage
            if (block.fields && block.fields.NAME) {
                const name = block.fields.NAME;
                if (!result.inputs.find((i) => i.name === name)) {
                    result.inputs.push({
                        name: name,
                        type: '*' // Default type
                    });
                }
            }
            break;
        case 'noodl_define_output':
            // Extract output definition
            if (block.fields && block.fields.NAME && block.fields.TYPE) {
                result.outputs.push({
                    name: block.fields.NAME,
                    type: block.fields.TYPE
                });
            }
            break;
        case 'noodl_set_output':
            // Auto-detect output from usage
            if (block.fields && block.fields.NAME) {
                const name = block.fields.NAME;
                if (!result.outputs.find((o) => o.name === name)) {
                    result.outputs.push({
                        name: name,
                        type: '*' // Default type
                    });
                }
            }
            break;
        case 'noodl_define_signal_input':
            // Extract signal input definition
            if (block.fields && block.fields.NAME) {
                result.signalInputs.push(block.fields.NAME);
            }
            break;
        case 'noodl_on_signal':
            // Auto-detect signal input from event handler
            if (block.fields && block.fields.SIGNAL) {
                const name = block.fields.SIGNAL;
                if (!result.signalInputs.includes(name)) {
                    result.signalInputs.push(name);
                }
            }
            break;
        case 'noodl_define_signal_output':
            // Extract signal output definition
            if (block.fields && block.fields.NAME) {
                result.signalOutputs.push(block.fields.NAME);
            }
            break;
        case 'noodl_send_signal':
            // Auto-detect signal output from send blocks
            if (block.fields && block.fields.NAME) {
                const name = block.fields.NAME;
                if (!result.signalOutputs.includes(name)) {
                    result.signalOutputs.push(name);
                }
            }
            break;
    }
    // Process nested blocks (inputs, next, etc.)
    if (block.inputs) {
        for (const inputKey in block.inputs) {
            const input = block.inputs[inputKey];
            if (input && input.block) {
                processBlock(input.block, result);
            }
        }
    }
    if (block.next && block.next.block) {
        processBlock(block.next.block, result);
    }
}
/**
 * Remove duplicates from array based on key
 */
function uniqueBy(array, key) {
    const seen = new Set();
    return array.filter((item) => {
        const k = item[key];
        if (seen.has(k)) {
            return false;
        }
        seen.add(k);
        return true;
    });
}

;// ./src/editor/src/utils/BlocklyEditorGlobals.ts
/**
 * Blockly Editor Globals
 *
 * Exposes Blockly-related utilities to the global scope for use by runtime nodes
 */


/**
 * Initialize Blockly editor globals
 * This makes IODetector and code generation available to runtime nodes
 */
function initBlocklyEditorGlobals() {
    console.log('🔍 [BlocklyGlobals] initBlocklyEditorGlobals called');
    console.log('🔍 [BlocklyGlobals] window undefined?', typeof window === 'undefined');
    // Create NoodlEditor namespace if it doesn't exist
    if (typeof window !== 'undefined') {
        console.log('🔍 [BlocklyGlobals] window.NoodlEditor before:', window.NoodlEditor);
        if (!window.NoodlEditor) {
            window.NoodlEditor = {};
            console.log('🔍 [BlocklyGlobals] Created new window.NoodlEditor');
        }
        // Expose IODetector
        window.NoodlEditor.detectIO = detectIO;
        console.log('🔍 [BlocklyGlobals] Assigned detectIO:', typeof window.NoodlEditor.detectIO);
        // Expose code generator
        window.NoodlEditor.generateBlocklyCode = generateCode;
        console.log('🔍 [BlocklyGlobals] Assigned generateBlocklyCode:', typeof window.NoodlEditor.generateBlocklyCode);
        console.log('✅ [Blockly] Editor globals initialized');
        console.log('🔍 [BlocklyGlobals] window.NoodlEditor after:', window.NoodlEditor);
    }
}
// Auto-initialize when module loads
initBlocklyEditorGlobals();

// EXTERNAL MODULE: ./src/editor/src/utils/debuginspector.js
var debuginspector = __webpack_require__(20435);
var debuginspector_default = /*#__PURE__*/__webpack_require__.n(debuginspector);
// EXTERNAL MODULE: ./src/editor/src/hooks/useEventListener.ts
var useEventListener = __webpack_require__(76750);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightedConnection.module.scss
var HighlightedConnection_module = __webpack_require__(35242);
;// ./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightedConnection.module.scss

      
      
      
      
      
      
      
      
      

var HighlightedConnection_module_options = {};

HighlightedConnection_module_options.styleTagTransform = (styleTagTransform_default());
HighlightedConnection_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      HighlightedConnection_module_options.insert = insertBySelector_default().bind(null, "head");
    
HighlightedConnection_module_options.domAPI = (styleDomAPI_default());
HighlightedConnection_module_options.insertStyleElement = (insertStyleElement_default());

var HighlightedConnection_module_update = injectStylesIntoStyleTag_default()(HighlightedConnection_module/* default */.A, HighlightedConnection_module_options);




       /* harmony default export */ const HighlightOverlay_HighlightedConnection_module = (HighlightedConnection_module/* default */.A && HighlightedConnection_module/* default */.A.locals ? HighlightedConnection_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightedConnection.tsx
/**
 * HighlightedConnection - Renders a highlight along a connection path
 *
 * Displays visual highlight effect along canvas connection paths with support for
 * different styles (solid, glow, pulse) and custom colors.
 */



/**
 * HighlightedConnection component
 *
 * Renders an SVG path from the source node's right edge to the target node's left edge,
 * using a bezier curve similar to the actual connection rendering.
 */
function HighlightedConnection({ connection, fromBounds, toBounds, color, style }) {
    // Calculate connection path
    const pathData = (0,external_react_.useMemo)(() => {
        // Start point: right edge of source node
        const x1 = fromBounds.x + fromBounds.width;
        const y1 = fromBounds.y + fromBounds.height / 2;
        // End point: left edge of target node
        const x2 = toBounds.x;
        const y2 = toBounds.y + toBounds.height / 2;
        // Bezier control points for smooth curve
        const dx = Math.abs(x2 - x1);
        const curve = Math.min(dx * 0.5, 100); // Max curve of 100px
        const cx1 = x1 + curve;
        const cy1 = y1;
        const cx2 = x2 - curve;
        const cy2 = y2;
        return `M ${x1} ${y1} C ${cx1} ${cy1}, ${cx2} ${cy2}, ${x2} ${y2}`;
    }, [fromBounds, toBounds]);
    // Calculate SVG viewBox to encompass the path
    const viewBox = (0,external_react_.useMemo)(() => {
        const x1 = fromBounds.x + fromBounds.width;
        const y1 = fromBounds.y + fromBounds.height / 2;
        const x2 = toBounds.x;
        const y2 = toBounds.y + toBounds.height / 2;
        const minX = Math.min(x1, x2) - 20; // Add padding for glow
        const minY = Math.min(y1, y2) - 20;
        const maxX = Math.max(x1, x2) + 20;
        const maxY = Math.max(y1, y2) + 20;
        return {
            x: minX,
            y: minY,
            width: maxX - minX,
            height: maxY - minY
        };
    }, [fromBounds, toBounds]);
    // SVG filter IDs must be unique per instance
    const filterId = (0,external_react_.useMemo)(() => `highlight-glow-${connection.fromNodeId}-${connection.toNodeId}`, [connection]);
    return (external_react_default().createElement("svg", { className: external_classnames_default()(HighlightOverlay_HighlightedConnection_module.highlightedConnection, HighlightOverlay_HighlightedConnection_module[style]), style: {
            left: `${viewBox.x}px`,
            top: `${viewBox.y}px`,
            width: `${viewBox.width}px`,
            height: `${viewBox.height}px`
        }, viewBox: `${viewBox.x} ${viewBox.y} ${viewBox.width} ${viewBox.height}`, xmlns: "http://www.w3.org/2000/svg", "data-connection": `${connection.fromNodeId}:${connection.fromPort}-${connection.toNodeId}:${connection.toPort}` },
        style === 'glow' && (external_react_default().createElement("defs", null,
            external_react_default().createElement("filter", { id: filterId, x: "-50%", y: "-50%", width: "200%", height: "200%" },
                external_react_default().createElement("feGaussianBlur", { in: "SourceGraphic", stdDeviation: "4" })))),
        external_react_default().createElement("path", { d: pathData, fill: "none", stroke: color, strokeWidth: style === 'solid' ? 3 : 4, strokeLinecap: "round", filter: style === 'glow' ? `url(#${filterId})` : undefined }),
        style === 'pulse' && (external_react_default().createElement("path", { d: pathData, fill: "none", stroke: color, strokeWidth: 3, strokeLinecap: "round", className: HighlightOverlay_HighlightedConnection_module.pulsePath }))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightedNode.module.scss
var HighlightedNode_module = __webpack_require__(74082);
;// ./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightedNode.module.scss

      
      
      
      
      
      
      
      
      

var HighlightedNode_module_options = {};

HighlightedNode_module_options.styleTagTransform = (styleTagTransform_default());
HighlightedNode_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      HighlightedNode_module_options.insert = insertBySelector_default().bind(null, "head");
    
HighlightedNode_module_options.domAPI = (styleDomAPI_default());
HighlightedNode_module_options.insertStyleElement = (insertStyleElement_default());

var HighlightedNode_module_update = injectStylesIntoStyleTag_default()(HighlightedNode_module/* default */.A, HighlightedNode_module_options);




       /* harmony default export */ const HighlightOverlay_HighlightedNode_module = (HighlightedNode_module/* default */.A && HighlightedNode_module/* default */.A.locals ? HighlightedNode_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightedNode.tsx
/**
 * HighlightedNode - Renders a highlight around a node
 *
 * Displays visual highlight effect around canvas nodes with support for
 * different styles (solid, glow, pulse) and custom colors.
 */



/**
 * HighlightedNode component
 */
function HighlightedNode({ nodeId, bounds, color, style, label }) {
    const highlightStyle = {
        left: `${bounds.x}px`,
        top: `${bounds.y}px`,
        width: `${bounds.width}px`,
        height: `${bounds.height}px`,
        borderColor: color,
        boxShadow: style === 'glow' ? `0 0 20px ${color}, 0 0 10px ${color}` : style === 'pulse' ? `0 0 15px ${color}` : undefined
    };
    return (external_react_default().createElement("div", { className: external_classnames_default()(HighlightOverlay_HighlightedNode_module.highlightedNode, HighlightOverlay_HighlightedNode_module[style]), style: highlightStyle, "data-node-id": nodeId }, label && external_react_default().createElement("div", { className: HighlightOverlay_HighlightedNode_module.label }, label)));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightOverlay.module.scss
var HighlightOverlay_module = __webpack_require__(18279);
;// ./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightOverlay.module.scss

      
      
      
      
      
      
      
      
      

var HighlightOverlay_module_options = {};

HighlightOverlay_module_options.styleTagTransform = (styleTagTransform_default());
HighlightOverlay_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      HighlightOverlay_module_options.insert = insertBySelector_default().bind(null, "head");
    
HighlightOverlay_module_options.domAPI = (styleDomAPI_default());
HighlightOverlay_module_options.insertStyleElement = (insertStyleElement_default());

var HighlightOverlay_module_update = injectStylesIntoStyleTag_default()(HighlightOverlay_module/* default */.A, HighlightOverlay_module_options);




       /* harmony default export */ const HighlightOverlay_HighlightOverlay_module = (HighlightOverlay_module/* default */.A && HighlightOverlay_module/* default */.A.locals ? HighlightOverlay_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/CanvasOverlays/HighlightOverlay/HighlightOverlay.tsx
/**
 * HighlightOverlay - Main overlay component for canvas highlights
 *
 * Renders persistent, multi-channel highlights over the node graph canvas.
 * Uses the canvas overlay pattern with CSS transform for coordinate mapping.
 *
 * Features:
 * - Subscribes to HighlightManager events via useEventListener
 * - Renders node and connection highlights
 * - Supports multiple visual styles (glow, pulse, solid)
 * - Handles viewport transformations automatically via CSS
 */






/**
 * HighlightOverlay component
 *
 * @example
 * ```tsx
 * <HighlightOverlay
 *   viewport={{ x: 0, y: 0, zoom: 1.0 }}
 *   getNodeBounds={(id) => nodeEditor.getNodeBounds(id)}
 * />
 * ```
 */
function HighlightOverlay({ viewport, getNodeBounds }) {
    const [highlights, setHighlights] = (0,external_react_.useState)([]);
    // Subscribe to HighlightManager events using Phase 0 pattern
    (0,useEventListener/* useEventListener */.M)(HighlightManager/* HighlightManager */.Ym.instance, 'highlightAdded', () => {
        setHighlights(HighlightManager/* HighlightManager */.Ym.instance.getHighlights());
    });
    (0,useEventListener/* useEventListener */.M)(HighlightManager/* HighlightManager */.Ym.instance, 'highlightRemoved', () => {
        setHighlights(HighlightManager/* HighlightManager */.Ym.instance.getHighlights());
    });
    (0,useEventListener/* useEventListener */.M)(HighlightManager/* HighlightManager */.Ym.instance, 'highlightUpdated', () => {
        setHighlights(HighlightManager/* HighlightManager */.Ym.instance.getHighlights());
    });
    (0,useEventListener/* useEventListener */.M)(HighlightManager/* HighlightManager */.Ym.instance, 'channelCleared', () => {
        setHighlights(HighlightManager/* HighlightManager */.Ym.instance.getHighlights());
    });
    (0,useEventListener/* useEventListener */.M)(HighlightManager/* HighlightManager */.Ym.instance, 'allCleared', () => {
        setHighlights([]);
    });
    // Initial load
    (0,external_react_.useEffect)(() => {
        setHighlights(HighlightManager/* HighlightManager */.Ym.instance.getHighlights());
    }, []);
    // Apply viewport transformation to the container
    // CRITICAL: Transform order must be scale THEN translate to match canvas rendering
    // Canvas does: ctx.scale() then ctx.translate() then draws at node.global coords
    // CSS transforms apply right-to-left, so "scale() translate()" = scale(translate(point))
    // This computes: scale * (pan + nodePos) which matches the canvas
    const containerStyle = {
        transform: `scale(${viewport.zoom}) translate(${viewport.x}px, ${viewport.y}px)`,
        transformOrigin: '0 0'
    };
    return (external_react_default().createElement("div", { className: HighlightOverlay_HighlightOverlay_module.highlightOverlay },
        external_react_default().createElement("div", { className: HighlightOverlay_HighlightOverlay_module.highlightContainer, style: containerStyle }, highlights.map((highlight) => (external_react_default().createElement((external_react_default()).Fragment, { key: highlight.id },
            highlight.nodeIds.map((nodeId) => {
                const bounds = getNodeBounds === null || getNodeBounds === void 0 ? void 0 : getNodeBounds(nodeId);
                if (!bounds)
                    return null;
                return (external_react_default().createElement(HighlightedNode, { key: `${highlight.id}-${nodeId}`, nodeId: nodeId, bounds: bounds, color: highlight.options.color || '#FFFFFF', style: highlight.options.style || 'solid', label: highlight.options.label }));
            }),
            highlight.connections.map((connection, index) => {
                const fromBounds = getNodeBounds === null || getNodeBounds === void 0 ? void 0 : getNodeBounds(connection.fromNodeId);
                const toBounds = getNodeBounds === null || getNodeBounds === void 0 ? void 0 : getNodeBounds(connection.toNodeId);
                if (!fromBounds || !toBounds)
                    return null;
                return (external_react_default().createElement(HighlightedConnection, { key: `${highlight.id}-conn-${index}`, connection: connection, fromBounds: fromBounds, toBounds: toBounds, color: highlight.options.color || '#FFFFFF', style: highlight.options.style || 'solid' }));
            })))))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/CanvasOverlays/HighlightOverlay/BoundaryIndicator.module.scss
var BoundaryIndicator_module = __webpack_require__(6068);
;// ./src/editor/src/views/CanvasOverlays/HighlightOverlay/BoundaryIndicator.module.scss

      
      
      
      
      
      
      
      
      

var BoundaryIndicator_module_options = {};

BoundaryIndicator_module_options.styleTagTransform = (styleTagTransform_default());
BoundaryIndicator_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      BoundaryIndicator_module_options.insert = insertBySelector_default().bind(null, "head");
    
BoundaryIndicator_module_options.domAPI = (styleDomAPI_default());
BoundaryIndicator_module_options.insertStyleElement = (insertStyleElement_default());

var BoundaryIndicator_module_update = injectStylesIntoStyleTag_default()(BoundaryIndicator_module/* default */.A, BoundaryIndicator_module_options);




       /* harmony default export */ const HighlightOverlay_BoundaryIndicator_module = (BoundaryIndicator_module/* default */.A && BoundaryIndicator_module/* default */.A.locals ? BoundaryIndicator_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/CanvasOverlays/HighlightOverlay/BoundaryIndicator.tsx
/**
 * BoundaryIndicator - Visual indicator for cross-component path boundaries
 *
 * Displays a floating badge when a highlighted path continues into a parent or child component.
 * Shows the component name and provides a navigation button to jump to that component.
 *
 * @example
 * ```tsx
 * <BoundaryIndicator
 *   boundary={{
 *     fromComponent: 'App',
 *     toComponent: 'UserCard',
 *     direction: 'down',
 *     edgeNodeId: 'node-123'
 *   }}
 *   position={{ x: 100, y: 200 }}
 *   onNavigate={(componentName) => editor.switchToComponent(componentName)}
 * />
 * ```
 */


/**
 * BoundaryIndicator component
 *
 * Renders a floating badge indicating that a highlighted path continues into another component.
 * Includes a navigation button to jump to that component.
 */
function BoundaryIndicator({ boundary, position, onNavigate }) {
    const isGoingUp = boundary.direction === 'up';
    const targetComponent = boundary.toComponent;
    const handleNavigate = (e) => {
        e.stopPropagation();
        onNavigate(targetComponent);
    };
    // Position the indicator
    const style = {
        left: `${position.x}px`,
        top: `${position.y}px`
    };
    return (React.createElement("div", { className: `${css.boundaryIndicator} ${isGoingUp ? css.directionUp : css.directionDown}`, style: style, "data-boundary-id": `${boundary.fromComponent}-${boundary.toComponent}` },
        React.createElement("div", { className: css.content },
            React.createElement("div", { className: css.icon }, isGoingUp ? '↑' : '↓'),
            React.createElement("div", { className: css.label },
                React.createElement("div", { className: css.text }, "Path continues in"),
                React.createElement("div", { className: css.componentName }, targetComponent)),
            React.createElement("button", { className: css.navigateButton, onClick: handleNavigate, title: `Navigate to ${targetComponent}`, type: "button" }, "\u2192"))));
}

;// ./src/editor/src/views/CanvasOverlays/HighlightOverlay/index.ts
/**
 * HighlightOverlay exports
 *
 * Canvas highlight overlay components for rendering persistent highlights
 * over nodes and connections.
 */





;// external "blockly"
const external_blockly_namespaceObject = require("blockly");
;// ./src/editor/src/views/BlocklyEditor/NoodlBlocks.ts
/**
 * Noodl Custom Blocks for Blockly
 *
 * Defines custom blocks for Noodl-specific functionality:
 * - Inputs/Outputs (node I/O)
 * - Variables (Noodl.Variables)
 * - Objects (Noodl.Objects)
 * - Arrays (Noodl.Arrays)
 * - Events/Signals
 *
 * @module BlocklyEditor
 */

/**
 * Initialize all Noodl custom blocks
 */
function initNoodlBlocks() {
    console.log('🔧 [Blockly] Initializing Noodl custom blocks');
    // Input/Output blocks
    defineInputOutputBlocks();
    // Variable blocks
    defineVariableBlocks();
    // Object blocks (basic - will expand later)
    defineObjectBlocks();
    // Array blocks (basic - will expand later)
    defineArrayBlocks();
    console.log('✅ [Blockly] Noodl blocks initialized');
}
/**
 * Input/Output Blocks
 */
function defineInputOutputBlocks() {
    // Define Input block - declares an input port
    external_blockly_namespaceObject.Blocks['noodl_define_input'] = {
        init: function () {
            this.appendDummyInput()
                .appendField('📥 Define input')
                .appendField(new external_blockly_namespaceObject.FieldTextInput('myInput'), 'NAME')
                .appendField('type')
                .appendField(new external_blockly_namespaceObject.FieldDropdown([
                ['any', '*'],
                ['string', 'string'],
                ['number', 'number'],
                ['boolean', 'boolean'],
                ['object', 'object'],
                ['array', 'array']
            ]), 'TYPE');
            this.setPreviousStatement(true, null);
            this.setNextStatement(true, null);
            this.setColour(230);
            this.setTooltip('Defines an input port that appears on the node');
            this.setHelpUrl('');
        }
    };
    // Get Input block - gets value from an input
    external_blockly_namespaceObject.Blocks['noodl_get_input'] = {
        init: function () {
            this.appendDummyInput().appendField('📥 get input').appendField(new external_blockly_namespaceObject.FieldTextInput('value'), 'NAME');
            this.setOutput(true, null);
            this.setColour(230);
            this.setTooltip('Gets the value from an input port');
            this.setHelpUrl('');
        }
    };
    // Define Output block - declares an output port
    external_blockly_namespaceObject.Blocks['noodl_define_output'] = {
        init: function () {
            this.appendDummyInput()
                .appendField('📤 Define output')
                .appendField(new external_blockly_namespaceObject.FieldTextInput('result'), 'NAME')
                .appendField('type')
                .appendField(new external_blockly_namespaceObject.FieldDropdown([
                ['any', '*'],
                ['string', 'string'],
                ['number', 'number'],
                ['boolean', 'boolean'],
                ['object', 'object'],
                ['array', 'array']
            ]), 'TYPE');
            this.setPreviousStatement(true, null);
            this.setNextStatement(true, null);
            this.setColour(230);
            this.setTooltip('Defines an output port that appears on the node');
            this.setHelpUrl('');
        }
    };
    // Set Output block - sets value on an output
    external_blockly_namespaceObject.Blocks['noodl_set_output'] = {
        init: function () {
            this.appendValueInput('VALUE')
                .setCheck(null)
                .appendField('📤 set output')
                .appendField(new external_blockly_namespaceObject.FieldTextInput('result'), 'NAME')
                .appendField('to');
            this.setPreviousStatement(true, null);
            this.setNextStatement(true, null);
            this.setColour(230);
            this.setTooltip('Sets the value of an output port');
            this.setHelpUrl('');
        }
    };
    // Define Signal Input block
    external_blockly_namespaceObject.Blocks['noodl_define_signal_input'] = {
        init: function () {
            this.appendDummyInput()
                .appendField('⚡ Define signal input')
                .appendField(new external_blockly_namespaceObject.FieldTextInput('trigger'), 'NAME');
            this.setPreviousStatement(true, null);
            this.setNextStatement(true, null);
            this.setColour(180);
            this.setTooltip('Defines a signal input that can trigger logic');
            this.setHelpUrl('');
        }
    };
    // Define Signal Output block
    external_blockly_namespaceObject.Blocks['noodl_define_signal_output'] = {
        init: function () {
            this.appendDummyInput()
                .appendField('⚡ Define signal output')
                .appendField(new external_blockly_namespaceObject.FieldTextInput('done'), 'NAME');
            this.setPreviousStatement(true, null);
            this.setNextStatement(true, null);
            this.setColour(180);
            this.setTooltip('Defines a signal output that can trigger other nodes');
            this.setHelpUrl('');
        }
    };
    // Send Signal block
    external_blockly_namespaceObject.Blocks['noodl_send_signal'] = {
        init: function () {
            this.appendDummyInput().appendField('⚡ send signal').appendField(new external_blockly_namespaceObject.FieldTextInput('done'), 'NAME');
            this.setPreviousStatement(true, null);
            this.setNextStatement(true, null);
            this.setColour(180);
            this.setTooltip('Sends a signal to connected nodes');
            this.setHelpUrl('');
        }
    };
}
/**
 * Variable Blocks
 */
function defineVariableBlocks() {
    // Get Variable block
    external_blockly_namespaceObject.Blocks['noodl_get_variable'] = {
        init: function () {
            this.appendDummyInput()
                .appendField('📖 get variable')
                .appendField(new external_blockly_namespaceObject.FieldTextInput('myVariable'), 'NAME');
            this.setOutput(true, null);
            this.setColour(330);
            this.setTooltip('Gets the value of a global Noodl variable');
            this.setHelpUrl('');
        }
    };
    // Set Variable block
    external_blockly_namespaceObject.Blocks['noodl_set_variable'] = {
        init: function () {
            this.appendValueInput('VALUE')
                .setCheck(null)
                .appendField('✏️ set variable')
                .appendField(new external_blockly_namespaceObject.FieldTextInput('myVariable'), 'NAME')
                .appendField('to');
            this.setPreviousStatement(true, null);
            this.setNextStatement(true, null);
            this.setColour(330);
            this.setTooltip('Sets the value of a global Noodl variable');
            this.setHelpUrl('');
        }
    };
}
/**
 * Object Blocks (basic set - will expand in Phase E)
 */
function defineObjectBlocks() {
    // Get Object block
    external_blockly_namespaceObject.Blocks['noodl_get_object'] = {
        init: function () {
            this.appendValueInput('ID').setCheck('String').appendField('📦 get object');
            this.setOutput(true, 'Object');
            this.setColour(20);
            this.setTooltip('Gets a Noodl Object by its ID');
            this.setHelpUrl('');
        }
    };
    // Get Object Property block
    external_blockly_namespaceObject.Blocks['noodl_get_object_property'] = {
        init: function () {
            this.appendValueInput('OBJECT')
                .setCheck(null)
                .appendField('📖 get')
                .appendField(new external_blockly_namespaceObject.FieldTextInput('name'), 'PROPERTY')
                .appendField('from object');
            this.setOutput(true, null);
            this.setColour(20);
            this.setTooltip('Gets a property value from an object');
            this.setHelpUrl('');
        }
    };
    // Set Object Property block
    external_blockly_namespaceObject.Blocks['noodl_set_object_property'] = {
        init: function () {
            this.appendValueInput('OBJECT')
                .setCheck(null)
                .appendField('✏️ set')
                .appendField(new external_blockly_namespaceObject.FieldTextInput('name'), 'PROPERTY')
                .appendField('on object');
            this.appendValueInput('VALUE').setCheck(null).appendField('to');
            this.setInputsInline(false);
            this.setPreviousStatement(true, null);
            this.setNextStatement(true, null);
            this.setColour(20);
            this.setTooltip('Sets a property value on an object');
            this.setHelpUrl('');
        }
    };
}
/**
 * Array Blocks (basic set - will expand in Phase E)
 */
function defineArrayBlocks() {
    // Get Array block
    external_blockly_namespaceObject.Blocks['noodl_get_array'] = {
        init: function () {
            this.appendDummyInput().appendField('📋 get array').appendField(new external_blockly_namespaceObject.FieldTextInput('myArray'), 'NAME');
            this.setOutput(true, 'Array');
            this.setColour(260);
            this.setTooltip('Gets a Noodl Array by name');
            this.setHelpUrl('');
        }
    };
    // Array Length block
    external_blockly_namespaceObject.Blocks['noodl_array_length'] = {
        init: function () {
            this.appendValueInput('ARRAY').setCheck('Array').appendField('🔢 length of array');
            this.setOutput(true, 'Number');
            this.setColour(260);
            this.setTooltip('Gets the number of items in an array');
            this.setHelpUrl('');
        }
    };
    // Array Add block
    external_blockly_namespaceObject.Blocks['noodl_array_add'] = {
        init: function () {
            this.appendValueInput('ITEM').setCheck(null).appendField('➕ add');
            this.appendValueInput('ARRAY').setCheck('Array').appendField('to array');
            this.setInputsInline(true);
            this.setPreviousStatement(true, null);
            this.setNextStatement(true, null);
            this.setColour(260);
            this.setTooltip('Adds an item to the end of an array');
            this.setHelpUrl('');
        }
    };
}

// EXTERNAL MODULE: ../../node_modules/@blockly/theme-dark/dist/index.js
var dist = __webpack_require__(91102);
var dist_default = /*#__PURE__*/__webpack_require__.n(dist);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/BlocklyEditor/BlocklyWorkspace.module.scss
var BlocklyWorkspace_module = __webpack_require__(39015);
;// ./src/editor/src/views/BlocklyEditor/BlocklyWorkspace.module.scss

      
      
      
      
      
      
      
      
      

var BlocklyWorkspace_module_options = {};

BlocklyWorkspace_module_options.styleTagTransform = (styleTagTransform_default());
BlocklyWorkspace_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      BlocklyWorkspace_module_options.insert = insertBySelector_default().bind(null, "head");
    
BlocklyWorkspace_module_options.domAPI = (styleDomAPI_default());
BlocklyWorkspace_module_options.insertStyleElement = (insertStyleElement_default());

var BlocklyWorkspace_module_update = injectStylesIntoStyleTag_default()(BlocklyWorkspace_module/* default */.A, BlocklyWorkspace_module_options);




       /* harmony default export */ const BlocklyEditor_BlocklyWorkspace_module = (BlocklyWorkspace_module/* default */.A && BlocklyWorkspace_module/* default */.A.locals ? BlocklyWorkspace_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/BlocklyEditor/BlocklyWorkspace.tsx
/**
 * BlocklyWorkspace Component
 *
 * React wrapper for Google Blockly visual programming workspace.
 * Provides integration with Noodl's node system for visual logic building.
 *
 * @module BlocklyEditor
 */






/**
 * BlocklyWorkspace - React component for Blockly integration
 *
 * Handles:
 * - Blockly workspace initialization
 * - Workspace persistence (save/load)
 * - Change detection and callbacks
 * - Cleanup on unmount
 */
function BlocklyWorkspace({ initialWorkspace, toolbox, onChange, readOnly = false, theme }) {
    const blocklyDiv = (0,external_react_.useRef)(null);
    const workspaceRef = (0,external_react_.useRef)(null);
    const changeTimeoutRef = (0,external_react_.useRef)(null);
    // Initialize Blockly workspace
    (0,external_react_.useEffect)(() => {
        if (!blocklyDiv.current)
            return;
        // Initialize custom Noodl blocks and generators before creating workspace
        initBlocklyIntegration();
        console.log('🔧 [Blockly] Initializing workspace');
        // Inject Blockly with dark theme
        const workspace = external_blockly_namespaceObject.inject(blocklyDiv.current, {
            toolbox: toolbox || getDefaultToolbox(),
            theme: theme || (dist_default()),
            readOnly: readOnly,
            trashcan: true,
            zoom: {
                controls: true,
                wheel: true,
                startScale: 1.0,
                maxScale: 3,
                minScale: 0.3,
                scaleSpeed: 1.2
            },
            grid: {
                spacing: 20,
                length: 3,
                colour: '#ccc',
                snap: true
            }
        });
        workspaceRef.current = workspace;
        // Load initial workspace if provided
        if (initialWorkspace) {
            try {
                const json = JSON.parse(initialWorkspace);
                external_blockly_namespaceObject.serialization.workspaces.load(json, workspace);
                console.log('✅ [Blockly] Loaded initial workspace');
            }
            catch (error) {
                console.error('❌ [Blockly] Failed to load initial workspace:', error);
            }
        }
        // Listen for changes - filter to only respond to finished workspace changes,
        // not UI events like dragging or moving blocks
        const changeListener = (event) => {
            if (!onChange || !workspace)
                return;
            // Ignore UI events that don't change the workspace structure
            // These fire constantly during drags and can cause state corruption
            if (event.type === external_blockly_namespaceObject.Events.BLOCK_DRAG)
                return;
            if (event.type === external_blockly_namespaceObject.Events.BLOCK_MOVE && !event.isUiEvent)
                return; // Allow programmatic moves
            if (event.type === external_blockly_namespaceObject.Events.SELECTED)
                return;
            if (event.type === external_blockly_namespaceObject.Events.CLICK)
                return;
            if (event.type === external_blockly_namespaceObject.Events.VIEWPORT_CHANGE)
                return;
            if (event.type === external_blockly_namespaceObject.Events.TOOLBOX_ITEM_SELECT)
                return;
            if (event.type === external_blockly_namespaceObject.Events.THEME_CHANGE)
                return;
            if (event.type === external_blockly_namespaceObject.Events.TRASHCAN_OPEN)
                return;
            // For UI events that DO change the workspace, debounce them
            const isUiEvent = event.isUiEvent;
            if (isUiEvent) {
                // Clear any pending timeout for UI events
                if (changeTimeoutRef.current) {
                    clearTimeout(changeTimeoutRef.current);
                }
                // Debounce UI-initiated changes (user editing)
                changeTimeoutRef.current = setTimeout(() => {
                    const json = JSON.stringify(external_blockly_namespaceObject.serialization.workspaces.save(workspace));
                    const code = javascriptGenerator.workspaceToCode(workspace);
                    console.log('[Blockly] Generated code:', code);
                    onChange(workspace, json, code);
                }, 300);
            }
            else {
                // Programmatic changes fire immediately (e.g., undo/redo, loading)
                const json = JSON.stringify(external_blockly_namespaceObject.serialization.workspaces.save(workspace));
                const code = javascriptGenerator.workspaceToCode(workspace);
                console.log('[Blockly] Generated code:', code);
                onChange(workspace, json, code);
            }
        };
        workspace.addChangeListener(changeListener);
        // Cleanup
        return () => {
            console.log('🧹 [Blockly] Disposing workspace');
            // Clear any pending debounced calls
            if (changeTimeoutRef.current) {
                clearTimeout(changeTimeoutRef.current);
            }
            workspace.removeChangeListener(changeListener);
            workspace.dispose();
            workspaceRef.current = null;
        };
    }, [toolbox, theme, readOnly]);
    // NOTE: Do NOT reload workspace on initialWorkspace changes!
    // The initialWorkspace prop changes on every save, which would cause corruption.
    // Workspace is loaded ONCE on mount above, and changes are saved via onChange callback.
    return (external_react_default().createElement("div", { className: BlocklyEditor_BlocklyWorkspace_module.Root },
        external_react_default().createElement("div", { ref: blocklyDiv, className: BlocklyEditor_BlocklyWorkspace_module.BlocklyContainer })));
}
/**
 * Default toolbox with Noodl-specific blocks
 */
function getDefaultToolbox() {
    return {
        kind: 'categoryToolbox',
        contents: [
            // Noodl I/O Category
            {
                kind: 'category',
                name: 'Noodl Inputs/Outputs',
                colour: '230',
                contents: [
                    { kind: 'block', type: 'noodl_define_input' },
                    { kind: 'block', type: 'noodl_get_input' },
                    { kind: 'block', type: 'noodl_define_output' },
                    { kind: 'block', type: 'noodl_set_output' }
                ]
            },
            // Noodl Signals Category
            {
                kind: 'category',
                name: 'Noodl Signals',
                colour: '180',
                contents: [
                    { kind: 'block', type: 'noodl_define_signal_input' },
                    { kind: 'block', type: 'noodl_define_signal_output' },
                    { kind: 'block', type: 'noodl_send_signal' }
                ]
            },
            // Noodl Variables Category
            {
                kind: 'category',
                name: 'Noodl Variables',
                colour: '330',
                contents: [
                    { kind: 'block', type: 'noodl_get_variable' },
                    { kind: 'block', type: 'noodl_set_variable' }
                ]
            },
            // Noodl Objects Category
            {
                kind: 'category',
                name: 'Noodl Objects',
                colour: '20',
                contents: [
                    { kind: 'block', type: 'noodl_get_object' },
                    { kind: 'block', type: 'noodl_get_object_property' },
                    { kind: 'block', type: 'noodl_set_object_property' }
                ]
            },
            // Noodl Arrays Category
            {
                kind: 'category',
                name: 'Noodl Arrays',
                colour: '260',
                contents: [
                    { kind: 'block', type: 'noodl_get_array' },
                    { kind: 'block', type: 'noodl_array_length' },
                    { kind: 'block', type: 'noodl_array_add' }
                ]
            },
            // Standard Logic blocks (useful for conditionals)
            {
                kind: 'category',
                name: 'Logic',
                colour: '210',
                contents: [
                    { kind: 'block', type: 'controls_if' },
                    { kind: 'block', type: 'logic_compare' },
                    { kind: 'block', type: 'logic_operation' },
                    { kind: 'block', type: 'logic_negate' },
                    { kind: 'block', type: 'logic_boolean' }
                ]
            },
            // Standard Math blocks
            {
                kind: 'category',
                name: 'Math',
                colour: '230',
                contents: [
                    { kind: 'block', type: 'math_number' },
                    { kind: 'block', type: 'math_arithmetic' },
                    { kind: 'block', type: 'math_single' }
                ]
            },
            // Standard Text blocks
            {
                kind: 'category',
                name: 'Text',
                colour: '160',
                contents: [
                    { kind: 'block', type: 'text' },
                    { kind: 'block', type: 'text_join' },
                    { kind: 'block', type: 'text_length' }
                ]
            }
        ]
    };
}

;// ./src/editor/src/views/BlocklyEditor/index.ts
/**
 * BlocklyEditor Module
 *
 * Entry point for Blockly integration in Noodl.
 * Exports components, blocks, and generators for visual logic building.
 *
 * @module BlocklyEditor
 */


// Initialize globals (IODetector, code generation)

// Main component

// Block definitions and generators


// Track initialization to prevent double-registration
let blocklyInitialized = false;
/**
 * Initialize all Noodl Blockly extensions
 * Call this once at app startup before using Blockly components
 * Safe to call multiple times - will only initialize once
 */
function initBlocklyIntegration() {
    if (blocklyInitialized) {
        console.log('⏭️  [Blockly] Already initialized, skipping');
        return;
    }
    console.log('🔧 [Blockly] Initializing Noodl Blockly integration');
    // Initialize custom blocks
    initNoodlBlocks();
    // Initialize code generators
    initNoodlGenerators();
    // Note: BlocklyEditorGlobals auto-initializes via side-effect import above
    blocklyInitialized = true;
    console.log('✅ [Blockly] Integration initialized');
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/CanvasTabs/CanvasTabs.module.scss
var CanvasTabs_module = __webpack_require__(49741);
;// ./src/editor/src/views/CanvasTabs/CanvasTabs.module.scss

      
      
      
      
      
      
      
      
      

var CanvasTabs_module_options = {};

CanvasTabs_module_options.styleTagTransform = (styleTagTransform_default());
CanvasTabs_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      CanvasTabs_module_options.insert = insertBySelector_default().bind(null, "head");
    
CanvasTabs_module_options.domAPI = (styleDomAPI_default());
CanvasTabs_module_options.insertStyleElement = (insertStyleElement_default());

var CanvasTabs_module_update = injectStylesIntoStyleTag_default()(CanvasTabs_module/* default */.A, CanvasTabs_module_options);




       /* harmony default export */ const CanvasTabs_CanvasTabs_module = (CanvasTabs_module/* default */.A && CanvasTabs_module/* default */.A.locals ? CanvasTabs_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/CanvasTabs/CanvasTabs.tsx




/**
 * Canvas Tabs Component
 *
 * Manages tabs for Logic Builder (Blockly) editors.
 * The canvas itself is NOT managed here - it's always visible in the background
 * unless a Logic Builder tab is open.
 */
function CanvasTabs({ onWorkspaceChange }) {
    const { tabs, activeTabId, switchTab, closeTab, updateTab } = useCanvasTabs();
    const activeTab = tabs.find((t) => t.id === activeTabId);
    /**
     * Handle workspace changes from Blockly editor
     */
    const handleWorkspaceChange = (_workspaceSvg, json, code) => {
        if (!activeTab) {
            return;
        }
        // Update tab's workspace with JSON
        updateTab(activeTab.id, { workspace: json });
        // Notify parent (pass both workspace JSON and generated code)
        if (onWorkspaceChange && activeTab.nodeId) {
            onWorkspaceChange(activeTab.nodeId, json, code);
        }
    };
    /**
     * Handle tab click
     */
    const handleTabClick = (tabId) => {
        switchTab(tabId);
    };
    /**
     * Handle tab close
     */
    const handleTabClose = (e, tabId) => {
        e.stopPropagation(); // Don't trigger tab switch
        closeTab(tabId);
    };
    // Don't render anything if no tabs are open
    if (tabs.length === 0) {
        return null;
    }
    return (external_react_default().createElement("div", { className: CanvasTabs_CanvasTabs_module['CanvasTabs'] },
        external_react_default().createElement("div", { className: CanvasTabs_CanvasTabs_module['TabBar'] }, tabs.map((tab) => {
            const isActive = tab.id === activeTabId;
            return (external_react_default().createElement("div", { key: tab.id, className: `${CanvasTabs_CanvasTabs_module['Tab']} ${isActive ? CanvasTabs_CanvasTabs_module['isActive'] : ''}`, onClick: () => handleTabClick(tab.id), role: "tab", "aria-selected": isActive, tabIndex: 0 },
                external_react_default().createElement("span", { className: CanvasTabs_CanvasTabs_module['TabLabel'] },
                    "Logic Builder: ",
                    tab.nodeName || 'Unnamed'),
                external_react_default().createElement("button", { className: CanvasTabs_CanvasTabs_module['TabCloseButton'], onClick: (e) => handleTabClose(e, tab.id), "aria-label": "Close tab", title: "Close tab" }, "\u00D7")));
        })),
        external_react_default().createElement("div", { className: CanvasTabs_CanvasTabs_module['TabContent'] }, activeTab && (external_react_default().createElement("div", { className: CanvasTabs_CanvasTabs_module['BlocklyContainer'] },
            external_react_default().createElement(BlocklyWorkspace, { initialWorkspace: activeTab.workspace || undefined, onChange: handleWorkspaceChange }))))));
}

;// ./src/editor/src/views/CanvasTabs/index.ts
/**
 * CanvasTabs Module
 *
 * Exports canvas tab system components
 */


// EXTERNAL MODULE: ./src/editor/src/views/CommentLayer/CommentLayerView.tsx + 4 modules
var CommentLayerView = __webpack_require__(23776);
;// ./src/editor/src/views/commentlayer.ts






function arrayShallowEqual(a, b) {
    return a.length === b.length && a.every((value, index) => value === b[index]);
}
class CommentLayer {
    constructor(nodegraphEditor) {
        this.nodegraphEditor = nodegraphEditor;
        this.props = {
            readOnly: undefined,
            scale: undefined,
            comments: [],
            selectedIds: [],
            showTextArea: false,
            activeCommentId: null,
            isContextOpen: false,
            setIsContextOpen: (state) => {
                this.props.isContextOpen = state;
                this._renderReact();
            },
            updateComment: (commentId, updatedData, args) => {
                const index = this.props.comments.findIndex((c) => c.id === commentId);
                const currentComment = this.props.comments[index];
                const updatedComment = { ...currentComment, ...updatedData };
                this.props.comments[index] = updatedComment;
                this._renderReact();
                if (args && args.commit) {
                    this.model.setComment(commentId, updatedComment, { undo: true, label: args.label || 'change comment' });
                }
            },
            removeComment: (commentId) => {
                this.model.removeComment(commentId, { undo: true, label: 'delete comment' });
            },
            onResizeStart: () => {
                this.nodegraphEditor.setMouseEventsEnabled(false);
                this.nodegraphEditor.clearSelection();
                this.nodegraphEditor.relayout();
                this.nodegraphEditor.repaint();
            },
            onResizeStop: () => {
                this.nodegraphEditor.setMouseEventsEnabled(true);
            },
            setActiveState: (id, active) => {
                if (this.props.activeCommentId === id && active === false) {
                    //current selection is removed
                    this.props.activeCommentId = null;
                    this._renderReact();
                }
                else if (this.props.activeCommentId !== id && active) {
                    //new selection
                    this._setActiveComment(id);
                }
            },
            toggleSelection: (id) => {
                const index = this.props.selectedIds.indexOf(id);
                if (index === -1) {
                    this.props.selectedIds.push(id);
                }
                else {
                    this.props.selectedIds.splice(index, 1);
                }
                this._renderReact();
            },
            setShowTextArea: (show) => {
                if (this.props.showTextArea === show) {
                    return;
                }
                this.props.showTextArea = show;
                this._renderReact();
            }
        };
    }
    setComponentModel(model) {
        if (this.model) {
            this.model.off(this);
        }
        if (!model) {
            this.props.comments = [];
            this.clearSelection();
            return;
        }
        const commentModel = model.graph.commentsModel;
        this.model = commentModel;
        this.props.comments = commentModel.getComments();
        commentModel.on('commentsChanged', () => {
            this.props.comments = commentModel.getComments();
            this._renderReact();
        }, this);
        this._renderReact();
    }
    _renderReact() {
        if (!this.backgroundDiv) {
            return;
        }
        // Create roots only once, reuse for subsequent renders
        if (!this.backgroundRoot) {
            this.backgroundRoot = (0,client.createRoot)(this.backgroundDiv);
        }
        this.backgroundRoot.render(external_react_default().createElement(CommentLayerView/* Background */.VS, this.props));
        if (!this.foregroundRoot) {
            this.foregroundRoot = (0,client.createRoot)(this.foregroundDiv);
        }
        this.foregroundRoot.render(external_react_default().createElement(CommentLayerView/* Foreground */._6, this.props));
    }
    renderTo(backgroundDiv, foregroundDiv) {
        // Clean up existing roots if we're switching to new divs
        if (this.backgroundDiv) {
            if (this.backgroundRoot) {
                this.backgroundRoot.unmount();
                this.backgroundRoot = null;
            }
            if (this.foregroundRoot) {
                this.foregroundRoot.unmount();
                this.foregroundRoot = null;
            }
        }
        this.backgroundDiv = backgroundDiv;
        this.foregroundDiv = foregroundDiv;
        this.setupMouseEventHandling(foregroundDiv);
        //ugly workaround to make it possible to render the nodegraph in an effect a React component
        //without warnings. React doesn't like if effects trigger react components to render directly.
        setTimeout(() => {
            this._renderReact();
        }, 1);
    }
    hasSelection() {
        return !!this.props.activeCommentId || this.props.selectedIds.length;
    }
    //Set pan and scale position. These transforms must be set when the comments mount since react-rnd checks the bounding box of the parent for the initial poisition
    setPanAndScale(panAndScale) {
        if (!this.backgroundDiv) {
            return;
        }
        const transform = `scale(${panAndScale.scale}) translate(${panAndScale.x}px, ${panAndScale.y}px)`;
        if (this.backgroundDiv.style.transform === transform)
            return;
        this.backgroundDiv.style.transform = transform;
        this.foregroundDiv.style.transform = transform;
        //let the comments know that scaling has changed so resizing and moving them works
        if (this.props.scale !== panAndScale.scale) {
            this.props.scale = panAndScale.scale;
            this._renderReact();
        }
    }
    setSelectedCommentIds(ids) {
        this.props.activeCommentId = null;
        this.props.selectedIds = ids;
        this.props.showTextArea = false;
        this._renderReact();
    }
    getSelectedComments() {
        return this.props.comments.filter((c) => this.props.selectedIds.includes(c.id));
    }
    deleteSelection(args) {
        const selectedComments = this.getSelectedComments();
        for (const comment of selectedComments) {
            this.model.removeComment(comment.id, args);
        }
        this.clearSelection();
    }
    clearMultiselection() {
        //clear all selections, except the active one (if any)
        this.props.selectedIds = this.props.selectedIds.filter((id) => id !== this.activeCommentId);
        this._renderReact();
    }
    clearSelection() {
        this.props.showTextArea = false;
        if (this.props.selectedIds.length) {
            this.props.activeCommentId = null;
            this.props.selectedIds = [];
            this._renderReact();
        }
    }
    //sets a comment to "active" (white outline)
    _setActiveComment(commentId) {
        if (this.props.activeCommentId === commentId) {
            return;
        }
        this.props.selectedIds = [commentId];
        this.props.activeCommentId = commentId;
        this.props.showTextArea = false; //new selection, so clear this flag
        //make sure we clear any selections in the graph
        this.nodegraphEditor.clearSelection();
        this.nodegraphEditor.relayout();
        this.nodegraphEditor.repaint();
        this._renderReact();
    }
    //select a comment to active and focuses the text area
    focusComment(commentId) {
        this._setActiveComment(commentId);
        this.props.showTextArea = true;
        this._renderReact();
    }
    setReadOnly(readOnly) {
        this.props.readOnly = readOnly;
        this._renderReact();
    }
    performMultiSelect(selectRect, mode) {
        const intersectedComments = this.props.comments.filter((c) => (0,utils.rectanglesOverlap)(c, selectRect));
        let commentIds = intersectedComments.map((c) => c.id);
        if (mode === 'union') {
            commentIds = external_underscore_default().union(this.props.selectedIds, commentIds);
        }
        else if (mode === 'reduce') {
            commentIds = external_underscore_default().difference(this.props.selectedIds, commentIds);
        }
        if (!arrayShallowEqual(this.props.selectedIds, commentIds)) {
            this.props.selectedIds = commentIds;
            this._renderReact();
        }
    }
    moveSelectedComments(dx, dy) {
        if (this.props.selectedIds.length === 0) {
            return;
        }
        for (const commentId of this.props.selectedIds) {
            const index = this.props.comments.findIndex((c) => c.id === commentId);
            const comment = this.props.comments[index];
            const updatedComment = { ...comment, x: comment.x + dx, y: comment.y + dy };
            this.props.comments[index] = updatedComment;
        }
        this._renderReact();
    }
    //save selected comments to the model. Called after a multiselect drag is complete
    commitSelectedComments(args) {
        const comments = this.getSelectedComments();
        for (const comment of comments) {
            this.model.setComment(comment.id, comment, args);
        }
    }
    dispose() {
        if (this.foregroundRoot) {
            this.foregroundRoot.unmount();
            this.foregroundRoot = null;
        }
        if (this.backgroundRoot) {
            this.backgroundRoot.unmount();
            this.backgroundRoot = null;
        }
        //hack to remove all event listeners without having to keep track of them
        if (this.foregroundDiv && this.foregroundDiv.parentNode) {
            const newForegroundDiv = this.foregroundDiv.cloneNode(true);
            this.foregroundDiv.parentNode.replaceChild(newForegroundDiv, this.foregroundDiv);
        }
        if (this.model) {
            this.model.off(this);
        }
    }
    //this is quite hacky... a comment is in front of the comments in the DOM, and will get mouse events before the canvas
    //so we need to figure out when to forward events to the canvas, and when not to (e.g. nodes are visually in front of a comment and should get priority)
    setupMouseEventHandling(foregroundDiv) {
        const events = {
            mousedown: 'down',
            mouseup: 'up',
            mousemove: 'move',
            mouseout: 'out',
            mouseover: 'over',
            click: 'click'
        };
        //node graph editor doesn't use the "click" event, and relies on up/down instead.
        //Let's assume that if the node graph consumed a down or up event, the next "click" event should be consumed as well
        let ignoreNextClick = false;
        let clickIgnoreTimeout;
        //listen for mouse events going into the comment layer
        //and route to the node graph in case it hits a node
        for (const eventName in events) {
            const type = events[eventName];
            foregroundDiv.addEventListener(eventName, (evt) => {
                if (evt.target && evt.target.closest('.comment-controls')) {
                    //we are interacting with the comment controls UI. Just let is through, and don't send events to node graph
                    return;
                }
                if (ignoreNextClick && type === 'click') {
                    ignoreNextClick = false;
                    evt.stopPropagation();
                    evt.preventDefault();
                    return;
                }
                //check if we're interacting with something in the canvas. If we aren't, then let the comment layer handle the mouse event
                //otherwise, forward the mouse even to the nodegraph
                evt.spaceKey = this.nodegraphEditor.spaceKeyDown; // This is set by the KeyboardHandler
                //nodeGraphEditor expects position argument that's relative to the top left of the canvas
                const tl = this.nodegraphEditor.topLeftCanvasPos;
                const pos = {
                    x: evt.pageX - tl[0],
                    y: evt.pageY - tl[1],
                    pageX: evt.pageX,
                    pageY: evt.pageY
                };
                const consumed = this.nodegraphEditor.mouse(type, pos, evt, { eventPropagatedFromCommentLayer: true });
                if (consumed) {
                    //stop event to propagate to a comment
                    evt.stopPropagation();
                    evt.preventDefault();
                    if (type === 'down' || type === 'up') {
                        //nodeGraphEditor consumed a up or down event, so let's ignore the next click event (which the nodeGraphEditor doesn't care about)
                        if (clickIgnoreTimeout) {
                            clearTimeout(clickIgnoreTimeout);
                        }
                        ignoreNextClick = true;
                        clickIgnoreTimeout = setTimeout(() => {
                            ignoreNextClick = false;
                        }, 1000);
                    }
                }
                else {
                    //start a multidrag select if we have selected comments, or selected nodes
                    const startMultiselectDrag = type === 'down' && (this.props.selectedIds.length > 1 || this.nodegraphEditor.selector.active);
                    if (startMultiselectDrag) {
                        const ngPos = this.nodegraphEditor.relativeCoordsToNodeGraphCords(pos);
                        //if we're starting a multi select drag, make sure that we're not starting the drag on top of a comment that's outside the current selection
                        const commentUnderCursor = this.props.comments.find((c) => (0,utils.pointInsideRectangle)(ngPos, c));
                        if (!commentUnderCursor || this.props.selectedIds.includes(commentUnderCursor.id)) {
                            this.nodegraphEditor.startDraggingNodes(this.nodegraphEditor.selector.nodes);
                            //stop event to propagate to a comment
                            evt.stopPropagation();
                            evt.preventDefault();
                        }
                    }
                }
            }, true);
        }
        //listen for mousewheel events on a comment.
        //They should zoom the canvas, except if a text area is active (then it should scroll), or ctrl/cmd is being held down
        foregroundDiv.addEventListener('wheel', (evt) => {
            if (evt.target.tagName !== 'TEXTAREA' || evt.ctrlKey || evt.metaKey) {
                //nodeGraphEditor expects position argument that's relative to the top left of the canvas
                const tl = this.nodegraphEditor.topLeftCanvasPos;
                this.nodegraphEditor.handleMouseWheelEvent(evt, { offsetX: evt.pageX - tl[0], offsetY: evt.pageY - tl[1] });
            }
        });
        //forward key events, except when a text area is active
        foregroundDiv.addEventListener('keydown', (evt) => {
            if (evt.target.tagName !== 'TEXTAREA') {
                //forward this key event to the keyboard handler
                keyboardhandler["default"].instance.executeCommandMatchingKeyEvent(evt, 'down');
            }
        });
    }
}

// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/index.ts
var Text = __webpack_require__(93834);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/EditorBanner/EditorBanner.module.scss
var EditorBanner_module = __webpack_require__(84379);
;// ./src/editor/src/views/EditorBanner/EditorBanner.module.scss

      
      
      
      
      
      
      
      
      

var EditorBanner_module_options = {};

EditorBanner_module_options.styleTagTransform = (styleTagTransform_default());
EditorBanner_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      EditorBanner_module_options.insert = insertBySelector_default().bind(null, "head");
    
EditorBanner_module_options.domAPI = (styleDomAPI_default());
EditorBanner_module_options.insertStyleElement = (insertStyleElement_default());

var EditorBanner_module_update = injectStylesIntoStyleTag_default()(EditorBanner_module/* default */.A, EditorBanner_module_options);




       /* harmony default export */ const EditorBanner_EditorBanner_module = (EditorBanner_module/* default */.A && EditorBanner_module/* default */.A.locals ? EditorBanner_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/EditorBanner/EditorBanner.tsx
/**
 * EditorBanner
 *
 * Warning banner that appears when a legacy (React 17) project is opened in read-only mode.
 * Provides clear messaging and actions for the user to migrate the project.
 *
 * @module noodl-editor/views/EditorBanner
 * @since 1.2.0
 */





// =============================================================================
// Component
// =============================================================================
function EditorBanner({ onDismiss }) {
    const [isDismissed, setIsDismissed] = (0,external_react_.useState)(false);
    const handleDismiss = () => {
        setIsDismissed(true);
        onDismiss();
    };
    if (isDismissed) {
        return null;
    }
    return (external_react_default().createElement("div", { className: EditorBanner_EditorBanner_module['EditorBanner'] },
        external_react_default().createElement("div", { className: EditorBanner_EditorBanner_module['Icon'] },
            external_react_default().createElement("svg", { width: "20", height: "20", viewBox: "0 0 20 20", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
                external_react_default().createElement("path", { d: "M10 6V11M10 14H10.01M19 10C19 14.9706 14.9706 19 10 19C5.02944 19 1 14.9706 1 10C1 5.02944 5.02944 1 10 1C14.9706 1 19 5.02944 19 10Z", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }))),
        external_react_default().createElement("div", { className: EditorBanner_EditorBanner_module['Content'] },
            external_react_default().createElement("div", { className: EditorBanner_EditorBanner_module['Title'] },
                external_react_default().createElement(Text/* Text */.EY, { textType: Text/* TextType */.M2.Default }, "Legacy Project (React 17) - Read-Only Mode")),
            external_react_default().createElement("div", { className: EditorBanner_EditorBanner_module['Description'] },
                external_react_default().createElement(Text/* Text */.EY, { textType: Text/* TextType */.M2.Secondary }, "This project uses React 17. Return to the launcher to migrate it before editing."))),
        external_react_default().createElement("div", { className: EditorBanner_EditorBanner_module['CloseButton'] },
            external_react_default().createElement(IconButton/* IconButton */.K0, { icon: Icon/* IconName */.$M.Close, onClick: handleDismiss, variant: IconButton/* IconButtonVariant */.nl.Transparent }))));
}
/* harmony default export */ const EditorBanner_EditorBanner = ((/* unused pure expression or super */ null && (EditorBanner)));

;// ./src/editor/src/views/EditorBanner/index.ts


;// ./src/editor/src/services/HighlightManager/test-highlights.ts
/**
 * Test/Demo functions for the Highlighting API
 *
 * This file provides helper functions to test the canvas highlighting system.
 * Open Electron DevTools (View → Toggle Developer Tools) and run these in the console:
 *
 * Usage from Console:
 * ```
 * // Import the test helpers
 * const { testHighlightManager } = require('./services/HighlightManager/test-highlights');
 *
 * // Run basic tests
 * testHighlightManager.testBasicHighlight();
 * testHighlightManager.testMultipleNodes();
 * testHighlightManager.testAnimatedPulse();
 * testHighlightManager.clearAll();
 * ```
 */

/**
 * Test highlighting the first visible node
 */
function testBasicHighlight() {
    console.log('🔍 Testing basic node highlight...');
    // Get the active NodeGraphEditor instance
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const editor = window.__nodeGraphEditor;
    if (!editor) {
        console.error('❌ No active NodeGraphEditor found. Open a component first.');
        return;
    }
    // Get the first node
    const firstNode = editor.roots[0];
    if (!firstNode) {
        console.error('❌ No nodes found in the current component.');
        return;
    }
    console.log(`✅ Highlighting node: ${firstNode.id}`);
    // Create a highlight
    const handle = HighlightManager/* HighlightManager */.Ym.instance.highlightNodes([firstNode.id], {
        channel: 'impact',
        color: '#00FF00',
        style: 'glow',
        label: 'Test Highlight'
    });
    console.log('✅ Highlight created! You should see a green glow around the first node.');
    console.log('💡 Clear it with: testHighlightManager.clearAll()');
    return handle;
}
/**
 * Test highlighting multiple nodes
 */
function testMultipleNodes() {
    console.log('🔍 Testing multiple node highlights...');
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const editor = window.__nodeGraphEditor;
    if (!editor) {
        console.error('❌ No active NodeGraphEditor found.');
        return;
    }
    // Get first 3 nodes
    const nodeIds = editor.roots.slice(0, 3).map((n) => n.id);
    if (nodeIds.length === 0) {
        console.error('❌ No nodes found.');
        return;
    }
    console.log(`✅ Highlighting ${nodeIds.length} nodes`);
    const handle = HighlightManager/* HighlightManager */.Ym.instance.highlightNodes(nodeIds, {
        channel: 'selection',
        color: '#FFA500',
        style: 'solid',
        label: 'Multi-Select Test'
    });
    console.log('✅ Multiple nodes highlighted in orange!');
    return handle;
}
/**
 * Test animated pulse highlight
 */
function testAnimatedPulse() {
    console.log('🔍 Testing animated pulse...');
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const editor = window.__nodeGraphEditor;
    if (!editor || !editor.roots[0]) {
        console.error('❌ No active editor or nodes found.');
        return;
    }
    const firstNode = editor.roots[0];
    console.log(`✅ Creating pulsing highlight on: ${firstNode.id}`);
    const handle = HighlightManager/* HighlightManager */.Ym.instance.highlightNodes([firstNode.id], {
        channel: 'warning',
        color: '#FF0000',
        style: 'pulse',
        label: 'Warning!'
    });
    console.log('✅ Pulsing red highlight created!');
    return handle;
}
/**
 * Test highlighting a connection (requires 2 connected nodes)
 */
function testConnection() {
    console.log('🔍 Testing connection highlight...');
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const editor = window.__nodeGraphEditor;
    if (!editor) {
        console.error('❌ No active NodeGraphEditor found.');
        return;
    }
    // Find the first connection
    const firstConnection = editor.connections[0];
    if (!firstConnection) {
        console.error('❌ No connections found. Create some connected nodes first.');
        return;
    }
    const fromNode = firstConnection.fromNode;
    const toNode = firstConnection.toNode;
    if (!fromNode || !toNode) {
        console.error('❌ Connection has invalid nodes.');
        return;
    }
    console.log(`✅ Highlighting connection: ${fromNode.id} → ${toNode.id}`);
    const handle = HighlightManager/* HighlightManager */.Ym.instance.highlightConnections([
        {
            fromNodeId: fromNode.id,
            fromPort: 'out', // Add required port fields
            toNodeId: toNode.id,
            toPort: 'in'
        }
    ], {
        channel: 'lineage',
        color: '#00FFFF',
        style: 'solid'
    });
    console.log('✅ Connection highlighted in cyan!');
    return handle;
}
/**
 * Test highlighting a path (chain of connected nodes)
 */
function testPath() {
    console.log('🔍 Testing path highlight...');
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const editor = window.__nodeGraphEditor;
    if (!editor) {
        console.error('❌ No active NodeGraphEditor found.');
        return;
    }
    // Get first 3 nodes (simulating a path)
    const nodeIds = editor.roots.slice(0, 3).map((n) => n.id);
    if (nodeIds.length < 2) {
        console.error('❌ Need at least 2 nodes for a path test.');
        return;
    }
    console.log(`✅ Highlighting path through ${nodeIds.length} nodes`);
    const handle = HighlightManager/* HighlightManager */.Ym.instance.highlightPath({
        nodes: nodeIds,
        connections: [], // Empty for this test
        crossesComponents: false
    }, {
        channel: 'lineage',
        color: '#9C27B0',
        style: 'glow',
        label: 'Execution Path'
    });
    console.log('✅ Path highlighted in purple!');
    return handle;
}
/**
 * Clear all highlights
 */
function clearAll() {
    console.log('🧹 Clearing all highlights...');
    HighlightManager/* HighlightManager */.Ym.instance.clearAll();
    console.log('✅ All highlights cleared!');
}
/**
 * Clear specific channel
 */
function clearChannel(channel) {
    console.log(`🧹 Clearing channel: ${channel}`);
    HighlightManager/* HighlightManager */.Ym.instance.clearChannel(channel);
    console.log('✅ Channel cleared!');
}
/**
 * Run a full demo sequence
 */
async function runDemoSequence() {
    console.log('🎬 Running highlight demo sequence...');
    // Test 1: Basic highlight
    console.log('\n1️⃣ Basic single node highlight');
    testBasicHighlight();
    await sleep(2000);
    clearAll();
    await sleep(500);
    // Test 2: Multiple nodes
    console.log('\n2️⃣ Multiple node highlight');
    testMultipleNodes();
    await sleep(2000);
    clearAll();
    await sleep(500);
    // Test 3: Animated pulse
    console.log('\n3️⃣ Animated pulse');
    testAnimatedPulse();
    await sleep(3000);
    clearAll();
    await sleep(500);
    // Test 4: Connection (if available)
    console.log('\n4️⃣ Connection highlight');
    try {
        testConnection();
        await sleep(2000);
    }
    catch (e) {
        console.warn('⚠️ Connection test skipped (no connections available)');
    }
    clearAll();
    console.log('\n✅ Demo sequence complete!');
}
function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}
// Export all test functions
const testHighlightManager = {
    testBasicHighlight,
    testMultipleNodes,
    testAnimatedPulse,
    testConnection,
    testPath,
    clearAll,
    clearChannel,
    runDemoSequence
};
// Make available in window for console access
if (typeof window !== 'undefined') {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    window.testHighlightManager = testHighlightManager;
    console.log('✅ Highlight test utilities loaded!');
    console.log('💡 Try: window.testHighlightManager.testBasicHighlight()');
}

// EXTERNAL MODULE: ./src/editor/src/constants/KeyCode.ts
var constants_KeyCode = __webpack_require__(76976);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/ConnectionPopup/ConnectionPopup.module.scss
var ConnectionPopup_module = __webpack_require__(95219);
;// ./src/editor/src/views/ConnectionPopup/ConnectionPopup.module.scss

      
      
      
      
      
      
      
      
      

var ConnectionPopup_module_options = {};

ConnectionPopup_module_options.styleTagTransform = (styleTagTransform_default());
ConnectionPopup_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ConnectionPopup_module_options.insert = insertBySelector_default().bind(null, "head");
    
ConnectionPopup_module_options.domAPI = (styleDomAPI_default());
ConnectionPopup_module_options.insertStyleElement = (insertStyleElement_default());

var ConnectionPopup_module_update = injectStylesIntoStyleTag_default()(ConnectionPopup_module/* default */.A, ConnectionPopup_module_options);




       /* harmony default export */ const ConnectionPopup_ConnectionPopup_module = (ConnectionPopup_module/* default */.A && ConnectionPopup_module/* default */.A.locals ? ConnectionPopup_module/* default */.A.locals : undefined);

// EXTERNAL MODULE: external "async"
var external_async_ = __webpack_require__(82626);
var external_async_default = /*#__PURE__*/__webpack_require__.n(external_async_);
// EXTERNAL MODULE: external "remarkable"
var external_remarkable_ = __webpack_require__(31890);
// EXTERNAL MODULE: ./src/editor/src/utils/getDocsEndpoint.ts
var getDocsEndpoint = __webpack_require__(41160);
;// ./src/editor/src/views/ConnectionPopup/DocsParser.ts



// Fetch and parse out documentation for inputs and outputs
const _pages = {};
class DocsParser {
    constructor() {
        this.md = new external_remarkable_.Remarkable({
            html: true,
            breaks: true
        });
    }
    getDocsForType(type, cb) {
        let docsUrl = type.docs.replace('#/', ''); // + '-short.md';
        if (!docsUrl.endsWith('.md'))
            docsUrl = docsUrl += '.md';
        // Update no version tag with version tag (and potentially switch to local docs)
        docsUrl = docsUrl.replace('https://docs.noodl.net', (0,getDocsEndpoint/* default */.A)());
        if (docsUrl.includes('localhost:3000') === false) {
            // See if the page is in the cache
            if (_pages[docsUrl] !== undefined)
                return cb(_pages[docsUrl]);
        }
        this.fetchPage(docsUrl, (md) => {
            if (!md)
                return;
            const page = {
                inputs: {},
                outputs: {}
            };
            // Find all input and output references
            const inputMatches = md.matchAll(/{\*\/##input:([A-Za-z0-9\s\.\*\-]+)##\*\\}(.*?){\*\/##input##\*\\}/g);
            for (const _s of inputMatches) {
                const inputName = _s[1];
                if (inputName === undefined)
                    continue;
                const docs = _s[2];
                page.inputs[inputName] = this.md.render(docs);
            }
            const outputMatches = md.matchAll(/{\*\/##output:([A-Za-z0-9\s\.\*\-]+)##\*\\}(.*?){\*\/##output##\*\\}/g);
            for (const _s of outputMatches) {
                const outputName = _s[1];
                if (outputName === undefined)
                    continue;
                const docs = _s[2];
                page.outputs[outputName] = this.md.render(docs);
            }
            _pages[docsUrl] = page;
            cb(page);
        });
    }
    fetchPage(url, callback) {
        this.baseUrl = new URL(url);
        $.ajax({
            url: url,
            headers: {
                Accept: 'text/html'
            },
            success: function (md) {
                // Find all filename references
                const matches = md.matchAll(/\[filename\]\((.*?)\'\:include\'\)/g);
                const refs = [];
                for (const m of matches) {
                    let ref = m[1];
                    if (ref !== undefined) {
                        ref = ref.trim();
                        const absoluteUrl = new URL(ref, url);
                        refs.push({ anchor: m[0], url: absoluteUrl.href });
                    }
                }
                external_async_default().each(refs, function (ref, cb) {
                    $.ajax({
                        url: ref.url,
                        headers: {
                            Accept: 'text/html'
                        },
                        success: function (refMd) {
                            md = md.replace(ref.anchor, refMd);
                            cb();
                        },
                        error: function () {
                            cb(); // Ignore error
                        }
                    });
                }, function () {
                    // All done
                    callback(md);
                });
            },
            error: function (err) {
                if (err.status === 401) {
                    /* Access denied */
                }
                else {
                    console.warn(err);
                    callback();
                }
            }
        });
    }
}
const docsParser = new DocsParser();


// EXTERNAL MODULE: external "react-dom"
var external_react_dom_ = __webpack_require__(20180);
var external_react_dom_default = /*#__PURE__*/__webpack_require__.n(external_react_dom_);
;// ./src/editor/src/views/ConnectionPopup/components/DocsPopup.tsx




function DocsPopup(props) {
    const enums = typeof props.type === 'object' && props.type.name === 'enum' ? props.type.enums : undefined;
    const typeDocs = '(' +
        nodelibrary/* NodeLibrary */.m.nameForPortType(props.type) +
        (enums !== undefined ? ':' + enums.map((e) => e.label).join(',') : '') +
        ')';
    return external_react_dom_default().createPortal(external_react_default().createElement("div", { className: ConnectionPopup_ConnectionPopup_module.docsPopup },
        external_react_default().createElement("div", { className: ConnectionPopup_ConnectionPopup_module.docsHeader },
            external_react_default().createElement("span", null, props.name),
            external_react_default().createElement("span", { className: ConnectionPopup_ConnectionPopup_module.docsType }, typeDocs)),
        external_react_default().createElement("div", { className: ConnectionPopup_ConnectionPopup_module.docsBody, dangerouslySetInnerHTML: { __html: props.body } })), document.querySelector('.popup-small-docs'));
}

;// ./src/editor/src/views/ConnectionPopup/components/PortItem.tsx







const _shouldShowDocsForPort = {}; // Ugly fix for not showing duplicate docs on ports
function PortItem(props) {
    const ref = (0,external_react_.useRef)(null);
    const [showDocs, setShowDocs] = (0,external_react_.useState)(false);
    const [docs, setDocs] = (0,external_react_.useState)();
    let tooltipTimeout;
    const onMouseOver = () => {
        if (props.port.message) {
            const bounds = ref.current.getBoundingClientRect();
            tooltipTimeout = setTimeout(() => {
                popuplayer_default().instance.showTooltip({
                    x: bounds.left + bounds.width / 2,
                    y: bounds.top + bounds.height,
                    position: 'bottom',
                    content: props.port.message
                });
            }, 1000);
        }
        const p = props.port;
        _shouldShowDocsForPort[p.name] = true;
        if (p.parent.type.docs) {
            docsParser.getDocsForType(p.parent.type, (docs) => {
                if (!_shouldShowDocsForPort[p.name])
                    return; // Make sure we should still show docs for port
                const ports = p.section === 'from' ? docs.outputs : docs.inputs;
                const name = (p.displayName || p.name).toLowerCase();
                let d = ports[name];
                if (d === undefined) {
                    // No docs found, try only the port name (not display name)
                    d = ports[p.name];
                }
                if (d === undefined) {
                    // Still no docs found, try using regexp
                    const keys = Object.keys(ports);
                    keys.sort((a, b) => b.length - a.length); // Match "longest" regexp first, so "*" becomes the last to match
                    const matchingPort = keys.find((key) => p.name.match(new RegExp(key)));
                    if (matchingPort)
                        d = ports[matchingPort];
                }
                if (d) {
                    // There is documentation for this port
                    setDocs(d);
                    setShowDocs(true);
                }
            });
        }
    };
    const onMouseOut = () => {
        _shouldShowDocsForPort[props.port.name] = false;
        popuplayer_default().instance.hideTooltip();
        clearTimeout(tooltipTimeout);
        setDocs(undefined);
        setShowDocs(false);
    };
    const p = props.port;
    const state = (props.isSelected && 'selected') || (p.disabled && 'disabled') || 'enabled';
    (0,external_react_.useEffect)(() => {
        var _a;
        if (props.isSelected) {
            (_a = ref === null || ref === void 0 ? void 0 : ref.current) === null || _a === void 0 ? void 0 : _a.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
            });
        }
    }, [props.isSelected]);
    return (external_react_default().createElement("div", null,
        external_react_default().createElement("div", { ref: ref, onMouseOver: onMouseOver, onMouseOut: onMouseOut, className: external_classnames_default()(ConnectionPopup_ConnectionPopup_module.listElementPort, ConnectionPopup_ConnectionPopup_module[state]), onClick: props.onClick },
            nodelibrary/* NodeLibrary */.m.nameForPortType(p.type) === 'signal' ? external_react_default().createElement("div", { className: ConnectionPopup_ConnectionPopup_module.signalIcon }) : null,
            p.annotatedName !== undefined ? (external_react_default().createElement("span", { dangerouslySetInnerHTML: { __html: p.annotatedName } })) : (external_react_default().createElement("span", null, p.displayName)),
            showDocs ? external_react_default().createElement(DocsPopup, { name: p.displayName, type: p.type, body: docs }) : null)));
}

;// ./src/editor/src/views/ConnectionPopup/components/PortGroup.tsx




function PortGroup(props) {
    // comments in this component is to remove the group folding.
    // delete the commented code if no-one misses the foldability
    //const [expanded, setExpanded] = useState(props.expanded);
    const colors = props.colors;
    return (external_react_default().createElement("div", null,
        external_react_default().createElement("div", { style: { backgroundColor: colors.header, borderBottom: `1px solid ${colors.base}` }, className: external_classnames_default()(ConnectionPopup_ConnectionPopup_module.listElementGroup, ConnectionPopup_ConnectionPopup_module.enabled) },
            external_react_default().createElement("div", { className: ConnectionPopup_ConnectionPopup_module.groupLabel }, props.group.name)),
        props.group.ports.map((p) => (external_react_default().createElement(PortItem, { key: p.name, colors: colors, onClick: () => props.onItemClicked(p), isSelected: props.selectedPort === p.name || p.name === props.highlightedPort, port: p })))));
}

;// ./src/editor/src/views/ConnectionPopup/components/ConnectionBar.tsx








function _getPorts(type, model /* NodeGraphNode */) {
    const ports = type === 'from' ? model.getPorts('output') : model.getPorts('input');
    const models = [];
    function isConnectable(p) {
        return !(typeof p.type === 'object' && p.type.allowEditOnly);
    }
    // Apply ports condition filter (only use extended filter, i.e. ones that should not be connectable if filtered)
    const portFilter = nodelibrary/* NodeLibrary */.m.instance.applyPortConditionsFilterForNode(model, ['extended']);
    portFilter.forEach((portname) => {
        const idx = ports.findIndex((p) => p.name === portname);
        if (idx !== -1)
            ports.splice(idx, 1);
    });
    for (const i in ports) {
        const p = ports[i];
        if (isConnectable(p)) {
            models.push({
                name: p.name,
                group: p.group,
                displayName: (p.displayName || p.name) + (p.tab && p.tab.label ? '(' + p.tab.label + ')' : ''), // Show the tab label in the connection editor
                annotatedName: nodelibrary/* NodeLibrary */.m.instance.getAnnotatedPortName(model, p),
                type: p.type,
                plug: p.plug,
                section: type,
                parent: model
            });
        }
    }
    return models;
}
function ConnectionBar(props) {
    var _a;
    const ports = _getPorts(props.type, props.model);
    const [selectedPort, setSelectedPort] = (0,external_react_.useState)();
    const [searchTerm, setSearchTerm] = (0,external_react_.useState)('');
    const searchRef = (0,external_react_.useRef)(null);
    const [cursorPosition, setCursorPosition] = (0,external_react_.useState)(0);
    const portAmount = (0,external_react_.useRef)(0);
    const disabled = props.type === 'to' && (props.fromNode === undefined || props.sourcePort === undefined);
    const colors = ((_a = props.model.metadata) === null || _a === void 0 ? void 0 : _a.colorOverride)
        ? nodelibrary/* NodeLibrary */.m.instance.colorSchemeForNodeColorName(props.model.metadata.colorOverride)
        : nodelibrary/* NodeLibrary */.m.instance.colorSchemeForNodeType(props.model.type);
    function focusSearch() {
        if ((searchRef === null || searchRef === void 0 ? void 0 : searchRef.current) && props.isActive) {
            searchRef.current.focus();
        }
    }
    (0,external_react_.useEffect)(() => {
        focusSearch();
    }, [searchRef.current, props.isActive]);
    (0,external_react_.useEffect)(() => {
        const eventGroup = {};
        EventDispatcher.EventDispatcher.instance.on('Model.connectionAdded', () => {
            setSelectedPort(undefined);
        }, eventGroup);
        return () => EventDispatcher.EventDispatcher.instance.off(eventGroup);
    });
    function moveCursor(amt) {
        if (!props.isActive)
            return;
        setCursorPosition((current) => {
            let newPos = current + amt;
            if (newPos < 0)
                newPos = 0;
            if (newPos > portAmount.current)
                newPos = portAmount.current;
            return newPos;
        });
    }
    function handleEnter() {
        if (!cursorPosition)
            return;
        if (!props.isActive)
            return;
        onPortClicked(flatPorts[cursorPosition - 1]);
        setCursorPosition(0);
    }
    (0,external_react_.useEffect)(() => {
        const handleKeyDown = (event) => {
            switch (event.keyCode) {
                case constants_KeyCode/* KeyCode */.D.Down:
                    moveCursor(1);
                    break;
                case constants_KeyCode/* KeyCode */.D.Up:
                    moveCursor(-1);
                    break;
                case constants_KeyCode/* KeyCode */.D.Enter:
                    handleEnter();
                    break;
            }
        };
        window.addEventListener('keydown', handleKeyDown);
        return () => {
            window.removeEventListener('keydown', handleKeyDown);
        };
    }, [cursorPosition, props.isActive]);
    // Update port state
    if (props.type === 'to' && props.fromNode !== undefined && props.sourcePort !== undefined) {
        const sourcePort = props.fromNode.getPort(props.sourcePort);
        if (sourcePort !== undefined)
            ports.forEach((p) => {
                const status = props.model.owner.getConnectionStatus({
                    sourceNode: props.fromNode,
                    sourcePort: props.sourcePort,
                    targetNode: props.model,
                    targetPort: p.name
                });
                p.disabled = !status.connectable;
                p.message = status.message;
                // Make sure signals only can connect to input signals
                const targetType = nodelibrary/* NodeLibrary */.m.nameForPortType(p.type);
                if (nodelibrary/* NodeLibrary */.m.nameForPortType(sourcePort.type) === 'signal' &&
                    targetType !== '*' &&
                    targetType !== 'signal') {
                    p.disabled = true;
                    p.message = 'Can only connect signal output to signal input';
                }
            });
    }
    // Group ports
    const groups = [];
    ports.forEach((p) => {
        if (p.disabled)
            return;
        if (searchTerm) {
            if (p.displayName.toLowerCase().indexOf(searchTerm.toLowerCase()) === -1)
                return;
        }
        const name = p.group ? p.group : 'Other';
        const g = groups.find((_g) => _g.name === name);
        if (!g)
            groups.push({ name: name, ports: [p] });
        else
            g.ports.push(p);
    });
    // Move important groups to top
    const priorityGroups = (props.model.type.connectionPanel !== undefined && props.model.type.connectionPanel.groupPriority !== undefined
        ? props.model.type.connectionPanel.groupPriority
        : ['General', 'Events', 'Actions', 'States'])
        .slice()
        .reverse();
    priorityGroups.forEach((g) => {
        groups.sort(function (x, y) {
            return x.name === g ? -1 : y.name === g ? 1 : 0;
        });
    });
    // Move other to the bottom
    const otherIdx = groups.findIndex((g) => g.name === 'Other');
    if (otherIdx !== -1) {
        const otherGroup = groups.splice(otherIdx, 1);
        groups.push(otherGroup[0]);
    }
    const flatPorts = [];
    groups.forEach((g) => flatPorts.push(...g.ports));
    portAmount.current = flatPorts.length;
    const onPortClicked = (p) => {
        if (p.disabled)
            return;
        setSelectedPort(p.name);
        props.onPortSelected(p.name);
    };
    const hasPorts = groups.length > 0;
    return (external_react_default().createElement("div", { style: {
            backgroundColor: colors.base,
            borderBottom: `1px solid ${colors.base}`,
            // @ts-expect-error CSS Variable
            '--local--port-hover-color': colors.baseHighlighted
        }, className: external_classnames_default()([ConnectionPopup_ConnectionPopup_module.bar, disabled && ConnectionPopup_ConnectionPopup_module.disabled]) },
        external_react_default().createElement("div", { className: ConnectionPopup_ConnectionPopup_module.searchContainer, style: { borderBottom: `1px solid ${colors.base}`, backgroundColor: colors.header }, key: "searchinput" },
            external_react_default().createElement(Icon/* Icon */.In, { icon: Icon/* IconName */.$M.Search, size: Icon/* IconSize */.lK.Tiny, UNSAFE_className: ConnectionPopup_ConnectionPopup_module.searchIcon }),
            external_react_default().createElement("input", { type: "text", placeholder: "Search", className: ConnectionPopup_ConnectionPopup_module.searchInput, value: searchTerm, onChange: (e) => setSearchTerm(e.target.value), onFocus: () => setCursorPosition(0), onBlur: () => setTimeout(() => setSearchTerm(''), 200), ref: searchRef })),
        hasPorts ? (external_react_default().createElement("div", null, groups.map((g) => {
            var _a;
            return (external_react_default().createElement(PortGroup, { key: g.name, colors: colors, expanded: true, onItemClicked: onPortClicked, group: g, selectedPort: selectedPort, highlightedPort: cursorPosition && ((_a = flatPorts[cursorPosition - 1]) === null || _a === void 0 ? void 0 : _a.name) }));
        }))) : (external_react_default().createElement("div", { className: ConnectionPopup_ConnectionPopup_module.noPortsMessage }, searchTerm ? (props.type === 'from' ? (external_react_default().createElement("span", null, "Can't find any outputs")) : (external_react_default().createElement("span", null, "Can't find any inputs"))) : props.type === 'from' ? (external_react_default().createElement("span", null, "This node has no outputs")) : (external_react_default().createElement("span", null, "This node has no inputs"))))));
}

;// ./src/editor/src/views/ConnectionPopup/ConnectionPopup.tsx




function ConnectionPopup(props) {
    return (external_react_default().createElement("div", { className: external_classnames_default()([ConnectionPopup_ConnectionPopup_module.popup, props.disabled && ConnectionPopup_ConnectionPopup_module.disabled]) },
        external_react_default().createElement("div", { className: external_classnames_default()([ConnectionPopup_ConnectionPopup_module.popupHeader, props.disabled && ConnectionPopup_ConnectionPopup_module.disabled]) },
            external_react_default().createElement("span", null, props.type === 'from' ? 'STEP 1 - Select output' : 'STEP 2 - Select input')),
        external_react_default().createElement("div", { className: ConnectionPopup_ConnectionPopup_module.popupScroll },
            props.type === 'from' && (external_react_default().createElement(ConnectionBar, { type: "from", isActive: props.isPanelActive('from'), model: props.model, onPortSelected: (e) => {
                    props.onPortSelected(e);
                } })),
            props.type === 'to' && (external_react_default().createElement(ConnectionBar, { type: "to", isActive: props.isPanelActive('to'), model: props.model, fromNode: props.fromNode, sourcePort: props.sourcePort, onPortSelected: (e) => {
                    props.onPortSelected(e);
                } })))));
}

;// ./src/editor/src/views/ConnectionPopup/index.ts


// EXTERNAL MODULE: ./src/editor/src/views/createnewnodepanel.ts + 49 modules
var createnewnodepanel = __webpack_require__(91559);
// EXTERNAL MODULE: ./src/editor/src/views/documents/EditorDocument/titlebar.ts
var titlebar = __webpack_require__(89398);
// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/ComponentIcon.ts
var ComponentIcon = __webpack_require__(56937);
// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.utils.ts
var projectmodel_utils = __webpack_require__(72866);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Label/index.ts + 2 modules
var Label = __webpack_require__(91629);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NodeGraphComponentTrail/NodeGraphComponentTrail.module.scss
var NodeGraphComponentTrail_module = __webpack_require__(34523);
;// ./src/editor/src/views/NodeGraphComponentTrail/NodeGraphComponentTrail.module.scss

      
      
      
      
      
      
      
      
      

var NodeGraphComponentTrail_module_options = {};

NodeGraphComponentTrail_module_options.styleTagTransform = (styleTagTransform_default());
NodeGraphComponentTrail_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      NodeGraphComponentTrail_module_options.insert = insertBySelector_default().bind(null, "head");
    
NodeGraphComponentTrail_module_options.domAPI = (styleDomAPI_default());
NodeGraphComponentTrail_module_options.insertStyleElement = (insertStyleElement_default());

var NodeGraphComponentTrail_module_update = injectStylesIntoStyleTag_default()(NodeGraphComponentTrail_module/* default */.A, NodeGraphComponentTrail_module_options);




       /* harmony default export */ const NodeGraphComponentTrail_NodeGraphComponentTrail_module = (NodeGraphComponentTrail_module/* default */.A && NodeGraphComponentTrail_module/* default */.A.locals ? NodeGraphComponentTrail_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/NodeGraphComponentTrail/NodeGraphComponentTrail.tsx










function NodeGraphComponentTrail({ componentTrail, canNavigateBack, canNavigateForward, onSwitchToComponent, onHistoryBack, onHistoryForward }) {
    const trailRef = (0,external_react_.useRef)(null);
    // Change the scroll direction to horizontal.
    function onScroll(event) {
        if (trailRef.current) {
            event.preventDefault();
            trailRef.current.scrollLeft += event.deltaY + event.deltaX;
        }
    }
    return (external_react_default().createElement("div", { className: NodeGraphComponentTrail_NodeGraphComponentTrail_module['Root'] },
        external_react_default().createElement("div", { className: NodeGraphComponentTrail_NodeGraphComponentTrail_module['HistoryControls'] },
            external_react_default().createElement(IconButton/* IconButton */.K0, { icon: Icon/* IconName */.$M.CaretLeft, onClick: onHistoryBack, size: Icon/* IconSize */.lK.Small, variant: IconButton/* IconButtonVariant */.nl.OpaqueOnHover, isDisabled: !canNavigateBack, UNSAFE_className: NodeGraphComponentTrail_NodeGraphComponentTrail_module['HistoryButton'] }),
            external_react_default().createElement(IconButton/* IconButton */.K0, { icon: Icon/* IconName */.$M.CaretRight, onClick: onHistoryForward, size: Icon/* IconSize */.lK.Small, variant: IconButton/* IconButtonVariant */.nl.OpaqueOnHover, isDisabled: !canNavigateForward, UNSAFE_className: NodeGraphComponentTrail_NodeGraphComponentTrail_module['HistoryButton'] })),
        external_react_default().createElement("div", { className: NodeGraphComponentTrail_NodeGraphComponentTrail_module['TrailContainer'] },
            external_react_default().createElement("div", { ref: trailRef, className: NodeGraphComponentTrail_NodeGraphComponentTrail_module['Trail'], onWheel: onScroll }, componentTrail.map((item) => {
                if (item.component)
                    return external_react_default().createElement(Item, { key: item.fullName, item: item, onSwitchToComponent: onSwitchToComponent });
                return (external_react_default().createElement(Tooltip/* Tooltip */.m, { UNSAFE_triggerClassName: NodeGraphComponentTrail_NodeGraphComponentTrail_module['ItemTrigger'], content: 'Has no graph', key: item.fullName, isNotHiddenOnClick: true },
                    external_react_default().createElement(Item, { item: item, onSwitchToComponent: onSwitchToComponent })));
            })))));
}
function Item({ item, onSwitchToComponent }) {
    let icon = getIconFromItem(item);
    const itemRef = (0,external_react_.useRef)(null);
    // change a visual component icon to be a regular component icon in the trail
    // @ts-expect-error fix this when we refactor the component sidebar to not use the old HTML templates
    if (icon === 2) {
        icon = Icon/* IconName */.$M.Component;
    }
    (0,external_react_.useEffect)(() => {
        if (!itemRef.current || !item.isCurrent)
            return;
        itemRef.current.scrollIntoView();
    }, [itemRef.current, item.isCurrent]);
    const name = item.name;
    let isSheet = false;
    if (!item.component) {
        if (name.substring(1, -1) === '#') {
            isSheet = true;
        }
    }
    if (name === '#__cloud__')
        return null;
    const rootComponent = (0,projectmodel_utils/* getDefaultComponent */.V)();
    let isRootComponent = false;
    if (rootComponent.id) {
        isRootComponent = rootComponent.id === item.id;
    }
    else {
        isRootComponent = rootComponent.name === item.fullName;
    }
    return (external_react_default().createElement("div", { ref: itemRef, className: external_classnames_default()(NodeGraphComponentTrail_NodeGraphComponentTrail_module['Item'], item.component ? NodeGraphComponentTrail_NodeGraphComponentTrail_module['is-component'] : NodeGraphComponentTrail_NodeGraphComponentTrail_module['is-folder'], item.isCurrent && NodeGraphComponentTrail_NodeGraphComponentTrail_module['is-current']), onClick: () => {
            if (!item.component || item.isCurrent)
                return;
            onSwitchToComponent(item.component, { pushHistory: true });
        } },
        icon && !isSheet && (external_react_default().createElement(Icon/* Icon */.In, { icon: isRootComponent ? Icon/* IconName */.$M.Home : icon, size: Icon/* IconSize */.lK.Tiny, UNSAFE_className: NodeGraphComponentTrail_NodeGraphComponentTrail_module['Icon'] })),
        external_react_default().createElement(Label/* Label */.JU, { variant: item.component ? Text/* TextType */.M2.Default : Text/* TextType */.M2.Shy, UNSAFE_className: NodeGraphComponentTrail_NodeGraphComponentTrail_module['Label'] }, name),
        item.component && Boolean(item.stateText) && (external_react_default().createElement(Label/* Label */.JU, { hasLeftSpacing: true, variant: Text/* TextType */.M2.Secondary },
            "(",
            item.stateText,
            ")"))));
}
function getIconFromItem(item) {
    if (!item.component)
        return Icon/* IconName */.$M.FolderClosed;
    const iconType = (0,ComponentIcon/* getComponentIconType */.N)(item.component);
    if (iconType) {
        // TODO: Typescript, ugly typings, is there a better way?
        return iconType;
    }
    return Icon/* IconName */.$M.Component;
}

;// ./src/editor/src/views/NodeGraphComponentTrail/index.ts


// EXTERNAL MODULE: ./src/editor/src/views/nodegrapheditor.debuginspectors.js
var nodegrapheditor_debuginspectors = __webpack_require__(20490);
var nodegrapheditor_debuginspectors_default = /*#__PURE__*/__webpack_require__.n(nodegrapheditor_debuginspectors);
;// ./src/editor/src/views/nodegrapheditor.drag.ts




function getDragItemComponent(dragItem) {
    if (dragItem.type === 'component' && dragItem.component) {
        return dragItem.component;
    }
    return dragItem.component || dragItem.nodeType || (dragItem.folder ? dragItem.folder.component : undefined);
}
/**
 * Drop can only be accepted if it is the right type
 * and if the highlighed node supports children
 *
 * @param editor
 * @param dragItem
 * @returns
 */
function canAcceptDrop(editor, dragItem) {
    if (editor.readOnly) {
        return false;
    }
    const activeBackend = (0,NodeGraph/* isComponentModel_CloudRuntime */.dk)(editor.activeComponent);
    // const activeIcon = getComponentIconType(editor.activeComponent);
    if (['component', 'folder'].includes(dragItem.type)) {
        const newComponent = getDragItemComponent(dragItem);
        if (newComponent) {
            const newBackend = (0,NodeGraph/* isComponentModel_CloudRuntime */.dk)(newComponent);
            const newIcon = (0,ComponentIcon/* getComponentIconType */.N)(newComponent);
            // (Cloud Function) Backend to backend
            if (activeBackend && newBackend && newIcon === ComponentIcon/* ComponentIconType */.J.CloudFunction) {
                // We dont allow Cloud Functions in Cloud Functions,
                // they have to be splitted up into logic nodes.
                popuplayer_default().instance.setDragMessage('Cannot create Cloud Function inside Cloud Function.');
                return false;
            }
            // TODO: Cloud Function with children
            // (Cloud Function) Backend to frontend
            if (!activeBackend && newBackend && newIcon === ComponentIcon/* ComponentIconType */.J.CloudFunction) {
                // We will convert it to a Cloud Function node
                popuplayer_default().instance.setDragMessage();
                return true;
            }
            // Backend to frontend
            if (!activeBackend && newBackend) {
                // We don't allow using logic components from the backend in the frontend
                popuplayer_default().instance.setDragMessage('Cannot mix frontend and Cloud nodes.');
                return false;
            }
            // Frontend to backend
            if (activeBackend && !newBackend) {
                popuplayer_default().instance.setDragMessage('Cannot mix frontend and Cloud nodes.');
                return false;
            }
        }
    }
    if (dragItem.type === 'component' ||
        dragItem.type === 'node' ||
        (dragItem.type === 'folder' && dragItem.folder.component)) {
        const component = editor.model.owner;
        const status = component.getCreateStatus({
            parent: editor.highlighted ? editor.highlighted.model : undefined,
            type: getDragItemComponent(dragItem)
        });
        if (!status.creatable)
            popuplayer_default().instance.setDragMessage(status.message);
        else
            popuplayer_default().instance.setDragMessage();
        return status.creatable;
    }
    return false;
}
function onDrop(editor, dragItem, position) {
    const activeBackend = (0,NodeGraph/* isComponentModel_CloudRuntime */.dk)(editor.activeComponent);
    // const activeIcon = getComponentIconType(editor.activeComponent);
    if (dragItem.type === 'component') {
        const newBackend = (0,NodeGraph/* isComponentModel_CloudRuntime */.dk)(dragItem.component);
        const newIcon = (0,ComponentIcon/* getComponentIconType */.N)(dragItem.component);
        // (Cloud Function) Backend to frontend
        // Convert it to a Cloud Function node
        if (!activeBackend && newBackend && newIcon === ComponentIcon/* ComponentIconType */.J.CloudFunction) {
            const cloudFunctionComponent = nodelibrary/* NodeLibrary */.m.instance.types.find((x) => x.name === 'CloudFunction2');
            if (!cloudFunctionComponent) {
                console.error("Cannot find 'Cloud Function' component.");
                return;
            }
            const functionName = dragItem.component.name.slice('/#__cloud__/'.length);
            // Create a reference component to the cloud function component.
            editor.createNewNode(cloudFunctionComponent, position, {
                parameters: {
                    function: functionName
                }
            });
            return true;
        }
    }
    // Create the component
    editor.createNewNode(getDragItemComponent(dragItem), position);
    return true;
}

// EXTERNAL MODULE: ./src/editor/src/views/nodegrapheditor/MouseWheelModeDetector.js
var MouseWheelModeDetector = __webpack_require__(94755);
var MouseWheelModeDetector_default = /*#__PURE__*/__webpack_require__.n(MouseWheelModeDetector);
;// ./src/editor/src/views/nodegrapheditor/NavigationHistory.ts

class NavigationHistory {
    constructor({ owner }) {
        this.owner = owner;
        this.reset();
    }
    reset() {
        this.history = [];
        this.index = -1;
        this.canNavigateBack = false;
        this.canNavigateForward = false;
    }
    //History can be incorrect when changing branch, this functions goes through and discards any incorrect entries
    discardInvalidEntries() {
        this.history = this.history.filter((componentName) => projectmodel.ProjectModel.instance.getComponentWithName(componentName) ? true : false);
        if (this.index >= this.history.length) {
            this.index = this.history.length - 1;
        }
        //remove components that appear more than once in a row. Can happen when a component is removed and the component before and after is the same.
        for (let i = this.history.length - 1; i > 0; i--) {
            if (this.history[i] === this.history[i - 1]) {
                this.history.splice(i, 1);
            }
        }
        this.canNavigateBack = this.index > 0;
        this.canNavigateForward = false;
        if (this.index > this.history.length - 1) {
            this.index = this.history.length - 1;
            this.goToCurrent();
        }
    }
    push(component) {
        if (this.history[this.index] === component.name)
            return;
        this.history.length = this.index + 1; //clear the history after the index
        this.history.push(component.name);
        this.index = this.history.length - 1;
        this.canNavigateBack = this.index > 0;
        this.canNavigateForward = false;
    }
    /**
     *
     * @returns Returns true when successfully went back; Otherwise, false.
     */
    goBack() {
        if (this.index <= 0) {
            return false;
        }
        this.index--;
        this.goToCurrent();
        return true;
    }
    /**
     *
     * @returns Returns true when successfully went forward; Otherwise, false.
     */
    goForward() {
        if (this.index === this.history.length - 1) {
            return false;
        }
        this.index++;
        this.goToCurrent();
        return true;
    }
    onComponentRemoved(component) {
        this.history = this.history.filter((componentName) => componentName !== component);
        this.discardInvalidEntries();
    }
    getTopComponent() {
        return this.history[this.history.length - 1];
    }
    /**
     *
     * @returns Returns true when successfully went to current component; Otherwise, false.
     */
    goToCurrent() {
        const componentName = this.history[this.index];
        if (!componentName)
            return false;
        const component = projectmodel.ProjectModel.instance.getComponentWithName(componentName);
        if (!component)
            return false;
        this.canNavigateBack = this.index > 0;
        this.canNavigateForward = this.index < this.history.length - 1;
        this.owner.switchToComponent(component);
        return true;
    }
}

;// ./src/editor/src/views/nodegrapheditor/NodeGraphEditorConnection.ts





function getPortName(p) {
    return p ? p.editorName || p.displayName : undefined;
}
function getPortIndex(p) {
    return p ? p.index || 0 : undefined;
}
class NodeGraphEditorConnection {
    constructor(model, ctx) {
        this.model = model;
        for (const i in model)
            this[i] = model[i];
        this.ctx = ctx;
    }
    static createFromModel(model, owner, ctx) {
        const con = new NodeGraphEditorConnection(model, ctx);
        con.fromNode = owner.findNodeWithId(model.fromId);
        con.toNode = owner.findNodeWithId(model.toId);
        con.owner = owner;
        con.connect(con);
        return con;
    }
    resolvePorts(args) {
        this.fromPort = this.fromNode.model.getPort(this.fromProperty, 'output');
        this.toPort = this.toNode.model.getPort(this.toProperty, 'input');
    }
    connect(args) {
        this.fromNode = args.fromNode;
        this.toNode = args.toNode;
        this.fromProperty = args.fromProperty;
        this.toProperty = args.toProperty;
        this.resolvePorts();
        this.fromNode.connections.push(this);
        this.fromNode.sortConnections();
        this.toNode.connections.push(this);
        this.toNode.sortConnections();
        this.owner.connections.push(this);
    }
    disconnect() {
        let idx = this.fromNode.connections.indexOf(this);
        if (idx !== -1)
            this.fromNode.connections.splice(idx, 1);
        idx = this.toNode.connections.indexOf(this);
        if (idx !== -1)
            this.toNode.connections.splice(idx, 1);
        idx = this.owner.connections.indexOf(this);
        if (idx !== -1)
            this.owner.connections.splice(idx, 1);
        this.fromNode = this.toNode = undefined;
        this.fromProperty = this.toProperty = undefined;
    }
    getLocationRelativeTo(node) {
        const other = node === this.toNode ? this.fromNode : this.toNode;
        if (node.global.x < other.global.x - NodeGraphEditorNode.size.width * 1.1) {
            return 'left';
        }
        else if (other.global.x < node.global.x - NodeGraphEditorNode.size.width * 1.1) {
            return 'right';
        }
        else {
            return 'inline';
        }
    }
    getPropertyFor(node) {
        return node === this.fromNode ? this.fromProperty : this.toProperty;
    }
    getPortDisplayNameFor(node) {
        return node === this.fromNode ? getPortName(this.fromPort) : getPortName(this.toPort);
    }
    getPortIndexFor(node) {
        return node === this.fromNode ? getPortIndex(this.fromPort) : getPortIndex(this.toPort);
    }
    getPortGroupNameFor(node) {
        return node === this.fromNode
            ? this.fromPort
                ? this.fromPort.group
                : undefined
            : this.toPort
                ? this.toPort.group
                : undefined;
    }
    getDirectionFor(node) {
        return node === this.fromNode ? 'from' : 'to';
    }
    setPlugFor(node, plug) {
        if (node === this.fromNode)
            this.fromPlug = plug;
        else
            this.toPlug = plug;
    }
    isHighlighted() {
        return ((this.owner && this.owner.highlightedConnection === this) ||
            this.owner.isHighlighted(this.fromNode) ||
            this.owner.isHighlighted(this.toNode) ||
            this.owner.selector.isActive(this.fromNode) ||
            this.owner.selector.isActive(this.toNode));
    }
    mouse(type, pos, evt) {
        if (evt.button !== 0)
            return; //only interact with left mouse button
        const _this = this;
        if (type === 'move') {
            if (this.ctx) {
                this.ctx.lineWidth = 10;
                this.drawCurve();
                if (this.ctx.isPointInStroke(pos.x, pos.y)) {
                    evt.consumed = true;
                    this.owner.setHighlightedConnection(this, pos);
                    // Show tooltip if the connection is unhealthy or has annotations
                    if (this.owner.deleteModeConnection !== this) {
                        // annotations takes priority over health
                        if (this.model.annotation) {
                            popuplayer_default().instance.showTooltip({
                                x: evt.pageX,
                                y: evt.pageY,
                                position: 'bottom',
                                content: this.model.annotation
                            });
                        }
                        else {
                            const health = this.getHealth();
                            if (!health.healthy) {
                                popuplayer_default().instance.showTooltip({
                                    x: evt.pageX,
                                    y: evt.pageY,
                                    position: 'bottom',
                                    content: health.message
                                });
                            }
                        }
                    }
                    this.owner.repaint();
                }
                else if (this.owner.highlightedConnection === this) {
                    this.owner.setHighlightedConnection(undefined);
                    popuplayer_default().instance.hideTooltip();
                    this.owner.repaint();
                }
            }
        }
        else if (type === 'down' && this.owner.highlightedConnection === this) {
            evt.consumed = true;
        }
        else if (type === 'up' && this.owner.highlightedConnection === this) {
            popuplayer_default().instance.hideTooltip();
            evt.consumed = true;
            if (this.model && this.owner.readOnly !== true) {
                // Don't do delete connection if in read only mode
                if (this.owner.deleteModeConnection === this) {
                    // Connection is clicked the second time
                    // Delete the connection
                    this.owner.deleteModeConnection = undefined;
                    this.owner.setHighlightedConnection(undefined);
                    this.owner.removeConnection(this.model);
                }
                else {
                    // Connection is clicked, turn it into a delete connection
                    this.owner.deleteModeConnection = this;
                    this.owner.repaint();
                    // If nothing has happened in 3 seconds clear delete mode
                    this.owner.clearDeleteModeTimer && clearTimeout(this.owner.clearDeleteModeTimer);
                    this.owner.clearDeleteModeTimer = setTimeout(function () {
                        if ((_this.owner.deleteModeConnection = _this)) {
                            _this.owner.deleteModeConnection = undefined;
                            _this.owner.repaint();
                        }
                    }, 3000);
                }
            }
        }
    }
    drawCurve() {
        const c = this.curve;
        if (!c)
            return;
        const ctx = this.ctx;
        ctx.beginPath();
        ctx.moveTo(c[0].x, c[0].y);
        ctx.bezierCurveTo(c[1].x, c[1].y, c[2].x, c[2].y, c[3].x, c[3].y);
    }
    midpoint(a, b) {
        return { x: a.x * 0.5 + b.x * 0.5, y: a.y * 0.5 + b.y * 0.5 };
    }
    _bezierInterpolation(t, a, b, c, d) {
        const t2 = t * t;
        const t3 = t2 * t;
        return (a +
            (-a * 3 + t * (3 * a - a * t)) * t +
            (3 * b + t * (-6 * b + b * 3 * t)) * t +
            (c * 3 - c * 3 * t) * t2 +
            d * t3);
    }
    pointOnCurve(t) {
        const c = this.curve;
        if (!c)
            return;
        return {
            x: this._bezierInterpolation(t, c[0].x, c[1].x, c[2].x, c[3].x),
            y: this._bezierInterpolation(t, c[0].y, c[1].y, c[2].y, c[3].y)
        };
    }
    _findClosestPointOnCurve(p, t0, t1) {
        const thres = 0.05;
        const _t0 = t0 + (t1 - t0) * 0.25;
        const p0 = this.pointOnCurve(_t0);
        const pd0 = (p0.x - p.x) * (p0.x - p.x) + (p0.y - p.y) * (p0.y - p.y);
        const _t1 = t0 + (t1 - t0) * 0.75;
        const p1 = this.pointOnCurve(_t1);
        const pd1 = (p1.x - p.x) * (p1.x - p.x) + (p1.y - p.y) * (p1.y - p.y);
        if (Math.abs(t0 - t1) < thres)
            return t0 * 0.5 + t1 * 0.5;
        if (pd0 < pd1)
            return this._findClosestPointOnCurve(p, t0, t0 + (t1 - t0) * 0.5);
        else
            return this._findClosestPointOnCurve(p, t0 + (t1 - t0) * 0.5, t1);
    }
    findClosestPointOnCurve(p) {
        return this._findClosestPointOnCurve(p, 0, 1);
    }
    getHealth() {
        if (!this.owner) {
            return {
                healthy: true,
                message: undefined
            };
        }
        return this.owner.model.getConnectionHealth({
            sourceNode: this.fromNode ? this.fromNode.model : undefined,
            sourcePort: this.fromProperty,
            targetNode: this.toNode ? this.toNode.model : undefined,
            targetPort: this.toProperty
        });
    }
    isHealthy() {
        return this.getHealth().healthy;
    }
    paint(ctx, paintRect) {
        this.ctx = ctx;
        if (!this.fromPlug || !this.toPlug)
            return;
        const from = this.fromNode.global;
        const to = this.toNode.global;
        // This is a connection between two plugs, figure out the placement
        // of the connection
        const fy = from.y +
            this.fromNode.titlebarHeight() +
            this.fromPlug.index * NodeGraphEditorNode.propertyConnectionHeight +
            NodeGraphEditorNode.propertyConnectionHeight / 2 +
            NodeGraphEditorNode.verticalSpacing;
        const ty = to.y +
            this.toNode.titlebarHeight() +
            this.toPlug.index * NodeGraphEditorNode.propertyConnectionHeight +
            NodeGraphEditorNode.propertyConnectionHeight / 2 +
            NodeGraphEditorNode.verticalSpacing;
        const loc = this.getLocationRelativeTo(this.fromNode);
        if (loc === 'left') {
            var mid = to.x * 0.5 + (from.x + NodeGraphEditorNode.size.width) * 0.5;
            this.curve = [
                { x: from.x + this.fromNode.nodeSize.width, y: fy },
                { x: mid, y: fy },
                { x: mid, y: ty },
                { x: to.x, y: ty }
            ];
        }
        else if (loc === 'right') {
            var mid = (to.x + NodeGraphEditorNode.size.width) * 0.5 + from.x * 0.5;
            this.curve = [
                { x: from.x, y: fy },
                { x: mid, y: fy },
                { x: mid, y: ty },
                { x: to.x + this.toNode.nodeSize.width, y: ty }
            ];
        }
        else {
            const dx = Math.min(from.x, to.x) - (50 + Math.abs(to.y - from.y) * 0.2);
            this.curve = [
                { x: from.x, y: fy },
                { x: dx, y: fy },
                { x: dx, y: ty },
                { x: to.x, y: ty }
            ];
        }
        function aabbIntersectTest(connection, paintArea) {
            const minX = Math.min(connection[0].x, connection[1].x, connection[2].x, connection[3].x);
            const maxX = Math.max(connection[0].x, connection[1].x, connection[2].x, connection[3].x);
            const minY = Math.min(connection[0].y, connection[1].y, connection[2].y, connection[3].y);
            const maxY = Math.max(connection[0].y, connection[1].y, connection[2].y, connection[3].y);
            return !(minX > paintArea.maxX || maxX < paintArea.minX || minY > paintArea.maxY || maxY < paintArea.minY);
        }
        if (aabbIntersectTest(this.curve, paintRect) === false) {
            return;
        }
        if (!this.getHealth().healthy) {
            ctx.setLineDash([5]);
        }
        const hoverConnection = this.isHighlighted();
        const type = nodelibrary/* NodeLibrary */.m.nameForPortType(this.fromPort ? this.fromPort.type : undefined);
        const connectionColors = nodelibrary/* NodeLibrary */.m.instance.colorSchemeForConnectionType(type);
        const color = hoverConnection ? connectionColors.highlighted : connectionColors.normal;
        ctx.strokeStyle = this.color ? this.color : color;
        if (this.model.annotation) {
            if (this.model.annotation === 'Deleted')
                ctx.strokeStyle = '#F57569';
            else if (this.model.annotation === 'Changed')
                ctx.strokeStyle = '#83B8BA';
            else if (this.model.annotation === 'Created')
                ctx.strokeStyle = '#5BF59E';
        }
        const lineWidth = 1.5;
        ctx.lineWidth = this.lineWidth ? this.lineWidth : lineWidth;
        this.drawCurve();
        ctx.stroke();
        if (debuginspector_default().instance.isEnabled() && debuginspector_default().instance.isConnectionPulsing(this)) {
            const t = debuginspector_default().instance.getPulseAnimationState(this);
            ctx.strokeStyle = connectionColors.pulsing ? connectionColors.pulsing : '#ffe85d';
            ctx.setLineDash([5, 15]);
            ctx.lineDashOffset = -t.offset;
            ctx.globalAlpha = t.opacity * 0.7;
            this.drawCurve();
            ctx.stroke();
            ctx.globalAlpha = 1;
        }
        ctx.lineDashOffset = 0;
        ctx.setLineDash([]); // Restore line dash if it has been previously set
        // Show the delete marker
        if (this.owner && this.owner.deleteModeConnection === this) {
            const a = this.midpoint(this.curve[0], this.curve[1]), b = this.midpoint(this.curve[1], this.curve[2]), c = this.midpoint(this.curve[2], this.curve[3]);
            const mp = this.midpoint(this.midpoint(a, b), this.midpoint(b, c));
            ctx.fillStyle = NodeGraphColors.red;
            ctx.beginPath();
            ctx.arc(mp.x, mp.y, 6, 0, 2 * Math.PI, false);
            ctx.fill();
            ctx.lineWidth = 1.5;
            ctx.strokeStyle = NodeGraphColors.base2;
            ctx.beginPath();
            const l = 2.5;
            ctx.moveTo(mp.x - l, mp.y - l);
            ctx.lineTo(mp.x + l, mp.y + l);
            ctx.moveTo(mp.x + l, mp.y - l);
            ctx.lineTo(mp.x - l, mp.y + l);
            ctx.stroke();
        }
    }
}

// EXTERNAL MODULE: ./src/editor/src/views/ShowContextMenuInPopup.tsx
var ShowContextMenuInPopup = __webpack_require__(28873);
// EXTERNAL MODULE: ./src/editor/src/views/ToastLayer/ToastLayer.tsx
var ToastLayer = __webpack_require__(80424);
;// ./src/editor/src/views/nodegrapheditor.ts




























// Initialize Blockly globals early (must run before runtime nodes load)








// Import test utilities for console debugging (dev only)














initBlocklyEditorGlobals();
// eslint-disable-next-line @typescript-eslint/no-var-requires
const NodeGraphEditorTemplate = __webpack_require__(80218);
// Styles
__webpack_require__(79114);
var CenterToFitMode;
(function (CenterToFitMode) {
    CenterToFitMode[CenterToFitMode["RootNodes"] = 0] = "RootNodes";
    CenterToFitMode[CenterToFitMode["AllNodes"] = 1] = "AllNodes";
})(CenterToFitMode || (CenterToFitMode = {}));
const SnapSpacing = 8;
class Selector {
    constructor() {
        this._selected = [];
    }
    get active() {
        return this._selected.length > 0;
    }
    get nodes() {
        return this._selected;
    }
    isActive(node) {
        return this._selected.indexOf(node) !== -1;
    }
    select(nodes) {
        this._selected = nodes;
    }
    unselect() {
        //remove selection highlight, if any
        if (this._selected.length === 1) {
            this._selected[0].selected = false;
        }
        this._selected = [];
    }
    unselectNode(node) {
        const index = this._selected.indexOf(node);
        if (index === -1) {
            return;
        }
        //remove selection highlight, if any
        if (node.selected) {
            node.selected = false;
        }
        this._selected.splice(index, 1);
    }
}
class NodeGraphEditor extends (view_default()) {
    constructor(args) {
        super();
        this.selector = new Selector();
        this.curtop = 0;
        this.lastBlocklyTabCloseTime = 0; // Track when Blockly tabs close to prevent accidental deletions
        this.draggingNodes = null;
        this.lastDraggingMousePos = { x: 0, y: 0 };
        this.startDraggingMousePos = { x: 0, y: 0 };
        this.runtimeType = undefined;
        this.toolbarRoots = [];
        this.titleRoot = null;
        this.highlightOverlayRoot = null;
        this.canvasTabsRoot = null;
        this.editorBannerRoot = null;
        /**
         * Get node bounds for the highlight overlay
         * Maps node IDs to their screen coordinates
         */
        this.getNodeBounds = (nodeId) => {
            const node = this.findNodeWithId(nodeId);
            if (!node)
                return null;
            return {
                x: node.global.x,
                y: node.global.y,
                width: node.nodeSize.width,
                height: node.nodeSize.height
            };
        };
        this.el = args.el;
        this.model = args.model;
        this.roots = [];
        this.connections = [];
        this.inspectors = [];
        this.origin = { x: 0, y: 0 };
        this.navigationHistory = new NavigationHistory({ owner: this });
        // this.breadcrumbs = [];
        this.canvas = {
            desiredWidth: 100,
            desiredHeight: 100,
            ratio: NaN,
            width: NaN,
            height: NaN,
            ctx: undefined
        };
        this.mouseEventsEnabled = true;
        this.graphAABB = {
            minX: Number.MAX_VALUE,
            maxX: -Number.MAX_VALUE,
            minY: Number.MAX_VALUE,
            maxY: -Number.MAX_VALUE
        };
        EventDispatcher.EventDispatcher.instance.on(['DebugInspectorConnectionPulseChanged'], () => {
            this.repaint();
        }, this);
        EventDispatcher.EventDispatcher.instance.on('ProjectModel.instanceHasChanged', (args) => {
            args.oldInstance && args.oldInstance.off(this);
            if (projectmodel.ProjectModel.instance === undefined)
                return;
            this.bindProjectModel();
            this.navigationHistory.discardInvalidEntries();
        }, this);
        // Listen for component switch requests from ComponentsPanel
        EventDispatcher.EventDispatcher.instance.on('ComponentPanel.SwitchToComponent', (args) => {
            if (args.component) {
                this.switchToComponent(args.component, {
                    pushHistory: args.pushHistory
                });
            }
        }, this);
        // Listen for Logic Builder tab opened - hide canvas
        EventDispatcher.EventDispatcher.instance.on('LogicBuilder.TabOpened', () => {
            console.log('[NodeGraphEditor] Logic Builder tab opened - hiding canvas');
            this.setCanvasVisibility(false);
        }, this);
        // Listen for all Logic Builder tabs closed - show canvas
        EventDispatcher.EventDispatcher.instance.on('LogicBuilder.AllTabsClosed', () => {
            console.log('[NodeGraphEditor] All Logic Builder tabs closed - showing canvas');
            // Track close time to prevent accidental node deletions during focus transition
            this.lastBlocklyTabCloseTime = Date.now();
            this.setCanvasVisibility(true);
        }, this);
        // Listen for Logic Builder tab open requests (for opening tabs from property panel)
        EventDispatcher.EventDispatcher.instance.on('LogicBuilder.OpenTab', (args) => {
            console.log('[NodeGraphEditor] Opening Logic Builder tab for node:', args.nodeId);
            // The CanvasTabs context will handle the actual tab opening
        }, this);
        if (false) // removed by dead control flow
{}
        this.keyboardCommands = [
            {
                handler: () => this.setSpaceKeyDown(true),
                keybinding: KeyCode.KeyCode.Space,
                type: 'down'
            },
            {
                handler: () => this.setSpaceKeyDown(false),
                keybinding: KeyCode.KeyCode.Space,
                type: 'up'
            },
            {
                handler: () => {
                    for (const node of this.selector.nodes) {
                        this.nudgeNode(node, node.x + SnapSpacing, node.y);
                    }
                },
                keybinding: KeyCode.KeyCode.RightArrow,
                type: 'down'
            },
            {
                handler: () => {
                    for (const node of this.selector.nodes) {
                        this.nudgeNode(node, node.x - SnapSpacing, node.y);
                    }
                },
                keybinding: KeyCode.KeyCode.LeftArrow,
                type: 'down'
            },
            {
                handler: () => {
                    for (const node of this.selector.nodes) {
                        this.nudgeNode(node, node.x, node.y - SnapSpacing);
                    }
                },
                keybinding: KeyCode.KeyCode.UpArrow,
                type: 'down'
            },
            {
                handler: () => {
                    for (const node of this.selector.nodes) {
                        this.nudgeNode(node, node.x, node.y + SnapSpacing);
                    }
                },
                keybinding: KeyCode.KeyCode.DownArrow,
                type: 'down'
            }
        ];
        keyboardhandler["default"].instance.registerCommands(this.keyboardCommands);
        // Load icons using webpack require to ensure proper bundling
        this.homeIcon = new Image();
        this.homeIcon.src = (__webpack_require__(33696)/* ["default"] */ .A);
        this.homeIcon.onload = () => this.repaint();
        this.homeIcon.onerror = (e) => console.error('Failed to load home icon:', e);
        this.componentIcon = new Image();
        this.componentIcon.src = (__webpack_require__(1082)/* ["default"] */ .A);
        this.componentIcon.onload = () => this.repaint();
        this.componentIcon.onerror = (e) => console.error('Failed to load component icon:', e);
        this.aiAssistantInnerIcon = new Image();
        this.aiAssistantInnerIcon.src =
            (__webpack_require__(70900)/* ["default"] */ .A);
        this.aiAssistantInnerIcon.onload = () => this.repaint();
        this.aiAssistantInnerIcon.onerror = (e) => console.error('Failed to load AI assistant inner icon:', e);
        this.aiAssistantOuterIcon = new Image();
        this.aiAssistantOuterIcon.src =
            (__webpack_require__(24445)/* ["default"] */ .A);
        this.aiAssistantOuterIcon.onload = () => this.repaint();
        this.aiAssistantOuterIcon.onerror = (e) => console.error('Failed to load AI assistant outer icon:', e);
        this.warningIcon = new Image();
        this.warningIcon.src = (__webpack_require__(81616)/* ["default"] */ .A);
        this.warningIcon.onload = () => this.repaint();
        this.warningIcon.onerror = (e) => console.error('Failed to load warning icon:', e);
        sidebar/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.activeChanged, (activeId) => {
            const isNodePanel = activeId === 'PropertyEditor' || activeId === 'PortEditor';
            if (isNodePanel === false) {
                //deselect nodes when switching away from property editor or port editor
                this.deselect({ disableHidePanels: true });
                this.repaint();
            }
        }, this);
    }
    dispose() {
        var _a;
        AiAssistantModel/* AiAssistantModel */.g.instance.off(this);
        keyboardhandler["default"].instance.deregisterCommands(this.keyboardCommands);
        EventDispatcher.EventDispatcher.instance.off(this);
        nodelibrary/* NodeLibrary */.m.instance.off(this);
        projectmodel.ProjectModel.instance && projectmodel.ProjectModel.instance.off(this);
        warningsmodel/* WarningsModel */.l.instance.off(this);
        (_a = this.inspectorsModel) === null || _a === void 0 ? void 0 : _a.off(this);
        this.commentLayer && this.commentLayer.dispose();
        // Clean up React roots
        if (this.highlightOverlayRoot) {
            this.highlightOverlayRoot.unmount();
            this.highlightOverlayRoot = null;
        }
        if (this.canvasTabsRoot) {
            this.canvasTabsRoot.unmount();
            this.canvasTabsRoot = null;
        }
        sidebar/* SidebarModel */.s.instance.off(this);
        this.reset();
        this._disposed = true;
    }
    setReadOnly(readOnly) {
        var _a;
        this.readOnly = readOnly;
        (_a = this.commentLayer) === null || _a === void 0 ? void 0 : _a.setReadOnly(readOnly);
        // Update banner visibility when read-only status changes
        if (this.editorBannerRoot) {
            this.renderEditorBanner();
        }
    }
    reset() {
        this.clearSelection({ disableHidePanels: true });
        this.highlighted && ViewerConnection/* ViewerConnection */.t.instance.sendNodeHighlighted(this.highlighted.model, false);
        this.highlighted = undefined; // This is not cleared in clearSelection
        // Delete existing nodes and connections
        while (this.roots.length > 0) {
            const root = this.roots[0];
            this.removeRoot(root);
            root.destruct();
        }
        // Remove all connections
        while (this.connections.length > 0) {
            const con = this.connections[0];
            con.disconnect(con);
        }
        // Remove all debug inspectors
        while (this.inspectors.length > 0) {
            this.removeInspector(this.inspectors[0]);
        }
        if (this.model) {
            // Unbind from current model
            this.model.off(this);
            this.model.commentsModel.off(this);
            for (const i in this.model.roots) {
                this.model.roots[i].forEach((model) => {
                    this.unbindNodeModel(model);
                });
            }
        }
    }
    bindModel(model) {
        const _this = this;
        this.reset();
        this.model = model;
        this.stateText = this.readOnly ? 'Read Only' : null;
        this.updateTitle();
        if (!model)
            return;
        // Create views for the content of the model
        this.roots = [];
        for (const i in model.roots) {
            const node = NodeGraphEditorNode.createFromModel(model.roots[i], this);
            model.roots[i].forEach(function (model) {
                _this.bindNodeModel(model);
            });
            this.roots.push(node);
        }
        this.connections = [];
        for (const i in model.connections) {
            NodeGraphEditorConnection.createFromModel(model.connections[i], this);
        }
        // Listen to when a node is attached in the model and
        // change the view accordingly
        model.on('nodeAdded', function (args) {
            const node = NodeGraphEditorNode.createFromModel(args.model, _this);
            _this.bindNodeModel(args.model);
            if (args.model.parent) {
                const parent = _this.findNodeWithId(args.model.parent.id);
                const index = args.model.parent.children.indexOf(args.model);
                parent.insertChild(node, index);
            }
            else {
                _this.roots.push(node);
            }
            if (!(args === null || args === void 0 ? void 0 : args.disableSelect)) {
                _this.clearSelection();
                //let the event loop do one tick before selecting, there might be other listeners that want to modify some paramters (like the router adapter)
                setTimeout(() => {
                    if (_this.selector.active) {
                        return;
                    }
                    _this.selectNode(node);
                    _this.relayout();
                    _this.repaint();
                }, 1);
            }
            else {
                _this.relayout();
                _this.repaint();
            }
        }, this);
        model.commentsModel.on('commentAdded', ({ comment, args }) => {
            this.clearSelection();
            if (args && args.focusComment) {
                this.commentLayer && this.commentLayer.focusComment(comment.id);
            }
        }, this);
        model.on('nodeRemoved', (args) => {
            const node = this.findNodeWithId(args.model.id);
            if (!node)
                return; // The node was not found
            // If the highlighted node is delete empty the reference
            if (this.highlighted === node) {
                this.highlighted && ViewerConnection/* ViewerConnection */.t.instance.sendNodeHighlighted(this.highlighted.model, false);
                this.highlighted = undefined;
            }
            //de-select in case it's active
            this.selector.unselectNode(node);
            const inspector = this.getInspectorForNode(node);
            inspector && inspector.remove();
            this.unbindNodeModel(args.model);
            if (node.parent) {
                node.parent.removeChild(node);
                node.destruct();
            }
            else {
                this.removeRoot(node);
                node.destruct();
            }
            this.clearSelection();
            this.relayout();
            this.repaint();
            if (!this.selector.active) {
                this.updateNodeToolbar();
            }
        }, this);
        model.on('nodeAttached', function (args) {
            const node = _this.findNodeWithId(args.model.id);
            const parent = _this.findNodeWithId(args.parent.id);
            parent.insertChild(node, args.index);
            _this.removeRoot(node);
            _this.relayout();
            _this.repaint();
        }, this);
        // Listen to when a node is detached in the model
        model.on('nodeDetached', function (args) {
            const node = _this.findNodeWithId(args.model.id);
            node && node.detach();
            _this.roots.push(node);
            _this.relayout();
            _this.repaint();
        }, this);
        // Connections
        model.on('connectionAdded', function (args) {
            NodeGraphEditorConnection.createFromModel(args.model, _this, _this.canvas.ctx);
            _this.relayout();
            _this.repaint();
        }, this);
        model.on('connectionRemoved', function (args) {
            const con = _this.findConnectionWithModel(args.model);
            con && con.disconnect();
            const inspector = _this.getInspectorForConnection(con);
            inspector && inspector.remove();
            _this.relayout();
            _this.repaint();
        }, this);
        model.on('connectionPortChanged', function (args) {
            const con = _this.findConnectionWithModel(args.model);
            con.fromProperty = args.model.fromProperty;
            con.toProperty = args.model.toProperty;
            con.resolvePorts();
            _this.relayout();
            _this.repaint();
        }, this);
        this.layout();
        this.paint();
        // Bind connection inspector and models after the first paint so they know what x and y position to attach to
        this.bindDebugInspector();
    }
    bindNodeModel(model) {
        const _this = this;
        model.on(['labelChanged', 'portRearranged', 'typeRenamed'], function () {
            _this.relayout();
            _this.repaint();
        }, this);
    }
    unbindNodeModel(model) {
        model.off(this);
    }
    bindDebugInspector() {
        const _this = this;
        // Add inspector views
        function createConnectionInspector(model) {
            const connection = _this.findConnectionWithKey(model.connectionKey);
            if (connection && connection.isHealthy()) {
                // Is this a connection in this graph
                return new (nodegrapheditor_debuginspectors_default()).ConnectionInspector({
                    model,
                    connection,
                    owner: _this,
                    parentElement: _this.domElementContainer
                });
            }
        }
        function createNodeInspector(model) {
            const node = _this.findNodeWithId(model.nodeId);
            if (node) {
                return new (nodegrapheditor_debuginspectors_default()).NodeInspector({
                    model,
                    node,
                    owner: _this,
                    parentElement: _this.domElementContainer
                });
            }
        }
        function createInspector(model) {
            if (model.type === 'connection') {
                return createConnectionInspector(model);
            }
            else {
                return createNodeInspector(model);
            }
        }
        const inspectorsModel = debuginspector_default().InspectorsModel.instanceForProject(projectmodel.ProjectModel.instance);
        this.inspectorsModel = inspectorsModel;
        inspectorsModel.getInspectors().forEach((model) => {
            const inspector = createInspector(model);
            if (inspector) {
                this.inspectors.push(inspector);
                inspector.render();
            }
        });
        inspectorsModel.off(this);
        inspectorsModel.on('inspectorAdded', (args) => {
            const inspector = createInspector(args.model);
            if (inspector) {
                this.inspectors.push(inspector);
                inspector.render();
            }
        }, this);
        inspectorsModel.on('inspectorRemoved', (args) => {
            const inspector = this.findInspectorWithModel(args.model);
            this.removeInspector(inspector);
        }, this);
    }
    bindProjectModel() {
        const _this = this;
        projectmodel.ProjectModel.instance.on('componentRemoved', (e) => {
            _this.navigationHistory.onComponentRemoved(e.model);
        }, this);
        projectmodel.ProjectModel.instance.on('componentRenamed', (e) => {
            _this.updateTitle();
        }, this);
    }
    //A request animation frame timer that renders the entire node graph while there are animations to play
    //TODO: only render when an animated node is visible
    startNodeAnimations() {
        if (this.isPlayingNodeAnimations) {
            return;
        }
        this.isPlayingNodeAnimations = true;
        const animate = () => {
            this.paint();
            if (this.isPlayingNodeAnimations) {
                requestAnimationFrame(animate);
            }
        };
        requestAnimationFrame(animate);
    }
    stopNodeAnimations() {
        this.isPlayingNodeAnimations = false;
    }
    render() {
        const _this = this;
        // Expose editor instance to window for console debugging (dev only)
        // Used by test utilities: window.testHighlightManager.testBasicHighlight()
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        window.__nodeGraphEditor = this;
        this.el = this.bindView($(NodeGraphEditorTemplate), this);
        this.domElementContainer = this.el.find('#nodegraph-dom-layer').get(0);
        this.commentLayer = new CommentLayer(this);
        this.commentLayer.setReadOnly(this.readOnly);
        // Bind canvas
        this.bindCanvas();
        // Bind model
        this.bindModel(this.model);
        this.bindProjectModel();
        //bind ai assistant
        AiAssistantModel/* AiAssistantModel */.g.instance.on(AiAssistantModel/* AiAssistantEvent */.z.ProcessingUpdated, () => {
            AiAssistantModel/* AiAssistantModel */.g.instance.getProcessingNodeIds().length
                ? this.startNodeAnimations()
                : this.stopNodeAnimations();
        }, this);
        // Rerender if warnings model changed
        warningsmodel/* WarningsModel */.l.instance.on('warningsChanged', function () {
            _this.repaint();
        }, this);
        // When the node library is changed we may need to rerender
        nodelibrary/* NodeLibrary */.m.instance.on(['moduleRegistered', 'moduleUnregistered', 'typeAdded', 'typeRemoved', 'libraryUpdated'], function () {
            // We must re-resolve ports as they could have changed
            external_underscore_default().each(_this.connections, function (c) {
                c.resolvePorts();
            });
            // Relayout and paint
            _this.relayout();
            _this.repaint();
        }, this);
        // May change warning status
        EventDispatcher.EventDispatcher.instance.on(['Model.portAdded', 'Model.portRemoved'], function () {
            _this.relayout();
            _this.repaint();
        }, this);
        // The module for the graph we are editing has been unregistered
        nodelibrary/* NodeLibrary */.m.instance.on('moduleUnregistered', function (args) {
            if (_this.model && args.model === _this.model.owner.owner) {
                _this.switchToComponent();
            }
        }, this);
        // The component we are editing has been removed
        nodelibrary/* NodeLibrary */.m.instance.on('typeRemoved', function (args) {
            if (_this.model && args.model === _this.model.owner) {
                _this.switchToComponent();
            }
        }, this);
        //the comment layer is using react-dnd which caches the parent position the first time a comment is rendered.
        //it's crucial that the parent position is correct, so delay the rendering a tick so all the DOM elements are in the right place
        setTimeout(() => {
            this.commentLayer.renderTo(this.el.find('#comment-layer-bg').get(0), this.el.find('#comment-layer-fg').get(0));
        }, 1);
        // Render the highlight overlay
        setTimeout(() => {
            this.renderHighlightOverlay();
        }, 1);
        // Render the canvas tabs
        setTimeout(() => {
            this.renderCanvasTabs();
        }, 1);
        // Render the editor banner (for read-only mode)
        setTimeout(() => {
            this.renderEditorBanner();
        }, 1);
        this.relayout();
        this.repaint();
        return this.el;
    }
    /**
     * Render the CanvasTabs React component
     */
    renderCanvasTabs() {
        const tabsElement = this.el.find('#canvas-tabs-root').get(0);
        if (!tabsElement) {
            console.warn('Canvas tabs root not found in DOM');
            return;
        }
        // Create React root if it doesn't exist
        if (!this.canvasTabsRoot) {
            this.canvasTabsRoot = (0,client.createRoot)(tabsElement);
        }
        // Render the tabs with provider
        this.canvasTabsRoot.render(external_react_default().createElement(CanvasTabsProvider, null, external_react_default().createElement(CanvasTabs, {
            onWorkspaceChange: this.handleBlocklyWorkspaceChange.bind(this)
        })));
    }
    /**
     * Handle workspace changes from Blockly editor
     */
    handleBlocklyWorkspaceChange(nodeId, workspace, code) {
        console.log(`[NodeGraphEditor] Workspace changed for node ${nodeId}`);
        const node = this.findNodeWithId(nodeId);
        if (!node) {
            console.warn(`[NodeGraphEditor] Node ${nodeId} not found`);
            return;
        }
        // Save workspace JSON to node model
        node.model.setParameter('workspace', workspace);
        // Save generated JavaScript code to node model
        // This triggers the runtime's parameterUpdated listener which calls updatePorts()
        node.model.setParameter('generatedCode', code);
        console.log(`[NodeGraphEditor] Saved workspace and generated code for node ${nodeId}`);
    }
    /**
     * Render the EditorBanner React component (for read-only mode)
     */
    renderEditorBanner() {
        const bannerElement = this.el.find('#editor-banner-root').get(0);
        if (!bannerElement) {
            console.warn('Editor banner root not found in DOM');
            return;
        }
        // Create React root if it doesn't exist
        if (!this.editorBannerRoot) {
            this.editorBannerRoot = (0,client.createRoot)(bannerElement);
        }
        // Only show banner if in read-only mode
        if (this.readOnly) {
            this.editorBannerRoot.render(external_react_default().createElement(EditorBanner, {
                onDismiss: this.handleDismissBanner.bind(this)
            }));
        }
        else {
            // Clear banner if not in read-only mode
            this.editorBannerRoot.render(null);
        }
    }
    /**
     * Handle banner dismiss
     */
    handleDismissBanner() {
        console.log('[NodeGraphEditor] Banner dismissed');
        // Banner handles its own visibility via state
    }
    /**
     * Render the HighlightOverlay React component
     */
    renderHighlightOverlay() {
        const overlayElement = this.el.find('#highlight-overlay-layer').get(0);
        if (!overlayElement) {
            console.warn('Highlight overlay layer not found in DOM');
            return;
        }
        // Create React root if it doesn't exist
        if (!this.highlightOverlayRoot) {
            this.highlightOverlayRoot = (0,client.createRoot)(overlayElement);
        }
        // Get current viewport state
        const panAndScale = this.getPanAndScale();
        const viewport = {
            x: panAndScale.x,
            y: panAndScale.y,
            zoom: panAndScale.scale
        };
        // Render the overlay
        this.highlightOverlayRoot.render(external_react_default().createElement(HighlightOverlay, {
            viewport,
            getNodeBounds: this.getNodeBounds
        }));
    }
    /**
     * Update the highlight overlay with new viewport state
     * Called whenever pan/zoom changes
     */
    updateHighlightOverlay() {
        if (this.highlightOverlayRoot) {
            this.renderHighlightOverlay();
        }
    }
    /**
     * Set canvas visibility (hide when Logic Builder is open, show when closed)
     */
    setCanvasVisibility(visible) {
        const canvasElement = this.el.find('#nodegraphcanvas');
        const commentLayerBg = this.el.find('#comment-layer-bg');
        const commentLayerFg = this.el.find('#comment-layer-fg');
        const highlightOverlay = this.el.find('#highlight-overlay-layer');
        const componentTrail = this.el.find('.nodegraph-component-trail-root');
        if (visible) {
            // Show canvas and related elements
            canvasElement.css('display', 'block');
            commentLayerBg.css('display', 'block');
            commentLayerFg.css('display', 'block');
            highlightOverlay.css('display', 'block');
            componentTrail.css('display', 'flex');
            this.domElementContainer.style.display = '';
        }
        else {
            // Hide canvas and related elements
            canvasElement.css('display', 'none');
            commentLayerBg.css('display', 'none');
            commentLayerFg.css('display', 'none');
            highlightOverlay.css('display', 'none');
            componentTrail.css('display', 'none');
            this.domElementContainer.style.display = 'none';
        }
    }
    // This is called by the parent view (frames view) when the size and position
    // changes
    resize(layout) {
        this.currentLayout = layout;
        //make sure the canvas is bound and rendering happens at the same frame, otherwise it'll flicker
        this.bindCanvas();
        this.layout();
        this.paint();
        if (this.model && this.canvas.width && this.canvas.height) {
            let panAndScale = this.getPanAndScale();
            panAndScale = this.clampPanAndScale(panAndScale);
            this.setPanAndScale(panAndScale);
        }
    }
    // --------------------------------- Cut n paste ------------------------------------------
    getSelectedNodes() {
        return [...this.selector.nodes];
    }
    copySelected() {
        const nodes = this.selector.nodes;
        // Make sure all nodes can be copied
        const _invalid = nodes.filter((n) => !n.model.canBeCopied());
        if (_invalid.length !== 0) {
            ToastLayer.ToastLayer.showError('One or more of these nodes cannot be copied.');
            return;
        }
        // Update coordinates so they are pasted correctly
        const nodeModels = nodes.map((n) => {
            n.x = n.global.x;
            n.y = n.global.y;
            n.updateModel();
            return n.model;
        });
        const nodeset = this.model.getNodeSetWithNodes(nodeModels);
        nodeset.comments = this.commentLayer.getSelectedComments();
        if (nodes.length > 0 || nodeset.comments.length > 0) {
            this.clipboard = nodeset.clone();
            this.clipboard.strip();
            external_electron_.clipboard.writeText(JSON.stringify(this.clipboard.toJSON()));
        }
        else {
            this.clipboard = undefined;
        }
        ToastLayer.ToastLayer.showInteraction('Copied');
        return nodeset;
    }
    delete() {
        if (this.readOnly) {
            return false;
        }
        // Guard against accidental deletions during Blockly tab close transition
        // This prevents nodes from being deleted if a Blockly tab was just closed
        const timeSinceBlocklyClose = Date.now() - this.lastBlocklyTabCloseTime;
        if (timeSinceBlocklyClose < 200) {
            console.warn('[NodeGraphEditor] Ignoring delete during Blockly tab close transition');
            return false;
        }
        const nodes = [...this.selector.nodes];
        // Make sure all nodes can be deleted
        const _invalid = nodes.filter((n) => !n.model.canBeDeleted());
        if (_invalid.length !== 0) {
            ToastLayer.ToastLayer.showError('One or more of these nodes cannot be deleted.');
            return;
        }
        const undo = new undo_queue_model/* UndoActionGroup */.C({ label: 'delete nodes' });
        if (this.commentLayer && this.commentLayer.hasSelection()) {
            this.commentLayer.deleteSelection({ undo: undo });
        }
        const models = external_underscore_default().pluck(nodes, 'model');
        this.model.removeNodeSet(this.model.getNodeSetWithNodes(models), {
            undo: undo
        });
        undo_queue_model/* UndoQueue */.g.instance.push(undo);
    }
    copy() {
        this.copySelected();
    }
    cut() {
        if (this.readOnly) {
            return false;
        }
        const nodeset = this.copySelected();
        if (nodeset === undefined)
            return;
        const undoCut = new undo_queue_model/* UndoActionGroup */.C({ label: 'cut' });
        this.model.removeNodeSet(nodeset, { undo: undoCut });
        undo_queue_model/* UndoQueue */.g.instance.push(undoCut);
        ToastLayer.ToastLayer.showInteraction('Cut');
    }
    getNodeSetFromClipboard() {
        try {
            const text = external_electron_.clipboard.readText();
            if (!text)
                return;
            var json = JSON.parse(text);
        }
        catch (e) {
            // Failed to parse clipboard text as json
            return;
        }
        return nodegraphmodel/* NodeGraphNodeSet */.bn.fromJSON(json);
    }
    insertNodeSet({ nodeset, x, y, toastMessage }) {
        if (this.readOnly) {
            return null;
        }
        const ns = nodeset.clone();
        // Check create status for all node types
        const component = this.model.owner;
        const errors = [];
        const _this = this;
        function checkCreateStatus(nodes) {
            for (const node of nodes) {
                if (node.type instanceof componentmodel/* ComponentModel */.j) {
                    const status = component.getCreateStatus({
                        type: node.type
                    });
                    if (!status.creatable) {
                        errors.push(status.message);
                    }
                }
                else if (node.type instanceof BasicNodeType/* BasicNodeType */.F) {
                    if (node.type.runtimeTypes && !node.type.runtimeTypes.includes(_this.runtimeType)) {
                        errors.push('One or more of these nodes cannot be created here.');
                    }
                }
                checkCreateStatus(node.children);
            }
        }
        checkCreateStatus(ns.nodes);
        if (errors.length > 0) {
            // There were create errors
            const msg = {};
            for (let j = 0; j < errors.length; j++) {
                msg[errors[j]] = true;
            }
            let _msg = '';
            for (const i in msg) {
                _msg += i;
            }
            ToastLayer.ToastLayer.showError(_msg);
            return;
        }
        ns.setOriginPosition({ x, y });
        const undoNodeSet = new undo_queue_model/* UndoActionGroup */.C({ label: 'paste' });
        this.model.insertNodeSet(ns, { undo: undoNodeSet });
        undoNodeSet.push({
            undo: () => {
                this.clearSelection();
                this.commentLayer.clearSelection();
            }
        });
        undo_queue_model/* UndoQueue */.g.instance.push(undoNodeSet);
        // Select all nodes
        const multiselected = [];
        for (const i in ns.nodes) {
            const model = ns.nodes[i];
            model.forEach((m) => {
                multiselected.push(this.findNodeWithId(m.id));
            });
        }
        this.selector.select(multiselected);
        //and comments
        if (ns.comments) {
            this.commentLayer.setSelectedCommentIds(ns.comments.map((c) => c.id));
        }
        this.layout();
        this.updateNodeToolbar();
        this.repaint();
        ToastLayer.ToastLayer.showInteraction(toastMessage);
        return ns;
    }
    paste() {
        const ns = this.getNodeSetFromClipboard() || this.clipboard;
        if (!ns)
            return;
        this.insertNodeSet({
            nodeset: ns,
            x: this.latestMousePos.x,
            y: this.latestMousePos.y,
            toastMessage: 'Paste'
        });
    }
    // --------------------------------- Undo n redo ------------------------------------------
    undo() {
        if (this.readOnly) {
            return false;
        }
        const action = undo_queue_model/* UndoQueue */.g.instance.undo();
        if (action) {
            ToastLayer.ToastLayer.showInteraction('Undo ' + action.label);
        }
        else {
            ToastLayer.ToastLayer.showInteraction('Nothing to undo');
        }
    }
    redo() {
        if (this.readOnly) {
            return false;
        }
        const action = undo_queue_model/* UndoQueue */.g.instance.redo();
        if (action) {
            ToastLayer.ToastLayer.showInteraction('Redo ' + action.label);
        }
        else {
            ToastLayer.ToastLayer.showInteraction('Nothing to redo');
        }
    }
    getDevicePixelRatio(ctx) {
        const dpr = window.devicePixelRatio || 1;
        const bsr = ctx.webkitBackingStorePixelRatio ||
            ctx.mozBackingStorePixelRatio ||
            ctx.msBackingStorePixelRatio ||
            ctx.oBackingStorePixelRatio ||
            ctx.backingStorePixelRatio ||
            1;
        const r = dpr / bsr;
        return r;
    }
    bindCanvas() {
        const _this = this;
        const canvas = this.$('#nodegraphcanvas')[0];
        const ctx = (this.canvas.ctx = canvas.getContext('2d', { alpha: true }));
        // Support retina display
        this.canvas.ratio = this.getDevicePixelRatio(ctx);
        const width = $(canvas).width();
        const height = $(canvas).height();
        canvas.width = width * this.canvas.ratio;
        canvas.height = height * this.canvas.ratio;
        this.canvas.width = canvas.width;
        this.canvas.height = canvas.height;
        // Bind mouse events
        const topLeft = function (canvas) {
            const { x, y } = canvas.getBoundingClientRect();
            return [x, y];
        };
        this.topLeftCanvasPos = topLeft(canvas);
        const events = {
            mousedown: 'down',
            mouseup: 'up',
            mousemove: 'move',
            mouseout: 'out',
            mouseover: 'over'
        };
        for (const i in events) {
            const type = events[i];
            $(canvas)
                .off(i)
                .on(i, (evt) => {
                // @ts-expect-error
                evt.spaceKey = _this.spaceKeyDown; // This is set by the KeyboardHandler
                this.mouse(type, {
                    x: evt.pageX - this.topLeftCanvasPos[0],
                    y: evt.pageY - this.topLeftCanvasPos[1],
                    pageX: evt.pageX,
                    pageY: evt.pageY
                }, evt);
            });
            $(canvas).on('mouseover', (evt) => {
                this.topLeftCanvasPos = topLeft(canvas);
            });
        }
        this.mouseWheelDetector = new (MouseWheelModeDetector_default())();
        $(canvas)
            .off('wheel')
            .on('wheel', (e) => {
            this.handleMouseWheelEvent(e.originalEvent);
        });
    }
    setSpaceKeyDown(pressed) {
        if (this.spaceKeyDown === pressed) {
            return;
        }
        this.spaceKeyDown = pressed;
        this.canvas.ctx.canvas.style.cursor = pressed ? 'grab' : 'inherit';
    }
    handleMouseWheelEvent(event, args) {
        event.preventDefault();
        const pointerDeviceType = this.mouseWheelDetector.changeMode(event);
        if (pointerDeviceType === 'mouse' || event.ctrlKey || event.metaKey) {
            const zoomFactor = pointerDeviceType === 'mouse' ? 1 / 100 : 1 / 10;
            //this function can be called by the comment layer (when a mousewheel event is fired on a comment DOM node)
            //this will send it's own offsets that should override the event offset
            const offsetX = args && args.hasOwnProperty('offsetX') ? args.offsetX : event.offsetX;
            const offsetY = args && args.hasOwnProperty('offsetY') ? args.offsetY : event.offsetY;
            this.updateZoomLevel(offsetX, offsetY, -event.deltaY * zoomFactor);
        }
        else {
            // Move all roots and relayout
            const panAndScale = this.getPanAndScale();
            const scale = panAndScale.scale;
            this.moveRoots(-event.deltaX / scale, -event.deltaY / scale);
            this.relayout();
            this.repaint();
        }
    }
    updateZoomLevel(x, y, deltaZ) {
        let panAndScale = this.getPanAndScale();
        const oldScale = panAndScale.scale;
        //Scale by multiplying with a factor to make zooming linear
        // (e.g. 0.5->0.6 is 20% increase, 1.0 -> 1.1 is only 10%)
        let scale = oldScale * Math.pow(0.95, -deltaZ);
        //Restrict scaling to max 1, and minimum so you can see the entire component plus some padding OR 0.33 (to always allow some zoom)
        const graphAABB = this.graphAABB;
        const canvasWidth = this.canvas.width / this.canvas.ratio;
        const canvasHeight = this.canvas.height / this.canvas.ratio;
        const ScalePadding = 200;
        const minXScale = canvasWidth / (graphAABB.maxX - graphAABB.minX + 2 * ScalePadding);
        const minYScale = canvasHeight / (graphAABB.maxY - graphAABB.minY + 2 * ScalePadding);
        const minScale = Math.min(minXScale, minYScale, 0.33);
        scale = Math.max(minScale, Math.min(1, scale));
        //apply scaling
        panAndScale = {
            scale: scale,
            x: panAndScale.x + (x / scale - x / oldScale),
            y: panAndScale.y + (y / scale - y / oldScale)
        };
        panAndScale = this.clampPanAndScale(panAndScale);
        this.setPanAndScale(panAndScale);
        this.updateHighlightOverlay();
        this.relayout();
        this.repaint();
    }
    forEachNode(callback) {
        for (const i in this.roots) {
            if (this.roots[i].forEach(callback))
                return;
        }
    }
    addNodeToSelection(node) {
        if (this.readOnly) {
            return;
        }
        const currentMultiselect = [...this.selector.nodes];
        this.deselect();
        const index = currentMultiselect.indexOf(node);
        if (index === -1) {
            currentMultiselect.push(node);
        }
        else {
            currentMultiselect.splice(index, 1);
        }
        this.selector.select(currentMultiselect);
        this.repaint();
    }
    startDraggingNode(node) {
        var _a;
        if (this.readOnly) {
            return;
        }
        if (!this.draggingNodes) {
            // Collect all highlighted/selected nodes that are roots in the selection
            let selected = [];
            if (this.selector.isActive(node)) {
                selected = [...this.selector.nodes];
            }
            else {
                this.selector.unselect();
                (_a = this.commentLayer) === null || _a === void 0 ? void 0 : _a.clearSelection();
                selected = [node];
            }
            const nodes = [];
            //add the roots
            for (const i in selected) {
                const n = selected[i];
                if (!n.parent || selected.indexOf(n.parent) === -1) {
                    nodes.push(n);
                }
            }
            this.startDraggingNodes(nodes);
        }
    }
    setDOMLayerVisible(visible) {
        this.domElementContainer.style.display = visible ? '' : 'none';
        if (visible) {
            for (const inspector of this.inspectors) {
                inspector.render();
            }
        }
    }
    startDraggingNodes(nodes) {
        this.draggingNodes = nodes || [];
        this.setDOMLayerVisible(false);
        this.lastDraggingMousePos = this.startDraggingMousePos = this.latestMousePos;
        this.dragNodesUndoGroup = new undo_queue_model/* UndoActionGroup */.C({
            label: 'drag nodes'
        });
    }
    startDraggingConnection(fromNode) {
        if (this.readOnly) {
            return false;
        }
        // Clear multiselect
        this.selector.unselect();
        this.setDOMLayerVisible(false);
        this.highlighted && ViewerConnection/* ViewerConnection */.t.instance.sendNodeHighlighted(this.highlighted.model, false);
        this.highlighted = undefined; // Clear highlighted
        this.draggingConnection = { fromNode: fromNode };
        this.draggingConnection.mouseTarget = {
            global: {
                x: this.latestMousePos.x,
                y: this.latestMousePos.y
            }
        };
    }
    removeRoot(node) {
        const idx = this.roots.indexOf(node);
        idx !== -1 && this.roots.splice(idx, 1);
    }
    moveRoots(dx, dy) {
        let panAndScale = this.getPanAndScale();
        panAndScale.x += dx;
        panAndScale.y += dy;
        panAndScale = this.clampPanAndScale(panAndScale);
        this.setPanAndScale(panAndScale);
        this.updateHighlightOverlay();
        /* for(var i in this.roots) {
          this.roots[i].x += dx;
          this.roots[i].y += dy;
    
          this.roots[i].updateModel();
        }*/
    }
    createNewNode(type, pos, options = {}) {
        const node = nodegraphmodel/* NodeGraphNode */.dF.fromJSON({
            type: type.name,
            x: pos.x,
            y: pos.y,
            id: (0,utils.guid)(),
            ...options
        });
        if (this.highlighted) {
            this.highlighted.model.addChild(node, { undo: true, label: 'create' });
        }
        else {
            this.model.addRoot(node, { undo: true, label: 'create' });
        }
        this.clearSelection();
        this.relayout();
        this.repaint();
    }
    deselect(args) {
        var _a, _b;
        (_a = this.commentLayer) === null || _a === void 0 ? void 0 : _a.clearMultiselection();
        this.selector.unselect();
        if (!(args === null || args === void 0 ? void 0 : args.disableHidePanels)) {
            (_b = sidebar/* SidebarModel */.s.instance) === null || _b === void 0 ? void 0 : _b.hidePanels();
        }
        // Broadcast a deselect event
        this.notifyListeners('deselect');
    }
    clearSelection(args) {
        this.deselect(args);
        // Clear dragging connection
        if (this.draggingConnection) {
            this.closeConnectionPanels();
            this.draggingConnection.fromNode.borderHighlighted = false;
            this.draggingConnection.toNode.borderHighlighted = false;
            this.draggingConnection = undefined;
        }
        // Clear any connections that are being deleted
        this.setHighlightedConnection(undefined);
        this.deleteModeConnection = undefined;
        // Close open popup
        popuplayer_default().instance.hideAllModalsAndPopups();
        popuplayer_default().instance.hideTooltip();
    }
    updateTitle() {
        const rootElem = this.el[0].querySelector('.nodegraph-component-trail-root');
        // Create root only once, reuse for subsequent renders
        if (!this.titleRoot) {
            this.titleRoot = (0,client.createRoot)(rootElem);
        }
        if (this.activeComponent) {
            const fullName = this.activeComponent.fullName;
            const nameParts = fullName.split('/');
            const firstItem = nameParts.shift();
            const componentTrail = [];
            for (let i = 0; i < nameParts.length; i++) {
                let part = '';
                for (let j = 0; j <= i; j++) {
                    part += '/' + nameParts[j];
                }
                componentTrail.push({
                    name: nameParts[i],
                    fullName: part,
                    stateText: this.stateText,
                    // TODO: this returns undefined if the component is a folder,
                    // but if a folder and a component has the same name the result
                    // of this check will be wrong. i think this is a rare edge case though
                    component: projectmodel.ProjectModel.instance.getComponentWithName(part),
                    isCurrent: i === nameParts.length - 1,
                    isFolderComponent: nameParts.length > 1 && !fullName.endsWith(part)
                });
            }
            const componentName = nameParts.pop();
            this.componentName = componentName;
            if (nameParts.length) {
                this.componentFolder = nameParts.join(' / ') + ' /';
            }
            else {
                this.componentFolder = '';
            }
            const props = {
                componentTrail,
                onSwitchToComponent: this.switchToComponent.bind(this),
                onHistoryForward: this.navigationHistory.goForward.bind(this.navigationHistory),
                onHistoryBack: this.navigationHistory.goBack.bind(this.navigationHistory),
                canNavigateBack: this.navigationHistory.canNavigateBack,
                canNavigateForward: this.navigationHistory.canNavigateForward
            };
            this.titleRoot.render(external_react_default().createElement(NodeGraphComponentTrail, props));
        }
        else {
            this.titleRoot.render(null);
        }
    }
    switchToComponent(component, args) {
        var _a, _b;
        if (!component) {
            (_a = this.activeComponent) === null || _a === void 0 ? void 0 : _a.off(this);
            this.activeComponent = undefined;
            this.runtimeType = undefined;
            this.updateTitle();
            this.bindModel();
            this.relayout();
            this.repaint();
            this.commentLayer.setComponentModel(undefined);
            // Clear all highlights when closing/switching away from component
            HighlightManager/* HighlightManager */.Ym.instance.clearAll();
            return;
        }
        // Update the runtime type, this is required for the node picker
        this.runtimeType = (0,NodeGraph/* getComponentModelRuntimeType */.$j)(component);
        if (this.activeComponent !== component) {
            (_b = this.activeComponent) === null || _b === void 0 ? void 0 : _b.off(this);
            // Clear highlights when switching to a different component
            HighlightManager/* HighlightManager */.Ym.instance.clearAll();
            this.activeComponent = component;
            if (args === null || args === void 0 ? void 0 : args.replaceHistory) {
                this.navigationHistory.reset();
                this.navigationHistory.push(component);
            }
            else if (args === null || args === void 0 ? void 0 : args.pushHistory) {
                this.navigationHistory.push(component);
            }
            titlebar/* TitleBar */.c.instance.getWarningsAmount(component);
            this.bindModel(component.graph);
            this.commentLayer.setComponentModel(component);
            //If the components graph model is changed, rebind the new model
            //Can be triggered when a user reset a component in the git panel
            component.on('graphModelBound', () => {
                this.bindModel(component.graph);
            }, this);
            // Notify HighlightManager of component change for cross-component path highlighting
            HighlightManager/* HighlightManager */.Ym.instance.setCurrentComponent(component.fullName);
            EventDispatcher.EventDispatcher.instance.emit('activeComponentChanged', { component });
        }
        this.notifyListeners('activeComponentChanged', {
            model: component,
            args: args
        });
        // Should we select a node
        this.panAndScale = undefined;
        if (args === null || args === void 0 ? void 0 : args.node) {
            const node = this.findNodeWithId(args.node.id);
            if (node) {
                this.clearSelection();
                this.selectNode(node);
                this.relayout(); // Need to relayout twice the first time a new model is set...
                this.layout();
                const panAndScale = this.getPanAndScale();
                this.moveRoots(-panAndScale.x + this.currentLayout.width / 2 / panAndScale.scale - node.global.x - node.nodeSize.width / 2, -panAndScale.y + this.currentLayout.height / 2 / panAndScale.scale - node.global.y - node.nodeSize.height / 2);
            }
        }
        this.relayout(); // Need to relayout twice the first time a new model is set...
        this.layout();
        this.repaint();
    }
    getActiveComponent() {
        return this.activeComponent;
    }
    selectNode(node) {
        var _a;
        if (this.readOnly) {
            this.notifyListeners('readOnlyNodeClicked', node.model);
            return;
        }
        // Always select the node in the selector if not already selected
        if (!node.selected) {
            this.clearSelection();
            (_a = this.commentLayer) === null || _a === void 0 ? void 0 : _a.clearSelection();
            node.selected = true;
            this.selector.select([node]);
            this.repaint();
        }
        // Always switch to the node in the sidebar (fixes property panel stuck issue)
        sidebar/* SidebarModel */.s.instance.switchToNode(node.model);
        // Handle double-click navigation
        if (this.leftButtonIsDoubleClicked) {
            if (node.model.type instanceof componentmodel/* ComponentModel */.j) {
                this.switchToComponent(node.model.type, { pushHistory: true });
            }
            else {
                const componentPorts = node.model
                    .getPorts()
                    .filter((p) => p.plug === 'input' && nodelibrary/* NodeLibrary */.m.nameForPortType(p.type) === 'component');
                //check if there's a type with the component name, if so switch to it
                const component = componentPorts.map((port) => node.model.parameters[port.name]).filter((c) => c !== undefined);
                const type = component.length && nodelibrary/* NodeLibrary */.m.instance.getNodeTypeWithName(component[0]);
                if (type) {
                    // @ts-expect-error TODO: this is wrong!
                    this.switchToComponent(type, { pushHistory: true });
                }
                else {
                    //there was no type that matched, so forward the double click event to the sidebar
                    sidebar/* SidebarModel */.s.instance.invokeActive('doubleClick', node);
                }
            }
        }
    }
    setHighlightedNode(node, atPosition) {
        // Node inspector
        if (this.model && !this.readOnly) {
            // Don't show node inspection in read only mode
            clearTimeout(this.showInspectorTimeout);
            if (node) {
                // We have a new node selected, show inspector
                if (!this.getInspectorForNode(node)) {
                    this.showInspectorTimeout = setTimeout(() => {
                        this.hideInspectors();
                        //and add new inspector
                        debuginspector_default().InspectorsModel.instanceForProject(projectmodel.ProjectModel.instance).addInspectorForNode({
                            node: node.model,
                            position: atPosition
                        });
                    }, 200);
                }
            }
        }
        this.highlighted = node;
    }
    setHighlightedConnection(c, atPosition) {
        // Don't show connection inspection in read only mode
        if (this.readOnly) {
            return false;
        }
        // Connection inspector
        clearTimeout(this.showInspectorTimeout);
        if (c) {
            // We have a new connection selected, show inspector
            if (c.isHealthy() && !this.getInspectorForConnection(c)) {
                this.showInspectorTimeout = setTimeout(() => {
                    this.hideInspectors();
                    debuginspector_default().InspectorsModel.instanceForProject(projectmodel.ProjectModel.instance).addInspectorForConnection({
                        connection: c.model,
                        position: c.findClosestPointOnCurve(atPosition)
                    });
                }, 200);
            }
        }
        this.highlightedConnection = c;
    }
    //hide all other inspectors that aren't pinned
    hideInspectors() {
        const inspectorsToRemove = this.inspectors.filter((inspector) => !inspector.isPinned());
        for (const inspector of inspectorsToRemove) {
            inspector.remove();
        }
    }
    getInspectorForConnection(c) {
        return this.inspectors.find((p) => p.connection === c);
    }
    getInspectorForNode(node) {
        return this.inspectors.find((p) => p.node === node);
    }
    removeInspector(inspector) {
        const idx = this.inspectors.indexOf(inspector);
        if (idx !== -1) {
            inspector.dispose();
            this.inspectors.splice(idx, 1);
        }
    }
    isPointInsideNodes(pos, nodes) {
        return nodes.some((node) => {
            const nodeRect = { x: node.global.x, y: node.global.y, width: node.nodeSize.width, height: node.nodeSize.height };
            return (pos.x >= nodeRect.x &&
                pos.x <= nodeRect.x + nodeRect.width &&
                pos.y >= nodeRect.y &&
                pos.y <= nodeRect.y + nodeRect.height);
        });
    }
    multiselectNodes(x, y, x2, y2, mode) {
        const selectRect = { x: Math.min(x, x2), y: Math.min(y, y2), width: Math.abs(x2 - x), height: Math.abs(y2 - y) };
        //select all comments
        this.commentLayer.performMultiSelect(selectRect, mode);
        // Select all nodes with a vertex inside of the multiselect area
        const selected = [];
        this.forEachNode((node) => {
            const nodeRect = { x: node.global.x, y: node.global.y, width: node.nodeSize.width, height: node.nodeSize.height };
            if ((0,utils.rectanglesOverlap)(nodeRect, selectRect)) {
                selected.push(node);
            }
        });
        if (mode === 'select') {
            this.selector.select(selected);
        }
        else if (mode === 'union') {
            this.selector.select(this.lastMultiselected ? external_underscore_default().union(this.lastMultiselected, selected) : selected);
        }
        else if (mode === 'reduce') {
            this.selector.select(this.lastMultiselected ? external_underscore_default().difference(this.lastMultiselected, selected) : []);
        }
    }
    isHighlighted(node) {
        return this.highlighted === node || this.selector.isActive(node);
    }
    openConnectionPanels() {
        // Hide viewer
        external_electron_.ipcRenderer.send('viewer-hide');
        // If a single or multiselect node is selected, deselect them
        this.deselect();
        const _this = this;
        setTimeout(() => {
            const topLeft = function (obj) {
                let curleft = (_this.curtop = 0);
                if (obj.offsetParent) {
                    do {
                        curleft += obj.offsetLeft;
                        _this.curtop += obj.offsetTop;
                    } while ((obj = obj.offsetParent));
                }
                return [curleft, _this.curtop];
            };
            const canvas = this.$('#nodegraphcanvas')[0];
            const tl = topLeft(canvas);
            const panAndScale = this.getPanAndScale();
            const fromNode = this.draggingConnection.fromNode;
            const toNode = this.draggingConnection.toNode;
            const fromNodeXPos = fromNode.global.x - 10;
            fromNode.borderHighlighted = true;
            toNode.borderHighlighted = false;
            let activePanel = 'from';
            function isPanelActive(id) {
                return activePanel === id;
            }
            // Show source node port picker
            const fromProps = {
                model: fromNode.model,
                type: 'from',
                disabled: false,
                isPanelActive,
                onPortSelected: (fromPort) => {
                    activePanel = 'to';
                    // @ts-expect-error
                    toProps.sourcePort = fromPort;
                    toProps.disabled = false;
                    toRoot.render(external_react_default().createElement(ConnectionPopup, toProps));
                    fromProps.disabled = true;
                    fromRoot.render(external_react_default().createElement(ConnectionPopup, fromProps));
                    fromNode.borderHighlighted = false;
                    toNode.borderHighlighted = true;
                    this.repaint();
                }
            };
            const fromDiv = document.createElement('div');
            const fromRoot = (0,client.createRoot)(fromDiv);
            fromRoot.render(external_react_default().createElement(ConnectionPopup, fromProps));
            const fromPosition = toNode.global.x > fromNodeXPos ? 'left' : 'right';
            external_electron_.ipcRenderer.send('viewer-hide');
            const fromPopout = popuplayer_default().instance.showPopout({
                content: { el: $(fromDiv) },
                position: fromPosition,
                arrowColor: '#464648',
                attachToPoint: {
                    x: (fromNode.global.x + panAndScale.x) * panAndScale.scale +
                        tl[0] +
                        fromNode.nodeSize.width * (fromPosition === 'left' ? 0 : 1.0) * panAndScale.scale,
                    y: (fromNode.global.y + panAndScale.y) * panAndScale.scale + tl[1] + 20 * panAndScale.scale
                },
                onClose: () => {
                    fromRoot.unmount();
                    external_electron_.ipcRenderer.send('viewer-show');
                }
            });
            // Show target node port picker
            const toProps = {
                model: toNode.model,
                fromNode: fromNode.model,
                type: 'to',
                disabled: true,
                isPanelActive,
                onPortSelected: (toPort) => {
                    activePanel = 'from';
                    // Make the connection
                    // Create the connection, this must be undoable
                    // @ts-expect-error
                    if (toProps.sourcePort !== undefined) {
                        const c = {
                            fromId: fromNode.model.id,
                            // @ts-expect-error
                            fromProperty: toProps.sourcePort,
                            toId: toNode.model.id,
                            toProperty: toPort
                        };
                        this.model.addConnection(c, {
                            undo: true,
                            label: 'connect'
                        });
                        // @ts-expect-error
                        toProps.sourcePort = undefined;
                        toProps.disabled = true;
                        toRoot.render(external_react_default().createElement(ConnectionPopup, toProps));
                        fromProps.disabled = false;
                        fromRoot.render(external_react_default().createElement(ConnectionPopup, fromProps));
                        fromNode.borderHighlighted = true;
                        toNode.borderHighlighted = false;
                        this.repaint();
                    }
                }
            };
            const toDiv = document.createElement('div');
            const toRoot = (0,client.createRoot)(toDiv);
            toRoot.render(external_react_default().createElement(ConnectionPopup, toProps));
            const toPosition = fromNodeXPos >= toNode.global.x ? 'left' : 'right';
            const toPopout = popuplayer_default().instance.showPopout({
                content: { el: $(toDiv) },
                position: toPosition,
                arrowColor: '#464648',
                attachToPoint: {
                    x: (toNode.global.x + panAndScale.x) * panAndScale.scale +
                        tl[0] +
                        toNode.nodeSize.width * (toPosition === 'left' ? 0 : 1.0) * panAndScale.scale,
                    y: (toNode.global.y + panAndScale.y) * panAndScale.scale + tl[1] + 20 * panAndScale.scale
                },
                onClose: () => {
                    toRoot.unmount();
                    this.clearSelection();
                    this.repaint();
                }
            });
        }, 0);
    }
    closeConnectionPanels() {
        external_electron_.ipcRenderer.send('viewer-show');
    }
    detachNode(node) {
        this.model.detachNode(node, { undo: this.dragNodesUndoGroup });
    }
    attachNode(parent, node, index) {
        this.model.attachNode(parent, node, index, {
            undo: this.dragNodesUndoGroup
        });
    }
    nudgeNode(node, x, y) {
        const enabled = editorsettings/* EditorSettings */.H.instance.get('nodeGraphEditor.snapToGrid');
        if (!enabled)
            return;
        //nodes with parent's don't use their x and y coords, so just bail out
        if (node.parent || (node.x === x && node.y === y))
            return;
        const startX = node.x;
        const startY = node.y;
        const startTime = performance.now();
        const anim = () => {
            const linearT = Math.min(1, (performance.now() - startTime) / 200);
            const easeOutT = 1 - Math.pow(1 - linearT, 4);
            node.x = startX * (1 - easeOutT) + x * easeOutT;
            node.y = startY * (1 - easeOutT) + y * easeOutT;
            this.relayout();
            this.repaint();
            if (easeOutT < 1)
                requestAnimationFrame(anim);
        };
        requestAnimationFrame(anim);
    }
    snapNodeToGrid(node) {
        const enabled = editorsettings/* EditorSettings */.H.instance.get('nodeGraphEditor.snapToGrid');
        if (!enabled)
            return;
        this.nudgeNode(node, Math.round(node.x / SnapSpacing) * SnapSpacing, Math.round(node.y / SnapSpacing) * SnapSpacing);
    }
    commitMoveNode(node) {
        const from = { x: node.model.x, y: node.model.y };
        const to = { x: node.x, y: node.y };
        const move = (to) => {
            node.model.set(to);
            node.x = to.x;
            node.y = to.y;
            this.snapNodeToGrid(node);
            this.relayout();
            this.repaint();
        };
        // Make sure we can undo move nodes
        if (from.x !== to.x || from.y !== to.y) {
            move(to);
            this.dragNodesUndoGroup.push({
                do: function () {
                    move(to);
                },
                undo: function () {
                    move(from);
                }
            });
        }
    }
    removeConnection(con) {
        this.model.removeConnection(con, { undo: true, label: 'disconnect' });
    }
    doDragNodesAndComments(draggingNodes, type, pos, evt) {
        if (type === 'move') {
            // Move all dragging nodes that are root nodes
            const dx = pos.x - this.lastDraggingMousePos.x;
            const dy = pos.y - this.lastDraggingMousePos.y;
            for (const n of draggingNodes) {
                if (!n.parent) {
                    n.x += dx;
                    n.y += dy;
                }
            }
            this.commentLayer.moveSelectedComments(dx, dy);
            this.lastDraggingMousePos = pos;
            // If we have dragged more than a given threshold, disconnect all nodes that are
            // currently in the hierarchy.
            if (Math.abs(pos.x - this.startDraggingMousePos.x) > NodeGraphEditorNode.attachedThreshold ||
                Math.abs(pos.y - this.startDraggingMousePos.y) > NodeGraphEditorNode.attachedThreshold) {
                for (const n of draggingNodes) {
                    if (n.parent)
                        this.detachNode(n.model);
                }
            }
            // If the nodes are detached
            const detached = draggingNodes.length && !external_underscore_default().some(draggingNodes, (n) => n.parent);
            if (detached) {
                for (const i in this.roots) {
                    // Don't attached to any nodes that are part of the current dragging
                    // nodes
                    if (draggingNodes.indexOf(this.roots[i]) !== -1)
                        continue;
                    this.insertLocation = this.roots[i].shouldAttach(pos, draggingNodes);
                    if (this.insertLocation)
                        break;
                }
            }
            evt.consumed = true;
            this.relayout();
            this.repaint();
        }
        else if (type === 'up') {
            const isClick = Math.abs(pos.x - this.startDraggingMousePos.x) < 5 && Math.abs(pos.y - this.startDraggingMousePos.y) < 5;
            // No insert location simply move the nodes
            // Update the model for all dragging nodes
            if (!isClick && (this.commentLayer.getSelectedComments().length || draggingNodes.length)) {
                //nodes or comments are selected, and we've moved the mouse since the down event
                //this means we've dragged elements around, so consume the event
                for (const n of draggingNodes) {
                    this.commitMoveNode(n);
                }
                this.commentLayer.commitSelectedComments({ undo: this.dragNodesUndoGroup });
                evt.consumed = true;
            }
            if (this.insertLocation) {
                // We have a new location for the insert it and relayout
                // Notify the model that a node should be attached
                const loc = this.insertLocation;
                for (let index = draggingNodes.length - 1; index >= 0; index--) {
                    const n = draggingNodes[index];
                    this.attachNode(loc.parent.model, n.model, loc.index);
                }
                this.insertLocation = undefined;
                evt.consumed = true;
            }
            // Commit undo action group
            if (this.dragNodesUndoGroup && !this.dragNodesUndoGroup.isEmpty()) {
                this.dragNodesUndoGroup.pushAndDo({
                    do: () => {
                        setTimeout(() => {
                            this.layout();
                            this.updateNodeToolbar();
                        }, 1);
                    },
                    undo: () => {
                        setTimeout(() => {
                            this.layout();
                            this.updateNodeToolbar();
                        }, 1);
                    }
                });
                undo_queue_model/* UndoQueue */.g.instance.push(this.dragNodesUndoGroup);
            }
            this.dragNodesUndoGroup = undefined;
            this.draggingNodes = undefined;
        }
    }
    doDragging(type, pos, evt) {
        // Node is being dragged to a new position
        if (this.draggingNodes) {
            this.doDragNodesAndComments(this.draggingNodes, type, pos, evt);
            if (evt.consumed)
                return true;
        }
        // A new connections is being dragged
        if (this.draggingConnection && !this.draggingConnection.popupOpen) {
            if (type === 'move') {
                // Hide viewer to get it out of the way
                external_electron_.ipcRenderer.send('viewer-hide');
                this.draggingConnection.pos = pos;
                this.draggingConnection.mouseTarget.global = pos;
                if (this.draggingConnection.toNode)
                    this.draggingConnection.toNode.borderHighlighted = false;
                let toNode;
                for (const i in this.roots) {
                    toNode = this.roots[i].shouldConnect(pos, this.draggingConnection.fromNode);
                    if (toNode)
                        break;
                }
                if (toNode && toNode != this.draggingConnection.fromNode) {
                    toNode.borderHighlighted = true;
                    this.draggingConnection.toNode = toNode;
                }
                else {
                    this.draggingConnection.toNode = undefined;
                }
                this.repaint();
            }
            else if (type === 'up') {
                // Show the viewer again
                external_electron_.ipcRenderer.send('viewer-show');
                if (this.draggingConnection.toNode) {
                    // We have a potential new connection
                    this.draggingConnection.popupOpen = true;
                    this.openConnectionPanels();
                    evt.stopPropagation();
                }
                else {
                    // No new connection, clear it
                    this.draggingConnection.fromNode.borderHighlighted = false;
                    this.draggingConnection = undefined;
                }
                this.repaint();
            }
            return true;
        }
        // Multi select in action
        if (this.multiselectMouseDown) {
            if (type === 'move') {
                let mode = 'select';
                if (evt.shiftKey)
                    mode = 'union';
                else if (evt.ctrlKey)
                    mode = 'reduce';
                this.multiselectMouseMove = pos;
                this.multiselectNodes(this.multiselectMouseDown.x, this.multiselectMouseDown.y, this.multiselectMouseMove.x, this.multiselectMouseMove.y, mode);
                this.repaint();
            }
            else if (type === 'up') {
                const isClick = Math.abs(pos.x - this.multiselectMouseDown.x) < 5 && Math.abs(pos.y - this.multiselectMouseDown.y) < 5;
                if (isClick) {
                    this.commentLayer.clearSelection();
                }
                this.multiselectMouseDown = this.multiselectMouseMove = undefined;
                if (!this.selector.active)
                    this.selector.unselect();
                this.repaint();
            }
            return true;
        }
    }
    updateNodeToolbar() {
        this.hideNodeToolbar(); //hide existing toolbar, if any
        const selection = this.selector.nodes;
        if (selection.length > 0 && !selection[0].selected) {
            const aabb = this.calculateNodesAABB(selection);
            this.showNodeToolbar(selection, aabb);
        }
    }
    showNodeToolbar(selectedNodes, aabb) {
        const menuItems = [];
        const canExtract = canExtractToComponent(this.model, selectedNodes);
        if (canExtract.allow) {
            menuItems.push({
                tooltip: 'Extract to component',
                icon: Icon/* IconName */.$M.Component,
                onClick: () => {
                    this.hideNodeToolbar();
                    this.extractSelectionToComponent();
                }
            });
        }
        if (selectedNodes.length === 1 &&
            createnewnodepanel/* CreateNewNodePanel */.F.shouldShow({
                component: this.model.owner,
                parentModel: selectedNodes[0].model
            })) {
            menuItems.push({
                tooltip: 'Add new child',
                onClick: () => {
                    this.hideNodeToolbar();
                    this.createNewNodePanel = new createnewnodepanel/* CreateNewNodePanel */.F({
                        model: this.model,
                        parentModel: this.highlighted ? this.highlighted.model : undefined,
                        pos: { x: 0, y: 0 },
                        runtimeType: this.runtimeType
                    });
                    this.createNewNodePanel.render();
                    setTimeout(() => {
                        popuplayer_default().instance.showPopup({
                            content: this.createNewNodePanel,
                            position: 'screen-center',
                            isBackgroundDimmed: true,
                            onClose: () => this.createNewNodePanel.dispose()
                        });
                    }, 1);
                },
                icon: Icon/* IconName */.$M.Plus
            });
        }
        const div = document.createElement('div');
        div.className = 'nodegraph-node-toolbar';
        this.domElementContainer.appendChild(div);
        const pos = {
            x: (aabb.minX + aabb.maxX) / 2,
            y: aabb.minY
        };
        div.style.width = 'max-content';
        div.style.transform = 'translate(-50%, calc(-100% - 10px))';
        div.style.position = 'absolute';
        div.style.left = pos.x + 'px';
        div.style.top = pos.y + 'px';
        const root = (0,client.createRoot)(div);
        this.toolbarRoots.push(root);
        root.render(external_react_default().createElement(PopupToolbar, {
            menuItems,
            contextMenuItems: this.getContextMenuActions()
        }));
    }
    hideNodeToolbar() {
        for (const root of this.toolbarRoots) {
            root.unmount();
        }
        this.toolbarRoots = [];
        const toolbars = this.domElementContainer.querySelectorAll('.nodegraph-node-toolbar');
        for (const toolbar of toolbars) {
            this.domElementContainer.removeChild(toolbar);
        }
    }
    setMouseEventsEnabled(enabled) {
        this.mouseEventsEnabled = enabled;
    }
    relativeCoordsToNodeGraphCords(pos) {
        const panAndScale = this.getPanAndScale();
        return {
            x: pos.x / panAndScale.scale - panAndScale.x,
            y: pos.y / panAndScale.scale - panAndScale.y
        };
    }
    mouse(type, pos, evt, args) {
        var _a;
        if (!this.mouseEventsEnabled || !this.model) {
            return false;
        }
        const _this = this;
        const panAndScale = this.getPanAndScale();
        const scale = panAndScale.scale;
        const scaledPos = this.relativeCoordsToNodeGraphCords(pos);
        if (type === 'down' && evt.button === 0) {
            //hide inspectors that aren't pinned
            this.hideInspectors();
            this.hideNodeToolbar();
        }
        //Elements in the dom layer (e.g. inspectors) are hidden when a node or connection is being dragged
        //Show them again if a mouse up event is triggered
        else if (type === 'up') {
            this.setDOMLayerVisible(true);
            this.updateNodeToolbar();
        }
        // Check for double clicks
        if (evt.button === 0 && evt.type === 'mousedown') {
            const lastPressed = this.lastLeftButtonPressedTime;
            const now = Date.now();
            if (now - lastPressed < 500) {
                // click interval here!
                this.leftButtonIsDoubleClicked = true;
            }
            else {
                this.leftButtonIsDoubleClicked = false;
            }
            this.lastLeftButtonPressedTime = now;
        }
        this.latestMousePos = scaledPos;
        if (!this.doDragging(type, scaledPos, evt)) {
            // If we are in "connection mode" then don't do any mouse tracking
            // until it is canceled
            const isPanning = this.panMouseDown || (evt.spaceKey && evt.button === 0);
            if (!isPanning && !(this.draggingConnection && this.draggingConnection.popupOpen)) {
                for (const i in this.roots) {
                    this.roots[i].propagateMouse(type, scaledPos, evt);
                }
            }
            // Pass mouse to connections
            if (!evt.consumed) {
                for (const i in this.connections) {
                    this.connections[i].mouse(type, scaledPos, evt);
                }
            }
            // If a drag item is current in place indicate if
            // a drop can be accepted
            if (popuplayer_default().instance.isDragging()) {
                const dragItem = (popuplayer_default()).instance.dragItem;
                // Indicate drop acceptable
                if (type === 'move') {
                    if (canAcceptDrop(_this, dragItem)) {
                        popuplayer_default().instance.indicateDropType('add');
                    }
                    else {
                        popuplayer_default().instance.indicateDropType('none');
                    }
                }
                else if (type === 'out') {
                    popuplayer_default().instance.indicateDropType('none');
                    popuplayer_default().instance.setDragMessage();
                }
                // Make the drop
                else if (type === 'up') {
                    // Create the new component that was dropped
                    if (canAcceptDrop(_this, dragItem)) {
                        evt.consumed = onDrop(this, dragItem, scaledPos);
                    }
                }
            }
            if (evt.consumed) {
                return true;
            }
            // Clear selection on left mouse up when no node is
            // highlighted
            if (!this.readOnly &&
                type === 'up' &&
                evt.button === 0 &&
                !evt.shiftKey &&
                this.highlighted === undefined &&
                this.highlightedConnection === undefined) {
                this.clearSelection();
                this.repaint();
            }
            // Pan view on right mouse drag, middle mouse drag, or space + left mouse
            if (type === 'down' && (evt.button === 2 || evt.button === 1 || (evt.spaceKey && evt.button === 0))) {
                this.panMouseDown = pos;
                this.canvas.ctx.canvas.style.cursor = 'grabbing';
                evt.consumed = true;
            }
            else if (type === 'move' && this.panMouseDown) {
                // Move all roots and relayout
                this.moveRoots((pos.x - this.panMouseDown.x) / scale, (pos.y - this.panMouseDown.y) / scale);
                this.panMouseDown = pos;
                this.relayout();
                this.repaint();
                evt.consumed = true;
            }
            else if ((type === 'up' || type === 'out') && this.panMouseDown) {
                this.panMouseDown = this.originMouseDown = undefined;
                this.canvas.ctx.canvas.style.cursor = 'inherit';
            }
            // Handle right click
            if (type === 'down' && evt.button === 2) {
                this.rightClickPos = pos;
            }
            else if (type === 'up' && evt.button === 2 && this.rightClickPos) {
                if (this.model &&
                    !this.readOnly &&
                    Math.abs(pos.x - this.rightClickPos.x) + Math.abs(pos.y - this.rightClickPos.y) < 10) {
                    popuplayer_default().instance.hidePopup();
                    evt.consumed = true;
                    // Check if we're right-clicking on a node (selected or not)
                    let nodeUnderCursor = null;
                    // First check if clicking on already selected nodes
                    if (this.isPointInsideNodes(scaledPos, this.selector.nodes)) {
                        nodeUnderCursor = this.selector.nodes.find((node) => {
                            const nodeRect = {
                                x: node.global.x,
                                y: node.global.y,
                                width: node.nodeSize.width,
                                height: node.nodeSize.height
                            };
                            return (scaledPos.x >= nodeRect.x &&
                                scaledPos.x <= nodeRect.x + nodeRect.width &&
                                scaledPos.y >= nodeRect.y &&
                                scaledPos.y <= nodeRect.y + nodeRect.height);
                        });
                    }
                    // If not on a selected node, check all nodes
                    if (!nodeUnderCursor) {
                        this.forEachNode((node) => {
                            const nodeRect = {
                                x: node.global.x,
                                y: node.global.y,
                                width: node.nodeSize.width,
                                height: node.nodeSize.height
                            };
                            if (scaledPos.x >= nodeRect.x &&
                                scaledPos.x <= nodeRect.x + nodeRect.width &&
                                scaledPos.y >= nodeRect.y &&
                                scaledPos.y <= nodeRect.y + nodeRect.height) {
                                nodeUnderCursor = node;
                                return true; // Stop iteration
                            }
                        });
                    }
                    if (nodeUnderCursor) {
                        // Select the node if it isn't already selected
                        if (!this.selector.isActive(nodeUnderCursor)) {
                            this.clearSelection();
                            (_a = this.commentLayer) === null || _a === void 0 ? void 0 : _a.clearSelection();
                            nodeUnderCursor.selected = true;
                            this.selector.select([nodeUnderCursor]);
                            this.repaint();
                        }
                        // Show context menu
                        this.openRightClickMenu();
                    }
                    else if (createnewnodepanel/* CreateNewNodePanel */.F.shouldShow({
                        component: this.model.owner,
                        parentModel: this.highlighted ? this.highlighted.model : undefined
                    })) {
                        this.createNewNodePanel = new createnewnodepanel/* CreateNewNodePanel */.F({
                            model: this.model,
                            parentModel: this.highlighted ? this.highlighted.model : undefined,
                            pos: scaledPos,
                            runtimeType: this.runtimeType
                        });
                        this.createNewNodePanel.render();
                        popuplayer_default().instance.showPopup({
                            content: this.createNewNodePanel,
                            /*attachToPoint:{x:pos.pageX, y:pos.pageY},*/
                            position: 'screen-center',
                            isBackgroundDimmed: true,
                            onClose: () => this.createNewNodePanel.dispose()
                        });
                    }
                    // If clicking empty space with no valid actions, do nothing (no broken tooltip)
                }
                this.rightClickPos = undefined;
            }
            // Start multi select, move is handled in the do dragging function
            if (!this.readOnly &&
                !evt.consumed &&
                type === 'down' &&
                evt.button === 0 &&
                !evt.spaceKey &&
                this.highlighted === undefined &&
                this.highlightedConnection === undefined &&
                this.draggingConnection === undefined &&
                !(args && args.eventPropagatedFromCommentLayer)) {
                // Store last multi select reduce and union operations
                this.lastMultiselected = this.selector.nodes;
                // reset current multi selection if it's not the start of a new multi select operation (ctrl or shift is pressed)
                if (!evt.ctrlKey && !evt.shiftKey) {
                    this.commentLayer.clearMultiselection();
                    this.clearSelection();
                }
                else {
                    this.selector.select(this.lastMultiselected);
                }
                this.multiselectMouseDown = scaledPos;
                this.repaint();
            }
        }
        const needRepaint = type != 'over' && type !== 'out' && !(type === 'move' && !this.rightClickPos && evt.button !== 0);
        if (needRepaint) {
            this.relayout();
            this.repaint();
        }
        return evt.consumed;
    }
    getContextMenuActions() {
        const items = [];
        const selectedNodes = this.selector.nodes;
        const canExtract = canExtractToComponent(this.model, selectedNodes);
        items.push({
            label: 'Extract to component',
            icon: Icon/* IconName */.$M.Component,
            onClick: () => this.extractSelectionToComponent(),
            isDisabled: !canExtract.allow,
            tooltip: canExtract.reason,
            tooltipShowAfterMs: 300
        });
        items.push('divider');
        // Data Lineage - DISABLED: Not production ready, requires more work
        // TODO: Re-enable when lineage filtering and event handling are fixed
        // items.push({
        //   label: 'Show Data Lineage',
        //   icon: IconName.Link,
        //   onClick: () => {
        //     const selectedNode = this.selector.nodes[0];
        //     if (selectedNode) {
        //       EventDispatcher.instance.emit('DataLineage.ShowForNode', {
        //         nodeId: selectedNode.model.id,
        //         componentName: this.activeComponent?.fullName
        //       });
        //       SidebarModel.instance.switch('data-lineage');
        //     }
        //   },
        //   isDisabled: selectedNodes.length !== 1,
        //   tooltip: selectedNodes.length !== 1 ? 'Select a single node to trace its data lineage' : undefined,
        //   tooltipShowAfterMs: 300
        // });
        // items.push('divider');
        if (selectedNodes.length === 1 &&
            createnewnodepanel/* CreateNewNodePanel */.F.shouldShow({
                component: this.model.owner,
                parentModel: selectedNodes[0].model
            })) {
            items.push({
                label: 'Add new child',
                onClick: () => {
                    const selectedNode = this.selector.nodes[0];
                    this.createNewNodePanel = new createnewnodepanel/* CreateNewNodePanel */.F({
                        model: this.model,
                        parentModel: selectedNode === null || selectedNode === void 0 ? void 0 : selectedNode.model,
                        pos: { x: 0, y: 0 },
                        runtimeType: this.runtimeType
                    });
                    this.createNewNodePanel.render();
                    popuplayer_default().instance.showPopup({
                        content: this.createNewNodePanel,
                        position: 'screen-center',
                        isBackgroundDimmed: true,
                        onClose: () => this.createNewNodePanel.dispose()
                    });
                },
                icon: Icon/* IconName */.$M.Plus
            });
        }
        items.push({
            label: 'Delete',
            onClick: () => this.delete(),
            icon: Icon/* IconName */.$M.Trash
        });
        return items;
    }
    openRightClickMenu() {
        (0,ShowContextMenuInPopup.showContextMenuInPopup)({
            items: this.getContextMenuActions(),
            width: MenuDialog.MenuDialogWidth.Default,
            renderDirection: BaseDialog/* DialogRenderDirection */.K1.Horizontal
        });
    }
    layoutAndPaint() {
        if (!this.el) {
            return;
        }
        if (this._disposed)
            return;
        if (this.relayoutNeeded)
            this.layout();
        this.paint();
        this.relayoutNeeded = this.layoutAndPaintScheduled = false;
    }
    relayout() {
        this.relayoutNeeded = true;
    }
    layout() {
        if (!this.model) {
            return;
        }
        this.forEachNode(function (node) {
            node.measuredSize = undefined;
        });
        external_underscore_default().each(this.roots, function (node) {
            node.measure();
            node.setPosition(node.x, node.y);
            node.layout();
        });
        this.calculateAABB();
    }
    repaint() {
        if (!this.layoutAndPaintScheduled) {
            window.requestAnimationFrame(this.layoutAndPaint.bind(this));
            this.layoutAndPaintScheduled = true;
        }
    }
    calculateAABB() {
        const _this = this;
        this.graphAABB = {
            minX: Number.MAX_VALUE,
            maxX: -Number.MAX_VALUE,
            minY: Number.MAX_VALUE,
            maxY: -Number.MAX_VALUE
        };
        external_underscore_default().each(this.roots, function (node) {
            if (node.x < _this.graphAABB.minX) {
                _this.graphAABB.minX = node.x;
            }
            if (node.x + node.measuredSize.width > _this.graphAABB.maxX) {
                _this.graphAABB.maxX = node.x + node.measuredSize.width;
            }
            if (node.y < _this.graphAABB.minY) {
                _this.graphAABB.minY = node.y;
            }
            if (node.y + node.measuredSize.height > _this.graphAABB.maxY) {
                _this.graphAABB.maxY = node.y + node.measuredSize.height;
            }
        });
        external_underscore_default().each(this.model.commentsModel.comments, function (comment) {
            if (comment.x < _this.graphAABB.minX) {
                _this.graphAABB.minX = comment.x;
            }
            if (comment.x + comment.width > _this.graphAABB.maxX) {
                _this.graphAABB.maxX = comment.x + comment.width;
            }
            if (comment.y < _this.graphAABB.minY) {
                _this.graphAABB.minY = comment.y;
            }
            if (comment.y + comment.height > _this.graphAABB.maxY) {
                _this.graphAABB.maxY = comment.y + comment.height;
            }
        });
    }
    findNodeWithId(id) {
        let res;
        this.forEachNode(function (node) {
            if (id === node.id) {
                res = node;
                return true;
            }
        });
        return res;
    }
    findConnectionWithModel(model) {
        for (const i in this.connections)
            if (this.connections[i].model === model)
                return this.connections[i];
    }
    findConnectionWithKey(key) {
        for (const i in this.connections) {
            const m = this.connections[i].model;
            if (m.fromId + m.fromProperty + m.toId + m.toProperty === key)
                return this.connections[i];
        }
    }
    findInspectorWithModel(model) {
        return this.inspectors.find((inspector) => inspector.model === model);
    }
    paint() {
        if (!this.canvas.width || !this.canvas.height) {
            return;
        }
        const ctx = this.canvas.ctx;
        const panAndScale = this.getPanAndScale();
        const scale = this.getPanAndScale().scale;
        const transform = `scale(${panAndScale.scale}) translate(${panAndScale.x}px, ${panAndScale.y}px)`;
        this.domElementContainer.style.transform = transform;
        this.commentLayer && this.commentLayer.setPanAndScale(panAndScale);
        ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        if (!nodelibrary/* NodeLibrary */.m.instance.isLoaded()) {
            // Don't paint if we don't have a node library yet
            return;
        }
        ctx.save();
        ctx.scale(this.canvas.ratio * scale, this.canvas.ratio * scale);
        ctx.translate(panAndScale.x, panAndScale.y);
        const paintRect = {
            minX: -panAndScale.x,
            maxX: this.canvas.width / (this.canvas.ratio * scale) - panAndScale.x,
            minY: -panAndScale.y,
            maxY: this.canvas.height / (this.canvas.ratio * scale) - panAndScale.y
        };
        ctx.font = '10px Helvetica';
        // Paint hierarchy
        function paintHierarchy(node) {
            const x = node.global.x;
            const y = node.global.y;
            // Draw hierarchy indicators
            let hy = y + node.nodeSize.height + 5;
            ctx.strokeStyle = '#504f4f'; //Grey 700
            ctx.lineWidth = 1;
            for (const i in node.children) {
                const child = node.children[i];
                ctx.beginPath();
                ctx.moveTo(x + NodeGraphEditorNode.childMargin / 2, hy);
                hy = child.global.y + child.nodeSize.height / 2;
                ctx.lineTo(x + NodeGraphEditorNode.childMargin / 2, hy);
                ctx.lineTo(x + NodeGraphEditorNode.childMargin - 5, hy);
                ctx.stroke();
            }
            ctx.globalAlpha = 1;
            external_underscore_default().each(node.children, paintHierarchy);
        }
        // Paint hierarchy
        external_underscore_default().each(this.roots, paintHierarchy);
        // Paint connections
        external_underscore_default().each(this.connections, function (con) {
            con.paint(ctx, paintRect);
        });
        // Paint all highlighted connections (so they always show up on top)
        external_underscore_default().each(this.connections, function (con) {
            if (con.isHighlighted())
                con.paint(ctx, paintRect);
        });
        // Paint nodes
        const _this = this;
        external_underscore_default().each(this.roots, function (node) {
            if (!_this.draggingNodes || _this.draggingNodes.indexOf(node) === -1) {
                node.paint(ctx, paintRect);
            }
        });
        if (this.insertLocation) {
            // Indicate that we have an insert location when
            // dragging this node
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(this.insertLocation.pos.x, this.insertLocation.pos.y + (NodeGraphEditorNode.childSpacing - 5) / 2, NodeGraphEditorNode.size.width, 5);
        }
        // Paint multiselect box
        if (this.selector.nodes.length > 0 && !this.selector.nodes[0].selected) {
            this.paintMultiselectBox(ctx, this.calculateNodesAABB(this.selector.nodes));
        }
        // if (window._debugNodeGraphAttachPoints) {
        //   ctx.save();
        //   for (const attach of window._debugNodeGraphAttachPoints) {
        //     ctx.fillStyle = '#ff00ff';
        //     ctx.fillRect(attach.anchorPoint.x - 6, attach.anchorPoint.y - 6, 12, 12);
        //   }
        //   ctx.restore();
        // }
        ctx.globalAlpha = 0.5;
        // Paint nodes that are being dragged
        external_underscore_default().each(this.draggingNodes, function (node) {
            node.paint(ctx, paintRect);
        });
        ctx.globalAlpha = 1;
        // Paint the new connection indicator if we have one
        if (this.draggingConnection) {
            // Make background darker
            if (this.draggingConnection.fromNode !== undefined && this.draggingConnection.toNode !== undefined) {
                ctx.fillStyle = '#000';
                ctx.globalAlpha = 0.6;
                ctx.fillRect(paintRect.minX, paintRect.minY, paintRect.maxX - paintRect.minX, paintRect.maxY - paintRect.minY);
                ctx.globalAlpha = 1;
                // First the two nodes where a connection is being made
                external_underscore_default().each([this.draggingConnection.fromNode, this.draggingConnection.toNode], function (node) {
                    node.paint(ctx, paintRect, { dontPaintChildren: true });
                });
                // Draw all connections between these nodes
                external_underscore_default().each(this.connections, (con) => {
                    if (con.fromNode === this.draggingConnection.fromNode && con.toNode === this.draggingConnection.toNode)
                        con.paint(ctx, paintRect);
                });
            }
            ctx.globalAlpha = 1;
            // Draw line between from node and mouse position, if a target node is hovered
            // draw to the center of the target node
            ctx.strokeStyle = NodeGraphColors.yellow;
            ctx.setLineDash([5]);
            ctx.lineWidth = 2;
            ctx.beginPath();
            const from = {
                x: this.draggingConnection.fromNode.global.x + this.draggingConnection.fromNode.nodeSize.width,
                y: this.draggingConnection.fromNode.global.y + this.draggingConnection.fromNode.titlebarHeight() / 2
            };
            if (this.draggingConnection.toNode) {
                var to = {
                    x: this.draggingConnection.toNode.global.x + this.draggingConnection.toNode.nodeSize.width / 2,
                    y: this.draggingConnection.toNode.global.y + this.draggingConnection.toNode.nodeSize.height / 2
                };
            }
            else {
                to = this.draggingConnection.mouseTarget.global;
            }
            const d = { x: to.x - from.x, y: to.y - from.y };
            const dl = Math.sqrt(d.x * d.x + d.y * d.y);
            d.x /= dl;
            d.y /= dl;
            const n = { x: d.y, y: -d.x };
            ctx.moveTo(from.x + d.x * 4, from.y + d.y * 4); // Don't draw over source circle, looks weird when alpha is down
            ctx.lineTo(to.x - d.x * 6, to.y - d.y * 6);
            ctx.stroke();
            // Draw the circle at the source node and the arrow head
            // at the target node
            ctx.beginPath();
            ctx.fillStyle = NodeGraphColors.yellow;
            ctx.arc(from.x, from.y, 4, 0, 2 * Math.PI, false);
            ctx.moveTo(to.x + d.x * 2, to.y + d.y * 2);
            ctx.lineTo(to.x - d.x * 6 - n.x * 4, to.y - d.y * 6 - n.y * 4);
            ctx.lineTo(to.x - d.x * 6 + n.x * 4, to.y - d.y * 6 + n.y * 4);
            ctx.fill();
            ctx.globalAlpha = 1;
        }
        // Paint multiselect
        if (this.multiselectMouseMove) {
            ctx.strokeStyle = NodeGraphColors.multiSelect;
            ctx.setLineDash([5]);
            ctx.beginPath();
            ctx.rect(this.multiselectMouseDown.x, this.multiselectMouseDown.y, this.multiselectMouseMove.x - this.multiselectMouseDown.x, this.multiselectMouseMove.y - this.multiselectMouseDown.y);
            ctx.stroke();
            ctx.setLineDash([]);
        }
        ctx.restore();
    }
    paintMultiselectBox(ctx, aabb) {
        const pad = 8;
        const shadowSize = 150;
        //draw a shadow
        //mask away everything inside the selection bounding box...
        const w = aabb.maxX - aabb.minX;
        const h = aabb.maxY - aabb.minY;
        ctx.save();
        ctx.beginPath();
        ctx.rect(aabb.minX - shadowSize, aabb.minY - shadowSize, 2 * shadowSize + w, shadowSize - pad);
        ctx.rect(aabb.minX - shadowSize, aabb.minY - pad, shadowSize - pad, h + 2 * pad + 2 * shadowSize);
        ctx.rect(aabb.maxX + pad, aabb.minY - pad, shadowSize, h + 2 * pad);
        ctx.rect(aabb.minX - shadowSize, aabb.maxY + pad, 2 * shadowSize + w, shadowSize);
        ctx.clip();
        //...and draw a shadow
        ctx.shadowColor = 'black';
        ctx.shadowBlur = shadowSize;
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;
        ctx.fillStyle = 'white'; //the color doesn't matter, just need full opacity. The rect is clipped and just the shadow remains
        ctx.beginPath();
        ctx.fillRect(aabb.minX - pad, aabb.minY - pad, w + 2 * pad, h + 2 * pad);
        //draw selection box
        ctx.lineWidth = 1;
        ctx.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue('--theme-color-fg-default').trim();
        ctx.strokeRect(aabb.minX - pad, aabb.minY - pad, w + 2 * pad, h + 2 * pad);
        ctx.restore();
    }
    // This function is used during the tests to verify that the view of the node graph editor
    // matches the model
    verifyWithModel() {
        const _this = this;
        let verified = true;
        function assert(cond) {
            if (!cond)
                verified = false;
        }
        this.forEachNode(function (node) {
            const model = node.model;
            assert(_this.findNodeWithId(model.id) == node);
            // Make sure parent are correctly linked
            if (node.parent)
                assert(_this.findNodeWithId(model.parent.id) === node.parent);
            else
                assert(!model.parent);
        });
        return verified;
    }
    /**
     * @returns The center of all the root nodes in the graph.
     */
    getCenterRootPanAndScale() {
        let centerX = 0;
        let centerY = 0;
        let count = 0;
        external_underscore_default().each(this.roots, function (root) {
            centerX += root.x + root.nodeSize.width / 2;
            centerY += root.y + root.nodeSize.height / 2;
            count++;
        });
        const centerViewX = this.canvas.width / this.canvas.ratio / 2;
        const centerViewY = this.canvas.height / this.canvas.ratio / 2;
        return {
            x: centerViewX - centerX / count,
            y: centerViewY - centerY / count,
            scale: 1
        };
    }
    /**
     * @returns The center of all the nodes in the graph.
     */
    getCenterPanAndScale() {
        let centerX = 0;
        let centerY = 0;
        let count = 0;
        external_underscore_default().each(this.roots, function (root) {
            centerX += root.x + root.measuredSize.width / 2;
            centerY += root.y + root.measuredSize.height / 2;
            count++;
        });
        const centerViewX = this.canvas.width / this.canvas.ratio / 2;
        const centerViewY = this.canvas.height / this.canvas.ratio / 2;
        return {
            x: centerViewX - centerX / count,
            y: centerViewY - centerY / count,
            // TODO: Do we want to figure out the scale here too?
            scale: 1
        };
    }
    /**
     * Center the camera in the middle of all the nodes.
     *
     * @returns The current pan and scale.
     */
    centerToFit(mode) {
        switch (mode) {
            default:
            case CenterToFitMode.RootNodes: {
                this.setPanAndScale(this.getCenterRootPanAndScale());
                break;
            }
            case CenterToFitMode.AllNodes: {
                this.setPanAndScale(this.getCenterPanAndScale());
                break;
            }
        }
        return this.panAndScale;
    }
    getPanAndScale() {
        if (this.panAndScale) {
            return this.panAndScale;
        }
        if (!this.model || !this.canvas.width || !this.canvas.height || !this.roots.length) {
            return { scale: 1, x: 0, y: 0 };
        }
        return this.centerToFit(CenterToFitMode.RootNodes);
    }
    setPanAndScale(panAndScale) {
        this.panAndScale = panAndScale;
        this.commentLayer && this.commentLayer.setPanAndScale(panAndScale);
        this.updateHighlightOverlay();
    }
    clampPanAndScale(panAndScale) {
        if (!this.model || this.model.roots.length === 0)
            return panAndScale;
        const ClampPadding = 100;
        const graphAABB = this.graphAABB;
        const canvasWidth = this.canvas.width / (this.canvas.ratio * panAndScale.scale);
        const canvasHeight = this.canvas.height / (this.canvas.ratio * panAndScale.scale);
        const visiblePixelsAtLeftBorder = panAndScale.x + graphAABB.maxX;
        const visiblePixelsAtTopBorder = panAndScale.y + graphAABB.maxY;
        const visiblePixelsAtRightBorder = canvasWidth - panAndScale.x - graphAABB.minX;
        const visiblePixelsAtBottomBorder = canvasHeight - panAndScale.y - graphAABB.minY;
        if (visiblePixelsAtLeftBorder < ClampPadding) {
            panAndScale.x = ClampPadding - graphAABB.maxX;
        }
        if (visiblePixelsAtRightBorder < ClampPadding) {
            panAndScale.x = canvasWidth - graphAABB.minX - ClampPadding;
        }
        if (visiblePixelsAtTopBorder < ClampPadding) {
            panAndScale.y = ClampPadding - graphAABB.maxY;
        }
        if (visiblePixelsAtBottomBorder < ClampPadding) {
            panAndScale.y = canvasHeight - graphAABB.minY - ClampPadding;
        }
        return panAndScale;
    }
    calculateNodesAABB(nodes) {
        const firstNode = nodes[0];
        const aabb = {
            minX: firstNode.global.x,
            minY: firstNode.global.y,
            maxX: firstNode.global.x + firstNode.nodeSize.width,
            maxY: firstNode.global.y + firstNode.nodeSize.height
        };
        for (let i = 1; i < nodes.length; i++) {
            const n = nodes[i];
            aabb.minX = Math.min(aabb.minX, n.global.x);
            aabb.minY = Math.min(aabb.minY, n.global.y);
            aabb.maxX = Math.max(aabb.maxX, n.global.x + n.nodeSize.width);
            aabb.maxY = Math.max(aabb.maxY, n.global.y + n.nodeSize.height);
        }
        return aabb;
    }
    nodesetFromSelection() {
        const nodes = this.selector.nodes;
        // Make sure all nodes can be copied
        const _invalid = nodes.filter((n) => !n.model.canBeCopied());
        if (_invalid.length !== 0) {
            popuplayer_default().instance.showToast('One of more of these nodes cannot be copied');
            return;
        }
        // Update coordinates so they are pasted correctly
        const nodeModels = nodes.map((n) => {
            n.x = n.global.x;
            n.y = n.global.y;
            n.updateModel();
            return n.model;
        });
        const nodeset = this.model.getNodeSetWithNodes(nodeModels);
        nodeset.comments = this.commentLayer.getSelectedComments();
        return nodeset;
    }
    extractSelectionToComponent() {
        const nodeset = this.nodesetFromSelection();
        const selection = this.selector.nodes;
        const aabb = this.calculateNodesAABB(selection);
        const pos = {
            x: (aabb.minX + aabb.maxX) / 2 - NodeGraphEditorNode.size.width / 2,
            y: aabb.minY
        };
        extractToComponent(projectmodel.ProjectModel.instance, this.model, nodeset, selection, pos);
        this.clearSelection();
        this.relayout();
        this.repaint();
    }
}


/***/ }),

/***/ 98373:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.Center-module__Root--ZBudJ{display:flex;justify-content:center;align-items:center}`, "",{"version":3,"sources":["webpack://./../noodl-core-ui/src/components/layout/Center/Center.module.scss"],"names":[],"mappings":"AAAA,4BACE,YAAA,CACA,sBAAA,CACA,kBAAA","sourcesContent":[".Root {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"Root": `Center-module__Root--ZBudJ`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 98424:
/***/ ((module) => {

class SchemaModel {
  constructor(args) {
    this.appId = args.appId;
    this.endpoint = args.endpoint || args.url;
    this.masterKey = args.masterKey;
  }

  _makeRequest(path, options) {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        var json;
        try {
          json = JSON.parse(xhr.response);
        } catch (e) {}

        if (xhr.status === 200 || xhr.status === 201) {
          options.success(json);
        } else {
          options.error(json);
        }
      }
    };

    xhr.open(options.method || 'GET', this.endpoint + path, true);

    xhr.setRequestHeader('X-Parse-Application-Id', this.appId);
    xhr.setRequestHeader('X-Parse-MASTER-Key', this.masterKey);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.send(JSON.stringify(options.content));
  }

  listSchemas(options) {
    this._makeRequest('/schemas', {
      success: function (response) {
        const _result = response.results;

        options.success(
          _result.map((schema) => {
            delete schema.fields.objectId;
            delete schema.fields.ACL;

            return {
              name: schema.className,
              fields: schema.fields
            };
          })
        );
      },
      error: function (res) {
        options.error(res);
      }
    });
  }

  getConfigSchema(options) {
    function _typeForValue(v) {
      if (typeof v === 'string') {
        return 'string';
      } else if (typeof v === 'number') {
        return 'number';
      } else if (typeof v === 'boolean') {
        return 'boolean';
      } else if (Array.isArray(v)) {
        return 'array';
      } else if (v instanceof Date && typeof v.toISOString === 'function') {
        return 'date';
      } else if (typeof v === 'object') {
        return 'object';
      }
    }

    this._makeRequest('/config', {
      success: function (response) {
        const configSchema = {};
        const params = response.params || {};
        const masterKeyOnly = response.masterKeyOnly || {};
        Object.keys(params).forEach((k) => {
          configSchema[k] = { masterKeyOnly: !!masterKeyOnly[k], type: _typeForValue(params[k]) };
        });

        options.success(configSchema);
      },
      error: function (res) {
        options.error(res);
      }
    });
  }

  createNewSchema(options) {
    this._makeRequest('/schemas/' + options.collection, {
      method: 'POST',
      content: {
        className: options.collection
      },
      success: function (response) {
        options.success();
      },
      error: function (res) {
        options.error(res);
      }
    });
  }

  getSchema(options) {
    this._makeRequest('/schemas/' + options.collection, {
      success: function (schema) {
        delete schema.fields.objectId;
        delete schema.fields.ACL;

        options.success(schema);
      },
      error: function (res) {
        options.error(res);
      }
    });
  }

  addSchemaFields(options) {
    this._makeRequest('/schemas/' + options.collection, {
      method: 'PUT',
      content: {
        className: options.collection,
        fields: options.fields
      },
      success: function (response) {
        options.success();
      },
      error: function (res) {
        options.error(res);
      }
    });
  }

  addSchemaField(options) {
    const fields = {};
    fields[options.field] = { type: options.type };
    this._makeRequest('/schemas/' + options.collection, {
      method: 'PUT',
      content: {
        className: options.collection,
        fields: fields
      },
      success: function (response) {
        options.success();
      },
      error: function (res) {
        options.error(res);
      }
    });
  }

  deleteSchemaField(options) {
    const fields = {};
    fields[options.field] = { __op: 'Delete' };
    this._makeRequest('/schemas/' + options.collection, {
      method: 'PUT',
      content: {
        className: options.collection,
        fields: fields
      },
      success: function (response) {
        options.success();
      },
      error: function (res) {
        options.error(res);
      }
    });
  }

  deleteSchema(options) {
    this._makeRequest('/schemas/' + options.collection, {
      method: 'DELETE',
      success: function (response) {
        options.success();
      },
      error: function (res) {
        options.error(res);
      }
    });
  }

  batchCreateObjects(options) {
    const url = new URL(this.endpoint);

    const _data = {
      requests: options.data.map((o) => ({
        method: 'POST',
        path: url.pathname + '/classes/' + options.collection,
        body: o
      }))
    };

    this._makeRequest('/batch', {
      method: 'POST',
      content: _data,
      success: function (response) {
        options.success();
      },
      error: function (res) {
        options.error(res.error);
      }
    });
  }
}

module.exports = SchemaModel;


/***/ }),

/***/ 98690:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  Z: () => (/* reexport */ PropertyPanelBaseInput)
});

// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/property-panel/PropertyPanelBaseInput/PropertyPanelBaseInput.module.scss
var PropertyPanelBaseInput_module = __webpack_require__(88007);
;// ../noodl-core-ui/src/components/property-panel/PropertyPanelBaseInput/PropertyPanelBaseInput.module.scss

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(PropertyPanelBaseInput_module/* default */.A, options);




       /* harmony default export */ const PropertyPanelBaseInput_PropertyPanelBaseInput_module = (PropertyPanelBaseInput_module/* default */.A && PropertyPanelBaseInput_module/* default */.A.locals ? PropertyPanelBaseInput_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelBaseInput/PropertyPanelBaseInput.tsx



function PropertyPanelBaseInput({ value, type, isChanged, isConnected, isFauxFocused, hasHiddenCaret, hasSmallText, onChange, onClick, onMouseEnter, onMouseLeave, onFocus, onBlur, onKeyDown, className }) {
    return (external_react_default().createElement("input", { className: external_classnames_default()(PropertyPanelBaseInput_PropertyPanelBaseInput_module['Root'], isChanged && PropertyPanelBaseInput_PropertyPanelBaseInput_module['is-changed'], isConnected && PropertyPanelBaseInput_PropertyPanelBaseInput_module['is-connected'], hasHiddenCaret && PropertyPanelBaseInput_PropertyPanelBaseInput_module['has-hidden-caret'], isFauxFocused && PropertyPanelBaseInput_PropertyPanelBaseInput_module['is-faux-focused'], hasSmallText && PropertyPanelBaseInput_PropertyPanelBaseInput_module['has-small-text']), type: type, value: value, onChange: (e) => onChange(e.target.value), onClick: onClick, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, onFocus: onFocus, onBlur: onBlur, onKeyDown: onKeyDown }));
}

;// ../noodl-core-ui/src/components/property-panel/PropertyPanelBaseInput/index.ts



/***/ }),

/***/ 98819:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
/* ---------- DiffEditor ---------- */

.monaco-diff-editor .diffOverview {
	z-index: 9;
}

.monaco-diff-editor .diffOverview .diffViewport {
	z-index: 10;
}

/* colors not externalized: using transparancy on background */
.monaco-diff-editor.vs			.diffOverview { background: rgba(0, 0, 0, 0.03); }
.monaco-diff-editor.vs-dark		.diffOverview { background: rgba(255, 255, 255, 0.01); }

.monaco-scrollable-element.modified-in-monaco-diff-editor.vs		.scrollbar { background: rgba(0,0,0,0); }
.monaco-scrollable-element.modified-in-monaco-diff-editor.vs-dark	.scrollbar { background: rgba(0,0,0,0); }
.monaco-scrollable-element.modified-in-monaco-diff-editor.hc-black	.scrollbar { background: none; }
.monaco-scrollable-element.modified-in-monaco-diff-editor.hc-light	.scrollbar { background: none; }

.monaco-scrollable-element.modified-in-monaco-diff-editor .slider {
	z-index: 10;
}
.modified-in-monaco-diff-editor				.slider.active { background: rgba(171, 171, 171, .4); }
.modified-in-monaco-diff-editor.hc-black	.slider.active { background: none; }
.modified-in-monaco-diff-editor.hc-light	.slider.active { background: none; }

/* ---------- Diff ---------- */

.monaco-editor .insert-sign,
.monaco-diff-editor .insert-sign,
.monaco-editor .delete-sign,
.monaco-diff-editor .delete-sign {
	font-size: 11px !important;
	opacity: 0.7 !important;
	display: flex !important;
	align-items: center;
}
.monaco-editor.hc-black .insert-sign,
.monaco-diff-editor.hc-black .insert-sign,
.monaco-editor.hc-black .delete-sign,
.monaco-diff-editor.hc-black .delete-sign,
.monaco-editor.hc-light .insert-sign,
.monaco-diff-editor.hc-light .insert-sign,
.monaco-editor.hc-light .delete-sign,
.monaco-diff-editor.hc-light .delete-sign {
	opacity: 1;
}

.monaco-editor .inline-deleted-margin-view-zone {
	text-align: right;
}
.monaco-editor .inline-added-margin-view-zone {
	text-align: right;
}

.monaco-editor .arrow-revert-change {
	z-index: 10;
	position: absolute;
}

.monaco-editor .arrow-revert-change:hover {
	cursor: pointer;
}

/* ---------- Inline Diff ---------- */

.monaco-editor .view-zones .view-lines .view-line span {
	display: inline-block;
}

.monaco-editor .margin-view-zones .lightbulb-glyph:hover {
	cursor: pointer;
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/editor/browser/widget/media/diffEditor.css"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F,qCAAqC;;AAErC;CACC,UAAU;AACX;;AAEA;CACC,WAAW;AACZ;;AAEA,8DAA8D;AAC9D,yCAAyC,+BAA+B,EAAE;AAC1E,6CAA6C,qCAAqC,EAAE;;AAEpF,2EAA2E,yBAAyB,EAAE;AACtG,+EAA+E,yBAAyB,EAAE;AAC1G,gFAAgF,gBAAgB,EAAE;AAClG,gFAAgF,gBAAgB,EAAE;;AAElG;CACC,WAAW;AACZ;AACA,oDAAoD,mCAAmC,EAAE;AACzF,0DAA0D,gBAAgB,EAAE;AAC5E,0DAA0D,gBAAgB,EAAE;;AAE5E,+BAA+B;;AAE/B;;;;CAIC,0BAA0B;CAC1B,uBAAuB;CACvB,wBAAwB;CACxB,mBAAmB;AACpB;AACA;;;;;;;;CAQC,UAAU;AACX;;AAEA;CACC,iBAAiB;AAClB;AACA;CACC,iBAAiB;AAClB;;AAEA;CACC,WAAW;CACX,kBAAkB;AACnB;;AAEA;CACC,eAAe;AAChB;;AAEA,sCAAsC;;AAEtC;CACC,qBAAqB;AACtB;;AAEA;CACC,eAAe;AAChB","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/* ---------- DiffEditor ---------- */\n\n.monaco-diff-editor .diffOverview {\n\tz-index: 9;\n}\n\n.monaco-diff-editor .diffOverview .diffViewport {\n\tz-index: 10;\n}\n\n/* colors not externalized: using transparancy on background */\n.monaco-diff-editor.vs\t\t\t.diffOverview { background: rgba(0, 0, 0, 0.03); }\n.monaco-diff-editor.vs-dark\t\t.diffOverview { background: rgba(255, 255, 255, 0.01); }\n\n.monaco-scrollable-element.modified-in-monaco-diff-editor.vs\t\t.scrollbar { background: rgba(0,0,0,0); }\n.monaco-scrollable-element.modified-in-monaco-diff-editor.vs-dark\t.scrollbar { background: rgba(0,0,0,0); }\n.monaco-scrollable-element.modified-in-monaco-diff-editor.hc-black\t.scrollbar { background: none; }\n.monaco-scrollable-element.modified-in-monaco-diff-editor.hc-light\t.scrollbar { background: none; }\n\n.monaco-scrollable-element.modified-in-monaco-diff-editor .slider {\n\tz-index: 10;\n}\n.modified-in-monaco-diff-editor\t\t\t\t.slider.active { background: rgba(171, 171, 171, .4); }\n.modified-in-monaco-diff-editor.hc-black\t.slider.active { background: none; }\n.modified-in-monaco-diff-editor.hc-light\t.slider.active { background: none; }\n\n/* ---------- Diff ---------- */\n\n.monaco-editor .insert-sign,\n.monaco-diff-editor .insert-sign,\n.monaco-editor .delete-sign,\n.monaco-diff-editor .delete-sign {\n\tfont-size: 11px !important;\n\topacity: 0.7 !important;\n\tdisplay: flex !important;\n\talign-items: center;\n}\n.monaco-editor.hc-black .insert-sign,\n.monaco-diff-editor.hc-black .insert-sign,\n.monaco-editor.hc-black .delete-sign,\n.monaco-diff-editor.hc-black .delete-sign,\n.monaco-editor.hc-light .insert-sign,\n.monaco-diff-editor.hc-light .insert-sign,\n.monaco-editor.hc-light .delete-sign,\n.monaco-diff-editor.hc-light .delete-sign {\n\topacity: 1;\n}\n\n.monaco-editor .inline-deleted-margin-view-zone {\n\ttext-align: right;\n}\n.monaco-editor .inline-added-margin-view-zone {\n\ttext-align: right;\n}\n\n.monaco-editor .arrow-revert-change {\n\tz-index: 10;\n\tposition: absolute;\n}\n\n.monaco-editor .arrow-revert-change:hover {\n\tcursor: pointer;\n}\n\n/* ---------- Inline Diff ---------- */\n\n.monaco-editor .view-zones .view-lines .view-line span {\n\tdisplay: inline-block;\n}\n\n.monaco-editor .margin-view-zones .lightbulb-glyph:hover {\n\tcursor: pointer;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 98838:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/* -------------------------------------------------------------------
   Popup layer

   TODO: Clean up order of layers
   ------------------------------------------------------------------- */
.popup-layer {
  pointer-events: none;
  z-index: 10;
  background-color: transparent;
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
}

.popup-layer.dim {
  background-color: var(--base-color-black-transparent-50);
  transition: background-color 0.2s linear;
  pointer-events: all;
}

/* Enable pointer events when popouts are active (without dimming background)
   This allows clicking outside popouts to close them */
.popup-layer.has-popouts {
  pointer-events: all;
}

.popup-menu {
  background-color: var(--theme-color-bg-3);
}

.popup-layer-popup {
  background-color: var(--theme-color-bg-4);
  filter: drop-shadow(0 4px 15px var(--theme-color-bg-1-transparent-2));
  box-shadow: 0 0 10px -5px var(--theme-color-bg-1-transparent-2);
  pointer-events: all;
  z-index: 2;
}

.popup-layer-popup-content {
  position: absolute;
}

.popup-layer-popup-arrow.top {
  bottom: 100%;
  left: 50%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-bottom-color: var(--theme-color-bg-3);
  border-width: 10px;
  margin-left: -10px;
}

.popup-layer-popup-arrow.right {
  left: 100%;
  top: 50%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-left-color: var(--theme-color-bg-4);
  border-width: 10px;
  margin-top: -10px;
}

.popup-layer-popup-arrow.bottom {
  top: 100%;
  left: 50%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-top-color: var(--theme-color-bg-4);
  border-width: 10px;
  margin-left: -10px;
}

.popup-layer-popup-arrow.left {
  right: 100%;
  top: 50%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-right-color: var(--theme-color-bg-4);
  border-width: 10px;
  margin-top: -10px;
}

.popup-layer-popup-arrow.dark {
  border-bottom-color: var(--base-color-black-transparent-70);
}

/** popout **/

.popup-layer-popout {
  background-color: var(--theme-color-bg-4);
  /* This filter breaks Chromium? causes an internal div in monaco to not be clipped by it's parent correctly, breaking mouse event when resizing */
  /* filter: drop-shadow(0 4px 15px var(--theme-color-bg-1-transparent-2)); */
  box-shadow: 0 5px 20px 5px var(--theme-color-bg-1-transparent);
  pointer-events: all;
  z-index: 2;
  display: inline;
}

.popup-layer-popout-content {
  display: inline-flex;
  flex-direction: column;
}

.popup-layer-popout-arrow.top {
  bottom: 100%;
  left: 50%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-bottom-color: var(--theme-color-bg-4);
  border-width: 10px;
  margin-left: -10px;
  transform: translateX(0);
}

.popup-layer-popout-arrow.right {
  left: 100%;
  top: 50%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-left-color: var(--theme-color-bg-5);
  border-width: 10px;
  margin-top: -10px;
}

.popup-layer-popout-arrow.bottom {
  top: 100%;
  left: 50%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-top-color: var(--theme-color-bg-5);
  border-width: 10px;
  margin-left: -10px;
}

.popup-layer-popout-arrow.left {
  right: 100%;
  top: 50%;
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-right-color: var(--theme-color-bg-5);
  border-width: 10px;
  margin-top: -10px;
}

/** modal **/

.popup-layer-modal {
  position: absolute;
  background-color: var(--theme-color-bg-3);
  filter: drop-shadow(0 4px 15px var(--theme-color-bg-1-transparent-2));
  box-shadow: 0 0 10px -5px var(--theme-color-bg-1-transparent-2);
  pointer-events: all;
  z-index: 21;
  top: 50%;
  left: 50%;
}

.popup-layer-react-modal {
  pointer-events: all;
  z-index: 2;
}

.popup-layer-popup-menu {
  min-width: 208px;
  cursor: default;
  background-color: var(--theme-color-bg-3);
  border-radius: 4px;
  padding: 4px 0;
}

.popup-layer-popup-menu-divider {
  height: 0px;
  border-top: 2px var(--theme-color-border-default) solid;
  margin-top: 3px;
  margin-bottom: 3px;
}

.popup-layer-toast {
  position: absolute;
  background-color: var(--base-color-black-transparent-70);
  border-radius: 3px;
  border-color: var(--base-color-black-transparent-70);
  border-width: 3px;
  padding: 5px;
  color: var(--theme-color-fg-highlight);
  opacity: 0;
  transition: opacity 500ms;
  font-size: 15px;
  z-index: 90;
}

.popup-layer-dragger {
  position: absolute;
  background-color: var(--base-color-black-transparent-80);
  border-radius: 3px;
  border-width: 3px;
  color: var(--theme-color-fg-highlight);
  font-size: 12px;
  -webkit-transition: opacity 0.25s ease-out;
  padding: 5px;
  opacity: 0;
  pointer-events: none;
  z-index: 1;
}

:root {
  --popup-layer-tooltip-border-color: var(--theme-color-border-default);
  --popup-layer-tooltip-background-color: var(--theme-color-bg-3);
}

.popup-layer-tooltip {
  box-sizing: border-box;
  font-weight: bold;
  background-color: var(--popup-layer-tooltip-background-color);
  border-radius: 2px;
  border-color: var(--popup-layer-tooltip-border-color);
  border-width: 1px;
  padding: 12px 16px;
  color: var(--theme-color-fg-default);
  position: absolute;
  opacity: 0;
  -webkit-transition: opacity 0.3s;
  pointer-events: none;
  z-index: 2000;
  box-shadow: -4px 4px 16px var(--base-color-black-transparent-30);
}

.popup-layer-tooltip-content {
  display: flex;
  flex-direction: column;
}

/* These classes are sent in HTML from the viewer */
.popup-layer-tooltip-content h3 {
  font-weight: bold;
  padding: 0;
  font-size: 12px;
  margin: 0;
}

.popup-layer-tooltip-content p {
  opacity: 0.75;
  margin: 4px 0 0 0;
  padding: 0;
  font-weight: normal;
  max-width: 268px;
}

.popup-layer-image-row {
  display: flex;
  margin-top: 20px;
  column-gap: 16px;
}

.popup-layer-image-item {
  display: flex;
  flex-grow: 1;
  flex-direction: column;
}

.popup-layer-image-item img {
  margin: 0 auto;
}

.popup-layer-image-item p {
  max-width: 128px; /* width of images */
  text-align: center;
}

.popup-layer-image-item h3 {
  margin-top: 4px;
  padding: 0;
  font-weight: normal;
  text-align: center;
}

/* Tooltip arrows */

.popup-layer-tooltip-arrow {
  border: solid transparent;
  content: ' ';
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-width: 5px;
}

.popup-layer-tooltip-arrow.bottom {
  bottom: 100%;
  left: 50%;
  border-bottom-color: var(--popup-layer-tooltip-border-color);
  margin-left: -5px;
}

.popup-layer-tooltip-arrow.left {
  left: 100%;
  top: 50%;
  border-left-color: var(--popup-layer-tooltip-border-color);
  margin-top: -5px;
}

.popup-layer-tooltip-arrow.top {
  top: 100%;
  left: 50%;
  border-top-color: var(--popup-layer-tooltip-border-color);
  margin-left: -5px;
}

.popup-layer-tooltip-arrow.right {
  right: 100%;
  top: 50%;
  border-right-color: var(--popup-layer-tooltip-border-color);
  margin-top: -5px;
}

.popup {
  padding-bottom: 3px;
  color: var(--theme-color-fg-default-shy);
}

.popup p {
  padding: 5px;
  margin: 0px;
}

.popup-group-label {
  display: block;
  color: var(--theme-color-fg-default);
  background-color: var(--theme-color-bg-4);
  padding: 5px;
}

.popup-text {
  display: block;
  color: var(--theme-color-fg-muted);
  margin-left: 5px;
  margin-right: 5px;
}

.popup-file-drop {
  background-color: var(--theme-color-bg-0);
  opacity: 0.7;
  width: 100%;
  height: 100%;
}

.popup-file-drop-msg {
  margin: auto;
  color: var(--theme-color-fg-default-contrast);
  width: 400px;
  background-color: transparent;
  border-color: var(--theme-color-fg-default-shy);
  border-width: 2px;
  border-style: dashed;
  font-size: 20px;
  text-align: center;
  padding: 20px;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 25px;
}

.popup-layer-activity {
  position: absolute;
  background-color: var(--base-color-black-transparent-70);
  border-radius: 3px;
  border-color: var(--base-color-black-transparent-70);
  border-width: 3px;
  padding: 10px;
  color: var(--theme-color-fg-highlight);
  opacity: 0;
  transition: opacity 500ms;
  font-size: 15px;
  z-index: 90;
}

.popup-layer-activity-spinner {
  width: 100%;
  height: 100%;
  top: 0px;
  left: 0px;
  opacity: 0.7;
  margin: 0px;
}

.popup-layer-activity-progress {
  margin-left: 10px;
  margin-right: 10px;
  background-color: var(--theme-color-bg-0);
  opacity: 0.5;
  height: 10px;
  display: none;
}

.popup-layer-activity-progress-bar {
  width: 0%;
  height: 100%;
  background-color: var(--theme-color-fg-default);
}

.popup-title {
  display: block;
  color: var(--theme-color-fg-default-shy);
  margin-left: 5px;
  margin-right: 5px;
}

.popup-title > strong {
  color: var(--theme-color-fg-default);
}

.popup-message {
  display: block;
  color: var(--theme-color-fg-default-shy);
  margin-left: 5px;
  margin-right: 5px;
}

.popup-message > strong {
  color: var(--theme-color-fg-default-contrast);
}

.popup-button {
  border: none;
  padding: 0px;
  background-color: var(--theme-color-notice);
  color: var(--theme-color-bg-2);
  padding: 2px 15px 2px 15px;
  font-size: 12px;
  text-transform: uppercase;
}

.popup-button:hover {
  background-color: var(--theme-color-notice-hover);
}

.popup-button-grey {
  border: none;
  padding: 0px;
  background-color: var(--theme-color-bg-5);
  color: var(--theme-color-fg-default-shy);
  padding: 2px 15px 2px 15px;
  font-size: 12px;
  text-transform: uppercase;
}

.popup-button-grey:hover {
  background-color: var(--theme-color-border-strong);
}

.popup-small-docs {
  position: absolute;
  background-color: var(--theme-color-bg-2);
  z-index: 2;
  bottom: 2px;
}

/* Confim modal */
.confirm-modal {
  color: var(--theme-color-fg-default);
  max-width: 70vw;
  max-height: 70vh;
  overflow-y: auto;
}

.confirm-modal label {
  display: block;
  background-color: var(--theme-color-bg-4);
  padding: 5px 10px;
}

.confirm-modal p {
  margin: 16px 16px;
  padding: 0;
}

.confirm-modal .confirm-buttons {
  display: flex;
  gap: 16px;
  margin: 16px 16px;
}

.confirm-modal button {
  line-height: 24px;
  border: none;
  padding: 0px 16px;
  font-weight: 600;
}

.confirm-modal .confirm-button {
  background-color: var(--theme-color-primary);
  color: var(--theme-color-bg-2);
}

.confirm-modal .confirm-button:hover {
  background-color: var(--theme-color-primary-hover);
}

.confirm-modal .cancel-button {
  background-color: var(--theme-color-bg-2);
  color: var(--theme-color-fg-default);
}

.confirm-modal .cancel-button:hover {
  background-color: var(--theme-color-bg-3);
}

/* String Input Popup */
.string-input-popup {
  padding: 16px;
  width: 500px;
  min-width: 400px;
  max-width: 600px;
}

.string-input-popup-label {
  display: block;
  color: var(--theme-color-fg-default);
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 12px;
}

.string-input-popup-editor-wrapper {
  position: relative;
  display: flex;
  background-color: var(--theme-color-bg-1);
  border: 1px solid var(--theme-color-border-default);
  border-radius: 4px;
  overflow: hidden;
  /* Fixed height to prevent modal from growing */
  height: 200px;
  max-height: 200px;
}

.string-input-popup-line-numbers {
  flex-shrink: 0;
  /* Match textarea padding exactly for alignment */
  padding: 12px 8px 12px 12px;
  background-color: var(--theme-color-bg-2);
  border-right: 1px solid var(--theme-color-border-default);
  color: var(--theme-color-fg-muted);
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 13px;
  line-height: 20.8px;
  text-align: right;
  user-select: none;
  pointer-events: none;
  min-width: 36px;
  /* Allow scroll sync - hide scrollbar but allow scrollTop changes */
  overflow-y: scroll;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
  white-space: pre;
}

/* Hide scrollbar for line numbers in WebKit browsers */
.string-input-popup-line-numbers::-webkit-scrollbar {
  display: none;
}

.string-input-popup-textarea {
  flex: 1;
  /* Fill the fixed-height wrapper */
  height: 100%;
  padding: 12px;
  background-color: transparent;
  border: none;
  border-radius: 0;
  color: var(--theme-color-fg-default);
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 13px;
  line-height: 20.8px;
  resize: none;
  box-sizing: border-box;
  outline: none;
  overflow-y: auto;
}

.string-input-popup-textarea:focus {
  outline: none;
  border-color: var(--theme-color-primary);
  box-shadow: 0 0 0 2px var(--theme-color-primary-transparent);
}

.string-input-popup-textarea::placeholder {
  color: var(--theme-color-fg-muted);
  font-style: italic;
}

.string-input-popup-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 16px;
}

.string-input-popup-button-ok,
.string-input-popup-button-cancel {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.15s ease;
}

.string-input-popup-button-ok {
  background-color: var(--theme-color-primary);
  color: var(--theme-color-bg-2);
}

.string-input-popup-button-ok:hover {
  background-color: var(--theme-color-primary-hover);
}

.string-input-popup-button-cancel {
  background-color: var(--theme-color-bg-4);
  color: var(--theme-color-fg-default);
}

.string-input-popup-button-cancel:hover {
  background-color: var(--theme-color-bg-5);
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/styles/popuplayer.css"],"names":[],"mappings":"AAAA;;;;wEAIwE;AACxE;EACE,oBAAoB;EACpB,WAAW;EACX,6BAA6B;EAC7B,YAAY;EACZ,aAAa;EACb,eAAe;EACf,MAAM;EACN,OAAO;AACT;;AAEA;EACE,wDAAwD;EACxD,wCAAwC;EACxC,mBAAmB;AACrB;;AAEA;uDACuD;AACvD;EACE,mBAAmB;AACrB;;AAEA;EACE,yCAAyC;AAC3C;;AAEA;EACE,yCAAyC;EACzC,qEAAqE;EACrE,+DAA+D;EAC/D,mBAAmB;EACnB,UAAU;AACZ;;AAEA;EACE,kBAAkB;AACpB;;AAEA;EACE,YAAY;EACZ,SAAS;EACT,yBAAyB;EACzB,YAAY;EACZ,SAAS;EACT,QAAQ;EACR,kBAAkB;EAClB,oBAAoB;EACpB,4CAA4C;EAC5C,kBAAkB;EAClB,kBAAkB;AACpB;;AAEA;EACE,UAAU;EACV,QAAQ;EACR,yBAAyB;EACzB,YAAY;EACZ,SAAS;EACT,QAAQ;EACR,kBAAkB;EAClB,oBAAoB;EACpB,0CAA0C;EAC1C,kBAAkB;EAClB,iBAAiB;AACnB;;AAEA;EACE,SAAS;EACT,SAAS;EACT,yBAAyB;EACzB,YAAY;EACZ,SAAS;EACT,QAAQ;EACR,kBAAkB;EAClB,oBAAoB;EACpB,yCAAyC;EACzC,kBAAkB;EAClB,kBAAkB;AACpB;;AAEA;EACE,WAAW;EACX,QAAQ;EACR,yBAAyB;EACzB,YAAY;EACZ,SAAS;EACT,QAAQ;EACR,kBAAkB;EAClB,oBAAoB;EACpB,2CAA2C;EAC3C,kBAAkB;EAClB,iBAAiB;AACnB;;AAEA;EACE,2DAA2D;AAC7D;;AAEA,aAAa;;AAEb;EACE,yCAAyC;EACzC,iJAAiJ;EACjJ,2EAA2E;EAC3E,8DAA8D;EAC9D,mBAAmB;EACnB,UAAU;EACV,eAAe;AACjB;;AAEA;EACE,oBAAoB;EACpB,sBAAsB;AACxB;;AAEA;EACE,YAAY;EACZ,SAAS;EACT,yBAAyB;EACzB,YAAY;EACZ,SAAS;EACT,QAAQ;EACR,kBAAkB;EAClB,oBAAoB;EACpB,4CAA4C;EAC5C,kBAAkB;EAClB,kBAAkB;EAClB,wBAAwB;AAC1B;;AAEA;EACE,UAAU;EACV,QAAQ;EACR,yBAAyB;EACzB,YAAY;EACZ,SAAS;EACT,QAAQ;EACR,kBAAkB;EAClB,oBAAoB;EACpB,0CAA0C;EAC1C,kBAAkB;EAClB,iBAAiB;AACnB;;AAEA;EACE,SAAS;EACT,SAAS;EACT,yBAAyB;EACzB,YAAY;EACZ,SAAS;EACT,QAAQ;EACR,kBAAkB;EAClB,oBAAoB;EACpB,yCAAyC;EACzC,kBAAkB;EAClB,kBAAkB;AACpB;;AAEA;EACE,WAAW;EACX,QAAQ;EACR,yBAAyB;EACzB,YAAY;EACZ,SAAS;EACT,QAAQ;EACR,kBAAkB;EAClB,oBAAoB;EACpB,2CAA2C;EAC3C,kBAAkB;EAClB,iBAAiB;AACnB;;AAEA,YAAY;;AAEZ;EACE,kBAAkB;EAClB,yCAAyC;EACzC,qEAAqE;EACrE,+DAA+D;EAC/D,mBAAmB;EACnB,WAAW;EACX,QAAQ;EACR,SAAS;AACX;;AAEA;EACE,mBAAmB;EACnB,UAAU;AACZ;;AAEA;EACE,gBAAgB;EAChB,eAAe;EACf,yCAAyC;EACzC,kBAAkB;EAClB,cAAc;AAChB;;AAEA;EACE,WAAW;EACX,uDAAuD;EACvD,eAAe;EACf,kBAAkB;AACpB;;AAEA;EACE,kBAAkB;EAClB,wDAAwD;EACxD,kBAAkB;EAClB,oDAAoD;EACpD,iBAAiB;EACjB,YAAY;EACZ,sCAAsC;EACtC,UAAU;EACV,yBAAyB;EACzB,eAAe;EACf,WAAW;AACb;;AAEA;EACE,kBAAkB;EAClB,wDAAwD;EACxD,kBAAkB;EAClB,iBAAiB;EACjB,sCAAsC;EACtC,eAAe;EACf,0CAA0C;EAC1C,YAAY;EACZ,UAAU;EACV,oBAAoB;EACpB,UAAU;AACZ;;AAEA;EACE,qEAAqE;EACrE,+DAA+D;AACjE;;AAEA;EACE,sBAAsB;EACtB,iBAAiB;EACjB,6DAA6D;EAC7D,kBAAkB;EAClB,qDAAqD;EACrD,iBAAiB;EACjB,kBAAkB;EAClB,oCAAoC;EACpC,kBAAkB;EAClB,UAAU;EACV,gCAAgC;EAChC,oBAAoB;EACpB,aAAa;EACb,gEAAgE;AAClE;;AAEA;EACE,aAAa;EACb,sBAAsB;AACxB;;AAEA,mDAAmD;AACnD;EACE,iBAAiB;EACjB,UAAU;EACV,eAAe;EACf,SAAS;AACX;;AAEA;EACE,aAAa;EACb,iBAAiB;EACjB,UAAU;EACV,mBAAmB;EACnB,gBAAgB;AAClB;;AAEA;EACE,aAAa;EACb,gBAAgB;EAChB,gBAAgB;AAClB;;AAEA;EACE,aAAa;EACb,YAAY;EACZ,sBAAsB;AACxB;;AAEA;EACE,cAAc;AAChB;;AAEA;EACE,gBAAgB,EAAE,oBAAoB;EACtC,kBAAkB;AACpB;;AAEA;EACE,eAAe;EACf,UAAU;EACV,mBAAmB;EACnB,kBAAkB;AACpB;;AAEA,mBAAmB;;AAEnB;EACE,yBAAyB;EACzB,YAAY;EACZ,SAAS;EACT,QAAQ;EACR,kBAAkB;EAClB,oBAAoB;EACpB,iBAAiB;AACnB;;AAEA;EACE,YAAY;EACZ,SAAS;EACT,4DAA4D;EAC5D,iBAAiB;AACnB;;AAEA;EACE,UAAU;EACV,QAAQ;EACR,0DAA0D;EAC1D,gBAAgB;AAClB;;AAEA;EACE,SAAS;EACT,SAAS;EACT,yDAAyD;EACzD,iBAAiB;AACnB;;AAEA;EACE,WAAW;EACX,QAAQ;EACR,2DAA2D;EAC3D,gBAAgB;AAClB;;AAEA;EACE,mBAAmB;EACnB,wCAAwC;AAC1C;;AAEA;EACE,YAAY;EACZ,WAAW;AACb;;AAEA;EACE,cAAc;EACd,oCAAoC;EACpC,yCAAyC;EACzC,YAAY;AACd;;AAEA;EACE,cAAc;EACd,kCAAkC;EAClC,gBAAgB;EAChB,iBAAiB;AACnB;;AAEA;EACE,yCAAyC;EACzC,YAAY;EACZ,WAAW;EACX,YAAY;AACd;;AAEA;EACE,YAAY;EACZ,6CAA6C;EAC7C,YAAY;EACZ,6BAA6B;EAC7B,+CAA+C;EAC/C,iBAAiB;EACjB,oBAAoB;EACpB,eAAe;EACf,kBAAkB;EAClB,aAAa;EACb,kBAAkB;EAClB,MAAM;EACN,OAAO;EACP,SAAS;EACT,QAAQ;EACR,YAAY;AACd;;AAEA;EACE,kBAAkB;EAClB,wDAAwD;EACxD,kBAAkB;EAClB,oDAAoD;EACpD,iBAAiB;EACjB,aAAa;EACb,sCAAsC;EACtC,UAAU;EACV,yBAAyB;EACzB,eAAe;EACf,WAAW;AACb;;AAEA;EACE,WAAW;EACX,YAAY;EACZ,QAAQ;EACR,SAAS;EACT,YAAY;EACZ,WAAW;AACb;;AAEA;EACE,iBAAiB;EACjB,kBAAkB;EAClB,yCAAyC;EACzC,YAAY;EACZ,YAAY;EACZ,aAAa;AACf;;AAEA;EACE,SAAS;EACT,YAAY;EACZ,+CAA+C;AACjD;;AAEA;EACE,cAAc;EACd,wCAAwC;EACxC,gBAAgB;EAChB,iBAAiB;AACnB;;AAEA;EACE,oCAAoC;AACtC;;AAEA;EACE,cAAc;EACd,wCAAwC;EACxC,gBAAgB;EAChB,iBAAiB;AACnB;;AAEA;EACE,6CAA6C;AAC/C;;AAEA;EACE,YAAY;EACZ,YAAY;EACZ,2CAA2C;EAC3C,8BAA8B;EAC9B,0BAA0B;EAC1B,eAAe;EACf,yBAAyB;AAC3B;;AAEA;EACE,iDAAiD;AACnD;;AAEA;EACE,YAAY;EACZ,YAAY;EACZ,yCAAyC;EACzC,wCAAwC;EACxC,0BAA0B;EAC1B,eAAe;EACf,yBAAyB;AAC3B;;AAEA;EACE,kDAAkD;AACpD;;AAEA;EACE,kBAAkB;EAClB,yCAAyC;EACzC,UAAU;EACV,WAAW;AACb;;AAEA,iBAAiB;AACjB;EACE,oCAAoC;EACpC,eAAe;EACf,gBAAgB;EAChB,gBAAgB;AAClB;;AAEA;EACE,cAAc;EACd,yCAAyC;EACzC,iBAAiB;AACnB;;AAEA;EACE,iBAAiB;EACjB,UAAU;AACZ;;AAEA;EACE,aAAa;EACb,SAAS;EACT,iBAAiB;AACnB;;AAEA;EACE,iBAAiB;EACjB,YAAY;EACZ,iBAAiB;EACjB,gBAAgB;AAClB;;AAEA;EACE,4CAA4C;EAC5C,8BAA8B;AAChC;;AAEA;EACE,kDAAkD;AACpD;;AAEA;EACE,yCAAyC;EACzC,oCAAoC;AACtC;;AAEA;EACE,yCAAyC;AAC3C;;AAEA,uBAAuB;AACvB;EACE,aAAa;EACb,YAAY;EACZ,gBAAgB;EAChB,gBAAgB;AAClB;;AAEA;EACE,cAAc;EACd,oCAAoC;EACpC,eAAe;EACf,gBAAgB;EAChB,mBAAmB;AACrB;;AAEA;EACE,kBAAkB;EAClB,aAAa;EACb,yCAAyC;EACzC,mDAAmD;EACnD,kBAAkB;EAClB,gBAAgB;EAChB,+CAA+C;EAC/C,aAAa;EACb,iBAAiB;AACnB;;AAEA;EACE,cAAc;EACd,iDAAiD;EACjD,2BAA2B;EAC3B,yCAAyC;EACzC,yDAAyD;EACzD,kCAAkC;EAClC,uFAAuF;EACvF,eAAe;EACf,mBAAmB;EACnB,iBAAiB;EACjB,iBAAiB;EACjB,oBAAoB;EACpB,eAAe;EACf,mEAAmE;EACnE,kBAAkB;EAClB,qBAAqB,EAAE,YAAY;EACnC,wBAAwB,EAAE,YAAY;EACtC,gBAAgB;AAClB;;AAEA,uDAAuD;AACvD;EACE,aAAa;AACf;;AAEA;EACE,OAAO;EACP,kCAAkC;EAClC,YAAY;EACZ,aAAa;EACb,6BAA6B;EAC7B,YAAY;EACZ,gBAAgB;EAChB,oCAAoC;EACpC,uFAAuF;EACvF,eAAe;EACf,mBAAmB;EACnB,YAAY;EACZ,sBAAsB;EACtB,aAAa;EACb,gBAAgB;AAClB;;AAEA;EACE,aAAa;EACb,wCAAwC;EACxC,4DAA4D;AAC9D;;AAEA;EACE,kCAAkC;EAClC,kBAAkB;AACpB;;AAEA;EACE,aAAa;EACb,QAAQ;EACR,yBAAyB;EACzB,gBAAgB;AAClB;;AAEA;;EAEE,iBAAiB;EACjB,YAAY;EACZ,kBAAkB;EAClB,eAAe;EACf,gBAAgB;EAChB,eAAe;EACf,uCAAuC;AACzC;;AAEA;EACE,4CAA4C;EAC5C,8BAA8B;AAChC;;AAEA;EACE,kDAAkD;AACpD;;AAEA;EACE,yCAAyC;EACzC,oCAAoC;AACtC;;AAEA;EACE,yCAAyC;AAC3C","sourcesContent":["/* -------------------------------------------------------------------\n   Popup layer\n\n   TODO: Clean up order of layers\n   ------------------------------------------------------------------- */\n.popup-layer {\n  pointer-events: none;\n  z-index: 10;\n  background-color: transparent;\n  width: 100vw;\n  height: 100vh;\n  position: fixed;\n  top: 0;\n  left: 0;\n}\n\n.popup-layer.dim {\n  background-color: var(--base-color-black-transparent-50);\n  transition: background-color 0.2s linear;\n  pointer-events: all;\n}\n\n/* Enable pointer events when popouts are active (without dimming background)\n   This allows clicking outside popouts to close them */\n.popup-layer.has-popouts {\n  pointer-events: all;\n}\n\n.popup-menu {\n  background-color: var(--theme-color-bg-3);\n}\n\n.popup-layer-popup {\n  background-color: var(--theme-color-bg-4);\n  filter: drop-shadow(0 4px 15px var(--theme-color-bg-1-transparent-2));\n  box-shadow: 0 0 10px -5px var(--theme-color-bg-1-transparent-2);\n  pointer-events: all;\n  z-index: 2;\n}\n\n.popup-layer-popup-content {\n  position: absolute;\n}\n\n.popup-layer-popup-arrow.top {\n  bottom: 100%;\n  left: 50%;\n  border: solid transparent;\n  content: ' ';\n  height: 0;\n  width: 0;\n  position: absolute;\n  pointer-events: none;\n  border-bottom-color: var(--theme-color-bg-3);\n  border-width: 10px;\n  margin-left: -10px;\n}\n\n.popup-layer-popup-arrow.right {\n  left: 100%;\n  top: 50%;\n  border: solid transparent;\n  content: ' ';\n  height: 0;\n  width: 0;\n  position: absolute;\n  pointer-events: none;\n  border-left-color: var(--theme-color-bg-4);\n  border-width: 10px;\n  margin-top: -10px;\n}\n\n.popup-layer-popup-arrow.bottom {\n  top: 100%;\n  left: 50%;\n  border: solid transparent;\n  content: ' ';\n  height: 0;\n  width: 0;\n  position: absolute;\n  pointer-events: none;\n  border-top-color: var(--theme-color-bg-4);\n  border-width: 10px;\n  margin-left: -10px;\n}\n\n.popup-layer-popup-arrow.left {\n  right: 100%;\n  top: 50%;\n  border: solid transparent;\n  content: ' ';\n  height: 0;\n  width: 0;\n  position: absolute;\n  pointer-events: none;\n  border-right-color: var(--theme-color-bg-4);\n  border-width: 10px;\n  margin-top: -10px;\n}\n\n.popup-layer-popup-arrow.dark {\n  border-bottom-color: var(--base-color-black-transparent-70);\n}\n\n/** popout **/\n\n.popup-layer-popout {\n  background-color: var(--theme-color-bg-4);\n  /* This filter breaks Chromium? causes an internal div in monaco to not be clipped by it's parent correctly, breaking mouse event when resizing */\n  /* filter: drop-shadow(0 4px 15px var(--theme-color-bg-1-transparent-2)); */\n  box-shadow: 0 5px 20px 5px var(--theme-color-bg-1-transparent);\n  pointer-events: all;\n  z-index: 2;\n  display: inline;\n}\n\n.popup-layer-popout-content {\n  display: inline-flex;\n  flex-direction: column;\n}\n\n.popup-layer-popout-arrow.top {\n  bottom: 100%;\n  left: 50%;\n  border: solid transparent;\n  content: ' ';\n  height: 0;\n  width: 0;\n  position: absolute;\n  pointer-events: none;\n  border-bottom-color: var(--theme-color-bg-4);\n  border-width: 10px;\n  margin-left: -10px;\n  transform: translateX(0);\n}\n\n.popup-layer-popout-arrow.right {\n  left: 100%;\n  top: 50%;\n  border: solid transparent;\n  content: ' ';\n  height: 0;\n  width: 0;\n  position: absolute;\n  pointer-events: none;\n  border-left-color: var(--theme-color-bg-5);\n  border-width: 10px;\n  margin-top: -10px;\n}\n\n.popup-layer-popout-arrow.bottom {\n  top: 100%;\n  left: 50%;\n  border: solid transparent;\n  content: ' ';\n  height: 0;\n  width: 0;\n  position: absolute;\n  pointer-events: none;\n  border-top-color: var(--theme-color-bg-5);\n  border-width: 10px;\n  margin-left: -10px;\n}\n\n.popup-layer-popout-arrow.left {\n  right: 100%;\n  top: 50%;\n  border: solid transparent;\n  content: ' ';\n  height: 0;\n  width: 0;\n  position: absolute;\n  pointer-events: none;\n  border-right-color: var(--theme-color-bg-5);\n  border-width: 10px;\n  margin-top: -10px;\n}\n\n/** modal **/\n\n.popup-layer-modal {\n  position: absolute;\n  background-color: var(--theme-color-bg-3);\n  filter: drop-shadow(0 4px 15px var(--theme-color-bg-1-transparent-2));\n  box-shadow: 0 0 10px -5px var(--theme-color-bg-1-transparent-2);\n  pointer-events: all;\n  z-index: 21;\n  top: 50%;\n  left: 50%;\n}\n\n.popup-layer-react-modal {\n  pointer-events: all;\n  z-index: 2;\n}\n\n.popup-layer-popup-menu {\n  min-width: 208px;\n  cursor: default;\n  background-color: var(--theme-color-bg-3);\n  border-radius: 4px;\n  padding: 4px 0;\n}\n\n.popup-layer-popup-menu-divider {\n  height: 0px;\n  border-top: 2px var(--theme-color-border-default) solid;\n  margin-top: 3px;\n  margin-bottom: 3px;\n}\n\n.popup-layer-toast {\n  position: absolute;\n  background-color: var(--base-color-black-transparent-70);\n  border-radius: 3px;\n  border-color: var(--base-color-black-transparent-70);\n  border-width: 3px;\n  padding: 5px;\n  color: var(--theme-color-fg-highlight);\n  opacity: 0;\n  transition: opacity 500ms;\n  font-size: 15px;\n  z-index: 90;\n}\n\n.popup-layer-dragger {\n  position: absolute;\n  background-color: var(--base-color-black-transparent-80);\n  border-radius: 3px;\n  border-width: 3px;\n  color: var(--theme-color-fg-highlight);\n  font-size: 12px;\n  -webkit-transition: opacity 0.25s ease-out;\n  padding: 5px;\n  opacity: 0;\n  pointer-events: none;\n  z-index: 1;\n}\n\n:root {\n  --popup-layer-tooltip-border-color: var(--theme-color-border-default);\n  --popup-layer-tooltip-background-color: var(--theme-color-bg-3);\n}\n\n.popup-layer-tooltip {\n  box-sizing: border-box;\n  font-weight: bold;\n  background-color: var(--popup-layer-tooltip-background-color);\n  border-radius: 2px;\n  border-color: var(--popup-layer-tooltip-border-color);\n  border-width: 1px;\n  padding: 12px 16px;\n  color: var(--theme-color-fg-default);\n  position: absolute;\n  opacity: 0;\n  -webkit-transition: opacity 0.3s;\n  pointer-events: none;\n  z-index: 2000;\n  box-shadow: -4px 4px 16px var(--base-color-black-transparent-30);\n}\n\n.popup-layer-tooltip-content {\n  display: flex;\n  flex-direction: column;\n}\n\n/* These classes are sent in HTML from the viewer */\n.popup-layer-tooltip-content h3 {\n  font-weight: bold;\n  padding: 0;\n  font-size: 12px;\n  margin: 0;\n}\n\n.popup-layer-tooltip-content p {\n  opacity: 0.75;\n  margin: 4px 0 0 0;\n  padding: 0;\n  font-weight: normal;\n  max-width: 268px;\n}\n\n.popup-layer-image-row {\n  display: flex;\n  margin-top: 20px;\n  column-gap: 16px;\n}\n\n.popup-layer-image-item {\n  display: flex;\n  flex-grow: 1;\n  flex-direction: column;\n}\n\n.popup-layer-image-item img {\n  margin: 0 auto;\n}\n\n.popup-layer-image-item p {\n  max-width: 128px; /* width of images */\n  text-align: center;\n}\n\n.popup-layer-image-item h3 {\n  margin-top: 4px;\n  padding: 0;\n  font-weight: normal;\n  text-align: center;\n}\n\n/* Tooltip arrows */\n\n.popup-layer-tooltip-arrow {\n  border: solid transparent;\n  content: ' ';\n  height: 0;\n  width: 0;\n  position: absolute;\n  pointer-events: none;\n  border-width: 5px;\n}\n\n.popup-layer-tooltip-arrow.bottom {\n  bottom: 100%;\n  left: 50%;\n  border-bottom-color: var(--popup-layer-tooltip-border-color);\n  margin-left: -5px;\n}\n\n.popup-layer-tooltip-arrow.left {\n  left: 100%;\n  top: 50%;\n  border-left-color: var(--popup-layer-tooltip-border-color);\n  margin-top: -5px;\n}\n\n.popup-layer-tooltip-arrow.top {\n  top: 100%;\n  left: 50%;\n  border-top-color: var(--popup-layer-tooltip-border-color);\n  margin-left: -5px;\n}\n\n.popup-layer-tooltip-arrow.right {\n  right: 100%;\n  top: 50%;\n  border-right-color: var(--popup-layer-tooltip-border-color);\n  margin-top: -5px;\n}\n\n.popup {\n  padding-bottom: 3px;\n  color: var(--theme-color-fg-default-shy);\n}\n\n.popup p {\n  padding: 5px;\n  margin: 0px;\n}\n\n.popup-group-label {\n  display: block;\n  color: var(--theme-color-fg-default);\n  background-color: var(--theme-color-bg-4);\n  padding: 5px;\n}\n\n.popup-text {\n  display: block;\n  color: var(--theme-color-fg-muted);\n  margin-left: 5px;\n  margin-right: 5px;\n}\n\n.popup-file-drop {\n  background-color: var(--theme-color-bg-0);\n  opacity: 0.7;\n  width: 100%;\n  height: 100%;\n}\n\n.popup-file-drop-msg {\n  margin: auto;\n  color: var(--theme-color-fg-default-contrast);\n  width: 400px;\n  background-color: transparent;\n  border-color: var(--theme-color-fg-default-shy);\n  border-width: 2px;\n  border-style: dashed;\n  font-size: 20px;\n  text-align: center;\n  padding: 20px;\n  position: absolute;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n  height: 25px;\n}\n\n.popup-layer-activity {\n  position: absolute;\n  background-color: var(--base-color-black-transparent-70);\n  border-radius: 3px;\n  border-color: var(--base-color-black-transparent-70);\n  border-width: 3px;\n  padding: 10px;\n  color: var(--theme-color-fg-highlight);\n  opacity: 0;\n  transition: opacity 500ms;\n  font-size: 15px;\n  z-index: 90;\n}\n\n.popup-layer-activity-spinner {\n  width: 100%;\n  height: 100%;\n  top: 0px;\n  left: 0px;\n  opacity: 0.7;\n  margin: 0px;\n}\n\n.popup-layer-activity-progress {\n  margin-left: 10px;\n  margin-right: 10px;\n  background-color: var(--theme-color-bg-0);\n  opacity: 0.5;\n  height: 10px;\n  display: none;\n}\n\n.popup-layer-activity-progress-bar {\n  width: 0%;\n  height: 100%;\n  background-color: var(--theme-color-fg-default);\n}\n\n.popup-title {\n  display: block;\n  color: var(--theme-color-fg-default-shy);\n  margin-left: 5px;\n  margin-right: 5px;\n}\n\n.popup-title > strong {\n  color: var(--theme-color-fg-default);\n}\n\n.popup-message {\n  display: block;\n  color: var(--theme-color-fg-default-shy);\n  margin-left: 5px;\n  margin-right: 5px;\n}\n\n.popup-message > strong {\n  color: var(--theme-color-fg-default-contrast);\n}\n\n.popup-button {\n  border: none;\n  padding: 0px;\n  background-color: var(--theme-color-notice);\n  color: var(--theme-color-bg-2);\n  padding: 2px 15px 2px 15px;\n  font-size: 12px;\n  text-transform: uppercase;\n}\n\n.popup-button:hover {\n  background-color: var(--theme-color-notice-hover);\n}\n\n.popup-button-grey {\n  border: none;\n  padding: 0px;\n  background-color: var(--theme-color-bg-5);\n  color: var(--theme-color-fg-default-shy);\n  padding: 2px 15px 2px 15px;\n  font-size: 12px;\n  text-transform: uppercase;\n}\n\n.popup-button-grey:hover {\n  background-color: var(--theme-color-border-strong);\n}\n\n.popup-small-docs {\n  position: absolute;\n  background-color: var(--theme-color-bg-2);\n  z-index: 2;\n  bottom: 2px;\n}\n\n/* Confim modal */\n.confirm-modal {\n  color: var(--theme-color-fg-default);\n  max-width: 70vw;\n  max-height: 70vh;\n  overflow-y: auto;\n}\n\n.confirm-modal label {\n  display: block;\n  background-color: var(--theme-color-bg-4);\n  padding: 5px 10px;\n}\n\n.confirm-modal p {\n  margin: 16px 16px;\n  padding: 0;\n}\n\n.confirm-modal .confirm-buttons {\n  display: flex;\n  gap: 16px;\n  margin: 16px 16px;\n}\n\n.confirm-modal button {\n  line-height: 24px;\n  border: none;\n  padding: 0px 16px;\n  font-weight: 600;\n}\n\n.confirm-modal .confirm-button {\n  background-color: var(--theme-color-primary);\n  color: var(--theme-color-bg-2);\n}\n\n.confirm-modal .confirm-button:hover {\n  background-color: var(--theme-color-primary-hover);\n}\n\n.confirm-modal .cancel-button {\n  background-color: var(--theme-color-bg-2);\n  color: var(--theme-color-fg-default);\n}\n\n.confirm-modal .cancel-button:hover {\n  background-color: var(--theme-color-bg-3);\n}\n\n/* String Input Popup */\n.string-input-popup {\n  padding: 16px;\n  width: 500px;\n  min-width: 400px;\n  max-width: 600px;\n}\n\n.string-input-popup-label {\n  display: block;\n  color: var(--theme-color-fg-default);\n  font-size: 14px;\n  font-weight: 600;\n  margin-bottom: 12px;\n}\n\n.string-input-popup-editor-wrapper {\n  position: relative;\n  display: flex;\n  background-color: var(--theme-color-bg-1);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  overflow: hidden;\n  /* Fixed height to prevent modal from growing */\n  height: 200px;\n  max-height: 200px;\n}\n\n.string-input-popup-line-numbers {\n  flex-shrink: 0;\n  /* Match textarea padding exactly for alignment */\n  padding: 12px 8px 12px 12px;\n  background-color: var(--theme-color-bg-2);\n  border-right: 1px solid var(--theme-color-border-default);\n  color: var(--theme-color-fg-muted);\n  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\n  font-size: 13px;\n  line-height: 20.8px;\n  text-align: right;\n  user-select: none;\n  pointer-events: none;\n  min-width: 36px;\n  /* Allow scroll sync - hide scrollbar but allow scrollTop changes */\n  overflow-y: scroll;\n  scrollbar-width: none; /* Firefox */\n  -ms-overflow-style: none; /* IE/Edge */\n  white-space: pre;\n}\n\n/* Hide scrollbar for line numbers in WebKit browsers */\n.string-input-popup-line-numbers::-webkit-scrollbar {\n  display: none;\n}\n\n.string-input-popup-textarea {\n  flex: 1;\n  /* Fill the fixed-height wrapper */\n  height: 100%;\n  padding: 12px;\n  background-color: transparent;\n  border: none;\n  border-radius: 0;\n  color: var(--theme-color-fg-default);\n  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\n  font-size: 13px;\n  line-height: 20.8px;\n  resize: none;\n  box-sizing: border-box;\n  outline: none;\n  overflow-y: auto;\n}\n\n.string-input-popup-textarea:focus {\n  outline: none;\n  border-color: var(--theme-color-primary);\n  box-shadow: 0 0 0 2px var(--theme-color-primary-transparent);\n}\n\n.string-input-popup-textarea::placeholder {\n  color: var(--theme-color-fg-muted);\n  font-style: italic;\n}\n\n.string-input-popup-buttons {\n  display: flex;\n  gap: 8px;\n  justify-content: flex-end;\n  margin-top: 16px;\n}\n\n.string-input-popup-button-ok,\n.string-input-popup-button-cancel {\n  padding: 8px 20px;\n  border: none;\n  border-radius: 4px;\n  font-size: 13px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: background-color 0.15s ease;\n}\n\n.string-input-popup-button-ok {\n  background-color: var(--theme-color-primary);\n  color: var(--theme-color-bg-2);\n}\n\n.string-input-popup-button-ok:hover {\n  background-color: var(--theme-color-primary-hover);\n}\n\n.string-input-popup-button-cancel {\n  background-color: var(--theme-color-bg-4);\n  color: var(--theme-color-fg-default);\n}\n\n.string-input-popup-button-cancel:hover {\n  background-color: var(--theme-color-bg-5);\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 98849:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (/* binding */ useTimeout)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

function useTimeout(callback, delay) {
    const timeoutRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);
    const savedCallback = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(callback);
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        savedCallback.current = callback;
    }, [callback]);
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        const tick = () => savedCallback.current();
        if (typeof delay === 'number') {
            timeoutRef.current = window.setTimeout(tick, delay);
            return () => window.clearTimeout(timeoutRef.current);
        }
    }, [delay]);
    return timeoutRef;
}


/***/ }),

/***/ 98867:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgSquareFilled = function SvgSquareFilled(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M19.232 3.32147L4.76772 3.32147C3.96888 3.32147 3.32129 3.96906 3.32129 4.7679L3.32129 19.2322C3.32129 20.031 3.96888 20.6786 4.76772 20.6786L19.232 20.6786C20.0308 20.6786 20.6784 20.031 20.6784 19.2322L20.6784 4.7679C20.6784 3.96906 20.0308 3.32147 19.232 3.32147Z",
    fill: "#B8B8B8"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgSquareFilled);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "b6753d20fc2c7eb752c7680402093305.svg");

/***/ }),

/***/ 99003:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgMagicWand = function SvgMagicWand(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 20,
    height: 20,
    viewBox: "0 0 20 20",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    d: "M16.875 10V13.75M15 11.875H18.75M6.5625 3.125V6.25M5 4.6875H8.125M13.125 14.375V16.875M11.875 15.625H14.375M11.25 6.25L13.75 8.75M2.94713 14.5575L14.5647 2.93998C14.8087 2.6959 15.2045 2.6959 15.4486 2.93998L17.0644 4.55583C17.3085 4.79991 17.3085 5.19564 17.0644 5.43971L5.44686 17.0573C5.20278 17.3013 4.80705 17.3013 4.56298 17.0573L2.94713 15.4414C2.70305 15.1973 2.70305 14.8016 2.94713 14.5575Z",
    stroke: "#B8B8B8",
    strokeWidth: 1.36364,
    strokeLinecap: "round",
    strokeLinejoin: "round"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgMagicWand);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "1ffcc01b8126ee923d0a8b3f267ade91.svg");

/***/ }),

/***/ 99107:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createFunctionWithReturnValue = exports.getGlobal = exports.getCurrentWebContents = exports.getCurrentWindow = exports.getBuiltin = void 0;
const callbacks_registry_1 = __webpack_require__(76157);
const type_utils_1 = __webpack_require__(86543);
const electron_1 = __webpack_require__(91288);
const module_names_1 = __webpack_require__(56038);
const get_electron_binding_1 = __webpack_require__(25374);
const { Promise } = global;
const callbacksRegistry = new callbacks_registry_1.CallbacksRegistry();
const remoteObjectCache = new Map();
const finalizationRegistry = new FinalizationRegistry((id) => {
    const ref = remoteObjectCache.get(id);
    if (ref !== undefined && ref.deref() === undefined) {
        remoteObjectCache.delete(id);
        electron_1.ipcRenderer.send("REMOTE_BROWSER_DEREFERENCE" /* BROWSER_DEREFERENCE */, contextId, id, 0);
    }
});
const electronIds = new WeakMap();
const isReturnValue = new WeakSet();
function getCachedRemoteObject(id) {
    const ref = remoteObjectCache.get(id);
    if (ref !== undefined) {
        const deref = ref.deref();
        if (deref !== undefined)
            return deref;
    }
}
function setCachedRemoteObject(id, value) {
    const wr = new WeakRef(value);
    remoteObjectCache.set(id, wr);
    finalizationRegistry.register(value, id);
    return value;
}
function getContextId() {
    const v8Util = get_electron_binding_1.getElectronBinding('v8_util');
    if (v8Util) {
        return v8Util.getHiddenValue(global, 'contextId');
    }
    else {
        throw new Error('Electron >=v13.0.0-beta.6 required to support sandboxed renderers');
    }
}
// An unique ID that can represent current context.
const contextId = process.contextId || getContextId();
// Notify the main process when current context is going to be released.
// Note that when the renderer process is destroyed, the message may not be
// sent, we also listen to the "render-view-deleted" event in the main process
// to guard that situation.
process.on('exit', () => {
    const command = "REMOTE_BROWSER_CONTEXT_RELEASE" /* BROWSER_CONTEXT_RELEASE */;
    electron_1.ipcRenderer.send(command, contextId);
});
const IS_REMOTE_PROXY = Symbol('is-remote-proxy');
// Convert the arguments object into an array of meta data.
function wrapArgs(args, visited = new Set()) {
    const valueToMeta = (value) => {
        // Check for circular reference.
        if (visited.has(value)) {
            return {
                type: 'value',
                value: null
            };
        }
        if (value && value.constructor && value.constructor.name === 'NativeImage') {
            return { type: 'nativeimage', value: type_utils_1.serialize(value) };
        }
        else if (Array.isArray(value)) {
            visited.add(value);
            const meta = {
                type: 'array',
                value: wrapArgs(value, visited)
            };
            visited.delete(value);
            return meta;
        }
        else if (value instanceof Buffer) {
            return {
                type: 'buffer',
                value
            };
        }
        else if (type_utils_1.isSerializableObject(value)) {
            return {
                type: 'value',
                value
            };
        }
        else if (typeof value === 'object') {
            if (type_utils_1.isPromise(value)) {
                return {
                    type: 'promise',
                    then: valueToMeta(function (onFulfilled, onRejected) {
                        value.then(onFulfilled, onRejected);
                    })
                };
            }
            else if (electronIds.has(value)) {
                return {
                    type: 'remote-object',
                    id: electronIds.get(value)
                };
            }
            const meta = {
                type: 'object',
                name: value.constructor ? value.constructor.name : '',
                members: []
            };
            visited.add(value);
            for (const prop in value) { // eslint-disable-line guard-for-in
                meta.members.push({
                    name: prop,
                    value: valueToMeta(value[prop])
                });
            }
            visited.delete(value);
            return meta;
        }
        else if (typeof value === 'function' && isReturnValue.has(value)) {
            return {
                type: 'function-with-return-value',
                value: valueToMeta(value())
            };
        }
        else if (typeof value === 'function') {
            return {
                type: 'function',
                id: callbacksRegistry.add(value),
                location: callbacksRegistry.getLocation(value),
                length: value.length
            };
        }
        else {
            return {
                type: 'value',
                value
            };
        }
    };
    return args.map(valueToMeta);
}
// Populate object's members from descriptors.
// The |ref| will be kept referenced by |members|.
// This matches |getObjectMemebers| in rpc-server.
function setObjectMembers(ref, object, metaId, members) {
    if (!Array.isArray(members))
        return;
    for (const member of members) {
        if (Object.prototype.hasOwnProperty.call(object, member.name))
            continue;
        const descriptor = { enumerable: member.enumerable };
        if (member.type === 'method') {
            const remoteMemberFunction = function (...args) {
                let command;
                if (this && this.constructor === remoteMemberFunction) {
                    command = "REMOTE_BROWSER_MEMBER_CONSTRUCTOR" /* BROWSER_MEMBER_CONSTRUCTOR */;
                }
                else {
                    command = "REMOTE_BROWSER_MEMBER_CALL" /* BROWSER_MEMBER_CALL */;
                }
                const ret = electron_1.ipcRenderer.sendSync(command, contextId, metaId, member.name, wrapArgs(args));
                return metaToValue(ret);
            };
            let descriptorFunction = proxyFunctionProperties(remoteMemberFunction, metaId, member.name);
            descriptor.get = () => {
                descriptorFunction.ref = ref; // The member should reference its object.
                return descriptorFunction;
            };
            // Enable monkey-patch the method
            descriptor.set = (value) => {
                descriptorFunction = value;
                return value;
            };
            descriptor.configurable = true;
        }
        else if (member.type === 'get') {
            descriptor.get = () => {
                const command = "REMOTE_BROWSER_MEMBER_GET" /* BROWSER_MEMBER_GET */;
                const meta = electron_1.ipcRenderer.sendSync(command, contextId, metaId, member.name);
                return metaToValue(meta);
            };
            if (member.writable) {
                descriptor.set = (value) => {
                    const args = wrapArgs([value]);
                    const command = "REMOTE_BROWSER_MEMBER_SET" /* BROWSER_MEMBER_SET */;
                    const meta = electron_1.ipcRenderer.sendSync(command, contextId, metaId, member.name, args);
                    if (meta != null)
                        metaToValue(meta);
                    return value;
                };
            }
        }
        Object.defineProperty(object, member.name, descriptor);
    }
}
// Populate object's prototype from descriptor.
// This matches |getObjectPrototype| in rpc-server.
function setObjectPrototype(ref, object, metaId, descriptor) {
    if (descriptor === null)
        return;
    const proto = {};
    setObjectMembers(ref, proto, metaId, descriptor.members);
    setObjectPrototype(ref, proto, metaId, descriptor.proto);
    Object.setPrototypeOf(object, proto);
}
// Wrap function in Proxy for accessing remote properties
function proxyFunctionProperties(remoteMemberFunction, metaId, name) {
    let loaded = false;
    // Lazily load function properties
    const loadRemoteProperties = () => {
        if (loaded)
            return;
        loaded = true;
        const command = "REMOTE_BROWSER_MEMBER_GET" /* BROWSER_MEMBER_GET */;
        const meta = electron_1.ipcRenderer.sendSync(command, contextId, metaId, name);
        setObjectMembers(remoteMemberFunction, remoteMemberFunction, meta.id, meta.members);
    };
    return new Proxy(remoteMemberFunction, {
        set: (target, property, value) => {
            if (property !== 'ref')
                loadRemoteProperties();
            target[property] = value;
            return true;
        },
        get: (target, property) => {
            if (property === IS_REMOTE_PROXY)
                return true;
            if (!Object.prototype.hasOwnProperty.call(target, property))
                loadRemoteProperties();
            const value = target[property];
            if (property === 'toString' && typeof value === 'function') {
                return value.bind(target);
            }
            return value;
        },
        ownKeys: (target) => {
            loadRemoteProperties();
            return Object.getOwnPropertyNames(target);
        },
        getOwnPropertyDescriptor: (target, property) => {
            const descriptor = Object.getOwnPropertyDescriptor(target, property);
            if (descriptor)
                return descriptor;
            loadRemoteProperties();
            return Object.getOwnPropertyDescriptor(target, property);
        }
    });
}
// Convert meta data from browser into real value.
function metaToValue(meta) {
    if (!meta)
        return {};
    if (meta.type === 'value') {
        return meta.value;
    }
    else if (meta.type === 'array') {
        return meta.members.map((member) => metaToValue(member));
    }
    else if (meta.type === 'nativeimage') {
        return type_utils_1.deserialize(meta.value);
    }
    else if (meta.type === 'buffer') {
        return Buffer.from(meta.value.buffer, meta.value.byteOffset, meta.value.byteLength);
    }
    else if (meta.type === 'promise') {
        return Promise.resolve({ then: metaToValue(meta.then) });
    }
    else if (meta.type === 'error') {
        return metaToError(meta);
    }
    else if (meta.type === 'exception') {
        if (meta.value.type === 'error') {
            throw metaToError(meta.value);
        }
        else {
            throw new Error(`Unexpected value type in exception: ${meta.value.type}`);
        }
    }
    else {
        let ret;
        if ('id' in meta) {
            const cached = getCachedRemoteObject(meta.id);
            if (cached !== undefined) {
                return cached;
            }
        }
        // A shadow class to represent the remote function object.
        if (meta.type === 'function') {
            const remoteFunction = function (...args) {
                let command;
                if (this && this.constructor === remoteFunction) {
                    command = "REMOTE_BROWSER_CONSTRUCTOR" /* BROWSER_CONSTRUCTOR */;
                }
                else {
                    command = "REMOTE_BROWSER_FUNCTION_CALL" /* BROWSER_FUNCTION_CALL */;
                }
                const obj = electron_1.ipcRenderer.sendSync(command, contextId, meta.id, wrapArgs(args));
                return metaToValue(obj);
            };
            ret = remoteFunction;
        }
        else {
            ret = {};
        }
        setObjectMembers(ret, ret, meta.id, meta.members);
        setObjectPrototype(ret, ret, meta.id, meta.proto);
        if (ret.constructor && ret.constructor[IS_REMOTE_PROXY]) {
            Object.defineProperty(ret.constructor, 'name', { value: meta.name });
        }
        // Track delegate obj's lifetime & tell browser to clean up when object is GCed.
        electronIds.set(ret, meta.id);
        setCachedRemoteObject(meta.id, ret);
        return ret;
    }
}
function metaToError(meta) {
    const obj = meta.value;
    for (const { name, value } of meta.members) {
        obj[name] = metaToValue(value);
    }
    return obj;
}
function hasSenderId(input) {
    return typeof input.senderId === "number";
}
function handleMessage(channel, handler) {
    electron_1.ipcRenderer.on(channel, (event, passedContextId, id, ...args) => {
        if (hasSenderId(event)) {
            if (event.senderId !== 0 && event.senderId !== undefined) {
                console.error(`Message ${channel} sent by unexpected WebContents (${event.senderId})`);
                return;
            }
        }
        if (passedContextId === contextId) {
            handler(id, ...args);
        }
        else {
            // Message sent to an un-exist context, notify the error to main process.
            electron_1.ipcRenderer.send("REMOTE_BROWSER_WRONG_CONTEXT_ERROR" /* BROWSER_WRONG_CONTEXT_ERROR */, contextId, passedContextId, id);
        }
    });
}
const enableStacks = process.argv.includes('--enable-api-filtering-logging');
function getCurrentStack() {
    const target = { stack: undefined };
    if (enableStacks) {
        Error.captureStackTrace(target, getCurrentStack);
    }
    return target.stack;
}
// Browser calls a callback in renderer.
handleMessage("REMOTE_RENDERER_CALLBACK" /* RENDERER_CALLBACK */, (id, args) => {
    callbacksRegistry.apply(id, metaToValue(args));
});
// A callback in browser is released.
handleMessage("REMOTE_RENDERER_RELEASE_CALLBACK" /* RENDERER_RELEASE_CALLBACK */, (id) => {
    callbacksRegistry.remove(id);
});
exports.require = (module) => {
    const command = "REMOTE_BROWSER_REQUIRE" /* BROWSER_REQUIRE */;
    const meta = electron_1.ipcRenderer.sendSync(command, contextId, module, getCurrentStack());
    return metaToValue(meta);
};
// Alias to remote.require('electron').xxx.
function getBuiltin(module) {
    const command = "REMOTE_BROWSER_GET_BUILTIN" /* BROWSER_GET_BUILTIN */;
    const meta = electron_1.ipcRenderer.sendSync(command, contextId, module, getCurrentStack());
    return metaToValue(meta);
}
exports.getBuiltin = getBuiltin;
function getCurrentWindow() {
    const command = "REMOTE_BROWSER_GET_CURRENT_WINDOW" /* BROWSER_GET_CURRENT_WINDOW */;
    const meta = electron_1.ipcRenderer.sendSync(command, contextId, getCurrentStack());
    return metaToValue(meta);
}
exports.getCurrentWindow = getCurrentWindow;
// Get current WebContents object.
function getCurrentWebContents() {
    const command = "REMOTE_BROWSER_GET_CURRENT_WEB_CONTENTS" /* BROWSER_GET_CURRENT_WEB_CONTENTS */;
    const meta = electron_1.ipcRenderer.sendSync(command, contextId, getCurrentStack());
    return metaToValue(meta);
}
exports.getCurrentWebContents = getCurrentWebContents;
// Get a global object in browser.
function getGlobal(name) {
    const command = "REMOTE_BROWSER_GET_GLOBAL" /* BROWSER_GET_GLOBAL */;
    const meta = electron_1.ipcRenderer.sendSync(command, contextId, name, getCurrentStack());
    return metaToValue(meta);
}
exports.getGlobal = getGlobal;
// Get the process object in browser.
Object.defineProperty(exports, "process", ({
    enumerable: true,
    get: () => exports.getGlobal('process')
}));
// Create a function that will return the specified value when called in browser.
function createFunctionWithReturnValue(returnValue) {
    const func = () => returnValue;
    isReturnValue.add(func);
    return func;
}
exports.createFunctionWithReturnValue = createFunctionWithReturnValue;
const addBuiltinProperty = (name) => {
    Object.defineProperty(exports, name, {
        enumerable: true,
        get: () => exports.getBuiltin(name)
    });
};
module_names_1.browserModuleNames
    .forEach(addBuiltinProperty);


/***/ }),

/***/ 99474:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   j: () => (/* binding */ deleteRef)
/* harmony export */ });
/* unused harmony export updateRef */
/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85869);

/**
 * Update the ref to a new value.
 *
 * @param repositoryDir - The repository in which the ref exists.
 * @param ref        - The ref to update. Must be fully qualified
 *                     (e.g., `refs/heads/NAME`).
 * @param oldValue   - The value we expect the ref to have currently. If it
 *                     doesn't match, the update will be aborted.
 * @param newValue   - The new value for the ref.
 * @param reason     - The reflog entry.
 */
async function updateRef(repositoryDir, ref, oldValue, newValue, reason) {
    await git(["update-ref", ref, newValue, oldValue, "-m", reason], repositoryDir, "updateRef");
}
/**
 * Remove a ref.
 *
 * @param repositoryDir - The repository in which the ref exists.
 * @param ref        - The ref to remove. Should be fully qualified, but may also be 'HEAD'.
 * @param reason     - The reflog entry (optional). Note that this is only useful when
 *                     deleting the HEAD reference as deleting any other reference will
 *                     implicitly delete the reflog file for that reference as well.
 */
async function deleteRef(repositoryDir, ref, reason) {
    const args = ["update-ref", "-d", ref];
    if (reason !== undefined) {
        args.push("-m", reason);
    }
    return await (0,_client__WEBPACK_IMPORTED_MODULE_0__/* .git */ .$)(args, repositoryDir, "deleteRef");
}


/***/ }),

/***/ 99503:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactComponent: () => (/* binding */ ForwardRef),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(54953);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
var _path, _path2;
var _excluded = ["title", "titleId"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }


var SvgCaretDownUp = function SvgCaretDownUp(_ref, ref) {
  var title = _ref.title,
    titleId = _ref.titleId,
    props = _objectWithoutProperties(_ref, _excluded);
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("svg", _extends({
    width: 25,
    height: 25,
    viewBox: "0 0 25 25",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg",
    ref: ref,
    "aria-labelledby": titleId
  }, props), title ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("title", {
    id: titleId
  }, title) : null, _path || (_path = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M11.6064 2.71027C11.8993 2.41738 12.3741 2.41738 12.667 2.71027L17.8213 7.86454C18.1142 8.15744 18.1142 8.63231 17.8213 8.9252C17.5284 9.2181 17.0535 9.2181 16.7606 8.9252L12.1367 4.30126L7.51275 8.9252C7.21986 9.2181 6.74498 9.2181 6.45209 8.9252C6.1592 8.63231 6.1592 8.15744 6.45209 7.86454L11.6064 2.71027Z",
    fill: "#F5F5F5"
  })), _path2 || (_path2 = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0__.createElement("path", {
    fillRule: "evenodd",
    clipRule: "evenodd",
    d: "M11.6064 22.0795C11.8993 22.3724 12.3741 22.3724 12.667 22.0795L17.8213 16.9252C18.1142 16.6323 18.1142 16.1574 17.8213 15.8645C17.5284 15.5716 17.0535 15.5716 16.7606 15.8645L12.1367 20.4885L7.51275 15.8645C7.21986 15.5716 6.74498 15.5716 6.45209 15.8645C6.1592 16.1574 6.1592 16.6323 6.45209 16.9252L11.6064 22.0795Z",
    fill: "#F5F5F5"
  })));
};
var ForwardRef = /*#__PURE__*/(0,react__WEBPACK_IMPORTED_MODULE_0__.forwardRef)(SvgCaretDownUp);

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__webpack_require__.p + "409b742a8340477071ad28d69cc17920.svg");

/***/ }),

/***/ 99594:
/***/ ((module) => {

"use strict";
module.exports = require("express");

/***/ }),

/***/ 99604:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const { ipcRenderer } = __webpack_require__(91288);
const { ProjectModel } = __webpack_require__(6203);
const Exporter = __webpack_require__(87144);
const { EventDispatcher } = __webpack_require__(11138);
const { CloudService } = __webpack_require__(48153);
const KeyboardHandler = __webpack_require__(70441);

class EditorAPI {
  keyDown(evt, cb) {
    KeyboardHandler.default.instance.onKeyDown(evt);
    cb();
  }

  inspectNodes(evt, cb) {
    EventDispatcher.instance.emit('inspectNodes', { nodeIds: evt.nodeIds });
    cb();
  }

  projectGetInfo(args, cb) {
    if (ProjectModel.instance) {
      cb({ id: ProjectModel.instance.id, projectDirectory: ProjectModel.instance._retainedProjectDirectory });
    } else {
      cb({ id: null, projectDirectory: null });
    }
  }

  projectSetMetaData(args, cb) {
    ProjectModel.instance.setMetaData(args.key, args.data);
    cb();
  }

  projectGetMetaData(args, cb) {
    var data = ProjectModel.instance.getMetaData(args.key);
    cb(data);
  }

  projectGetSettings(args, cb) {
    var data = ProjectModel.instance ? ProjectModel.instance.getSettings() : undefined;
    cb(data);
  }

  async cloudServicesGetActive(args, cb) {
    const environment = await CloudService.instance.backend.fromProject(ProjectModel.instance);
    cb({
      endpoint: environment.url,
      instanceId: environment.id,
      masterKey: environment.masterKey,
      appId: environment.appId
    });
  }

  projectGetComponentBundleExport(args, cb) {
    if (!ProjectModel.instance) {
      cb();
      return;
    }

    const root = ProjectModel.instance.getRootNode();
    if (!root) {
      cb({});
    }

    if (!cachedComponentIndex) {
      const rootComponent = root.owner.owner;
      const allComponents = ProjectModel.instance.getComponents();
      cachedComponentIndex = Exporter.getComponentIndex(rootComponent, allComponents);
    }

    const json = JSON.stringify(Exporter.exportComponentBundle(ProjectModel.instance, args.name, cachedComponentIndex));
    cb(json);
  }

  handleRequest(args, fn) {
    EditorAPI.instance[args.api](args.args, function (response) {
      fn({
        api: args.api,
        token: args.token,
        response: response
      });
    });
  }
}

ipcRenderer.on('editor-api-request', function (event, args) {
  EditorAPI.instance.handleRequest(args, function (response) {
    event.sender.send('editor-api-response', response);
  });
});

EditorAPI.instance = new EditorAPI();

//optimization for bundle generation so we don't have to re-generate the component index all the time
let cachedComponentIndex = null;

var ignoreEvents = ['Model.thumbnailChanged', 'Model.warningsChanged', 'Model.myProjectsChanged'];

EventDispatcher.instance.on('Model.*', (e, name) => {
  if (ignoreEvents.includes(name)) return;
  cachedComponentIndex = null;
});

module.exports = EditorAPI;


/***/ }),

/***/ 99619:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `.PRsList-module__PRsList--Bqp2r{padding:8px;overflow-y:auto;flex:1}.PRsList-module__LoadingState--LKgOw,.PRsList-module__ErrorState--lMQvI,.PRsList-module__EmptyState--vzKgc{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:40px 20px;text-align:center;color:var(--theme-color-fg-default-shy)}.PRsList-module__Spinner--Mg_fq{width:32px;height:32px;border:3px solid var(--theme-color-border-default);border-top-color:var(--theme-color-primary);border-radius:50%;animation:PRsList-module__spin--IPyv2 1s linear infinite;margin-bottom:16px}@keyframes PRsList-module__spin--IPyv2{to{transform:rotate(360deg)}}.PRsList-module__LoadingState--LKgOw p{color:var(--theme-color-fg-default-shy);font-size:13px}.PRsList-module__ErrorState--lMQvI{color:var(--theme-color-fg-error)}.PRsList-module__ErrorIcon--hz8YK{font-size:48px;margin-bottom:16px}.PRsList-module__ErrorState--lMQvI h3{color:var(--theme-color-fg-default);font-size:15px;font-weight:600;margin-bottom:8px}.PRsList-module__ErrorState--lMQvI p{color:var(--theme-color-fg-default-shy);font-size:13px;margin-bottom:16px}.PRsList-module__RetryButton--O3Y6f{padding:8px 16px;background-color:var(--theme-color-primary);color:#fff;border:none;border-radius:4px;font-size:13px;font-weight:500;cursor:pointer;transition:opacity .15s ease}.PRsList-module__RetryButton--O3Y6f:hover{opacity:.9}.PRsList-module__RetryButton--O3Y6f:active{opacity:.8}.PRsList-module__EmptyIcon--cBZ1Y{font-size:48px;margin-bottom:16px}.PRsList-module__EmptyState--vzKgc h3{color:var(--theme-color-fg-default);font-size:15px;font-weight:600;margin-bottom:8px}.PRsList-module__EmptyState--vzKgc p{color:var(--theme-color-fg-default-shy);font-size:13px}.PRsList-module__LoadMoreButton--Iqsre{width:100%;padding:10px;margin-top:8px;background-color:var(--theme-color-bg-3);border:1px solid var(--theme-color-border-default);border-radius:4px;color:var(--theme-color-fg-default);font-size:13px;font-weight:500;cursor:pointer;transition:all .15s ease;display:flex;align-items:center;justify-content:center;gap:8px}.PRsList-module__LoadMoreButton--Iqsre:hover:not(:disabled){background-color:var(--theme-color-bg-4);border-color:var(--theme-color-border-hover)}.PRsList-module__LoadMoreButton--Iqsre:disabled{opacity:.6;cursor:not-allowed}.PRsList-module__SmallSpinner--lwb3P{width:14px;height:14px;border:2px solid var(--theme-color-border-default);border-top-color:var(--theme-color-primary);border-radius:50%;animation:PRsList-module__spin--IPyv2 1s linear infinite}.PRsList-module__EndMessage--WWK1G{text-align:center;padding:16px;color:var(--theme-color-fg-default-shy);font-size:12px}`, "",{"version":3,"sources":["webpack://./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRsList.module.scss"],"names":[],"mappings":"AAIA,gCACE,WAAA,CACA,eAAA,CACA,MAAA,CAGF,2GAGE,YAAA,CACA,qBAAA,CACA,kBAAA,CACA,sBAAA,CACA,iBAAA,CACA,iBAAA,CACA,uCAAA,CAGF,gCACE,UAAA,CACA,WAAA,CACA,kDAAA,CACA,2CAAA,CACA,iBAAA,CACA,wDAAA,CACA,kBAAA,CAGF,uCACE,GACE,wBAAA,CAAA,CAIJ,uCACE,uCAAA,CACA,cAAA,CAGF,mCACE,iCAAA,CAGF,kCACE,cAAA,CACA,kBAAA,CAGF,sCACE,mCAAA,CACA,cAAA,CACA,eAAA,CACA,iBAAA,CAGF,qCACE,uCAAA,CACA,cAAA,CACA,kBAAA,CAGF,oCACE,gBAAA,CACA,2CAAA,CACA,UAAA,CACA,WAAA,CACA,iBAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,4BAAA,CAEA,0CACE,UAAA,CAGF,2CACE,UAAA,CAIJ,kCACE,cAAA,CACA,kBAAA,CAGF,sCACE,mCAAA,CACA,cAAA,CACA,eAAA,CACA,iBAAA,CAGF,qCACE,uCAAA,CACA,cAAA,CAGF,uCACE,UAAA,CACA,YAAA,CACA,cAAA,CACA,wCAAA,CACA,kDAAA,CACA,iBAAA,CACA,mCAAA,CACA,cAAA,CACA,eAAA,CACA,cAAA,CACA,wBAAA,CACA,YAAA,CACA,kBAAA,CACA,sBAAA,CACA,OAAA,CAEA,4DACE,wCAAA,CACA,4CAAA,CAGF,gDACE,UAAA,CACA,kBAAA,CAIJ,qCACE,UAAA,CACA,WAAA,CACA,kDAAA,CACA,2CAAA,CACA,iBAAA,CACA,wDAAA,CAGF,mCACE,iBAAA,CACA,YAAA,CACA,uCAAA,CACA,cAAA","sourcesContent":["/**\n * PRsList Styles\n */\n\n.PRsList {\n  padding: 8px;\n  overflow-y: auto;\n  flex: 1;\n}\n\n.LoadingState,\n.ErrorState,\n.EmptyState {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  padding: 40px 20px;\n  text-align: center;\n  color: var(--theme-color-fg-default-shy);\n}\n\n.Spinner {\n  width: 32px;\n  height: 32px;\n  border: 3px solid var(--theme-color-border-default);\n  border-top-color: var(--theme-color-primary);\n  border-radius: 50%;\n  animation: spin 1s linear infinite;\n  margin-bottom: 16px;\n}\n\n@keyframes spin {\n  to {\n    transform: rotate(360deg);\n  }\n}\n\n.LoadingState p {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 13px;\n}\n\n.ErrorState {\n  color: var(--theme-color-fg-error);\n}\n\n.ErrorIcon {\n  font-size: 48px;\n  margin-bottom: 16px;\n}\n\n.ErrorState h3 {\n  color: var(--theme-color-fg-default);\n  font-size: 15px;\n  font-weight: 600;\n  margin-bottom: 8px;\n}\n\n.ErrorState p {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 13px;\n  margin-bottom: 16px;\n}\n\n.RetryButton {\n  padding: 8px 16px;\n  background-color: var(--theme-color-primary);\n  color: white;\n  border: none;\n  border-radius: 4px;\n  font-size: 13px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: opacity 0.15s ease;\n\n  &:hover {\n    opacity: 0.9;\n  }\n\n  &:active {\n    opacity: 0.8;\n  }\n}\n\n.EmptyIcon {\n  font-size: 48px;\n  margin-bottom: 16px;\n}\n\n.EmptyState h3 {\n  color: var(--theme-color-fg-default);\n  font-size: 15px;\n  font-weight: 600;\n  margin-bottom: 8px;\n}\n\n.EmptyState p {\n  color: var(--theme-color-fg-default-shy);\n  font-size: 13px;\n}\n\n.LoadMoreButton {\n  width: 100%;\n  padding: 10px;\n  margin-top: 8px;\n  background-color: var(--theme-color-bg-3);\n  border: 1px solid var(--theme-color-border-default);\n  border-radius: 4px;\n  color: var(--theme-color-fg-default);\n  font-size: 13px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: all 0.15s ease;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  gap: 8px;\n\n  &:hover:not(:disabled) {\n    background-color: var(--theme-color-bg-4);\n    border-color: var(--theme-color-border-hover);\n  }\n\n  &:disabled {\n    opacity: 0.6;\n    cursor: not-allowed;\n  }\n}\n\n.SmallSpinner {\n  width: 14px;\n  height: 14px;\n  border: 2px solid var(--theme-color-border-default);\n  border-top-color: var(--theme-color-primary);\n  border-radius: 50%;\n  animation: spin 1s linear infinite;\n}\n\n.EndMessage {\n  text-align: center;\n  padding: 16px;\n  color: var(--theme-color-fg-default-shy);\n  font-size: 12px;\n}\n"],"sourceRoot":""}]);
// Exports
___CSS_LOADER_EXPORT___.locals = {
	"PRsList": `PRsList-module__PRsList--Bqp2r`,
	"LoadingState": `PRsList-module__LoadingState--LKgOw`,
	"ErrorState": `PRsList-module__ErrorState--lMQvI`,
	"EmptyState": `PRsList-module__EmptyState--vzKgc`,
	"Spinner": `PRsList-module__Spinner--Mg_fq`,
	"spin": `PRsList-module__spin--IPyv2`,
	"ErrorIcon": `PRsList-module__ErrorIcon--hz8YK`,
	"RetryButton": `PRsList-module__RetryButton--O3Y6f`,
	"EmptyIcon": `PRsList-module__EmptyIcon--cBZ1Y`,
	"LoadMoreButton": `PRsList-module__LoadMoreButton--Iqsre`,
	"SmallSpinner": `PRsList-module__SmallSpinner--lwb3P`,
	"EndMessage": `PRsList-module__EndMessage--WWK1G`
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 99682:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `#comment-layer-fg {
  position: absolute;
  top: 0;
  left: 0;
}

#comment-layer-bg {
  position: absolute;
  top: 0;
  left: 0;
}

#comment-layer-bg *,
#comment-layer-fg * {
  box-sizing: border-box;
}

.comment-layer-comments {
  transform-origin: 0 0;
}

.comment-layer-comment textarea::-webkit-scrollbar {
  display: none;
}

.comment-layer-comment {
  color: var(--theme-color-fg-default-contrast);
  font-size: 12px;
  font-weight: 600;
  line-height: 1.5;
  white-space: pre-wrap;
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.comment-layer-comment.large-font {
  font-size: 18px;
}

.comment-layer-comment.background {
  left: 0;
  top: 0;
  position: absolute;
  overflow: hidden;
  border: 2px solid transparent;
}

.comment-layer-comment.background.fill:not(.selected),
.comment-layer-comment.background.transparent:not(.selected) {
  border: 2px solid rgba(0, 0, 0, 0.125);
}

.comment-layer-comment.background.selected.fill,
.comment-layer-comment.background.selected.transparent {
  outline: 1px solid white;
  outline-offset: 0px;
}

.comment-layer-comment.background.selected.no-fill {
  outline: 1px solid white;
  outline-offset: 4px;
}

.comment-layer-comment.background .content {
  margin: 0;
  padding: 0;
  width: 100%;
  flex-shrink: 0;
}

.comment-layer-comment.foreground {
  border: 2px solid transparent; /* need a border to line up correctly with the background version */
}

.comment-layer-comment.background.no-fill {
  outline-offset: 4px;
}

.comment-layer-comment.background.has-annotation.changed {
  outline: 2px solid var(--theme-color-primary);
}

.comment-layer-comment.background.has-annotation.deleted {
  outline: 2px solid var(--theme-color-danger);
}

.comment-layer-comment.background.has-annotation.created {
  outline: 2px solid var(--theme-color-success);
}

.comment-drag-area {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.comment-layer-comment textarea {
  font: inherit;
  border: none;
  resize: none;
  color: inherit;
  align-self: stretch;
  margin: 0;
  padding: 0;
  background-color: transparent;
  line-height: inherit;
  flex-shrink: 0;
}

/*
    Control bar on top of comments
*/

.comment-controls {
  position: absolute;
  top: -60px;
  transform: translateX(-50%);
  left: 50%;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
  padding: 1px;
  display: flex;
  animation-duration: 300ms;
  animation-name: slideup;
  background-color: var(--theme-color-bg-2);
  justify-content: center;
  align-items: center;
  gap: 1px;
  border-radius: 2px;
  line-height: 0;
}

@keyframes slideup {
  from {
    top: -30px;
    opacity: 0;
  }

  to {
    top: -60px;
    opacity: 1;
  }
}

.comment-color-picker-icon-parent {
  width: 36px;
  height: 36px;
  padding: 4px;
  border-radius: 2px;
  background-color: var(--theme-color-bg-3);
  cursor: pointer;
}

.comment-color-picker-icon-parent:hover {
  background-color: var(--theme-color-bg-1);
}

.comment-color-picker-icon {
  width: 100%;
  height: 100%;
}

.comment-color-picker {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  padding: 8px 6px;
  width: calc(34px * 3);
  gap: 1px;
}

.comment-color-picker > div {
  width: 32px;
  height: 32px;
  flex: 0 0 32px;
  margin: 0;
  padding: 0;
  cursor: pointer;
  outline: 1px solid var(--theme-color-bg-1-transparent);
}

.comment-color-picker > div:not(.active):hover {
  box-shadow: 0 0 0 1px var(--theme-color-fg-transparent) inset, 0 0 0 1px var(--theme-color-fg-transparent) inset;
}

.comment-color-picker > div:last-child {
  /* border-right: none; */
}

.comment-color-picker .active {
  position: relative;
  box-shadow: 0 0 0 1px var(--theme-color-fg-default) inset;
  z-index: 1;
}
`, "",{"version":3,"sources":["webpack://./src/editor/src/views/CommentLayer/CommentLayer.css"],"names":[],"mappings":"AAAA;EACE,kBAAkB;EAClB,MAAM;EACN,OAAO;AACT;;AAEA;EACE,kBAAkB;EAClB,MAAM;EACN,OAAO;AACT;;AAEA;;EAEE,sBAAsB;AACxB;;AAEA;EACE,qBAAqB;AACvB;;AAEA;EACE,aAAa;AACf;;AAEA;EACE,6CAA6C;EAC7C,eAAe;EACf,gBAAgB;EAChB,gBAAgB;EAChB,qBAAqB;EACrB,aAAa;EACb,sBAAsB;EACtB,aAAa;AACf;;AAEA;EACE,eAAe;AACjB;;AAEA;EACE,OAAO;EACP,MAAM;EACN,kBAAkB;EAClB,gBAAgB;EAChB,6BAA6B;AAC/B;;AAEA;;EAEE,sCAAsC;AACxC;;AAEA;;EAEE,wBAAwB;EACxB,mBAAmB;AACrB;;AAEA;EACE,wBAAwB;EACxB,mBAAmB;AACrB;;AAEA;EACE,SAAS;EACT,UAAU;EACV,WAAW;EACX,cAAc;AAChB;;AAEA;EACE,6BAA6B,EAAE,mEAAmE;AACpG;;AAEA;EACE,mBAAmB;AACrB;;AAEA;EACE,6CAA6C;AAC/C;;AAEA;EACE,4CAA4C;AAC9C;;AAEA;EACE,6CAA6C;AAC/C;;AAEA;EACE,YAAY;EACZ,WAAW;EACX,aAAa;EACb,sBAAsB;AACxB;;AAEA;EACE,aAAa;EACb,YAAY;EACZ,YAAY;EACZ,cAAc;EACd,mBAAmB;EACnB,SAAS;EACT,UAAU;EACV,6BAA6B;EAC7B,oBAAoB;EACpB,cAAc;AAChB;;AAEA;;CAEC;;AAED;EACE,kBAAkB;EAClB,UAAU;EACV,2BAA2B;EAC3B,SAAS;EACT,yCAAyC;EACzC,YAAY;EACZ,aAAa;EACb,yBAAyB;EACzB,uBAAuB;EACvB,yCAAyC;EACzC,uBAAuB;EACvB,mBAAmB;EACnB,QAAQ;EACR,kBAAkB;EAClB,cAAc;AAChB;;AAEA;EACE;IACE,UAAU;IACV,UAAU;EACZ;;EAEA;IACE,UAAU;IACV,UAAU;EACZ;AACF;;AAEA;EACE,WAAW;EACX,YAAY;EACZ,YAAY;EACZ,kBAAkB;EAClB,yCAAyC;EACzC,eAAe;AACjB;;AAEA;EACE,yCAAyC;AAC3C;;AAEA;EACE,WAAW;EACX,YAAY;AACd;;AAEA;EACE,aAAa;EACb,eAAe;EACf,uBAAuB;EACvB,mBAAmB;EACnB,gBAAgB;EAChB,qBAAqB;EACrB,QAAQ;AACV;;AAEA;EACE,WAAW;EACX,YAAY;EACZ,cAAc;EACd,SAAS;EACT,UAAU;EACV,eAAe;EACf,sDAAsD;AACxD;;AAEA;EACE,gHAAgH;AAClH;;AAEA;EACE,wBAAwB;AAC1B;;AAEA;EACE,kBAAkB;EAClB,yDAAyD;EACzD,UAAU;AACZ","sourcesContent":["#comment-layer-fg {\n  position: absolute;\n  top: 0;\n  left: 0;\n}\n\n#comment-layer-bg {\n  position: absolute;\n  top: 0;\n  left: 0;\n}\n\n#comment-layer-bg *,\n#comment-layer-fg * {\n  box-sizing: border-box;\n}\n\n.comment-layer-comments {\n  transform-origin: 0 0;\n}\n\n.comment-layer-comment textarea::-webkit-scrollbar {\n  display: none;\n}\n\n.comment-layer-comment {\n  color: var(--theme-color-fg-default-contrast);\n  font-size: 12px;\n  font-weight: 600;\n  line-height: 1.5;\n  white-space: pre-wrap;\n  display: flex;\n  flex-direction: column;\n  padding: 10px;\n}\n\n.comment-layer-comment.large-font {\n  font-size: 18px;\n}\n\n.comment-layer-comment.background {\n  left: 0;\n  top: 0;\n  position: absolute;\n  overflow: hidden;\n  border: 2px solid transparent;\n}\n\n.comment-layer-comment.background.fill:not(.selected),\n.comment-layer-comment.background.transparent:not(.selected) {\n  border: 2px solid rgba(0, 0, 0, 0.125);\n}\n\n.comment-layer-comment.background.selected.fill,\n.comment-layer-comment.background.selected.transparent {\n  outline: 1px solid white;\n  outline-offset: 0px;\n}\n\n.comment-layer-comment.background.selected.no-fill {\n  outline: 1px solid white;\n  outline-offset: 4px;\n}\n\n.comment-layer-comment.background .content {\n  margin: 0;\n  padding: 0;\n  width: 100%;\n  flex-shrink: 0;\n}\n\n.comment-layer-comment.foreground {\n  border: 2px solid transparent; /* need a border to line up correctly with the background version */\n}\n\n.comment-layer-comment.background.no-fill {\n  outline-offset: 4px;\n}\n\n.comment-layer-comment.background.has-annotation.changed {\n  outline: 2px solid var(--theme-color-primary);\n}\n\n.comment-layer-comment.background.has-annotation.deleted {\n  outline: 2px solid var(--theme-color-danger);\n}\n\n.comment-layer-comment.background.has-annotation.created {\n  outline: 2px solid var(--theme-color-success);\n}\n\n.comment-drag-area {\n  height: 100%;\n  width: 100%;\n  display: flex;\n  flex-direction: column;\n}\n\n.comment-layer-comment textarea {\n  font: inherit;\n  border: none;\n  resize: none;\n  color: inherit;\n  align-self: stretch;\n  margin: 0;\n  padding: 0;\n  background-color: transparent;\n  line-height: inherit;\n  flex-shrink: 0;\n}\n\n/*\n    Control bar on top of comments\n*/\n\n.comment-controls {\n  position: absolute;\n  top: -60px;\n  transform: translateX(-50%);\n  left: 50%;\n  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);\n  padding: 1px;\n  display: flex;\n  animation-duration: 300ms;\n  animation-name: slideup;\n  background-color: var(--theme-color-bg-2);\n  justify-content: center;\n  align-items: center;\n  gap: 1px;\n  border-radius: 2px;\n  line-height: 0;\n}\n\n@keyframes slideup {\n  from {\n    top: -30px;\n    opacity: 0;\n  }\n\n  to {\n    top: -60px;\n    opacity: 1;\n  }\n}\n\n.comment-color-picker-icon-parent {\n  width: 36px;\n  height: 36px;\n  padding: 4px;\n  border-radius: 2px;\n  background-color: var(--theme-color-bg-3);\n  cursor: pointer;\n}\n\n.comment-color-picker-icon-parent:hover {\n  background-color: var(--theme-color-bg-1);\n}\n\n.comment-color-picker-icon {\n  width: 100%;\n  height: 100%;\n}\n\n.comment-color-picker {\n  display: flex;\n  flex-wrap: wrap;\n  justify-content: center;\n  align-items: center;\n  padding: 8px 6px;\n  width: calc(34px * 3);\n  gap: 1px;\n}\n\n.comment-color-picker > div {\n  width: 32px;\n  height: 32px;\n  flex: 0 0 32px;\n  margin: 0;\n  padding: 0;\n  cursor: pointer;\n  outline: 1px solid var(--theme-color-bg-1-transparent);\n}\n\n.comment-color-picker > div:not(.active):hover {\n  box-shadow: 0 0 0 1px var(--theme-color-fg-transparent) inset, 0 0 0 1px var(--theme-color-fg-transparent) inset;\n}\n\n.comment-color-picker > div:last-child {\n  /* border-right: none; */\n}\n\n.comment-color-picker .active {\n  position: relative;\n  box-shadow: 0 0 0 1px var(--theme-color-fg-default) inset;\n  z-index: 1;\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 99712:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(72591);
/* harmony import */ var _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1740);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88128);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30855);
/* harmony import */ var _node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93051);
/* harmony import */ var _node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(73656);
/* harmony import */ var _node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_popuplayer_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(98838);

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_node_modules_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_node_modules_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _node_modules_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_node_modules_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_node_modules_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _node_modules_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_popuplayer_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A, options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_popuplayer_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A && _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_popuplayer_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals ? _node_modules_css_loader_dist_cjs_js_ruleSet_1_rules_5_use_1_popuplayer_css__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A.locals : undefined);


/***/ }),

/***/ 99731:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   A: () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82001);
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40935);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

.monaco-progress-container {
	width: 100%;
	height: 5px;
	overflow: hidden; /* keep progress bit in bounds */
}

.monaco-progress-container .progress-bit {
	width: 2%;
	height: 5px;
	position: absolute;
	left: 0;
	display: none;
}

.monaco-progress-container.active .progress-bit {
	display: inherit;
}

.monaco-progress-container.discrete .progress-bit {
	left: 0;
	transition: width 100ms linear;
}

.monaco-progress-container.discrete.done .progress-bit {
	width: 100%;
}

.monaco-progress-container.infinite .progress-bit {
	animation-name: progress;
	animation-duration: 4s;
	animation-iteration-count: infinite;
	transform: translate3d(0px, 0px, 0px);
	animation-timing-function: linear;
}

.monaco-progress-container.infinite.infinite-long-running .progress-bit {
	/*
		The more smooth \`linear\` timing function can cause
		higher GPU consumption as indicated in
		https://github.com/microsoft/vscode/issues/97900 &
		https://github.com/microsoft/vscode/issues/138396
	*/
	animation-timing-function: steps(100);
}

/**
 * The progress bit has a width: 2% (1/50) of the parent container. The animation moves it from 0% to 100% of
 * that container. Since translateX is relative to the progress bit size, we have to multiple it with
 * its relative size to the parent container:
 * parent width: 5000%
 *    bit width: 100%
 * translateX should be as follow:
 *  50%: 5000% * 50% - 50% (set to center) = 2450%
 * 100%: 5000% * 100% - 100% (do not overflow) = 4900%
 */
@keyframes progress { from { transform: translateX(0%) scaleX(1) } 50% { transform: translateX(2500%) scaleX(3) } to { transform: translateX(4900%) scaleX(1) } }
`, "",{"version":3,"sources":["webpack://./../../node_modules/monaco-editor/esm/vs/base/browser/ui/progressbar/progressbar.css"],"names":[],"mappings":"AAAA;;;+FAG+F;;AAE/F;CACC,WAAW;CACX,WAAW;CACX,gBAAgB,EAAE,gCAAgC;AACnD;;AAEA;CACC,SAAS;CACT,WAAW;CACX,kBAAkB;CAClB,OAAO;CACP,aAAa;AACd;;AAEA;CACC,gBAAgB;AACjB;;AAEA;CACC,OAAO;CACP,8BAA8B;AAC/B;;AAEA;CACC,WAAW;AACZ;;AAEA;CACC,wBAAwB;CACxB,sBAAsB;CACtB,mCAAmC;CACnC,qCAAqC;CACrC,iCAAiC;AAClC;;AAEA;CACC;;;;;EAKC;CACD,qCAAqC;AACtC;;AAEA;;;;;;;;;EASE;AACF,sBAAsB,OAAO,oCAAoC,EAAE,MAAM,uCAAuC,EAAE,KAAK,uCAAuC,EAAE","sourcesContent":["/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Microsoft Corporation. All rights reserved.\n *  Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n\n.monaco-progress-container {\n\twidth: 100%;\n\theight: 5px;\n\toverflow: hidden; /* keep progress bit in bounds */\n}\n\n.monaco-progress-container .progress-bit {\n\twidth: 2%;\n\theight: 5px;\n\tposition: absolute;\n\tleft: 0;\n\tdisplay: none;\n}\n\n.monaco-progress-container.active .progress-bit {\n\tdisplay: inherit;\n}\n\n.monaco-progress-container.discrete .progress-bit {\n\tleft: 0;\n\ttransition: width 100ms linear;\n}\n\n.monaco-progress-container.discrete.done .progress-bit {\n\twidth: 100%;\n}\n\n.monaco-progress-container.infinite .progress-bit {\n\tanimation-name: progress;\n\tanimation-duration: 4s;\n\tanimation-iteration-count: infinite;\n\ttransform: translate3d(0px, 0px, 0px);\n\tanimation-timing-function: linear;\n}\n\n.monaco-progress-container.infinite.infinite-long-running .progress-bit {\n\t/*\n\t\tThe more smooth `linear` timing function can cause\n\t\thigher GPU consumption as indicated in\n\t\thttps://github.com/microsoft/vscode/issues/97900 &\n\t\thttps://github.com/microsoft/vscode/issues/138396\n\t*/\n\tanimation-timing-function: steps(100);\n}\n\n/**\n * The progress bit has a width: 2% (1/50) of the parent container. The animation moves it from 0% to 100% of\n * that container. Since translateX is relative to the progress bit size, we have to multiple it with\n * its relative size to the parent container:\n * parent width: 5000%\n *    bit width: 100%\n * translateX should be as follow:\n *  50%: 5000% * 50% - 50% (set to center) = 2450%\n * 100%: 5000% * 100% - 100% (do not overflow) = 4900%\n */\n@keyframes progress { from { transform: translateX(0%) scaleX(1) } 50% { transform: translateX(2500%) scaleX(3) } to { transform: translateX(4900%) scaleX(1) } }\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ 99918:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  B: () => (/* binding */ getStatus)
});

// EXTERNAL MODULE: ../noodl-git/src/core/models/status.ts
var models_status = __webpack_require__(45226);
;// external "double-ended-queue"
const external_double_ended_queue_namespaceObject = require("double-ended-queue");
var external_double_ended_queue_default = /*#__PURE__*/__webpack_require__.n(external_double_ended_queue_namespaceObject);
;// ../noodl-git/src/core/status-parser.ts


function isStatusHeader(statusItem) {
    return statusItem.kind === 'header';
}
function isStatusEntry(statusItem) {
    return statusItem.kind === 'entry';
}
const ChangedEntryType = '1';
const RenamedOrCopiedEntryType = '2';
const UnmergedEntryType = 'u';
const UntrackedEntryType = '?';
const IgnoredEntryType = '!';
/** Parses output from git status --porcelain -z into file status entries */
function parsePorcelainStatus(output) {
    const entries = new Array();
    // See https://git-scm.com/docs/git-status
    //
    // In the short-format, the status of each path is shown as
    // XY PATH1 -> PATH2
    //
    // There is also an alternate -z format recommended for machine parsing. In that
    // format, the status field is the same, but some other things change. First,
    // the -> is omitted from rename entries and the field order is reversed (e.g
    // from -> to becomes to from). Second, a NUL (ASCII 0) follows each filename,
    // replacing space as a field separator and the terminating newline (but a space
    // still separates the status field from the first filename). Third, filenames
    // containing special characters are not specially formatted; no quoting or
    // backslash-escaping is performed.
    const tokens = output.split('\0');
    const queue = new (external_double_ended_queue_default())(tokens);
    let field;
    while ((field = queue.shift())) {
        if (field.startsWith('# ') && field.length > 2) {
            entries.push({ kind: 'header', value: field.substr(2) });
            continue;
        }
        const entryKind = field.substr(0, 1);
        if (entryKind === ChangedEntryType) {
            entries.push(parseChangedEntry(field));
        }
        else if (entryKind === RenamedOrCopiedEntryType) {
            entries.push(parsedRenamedOrCopiedEntry(field, queue.shift()));
        }
        else if (entryKind === UnmergedEntryType) {
            entries.push(parseUnmergedEntry(field));
        }
        else if (entryKind === UntrackedEntryType) {
            entries.push(parseUntrackedEntry(field));
        }
        else if (entryKind === IgnoredEntryType) {
            // Ignored, we don't care about these for now
        }
    }
    return entries;
}
// 1 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <path>
const changedEntryRe = /^1 ([MADRCUTX?!.]{2}) (N\.\.\.|S[C.][M.][U.]) (\d+) (\d+) (\d+) ([a-f0-9]+) ([a-f0-9]+) ([\s\S]*?)$/;
function parseChangedEntry(field) {
    const match = changedEntryRe.exec(field);
    if (!match) {
        console.debug(`parseChangedEntry parse error: ${field}`);
        throw new Error(`Failed to parse status line for changed entry`);
    }
    return {
        kind: 'entry',
        statusCode: match[1],
        path: match[8]
    };
}
// 2 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <X><score> <path><sep><origPath>
const renamedOrCopiedEntryRe = /^2 ([MADRCUTX?!.]{2}) (N\.\.\.|S[C.][M.][U.]) (\d+) (\d+) (\d+) ([a-f0-9]+) ([a-f0-9]+) ([RC]\d+) ([\s\S]*?)$/;
function parsedRenamedOrCopiedEntry(field, oldPath) {
    const match = renamedOrCopiedEntryRe.exec(field);
    if (!match) {
        console.debug(`parsedRenamedOrCopiedEntry parse error: ${field}`);
        throw new Error(`Failed to parse status line for renamed or copied entry`);
    }
    if (!oldPath) {
        throw new Error('Failed to parse renamed or copied entry, could not parse old path');
    }
    return {
        kind: 'entry',
        statusCode: match[1],
        oldPath,
        path: match[9]
    };
}
// u <xy> <sub> <m1> <m2> <m3> <mW> <h1> <h2> <h3> <path>
const unmergedEntryRe = /^u ([DAU]{2}) (N\.\.\.|S[C.][M.][U.]) (\d+) (\d+) (\d+) (\d+) ([a-f0-9]+) ([a-f0-9]+) ([a-f0-9]+) ([\s\S]*?)$/;
function parseUnmergedEntry(field) {
    const match = unmergedEntryRe.exec(field);
    if (!match) {
        console.debug(`parseUnmergedEntry parse error: ${field}`);
        throw new Error(`Failed to parse status line for unmerged entry`);
    }
    return {
        kind: 'entry',
        statusCode: match[1],
        path: match[10]
    };
}
function parseUntrackedEntry(field) {
    const path = field.substr(2);
    return {
        kind: 'entry',
        // NOTE: We return ?? instead of ? here to play nice with mapStatus,
        // might want to consider changing this (and mapStatus) in the future.
        statusCode: '??',
        path
    };
}
/**
 * Map the raw status text from Git to a structure we can work with in the app.
 */
function mapStatus(status) {
    if (status === '??') {
        return {
            kind: 'untracked'
        };
    }
    if (status === '.M') {
        return {
            kind: 'ordinary',
            type: 'modified',
            index: models_status/* GitStatusEntry */.FR.Unchanged,
            workingTree: models_status/* GitStatusEntry */.FR.Modified
        };
    }
    if (status === 'M.') {
        return {
            kind: 'ordinary',
            type: 'modified',
            index: models_status/* GitStatusEntry */.FR.Modified,
            workingTree: models_status/* GitStatusEntry */.FR.Unchanged
        };
    }
    if (status === '.A') {
        return {
            kind: 'ordinary',
            type: 'added',
            index: models_status/* GitStatusEntry */.FR.Unchanged,
            workingTree: models_status/* GitStatusEntry */.FR.Added
        };
    }
    if (status === 'A.') {
        return {
            kind: 'ordinary',
            type: 'added',
            index: models_status/* GitStatusEntry */.FR.Added,
            workingTree: models_status/* GitStatusEntry */.FR.Unchanged
        };
    }
    if (status === '.D') {
        return {
            kind: 'ordinary',
            type: 'deleted',
            index: models_status/* GitStatusEntry */.FR.Unchanged,
            workingTree: models_status/* GitStatusEntry */.FR.Deleted
        };
    }
    if (status === 'D.') {
        return {
            kind: 'ordinary',
            type: 'deleted',
            index: models_status/* GitStatusEntry */.FR.Deleted,
            workingTree: models_status/* GitStatusEntry */.FR.Unchanged
        };
    }
    if (status === 'R.') {
        return {
            kind: 'renamed',
            index: models_status/* GitStatusEntry */.FR.Renamed,
            workingTree: models_status/* GitStatusEntry */.FR.Unchanged
        };
    }
    if (status === '.R') {
        return {
            kind: 'renamed',
            index: models_status/* GitStatusEntry */.FR.Unchanged,
            workingTree: models_status/* GitStatusEntry */.FR.Renamed
        };
    }
    if (status === 'C.') {
        return {
            kind: 'copied',
            index: models_status/* GitStatusEntry */.FR.Copied,
            workingTree: models_status/* GitStatusEntry */.FR.Unchanged
        };
    }
    if (status === '.C') {
        return {
            kind: 'copied',
            index: models_status/* GitStatusEntry */.FR.Unchanged,
            workingTree: models_status/* GitStatusEntry */.FR.Copied
        };
    }
    if (status === 'AD') {
        return {
            kind: 'ordinary',
            type: 'added',
            index: models_status/* GitStatusEntry */.FR.Added,
            workingTree: models_status/* GitStatusEntry */.FR.Deleted
        };
    }
    if (status === 'AM') {
        return {
            kind: 'ordinary',
            type: 'added',
            index: models_status/* GitStatusEntry */.FR.Added,
            workingTree: models_status/* GitStatusEntry */.FR.Modified
        };
    }
    if (status === 'RM') {
        return {
            kind: 'renamed',
            index: models_status/* GitStatusEntry */.FR.Renamed,
            workingTree: models_status/* GitStatusEntry */.FR.Modified
        };
    }
    if (status === 'RD') {
        return {
            kind: 'renamed',
            index: models_status/* GitStatusEntry */.FR.Renamed,
            workingTree: models_status/* GitStatusEntry */.FR.Deleted
        };
    }
    if (status === 'DD') {
        return {
            kind: 'conflicted',
            action: models_status/* UnmergedEntrySummary */.Y4.BothDeleted,
            us: models_status/* GitStatusEntry */.FR.Deleted,
            them: models_status/* GitStatusEntry */.FR.Deleted
        };
    }
    if (status === 'AU') {
        return {
            kind: 'conflicted',
            action: models_status/* UnmergedEntrySummary */.Y4.AddedByUs,
            us: models_status/* GitStatusEntry */.FR.Added,
            them: models_status/* GitStatusEntry */.FR.UpdatedButUnmerged
        };
    }
    if (status === 'UD') {
        return {
            kind: 'conflicted',
            action: models_status/* UnmergedEntrySummary */.Y4.DeletedByThem,
            us: models_status/* GitStatusEntry */.FR.UpdatedButUnmerged,
            them: models_status/* GitStatusEntry */.FR.Deleted
        };
    }
    if (status === 'UA') {
        return {
            kind: 'conflicted',
            action: models_status/* UnmergedEntrySummary */.Y4.AddedByThem,
            us: models_status/* GitStatusEntry */.FR.UpdatedButUnmerged,
            them: models_status/* GitStatusEntry */.FR.Added
        };
    }
    if (status === 'DU') {
        return {
            kind: 'conflicted',
            action: models_status/* UnmergedEntrySummary */.Y4.DeletedByUs,
            us: models_status/* GitStatusEntry */.FR.Deleted,
            them: models_status/* GitStatusEntry */.FR.UpdatedButUnmerged
        };
    }
    if (status === 'AA') {
        return {
            kind: 'conflicted',
            action: models_status/* UnmergedEntrySummary */.Y4.BothAdded,
            us: models_status/* GitStatusEntry */.FR.Added,
            them: models_status/* GitStatusEntry */.FR.Added
        };
    }
    if (status === 'UU') {
        return {
            kind: 'conflicted',
            action: models_status/* UnmergedEntrySummary */.Y4.BothModified,
            us: models_status/* GitStatusEntry */.FR.UpdatedButUnmerged,
            them: models_status/* GitStatusEntry */.FR.UpdatedButUnmerged
        };
    }
    // as a fallback, we assume the file is modified in some way
    return {
        kind: 'ordinary',
        type: 'modified'
    };
}

// EXTERNAL MODULE: ../noodl-git/src/core/models/diff.ts + 2 modules
var diff = __webpack_require__(46553);
// EXTERNAL MODULE: ../noodl-git/src/core/client.ts + 14 modules
var client = __webpack_require__(85869);
// EXTERNAL MODULE: ../noodl-git/src/core/merge.ts + 1 modules
var merge = __webpack_require__(73622);
// EXTERNAL MODULE: external "path"
var external_path_ = __webpack_require__(16928);
var external_path_default = /*#__PURE__*/__webpack_require__.n(external_path_);
// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(79896);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
;// ../noodl-git/src/core/rebase.ts


/** The app-specific results from attempting to rebase a repository */
var RebaseResult;
(function (RebaseResult) {
    /**
     * Git completed the rebase without reporting any errors, and the caller can
     * signal success to the user.
     */
    RebaseResult["CompletedWithoutError"] = "CompletedWithoutError";
    /**
     * The rebase encountered conflicts while attempting to rebase, and these
     * need to be resolved by the user before the rebase can continue.
     */
    RebaseResult["ConflictsEncountered"] = "ConflictsEncountered";
    /**
     * The rebase was not able to continue as tracked files were not staged in
     * the index.
     */
    RebaseResult["OutstandingFilesNotStaged"] = "OutstandingFilesNotStaged";
    /**
     * The rebase was not attempted because it could not check the status of the
     * repository. The caller needs to confirm the repository is in a usable
     * state.
     */
    RebaseResult["Aborted"] = "Aborted";
    /**
     * An unexpected error as part of the rebase flow was caught and handled.
     *
     * Check the logs to find the relevant Git details.
     */
    RebaseResult["Error"] = "Error";
})(RebaseResult || (RebaseResult = {}));
/**
 * Check the `.git/REBASE_HEAD` file exists in a repository to confirm
 * a rebase operation is underway.
 */
async function isRebaseHeadSet(repositoryDir) {
    const path = external_path_default().join(repositoryDir, '.git', 'REBASE_HEAD');
    // NOTE: access calls reject, which causes issues with devtools.
    // return fs.promises.access(path).then(constant(true), constant(false));
    return new Promise((resolve) => {
        resolve(external_fs_default().existsSync(path));
    });
}
/**
 * Get the internal state about the rebase being performed on a repository. This
 * information is required to help Desktop display information to the user
 * about the current action as well as the options available.
 *
 * Returns `null` if no rebase is detected, or if the expected information
 * cannot be found in the repository.
 */
async function getRebaseInternalState(repositoryDir) {
    const isRebase = await isRebaseHeadSet(repositoryDir);
    if (!isRebase) {
        return null;
    }
    let originalBranchTip = null;
    let targetBranch = null;
    let baseBranchTip = null;
    try {
        originalBranchTip = await external_fs_default().promises.readFile(external_path_default().join(repositoryDir, '.git', 'rebase-merge', 'orig-head'), 'utf8');
        originalBranchTip = originalBranchTip.trim();
        targetBranch = await external_fs_default().promises.readFile(external_path_default().join(repositoryDir, '.git', 'rebase-merge', 'head-name'), 'utf8');
        if (targetBranch.startsWith('refs/heads/')) {
            targetBranch = targetBranch.substring(11).trim();
        }
        baseBranchTip = await external_fs_default().promises.readFile(external_path_default().join(repositoryDir, '.git', 'rebase-merge', 'onto'), 'utf8');
        baseBranchTip = baseBranchTip.trim();
    }
    catch { }
    if (originalBranchTip != null && targetBranch != null && baseBranchTip != null) {
        return { originalBranchTip, targetBranch, baseBranchTip };
    }
    // unable to resolve the rebase state of this repository
    return null;
}

// EXTERNAL MODULE: ../noodl-git/src/core/helpers/regex.ts + 1 modules
var regex = __webpack_require__(51025);
;// ../noodl-git/src/core/diff-check.ts


/**
 * Returns a list of files with conflict markers present
 *
 * @param repositoryPath filepath to repository
 * @returns filepaths with their number of conflicted markers
 */
async function getFilesWithConflictMarkers(repositoryPath) {
    // git operation
    const args = ['diff', '--check'];
    const { output } = await (0,client/* git */.$)(args, repositoryPath, 'getFilesWithConflictMarkers', {
        successExitCodes: new Set([0, 2]),
        spawn: true
    });
    // result parsing
    const captures = (0,regex/* getCaptures */.En)(output, fileNameCaptureRe);
    if (captures.length === 0) {
        return new Map();
    }
    // flatten the list (only does one level deep)
    const flatCaptures = captures.reduce((acc, val) => acc.concat(val));
    // count number of occurrences
    const counted = flatCaptures.reduce((acc, val) => acc.set(val, (acc.get(val) || 0) + 1), new Map());
    return counted;
}
/**
 * matches a line reporting a leftover conflict marker
 * and captures the name of the file
 */
const fileNameCaptureRe = /(.+):\d+: leftover conflict marker/gi;

;// ../noodl-git/src/core/diff.ts




/** Parse the line ending string into an enum value (or `null` if unknown) */
function parseLineEndingText(text) {
    const input = text.trim();
    switch (input) {
        case "CR":
            return "CR";
        case "LF":
            return "LF";
        case "CRLF":
            return "CRLF";
        default:
            return null;
    }
}
/**
 * V8 has a limit on the size of string it can create (~256MB), and unless we want to
 * trigger an unhandled exception we need to do the encoding conversion by hand.
 *
 * This is a hard limit on how big a buffer can be and still be converted into
 * a string.
 */
const MaxDiffBufferSize = 70e6; // 70MB in decimal
/**
 * Utility function to check whether parsing this buffer is going to cause
 * issues at runtime.
 *
 * @param buffer A buffer of binary text from a spawned process
 */
function isValidBuffer(buffer) {
    return buffer.length <= MaxDiffBufferSize;
}
function buildDiff(buffer, repositoryDir, file, commitish, lineEndingsChange) {
    if (!isValidBuffer(buffer)) {
        // the buffer's diff is too large to be renderable in the UI
        return Promise.resolve({ kind: DiffType.Unrenderable });
    }
    return null;
}
/**
 * Render the difference between a file in the given commit and its parent
 *
 * @param commitish A commit SHA or some other identifier that ultimately dereferences
 *                  to a commit.
 */
async function getCommitDiff(repositoryDir, file, commitish, hideWhitespaceInDiff = false) {
    const args = [
        "log",
        commitish,
        ...(hideWhitespaceInDiff ? ["-w"] : []),
        "-m",
        "-1",
        "--first-parent",
        "--patch-with-raw",
        "-z",
        "--no-color",
        "--",
        file.path,
    ];
    if (file.status.kind === FileStatusKind.Renamed ||
        file.status.kind === FileStatusKind.Copied) {
        args.push(file.status.oldPath);
    }
    const { output } = await git(args, repositoryDir, "getCommitDiff");
    return buildDiff(Buffer.from(output), repositoryDir, file, commitish);
}
/**
 * Render the diff for a file within the repository working directory. The file will be
 * compared against HEAD if it's tracked, if not it'll be compared to an empty file meaning
 * that all content in the file will be treated as additions.
 */
async function getWorkingDirectoryDiff(repositoryDir, file, hideWhitespaceInDiff = false) {
    // `--no-ext-diff` should be provided wherever we invoke `git diff` so that any
    // diff.external program configured by the user is ignored
    const args = [
        "diff",
        ...(hideWhitespaceInDiff ? ["-w"] : []),
        "--no-ext-diff",
        "--patch-with-raw",
        "-z",
        "--no-color",
    ];
    const successExitCodes = new Set([0]);
    if (file.status.kind === FileStatusKind.New ||
        file.status.kind === FileStatusKind.Untracked) {
        // `git diff --no-index` seems to emulate the exit codes from `diff` irrespective of
        // whether you set --exit-code
        //
        // this is the behavior:
        // - 0 if no changes found
        // - 1 if changes found
        // -   and error otherwise
        //
        // citation in source:
        // https://github.com/git/git/blob/1f66975deb8402131fbf7c14330d0c7cdebaeaa2/diff-no-index.c#L300
        successExitCodes.add(1);
        args.push("--no-index", "--", "/dev/null", file.path);
    }
    else if (file.status.kind === FileStatusKind.Renamed) {
        // NB: Technically this is incorrect, the best kind of incorrect.
        // In order to show exactly what will end up in the commit we should
        // perform a diff between the new file and the old file as it appears
        // in HEAD. By diffing against the index we won't show any changes
        // already staged to the renamed file which differs from our other diffs.
        // The closest I got to that was running hash-object and then using
        // git diff <blob> <blob> but that seems a bit excessive.
        args.push("--", file.path);
    }
    else {
        args.push("HEAD", "--", file.path);
    }
    const { output, error } = await git(args, repositoryDir, "getWorkingDirectoryDiff", { successExitCodes });
    const lineEndingsChange = parseLineEndingsWarning(error);
    return buildDiff(Buffer.from(output), repositoryDir, file, "HEAD", lineEndingsChange);
}
/**
 * `git diff` will write out messages about the line ending changes it knows
 * about to `stderr` - this rule here will catch this and also the to/from
 * changes based on what the user has configured.
 */
const lineEndingsChangeRegex = /warning: (CRLF|CR|LF) will be replaced by (CRLF|CR|LF) in .*/;
/**
 * Utility function for inspecting the stderr output for the line endings
 * warning that Git may report.
 *
 * @param error A buffer of binary text from a spawned process
 */
function parseLineEndingsWarning(error) {
    if (error.length === 0) {
        return undefined;
    }
    const match = lineEndingsChangeRegex.exec(error);
    if (match) {
        const from = parseLineEndingText(match[1]);
        const to = parseLineEndingText(match[2]);
        if (from && to) {
            return { from, to };
        }
    }
    return undefined;
}
/**
 * List the modified binary files' paths in the given repository
 *
 * @param repository to run git operation in
 * @param ref ref (sha, branch, etc) to compare the working index against
 *
 * if you're mid-merge pass `'MERGE_HEAD'` to ref to get a diff of `HEAD` vs `MERGE_HEAD`,
 * otherwise you should probably pass `'HEAD'` to get a diff of the working tree vs `HEAD`
 */
async function getBinaryPaths(repositoryDir, ref) {
    const { output } = await (0,client/* git */.$)(["diff", "--numstat", "-z", ref], repositoryDir, "getBinaryPaths");
    const captures = (0,regex/* getCaptures */.En)(output, binaryListRegex);
    if (captures.length === 0) {
        return [];
    }
    // flatten the list (only does one level deep)
    const flatCaptures = captures.reduce((acc, val) => acc.concat(val));
    return flatCaptures;
}
const binaryListRegex = /-\t-\t(?:\0.+\0)?([^\0]*)/gi;

;// ../noodl-git/src/core/status.ts








/**
 * V8 has a limit on the size of string it can create (~256MB), and unless we want to
 * trigger an unhandled exception we need to do the encoding conversion by hand.
 *
 * As we may be executing status often, we should keep this to a reasonable threshold.
 */
const MaxStatusBufferSize = 20e6; // 20MB in decimal
function parseConflictedState(entry, // UnmergedEntry,
path, conflictDetails) {
    switch (entry.action) {
        case models_status/* UnmergedEntrySummary */.Y4.BothAdded: {
            const isBinary = conflictDetails.binaryFilePaths.includes(path);
            if (!isBinary) {
                return {
                    kind: models_status/* FileStatusKind */.Jb.Conflicted,
                    entry,
                    conflictMarkerCount: conflictDetails.conflictCountsByPath.get(path) || 0
                };
            }
            else {
                return {
                    kind: models_status/* FileStatusKind */.Jb.Conflicted,
                    entry
                };
            }
        }
        case models_status/* UnmergedEntrySummary */.Y4.BothModified: {
            const isBinary = conflictDetails.binaryFilePaths.includes(path);
            if (!isBinary) {
                return {
                    kind: models_status/* FileStatusKind */.Jb.Conflicted,
                    entry,
                    conflictMarkerCount: conflictDetails.conflictCountsByPath.get(path) || 0
                };
            }
            else {
                return {
                    kind: models_status/* FileStatusKind */.Jb.Conflicted,
                    entry
                };
            }
        }
        default:
            return {
                kind: models_status/* FileStatusKind */.Jb.Conflicted,
                entry
            };
    }
}
function convertToAppStatus(path, entry, conflictDetails, oldPath) {
    if (entry.kind === 'ordinary') {
        switch (entry.type) {
            case 'added':
                return { kind: models_status/* FileStatusKind */.Jb.New };
            case 'modified':
                return { kind: models_status/* FileStatusKind */.Jb.Modified };
            case 'deleted':
                return { kind: models_status/* FileStatusKind */.Jb.Deleted };
        }
    }
    else if (entry.kind === 'copied' && oldPath != null) {
        return { kind: models_status/* FileStatusKind */.Jb.Copied, oldPath };
    }
    else if (entry.kind === 'renamed' && oldPath != null) {
        return { kind: models_status/* FileStatusKind */.Jb.Renamed, oldPath };
    }
    else if (entry.kind === 'untracked') {
        return { kind: models_status/* FileStatusKind */.Jb.Untracked };
    }
    else if (entry.kind === 'conflicted') {
        return parseConflictedState(entry, path, conflictDetails);
    }
    throw new Error(`Unknown file status ${status}`);
}
/**
 * Update status header based on the current header entry.
 * Reducer.
 */
function parseStatusHeader(results, header) {
    let { currentBranch, currentUpstreamBranch, currentTip, branchAheadBehind, match } = results;
    const value = header.value;
    // This intentionally does not match branch.oid initial
    if ((match = value.match(/^branch\.oid ([a-f0-9]+)$/))) {
        currentTip = match[1];
    }
    else if ((match = value.match(/^branch.head (.*)/))) {
        if (match[1] !== '(detached)') {
            currentBranch = match[1];
        }
    }
    else if ((match = value.match(/^branch.upstream (.*)/))) {
        currentUpstreamBranch = match[1];
    }
    else if ((match = value.match(/^branch.ab \+(\d+) -(\d+)$/))) {
        const ahead = parseInt(match[1], 10);
        const behind = parseInt(match[2], 10);
        if (!isNaN(ahead) && !isNaN(behind)) {
            branchAheadBehind = { ahead, behind };
        }
    }
    return {
        currentBranch,
        currentUpstreamBranch,
        currentTip,
        branchAheadBehind,
        match
    };
}
// List of known conflicted index entries for a file, extracted from mapStatus
// inside `app/src/lib/status-parser.ts` for convenience
const conflictStatusCodes = ['DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'];
/**
 *  Retrieve the status for a given repository,
 *  and fail gracefully if the location is not a Git repository
 */
async function getStatus(repositoryDir) {
    const args = ['--no-optional-locks', 'status', '--untracked-files=all', '--branch', '--porcelain=2', '-z'];
    const result = await (0,client/* git */.$)(args, repositoryDir, 'getStatus', {
        successExitCodes: new Set([0, 128])
    });
    if (result.exitCode === 128) {
        console.debug(`'git status' returned 128 for '${repositoryDir}' and is likely missing its .git directory`);
        return null;
    }
    if (result.output.length > MaxStatusBufferSize) {
        console.error(`'git status' emitted ${result.output.length} bytes, which is beyond the supported threshold of ${MaxStatusBufferSize} bytes`);
        return null;
    }
    const stdout = result.output;
    const parsed = parsePorcelainStatus(stdout);
    // const headers = parsed.filter(isStatusHeader)
    const entries = parsed.filter(isStatusEntry);
    const mergeHeadFound = await (0,merge/* isMergeHeadSet */.X)(repositoryDir);
    const conflictedFilesInIndex = entries.some((e) => conflictStatusCodes.indexOf(e.statusCode) > -1);
    const rebaseInternalState = await getRebaseInternalState(repositoryDir);
    const conflictDetails = await getConflictDetails(repositoryDir, mergeHeadFound, conflictedFilesInIndex, rebaseInternalState);
    // Map of files keyed on their paths.
    const files = entries.reduce((files, entry) => buildStatusMap(files, entry, conflictDetails), new Map());
    return models_status/* WorkingDirectoryStatus */.RI.fromFiles([...files.values()]);
}
/**
 *
 * Update map of working directory changes with a file status entry.
 * Reducer(ish).
 *
 * (Map is used here to maintain insertion order.)
 */
function buildStatusMap(files, entry, conflictDetails) {
    const status = mapStatus(entry.statusCode);
    if (status.kind === 'ordinary') {
        // when a file is added in the index but then removed in the working
        // directory, the file won't be part of the commit, so we can skip
        // displaying this entry in the changes list
        if (status.index === models_status/* GitStatusEntry */.FR.Added && status.workingTree === models_status/* GitStatusEntry */.FR.Deleted) {
            return files;
        }
    }
    if (status.kind === 'untracked') {
        // when a delete has been staged, but an untracked file exists with the
        // same path, we should ensure that we only draw one entry in the
        // changes list - see if an entry already exists for this path and
        // remove it if found
        files.delete(entry.path);
    }
    // for now we just poke at the existing summary
    const appStatus = convertToAppStatus(entry.path, status, conflictDetails, entry.oldPath);
    const selection = diff/* DiffSelection */.MD.fromInitialSelection(diff/* DiffSelectionType */.i2.All);
    files.set(entry.path, new models_status/* WorkingDirectoryFileChange */.lY(entry.path, appStatus, selection));
    return files;
}
async function getMergeConflictDetails(repositoryDir) {
    const conflictCountsByPath = await getFilesWithConflictMarkers(repositoryDir);
    const binaryFilePaths = await getBinaryPaths(repositoryDir, 'MERGE_HEAD');
    return {
        conflictCountsByPath,
        binaryFilePaths
    };
}
async function getRebaseConflictDetails(repositoryDir) {
    const conflictCountsByPath = await getFilesWithConflictMarkers(repositoryDir);
    const binaryFilePaths = await getBinaryPaths(repositoryDir, 'REBASE_HEAD');
    return {
        conflictCountsByPath,
        binaryFilePaths
    };
}
/**
 * We need to do these operations to detect conflicts that were the result
 * of popping a stash into the index
 */
async function getWorkingDirectoryConflictDetails(repositoryDir) {
    const conflictCountsByPath = await getFilesWithConflictMarkers(repositoryDir);
    let binaryFilePaths = [];
    try {
        // its totally fine if HEAD doesn't exist, which throws an error
        binaryFilePaths = await getBinaryPaths(repositoryDir, 'HEAD');
    }
    catch (error) { }
    return {
        conflictCountsByPath,
        binaryFilePaths
    };
}
/**
 * gets the conflicted files count and binary file paths in a given repository.
 * for computing an `IStatusResult`.
 *
 * @param repositoryDir to get details from
 * @param mergeHeadFound whether a merge conflict has been detected
 * @param lookForStashConflicts whether it looks like a stash has introduced conflicts
 * @param rebaseInternalState details about the current rebase operation (if found)
 */
async function getConflictDetails(repositoryDir, mergeHeadFound, lookForStashConflicts, rebaseInternalState) {
    try {
        if (mergeHeadFound) {
            return await getMergeConflictDetails(repositoryDir);
        }
        if (rebaseInternalState !== null) {
            return await getRebaseConflictDetails(repositoryDir);
        }
        if (lookForStashConflicts) {
            return await getWorkingDirectoryConflictDetails(repositoryDir);
        }
    }
    catch (error) {
        console.error('Unexpected error from git operations in getConflictDetails', error);
    }
    return {
        conflictCountsByPath: new Map(),
        binaryFilePaths: new Array()
    };
}


/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			id: moduleId,
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = __webpack_modules__;
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/amd options */
/******/ 	(() => {
/******/ 		__webpack_require__.amdO = {};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/compat get default export */
/******/ 	(() => {
/******/ 		// getDefaultExport function for compatibility with non-harmony modules
/******/ 		__webpack_require__.n = (module) => {
/******/ 			var getter = module && module.__esModule ?
/******/ 				() => (module['default']) :
/******/ 				() => (module);
/******/ 			__webpack_require__.d(getter, { a: getter });
/******/ 			return getter;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/ensure chunk */
/******/ 	(() => {
/******/ 		__webpack_require__.f = {};
/******/ 		// This file contains only the entry chunk.
/******/ 		// The chunk loading function for additional chunks
/******/ 		__webpack_require__.e = (chunkId) => {
/******/ 			return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
/******/ 				__webpack_require__.f[key](chunkId, promises);
/******/ 				return promises;
/******/ 			}, []));
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/get javascript chunk filename */
/******/ 	(() => {
/******/ 		// This function allow to reference async chunks
/******/ 		__webpack_require__.u = (chunkId) => {
/******/ 			// return url for filenames based on template
/******/ 			return "" + chunkId + ".bundle.js";
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/global */
/******/ 	(() => {
/******/ 		__webpack_require__.g = (function() {
/******/ 			if (typeof globalThis === 'object') return globalThis;
/******/ 			try {
/******/ 				return this || new Function('return this')();
/******/ 			} catch (e) {
/******/ 				if (typeof window === 'object') return window;
/******/ 			}
/******/ 		})();
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/load script */
/******/ 	(() => {
/******/ 		var inProgress = {};
/******/ 		var dataWebpackPrefix = "noodl-editor:";
/******/ 		// loadScript function to load a script via script tag
/******/ 		__webpack_require__.l = (url, done, key, chunkId) => {
/******/ 			if(inProgress[url]) { inProgress[url].push(done); return; }
/******/ 			var script, needAttach;
/******/ 			if(key !== undefined) {
/******/ 				var scripts = document.getElementsByTagName("script");
/******/ 				for(var i = 0; i < scripts.length; i++) {
/******/ 					var s = scripts[i];
/******/ 					if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == dataWebpackPrefix + key) { script = s; break; }
/******/ 				}
/******/ 			}
/******/ 			if(!script) {
/******/ 				needAttach = true;
/******/ 				script = document.createElement('script');
/******/ 		
/******/ 				script.charset = 'utf-8';
/******/ 				if (__webpack_require__.nc) {
/******/ 					script.setAttribute("nonce", __webpack_require__.nc);
/******/ 				}
/******/ 				script.setAttribute("data-webpack", dataWebpackPrefix + key);
/******/ 		
/******/ 				script.src = url;
/******/ 			}
/******/ 			inProgress[url] = [done];
/******/ 			var onScriptComplete = (prev, event) => {
/******/ 				// avoid mem leaks in IE.
/******/ 				script.onerror = script.onload = null;
/******/ 				clearTimeout(timeout);
/******/ 				var doneFns = inProgress[url];
/******/ 				delete inProgress[url];
/******/ 				script.parentNode && script.parentNode.removeChild(script);
/******/ 				doneFns && doneFns.forEach((fn) => (fn(event)));
/******/ 				if(prev) return prev(event);
/******/ 			}
/******/ 			var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);
/******/ 			script.onerror = onScriptComplete.bind(null, script.onerror);
/******/ 			script.onload = onScriptComplete.bind(null, script.onload);
/******/ 			needAttach && document.head.appendChild(script);
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/publicPath */
/******/ 	(() => {
/******/ 		var scriptUrl;
/******/ 		if (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + "";
/******/ 		var document = __webpack_require__.g.document;
/******/ 		if (!scriptUrl && document) {
/******/ 			if (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT')
/******/ 				scriptUrl = document.currentScript.src;
/******/ 			if (!scriptUrl) {
/******/ 				var scripts = document.getElementsByTagName("script");
/******/ 				if(scripts.length) {
/******/ 					var i = scripts.length - 1;
/******/ 					while (i > -1 && (!scriptUrl || !/^http(s?):/.test(scriptUrl))) scriptUrl = scripts[i--].src;
/******/ 				}
/******/ 			}
/******/ 		}
/******/ 		// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration
/******/ 		// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.
/******/ 		if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");
/******/ 		scriptUrl = scriptUrl.replace(/^blob:/, "").replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
/******/ 		__webpack_require__.p = scriptUrl + "../../";
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/jsonp chunk loading */
/******/ 	(() => {
/******/ 		// no baseURI
/******/ 		
/******/ 		// object to store loaded and loading chunks
/******/ 		// undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ 		// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ 		var installedChunks = {
/******/ 			705: 0
/******/ 		};
/******/ 		
/******/ 		__webpack_require__.f.j = (chunkId, promises) => {
/******/ 				// JSONP chunk loading for javascript
/******/ 				var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
/******/ 				if(installedChunkData !== 0) { // 0 means "already installed".
/******/ 		
/******/ 					// a Promise means "currently loading".
/******/ 					if(installedChunkData) {
/******/ 						promises.push(installedChunkData[2]);
/******/ 					} else {
/******/ 						if(true) { // all chunks have JS
/******/ 							// setup Promise in chunk cache
/******/ 							var promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));
/******/ 							promises.push(installedChunkData[2] = promise);
/******/ 		
/******/ 							// start chunk loading
/******/ 							var url = __webpack_require__.p + __webpack_require__.u(chunkId);
/******/ 							// create error before stack unwound to get useful stacktrace later
/******/ 							var error = new Error();
/******/ 							var loadingEnded = (event) => {
/******/ 								if(__webpack_require__.o(installedChunks, chunkId)) {
/******/ 									installedChunkData = installedChunks[chunkId];
/******/ 									if(installedChunkData !== 0) installedChunks[chunkId] = undefined;
/******/ 									if(installedChunkData) {
/******/ 										var errorType = event && (event.type === 'load' ? 'missing' : event.type);
/******/ 										var realSrc = event && event.target && event.target.src;
/******/ 										error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
/******/ 										error.name = 'ChunkLoadError';
/******/ 										error.type = errorType;
/******/ 										error.request = realSrc;
/******/ 										installedChunkData[1](error);
/******/ 									}
/******/ 								}
/******/ 							};
/******/ 							__webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId);
/******/ 						}
/******/ 					}
/******/ 				}
/******/ 		};
/******/ 		
/******/ 		// no prefetching
/******/ 		
/******/ 		// no preloaded
/******/ 		
/******/ 		// no HMR
/******/ 		
/******/ 		// no HMR manifest
/******/ 		
/******/ 		// no on chunks loaded
/******/ 		
/******/ 		// install a JSONP callback for chunk loading
/******/ 		var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
/******/ 			var [chunkIds, moreModules, runtime] = data;
/******/ 			// add "moreModules" to the modules object,
/******/ 			// then flag all "chunkIds" as loaded and fire callback
/******/ 			var moduleId, chunkId, i = 0;
/******/ 			if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
/******/ 				for(moduleId in moreModules) {
/******/ 					if(__webpack_require__.o(moreModules, moduleId)) {
/******/ 						__webpack_require__.m[moduleId] = moreModules[moduleId];
/******/ 					}
/******/ 				}
/******/ 				if(runtime) var result = runtime(__webpack_require__);
/******/ 			}
/******/ 			if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
/******/ 			for(;i < chunkIds.length; i++) {
/******/ 				chunkId = chunkIds[i];
/******/ 				if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ 					installedChunks[chunkId][0]();
/******/ 				}
/******/ 				installedChunks[chunkId] = 0;
/******/ 			}
/******/ 		
/******/ 		}
/******/ 		
/******/ 		var chunkLoadingGlobal = global["webpackChunknoodl_editor"] = global["webpackChunknoodl_editor"] || [];
/******/ 		chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
/******/ 		chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/nonce */
/******/ 	(() => {
/******/ 		__webpack_require__.nc = undefined;
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// This entry needs to be wrapped in an IIFE because it needs to be in strict mode.
(() => {
"use strict";

// EXTERNAL MODULE: ../../node_modules/@electron/remote/renderer/index.js
var renderer = __webpack_require__(52391);
// EXTERNAL MODULE: external "electron"
var external_electron_ = __webpack_require__(91288);
var external_electron_default = /*#__PURE__*/__webpack_require__.n(external_electron_);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(54953);
var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_);
// EXTERNAL MODULE: ../../node_modules/react-dom/client.js
var client = __webpack_require__(25873);
// EXTERNAL MODULE: ../noodl-platform/src/index.ts + 10 modules
var src = __webpack_require__(37218);
// EXTERNAL MODULE: external "path"
var external_path_ = __webpack_require__(16928);
var external_path_default = /*#__PURE__*/__webpack_require__.n(external_path_);
// EXTERNAL MODULE: external "mkdirp-sync"
var external_mkdirp_sync_ = __webpack_require__(66321);
var external_mkdirp_sync_default = /*#__PURE__*/__webpack_require__.n(external_mkdirp_sync_);
// EXTERNAL MODULE: external "rimraf"
var external_rimraf_ = __webpack_require__(55231);
var external_rimraf_default = /*#__PURE__*/__webpack_require__.n(external_rimraf_);
;// ../noodl-platform-node/src/storage-node.ts




function fileNameForKey(key) {
    const keyFileName = external_path_default().basename(key, ".json") + ".json";
    // Prevent ENOENT and other similar errors when using
    // reserved characters in Windows filenames.
    // See: https://en.wikipedia.org/wiki/Filename#Reserved%5Fcharacters%5Fand%5Fwords
    const escapedFileName = encodeURIComponent(keyFileName);
    const userDataPath = src.platform.getUserDataPath();
    return external_path_default().join(userDataPath, escapedFileName);
}
class StorageNode {
    async get(key) {
        try {
            const filename = fileNameForKey(key);
            const fileContent = await src.filesystem.readJson(filename);
            return fileContent;
        }
        catch (error) {
            // In some cases there is no json file
            // so we just return an empty object.
            return {};
        }
    }
    async set(key, data) {
        const filename = fileNameForKey(key);
        external_mkdirp_sync_default()(external_path_default().dirname(filename));
        await src.filesystem.writeJson(filename, data);
    }
    async remove(key) {
        var filename = fileNameForKey(key);
        return new Promise((resolve, reject) => {
            external_rimraf_default()(filename, (error) => {
                if (error) {
                    reject(error);
                }
                else {
                    resolve();
                }
            });
        });
    }
}

// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(79896);
var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_);
// EXTERNAL MODULE: external "fs-extra"
var external_fs_extra_ = __webpack_require__(59638);
var external_fs_extra_default = /*#__PURE__*/__webpack_require__.n(external_fs_extra_);
// EXTERNAL MODULE: external "jszip"
var external_jszip_ = __webpack_require__(69856);
var external_jszip_default = /*#__PURE__*/__webpack_require__.n(external_jszip_);
;// ../noodl-platform-node/src/filesystem-node.ts




class FileSystemNode {
    resolve(...paths) {
        return external_path_default().resolve(...paths);
    }
    join(...paths) {
        return external_path_default().join(...paths);
    }
    exists(path) {
        return external_fs_default().existsSync(path);
    }
    dirname(path) {
        return external_path_default().dirname(path);
    }
    basename(path) {
        return external_path_default().basename(path);
    }
    file(path) {
        const stat = external_fs_default().lstatSync(path);
        return { size: stat.size };
    }
    writeFile(path, blob) {
        if (typeof blob === 'string') {
            return external_fs_default().promises.writeFile(path, Buffer.from(blob));
        }
        return external_fs_default().promises.writeFile(path, blob);
    }
    async writeFileOverride(path, blob) {
        try {
            await this.removeFile(path);
        }
        catch (error) {
            // noop
        }
        await this.writeFile(path, blob);
    }
    /**
     * Read file content, with utf-8 encoding.
     *
     * @param path
     * @returns
     */
    readFile(path) {
        return external_fs_default().promises.readFile(path, 'utf8');
    }
    async readBinaryFile(path) {
        const content = await external_fs_default().promises.readFile(path, 'binary');
        return Buffer.from(content, 'binary');
    }
    removeFile(path) {
        return external_fs_default().promises.unlink(path);
    }
    renameFile(oldPath, newPath) {
        return external_fs_default().promises.rename(oldPath, newPath);
    }
    copyFile(from, to) {
        return external_fs_default().promises.copyFile(from, to);
    }
    copyFolder(from, to) {
        return new Promise((resolve, reject) => {
            external_fs_extra_default().copy(from, to, { recursive: true }, (err) => {
                if (err) {
                    reject(err);
                }
                else {
                    resolve();
                }
            });
        });
    }
    /**
     * Read a JSON file, with utf-8 encoding.
     *
     * @param path
     * @returns
     */
    async readJson(path) {
        const fileContent = await external_fs_default().promises.readFile(path, 'utf8');
        return JSON.parse(fileContent);
    }
    async writeJson(path, obj) {
        const tmpFileName = path + '.tmp-' + Date.now();
        let jsonText = '';
        try {
            jsonText = JSON.stringify(obj);
        }
        catch (error) {
            console.log('Error serializing json', error);
            throw error;
        }
        try {
            await external_fs_default().promises.writeFile(tmpFileName, jsonText);
            await external_fs_default().promises.rename(tmpFileName, path);
        }
        catch (error) {
            await external_fs_default().promises.unlink(tmpFileName);
            console.log('Error writing json file', error);
            throw error;
        }
    }
    /**
     * Returns whether the folder is empty.
     *
     * @param path
     * @returns Returns true, if the folder is empty; Otherwise, false.
     */
    async isDirectoryEmpty(path) {
        const files = await this.listDirectory(path);
        return files.length === 0;
    }
    /**
     * List all entries in the directory.
     *
     * @param path
     * @returns A list of all entries.
     */
    async listDirectory(path) {
        const files = await external_fs_default().promises.readdir(path);
        return files.map(function (f) {
            return {
                fullPath: path + '/' + f,
                name: f,
                isDirectory: external_fs_default().lstatSync(path + '/' + f).isDirectory()
            };
        });
    }
    /**
     * Returns all the files including all sub folders.
     *
     * @param path
     * @returns
     */
    listDirectoryFiles(path) {
        // https://stackoverflow.com/a/5827895
        const walk = function (dir, done) {
            let results = [];
            external_fs_default().readdir(dir, function (err, list) {
                if (err)
                    return done(err);
                let pending = list.length;
                if (!pending)
                    return done(null, results);
                list.forEach(function (file) {
                    file = external_path_default().resolve(dir, file);
                    external_fs_default().stat(file, function (err, stat) {
                        if (stat && stat.isDirectory()) {
                            walk(file, function (err, res) {
                                results = results.concat(res);
                                if (!--pending)
                                    done(null, results);
                            });
                        }
                        else {
                            results.push(file);
                            if (!--pending)
                                done(null, results);
                        }
                    });
                });
            });
        };
        return new Promise((resolve, reject) => {
            walk(path, function (error, files) {
                if (error) {
                    reject(error);
                }
                else {
                    resolve(files.map(function (fullPath) {
                        const isDirectory = (function () {
                            try {
                                return external_fs_default().lstatSync(fullPath).isDirectory();
                            }
                            catch (_err) {
                                return false;
                            }
                        })();
                        return {
                            fullPath,
                            name: external_path_default().basename(fullPath),
                            isDirectory
                        };
                    }));
                }
            });
        });
    }
    /**
     * https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/ensureDir.md
     * @param path
     * @returns
     */
    makeDirectory(path) {
        if (path.length === 0 || external_fs_default().existsSync(path)) {
            return Promise.resolve();
        }
        return new Promise((resolve, reject) => {
            (0,external_fs_extra_.mkdirp)(path, function (err) {
                if (err)
                    reject({ result: 'failure', err: err });
                else
                    resolve();
            });
        });
    }
    removeDirRecursive(path) {
        external_fs_extra_default().removeSync(path);
    }
    openDialog(args) {
        throw new Error('Not Supported');
    }
    unzipUrl(url, to) {
        const _this = this;
        function unzipToFolder(path, blob, callback) {
            external_jszip_default().loadAsync(blob)
                .then(function (zip) {
                let numFiles = Object.keys(zip.files).length;
                let err = false;
                function fileCompleted(_success) {
                    numFiles--;
                    if (numFiles === 0) {
                        if (err)
                            callback({ result: 'failure' });
                        else
                            callback({ result: 'success' });
                    }
                }
                Object.keys(zip.files).forEach(function (filename) {
                    if (zip.files[filename].dir) {
                        fileCompleted();
                        return;
                    } // Ignore dirs
                    let dest, buffer;
                    zip
                        .file(filename)
                        .async('nodebuffer')
                        .then((_buffer) => {
                        dest = external_path_default().join(path, filename);
                        buffer = _buffer;
                        return _this.makeDirectory(external_path_default().dirname(dest));
                    })
                        .then(() => {
                        external_fs_default().writeFileSync(dest, buffer);
                        fileCompleted();
                    })
                        .catch((e) => {
                        err = e;
                        fileCompleted(false);
                    });
                });
            })
                .catch(function (e) {
                callback({ result: 'failure' });
            });
        }
        return new Promise((resolve, reject) => {
            // Make sure the folder is empty
            const isEmpty = this.isDirectoryEmpty(to);
            if (!isEmpty) {
                reject({ result: 'failure', message: 'Folder must be empty' });
                return;
            }
            // Load zip file from URL
            // @ts-ignore XMLHttpRequest
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function (_e) {
                unzipToFolder(to, this.response, function (r) {
                    if (r.result !== 'success') {
                        reject({ result: 'failure', message: 'Failed to extract' });
                        _this.removeDirRecursive(to);
                        return;
                    }
                    resolve();
                });
            };
            xhr.send();
        });
    }
    makeUniquePath(path) {
        let _path = path;
        let count = 1;
        while (external_fs_default().existsSync(_path)) {
            _path = path + '-' + count;
            count++;
        }
        return _path;
    }
}

;// ../noodl-platform-electron/src/filesystem-electron.ts


class FileSystemElectron extends FileSystemNode {
    openDialog(args) {
        return new Promise((resolve, reject) => {
            const properties = ['openDirectory'];
            if (args === null || args === void 0 ? void 0 : args.allowCreateDirectory) {
                properties.push('createDirectory');
            }
            renderer.dialog.showOpenDialog({ properties }).then((res) => {
                if (res.canceled) {
                    reject();
                }
                else {
                    resolve(res.filePaths[0]);
                }
            });
        });
    }
}

;// ../noodl-platform-node/src/helper.ts

function processPlatformToPlatformOS() {
    switch (process.platform) {
        default:
            return src.PlatformOS.Unknown;
        case "darwin":
            return src.PlatformOS.MacOS;
        case "win32":
            return src.PlatformOS.Windows;
        case "linux":
            return src.PlatformOS.Linux;
    }
}

;// ../noodl-platform-electron/src/platform-electron.ts





class PlatformElectron {
    get name() {
        return 'Electron';
    }
    get os() {
        return this._os;
    }
    constructor() {
        const app = (__webpack_require__(91288).app) || (__webpack_require__(52391).app);
        this._userDataPath = app.getPath('userData');
        this._documentsPath = app.getPath('documents');
        this._tempPath = (0,src.addTrailingSlash)(app.getPath('temp'));
        this._appPath = (0,src.addTrailingSlash)(app.getAppPath());
        const packagePath = external_path_default().join(this._appPath, 'package.json');
        if (!external_fs_default().existsSync(packagePath)) {
            throw 'Cannot find package.json, to get the build version.';
        }
        const packageJson = external_fs_default().readFileSync(packagePath, 'utf8');
        const packageContent = JSON.parse(packageJson);
        this._buildNumber = packageContent.buildNumber || 1;
        this._version = (__webpack_require__(52391).app).getVersion();
        this._versionId = packageContent.fullVersion;
        this._versionTag = packageContent.versionTag;
        this._os = processPlatformToPlatformOS();
    }
    getBuildNumber() {
        return this._buildNumber;
    }
    getFullVersion() {
        return this._versionId;
    }
    getVersion() {
        return this._version;
    }
    getVersionWithTag() {
        return this._versionTag ? `${this._version}-${this._versionTag}` : this._version;
    }
    getUserDataPath() {
        return this._userDataPath;
    }
    getDocumentsPath() {
        return this._documentsPath;
    }
    getTempPath() {
        return this._tempPath;
    }
    getAppPath() {
        return this._appPath;
    }
    openExternal(url) {
        return external_electron_.shell.openExternal(url);
    }
    copyToClipboard(value) {
        external_electron_.clipboard.writeText(value);
        return Promise.resolve();
    }
}

;// ../noodl-platform-electron/src/index.ts




(0,src.setPlatform)(new PlatformElectron());
(0,src.setFileSystem)(new FileSystemElectron());
(0,src.setStorage)(new StorageNode());

// EXTERNAL MODULE: ./src/editor/src/utils/tracker/index.ts + 1 modules
var tracker = __webpack_require__(38986);
// EXTERNAL MODULE: ./src/editor/src/utils/bugtracker.ts
var bugtracker = __webpack_require__(90962);
;// ./src/editor/process-setup.ts
/* eslint-disable */
/*
  This file is added to .prettierignore too!

  It is very important that the steps in here are done in the right order.
*/
// Setup the platform before anything else is loading
// This is a problem since we are calling the platform when importing

// Setup the tracker to send to Mixpanel,
// Very important that this is before anything else.



// EXTERNAL MODULE: ./src/shared/utils/EventDispatcher.ts
var EventDispatcher = __webpack_require__(11138);
// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/index.ts
var nodelibrary = __webpack_require__(68091);
// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.ts + 4 modules
var projectmodel = __webpack_require__(6203);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js
var injectStylesIntoStyleTag = __webpack_require__(72591);
var injectStylesIntoStyleTag_default = /*#__PURE__*/__webpack_require__.n(injectStylesIntoStyleTag);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleDomAPI.js
var styleDomAPI = __webpack_require__(1740);
var styleDomAPI_default = /*#__PURE__*/__webpack_require__.n(styleDomAPI);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertBySelector.js
var insertBySelector = __webpack_require__(88128);
var insertBySelector_default = /*#__PURE__*/__webpack_require__.n(insertBySelector);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js
var setAttributesWithoutAttributes = __webpack_require__(30855);
var setAttributesWithoutAttributes_default = /*#__PURE__*/__webpack_require__.n(setAttributesWithoutAttributes);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/insertStyleElement.js
var insertStyleElement = __webpack_require__(93051);
var insertStyleElement_default = /*#__PURE__*/__webpack_require__.n(insertStyleElement);
// EXTERNAL MODULE: ../../node_modules/style-loader/dist/runtime/styleTagTransform.js
var styleTagTransform = __webpack_require__(73656);
var styleTagTransform_default = /*#__PURE__*/__webpack_require__.n(styleTagTransform);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!./src/editor/src/styles/custom-properties/animations.css
var animations = __webpack_require__(16406);
;// ./src/editor/src/styles/custom-properties/animations.css

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (styleTagTransform_default());
options.setAttributes = (setAttributesWithoutAttributes_default());

      options.insert = insertBySelector_default().bind(null, "head");
    
options.domAPI = (styleDomAPI_default());
options.insertStyleElement = (insertStyleElement_default());

var update = injectStylesIntoStyleTag_default()(animations/* default */.A, options);




       /* harmony default export */ const custom_properties_animations = (animations/* default */.A && animations/* default */.A.locals ? animations/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!./src/editor/src/styles/custom-properties/fonts.css
var fonts = __webpack_require__(70533);
;// ./src/editor/src/styles/custom-properties/fonts.css

      
      
      
      
      
      
      
      
      

var fonts_options = {};

fonts_options.styleTagTransform = (styleTagTransform_default());
fonts_options.setAttributes = (setAttributesWithoutAttributes_default());

      fonts_options.insert = insertBySelector_default().bind(null, "head");
    
fonts_options.domAPI = (styleDomAPI_default());
fonts_options.insertStyleElement = (insertStyleElement_default());

var fonts_update = injectStylesIntoStyleTag_default()(fonts/* default */.A, fonts_options);




       /* harmony default export */ const custom_properties_fonts = (fonts/* default */.A && fonts/* default */.A.locals ? fonts/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!./src/editor/src/styles/custom-properties/colors.css
var colors = __webpack_require__(27283);
;// ./src/editor/src/styles/custom-properties/colors.css

      
      
      
      
      
      
      
      
      

var colors_options = {};

colors_options.styleTagTransform = (styleTagTransform_default());
colors_options.setAttributes = (setAttributesWithoutAttributes_default());

      colors_options.insert = insertBySelector_default().bind(null, "head");
    
colors_options.domAPI = (styleDomAPI_default());
colors_options.insertStyleElement = (insertStyleElement_default());

var colors_update = injectStylesIntoStyleTag_default()(colors/* default */.A, colors_options);




       /* harmony default export */ const custom_properties_colors = (colors/* default */.A && colors/* default */.A.locals ? colors/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[5].use[1]!./src/editor/src/styles/custom-properties/spacing.css
var spacing = __webpack_require__(31484);
;// ./src/editor/src/styles/custom-properties/spacing.css

      
      
      
      
      
      
      
      
      

var spacing_options = {};

spacing_options.styleTagTransform = (styleTagTransform_default());
spacing_options.setAttributes = (setAttributesWithoutAttributes_default());

      spacing_options.insert = insertBySelector_default().bind(null, "head");
    
spacing_options.domAPI = (styleDomAPI_default());
spacing_options.insertStyleElement = (insertStyleElement_default());

var spacing_update = injectStylesIntoStyleTag_default()(spacing/* default */.A, spacing_options);




       /* harmony default export */ const custom_properties_spacing = (spacing/* default */.A && spacing/* default */.A.locals ? spacing/* default */.A.locals : undefined);

// EXTERNAL MODULE: ./src/editor/src/models/lessontemplatesmodel.js
var lessontemplatesmodel = __webpack_require__(85130);
var lessontemplatesmodel_default = /*#__PURE__*/__webpack_require__.n(lessontemplatesmodel);
// EXTERNAL MODULE: ./src/editor/src/views/popuplayer.js
var popuplayer = __webpack_require__(45653);
var popuplayer_default = /*#__PURE__*/__webpack_require__.n(popuplayer);
// EXTERNAL MODULE: ./src/editor/src/utils/keyboardhandler.ts
var keyboardhandler = __webpack_require__(70441);
// EXTERNAL MODULE: ./src/editor/src/utils/editorapi.js
var editorapi = __webpack_require__(99604);
// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/index.ts
var AiAssistant = __webpack_require__(10142);
;// ./src/editor/src/pages/AppRoute.ts
class AppRoute {
    constructor(router) {
        this.router = router;
    }
}

// EXTERNAL MODULE: ./src/editor/src/contexts/NodeGraphContext/NodeGraphContext.tsx
var NodeGraphContext = __webpack_require__(18498);
// EXTERNAL MODULE: ./src/editor/src/hooks/useModel.ts
var useModel = __webpack_require__(85755);
// EXTERNAL MODULE: ./src/editor/src/models/undo-queue-model.ts
var undo_queue_model = __webpack_require__(50867);
// EXTERNAL MODULE: ./src/shared/model.js
var model = __webpack_require__(47821);
var model_default = /*#__PURE__*/__webpack_require__.n(model);
;// ./src/editor/src/models/StylesModel.ts




class StylesModel extends (model_default()) {
    constructor() {
        super();
        this.styles = projectmodel.ProjectModel.instance.getMetaData('styles') || {};
        this.bindListeners();
    }
    bindListeners() {
        const onStylesUpdated = () => {
            this.styles = projectmodel.ProjectModel.instance.getMetaData('styles') || {};
            this.notifyListeners('stylesChanged', { type: 'text' });
            this.notifyListeners('stylesChanged', { type: 'colors' });
        };
        EventDispatcher.EventDispatcher.instance.on(['ProjectModel.importComplete', 'ProjectModel.instanceHasChanged'], () => {
            if (projectmodel.ProjectModel.instance) {
                onStylesUpdated();
            }
        }, this);
        EventDispatcher.EventDispatcher.instance.on('ProjectModel.metadataChanged', ({ key }) => {
            if (key === 'styles') {
                onStylesUpdated();
            }
        }, this);
    }
    unbindListeners() {
        EventDispatcher.EventDispatcher.instance.off(this);
    }
    dispose() {
        this.unbindListeners();
        this.removeAllListeners();
    }
    store() {
        this.unbindListeners();
        projectmodel.ProjectModel.instance.setMetaData('styles', this.styles);
        this.bindListeners();
    }
    getStyles(type) {
        return Object.keys(this.styles[type] || {}).map((name) => {
            return {
                name,
                style: this.styles[type][name]
            };
        });
    }
    styleExists(type, name) {
        const styles = this.styles[type];
        return styles && styles.hasOwnProperty(name);
    }
    deleteStyle(type, name, args) {
        if (!this.styles[type] || !this.styleExists(type, name))
            return;
        const style = this.styles[type][name];
        delete this.styles[type][name];
        this.store();
        this.notifyListeners('stylesChanged', { type });
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo &&
                undo.push({
                    label: args.label,
                    do: () => {
                        this.deleteStyle(name, type);
                    },
                    undo: () => {
                        this.setStyle(type, name, style);
                    }
                });
        }
    }
    setStyle(type, name, newStyle, args) {
        if (this.styles[type] && this.styles[type][name] === newStyle)
            return;
        if (!this.styles[type]) {
            this.styles[type] = {};
        }
        const prevStyle = this.styles[type][name];
        this.styles[type][name] = newStyle;
        this.store();
        this.notifyListeners('stylesChanged', { type });
        this.notifyListeners('styleChanged', { type, name, style: newStyle });
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo &&
                undo.push({
                    label: args.label,
                    do: () => {
                        this.setStyle(type, name, newStyle);
                    },
                    undo: () => {
                        this.setStyle(type, name, prevStyle);
                    }
                });
        }
    }
    changeStyleName(type, name, newName, args) {
        if (!this.styleExists(type, name))
            return;
        if (this.styleExists(type, newName))
            return;
        const style = this.styles[type][name];
        delete this.styles[type][name];
        this.styles[type][newName] = style;
        renameStylesOnNodes(type, name, newName);
        this.store();
        this.notifyListeners('stylesChanged', { type });
        this.notifyListeners('styleRenamed', { type, oldName: name, name: newName });
        if (args && args.undo) {
            const undo = typeof args.undo === 'object' ? args.undo : undo_queue_model/* UndoQueue */.g.instance;
            undo &&
                undo.push({
                    label: args.label,
                    do: () => {
                        this.changeStyleName(type, name, newName);
                    },
                    undo: () => {
                        this.changeStyleName(type, newName, name);
                    }
                });
        }
    }
}
function renameStyle(nodeOrVariant, portType, name, newName) {
    const stylePortNames = nodeOrVariant
        .getPorts('input')
        .filter((p) => (p.type.name || p.type) === portType)
        .map((p) => p.name);
    if (nodeOrVariant.stateParameters) {
        for (const state of Object.keys(nodeOrVariant.stateParameters)) {
            for (const port of stylePortNames) {
                if (nodeOrVariant.stateParameters[state][port] === name) {
                    nodeOrVariant.setParameter(port, newName, { state });
                }
            }
        }
    }
    if (nodeOrVariant.parameters) {
        for (const port of stylePortNames) {
            if (nodeOrVariant.parameters[port] === name) {
                nodeOrVariant.setParameter(port, newName);
            }
        }
    }
}
//TODO: this needs to work with variants and states as well
function renameStylesOnNodes(styleType, name, newName) {
    let portType;
    switch (styleType) {
        case 'text':
            portType = 'textStyle';
            break;
        case 'colors':
            portType = 'color';
            break;
        default:
            return;
    }
    //look in parameters, variants, and all visual states
    const components = projectmodel.ProjectModel.instance.getComponents();
    components.forEach((c) => {
        c.graph.forEachNode((node) => {
            renameStyle(node, portType, name, newName);
        });
    });
    const variants = projectmodel.ProjectModel.instance.getAllVariants();
    for (const variant of variants) {
        renameStyle(variant, portType, name, newName);
    }
}

;// ./src/editor/src/contexts/ProjectDesignTokenContext/extractProjectColors.ts

function extractProjectColors(project, colorStyles) {
    const colors = {};
    const components = project.getComponents();
    components.forEach((c) => {
        c.graph.forEachNode((node) => {
            const colorPorts = node.getPorts('input').filter((p) => p.type === 'color');
            const values = colorPorts.map((port) => node.getParameter(port.name));
            values
                .filter((name) => name)
                .forEach((name) => {
                if (!colors[name]) {
                    colors[name] = {
                        name,
                        color: null,
                        refs: []
                    };
                }
                colors[name].refs.push(node.type.name);
            });
        });
    });
    const staticColors = Object.values(colors)
        .filter((c) => colorStyles.find((s) => s.name === c.name))
        .sort((a, b) => a.name.localeCompare(b.name))
        .map((x) => ({
        name: x.name,
        refs: x.refs,
        color: projectmodel.ProjectModel.instance.resolveColor(x.name)
    }));
    const dynamicColors = Object.values(colors)
        // remove all color styles from the list, so we only get the #HEX colors
        .filter((c) => !colorStyles.find((s) => s.name === c.name))
        .sort((a, b) => a.name.localeCompare(b.name))
        .map((x) => ({
        name: x.name,
        refs: x.refs,
        color: projectmodel.ProjectModel.instance.resolveColor(x.name)
    }));
    return {
        staticColors,
        dynamicColors
    };
}

;// ./src/editor/src/contexts/ProjectDesignTokenContext/ProjectDesignTokenContext.tsx





const ProjectDesignTokenContext = (0,external_react_.createContext)({
    staticColors: [],
    dynamicColors: [],
    textStyles: []
});
function ProjectDesignTokenContextProvider({ children }) {
    (0,useModel/* useModel */.f)(projectmodel.ProjectModel.instance);
    const [group] = (0,external_react_.useState)({});
    const [staticColors, setStaticColors] = (0,external_react_.useState)([]);
    const [dynamicColors, setDynamicColors] = (0,external_react_.useState)([]);
    const [textStyles, setTextStyles] = (0,external_react_.useState)([]);
    (0,external_react_.useEffect)(() => {
        const stylesModel = new StylesModel();
        function extract() {
            const styles = stylesModel.getStyles('colors');
            const colors = extractProjectColors(projectmodel.ProjectModel.instance, styles);
            const textStyles = stylesModel.getStyles('text');
            setStaticColors(colors.staticColors);
            setDynamicColors(colors.dynamicColors);
            setTextStyles(textStyles);
        }
        stylesModel.on('stylesChanged', (args) => {
            if (['colors', 'text'].includes(args.type)) {
                extract();
            }
        });
        extract();
        return () => {
            stylesModel.dispose();
            projectmodel.ProjectModel.instance.off(group);
        };
    }, []);
    return (external_react_default().createElement(ProjectDesignTokenContext.Provider, { value: {
            staticColors,
            dynamicColors,
            textStyles
        } }, children));
}
function useProjectDesignTokenContext() {
    const context = (0,external_react_.useContext)(ProjectDesignTokenContext);
    if (context === undefined) {
        throw new Error('useProjectDesignTokenContext must be a child of ProjectDesignTokenContextProvider');
    }
    return context;
}

;// ./src/editor/src/contexts/ProjectDesignTokenContext/index.ts


// EXTERNAL MODULE: ./src/editor/src/models/sidebar/index.ts
var models_sidebar = __webpack_require__(53612);
// EXTERNAL MODULE: ./src/editor/src/models/sidebar/sidebarmodel.tsx
var sidebarmodel = __webpack_require__(41669);
;// ./src/editor/src/hooks/useKeyboardCommands.ts





function useKeyboardCommands(createCommandsFn, deps) {
    (0,external_react_.useEffect)(() => {
        const commands = createCommandsFn();
        keyboardhandler["default"].instance.registerCommands(commands);
        return () => {
            keyboardhandler["default"].instance.deregisterCommands(commands);
        };
    }, deps || []);
}
/**
 * The Side Panel is always active,
 * so lets unregister the commands while it is not visible.
 *
 * @param createCommandsFn
 * @param panelId
 * @param deps
 */
function useSidePanelKeyboardCommands(createCommandsFn, panelId, deps) {
    const sidebarModel = (0,useModel/* useModernModel */.e)(models_sidebar/* SidebarModel */.s.instance, [sidebarmodel/* SidebarModelEvent */.q.activeChanged]);
    const activeId = sidebarModel.ActiveId;
    (0,external_react_.useEffect)(() => {
        if (activeId !== panelId)
            return;
        const commands = createCommandsFn();
        keyboardhandler["default"].instance.registerCommands(commands);
        return () => {
            keyboardhandler["default"].instance.deregisterCommands(commands);
        };
    }, [...(deps || []), panelId, activeId]);
}

;// ./src/editor/src/models/app.ts

class App extends (model_default()) {
    /**
     * Exit the Editor project.
     *
     * There is a listener in router.js that close the app.
     */
    exitProject() {
        this.notifyListeners('exitEditor');
    }
    maximize() {
        const win = (__webpack_require__(52391).getCurrentWindow)();
        win.isMaximized() ? win.unmaximize() : win.maximize();
    }
    minimize() {
        const win = (__webpack_require__(52391).getCurrentWindow)();
        win.minimize();
    }
    close() {
        const win = (__webpack_require__(52391).getCurrentWindow)();
        win.close();
    }
}
App.instance = new App();

;// ./src/editor/src/models/app_registry.ts


class AppRegistry extends (model_default()) {
    constructor() {
        super(...arguments);
        this.documentProviders = {};
    }
    get CurrentDocumentId() {
        return this.activeDocumentId;
    }
    getActiveDocument() {
        return this.activeDocument;
    }
    registerDocumentProvider(id, provider) {
        if (!provider.getComponent) {
            throw new Error('Invalid Document Provider');
        }
        const isReplaced = !!this.documentProviders[id];
        this.documentProviders[id] = provider;
        if (isReplaced && this.activeDocumentId === id) {
            this.activeDocument = provider.getComponent();
            this.notifyListeners('documentChanged');
        }
    }
    openDocument(id, props) {
        const provider = this.documentProviders[id];
        if (provider) {
            this.activeDocumentId = id;
            this.activeDocument = () => external_react_default().createElement(provider.getComponent(), props);
            this.notifyListeners('documentChanged');
            return;
        }
        throw new Error('Document Provider not registered.');
    }
}
AppRegistry.instance = new AppRegistry();

// EXTERNAL MODULE: ./src/editor/src/models/CloudServices/index.ts + 3 modules
var CloudServices = __webpack_require__(48153);
// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/NodeLibraryImporter.ts
var NodeLibraryImporter = __webpack_require__(42146);
// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.editor.ts
var projectmodel_editor = __webpack_require__(46998);
// EXTERNAL MODULE: ./src/editor/src/ViewerConnection.ts
var ViewerConnection = __webpack_require__(71336);
// EXTERNAL MODULE: ./src/editor/src/views/ToastLayer/ToastLayer.tsx
var ToastLayer = __webpack_require__(80424);
// EXTERNAL MODULE: ./src/editor/src/utils/filesystem.js
var filesystem = __webpack_require__(38656);
var filesystem_default = /*#__PURE__*/__webpack_require__.n(filesystem);
// EXTERNAL MODULE: ./src/editor/src/utils/projectimporter.js
var projectimporter = __webpack_require__(11684);
var projectimporter_default = /*#__PURE__*/__webpack_require__.n(projectimporter);
// EXTERNAL MODULE: ./src/editor/src/utils/utils.ts
var utils = __webpack_require__(93015);
;// ./src/editor/src/utils/exportProjectComponets.ts







const ImportPopup = __webpack_require__(52501);
const ExportPopupTemplate = __webpack_require__(97467);
const archiver = __webpack_require__(80786);
const editor_fs = __webpack_require__(79896);
function _zipFolderContent(options) {
    const output = editor_fs.createWriteStream(options.output);
    const archive = archiver('zip', {
        zlib: { level: 9 } // Sets the compression level.
    });
    function _readDirRec(dir, _res) {
        const res = _res || [];
        const files = editor_fs.readdirSync(dir);
        files.forEach((f) => {
            const stats = editor_fs.statSync(dir + '/' + f);
            if (stats && stats.isDirectory()) {
                _readDirRec(dir + '/' + f, res);
            }
            else {
                res.push(dir + '/' + f);
            }
        });
        return res;
    }
    return new Promise(function (resolve, reject) {
        const folderPath = options.folder;
        // @ts-expect-error
        const files = _readDirRec(folderPath);
        const f = files.pop();
        archive.file(f, { name: f.substring(folderPath.length + 1) });
        // good practice to catch warnings (ie stat failures and other non-blocking errors)
        archive.on('warning', function (err) {
            console.log(err);
        });
        // good practice to catch this error explicitly
        archive.on('error', function (err) {
            reject(err);
        });
        archive.on('entry', function (arg) {
            //console.log(arg.name,arg.sourcePath);
            if (files.length > 0) {
                const f = files.pop();
                archive.file(f, { name: f.substring(folderPath.length + 1) });
            }
            else {
                archive.finalize();
            }
        });
        output.on('close', function () {
            resolve(undefined);
        });
        // pipe archive data to the file
        archive.pipe(output);
    });
}
function exportProjectComponents() {
    projectimporter_default().instance.listComponentsAndDependencies(projectmodel.ProjectModel.instance._retainedProjectDirectory, (imports) => {
        const activityId = 'exporting-components';
        // Show popup and allow the user to choose which components to export
        // we reuse the import popup with a new template
        var chooseExportsPopup = new ImportPopup({
            template: ExportPopupTemplate,
            imports: imports,
            onOk: function () {
                ToastLayer.ToastLayer.showActivity('Exporting...', activityId);
                // Export to temporary directory
                const exportName = 'export-' + (0,utils.guid)();
                const exportDir = filesystem_default().instance.getTempPath() + exportName;
                filesystem_default().instance.makeDirectorySync(exportDir);
                const project = projectmodel.ProjectModel.fromJSON({
                    name: 'Export',
                    components: [],
                    settings: {},
                    version: '3',
                    metadata: {},
                    variants: []
                });
                project._retainedProjectDirectory = exportDir;
                const selectedExports = chooseExportsPopup.getSelectedImports();
                ViewerConnection/* ViewerConnection */.t.instance.setWatchModelChangesEnabled(false);
                projectimporter_default().instance.import(projectmodel.ProjectModel.instance._retainedProjectDirectory, selectedExports, (r) => {
                    ViewerConnection/* ViewerConnection */.t.instance.setWatchModelChangesEnabled(true);
                    popuplayer_default().instance.hideModal();
                    if (r.result !== 'success') {
                        ToastLayer.ToastLayer.hideActivity(activityId);
                        ToastLayer.ToastLayer.showError(r.message);
                        return;
                    }
                    project.toDirectory(project._retainedProjectDirectory, (r) => {
                        if (r.result !== 'success') {
                            ToastLayer.ToastLayer.hideActivity(activityId);
                            ToastLayer.ToastLayer.showSuccess(r.message);
                        }
                        else {
                            filesystem_default().instance.chooseDirectory(function (direntry) {
                                if (!direntry) {
                                    ToastLayer.ToastLayer.hideActivity(activityId);
                                    return;
                                }
                                _zipFolderContent({ folder: exportDir, output: direntry + '/' + exportName + '.zip' })
                                    .then(() => {
                                    ToastLayer.ToastLayer.hideActivity(activityId);
                                    ToastLayer.ToastLayer.showSuccess('Export successful');
                                })
                                    .catch(() => {
                                    ToastLayer.ToastLayer.hideActivity(activityId);
                                    ToastLayer.ToastLayer.showError('Failed to create archive');
                                });
                            });
                        }
                    });
                }, { importIntoProject: project });
            },
            onCancel: function () {
                popuplayer_default().instance.hideModal();
            }
        });
        chooseExportsPopup.render();
        chooseExportsPopup.el.css('width', '500px'); // Make it a little bit wider as a modal
        ToastLayer.ToastLayer.hideActivity(activityId);
        popuplayer_default().instance.showModal({
            content: chooseExportsPopup
        });
    });
}

// EXTERNAL MODULE: ./src/editor/src/utils/keyboard/KeyCode.ts
var KeyCode = __webpack_require__(7444);
// EXTERNAL MODULE: ./src/editor/src/utils/LocalProjectsModel.ts + 4 modules
var LocalProjectsModel = __webpack_require__(47426);
// EXTERNAL MODULE: external "express"
var external_express_ = __webpack_require__(99594);
var external_express_default = /*#__PURE__*/__webpack_require__.n(external_express_);
// EXTERNAL MODULE: ../noodl-parse-dashboard/Parse-Dashboard/app.js
var Parse_Dashboard_app = __webpack_require__(22275);
var app_default = /*#__PURE__*/__webpack_require__.n(Parse_Dashboard_app);
;// ./src/editor/src/utils/parsedashboardserver.ts



const { BrowserWindow } = __webpack_require__(52391);
class ParseDashboardServer {
    /**
     * Open the parse dashboard in the browser.
     *
     * @param environment The environment we want to open with.
     */
    openInBrowser(environment) {
        this.start(environment, (port) => {
            external_electron_default().shell.openExternal(`http://localhost:${port}`);
        });
    }
    /**
     * Open the parse dashboard in a new window.
     *
     * @param environment The environment we want to open with.
     */
    openInWindow(environment) {
        this.start(environment, (port) => {
            if (this.browserWin) {
                this.browserWin.focus();
            }
            else {
                this.browserWin = new BrowserWindow({
                    width: 1280,
                    height: 600,
                    center: true,
                    title: 'Cloud Services Dashboard'
                });
                this.browserWin.on('close', () => {
                    this.browserWin = undefined;
                });
                this.browserWin.loadURL(`http://localhost:${port}`);
            }
        });
    }
    stop() {
        this.currentEnvironment = null;
        if (this.browserWin) {
            this.browserWin.close();
            this.browserWin = undefined;
        }
        if (this.httpServer) {
            this.httpServer.close();
            this.httpServer = undefined;
        }
    }
    start(environment, cb) {
        const alreadyRunning = this.currentEnvironment &&
            this.currentEnvironment.url === environment.url &&
            this.currentEnvironment.appId === environment.appId;
        if (alreadyRunning) {
            cb(this.port);
        }
        else
            this.startWebServer(environment, (port) => {
                this.port = port;
                cb(port);
            });
    }
    startWebServer(environment, cb) {
        // @ts-expect-error
        let endpoint = environment.url || environment.endpoint;
        if (endpoint.endsWith('/')) {
            endpoint = endpoint.slice(0, -1);
        }
        //app name is used as an url in the dashboard, so strip away some characters so the URLs arent invalid
        //url-encoding breaks the dashboard in some cases for some reason, so just stripping away : and / for now
        const appName = environment.name.replace(/\//g, '').replace(/\:/g, '');
        // @ts-ignore
        const dashboard = new (app_default())({
            apps: [
                {
                    serverURL: endpoint,
                    appId: environment.appId || environment.url.split(':')[0] + '-' + environment.id,
                    masterKey: environment.masterKey,
                    appName: appName,
                    graphQLServerURL: endpoint + '/graphql'
                }
            ]
        });
        const app = external_express_default()();
        app.use('/', dashboard);
        this.stop(); //stop running server (if any) so there's only one
        this.httpServer = app.listen(0, () => {
            //save current config
            this.currentEnvironment = environment;
            const address = this.httpServer.address();
            if (typeof address === 'string')
                throw new Error('Invalid server address type.');
            cb(address.port);
        });
    }
}
ParseDashboardServer.instance = new ParseDashboardServer();
/* harmony default export */ const parsedashboardserver = (ParseDashboardServer);

// EXTERNAL MODULE: ./src/editor/src/utils/projectvalidator.js
var projectvalidator = __webpack_require__(59734);
var projectvalidator_default = /*#__PURE__*/__webpack_require__.n(projectvalidator);
// EXTERNAL MODULE: ./src/editor/src/utils/schemahandler.ts
var schemahandler = __webpack_require__(96543);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/ActivityIndicator/index.ts + 2 modules
var ActivityIndicator = __webpack_require__(12093);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/inputs/PrimaryButton/index.ts + 2 modules
var inputs_PrimaryButton = __webpack_require__(76302);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Box/index.ts + 2 modules
var Box = __webpack_require__(22484);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Collapsible/index.ts + 2 modules
var Collapsible = __webpack_require__(20014);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Stack/index.ts + 2 modules
var Stack = __webpack_require__(86380);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Label/index.ts + 2 modules
var Label = __webpack_require__(91629);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/index.ts
var typography_Text = __webpack_require__(93834);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/common/ErrorBoundary/ErrorBoundary.module.scss
var ErrorBoundary_module = __webpack_require__(1696);
;// ../noodl-core-ui/src/components/common/ErrorBoundary/ErrorBoundary.module.scss

      
      
      
      
      
      
      
      
      

var ErrorBoundary_module_options = {};

ErrorBoundary_module_options.styleTagTransform = (styleTagTransform_default());
ErrorBoundary_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ErrorBoundary_module_options.insert = insertBySelector_default().bind(null, "head");
    
ErrorBoundary_module_options.domAPI = (styleDomAPI_default());
ErrorBoundary_module_options.insertStyleElement = (insertStyleElement_default());

var ErrorBoundary_module_update = injectStylesIntoStyleTag_default()(ErrorBoundary_module/* default */.A, ErrorBoundary_module_options);




       /* harmony default export */ const ErrorBoundary_ErrorBoundary_module = (ErrorBoundary_module/* default */.A && ErrorBoundary_module/* default */.A.locals ? ErrorBoundary_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/common/ErrorBoundary/ErrorBoundary.tsx








// https://reactjs.org/docs/error-boundaries.html
class ErrorBoundary extends (external_react_default()).Component {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
            errorInfo: null,
            showMore: false
        };
    }
    componentDidCatch(error, errorInfo) {
        // Catch errors in any components below and re-render with error message
        this.setState({
            error: error,
            errorInfo: errorInfo
        });
        // You can also log error messages to an error reporting service here
    }
    render() {
        if (this.state.errorInfo) {
            const onCopyError = () => {
                var _a;
                navigator.clipboard.writeText(JSON.stringify({
                    // TODO: Add Noodl version etc
                    error: (_a = this.state.error) === null || _a === void 0 ? void 0 : _a.toString(),
                    stack: this.state.errorInfo.componentStack
                }));
                // TODO: Add some user feedback, this component should probably be in the editor
            };
            // Error path
            return (external_react_default().createElement("div", { className: ErrorBoundary_ErrorBoundary_module['Root'] },
                external_react_default().createElement("div", { className: ErrorBoundary_ErrorBoundary_module['Center'] },
                    external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, UNSAFE_style: { width: '100%', boxSizing: 'border-box' } },
                        external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Big, hasBottomSpacing: true }, "Aw, Snap!"),
                        external_react_default().createElement(typography_Text/* Text */.EY, null, "Something happened."),
                        this.props.showTryAgain && (external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
                            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                                external_react_default().createElement(Box/* Box */.a, null,
                                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, label: "Click here to try again", onClick: this.props.onTryAgain }))))))),
                this.props.hideCopyError !== true && (external_react_default().createElement("div", { style: { position: 'absolute', bottom: 0, width: '100%' } },
                    external_react_default().createElement("div", { style: { background: 'var(--theme-color-bg-2)', borderTop: '1px solid var(--theme-color-bg-1)' } },
                        external_react_default().createElement("div", { className: ErrorBoundary_ErrorBoundary_module['Container'] },
                            external_react_default().createElement(Collapsible/* Collapsible */.N, { isCollapsed: !this.state.showMore },
                                external_react_default().createElement("pre", null,
                                    external_react_default().createElement("span", { className: ErrorBoundary_ErrorBoundary_module['Error'] }, this.state.error && this.state.error.toString()),
                                    external_react_default().createElement("span", null, this.state.errorInfo.componentStack))))),
                    external_react_default().createElement("div", { className: ErrorBoundary_ErrorBoundary_module['Container'] },
                        external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                            this.props.hideErrorStack !== true && (external_react_default().createElement(Box/* Box */.a, null,
                                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, label: "More info", onClick: () => this.setState((prev) => ({
                                        showMore: !prev.showMore
                                    })), hasBottomSpacing: true }))),
                            external_react_default().createElement(Box/* Box */.a, null,
                                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Ghost, size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, label: "Copy Error Message", onClick: onCopyError }))))))));
        }
        // Normally, just render children
        return this.props.children;
    }
}

;// ../noodl-core-ui/src/components/common/ErrorBoundary/index.ts


// EXTERNAL MODULE: external "classnames"
var external_classnames_ = __webpack_require__(12678);
var external_classnames_default = /*#__PURE__*/__webpack_require__.n(external_classnames_);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/FrameDivider/FrameDivider.module.scss
var FrameDivider_module = __webpack_require__(72927);
;// ../noodl-core-ui/src/components/layout/FrameDivider/FrameDivider.module.scss

      
      
      
      
      
      
      
      
      

var FrameDivider_module_options = {};

FrameDivider_module_options.styleTagTransform = (styleTagTransform_default());
FrameDivider_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      FrameDivider_module_options.insert = insertBySelector_default().bind(null, "head");
    
FrameDivider_module_options.domAPI = (styleDomAPI_default());
FrameDivider_module_options.insertStyleElement = (insertStyleElement_default());

var FrameDivider_module_update = injectStylesIntoStyleTag_default()(FrameDivider_module/* default */.A, FrameDivider_module_options);




       /* harmony default export */ const FrameDivider_FrameDivider_module = (FrameDivider_module/* default */.A && FrameDivider_module/* default */.A.locals ? FrameDivider_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/FrameDivider/FrameDivider.tsx



var FrameDividerOwner;
(function (FrameDividerOwner) {
    FrameDividerOwner[FrameDividerOwner["First"] = 0] = "First";
    FrameDividerOwner[FrameDividerOwner["Second"] = 1] = "Second";
})(FrameDividerOwner || (FrameDividerOwner = {}));
function setCssVariables(hash, owner, element, value, horizontal, width, height) {
    const halfDividerSize = 3;
    if (horizontal) {
        if (owner === FrameDividerOwner.First) {
            // Divider
            element.style.setProperty(`--frame-divider-${hash}-divider-top`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-divider-left`, Math.max(Math.min(value, width), 0) - halfDividerSize + 'px');
            // Container 1
            element.style.setProperty(`--frame-divider-${hash}-container-1-top`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-left`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-width`, Math.max(Math.min(value, width), 0) + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-height`, height + 'px');
            // Container 2
            element.style.setProperty(`--frame-divider-${hash}-container-2-top`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-left`, Math.max(value, 0) + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-width`, Math.min(Math.max(width - value, 0), width) + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-height`, height + 'px');
        }
        else {
            // Divider
            element.style.setProperty(`--frame-divider-${hash}-divider-top`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-divider-left`, Math.min(Math.max(width - value, 0), width) - halfDividerSize + 'px');
            // Container 1
            element.style.setProperty(`--frame-divider-${hash}-container-1-top`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-left`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-width`, Math.min(Math.max(width - value, 0), width) + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-height`, height + 'px');
            // Container 2
            element.style.setProperty(`--frame-divider-${hash}-container-2-top`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-left`, Math.max(width - value, 0) + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-width`, Math.max(Math.min(value, width), 0) + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-height`, height + 'px');
        }
    }
    else {
        if (owner === FrameDividerOwner.First) {
            // Divider
            element.style.setProperty(`--frame-divider-${hash}-divider-top`, Math.max(Math.min(value, height), 0) - 3 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-divider-left`, 0 + 'px');
            // Container 1
            element.style.setProperty(`--frame-divider-${hash}-container-1-top`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-left`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-width`, width + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-height`, Math.max(Math.min(value, height), 0) + 'px');
            // Container 2
            element.style.setProperty(`--frame-divider-${hash}-container-2-top`, Math.max(value, 0) + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-left`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-width`, width + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-height`, Math.min(Math.max(height - value, 0), height) + 'px');
        }
        else {
            // Divider
            element.style.setProperty(`--frame-divider-${hash}-divider-top`, Math.min(Math.max(height - value, 0), height) - 3 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-divider-left`, 0 + 'px');
            // Container 1
            element.style.setProperty(`--frame-divider-${hash}-container-1-top`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-left`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-width`, width + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-1-height`, Math.min(Math.max(height - value, 0), height) + 'px');
            // Container 2
            element.style.setProperty(`--frame-divider-${hash}-container-2-top`, Math.max(height - value, 0) + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-left`, 0 + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-width`, width + 'px');
            element.style.setProperty(`--frame-divider-${hash}-container-2-height`, Math.max(Math.min(value, height), 0) + 'px');
        }
    }
}
function setCssDragVariables(hash, element, start) {
    if (start) {
        element.style.setProperty(`--frame-divider-${hash}-pointer-events`, 'none');
    }
    else {
        element.style.setProperty(`--frame-divider-${hash}-pointer-events`, 'inherit');
    }
}
function FrameDivider({ horizontal = false, reverse = false, splitOwner = FrameDividerOwner.First, size = 343, sizeMin = 0, sizeMax, first, second, onDrag, onDragStart, onDragEnd, onResize, onSizeChanged, onBoundsChanged }) {
    // TODO: Create a custom hook for this? (hash)
    const [hash] = (0,external_react_.useState)(() => Math.floor((1 + Math.random()) * 0x100000000)
        .toString(16)
        .substring(1));
    const rootRef = (0,external_react_.useRef)(null);
    const resizingSize = (0,external_react_.useRef)(null);
    const observerRef = (0,external_react_.useRef)(null);
    const [bounds, setBounds] = (0,external_react_.useState)(undefined);
    const dividerStyle = {
        top: `var(--frame-divider-${hash}-divider-top)`,
        left: `var(--frame-divider-${hash}-divider-left)`
    };
    const container1Style = {
        top: `var(--frame-divider-${hash}-container-1-top)`,
        left: `var(--frame-divider-${hash}-container-1-left)`,
        width: `var(--frame-divider-${hash}-container-1-width)`,
        height: `var(--frame-divider-${hash}-container-1-height)`,
        // @ts-expect-error
        pointerEvents: `var(--frame-divider-${hash}-pointer-events, inherit)`
    };
    const container2Style = {
        top: `var(--frame-divider-${hash}-container-2-top)`,
        left: `var(--frame-divider-${hash}-container-2-left)`,
        width: `var(--frame-divider-${hash}-container-2-width)`,
        height: `var(--frame-divider-${hash}-container-2-height)`,
        // @ts-expect-error
        pointerEvents: `var(--frame-divider-${hash}-pointer-events, inherit)`
    };
    /** Returns the current frame bounds. */
    const getFrameDividerRects = (0,external_react_.useCallback)(() => {
        const actualSize = resizingSize.current || size;
        if (horizontal) {
            const cell1 = {
                x: bounds.x,
                y: bounds.y,
                width: actualSize,
                height: bounds.height
            };
            const cell2 = {
                x: bounds.x + actualSize,
                y: bounds.y,
                width: bounds.width - actualSize,
                height: bounds.height
            };
            return {
                first: splitOwner === FrameDividerOwner.First ? cell1 : cell2,
                second: splitOwner !== FrameDividerOwner.First ? cell1 : cell2
            };
        }
        else {
            const cell1 = {
                x: bounds.x,
                y: bounds.y,
                width: bounds.width,
                height: actualSize
            };
            const cell2 = {
                x: bounds.x,
                y: bounds.y + actualSize,
                width: bounds.width,
                height: bounds.height - actualSize
            };
            return {
                first: splitOwner === FrameDividerOwner.First ? cell1 : cell2,
                second: splitOwner !== FrameDividerOwner.First ? cell1 : cell2
            };
        }
    }, [bounds, horizontal, size, splitOwner]);
    const setBoundingClientRect = (0,external_react_.useCallback)(() => {
        if (rootRef.current) {
            const newBounds = rootRef.current.getBoundingClientRect();
            const hasChanged = (bounds === null || bounds === void 0 ? void 0 : bounds.x) !== newBounds.x ||
                (bounds === null || bounds === void 0 ? void 0 : bounds.y) !== newBounds.y ||
                (bounds === null || bounds === void 0 ? void 0 : bounds.width) !== newBounds.width ||
                (bounds === null || bounds === void 0 ? void 0 : bounds.height) !== newBounds.height;
            if (hasChanged && newBounds.width !== 0 && newBounds.height !== 0) {
                setBounds(newBounds);
                onBoundsChanged && onBoundsChanged(newBounds);
            }
        }
    }, [bounds, onBoundsChanged]);
    (0,external_react_.useLayoutEffect)(() => {
        if (rootRef.current) {
            if (observerRef.current) {
                observerRef.current.disconnect();
                observerRef.current = null;
            }
            const observer = new ResizeObserver(setBoundingClientRect);
            observer.observe(rootRef.current);
            observerRef.current = observer;
            setBoundingClientRect();
        }
    }, [getFrameDividerRects, onResize, rootRef, setBoundingClientRect]);
    (0,external_react_.useEffect)(() => {
        if (bounds) {
            onResize && onResize(getFrameDividerRects());
        }
    }, [bounds, getFrameDividerRects, onResize]);
    const onMouseMove = (0,external_react_.useCallback)(function (eventObject) {
        if (horizontal) {
            const x = splitOwner === FrameDividerOwner.First
                ? Math.max(Math.min(eventObject.pageX - bounds.x, bounds.width), 0)
                : Math.max(Math.min(bounds.x + bounds.width - eventObject.pageX, bounds.width), 0);
            if (sizeMax) {
                resizingSize.current = Math.min(Math.max(x, sizeMin), sizeMax);
            }
            else {
                resizingSize.current = Math.max(x, sizeMin);
            }
        }
        else {
            const y = splitOwner === FrameDividerOwner.First
                ? Math.max(Math.min(eventObject.pageY - bounds.y, bounds.height), 0)
                : Math.max(Math.min(bounds.y + bounds.height - eventObject.pageY, bounds.height), 0);
            if (sizeMax) {
                resizingSize.current = Math.min(Math.max(y, sizeMin), sizeMax);
            }
            else {
                resizingSize.current = Math.max(y, sizeMin);
            }
        }
        setCssVariables(hash, splitOwner, rootRef.current, resizingSize.current, horizontal, bounds.width, bounds.height);
        // TODO: throttle onDrag ?
        onDrag && onDrag(getFrameDividerRects());
    }, [horizontal, hash, splitOwner, bounds, onDrag, getFrameDividerRects, sizeMax, sizeMin]);
    const onMouseUp = (0,external_react_.useCallback)(function () {
        onSizeChanged(resizingSize.current);
        window.removeEventListener('mouseup', onMouseUp);
        window.removeEventListener('mousemove', onMouseMove);
        onDragEnd && onDragEnd(getFrameDividerRects());
        setCssDragVariables(hash, rootRef.current, false);
    }, [onMouseMove, onDragEnd, getFrameDividerRects, onSizeChanged, hash]);
    (0,external_react_.useEffect)(() => {
        if (bounds) {
            setCssVariables(hash, splitOwner, rootRef.current, size, horizontal, bounds.width, bounds.height);
        }
    }, [hash, bounds, horizontal, size, splitOwner, onDrag]);
    function startDragging(eventObject) {
        resizingSize.current = size;
        window.addEventListener('mouseup', onMouseUp);
        window.addEventListener('mousemove', onMouseMove);
        onDragStart && onDragStart(getFrameDividerRects());
        setCssDragVariables(hash, rootRef.current, true);
        eventObject.stopPropagation();
    }
    (0,external_react_.useEffect)(() => {
        // Check if the current size is already outside the bounds
        if (sizeMax) {
            onSizeChanged(Math.min(Math.max(size, sizeMin), sizeMax));
        }
        else {
            onSizeChanged(Math.max(size, sizeMin));
        }
    }, [size, sizeMax, sizeMin, onSizeChanged]);
    return (external_react_default().createElement("div", { ref: rootRef, className: external_classnames_default()([FrameDivider_FrameDivider_module['Root']]) },
        external_react_default().createElement("div", { style: container1Style, className: external_classnames_default()([
                FrameDivider_FrameDivider_module['Container1'],
                horizontal && FrameDivider_FrameDivider_module['is-horizontal'],
                !horizontal && FrameDivider_FrameDivider_module['is-vertical']
            ]) }, reverse ? second : first),
        external_react_default().createElement("div", { style: container2Style, className: external_classnames_default()([FrameDivider_FrameDivider_module['Container2']]) }, reverse ? first : second),
        external_react_default().createElement("div", { style: dividerStyle, className: external_classnames_default()([
                FrameDivider_FrameDivider_module['Divider'],
                horizontal && FrameDivider_FrameDivider_module['is-horizontal'],
                !horizontal && FrameDivider_FrameDivider_module['is-vertical']
            ]), onMouseDown: startDragging },
            external_react_default().createElement("div", { className: external_classnames_default()([FrameDivider_FrameDivider_module['DividerBorder']]) }),
            external_react_default().createElement("div", { className: external_classnames_default()([FrameDivider_FrameDivider_module['DividerHighlight']]) }))));
}

;// ../noodl-core-ui/src/components/layout/FrameDivider/index.ts


// EXTERNAL MODULE: ./src/editor/src/utils/keyboard/KeyCodeMapper.ts
var KeyCodeMapper = __webpack_require__(45977);
;// ./src/editor/src/utils/keyboard/KeyModMapper.ts


class KeyModStrMap {
    constructor() {
        this._keyModToStr = [];
        this._strToKeyMod = Object.create(null);
    }
    define(keyMod, str) {
        this._keyModToStr[keyMod] = str;
        this._strToKeyMod[str.toLowerCase()] = keyMod;
    }
    keyModToStr(keyMod) {
        return this._keyModToStr[keyMod];
    }
    strToKeyMod(str) {
        return this._strToKeyMod[str.toLowerCase()];
    }
}
const uiMap = new KeyModStrMap();
(function () {
    function define(keyMod, { windows, mac }) {
        switch (src.platform.os) {
            case src.PlatformOS.MacOS:
                uiMap.define(keyMod, mac);
                break;
            default:
            case src.PlatformOS.Windows:
                uiMap.define(keyMod, windows);
                break;
        }
    }
    define(KeyCode.KeyMod.Alt, { windows: 'Alt', mac: '⌥' });
    define(KeyCode.KeyMod.CtrlCmd, { windows: 'Ctrl', mac: '⌘' });
    define(KeyCode.KeyMod.Shift, { windows: 'Shift', mac: '⇧' });
    define(KeyCode.KeyMod.WinCtrl, { windows: 'Win', mac: '⌘' });
})();
var KeyModUtils;
(function (KeyModUtils) {
    function toString(keyMod) {
        return uiMap.keyModToStr(keyMod);
    }
    KeyModUtils.toString = toString;
    function fromString(key) {
        return uiMap.strToKeyMod(key);
    }
    KeyModUtils.fromString = fromString;
})(KeyModUtils || (KeyModUtils = {}));

;// ./src/editor/src/utils/keyboard/Keybinding.ts



const KeyMods = Object.keys(KeyCode.KeyMod);
class Keybinding {
    get hash() {
        return this._hash;
    }
    get label() {
        return this._label;
    }
    constructor(...keys) {
        this._hash = keys.reduce((r, c) => r | c, 0);
        this._label = keys
            .map((key) => {
            const modifier = KeyMods.find((mod) => key & mod);
            if (modifier)
                return KeyModUtils.toString(modifier);
            return KeyCodeMapper/* KeyCodeUtils */.Y.toString(key);
        })
            .join('+');
    }
}

// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/Icon/index.ts + 2 modules
var common_Icon = __webpack_require__(55655);
// EXTERNAL MODULE: ./src/shared/config/config.js
var config = __webpack_require__(35313);
var config_default = /*#__PURE__*/__webpack_require__.n(config);
// EXTERNAL MODULE: ../noodl-git/src/core/models/diff-data.ts
var diff_data = __webpack_require__(49264);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/Container/Container.module.scss
var Container_module = __webpack_require__(1197);
;// ../noodl-core-ui/src/components/layout/Container/Container.module.scss

      
      
      
      
      
      
      
      
      

var Container_module_options = {};

Container_module_options.styleTagTransform = (styleTagTransform_default());
Container_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      Container_module_options.insert = insertBySelector_default().bind(null, "head");
    
Container_module_options.domAPI = (styleDomAPI_default());
Container_module_options.insertStyleElement = (insertStyleElement_default());

var Container_module_update = injectStylesIntoStyleTag_default()(Container_module/* default */.A, Container_module_options);




       /* harmony default export */ const Container_Container_module = (Container_module/* default */.A && Container_module/* default */.A.locals ? Container_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/Container/Container.tsx



var ContainerDirection;
(function (ContainerDirection) {
    ContainerDirection["Horizontal"] = "horizontal";
    ContainerDirection["Vertical"] = "vertical";
})(ContainerDirection || (ContainerDirection = {}));
function Container({ direction = ContainerDirection.Horizontal, hasLeftSpacing, hasRightSpacing, hasTopSpacing, hasBottomSpacing, hasXSpacing, hasYSpacing, isFill, hasSpaceBetween, UNSAFE_style, UNSAFE_className, children }) {
    return (external_react_default().createElement("div", { className: external_classnames_default()([
            Container_Container_module['Root'],
            Container_Container_module[`is-direction-${direction}`],
            (hasXSpacing || hasLeftSpacing) && Container_Container_module['has-left-spacing'],
            (hasXSpacing || hasRightSpacing) && Container_Container_module['has-right-spacing'],
            (hasYSpacing || hasTopSpacing) && Container_Container_module['has-top-spacing'],
            (hasYSpacing || hasBottomSpacing) && Container_Container_module['has-bottom-spacing'],
            isFill && Container_Container_module['is-fill'],
            hasSpaceBetween && Container_Container_module['has-space-between'],
            UNSAFE_className
        ]), style: UNSAFE_style }, children));
}

;// ../noodl-core-ui/src/components/layout/Container/index.ts


;// ../noodl-core-ui/src/hooks/useTrackBounds.ts

/**
 * Track the Bounding Client Rect on a HTMLElement.
 *
 * @param ref The HTML Element we are tracking.
 * @returns ref.current.getBoundingClientRect() result.
 */
function useTrackBounds(ref) {
    const [bounds, setBounds] = (0,external_react_.useState)(null);
    (0,external_react_.useLayoutEffect)(() => {
        var _a;
        const observer = new ResizeObserver(() => {
            var _a;
            const newBounds = (_a = ref.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
            setBounds(newBounds);
        });
        observer.observe(ref.current);
        setBounds((_a = ref.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect());
        return function () {
            observer.disconnect();
        };
    }, [ref]);
    return bounds;
}

;// ./src/editor/src/views/common/Frame/Frame.tsx


function Frame({ instance, refresh, isAbsolute, isFitWidth, isContentSize, onResize, onRefChange, UNSAFE_className, UNSAFE_style }) {
    const rootRef = (0,external_react_.useRef)(null);
    const bounds = useTrackBounds(rootRef);
    (0,external_react_.useEffect)(() => {
        onRefChange && onRefChange(rootRef);
    }, [rootRef, onRefChange]);
    (0,external_react_.useEffect)(() => {
        bounds && onResize && onResize(bounds);
    }, [bounds]);
    (0,external_react_.useEffect)(() => {
        if (!rootRef.current) {
            return;
        }
        while (rootRef.current.firstChild) {
            rootRef.current.removeChild(rootRef.current.firstChild);
        }
        if (instance && instance.el && instance.el[0]) {
            rootRef.current.appendChild(instance.el[0]);
            bounds && onResize && onResize(bounds);
        }
    }, [rootRef, instance, refresh]);
    const style = {
        position: 'relative'
    };
    if (isAbsolute) {
        style.position = 'absolute';
    }
    if (!isContentSize) {
        style.width = '100%';
        style.height = '100%';
    }
    if (isFitWidth) {
        style.width = '100%';
    }
    return external_react_default().createElement("div", { className: UNSAFE_className, style: { ...style, ...UNSAFE_style }, ref: rootRef });
}

;// ./src/editor/src/views/common/Frame/index.ts


// EXTERNAL MODULE: ./src/editor/src/views/nodegrapheditor.ts + 48 modules
var nodegrapheditor = __webpack_require__(98278);
// EXTERNAL MODULE: include-loader!../../node_modules/monaco-editor/esm/vs/editor/editor.api.js + 669 modules
var editor_api = __webpack_require__(15618);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/inputs/IconButton/index.ts + 2 modules
var inputs_IconButton = __webpack_require__(28208);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/BaseDialog/index.ts + 3 modules
var BaseDialog = __webpack_require__(65762);
// EXTERNAL MODULE: ./src/editor/src/views/panels/propertyeditor/CodeEditor/actions/index.ts + 2 modules
var actions = __webpack_require__(53823);
;// ./src/editor/src/views/documents/ComponentDiffDocument/CodeDiffDialog.tsx







function anyToString(value) {
    if (value && typeof value === 'object') {
        return JSON.stringify(value, null, 2);
    }
    return String(value);
}
function CodeDiffDialog({ diff, onClose }) {
    const codeEditorRef = (0,external_react_.useRef)(null);
    (0,external_react_.useEffect)(() => {
        if (!codeEditorRef.current) {
            return;
        }
        const originalModel = editor_api.editor.createModel(anyToString(diff.original), 'text/plain');
        const modifiedModel = editor_api.editor.createModel(anyToString(diff.modified), 'text/plain');
        let editor;
        if (diff.original && !diff.modified) {
            editor = editor_api.editor.create(codeEditorRef.current, {
                model: originalModel,
                theme: (0,actions/* getTheme */.O)(),
                readOnly: true
            });
        }
        else if (!diff.original && diff.modified) {
            editor = editor_api.editor.create(codeEditorRef.current, {
                model: modifiedModel,
                theme: (0,actions/* getTheme */.O)(),
                readOnly: true
            });
        }
        else {
            editor = editor_api.editor.createDiffEditor(codeEditorRef.current, {
                theme: (0,actions/* getTheme */.O)()
            });
            editor.setModel({
                original: originalModel,
                modified: modifiedModel
            });
        }
        const onResize = () => editor.layout();
        window.addEventListener('resize', onResize);
        return () => {
            window.removeEventListener('resize', onResize);
            editor.dispose();
            originalModel.dispose();
            modifiedModel.dispose();
        };
    }, [codeEditorRef, diff]);
    return (external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { background: BaseDialog/* DialogBackground */.$j.Secondary, isVisible: diff !== null, hasBackdrop: true, onClose: onClose, UNSAFE_style: { width: '80vw' } },
        external_react_default().createElement(Container, { isFill: true, direction: ContainerDirection.Vertical },
            external_react_default().createElement("div", { style: { display: 'flex', justifyContent: 'flex-end', zIndex: 100 } },
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Close, onClick: onClose })),
            external_react_default().createElement("div", { ref: codeEditorRef, style: { height: '80vh' } }))));
}

// EXTERNAL MODULE: ./src/editor/src/hooks/usePrevious.ts
var usePrevious = __webpack_require__(45217);
// EXTERNAL MODULE: ./src/editor/src/store/AiAssistantStore.ts
var AiAssistantStore = __webpack_require__(61231);
// EXTERNAL MODULE: ./src/editor/src/utils/editorsettings.ts
var editorsettings = __webpack_require__(39804);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/popups/MenuDialog/index.ts + 2 modules
var MenuDialog = __webpack_require__(23442);
// EXTERNAL MODULE: ./src/editor/src/constants/FeedbackType.ts
var FeedbackType = __webpack_require__(30187);
// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/api.ts
var api = __webpack_require__(35266);
// EXTERNAL MODULE: ./src/editor/src/utils/getDocsEndpoint.ts
var editor_getDocsEndpoint = __webpack_require__(41160);
;// ./src/editor/src/utils/LocalUserIdentity.ts
class LocalUserIdentity {
    static getUserInfo() {
        //TODO: take from git?
        return {
            name: 'Local',
            id: 'local',
            email: ''
        };
    }
}

// EXTERNAL MODULE: ./src/editor/src/hooks/useCallAfterNextRender.ts
var useCallAfterNextRender = __webpack_require__(61113);
;// ./src/editor/src/types/globalInputTypes.ts
var InputNotificationDisplayMode;
(function (InputNotificationDisplayMode) {
    InputNotificationDisplayMode["Stay"] = "stay";
    InputNotificationDisplayMode["FadeQuick"] = "fade-quick";
    InputNotificationDisplayMode["FadeSlow"] = "fade-slow";
})(InputNotificationDisplayMode || (InputNotificationDisplayMode = {}));

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/InputLabelSection/InputLabelSection.module.scss
var InputLabelSection_module = __webpack_require__(16580);
;// ../noodl-core-ui/src/components/inputs/InputLabelSection/InputLabelSection.module.scss

      
      
      
      
      
      
      
      
      

var InputLabelSection_module_options = {};

InputLabelSection_module_options.styleTagTransform = (styleTagTransform_default());
InputLabelSection_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      InputLabelSection_module_options.insert = insertBySelector_default().bind(null, "head");
    
InputLabelSection_module_options.domAPI = (styleDomAPI_default());
InputLabelSection_module_options.insertStyleElement = (insertStyleElement_default());

var InputLabelSection_module_update = injectStylesIntoStyleTag_default()(InputLabelSection_module/* default */.A, InputLabelSection_module_options);




       /* harmony default export */ const InputLabelSection_InputLabelSection_module = (InputLabelSection_module/* default */.A && InputLabelSection_module/* default */.A.locals ? InputLabelSection_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/InputLabelSection/InputLabelSection.tsx


function InputLabelSection({ label }) {
    return external_react_default().createElement("div", { className: InputLabelSection_InputLabelSection_module['Root'] }, label);
}

;// ../noodl-core-ui/src/components/inputs/InputLabelSection/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/NotificationFeedbackDisplay/NotificationFeedbackDisplay.module.scss
var NotificationFeedbackDisplay_module = __webpack_require__(3348);
;// ../noodl-core-ui/src/components/inputs/NotificationFeedbackDisplay/NotificationFeedbackDisplay.module.scss

      
      
      
      
      
      
      
      
      

var NotificationFeedbackDisplay_module_options = {};

NotificationFeedbackDisplay_module_options.styleTagTransform = (styleTagTransform_default());
NotificationFeedbackDisplay_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      NotificationFeedbackDisplay_module_options.insert = insertBySelector_default().bind(null, "head");
    
NotificationFeedbackDisplay_module_options.domAPI = (styleDomAPI_default());
NotificationFeedbackDisplay_module_options.insertStyleElement = (insertStyleElement_default());

var NotificationFeedbackDisplay_module_update = injectStylesIntoStyleTag_default()(NotificationFeedbackDisplay_module/* default */.A, NotificationFeedbackDisplay_module_options);




       /* harmony default export */ const NotificationFeedbackDisplay_NotificationFeedbackDisplay_module = (NotificationFeedbackDisplay_module/* default */.A && NotificationFeedbackDisplay_module/* default */.A.locals ? NotificationFeedbackDisplay_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/NotificationFeedbackDisplay/NotificationFeedbackDisplay.tsx




function NotificationFeedbackDisplay({ notification }) {
    if (!notification)
        return null;
    return (external_react_default().createElement("div", { className: external_classnames_default()([
            NotificationFeedbackDisplay_NotificationFeedbackDisplay_module['Root'],
            NotificationFeedbackDisplay_NotificationFeedbackDisplay_module[`is-type-${notification === null || notification === void 0 ? void 0 : notification.type}`],
            NotificationFeedbackDisplay_NotificationFeedbackDisplay_module[`is-display-mode-${(notification === null || notification === void 0 ? void 0 : notification.displayMode) || InputNotificationDisplayMode.Stay}`]
        ]) }));
}

;// ../noodl-core-ui/src/components/inputs/NotificationFeedbackDisplay/index.ts


;// ../noodl-core-ui/src/components/inputs/NotificationFeedbackDisplay/NotificationFeedbackDisplay.hooks.ts

function useNotificationFeedbackDisplay(initialNotification) {
    const [newNotification, setNewNotification] = (0,external_react_.useState)(null);
    function updateNotification(notificationObject) {
        setNewNotification(null);
        if (notificationObject) {
            requestAnimationFrame(() => {
                setNewNotification(notificationObject);
            });
        }
    }
    (0,external_react_.useEffect)(() => {
        updateNotification(initialNotification);
    }, [initialNotification]);
    return [newNotification, updateNotification];
}

;// ../noodl-core-ui/src/components/inputs/TextInput/TextInput.hooks.ts

function useResizableInput({ value, placeholder, sizerRef }) {
    const [sizerContent, setSizerContent] = (0,external_react_.useState)(null);
    const [valueWidth, setValueWidth] = (0,external_react_.useState)(null);
    (0,external_react_.useEffect)(() => {
        if (!sizerRef.current)
            return;
        const observer = new ResizeObserver(() => {
            if (!sizerRef.current)
                return;
            // https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth
            // If you need a fractional value, use element.getBoundingClientRect().
            const rect = sizerRef.current.getBoundingClientRect();
            setValueWidth(`calc(${rect.width}px)`);
        });
        observer.observe(sizerRef.current);
        return function () {
            observer.disconnect();
        };
    }, [sizerRef]);
    (0,external_react_.useEffect)(() => {
        if (Boolean(value)) {
            setSizerContent(value);
        }
        else {
            setSizerContent(placeholder);
        }
    }, [value, placeholder]);
    return { sizerContent, valueWidth };
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/TextInput/TextInput.module.scss
var TextInput_module = __webpack_require__(49408);
;// ../noodl-core-ui/src/components/inputs/TextInput/TextInput.module.scss

      
      
      
      
      
      
      
      
      

var TextInput_module_options = {};

TextInput_module_options.styleTagTransform = (styleTagTransform_default());
TextInput_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      TextInput_module_options.insert = insertBySelector_default().bind(null, "head");
    
TextInput_module_options.domAPI = (styleDomAPI_default());
TextInput_module_options.insertStyleElement = (insertStyleElement_default());

var TextInput_module_update = injectStylesIntoStyleTag_default()(TextInput_module/* default */.A, TextInput_module_options);




       /* harmony default export */ const TextInput_TextInput_module = (TextInput_module/* default */.A && TextInput_module/* default */.A.locals ? TextInput_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/TextInput/TextInput.tsx














var TextInputVariant;
(function (TextInputVariant) {
    TextInputVariant["Default"] = "is-variant-default";
    TextInputVariant["InModal"] = "is-variant-in-modal";
    TextInputVariant["OpaqueOnHover"] = "is-variant-opaque-on-hover";
    TextInputVariant["Transparent"] = "is-variant-transparent";
})(TextInputVariant || (TextInputVariant = {}));
function TextInput({ value, placeholder, prefix, suffix, type, notification, label, variant = TextInputVariant.Default, hasBottomSpacing, isReadonly, isCopyable, isDisabled, isAutoFocus, slotBeforeInput, slotAfterInput, forwardedInputRef, onChange, onMouseEnter, onMouseLeave, onFocus, onBlur, onEnter, onKeyDown, onScrollbarCreated, onScrollbarRemoved, onRefChange, testId, UNSAFE_textClassName, UNSAFE_textStyle, UNSAFE_className, UNSAFE_style }) {
    const inputRef = (0,external_react_.useRef)(null);
    const sizerRef = (0,external_react_.useRef)(null);
    const inputWrapperRef = (0,external_react_.useRef)(null);
    const { sizerContent, valueWidth } = useResizableInput({ value, placeholder, sizerRef });
    const [isFocused, setIsFocused] = (0,external_react_.useState)(false);
    const [hasScrollbar, setHasScrollbar] = (0,external_react_.useState)(false);
    const [newNotification, updateNotification] = useNotificationFeedbackDisplay(notification);
    (0,external_react_.useEffect)(() => {
        onRefChange && onRefChange(inputRef);
    }, [inputRef.current, onRefChange]);
    (0,external_react_.useEffect)(() => {
        if (!inputRef.current || !forwardedInputRef)
            return;
        forwardedInputRef.current = inputRef.current;
    }, [forwardedInputRef, inputRef]);
    const doAfterNextRender = (0,useCallAfterNextRender/* default */.A)();
    (0,external_react_.useEffect)(() => {
        doAfterNextRender(() => {
            if (!inputWrapperRef.current)
                return;
            if (inputWrapperRef.current.scrollWidth > inputWrapperRef.current.clientWidth) {
                setHasScrollbar(true);
            }
            else {
                setHasScrollbar(false);
            }
        });
    }, [value]);
    (0,external_react_.useEffect)(() => {
        if (hasScrollbar) {
            onScrollbarCreated && onScrollbarCreated();
        }
        else {
            onScrollbarRemoved && onScrollbarRemoved();
        }
    }, [hasScrollbar]);
    function notifyReadOnlyField() {
        updateNotification({
            type: FeedbackType/* FeedbackType */.M.Danger,
            displayMode: InputNotificationDisplayMode.FadeQuick,
            message: 'Read only value'
        });
    }
    function notifyOnCopySuccess() {
        updateNotification({
            type: FeedbackType/* FeedbackType */.M.Success,
            displayMode: InputNotificationDisplayMode.FadeSlow,
            message: 'Copied!'
        });
    }
    function notifyOnCopyError() {
        updateNotification({
            type: FeedbackType/* FeedbackType */.M.Danger,
            displayMode: InputNotificationDisplayMode.FadeSlow,
            message: 'Failed copying. Try doing it manually.'
        });
    }
    function handleChange(event) {
        if (isReadonly) {
            notifyReadOnlyField();
        }
        else {
            if (onChange)
                onChange(event);
            updateNotification(null);
        }
    }
    function focusInput() {
        if (!inputRef.current)
            return;
        inputRef.current.focus();
    }
    // Change the scroll direction to horizontal.
    function onScroll(event) {
        if (inputWrapperRef.current) {
            inputWrapperRef.current.scrollLeft += event.deltaY + event.deltaX;
        }
    }
    return (external_react_default().createElement("div", { className: external_classnames_default()(TextInput_TextInput_module['Root'], hasBottomSpacing && TextInput_TextInput_module['has-bottom-spacing'], TextInput_TextInput_module[variant], suffix && TextInput_TextInput_module['has-suffix'], UNSAFE_className), onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, style: UNSAFE_style },
        label && external_react_default().createElement(InputLabelSection, { label: label }),
        external_react_default().createElement("div", { className: external_classnames_default()(TextInput_TextInput_module['InputArea'], isReadonly && TextInput_TextInput_module['is-readonly'], (newNotification === null || newNotification === void 0 ? void 0 : newNotification.message) && TextInput_TextInput_module['has-message'], isFocused && TextInput_TextInput_module['is-focused']), onClick: () => focusInput() },
            !isReadonly && (external_react_default().createElement("div", { className: external_classnames_default()([TextInput_TextInput_module['Sizer'], TextInput_TextInput_module['TextStyle']]), ref: sizerRef }, sizerContent)),
            slotBeforeInput && external_react_default().createElement("div", { className: TextInput_TextInput_module['BeforeContainer'] }, slotBeforeInput),
            external_react_default().createElement("div", { ref: inputWrapperRef, onWheel: onScroll, className: external_classnames_default()([
                    TextInput_TextInput_module['InputWrapper'],
                    sizerRef.current && TextInput_TextInput_module['is-scrollable'],
                    isCopyable && TextInput_TextInput_module['has-button-spacing']
                ]) },
                external_react_default().createElement("div", { className: TextInput_TextInput_module['InputWrapperInner'] },
                    prefix && external_react_default().createElement("span", { className: external_classnames_default()([TextInput_TextInput_module['Prefix'], TextInput_TextInput_module['TextStyle']]) }, prefix),
                    !isReadonly && (external_react_default().createElement("input", { className: external_classnames_default()([
                            TextInput_TextInput_module['Input'],
                            TextInput_TextInput_module['TextStyle'],
                            isReadonly && TextInput_TextInput_module['is-readonly'],
                            Boolean(suffix) && TextInput_TextInput_module['has-suffix'],
                            UNSAFE_textClassName
                        ]), value: value, placeholder: placeholder, onChange: handleChange, onKeyDown: (e) => {
                            onKeyDown && onKeyDown(e);
                            if (e.key === 'Enter') {
                                onEnter && onEnter();
                                e.stopPropagation();
                            }
                        }, onFocus: (e) => {
                            setIsFocused(true);
                            if (onFocus)
                                onFocus(e);
                        }, onBlur: (e) => {
                            setIsFocused(false);
                            if (onBlur)
                                onBlur(e);
                        }, disabled: isDisabled, type: type, style: sizerRef.current
                            ? {
                                maxWidth: valueWidth,
                                flexBasis: valueWidth,
                                ...UNSAFE_textStyle
                            }
                            : UNSAFE_textStyle, ref: inputRef, "data-test": testId, autoFocus: isAutoFocus })),
                    isReadonly && (external_react_default().createElement("div", { className: external_classnames_default()([
                            TextInput_TextInput_module['Input'],
                            TextInput_TextInput_module['TextStyle'],
                            isReadonly && TextInput_TextInput_module['is-readonly'],
                            TextInput_TextInput_module['is-div']
                        ]), style: sizerRef.current
                            ? {
                                minWidth: valueWidth,
                                flexBasis: valueWidth
                            }
                            : null, "data-test": testId }, value)),
                    suffix && external_react_default().createElement("span", { className: external_classnames_default()([TextInput_TextInput_module['Suffix'], TextInput_TextInput_module['TextStyle']]) }, suffix))),
            slotAfterInput && external_react_default().createElement("div", { className: TextInput_TextInput_module['AfterContainer'] }, slotAfterInput),
            isCopyable && (external_react_default().createElement("div", { className: TextInput_TextInput_module['ButtonContainer'] },
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Copy, size: common_Icon/* IconSize */.lK.Small, variant: inputs_IconButton/* IconButtonVariant */.nl.SemiTransparent, onClick: () => {
                        src.platform.copyToClipboard(value.toString()).then(notifyOnCopySuccess).catch(notifyOnCopyError);
                    } }))),
            (newNotification === null || newNotification === void 0 ? void 0 : newNotification.message) && (external_react_default().createElement(typography_Text/* Text */.EY, { className: TextInput_TextInput_module['NotificationMessage'], textType: newNotification.type }, newNotification.message)),
            newNotification && external_react_default().createElement(NotificationFeedbackDisplay, { notification: newNotification }))));
}

;// ../noodl-core-ui/src/components/inputs/TextInput/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Portal/index.ts + 1 modules
var Portal = __webpack_require__(31302);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/popups/Tooltip/index.ts + 2 modules
var Tooltip = __webpack_require__(87073);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Title/index.ts
var Title = __webpack_require__(48237);
;// ../noodl-core-ui/src/styles/badges.ts
// Badge colors used for example in Avatar components
const badges_BADGE_COLORS = [
    '#EF5350',
    '#EC407A',
    '#A450B2',
    '#7E57C2',
    '#5C6BC0',
    '#009688',
    '#43A047',
    '#558B2F',
    '#91776D',
    '#F45827'
];

;// ../noodl-core-ui/src/utils/color.ts
function color_getColorFromMap(baseString, colorMap) {
    function hashCode(str) {
        var hash = 0, i, chr;
        if (!(str === null || str === void 0 ? void 0 : str.length))
            return hash;
        for (i = 0; i < str.length; i++) {
            chr = str.charCodeAt(i);
            hash = (hash << 5) - hash + chr;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
    }
    return colorMap[Math.abs(hashCode(baseString)) % colorMap.length];
}

;// ../noodl-core-ui/src/utils/collaborator.ts


function getBadgeAndNameForUser(user) {
    function hashCode(str) {
        var hash = 0, i, chr;
        if (!(str === null || str === void 0 ? void 0 : str.length))
            return hash;
        for (i = 0; i < str.length; i++) {
            chr = str.charCodeAt(i);
            hash = (hash << 5) - hash + chr;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
    }
    let badge = 'UK';
    function _makeBadge(first, second) {
        if (first === undefined)
            return 'UK';
        else if (second === undefined)
            return (first + first).toUpperCase();
        else
            return (first + second).toUpperCase();
    }
    let name = undefined;
    try {
        name = user.name;
        if (!name && user.email && user.email.length >= 2) {
            name = user.email.split('@')[0];
        }
        let p;
        if (user.name && user.name.length >= 2) {
            p = user.name.split(' ');
        }
        else if (user.email && user.email.length >= 2) {
            p = user.email.split('.');
        }
        if (p.length === 1) {
            badge = _makeBadge(p[0][0], p[0][1]);
        }
        else if (p.length >= 2) {
            badge = _makeBadge(p[0][0], p[1][0]);
        }
    }
    catch (e) { }
    const color = color_getColorFromMap(user.id, badges_BADGE_COLORS);
    return {
        badge: { label: badge, color: color },
        name
    };
}
function getBadgeForUser(c) {
    function hashCode(str) {
        var hash = 0, i, chr;
        if (!(str === null || str === void 0 ? void 0 : str.length))
            return hash;
        for (i = 0; i < str.length; i++) {
            chr = str.charCodeAt(i);
            hash = (hash << 5) - hash + chr;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
    }
    var badge = 'UK';
    function _makeBadge(first, second) {
        if (first === undefined)
            return 'UK';
        else if (second === undefined)
            return (first + first).toUpperCase();
        else
            return (first + second).toUpperCase();
    }
    try {
        var name = c.name;
        if (!name && c.email && c.email.length >= 2) {
            name = c.email.split('@')[0];
        }
        if (c.name && c.name.length >= 2) {
            var p = c.name.split(' ');
        }
        else if (c.email && c.email.length >= 2) {
            var p = c.email.split('.');
        }
        if (p.length === 1) {
            badge = _makeBadge(p[0][0], p[0][1]);
        }
        else if (p.length >= 2) {
            badge = _makeBadge(p[0][0], p[1][0]);
        }
    }
    catch (e) { }
    var color = getColorFromMap(c.id, BADGE_COLORS);
    return {
        label: badge,
        color: color
    };
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/user/UserBadge/UserBadge.module.scss
var UserBadge_module = __webpack_require__(59838);
;// ../noodl-core-ui/src/components/user/UserBadge/UserBadge.module.scss

      
      
      
      
      
      
      
      
      

var UserBadge_module_options = {};

UserBadge_module_options.styleTagTransform = (styleTagTransform_default());
UserBadge_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      UserBadge_module_options.insert = insertBySelector_default().bind(null, "head");
    
UserBadge_module_options.domAPI = (styleDomAPI_default());
UserBadge_module_options.insertStyleElement = (insertStyleElement_default());

var UserBadge_module_update = injectStylesIntoStyleTag_default()(UserBadge_module/* default */.A, UserBadge_module_options);




       /* harmony default export */ const UserBadge_UserBadge_module = (UserBadge_module/* default */.A && UserBadge_module/* default */.A.locals ? UserBadge_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/user/UserBadge/UserBadge.tsx




var UserBadgeSize;
(function (UserBadgeSize) {
    UserBadgeSize["Medium"] = "medium";
    UserBadgeSize["Small"] = "small";
    UserBadgeSize["Tiny"] = "tiny";
})(UserBadgeSize || (UserBadgeSize = {}));
function UserBadge({ size = UserBadgeSize.Medium, name, email, id, hasRightSpacing, UNSAFE_className, UNSAFE_style }) {
    const badgeData = getBadgeAndNameForUser({ name, email, id });
    return (external_react_default().createElement("div", { className: external_classnames_default()([
            UserBadge_UserBadge_module['Root'],
            UserBadge_UserBadge_module[`is-size-${size}`],
            hasRightSpacing && UserBadge_UserBadge_module['has-right-spacing'],
            UNSAFE_className
        ]), style: { backgroundColor: badgeData.badge.color, ...UNSAFE_style } },
        external_react_default().createElement("span", null, badgeData.badge.label)));
}

;// ../noodl-core-ui/src/components/user/UserBadge/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/Clippy/Clippy.module.scss
var Clippy_module = __webpack_require__(25155);
;// ./src/editor/src/views/Clippy/Clippy.module.scss

      
      
      
      
      
      
      
      
      

var Clippy_module_options = {};

Clippy_module_options.styleTagTransform = (styleTagTransform_default());
Clippy_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      Clippy_module_options.insert = insertBySelector_default().bind(null, "head");
    
Clippy_module_options.domAPI = (styleDomAPI_default());
Clippy_module_options.insertStyleElement = (insertStyleElement_default());

var Clippy_module_update = injectStylesIntoStyleTag_default()(Clippy_module/* default */.A, Clippy_module_options);




       /* harmony default export */ const Clippy_Clippy_module = (Clippy_module/* default */.A && Clippy_module/* default */.A.locals ? Clippy_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/Clippy/ClippyCommandsMetadata.ts

var PopupItemType;
(function (PopupItemType) {
    PopupItemType["Visual"] = "is-visual";
    PopupItemType["Data"] = "is-data";
    PopupItemType["Custom"] = "is-custom";
})(PopupItemType || (PopupItemType = {}));
const promptToNodeCommands = [
    {
        title: '/UI',
        tag: 'UI Prompt',
        description: 'Create UI elements from a text prompt',
        placeholder: 'What should it be?',
        type: PopupItemType.Visual,
        icon: common_Icon/* IconName */.$M.UI,
        availableOnFrontend: true,
        availableOnBackend: false,
        requireGPT4: true,
        examples: [
            'A login form',
            'A dropdown with values 1 to 10',
            'Landing page of a car rental company'
            // 'A vertical list with five popular car brands. Each list item should have the brand name, most popular vechicle name and type, and a button that says "view". The items should use a horizontal layout.',
            // 'Pokemon card creator form',
            // 'A group that contains two columns. First column has the text "Left column" and the other column the text "Right column". Left column is twice the size of the right one.'
        ]
    },
    {
        title: '/Image',
        tag: 'Image Prompt',
        description: 'Create an image with DALL·E 2',
        placeholder: 'How should it look?',
        type: PopupItemType.Visual,
        icon: common_Icon/* IconName */.$M.Image,
        availableOnFrontend: true,
        availableOnBackend: false,
        requireGPT4: true,
        examples: [
            'A big, steaming bowl of noodles',
            'Four kittens with cool sunshades',
            'The worlds fastest car on holiday'
        ]
    }
];
const copilotNodeInstaPromptable = ['/function', '/read from database', '/write to database'];
const copilotNodeCommands = [
    {
        requireGPT4: false,
        templateId: 'function',
        title: '/Function',
        tag: 'Function',
        description: 'Create custom JavaScript function from a text prompt',
        placeholder: 'What should it do?',
        type: PopupItemType.Custom,
        icon: common_Icon/* IconName */.$M.Code,
        availableOnFrontend: true,
        availableOnBackend: true,
        examples: [
            'Create inputs for Array1 and Array2 and output all items with the same ID',
            'Get a random number between the min and max inputs',
            'Get the current location of the device'
        ]
    },
    {
        requireGPT4: true,
        templateId: 'function-query-database',
        title: '/Read from database',
        tag: 'Read from database',
        description: 'This will create a node that queries the database and returns the results',
        placeholder: 'What data you want?',
        type: PopupItemType.Data,
        icon: common_Icon/* IconName */.$M.CloudDownload,
        availableOnFrontend: true,
        availableOnBackend: true,
        examples: [
            'Get all users that belong to the "Vendor" group',
            'Get all products, sort from lowest to highest price',
            'Get all unread messages for the currently logged in user'
        ]
    },
    // {
    //   templateId: 'rest',
    //   title: '/REST API',
    //   tag: 'REST',
    //   description: 'Connects to an external REST API via an HTTP from a text prompt',
    //   placeholder: 'Where and what do you want to get?',
    //   type: PopupItemType.Data,
    //   icon: IconName.RestApi,
    //   examples: [
    //     'Get the current weather at the inputs "Lat" and "Lon" from OpenWeather API',
    //     'POST Inputs.Message to the "/messages" endpoint of Inputs.APIBasePath'
    //   ]
    // },
    {
        requireGPT4: true,
        templateId: 'function-crud',
        title: '/Write to database',
        tag: 'Write to database',
        description: 'Create, read, update or delete records in the database',
        placeholder: 'What should be edited in the database?',
        type: PopupItemType.Data,
        icon: common_Icon/* IconName */.$M.CloudUpload,
        availableOnFrontend: true,
        availableOnBackend: true,
        examples: ['Get an array of numbers, calculate the average, and save that to the current users score attribute']
    }
];
const comingSoonCommands = [
    {
        requireGPT4: true,
        // templateId: 'chart',
        title: '/Chart',
        tag: 'Chart Prompt',
        description: 'Generate a chart that can display data',
        placeholder: '',
        type: PopupItemType.Visual,
        icon: common_Icon/* IconName */.$M.Question,
        availableOnFrontend: true,
        availableOnBackend: false,
        examples: []
    },
    {
        title: '/Suggest',
        requireGPT4: true,
        tag: 'Suggest Prompt',
        description: 'Get suggestions',
        placeholder: 'What to get suggestions for',
        type: PopupItemType.Visual,
        icon: common_Icon/* IconName */.$M.Question,
        availableOnFrontend: true,
        availableOnBackend: false,
        examples: ['What feature should I add next?', 'How can the form be improved?']
    }
];

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/Clippy/components/ClippyLogo/ClippyLogo.module.scss
var ClippyLogo_module = __webpack_require__(87162);
;// ./src/editor/src/views/Clippy/components/ClippyLogo/ClippyLogo.module.scss

      
      
      
      
      
      
      
      
      

var ClippyLogo_module_options = {};

ClippyLogo_module_options.styleTagTransform = (styleTagTransform_default());
ClippyLogo_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ClippyLogo_module_options.insert = insertBySelector_default().bind(null, "head");
    
ClippyLogo_module_options.domAPI = (styleDomAPI_default());
ClippyLogo_module_options.insertStyleElement = (insertStyleElement_default());

var ClippyLogo_module_update = injectStylesIntoStyleTag_default()(ClippyLogo_module/* default */.A, ClippyLogo_module_options);




       /* harmony default export */ const ClippyLogo_ClippyLogo_module = (ClippyLogo_module/* default */.A && ClippyLogo_module/* default */.A.locals ? ClippyLogo_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/Clippy/components/ClippyLogo/ClippyLogo.tsx



function ClippyLogo({ isListening, isDimmed, isThinking }) {
    return (external_react_default().createElement("div", { className: external_classnames_default()(ClippyLogo_ClippyLogo_module.Root, isListening && ClippyLogo_ClippyLogo_module.__isListening, isDimmed && ClippyLogo_ClippyLogo_module.__isDimmed, isThinking && ClippyLogo_ClippyLogo_module.__isThinking) },
        external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.HeroLogoWrapper },
            external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.HeroLogo },
                external_react_default().createElement("span", null, "Ai"),
                external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.LogoIdleCircleContainer },
                    external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.LogoIdleCircleInner },
                        external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.LogoIdleCircle }))),
                external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.LogoListeningCircleContainer },
                    external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.LogoListeningCircleInner },
                        external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.LogoListeningCircle }))),
                external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.LogoLoader },
                    external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.LogoLoaderInner },
                        external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.Circle1 },
                            external_react_default().createElement("span", { className: ClippyLogo_ClippyLogo_module.SpinningBalls })),
                        external_react_default().createElement("div", { className: ClippyLogo_ClippyLogo_module.Circle2 },
                            external_react_default().createElement("span", { className: ClippyLogo_ClippyLogo_module.SpinningBalls }))))))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/Clippy/components/GrowingTextArea/GrowingTextArea.module.scss
var GrowingTextArea_module = __webpack_require__(75252);
;// ./src/editor/src/views/Clippy/components/GrowingTextArea/GrowingTextArea.module.scss

      
      
      
      
      
      
      
      
      

var GrowingTextArea_module_options = {};

GrowingTextArea_module_options.styleTagTransform = (styleTagTransform_default());
GrowingTextArea_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      GrowingTextArea_module_options.insert = insertBySelector_default().bind(null, "head");
    
GrowingTextArea_module_options.domAPI = (styleDomAPI_default());
GrowingTextArea_module_options.insertStyleElement = (insertStyleElement_default());

var GrowingTextArea_module_update = injectStylesIntoStyleTag_default()(GrowingTextArea_module/* default */.A, GrowingTextArea_module_options);




       /* harmony default export */ const GrowingTextArea_GrowingTextArea_module = (GrowingTextArea_module/* default */.A && GrowingTextArea_module/* default */.A.locals ? GrowingTextArea_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/Clippy/components/GrowingTextArea/GrowingTextArea.tsx


function GrowingTextArea({ placeholder = '', value, forwardedTextAreaRef, isFocused, isAutoFocus, onChange, onFocus, onBlur, onEnter, onKeyDown }) {
    const textAreaRef = (0,external_react_.useRef)(null);
    (0,external_react_.useEffect)(() => {
        if (textAreaRef) {
            // reset to check scroll height
            textAreaRef.current.style.height = '0px';
            const scrollHeight = textAreaRef.current.scrollHeight;
            // set the height
            textAreaRef.current.style.height = scrollHeight + 'px';
        }
    }, [textAreaRef, value]);
    (0,external_react_.useEffect)(() => {
        if (!textAreaRef.current || !forwardedTextAreaRef)
            return;
        forwardedTextAreaRef.current = textAreaRef.current;
    }, [forwardedTextAreaRef, textAreaRef]);
    return (external_react_default().createElement("textarea", { className: GrowingTextArea_GrowingTextArea_module.Root, onChange: onChange, placeholder: placeholder, ref: textAreaRef, rows: 1, value: value, autoFocus: isAutoFocus, onFocus: (e) => {
            e.currentTarget.setSelectionRange(value.length, value.length);
            onFocus && onFocus(e);
        }, onKeyDown: (e) => {
            onKeyDown && onKeyDown(e);
            if (e.key === 'Enter') {
                onEnter && onEnter();
                e.stopPropagation();
            }
        }, onBlur: (e) => {
            onBlur && onBlur(e);
        } }));
}

// EXTERNAL MODULE: ./src/editor/src/models/nodegraphmodel/index.ts + 4 modules
var nodegraphmodel = __webpack_require__(87844);
// EXTERNAL MODULE: external "node:path"
var external_node_path_ = __webpack_require__(76760);
var external_node_path_default = /*#__PURE__*/__webpack_require__.n(external_node_path_);
;// ./src/editor/src/views/Clippy/Commands/utils.tsx





async function makeImageGenerationRequest(prompt) {
    const OPENAI_API_KEY = AiAssistantStore/* OpenAiStore */.q.getApiKey();
    const response = await fetch(`https://api.openai.com/v1/images/generations`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: 'Bearer ' + OPENAI_API_KEY
        },
        body: JSON.stringify({
            prompt,
            n: 1,
            size: '512x512',
            response_format: 'b64_json'
        })
    });
    const json = await response.json();
    if (json.error) {
        console.error(json.error);
        throw new Error(json.error);
    }
    const b64_json = json.data[0].b64_json;
    return { data: Buffer.from(b64_json, 'base64'), type: 'png' };
}
async function saveImageDataToDisk(imageData) {
    const projectFolder = projectmodel.ProjectModel.instance._retainedProjectDirectory;
    if (!projectFolder)
        throw new Error('Project has no folder');
    const filename = `image-${(0,utils.guid)()}.${imageData.type}`;
    const folder = 'generated-images';
    const relativeFilePath = external_node_path_default().join(folder, filename);
    const absolutePath = external_node_path_default().join(projectFolder, relativeFilePath);
    await src.filesystem.makeDirectory(external_node_path_default().join(projectFolder, folder));
    await src.filesystem.writeFile(absolutePath, imageData.data);
    return relativeFilePath;
}
async function makeChatRequest(model, messages) {
    const OPENAI_API_KEY = AiAssistantStore/* OpenAiStore */.q.getApiKey();
    const response = await fetch(`https://api.openai.com/v1/chat/completions`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: 'Bearer ' + OPENAI_API_KEY
        },
        body: JSON.stringify({
            model,
            messages,
            temperature: 0.5,
            max_tokens: 2048
        })
    });
    const json = await response.json();
    if (json.error) {
        console.error(json.error);
        return null;
    }
    else {
        const promptTokenCost = model === 'gpt-4o-mini' ? 0.03 : 0.002;
        const completionTokenCost = model === 'gpt-4o-mini' ? 0.06 : 0.002;
        let cost = (json.usage.completion_tokens * completionTokenCost) / 1000 + (json.usage.prompt_tokens * promptTokenCost) / 1000;
        cost = Math.round(cost * 10000) / 10000; //round to 4 decimals
        console.log('prompt cost', `$${cost}`);
        return {
            content: json.choices[0].message.content,
            usage: json.usage
        };
    }
}

;// ./src/editor/src/views/Clippy/Commands/ImageCommand.tsx




async function handleImageCommand(prompt, statusCallback) {
    var _a;
    statusCallback('Generating image...');
    const imageData = await makeImageGenerationRequest(prompt);
    const imageUrl = await saveImageDataToDisk(imageData);
    const selectedNodes = NodeGraphContext.NodeGraphContextTmp.nodeGraph.getSelectedNodes();
    const nodeModel = (_a = selectedNodes[0]) === null || _a === void 0 ? void 0 : _a.model;
    //if the selected node has a "src" input, set that input directly...
    if (nodeModel && nodeModel.findPortWithName('src')) {
        nodeModel.setParameter('src', imageUrl);
    }
    else {
        // ...otherwise create a new node
        addNodeToGraph(nodegraphmodel/* NodeGraphNode */.dF.fromJSON({
            x: 0,
            y: 0,
            id: (0,utils.guid)(),
            type: 'Image',
            parameters: {
                src: imageUrl
            }
        }));
    }
}
function addNodeToGraph(node) {
    const nodeGraphModel = NodeGraphContext.NodeGraphContextTmp.nodeGraph.model;
    for (const root of nodeGraphModel.roots) {
        if (root.canAcceptChildren([node])) {
            root.addChild(node, { undo: true, label: 'create' });
        }
    }
    if (node.parent === undefined) {
        // Couldn't find compatiable root
        nodeGraphModel.addRoot(node, { undo: true, label: 'create' });
    }
}

;// ./src/editor/src/views/Clippy/Commands/SuggestCommand.tsx


async function handleSuggestionCommand(prompt, statusCallback) {
    statusCallback('Generating suggestions...');
    const nodeGraphModel = NodeGraphContext.NodeGraphContextTmp.nodeGraph.model;
    const json = nodeGraphModel.toJSON().roots;
    const group = json.find((x) => x.type === 'Group' || x.type === 'Page');
    if (!group) {
        return;
    }
    function cleanNodes(node) {
        let children;
        if (node.children) {
            children = [];
            for (const c of node.children) {
                children.push(cleanNodes(c));
            }
        }
        return {
            type: getType(node.type),
            children: children,
            parameters: node.parameters
        };
    }
    const cleanNode = cleanNodes(group);
    const p = `
  Suggest ${prompt}
  
  UI:
  ${JSON.stringify(cleanNode, null, 2)}
  `;
    const messages = [
        { role: 'system', content: suggestPrimer },
        { role: 'user', content: p }
    ];
    const response = await makeChatRequest('gpt-4o-mini', messages);
    console.log(response);
    return JSON.parse(response.content);
}
const nameMap = {
    columns: 'net.noodl.visual.columns',
    button: 'net.noodl.controls.button',
    group: 'Group',
    text: 'Text',
    input: 'net.noodl.controls.textinput',
    img: 'Image',
    dropdown: 'net.noodl.controls.options',
    checkbox: 'net.noodl.controls.checkbox'
};
function getType(type) {
    for (const key in nameMap) {
        if (nameMap[key] === type) {
            return key;
        }
    }
    return type;
}
const suggestPrimer = `
You are a suggestion bot that recommends commands for improving a page in an application.

The pages is described with JSON.

The answer can include the following commands:

Name: Image
Description: generate a single image
Prompt: a prompt for the openai image generation API

Name: UI
Description: add user interface elements like buttons, inputs, groups
Prompt: a short description of an UI

Name: Function:
Description: a javascript function
Prompt: a prompt for GTP that generates a javascript function

Name: Suggestion
Description: Suggest commands from the list above
Prompt: a command and its prompt

Each command takes a prompt for an AI to use.

Only answer with the following JSON format:
[
{
name: 'command name',
description: 'short description why this command is suggested',
prompt: 'a prompt for the command'
]
`;

// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/AiCopilotContext.ts
var AiCopilotContext = __webpack_require__(69401);
;// ./src/editor/src/views/Clippy/Commands/UICommand.tsx








async function handleUICommand(prompt, statusCallback, options) {
    var _a, _b, _c;
    const selectedNodes = NodeGraphContext.NodeGraphContextTmp.nodeGraph.getSelectedNodes();
    let parentModel = (_a = selectedNodes[0]) === null || _a === void 0 ? void 0 : _a.model;
    const nodeGraphModel = options.nodeGraphModel || NodeGraphContext.NodeGraphContextTmp.nodeGraph.model;
    // HACK: To support custom node graph model
    if (options.nodeGraphModel) {
        parentModel = null;
    }
    if (!parentModel || !((_b = parentModel.type.allowChildrenWithCategory) === null || _b === void 0 ? void 0 : _b.includes('Visual'))) {
        //find a root that can add the nodes as children
        parentModel = nodeGraphModel.roots.find((root) => { var _a; return (_a = root.type.allowChildrenWithCategory) === null || _a === void 0 ? void 0 : _a.includes('Visual'); });
    }
    const components = projectmodel.ProjectModel.instance.components.filter((c) => c.graph.commentsModel.getComments().some((c) => c.text.toLowerCase().startsWith('ai:')));
    const comments = projectmodel.ProjectModel.instance.components.flatMap((c) => c.graph.commentsModel.getComments());
    const uiPrimer = (_c = comments.find((c) => c.text.toLowerCase().startsWith('ai ui primer:'))) === null || _c === void 0 ? void 0 : _c.text;
    const userComponents = components.map((c) => {
        var _a;
        const comment = c.graph.commentsModel.getComments().find((c) => c.text.toLowerCase().startsWith('ai:'));
        const description = comment.text.substring(3).trim();
        return {
            name: c.localName.toLowerCase().replaceAll(' ', '-'),
            fullName: c.fullName,
            description,
            canHaveChildren: (_a = c.allowChildrenWithCategory) === null || _a === void 0 ? void 0 : _a.includes('Visual')
        };
    });
    statusCallback('Generating nodes');
    const messages = [
        { role: 'system', content: generatePrimer({ ...options, userComponents, uiPrimer }) },
        { role: 'user', content: prompt }
    ];
    const ctx = new AiCopilotContext/* AiCopilotContext */.q(null, null, null);
    const undoGroup = new undo_queue_model/* UndoActionGroup */.C({ label: 'AI: Generate nodes' });
    const callbacks = {
        onTagOpen(tagName, attributes) {
            const json = {
                type: attributes.componentName ? transformComponentName(attributes.componentName) : transformName(tagName),
                parameters: {},
                children: [],
                x: 0,
                y: 0,
                id: (0,utils.guid)()
            };
            const type = nodelibrary/* NodeLibrary */.m.instance.getNodeTypeWithName(json.type);
            const allPortNames = new Set(type.ports.map((p) => p.name));
            const portMap = new Map();
            for (const portName of allPortNames.values()) {
                portMap.set(portName.replaceAll(' ', '').toLowerCase(), portName);
            }
            for (const attr of Object.keys(attributes)) {
                if (attr === 'nodeLabel') {
                    json.label = attributes[attr];
                }
                if (attr === 'variant') {
                    json.variant = attributes[attr];
                }
                else {
                    let portName = attr;
                    // ports can have spaces, but xml attributes can't
                    // so if the attribute doesn't match a port, try again but without spaces
                    if (!allPortNames.has(portName)) {
                        const n = portName.replaceAll(' ', '').toLowerCase();
                        if (portMap.has(n)) {
                            portName = portMap.get(n);
                        }
                    }
                    json.parameters[portName] = getAttributeValue(portName, attributes[attr]);
                }
            }
            setDefaultValues(json);
            const node = nodegraphmodel/* NodeGraphNode */.dF.fromJSON(json);
            if (parentModel) {
                parentModel.addChild(node, { undo: undoGroup, disableSelect: true });
            }
            else {
                nodeGraphModel.addRoot(node, { undo: undoGroup, disableSelect: true });
            }
            parentModel = node;
            if (node.findPortWithName('src')) {
                if (attributes.prompt) {
                    makeImageGenerationRequest(attributes.prompt)
                        .then((imageData) => saveImageDataToDisk(imageData))
                        .then((url) => node.setParameter('src', url));
                }
                else {
                    const width = attributes.width || 100;
                    const height = attributes.height || 100;
                    const url = `https://via.placeholder.com/${width}x${height}`;
                    node.setParameter('src', url);
                }
            }
        },
        onTagEnd() {
            parentModel = parentModel.parent;
        }
    };
    await ctx.chatStreamXml({
        messages: messages,
        provider: {
            model: 'gpt-4o-mini',
            // The next context doesnt work with GPT-3.5
            temperature: 0.1
        },
        ...callbacks
    });
    undo_queue_model/* UndoQueue */.g.instance.push(undoGroup);
}
function generatePrimer(options) {
    const userComponentsPrimer = options.userComponents
        .map((c) => {
        return `
${c.name}
${c.description}
The attribute "componentName" must always be set to "${c.fullName}" 
xml: <${c.name} componentName="${c.fullName}" />
${c.canHaveChildren ? 'Can contain children' : 'This element must have no child elements'}
  `;
    })
        .join('\n');
    const primer = `
Format the response as xml using the following elements:

Group
An element that can contain multiple children.
xml: <group>[insert children]</group>
Attributes:
- flexDirection: "column"|"row". Default is column.
- backgroundColor: hex color|"transparent". Default is transparent.
- paddingTop: top padding. Default 0
- paddingBottom: bottom padding. Default 0
- paddingLeft: top padding. Default 0
- paddingRight: bottom padding. Default 0
- borderRadius: corner radius in pixels
Rules:
- Padding is one of the following: 0, 8, 16, 32
- A group with a background color has to have a padding of 16.

Columns
An element that contain groups, one per column.
xml: <columns>[insert children]</columns>
Attributes:
- layoutString: a string that has one value per column, separated by a space. The value is the relative size of the column. Default size is 1.

Text
xml: <text />
Children: not allowed
Attributes:
- text: the text content

Button
xml: <button />
Attributes
- label: the button label

Input
xml: <input />
Children: not allowed
Attributes:
- label: the inputs label
- type: the type of input
- placeholder: placeholder text when no option is selected

Checkbox
xml: <checkbox />
Children: not allowed
- label: the checkbox label
- checked: a boolean. Default is false.

Image
xml: <img />
Attributes:
- src: an url
- width: the width as a number in pixels or %
- height: the height as a number in pixels
- prompt: prompt for OpenAIs image generation describing the picture

Dropdown
xml: <dropdown />
Children: not allowed
Attributes:
- items: an array with options with the format: [{Label: "[label name]", Value: "[value]"}]
- label: the label
- placeholder: placeholder text when no option is selected

All elements above have the following attributes:
- marginTop: top margin. Default 0
- marginBottom: bottom margin. Default 0
- marginLeft: top margin. Default 0
- marginRight: bottom margin. Default 0
- position: "absolute" | "relative". Default is relative.
Rules:
- Margins can be one of the following: 0, 8, 16, 32

Prefer to use these elements:
{userComponentPrimers}

Add a "nodeLabel" attribute to every node with an explanation for why this node was created

Attributes with spaces should be formatted as camelCase, no spaces.

Response only contains XML with the elements listed above. Always start with a group.`;
    return (options.uiPrimer || primer).replace('{userComponentPrimers}', userComponentsPrimer);
}
function transformName(name) {
    const nameMap = {
        columns: 'net.noodl.visual.columns',
        button: 'net.noodl.controls.button',
        group: 'Group',
        text: 'Text',
        input: 'net.noodl.controls.textinput',
        img: 'Image',
        dropdown: 'net.noodl.controls.options',
        checkbox: 'net.noodl.controls.checkbox'
    };
    return nameMap[name] ? nameMap[name] : name;
}
function transformComponentName(name) {
    const component = projectmodel.ProjectModel.instance.components.find((c) => c.fullName.toLocaleLowerCase() === name.toLocaleLowerCase());
    return (component === null || component === void 0 ? void 0 : component.fullName) || name;
}
function getAttributeValue(name, value) {
    if ([
        'marginTop',
        'marginBottom',
        'marginLeft',
        'marginRight',
        'paddingTop',
        'paddingBottom',
        'paddingLeft',
        'paddingRight',
        'width',
        'height',
        'borderRadius'
    ].indexOf(name) !== -1) {
        if (value === 'auto') {
            return undefined;
        }
        if (value.endsWith('%')) {
            return { value: Number(value.substring(0, value.length - 1)), unit: '%' };
        }
        return { value: Number(value), unit: 'px' };
    }
    else if (name === 'src' && value === '') {
        return undefined;
    }
    return value;
}
function setDefaultValues(node) {
    if (node.type === 'Group') {
        node.parameters.sizeMode = 'contentHeight';
    }
    if (node.type === 'Group' && node.parameters.borderRadius) {
        node.parameters.clip = true;
    }
    if (node.type === 'Image') {
        if (node.parameters.height) {
            node.parameters.sizeMode = 'explicit';
        }
        else {
            node.parameters.sizeMode = 'contentHeight';
        }
        node.parameters.objectFit = 'cover';
    }
    if (node.type === 'net.noodl.controls.options' && node.parameters.label) {
        node.parameters.useLabel = true;
    }
}

;// ./src/editor/src/views/Clippy/HackyClippyBackend.tsx






async function handleCommand(command, prompt, options, statusCallback) {
    console.log(command, prompt);
    if (command === '/ui') {
        return await handleUICommand(prompt, statusCallback, {
            allowImageGeneration: true,
            allowImageNode: true
        });
    }
    if (copilotNodeInstaPromptable.includes(command)) {
        const item = copilotNodeCommands.find((x) => x.title.toLowerCase() === command);
        if (!item)
            throw new Error('Invalid command');
        const templateId = item.templateId;
        const panAndScale = options.nodeGraph.getPanAndScale();
        const x = Math.round(Math.random() * 100 + 50);
        const y = Math.round(Math.random() * 100 + 50);
        const scaledPos = {
            x: x / panAndScale.scale - panAndScale.x,
            y: y / panAndScale.scale - panAndScale.y
        };
        const context = await AiAssistant/* AiAssistantModel */.g.instance.createNode(templateId, null, scaledPos);
        context.chatHistory.add({
            content: prompt,
            metadata: {
                user: LocalUserIdentity.getUserInfo()
            }
        });
        statusCallback('Processing...');
        await AiAssistant/* AiAssistantModel */.g.instance.send(context);
        return;
    }
    if (command === '/image') {
        return await handleImageCommand(prompt, statusCallback);
    }
    else if (command === '/suggest') {
        return await handleSuggestionCommand(prompt, statusCallback);
    }
}

;// ./src/editor/src/views/Clippy/Clippy.tsx




























function Clippy() {
    const [firstInputValue, setFirstInputValue] = (0,external_react_.useState)('');
    const [secondInputValue, setSecondInputValue] = (0,external_react_.useState)('');
    const [isInputOpen, setIsInputOpen] = (0,external_react_.useState)(false);
    const [isInputFocused, setIsInputFocused] = (0,external_react_.useState)(false);
    const [selectedPromptTitle, setSelectedPromptTitle] = (0,external_react_.useState)(null);
    const [isAiThinking, setIsAiThinking] = (0,external_react_.useState)(false);
    const [aiThinkingStatus, setAIThinkingStatus] = (0,external_react_.useState)('');
    const [shouldFirstInputAutofocus, setShouldFirstInputAutofocus] = (0,external_react_.useState)(false);
    const [isTextareaInsteadOfInput, setIsTextareaInsteadOfInput] = (0,external_react_.useState)(false);
    const [commandResultItems, setCommandResultItems] = (0,external_react_.useState)(null); //commands might generate follow-up items
    const [hasGPT4, setHasGPT4] = (0,external_react_.useState)(false);
    const firstInputRef = (0,external_react_.useRef)(null);
    const secondInputRef = (0,external_react_.useRef)(null);
    const secondTextAreaRef = (0,external_react_.useRef)(null);
    const ref = (0,external_react_.useRef)(undefined);
    const [hasApiKey, setHasApiKey] = (0,external_react_.useState)(false);
    const aiAssistantModel = (0,useModel/* useModernModel */.e)(AiAssistant/* AiAssistantModel */.g.instance);
    const nodeGraphContext = (0,NodeGraphContext.useNodeGraphContext)();
    const version = AiAssistantStore/* OpenAiStore */.q.getVersion();
    const isFrontend = nodeGraphContext.active === 'frontend';
    const commandFilter = (x) => ((x.availableOnFrontend && isFrontend) || (x.availableOnBackend && !isFrontend)) &&
        (!x.requireGPT4 || (x.requireGPT4 && hasGPT4));
    const promptToNode = promptToNodeCommands.filter(commandFilter);
    const copilotNodes = copilotNodeCommands.filter(commandFilter);
    const comingSoonItems = comingSoonCommands.filter(commandFilter);
    const disabledDueToGpt3Items = promptToNodeCommands
        .concat(copilotNodeCommands)
        .concat(comingSoonCommands)
        .filter((x) => x.requireGPT4 && !hasGPT4);
    const ALL_OPTIONS = [...promptToNode, ...copilotNodes];
    const user = LocalUserIdentity.getUserInfo();
    (0,external_react_.useEffect)(() => {
        const version = AiAssistantStore/* OpenAiStore */.q.getVersion();
        if (version === 'enterprise') {
            setHasApiKey(true);
            setHasGPT4(AiAssistantStore/* OpenAiStore */.q.getModel() === 'gpt-4o-mini');
        }
        else if (version === 'full-beta') {
            setHasApiKey(AiAssistantStore/* OpenAiStore */.q.getIsAiApiKeyVerified());
        }
        else {
            setHasGPT4(false);
            setHasApiKey(false);
        }
    }, [isInputOpen]);
    (0,external_react_.useEffect)(() => {
        if (!hasApiKey)
            return;
        async function doIt() {
            const version = AiAssistantStore/* OpenAiStore */.q.getVersion();
            if (version === 'enterprise') {
                setHasGPT4(AiAssistantStore/* OpenAiStore */.q.getModel() === 'gpt-4o-mini');
            }
            else {
                const models = await (0,api/* verifyOpenAiApiKey */.z)(AiAssistantStore/* OpenAiStore */.q.getApiKey());
                setHasGPT4(!!models['gpt-4o-mini']);
            }
        }
        doIt();
    }, [hasApiKey]);
    //check for clicks outside clippy, which should close it if it's open and not thinking
    (0,external_react_.useEffect)(() => {
        if (!isInputOpen || isAiThinking)
            return;
        function handleClickOutside(event) {
            if (ref.current && !ref.current.contains(event.target)) {
                setIsInputOpen(false);
            }
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [ref, isInputOpen, isAiThinking]);
    //reset everything when the close animation is done
    (0,external_react_.useEffect)(() => {
        if (isInputOpen)
            return;
        const speed = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--speed-quick'));
        const id = setTimeout(() => closeAndResetInput(), speed);
        return () => clearTimeout(id);
    }, [isInputOpen]);
    (0,external_react_.useEffect)(() => {
        const split = firstInputValue.split(' ');
        if (split.length <= 1 || split[0][0] !== '/')
            return;
        const highlightedOption = ALL_OPTIONS.find((item) => item.title.toLowerCase().indexOf(split[0].toLowerCase()) !== -1);
        if (highlightedOption) {
            setSelectedPromptTitle(highlightedOption.title);
        }
    }, [firstInputValue, ALL_OPTIONS]);
    const closeAndResetInput = (0,external_react_.useCallback)(() => {
        setIsInputOpen(false);
        setFirstInputValue('');
        setSecondInputValue('');
        setIsInputFocused(false);
        setSelectedPromptTitle(null);
        setIsAiThinking(false);
        setShouldFirstInputAutofocus(false);
        setCommandResultItems(null);
    }, []);
    const restartInput = (0,external_react_.useCallback)(() => {
        setFirstInputValue('');
        setSecondInputValue('');
        setSelectedPromptTitle(null);
        setTimeout(() => {
            firstInputRef.current.focus();
        }, 100);
    }, []);
    const portalRoot = document.querySelector('.clippy-layer');
    if (!portalRoot)
        return null;
    const highlightedOption = (firstInputValue === null || firstInputValue === void 0 ? void 0 : firstInputValue.charAt(0)) === '/'
        ? ALL_OPTIONS.find((item) => item.title.toLowerCase().indexOf(firstInputValue.toLowerCase()) !== -1)
        : null;
    const isRegularChat = false; // bring this back later: firstInputValue && firstInputValue.charAt(0) !== '/';
    const selectedOption = selectedPromptTitle ? ALL_OPTIONS.find((item) => item.title === selectedPromptTitle) : null;
    async function runCommand() {
        const id = new Date().getTime().toString();
        closeAndResetInput();
        try {
            const command = selectedOption === null || selectedOption === void 0 ? void 0 : selectedOption.title.toLowerCase();
            const prompt = secondInputValue;
            tracker.tracker.track('AI Command', {
                command,
                prompt
            });
            aiAssistantModel.addActivity({
                id,
                type: selectedOption.type,
                title: selectedOption.title,
                prompt,
                graph: nodeGraphContext.nodeGraph.activeComponent
            });
            setAIThinkingStatus('Give me a second...');
            const res = await handleCommand(command, prompt, { nodeGraph: nodeGraphContext.nodeGraph }, (status) => setAIThinkingStatus(status));
            if (res) {
                setCommandResultItems(res);
            }
        }
        catch (e) {
            console.log(e);
            ToastLayer.ToastLayer.showError(e.toString());
        }
        aiAssistantModel.removeActivity(id);
    }
    const initialPlaceholder = isInputOpen ? 'Select (or type) a command below' : 'Ask Noodl AI';
    const isPromptInWrongOrder = Boolean(!selectedOption) && Boolean(secondInputValue);
    const isFullBeta = ['full-beta', 'enterprise'].includes(version);
    const isLimitedBeta = false; // TODO: version === 'limited-beta';
    let isCommandsEnabled = isLimitedBeta;
    if (version === 'enterprise') {
        isCommandsEnabled = true;
    }
    else if (isFullBeta) {
        if (!hasGPT4 || !hasApiKey) {
            isCommandsEnabled = false;
        }
        else {
            isCommandsEnabled = true;
        }
    }
    let versionLabel = '';
    if (version === 'enterprise') {
        versionLabel = `Enterprise (${AiAssistantStore/* OpenAiStore */.q.getModel()})`;
    }
    else if (isLimitedBeta) {
        versionLabel = 'Limited Beta (gpt-3)';
    }
    else if (isFullBeta && hasApiKey && hasGPT4) {
        versionLabel = 'Full beta (gpt-4)';
    }
    return (external_react_default().createElement(Portal/* Portal */.Z, { portalRoot: portalRoot },
        external_react_default().createElement("div", { ref: ref, className: Clippy_Clippy_module.Root },
            external_react_default().createElement("div", { className: external_classnames_default()(Clippy_Clippy_module.ClippyContainer, isInputFocused && Clippy_Clippy_module.__isFocused, isAiThinking && Clippy_Clippy_module.__isThinking), onClick: () => {
                    if (!isInputOpen) {
                        setShouldFirstInputAutofocus(false);
                        setIsInputOpen(true);
                    }
                } },
                external_react_default().createElement("div", { className: Clippy_Clippy_module.ClippyContent },
                    external_react_default().createElement("div", { className: external_classnames_default()(Clippy_Clippy_module.IconContainer, isInputOpen && Clippy_Clippy_module.__isOpen) },
                        external_react_default().createElement("div", { className: external_classnames_default()(Clippy_Clippy_module.ClippyIcon, isRegularChat && Clippy_Clippy_module.__isHidden) },
                            external_react_default().createElement(ClippyLogo, { isListening: isInputFocused, isDimmed: !isInputOpen, isThinking: isAiThinking })),
                        external_react_default().createElement("div", { className: external_classnames_default()(Clippy_Clippy_module.UserBadge, !isRegularChat && Clippy_Clippy_module.__isHidden) }, user && external_react_default().createElement(UserBadge, { size: UserBadgeSize.Medium, name: user.name, email: user.email, id: user.id }))),
                    external_react_default().createElement("div", { className: external_classnames_default()(Clippy_Clippy_module.InputContainer, isInputOpen && Clippy_Clippy_module.__isOpen) },
                        external_react_default().createElement("div", { className: Clippy_Clippy_module.InputWrapper },
                            Boolean(selectedOption) && (external_react_default().createElement(PromptTag, { title: selectedOption.tag, type: selectedOption.type, onRemoveClick: () => {
                                    restartInput();
                                } })),
                            !selectedOption && (external_react_default().createElement(TextInput, { variant: TextInputVariant.Transparent, value: firstInputValue, placeholder: !isPromptInWrongOrder ? initialPlaceholder : secondInputValue, onFocus: () => setIsInputFocused(true), onBlur: () => setIsInputFocused(false), onChange: (e) => setFirstInputValue(e.currentTarget.value), isAutoFocus: shouldFirstInputAutofocus, forwardedInputRef: firstInputRef, onKeyDown: (e) => {
                                    if (!isCommandsEnabled)
                                        return;
                                    switch (e.key) {
                                        case 'Escape':
                                            closeAndResetInput();
                                            return;
                                    }
                                }, onEnter: () => {
                                    if (!isCommandsEnabled)
                                        return;
                                    if (firstInputValue.charAt(0) === '/') {
                                        setSelectedPromptTitle(highlightedOption.title);
                                    }
                                    else {
                                        const value = firstInputValue;
                                        setSecondInputValue(value);
                                        setFirstInputValue('');
                                    }
                                } })),
                            Boolean(selectedOption) && (external_react_default().createElement(TextInput, { UNSAFE_className: external_classnames_default()(isTextareaInsteadOfInput && Clippy_Clippy_module.__isHiddenInput), variant: TextInputVariant.Transparent, value: secondInputValue, placeholder: selectedOption.placeholder, isAutoFocus: true, onFocus: () => setIsInputFocused(true), onBlur: () => setIsInputFocused(false), onChange: (e) => setSecondInputValue(e.currentTarget.value), onScrollbarCreated: () => setIsTextareaInsteadOfInput(true), onScrollbarRemoved: () => {
                                    setIsTextareaInsteadOfInput(false);
                                    secondInputRef.current.focus();
                                }, forwardedInputRef: secondInputRef, onKeyDown: (e) => {
                                    switch (e.key) {
                                        case 'Backspace':
                                            if (secondInputValue === '') {
                                                restartInput();
                                            }
                                            return;
                                        case 'Escape':
                                            closeAndResetInput();
                                            return;
                                    }
                                }, onEnter: runCommand })),
                            external_react_default().createElement("div", { className: Clippy_Clippy_module.SendIcon, style: { pointerEvents: isCommandsEnabled ? 'all' : 'none' }, onClick: async () => {
                                    if (!selectedOption) {
                                        firstInputRef.current.focus();
                                        setSelectedPromptTitle(highlightedOption.title);
                                    }
                                    if (selectedOption) {
                                        secondInputRef.current.focus();
                                        await runCommand();
                                    }
                                } },
                                external_react_default().createElement(SendIcon, null)),
                            external_react_default().createElement("div", { className: external_classnames_default()(Clippy_Clippy_module.ThinkingOverlay, isAiThinking && Clippy_Clippy_module.__isVisible) },
                                external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Medium }, aiThinkingStatus))),
                        Boolean(selectedOption) && isTextareaInsteadOfInput && isInputOpen && (external_react_default().createElement("div", { className: Clippy_Clippy_module.TextArea },
                            external_react_default().createElement(GrowingTextArea, { value: secondInputValue, onChange: (e) => {
                                    setSecondInputValue(e.currentTarget.value);
                                    if (e.currentTarget.value === '') {
                                        setIsTextareaInsteadOfInput(false);
                                        secondInputRef.current.focus();
                                    }
                                }, onFocus: () => setIsInputFocused(true), onBlur: () => setIsInputFocused(false), forwardedTextAreaRef: secondTextAreaRef, isAutoFocus: true, onKeyDown: (e) => {
                                    switch (e.key) {
                                        case 'Enter':
                                            e.shiftKey && runCommand();
                                            return;
                                        case 'Escape':
                                            closeAndResetInput();
                                            return;
                                    }
                                } })))))),
            external_react_default().createElement("div", { className: Clippy_Clippy_module.UglySpacingHackPleaseLookAway }),
            external_react_default().createElement("div", { className: external_classnames_default()(Clippy_Clippy_module.ClippyPopup, isInputOpen && !isAiThinking && Clippy_Clippy_module.__isVisible) },
                isFullBeta && !isCommandsEnabled && (external_react_default().createElement("div", { className: Clippy_Clippy_module.ClippyNoApiKey },
                    external_react_default().createElement(Title/* Title */.hE, { hasBottomSpacing: true }, "Add your OpenAI API key"),
                    external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, "You need a GPT-4 API key to access the full beta features."),
                    external_react_default().createElement(typography_Text/* Text */.EY, null,
                        "1. Get your API key from your",
                        ' ',
                        external_react_default().createElement("a", { href: "https://platform.openai.com/account/api-keys", target: "_blank", rel: "noreferrer" }, "OpenAI account")),
                    external_react_default().createElement(typography_Text/* Text */.EY, null, "2. Make sure GPT-4 is enabled for your account"),
                    external_react_default().createElement(typography_Text/* Text */.EY, null, "3. Paste the key into the AI section in the Editor Settings panel"),
                    external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, "4. Click the \"Verify API Key\" button"),
                    external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, "If you dont have an API key with GPT-4 access, you can set the Noodl AI to use the Limited Beta in the editor settings."),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, onClick: () => models_sidebar/* SidebarModel */.s.instance.switch('editor-settings'), label: "Open editor settings" }))),
                isCommandsEnabled && !selectedPromptTitle && !isRegularChat && (external_react_default().createElement((external_react_default()).Fragment, null,
                    isPromptInWrongOrder && (external_react_default().createElement(Label/* Label */.JU, { UNSAFE_style: { padding: 12, marginTop: 2 }, size: Label/* LabelSize */.IV.Big, variant: FeedbackType/* FeedbackType */.M.Danger }, "The AI needs some context. Please select one below.")),
                    Boolean(copilotNodes.length) && (external_react_default().createElement((external_react_default()).Fragment, null,
                        external_react_default().createElement(SectionTitle, { title: "Copilot nodes" }),
                        copilotNodes.map((item, i) => (external_react_default().createElement(PromptTagSuggestion, { title: item.title, description: item.description, type: item.type, icon: item.icon, key: item.title, isHighlighted: highlightedOption ? highlightedOption.title === item.title : false, onClick: () => {
                                if (copilotNodeInstaPromptable.includes(item.title.toLowerCase())) {
                                    setSelectedPromptTitle(item.title);
                                    setSecondInputValue(firstInputValue);
                                }
                                else {
                                    const panAndScale = nodeGraphContext.nodeGraph.getPanAndScale();
                                    const x = Math.round(Math.random() * 100 + 50);
                                    const y = Math.round(Math.random() * 100 + 50);
                                    const scaledPos = {
                                        x: x / panAndScale.scale - panAndScale.x,
                                        y: y / panAndScale.scale - panAndScale.y
                                    };
                                    AiAssistant/* AiAssistantModel */.g.instance.createNode(item.templateId, null, scaledPos);
                                    setIsInputOpen(false);
                                }
                            } }))))),
                    Boolean(promptToNode.length) && (external_react_default().createElement((external_react_default()).Fragment, null,
                        external_react_default().createElement(SectionTitle, { title: "Experimental features" }),
                        promptToNode.map((item, i) => (external_react_default().createElement(PromptTagSuggestion, { title: item.title, description: item.description, type: item.type, icon: item.icon, key: item.title, isHighlighted: highlightedOption ? highlightedOption.title === item.title : false, onClick: () => setSelectedPromptTitle(item.title) }))))),
                    Boolean(disabledDueToGpt3Items.length) && (external_react_default().createElement((external_react_default()).Fragment, null,
                        external_react_default().createElement(SectionTitle, { title: "Requires a key with GPT4 support" }),
                        disabledDueToGpt3Items.map((item, i) => (external_react_default().createElement(PromptTagSuggestion, { isDisabled: true, title: item.title, description: item.description, type: item.type, icon: item.icon, key: item.title }))))),
                    Boolean(comingSoonItems.length) && (external_react_default().createElement((external_react_default()).Fragment, null,
                        external_react_default().createElement(SectionTitle, { title: "Coming soon" }),
                        comingSoonItems.map((item, i) => (external_react_default().createElement(PromptTagSuggestion, { isDisabled: true, title: item.title, description: item.description, type: item.type, icon: item.icon, key: item.title }))))),
                    Boolean(aiAssistantModel.activities.length) && (external_react_default().createElement((external_react_default()).Fragment, null,
                        external_react_default().createElement(SectionTitle, { title: "Processing" }),
                        aiAssistantModel.activities.map((activity) => (external_react_default().createElement(PromptTagSuggestion, { title: activity.title, description: activity.prompt, icon: "AI", type: activity.type, key: activity.id, isDisabled: !activity.graph, onClick: () => {
                                if (!activity.graph)
                                    return;
                                nodeGraphContext.switchToComponent(activity.graph, {
                                    node: (activity === null || activity === void 0 ? void 0 : activity.node) || undefined,
                                    pushHistory: true
                                });
                            } }))))))),
                isRegularChat && (external_react_default().createElement((external_react_default()).Fragment, null,
                    external_react_default().createElement(SectionTitle, { title: "Chat history" }),
                    external_react_default().createElement("div", { className: Clippy_Clippy_module.AiChatItem },
                        external_react_default().createElement("div", { className: Clippy_Clippy_module.IconContainer },
                            external_react_default().createElement(ClippyLogo, { isListening: true })),
                        external_react_default().createElement(Label/* Label */.JU, null, "How can I help you?")))),
                Boolean(selectedPromptTitle) && selectedOption.examples && !commandResultItems && (external_react_default().createElement((external_react_default()).Fragment, null,
                    external_react_default().createElement(SectionTitle, { title: "Example prompts" }),
                    selectedOption.examples.map((item, i) => (external_react_default().createElement(ExamplePrompt, { prompt: item, onClick: () => {
                            setSecondInputValue(item);
                            secondInputRef.current.focus();
                        }, key: item }))))),
                Boolean(commandResultItems) && (external_react_default().createElement((external_react_default()).Fragment, null,
                    external_react_default().createElement(SectionTitle, { title: "Example prompts" }),
                    commandResultItems.map((item, i) => (external_react_default().createElement(PromptTagSuggestion, { title: item.name, description: item.description, type: PopupItemType.Visual, icon: common_Icon/* IconName */.$M.UI, key: i, onClick: () => {
                            setSelectedPromptTitle('/' + item.name);
                            setSecondInputValue(item.prompt);
                            setCommandResultItems(null);
                        } }))))),
                !isFullBeta && (external_react_default().createElement("div", { className: Clippy_Clippy_module.LimitedBetaCard },
                    external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Medium, variant: typography_Text/* TextType */.M2.Proud, hasBottomSpacing: true }, "Limited beta"),
                    external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true, size: typography_Text/* TextSize */.$C.Medium }, "You are running the limited beta of Noodl AI. If features fewer commands and a less capable AI. Get full beta access by bringing your own GPT-4 API key."),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, label: "Full beta setup instructions", href: (0,editor_getDocsEndpoint/* default */.A)() + '/docs/getting-started/noodl-ai#full-beta' }))),
                versionLabel && (external_react_default().createElement("div", { className: Clippy_Clippy_module.GptVersionDisplay },
                    external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Small, variant: typography_Text/* TextType */.M2.Shy }, versionLabel)))),
            external_react_default().createElement("div", { className: Clippy_Clippy_module.CurrentActivities }, aiAssistantModel.activities.map((activity) => (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: activity.prompt, fineType: activity.title, showAfterMs: 100, renderDirection: BaseDialog/* DialogRenderDirection */.K1.Horizontal, key: activity.id },
                external_react_default().createElement("div", { className: external_classnames_default()(Clippy_Clippy_module.ActivityItem, Clippy_Clippy_module[activity.type]), onClick: () => {
                        if (!activity.graph)
                            return;
                        nodeGraphContext.switchToComponent(activity.graph, {
                            node: (activity === null || activity === void 0 ? void 0 : activity.node) || undefined,
                            pushHistory: true
                        });
                    } },
                    external_react_default().createElement("div", { className: Clippy_Clippy_module.ActivityLogo },
                        external_react_default().createElement(ClippyLogo, { isThinking: true }))))))))));
}
function SectionTitle({ title }) {
    return (external_react_default().createElement("div", { className: Clippy_Clippy_module.SectionTitle },
        external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Shy, size: Label/* LabelSize */.IV.Small }, title)));
}
function PromptTagSuggestion({ title, description, type, icon, isHighlighted, isDisabled, onClick }) {
    return (external_react_default().createElement("div", { className: external_classnames_default()(Clippy_Clippy_module.PromptTagSuggestionRoot, isHighlighted && Clippy_Clippy_module.__isHighlighted, isDisabled && Clippy_Clippy_module.__isDisabled), onClick: onClick },
        external_react_default().createElement("div", { className: Clippy_Clippy_module.PromptTagSuggestionItem },
            external_react_default().createElement("div", { className: external_classnames_default()(Clippy_Clippy_module.TagType, icon !== 'AI' && Clippy_Clippy_module[type]) }, icon === 'AI' ? (external_react_default().createElement("div", { className: Clippy_Clippy_module.PromptTagSuggestionAiIconContainer },
                external_react_default().createElement(ClippyLogo, { isThinking: true }))) : (external_react_default().createElement(common_Icon/* Icon */.In, { icon: icon, variant: typography_Text/* TextType */.M2.DefaultContrast, size: common_Icon/* IconSize */.lK.Tiny }))),
            external_react_default().createElement("div", { className: Clippy_Clippy_module.details },
                external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Proud }, title),
                external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, description)))));
}
function PromptTag({ title, type, onRemoveClick }) {
    return (external_react_default().createElement("div", { className: external_classnames_default()(Clippy_Clippy_module.PromptTagRoot, Clippy_Clippy_module[type]) },
        external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Small, variant: typography_Text/* TextType */.M2.DefaultContrast }, title),
        external_react_default().createElement("div", { className: Clippy_Clippy_module.PromptTagRemove, onClick: onRemoveClick },
            external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Close, size: common_Icon/* IconSize */.lK.Tiny }))));
}
function ExamplePrompt({ prompt, onClick }) {
    return (external_react_default().createElement("div", { className: Clippy_Clippy_module.ExamplePromptRoot },
        external_react_default().createElement("div", { className: Clippy_Clippy_module.ExamplePrompt, onClick: onClick },
            external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Default },
                "\"",
                prompt,
                "\""))));
}
function SendIcon() {
    return (external_react_default().createElement("svg", { width: "28", height: "28", viewBox: "0 0 28 28", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
        external_react_default().createElement("path", { d: "M21.7409 13.0157L9.92836 6.27347C9.72924 6.16177 9.50086 6.1133 9.27354 6.1345C9.04622 6.15569 8.83073 6.24554 8.65569 6.39212C8.48065 6.5387 8.35436 6.73506 8.29357 6.95512C8.23279 7.17519 8.2404 7.40854 8.31539 7.62417L10.4951 13.9853C10.4948 13.9877 10.4948 13.99 10.4951 13.9924C10.4947 13.9947 10.4947 13.9971 10.4951 13.9994L8.31539 20.3746C8.25533 20.5443 8.23684 20.7258 8.26147 20.9041C8.2861 21.0823 8.35313 21.2521 8.45693 21.3991C8.56073 21.5461 8.69828 21.666 8.85802 21.7488C9.01777 21.8317 9.19505 21.875 9.375 21.8751C9.57024 21.8746 9.76204 21.8238 9.93188 21.7275L21.738 14.9739C21.9122 14.8764 22.0573 14.7343 22.1583 14.5621C22.2594 14.39 22.3129 14.1941 22.3132 13.9945C22.3136 13.7948 22.2608 13.5987 22.1604 13.4262C22.0599 13.2538 21.9154 13.1111 21.7416 13.0129L21.7409 13.0157ZM9.375 20.7501V20.7438L11.4942 14.5626H15.5625C15.7117 14.5626 15.8548 14.5033 15.9602 14.3979C16.0657 14.2924 16.125 14.1493 16.125 14.0001C16.125 13.8509 16.0657 13.7079 15.9602 13.6024C15.8548 13.4969 15.7117 13.4376 15.5625 13.4376H11.4998L9.37922 7.25855L9.375 7.25011L21.1875 13.9882L9.375 20.7501Z", fill: "#f5f5f5" })));
}

;// ./src/editor/src/hooks/useTriggerRerender.ts

function useTriggerRerender() {
    const [_, setTimestamp] = (0,external_react_.useState)(0);
    function triggerRender() {
        const timestamp = Date.now();
        setTimestamp(timestamp);
    }
    return triggerRender;
}
function useTriggerRerenderState() {
    const [time, setTimestamp] = (0,external_react_.useState)(0);
    function triggerRender() {
        const timestamp = Date.now();
        setTimestamp(timestamp);
    }
    return [time, triggerRender];
}

;// ./src/editor/src/constants/Keybindings.ts


var Keybindings;
(function (Keybindings) {
    Keybindings.REFRESH_PREVIEW = new Keybinding(KeyCode.KeyMod.CtrlCmd, KeyCode.KeyCode.KEY_R);
    Keybindings.OPEN_DEVTOOLS = new Keybinding(KeyCode.KeyMod.CtrlCmd, KeyCode.KeyCode.KEY_D);
    Keybindings.OPEN_CLOUD_DEVTOOLS = new Keybinding(KeyCode.KeyMod.CtrlCmd, KeyCode.KeyMod.Shift, KeyCode.KeyCode.KEY_R);
    Keybindings.TOGGLE_PREVIEW_MODE = new Keybinding(KeyCode.KeyMod.CtrlCmd, KeyCode.KeyCode.KEY_T);
    Keybindings.PROPERTY_PANEL_OPEN_DOCS = new Keybinding(KeyCode.KeyCode.F1);
    Keybindings.PROPERTY_PANEL_EDIT_LABEL = new Keybinding(KeyCode.KeyCode.Enter);
    Keybindings.PROPERTY_PANEL_EDIT_LABEL2 = new Keybinding(KeyCode.KeyCode.F2);
    Keybindings.PROPERTY_PANEL_DELETE = new Keybinding(KeyCode.KeyCode.Delete); // Actually node graph delete
})(Keybindings || (Keybindings = {}));

// EXTERNAL MODULE: ./src/editor/src/models/warningsmodel.ts
var warningsmodel = __webpack_require__(86105);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/ToggleSwitch/ToggleSwitch.module.scss
var ToggleSwitch_module = __webpack_require__(93158);
;// ../noodl-core-ui/src/components/inputs/ToggleSwitch/ToggleSwitch.module.scss

      
      
      
      
      
      
      
      
      

var ToggleSwitch_module_options = {};

ToggleSwitch_module_options.styleTagTransform = (styleTagTransform_default());
ToggleSwitch_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ToggleSwitch_module_options.insert = insertBySelector_default().bind(null, "head");
    
ToggleSwitch_module_options.domAPI = (styleDomAPI_default());
ToggleSwitch_module_options.insertStyleElement = (insertStyleElement_default());

var ToggleSwitch_module_update = injectStylesIntoStyleTag_default()(ToggleSwitch_module/* default */.A, ToggleSwitch_module_options);




       /* harmony default export */ const ToggleSwitch_ToggleSwitch_module = (ToggleSwitch_module/* default */.A && ToggleSwitch_module/* default */.A.locals ? ToggleSwitch_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/ToggleSwitch/ToggleSwitch.tsx




function ToggleSwitch({ value, label, isChecked, isAlwaysActiveColor, onChange }) {
    return (external_react_default().createElement("div", { className: ToggleSwitch_ToggleSwitch_module['Root'] },
        label && external_react_default().createElement(Label/* Label */.JU, null, label),
        external_react_default().createElement("label", { className: ToggleSwitch_ToggleSwitch_module['Track'] },
            external_react_default().createElement("div", { className: external_classnames_default()(ToggleSwitch_ToggleSwitch_module['Indicator'], isChecked && ToggleSwitch_ToggleSwitch_module['is-checked'], isAlwaysActiveColor && ToggleSwitch_ToggleSwitch_module['is-always-active-color']) }),
            external_react_default().createElement("input", { className: ToggleSwitch_ToggleSwitch_module['Input'], type: "checkbox", checked: isChecked, onChange: onChange, value: value }))));
}

;// ../noodl-core-ui/src/components/inputs/ToggleSwitch/index.ts


// EXTERNAL MODULE: ./src/editor/src/views/createnewnodepanel.ts + 49 modules
var createnewnodepanel = __webpack_require__(91559);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Tabs/index.ts + 2 modules
var Tabs = __webpack_require__(35315);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/popups/PopupSection/PopupSection.module.scss
var PopupSection_module = __webpack_require__(5270);
;// ../noodl-core-ui/src/components/popups/PopupSection/PopupSection.module.scss

      
      
      
      
      
      
      
      
      

var PopupSection_module_options = {};

PopupSection_module_options.styleTagTransform = (styleTagTransform_default());
PopupSection_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      PopupSection_module_options.insert = insertBySelector_default().bind(null, "head");
    
PopupSection_module_options.domAPI = (styleDomAPI_default());
PopupSection_module_options.insertStyleElement = (insertStyleElement_default());

var PopupSection_module_update = injectStylesIntoStyleTag_default()(PopupSection_module/* default */.A, PopupSection_module_options);




       /* harmony default export */ const PopupSection_PopupSection_module = (PopupSection_module/* default */.A && PopupSection_module/* default */.A.locals ? PopupSection_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/popups/PopupSection/PopupSection.tsx



function PopupSection({ children, title, className, maxContentHeight, hasBottomBorder, hasYPadding, isCenteringChildren, style, contentContainerStyle }) {
    const contentRef = (0,external_react_.useRef)(null);
    const [shouldScroll, setShouldScroll] = (0,external_react_.useState)(false);
    const [hasBeenCalculated, setHasBeenCalculated] = (0,external_react_.useState)(false);
    function checkIfShouldScroll() {
        if (!contentRef.current || !maxContentHeight)
            return false;
        if (contentRef.current.getBoundingClientRect().height >= maxContentHeight)
            return true;
        return false;
    }
    (0,external_react_.useLayoutEffect)(() => {
        if (contentRef.current) {
            setShouldScroll(checkIfShouldScroll());
            setHasBeenCalculated(true);
        }
    }, [contentRef, children]);
    return (external_react_default().createElement("section", { className: external_classnames_default()([PopupSection_PopupSection_module['Root'], hasBottomBorder && PopupSection_PopupSection_module['has-bottom-border'], className]), style: {
            ...style,
            overflowY: hasBeenCalculated ? undefined : 'hidden',
            height: hasBeenCalculated ? undefined : 0
        } },
        title && (external_react_default().createElement("header", { className: PopupSection_PopupSection_module['Header'] },
            external_react_default().createElement("h2", { className: PopupSection_PopupSection_module['Title'] }, title))),
        children ? (external_react_default().createElement("div", { className: external_classnames_default()([
                PopupSection_PopupSection_module['Content'],
                hasYPadding && PopupSection_PopupSection_module['has-y-padding'],
                isCenteringChildren && PopupSection_PopupSection_module['is-centering-children']
            ]), ref: contentRef, style: {
                ...contentContainerStyle,
                height: shouldScroll ? maxContentHeight : undefined,
                overflowY: shouldScroll ? 'overlay' : undefined
            } }, children)) : (external_react_default().createElement("div", { ref: contentRef }))));
}

;// ../noodl-core-ui/src/components/popups/PopupSection/index.ts


// EXTERNAL MODULE: ./src/editor/src/views/ToastLayer/components/ToastCard/index.ts + 5 modules
var ToastCard = __webpack_require__(20749);
;// ./src/editor/src/hooks/useActivityQueue.ts




/**
 *
 * @returns
 */
function useActivityQueue({ errorMessage = 'Something went wrong', onSuccess, onError }) {
    const [activities, setActivities] = (0,external_react_.useState)([]);
    function addActivity(activityId) {
        setActivities((value) => {
            if (!value.includes(activityId)) {
                value.push(activityId);
            }
            return value;
        });
    }
    function removeActivity(activityId) {
        setActivities((value) => {
            if (value.includes(activityId)) {
                return value.filter((x) => x !== activityId);
            }
            return value;
        });
    }
    async function runActivity(message, callback) {
        const activityId = (0,utils.guid)();
        addActivity(activityId);
        ToastLayer.ToastLayer.showActivity(message, activityId);
        try {
            const response = await callback();
            ToastLayer.ToastLayer.hideActivity(activityId);
            switch (response.type) {
                default:
                case ToastCard/* ToastType */.C.Neutral:
                    ToastLayer.ToastLayer.showInteraction(response.message);
                    break;
                case ToastCard/* ToastType */.C.Danger:
                    ToastLayer.ToastLayer.showError(response.message);
                    break;
                case ToastCard/* ToastType */.C.Success:
                    ToastLayer.ToastLayer.showSuccess(response.message);
                    break;
            }
            if (onSuccess) {
                await onSuccess();
            }
        }
        catch (error) {
            ToastLayer.ToastLayer.hideActivity(activityId);
            ToastLayer.ToastLayer.showError(errorMessage);
            if (onError) {
                await onError();
            }
            throw error;
        }
        finally {
            removeActivity(activityId);
        }
    }
    async function runQuietActivity(callback) {
        const activityId = (0,utils.guid)();
        addActivity(activityId);
        try {
            await callback(activityId);
            if (onSuccess) {
                await onSuccess();
            }
        }
        catch (error) {
            ToastLayer.ToastLayer.hideActivity(activityId);
            ToastLayer.ToastLayer.showError(errorMessage);
            if (onError) {
                await onError();
            }
            throw error;
        }
        finally {
            removeActivity(activityId);
        }
    }
    return {
        activities,
        hasActivity: activities.length > 0,
        runActivity,
        runQuietActivity
    };
}

;// ./src/editor/src/views/DeployPopup/DeployPopup.context.tsx


const DeployContext = (0,external_react_.createContext)({
    updateQueue: null,
    hasActivity: null,
    runActivity: null
});
function DeployContextProvider({ children }) {
    const { hasActivity, runActivity } = useActivityQueue({});
    return (external_react_default().createElement(DeployContext.Provider, { value: {
            updateQueue: null,
            hasActivity,
            runActivity
        } }, children));
}
function useDeployContext() {
    const context = (0,external_react_.useContext)(DeployContext);
    if (context === undefined) {
        throw new Error('useDeployContext must be a child of DeployContextProvider');
    }
    return context;
}

// EXTERNAL MODULE: ./src/editor/src/utils/compilation/compilation.ts
var compilation = __webpack_require__(93193);
;// ./src/editor/src/utils/compilation/compilation.editor.ts


/**
 * Create a Compilation instance with Editor settings.
 *
 * @param project
 * @returns
 */
function createEditorCompilation(project) {
    const feedback = {
        showActivity: ToastLayer.ToastLayer.showActivity,
        hideActivity: ToastLayer.ToastLayer.hideActivity,
        showSuccess: ToastLayer.ToastLayer.showSuccess,
        showError: ToastLayer.ToastLayer.showError,
        showInteraction: ToastLayer.ToastLayer.showInteraction
    };
    return new compilation/* Compilation */.O(project, feedback, {
        cloneProject: true
    });
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/Select/Select.module.scss
var Select_module = __webpack_require__(73186);
;// ../noodl-core-ui/src/components/inputs/Select/Select.module.scss

      
      
      
      
      
      
      
      
      

var Select_module_options = {};

Select_module_options.styleTagTransform = (styleTagTransform_default());
Select_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      Select_module_options.insert = insertBySelector_default().bind(null, "head");
    
Select_module_options.domAPI = (styleDomAPI_default());
Select_module_options.insertStyleElement = (insertStyleElement_default());

var Select_module_update = injectStylesIntoStyleTag_default()(Select_module/* default */.A, Select_module_options);




       /* harmony default export */ const Select_Select_module = (Select_module/* default */.A && Select_module/* default */.A.locals ? Select_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/Select/Select.tsx








var SelectColorTheme;
(function (SelectColorTheme) {
    SelectColorTheme["Transparent"] = "is-color-theme-transparent";
    SelectColorTheme["Dark"] = "is-color-theme-dark";
    SelectColorTheme["DarkLighter"] = "is-color-theme-dark-lighter";
})(SelectColorTheme || (SelectColorTheme = {}));
var SelectSize;
(function (SelectSize) {
    SelectSize["Default"] = "is-size-default";
    SelectSize["Small"] = "is-size-small";
})(SelectSize || (SelectSize = {}));
function Select({ options = [], value, placeholder = 'Select an option', notification, label, colorTheme = SelectColorTheme.Dark, size = SelectSize.Default, isOptionsPushingSiblings, hasBottomSpacing, isDisabled, onChange, testId, UNSAFE_className, UNSAFE_style }) {
    const rootRef = (0,external_react_.useRef)(null);
    const [newNotification, updateNotification] = useNotificationFeedbackDisplay(notification);
    const [showOptions, setShowOptions] = (0,external_react_.useState)(false);
    const selectedOption = (0,external_react_.useMemo)(() => {
        if (value === undefined)
            return null;
        return options.find((option) => option.value === value);
    }, [options, value]);
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        label && external_react_default().createElement(InputLabelSection, { label: label }),
        external_react_default().createElement("div", { ref: rootRef, tabIndex: 1, className: external_classnames_default()([
                Select_Select_module['Root'],
                Select_Select_module[colorTheme],
                hasBottomSpacing && Select_Select_module['has-bottom-spacing'],
                isDisabled && Select_Select_module['is-disabled'],
                showOptions && Select_Select_module['is-focused'],
                UNSAFE_className
            ]), "data-test": testId, style: UNSAFE_style },
            external_react_default().createElement("div", { className: Select_Select_module['DisplayContainer'], onClick: () => setShowOptions(!showOptions) },
                external_react_default().createElement("div", { className: external_classnames_default()([Select_Select_module['DisplayText'], Select_Select_module[size], !(selectedOption === null || selectedOption === void 0 ? void 0 : selectedOption.label) && Select_Select_module['is-placeholder']]) }, (selectedOption === null || selectedOption === void 0 ? void 0 : selectedOption.label) || placeholder),
                external_react_default().createElement(common_Icon/* Icon */.In, { UNSAFE_className: Select_Select_module['Icon'], icon: common_Icon/* IconName */.$M.CaretDown }),
                newNotification && external_react_default().createElement(NotificationFeedbackDisplay, { notification: newNotification })),
            external_react_default().createElement("div", { className: external_classnames_default()([
                    Select_Select_module['OptionsContainer'],
                    isOptionsPushingSiblings ? Select_Select_module['is-options-pushing-siblings'] : Select_Select_module['is-options-overlaid']
                ]) },
                external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { triggerRef: rootRef, variant: BaseDialog/* BaseDialogVariant */.TT.Select, isVisible: showOptions, onClose: () => setShowOptions(false), renderDirection: BaseDialog/* DialogRenderDirection */.K1.Below, isLockingScroll: true },
                    external_react_default().createElement("div", { className: external_classnames_default()([Select_Select_module['OptionsList'], Select_Select_module[colorTheme]]) }, options.map((option) => {
                        if (option.value === value)
                            return null;
                        return (external_react_default().createElement("div", { "data-test": "select-option", key: option.value, className: external_classnames_default()([
                                Select_Select_module['Option'],
                                Select_Select_module[size],
                                option.isDisabled && Select_Select_module['is-disabled'],
                                option.value === value && Select_Select_module['is-selected']
                            ]), onClick: () => {
                                if (option.isDisabled)
                                    return;
                                setShowOptions(false);
                                onChange(option.value);
                            } }, option.label));
                    })))))));
}

;// ../noodl-core-ui/src/components/inputs/Select/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Text/Text.tsx + 1 modules
var Text_Text = __webpack_require__(75864);
;// ./src/editor/src/views/DeployPopup/DeployPopup.constants.ts
const NO_ENVIRONMENT_VALUE = '';

;// ./src/editor/src/views/DeployPopup/DeployPopup.hooks.ts

/**
 * No caching, enjoy!
 *
 * @param cloudService
 * @returns
 */
function useEnvironmentsAsOptions(cloudService) {
    var _a;
    const options = [{ label: 'No cloud service', value: NO_ENVIRONMENT_VALUE }];
    if (!((_a = cloudService.backend.items) === null || _a === void 0 ? void 0 : _a.length))
        return options;
    cloudService.backend.items.forEach((env) => {
        options.push({ label: env.name, value: env.id });
    });
    return options;
}

;// ./src/editor/src/views/DeployPopup/tabs/DeployToFolderTab/DeployToFolderTab.tsx















function DeployToFolderTab() {
    var _a;
    const cloudService = (0,useModel/* useModernModel */.e)(CloudServices.CloudService.instance);
    const environmentOptions = useEnvironmentsAsOptions(cloudService);
    const [environmentId, setEnvironmentId] = (0,external_react_.useState)(NO_ENVIRONMENT_VALUE);
    function onPickFolderClicked() {
        const activityId = 'deploying-project';
        src.filesystem
            .openDialog({
            allowCreateDirectory: true
        })
            .then((direntry) => {
            const compilation = createEditorCompilation(projectmodel.ProjectModel.instance)
                .addProjectBuildScripts()
                .addBuildScript({
                async onPreBuild() {
                    ToastLayer.ToastLayer.showActivity('Deploying', activityId);
                },
                async onPostBuild({ status }) {
                    ToastLayer.ToastLayer.hideActivity(activityId);
                    if (status === 'success') {
                        ToastLayer.ToastLayer.showSuccess('Deploy successful!');
                    }
                    else {
                        ToastLayer.ToastLayer.showError('Deploy failed.');
                    }
                }
            });
            const environment = cloudService.backend.items.find((x) => x.id === environmentId);
            // NOTE: Fire-n-forget
            compilation.deployToFolder(direntry, {
                environment
            });
            // NOTE: To deploy SSR, this will be updated with the new deploy popup design
            // compilation
            //   .deployToFolder(direntry, {
            //     environment,
            //     runtimeType: 'ssr'
            //   })
            //   .then(() => {
            //     compilation.deployToFolder(direntry + '/public', {
            //       environment,
            //     });
            //   });
        });
        popuplayer_default().instance.hidePopup();
    }
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(PopupSection, null,
            external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true, textType: Text_Text/* TextType */.M2.DefaultContrast }, "Deploy your frontend to a local folder"),
            Boolean((_a = cloudService.backend.items) === null || _a === void 0 ? void 0 : _a.length) && (external_react_default().createElement(Select, { options: environmentOptions, onChange: (value) => setEnvironmentId(value), placeholder: "No cloud services", value: environmentId, label: "Connected cloud services", hasBottomSpacing: true })),
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Pick folder", onClick: onPickFolderClicked }))));
}

;// ./src/editor/src/views/DeployPopup/tabs/DeployToFolderTab/index.ts


;// ./src/editor/src/views/DeployPopup/DeployPopup.tsx







function DeployPopupChild() {
    const { hasActivity } = useDeployContext();
    return (external_react_default().createElement("div", { style: { width: 400 } },
        external_react_default().createElement("div", { style: {
                backgroundColor: '#444444',
                position: 'relative',
                maxHeight: `calc(90vh - 40px)`,
                overflowY: 'overlay',
                overflowX: 'hidden'
            } },
            external_react_default().createElement(PopupSection, { title: "Deploy options" }),
            external_react_default().createElement(Tabs/* Tabs */.t, { tabs: [{ label: 'Self Hosting', content: external_react_default().createElement(DeployToFolderTab, null), testId: 'self-hosting-tab-button' }] }),
            hasActivity && external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, { isOverlay: true }))));
}
function DeployPopup(props) {
    return (external_react_default().createElement(DeployContextProvider, null,
        external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { triggerRef: props.triggerRef, isVisible: props.isVisible, onClose: props.onClose, hasArrow: true, isLockingScroll: true },
            external_react_default().createElement(DeployPopupChild, null))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/EditorTopbar/EditorTopbar.module.scss
var EditorTopbar_module = __webpack_require__(10267);
;// ./src/editor/src/views/EditorTopbar/EditorTopbar.module.scss

      
      
      
      
      
      
      
      
      

var EditorTopbar_module_options = {};

EditorTopbar_module_options.styleTagTransform = (styleTagTransform_default());
EditorTopbar_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      EditorTopbar_module_options.insert = insertBySelector_default().bind(null, "head");
    
EditorTopbar_module_options.domAPI = (styleDomAPI_default());
EditorTopbar_module_options.insertStyleElement = (insertStyleElement_default());

var EditorTopbar_module_update = injectStylesIntoStyleTag_default()(EditorTopbar_module/* default */.A, EditorTopbar_module_options);




       /* harmony default export */ const EditorTopbar_EditorTopbar_module = (EditorTopbar_module/* default */.A && EditorTopbar_module/* default */.A.locals ? EditorTopbar_module/* default */.A.locals : undefined);

// EXTERNAL MODULE: ./src/editor/src/constants/NodeType.ts
var NodeType = __webpack_require__(20396);
// EXTERNAL MODULE: ./src/editor/src/utils/NodeGraph/index.ts
var NodeGraph = __webpack_require__(52877);
;// ../noodl-core-ui/src/components/popups/MenuDialog/MenuDialog.utils.ts
function insertDividerBetweenAllItems(array) {
    return [].concat(...array.map((item) => [item, 'divider'])).slice(0, -1);
}

;// ./src/editor/src/views/EditorTopbar/EditorTopbar.returnWarningItems.tsx










function getStyleFromNodeType(nodeType) {
    const type = nodeType === null || nodeType === void 0 ? void 0 : nodeType.color;
    let colorName = '';
    switch (type) {
        case NodeType/* NodeType */.Z.Visual:
            colorName = 'blue';
            break;
        case NodeType/* NodeType */.Z.Logic:
            colorName = 'grey';
            break;
        case NodeType/* NodeType */.Z.Data:
            colorName = 'green';
            break;
        case NodeType/* NodeType */.Z.Connection:
            colorName = 'purple';
            break;
        case NodeType/* NodeType */.Z.Custom:
            colorName = 'pink';
            break;
        default:
            colorName = 'grey';
    }
    return {
        backgroundColor: `var(--base-color-node-${colorName}-500)`,
        color: `var(--base-color-node-${colorName}-100)`,
        display: 'inline-block',
        padding: 2,
        borderRadius: 2
    };
}
function partitionArray(array, conditionFunc) {
    return array.reduce(([pass, fail], elem) => {
        return conditionFunc(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]];
    }, [[], []]);
}
function isMergeConflictWarning(warning) {
    var _a, _b;
    return ((_a = warning === null || warning === void 0 ? void 0 : warning.warning) === null || _a === void 0 ? void 0 : _a.type) === 'conflict-source-code' || ((_b = warning === null || warning === void 0 ? void 0 : warning.warning) === null || _b === void 0 ? void 0 : _b.type) === 'conflict';
}
function returnWarningItems(warnings, nodeGraphContext) {
    if (!warnings.length)
        return [];
    const existingWarnings = warnings.filter((warning) => Boolean(warning.ref.component));
    if (!existingWarnings.length)
        return [];
    //put all the merge warnings at the top
    const [mergeConflictWarnings, otherWarnings] = partitionArray(existingWarnings, isMergeConflictWarning);
    const sortedWarnings = mergeConflictWarnings.concat(otherWarnings);
    return insertDividerBetweenAllItems(sortedWarnings.map((warning) => {
        var _a, _b, _c, _d, _e, _f, _g;
        function endSlot() {
            var _a, _b, _c;
            const componentName = (_a = warning.ref.component) === null || _a === void 0 ? void 0 : _a.name.replace('/#__cloud__', '');
            const isCloudComponent = (0,NodeGraph/* isComponentModel_CloudRuntime */.dk)(warning.ref.component);
            if (isMergeConflictWarning(warning)) {
                return (external_react_default().createElement(Stack/* VStack */.Tk, null,
                    external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true },
                        "At node",
                        ' ',
                        external_react_default().createElement(Label/* Label */.JU, { isInline: true, UNSAFE_style: getStyleFromNodeType(warning.ref.node.type) }, warning.ref.node.label),
                        ' ',
                        "in ",
                        isCloudComponent && 'cloud function ',
                        "component ",
                        componentName),
                    external_react_default().createElement(MergeConflict, { warning: warning })));
            }
            else if ((_b = warning === null || warning === void 0 ? void 0 : warning.ref) === null || _b === void 0 ? void 0 : _b.node) {
                return (external_react_default().createElement(typography_Text/* Text */.EY, null,
                    "At node",
                    ' ',
                    external_react_default().createElement(Label/* Label */.JU, { isInline: true, UNSAFE_style: getStyleFromNodeType(warning.ref.node.type) }, warning.ref.node.label),
                    ' ',
                    "in ",
                    isCloudComponent && 'cloud function ',
                    "component ",
                    componentName));
            }
            else if ((_c = warning === null || warning === void 0 ? void 0 : warning.ref) === null || _c === void 0 ? void 0 : _c.component) {
                const sourceNode = warning.ref.component.graph.findNodeWithId(warning.ref.connection.fromId);
                const targetNode = warning.ref.component.graph.findNodeWithId(warning.ref.connection.toId);
                const sourcePort = sourceNode === null || sourceNode === void 0 ? void 0 : sourceNode.getPort(warning.ref.connection.fromProperty);
                const targetPort = targetNode === null || targetNode === void 0 ? void 0 : targetNode.getPort(warning.ref.connection.toProperty);
                return (external_react_default().createElement(typography_Text/* Text */.EY, null,
                    "At connection between",
                    ' ',
                    external_react_default().createElement(Label/* Label */.JU, { isInline: true, UNSAFE_style: getStyleFromNodeType(sourceNode === null || sourceNode === void 0 ? void 0 : sourceNode.type) },
                        ' ',
                        (sourceNode === null || sourceNode === void 0 ? void 0 : sourceNode.label) || 'undefined',
                        " (",
                        (sourcePort === null || sourcePort === void 0 ? void 0 : sourcePort.displayName) || 'unknown',
                        ")"),
                    ' ',
                    "and",
                    ' ',
                    external_react_default().createElement(Label/* Label */.JU, { isInline: true, UNSAFE_style: getStyleFromNodeType(targetNode === null || targetNode === void 0 ? void 0 : targetNode.type) },
                        (targetNode === null || targetNode === void 0 ? void 0 : targetNode.label) || 'undefined',
                        " (",
                        (targetPort === null || targetPort === void 0 ? void 0 : targetPort.displayName) || 'unknown',
                        ")"),
                    ' ',
                    "in ",
                    isCloudComponent && 'cloud function ',
                    "component ",
                    componentName));
            }
        }
        const message = warning.warning.message;
        let label = '';
        if (typeof message === 'string') {
            label = message.replace('<br>', ' - ');
        }
        else if (message && typeof message === 'object') {
            label = JSON.stringify(message);
        }
        return {
            icon: common_Icon/* IconName */.$M.WarningTriangle,
            label: external_react_default().createElement("span", { dangerouslySetInnerHTML: { __html: label } }),
            key: 
            // long key, just to be sure
            ((_a = warning.ref.component) === null || _a === void 0 ? void 0 : _a.id) +
                warning.warning.message +
                ((_c = (_b = warning === null || warning === void 0 ? void 0 : warning.ref) === null || _b === void 0 ? void 0 : _b.connection) === null || _c === void 0 ? void 0 : _c.fromProperty) +
                ((_e = (_d = warning === null || warning === void 0 ? void 0 : warning.ref) === null || _d === void 0 ? void 0 : _d.connection) === null || _e === void 0 ? void 0 : _e.toProperty) +
                ((_g = (_f = warning === null || warning === void 0 ? void 0 : warning.ref) === null || _f === void 0 ? void 0 : _f.node) === null || _g === void 0 ? void 0 : _g.id),
            isDangerous: true,
            endSlot: endSlot(),
            onClick: () => {
                var _a;
                return nodeGraphContext.switchToComponent(warning.ref.component, {
                    node: ((_a = warning === null || warning === void 0 ? void 0 : warning.ref) === null || _a === void 0 ? void 0 : _a.node) || undefined,
                    pushHistory: true
                });
            }
        };
    }));
}
const ourTheirsStyle = {
    backgroundColor: `var(--theme-color-bg-3)`,
    color: `var(--theme-color-fg-default)`,
    display: 'inline-block',
    padding: 2,
    borderRadius: 2,
    marginBottom: 4
};
function formatMergeConflictParamter(param) {
    return param && (typeof param === 'object' || Array.isArray(param)) ? JSON.stringify(param, null, 2) : param;
}
function MergeConflict({ warning }) {
    var _a, _b;
    const ours = (_a = warning.warning.conflictMetadata) === null || _a === void 0 ? void 0 : _a.ours;
    const theirs = (_b = warning.warning.conflictMetadata) === null || _b === void 0 ? void 0 : _b.theirs;
    return (external_react_default().createElement(Stack/* VStack */.Tk, null,
        warning.warning.type !== 'conflict-source-code' && (external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement(typography_Text/* Text */.EY, null,
                external_react_default().createElement(Label/* Label */.JU, { isInline: true, UNSAFE_style: ourTheirsStyle }, "Ours"),
                '  ',
                external_react_default().createElement(Label/* Label */.JU, { isInline: true }, formatMergeConflictParamter(ours))),
            external_react_default().createElement(typography_Text/* Text */.EY, null,
                external_react_default().createElement(Label/* Label */.JU, { isInline: true, UNSAFE_style: ourTheirsStyle }, "Theirs"),
                ' ',
                external_react_default().createElement(Label/* Label */.JU, { isInline: true }, formatMergeConflictParamter(theirs))))),
        external_react_default().createElement(Container, { hasTopSpacing: true },
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: warning.warning.type === 'conflict-source-code' ? 'Mark resolved' : 'Use mine', size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, hasRightSpacing: true, onClick: () => { var _a; return (_a = warning.warning) === null || _a === void 0 ? void 0 : _a.onDismiss(); } }),
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Use theirs", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: () => { var _a; return (_a = warning.warning) === null || _a === void 0 ? void 0 : _a.onUseTheirs(); } }))));
}

;// ./src/editor/src/views/EditorTopbar/ScreenSizes.ts

const screenSizesWithDividers = [
    {
        name: 'Fit viewport',
        group: 'Editor',
        width: null,
        height: null
    },
    'divider',
    {
        name: 'Desktop, common',
        group: 'Desktop',
        width: 1920,
        height: 1080
    },
    {
        name: 'Desktop, medium',
        group: 'Desktop small',
        width: 1366,
        height: 768
    },
    {
        name: 'Desktop, small',
        group: 'Desktop small',
        width: 1024,
        height: 768
    },
    'divider',
    {
        name: 'Tablet, large',
        group: 'Tablet',
        width: 800,
        height: 1280
    },
    {
        name: 'Tablet, common',
        group: 'Tablet',
        width: 768,
        height: 1024
    },
    {
        name: 'Tablet, small',
        group: 'Tablet',
        width: 601,
        height: 962
    },
    'divider',
    {
        name: 'Mobile, big',
        group: 'Mobile',
        width: 414,
        height: 896
    },
    {
        name: 'Mobile, common',
        group: 'Mobile',
        width: 360,
        height: 800
    },
    {
        name: 'Mobile, small',
        group: 'Mobile',
        width: 320,
        height: 568
    }
];
const screenSizes = screenSizesWithDividers.filter((item) => typeof item !== 'string');
function getIconFromScreenSizeGroupName(group) {
    switch (group) {
        case 'Desktop':
            return common_Icon/* IconName */.$M.DeviceDesktop;
        case 'Desktop small':
            return common_Icon/* IconName */.$M.DeviceLaptop;
        case 'Tablet':
            return common_Icon/* IconName */.$M.DeviceTablet;
        case 'Mobile':
            return common_Icon/* IconName */.$M.DevicePhone;
        case 'Editor':
            return common_Icon/* IconName */.$M.ViewportDiagonalArrow;
        default:
            return common_Icon/* IconName */.$M.User;
    }
}
function getScreenSizeObjectFromMeasurements(width, height) {
    const size = screenSizes.find((screen) => screen.width === width && screen.height === height);
    return size ? size : screenSizes[0];
}

;// ./src/editor/src/views/EditorTopbar/EditorTopbar.tsx


























function EditorTopbar({ instance, routes, onRouteChanged, setDocumentLayout, documentLayout, setZoomFactor, zoomFactor, previewSize, onUrlNavigateBack, onUrlNavigateForward, navigationState, onPreviewSizeChanged, previewMode, onPreviewModeChanged, nodeGraph, deployIsDisabled }) {
    var _a;
    const urlBarRef = (0,external_react_.useRef)(null);
    const deployButtonRef = (0,external_react_.useRef)(null);
    const warningButtonRef = (0,external_react_.useRef)(null);
    const urlInputRef = (0,external_react_.useRef)(null);
    const zoomLevelTrigger = (0,external_react_.useRef)(null);
    const screenSizeTrigger = (0,external_react_.useRef)(null);
    const previewLayoutTrigger = (0,external_react_.useRef)(null);
    const [isDeployVisible, setIsDeployVisible] = (0,external_react_.useState)(false);
    const [isWarningsDialogVisible, setIsWarningsDialogVisible] = (0,external_react_.useState)(false);
    const [isZoomDialogVisible, setIsZoomDialogVisible] = (0,external_react_.useState)(false);
    const [isSizeDialogVisible, setIsSizeDialogVisible] = (0,external_react_.useState)(false);
    const [isPreviewLayoutDialogVisible, setIsPreviewLayoutDialogVisible] = (0,external_react_.useState)(false);
    const triggerRerender = useTriggerRerender();
    const [isRouteListVisible, setIsRouteListVisible] = (0,external_react_.useState)(false);
    const currentScreenSize = getScreenSizeObjectFromMeasurements(previewSize.width, previewSize.height);
    const [routeTextInputValue, setRouteTextInputValue] = (0,external_react_.useState)('');
    const zoomLevelOptions = [
        {
            label: '100%',
            value: 1
        },
        {
            label: '75%',
            value: 0.75
        },
        {
            label: '50%',
            value: 0.5
        },
        {
            label: '25%',
            value: 0.25
        }
    ];
    if (previewSize.width) {
        zoomLevelOptions.unshift({
            label: 'Fit',
            value: 0
        });
    }
    (0,external_react_.useEffect)(() => {
        setRouteTextInputValue(navigationState.route);
    }, [navigationState === null || navigationState === void 0 ? void 0 : navigationState.route]);
    // Warningsmodel does not extend Model, so we get a lot of TS errors.
    // Listening to these events manually to force rerenders
    // TODO: Update WarningsModel
    (0,external_react_.useEffect)(() => {
        const eventGroup = {};
        warningsmodel/* WarningsModel */.l.instance.on('warningsChanged', () => triggerRerender(), eventGroup);
        return () => {
            warningsmodel/* WarningsModel */.l.instance.off(eventGroup);
        };
    });
    function showWarnings(e) {
        setIsWarningsDialogVisible(true);
    }
    function onAddClicked(evt) {
        evt.stopPropagation();
        const x = Math.round(Math.random() * 100 + 50);
        const y = Math.round(Math.random() * 100 + 50);
        // Put the new node at random position 50-150
        const panAndScale = nodeGraph.getPanAndScale();
        const scaledPos = {
            x: x / panAndScale.scale - panAndScale.x,
            y: y / panAndScale.scale - panAndScale.y
        };
        const createNewNodePanel = new createnewnodepanel/* CreateNewNodePanel */.F({
            attachToRoot: true,
            model: nodeGraph.model,
            pos: scaledPos,
            runtimeType: nodeGraph.runtimeType
        });
        createNewNodePanel.render();
        popuplayer_default().instance.showPopup({
            content: createNewNodePanel,
            position: 'screen-center',
            isBackgroundDimmed: true,
            onClose: () => createNewNodePanel.dispose()
        });
    }
    const rootRef = (0,external_react_.useRef)(null);
    const bounds = useTrackBounds(rootRef);
    const isSmall = (bounds === null || bounds === void 0 ? void 0 : bounds.width) < 850;
    const getActiveLayoutIcon = () => {
        switch (documentLayout) {
            case 'vertical':
                return common_Icon/* IconName */.$M.VerticalSplit;
            case 'horizontal':
                return common_Icon/* IconName */.$M.HorizontalSplit;
            default:
                return common_Icon/* IconName */.$M.Cards;
        }
    };
    useKeyboardCommands(() => [
        {
            handler: () => {
                var _a;
                (_a = urlBarRef.current) === null || _a === void 0 ? void 0 : _a.focus();
            },
            keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.KEY_L
        }
    ]);
    return (external_react_default().createElement("div", { ref: rootRef, className: external_classnames_default()(EditorTopbar_EditorTopbar_module['Root'], isSmall && EditorTopbar_EditorTopbar_module['is-small']) },
        external_react_default().createElement("div", { className: EditorTopbar_EditorTopbar_module['LeftSide'] },
            external_react_default().createElement("div", { className: EditorTopbar_EditorTopbar_module['is-padded-s'] },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Add node to graph" },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Plus, iconVariant: FeedbackType/* FeedbackType */.M.Notice, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: onAddClicked }))),
            external_react_default().createElement("div", { className: EditorTopbar_EditorTopbar_module['is-padded'] },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Navigate back" },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, icon: common_Icon/* IconName */.$M.CaretLeft, onClick: onUrlNavigateBack, isDisabled: !navigationState.canGoBack })),
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Navigate forward" },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, icon: common_Icon/* IconName */.$M.CaretRight, onClick: onUrlNavigateForward, isDisabled: !navigationState.canGoForward })),
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Refresh preview", fineType: Keybindings.REFRESH_PREVIEW.label },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Refresh, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: () => EventDispatcher.EventDispatcher.instance.emit('viewer-refresh') }))),
            external_react_default().createElement(MenuDialog.MenuDialog, { title: "Preview routes", width: MenuDialog.MenuDialogWidth.Large, isVisible: isRouteListVisible, onClose: () => setIsRouteListVisible(false), triggerRef: urlInputRef, items: routes.map((url) => ({
                    label: url,
                    isHighlighted: routes.length > 1 && navigationState.route === url,
                    onClick: () => onRouteChanged(url)
                })) }),
            external_react_default().createElement("div", { ref: urlInputRef, className: EditorTopbar_EditorTopbar_module.UrlBarWrapper },
                external_react_default().createElement(TextInput, { onRefChange: (ref) => {
                        urlBarRef.current = ref.current;
                    }, value: routeTextInputValue, onFocus: () => setIsRouteListVisible(true), onChange: (e) => {
                        setRouteTextInputValue(e.target.value);
                        setIsRouteListVisible(false);
                    }, onEnter: () => onRouteChanged(routeTextInputValue), UNSAFE_className: EditorTopbar_EditorTopbar_module.UrlBarTextInput, variant: TextInputVariant.OpaqueOnHover, slotBeforeInput: external_react_default().createElement(common_Icon/* Icon */.In, { size: common_Icon/* IconSize */.lK.Small, variant: typography_Text/* TextType */.M2.Default, icon: navigationState.route === '/' ? common_Icon/* IconName */.$M.Home : common_Icon/* IconName */.$M.File, UNSAFE_style: { marginRight: 8 } }), slotAfterInput: external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CaretDown, variant: typography_Text/* TextType */.M2.Default, UNSAFE_style: { marginTop: -2 } }) })),
            external_react_default().createElement("div", { className: EditorTopbar_EditorTopbar_module['is-padded-s'] },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Open dev tools", fineType: Keybindings.OPEN_DEVTOOLS.label },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Bug, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: () => EventDispatcher.EventDispatcher.instance.emit('viewer-open-devtools') })))),
        external_react_default().createElement("div", { className: EditorTopbar_EditorTopbar_module['RightSide'] },
            instance.warningsAmount > 0 && (external_react_default().createElement("div", { className: EditorTopbar_EditorTopbar_module['is-padded'], ref: warningButtonRef },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Show warnings" },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { id: "editortopbar-warning-button", variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, iconVariant: FeedbackType/* FeedbackType */.M.Danger, icon: common_Icon/* IconName */.$M.WarningTriangle, onClick: showWarnings, label: String(instance.warningsAmount) })))),
            external_react_default().createElement("div", { ref: screenSizeTrigger },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Preview screen size", UNSAFE_triggerClassName: EditorTopbar_EditorTopbar_module.TooltipPositioner },
                    external_react_default().createElement("div", { className: external_classnames_default()(EditorTopbar_EditorTopbar_module['ZoomSelect'], EditorTopbar_EditorTopbar_module['TopbarSelect']), onClick: () => setIsSizeDialogVisible(true) },
                        external_react_default().createElement(common_Icon/* Icon */.In, { icon: getIconFromScreenSizeGroupName(currentScreenSize.group) }),
                        external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CaretDown }))),
                external_react_default().createElement(MenuDialog.MenuDialog, { title: "Preview screen size", width: MenuDialog.MenuDialogWidth.Medium, isVisible: isSizeDialogVisible, triggerRef: screenSizeTrigger, onClose: () => setIsSizeDialogVisible(false), items: screenSizesWithDividers.map((size) => {
                        if (typeof size === 'string')
                            return size;
                        return {
                            label: size.name + (size.width ? ` (${size.width} x ${size.height})` : ''),
                            icon: getIconFromScreenSizeGroupName(size.group),
                            isHighlighted: size.width === currentScreenSize.width && size.height === currentScreenSize.height,
                            onClick: () => onPreviewSizeChanged(size.width, size.height, size.width ? size.name : null)
                        };
                    }) })),
            external_react_default().createElement("div", { ref: zoomLevelTrigger },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Preview zoom level", UNSAFE_triggerClassName: EditorTopbar_EditorTopbar_module.TooltipPositioner },
                    external_react_default().createElement("div", { className: external_classnames_default()(EditorTopbar_EditorTopbar_module['ZoomSelect'], EditorTopbar_EditorTopbar_module['TopbarSelect']), onClick: () => setIsZoomDialogVisible(true) },
                        external_react_default().createElement(Label/* Label */.JU, null, (_a = zoomLevelOptions.find((option) => option.value === zoomFactor)) === null || _a === void 0 ? void 0 : _a.label),
                        external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CaretDown }))),
                external_react_default().createElement(MenuDialog.MenuDialog, { title: "Preview zoom level", width: MenuDialog.MenuDialogWidth.Small, isVisible: isZoomDialogVisible, onClose: () => setIsZoomDialogVisible(false), triggerRef: zoomLevelTrigger, items: zoomLevelOptions.map((level) => ({
                        label: level.label,
                        isHighlighted: zoomFactor === level.value,
                        onClick: () => setZoomFactor(level.value)
                    })) })),
            isSmall && (external_react_default().createElement("div", { ref: previewLayoutTrigger },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Preview layout", UNSAFE_triggerClassName: EditorTopbar_EditorTopbar_module.TooltipPositioner },
                    external_react_default().createElement("div", { className: external_classnames_default()(EditorTopbar_EditorTopbar_module['ZoomSelect'], EditorTopbar_EditorTopbar_module['TopbarSelect']), onClick: () => setIsPreviewLayoutDialogVisible(true) },
                        external_react_default().createElement(common_Icon/* Icon */.In, { icon: getActiveLayoutIcon() }),
                        external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CaretDown }))),
                external_react_default().createElement(MenuDialog.MenuDialog, { title: "Preview layout", width: MenuDialog.MenuDialogWidth.Small, isVisible: isPreviewLayoutDialogVisible, onClose: () => setIsPreviewLayoutDialogVisible(false), triggerRef: previewLayoutTrigger, items: [
                        {
                            label: 'Vertical',
                            icon: common_Icon/* IconName */.$M.VerticalSplit,
                            isHighlighted: documentLayout === 'vertical',
                            onClick: () => setDocumentLayout('vertical')
                        },
                        {
                            label: 'Horizontal',
                            icon: common_Icon/* IconName */.$M.HorizontalSplit,
                            isHighlighted: documentLayout === 'horizontal',
                            onClick: () => setDocumentLayout('horizontal')
                        },
                        {
                            label: 'Detached',
                            icon: common_Icon/* IconName */.$M.Cards,
                            isHighlighted: documentLayout === 'detachedPreview',
                            onClick: () => {
                                setDocumentLayout('detachedPreview');
                                external_electron_.ipcRenderer.send('viewer-focus');
                            }
                        }
                    ] }))),
            !isSmall && (external_react_default().createElement("div", { className: EditorTopbar_EditorTopbar_module['is-padded'] },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Split workspace vertically" },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.VerticalSplit, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: () => setDocumentLayout('vertical'), state: documentLayout === 'vertical' ? inputs_IconButton/* IconButtonState */.Df.Active : undefined })),
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Split workspace horizontally" },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.HorizontalSplit, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: () => setDocumentLayout('horizontal'), state: documentLayout === 'horizontal' ? inputs_IconButton/* IconButtonState */.Df.Active : undefined })),
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Detach preview from editor" },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Cards, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: () => {
                            setDocumentLayout('detachedPreview');
                            external_electron_.ipcRenderer.send('viewer-focus');
                        }, state: documentLayout === 'detachedPreview' ? inputs_IconButton/* IconButtonState */.Df.Active : undefined })))),
            external_react_default().createElement("div", { className: EditorTopbar_EditorTopbar_module['is-padded-l'] },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Design mode", fineType: Keybindings.TOGGLE_PREVIEW_MODE.label, UNSAFE_triggerClassName: EditorTopbar_EditorTopbar_module.TooltipPositioner },
                    external_react_default().createElement("div", { className: EditorTopbar_EditorTopbar_module.DesignPreviewModeButton, onClick: () => onPreviewModeChanged(false) }, isSmall ? (external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Pencil, variant: !previewMode ? typography_Text/* TextType */.M2.Secondary : undefined })) : (external_react_default().createElement(Label/* Label */.JU, { variant: !previewMode ? typography_Text/* TextType */.M2.Secondary : undefined }, "Design")))),
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Set editor mode", fineType: Keybindings.TOGGLE_PREVIEW_MODE.label, UNSAFE_triggerClassName: EditorTopbar_EditorTopbar_module.TooltipPositioner },
                    external_react_default().createElement(ToggleSwitch, { isChecked: previewMode, onChange: (e) => onPreviewModeChanged(e.target.checked), isAlwaysActiveColor: true })),
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Preview mode", fineType: Keybindings.TOGGLE_PREVIEW_MODE.label, UNSAFE_triggerClassName: EditorTopbar_EditorTopbar_module.TooltipPositioner },
                    external_react_default().createElement("div", { className: EditorTopbar_EditorTopbar_module.DesignPreviewModeButton, onClick: () => onPreviewModeChanged(true) }, isSmall ? (external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.PlayCircle, variant: previewMode ? typography_Text/* TextType */.M2.Secondary : undefined })) : (external_react_default().createElement(Label/* Label */.JU, { variant: previewMode ? typography_Text/* TextType */.M2.Secondary : undefined }, "Preview"))))),
            external_react_default().createElement("span", { ref: deployButtonRef },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: isSmall ? '' : 'Deploy', icon: common_Icon/* IconName */.$M.Rocket, isDisabled: deployIsDisabled, onClick: () => setIsDeployVisible(true), UNSAFE_className: EditorTopbar_EditorTopbar_module['DeployButton'], testId: "deploy-popup-button" }))),
        external_react_default().createElement(DeployPopup, { isVisible: isDeployVisible, onClose: () => setIsDeployVisible(false), triggerRef: deployButtonRef }),
        external_react_default().createElement(MenuDialog.MenuDialog, { title: "Warnings", isVisible: isWarningsDialogVisible, onClose: () => setIsWarningsDialogVisible(false), triggerRef: warningButtonRef, items: [...returnWarningItems(instance.allWarnings, nodeGraph)], width: MenuDialog.MenuDialogWidth.Large })));
}

;// ./src/editor/src/views/EditorTopbar/index.ts


;// external "http"
const external_http_namespaceObject = require("http");
;// external "https"
const external_https_namespaceObject = require("https");
;// external "url"
const external_url_namespaceObject = require("url");
;// ../../node_modules/@algolia/requester-node-http/dist/requester.http.js
// src/createHttpRequester.ts



var agentOptions = { keepAlive: true };
var defaultHttpAgent = new external_http_namespaceObject.Agent(agentOptions);
var defaultHttpsAgent = new external_https_namespaceObject.Agent(agentOptions);
function createHttpRequester({
  agent: userGlobalAgent,
  httpAgent: userHttpAgent,
  httpsAgent: userHttpsAgent,
  requesterOptions = {}
} = {}) {
  const httpAgent = userHttpAgent || userGlobalAgent || defaultHttpAgent;
  const httpsAgent = userHttpsAgent || userGlobalAgent || defaultHttpsAgent;
  function send(request) {
    return new Promise((resolve) => {
      let responseTimeout;
      let connectTimeout;
      const url = new external_url_namespaceObject.URL(request.url);
      const path = url.search === null ? url.pathname : `${url.pathname}${url.search}`;
      const options = {
        agent: url.protocol === "https:" ? httpsAgent : httpAgent,
        hostname: url.hostname,
        path,
        method: request.method,
        ...requesterOptions,
        headers: {
          ...request.headers,
          ...requesterOptions.headers
        }
      };
      if (url.port && !requesterOptions.port) {
        options.port = url.port;
      }
      const req = (url.protocol === "https:" ? external_https_namespaceObject : external_http_namespaceObject).request(options, (response) => {
        let contentBuffers = [];
        response.on("data", (chunk) => {
          contentBuffers = contentBuffers.concat(chunk);
        });
        response.on("end", () => {
          clearTimeout(connectTimeout);
          clearTimeout(responseTimeout);
          resolve({
            status: response.statusCode || 0,
            content: Buffer.concat(contentBuffers).toString(),
            isTimedOut: false
          });
        });
      });
      const createTimeout = (timeout, content) => {
        return setTimeout(() => {
          req.destroy();
          resolve({
            status: 0,
            content,
            isTimedOut: true
          });
        }, timeout);
      };
      connectTimeout = createTimeout(request.connectTimeout, "Connection timeout");
      req.on("error", (error) => {
        clearTimeout(connectTimeout);
        clearTimeout(responseTimeout);
        resolve({ status: 0, content: error.message, isTimedOut: false });
      });
      req.once("response", () => {
        clearTimeout(connectTimeout);
        responseTimeout = createTimeout(request.responseTimeout, "Socket timeout");
      });
      if (request.data !== void 0) {
        req.write(request.data);
      }
      req.end();
    });
  }
  return { send };
}

//# sourceMappingURL=requester.http.js.map
;// ../../node_modules/@algolia/client-common/dist/common.js
// src/cache/createBrowserLocalStorageCache.ts
function createBrowserLocalStorageCache(options) {
  let storage;
  const namespaceKey = `algolia-client-js-${options.key}`;
  function getStorage() {
    if (storage === void 0) {
      storage = options.localStorage || window.localStorage;
    }
    return storage;
  }
  function getNamespace() {
    return JSON.parse(getStorage().getItem(namespaceKey) || "{}");
  }
  function setNamespace(namespace) {
    getStorage().setItem(namespaceKey, JSON.stringify(namespace));
  }
  function removeOutdatedCacheItems() {
    const timeToLive = options.timeToLive ? options.timeToLive * 1e3 : null;
    const namespace = getNamespace();
    const filteredNamespaceWithoutOldFormattedCacheItems = Object.fromEntries(
      Object.entries(namespace).filter(([, cacheItem]) => {
        return cacheItem.timestamp !== void 0;
      })
    );
    setNamespace(filteredNamespaceWithoutOldFormattedCacheItems);
    if (!timeToLive) {
      return;
    }
    const filteredNamespaceWithoutExpiredItems = Object.fromEntries(
      Object.entries(filteredNamespaceWithoutOldFormattedCacheItems).filter(([, cacheItem]) => {
        const currentTimestamp = (/* @__PURE__ */ new Date()).getTime();
        const isExpired = cacheItem.timestamp + timeToLive < currentTimestamp;
        return !isExpired;
      })
    );
    setNamespace(filteredNamespaceWithoutExpiredItems);
  }
  return {
    get(key, defaultValue, events = {
      miss: () => Promise.resolve()
    }) {
      return Promise.resolve().then(() => {
        removeOutdatedCacheItems();
        return getNamespace()[JSON.stringify(key)];
      }).then((value) => {
        return Promise.all([value ? value.value : defaultValue(), value !== void 0]);
      }).then(([value, exists]) => {
        return Promise.all([value, exists || events.miss(value)]);
      }).then(([value]) => value);
    },
    set(key, value) {
      return Promise.resolve().then(() => {
        const namespace = getNamespace();
        namespace[JSON.stringify(key)] = {
          timestamp: (/* @__PURE__ */ new Date()).getTime(),
          value
        };
        getStorage().setItem(namespaceKey, JSON.stringify(namespace));
        return value;
      });
    },
    delete(key) {
      return Promise.resolve().then(() => {
        const namespace = getNamespace();
        delete namespace[JSON.stringify(key)];
        getStorage().setItem(namespaceKey, JSON.stringify(namespace));
      });
    },
    clear() {
      return Promise.resolve().then(() => {
        getStorage().removeItem(namespaceKey);
      });
    }
  };
}

// src/cache/createNullCache.ts
function createNullCache() {
  return {
    get(_key, defaultValue, events = {
      miss: () => Promise.resolve()
    }) {
      const value = defaultValue();
      return value.then((result) => Promise.all([result, events.miss(result)])).then(([result]) => result);
    },
    set(_key, value) {
      return Promise.resolve(value);
    },
    delete(_key) {
      return Promise.resolve();
    },
    clear() {
      return Promise.resolve();
    }
  };
}

// src/cache/createFallbackableCache.ts
function createFallbackableCache(options) {
  const caches = [...options.caches];
  const current = caches.shift();
  if (current === void 0) {
    return createNullCache();
  }
  return {
    get(key, defaultValue, events = {
      miss: () => Promise.resolve()
    }) {
      return current.get(key, defaultValue, events).catch(() => {
        return createFallbackableCache({ caches }).get(key, defaultValue, events);
      });
    },
    set(key, value) {
      return current.set(key, value).catch(() => {
        return createFallbackableCache({ caches }).set(key, value);
      });
    },
    delete(key) {
      return current.delete(key).catch(() => {
        return createFallbackableCache({ caches }).delete(key);
      });
    },
    clear() {
      return current.clear().catch(() => {
        return createFallbackableCache({ caches }).clear();
      });
    }
  };
}

// src/cache/createMemoryCache.ts
function createMemoryCache(options = { serializable: true }) {
  let cache = {};
  return {
    get(key, defaultValue, events = {
      miss: () => Promise.resolve()
    }) {
      const keyAsString = JSON.stringify(key);
      if (keyAsString in cache) {
        return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
      }
      const promise = defaultValue();
      return promise.then((value) => events.miss(value)).then(() => promise);
    },
    set(key, value) {
      cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
      return Promise.resolve(value);
    },
    delete(key) {
      delete cache[JSON.stringify(key)];
      return Promise.resolve();
    },
    clear() {
      cache = {};
      return Promise.resolve();
    }
  };
}

// src/constants.ts
var DEFAULT_CONNECT_TIMEOUT_BROWSER = 1e3;
var DEFAULT_READ_TIMEOUT_BROWSER = 2e3;
var DEFAULT_WRITE_TIMEOUT_BROWSER = 3e4;
var DEFAULT_CONNECT_TIMEOUT_NODE = 2e3;
var DEFAULT_READ_TIMEOUT_NODE = 5e3;
var DEFAULT_WRITE_TIMEOUT_NODE = 3e4;

// src/createAlgoliaAgent.ts
function createAlgoliaAgent(version) {
  const algoliaAgent = {
    value: `Algolia for JavaScript (${version})`,
    add(options) {
      const addedAlgoliaAgent = `; ${options.segment}${options.version !== void 0 ? ` (${options.version})` : ""}`;
      if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
        algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
      }
      return algoliaAgent;
    }
  };
  return algoliaAgent;
}

// src/createAuth.ts
function createAuth(appId, apiKey, authMode = "WithinHeaders") {
  const credentials = {
    "x-algolia-api-key": apiKey,
    "x-algolia-application-id": appId
  };
  return {
    headers() {
      return authMode === "WithinHeaders" ? credentials : {};
    },
    queryParameters() {
      return authMode === "WithinQueryParameters" ? credentials : {};
    }
  };
}

// src/createIterablePromise.ts
function createIterablePromise({
  func,
  validate,
  aggregator,
  error,
  timeout = () => 0
}) {
  const retry = (previousResponse) => {
    return new Promise((resolve, reject) => {
      func(previousResponse).then(async (response) => {
        if (aggregator) {
          await aggregator(response);
        }
        if (await validate(response)) {
          return resolve(response);
        }
        if (error && await error.validate(response)) {
          return reject(new Error(await error.message(response)));
        }
        return setTimeout(
          () => {
            retry(response).then(resolve).catch(reject);
          },
          await timeout()
        );
      }).catch((err) => {
        reject(err);
      });
    });
  };
  return retry();
}

// src/getAlgoliaAgent.ts
function getAlgoliaAgent({ algoliaAgents, client, version }) {
  const defaultAlgoliaAgent = createAlgoliaAgent(version).add({
    segment: client,
    version
  });
  algoliaAgents.forEach((algoliaAgent) => defaultAlgoliaAgent.add(algoliaAgent));
  return defaultAlgoliaAgent;
}

// src/logger/createNullLogger.ts
function createNullLogger() {
  return {
    debug(_message, _args) {
      return Promise.resolve();
    },
    info(_message, _args) {
      return Promise.resolve();
    },
    error(_message, _args) {
      return Promise.resolve();
    }
  };
}

// src/transporter/createStatefulHost.ts
var EXPIRATION_DELAY = 2 * 60 * 1e3;
function createStatefulHost(host, status = "up") {
  const lastUpdate = Date.now();
  function isUp() {
    return status === "up" || Date.now() - lastUpdate > EXPIRATION_DELAY;
  }
  function isTimedOut() {
    return status === "timed out" && Date.now() - lastUpdate <= EXPIRATION_DELAY;
  }
  return { ...host, status, lastUpdate, isUp, isTimedOut };
}

// src/transporter/errors.ts
var AlgoliaError = class extends Error {
  name = "AlgoliaError";
  constructor(message, name) {
    super(message);
    if (name) {
      this.name = name;
    }
  }
};
var IndexNotFoundError = class extends AlgoliaError {
  constructor(indexName) {
    super(`${indexName} does not exist`, "IndexNotFoundError");
  }
};
var IndicesInSameAppError = class extends AlgoliaError {
  constructor() {
    super("Indices are in the same application. Use operationIndex instead.", "IndicesInSameAppError");
  }
};
var IndexAlreadyExistsError = class extends AlgoliaError {
  constructor(indexName) {
    super(`${indexName} index already exists.`, "IndexAlreadyExistsError");
  }
};
var ErrorWithStackTrace = class extends AlgoliaError {
  stackTrace;
  constructor(message, stackTrace, name) {
    super(message, name);
    this.stackTrace = stackTrace;
  }
};
var RetryError = class extends ErrorWithStackTrace {
  constructor(stackTrace) {
    super(
      "Unreachable hosts - your application id may be incorrect. If the error persists, please visit our help center https://alg.li/support-unreachable-hosts or reach out to the Algolia Support team: https://alg.li/support",
      stackTrace,
      "RetryError"
    );
  }
};
var ApiError = class extends ErrorWithStackTrace {
  status;
  constructor(message, status, stackTrace, name = "ApiError") {
    super(message, stackTrace, name);
    this.status = status;
  }
};
var DeserializationError = class extends AlgoliaError {
  response;
  constructor(message, response) {
    super(message, "DeserializationError");
    this.response = response;
  }
};
var DetailedApiError = class extends ApiError {
  error;
  constructor(message, status, error, stackTrace) {
    super(message, status, stackTrace, "DetailedApiError");
    this.error = error;
  }
};

// src/transporter/helpers.ts
function shuffle(array) {
  const shuffledArray = array;
  for (let c = array.length - 1; c > 0; c--) {
    const b = Math.floor(Math.random() * (c + 1));
    const a = array[c];
    shuffledArray[c] = array[b];
    shuffledArray[b] = a;
  }
  return shuffledArray;
}
function serializeUrl(host, path, queryParameters) {
  const queryParametersAsString = serializeQueryParameters(queryParameters);
  let url = `${host.protocol}://${host.url}${host.port ? `:${host.port}` : ""}/${path.charAt(0) === "/" ? path.substring(1) : path}`;
  if (queryParametersAsString.length) {
    url += `?${queryParametersAsString}`;
  }
  return url;
}
function serializeQueryParameters(parameters) {
  return Object.keys(parameters).filter((key) => parameters[key] !== void 0).sort().map(
    (key) => `${key}=${encodeURIComponent(
      Object.prototype.toString.call(parameters[key]) === "[object Array]" ? parameters[key].join(",") : parameters[key]
    ).replace(/\+/g, "%20")}`
  ).join("&");
}
function serializeData(request, requestOptions) {
  if (request.method === "GET" || request.data === void 0 && requestOptions.data === void 0) {
    return void 0;
  }
  const data = Array.isArray(request.data) ? request.data : { ...request.data, ...requestOptions.data };
  return JSON.stringify(data);
}
function serializeHeaders(baseHeaders, requestHeaders, requestOptionsHeaders) {
  const headers = {
    Accept: "application/json",
    ...baseHeaders,
    ...requestHeaders,
    ...requestOptionsHeaders
  };
  const serializedHeaders = {};
  Object.keys(headers).forEach((header) => {
    const value = headers[header];
    serializedHeaders[header.toLowerCase()] = value;
  });
  return serializedHeaders;
}
function deserializeSuccess(response) {
  try {
    return JSON.parse(response.content);
  } catch (e) {
    throw new DeserializationError(e.message, response);
  }
}
function deserializeFailure({ content, status }, stackFrame) {
  try {
    const parsed = JSON.parse(content);
    if ("error" in parsed) {
      return new DetailedApiError(parsed.message, status, parsed.error, stackFrame);
    }
    return new ApiError(parsed.message, status, stackFrame);
  } catch {
  }
  return new ApiError(content, status, stackFrame);
}

// src/transporter/responses.ts
function isNetworkError({ isTimedOut, status }) {
  return !isTimedOut && ~~status === 0;
}
function isRetryable({ isTimedOut, status }) {
  return isTimedOut || isNetworkError({ isTimedOut, status }) || ~~(status / 100) !== 2 && ~~(status / 100) !== 4;
}
function isSuccess({ status }) {
  return ~~(status / 100) === 2;
}

// src/transporter/stackTrace.ts
function stackTraceWithoutCredentials(stackTrace) {
  return stackTrace.map((stackFrame) => stackFrameWithoutCredentials(stackFrame));
}
function stackFrameWithoutCredentials(stackFrame) {
  const modifiedHeaders = stackFrame.request.headers["x-algolia-api-key"] ? { "x-algolia-api-key": "*****" } : {};
  return {
    ...stackFrame,
    request: {
      ...stackFrame.request,
      headers: {
        ...stackFrame.request.headers,
        ...modifiedHeaders
      }
    }
  };
}

// src/transporter/createTransporter.ts
function createTransporter({
  hosts,
  hostsCache,
  baseHeaders,
  logger,
  baseQueryParameters,
  algoliaAgent,
  timeouts,
  requester,
  requestsCache,
  responsesCache
}) {
  async function createRetryableOptions(compatibleHosts) {
    const statefulHosts = await Promise.all(
      compatibleHosts.map((compatibleHost) => {
        return hostsCache.get(compatibleHost, () => {
          return Promise.resolve(createStatefulHost(compatibleHost));
        });
      })
    );
    const hostsUp = statefulHosts.filter((host) => host.isUp());
    const hostsTimedOut = statefulHosts.filter((host) => host.isTimedOut());
    const hostsAvailable = [...hostsUp, ...hostsTimedOut];
    const compatibleHostsAvailable = hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
    return {
      hosts: compatibleHostsAvailable,
      getTimeout(timeoutsCount, baseTimeout) {
        const timeoutMultiplier = hostsTimedOut.length === 0 && timeoutsCount === 0 ? 1 : hostsTimedOut.length + 3 + timeoutsCount;
        return timeoutMultiplier * baseTimeout;
      }
    };
  }
  async function retryableRequest(request, requestOptions, isRead) {
    const stackTrace = [];
    const data = serializeData(request, requestOptions);
    const headers = serializeHeaders(baseHeaders, request.headers, requestOptions.headers);
    const dataQueryParameters = request.method === "GET" ? {
      ...request.data,
      ...requestOptions.data
    } : {};
    const queryParameters = {
      ...baseQueryParameters,
      ...request.queryParameters,
      ...dataQueryParameters
    };
    if (algoliaAgent.value) {
      queryParameters["x-algolia-agent"] = algoliaAgent.value;
    }
    if (requestOptions && requestOptions.queryParameters) {
      for (const key of Object.keys(requestOptions.queryParameters)) {
        if (!requestOptions.queryParameters[key] || Object.prototype.toString.call(requestOptions.queryParameters[key]) === "[object Object]") {
          queryParameters[key] = requestOptions.queryParameters[key];
        } else {
          queryParameters[key] = requestOptions.queryParameters[key].toString();
        }
      }
    }
    let timeoutsCount = 0;
    const retry = async (retryableHosts, getTimeout) => {
      const host = retryableHosts.pop();
      if (host === void 0) {
        throw new RetryError(stackTraceWithoutCredentials(stackTrace));
      }
      const timeout = { ...timeouts, ...requestOptions.timeouts };
      const payload = {
        data,
        headers,
        method: request.method,
        url: serializeUrl(host, request.path, queryParameters),
        connectTimeout: getTimeout(timeoutsCount, timeout.connect),
        responseTimeout: getTimeout(timeoutsCount, isRead ? timeout.read : timeout.write)
      };
      const pushToStackTrace = (response2) => {
        const stackFrame = {
          request: payload,
          response: response2,
          host,
          triesLeft: retryableHosts.length
        };
        stackTrace.push(stackFrame);
        return stackFrame;
      };
      const response = await requester.send(payload);
      if (isRetryable(response)) {
        const stackFrame = pushToStackTrace(response);
        if (response.isTimedOut) {
          timeoutsCount++;
        }
        logger.info("Retryable failure", stackFrameWithoutCredentials(stackFrame));
        await hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? "timed out" : "down"));
        return retry(retryableHosts, getTimeout);
      }
      if (isSuccess(response)) {
        return deserializeSuccess(response);
      }
      pushToStackTrace(response);
      throw deserializeFailure(response, stackTrace);
    };
    const compatibleHosts = hosts.filter(
      (host) => host.accept === "readWrite" || (isRead ? host.accept === "read" : host.accept === "write")
    );
    const options = await createRetryableOptions(compatibleHosts);
    return retry([...options.hosts].reverse(), options.getTimeout);
  }
  function createRequest(request, requestOptions = {}) {
    const createRetryableRequest = () => {
      return retryableRequest(request, requestOptions, isRead);
    };
    const isRead = request.useReadTransporter || request.method === "GET";
    const cacheable = requestOptions.cacheable || request.cacheable;
    if (cacheable !== true) {
      return createRetryableRequest();
    }
    const key = {
      request,
      requestOptions,
      transporter: {
        queryParameters: baseQueryParameters,
        headers: baseHeaders
      }
    };
    return responsesCache.get(
      key,
      () => {
        return requestsCache.get(
          key,
          () => (
            /**
             * Finally, if there is no request in progress with the same key,
             * this `createRetryableRequest()` will actually trigger the
             * retryable request.
             */
            requestsCache.set(key, createRetryableRequest()).then(
              (response) => Promise.all([requestsCache.delete(key), response]),
              (err) => Promise.all([requestsCache.delete(key), Promise.reject(err)])
            ).then(([_, response]) => response)
          )
        );
      },
      {
        /**
         * Of course, once we get this response back from the server, we
         * tell response cache to actually store the received response
         * to be used later.
         */
        miss: (response) => responsesCache.set(key, response)
      }
    );
  }
  return {
    hostsCache,
    requester,
    timeouts,
    logger,
    algoliaAgent,
    baseHeaders,
    baseQueryParameters,
    hosts,
    request: createRequest,
    requestsCache,
    responsesCache
  };
}

// src/types/logger.ts
var LogLevelEnum = {
  Debug: 1,
  Info: 2,
  Error: 3
};

//# sourceMappingURL=common.js.map
;// ../../node_modules/algoliasearch/dist/lite/builds/node.js
// lite/builds/node.ts



// lite/src/liteClient.ts

var apiClientVersion = "5.46.0";
function getDefaultHosts(appId) {
  return [
    {
      url: `${appId}-dsn.algolia.net`,
      accept: "read",
      protocol: "https"
    },
    {
      url: `${appId}.algolia.net`,
      accept: "write",
      protocol: "https"
    }
  ].concat(
    shuffle([
      {
        url: `${appId}-1.algolianet.com`,
        accept: "readWrite",
        protocol: "https"
      },
      {
        url: `${appId}-2.algolianet.com`,
        accept: "readWrite",
        protocol: "https"
      },
      {
        url: `${appId}-3.algolianet.com`,
        accept: "readWrite",
        protocol: "https"
      }
    ])
  );
}
function createLiteClient({
  appId: appIdOption,
  apiKey: apiKeyOption,
  authMode,
  algoliaAgents,
  ...options
}) {
  const auth = createAuth(appIdOption, apiKeyOption, authMode);
  const transporter = createTransporter({
    hosts: getDefaultHosts(appIdOption),
    ...options,
    algoliaAgent: getAlgoliaAgent({
      algoliaAgents,
      client: "Lite",
      version: apiClientVersion
    }),
    baseHeaders: {
      "content-type": "text/plain",
      ...auth.headers(),
      ...options.baseHeaders
    },
    baseQueryParameters: {
      ...auth.queryParameters(),
      ...options.baseQueryParameters
    }
  });
  return {
    transporter,
    /**
     * The `appId` currently in use.
     */
    appId: appIdOption,
    /**
     * The `apiKey` currently in use.
     */
    apiKey: apiKeyOption,
    /**
     * Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
     */
    clearCache() {
      return Promise.all([transporter.requestsCache.clear(), transporter.responsesCache.clear()]).then(() => void 0);
    },
    /**
     * Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
     */
    get _ua() {
      return transporter.algoliaAgent.value;
    },
    /**
     * Adds a `segment` to the `x-algolia-agent` sent with every requests.
     *
     * @param segment - The algolia agent (user-agent) segment to add.
     * @param version - The version of the agent.
     */
    addAlgoliaAgent(segment, version) {
      transporter.algoliaAgent.add({ segment, version });
    },
    /**
     * Helper method to switch the API key used to authenticate the requests.
     *
     * @param params - Method params.
     * @param params.apiKey - The new API Key to use.
     */
    setClientApiKey({ apiKey }) {
      if (!authMode || authMode === "WithinHeaders") {
        transporter.baseHeaders["x-algolia-api-key"] = apiKey;
      } else {
        transporter.baseQueryParameters["x-algolia-api-key"] = apiKey;
      }
    },
    /**
     * Helper: calls the `search` method but with certainty that we will only request Algolia records (hits) and not facets.
     * Disclaimer: We don't assert that the parameters you pass to this method only contains `hits` requests to prevent impacting search performances, this helper is purely for typing purposes.
     *
     * @summary Search multiple indices for `hits`.
     * @param searchMethodParams - Query requests and strategies. Results will be received in the same order as the queries.
     * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
     */
    searchForHits(searchMethodParams, requestOptions) {
      return this.search(searchMethodParams, requestOptions);
    },
    /**
     * Helper: calls the `search` method but with certainty that we will only request Algolia facets and not records (hits).
     * Disclaimer: We don't assert that the parameters you pass to this method only contains `facets` requests to prevent impacting search performances, this helper is purely for typing purposes.
     *
     * @summary Search multiple indices for `facets`.
     * @param searchMethodParams - Query requests and strategies. Results will be received in the same order as the queries.
     * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
     */
    searchForFacets(searchMethodParams, requestOptions) {
      return this.search(searchMethodParams, requestOptions);
    },
    /**
     * This method lets you send requests to the Algolia REST API.
     * @param customPost - The customPost object.
     * @param customPost.path - Path of the endpoint, for example `1/newFeature`.
     * @param customPost.parameters - Query parameters to apply to the current query.
     * @param customPost.body - Parameters to send with the custom request.
     * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
     */
    customPost({ path, parameters, body }, requestOptions) {
      if (!path) {
        throw new Error("Parameter `path` is required when calling `customPost`.");
      }
      const requestPath = "/{path}".replace("{path}", path);
      const headers = {};
      const queryParameters = parameters ? parameters : {};
      const request = {
        method: "POST",
        path: requestPath,
        queryParameters,
        headers,
        data: body ? body : {}
      };
      return transporter.request(request, requestOptions);
    },
    /**
     * Retrieves recommendations from selected AI models.
     *
     * Required API Key ACLs:
     *  - search
     * @param getRecommendationsParams - The getRecommendationsParams object.
     * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
     */
    getRecommendations(getRecommendationsParams, requestOptions) {
      if (getRecommendationsParams && Array.isArray(getRecommendationsParams)) {
        const newSignatureRequest = {
          requests: getRecommendationsParams
        };
        getRecommendationsParams = newSignatureRequest;
      }
      if (!getRecommendationsParams) {
        throw new Error("Parameter `getRecommendationsParams` is required when calling `getRecommendations`.");
      }
      if (!getRecommendationsParams.requests) {
        throw new Error("Parameter `getRecommendationsParams.requests` is required when calling `getRecommendations`.");
      }
      const requestPath = "/1/indexes/*/recommendations";
      const headers = {};
      const queryParameters = {};
      const request = {
        method: "POST",
        path: requestPath,
        queryParameters,
        headers,
        data: getRecommendationsParams,
        useReadTransporter: true,
        cacheable: true
      };
      return transporter.request(request, requestOptions);
    },
    /**
     * Sends multiple search requests to one or more indices.  This can be useful in these cases:  - Different indices for different purposes, such as, one index for products, another one for marketing content. - Multiple searches to the same index—for example, with different filters.  Use the helper `searchForHits` or `searchForFacets` to get the results in a more convenient format, if you already know the return type you want.
     *
     * Required API Key ACLs:
     *  - search
     * @param searchMethodParams - Muli-search request body. Results are returned in the same order as the requests.
     * @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
     */
    search(searchMethodParams, requestOptions) {
      if (searchMethodParams && Array.isArray(searchMethodParams)) {
        const newSignatureRequest = {
          requests: searchMethodParams.map(({ params, ...legacyRequest }) => {
            if (legacyRequest.type === "facet") {
              return {
                ...legacyRequest,
                ...params,
                type: "facet"
              };
            }
            return {
              ...legacyRequest,
              ...params,
              facet: void 0,
              maxFacetHits: void 0,
              facetQuery: void 0
            };
          })
        };
        searchMethodParams = newSignatureRequest;
      }
      if (!searchMethodParams) {
        throw new Error("Parameter `searchMethodParams` is required when calling `search`.");
      }
      if (!searchMethodParams.requests) {
        throw new Error("Parameter `searchMethodParams.requests` is required when calling `search`.");
      }
      const requestPath = "/1/indexes/*/queries";
      const headers = {};
      const queryParameters = {};
      const request = {
        method: "POST",
        path: requestPath,
        queryParameters,
        headers,
        data: searchMethodParams,
        useReadTransporter: true,
        cacheable: true
      };
      return transporter.request(request, requestOptions);
    }
  };
}

// lite/builds/node.ts
function liteClient(appId, apiKey, options) {
  if (!appId || typeof appId !== "string") {
    throw new Error("`appId` is missing.");
  }
  if (!apiKey || typeof apiKey !== "string") {
    throw new Error("`apiKey` is missing.");
  }
  return createLiteClient({
    appId,
    apiKey,
    timeouts: {
      connect: 2e3,
      read: 5e3,
      write: 3e4
    },
    logger: createNullLogger(),
    requester: createHttpRequester(),
    algoliaAgents: [{ segment: "Node.js", version: process.versions.node }],
    responsesCache: createNullCache(),
    requestsCache: createNullCache(),
    hostsCache: createMemoryCache(),
    ...options
  });
}

//# sourceMappingURL=node.js.map
;// external "react-instantsearch"
const external_react_instantsearch_namespaceObject = require("react-instantsearch");
// EXTERNAL MODULE: ../noodl-core-ui/src/components/inputs/SearchInput/index.ts + 2 modules
var SearchInput = __webpack_require__(16202);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/typography/Title/Title.tsx + 1 modules
var Title_Title = __webpack_require__(79015);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/Modal/Modal.module.scss
var Modal_module = __webpack_require__(21569);
;// ../noodl-core-ui/src/components/layout/Modal/Modal.module.scss

      
      
      
      
      
      
      
      
      

var Modal_module_options = {};

Modal_module_options.styleTagTransform = (styleTagTransform_default());
Modal_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      Modal_module_options.insert = insertBySelector_default().bind(null, "head");
    
Modal_module_options.domAPI = (styleDomAPI_default());
Modal_module_options.insertStyleElement = (insertStyleElement_default());

var Modal_module_update = injectStylesIntoStyleTag_default()(Modal_module/* default */.A, Modal_module_options);




       /* harmony default export */ const Modal_Modal_module = (Modal_module/* default */.A && Modal_module/* default */.A.locals ? Modal_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/Modal/Modal.tsx








function Modal({ children, headerSlot, hasHeaderDivider, footerSlot, hasFooterDivider, strapline, title, subtitle, isVisible, onClose, UNSAFE_className, UNSAFE_style }) {
    return (external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { hasBackdrop: true, isVisible: isVisible, onClose: onClose },
        external_react_default().createElement("div", { className: external_classnames_default()(Modal_Modal_module['Root'], isVisible && Modal_Modal_module['is-visible'], UNSAFE_className), style: UNSAFE_style, onClick: (e) => {
                e.stopPropagation();
            } },
            external_react_default().createElement("div", { className: Modal_Modal_module['CloseButtonContainer'], "data-test": "close-modal-button" },
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Close, onClick: onClose, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent })),
            external_react_default().createElement("header", { className: external_classnames_default()(Modal_Modal_module['Header'], hasHeaderDivider && Modal_Modal_module['has-divider']) },
                external_react_default().createElement("div", { className: Modal_Modal_module['TitleWrapper'] },
                    strapline && external_react_default().createElement(Title/* Title */.hE, { hasBottomSpacing: true }, strapline),
                    title && (external_react_default().createElement(Title/* Title */.hE, { size: Title_Title/* TitleSize */.uM.Large, variant: Title_Title/* TitleVariant */.Is.Highlighted, hasBottomSpacing: !!subtitle }, title)),
                    subtitle && external_react_default().createElement(Title/* Title */.hE, null, subtitle)),
                headerSlot),
            external_react_default().createElement("div", { className: Modal_Modal_module['Content'] }, children),
            footerSlot && (external_react_default().createElement("footer", { className: external_classnames_default()(Modal_Modal_module['Footer'], hasFooterDivider && Modal_Modal_module['has-divider']) }, footerSlot)))));
}
/** @deprecated No default imports */
/* harmony default export */ const Modal_Modal = (Modal);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/HelpCenter/HelpCenter.module.scss
var HelpCenter_module = __webpack_require__(96157);
;// ./src/editor/src/views/HelpCenter/HelpCenter.module.scss

      
      
      
      
      
      
      
      
      

var HelpCenter_module_options = {};

HelpCenter_module_options.styleTagTransform = (styleTagTransform_default());
HelpCenter_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      HelpCenter_module_options.insert = insertBySelector_default().bind(null, "head");
    
HelpCenter_module_options.domAPI = (styleDomAPI_default());
HelpCenter_module_options.insertStyleElement = (insertStyleElement_default());

var HelpCenter_module_update = injectStylesIntoStyleTag_default()(HelpCenter_module/* default */.A, HelpCenter_module_options);




       /* harmony default export */ const HelpCenter_HelpCenter_module = (HelpCenter_module/* default */.A && HelpCenter_module/* default */.A.locals ? HelpCenter_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/HelpCenter/HelpCenter.tsx















function HelpCenter() {
    const rootRef = (0,external_react_.useRef)(null);
    const [version] = (0,external_react_.useState)(src.platform.getVersion().slice(0, 3));
    const [isDialogVisible, setIsDialogVisible] = (0,external_react_.useState)(false);
    const [isSearchModalVisible, setIsSearchModalVisible] = (0,external_react_.useState)(false);
    const searchClient = liteClient('D29X2LNM4J', '7984d5feef068e1161527316bb9a1a4d');
    const portalRoot = document.querySelector('.help-center-layer');
    if (!portalRoot)
        return null;
    return (external_react_default().createElement(Portal/* Portal */.Z, { portalRoot: portalRoot },
        external_react_default().createElement("div", { className: HelpCenter_HelpCenter_module['Root'], ref: rootRef, onClick: () => setIsDialogVisible(true) },
            external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.QuestionFree, variant: inputs_IconButton/* IconButtonVariant */.nl.OpaqueOnHover, size: common_Icon/* IconSize */.lK.Large })),
        external_react_default().createElement(Modal_Modal, { isVisible: isSearchModalVisible, onClose: () => {
                // small hack to prevent some memory leaks when closing modal
                // while InstantSearch is still running
                // not the best solution ever, but at least its quick and dirty
                setTimeout(() => setIsSearchModalVisible(false), 100);
            }, title: "Search Help Center" },
            external_react_default().createElement(external_react_instantsearch_namespaceObject.InstantSearch, { searchClient: searchClient, indexName: "docs_2-9" },
                external_react_default().createElement(SearchView, null))),
        external_react_default().createElement(MenuDialog.MenuDialog, { triggerRef: rootRef, isVisible: isDialogVisible, onClose: () => setIsDialogVisible(false), items: [
                { label: 'Quick search docs', icon: common_Icon/* IconName */.$M.Search, onClick: () => setIsSearchModalVisible(true) },
                'divider',
                {
                    label: 'Getting started',
                    onClick: () => src.platform.openExternal(`https://docs.noodl.net/${version}/docs/getting-started/overview`)
                },
                {
                    label: 'YouTube videos',
                    onClick: () => src.platform.openExternal('https://www.youtube.com/channel/UCLkJ8XYV1J1RqrZKY-o1YWg/playlists')
                },
                {
                    label: 'Guides',
                    onClick: () => src.platform.openExternal(`https://docs.noodl.net/${version}/docs/learn`)
                },
                'divider',
                {
                    label: 'Ask the community (Discord)',
                    onClick: () => src.platform.openExternal('https://discord.com/invite/23xU2hYrSJ')
                },
                { label: 'Support forum', onClick: () => src.platform.openExternal('https://forum.noodl.net/') },
                'divider',
                {
                    label: 'Release notes',
                    onClick: () => src.platform.openExternal(`https://docs.noodl.net/${version}/whats-new/`)
                },
                { label: 'Contact support', onClick: () => src.platform.openExternal('https://www.noodl.net/support') }
            ] })));
}
function SearchView(props) {
    const { query, refine } = (0,external_react_instantsearch_namespaceObject.useSearchBox)(props);
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(SearchInput/* SearchInput */.D, { value: query, onChange: (value) => refine(value), isAutoFocus: true }),
        external_react_default().createElement(external_react_instantsearch_namespaceObject.Configure, { restrictSearchableAttributes: ['content'], attributesToRetrieve: ['content', 'hierarchy', 'url'], hitsPerPage: 10 }),
        Boolean(query) && (external_react_default().createElement("div", { className: HelpCenter_HelpCenter_module['ResultContainer'] },
            external_react_default().createElement(external_react_instantsearch_namespaceObject.Hits, { hitComponent: Hit }))),
        external_react_default().createElement("div", { className: HelpCenter_HelpCenter_module['MessageContainer'] },
            external_react_default().createElement("div", { className: HelpCenter_HelpCenter_module['Message'] },
                external_react_default().createElement(Title/* Title */.hE, { hasBottomSpacing: true, size: Title/* TitleSize */.uM.Large }, query ? "Can't find what you're looking for?" : "Don't know what you're looking for?"),
                external_react_default().createElement(Label/* Label */.JU, null, "Browse our docs or reach out on Discord"),
                external_react_default().createElement("div", { className: HelpCenter_HelpCenter_module['Buttons'] },
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Visit docs", href: "https://docs.noodl.net", hasRightSpacing: true }),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Join our Discord", href: "https://discord.com/invite/23xU2hYrSJ" }))))));
}
function Hit({ hit, sendEvent }) {
    return (external_react_default().createElement("div", { className: HelpCenter_HelpCenter_module['SearchHit'] },
        external_react_default().createElement("div", { className: HelpCenter_HelpCenter_module['HitTitle'] },
            external_react_default().createElement("div", null,
                external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Small, variant: typography_Text/* TextType */.M2.Secondary, hasBottomSpacing: true }, hit.hierarchy.lvl1),
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Large, hasBottomSpacing: true },
                    hit.hierarchy.lvl2,
                    !hit.hierarchy.lvl2 && hit.hierarchy.lvl1)),
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Read full docs", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, onClick: () => {
                    src.platform.openExternal(hit.url);
                    sendEvent('clickedObjectIDsAfterSearch', hit, 'editor-docs-search');
                } })),
        external_react_default().createElement(typography_Text/* Text */.EY, null,
            external_react_default().createElement(external_react_instantsearch_namespaceObject.Highlight, { attribute: "content", hit: hit }))));
}

;// ./src/editor/src/views/HelpCenter/index.ts


// EXTERNAL MODULE: ./src/editor/src/views/ShowContextMenuInPopup.tsx
var ShowContextMenuInPopup = __webpack_require__(28873);
// EXTERNAL MODULE: ./src/shared/view.js
var view = __webpack_require__(92207);
var view_default = /*#__PURE__*/__webpack_require__.n(view);
;// ./src/editor/src/hooks/useThrottleState.ts

const defaultOptions = {
    onChange: () => { },
    leading: false,
    trailing: true
};
function useThrottle(value, delay, options = {}) {
    const [throttledValue, setThrottledValue] = (0,external_react_.useState)(value);
    const lastExecuted = (0,external_react_.useRef)(Date.now());
    const handler = (0,external_react_.useRef)(null);
    const componentMounted = (0,external_react_.useRef)(null);
    const leadingCall = (0,external_react_.useRef)(false);
    const optionsRef = (0,external_react_.useRef)(null);
    options = Object.assign({}, defaultOptions, options);
    // Updating the options on every render, room for improvement
    (0,external_react_.useEffect)(() => {
        optionsRef.current = options;
    });
    const clearHandler = (0,external_react_.useCallback)(() => {
        if (handler.current)
            clearTimeout(handler.current);
        handler.current = null;
        leadingCall.current = false;
    }, []);
    (0,external_react_.useEffect)(() => {
        componentMounted.current = true;
        return () => {
            // on component unmount
            componentMounted.current = false;
        };
    }, []);
    (0,external_react_.useEffect)(() => {
        var _a;
        if ((_a = optionsRef.current) === null || _a === void 0 ? void 0 : _a.onChange)
            optionsRef.current.onChange(throttledValue);
    }, [throttledValue]);
    (0,external_react_.useEffect)(() => {
        if (handler.current)
            clearTimeout(handler.current);
        if (leadingCall.current) {
            leadingCall.current = false;
        }
        if (!handler.current && options.leading && !leadingCall.current) {
            setThrottledValue(value);
            leadingCall.current = true;
            lastExecuted.current = Date.now();
        }
        handler.current = setTimeout(() => {
            let shouldCallFunction = true;
            if (options.leading && leadingCall.current) {
                shouldCallFunction = false;
            }
            clearHandler();
            if (componentMounted.current && options.trailing && shouldCallFunction) {
                if (Date.now() - lastExecuted.current >= delay) {
                    setThrottledValue(value);
                    lastExecuted.current = Date.now();
                }
            }
        }, delay - (Date.now() - lastExecuted.current));
        return () => {
            if (handler.current)
                clearTimeout(handler.current);
        };
    }, [value, delay, clearHandler, options.leading, options.trailing]);
    return throttledValue;
}
function useThrottleState(initialValue, delay, options = {}) {
    const [value, setValue] = useState(initialValue);
    const throttledValue = useThrottle(value, delay, options);
    return [value, setValue, throttledValue];
}


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/VisualCanvas/VisualCanvas.module.scss
var VisualCanvas_module = __webpack_require__(51681);
;// ./src/editor/src/views/VisualCanvas/VisualCanvas.module.scss

      
      
      
      
      
      
      
      
      

var VisualCanvas_module_options = {};

VisualCanvas_module_options.styleTagTransform = (styleTagTransform_default());
VisualCanvas_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      VisualCanvas_module_options.insert = insertBySelector_default().bind(null, "head");
    
VisualCanvas_module_options.domAPI = (styleDomAPI_default());
VisualCanvas_module_options.insertStyleElement = (insertStyleElement_default());

var VisualCanvas_module_update = injectStylesIntoStyleTag_default()(VisualCanvas_module/* default */.A, VisualCanvas_module_options);




       /* harmony default export */ const VisualCanvas_VisualCanvas_module = (VisualCanvas_module/* default */.A && VisualCanvas_module/* default */.A.locals ? VisualCanvas_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/VisualCanvas/VisualCanvas.tsx








function VisualCanvas({ onWebView, deviceName, zoom }) {
    const webviewRef = (0,external_react_.useRef)(null);
    const containerRef = (0,external_react_.useRef)(null);
    const webviewBounds = useThrottle(useTrackBounds(webviewRef), 100);
    const containerBounds = useThrottle(useTrackBounds(containerRef), 100);
    const [crashed, setCrashed] = (0,external_react_.useState)(false);
    const [style, setStyle] = (0,external_react_.useState)({});
    const [showViewportSize, setShowViewportSize] = (0,external_react_.useState)(false);
    (0,external_react_.useEffect)(() => {
        onWebView(webviewRef.current);
        if (webviewRef.current) {
            webviewRef.current.addEventListener('crashed', () => {
                setCrashed(true);
            });
        }
    }, [webviewRef]);
    function restart() {
        if (webviewRef.current) {
            setCrashed(false);
            onWebView(webviewRef.current);
        }
    }
    (0,external_react_.useEffect)(() => {
        if (!webviewBounds || !containerBounds) {
            return;
        }
        if (webviewBounds.width > containerBounds.width && webviewBounds.height > containerBounds.height) {
            setStyle({});
        }
        else if (webviewBounds.width > containerBounds.width) {
            setStyle({ flexDirection: 'row', alignItems: 'center' });
        }
        else if (webviewBounds.height > containerBounds.height) {
            setStyle({ flexDirection: 'column', alignItems: 'center' });
        }
        else {
            setStyle({ alignItems: 'center', justifyContent: 'center' });
        }
    }, [webviewBounds, containerBounds]);
    (0,external_react_.useEffect)(() => {
        if (!webviewBounds) {
            return;
        }
        setShowViewportSize(true);
        const timeout = setTimeout(() => {
            setShowViewportSize(false);
        }, 2000);
        return () => {
            clearTimeout(timeout);
        };
    }, [containerBounds, webviewBounds]);
    return (external_react_default().createElement("div", { className: VisualCanvas_VisualCanvas_module.Background },
        showViewportSize && (external_react_default().createElement("div", { className: VisualCanvas_VisualCanvas_module.ViewportInfo }, `${deviceName ? deviceName + ' -' : ''} ${Math.floor(webviewBounds.width)}x${Math.floor(webviewBounds.height)}px - ${Math.floor(zoom * 100)}%`)),
        external_react_default().createElement("div", { className: VisualCanvas_VisualCanvas_module.WebviewContainer, style: style, ref: containerRef },
            external_react_default().createElement("webview", { className: VisualCanvas_VisualCanvas_module.Webview, ref: webviewRef, 
                // @ts-expect-error. Typings think this is a boolean. It's not, html attributes are strings.
                disablewebsecurity: "true", webpreferences: "allowRunningInsecureContent, enableRemoteModule" })),
        Boolean(crashed) && (external_react_default().createElement("div", { className: VisualCanvas_VisualCanvas_module.Crashed },
            external_react_default().createElement("div", { className: VisualCanvas_VisualCanvas_module.CrashedContent },
                external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Big, hasBottomSpacing: true }, "Aw, Snap!"),
                external_react_default().createElement(typography_Text/* Text */.EY, null, "Something went wrong while displaying this web page."),
                external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, label: "Try again.", onClick: restart })))))));
}

;// ./src/editor/src/views/VisualCanvas/CanvasView.ts







class CanvasView extends (view_default()) {
    constructor({ onNavigationStateChanged }) {
        super();
        this.root = null;
        this.zoomFactor = 1;
        this.inspectMode = false;
        this.viewportWidth = null;
        this.onNavigationStateChanged = (state) => {
            onNavigationStateChanged(state);
            window.noodlEditorPreviewRoute = state.route.substring(0, state.route.indexOf('?'));
            EventDispatcher.EventDispatcher.instance.emit('viewer-navigated', state.route);
        };
        this.viewportHeight = null;
        this.props = {
            onWebView: (webview) => {
                if (webview) {
                    this._setupWebview(webview);
                }
                else {
                    this.webviewDomReady = false;
                    this.webview = null;
                }
            }
        };
    }
    _setupWebview(webview) {
        this.webview = webview;
        webview.preload = src.platform.getAppPath() + 'src/assets/webview-preload-viewer.js';
        webview.addEventListener('dom-ready', async () => {
            this.webviewDomReady = true;
            const isValidSession = await this.webview.executeJavaScript(`typeof NoodlEditorInspectorAPI !== 'undefined'`);
            if (!isValidSession) {
                // TODO: When loading a page with "Path" navigation and you have a "."
                // (dot) in the URL our web server will return 404, this is technically
                // a crash, right? This can also be a file, and we have no file preview yet.
                // TODO: there are use cases for invalid sessions, such as a google auth login flow that uses redirect.
                // Let's allow it for now
                // this.webview.dispatchEvent(new Event('crashed'));
                return;
            }
            const code = `
        document.addEventListener('keydown', (e) => {
          const hasFocusedElement = document.querySelector(':focus') ? true : false;
          if (!hasFocusedElement && (e.metaKey || e.ctrlKey || e.shiftKey)) {
            NoodlEditor.keyDown({
              metaKey: e.metaKey,
              ctrlKey: e.ctrlKey,
              shiftKey: e.shiftKey,
              keyCode: e.keyCode,
              key: e.key
            });
          }
        });
      `;
            webview.executeJavaScript(code);
            this.webview.executeJavaScript(`NoodlEditorInspectorAPI.setEnabled(${this.inspectMode})`);
            if (this.selectedNodeId) {
                this.webview.executeJavaScript(`NoodlEditorHighlightAPI.selectNode('${this.selectedNodeId}')`);
            }
            this.updateViewportSize();
        });
        webview.addEventListener('load-commit', (event) => {
            if (event.isMainFrame === false) {
                return;
            }
            const protocol = process.env.ssl ? 'https://' : 'http://';
            const port = process.env.NOODLPORT || 8574;
            const urlPrefix = protocol + 'localhost:' + port;
            const route = event.url.startsWith(urlPrefix) ? event.url.substring(urlPrefix.length) : event.url;
            this.onNavigationStateChanged &&
                this.onNavigationStateChanged({ route, canGoBack: webview.canGoBack(), canGoForward: webview.canGoForward() });
        });
        this.setCurrentRoute('/');
    }
    resize() {
        this.updateViewportSize();
    }
    render() {
        const div = document.createElement('div');
        div.style.display = 'flex';
        div.style.width = '100%';
        div.style.height = '100%';
        div.style.overflow = 'hidden';
        this.el = $(div);
        // If there is an api response from the main thread, pass it along to the webview
        this._onEditorApiResponse = (event, args) => {
            this.tryWebviewCall(() => {
                this.webview.send('editor-api-response', args);
            });
        };
        external_electron_.ipcRenderer.on('editor-api-response', this._onEditorApiResponse);
        this.renderReact();
        return this.el;
    }
    renderReact() {
        if (!this.root) {
            this.root = (0,client.createRoot)(this.el[0]);
        }
        this.root.render(external_react_default().createElement(VisualCanvas, this.props));
    }
    setCurrentRoute(route) {
        const protocol = process.env.ssl ? 'https://' : 'http://';
        const port = process.env.NOODLPORT || 8574;
        this.webview.src = protocol + 'localhost:' + port + route;
        window.noodlEditorPreviewRoute = route;
        EventDispatcher.EventDispatcher.instance.emit('viewer-navigated', route);
    }
    dispose() {
        if (this.webview) {
            this.tryWebviewCall(() => {
                if (this.webview.isDevToolsOpened()) {
                    this.webview.closeDevTools();
                }
            });
        }
        if (this.root) {
            this.root.unmount();
            this.root = null;
        }
        external_electron_.ipcRenderer.off('editor-api-response', this._onEditorApiResponse);
    }
    refresh() {
        //set back to root to reset any navigation that's been done
        // const protocol = process.env.ssl ? 'https://' : 'http://';
        // const port = process.env.NOODLPORT || 8574;
        // this.webview.src = protocol + 'localhost:' + port;
        this.tryWebviewCall(() => {
            this.webview.reloadIgnoringCache();
        });
        EventDispatcher.EventDispatcher.instance.emit('viewer-refreshed');
    }
    openDevTools() {
        if (this.webview.isDevToolsOpened()) {
            this.webview.closeDevTools();
        }
        this.webview.openDevTools();
    }
    setZoomFactor(zoomFactor) {
        this.zoomFactor = zoomFactor;
        this.updateViewportSize();
    }
    navigateBack() {
        this.tryWebviewCall(() => {
            this.webview.goBack();
        });
    }
    navigateForward() {
        this.tryWebviewCall(() => {
            this.webview.goForward();
        });
    }
    setViewportSize({ width, height, deviceName }) {
        this.viewportWidth = width;
        this.viewportHeight = height;
        this.props.deviceName = deviceName;
        this.renderReact();
        this.updateViewportSize();
    }
    updateViewportSize() {
        if (!this.webview) {
            return;
        }
        const width = this.viewportWidth;
        const height = this.viewportHeight;
        if (width !== null) {
            let zoom = this.zoomFactor;
            if (!zoom) {
                const rect = this.webview.parentElement.getBoundingClientRect();
                const aspectX = rect.width / width;
                const aspectY = rect.height / height;
                const zoomFit = Math.min(aspectX, aspectY); //zoom level that maximizes the viewport
                zoom = Math.min(1, zoomFit); //cap the zoom so it can't zoom in > 1 since it'll become blurry
            }
            this.webview.style.width = Math.floor(zoom * width) + 'px';
            this.webview.style.height = Math.floor(zoom * height) + 'px';
            this.props.zoom = zoom;
            this.renderReact();
            this.tryWebviewCall(() => this.webview.executeJavaScript(`document.body.style.zoom = '${zoom}'`));
        }
        else {
            const zoom = this.zoomFactor || 1;
            this.tryWebviewCall(() => this.webview.executeJavaScript(`document.body.style.zoom = '${zoom}'`));
            this.webview.style.width = '100%';
            this.webview.style.height = '100%';
            this.props.zoom = zoom;
            this.renderReact();
        }
    }
    setInspectMode(enabled) {
        this.inspectMode = enabled;
        this.tryWebviewCall(() => {
            this.webview.executeJavaScript(`NoodlEditorInspectorAPI.setEnabled(${enabled})`);
            this.webview.executeJavaScript(`NoodlEditorHighlightAPI.selectNode(null)`);
        });
    }
    setNodeSelected(nodeId) {
        this.selectedNodeId = nodeId;
        this.tryWebviewCall(() => {
            this.webview.executeJavaScript(`NoodlEditorHighlightAPI.selectNode('${nodeId}')`);
        });
    }
    async captureThumbnail() {
        var _a;
        if (!this.webviewDomReady || !((_a = this.webview) === null || _a === void 0 ? void 0 : _a.isConnected)) {
            return null;
        }
        const nativeImage = await this.webview.capturePage();
        const size = nativeImage.getSize();
        const canvasWidth = size.width;
        const canvasHeight = size.height;
        let thumbHeight, thumbWidth;
        if (canvasWidth > canvasHeight) {
            thumbWidth = Math.round(400 * (canvasWidth / canvasHeight));
            thumbHeight = 400;
        }
        else {
            thumbWidth = 400;
            thumbHeight = Math.round(400 * (canvasHeight / canvasWidth));
        }
        const resizedImage = nativeImage.resize({
            width: thumbWidth,
            height: thumbHeight
        });
        return resizedImage;
    }
    tryWebviewCall(func) {
        if (this.webviewDomReady && this.webview.isConnected) {
            try {
                func();
            }
            catch (e) {
                if (!e.toString().includes('The WebView must be attached to the DOM')) {
                    throw e;
                }
            }
        }
    }
}

;// ./src/editor/src/views/documents/EditorDocument/hooks/UseCanvasView.ts


function useCanvasView(setNavigationState) {
    const [canvasView, setCanvasView] = (0,external_react_.useState)(null);
    function createCanvasView() {
        const cv = new CanvasView({
            onNavigationStateChanged: (state) => {
                setNavigationState(state);
            }
        });
        cv.render();
        setCanvasView(cv);
        return cv;
    }
    //Create canvas view (and support hot reload)
    (0,external_react_.useLayoutEffect)(() => {
        let cv = createCanvasView();
        if (false) // removed by dead control flow
{}
        return () => {
            cv.dispose();
        };
    }, []);
    return canvasView;
}

;// ./src/editor/src/views/documents/EditorDocument/hooks/UseCaptureThumbnails.ts



function useCaptureThumbnails(canvasView, viewerDetached) {
    (0,external_react_.useEffect)(() => {
        // Start capture interval for viewer thumbs
        const timer = setInterval(async () => {
            if (viewerDetached) {
                external_electron_.ipcRenderer.send('viewer-capture-thumb');
                external_electron_.ipcRenderer.once('viewer-capture-thumb-reply', (event, url) => {
                    projectmodel.ProjectModel.instance.setThumbnailFromDataURI(url);
                });
            }
            else {
                const thumb = await (canvasView === null || canvasView === void 0 ? void 0 : canvasView.captureThumbnail());
                if (thumb) {
                    projectmodel.ProjectModel.instance.setThumbnailFromDataURI(thumb.toDataURL());
                }
            }
        }, 20 * 1000); // Every 20 secs
        return () => {
            clearInterval(timer);
        };
    }, [canvasView, viewerDetached]);
}

;// ./src/editor/src/views/documents/EditorDocument/hooks/UseImportNodeset.ts



function useImportNodeset(nodeGraph) {
    (0,external_react_.useEffect)(() => {
        function onImportNodeset(event, data) {
            const json = data;
            const panAndScale = nodeGraph.getPanAndScale();
            const scaledPos = {
                x: 0 / panAndScale.scale - panAndScale.x,
                y: 0 / panAndScale.scale - panAndScale.y
            };
            const canvas = nodeGraph.canvas;
            const canvasWidth = canvas.width / (canvas.ratio * panAndScale.scale);
            const canvasHeight = canvas.height / (canvas.ratio * panAndScale.scale);
            nodeGraph.insertNodeSet({
                nodeset: nodegraphmodel/* NodeGraphNodeSet */.bn.fromJSON(json),
                x: scaledPos.x + canvasWidth / 2,
                y: scaledPos.y + canvasHeight / 2,
                toastMessage: 'Import'
            });
        }
        external_electron_.ipcRenderer.on('import-nodeset', onImportNodeset);
        return function () {
            external_electron_.ipcRenderer.removeListener('import-nodeset', onImportNodeset);
        };
    }, [nodeGraph]);
}

// EXTERNAL MODULE: ./src/editor/src/utils/compilation/context/pages.ts + 1 modules
var context_pages = __webpack_require__(3567);
// EXTERNAL MODULE: ./src/editor/src/utils/node-graph-traverser.ts
var node_graph_traverser = __webpack_require__(6056);
;// ./src/editor/src/views/documents/EditorDocument/hooks/UseRoutes.ts




function useRoutes(projectModel, eventDispatcher) {
    const [routes, setRoutes] = (0,external_react_.useState)([]);
    (0,external_react_.useEffect)(() => {
        async function updateRoutes() {
            const pages = await (0,context_pages/* getIndexedPages */.g)(projectModel, {
                expandPaths: async (route) => {
                    return [
                        {
                            title: route.title,
                            path: route.current.path,
                            meta: {}
                        }
                    ];
                }
            });
            const { navigationPathType } = projectModel.getSettings();
            const prefix = navigationPathType === undefined || navigationPathType === 'hash' ? '/#' : '';
            const pageRoutes = pages.map((p) => p.path);
            const routes = pageRoutes.concat(getComponentStackComponents()).map((path) => prefix + path);
            routes.sort();
            setRoutes(routes);
        }
        updateRoutes();
        const group = {};
        eventDispatcher.on(['Model.componentAdded', 'Model.componentRemoved'], updateRoutes, group);
        eventDispatcher.on('Model.parametersChanged', (event) => {
            var _a, _b, _c;
            if (((_a = event.model) === null || _a === void 0 ? void 0 : _a.typename) === 'Page' ||
                ((_b = event.model) === null || _b === void 0 ? void 0 : _b.typename) === 'Router' ||
                ((_c = event.model) === null || _c === void 0 ? void 0 : _c.typename) === 'Page Stack') {
                updateRoutes();
            }
        }, group);
        projectModel.on('settingsChanged', updateRoutes, group);
        return () => {
            eventDispatcher.off(group);
            projectModel.off(group);
        };
    }, [eventDispatcher, projectModel]);
    return routes;
}
function getComponentStackComponents() {
    const traverser = new node_graph_traverser/* NodeGraphTraverser */.r(projectmodel.ProjectModel.instance, (node) => node.typename === 'Page Stack Proxy Path', {
        traverseComponentStacks: true
    });
    const componentStacks = traverser.filter((node) => node.node.typename === 'Page Stack Proxy Path');
    const fullRoutes = componentStacks
        .map((node) => {
        const parentsAndSelf = node.parents(traverser.selector).reverse();
        parentsAndSelf.push(node);
        return ('/' +
            parentsAndSelf
                .map((n) => n.node.parameters.route)
                .filter((r) => !!r)
                .join('/'));
    })
        .filter((r) => !!r && r !== '/');
    return Array.from(new Set(fullRoutes));
}

// EXTERNAL MODULE: ./src/editor/src/models/projectmodel.utils.ts
var projectmodel_utils = __webpack_require__(72866);
;// ./src/editor/src/views/documents/EditorDocument/hooks/UseSetupNodeGraph.ts




function useSetupNodeGraph(nodeGraph) {
    //set nodegraph to a component when it's first created
    useSwitchToDefaultComponent(nodeGraph);
    //If the project is reloaded all the ComponentModels are new, so the node graph will have an old model as it's active component.
    //So we need to switch to the new version
    useSwitchToSameComponentAfterProjectReload(nodeGraph);
    //If the active component in the node graph is removed, switch to another component
    useSwitchComponentAfterActiveComponentDeleted(nodeGraph);
}
function useSwitchToDefaultComponent(nodeGraph) {
    (0,external_react_.useEffect)(() => {
        const component = (0,projectmodel_utils/* getDefaultComponent */.V)();
        nodeGraph.switchToComponent(component, { pushHistory: true });
    }, [nodeGraph]);
}
function useSwitchToSameComponentAfterProjectReload(nodeGraph) {
    (0,external_react_.useEffect)(() => {
        const eventGroup = {};
        EventDispatcher.EventDispatcher.instance.on('ProjectModel.instanceWillChange', () => {
            var _a;
            const activeComponentName = (_a = nodeGraph.activeComponent) === null || _a === void 0 ? void 0 : _a.fullName;
            if (activeComponentName) {
                const hasChangedEventGroup = {};
                EventDispatcher.EventDispatcher.instance.on('ProjectModel.instanceHasChanged', () => {
                    EventDispatcher.EventDispatcher.instance.off(hasChangedEventGroup);
                    const component = projectmodel.ProjectModel.instance.getComponentWithName(activeComponentName);
                    if (component) {
                        nodeGraph.switchToComponent(component);
                    }
                }, hasChangedEventGroup);
            }
        }, eventGroup);
        return () => EventDispatcher.EventDispatcher.instance.off(eventGroup);
    }, [nodeGraph]);
}
function useSwitchComponentAfterActiveComponentDeleted(nodeGraph) {
    const [project, setProject] = (0,external_react_.useState)(projectmodel.ProjectModel.instance);
    //Track the currently active project
    (0,external_react_.useEffect)(() => {
        const eventGroup = {};
        EventDispatcher.EventDispatcher.instance.on('ProjectModel.instanceHasChanged', () => setProject(projectmodel.ProjectModel.instance), eventGroup);
        return () => EventDispatcher.EventDispatcher.instance.off(eventGroup);
    }, []);
    (0,external_react_.useEffect)(() => {
        const eventGroup = {};
        project.on('componentRemoved', ({ model }) => {
            if (nodeGraph.activeComponent === model) {
                const component = (0,projectmodel_utils/* getDefaultComponent */.V)();
                nodeGraph.switchToComponent(component);
            }
        }, eventGroup);
        return () => {
            project.off(eventGroup);
        };
    }, [project, nodeGraph]);
}

// EXTERNAL MODULE: ./src/editor/src/views/documents/EditorDocument/titlebar.ts
var titlebar = __webpack_require__(89398);
;// ./src/editor/src/views/documents/EditorDocument/EditorDocument.tsx


























function EditorDocument() {
    const titlebarViewInstance = titlebar/* TitleBar */.c.instance;
    const { nodeGraph } = (0,NodeGraphContext.useNodeGraphContext)();
    // this never changes, so saving it in a state
    // this way it doesnt have to check for it every render
    const [isLesson] = (0,external_react_.useState)(projectmodel.ProjectModel.instance.isLesson());
    useKeyboardCommands(() => createKeyboardCommands(nodeGraph), [nodeGraph]);
    const routes = ['/'].concat(useRoutes(projectmodel.ProjectModel.instance, EventDispatcher.EventDispatcher.instance));
    const [documentLayout, setDocumentLayout] = (0,external_react_.useState)(isLesson ? 'vertical' : 'horizontal');
    const previousDocumentLayout = (0,usePrevious/* default */.A)(documentLayout);
    const [zoomFactor, setZoomFactor] = (0,external_react_.useState)(1);
    const [viewportSize, setViewportSize] = (0,external_react_.useState)({ width: null, height: null, deviceName: null });
    const [frameDividerSize, setFrameDividerSize] = (0,external_react_.useState)(undefined);
    const [enableAi, setEnableAi] = (0,external_react_.useState)(AiAssistantStore/* OpenAiStore */.q.getVersion() !== 'disabled');
    (0,external_react_.useEffect)(() => {
        const group = {};
        editorsettings/* EditorSettings */.H.instance.on('updated', () => {
            console.log('ai', AiAssistantStore/* OpenAiStore */.q.getVersion());
            setEnableAi(AiAssistantStore/* OpenAiStore */.q.getVersion() !== 'disabled');
        }, group);
        return function () {
            editorsettings/* EditorSettings */.H.instance.off(group);
        };
    }, []);
    const [selectedNodeId, setSelectedNodeId] = (0,external_react_.useState)(null); //The ID of the selected node, as highlighted by the viewer
    const [hasLoadedEditorSettings, setHasLoadedEditorSettings] = (0,external_react_.useState)(false);
    const [_forceUpdate, setForceUpdate] = (0,external_react_.useState)(0);
    const [navigationState, setNavigationState] = (0,external_react_.useState)({
        canGoBack: false,
        canGoForward: false,
        route: '/'
    });
    const [previewMode, setPreviewMode] = (0,external_react_.useState)(true);
    const viewerDetached = documentLayout === 'detachedPreview';
    const canvasView = useCanvasView(setNavigationState);
    (0,external_react_.useEffect)(() => {
        if (false) // removed by dead control flow
{}
    });
    useKeyboardCommands(() => [
        {
            handler: () => setPreviewMode((previewMode) => !previewMode),
            keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.KEY_T
        }
    ]);
    useImportNodeset(nodeGraph);
    //close detached viewer when EditorDocmument unmounts
    (0,external_react_.useEffect)(() => {
        return () => {
            external_electron_.ipcRenderer.send('viewer-attach', {});
        };
    }, []);
    (0,external_react_.useEffect)(() => {
        if (!viewportSize.width && !zoomFactor) {
            setZoomFactor(1);
        }
    }, [zoomFactor, viewportSize]);
    useSetupNodeGraph(nodeGraph);
    //track which nodes is currently selected. A hack that relies on the side panel to tell us.
    (0,external_react_.useEffect)(() => {
        const eventGroup = {};
        models_sidebar/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.nodeSelected, (nodeId) => {
            setSelectedNodeId(nodeId);
        }, eventGroup);
        models_sidebar/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.activeChanged, (activeId) => {
            const isNodePanel = activeId === 'PropertyEditor' || activeId === 'PortEditor';
            if (isNodePanel === false) {
                setSelectedNodeId(null);
            }
        }, eventGroup);
        return () => {
            models_sidebar/* SidebarModel */.s.instance.off(eventGroup);
        };
    }, [nodeGraph]);
    (0,external_react_.useEffect)(() => {
        if (viewerDetached) {
            external_electron_.ipcRenderer.send('viewer-detach', {
                zoomFactor,
                route: navigationState.route,
                viewportSize,
                inspectMode: previewMode ? false : true,
                selectedNodeId
            });
            const onViewerInspectNode = (_event, nodeId) => {
                EventDispatcher.EventDispatcher.instance.emit('inspectNodes', { nodeIds: [nodeId] });
            };
            external_electron_.ipcRenderer.on('viewer-inspect-node', onViewerInspectNode);
            return () => {
                external_electron_.ipcRenderer.off('viewer-inspect-node', onViewerInspectNode);
            };
        }
        else {
            external_electron_.ipcRenderer.send('viewer-attach', {});
        }
    }, [viewerDetached, canvasView]);
    (0,external_react_.useEffect)(() => {
        const inspectMode = previewMode ? false : true;
        external_electron_.ipcRenderer.send('viewer-set-inspect-mode', inspectMode);
        canvasView === null || canvasView === void 0 ? void 0 : canvasView.setInspectMode(inspectMode);
        if (previewMode) {
            canvasView === null || canvasView === void 0 ? void 0 : canvasView.setNodeSelected(null);
            external_electron_.ipcRenderer.send('viewer-select-node', null);
        }
    }, [previewMode, canvasView]);
    (0,external_react_.useEffect)(() => {
        if (!previewMode) {
            canvasView === null || canvasView === void 0 ? void 0 : canvasView.setNodeSelected(selectedNodeId);
            external_electron_.ipcRenderer.send('viewer-select-node', selectedNodeId);
        }
    }, [selectedNodeId, canvasView, previewMode]);
    const onRouteChanged = (0,external_react_.useCallback)((route) => {
        canvasView === null || canvasView === void 0 ? void 0 : canvasView.setCurrentRoute(route);
        external_electron_.ipcRenderer.send('viewer-set-route', route);
    }, [canvasView]);
    const onUrlNavigateBack = (0,external_react_.useCallback)(() => {
        external_electron_.ipcRenderer.send('viewer-navigate-back');
        canvasView === null || canvasView === void 0 ? void 0 : canvasView.navigateBack();
    }, [canvasView]);
    const onUrlNavigateForward = (0,external_react_.useCallback)(() => {
        external_electron_.ipcRenderer.send('viewer-navigate-forward');
        canvasView === null || canvasView === void 0 ? void 0 : canvasView.navigateForward();
    }, [canvasView]);
    const onPreviewSizeChanged = (0,external_react_.useCallback)((width, height, deviceName) => {
        setViewportSize({ width, height, deviceName });
    }, []);
    (0,external_react_.useEffect)(() => {
        external_electron_.ipcRenderer.send('viewer-set-zoom-factor', zoomFactor);
        canvasView === null || canvasView === void 0 ? void 0 : canvasView.setZoomFactor(zoomFactor);
    }, [zoomFactor, canvasView]);
    (0,external_react_.useEffect)(() => {
        canvasView === null || canvasView === void 0 ? void 0 : canvasView.setViewportSize(viewportSize);
        external_electron_.ipcRenderer.send('viewer-set-viewport-size', viewportSize);
    }, [viewportSize, canvasView]);
    (0,external_react_.useEffect)(() => {
        const eventGroup = {};
        if (documentLayout === 'detachedPreview') {
            EventDispatcher.EventDispatcher.instance.on('viewer-closed', () => {
                setDocumentLayout(previousDocumentLayout || 'horizontal');
            }, eventGroup);
        }
        EventDispatcher.EventDispatcher.instance.on('viewer-open-devtools', () => {
            if (documentLayout === 'detachedPreview') {
                external_electron_.ipcRenderer.send('viewer-open-devtools');
            }
            else {
                canvasView === null || canvasView === void 0 ? void 0 : canvasView.openDevTools();
            }
        }, eventGroup);
        EventDispatcher.EventDispatcher.instance.on('viewer-refresh', () => canvasView === null || canvasView === void 0 ? void 0 : canvasView.refresh(), eventGroup);
        //refresh viewer when cloud services are changed
        projectmodel.ProjectModel.instance.on('cloudServicesChanged', () => {
            EventDispatcher.EventDispatcher.instance.notifyListeners('viewer-refresh');
        }, eventGroup);
        //this is sent by viewers in design mode, and lessons
        EventDispatcher.EventDispatcher.instance.on('inspectNodes', (args) => {
            if (args.nodeIds.length === 1) {
                // Select node
                const node = projectmodel.ProjectModel.instance.findNodeWithId(args.nodeIds[0]);
                // Did we find a node that belongs to a component
                if (node && node.owner && node.owner.owner) {
                    const component = node.owner.owner;
                    nodeGraph.switchToComponent(component, { node: node, pushHistory: true });
                }
            }
            else {
                const nodes = args.nodeIds.map((id) => projectmodel.ProjectModel.instance.findNodeWithId(id)).filter((node) => !!node);
                const components = [nodes[0]];
                for (let i = 1; i < nodes.length; i++) {
                    if (components[components.length - 1].owner.owner !== nodes[i].owner.owner) {
                        components.push(nodes[i]);
                    }
                }
                if (documentLayout === 'detachedPreview') {
                    external_electron_.ipcRenderer.send('viewer-show-inspect-menu', components.map((node) => ({
                        label: node.owner.owner.name + ' - ' + node.label,
                        nodeId: node.id
                    })));
                }
                else {
                    const items = components.map((node) => ({
                        label: node.owner.owner.name + ' - ' + node.label,
                        onClick: () => {
                            const component = node.owner.owner;
                            nodeGraph.switchToComponent(component, { node: node, pushHistory: true });
                        }
                    }));
                    (0,ShowContextMenuInPopup.showContextMenuInPopup)({ title: 'Nodes behind cursor', items, width: MenuDialog.MenuDialogWidth.Large });
                }
            }
        }, eventGroup);
        //used by lessons
        EventDispatcher.EventDispatcher.instance.on('setPreviewRoute', (args) => {
            onRouteChanged(args.url);
        }, eventGroup);
        EventDispatcher.EventDispatcher.instance.on('selectComponent', (args) => {
            const component = projectmodel.ProjectModel.instance.getComponentWithName(args.componentName);
            if (component) {
                nodeGraph.switchToComponent(component, { pushHistory: true });
            }
        }, eventGroup);
        return () => {
            EventDispatcher.EventDispatcher.instance.off(eventGroup);
            projectmodel.ProjectModel.instance.off(projectmodel.ProjectModel);
        };
    }, [documentLayout, canvasView, previewMode, nodeGraph]);
    (0,external_react_.useEffect)(() => {
        const onViewerNavigationState = (event, state) => {
            setNavigationState(state);
            //make sure canvas view is updated as well so the route matches if layout is changed
            canvasView === null || canvasView === void 0 ? void 0 : canvasView.setCurrentRoute(state.route);
        };
        external_electron_.ipcRenderer.on('viewer-navigation-state', onViewerNavigationState);
        return () => {
            external_electron_.ipcRenderer.off('viewer-navigation-state', onViewerNavigationState);
        };
    }, [canvasView]);
    // Save settings
    (0,external_react_.useEffect)(() => {
        if (!hasLoadedEditorSettings) {
            return;
        }
        editorsettings/* EditorSettings */.H.instance.setMerge(projectmodel.ProjectModel.instance.id, {
            documentLayout,
            viewportSize,
            frameDividerSize,
            previewMode
        });
        const eventGroup = {};
        nodeGraph.on('activeComponentChanged', ({ model }) => editorsettings/* EditorSettings */.H.instance.setMerge(projectmodel.ProjectModel.instance.id, { selectedComponentName: model.fullName }), eventGroup);
        return () => {
            nodeGraph.off(eventGroup);
        };
    }, [hasLoadedEditorSettings, documentLayout, viewportSize, frameDividerSize, previewMode, nodeGraph]);
    // Apply settings
    (0,external_react_.useEffect)(() => {
        setHasLoadedEditorSettings(true);
        const settings = editorsettings/* EditorSettings */.H.instance.get(projectmodel.ProjectModel.instance.id);
        if (!settings) {
            return;
        }
        if (settings.documentLayout) {
            setDocumentLayout(settings.documentLayout);
        }
        if (settings.viewportSize) {
            setViewportSize(settings.viewportSize);
        }
        if (settings.frameDividerSize) {
            setFrameDividerSize(settings.frameDividerSize);
        }
        // setEnableAi(settings[AI_ASSISTANT_ENABLED_KEY]);
        if (settings.selectedComponentName) {
            const component = projectmodel.ProjectModel.instance.getComponentWithName(settings.selectedComponentName);
            if (component) {
                nodeGraph.switchToComponent(component, { replaceHistory: true });
            }
        }
        setPreviewMode(settings.previewMode ? true : false);
    }, [nodeGraph]);
    // useEffect(() => {
    //   const func = () => {
    //     setEnableAi(!!EditorSettings.instance.get(AI_ASSISTANT_ENABLED_KEY));
    //   };
    //
    //   func();
    //
    //   EditorSettings.instance.on('updated', func, group);
    //   return function () {
    //     EditorSettings.instance.off(group);
    //   };
    // }, []);
    useCaptureThumbnails(canvasView, viewerDetached);
    return (external_react_default().createElement(Container, { direction: ContainerDirection.Vertical, isFill: true },
        external_react_default().createElement(EditorTopbar, { instance: titlebarViewInstance, routes: routes, onRouteChanged: onRouteChanged, setDocumentLayout: setDocumentLayout, documentLayout: documentLayout, zoomFactor: zoomFactor, setZoomFactor: setZoomFactor, onUrlNavigateBack: onUrlNavigateBack, onUrlNavigateForward: onUrlNavigateForward, navigationState: navigationState, onPreviewSizeChanged: onPreviewSizeChanged, previewSize: viewportSize, onPreviewModeChanged: setPreviewMode, previewMode: previewMode, nodeGraph: nodeGraph, deployIsDisabled: projectmodel.ProjectModel.instance.isLesson() }),
        hasLoadedEditorSettings && (external_react_default().createElement(ViewComponent, { documentLayout: documentLayout, canvasViewInstance: canvasView, nodeGraphEditorInstance: nodeGraph, frameDividerSize: frameDividerSize, onSizeUpdated: (size) => {
                setFrameDividerSize(size);
            } })),
        external_react_default().createElement(HelpCenter, null),
        enableAi && external_react_default().createElement(Clippy, null)));
}
function ViewComponent({ canvasViewInstance, documentLayout, nodeGraphEditorInstance, onSizeUpdated, frameDividerSize }) {
    const [frameBounds, setFrameBounds] = (0,external_react_.useState)(undefined);
    const horizontal = documentLayout === 'horizontal';
    const totalSize = frameBounds ? (horizontal ? frameBounds.height : frameBounds.width) : undefined;
    if (documentLayout === 'detachedPreview') {
        return external_react_default().createElement(Frame, { instance: nodeGraphEditorInstance, onResize: (bounds) => nodeGraphEditorInstance.resize(bounds) });
    }
    else {
        const firstInstance = horizontal ? canvasViewInstance : nodeGraphEditorInstance;
        const secondInstance = horizontal ? nodeGraphEditorInstance : canvasViewInstance;
        return (external_react_default().createElement(FrameDivider, { splitOwner: horizontal ? FrameDividerOwner.First : FrameDividerOwner.Second, horizontal: !horizontal, first: external_react_default().createElement(Frame, { instance: firstInstance, onResize: (bounds) => firstInstance.resize(bounds) }), second: external_react_default().createElement(Frame, { instance: secondInstance, onResize: (bounds) => secondInstance.resize(bounds) }), sizeMin: 100, sizeMax: totalSize ? totalSize - 100 : undefined, size: frameDividerSize, onSizeChanged: (size) => {
                onSizeUpdated(size);
            }, onBoundsChanged: setFrameBounds }));
    }
}
function createKeyboardCommands(nodeGraph) {
    const copy = {
        handler: () => nodeGraph.copy(),
        keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.KEY_C
    };
    const paste = {
        handler: () => nodeGraph.paste(),
        keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.KEY_V
    };
    const cut = {
        handler: () => nodeGraph.cut(),
        keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.KEY_X
    };
    const undo = {
        handler: () => nodeGraph.undo(),
        keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.KEY_Z
    };
    const redo = {
        handler: () => nodeGraph.redo(),
        keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyMod.Shift | KeyCode.KeyCode.KEY_Z
    };
    const navBack = {
        handler: () => nodeGraph.navigationHistory.goBack(),
        keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.US_OPEN_SQUARE_BRACKET
    };
    const navForward = {
        handler: () => nodeGraph.navigationHistory.goForward(),
        keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.US_CLOSE_SQUARE_BRACKET
    };
    const deleteWithBackspace = {
        handler: () => nodeGraph.delete(),
        keybinding: KeyCode.KeyCode.Backspace
    };
    const deleteWithDel = {
        handler: () => nodeGraph.delete(),
        keybinding: KeyCode.KeyCode.Delete
    };
    const createComment = {
        handler: () => nodeGraph.activeComponent.graph.commentsModel.addComment({
            text: '',
            fill: true,
            width: 150,
            height: 100,
            x: nodeGraph.latestMousePos.x,
            y: nodeGraph.latestMousePos.y
        }, { undo: true, label: 'add comment', focusComment: true }),
        keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.US_SLASH
    };
    return [copy, paste, cut, undo, redo, navBack, navForward, deleteWithBackspace, deleteWithDel, createComment];
}
class EditorDocumentProvider {
    getComponent() {
        // React Component of the editor view (canvas, and node graph)
        return EditorDocument;
    }
}
EditorDocumentProvider.ID = 'EditorDocumentProvider';

;// ./src/editor/src/views/documents/EditorDocument/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/documents/ComponentDiffDocument/ComponentDiffTopbar/ComponentDiffTopbar.module.scss
var ComponentDiffTopbar_module = __webpack_require__(79486);
;// ./src/editor/src/views/documents/ComponentDiffDocument/ComponentDiffTopbar/ComponentDiffTopbar.module.scss

      
      
      
      
      
      
      
      
      

var ComponentDiffTopbar_module_options = {};

ComponentDiffTopbar_module_options.styleTagTransform = (styleTagTransform_default());
ComponentDiffTopbar_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ComponentDiffTopbar_module_options.insert = insertBySelector_default().bind(null, "head");
    
ComponentDiffTopbar_module_options.domAPI = (styleDomAPI_default());
ComponentDiffTopbar_module_options.insertStyleElement = (insertStyleElement_default());

var ComponentDiffTopbar_module_update = injectStylesIntoStyleTag_default()(ComponentDiffTopbar_module/* default */.A, ComponentDiffTopbar_module_options);




       /* harmony default export */ const ComponentDiffTopbar_ComponentDiffTopbar_module = (ComponentDiffTopbar_module/* default */.A && ComponentDiffTopbar_module/* default */.A.locals ? ComponentDiffTopbar_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/documents/ComponentDiffDocument/ComponentDiffTopbar/ComponentDiffTopbar.tsx






function ComponentDiffTopbar({ title }) {
    return (external_react_default().createElement("div", { className: ComponentDiffTopbar_ComponentDiffTopbar_module.Root },
        external_react_default().createElement(Label/* Label */.JU, { hasLeftSpacing: true }, title),
        external_react_default().createElement("div", { style: { marginLeft: 'auto' } },
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Exit", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, onClick: () => {
                    AppRegistry.instance.openDocument(EditorDocumentProvider.ID);
                } }))));
}

;// ./src/editor/src/views/documents/ComponentDiffDocument/ComponentDiffDocument.tsx







function ComponentDiffDocument({ component, title }) {
    const [nodeGraph] = (0,external_react_.useState)(() => {
        const ng = new nodegrapheditor/* NodeGraphEditor */._({});
        ng.setReadOnly(true);
        ng.render();
        return ng;
    });
    const [codeDiff, setCodeDiff] = (0,external_react_.useState)(null);
    (0,external_react_.useEffect)(() => {
        const eventGroup = {};
        nodeGraph.on('readOnlyNodeClicked', (node) => {
            var _a;
            if (!node.annotation) {
                return;
            }
            const port = node.getPorts('input').find((port) => !!port.type.codeeditor);
            if (port && node.parameters[port.name]) {
                const theirs = node.parameters[port.name];
                const ours = (_a = node.diffData) === null || _a === void 0 ? void 0 : _a.parent.parameters[port.name];
                if (ours !== theirs) {
                    setCodeDiff({
                        kind: diff_data/* DiffType */.s.Text,
                        original: ours,
                        modified: theirs
                    });
                }
            }
            else {
                const theirs = JSON.stringify(node.parameters, null, 2);
                const ours = node.diffData ? JSON.stringify(node.diffData.parent.parameters, null, 2) : undefined;
                if (ours !== theirs) {
                    setCodeDiff({
                        kind: diff_data/* DiffType */.s.Text,
                        original: ours,
                        modified: theirs
                    });
                }
            }
        });
        return () => {
            nodeGraph.off(eventGroup);
            nodeGraph.dispose();
        };
    }, []);
    (0,external_react_.useEffect)(() => {
        nodeGraph.switchToComponent(component);
    }, [component]);
    return (external_react_default().createElement(Container, { direction: ContainerDirection.Vertical, isFill: true },
        external_react_default().createElement(CodeDiffDialog, { onClose: () => setCodeDiff(null), diff: codeDiff }),
        external_react_default().createElement(ComponentDiffTopbar, { title: title }),
        external_react_default().createElement(Frame, { instance: nodeGraph, onResize: (bounds) => {
                nodeGraph.resize(bounds);
            } })));
}
class ComponentDiffDocumentProvider {
    getComponent() {
        return ComponentDiffDocument;
    }
}
ComponentDiffDocumentProvider.ID = 'ComponentDiffDocumentProvider';

;// ./src/editor/src/views/documents/ComponentDiffDocument/index.ts


// EXTERNAL MODULE: ./src/editor/src/hooks/useEventListener.ts
var useEventListener = __webpack_require__(76750);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/sidebar/PanelHeader/PanelHeader.module.scss
var PanelHeader_module = __webpack_require__(30149);
;// ../noodl-core-ui/src/components/sidebar/PanelHeader/PanelHeader.module.scss

      
      
      
      
      
      
      
      
      

var PanelHeader_module_options = {};

PanelHeader_module_options.styleTagTransform = (styleTagTransform_default());
PanelHeader_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      PanelHeader_module_options.insert = insertBySelector_default().bind(null, "head");
    
PanelHeader_module_options.domAPI = (styleDomAPI_default());
PanelHeader_module_options.insertStyleElement = (insertStyleElement_default());

var PanelHeader_module_update = injectStylesIntoStyleTag_default()(PanelHeader_module/* default */.A, PanelHeader_module_options);




       /* harmony default export */ const PanelHeader_PanelHeader_module = (PanelHeader_module/* default */.A && PanelHeader_module/* default */.A.locals ? PanelHeader_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/sidebar/PanelHeader/PanelHeader.tsx




function PanelHeader({ title, hasNoHeaderDivider, children, UNSAFE_className, UNSAFE_style }) {
    return (external_react_default().createElement("div", { className: external_classnames_default()(PanelHeader_PanelHeader_module['Root'], hasNoHeaderDivider && PanelHeader_PanelHeader_module._hasNoHeaderDivider, UNSAFE_className), style: UNSAFE_style },
        external_react_default().createElement("div", { className: PanelHeader_PanelHeader_module['Title'] },
            external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Big }, title)),
        external_react_default().createElement("div", { className: PanelHeader_PanelHeader_module['Children'] }, children)));
}

;// ../noodl-core-ui/src/components/sidebar/PanelHeader/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/sidebar/BasePanel/BasePanel.module.scss
var BasePanel_module = __webpack_require__(86521);
;// ../noodl-core-ui/src/components/sidebar/BasePanel/BasePanel.module.scss

      
      
      
      
      
      
      
      
      

var BasePanel_module_options = {};

BasePanel_module_options.styleTagTransform = (styleTagTransform_default());
BasePanel_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      BasePanel_module_options.insert = insertBySelector_default().bind(null, "head");
    
BasePanel_module_options.domAPI = (styleDomAPI_default());
BasePanel_module_options.insertStyleElement = (insertStyleElement_default());

var BasePanel_module_update = injectStylesIntoStyleTag_default()(BasePanel_module/* default */.A, BasePanel_module_options);




       /* harmony default export */ const BasePanel_BasePanel_module = (BasePanel_module/* default */.A && BasePanel_module/* default */.A.locals ? BasePanel_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/sidebar/BasePanel/BasePanel.tsx





function BasePanel({ title, hasActivityBlocker, hasContentScroll, hasNoHeaderDivider, isFill, headerSlot, footerSlot, children, UNSAFE_className, UNSAFE_style, UNSAFE_content_style }) {
    return (external_react_default().createElement("div", { className: external_classnames_default()(BasePanel_BasePanel_module['Root'], UNSAFE_className), style: UNSAFE_style },
        Boolean(title) && (external_react_default().createElement(PanelHeader, { hasNoHeaderDivider: hasNoHeaderDivider, title: title }, headerSlot)),
        external_react_default().createElement("div", { className: BasePanel_BasePanel_module['Inner'] },
            external_react_default().createElement("div", { className: external_classnames_default()(BasePanel_BasePanel_module['ChildrenContainer'], hasContentScroll && BasePanel_BasePanel_module['has-content-scroll'], isFill && BasePanel_BasePanel_module['is-fill']), style: UNSAFE_content_style }, children),
            footerSlot && external_react_default().createElement("div", { className: BasePanel_BasePanel_module['Footer'] }, footerSlot)),
        hasActivityBlocker && external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, { isOverlay: true })));
}

;// ../noodl-core-ui/src/components/sidebar/BasePanel/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelTextInput/index.ts + 1 modules
var PropertyPanelTextInput = __webpack_require__(55506);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/sidebar/CollapsableSection/index.ts + 2 modules
var CollapsableSection = __webpack_require__(11603);
;// ./src/editor/src/views/panels/AppSetupPanel/sections/IdentitySection.tsx



function IdentitySection({ identity, onChange }) {
    // Local state for immediate textarea updates
    const [localDescription, setLocalDescription] = (0,external_react_.useState)(identity.description || '');
    // Sync local state when external identity changes
    (0,external_react_.useEffect)(() => {
        setLocalDescription(identity.description || '');
    }, [identity.description]);
    return (external_react_default().createElement(CollapsableSection/* CollapsableSection */.M, { title: "App Identity", hasGutter: true, hasVisibleOverflow: true },
        external_react_default().createElement("div", { style: { marginBottom: '12px' } },
            external_react_default().createElement("label", { style: {
                    display: 'block',
                    fontSize: '12px',
                    fontWeight: 500,
                    marginBottom: '4px',
                    color: 'var(--theme-color-fg-default)'
                } }, "App Name"),
            external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: identity.appName || '', onChange: (value) => onChange({ appName: value }) })),
        external_react_default().createElement("div", { style: { marginBottom: '12px' } },
            external_react_default().createElement("label", { style: {
                    display: 'block',
                    fontSize: '12px',
                    fontWeight: 500,
                    marginBottom: '4px',
                    color: 'var(--theme-color-fg-default)'
                } }, "Description"),
            external_react_default().createElement("textarea", { value: localDescription, onChange: (e) => {
                    setLocalDescription(e.target.value);
                    onChange({ description: e.target.value });
                }, placeholder: "Describe your app...", rows: 3, style: {
                    width: '100%',
                    padding: '8px',
                    fontSize: '13px',
                    fontFamily: 'inherit',
                    backgroundColor: 'var(--theme-color-bg-3)',
                    border: '1px solid var(--theme-color-border-default)',
                    borderRadius: '4px',
                    color: 'var(--theme-color-fg-default)',
                    resize: 'vertical'
                } })),
        external_react_default().createElement("div", { style: { marginBottom: '12px' } },
            external_react_default().createElement("label", { style: {
                    display: 'block',
                    fontSize: '12px',
                    fontWeight: 500,
                    marginBottom: '4px',
                    color: 'var(--theme-color-fg-default)'
                } }, "Cover Image"),
            external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: identity.coverImage || '', onChange: (value) => onChange({ coverImage: value }) }),
            external_react_default().createElement("div", { style: {
                    fontSize: '11px',
                    color: 'var(--theme-color-fg-muted)',
                    marginTop: '4px'
                } }, "Path to cover image in project"))));
}

;// ./src/editor/src/views/panels/AppSetupPanel/sections/PWASection.tsx



const DISPLAY_MODES = [
    { value: 'standalone', label: 'Standalone (Recommended)' },
    { value: 'fullscreen', label: 'Fullscreen' },
    { value: 'minimal-ui', label: 'Minimal UI' },
    { value: 'browser', label: 'Browser' }
];
function PWASection({ pwa, onChange }) {
    // Local state for immediate UI updates
    const [localEnabled, setLocalEnabled] = (0,external_react_.useState)((pwa === null || pwa === void 0 ? void 0 : pwa.enabled) || false);
    const [localDisplay, setLocalDisplay] = (0,external_react_.useState)((pwa === null || pwa === void 0 ? void 0 : pwa.display) || 'standalone');
    const [localBgColor, setLocalBgColor] = (0,external_react_.useState)((pwa === null || pwa === void 0 ? void 0 : pwa.backgroundColor) || '#ffffff');
    // Sync local state when external pwa changes
    (0,external_react_.useEffect)(() => {
        setLocalEnabled((pwa === null || pwa === void 0 ? void 0 : pwa.enabled) || false);
    }, [pwa === null || pwa === void 0 ? void 0 : pwa.enabled]);
    (0,external_react_.useEffect)(() => {
        setLocalDisplay((pwa === null || pwa === void 0 ? void 0 : pwa.display) || 'standalone');
    }, [pwa === null || pwa === void 0 ? void 0 : pwa.display]);
    (0,external_react_.useEffect)(() => {
        setLocalBgColor((pwa === null || pwa === void 0 ? void 0 : pwa.backgroundColor) || '#ffffff');
    }, [pwa === null || pwa === void 0 ? void 0 : pwa.backgroundColor]);
    const handleToggle = () => {
        if (!localEnabled) {
            // Enable with defaults
            setLocalEnabled(true); // Immediate UI update
            onChange({
                enabled: true,
                startUrl: '/',
                display: 'standalone'
            });
        }
        else {
            // Disable
            setLocalEnabled(false); // Immediate UI update
            onChange({ enabled: false });
        }
    };
    return (external_react_default().createElement(CollapsableSection/* CollapsableSection */.M, { title: "Progressive Web App", hasGutter: true, hasVisibleOverflow: true, hasTopDivider: true },
        external_react_default().createElement("div", { style: { marginBottom: '16px' } },
            external_react_default().createElement("label", { style: {
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px',
                    cursor: 'pointer',
                    fontSize: '13px',
                    fontWeight: 500,
                    color: 'var(--theme-color-fg-default)'
                } },
                external_react_default().createElement("input", { type: "checkbox", checked: localEnabled, onChange: handleToggle, style: {
                        width: '16px',
                        height: '16px',
                        cursor: 'pointer'
                    } }),
                "Enable Progressive Web App"),
            external_react_default().createElement("div", { style: {
                    fontSize: '11px',
                    color: 'var(--theme-color-fg-muted)',
                    marginTop: '4px',
                    marginLeft: '24px'
                } }, "Allow users to install your app on their device")),
        localEnabled && (external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement("div", { style: { marginBottom: '12px' } },
                external_react_default().createElement("label", { style: {
                        display: 'block',
                        fontSize: '12px',
                        fontWeight: 500,
                        marginBottom: '4px',
                        color: 'var(--theme-color-fg-default)'
                    } }, "Short Name"),
                external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: (pwa === null || pwa === void 0 ? void 0 : pwa.shortName) || '', onChange: (value) => onChange({ shortName: value }) }),
                external_react_default().createElement("div", { style: {
                        fontSize: '11px',
                        color: 'var(--theme-color-fg-muted)',
                        marginTop: '4px'
                    } }, "Name shown on home screen (12 chars max recommended)")),
            external_react_default().createElement("div", { style: { marginBottom: '12px' } },
                external_react_default().createElement("label", { style: {
                        display: 'block',
                        fontSize: '12px',
                        fontWeight: 500,
                        marginBottom: '4px',
                        color: 'var(--theme-color-fg-default)'
                    } }, "Start URL"),
                external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: (pwa === null || pwa === void 0 ? void 0 : pwa.startUrl) || '/', onChange: (value) => onChange({ startUrl: value || '/' }) }),
                external_react_default().createElement("div", { style: {
                        fontSize: '11px',
                        color: 'var(--theme-color-fg-muted)',
                        marginTop: '4px'
                    } }, "URL the app opens to (default: /)")),
            external_react_default().createElement("div", { style: { marginBottom: '12px' } },
                external_react_default().createElement("label", { style: {
                        display: 'block',
                        fontSize: '12px',
                        fontWeight: 500,
                        marginBottom: '4px',
                        color: 'var(--theme-color-fg-default)'
                    } }, "Display Mode"),
                external_react_default().createElement("select", { value: localDisplay, onChange: (e) => {
                        const newValue = e.target.value;
                        setLocalDisplay(newValue);
                        onChange({ display: newValue });
                    }, style: {
                        width: '100%',
                        padding: '8px',
                        fontSize: '13px',
                        fontFamily: 'inherit',
                        backgroundColor: 'var(--theme-color-bg-3)',
                        border: '1px solid var(--theme-color-border-default)',
                        borderRadius: '4px',
                        color: 'var(--theme-color-fg-default)',
                        cursor: 'pointer'
                    } }, DISPLAY_MODES.map((mode) => (external_react_default().createElement("option", { key: mode.value, value: mode.value }, mode.label)))),
                external_react_default().createElement("div", { style: {
                        fontSize: '11px',
                        color: 'var(--theme-color-fg-muted)',
                        marginTop: '4px'
                    } }, "How the app appears when launched")),
            external_react_default().createElement("div", { style: { marginBottom: '12px' } },
                external_react_default().createElement("label", { style: {
                        display: 'block',
                        fontSize: '12px',
                        fontWeight: 500,
                        marginBottom: '4px',
                        color: 'var(--theme-color-fg-default)'
                    } }, "Background Color"),
                external_react_default().createElement("div", { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
                    external_react_default().createElement("input", { type: "color", value: localBgColor, onChange: (e) => {
                            setLocalBgColor(e.target.value);
                            onChange({ backgroundColor: e.target.value });
                        }, style: {
                            width: '40px',
                            height: '32px',
                            border: '1px solid var(--theme-color-border-default)',
                            borderRadius: '4px',
                            cursor: 'pointer',
                            backgroundColor: 'transparent'
                        } }),
                    external_react_default().createElement("div", { style: { flex: 1 } },
                        external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: localBgColor, onChange: (value) => {
                                setLocalBgColor(value);
                                onChange({ backgroundColor: value });
                            } }))),
                external_react_default().createElement("div", { style: {
                        fontSize: '11px',
                        color: 'var(--theme-color-fg-muted)',
                        marginTop: '4px'
                    } }, "Splash screen background color")),
            external_react_default().createElement("div", { style: { marginBottom: '12px' } },
                external_react_default().createElement("label", { style: {
                        display: 'block',
                        fontSize: '12px',
                        fontWeight: 500,
                        marginBottom: '4px',
                        color: 'var(--theme-color-fg-default)'
                    } }, "Source Icon"),
                external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: (pwa === null || pwa === void 0 ? void 0 : pwa.sourceIcon) || '', onChange: (value) => onChange({ sourceIcon: value }) }),
                external_react_default().createElement("div", { style: {
                        fontSize: '11px',
                        color: 'var(--theme-color-fg-muted)',
                        marginTop: '4px'
                    } }, "Path to 512x512 icon (generates all sizes automatically)"))))));
}

;// ./src/editor/src/views/panels/AppSetupPanel/sections/SEOSection.tsx



function SEOSection({ seo, identity, onChange }) {
    // Local state for immediate UI updates
    const [localOgDescription, setLocalOgDescription] = (0,external_react_.useState)(seo.ogDescription || '');
    const [localThemeColor, setLocalThemeColor] = (0,external_react_.useState)(seo.themeColor || '#000000');
    // Sync local state when external seo changes
    (0,external_react_.useEffect)(() => {
        setLocalOgDescription(seo.ogDescription || '');
    }, [seo.ogDescription]);
    (0,external_react_.useEffect)(() => {
        setLocalThemeColor(seo.themeColor || '#000000');
    }, [seo.themeColor]);
    // Smart defaults from identity
    const defaultOgTitle = identity.appName || '';
    const defaultOgDescription = identity.description || '';
    const defaultOgImage = identity.coverImage || '';
    return (external_react_default().createElement(CollapsableSection/* CollapsableSection */.M, { title: "SEO & Metadata", hasGutter: true, hasVisibleOverflow: true, hasTopDivider: true },
        external_react_default().createElement("div", { style: { marginBottom: '12px' } },
            external_react_default().createElement("label", { style: {
                    display: 'block',
                    fontSize: '12px',
                    fontWeight: 500,
                    marginBottom: '4px',
                    color: 'var(--theme-color-fg-default)'
                } }, "Open Graph Title"),
            external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: seo.ogTitle || '', onChange: (value) => onChange({ ogTitle: value || undefined }) }),
            !seo.ogTitle && defaultOgTitle && (external_react_default().createElement("div", { style: {
                    fontSize: '11px',
                    color: 'var(--theme-color-fg-muted)',
                    marginTop: '4px'
                } },
                "Defaults to: ",
                defaultOgTitle))),
        external_react_default().createElement("div", { style: { marginBottom: '12px' } },
            external_react_default().createElement("label", { style: {
                    display: 'block',
                    fontSize: '12px',
                    fontWeight: 500,
                    marginBottom: '4px',
                    color: 'var(--theme-color-fg-default)'
                } }, "Open Graph Description"),
            external_react_default().createElement("textarea", { value: localOgDescription, onChange: (e) => {
                    setLocalOgDescription(e.target.value);
                    onChange({ ogDescription: e.target.value || undefined });
                }, placeholder: "Enter description...", rows: 3, style: {
                    width: '100%',
                    padding: '8px',
                    fontSize: '13px',
                    fontFamily: 'inherit',
                    backgroundColor: 'var(--theme-color-bg-3)',
                    border: '1px solid var(--theme-color-border-default)',
                    borderRadius: '4px',
                    color: 'var(--theme-color-fg-default)',
                    resize: 'vertical'
                } }),
            !seo.ogDescription && defaultOgDescription && (external_react_default().createElement("div", { style: {
                    fontSize: '11px',
                    color: 'var(--theme-color-fg-muted)',
                    marginTop: '4px'
                } },
                "Defaults to: ",
                defaultOgDescription.substring(0, 50),
                defaultOgDescription.length > 50 ? '...' : ''))),
        external_react_default().createElement("div", { style: { marginBottom: '12px' } },
            external_react_default().createElement("label", { style: {
                    display: 'block',
                    fontSize: '12px',
                    fontWeight: 500,
                    marginBottom: '4px',
                    color: 'var(--theme-color-fg-default)'
                } }, "Open Graph Image"),
            external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: seo.ogImage || '', onChange: (value) => onChange({ ogImage: value || undefined }) }),
            !seo.ogImage && defaultOgImage && (external_react_default().createElement("div", { style: {
                    fontSize: '11px',
                    color: 'var(--theme-color-fg-muted)',
                    marginTop: '4px'
                } },
                "Defaults to: ",
                defaultOgImage))),
        external_react_default().createElement("div", { style: { marginBottom: '12px' } },
            external_react_default().createElement("label", { style: {
                    display: 'block',
                    fontSize: '12px',
                    fontWeight: 500,
                    marginBottom: '4px',
                    color: 'var(--theme-color-fg-default)'
                } }, "Favicon"),
            external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: seo.favicon || '', onChange: (value) => onChange({ favicon: value }) }),
            external_react_default().createElement("div", { style: {
                    fontSize: '11px',
                    color: 'var(--theme-color-fg-muted)',
                    marginTop: '4px'
                } }, "Path to favicon (.ico, .png, .svg)")),
        external_react_default().createElement("div", { style: { marginBottom: '12px' } },
            external_react_default().createElement("label", { style: {
                    display: 'block',
                    fontSize: '12px',
                    fontWeight: 500,
                    marginBottom: '4px',
                    color: 'var(--theme-color-fg-default)'
                } }, "Theme Color"),
            external_react_default().createElement("div", { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
                external_react_default().createElement("input", { type: "color", value: localThemeColor, onChange: (e) => {
                        setLocalThemeColor(e.target.value);
                        onChange({ themeColor: e.target.value });
                    }, style: {
                        width: '40px',
                        height: '32px',
                        border: '1px solid var(--theme-color-border-default)',
                        borderRadius: '4px',
                        cursor: 'pointer',
                        backgroundColor: 'transparent'
                    } }),
                external_react_default().createElement("div", { style: { flex: 1 } },
                    external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: localThemeColor, onChange: (value) => {
                            setLocalThemeColor(value);
                            onChange({ themeColor: value });
                        } }))),
            external_react_default().createElement("div", { style: {
                    fontSize: '11px',
                    color: 'var(--theme-color-fg-muted)',
                    marginTop: '4px'
                } }, "Browser theme color (hex format)"))));
}

// EXTERNAL MODULE: ../noodl-runtime/src/config/types.ts
var editor_types = __webpack_require__(54743);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/json-editor/JSONEditor.module.scss
var JSONEditor_module = __webpack_require__(60893);
;// ../noodl-core-ui/src/components/json-editor/JSONEditor.module.scss

      
      
      
      
      
      
      
      
      

var JSONEditor_module_options = {};

JSONEditor_module_options.styleTagTransform = (styleTagTransform_default());
JSONEditor_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      JSONEditor_module_options.insert = insertBySelector_default().bind(null, "head");
    
JSONEditor_module_options.domAPI = (styleDomAPI_default());
JSONEditor_module_options.insertStyleElement = (insertStyleElement_default());

var JSONEditor_module_update = injectStylesIntoStyleTag_default()(JSONEditor_module/* default */.A, JSONEditor_module_options);




       /* harmony default export */ const json_editor_JSONEditor_module = (JSONEditor_module/* default */.A && JSONEditor_module/* default */.A.locals ? JSONEditor_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/json-editor/utils/jsonValidator.ts
/**
 * JSON Validator with Helpful Error Messages
 *
 * Validates JSON and provides detailed error information with
 * suggested fixes for common mistakes. Designed to be helpful
 * for no-coders who may not understand JSON syntax.
 *
 * @module json-editor/utils
 */
/**
 * Validates JSON string and provides detailed error information with fix suggestions.
 *
 * @param jsonString - The JSON string to validate
 * @param expectedType - Optional type constraint ('array' | 'object' | 'any')
 * @returns Validation result with error details and suggestions
 *
 * @example
 * ```typescript
 * const result = validateJSON('[1, 2, 3]', 'array');
 * if (result.valid) {
 *   console.log('Valid!', result.value);
 * } else {
 *   console.error(result.error, result.suggestion);
 * }
 * ```
 */
function validateJSON(jsonString, expectedType) {
    // Handle empty input
    if (!jsonString || jsonString.trim() === '') {
        return {
            valid: false,
            error: 'Empty input',
            suggestion: expectedType === 'array' ? 'Start with [ ] for an array' : 'Start with { } for an object'
        };
    }
    const trimmed = jsonString.trim();
    try {
        // Attempt to parse
        const parsed = JSON.parse(trimmed);
        // Check type constraints
        if (expectedType === 'array' && !Array.isArray(parsed)) {
            return {
                valid: false,
                error: 'Expected an array, but got an object',
                suggestion: 'Wrap your data in [ ] brackets to make it an array. Example: [ {...} ]'
            };
        }
        if (expectedType === 'object' && (typeof parsed !== 'object' || Array.isArray(parsed))) {
            return {
                valid: false,
                error: 'Expected an object, but got ' + (Array.isArray(parsed) ? 'an array' : typeof parsed),
                suggestion: 'Wrap your data in { } braces to make it an object. Example: { "key": "value" }'
            };
        }
        // Valid!
        return {
            valid: true,
            value: parsed
        };
    }
    catch (error) {
        // Parse the error to provide helpful feedback
        return parseJSONError(error, trimmed);
    }
}
/**
 * Parses a JSON.parse() error and extracts helpful information
 *
 * @param error - The SyntaxError from JSON.parse()
 * @param jsonString - The original JSON string
 * @returns Validation result with detailed error and suggestions
 */
function parseJSONError(error, jsonString) {
    const message = error.message;
    // Extract position from error message
    // Error messages typically look like: "Unexpected token } in JSON at position 42"
    const positionMatch = message.match(/position (\d+)/);
    const position = positionMatch ? parseInt(positionMatch[1], 10) : null;
    // Calculate line and column from position
    let line = 1;
    let column = 1;
    if (position !== null) {
        const lines = jsonString.substring(0, position).split('\n');
        line = lines.length;
        column = lines[lines.length - 1].length + 1;
    }
    // Analyze the error and provide helpful suggestions
    const suggestion = getErrorSuggestion(message, jsonString, position);
    return {
        valid: false,
        error: `Line ${line}, Column ${column}: ${extractSimpleError(message)}`,
        line,
        column,
        suggestion
    };
}
/**
 * Extracts a simple, user-friendly error message from the technical error
 *
 * @param message - The technical error message from JSON.parse()
 * @returns Simplified error message
 */
function extractSimpleError(message) {
    // Common patterns
    if (message.includes('Unexpected token')) {
        const tokenMatch = message.match(/Unexpected token ([^\s]+)/);
        const token = tokenMatch ? tokenMatch[1] : 'character';
        return `Unexpected ${token}`;
    }
    if (message.includes('Unexpected end of JSON')) {
        return 'Unexpected end of JSON';
    }
    if (message.includes('Unexpected string')) {
        return 'Unexpected string';
    }
    if (message.includes('Unexpected number')) {
        return 'Unexpected number';
    }
    // Default to original message
    return message;
}
/**
 * Provides a helpful suggestion based on the error message and context
 *
 * @param message - The error message from JSON.parse()
 * @param jsonString - The original JSON string
 * @param position - The error position in the string
 * @returns A helpful suggestion for fixing the error
 */
function getErrorSuggestion(message, jsonString, position) {
    const lower = message.toLowerCase();
    // Missing closing bracket/brace
    if (lower.includes('unexpected end of json') || lower.includes('unterminated')) {
        const openBraces = (jsonString.match(/{/g) || []).length;
        const closeBraces = (jsonString.match(/}/g) || []).length;
        const openBrackets = (jsonString.match(/\[/g) || []).length;
        const closeBrackets = (jsonString.match(/]/g) || []).length;
        if (openBraces > closeBraces) {
            return `Missing ${openBraces - closeBraces} closing } brace(s) at the end`;
        }
        if (openBrackets > closeBrackets) {
            return `Missing ${openBrackets - closeBrackets} closing ] bracket(s) at the end`;
        }
        return 'Check if you have matching { } braces and [ ] brackets';
    }
    // Missing comma
    if (lower.includes('unexpected token') && position !== null) {
        const context = jsonString.substring(Math.max(0, position - 20), position);
        const nextChar = jsonString[position];
        // Check if previous line ended without comma
        if (context.includes('"') && (nextChar === '"' || nextChar === '{' || nextChar === '[')) {
            return 'Add a comma (,) after the previous property or value';
        }
        // Unexpected } or ]
        if (nextChar === '}' || nextChar === ']') {
            return 'Remove the trailing comma before the closing bracket';
        }
        // Unexpected :
        if (nextChar === ':') {
            return 'Property keys must be wrapped in "quotes"';
        }
    }
    // Unexpected token } or ]
    if (lower.includes('unexpected token }')) {
        return 'Either remove this extra } brace, or add a comma before it if there should be more properties';
    }
    if (lower.includes('unexpected token ]')) {
        return 'Either remove this extra ] bracket, or add a comma before it if there should be more items';
    }
    // Unexpected string
    if (lower.includes('unexpected string')) {
        return 'Add a comma (,) between values, or check if a property key needs a colon (:)';
    }
    // Missing quotes around key
    if (lower.includes('unexpected token') && position !== null && jsonString[position] !== '"') {
        const context = jsonString.substring(Math.max(0, position - 10), position + 10);
        if (context.includes(':')) {
            return 'Property keys must be wrapped in "double quotes"';
        }
    }
    // Single quotes instead of double quotes
    if (jsonString.includes("'")) {
        return 'JSON requires "double quotes" for strings, not \'single quotes\'';
    }
    // Trailing comma
    if (lower.includes('unexpected token }') || lower.includes('unexpected token ]')) {
        return 'Remove the trailing comma before the closing bracket';
    }
    // Generic help
    return 'Check for common issues: missing commas, unmatched brackets { } [ ], or keys without "quotes"';
}
/**
 * Formats JSON string with proper indentation
 *
 * @param jsonString - The JSON string to format
 * @param indent - Number of spaces for indentation (default: 2)
 * @returns Formatted JSON string or original if invalid
 */
function formatJSON(jsonString, indent = 2) {
    try {
        const parsed = JSON.parse(jsonString);
        return JSON.stringify(parsed, null, indent);
    }
    catch {
        // Return original if invalid
        return jsonString;
    }
}
/**
 * Checks if a string is valid JSON without throwing errors
 *
 * @param jsonString - The string to check
 * @returns True if valid JSON
 */
function isValidJSON(jsonString) {
    try {
        JSON.parse(jsonString);
        return true;
    }
    catch {
        return false;
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/json-editor/modes/AdvancedMode/AdvancedMode.module.scss
var AdvancedMode_module = __webpack_require__(74880);
;// ../noodl-core-ui/src/components/json-editor/modes/AdvancedMode/AdvancedMode.module.scss

      
      
      
      
      
      
      
      
      

var AdvancedMode_module_options = {};

AdvancedMode_module_options.styleTagTransform = (styleTagTransform_default());
AdvancedMode_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      AdvancedMode_module_options.insert = insertBySelector_default().bind(null, "head");
    
AdvancedMode_module_options.domAPI = (styleDomAPI_default());
AdvancedMode_module_options.insertStyleElement = (insertStyleElement_default());

var AdvancedMode_module_update = injectStylesIntoStyleTag_default()(AdvancedMode_module/* default */.A, AdvancedMode_module_options);




       /* harmony default export */ const AdvancedMode_AdvancedMode_module = (AdvancedMode_module/* default */.A && AdvancedMode_module/* default */.A.locals ? AdvancedMode_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/json-editor/modes/AdvancedMode/AdvancedMode.tsx
/**
 * Advanced Mode - Text Editor for Power Users
 *
 * A text-based JSON editor with syntax highlighting, validation,
 * and helpful error messages. For users who prefer direct editing.
 *
 * @module json-editor/modes
 */



/**
 * Advanced text editor mode
 */
function AdvancedMode({ value, onChange, disabled }) {
    const [localValue, setLocalValue] = (0,external_react_.useState)(value);
    const [validationResult, setValidationResult] = (0,external_react_.useState)(validateJSON(value));
    // Sync with external value changes
    (0,external_react_.useEffect)(() => {
        setLocalValue(value);
        setValidationResult(validateJSON(value));
    }, [value]);
    // Handle text changes
    const handleChange = (newValue) => {
        setLocalValue(newValue);
        const result = validateJSON(newValue);
        setValidationResult(result);
        // Only propagate valid JSON changes
        if (result.valid && onChange) {
            onChange(newValue);
        }
    };
    // Format/pretty-print JSON
    const handleFormat = () => {
        if (validationResult.valid) {
            try {
                const parsed = JSON.parse(localValue);
                const formatted = JSON.stringify(parsed, null, 2);
                setLocalValue(formatted);
                if (onChange) {
                    onChange(formatted);
                }
            }
            catch (e) {
                // Should not happen if validation passed
                console.error('Format error:', e);
            }
        }
    };
    return (external_react_default().createElement("div", { className: AdvancedMode_AdvancedMode_module['Root'] },
        external_react_default().createElement("div", { className: AdvancedMode_AdvancedMode_module['Toolbar'] },
            external_react_default().createElement("div", { className: AdvancedMode_AdvancedMode_module['ToolbarLeft'] }, validationResult.valid ? (external_react_default().createElement("span", { className: AdvancedMode_AdvancedMode_module['StatusValid'] }, "\u2713 Valid JSON")) : (external_react_default().createElement("span", { className: AdvancedMode_AdvancedMode_module['StatusInvalid'] }, "\u2717 Invalid JSON"))),
            external_react_default().createElement("div", { className: AdvancedMode_AdvancedMode_module['ToolbarRight'] },
                external_react_default().createElement("button", { onClick: handleFormat, disabled: !validationResult.valid || disabled, className: AdvancedMode_AdvancedMode_module['FormatButton'], title: "Format JSON (Ctrl+Shift+F)" }, "Format"))),
        external_react_default().createElement("textarea", { value: localValue, onChange: (e) => handleChange(e.target.value), disabled: disabled, className: AdvancedMode_AdvancedMode_module['Editor'], placeholder: '{\\n  "key": "value"\\n}', spellCheck: false }),
        !validationResult.valid && (external_react_default().createElement("div", { className: AdvancedMode_AdvancedMode_module['ErrorPanel'] },
            external_react_default().createElement("div", { className: AdvancedMode_AdvancedMode_module['ErrorHeader'] },
                external_react_default().createElement("span", { className: AdvancedMode_AdvancedMode_module['ErrorIcon'] }, "\u26A0\uFE0F"),
                external_react_default().createElement("span", { className: AdvancedMode_AdvancedMode_module['ErrorTitle'] }, "JSON Syntax Error")),
            external_react_default().createElement("div", { className: AdvancedMode_AdvancedMode_module['ErrorMessage'] }, validationResult.error),
            validationResult.suggestion && (external_react_default().createElement("div", { className: AdvancedMode_AdvancedMode_module['ErrorSuggestion'] },
                external_react_default().createElement("strong", null, "\uD83D\uDCA1 Suggestion:"),
                " ",
                validationResult.suggestion)),
            validationResult.line !== undefined && (external_react_default().createElement("div", { className: AdvancedMode_AdvancedMode_module['ErrorLocation'] },
                "Line ",
                validationResult.line,
                validationResult.column !== undefined && `, Column ${validationResult.column}`))))));
}

;// ../noodl-core-ui/src/components/json-editor/utils/treeConverter.ts
/**
 * Tree Converter Utility
 *
 * Converts between JSON values and tree node representations
 * for the Easy Mode visual editor.
 *
 * @module json-editor/utils
 */
/**
 * Converts a JSON value to a tree node structure for Easy Mode display
 *
 * @param value - The JSON value to convert
 * @param path - Current path in the tree (for editing)
 * @param key - Object key (if this is an object property)
 * @param index - Array index (if this is an array element)
 * @returns Tree node representation
 */
function valueToTreeNode(value, path = [], key, index) {
    const type = getValueType(value);
    const id = path.length === 0 ? 'root' : path.join('.');
    const baseNode = {
        id,
        type,
        path,
        key,
        index,
        isExpanded: true // Default to expanded
    };
    if (type === 'array') {
        const arr = value;
        return {
            ...baseNode,
            children: arr.map((item, idx) => valueToTreeNode(item, [...path, idx], undefined, idx))
        };
    }
    if (type === 'object') {
        const obj = value;
        return {
            ...baseNode,
            children: Object.entries(obj).map(([k, v]) => valueToTreeNode(v, [...path, k], k))
        };
    }
    // Primitive values
    return {
        ...baseNode,
        value: value
    };
}
/**
 * Converts a tree node back to a JSON value
 *
 * @param node - The tree node to convert
 * @returns JSON value
 */
function treeNodeToValue(node) {
    if (node.type === 'array') {
        return (node.children || []).map(treeNodeToValue);
    }
    if (node.type === 'object') {
        const result = {};
        (node.children || []).forEach((child) => {
            if (child.key) {
                result[child.key] = treeNodeToValue(child);
            }
        });
        return result;
    }
    // Primitive values
    return node.value;
}
/**
 * Determines the JSON value type
 *
 * @param value - The value to check
 * @returns The JSON value type
 */
function getValueType(value) {
    if (value === null)
        return 'null';
    if (Array.isArray(value))
        return 'array';
    if (typeof value === 'object')
        return 'object';
    if (typeof value === 'boolean')
        return 'boolean';
    if (typeof value === 'number')
        return 'number';
    return 'string';
}
/**
 * Gets a value from an object/array using a path
 *
 * @param root - The root object/array
 * @param path - Path to the value
 * @returns The value at the path, or undefined
 */
function getValueAtPath(root, path) {
    let current = root;
    for (const segment of path) {
        if (current === null || current === undefined)
            return undefined;
        if (typeof current === 'object') {
            current = current[segment];
        }
        else {
            return undefined;
        }
    }
    return current;
}
/**
 * Sets a value in an object/array using a path (immutably)
 *
 * @param root - The root object/array
 * @param path - Path to set the value
 * @param value - Value to set
 * @returns New root with the value updated
 */
function setValueAtPath(root, path, value) {
    if (path.length === 0)
        return value;
    const [first, ...rest] = path;
    if (Array.isArray(root)) {
        const newArray = [...root];
        if (typeof first === 'number') {
            newArray[first] = rest.length === 0 ? value : setValueAtPath(newArray[first], rest, value);
        }
        return newArray;
    }
    if (typeof root === 'object' && root !== null) {
        return {
            ...root,
            [first]: rest.length === 0 ? value : setValueAtPath(root[first], rest, value)
        };
    }
    return root;
}
/**
 * Deletes a value in an object/array using a path (immutably)
 *
 * @param root - The root object/array
 * @param path - Path to delete
 * @returns New root with the value deleted
 */
function deleteValueAtPath(root, path) {
    if (path.length === 0)
        return root;
    const [first, ...rest] = path;
    if (Array.isArray(root)) {
        if (rest.length === 0 && typeof first === 'number') {
            return root.filter((_, idx) => idx !== first);
        }
        const newArray = [...root];
        if (typeof first === 'number') {
            newArray[first] = deleteValueAtPath(newArray[first], rest);
        }
        return newArray;
    }
    if (typeof root === 'object' && root !== null) {
        if (rest.length === 0) {
            const { [first]: _, ...newObj } = root;
            return newObj;
        }
        return {
            ...root,
            [first]: deleteValueAtPath(root[first], rest)
        };
    }
    return root;
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/json-editor/modes/EasyMode/EasyMode.module.scss
var EasyMode_module = __webpack_require__(368);
;// ../noodl-core-ui/src/components/json-editor/modes/EasyMode/EasyMode.module.scss

      
      
      
      
      
      
      
      
      

var EasyMode_module_options = {};

EasyMode_module_options.styleTagTransform = (styleTagTransform_default());
EasyMode_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      EasyMode_module_options.insert = insertBySelector_default().bind(null, "head");
    
EasyMode_module_options.domAPI = (styleDomAPI_default());
EasyMode_module_options.insertStyleElement = (insertStyleElement_default());

var EasyMode_module_update = injectStylesIntoStyleTag_default()(EasyMode_module/* default */.A, EasyMode_module_options);




       /* harmony default export */ const EasyMode_EasyMode_module = (EasyMode_module/* default */.A && EasyMode_module/* default */.A.locals ? EasyMode_module/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/json-editor/modes/EasyMode/ValueEditor.module.scss
var ValueEditor_module = __webpack_require__(76817);
;// ../noodl-core-ui/src/components/json-editor/modes/EasyMode/ValueEditor.module.scss

      
      
      
      
      
      
      
      
      

var ValueEditor_module_options = {};

ValueEditor_module_options.styleTagTransform = (styleTagTransform_default());
ValueEditor_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ValueEditor_module_options.insert = insertBySelector_default().bind(null, "head");
    
ValueEditor_module_options.domAPI = (styleDomAPI_default());
ValueEditor_module_options.insertStyleElement = (insertStyleElement_default());

var ValueEditor_module_update = injectStylesIntoStyleTag_default()(ValueEditor_module/* default */.A, ValueEditor_module_options);




       /* harmony default export */ const EasyMode_ValueEditor_module = (ValueEditor_module/* default */.A && ValueEditor_module/* default */.A.locals ? ValueEditor_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/json-editor/modes/EasyMode/ValueEditor.tsx
/**
 * ValueEditor Component
 *
 * Type-aware inline editor for primitive JSON values.
 * Provides appropriate input controls for each type.
 *
 * @module json-editor/modes/EasyMode
 */


/**
 * Inline editor for primitive values
 */
function ValueEditor({ value, type, onSave, onCancel, autoFocus = true }) {
    const [localValue, setLocalValue] = (0,external_react_.useState)(() => {
        if (type === 'null')
            return 'null';
        if (type === 'boolean')
            return value ? 'true' : 'false';
        return String(value !== null && value !== void 0 ? value : '');
    });
    const inputRef = (0,external_react_.useRef)(null);
    // Auto-focus on mount
    (0,external_react_.useEffect)(() => {
        if (autoFocus && inputRef.current) {
            inputRef.current.focus();
            inputRef.current.select();
        }
    }, [autoFocus]);
    const handleSave = () => {
        // Convert string to appropriate type
        let parsedValue;
        if (type === 'null') {
            parsedValue = null;
        }
        else if (type === 'boolean') {
            parsedValue = localValue === 'true';
        }
        else if (type === 'number') {
            const num = Number(localValue);
            if (isNaN(num)) {
                // Invalid number, cancel
                onCancel();
                return;
            }
            parsedValue = num;
        }
        else {
            // String
            parsedValue = localValue;
        }
        onSave(parsedValue);
    };
    const handleKeyDown = (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSave();
        }
        else if (e.key === 'Escape') {
            e.preventDefault();
            onCancel();
        }
    };
    // Boolean toggle
    if (type === 'boolean') {
        return (external_react_default().createElement("div", { className: EasyMode_ValueEditor_module['BooleanEditor'] },
            external_react_default().createElement("label", { className: EasyMode_ValueEditor_module['BooleanToggle'] },
                external_react_default().createElement("input", { ref: inputRef, type: "checkbox", checked: localValue === 'true', onChange: (e) => {
                        const newValue = e.target.checked ? 'true' : 'false';
                        setLocalValue(newValue);
                        // Auto-save on toggle
                        onSave(e.target.checked);
                    }, autoFocus: autoFocus }),
                external_react_default().createElement("span", { className: EasyMode_ValueEditor_module['ToggleLabel'] }, localValue))));
    }
    // Null (read-only, just show the value)
    if (type === 'null') {
        return (external_react_default().createElement("div", { className: EasyMode_ValueEditor_module['NullEditor'] },
            external_react_default().createElement("span", { className: EasyMode_ValueEditor_module['NullValue'] }, "null"),
            external_react_default().createElement("button", { onClick: onCancel, className: EasyMode_ValueEditor_module['CloseButton'] }, "\u2715")));
    }
    // String and Number input
    return (external_react_default().createElement("div", { className: EasyMode_ValueEditor_module['InputEditor'] },
        external_react_default().createElement("input", { ref: inputRef, type: type === 'number' ? 'number' : 'text', value: localValue, onChange: (e) => setLocalValue(e.target.value), onKeyDown: handleKeyDown, onBlur: handleSave, className: EasyMode_ValueEditor_module['Input'], placeholder: type === 'string' ? 'Enter text...' : 'Enter number...' }),
        external_react_default().createElement("div", { className: EasyMode_ValueEditor_module['ButtonGroup'] },
            external_react_default().createElement("button", { onClick: handleSave, className: EasyMode_ValueEditor_module['SaveButton'], title: "Save (Enter)" }, "\u2713"),
            external_react_default().createElement("button", { onClick: onCancel, className: EasyMode_ValueEditor_module['CancelButton'], title: "Cancel (Esc)" }, "\u2715"))));
}

;// ../noodl-core-ui/src/components/json-editor/modes/EasyMode/EasyMode.tsx
/**
 * Easy Mode - Visual JSON Tree Builder (WITH EDITING)
 *
 * A visual tree-based editor where users can't break JSON structure.
 * Perfect for no-coders who don't understand JSON syntax.
 *
 * @module json-editor/modes
 */




/**
 * Editable Tree Node Component
 */
function EditableTreeNode({ node, depth, onEdit, onDelete, onAdd, disabled }) {
    var _a, _b;
    const [isEditing, setIsEditing] = (0,external_react_.useState)(false);
    const [isAddingItem, setIsAddingItem] = (0,external_react_.useState)(false);
    const [newItemType, setNewItemType] = (0,external_react_.useState)('string');
    const [newKey, setNewKey] = (0,external_react_.useState)('');
    const hasChildren = node.children && node.children.length > 0;
    const indent = depth * 20;
    const canEdit = !disabled && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null');
    const canDelete = !disabled && depth > 0; // Can't delete root
    // Type badge
    const typeBadge = (external_react_default().createElement("span", { className: EasyMode_EasyMode_module['TypeBadge'], "data-type": node.type }, node.type));
    // Handle saving edited value
    const handleSaveEdit = (value) => {
        onEdit(node.path, value);
        setIsEditing(false);
    };
    // Handle adding new item/property
    const handleAddItem = () => {
        if (node.type === 'array') {
            onAdd(node.path, newItemType);
        }
        else if (node.type === 'object') {
            if (!newKey.trim())
                return;
            onAdd(node.path, newItemType, newKey.trim());
        }
        setIsAddingItem(false);
        setNewKey('');
        setNewItemType('string');
    };
    // Arrays
    if (node.type === 'array') {
        return (external_react_default().createElement("div", { className: EasyMode_EasyMode_module['TreeNode'], style: { marginLeft: `${indent}px` } },
            external_react_default().createElement("div", { className: EasyMode_EasyMode_module['NodeHeader'] },
                node.key && (external_react_default().createElement((external_react_default()).Fragment, null,
                    external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Key'] }, node.key),
                    external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Colon'] }, ":"))),
                node.index !== undefined && external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Index'] },
                    "[",
                    node.index,
                    "]"),
                typeBadge,
                external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Count'] },
                    "(",
                    ((_a = node.children) === null || _a === void 0 ? void 0 : _a.length) || 0,
                    " items)"),
                !disabled && (external_react_default().createElement("button", { onClick: () => setIsAddingItem(!isAddingItem), className: EasyMode_EasyMode_module['AddButton'], title: "Add item" }, "+ Add Item")),
                canDelete && (external_react_default().createElement("button", { onClick: () => onDelete(node.path), className: EasyMode_EasyMode_module['DeleteButton'], title: "Delete" }, "\u2715"))),
            isAddingItem && (external_react_default().createElement("div", { className: EasyMode_EasyMode_module['AddItemForm'] },
                external_react_default().createElement("select", { value: newItemType, onChange: (e) => setNewItemType(e.target.value) },
                    external_react_default().createElement("option", { value: "string" }, "String"),
                    external_react_default().createElement("option", { value: "number" }, "Number"),
                    external_react_default().createElement("option", { value: "boolean" }, "Boolean"),
                    external_react_default().createElement("option", { value: "null" }, "Null"),
                    external_react_default().createElement("option", { value: "array" }, "Array"),
                    external_react_default().createElement("option", { value: "object" }, "Object")),
                external_react_default().createElement("button", { onClick: handleAddItem }, "Add"),
                external_react_default().createElement("button", { onClick: () => setIsAddingItem(false) }, "Cancel"))),
            hasChildren && (external_react_default().createElement("div", { className: EasyMode_EasyMode_module['Children'] }, node.children.map((child, idx) => (external_react_default().createElement(EditableTreeNode, { key: child.id || idx, node: child, depth: depth + 1, onEdit: onEdit, onDelete: onDelete, onAdd: onAdd, disabled: disabled })))))));
    }
    // Objects
    if (node.type === 'object') {
        return (external_react_default().createElement("div", { className: EasyMode_EasyMode_module['TreeNode'], style: { marginLeft: `${indent}px` } },
            external_react_default().createElement("div", { className: EasyMode_EasyMode_module['NodeHeader'] },
                node.key && (external_react_default().createElement((external_react_default()).Fragment, null,
                    external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Key'] }, node.key),
                    external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Colon'] }, ":"))),
                node.index !== undefined && external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Index'] },
                    "[",
                    node.index,
                    "]"),
                typeBadge,
                external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Count'] },
                    "(",
                    ((_b = node.children) === null || _b === void 0 ? void 0 : _b.length) || 0,
                    " properties)"),
                !disabled && (external_react_default().createElement("button", { onClick: () => setIsAddingItem(!isAddingItem), className: EasyMode_EasyMode_module['AddButton'], title: "Add property" }, "+ Add Property")),
                canDelete && (external_react_default().createElement("button", { onClick: () => onDelete(node.path), className: EasyMode_EasyMode_module['DeleteButton'], title: "Delete" }, "\u2715"))),
            isAddingItem && (external_react_default().createElement("div", { className: EasyMode_EasyMode_module['AddItemForm'] },
                external_react_default().createElement("input", { type: "text", placeholder: "Property key", value: newKey, onChange: (e) => setNewKey(e.target.value) }),
                external_react_default().createElement("select", { value: newItemType, onChange: (e) => setNewItemType(e.target.value) },
                    external_react_default().createElement("option", { value: "string" }, "String"),
                    external_react_default().createElement("option", { value: "number" }, "Number"),
                    external_react_default().createElement("option", { value: "boolean" }, "Boolean"),
                    external_react_default().createElement("option", { value: "null" }, "Null"),
                    external_react_default().createElement("option", { value: "array" }, "Array"),
                    external_react_default().createElement("option", { value: "object" }, "Object")),
                external_react_default().createElement("button", { onClick: handleAddItem, disabled: !newKey.trim() }, "Add"),
                external_react_default().createElement("button", { onClick: () => setIsAddingItem(false) }, "Cancel"))),
            hasChildren && (external_react_default().createElement("div", { className: EasyMode_EasyMode_module['Children'] }, node.children.map((child, idx) => (external_react_default().createElement(EditableTreeNode, { key: child.id || idx, node: child, depth: depth + 1, onEdit: onEdit, onDelete: onDelete, onAdd: onAdd, disabled: disabled })))))));
    }
    // Primitive values
    return (external_react_default().createElement("div", { className: EasyMode_EasyMode_module['TreeNode'], style: { marginLeft: `${indent}px` } },
        external_react_default().createElement("div", { className: EasyMode_EasyMode_module['NodeHeader'] },
            node.key && (external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Key'] }, node.key),
                external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Colon'] }, ":"))),
            node.index !== undefined && external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Index'] },
                "[",
                node.index,
                "]"),
            typeBadge,
            isEditing ? (external_react_default().createElement(ValueEditor, { value: node.value, type: node.type, onSave: handleSaveEdit, onCancel: () => setIsEditing(false) })) : (external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement("span", { className: EasyMode_EasyMode_module['Value'], "data-type": node.type, onClick: () => canEdit && setIsEditing(true) }, formatValue(node.value, node.type)),
                canEdit && (external_react_default().createElement("button", { onClick: () => setIsEditing(true), className: EasyMode_EasyMode_module['EditButton'], title: "Edit" }, "\u270E")))),
            canDelete && (external_react_default().createElement("button", { onClick: () => onDelete(node.path), className: EasyMode_EasyMode_module['DeleteButton'], title: "Delete" }, "\u2715")))));
}
function formatValue(value, type) {
    if (type === 'null')
        return 'null';
    if (type === 'boolean')
        return value ? 'true' : 'false';
    if (type === 'string')
        return `"${value}"`;
    return String(value);
}
/**
 * Easy Mode Component
 */
function EasyMode({ rootNode, onChange, disabled }) {
    var _a, _b;
    // Handle editing a value at a path
    const handleEdit = (path, value) => {
        if (!onChange)
            return;
        const currentValue = treeNodeToValue(rootNode);
        const newValue = setValueAtPath(currentValue, path, value);
        const newNode = valueToTreeNode(newValue);
        onChange(newNode);
    };
    // Handle deleting a value at a path
    const handleDelete = (path) => {
        if (!onChange)
            return;
        const currentValue = treeNodeToValue(rootNode);
        const newValue = deleteValueAtPath(currentValue, path);
        const newNode = valueToTreeNode(newValue);
        onChange(newNode);
    };
    // Handle adding a new item/property
    const handleAdd = (path, type, key) => {
        if (!onChange)
            return;
        const currentValue = treeNodeToValue(rootNode);
        // Get the parent value at path
        let parent = currentValue;
        for (const segment of path) {
            parent = parent[segment];
        }
        // Create default value for the type
        let defaultValue;
        if (type === 'string')
            defaultValue = '';
        else if (type === 'number')
            defaultValue = 0;
        else if (type === 'boolean')
            defaultValue = false;
        else if (type === 'null')
            defaultValue = null;
        else if (type === 'array')
            defaultValue = [];
        else if (type === 'object')
            defaultValue = {};
        // Add to parent
        if (Array.isArray(parent)) {
            parent.push(defaultValue);
        }
        else if (typeof parent === 'object' && parent !== null && key) {
            parent[key] = defaultValue;
        }
        const newNode = valueToTreeNode(currentValue);
        onChange(newNode);
    };
    // Empty state
    if (!rootNode || (rootNode.type === 'array' && !((_a = rootNode.children) === null || _a === void 0 ? void 0 : _a.length))) {
        return (external_react_default().createElement("div", { className: EasyMode_EasyMode_module['Root'] },
            external_react_default().createElement("div", { className: EasyMode_EasyMode_module['EmptyState'] },
                external_react_default().createElement("div", { className: EasyMode_EasyMode_module['EmptyIcon'] }, "\uD83D\uDCCB"),
                external_react_default().createElement("div", { className: EasyMode_EasyMode_module['EmptyText'] }, "Empty array - click \"Add Item\" to start")),
            !disabled && (external_react_default().createElement(EditableTreeNode, { node: rootNode || valueToTreeNode([]), depth: 0, onEdit: handleEdit, onDelete: handleDelete, onAdd: handleAdd, disabled: disabled }))));
    }
    if (rootNode.type === 'object' && !((_b = rootNode.children) === null || _b === void 0 ? void 0 : _b.length)) {
        return (external_react_default().createElement("div", { className: EasyMode_EasyMode_module['Root'] },
            external_react_default().createElement("div", { className: EasyMode_EasyMode_module['EmptyState'] },
                external_react_default().createElement("div", { className: EasyMode_EasyMode_module['EmptyIcon'] }, "\uD83D\uDCE6"),
                external_react_default().createElement("div", { className: EasyMode_EasyMode_module['EmptyText'] }, "Empty object - click \"Add Property\" to start")),
            !disabled && (external_react_default().createElement(EditableTreeNode, { node: rootNode || valueToTreeNode({}), depth: 0, onEdit: handleEdit, onDelete: handleDelete, onAdd: handleAdd, disabled: disabled }))));
    }
    return (external_react_default().createElement("div", { className: EasyMode_EasyMode_module['Root'] },
        external_react_default().createElement(EditableTreeNode, { node: rootNode, depth: 0, onEdit: handleEdit, onDelete: handleDelete, onAdd: handleAdd, disabled: disabled })));
}

;// ../noodl-core-ui/src/components/json-editor/JSONEditor.tsx
/**
 * JSONEditor Component
 *
 * A modern, dual-mode JSON editor with:
 * - Easy Mode: Visual tree builder (no-code friendly)
 * - Advanced Mode: Text editor with validation
 *
 * @module json-editor
 */






/**
 * Main JSONEditor Component
 */
function JSONEditor({ value, onChange, onSave, defaultMode = 'easy', mode: forcedMode, expectedType = 'any', disabled = false, height, placeholder }) {
    // Current editor mode
    const [currentMode, setCurrentMode] = (0,external_react_.useState)(forcedMode || defaultMode);
    // Internal JSON string state
    const [jsonString, setJsonString] = (0,external_react_.useState)(() => {
        if (typeof value === 'string')
            return value;
        try {
            return JSON.stringify(value, null, 2);
        }
        catch {
            return expectedType === 'array' ? '[]' : '{}';
        }
    });
    // Sync with external value changes
    (0,external_react_.useEffect)(() => {
        if (typeof value === 'string') {
            setJsonString(value);
        }
        else {
            try {
                setJsonString(JSON.stringify(value, null, 2));
            }
            catch {
                // Invalid value, keep current
            }
        }
    }, [value]);
    // Parse JSON to tree node for Easy Mode
    const treeNode = (0,external_react_.useMemo)(() => {
        try {
            const parsed = JSON.parse(jsonString || (expectedType === 'array' ? '[]' : '{}'));
            return valueToTreeNode(parsed);
        }
        catch {
            // Invalid JSON - return empty structure
            return valueToTreeNode(expectedType === 'array' ? [] : {});
        }
    }, [jsonString, expectedType]);
    // Validate current JSON
    const validation = (0,external_react_.useMemo)(() => {
        return validateJSON(jsonString, expectedType);
    }, [jsonString, expectedType]);
    // Handle mode toggle
    const handleModeChange = (newMode) => {
        if (forcedMode)
            return; // Can't change if forced
        setCurrentMode(newMode);
        // Save preference to localStorage
        try {
            localStorage.setItem('json-editor-preferred-mode', newMode);
        }
        catch {
            // Ignore storage errors
        }
    };
    // Handle tree changes from Easy Mode
    const handleTreeChange = (newNode) => {
        try {
            const newValue = treeNodeToValue(newNode);
            const newJson = JSON.stringify(newValue, null, 2);
            setJsonString(newJson);
            onChange(newJson);
        }
        catch (error) {
            console.error('Failed to convert tree to JSON:', error);
        }
    };
    // Handle text changes from Advanced Mode
    const handleTextChange = (newText) => {
        setJsonString(newText);
        onChange(newText);
    };
    // Container style
    const containerStyle = {
        height: height !== undefined ? (typeof height === 'number' ? `${height}px` : height) : '400px'
    };
    return (external_react_default().createElement("div", { className: json_editor_JSONEditor_module['Root'], style: containerStyle },
        external_react_default().createElement("div", { className: json_editor_JSONEditor_module['Header'] },
            external_react_default().createElement("div", { className: json_editor_JSONEditor_module['Title'] }, "JSON Editor"),
            !forcedMode && (external_react_default().createElement("div", { className: json_editor_JSONEditor_module['ModeToggle'] },
                external_react_default().createElement("button", { className: currentMode === 'easy' ? json_editor_JSONEditor_module['Active'] : '', onClick: () => handleModeChange('easy'), disabled: disabled }, "Easy"),
                external_react_default().createElement("button", { className: currentMode === 'advanced' ? json_editor_JSONEditor_module['Active'] : '', onClick: () => handleModeChange('advanced'), disabled: disabled }, "Advanced")))),
        !validation.valid && (external_react_default().createElement("div", { className: json_editor_JSONEditor_module['ValidationError'] },
            external_react_default().createElement("div", { className: json_editor_JSONEditor_module['ErrorIcon'] }, "\u26A0\uFE0F"),
            external_react_default().createElement("div", { className: json_editor_JSONEditor_module['ErrorContent'] },
                external_react_default().createElement("div", { className: json_editor_JSONEditor_module['ErrorMessage'] }, validation.error),
                validation.suggestion && external_react_default().createElement("div", { className: json_editor_JSONEditor_module['ErrorSuggestion'] },
                    "\uD83D\uDCA1 ",
                    validation.suggestion)))),
        external_react_default().createElement("div", { className: json_editor_JSONEditor_module['EditorContent'] }, currentMode === 'easy' ? (external_react_default().createElement(EasyMode, { rootNode: treeNode, onChange: handleTreeChange, disabled: disabled })) : (external_react_default().createElement(AdvancedMode, { value: jsonString, onChange: handleTextChange, disabled: disabled })))));
}

;// ../noodl-core-ui/src/components/json-editor/index.ts
/**
 * JSON Editor Component
 *
 * Public exports for the JSON Editor component.
 *
 * @module json-editor
 */



;// ./src/editor/src/views/panels/AppSetupPanel/sections/VariablesSection.tsx







function JSONEditorButton({ value, varType, onSave }) {
    const buttonRef = (0,external_react_.useRef)(null);
    const popoutRef = (0,external_react_.useRef)(null);
    const rootRef = (0,external_react_.useRef)(null);
    // Cleanup editor on unmount
    (0,external_react_.useEffect)(() => {
        return () => {
            if (rootRef.current) {
                rootRef.current.unmount();
                rootRef.current = null;
            }
            if (popoutRef.current) {
                popoutRef.current = null;
            }
        };
    }, []);
    const openEditor = () => {
        if (!buttonRef.current) {
            return;
        }
        // Close any existing editor
        if (rootRef.current) {
            rootRef.current.unmount();
            rootRef.current = null;
        }
        // Create popup container
        const popupDiv = document.createElement('div');
        const root = (0,client.createRoot)(popupDiv);
        rootRef.current = root;
        // Track current value for save
        let currentValue = value;
        const handleChange = (newValue) => {
            currentValue = newValue;
        };
        const handleClose = () => {
            try {
                // Parse and validate before saving
                const parsed = JSON.parse(currentValue);
                if (varType === 'array' && !Array.isArray(parsed)) {
                    return;
                }
                if (varType === 'object' && (typeof parsed !== 'object' || Array.isArray(parsed))) {
                    return;
                }
                onSave(currentValue);
            }
            catch {
                // Invalid JSON - don't save
            }
            root.unmount();
            rootRef.current = null;
        };
        root.render(external_react_default().createElement("div", { style: { padding: '16px', width: '600px', height: '500px', display: 'flex', flexDirection: 'column' } },
            external_react_default().createElement(JSONEditor, { value: value, onChange: handleChange, expectedType: varType, height: "100%" })));
        const popout = popuplayer_default().instance.showPopout({
            content: { el: [popupDiv] },
            attachTo: $(buttonRef.current),
            position: 'right',
            onClose: handleClose
        });
        popoutRef.current = popout;
    };
    return (external_react_default().createElement("button", { ref: buttonRef, onClick: (e) => {
            e.stopPropagation();
            openEditor();
        }, style: {
            width: '100%',
            padding: '10px',
            fontSize: '13px',
            fontFamily: 'monospace',
            backgroundColor: 'var(--theme-color-bg-3)',
            border: '1px solid var(--theme-color-border-default)',
            borderRadius: '4px',
            color: 'var(--theme-color-fg-default)',
            cursor: 'pointer',
            textAlign: 'left',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between'
        } },
        external_react_default().createElement("span", { style: {
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                flex: 1,
                color: 'var(--theme-color-fg-muted)'
            } }, value || (varType === 'array' ? '[]' : '{}')),
        external_react_default().createElement("span", { style: { marginLeft: '8px', color: 'var(--theme-color-primary)' } }, "Edit JSON \u279C")));
}
const ALL_TYPES = [
    { value: 'string', label: 'String' },
    { value: 'number', label: 'Number' },
    { value: 'boolean', label: 'Boolean' },
    { value: 'color', label: 'Color' },
    { value: 'array', label: 'Array' },
    { value: 'object', label: 'Object' }
];
function VariablesSection({ variables, onChange }) {
    // Local state for optimistic updates
    const [localVariables, setLocalVariables] = (0,external_react_.useState)(variables);
    const [isAdding, setIsAdding] = (0,external_react_.useState)(false);
    // Sync with props when they change externally
    (0,external_react_.useEffect)(() => {
        setLocalVariables(variables);
    }, [variables]);
    // New variable form state
    const [newKey, setNewKey] = (0,external_react_.useState)('');
    const [newType, setNewType] = (0,external_react_.useState)('string');
    const [newValue, setNewValue] = (0,external_react_.useState)('');
    const [newDescription, setNewDescription] = (0,external_react_.useState)('');
    const [newCategory, setNewCategory] = (0,external_react_.useState)('');
    const [error, setError] = (0,external_react_.useState)('');
    const [jsonError, setJsonError] = (0,external_react_.useState)('');
    const validateKey = (key, excludeIndex) => {
        if (!key.trim()) {
            return 'Key is required';
        }
        if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
            return 'Key must start with letter or underscore, and contain only letters, numbers, and underscores';
        }
        if (editor_types.RESERVED_CONFIG_KEYS.includes(key)) {
            return `"${key}" is a reserved key`;
        }
        const isDuplicate = localVariables.some((v, index) => v.key === key && index !== excludeIndex);
        if (isDuplicate) {
            return `Key "${key}" already exists`;
        }
        return null;
    };
    const parseValue = (type, valueStr) => {
        if (type === 'string')
            return valueStr;
        if (type === 'number') {
            const num = Number(valueStr);
            return isNaN(num) ? 0 : num;
        }
        if (type === 'boolean')
            return valueStr === 'true';
        if (type === 'color')
            return valueStr || '#000000';
        if (type === 'array') {
            try {
                const parsed = JSON.parse(valueStr || '[]');
                return Array.isArray(parsed) ? parsed : [];
            }
            catch {
                return [];
            }
        }
        if (type === 'object') {
            try {
                const parsed = JSON.parse(valueStr || '{}');
                return typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
            }
            catch {
                return {};
            }
        }
        return valueStr;
    };
    const serializeValue = (variable) => {
        if (variable.type === 'string')
            return String(variable.value || '');
        if (variable.type === 'number')
            return String(variable.value || 0);
        if (variable.type === 'boolean')
            return String(variable.value);
        if (variable.type === 'color')
            return String(variable.value || '#000000');
        if (variable.type === 'array' || variable.type === 'object') {
            try {
                return JSON.stringify(variable.value, null, 2);
            }
            catch {
                return variable.type === 'array' ? '[]' : '{}';
            }
        }
        return String(variable.value || '');
    };
    const handleAdd = () => {
        const keyError = validateKey(newKey);
        if (keyError) {
            setError(keyError);
            return;
        }
        // Validate JSON for array/object types
        if ((newType === 'array' || newType === 'object') && newValue) {
            try {
                JSON.parse(newValue);
                setJsonError('');
            }
            catch {
                setJsonError('Invalid JSON');
                return;
            }
        }
        const newVariable = {
            key: newKey.trim(),
            type: newType,
            value: parseValue(newType, newValue),
            description: newDescription.trim() || undefined,
            category: newCategory.trim() || undefined
        };
        // Update local state immediately (optimistic update)
        const updated = [...localVariables, newVariable];
        setLocalVariables(updated);
        // Persist in background
        onChange(updated);
        // Reset form
        setNewKey('');
        setNewType('string');
        setNewValue('');
        setNewDescription('');
        setNewCategory('');
        setError('');
        setJsonError('');
        setIsAdding(false);
    };
    const handleUpdate = (index, updates) => {
        // Update local state immediately (optimistic update)
        const updated = [...localVariables];
        updated[index] = { ...updated[index], ...updates };
        setLocalVariables(updated);
        // Persist in background
        onChange(updated);
    };
    const handleDelete = (index) => {
        // Update local state immediately (optimistic update)
        const updated = localVariables.filter((_, i) => i !== index);
        setLocalVariables(updated);
        // Persist in background
        onChange(updated);
    };
    const handleCancel = () => {
        setIsAdding(false);
        setNewKey('');
        setNewType('string');
        setNewValue('');
        setNewDescription('');
        setNewCategory('');
        setError('');
        setJsonError('');
    };
    const renderValueInput = (type, value, onValueChange) => {
        if (type === 'boolean') {
            return (external_react_default().createElement("label", { style: {
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px',
                    cursor: 'pointer',
                    fontSize: '13px',
                    color: 'var(--theme-color-fg-default)'
                } },
                external_react_default().createElement("input", { type: "checkbox", checked: value === 'true', onChange: (e) => onValueChange(e.target.checked ? 'true' : 'false'), style: {
                        width: '16px',
                        height: '16px',
                        cursor: 'pointer'
                    } }),
                "Enabled"));
        }
        if (type === 'number') {
            return (external_react_default().createElement("input", { type: "number", value: value || '', onChange: (e) => onValueChange(e.target.value), placeholder: "0", style: {
                    width: '100%',
                    padding: '8px',
                    fontSize: '13px',
                    fontFamily: 'inherit',
                    backgroundColor: 'var(--theme-color-bg-3)',
                    border: '1px solid var(--theme-color-border-default)',
                    borderRadius: '4px',
                    color: 'var(--theme-color-fg-default)'
                } }));
        }
        if (type === 'color') {
            return (external_react_default().createElement("div", { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
                external_react_default().createElement("input", { type: "color", value: value || '#000000', onChange: (e) => onValueChange(e.target.value), style: {
                        width: '40px',
                        height: '32px',
                        border: '1px solid var(--theme-color-border-default)',
                        borderRadius: '4px',
                        cursor: 'pointer',
                        backgroundColor: 'transparent'
                    } }),
                external_react_default().createElement("div", { style: { flex: 1 } },
                    external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: value || '#000000', onChange: onValueChange }))));
        }
        if (type === 'array' || type === 'object') {
            return (external_react_default().createElement(JSONEditorButton, { value: value || (type === 'array' ? '[]' : '{}'), varType: type, onSave: (newValue) => {
                    onValueChange(newValue);
                    setJsonError('');
                } }));
        }
        return external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: value, onChange: onValueChange });
    };
    // Group variables by category
    const groupedVariables = {};
    localVariables.forEach((variable) => {
        const cat = variable.category || 'Uncategorized';
        if (!groupedVariables[cat]) {
            groupedVariables[cat] = [];
        }
        groupedVariables[cat].push(variable);
    });
    const categories = Object.keys(groupedVariables).sort((a, b) => {
        // Uncategorized always first
        if (a === 'Uncategorized')
            return -1;
        if (b === 'Uncategorized')
            return 1;
        return a.localeCompare(b);
    });
    return (external_react_default().createElement(CollapsableSection/* CollapsableSection */.M, { title: "Custom Variables", hasGutter: true, hasVisibleOverflow: true, hasTopDivider: true },
        external_react_default().createElement("div", { style: {
                fontSize: '11px',
                color: 'var(--theme-color-fg-muted)',
                marginBottom: '12px'
            } }, "Define custom config variables accessible via Noodl.Config.get('key')"),
        !isAdding && (external_react_default().createElement("div", { style: { display: 'flex', gap: '8px', marginBottom: '12px' } },
            external_react_default().createElement("button", { onClick: () => setIsAdding(true), style: {
                    flex: 1,
                    padding: '8px',
                    fontSize: '13px',
                    fontWeight: 500,
                    backgroundColor: 'var(--theme-color-primary)',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    cursor: 'pointer'
                } }, "+ Add Variable"),
            localVariables.length > 0 && (external_react_default().createElement("button", { onClick: () => {
                    if (window.confirm(`Delete all ${localVariables.length} variables?`)) {
                        setLocalVariables([]);
                        onChange([]);
                    }
                }, style: {
                    padding: '8px 12px',
                    fontSize: '13px',
                    fontWeight: 500,
                    backgroundColor: '#dc3545',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    cursor: 'pointer'
                } }, "Clear All")))),
        isAdding && (external_react_default().createElement("div", { style: {
                padding: '12px',
                marginBottom: '12px',
                backgroundColor: 'var(--theme-color-bg-2)',
                border: '1px solid var(--theme-color-border-default)',
                borderRadius: '4px'
            } },
            external_react_default().createElement("div", { style: { marginBottom: '8px' } },
                external_react_default().createElement("label", { style: {
                        display: 'block',
                        fontSize: '12px',
                        fontWeight: 500,
                        marginBottom: '4px',
                        color: 'var(--theme-color-fg-default)'
                    } }, "Key *"),
                external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: newKey, onChange: (value) => {
                        setNewKey(value);
                        setError('');
                    } })),
            external_react_default().createElement("div", { style: { marginBottom: '8px' } },
                external_react_default().createElement("label", { style: {
                        display: 'block',
                        fontSize: '12px',
                        fontWeight: 500,
                        marginBottom: '4px',
                        color: 'var(--theme-color-fg-default)'
                    } }, "Type"),
                external_react_default().createElement("select", { value: newType, onChange: (e) => {
                        const newT = e.target.value;
                        setNewType(newT);
                        // Set appropriate default values
                        if (newT === 'boolean')
                            setNewValue('false');
                        else if (newT === 'number')
                            setNewValue('0');
                        else if (newT === 'color')
                            setNewValue('#000000');
                        else if (newT === 'array')
                            setNewValue('[]');
                        else if (newT === 'object')
                            setNewValue('{}');
                        else
                            setNewValue('');
                        setJsonError('');
                    }, style: {
                        width: '100%',
                        padding: '8px',
                        fontSize: '13px',
                        fontFamily: 'inherit',
                        backgroundColor: 'var(--theme-color-bg-3)',
                        border: '1px solid var(--theme-color-border-default)',
                        borderRadius: '4px',
                        color: 'var(--theme-color-fg-default)',
                        cursor: 'pointer'
                    } }, ALL_TYPES.map((type) => (external_react_default().createElement("option", { key: type.value, value: type.value }, type.label))))),
            external_react_default().createElement("div", { style: { marginBottom: '8px' } },
                external_react_default().createElement("label", { style: {
                        display: 'block',
                        fontSize: '12px',
                        fontWeight: 500,
                        marginBottom: '4px',
                        color: 'var(--theme-color-fg-default)'
                    } }, "Value"),
                renderValueInput(newType, newValue, setNewValue)),
            external_react_default().createElement("div", { style: { marginBottom: '8px' } },
                external_react_default().createElement("label", { style: {
                        display: 'block',
                        fontSize: '12px',
                        fontWeight: 500,
                        marginBottom: '4px',
                        color: 'var(--theme-color-fg-default)'
                    } }, "Category (optional)"),
                external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: newCategory, onChange: setNewCategory })),
            external_react_default().createElement("div", { style: { marginBottom: '12px' } },
                external_react_default().createElement("label", { style: {
                        display: 'block',
                        fontSize: '12px',
                        fontWeight: 500,
                        marginBottom: '4px',
                        color: 'var(--theme-color-fg-default)'
                    } }, "Description"),
                external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: newDescription, onChange: setNewDescription })),
            error && (external_react_default().createElement("div", { style: {
                    padding: '8px',
                    marginBottom: '8px',
                    fontSize: '12px',
                    color: 'var(--theme-color-error)',
                    backgroundColor: 'var(--theme-color-error-bg)',
                    border: '1px solid var(--theme-color-error)',
                    borderRadius: '4px'
                } }, error)),
            jsonError && (external_react_default().createElement("div", { style: {
                    padding: '8px',
                    marginBottom: '8px',
                    fontSize: '12px',
                    color: 'var(--theme-color-error)',
                    backgroundColor: 'var(--theme-color-error-bg)',
                    border: '1px solid var(--theme-color-error)',
                    borderRadius: '4px'
                } }, jsonError)),
            external_react_default().createElement("div", { style: { display: 'flex', gap: '8px' } },
                external_react_default().createElement("button", { onClick: handleAdd, disabled: !!error || !!jsonError, style: {
                        flex: 1,
                        padding: '8px',
                        fontSize: '13px',
                        fontWeight: 500,
                        backgroundColor: error || jsonError ? 'var(--theme-color-bg-3)' : 'var(--theme-color-primary)',
                        color: error || jsonError ? 'var(--theme-color-fg-muted)' : 'white',
                        border: 'none',
                        borderRadius: '4px',
                        cursor: error || jsonError ? 'not-allowed' : 'pointer'
                    } }, "Add"),
                external_react_default().createElement("button", { onClick: handleCancel, style: {
                        flex: 1,
                        padding: '8px',
                        fontSize: '13px',
                        fontWeight: 500,
                        backgroundColor: 'var(--theme-color-bg-3)',
                        color: 'var(--theme-color-fg-default)',
                        border: '1px solid var(--theme-color-border-default)',
                        borderRadius: '4px',
                        cursor: 'pointer'
                    } }, "Cancel")))),
        localVariables.length === 0 && !isAdding && (external_react_default().createElement("div", { style: {
                padding: '16px',
                textAlign: 'center',
                fontSize: '13px',
                color: 'var(--theme-color-fg-muted)',
                backgroundColor: 'var(--theme-color-bg-2)',
                border: '1px dashed var(--theme-color-border-default)',
                borderRadius: '4px'
            } }, "No variables defined yet")),
        categories.map((category) => (external_react_default().createElement("div", { key: category, style: { marginBottom: '16px' } },
            categories.length > 1 && (external_react_default().createElement("div", { style: {
                    fontSize: '11px',
                    fontWeight: 600,
                    textTransform: 'uppercase',
                    color: 'var(--theme-color-fg-muted)',
                    marginBottom: '8px',
                    letterSpacing: '0.5px'
                } }, category)),
            groupedVariables[category].map((variable) => {
                const index = localVariables.indexOf(variable);
                return (external_react_default().createElement("div", { key: index, style: {
                        padding: '12px',
                        marginBottom: '8px',
                        backgroundColor: 'var(--theme-color-bg-2)',
                        border: '1px solid var(--theme-color-border-default)',
                        borderRadius: '4px'
                    } },
                    external_react_default().createElement("div", { style: {
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'space-between',
                            marginBottom: '8px'
                        } },
                        external_react_default().createElement("div", { style: { display: 'flex', alignItems: 'center', gap: '12px', flex: 1 } },
                            external_react_default().createElement("span", { style: {
                                    fontSize: '13px',
                                    fontWeight: 500,
                                    fontFamily: 'monospace',
                                    color: 'var(--theme-color-fg-default)'
                                } }, variable.key),
                            external_react_default().createElement("span", { style: {
                                    fontSize: '11px',
                                    padding: '2px 6px',
                                    backgroundColor: 'var(--theme-color-bg-3)',
                                    border: '1px solid var(--theme-color-border-default)',
                                    borderRadius: '3px',
                                    color: 'var(--theme-color-fg-muted)'
                                } }, variable.type)),
                        external_react_default().createElement("button", { onClick: () => handleDelete(index), title: "Delete variable", style: {
                                padding: '4px 10px',
                                fontSize: '16px',
                                fontWeight: 'bold',
                                backgroundColor: '#dc3545',
                                color: 'white',
                                border: 'none',
                                borderRadius: '4px',
                                cursor: 'pointer',
                                minWidth: '28px',
                                lineHeight: 1
                            } }, "\u2715")),
                    external_react_default().createElement("div", { style: { marginBottom: '8px' } },
                        external_react_default().createElement("label", { style: {
                                display: 'block',
                                fontSize: '11px',
                                fontWeight: 500,
                                marginBottom: '4px',
                                color: 'var(--theme-color-fg-muted)'
                            } }, "Value"),
                        renderValueInput(variable.type, serializeValue(variable), (value) => handleUpdate(index, { value: parseValue(variable.type, value) }))),
                    variable.description && (external_react_default().createElement("div", { style: {
                            fontSize: '11px',
                            color: 'var(--theme-color-fg-muted)',
                            fontStyle: 'italic',
                            marginTop: '4px'
                        } }, variable.description))));
            }))))));
}

;// ./src/editor/src/views/panels/AppSetupPanel/AppSetupPanel.tsx








function AppSetupPanel() {
    const [, forceUpdate] = (0,external_react_.useState)(0);
    // Listen for metadata changes to refresh the panel
    (0,useEventListener/* useEventListener */.M)(projectmodel.ProjectModel.instance, 'ProjectModel.metadataChanged', (0,external_react_.useCallback)((data) => {
        if (data.key === 'appConfig') {
            forceUpdate((prev) => prev + 1);
        }
    }, []));
    const config = projectmodel.ProjectModel.instance.getAppConfig();
    const updateIdentity = (0,external_react_.useCallback)((updates) => {
        const currentConfig = projectmodel.ProjectModel.instance.getAppConfig();
        projectmodel.ProjectModel.instance.updateAppConfig({
            identity: { ...currentConfig.identity, ...updates }
        });
    }, []);
    const updateSEO = (0,external_react_.useCallback)((updates) => {
        const currentConfig = projectmodel.ProjectModel.instance.getAppConfig();
        projectmodel.ProjectModel.instance.updateAppConfig({
            seo: { ...currentConfig.seo, ...updates }
        });
    }, []);
    const updatePWA = (0,external_react_.useCallback)((updates) => {
        const currentConfig = projectmodel.ProjectModel.instance.getAppConfig();
        projectmodel.ProjectModel.instance.updateAppConfig({
            pwa: { ...(currentConfig.pwa || {}), ...updates }
        });
    }, []);
    const updateVariables = (0,external_react_.useCallback)((variables) => {
        // Defer the update to avoid re-render race condition
        setTimeout(() => {
            projectmodel.ProjectModel.instance.updateAppConfig({
                variables
            });
        }, 0);
    }, []);
    return (external_react_default().createElement(BasePanel, { title: "App Setup", hasContentScroll: true },
        external_react_default().createElement(IdentitySection, { identity: config.identity, onChange: updateIdentity }),
        external_react_default().createElement(SEOSection, { seo: config.seo, identity: config.identity, onChange: updateSEO }),
        external_react_default().createElement(PWASection, { pwa: config.pwa, onChange: updatePWA }),
        external_react_default().createElement(VariablesSection, { variables: config.variables, onChange: updateVariables })));
}

// EXTERNAL MODULE: ./src/editor/src/utils/model.ts
var utils_model = __webpack_require__(81267);
;// ./src/editor/src/models/BackendServices/presets.ts
/**
 * Backend Presets
 *
 * Pre-configured endpoint patterns for popular BaaS platforms.
 * These can be customized by users after selection.
 *
 * @module BackendServices
 * @since 1.2.0
 */
/**
 * Directus preset configuration
 * @see https://docs.directus.io/reference/introduction.html
 */
const directusPreset = {
    type: 'directus',
    displayName: 'Directus',
    description: 'Open source headless CMS with powerful REST API and admin panel',
    icon: 'directus',
    docsUrl: 'https://docs.directus.io/reference/introduction.html',
    urlPlaceholder: 'https://your-directus-instance.com',
    authHelpText: 'Configure tokens from Directus Admin > Settings > Access Tokens',
    adminKeyHelp: `**Admin API Key Setup (Directus)**

1. Go to **Settings → Access Tokens** in your Directus admin panel
2. Click **Create Token** and give it a descriptive name (e.g., "Noodl Schema Access")
3. Set the role to **Admin** or a custom role with:
   - Read access to \`directus_fields\` (required for schema)
   - Read access to \`directus_collections\` (required for table list)
4. Copy the generated token

**Note:** This token is only used in the editor for fetching your database structure. It will NOT be published to your deployed app.`,
    publicKeyHelp: `**Public API Key Setup (Directus)**

1. Go to **Settings → Access Tokens** in your Directus admin panel  
2. Create a new token with the **Public** role (or a custom limited role)
3. Configure which collections this role can access:
   - Go to **Settings → Roles & Permissions → Public**
   - Enable **read** permissions only on collections you want public
   - Example: Allow reading "products" but not "users"
4. Copy the generated token

**⚠️ Warning:** This token WILL be visible in your deployed app. Only grant access to data that should be publicly readable.`,
    defaultAuth: {
        method: 'bearer',
        adminToken: '',
        publicToken: ''
    },
    endpoints: {
        list: '/items/{table}',
        get: '/items/{table}/{id}',
        create: '/items/{table}',
        update: '/items/{table}/{id}',
        delete: '/items/{table}/{id}',
        schema: '/fields'
    },
    responseConfig: {
        dataPath: 'data',
        totalCountPath: 'meta.total_count',
        paginationType: 'offset',
        offsetParam: 'offset',
        limitParam: 'limit'
    }
};
/**
 * Supabase preset configuration
 * @see https://supabase.com/docs/guides/api
 */
const supabasePreset = {
    type: 'supabase',
    displayName: 'Supabase',
    description: 'Open source Firebase alternative with PostgreSQL database',
    icon: 'supabase',
    docsUrl: 'https://supabase.com/docs/guides/api',
    urlPlaceholder: 'https://your-project.supabase.co',
    authHelpText: 'Find your keys in Supabase Dashboard > Settings > API',
    adminKeyHelp: `**Admin API Key Setup (Supabase)**

1. Go to your Supabase project dashboard
2. Navigate to **Settings → API**
3. Under "Project API Keys", find the **service_role** key
4. Click "Reveal" and copy the key

**Important:** The service_role key bypasses Row Level Security (RLS). This gives full database access which is needed for schema introspection.

**Note:** This key is only used in the editor. It will NOT be published to your deployed app.`,
    publicKeyHelp: `**Public API Key Setup (Supabase)**

1. Go to your Supabase project dashboard
2. Navigate to **Settings → API**
3. Under "Project API Keys", find the **anon** (public) key
4. Copy this key

**Security with RLS:**
The anon key works with Row Level Security (RLS) policies. Make sure to:
- Enable RLS on tables that should have restricted access
- Create policies for what anonymous users can read
- Example policy: Allow reading products where \`is_published = true\`

**⚠️ Warning:** This key WILL be visible in your deployed app. Use RLS policies to control data access.`,
    defaultAuth: {
        method: 'api-key',
        apiKeyHeader: 'apikey',
        adminToken: '',
        publicToken: ''
    },
    endpoints: {
        list: '/rest/v1/{table}',
        get: '/rest/v1/{table}?id=eq.{id}',
        create: '/rest/v1/{table}',
        update: '/rest/v1/{table}?id=eq.{id}',
        delete: '/rest/v1/{table}?id=eq.{id}',
        schema: '/rest/v1/' // Returns OpenAPI spec
    },
    responseConfig: {
        dataPath: '', // Supabase returns array directly
        totalCountPath: '', // Needs special header: Prefer: count=exact
        paginationType: 'offset',
        offsetParam: 'offset',
        limitParam: 'limit'
    }
};
/**
 * Pocketbase preset configuration
 * @see https://pocketbase.io/docs/api-records/
 */
const pocketbasePreset = {
    type: 'pocketbase',
    displayName: 'Pocketbase',
    description: 'Lightweight backend in a single binary with SQLite',
    icon: 'pocketbase',
    docsUrl: 'https://pocketbase.io/docs/api-records/',
    urlPlaceholder: 'http://localhost:8090',
    authHelpText: 'Use admin credentials for schema access',
    adminKeyHelp: `**Admin API Key Setup (Pocketbase)**

1. Start your Pocketbase instance and go to the admin UI (typically /_/)
2. Navigate to **Settings → Admins**
3. You can either:
   - Use your admin email/password for authentication, OR
   - Create an admin API token if your version supports it

**Alternative - Using Admin Auth:**
For Pocketbase, you may need to use admin email + password authentication instead of a static token. The editor will handle this appropriately.

**Note:** Admin access is only used in the editor for fetching collections and their schemas. It will NOT be published.`,
    publicKeyHelp: `**Public API Key Setup (Pocketbase)**

Pocketbase uses **API Rules** instead of API keys for public access:

1. Go to your Pocketbase admin UI
2. Navigate to **Collections** and select a collection
3. Click **API Rules** tab
4. Configure rules for anonymous access:
   - **List rule:** Leave empty for public read, or add conditions
   - **View rule:** Leave empty for public single-item read
   - Example: \`is_published = true\` to only show published items

**No Public Token Needed:**
If you've configured API rules to allow anonymous access, you can leave this field empty. Pocketbase will allow access based on your rules.

**⚠️ Note:** API rules determine what unauthenticated users can access in your deployed app.`,
    defaultAuth: {
        method: 'bearer',
        adminToken: '',
        publicToken: ''
    },
    endpoints: {
        list: '/api/collections/{table}/records',
        get: '/api/collections/{table}/records/{id}',
        create: '/api/collections/{table}/records',
        update: '/api/collections/{table}/records/{id}',
        delete: '/api/collections/{table}/records/{id}',
        schema: '/api/collections'
    },
    responseConfig: {
        dataPath: 'items',
        totalCountPath: 'totalItems',
        paginationType: 'page',
        offsetParam: 'page',
        limitParam: 'perPage'
    }
};
/**
 * Custom REST API preset (starting point for manual configuration)
 */
const customPreset = {
    type: 'custom',
    displayName: 'Custom REST API',
    description: 'Configure any REST API with custom endpoints',
    icon: 'api',
    docsUrl: '',
    urlPlaceholder: 'https://api.example.com',
    authHelpText: 'Configure authentication based on your API requirements',
    adminKeyHelp: `**Admin API Key Setup (Custom REST)**

For schema introspection, you need an API key or token that has permission to:
- Read your API's schema endpoint
- Access metadata about tables/collections and their fields

This will depend on your specific API implementation. Common patterns:
- Bearer token with admin scope
- API key with read-all permissions
- Service account credentials

**Note:** This key is only used in the editor for development. It will NOT be published to your deployed app.`,
    publicKeyHelp: `**Public API Key Setup (Custom REST)**

If your API supports unauthenticated or limited-access requests, configure:
- A public API key with restricted permissions
- A read-only token for specific resources
- Or leave empty if your API handles public access differently

**⚠️ Warning:** If you provide a public key, it WILL be included in your deployed app and visible to end users. Only use keys that are safe to expose publicly.`,
    defaultAuth: {
        method: 'bearer',
        adminToken: '',
        publicToken: ''
    },
    endpoints: {
        list: '/{table}',
        get: '/{table}/{id}',
        create: '/{table}',
        update: '/{table}/{id}',
        delete: '/{table}/{id}',
        schema: '/schema'
    },
    responseConfig: {
        dataPath: 'data',
        totalCountPath: 'total',
        paginationType: 'offset',
        offsetParam: 'offset',
        limitParam: 'limit'
    }
};
/**
 * All available presets
 */
const backendPresets = {
    directus: directusPreset,
    supabase: supabasePreset,
    pocketbase: pocketbasePreset,
    custom: customPreset
};
/**
 * Get a preset by type
 */
function getPreset(type) {
    return backendPresets[type] || customPreset;
}
/**
 * Get all presets as an array (useful for UI)
 */
function getAllPresets() {
    return Object.values(backendPresets);
}
/**
 * Get presets excluding custom (for preset selection UI)
 */
function getPresetOptions() {
    return [directusPreset, supabasePreset, pocketbasePreset];
}

;// ./src/editor/src/models/BackendServices/types.ts
/**
 * Backend Services Types
 *
 * Type definitions for the BYOB (Bring Your Own Backend) system.
 * Supports Directus, Supabase, Pocketbase, and custom REST APIs.
 *
 * @module BackendServices
 * @since 1.2.0
 */
// ============================================================================
// Event Types
// ============================================================================
/**
 * Events emitted by BackendServices
 */
var BackendServicesEvent;
(function (BackendServicesEvent) {
    /** A backend was added, updated, or deleted */
    BackendServicesEvent["BackendsChanged"] = "BackendsChanged";
    /** The active backend changed */
    BackendServicesEvent["ActiveBackendChanged"] = "ActiveBackendChanged";
    /** Schema was fetched for a backend */
    BackendServicesEvent["SchemaUpdated"] = "SchemaUpdated";
    /** Connection status changed for a backend */
    BackendServicesEvent["StatusChanged"] = "StatusChanged";
})(BackendServicesEvent || (BackendServicesEvent = {}));

;// ./src/editor/src/models/BackendServices/BackendServices.ts
/**
 * Backend Services Model
 *
 * Manages backend configurations for the BYOB (Bring Your Own Backend) system.
 * Handles CRUD operations, connection testing, and schema introspection.
 *
 * @module BackendServices
 * @since 1.2.0
 */




/**
 * Generate a unique ID for a new backend
 */
function generateId() {
    return `backend_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
/**
 * Serialize a BackendConfig for storage
 */
function serializeBackend(backend) {
    var _a;
    return {
        ...backend,
        schema: backend.schema
            ? {
                ...backend.schema,
                fetchedAt: backend.schema.fetchedAt.toISOString()
            }
            : undefined,
        lastSynced: (_a = backend.lastSynced) === null || _a === void 0 ? void 0 : _a.toISOString(),
        createdAt: backend.createdAt.toISOString(),
        updatedAt: backend.updatedAt.toISOString()
    };
}
/**
 * Deserialize a BackendConfig from storage
 */
function deserializeBackend(data) {
    return {
        ...data,
        schema: data.schema
            ? {
                ...data.schema,
                fetchedAt: new Date(data.schema.fetchedAt)
            }
            : undefined,
        lastSynced: data.lastSynced ? new Date(data.lastSynced) : undefined,
        createdAt: new Date(data.createdAt),
        updatedAt: new Date(data.updatedAt)
    };
}
/**
 * Backend Services singleton
 * Manages all backend configurations for the current project
 */
class BackendServices extends utils_model/* Model */.K {
    constructor() {
        super(...arguments);
        this._isLoading = false;
        this._backends = [];
    }
    // ============================================================================
    // Getters
    // ============================================================================
    get isLoading() {
        return this._isLoading;
    }
    get backends() {
        return this._backends;
    }
    get activeBackendId() {
        return this._activeBackendId;
    }
    get activeBackend() {
        if (!this._activeBackendId)
            return undefined;
        return this._backends.find((b) => b.id === this._activeBackendId);
    }
    // ============================================================================
    // Initialization
    // ============================================================================
    /**
     * Initialize and load backends from the current project
     */
    async initialize() {
        this._isLoading = true;
        try {
            const project = projectmodel.ProjectModel.instance;
            if (!project) {
                console.warn('[BackendServices] No project loaded');
                return;
            }
            const metadata = project.getMetaData('backendServices');
            if (metadata) {
                this._backends = metadata.backends.map(deserializeBackend);
                this._activeBackendId = metadata.activeBackendId;
            }
            else {
                this._backends = [];
                this._activeBackendId = undefined;
            }
            this.notifyListeners(BackendServicesEvent.BackendsChanged);
        }
        finally {
            this._isLoading = false;
        }
    }
    /**
     * Reset the service (for project switching)
     */
    reset() {
        this._backends = [];
        this._activeBackendId = undefined;
        this._isLoading = false;
        this.notifyListeners(BackendServicesEvent.BackendsChanged);
    }
    // ============================================================================
    // Persistence
    // ============================================================================
    /**
     * Save backends to project metadata
     */
    saveToProject() {
        const project = projectmodel.ProjectModel.instance;
        if (!project) {
            console.warn('[BackendServices] Cannot save - no project loaded');
            return;
        }
        const metadata = {
            backends: this._backends.map(serializeBackend),
            activeBackendId: this._activeBackendId
        };
        project.setMetaData('backendServices', metadata);
        project.notifyListeners('backendServicesChanged');
    }
    // ============================================================================
    // CRUD Operations
    // ============================================================================
    /**
     * Get a backend by ID
     */
    getBackend(id) {
        return this._backends.find((b) => b.id === id);
    }
    /**
     * Create a new backend configuration
     */
    async createBackend(request) {
        const preset = getPreset(request.type);
        const now = new Date();
        const backend = {
            id: generateId(),
            name: request.name,
            type: request.type,
            url: request.url.replace(/\/$/, ''), // Remove trailing slash
            auth: {
                ...preset.defaultAuth,
                ...request.auth
            },
            endpoints: {
                ...preset.endpoints,
                ...request.endpoints
            },
            responseConfig: {
                ...preset.responseConfig,
                ...request.responseConfig
            },
            status: 'disconnected',
            createdAt: now,
            updatedAt: now
        };
        this._backends.push(backend);
        // If this is the first backend, make it active
        if (this._backends.length === 1) {
            this._activeBackendId = backend.id;
            this.notifyListeners(BackendServicesEvent.ActiveBackendChanged, backend.id);
        }
        this.saveToProject();
        this.notifyListeners(BackendServicesEvent.BackendsChanged);
        return backend;
    }
    /**
     * Update an existing backend configuration
     */
    async updateBackend(request) {
        var _a;
        const index = this._backends.findIndex((b) => b.id === request.id);
        if (index === -1) {
            throw new Error(`Backend not found: ${request.id}`);
        }
        const existing = this._backends[index];
        const updated = {
            ...existing,
            name: (_a = request.name) !== null && _a !== void 0 ? _a : existing.name,
            url: request.url ? request.url.replace(/\/$/, '') : existing.url,
            auth: request.auth ? { ...existing.auth, ...request.auth } : existing.auth,
            endpoints: request.endpoints ? { ...existing.endpoints, ...request.endpoints } : existing.endpoints,
            responseConfig: request.responseConfig
                ? { ...existing.responseConfig, ...request.responseConfig }
                : existing.responseConfig,
            updatedAt: new Date()
        };
        this._backends[index] = updated;
        this.saveToProject();
        this.notifyListeners(BackendServicesEvent.BackendsChanged);
        return updated;
    }
    /**
     * Delete a backend configuration
     */
    async deleteBackend(id) {
        const index = this._backends.findIndex((b) => b.id === id);
        if (index === -1) {
            return false;
        }
        this._backends.splice(index, 1);
        // If we deleted the active backend, clear it or pick another
        if (this._activeBackendId === id) {
            this._activeBackendId = this._backends.length > 0 ? this._backends[0].id : undefined;
            this.notifyListeners(BackendServicesEvent.ActiveBackendChanged, this._activeBackendId);
        }
        this.saveToProject();
        this.notifyListeners(BackendServicesEvent.BackendsChanged);
        return true;
    }
    /**
     * Set the active backend
     */
    setActiveBackend(id) {
        if (id && !this._backends.find((b) => b.id === id)) {
            console.warn(`[BackendServices] Backend not found: ${id}`);
            return;
        }
        this._activeBackendId = id;
        this.saveToProject();
        this.notifyListeners(BackendServicesEvent.ActiveBackendChanged, id);
    }
    // ============================================================================
    // Connection Testing
    // ============================================================================
    /**
     * Test connection to a backend
     */
    async testConnection(backendOrConfig) {
        const startTime = Date.now();
        // Determine URL and auth
        const url = backendOrConfig.url.replace(/\/$/, '');
        const auth = backendOrConfig.auth;
        const preset = getPreset(backendOrConfig.type);
        const endpoints = 'endpoints' in backendOrConfig ? backendOrConfig.endpoints : preset.endpoints;
        // Build headers - use adminToken for schema introspection (editor-only)
        const headers = {
            'Content-Type': 'application/json'
        };
        // Use adminToken for testing connection (schema access requires admin permissions)
        const token = auth.adminToken;
        if (auth.method === 'bearer' && token) {
            headers['Authorization'] = `Bearer ${token}`;
        }
        else if (auth.method === 'api-key' && token) {
            const headerName = auth.apiKeyHeader || 'X-API-Key';
            headers[headerName] = token;
        }
        else if (auth.method === 'basic' && auth.username && auth.password) {
            const encoded = btoa(`${auth.username}:${auth.password}`);
            headers['Authorization'] = `Basic ${encoded}`;
        }
        try {
            // Try to fetch schema endpoint as a connectivity test (requires admin token)
            const schemaUrl = `${url}${endpoints.schema}`;
            const response = await fetch(schemaUrl, {
                method: 'GET',
                headers
            });
            const responseTime = Date.now() - startTime;
            if (response.ok) {
                // Update status if this is an existing backend
                if ('id' in backendOrConfig) {
                    this.updateBackendStatus(backendOrConfig.id, 'connected');
                }
                return {
                    success: true,
                    message: `Connected successfully (${responseTime}ms)`,
                    responseTime
                };
            }
            else {
                // Get error details for better error messages
                const errorBody = await response.text().catch(() => '');
                const message = response.status === 401 || response.status === 403
                    ? `Authentication failed${errorBody ? `: ${errorBody.slice(0, 100)}` : ''}`
                    : `HTTP ${response.status}: ${response.statusText}`;
                if ('id' in backendOrConfig) {
                    this.updateBackendStatus(backendOrConfig.id, 'error', message);
                }
                return {
                    success: false,
                    message,
                    responseTime
                };
            }
        }
        catch (error) {
            const message = error instanceof Error ? error.message : 'Connection failed';
            if ('id' in backendOrConfig) {
                this.updateBackendStatus(backendOrConfig.id, 'error', message);
            }
            return {
                success: false,
                message: `Connection error: ${message}`
            };
        }
    }
    /**
     * Update the connection status of a backend
     */
    updateBackendStatus(id, status, errorMessage) {
        const backend = this._backends.find((b) => b.id === id);
        if (!backend)
            return;
        backend.status = status;
        backend.lastError = errorMessage;
        backend.updatedAt = new Date();
        this.saveToProject();
        this.notifyListeners(BackendServicesEvent.StatusChanged, id, status);
    }
    // ============================================================================
    // Schema Introspection
    // ============================================================================
    /**
     * Fetch schema from a backend
     */
    async fetchSchema(backendId) {
        const backend = this._backends.find((b) => b.id === backendId);
        if (!backend) {
            throw new Error(`Backend not found: ${backendId}`);
        }
        // Build headers - use adminToken for schema introspection (editor-only)
        const headers = {
            'Content-Type': 'application/json'
        };
        // Use adminToken for schema fetching (requires admin/service permissions)
        const token = backend.auth.adminToken;
        if (backend.auth.method === 'bearer' && token) {
            headers['Authorization'] = `Bearer ${token}`;
        }
        else if (backend.auth.method === 'api-key' && token) {
            const headerName = backend.auth.apiKeyHeader || 'X-API-Key';
            headers[headerName] = token;
        }
        try {
            const schemaUrl = `${backend.url}${backend.endpoints.schema}`;
            const response = await fetch(schemaUrl, {
                method: 'GET',
                headers
            });
            if (!response.ok) {
                throw new Error(`Failed to fetch schema: HTTP ${response.status}`);
            }
            const data = await response.json();
            // Parse schema based on backend type
            const schema = this.parseSchemaResponse(backend.type, data);
            // Update backend with schema
            backend.schema = schema;
            backend.lastSynced = new Date();
            backend.status = 'connected';
            backend.updatedAt = new Date();
            this.saveToProject();
            this.notifyListeners(BackendServicesEvent.SchemaUpdated, backendId);
            return schema;
        }
        catch (error) {
            const message = error instanceof Error ? error.message : 'Schema fetch failed';
            this.updateBackendStatus(backendId, 'error', message);
            throw error;
        }
    }
    /**
     * Parse schema response based on backend type
     */
    parseSchemaResponse(type, data) {
        const now = new Date();
        // Default empty schema
        const schema = {
            version: now.getTime().toString(),
            fetchedAt: now,
            collections: []
        };
        if (type === 'directus') {
            return this.parseDirectusSchema(data, schema);
        }
        else if (type === 'supabase') {
            return this.parseSupabaseSchema(data, schema);
        }
        else if (type === 'pocketbase') {
            return this.parsePocketbaseSchema(data, schema);
        }
        // For custom, try to parse as a generic schema format
        return this.parseGenericSchema(data, schema);
    }
    /**
     * Parse Directus schema from /fields endpoint
     */
    parseDirectusSchema(data, schema) {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        // Directus returns: { data: [{ collection, field, type, ... }] }
        const fieldsData = (data === null || data === void 0 ? void 0 : data.data) || [];
        const collectionMap = new Map();
        for (const field of fieldsData) {
            // Only skip if collection name is missing - include system tables (directus_*)
            if (!field.collection)
                continue;
            if (!collectionMap.has(field.collection)) {
                collectionMap.set(field.collection, {
                    name: field.collection,
                    displayName: field.collection,
                    fields: [],
                    primaryKey: 'id'
                });
            }
            const collection = collectionMap.get(field.collection);
            collection.fields.push({
                name: field.field,
                displayName: field.field,
                type: field.type,
                nativeType: field.type,
                required: ((_a = field.schema) === null || _a === void 0 ? void 0 : _a.is_nullable) === false,
                primaryKey: (_b = field.schema) === null || _b === void 0 ? void 0 : _b.is_primary_key,
                unique: (_c = field.schema) === null || _c === void 0 ? void 0 : _c.is_unique,
                defaultValue: (_d = field.schema) === null || _d === void 0 ? void 0 : _d.default_value,
                enumValues: (_g = (_f = (_e = field.meta) === null || _e === void 0 ? void 0 : _e.options) === null || _f === void 0 ? void 0 : _f.choices) === null || _g === void 0 ? void 0 : _g.map((c) => c.value)
            });
            if ((_h = field.schema) === null || _h === void 0 ? void 0 : _h.is_primary_key) {
                collection.primaryKey = field.field;
            }
        }
        schema.collections = Array.from(collectionMap.values());
        return schema;
    }
    /**
     * Parse Supabase schema from OpenAPI spec
     */
    parseSupabaseSchema(data, schema) {
        // Supabase returns OpenAPI spec with definitions/paths
        const openApi = data;
        if (openApi.definitions) {
            for (const [tableName, tableDef] of Object.entries(openApi.definitions)) {
                const fields = tableDef.properties &&
                    Object.entries(tableDef.properties).map(([fieldName, fieldDef]) => ({
                        name: fieldName,
                        displayName: fieldName,
                        type: fieldDef.type || 'unknown',
                        nativeType: fieldDef.format || fieldDef.type || 'unknown',
                        required: false
                    }));
                schema.collections.push({
                    name: tableName,
                    displayName: tableName,
                    fields: fields || [],
                    primaryKey: 'id'
                });
            }
        }
        return schema;
    }
    /**
     * Parse Pocketbase schema from /api/collections
     */
    parsePocketbaseSchema(data, schema) {
        var _a;
        // Pocketbase returns: [{ id, name, schema: [{ name, type, required, ... }] }]
        const collections = Array.isArray(data) ? data : (data === null || data === void 0 ? void 0 : data.items) || [];
        for (const col of collections) {
            if (col.system)
                continue;
            schema.collections.push({
                name: col.name,
                displayName: col.name,
                fields: ((_a = col.schema) === null || _a === void 0 ? void 0 : _a.map((f) => {
                    var _a;
                    return ({
                        name: f.name,
                        displayName: f.name,
                        type: f.type,
                        nativeType: f.type,
                        required: f.required || false,
                        enumValues: (_a = f.options) === null || _a === void 0 ? void 0 : _a.values
                    });
                })) || [],
                primaryKey: 'id'
            });
        }
        return schema;
    }
    /**
     * Parse generic schema format
     */
    parseGenericSchema(data, schema) {
        var _a;
        // Try to parse as array of collections or object with collections property
        const collections = Array.isArray(data)
            ? data
            : (data === null || data === void 0 ? void 0 : data.collections) ||
                (data === null || data === void 0 ? void 0 : data.tables) ||
                [];
        for (const col of collections) {
            if (!col.name)
                continue;
            schema.collections.push({
                name: col.name,
                displayName: col.name,
                fields: ((_a = col.fields) === null || _a === void 0 ? void 0 : _a.map((f) => ({
                    name: f.name,
                    displayName: f.name,
                    type: f.type || 'unknown',
                    nativeType: f.type || 'unknown',
                    required: false
                }))) || [],
                primaryKey: 'id'
            });
        }
        return schema;
    }
}
BackendServices.instance = new BackendServices();

;// ./src/editor/src/models/BackendServices/index.ts
/**
 * Backend Services Module
 *
 * BYOB (Bring Your Own Backend) system for connecting to external databases.
 * Supports Directus, Supabase, Pocketbase, and custom REST APIs.
 *
 * @module BackendServices
 * @since 1.2.0
 */




// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/HtmlRenderer/index.ts + 2 modules
var HtmlRenderer = __webpack_require__(88569);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/popups/ConfirmationDialog/ConfirmationDialog.module.scss
var ConfirmationDialog_module = __webpack_require__(46054);
;// ../noodl-core-ui/src/components/popups/ConfirmationDialog/ConfirmationDialog.module.scss

      
      
      
      
      
      
      
      
      

var ConfirmationDialog_module_options = {};

ConfirmationDialog_module_options.styleTagTransform = (styleTagTransform_default());
ConfirmationDialog_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ConfirmationDialog_module_options.insert = insertBySelector_default().bind(null, "head");
    
ConfirmationDialog_module_options.domAPI = (styleDomAPI_default());
ConfirmationDialog_module_options.insertStyleElement = (insertStyleElement_default());

var ConfirmationDialog_module_update = injectStylesIntoStyleTag_default()(ConfirmationDialog_module/* default */.A, ConfirmationDialog_module_options);




       /* harmony default export */ const ConfirmationDialog_ConfirmationDialog_module = (ConfirmationDialog_module/* default */.A && ConfirmationDialog_module/* default */.A.locals ? ConfirmationDialog_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/popups/ConfirmationDialog/ConfirmationDialog.tsx







function ConfirmationDialog({ title = 'Please confirm', message, confirmButtonLabel = 'Continue', cancelButtonLabel = 'Cancel', isVisible, isDangerousAction, isCancelButtonHidden, onConfirm, onCancel }) {
    return (external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { isVisible: isVisible, hasBackdrop: true, onClose: onCancel },
        external_react_default().createElement("div", { className: ConfirmationDialog_ConfirmationDialog_module['Root'] },
            external_react_default().createElement(PopupSection, { title: title, hasBottomBorder: true }, message && external_react_default().createElement(typography_Text/* Text */.EY, null, message)),
            external_react_default().createElement(PopupSection, null,
                external_react_default().createElement(Container, { direction: ContainerDirection.Horizontal },
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: isDangerousAction ? inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Danger : inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Cta, label: confirmButtonLabel, hasRightSpacing: true, onClick: onConfirm }),
                    !isCancelButtonHidden && external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, label: cancelButtonLabel, onClick: onCancel }))))));
}

;// ../noodl-core-ui/src/components/popups/ConfirmationDialog/ConfirmationDialog.hooks.tsx



function useConfirmationDialog(options, skipRejectCallback) {
    const [promise, setPromise] = (0,external_react_.useState)(null);
    function confirmationPromise() {
        return new Promise((resolve, reject) => {
            setPromise({ resolve, reject });
        });
    }
    const Dialog = (0,external_react_.useCallback)(() => (external_react_default().createElement(ConfirmationDialog, { isVisible: promise !== null, title: options.title, confirmButtonLabel: options.confirmButtonLabel, cancelButtonLabel: options.cancelButtonLabel, message: options.message, isDangerousAction: options.isDangerousAction, isCancelButtonHidden: options.isCancelButtonHidden, onConfirm: () => {
            promise === null || promise === void 0 ? void 0 : promise.resolve();
            setPromise(null);
        }, onCancel: () => {
            !skipRejectCallback && (promise === null || promise === void 0 ? void 0 : promise.reject(false));
            setPromise(null);
        } })), [
        promise,
        skipRejectCallback,
        options.title,
        options.confirmButtonLabel,
        options.cancelButtonLabel,
        options.message,
        options.isDangerousAction,
        options.isCancelButtonHidden
    ]);
    return [Dialog, confirmationPromise];
}
function useSimpleConfirmationDialog(options) {
    const [dialogMessage, setDialogMessage] = (0,external_react_.useState)('');
    const [Dialog, handleConfirmation] = useConfirmationDialog({
        ...options,
        message: external_react_default().createElement(HtmlRenderer/* HtmlRenderer */.j, { html: dialogMessage })
    });
    function handle(message) {
        setDialogMessage(message);
        return handleConfirmation();
    }
    return [Dialog, handle];
}

// EXTERNAL MODULE: ../noodl-core-ui/src/components/sidebar/Section/index.ts + 2 modules
var Section = __webpack_require__(60028);
;// ../noodl-core-ui/src/components/layout/Modal/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/BackendServicesPanel/AddBackendDialog/AddBackendDialog.module.scss
var AddBackendDialog_module = __webpack_require__(59048);
;// ./src/editor/src/views/panels/BackendServicesPanel/AddBackendDialog/AddBackendDialog.module.scss

      
      
      
      
      
      
      
      
      

var AddBackendDialog_module_options = {};

AddBackendDialog_module_options.styleTagTransform = (styleTagTransform_default());
AddBackendDialog_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      AddBackendDialog_module_options.insert = insertBySelector_default().bind(null, "head");
    
AddBackendDialog_module_options.domAPI = (styleDomAPI_default());
AddBackendDialog_module_options.insertStyleElement = (insertStyleElement_default());

var AddBackendDialog_module_update = injectStylesIntoStyleTag_default()(AddBackendDialog_module/* default */.A, AddBackendDialog_module_options);




       /* harmony default export */ const AddBackendDialog_AddBackendDialog_module = (AddBackendDialog_module/* default */.A && AddBackendDialog_module/* default */.A.locals ? AddBackendDialog_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/BackendServicesPanel/AddBackendDialog/AddBackendDialog.tsx
/**
 * Add Backend Dialog
 *
 * Modal dialog for adding new backend configurations.
 * Supports preset selection (Directus, Supabase, Pocketbase) and custom REST APIs.
 *
 * @module BackendServicesPanel
 * @since 1.2.0
 */













function HelpPopup({ content, onClose }) {
    return (external_react_default().createElement("div", { className: AddBackendDialog_AddBackendDialog_module.HelpPopupOverlay, onClick: onClose },
        external_react_default().createElement("div", { className: AddBackendDialog_AddBackendDialog_module.HelpPopup, onClick: (e) => e.stopPropagation() },
            external_react_default().createElement("div", { className: AddBackendDialog_AddBackendDialog_module.HelpPopupHeader },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, "Setup Instructions"),
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Close, size: common_Icon/* IconSize */.lK.Small, onClick: onClose })),
            external_react_default().createElement("div", { className: AddBackendDialog_AddBackendDialog_module.HelpPopupContent }, content.split('\n').map((line, i) => {
                // Handle bold text with **text**
                const parts = line.split(/(\*\*[^*]+\*\*)/g);
                return (external_react_default().createElement("p", { key: i, className: line.startsWith('**') ? AddBackendDialog_AddBackendDialog_module.HelpHeading : undefined }, parts.map((part, j) => {
                    if (part.startsWith('**') && part.endsWith('**')) {
                        return external_react_default().createElement("strong", { key: j }, part.slice(2, -2));
                    }
                    // Handle inline code with `text`
                    const codeParts = part.split(/(`[^`]+`)/g);
                    return codeParts.map((codePart, k) => {
                        if (codePart.startsWith('`') && codePart.endsWith('`')) {
                            return (external_react_default().createElement("code", { key: `${j}-${k}`, className: AddBackendDialog_AddBackendDialog_module.InlineCode }, codePart.slice(1, -1)));
                        }
                        return codePart;
                    });
                })));
            })))));
}
function AddBackendDialog({ isVisible, onClose, onCreated }) {
    const [selectedType, setSelectedType] = (0,external_react_.useState)('directus');
    const [name, setName] = (0,external_react_.useState)('');
    const [url, setUrl] = (0,external_react_.useState)('');
    const [adminToken, setAdminToken] = (0,external_react_.useState)('');
    const [publicToken, setPublicToken] = (0,external_react_.useState)('');
    const [isLoading, setIsLoading] = (0,external_react_.useState)(false);
    const [testResult, setTestResult] = (0,external_react_.useState)(null);
    const [showAdminHelp, setShowAdminHelp] = (0,external_react_.useState)(false);
    const [showPublicHelp, setShowPublicHelp] = (0,external_react_.useState)(false);
    const presetOptions = getPresetOptions();
    const selectedPreset = getPreset(selectedType);
    // Reset form when dialog opens
    external_react_default().useEffect(() => {
        if (isVisible) {
            setSelectedType('directus');
            setName('');
            setUrl('');
            setAdminToken('');
            setPublicToken('');
            setTestResult(null);
            setShowAdminHelp(false);
            setShowPublicHelp(false);
        }
    }, [isVisible]);
    const handleSelectPreset = (0,external_react_.useCallback)((preset) => {
        setSelectedType(preset.type);
        setTestResult(null);
    }, []);
    const handleTestConnection = (0,external_react_.useCallback)(async () => {
        if (!url) {
            setTestResult({ success: false, message: 'Please enter a URL' });
            return;
        }
        if (!adminToken) {
            setTestResult({ success: false, message: 'Please enter an Admin API Key to test connection' });
            return;
        }
        setIsLoading(true);
        setTestResult(null);
        try {
            const request = {
                name: name || 'Test',
                type: selectedType,
                url,
                auth: {
                    method: selectedPreset.defaultAuth.method,
                    adminToken,
                    publicToken,
                    apiKeyHeader: selectedPreset.defaultAuth.apiKeyHeader
                }
            };
            const result = await BackendServices.instance.testConnection(request);
            setTestResult(result);
        }
        catch (error) {
            setTestResult({
                success: false,
                message: error instanceof Error ? error.message : 'Connection test failed'
            });
        }
        finally {
            setIsLoading(false);
        }
    }, [url, name, selectedType, selectedPreset, adminToken, publicToken]);
    const handleCreate = (0,external_react_.useCallback)(async () => {
        if (!name || !url) {
            ToastLayer.ToastLayer.showError('Please fill in all required fields');
            return;
        }
        if (!adminToken) {
            ToastLayer.ToastLayer.showError('Admin API Key is required for schema introspection');
            return;
        }
        setIsLoading(true);
        try {
            const request = {
                name,
                type: selectedType,
                url,
                auth: {
                    method: selectedPreset.defaultAuth.method,
                    adminToken,
                    publicToken,
                    apiKeyHeader: selectedPreset.defaultAuth.apiKeyHeader
                }
            };
            await BackendServices.instance.createBackend(request);
            ToastLayer.ToastLayer.showSuccess(`Backend "${name}" created successfully`);
            onCreated();
        }
        catch (error) {
            ToastLayer.ToastLayer.showError(error instanceof Error ? error.message : 'Failed to create backend');
        }
        finally {
            setIsLoading(false);
        }
    }, [name, url, selectedType, selectedPreset, adminToken, publicToken, onCreated]);
    const isFormValid = name.trim().length > 0 && url.trim().length > 0 && adminToken.trim().length > 0;
    return (external_react_default().createElement(Modal, { isVisible: isVisible, onClose: onClose, title: "Add Backend" },
        external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: true },
            external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, hasBottomSpacing: true }, "Select a backend type"),
                external_react_default().createElement("div", { className: AddBackendDialog_AddBackendDialog_module.PresetGrid },
                    presetOptions.map((preset) => (external_react_default().createElement("button", { key: preset.type, type: "button", className: `${AddBackendDialog_AddBackendDialog_module.PresetCard} ${selectedType === preset.type ? AddBackendDialog_AddBackendDialog_module.Selected : ''}`, onClick: () => handleSelectPreset(preset) },
                        external_react_default().createElement("div", { className: AddBackendDialog_AddBackendDialog_module.PresetIcon }, preset.displayName.charAt(0)),
                        external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, preset.displayName),
                        external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } },
                            preset.description.substring(0, 50),
                            "...")))),
                    external_react_default().createElement("button", { type: "button", className: `${AddBackendDialog_AddBackendDialog_module.PresetCard} ${selectedType === 'custom' ? AddBackendDialog_AddBackendDialog_module.Selected : ''}`, onClick: () => handleSelectPreset(getPreset('custom')) },
                        external_react_default().createElement("div", { className: AddBackendDialog_AddBackendDialog_module.PresetIcon }, "?"),
                        external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, "Custom REST"),
                        external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } }, "Configure any REST API")))),
            external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
                external_react_default().createElement(TextInput, { label: "Name", value: name, onChange: (e) => setName(e.target.value), placeholder: `My ${selectedPreset.displayName} Backend`, hasBottomSpacing: true })),
            external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
                external_react_default().createElement(TextInput, { label: "URL", value: url, onChange: (e) => setUrl(e.target.value), placeholder: selectedPreset.urlPlaceholder, hasBottomSpacing: true })),
            external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
                external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { alignItems: 'center', marginBottom: '4px' } },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast, style: { flex: 1 } }, "Admin API Key (Required)"),
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Question, size: common_Icon/* IconSize */.lK.Small, onClick: () => setShowAdminHelp(true), testId: "admin-key-help" })),
                external_react_default().createElement(TextInput, { value: adminToken, onChange: (e) => setAdminToken(e.target.value), type: "password", placeholder: "Enter your admin/service API key" }),
                external_react_default().createElement("div", { className: AddBackendDialog_AddBackendDialog_module.FieldNote },
                    external_react_default().createElement("span", { className: AddBackendDialog_AddBackendDialog_module.LockIcon }, "\uD83D\uDD12"),
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } }, "Editor only \u2014 not published to deployed app"))),
            external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
                external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { alignItems: 'center', marginBottom: '4px' } },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast, style: { flex: 1 } }, "Public API Key (Optional)"),
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Question, size: common_Icon/* IconSize */.lK.Small, onClick: () => setShowPublicHelp(true), testId: "public-key-help" })),
                external_react_default().createElement(TextInput, { value: publicToken, onChange: (e) => setPublicToken(e.target.value), type: "password", placeholder: "Enter your public/anon API key" }),
                external_react_default().createElement("div", { className: AddBackendDialog_AddBackendDialog_module.FieldNote },
                    external_react_default().createElement("span", { className: AddBackendDialog_AddBackendDialog_module.WarningIcon }, "\u26A0\uFE0F"),
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } }, "Will be visible in deployed app \u2014 scope for public access only"))),
            testResult && (external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
                external_react_default().createElement("div", { className: AddBackendDialog_AddBackendDialog_module.TestResult, style: {
                        backgroundColor: testResult.success ? 'var(--theme-color-success-bg)' : 'var(--theme-color-danger-bg)',
                        borderColor: testResult.success ? 'var(--theme-color-success)' : 'var(--theme-color-danger)'
                    } },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast, style: {
                            color: testResult.success ? 'var(--theme-color-success)' : 'var(--theme-color-danger)'
                        } },
                        testResult.success ? '✓ ' : '✗ ',
                        testResult.message)))),
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true, UNSAFE_style: { justifyContent: 'flex-end' } },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onClose, isDisabled: isLoading }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Test Connection", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: handleTestConnection, isDisabled: isLoading || !url || !adminToken }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Create Backend", onClick: handleCreate, isDisabled: isLoading || !isFormValid }))),
        showAdminHelp && external_react_default().createElement(HelpPopup, { content: selectedPreset.adminKeyHelp, onClose: () => setShowAdminHelp(false) }),
        showPublicHelp && external_react_default().createElement(HelpPopup, { content: selectedPreset.publicKeyHelp, onClose: () => setShowPublicHelp(false) })));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/BackendServicesPanel/BackendCard/BackendCard.module.scss
var BackendCard_module = __webpack_require__(69820);
;// ./src/editor/src/views/panels/BackendServicesPanel/BackendCard/BackendCard.module.scss

      
      
      
      
      
      
      
      
      

var BackendCard_module_options = {};

BackendCard_module_options.styleTagTransform = (styleTagTransform_default());
BackendCard_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      BackendCard_module_options.insert = insertBySelector_default().bind(null, "head");
    
BackendCard_module_options.domAPI = (styleDomAPI_default());
BackendCard_module_options.insertStyleElement = (insertStyleElement_default());

var BackendCard_module_update = injectStylesIntoStyleTag_default()(BackendCard_module/* default */.A, BackendCard_module_options);




       /* harmony default export */ const BackendCard_BackendCard_module = (BackendCard_module/* default */.A && BackendCard_module/* default */.A.locals ? BackendCard_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/BackendServicesPanel/BackendCard/BackendCard.tsx
/**
 * Backend Card Component
 *
 * Displays a single backend configuration with status and actions.
 *
 * @module BackendServicesPanel
 * @since 1.2.0
 */








/**
 * Get status icon and color based on connection status
 */
function getStatusDisplay(status) {
    switch (status) {
        case 'connected':
            return { icon: common_Icon/* IconName */.$M.Check, color: 'var(--theme-color-success)', text: 'Connected' };
        case 'disconnected':
            return { icon: common_Icon/* IconName */.$M.CircleOpen, color: 'var(--theme-color-fg-default-shy)', text: 'Disconnected' };
        case 'error':
            return { icon: common_Icon/* IconName */.$M.WarningTriangle, color: 'var(--theme-color-danger)', text: 'Error' };
        case 'checking':
            return { icon: common_Icon/* IconName */.$M.Refresh, color: 'var(--theme-color-primary)', text: 'Checking...' };
        default:
            return { icon: common_Icon/* IconName */.$M.CircleOpen, color: 'var(--theme-color-fg-default-shy)', text: 'Unknown' };
    }
}
function BackendCard({ backend, isActive, onSetActive, onDelete, onTestConnection, onFetchSchema }) {
    const preset = getPreset(backend.type);
    const statusDisplay = getStatusDisplay(backend.status);
    return (external_react_default().createElement("div", { className: `${BackendCard_BackendCard_module.Root} ${isActive ? BackendCard_BackendCard_module.Active : ''}`, "data-test": `backend-card-${backend.id}` },
        external_react_default().createElement("div", { className: BackendCard_BackendCard_module.Header },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement("div", { className: BackendCard_BackendCard_module.TypeIcon },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud }, preset.displayName.charAt(0).toUpperCase())),
                external_react_default().createElement(Stack/* VStack */.Tk, null,
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, backend.name),
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } },
                        preset.displayName,
                        " \u2022 ",
                        backend.url))),
            isActive && (external_react_default().createElement("div", { className: BackendCard_BackendCard_module.ActiveBadge },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '10px' } }, "ACTIVE")))),
        external_react_default().createElement("div", { className: BackendCard_BackendCard_module.Status },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: statusDisplay.icon, size: common_Icon/* IconSize */.lK.Tiny, UNSAFE_style: { color: statusDisplay.color } }),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, statusDisplay.text),
                backend.lastSynced && (external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '10px' } },
                    "\u2022 Last sync: ",
                    new Date(backend.lastSynced).toLocaleTimeString()))),
            backend.lastError && (external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px', color: 'var(--theme-color-danger)' } }, backend.lastError))),
        backend.schema && backend.schema.collections.length > 0 && (external_react_default().createElement("div", { className: BackendCard_BackendCard_module.SchemaInfo },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } },
                backend.schema.collections.length,
                " collection",
                backend.schema.collections.length !== 1 ? 's' : ''))),
        external_react_default().createElement("div", { className: BackendCard_BackendCard_module.Actions },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                !isActive && (external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Set Active", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onSetActive })),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Test", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onTestConnection }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Sync Schema", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onFetchSchema }),
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Trash, size: common_Icon/* IconSize */.lK.Small, onClick: onDelete, testId: `delete-backend-${backend.id}` })))));
}

;// ./src/editor/src/views/panels/BackendServicesPanel/hooks/useLocalBackends.ts
/**
 * useLocalBackends
 *
 * React hook for managing local SQLite backends via IPC.
 * Provides state and actions for the BYOB local backend system.
 *
 * @module BackendServicesPanel/hooks/useLocalBackends
 * @since 1.2.0
 */

/**
 * Invoke IPC handler with error handling
 * Uses window.require('electron').ipcRenderer like GitHubOAuthService
 */
async function invokeIPC(channel, ...args) {
    try {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const { ipcRenderer } = window.require('electron');
        if (ipcRenderer === null || ipcRenderer === void 0 ? void 0 : ipcRenderer.invoke) {
            return await ipcRenderer.invoke(channel, ...args);
        }
        console.warn('[useLocalBackends] ipcRenderer not available');
        return null;
    }
    catch (error) {
        console.error(`[useLocalBackends] IPC error (${channel}):`, error);
        throw error;
    }
}
/**
 * Hook for managing local backends
 */
function useLocalBackends() {
    const [backends, setBackends] = (0,external_react_.useState)([]);
    const [isLoading, setIsLoading] = (0,external_react_.useState)(true);
    const [isOperating, setIsOperating] = (0,external_react_.useState)(false);
    const [error, setError] = (0,external_react_.useState)(null);
    // Fetch all backends and their statuses
    const refresh = (0,external_react_.useCallback)(async () => {
        setError(null);
        try {
            const list = await invokeIPC('backend:list');
            if (!list) {
                setBackends([]);
                return;
            }
            // Get status for each backend
            const backendsWithStatus = await Promise.all(list.map(async (backend) => {
                var _a;
                const status = await invokeIPC('backend:status', backend.id);
                return {
                    ...backend,
                    running: (_a = status === null || status === void 0 ? void 0 : status.running) !== null && _a !== void 0 ? _a : false,
                    endpoint: (status === null || status === void 0 ? void 0 : status.running) && (status === null || status === void 0 ? void 0 : status.port) ? `http://localhost:${status.port}` : undefined
                };
            }));
            setBackends(backendsWithStatus);
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to fetch backends';
            setError(message);
            console.error('[useLocalBackends] refresh error:', err);
        }
    }, []);
    // Initial load
    (0,external_react_.useEffect)(() => {
        setIsLoading(true);
        refresh().finally(() => setIsLoading(false));
    }, [refresh]);
    // Create a new backend
    const createBackend = (0,external_react_.useCallback)(async (name) => {
        setIsOperating(true);
        setError(null);
        try {
            const result = await invokeIPC('backend:create', name);
            await refresh();
            return result;
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to create backend';
            setError(message);
            return null;
        }
        finally {
            setIsOperating(false);
        }
    }, [refresh]);
    // Delete a backend
    const deleteBackend = (0,external_react_.useCallback)(async (id) => {
        setIsOperating(true);
        setError(null);
        try {
            await invokeIPC('backend:delete', id);
            await refresh();
            return true;
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to delete backend';
            setError(message);
            return false;
        }
        finally {
            setIsOperating(false);
        }
    }, [refresh]);
    // Start a backend
    const startBackend = (0,external_react_.useCallback)(async (id) => {
        setIsOperating(true);
        setError(null);
        try {
            await invokeIPC('backend:start', id);
            await refresh();
            return true;
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to start backend';
            setError(message);
            return false;
        }
        finally {
            setIsOperating(false);
        }
    }, [refresh]);
    // Stop a backend
    const stopBackend = (0,external_react_.useCallback)(async (id) => {
        setIsOperating(true);
        setError(null);
        try {
            await invokeIPC('backend:stop', id);
            await refresh();
            return true;
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to stop backend';
            setError(message);
            return false;
        }
        finally {
            setIsOperating(false);
        }
    }, [refresh]);
    // Export schema
    const exportSchema = (0,external_react_.useCallback)(async (id, format) => {
        setIsOperating(true);
        setError(null);
        try {
            const result = await invokeIPC('backend:export-schema', id, format);
            return result;
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to export schema';
            setError(message);
            return null;
        }
        finally {
            setIsOperating(false);
        }
    }, []);
    return {
        backends,
        isLoading,
        isOperating,
        error,
        refresh,
        createBackend,
        deleteBackend,
        startBackend,
        stopBackend,
        exportSchema
    };
}

// EXTERNAL MODULE: external "react-dom"
var external_react_dom_ = __webpack_require__(20180);
var external_react_dom_default = /*#__PURE__*/__webpack_require__.n(external_react_dom_);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/databrowser/DataBrowser.module.scss
var DataBrowser_module = __webpack_require__(84755);
;// ./src/editor/src/views/panels/databrowser/DataBrowser.module.scss

      
      
      
      
      
      
      
      
      

var DataBrowser_module_options = {};

DataBrowser_module_options.styleTagTransform = (styleTagTransform_default());
DataBrowser_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      DataBrowser_module_options.insert = insertBySelector_default().bind(null, "head");
    
DataBrowser_module_options.domAPI = (styleDomAPI_default());
DataBrowser_module_options.insertStyleElement = (insertStyleElement_default());

var DataBrowser_module_update = injectStylesIntoStyleTag_default()(DataBrowser_module/* default */.A, DataBrowser_module_options);




       /* harmony default export */ const databrowser_DataBrowser_module = (DataBrowser_module/* default */.A && DataBrowser_module/* default */.A.locals ? DataBrowser_module/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/databrowser/CellEditor.module.scss
var CellEditor_module = __webpack_require__(3762);
;// ./src/editor/src/views/panels/databrowser/CellEditor.module.scss

      
      
      
      
      
      
      
      
      

var CellEditor_module_options = {};

CellEditor_module_options.styleTagTransform = (styleTagTransform_default());
CellEditor_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      CellEditor_module_options.insert = insertBySelector_default().bind(null, "head");
    
CellEditor_module_options.domAPI = (styleDomAPI_default());
CellEditor_module_options.insertStyleElement = (insertStyleElement_default());

var CellEditor_module_update = injectStylesIntoStyleTag_default()(CellEditor_module/* default */.A, CellEditor_module_options);




       /* harmony default export */ const databrowser_CellEditor_module = (CellEditor_module/* default */.A && CellEditor_module/* default */.A.locals ? CellEditor_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/databrowser/CellEditor.tsx
/**
 * CellEditor
 *
 * Inline cell editor component with type-aware input controls.
 * Handles String, Number, Boolean, Date, Object, and Array types.
 *
 * @module panels/databrowser/CellEditor
 * @since 1.2.0
 */


/**
 * CellEditor component - type-aware inline editor
 */
function CellEditor({ value, type, onSave, onCancel, error }) {
    const [editValue, setEditValue] = (0,external_react_.useState)(() => {
        if (value === null || value === undefined)
            return '';
        if (typeof value === 'object')
            return JSON.stringify(value, null, 2);
        return String(value);
    });
    const [jsonError, setJsonError] = (0,external_react_.useState)(null);
    const [isFocused, setIsFocused] = (0,external_react_.useState)(false);
    const inputRef = (0,external_react_.useRef)(null);
    // Focus input on mount with delay to prevent immediate blur
    (0,external_react_.useEffect)(() => {
        const timer = setTimeout(() => {
            if (inputRef.current) {
                inputRef.current.focus();
                if (inputRef.current instanceof HTMLInputElement) {
                    inputRef.current.select();
                }
                setIsFocused(true);
            }
        }, 50);
        return () => clearTimeout(timer);
    }, []);
    // Handle keyboard events
    const handleKeyDown = (0,external_react_.useCallback)((e) => {
        if (e.key === 'Enter' && !e.shiftKey && type !== 'Object' && type !== 'Array') {
            e.preventDefault();
            handleSave();
        }
        else if (e.key === 'Escape') {
            onCancel();
        }
    }, [type, onCancel]);
    // Handle save with type conversion
    const handleSave = (0,external_react_.useCallback)(() => {
        let finalValue = editValue;
        try {
            switch (type) {
                case 'Number':
                    if (editValue.trim() === '') {
                        finalValue = null;
                    }
                    else {
                        finalValue = parseFloat(editValue);
                        if (isNaN(finalValue)) {
                            setJsonError('Invalid number');
                            return;
                        }
                    }
                    break;
                case 'Boolean':
                    // Boolean is handled by checkbox, just use editValue
                    finalValue = editValue === 'true';
                    break;
                case 'Date':
                    if (editValue.trim() === '') {
                        finalValue = null;
                    }
                    else {
                        finalValue = new Date(editValue).toISOString();
                    }
                    break;
                case 'Object':
                case 'Array':
                    if (editValue.trim() === '') {
                        finalValue = type === 'Array' ? [] : {};
                    }
                    else {
                        finalValue = JSON.parse(editValue);
                    }
                    break;
                default:
                    // String - use as-is
                    finalValue = editValue;
            }
            setJsonError(null);
            onSave(finalValue);
        }
        catch (err) {
            setJsonError('Invalid JSON');
        }
    }, [editValue, type, onSave]);
    // Boolean - render checkbox
    if (type === 'Boolean') {
        return (external_react_default().createElement("div", { className: databrowser_CellEditor_module.CellEditor },
            external_react_default().createElement("input", { type: "checkbox", checked: value === true || editValue === 'true', onChange: (e) => {
                    setEditValue(e.target.checked ? 'true' : 'false');
                    onSave(e.target.checked);
                }, onKeyDown: (e) => e.key === 'Escape' && onCancel() }),
            error && external_react_default().createElement("div", { className: databrowser_CellEditor_module.Error }, error)));
    }
    // Date - render datetime input
    if (type === 'Date') {
        const dateValue = value ? new Date(value).toISOString().slice(0, 16) : '';
        return (external_react_default().createElement("div", { className: databrowser_CellEditor_module.CellEditor },
            external_react_default().createElement("input", { ref: inputRef, type: "datetime-local", className: databrowser_CellEditor_module.DateInput, value: editValue || dateValue, onChange: (e) => setEditValue(e.target.value), onKeyDown: handleKeyDown, onBlur: () => isFocused && handleSave() }),
            (error || jsonError) && external_react_default().createElement("div", { className: databrowser_CellEditor_module.Error }, error || jsonError)));
    }
    // Object/Array - render textarea
    if (type === 'Object' || type === 'Array') {
        return (external_react_default().createElement("div", { className: databrowser_CellEditor_module.CellEditor },
            external_react_default().createElement("textarea", { ref: inputRef, className: databrowser_CellEditor_module.JsonEditor, value: editValue, onChange: (e) => {
                    setEditValue(e.target.value);
                    setJsonError(null);
                }, onKeyDown: (e) => {
                    if (e.key === 'Escape')
                        onCancel();
                }, rows: 5, spellCheck: false }),
            external_react_default().createElement("div", { className: databrowser_CellEditor_module.JsonActions },
                external_react_default().createElement("button", { className: databrowser_CellEditor_module.SaveButton, onClick: handleSave }, "Save"),
                external_react_default().createElement("button", { className: databrowser_CellEditor_module.CancelButton, onClick: onCancel }, "Cancel")),
            (error || jsonError) && external_react_default().createElement("div", { className: databrowser_CellEditor_module.Error }, error || jsonError)));
    }
    // Number - render number input
    if (type === 'Number') {
        return (external_react_default().createElement("div", { className: databrowser_CellEditor_module.CellEditor },
            external_react_default().createElement("input", { ref: inputRef, type: "number", className: databrowser_CellEditor_module.Input, value: editValue, onChange: (e) => setEditValue(e.target.value), onKeyDown: handleKeyDown, onBlur: () => isFocused && handleSave(), step: "any" }),
            (error || jsonError) && external_react_default().createElement("div", { className: databrowser_CellEditor_module.Error }, error || jsonError)));
    }
    // Default: String - render text input
    return (external_react_default().createElement("div", { className: databrowser_CellEditor_module.CellEditor },
        external_react_default().createElement("input", { ref: inputRef, type: "text", className: databrowser_CellEditor_module.Input, value: editValue, onChange: (e) => setEditValue(e.target.value), onKeyDown: handleKeyDown, onBlur: () => isFocused && handleSave() }),
        (error || jsonError) && external_react_default().createElement("div", { className: databrowser_CellEditor_module.Error }, error || jsonError)));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/databrowser/DataGrid.module.scss
var DataGrid_module = __webpack_require__(39961);
;// ./src/editor/src/views/panels/databrowser/DataGrid.module.scss

      
      
      
      
      
      
      
      
      

var DataGrid_module_options = {};

DataGrid_module_options.styleTagTransform = (styleTagTransform_default());
DataGrid_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      DataGrid_module_options.insert = insertBySelector_default().bind(null, "head");
    
DataGrid_module_options.domAPI = (styleDomAPI_default());
DataGrid_module_options.insertStyleElement = (insertStyleElement_default());

var DataGrid_module_update = injectStylesIntoStyleTag_default()(DataGrid_module/* default */.A, DataGrid_module_options);




       /* harmony default export */ const databrowser_DataGrid_module = (DataGrid_module/* default */.A && DataGrid_module/* default */.A.locals ? DataGrid_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/databrowser/DataGrid.tsx
/**
 * DataGrid
 *
 * Spreadsheet-style grid for displaying and editing records.
 * Supports inline editing, selection, and type-aware cell rendering.
 *
 * @module panels/databrowser/DataGrid
 * @since 1.2.0
 */





/** System fields that are read-only */
const READ_ONLY_FIELDS = new Set(['id', 'createdAt', 'updatedAt']);
/**
 * Format a cell value for display
 */
function formatCellValue(value, type) {
    if (value === null || value === undefined)
        return '';
    switch (type) {
        case 'Boolean':
            return value ? '✓' : '';
        case 'Date':
            try {
                return new Date(value).toLocaleString();
            }
            catch {
                return String(value);
            }
        case 'Object':
        case 'Array':
            return JSON.stringify(value);
        default:
            return String(value);
    }
}
/**
 * Get CSS class for type badge
 */
function getTypeBadgeClass(type) {
    switch (type) {
        case 'String':
            return databrowser_DataGrid_module.TypeString;
        case 'Number':
            return databrowser_DataGrid_module.TypeNumber;
        case 'Boolean':
            return databrowser_DataGrid_module.TypeBoolean;
        case 'Date':
            return databrowser_DataGrid_module.TypeDate;
        case 'Object':
            return databrowser_DataGrid_module.TypeObject;
        case 'Array':
            return databrowser_DataGrid_module.TypeArray;
        case 'Pointer':
        case 'Relation':
            return databrowser_DataGrid_module.TypePointer;
        default:
            return '';
    }
}
/**
 * DataGrid component
 */
function DataGrid({ columns, records, selectedRecords, onSelectRecord, onSelectAll, onSaveCell, onDeleteRecord }) {
    const [editingCell, setEditingCell] = (0,external_react_.useState)(null);
    const [savingError, setSavingError] = (0,external_react_.useState)(null);
    // Check if all records are selected
    const allSelected = records.length > 0 && selectedRecords.size === records.length;
    // Handle cell click - start editing if editable
    const handleCellClick = (0,external_react_.useCallback)((recordId, field) => {
        if (READ_ONLY_FIELDS.has(field))
            return;
        setEditingCell({ recordId, field });
        setSavingError(null);
    }, []);
    // Handle save from CellEditor
    const handleSave = (0,external_react_.useCallback)(async (recordId, field, value) => {
        try {
            await onSaveCell(recordId, field, value);
            setEditingCell(null);
            setSavingError(null);
        }
        catch (err) {
            setSavingError('Failed to save');
            // Don't close editor on error
        }
    }, [onSaveCell]);
    // Handle cancel editing
    const handleCancel = (0,external_react_.useCallback)(() => {
        setEditingCell(null);
        setSavingError(null);
    }, []);
    return (external_react_default().createElement("div", { className: databrowser_DataGrid_module.GridContainer },
        external_react_default().createElement("table", { className: databrowser_DataGrid_module.Grid },
            external_react_default().createElement("thead", null,
                external_react_default().createElement("tr", null,
                    external_react_default().createElement("th", { className: databrowser_DataGrid_module.CheckboxCol },
                        external_react_default().createElement("input", { type: "checkbox", checked: allSelected, onChange: (e) => onSelectAll(e.target.checked) })),
                    columns.map((col) => (external_react_default().createElement("th", { key: col.name, className: databrowser_DataGrid_module.HeaderCell },
                        external_react_default().createElement("div", { className: databrowser_DataGrid_module.HeaderContent },
                            external_react_default().createElement("span", { className: databrowser_DataGrid_module.HeaderName }, col.name),
                            external_react_default().createElement("span", { className: `${databrowser_DataGrid_module.TypeBadge} ${getTypeBadgeClass(col.type)}` }, col.type))))),
                    external_react_default().createElement("th", { className: databrowser_DataGrid_module.ActionsCol }, "Actions"))),
            external_react_default().createElement("tbody", null, records.map((record) => {
                const recordId = record.id;
                const isSelected = selectedRecords.has(recordId);
                return (external_react_default().createElement("tr", { key: recordId, className: isSelected ? databrowser_DataGrid_module.SelectedRow : '' },
                    external_react_default().createElement("td", { className: databrowser_DataGrid_module.CheckboxCol },
                        external_react_default().createElement("input", { type: "checkbox", checked: isSelected, onChange: (e) => onSelectRecord(recordId, e.target.checked) })),
                    columns.map((col) => {
                        const value = record[col.name];
                        const isEditing = (editingCell === null || editingCell === void 0 ? void 0 : editingCell.recordId) === recordId && (editingCell === null || editingCell === void 0 ? void 0 : editingCell.field) === col.name;
                        const isReadOnly = READ_ONLY_FIELDS.has(col.name);
                        return (external_react_default().createElement("td", { key: col.name, className: `${databrowser_DataGrid_module.Cell} ${isReadOnly ? databrowser_DataGrid_module.ReadOnlyCell : databrowser_DataGrid_module.EditableCell}`, onClick: () => !isEditing && handleCellClick(recordId, col.name) }, isEditing ? (external_react_default().createElement(CellEditor, { value: value, type: col.type, onSave: (newValue) => handleSave(recordId, col.name, newValue), onCancel: handleCancel, error: savingError })) : (external_react_default().createElement("div", { className: databrowser_DataGrid_module.CellValue, title: String(value !== null && value !== void 0 ? value : '') }, formatCellValue(value, col.type)))));
                    }),
                    external_react_default().createElement("td", { className: databrowser_DataGrid_module.ActionsCol },
                        external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Trash, size: common_Icon/* IconSize */.lK.Small, onClick: () => onDeleteRecord(recordId) }))));
            })))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/databrowser/NewRecordModal.module.scss
var NewRecordModal_module = __webpack_require__(18173);
;// ./src/editor/src/views/panels/databrowser/NewRecordModal.module.scss

      
      
      
      
      
      
      
      
      

var NewRecordModal_module_options = {};

NewRecordModal_module_options.styleTagTransform = (styleTagTransform_default());
NewRecordModal_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      NewRecordModal_module_options.insert = insertBySelector_default().bind(null, "head");
    
NewRecordModal_module_options.domAPI = (styleDomAPI_default());
NewRecordModal_module_options.insertStyleElement = (insertStyleElement_default());

var NewRecordModal_module_update = injectStylesIntoStyleTag_default()(NewRecordModal_module/* default */.A, NewRecordModal_module_options);




       /* harmony default export */ const databrowser_NewRecordModal_module = (NewRecordModal_module/* default */.A && NewRecordModal_module/* default */.A.locals ? NewRecordModal_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/databrowser/NewRecordModal.tsx
/**
 * NewRecordModal
 *
 * Modal dialog for creating a new record with type-aware form fields.
 *
 * @module panels/databrowser/NewRecordModal
 * @since 1.2.0
 */




const { ipcRenderer: NewRecordModal_ipcRenderer } = window.require('electron');
/**
 * Get default value for a column type
 */
function getDefaultValue(type) {
    switch (type) {
        case 'Boolean':
            return false;
        case 'Number':
            return 0;
        case 'Object':
            return {};
        case 'Array':
            return [];
        default:
            return '';
    }
}
/**
 * NewRecordModal component
 */
function NewRecordModal({ backendId, tableName, columns, onClose, onSuccess }) {
    // Initialize form state with default values
    const [formData, setFormData] = (0,external_react_.useState)(() => {
        const initial = {};
        columns.forEach((col) => {
            initial[col.name] = col.default !== undefined ? col.default : getDefaultValue(col.type);
        });
        return initial;
    });
    const [saving, setSaving] = (0,external_react_.useState)(false);
    const [error, setError] = (0,external_react_.useState)(null);
    // Handle field change
    const handleChange = (0,external_react_.useCallback)((field, value) => {
        setFormData((prev) => ({ ...prev, [field]: value }));
        setError(null);
    }, []);
    // Handle form submit
    const handleSubmit = (0,external_react_.useCallback)(async (e) => {
        e.preventDefault();
        // Validate required fields
        for (const col of columns) {
            if (col.required) {
                const value = formData[col.name];
                if (value === null || value === undefined || value === '') {
                    setError(`${col.name} is required`);
                    return;
                }
            }
        }
        setSaving(true);
        setError(null);
        try {
            await NewRecordModal_ipcRenderer.invoke('backend:createRecord', backendId, tableName, formData);
            onSuccess();
        }
        catch (err) {
            console.error('Failed to create record:', err);
            setError('Failed to create record');
        }
        finally {
            setSaving(false);
        }
    }, [backendId, tableName, formData, columns, onSuccess]);
    // Render form field based on type
    const renderField = (col) => {
        const value = formData[col.name];
        switch (col.type) {
            case 'Boolean':
                return (external_react_default().createElement("input", { type: "checkbox", checked: value === true, onChange: (e) => handleChange(col.name, e.target.checked) }));
            case 'Number':
                return (external_react_default().createElement("input", { type: "number", className: databrowser_NewRecordModal_module.Input, value: String(value !== null && value !== void 0 ? value : ''), onChange: (e) => handleChange(col.name, e.target.value ? parseFloat(e.target.value) : null), step: "any" }));
            case 'Date':
                return (external_react_default().createElement("input", { type: "datetime-local", className: databrowser_NewRecordModal_module.Input, value: value ? new Date(value).toISOString().slice(0, 16) : '', onChange: (e) => handleChange(col.name, e.target.value ? new Date(e.target.value).toISOString() : null) }));
            case 'Object':
            case 'Array':
                return (external_react_default().createElement("textarea", { className: databrowser_NewRecordModal_module.JsonInput, value: typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value !== null && value !== void 0 ? value : ''), onChange: (e) => {
                        try {
                            handleChange(col.name, JSON.parse(e.target.value));
                        }
                        catch {
                            // Keep as string while editing, parse on blur
                        }
                    }, rows: 3, spellCheck: false, placeholder: col.type === 'Array' ? '[]' : '{}' }));
            default:
                // String
                return (external_react_default().createElement("input", { type: "text", className: databrowser_NewRecordModal_module.Input, value: String(value !== null && value !== void 0 ? value : ''), onChange: (e) => handleChange(col.name, e.target.value), placeholder: `Enter ${col.name}...` }));
        }
    };
    return (external_react_default().createElement("div", { className: databrowser_NewRecordModal_module.Overlay, onClick: onClose },
        external_react_default().createElement("div", { className: databrowser_NewRecordModal_module.Modal, onClick: (e) => e.stopPropagation() },
            external_react_default().createElement("div", { className: databrowser_NewRecordModal_module.Header },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast },
                    "New Record in ",
                    tableName)),
            external_react_default().createElement("form", { onSubmit: handleSubmit },
                external_react_default().createElement("div", { className: databrowser_NewRecordModal_module.Content },
                    columns.length === 0 ? (external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "No columns defined for this table")) : (columns.map((col) => (external_react_default().createElement("div", { key: col.name, className: databrowser_NewRecordModal_module.Field },
                        external_react_default().createElement("label", { className: databrowser_NewRecordModal_module.Label },
                            col.name,
                            col.required && external_react_default().createElement("span", { className: databrowser_NewRecordModal_module.Required }, "*"),
                            external_react_default().createElement("span", { className: databrowser_NewRecordModal_module.TypeHint }, col.type)),
                        renderField(col))))),
                    error && (external_react_default().createElement("div", { className: databrowser_NewRecordModal_module.Error },
                        external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Default }, error)))),
                external_react_default().createElement("div", { className: databrowser_NewRecordModal_module.Footer },
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onClose }),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: saving ? 'Creating...' : 'Create Record', size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, isDisabled: saving || columns.length === 0, onClick: handleSubmit }))))));
}

;// ./src/editor/src/views/panels/databrowser/DataBrowser.tsx
/**
 * DataBrowser
 *
 * Main data browser panel for viewing and editing records in local backend tables.
 * Provides a spreadsheet-like interface with inline editing, search, and pagination.
 *
 * @module panels/databrowser/DataBrowser
 * @since 1.2.0
 */









const { ipcRenderer: DataBrowser_ipcRenderer } = window.require('electron');
const PAGE_SIZE = 50;
/**
 * DataBrowser component - main data browsing UI
 */
function DataBrowser({ backendId, backendName, initialTable, onClose }) {
    // State
    const [tables, setTables] = (0,external_react_.useState)([]);
    const [selectedTable, setSelectedTable] = (0,external_react_.useState)(initialTable || null);
    const [schema, setSchema] = (0,external_react_.useState)(null);
    const [records, setRecords] = (0,external_react_.useState)([]);
    const [totalCount, setTotalCount] = (0,external_react_.useState)(0);
    const [page, setPage] = (0,external_react_.useState)(0);
    const [loading, setLoading] = (0,external_react_.useState)(false);
    const [searchQuery, setSearchQuery] = (0,external_react_.useState)('');
    const [selectedRecords, setSelectedRecords] = (0,external_react_.useState)(new Set());
    const [showNewRecord, setShowNewRecord] = (0,external_react_.useState)(false);
    const [error, setError] = (0,external_react_.useState)(null);
    // System columns shown for all tables
    const systemColumns = (0,external_react_.useMemo)(() => [
        { name: 'id', type: 'String', required: true },
        { name: 'createdAt', type: 'Date', required: true },
        { name: 'updatedAt', type: 'Date', required: true }
    ], []);
    // All columns = system + user columns (deduplicated by name)
    const allColumns = (0,external_react_.useMemo)(() => {
        if (!schema)
            return systemColumns;
        // Deduplicate by column name, system columns first
        const seen = new Set(systemColumns.map((c) => c.name));
        const userColumns = (schema.columns || []).filter((c) => !seen.has(c.name));
        return [...systemColumns, ...userColumns];
    }, [schema, systemColumns]);
    // Load table list
    const loadTables = (0,external_react_.useCallback)(async () => {
        try {
            const result = await DataBrowser_ipcRenderer.invoke('backend:getSchema', backendId);
            const tableNames = result.tables.map((t) => t.name);
            setTables(tableNames);
            // Auto-select first table if none selected
            if (!selectedTable && tableNames.length > 0) {
                setSelectedTable(tableNames[0]);
            }
        }
        catch (err) {
            console.error('Failed to load tables:', err);
            setError('Failed to load tables');
        }
    }, [backendId, selectedTable]);
    // Load data for selected table
    const loadData = (0,external_react_.useCallback)(async () => {
        var _a;
        if (!selectedTable)
            return;
        setLoading(true);
        setError(null);
        try {
            // Load schema for this table
            const tableSchema = await DataBrowser_ipcRenderer.invoke('backend:getTableSchema', backendId, selectedTable);
            setSchema(tableSchema);
            // Build query
            const queryOptions = {
                collection: selectedTable,
                limit: PAGE_SIZE,
                skip: page * PAGE_SIZE,
                sort: ['-createdAt'],
                count: true
            };
            // Apply search (simple contains search across string fields)
            if (searchQuery.trim()) {
                const stringColumns = ((_a = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.columns) === null || _a === void 0 ? void 0 : _a.filter((c) => c.type === 'String')) || [];
                const searchConditions = stringColumns.map((col) => ({
                    [col.name]: { contains: searchQuery.trim() }
                }));
                // Also search id
                searchConditions.push({ id: { contains: searchQuery.trim() } });
                if (searchConditions.length > 0) {
                    queryOptions.where = { $or: searchConditions };
                }
            }
            // Load records
            const result = await DataBrowser_ipcRenderer.invoke('backend:queryRecords', backendId, queryOptions);
            setRecords(result.results || []);
            setTotalCount(result.count || 0);
        }
        catch (err) {
            console.error('Failed to load data:', err);
            setError('Failed to load data');
        }
        finally {
            setLoading(false);
        }
    }, [backendId, selectedTable, page, searchQuery]);
    // Initial load
    (0,external_react_.useEffect)(() => {
        loadTables();
    }, [loadTables]);
    // Load data when table, page, or search changes
    (0,external_react_.useEffect)(() => {
        loadData();
    }, [loadData]);
    // Reset page when search or table changes
    (0,external_react_.useEffect)(() => {
        setPage(0);
        setSelectedRecords(new Set());
    }, [selectedTable, searchQuery]);
    // Save cell (inline edit)
    const handleSaveCell = (0,external_react_.useCallback)(async (recordId, field, value) => {
        if (!selectedTable)
            return;
        try {
            await DataBrowser_ipcRenderer.invoke('backend:saveRecord', backendId, selectedTable, recordId, {
                [field]: value
            });
            // Update local state
            setRecords((prev) => prev.map((r) => (r.id === recordId ? { ...r, [field]: value, updatedAt: new Date().toISOString() } : r)));
        }
        catch (err) {
            console.error('Failed to save cell:', err);
            throw err; // Re-throw so CellEditor can show error
        }
    }, [backendId, selectedTable]);
    // Delete single record
    const handleDeleteRecord = (0,external_react_.useCallback)(async (recordId) => {
        if (!selectedTable)
            return;
        if (!window.confirm('Delete this record?'))
            return;
        try {
            await DataBrowser_ipcRenderer.invoke('backend:deleteRecord', backendId, selectedTable, recordId);
            loadData();
        }
        catch (err) {
            console.error('Failed to delete record:', err);
            setError('Failed to delete record');
        }
    }, [backendId, selectedTable, loadData]);
    // Bulk delete
    const handleBulkDelete = (0,external_react_.useCallback)(async () => {
        if (selectedRecords.size === 0 || !selectedTable)
            return;
        if (!window.confirm(`Delete ${selectedRecords.size} records?`))
            return;
        try {
            for (const recordId of selectedRecords) {
                await DataBrowser_ipcRenderer.invoke('backend:deleteRecord', backendId, selectedTable, recordId);
            }
            setSelectedRecords(new Set());
            loadData();
        }
        catch (err) {
            console.error('Failed to bulk delete:', err);
            setError('Failed to delete some records');
        }
    }, [backendId, selectedTable, selectedRecords, loadData]);
    // Export to CSV
    const handleExport = (0,external_react_.useCallback)(() => {
        if (records.length === 0 || !schema)
            return;
        // Build CSV
        const headers = allColumns.map((c) => c.name).join(',');
        const rows = records.map((record) => allColumns
            .map((col) => {
            const value = record[col.name];
            if (value === null || value === undefined)
                return '';
            if (typeof value === 'object')
                return `"${JSON.stringify(value).replace(/"/g, '""')}"`;
            if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n'))) {
                return `"${value.replace(/"/g, '""')}"`;
            }
            return String(value);
        })
            .join(','));
        const csv = [headers, ...rows].join('\n');
        // Download
        const blob = new Blob([csv], { type: 'text/csv' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${selectedTable}.csv`;
        a.click();
        URL.revokeObjectURL(url);
    }, [records, allColumns, selectedTable, schema]);
    // Toggle record selection
    const handleSelectRecord = (0,external_react_.useCallback)((recordId, selected) => {
        setSelectedRecords((prev) => {
            const next = new Set(prev);
            if (selected) {
                next.add(recordId);
            }
            else {
                next.delete(recordId);
            }
            return next;
        });
    }, []);
    // Select/deselect all
    const handleSelectAll = (0,external_react_.useCallback)((selected) => {
        if (selected) {
            setSelectedRecords(new Set(records.map((r) => r.id)));
        }
        else {
            setSelectedRecords(new Set());
        }
    }, [records]);
    // Pagination
    const totalPages = Math.ceil(totalCount / PAGE_SIZE);
    const startRecord = page * PAGE_SIZE + 1;
    const endRecord = Math.min((page + 1) * PAGE_SIZE, totalCount);
    return (external_react_default().createElement("div", { className: databrowser_DataBrowser_module.Root },
        external_react_default().createElement("div", { className: databrowser_DataBrowser_module.Header },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement("div", { className: databrowser_DataBrowser_module.HeaderIcon },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CloudData, size: common_Icon/* IconSize */.lK.Small })),
                external_react_default().createElement(Stack/* VStack */.Tk, null,
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, "Data Browser"),
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } }, backendName))),
            external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Close, onClick: onClose })),
        external_react_default().createElement("div", { className: databrowser_DataBrowser_module.Toolbar },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement("select", { className: databrowser_DataBrowser_module.TableSelect, value: selectedTable || '', onChange: (e) => setSelectedTable(e.target.value || null) },
                    external_react_default().createElement("option", { value: "", disabled: true }, "Select table..."),
                    tables.map((table) => (external_react_default().createElement("option", { key: table, value: table }, table)))),
                external_react_default().createElement("input", { type: "text", className: databrowser_DataBrowser_module.SearchInput, placeholder: "Search records...", value: searchQuery, onChange: (e) => setSearchQuery(e.target.value) }),
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Refresh, onClick: loadData })),
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true }, selectedTable && (external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "+ New Record", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: () => setShowNewRecord(true) }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Export CSV", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: handleExport, isDisabled: records.length === 0 }))))),
        selectedRecords.size > 0 && (external_react_default().createElement("div", { className: databrowser_DataBrowser_module.BulkActions },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Default },
                selectedRecords.size,
                " records selected"),
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Delete Selected", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Danger, onClick: handleBulkDelete }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Clear Selection", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: () => setSelectedRecords(new Set()) })))),
        error && (external_react_default().createElement("div", { className: databrowser_DataBrowser_module.Error },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Default }, error))),
        external_react_default().createElement("div", { className: databrowser_DataBrowser_module.Content }, loading ? (external_react_default().createElement("div", { className: databrowser_DataBrowser_module.Loading },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "Loading..."))) : !selectedTable ? (external_react_default().createElement("div", { className: databrowser_DataBrowser_module.EmptyState },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "Select a table to browse data"))) : records.length === 0 ? (external_react_default().createElement("div", { className: databrowser_DataBrowser_module.EmptyState },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "No records found"),
            !searchQuery && (external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Create First Record", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: () => setShowNewRecord(true), UNSAFE_style: { marginTop: '12px' } })))) : (external_react_default().createElement(DataGrid, { columns: allColumns, records: records, selectedRecords: selectedRecords, onSelectRecord: handleSelectRecord, onSelectAll: handleSelectAll, onSaveCell: handleSaveCell, onDeleteRecord: handleDeleteRecord }))),
        selectedTable && totalCount > 0 && (external_react_default().createElement("div", { className: databrowser_DataBrowser_module.Pagination },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '12px' } },
                "Showing ",
                startRecord.toLocaleString(),
                "-",
                endRecord.toLocaleString(),
                " of ",
                totalCount.toLocaleString(),
                " records"),
            external_react_default().createElement("div", { className: databrowser_DataBrowser_module.PageControls },
                external_react_default().createElement("button", { className: databrowser_DataBrowser_module.PageButton, onClick: () => setPage(0), disabled: page === 0 }, "First"),
                external_react_default().createElement("button", { className: databrowser_DataBrowser_module.PageButton, onClick: () => setPage(page - 1), disabled: page === 0 }, "Previous"),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '12px', margin: '0 8px' } },
                    "Page ",
                    page + 1,
                    " of ",
                    totalPages),
                external_react_default().createElement("button", { className: databrowser_DataBrowser_module.PageButton, onClick: () => setPage(page + 1), disabled: page >= totalPages - 1 }, "Next"),
                external_react_default().createElement("button", { className: databrowser_DataBrowser_module.PageButton, onClick: () => setPage(totalPages - 1), disabled: page >= totalPages - 1 }, "Last")))),
        showNewRecord && schema && selectedTable && (external_react_default().createElement(NewRecordModal, { backendId: backendId, tableName: selectedTable, columns: schema.columns, onClose: () => setShowNewRecord(false), onSuccess: () => {
                setShowNewRecord(false);
                loadData();
            } }))));
}

;// ./src/editor/src/views/panels/databrowser/index.ts
/**
 * Data Browser Panel
 *
 * Export all data browser components.
 *
 * @module panels/databrowser
 * @since 1.2.0
 */





// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/schemamanager/CreateTableModal.module.scss
var CreateTableModal_module = __webpack_require__(14596);
;// ./src/editor/src/views/panels/schemamanager/CreateTableModal.module.scss

      
      
      
      
      
      
      
      
      

var CreateTableModal_module_options = {};

CreateTableModal_module_options.styleTagTransform = (styleTagTransform_default());
CreateTableModal_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      CreateTableModal_module_options.insert = insertBySelector_default().bind(null, "head");
    
CreateTableModal_module_options.domAPI = (styleDomAPI_default());
CreateTableModal_module_options.insertStyleElement = (insertStyleElement_default());

var CreateTableModal_module_update = injectStylesIntoStyleTag_default()(CreateTableModal_module/* default */.A, CreateTableModal_module_options);




       /* harmony default export */ const schemamanager_CreateTableModal_module = (CreateTableModal_module/* default */.A && CreateTableModal_module/* default */.A.locals ? CreateTableModal_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/schemamanager/CreateTableModal.tsx
/**
 * CreateTableModal
 *
 * Modal for creating a new database table with columns.
 *
 * @module schemamanager/CreateTableModal
 * @since 1.2.0
 */







const { ipcRenderer: CreateTableModal_ipcRenderer } = window.require('electron');
/** Supported column types */
const COLUMN_TYPES = ['String', 'Number', 'Boolean', 'Date', 'Object', 'Array'];
/** SQLite reserved words to prevent as table names */
const SQLITE_RESERVED = [
    'ABORT',
    'ACTION',
    'ADD',
    'ALL',
    'ALTER',
    'AND',
    'AS',
    'ASC',
    'AUTOINCREMENT',
    'BETWEEN',
    'BY',
    'CASCADE',
    'CASE',
    'CHECK',
    'COLLATE',
    'COLUMN',
    'COMMIT',
    'CONFLICT',
    'CONSTRAINT',
    'CREATE',
    'CROSS',
    'DATABASE',
    'DEFAULT',
    'DELETE',
    'DESC',
    'DISTINCT',
    'DROP',
    'ELSE',
    'END',
    'ESCAPE',
    'EXCEPT',
    'EXISTS',
    'FOREIGN',
    'FROM',
    'GROUP',
    'HAVING',
    'IN',
    'INDEX',
    'INNER',
    'INSERT',
    'INTERSECT',
    'INTO',
    'IS',
    'ISNULL',
    'JOIN',
    'KEY',
    'LEFT',
    'LIKE',
    'LIMIT',
    'NATURAL',
    'NOT',
    'NOTNULL',
    'NULL',
    'ON',
    'OR',
    'ORDER',
    'OUTER',
    'PRIMARY',
    'REFERENCES',
    'REPLACE',
    'RIGHT',
    'ROLLBACK',
    'SELECT',
    'SET',
    'TABLE',
    'THEN',
    'TO',
    'TRANSACTION',
    'UNION',
    'UNIQUE',
    'UPDATE',
    'USING',
    'VALUES',
    'WHEN',
    'WHERE'
];
/**
 * Validate table name
 */
function validateTableName(name) {
    if (!name.trim()) {
        return 'Table name is required';
    }
    if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(name)) {
        return 'Must start with letter, only alphanumeric and underscore';
    }
    if (SQLITE_RESERVED.includes(name.toUpperCase())) {
        return `"${name}" is a reserved word`;
    }
    if (name.length > 64) {
        return 'Name too long (max 64 characters)';
    }
    return null;
}
/**
 * Validate column name
 */
function validateColumnName(name, existingNames) {
    if (!name.trim()) {
        return 'Column name is required';
    }
    if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(name)) {
        return 'Invalid column name';
    }
    if (['objectId', 'createdAt', 'updatedAt', 'ACL'].includes(name)) {
        return 'Reserved column name';
    }
    if (existingNames.includes(name)) {
        return 'Duplicate column name';
    }
    return null;
}
/**
 * Generate unique ID
 */
function CreateTableModal_generateId() {
    return Math.random().toString(36).substring(2, 9);
}
/**
 * CreateTableModal component
 */
function CreateTableModal({ backendId, onClose, onSuccess }) {
    // State
    const [tableName, setTableName] = (0,external_react_.useState)('');
    const [columns, setColumns] = (0,external_react_.useState)([
        { id: CreateTableModal_generateId(), name: '', type: 'String', required: false, defaultValue: '' }
    ]);
    const [saving, setSaving] = (0,external_react_.useState)(false);
    const [error, setError] = (0,external_react_.useState)(null);
    // Add a new column
    const handleAddColumn = (0,external_react_.useCallback)(() => {
        setColumns((prev) => [...prev, { id: CreateTableModal_generateId(), name: '', type: 'String', required: false, defaultValue: '' }]);
    }, []);
    // Remove a column
    const handleRemoveColumn = (0,external_react_.useCallback)((id) => {
        setColumns((prev) => prev.filter((c) => c.id !== id));
    }, []);
    // Update a column field
    const handleUpdateColumn = (0,external_react_.useCallback)((id, field, value) => {
        setColumns((prev) => prev.map((c) => (c.id === id ? { ...c, [field]: value } : c)));
    }, []);
    // Handle form submission
    const handleSubmit = (0,external_react_.useCallback)(async () => {
        setError(null);
        // Validate table name
        const tableNameError = validateTableName(tableName);
        if (tableNameError) {
            setError(tableNameError);
            return;
        }
        // Filter out empty columns and validate remaining
        const validColumns = columns.filter((c) => c.name.trim());
        const columnNames = [];
        for (const col of validColumns) {
            const colError = validateColumnName(col.name, columnNames);
            if (colError) {
                setError(`Column "${col.name}": ${colError}`);
                return;
            }
            columnNames.push(col.name);
        }
        // Build schema
        const tableSchema = {
            name: tableName.trim(),
            columns: validColumns.map((col) => ({
                name: col.name.trim(),
                type: col.type,
                required: col.required,
                defaultValue: col.defaultValue.trim() || undefined
            }))
        };
        setSaving(true);
        try {
            await CreateTableModal_ipcRenderer.invoke('backend:createTable', backendId, tableSchema);
            onSuccess();
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to create table';
            setError(message);
            setSaving(false);
        }
    }, [backendId, tableName, columns, onSuccess]);
    // Handle Enter key
    const handleKeyDown = (0,external_react_.useCallback)((e) => {
        if (e.key === 'Enter' && e.metaKey) {
            handleSubmit();
        }
    }, [handleSubmit]);
    return (external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.Overlay, onClick: onClose },
        external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.Modal, onClick: (e) => e.stopPropagation(), onKeyDown: handleKeyDown },
            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.Header },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud }, "Create New Table"),
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Close, onClick: onClose })),
            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.Content },
                external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.Section },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, "Table Name"),
                    external_react_default().createElement("input", { type: "text", className: schemamanager_CreateTableModal_module.Input, placeholder: "e.g., Products, Users, Orders", value: tableName, onChange: (e) => setTableName(e.target.value), autoFocus: true })),
                external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.Section },
                    external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { justifyContent: 'space-between', alignItems: 'center' } },
                        external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, "Fields"),
                        external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "+ Add Field", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Ghost, onClick: handleAddColumn })),
                    external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColumnsTable },
                        external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColumnRow },
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColName }, "Name"),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColType }, "Type"),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColRequired }, "Required"),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColDefault }, "Default"),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColActions })),
                        external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColumnRow, "data-system": "true" },
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColName },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "objectId")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColType },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "String")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColRequired },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "\u2713")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColDefault },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "auto")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColActions })),
                        external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColumnRow, "data-system": "true" },
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColName },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "createdAt")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColType },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "Date")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColRequired },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "\u2713")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColDefault },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "auto")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColActions })),
                        external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColumnRow, "data-system": "true" },
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColName },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "updatedAt")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColType },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "Date")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColRequired },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "\u2713")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColDefault },
                                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "auto")),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColActions })),
                        columns.map((col) => (external_react_default().createElement("div", { key: col.id, className: schemamanager_CreateTableModal_module.ColumnRow },
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColName },
                                external_react_default().createElement("input", { type: "text", className: schemamanager_CreateTableModal_module.ColumnInput, placeholder: "field_name", value: col.name, onChange: (e) => handleUpdateColumn(col.id, 'name', e.target.value) })),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColType },
                                external_react_default().createElement("select", { className: schemamanager_CreateTableModal_module.TypeSelect, value: col.type, onChange: (e) => handleUpdateColumn(col.id, 'type', e.target.value) }, COLUMN_TYPES.map((t) => (external_react_default().createElement("option", { key: t, value: t }, t))))),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColRequired },
                                external_react_default().createElement("input", { type: "checkbox", checked: col.required, onChange: (e) => handleUpdateColumn(col.id, 'required', e.target.checked) })),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColDefault },
                                external_react_default().createElement("input", { type: "text", className: schemamanager_CreateTableModal_module.ColumnInput, placeholder: col.type === 'Boolean' ? 'true/false' : '', value: col.defaultValue, onChange: (e) => handleUpdateColumn(col.id, 'defaultValue', e.target.value) })),
                            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.ColActions },
                                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Trash, onClick: () => handleRemoveColumn(col.id), UNSAFE_style: { opacity: columns.length === 1 ? 0.3 : 1 } }))))))),
                error && (external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.Error },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.WarningTriangle, size: common_Icon/* IconSize */.lK.Tiny }),
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Default }, error)))),
            external_react_default().createElement("div", { className: schemamanager_CreateTableModal_module.Footer },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onClose }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: saving ? 'Creating...' : 'Create Table', size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Cta, onClick: handleSubmit, isDisabled: saving || !tableName.trim() })))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/schemamanager/SchemaPanel.module.scss
var SchemaPanel_module = __webpack_require__(75232);
;// ./src/editor/src/views/panels/schemamanager/SchemaPanel.module.scss

      
      
      
      
      
      
      
      
      

var SchemaPanel_module_options = {};

SchemaPanel_module_options.styleTagTransform = (styleTagTransform_default());
SchemaPanel_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      SchemaPanel_module_options.insert = insertBySelector_default().bind(null, "head");
    
SchemaPanel_module_options.domAPI = (styleDomAPI_default());
SchemaPanel_module_options.insertStyleElement = (insertStyleElement_default());

var SchemaPanel_module_update = injectStylesIntoStyleTag_default()(SchemaPanel_module/* default */.A, SchemaPanel_module_options);




       /* harmony default export */ const schemamanager_SchemaPanel_module = (SchemaPanel_module/* default */.A && SchemaPanel_module/* default */.A.locals ? SchemaPanel_module/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/schemamanager/TableRow.module.scss
var TableRow_module = __webpack_require__(27339);
;// ./src/editor/src/views/panels/schemamanager/TableRow.module.scss

      
      
      
      
      
      
      
      
      

var TableRow_module_options = {};

TableRow_module_options.styleTagTransform = (styleTagTransform_default());
TableRow_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      TableRow_module_options.insert = insertBySelector_default().bind(null, "head");
    
TableRow_module_options.domAPI = (styleDomAPI_default());
TableRow_module_options.insertStyleElement = (insertStyleElement_default());

var TableRow_module_update = injectStylesIntoStyleTag_default()(TableRow_module/* default */.A, TableRow_module_options);




       /* harmony default export */ const schemamanager_TableRow_module = (TableRow_module/* default */.A && TableRow_module/* default */.A.locals ? TableRow_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/schemamanager/TableRow.tsx
/**
 * TableRow
 *
 * Expandable row showing table name, column count, and record count.
 * When expanded, shows all columns with their types.
 * Supports adding columns, renaming columns, and deleting tables.
 *
 * @module schemamanager/TableRow
 * @since 1.2.0
 */






/** Color mapping for data types */
const TYPE_COLORS = {
    String: 'var(--theme-color-primary)',
    Number: 'var(--theme-color-success)',
    Boolean: 'var(--theme-color-notice)',
    Date: '#8b5cf6',
    Object: '#ec4899',
    Array: '#6366f1',
    Pointer: 'var(--theme-color-danger)',
    Relation: 'var(--theme-color-danger)',
    GeoPoint: '#14b8a6',
    File: '#f97316'
};
/**
 * TypeBadge - Small colored badge showing column type
 */
function TypeBadge({ type }) {
    const color = TYPE_COLORS[type] || 'var(--theme-color-fg-default-shy)';
    return (external_react_default().createElement("span", { className: schemamanager_TableRow_module.TypeBadge, style: { backgroundColor: color } }, type));
}
/**
 * TableRow - Expandable table display row
 */
function TableRow({ table, recordCount, expanded, onToggleExpand, onEdit }) {
    var _a;
    const columnCount = ((_a = table.columns) === null || _a === void 0 ? void 0 : _a.length) || 0;
    return (external_react_default().createElement("div", { className: schemamanager_TableRow_module.Root, "data-expanded": expanded },
        external_react_default().createElement("div", { className: schemamanager_TableRow_module.Header, onClick: onToggleExpand },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement("div", { className: schemamanager_TableRow_module.ExpandIcon },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: expanded ? common_Icon/* IconName */.$M.CaretDown : common_Icon/* IconName */.$M.CaretRight, size: common_Icon/* IconSize */.lK.Tiny, UNSAFE_style: { color: 'var(--theme-color-fg-default-shy)' } })),
                external_react_default().createElement("div", { className: schemamanager_TableRow_module.TableIcon },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud }, "T")),
                external_react_default().createElement("div", { className: schemamanager_TableRow_module.TableName },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, table.name))),
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement("div", { className: schemamanager_TableRow_module.Stats },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } },
                        columnCount,
                        " ",
                        columnCount === 1 ? 'field' : 'fields'),
                    recordCount !== undefined && (external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px', marginLeft: '8px' } },
                        "\u2022 ",
                        recordCount.toLocaleString(),
                        " ",
                        recordCount === 1 ? 'record' : 'records'))),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Edit", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Ghost, onClick: (e) => {
                        e.stopPropagation();
                        onEdit();
                    } }))),
        expanded && (external_react_default().createElement("div", { className: schemamanager_TableRow_module.Columns },
            external_react_default().createElement("table", { className: schemamanager_TableRow_module.ColumnTable },
                external_react_default().createElement("thead", null,
                    external_react_default().createElement("tr", null,
                        external_react_default().createElement("th", null, "Field Name"),
                        external_react_default().createElement("th", null, "Type"),
                        external_react_default().createElement("th", null, "Required"),
                        external_react_default().createElement("th", null, "Default"))),
                external_react_default().createElement("tbody", null,
                    external_react_default().createElement("tr", { className: schemamanager_TableRow_module.SystemColumn },
                        external_react_default().createElement("td", null, "id"),
                        external_react_default().createElement("td", null,
                            external_react_default().createElement(TypeBadge, { type: "String" })),
                        external_react_default().createElement("td", null, "\u2713"),
                        external_react_default().createElement("td", null, "UUID (auto)")),
                    external_react_default().createElement("tr", { className: schemamanager_TableRow_module.SystemColumn },
                        external_react_default().createElement("td", null, "createdAt"),
                        external_react_default().createElement("td", null,
                            external_react_default().createElement(TypeBadge, { type: "Date" })),
                        external_react_default().createElement("td", null, "\u2713"),
                        external_react_default().createElement("td", null, "auto")),
                    external_react_default().createElement("tr", { className: schemamanager_TableRow_module.SystemColumn },
                        external_react_default().createElement("td", null, "updatedAt"),
                        external_react_default().createElement("td", null,
                            external_react_default().createElement(TypeBadge, { type: "Date" })),
                        external_react_default().createElement("td", null, "\u2713"),
                        external_react_default().createElement("td", null, "auto")),
                    table.columns.map((col) => (external_react_default().createElement("tr", { key: col.name },
                        external_react_default().createElement("td", null, col.name),
                        external_react_default().createElement("td", null,
                            external_react_default().createElement(TypeBadge, { type: col.type }),
                            col.targetClass && external_react_default().createElement("span", { className: schemamanager_TableRow_module.TargetClass },
                                " \u2192 ",
                                col.targetClass)),
                        external_react_default().createElement("td", null, col.required ? '✓' : ''),
                        external_react_default().createElement("td", null, col.default !== undefined ? String(col.default) : '—')))),
                    table.columns.length === 0 && (external_react_default().createElement("tr", null,
                        external_react_default().createElement("td", { colSpan: 4, className: schemamanager_TableRow_module.NoColumns }, "No custom fields defined yet")))))))));
}

;// ./src/editor/src/views/panels/schemamanager/SchemaPanel.tsx
/**
 * SchemaPanel
 *
 * Main panel for viewing and managing database schemas in local backends.
 * Shows a list of tables with columns, record counts, and management options.
 *
 * @module schemamanager/SchemaPanel
 * @since 1.2.0
 */







/**
 * Invoke IPC handler with error handling
 */
async function SchemaPanel_invokeIPC(channel, ...args) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const { ipcRenderer } = window.require('electron');
    return ipcRenderer.invoke(channel, ...args);
}
/**
 * SchemaPanel - View and manage database schemas
 */
function SchemaPanel({ backendId, backendName, isRunning, onClose }) {
    const [loading, setLoading] = (0,external_react_.useState)(true);
    const [error, setError] = (0,external_react_.useState)(null);
    const [schema, setSchema] = (0,external_react_.useState)(null);
    const [expandedTable, setExpandedTable] = (0,external_react_.useState)(null);
    const [recordCounts, setRecordCounts] = (0,external_react_.useState)({});
    const [showCreateTable, setShowCreateTable] = (0,external_react_.useState)(false);
    // Load schema from backend
    const loadSchema = (0,external_react_.useCallback)(async () => {
        if (!isRunning) {
            setError('Backend must be running to view schema');
            setLoading(false);
            return;
        }
        setLoading(true);
        setError(null);
        try {
            const schemaData = await SchemaPanel_invokeIPC('backend:getSchema', backendId);
            setSchema(schemaData);
            // Load record counts asynchronously
            loadRecordCounts(schemaData.tables);
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to load schema';
            setError(message);
        }
        finally {
            setLoading(false);
        }
    }, [backendId, isRunning]);
    // Load record counts for all tables
    const loadRecordCounts = (0,external_react_.useCallback)(async (tables) => {
        const counts = {};
        for (const table of tables) {
            try {
                const count = await SchemaPanel_invokeIPC('backend:getRecordCount', backendId, table.name);
                counts[table.name] = count;
            }
            catch {
                counts[table.name] = 0;
            }
        }
        setRecordCounts(counts);
    }, [backendId]);
    // Load schema on mount and when backend changes
    (0,external_react_.useEffect)(() => {
        loadSchema();
    }, [loadSchema]);
    // Handle table expand/collapse
    const handleToggleExpand = (0,external_react_.useCallback)((tableName) => {
        setExpandedTable((prev) => (prev === tableName ? null : tableName));
    }, []);
    // Handle edit table - expands table to show columns
    const handleEditTable = (0,external_react_.useCallback)((tableName) => {
        // Expand the table to show columns - full editing (add/remove columns) will be added in a future task
        setExpandedTable((prev) => (prev === tableName ? tableName : tableName));
    }, []);
    // Render loading state
    if (loading) {
        return (external_react_default().createElement("div", { className: schemamanager_SchemaPanel_module.Root },
            external_react_default().createElement("div", { className: schemamanager_SchemaPanel_module.Header },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud },
                    "Schema: ",
                    backendName),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Close", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onClose })),
            external_react_default().createElement("div", { className: schemamanager_SchemaPanel_module.Loading },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "Loading schema..."))));
    }
    // Render error state
    if (error) {
        return (external_react_default().createElement("div", { className: schemamanager_SchemaPanel_module.Root },
            external_react_default().createElement("div", { className: schemamanager_SchemaPanel_module.Header },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud },
                    "Schema: ",
                    backendName),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Close", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onClose })),
            external_react_default().createElement("div", { className: schemamanager_SchemaPanel_module.Error },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, error),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Retry", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: loadSchema }))));
    }
    const tables = (schema === null || schema === void 0 ? void 0 : schema.tables) || [];
    return (external_react_default().createElement("div", { className: schemamanager_SchemaPanel_module.Root },
        external_react_default().createElement("div", { className: schemamanager_SchemaPanel_module.Header },
            external_react_default().createElement(Stack/* VStack */.Tk, null,
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud },
                    "Schema: ",
                    backendName),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } },
                    tables.length,
                    " ",
                    tables.length === 1 ? 'table' : 'tables')),
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "+ New Table", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Cta, onClick: () => setShowCreateTable(true) }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Refresh", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: loadSchema }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Close", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onClose }))),
        external_react_default().createElement("div", { className: schemamanager_SchemaPanel_module.TableList }, tables.length === 0 ? (external_react_default().createElement("div", { className: schemamanager_SchemaPanel_module.EmptyState },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, "No tables yet"),
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { marginTop: '8px' } }, "Create your first table to start storing data."),
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Create First Table", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Cta, onClick: () => setShowCreateTable(true), UNSAFE_style: { marginTop: '16px' } }))) : (tables.map((table) => (external_react_default().createElement(TableRow, { key: table.name, table: table, recordCount: recordCounts[table.name], expanded: expandedTable === table.name, onToggleExpand: () => handleToggleExpand(table.name), onEdit: () => handleEditTable(table.name) }))))),
        showCreateTable && (external_react_default().createElement(CreateTableModal, { backendId: backendId, onClose: () => setShowCreateTable(false), onSuccess: () => {
                setShowCreateTable(false);
                loadSchema();
            } }))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/schemamanager/AddColumnForm.module.scss
var AddColumnForm_module = __webpack_require__(25044);
;// ./src/editor/src/views/panels/schemamanager/AddColumnForm.module.scss

      
      
      
      
      
      
      
      
      

var AddColumnForm_module_options = {};

AddColumnForm_module_options.styleTagTransform = (styleTagTransform_default());
AddColumnForm_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      AddColumnForm_module_options.insert = insertBySelector_default().bind(null, "head");
    
AddColumnForm_module_options.domAPI = (styleDomAPI_default());
AddColumnForm_module_options.insertStyleElement = (insertStyleElement_default());

var AddColumnForm_module_update = injectStylesIntoStyleTag_default()(AddColumnForm_module/* default */.A, AddColumnForm_module_options);




       /* harmony default export */ const schemamanager_AddColumnForm_module = (AddColumnForm_module/* default */.A && AddColumnForm_module/* default */.A.locals ? AddColumnForm_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/schemamanager/AddColumnForm.tsx
/**
 * AddColumnForm
 *
 * Inline form for adding a new column to an existing table.
 * Also handles column renaming via inline edit.
 *
 * @module schemamanager/AddColumnForm
 * @since 1.2.0
 */






const { ipcRenderer: AddColumnForm_ipcRenderer } = window.require('electron');
/** Supported column types */
const AddColumnForm_COLUMN_TYPES = (/* unused pure expression or super */ null && (['String', 'Number', 'Boolean', 'Date', 'Object', 'Array']));
/**
 * Validate column name
 */
function AddColumnForm_validateColumnName(name, existingNames) {
    if (!name.trim()) {
        return 'Column name is required';
    }
    if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(name)) {
        return 'Must start with letter, alphanumeric and underscore only';
    }
    if (['objectId', 'createdAt', 'updatedAt', 'ACL'].includes(name)) {
        return 'Reserved column name';
    }
    if (existingNames.includes(name)) {
        return 'Column already exists';
    }
    return null;
}
/**
 * AddColumnForm component - inline form for adding columns
 */
function AddColumnForm({ backendId, tableName, existingColumns, onSuccess, onCancel }) {
    const [name, setName] = useState('');
    const [type, setType] = useState('String');
    const [required, setRequired] = useState(false);
    const [defaultValue, setDefaultValue] = useState('');
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState(null);
    const handleSubmit = useCallback(async () => {
        setError(null);
        const nameError = AddColumnForm_validateColumnName(name, existingColumns);
        if (nameError) {
            setError(nameError);
            return;
        }
        const column = {
            name: name.trim(),
            type,
            required,
            defaultValue: defaultValue.trim() || undefined
        };
        setSaving(true);
        try {
            await AddColumnForm_ipcRenderer.invoke('backend:addColumn', backendId, tableName, column);
            onSuccess();
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to add column';
            setError(message);
            setSaving(false);
        }
    }, [backendId, tableName, name, type, required, defaultValue, existingColumns, onSuccess]);
    return (React.createElement("div", { className: css.Root },
        React.createElement("div", { className: css.Row },
            React.createElement("div", { className: css.Field },
                React.createElement("input", { type: "text", className: css.Input, placeholder: "column_name", value: name, onChange: (e) => setName(e.target.value), autoFocus: true })),
            React.createElement("div", { className: css.Field },
                React.createElement("select", { className: css.Select, value: type, onChange: (e) => setType(e.target.value) }, AddColumnForm_COLUMN_TYPES.map((t) => (React.createElement("option", { key: t, value: t }, t))))),
            React.createElement("div", { className: css.FieldSmall },
                React.createElement("input", { type: "checkbox", checked: required, onChange: (e) => setRequired(e.target.checked) })),
            React.createElement("div", { className: css.Field },
                React.createElement("input", { type: "text", className: css.Input, placeholder: "default", value: defaultValue, onChange: (e) => setDefaultValue(e.target.value) })),
            React.createElement("div", { className: css.Actions },
                React.createElement(PrimaryButton, { label: saving ? '...' : 'Add', size: PrimaryButtonSize.Small, variant: PrimaryButtonVariant.Cta, onClick: handleSubmit, isDisabled: saving || !name.trim() }),
                React.createElement(IconButton, { icon: IconName.Close, onClick: onCancel }))),
        error && (React.createElement("div", { className: css.Error },
            React.createElement(Icon, { icon: IconName.WarningTriangle, size: IconSize.Tiny }),
            React.createElement(Text, { textType: TextType.Default }, error)))));
}
/**
 * ColumnRenameInput - inline input for renaming a column
 */
function ColumnRenameInput({ backendId, tableName, columnName, existingColumns, onSuccess, onCancel }) {
    const [newName, setNewName] = useState(columnName);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState(null);
    const handleSubmit = useCallback(async () => {
        setError(null);
        // No change
        if (newName.trim() === columnName) {
            onCancel();
            return;
        }
        // Validate (exclude current name from existing list)
        const otherColumns = existingColumns.filter((c) => c !== columnName);
        const nameError = AddColumnForm_validateColumnName(newName, otherColumns);
        if (nameError) {
            setError(nameError);
            return;
        }
        setSaving(true);
        try {
            await AddColumnForm_ipcRenderer.invoke('backend:renameColumn', backendId, tableName, columnName, newName.trim());
            onSuccess();
        }
        catch (err) {
            const message = err instanceof Error ? err.message : 'Failed to rename column';
            setError(message);
            setSaving(false);
        }
    }, [backendId, tableName, columnName, newName, existingColumns, onSuccess, onCancel]);
    const handleKeyDown = useCallback((e) => {
        if (e.key === 'Enter') {
            handleSubmit();
        }
        else if (e.key === 'Escape') {
            onCancel();
        }
    }, [handleSubmit, onCancel]);
    return (React.createElement("div", { className: css.RenameWrapper },
        React.createElement("input", { type: "text", className: css.RenameInput, value: newName, onChange: (e) => setNewName(e.target.value), onKeyDown: handleKeyDown, onBlur: handleSubmit, autoFocus: true, disabled: saving }),
        error && React.createElement("span", { className: css.RenameError }, error)));
}

;// ./src/editor/src/views/panels/schemamanager/index.ts
/**
 * Schema Manager Panel
 *
 * UI components for viewing and managing database schemas in local backends.
 *
 * @module schemamanager
 * @since 1.2.0
 */





// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/BackendServicesPanel/LocalBackendCard/LocalBackendCard.module.scss
var LocalBackendCard_module = __webpack_require__(55836);
;// ./src/editor/src/views/panels/BackendServicesPanel/LocalBackendCard/LocalBackendCard.module.scss

      
      
      
      
      
      
      
      
      

var LocalBackendCard_module_options = {};

LocalBackendCard_module_options.styleTagTransform = (styleTagTransform_default());
LocalBackendCard_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      LocalBackendCard_module_options.insert = insertBySelector_default().bind(null, "head");
    
LocalBackendCard_module_options.domAPI = (styleDomAPI_default());
LocalBackendCard_module_options.insertStyleElement = (insertStyleElement_default());

var LocalBackendCard_module_update = injectStylesIntoStyleTag_default()(LocalBackendCard_module/* default */.A, LocalBackendCard_module_options);




       /* harmony default export */ const LocalBackendCard_LocalBackendCard_module = (LocalBackendCard_module/* default */.A && LocalBackendCard_module/* default */.A.locals ? LocalBackendCard_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/BackendServicesPanel/LocalBackendCard/LocalBackendCard.tsx
/**
 * LocalBackendCard
 *
 * Card component for displaying and managing a local SQLite backend.
 * Shows status, start/stop controls, and endpoint information.
 *
 * @module BackendServicesPanel/LocalBackendCard
 * @since 1.2.0
 */










/**
 * Get status icon and color based on running status
 */
function LocalBackendCard_getStatusDisplay(running) {
    if (running) {
        return { icon: common_Icon/* IconName */.$M.Check, color: 'var(--theme-color-success)', text: 'Running' };
    }
    return { icon: common_Icon/* IconName */.$M.CircleOpen, color: 'var(--theme-color-fg-default-shy)', text: 'Stopped' };
}
function LocalBackendCard({ backend, onStart, onStop, onDelete, onExport }) {
    const [isOperating, setIsOperating] = (0,external_react_.useState)(false);
    const [showSchemaPanel, setShowSchemaPanel] = (0,external_react_.useState)(false);
    const [showDataBrowser, setShowDataBrowser] = (0,external_react_.useState)(false);
    const statusDisplay = LocalBackendCard_getStatusDisplay(backend.running);
    // Format date
    const createdDate = new Date(backend.createdAt).toLocaleDateString(undefined, {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
    // Handle start/stop
    const handleToggle = (0,external_react_.useCallback)(async () => {
        setIsOperating(true);
        try {
            if (backend.running) {
                await onStop();
            }
            else {
                await onStart();
            }
        }
        finally {
            setIsOperating(false);
        }
    }, [backend.running, onStart, onStop]);
    // Copy endpoint to clipboard
    const handleCopyEndpoint = (0,external_react_.useCallback)(() => {
        if (backend.endpoint) {
            navigator.clipboard.writeText(backend.endpoint);
        }
    }, [backend.endpoint]);
    return (external_react_default().createElement("div", { className: LocalBackendCard_LocalBackendCard_module.Root, "data-test": `local-backend-card-${backend.id}` },
        external_react_default().createElement("div", { className: LocalBackendCard_LocalBackendCard_module.Header },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement("div", { className: LocalBackendCard_LocalBackendCard_module.TypeIcon },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud }, "L")),
                external_react_default().createElement(Stack/* VStack */.Tk, null,
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, backend.name),
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } },
                        "Local SQLite \u2022 Port ",
                        backend.port))),
            external_react_default().createElement("div", { className: LocalBackendCard_LocalBackendCard_module.StatusBadge, style: { color: statusDisplay.color } },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: statusDisplay.icon, size: common_Icon/* IconSize */.lK.Tiny, UNSAFE_style: { color: statusDisplay.color } }),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '10px', marginLeft: '4px' } }, statusDisplay.text))),
        backend.running && backend.endpoint && (external_react_default().createElement("div", { className: LocalBackendCard_LocalBackendCard_module.Endpoint, onClick: handleCopyEndpoint },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } }, backend.endpoint),
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '10px', marginLeft: '8px' } }, "(click to copy)"))),
        external_react_default().createElement("div", { className: LocalBackendCard_LocalBackendCard_module.Info },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, style: { fontSize: '11px' } },
                "Created ",
                createdDate)),
        external_react_default().createElement("div", { className: LocalBackendCard_LocalBackendCard_module.Actions },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: isOperating ? 'Processing...' : backend.running ? 'Stop' : 'Start', size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: backend.running ? inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted : inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: handleToggle, isDisabled: isOperating }),
                backend.running && (external_react_default().createElement((external_react_default()).Fragment, null,
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Data", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: () => setShowDataBrowser(true) }),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Schema", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: () => setShowSchemaPanel(true) }))),
                onExport && backend.running && (external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Export", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onExport })),
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Trash, size: common_Icon/* IconSize */.lK.Small, onClick: onDelete, isDisabled: backend.running, testId: `delete-local-backend-${backend.id}` }))),
        showSchemaPanel &&
            (0,external_react_dom_.createPortal)(external_react_default().createElement("div", { className: LocalBackendCard_LocalBackendCard_module.SchemaPanelOverlay },
                external_react_default().createElement(SchemaPanel, { backendId: backend.id, backendName: backend.name, isRunning: backend.running, onClose: () => setShowSchemaPanel(false) })), document.body),
        showDataBrowser &&
            (0,external_react_dom_.createPortal)(external_react_default().createElement("div", { className: LocalBackendCard_LocalBackendCard_module.SchemaPanelOverlay },
                external_react_default().createElement(DataBrowser, { backendId: backend.id, backendName: backend.name, onClose: () => setShowDataBrowser(false) })), document.body)));
}

;// ./src/editor/src/views/panels/BackendServicesPanel/BackendServicesPanel.tsx
/**
 * Backend Services Panel
 *
 * Main panel for managing backend database connections (BYOB).
 * Similar in structure to CloudServicePanel.
 *
 * @module BackendServicesPanel
 * @since 1.2.0
 */



















function BackendServicesPanel() {
    const [backends, setBackends] = (0,external_react_.useState)(BackendServices.instance.backends);
    const [activeBackendId, setActiveBackendId] = (0,external_react_.useState)(BackendServices.instance.activeBackendId);
    const [isLoading, setIsLoading] = (0,external_react_.useState)(false);
    const [isAddDialogVisible, setIsAddDialogVisible] = (0,external_react_.useState)(false);
    const [hasActivity, setHasActivity] = (0,external_react_.useState)(false);
    // Local backend creation state
    const [isAddLocalVisible, setIsAddLocalVisible] = (0,external_react_.useState)(false);
    const [newLocalBackendName, setNewLocalBackendName] = (0,external_react_.useState)('');
    // Local backends hook
    const { backends: localBackends, isLoading: isLoadingLocal, createBackend: createLocalBackend, deleteBackend: deleteLocalBackend, startBackend: startLocalBackend, stopBackend: stopLocalBackend } = useLocalBackends();
    // Initialize backends on mount
    (0,external_react_.useEffect)(() => {
        setIsLoading(true);
        BackendServices.instance.initialize().finally(() => {
            setBackends(BackendServices.instance.backends);
            setActiveBackendId(BackendServices.instance.activeBackendId);
            setIsLoading(false);
        });
    }, []);
    // Listen for backend changes
    (0,useEventListener/* useEventListener */.M)(BackendServices.instance, BackendServicesEvent.BackendsChanged, () => {
        setBackends([...BackendServices.instance.backends]);
    });
    (0,useEventListener/* useEventListener */.M)(BackendServices.instance, BackendServicesEvent.ActiveBackendChanged, (id) => {
        setActiveBackendId(id);
    });
    // Delete confirmation dialog for external backends
    const [DeleteDialog, confirmDelete] = useConfirmationDialog({
        title: 'Delete Backend',
        message: 'Are you sure you want to delete this backend configuration? This cannot be undone.',
        isDangerousAction: true
    });
    // Delete confirmation dialog for local backends
    const [DeleteLocalDialog, confirmDeleteLocal] = useConfirmationDialog({
        title: 'Delete Local Backend',
        message: 'Delete this local backend? All data will be permanently lost.',
        isDangerousAction: true
    });
    // Handle delete local backend
    const handleDeleteLocalBackend = (0,external_react_.useCallback)(async (id) => {
        try {
            await confirmDeleteLocal();
            await deleteLocalBackend(id);
        }
        catch {
            // User cancelled
        }
    }, [confirmDeleteLocal, deleteLocalBackend]);
    // Handle create local backend
    const handleCreateLocalBackend = (0,external_react_.useCallback)(async () => {
        if (newLocalBackendName.trim()) {
            await createLocalBackend(newLocalBackendName.trim());
            setNewLocalBackendName('');
            setIsAddLocalVisible(false);
        }
    }, [newLocalBackendName, createLocalBackend]);
    // Handle delete backend
    const handleDeleteBackend = (0,external_react_.useCallback)(async (id) => {
        try {
            await confirmDelete();
            // If we get here, user confirmed
            setHasActivity(true);
            try {
                await BackendServices.instance.deleteBackend(id);
            }
            finally {
                setHasActivity(false);
            }
        }
        catch {
            // User cancelled - do nothing
        }
    }, [confirmDelete]);
    // Handle set active backend
    const handleSetActive = (0,external_react_.useCallback)((id) => {
        BackendServices.instance.setActiveBackend(id);
    }, []);
    // Handle test connection
    const handleTestConnection = (0,external_react_.useCallback)(async (id) => {
        setHasActivity(true);
        try {
            const backend = BackendServices.instance.getBackend(id);
            if (backend) {
                await BackendServices.instance.testConnection(backend);
                setBackends([...BackendServices.instance.backends]);
            }
        }
        finally {
            setHasActivity(false);
        }
    }, []);
    // Handle fetch schema
    const handleFetchSchema = (0,external_react_.useCallback)(async (id) => {
        setHasActivity(true);
        try {
            await BackendServices.instance.fetchSchema(id);
            setBackends([...BackendServices.instance.backends]);
        }
        finally {
            setHasActivity(false);
        }
    }, []);
    return (external_react_default().createElement(BasePanel, { title: "Backend Services", hasActivityBlocker: hasActivity, hasContentScroll: true },
        external_react_default().createElement(DeleteDialog, null),
        external_react_default().createElement(DeleteLocalDialog, null),
        isLoading || isLoadingLocal ? (external_react_default().createElement(Container, { hasLeftSpacing: true, hasTopSpacing: true },
            external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null))) : (external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement(Section/* Section */.w, { title: "Local Backends", variant: Section/* SectionVariant */.$.Panel, actions: !isAddLocalVisible && (external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Plus, size: common_Icon/* IconSize */.lK.Small, onClick: () => setIsAddLocalVisible(true), testId: "add-local-backend-button" })) },
                isAddLocalVisible && (external_react_default().createElement(Container, { hasLeftSpacing: true, hasRightSpacing: true, hasTopSpacing: true, hasBottomSpacing: true },
                    external_react_default().createElement(Stack/* VStack */.Tk, null,
                        external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, "Create Local Backend"),
                        external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
                            external_react_default().createElement(TextInput, { value: newLocalBackendName, onChange: (e) => setNewLocalBackendName(e.target.value), placeholder: "Backend name", onKeyDown: (e) => {
                                    if (e.key === 'Enter')
                                        handleCreateLocalBackend();
                                    if (e.key === 'Escape') {
                                        setIsAddLocalVisible(false);
                                        setNewLocalBackendName('');
                                    }
                                } })),
                        external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
                            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Create", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: handleCreateLocalBackend, isDisabled: !newLocalBackendName.trim() }),
                                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: () => {
                                        setIsAddLocalVisible(false);
                                        setNewLocalBackendName('');
                                    } })))))),
                localBackends.length > 0 ? (external_react_default().createElement(Stack/* VStack */.Tk, null, localBackends.map((backend) => (external_react_default().createElement(LocalBackendCard, { key: backend.id, backend: backend, onStart: async () => startLocalBackend(backend.id), onStop: async () => stopLocalBackend(backend.id), onDelete: () => handleDeleteLocalBackend(backend.id) }))))) : (!isAddLocalVisible && (external_react_default().createElement(Container, { hasLeftSpacing: true, hasTopSpacing: true, hasBottomSpacing: true },
                    external_react_default().createElement(typography_Text/* Text */.EY, null, "No local backends"),
                    external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
                        external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "Create a local SQLite backend for zero-config database development.")))))),
            external_react_default().createElement(Section/* Section */.w, { title: "External Backends", variant: Section/* SectionVariant */.$.Panel, actions: external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Plus, size: common_Icon/* IconSize */.lK.Small, onClick: () => setIsAddDialogVisible(true), testId: "add-backend-button" }) }, backends.length > 0 ? (external_react_default().createElement(Stack/* VStack */.Tk, null, backends.map((backend) => (external_react_default().createElement(BackendCard, { key: backend.id, backend: backend, isActive: backend.id === activeBackendId, onSetActive: () => handleSetActive(backend.id), onDelete: () => handleDeleteBackend(backend.id), onTestConnection: () => handleTestConnection(backend.id), onFetchSchema: () => handleFetchSchema(backend.id) }))))) : (external_react_default().createElement(Container, { hasLeftSpacing: true, hasTopSpacing: true, hasBottomSpacing: true },
                external_react_default().createElement(typography_Text/* Text */.EY, null, "No external backends configured"),
                external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "Click the + button to add a Directus, Supabase, or custom REST backend."))))))),
        external_react_default().createElement(AddBackendDialog, { isVisible: isAddDialogVisible, onClose: () => setIsAddDialogVisible(false), onCreated: () => {
                setIsAddDialogVisible(false);
                setBackends([...BackendServices.instance.backends]);
            } })));
}

;// ./src/editor/src/hooks/useActiveEnvironment.ts


function useActiveEnvironment(project) {
    const [environment, setEnvironment] = (0,external_react_.useState)(null);
    const [group] = (0,external_react_.useState)({});
    (0,external_react_.useEffect)(() => {
        function update() {
            CloudServices.CloudService.instance.getActiveEnvironment(project).then((env) => setEnvironment(env));
        }
        update();
        project.on('cloudServicesChanged', update, group);
        return function () {
            project.off(group);
        };
    }, []);
    return environment;
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/ActionButton/ActionButton.module.scss
var ActionButton_module = __webpack_require__(78318);
;// ../noodl-core-ui/src/components/inputs/ActionButton/ActionButton.module.scss

      
      
      
      
      
      
      
      
      

var ActionButton_module_options = {};

ActionButton_module_options.styleTagTransform = (styleTagTransform_default());
ActionButton_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ActionButton_module_options.insert = insertBySelector_default().bind(null, "head");
    
ActionButton_module_options.domAPI = (styleDomAPI_default());
ActionButton_module_options.insertStyleElement = (insertStyleElement_default());

var ActionButton_module_update = injectStylesIntoStyleTag_default()(ActionButton_module/* default */.A, ActionButton_module_options);




       /* harmony default export */ const ActionButton_ActionButton_module = (ActionButton_module/* default */.A && ActionButton_module/* default */.A.locals ? ActionButton_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/ActionButton/ActionButton.tsx






var ActionButtonVariant;
(function (ActionButtonVariant) {
    ActionButtonVariant["Default"] = "default";
    ActionButtonVariant["Secondary"] = "secondary";
    ActionButtonVariant["OnBg2"] = "on-bg-2";
    /** CallToAction is when the user __can__ act, but it is doing something. */
    ActionButtonVariant["CallToAction"] = "user-action";
    ActionButtonVariant["Background"] = "background";
    /** BackgroundAction is when the user __can't__ act */
    ActionButtonVariant["BackgroundAction"] = "background-action";
    ActionButtonVariant["Proud"] = "proud";
})(ActionButtonVariant || (ActionButtonVariant = {}));
function ActionButton({ variant = ActionButtonVariant.Default, icon = common_Icon/* IconName */.$M.Refresh, affixIcon, prefixText, label, affixText, hasTopDivider, isDisabled = false, hasNoBottomBorder, isInactive, onClick, onMouseEnter, onMouseLeave, onFocus, onBlur, testId }) {
    const iconVariant = (0,external_react_.useMemo)(() => {
        switch (variant) {
            default:
                return typography_Text/* TextType */.M2.Default;
            case ActionButtonVariant.CallToAction:
                return typography_Text/* TextType */.M2.Shy;
        }
    }, [variant]);
    return (external_react_default().createElement("button", { className: external_classnames_default()([
            ActionButton_ActionButton_module['Root'],
            ActionButton_ActionButton_module[`is-variant-${variant}`],
            hasNoBottomBorder && ActionButton_ActionButton_module['has-no-bottom-border'],
            isInactive && ActionButton_ActionButton_module['is-inactive'],
            hasTopDivider && ActionButton_ActionButton_module['has-top-divider']
        ]), onClick: (e) => {
            if (onClick)
                onClick(e);
        }, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, onFocus: onFocus, onBlur: onBlur, disabled: isDisabled, "data-test": testId },
        external_react_default().createElement("div", { className: external_classnames_default()(ActionButton_ActionButton_module['Container']) },
            external_react_default().createElement("div", { className: external_classnames_default()(ActionButton_ActionButton_module['Icon'], isDisabled && ActionButton_ActionButton_module['is-disabled']) },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: icon })),
            external_react_default().createElement("div", { className: external_classnames_default()(ActionButton_ActionButton_module['Text'], isDisabled && ActionButton_ActionButton_module['is-disabled']) },
                Boolean(prefixText) && external_react_default().createElement("small", { className: ActionButton_ActionButton_module['Label'] }, prefixText),
                Boolean(typeof label === 'string') ? external_react_default().createElement("p", { className: ActionButton_ActionButton_module['Label'] }, label) : label,
                Boolean(affixText) && external_react_default().createElement("small", { className: ActionButton_ActionButton_module['Label'] }, affixText)),
            Boolean(affixIcon) && (external_react_default().createElement("div", { className: external_classnames_default()(ActionButton_ActionButton_module['Icon'], isDisabled && ActionButton_ActionButton_module['is-disabled']) },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: affixIcon, variant: iconVariant })))),
        variant === ActionButtonVariant.BackgroundAction && external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null)));
}

;// ../noodl-core-ui/src/components/inputs/ActionButton/index.ts


;// ./src/editor/src/views/DialogLayer/components/ConfirmDialog/ConfirmDialog.tsx






function ConfirmDialog({ title, text, confirmText, abortText, onConfirm, onAbort }) {
    return (external_react_default().createElement(BaseDialog/* CoreBaseDialog */.V9, { title: title, isVisible: true, hasBackdrop: true },
        external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasYSpacing: true, UNSAFE_style: { maxWidth: '400px' } },
            external_react_default().createElement(typography_Text/* Text */.EY, null, text),
            external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
                external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: confirmText !== null && confirmText !== void 0 ? confirmText : 'Confirm', size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, onClick: onConfirm }),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: abortText !== null && abortText !== void 0 ? abortText : 'Cancel', variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, onClick: onAbort }))))));
}

;// ./src/editor/src/views/DialogLayer/components/ConfirmDialog/index.ts


;// ./src/editor/src/models/DialogLayerModel.tsx




var DialogLayerModelEvent;
(function (DialogLayerModelEvent) {
    DialogLayerModelEvent["DialogsChanged"] = "dialogs-changed";
})(DialogLayerModelEvent || (DialogLayerModelEvent = {}));
class DialogLayerModel extends utils_model/* Model */.K {
    get dialogs() {
        return this._order.map((x) => this._dialogs[x]);
    }
    constructor() {
        super();
        this._order = [];
        this._dialogs = {};
        // const showDebug = (index) => {
        //   this.showConfirm({
        //     title: 'Hello World',
        //     text: 'Oh no' + new Array(index + 1).join('!'),
        //     onConfirm() {
        //       showDebug(index + 1);
        //     }
        //   });
        // };
        // showDebug(1);
    }
    closeById(id) {
        if (this._dialogs[id]) {
            this._order = this._order.filter((x) => x !== id);
            delete this._dialogs[id];
            this.notifyListeners(DialogLayerModelEvent.DialogsChanged);
            return true;
        }
        return false;
    }
    showConfirm(props) {
        var _a;
        const { onConfirm, onAbort } = props;
        const id = (_a = props.id) !== null && _a !== void 0 ? _a : (0,utils.guid)();
        props.onConfirm = () => {
            this.closeById(id);
            onConfirm && onConfirm();
        };
        props.onAbort = () => {
            this.closeById(id);
            onAbort && onAbort();
        };
        if (this._dialogs[id]) {
            this._order = this._order.filter((x) => x !== id);
            delete this._dialogs[id];
        }
        this._order.push(id);
        this._dialogs[id] = {
            id,
            slot: () => external_react_default().createElement(ConfirmDialog, { ...props })
        };
        this.notifyListeners(DialogLayerModelEvent.DialogsChanged);
    }
    /**
     * Show a custom dialog component.
     * Returns a close function that can be called to programmatically close the dialog.
     *
     * @param render - Function that receives a close callback and returns JSX
     * @param options - Dialog options including optional id
     * @returns A function to close the dialog
     */
    showDialog(render, options = {}) {
        var _a;
        const id = (_a = options.id) !== null && _a !== void 0 ? _a : (0,utils.guid)();
        const { onClose } = options;
        const close = () => {
            this.closeById(id);
            onClose && onClose();
        };
        // Remove existing dialog with same id if present
        if (this._dialogs[id]) {
            this._order = this._order.filter((x) => x !== id);
            delete this._dialogs[id];
        }
        this._order.push(id);
        this._dialogs[id] = {
            id,
            slot: () => render(close)
        };
        this.notifyListeners(DialogLayerModelEvent.DialogsChanged);
        return close;
    }
}
DialogLayerModel.instance = new DialogLayerModel();

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/ComponentsPanelNew/ComponentsPanel.module.scss
var ComponentsPanel_module = __webpack_require__(53029);
;// ./src/editor/src/views/panels/ComponentsPanelNew/ComponentsPanel.module.scss

      
      
      
      
      
      
      
      
      

var ComponentsPanel_module_options = {};

ComponentsPanel_module_options.styleTagTransform = (styleTagTransform_default());
ComponentsPanel_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ComponentsPanel_module_options.insert = insertBySelector_default().bind(null, "head");
    
ComponentsPanel_module_options.domAPI = (styleDomAPI_default());
ComponentsPanel_module_options.insertStyleElement = (insertStyleElement_default());

var ComponentsPanel_module_update = injectStylesIntoStyleTag_default()(ComponentsPanel_module/* default */.A, ComponentsPanel_module_options);




       /* harmony default export */ const ComponentsPanelNew_ComponentsPanel_module = (ComponentsPanel_module/* default */.A && ComponentsPanel_module/* default */.A.locals ? ComponentsPanel_module/* default */.A.locals : undefined);

// EXTERNAL MODULE: ./src/editor/src/models/componentmodel.ts
var componentmodel = __webpack_require__(16163);
// EXTERNAL MODULE: ./src/editor/src/models/NodeTypeAdapters/RouterAdapter.ts
var RouterAdapter = __webpack_require__(5604);
;// ./src/editor/src/views/panels/ComponentsPanelNew/PageTemplatePopup.tsx





class PageComponentTemplatePopup extends (external_react_default()).Component {
    constructor(props) {
        super(props);
        this.state = {
            router: props.routers !== undefined ? props.routers[0] : undefined
        };
    }
    setComponentName(name) {
        this.componentName = name;
    }
    onAddClicked() {
        this.props.onCreate && this.props.onCreate(this.componentName, this.state.router);
    }
    onCancelClicked() {
        this.props.onCancel && this.props.onCancel();
    }
    render() {
        var _a;
        const hasRouters = this.props.routers !== undefined && this.props.routers.length > 1;
        const routers = (_a = this.props.routers) === null || _a === void 0 ? void 0 : _a.map((router) => ({
            label: router,
            value: router
        }));
        return (external_react_default().createElement("div", { style: {
                width: '300px',
                padding: '7px',
                display: 'flex',
                flexDirection: 'column'
            } },
            external_react_default().createElement(TextInput, { label: "New page name", onRefChange: (ref) => (ref === null || ref === void 0 ? void 0 : ref.current) && ref.current.focus(), onChange: (e) => this.setComponentName(e.target.value), onEnter: () => this.onAddClicked(), hasBottomSpacing: hasRouters, value: this.componentName }),
            hasRouters ? (external_react_default().createElement(Select, { label: "Choose router", value: this.state.router, options: routers, onChange: (r) => this.setState({ router: String(r) }) })) : null,
            external_react_default().createElement(Container, { hasTopSpacing: true },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Add", hasRightSpacing: true, onClick: () => this.onAddClicked() }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: () => this.onCancelClicked() }))));
    }
}

;// ./src/editor/src/views/panels/ComponentsPanelNew/ComponentTemplates.ts









class ComponentTemplate {
    constructor(label, icon) {
        this.label = label;
        this.icon = icon;
    }
    createComponent(componentName, options, undoGroup) {
        // Create component from template
        const component = new componentmodel/* ComponentModel */.j({
            name: componentName,
            graph: nodegraphmodel/* NodeGraphModel */.W2.fromJSON(JSON.parse(JSON.stringify(this.template))),
            id: utils["default"].guid()
        });
        component.rekeyAllIds();
        return component;
    }
    createPopup(options) {
        const popup = new (popuplayer_default()).StringInputPopup({
            label: 'New component name',
            okLabel: 'Add',
            cancelLabel: 'Cancel',
            onOk(localName) {
                options.onCreate(localName);
            },
            onCancel() {
                options.onCancel && options.onCancel();
            }
        });
        popup.render();
        return popup;
    }
}
class VisualComponentTemplate extends ComponentTemplate {
    constructor() {
        super('Visual Component', common_Icon/* IconName */.$M.Component);
        this.parentTypes = ['folder', 'component'];
        this.runtimeTypes = ['browser'];
        this.template = {
            connections: [],
            roots: [
                {
                    id: 'xxx',
                    type: 'Group',
                    x: 0,
                    y: 0,
                    parameters: {},
                    ports: [],
                    dynamicports: [],
                    children: []
                }
            ]
        };
    }
}
class LogicComponentTemplate extends ComponentTemplate {
    constructor() {
        super('Logic Component', common_Icon/* IconName */.$M.Component);
        this.parentTypes = ['folder', 'component'];
        this.runtimeTypes = ['cloud', 'browser'];
        this.template = {
            connections: [],
            roots: [
                {
                    id: 'A',
                    type: 'Component Inputs',
                    x: 0,
                    y: 0,
                    parameters: {},
                    ports: [
                        {
                            name: 'Do',
                            plug: 'output',
                            type: '*'
                        }
                    ],
                    dynamicports: [],
                    children: []
                },
                {
                    id: 'B',
                    type: 'Component Outputs',
                    x: 300,
                    y: 0,
                    parameters: {},
                    ports: [
                        {
                            name: 'Success',
                            plug: 'input',
                            type: '*'
                        },
                        {
                            name: 'Failure',
                            plug: 'input',
                            type: '*'
                        }
                    ],
                    dynamicports: [],
                    children: []
                }
            ]
        };
    }
}
class CloudFunctionComponentTemplate extends ComponentTemplate {
    constructor() {
        super('Cloud Function Component', common_Icon/* IconName */.$M.CloudFunction);
        this.parentTypes = ['folder'];
        this.runtimeTypes = ['cloud'];
        this.template = {
            connections: [],
            roots: [
                {
                    id: 'A',
                    type: 'noodl.cloud.request',
                    x: 0,
                    y: 0,
                    parameters: {},
                    ports: [],
                    dynamicports: [],
                    children: []
                },
                {
                    id: 'B',
                    type: 'noodl.cloud.response',
                    x: 300,
                    y: 0,
                    parameters: {},
                    ports: [],
                    dynamicports: [],
                    children: []
                }
            ]
        };
    }
}
class PageComponentTemplate extends ComponentTemplate {
    constructor() {
        super('Page Component', common_Icon/* IconName */.$M.File);
        this.parentTypes = ['folder'];
        this.runtimeTypes = ['browser'];
        this.template = {
            connections: [],
            roots: [
                {
                    id: 'xxx',
                    type: 'Page',
                    x: 0,
                    y: 0,
                    parameters: {},
                    ports: [],
                    dynamicports: [],
                    children: []
                },
                {
                    id: 'yyy',
                    type: 'PageInputs',
                    x: -100,
                    y: -50,
                    parameters: {},
                    ports: [],
                    dynamicports: [],
                    children: []
                }
            ]
        };
    }
    createComponent(componentName, options, undoGroup) {
        // Create component from template
        const component = new componentmodel/* ComponentModel */.j({
            name: componentName,
            graph: nodegraphmodel/* NodeGraphModel */.W2.fromJSON(JSON.parse(JSON.stringify(this.template))),
            id: utils["default"].guid()
        });
        component.rekeyAllIds();
        // Find the router and add the template to the router
        RouterAdapter/* RouterAdapter */.F.addPageToRouters(options.router, componentName, { undo: undoGroup });
        return component;
    }
    createPopup(options) {
        // Find all routers in the project
        const _routers = RouterAdapter/* RouterAdapter */.F.getRouterNames();
        const props = {
            routers: _routers,
            onCreate(localName, router) {
                options.onCreate(localName, { router });
            },
            onCancel() {
                options.onCancel && options.onCancel();
            }
        };
        const div = document.createElement('div');
        const root = (0,client.createRoot)(div);
        root.render(external_react_default().createElement(PageComponentTemplatePopup, props));
        return { el: $(div) };
    }
}
/**
 * Panel that opens in the sidepanel components header plus icon
 */
class ComponentTemplates {
    constructor() {
        this.templates = [
            new PageComponentTemplate(),
            new VisualComponentTemplate(),
            new LogicComponentTemplate(),
            new CloudFunctionComponentTemplate()
        ];
    }
    getTemplates(args) {
        if (args && (args.forParentType || args.forRuntimeType)) {
            return this.templates.filter((t) => (args.forParentType === undefined || t.parentTypes.indexOf(args.forParentType) !== -1) &&
                (args.forRuntimeType === undefined || t.runtimeTypes.indexOf(args.forRuntimeType) !== -1));
        }
        return this.templates;
    }
}
ComponentTemplates.instance = new ComponentTemplates();

;// ./src/editor/src/views/panels/ComponentsPanelNew/components/RenameInput.tsx
/**
 * RenameInput
 *
 * Inline input field for renaming components/folders.
 * Auto-focuses and selects text on mount.
 */


function RenameInput({ value, onChange, onConfirm, onCancel, level }) {
    const inputRef = (0,external_react_.useRef)(null);
    const indent = level * 12;
    // Auto-focus and select all on mount
    (0,external_react_.useEffect)(() => {
        if (inputRef.current) {
            inputRef.current.focus();
            inputRef.current.select();
        }
    }, []);
    const handleKeyDown = (0,external_react_.useCallback)((e) => {
        console.log('🔍 RenameInput keyDown:', e.key);
        if (e.key === 'Enter') {
            console.log('✅ Enter pressed - calling onConfirm');
            e.preventDefault();
            e.stopPropagation();
            onConfirm();
        }
        else if (e.key === 'Escape') {
            console.log('✅ Escape pressed - calling onCancel');
            e.preventDefault();
            e.stopPropagation();
            onCancel();
        }
    }, [onConfirm, onCancel]);
    const handleBlur = (0,external_react_.useCallback)(() => {
        console.log('🔍 RenameInput blur - calling onConfirm');
        onConfirm();
    }, [onConfirm]);
    const handleChange = (0,external_react_.useCallback)((e) => {
        onChange(e.target.value);
    }, [onChange]);
    return (external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['RenameContainer'], style: { paddingLeft: `${indent + 23}px` } },
        external_react_default().createElement("input", { ref: inputRef, type: "text", className: ComponentsPanelNew_ComponentsPanel_module['RenameInput'], value: value, onChange: handleChange, onKeyDown: handleKeyDown, onBlur: handleBlur })));
}

;// ./src/editor/src/views/panels/ComponentsPanelNew/components/ComponentItem.tsx
/**
 * ComponentItem
 *
 * Renders a single component row with appropriate icon.
 */








// eslint-disable-next-line @typescript-eslint/no-var-requires
const PopupLayer = __webpack_require__(45653);
function ComponentItem({ component, level, isSelected, onClick, onMakeHome, onDelete, onDuplicate, onRename, onOpen, onDragStart, onDrop, canAcceptDrop, onDoubleClick, onAddComponent, onAddFolder, isRenaming, renameValue, onRenameChange, onRenameConfirm, onRenameCancel, sheets, onMoveToSheet }) {
    const indent = level * 12;
    const itemRef = (0,external_react_.useRef)(null);
    const dragStartPos = (0,external_react_.useRef)(null);
    const [isDropTarget, setIsDropTarget] = (0,external_react_.useState)(false);
    // Determine icon based on component type
    let icon = common_Icon/* IconName */.$M.Component;
    if (component.isRoot) {
        icon = common_Icon/* IconName */.$M.Home;
    }
    else if (component.isPage) {
        icon = common_Icon/* IconName */.$M.PageRouter;
    }
    else if (component.isCloudFunction) {
        icon = common_Icon/* IconName */.$M.CloudFunction;
    }
    else if (component.isVisual) {
        icon = common_Icon/* IconName */.$M.UI;
    }
    // Drag handlers
    const handleMouseDown = (0,external_react_.useCallback)((e) => {
        dragStartPos.current = { x: e.clientX, y: e.clientY };
    }, []);
    const handleMouseMove = (0,external_react_.useCallback)((e) => {
        if (!dragStartPos.current || !onDragStart)
            return;
        // Check if mouse moved enough to start drag (5px threshold)
        const dx = e.clientX - dragStartPos.current.x;
        const dy = e.clientY - dragStartPos.current.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        if (distance > 5 && itemRef.current) {
            const node = { type: 'component', data: component };
            onDragStart(node, itemRef.current);
            dragStartPos.current = null;
        }
    }, [component, onDragStart]);
    const handleMouseUp = (0,external_react_.useCallback)((e) => {
        dragStartPos.current = null;
        // If this item is a valid drop target, execute the drop
        if (isDropTarget && onDrop) {
            e.stopPropagation(); // Prevent bubble to Tree (for root drop fallback)
            // End drag IMMEDIATELY at event handler level (before action chain)
            // This matches the working root drop pattern
            PopupLayer.instance.dragCompleted();
            const node = { type: 'component', data: component };
            onDrop(node);
            setIsDropTarget(false);
        }
    }, [isDropTarget, component, onDrop]);
    // Drop handlers
    const handleMouseEnter = (0,external_react_.useCallback)(() => {
        if (PopupLayer.instance.isDragging() && canAcceptDrop) {
            const node = { type: 'component', data: component };
            if (canAcceptDrop(node)) {
                setIsDropTarget(true);
                PopupLayer.instance.indicateDropType('move');
            }
        }
    }, [component, canAcceptDrop]);
    const handleMouseLeave = (0,external_react_.useCallback)(() => {
        setIsDropTarget(false);
        if (PopupLayer.instance.isDragging()) {
            PopupLayer.instance.indicateDropType('none');
        }
    }, []);
    const handleDrop = (0,external_react_.useCallback)(() => {
        if (isDropTarget && onDrop) {
            const node = { type: 'component', data: component };
            onDrop(node);
            setIsDropTarget(false);
        }
    }, [isDropTarget, component, onDrop]);
    const handleContextMenu = (0,external_react_.useCallback)((e) => {
        e.preventDefault();
        e.stopPropagation();
        // Clear drag state to prevent phantom drags after menu closes
        dragStartPos.current = null;
        const node = { type: 'component', data: component };
        // Calculate parent path for new components (nested inside this component)
        // Use the component's full path + "/" to nest inside it
        const parentPath = component.path + '/';
        const items = [];
        // Add "Create" menu items if handlers are provided
        if (onAddComponent && onAddFolder) {
            // Get templates for browser runtime (default)
            const templates = ComponentTemplates.instance.getTemplates({
                forRuntimeType: 'browser'
            });
            // Add template creation items
            templates.forEach((template) => {
                items.push({
                    icon: template.icon,
                    label: `Create ${template.label}`,
                    onClick: () => onAddComponent(template, parentPath)
                });
            });
            // Add folder creation
            items.push('divider');
            items.push({
                icon: common_Icon/* IconName */.$M.FolderClosed,
                label: 'Create Folder',
                onClick: () => onAddFolder(parentPath)
            });
            items.push('divider');
        }
        // Add existing menu items
        items.push({
            label: 'Open',
            onClick: () => onOpen === null || onOpen === void 0 ? void 0 : onOpen(node)
        });
        items.push('divider');
        // Only show "Make Home" for pages or visual components (not logic/cloud functions)
        if (component.isPage || component.isVisual) {
            items.push({
                label: 'Make Home',
                disabled: component.isRoot,
                onClick: () => onMakeHome === null || onMakeHome === void 0 ? void 0 : onMakeHome(node)
            });
            items.push('divider');
        }
        items.push({
            label: 'Rename',
            onClick: () => onRename === null || onRename === void 0 ? void 0 : onRename(node)
        });
        items.push({
            label: 'Duplicate',
            onClick: () => onDuplicate === null || onDuplicate === void 0 ? void 0 : onDuplicate(node)
        });
        // Add "Move to" option if sheets are available
        if (sheets && sheets.length > 0 && onMoveToSheet) {
            items.push('divider');
            // "Move to" opens a separate popup with sheet options
            items.push({
                label: 'Move to...',
                icon: common_Icon/* IconName */.$M.FolderClosed,
                onClick: () => {
                    // Determine which sheet this component is currently in
                    const currentSheetFolder = sheets.find((s) => !s.isDefault && component.path.startsWith('/' + s.folderName + '/'));
                    const isInDefaultSheet = !currentSheetFolder;
                    // Create sheet selection menu items
                    const sheetItems = sheets.map((sheet) => {
                        const isCurrentSheet = sheet.isDefault
                            ? isInDefaultSheet
                            : sheet.folderName === (currentSheetFolder === null || currentSheetFolder === void 0 ? void 0 : currentSheetFolder.folderName);
                        return {
                            label: sheet.name + (isCurrentSheet ? ' (current)' : ''),
                            icon: sheet.isDefault ? common_Icon/* IconName */.$M.Component : common_Icon/* IconName */.$M.FolderClosed,
                            isDisabled: isCurrentSheet,
                            isHighlighted: isCurrentSheet,
                            onClick: () => {
                                if (!isCurrentSheet) {
                                    onMoveToSheet(component.name, sheet);
                                }
                            }
                        };
                    });
                    // Show the sheet selection popup
                    (0,ShowContextMenuInPopup.showContextMenuInPopup)({
                        items: sheetItems,
                        width: MenuDialog.MenuDialogWidth.Default
                    });
                }
            });
        }
        items.push('divider');
        items.push({
            label: 'Delete',
            onClick: () => onDelete === null || onDelete === void 0 ? void 0 : onDelete(node)
        });
        (0,ShowContextMenuInPopup.showContextMenuInPopup)({
            items,
            width: MenuDialog.MenuDialogWidth.Default
        });
    }, [component, onOpen, onMakeHome, onRename, onDuplicate, onDelete, onAddComponent, onAddFolder, sheets, onMoveToSheet]);
    const handleDoubleClick = (0,external_react_.useCallback)(() => {
        if (onDoubleClick) {
            const node = { type: 'component', data: component };
            onDoubleClick(node);
        }
    }, [component, onDoubleClick]);
    // Show rename input if in rename mode
    if (isRenaming && renameValue !== undefined && onRenameChange && onRenameConfirm && onRenameCancel) {
        return (external_react_default().createElement(RenameInput, { value: renameValue, onChange: onRenameChange, onConfirm: onRenameConfirm, onCancel: onRenameCancel, level: level }));
    }
    return (external_react_default().createElement("div", { ref: itemRef, className: external_classnames_default()(ComponentsPanelNew_ComponentsPanel_module['TreeItem'], {
            [ComponentsPanelNew_ComponentsPanel_module['Selected']]: isSelected,
            [ComponentsPanelNew_ComponentsPanel_module['DropTarget']]: isDropTarget
        }), style: { paddingLeft: `${indent + 23}px` }, onClick: onClick, onDoubleClick: handleDoubleClick, onContextMenu: handleContextMenu, onMouseDown: handleMouseDown, onMouseMove: handleMouseMove, onMouseUp: handleMouseUp, onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, onDrop: handleDrop },
        external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['ItemContent'] },
            external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['Icon'] },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: icon })),
            external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['Label'] }, component.localName),
            component.hasWarnings && external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['Warning'] }, "!"))));
}

;// ./src/editor/src/views/panels/ComponentsPanelNew/components/FolderItem.tsx
/**
 * FolderItem
 *
 * Renders a folder row with caret and folder icon.
 */








// eslint-disable-next-line @typescript-eslint/no-var-requires
const FolderItem_PopupLayer = __webpack_require__(45653);
function FolderItem({ folder, level, isExpanded, isSelected, onCaretClick, onClick, children, onDelete, onRename, onDragStart, onDrop, canAcceptDrop, onDoubleClick, onAddComponent, onAddFolder, isRenaming, renameValue, onRenameChange, onRenameConfirm, onRenameCancel, sheets, onMoveToSheet, onOpen, onMakeHome, onDuplicate }) {
    const indent = level * 12;
    const itemRef = (0,external_react_.useRef)(null);
    const dragStartPos = (0,external_react_.useRef)(null);
    const [isDropTarget, setIsDropTarget] = (0,external_react_.useState)(false);
    // Drag handlers
    const handleMouseDown = (0,external_react_.useCallback)((e) => {
        dragStartPos.current = { x: e.clientX, y: e.clientY };
    }, []);
    const handleMouseMove = (0,external_react_.useCallback)((e) => {
        if (!dragStartPos.current || !onDragStart)
            return;
        // Check if mouse moved enough to start drag (5px threshold)
        const dx = e.clientX - dragStartPos.current.x;
        const dy = e.clientY - dragStartPos.current.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        if (distance > 5 && itemRef.current) {
            const node = { type: 'folder', data: folder };
            onDragStart(node, itemRef.current);
            dragStartPos.current = null;
        }
    }, [folder, onDragStart]);
    const handleMouseUp = (0,external_react_.useCallback)((e) => {
        dragStartPos.current = null;
        // If this folder is a valid drop target, execute the drop
        if (isDropTarget && onDrop) {
            e.stopPropagation(); // Prevent bubble to Tree (for root drop fallback)
            // End drag IMMEDIATELY at event handler level (before action chain)
            // This matches the working root drop pattern
            FolderItem_PopupLayer.instance.dragCompleted();
            const node = { type: 'folder', data: folder };
            onDrop(node);
            setIsDropTarget(false);
        }
    }, [isDropTarget, folder, onDrop]);
    // Drop handlers
    const handleMouseEnter = (0,external_react_.useCallback)(() => {
        if (FolderItem_PopupLayer.instance.isDragging() && canAcceptDrop) {
            const node = { type: 'folder', data: folder };
            if (canAcceptDrop(node)) {
                setIsDropTarget(true);
                FolderItem_PopupLayer.instance.indicateDropType('move');
            }
        }
    }, [folder, canAcceptDrop]);
    const handleMouseLeave = (0,external_react_.useCallback)(() => {
        setIsDropTarget(false);
        if (FolderItem_PopupLayer.instance.isDragging()) {
            FolderItem_PopupLayer.instance.indicateDropType('none');
        }
    }, []);
    const handleDrop = (0,external_react_.useCallback)(() => {
        if (isDropTarget && onDrop) {
            const node = { type: 'folder', data: folder };
            onDrop(node);
            setIsDropTarget(false);
        }
    }, [isDropTarget, folder, onDrop]);
    const handleContextMenu = (0,external_react_.useCallback)((e) => {
        e.preventDefault();
        e.stopPropagation();
        // Clear drag state to prevent phantom drags after menu closes
        dragStartPos.current = null;
        const node = { type: 'folder', data: folder };
        // Parent path for new items in this folder
        const parentPath = folder.path === '/' ? '/' : folder.path + '/';
        const items = [];
        // Add "Create" menu items if handlers are provided
        if (onAddComponent && onAddFolder) {
            // Get templates for browser runtime (default)
            const templates = ComponentTemplates.instance.getTemplates({
                forRuntimeType: 'browser'
            });
            // Add template creation items
            templates.forEach((template) => {
                items.push({
                    icon: template.icon,
                    label: `Create ${template.label}`,
                    onClick: () => onAddComponent(template, parentPath)
                });
            });
            // Add folder creation
            items.push('divider');
            items.push({
                icon: common_Icon/* IconName */.$M.FolderClosed,
                label: 'Create Folder',
                onClick: () => onAddFolder(parentPath)
            });
            items.push('divider');
        }
        // For component-folders, add component-specific actions (Open, Make Home, Duplicate)
        if (folder.isComponentFolder && folder.component) {
            items.push({
                label: 'Open',
                onClick: () => onOpen === null || onOpen === void 0 ? void 0 : onOpen(node)
            });
            items.push('divider');
            // Only show "Make Home" for pages or visual components (not logic/cloud functions)
            if (folder.isPage || folder.isVisual) {
                items.push({
                    label: 'Make Home',
                    disabled: folder.isRoot,
                    onClick: () => onMakeHome === null || onMakeHome === void 0 ? void 0 : onMakeHome(node)
                });
                items.push('divider');
            }
        }
        // Add rename (available for all folders)
        items.push({
            label: 'Rename',
            onClick: () => onRename === null || onRename === void 0 ? void 0 : onRename(node)
        });
        // Add duplicate for component-folders
        if (folder.isComponentFolder && folder.component) {
            items.push({
                label: 'Duplicate',
                onClick: () => onDuplicate === null || onDuplicate === void 0 ? void 0 : onDuplicate(node)
            });
        }
        // Add "Move to" option for any folder that has a path and sheets are available
        // Works for both component-folders and regular folders
        if (folder.path && sheets && sheets.length > 0 && onMoveToSheet) {
            items.push('divider');
            // Use component.name for component-folders, folder.path for regular folders
            const folderPath = folder.isComponentFolder && folder.component ? folder.component.name : folder.path;
            // "Move to" opens a separate popup with sheet options
            items.push({
                label: 'Move to...',
                icon: common_Icon/* IconName */.$M.FolderClosed,
                onClick: () => {
                    // Determine which sheet this folder is currently in
                    const currentSheetFolder = sheets.find((s) => !s.isDefault && folderPath.startsWith('/' + s.folderName + '/'));
                    const isInDefaultSheet = !currentSheetFolder;
                    // Create sheet selection menu items
                    const sheetItems = sheets.map((sheet) => {
                        const isCurrentSheet = sheet.isDefault
                            ? isInDefaultSheet
                            : sheet.folderName === (currentSheetFolder === null || currentSheetFolder === void 0 ? void 0 : currentSheetFolder.folderName);
                        return {
                            label: sheet.name + (isCurrentSheet ? ' (current)' : ''),
                            icon: sheet.isDefault ? common_Icon/* IconName */.$M.Component : common_Icon/* IconName */.$M.FolderClosed,
                            isDisabled: isCurrentSheet,
                            isHighlighted: isCurrentSheet,
                            onClick: () => {
                                if (!isCurrentSheet) {
                                    onMoveToSheet(folderPath, sheet);
                                }
                            }
                        };
                    });
                    // Show the sheet selection popup
                    (0,ShowContextMenuInPopup.showContextMenuInPopup)({
                        items: sheetItems,
                        width: MenuDialog.MenuDialogWidth.Default
                    });
                }
            });
        }
        items.push('divider');
        items.push({
            label: 'Delete',
            onClick: () => onDelete === null || onDelete === void 0 ? void 0 : onDelete(node)
        });
        (0,ShowContextMenuInPopup.showContextMenuInPopup)({
            items,
            width: MenuDialog.MenuDialogWidth.Default
        });
    }, [folder, onRename, onDelete, onAddComponent, onAddFolder, sheets, onMoveToSheet, onOpen, onMakeHome, onDuplicate]);
    const handleDoubleClick = (0,external_react_.useCallback)(() => {
        if (onDoubleClick) {
            const node = { type: 'folder', data: folder };
            onDoubleClick(node);
        }
    }, [folder, onDoubleClick]);
    // Show rename input if in rename mode
    if (isRenaming && renameValue !== undefined && onRenameChange && onRenameConfirm && onRenameCancel) {
        return (external_react_default().createElement(RenameInput, { value: renameValue, onChange: onRenameChange, onConfirm: onRenameConfirm, onCancel: onRenameCancel, level: level }));
    }
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement("div", { ref: itemRef, className: external_classnames_default()(ComponentsPanelNew_ComponentsPanel_module['TreeItem'], {
                [ComponentsPanelNew_ComponentsPanel_module['Selected']]: isSelected,
                [ComponentsPanelNew_ComponentsPanel_module['DropTarget']]: isDropTarget
            }), style: { paddingLeft: `${indent + 10}px` }, onContextMenu: handleContextMenu, onDoubleClick: handleDoubleClick, onMouseDown: handleMouseDown, onMouseMove: handleMouseMove, onMouseUp: handleMouseUp, onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, onDrop: handleDrop },
            external_react_default().createElement("div", { className: external_classnames_default()(ComponentsPanelNew_ComponentsPanel_module['Caret'], {
                    [ComponentsPanelNew_ComponentsPanel_module['Expanded']]: isExpanded
                }), onClick: (e) => {
                    e.stopPropagation();
                    onCaretClick();
                } }, "\u25B6"),
            external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['ItemContent'], onClick: onClick },
                external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['Icon'] },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: folder.isComponentFolder ? common_Icon/* IconName */.$M.ComponentWithChildren : common_Icon/* IconName */.$M.FolderClosed })),
                external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['Label'] }, folder.name))),
        children));
}

;// ./src/editor/src/views/panels/ComponentsPanelNew/components/ComponentTree.tsx
/**
 * ComponentTree
 *
 * Recursively renders the component/folder tree structure.
 */



function ComponentTree({ nodes, level = 0, onItemClick, onCaretClick, expandedFolders, selectedId, onMakeHome, onDelete, onDuplicate, onRename, onOpen, onDragStart, onDrop, canAcceptDrop, onAddComponent, onAddFolder, renamingItem, renameValue, onRenameChange, onRenameConfirm, onRenameCancel, onDoubleClick, sheets, onMoveToSheet }) {
    return (external_react_default().createElement((external_react_default()).Fragment, null, nodes.map((node) => {
        // Check if this item is being renamed
        const isRenaming = renamingItem &&
            ((node.type === 'component' && renamingItem.type === 'component' && node.data.id === renamingItem.data.id) ||
                (node.type === 'folder' && renamingItem.type === 'folder' && node.data.path === renamingItem.data.path));
        if (node.type === 'folder') {
            return (external_react_default().createElement(FolderItem, { key: node.data.path, folder: node.data, level: level, isExpanded: expandedFolders.has(node.data.path), isSelected: selectedId === node.data.path, onCaretClick: () => onCaretClick(node.data.path), onClick: () => onItemClick(node), onDelete: onDelete, onRename: onRename, onDragStart: onDragStart, onDrop: onDrop, canAcceptDrop: canAcceptDrop, onDoubleClick: onDoubleClick, onAddComponent: onAddComponent, onAddFolder: onAddFolder, isRenaming: isRenaming, renameValue: renameValue, onRenameChange: onRenameChange, onRenameConfirm: onRenameConfirm, onRenameCancel: onRenameCancel, sheets: sheets, onMoveToSheet: onMoveToSheet, onOpen: onOpen, onMakeHome: onMakeHome, onDuplicate: onDuplicate }, expandedFolders.has(node.data.path) && node.data.children.length > 0 && (external_react_default().createElement(ComponentTree, { nodes: node.data.children, level: level + 1, onItemClick: onItemClick, onCaretClick: onCaretClick, expandedFolders: expandedFolders, selectedId: selectedId, onMakeHome: onMakeHome, onDelete: onDelete, onDuplicate: onDuplicate, onRename: onRename, onOpen: onOpen, onDragStart: onDragStart, onDrop: onDrop, canAcceptDrop: canAcceptDrop, onAddComponent: onAddComponent, onAddFolder: onAddFolder, renamingItem: renamingItem, renameValue: renameValue, onRenameChange: onRenameChange, onRenameConfirm: onRenameConfirm, onRenameCancel: onRenameCancel, onDoubleClick: onDoubleClick, sheets: sheets, onMoveToSheet: onMoveToSheet }))));
        }
        else {
            return (external_react_default().createElement(ComponentItem, { key: node.data.id, component: node.data, level: level, isSelected: selectedId === node.data.name, onClick: () => onItemClick(node), onMakeHome: onMakeHome, onDelete: onDelete, onDuplicate: onDuplicate, onRename: onRename, onOpen: onOpen, onDragStart: onDragStart, onDrop: onDrop, canAcceptDrop: canAcceptDrop, onDoubleClick: onDoubleClick, onAddComponent: onAddComponent, onAddFolder: onAddFolder, isRenaming: isRenaming, renameValue: renameValue, onRenameChange: onRenameChange, onRenameConfirm: onRenameConfirm, onRenameCancel: onRenameCancel, sheets: sheets, onMoveToSheet: onMoveToSheet }));
        }
    })));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/ComponentsPanelNew/components/SheetSelector.module.scss
var SheetSelector_module = __webpack_require__(93774);
;// ./src/editor/src/views/panels/ComponentsPanelNew/components/SheetSelector.module.scss

      
      
      
      
      
      
      
      
      

var SheetSelector_module_options = {};

SheetSelector_module_options.styleTagTransform = (styleTagTransform_default());
SheetSelector_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      SheetSelector_module_options.insert = insertBySelector_default().bind(null, "head");
    
SheetSelector_module_options.domAPI = (styleDomAPI_default());
SheetSelector_module_options.insertStyleElement = (insertStyleElement_default());

var SheetSelector_module_update = injectStylesIntoStyleTag_default()(SheetSelector_module/* default */.A, SheetSelector_module_options);




       /* harmony default export */ const components_SheetSelector_module = (SheetSelector_module/* default */.A && SheetSelector_module/* default */.A.locals ? SheetSelector_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/ComponentsPanelNew/components/SheetSelector.tsx
/**
 * SheetSelector
 *
 * Dropdown component for selecting and managing component sheets.
 * Sheets are top-level organizational folders starting with #.
 */




/**
 * SheetSelector displays a dropdown to switch between component sheets.
 * When no sheet is selected, all components are shown.
 */
function SheetSelector({ sheets, currentSheet, onSelectSheet, onCreateSheet, onRenameSheet, onDeleteSheet, disabled = false }) {
    const [isOpen, setIsOpen] = (0,external_react_.useState)(false);
    const [activeSheetMenu, setActiveSheetMenu] = (0,external_react_.useState)(null);
    const dropdownRef = (0,external_react_.useRef)(null);
    // Close dropdown and action menu when clicking outside
    (0,external_react_.useEffect)(() => {
        if (!isOpen)
            return;
        const handleClickOutside = (e) => {
            if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
                setIsOpen(false);
                setActiveSheetMenu(null);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, [isOpen]);
    // Close action menu when clicking elsewhere in the dropdown (but not outside)
    (0,external_react_.useEffect)(() => {
        if (!activeSheetMenu)
            return;
        const handleClickInDropdown = (e) => {
            // Check if click is inside the dropdown but outside the action menu area
            const target = e.target;
            const isInsideActionMenu = target.closest(`.${components_SheetSelector_module['ActionMenu']}`) || target.closest(`.${components_SheetSelector_module['ActionButton']}`);
            if (!isInsideActionMenu) {
                setActiveSheetMenu(null);
            }
        };
        document.addEventListener('mousedown', handleClickInDropdown);
        return () => document.removeEventListener('mousedown', handleClickInDropdown);
    }, [activeSheetMenu]);
    // Close dropdown on escape
    (0,external_react_.useEffect)(() => {
        if (!isOpen)
            return;
        const handleKeyDown = (e) => {
            if (e.key === 'Escape') {
                setIsOpen(false);
            }
        };
        document.addEventListener('keydown', handleKeyDown);
        return () => document.removeEventListener('keydown', handleKeyDown);
    }, [isOpen]);
    const handleToggle = (0,external_react_.useCallback)(() => {
        if (!disabled) {
            setIsOpen((prev) => !prev);
        }
    }, [disabled]);
    const handleSelectSheet = (0,external_react_.useCallback)((sheet) => {
        onSelectSheet(sheet);
        setIsOpen(false);
    }, [onSelectSheet]);
    const handleCreateSheet = (0,external_react_.useCallback)(() => {
        // Close dropdown first
        setIsOpen(false);
        // Delay popup to allow dropdown to fully close and React to complete its render cycle
        // This prevents timing conflicts between dropdown close and popup open
        setTimeout(() => {
            onCreateSheet === null || onCreateSheet === void 0 ? void 0 : onCreateSheet();
        }, 50);
    }, [onCreateSheet]);
    // Don't render if only default sheet exists and no create option
    if (sheets.length <= 1 && !onCreateSheet) {
        return null;
    }
    const displayName = currentSheet ? currentSheet.name : 'All';
    return (external_react_default().createElement("div", { className: components_SheetSelector_module['SheetSelector'], ref: dropdownRef },
        external_react_default().createElement("button", { className: external_classnames_default()(components_SheetSelector_module['TriggerButton'], { [components_SheetSelector_module['Open']]: isOpen }), onClick: handleToggle, disabled: disabled, title: disabled ? 'Sheet selection is locked' : 'Select sheet' },
            external_react_default().createElement("span", { className: components_SheetSelector_module['SheetName'] }, displayName),
            external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CaretDown, size: common_Icon/* IconSize */.lK.Tiny, UNSAFE_className: external_classnames_default()(components_SheetSelector_module['ChevronIcon'], { [components_SheetSelector_module['Open']]: isOpen }) })),
        isOpen && (external_react_default().createElement("div", { className: components_SheetSelector_module['Dropdown'] },
            external_react_default().createElement("div", { className: components_SheetSelector_module['SheetList'] },
                external_react_default().createElement("div", { className: external_classnames_default()(components_SheetSelector_module['SheetItem'], components_SheetSelector_module['AllSheets'], {
                        [components_SheetSelector_module['Selected']]: currentSheet === null
                    }), onClick: () => handleSelectSheet(null) },
                    external_react_default().createElement("div", { className: external_classnames_default()(components_SheetSelector_module['RadioIndicator'], {
                            [components_SheetSelector_module['Selected']]: currentSheet === null
                        }) }),
                    external_react_default().createElement("span", { className: components_SheetSelector_module['SheetLabel'] }, "All")),
                sheets.map((sheet) => (external_react_default().createElement("div", { key: sheet.folderName || 'default', className: external_classnames_default()(components_SheetSelector_module['SheetItem'], {
                        [components_SheetSelector_module['Selected']]: (currentSheet === null || currentSheet === void 0 ? void 0 : currentSheet.folderName) === sheet.folderName,
                        [components_SheetSelector_module['HasActions']]: !sheet.isDefault && (onRenameSheet || onDeleteSheet)
                    }), onClick: () => handleSelectSheet(sheet) },
                    external_react_default().createElement("div", { className: external_classnames_default()(components_SheetSelector_module['RadioIndicator'], {
                            [components_SheetSelector_module['Selected']]: (currentSheet === null || currentSheet === void 0 ? void 0 : currentSheet.folderName) === sheet.folderName
                        }) }),
                    external_react_default().createElement("span", { className: components_SheetSelector_module['SheetLabel'] }, sheet.name),
                    external_react_default().createElement("span", { className: components_SheetSelector_module['SheetCount'] },
                        "(",
                        sheet.componentCount,
                        ")"),
                    !sheet.isDefault && (onRenameSheet || onDeleteSheet) && (external_react_default().createElement("div", { className: external_classnames_default()(components_SheetSelector_module['SheetActions'], {
                            [components_SheetSelector_module['Visible']]: activeSheetMenu === sheet.folderName
                        }), onClick: (e) => e.stopPropagation() },
                        external_react_default().createElement("button", { className: components_SheetSelector_module['ActionButton'], onClick: (e) => {
                                e.stopPropagation();
                                setActiveSheetMenu(activeSheetMenu === sheet.folderName ? null : sheet.folderName);
                            }, title: "Sheet actions" },
                            external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.DotsThree, size: common_Icon/* IconSize */.lK.Tiny })),
                        activeSheetMenu === sheet.folderName && (external_react_default().createElement("div", { className: components_SheetSelector_module['ActionMenu'] },
                            onRenameSheet && (external_react_default().createElement("button", { className: components_SheetSelector_module['ActionMenuItem'], onClick: (e) => {
                                    e.stopPropagation();
                                    setIsOpen(false);
                                    setActiveSheetMenu(null);
                                    setTimeout(() => onRenameSheet(sheet), 50);
                                } }, "Rename")),
                            onDeleteSheet && (external_react_default().createElement("button", { className: external_classnames_default()(components_SheetSelector_module['ActionMenuItem'], components_SheetSelector_module['Danger']), onClick: (e) => {
                                    e.stopPropagation();
                                    setIsOpen(false);
                                    setActiveSheetMenu(null);
                                    setTimeout(() => onDeleteSheet(sheet), 50);
                                } }, "Delete")))))))))),
            onCreateSheet && (external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement("div", { className: components_SheetSelector_module['Divider'] }),
                external_react_default().createElement("button", { className: components_SheetSelector_module['AddSheetButton'], onClick: handleCreateSheet },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Plus, size: common_Icon/* IconSize */.lK.Tiny, UNSAFE_className: components_SheetSelector_module['AddIcon'] }),
                    external_react_default().createElement("span", null, "Add Sheet"))))))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/ComponentsPanelNew/components/StringInputDialog.module.scss
var StringInputDialog_module = __webpack_require__(8593);
;// ./src/editor/src/views/panels/ComponentsPanelNew/components/StringInputDialog.module.scss

      
      
      
      
      
      
      
      
      

var StringInputDialog_module_options = {};

StringInputDialog_module_options.styleTagTransform = (styleTagTransform_default());
StringInputDialog_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      StringInputDialog_module_options.insert = insertBySelector_default().bind(null, "head");
    
StringInputDialog_module_options.domAPI = (styleDomAPI_default());
StringInputDialog_module_options.insertStyleElement = (insertStyleElement_default());

var StringInputDialog_module_update = injectStylesIntoStyleTag_default()(StringInputDialog_module/* default */.A, StringInputDialog_module_options);




       /* harmony default export */ const components_StringInputDialog_module = (StringInputDialog_module/* default */.A && StringInputDialog_module/* default */.A.locals ? StringInputDialog_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/ComponentsPanelNew/components/StringInputDialog.tsx
/**
 * StringInputDialog
 *
 * Simple centered dialog for string input (sheet creation/renaming).
 * Uses CSS classes for proper Electron compatibility (inline styles don't work).
 */


function StringInputDialog({ title, defaultValue = '', placeholder, confirmLabel = 'Confirm', onConfirm, onCancel }) {
    const [value, setValue] = (0,external_react_.useState)(defaultValue);
    const inputRef = (0,external_react_.useRef)(null);
    // Auto-focus the input
    (0,external_react_.useEffect)(() => {
        setTimeout(() => {
            var _a, _b;
            (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
            (_b = inputRef.current) === null || _b === void 0 ? void 0 : _b.select();
        }, 50);
    }, []);
    const handleConfirm = (0,external_react_.useCallback)(() => {
        if (value.trim()) {
            onConfirm(value.trim());
        }
    }, [value, onConfirm]);
    const handleKeyDown = (0,external_react_.useCallback)((e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            handleConfirm();
        }
        else if (e.key === 'Escape') {
            e.preventDefault();
            onCancel();
        }
    }, [handleConfirm, onCancel]);
    return (external_react_default().createElement("div", { className: components_StringInputDialog_module['Root'], onClick: onCancel },
        external_react_default().createElement("div", { className: components_StringInputDialog_module['Dialog'], onClick: (e) => e.stopPropagation() },
            external_react_default().createElement("h2", { className: components_StringInputDialog_module['Title'] }, title),
            external_react_default().createElement("input", { ref: inputRef, type: "text", className: components_StringInputDialog_module['Input'], value: value, placeholder: placeholder, onChange: (e) => setValue(e.target.value), onKeyDown: handleKeyDown }),
            external_react_default().createElement("div", { className: components_StringInputDialog_module['Actions'] },
                external_react_default().createElement("button", { className: components_StringInputDialog_module['ButtonCancel'], onClick: onCancel }, "Cancel"),
                external_react_default().createElement("button", { className: components_StringInputDialog_module['ButtonConfirm'], onClick: handleConfirm, disabled: !value.trim() }, confirmLabel)))));
}

;// ./src/editor/src/views/panels/ComponentsPanelNew/hooks/useComponentActions.ts
/**
 * useComponentActions
 *
 * Provides handlers for component/folder actions.
 * Integrates with UndoQueue for all operations.
 */









// eslint-disable-next-line @typescript-eslint/no-var-requires
const useComponentActions_PopupLayer = __webpack_require__(45653);
function useComponentActions() {
    const handleMakeHome = (0,external_react_.useCallback)((node) => {
        var _a, _b;
        // Support both component nodes and folder nodes (for component-folders)
        let component;
        if (node.type === 'component') {
            component = node.data.component;
        }
        else if (node.type === 'folder' && node.data.isComponentFolder && node.data.component) {
            component = node.data.component;
        }
        else {
            return;
        }
        if (!component)
            return;
        const canDelete = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.deleteComponentAllowed(component);
        if (!(canDelete === null || canDelete === void 0 ? void 0 : canDelete.canBeDelete)) {
            console.warn('Cannot set component as home:', canDelete === null || canDelete === void 0 ? void 0 : canDelete.reason);
            return;
        }
        const previousRoot = (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.getRootComponent();
        const undoGroup = new undo_queue_model/* UndoActionGroup */.C({
            label: `Make ${component.name} home`
        });
        undo_queue_model/* UndoQueue */.g.instance.push(undoGroup);
        undoGroup.push({
            do: () => {
                var _a;
                (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.setRootComponent(component);
            },
            undo: () => {
                var _a, _b;
                if (previousRoot) {
                    (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.setRootComponent(previousRoot);
                }
                else {
                    (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.setRootNode(undefined);
                }
            }
        });
        undoGroup.do();
    }, []);
    const handleDelete = (0,external_react_.useCallback)((node) => {
        var _a;
        if (node.type !== 'component') {
            // TODO: Implement folder deletion
            console.log('Folder deletion not yet implemented');
            return;
        }
        const component = node.data.component;
        const canDelete = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.deleteComponentAllowed(component);
        if (!(canDelete === null || canDelete === void 0 ? void 0 : canDelete.canBeDelete)) {
            alert((canDelete === null || canDelete === void 0 ? void 0 : canDelete.reason) || "This component can't be deleted");
            return;
        }
        // Confirm deletion
        const confirmed = confirm(`Are you sure you want to delete "${component.localName}"?`);
        if (!confirmed)
            return;
        // Use pushAndDo pattern - removeComponent handles its own undo internally
        undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
            label: `Delete ${component.name}`,
            do: () => {
                var _a;
                const undoGroup = new undo_queue_model/* UndoActionGroup */.C({ label: `Delete ${component.name}` });
                undo_queue_model/* UndoQueue */.g.instance.push(undoGroup);
                (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.removeComponent(component, { undo: undoGroup });
            },
            undo: () => {
                // Undo is handled internally by removeComponent
            }
        }));
    }, []);
    const handleDuplicate = (0,external_react_.useCallback)((node) => {
        var _a, _b, _c;
        // Support both component nodes and folder nodes (for component-folders)
        let component;
        if (node.type === 'component') {
            component = node.data.component;
        }
        else if (node.type === 'folder' && node.data.isComponentFolder && node.data.component) {
            component = node.data.component;
        }
        else {
            // TODO: Implement pure folder duplication
            console.log('Folder duplication not yet implemented');
            return;
        }
        let newName = component.name + ' Copy';
        // Find unique name
        let counter = 1;
        while ((_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(newName)) {
            newName = `${component.name} Copy ${counter}`;
            counter++;
        }
        // Create undo group - duplicateComponent handles its own undo registration
        const undoGroup = new undo_queue_model/* UndoActionGroup */.C({
            label: `Duplicate ${component.localName}`
        });
        // Call duplicateComponent which internally registers undo actions
        (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.duplicateComponent(component, newName, {
            undo: undoGroup,
            rerouteComponentRefs: null
        });
        // Push the undo group after duplicate is done
        undo_queue_model/* UndoQueue */.g.instance.push(undoGroup);
        // Switch to the new component
        const duplicatedComponent = (_c = projectmodel.ProjectModel.instance) === null || _c === void 0 ? void 0 : _c.getComponentWithName(newName);
        if (duplicatedComponent) {
            EventDispatcher.EventDispatcher.instance.notifyListeners('ComponentPanel.SwitchToComponent', {
                component: duplicatedComponent,
                pushHistory: true
            });
        }
        tracker.tracker.track('Component Duplicated');
    }, []);
    const handleRename = (0,external_react_.useCallback)((node) => {
        // This triggers the rename UI - the actual implementation
        // will be wired up in ComponentsPanelReact
        console.log('Rename initiated for:', node);
    }, []);
    /**
     * Perform the actual rename operation with undo support
     */
    const performRename = (0,external_react_.useCallback)((node, newName) => {
        var _a, _b;
        if (node.type === 'component') {
            const component = node.data.component;
            const oldName = component.name;
            const parentPath = oldName.includes('/') ? oldName.substring(0, oldName.lastIndexOf('/')) : '';
            const fullNewName = parentPath ? `${parentPath}/${newName}` : newName;
            // Check for naming conflicts
            if ((_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(fullNewName)) {
                ToastLayer.ToastLayer.showError('Component name already exists. Name must be unique.');
                return false;
            }
            undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
                label: `Rename ${component.localName} to ${newName}`,
                do: () => {
                    var _a;
                    (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, fullNewName);
                },
                undo: () => {
                    var _a;
                    (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, oldName);
                }
            }));
            return true;
        }
        else if (node.type === 'folder') {
            const oldPath = node.data.path;
            const parentPath = oldPath.includes('/') ? oldPath.substring(0, oldPath.lastIndexOf('/')) : '';
            const newPath = parentPath ? `${parentPath}/${newName}` : newName;
            // Get all components in this folder
            const componentsToRename = (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.getComponents().filter((comp) => comp.name.startsWith(oldPath + '/'));
            if (!componentsToRename || componentsToRename.length === 0) {
                // Empty folder - just update the path (no actual operation needed)
                // Folders are virtual, so we don't need to do anything
                return true;
            }
            // Check for naming conflicts
            const wouldConflict = componentsToRename.some((comp) => {
                var _a, _b;
                const relativePath = comp.name.substring(oldPath.length);
                const newFullName = newPath + relativePath;
                return (((_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(newFullName)) &&
                    ((_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.getComponentWithName(newFullName)) !== comp);
            });
            if (wouldConflict) {
                ToastLayer.ToastLayer.showError('Folder rename would create naming conflicts');
                return false;
            }
            const renames = [];
            componentsToRename.forEach((comp) => {
                const relativePath = comp.name.substring(oldPath.length);
                const newFullName = newPath + relativePath;
                renames.push({ component: comp, oldName: comp.name, newName: newFullName });
            });
            const undoGroup = new undo_queue_model/* UndoActionGroup */.C({
                label: `Rename folder ${node.data.name} to ${newName}`
            });
            undo_queue_model/* UndoQueue */.g.instance.push(undoGroup);
            undoGroup.push({
                do: () => {
                    renames.forEach(({ component, newName }) => {
                        var _a;
                        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, newName);
                    });
                },
                undo: () => {
                    renames.forEach(({ component, oldName }) => {
                        var _a;
                        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, oldName);
                    });
                }
            });
            undoGroup.do();
            return true;
        }
        return false;
    }, []);
    const handleOpen = (0,external_react_.useCallback)((node) => {
        // Support both component nodes and folder nodes (for component-folders)
        let component;
        if (node.type === 'component') {
            component = node.data.component;
        }
        else if (node.type === 'folder' && node.data.isComponentFolder && node.data.component) {
            component = node.data.component;
        }
        else {
            return;
        }
        // Open component in NodeGraphEditor by dispatching event
        if (component) {
            EventDispatcher.EventDispatcher.instance.notifyListeners('ComponentPanel.SwitchToComponent', {
                component,
                pushHistory: true
            });
        }
    }, []);
    /**
     * Handle dropping an item onto a target
     */
    /**
     * Handle adding a new component using a template
     */
    const handleAddComponent = (0,external_react_.useCallback)((template, parentPath) => {
        // Normalize parent path: '/' means root (empty string), otherwise use as-is
        const finalParentPath = !parentPath || parentPath === '/' ? '' : parentPath;
        const popup = template.createPopup({
            onCreate: (localName, options) => {
                var _a, _b;
                const componentName = finalParentPath + localName;
                // Validate name
                if (!localName || localName.trim() === '') {
                    ToastLayer.ToastLayer.showError('Component name cannot be empty');
                    return;
                }
                if ((_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(componentName)) {
                    ToastLayer.ToastLayer.showError('Component name already exists. Name must be unique.');
                    return;
                }
                // Create component with undo support
                const undoGroup = new undo_queue_model/* UndoActionGroup */.C({ label: 'add component' });
                let component;
                if (template) {
                    component = template.createComponent(componentName, options, undoGroup);
                }
                else {
                    component = new componentmodel/* ComponentModel */.j({
                        name: componentName,
                        graph: new nodegraphmodel/* NodeGraphModel */.W2(),
                        id: (0,utils.guid)()
                    });
                }
                tracker.tracker.track('Component Created', {
                    template: template ? template.label : undefined
                });
                (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.addComponent(component, { undo: undoGroup });
                undo_queue_model/* UndoQueue */.g.instance.push(undoGroup);
                // Switch to the new component
                EventDispatcher.EventDispatcher.instance.notifyListeners('ComponentPanel.SwitchToComponent', {
                    component,
                    pushHistory: true
                });
                useComponentActions_PopupLayer.instance.hidePopup();
            },
            onCancel: () => {
                useComponentActions_PopupLayer.instance.hidePopup();
            }
        });
        useComponentActions_PopupLayer.instance.showPopup({
            content: popup,
            position: 'screen-center',
            isBackgroundDimmed: true
        });
    }, []);
    /**
     * Handle adding a new folder
     */
    const handleAddFolder = (0,external_react_.useCallback)((parentPath) => {
        const popup = new useComponentActions_PopupLayer.StringInputPopup({
            label: 'New folder name',
            okLabel: 'Add',
            cancelLabel: 'Cancel',
            onOk: (folderName) => {
                var _a;
                // Validate name
                if (!folderName || folderName.trim() === '') {
                    ToastLayer.ToastLayer.showError('Folder name cannot be empty');
                    return;
                }
                // Normalize parent path: ensure it starts with /
                // If parentPath is undefined, empty, or '/', treat as root '/'
                let normalizedPath = parentPath || '/';
                if (normalizedPath === '/') {
                    normalizedPath = '/';
                }
                else if (!normalizedPath.startsWith('/')) {
                    normalizedPath = '/' + normalizedPath;
                }
                // Ensure it ends with / for concatenation (unless it's just '/')
                if (normalizedPath !== '/' && !normalizedPath.endsWith('/')) {
                    normalizedPath = normalizedPath + '/';
                }
                // Create folder path - component names MUST start with /
                const folderPath = normalizedPath === '/' ? `/${folderName}` : `${normalizedPath}${folderName}`;
                // Check if folder already exists (any component starts with this path)
                const folderExists = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponents().some((comp) => comp.name.startsWith(folderPath + '/'));
                if (folderExists) {
                    ToastLayer.ToastLayer.showError('A folder with this name already exists');
                    return;
                }
                // Create a placeholder component to make the folder visible
                // The placeholder will be at {folderPath}/.placeholder
                const placeholderName = `${folderPath}/.placeholder`;
                undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
                    label: `Create folder ${folderName}`,
                    do: () => {
                        var _a;
                        const placeholder = new componentmodel/* ComponentModel */.j({
                            name: placeholderName,
                            graph: new nodegraphmodel/* NodeGraphModel */.W2(),
                            id: (0,utils.guid)()
                        });
                        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.addComponent(placeholder);
                    },
                    undo: () => {
                        var _a, _b;
                        const placeholder = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(placeholderName);
                        if (placeholder) {
                            (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.removeComponent(placeholder);
                        }
                    }
                }));
                useComponentActions_PopupLayer.instance.hidePopup();
            }
        });
        popup.render();
        useComponentActions_PopupLayer.instance.showPopup({
            content: popup,
            position: 'screen-center',
            isBackgroundDimmed: true
        });
    }, []);
    /**
     * Handle dropping an item onto the root level (empty space)
     */
    const handleDropOnRoot = (0,external_react_.useCallback)((draggedItem) => {
        var _a, _b;
        // Component → Root
        if (draggedItem.type === 'component') {
            const component = draggedItem.data.component;
            const newName = component.localName;
            // Check if already at root
            if (!component.name.includes('/')) {
                console.log('Component already at root level');
                useComponentActions_PopupLayer.instance.dragCompleted();
                return;
            }
            // Check for naming conflicts
            if ((_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(newName)) {
                alert(`Component "${newName}" already exists at root level`);
                useComponentActions_PopupLayer.instance.dragCompleted();
                return;
            }
            const oldName = component.name;
            // End drag operation FIRST - before the rename triggers a re-render
            useComponentActions_PopupLayer.instance.dragCompleted();
            undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
                label: `Move ${component.localName} to root`,
                do: () => {
                    var _a;
                    (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, newName);
                },
                undo: () => {
                    var _a;
                    (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, oldName);
                }
            }));
        }
        // Folder → Root (including component-folders)
        else if (draggedItem.type === 'folder') {
            const sourcePath = draggedItem.data.path;
            const newPath = draggedItem.data.name;
            // Check if already at root
            if (!sourcePath.includes('/')) {
                console.log('Folder already at root level');
                useComponentActions_PopupLayer.instance.dragCompleted();
                return;
            }
            // Get all components in source folder (including the folder's component if it exists)
            const componentsToMove = (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.getComponents().filter((comp) => comp.name === sourcePath || comp.name.startsWith(sourcePath + '/'));
            if (!componentsToMove || componentsToMove.length === 0) {
                console.log('Folder is empty, nothing to move');
                useComponentActions_PopupLayer.instance.dragCompleted();
                return;
            }
            const renames = [];
            componentsToMove.forEach((comp) => {
                let newName;
                if (comp.name === sourcePath) {
                    // This is the component-folder itself
                    newName = newPath;
                }
                else {
                    // This is a nested component
                    const relativePath = comp.name.substring(sourcePath.length);
                    newName = newPath + relativePath;
                }
                renames.push({ component: comp, oldName: comp.name, newName });
            });
            // End drag operation FIRST - before the rename triggers a re-render
            useComponentActions_PopupLayer.instance.dragCompleted();
            undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
                label: `Move ${draggedItem.data.name} to root`,
                do: () => {
                    renames.forEach(({ component, newName }) => {
                        var _a;
                        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, newName);
                    });
                },
                undo: () => {
                    renames.forEach(({ component, oldName }) => {
                        var _a;
                        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, oldName);
                    });
                }
            }));
        }
    }, []);
    /**
     * Handle dropping an item onto a target
     */
    const handleDropOn = (0,external_react_.useCallback)((draggedItem, targetItem) => {
        var _a, _b, _c, _d;
        // Component → Folder
        if (draggedItem.type === 'component' && targetItem.type === 'folder') {
            const component = draggedItem.data.component;
            const targetPath = targetItem.data.path === '/' ? '' : targetItem.data.path;
            const newName = targetPath ? `${targetPath}/${component.localName}` : component.localName;
            // Check for naming conflicts
            if ((_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(newName)) {
                alert(`Component "${newName}" already exists in that folder`);
                return;
            }
            const oldName = component.name;
            // Note: dragCompleted() now called by ComponentItem.handleMouseUp before this action
            undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
                label: `Move ${component.localName} to folder`,
                do: () => {
                    var _a;
                    (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, newName);
                },
                undo: () => {
                    var _a;
                    (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, oldName);
                }
            }));
        }
        // Folder → Folder
        else if (draggedItem.type === 'folder' && targetItem.type === 'folder') {
            const sourcePath = draggedItem.data.path;
            const targetPath = targetItem.data.path === '/' ? '' : targetItem.data.path;
            const newPath = targetPath ? `${targetPath}/${draggedItem.data.name}` : draggedItem.data.name;
            // Prevent moving folder into itself
            if (targetPath.startsWith(sourcePath + '/') || targetPath === sourcePath) {
                alert('Cannot move folder into itself');
                return;
            }
            // Get all components in source folder (including the folder's component if it exists)
            const componentsToMove = (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.getComponents().filter((comp) => comp.name === sourcePath || comp.name.startsWith(sourcePath + '/'));
            if (!componentsToMove || componentsToMove.length === 0) {
                console.log('Folder is empty, nothing to move');
                return;
            }
            const renames = [];
            componentsToMove.forEach((comp) => {
                let newName;
                if (comp.name === sourcePath) {
                    // This is the component-folder itself
                    newName = newPath;
                }
                else {
                    // This is a nested component
                    const relativePath = comp.name.substring(sourcePath.length);
                    newName = newPath + relativePath;
                }
                renames.push({ component: comp, oldName: comp.name, newName });
            });
            // Note: dragCompleted() now called by FolderItem.handleMouseUp before this action
            undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
                label: `Move ${draggedItem.data.name} folder`,
                do: () => {
                    renames.forEach(({ component, newName }) => {
                        var _a;
                        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, newName);
                    });
                },
                undo: () => {
                    renames.forEach(({ component, oldName }) => {
                        var _a;
                        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, oldName);
                    });
                }
            }));
        }
        // Component → Component (make subcomponent)
        else if (draggedItem.type === 'component' && targetItem.type === 'component') {
            const component = draggedItem.data.component;
            const targetComponent = targetItem.data.component;
            const newName = `${targetComponent.name}/${component.localName}`;
            // Check for naming conflicts
            if ((_c = projectmodel.ProjectModel.instance) === null || _c === void 0 ? void 0 : _c.getComponentWithName(newName)) {
                alert(`Component "${newName}" already exists`);
                return;
            }
            const oldName = component.name;
            // Note: dragCompleted() now called by ComponentItem.handleMouseUp before this action
            undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
                label: `Move ${component.localName} into ${targetComponent.localName}`,
                do: () => {
                    var _a;
                    (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, newName);
                },
                undo: () => {
                    var _a;
                    (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, oldName);
                }
            }));
        }
        // Folder → Component (treat component-folder AS a component, nest inside target)
        else if (draggedItem.type === 'folder' && targetItem.type === 'component') {
            const sourcePath = draggedItem.data.path;
            const targetComponent = targetItem.data.component;
            const newPath = `${targetComponent.name}/${draggedItem.data.name}`;
            // Get all components in source folder (including the folder's component if it exists)
            const componentsToMove = (_d = projectmodel.ProjectModel.instance) === null || _d === void 0 ? void 0 : _d.getComponents().filter((comp) => comp.name === sourcePath || comp.name.startsWith(sourcePath + '/'));
            if (!componentsToMove || componentsToMove.length === 0) {
                console.log('Folder is empty, nothing to move');
                return;
            }
            const renames = [];
            componentsToMove.forEach((comp) => {
                let newName;
                if (comp.name === sourcePath) {
                    // This is the component-folder itself
                    newName = newPath;
                }
                else {
                    // This is a nested component
                    const relativePath = comp.name.substring(sourcePath.length);
                    newName = newPath + relativePath;
                }
                renames.push({ component: comp, oldName: comp.name, newName });
            });
            // Check for conflicts
            const hasConflict = renames.some(({ newName }) => { var _a; return (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(newName); });
            if (hasConflict) {
                alert(`Some components would conflict with existing names`);
                return;
            }
            // Note: dragCompleted() now called by ComponentItem.handleMouseUp before this action
            undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
                label: `Move ${draggedItem.data.name} into ${targetComponent.localName}`,
                do: () => {
                    renames.forEach(({ component, newName }) => {
                        var _a;
                        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, newName);
                    });
                },
                undo: () => {
                    renames.forEach(({ component, oldName }) => {
                        var _a;
                        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.renameComponent(component, oldName);
                    });
                }
            }));
        }
    }, []);
    return {
        handleMakeHome,
        handleDelete,
        handleDuplicate,
        handleRename,
        performRename,
        handleOpen,
        handleDropOn,
        handleDropOnRoot,
        handleAddComponent,
        handleAddFolder
    };
}

;// ./src/editor/src/views/panels/ComponentsPanelNew/hooks/useComponentsPanel.ts



/**
 * useComponentsPanel
 *
 * Main state management hook for ComponentsPanel.
 * Subscribes to ProjectModel and builds tree structure.
 *
 * Uses the PROVEN direct subscription pattern from UseRoutes.ts
 * instead of the abstracted useEventListener hook.
 */
// Events to subscribe to on ProjectModel.instance
const PROJECT_EVENTS = ['componentAdded', 'componentRemoved', 'componentRenamed', 'rootNodeChanged'];
function useComponentsPanel(options = {}) {
    const { hideSheets = [], lockToSheet } = options;
    // Local state
    const [expandedFolders, setExpandedFolders] = (0,external_react_.useState)(new Set(['/']));
    const [selectedId, setSelectedId] = (0,external_react_.useState)();
    const [updateCounter, setUpdateCounter] = (0,external_react_.useState)(0);
    const [currentSheetName, setCurrentSheetName] = (0,external_react_.useState)(lockToSheet || null);
    // Subscribe to ProjectModel events using DIRECT pattern (proven in UseRoutes.ts)
    // This bypasses the problematic useEventListener abstraction
    (0,external_react_.useEffect)(() => {
        if (!projectmodel.ProjectModel.instance) {
            return;
        }
        // Create a group object for cleanup (same pattern as UseRoutes.ts)
        const group = { id: 'useComponentsPanel' };
        // Handler that triggers re-render
        const handleUpdate = () => {
            setUpdateCounter((c) => c + 1);
        };
        // Subscribe to all events (Model.on supports arrays)
        projectmodel.ProjectModel.instance.on(PROJECT_EVENTS, handleUpdate, group);
        // Cleanup: unsubscribe when unmounting
        return () => {
            if (projectmodel.ProjectModel.instance) {
                projectmodel.ProjectModel.instance.off(group);
            }
        };
    }, []); // Empty deps: ProjectModel.instance is a singleton that never changes, so subscribe once and cleanup on unmount
    // Get all components (including placeholders) for sheet detection
    // IMPORTANT: Spread to create new array reference - getComponents() may return
    // the same mutated array, which would cause useMemo to skip recalculation
    const rawComponents = (0,external_react_.useMemo)(() => {
        if (!projectmodel.ProjectModel.instance)
            return [];
        return [...projectmodel.ProjectModel.instance.getComponents()];
    }, [updateCounter]);
    // Get non-placeholder components for counting and tree display
    const allComponents = (0,external_react_.useMemo)(() => {
        return rawComponents.filter((comp) => !comp.name.endsWith('/.placeholder'));
    }, [rawComponents]);
    // Detect all sheets from component paths (including placeholders for empty sheet detection)
    // Sheets are top-level folders starting with # (e.g., #Pages, #Components)
    // Note: Component names start with leading "/" (e.g., "/#Pages/Home")
    const sheets = (0,external_react_.useMemo)(() => {
        const sheetSet = new Set(); // All detected sheet folder names
        const sheetCounts = new Map(); // folderName -> non-placeholder component count
        // First pass: detect all sheets (including from placeholders)
        rawComponents.forEach((comp) => {
            const parts = comp.name.split('/').filter((p) => p !== ''); // Remove empty strings from leading /
            if (parts.length > 0 && parts[0].startsWith('#')) {
                const sheetFolder = parts[0];
                sheetSet.add(sheetFolder);
            }
        });
        // Second pass: count non-placeholder components per sheet
        allComponents.forEach((comp) => {
            const parts = comp.name.split('/').filter((p) => p !== '');
            if (parts.length > 0 && parts[0].startsWith('#')) {
                const sheetFolder = parts[0];
                sheetCounts.set(sheetFolder, (sheetCounts.get(sheetFolder) || 0) + 1);
            }
        });
        // Count default sheet components (not in any # folder)
        const defaultCount = allComponents.filter((comp) => {
            const parts = comp.name.split('/').filter((p) => p !== '');
            return parts.length === 0 || !parts[0].startsWith('#');
        }).length;
        // Build sheet list with Default first
        const result = [
            {
                name: 'Default',
                folderName: '',
                isDefault: true,
                componentCount: defaultCount
            }
        ];
        // Add detected sheets, filtering out hidden ones
        sheetSet.forEach((folderName) => {
            const displayName = folderName.substring(1); // Remove # prefix
            if (!hideSheets.includes(displayName) && !hideSheets.includes(folderName)) {
                result.push({
                    name: displayName,
                    folderName,
                    isDefault: false,
                    componentCount: sheetCounts.get(folderName) || 0
                });
            }
        });
        // Sort non-default sheets alphabetically
        result.sort((a, b) => {
            if (a.isDefault)
                return -1;
            if (b.isDefault)
                return 1;
            return a.name.localeCompare(b.name);
        });
        return result;
    }, [rawComponents, allComponents, hideSheets, updateCounter]);
    // Get current sheet object
    const currentSheet = (0,external_react_.useMemo)(() => {
        if (currentSheetName === null) {
            // No sheet selected = show all (no filtering)
            return null;
        }
        return sheets.find((s) => s.folderName === currentSheetName || (s.isDefault && currentSheetName === '')) || null;
    }, [currentSheetName, sheets]);
    // Select a sheet
    const selectSheet = (0,external_react_.useCallback)((sheet) => {
        // Don't allow switching if locked
        if (lockToSheet !== undefined)
            return;
        setCurrentSheetName(sheet ? sheet.folderName : null);
    }, [lockToSheet]);
    // Build tree structure with optional sheet filtering
    const treeData = (0,external_react_.useMemo)(() => {
        if (!projectmodel.ProjectModel.instance)
            return [];
        return buildTreeFromProject(projectmodel.ProjectModel.instance, hideSheets, currentSheet);
    }, [updateCounter, hideSheets, currentSheet]);
    // Toggle folder expand/collapse
    const toggleFolder = (0,external_react_.useCallback)((folderId) => {
        setExpandedFolders((prev) => {
            const next = new Set(prev);
            if (next.has(folderId)) {
                next.delete(folderId);
            }
            else {
                next.add(folderId);
            }
            return next;
        });
    }, []);
    // Handle item click
    const handleItemClick = (0,external_react_.useCallback)((node) => {
        if (node.type === 'component') {
            setSelectedId(node.data.name);
            // Open component - trigger the NodeGraphEditor to switch to this component
            const component = node.data.component;
            if (component) {
                EventDispatcher.EventDispatcher.instance.notifyListeners('ComponentPanel.SwitchToComponent', {
                    component,
                    pushHistory: true
                });
            }
        }
        else {
            // It's a folder
            setSelectedId(node.data.path);
            // BUG-6 FIX: If it's a component-folder, open the component too
            // Component-folders are folders that also have an associated component
            // (e.g., App with App/Header as a child)
            if (node.data.isComponentFolder && node.data.component) {
                EventDispatcher.EventDispatcher.instance.notifyListeners('ComponentPanel.SwitchToComponent', {
                    component: node.data.component,
                    pushHistory: true
                });
            }
            // Toggle folder expand/collapse
            toggleFolder(node.data.path);
        }
    }, [toggleFolder]);
    return {
        treeData,
        expandedFolders,
        selectedId,
        toggleFolder,
        handleItemClick,
        // Sheet system
        sheets,
        currentSheet,
        selectSheet
    };
}
/**
 * Build tree structure from ProjectModel
 *
 * @param project - The project model
 * @param hideSheets - Sheet names to hide (filter out)
 * @param currentSheet - If provided, filter to only show components in this sheet
 */
function buildTreeFromProject(project, hideSheets, currentSheet) {
    const rootFolder = {
        name: '',
        path: '/',
        components: [],
        children: []
    };
    // Get all components
    const components = project.getComponents();
    // First pass: Build folder structure from ALL components (including placeholders)
    // This ensures empty folders created via placeholders are visible
    components.forEach((comp) => {
        // Filter by hideSheets
        const sheet = getSheetForComponent(comp.name);
        if (hideSheets.includes(sheet)) {
            return;
        }
        // Apply current sheet filtering
        if (currentSheet !== null) {
            const parts = comp.name.split('/').filter((p) => p !== '');
            const firstPart = parts.length > 0 ? parts[0] : '';
            const isInSheetFolder = firstPart.startsWith('#');
            if (currentSheet.isDefault) {
                if (isInSheetFolder)
                    return;
            }
            else {
                if (firstPart !== currentSheet.folderName)
                    return;
            }
        }
        // Determine display path (strip sheet prefix if needed)
        let displayPath = comp.name;
        if (currentSheet === null) {
            const parts = comp.name.split('/').filter((p) => p !== '');
            if (parts.length > 0 && parts[0].startsWith('#')) {
                displayPath = '/' + parts.slice(1).join('/');
            }
        }
        else if (!currentSheet.isDefault) {
            const sheetPrefix = '/' + currentSheet.folderName + '/';
            if (comp.name.startsWith(sheetPrefix)) {
                displayPath = '/' + comp.name.substring(sheetPrefix.length);
            }
        }
        if (displayPath && displayPath !== '/') {
            // For placeholders: create folder structure but don't add to components array
            const isPlaceholder = comp.name.endsWith('/.placeholder');
            addComponentToFolderStructure(rootFolder, comp, displayPath, isPlaceholder);
        }
    });
    // Convert folder structure to tree nodes
    return convertFolderToTreeNodes(rootFolder);
}
/**
 * Add a component to the folder structure
 * @param displayPath - Optional override path for tree building (used when stripping sheet prefix)
 * @param skipAddComponent - If true, only create folder structure but don't add component (for placeholders)
 */
function addComponentToFolderStructure(rootFolder, component, displayPath, skipAddComponent) {
    // Use displayPath for tree structure, but keep original component reference
    const pathForTree = displayPath || component.name;
    const parts = pathForTree.split('/');
    let currentFolder = rootFolder;
    // Navigate/create folder structure (all parts except the last one)
    for (let i = 0; i < parts.length - 1; i++) {
        const folderName = parts[i];
        let folder = currentFolder.children.find((c) => c.name === folderName);
        if (!folder) {
            folder = {
                name: folderName,
                path: parts.slice(0, i + 1).join('/'),
                components: [],
                children: []
            };
            currentFolder.children.push(folder);
        }
        currentFolder = folder;
    }
    // Add component to final folder (unless it's a placeholder - we only want the folder structure)
    if (!skipAddComponent) {
        currentFolder.components.push(component);
    }
}
/**
 * Convert folder structure to tree nodes
 */
function convertFolderToTreeNodes(folder) {
    const nodes = [];
    // Build a set of folder paths for quick lookup
    const folderPaths = new Set(folder.children.map((child) => child.path));
    // Sort folder children alphabetically
    const sortedChildren = [...folder.children].sort((a, b) => a.name.localeCompare(b.name));
    // Add folder children first
    sortedChildren.forEach((childFolder) => {
        var _a;
        // Skip root folder (empty name) from rendering as a folder item
        // The root should be transparent - just show its contents directly
        if (childFolder.name === '') {
            nodes.push(...convertFolderToTreeNodes(childFolder));
            return;
        }
        // Check if there's a component with the same path as this folder
        // This happens when a component has nested children (e.g., /test1 with /test1/child)
        const matchingComponent = folder.components.find((comp) => comp.name === childFolder.path);
        // A folder is only a "component-folder" if there's an actual component with the same path.
        // Having children (components inside) does NOT make it a component-folder - that's just a regular folder.
        const isComponentFolder = matchingComponent !== undefined;
        const isRoot = matchingComponent ? ((_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getRootComponent()) === matchingComponent : false;
        const isPage = matchingComponent ? checkIsPage(matchingComponent) : false;
        const isCloudFunction = matchingComponent ? checkIsCloudFunction(matchingComponent) : false;
        const isVisual = matchingComponent ? checkIsVisual(matchingComponent) : false;
        const folderNode = {
            type: 'folder',
            data: {
                name: childFolder.name,
                path: childFolder.path,
                isOpen: false,
                isComponentFolder,
                component: matchingComponent, // Attach the component if it exists
                children: convertFolderToTreeNodes(childFolder),
                // Component type flags (only meaningful when isComponentFolder && matchingComponent exists)
                isRoot,
                isPage,
                isCloudFunction,
                isVisual
            }
        };
        nodes.push(folderNode);
    });
    // Sort components alphabetically
    const sortedComponents = [...folder.components].sort((a, b) => a.localName.localeCompare(b.localName));
    // Add components (but skip any that are also folder paths)
    sortedComponents.forEach((comp) => {
        var _a;
        // Skip components that match folder paths - they're already rendered as folders
        if (folderPaths.has(comp.name)) {
            return;
        }
        const isRoot = ((_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getRootComponent()) === comp;
        const isPage = checkIsPage(comp);
        const isCloudFunction = checkIsCloudFunction(comp);
        const isVisual = checkIsVisual(comp);
        const componentNode = {
            type: 'component',
            data: {
                id: comp.id,
                name: comp.name,
                localName: comp.localName,
                component: comp,
                isRoot,
                isPage,
                isCloudFunction,
                isVisual,
                hasWarnings: false, // TODO: Implement warning detection
                path: comp.name
            }
        };
        nodes.push(componentNode);
    });
    return nodes;
}
/**
 * Extract sheet name from component name
 * Note: Component names start with leading "/" (e.g., "/#Pages/Home")
 */
function getSheetForComponent(componentName) {
    const parts = componentName.split('/').filter((p) => p !== '');
    if (parts.length > 0 && parts[0].startsWith('#')) {
        return parts[0].substring(1); // Return sheet name without # prefix
    }
    return 'default';
}
/**
 * Check if component is a page
 */
function checkIsPage(component) {
    // A component is a page if it has nodes of type 'Page' or 'PageRouter'
    let isPage = false;
    component.forEachNode((node) => {
        if (node.type.name === 'Page' || node.typename === 'Page') {
            isPage = true;
            return true; // Stop iteration
        }
    });
    return isPage;
}
/**
 * Check if component is a cloud function
 */
function checkIsCloudFunction(component) {
    // A component is a cloud function if it has nodes of type 'Cloud Function'
    let isCloudFunction = false;
    component.forEachNode((node) => {
        if (node.type.name === 'Cloud Function' || node.typename === 'Cloud Function') {
            isCloudFunction = true;
            return true; // Stop iteration
        }
    });
    return isCloudFunction;
}
/**
 * Check if component is visual (has UI elements)
 */
function checkIsVisual(component) {
    // A component is visual if it's not a cloud function and has visual nodes
    // For now, we'll consider all non-cloud-function components as visual
    return !checkIsCloudFunction(component);
}

;// ./src/editor/src/views/panels/ComponentsPanelNew/hooks/useDragDrop.ts
/**
 * useDragDrop
 *
 * Manages drag-drop state and operations for components/folders.
 * Integrates with PopupLayer.startDragging system.
 */

// eslint-disable-next-line @typescript-eslint/no-var-requires
const useDragDrop_PopupLayer = __webpack_require__(45653);
function useDragDrop() {
    const [draggedItem, setDraggedItem] = (0,external_react_.useState)(null);
    const [dropTarget, setDropTarget] = (0,external_react_.useState)(null);
    /**
     * Start dragging an item
     */
    const startDrag = (0,external_react_.useCallback)((item, sourceElement) => {
        setDraggedItem(item);
        const label = item.type === 'component' ? item.data.localName : `📁 ${item.data.name}`;
        useDragDrop_PopupLayer.instance.startDragging({
            label,
            type: item.type,
            dragTarget: sourceElement,
            component: item.type === 'component' ? item.data.component : undefined,
            folder: item.type === 'folder' ? item.data : undefined,
            onDragEnd: () => {
                setDraggedItem(null);
                setDropTarget(null);
            }
        });
    }, []);
    /**
     * Check if an item can be dropped on a target
     */
    const canDrop = (0,external_react_.useCallback)((target) => {
        if (!draggedItem)
            return false;
        // Can't drop on self
        if (draggedItem.type === 'component' && target.type === 'component') {
            if (draggedItem.data.id === target.data.id)
                return false;
        }
        if (draggedItem.type === 'folder' && target.type === 'folder') {
            if (draggedItem.data.path === target.data.path)
                return false;
        }
        // Folder-specific rules
        if (draggedItem.type === 'folder' && target.type === 'folder') {
            // Can't drop folder into its own children (descendant check)
            const draggedPath = draggedItem.data.path;
            const targetPath = target.data.path;
            if (targetPath.startsWith(draggedPath + '/')) {
                return false; // Target is a descendant of dragged folder
            }
        }
        return true;
    }, [draggedItem]);
    /**
     * Handle drop on a target
     */
    const handleDrop = (0,external_react_.useCallback)((target) => {
        if (!draggedItem || !canDrop(target))
            return;
        setDropTarget(target);
        // Drop will be executed by parent component
        // which has access to ProjectModel and UndoQueue
    }, [draggedItem, canDrop]);
    /**
     * Clear drop state
     */
    const clearDrop = (0,external_react_.useCallback)(() => {
        setDropTarget(null);
    }, []);
    return {
        draggedItem,
        dropTarget,
        startDrag,
        canDrop,
        handleDrop,
        clearDrop
    };
}

;// ./src/editor/src/views/panels/ComponentsPanelNew/hooks/useRenameMode.ts
/**
 * useRenameMode
 *
 * Manages inline rename state and validation for components and folders.
 */


function useRenameMode() {
    const [renamingItem, setRenamingItem] = (0,external_react_.useState)(null);
    const [renameValue, setRenameValue] = (0,external_react_.useState)('');
    /**
     * Start rename mode for an item
     */
    const startRename = (0,external_react_.useCallback)((item) => {
        setRenamingItem(item);
        // Set initial value based on item type
        if (item.type === 'component') {
            setRenameValue(item.data.localName);
        }
        else {
            setRenameValue(item.data.name);
        }
    }, []);
    /**
     * Cancel rename mode
     */
    const cancelRename = (0,external_react_.useCallback)(() => {
        setRenamingItem(null);
        setRenameValue('');
    }, []);
    /**
     * Validate the new name
     */
    const validateName = (0,external_react_.useCallback)((newName) => {
        var _a, _b;
        if (!renamingItem) {
            return { valid: false, error: 'No item selected for rename' };
        }
        // Check for empty name
        if (!newName || newName.trim() === '') {
            return { valid: false, error: 'Name cannot be empty' };
        }
        // Check for invalid characters
        const invalidChars = /[<>:"|?*\\/]/;
        if (invalidChars.test(newName)) {
            return { valid: false, error: 'Name contains invalid characters (< > : " | ? * \\ /)' };
        }
        // If name hasn't changed, it's valid (no-op)
        if (renamingItem.type === 'component' && newName === renamingItem.data.localName) {
            return { valid: true };
        }
        if (renamingItem.type === 'folder' && newName === renamingItem.data.name) {
            return { valid: true };
        }
        // Check for duplicate names
        if (renamingItem.type === 'component') {
            // Build the full component name with folder path
            const currentPath = renamingItem.data.path;
            const pathParts = currentPath.split('/');
            pathParts.pop(); // Remove current component name
            const folderPath = pathParts.join('/');
            const newFullName = folderPath ? `${folderPath}/${newName}` : newName;
            // Check if component with this name already exists
            const existingComponent = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(newFullName);
            if (existingComponent && existingComponent !== renamingItem.data.component) {
                return { valid: false, error: 'A component with this name already exists' };
            }
        }
        else if (renamingItem.type === 'folder') {
            // For folders, check if any component exists with this folder path
            const currentPath = renamingItem.data.path;
            const pathParts = currentPath.split('/');
            pathParts.pop(); // Remove current folder name
            const parentPath = pathParts.join('/');
            const newFolderPath = parentPath ? `${parentPath}/${newName}` : newName;
            // Check if any component starts with this folder path
            const components = ((_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.getComponents()) || [];
            const hasConflict = components.some((comp) => {
                // Check if component is in a folder with the new name
                return comp.name.startsWith(newFolderPath + '/') && !comp.name.startsWith(currentPath + '/');
            });
            if (hasConflict) {
                return { valid: false, error: 'A folder with this name already exists' };
            }
        }
        return { valid: true };
    }, [renamingItem]);
    return {
        renamingItem,
        renameValue,
        setRenameValue,
        startRename,
        cancelRename,
        validateName
    };
}

;// ./src/editor/src/views/panels/ComponentsPanelNew/hooks/useSheetManagement.ts







/**
 * useSheetManagement
 *
 * Hook for managing sheets (top-level organizational folders starting with #).
 * Provides CRUD operations with full undo/redo support.
 */
function useSheetManagement() {
    /**
     * Create a new sheet with the given name.
     * Creates a placeholder component at #SheetName/.placeholder to establish the folder.
     */
    const createSheet = (0,external_react_.useCallback)((name) => {
        if (!projectmodel.ProjectModel.instance) {
            ToastLayer.ToastLayer.showError('No project open');
            return false;
        }
        // Validate name
        const trimmedName = name.trim();
        if (!trimmedName) {
            ToastLayer.ToastLayer.showError('Sheet name cannot be empty');
            return false;
        }
        // Check for invalid characters
        if (trimmedName.includes('/') || trimmedName.includes('#')) {
            ToastLayer.ToastLayer.showError('Sheet name cannot contain / or #');
            return false;
        }
        // Build the folder name (with # prefix)
        const folderName = `#${trimmedName}`;
        // Check if sheet already exists
        const existingComponents = projectmodel.ProjectModel.instance.getComponents();
        const sheetExists = existingComponents.some((comp) => comp.name.startsWith(folderName + '/'));
        if (sheetExists) {
            ToastLayer.ToastLayer.showError(`Sheet "${trimmedName}" already exists`);
            return false;
        }
        // Create placeholder to establish the folder
        // Component names start with "/" to match project naming convention
        const placeholderName = `/${folderName}/.placeholder`;
        undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
            label: `Create sheet "${trimmedName}"`,
            do: () => {
                var _a;
                const placeholder = new componentmodel/* ComponentModel */.j({
                    name: placeholderName,
                    graph: new nodegraphmodel/* NodeGraphModel */.W2(),
                    id: (0,utils.guid)()
                });
                (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.addComponent(placeholder);
            },
            undo: () => {
                var _a, _b;
                const placeholder = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(placeholderName);
                if (placeholder) {
                    (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.removeComponent(placeholder);
                }
            }
        }));
        ToastLayer.ToastLayer.showSuccess(`Created sheet "${trimmedName}"`);
        return true;
    }, []);
    /**
     * Rename a sheet and update all component paths within it.
     */
    const renameSheet = (0,external_react_.useCallback)((sheet, newName) => {
        if (!projectmodel.ProjectModel.instance) {
            ToastLayer.ToastLayer.showError('No project open');
            return false;
        }
        if (sheet.isDefault) {
            ToastLayer.ToastLayer.showError('Cannot rename the default sheet');
            return false;
        }
        // Validate new name
        const trimmedNewName = newName.trim();
        if (!trimmedNewName) {
            ToastLayer.ToastLayer.showError('Sheet name cannot be empty');
            return false;
        }
        if (trimmedNewName.includes('/') || trimmedNewName.includes('#')) {
            ToastLayer.ToastLayer.showError('Sheet name cannot contain / or #');
            return false;
        }
        const oldFolderName = sheet.folderName;
        const newFolderName = `#${trimmedNewName}`;
        // If the name hasn't changed, nothing to do
        if (oldFolderName === newFolderName) {
            return true;
        }
        // Check if target name already exists
        // Components start with "/" so we need to check for "/#{NewName}/"
        const oldPrefix = '/' + oldFolderName + '/';
        const newPrefix = '/' + newFolderName + '/';
        const existingComponents = projectmodel.ProjectModel.instance.getComponents();
        const targetExists = existingComponents.some((comp) => comp.name.startsWith(newPrefix));
        if (targetExists) {
            ToastLayer.ToastLayer.showError(`Sheet "${trimmedNewName}" already exists`);
            return false;
        }
        // Find all components in this sheet (components start with "/")
        const componentsInSheet = existingComponents.filter((comp) => comp.name.startsWith(oldPrefix));
        if (componentsInSheet.length === 0) {
            ToastLayer.ToastLayer.showError('Sheet has no components to rename');
            return false;
        }
        // Build the rename map with old/new name STRINGS (not component references for undo)
        const renameMap = [];
        componentsInSheet.forEach((comp) => {
            // Replace the old prefix with new prefix
            const newComponentName = comp.name.replace(oldPrefix, newPrefix);
            renameMap.push({
                oldName: comp.name,
                newName: newComponentName
            });
        });
        undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
            label: `Rename sheet "${sheet.name}" to "${trimmedNewName}"`,
            do: () => {
                // Find and rename each component by its current name
                renameMap.forEach(({ oldName, newName }) => {
                    var _a, _b;
                    const comp = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(oldName);
                    if (comp) {
                        (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.renameComponent(comp, newName);
                    }
                });
            },
            undo: () => {
                // Rename in reverse order - find by NEW name and rename back to OLD name
                [...renameMap].reverse().forEach(({ oldName, newName }) => {
                    var _a, _b;
                    const comp = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(newName);
                    if (comp) {
                        (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.renameComponent(comp, oldName);
                    }
                });
            }
        }));
        ToastLayer.ToastLayer.showSuccess(`Renamed sheet to "${trimmedNewName}"`);
        return true;
    }, []);
    /**
     * Delete a sheet by moving all its components to the default sheet (root level).
     * Components are preserved - only the sheet organization is removed.
     */
    const deleteSheet = (0,external_react_.useCallback)((sheet) => {
        if (!projectmodel.ProjectModel.instance) {
            ToastLayer.ToastLayer.showError('No project open');
            return false;
        }
        if (sheet.isDefault) {
            ToastLayer.ToastLayer.showError('Cannot delete the default sheet');
            return false;
        }
        // Find all components in this sheet (including placeholders)
        const componentsInSheet = projectmodel.ProjectModel.instance
            .getComponents()
            .filter((comp) => comp.name.startsWith('/' + sheet.folderName + '/'));
        // Check if sheet exists at all (must have at least a placeholder)
        if (componentsInSheet.length === 0) {
            ToastLayer.ToastLayer.showError('Sheet does not exist');
            return false;
        }
        // Build rename map using STRINGS only (not component references for undo)
        // e.g., "/#Pages/MyPage" becomes "/MyPage"
        const renameMap = [];
        const placeholderNames = [];
        componentsInSheet.forEach((comp) => {
            if (comp.name.endsWith('/.placeholder')) {
                // Mark placeholders for deletion (they're only needed for empty folders)
                placeholderNames.push(comp.name);
            }
            else {
                // Calculate new name by removing sheet prefix
                const sheetPrefix = '/' + sheet.folderName;
                const newName = comp.name.replace(sheetPrefix, '');
                renameMap.push({
                    oldName: comp.name,
                    newName
                });
            }
        });
        // Allow deletion of empty sheets (sheets with only placeholders)
        if (renameMap.length === 0) {
            // Sheet is empty (only has placeholders) - just delete the placeholders
            undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
                label: `Delete empty sheet "${sheet.name}"`,
                do: () => {
                    placeholderNames.forEach((placeholderName) => {
                        var _a, _b;
                        const placeholder = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(placeholderName);
                        if (placeholder) {
                            (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.removeComponent(placeholder);
                        }
                    });
                },
                undo: () => {
                    placeholderNames.forEach((placeholderName) => {
                        var _a;
                        const restoredPlaceholder = new componentmodel/* ComponentModel */.j({
                            name: placeholderName,
                            graph: new nodegraphmodel/* NodeGraphModel */.W2(),
                            id: (0,utils.guid)()
                        });
                        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.addComponent(restoredPlaceholder);
                    });
                }
            }));
            ToastLayer.ToastLayer.showSuccess(`Deleted empty sheet "${sheet.name}"`);
            return true;
        }
        // Check for naming conflicts
        for (const { newName } of renameMap) {
            const existing = projectmodel.ProjectModel.instance.getComponentWithName(newName);
            if (existing) {
                ToastLayer.ToastLayer.showError(`Cannot delete sheet: "${newName.split('/').pop()}" already exists at root level`);
                return false;
            }
        }
        undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
            label: `Delete sheet "${sheet.name}"`,
            do: () => {
                // Remove placeholders first (find by name)
                placeholderNames.forEach((placeholderName) => {
                    var _a, _b;
                    const placeholder = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(placeholderName);
                    if (placeholder) {
                        (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.removeComponent(placeholder);
                    }
                });
                // Rename components to remove sheet prefix (find by OLD name)
                renameMap.forEach(({ oldName, newName }) => {
                    var _a, _b;
                    const comp = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(oldName);
                    if (comp) {
                        (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.renameComponent(comp, newName);
                    }
                });
            },
            undo: () => {
                // Rename components back to include sheet prefix (find by NEW name)
                [...renameMap].reverse().forEach(({ oldName, newName }) => {
                    var _a, _b;
                    const comp = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(newName);
                    if (comp) {
                        (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.renameComponent(comp, oldName);
                    }
                });
                // Restore placeholders
                placeholderNames.forEach((placeholderName) => {
                    var _a;
                    const restoredPlaceholder = new componentmodel/* ComponentModel */.j({
                        name: placeholderName,
                        graph: new nodegraphmodel/* NodeGraphModel */.W2(),
                        id: (0,utils.guid)()
                    });
                    (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.addComponent(restoredPlaceholder);
                });
            }
        }));
        const componentCount = renameMap.length;
        ToastLayer.ToastLayer.showSuccess(`Deleted sheet "${sheet.name}" - ${componentCount} component${componentCount !== 1 ? 's' : ''} moved to root`);
        return true;
    }, []);
    /**
     * Move a component to a different sheet.
     */
    const moveToSheet = (0,external_react_.useCallback)((componentName, targetSheet) => {
        if (!projectmodel.ProjectModel.instance) {
            ToastLayer.ToastLayer.showError('No project open');
            return false;
        }
        const component = projectmodel.ProjectModel.instance.getComponentWithName(componentName);
        if (!component) {
            ToastLayer.ToastLayer.showError('Component not found');
            return false;
        }
        // Determine the component's local name (without any folder prefix)
        const parts = componentName.split('/');
        const localName = parts[parts.length - 1];
        // Build the new name - component names must start with "/"
        let newName;
        if (targetSheet.isDefault) {
            // Moving to default sheet - use "/" + local name
            newName = `/${localName}`;
        }
        else {
            // Moving to named sheet - "/#SheetName/localName"
            newName = `/${targetSheet.folderName}/${localName}`;
        }
        // Check if name already exists in target
        if (projectmodel.ProjectModel.instance.getComponentWithName(newName)) {
            ToastLayer.ToastLayer.showError(`A component named "${localName}" already exists in ${targetSheet.name}`);
            return false;
        }
        const oldName = componentName;
        undo_queue_model/* UndoQueue */.g.instance.pushAndDo(new undo_queue_model/* UndoActionGroup */.C({
            label: `Move "${localName}" to sheet "${targetSheet.name}"`,
            do: () => {
                var _a, _b;
                // Find component by current name, not stale reference
                const comp = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(oldName);
                if (comp) {
                    (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.renameComponent(comp, newName);
                }
            },
            undo: () => {
                var _a, _b;
                // Find component by NEW name to rename back
                const comp = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(newName);
                if (comp) {
                    (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.renameComponent(comp, oldName);
                }
            }
        }));
        ToastLayer.ToastLayer.showSuccess(`Moved "${localName}" to ${targetSheet.name}`);
        return true;
    }, []);
    return {
        createSheet,
        renameSheet,
        deleteSheet,
        moveToSheet
    };
}

;// ./src/editor/src/views/panels/ComponentsPanelNew/ComponentsPanelReact.tsx
/**
 * ComponentsPanel
 *
 * Modern React component for displaying and managing project components.
 * Migrated from legacy jQuery/underscore.js View implementation.
 *
 * @module noodl-editor
 */















/**
 * ComponentsPanel displays the project's component tree with folders,
 * allowing users to navigate, create, rename, and organize components.
 */
function ComponentsPanel({ options }) {
    const { treeData, expandedFolders, selectedId, toggleFolder, handleItemClick, sheets, currentSheet, selectSheet } = useComponentsPanel({
        hideSheets: options === null || options === void 0 ? void 0 : options.hideSheets,
        lockToSheet: options === null || options === void 0 ? void 0 : options.lockToSheet
    });
    const { handleMakeHome, handleDelete, handleDuplicate, performRename, handleOpen, handleDropOn, handleDropOnRoot, handleAddComponent, handleAddFolder } = useComponentActions();
    const { createSheet, renameSheet, deleteSheet, moveToSheet } = useSheetManagement();
    const { draggedItem, startDrag, canDrop } = useDragDrop();
    const { renamingItem, renameValue, startRename, setRenameValue, cancelRename, validateName } = useRenameMode();
    // Handle creating a new sheet
    const handleCreateSheet = (0,external_react_.useCallback)(() => {
        DialogLayerModel.instance.showDialog((close) => external_react_default().createElement(StringInputDialog, {
            title: 'New sheet name',
            placeholder: 'Enter sheet name',
            confirmLabel: 'Create',
            onConfirm: (value) => {
                createSheet(value);
                close();
            },
            onCancel: close
        }));
    }, [createSheet]);
    // Handle renaming a sheet
    const handleRenameSheet = (0,external_react_.useCallback)((sheet) => {
        DialogLayerModel.instance.showDialog((close) => external_react_default().createElement(StringInputDialog, {
            title: 'Rename sheet',
            defaultValue: sheet.name,
            confirmLabel: 'Rename',
            onConfirm: (value) => {
                renameSheet(sheet, value);
                close();
            },
            onCancel: close
        }));
    }, [renameSheet]);
    // Handle deleting a sheet
    const handleDeleteSheet = (0,external_react_.useCallback)((sheet) => {
        DialogLayerModel.instance.showConfirm({
            title: `Delete sheet "${sheet.name}"?`,
            text: `The ${sheet.componentCount} component(s) in this sheet will be moved to the root level.`,
            onConfirm: () => {
                const wasCurrentSheet = currentSheet && currentSheet.folderName === sheet.folderName;
                const success = deleteSheet(sheet);
                // Navigate to "All" view if we deleted the currently selected sheet
                if (success && wasCurrentSheet) {
                    selectSheet(null);
                }
            }
        });
    }, [deleteSheet, currentSheet, selectSheet]);
    // Handle moving a component to a sheet
    const handleMoveToSheet = (0,external_react_.useCallback)((componentPath, sheet) => {
        moveToSheet(componentPath, sheet);
    }, [moveToSheet]);
    // Handle rename action from context menu
    const handleRename = (0,external_react_.useCallback)((node) => {
        startRename(node);
    }, [startRename]);
    // Handle rename confirmation
    const handleRenameConfirm = (0,external_react_.useCallback)(() => {
        if (!renamingItem || !renameValue) {
            return;
        }
        // Check if name actually changed
        const currentName = renamingItem.type === 'component' ? renamingItem.data.localName : renamingItem.data.name;
        if (renameValue === currentName) {
            // Name unchanged, just exit rename mode
            cancelRename();
            return;
        }
        // Validate the NEW name
        const validation = validateName(renameValue);
        if (!validation.valid) {
            console.warn('Invalid component name:', validation.error);
            return; // Stay in rename mode so user can fix
        }
        // Perform the actual rename
        const success = performRename(renamingItem, renameValue);
        if (success) {
            cancelRename();
        }
    }, [renamingItem, renameValue, validateName, performRename, cancelRename]);
    // Direct drop handler - bypasses useDragDrop state system for immediate execution
    // This matches how handleDropOnRoot works (which is reliable)
    const handleDirectDrop = (0,external_react_.useCallback)((targetNode) => {
        if (draggedItem) {
            handleDropOn(draggedItem, targetNode);
        }
    }, [draggedItem, handleDropOn]);
    // Handle mouse up on Tree background - this is the root drop fallback
    // If an item is a valid drop target, its handleMouseUp calls stopPropagation
    // So if we receive mouseUp here, it means no item claimed the drop
    const handleTreeMouseUp = (0,external_react_.useCallback)(() => {
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const PopupLayer = __webpack_require__(45653);
        // If we're dragging and no specific item claimed the drop, it's a root drop
        if (draggedItem && PopupLayer.instance.isDragging()) {
            handleDropOnRoot(draggedItem);
        }
    }, [draggedItem, handleDropOnRoot]);
    // Handle right-click on empty space - Show create menu
    const handleTreeContextMenu = (0,external_react_.useCallback)((e) => {
        e.preventDefault();
        e.stopPropagation();
        const templates = ComponentTemplates.instance.getTemplates({
            forRuntimeType: 'browser'
        });
        const items = templates.map((template) => ({
            icon: template.icon,
            label: `Create ${template.label}`,
            onClick: () => handleAddComponent(template)
        }));
        items.push({
            icon: common_Icon/* IconName */.$M.FolderClosed,
            label: 'Create Folder',
            onClick: () => handleAddFolder()
        });
        (0,ShowContextMenuInPopup.showContextMenuInPopup)({
            items,
            width: MenuDialog.MenuDialogWidth.Default
        });
    }, [handleAddComponent, handleAddFolder]);
    return (external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['ComponentsPanel'] },
        external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['Header'] },
            external_react_default().createElement("span", { className: ComponentsPanelNew_ComponentsPanel_module['Title'] }, "Components"),
            external_react_default().createElement(SheetSelector, { sheets: sheets, currentSheet: currentSheet, onSelectSheet: selectSheet, onCreateSheet: handleCreateSheet, onRenameSheet: handleRenameSheet, onDeleteSheet: handleDeleteSheet, disabled: !!(options === null || options === void 0 ? void 0 : options.lockToSheet) })),
        external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['Tree'], onContextMenu: handleTreeContextMenu, onMouseUp: handleTreeMouseUp }, treeData.length > 0 ? (external_react_default().createElement(ComponentTree, { nodes: treeData, expandedFolders: expandedFolders, selectedId: selectedId, onItemClick: handleItemClick, onCaretClick: toggleFolder, onMakeHome: handleMakeHome, onDelete: handleDelete, onDuplicate: handleDuplicate, onRename: handleRename, onOpen: handleOpen, onDragStart: startDrag, onDrop: handleDirectDrop, canAcceptDrop: canDrop, onAddComponent: handleAddComponent, onAddFolder: handleAddFolder, renamingItem: renamingItem, renameValue: renameValue, onRenameChange: setRenameValue, onRenameConfirm: handleRenameConfirm, onRenameCancel: cancelRename, onDoubleClick: handleRename, sheets: sheets, onMoveToSheet: handleMoveToSheet })) : (external_react_default().createElement("div", { className: ComponentsPanelNew_ComponentsPanel_module['PlaceholderMessage'] },
            external_react_default().createElement("span", null, "No components in project"))))));
}

;// ./src/editor/src/views/panels/componentspanel/index.tsx
/**
 * ComponentsPanel Wrapper
 *
 * Temporary wrapper that will be replaced with direct import
 * from the new ComponentsPanel React component.
 */


/**
 * Wrapper component for ComponentsPanel
 * Currently using new React implementation
 */
function componentspanel_ComponentsPanel({ options }) {
    return external_react_default().createElement(ComponentsPanel, { options: options });
}

;// ./src/editor/src/views/panels/CloudFunctionsPanel/CloudFunctionsPanel.tsx














function CloudFunctionsPanel() {
    const environment = useActiveEnvironment(projectmodel.ProjectModel.instance);
    const componentPanelOptions = {
        showSheetList: false,
        lockCurrentSheetName: '__cloud__',
        componentTitle: 'Cloud Components'
    };
    return (external_react_default().createElement(BasePanel, { title: "Cloud Functions", isFill: true },
        external_react_default().createElement(Container, { direction: ContainerDirection.Vertical, isFill: true },
            external_react_default().createElement(ActionButton, { prefixText: "Active cloud service", label: environment === null || environment === void 0 ? void 0 : environment.name, icon: common_Icon/* IconName */.$M.CloudData, variant: ActionButtonVariant.Default, isInactive: true }),
            external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasYSpacing: true },
                external_react_default().createElement(Stack/* VStack */.Tk, null,
                    external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
                        external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Open cloud dev tools", fineType: Keybindings.OPEN_CLOUD_DEVTOOLS.label },
                            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { icon: common_Icon/* IconName */.$M.Bug, label: "Open cloud dev tools", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, onClick: () => external_electron_.ipcRenderer.send('cloud-runtime-open-devtools'), isGrowing: true }))),
                    external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Refresh cloud functions" },
                        external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { icon: common_Icon/* IconName */.$M.Refresh, label: "Refresh cloud functions", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, onClick: () => external_electron_.ipcRenderer.send('cloud-runtime-refresh'), isGrowing: true })))),
            external_react_default().createElement("div", { style: { flex: '1', overflow: 'hidden' } },
                external_react_default().createElement(componentspanel_ComponentsPanel, { options: componentPanelOptions })))));
}

// EXTERNAL MODULE: ./src/editor/src/hooks/useTimeout.ts
var useTimeout = __webpack_require__(98849);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/ConditionalContainer/ConditionalContainer.module.scss
var ConditionalContainer_module = __webpack_require__(41453);
;// ../noodl-core-ui/src/components/layout/ConditionalContainer/ConditionalContainer.module.scss

      
      
      
      
      
      
      
      
      

var ConditionalContainer_module_options = {};

ConditionalContainer_module_options.styleTagTransform = (styleTagTransform_default());
ConditionalContainer_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ConditionalContainer_module_options.insert = insertBySelector_default().bind(null, "head");
    
ConditionalContainer_module_options.domAPI = (styleDomAPI_default());
ConditionalContainer_module_options.insertStyleElement = (insertStyleElement_default());

var ConditionalContainer_module_update = injectStylesIntoStyleTag_default()(ConditionalContainer_module/* default */.A, ConditionalContainer_module_options);




       /* harmony default export */ const ConditionalContainer_ConditionalContainer_module = (ConditionalContainer_module/* default */.A && ConditionalContainer_module/* default */.A.locals ? ConditionalContainer_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/ConditionalContainer/ConditionalContainer.tsx





var LoaderType;
(function (LoaderType) {
    LoaderType["Block"] = "block";
    LoaderType["Inline"] = "inline";
})(LoaderType || (LoaderType = {}));
function ConditionalContainer({ doRenderWhen, isLoaderHidden, loaderType = LoaderType.Block, children, loaderStyle, loaderVisibilityDelayMs = 1500, UNSAFE_root_className, UNSAFE_root_style, UNSAFE_className, UNSAFE_style }) {
    const [isTimeoutCleared, setIsTimeoutCleared] = (0,external_react_.useState)(false);
    const [isLoaderRendered, setIsLoaderRendered] = (0,external_react_.useState)(Boolean(loaderVisibilityDelayMs) ? false : true);
    (0,useTimeout/* default */.A)(() => {
        setIsLoaderRendered(true);
    }, isTimeoutCleared ? null : loaderVisibilityDelayMs);
    (0,external_react_.useEffect)(() => {
        if (!doRenderWhen) {
            setIsTimeoutCleared(false);
            setIsLoaderRendered(true);
        }
        else {
            setIsLoaderRendered(false);
            setIsTimeoutCleared(true);
        }
    }, [doRenderWhen]);
    (0,external_react_.useEffect)(() => {
        if (!isLoaderHidden)
            return;
        setIsLoaderRendered(false);
        setIsTimeoutCleared(true);
    }, [isLoaderHidden]);
    return (external_react_default().createElement("div", { className: external_classnames_default()(ConditionalContainer_ConditionalContainer_module['Root'], UNSAFE_root_className), style: UNSAFE_root_style },
        doRenderWhen && children,
        isLoaderRendered && !doRenderWhen && (external_react_default().createElement("div", { style: loaderStyle, className: external_classnames_default()([ConditionalContainer_ConditionalContainer_module['Loader'], ConditionalContainer_ConditionalContainer_module[`is-loader-type-${loaderType}`]]) },
            external_react_default().createElement("div", { className: external_classnames_default()(ConditionalContainer_ConditionalContainer_module['LoaderInner'], UNSAFE_className), style: UNSAFE_style },
                external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null))))));
}

;// ../noodl-core-ui/src/components/layout/ConditionalContainer/index.ts


// EXTERNAL MODULE: ./src/editor/src/hooks/useParsedHref.ts
var useParsedHref = __webpack_require__(49484);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/TextButton/TextButton.module.scss
var TextButton_module = __webpack_require__(4628);
;// ../noodl-core-ui/src/components/inputs/TextButton/TextButton.module.scss

      
      
      
      
      
      
      
      
      

var TextButton_module_options = {};

TextButton_module_options.styleTagTransform = (styleTagTransform_default());
TextButton_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      TextButton_module_options.insert = insertBySelector_default().bind(null, "head");
    
TextButton_module_options.domAPI = (styleDomAPI_default());
TextButton_module_options.insertStyleElement = (insertStyleElement_default());

var TextButton_module_update = injectStylesIntoStyleTag_default()(TextButton_module/* default */.A, TextButton_module_options);




       /* harmony default export */ const TextButton_TextButton_module = (TextButton_module/* default */.A && TextButton_module/* default */.A.locals ? TextButton_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/TextButton/TextButton.tsx







var TextButtonSize;
(function (TextButtonSize) {
    TextButtonSize["Default"] = "default";
    TextButtonSize["Small"] = "small";
})(TextButtonSize || (TextButtonSize = {}));
function TextButton({ label, variant, variantOnHover, size = TextButtonSize.Default, href, icon, hasLeftSpacing, hasRightSpacing, onClick, testId, UNSAFE_className, UNSAFE_style }) {
    const parsedHref = (0,useParsedHref/* default */.A)(href);
    const [currentVariant, setCurrentVariant] = (0,external_react_.useState)(variant);
    const iconSize = size === TextButtonSize.Default ? common_Icon/* IconSize */.lK.Default : common_Icon/* IconSize */.lK.Tiny;
    return (external_react_default().createElement("button", { className: external_classnames_default()([
            TextButton_TextButton_module['Root'],
            TextButton_TextButton_module[`is-size-${size}`],
            hasLeftSpacing && TextButton_TextButton_module['has-left-spacing'],
            hasRightSpacing && TextButton_TextButton_module['has-right-spacing'],
            TextButton_TextButton_module[`is-variant-${currentVariant}`],
            UNSAFE_className
        ]), onClick: (e) => {
            if (parsedHref)
                src.platform.openExternal(parsedHref);
            if (onClick)
                onClick(e);
        }, onMouseEnter: () => {
            if (!variantOnHover)
                return;
            setCurrentVariant(variantOnHover);
        }, onMouseLeave: () => {
            if (!variantOnHover)
                return;
            setCurrentVariant(variant);
        }, "data-test": testId, style: UNSAFE_style },
        icon && external_react_default().createElement(common_Icon/* Icon */.In, { icon: icon, size: iconSize, UNSAFE_style: { marginRight: 4 } }),
        ' ',
        external_react_default().createElement(typography_Text/* Text */.EY, { textType: currentVariant }, label)));
}

;// ../noodl-core-ui/src/components/inputs/TextButton/index.ts


;// ../noodl-core-ui/src/components/layout/Columns/Columns.tsx


function toArray(value) {
    return Array.isArray(value) ? value : [value];
}
function convert(...values) {
    for (const value of values) {
        if (typeof value === 'boolean' && value) {
            return '16px';
        }
        if (typeof value === 'number') {
            return value * 4 + 'px';
        }
    }
    return undefined;
}
function Columns({ hasXGap, hasYGap, layoutString = '1 1', direction = 'row', justifyContent = 'flex-start', UNSAFE_style, UNSAFE_className, children }) {
    if (!children)
        return null;
    let columnLayout = null;
    switch (typeof layoutString) {
        case 'string':
            columnLayout = layoutString.trim();
            break;
        case 'number':
            columnLayout = layoutString.toString().trim();
            break;
        default:
            columnLayout = null;
    }
    if (!columnLayout) {
        return external_react_default().createElement((external_react_default()).Fragment, null, children);
    }
    // all data for childrens width calculation
    const layout = columnLayout.split(' ').map((number) => parseInt(number));
    const totalFractions = layout.reduce((a, b) => a + b, 0);
    const fractionSize = 100 / totalFractions;
    const columnAmount = layout.length;
    const marginX = convert(hasXGap);
    const marginY = convert(hasYGap);
    return (external_react_default().createElement("div", { className: external_classnames_default()('columns-container', UNSAFE_className), style: {
            ...UNSAFE_style,
            marginTop: `calc(${marginY} * -1)`,
            marginLeft: `calc(${marginX} * -1)`,
            display: 'flex',
            flexWrap: 'wrap',
            flexDirection: direction,
            width: `calc(100% + (${marginX})`,
            boxSizing: 'border-box',
            alignItems: 'stretch',
            justifyContent: justifyContent
        } }, toArray(children).map((child, i) => {
        // Skip non-element children (null, undefined, boolean)
        if (!external_react_default().isValidElement(child)) {
            return child;
        }
        return (external_react_default().createElement("div", { className: "column-item", key: i, style: {
                boxSizing: 'border-box',
                paddingTop: marginY,
                paddingLeft: marginX,
                width: layout[i % columnAmount] * fractionSize + '%',
                flexShrink: 0,
                flexGrow: 0
            } }, external_react_default().cloneElement(child)));
    })));
}

;// ../noodl-core-ui/src/components/layout/Columns/index.ts


// EXTERNAL MODULE: external "react-hot-toast"
var external_react_hot_toast_ = __webpack_require__(64389);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/ToastLayer/ToastLayerContainer.module.scss
var ToastLayerContainer_module = __webpack_require__(51490);
;// ./src/editor/src/views/ToastLayer/ToastLayerContainer.module.scss

      
      
      
      
      
      
      
      
      

var ToastLayerContainer_module_options = {};

ToastLayerContainer_module_options.styleTagTransform = (styleTagTransform_default());
ToastLayerContainer_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ToastLayerContainer_module_options.insert = insertBySelector_default().bind(null, "head");
    
ToastLayerContainer_module_options.domAPI = (styleDomAPI_default());
ToastLayerContainer_module_options.insertStyleElement = (insertStyleElement_default());

var ToastLayerContainer_module_update = injectStylesIntoStyleTag_default()(ToastLayerContainer_module/* default */.A, ToastLayerContainer_module_options);




       /* harmony default export */ const ToastLayer_ToastLayerContainer_module = (ToastLayerContainer_module/* default */.A && ToastLayerContainer_module/* default */.A.locals ? ToastLayerContainer_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/ToastLayer/ToastLayerContainer.tsx



function ToastLayerContainer() {
    return (external_react_default().createElement("div", { className: ToastLayer_ToastLayerContainer_module['Root'] },
        external_react_default().createElement(external_react_hot_toast_.Toaster, { position: "bottom-right", containerClassName: ToastLayer_ToastLayerContainer_module['ToastContainer'], toastOptions: {
                icon: null,
                style: {
                    border: 'none',
                    padding: '0',
                    backgroundColor: 'transparent',
                    margin: 0
                },
                duration: 6000
            } })));
}

;// ./src/editor/src/views/ToastLayer/index.ts



;// ./src/editor/src/views/panels/CloudServicePanel/CloudServiceModal/CloudSerivceModal.tsx











function CloudServiceModal(props) {
    return external_react_default().createElement(AsSelfHosted, { ...props });
}
function AsSelfHosted({ isVisible, setIsVisible, isActive, environment, onUnsetEditorClick, onDeleteClick, onSetEditorClick }) {
    const [name, setName] = (0,external_react_.useState)(environment.name);
    const [description, setDescription] = (0,external_react_.useState)(environment.description);
    const [showMasterKey, setShowMasterKey] = (0,external_react_.useState)(false);
    const [masterKey, setMasterKey] = (0,external_react_.useState)(environment.masterKey);
    function update() {
        CloudServices.CloudService.instance.backend
            .update({
            id: environment.id,
            name,
            description,
            masterKey
        })
            .then(() => {
            ToastLayer.ToastLayer.showSuccess(`Updated Cloud Service`);
            CloudServices.CloudService.instance.backend.fetch();
        })
            .catch(() => {
            ToastLayer.ToastLayer.showError(`Failed to update Cloud Service`);
        });
    }
    return (external_react_default().createElement(Modal, { title: "Manage self hosted cloud service", isVisible: isVisible, onClose: () => setIsVisible(false) },
        external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
            external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: true },
                external_react_default().createElement(TextInput, { value: name, variant: TextInputVariant.InModal, label: "Name", onChange: (e) => setName(e.target.value), onBlur: update, onEnter: update }),
                external_react_default().createElement(TextInput, { value: description, variant: TextInputVariant.InModal, label: "Description", onChange: (e) => setDescription(e.target.value), onBlur: update, onEnter: update }),
                external_react_default().createElement(Columns, { hasXGap: 4, layoutString: "1 1" },
                    external_react_default().createElement(TextInput, { value: environment.appId, variant: TextInputVariant.InModal, label: "App Id", isReadonly: true, isCopyable: true, UNSAFE_style: { flex: 1 } }),
                    external_react_default().createElement(Stack/* VStack */.Tk, null,
                        external_react_default().createElement(TextInput, { value: masterKey, variant: TextInputVariant.InModal, label: "Master key", type: showMasterKey ? 'text' : 'password', notification: !masterKey ? { type: FeedbackType/* FeedbackType */.M.Danger } : undefined, onChange: (e) => setMasterKey(e.target.value), UNSAFE_style: { flex: 1 }, onFocus: () => {
                                setShowMasterKey(true);
                            }, onBlur: () => {
                                setShowMasterKey(false);
                                update();
                            }, onEnter: update }),
                        !masterKey && (external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: 2 },
                            external_react_default().createElement(typography_Text/* Text */.EY, { textType: FeedbackType/* FeedbackType */.M.Danger }, "Missing Master Key, enter the Master Key to be able to use this Cloud Service in the editor."))),
                        external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: 2 },
                            external_react_default().createElement(typography_Text/* Text */.EY, null, "The Master Key is saved locally in an encrypted file.")))),
                external_react_default().createElement(TextInput, { value: environment.url, variant: TextInputVariant.InModal, label: "Endpoint", isReadonly: true, isCopyable: true }))),
        isActive ? (external_react_default().createElement(TextButton, { label: "Use editor without backend", onClick: onUnsetEditorClick })) : (external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: 2 },
            external_react_default().createElement(TextButton, { label: "Unlink service", onClick: onDeleteClick, variant: FeedbackType/* FeedbackType */.M.Danger }),
            external_react_default().createElement(TextButton, { label: "Use in editor", onClick: () => {
                    // A lil' ugly hack to trigger the overlay
                    setTimeout(() => {
                        onSetEditorClick && onSetEditorClick(environment.id);
                    }, 10);
                } })))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/CloudServicePanel/CloudServiceCard/CloudServiceCard.module.scss
var CloudServiceCard_module = __webpack_require__(6014);
;// ./src/editor/src/views/panels/CloudServicePanel/CloudServiceCard/CloudServiceCard.module.scss

      
      
      
      
      
      
      
      
      

var CloudServiceCard_module_options = {};

CloudServiceCard_module_options.styleTagTransform = (styleTagTransform_default());
CloudServiceCard_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      CloudServiceCard_module_options.insert = insertBySelector_default().bind(null, "head");
    
CloudServiceCard_module_options.domAPI = (styleDomAPI_default());
CloudServiceCard_module_options.insertStyleElement = (insertStyleElement_default());

var CloudServiceCard_module_update = injectStylesIntoStyleTag_default()(CloudServiceCard_module/* default */.A, CloudServiceCard_module_options);




       /* harmony default export */ const CloudServiceCard_CloudServiceCard_module = (CloudServiceCard_module/* default */.A && CloudServiceCard_module/* default */.A.locals ? CloudServiceCard_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/CloudServicePanel/CloudServiceCard/CloudServiceCard.tsx











function CloudServiceCard({ environment, isEditorEnvironment, isAlerting, isAlwaysOpen, onDeleteClick, onArchiveClick, onRestoreClick, onSetEditorClick, onUnsetEditorClick }) {
    const rootRef = (0,external_react_.useRef)(null);
    const [isDrawerOpen, setIsDrawerOpen] = (0,external_react_.useState)(false);
    const [isModalVisible, setIsModalVisible] = (0,external_react_.useState)(false);
    let isDrawerCollapsed = !isDrawerOpen;
    if (isAlwaysOpen)
        isDrawerCollapsed = false;
    function onDashboardClicked() {
        // Open Parse Dashboard
        parsedashboardserver.instance.openInWindow(environment);
    }
    const { name, description } = environment;
    (0,external_react_.useEffect)(() => {
        var _a;
        if (!(rootRef === null || rootRef === void 0 ? void 0 : rootRef.current) || !isAlerting)
            return;
        (_a = rootRef.current) === null || _a === void 0 ? void 0 : _a.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }, [rootRef === null || rootRef === void 0 ? void 0 : rootRef.current, isAlerting]);
    let errorMessage = '';
    if (!environment.masterKey) {
        errorMessage = 'Missing Master Key';
    }
    return (external_react_default().createElement("div", { ref: rootRef, className: external_classnames_default()([
            CloudServiceCard_CloudServiceCard_module['Root'],
            isEditorEnvironment && CloudServiceCard_CloudServiceCard_module['is-editor-environment'],
            !isDrawerCollapsed && CloudServiceCard_CloudServiceCard_module['is-open'],
            isAlerting && CloudServiceCard_CloudServiceCard_module['is-alerting']
        ]), "data-test": `cloud-service-card-${name}` },
        external_react_default().createElement("div", { className: external_classnames_default()(CloudServiceCard_CloudServiceCard_module['Inner'], isAlwaysOpen && CloudServiceCard_CloudServiceCard_module['is-always-open']), onClick: () => !isAlwaysOpen && setIsDrawerOpen(!isDrawerOpen) },
            external_react_default().createElement("div", { className: CloudServiceCard_CloudServiceCard_module['MetaBar'] },
                external_react_default().createElement("div", { className: external_classnames_default()([CloudServiceCard_CloudServiceCard_module['TypeDisplay'], isEditorEnvironment && CloudServiceCard_CloudServiceCard_module['is-editor-environment']]) },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CloudCheck, size: common_Icon/* IconSize */.lK.Small, UNSAFE_style: { marginRight: 4 } }),
                    'Self hosted ',
                    errorMessage && external_react_default().createElement("span", { className: CloudServiceCard_CloudServiceCard_module['ArchivedDisplay'] },
                        "(",
                        errorMessage,
                        ")"),
                    isEditorEnvironment && external_react_default().createElement("span", { className: CloudServiceCard_CloudServiceCard_module['UsedInEditorDisplay'] }, "(Used in editor)")),
                external_react_default().createElement("div", { className: CloudServiceCard_CloudServiceCard_module['ToggleContainer'] }, !isAlwaysOpen && (external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.CaretDown, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, state: isDrawerOpen ? inputs_IconButton/* IconButtonState */.Df.Rotated : null })))),
            external_react_default().createElement("div", { className: CloudServiceCard_CloudServiceCard_module['Header'], "data-test": "open-cloud-service-card-drawer" },
                external_react_default().createElement("div", { className: CloudServiceCard_CloudServiceCard_module['HeaderInner'] },
                    external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.DefaultContrast, hasBottomSpacing: 
                        // sorry for double ternary, but essentially:
                        // SMALL if has description
                        // LARGE if no description and isAlwaysOpen
                        description ? Label/* LabelSpacingSize */.Zt.Small : isAlwaysOpen ? Label/* LabelSpacingSize */.Zt.Large : undefined }, name),
                    description && external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: isEditorEnvironment }, description)),
                isEditorEnvironment && (external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Open dashboard", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, onClick: onDashboardClicked, isGrowing: true })))),
        external_react_default().createElement(Collapsible/* Collapsible */.N, { isCollapsed: isDrawerCollapsed },
            external_react_default().createElement("div", { className: external_classnames_default()(CloudServiceCard_CloudServiceCard_module['Drawer'], isEditorEnvironment && CloudServiceCard_CloudServiceCard_module['has-no-top-padding']) },
                !isEditorEnvironment && (external_react_default().createElement((external_react_default()).Fragment, null,
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Open dashboard", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, onClick: onDashboardClicked, isGrowing: true, hasBottomSpacing: true }))),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, label: "Manage cloud service", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, onClick: () => setIsModalVisible(true), hasBottomSpacing: true }),
                isEditorEnvironment && (external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, label: "Use editor without backend", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, onClick: onUnsetEditorClick, hasBottomSpacing: !isEditorEnvironment })),
                !isEditorEnvironment && (external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, label: "Use in editor", onClick: () => {
                        // A lil' ugly hack to trigger the overlay
                        setTimeout(() => {
                            onSetEditorClick(isEditorEnvironment ? null : environment.id);
                        }, 10);
                    } })))),
        isModalVisible && (external_react_default().createElement(CloudServiceModal, { isVisible: isModalVisible, setIsVisible: setIsModalVisible, isActive: isEditorEnvironment, environment: environment, onDeleteClick: onDeleteClick, onArchiveClick: onArchiveClick, onRestoreClick: onRestoreClick, onSetEditorClick: onSetEditorClick, onUnsetEditorClick: onUnsetEditorClick }))));
}

;// ./src/editor/src/views/panels/CloudServicePanel/CloudServiceCard/index.ts


;// ./src/editor/src/views/panels/CloudServicePanel/CloudServicePanel.context.tsx







const CloudServiceContext = (0,external_react_.createContext)({
    hasUpdatedEditorEnvironment: null,
    editorEnvironmentId: null,
    editorEnvironment: null,
    setSelectedEnvironment: null,
    hasActivity: null,
    runActivity: null
});
function CloudServiceContextProvider({ children }) {
    const cloudService = (0,useModel/* useModernModel */.e)(CloudServices.CloudService.instance);
    const { hasActivity, runActivity } = useActivityQueue({
        onSuccess: async () => {
            // Always fetch all the backends after something have changed
            await cloudService.backend.fetch();
        }
    });
    const [hasUpdatedEditorEnvironment, setHasUpdatedEditorEnvironment] = (0,external_react_.useState)(false);
    // Listen for selected environment change.
    // TODO: This hook should be somewhere else (project context)
    const [editorEnvironmentId, setEditorEnvironmentId] = (0,external_react_.useState)(NO_ENVIRONMENT_VALUE);
    const [editorEnvironment, setEditorEnvironment] = (0,external_react_.useState)(null);
    (0,external_react_.useEffect)(() => {
        function updateSelectedEnvironment() {
            const activeEnvironment = (0,projectmodel_editor.getCloudServices)(projectmodel.ProjectModel.instance);
            const environment = cloudService.backend.items.find((x) => x.id === activeEnvironment.id ||
                // Can't find the environment, it's likely an external service.
                // Check if we have a service with the same endpoint and appId
                (x.url === activeEnvironment.endpoint && x.appId === activeEnvironment.appId));
            setEditorEnvironmentId(environment ? environment.id : null);
            setEditorEnvironment(environment || null);
        }
        projectmodel.ProjectModel.instance.on('cloudServicesChanged', updateSelectedEnvironment, this);
        updateSelectedEnvironment();
        return function () {
            var _a;
            (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.off(this);
        };
    }, [cloudService.backend.items]);
    function setSelectedEnvironment(id) {
        setHasUpdatedEditorEnvironment(true);
        // reset flag after alert has been shown
        setTimeout(() => setHasUpdatedEditorEnvironment(false), 3000);
        const environment = cloudService.backend.items.find((x) => x.id === id);
        const broker = environment
            ? {
                id: environment.id,
                endpoint: environment.url,
                appId: environment.appId
            }
            : {
                id: undefined,
                endpoint: undefined,
                appId: undefined
            };
        (0,projectmodel_editor.setCloudServices)(projectmodel.ProjectModel.instance, broker);
    }
    return (external_react_default().createElement(CloudServiceContext.Provider, { value: {
            hasUpdatedEditorEnvironment,
            editorEnvironmentId,
            editorEnvironment,
            setSelectedEnvironment,
            hasActivity,
            runActivity
        } }, children));
}
function useCloudServiceContext() {
    const context = (0,external_react_.useContext)(CloudServiceContext);
    if (context === undefined) {
        throw new Error('useCloudServiceContext must be a child of CloudServiceContextProvider');
    }
    return context;
}

;// ./src/editor/src/views/panels/CloudServicePanel/CloudServiceCardItem/CloudServiceCardItem.tsx





function CloudServiceCardItem({ environment, deleteEnvironment }) {
    const { hasUpdatedEditorEnvironment, editorEnvironmentId, setSelectedEnvironment, runActivity } = useCloudServiceContext();
    const isSelected = environment.id === editorEnvironmentId;
    async function onDelete() {
        await deleteEnvironment();
        await runActivity('Deleting cloud service...', async () => {
            const response = await CloudServices.CloudService.instance.backend.delete(environment.id);
            return {
                type: ToastCard/* ToastType */.C.Success,
                message: 'Cloud service deleted'
            };
        });
    }
    async function onArchive() {
        throw new Error('Method not implemented.');
    }
    async function onRestore() {
        throw new Error('Method not implemented.');
    }
    return (external_react_default().createElement(CloudServiceCard, { isAlwaysOpen: isSelected, key: environment.id, environment: environment, isEditorEnvironment: isSelected, isAlerting: isSelected && hasUpdatedEditorEnvironment, onDeleteClick: onDelete, onArchiveClick: onArchive, onRestoreClick: onRestore, onSetEditorClick: setSelectedEnvironment, onUnsetEditorClick: () => setSelectedEnvironment(null) }));
}

;// ./src/editor/src/views/panels/CloudServicePanel/CloudServiceCardItem/index.ts


;// ./src/editor/src/views/panels/CloudServicePanel/CloudServiceCreateModal/CloudServiceCreateModal.tsx











function isValidParseUrl(url) {
    if (!url)
        return false;
    if (!url.toLowerCase().startsWith('http')) {
        url = 'http://' + url;
    }
    try {
        new URL(url);
        if (url.endsWith('/') || url.endsWith('\\')) {
            return 'Invalid Url, remove the slash from the end';
        }
        return undefined;
    }
    catch (err) {
        return 'Invalid Url';
    }
}
function CloudServiceCreateModal({ isVisible, onClose }) {
    const { runActivity } = useCloudServiceContext();
    const cloudService = (0,useModel/* useModernModel */.e)(CloudServices.CloudService.instance);
    const [name, setName] = (0,external_react_.useState)('');
    const [description, setDescription] = (0,external_react_.useState)('');
    const [masterKey, setMasterKey] = (0,external_react_.useState)('');
    // Fields required for External
    const [endpoint, setEndpoint] = (0,external_react_.useState)('');
    const isEndpointValid = isValidParseUrl(endpoint);
    const [appId, setAppId] = (0,external_react_.useState)('');
    function clearForm() {
        setName('');
        setDescription('');
        setEndpoint('');
        setAppId('');
        setMasterKey('');
    }
    async function onCreate() {
        await runActivity('Creating Cloud Service...', async () => {
            await cloudService.backend.create({
                name,
                description,
                masterKey: masterKey ? masterKey : undefined,
                appId: appId ? appId : undefined,
                url: endpoint ? endpoint : undefined
            });
            clearForm();
            onClose();
            return {
                type: ToastCard/* ToastType */.C.Success,
                message: 'Cloud Service created!'
            };
        });
    }
    function isCloudServiceCreationAllowed() {
        if (!name)
            return false;
        if (!endpoint || !appId)
            return false;
        return true;
    }
    const externalGuideUrl = (0,editor_getDocsEndpoint/* default */.A)() + '/docs/guides/deploy/using-an-external-backend';
    return (external_react_default().createElement(Modal_Modal, { isVisible: isVisible, onClose: onClose, title: "Add new cloud service" },
        external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true, textType: typography_Text/* TextType */.M2.DefaultContrast }, "Each cloud service is isolated. This allows you to create separate ones for development, testing and production, or for different locales."),
            external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true, textType: typography_Text/* TextType */.M2.DefaultContrast },
                "For a cloud service to be compatible with the Noodl Cloud Functions you need to use our image. Read more about self hosting cloud services",
                ' ',
                external_react_default().createElement("a", { target: "_blank", href: externalGuideUrl, rel: "noreferrer" }, "here"),
                "."),
            external_react_default().createElement("div", { style: { textAlign: 'right' } },
                external_react_default().createElement("div", { style: { textAlign: 'left', display: 'flex', flexDirection: 'column' } },
                    external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true, textType: typography_Text/* TextType */.M2.DefaultContrast },
                        "Noodl backends are self hosted. Refer to to",
                        ' ',
                        external_react_default().createElement("a", { href: externalGuideUrl, target: "_blank", rel: "noreferrer" }, "this guide"),
                        ' ',
                        "to learn more.")),
                external_react_default().createElement(TextInput, { label: "Name", value: name, variant: TextInputVariant.InModal, onChange: (e) => setName(e.target.value), testId: "new-cloud-service-name-input", hasBottomSpacing: true }),
                external_react_default().createElement(TextInput, { label: "Description (optional)", value: description, variant: TextInputVariant.InModal, onChange: (e) => setDescription(e.target.value), hasBottomSpacing: true }),
                external_react_default().createElement("div", null,
                    external_react_default().createElement(TextInput, { label: "Endpoint", value: endpoint, notification: isEndpointValid
                            ? {
                                type: FeedbackType/* FeedbackType */.M.Notice,
                                message: isEndpointValid
                            }
                            : undefined, variant: TextInputVariant.InModal, onChange: (e) => setEndpoint(e.target.value), hasBottomSpacing: true }),
                    external_react_default().createElement(TextInput, { label: "Application ID", value: appId, variant: TextInputVariant.InModal, onChange: (e) => setAppId(e.target.value), hasBottomSpacing: true })),
                external_react_default().createElement(TextInput, { label: "Master key (encrypted and only stored on your computer)", value: masterKey, variant: TextInputVariant.InModal, onChange: (e) => setMasterKey(e.target.value) }),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast, hasBottomSpacing: true, style: { textAlign: 'left' } }, "Can't be used as editor backend if left blank"),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { onClick: () => onCreate(), label: "Create new cloud service", isDisabled: !isCloudServiceCreationAllowed(), testId: "create-new-cloud-service-button" })))));
}

;// ./src/editor/src/views/panels/CloudServicePanel/CloudServicePanel.tsx
















function CloudServicePanel() {
    return (external_react_default().createElement(CloudServiceContextProvider, null,
        external_react_default().createElement(CloudServicePanelChild, null)));
}
function CloudServicePanelChild() {
    var _a, _b;
    const { hasActivity } = useCloudServiceContext();
    const cloudService = (0,useModel/* useModernModel */.e)(CloudServices.CloudService.instance);
    const [DeleteDialog, deleteEnvironment] = useConfirmationDialog({
        title: 'Please confirm',
        message: 'Are you sure you want to delete this cloud service?',
        isDangerousAction: true
    });
    const [isCreateModalVisible, setIsCreateModalVisible] = (0,external_react_.useState)(false);
    return (external_react_default().createElement(BasePanel, { title: "Cloud Services", hasActivityBlocker: hasActivity, hasContentScroll: true },
        external_react_default().createElement(DeleteDialog, null),
        external_react_default().createElement(ConditionalContainer, { doRenderWhen: Boolean(cloudService.backend.items), loaderVisibilityDelayMs: 0 },
            external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement(Section/* Section */.w, { title: "Available Cloud Services", variant: Section/* SectionVariant */.$.Panel, actions: external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Plus, size: common_Icon/* IconSize */.lK.Small, onClick: () => setIsCreateModalVisible(true), testId: "add-cloud-service-tab-button" }) }, ((_a = cloudService.backend.items) === null || _a === void 0 ? void 0 : _a.length) ? (external_react_default().createElement(Stack/* VStack */.Tk, null, (_b = cloudService.backend.items) === null || _b === void 0 ? void 0 : _b.map((environment) => (external_react_default().createElement(CloudServiceCardItem, { key: environment.id, environment: environment, deleteEnvironment: deleteEnvironment }))))) : cloudService.backend.isLoading ? (external_react_default().createElement(Container, { hasLeftSpacing: true, hasTopSpacing: true },
                    external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null))) : (external_react_default().createElement(Container, { hasLeftSpacing: true, hasTopSpacing: true },
                    external_react_default().createElement(typography_Text/* Text */.EY, null, "No cloud services")))))),
        external_react_default().createElement(CloudServiceCreateModal, { isVisible: isCreateModalVisible, onClose: () => setIsCreateModalVisible(false) })));
}

// EXTERNAL MODULE: external "underscore"
var external_underscore_ = __webpack_require__(80002);
var external_underscore_default = /*#__PURE__*/__webpack_require__.n(external_underscore_);
;// ./src/editor/src/views/panels/componentports.tsx
/* eslint-disable @typescript-eslint/no-this-alias */







// eslint-disable-next-line @typescript-eslint/no-var-requires
const ComponentPortsTemplate = __webpack_require__(24070);
class ComponentPorts extends (view_default()) {
    constructor(args) {
        super();
        this.parent = args.parent;
        this.model = args.model;
        this.type = args.type;
        this.plug = args.plug;
        this.title = args.title ? args.title : 'Ports';
        this.group = args.group;
        this.lastIndex = 0;
        this.lastGroup = undefined;
        this.canArrangeInGroups = args.canArrangeInGroups;
    }
    render() {
        // Component inputs will have output ports, and vice versa
        this.el = this.bindView($(ComponentPortsTemplate), this);
        if (!this.canArrangeInGroups)
            this.$('.add-group-button').hide();
        this.bindModel();
        this.renderPorts(true);
        this.parent && this.parent.append(this.el);
        return this.el;
    }
    resize(layout) {
        this.el.css({
            position: 'absolute',
            left: layout.x,
            top: layout.y,
            width: layout.width,
            height: layout.height
        });
    }
    bindModel() {
        const _this = this;
        this.model.on(['portAdded', 'portRemoved', 'portRenamed', 'portRearranged'], function () {
            _this.scheduleRender(true);
        });
    }
    getPorts(filter) {
        // We must explicitly get node instance ports only
        const ports = (0,external_underscore_.filter)(this.model.ports, function (p) {
            return !filter || p.plug === filter;
        });
        ports.sort(function (a, b) {
            return a.index > b.index ? 1 : -1;
        });
        return ports;
    }
    getItemsWithGroups() {
        const groups = [
            {
                name: undefined,
                ports: []
            }
        ];
        function addToGroup(name, p) {
            for (let i = 0; i < groups.length; i++)
                if (groups[i].name === name) {
                    groups[i].ports.push(p);
                    return;
                }
            groups.push({ name: name, ports: [p] });
        }
        const ports = this.getPorts(this.plug);
        for (let i = 0; i < ports.length; i++) {
            const p = ports[i];
            addToGroup(p.group, p);
        }
        const items = [];
        for (let i = 0; i < groups.length; i++) {
            const g = groups[i];
            if (g.name !== undefined)
                items.push({ type: 'group', label: g.name });
            for (let j = 0; j < g.ports.length; j++) {
                const p = g.ports[j];
                items.push({ type: 'port', label: p.name, port: p });
            }
        }
        this.lastIndex = items.length > 0 ? items[items.length - 1].port.index : 0;
        this.lastGroup = groups[groups.length - 1].name;
        return items;
    }
    getItems() {
        if (this.canArrangeInGroups)
            return this.getItemsWithGroups();
        else {
            const ports = this.getPorts(this.plug);
            return ports.map(function (p) {
                return { type: 'port', label: p.name, port: p };
            });
        }
    }
    makeDraggable(el, item) {
        const _this = this;
        let mouseDownOnItem = false;
        el.find('.drag-handle').on('mousedown', function (e) {
            mouseDownOnItem = true;
        });
        el.find('.drag-handle').on('mouseup', function (e) {
            mouseDownOnItem = false;
        });
        el.find('.drag-handle').on('mousemove', function (e) {
            if (mouseDownOnItem) {
                popuplayer_default().instance.startDragging({ label: item.label, item: item });
                mouseDownOnItem = false;
            }
        });
    }
    makeDroppable(el, item) {
        const _this = this;
        el.find('.drop-target').on('mouseover', (e) => {
            if (popuplayer_default().instance.isDragging()) {
                const dragItem = (popuplayer_default()).instance.dragItem;
                const sourceIdx = this.items.indexOf(dragItem.item);
                const targetIdx = this.items.indexOf(item);
                const renderTop = targetIdx < sourceIdx;
                el.find('.drop-indicator')
                    .show()
                    .css(renderTop ? { top: 0, bottom: '' } : { top: '', bottom: 0 });
                popuplayer_default().instance.indicateDropType('move');
            }
        });
        el.find('.drop-target').on('mouseout', function (e) {
            el.find('.drop-indicator').hide();
            popuplayer_default().instance.indicateDropType('none');
        });
        el.find('.drop-target').on('mouseup', function (e) {
            const dragItem = (popuplayer_default()).instance.dragItem;
            if (dragItem) {
                _this.dropOnItem({ target: item, source: dragItem.item });
                popuplayer_default().instance.dragCompleted();
            }
        });
    }
    arrangePorts(args) {
        const items = this.items;
        const undo = new undo_queue_model/* UndoActionGroup */.C({ label: args && args.label ? args.label : 'rearrange ports' });
        // Update groups and index for all ports
        let group = undefined;
        let index = 0;
        for (let i = 0; i < items.length; i++) {
            const item = items[i];
            if (item.type === 'group')
                group = item.label;
            else if (item.type === 'port') {
                this.model.arrangePort(item.port.name, index, group, { undo: undo });
                index++;
            }
        }
        undo_queue_model/* UndoQueue */.g.instance.push(undo);
    }
    dropOnItem(args) {
        if (args.target === args.source)
            return;
        // Reorder items
        const sourceIdx = this.items.indexOf(args.source);
        const targetIdx = this.items.indexOf(args.target);
        this.items.splice(sourceIdx, 1);
        const newIdx = targetIdx;
        // if(sourceIdx > targetIdx) newIdx++;
        this.items.splice(newIdx, 0, args.source);
        this.arrangePorts();
    }
    scheduleRender(refresh) {
        const _this = this;
        if (refresh)
            this.refreshItemsScheduled = true;
        if (this.renderScheduled)
            return;
        this.renderScheduled = true;
        setTimeout(function () {
            if (_this.renderScheduled) {
                _this.renderPorts(_this.refreshItemsScheduled);
            }
            _this.renderScheduled = false;
            _this.refreshItemsScheduled = false;
        }, 1);
    }
    renderPorts(refresh) {
        this.$('.ports').html('');
        if (refresh)
            this.items = this.getItems();
        const items = this.items;
        for (const i in items) {
            const item = items[i];
            let itemEl = null;
            if (item.type === 'port') {
                itemEl = this.bindView(this.cloneTemplate('item'), { port: item.port, label: item.label });
            }
            else if (item.type === 'group') {
                itemEl = this.bindView(this.cloneTemplate('group'), { label: item.label, item: item });
            }
            this.makeDraggable(itemEl, item);
            this.makeDroppable(itemEl, item);
            this.$('.ports').append(itemEl);
        }
    }
    // Add port
    onAddPortClicked(scope, el, evt) {
        const _this = this;
        const popup = new popuplayer.StringInputPopup({
            label: 'New port name',
            okLabel: 'Add',
            cancelLabel: 'Cancel',
            onOk: function (portName) {
                const result = _this.performAdd(portName);
                if (!result.success) {
                    ToastLayer.ToastLayer.showError(result.message);
                }
                _this.notifyListeners('panelResized');
            }
        });
        popup.render();
        popuplayer_default().instance.showPopup({
            content: popup,
            attachTo: el,
            position: 'top'
        });
        evt.stopPropagation();
    }
    performAdd(portNames) {
        if (portNames === '') {
            return { success: false, message: 'Port name cannot be empty' };
        }
        else {
            const result = portNames.split(',').map((port) => {
                const portName = port.trim();
                if (this.model.findPortWithName(portName)) {
                    return { success: false, message: 'Cannot create a port with the same name as an existing one.' };
                }
                else {
                    const port = {
                        name: portName,
                        plug: this.plug,
                        type: this.type,
                        group: this.group !== undefined ? this.group : this.lastGroup,
                        index: ++this.lastIndex
                    };
                    this.model.addPort(port, { undo: true, label: 'add port' });
                    return { success: true };
                }
            });
            const failed = result.find((r) => !r.success);
            return failed ? failed : { success: true };
        }
    }
    // Rename port
    performRename(args) {
        if (args.newName === '') {
            return { success: false, message: 'Port name cannot be empty' };
        }
        else if (this.model.findPortWithName(args.newName)) {
            // Show alert that component cannot have same name as an
            // existing component
            return { success: false, message: 'Cannot rename a port to the same name as an existing one.' };
        }
        else {
            this.model.renamePortWithName(args.oldName, args.newName, { undo: true, label: 'rename port' });
            return { success: true };
        }
    }
    onRenameClicked(scope, el, evt) {
        const _this = this;
        const parent = el.parents('.component-ports-item');
        parent.find('.show-on-edit').show();
        parent.find('.hide-on-edit').hide();
        function rename() {
            const newName = input.val();
            if (newName !== scope.port.name) {
                const result = _this.performRename({ newName: newName, oldName: scope.port.name });
                if (!result.success) {
                    ToastLayer.ToastLayer.showError(result.message);
                }
            }
            parent.find('.show-on-edit').hide();
            parent.find('.hide-on-edit').show();
            input.off('blur').off('keypress'); // Make sure rename doesn't get called twice
        }
        const input = parent.find('input');
        input
            .focus()
            .off('blur')
            .on('blur', function () {
            rename();
        })
            .off('keypress')
            .on('keypress', function (e) {
            if (e.which == 13)
                rename();
        });
        evt.stopPropagation();
    }
    // Delete port
    performDelete(portname) {
        if (this.model.isPortConnected(portname)) {
            return { success: false, message: 'Cannot remove port, does it have active connections?' };
        }
        else {
            this.model.removePortWithName(portname, { undo: true, label: 'delete port' });
            return { success: true };
        }
    }
    onDeleteClicked(scope, el, evt) {
        const result = this.performDelete(scope.port.name);
        if (!result.success) {
            ToastLayer.ToastLayer.showError(result.message);
        }
        this.notifyListeners('panelResized');
        evt.stopPropagation();
    }
    // Add group
    onAddGroupClicked(scope, el, evt) {
        const _this = this;
        const popup = new popuplayer.StringInputPopup({
            label: 'New group name',
            okLabel: 'Add',
            cancelLabel: 'Cancel',
            onOk: function (groupName) {
                const result = _this.performAddGroup(groupName);
                if (!result.success) {
                    ToastLayer.ToastLayer.showError(result.message);
                }
                _this.notifyListeners('panelResized');
            }
        });
        popup.render();
        popuplayer_default().instance.showPopup({
            content: popup,
            attachTo: el,
            position: 'top'
        });
        evt.stopPropagation();
    }
    findGroupWithName(groupName) {
        if (!this.items)
            this.item = this.getItems();
        const items = this.items;
        for (let i = 0; i < items.length; i++) {
            const item = items[i];
            if (item.label === groupName && item.type === 'group')
                return item;
        }
    }
    performAddGroup(groupNames) {
        const _this = this;
        if (groupNames === '') {
            return { success: false, message: 'Group name cannot be empty' };
        }
        else {
            const result = groupNames.split(',').map((group) => {
                const groupName = group.trim();
                if (this.findGroupWithName(groupName)) {
                    return { success: false, message: 'Group with that name already exist' };
                }
                else {
                    const oldLastGroup = this.lastGroup;
                    const newGroup = { type: 'group', label: groupName };
                    // @ts-expect-error TODO: What?
                    undo_queue_model/* UndoQueue */.g.instance.pushAndDo({
                        label: 'add group',
                        do: function () {
                            _this.lastGroup = groupName;
                            _this.items.push(newGroup);
                            _this.scheduleRender();
                        },
                        undo: function () {
                            _this.lastGroup = oldLastGroup;
                            const idx = _this.items.indexOf(newGroup);
                            idx !== -1 && _this.items.splice(idx, 1);
                            _this.scheduleRender();
                        }
                    });
                    return { success: true };
                }
            });
            const failed = result.find((r) => !r.success);
            return failed ? failed : { success: true };
        }
    }
    // Rename group
    performRenameGroup(args) {
        if (args.newName === '') {
            return { success: false, message: 'Group name cannot be empty' };
        }
        else {
            args.item.label = args.newName;
            this.arrangePorts({ label: 'rename group' });
            return { success: true };
        }
    }
    onRenameGroupClicked(scope, el, evt) {
        const _this = this;
        const parent = el.parents('.component-ports-group-item');
        parent.find('.show-on-edit').show();
        parent.find('.hide-on-edit').hide();
        function rename() {
            const newName = input.val();
            if (newName !== scope.item.label) {
                const result = _this.performRenameGroup({ newName: newName, item: scope.item });
                if (!result.success) {
                    ToastLayer.ToastLayer.showError(result.message);
                }
            }
            parent.find('.show-on-edit').hide();
            parent.find('.hide-on-edit').show();
            input.off('blur').off('keypress'); // Make sure rename doesn't get called twice
        }
        const input = parent.find('input');
        input
            .focus()
            .off('blur')
            .on('blur', function () {
            rename();
        })
            .off('keypress')
            .on('keypress', function (e) {
            if (e.which == 13)
                rename();
        });
        evt.stopPropagation();
    }
    // Delete group
    performDeleteGroup(item) {
        const idx = this.items.indexOf(item);
        this.items.splice(idx, 1);
        this.arrangePorts({ label: 'delete group' });
        return { success: true };
    }
    onDeleteGroupClicked(scope, el, evt) {
        const result = this.performDeleteGroup(scope.item);
        if (!result.success) {
            // @ts-expect-error TODO: What?
            ToastLayer.ToastLayer.showError(result.message);
        }
        this.notifyListeners('panelResized');
        evt.stopPropagation();
    }
}
function ComponentPortsComponent(props) {
    const [instance, setInstance] = (0,external_react_.useState)(null);
    (0,external_react_.useEffect)(() => {
        const instance = new ComponentPorts(props);
        instance.render();
        setInstance(instance);
    }, []);
    return external_react_default().createElement(Frame, { instance: instance, isFitWidth: true });
}

// EXTERNAL MODULE: ./src/editor/src/services/HighlightManager/index.ts + 4 modules
var HighlightManager = __webpack_require__(57002);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/ComponentXRayPanel/ComponentXRayPanel.module.scss
var ComponentXRayPanel_module = __webpack_require__(94715);
;// ./src/editor/src/views/panels/ComponentXRayPanel/ComponentXRayPanel.module.scss

      
      
      
      
      
      
      
      
      

var ComponentXRayPanel_module_options = {};

ComponentXRayPanel_module_options.styleTagTransform = (styleTagTransform_default());
ComponentXRayPanel_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ComponentXRayPanel_module_options.insert = insertBySelector_default().bind(null, "head");
    
ComponentXRayPanel_module_options.domAPI = (styleDomAPI_default());
ComponentXRayPanel_module_options.insertStyleElement = (insertStyleElement_default());

var ComponentXRayPanel_module_update = injectStylesIntoStyleTag_default()(ComponentXRayPanel_module/* default */.A, ComponentXRayPanel_module_options);




       /* harmony default export */ const ComponentXRayPanel_ComponentXRayPanel_module = (ComponentXRayPanel_module/* default */.A && ComponentXRayPanel_module/* default */.A.locals ? ComponentXRayPanel_module/* default */.A.locals : undefined);

;// ./src/editor/src/utils/graphAnalysis/traversal.ts
/**
 * Graph traversal utilities for analyzing node connections and data flow
 */
/**
 * Trace a connection chain from a starting point.
 * Follows connections upstream (to sources) or downstream (to sinks).
 *
 * @param component - Component containing the starting node
 * @param startNodeId - ID of the node to start from
 * @param startPort - Port name to start from
 * @param direction - 'upstream' (find sources) or 'downstream' (find sinks)
 * @param options - Traversal options
 * @returns Traversal result with path and metadata
 *
 * @example
 * ```typescript
 * // Find what feeds into a Text node's 'text' input
 * const result = traceConnectionChain(
 *   component,
 *   textNodeId,
 *   'text',
 *   'upstream'
 * );
 * console.log('Path:', result.path.map(p => p.node.label));
 * ```
 */
function traceConnectionChain(component, startNodeId, startPort, direction, options = {}) {
    var _a, _b, _c, _d;
    const maxDepth = (_a = options.maxDepth) !== null && _a !== void 0 ? _a : 100;
    const crossComponents = (_b = options.crossComponents) !== null && _b !== void 0 ? _b : false;
    const stopAtTypes = (_c = options.stopAtTypes) !== null && _c !== void 0 ? _c : [];
    const stopAtBranch = (_d = options.stopAtBranch) !== null && _d !== void 0 ? _d : false;
    const path = [];
    const crossedComponents = [];
    const visited = new Set();
    const startNode = component.graph.nodeMap.get(startNodeId);
    if (!startNode) {
        return {
            path: [],
            crossedComponents: [],
            terminatedAt: 'source'
        };
    }
    // Add starting point
    path.push({
        node: startNode,
        port: startPort,
        direction: direction === 'upstream' ? 'input' : 'output'
    });
    let currentNodes = [{ nodeId: startNodeId, port: startPort }];
    let depth = 0;
    while (currentNodes.length > 0 && depth < maxDepth) {
        const nextNodes = [];
        for (const current of currentNodes) {
            const key = `${current.nodeId}:${current.port}`;
            if (visited.has(key)) {
                continue; // Skip cycles
            }
            visited.add(key);
            const connections = getPortConnections(component, current.nodeId, current.port, direction === 'upstream' ? 'input' : 'output');
            if (connections.length === 0) {
                // Dead end - no more connections
                continue;
            }
            if (stopAtBranch && connections.length > 1) {
                // Multiple branches - stop here if requested
                return {
                    path,
                    crossedComponents,
                    terminatedAt: 'sink'
                };
            }
            for (const conn of connections) {
                const targetNodeId = direction === 'upstream' ? conn.fromNodeId : conn.toNodeId;
                const targetPort = direction === 'upstream' ? conn.fromPort : conn.toPort;
                const targetNode = component.graph.nodeMap.get(targetNodeId);
                if (!targetNode)
                    continue;
                // Check if we should stop at this node type
                if (stopAtTypes.includes(targetNode.typename)) {
                    path.push({
                        node: targetNode,
                        port: targetPort,
                        direction: direction === 'upstream' ? 'output' : 'input',
                        connection: conn
                    });
                    return {
                        path,
                        crossedComponents,
                        terminatedAt: 'source'
                    };
                }
                // Check for component boundary
                if (targetNode.typename === 'Component Inputs' || targetNode.typename === 'Component Outputs') {
                    if (crossComponents) {
                        // TODO: Cross component boundary resolution
                        // This requires finding the parent component instance and resolving connections
                        return {
                            path,
                            crossedComponents,
                            terminatedAt: 'component-boundary'
                        };
                    }
                    else {
                        path.push({
                            node: targetNode,
                            port: targetPort,
                            direction: direction === 'upstream' ? 'output' : 'input',
                            connection: conn
                        });
                        return {
                            path,
                            crossedComponents,
                            terminatedAt: 'component-boundary'
                        };
                    }
                }
                // Add to path and continue
                path.push({
                    node: targetNode,
                    port: targetPort,
                    direction: direction === 'upstream' ? 'output' : 'input',
                    connection: conn
                });
                nextNodes.push({ nodeId: targetNodeId, port: targetPort });
            }
        }
        currentNodes = nextNodes;
        depth++;
    }
    // Determine termination reason
    if (depth >= maxDepth) {
        return { path, crossedComponents, terminatedAt: 'cycle' };
    }
    return {
        path,
        crossedComponents,
        terminatedAt: direction === 'upstream' ? 'source' : 'sink'
    };
}
/**
 * Get all nodes directly connected to a given node.
 *
 * @param component - Component containing the node
 * @param nodeId - ID of the node to check
 * @returns Object with arrays of connected input and output nodes
 *
 * @example
 * ```typescript
 * const neighbors = getConnectedNodes(component, nodeId);
 * console.log('Inputs from:', neighbors.inputs.map(n => n.label));
 * console.log('Outputs to:', neighbors.outputs.map(n => n.label));
 * ```
 */
function getConnectedNodes(component, nodeId) {
    const inputs = [];
    const outputs = [];
    const inputSet = new Set();
    const outputSet = new Set();
    for (const conn of component.graph.connections) {
        // Find nodes that feed into this node (inputs)
        if (conn.toId === nodeId) {
            if (!inputSet.has(conn.fromId)) {
                const node = component.graph.nodeMap.get(conn.fromId);
                if (node) {
                    inputs.push(node);
                    inputSet.add(conn.fromId);
                }
            }
        }
        // Find nodes that this node feeds into (outputs)
        if (conn.fromId === nodeId) {
            if (!outputSet.has(conn.toId)) {
                const node = component.graph.nodeMap.get(conn.toId);
                if (node) {
                    outputs.push(node);
                    outputSet.add(conn.toId);
                }
            }
        }
    }
    return { inputs, outputs };
}
/**
 * Get all connections for a specific port.
 *
 * @param component - Component containing the node
 * @param nodeId - ID of the node
 * @param portName - Name of the port
 * @param direction - Port direction ('input' or 'output')
 * @returns Array of connection references
 *
 * @example
 * ```typescript
 * const connections = getPortConnections(component, nodeId, 'value', 'output');
 * console.log('Sends to:', connections.map(c => c.toNodeId));
 * ```
 */
function getPortConnections(component, nodeId, portName, direction) {
    const connections = [];
    for (const conn of component.graph.connections) {
        if (direction === 'input' && conn.toId === nodeId && conn.toProperty === portName) {
            connections.push({
                fromNodeId: conn.fromId,
                fromPort: conn.fromProperty,
                toNodeId: conn.toId,
                toPort: conn.toProperty
            });
        }
        else if (direction === 'output' && conn.fromId === nodeId && conn.fromProperty === portName) {
            connections.push({
                fromNodeId: conn.fromId,
                fromPort: conn.fromProperty,
                toNodeId: conn.toId,
                toPort: conn.toProperty
            });
        }
    }
    return connections;
}
/**
 * Build an adjacency list representation of the node graph.
 * Useful for graph algorithms and analysis.
 *
 * @param component - Component to analyze
 * @returns Map of node IDs to their connected node IDs (inputs and outputs)
 *
 * @example
 * ```typescript
 * const adjacency = buildAdjacencyList(component);
 * const nodeConnections = adjacency.get(nodeId);
 * console.log('Inputs:', nodeConnections.inputs);
 * console.log('Outputs:', nodeConnections.outputs);
 * ```
 */
function buildAdjacencyList(component) {
    const adjacency = new Map();
    // Initialize all nodes
    component.graph.nodeMap.forEach((node) => {
        adjacency.set(node.id, { inputs: [], outputs: [] });
    });
    // Add connections
    for (const conn of component.graph.connections) {
        const fromEntry = adjacency.get(conn.fromId);
        const toEntry = adjacency.get(conn.toId);
        if (fromEntry) {
            fromEntry.outputs.push(conn.toId);
        }
        if (toEntry) {
            toEntry.inputs.push(conn.fromId);
        }
    }
    return adjacency;
}
/**
 * Get all connections in a component.
 *
 * @param component - Component to analyze
 * @returns Array of all connection references
 */
function getAllConnections(component) {
    return component.graph.connections.map((conn) => ({
        fromNodeId: conn.fromId,
        fromPort: conn.fromProperty,
        toNodeId: conn.toId,
        toPort: conn.toProperty
    }));
}
/**
 * Find all nodes of a specific type in a component.
 *
 * @param component - Component to search
 * @param typename - Node type name to find
 * @returns Array of matching nodes
 *
 * @example
 * ```typescript
 * const variables = findNodesOfType(component, 'Variable');
 * console.log('Variables:', variables.map(n => n.label));
 * ```
 */
function findNodesOfType(component, typename) {
    const nodes = [];
    component.graph.nodeMap.forEach((node) => {
        if (node.typename === typename) {
            nodes.push(node);
        }
    });
    return nodes;
}

;// ./src/editor/src/utils/graphAnalysis/crossComponent.ts
/**
 * Cross-component resolution utilities for tracing connections through component boundaries
 */

/**
 * Find all places where a component is instantiated across the project.
 *
 * @param project - Project to search
 * @param componentName - Name of the component to find usages of
 * @returns Array of component usage information
 *
 * @example
 * ```typescript
 * const usages = findComponentUsages(project, 'UserCard');
 * usages.forEach(usage => {
 *   console.log(`Used in ${usage.usedIn.name} as node ${usage.instanceNodeId}`);
 * });
 * ```
 */
function findComponentUsages(project, componentName) {
    const usages = [];
    const targetComponent = project.getComponentWithName(componentName);
    if (!targetComponent) {
        return usages;
    }
    // Iterate through all components in the project
    project.forEachComponent((component) => {
        // Skip the component itself
        if (component.name === componentName) {
            return;
        }
        // Check all nodes in this component
        component.graph.nodeMap.forEach((node) => {
            // Check if this node is an instance of the target component
            if (node.type instanceof componentmodel/* ComponentModel */.j && node.type.name === componentName) {
                // Find all connections to this component instance
                const connectedPorts = [];
                const ports = node.getPorts('input');
                ports.forEach((port) => {
                    const connections = component.graph.connections.filter((conn) => conn.toId === node.id && conn.toProperty === port.name);
                    if (connections.length > 0) {
                        connectedPorts.push({
                            port: port.name,
                            connectedTo: connections.map((conn) => ({
                                nodeId: conn.fromId,
                                port: conn.fromProperty
                            }))
                        });
                    }
                });
                usages.push({
                    component: targetComponent,
                    usedIn: component,
                    instanceNodeId: node.id,
                    connectedPorts
                });
            }
        });
    });
    return usages;
}
/**
 * Resolve a Component Input/Output port to its external connections.
 * Given a Component Inputs node, find what feeds into it from the parent component.
 * Given a Component Outputs node, find what it feeds into in the parent component.
 *
 * @param project - Project containing the components
 * @param component - Component containing the boundary node
 * @param boundaryNodeId - ID of the Component Inputs or Component Outputs node
 * @param portName - Name of the port on the boundary node
 * @returns Array of external connections (empty if not found or no parent)
 *
 * @example
 * ```typescript
 * // Inside a "UserCard" component, find what connects to Component Inputs "userId" port
 * const external = resolveComponentBoundary(
 *   project,
 *   userCardComponent,
 *   componentInputsNodeId,
 *   'userId'
 * );
 * external.forEach(conn => {
 *   console.log(`Parent connects from node ${conn.parentNodeId}`);
 * });
 * ```
 */
function resolveComponentBoundary(project, component, boundaryNodeId, portName) {
    const boundaryNode = component.graph.nodeMap.get(boundaryNodeId);
    if (!boundaryNode) {
        return [];
    }
    const connections = [];
    // Determine if this is an input or output boundary
    const isInput = boundaryNode.typename === 'Component Inputs';
    const isOutput = boundaryNode.typename === 'Component Outputs';
    if (!isInput && !isOutput) {
        return [];
    }
    // Find all instances of this component in other components
    const usages = findComponentUsages(project, component.name);
    for (const usage of usages) {
        const parentComponent = usage.usedIn;
        const instanceNode = parentComponent.graph.nodeMap.get(usage.instanceNodeId);
        if (!instanceNode)
            continue;
        if (isInput) {
            // For Component Inputs, find connections in parent that feed into this port
            const parentConnections = parentComponent.graph.connections.filter((conn) => conn.toId === usage.instanceNodeId && conn.toProperty === portName);
            for (const conn of parentConnections) {
                connections.push({
                    parentNodeId: conn.fromId,
                    parentPort: conn.fromProperty,
                    childComponent: component,
                    childBoundaryNodeId: boundaryNodeId,
                    childPort: portName
                });
            }
        }
        else if (isOutput) {
            // For Component Outputs, find connections in parent that this port feeds into
            const parentConnections = parentComponent.graph.connections.filter((conn) => conn.fromId === usage.instanceNodeId && conn.fromProperty === portName);
            for (const conn of parentConnections) {
                connections.push({
                    parentNodeId: conn.toId,
                    parentPort: conn.toProperty,
                    childComponent: component,
                    childBoundaryNodeId: boundaryNodeId,
                    childPort: portName
                });
            }
        }
    }
    return connections;
}
/**
 * Build a complete component dependency graph for the project.
 * Shows which components use which other components.
 *
 * @param project - Project to analyze
 * @returns Object with nodes (components) and edges (usage relationships)
 *
 * @example
 * ```typescript
 * const graph = buildComponentDependencyGraph(project);
 * console.log('Components:', graph.nodes.map(c => c.name));
 * graph.edges.forEach(edge => {
 *   console.log(`${edge.from} uses ${edge.to} ${edge.count} times`);
 * });
 * ```
 */
function buildComponentDependencyGraph(project) {
    const nodes = [];
    const edgeMap = new Map();
    // Collect all components as nodes
    project.forEachComponent((component) => {
        nodes.push(component);
    });
    // Build edges by finding component instances
    project.forEachComponent((component) => {
        component.graph.nodeMap.forEach((node) => {
            if (node.type instanceof ComponentModel) {
                const usedComponentName = node.type.name;
                const key = `${component.name}→${usedComponentName}`;
                if (edgeMap.has(key)) {
                    const edge = edgeMap.get(key);
                    edge.count++;
                }
                else {
                    edgeMap.set(key, {
                        from: component.name,
                        to: usedComponentName,
                        count: 1
                    });
                }
            }
        });
    });
    const edges = Array.from(edgeMap.values());
    return { nodes, edges };
}
/**
 * Check if a component is used (instantiated) anywhere in the project.
 *
 * @param project - Project to search
 * @param componentName - Name of the component to check
 * @returns True if the component is used at least once
 *
 * @example
 * ```typescript
 * if (!isComponentUsed(project, 'OldWidget')) {
 *   console.log('This component is not used and can be deleted');
 * }
 * ```
 */
function isComponentUsed(project, componentName) {
    return findComponentUsages(project, componentName).length > 0;
}
/**
 * Find all components that are not used anywhere in the project.
 * These might be candidates for cleanup.
 *
 * @param project - Project to analyze
 * @returns Array of unused component names
 *
 * @example
 * ```typescript
 * const unused = findUnusedComponents(project);
 * console.log('Unused components:', unused);
 * ```
 */
function findUnusedComponents(project) {
    const unused = [];
    project.forEachComponent((component) => {
        // Skip special components that might not be directly instantiated
        // but are used via routing (like App Shell)
        const rootComponent = project.getRootComponent();
        if (rootComponent && component.name === rootComponent.name) {
            return; // Skip root component
        }
        if (!isComponentUsed(project, component.name)) {
            unused.push(component.name);
        }
    });
    return unused;
}
/**
 * Get the depth of a component in the component hierarchy.
 * Depth 0 = root component
 * Depth 1 = components used by root
 * Depth 2 = components used by depth 1 components, etc.
 *
 * @param project - Project to analyze
 * @param componentName - Name of the component
 * @returns Depth in the hierarchy (0 for root, -1 if unused/unreachable)
 *
 * @example
 * ```typescript
 * const depth = getComponentDepth(project, 'UserCard');
 * console.log(`UserCard is at depth ${depth} in the hierarchy`);
 * ```
 */
function getComponentDepth(project, componentName) {
    const rootComponent = project.getRootComponent();
    const rootName = rootComponent === null || rootComponent === void 0 ? void 0 : rootComponent.name;
    if (!rootName || componentName === rootName) {
        return componentName === rootName ? 0 : -1;
    }
    const visited = new Set();
    const queue = [{ name: rootName, depth: 0 }];
    while (queue.length > 0) {
        const current = queue.shift();
        if (visited.has(current.name)) {
            continue;
        }
        visited.add(current.name);
        const component = project.getComponentWithName(current.name);
        if (!component)
            continue;
        // Check all nodes in this component
        component.graph.nodeMap.forEach((node) => {
            if (node.type instanceof ComponentModel) {
                const usedName = node.type.name;
                if (usedName === componentName) {
                    return current.depth + 1; // Found it!
                }
                queue.push({ name: usedName, depth: current.depth + 1 });
            }
        });
    }
    return -1; // Not reachable from root
}

;// ./src/editor/src/utils/graphAnalysis/categorization.ts
/**
 * Node categorization utilities for semantic grouping and analysis
 */
/**
 * Node type to category mapping
 * This mapping groups node types into semantic categories for analysis
 */
const NODE_TYPE_CATEGORIES = {
    // Visual nodes
    Group: 'visual',
    Text: 'visual',
    Image: 'visual',
    Video: 'visual',
    Icon: 'visual',
    Circle: 'visual',
    Rectangle: 'visual',
    'Page Stack': 'visual',
    Columns: 'visual',
    'Scroll View': 'visual',
    // Data nodes
    Variable: 'data',
    Object: 'data',
    Array: 'data',
    Number: 'data',
    String: 'data',
    Boolean: 'data',
    'Static Array': 'data',
    'Array Filter': 'data',
    'Array Map': 'data',
    // Logic nodes
    Condition: 'logic',
    Expression: 'logic',
    Switch: 'logic',
    States: 'logic',
    'Boolean To String': 'logic',
    'String Mapper': 'logic',
    'Number Remapper': 'logic',
    // Event nodes
    'Send Event': 'events',
    'Receive Event': 'events',
    'Component Inputs': 'events',
    'Component Outputs': 'events',
    'Receive Global Event': 'events',
    'Send Global Event': 'events',
    // API/Network nodes
    REST: 'api',
    'REST v2': 'api',
    'Cloud Function': 'api',
    'Cloud Function 2.0': 'api',
    Function: 'api',
    'Javascript Function': 'api',
    // Navigation nodes
    'Page Router': 'navigation',
    Navigate: 'navigation',
    'Navigate To Path': 'navigation',
    'Navigate Back': 'navigation',
    'External Link': 'navigation',
    // Animation nodes
    'Value Changed': 'animation',
    'Did Mount': 'animation',
    'Will Unmount': 'animation'
};
/**
 * Categorize all nodes in a component by semantic type.
 *
 * @param component - Component to analyze
 * @returns Categorized node information with totals
 *
 * @example
 * ```typescript
 * const categorized = categorizeNodes(component);
 * categorized.totals.forEach(({ category, count }) => {
 *   console.log(`${category}: ${count} nodes`);
 * });
 * ```
 */
function categorizeNodes(component) {
    const byCategory = new Map();
    const byType = new Map();
    // Initialize category maps
    const categories = ['visual', 'data', 'logic', 'events', 'api', 'navigation', 'animation', 'utility'];
    categories.forEach((cat) => byCategory.set(cat, []));
    // Categorize each node
    component.graph.nodeMap.forEach((node) => {
        const category = getNodeCategory(node.typename);
        // Add to category map
        const categoryNodes = byCategory.get(category) || [];
        categoryNodes.push(node);
        byCategory.set(category, categoryNodes);
        // Add to type map
        const typeNodes = byType.get(node.typename) || [];
        typeNodes.push(node);
        byType.set(node.typename, typeNodes);
    });
    // Calculate totals
    const totals = categories.map((category) => {
        var _a;
        return ({
            category,
            count: ((_a = byCategory.get(category)) === null || _a === void 0 ? void 0 : _a.length) || 0
        });
    });
    return { byCategory, byType, totals };
}
/**
 * Get the category for a specific node type.
 *
 * @param nodeType - Node type name
 * @returns Category for the node type
 *
 * @example
 * ```typescript
 * const category = getNodeCategory('Variable');
 * console.log(category); // 'data'
 * ```
 */
function getNodeCategory(nodeType) {
    return NODE_TYPE_CATEGORIES[nodeType] || 'utility';
}
/**
 * Check if a node is a visual node (has visual hierarchy).
 *
 * @param node - Node to check
 * @returns True if the node is a visual node
 *
 * @example
 * ```typescript
 * if (isVisualNode(node)) {
 *   console.log('This node can have children in the visual hierarchy');
 * }
 * ```
 */
function isVisualNode(node) {
    const category = getNodeCategory(node.typename);
    return category === 'visual';
}
/**
 * Check if a node is a data source (Variable, Object, Array, etc.).
 *
 * @param node - Node to check
 * @returns True if the node is a data source
 *
 * @example
 * ```typescript
 * if (isDataSourceNode(node)) {
 *   console.log('This node stores or provides data');
 * }
 * ```
 */
function isDataSourceNode(node) {
    const category = getNodeCategory(node.typename);
    return category === 'data';
}
/**
 * Check if a node is a logic node (Condition, Expression, etc.).
 *
 * @param node - Node to check
 * @returns True if the node performs logical operations
 *
 * @example
 * ```typescript
 * if (isLogicNode(node)) {
 *   console.log('This node performs logical operations');
 * }
 * ```
 */
function isLogicNode(node) {
    const category = getNodeCategory(node.typename);
    return category === 'logic';
}
/**
 * Check if a node is an event node (Send Event, Receive Event, etc.).
 *
 * @param node - Node to check
 * @returns True if the node handles events
 *
 * @example
 * ```typescript
 * if (isEventNode(node)) {
 *   console.log('This node handles event communication');
 * }
 * ```
 */
function isEventNode(node) {
    const category = getNodeCategory(node.typename);
    return category === 'events';
}
/**
 * Get a summary of node categories in a component.
 *
 * @param component - Component to analyze
 * @returns Array of category counts sorted by count (descending)
 *
 * @example
 * ```typescript
 * const summary = getNodeCategorySummary(component);
 * console.log('Most common category:', summary[0].category);
 * ```
 */
function getNodeCategorySummary(component) {
    const categorized = categorizeNodes(component);
    return categorized.totals.filter((t) => t.count > 0).sort((a, b) => b.count - a.count);
}
/**
 * Get a summary of node types in a component.
 *
 * @param component - Component to analyze
 * @returns Array of type counts sorted by count (descending)
 *
 * @example
 * ```typescript
 * const summary = getNodeTypeSummary(component);
 * console.log('Most common node type:', summary[0].type);
 * ```
 */
function getNodeTypeSummary(component) {
    const categorized = categorizeNodes(component);
    const summary = [];
    categorized.byType.forEach((nodes, type) => {
        summary.push({
            type,
            category: getNodeCategory(type),
            count: nodes.length
        });
    });
    return summary.sort((a, b) => b.count - a.count);
}

;// ./src/editor/src/utils/graphAnalysis/lineage.ts
/**
 * Data Lineage Analysis
 *
 * Traces the complete upstream (source) and downstream (destination) paths for data flow,
 * crossing component boundaries to provide a full picture of where values come from and where they go.
 *
 * @module graphAnalysis/lineage
 * @since 1.3.0
 */


/**
 * Build complete lineage for a node, tracing both upstream and downstream paths.
 *
 * @param project - Project containing all components
 * @param component - Component containing the starting node
 * @param nodeId - ID of the node to trace
 * @param port - Optional specific port to trace (if omitted, traces all connections)
 * @returns Complete lineage result with upstream and downstream paths
 *
 * @example
 * ```typescript
 * const lineage = buildLineage(project, component, textNodeId, 'text');
 * console.log('Source:', lineage.upstream.steps[0].node.label);
 * console.log('Destinations:', lineage.downstream.map(p => p.steps[p.steps.length - 1].node.label));
 * ```
 */
function buildLineage(project, component, nodeId, port) {
    const node = component.graph.nodeMap.get(nodeId);
    if (!node) {
        return null;
    }
    const selectedNode = {
        id: node.id,
        label: node.label || node.typename,
        type: node.typename,
        componentName: component.name,
        port
    };
    // Trace upstream (find sources)
    const upstream = traceUpstream(project, component, node, port);
    // Trace downstream (find all destinations)
    const downstream = traceDownstream(project, component, node, port);
    return {
        selectedNode,
        upstream,
        downstream
    };
}
/**
 * Trace upstream to find the source(s) of data.
 * Follows connections backwards through the graph and across component boundaries.
 */
/**
 * Primary data ports by node type - only trace these ports for focused results
 */
const PRIMARY_DATA_PORTS = {
    Variable: ['value'],
    Variable2: ['value'],
    String: ['value'],
    Number: ['value'],
    Boolean: ['value'],
    Object: ['value'],
    Array: ['value'],
    Text: ['text'],
    Image: ['src'],
    Component: [], // Skip visual components entirely for primary tracing
    Group: [] // Skip layout components
};
function traceUpstream(project, component, startNode, startPort, visited = new Set(), depth = 0) {
    const MAX_DEPTH = 5; // Limit depth to prevent noise
    const steps = [];
    const crossings = [];
    if (depth >= MAX_DEPTH) {
        return { steps, crossings };
    }
    // Create unique key for cycle detection
    const nodeKey = `${component.fullName}:${startNode.id}:${startPort || '*'}`;
    if (visited.has(nodeKey)) {
        return { steps, crossings }; // Cycle detected
    }
    visited.add(nodeKey);
    // Determine which inputs to trace
    const portsToTrace = startPort ? [startPort] : getInputPorts(startNode);
    for (const portName of portsToTrace) {
        const connections = getPortConnections(component, startNode.id, portName, 'input');
        if (connections.length === 0) {
            // No connections - skip unconnected ports unless this is a Component Input boundary
            if (startNode.typename === 'Component Inputs') {
                // Cross into parent component
                const external = resolveComponentBoundary(project, component, startNode.id, portName);
                if (external.length > 0) {
                    // Found connection in parent - continue tracing there
                    const ext = external[0]; // Take first parent connection
                    const parentComponent = project.getComponentWithName(ext.parentNodeId.split('.')[0]);
                    if (parentComponent) {
                        const parentNode = parentComponent.graph.nodeMap.get(ext.parentNodeId);
                        if (parentNode) {
                            crossings.push({
                                from: component,
                                to: parentComponent,
                                viaPort: portName,
                                direction: 'into',
                                stepIndex: steps.length
                            });
                            // Recursively trace in parent
                            const parentPath = traceUpstream(project, parentComponent, parentNode, ext.parentPort, visited, depth + 1);
                            steps.push(...parentPath.steps);
                            crossings.push(...parentPath.crossings);
                        }
                    }
                }
            }
            else {
                // True source node - no further upstream
                steps.push({
                    node: startNode,
                    component,
                    port: portName,
                    portType: 'input',
                    isSource: true
                });
            }
            continue;
        }
        // Follow connections upstream
        for (const conn of connections) {
            const sourceNode = component.graph.nodeMap.get(conn.fromNodeId);
            if (!sourceNode)
                continue;
            // Add this step
            steps.push({
                node: sourceNode,
                component,
                port: conn.fromPort,
                portType: 'output',
                transformation: describeTransformation(sourceNode, conn.fromPort),
                connection: conn
            });
            // Check if source is a source-type node
            if (isSourceNode(sourceNode)) {
                steps[steps.length - 1].isSource = true;
                continue; // Don't trace further
            }
            // Check for component boundary
            if (sourceNode.typename === 'Component Outputs') {
                // This comes from a child component
                // For now, mark as boundary - full child traversal can be added later
                steps[steps.length - 1].transformation = `From child component output: ${conn.fromPort}`;
                continue;
            }
            // Recursively trace further upstream
            const upstreamPath = traceUpstream(project, component, sourceNode, undefined, visited, depth + 1);
            steps.push(...upstreamPath.steps);
            crossings.push(...upstreamPath.crossings);
        }
    }
    return { steps, crossings };
}
/**
 * Trace downstream to find all destinations of data.
 * Follows connections forward through the graph and across component boundaries.
 */
function traceDownstream(project, component, startNode, startPort, visited = new Set(), depth = 0) {
    const MAX_DEPTH = 50;
    const paths = [];
    if (depth >= MAX_DEPTH) {
        return paths;
    }
    const nodeKey = `${component.fullName}:${startNode.id}:${startPort || '*'}`;
    if (visited.has(nodeKey)) {
        return paths;
    }
    visited.add(nodeKey);
    // Determine which outputs to trace
    const portsToTrace = startPort ? [startPort] : getOutputPorts(startNode);
    for (const portName of portsToTrace) {
        const connections = getPortConnections(component, startNode.id, portName, 'output');
        if (connections.length === 0) {
            // No connections - check if this is a component boundary
            if (startNode.typename === 'Component Outputs') {
                // Cross out to parent component
                const external = resolveComponentBoundary(project, component, startNode.id, portName);
                if (external.length > 0) {
                    const ext = external[0];
                    // Create path showing we crossed the boundary
                    paths.push({
                        steps: [
                            {
                                node: startNode,
                                component,
                                port: portName,
                                portType: 'output',
                                transformation: `Exported to parent as: ${portName}`
                            }
                        ],
                        crossings: [
                            {
                                from: component,
                                to: component, // Would need to resolve parent component here
                                viaPort: portName,
                                direction: 'outof',
                                stepIndex: 0
                            }
                        ]
                    });
                }
            }
            else {
                // True sink - no further downstream
                paths.push({
                    steps: [
                        {
                            node: startNode,
                            component,
                            port: portName,
                            portType: 'output',
                            isSink: true
                        }
                    ],
                    crossings: []
                });
            }
            continue;
        }
        // Follow each connection downstream (can branch to multiple destinations)
        for (const conn of connections) {
            const destNode = component.graph.nodeMap.get(conn.toNodeId);
            if (!destNode)
                continue;
            const pathSteps = [
                {
                    node: destNode,
                    component,
                    port: conn.toPort,
                    portType: 'input',
                    transformation: describeTransformation(destNode, conn.toPort),
                    connection: conn
                }
            ];
            // Check if destination is a sink
            if (isSinkNode(destNode)) {
                pathSteps[0].isSink = true;
                paths.push({ steps: pathSteps, crossings: [] });
                continue;
            }
            // Check for component boundary
            if (destNode.typename === 'Component Inputs') {
                // This goes into a child component
                pathSteps[0].transformation = `Into child component input: ${conn.toPort}`;
                paths.push({ steps: pathSteps, crossings: [] });
                continue;
            }
            // Recursively trace further downstream
            const downstreamPaths = traceDownstream(project, component, destNode, undefined, visited, depth + 1);
            if (downstreamPaths.length === 0) {
                // Dead end
                paths.push({ steps: pathSteps, crossings: [] });
            }
            else {
                // Merge this step with downstream paths
                for (const downPath of downstreamPaths) {
                    paths.push({
                        steps: [...pathSteps, ...downPath.steps],
                        crossings: downPath.crossings,
                        branches: downstreamPaths.length > 1
                    });
                }
            }
        }
    }
    return paths;
}
/**
 * Describe what transformation a node performs (if any)
 */
function describeTransformation(node, port) {
    switch (node.typename) {
        case 'Expression':
            return `Expression: ${node.parameters.expression || '...'}`;
        case 'String Format':
            return `Format: ${node.parameters.format || '...'}`;
        case 'Object':
            // Check if accessing a property
            if (port && port !== 'object') {
                return `.${port} property`;
            }
            return 'Object value';
        case 'Array':
            if (port === 'length')
                return 'Array length';
            if (port.startsWith('item-'))
                return `Array item [${port.substring(5)}]`;
            return undefined;
        case 'Variable':
            return `Variable: ${node.parameters.name || node.label || 'unnamed'}`;
        case 'Function':
            return `Function: ${node.parameters.name || 'unnamed'}`;
        default:
            return undefined;
    }
}
/**
 * Check if a node is a data source (no further upstream to trace)
 */
function isSourceNode(node) {
    const sourceTypes = [
        'REST',
        'Cloud Function',
        'Function',
        'String',
        'Number',
        'Boolean',
        'Color',
        'Page Inputs',
        'Receive Event'
    ];
    return sourceTypes.includes(node.typename);
}
/**
 * Check if a node is a data sink (no further downstream to trace)
 */
function isSinkNode(node) {
    const sinkTypes = [
        'REST', // Also a sink when sending
        'Cloud Function',
        'Function',
        'Send Event',
        'Navigate',
        'Set Variable',
        'Page Router'
    ];
    return sinkTypes.includes(node.typename);
}
/**
 * Ports to skip when tracing lineage (signals, metadata, internal state)
 */
const SKIP_PORTS = new Set([
    // Signal ports (events, not data)
    'changed',
    'fetched',
    'onSave',
    'onLoad',
    'onClick',
    'onHover',
    'onPress',
    'onFocus',
    'onBlur',
    // Metadata ports (not actual data flow)
    'name',
    'id',
    'savedValue',
    'isLoading',
    'error',
    // Internal state
    '__state',
    '__internal'
]);
/**
 * Check if a port should be included in lineage tracing
 */
function shouldTracePort(port) {
    // Skip signal ports
    if (port.type === 'signal') {
        return false;
    }
    // Skip known metadata/event ports
    if (SKIP_PORTS.has(port.name)) {
        return false;
    }
    // Skip ports starting with underscore (internal)
    if (port.name.startsWith('_')) {
        return false;
    }
    return true;
}
/**
 * Get all input port names for a node (filtered for data ports only)
 */
function getInputPorts(node) {
    const ports = node.getPorts('input');
    return ports.filter(shouldTracePort).map((p) => p.name);
}
/**
 * Get all output port names for a node (filtered for data ports only)
 */
function getOutputPorts(node) {
    // Check if this node type has primary data ports defined
    const primaryPorts = PRIMARY_DATA_PORTS[node.typename];
    if (primaryPorts !== undefined) {
        return primaryPorts; // Only trace primary ports for this type
    }
    // Default: trace all filtered ports
    const ports = node.getPorts('output');
    return ports.filter(shouldTracePort).map((p) => p.name);
}

;// ./src/editor/src/utils/graphAnalysis/index.ts
/**
 * Graph Analysis Utilities
 *
 * This module provides utilities for analyzing node graphs, tracing connections,
 * resolving cross-component relationships, and detecting potential issues.
 *
 * @module graphAnalysis
 * @since 1.3.0
 */
// Export traversal utilities

// Export cross-component utilities

// Export categorization utilities

// Export duplicate detection utilities

// Export lineage analysis utilities


;// ./src/editor/src/views/panels/ComponentXRayPanel/hooks/useComponentXRay.ts
/**
 * useComponentXRay Hook
 *
 * Collects comprehensive X-Ray data for a component, including:
 * - Where it's used
 * - Component interface (inputs/outputs)
 * - Internal structure (subcomponents, node breakdown)
 * - External dependencies (REST, Events, Functions)
 * - Internal state (Variables, Objects, States)
 */






/**
 * Extract component inputs from Component Inputs nodes
 */
function extractComponentInputs(component) {
    var _a, _b;
    const inputNodes = findNodesOfType(component, 'Component Inputs');
    const inputs = [];
    for (const node of inputNodes) {
        // Get all ports defined on this node
        const ports = node.getPorts();
        for (const port of ports) {
            if (port.plug === 'output') {
                // Component Inputs node has outputs that represent component inputs
                inputs.push({
                    name: port.name,
                    type: ((_a = port.type) === null || _a === void 0 ? void 0 : _a.name) || port.type || 'any',
                    isSignal: port.type === 'signal' || ((_b = port.type) === null || _b === void 0 ? void 0 : _b.name) === 'signal'
                });
            }
        }
    }
    return inputs;
}
/**
 * Extract component outputs from Component Outputs nodes
 */
function extractComponentOutputs(component) {
    var _a, _b;
    const outputNodes = findNodesOfType(component, 'Component Outputs');
    const outputs = [];
    for (const node of outputNodes) {
        // Get all ports defined on this node
        const ports = node.getPorts();
        for (const port of ports) {
            if (port.plug === 'input') {
                // Component Outputs node has inputs that represent component outputs
                outputs.push({
                    name: port.name,
                    type: ((_a = port.type) === null || _a === void 0 ? void 0 : _a.name) || port.type || 'any',
                    isSignal: port.type === 'signal' || ((_b = port.type) === null || _b === void 0 ? void 0 : _b.name) === 'signal'
                });
            }
        }
    }
    return outputs;
}
/**
 * Extract subcomponent instances used within this component
 */
function extractSubcomponents(component) {
    const subcomponents = [];
    const seen = new Set();
    // Find all nodes that are component instances
    component.graph.forEachNode((node) => {
        if (node.type instanceof componentmodel/* ComponentModel */.j) {
            const key = `${node.type.fullName}-${node.id}`;
            if (!seen.has(key)) {
                seen.add(key);
                subcomponents.push({
                    name: node.type.name,
                    fullName: node.type.fullName,
                    component: node.type,
                    nodeId: node.id
                });
            }
        }
    });
    return subcomponents;
}
/**
 * Extract REST call information from REST nodes
 */
function extractRESTCalls(component) {
    const restNodes = findNodesOfType(component, 'REST');
    const rest2Nodes = findNodesOfType(component, 'REST2');
    const allRestNodes = [...restNodes, ...rest2Nodes];
    return allRestNodes.map((node) => ({
        method: node.parameters.method || 'GET',
        endpoint: node.parameters.url || node.parameters.endpoint || 'No endpoint',
        nodeId: node.id,
        nodeLabel: node.label || 'REST Call'
    }));
}
/**
 * Extract sent event information from Send Event nodes
 */
function extractSentEvents(component) {
    const sendEventNodes = findNodesOfType(component, 'Send Event');
    return sendEventNodes.map((node) => ({
        eventName: node.parameters.eventName || node.parameters.channel || 'Unnamed Event',
        nodeId: node.id,
        nodeLabel: node.label || 'Send Event'
    }));
}
/**
 * Extract received event information from Receive Event nodes
 */
function extractReceivedEvents(component) {
    const receiveEventNodes = findNodesOfType(component, 'Receive Event');
    return receiveEventNodes.map((node) => ({
        eventName: node.parameters.eventName || node.parameters.channel || 'Unnamed Event',
        nodeId: node.id,
        nodeLabel: node.label || 'Receive Event'
    }));
}
/**
 * Extract function information from JavaScriptFunction nodes
 */
function extractFunctions(component) {
    const functionNodes = findNodesOfType(component, 'JavaScriptFunction');
    return functionNodes.map((node) => ({
        name: node.parameters.name || node.typename,
        nodeId: node.id,
        nodeLabel: node.label || 'JavaScript Function'
    }));
}
/**
 * Extract internal state nodes (Variables, Objects, States)
 */
function extractStateNodes(component) {
    // Support both Variable and Variable2 (newer version)
    const variableNodes = findNodesOfType(component, 'Variable');
    const variable2Nodes = findNodesOfType(component, 'Variable2');
    const objectNodes = findNodesOfType(component, 'Object');
    const statesNodes = findNodesOfType(component, 'States');
    const stateNodes = [];
    for (const node of variableNodes) {
        stateNodes.push({
            name: node.label || 'Unnamed Variable',
            nodeId: node.id,
            nodeType: 'Variable'
        });
    }
    for (const node of variable2Nodes) {
        stateNodes.push({
            name: node.label || 'Unnamed Variable',
            nodeId: node.id,
            nodeType: 'Variable'
        });
    }
    for (const node of objectNodes) {
        stateNodes.push({
            name: node.label || 'Unnamed Object',
            nodeId: node.id,
            nodeType: 'Object'
        });
    }
    for (const node of statesNodes) {
        stateNodes.push({
            name: node.label || 'States',
            nodeId: node.id,
            nodeType: 'States'
        });
    }
    return stateNodes;
}
/**
 * Extract node breakdown by category
 */
function extractNodeBreakdown(component) {
    const categorized = categorizeNodes(component);
    // Map totals to include node IDs for highlighting
    return categorized.totals.map((total) => {
        const nodes = categorized.byCategory.get(total.category) || [];
        const nodeIds = nodes.map((node) => node.id);
        return {
            category: total.category,
            count: total.count,
            nodeIds
        };
    });
}
/**
 * Extract component usage information from the project
 */
function extractUsageInfo(project, componentFullName) {
    const usages = findComponentUsages(project, componentFullName);
    return usages.map((usage) => ({
        component: usage.usedIn,
        instanceCount: 1, // Each usage represents one instance
        instanceNodeIds: [usage.instanceNodeId]
    }));
}
/**
 * Hook that builds and returns complete X-Ray data for the currently active component.
 *
 * Automatically updates when:
 * - The active component changes
 * - Components are added or removed from the project
 * - Nodes are added or removed from the current component
 *
 * @returns Complete X-Ray data for the current component, or null if no component is active
 *
 * @example
 * ```tsx
 * function MyPanel() {
 *   const xrayData = useComponentXRay();
 *
 *   if (!xrayData) {
 *     return <div>No component selected</div>;
 *   }
 *
 *   return (
 *     <div>
 *       <h2>{xrayData.componentName}</h2>
 *       <p>Total nodes: {xrayData.totalNodes}</p>
 *       <p>Used in {xrayData.usedIn.length} places</p>
 *     </div>
 *   );
 * }
 * ```
 */
function useComponentXRay() {
    var _a;
    const project = projectmodel.ProjectModel.instance;
    const [updateTrigger, setUpdateTrigger] = (0,external_react_.useState)(0);
    // Get current component from NodeGraphContext
    const currentComponent = ((_a = NodeGraphContext.NodeGraphContextTmp.nodeGraph) === null || _a === void 0 ? void 0 : _a.activeComponent) || null;
    // Trigger rebuild when components change
    (0,useEventListener/* useEventListener */.M)(projectmodel.ProjectModel.instance, 'componentAdded', () => {
        setUpdateTrigger((prev) => prev + 1);
    });
    (0,useEventListener/* useEventListener */.M)(projectmodel.ProjectModel.instance, 'componentRemoved', () => {
        setUpdateTrigger((prev) => prev + 1);
    });
    // Trigger rebuild when active component switches
    (0,useEventListener/* useEventListener */.M)(NodeGraphContext.NodeGraphContextTmp.nodeGraph, 'activeComponentChanged', () => {
        setUpdateTrigger((prev) => prev + 1);
    });
    // Trigger rebuild when nodes change in the current component
    // IMPORTANT: Listen to the component's graph, not the NodeGraphContextTmp singleton
    (0,useEventListener/* useEventListener */.M)(currentComponent === null || currentComponent === void 0 ? void 0 : currentComponent.graph, 'nodeAdded', () => {
        setUpdateTrigger((prev) => prev + 1);
    });
    (0,useEventListener/* useEventListener */.M)(currentComponent === null || currentComponent === void 0 ? void 0 : currentComponent.graph, 'nodeRemoved', () => {
        setUpdateTrigger((prev) => prev + 1);
    });
    const xrayData = (0,external_react_.useMemo)(() => {
        if (!currentComponent) {
            return null;
        }
        // Build complete X-Ray data
        const data = {
            // Identity
            componentName: currentComponent.name,
            componentFullName: currentComponent.fullName,
            // Usage
            usedIn: extractUsageInfo(project, currentComponent.fullName),
            // Interface
            inputs: extractComponentInputs(currentComponent),
            outputs: extractComponentOutputs(currentComponent),
            // Contents
            subcomponents: extractSubcomponents(currentComponent),
            nodeBreakdown: extractNodeBreakdown(currentComponent),
            totalNodes: extractNodeBreakdown(currentComponent).reduce((sum, cat) => sum + cat.count, 0),
            // External dependencies
            restCalls: extractRESTCalls(currentComponent),
            eventsSent: extractSentEvents(currentComponent),
            eventsReceived: extractReceivedEvents(currentComponent),
            functions: extractFunctions(currentComponent),
            // Internal state
            stateNodes: extractStateNodes(currentComponent)
        };
        return data;
    }, [currentComponent, project, updateTrigger]);
    return xrayData;
}

;// ./src/editor/src/views/panels/ComponentXRayPanel/ComponentXRayPanel.tsx
/**
 * Component X-Ray Panel
 *
 * Shows comprehensive information about the currently active component:
 * - Usage locations
 * - Component interface (inputs/outputs)
 * - Internal structure
 * - External dependencies
 * - Internal state
 */






function ComponentXRayPanel() {
    var _a;
    const xrayData = useComponentXRay();
    // Collapsible section state
    const [collapsed, setCollapsed] = (0,external_react_.useState)({
        usedIn: false,
        interface: false,
        contains: false,
        dependencies: false,
        state: false
    });
    // Selected category for highlighting
    const [selectedCategory, setSelectedCategory] = (0,external_react_.useState)(null);
    const toggleSection = (0,external_react_.useCallback)((section) => {
        setCollapsed((prev) => ({ ...prev, [section]: !prev[section] }));
    }, []);
    // Get the current component for node selection
    const currentComponent = (_a = NodeGraphContext.NodeGraphContextTmp.nodeGraph) === null || _a === void 0 ? void 0 : _a.activeComponent;
    // Navigation: Switch to a component and optionally select a node
    const navigateToComponent = (0,external_react_.useCallback)((component, nodeToSelect) => {
        NodeGraphContext.NodeGraphContextTmp.switchToComponent(component, {
            node: nodeToSelect,
            pushHistory: true
        });
    }, []);
    // Node selection: Select a node in the current component by finding it
    const selectNodeById = (0,external_react_.useCallback)((nodeId) => {
        if (currentComponent === null || currentComponent === void 0 ? void 0 : currentComponent.graph) {
            const node = currentComponent.graph.findNodeWithId(nodeId);
            if (node) {
                NodeGraphContext.NodeGraphContextTmp.switchToComponent(currentComponent, {
                    node: node,
                    pushHistory: false
                });
            }
        }
    }, [currentComponent]);
    // Highlight nodes: Highlight multiple nodes in a category with toggle
    const highlightCategory = (0,external_react_.useCallback)((category, nodeIds) => {
        if (nodeIds.length === 0)
            return;
        if (selectedCategory === category) {
            // Clicking same category - toggle OFF
            HighlightManager/* HighlightManager */.Ym.instance.clearChannel('selection');
            setSelectedCategory(null);
        }
        else {
            // New category - switch highlights
            HighlightManager/* HighlightManager */.Ym.instance.clearChannel('selection');
            HighlightManager/* HighlightManager */.Ym.instance.highlightNodes(nodeIds, {
                channel: 'selection',
                label: `${category} nodes`,
                persistent: false
            });
            setSelectedCategory(category);
        }
    }, [selectedCategory]);
    if (!xrayData) {
        return (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['ComponentXRayPanel'] },
            external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['EmptyState'] },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Search }),
                external_react_default().createElement("h3", null, "No Component Selected"),
                external_react_default().createElement("p", null, "Select a component to view its X-Ray analysis"))));
    }
    return (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['ComponentXRayPanel'] },
        external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Header'] },
            external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Title'] },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Search }),
                external_react_default().createElement("h2", null, "Component X-Ray")),
            external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['ComponentName'] },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Component }),
                external_react_default().createElement("span", null, xrayData.componentFullName))),
        external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Content'] },
            external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['SummaryStats'] },
                external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Stat'] },
                    external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['StatLabel'] }, "Total Nodes"),
                    external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['StatValue'] }, xrayData.totalNodes)),
                external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Stat'] },
                    external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['StatLabel'] }, "Used In"),
                    external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['StatValue'] },
                        xrayData.usedIn.length,
                        " places")),
                external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Stat'] },
                    external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['StatLabel'] }, "Inputs"),
                    external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['StatValue'] }, xrayData.inputs.length)),
                external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Stat'] },
                    external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['StatLabel'] }, "Outputs"),
                    external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['StatValue'] }, xrayData.outputs.length))),
            xrayData.usedIn.length > 0 && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Section'] },
                external_react_default().createElement("h3", { className: ComponentXRayPanel_ComponentXRayPanel_module['SectionTitle'], onClick: () => toggleSection('usedIn') },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: collapsed.usedIn ? common_Icon/* IconName */.$M.CaretRight : common_Icon/* IconName */.$M.CaretDown }),
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Navigate }),
                    "Used In (",
                    xrayData.usedIn.length,
                    ")"),
                !collapsed.usedIn && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['SectionContent'] }, xrayData.usedIn.map((usage, idx) => {
                    // Find the node instance in the parent component
                    const instanceNode = usage.component.graph.findNodeWithId(usage.instanceNodeIds[0]);
                    return (external_react_default().createElement("div", { key: idx, className: ComponentXRayPanel_ComponentXRayPanel_module['UsageItem'], onClick: () => navigateToComponent(usage.component, instanceNode) },
                        external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Component }),
                        external_react_default().createElement("span", null, usage.component.fullName)));
                }))))),
            (xrayData.inputs.length > 0 || xrayData.outputs.length > 0) && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Section'] },
                external_react_default().createElement("h3", { className: ComponentXRayPanel_ComponentXRayPanel_module['SectionTitle'], onClick: () => toggleSection('interface') },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: collapsed.interface ? common_Icon/* IconName */.$M.CaretRight : common_Icon/* IconName */.$M.CaretDown }),
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Setting }),
                    "Interface"),
                !collapsed.interface && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['InterfaceGrid'] },
                    external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['InterfaceColumn'] },
                        external_react_default().createElement("h4", null,
                            "Inputs (",
                            xrayData.inputs.length,
                            ")"),
                        xrayData.inputs.map((input, idx) => (external_react_default().createElement("div", { key: idx, className: ComponentXRayPanel_ComponentXRayPanel_module['PortItem'] },
                            external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['PortName'] }, input.name),
                            external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['PortType'] }, input.type))))),
                    external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['InterfaceColumn'] },
                        external_react_default().createElement("h4", null,
                            "Outputs (",
                            xrayData.outputs.length,
                            ")"),
                        xrayData.outputs.map((output, idx) => (external_react_default().createElement("div", { key: idx, className: ComponentXRayPanel_ComponentXRayPanel_module['PortItem'] },
                            external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['PortName'] }, output.name),
                            external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['PortType'] }, output.type))))))))),
            xrayData.inputs.length === 0 && xrayData.outputs.length === 0 && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Section'] },
                external_react_default().createElement("h3", { className: ComponentXRayPanel_ComponentXRayPanel_module['SectionTitle'], onClick: () => toggleSection('interface') },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: collapsed.interface ? common_Icon/* IconName */.$M.CaretRight : common_Icon/* IconName */.$M.CaretDown }),
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Setting }),
                    "Interface"),
                !collapsed.interface && external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['NoData'] }, "This component has no defined interface"))),
            external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Section'] },
                external_react_default().createElement("h3", { className: ComponentXRayPanel_ComponentXRayPanel_module['SectionTitle'], onClick: () => toggleSection('contains') },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: collapsed.contains ? common_Icon/* IconName */.$M.CaretRight : common_Icon/* IconName */.$M.CaretDown }),
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Component }),
                    "Contains"),
                !collapsed.contains && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['SectionContent'] },
                    xrayData.subcomponents.length > 0 && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Subsection'] },
                        external_react_default().createElement("h4", null,
                            "Subcomponents (",
                            xrayData.subcomponents.length,
                            ")"),
                        xrayData.subcomponents.map((sub, idx) => (external_react_default().createElement("div", { key: idx, className: ComponentXRayPanel_ComponentXRayPanel_module['SubcomponentItem'], onClick: () => navigateToComponent(sub.component) },
                            external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Component }),
                            external_react_default().createElement("span", null, sub.fullName)))))),
                    xrayData.nodeBreakdown.length > 0 && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Subsection'] },
                        external_react_default().createElement("h4", null, "Node Breakdown"),
                        xrayData.nodeBreakdown.map((breakdown, idx) => (external_react_default().createElement("div", { key: idx, className: `${ComponentXRayPanel_ComponentXRayPanel_module['BreakdownItem']} ${selectedCategory === breakdown.category ? ComponentXRayPanel_ComponentXRayPanel_module['active'] : ''}`, onClick: () => highlightCategory(breakdown.category, breakdown.nodeIds) },
                            external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['CategoryName'] }, breakdown.category),
                            external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['CategoryCount'] }, breakdown.count))))))))),
            (xrayData.restCalls.length > 0 ||
                xrayData.eventsSent.length > 0 ||
                xrayData.eventsReceived.length > 0 ||
                xrayData.functions.length > 0) && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Section'] },
                external_react_default().createElement("h3", { className: ComponentXRayPanel_ComponentXRayPanel_module['SectionTitle'], onClick: () => toggleSection('dependencies') },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: collapsed.dependencies ? common_Icon/* IconName */.$M.CaretRight : common_Icon/* IconName */.$M.CaretDown }),
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CloudData }),
                    "External Dependencies"),
                !collapsed.dependencies && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['SectionContent'] },
                    xrayData.restCalls.length > 0 && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Subsection'] },
                        external_react_default().createElement("h4", null,
                            "REST Calls (",
                            xrayData.restCalls.length,
                            ")"),
                        xrayData.restCalls.map((rest, idx) => (external_react_default().createElement("div", { key: idx, className: ComponentXRayPanel_ComponentXRayPanel_module['DependencyItem'], onClick: () => selectNodeById(rest.nodeId) },
                            external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['Method'] }, rest.method),
                            external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['Endpoint'] }, rest.endpoint)))))),
                    xrayData.eventsSent.length > 0 && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Subsection'] },
                        external_react_default().createElement("h4", null,
                            "Events Sent (",
                            xrayData.eventsSent.length,
                            ")"),
                        xrayData.eventsSent.map((event, idx) => (external_react_default().createElement("div", { key: idx, className: ComponentXRayPanel_ComponentXRayPanel_module['EventItem'], onClick: () => selectNodeById(event.nodeId) },
                            external_react_default().createElement("span", null, event.eventName)))))),
                    xrayData.eventsReceived.length > 0 && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Subsection'] },
                        external_react_default().createElement("h4", null,
                            "Events Received (",
                            xrayData.eventsReceived.length,
                            ")"),
                        xrayData.eventsReceived.map((event, idx) => (external_react_default().createElement("div", { key: idx, className: ComponentXRayPanel_ComponentXRayPanel_module['EventItem'], onClick: () => selectNodeById(event.nodeId) },
                            external_react_default().createElement("span", null, event.eventName)))))),
                    xrayData.functions.length > 0 && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Subsection'] },
                        external_react_default().createElement("h4", null,
                            "Functions (",
                            xrayData.functions.length,
                            ")"),
                        xrayData.functions.map((func, idx) => (external_react_default().createElement("div", { key: idx, className: ComponentXRayPanel_ComponentXRayPanel_module['FunctionItem'], onClick: () => selectNodeById(func.nodeId) },
                            external_react_default().createElement("span", null, func.nodeLabel)))))))))),
            xrayData.stateNodes.length > 0 && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['Section'] },
                external_react_default().createElement("h3", { className: ComponentXRayPanel_ComponentXRayPanel_module['SectionTitle'], onClick: () => toggleSection('state') },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: collapsed.state ? common_Icon/* IconName */.$M.CaretRight : common_Icon/* IconName */.$M.CaretDown }),
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CloudData }),
                    "Internal State (",
                    xrayData.stateNodes.length,
                    ")"),
                !collapsed.state && (external_react_default().createElement("div", { className: ComponentXRayPanel_ComponentXRayPanel_module['SectionContent'] }, xrayData.stateNodes.map((state, idx) => (external_react_default().createElement("div", { key: idx, className: ComponentXRayPanel_ComponentXRayPanel_module['StateItem'], onClick: () => selectNodeById(state.nodeId) },
                    external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['StateType'] }, state.nodeType),
                    external_react_default().createElement("span", { className: ComponentXRayPanel_ComponentXRayPanel_module['StateName'] }, state.name)))))))))));
}

;// ./src/editor/src/views/panels/ComponentXRayPanel/index.ts
/**
 * Component X-Ray Panel
 *
 * Exports the Component X-Ray panel for sidebar registration
 */


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/DataLineagePanel/components/LineagePath.module.scss
var LineagePath_module = __webpack_require__(78879);
;// ./src/editor/src/views/panels/DataLineagePanel/components/LineagePath.module.scss

      
      
      
      
      
      
      
      
      

var LineagePath_module_options = {};

LineagePath_module_options.styleTagTransform = (styleTagTransform_default());
LineagePath_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      LineagePath_module_options.insert = insertBySelector_default().bind(null, "head");
    
LineagePath_module_options.domAPI = (styleDomAPI_default());
LineagePath_module_options.insertStyleElement = (insertStyleElement_default());

var LineagePath_module_update = injectStylesIntoStyleTag_default()(LineagePath_module/* default */.A, LineagePath_module_options);




       /* harmony default export */ const components_LineagePath_module = (LineagePath_module/* default */.A && LineagePath_module/* default */.A.locals ? LineagePath_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/DataLineagePanel/components/LineagePath.tsx
/**
 * LineagePath Component
 * Displays a single lineage path (upstream or downstream)
 */


function LineagePath({ path, direction, onNavigateToNode }) {
    if (!path || path.steps.length === 0) {
        return null;
    }
    return (external_react_default().createElement("div", { className: components_LineagePath_module['LineagePath'], "data-direction": direction },
        path.steps.map((step, index) => (external_react_default().createElement("div", { key: `${step.node.id}-${index}`, className: components_LineagePath_module['Step'] },
            external_react_default().createElement("div", { className: components_LineagePath_module['Step-node'], onClick: () => onNavigateToNode(step.component.name, step.node.id), title: `Click to navigate to ${step.node.label || step.node.typename}` },
                external_react_default().createElement("span", { className: components_LineagePath_module['Step-icon'] }, "\uD83D\uDD35"),
                external_react_default().createElement("span", { className: components_LineagePath_module['Step-label'] }, step.node.label || step.node.typename),
                step.port && external_react_default().createElement("span", { className: components_LineagePath_module['Step-port'] },
                    "\u2192 ",
                    step.port)),
            step.transformation && external_react_default().createElement("div", { className: components_LineagePath_module['Step-transformation'] }, step.transformation),
            step.isSource && external_react_default().createElement("div", { className: components_LineagePath_module['Step-badge'] }, "SOURCE"),
            step.isSink && external_react_default().createElement("div", { className: components_LineagePath_module['Step-badge'] }, "SINK"),
            index < path.steps.length - 1 && external_react_default().createElement("div", { className: components_LineagePath_module['Step-arrow'] }, "\u2193")))),
        path.crossings && path.crossings.length > 0 && (external_react_default().createElement("div", { className: components_LineagePath_module['Crossings'] },
            external_react_default().createElement("div", { className: components_LineagePath_module['Crossings-label'] },
                "Component boundaries crossed: ",
                path.crossings.length)))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/DataLineagePanel/components/PathSummary.module.scss
var PathSummary_module = __webpack_require__(79210);
;// ./src/editor/src/views/panels/DataLineagePanel/components/PathSummary.module.scss

      
      
      
      
      
      
      
      
      

var PathSummary_module_options = {};

PathSummary_module_options.styleTagTransform = (styleTagTransform_default());
PathSummary_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      PathSummary_module_options.insert = insertBySelector_default().bind(null, "head");
    
PathSummary_module_options.domAPI = (styleDomAPI_default());
PathSummary_module_options.insertStyleElement = (insertStyleElement_default());

var PathSummary_module_update = injectStylesIntoStyleTag_default()(PathSummary_module/* default */.A, PathSummary_module_options);




       /* harmony default export */ const components_PathSummary_module = (PathSummary_module/* default */.A && PathSummary_module/* default */.A.locals ? PathSummary_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/DataLineagePanel/components/PathSummary.tsx
/**
 * PathSummary Component
 * Shows a compact summary of the lineage path
 */


function PathSummary({ upstream, downstream, selectedNodeLabel }) {
    // Build compact path summary
    const upstreamSummary = upstream.steps.map((s) => s.node.label || s.node.typename).join(' → ');
    const downstreamSummaries = downstream.map((path) => path.steps.map((s) => s.node.label || s.node.typename).join(' → '));
    const hasUpstream = upstream.steps.length > 0;
    const hasDownstream = downstream.length > 0 && downstream.some((p) => p.steps.length > 0);
    if (!hasUpstream && !hasDownstream) {
        return null;
    }
    return (external_react_default().createElement("div", { className: components_PathSummary_module['PathSummary'] },
        external_react_default().createElement("div", { className: components_PathSummary_module['PathSummary-title'] }, "Path Summary"),
        external_react_default().createElement("div", { className: components_PathSummary_module['PathSummary-content'] },
            hasUpstream && (external_react_default().createElement("div", { className: components_PathSummary_module['Path'] },
                external_react_default().createElement("span", { className: components_PathSummary_module['Path-segment'] }, upstreamSummary),
                external_react_default().createElement("span", { className: components_PathSummary_module['Path-arrow'] }, "\u2192"))),
            external_react_default().createElement("div", { className: components_PathSummary_module['Path-selected'] },
                external_react_default().createElement("strong", null, selectedNodeLabel)),
            hasDownstream && (external_react_default().createElement((external_react_default()).Fragment, null, downstreamSummaries.map((summary, index) => (external_react_default().createElement("div", { key: index, className: components_PathSummary_module['Path'] },
                external_react_default().createElement("span", { className: components_PathSummary_module['Path-arrow'] }, "\u2192"),
                external_react_default().createElement("span", { className: components_PathSummary_module['Path-segment'] }, summary),
                downstream.length > 1 && external_react_default().createElement("span", { className: components_PathSummary_module['Path-branch'] },
                    "Branch ",
                    index + 1)))))))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/DataLineagePanel/DataLineagePanel.module.scss
var DataLineagePanel_module = __webpack_require__(10651);
;// ./src/editor/src/views/panels/DataLineagePanel/DataLineagePanel.module.scss

      
      
      
      
      
      
      
      
      

var DataLineagePanel_module_options = {};

DataLineagePanel_module_options.styleTagTransform = (styleTagTransform_default());
DataLineagePanel_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      DataLineagePanel_module_options.insert = insertBySelector_default().bind(null, "head");
    
DataLineagePanel_module_options.domAPI = (styleDomAPI_default());
DataLineagePanel_module_options.insertStyleElement = (insertStyleElement_default());

var DataLineagePanel_module_update = injectStylesIntoStyleTag_default()(DataLineagePanel_module/* default */.A, DataLineagePanel_module_options);




       /* harmony default export */ const DataLineagePanel_DataLineagePanel_module = (DataLineagePanel_module/* default */.A && DataLineagePanel_module/* default */.A.locals ? DataLineagePanel_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/DataLineagePanel/hooks/useDataLineage.ts
/**
 * Hook for calculating data lineage for a selected node
 */






/**
 * Custom hook to calculate and return lineage data for a selected node
 *
 * @param selectedNodeId - ID of the node to trace (optional - if not provided, uses canvas selection)
 * @param selectedPort - Specific port to trace (optional)
 * @returns Lineage result or null if no node selected
 */
function useDataLineage(selectedNodeId, selectedPort) {
    const [lineage, setLineage] = (0,external_react_.useState)(null);
    const [currentSelectedNodeId, setCurrentSelectedNodeId] = (0,external_react_.useState)(selectedNodeId);
    console.log('🔗 [DataLineage] Hook render - currentSelectedNodeId:', currentSelectedNodeId, 'selectedNodeId prop:', selectedNodeId);
    // Check current selection on mount (catches selection that happened before panel opened)
    (0,external_react_.useEffect)(() => {
        var _a, _b;
        console.log('🔗 [DataLineage] Mount check useEffect running');
        // Only if we're not using a fixed selectedNodeId prop
        if (!selectedNodeId) {
            console.log('🔗 [DataLineage] No prop provided, checking graph selection...');
            console.log('🔗 [DataLineage] NodeGraphContextTmp.nodeGraph:', NodeGraphContext.NodeGraphContextTmp.nodeGraph);
            const selection = (_b = (_a = NodeGraphContext.NodeGraphContextTmp.nodeGraph) === null || _a === void 0 ? void 0 : _a.getSelectedNodes) === null || _b === void 0 ? void 0 : _b.call(_a);
            console.log('🔗 [DataLineage] getSelectedNodes() returned:', selection);
            if (selection && selection.length === 1) {
                console.log('🔗 [DataLineage] ✅ Setting currentSelectedNodeId to:', selection[0].id);
                setCurrentSelectedNodeId(selection[0].id);
            }
            else {
                console.log('🔗 [DataLineage] ❌ No valid single selection on mount');
            }
        }
        else {
            console.log('🔗 [DataLineage] Using prop selectedNodeId:', selectedNodeId);
        }
    }, []); // Empty deps = run once on mount
    // Listen to context menu "Show Data Lineage" requests
    (0,useEventListener/* useEventListener */.M)(EventDispatcher.EventDispatcher.instance, 'DataLineage.ShowForNode', (data) => {
        console.log('📍 [DataLineage] Context menu event - Show lineage for node:', data.nodeId);
        setCurrentSelectedNodeId(data.nodeId);
    }, []);
    // Listen to selection changes on the canvas
    (0,useEventListener/* useEventListener */.M)(NodeGraphContext.NodeGraphContextTmp.nodeGraph, 'selectionChanged', (selection) => {
        console.log('🔗 [DataLineage] selectionChanged event fired:', selection);
        // Only update if we're not using a fixed selectedNodeId prop
        if (!selectedNodeId) {
            if (selection.nodeIds.length === 1) {
                console.log('🔗 [DataLineage] ✅ Event: Setting selection to:', selection.nodeIds[0]);
                setCurrentSelectedNodeId(selection.nodeIds[0]);
            }
            else {
                console.log('🔗 [DataLineage] ❌ Event: Clearing selection (count:', selection.nodeIds.length, ')');
                setCurrentSelectedNodeId(undefined);
            }
        }
        else {
            console.log('🔗 [DataLineage] Event: Ignoring (using prop)');
        }
    }, [selectedNodeId]);
    // Recalculate lineage when selection or component changes
    (0,external_react_.useEffect)(() => {
        var _a;
        console.log('🔗 [DataLineage] Lineage calc useEffect running');
        const component = (_a = NodeGraphContext.NodeGraphContextTmp.nodeGraph) === null || _a === void 0 ? void 0 : _a.activeComponent;
        console.log('🔗 [DataLineage] Active component:', component === null || component === void 0 ? void 0 : component.name);
        if (!component) {
            console.log('🔗 [DataLineage] ❌ No active component');
            setLineage(null);
            return;
        }
        // Use either the prop or the current selection
        const nodeId = selectedNodeId || currentSelectedNodeId;
        console.log('🔗 [DataLineage] Node ID to trace:', nodeId);
        if (!nodeId) {
            console.log('🔗 [DataLineage] ❌ No node ID to trace');
            setLineage(null);
            return;
        }
        // Calculate lineage
        try {
            console.log('🔗 [DataLineage] 🚀 Calling buildLineage...');
            const result = buildLineage(projectmodel.ProjectModel.instance, component, nodeId, selectedPort);
            console.log('🔗 [DataLineage] ✅ Lineage built successfully:', result);
            setLineage(result);
        }
        catch (error) {
            console.error('🔗 [DataLineage] ❌ Error building lineage:', error);
            setLineage(null);
        }
    }, [selectedNodeId, currentSelectedNodeId, selectedPort]);
    return lineage;
}

;// ./src/editor/src/views/panels/DataLineagePanel/DataLineagePanel.tsx
/**
 * Data Lineage Panel
 *
 * Shows the complete upstream (source) and downstream (destination) paths for data flow
 * through the node graph, including cross-component traversal.
 */








/**
 * DataLineagePanel component
 *
 * Displays data lineage information for a selected node, showing where
 * data comes from (upstream) and where it goes to (downstream).
 *
 * @example
 * ```tsx
 * <DataLineagePanel selectedNodeId="node-123" />
 * ```
 */
function DataLineagePanel({ selectedNodeId, selectedPort }) {
    const [activeHighlightHandle, setActiveHighlightHandle] = (0,external_react_.useState)(null);
    const [lineageData, setLineageData] = (0,external_react_.useState)(null);
    const [isUpstreamExpanded, setIsUpstreamExpanded] = (0,external_react_.useState)(true);
    const [isDownstreamExpanded, setIsDownstreamExpanded] = (0,external_react_.useState)(true);
    // Get lineage data using custom hook
    const lineage = useDataLineage(selectedNodeId, selectedPort);
    // Update lineage data when it changes
    (0,external_react_.useEffect)(() => {
        setLineageData(lineage);
    }, [lineage]);
    // Cleanup highlights on unmount
    (0,external_react_.useEffect)(() => {
        return () => {
            if (activeHighlightHandle) {
                activeHighlightHandle.dismiss();
            }
        };
    }, [activeHighlightHandle]);
    /**
     * Highlight the full lineage path on the canvas
     */
    const handleHighlightPath = () => {
        if (!lineageData)
            return;
        // Dismiss any existing highlight
        if (activeHighlightHandle) {
            activeHighlightHandle.dismiss();
        }
        // Collect all nodes in the lineage
        const nodeIds = new Set();
        const connections = [];
        // Add upstream nodes
        lineageData.upstream.steps.forEach((step) => {
            nodeIds.add(step.node.id);
            if (step.connection) {
                connections.push(step.connection);
            }
        });
        // Add downstream nodes
        lineageData.downstream.forEach((path) => {
            path.steps.forEach((step) => {
                nodeIds.add(step.node.id);
                if (step.connection) {
                    connections.push(step.connection);
                }
            });
        });
        // Add the selected node itself
        nodeIds.add(lineageData.selectedNode.id);
        // Create highlight
        const handle = HighlightManager/* HighlightManager */.Ym.instance.highlightPath({
            nodes: Array.from(nodeIds),
            connections,
            crossesComponents: lineageData.upstream.crossings.length > 0
        }, {
            channel: 'lineage',
            style: 'glow',
            persistent: true,
            label: `Lineage: ${lineageData.selectedNode.label}`
        });
        setActiveHighlightHandle(handle);
    };
    /**
     * Dismiss the lineage highlight
     */
    const handleDismiss = () => {
        if (activeHighlightHandle) {
            activeHighlightHandle.dismiss();
            setActiveHighlightHandle(null);
        }
        setLineageData(null);
    };
    /**
     * Navigate to a specific node on the canvas
     */
    const handleNavigateToNode = (componentName, _nodeId) => {
        // Switch to the component if needed
        const component = projectmodel.ProjectModel.instance.getComponentWithName(componentName);
        if (component && NodeGraphContext.NodeGraphContextTmp.switchToComponent) {
            NodeGraphContext.NodeGraphContextTmp.switchToComponent(component, { pushHistory: true });
        }
        // The canvas will auto-center on the node due to selection
        // TODO: Add explicit pan-to-node and selection once that API is available
    };
    // Empty state
    if (!lineageData) {
        return (external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['DataLineagePanel'] },
            external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyState'] },
                external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyState-icon'] }, "\uD83D\uDD17"),
                external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyState-title'] }, "No Node Selected"),
                external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyState-description'] }, "Select a node on the canvas to trace its data lineage"))));
    }
    const hasUpstream = lineageData.upstream.steps.length > 0;
    const hasDownstream = lineageData.downstream.length > 0 && lineageData.downstream.some((p) => p.steps.length > 0);
    return (external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['DataLineagePanel'] },
        external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['Header'] },
            external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['Header-title'] },
                external_react_default().createElement("span", { className: DataLineagePanel_DataLineagePanel_module['Header-icon'] }, "\uD83D\uDD17"),
                external_react_default().createElement("span", { className: DataLineagePanel_DataLineagePanel_module['Header-label'] }, "Data Lineage")),
            external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['Header-actions'] }, activeHighlightHandle ? (external_react_default().createElement("button", { className: DataLineagePanel_DataLineagePanel_module['Button'], onClick: handleDismiss, title: "Clear highlighting" }, "Clear")) : (external_react_default().createElement("button", { className: DataLineagePanel_DataLineagePanel_module['Button'], onClick: handleHighlightPath, title: "Highlight path on canvas" }, "Highlight")))),
        external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['SelectedNode'] },
            external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['SelectedNode-label'] },
                external_react_default().createElement("strong", null, lineageData.selectedNode.label)),
            external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['SelectedNode-meta'] },
                lineageData.selectedNode.type,
                lineageData.selectedNode.port && ` → ${lineageData.selectedNode.port}`),
            external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['SelectedNode-component'] }, lineageData.selectedNode.componentName)),
        (hasUpstream || hasDownstream) && (external_react_default().createElement(PathSummary, { upstream: lineageData.upstream, downstream: lineageData.downstream, selectedNodeLabel: lineageData.selectedNode.label })),
        external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['Section'] },
            external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['Section-header'], onClick: () => setIsUpstreamExpanded(!isUpstreamExpanded) },
                external_react_default().createElement("span", { className: DataLineagePanel_DataLineagePanel_module['Section-toggle'] }, isUpstreamExpanded ? '▼' : '▶'),
                external_react_default().createElement("span", { className: DataLineagePanel_DataLineagePanel_module['Section-title'] },
                    external_react_default().createElement("span", { className: DataLineagePanel_DataLineagePanel_module['Section-icon'] }, "\u25B2"),
                    " UPSTREAM"),
                external_react_default().createElement("span", { className: DataLineagePanel_DataLineagePanel_module['Section-subtitle'] }, "Where does this value come from?")),
            isUpstreamExpanded && (external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['Section-content'] }, hasUpstream ? (external_react_default().createElement(LineagePath, { path: lineageData.upstream, direction: "upstream", onNavigateToNode: handleNavigateToNode })) : (external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyPath'] },
                external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyPath-icon'] }, "\u2297"),
                external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyPath-text'] }, "No upstream connections"),
                external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyPath-hint'] }, "This is a source node")))))),
        external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['Section'] },
            external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['Section-header'], onClick: () => setIsDownstreamExpanded(!isDownstreamExpanded) },
                external_react_default().createElement("span", { className: DataLineagePanel_DataLineagePanel_module['Section-toggle'] }, isDownstreamExpanded ? '▼' : '▶'),
                external_react_default().createElement("span", { className: DataLineagePanel_DataLineagePanel_module['Section-title'] },
                    external_react_default().createElement("span", { className: DataLineagePanel_DataLineagePanel_module['Section-icon'] }, "\u25BC"),
                    " DOWNSTREAM"),
                external_react_default().createElement("span", { className: DataLineagePanel_DataLineagePanel_module['Section-subtitle'] }, "Where does this value go?")),
            isDownstreamExpanded && (external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['Section-content'] }, hasDownstream ? (external_react_default().createElement((external_react_default()).Fragment, null, lineageData.downstream.map((path, index) => (external_react_default().createElement("div", { key: index, className: DataLineagePanel_DataLineagePanel_module['DownstreamPath'] },
                lineageData.downstream.length > 1 && external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['PathBranch'] },
                    "Branch ",
                    index + 1),
                external_react_default().createElement(LineagePath, { path: path, direction: "downstream", onNavigateToNode: handleNavigateToNode })))))) : (external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyPath'] },
                external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyPath-icon'] }, "\u2297"),
                external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyPath-text'] }, "No downstream connections"),
                external_react_default().createElement("div", { className: DataLineagePanel_DataLineagePanel_module['EmptyPath-hint'] }, "This is a sink node"))))))));
}

;// ./src/editor/src/views/panels/DataLineagePanel/index.ts
/**
 * Data Lineage Panel
 *
 * Exports for the Data Lineage visualization panel
 */


// EXTERNAL MODULE: ../noodl-core-ui/src/components/popups/ContextMenu/index.ts + 2 modules
var ContextMenu = __webpack_require__(93739);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/tree-view/TreeView/TreeView.module.scss
var TreeView_module = __webpack_require__(1647);
;// ../noodl-core-ui/src/components/tree-view/TreeView/TreeView.module.scss

      
      
      
      
      
      
      
      
      

var TreeView_module_options = {};

TreeView_module_options.styleTagTransform = (styleTagTransform_default());
TreeView_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      TreeView_module_options.insert = insertBySelector_default().bind(null, "head");
    
TreeView_module_options.domAPI = (styleDomAPI_default());
TreeView_module_options.insertStyleElement = (insertStyleElement_default());

var TreeView_module_update = injectStylesIntoStyleTag_default()(TreeView_module/* default */.A, TreeView_module_options);




       /* harmony default export */ const TreeView_TreeView_module = (TreeView_module/* default */.A && TreeView_module/* default */.A.locals ? TreeView_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/tree-view/TreeView/TreeView.tsx



const TreeViewContext = (0,external_react_.createContext)({
    dropElement: null,
    setDropElement: null,
    dropSpot: null,
    setDropSpot: null,
    drop: null,
    activeItemId: null,
    setActiveItemId: null
});
function useTreeViewContext() {
    const context = (0,external_react_.useContext)(TreeViewContext);
    if (context === undefined) {
        throw new Error('useTreeViewContext must be a child of a TreeView node');
    }
    return context;
}
function TreeViewVisual({ items, node, onItemClick }) {
    function recursive(depth, children) {
        return children.map((child) => external_react_default().createElement(node, {
            depth,
            item: child,
            children: recursive(depth + 1, (child.children || [])),
            onClick: () => onItemClick(child)
        }));
    }
    return external_react_default().createElement("div", { className: external_classnames_default()([TreeView_TreeView_module['Root']]) }, recursive(0, items));
}
function TreeViewItemDraggable({ id, className, onClick, children }) {
    const context = useTreeViewContext();
    return (external_react_default().createElement("div", { className: external_classnames_default()([className, TreeView_TreeView_module['TreeViewItemDraggable']]), onClick: onClick, "data-id": id, draggable: true, onDragStart: (eventObject) => {
            // TODO: This can probably be placed in dataTransfer instead
            context.setDropElement(eventObject.target);
            // TODO: Make it easier to set data
            eventObject.dataTransfer.setData('noodl/draggable-id', id);
        }, onDragEnd: () => {
            context.setDropSpot(null);
        }, onDragOver: (eventObject) => {
            if (!!eventObject.dataTransfer.getData('noodl/draggable-id')) {
                return;
            }
            eventObject.dataTransfer.dropEffect = 'move';
            eventObject.preventDefault();
            if (eventObject.target) {
                // @ts-ignore
                const targetId = eventObject.target.getAttribute('data-id');
                context.setDropSpot(targetId || null);
            }
        }, onDrop: (eventObject) => {
            eventObject.preventDefault();
            const sourceId = eventObject.dataTransfer.getData('noodl/draggable-id');
            // @ts-ignore
            const destinationId = eventObject.target.getAttribute('data-id');
            context.drop(sourceId, destinationId);
        } }, children));
}
function TreeView({ items, node, onChanged, onItemClick, onItemDrop }) {
    const [, setTime] = (0,external_react_.useState)(Date.now());
    const [dropElement, setDropElement] = (0,external_react_.useState)(null);
    const [dropSpot, setDropSpot] = (0,external_react_.useState)(null);
    const [activeItemId, setActiveItemId] = (0,external_react_.useState)(null);
    const [internal_items, setItems] = (0,external_react_.useState)(() => items);
    (0,external_react_.useEffect)(() => setItems(items), [items]);
    const onItemClickCallback = (0,external_react_.useCallback)((item) => {
        let updated = false;
        onItemClick &&
            onItemClick(new Proxy(item, {
                set(obj, prop, value) {
                    obj[prop] = value;
                    updated = true;
                    return true;
                }
            }));
        if (updated) {
            setTime(Date.now());
            onChanged && onChanged(internal_items);
        }
    }, [internal_items, onChanged, onItemClick]);
    const onItemDropCallback = (0,external_react_.useCallback)((sourceId, destinationId) => {
        console.log(sourceId, destinationId);
        onItemDrop && onItemDrop(sourceId, destinationId);
    }, [onItemDrop]);
    return (external_react_default().createElement(TreeViewContext.Provider, { value: {
            dropElement,
            setDropElement,
            dropSpot,
            setDropSpot,
            drop: onItemDropCallback,
            activeItemId,
            setActiveItemId
        } },
        external_react_default().createElement(TreeViewVisual, { items: internal_items, node: node, onItemClick: onItemClickCallback })));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/tree-view/ColorListView/ColorListView.module.scss
var ColorListView_module = __webpack_require__(79435);
;// ../noodl-core-ui/src/components/tree-view/ColorListView/ColorListView.module.scss

      
      
      
      
      
      
      
      
      

var ColorListView_module_options = {};

ColorListView_module_options.styleTagTransform = (styleTagTransform_default());
ColorListView_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ColorListView_module_options.insert = insertBySelector_default().bind(null, "head");
    
ColorListView_module_options.domAPI = (styleDomAPI_default());
ColorListView_module_options.insertStyleElement = (insertStyleElement_default());

var ColorListView_module_update = injectStylesIntoStyleTag_default()(ColorListView_module/* default */.A, ColorListView_module_options);




       /* harmony default export */ const ColorListView_ColorListView_module = (ColorListView_module/* default */.A && ColorListView_module/* default */.A.locals ? ColorListView_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/tree-view/ColorListView/ColorListView.tsx







function ColorListItem({ depth, item, children, onClick }) {
    const context = useTreeViewContext();
    const isDropSpot = context.dropSpot === item.id.toString();
    const isExpanded = typeof item.isExpanded === 'undefined' || item.isExpanded;
    const isActive = item.id === context.activeItemId;
    return (external_react_default().createElement("div", { key: item.id },
        external_react_default().createElement(TreeViewItemDraggable, { id: item.id, className: external_classnames_default()([ColorListView_ColorListView_module['DraggableItem'], isActive && ColorListView_ColorListView_module['is-active']]), onClick: () => {
                onClick && onClick();
            } },
            external_react_default().createElement("div", { className: external_classnames_default()([ColorListView_ColorListView_module['Item']]), style: {
                    paddingLeft: `calc(${depth + 1} * 16px + ${2 * depth}px)`
                } },
                external_react_default().createElement("div", { className: external_classnames_default()(ColorListView_ColorListView_module['ColorItem']) },
                    external_react_default().createElement("div", { className: external_classnames_default()([ColorListView_ColorListView_module['ColorItem_Block']]), style: {
                            background: item.color || 'black'
                        } })),
                external_react_default().createElement("div", { className: external_classnames_default()([ColorListView_ColorListView_module['ItemText']]) },
                    external_react_default().createElement(Label/* Label */.JU, null, item.text),
                    item.text !== item.color && external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Shy }, item.color)),
                item.endSlot && external_react_default().createElement("div", { className: ColorListView_ColorListView_module['EndSlotContainer'] }, item.endSlot))),
        external_react_default().createElement("div", { style: {
                height: '2px',
                padding: '0 8px'
            } }, isDropSpot && (external_react_default().createElement("div", { style: {
                height: '100%',
                width: '100%',
                background: 'var(--theme-color-secondary-highlight)'
            } }))),
        external_react_default().createElement(Collapsible/* Collapsible */.N, { isCollapsed: !isExpanded }, children)));
}
function ColorListView({ items, onChanged, onItemDrop }) {
    function onItemClick(item) {
        if (item.children) {
            if (typeof item.isExpanded === 'undefined') {
                item.isExpanded = false;
            }
            else {
                item.isExpanded = !item.isExpanded;
            }
        }
    }
    return (external_react_default().createElement(TreeView, { items: items, node: ColorListItem, onItemClick: onItemClick, onChanged: onChanged, onItemDrop: onItemDrop }));
}

;// ../noodl-core-ui/src/components/tree-view/ColorListView/index.ts


;// ./src/editor/src/views/panels/DesignTokenPanel/components/ColorsTab/ColorsTab.tsx







function ColorsTab() {
    const { staticColors, dynamicColors } = useProjectDesignTokenContext();
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(CollapsableSection/* CollapsableSection */.M, { title: "Styles", variant: Section/* SectionVariant */.$.Panel, UNSAFE_style: {
                marginTop: '16px'
            } },
            external_react_default().createElement(ColorListView, { items: staticColors.map((x) => ({
                    id: x.name,
                    text: x.name,
                    color: x.color,
                    endSlot: (external_react_default().createElement(ContextMenu/* ContextMenu */.t, { variant: inputs_IconButton/* IconButtonVariant */.nl.SemiTransparent, menuItems: [
                            {
                                label: 'Another Action'
                            },
                            'divider',
                            {
                                label: 'Success'
                            },
                            {
                                label: 'Danger',
                                isDangerous: true
                            },
                            {
                                label: 'With subtitle',
                                endSlot: 'Subtitle goes here'
                            }
                        ] }))
                })) })),
        external_react_default().createElement(CollapsableSection/* CollapsableSection */.M, { title: "Project colors", variant: Section/* SectionVariant */.$.Panel, UNSAFE_style: {
                marginTop: '8px'
            } },
            external_react_default().createElement(ColorListView, { items: dynamicColors.map((x) => ({
                    id: x.name,
                    text: x.name,
                    color: x.color
                })) }))));
}

;// ./src/editor/src/views/panels/DesignTokenPanel/components/ColorsTab/index.ts


;// ./src/editor/src/views/panels/DesignTokenPanel/DesignTokenPanel.tsx









function DesignTokenPanel() {
    const { textStyles } = useProjectDesignTokenContext();
    return (external_react_default().createElement(BasePanel, { title: "Design Tokens" },
        external_react_default().createElement(Tabs/* Tabs */.t, { variant: Tabs/* TabsVariant */._.Sidebar, tabs: [
                {
                    label: 'Colors',
                    content: external_react_default().createElement(ColorsTab, null)
                },
                {
                    label: 'Typography',
                    content: (external_react_default().createElement(Section/* Section */.w, { title: "Experimental features" },
                        external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasTopSpacing: true },
                            external_react_default().createElement(Stack/* VStack */.Tk, null, textStyles.map((textStyle) => (external_react_default().createElement(Box/* Box */.a, { key: textStyle.name, hasBottomSpacing: 1 },
                                external_react_default().createElement(Label/* Label */.JU, null, JSON.stringify(textStyle)))))))))
                }
            ] })));
}

// EXTERNAL MODULE: ../noodl-core-ui/src/assets/icons/checkmark.svg
var checkmark = __webpack_require__(56182);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/Checkbox/Checkbox.module.scss
var Checkbox_module = __webpack_require__(86716);
;// ../noodl-core-ui/src/components/inputs/Checkbox/Checkbox.module.scss

      
      
      
      
      
      
      
      
      

var Checkbox_module_options = {};

Checkbox_module_options.styleTagTransform = (styleTagTransform_default());
Checkbox_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      Checkbox_module_options.insert = insertBySelector_default().bind(null, "head");
    
Checkbox_module_options.domAPI = (styleDomAPI_default());
Checkbox_module_options.insertStyleElement = (insertStyleElement_default());

var Checkbox_module_update = injectStylesIntoStyleTag_default()(Checkbox_module/* default */.A, Checkbox_module_options);




       /* harmony default export */ const Checkbox_Checkbox_module = (Checkbox_module/* default */.A && Checkbox_module/* default */.A.locals ? Checkbox_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/Checkbox/Checkbox.tsx







var CheckboxVariant;
(function (CheckboxVariant) {
    CheckboxVariant["Default"] = "default";
    CheckboxVariant["Sidebar"] = "sidebar";
    CheckboxVariant["Light"] = "light";
})(CheckboxVariant || (CheckboxVariant = {}));
var CheckboxSize;
(function (CheckboxSize) {
    CheckboxSize["Small"] = "small";
    CheckboxSize["Large"] = "large";
})(CheckboxSize || (CheckboxSize = {}));
function Checkbox({ variant = CheckboxVariant.Default, label, value, children, checkboxSize = CheckboxSize.Small, notification, hasHiddenCheckbox, hasBottomSpacing, onChange, onMouseEnter, onMouseLeave, onFocus, onBlur, isChecked, isDisabled, testId, UNSAFE_className, UNSAFE_style }) {
    const [newNotification, setNewNotification] = useNotificationFeedbackDisplay(notification);
    return (external_react_default().createElement("label", { className: external_classnames_default()([
            Checkbox_Checkbox_module['Root'],
            Checkbox_Checkbox_module[`is-variant-${variant}`],
            isDisabled && Checkbox_Checkbox_module['is-disabled'],
            hasBottomSpacing && Checkbox_Checkbox_module['has-bottom-spacing'],
            UNSAFE_className
        ]), onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, onFocus: onFocus, onBlur: onBlur, "data-test": testId, style: UNSAFE_style },
        external_react_default().createElement(NotificationFeedbackDisplay, { notification: newNotification }),
        external_react_default().createElement("input", { className: Checkbox_Checkbox_module['Checkbox'], type: "checkbox", checked: isChecked, disabled: isDisabled, onChange: onChange, value: value }),
        !hasHiddenCheckbox && (external_react_default().createElement("div", { className: external_classnames_default()([
                Checkbox_Checkbox_module['FauxCheckbox'],
                Checkbox_Checkbox_module[`is-size-${checkboxSize}`],
                Boolean(label) && Checkbox_Checkbox_module['has-right-margin']
            ]) }, isChecked && external_react_default().createElement(checkmark/* ReactComponent */.h, null))),
        children && (0,external_react_.isValidElement)(children) && external_react_default().createElement("div", { className: Checkbox_Checkbox_module['ChildContainer'] }, (0,external_react_.cloneElement)(children, { isChecked })),
        label && external_react_default().createElement(InputLabelSection, { label: label })));
}

;// ../noodl-core-ui/src/components/inputs/Checkbox/index.ts


;// ../noodl-core-ui/src/components/sidebar/ExperimentalFlag/ExperimentalFlag.tsx




var ExperimentalFlagVariant;
(function (ExperimentalFlagVariant) {
    ExperimentalFlagVariant[ExperimentalFlagVariant["Default"] = 0] = "Default";
    ExperimentalFlagVariant[ExperimentalFlagVariant["Small"] = 1] = "Small";
    ExperimentalFlagVariant[ExperimentalFlagVariant["NoPadding"] = 2] = "NoPadding";
})(ExperimentalFlagVariant || (ExperimentalFlagVariant = {}));
function ExperimentalFlag({ variant = ExperimentalFlagVariant.Default, text = 'Please note that this feature is untested and may lead to instability or lost work. Proceed with caution!' }) {
    if (variant === ExperimentalFlagVariant.Small) {
        return (external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasBottomSpacing: true, hasTopSpacing: 1 },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: FeedbackType/* FeedbackType */.M.Notice }, text)));
    }
    if (variant === ExperimentalFlagVariant.NoPadding) {
        return (external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: 6 },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: FeedbackType/* FeedbackType */.M.Notice }, text)));
    }
    return (external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasBottomSpacing: true, hasTopSpacing: true },
        external_react_default().createElement(typography_Text/* Text */.EY, { textType: FeedbackType/* FeedbackType */.M.Notice }, text)));
}

;// ../noodl-core-ui/src/components/sidebar/ExperimentalFlag/index.ts


// EXTERNAL MODULE: ./src/editor/src/views/panels/EditorSettingsPanel/sections/OpenAiSection.tsx + 2 modules
var OpenAiSection = __webpack_require__(56353);
;// ./src/editor/src/views/panels/EditorSettingsPanel/EditorSettingsPanel.tsx












function EditorSettingsPanel() {
    // @ts-expect-error Model is yeah, not great!
    (0,useModel/* useModel */.f)(editorsettings/* EditorSettings */.H.instance, ['updated']);
    const experimentalPanels = models_sidebar/* SidebarModel */.s.instance.getExperimentalItems();
    const experimentalFeautures = [
        {
            id: 'nodeGraphEditor.snapToGrid',
            settingsKey: 'nodeGraphEditor.snapToGrid',
            name: 'Snap nodes to grid',
            description: '',
            enabled: !!editorsettings/* EditorSettings */.H.instance.get('nodeGraphEditor.snapToGrid')
        }
    ];
    return (external_react_default().createElement(BasePanel, { title: "Editor Settings", hasContentScroll: true }, Boolean(experimentalPanels.length) && (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(CollapsableSection/* CollapsableSection */.M, { title: "Experimental panels", isClosed: true },
            external_react_default().createElement(ExperimentalFlag, { variant: ExperimentalFlagVariant.Small }),
            external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasTopSpacing: 1, hasBottomSpacing: 5 },
                external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: true }, experimentalPanels.map((item) => (external_react_default().createElement(ExperimentalFeautureItem, { key: item.id, ...item, labelPrefix: "Enable " })))))),
        external_react_default().createElement(CollapsableSection/* CollapsableSection */.M, { title: "Experimental features", isClosed: true },
            external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasTopSpacing: 1, hasBottomSpacing: 5 },
                external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: true }, experimentalFeautures.map((item) => (external_react_default().createElement(ExperimentalFeautureItem, { key: item.id, ...item })))))),
        external_react_default().createElement(OpenAiSection/* OpenAiSection */.z, null)))));
}
function ExperimentalFeautureItem(item) {
    return (external_react_default().createElement(Box/* Box */.a, null,
        external_react_default().createElement(Checkbox, { key: item.id, label: `${item.labelPrefix || ''}${item.name}`, variant: CheckboxVariant.Sidebar, isChecked: item.enabled, onChange: (ev) => {
                editorsettings/* EditorSettings */.H.instance.set(item.settingsKey, ev.target.checked);
            } }),
        Boolean(item.description) && (external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasTopSpacing: true },
            external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Medium }, item.description)))));
}

;// ./src/editor/src/views/panels/FileExplorerPanel/FileExplorerPanel.tsx




function FileExplorerPanel() {
    return (external_react_default().createElement(BasePanel, { title: "File Explorer", isFill: true },
        external_react_default().createElement(Tabs/* Tabs */.t, { variant: Tabs/* TabsVariant */._.Sidebar, tabs: [
                {
                    label: 'Project',
                    content: external_react_default().createElement(FileExplorer_Project, null)
                }
            ] })));
}
function FileExplorer_Project() {
    return (external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasYSpacing: true }, "Files"));
}

;// ./src/editor/src/views/panels/FileExplorerPanel/index.ts


// EXTERNAL MODULE: ./src/editor/src/services/GitHubOAuthService.ts
var GitHubOAuthService = __webpack_require__(5576);
// EXTERNAL MODULE: external "electron-store"
var external_electron_store_ = __webpack_require__(49468);
var external_electron_store_default = /*#__PURE__*/__webpack_require__.n(external_electron_store_);
;// ./src/editor/src/services/github/GitHubTokenStore.ts
/**
 * GitHubTokenStore
 *
 * Secure storage for GitHub OAuth tokens using Electron Store.
 * Tokens are stored encrypted using Electron's safeStorage API.
 * This provides OS-level encryption (Keychain on macOS, Credential Manager on Windows).
 *
 * @module services/github
 * @since 1.1.0
 */

/**
 * Store key for GitHub authentication data
 */
const GITHUB_AUTH_KEY = 'github.auth';
/**
 * Electron store instance for GitHub credentials
 * Uses encryption for sensitive data
 */
const store = new (external_electron_store_default())({
    name: 'github-credentials',
    // Encrypt the entire store for security
    encryptionKey: 'opennoodl-github-credentials'
});
/**
 * GitHubTokenStore
 *
 * Manages secure storage and retrieval of GitHub OAuth tokens.
 * Provides methods to save, retrieve, and clear authentication data.
 */
class GitHubTokenStore_GitHubTokenStore {
    /**
     * Save GitHub authentication data to secure storage
     *
     * @param token - OAuth access token
     * @param username - GitHub username
     * @param email - User's email (nullable)
     * @param installations - Optional list of installations (orgs/repos with access)
     *
     * @example
     * ```typescript
     * await GitHubTokenStore.saveToken(
     *   { access_token: 'gho_...', token_type: 'bearer', scope: 'repo' },
     *   'octocat',
     *   'octocat@github.com',
     *   installations
     * );
     * ```
     */
    static saveToken(token, username, email, installations) {
        const authData = {
            token,
            user: {
                login: username,
                email
            },
            installations,
            storedAt: new Date().toISOString()
        };
        store.set(GITHUB_AUTH_KEY, authData);
        if (installations && installations.length > 0) {
            const orgNames = installations.map((i) => i.account.login).join(', ');
            console.log(`[GitHub] Token saved for user: ${username} with access to: ${orgNames}`);
        }
        else {
            console.log('[GitHub] Token saved for user:', username);
        }
    }
    /**
     * Get installations (organizations/repos with access)
     *
     * @returns List of installations if authenticated, empty array otherwise
     */
    static getInstallations() {
        const authData = this.getToken();
        return (authData === null || authData === void 0 ? void 0 : authData.installations) || [];
    }
    /**
     * Retrieve stored GitHub authentication data
     *
     * @returns Stored auth data if exists, null otherwise
     *
     * @example
     * ```typescript
     * const authData = GitHubTokenStore.getToken();
     * if (authData) {
     *   console.log('Authenticated as:', authData.user.login);
     * }
     * ```
     */
    static getToken() {
        try {
            const authData = store.get(GITHUB_AUTH_KEY);
            return authData || null;
        }
        catch (error) {
            console.error('[GitHub] Error reading token:', error);
            return null;
        }
    }
    /**
     * Check if a valid token exists
     *
     * @returns True if token exists, false otherwise
     *
     * @example
     * ```typescript
     * if (GitHubTokenStore.hasToken()) {
     *   // User is authenticated
     * }
     * ```
     */
    static hasToken() {
        const authData = this.getToken();
        return authData !== null && !!authData.token.access_token;
    }
    /**
     * Get the username of the authenticated user
     *
     * @returns Username if authenticated, null otherwise
     */
    static getUsername() {
        const authData = this.getToken();
        return (authData === null || authData === void 0 ? void 0 : authData.user.login) || null;
    }
    /**
     * Get the access token string
     *
     * @returns Access token if exists, null otherwise
     */
    static getAccessToken() {
        const authData = this.getToken();
        return (authData === null || authData === void 0 ? void 0 : authData.token.access_token) || null;
    }
    /**
     * Clear stored authentication data
     * Call this when user disconnects their GitHub account
     *
     * @example
     * ```typescript
     * GitHubTokenStore.clearToken();
     * console.log('User disconnected from GitHub');
     * ```
     */
    static clearToken() {
        store.delete(GITHUB_AUTH_KEY);
        console.log('[GitHub] Token cleared');
    }
    /**
     * Check if token is expired (if expiration is set)
     *
     * @returns True if token is expired, false if valid or no expiration
     */
    static isTokenExpired() {
        const authData = this.getToken();
        if (!authData || !authData.token.expires_at) {
            // No expiration set - assume valid
            return false;
        }
        const expiresAt = new Date(authData.token.expires_at);
        const now = new Date();
        return now >= expiresAt;
    }
    /**
     * Update token (for refresh scenarios)
     *
     * @param token - New OAuth token
     */
    static updateToken(token) {
        const existing = this.getToken();
        if (!existing) {
            throw new Error('Cannot update token: No existing auth data found');
        }
        const updated = {
            ...existing,
            token,
            storedAt: new Date().toISOString()
        };
        store.set(GITHUB_AUTH_KEY, updated);
        console.log('[GitHub] Token updated');
    }
    /**
     * Get all stored GitHub data (for debugging)
     * WARNING: Contains sensitive data - use carefully
     *
     * @returns All stored data
     */
    static _debug_getAllData() {
        return this.getToken();
    }
}

;// ./src/editor/src/services/github/GitHubAuth.ts
/**
 * GitHubAuth
 *
 * Handles GitHub OAuth authentication using Web OAuth Flow.
 * Web OAuth Flow allows users to select which organizations and repositories
 * to grant access to, providing better permission control.
 *
 * @module services/github
 * @since 1.1.0
 */


/**
 * Scopes required for GitHub integration
 * - repo: Full control of private repositories (for issues, PRs)
 * - read:org: Read organization membership
 * - read:user: Read user profile data
 * - user:email: Read user email addresses
 */
const REQUIRED_SCOPES = (/* unused pure expression or super */ null && (['repo', 'read:org', 'read:user', 'user:email']));
/**
 * GitHubAuth
 *
 * Manages GitHub OAuth authentication using Device Flow.
 * Provides methods to authenticate, check status, and disconnect.
 */
class GitHubAuth {
    /**
     * Initiate GitHub Web OAuth flow
     *
     * Opens browser to GitHub authorization page where user can select
     * which organizations and repositories to grant access to.
     *
     * @param onProgress - Callback for progress updates
     * @returns Promise that resolves when authentication completes
     *
     * @throws {GitHubAuthError} If OAuth flow fails
     *
     * @example
     * ```typescript
     * await GitHubAuth.startWebOAuthFlow((message) => {
     *   console.log(message);
     * });
     * console.log('Successfully authenticated!');
     * ```
     */
    static async startWebOAuthFlow(onProgress) {
        try {
            onProgress === null || onProgress === void 0 ? void 0 : onProgress('Starting GitHub authentication...');
            // Request OAuth flow from main process
            const result = await ipcRenderer.invoke('github-oauth-start');
            if (!result.success) {
                throw new Error(result.error || 'Failed to start OAuth flow');
            }
            onProgress === null || onProgress === void 0 ? void 0 : onProgress('Opening GitHub in your browser...');
            // Open browser to GitHub authorization page
            shell.openExternal(result.authUrl);
            // Wait for OAuth callback from main process
            return new Promise((resolve, reject) => {
                const timeout = setTimeout(() => {
                    cleanup();
                    reject(new Error('Authentication timed out after 5 minutes'));
                }, 300000); // 5 minutes
                const handleSuccess = async (_event, data) => {
                    console.log('🎉 [GitHub Auth] ========================================');
                    console.log('🎉 [GitHub Auth] IPC EVENT RECEIVED: github-oauth-complete');
                    console.log('🎉 [GitHub Auth] Data:', data);
                    console.log('🎉 [GitHub Auth] ========================================');
                    cleanup();
                    try {
                        onProgress === null || onProgress === void 0 ? void 0 : onProgress('Authentication successful, fetching details...');
                        // Save token and user info
                        const token = {
                            access_token: data.token.access_token,
                            token_type: data.token.token_type,
                            scope: data.token.scope
                        };
                        const installations = data.installations;
                        GitHubTokenStore.saveToken(token, data.user.login, data.user.email, installations);
                        onProgress === null || onProgress === void 0 ? void 0 : onProgress(`Successfully authenticated as ${data.user.login}`);
                        resolve();
                    }
                    catch (error) {
                        reject(error);
                    }
                };
                const handleError = (_event, data) => {
                    cleanup();
                    reject(new Error(data.message || 'Authentication failed'));
                };
                const cleanup = () => {
                    clearTimeout(timeout);
                    ipcRenderer.removeListener('github-oauth-complete', handleSuccess);
                    ipcRenderer.removeListener('github-oauth-error', handleError);
                };
                ipcRenderer.once('github-oauth-complete', handleSuccess);
                ipcRenderer.once('github-oauth-error', handleError);
            });
        }
        catch (error) {
            const authError = new Error(`GitHub authentication failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
            authError.code = error instanceof Error && 'code' in error ? error.code : undefined;
            console.error('[GitHub] Authentication error:', authError);
            throw authError;
        }
    }
    /**
     * @deprecated Use startWebOAuthFlow instead. Device Flow kept for backward compatibility.
     */
    static async startDeviceFlow(onProgress) {
        console.warn('[GitHub] startDeviceFlow is deprecated, using startWebOAuthFlow instead');
        await this.startWebOAuthFlow(onProgress);
        // Return empty device code for backward compatibility
        return {
            device_code: '',
            user_code: '',
            verification_uri: '',
            expires_in: 0,
            interval: 0
        };
    }
    /**
     * Fetch user information from GitHub API
     *
     * @param token - Access token
     * @returns User information
     *
     * @throws {Error} If API request fails
     */
    static async fetchUserInfo(token) {
        const response = await fetch('https://api.github.com/user', {
            headers: {
                Authorization: `Bearer ${token}`,
                Accept: 'application/vnd.github.v3+json'
            }
        });
        if (!response.ok) {
            throw new Error(`Failed to fetch user info: ${response.statusText}`);
        }
        return response.json();
    }
    /**
     * Get current authentication state
     *
     * @returns Current auth state
     *
     * @example
     * ```typescript
     * const state = GitHubAuth.getAuthState();
     * if (state.isAuthenticated) {
     *   console.log('Connected as:', state.username);
     * }
     * ```
     */
    static getAuthState() {
        const storedAuth = GitHubTokenStore.getToken();
        if (!storedAuth) {
            return {
                isAuthenticated: false
            };
        }
        // Check if token is expired
        if (GitHubTokenStore.isTokenExpired()) {
            console.warn('[GitHub] Token is expired');
            return {
                isAuthenticated: false
            };
        }
        return {
            isAuthenticated: true,
            username: storedAuth.user.login,
            email: storedAuth.user.email || undefined,
            token: storedAuth.token,
            authenticatedAt: storedAuth.storedAt
        };
    }
    /**
     * Check if user is currently authenticated
     *
     * @returns True if authenticated and token is valid
     */
    static isAuthenticated() {
        return this.getAuthState().isAuthenticated;
    }
    /**
     * Get the username of authenticated user
     *
     * @returns Username or null if not authenticated
     */
    static getUsername() {
        return this.getAuthState().username || null;
    }
    /**
     * Get current access token
     *
     * @returns Access token or null if not authenticated
     */
    static getAccessToken() {
        var _a;
        const state = this.getAuthState();
        return ((_a = state.token) === null || _a === void 0 ? void 0 : _a.access_token) || null;
    }
    /**
     * Disconnect from GitHub
     *
     * Clears stored authentication data. User will need to re-authenticate.
     *
     * @example
     * ```typescript
     * GitHubAuth.disconnect();
     * console.log('Disconnected from GitHub');
     * ```
     */
    static disconnect() {
        GitHubTokenStore.clearToken();
        console.log('[GitHub] User disconnected');
    }
    /**
     * Validate current token by making a test API call
     *
     * @returns True if token is valid, false otherwise
     */
    static async validateToken() {
        const token = this.getAccessToken();
        if (!token) {
            return false;
        }
        try {
            const response = await fetch('https://api.github.com/user', {
                headers: {
                    Authorization: `Bearer ${token}`,
                    Accept: 'application/vnd.github.v3+json'
                }
            });
            return response.ok;
        }
        catch (error) {
            console.error('[GitHub] Token validation failed:', error);
            return false;
        }
    }
    /**
     * Refresh user information from GitHub
     *
     * Useful for updating cached user data
     *
     * @returns Updated auth state
     * @throws {Error} If not authenticated or refresh fails
     */
    static async refreshUserInfo() {
        const token = this.getAccessToken();
        if (!token) {
            throw new Error('Not authenticated');
        }
        const user = await this.fetchUserInfo(token);
        // Update stored auth with new user info
        const storedAuth = GitHubTokenStore.getToken();
        if (storedAuth) {
            GitHubTokenStore.saveToken(storedAuth.token, user.login, user.email);
        }
        return this.getAuthState();
    }
}

;// external "universal-user-agent"
const external_universal_user_agent_namespaceObject = require("universal-user-agent");
;// external "before-after-hook"
const external_before_after_hook_namespaceObject = require("before-after-hook");
;// ./node_modules/@octokit/endpoint/dist-web/index.js
// pkg/dist-src/defaults.js


// pkg/dist-src/version.js
var VERSION = "9.0.6";

// pkg/dist-src/defaults.js
var userAgent = `octokit-endpoint.js/${VERSION} ${(0,external_universal_user_agent_namespaceObject.getUserAgent)()}`;
var DEFAULTS = {
  method: "GET",
  baseUrl: "https://api.github.com",
  headers: {
    accept: "application/vnd.github.v3+json",
    "user-agent": userAgent
  },
  mediaType: {
    format: ""
  }
};

// pkg/dist-src/util/lowercase-keys.js
function lowercaseKeys(object) {
  if (!object) {
    return {};
  }
  return Object.keys(object).reduce((newObj, key) => {
    newObj[key.toLowerCase()] = object[key];
    return newObj;
  }, {});
}

// pkg/dist-src/util/is-plain-object.js
function isPlainObject(value) {
  if (typeof value !== "object" || value === null)
    return false;
  if (Object.prototype.toString.call(value) !== "[object Object]")
    return false;
  const proto = Object.getPrototypeOf(value);
  if (proto === null)
    return true;
  const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
}

// pkg/dist-src/util/merge-deep.js
function mergeDeep(defaults, options) {
  const result = Object.assign({}, defaults);
  Object.keys(options).forEach((key) => {
    if (isPlainObject(options[key])) {
      if (!(key in defaults))
        Object.assign(result, { [key]: options[key] });
      else
        result[key] = mergeDeep(defaults[key], options[key]);
    } else {
      Object.assign(result, { [key]: options[key] });
    }
  });
  return result;
}

// pkg/dist-src/util/remove-undefined-properties.js
function removeUndefinedProperties(obj) {
  for (const key in obj) {
    if (obj[key] === void 0) {
      delete obj[key];
    }
  }
  return obj;
}

// pkg/dist-src/merge.js
function merge(defaults, route, options) {
  if (typeof route === "string") {
    let [method, url] = route.split(" ");
    options = Object.assign(url ? { method, url } : { url: method }, options);
  } else {
    options = Object.assign({}, route);
  }
  options.headers = lowercaseKeys(options.headers);
  removeUndefinedProperties(options);
  removeUndefinedProperties(options.headers);
  const mergedOptions = mergeDeep(defaults || {}, options);
  if (options.url === "/graphql") {
    if (defaults && defaults.mediaType.previews?.length) {
      mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(
        (preview) => !mergedOptions.mediaType.previews.includes(preview)
      ).concat(mergedOptions.mediaType.previews);
    }
    mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, ""));
  }
  return mergedOptions;
}

// pkg/dist-src/util/add-query-parameters.js
function addQueryParameters(url, parameters) {
  const separator = /\?/.test(url) ? "&" : "?";
  const names = Object.keys(parameters);
  if (names.length === 0) {
    return url;
  }
  return url + separator + names.map((name) => {
    if (name === "q") {
      return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
    }
    return `${name}=${encodeURIComponent(parameters[name])}`;
  }).join("&");
}

// pkg/dist-src/util/extract-url-variable-names.js
var urlVariableRegex = /\{[^{}}]+\}/g;
function removeNonChars(variableName) {
  return variableName.replace(/(?:^\W+)|(?:(?<!\W)\W+$)/g, "").split(/,/);
}
function extractUrlVariableNames(url) {
  const matches = url.match(urlVariableRegex);
  if (!matches) {
    return [];
  }
  return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
}

// pkg/dist-src/util/omit.js
function omit(object, keysToOmit) {
  const result = { __proto__: null };
  for (const key of Object.keys(object)) {
    if (keysToOmit.indexOf(key) === -1) {
      result[key] = object[key];
    }
  }
  return result;
}

// pkg/dist-src/util/url-template.js
function encodeReserved(str) {
  return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
    if (!/%[0-9A-Fa-f]/.test(part)) {
      part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
    }
    return part;
  }).join("");
}
function encodeUnreserved(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return "%" + c.charCodeAt(0).toString(16).toUpperCase();
  });
}
function encodeValue(operator, value, key) {
  value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
  if (key) {
    return encodeUnreserved(key) + "=" + value;
  } else {
    return value;
  }
}
function isDefined(value) {
  return value !== void 0 && value !== null;
}
function isKeyOperator(operator) {
  return operator === ";" || operator === "&" || operator === "?";
}
function getValues(context, operator, key, modifier) {
  var value = context[key], result = [];
  if (isDefined(value) && value !== "") {
    if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
      value = value.toString();
      if (modifier && modifier !== "*") {
        value = value.substring(0, parseInt(modifier, 10));
      }
      result.push(
        encodeValue(operator, value, isKeyOperator(operator) ? key : "")
      );
    } else {
      if (modifier === "*") {
        if (Array.isArray(value)) {
          value.filter(isDefined).forEach(function(value2) {
            result.push(
              encodeValue(operator, value2, isKeyOperator(operator) ? key : "")
            );
          });
        } else {
          Object.keys(value).forEach(function(k) {
            if (isDefined(value[k])) {
              result.push(encodeValue(operator, value[k], k));
            }
          });
        }
      } else {
        const tmp = [];
        if (Array.isArray(value)) {
          value.filter(isDefined).forEach(function(value2) {
            tmp.push(encodeValue(operator, value2));
          });
        } else {
          Object.keys(value).forEach(function(k) {
            if (isDefined(value[k])) {
              tmp.push(encodeUnreserved(k));
              tmp.push(encodeValue(operator, value[k].toString()));
            }
          });
        }
        if (isKeyOperator(operator)) {
          result.push(encodeUnreserved(key) + "=" + tmp.join(","));
        } else if (tmp.length !== 0) {
          result.push(tmp.join(","));
        }
      }
    }
  } else {
    if (operator === ";") {
      if (isDefined(value)) {
        result.push(encodeUnreserved(key));
      }
    } else if (value === "" && (operator === "&" || operator === "?")) {
      result.push(encodeUnreserved(key) + "=");
    } else if (value === "") {
      result.push("");
    }
  }
  return result;
}
function parseUrl(template) {
  return {
    expand: expand.bind(null, template)
  };
}
function expand(template, context) {
  var operators = ["+", "#", ".", "/", ";", "?", "&"];
  template = template.replace(
    /\{([^\{\}]+)\}|([^\{\}]+)/g,
    function(_, expression, literal) {
      if (expression) {
        let operator = "";
        const values = [];
        if (operators.indexOf(expression.charAt(0)) !== -1) {
          operator = expression.charAt(0);
          expression = expression.substr(1);
        }
        expression.split(/,/g).forEach(function(variable) {
          var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
          values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
        });
        if (operator && operator !== "+") {
          var separator = ",";
          if (operator === "?") {
            separator = "&";
          } else if (operator !== "#") {
            separator = operator;
          }
          return (values.length !== 0 ? operator : "") + values.join(separator);
        } else {
          return values.join(",");
        }
      } else {
        return encodeReserved(literal);
      }
    }
  );
  if (template === "/") {
    return template;
  } else {
    return template.replace(/\/$/, "");
  }
}

// pkg/dist-src/parse.js
function parse(options) {
  let method = options.method.toUpperCase();
  let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
  let headers = Object.assign({}, options.headers);
  let body;
  let parameters = omit(options, [
    "method",
    "baseUrl",
    "url",
    "headers",
    "request",
    "mediaType"
  ]);
  const urlVariableNames = extractUrlVariableNames(url);
  url = parseUrl(url).expand(parameters);
  if (!/^http/.test(url)) {
    url = options.baseUrl + url;
  }
  const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
  const remainingParameters = omit(parameters, omittedParameters);
  const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
  if (!isBinaryRequest) {
    if (options.mediaType.format) {
      headers.accept = headers.accept.split(/,/).map(
        (format) => format.replace(
          /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,
          `application/vnd$1$2.${options.mediaType.format}`
        )
      ).join(",");
    }
    if (url.endsWith("/graphql")) {
      if (options.mediaType.previews?.length) {
        const previewsFromAcceptHeader = headers.accept.match(/(?<![\w-])[\w-]+(?=-preview)/g) || [];
        headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {
          const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
          return `application/vnd.github.${preview}-preview${format}`;
        }).join(",");
      }
    }
  }
  if (["GET", "HEAD"].includes(method)) {
    url = addQueryParameters(url, remainingParameters);
  } else {
    if ("data" in remainingParameters) {
      body = remainingParameters.data;
    } else {
      if (Object.keys(remainingParameters).length) {
        body = remainingParameters;
      }
    }
  }
  if (!headers["content-type"] && typeof body !== "undefined") {
    headers["content-type"] = "application/json; charset=utf-8";
  }
  if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
    body = "";
  }
  return Object.assign(
    { method, url, headers },
    typeof body !== "undefined" ? { body } : null,
    options.request ? { request: options.request } : null
  );
}

// pkg/dist-src/endpoint-with-defaults.js
function endpointWithDefaults(defaults, route, options) {
  return parse(merge(defaults, route, options));
}

// pkg/dist-src/with-defaults.js
function withDefaults(oldDefaults, newDefaults) {
  const DEFAULTS2 = merge(oldDefaults, newDefaults);
  const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);
  return Object.assign(endpoint2, {
    DEFAULTS: DEFAULTS2,
    defaults: withDefaults.bind(null, DEFAULTS2),
    merge: merge.bind(null, DEFAULTS2),
    parse
  });
}

// pkg/dist-src/index.js
var endpoint = withDefaults(null, DEFAULTS);


;// external "deprecation"
const external_deprecation_namespaceObject = require("deprecation");
;// external "once"
const external_once_namespaceObject = require("once");
var external_once_default = /*#__PURE__*/__webpack_require__.n(external_once_namespaceObject);
;// ./node_modules/@octokit/request-error/dist-web/index.js
// pkg/dist-src/index.js


var logOnceCode = external_once_default()((deprecation) => console.warn(deprecation));
var logOnceHeaders = external_once_default()((deprecation) => console.warn(deprecation));
var RequestError = class extends Error {
  constructor(message, statusCode, options) {
    super(message);
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor);
    }
    this.name = "HttpError";
    this.status = statusCode;
    let headers;
    if ("headers" in options && typeof options.headers !== "undefined") {
      headers = options.headers;
    }
    if ("response" in options) {
      this.response = options.response;
      headers = options.response.headers;
    }
    const requestCopy = Object.assign({}, options.request);
    if (options.request.headers.authorization) {
      requestCopy.headers = Object.assign({}, options.request.headers, {
        authorization: options.request.headers.authorization.replace(
          /(?<! ) .*$/,
          " [REDACTED]"
        )
      });
    }
    requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
    this.request = requestCopy;
    Object.defineProperty(this, "code", {
      get() {
        logOnceCode(
          new external_deprecation_namespaceObject.Deprecation(
            "[@octokit/request-error] `error.code` is deprecated, use `error.status`."
          )
        );
        return statusCode;
      }
    });
    Object.defineProperty(this, "headers", {
      get() {
        logOnceHeaders(
          new external_deprecation_namespaceObject.Deprecation(
            "[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`."
          )
        );
        return headers || {};
      }
    });
  }
};


;// ./node_modules/@octokit/request/dist-web/index.js
// pkg/dist-src/index.js



// pkg/dist-src/version.js
var dist_web_VERSION = "8.4.1";

// pkg/dist-src/is-plain-object.js
function dist_web_isPlainObject(value) {
  if (typeof value !== "object" || value === null)
    return false;
  if (Object.prototype.toString.call(value) !== "[object Object]")
    return false;
  const proto = Object.getPrototypeOf(value);
  if (proto === null)
    return true;
  const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
}

// pkg/dist-src/fetch-wrapper.js


// pkg/dist-src/get-buffer-response.js
function getBufferResponse(response) {
  return response.arrayBuffer();
}

// pkg/dist-src/fetch-wrapper.js
function fetchWrapper(requestOptions) {
  const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
  const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false;
  if (dist_web_isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
    requestOptions.body = JSON.stringify(requestOptions.body);
  }
  let headers = {};
  let status;
  let url;
  let { fetch } = globalThis;
  if (requestOptions.request?.fetch) {
    fetch = requestOptions.request.fetch;
  }
  if (!fetch) {
    throw new Error(
      "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing"
    );
  }
  return fetch(requestOptions.url, {
    method: requestOptions.method,
    body: requestOptions.body,
    redirect: requestOptions.request?.redirect,
    headers: requestOptions.headers,
    signal: requestOptions.request?.signal,
    // duplex must be set if request.body is ReadableStream or Async Iterables.
    // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex.
    ...requestOptions.body && { duplex: "half" }
  }).then(async (response) => {
    url = response.url;
    status = response.status;
    for (const keyAndValue of response.headers) {
      headers[keyAndValue[0]] = keyAndValue[1];
    }
    if ("deprecation" in headers) {
      const matches = headers.link && headers.link.match(/<([^<>]+)>; rel="deprecation"/);
      const deprecationLink = matches && matches.pop();
      log.warn(
        `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`
      );
    }
    if (status === 204 || status === 205) {
      return;
    }
    if (requestOptions.method === "HEAD") {
      if (status < 400) {
        return;
      }
      throw new RequestError(response.statusText, status, {
        response: {
          url,
          status,
          headers,
          data: void 0
        },
        request: requestOptions
      });
    }
    if (status === 304) {
      throw new RequestError("Not modified", status, {
        response: {
          url,
          status,
          headers,
          data: await getResponseData(response)
        },
        request: requestOptions
      });
    }
    if (status >= 400) {
      const data = await getResponseData(response);
      const error = new RequestError(toErrorMessage(data), status, {
        response: {
          url,
          status,
          headers,
          data
        },
        request: requestOptions
      });
      throw error;
    }
    return parseSuccessResponseBody ? await getResponseData(response) : response.body;
  }).then((data) => {
    return {
      status,
      url,
      headers,
      data
    };
  }).catch((error) => {
    if (error instanceof RequestError)
      throw error;
    else if (error.name === "AbortError")
      throw error;
    let message = error.message;
    if (error.name === "TypeError" && "cause" in error) {
      if (error.cause instanceof Error) {
        message = error.cause.message;
      } else if (typeof error.cause === "string") {
        message = error.cause;
      }
    }
    throw new RequestError(message, 500, {
      request: requestOptions
    });
  });
}
async function getResponseData(response) {
  const contentType = response.headers.get("content-type");
  if (/application\/json/.test(contentType)) {
    return response.json().catch(() => response.text()).catch(() => "");
  }
  if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
    return response.text();
  }
  return getBufferResponse(response);
}
function toErrorMessage(data) {
  if (typeof data === "string")
    return data;
  let suffix;
  if ("documentation_url" in data) {
    suffix = ` - ${data.documentation_url}`;
  } else {
    suffix = "";
  }
  if ("message" in data) {
    if (Array.isArray(data.errors)) {
      return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`;
    }
    return `${data.message}${suffix}`;
  }
  return `Unknown error: ${JSON.stringify(data)}`;
}

// pkg/dist-src/with-defaults.js
function dist_web_withDefaults(oldEndpoint, newDefaults) {
  const endpoint2 = oldEndpoint.defaults(newDefaults);
  const newApi = function(route, parameters) {
    const endpointOptions = endpoint2.merge(route, parameters);
    if (!endpointOptions.request || !endpointOptions.request.hook) {
      return fetchWrapper(endpoint2.parse(endpointOptions));
    }
    const request2 = (route2, parameters2) => {
      return fetchWrapper(
        endpoint2.parse(endpoint2.merge(route2, parameters2))
      );
    };
    Object.assign(request2, {
      endpoint: endpoint2,
      defaults: dist_web_withDefaults.bind(null, endpoint2)
    });
    return endpointOptions.request.hook(request2, endpointOptions);
  };
  return Object.assign(newApi, {
    endpoint: endpoint2,
    defaults: dist_web_withDefaults.bind(null, endpoint2)
  });
}

// pkg/dist-src/index.js
var request = dist_web_withDefaults(endpoint, {
  headers: {
    "user-agent": `octokit-request.js/${dist_web_VERSION} ${(0,external_universal_user_agent_namespaceObject.getUserAgent)()}`
  }
});


;// ./node_modules/@octokit/graphql/dist-web/index.js
// pkg/dist-src/index.js



// pkg/dist-src/version.js
var graphql_dist_web_VERSION = "7.1.1";

// pkg/dist-src/with-defaults.js


// pkg/dist-src/graphql.js


// pkg/dist-src/error.js
function _buildMessageForResponseErrors(data) {
  return `Request failed due to following response errors:
` + data.errors.map((e) => ` - ${e.message}`).join("\n");
}
var GraphqlResponseError = class extends Error {
  constructor(request2, headers, response) {
    super(_buildMessageForResponseErrors(response));
    this.request = request2;
    this.headers = headers;
    this.response = response;
    this.name = "GraphqlResponseError";
    this.errors = response.errors;
    this.data = response.data;
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor);
    }
  }
};

// pkg/dist-src/graphql.js
var NON_VARIABLE_OPTIONS = [
  "method",
  "baseUrl",
  "url",
  "headers",
  "request",
  "query",
  "mediaType"
];
var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
function graphql(request2, query, options) {
  if (options) {
    if (typeof query === "string" && "query" in options) {
      return Promise.reject(
        new Error(`[@octokit/graphql] "query" cannot be used as variable name`)
      );
    }
    for (const key in options) {
      if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;
      return Promise.reject(
        new Error(
          `[@octokit/graphql] "${key}" cannot be used as variable name`
        )
      );
    }
  }
  const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
  const requestOptions = Object.keys(
    parsedOptions
  ).reduce((result, key) => {
    if (NON_VARIABLE_OPTIONS.includes(key)) {
      result[key] = parsedOptions[key];
      return result;
    }
    if (!result.variables) {
      result.variables = {};
    }
    result.variables[key] = parsedOptions[key];
    return result;
  }, {});
  const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl;
  if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
    requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
  }
  return request2(requestOptions).then((response) => {
    if (response.data.errors) {
      const headers = {};
      for (const key of Object.keys(response.headers)) {
        headers[key] = response.headers[key];
      }
      throw new GraphqlResponseError(
        requestOptions,
        headers,
        response.data
      );
    }
    return response.data.data;
  });
}

// pkg/dist-src/with-defaults.js
function graphql_dist_web_withDefaults(request2, newDefaults) {
  const newRequest = request2.defaults(newDefaults);
  const newApi = (query, options) => {
    return graphql(newRequest, query, options);
  };
  return Object.assign(newApi, {
    defaults: graphql_dist_web_withDefaults.bind(null, newRequest),
    endpoint: newRequest.endpoint
  });
}

// pkg/dist-src/index.js
var graphql2 = graphql_dist_web_withDefaults(request, {
  headers: {
    "user-agent": `octokit-graphql.js/${graphql_dist_web_VERSION} ${(0,external_universal_user_agent_namespaceObject.getUserAgent)()}`
  },
  method: "POST",
  url: "/graphql"
});
function withCustomRequest(customRequest) {
  return graphql_dist_web_withDefaults(customRequest, {
    method: "POST",
    url: "/graphql"
  });
}


;// ./node_modules/@octokit/auth-token/dist-web/index.js
// pkg/dist-src/auth.js
var REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
var REGEX_IS_INSTALLATION = /^ghs_/;
var REGEX_IS_USER_TO_SERVER = /^ghu_/;
async function auth(token) {
  const isApp = token.split(/\./).length === 3;
  const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);
  const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
  const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
  return {
    type: "token",
    token,
    tokenType
  };
}

// pkg/dist-src/with-authorization-prefix.js
function withAuthorizationPrefix(token) {
  if (token.split(/\./).length === 3) {
    return `bearer ${token}`;
  }
  return `token ${token}`;
}

// pkg/dist-src/hook.js
async function hook(token, request, route, parameters) {
  const endpoint = request.endpoint.merge(
    route,
    parameters
  );
  endpoint.headers.authorization = withAuthorizationPrefix(token);
  return request(endpoint);
}

// pkg/dist-src/index.js
var createTokenAuth = function createTokenAuth2(token) {
  if (!token) {
    throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
  }
  if (typeof token !== "string") {
    throw new Error(
      "[@octokit/auth-token] Token passed to createTokenAuth is not a string"
    );
  }
  token = token.replace(/^(token|bearer) +/i, "");
  return Object.assign(auth.bind(null, token), {
    hook: hook.bind(null, token)
  });
};


;// ./node_modules/@octokit/core/dist-web/index.js
// pkg/dist-src/index.js






// pkg/dist-src/version.js
var core_dist_web_VERSION = "5.2.2";

// pkg/dist-src/index.js
var noop = () => {
};
var consoleWarn = console.warn.bind(console);
var consoleError = console.error.bind(console);
function createLogger(logger = {}) {
  if (typeof logger.debug !== "function") {
    logger.debug = noop;
  }
  if (typeof logger.info !== "function") {
    logger.info = noop;
  }
  if (typeof logger.warn !== "function") {
    logger.warn = consoleWarn;
  }
  if (typeof logger.error !== "function") {
    logger.error = consoleError;
  }
  return logger;
}
var userAgentTrail = `octokit-core.js/${core_dist_web_VERSION} ${(0,external_universal_user_agent_namespaceObject.getUserAgent)()}`;
var Octokit = class {
  static {
    this.VERSION = core_dist_web_VERSION;
  }
  static defaults(defaults) {
    const OctokitWithDefaults = class extends this {
      constructor(...args) {
        const options = args[0] || {};
        if (typeof defaults === "function") {
          super(defaults(options));
          return;
        }
        super(
          Object.assign(
            {},
            defaults,
            options,
            options.userAgent && defaults.userAgent ? {
              userAgent: `${options.userAgent} ${defaults.userAgent}`
            } : null
          )
        );
      }
    };
    return OctokitWithDefaults;
  }
  static {
    this.plugins = [];
  }
  /**
   * Attach a plugin (or many) to your Octokit instance.
   *
   * @example
   * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
   */
  static plugin(...newPlugins) {
    const currentPlugins = this.plugins;
    const NewOctokit = class extends this {
      static {
        this.plugins = currentPlugins.concat(
          newPlugins.filter((plugin) => !currentPlugins.includes(plugin))
        );
      }
    };
    return NewOctokit;
  }
  constructor(options = {}) {
    const hook = new external_before_after_hook_namespaceObject.Collection();
    const requestDefaults = {
      baseUrl: request.endpoint.DEFAULTS.baseUrl,
      headers: {},
      request: Object.assign({}, options.request, {
        // @ts-ignore internal usage only, no need to type
        hook: hook.bind(null, "request")
      }),
      mediaType: {
        previews: [],
        format: ""
      }
    };
    requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail;
    if (options.baseUrl) {
      requestDefaults.baseUrl = options.baseUrl;
    }
    if (options.previews) {
      requestDefaults.mediaType.previews = options.previews;
    }
    if (options.timeZone) {
      requestDefaults.headers["time-zone"] = options.timeZone;
    }
    this.request = request.defaults(requestDefaults);
    this.graphql = withCustomRequest(this.request).defaults(requestDefaults);
    this.log = createLogger(options.log);
    this.hook = hook;
    if (!options.authStrategy) {
      if (!options.auth) {
        this.auth = async () => ({
          type: "unauthenticated"
        });
      } else {
        const auth = createTokenAuth(options.auth);
        hook.wrap("request", auth.hook);
        this.auth = auth;
      }
    } else {
      const { authStrategy, ...otherOptions } = options;
      const auth = authStrategy(
        Object.assign(
          {
            request: this.request,
            log: this.log,
            // we pass the current octokit instance as well as its constructor options
            // to allow for authentication strategies that return a new octokit instance
            // that shares the same internal state as the current one. The original
            // requirement for this was the "event-octokit" authentication strategy
            // of https://github.com/probot/octokit-auth-probot.
            octokit: this,
            octokitOptions: otherOptions
          },
          options.auth
        )
      );
      hook.wrap("request", auth.hook);
      this.auth = auth;
    }
    const classConstructor = this.constructor;
    for (let i = 0; i < classConstructor.plugins.length; ++i) {
      Object.assign(this, classConstructor.plugins[i](this, options));
    }
  }
};


;// ./node_modules/@octokit/plugin-request-log/dist-web/index.js
// pkg/dist-src/version.js
var plugin_request_log_dist_web_VERSION = "4.0.1";

// pkg/dist-src/index.js
function requestLog(octokit) {
  octokit.hook.wrap("request", (request, options) => {
    octokit.log.debug("request", options);
    const start = Date.now();
    const requestOptions = octokit.request.endpoint.parse(options);
    const path = requestOptions.url.replace(options.baseUrl, "");
    return request(options).then((response) => {
      octokit.log.info(
        `${requestOptions.method} ${path} - ${response.status} in ${Date.now() - start}ms`
      );
      return response;
    }).catch((error) => {
      octokit.log.info(
        `${requestOptions.method} ${path} - ${error.status} in ${Date.now() - start}ms`
      );
      throw error;
    });
  });
}
requestLog.VERSION = plugin_request_log_dist_web_VERSION;


;// ./node_modules/@octokit/plugin-paginate-rest/dist-web/index.js
// pkg/dist-src/version.js
var plugin_paginate_rest_dist_web_VERSION = "11.4.4-cjs.2";

// pkg/dist-src/normalize-paginated-list-response.js
function normalizePaginatedListResponse(response) {
  if (!response.data) {
    return {
      ...response,
      data: []
    };
  }
  const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
  if (!responseNeedsNormalization) return response;
  const incompleteResults = response.data.incomplete_results;
  const repositorySelection = response.data.repository_selection;
  const totalCount = response.data.total_count;
  delete response.data.incomplete_results;
  delete response.data.repository_selection;
  delete response.data.total_count;
  const namespaceKey = Object.keys(response.data)[0];
  const data = response.data[namespaceKey];
  response.data = data;
  if (typeof incompleteResults !== "undefined") {
    response.data.incomplete_results = incompleteResults;
  }
  if (typeof repositorySelection !== "undefined") {
    response.data.repository_selection = repositorySelection;
  }
  response.data.total_count = totalCount;
  return response;
}

// pkg/dist-src/iterator.js
function iterator(octokit, route, parameters) {
  const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);
  const requestMethod = typeof route === "function" ? route : octokit.request;
  const method = options.method;
  const headers = options.headers;
  let url = options.url;
  return {
    [Symbol.asyncIterator]: () => ({
      async next() {
        if (!url) return { done: true };
        try {
          const response = await requestMethod({ method, url, headers });
          const normalizedResponse = normalizePaginatedListResponse(response);
          url = ((normalizedResponse.headers.link || "").match(
            /<([^<>]+)>;\s*rel="next"/
          ) || [])[1];
          return { value: normalizedResponse };
        } catch (error) {
          if (error.status !== 409) throw error;
          url = "";
          return {
            value: {
              status: 200,
              headers: {},
              data: []
            }
          };
        }
      }
    })
  };
}

// pkg/dist-src/paginate.js
function paginate(octokit, route, parameters, mapFn) {
  if (typeof parameters === "function") {
    mapFn = parameters;
    parameters = void 0;
  }
  return gather(
    octokit,
    [],
    iterator(octokit, route, parameters)[Symbol.asyncIterator](),
    mapFn
  );
}
function gather(octokit, results, iterator2, mapFn) {
  return iterator2.next().then((result) => {
    if (result.done) {
      return results;
    }
    let earlyExit = false;
    function done() {
      earlyExit = true;
    }
    results = results.concat(
      mapFn ? mapFn(result.value, done) : result.value.data
    );
    if (earlyExit) {
      return results;
    }
    return gather(octokit, results, iterator2, mapFn);
  });
}

// pkg/dist-src/compose-paginate.js
var composePaginateRest = Object.assign(paginate, {
  iterator
});

// pkg/dist-src/generated/paginating-endpoints.js
var paginatingEndpoints = (/* unused pure expression or super */ null && ([
  "GET /advisories",
  "GET /app/hook/deliveries",
  "GET /app/installation-requests",
  "GET /app/installations",
  "GET /assignments/{assignment_id}/accepted_assignments",
  "GET /classrooms",
  "GET /classrooms/{classroom_id}/assignments",
  "GET /enterprises/{enterprise}/code-security/configurations",
  "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories",
  "GET /enterprises/{enterprise}/dependabot/alerts",
  "GET /enterprises/{enterprise}/secret-scanning/alerts",
  "GET /events",
  "GET /gists",
  "GET /gists/public",
  "GET /gists/starred",
  "GET /gists/{gist_id}/comments",
  "GET /gists/{gist_id}/commits",
  "GET /gists/{gist_id}/forks",
  "GET /installation/repositories",
  "GET /issues",
  "GET /licenses",
  "GET /marketplace_listing/plans",
  "GET /marketplace_listing/plans/{plan_id}/accounts",
  "GET /marketplace_listing/stubbed/plans",
  "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts",
  "GET /networks/{owner}/{repo}/events",
  "GET /notifications",
  "GET /organizations",
  "GET /orgs/{org}/actions/cache/usage-by-repository",
  "GET /orgs/{org}/actions/permissions/repositories",
  "GET /orgs/{org}/actions/runner-groups",
  "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories",
  "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners",
  "GET /orgs/{org}/actions/runners",
  "GET /orgs/{org}/actions/secrets",
  "GET /orgs/{org}/actions/secrets/{secret_name}/repositories",
  "GET /orgs/{org}/actions/variables",
  "GET /orgs/{org}/actions/variables/{name}/repositories",
  "GET /orgs/{org}/attestations/{subject_digest}",
  "GET /orgs/{org}/blocks",
  "GET /orgs/{org}/code-scanning/alerts",
  "GET /orgs/{org}/code-security/configurations",
  "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories",
  "GET /orgs/{org}/codespaces",
  "GET /orgs/{org}/codespaces/secrets",
  "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories",
  "GET /orgs/{org}/copilot/billing/seats",
  "GET /orgs/{org}/copilot/metrics",
  "GET /orgs/{org}/copilot/usage",
  "GET /orgs/{org}/dependabot/alerts",
  "GET /orgs/{org}/dependabot/secrets",
  "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories",
  "GET /orgs/{org}/events",
  "GET /orgs/{org}/failed_invitations",
  "GET /orgs/{org}/hooks",
  "GET /orgs/{org}/hooks/{hook_id}/deliveries",
  "GET /orgs/{org}/insights/api/route-stats/{actor_type}/{actor_id}",
  "GET /orgs/{org}/insights/api/subject-stats",
  "GET /orgs/{org}/insights/api/user-stats/{user_id}",
  "GET /orgs/{org}/installations",
  "GET /orgs/{org}/invitations",
  "GET /orgs/{org}/invitations/{invitation_id}/teams",
  "GET /orgs/{org}/issues",
  "GET /orgs/{org}/members",
  "GET /orgs/{org}/members/{username}/codespaces",
  "GET /orgs/{org}/migrations",
  "GET /orgs/{org}/migrations/{migration_id}/repositories",
  "GET /orgs/{org}/organization-roles/{role_id}/teams",
  "GET /orgs/{org}/organization-roles/{role_id}/users",
  "GET /orgs/{org}/outside_collaborators",
  "GET /orgs/{org}/packages",
  "GET /orgs/{org}/packages/{package_type}/{package_name}/versions",
  "GET /orgs/{org}/personal-access-token-requests",
  "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories",
  "GET /orgs/{org}/personal-access-tokens",
  "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories",
  "GET /orgs/{org}/private-registries",
  "GET /orgs/{org}/projects",
  "GET /orgs/{org}/properties/values",
  "GET /orgs/{org}/public_members",
  "GET /orgs/{org}/repos",
  "GET /orgs/{org}/rulesets",
  "GET /orgs/{org}/rulesets/rule-suites",
  "GET /orgs/{org}/secret-scanning/alerts",
  "GET /orgs/{org}/security-advisories",
  "GET /orgs/{org}/team/{team_slug}/copilot/metrics",
  "GET /orgs/{org}/team/{team_slug}/copilot/usage",
  "GET /orgs/{org}/teams",
  "GET /orgs/{org}/teams/{team_slug}/discussions",
  "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments",
  "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions",
  "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions",
  "GET /orgs/{org}/teams/{team_slug}/invitations",
  "GET /orgs/{org}/teams/{team_slug}/members",
  "GET /orgs/{org}/teams/{team_slug}/projects",
  "GET /orgs/{org}/teams/{team_slug}/repos",
  "GET /orgs/{org}/teams/{team_slug}/teams",
  "GET /projects/columns/{column_id}/cards",
  "GET /projects/{project_id}/collaborators",
  "GET /projects/{project_id}/columns",
  "GET /repos/{owner}/{repo}/actions/artifacts",
  "GET /repos/{owner}/{repo}/actions/caches",
  "GET /repos/{owner}/{repo}/actions/organization-secrets",
  "GET /repos/{owner}/{repo}/actions/organization-variables",
  "GET /repos/{owner}/{repo}/actions/runners",
  "GET /repos/{owner}/{repo}/actions/runs",
  "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts",
  "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs",
  "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs",
  "GET /repos/{owner}/{repo}/actions/secrets",
  "GET /repos/{owner}/{repo}/actions/variables",
  "GET /repos/{owner}/{repo}/actions/workflows",
  "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs",
  "GET /repos/{owner}/{repo}/activity",
  "GET /repos/{owner}/{repo}/assignees",
  "GET /repos/{owner}/{repo}/attestations/{subject_digest}",
  "GET /repos/{owner}/{repo}/branches",
  "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations",
  "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs",
  "GET /repos/{owner}/{repo}/code-scanning/alerts",
  "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",
  "GET /repos/{owner}/{repo}/code-scanning/analyses",
  "GET /repos/{owner}/{repo}/codespaces",
  "GET /repos/{owner}/{repo}/codespaces/devcontainers",
  "GET /repos/{owner}/{repo}/codespaces/secrets",
  "GET /repos/{owner}/{repo}/collaborators",
  "GET /repos/{owner}/{repo}/comments",
  "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions",
  "GET /repos/{owner}/{repo}/commits",
  "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments",
  "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls",
  "GET /repos/{owner}/{repo}/commits/{ref}/check-runs",
  "GET /repos/{owner}/{repo}/commits/{ref}/check-suites",
  "GET /repos/{owner}/{repo}/commits/{ref}/status",
  "GET /repos/{owner}/{repo}/commits/{ref}/statuses",
  "GET /repos/{owner}/{repo}/contributors",
  "GET /repos/{owner}/{repo}/dependabot/alerts",
  "GET /repos/{owner}/{repo}/dependabot/secrets",
  "GET /repos/{owner}/{repo}/deployments",
  "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses",
  "GET /repos/{owner}/{repo}/environments",
  "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies",
  "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps",
  "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets",
  "GET /repos/{owner}/{repo}/environments/{environment_name}/variables",
  "GET /repos/{owner}/{repo}/events",
  "GET /repos/{owner}/{repo}/forks",
  "GET /repos/{owner}/{repo}/hooks",
  "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries",
  "GET /repos/{owner}/{repo}/invitations",
  "GET /repos/{owner}/{repo}/issues",
  "GET /repos/{owner}/{repo}/issues/comments",
  "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions",
  "GET /repos/{owner}/{repo}/issues/events",
  "GET /repos/{owner}/{repo}/issues/{issue_number}/comments",
  "GET /repos/{owner}/{repo}/issues/{issue_number}/events",
  "GET /repos/{owner}/{repo}/issues/{issue_number}/labels",
  "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions",
  "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues",
  "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline",
  "GET /repos/{owner}/{repo}/keys",
  "GET /repos/{owner}/{repo}/labels",
  "GET /repos/{owner}/{repo}/milestones",
  "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels",
  "GET /repos/{owner}/{repo}/notifications",
  "GET /repos/{owner}/{repo}/pages/builds",
  "GET /repos/{owner}/{repo}/projects",
  "GET /repos/{owner}/{repo}/pulls",
  "GET /repos/{owner}/{repo}/pulls/comments",
  "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions",
  "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments",
  "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits",
  "GET /repos/{owner}/{repo}/pulls/{pull_number}/files",
  "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews",
  "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments",
  "GET /repos/{owner}/{repo}/releases",
  "GET /repos/{owner}/{repo}/releases/{release_id}/assets",
  "GET /repos/{owner}/{repo}/releases/{release_id}/reactions",
  "GET /repos/{owner}/{repo}/rules/branches/{branch}",
  "GET /repos/{owner}/{repo}/rulesets",
  "GET /repos/{owner}/{repo}/rulesets/rule-suites",
  "GET /repos/{owner}/{repo}/secret-scanning/alerts",
  "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations",
  "GET /repos/{owner}/{repo}/security-advisories",
  "GET /repos/{owner}/{repo}/stargazers",
  "GET /repos/{owner}/{repo}/subscribers",
  "GET /repos/{owner}/{repo}/tags",
  "GET /repos/{owner}/{repo}/teams",
  "GET /repos/{owner}/{repo}/topics",
  "GET /repositories",
  "GET /search/code",
  "GET /search/commits",
  "GET /search/issues",
  "GET /search/labels",
  "GET /search/repositories",
  "GET /search/topics",
  "GET /search/users",
  "GET /teams/{team_id}/discussions",
  "GET /teams/{team_id}/discussions/{discussion_number}/comments",
  "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions",
  "GET /teams/{team_id}/discussions/{discussion_number}/reactions",
  "GET /teams/{team_id}/invitations",
  "GET /teams/{team_id}/members",
  "GET /teams/{team_id}/projects",
  "GET /teams/{team_id}/repos",
  "GET /teams/{team_id}/teams",
  "GET /user/blocks",
  "GET /user/codespaces",
  "GET /user/codespaces/secrets",
  "GET /user/emails",
  "GET /user/followers",
  "GET /user/following",
  "GET /user/gpg_keys",
  "GET /user/installations",
  "GET /user/installations/{installation_id}/repositories",
  "GET /user/issues",
  "GET /user/keys",
  "GET /user/marketplace_purchases",
  "GET /user/marketplace_purchases/stubbed",
  "GET /user/memberships/orgs",
  "GET /user/migrations",
  "GET /user/migrations/{migration_id}/repositories",
  "GET /user/orgs",
  "GET /user/packages",
  "GET /user/packages/{package_type}/{package_name}/versions",
  "GET /user/public_emails",
  "GET /user/repos",
  "GET /user/repository_invitations",
  "GET /user/social_accounts",
  "GET /user/ssh_signing_keys",
  "GET /user/starred",
  "GET /user/subscriptions",
  "GET /user/teams",
  "GET /users",
  "GET /users/{username}/attestations/{subject_digest}",
  "GET /users/{username}/events",
  "GET /users/{username}/events/orgs/{org}",
  "GET /users/{username}/events/public",
  "GET /users/{username}/followers",
  "GET /users/{username}/following",
  "GET /users/{username}/gists",
  "GET /users/{username}/gpg_keys",
  "GET /users/{username}/keys",
  "GET /users/{username}/orgs",
  "GET /users/{username}/packages",
  "GET /users/{username}/projects",
  "GET /users/{username}/received_events",
  "GET /users/{username}/received_events/public",
  "GET /users/{username}/repos",
  "GET /users/{username}/social_accounts",
  "GET /users/{username}/ssh_signing_keys",
  "GET /users/{username}/starred",
  "GET /users/{username}/subscriptions"
]));

// pkg/dist-src/paginating-endpoints.js
function isPaginatingEndpoint(arg) {
  if (typeof arg === "string") {
    return paginatingEndpoints.includes(arg);
  } else {
    return false;
  }
}

// pkg/dist-src/index.js
function paginateRest(octokit) {
  return {
    paginate: Object.assign(paginate.bind(null, octokit), {
      iterator: iterator.bind(null, octokit)
    })
  };
}
paginateRest.VERSION = plugin_paginate_rest_dist_web_VERSION;


;// ./node_modules/@octokit/plugin-rest-endpoint-methods/dist-web/index.js
// pkg/dist-src/version.js
var plugin_rest_endpoint_methods_dist_web_VERSION = "13.3.2-cjs.1";

// pkg/dist-src/generated/endpoints.js
var Endpoints = {
  actions: {
    addCustomLabelsToSelfHostedRunnerForOrg: [
      "POST /orgs/{org}/actions/runners/{runner_id}/labels"
    ],
    addCustomLabelsToSelfHostedRunnerForRepo: [
      "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"
    ],
    addRepoAccessToSelfHostedRunnerGroupInOrg: [
      "PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}"
    ],
    addSelectedRepoToOrgSecret: [
      "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"
    ],
    addSelectedRepoToOrgVariable: [
      "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"
    ],
    approveWorkflowRun: [
      "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"
    ],
    cancelWorkflowRun: [
      "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"
    ],
    createEnvironmentVariable: [
      "POST /repos/{owner}/{repo}/environments/{environment_name}/variables"
    ],
    createOrUpdateEnvironmentSecret: [
      "PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"
    ],
    createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"],
    createOrUpdateRepoSecret: [
      "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"
    ],
    createOrgVariable: ["POST /orgs/{org}/actions/variables"],
    createRegistrationTokenForOrg: [
      "POST /orgs/{org}/actions/runners/registration-token"
    ],
    createRegistrationTokenForRepo: [
      "POST /repos/{owner}/{repo}/actions/runners/registration-token"
    ],
    createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"],
    createRemoveTokenForRepo: [
      "POST /repos/{owner}/{repo}/actions/runners/remove-token"
    ],
    createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"],
    createWorkflowDispatch: [
      "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"
    ],
    deleteActionsCacheById: [
      "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}"
    ],
    deleteActionsCacheByKey: [
      "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}"
    ],
    deleteArtifact: [
      "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"
    ],
    deleteEnvironmentSecret: [
      "DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"
    ],
    deleteEnvironmentVariable: [
      "DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"
    ],
    deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"],
    deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"],
    deleteRepoSecret: [
      "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"
    ],
    deleteRepoVariable: [
      "DELETE /repos/{owner}/{repo}/actions/variables/{name}"
    ],
    deleteSelfHostedRunnerFromOrg: [
      "DELETE /orgs/{org}/actions/runners/{runner_id}"
    ],
    deleteSelfHostedRunnerFromRepo: [
      "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"
    ],
    deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"],
    deleteWorkflowRunLogs: [
      "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"
    ],
    disableSelectedRepositoryGithubActionsOrganization: [
      "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"
    ],
    disableWorkflow: [
      "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"
    ],
    downloadArtifact: [
      "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"
    ],
    downloadJobLogsForWorkflowRun: [
      "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"
    ],
    downloadWorkflowRunAttemptLogs: [
      "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs"
    ],
    downloadWorkflowRunLogs: [
      "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"
    ],
    enableSelectedRepositoryGithubActionsOrganization: [
      "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"
    ],
    enableWorkflow: [
      "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"
    ],
    forceCancelWorkflowRun: [
      "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel"
    ],
    generateRunnerJitconfigForOrg: [
      "POST /orgs/{org}/actions/runners/generate-jitconfig"
    ],
    generateRunnerJitconfigForRepo: [
      "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig"
    ],
    getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"],
    getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"],
    getActionsCacheUsageByRepoForOrg: [
      "GET /orgs/{org}/actions/cache/usage-by-repository"
    ],
    getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"],
    getAllowedActionsOrganization: [
      "GET /orgs/{org}/actions/permissions/selected-actions"
    ],
    getAllowedActionsRepository: [
      "GET /repos/{owner}/{repo}/actions/permissions/selected-actions"
    ],
    getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"],
    getCustomOidcSubClaimForRepo: [
      "GET /repos/{owner}/{repo}/actions/oidc/customization/sub"
    ],
    getEnvironmentPublicKey: [
      "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key"
    ],
    getEnvironmentSecret: [
      "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}"
    ],
    getEnvironmentVariable: [
      "GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"
    ],
    getGithubActionsDefaultWorkflowPermissionsOrganization: [
      "GET /orgs/{org}/actions/permissions/workflow"
    ],
    getGithubActionsDefaultWorkflowPermissionsRepository: [
      "GET /repos/{owner}/{repo}/actions/permissions/workflow"
    ],
    getGithubActionsPermissionsOrganization: [
      "GET /orgs/{org}/actions/permissions"
    ],
    getGithubActionsPermissionsRepository: [
      "GET /repos/{owner}/{repo}/actions/permissions"
    ],
    getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"],
    getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"],
    getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"],
    getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"],
    getPendingDeploymentsForRun: [
      "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"
    ],
    getRepoPermissions: [
      "GET /repos/{owner}/{repo}/actions/permissions",
      {},
      { renamed: ["actions", "getGithubActionsPermissionsRepository"] }
    ],
    getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"],
    getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"],
    getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"],
    getReviewsForRun: [
      "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"
    ],
    getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"],
    getSelfHostedRunnerForRepo: [
      "GET /repos/{owner}/{repo}/actions/runners/{runner_id}"
    ],
    getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"],
    getWorkflowAccessToRepository: [
      "GET /repos/{owner}/{repo}/actions/permissions/access"
    ],
    getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"],
    getWorkflowRunAttempt: [
      "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"
    ],
    getWorkflowRunUsage: [
      "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"
    ],
    getWorkflowUsage: [
      "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"
    ],
    listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"],
    listEnvironmentSecrets: [
      "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets"
    ],
    listEnvironmentVariables: [
      "GET /repos/{owner}/{repo}/environments/{environment_name}/variables"
    ],
    listJobsForWorkflowRun: [
      "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"
    ],
    listJobsForWorkflowRunAttempt: [
      "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"
    ],
    listLabelsForSelfHostedRunnerForOrg: [
      "GET /orgs/{org}/actions/runners/{runner_id}/labels"
    ],
    listLabelsForSelfHostedRunnerForRepo: [
      "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"
    ],
    listOrgSecrets: ["GET /orgs/{org}/actions/secrets"],
    listOrgVariables: ["GET /orgs/{org}/actions/variables"],
    listRepoOrganizationSecrets: [
      "GET /repos/{owner}/{repo}/actions/organization-secrets"
    ],
    listRepoOrganizationVariables: [
      "GET /repos/{owner}/{repo}/actions/organization-variables"
    ],
    listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"],
    listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"],
    listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"],
    listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"],
    listRunnerApplicationsForRepo: [
      "GET /repos/{owner}/{repo}/actions/runners/downloads"
    ],
    listSelectedReposForOrgSecret: [
      "GET /orgs/{org}/actions/secrets/{secret_name}/repositories"
    ],
    listSelectedReposForOrgVariable: [
      "GET /orgs/{org}/actions/variables/{name}/repositories"
    ],
    listSelectedRepositoriesEnabledGithubActionsOrganization: [
      "GET /orgs/{org}/actions/permissions/repositories"
    ],
    listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"],
    listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"],
    listWorkflowRunArtifacts: [
      "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"
    ],
    listWorkflowRuns: [
      "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"
    ],
    listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"],
    reRunJobForWorkflowRun: [
      "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun"
    ],
    reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"],
    reRunWorkflowFailedJobs: [
      "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs"
    ],
    removeAllCustomLabelsFromSelfHostedRunnerForOrg: [
      "DELETE /orgs/{org}/actions/runners/{runner_id}/labels"
    ],
    removeAllCustomLabelsFromSelfHostedRunnerForRepo: [
      "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"
    ],
    removeCustomLabelFromSelfHostedRunnerForOrg: [
      "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}"
    ],
    removeCustomLabelFromSelfHostedRunnerForRepo: [
      "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}"
    ],
    removeSelectedRepoFromOrgSecret: [
      "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"
    ],
    removeSelectedRepoFromOrgVariable: [
      "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}"
    ],
    reviewCustomGatesForRun: [
      "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule"
    ],
    reviewPendingDeploymentsForRun: [
      "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"
    ],
    setAllowedActionsOrganization: [
      "PUT /orgs/{org}/actions/permissions/selected-actions"
    ],
    setAllowedActionsRepository: [
      "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"
    ],
    setCustomLabelsForSelfHostedRunnerForOrg: [
      "PUT /orgs/{org}/actions/runners/{runner_id}/labels"
    ],
    setCustomLabelsForSelfHostedRunnerForRepo: [
      "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels"
    ],
    setCustomOidcSubClaimForRepo: [
      "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub"
    ],
    setGithubActionsDefaultWorkflowPermissionsOrganization: [
      "PUT /orgs/{org}/actions/permissions/workflow"
    ],
    setGithubActionsDefaultWorkflowPermissionsRepository: [
      "PUT /repos/{owner}/{repo}/actions/permissions/workflow"
    ],
    setGithubActionsPermissionsOrganization: [
      "PUT /orgs/{org}/actions/permissions"
    ],
    setGithubActionsPermissionsRepository: [
      "PUT /repos/{owner}/{repo}/actions/permissions"
    ],
    setSelectedReposForOrgSecret: [
      "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"
    ],
    setSelectedReposForOrgVariable: [
      "PUT /orgs/{org}/actions/variables/{name}/repositories"
    ],
    setSelectedRepositoriesEnabledGithubActionsOrganization: [
      "PUT /orgs/{org}/actions/permissions/repositories"
    ],
    setWorkflowAccessToRepository: [
      "PUT /repos/{owner}/{repo}/actions/permissions/access"
    ],
    updateEnvironmentVariable: [
      "PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}"
    ],
    updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"],
    updateRepoVariable: [
      "PATCH /repos/{owner}/{repo}/actions/variables/{name}"
    ]
  },
  activity: {
    checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"],
    deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"],
    deleteThreadSubscription: [
      "DELETE /notifications/threads/{thread_id}/subscription"
    ],
    getFeeds: ["GET /feeds"],
    getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"],
    getThread: ["GET /notifications/threads/{thread_id}"],
    getThreadSubscriptionForAuthenticatedUser: [
      "GET /notifications/threads/{thread_id}/subscription"
    ],
    listEventsForAuthenticatedUser: ["GET /users/{username}/events"],
    listNotificationsForAuthenticatedUser: ["GET /notifications"],
    listOrgEventsForAuthenticatedUser: [
      "GET /users/{username}/events/orgs/{org}"
    ],
    listPublicEvents: ["GET /events"],
    listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"],
    listPublicEventsForUser: ["GET /users/{username}/events/public"],
    listPublicOrgEvents: ["GET /orgs/{org}/events"],
    listReceivedEventsForUser: ["GET /users/{username}/received_events"],
    listReceivedPublicEventsForUser: [
      "GET /users/{username}/received_events/public"
    ],
    listRepoEvents: ["GET /repos/{owner}/{repo}/events"],
    listRepoNotificationsForAuthenticatedUser: [
      "GET /repos/{owner}/{repo}/notifications"
    ],
    listReposStarredByAuthenticatedUser: ["GET /user/starred"],
    listReposStarredByUser: ["GET /users/{username}/starred"],
    listReposWatchedByUser: ["GET /users/{username}/subscriptions"],
    listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"],
    listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"],
    listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"],
    markNotificationsAsRead: ["PUT /notifications"],
    markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"],
    markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"],
    markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"],
    setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"],
    setThreadSubscription: [
      "PUT /notifications/threads/{thread_id}/subscription"
    ],
    starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"],
    unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"]
  },
  apps: {
    addRepoToInstallation: [
      "PUT /user/installations/{installation_id}/repositories/{repository_id}",
      {},
      { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] }
    ],
    addRepoToInstallationForAuthenticatedUser: [
      "PUT /user/installations/{installation_id}/repositories/{repository_id}"
    ],
    checkToken: ["POST /applications/{client_id}/token"],
    createFromManifest: ["POST /app-manifests/{code}/conversions"],
    createInstallationAccessToken: [
      "POST /app/installations/{installation_id}/access_tokens"
    ],
    deleteAuthorization: ["DELETE /applications/{client_id}/grant"],
    deleteInstallation: ["DELETE /app/installations/{installation_id}"],
    deleteToken: ["DELETE /applications/{client_id}/token"],
    getAuthenticated: ["GET /app"],
    getBySlug: ["GET /apps/{app_slug}"],
    getInstallation: ["GET /app/installations/{installation_id}"],
    getOrgInstallation: ["GET /orgs/{org}/installation"],
    getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"],
    getSubscriptionPlanForAccount: [
      "GET /marketplace_listing/accounts/{account_id}"
    ],
    getSubscriptionPlanForAccountStubbed: [
      "GET /marketplace_listing/stubbed/accounts/{account_id}"
    ],
    getUserInstallation: ["GET /users/{username}/installation"],
    getWebhookConfigForApp: ["GET /app/hook/config"],
    getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"],
    listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"],
    listAccountsForPlanStubbed: [
      "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"
    ],
    listInstallationReposForAuthenticatedUser: [
      "GET /user/installations/{installation_id}/repositories"
    ],
    listInstallationRequestsForAuthenticatedApp: [
      "GET /app/installation-requests"
    ],
    listInstallations: ["GET /app/installations"],
    listInstallationsForAuthenticatedUser: ["GET /user/installations"],
    listPlans: ["GET /marketplace_listing/plans"],
    listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"],
    listReposAccessibleToInstallation: ["GET /installation/repositories"],
    listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"],
    listSubscriptionsForAuthenticatedUserStubbed: [
      "GET /user/marketplace_purchases/stubbed"
    ],
    listWebhookDeliveries: ["GET /app/hook/deliveries"],
    redeliverWebhookDelivery: [
      "POST /app/hook/deliveries/{delivery_id}/attempts"
    ],
    removeRepoFromInstallation: [
      "DELETE /user/installations/{installation_id}/repositories/{repository_id}",
      {},
      { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] }
    ],
    removeRepoFromInstallationForAuthenticatedUser: [
      "DELETE /user/installations/{installation_id}/repositories/{repository_id}"
    ],
    resetToken: ["PATCH /applications/{client_id}/token"],
    revokeInstallationAccessToken: ["DELETE /installation/token"],
    scopeToken: ["POST /applications/{client_id}/token/scoped"],
    suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"],
    unsuspendInstallation: [
      "DELETE /app/installations/{installation_id}/suspended"
    ],
    updateWebhookConfigForApp: ["PATCH /app/hook/config"]
  },
  billing: {
    getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"],
    getGithubActionsBillingUser: [
      "GET /users/{username}/settings/billing/actions"
    ],
    getGithubBillingUsageReportOrg: [
      "GET /organizations/{org}/settings/billing/usage"
    ],
    getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"],
    getGithubPackagesBillingUser: [
      "GET /users/{username}/settings/billing/packages"
    ],
    getSharedStorageBillingOrg: [
      "GET /orgs/{org}/settings/billing/shared-storage"
    ],
    getSharedStorageBillingUser: [
      "GET /users/{username}/settings/billing/shared-storage"
    ]
  },
  checks: {
    create: ["POST /repos/{owner}/{repo}/check-runs"],
    createSuite: ["POST /repos/{owner}/{repo}/check-suites"],
    get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"],
    getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"],
    listAnnotations: [
      "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"
    ],
    listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"],
    listForSuite: [
      "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"
    ],
    listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"],
    rerequestRun: [
      "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest"
    ],
    rerequestSuite: [
      "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"
    ],
    setSuitesPreferences: [
      "PATCH /repos/{owner}/{repo}/check-suites/preferences"
    ],
    update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"]
  },
  codeScanning: {
    commitAutofix: [
      "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits"
    ],
    createAutofix: [
      "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"
    ],
    createVariantAnalysis: [
      "POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses"
    ],
    deleteAnalysis: [
      "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"
    ],
    deleteCodeqlDatabase: [
      "DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"
    ],
    getAlert: [
      "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}",
      {},
      { renamedParameters: { alert_id: "alert_number" } }
    ],
    getAnalysis: [
      "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"
    ],
    getAutofix: [
      "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix"
    ],
    getCodeqlDatabase: [
      "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}"
    ],
    getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"],
    getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"],
    getVariantAnalysis: [
      "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}"
    ],
    getVariantAnalysisRepoTask: [
      "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}"
    ],
    listAlertInstances: [
      "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"
    ],
    listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"],
    listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"],
    listAlertsInstances: [
      "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",
      {},
      { renamed: ["codeScanning", "listAlertInstances"] }
    ],
    listCodeqlDatabases: [
      "GET /repos/{owner}/{repo}/code-scanning/codeql/databases"
    ],
    listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"],
    updateAlert: [
      "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"
    ],
    updateDefaultSetup: [
      "PATCH /repos/{owner}/{repo}/code-scanning/default-setup"
    ],
    uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"]
  },
  codeSecurity: {
    attachConfiguration: [
      "POST /orgs/{org}/code-security/configurations/{configuration_id}/attach"
    ],
    attachEnterpriseConfiguration: [
      "POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach"
    ],
    createConfiguration: ["POST /orgs/{org}/code-security/configurations"],
    createConfigurationForEnterprise: [
      "POST /enterprises/{enterprise}/code-security/configurations"
    ],
    deleteConfiguration: [
      "DELETE /orgs/{org}/code-security/configurations/{configuration_id}"
    ],
    deleteConfigurationForEnterprise: [
      "DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}"
    ],
    detachConfiguration: [
      "DELETE /orgs/{org}/code-security/configurations/detach"
    ],
    getConfiguration: [
      "GET /orgs/{org}/code-security/configurations/{configuration_id}"
    ],
    getConfigurationForRepository: [
      "GET /repos/{owner}/{repo}/code-security-configuration"
    ],
    getConfigurationsForEnterprise: [
      "GET /enterprises/{enterprise}/code-security/configurations"
    ],
    getConfigurationsForOrg: ["GET /orgs/{org}/code-security/configurations"],
    getDefaultConfigurations: [
      "GET /orgs/{org}/code-security/configurations/defaults"
    ],
    getDefaultConfigurationsForEnterprise: [
      "GET /enterprises/{enterprise}/code-security/configurations/defaults"
    ],
    getRepositoriesForConfiguration: [
      "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories"
    ],
    getRepositoriesForEnterpriseConfiguration: [
      "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories"
    ],
    getSingleConfigurationForEnterprise: [
      "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}"
    ],
    setConfigurationAsDefault: [
      "PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults"
    ],
    setConfigurationAsDefaultForEnterprise: [
      "PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults"
    ],
    updateConfiguration: [
      "PATCH /orgs/{org}/code-security/configurations/{configuration_id}"
    ],
    updateEnterpriseConfiguration: [
      "PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}"
    ]
  },
  codesOfConduct: {
    getAllCodesOfConduct: ["GET /codes_of_conduct"],
    getConductCode: ["GET /codes_of_conduct/{key}"]
  },
  codespaces: {
    addRepositoryForSecretForAuthenticatedUser: [
      "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"
    ],
    addSelectedRepoToOrgSecret: [
      "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"
    ],
    checkPermissionsForDevcontainer: [
      "GET /repos/{owner}/{repo}/codespaces/permissions_check"
    ],
    codespaceMachinesForAuthenticatedUser: [
      "GET /user/codespaces/{codespace_name}/machines"
    ],
    createForAuthenticatedUser: ["POST /user/codespaces"],
    createOrUpdateOrgSecret: [
      "PUT /orgs/{org}/codespaces/secrets/{secret_name}"
    ],
    createOrUpdateRepoSecret: [
      "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"
    ],
    createOrUpdateSecretForAuthenticatedUser: [
      "PUT /user/codespaces/secrets/{secret_name}"
    ],
    createWithPrForAuthenticatedUser: [
      "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces"
    ],
    createWithRepoForAuthenticatedUser: [
      "POST /repos/{owner}/{repo}/codespaces"
    ],
    deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"],
    deleteFromOrganization: [
      "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}"
    ],
    deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"],
    deleteRepoSecret: [
      "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"
    ],
    deleteSecretForAuthenticatedUser: [
      "DELETE /user/codespaces/secrets/{secret_name}"
    ],
    exportForAuthenticatedUser: [
      "POST /user/codespaces/{codespace_name}/exports"
    ],
    getCodespacesForUserInOrg: [
      "GET /orgs/{org}/members/{username}/codespaces"
    ],
    getExportDetailsForAuthenticatedUser: [
      "GET /user/codespaces/{codespace_name}/exports/{export_id}"
    ],
    getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"],
    getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"],
    getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"],
    getPublicKeyForAuthenticatedUser: [
      "GET /user/codespaces/secrets/public-key"
    ],
    getRepoPublicKey: [
      "GET /repos/{owner}/{repo}/codespaces/secrets/public-key"
    ],
    getRepoSecret: [
      "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}"
    ],
    getSecretForAuthenticatedUser: [
      "GET /user/codespaces/secrets/{secret_name}"
    ],
    listDevcontainersInRepositoryForAuthenticatedUser: [
      "GET /repos/{owner}/{repo}/codespaces/devcontainers"
    ],
    listForAuthenticatedUser: ["GET /user/codespaces"],
    listInOrganization: [
      "GET /orgs/{org}/codespaces",
      {},
      { renamedParameters: { org_id: "org" } }
    ],
    listInRepositoryForAuthenticatedUser: [
      "GET /repos/{owner}/{repo}/codespaces"
    ],
    listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"],
    listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"],
    listRepositoriesForSecretForAuthenticatedUser: [
      "GET /user/codespaces/secrets/{secret_name}/repositories"
    ],
    listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"],
    listSelectedReposForOrgSecret: [
      "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories"
    ],
    preFlightWithRepoForAuthenticatedUser: [
      "GET /repos/{owner}/{repo}/codespaces/new"
    ],
    publishForAuthenticatedUser: [
      "POST /user/codespaces/{codespace_name}/publish"
    ],
    removeRepositoryForSecretForAuthenticatedUser: [
      "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}"
    ],
    removeSelectedRepoFromOrgSecret: [
      "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}"
    ],
    repoMachinesForAuthenticatedUser: [
      "GET /repos/{owner}/{repo}/codespaces/machines"
    ],
    setRepositoriesForSecretForAuthenticatedUser: [
      "PUT /user/codespaces/secrets/{secret_name}/repositories"
    ],
    setSelectedReposForOrgSecret: [
      "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories"
    ],
    startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"],
    stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"],
    stopInOrganization: [
      "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop"
    ],
    updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"]
  },
  copilot: {
    addCopilotSeatsForTeams: [
      "POST /orgs/{org}/copilot/billing/selected_teams"
    ],
    addCopilotSeatsForUsers: [
      "POST /orgs/{org}/copilot/billing/selected_users"
    ],
    cancelCopilotSeatAssignmentForTeams: [
      "DELETE /orgs/{org}/copilot/billing/selected_teams"
    ],
    cancelCopilotSeatAssignmentForUsers: [
      "DELETE /orgs/{org}/copilot/billing/selected_users"
    ],
    copilotMetricsForOrganization: ["GET /orgs/{org}/copilot/metrics"],
    copilotMetricsForTeam: ["GET /orgs/{org}/team/{team_slug}/copilot/metrics"],
    getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"],
    getCopilotSeatDetailsForUser: [
      "GET /orgs/{org}/members/{username}/copilot"
    ],
    listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"],
    usageMetricsForOrg: ["GET /orgs/{org}/copilot/usage"],
    usageMetricsForTeam: ["GET /orgs/{org}/team/{team_slug}/copilot/usage"]
  },
  dependabot: {
    addSelectedRepoToOrgSecret: [
      "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"
    ],
    createOrUpdateOrgSecret: [
      "PUT /orgs/{org}/dependabot/secrets/{secret_name}"
    ],
    createOrUpdateRepoSecret: [
      "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"
    ],
    deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"],
    deleteRepoSecret: [
      "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"
    ],
    getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"],
    getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"],
    getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"],
    getRepoPublicKey: [
      "GET /repos/{owner}/{repo}/dependabot/secrets/public-key"
    ],
    getRepoSecret: [
      "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}"
    ],
    listAlertsForEnterprise: [
      "GET /enterprises/{enterprise}/dependabot/alerts"
    ],
    listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"],
    listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"],
    listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"],
    listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"],
    listSelectedReposForOrgSecret: [
      "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories"
    ],
    removeSelectedRepoFromOrgSecret: [
      "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}"
    ],
    setSelectedReposForOrgSecret: [
      "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories"
    ],
    updateAlert: [
      "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"
    ]
  },
  dependencyGraph: {
    createRepositorySnapshot: [
      "POST /repos/{owner}/{repo}/dependency-graph/snapshots"
    ],
    diffRange: [
      "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}"
    ],
    exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"]
  },
  emojis: { get: ["GET /emojis"] },
  gists: {
    checkIsStarred: ["GET /gists/{gist_id}/star"],
    create: ["POST /gists"],
    createComment: ["POST /gists/{gist_id}/comments"],
    delete: ["DELETE /gists/{gist_id}"],
    deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"],
    fork: ["POST /gists/{gist_id}/forks"],
    get: ["GET /gists/{gist_id}"],
    getComment: ["GET /gists/{gist_id}/comments/{comment_id}"],
    getRevision: ["GET /gists/{gist_id}/{sha}"],
    list: ["GET /gists"],
    listComments: ["GET /gists/{gist_id}/comments"],
    listCommits: ["GET /gists/{gist_id}/commits"],
    listForUser: ["GET /users/{username}/gists"],
    listForks: ["GET /gists/{gist_id}/forks"],
    listPublic: ["GET /gists/public"],
    listStarred: ["GET /gists/starred"],
    star: ["PUT /gists/{gist_id}/star"],
    unstar: ["DELETE /gists/{gist_id}/star"],
    update: ["PATCH /gists/{gist_id}"],
    updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"]
  },
  git: {
    createBlob: ["POST /repos/{owner}/{repo}/git/blobs"],
    createCommit: ["POST /repos/{owner}/{repo}/git/commits"],
    createRef: ["POST /repos/{owner}/{repo}/git/refs"],
    createTag: ["POST /repos/{owner}/{repo}/git/tags"],
    createTree: ["POST /repos/{owner}/{repo}/git/trees"],
    deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"],
    getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"],
    getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"],
    getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"],
    getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"],
    getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"],
    listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"],
    updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"]
  },
  gitignore: {
    getAllTemplates: ["GET /gitignore/templates"],
    getTemplate: ["GET /gitignore/templates/{name}"]
  },
  interactions: {
    getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"],
    getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"],
    getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"],
    getRestrictionsForYourPublicRepos: [
      "GET /user/interaction-limits",
      {},
      { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] }
    ],
    removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"],
    removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"],
    removeRestrictionsForRepo: [
      "DELETE /repos/{owner}/{repo}/interaction-limits"
    ],
    removeRestrictionsForYourPublicRepos: [
      "DELETE /user/interaction-limits",
      {},
      { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] }
    ],
    setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"],
    setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"],
    setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"],
    setRestrictionsForYourPublicRepos: [
      "PUT /user/interaction-limits",
      {},
      { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] }
    ]
  },
  issues: {
    addAssignees: [
      "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"
    ],
    addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"],
    addSubIssue: [
      "POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"
    ],
    checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"],
    checkUserCanBeAssignedToIssue: [
      "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}"
    ],
    create: ["POST /repos/{owner}/{repo}/issues"],
    createComment: [
      "POST /repos/{owner}/{repo}/issues/{issue_number}/comments"
    ],
    createLabel: ["POST /repos/{owner}/{repo}/labels"],
    createMilestone: ["POST /repos/{owner}/{repo}/milestones"],
    deleteComment: [
      "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"
    ],
    deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"],
    deleteMilestone: [
      "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"
    ],
    get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"],
    getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"],
    getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"],
    getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"],
    getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"],
    list: ["GET /issues"],
    listAssignees: ["GET /repos/{owner}/{repo}/assignees"],
    listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"],
    listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"],
    listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"],
    listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"],
    listEventsForTimeline: [
      "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline"
    ],
    listForAuthenticatedUser: ["GET /user/issues"],
    listForOrg: ["GET /orgs/{org}/issues"],
    listForRepo: ["GET /repos/{owner}/{repo}/issues"],
    listLabelsForMilestone: [
      "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"
    ],
    listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"],
    listLabelsOnIssue: [
      "GET /repos/{owner}/{repo}/issues/{issue_number}/labels"
    ],
    listMilestones: ["GET /repos/{owner}/{repo}/milestones"],
    listSubIssues: [
      "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues"
    ],
    lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"],
    removeAllLabels: [
      "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"
    ],
    removeAssignees: [
      "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"
    ],
    removeLabel: [
      "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"
    ],
    removeSubIssue: [
      "DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue"
    ],
    reprioritizeSubIssue: [
      "PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority"
    ],
    setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"],
    unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"],
    update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"],
    updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"],
    updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"],
    updateMilestone: [
      "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"
    ]
  },
  licenses: {
    get: ["GET /licenses/{license}"],
    getAllCommonlyUsed: ["GET /licenses"],
    getForRepo: ["GET /repos/{owner}/{repo}/license"]
  },
  markdown: {
    render: ["POST /markdown"],
    renderRaw: [
      "POST /markdown/raw",
      { headers: { "content-type": "text/plain; charset=utf-8" } }
    ]
  },
  meta: {
    get: ["GET /meta"],
    getAllVersions: ["GET /versions"],
    getOctocat: ["GET /octocat"],
    getZen: ["GET /zen"],
    root: ["GET /"]
  },
  migrations: {
    deleteArchiveForAuthenticatedUser: [
      "DELETE /user/migrations/{migration_id}/archive"
    ],
    deleteArchiveForOrg: [
      "DELETE /orgs/{org}/migrations/{migration_id}/archive"
    ],
    downloadArchiveForOrg: [
      "GET /orgs/{org}/migrations/{migration_id}/archive"
    ],
    getArchiveForAuthenticatedUser: [
      "GET /user/migrations/{migration_id}/archive"
    ],
    getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"],
    getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"],
    listForAuthenticatedUser: ["GET /user/migrations"],
    listForOrg: ["GET /orgs/{org}/migrations"],
    listReposForAuthenticatedUser: [
      "GET /user/migrations/{migration_id}/repositories"
    ],
    listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"],
    listReposForUser: [
      "GET /user/migrations/{migration_id}/repositories",
      {},
      { renamed: ["migrations", "listReposForAuthenticatedUser"] }
    ],
    startForAuthenticatedUser: ["POST /user/migrations"],
    startForOrg: ["POST /orgs/{org}/migrations"],
    unlockRepoForAuthenticatedUser: [
      "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock"
    ],
    unlockRepoForOrg: [
      "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock"
    ]
  },
  oidc: {
    getOidcCustomSubTemplateForOrg: [
      "GET /orgs/{org}/actions/oidc/customization/sub"
    ],
    updateOidcCustomSubTemplateForOrg: [
      "PUT /orgs/{org}/actions/oidc/customization/sub"
    ]
  },
  orgs: {
    addSecurityManagerTeam: [
      "PUT /orgs/{org}/security-managers/teams/{team_slug}",
      {},
      {
        deprecated: "octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team"
      }
    ],
    assignTeamToOrgRole: [
      "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"
    ],
    assignUserToOrgRole: [
      "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}"
    ],
    blockUser: ["PUT /orgs/{org}/blocks/{username}"],
    cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"],
    checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"],
    checkMembershipForUser: ["GET /orgs/{org}/members/{username}"],
    checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"],
    convertMemberToOutsideCollaborator: [
      "PUT /orgs/{org}/outside_collaborators/{username}"
    ],
    createInvitation: ["POST /orgs/{org}/invitations"],
    createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"],
    createOrUpdateCustomPropertiesValuesForRepos: [
      "PATCH /orgs/{org}/properties/values"
    ],
    createOrUpdateCustomProperty: [
      "PUT /orgs/{org}/properties/schema/{custom_property_name}"
    ],
    createWebhook: ["POST /orgs/{org}/hooks"],
    delete: ["DELETE /orgs/{org}"],
    deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"],
    enableOrDisableSecurityProductOnAllOrgRepos: [
      "POST /orgs/{org}/{security_product}/{enablement}",
      {},
      {
        deprecated: "octokit.rest.orgs.enableOrDisableSecurityProductOnAllOrgRepos() is deprecated, see https://docs.github.com/rest/orgs/orgs#enable-or-disable-a-security-feature-for-an-organization"
      }
    ],
    get: ["GET /orgs/{org}"],
    getAllCustomProperties: ["GET /orgs/{org}/properties/schema"],
    getCustomProperty: [
      "GET /orgs/{org}/properties/schema/{custom_property_name}"
    ],
    getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"],
    getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"],
    getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"],
    getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"],
    getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"],
    getWebhookDelivery: [
      "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"
    ],
    list: ["GET /organizations"],
    listAppInstallations: ["GET /orgs/{org}/installations"],
    listAttestations: ["GET /orgs/{org}/attestations/{subject_digest}"],
    listBlockedUsers: ["GET /orgs/{org}/blocks"],
    listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"],
    listFailedInvitations: ["GET /orgs/{org}/failed_invitations"],
    listForAuthenticatedUser: ["GET /user/orgs"],
    listForUser: ["GET /users/{username}/orgs"],
    listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"],
    listMembers: ["GET /orgs/{org}/members"],
    listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"],
    listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"],
    listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"],
    listOrgRoles: ["GET /orgs/{org}/organization-roles"],
    listOrganizationFineGrainedPermissions: [
      "GET /orgs/{org}/organization-fine-grained-permissions"
    ],
    listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"],
    listPatGrantRepositories: [
      "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories"
    ],
    listPatGrantRequestRepositories: [
      "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories"
    ],
    listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"],
    listPatGrants: ["GET /orgs/{org}/personal-access-tokens"],
    listPendingInvitations: ["GET /orgs/{org}/invitations"],
    listPublicMembers: ["GET /orgs/{org}/public_members"],
    listSecurityManagerTeams: [
      "GET /orgs/{org}/security-managers",
      {},
      {
        deprecated: "octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams"
      }
    ],
    listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"],
    listWebhooks: ["GET /orgs/{org}/hooks"],
    pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"],
    redeliverWebhookDelivery: [
      "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"
    ],
    removeCustomProperty: [
      "DELETE /orgs/{org}/properties/schema/{custom_property_name}"
    ],
    removeMember: ["DELETE /orgs/{org}/members/{username}"],
    removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"],
    removeOutsideCollaborator: [
      "DELETE /orgs/{org}/outside_collaborators/{username}"
    ],
    removePublicMembershipForAuthenticatedUser: [
      "DELETE /orgs/{org}/public_members/{username}"
    ],
    removeSecurityManagerTeam: [
      "DELETE /orgs/{org}/security-managers/teams/{team_slug}",
      {},
      {
        deprecated: "octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team"
      }
    ],
    reviewPatGrantRequest: [
      "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}"
    ],
    reviewPatGrantRequestsInBulk: [
      "POST /orgs/{org}/personal-access-token-requests"
    ],
    revokeAllOrgRolesTeam: [
      "DELETE /orgs/{org}/organization-roles/teams/{team_slug}"
    ],
    revokeAllOrgRolesUser: [
      "DELETE /orgs/{org}/organization-roles/users/{username}"
    ],
    revokeOrgRoleTeam: [
      "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}"
    ],
    revokeOrgRoleUser: [
      "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}"
    ],
    setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"],
    setPublicMembershipForAuthenticatedUser: [
      "PUT /orgs/{org}/public_members/{username}"
    ],
    unblockUser: ["DELETE /orgs/{org}/blocks/{username}"],
    update: ["PATCH /orgs/{org}"],
    updateMembershipForAuthenticatedUser: [
      "PATCH /user/memberships/orgs/{org}"
    ],
    updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"],
    updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"],
    updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"],
    updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"]
  },
  packages: {
    deletePackageForAuthenticatedUser: [
      "DELETE /user/packages/{package_type}/{package_name}"
    ],
    deletePackageForOrg: [
      "DELETE /orgs/{org}/packages/{package_type}/{package_name}"
    ],
    deletePackageForUser: [
      "DELETE /users/{username}/packages/{package_type}/{package_name}"
    ],
    deletePackageVersionForAuthenticatedUser: [
      "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"
    ],
    deletePackageVersionForOrg: [
      "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"
    ],
    deletePackageVersionForUser: [
      "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"
    ],
    getAllPackageVersionsForAPackageOwnedByAnOrg: [
      "GET /orgs/{org}/packages/{package_type}/{package_name}/versions",
      {},
      { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] }
    ],
    getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [
      "GET /user/packages/{package_type}/{package_name}/versions",
      {},
      {
        renamed: [
          "packages",
          "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"
        ]
      }
    ],
    getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [
      "GET /user/packages/{package_type}/{package_name}/versions"
    ],
    getAllPackageVersionsForPackageOwnedByOrg: [
      "GET /orgs/{org}/packages/{package_type}/{package_name}/versions"
    ],
    getAllPackageVersionsForPackageOwnedByUser: [
      "GET /users/{username}/packages/{package_type}/{package_name}/versions"
    ],
    getPackageForAuthenticatedUser: [
      "GET /user/packages/{package_type}/{package_name}"
    ],
    getPackageForOrganization: [
      "GET /orgs/{org}/packages/{package_type}/{package_name}"
    ],
    getPackageForUser: [
      "GET /users/{username}/packages/{package_type}/{package_name}"
    ],
    getPackageVersionForAuthenticatedUser: [
      "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"
    ],
    getPackageVersionForOrganization: [
      "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"
    ],
    getPackageVersionForUser: [
      "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"
    ],
    listDockerMigrationConflictingPackagesForAuthenticatedUser: [
      "GET /user/docker/conflicts"
    ],
    listDockerMigrationConflictingPackagesForOrganization: [
      "GET /orgs/{org}/docker/conflicts"
    ],
    listDockerMigrationConflictingPackagesForUser: [
      "GET /users/{username}/docker/conflicts"
    ],
    listPackagesForAuthenticatedUser: ["GET /user/packages"],
    listPackagesForOrganization: ["GET /orgs/{org}/packages"],
    listPackagesForUser: ["GET /users/{username}/packages"],
    restorePackageForAuthenticatedUser: [
      "POST /user/packages/{package_type}/{package_name}/restore{?token}"
    ],
    restorePackageForOrg: [
      "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"
    ],
    restorePackageForUser: [
      "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"
    ],
    restorePackageVersionForAuthenticatedUser: [
      "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"
    ],
    restorePackageVersionForOrg: [
      "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"
    ],
    restorePackageVersionForUser: [
      "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"
    ]
  },
  privateRegistries: {
    createOrgPrivateRegistry: ["POST /orgs/{org}/private-registries"],
    deleteOrgPrivateRegistry: [
      "DELETE /orgs/{org}/private-registries/{secret_name}"
    ],
    getOrgPrivateRegistry: ["GET /orgs/{org}/private-registries/{secret_name}"],
    getOrgPublicKey: ["GET /orgs/{org}/private-registries/public-key"],
    listOrgPrivateRegistries: ["GET /orgs/{org}/private-registries"],
    updateOrgPrivateRegistry: [
      "PATCH /orgs/{org}/private-registries/{secret_name}"
    ]
  },
  projects: {
    addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"],
    createCard: ["POST /projects/columns/{column_id}/cards"],
    createColumn: ["POST /projects/{project_id}/columns"],
    createForAuthenticatedUser: ["POST /user/projects"],
    createForOrg: ["POST /orgs/{org}/projects"],
    createForRepo: ["POST /repos/{owner}/{repo}/projects"],
    delete: ["DELETE /projects/{project_id}"],
    deleteCard: ["DELETE /projects/columns/cards/{card_id}"],
    deleteColumn: ["DELETE /projects/columns/{column_id}"],
    get: ["GET /projects/{project_id}"],
    getCard: ["GET /projects/columns/cards/{card_id}"],
    getColumn: ["GET /projects/columns/{column_id}"],
    getPermissionForUser: [
      "GET /projects/{project_id}/collaborators/{username}/permission"
    ],
    listCards: ["GET /projects/columns/{column_id}/cards"],
    listCollaborators: ["GET /projects/{project_id}/collaborators"],
    listColumns: ["GET /projects/{project_id}/columns"],
    listForOrg: ["GET /orgs/{org}/projects"],
    listForRepo: ["GET /repos/{owner}/{repo}/projects"],
    listForUser: ["GET /users/{username}/projects"],
    moveCard: ["POST /projects/columns/cards/{card_id}/moves"],
    moveColumn: ["POST /projects/columns/{column_id}/moves"],
    removeCollaborator: [
      "DELETE /projects/{project_id}/collaborators/{username}"
    ],
    update: ["PATCH /projects/{project_id}"],
    updateCard: ["PATCH /projects/columns/cards/{card_id}"],
    updateColumn: ["PATCH /projects/columns/{column_id}"]
  },
  pulls: {
    checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
    create: ["POST /repos/{owner}/{repo}/pulls"],
    createReplyForReviewComment: [
      "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"
    ],
    createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
    createReviewComment: [
      "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"
    ],
    deletePendingReview: [
      "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"
    ],
    deleteReviewComment: [
      "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"
    ],
    dismissReview: [
      "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"
    ],
    get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"],
    getReview: [
      "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"
    ],
    getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"],
    list: ["GET /repos/{owner}/{repo}/pulls"],
    listCommentsForReview: [
      "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"
    ],
    listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"],
    listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"],
    listRequestedReviewers: [
      "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"
    ],
    listReviewComments: [
      "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"
    ],
    listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"],
    listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"],
    merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"],
    removeRequestedReviewers: [
      "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"
    ],
    requestReviewers: [
      "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"
    ],
    submitReview: [
      "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"
    ],
    update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"],
    updateBranch: [
      "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch"
    ],
    updateReview: [
      "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"
    ],
    updateReviewComment: [
      "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"
    ]
  },
  rateLimit: { get: ["GET /rate_limit"] },
  reactions: {
    createForCommitComment: [
      "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions"
    ],
    createForIssue: [
      "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions"
    ],
    createForIssueComment: [
      "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"
    ],
    createForPullRequestReviewComment: [
      "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"
    ],
    createForRelease: [
      "POST /repos/{owner}/{repo}/releases/{release_id}/reactions"
    ],
    createForTeamDiscussionCommentInOrg: [
      "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"
    ],
    createForTeamDiscussionInOrg: [
      "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"
    ],
    deleteForCommitComment: [
      "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}"
    ],
    deleteForIssue: [
      "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}"
    ],
    deleteForIssueComment: [
      "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}"
    ],
    deleteForPullRequestComment: [
      "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}"
    ],
    deleteForRelease: [
      "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}"
    ],
    deleteForTeamDiscussion: [
      "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}"
    ],
    deleteForTeamDiscussionComment: [
      "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}"
    ],
    listForCommitComment: [
      "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions"
    ],
    listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"],
    listForIssueComment: [
      "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions"
    ],
    listForPullRequestReviewComment: [
      "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions"
    ],
    listForRelease: [
      "GET /repos/{owner}/{repo}/releases/{release_id}/reactions"
    ],
    listForTeamDiscussionCommentInOrg: [
      "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions"
    ],
    listForTeamDiscussionInOrg: [
      "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions"
    ]
  },
  repos: {
    acceptInvitation: [
      "PATCH /user/repository_invitations/{invitation_id}",
      {},
      { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] }
    ],
    acceptInvitationForAuthenticatedUser: [
      "PATCH /user/repository_invitations/{invitation_id}"
    ],
    addAppAccessRestrictions: [
      "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",
      {},
      { mapToData: "apps" }
    ],
    addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"],
    addStatusCheckContexts: [
      "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",
      {},
      { mapToData: "contexts" }
    ],
    addTeamAccessRestrictions: [
      "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",
      {},
      { mapToData: "teams" }
    ],
    addUserAccessRestrictions: [
      "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",
      {},
      { mapToData: "users" }
    ],
    cancelPagesDeployment: [
      "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel"
    ],
    checkAutomatedSecurityFixes: [
      "GET /repos/{owner}/{repo}/automated-security-fixes"
    ],
    checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"],
    checkPrivateVulnerabilityReporting: [
      "GET /repos/{owner}/{repo}/private-vulnerability-reporting"
    ],
    checkVulnerabilityAlerts: [
      "GET /repos/{owner}/{repo}/vulnerability-alerts"
    ],
    codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"],
    compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"],
    compareCommitsWithBasehead: [
      "GET /repos/{owner}/{repo}/compare/{basehead}"
    ],
    createAttestation: ["POST /repos/{owner}/{repo}/attestations"],
    createAutolink: ["POST /repos/{owner}/{repo}/autolinks"],
    createCommitComment: [
      "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"
    ],
    createCommitSignatureProtection: [
      "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"
    ],
    createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"],
    createDeployKey: ["POST /repos/{owner}/{repo}/keys"],
    createDeployment: ["POST /repos/{owner}/{repo}/deployments"],
    createDeploymentBranchPolicy: [
      "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"
    ],
    createDeploymentProtectionRule: [
      "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"
    ],
    createDeploymentStatus: [
      "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"
    ],
    createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"],
    createForAuthenticatedUser: ["POST /user/repos"],
    createFork: ["POST /repos/{owner}/{repo}/forks"],
    createInOrg: ["POST /orgs/{org}/repos"],
    createOrUpdateCustomPropertiesValues: [
      "PATCH /repos/{owner}/{repo}/properties/values"
    ],
    createOrUpdateEnvironment: [
      "PUT /repos/{owner}/{repo}/environments/{environment_name}"
    ],
    createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"],
    createOrgRuleset: ["POST /orgs/{org}/rulesets"],
    createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"],
    createPagesSite: ["POST /repos/{owner}/{repo}/pages"],
    createRelease: ["POST /repos/{owner}/{repo}/releases"],
    createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"],
    createUsingTemplate: [
      "POST /repos/{template_owner}/{template_repo}/generate"
    ],
    createWebhook: ["POST /repos/{owner}/{repo}/hooks"],
    declineInvitation: [
      "DELETE /user/repository_invitations/{invitation_id}",
      {},
      { renamed: ["repos", "declineInvitationForAuthenticatedUser"] }
    ],
    declineInvitationForAuthenticatedUser: [
      "DELETE /user/repository_invitations/{invitation_id}"
    ],
    delete: ["DELETE /repos/{owner}/{repo}"],
    deleteAccessRestrictions: [
      "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"
    ],
    deleteAdminBranchProtection: [
      "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"
    ],
    deleteAnEnvironment: [
      "DELETE /repos/{owner}/{repo}/environments/{environment_name}"
    ],
    deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"],
    deleteBranchProtection: [
      "DELETE /repos/{owner}/{repo}/branches/{branch}/protection"
    ],
    deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"],
    deleteCommitSignatureProtection: [
      "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"
    ],
    deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"],
    deleteDeployment: [
      "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"
    ],
    deleteDeploymentBranchPolicy: [
      "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"
    ],
    deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"],
    deleteInvitation: [
      "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"
    ],
    deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"],
    deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"],
    deletePullRequestReviewProtection: [
      "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"
    ],
    deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"],
    deleteReleaseAsset: [
      "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"
    ],
    deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"],
    deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"],
    disableAutomatedSecurityFixes: [
      "DELETE /repos/{owner}/{repo}/automated-security-fixes"
    ],
    disableDeploymentProtectionRule: [
      "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"
    ],
    disablePrivateVulnerabilityReporting: [
      "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting"
    ],
    disableVulnerabilityAlerts: [
      "DELETE /repos/{owner}/{repo}/vulnerability-alerts"
    ],
    downloadArchive: [
      "GET /repos/{owner}/{repo}/zipball/{ref}",
      {},
      { renamed: ["repos", "downloadZipballArchive"] }
    ],
    downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"],
    downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"],
    enableAutomatedSecurityFixes: [
      "PUT /repos/{owner}/{repo}/automated-security-fixes"
    ],
    enablePrivateVulnerabilityReporting: [
      "PUT /repos/{owner}/{repo}/private-vulnerability-reporting"
    ],
    enableVulnerabilityAlerts: [
      "PUT /repos/{owner}/{repo}/vulnerability-alerts"
    ],
    generateReleaseNotes: [
      "POST /repos/{owner}/{repo}/releases/generate-notes"
    ],
    get: ["GET /repos/{owner}/{repo}"],
    getAccessRestrictions: [
      "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"
    ],
    getAdminBranchProtection: [
      "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"
    ],
    getAllDeploymentProtectionRules: [
      "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules"
    ],
    getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"],
    getAllStatusCheckContexts: [
      "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"
    ],
    getAllTopics: ["GET /repos/{owner}/{repo}/topics"],
    getAppsWithAccessToProtectedBranch: [
      "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"
    ],
    getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"],
    getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"],
    getBranchProtection: [
      "GET /repos/{owner}/{repo}/branches/{branch}/protection"
    ],
    getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"],
    getClones: ["GET /repos/{owner}/{repo}/traffic/clones"],
    getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"],
    getCollaboratorPermissionLevel: [
      "GET /repos/{owner}/{repo}/collaborators/{username}/permission"
    ],
    getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"],
    getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"],
    getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"],
    getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"],
    getCommitSignatureProtection: [
      "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures"
    ],
    getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"],
    getContent: ["GET /repos/{owner}/{repo}/contents/{path}"],
    getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"],
    getCustomDeploymentProtectionRule: [
      "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}"
    ],
    getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"],
    getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"],
    getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"],
    getDeploymentBranchPolicy: [
      "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"
    ],
    getDeploymentStatus: [
      "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"
    ],
    getEnvironment: [
      "GET /repos/{owner}/{repo}/environments/{environment_name}"
    ],
    getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"],
    getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"],
    getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"],
    getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"],
    getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"],
    getOrgRulesets: ["GET /orgs/{org}/rulesets"],
    getPages: ["GET /repos/{owner}/{repo}/pages"],
    getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"],
    getPagesDeployment: [
      "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}"
    ],
    getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"],
    getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"],
    getPullRequestReviewProtection: [
      "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"
    ],
    getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"],
    getReadme: ["GET /repos/{owner}/{repo}/readme"],
    getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"],
    getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"],
    getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"],
    getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"],
    getRepoRuleSuite: [
      "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}"
    ],
    getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"],
    getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"],
    getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"],
    getStatusChecksProtection: [
      "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"
    ],
    getTeamsWithAccessToProtectedBranch: [
      "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"
    ],
    getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"],
    getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"],
    getUsersWithAccessToProtectedBranch: [
      "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"
    ],
    getViews: ["GET /repos/{owner}/{repo}/traffic/views"],
    getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"],
    getWebhookConfigForRepo: [
      "GET /repos/{owner}/{repo}/hooks/{hook_id}/config"
    ],
    getWebhookDelivery: [
      "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"
    ],
    listActivities: ["GET /repos/{owner}/{repo}/activity"],
    listAttestations: [
      "GET /repos/{owner}/{repo}/attestations/{subject_digest}"
    ],
    listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"],
    listBranches: ["GET /repos/{owner}/{repo}/branches"],
    listBranchesForHeadCommit: [
      "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head"
    ],
    listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"],
    listCommentsForCommit: [
      "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"
    ],
    listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"],
    listCommitStatusesForRef: [
      "GET /repos/{owner}/{repo}/commits/{ref}/statuses"
    ],
    listCommits: ["GET /repos/{owner}/{repo}/commits"],
    listContributors: ["GET /repos/{owner}/{repo}/contributors"],
    listCustomDeploymentRuleIntegrations: [
      "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps"
    ],
    listDeployKeys: ["GET /repos/{owner}/{repo}/keys"],
    listDeploymentBranchPolicies: [
      "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies"
    ],
    listDeploymentStatuses: [
      "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"
    ],
    listDeployments: ["GET /repos/{owner}/{repo}/deployments"],
    listForAuthenticatedUser: ["GET /user/repos"],
    listForOrg: ["GET /orgs/{org}/repos"],
    listForUser: ["GET /users/{username}/repos"],
    listForks: ["GET /repos/{owner}/{repo}/forks"],
    listInvitations: ["GET /repos/{owner}/{repo}/invitations"],
    listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"],
    listLanguages: ["GET /repos/{owner}/{repo}/languages"],
    listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"],
    listPublic: ["GET /repositories"],
    listPullRequestsAssociatedWithCommit: [
      "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls"
    ],
    listReleaseAssets: [
      "GET /repos/{owner}/{repo}/releases/{release_id}/assets"
    ],
    listReleases: ["GET /repos/{owner}/{repo}/releases"],
    listTags: ["GET /repos/{owner}/{repo}/tags"],
    listTeams: ["GET /repos/{owner}/{repo}/teams"],
    listWebhookDeliveries: [
      "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"
    ],
    listWebhooks: ["GET /repos/{owner}/{repo}/hooks"],
    merge: ["POST /repos/{owner}/{repo}/merges"],
    mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"],
    pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"],
    redeliverWebhookDelivery: [
      "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"
    ],
    removeAppAccessRestrictions: [
      "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",
      {},
      { mapToData: "apps" }
    ],
    removeCollaborator: [
      "DELETE /repos/{owner}/{repo}/collaborators/{username}"
    ],
    removeStatusCheckContexts: [
      "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",
      {},
      { mapToData: "contexts" }
    ],
    removeStatusCheckProtection: [
      "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"
    ],
    removeTeamAccessRestrictions: [
      "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",
      {},
      { mapToData: "teams" }
    ],
    removeUserAccessRestrictions: [
      "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",
      {},
      { mapToData: "users" }
    ],
    renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"],
    replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"],
    requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"],
    setAdminBranchProtection: [
      "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"
    ],
    setAppAccessRestrictions: [
      "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps",
      {},
      { mapToData: "apps" }
    ],
    setStatusCheckContexts: [
      "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts",
      {},
      { mapToData: "contexts" }
    ],
    setTeamAccessRestrictions: [
      "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams",
      {},
      { mapToData: "teams" }
    ],
    setUserAccessRestrictions: [
      "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users",
      {},
      { mapToData: "users" }
    ],
    testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"],
    transfer: ["POST /repos/{owner}/{repo}/transfer"],
    update: ["PATCH /repos/{owner}/{repo}"],
    updateBranchProtection: [
      "PUT /repos/{owner}/{repo}/branches/{branch}/protection"
    ],
    updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"],
    updateDeploymentBranchPolicy: [
      "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}"
    ],
    updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"],
    updateInvitation: [
      "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"
    ],
    updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"],
    updatePullRequestReviewProtection: [
      "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"
    ],
    updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"],
    updateReleaseAsset: [
      "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"
    ],
    updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"],
    updateStatusCheckPotection: [
      "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks",
      {},
      { renamed: ["repos", "updateStatusCheckProtection"] }
    ],
    updateStatusCheckProtection: [
      "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"
    ],
    updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"],
    updateWebhookConfigForRepo: [
      "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"
    ],
    uploadReleaseAsset: [
      "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}",
      { baseUrl: "https://uploads.github.com" }
    ]
  },
  search: {
    code: ["GET /search/code"],
    commits: ["GET /search/commits"],
    issuesAndPullRequests: ["GET /search/issues"],
    labels: ["GET /search/labels"],
    repos: ["GET /search/repositories"],
    topics: ["GET /search/topics"],
    users: ["GET /search/users"]
  },
  secretScanning: {
    createPushProtectionBypass: [
      "POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses"
    ],
    getAlert: [
      "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"
    ],
    getScanHistory: ["GET /repos/{owner}/{repo}/secret-scanning/scan-history"],
    listAlertsForEnterprise: [
      "GET /enterprises/{enterprise}/secret-scanning/alerts"
    ],
    listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"],
    listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"],
    listLocationsForAlert: [
      "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations"
    ],
    updateAlert: [
      "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"
    ]
  },
  securityAdvisories: {
    createFork: [
      "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks"
    ],
    createPrivateVulnerabilityReport: [
      "POST /repos/{owner}/{repo}/security-advisories/reports"
    ],
    createRepositoryAdvisory: [
      "POST /repos/{owner}/{repo}/security-advisories"
    ],
    createRepositoryAdvisoryCveRequest: [
      "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve"
    ],
    getGlobalAdvisory: ["GET /advisories/{ghsa_id}"],
    getRepositoryAdvisory: [
      "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}"
    ],
    listGlobalAdvisories: ["GET /advisories"],
    listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"],
    listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"],
    updateRepositoryAdvisory: [
      "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}"
    ]
  },
  teams: {
    addOrUpdateMembershipForUserInOrg: [
      "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"
    ],
    addOrUpdateProjectPermissionsInOrg: [
      "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}"
    ],
    addOrUpdateRepoPermissionsInOrg: [
      "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"
    ],
    checkPermissionsForProjectInOrg: [
      "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}"
    ],
    checkPermissionsForRepoInOrg: [
      "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"
    ],
    create: ["POST /orgs/{org}/teams"],
    createDiscussionCommentInOrg: [
      "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"
    ],
    createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"],
    deleteDiscussionCommentInOrg: [
      "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"
    ],
    deleteDiscussionInOrg: [
      "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"
    ],
    deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"],
    getByName: ["GET /orgs/{org}/teams/{team_slug}"],
    getDiscussionCommentInOrg: [
      "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"
    ],
    getDiscussionInOrg: [
      "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"
    ],
    getMembershipForUserInOrg: [
      "GET /orgs/{org}/teams/{team_slug}/memberships/{username}"
    ],
    list: ["GET /orgs/{org}/teams"],
    listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"],
    listDiscussionCommentsInOrg: [
      "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"
    ],
    listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"],
    listForAuthenticatedUser: ["GET /user/teams"],
    listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"],
    listPendingInvitationsInOrg: [
      "GET /orgs/{org}/teams/{team_slug}/invitations"
    ],
    listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"],
    listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"],
    removeMembershipForUserInOrg: [
      "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"
    ],
    removeProjectInOrg: [
      "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"
    ],
    removeRepoInOrg: [
      "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"
    ],
    updateDiscussionCommentInOrg: [
      "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"
    ],
    updateDiscussionInOrg: [
      "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"
    ],
    updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"]
  },
  users: {
    addEmailForAuthenticated: [
      "POST /user/emails",
      {},
      { renamed: ["users", "addEmailForAuthenticatedUser"] }
    ],
    addEmailForAuthenticatedUser: ["POST /user/emails"],
    addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"],
    block: ["PUT /user/blocks/{username}"],
    checkBlocked: ["GET /user/blocks/{username}"],
    checkFollowingForUser: ["GET /users/{username}/following/{target_user}"],
    checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"],
    createGpgKeyForAuthenticated: [
      "POST /user/gpg_keys",
      {},
      { renamed: ["users", "createGpgKeyForAuthenticatedUser"] }
    ],
    createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"],
    createPublicSshKeyForAuthenticated: [
      "POST /user/keys",
      {},
      { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] }
    ],
    createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"],
    createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"],
    deleteEmailForAuthenticated: [
      "DELETE /user/emails",
      {},
      { renamed: ["users", "deleteEmailForAuthenticatedUser"] }
    ],
    deleteEmailForAuthenticatedUser: ["DELETE /user/emails"],
    deleteGpgKeyForAuthenticated: [
      "DELETE /user/gpg_keys/{gpg_key_id}",
      {},
      { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] }
    ],
    deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"],
    deletePublicSshKeyForAuthenticated: [
      "DELETE /user/keys/{key_id}",
      {},
      { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] }
    ],
    deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"],
    deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"],
    deleteSshSigningKeyForAuthenticatedUser: [
      "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}"
    ],
    follow: ["PUT /user/following/{username}"],
    getAuthenticated: ["GET /user"],
    getById: ["GET /user/{account_id}"],
    getByUsername: ["GET /users/{username}"],
    getContextForUser: ["GET /users/{username}/hovercard"],
    getGpgKeyForAuthenticated: [
      "GET /user/gpg_keys/{gpg_key_id}",
      {},
      { renamed: ["users", "getGpgKeyForAuthenticatedUser"] }
    ],
    getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"],
    getPublicSshKeyForAuthenticated: [
      "GET /user/keys/{key_id}",
      {},
      { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] }
    ],
    getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"],
    getSshSigningKeyForAuthenticatedUser: [
      "GET /user/ssh_signing_keys/{ssh_signing_key_id}"
    ],
    list: ["GET /users"],
    listAttestations: ["GET /users/{username}/attestations/{subject_digest}"],
    listBlockedByAuthenticated: [
      "GET /user/blocks",
      {},
      { renamed: ["users", "listBlockedByAuthenticatedUser"] }
    ],
    listBlockedByAuthenticatedUser: ["GET /user/blocks"],
    listEmailsForAuthenticated: [
      "GET /user/emails",
      {},
      { renamed: ["users", "listEmailsForAuthenticatedUser"] }
    ],
    listEmailsForAuthenticatedUser: ["GET /user/emails"],
    listFollowedByAuthenticated: [
      "GET /user/following",
      {},
      { renamed: ["users", "listFollowedByAuthenticatedUser"] }
    ],
    listFollowedByAuthenticatedUser: ["GET /user/following"],
    listFollowersForAuthenticatedUser: ["GET /user/followers"],
    listFollowersForUser: ["GET /users/{username}/followers"],
    listFollowingForUser: ["GET /users/{username}/following"],
    listGpgKeysForAuthenticated: [
      "GET /user/gpg_keys",
      {},
      { renamed: ["users", "listGpgKeysForAuthenticatedUser"] }
    ],
    listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"],
    listGpgKeysForUser: ["GET /users/{username}/gpg_keys"],
    listPublicEmailsForAuthenticated: [
      "GET /user/public_emails",
      {},
      { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] }
    ],
    listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"],
    listPublicKeysForUser: ["GET /users/{username}/keys"],
    listPublicSshKeysForAuthenticated: [
      "GET /user/keys",
      {},
      { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] }
    ],
    listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"],
    listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"],
    listSocialAccountsForUser: ["GET /users/{username}/social_accounts"],
    listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"],
    listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"],
    setPrimaryEmailVisibilityForAuthenticated: [
      "PATCH /user/email/visibility",
      {},
      { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] }
    ],
    setPrimaryEmailVisibilityForAuthenticatedUser: [
      "PATCH /user/email/visibility"
    ],
    unblock: ["DELETE /user/blocks/{username}"],
    unfollow: ["DELETE /user/following/{username}"],
    updateAuthenticated: ["PATCH /user"]
  }
};
var endpoints_default = Endpoints;

// pkg/dist-src/endpoints-to-methods.js
var endpointMethodsMap = /* @__PURE__ */ new Map();
for (const [scope, endpoints] of Object.entries(endpoints_default)) {
  for (const [methodName, endpoint] of Object.entries(endpoints)) {
    const [route, defaults, decorations] = endpoint;
    const [method, url] = route.split(/ /);
    const endpointDefaults = Object.assign(
      {
        method,
        url
      },
      defaults
    );
    if (!endpointMethodsMap.has(scope)) {
      endpointMethodsMap.set(scope, /* @__PURE__ */ new Map());
    }
    endpointMethodsMap.get(scope).set(methodName, {
      scope,
      methodName,
      endpointDefaults,
      decorations
    });
  }
}
var handler = {
  has({ scope }, methodName) {
    return endpointMethodsMap.get(scope).has(methodName);
  },
  getOwnPropertyDescriptor(target, methodName) {
    return {
      value: this.get(target, methodName),
      // ensures method is in the cache
      configurable: true,
      writable: true,
      enumerable: true
    };
  },
  defineProperty(target, methodName, descriptor) {
    Object.defineProperty(target.cache, methodName, descriptor);
    return true;
  },
  deleteProperty(target, methodName) {
    delete target.cache[methodName];
    return true;
  },
  ownKeys({ scope }) {
    return [...endpointMethodsMap.get(scope).keys()];
  },
  set(target, methodName, value) {
    return target.cache[methodName] = value;
  },
  get({ octokit, scope, cache }, methodName) {
    if (cache[methodName]) {
      return cache[methodName];
    }
    const method = endpointMethodsMap.get(scope).get(methodName);
    if (!method) {
      return void 0;
    }
    const { endpointDefaults, decorations } = method;
    if (decorations) {
      cache[methodName] = decorate(
        octokit,
        scope,
        methodName,
        endpointDefaults,
        decorations
      );
    } else {
      cache[methodName] = octokit.request.defaults(endpointDefaults);
    }
    return cache[methodName];
  }
};
function endpointsToMethods(octokit) {
  const newMethods = {};
  for (const scope of endpointMethodsMap.keys()) {
    newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler);
  }
  return newMethods;
}
function decorate(octokit, scope, methodName, defaults, decorations) {
  const requestWithDefaults = octokit.request.defaults(defaults);
  function withDecorations(...args) {
    let options = requestWithDefaults.endpoint.merge(...args);
    if (decorations.mapToData) {
      options = Object.assign({}, options, {
        data: options[decorations.mapToData],
        [decorations.mapToData]: void 0
      });
      return requestWithDefaults(options);
    }
    if (decorations.renamed) {
      const [newScope, newMethodName] = decorations.renamed;
      octokit.log.warn(
        `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`
      );
    }
    if (decorations.deprecated) {
      octokit.log.warn(decorations.deprecated);
    }
    if (decorations.renamedParameters) {
      const options2 = requestWithDefaults.endpoint.merge(...args);
      for (const [name, alias] of Object.entries(
        decorations.renamedParameters
      )) {
        if (name in options2) {
          octokit.log.warn(
            `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`
          );
          if (!(alias in options2)) {
            options2[alias] = options2[name];
          }
          delete options2[name];
        }
      }
      return requestWithDefaults(options2);
    }
    return requestWithDefaults(...args);
  }
  return Object.assign(withDecorations, requestWithDefaults);
}

// pkg/dist-src/index.js
function restEndpointMethods(octokit) {
  const api = endpointsToMethods(octokit);
  return {
    rest: api
  };
}
restEndpointMethods.VERSION = plugin_rest_endpoint_methods_dist_web_VERSION;
function legacyRestEndpointMethods(octokit) {
  const api = endpointsToMethods(octokit);
  return {
    ...api,
    rest: api
  };
}
legacyRestEndpointMethods.VERSION = plugin_rest_endpoint_methods_dist_web_VERSION;


;// ./node_modules/@octokit/rest/dist-web/index.js
// pkg/dist-src/index.js





// pkg/dist-src/version.js
var rest_dist_web_VERSION = "20.1.2";

// pkg/dist-src/index.js
var dist_web_Octokit = Octokit.plugin(
  requestLog,
  legacyRestEndpointMethods,
  paginateRest
).defaults({
  userAgent: `octokit-rest.js/${rest_dist_web_VERSION}`
});


;// ./src/editor/src/services/github/GitHubClient.ts
/**
 * GitHubClient
 *
 * High-level GitHub REST API client with rate limiting, caching, and error handling.
 * Built on top of GitHubOAuthService for authentication.
 *
 * @module noodl-editor/services/github
 */



/**
 * Rate limit warning threshold (percentage)
 */
const RATE_LIMIT_WARNING_THRESHOLD = 0.1; // Warn at 10% remaining
/**
 * Default cache TTL in milliseconds
 */
const DEFAULT_CACHE_TTL = 30000; // 30 seconds
/**
 * Maximum cache size (number of entries)
 */
const MAX_CACHE_SIZE = 100;
/**
 * GitHub API client with rate limiting, caching, and error handling
 */
class GitHubClient extends EventDispatcher.EventDispatcher {
    constructor() {
        super();
        this.octokit = null;
        this.cache = new Map();
        this.rateLimit = null;
        this.authService = GitHubOAuthService/* GitHubOAuthService */.W.instance;
        // Listen for auth changes
        this.authService.on('auth-state-changed', this.handleAuthChange.bind(this), this);
        this.authService.on('disconnected', this.handleDisconnect.bind(this), this);
        // Initialize if already authenticated
        if (this.authService.isAuthenticated()) {
            this.initializeOctokit();
        }
    }
    static get instance() {
        if (!GitHubClient._instance) {
            GitHubClient._instance = new GitHubClient();
        }
        return GitHubClient._instance;
    }
    /**
     * Handle authentication state changes
     */
    handleAuthChange(event) {
        if (event.authenticated) {
            this.initializeOctokit();
        }
        else {
            this.octokit = null;
            this.clearCache();
        }
    }
    /**
     * Handle disconnection
     */
    handleDisconnect() {
        this.octokit = null;
        this.clearCache();
        this.rateLimit = null;
    }
    /**
     * Initialize Octokit with current auth token
     */
    async initializeOctokit() {
        const token = await this.authService.getToken();
        if (!token) {
            throw new Error('No authentication token available');
        }
        this.octokit = new dist_web_Octokit({
            auth: token,
            userAgent: 'OpenNoodl/1.1.0'
        });
        // Fetch initial rate limit info
        await this.updateRateLimit();
    }
    /**
     * Ensure client is authenticated and initialized
     */
    async ensureAuthenticated() {
        if (!this.octokit) {
            await this.initializeOctokit();
        }
        if (!this.octokit) {
            throw new Error('GitHub client not authenticated');
        }
        return this.octokit;
    }
    /**
     * Update rate limit information from response headers
     */
    updateRateLimitFromHeaders(headers) {
        if (headers['x-ratelimit-limit']) {
            this.rateLimit = {
                limit: parseInt(headers['x-ratelimit-limit'], 10),
                remaining: parseInt(headers['x-ratelimit-remaining'], 10),
                reset: parseInt(headers['x-ratelimit-reset'], 10),
                used: parseInt(headers['x-ratelimit-used'] || '0', 10)
            };
            // Emit warning if approaching limit
            if (this.rateLimit.remaining / this.rateLimit.limit < RATE_LIMIT_WARNING_THRESHOLD) {
                this.notifyListeners('rate-limit-warning', { rateLimit: this.rateLimit });
            }
            // Emit event with current rate limit
            this.notifyListeners('rate-limit-updated', { rateLimit: this.rateLimit });
        }
    }
    /**
     * Fetch current rate limit status
     */
    async updateRateLimit() {
        const octokit = await this.ensureAuthenticated();
        const response = await octokit.rateLimit.get();
        this.rateLimit = {
            limit: response.data.rate.limit,
            remaining: response.data.rate.remaining,
            reset: response.data.rate.reset,
            used: response.data.rate.used
        };
        return this.rateLimit;
    }
    /**
     * Get current rate limit info (cached)
     */
    getRateLimit() {
        return this.rateLimit;
    }
    /**
     * Generate cache key
     */
    getCacheKey(method, params) {
        return `${method}:${JSON.stringify(params)}`;
    }
    /**
     * Get data from cache if valid
     * Returns undefined if not in cache, the cached value (which could be null) if present
     */
    getFromCache(key, ttl = DEFAULT_CACHE_TTL) {
        const entry = this.cache.get(key);
        if (!entry) {
            return undefined; // Not in cache
        }
        const age = Date.now() - entry.timestamp;
        if (age > ttl) {
            this.cache.delete(key);
            return undefined; // Cache expired
        }
        return entry.data; // Return cached value (could be null)
    }
    /**
     * Store data in cache
     */
    setCache(key, data, etag) {
        // Implement simple LRU by removing oldest entries when cache is full
        if (this.cache.size >= MAX_CACHE_SIZE) {
            const firstKey = this.cache.keys().next().value;
            if (firstKey) {
                this.cache.delete(firstKey);
            }
        }
        this.cache.set(key, {
            data,
            timestamp: Date.now(),
            etag
        });
    }
    /**
     * Clear all cached data
     */
    clearCache() {
        this.cache.clear();
    }
    /**
     * Handle API errors with user-friendly messages
     */
    handleApiError(error) {
        var _a, _b, _c, _d, _e, _f, _g;
        if (error && typeof error === 'object' && 'status' in error) {
            const apiError = error;
            switch (apiError.status) {
                case 401:
                    throw new Error('Authentication failed. Please reconnect your GitHub account.');
                case 403:
                    if ((_c = (_b = (_a = apiError.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.message) === null || _c === void 0 ? void 0 : _c.includes('rate limit')) {
                        const resetTime = this.rateLimit ? new Date(this.rateLimit.reset * 1000) : new Date();
                        throw new Error(`Rate limit exceeded. Resets at ${resetTime.toLocaleTimeString()}`);
                    }
                    throw new Error('Access forbidden. Check repository permissions.');
                case 404:
                    throw new Error('Repository or resource not found.');
                case 422: {
                    const message = ((_e = (_d = apiError.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.message) || 'Validation failed';
                    throw new Error(`Invalid request: ${message}`);
                }
                default:
                    throw new Error(`GitHub API error: ${((_g = (_f = apiError.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.message) || 'Unknown error'}`);
            }
        }
        throw error;
    }
    // ==================== REPOSITORY METHODS ====================
    /**
     * Get repository information
     */
    async getRepository(owner, repo) {
        const cacheKey = this.getCacheKey('getRepository', { owner, repo });
        const cached = this.getFromCache(cacheKey, 60000); // 1 minute cache
        if (cached) {
            return { data: cached, rateLimit: this.rateLimit };
        }
        try {
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.repos.get({ owner, repo });
            this.updateRateLimitFromHeaders(response.headers);
            this.setCache(cacheKey, response.data);
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    /**
     * List user repositories
     */
    async listRepositories(options) {
        var _a;
        console.log('🔍 [GitHubClient] listRepositories called with:', options);
        const cacheKey = this.getCacheKey('listRepositories', options || {});
        const cached = this.getFromCache(cacheKey, 60000);
        if (cached) {
            console.log('🔍 [GitHubClient] Returning cached repos:', cached.length);
            return { data: cached, rateLimit: this.rateLimit };
        }
        try {
            console.log('🔍 [GitHubClient] Calling octokit.repos.listForAuthenticatedUser...');
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.repos.listForAuthenticatedUser(options);
            console.log('🔍 [GitHubClient] Got repos from API:', ((_a = response.data) === null || _a === void 0 ? void 0 : _a.length) || 0);
            this.updateRateLimitFromHeaders(response.headers);
            this.setCache(cacheKey, response.data);
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            console.error('❌ [GitHubClient] listRepositories error:', error);
            this.handleApiError(error);
        }
    }
    // ==================== ISSUE METHODS ====================
    /**
     * List issues for a repository
     */
    async listIssues(owner, repo, filters) {
        var _a;
        const cacheKey = this.getCacheKey('listIssues', { owner, repo, ...filters });
        const cached = this.getFromCache(cacheKey);
        if (cached) {
            return { data: cached, rateLimit: this.rateLimit };
        }
        try {
            const octokit = await this.ensureAuthenticated();
            // Convert milestone number to string if present
            const apiFilters = filters
                ? {
                    ...filters,
                    milestone: filters.milestone ? String(filters.milestone) : undefined,
                    labels: (_a = filters.labels) === null || _a === void 0 ? void 0 : _a.join(',')
                }
                : {};
            const response = await octokit.issues.listForRepo({
                owner,
                repo,
                ...apiFilters
            });
            this.updateRateLimitFromHeaders(response.headers);
            this.setCache(cacheKey, response.data);
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    /**
     * Get a single issue
     */
    async getIssue(owner, repo, issue_number) {
        const cacheKey = this.getCacheKey('getIssue', { owner, repo, issue_number });
        const cached = this.getFromCache(cacheKey);
        if (cached) {
            return { data: cached, rateLimit: this.rateLimit };
        }
        try {
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.issues.get({
                owner,
                repo,
                issue_number
            });
            this.updateRateLimitFromHeaders(response.headers);
            this.setCache(cacheKey, response.data);
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    /**
     * Create a new issue
     */
    async createIssue(owner, repo, options) {
        try {
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.issues.create({
                owner,
                repo,
                ...options
            });
            this.updateRateLimitFromHeaders(response.headers);
            // Invalidate list cache
            this.clearCacheForPattern('listIssues');
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    /**
     * Update an existing issue
     */
    async updateIssue(owner, repo, issue_number, options) {
        try {
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.issues.update({
                owner,
                repo,
                issue_number,
                ...options
            });
            this.updateRateLimitFromHeaders(response.headers);
            // Invalidate caches
            this.clearCacheForPattern('listIssues');
            this.clearCacheForPattern('getIssue');
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    /**
     * List comments on an issue
     */
    async listIssueComments(owner, repo, issue_number) {
        const cacheKey = this.getCacheKey('listIssueComments', { owner, repo, issue_number });
        const cached = this.getFromCache(cacheKey);
        if (cached) {
            return { data: cached, rateLimit: this.rateLimit };
        }
        try {
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.issues.listComments({
                owner,
                repo,
                issue_number
            });
            this.updateRateLimitFromHeaders(response.headers);
            this.setCache(cacheKey, response.data);
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    /**
     * Create a comment on an issue
     */
    async createIssueComment(owner, repo, issue_number, body) {
        try {
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.issues.createComment({
                owner,
                repo,
                issue_number,
                body
            });
            this.updateRateLimitFromHeaders(response.headers);
            // Invalidate comment cache
            this.clearCacheForPattern('listIssueComments');
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    // ==================== PULL REQUEST METHODS ====================
    /**
     * List pull requests for a repository
     */
    async listPullRequests(owner, repo, filters) {
        const cacheKey = this.getCacheKey('listPullRequests', { owner, repo, ...filters });
        const cached = this.getFromCache(cacheKey);
        if (cached) {
            return { data: cached, rateLimit: this.rateLimit };
        }
        try {
            const octokit = await this.ensureAuthenticated();
            // Map our filters to PR-specific parameters
            const prSort = (filters === null || filters === void 0 ? void 0 : filters.sort) === 'comments' ? 'created' : filters === null || filters === void 0 ? void 0 : filters.sort;
            const apiFilters = filters
                ? {
                    state: filters.state,
                    sort: prSort,
                    direction: filters.direction,
                    per_page: filters.per_page,
                    page: filters.page
                }
                : {};
            const response = await octokit.pulls.list({
                owner,
                repo,
                ...apiFilters
            });
            this.updateRateLimitFromHeaders(response.headers);
            this.setCache(cacheKey, response.data);
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    /**
     * Get a single pull request
     */
    async getPullRequest(owner, repo, pull_number) {
        const cacheKey = this.getCacheKey('getPullRequest', { owner, repo, pull_number });
        const cached = this.getFromCache(cacheKey);
        if (cached) {
            return { data: cached, rateLimit: this.rateLimit };
        }
        try {
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.pulls.get({
                owner,
                repo,
                pull_number
            });
            this.updateRateLimitFromHeaders(response.headers);
            this.setCache(cacheKey, response.data);
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    /**
     * List commits in a pull request
     */
    async listPullRequestCommits(owner, repo, pull_number) {
        const cacheKey = this.getCacheKey('listPullRequestCommits', { owner, repo, pull_number });
        const cached = this.getFromCache(cacheKey);
        if (cached) {
            return { data: cached, rateLimit: this.rateLimit };
        }
        try {
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.pulls.listCommits({
                owner,
                repo,
                pull_number
            });
            this.updateRateLimitFromHeaders(response.headers);
            this.setCache(cacheKey, response.data);
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    // ==================== LABEL METHODS ====================
    /**
     * List labels for a repository
     */
    async listLabels(owner, repo) {
        const cacheKey = this.getCacheKey('listLabels', { owner, repo });
        const cached = this.getFromCache(cacheKey, 300000); // 5 minute cache
        if (cached) {
            return { data: cached, rateLimit: this.rateLimit };
        }
        try {
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.issues.listLabelsForRepo({
                owner,
                repo
            });
            this.updateRateLimitFromHeaders(response.headers);
            this.setCache(cacheKey, response.data);
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    // ==================== ORGANIZATION METHODS ====================
    /**
     * List organizations for the authenticated user
     */
    async listOrganizations() {
        var _a;
        console.log('🔍 [GitHubClient] listOrganizations called');
        const cacheKey = this.getCacheKey('listOrganizations', {});
        const cached = this.getFromCache(cacheKey, 60000); // 1 minute cache
        if (cached) {
            console.log('🔍 [GitHubClient] Returning cached orgs:', cached.length);
            return { data: cached, rateLimit: this.rateLimit };
        }
        try {
            console.log('🔍 [GitHubClient] Calling octokit.orgs.listForAuthenticatedUser...');
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.orgs.listForAuthenticatedUser({
                per_page: 100
            });
            console.log('🔍 [GitHubClient] Got orgs from API:', ((_a = response.data) === null || _a === void 0 ? void 0 : _a.length) || 0);
            this.updateRateLimitFromHeaders(response.headers);
            this.setCache(cacheKey, response.data);
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            console.error('❌ [GitHubClient] listOrganizations error:', error);
            this.handleApiError(error);
        }
    }
    /**
     * List repositories for an organization
     */
    async listOrganizationRepositories(org, options) {
        const cacheKey = this.getCacheKey('listOrganizationRepositories', { org, ...options });
        const cached = this.getFromCache(cacheKey, 60000); // 1 minute cache
        if (cached) {
            return { data: cached, rateLimit: this.rateLimit };
        }
        try {
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.repos.listForOrg({
                org,
                ...options
            });
            this.updateRateLimitFromHeaders(response.headers);
            this.setCache(cacheKey, response.data);
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            this.handleApiError(error);
        }
    }
    /**
     * Create a new repository
     *
     * @param options - Repository creation options
     * @returns The created repository
     */
    async createRepository(options) {
        var _a, _b, _c, _d;
        console.log('🔧 [GitHubClient] createRepository called with:', options);
        try {
            const octokit = await this.ensureAuthenticated();
            let response;
            if (options.org) {
                // Create repository in organization
                console.log('🔧 [GitHubClient] Creating repo in org:', options.org);
                response = await octokit.repos.createInOrg({
                    org: options.org,
                    name: options.name,
                    description: options.description,
                    private: (_a = options.private) !== null && _a !== void 0 ? _a : true,
                    auto_init: (_b = options.auto_init) !== null && _b !== void 0 ? _b : false,
                    gitignore_template: options.gitignore_template,
                    license_template: options.license_template
                });
            }
            else {
                // Create repository in user account
                console.log('🔧 [GitHubClient] Creating repo in user account');
                response = await octokit.repos.createForAuthenticatedUser({
                    name: options.name,
                    description: options.description,
                    private: (_c = options.private) !== null && _c !== void 0 ? _c : true,
                    auto_init: (_d = options.auto_init) !== null && _d !== void 0 ? _d : false,
                    gitignore_template: options.gitignore_template,
                    license_template: options.license_template
                });
            }
            console.log('✅ [GitHubClient] Repository created:', response.data.full_name);
            this.updateRateLimitFromHeaders(response.headers);
            // Invalidate repo list caches
            this.clearCacheForPattern('listRepositories');
            this.clearCacheForPattern('listOrganizationRepositories');
            return {
                data: response.data,
                rateLimit: this.rateLimit
            };
        }
        catch (error) {
            console.error('❌ [GitHubClient] createRepository error:', error);
            this.handleApiError(error);
        }
    }
    // ==================== FILE CONTENT METHODS ====================
    /**
     * Get file content from a repository
     * @returns File content as string, or null if file doesn't exist
     */
    async getFileContent(owner, repo, path) {
        const cacheKey = this.getCacheKey('getFileContent', { owner, repo, path });
        const cached = this.getFromCache(cacheKey, 60000); // 1 minute cache
        if (cached !== undefined) {
            console.log('📦 [getFileContent] Cache hit for', `${owner}/${repo}/${path}`);
            return cached;
        }
        console.log('🔍 [getFileContent] Fetching', `${owner}/${repo}/${path}`);
        try {
            const octokit = await this.ensureAuthenticated();
            const response = await octokit.repos.getContent({
                owner,
                repo,
                path
            });
            const responseType = !Array.isArray(response.data) && 'type' in response.data ? response.data.type : 'unknown';
            console.log('✅ [getFileContent] Got response for', `${owner}/${repo}/${path}`, responseType);
            this.updateRateLimitFromHeaders(response.headers);
            // Handle file content (not directory)
            if (!Array.isArray(response.data) && 'content' in response.data && response.data.type === 'file') {
                const content = Buffer.from(response.data.content, 'base64').toString('utf-8');
                this.setCache(cacheKey, content);
                console.log('✅ [getFileContent] Found file', `${owner}/${repo}/${path}`, content.substring(0, 50) + '...');
                return content;
            }
            // It's a directory or something else
            console.log('⚠️ [getFileContent] Not a file:', `${owner}/${repo}/${path}`, responseType);
            this.setCache(cacheKey, null);
            return null;
        }
        catch (error) {
            const errorStatus = error && typeof error === 'object' && 'status' in error ? error.status : 'unknown';
            console.log('❌ [getFileContent] Error for', `${owner}/${repo}/${path}`, 'status:', errorStatus);
            // 404 means file doesn't exist - cache that result
            if (errorStatus === 404) {
                this.setCache(cacheKey, null);
                return null;
            }
            // Log the full error for non-404 errors
            console.error('❌ [getFileContent] Full error:', error);
            // For other errors, don't cache and rethrow
            throw error;
        }
    }
    /**
     * Check if a repository is a Noodl project
     * Checks for project.json at the root of the repo
     */
    async isNoodlProject(owner, repo) {
        console.log('🔍 [GitHubClient] isNoodlProject checking:', `${owner}/${repo}`);
        try {
            const projectJson = await this.getFileContent(owner, repo, 'project.json');
            if (projectJson !== null) {
                console.log('✅ [GitHubClient] Found project.json in', `${owner}/${repo}`);
                return true;
            }
            console.log('❌ [GitHubClient] No project.json found in', `${owner}/${repo}`);
            return false;
        }
        catch (error) {
            console.error('❌ [GitHubClient] Error checking isNoodlProject for', `${owner}/${repo}`, error);
            return false;
        }
    }
    // ==================== UTILITY METHODS ====================
    /**
     * Clear cache entries matching a pattern
     */
    clearCacheForPattern(pattern) {
        for (const key of this.cache.keys()) {
            if (key.startsWith(pattern)) {
                this.cache.delete(key);
            }
        }
    }
    /**
     * Check if client is ready to make API calls
     */
    isReady() {
        return this.octokit !== null;
    }
    /**
     * Get time until rate limit resets (in milliseconds)
     */
    getTimeUntilRateLimitReset() {
        if (!this.rateLimit) {
            return 0;
        }
        const resetTime = this.rateLimit.reset * 1000;
        const now = Date.now();
        return Math.max(0, resetTime - now);
    }
}

;// ./src/editor/src/services/github/index.ts
/**
 * GitHub Service - Public API
 *
 * Provides GitHub integration services including OAuth authentication
 * and REST API client with rate limiting and caching.
 *
 * @module noodl-editor/services/github
 *
 * @example
 * ```typescript
 * import { GitHubClient, GitHubOAuthService } from '@noodl-editor/services/github';
 *
 * // Initialize OAuth
 * await GitHubOAuthService.instance.initialize();
 *
 * // Use API client
 * const client = GitHubClient.instance;
 * const { data: issues } = await client.listIssues('owner', 'repo');
 * ```
 */
// Re-export main services




// EXTERNAL MODULE: ../noodl-git/src/index.ts + 14 modules
var noodl_git_src = __webpack_require__(7457);
// EXTERNAL MODULE: ./src/editor/src/utils/projectmerger.js
var projectmerger = __webpack_require__(78200);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/GitHubPanel/components/ConnectToGitHub/ConnectToGitHub.module.scss
var ConnectToGitHub_module = __webpack_require__(28862);
;// ./src/editor/src/views/panels/GitHubPanel/components/ConnectToGitHub/ConnectToGitHub.module.scss

      
      
      
      
      
      
      
      
      

var ConnectToGitHub_module_options = {};

ConnectToGitHub_module_options.styleTagTransform = (styleTagTransform_default());
ConnectToGitHub_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ConnectToGitHub_module_options.insert = insertBySelector_default().bind(null, "head");
    
ConnectToGitHub_module_options.domAPI = (styleDomAPI_default());
ConnectToGitHub_module_options.insertStyleElement = (insertStyleElement_default());

var ConnectToGitHub_module_update = injectStylesIntoStyleTag_default()(ConnectToGitHub_module/* default */.A, ConnectToGitHub_module_options);




       /* harmony default export */ const ConnectToGitHub_ConnectToGitHub_module = (ConnectToGitHub_module/* default */.A && ConnectToGitHub_module/* default */.A.locals ? ConnectToGitHub_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/GitHubPanel/components/ConnectToGitHub/CreateRepoModal.tsx
/**
 * CreateRepoModal
 *
 * Modal for creating a new GitHub repository
 */



function CreateRepoModal({ onClose, onCreate, isCreating }) {
    const [name, setName] = (0,external_react_.useState)('');
    const [description, setDescription] = (0,external_react_.useState)('');
    const [isPrivate, setIsPrivate] = (0,external_react_.useState)(true);
    const [selectedOrg, setSelectedOrg] = (0,external_react_.useState)('');
    const [orgs, setOrgs] = (0,external_react_.useState)([]);
    const [loadingOrgs, setLoadingOrgs] = (0,external_react_.useState)(true);
    const [error, setError] = (0,external_react_.useState)(null);
    // Load organizations
    (0,external_react_.useEffect)(() => {
        async function loadOrgs() {
            try {
                const client = GitHubClient.instance;
                const result = await client.listOrganizations();
                setOrgs(result.data);
            }
            catch (err) {
                console.error('Failed to load organizations:', err);
            }
            finally {
                setLoadingOrgs(false);
            }
        }
        loadOrgs();
    }, []);
    const handleSubmit = (e) => {
        e.preventDefault();
        if (!name.trim()) {
            setError('Repository name is required');
            return;
        }
        // Validate repo name (GitHub rules)
        const nameRegex = /^[a-zA-Z0-9._-]+$/;
        if (!nameRegex.test(name)) {
            setError('Repository name can only contain letters, numbers, hyphens, underscores, and dots');
            return;
        }
        setError(null);
        onCreate({
            name: name.trim(),
            description: description.trim() || undefined,
            private: isPrivate,
            org: selectedOrg || undefined
        });
    };
    const handleBackdropClick = (e) => {
        if (e.target === e.currentTarget && !isCreating) {
            onClose();
        }
    };
    return (external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ModalBackdrop, onClick: handleBackdropClick },
        external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.Modal },
            external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ModalHeader },
                external_react_default().createElement("h2", null, "Create New Repository"),
                external_react_default().createElement("button", { className: ConnectToGitHub_ConnectToGitHub_module.CloseButton, onClick: onClose, disabled: isCreating }, "\u00D7")),
            external_react_default().createElement("form", { onSubmit: handleSubmit },
                external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ModalBody },
                    external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.FormGroup },
                        external_react_default().createElement("label", { htmlFor: "owner" }, "Owner"),
                        external_react_default().createElement("select", { id: "owner", value: selectedOrg, onChange: (e) => setSelectedOrg(e.target.value), disabled: loadingOrgs || isCreating, className: ConnectToGitHub_ConnectToGitHub_module.Select },
                            external_react_default().createElement("option", { value: "" }, "Personal Account"),
                            orgs.map((org) => (external_react_default().createElement("option", { key: org.id, value: org.login }, org.login))))),
                    external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.FormGroup },
                        external_react_default().createElement("label", { htmlFor: "name" }, "Repository name *"),
                        external_react_default().createElement("input", { id: "name", type: "text", value: name, onChange: (e) => setName(e.target.value), placeholder: "my-noodl-project", disabled: isCreating, className: ConnectToGitHub_ConnectToGitHub_module.Input, autoFocus: true })),
                    external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.FormGroup },
                        external_react_default().createElement("label", { htmlFor: "description" }, "Description"),
                        external_react_default().createElement("input", { id: "description", type: "text", value: description, onChange: (e) => setDescription(e.target.value), placeholder: "A brief description of your project", disabled: isCreating, className: ConnectToGitHub_ConnectToGitHub_module.Input })),
                    external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.FormGroup },
                        external_react_default().createElement("label", null, "Visibility"),
                        external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.RadioGroup },
                            external_react_default().createElement("label", { className: ConnectToGitHub_ConnectToGitHub_module.RadioLabel },
                                external_react_default().createElement("input", { type: "radio", name: "visibility", checked: isPrivate, onChange: () => setIsPrivate(true), disabled: isCreating }),
                                external_react_default().createElement("span", { className: ConnectToGitHub_ConnectToGitHub_module.RadioIcon }, "\uD83D\uDD12"),
                                external_react_default().createElement("span", null, "Private")),
                            external_react_default().createElement("label", { className: ConnectToGitHub_ConnectToGitHub_module.RadioLabel },
                                external_react_default().createElement("input", { type: "radio", name: "visibility", checked: !isPrivate, onChange: () => setIsPrivate(false), disabled: isCreating }),
                                external_react_default().createElement("span", { className: ConnectToGitHub_ConnectToGitHub_module.RadioIcon }, "\uD83C\uDF10"),
                                external_react_default().createElement("span", null, "Public")))),
                    error && external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ErrorMessage }, error)),
                external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ModalFooter },
                    external_react_default().createElement("button", { type: "button", className: ConnectToGitHub_ConnectToGitHub_module.SecondaryButton, onClick: onClose, disabled: isCreating }, "Cancel"),
                    external_react_default().createElement("button", { type: "submit", className: ConnectToGitHub_ConnectToGitHub_module.PrimaryButton, disabled: isCreating || !name.trim() }, isCreating ? 'Creating...' : 'Create Repository'))))));
}

;// ./src/editor/src/views/panels/GitHubPanel/components/ConnectToGitHub/SelectRepoModal.tsx
/**
 * SelectRepoModal
 *
 * Modal for selecting an existing GitHub repository to connect
 */



function SelectRepoModal({ onClose, onSelect, isConnecting }) {
    const [repos, setRepos] = (0,external_react_.useState)([]);
    const [orgs, setOrgs] = (0,external_react_.useState)([]);
    const [loading, setLoading] = (0,external_react_.useState)(true);
    const [error, setError] = (0,external_react_.useState)(null);
    const [searchQuery, setSearchQuery] = (0,external_react_.useState)('');
    const [selectedRepo, setSelectedRepo] = (0,external_react_.useState)(null);
    // Load repositories and organizations
    (0,external_react_.useEffect)(() => {
        async function loadData() {
            setLoading(true);
            setError(null);
            try {
                const client = GitHubClient.instance;
                // Load in parallel
                const [reposResult, orgsResult] = await Promise.all([
                    client.listRepositories({ per_page: 100, sort: 'updated' }),
                    client.listOrganizations()
                ]);
                setRepos(reposResult.data);
                setOrgs(orgsResult.data);
                // Also load org repos
                const orgRepos = await Promise.all(orgsResult.data.map((org) => client.listOrganizationRepositories(org.login, { per_page: 100, sort: 'updated' })));
                // Combine all repos
                const allRepos = [...reposResult.data];
                orgRepos.forEach((result) => {
                    result.data.forEach((repo) => {
                        if (!allRepos.find((r) => r.id === repo.id)) {
                            allRepos.push(repo);
                        }
                    });
                });
                setRepos(allRepos);
            }
            catch (err) {
                console.error('Failed to load repositories:', err);
                setError('Failed to load repositories. Please try again.');
            }
            finally {
                setLoading(false);
            }
        }
        loadData();
    }, []);
    // Group and filter repos
    const groupedRepos = (0,external_react_.useMemo)(() => {
        // Filter by search query
        const filtered = searchQuery
            ? repos.filter((repo) => {
                var _a;
                return repo.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                    repo.full_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                    ((_a = repo.description) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(searchQuery.toLowerCase()));
            })
            : repos;
        // Group by owner
        const groups = {};
        filtered.forEach((repo) => {
            const ownerLogin = repo.owner.login;
            if (!groups[ownerLogin]) {
                groups[ownerLogin] = [];
            }
            groups[ownerLogin].push(repo);
        });
        // Sort groups: personal first, then orgs alphabetically
        const sortedGroups = [];
        const personalRepos = Object.entries(groups).find(([name]) => !orgs.find((org) => org.login === name));
        if (personalRepos) {
            sortedGroups.push({ name: 'Personal', repos: personalRepos[1] });
        }
        Object.entries(groups)
            .filter(([name]) => orgs.find((org) => org.login === name))
            .sort(([a], [b]) => a.localeCompare(b))
            .forEach(([name, repoList]) => {
            sortedGroups.push({ name, repos: repoList });
        });
        return sortedGroups;
    }, [repos, orgs, searchQuery]);
    const handleSelect = () => {
        if (selectedRepo) {
            onSelect(selectedRepo.html_url + '.git');
        }
    };
    const handleBackdropClick = (e) => {
        if (e.target === e.currentTarget && !isConnecting) {
            onClose();
        }
    };
    const formatDate = (dateString) => {
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now.getTime() - date.getTime();
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
        if (diffDays === 0)
            return 'today';
        if (diffDays === 1)
            return 'yesterday';
        if (diffDays < 7)
            return `${diffDays} days ago`;
        if (diffDays < 30)
            return `${Math.floor(diffDays / 7)} weeks ago`;
        if (diffDays < 365)
            return `${Math.floor(diffDays / 30)} months ago`;
        return `${Math.floor(diffDays / 365)} years ago`;
    };
    return (external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ModalBackdrop, onClick: handleBackdropClick },
        external_react_default().createElement("div", { className: `${ConnectToGitHub_ConnectToGitHub_module.Modal} ${ConnectToGitHub_ConnectToGitHub_module.ModalLarge}` },
            external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ModalHeader },
                external_react_default().createElement("h2", null, "Connect to Existing Repository"),
                external_react_default().createElement("button", { className: ConnectToGitHub_ConnectToGitHub_module.CloseButton, onClick: onClose, disabled: isConnecting }, "\u00D7")),
            external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ModalBody },
                external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.SearchContainer },
                    external_react_default().createElement("input", { type: "text", placeholder: "Search repositories...", value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), className: ConnectToGitHub_ConnectToGitHub_module.SearchInput, autoFocus: true })),
                loading && (external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.LoadingState },
                    external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.Spinner }),
                    external_react_default().createElement("p", null, "Loading repositories..."))),
                error && external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ErrorMessage }, error),
                !loading && !error && (external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.RepoList }, groupedRepos.length === 0 ? (external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.EmptyState },
                    external_react_default().createElement("p", null, "No repositories found"))) : (groupedRepos.map((group) => (external_react_default().createElement("div", { key: group.name, className: ConnectToGitHub_ConnectToGitHub_module.RepoGroup },
                    external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.RepoGroupHeader }, group.name),
                    group.repos.map((repo) => (external_react_default().createElement("div", { key: repo.id, className: `${ConnectToGitHub_ConnectToGitHub_module.RepoItem} ${(selectedRepo === null || selectedRepo === void 0 ? void 0 : selectedRepo.id) === repo.id ? ConnectToGitHub_ConnectToGitHub_module.RepoItemSelected : ''}`, onClick: () => setSelectedRepo(repo) },
                        external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.RepoInfo },
                            external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.RepoName },
                                external_react_default().createElement("span", null, repo.name),
                                repo.private && external_react_default().createElement("span", { className: ConnectToGitHub_ConnectToGitHub_module.PrivateBadge }, "Private")),
                            repo.description && external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.RepoDescription }, repo.description),
                            external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.RepoMeta },
                                "Updated ",
                                formatDate(repo.updated_at))))))))))))),
            external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ModalFooter },
                external_react_default().createElement("button", { type: "button", className: ConnectToGitHub_ConnectToGitHub_module.SecondaryButton, onClick: onClose, disabled: isConnecting }, "Cancel"),
                external_react_default().createElement("button", { type: "button", className: ConnectToGitHub_ConnectToGitHub_module.PrimaryButton, onClick: handleSelect, disabled: isConnecting || !selectedRepo }, isConnecting ? 'Connecting...' : 'Connect Repository')))));
}

;// ./src/editor/src/views/panels/GitHubPanel/components/ConnectToGitHub/ConnectToGitHubView.tsx
/**
 * ConnectToGitHubView
 *
 * Displays appropriate UI based on project's git state:
 * - no-git: Offer to initialize git and create/connect repo
 * - git-no-remote: Offer to create or connect to existing repo
 * - remote-not-github: Show info that it's not a GitHub repo
 */









function ConnectToGitHubView({ gitState, remoteUrl, provider, onConnected }) {
    const [showCreateModal, setShowCreateModal] = (0,external_react_.useState)(false);
    const [showSelectModal, setShowSelectModal] = (0,external_react_.useState)(false);
    const [isConnecting, setIsConnecting] = (0,external_react_.useState)(false);
    const [error, setError] = (0,external_react_.useState)(null);
    const isGitHubConnected = GitHubOAuthService/* GitHubOAuthService */.W.instance.isAuthenticated();
    const handleConnectGitHub = async () => {
        try {
            await GitHubOAuthService/* GitHubOAuthService */.W.instance.initiateOAuth();
        }
        catch (err) {
            console.error('Failed to initiate GitHub OAuth:', err);
            setError('Failed to connect to GitHub. Please try again.');
        }
    };
    const handleCreateRepo = (0,external_react_.useCallback)(async (options) => {
        var _a, _b, _c;
        setIsConnecting(true);
        setError(null);
        try {
            const projectDirectory = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a._retainedProjectDirectory;
            if (!projectDirectory) {
                throw new Error('No project directory found');
            }
            console.log('🔧 [ConnectToGitHub] Creating repository:', options);
            // 1. Create repo on GitHub
            const client = GitHubClient.instance;
            const result = await client.createRepository({
                name: options.name,
                description: options.description,
                private: (_b = options.private) !== null && _b !== void 0 ? _b : true,
                org: options.org
            });
            const repoUrl = result.data.html_url + '.git';
            console.log('✅ [ConnectToGitHub] Repository created:', repoUrl);
            // 2. Set up git auth before any git operations
            const projectId = ((_c = projectmodel.ProjectModel.instance) === null || _c === void 0 ? void 0 : _c.id) || 'temp';
            console.log('🔧 [ConnectToGitHub] Setting up git auth for project:', projectId);
            LocalProjectsModel/* LocalProjectsModel */.h.instance.setCurrentGlobalGitAuth(projectId);
            // 3. Initialize git if needed
            const git = new noodl_git_src/* Git */.TU(projectmerger.mergeProject);
            if (gitState === 'no-git') {
                console.log('🔧 [ConnectToGitHub] Initializing git repository...');
                await git.initNewRepo(projectDirectory);
            }
            else {
                await git.openRepository(projectDirectory);
            }
            // 3. Add remote
            console.log('🔧 [ConnectToGitHub] Adding remote origin:', repoUrl);
            await git.setRemoteURL(repoUrl);
            // 4. Make initial commit if there are changes
            const status = await git.status();
            if (status.length > 0 || gitState === 'no-git') {
                console.log('🔧 [ConnectToGitHub] Creating initial commit...');
                await git.commit('Initial commit');
            }
            // 5. Push to remote
            console.log('🔧 [ConnectToGitHub] Pushing to remote...');
            await git.push();
            console.log('✅ [ConnectToGitHub] Successfully connected to GitHub!');
            // Notify parent
            setShowCreateModal(false);
            onConnected();
        }
        catch (err) {
            console.error('❌ [ConnectToGitHub] Error:', err);
            setError(err instanceof Error ? err.message : 'Failed to create repository');
        }
        finally {
            setIsConnecting(false);
        }
    }, [gitState, onConnected]);
    const handleSelectRepo = (0,external_react_.useCallback)(async (repoUrl) => {
        var _a, _b;
        setIsConnecting(true);
        setError(null);
        try {
            const projectDirectory = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a._retainedProjectDirectory;
            if (!projectDirectory) {
                throw new Error('No project directory found');
            }
            console.log('🔧 [ConnectToGitHub] Connecting to existing repo:', repoUrl);
            // Set up git auth before any git operations
            const projectId = ((_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.id) || 'temp';
            console.log('🔧 [ConnectToGitHub] Setting up git auth for project:', projectId);
            LocalProjectsModel/* LocalProjectsModel */.h.instance.setCurrentGlobalGitAuth(projectId);
            // Initialize git if needed
            const git = new noodl_git_src/* Git */.TU(projectmerger.mergeProject);
            if (gitState === 'no-git') {
                console.log('🔧 [ConnectToGitHub] Initializing git repository...');
                await git.initNewRepo(projectDirectory);
            }
            else {
                await git.openRepository(projectDirectory);
            }
            // Add remote
            console.log('🔧 [ConnectToGitHub] Setting remote URL:', repoUrl);
            await git.setRemoteURL(repoUrl);
            // Fetch from remote to see if there are existing commits
            try {
                console.log('🔧 [ConnectToGitHub] Fetching from remote...');
                await git.fetch({ onProgress: () => { } });
                // Check if remote has commits
                const hasRemote = await git.hasRemoteCommits();
                if (hasRemote) {
                    console.log('🔧 [ConnectToGitHub] Remote has commits, attempting to merge...');
                    // Pull changes
                    await git.mergeToCurrentBranch('origin/main', false);
                }
            }
            catch (fetchErr) {
                // Remote might be empty, that's okay
                console.log('⚠️ [ConnectToGitHub] Fetch warning (might be empty repo):', fetchErr);
            }
            console.log('✅ [ConnectToGitHub] Successfully connected to GitHub!');
            setShowSelectModal(false);
            onConnected();
        }
        catch (err) {
            console.error('❌ [ConnectToGitHub] Error:', err);
            setError(err instanceof Error ? err.message : 'Failed to connect to repository');
        }
        finally {
            setIsConnecting(false);
        }
    }, [gitState, onConnected]);
    // If not connected to GitHub, show connect button
    if (!isGitHubConnected) {
        return (external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ConnectView },
            external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.Icon },
                external_react_default().createElement(GitHubIcon, null)),
            external_react_default().createElement("h3", null, "Connect to GitHub"),
            external_react_default().createElement("p", null, "Connect your GitHub account to create or link repositories."),
            external_react_default().createElement("button", { className: ConnectToGitHub_ConnectToGitHub_module.PrimaryButton, onClick: handleConnectGitHub }, "Connect GitHub Account")));
    }
    // Show state-specific UI
    return (external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ConnectView },
        gitState === 'no-git' && (external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.Icon },
                external_react_default().createElement(FolderIcon, null)),
            external_react_default().createElement("h3", null, "Initialize Git Repository"),
            external_react_default().createElement("p", null, "This project is not under version control. Initialize git and connect to GitHub."))),
        gitState === 'git-no-remote' && (external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.Icon },
                external_react_default().createElement(GitIcon, null)),
            external_react_default().createElement("h3", null, "Connect to GitHub"),
            external_react_default().createElement("p", null, "This project has git initialized but no remote. Connect it to a GitHub repository."))),
        gitState === 'remote-not-github' && (external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.Icon },
                external_react_default().createElement(CloudIcon, null)),
            external_react_default().createElement("h3", null, "Not a GitHub Repository"),
            external_react_default().createElement("p", null,
                "This project is connected to a different git provider:",
                external_react_default().createElement("br", null),
                external_react_default().createElement("code", { className: ConnectToGitHub_ConnectToGitHub_module.RemoteUrl }, remoteUrl || provider)),
            external_react_default().createElement("p", { className: ConnectToGitHub_ConnectToGitHub_module.HintText }, "To use GitHub features, you will need to change the remote or create a new GitHub repository."))),
        error && external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.ErrorMessage }, error),
        gitState !== 'remote-not-github' && (external_react_default().createElement("div", { className: ConnectToGitHub_ConnectToGitHub_module.Actions },
            external_react_default().createElement("button", { className: ConnectToGitHub_ConnectToGitHub_module.PrimaryButton, onClick: () => setShowCreateModal(true), disabled: isConnecting }, "Create New Repository"),
            external_react_default().createElement("button", { className: ConnectToGitHub_ConnectToGitHub_module.SecondaryButton, onClick: () => setShowSelectModal(true), disabled: isConnecting }, "Connect Existing Repository"))),
        showCreateModal && (external_react_default().createElement(CreateRepoModal, { onClose: () => setShowCreateModal(false), onCreate: handleCreateRepo, isCreating: isConnecting })),
        showSelectModal && (external_react_default().createElement(SelectRepoModal, { onClose: () => setShowSelectModal(false), onSelect: handleSelectRepo, isConnecting: isConnecting }))));
}
// Simple icon components
function GitHubIcon() {
    return (external_react_default().createElement("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "currentColor" },
        external_react_default().createElement("path", { d: "M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" })));
}
function FolderIcon() {
    return (external_react_default().createElement("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" },
        external_react_default().createElement("path", { d: "M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" })));
}
function GitIcon() {
    return (external_react_default().createElement("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "currentColor" },
        external_react_default().createElement("path", { d: "M23.546 10.93L13.067.452c-.604-.603-1.582-.603-2.188 0L8.708 2.627l2.76 2.76c.645-.215 1.379-.07 1.889.441.516.515.658 1.258.438 1.9l2.658 2.66c.645-.223 1.387-.078 1.9.435.721.72.721 1.884 0 2.604-.719.719-1.881.719-2.6 0-.539-.541-.674-1.337-.404-1.996L12.86 8.955v6.525c.176.086.342.203.488.348.713.721.713 1.883 0 2.6-.719.721-1.889.721-2.609 0-.719-.719-.719-1.879 0-2.598.182-.18.387-.316.605-.406V8.835c-.217-.091-.424-.222-.6-.401-.545-.545-.676-1.342-.396-2.009L7.636 3.7.45 10.881c-.6.605-.6 1.584 0 2.189l10.48 10.477c.604.604 1.582.604 2.186 0l10.43-10.43c.605-.603.605-1.582 0-2.187" })));
}
function CloudIcon() {
    return (external_react_default().createElement("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" },
        external_react_default().createElement("path", { d: "M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z" })));
}

;// ./src/editor/src/views/panels/GitHubPanel/components/ConnectToGitHub/index.ts




// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssueDetail.module.scss
var IssueDetail_module = __webpack_require__(71497);
;// ./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssueDetail.module.scss

      
      
      
      
      
      
      
      
      

var IssueDetail_module_options = {};

IssueDetail_module_options.styleTagTransform = (styleTagTransform_default());
IssueDetail_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      IssueDetail_module_options.insert = insertBySelector_default().bind(null, "head");
    
IssueDetail_module_options.domAPI = (styleDomAPI_default());
IssueDetail_module_options.insertStyleElement = (insertStyleElement_default());

var IssueDetail_module_update = injectStylesIntoStyleTag_default()(IssueDetail_module/* default */.A, IssueDetail_module_options);




       /* harmony default export */ const IssuesTab_IssueDetail_module = (IssueDetail_module/* default */.A && IssueDetail_module/* default */.A.locals ? IssueDetail_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssueDetail.tsx
/**
 * IssueDetail Component
 *
 * Slide-out panel displaying full issue details with markdown rendering
 */


function IssueDetail({ issue, onClose }) {
    return (external_react_default().createElement("div", { className: IssuesTab_IssueDetail_module.IssueDetailOverlay, onClick: onClose },
        external_react_default().createElement("div", { className: IssuesTab_IssueDetail_module.IssueDetail, onClick: (e) => e.stopPropagation() },
            external_react_default().createElement("div", { className: IssuesTab_IssueDetail_module.Header },
                external_react_default().createElement("div", { className: IssuesTab_IssueDetail_module.TitleSection },
                    external_react_default().createElement("h2", { className: IssuesTab_IssueDetail_module.Title },
                        "#",
                        issue.number,
                        " ",
                        issue.title),
                    external_react_default().createElement("div", { className: IssuesTab_IssueDetail_module.StatusBadge, "data-state": issue.state },
                        issue.state === 'open' ? '🟢' : '🔴',
                        " ",
                        issue.state)),
                external_react_default().createElement("button", { className: IssuesTab_IssueDetail_module.CloseButton, onClick: onClose, "aria-label": "Close" }, "\u2715")),
            external_react_default().createElement("div", { className: IssuesTab_IssueDetail_module.Meta },
                external_react_default().createElement("span", null,
                    external_react_default().createElement("strong", null, issue.user.login),
                    " opened this issue ",
                    getRelativeTimeString(new Date(issue.created_at))),
                issue.comments > 0 && external_react_default().createElement("span", null,
                    "\u2022 ",
                    issue.comments,
                    " comments")),
            issue.labels && issue.labels.length > 0 && (external_react_default().createElement("div", { className: IssuesTab_IssueDetail_module.Labels }, issue.labels.map((label) => (external_react_default().createElement("span", { key: label.id, className: IssuesTab_IssueDetail_module.Label, style: {
                    backgroundColor: `#${label.color}`,
                    color: getContrastColor(label.color)
                } }, label.name))))),
            external_react_default().createElement("div", { className: IssuesTab_IssueDetail_module.Body }, issue.body ? (external_react_default().createElement("div", { className: IssuesTab_IssueDetail_module.MarkdownContent }, issue.body)) : (external_react_default().createElement("p", { className: IssuesTab_IssueDetail_module.NoDescription }, "No description provided."))),
            external_react_default().createElement("div", { className: IssuesTab_IssueDetail_module.Footer },
                external_react_default().createElement("a", { href: issue.html_url, target: "_blank", rel: "noopener noreferrer", className: IssuesTab_IssueDetail_module.ViewOnGitHub, onClick: (e) => e.stopPropagation() }, "View on GitHub \u2192")))));
}
/**
 * Get relative time string (e.g., "2 hours ago", "3 days ago")
 */
function getRelativeTimeString(date) {
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHour = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHour / 24);
    if (diffSec < 60) {
        return 'just now';
    }
    else if (diffMin < 60) {
        return `${diffMin} minute${diffMin !== 1 ? 's' : ''} ago`;
    }
    else if (diffHour < 24) {
        return `${diffHour} hour${diffHour !== 1 ? 's' : ''} ago`;
    }
    else if (diffDay < 30) {
        return `${diffDay} day${diffDay !== 1 ? 's' : ''} ago`;
    }
    else {
        return date.toLocaleDateString();
    }
}
/**
 * Get contrasting text color (black or white) for a background color
 */
function getContrastColor(hexColor) {
    // Remove # if present
    const hex = hexColor.replace('#', '');
    // Convert to RGB
    const r = parseInt(hex.substr(0, 2), 16);
    const g = parseInt(hex.substr(2, 2), 16);
    const b = parseInt(hex.substr(4, 2), 16);
    // Calculate luminance
    const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
    return luminance > 0.5 ? '#000000' : '#ffffff';
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssueItem.module.scss
var IssueItem_module = __webpack_require__(33295);
;// ./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssueItem.module.scss

      
      
      
      
      
      
      
      
      

var IssueItem_module_options = {};

IssueItem_module_options.styleTagTransform = (styleTagTransform_default());
IssueItem_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      IssueItem_module_options.insert = insertBySelector_default().bind(null, "head");
    
IssueItem_module_options.domAPI = (styleDomAPI_default());
IssueItem_module_options.insertStyleElement = (insertStyleElement_default());

var IssueItem_module_update = injectStylesIntoStyleTag_default()(IssueItem_module/* default */.A, IssueItem_module_options);




       /* harmony default export */ const IssuesTab_IssueItem_module = (IssueItem_module/* default */.A && IssueItem_module/* default */.A.locals ? IssueItem_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssueItem.tsx
/**
 * IssueItem Component
 *
 * Displays a single GitHub issue in a card format
 */


function IssueItem({ issue, onClick }) {
    const createdDate = new Date(issue.created_at);
    const relativeTime = IssueItem_getRelativeTimeString(createdDate);
    return (external_react_default().createElement("div", { className: IssuesTab_IssueItem_module.IssueItem, onClick: () => onClick(issue) },
        external_react_default().createElement("div", { className: IssuesTab_IssueItem_module.Header },
            external_react_default().createElement("div", { className: IssuesTab_IssueItem_module.TitleRow },
                external_react_default().createElement("span", { className: IssuesTab_IssueItem_module.Number },
                    "#",
                    issue.number),
                external_react_default().createElement("span", { className: IssuesTab_IssueItem_module.Title }, issue.title)),
            external_react_default().createElement("div", { className: IssuesTab_IssueItem_module.StatusBadge, "data-state": issue.state },
                issue.state === 'open' ? '🟢' : '🔴',
                " ",
                issue.state)),
        external_react_default().createElement("div", { className: IssuesTab_IssueItem_module.Meta },
            external_react_default().createElement("span", { className: IssuesTab_IssueItem_module.Author },
                "Opened by ",
                issue.user.login,
                " ",
                relativeTime),
            issue.comments > 0 && external_react_default().createElement("span", { className: IssuesTab_IssueItem_module.Comments },
                "\uD83D\uDCAC ",
                issue.comments)),
        issue.labels && issue.labels.length > 0 && (external_react_default().createElement("div", { className: IssuesTab_IssueItem_module.Labels },
            issue.labels.slice(0, 3).map((label) => (external_react_default().createElement("span", { key: label.id, className: IssuesTab_IssueItem_module.Label, style: {
                    backgroundColor: `#${label.color}`,
                    color: IssueItem_getContrastColor(label.color)
                } }, label.name))),
            issue.labels.length > 3 && external_react_default().createElement("span", { className: IssuesTab_IssueItem_module.MoreLabels },
                "+",
                issue.labels.length - 3)))));
}
/**
 * Get relative time string (e.g., "2 hours ago", "3 days ago")
 */
function IssueItem_getRelativeTimeString(date) {
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHour = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHour / 24);
    if (diffSec < 60) {
        return 'just now';
    }
    else if (diffMin < 60) {
        return `${diffMin} minute${diffMin !== 1 ? 's' : ''} ago`;
    }
    else if (diffHour < 24) {
        return `${diffHour} hour${diffHour !== 1 ? 's' : ''} ago`;
    }
    else if (diffDay < 30) {
        return `${diffDay} day${diffDay !== 1 ? 's' : ''} ago`;
    }
    else {
        return date.toLocaleDateString();
    }
}
/**
 * Get contrasting text color (black or white) for a background color
 */
function IssueItem_getContrastColor(hexColor) {
    // Remove # if present
    const hex = hexColor.replace('#', '');
    // Convert to RGB
    const r = parseInt(hex.substr(0, 2), 16);
    const g = parseInt(hex.substr(2, 2), 16);
    const b = parseInt(hex.substr(4, 2), 16);
    // Calculate luminance
    const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
    return luminance > 0.5 ? '#000000' : '#ffffff';
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssuesList.module.scss
var IssuesList_module = __webpack_require__(94417);
;// ./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssuesList.module.scss

      
      
      
      
      
      
      
      
      

var IssuesList_module_options = {};

IssuesList_module_options.styleTagTransform = (styleTagTransform_default());
IssuesList_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      IssuesList_module_options.insert = insertBySelector_default().bind(null, "head");
    
IssuesList_module_options.domAPI = (styleDomAPI_default());
IssuesList_module_options.insertStyleElement = (insertStyleElement_default());

var IssuesList_module_update = injectStylesIntoStyleTag_default()(IssuesList_module/* default */.A, IssuesList_module_options);




       /* harmony default export */ const IssuesTab_IssuesList_module = (IssuesList_module/* default */.A && IssuesList_module/* default */.A.locals ? IssuesList_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/GitHubPanel/components/IssuesTab/IssuesList.tsx
/**
 * IssuesList Component
 *
 * Displays a list of GitHub issues with loading states and pagination
 */




function IssuesList({ issues, loading, error, hasMore, loadMore, loadingMore, onRefresh }) {
    const [selectedIssue, setSelectedIssue] = (0,external_react_.useState)(null);
    if (loading) {
        return (external_react_default().createElement("div", { className: IssuesTab_IssuesList_module.LoadingState },
            external_react_default().createElement("div", { className: IssuesTab_IssuesList_module.Spinner }),
            external_react_default().createElement("p", null, "Loading issues...")));
    }
    if (error) {
        return (external_react_default().createElement("div", { className: IssuesTab_IssuesList_module.ErrorState },
            external_react_default().createElement("div", { className: IssuesTab_IssuesList_module.ErrorIcon }, "\u26A0\uFE0F"),
            external_react_default().createElement("h3", null, "Failed to load issues"),
            external_react_default().createElement("p", null, error.message),
            external_react_default().createElement("button", { className: IssuesTab_IssuesList_module.RetryButton, onClick: onRefresh }, "Try Again")));
    }
    if (issues.length === 0) {
        return (external_react_default().createElement("div", { className: IssuesTab_IssuesList_module.EmptyState },
            external_react_default().createElement("div", { className: IssuesTab_IssuesList_module.EmptyIcon }, "\uD83D\uDCDD"),
            external_react_default().createElement("h3", null, "No issues found"),
            external_react_default().createElement("p", null, "This repository doesn't have any issues yet.")));
    }
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement("div", { className: IssuesTab_IssuesList_module.IssuesList },
            issues.map((issue) => (external_react_default().createElement(IssueItem, { key: issue.id, issue: issue, onClick: setSelectedIssue }))),
            hasMore && (external_react_default().createElement("button", { className: IssuesTab_IssuesList_module.LoadMoreButton, onClick: loadMore, disabled: loadingMore }, loadingMore ? (external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement("div", { className: IssuesTab_IssuesList_module.SmallSpinner }),
                "Loading more...")) : ('Load More'))),
            !hasMore && issues.length > 0 && external_react_default().createElement("div", { className: IssuesTab_IssuesList_module.EndMessage }, "No more issues to load")),
        selectedIssue && external_react_default().createElement(IssueDetail, { issue: selectedIssue, onClose: () => setSelectedIssue(null) })));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRDetail.module.scss
var PRDetail_module = __webpack_require__(96039);
;// ./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRDetail.module.scss

      
      
      
      
      
      
      
      
      

var PRDetail_module_options = {};

PRDetail_module_options.styleTagTransform = (styleTagTransform_default());
PRDetail_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      PRDetail_module_options.insert = insertBySelector_default().bind(null, "head");
    
PRDetail_module_options.domAPI = (styleDomAPI_default());
PRDetail_module_options.insertStyleElement = (insertStyleElement_default());

var PRDetail_module_update = injectStylesIntoStyleTag_default()(PRDetail_module/* default */.A, PRDetail_module_options);




       /* harmony default export */ const PullRequestsTab_PRDetail_module = (PRDetail_module/* default */.A && PRDetail_module/* default */.A.locals ? PRDetail_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRDetail.tsx
/**
 * PRDetail Component
 *
 * Slide-out panel displaying full pull request details
 */


function PRDetail({ pr, onClose }) {
    const isDraft = pr.draft;
    const isMerged = pr.merged_at !== null;
    const isClosed = pr.state === 'closed' && !isMerged;
    return (external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.PRDetailOverlay, onClick: onClose },
        external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.PRDetail, onClick: (e) => e.stopPropagation() },
            external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.Header },
                external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.TitleSection },
                    external_react_default().createElement("h2", { className: PullRequestsTab_PRDetail_module.Title },
                        "#",
                        pr.number,
                        " ",
                        pr.title),
                    external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.StatusBadge, "data-status": getStatus(pr) },
                        getStatusIcon(pr),
                        " ",
                        getStatusText(pr))),
                external_react_default().createElement("button", { className: PullRequestsTab_PRDetail_module.CloseButton, onClick: onClose, "aria-label": "Close" }, "\u2715")),
            external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.Meta },
                external_react_default().createElement("span", null,
                    external_react_default().createElement("strong", null, pr.user.login),
                    " wants to merge ",
                    pr.commits,
                    " commit",
                    pr.commits !== 1 ? 's' : '',
                    " into",
                    ' ',
                    external_react_default().createElement("code", { className: PullRequestsTab_PRDetail_module.Branch }, pr.base.ref),
                    " from",
                    ' ',
                    external_react_default().createElement("code", { className: PullRequestsTab_PRDetail_module.Branch }, pr.head.ref)),
                external_react_default().createElement("span", null,
                    "\u2022 Opened ",
                    PRDetail_getRelativeTimeString(new Date(pr.created_at)))),
            pr.labels && pr.labels.length > 0 && (external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.Labels }, pr.labels.map((label) => (external_react_default().createElement("span", { key: label.id, className: PullRequestsTab_PRDetail_module.Label, style: {
                    backgroundColor: `#${label.color}`,
                    color: PRDetail_getContrastColor(label.color)
                } }, label.name))))),
            external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.Stats },
                external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.StatItem },
                    external_react_default().createElement("span", { className: PullRequestsTab_PRDetail_module.StatLabel }, "Commits"),
                    external_react_default().createElement("span", { className: PullRequestsTab_PRDetail_module.StatValue }, pr.commits)),
                external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.StatItem },
                    external_react_default().createElement("span", { className: PullRequestsTab_PRDetail_module.StatLabel }, "Files Changed"),
                    external_react_default().createElement("span", { className: PullRequestsTab_PRDetail_module.StatValue }, pr.changed_files)),
                external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.StatItem },
                    external_react_default().createElement("span", { className: PullRequestsTab_PRDetail_module.StatLabel }, "Comments"),
                    external_react_default().createElement("span", { className: PullRequestsTab_PRDetail_module.StatValue }, pr.comments))),
            external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.Body }, pr.body ? (external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.MarkdownContent }, pr.body)) : (external_react_default().createElement("p", { className: PullRequestsTab_PRDetail_module.NoDescription }, "No description provided."))),
            isMerged && pr.merged_at && (external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.MergeInfo },
                external_react_default().createElement("span", { className: PullRequestsTab_PRDetail_module.MergeIcon }, "\uD83D\uDFE3"),
                external_react_default().createElement("span", null,
                    "Merged ",
                    PRDetail_getRelativeTimeString(new Date(pr.merged_at))))),
            isDraft && (external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.DraftInfo },
                external_react_default().createElement("span", { className: PullRequestsTab_PRDetail_module.DraftIcon }, "\uD83D\uDCDD"),
                external_react_default().createElement("span", null, "This pull request is still a work in progress"))),
            isClosed && (external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.ClosedInfo },
                external_react_default().createElement("span", { className: PullRequestsTab_PRDetail_module.ClosedIcon }, "\uD83D\uDD34"),
                external_react_default().createElement("span", null, "This pull request was closed without merging"))),
            external_react_default().createElement("div", { className: PullRequestsTab_PRDetail_module.Footer },
                external_react_default().createElement("a", { href: pr.html_url, target: "_blank", rel: "noopener noreferrer", className: PullRequestsTab_PRDetail_module.ViewOnGitHub, onClick: (e) => e.stopPropagation() }, "View on GitHub \u2192")))));
}
/**
 * Get PR status
 */
function getStatus(pr) {
    if (pr.draft)
        return 'draft';
    if (pr.merged_at)
        return 'merged';
    if (pr.state === 'closed')
        return 'closed';
    return 'open';
}
/**
 * Get status icon
 */
function getStatusIcon(pr) {
    if (pr.draft)
        return '📝';
    if (pr.merged_at)
        return '🟣';
    if (pr.state === 'closed')
        return '🔴';
    return '🟢';
}
/**
 * Get status text
 */
function getStatusText(pr) {
    if (pr.draft)
        return 'Draft';
    if (pr.merged_at)
        return 'Merged';
    if (pr.state === 'closed')
        return 'Closed';
    return 'Open';
}
/**
 * Get relative time string (e.g., "2 hours ago", "3 days ago")
 */
function PRDetail_getRelativeTimeString(date) {
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHour = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHour / 24);
    if (diffSec < 60) {
        return 'just now';
    }
    else if (diffMin < 60) {
        return `${diffMin} minute${diffMin !== 1 ? 's' : ''} ago`;
    }
    else if (diffHour < 24) {
        return `${diffHour} hour${diffHour !== 1 ? 's' : ''} ago`;
    }
    else if (diffDay < 30) {
        return `${diffDay} day${diffDay !== 1 ? 's' : ''} ago`;
    }
    else {
        return date.toLocaleDateString();
    }
}
/**
 * Get contrasting text color (black or white) for a background color
 */
function PRDetail_getContrastColor(hexColor) {
    // Remove # if present
    const hex = hexColor.replace('#', '');
    // Convert to RGB
    const r = parseInt(hex.substr(0, 2), 16);
    const g = parseInt(hex.substr(2, 2), 16);
    const b = parseInt(hex.substr(4, 2), 16);
    // Calculate luminance
    const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
    return luminance > 0.5 ? '#000000' : '#ffffff';
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRItem.module.scss
var PRItem_module = __webpack_require__(65949);
;// ./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRItem.module.scss

      
      
      
      
      
      
      
      
      

var PRItem_module_options = {};

PRItem_module_options.styleTagTransform = (styleTagTransform_default());
PRItem_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      PRItem_module_options.insert = insertBySelector_default().bind(null, "head");
    
PRItem_module_options.domAPI = (styleDomAPI_default());
PRItem_module_options.insertStyleElement = (insertStyleElement_default());

var PRItem_module_update = injectStylesIntoStyleTag_default()(PRItem_module/* default */.A, PRItem_module_options);




       /* harmony default export */ const PullRequestsTab_PRItem_module = (PRItem_module/* default */.A && PRItem_module/* default */.A.locals ? PRItem_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRItem.tsx
/**
 * PRItem Component
 *
 * Displays a single GitHub pull request in a card format
 */


function PRItem({ pr, onClick }) {
    const createdDate = new Date(pr.created_at);
    const relativeTime = PRItem_getRelativeTimeString(createdDate);
    return (external_react_default().createElement("div", { className: PullRequestsTab_PRItem_module.PRItem, onClick: () => onClick(pr) },
        external_react_default().createElement("div", { className: PullRequestsTab_PRItem_module.Header },
            external_react_default().createElement("div", { className: PullRequestsTab_PRItem_module.TitleRow },
                external_react_default().createElement("span", { className: PullRequestsTab_PRItem_module.Number },
                    "#",
                    pr.number),
                external_react_default().createElement("span", { className: PullRequestsTab_PRItem_module.Title }, pr.title)),
            external_react_default().createElement("div", { className: PullRequestsTab_PRItem_module.StatusBadge, "data-status": PRItem_getStatus(pr) },
                PRItem_getStatusIcon(pr),
                " ",
                PRItem_getStatusText(pr))),
        external_react_default().createElement("div", { className: PullRequestsTab_PRItem_module.Meta },
            external_react_default().createElement("span", { className: PullRequestsTab_PRItem_module.Author },
                pr.user.login,
                " wants to merge into ",
                pr.base.ref,
                " from ",
                pr.head.ref),
            external_react_default().createElement("span", { className: PullRequestsTab_PRItem_module.Time }, relativeTime)),
        external_react_default().createElement("div", { className: PullRequestsTab_PRItem_module.Stats },
            pr.comments > 0 && external_react_default().createElement("span", { className: PullRequestsTab_PRItem_module.Stat },
                "\uD83D\uDCAC ",
                pr.comments),
            pr.commits > 0 && external_react_default().createElement("span", { className: PullRequestsTab_PRItem_module.Stat },
                "\uD83D\uDCDD ",
                pr.commits,
                " commits"),
            pr.changed_files > 0 && external_react_default().createElement("span", { className: PullRequestsTab_PRItem_module.Stat },
                "\uD83D\uDCC4 ",
                pr.changed_files,
                " files")),
        pr.labels && pr.labels.length > 0 && (external_react_default().createElement("div", { className: PullRequestsTab_PRItem_module.Labels },
            pr.labels.slice(0, 3).map((label) => (external_react_default().createElement("span", { key: label.id, className: PullRequestsTab_PRItem_module.Label, style: {
                    backgroundColor: `#${label.color}`,
                    color: PRItem_getContrastColor(label.color)
                } }, label.name))),
            pr.labels.length > 3 && external_react_default().createElement("span", { className: PullRequestsTab_PRItem_module.MoreLabels },
                "+",
                pr.labels.length - 3)))));
}
/**
 * Get PR status
 */
function PRItem_getStatus(pr) {
    if (pr.draft)
        return 'draft';
    if (pr.merged_at)
        return 'merged';
    if (pr.state === 'closed')
        return 'closed';
    return 'open';
}
/**
 * Get status icon
 */
function PRItem_getStatusIcon(pr) {
    if (pr.draft)
        return '📝';
    if (pr.merged_at)
        return '🟣';
    if (pr.state === 'closed')
        return '🔴';
    return '🟢';
}
/**
 * Get status text
 */
function PRItem_getStatusText(pr) {
    if (pr.draft)
        return 'Draft';
    if (pr.merged_at)
        return 'Merged';
    if (pr.state === 'closed')
        return 'Closed';
    return 'Open';
}
/**
 * Get relative time string (e.g., "2 hours ago", "3 days ago")
 */
function PRItem_getRelativeTimeString(date) {
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHour = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHour / 24);
    if (diffSec < 60) {
        return 'just now';
    }
    else if (diffMin < 60) {
        return `${diffMin} minute${diffMin !== 1 ? 's' : ''} ago`;
    }
    else if (diffHour < 24) {
        return `${diffHour} hour${diffHour !== 1 ? 's' : ''} ago`;
    }
    else if (diffDay < 30) {
        return `${diffDay} day${diffDay !== 1 ? 's' : ''} ago`;
    }
    else {
        return date.toLocaleDateString();
    }
}
/**
 * Get contrasting text color (black or white) for a background color
 */
function PRItem_getContrastColor(hexColor) {
    // Remove # if present
    const hex = hexColor.replace('#', '');
    // Convert to RGB
    const r = parseInt(hex.substr(0, 2), 16);
    const g = parseInt(hex.substr(2, 2), 16);
    const b = parseInt(hex.substr(4, 2), 16);
    // Calculate luminance
    const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
    return luminance > 0.5 ? '#000000' : '#ffffff';
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRsList.module.scss
var PRsList_module = __webpack_require__(99619);
;// ./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRsList.module.scss

      
      
      
      
      
      
      
      
      

var PRsList_module_options = {};

PRsList_module_options.styleTagTransform = (styleTagTransform_default());
PRsList_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      PRsList_module_options.insert = insertBySelector_default().bind(null, "head");
    
PRsList_module_options.domAPI = (styleDomAPI_default());
PRsList_module_options.insertStyleElement = (insertStyleElement_default());

var PRsList_module_update = injectStylesIntoStyleTag_default()(PRsList_module/* default */.A, PRsList_module_options);




       /* harmony default export */ const PullRequestsTab_PRsList_module = (PRsList_module/* default */.A && PRsList_module/* default */.A.locals ? PRsList_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/GitHubPanel/components/PullRequestsTab/PRsList.tsx
/**
 * PRsList Component
 *
 * Displays a list of GitHub pull requests with loading states and pagination
 */




function PRsList({ pullRequests, loading, error, hasMore, loadMore, loadingMore, onRefresh }) {
    const [selectedPR, setSelectedPR] = (0,external_react_.useState)(null);
    if (loading) {
        return (external_react_default().createElement("div", { className: PullRequestsTab_PRsList_module.LoadingState },
            external_react_default().createElement("div", { className: PullRequestsTab_PRsList_module.Spinner }),
            external_react_default().createElement("p", null, "Loading pull requests...")));
    }
    if (error) {
        return (external_react_default().createElement("div", { className: PullRequestsTab_PRsList_module.ErrorState },
            external_react_default().createElement("div", { className: PullRequestsTab_PRsList_module.ErrorIcon }, "\u26A0\uFE0F"),
            external_react_default().createElement("h3", null, "Failed to load pull requests"),
            external_react_default().createElement("p", null, error.message),
            external_react_default().createElement("button", { className: PullRequestsTab_PRsList_module.RetryButton, onClick: onRefresh }, "Try Again")));
    }
    if (pullRequests.length === 0) {
        return (external_react_default().createElement("div", { className: PullRequestsTab_PRsList_module.EmptyState },
            external_react_default().createElement("div", { className: PullRequestsTab_PRsList_module.EmptyIcon }, "\uD83D\uDD00"),
            external_react_default().createElement("h3", null, "No pull requests found"),
            external_react_default().createElement("p", null, "This repository doesn't have any pull requests yet.")));
    }
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement("div", { className: PullRequestsTab_PRsList_module.PRsList },
            pullRequests.map((pr) => (external_react_default().createElement(PRItem, { key: pr.id, pr: pr, onClick: setSelectedPR }))),
            hasMore && (external_react_default().createElement("button", { className: PullRequestsTab_PRsList_module.LoadMoreButton, onClick: loadMore, disabled: loadingMore }, loadingMore ? (external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement("div", { className: PullRequestsTab_PRsList_module.SmallSpinner }),
                "Loading more...")) : ('Load More'))),
            !hasMore && pullRequests.length > 0 && external_react_default().createElement("div", { className: PullRequestsTab_PRsList_module.EndMessage }, "No more pull requests to load")),
        selectedPR && external_react_default().createElement(PRDetail, { pr: selectedPR, onClose: () => setSelectedPR(null) })));
}

;// ./src/editor/src/views/panels/GitHubPanel/hooks/useGitSyncStatus.ts
/**
 * useGitSyncStatus Hook
 *
 * Monitors git sync status including ahead/behind counts and uncommitted changes.
 * Provides push/pull functionality.
 */





function useGitSyncStatus() {
    const [status, setStatus] = (0,external_react_.useState)({
        ahead: 0,
        behind: 0,
        hasUncommittedChanges: false,
        loading: true,
        error: null,
        isSyncing: false
    });
    const fetchStatus = (0,external_react_.useCallback)(async () => {
        var _a, _b;
        const projectDirectory = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a._retainedProjectDirectory;
        if (!projectDirectory) {
            setStatus((prev) => ({
                ...prev,
                loading: false,
                error: 'No project directory'
            }));
            return;
        }
        try {
            // Ensure git auth is set up
            const projectId = ((_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.id) || 'temp';
            LocalProjectsModel/* LocalProjectsModel */.h.instance.setCurrentGlobalGitAuth(projectId);
            const git = new noodl_git_src/* Git */.TU(projectmerger.mergeProject);
            await git.openRepository(projectDirectory);
            // Check for remote
            const remoteName = await git.getRemoteName();
            if (!remoteName) {
                setStatus((prev) => ({
                    ...prev,
                    loading: false,
                    error: 'No remote configured'
                }));
                return;
            }
            // Fetch latest from remote (silently)
            try {
                await git.fetch({ onProgress: () => { } });
            }
            catch (fetchError) {
                console.warn('[useGitSyncStatus] Fetch warning:', fetchError);
                // Continue anyway - might be offline
            }
            // Get ahead/behind counts
            let ahead = 0;
            let behind = 0;
            try {
                const aheadBehind = await git.currentAheadBehind();
                ahead = aheadBehind.ahead;
                behind = aheadBehind.behind;
            }
            catch (abError) {
                console.warn('[useGitSyncStatus] Could not get ahead/behind:', abError);
                // Remote might not have any commits yet
            }
            // Check for uncommitted changes
            const changes = await git.status();
            const hasUncommittedChanges = changes.length > 0;
            setStatus({
                ahead,
                behind,
                hasUncommittedChanges,
                loading: false,
                error: null,
                isSyncing: false
            });
        }
        catch (error) {
            console.error('[useGitSyncStatus] Error:', error);
            setStatus((prev) => ({
                ...prev,
                loading: false,
                error: error instanceof Error ? error.message : 'Failed to get sync status'
            }));
        }
    }, []);
    const push = (0,external_react_.useCallback)(async () => {
        var _a, _b;
        const projectDirectory = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a._retainedProjectDirectory;
        if (!projectDirectory) {
            throw new Error('No project directory');
        }
        setStatus((prev) => ({ ...prev, isSyncing: true, error: null }));
        try {
            // Ensure git auth is set up
            const projectId = ((_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.id) || 'temp';
            LocalProjectsModel/* LocalProjectsModel */.h.instance.setCurrentGlobalGitAuth(projectId);
            const git = new noodl_git_src/* Git */.TU(projectmerger.mergeProject);
            await git.openRepository(projectDirectory);
            // Check for uncommitted changes first
            const changes = await git.status();
            if (changes.length > 0) {
                // Auto-commit changes before pushing
                console.log('[useGitSyncStatus] Committing changes before push...');
                await git.commit('Auto-commit before push');
            }
            console.log('[useGitSyncStatus] Pushing to remote...');
            await git.push();
            console.log('[useGitSyncStatus] Push successful');
            // Refresh status
            await fetchStatus();
        }
        catch (error) {
            console.error('[useGitSyncStatus] Push error:', error);
            setStatus((prev) => ({
                ...prev,
                isSyncing: false,
                error: error instanceof Error ? error.message : 'Push failed'
            }));
            throw error;
        }
    }, [fetchStatus]);
    const pull = (0,external_react_.useCallback)(async () => {
        var _a, _b, _c;
        const projectDirectory = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a._retainedProjectDirectory;
        if (!projectDirectory) {
            throw new Error('No project directory');
        }
        setStatus((prev) => ({ ...prev, isSyncing: true, error: null }));
        try {
            // Ensure git auth is set up
            const projectId = ((_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.id) || 'temp';
            LocalProjectsModel/* LocalProjectsModel */.h.instance.setCurrentGlobalGitAuth(projectId);
            const git = new noodl_git_src/* Git */.TU(projectmerger.mergeProject);
            await git.openRepository(projectDirectory);
            // Stash any uncommitted changes
            const changes = await git.status();
            const needsStash = changes.length > 0;
            if (needsStash) {
                console.log('[useGitSyncStatus] Stashing local changes...');
                await git.stashPushChanges();
            }
            // Fetch and merge
            console.log('[useGitSyncStatus] Fetching from remote...');
            await git.fetch({ onProgress: () => { } });
            // Get current branch
            const branchName = await git.getCurrentBranchName();
            const remoteBranch = `origin/${branchName}`;
            console.log('[useGitSyncStatus] Merging', remoteBranch, 'into', branchName);
            await git.mergeToCurrentBranch(remoteBranch, false);
            // Pop stash if we stashed
            if (needsStash) {
                console.log('[useGitSyncStatus] Restoring stashed changes...');
                await git.stashPopChanges();
            }
            console.log('[useGitSyncStatus] Pull successful');
            // Refresh status
            await fetchStatus();
            // Notify project to reload
            (_c = projectmodel.ProjectModel.instance) === null || _c === void 0 ? void 0 : _c.notifyListeners('projectMightNeedRefresh');
        }
        catch (error) {
            console.error('[useGitSyncStatus] Pull error:', error);
            setStatus((prev) => ({
                ...prev,
                isSyncing: false,
                error: error instanceof Error ? error.message : 'Pull failed'
            }));
            throw error;
        }
    }, [fetchStatus]);
    // Initial fetch
    (0,external_react_.useEffect)(() => {
        fetchStatus();
    }, [fetchStatus]);
    // Auto-refresh on project changes
    (0,external_react_.useEffect)(() => {
        var _a, _b;
        const handleProjectChange = () => {
            fetchStatus();
        };
        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.on('projectSaved', handleProjectChange);
        (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.on('remoteChanged', handleProjectChange);
        return () => {
            var _a;
            (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.off(handleProjectChange);
        };
    }, [fetchStatus]);
    return {
        ...status,
        push,
        pull,
        refresh: fetchStatus
    };
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/GitHubPanel/components/SyncToolbar/SyncToolbar.module.scss
var SyncToolbar_module = __webpack_require__(83770);
;// ./src/editor/src/views/panels/GitHubPanel/components/SyncToolbar/SyncToolbar.module.scss

      
      
      
      
      
      
      
      
      

var SyncToolbar_module_options = {};

SyncToolbar_module_options.styleTagTransform = (styleTagTransform_default());
SyncToolbar_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      SyncToolbar_module_options.insert = insertBySelector_default().bind(null, "head");
    
SyncToolbar_module_options.domAPI = (styleDomAPI_default());
SyncToolbar_module_options.insertStyleElement = (insertStyleElement_default());

var SyncToolbar_module_update = injectStylesIntoStyleTag_default()(SyncToolbar_module/* default */.A, SyncToolbar_module_options);




       /* harmony default export */ const SyncToolbar_SyncToolbar_module = (SyncToolbar_module/* default */.A && SyncToolbar_module/* default */.A.locals ? SyncToolbar_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/GitHubPanel/components/SyncToolbar/SyncToolbar.tsx
/**
 * SyncToolbar
 *
 * Toolbar with push/pull buttons and sync status display
 */



function SyncToolbar({ owner, repo }) {
    const { ahead, behind, hasUncommittedChanges, loading, error, isSyncing, push, pull, refresh } = useGitSyncStatus();
    const [lastError, setLastError] = (0,external_react_.useState)(null);
    const handlePush = async () => {
        setLastError(null);
        try {
            await push();
        }
        catch (err) {
            setLastError(err instanceof Error ? err.message : 'Push failed');
        }
    };
    const handlePull = async () => {
        setLastError(null);
        try {
            await pull();
        }
        catch (err) {
            setLastError(err instanceof Error ? err.message : 'Pull failed');
        }
    };
    const handleRefresh = () => {
        setLastError(null);
        refresh();
    };
    // Show error or status message
    const displayError = lastError || error;
    return (external_react_default().createElement("div", { className: SyncToolbar_SyncToolbar_module.SyncToolbar },
        external_react_default().createElement("div", { className: SyncToolbar_SyncToolbar_module.RepoInfo },
            external_react_default().createElement("span", { className: SyncToolbar_SyncToolbar_module.RepoName },
                owner,
                "/",
                repo),
            loading && external_react_default().createElement("span", { className: SyncToolbar_SyncToolbar_module.StatusText }, "Loading..."),
            !loading && !displayError && (external_react_default().createElement("span", { className: SyncToolbar_SyncToolbar_module.StatusText },
                hasUncommittedChanges && external_react_default().createElement("span", { className: SyncToolbar_SyncToolbar_module.ChangesIndicator }, "Uncommitted changes"),
                !hasUncommittedChanges && ahead === 0 && behind === 0 && (external_react_default().createElement("span", { className: SyncToolbar_SyncToolbar_module.SyncedIndicator }, "Up to date"))))),
        external_react_default().createElement("div", { className: SyncToolbar_SyncToolbar_module.Actions },
            external_react_default().createElement("button", { className: `${SyncToolbar_SyncToolbar_module.SyncButton} ${behind > 0 ? SyncToolbar_SyncToolbar_module.HasChanges : ''}`, onClick: handlePull, disabled: isSyncing || loading, title: behind > 0 ? `Pull ${behind} commit${behind > 1 ? 's' : ''} from remote` : 'Pull from remote' },
                external_react_default().createElement(DownloadIcon, null),
                external_react_default().createElement("span", null, "Pull"),
                behind > 0 && external_react_default().createElement("span", { className: SyncToolbar_SyncToolbar_module.Badge }, behind)),
            external_react_default().createElement("button", { className: `${SyncToolbar_SyncToolbar_module.SyncButton} ${ahead > 0 || hasUncommittedChanges ? SyncToolbar_SyncToolbar_module.HasChanges : ''}`, onClick: handlePush, disabled: isSyncing || loading || (ahead === 0 && !hasUncommittedChanges), title: hasUncommittedChanges
                    ? 'Commit and push changes'
                    : ahead > 0
                        ? `Push ${ahead} commit${ahead > 1 ? 's' : ''} to remote`
                        : 'Nothing to push' },
                external_react_default().createElement(UploadIcon, null),
                external_react_default().createElement("span", null, "Push"),
                (ahead > 0 || hasUncommittedChanges) && (external_react_default().createElement("span", { className: SyncToolbar_SyncToolbar_module.Badge }, hasUncommittedChanges ? '!' : ahead))),
            external_react_default().createElement("button", { className: SyncToolbar_SyncToolbar_module.RefreshButton, onClick: handleRefresh, disabled: isSyncing || loading, title: "Refresh sync status" },
                external_react_default().createElement(RefreshIcon, { spinning: loading || isSyncing }))),
        displayError && (external_react_default().createElement("div", { className: SyncToolbar_SyncToolbar_module.ErrorBar },
            external_react_default().createElement("span", null, displayError),
            external_react_default().createElement("button", { onClick: () => setLastError(null) }, "\u00D7")))));
}
// Icon components
function DownloadIcon() {
    return (external_react_default().createElement("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "currentColor" },
        external_react_default().createElement("path", { d: "M8 12L3 7l1.4-1.4L7 8.2V1h2v7.2l2.6-2.6L13 7l-5 5z" }),
        external_react_default().createElement("path", { d: "M14 13v1H2v-1h12z" })));
}
function UploadIcon() {
    return (external_react_default().createElement("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "currentColor" },
        external_react_default().createElement("path", { d: "M8 1l5 5-1.4 1.4L9 4.8V12H7V4.8L4.4 7.4 3 6l5-5z" }),
        external_react_default().createElement("path", { d: "M14 13v1H2v-1h12z" })));
}
function RefreshIcon({ spinning }) {
    return (external_react_default().createElement("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "currentColor", className: spinning ? SyncToolbar_SyncToolbar_module.Spinning : undefined },
        external_react_default().createElement("path", { d: "M13.5 8c0-3-2.5-5.5-5.5-5.5S2.5 5 2.5 8H1C1 4.1 4.1 1 8 1s7 3.1 7 7h-1.5z" }),
        external_react_default().createElement("path", { d: "M2.5 8c0 3 2.5 5.5 5.5 5.5s5.5-2.5 5.5-5.5H15c0 3.9-3.1 7-7 7s-7-3.1-7-7h1.5z" })));
}

;// ./src/editor/src/views/panels/GitHubPanel/components/SyncToolbar/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/GitHubPanel/GitHubPanel.module.scss
var GitHubPanel_module = __webpack_require__(5731);
;// ./src/editor/src/views/panels/GitHubPanel/GitHubPanel.module.scss

      
      
      
      
      
      
      
      
      

var GitHubPanel_module_options = {};

GitHubPanel_module_options.styleTagTransform = (styleTagTransform_default());
GitHubPanel_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      GitHubPanel_module_options.insert = insertBySelector_default().bind(null, "head");
    
GitHubPanel_module_options.domAPI = (styleDomAPI_default());
GitHubPanel_module_options.insertStyleElement = (insertStyleElement_default());

var GitHubPanel_module_update = injectStylesIntoStyleTag_default()(GitHubPanel_module/* default */.A, GitHubPanel_module_options);




       /* harmony default export */ const GitHubPanel_GitHubPanel_module = (GitHubPanel_module/* default */.A && GitHubPanel_module/* default */.A.locals ? GitHubPanel_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/GitHubPanel/hooks/useGitHubRepository.ts
/**
 * useGitHubRepository Hook
 *
 * Extracts GitHub repository information from the Git remote URL.
 * Returns owner, repo name, connection status, and detailed git state.
 */




/**
 * Parse GitHub owner and repo from a remote URL
 * Handles formats:
 * - https://github.com/owner/repo.git
 * - git@github.com:owner/repo.git
 * - https://github.com/owner/repo
 */
function parseGitHubUrl(url) {
    if (!url || !url.includes('github.com')) {
        return null;
    }
    // Remove .git suffix if present
    const cleanUrl = url.replace(/\.git$/, '');
    // Handle HTTPS format: https://github.com/owner/repo
    const httpsMatch = cleanUrl.match(/github\.com\/([^/]+)\/([^/]+)/);
    if (httpsMatch) {
        return {
            owner: httpsMatch[1],
            repo: httpsMatch[2]
        };
    }
    // Handle SSH format: git@github.com:owner/repo
    const sshMatch = cleanUrl.match(/github\.com:([^/]+)\/([^/]+)/);
    if (sshMatch) {
        return {
            owner: sshMatch[1],
            repo: sshMatch[2]
        };
    }
    return null;
}
const initialState = {
    owner: null,
    repo: null,
    isGitHub: false,
    isReady: false,
    gitState: 'loading',
    remoteUrl: null,
    provider: null
};
/**
 * Hook to get GitHub repository information from current project's Git remote
 */
function useGitHubRepository() {
    const [repoInfo, setRepoInfo] = (0,external_react_.useState)(initialState);
    const fetchRepoInfo = (0,external_react_.useCallback)(async () => {
        var _a;
        try {
            const projectDirectory = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a._retainedProjectDirectory;
            if (!projectDirectory) {
                setRepoInfo({
                    ...initialState,
                    gitState: 'no-git'
                });
                return;
            }
            // Create Git instance and try to open repository
            const git = new noodl_git_src/* Git */.TU(projectmerger.mergeProject);
            try {
                await git.openRepository(projectDirectory);
            }
            catch (gitError) {
                // Not a git repository - this is expected for non-git projects
                const errorMessage = gitError instanceof Error ? gitError.message : String(gitError);
                if (errorMessage.includes('Not a git repository')) {
                    console.log('[useGitHubRepository] Project is not a git repository');
                }
                else {
                    console.warn('[useGitHubRepository] Git error:', errorMessage);
                }
                setRepoInfo({
                    ...initialState,
                    gitState: 'no-git'
                });
                return;
            }
            // Check if we have a remote
            const remoteName = await git.getRemoteName();
            if (!remoteName) {
                console.log('[useGitHubRepository] No remote configured');
                setRepoInfo({
                    ...initialState,
                    gitState: 'git-no-remote'
                });
                return;
            }
            // Get remote URL and provider
            const remoteUrl = git.OriginUrl;
            const provider = git.Provider;
            // Check if it's a GitHub repository
            if (provider !== 'github') {
                setRepoInfo({
                    owner: null,
                    repo: null,
                    isGitHub: false,
                    isReady: false,
                    gitState: 'remote-not-github',
                    remoteUrl,
                    provider
                });
                return;
            }
            // Parse the remote URL
            const parsed = parseGitHubUrl(remoteUrl);
            if (parsed) {
                setRepoInfo({
                    owner: parsed.owner,
                    repo: parsed.repo,
                    isGitHub: true,
                    isReady: true,
                    gitState: 'github-connected',
                    remoteUrl,
                    provider
                });
            }
            else {
                setRepoInfo({
                    owner: null,
                    repo: null,
                    isGitHub: true, // It's GitHub but couldn't parse
                    isReady: false,
                    gitState: 'github-connected',
                    remoteUrl,
                    provider
                });
            }
        }
        catch (error) {
            console.error('[useGitHubRepository] Unexpected error:', error);
            setRepoInfo({
                ...initialState,
                gitState: 'no-git'
            });
        }
    }, []);
    (0,external_react_.useEffect)(() => {
        var _a, _b;
        fetchRepoInfo();
        // Refetch when project changes
        const handleProjectChange = () => {
            fetchRepoInfo();
        };
        (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.on('projectOpened', handleProjectChange);
        (_b = projectmodel.ProjectModel.instance) === null || _b === void 0 ? void 0 : _b.on('remoteChanged', handleProjectChange);
        return () => {
            var _a;
            (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.off(handleProjectChange);
        };
    }, [fetchRepoInfo]);
    return { ...repoInfo, refetch: fetchRepoInfo };
}

;// ./src/editor/src/views/panels/GitHubPanel/hooks/useIssues.ts
/**
 * useIssues Hook
 *
 * Fetches and manages GitHub issues for a repository.
 * Handles pagination, filtering, and real-time updates.
 */



const DEFAULT_PER_PAGE = 30;
/**
 * Hook to fetch and manage GitHub issues
 */
function useIssues({ owner, repo, filters = {}, enabled = true }) {
    const [issues, setIssues] = (0,external_react_.useState)([]);
    const [loading, setLoading] = (0,external_react_.useState)(true);
    const [loadingMore, setLoadingMore] = (0,external_react_.useState)(false);
    const [error, setError] = (0,external_react_.useState)(null);
    const [page, setPage] = (0,external_react_.useState)(1);
    const [hasMore, setHasMore] = (0,external_react_.useState)(true);
    const client = GitHubClient.instance;
    // Use ref to store filters to avoid infinite loops
    const filtersRef = (0,external_react_.useRef)(filters);
    filtersRef.current = filters;
    const fetchIssues = (0,external_react_.useCallback)(async (pageNum = 1, append = false) => {
        if (!owner || !repo || !enabled) {
            setLoading(false);
            return;
        }
        try {
            if (append) {
                setLoadingMore(true);
            }
            else {
                setLoading(true);
                setError(null);
            }
            const response = await client.listIssues(owner, repo, {
                ...filtersRef.current,
                per_page: DEFAULT_PER_PAGE,
                page: pageNum
            });
            const newIssues = response.data;
            if (append) {
                setIssues((prev) => [...prev, ...newIssues]);
            }
            else {
                setIssues(newIssues);
            }
            // Check if there are more issues to load
            setHasMore(newIssues.length === DEFAULT_PER_PAGE);
            setPage(pageNum);
        }
        catch (err) {
            console.error('Failed to fetch issues:', err);
            setError(err instanceof Error ? err : new Error('Failed to fetch issues'));
            setHasMore(false);
        }
        finally {
            setLoading(false);
            setLoadingMore(false);
        }
    }, [owner, repo, enabled, client]);
    const refetch = (0,external_react_.useCallback)(async () => {
        setPage(1);
        setHasMore(true);
        await fetchIssues(1, false);
    }, [fetchIssues]);
    const loadMore = (0,external_react_.useCallback)(async () => {
        if (!loadingMore && hasMore) {
            await fetchIssues(page + 1, true);
        }
    }, [fetchIssues, page, hasMore, loadingMore]);
    // Serialize filters to avoid infinite loops from object reference changes
    const filtersKey = JSON.stringify(filters);
    // Initial fetch - use serialized filters key to avoid infinite loop
    // Note: refetch is excluded from deps to prevent loops, we use filtersKey instead
    (0,external_react_.useEffect)(() => {
        if (owner && repo && enabled) {
            refetch();
        }
    }, [owner, repo, filtersKey, enabled, refetch]);
    // Listen for cache invalidation events
    (0,useEventListener/* useEventListener */.M)(client, 'rate-limit-updated', () => {
        // Could show a notification about rate limits
    });
    return {
        issues,
        loading,
        error,
        refetch,
        hasMore,
        loadMore,
        loadingMore
    };
}

;// ./src/editor/src/views/panels/GitHubPanel/hooks/usePullRequests.ts
/**
 * usePullRequests Hook
 *
 * Fetches and manages GitHub pull requests for a repository.
 * Handles pagination, filtering, and real-time updates.
 */



const usePullRequests_DEFAULT_PER_PAGE = 30;
/**
 * Hook to fetch and manage GitHub pull requests
 */
function usePullRequests({ owner, repo, filters = {}, enabled = true }) {
    const [pullRequests, setPullRequests] = (0,external_react_.useState)([]);
    const [loading, setLoading] = (0,external_react_.useState)(true);
    const [loadingMore, setLoadingMore] = (0,external_react_.useState)(false);
    const [error, setError] = (0,external_react_.useState)(null);
    const [page, setPage] = (0,external_react_.useState)(1);
    const [hasMore, setHasMore] = (0,external_react_.useState)(true);
    const client = GitHubClient.instance;
    // Use ref to store filters to avoid infinite loops
    const filtersRef = (0,external_react_.useRef)(filters);
    filtersRef.current = filters;
    const fetchPullRequests = (0,external_react_.useCallback)(async (pageNum = 1, append = false) => {
        if (!owner || !repo || !enabled) {
            setLoading(false);
            return;
        }
        try {
            if (append) {
                setLoadingMore(true);
            }
            else {
                setLoading(true);
                setError(null);
            }
            const response = await client.listPullRequests(owner, repo, {
                ...filtersRef.current,
                per_page: usePullRequests_DEFAULT_PER_PAGE,
                page: pageNum
            });
            const newPRs = response.data;
            if (append) {
                setPullRequests((prev) => [...prev, ...newPRs]);
            }
            else {
                setPullRequests(newPRs);
            }
            // Check if there are more PRs to load
            setHasMore(newPRs.length === usePullRequests_DEFAULT_PER_PAGE);
            setPage(pageNum);
        }
        catch (err) {
            console.error('Failed to fetch pull requests:', err);
            setError(err instanceof Error ? err : new Error('Failed to fetch pull requests'));
            setHasMore(false);
        }
        finally {
            setLoading(false);
            setLoadingMore(false);
        }
    }, [owner, repo, enabled, client]);
    const refetch = (0,external_react_.useCallback)(async () => {
        setPage(1);
        setHasMore(true);
        await fetchPullRequests(1, false);
    }, [fetchPullRequests]);
    const loadMore = (0,external_react_.useCallback)(async () => {
        if (!loadingMore && hasMore) {
            await fetchPullRequests(page + 1, true);
        }
    }, [fetchPullRequests, page, hasMore, loadingMore]);
    // Serialize filters to avoid infinite loops
    const filtersKey = JSON.stringify(filters);
    // Initial fetch - use serialized filters key
    (0,external_react_.useEffect)(() => {
        if (owner && repo && enabled) {
            refetch();
        }
    }, [owner, repo, filtersKey, enabled, refetch]);
    // Listen for cache invalidation events
    (0,useEventListener/* useEventListener */.M)(client, 'rate-limit-updated', () => {
        // Could show a notification about rate limits
    });
    return {
        pullRequests,
        loading,
        error,
        refetch,
        hasMore,
        loadMore,
        loadingMore
    };
}

;// ./src/editor/src/views/panels/GitHubPanel/GitHubPanel.tsx
/**
 * GitHubPanel - GitHub Issues and Pull Requests integration
 *
 * Displays GitHub issues and PRs for the connected repository
 * with filtering, search, and detail views.
 */











function GitHubPanel() {
    const [activeTab, setActiveTab] = (0,external_react_.useState)('issues');
    const [isConnected, setIsConnected] = (0,external_react_.useState)(false);
    const [isInitialized, setIsInitialized] = (0,external_react_.useState)(false);
    const client = GitHubClient.instance;
    const { owner, repo, isGitHub, isReady, gitState, remoteUrl, provider, refetch } = useGitHubRepository();
    // Initialize GitHubOAuthService on mount
    (0,external_react_.useEffect)(() => {
        console.log('🔧 [GitHubPanel] useEffect running - initializing OAuth service');
        const initAuth = async () => {
            try {
                console.log('🔧 [GitHubPanel] Calling GitHubOAuthService.instance.initialize()...');
                await GitHubOAuthService/* GitHubOAuthService */.W.instance.initialize();
                const ready = client.isReady();
                console.log('🔧 [GitHubPanel] After initialize - client.isReady():', ready);
                setIsConnected(ready);
            }
            catch (error) {
                console.error('[GitHubPanel] Failed to initialize OAuth service:', error);
            }
            finally {
                setIsInitialized(true);
                console.log('🔧 [GitHubPanel] Initialization complete');
            }
        };
        initAuth();
    }, [client]);
    // Listen for auth state changes
    console.log('🎧 [GitHubPanel] Setting up useEventListener for auth-state-changed');
    (0,useEventListener/* useEventListener */.M)(GitHubOAuthService/* GitHubOAuthService */.W.instance, 'auth-state-changed', (event) => {
        console.log('🔔 [GitHubPanel] AUTH STATE CHANGED EVENT RECEIVED:', event.authenticated);
        setIsConnected(event.authenticated);
    });
    const handleConnectGitHub = async () => {
        try {
            await GitHubOAuthService/* GitHubOAuthService */.W.instance.initiateOAuth();
        }
        catch (error) {
            console.error('Failed to initiate GitHub OAuth:', error);
        }
    };
    const handleConnected = () => {
        // Refetch git state after connecting
        refetch();
    };
    // Show loading while initializing
    if (!isInitialized) {
        return (external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.GitHubPanel },
            external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.EmptyState },
                external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.EmptyStateIcon }, "\u23F3"),
                external_react_default().createElement("h3", null, "Initializing"),
                external_react_default().createElement("p", null, "Checking GitHub connection..."))));
    }
    // Loading state while determining git state
    if (gitState === 'loading') {
        return (external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.GitHubPanel },
            external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.EmptyState },
                external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.EmptyStateIcon }, "\u23F3"),
                external_react_default().createElement("h3", null, "Loading"),
                external_react_default().createElement("p", null, "Checking repository status..."))));
    }
    // Not connected to GitHub account
    if (!isConnected) {
        return (external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.GitHubPanel },
            external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.EmptyState },
                external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.EmptyStateIcon }, "\uD83D\uDD17"),
                external_react_default().createElement("h3", null, "Connect GitHub"),
                external_react_default().createElement("p", null, "Connect your GitHub account to view and manage issues and pull requests."),
                external_react_default().createElement("button", { className: GitHubPanel_GitHubPanel_module.ConnectButton, onClick: handleConnectGitHub }, "Connect GitHub Account"))));
    }
    // Project not connected to GitHub - show connect options
    if (gitState === 'no-git' || gitState === 'git-no-remote' || gitState === 'remote-not-github') {
        return (external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.GitHubPanel },
            external_react_default().createElement(ConnectToGitHubView, { gitState: gitState, remoteUrl: remoteUrl, provider: provider, onConnected: handleConnected })));
    }
    if (!isGitHub) {
        return (external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.GitHubPanel },
            external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.EmptyState },
                external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.EmptyStateIcon }, "\uD83D\uDCE6"),
                external_react_default().createElement("h3", null, "Not a GitHub Repository"),
                external_react_default().createElement("p", null, "This project is not connected to a GitHub repository."))));
    }
    if (!isReady) {
        return (external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.GitHubPanel },
            external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.EmptyState },
                external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.EmptyStateIcon }, "\u2699\uFE0F"),
                external_react_default().createElement("h3", null, "Loading Repository"),
                external_react_default().createElement("p", null, "Loading repository information..."))));
    }
    return (external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.GitHubPanel },
        external_react_default().createElement(SyncToolbar, { owner: owner, repo: repo }),
        external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.Header },
            external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.Tabs },
                external_react_default().createElement("button", { className: `${GitHubPanel_GitHubPanel_module.Tab} ${activeTab === 'issues' ? GitHubPanel_GitHubPanel_module.TabActive : ''}`, onClick: () => setActiveTab('issues') }, "Issues"),
                external_react_default().createElement("button", { className: `${GitHubPanel_GitHubPanel_module.Tab} ${activeTab === 'pullRequests' ? GitHubPanel_GitHubPanel_module.TabActive : ''}`, onClick: () => setActiveTab('pullRequests') }, "Pull Requests"))),
        external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.Content },
            activeTab === 'issues' && external_react_default().createElement(IssuesTab, { owner: owner, repo: repo }),
            activeTab === 'pullRequests' && external_react_default().createElement(PullRequestsTab, { owner: owner, repo: repo }))));
}
/**
 * Issues tab content
 */
function IssuesTab({ owner, repo }) {
    const { issues, loading, error, hasMore, loadMore, loadingMore, refetch } = useIssues({
        owner,
        repo,
        filters: { state: 'open' }
    });
    return (external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.IssuesTab },
        external_react_default().createElement(IssuesList, { issues: issues, loading: loading, error: error, hasMore: hasMore, loadMore: loadMore, loadingMore: loadingMore, onRefresh: refetch })));
}
/**
 * Pull Requests tab content
 */
function PullRequestsTab({ owner, repo }) {
    const { pullRequests, loading, error, hasMore, loadMore, loadingMore, refetch } = usePullRequests({
        owner,
        repo,
        filters: { state: 'open' }
    });
    return (external_react_default().createElement("div", { className: GitHubPanel_GitHubPanel_module.PullRequestsTab },
        external_react_default().createElement(PRsList, { pullRequests: pullRequests, loading: loading, error: error, hasMore: hasMore, loadMore: loadMore, loadingMore: loadingMore, onRefresh: refetch })));
}

;// ./src/editor/src/views/panels/GitHubPanel/index.ts


;// ./src/editor/src/views/panels/NodeReferencesPanel/index.ts
const NodeReferencesPanel_ID = 'node-references';

;// ./src/editor/src/hooks/useFocusRefOnPanelActive.ts



function useFocusRefOnPanelActive(inputRef, panelId) {
    (0,external_react_.useEffect)(() => {
        if (!inputRef.current) {
            return;
        }
        const eventRef = {};
        models_sidebar/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.activeChanged, (activeId, previousActiveId) => {
            if (activeId === panelId && panelId !== previousActiveId) {
                //not sure why this timeout is required, but it doesn't work without it
                setTimeout(() => {
                    var _a;
                    (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
                }, 10);
            }
        }, eventRef);
        return () => {
            models_sidebar/* SidebarModel */.s.instance.off(eventRef);
        };
    }, [inputRef.current, panelId]);
}
function useOnPanelActive(func, panelId) {
    (0,external_react_.useEffect)(() => {
        const eventRef = {};
        models_sidebar/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.activeChanged, (activeId, previousActiveId) => {
            if (activeId === panelId && panelId !== previousActiveId) {
                //not sure why this timeout is required, but it doesn't work without it
                setTimeout(() => {
                    func();
                }, 10);
            }
        }, eventRef);
        return () => {
            models_sidebar/* SidebarModel */.s.instance.off(eventRef);
        };
    }, [func, panelId]);
}

;// ./src/editor/src/hooks/useNodeLibraryLoaded.ts


function useNodeLibraryLoaded() {
    const [group] = (0,external_react_.useState)({});
    const [loaded, setLoaded] = (0,external_react_.useState)(false);
    (0,external_react_.useEffect)(() => {
        function update() {
            setLoaded(nodelibrary/* NodeLibrary */.m.instance.isLoaded());
        }
        update();
        nodelibrary/* NodeLibrary */.m.instance.on('libraryUpdated', update, group);
        return function () {
            nodelibrary/* NodeLibrary */.m.instance.off(group);
        };
    }, []);
    return loaded;
}

// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/BasicNodeType.ts
var BasicNodeType = __webpack_require__(28593);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/common/EditorNode/index.ts + 2 modules
var EditorNode = __webpack_require__(51183);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/ListItem/ListItem.module.scss
var ListItem_module = __webpack_require__(37149);
;// ../noodl-core-ui/src/components/layout/ListItem/ListItem.module.scss

      
      
      
      
      
      
      
      
      

var ListItem_module_options = {};

ListItem_module_options.styleTagTransform = (styleTagTransform_default());
ListItem_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ListItem_module_options.insert = insertBySelector_default().bind(null, "head");
    
ListItem_module_options.domAPI = (styleDomAPI_default());
ListItem_module_options.insertStyleElement = (insertStyleElement_default());

var ListItem_module_update = injectStylesIntoStyleTag_default()(ListItem_module/* default */.A, ListItem_module_options);




       /* harmony default export */ const ListItem_ListItem_module = (ListItem_module/* default */.A && ListItem_module/* default */.A.locals ? ListItem_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/ListItem/ListItem.tsx





var ListItemVariant;
(function (ListItemVariant) {
    ListItemVariant["Default"] = "default";
    ListItemVariant["DefaultContrast"] = "default-contrast";
    ListItemVariant["Active"] = "active";
    ListItemVariant["Shy"] = "shy";
    ListItemVariant["Highlighted"] = "highlighted";
    ListItemVariant["HighlightedShy"] = "highlighted-shy";
})(ListItemVariant || (ListItemVariant = {}));
function ListItem({ icon, iconVariant, variant = ListItemVariant.Default, text, isDisabled, isHover, isActive, hasHiddenIconSlot, children, gutter = 0, prefix, affix, isShowingAffixOnHover, UNSAFE_className, UNSAFE_style, onClick }) {
    const textVariant = listItemVariantToTextVariant(variant);
    return (external_react_default().createElement("div", { className: external_classnames_default()([
            ListItem_ListItem_module['Root'],
            isDisabled && ListItem_ListItem_module['is-disabled'],
            isHover && ListItem_ListItem_module['is-hover'],
            ListItem_ListItem_module[`is-variant-${variant}`],
            isShowingAffixOnHover && ListItem_ListItem_module['is-showing-affix-on-hover'],
            isActive && ListItem_ListItem_module['is-active'],
            UNSAFE_className
        ]), style: {
            paddingLeft: 4 * gutter + 'px',
            paddingRight: 4 * gutter + 'px',
            ...(UNSAFE_style || {})
        }, onClick: onClick },
        !hasHiddenIconSlot && (external_react_default().createElement("div", { className: external_classnames_default()([ListItem_ListItem_module['Prefix']]) },
            Boolean(icon) && external_react_default().createElement(common_Icon/* Icon */.In, { icon: icon, size: common_Icon/* IconSize */.lK.Small, variant: iconVariant }),
            Boolean(prefix) && prefix)),
        external_react_default().createElement("div", { className: external_classnames_default()([ListItem_ListItem_module['Body']]) },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: textVariant }, text),
            children),
        Boolean(affix) && external_react_default().createElement("div", { className: external_classnames_default()([ListItem_ListItem_module['Affix']]) }, affix)));
}
function listItemVariantToTextVariant(variant) {
    switch (variant) {
        case ListItemVariant.Shy:
        case ListItemVariant.HighlightedShy:
            return typography_Text/* TextType */.M2.Shy;
        case ListItemVariant.DefaultContrast:
            return typography_Text/* TextType */.M2.DefaultContrast;
        default:
            return typography_Text/* TextType */.M2.Default;
    }
}

;// ../noodl-core-ui/src/components/layout/ListItem/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/ScrollArea/ScrollArea.module.scss
var ScrollArea_module = __webpack_require__(71307);
;// ../noodl-core-ui/src/components/layout/ScrollArea/ScrollArea.module.scss

      
      
      
      
      
      
      
      
      

var ScrollArea_module_options = {};

ScrollArea_module_options.styleTagTransform = (styleTagTransform_default());
ScrollArea_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ScrollArea_module_options.insert = insertBySelector_default().bind(null, "head");
    
ScrollArea_module_options.domAPI = (styleDomAPI_default());
ScrollArea_module_options.insertStyleElement = (insertStyleElement_default());

var ScrollArea_module_update = injectStylesIntoStyleTag_default()(ScrollArea_module/* default */.A, ScrollArea_module_options);




       /* harmony default export */ const ScrollArea_ScrollArea_module = (ScrollArea_module/* default */.A && ScrollArea_module/* default */.A.locals ? ScrollArea_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/ScrollArea/ScrollArea.tsx



function ScrollArea({ children, UNSAFE_className, UNSAFE_style }) {
    return (external_react_default().createElement("div", { className: external_classnames_default()(ScrollArea_ScrollArea_module['Root'], UNSAFE_className), style: UNSAFE_style },
        external_react_default().createElement("div", { className: ScrollArea_ScrollArea_module['Container'] }, children)));
}

;// ../noodl-core-ui/src/components/layout/ScrollArea/index.ts


;// ./src/editor/src/views/panels/NodeReferencesPanel/NodeReferencesPanel.tsx























function useNodeReferences() {
    const [group] = (0,external_react_.useState)({});
    const [result, setResult] = (0,external_react_.useState)([]);
    (0,external_react_.useEffect)(() => {
        function updateIndex() {
            const types = {};
            const references = new Map();
            function handleComponent(component) {
                component.forEachNode((node) => {
                    const name = node.type.name;
                    // Add the reference
                    references.set(name, [
                        ...(references.get(name) || []),
                        {
                            displayName: component.displayName || component.name,
                            node,
                            component
                        }
                    ]);
                    // Repeater
                    if (name === 'For Each' && node.parameters.template) {
                        const templateComponent = projectmodel.ProjectModel.instance.getComponentWithName(node.parameters.template);
                        if (templateComponent) {
                            references.set(templateComponent.fullName, [
                                ...(references.get(templateComponent.fullName) || []),
                                {
                                    displayName: component.displayName || component.name,
                                    node,
                                    component
                                }
                            ]);
                            handleComponent(templateComponent);
                        }
                    }
                    // Add some metadata for this node if we dont have it yet.
                    if (!types[name]) {
                        types[name] = node.type;
                    }
                });
            }
            // Loop all the nodes in the project
            projectmodel.ProjectModel.instance.forEachComponent(handleComponent);
            // Combine the result to look a little better.
            const results = Array.from(references.keys())
                .map((key) => {
                var _a;
                return ({
                    type: types[key],
                    displayName: ((_a = types[key]) === null || _a === void 0 ? void 0 : _a.displayName) || key,
                    referenaces: references.get(key)
                });
            })
                .sort((a, b) => b.referenaces.length - a.referenaces.length);
            setResult(results);
        }
        updateIndex();
        EventDispatcher.EventDispatcher.instance.on([
            'Model.nodeAdded',
            'Model.nodeRemoved',
            'Model.componentAdded',
            'Model.componentRemoved',
            'Model.componentRenamed'
        ], updateIndex, group);
        return function () {
            EventDispatcher.EventDispatcher.instance.off(group);
        };
    }, []);
    return [result];
}
function NodeReferencesPanel() {
    const [searchTerm, setSearchTerm] = (0,external_react_.useState)('');
    const [includeCoreNodes, setIncludeCoreNodes] = (0,external_react_.useState)(false);
    const inputRef = (0,external_react_.useRef)(null);
    const [result] = useNodeReferences();
    const nodeLibraryLoaded = useNodeLibraryLoaded();
    useFocusRefOnPanelActive(inputRef, NodeReferencesPanel_ID);
    function searchFilter(x) {
        if (x.displayName.toLowerCase().includes(searchTerm)) {
            return true;
        }
        if (x.type instanceof BasicNodeType/* BasicNodeType */.F) {
            if (x.type.displayName.toLowerCase().includes(searchTerm))
                return;
        }
        return false;
    }
    let filteredResult = result.filter(searchFilter);
    if (!includeCoreNodes) {
        filteredResult = filteredResult.filter((x) => x.displayName.startsWith('/'));
    }
    return (external_react_default().createElement(BasePanel, { title: "Node References", isFill: true },
        external_react_default().createElement(ExperimentalFlag, null),
        external_react_default().createElement(Section/* Section */.w, { variant: Section/* SectionVariant */.$.PanelShy, hasVisibleOverflow: true, hasGutter: true },
            external_react_default().createElement(SearchInput/* SearchInput */.D, { placeholder: "Search...", onChange: (text) => setSearchTerm(text.toLowerCase()), UNSAFE_style: { height: 34 }, value: searchTerm, inputRef: inputRef }),
            external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
                external_react_default().createElement(Checkbox, { isChecked: includeCoreNodes, label: "Include Core Nodes", variant: CheckboxVariant.Sidebar, onChange: (event) => {
                        setIncludeCoreNodes(!!event.target.checked);
                    } }))),
        nodeLibraryLoaded && (external_react_default().createElement(ScrollArea, null,
            external_react_default().createElement(Box/* Box */.a, { hasYSpacing: true, UNSAFE_style: { width: '100%' } }, filteredResult.map((entry) => (external_react_default().createElement(Item, { key: entry.displayName, entry: entry }))))))));
}
function Item({ entry }) {
    const [isOpen, setIsOpen] = (0,external_react_.useState)(false);
    const colors = (0,external_react_.useMemo)(() => entry.type
        ? nodelibrary/* NodeLibrary */.m.instance.colorSchemeForNodeType(entry.type)
        : {
            base: '#4C4F59',
            baseHighlighted: '#62656e',
            header: '#373B45',
            headerHighlighted: '#4c4f59',
            outline: '#373B45',
            outlineHighlighted: '#b58900',
            text: '#d3d4d6'
        }, [entry]);
    return (external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasBottomSpacing: 3, UNSAFE_style: { cursor: 'pointer' } },
        external_react_default().createElement("div", { onClick: () => {
                setIsOpen((prev) => !prev);
            } },
            external_react_default().createElement("div", { style: { height: 36 } }, entry.type ? (
            /* @ts-expect-error */
            external_react_default().createElement(EditorNode/* EditorNode */.c, { item: entry.type, colors: colors })) : (
            /* @ts-expect-error */
            external_react_default().createElement(EditorNode/* EditorNode */.c, { item: { name: entry.displayName }, colors: colors }))),
            external_react_default().createElement(Box/* Box */.a, { hasXSpacing: 2, UNSAFE_style: { backgroundColor: colors.header } },
                external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { justifyContent: 'space-between', alignItems: 'center' } },
                    external_react_default().createElement(Label/* Label */.JU, null,
                        entry.referenaces.length,
                        " references"),
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, icon: common_Icon/* IconName */.$M.CaretDown, size: common_Icon/* IconSize */.lK.Tiny, state: isOpen ? inputs_IconButton/* IconButtonState */.Df.Rotated : null })))),
        external_react_default().createElement(Collapsible/* Collapsible */.N, { isCollapsed: !isOpen }, entry.referenaces.map((referenace, index) => (external_react_default().createElement(ItemReference, { key: index, entry: entry, referenace: referenace, colors: colors }))))));
}
function ItemReference({ entry, referenace, colors }) {
    const [hover, setHover] = (0,external_react_.useState)(false);
    return (external_react_default().createElement("div", { onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false) },
        external_react_default().createElement(ListItem, { text: referenace.displayName, UNSAFE_style: { backgroundColor: hover ? colors.baseHighlighted : colors.base }, onClick: () => {
                if (!referenace.node)
                    return;
                NodeGraphContext.NodeGraphContextTmp.nodeGraph.switchToComponent(referenace.component, {
                    node: referenace.node,
                    pushHistory: true
                });
            } })));
}

// EXTERNAL MODULE: ./src/editor/src/models/CodeHistoryManager.ts
var CodeHistoryManager = __webpack_require__(37949);
// EXTERNAL MODULE: ../../node_modules/monaco-editor/esm/vs/language/css/monaco.contribution.js
var monaco_contribution = __webpack_require__(62877);
;// ../../node_modules/monaco-editor/esm/vs/language/json/monaco.contribution.js

/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));

// src/fillers/monaco-editor-core.ts
var monaco_editor_core_exports = {};
__reExport(monaco_editor_core_exports, editor_api);


// src/language/json/monaco.contribution.ts
var LanguageServiceDefaultsImpl = class {
  _onDidChange = new monaco_editor_core_exports.Emitter();
  _diagnosticsOptions;
  _modeConfiguration;
  _languageId;
  constructor(languageId, diagnosticsOptions, modeConfiguration) {
    this._languageId = languageId;
    this.setDiagnosticsOptions(diagnosticsOptions);
    this.setModeConfiguration(modeConfiguration);
  }
  get onDidChange() {
    return this._onDidChange.event;
  }
  get languageId() {
    return this._languageId;
  }
  get modeConfiguration() {
    return this._modeConfiguration;
  }
  get diagnosticsOptions() {
    return this._diagnosticsOptions;
  }
  setDiagnosticsOptions(options) {
    this._diagnosticsOptions = options || /* @__PURE__ */ Object.create(null);
    this._onDidChange.fire(this);
  }
  setModeConfiguration(modeConfiguration) {
    this._modeConfiguration = modeConfiguration || /* @__PURE__ */ Object.create(null);
    this._onDidChange.fire(this);
  }
};
var diagnosticDefault = {
  validate: true,
  allowComments: true,
  schemas: [],
  enableSchemaRequest: false,
  schemaRequest: "warning",
  schemaValidation: "warning",
  comments: "error",
  trailingCommas: "error"
};
var modeConfigurationDefault = {
  documentFormattingEdits: true,
  documentRangeFormattingEdits: true,
  completionItems: true,
  hovers: true,
  documentSymbols: true,
  tokens: true,
  colors: true,
  foldingRanges: true,
  diagnostics: true,
  selectionRanges: true
};
var jsonDefaults = new LanguageServiceDefaultsImpl("json", diagnosticDefault, modeConfigurationDefault);
monaco_editor_core_exports.languages.json = { jsonDefaults };
function getMode() {
  if (false) // removed by dead control flow
{} else {
    return __webpack_require__.e(/* import() */ 898).then(__webpack_require__.bind(__webpack_require__, 21898));
  }
}
monaco_editor_core_exports.languages.register({
  id: "json",
  extensions: [".json", ".bowerrc", ".jshintrc", ".jscsrc", ".eslintrc", ".babelrc", ".har"],
  aliases: ["JSON", "json"],
  mimetypes: ["application/json"]
});
monaco_editor_core_exports.languages.onLanguage("json", () => {
  getMode().then((mode) => mode.setupMode(jsonDefaults));
});


// EXTERNAL MODULE: ../../node_modules/monaco-editor/esm/vs/language/typescript/monaco.contribution.js
var typescript_monaco_contribution = __webpack_require__(32263);
// EXTERNAL MODULE: ../../node_modules/monaco-editor/esm/vs/basic-languages/_.contribution.js
var _contribution = __webpack_require__(86919);
;// ../../node_modules/monaco-editor/esm/vs/basic-languages/html/html.contribution.js
/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/

// src/basic-languages/html/html.contribution.ts

(0,_contribution/* registerLanguage */.K)({
  id: "html",
  extensions: [".html", ".htm", ".shtml", ".xhtml", ".mdoc", ".jsp", ".asp", ".aspx", ".jshtm"],
  aliases: ["HTML", "htm", "html", "xhtml"],
  mimetypes: ["text/html", "text/x-jshtm", "text/template", "text/ng-template"],
  loader: () => {
    if (false) // removed by dead control flow
{} else {
      return __webpack_require__.e(/* import() */ 581).then(__webpack_require__.bind(__webpack_require__, 68581));
    }
  }
});

;// ../../node_modules/monaco-editor/esm/vs/basic-languages/graphql/graphql.contribution.js
/*!-----------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Version: 0.34.1(547870b6881302c5b4ff32173c16d06009e3588f)
 * Released under the MIT license
 * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt
 *-----------------------------------------------------------------------------*/

// src/basic-languages/graphql/graphql.contribution.ts

(0,_contribution/* registerLanguage */.K)({
  id: "graphql",
  extensions: [".graphql", ".gql"],
  aliases: ["GraphQL", "graphql", "gql"],
  mimetypes: ["application/graphql"],
  loader: () => {
    if (false) // removed by dead control flow
{} else {
      return __webpack_require__.e(/* import() */ 13).then(__webpack_require__.bind(__webpack_require__, 99013));
    }
  }
});

// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/NodeLibraryData.ts
var NodeLibraryData = __webpack_require__(68228);
;// ./src/editor/src/utils/CodeEditor/mappings.ts
// NOTE: I can't find a built in function for this, but maybe it exists!
const prettyLanguageId = {
    javascript: 'JavaScript',
    // We currently dont have TypeScript,
    // it does provide more annotations though!
    typescript: 'JavaScript',
    html: 'HTML',
    css: 'CSS',
    json: 'JSON',
    plaintext: 'Plain Text'
};
const languageIdMapping = {
    // Disable this for now, we have to come up with some nice TS config for this
    // javascript: 'typescript',
    text: 'plaintext'
};
function prettyLanguage(languageId) {
    var _a;
    return (_a = prettyLanguageId[languageId]) !== null && _a !== void 0 ? _a : languageId;
}
function codeEditorTypeToLanguageId(type) {
    var _a, _b;
    return (_b = (_a = languageIdMapping[type]) !== null && _a !== void 0 ? _a : type) !== null && _b !== void 0 ? _b : 'plaintext';
}

;// ./src/editor/src/utils/CodeEditor/model/editorModel.ts

class EditorModel {
    //private _prefixSuffixExtension: PrefixSuffixExtension;
    constructor(model, modules = []) {
        this.model = model;
        this.modules = modules;
    }
    attachEditor(editor) {
        if (this._editor)
            throw new Error('Editor is already attached to editor model.');
        this._editor = editor;
        //    this._prefixSuffixExtension = new PrefixSuffixExtension(
        //      editor,
        //      this.model,
        //      `/** The CSS in here is directly applied to this Node. */
        ///** It's is not possible to use classes in here. */
        //[self] {
        //`,
        //      `
        //}
        //`
        //    );
    }
    getValue() {
        //    if (this._prefixSuffixExtension) {
        //      return this._prefixSuffixExtension.getValue();
        //    }
        return this.model.getValue();
    }
    getPrettyLanguageName() {
        return prettyLanguage(this.model.getLanguageId());
    }
    dispose() {
        var _a;
        (_a = this.model) === null || _a === void 0 ? void 0 : _a.dispose();
        this.modules.forEach((model) => {
            model.dispose();
        });
    }
}

;// ./src/editor/src/utils/CodeEditor/typescript/helper.ts
/**
 * Convert a Noodl plug type to Typescript Type.
 */
function plugTypeToTSDef(type, isInput) {
    switch (type) {
        case 'string':
            return 'string';
        case 'number':
            return 'number';
        case 'boolean':
            return 'boolean';
        case 'date':
            return 'Date';
        case 'object':
            return isInput ? 'any' : 'unknown';
        case 'array':
            return isInput ? 'any[]' : 'unknown[]';
        case 'signal':
            return '() => void';
        default:
            return isInput ? 'any' : 'unknown';
    }
}
class TypescriptModule {
    constructor() {
        this._libs = [];
    }
    /**
     * https://github.com/microsoft/monaco-editor/blob/main/src/language/typescript/lib/lib.index.ts
     * https://github.com/microsoft/monaco-editor/blob/main/src/language/typescript/lib/lib.ts
     * https://www.typescriptlang.org/tsconfig#lib
     */
    get libs() {
        return this._libs;
    }
    setLib(libs) {
        this._libs = libs || [];
    }
    setModel(model) {
        var _a;
        (_a = this._model) === null || _a === void 0 ? void 0 : _a.dispose();
        this._model = model;
    }
    setSource(value) {
        var _a;
        (_a = this._model) === null || _a === void 0 ? void 0 : _a.setValue(value);
    }
    setExtraLib(model) {
        var _a;
        (_a = this._extraLib) === null || _a === void 0 ? void 0 : _a.dispose();
        this._extraLib = model;
    }
    dispose() {
        var _a;
        this._model.dispose();
        (_a = this._extraLib) === null || _a === void 0 ? void 0 : _a.dispose();
    }
}

;// ./src/editor/src/utils/CodeEditor/typescript/nodes/DbCollection2/index.ts


const STATIC = `
declare const Inputs: any;

interface DbKlass {
  createdAt?: DateFilter,
  updatedAt?: DateFilter,
  Name?: StringFilter,
  value?: NumberFilter;
}

interface DateFilter {
  exist?: boolean;
  equalTo?: Date;
}

interface StringFilter {
  exist?: boolean;
  equalTo?: string;
  containedIn?: string[];
  text?: {
    search: string | {
      term: string;
      caseSensitive?: boolean;
    };
  }
  matchesRegex?: any;
}

interface NumberFilter {
  exist?: boolean;
  lessThan?: number;
  lessThanOrEqualTo: number;
  greaterThan?: number;
  greaterThanOrEqualTo?: number;
  equalTo?: number;
  notEqualTo: number;
  containedIn?: number[];
  notContainedIn?: number[];
}

interface GeoPointNearSphere {
  exist?: boolean;
  nearSphere: {
    latitude: number;
    longitude: number;
    maxDistanceInKilometers: number;
  }
}

interface GeoPointWithinBox {
  exist?: boolean;
  withinBox: [
    {
      latitude: number;
      longitude: number;
    },
    {
      latitude: number;
      longitude: number;
    }
  ];
}

interface GeoPointWithinPolygon {
  exist?: boolean;
  withinPolygon: {
    latitude: number;
    longitude: number;
  }[];
}

type GeoPointFilter =
  | GeoPointNearSphere
  | GeoPointWithinBox
  | GeoPointWithinPolygon;

interface Klass extends DbKlass {
  idEqualTo?: string;
  idContainedIn?: string[];
}

type WhereFilter = 
  | Klass
  | {
      and: Klass[];
    }
  | {
      or: Klass[];
    };

type SortKey = \`\${('' | '-')}\${keyof DbKlass}\`;

/**
 * Define the Filter.
 */
declare function where(filter: WhereFilter): void;

/**
 * Takes an array with strings specifying the names of the properties you want
 * to sort by. You can prefix the property name with "-" to specify that you
 * want to sort in descending order instead of the default ascending order.
 */
declare function sort(pattern: SortKey[]): void;
`;
function functionLib(node) {
    var _a;
    const ports = ((_a = node === null || node === void 0 ? void 0 : node.getPorts()) !== null && _a !== void 0 ? _a : [])
        .filter((x) => ['Inputs', 'Outputs'].includes(x.group))
        .map((x) => ({
        name: x.displayName || x.name,
        type: plugTypeToTSDef(x.type, x.group === 'Inputs'),
        group: x.group
    }));
    const inputs = [];
    const outputs = [];
    ports.forEach((p) => {
        if (p.group === 'Inputs') {
            inputs.push(`    readonly ['${p.name}']: ${p.type};`);
        }
        if (p.group === 'Outputs') {
            outputs.push(`    ['${p.name}']: ${p.type};`);
        }
    });
    return STATIC;
}
function buildNodeLib(node) {
    const libPathName = 'inmemory://@noodl/nodes/DbCollection2/DbCollection2.d.ts';
    const libUri = editor_api.Uri.parse(libPathName);
    const source = functionLib(node);
    return {
        source,
        libPathName,
        libUri
    };
}
function registerOrUpdate_DbCollection2(node) {
    const { source, libPathName, libUri } = buildNodeLib(node);
    const pkg = new TypescriptModule();
    pkg.setLib(['es2020']);
    // Try get the model
    const model = editor_api.editor.getModel(libUri);
    if (model) {
        pkg.setModel(model);
        pkg.setSource(source);
    }
    else {
        const model = editor_api.editor.createModel(source, 'typescript', libUri);
        pkg.setModel(model);
        pkg.setExtraLib(editor_api.languages.typescript.javascriptDefaults.addExtraLib(source, libPathName));
        pkg.setSource(source);
    }
    return pkg;
}

;// ./src/editor/src/utils/CodeEditor/typescript/nodes/Expression/index.ts


function expressionLib() {
    return `
/** Pi. This is the ratio of the circumference of a circle to its diameter. */
declare const pi: number;

/**
 * Returns the smaller of a set of supplied numeric expressions.
 * @param values Numeric expressions to be evaluated.
 */
declare function min(...values: number[]): number;

/**
 * Returns the larger of a set of supplied numeric expressions.
 * @param values Numeric expressions to be evaluated.
 */
declare function max(...values: number[]): number;

/**
 * Returns the cosine of a number.
 * @param x A numeric expression that contains an angle measured in radians.
 */
declare function cos(x: number): number;

/**
 * Returns the sine of a number.
 * @param x A numeric expression that contains an angle measured in radians.
 */
declare function sin(x: number): number;

/**
 * Returns the tangent of a number.
 * @param x A numeric expression that contains an angle measured in radians.
 */
declare function tan(x: number): number;

/**
 * Returns the square root of a number.
 * @param x A numeric expression.
 */
declare function sqrt(x: number): number;

/**
 * Returns a supplied numeric expression rounded to the nearest integer.
 * @param x The value to be rounded to the nearest integer.
 */
declare function round(x: number): number;

/**
 * Returns the greatest integer less than or equal to its numeric argument.
 * @param x A numeric expression.
 */
declare function floor(x: number): number;

/**
 * Returns the smallest integer greater than or equal to its numeric argument.
 * @param x A numeric expression.
 */
declare function ceil(x: number): number;

/**
 * Returns the absolute value of a number (the value without regard to whether it is positive or negative).
 * For example, the absolute value of -5 is the same as the absolute value of 5.
 * @param x A numeric expression for which the absolute value is needed.
 */
declare function abs(x: number): number;

/** Returns a pseudorandom number between 0 and 1. */
declare function random(): number;
`;
}
function Expression_buildNodeLib() {
    const libPathName = 'inmemory://@noodl/nodes/Expression/Expression.d.ts';
    const libUri = editor_api.Uri.parse(libPathName);
    const source = expressionLib();
    return {
        source,
        libPathName,
        libUri
    };
}
function registerOrUpdate_Expression() {
    const { source, libPathName, libUri } = Expression_buildNodeLib();
    const pkg = new TypescriptModule();
    pkg.setLib([]);
    // Try get the model
    const model = editor_api.editor.getModel(libUri);
    if (model) {
        pkg.setModel(model);
        pkg.setSource(source);
    }
    else {
        const model = editor_api.editor.createModel(source, 'typescript', libUri);
        pkg.setModel(model);
        pkg.setExtraLib(editor_api.languages.typescript.javascriptDefaults.addExtraLib(source, libPathName));
        pkg.setSource(source);
    }
    return pkg;
}

;// ./src/editor/src/utils/CodeEditor/typescript/nodes/Javascript2/index.ts



function Javascript2_functionLib(node) {
    var _a;
    const ports = ((_a = node === null || node === void 0 ? void 0 : node.getPorts()) !== null && _a !== void 0 ? _a : [])
        .filter((x) => ['Inputs', 'Outputs'].includes(x.group))
        .map((x) => ({
        name: x.displayName || x.name,
        type: plugTypeToTSDef(x.type, x.group === 'Inputs'),
        group: x.group
    }));
    const inputs = [];
    const outputs = [];
    ports.forEach((p) => {
        if (p.group === 'Inputs') {
            inputs.push(`  readonly ['${p.name}']: ${p.type};`);
        }
        if (p.group === 'Outputs') {
            outputs.push(`  ['${p.name}']: ${p.type};`);
        }
    });
    return [
        'type Prettify<T> = {',
        '  [K in keyof T]: T[K];',
        '} & {};',
        '',
        'type InputTypes = {',
        ...inputs,
        '',
        '  readonly [key: string]: any;',
        '}',
        '',
        'type OutputTypes = {',
        ...outputs,
        '',
        '  [key: string]: unknown;',
        '}',
        '',
        '/** @deprecated Did you mean Script.Inputs? */',
        'declare const Inputs: never;',
        '',
        '/** @deprecated Did you mean Script.Outputs? */',
        'declare const Outputs: never;',
        '',
        'declare const Script: {',
        '  Inputs: Prettify<InputTypes>;',
        '  Outputs: Prettify<OutputTypes>;',
        '',
        '  // Called when the node is unmounted',
        '  OnDestroy: () => void;',
        '',
        '  Signals: Record<string, () => void>;',
        '  Setters: Record<string, () => void>;',
        '};'
    ].join('\n');
}
function Javascript2_buildNodeLib(node) {
    const libPathName = 'inmemory://@noodl/nodes/Javascript2/Javascript2.d.ts';
    const libUri = editor_api.Uri.parse(libPathName);
    const source = Javascript2_functionLib(node);
    return {
        source,
        libPathName,
        libUri
    };
}
function registerOrUpdate_Javascript2(node, runtimeType) {
    const { source, libPathName, libUri } = Javascript2_buildNodeLib(node);
    const pkg = new TypescriptModule();
    switch (runtimeType) {
        case NodeLibraryData/* RuntimeType */.r.Browser:
            pkg.setLib(['dom', 'es2020']);
            break;
        case NodeLibraryData/* RuntimeType */.r.Cloud:
            pkg.setLib(['es2020']);
            break;
    }
    // Try get the model
    const model = editor_api.editor.getModel(libUri);
    if (model) {
        pkg.setModel(model);
        pkg.setSource(source);
    }
    else {
        const model = editor_api.editor.createModel(source, 'typescript', libUri);
        pkg.setModel(model);
        pkg.setExtraLib(editor_api.languages.typescript.javascriptDefaults.addExtraLib(source, libPathName));
        pkg.setSource(source);
    }
    return pkg;
}

;// ./src/editor/src/utils/CodeEditor/typescript/nodes/JavaScriptFunction/index.ts



function JavaScriptFunction_functionLib(node) {
    var _a;
    const ports = ((_a = node === null || node === void 0 ? void 0 : node.getPorts()) !== null && _a !== void 0 ? _a : [])
        .filter((x) => ['Inputs', 'Outputs'].includes(x.group))
        .map((x) => ({
        name: x.displayName || x.name,
        type: plugTypeToTSDef(x.type, x.group === 'Inputs'),
        group: x.group
    }));
    const inputs = [];
    const outputs = [];
    ports.forEach((p) => {
        if (p.group === 'Inputs') {
            inputs.push(`    readonly ['${p.name}']: ${p.type};`);
        }
        if (p.group === 'Outputs') {
            outputs.push(`    ['${p.name}']: ${p.type};`);
        }
    });
    return [
        'type Prettify<T> = {',
        '  [K in keyof T]: T[K];',
        '} & {};',
        '',
        'type InputTypes = {',
        ...inputs,
        '',
        '    readonly [key: string]: any;',
        '}',
        '',
        'type OutputTypes = {',
        ...outputs,
        '',
        '    [key: string]: unknown;',
        '}',
        '',
        'declare const Inputs: Prettify<InputTypes>;',
        'declare const Outputs: Prettify<OutputTypes>;'
    ].join('\n');
}
function JavaScriptFunction_buildNodeLib(node) {
    const libPathName = 'inmemory://@noodl/nodes/JavaScriptFunction/JavaScriptFunction.d.ts';
    const libUri = editor_api.Uri.parse(libPathName);
    const source = JavaScriptFunction_functionLib(node);
    return {
        source,
        libPathName,
        libUri
    };
}
function registerOrUpdate_JavaScriptFunction(node, runtimeType) {
    const { source, libPathName, libUri } = JavaScriptFunction_buildNodeLib(node);
    const pkg = new TypescriptModule();
    switch (runtimeType) {
        case NodeLibraryData/* RuntimeType */.r.Browser:
            pkg.setLib(['dom', 'es2020']);
            break;
        case NodeLibraryData/* RuntimeType */.r.Cloud:
            pkg.setLib(['es2020']);
            break;
    }
    // Try get the model
    const model = editor_api.editor.getModel(libUri);
    if (model) {
        pkg.setModel(model);
        pkg.setSource(source);
    }
    else {
        const model = editor_api.editor.createModel(source, 'typescript', libUri);
        pkg.setModel(model);
        pkg.setExtraLib(editor_api.languages.typescript.javascriptDefaults.addExtraLib(source, libPathName));
        pkg.setSource(source);
    }
    return pkg;
}

;// ./src/editor/src/utils/CodeEditor/context.ts


function getIdentifiers(project) {
    const identifiers = {};
    project.forEachComponent((component) => {
        component.forEachNode((node) => {
            (0,external_underscore_.each)(node.getPorts(), (port) => {
                const identifierOf = port.type.identifierOf;
                if (!identifierOf)
                    return;
                if (!identifiers[identifierOf]) {
                    identifiers[identifierOf] = new Set();
                }
                const name = node.parameters[port.name];
                if (name) {
                    identifiers[identifierOf].add(name);
                }
            });
        });
    });
    return identifiers;
}
function getCloudFunctions(project) {
    const functions = [];
    const components = project.getComponents().filter(NodeGraph/* isComponentModel_CloudRuntime */.dk);
    components.forEach((component) => {
        const nodes = component.getNodes();
        const requestNode = nodes.find((x) => x.typename === 'noodl.cloud.request');
        if (!requestNode)
            return;
        // ---
        // Find all the outputs and types from connections
        const outputs = {};
        const responseNodes = nodes.filter((x) => x.typename === 'noodl.cloud.response');
        responseNodes.forEach((responseNode) => {
            const ports = responseNode.getPorts('input');
            ports.forEach((port) => {
                if (!port.name.startsWith('pm-'))
                    return;
                if (!outputs[port.name]) {
                    outputs[port.name] = {
                        name: port.name,
                        types: []
                    };
                }
                if (!outputs[port.name].types.includes(port.type)) {
                    outputs[port.name].types.push(port.type);
                }
            });
        });
        // ---
        // Find all the inputs and types from connections
        const inputs = [];
        const requestNodeConnections = requestNode.getConnectionsOnThisNode();
        requestNodeConnections.forEach((connection) => {
            if (!connection.fromProperty.startsWith('pm-'))
                return;
            const connectedNode = nodes.find((x) => x.id === connection.toId);
            if (!connectedNode)
                return;
            const connectedPort = connectedNode.getPort(connection.toProperty, 'input');
            if (!connectedPort)
                return;
            // TODO: Maybe it should take all the outputs instead of the connections?
            inputs.push({
                name: connection.fromProperty,
                type: connectedPort.type
            });
        });
        // ---
        // Add the function
        functions.push({
            name: component.name,
            displayName: component.displayName,
            fullName: component.fullName,
            inputs,
            outputs: Object.values(outputs)
        });
    });
    return functions;
}

;// ./src/editor/src/utils/CodeEditor/typescript/viewer/index.ts






function typeToTypescript(type) {
    function convert(type) {
        switch (type) {
            case 'string':
                return 'string';
            case 'number':
                return 'number';
            case 'array':
                return 'any[]';
            default:
                return 'any';
        }
    }
    return typeof type === 'string' ? convert(type) : convert(type.name);
}
async function GetSource() {
    const project = projectmodel.ProjectModel.instance;
    // ---
    // Identifiers
    const identifiers = getIdentifiers(project);
    // ---
    // Database
    const schema = schemahandler/* default */.A.instance;
    if (typeof schema.haveCloudServices === 'undefined') {
        try {
            await schema._fetch();
        }
        catch (error) {
            // lets ignore it then...
            console.error(error);
        }
    }
    // ---
    // Cloud Functions
    const cloudFunctions = getCloudFunctions(project);
    const tsCloudFunctions = cloudFunctions.map((x) => {
        return {
            name: x.name,
            displayName: x.displayName,
            fullName: x.fullName,
            inputs: x.inputs.reduce((result, item) => {
                result[item.name] = typeToTypescript(item.type);
                return result;
            }, {}),
            outputs: x.outputs.reduce((result, item) => {
                result[item.name] = item.types.map((x) => typeToTypescript(x)).join(' | ');
                return result;
            }, {})
        };
    });
    // ---
    // Page Routes & page routers
    const pageRoutes = await (0,context_pages/* getPageRoutes */.w)(project, {});
    const pageRouters = pageRoutes.routes.reduce((result, item) => {
        result[item.componentName] = { routerName: item.routerName };
        return result;
    }, {});
    return CreateSource({
        isLoading: false,
        identifiers,
        dbCollections: schema.dbCollections || [],
        cloudFunctions: tsCloudFunctions,
        pages: pageRoutes.pages,
        pageRouters: pageRouters
    });
}
function CreateSource({ isLoading = true, identifiers = {}, dbCollections = [], cloudFunctions = [], pages = [], pageRouters = {} }) {
    // ---
    // Identifiers
    const identifierKeys = Object.keys(identifiers);
    // NOTE: Always make sure we have this property in there.
    //       Come up with a better solution for this
    if (!identifierKeys.includes('VariableName')) {
        identifierKeys.push('VariableName');
    }
    const identifierSource = identifierKeys.map((key) => {
        let str = `    ['${key}']: {\n`;
        if (identifiers[key]) {
            identifiers[key].forEach((name) => {
                str += `      ['${name}']: {},\n`;
            });
        }
        return str + `    }`;
    });
    // ---
    // Database
    const dbCollectionsSource = dbCollections.map((collection) => {
        let str = `    ['${collection.name}']: {\n`;
        Object.keys(collection.schema.properties).forEach((name) => {
            const property = collection.schema.properties[name];
            const source = JSON.stringify(property, null, 2).replace(/\n/g, '\n      ');
            str += `      ['${name}']: ${source},\n`;
        });
        return str + `    }`;
    });
    // ---
    // Cloud Functions
    const cloudFunctionsSource = cloudFunctions.map((cf) => {
        let str = `    ['${cf.displayName}']: {\n`;
        str += `      fullName: '${cf.fullName}',\n`;
        str += `      inputs: {\n`;
        Object.entries(cf.inputs).forEach(([name, type]) => {
            str += `        ['${name.substring(3)}']: ${type},\n`;
        });
        str += `      },\n`;
        str += `      outputs: {\n`;
        Object.entries(cf.outputs).forEach(([name, type]) => {
            str += `        ['${name.substring(3)}']: ${type},\n`;
        });
        str += `      },\n`;
        return str + `    }`;
    });
    // ---
    // Pages
    const pagesSource = pages.map((page) => {
        const source = JSON.stringify(page, null, 2).replace(/\n/g, '\n    ');
        const str = `    ['${page.componentName}']: ${source}`;
        return str;
    });
    const routerNames = Object.keys(Object.values(pageRouters).reduce((result, item) => {
        result[item.routerName] = true;
        return result;
    }, {}));
    // In case there are none, or loading state. Add 'Main' by default.
    if (routerNames.length === 0) {
        routerNames.push('Main');
    }
    const routerNamesSource = routerNames.map((routerName) => {
        return `'${routerName}'`;
    });
    // ---
    // Final
    const createComment = (text, tabs = 2) => {
        const tabsText = new Array(tabs + 1).join(' ');
        if (isLoading) {
            return tabsText + '/* Loading... */';
        }
        // A little ugly code, but it's all to make the comments look nice.
        let result = `/**\n ${text}\n*/`;
        result = result
            .split('\n')
            .map((line) => {
            if (line.startsWith('/')) {
                return tabsText + line + '\n';
            }
            if (line.startsWith('*')) {
                return tabsText + ' ' + line + '\n';
            }
            return tabsText + ' *' + line + '\n';
        })
            .join('')
            .slice(0, -1);
        return result;
    };
    return `//
// Auto generated typings based on the App.
//

declare namespace Noodl {
  type Identifiers = {
${identifierSource.join(',\n')}
  }

${createComment('The variables names from the Variable nodes.')}
  type VariableNames = keyof Identifiers["VariableName"] & string;

  type DatabaseSchema = {
${dbCollectionsSource.join(',\n')}
  }

${createComment('The Database Record ClassNames')}
  type RecordClassName = keyof DatabaseSchema & string;

  type CloudFunctionSchema = {
${cloudFunctionsSource.join(',\n')}
  }

${createComment('All the pages.')}
  type PagesSchema = {
${pagesSource.join(',\n')}
  }

${createComment('All the page routers.')}
  type PageRouterNames = ${routerNamesSource.join(' | ')};
}
`;
}
function GetOrCreateViewerModel() {
    const libPathName = 'inmemory://@noodl/viewer/global.d.ts';
    const libUri = editor_api.Uri.parse(libPathName);
    const pkg = new TypescriptModule();
    // Create model
    const model = editor_api.editor.getModel(libUri);
    if (model) {
        pkg.setModel(model);
    }
    else {
        const loadingSource = CreateSource({});
        pkg.setExtraLib(editor_api.languages.typescript.javascriptDefaults.addExtraLib(loadingSource, libPathName));
        pkg.setModel(editor_api.editor.createModel(loadingSource, 'typescript', libUri));
    }
    (async () => {
        const source = await GetSource();
        pkg.setExtraLib(editor_api.languages.typescript.javascriptDefaults.addExtraLib(source, libPathName));
        pkg.setSource(source);
    })();
    return pkg;
}

// EXTERNAL MODULE: ./src/editor/src/utils/compilation/build/deploy-index.ts
var deploy_index = __webpack_require__(71287);
;// ./src/editor/src/utils/CodeEditor/typescript/viewer-cloud/index.ts




function GetOrCreateViewerCloudModel() {
    const libPathName = 'inmemory://@noodl/viewer/cloud/global.d.ts';
    const libUri = editor_api.Uri.parse(libPathName);
    const pkg = new TypescriptModule();
    // Create model
    const model = editor_api.editor.getModel(libUri);
    if (model) {
        pkg.setModel(model);
    }
    else {
        const loadingSource = '/* loading... */';
        pkg.setExtraLib(editor_api.languages.typescript.javascriptDefaults.addExtraLib(loadingSource, libPathName));
        pkg.setModel(editor_api.editor.createModel(loadingSource, 'typescript', libUri));
    }
    (async () => {
        const filePath = src.filesystem.join((0,deploy_index/* getExternalFolderPath */.Pw)(), 'cloudruntime', 'global.d.ts.keep');
        const source = await src.filesystem.readFile(filePath);
        pkg.setExtraLib(editor_api.languages.typescript.javascriptDefaults.addExtraLib(source, libPathName));
        pkg.setSource(source);
    })();
    return pkg;
}

;// ./src/editor/src/utils/CodeEditor/typescript/viewer-react/index.ts




function GetOrCreateViewerReactModel() {
    const libPathName = 'inmemory://@noodl/viewer/react/global.d.ts';
    const libUri = editor_api.Uri.parse(libPathName);
    const pkg = new TypescriptModule();
    // Create model
    const model = editor_api.editor.getModel(libUri);
    if (model) {
        pkg.setModel(model);
    }
    else {
        const loadingSource = '/* loading... */';
        pkg.setExtraLib(editor_api.languages.typescript.javascriptDefaults.addExtraLib(loadingSource, libPathName));
        pkg.setModel(editor_api.editor.createModel(loadingSource, 'typescript', libUri));
    }
    (async () => {
        const filePath = src.filesystem.join((0,deploy_index/* getExternalFolderPath */.Pw)(), 'viewer', 'global.d.ts.keep');
        const source = await src.filesystem.readFile(filePath);
        pkg.setExtraLib(editor_api.languages.typescript.javascriptDefaults.addExtraLib(source, libPathName));
        pkg.setSource(source);
    })();
    return pkg;
}

;// ./src/editor/src/utils/CodeEditor/model.ts













/**
 * Create the Monaco Model, with better typings etc
 */
function createModel(options, node) {
    // Simple JSON editing - use plaintext (no workers needed)
    // Monaco workers require initialization from node context; plaintext avoids this.
    // JSON validation happens on save via JSON.parse()
    if (options.codeeditor === 'json') {
        return new EditorModel(editor_api.editor.createModel(options.value, 'plaintext'));
    }
    // arrays are edited as javascript (and eval:ed during runtime)
    // we are not going to add any extra typings here.
    if (options.type === 'array') {
        return new EditorModel(editor_api.editor.createModel(options.value, 'typescript'));
    }
    const modules = [];
    if (['javascript', 'typescript'].includes(options.codeeditor)) {
        const runtimeType = (0,NodeGraph/* getNodeGraphNodeRuntimeType */.lb)(node);
        if (node.typename !== 'Expression') {
            modules.push(GetOrCreateViewerModel());
        }
        const defaultLibs = [];
        switch (runtimeType) {
            case NodeLibraryData/* RuntimeType */.r.Browser:
                modules.push(GetOrCreateViewerReactModel());
                break;
            case NodeLibraryData/* RuntimeType */.r.Cloud:
                modules.push(GetOrCreateViewerCloudModel());
                break;
        }
        switch (node.typename) {
            case 'DbCollection2':
                modules.push(registerOrUpdate_DbCollection2(node));
                break;
            case 'Expression':
                modules.push(registerOrUpdate_Expression());
                break;
            case 'JavaScriptFunction':
                modules.push(registerOrUpdate_JavaScriptFunction(node, runtimeType));
                break;
            case 'Javascript2':
                modules.push(registerOrUpdate_Javascript2(node, runtimeType));
                break;
            default:
                switch (runtimeType) {
                    case NodeLibraryData/* RuntimeType */.r.Browser:
                        defaultLibs.push('dom', 'es2020');
                        break;
                    case NodeLibraryData/* RuntimeType */.r.Cloud:
                        defaultLibs.push('es2020');
                        break;
                }
                break;
        }
        // Get a list of all the available libs
        // this is removing all the DOM typings
        const lib = (0,external_underscore_.uniq)([...defaultLibs, ...modules.flatMap((x) => x.libs)]);
        const compilerOptions = {
            target: editor_api.languages.typescript.ScriptTarget.ES5,
            lib,
            allowNonTsExtensions: true,
            allowJs: true,
            noImplicitAny: false
        };
        editor_api.languages.typescript.javascriptDefaults.setCompilerOptions(compilerOptions);
        editor_api.languages.typescript.typescriptDefaults.setCompilerOptions(compilerOptions);
        editor_api.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
            noSemanticValidation: false,
            noSyntaxValidation: false
        });
    }
    const languageId = codeEditorTypeToLanguageId(options.codeeditor);
    const model = editor_api.editor.createModel(options.value, languageId);
    return new EditorModel(model, modules);
}

;// ./src/editor/src/utils/CodeEditor/index.ts







;// ../../node_modules/@marijn/find-cluster-break/src/index.js
// These are filled with ranges (rangeFrom[i] up to but not including
// rangeTo[i]) of code points that count as extending characters.
let rangeFrom = [], rangeTo = []

;(() => {
  // Compressed representation of the Grapheme_Cluster_Break=Extend
  // information from
  // http://www.unicode.org/Public/16.0.0/ucd/auxiliary/GraphemeBreakProperty.txt.
  // Each pair of elements represents a range, as an offet from the
  // previous range and a length. Numbers are in base-36, with the empty
  // string being a shorthand for 1.
  let numbers = "lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s => s ? parseInt(s, 36) : 1)
  for (let i = 0, n = 0; i < numbers.length; i++)
    (i % 2 ? rangeTo : rangeFrom).push(n = n + numbers[i])
})()

function isExtendingChar(code) {
  if (code < 768) return false
  for (let from = 0, to = rangeFrom.length;;) {
    let mid = (from + to) >> 1
    if (code < rangeFrom[mid]) to = mid
    else if (code >= rangeTo[mid]) from = mid + 1
    else return true
    if (from == to) return false
  }
}

function isRegionalIndicator(code) {
  return code >= 0x1F1E6 && code <= 0x1F1FF
}

function check(code) {
  for (let i = 0; i < rangeFrom.length; i++) {
    if (rangeTo[i] > code) return rangeFrom[i] <= code
  }
  return false
}

const ZWJ = 0x200d

function src_findClusterBreak(str, pos, forward = true, includeExtending = true) {
  return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending)
}

function nextClusterBreak(str, pos, includeExtending) {
  if (pos == str.length) return pos
  // If pos is in the middle of a surrogate pair, move to its start
  if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) pos--
  let prev = src_codePointAt(str, pos)
  pos += src_codePointSize(prev)
  while (pos < str.length) {
    let next = src_codePointAt(str, pos)
    if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {
      pos += src_codePointSize(next)
      prev = next
    } else if (isRegionalIndicator(next)) {
      let countBefore = 0, i = pos - 2
      while (i >= 0 && isRegionalIndicator(src_codePointAt(str, i))) { countBefore++; i -= 2 }
      if (countBefore % 2 == 0) break
      else pos += 2
    } else {
      break
    }
  }
  return pos
}

function prevClusterBreak(str, pos, includeExtending) {
  while (pos > 0) {
    let found = nextClusterBreak(str, pos - 2, includeExtending)
    if (found < pos) return found
    pos--
  }
  return 0
}

function src_codePointAt(str, pos) {
  let code0 = str.charCodeAt(pos)
  if (!surrogateHigh(code0) || pos + 1 == str.length) return code0
  let code1 = str.charCodeAt(pos + 1)
  if (!surrogateLow(code1)) return code0
  return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000
}

function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000 }
function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00 }
function src_codePointSize(code) { return code < 0x10000 ? 1 : 2 }

;// ../../node_modules/@codemirror/state/dist/index.js


/**
The data structure for documents. @nonabstract
*/
class dist_Text {
    /**
    Get the line description around the given position.
    */
    lineAt(pos) {
        if (pos < 0 || pos > this.length)
            throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
        return this.lineInner(pos, false, 1, 0);
    }
    /**
    Get the description for the given (1-based) line number.
    */
    line(n) {
        if (n < 1 || n > this.lines)
            throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
        return this.lineInner(n, true, 1, 0);
    }
    /**
    Replace a range of the text with the given content.
    */
    replace(from, to, text) {
        [from, to] = clip(this, from, to);
        let parts = [];
        this.decompose(0, from, parts, 2 /* Open.To */);
        if (text.length)
            text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */);
        this.decompose(to, this.length, parts, 1 /* Open.From */);
        return TextNode.from(parts, this.length - (to - from) + text.length);
    }
    /**
    Append another document to this one.
    */
    append(other) {
        return this.replace(this.length, this.length, other);
    }
    /**
    Retrieve the text between the given points.
    */
    slice(from, to = this.length) {
        [from, to] = clip(this, from, to);
        let parts = [];
        this.decompose(from, to, parts, 0);
        return TextNode.from(parts, to - from);
    }
    /**
    Test whether this text is equal to another instance.
    */
    eq(other) {
        if (other == this)
            return true;
        if (other.length != this.length || other.lines != this.lines)
            return false;
        let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
        let a = new RawTextCursor(this), b = new RawTextCursor(other);
        for (let skip = start, pos = start;;) {
            a.next(skip);
            b.next(skip);
            skip = 0;
            if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)
                return false;
            pos += a.value.length;
            if (a.done || pos >= end)
                return true;
        }
    }
    /**
    Iterate over the text. When `dir` is `-1`, iteration happens
    from end to start. This will return lines and the breaks between
    them as separate strings.
    */
    iter(dir = 1) { return new RawTextCursor(this, dir); }
    /**
    Iterate over a range of the text. When `from` > `to`, the
    iterator will run in reverse.
    */
    iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); }
    /**
    Return a cursor that iterates over the given range of lines,
    _without_ returning the line breaks between, and yielding empty
    strings for empty lines.
    
    When `from` and `to` are given, they should be 1-based line numbers.
    */
    iterLines(from, to) {
        let inner;
        if (from == null) {
            inner = this.iter();
        }
        else {
            if (to == null)
                to = this.lines + 1;
            let start = this.line(from).from;
            inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
        }
        return new LineCursor(inner);
    }
    /**
    Return the document as a string, using newline characters to
    separate lines.
    */
    toString() { return this.sliceString(0); }
    /**
    Convert the document to an array of lines (which can be
    deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
    */
    toJSON() {
        let lines = [];
        this.flatten(lines);
        return lines;
    }
    /**
    @internal
    */
    constructor() { }
    /**
    Create a `Text` instance for the given array of lines.
    */
    static of(text) {
        if (text.length == 0)
            throw new RangeError("A document must have at least one line");
        if (text.length == 1 && !text[0])
            return dist_Text.empty;
        return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));
    }
}
// Leaves store an array of line strings. There are always line breaks
// between these strings. Leaves are limited in size and have to be
// contained in TextNode instances for bigger documents.
class TextLeaf extends dist_Text {
    constructor(text, length = textLength(text)) {
        super();
        this.text = text;
        this.length = length;
    }
    get lines() { return this.text.length; }
    get children() { return null; }
    lineInner(target, isLine, line, offset) {
        for (let i = 0;; i++) {
            let string = this.text[i], end = offset + string.length;
            if ((isLine ? line : end) >= target)
                return new Line(offset, end, line, string);
            offset = end + 1;
            line++;
        }
    }
    decompose(from, to, target, open) {
        let text = from <= 0 && to >= this.length ? this
            : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
        if (open & 1 /* Open.From */) {
            let prev = target.pop();
            let joined = appendText(text.text, prev.text.slice(), 0, text.length);
            if (joined.length <= 32 /* Tree.Branch */) {
                target.push(new TextLeaf(joined, prev.length + text.length));
            }
            else {
                let mid = joined.length >> 1;
                target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
            }
        }
        else {
            target.push(text);
        }
    }
    replace(from, to, text) {
        if (!(text instanceof TextLeaf))
            return super.replace(from, to, text);
        [from, to] = clip(this, from, to);
        let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);
        let newLen = this.length + text.length - (to - from);
        if (lines.length <= 32 /* Tree.Branch */)
            return new TextLeaf(lines, newLen);
        return TextNode.from(TextLeaf.split(lines, []), newLen);
    }
    sliceString(from, to = this.length, lineSep = "\n") {
        [from, to] = clip(this, from, to);
        let result = "";
        for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {
            let line = this.text[i], end = pos + line.length;
            if (pos > from && i)
                result += lineSep;
            if (from < end && to > pos)
                result += line.slice(Math.max(0, from - pos), to - pos);
            pos = end + 1;
        }
        return result;
    }
    flatten(target) {
        for (let line of this.text)
            target.push(line);
    }
    scanIdentical() { return 0; }
    static split(text, target) {
        let part = [], len = -1;
        for (let line of text) {
            part.push(line);
            len += line.length + 1;
            if (part.length == 32 /* Tree.Branch */) {
                target.push(new TextLeaf(part, len));
                part = [];
                len = -1;
            }
        }
        if (len > -1)
            target.push(new TextLeaf(part, len));
        return target;
    }
}
// Nodes provide the tree structure of the `Text` type. They store a
// number of other nodes or leaves, taking care to balance themselves
// on changes. There are implied line breaks _between_ the children of
// a node (but not before the first or after the last child).
class TextNode extends dist_Text {
    constructor(children, length) {
        super();
        this.children = children;
        this.length = length;
        this.lines = 0;
        for (let child of children)
            this.lines += child.lines;
    }
    lineInner(target, isLine, line, offset) {
        for (let i = 0;; i++) {
            let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;
            if ((isLine ? endLine : end) >= target)
                return child.lineInner(target, isLine, line, offset);
            offset = end + 1;
            line = endLine + 1;
        }
    }
    decompose(from, to, target, open) {
        for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {
            let child = this.children[i], end = pos + child.length;
            if (from <= end && to >= pos) {
                let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0));
                if (pos >= from && end <= to && !childOpen)
                    target.push(child);
                else
                    child.decompose(from - pos, to - pos, target, childOpen);
            }
            pos = end + 1;
        }
    }
    replace(from, to, text) {
        [from, to] = clip(this, from, to);
        if (text.lines < this.lines)
            for (let i = 0, pos = 0; i < this.children.length; i++) {
                let child = this.children[i], end = pos + child.length;
                // Fast path: if the change only affects one child and the
                // child's size remains in the acceptable range, only update
                // that child
                if (from >= pos && to <= end) {
                    let updated = child.replace(from - pos, to - pos, text);
                    let totalLines = this.lines - child.lines + updated.lines;
                    if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) &&
                        updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) {
                        let copy = this.children.slice();
                        copy[i] = updated;
                        return new TextNode(copy, this.length - (to - from) + text.length);
                    }
                    return super.replace(pos, end, updated);
                }
                pos = end + 1;
            }
        return super.replace(from, to, text);
    }
    sliceString(from, to = this.length, lineSep = "\n") {
        [from, to] = clip(this, from, to);
        let result = "";
        for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {
            let child = this.children[i], end = pos + child.length;
            if (pos > from && i)
                result += lineSep;
            if (from < end && to > pos)
                result += child.sliceString(from - pos, to - pos, lineSep);
            pos = end + 1;
        }
        return result;
    }
    flatten(target) {
        for (let child of this.children)
            child.flatten(target);
    }
    scanIdentical(other, dir) {
        if (!(other instanceof TextNode))
            return 0;
        let length = 0;
        let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length]
            : [this.children.length - 1, other.children.length - 1, -1, -1];
        for (;; iA += dir, iB += dir) {
            if (iA == eA || iB == eB)
                return length;
            let chA = this.children[iA], chB = other.children[iB];
            if (chA != chB)
                return length + chA.scanIdentical(chB, dir);
            length += chA.length + 1;
        }
    }
    static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {
        let lines = 0;
        for (let ch of children)
            lines += ch.lines;
        if (lines < 32 /* Tree.Branch */) {
            let flat = [];
            for (let ch of children)
                ch.flatten(flat);
            return new TextLeaf(flat, length);
        }
        let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1;
        let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
        function add(child) {
            let last;
            if (child.lines > maxChunk && child instanceof TextNode) {
                for (let node of child.children)
                    add(node);
            }
            else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
                flush();
                chunked.push(child);
            }
            else if (child instanceof TextLeaf && currentLines &&
                (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf &&
                child.lines + last.lines <= 32 /* Tree.Branch */) {
                currentLines += child.lines;
                currentLen += child.length + 1;
                currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);
            }
            else {
                if (currentLines + child.lines > chunk)
                    flush();
                currentLines += child.lines;
                currentLen += child.length + 1;
                currentChunk.push(child);
            }
        }
        function flush() {
            if (currentLines == 0)
                return;
            chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
            currentLen = -1;
            currentLines = currentChunk.length = 0;
        }
        for (let child of children)
            add(child);
        flush();
        return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
    }
}
dist_Text.empty = /*@__PURE__*/new TextLeaf([""], 0);
function textLength(text) {
    let length = -1;
    for (let line of text)
        length += line.length + 1;
    return length;
}
function appendText(text, target, from = 0, to = 1e9) {
    for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) {
        let line = text[i], end = pos + line.length;
        if (end >= from) {
            if (end > to)
                line = line.slice(0, to - pos);
            if (pos < from)
                line = line.slice(from - pos);
            if (first) {
                target[target.length - 1] += line;
                first = false;
            }
            else
                target.push(line);
        }
        pos = end + 1;
    }
    return target;
}
function sliceText(text, from, to) {
    return appendText(text, [""], from, to);
}
class RawTextCursor {
    constructor(text, dir = 1) {
        this.dir = dir;
        this.done = false;
        this.lineBreak = false;
        this.value = "";
        this.nodes = [text];
        this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1];
    }
    nextInner(skip, dir) {
        this.done = this.lineBreak = false;
        for (;;) {
            let last = this.nodes.length - 1;
            let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;
            let size = top instanceof TextLeaf ? top.text.length : top.children.length;
            if (offset == (dir > 0 ? size : 0)) {
                if (last == 0) {
                    this.done = true;
                    this.value = "";
                    return this;
                }
                if (dir > 0)
                    this.offsets[last - 1]++;
                this.nodes.pop();
                this.offsets.pop();
            }
            else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
                this.offsets[last] += dir;
                if (skip == 0) {
                    this.lineBreak = true;
                    this.value = "\n";
                    return this;
                }
                skip--;
            }
            else if (top instanceof TextLeaf) {
                // Move to the next string
                let next = top.text[offset + (dir < 0 ? -1 : 0)];
                this.offsets[last] += dir;
                if (next.length > Math.max(0, skip)) {
                    this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
                    return this;
                }
                skip -= next.length;
            }
            else {
                let next = top.children[offset + (dir < 0 ? -1 : 0)];
                if (skip > next.length) {
                    skip -= next.length;
                    this.offsets[last] += dir;
                }
                else {
                    if (dir < 0)
                        this.offsets[last]--;
                    this.nodes.push(next);
                    this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);
                }
            }
        }
    }
    next(skip = 0) {
        if (skip < 0) {
            this.nextInner(-skip, (-this.dir));
            skip = this.value.length;
        }
        return this.nextInner(skip, this.dir);
    }
}
class PartialTextCursor {
    constructor(text, start, end) {
        this.value = "";
        this.done = false;
        this.cursor = new RawTextCursor(text, start > end ? -1 : 1);
        this.pos = start > end ? text.length : 0;
        this.from = Math.min(start, end);
        this.to = Math.max(start, end);
    }
    nextInner(skip, dir) {
        if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
            this.value = "";
            this.done = true;
            return this;
        }
        skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
        let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
        if (skip > limit)
            skip = limit;
        limit -= skip;
        let { value } = this.cursor.next(skip);
        this.pos += (value.length + skip) * dir;
        this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
        this.done = !this.value;
        return this;
    }
    next(skip = 0) {
        if (skip < 0)
            skip = Math.max(skip, this.from - this.pos);
        else if (skip > 0)
            skip = Math.min(skip, this.to - this.pos);
        return this.nextInner(skip, this.cursor.dir);
    }
    get lineBreak() { return this.cursor.lineBreak && this.value != ""; }
}
class LineCursor {
    constructor(inner) {
        this.inner = inner;
        this.afterBreak = true;
        this.value = "";
        this.done = false;
    }
    next(skip = 0) {
        let { done, lineBreak, value } = this.inner.next(skip);
        if (done && this.afterBreak) {
            this.value = "";
            this.afterBreak = false;
        }
        else if (done) {
            this.done = true;
            this.value = "";
        }
        else if (lineBreak) {
            if (this.afterBreak) {
                this.value = "";
            }
            else {
                this.afterBreak = true;
                this.next();
            }
        }
        else {
            this.value = value;
            this.afterBreak = false;
        }
        return this;
    }
    get lineBreak() { return false; }
}
if (typeof Symbol != "undefined") {
    dist_Text.prototype[Symbol.iterator] = function () { return this.iter(); };
    RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] =
        LineCursor.prototype[Symbol.iterator] = function () { return this; };
}
/**
This type describes a line in the document. It is created
on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).
*/
class Line {
    /**
    @internal
    */
    constructor(
    /**
    The position of the start of the line.
    */
    from, 
    /**
    The position at the end of the line (_before_ the line break,
    or at the end of document for the last line).
    */
    to, 
    /**
    This line's line number (1-based).
    */
    number, 
    /**
    The line's content.
    */
    text) {
        this.from = from;
        this.to = to;
        this.number = number;
        this.text = text;
    }
    /**
    The length of the line (not including any line break after it).
    */
    get length() { return this.to - this.from; }
}
function clip(text, from, to) {
    from = Math.max(0, Math.min(text.length, from));
    return [from, Math.max(from, Math.min(text.length, to))];
}

/**
Returns a next grapheme cluster break _after_ (not equal to)
`pos`, if `forward` is true, or before otherwise. Returns `pos`
itself if no further cluster break is available in the string.
Moves across surrogate pairs, extending characters (when
`includeExtending` is true), characters joined with zero-width
joiners, and flag emoji.
*/
function dist_findClusterBreak(str, pos, forward = true, includeExtending = true) {
    return src_findClusterBreak(str, pos, forward, includeExtending);
}
function dist_surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }
function dist_surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }
/**
Find the code point at the given position in a string (like the
[`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
string method).
*/
function dist_codePointAt(str, pos) {
    let code0 = str.charCodeAt(pos);
    if (!dist_surrogateHigh(code0) || pos + 1 == str.length)
        return code0;
    let code1 = str.charCodeAt(pos + 1);
    if (!dist_surrogateLow(code1))
        return code0;
    return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000;
}
/**
Given a Unicode codepoint, return the JavaScript string that
respresents it (like
[`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).
*/
function fromCodePoint(code) {
    if (code <= 0xffff)
        return String.fromCharCode(code);
    code -= 0x10000;
    return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);
}
/**
The amount of positions a character takes up in a JavaScript string.
*/
function dist_codePointSize(code) { return code < 0x10000 ? 1 : 2; }

const DefaultSplit = /\r\n?|\n/;
/**
Distinguishes different ways in which positions can be mapped.
*/
var dist_MapMode = /*@__PURE__*/(function (MapMode) {
    /**
    Map a position to a valid new position, even when its context
    was deleted.
    */
    MapMode[MapMode["Simple"] = 0] = "Simple";
    /**
    Return null if deletion happens across the position.
    */
    MapMode[MapMode["TrackDel"] = 1] = "TrackDel";
    /**
    Return null if the character _before_ the position is deleted.
    */
    MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore";
    /**
    Return null if the character _after_ the position is deleted.
    */
    MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter";
return MapMode})(dist_MapMode || (dist_MapMode = {}));
/**
A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)
that doesn't store the inserted text. As such, it can't be
applied, but is cheaper to store and manipulate.
*/
class ChangeDesc {
    // Sections are encoded as pairs of integers. The first is the
    // length in the current document, and the second is -1 for
    // unaffected sections, and the length of the replacement content
    // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
    // 0), and a replacement two positive numbers.
    /**
    @internal
    */
    constructor(
    /**
    @internal
    */
    sections) {
        this.sections = sections;
    }
    /**
    The length of the document before the change.
    */
    get length() {
        let result = 0;
        for (let i = 0; i < this.sections.length; i += 2)
            result += this.sections[i];
        return result;
    }
    /**
    The length of the document after the change.
    */
    get newLength() {
        let result = 0;
        for (let i = 0; i < this.sections.length; i += 2) {
            let ins = this.sections[i + 1];
            result += ins < 0 ? this.sections[i] : ins;
        }
        return result;
    }
    /**
    False when there are actual changes in this set.
    */
    get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }
    /**
    Iterate over the unchanged parts left by these changes. `posA`
    provides the position of the range in the old document, `posB`
    the new position in the changed document.
    */
    iterGaps(f) {
        for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {
            let len = this.sections[i++], ins = this.sections[i++];
            if (ins < 0) {
                f(posA, posB, len);
                posB += len;
            }
            else {
                posB += ins;
            }
            posA += len;
        }
    }
    /**
    Iterate over the ranges changed by these changes. (See
    [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
    variant that also provides you with the inserted text.)
    `fromA`/`toA` provides the extent of the change in the starting
    document, `fromB`/`toB` the extent of the replacement in the
    changed document.
    
    When `individual` is true, adjacent changes (which are kept
    separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
    reported separately.
    */
    iterChangedRanges(f, individual = false) {
        iterChanges(this, f, individual);
    }
    /**
    Get a description of the inverted form of these changes.
    */
    get invertedDesc() {
        let sections = [];
        for (let i = 0; i < this.sections.length;) {
            let len = this.sections[i++], ins = this.sections[i++];
            if (ins < 0)
                sections.push(len, ins);
            else
                sections.push(ins, len);
        }
        return new ChangeDesc(sections);
    }
    /**
    Compute the combined effect of applying another set of changes
    after this one. The length of the document after this set should
    match the length before `other`.
    */
    composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); }
    /**
    Map this description, which should start with the same document
    as `other`, over another set of changes, so that it can be
    applied after it. When `before` is true, map as if the changes
    in `this` happened before the ones in `other`.
    */
    mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); }
    mapPos(pos, assoc = -1, mode = dist_MapMode.Simple) {
        let posA = 0, posB = 0;
        for (let i = 0; i < this.sections.length;) {
            let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;
            if (ins < 0) {
                if (endA > pos)
                    return posB + (pos - posA);
                posB += len;
            }
            else {
                if (mode != dist_MapMode.Simple && endA >= pos &&
                    (mode == dist_MapMode.TrackDel && posA < pos && endA > pos ||
                        mode == dist_MapMode.TrackBefore && posA < pos ||
                        mode == dist_MapMode.TrackAfter && endA > pos))
                    return null;
                if (endA > pos || endA == pos && assoc < 0 && !len)
                    return pos == posA || assoc < 0 ? posB : posB + ins;
                posB += ins;
            }
            posA = endA;
        }
        if (pos > posA)
            throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
        return posB;
    }
    /**
    Check whether these changes touch a given range. When one of the
    changes entirely covers the range, the string `"cover"` is
    returned.
    */
    touchesRange(from, to = from) {
        for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {
            let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
            if (ins >= 0 && pos <= to && end >= from)
                return pos < from && end > to ? "cover" : true;
            pos = end;
        }
        return false;
    }
    /**
    @internal
    */
    toString() {
        let result = "";
        for (let i = 0; i < this.sections.length;) {
            let len = this.sections[i++], ins = this.sections[i++];
            result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
        }
        return result;
    }
    /**
    Serialize this change desc to a JSON-representable value.
    */
    toJSON() { return this.sections; }
    /**
    Create a change desc from its JSON representation (as produced
    by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
    */
    static fromJSON(json) {
        if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number"))
            throw new RangeError("Invalid JSON representation of ChangeDesc");
        return new ChangeDesc(json);
    }
    /**
    @internal
    */
    static create(sections) { return new ChangeDesc(sections); }
}
/**
A change set represents a group of modifications to a document. It
stores the document length, and can only be applied to documents
with exactly that length.
*/
class ChangeSet extends ChangeDesc {
    constructor(sections, 
    /**
    @internal
    */
    inserted) {
        super(sections);
        this.inserted = inserted;
    }
    /**
    Apply the changes to a document, returning the modified
    document.
    */
    apply(doc) {
        if (this.length != doc.length)
            throw new RangeError("Applying change set to a document with the wrong length");
        iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false);
        return doc;
    }
    mapDesc(other, before = false) { return mapSet(this, other, before, true); }
    /**
    Given the document as it existed _before_ the changes, return a
    change set that represents the inverse of this set, which could
    be used to go from the document created by the changes back to
    the document as it existed before the changes.
    */
    invert(doc) {
        let sections = this.sections.slice(), inserted = [];
        for (let i = 0, pos = 0; i < sections.length; i += 2) {
            let len = sections[i], ins = sections[i + 1];
            if (ins >= 0) {
                sections[i] = ins;
                sections[i + 1] = len;
                let index = i >> 1;
                while (inserted.length < index)
                    inserted.push(dist_Text.empty);
                inserted.push(len ? doc.slice(pos, pos + len) : dist_Text.empty);
            }
            pos += len;
        }
        return new ChangeSet(sections, inserted);
    }
    /**
    Combine two subsequent change sets into a single set. `other`
    must start in the document produced by `this`. If `this` goes
    `docA` → `docB` and `other` represents `docB` → `docC`, the
    returned value will represent the change `docA` → `docC`.
    */
    compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); }
    /**
    Given another change set starting in the same document, maps this
    change set over the other, producing a new change set that can be
    applied to the document produced by applying `other`. When
    `before` is `true`, order changes as if `this` comes before
    `other`, otherwise (the default) treat `other` as coming first.
    
    Given two changes `A` and `B`, `A.compose(B.map(A))` and
    `B.compose(A.map(B, true))` will produce the same document. This
    provides a basic form of [operational
    transformation](https://en.wikipedia.org/wiki/Operational_transformation),
    and can be used for collaborative editing.
    */
    map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); }
    /**
    Iterate over the changed ranges in the document, calling `f` for
    each, with the range in the original document (`fromA`-`toA`)
    and the range that replaces it in the new document
    (`fromB`-`toB`).
    
    When `individual` is true, adjacent changes are reported
    separately.
    */
    iterChanges(f, individual = false) {
        iterChanges(this, f, individual);
    }
    /**
    Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
    set.
    */
    get desc() { return ChangeDesc.create(this.sections); }
    /**
    @internal
    */
    filter(ranges) {
        let resultSections = [], resultInserted = [], filteredSections = [];
        let iter = new SectionIter(this);
        done: for (let i = 0, pos = 0;;) {
            let next = i == ranges.length ? 1e9 : ranges[i++];
            while (pos < next || pos == next && iter.len == 0) {
                if (iter.done)
                    break done;
                let len = Math.min(iter.len, next - pos);
                addSection(filteredSections, len, -1);
                let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
                addSection(resultSections, len, ins);
                if (ins > 0)
                    addInsert(resultInserted, resultSections, iter.text);
                iter.forward(len);
                pos += len;
            }
            let end = ranges[i++];
            while (pos < end) {
                if (iter.done)
                    break done;
                let len = Math.min(iter.len, end - pos);
                addSection(resultSections, len, -1);
                addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
                iter.forward(len);
                pos += len;
            }
        }
        return { changes: new ChangeSet(resultSections, resultInserted),
            filtered: ChangeDesc.create(filteredSections) };
    }
    /**
    Serialize this change set to a JSON-representable value.
    */
    toJSON() {
        let parts = [];
        for (let i = 0; i < this.sections.length; i += 2) {
            let len = this.sections[i], ins = this.sections[i + 1];
            if (ins < 0)
                parts.push(len);
            else if (ins == 0)
                parts.push([len]);
            else
                parts.push([len].concat(this.inserted[i >> 1].toJSON()));
        }
        return parts;
    }
    /**
    Create a change set for the given changes, for a document of the
    given length, using `lineSep` as line separator.
    */
    static of(changes, length, lineSep) {
        let sections = [], inserted = [], pos = 0;
        let total = null;
        function flush(force = false) {
            if (!force && !sections.length)
                return;
            if (pos < length)
                addSection(sections, length - pos, -1);
            let set = new ChangeSet(sections, inserted);
            total = total ? total.compose(set.map(total)) : set;
            sections = [];
            inserted = [];
            pos = 0;
        }
        function process(spec) {
            if (Array.isArray(spec)) {
                for (let sub of spec)
                    process(sub);
            }
            else if (spec instanceof ChangeSet) {
                if (spec.length != length)
                    throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
                flush();
                total = total ? total.compose(spec.map(total)) : spec;
            }
            else {
                let { from, to = from, insert } = spec;
                if (from > to || from < 0 || to > length)
                    throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
                let insText = !insert ? dist_Text.empty : typeof insert == "string" ? dist_Text.of(insert.split(lineSep || DefaultSplit)) : insert;
                let insLen = insText.length;
                if (from == to && insLen == 0)
                    return;
                if (from < pos)
                    flush();
                if (from > pos)
                    addSection(sections, from - pos, -1);
                addSection(sections, to - from, insLen);
                addInsert(inserted, sections, insText);
                pos = to;
            }
        }
        process(changes);
        flush(!total);
        return total;
    }
    /**
    Create an empty changeset of the given length.
    */
    static empty(length) {
        return new ChangeSet(length ? [length, -1] : [], []);
    }
    /**
    Create a changeset from its JSON representation (as produced by
    [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
    */
    static fromJSON(json) {
        if (!Array.isArray(json))
            throw new RangeError("Invalid JSON representation of ChangeSet");
        let sections = [], inserted = [];
        for (let i = 0; i < json.length; i++) {
            let part = json[i];
            if (typeof part == "number") {
                sections.push(part, -1);
            }
            else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) {
                throw new RangeError("Invalid JSON representation of ChangeSet");
            }
            else if (part.length == 1) {
                sections.push(part[0], 0);
            }
            else {
                while (inserted.length < i)
                    inserted.push(dist_Text.empty);
                inserted[i] = dist_Text.of(part.slice(1));
                sections.push(part[0], inserted[i].length);
            }
        }
        return new ChangeSet(sections, inserted);
    }
    /**
    @internal
    */
    static createSet(sections, inserted) {
        return new ChangeSet(sections, inserted);
    }
}
function addSection(sections, len, ins, forceJoin = false) {
    if (len == 0 && ins <= 0)
        return;
    let last = sections.length - 2;
    if (last >= 0 && ins <= 0 && ins == sections[last + 1])
        sections[last] += len;
    else if (last >= 0 && len == 0 && sections[last] == 0)
        sections[last + 1] += ins;
    else if (forceJoin) {
        sections[last] += len;
        sections[last + 1] += ins;
    }
    else
        sections.push(len, ins);
}
function addInsert(values, sections, value) {
    if (value.length == 0)
        return;
    let index = (sections.length - 2) >> 1;
    if (index < values.length) {
        values[values.length - 1] = values[values.length - 1].append(value);
    }
    else {
        while (values.length < index)
            values.push(dist_Text.empty);
        values.push(value);
    }
}
function iterChanges(desc, f, individual) {
    let inserted = desc.inserted;
    for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) {
        let len = desc.sections[i++], ins = desc.sections[i++];
        if (ins < 0) {
            posA += len;
            posB += len;
        }
        else {
            let endA = posA, endB = posB, text = dist_Text.empty;
            for (;;) {
                endA += len;
                endB += ins;
                if (ins && inserted)
                    text = text.append(inserted[(i - 2) >> 1]);
                if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)
                    break;
                len = desc.sections[i++];
                ins = desc.sections[i++];
            }
            f(posA, endA, posB, endB, text);
            posA = endA;
            posB = endB;
        }
    }
}
function mapSet(setA, setB, before, mkSet = false) {
    // Produce a copy of setA that applies to the document after setB
    // has been applied (assuming both start at the same document).
    let sections = [], insert = mkSet ? [] : null;
    let a = new SectionIter(setA), b = new SectionIter(setB);
    // Iterate over both sets in parallel. inserted tracks, for changes
    // in A that have to be processed piece-by-piece, whether their
    // content has been inserted already, and refers to the section
    // index.
    for (let inserted = -1;;) {
        if (a.done && b.len || b.done && a.len) {
            throw new Error("Mismatched change set lengths");
        }
        else if (a.ins == -1 && b.ins == -1) {
            // Move across ranges skipped by both sets.
            let len = Math.min(a.len, b.len);
            addSection(sections, len, -1);
            a.forward(len);
            b.forward(len);
        }
        else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
            // If there's a change in B that comes before the next change in
            // A (ordered by start pos, then len, then before flag), skip
            // that (and process any changes in A it covers).
            let len = b.len;
            addSection(sections, b.ins, -1);
            while (len) {
                let piece = Math.min(a.len, len);
                if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
                    addSection(sections, 0, a.ins);
                    if (insert)
                        addInsert(insert, sections, a.text);
                    inserted = a.i;
                }
                a.forward(piece);
                len -= piece;
            }
            b.next();
        }
        else if (a.ins >= 0) {
            // Process the part of a change in A up to the start of the next
            // non-deletion change in B (if overlapping).
            let len = 0, left = a.len;
            while (left) {
                if (b.ins == -1) {
                    let piece = Math.min(left, b.len);
                    len += piece;
                    left -= piece;
                    b.forward(piece);
                }
                else if (b.ins == 0 && b.len < left) {
                    left -= b.len;
                    b.next();
                }
                else {
                    break;
                }
            }
            addSection(sections, len, inserted < a.i ? a.ins : 0);
            if (insert && inserted < a.i)
                addInsert(insert, sections, a.text);
            inserted = a.i;
            a.forward(a.len - left);
        }
        else if (a.done && b.done) {
            return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
        }
        else {
            throw new Error("Mismatched change set lengths");
        }
    }
}
function composeSets(setA, setB, mkSet = false) {
    let sections = [];
    let insert = mkSet ? [] : null;
    let a = new SectionIter(setA), b = new SectionIter(setB);
    for (let open = false;;) {
        if (a.done && b.done) {
            return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
        }
        else if (a.ins == 0) { // Deletion in A
            addSection(sections, a.len, 0, open);
            a.next();
        }
        else if (b.len == 0 && !b.done) { // Insertion in B
            addSection(sections, 0, b.ins, open);
            if (insert)
                addInsert(insert, sections, b.text);
            b.next();
        }
        else if (a.done || b.done) {
            throw new Error("Mismatched change set lengths");
        }
        else {
            let len = Math.min(a.len2, b.len), sectionLen = sections.length;
            if (a.ins == -1) {
                let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
                addSection(sections, len, insB, open);
                if (insert && insB)
                    addInsert(insert, sections, b.text);
            }
            else if (b.ins == -1) {
                addSection(sections, a.off ? 0 : a.len, len, open);
                if (insert)
                    addInsert(insert, sections, a.textBit(len));
            }
            else {
                addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
                if (insert && !b.off)
                    addInsert(insert, sections, b.text);
            }
            open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
            a.forward2(len);
            b.forward(len);
        }
    }
}
class SectionIter {
    constructor(set) {
        this.set = set;
        this.i = 0;
        this.next();
    }
    next() {
        let { sections } = this.set;
        if (this.i < sections.length) {
            this.len = sections[this.i++];
            this.ins = sections[this.i++];
        }
        else {
            this.len = 0;
            this.ins = -2;
        }
        this.off = 0;
    }
    get done() { return this.ins == -2; }
    get len2() { return this.ins < 0 ? this.len : this.ins; }
    get text() {
        let { inserted } = this.set, index = (this.i - 2) >> 1;
        return index >= inserted.length ? dist_Text.empty : inserted[index];
    }
    textBit(len) {
        let { inserted } = this.set, index = (this.i - 2) >> 1;
        return index >= inserted.length && !len ? dist_Text.empty
            : inserted[index].slice(this.off, len == null ? undefined : this.off + len);
    }
    forward(len) {
        if (len == this.len)
            this.next();
        else {
            this.len -= len;
            this.off += len;
        }
    }
    forward2(len) {
        if (this.ins == -1)
            this.forward(len);
        else if (len == this.ins)
            this.next();
        else {
            this.ins -= len;
            this.off += len;
        }
    }
}

/**
A single selection range. When
[`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold
multiple ranges. By default, selections hold exactly one range.
*/
class SelectionRange {
    constructor(
    /**
    The lower boundary of the range.
    */
    from, 
    /**
    The upper boundary of the range.
    */
    to, flags) {
        this.from = from;
        this.to = to;
        this.flags = flags;
    }
    /**
    The anchor of the range—the side that doesn't move when you
    extend it.
    */
    get anchor() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.to : this.from; }
    /**
    The head of the range, which is moved when the range is
    [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
    */
    get head() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.from : this.to; }
    /**
    True when `anchor` and `head` are at the same position.
    */
    get empty() { return this.from == this.to; }
    /**
    If this is a cursor that is explicitly associated with the
    character on one of its sides, this returns the side. -1 means
    the character before its position, 1 the character after, and 0
    means no association.
    */
    get assoc() { return this.flags & 8 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 16 /* RangeFlag.AssocAfter */ ? 1 : 0; }
    /**
    The bidirectional text level associated with this cursor, if
    any.
    */
    get bidiLevel() {
        let level = this.flags & 7 /* RangeFlag.BidiLevelMask */;
        return level == 7 ? null : level;
    }
    /**
    The goal column (stored vertical offset) associated with a
    cursor. This is used to preserve the vertical position when
    [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
    lines of different length.
    */
    get goalColumn() {
        let value = this.flags >> 6 /* RangeFlag.GoalColumnOffset */;
        return value == 16777215 /* RangeFlag.NoGoalColumn */ ? undefined : value;
    }
    /**
    Map this range through a change, producing a valid range in the
    updated document.
    */
    map(change, assoc = -1) {
        let from, to;
        if (this.empty) {
            from = to = change.mapPos(this.from, assoc);
        }
        else {
            from = change.mapPos(this.from, 1);
            to = change.mapPos(this.to, -1);
        }
        return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);
    }
    /**
    Extend this range to cover at least `from` to `to`.
    */
    extend(from, to = from) {
        if (from <= this.anchor && to >= this.anchor)
            return dist_EditorSelection.range(from, to);
        let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
        return dist_EditorSelection.range(this.anchor, head);
    }
    /**
    Compare this range to another range.
    */
    eq(other, includeAssoc = false) {
        return this.anchor == other.anchor && this.head == other.head &&
            (!includeAssoc || !this.empty || this.assoc == other.assoc);
    }
    /**
    Return a JSON-serializable object representing the range.
    */
    toJSON() { return { anchor: this.anchor, head: this.head }; }
    /**
    Convert a JSON representation of a range to a `SelectionRange`
    instance.
    */
    static fromJSON(json) {
        if (!json || typeof json.anchor != "number" || typeof json.head != "number")
            throw new RangeError("Invalid JSON representation for SelectionRange");
        return dist_EditorSelection.range(json.anchor, json.head);
    }
    /**
    @internal
    */
    static create(from, to, flags) {
        return new SelectionRange(from, to, flags);
    }
}
/**
An editor selection holds one or more selection ranges.
*/
class dist_EditorSelection {
    constructor(
    /**
    The ranges in the selection, sorted by position. Ranges cannot
    overlap (but they may touch, if they aren't empty).
    */
    ranges, 
    /**
    The index of the _main_ range in the selection (which is
    usually the range that was added last).
    */
    mainIndex) {
        this.ranges = ranges;
        this.mainIndex = mainIndex;
    }
    /**
    Map a selection through a change. Used to adjust the selection
    position for changes.
    */
    map(change, assoc = -1) {
        if (change.empty)
            return this;
        return dist_EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);
    }
    /**
    Compare this selection to another selection. By default, ranges
    are compared only by position. When `includeAssoc` is true,
    cursor ranges must also have the same
    [`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value.
    */
    eq(other, includeAssoc = false) {
        if (this.ranges.length != other.ranges.length ||
            this.mainIndex != other.mainIndex)
            return false;
        for (let i = 0; i < this.ranges.length; i++)
            if (!this.ranges[i].eq(other.ranges[i], includeAssoc))
                return false;
        return true;
    }
    /**
    Get the primary selection range. Usually, you should make sure
    your code applies to _all_ ranges, by using methods like
    [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
    */
    get main() { return this.ranges[this.mainIndex]; }
    /**
    Make sure the selection only has one range. Returns a selection
    holding only the main range from this selection.
    */
    asSingle() {
        return this.ranges.length == 1 ? this : new dist_EditorSelection([this.main], 0);
    }
    /**
    Extend this selection with an extra range.
    */
    addRange(range, main = true) {
        return dist_EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
    }
    /**
    Replace a given range with another range, and then normalize the
    selection to merge and sort ranges if necessary.
    */
    replaceRange(range, which = this.mainIndex) {
        let ranges = this.ranges.slice();
        ranges[which] = range;
        return dist_EditorSelection.create(ranges, this.mainIndex);
    }
    /**
    Convert this selection to an object that can be serialized to
    JSON.
    */
    toJSON() {
        return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex };
    }
    /**
    Create a selection from a JSON representation.
    */
    static fromJSON(json) {
        if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length)
            throw new RangeError("Invalid JSON representation for EditorSelection");
        return new dist_EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);
    }
    /**
    Create a selection holding a single range.
    */
    static single(anchor, head = anchor) {
        return new dist_EditorSelection([dist_EditorSelection.range(anchor, head)], 0);
    }
    /**
    Sort and merge the given set of ranges, creating a valid
    selection.
    */
    static create(ranges, mainIndex = 0) {
        if (ranges.length == 0)
            throw new RangeError("A selection needs at least one range");
        for (let pos = 0, i = 0; i < ranges.length; i++) {
            let range = ranges[i];
            if (range.empty ? range.from <= pos : range.from < pos)
                return dist_EditorSelection.normalized(ranges.slice(), mainIndex);
            pos = range.to;
        }
        return new dist_EditorSelection(ranges, mainIndex);
    }
    /**
    Create a cursor selection range at the given position. You can
    safely ignore the optional arguments in most situations.
    */
    static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
        return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 /* RangeFlag.AssocBefore */ : 16 /* RangeFlag.AssocAfter */) |
            (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) |
            ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */));
    }
    /**
    Create a selection range.
    */
    static range(anchor, head, goalColumn, bidiLevel) {
        let flags = ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */) |
            (bidiLevel == null ? 7 : Math.min(6, bidiLevel));
        return head < anchor ? SelectionRange.create(head, anchor, 32 /* RangeFlag.Inverted */ | 16 /* RangeFlag.AssocAfter */ | flags)
            : SelectionRange.create(anchor, head, (head > anchor ? 8 /* RangeFlag.AssocBefore */ : 0) | flags);
    }
    /**
    @internal
    */
    static normalized(ranges, mainIndex = 0) {
        let main = ranges[mainIndex];
        ranges.sort((a, b) => a.from - b.from);
        mainIndex = ranges.indexOf(main);
        for (let i = 1; i < ranges.length; i++) {
            let range = ranges[i], prev = ranges[i - 1];
            if (range.empty ? range.from <= prev.to : range.from < prev.to) {
                let from = prev.from, to = Math.max(range.to, prev.to);
                if (i <= mainIndex)
                    mainIndex--;
                ranges.splice(--i, 2, range.anchor > range.head ? dist_EditorSelection.range(to, from) : dist_EditorSelection.range(from, to));
            }
        }
        return new dist_EditorSelection(ranges, mainIndex);
    }
}
function checkSelection(selection, docLength) {
    for (let range of selection.ranges)
        if (range.to > docLength)
            throw new RangeError("Selection points outside of document");
}

let nextID = 0;
/**
A facet is a labeled value that is associated with an editor
state. It takes inputs from any number of extensions, and combines
those into a single output value.

Examples of uses of facets are the [tab
size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor
attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update
listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).

Note that `Facet` instances can be used anywhere where
[`FacetReader`](https://codemirror.net/6/docs/ref/#state.FacetReader) is expected.
*/
class Facet {
    constructor(
    /**
    @internal
    */
    combine, 
    /**
    @internal
    */
    compareInput, 
    /**
    @internal
    */
    compare, isStatic, enables) {
        this.combine = combine;
        this.compareInput = compareInput;
        this.compare = compare;
        this.isStatic = isStatic;
        /**
        @internal
        */
        this.id = nextID++;
        this.default = combine([]);
        this.extensions = typeof enables == "function" ? enables(this) : enables;
    }
    /**
    Returns a facet reader for this facet, which can be used to
    [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.
    */
    get reader() { return this; }
    /**
    Define a new facet.
    */
    static define(config = {}) {
        return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray : (a, b) => a === b), !!config.static, config.enables);
    }
    /**
    Returns an extension that adds the given value to this facet.
    */
    of(value) {
        return new FacetProvider([], this, 0 /* Provider.Static */, value);
    }
    /**
    Create an extension that computes a value for the facet from a
    state. You must take care to declare the parts of the state that
    this value depends on, since your function is only called again
    for a new state when one of those parts changed.
    
    In cases where your value depends only on a single field, you'll
    want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
    */
    compute(deps, get) {
        if (this.isStatic)
            throw new Error("Can't compute a static facet");
        return new FacetProvider(deps, this, 1 /* Provider.Single */, get);
    }
    /**
    Create an extension that computes zero or more values for this
    facet from a state.
    */
    computeN(deps, get) {
        if (this.isStatic)
            throw new Error("Can't compute a static facet");
        return new FacetProvider(deps, this, 2 /* Provider.Multi */, get);
    }
    from(field, get) {
        if (!get)
            get = x => x;
        return this.compute([field], state => get(state.field(field)));
    }
}
function sameArray(a, b) {
    return a == b || a.length == b.length && a.every((e, i) => e === b[i]);
}
class FacetProvider {
    constructor(dependencies, facet, type, value) {
        this.dependencies = dependencies;
        this.facet = facet;
        this.type = type;
        this.value = value;
        this.id = nextID++;
    }
    dynamicSlot(addresses) {
        var _a;
        let getter = this.value;
        let compare = this.facet.compareInput;
        let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */;
        let depDoc = false, depSel = false, depAddrs = [];
        for (let dep of this.dependencies) {
            if (dep == "doc")
                depDoc = true;
            else if (dep == "selection")
                depSel = true;
            else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0)
                depAddrs.push(addresses[dep.id]);
        }
        return {
            create(state) {
                state.values[idx] = getter(state);
                return 1 /* SlotStatus.Changed */;
            },
            update(state, tr) {
                if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) {
                    let newVal = getter(state);
                    if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) {
                        state.values[idx] = newVal;
                        return 1 /* SlotStatus.Changed */;
                    }
                }
                return 0;
            },
            reconfigure: (state, oldState) => {
                let newVal, oldAddr = oldState.config.address[id];
                if (oldAddr != null) {
                    let oldVal = getAddr(oldState, oldAddr);
                    if (this.dependencies.every(dep => {
                        return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) :
                            dep instanceof dist_StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
                    }) || (multi ? compareArray(newVal = getter(state), oldVal, compare) : compare(newVal = getter(state), oldVal))) {
                        state.values[idx] = oldVal;
                        return 0;
                    }
                }
                else {
                    newVal = getter(state);
                }
                state.values[idx] = newVal;
                return 1 /* SlotStatus.Changed */;
            }
        };
    }
}
function compareArray(a, b, compare) {
    if (a.length != b.length)
        return false;
    for (let i = 0; i < a.length; i++)
        if (!compare(a[i], b[i]))
            return false;
    return true;
}
function ensureAll(state, addrs) {
    let changed = false;
    for (let addr of addrs)
        if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */)
            changed = true;
    return changed;
}
function dynamicFacetSlot(addresses, facet, providers) {
    let providerAddrs = providers.map(p => addresses[p.id]);
    let providerTypes = providers.map(p => p.type);
    let dynamic = providerAddrs.filter(p => !(p & 1));
    let idx = addresses[facet.id] >> 1;
    function get(state) {
        let values = [];
        for (let i = 0; i < providerAddrs.length; i++) {
            let value = getAddr(state, providerAddrs[i]);
            if (providerTypes[i] == 2 /* Provider.Multi */)
                for (let val of value)
                    values.push(val);
            else
                values.push(value);
        }
        return facet.combine(values);
    }
    return {
        create(state) {
            for (let addr of providerAddrs)
                ensureAddr(state, addr);
            state.values[idx] = get(state);
            return 1 /* SlotStatus.Changed */;
        },
        update(state, tr) {
            if (!ensureAll(state, dynamic))
                return 0;
            let value = get(state);
            if (facet.compare(value, state.values[idx]))
                return 0;
            state.values[idx] = value;
            return 1 /* SlotStatus.Changed */;
        },
        reconfigure(state, oldState) {
            let depChanged = ensureAll(state, providerAddrs);
            let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
            if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {
                state.values[idx] = oldValue;
                return 0;
            }
            let value = get(state);
            if (facet.compare(value, oldValue)) {
                state.values[idx] = oldValue;
                return 0;
            }
            state.values[idx] = value;
            return 1 /* SlotStatus.Changed */;
        }
    };
}
const initField = /*@__PURE__*/Facet.define({ static: true });
/**
Fields can store additional information in an editor state, and
keep it in sync with the rest of the state.
*/
class dist_StateField {
    constructor(
    /**
    @internal
    */
    id, createF, updateF, compareF, 
    /**
    @internal
    */
    spec) {
        this.id = id;
        this.createF = createF;
        this.updateF = updateF;
        this.compareF = compareF;
        this.spec = spec;
        /**
        @internal
        */
        this.provides = undefined;
    }
    /**
    Define a state field.
    */
    static define(config) {
        let field = new dist_StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);
        if (config.provide)
            field.provides = config.provide(field);
        return field;
    }
    create(state) {
        let init = state.facet(initField).find(i => i.field == this);
        return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
    }
    /**
    @internal
    */
    slot(addresses) {
        let idx = addresses[this.id] >> 1;
        return {
            create: (state) => {
                state.values[idx] = this.create(state);
                return 1 /* SlotStatus.Changed */;
            },
            update: (state, tr) => {
                let oldVal = state.values[idx];
                let value = this.updateF(oldVal, tr);
                if (this.compareF(oldVal, value))
                    return 0;
                state.values[idx] = value;
                return 1 /* SlotStatus.Changed */;
            },
            reconfigure: (state, oldState) => {
                let init = state.facet(initField), oldInit = oldState.facet(initField), reInit;
                if ((reInit = init.find(i => i.field == this)) && reInit != oldInit.find(i => i.field == this)) {
                    state.values[idx] = reInit.create(state);
                    return 1 /* SlotStatus.Changed */;
                }
                if (oldState.config.address[this.id] != null) {
                    state.values[idx] = oldState.field(this);
                    return 0;
                }
                state.values[idx] = this.create(state);
                return 1 /* SlotStatus.Changed */;
            }
        };
    }
    /**
    Returns an extension that enables this field and overrides the
    way it is initialized. Can be useful when you need to provide a
    non-default starting value for the field.
    */
    init(create) {
        return [this, initField.of({ field: this, create })];
    }
    /**
    State field instances can be used as
    [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
    given state.
    */
    get extension() { return this; }
}
const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
function prec(value) {
    return (ext) => new PrecExtension(ext, value);
}
/**
By default extensions are registered in the order they are found
in the flattened form of nested array that was provided.
Individual extension values can be assigned a precedence to
override this. Extensions that do not have a precedence set get
the precedence of the nearest parent with a precedence, or
[`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The
final ordering of extensions is determined by first sorting by
precedence and then by order within each precedence.
*/
const Prec = {
    /**
    The highest precedence level, for extensions that should end up
    near the start of the precedence ordering.
    */
    highest: /*@__PURE__*/prec(Prec_.highest),
    /**
    A higher-than-default precedence, for extensions that should
    come before those with default precedence.
    */
    high: /*@__PURE__*/prec(Prec_.high),
    /**
    The default precedence, which is also used for extensions
    without an explicit precedence.
    */
    default: /*@__PURE__*/prec(Prec_.default),
    /**
    A lower-than-default precedence.
    */
    low: /*@__PURE__*/prec(Prec_.low),
    /**
    The lowest precedence level. Meant for things that should end up
    near the end of the extension order.
    */
    lowest: /*@__PURE__*/prec(Prec_.lowest)
};
class PrecExtension {
    constructor(inner, prec) {
        this.inner = inner;
        this.prec = prec;
    }
}
/**
Extension compartments can be used to make a configuration
dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your
configuration in a compartment, you can later
[replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a
transaction.
*/
class Compartment {
    /**
    Create an instance of this compartment to add to your [state
    configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
    */
    of(ext) { return new CompartmentInstance(this, ext); }
    /**
    Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
    reconfigures this compartment.
    */
    reconfigure(content) {
        return Compartment.reconfigure.of({ compartment: this, extension: content });
    }
    /**
    Get the current content of the compartment in the state, or
    `undefined` if it isn't present.
    */
    get(state) {
        return state.config.compartments.get(this);
    }
}
class CompartmentInstance {
    constructor(compartment, inner) {
        this.compartment = compartment;
        this.inner = inner;
    }
}
class Configuration {
    constructor(base, compartments, dynamicSlots, address, staticValues, facets) {
        this.base = base;
        this.compartments = compartments;
        this.dynamicSlots = dynamicSlots;
        this.address = address;
        this.staticValues = staticValues;
        this.facets = facets;
        this.statusTemplate = [];
        while (this.statusTemplate.length < dynamicSlots.length)
            this.statusTemplate.push(0 /* SlotStatus.Unresolved */);
    }
    staticFacet(facet) {
        let addr = this.address[facet.id];
        return addr == null ? facet.default : this.staticValues[addr >> 1];
    }
    static resolve(base, compartments, oldState) {
        let fields = [];
        let facets = Object.create(null);
        let newCompartments = new Map();
        for (let ext of flatten(base, compartments, newCompartments)) {
            if (ext instanceof dist_StateField)
                fields.push(ext);
            else
                (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
        }
        let address = Object.create(null);
        let staticValues = [];
        let dynamicSlots = [];
        for (let field of fields) {
            address[field.id] = dynamicSlots.length << 1;
            dynamicSlots.push(a => field.slot(a));
        }
        let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
        for (let id in facets) {
            let providers = facets[id], facet = providers[0].facet;
            let oldProviders = oldFacets && oldFacets[id] || [];
            if (providers.every(p => p.type == 0 /* Provider.Static */)) {
                address[facet.id] = (staticValues.length << 1) | 1;
                if (sameArray(oldProviders, providers)) {
                    staticValues.push(oldState.facet(facet));
                }
                else {
                    let value = facet.combine(providers.map(p => p.value));
                    staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
                }
            }
            else {
                for (let p of providers) {
                    if (p.type == 0 /* Provider.Static */) {
                        address[p.id] = (staticValues.length << 1) | 1;
                        staticValues.push(p.value);
                    }
                    else {
                        address[p.id] = dynamicSlots.length << 1;
                        dynamicSlots.push(a => p.dynamicSlot(a));
                    }
                }
                address[facet.id] = dynamicSlots.length << 1;
                dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));
            }
        }
        let dynamic = dynamicSlots.map(f => f(address));
        return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);
    }
}
function flatten(extension, compartments, newCompartments) {
    let result = [[], [], [], [], []];
    let seen = new Map();
    function inner(ext, prec) {
        let known = seen.get(ext);
        if (known != null) {
            if (known <= prec)
                return;
            let found = result[known].indexOf(ext);
            if (found > -1)
                result[known].splice(found, 1);
            if (ext instanceof CompartmentInstance)
                newCompartments.delete(ext.compartment);
        }
        seen.set(ext, prec);
        if (Array.isArray(ext)) {
            for (let e of ext)
                inner(e, prec);
        }
        else if (ext instanceof CompartmentInstance) {
            if (newCompartments.has(ext.compartment))
                throw new RangeError(`Duplicate use of compartment in extensions`);
            let content = compartments.get(ext.compartment) || ext.inner;
            newCompartments.set(ext.compartment, content);
            inner(content, prec);
        }
        else if (ext instanceof PrecExtension) {
            inner(ext.inner, ext.prec);
        }
        else if (ext instanceof dist_StateField) {
            result[prec].push(ext);
            if (ext.provides)
                inner(ext.provides, prec);
        }
        else if (ext instanceof FacetProvider) {
            result[prec].push(ext);
            if (ext.facet.extensions)
                inner(ext.facet.extensions, Prec_.default);
        }
        else {
            let content = ext.extension;
            if (!content)
                throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
            inner(content, prec);
        }
    }
    inner(extension, Prec_.default);
    return result.reduce((a, b) => a.concat(b));
}
function ensureAddr(state, addr) {
    if (addr & 1)
        return 2 /* SlotStatus.Computed */;
    let idx = addr >> 1;
    let status = state.status[idx];
    if (status == 4 /* SlotStatus.Computing */)
        throw new Error("Cyclic dependency between fields and/or facets");
    if (status & 2 /* SlotStatus.Computed */)
        return status;
    state.status[idx] = 4 /* SlotStatus.Computing */;
    let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
    return state.status[idx] = 2 /* SlotStatus.Computed */ | changed;
}
function getAddr(state, addr) {
    return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
}

const languageData = /*@__PURE__*/Facet.define();
const allowMultipleSelections = /*@__PURE__*/Facet.define({
    combine: values => values.some(v => v),
    static: true
});
const lineSeparator = /*@__PURE__*/Facet.define({
    combine: values => values.length ? values[0] : undefined,
    static: true
});
const changeFilter = /*@__PURE__*/Facet.define();
const transactionFilter = /*@__PURE__*/Facet.define();
const transactionExtender = /*@__PURE__*/Facet.define();
const readOnly = /*@__PURE__*/Facet.define({
    combine: values => values.length ? values[0] : false
});

/**
Annotations are tagged values that are used to add metadata to
transactions in an extensible way. They should be used to model
things that effect the entire transaction (such as its [time
stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its
[origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen
_alongside_ the other changes made by the transaction, [state
effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.
*/
class Annotation {
    /**
    @internal
    */
    constructor(
    /**
    The annotation type.
    */
    type, 
    /**
    The value of this annotation.
    */
    value) {
        this.type = type;
        this.value = value;
    }
    /**
    Define a new type of annotation.
    */
    static define() { return new AnnotationType(); }
}
/**
Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).
*/
class AnnotationType {
    /**
    Create an instance of this annotation.
    */
    of(value) { return new Annotation(this, value); }
}
/**
Representation of a type of state effect. Defined with
[`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).
*/
class StateEffectType {
    /**
    @internal
    */
    constructor(
    // The `any` types in these function types are there to work
    // around TypeScript issue #37631, where the type guard on
    // `StateEffect.is` mysteriously stops working when these properly
    // have type `Value`.
    /**
    @internal
    */
    map) {
        this.map = map;
    }
    /**
    Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
    type.
    */
    of(value) { return new dist_StateEffect(this, value); }
}
/**
State effects can be used to represent additional effects
associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They
are often useful to model changes to custom [state
fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in
document or selection changes.
*/
class dist_StateEffect {
    /**
    @internal
    */
    constructor(
    /**
    @internal
    */
    type, 
    /**
    The value of this effect.
    */
    value) {
        this.type = type;
        this.value = value;
    }
    /**
    Map this effect through a position mapping. Will return
    `undefined` when that ends up deleting the effect.
    */
    map(mapping) {
        let mapped = this.type.map(this.value, mapping);
        return mapped === undefined ? undefined : mapped == this.value ? this : new dist_StateEffect(this.type, mapped);
    }
    /**
    Tells you whether this effect object is of a given
    [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
    */
    is(type) { return this.type == type; }
    /**
    Define a new effect type. The type parameter indicates the type
    of values that his effect holds. It should be a type that
    doesn't include `undefined`, since that is used in
    [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
    removed.
    */
    static define(spec = {}) {
        return new StateEffectType(spec.map || (v => v));
    }
    /**
    Map an array of effects through a change set.
    */
    static mapEffects(effects, mapping) {
        if (!effects.length)
            return effects;
        let result = [];
        for (let effect of effects) {
            let mapped = effect.map(mapping);
            if (mapped)
                result.push(mapped);
        }
        return result;
    }
}
/**
This effect can be used to reconfigure the root extensions of
the editor. Doing this will discard any extensions
[appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset
the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)
compartments.
*/
dist_StateEffect.reconfigure = /*@__PURE__*/dist_StateEffect.define();
/**
Append extensions to the top-level configuration of the editor.
*/
dist_StateEffect.appendConfig = /*@__PURE__*/dist_StateEffect.define();
/**
Changes to the editor state are grouped into transactions.
Typically, a user action creates a single transaction, which may
contain any number of document changes, may change the selection,
or have other effects. Create a transaction by calling
[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately
dispatch one by calling
[`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).
*/
class Transaction {
    constructor(
    /**
    The state from which the transaction starts.
    */
    startState, 
    /**
    The document changes made by this transaction.
    */
    changes, 
    /**
    The selection set by this transaction, or undefined if it
    doesn't explicitly set a selection.
    */
    selection, 
    /**
    The effects added to the transaction.
    */
    effects, 
    /**
    @internal
    */
    annotations, 
    /**
    Whether the selection should be scrolled into view after this
    transaction is dispatched.
    */
    scrollIntoView) {
        this.startState = startState;
        this.changes = changes;
        this.selection = selection;
        this.effects = effects;
        this.annotations = annotations;
        this.scrollIntoView = scrollIntoView;
        /**
        @internal
        */
        this._doc = null;
        /**
        @internal
        */
        this._state = null;
        if (selection)
            checkSelection(selection, changes.newLength);
        if (!annotations.some((a) => a.type == Transaction.time))
            this.annotations = annotations.concat(Transaction.time.of(Date.now()));
    }
    /**
    @internal
    */
    static create(startState, changes, selection, effects, annotations, scrollIntoView) {
        return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView);
    }
    /**
    The new document produced by the transaction. Contrary to
    [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
    force the entire new state to be computed right away, so it is
    recommended that [transaction
    filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
    when they need to look at the new document.
    */
    get newDoc() {
        return this._doc || (this._doc = this.changes.apply(this.startState.doc));
    }
    /**
    The new selection produced by the transaction. If
    [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
    this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
    current selection through the changes made by the transaction.
    */
    get newSelection() {
        return this.selection || this.startState.selection.map(this.changes);
    }
    /**
    The new state created by the transaction. Computed on demand
    (but retained for subsequent access), so it is recommended not to
    access it in [transaction
    filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
    */
    get state() {
        if (!this._state)
            this.startState.applyTransaction(this);
        return this._state;
    }
    /**
    Get the value of the given annotation type, if any.
    */
    annotation(type) {
        for (let ann of this.annotations)
            if (ann.type == type)
                return ann.value;
        return undefined;
    }
    /**
    Indicates whether the transaction changed the document.
    */
    get docChanged() { return !this.changes.empty; }
    /**
    Indicates whether this transaction reconfigures the state
    (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
    with a top-level configuration
    [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
    */
    get reconfigured() { return this.startState.config != this.state.config; }
    /**
    Returns true if the transaction has a [user
    event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
    or more specific than `event`. For example, if the transaction
    has `"select.pointer"` as user event, `"select"` and
    `"select.pointer"` will match it.
    */
    isUserEvent(event) {
        let e = this.annotation(Transaction.userEvent);
        return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
    }
}
/**
Annotation used to store transaction timestamps. Automatically
added to every transaction, holding `Date.now()`.
*/
Transaction.time = /*@__PURE__*/Annotation.define();
/**
Annotation used to associate a transaction with a user interface
event. Holds a string identifying the event, using a
dot-separated format to support attaching more specific
information. The events used by the core libraries are:

 - `"input"` when content is entered
   - `"input.type"` for typed input
     - `"input.type.compose"` for composition
   - `"input.paste"` for pasted input
   - `"input.drop"` when adding content with drag-and-drop
   - `"input.complete"` when autocompleting
 - `"delete"` when the user deletes content
   - `"delete.selection"` when deleting the selection
   - `"delete.forward"` when deleting forward from the selection
   - `"delete.backward"` when deleting backward from the selection
   - `"delete.cut"` when cutting to the clipboard
 - `"move"` when content is moved
   - `"move.drop"` when content is moved within the editor through drag-and-drop
 - `"select"` when explicitly changing the selection
   - `"select.pointer"` when selecting with a mouse or other pointing device
 - `"undo"` and `"redo"` for history actions

Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check
whether the annotation matches a given event.
*/
Transaction.userEvent = /*@__PURE__*/Annotation.define();
/**
Annotation indicating whether a transaction should be added to
the undo history or not.
*/
Transaction.addToHistory = /*@__PURE__*/Annotation.define();
/**
Annotation indicating (when present and true) that a transaction
represents a change made by some other actor, not the user. This
is used, for example, to tag other people's changes in
collaborative editing.
*/
Transaction.remote = /*@__PURE__*/Annotation.define();
function joinRanges(a, b) {
    let result = [];
    for (let iA = 0, iB = 0;;) {
        let from, to;
        if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
            from = a[iA++];
            to = a[iA++];
        }
        else if (iB < b.length) {
            from = b[iB++];
            to = b[iB++];
        }
        else
            return result;
        if (!result.length || result[result.length - 1] < from)
            result.push(from, to);
        else if (result[result.length - 1] < to)
            result[result.length - 1] = to;
    }
}
function mergeTransaction(a, b, sequential) {
    var _a;
    let mapForA, mapForB, changes;
    if (sequential) {
        mapForA = b.changes;
        mapForB = ChangeSet.empty(b.changes.length);
        changes = a.changes.compose(b.changes);
    }
    else {
        mapForA = b.changes.map(a.changes);
        mapForB = a.changes.mapDesc(b.changes, true);
        changes = a.changes.compose(mapForA);
    }
    return {
        changes,
        selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),
        effects: dist_StateEffect.mapEffects(a.effects, mapForA).concat(dist_StateEffect.mapEffects(b.effects, mapForB)),
        annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
        scrollIntoView: a.scrollIntoView || b.scrollIntoView
    };
}
function resolveTransactionInner(state, spec, docSize) {
    let sel = spec.selection, annotations = asArray(spec.annotations);
    if (spec.userEvent)
        annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
    return {
        changes: spec.changes instanceof ChangeSet ? spec.changes
            : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
        selection: sel && (sel instanceof dist_EditorSelection ? sel : dist_EditorSelection.single(sel.anchor, sel.head)),
        effects: asArray(spec.effects),
        annotations,
        scrollIntoView: !!spec.scrollIntoView
    };
}
function resolveTransaction(state, specs, filter) {
    let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
    if (specs.length && specs[0].filter === false)
        filter = false;
    for (let i = 1; i < specs.length; i++) {
        if (specs[i].filter === false)
            filter = false;
        let seq = !!specs[i].sequential;
        s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);
    }
    let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
    return extendTransaction(filter ? filterTransaction(tr) : tr);
}
// Finish a transaction by applying filters if necessary.
function filterTransaction(tr) {
    let state = tr.startState;
    // Change filters
    let result = true;
    for (let filter of state.facet(changeFilter)) {
        let value = filter(tr);
        if (value === false) {
            result = false;
            break;
        }
        if (Array.isArray(value))
            result = result === true ? value : joinRanges(result, value);
    }
    if (result !== true) {
        let changes, back;
        if (result === false) {
            back = tr.changes.invertedDesc;
            changes = ChangeSet.empty(state.doc.length);
        }
        else {
            let filtered = tr.changes.filter(result);
            changes = filtered.changes;
            back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
        }
        tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), dist_StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
    }
    // Transaction filters
    let filters = state.facet(transactionFilter);
    for (let i = filters.length - 1; i >= 0; i--) {
        let filtered = filters[i](tr);
        if (filtered instanceof Transaction)
            tr = filtered;
        else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
            tr = filtered[0];
        else
            tr = resolveTransaction(state, asArray(filtered), false);
    }
    return tr;
}
function extendTransaction(tr) {
    let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;
    for (let i = extenders.length - 1; i >= 0; i--) {
        let extension = extenders[i](tr);
        if (extension && Object.keys(extension).length)
            spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);
    }
    return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
}
const none = [];
function asArray(value) {
    return value == null ? none : Array.isArray(value) ? value : [value];
}

/**
The categories produced by a [character
categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
do things like selecting by word.
*/
var dist_CharCategory = /*@__PURE__*/(function (CharCategory) {
    /**
    Word characters.
    */
    CharCategory[CharCategory["Word"] = 0] = "Word";
    /**
    Whitespace.
    */
    CharCategory[CharCategory["Space"] = 1] = "Space";
    /**
    Anything else.
    */
    CharCategory[CharCategory["Other"] = 2] = "Other";
return CharCategory})(dist_CharCategory || (dist_CharCategory = {}));
const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
let wordChar;
try {
    wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
}
catch (_) { }
function hasWordChar(str) {
    if (wordChar)
        return wordChar.test(str);
    for (let i = 0; i < str.length; i++) {
        let ch = str[i];
        if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
            return true;
    }
    return false;
}
function makeCategorizer(wordChars) {
    return (char) => {
        if (!/\S/.test(char))
            return dist_CharCategory.Space;
        if (hasWordChar(char))
            return dist_CharCategory.Word;
        for (let i = 0; i < wordChars.length; i++)
            if (char.indexOf(wordChars[i]) > -1)
                return dist_CharCategory.Word;
        return dist_CharCategory.Other;
    };
}

/**
The editor state class is a persistent (immutable) data structure.
To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a
[transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state
instance, without modifying the original object.

As such, _never_ mutate properties of a state directly. That'll
just break things.
*/
class dist_EditorState {
    constructor(
    /**
    @internal
    */
    config, 
    /**
    The current document.
    */
    doc, 
    /**
    The current selection.
    */
    selection, 
    /**
    @internal
    */
    values, computeSlot, tr) {
        this.config = config;
        this.doc = doc;
        this.selection = selection;
        this.values = values;
        this.status = config.statusTemplate.slice();
        this.computeSlot = computeSlot;
        // Fill in the computed state immediately, so that further queries
        // for it made during the update return this state
        if (tr)
            tr._state = this;
        for (let i = 0; i < this.config.dynamicSlots.length; i++)
            ensureAddr(this, i << 1);
        this.computeSlot = null;
    }
    field(field, require = true) {
        let addr = this.config.address[field.id];
        if (addr == null) {
            if (require)
                throw new RangeError("Field is not present in this state");
            return undefined;
        }
        ensureAddr(this, addr);
        return getAddr(this, addr);
    }
    /**
    Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
    state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
    can be passed. Unless
    [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
    [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
    are assumed to start in the _current_ document (not the document
    produced by previous specs), and its
    [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
    [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
    to the document created by its _own_ changes. The resulting
    transaction contains the combined effect of all the different
    specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
    specs take precedence over earlier ones.
    */
    update(...specs) {
        return resolveTransaction(this, specs, true);
    }
    /**
    @internal
    */
    applyTransaction(tr) {
        let conf = this.config, { base, compartments } = conf;
        for (let effect of tr.effects) {
            if (effect.is(Compartment.reconfigure)) {
                if (conf) {
                    compartments = new Map;
                    conf.compartments.forEach((val, key) => compartments.set(key, val));
                    conf = null;
                }
                compartments.set(effect.value.compartment, effect.value.extension);
            }
            else if (effect.is(dist_StateEffect.reconfigure)) {
                conf = null;
                base = effect.value;
            }
            else if (effect.is(dist_StateEffect.appendConfig)) {
                conf = null;
                base = asArray(base).concat(effect.value);
            }
        }
        let startValues;
        if (!conf) {
            conf = Configuration.resolve(base, compartments, this);
            let intermediateState = new dist_EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
            startValues = intermediateState.values;
        }
        else {
            startValues = tr.startState.values.slice();
        }
        let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();
        new dist_EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr);
    }
    /**
    Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
    replaces every selection range with the given content.
    */
    replaceSelection(text) {
        if (typeof text == "string")
            text = this.toText(text);
        return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },
            range: dist_EditorSelection.cursor(range.from + text.length) }));
    }
    /**
    Create a set of changes and a new selection by running the given
    function for each range in the active selection. The function
    can return an optional set of changes (in the coordinate space
    of the start document), plus an updated range (in the coordinate
    space of the document produced by the call's own changes). This
    method will merge all the changes and ranges into a single
    changeset and selection, and return it as a [transaction
    spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
    [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
    */
    changeByRange(f) {
        let sel = this.selection;
        let result1 = f(sel.ranges[0]);
        let changes = this.changes(result1.changes), ranges = [result1.range];
        let effects = asArray(result1.effects);
        for (let i = 1; i < sel.ranges.length; i++) {
            let result = f(sel.ranges[i]);
            let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
            for (let j = 0; j < i; j++)
                ranges[j] = ranges[j].map(newMapped);
            let mapBy = changes.mapDesc(newChanges, true);
            ranges.push(result.range.map(mapBy));
            changes = changes.compose(newMapped);
            effects = dist_StateEffect.mapEffects(effects, newMapped).concat(dist_StateEffect.mapEffects(asArray(result.effects), mapBy));
        }
        return {
            changes,
            selection: dist_EditorSelection.create(ranges, sel.mainIndex),
            effects
        };
    }
    /**
    Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
    description, taking the state's document length and line
    separator into account.
    */
    changes(spec = []) {
        if (spec instanceof ChangeSet)
            return spec;
        return ChangeSet.of(spec, this.doc.length, this.facet(dist_EditorState.lineSeparator));
    }
    /**
    Using the state's [line
    separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
    [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
    */
    toText(string) {
        return dist_Text.of(string.split(this.facet(dist_EditorState.lineSeparator) || DefaultSplit));
    }
    /**
    Return the given range of the document as a string.
    */
    sliceDoc(from = 0, to = this.doc.length) {
        return this.doc.sliceString(from, to, this.lineBreak);
    }
    /**
    Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
    */
    facet(facet) {
        let addr = this.config.address[facet.id];
        if (addr == null)
            return facet.default;
        ensureAddr(this, addr);
        return getAddr(this, addr);
    }
    /**
    Convert this state to a JSON-serializable object. When custom
    fields should be serialized, you can pass them in as an object
    mapping property names (in the resulting object, which should
    not use `doc` or `selection`) to fields.
    */
    toJSON(fields) {
        let result = {
            doc: this.sliceDoc(),
            selection: this.selection.toJSON()
        };
        if (fields)
            for (let prop in fields) {
                let value = fields[prop];
                if (value instanceof dist_StateField && this.config.address[value.id] != null)
                    result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
            }
        return result;
    }
    /**
    Deserialize a state from its JSON representation. When custom
    fields should be deserialized, pass the same object you passed
    to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
    third argument.
    */
    static fromJSON(json, config = {}, fields) {
        if (!json || typeof json.doc != "string")
            throw new RangeError("Invalid JSON representation for EditorState");
        let fieldInit = [];
        if (fields)
            for (let prop in fields) {
                if (Object.prototype.hasOwnProperty.call(json, prop)) {
                    let field = fields[prop], value = json[prop];
                    fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
                }
            }
        return dist_EditorState.create({
            doc: json.doc,
            selection: dist_EditorSelection.fromJSON(json.selection),
            extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit
        });
    }
    /**
    Create a new state. You'll usually only need this when
    initializing an editor—updated states are created by applying
    transactions.
    */
    static create(config = {}) {
        let configuration = Configuration.resolve(config.extensions || [], new Map);
        let doc = config.doc instanceof dist_Text ? config.doc
            : dist_Text.of((config.doc || "").split(configuration.staticFacet(dist_EditorState.lineSeparator) || DefaultSplit));
        let selection = !config.selection ? dist_EditorSelection.single(0)
            : config.selection instanceof dist_EditorSelection ? config.selection
                : dist_EditorSelection.single(config.selection.anchor, config.selection.head);
        checkSelection(selection, doc.length);
        if (!configuration.staticFacet(allowMultipleSelections))
            selection = selection.asSingle();
        return new dist_EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
    }
    /**
    The size (in columns) of a tab in the document, determined by
    the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
    */
    get tabSize() { return this.facet(dist_EditorState.tabSize); }
    /**
    Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
    string for this state.
    */
    get lineBreak() { return this.facet(dist_EditorState.lineSeparator) || "\n"; }
    /**
    Returns true when the editor is
    [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
    */
    get readOnly() { return this.facet(readOnly); }
    /**
    Look up a translation for the given phrase (via the
    [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
    original string if no translation is found.
    
    If additional arguments are passed, they will be inserted in
    place of markers like `$1` (for the first value) and `$2`, etc.
    A single `$` is equivalent to `$1`, and `$$` will produce a
    literal dollar sign.
    */
    phrase(phrase, ...insert) {
        for (let map of this.facet(dist_EditorState.phrases))
            if (Object.prototype.hasOwnProperty.call(map, phrase)) {
                phrase = map[phrase];
                break;
            }
        if (insert.length)
            phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => {
                if (i == "$")
                    return "$";
                let n = +(i || 1);
                return !n || n > insert.length ? m : insert[n - 1];
            });
        return phrase;
    }
    /**
    Find the values for a given language data field, provided by the
    the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
    
    Examples of language data fields are...
    
    - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
      comment syntax.
    - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
      for providing language-specific completion sources.
    - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
      characters that should be considered part of words in this
      language.
    - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
      bracket closing behavior.
    */
    languageDataAt(name, pos, side = -1) {
        let values = [];
        for (let provider of this.facet(languageData)) {
            for (let result of provider(this, pos, side)) {
                if (Object.prototype.hasOwnProperty.call(result, name))
                    values.push(result[name]);
            }
        }
        return values;
    }
    /**
    Return a function that can categorize strings (expected to
    represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
    into one of:
    
     - Word (contains an alphanumeric character or a character
       explicitly listed in the local language's `"wordChars"`
       language data, which should be a string)
     - Space (contains only whitespace)
     - Other (anything else)
    */
    charCategorizer(at) {
        let chars = this.languageDataAt("wordChars", at);
        return makeCategorizer(chars.length ? chars[0] : "");
    }
    /**
    Find the word at the given position, meaning the range
    containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
    around it. If no word characters are adjacent to the position,
    this returns null.
    */
    wordAt(pos) {
        let { text, from, length } = this.doc.lineAt(pos);
        let cat = this.charCategorizer(pos);
        let start = pos - from, end = pos - from;
        while (start > 0) {
            let prev = dist_findClusterBreak(text, start, false);
            if (cat(text.slice(prev, start)) != dist_CharCategory.Word)
                break;
            start = prev;
        }
        while (end < length) {
            let next = dist_findClusterBreak(text, end);
            if (cat(text.slice(end, next)) != dist_CharCategory.Word)
                break;
            end = next;
        }
        return start == end ? null : dist_EditorSelection.range(start + from, end + from);
    }
}
/**
A facet that, when enabled, causes the editor to allow multiple
ranges to be selected. Be careful though, because by default the
editor relies on the native DOM selection, which cannot handle
multiple selections. An extension like
[`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make
secondary selections visible to the user.
*/
dist_EditorState.allowMultipleSelections = allowMultipleSelections;
/**
Configures the tab size to use in this state. The first
(highest-precedence) value of the facet is used. If no value is
given, this defaults to 4.
*/
dist_EditorState.tabSize = /*@__PURE__*/Facet.define({
    combine: values => values.length ? values[0] : 4
});
/**
The line separator to use. By default, any of `"\n"`, `"\r\n"`
and `"\r"` is treated as a separator when splitting lines, and
lines are joined with `"\n"`.

When you configure a value here, only that precise separator
will be used, allowing you to round-trip documents through the
editor without normalizing line separators.
*/
dist_EditorState.lineSeparator = lineSeparator;
/**
This facet controls the value of the
[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is
consulted by commands and extensions that implement editing
functionality to determine whether they should apply. It
defaults to false, but when its highest-precedence value is
`true`, such functionality disables itself.

Not to be confused with
[`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which
controls whether the editor's DOM is set to be editable (and
thus focusable).
*/
dist_EditorState.readOnly = readOnly;
/**
Registers translation phrases. The
[`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through
all objects registered with this facet to find translations for
its argument.
*/
dist_EditorState.phrases = /*@__PURE__*/Facet.define({
    compare(a, b) {
        let kA = Object.keys(a), kB = Object.keys(b);
        return kA.length == kB.length && kA.every(k => a[k] == b[k]);
    }
});
/**
A facet used to register [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.
*/
dist_EditorState.languageData = languageData;
/**
Facet used to register change filters, which are called for each
transaction (unless explicitly
[disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress
part of the transaction's changes.

Such a function can return `true` to indicate that it doesn't
want to do anything, `false` to completely stop the changes in
the transaction, or a set of ranges in which changes should be
suppressed. Such ranges are represented as an array of numbers,
with each pair of two numbers indicating the start and end of a
range. So for example `[10, 20, 100, 110]` suppresses changes
between 10 and 20, and between 100 and 110.
*/
dist_EditorState.changeFilter = changeFilter;
/**
Facet used to register a hook that gets a chance to update or
replace transaction specs before they are applied. This will
only be applied for transactions that don't have
[`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You
can either return a single transaction spec (possibly the input
transaction), or an array of specs (which will be combined in
the same way as the arguments to
[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).

When possible, it is recommended to avoid accessing
[`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,
since it will force creation of a state that will then be
discarded again, if the transaction is actually filtered.

(This functionality should be used with care. Indiscriminately
modifying transaction is likely to break something or degrade
the user experience.)
*/
dist_EditorState.transactionFilter = transactionFilter;
/**
This is a more limited form of
[`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),
which can only add
[annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and
[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type
of filter runs even if the transaction has disabled regular
[filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable
for effects that don't need to touch the changes or selection,
but do want to process every transaction.

Extenders run _after_ filters, when both are present.
*/
dist_EditorState.transactionExtender = transactionExtender;
Compartment.reconfigure = /*@__PURE__*/dist_StateEffect.define();

/**
Utility function for combining behaviors to fill in a config
object from an array of provided configs. `defaults` should hold
default values for all optional fields in `Config`.

The function will, by default, error
when a field gets two values that aren't `===`-equal, but you can
provide combine functions per field to do something else.
*/
function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that
combine = {}) {
    let result = {};
    for (let config of configs)
        for (let key of Object.keys(config)) {
            let value = config[key], current = result[key];
            if (current === undefined)
                result[key] = value;
            else if (current === value || value === undefined) ; // No conflict
            else if (Object.hasOwnProperty.call(combine, key))
                result[key] = combine[key](current, value);
            else
                throw new Error("Config merge conflict for field " + key);
        }
    for (let key in defaults)
        if (result[key] === undefined)
            result[key] = defaults[key];
    return result;
}

/**
Each range is associated with a value, which must inherit from
this class.
*/
class RangeValue {
    /**
    Compare this value with another value. Used when comparing
    rangesets. The default implementation compares by identity.
    Unless you are only creating a fixed number of unique instances
    of your value type, it is a good idea to implement this
    properly.
    */
    eq(other) { return this == other; }
    /**
    Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
    */
    range(from, to = from) { return Range.create(from, to, this); }
}
RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
RangeValue.prototype.point = false;
RangeValue.prototype.mapMode = dist_MapMode.TrackDel;
function cmpVal(a, b) {
    return a == b || a.constructor == b.constructor && a.eq(b);
}
/**
A range associates a value with a range of positions.
*/
class Range {
    constructor(
    /**
    The range's start position.
    */
    from, 
    /**
    Its end position.
    */
    to, 
    /**
    The value associated with this range.
    */
    value) {
        this.from = from;
        this.to = to;
        this.value = value;
    }
    /**
    @internal
    */
    static create(from, to, value) {
        return new Range(from, to, value);
    }
}
function cmpRange(a, b) {
    return a.from - b.from || a.value.startSide - b.value.startSide;
}
class Chunk {
    constructor(from, to, value, 
    // Chunks are marked with the largest point that occurs
    // in them (or -1 for no points), so that scans that are
    // only interested in points (such as the
    // heightmap-related logic) can skip range-only chunks.
    maxPoint) {
        this.from = from;
        this.to = to;
        this.value = value;
        this.maxPoint = maxPoint;
    }
    get length() { return this.to[this.to.length - 1]; }
    // Find the index of the given position and side. Use the ranges'
    // `from` pos when `end == false`, `to` when `end == true`.
    findIndex(pos, side, end, startAt = 0) {
        let arr = end ? this.to : this.from;
        for (let lo = startAt, hi = arr.length;;) {
            if (lo == hi)
                return lo;
            let mid = (lo + hi) >> 1;
            let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
            if (mid == lo)
                return diff >= 0 ? lo : hi;
            if (diff >= 0)
                hi = mid;
            else
                lo = mid + 1;
        }
    }
    between(offset, from, to, f) {
        for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++)
            if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)
                return false;
    }
    map(offset, changes) {
        let value = [], from = [], to = [], newPos = -1, maxPoint = -1;
        for (let i = 0; i < this.value.length; i++) {
            let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;
            if (curFrom == curTo) {
                let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
                if (mapped == null)
                    continue;
                newFrom = newTo = mapped;
                if (val.startSide != val.endSide) {
                    newTo = changes.mapPos(curFrom, val.endSide);
                    if (newTo < newFrom)
                        continue;
                }
            }
            else {
                newFrom = changes.mapPos(curFrom, val.startSide);
                newTo = changes.mapPos(curTo, val.endSide);
                if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
                    continue;
            }
            if ((newTo - newFrom || val.endSide - val.startSide) < 0)
                continue;
            if (newPos < 0)
                newPos = newFrom;
            if (val.point)
                maxPoint = Math.max(maxPoint, newTo - newFrom);
            value.push(val);
            from.push(newFrom - newPos);
            to.push(newTo - newPos);
        }
        return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };
    }
}
/**
A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a
way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and
[update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data
structure.
*/
class dist_RangeSet {
    constructor(
    /**
    @internal
    */
    chunkPos, 
    /**
    @internal
    */
    chunk, 
    /**
    @internal
    */
    nextLayer, 
    /**
    @internal
    */
    maxPoint) {
        this.chunkPos = chunkPos;
        this.chunk = chunk;
        this.nextLayer = nextLayer;
        this.maxPoint = maxPoint;
    }
    /**
    @internal
    */
    static create(chunkPos, chunk, nextLayer, maxPoint) {
        return new dist_RangeSet(chunkPos, chunk, nextLayer, maxPoint);
    }
    /**
    @internal
    */
    get length() {
        let last = this.chunk.length - 1;
        return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
    }
    /**
    The number of ranges in the set.
    */
    get size() {
        if (this.isEmpty)
            return 0;
        let size = this.nextLayer.size;
        for (let chunk of this.chunk)
            size += chunk.value.length;
        return size;
    }
    /**
    @internal
    */
    chunkEnd(index) {
        return this.chunkPos[index] + this.chunk[index].length;
    }
    /**
    Update the range set, optionally adding new ranges or filtering
    out existing ones.
    
    (Note: The type parameter is just there as a kludge to work
    around TypeScript variance issues that prevented `RangeSet<X>`
    from being a subtype of `RangeSet<Y>` when `X` is a subtype of
    `Y`.)
    */
    update(updateSpec) {
        let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
        let filter = updateSpec.filter;
        if (add.length == 0 && !filter)
            return this;
        if (sort)
            add = add.slice().sort(cmpRange);
        if (this.isEmpty)
            return add.length ? dist_RangeSet.of(add) : this;
        let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];
        let builder = new RangeSetBuilder();
        while (cur.value || i < add.length) {
            if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) {
                let range = add[i++];
                if (!builder.addInner(range.from, range.to, range.value))
                    spill.push(range);
            }
            else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length &&
                (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) &&
                (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) &&
                builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) {
                cur.nextChunk();
            }
            else {
                if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {
                    if (!builder.addInner(cur.from, cur.to, cur.value))
                        spill.push(Range.create(cur.from, cur.to, cur.value));
                }
                cur.next();
            }
        }
        return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? dist_RangeSet.empty
            : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));
    }
    /**
    Map this range set through a set of changes, return the new set.
    */
    map(changes) {
        if (changes.empty || this.isEmpty)
            return this;
        let chunks = [], chunkPos = [], maxPoint = -1;
        for (let i = 0; i < this.chunk.length; i++) {
            let start = this.chunkPos[i], chunk = this.chunk[i];
            let touch = changes.touchesRange(start, start + chunk.length);
            if (touch === false) {
                maxPoint = Math.max(maxPoint, chunk.maxPoint);
                chunks.push(chunk);
                chunkPos.push(changes.mapPos(start));
            }
            else if (touch === true) {
                let { mapped, pos } = chunk.map(start, changes);
                if (mapped) {
                    maxPoint = Math.max(maxPoint, mapped.maxPoint);
                    chunks.push(mapped);
                    chunkPos.push(pos);
                }
            }
        }
        let next = this.nextLayer.map(changes);
        return chunks.length == 0 ? next : new dist_RangeSet(chunkPos, chunks, next || dist_RangeSet.empty, maxPoint);
    }
    /**
    Iterate over the ranges that touch the region `from` to `to`,
    calling `f` for each. There is no guarantee that the ranges will
    be reported in any specific order. When the callback returns
    `false`, iteration stops.
    */
    between(from, to, f) {
        if (this.isEmpty)
            return;
        for (let i = 0; i < this.chunk.length; i++) {
            let start = this.chunkPos[i], chunk = this.chunk[i];
            if (to >= start && from <= start + chunk.length &&
                chunk.between(start, from - start, to - start, f) === false)
                return;
        }
        this.nextLayer.between(from, to, f);
    }
    /**
    Iterate over the ranges in this set, in order, including all
    ranges that end at or after `from`.
    */
    iter(from = 0) {
        return HeapCursor.from([this]).goto(from);
    }
    /**
    @internal
    */
    get isEmpty() { return this.nextLayer == this; }
    /**
    Iterate over the ranges in a collection of sets, in order,
    starting from `from`.
    */
    static iter(sets, from = 0) {
        return HeapCursor.from(sets).goto(from);
    }
    /**
    Iterate over two groups of sets, calling methods on `comparator`
    to notify it of possible differences.
    */
    static compare(oldSets, newSets, 
    /**
    This indicates how the underlying data changed between these
    ranges, and is needed to synchronize the iteration.
    */
    textDiff, comparator, 
    /**
    Can be used to ignore all non-point ranges, and points below
    the given size. When -1, all ranges are compared.
    */
    minPointSize = -1) {
        let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
        let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
        let sharedChunks = findSharedChunks(a, b, textDiff);
        let sideA = new SpanCursor(a, sharedChunks, minPointSize);
        let sideB = new SpanCursor(b, sharedChunks, minPointSize);
        textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
        if (textDiff.empty && textDiff.length == 0)
            compare(sideA, 0, sideB, 0, 0, comparator);
    }
    /**
    Compare the contents of two groups of range sets, returning true
    if they are equivalent in the given range.
    */
    static eq(oldSets, newSets, from = 0, to) {
        if (to == null)
            to = 1000000000 /* C.Far */ - 1;
        let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);
        let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);
        if (a.length != b.length)
            return false;
        if (!a.length)
            return true;
        let sharedChunks = findSharedChunks(a, b);
        let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);
        for (;;) {
            if (sideA.to != sideB.to ||
                !sameValues(sideA.active, sideB.active) ||
                sideA.point && (!sideB.point || !cmpVal(sideA.point, sideB.point)))
                return false;
            if (sideA.to > to)
                return true;
            sideA.next();
            sideB.next();
        }
    }
    /**
    Iterate over a group of range sets at the same time, notifying
    the iterator about the ranges covering every given piece of
    content. Returns the open count (see
    [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
    of the iteration.
    */
    static spans(sets, from, to, iterator, 
    /**
    When given and greater than -1, only points of at least this
    size are taken into account.
    */
    minPointSize = -1) {
        let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
        let openRanges = cursor.openStart;
        for (;;) {
            let curTo = Math.min(cursor.to, to);
            if (cursor.point) {
                let active = cursor.activeForPoint(cursor.to);
                let openCount = cursor.pointFrom < from ? active.length + 1
                    : cursor.point.startSide < 0 ? active.length
                        : Math.min(active.length, openRanges);
                iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);
                openRanges = Math.min(cursor.openEnd(curTo), active.length);
            }
            else if (curTo > pos) {
                iterator.span(pos, curTo, cursor.active, openRanges);
                openRanges = cursor.openEnd(curTo);
            }
            if (cursor.to > to)
                return openRanges + (cursor.point && cursor.to > to ? 1 : 0);
            pos = cursor.to;
            cursor.next();
        }
    }
    /**
    Create a range set for the given range or array of ranges. By
    default, this expects the ranges to be _sorted_ (by start
    position and, if two start at the same position,
    `value.startSide`). You can pass `true` as second argument to
    cause the method to sort them.
    */
    static of(ranges, sort = false) {
        let build = new RangeSetBuilder();
        for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges)
            build.add(range.from, range.to, range.value);
        return build.finish();
    }
    /**
    Join an array of range sets into a single set.
    */
    static join(sets) {
        if (!sets.length)
            return dist_RangeSet.empty;
        let result = sets[sets.length - 1];
        for (let i = sets.length - 2; i >= 0; i--) {
            for (let layer = sets[i]; layer != dist_RangeSet.empty; layer = layer.nextLayer)
                result = new dist_RangeSet(layer.chunkPos, layer.chunk, result, Math.max(layer.maxPoint, result.maxPoint));
        }
        return result;
    }
}
/**
The empty set of ranges.
*/
dist_RangeSet.empty = /*@__PURE__*/new dist_RangeSet([], [], null, -1);
function lazySort(ranges) {
    if (ranges.length > 1)
        for (let prev = ranges[0], i = 1; i < ranges.length; i++) {
            let cur = ranges[i];
            if (cmpRange(prev, cur) > 0)
                return ranges.slice().sort(cmpRange);
            prev = cur;
        }
    return ranges;
}
dist_RangeSet.empty.nextLayer = dist_RangeSet.empty;
/**
A range set builder is a data structure that helps build up a
[range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating
an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.
*/
class RangeSetBuilder {
    finishChunk(newArrays) {
        this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
        this.chunkPos.push(this.chunkStart);
        this.chunkStart = -1;
        this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
        this.maxPoint = -1;
        if (newArrays) {
            this.from = [];
            this.to = [];
            this.value = [];
        }
    }
    /**
    Create an empty builder.
    */
    constructor() {
        this.chunks = [];
        this.chunkPos = [];
        this.chunkStart = -1;
        this.last = null;
        this.lastFrom = -1000000000 /* C.Far */;
        this.lastTo = -1000000000 /* C.Far */;
        this.from = [];
        this.to = [];
        this.value = [];
        this.maxPoint = -1;
        this.setMaxPoint = -1;
        this.nextLayer = null;
    }
    /**
    Add a range. Ranges should be added in sorted (by `from` and
    `value.startSide`) order.
    */
    add(from, to, value) {
        if (!this.addInner(from, to, value))
            (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value);
    }
    /**
    @internal
    */
    addInner(from, to, value) {
        let diff = from - this.lastTo || value.startSide - this.last.endSide;
        if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
            throw new Error("Ranges must be added sorted by `from` position and `startSide`");
        if (diff < 0)
            return false;
        if (this.from.length == 250 /* C.ChunkSize */)
            this.finishChunk(true);
        if (this.chunkStart < 0)
            this.chunkStart = from;
        this.from.push(from - this.chunkStart);
        this.to.push(to - this.chunkStart);
        this.last = value;
        this.lastFrom = from;
        this.lastTo = to;
        this.value.push(value);
        if (value.point)
            this.maxPoint = Math.max(this.maxPoint, to - from);
        return true;
    }
    /**
    @internal
    */
    addChunk(from, chunk) {
        if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
            return false;
        if (this.from.length)
            this.finishChunk(true);
        this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
        this.chunks.push(chunk);
        this.chunkPos.push(from);
        let last = chunk.value.length - 1;
        this.last = chunk.value[last];
        this.lastFrom = chunk.from[last] + from;
        this.lastTo = chunk.to[last] + from;
        return true;
    }
    /**
    Finish the range set. Returns the new set. The builder can't be
    used anymore after this has been called.
    */
    finish() { return this.finishInner(dist_RangeSet.empty); }
    /**
    @internal
    */
    finishInner(next) {
        if (this.from.length)
            this.finishChunk(false);
        if (this.chunks.length == 0)
            return next;
        let result = dist_RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
        this.from = null; // Make sure further `add` calls produce errors
        return result;
    }
}
function findSharedChunks(a, b, textDiff) {
    let inA = new Map();
    for (let set of a)
        for (let i = 0; i < set.chunk.length; i++)
            if (set.chunk[i].maxPoint <= 0)
                inA.set(set.chunk[i], set.chunkPos[i]);
    let shared = new Set();
    for (let set of b)
        for (let i = 0; i < set.chunk.length; i++) {
            let known = inA.get(set.chunk[i]);
            if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] &&
                !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length)))
                shared.add(set.chunk[i]);
        }
    return shared;
}
class LayerCursor {
    constructor(layer, skip, minPoint, rank = 0) {
        this.layer = layer;
        this.skip = skip;
        this.minPoint = minPoint;
        this.rank = rank;
    }
    get startSide() { return this.value ? this.value.startSide : 0; }
    get endSide() { return this.value ? this.value.endSide : 0; }
    goto(pos, side = -1000000000 /* C.Far */) {
        this.chunkIndex = this.rangeIndex = 0;
        this.gotoInner(pos, side, false);
        return this;
    }
    gotoInner(pos, side, forward) {
        while (this.chunkIndex < this.layer.chunk.length) {
            let next = this.layer.chunk[this.chunkIndex];
            if (!(this.skip && this.skip.has(next) ||
                this.layer.chunkEnd(this.chunkIndex) < pos ||
                next.maxPoint < this.minPoint))
                break;
            this.chunkIndex++;
            forward = false;
        }
        if (this.chunkIndex < this.layer.chunk.length) {
            let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
            if (!forward || this.rangeIndex < rangeIndex)
                this.setRangeIndex(rangeIndex);
        }
        this.next();
    }
    forward(pos, side) {
        if ((this.to - pos || this.endSide - side) < 0)
            this.gotoInner(pos, side, true);
    }
    next() {
        for (;;) {
            if (this.chunkIndex == this.layer.chunk.length) {
                this.from = this.to = 1000000000 /* C.Far */;
                this.value = null;
                break;
            }
            else {
                let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
                let from = chunkPos + chunk.from[this.rangeIndex];
                this.from = from;
                this.to = chunkPos + chunk.to[this.rangeIndex];
                this.value = chunk.value[this.rangeIndex];
                this.setRangeIndex(this.rangeIndex + 1);
                if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
                    break;
            }
        }
    }
    setRangeIndex(index) {
        if (index == this.layer.chunk[this.chunkIndex].value.length) {
            this.chunkIndex++;
            if (this.skip) {
                while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
                    this.chunkIndex++;
            }
            this.rangeIndex = 0;
        }
        else {
            this.rangeIndex = index;
        }
    }
    nextChunk() {
        this.chunkIndex++;
        this.rangeIndex = 0;
        this.next();
    }
    compare(other) {
        return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank ||
            this.to - other.to || this.endSide - other.endSide;
    }
}
class HeapCursor {
    constructor(heap) {
        this.heap = heap;
    }
    static from(sets, skip = null, minPoint = -1) {
        let heap = [];
        for (let i = 0; i < sets.length; i++) {
            for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) {
                if (cur.maxPoint >= minPoint)
                    heap.push(new LayerCursor(cur, skip, minPoint, i));
            }
        }
        return heap.length == 1 ? heap[0] : new HeapCursor(heap);
    }
    get startSide() { return this.value ? this.value.startSide : 0; }
    goto(pos, side = -1000000000 /* C.Far */) {
        for (let cur of this.heap)
            cur.goto(pos, side);
        for (let i = this.heap.length >> 1; i >= 0; i--)
            heapBubble(this.heap, i);
        this.next();
        return this;
    }
    forward(pos, side) {
        for (let cur of this.heap)
            cur.forward(pos, side);
        for (let i = this.heap.length >> 1; i >= 0; i--)
            heapBubble(this.heap, i);
        if ((this.to - pos || this.value.endSide - side) < 0)
            this.next();
    }
    next() {
        if (this.heap.length == 0) {
            this.from = this.to = 1000000000 /* C.Far */;
            this.value = null;
            this.rank = -1;
        }
        else {
            let top = this.heap[0];
            this.from = top.from;
            this.to = top.to;
            this.value = top.value;
            this.rank = top.rank;
            if (top.value)
                top.next();
            heapBubble(this.heap, 0);
        }
    }
}
function heapBubble(heap, index) {
    for (let cur = heap[index];;) {
        let childIndex = (index << 1) + 1;
        if (childIndex >= heap.length)
            break;
        let child = heap[childIndex];
        if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
            child = heap[childIndex + 1];
            childIndex++;
        }
        if (cur.compare(child) < 0)
            break;
        heap[childIndex] = cur;
        heap[index] = child;
        index = childIndex;
    }
}
class SpanCursor {
    constructor(sets, skip, minPoint) {
        this.minPoint = minPoint;
        this.active = [];
        this.activeTo = [];
        this.activeRank = [];
        this.minActive = -1;
        // A currently active point range, if any
        this.point = null;
        this.pointFrom = 0;
        this.pointRank = 0;
        this.to = -1000000000 /* C.Far */;
        this.endSide = 0;
        // The amount of open active ranges at the start of the iterator.
        // Not including points.
        this.openStart = -1;
        this.cursor = HeapCursor.from(sets, skip, minPoint);
    }
    goto(pos, side = -1000000000 /* C.Far */) {
        this.cursor.goto(pos, side);
        this.active.length = this.activeTo.length = this.activeRank.length = 0;
        this.minActive = -1;
        this.to = pos;
        this.endSide = side;
        this.openStart = -1;
        this.next();
        return this;
    }
    forward(pos, side) {
        while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
            this.removeActive(this.minActive);
        this.cursor.forward(pos, side);
    }
    removeActive(index) {
        remove(this.active, index);
        remove(this.activeTo, index);
        remove(this.activeRank, index);
        this.minActive = findMinIndex(this.active, this.activeTo);
    }
    addActive(trackOpen) {
        let i = 0, { value, to, rank } = this.cursor;
        // Organize active marks by rank first, then by size
        while (i < this.activeRank.length && (rank - this.activeRank[i] || to - this.activeTo[i]) > 0)
            i++;
        insert(this.active, i, value);
        insert(this.activeTo, i, to);
        insert(this.activeRank, i, rank);
        if (trackOpen)
            insert(trackOpen, i, this.cursor.from);
        this.minActive = findMinIndex(this.active, this.activeTo);
    }
    // After calling this, if `this.point` != null, the next range is a
    // point. Otherwise, it's a regular range, covered by `this.active`.
    next() {
        let from = this.to, wasPoint = this.point;
        this.point = null;
        let trackOpen = this.openStart < 0 ? [] : null;
        for (;;) {
            let a = this.minActive;
            if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
                if (this.activeTo[a] > from) {
                    this.to = this.activeTo[a];
                    this.endSide = this.active[a].endSide;
                    break;
                }
                this.removeActive(a);
                if (trackOpen)
                    remove(trackOpen, a);
            }
            else if (!this.cursor.value) {
                this.to = this.endSide = 1000000000 /* C.Far */;
                break;
            }
            else if (this.cursor.from > from) {
                this.to = this.cursor.from;
                this.endSide = this.cursor.startSide;
                break;
            }
            else {
                let nextVal = this.cursor.value;
                if (!nextVal.point) { // Opening a range
                    this.addActive(trackOpen);
                    this.cursor.next();
                }
                else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {
                    // Ignore any non-empty points that end precisely at the end of the prev point
                    this.cursor.next();
                }
                else { // New point
                    this.point = nextVal;
                    this.pointFrom = this.cursor.from;
                    this.pointRank = this.cursor.rank;
                    this.to = this.cursor.to;
                    this.endSide = nextVal.endSide;
                    this.cursor.next();
                    this.forward(this.to, this.endSide);
                    break;
                }
            }
        }
        if (trackOpen) {
            this.openStart = 0;
            for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)
                this.openStart++;
        }
    }
    activeForPoint(to) {
        if (!this.active.length)
            return this.active;
        let active = [];
        for (let i = this.active.length - 1; i >= 0; i--) {
            if (this.activeRank[i] < this.pointRank)
                break;
            if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)
                active.push(this.active[i]);
        }
        return active.reverse();
    }
    openEnd(to) {
        let open = 0;
        for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)
            open++;
        return open;
    }
}
function compare(a, startA, b, startB, length, comparator) {
    a.goto(startA);
    b.goto(startB);
    let endB = startB + length;
    let pos = startB, dPos = startB - startA;
    let bounds = !!comparator.boundChange;
    for (let boundChange = false;;) {
        let dEnd = (a.to + dPos) - b.to, diff = dEnd || a.endSide - b.endSide;
        let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
        let point = a.point || b.point;
        if (point) {
            if (!(a.point && b.point && cmpVal(a.point, b.point) &&
                sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to))))
                comparator.comparePoint(pos, clipEnd, a.point, b.point);
            boundChange = false;
        }
        else {
            if (boundChange)
                comparator.boundChange(pos);
            if (clipEnd > pos && !sameValues(a.active, b.active))
                comparator.compareRange(pos, clipEnd, a.active, b.active);
            if (bounds && clipEnd < endB && (dEnd || a.openEnd(end) != b.openEnd(end)))
                boundChange = true;
        }
        if (end > endB)
            break;
        pos = end;
        if (diff <= 0)
            a.next();
        if (diff >= 0)
            b.next();
    }
}
function sameValues(a, b) {
    if (a.length != b.length)
        return false;
    for (let i = 0; i < a.length; i++)
        if (a[i] != b[i] && !cmpVal(a[i], b[i]))
            return false;
    return true;
}
function remove(array, index) {
    for (let i = index, e = array.length - 1; i < e; i++)
        array[i] = array[i + 1];
    array.pop();
}
function insert(array, index, value) {
    for (let i = array.length - 1; i >= index; i--)
        array[i + 1] = array[i];
    array[index] = value;
}
function findMinIndex(value, array) {
    let found = -1, foundPos = 1000000000 /* C.Far */;
    for (let i = 0; i < array.length; i++)
        if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
            found = i;
            foundPos = array[i];
        }
    return found;
}

/**
Count the column position at the given offset into the string,
taking extending characters and tab size into account.
*/
function dist_countColumn(string, tabSize, to = string.length) {
    let n = 0;
    for (let i = 0; i < to && i < string.length;) {
        if (string.charCodeAt(i) == 9) {
            n += tabSize - (n % tabSize);
            i++;
        }
        else {
            n++;
            i = dist_findClusterBreak(string, i);
        }
    }
    return n;
}
/**
Find the offset that corresponds to the given column position in a
string, taking extending characters and tab size into account. By
default, the string length is returned when it is too short to
reach the column. Pass `strict` true to make it return -1 in that
situation.
*/
function findColumn(string, col, tabSize, strict) {
    for (let i = 0, n = 0;;) {
        if (n >= col)
            return i;
        if (i == string.length)
            break;
        n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;
        i = dist_findClusterBreak(string, i);
    }
    return strict === true ? -1 : string.length;
}



;// external "style-mod"
const external_style_mod_namespaceObject = require("style-mod");
;// external "w3c-keyname"
const external_w3c_keyname_namespaceObject = require("w3c-keyname");
;// external "crelt"
const external_crelt_namespaceObject = require("crelt");
;// ../../node_modules/@codemirror/view/dist/index.js





let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" };
let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } };
const ie_edge = /*@__PURE__*//Edge\/(\d+)/.exec(nav.userAgent);
const ie_upto10 = /*@__PURE__*//MSIE \d/.test(nav.userAgent);
const ie_11up = /*@__PURE__*//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
const ie = !!(ie_upto10 || ie_11up || ie_edge);
const gecko = !ie && /*@__PURE__*//gecko\/(\d+)/i.test(nav.userAgent);
const chrome = !ie && /*@__PURE__*//Chrome\/(\d+)/.exec(nav.userAgent);
const webkit = "webkitFontSmoothing" in doc.documentElement.style;
const safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor);
const ios = safari && (/*@__PURE__*//Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);
var browser = {
    mac: ios || /*@__PURE__*//Mac/.test(nav.platform),
    windows: /*@__PURE__*//Win/.test(nav.platform),
    linux: /*@__PURE__*//Linux|X11/.test(nav.platform),
    ie,
    ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,
    gecko,
    gecko_version: gecko ? +(/*@__PURE__*//Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
    chrome: !!chrome,
    chrome_version: chrome ? +chrome[1] : 0,
    ios,
    android: /*@__PURE__*//Android\b/.test(nav.userAgent),
    webkit,
    webkit_version: webkit ? +(/*@__PURE__*//\bAppleWebKit\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
    safari,
    safari_version: safari ? +(/*@__PURE__*//\bVersion\/(\d+(\.\d+)?)/.exec(nav.userAgent) || [0, 0])[1] : 0,
    tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
};

function combineAttrs(source, target) {
    for (let name in source) {
        if (name == "class" && target.class)
            target.class += " " + source.class;
        else if (name == "style" && target.style)
            target.style += ";" + source.style;
        else
            target[name] = source[name];
    }
    return target;
}
const noAttrs = /*@__PURE__*/Object.create(null);
function attrsEq(a, b, ignore) {
    if (a == b)
        return true;
    if (!a)
        a = noAttrs;
    if (!b)
        b = noAttrs;
    let keysA = Object.keys(a), keysB = Object.keys(b);
    if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) !=
        keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0))
        return false;
    for (let key of keysA) {
        if (key != ignore && (keysB.indexOf(key) == -1 || a[key] !== b[key]))
            return false;
    }
    return true;
}
function setAttrs(dom, attrs) {
    for (let i = dom.attributes.length - 1; i >= 0; i--) {
        let name = dom.attributes[i].name;
        if (attrs[name] == null)
            dom.removeAttribute(name);
    }
    for (let name in attrs) {
        let value = attrs[name];
        if (name == "style")
            dom.style.cssText = value;
        else if (dom.getAttribute(name) != value)
            dom.setAttribute(name, value);
    }
}
function updateAttrs(dom, prev, attrs) {
    let changed = false;
    if (prev)
        for (let name in prev)
            if (!(attrs && name in attrs)) {
                changed = true;
                if (name == "style")
                    dom.style.cssText = "";
                else
                    dom.removeAttribute(name);
            }
    if (attrs)
        for (let name in attrs)
            if (!(prev && prev[name] == attrs[name])) {
                changed = true;
                if (name == "style")
                    dom.style.cssText = attrs[name];
                else
                    dom.setAttribute(name, attrs[name]);
            }
    return changed;
}
function getAttrs(dom) {
    let attrs = Object.create(null);
    for (let i = 0; i < dom.attributes.length; i++) {
        let attr = dom.attributes[i];
        attrs[attr.name] = attr.value;
    }
    return attrs;
}

/**
Widgets added to the content are described by subclasses of this
class. Using a description object like that makes it possible to
delay creating of the DOM structure for a widget until it is
needed, and to avoid redrawing widgets even if the decorations
that define them are recreated.
*/
class WidgetType {
    /**
    Compare this instance to another instance of the same type.
    (TypeScript can't express this, but only instances of the same
    specific class will be passed to this method.) This is used to
    avoid redrawing widgets when they are replaced by a new
    decoration of the same type. The default implementation just
    returns `false`, which will cause new instances of the widget to
    always be redrawn.
    */
    eq(widget) { return false; }
    /**
    Update a DOM element created by a widget of the same type (but
    different, non-`eq` content) to reflect this widget. May return
    true to indicate that it could update, false to indicate it
    couldn't (in which case the widget will be redrawn). The default
    implementation just returns false.
    */
    updateDOM(dom, view) { return false; }
    /**
    @internal
    */
    compare(other) {
        return this == other || this.constructor == other.constructor && this.eq(other);
    }
    /**
    The estimated height this widget will have, to be used when
    estimating the height of content that hasn't been drawn. May
    return -1 to indicate you don't know. The default implementation
    returns -1.
    */
    get estimatedHeight() { return -1; }
    /**
    For inline widgets that are displayed inline (as opposed to
    `inline-block`) and introduce line breaks (through `<br>` tags
    or textual newlines), this must indicate the amount of line
    breaks they introduce. Defaults to 0.
    */
    get lineBreaks() { return 0; }
    /**
    Can be used to configure which kinds of events inside the widget
    should be ignored by the editor. The default is to ignore all
    events.
    */
    ignoreEvent(event) { return true; }
    /**
    Override the way screen coordinates for positions at/in the
    widget are found. `pos` will be the offset into the widget, and
    `side` the side of the position that is being queried—less than
    zero for before, greater than zero for after, and zero for
    directly at that position.
    */
    coordsAt(dom, pos, side) { return null; }
    /**
    @internal
    */
    get isHidden() { return false; }
    /**
    @internal
    */
    get editable() { return false; }
    /**
    This is called when the an instance of the widget is removed
    from the editor view.
    */
    destroy(dom) { }
}
/**
The different types of blocks that can occur in an editor view.
*/
var BlockType = /*@__PURE__*/(function (BlockType) {
    /**
    A line of text.
    */
    BlockType[BlockType["Text"] = 0] = "Text";
    /**
    A block widget associated with the position after it.
    */
    BlockType[BlockType["WidgetBefore"] = 1] = "WidgetBefore";
    /**
    A block widget associated with the position before it.
    */
    BlockType[BlockType["WidgetAfter"] = 2] = "WidgetAfter";
    /**
    A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content.
    */
    BlockType[BlockType["WidgetRange"] = 3] = "WidgetRange";
return BlockType})(BlockType || (BlockType = {}));
/**
A decoration provides information on how to draw or style a piece
of content. You'll usually use it wrapped in a
[`Range`](https://codemirror.net/6/docs/ref/#state.Range), which adds a start and end position.
@nonabstract
*/
class dist_Decoration extends RangeValue {
    constructor(
    /**
    @internal
    */
    startSide, 
    /**
    @internal
    */
    endSide, 
    /**
    @internal
    */
    widget, 
    /**
    The config object used to create this decoration. You can
    include additional properties in there to store metadata about
    your decoration.
    */
    spec) {
        super();
        this.startSide = startSide;
        this.endSide = endSide;
        this.widget = widget;
        this.spec = spec;
    }
    /**
    @internal
    */
    get heightRelevant() { return false; }
    /**
    Create a mark decoration, which influences the styling of the
    content in its range. Nested mark decorations will cause nested
    DOM elements to be created. Nesting order is determined by
    precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with
    the higher-precedence decorations creating the inner DOM nodes.
    Such elements are split on line boundaries and on the boundaries
    of lower-precedence decorations.
    */
    static mark(spec) {
        return new MarkDecoration(spec);
    }
    /**
    Create a widget decoration, which displays a DOM element at the
    given position.
    */
    static widget(spec) {
        let side = Math.max(-10000, Math.min(10000, spec.side || 0)), block = !!spec.block;
        side += (block && !spec.inlineOrder)
            ? (side > 0 ? 300000000 /* Side.BlockAfter */ : -400000000 /* Side.BlockBefore */)
            : (side > 0 ? 100000000 /* Side.InlineAfter */ : -100000000 /* Side.InlineBefore */);
        return new PointDecoration(spec, side, side, block, spec.widget || null, false);
    }
    /**
    Create a replace decoration which replaces the given range with
    a widget, or simply hides it.
    */
    static replace(spec) {
        let block = !!spec.block, startSide, endSide;
        if (spec.isBlockGap) {
            startSide = -500000000 /* Side.GapStart */;
            endSide = 400000000 /* Side.GapEnd */;
        }
        else {
            let { start, end } = getInclusive(spec, block);
            startSide = (start ? (block ? -300000000 /* Side.BlockIncStart */ : -1 /* Side.InlineIncStart */) : 500000000 /* Side.NonIncStart */) - 1;
            endSide = (end ? (block ? 200000000 /* Side.BlockIncEnd */ : 1 /* Side.InlineIncEnd */) : -600000000 /* Side.NonIncEnd */) + 1;
        }
        return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);
    }
    /**
    Create a line decoration, which can add DOM attributes to the
    line starting at the given position.
    */
    static line(spec) {
        return new LineDecoration(spec);
    }
    /**
    Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given
    decorated range or ranges. If the ranges aren't already sorted,
    pass `true` for `sort` to make the library sort them for you.
    */
    static set(of, sort = false) {
        return dist_RangeSet.of(of, sort);
    }
    /**
    @internal
    */
    hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; }
}
/**
The empty set of decorations.
*/
dist_Decoration.none = dist_RangeSet.empty;
class MarkDecoration extends dist_Decoration {
    constructor(spec) {
        let { start, end } = getInclusive(spec);
        super(start ? -1 /* Side.InlineIncStart */ : 500000000 /* Side.NonIncStart */, end ? 1 /* Side.InlineIncEnd */ : -600000000 /* Side.NonIncEnd */, null, spec);
        this.tagName = spec.tagName || "span";
        this.attrs = spec.class && spec.attributes ? combineAttrs(spec.attributes, { class: spec.class })
            : spec.class ? { class: spec.class } : spec.attributes || noAttrs;
    }
    eq(other) {
        return this == other || other instanceof MarkDecoration && this.tagName == other.tagName && attrsEq(this.attrs, other.attrs);
    }
    range(from, to = from) {
        if (from >= to)
            throw new RangeError("Mark decorations may not be empty");
        return super.range(from, to);
    }
}
MarkDecoration.prototype.point = false;
class LineDecoration extends dist_Decoration {
    constructor(spec) {
        super(-200000000 /* Side.Line */, -200000000 /* Side.Line */, null, spec);
    }
    eq(other) {
        return other instanceof LineDecoration &&
            this.spec.class == other.spec.class &&
            attrsEq(this.spec.attributes, other.spec.attributes);
    }
    range(from, to = from) {
        if (to != from)
            throw new RangeError("Line decoration ranges must be zero-length");
        return super.range(from, to);
    }
}
LineDecoration.prototype.mapMode = dist_MapMode.TrackBefore;
LineDecoration.prototype.point = true;
class PointDecoration extends dist_Decoration {
    constructor(spec, startSide, endSide, block, widget, isReplace) {
        super(startSide, endSide, widget, spec);
        this.block = block;
        this.isReplace = isReplace;
        this.mapMode = !block ? dist_MapMode.TrackDel : startSide <= 0 ? dist_MapMode.TrackBefore : dist_MapMode.TrackAfter;
    }
    // Only relevant when this.block == true
    get type() {
        return this.startSide != this.endSide ? BlockType.WidgetRange
            : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter;
    }
    get heightRelevant() {
        return this.block || !!this.widget && (this.widget.estimatedHeight >= 5 || this.widget.lineBreaks > 0);
    }
    eq(other) {
        return other instanceof PointDecoration &&
            widgetsEq(this.widget, other.widget) &&
            this.block == other.block &&
            this.startSide == other.startSide && this.endSide == other.endSide;
    }
    range(from, to = from) {
        if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0)))
            throw new RangeError("Invalid range for replacement decoration");
        if (!this.isReplace && to != from)
            throw new RangeError("Widget decorations can only have zero-length ranges");
        return super.range(from, to);
    }
}
PointDecoration.prototype.point = true;
function getInclusive(spec, block = false) {
    let { inclusiveStart: start, inclusiveEnd: end } = spec;
    if (start == null)
        start = spec.inclusive;
    if (end == null)
        end = spec.inclusive;
    return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block };
}
function widgetsEq(a, b) {
    return a == b || !!(a && b && a.compare(b));
}
function addRange(from, to, ranges, margin = 0) {
    let last = ranges.length - 1;
    if (last >= 0 && ranges[last] + margin >= from)
        ranges[last] = Math.max(ranges[last], to);
    else
        ranges.push(from, to);
}
/**
A block wrapper defines a DOM node that wraps lines or other block
wrappers at the top of the document. It affects any line or block
widget that starts inside its range, including blocks starting
directly at `from` but not including `to`.
*/
class BlockWrapper extends RangeValue {
    constructor(tagName, attributes) {
        super();
        this.tagName = tagName;
        this.attributes = attributes;
    }
    eq(other) {
        return other == this ||
            other instanceof BlockWrapper && this.tagName == other.tagName && attrsEq(this.attributes, other.attributes);
    }
    /**
    Create a block wrapper object with the given tag name and
    attributes.
    */
    static create(spec) {
        return new BlockWrapper(spec.tagName, spec.attributes || noAttrs);
    }
    /**
    Create a range set from the given block wrapper ranges.
    */
    static set(of, sort = false) {
        return dist_RangeSet.of(of, sort);
    }
}
BlockWrapper.prototype.startSide = BlockWrapper.prototype.endSide = -1;

function getSelection(root) {
    let target;
    // Browsers differ on whether shadow roots have a getSelection
    // method. If it exists, use that, otherwise, call it on the
    // document.
    if (root.nodeType == 11) { // Shadow root
        target = root.getSelection ? root : root.ownerDocument;
    }
    else {
        target = root;
    }
    return target.getSelection();
}
function contains(dom, node) {
    return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;
}
function hasSelection(dom, selection) {
    if (!selection.anchorNode)
        return false;
    try {
        // Firefox will raise 'permission denied' errors when accessing
        // properties of `sel.anchorNode` when it's in a generated CSS
        // element.
        return contains(dom, selection.anchorNode);
    }
    catch (_) {
        return false;
    }
}
function clientRectsFor(dom) {
    if (dom.nodeType == 3)
        return textRange(dom, 0, dom.nodeValue.length).getClientRects();
    else if (dom.nodeType == 1)
        return dom.getClientRects();
    else
        return [];
}
// Scans forward and backward through DOM positions equivalent to the
// given one to see if the two are in the same place (i.e. after a
// text node vs at the end of that text node)
function isEquivalentPosition(node, off, targetNode, targetOff) {
    return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) ||
        scanFor(node, off, targetNode, targetOff, 1)) : false;
}
function domIndex(node) {
    for (var index = 0;; index++) {
        node = node.previousSibling;
        if (!node)
            return index;
    }
}
function isBlockElement(node) {
    return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName);
}
function scanFor(node, off, targetNode, targetOff, dir) {
    for (;;) {
        if (node == targetNode && off == targetOff)
            return true;
        if (off == (dir < 0 ? 0 : maxOffset(node))) {
            if (node.nodeName == "DIV")
                return false;
            let parent = node.parentNode;
            if (!parent || parent.nodeType != 1)
                return false;
            off = domIndex(node) + (dir < 0 ? 0 : 1);
            node = parent;
        }
        else if (node.nodeType == 1) {
            node = node.childNodes[off + (dir < 0 ? -1 : 0)];
            if (node.nodeType == 1 && node.contentEditable == "false")
                return false;
            off = dir < 0 ? maxOffset(node) : 0;
        }
        else {
            return false;
        }
    }
}
function maxOffset(node) {
    return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
function flattenRect(rect, left) {
    let x = left ? rect.left : rect.right;
    return { left: x, right: x, top: rect.top, bottom: rect.bottom };
}
function windowRect(win) {
    let vp = win.visualViewport;
    if (vp)
        return {
            left: 0, right: vp.width,
            top: 0, bottom: vp.height
        };
    return { left: 0, right: win.innerWidth,
        top: 0, bottom: win.innerHeight };
}
function getScale(elt, rect) {
    let scaleX = rect.width / elt.offsetWidth;
    let scaleY = rect.height / elt.offsetHeight;
    if (scaleX > 0.995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1)
        scaleX = 1;
    if (scaleY > 0.995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1)
        scaleY = 1;
    return { scaleX, scaleY };
}
function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) {
    let doc = dom.ownerDocument, win = doc.defaultView || window;
    for (let cur = dom, stop = false; cur && !stop;) {
        if (cur.nodeType == 1) { // Element
            let bounding, top = cur == doc.body;
            let scaleX = 1, scaleY = 1;
            if (top) {
                bounding = windowRect(win);
            }
            else {
                if (/^(fixed|sticky)$/.test(getComputedStyle(cur).position))
                    stop = true;
                if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) {
                    cur = cur.assignedSlot || cur.parentNode;
                    continue;
                }
                let rect = cur.getBoundingClientRect();
                ({ scaleX, scaleY } = getScale(cur, rect));
                // Make sure scrollbar width isn't included in the rectangle
                bounding = { left: rect.left, right: rect.left + cur.clientWidth * scaleX,
                    top: rect.top, bottom: rect.top + cur.clientHeight * scaleY };
            }
            let moveX = 0, moveY = 0;
            if (y == "nearest") {
                if (rect.top < bounding.top) {
                    moveY = rect.top - (bounding.top + yMargin);
                    if (side > 0 && rect.bottom > bounding.bottom + moveY)
                        moveY = rect.bottom - bounding.bottom + yMargin;
                }
                else if (rect.bottom > bounding.bottom) {
                    moveY = rect.bottom - bounding.bottom + yMargin;
                    if (side < 0 && (rect.top - moveY) < bounding.top)
                        moveY = rect.top - (bounding.top + yMargin);
                }
            }
            else {
                let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top;
                let targetTop = y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 :
                    y == "start" || y == "center" && side < 0 ? rect.top - yMargin :
                        rect.bottom - boundingHeight + yMargin;
                moveY = targetTop - bounding.top;
            }
            if (x == "nearest") {
                if (rect.left < bounding.left) {
                    moveX = rect.left - (bounding.left + xMargin);
                    if (side > 0 && rect.right > bounding.right + moveX)
                        moveX = rect.right - bounding.right + xMargin;
                }
                else if (rect.right > bounding.right) {
                    moveX = rect.right - bounding.right + xMargin;
                    if (side < 0 && rect.left < bounding.left + moveX)
                        moveX = rect.left - (bounding.left + xMargin);
                }
            }
            else {
                let targetLeft = x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 :
                    (x == "start") == ltr ? rect.left - xMargin :
                        rect.right - (bounding.right - bounding.left) + xMargin;
                moveX = targetLeft - bounding.left;
            }
            if (moveX || moveY) {
                if (top) {
                    win.scrollBy(moveX, moveY);
                }
                else {
                    let movedX = 0, movedY = 0;
                    if (moveY) {
                        let start = cur.scrollTop;
                        cur.scrollTop += moveY / scaleY;
                        movedY = (cur.scrollTop - start) * scaleY;
                    }
                    if (moveX) {
                        let start = cur.scrollLeft;
                        cur.scrollLeft += moveX / scaleX;
                        movedX = (cur.scrollLeft - start) * scaleX;
                    }
                    rect = { left: rect.left - movedX, top: rect.top - movedY,
                        right: rect.right - movedX, bottom: rect.bottom - movedY };
                    if (movedX && Math.abs(movedX - moveX) < 1)
                        x = "nearest";
                    if (movedY && Math.abs(movedY - moveY) < 1)
                        y = "nearest";
                }
            }
            if (top)
                break;
            if (rect.top < bounding.top || rect.bottom > bounding.bottom ||
                rect.left < bounding.left || rect.right > bounding.right)
                rect = { left: Math.max(rect.left, bounding.left), right: Math.min(rect.right, bounding.right),
                    top: Math.max(rect.top, bounding.top), bottom: Math.min(rect.bottom, bounding.bottom) };
            cur = cur.assignedSlot || cur.parentNode;
        }
        else if (cur.nodeType == 11) { // A shadow root
            cur = cur.host;
        }
        else {
            break;
        }
    }
}
function scrollableParents(dom) {
    let doc = dom.ownerDocument, x, y;
    for (let cur = dom.parentNode; cur;) {
        if (cur == doc.body || (x && y)) {
            break;
        }
        else if (cur.nodeType == 1) {
            if (!y && cur.scrollHeight > cur.clientHeight)
                y = cur;
            if (!x && cur.scrollWidth > cur.clientWidth)
                x = cur;
            cur = cur.assignedSlot || cur.parentNode;
        }
        else if (cur.nodeType == 11) {
            cur = cur.host;
        }
        else {
            break;
        }
    }
    return { x, y };
}
class DOMSelectionState {
    constructor() {
        this.anchorNode = null;
        this.anchorOffset = 0;
        this.focusNode = null;
        this.focusOffset = 0;
    }
    eq(domSel) {
        return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset &&
            this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;
    }
    setRange(range) {
        let { anchorNode, focusNode } = range;
        // Clip offsets to node size to avoid crashes when Safari reports bogus offsets (#1152)
        this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset(focusNode) : 0));
    }
    set(anchorNode, anchorOffset, focusNode, focusOffset) {
        this.anchorNode = anchorNode;
        this.anchorOffset = anchorOffset;
        this.focusNode = focusNode;
        this.focusOffset = focusOffset;
    }
}
let preventScrollSupported = null;
// Safari 26 breaks preventScroll support
if (browser.safari && browser.safari_version >= 26)
    preventScrollSupported = false;
// Feature-detects support for .focus({preventScroll: true}), and uses
// a fallback kludge when not supported.
function focusPreventScroll(dom) {
    if (dom.setActive)
        return dom.setActive(); // in IE
    if (preventScrollSupported)
        return dom.focus(preventScrollSupported);
    let stack = [];
    for (let cur = dom; cur; cur = cur.parentNode) {
        stack.push(cur, cur.scrollTop, cur.scrollLeft);
        if (cur == cur.ownerDocument)
            break;
    }
    dom.focus(preventScrollSupported == null ? {
        get preventScroll() {
            preventScrollSupported = { preventScroll: true };
            return true;
        }
    } : undefined);
    if (!preventScrollSupported) {
        preventScrollSupported = false;
        for (let i = 0; i < stack.length;) {
            let elt = stack[i++], top = stack[i++], left = stack[i++];
            if (elt.scrollTop != top)
                elt.scrollTop = top;
            if (elt.scrollLeft != left)
                elt.scrollLeft = left;
        }
    }
}
let scratchRange;
function textRange(node, from, to = from) {
    let range = scratchRange || (scratchRange = document.createRange());
    range.setEnd(node, to);
    range.setStart(node, from);
    return range;
}
function dispatchKey(elt, name, code, mods) {
    let options = { key: name, code: name, keyCode: code, which: code, cancelable: true };
    if (mods)
        ({ altKey: options.altKey, ctrlKey: options.ctrlKey, shiftKey: options.shiftKey, metaKey: options.metaKey } = mods);
    let down = new KeyboardEvent("keydown", options);
    down.synthetic = true;
    elt.dispatchEvent(down);
    let up = new KeyboardEvent("keyup", options);
    up.synthetic = true;
    elt.dispatchEvent(up);
    return down.defaultPrevented || up.defaultPrevented;
}
function getRoot(node) {
    while (node) {
        if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host))
            return node;
        node = node.assignedSlot || node.parentNode;
    }
    return null;
}
function atElementStart(doc, selection) {
    let node = selection.focusNode, offset = selection.focusOffset;
    if (!node || selection.anchorNode != node || selection.anchorOffset != offset)
        return false;
    // Safari can report bogus offsets (#1152)
    offset = Math.min(offset, maxOffset(node));
    for (;;) {
        if (offset) {
            if (node.nodeType != 1)
                return false;
            let prev = node.childNodes[offset - 1];
            if (prev.contentEditable == "false")
                offset--;
            else {
                node = prev;
                offset = maxOffset(node);
            }
        }
        else if (node == doc) {
            return true;
        }
        else {
            offset = domIndex(node);
            node = node.parentNode;
        }
    }
}
function isScrolledToBottom(elt) {
    return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);
}
function textNodeBefore(startNode, startOffset) {
    for (let node = startNode, offset = startOffset;;) {
        if (node.nodeType == 3 && offset > 0) {
            return { node: node, offset: offset };
        }
        else if (node.nodeType == 1 && offset > 0) {
            if (node.contentEditable == "false")
                return null;
            node = node.childNodes[offset - 1];
            offset = maxOffset(node);
        }
        else if (node.parentNode && !isBlockElement(node)) {
            offset = domIndex(node);
            node = node.parentNode;
        }
        else {
            return null;
        }
    }
}
function textNodeAfter(startNode, startOffset) {
    for (let node = startNode, offset = startOffset;;) {
        if (node.nodeType == 3 && offset < node.nodeValue.length) {
            return { node: node, offset: offset };
        }
        else if (node.nodeType == 1 && offset < node.childNodes.length) {
            if (node.contentEditable == "false")
                return null;
            node = node.childNodes[offset];
            offset = 0;
        }
        else if (node.parentNode && !isBlockElement(node)) {
            offset = domIndex(node) + 1;
            node = node.parentNode;
        }
        else {
            return null;
        }
    }
}
class DOMPos {
    constructor(node, offset, precise = true) {
        this.node = node;
        this.offset = offset;
        this.precise = precise;
    }
    static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); }
    static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); }
}

/**
Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
*/
var Direction = /*@__PURE__*/(function (Direction) {
    // (These are chosen to match the base levels, in bidi algorithm
    // terms, of spans in that direction.)
    /**
    Left-to-right.
    */
    Direction[Direction["LTR"] = 0] = "LTR";
    /**
    Right-to-left.
    */
    Direction[Direction["RTL"] = 1] = "RTL";
return Direction})(Direction || (Direction = {}));
const LTR = Direction.LTR, RTL = Direction.RTL;
// Decode a string with each type encoded as log2(type)
function dec(str) {
    let result = [];
    for (let i = 0; i < str.length; i++)
        result.push(1 << +str[i]);
    return result;
}
// Character types for codepoints 0 to 0xf8
const LowTypes = /*@__PURE__*/dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
// Character types for codepoints 0x600 to 0x6f9
const ArabicTypes = /*@__PURE__*/dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
const Brackets = /*@__PURE__*/Object.create(null), BracketStack = [];
// There's a lot more in
// https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt,
// which are left out to keep code size down.
for (let p of ["()", "[]", "{}"]) {
    let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1);
    Brackets[l] = r;
    Brackets[r] = -l;
}
function charType(ch) {
    return ch <= 0xf7 ? LowTypes[ch] :
        0x590 <= ch && ch <= 0x5f4 ? 2 /* T.R */ :
            0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] :
                0x6ee <= ch && ch <= 0x8ac ? 4 /* T.AL */ :
                    0x2000 <= ch && ch <= 0x200c ? 256 /* T.NI */ :
                        0xfb50 <= ch && ch <= 0xfdff ? 4 /* T.AL */ : 1 /* T.L */;
}
const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
/**
Represents a contiguous range of text that has a single direction
(as in left-to-right or right-to-left).
*/
class BidiSpan {
    /**
    The direction of this span.
    */
    get dir() { return this.level % 2 ? RTL : LTR; }
    /**
    @internal
    */
    constructor(
    /**
    The start of the span (relative to the start of the line).
    */
    from, 
    /**
    The end of the span.
    */
    to, 
    /**
    The ["bidi
    level"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm)
    of the span (in this context, 0 means
    left-to-right, 1 means right-to-left, 2 means left-to-right
    number inside right-to-left text).
    */
    level) {
        this.from = from;
        this.to = to;
        this.level = level;
    }
    /**
    @internal
    */
    side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; }
    /**
    @internal
    */
    forward(forward, dir) { return forward == (this.dir == dir); }
    /**
    @internal
    */
    static find(order, index, level, assoc) {
        let maybe = -1;
        for (let i = 0; i < order.length; i++) {
            let span = order[i];
            if (span.from <= index && span.to >= index) {
                if (span.level == level)
                    return i;
                // When multiple spans match, if assoc != 0, take the one that
                // covers that side, otherwise take the one with the minimum
                // level.
                if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level))
                    maybe = i;
            }
        }
        if (maybe < 0)
            throw new RangeError("Index out of range");
        return maybe;
    }
}
function isolatesEq(a, b) {
    if (a.length != b.length)
        return false;
    for (let i = 0; i < a.length; i++) {
        let iA = a[i], iB = b[i];
        if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner))
            return false;
    }
    return true;
}
// Reused array of character types
const dist_types = [];
// Fill in the character types (in `types`) from `from` to `to` and
// apply W normalization rules.
function computeCharTypes(line, rFrom, rTo, isolates, outerType) {
    for (let iI = 0; iI <= isolates.length; iI++) {
        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
        let prevType = iI ? 256 /* T.NI */ : outerType;
        // W1. Examine each non-spacing mark (NSM) in the level run, and
        // change the type of the NSM to the type of the previous
        // character. If the NSM is at the start of the level run, it will
        // get the type of sor.
        // W2. Search backwards from each instance of a European number
        // until the first strong type (R, L, AL, or sor) is found. If an
        // AL is found, change the type of the European number to Arabic
        // number.
        // W3. Change all ALs to R.
        // (Left after this: L, R, EN, AN, ET, CS, NI)
        for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
            let type = charType(line.charCodeAt(i));
            if (type == 512 /* T.NSM */)
                type = prev;
            else if (type == 8 /* T.EN */ && prevStrong == 4 /* T.AL */)
                type = 16 /* T.AN */;
            dist_types[i] = type == 4 /* T.AL */ ? 2 /* T.R */ : type;
            if (type & 7 /* T.Strong */)
                prevStrong = type;
            prev = type;
        }
        // W5. A sequence of European terminators adjacent to European
        // numbers changes to all European numbers.
        // W6. Otherwise, separators and terminators change to Other
        // Neutral.
        // W7. Search backwards from each instance of a European number
        // until the first strong type (R, L, or sor) is found. If an L is
        // found, then change the type of the European number to L.
        // (Left after this: L, R, EN+AN, NI)
        for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
            let type = dist_types[i];
            if (type == 128 /* T.CS */) {
                if (i < to - 1 && prev == dist_types[i + 1] && (prev & 24 /* T.Num */))
                    type = dist_types[i] = prev;
                else
                    dist_types[i] = 256 /* T.NI */;
            }
            else if (type == 64 /* T.ET */) {
                let end = i + 1;
                while (end < to && dist_types[end] == 64 /* T.ET */)
                    end++;
                let replace = (i && prev == 8 /* T.EN */) || (end < rTo && dist_types[end] == 8 /* T.EN */) ? (prevStrong == 1 /* T.L */ ? 1 /* T.L */ : 8 /* T.EN */) : 256 /* T.NI */;
                for (let j = i; j < end; j++)
                    dist_types[j] = replace;
                i = end - 1;
            }
            else if (type == 8 /* T.EN */ && prevStrong == 1 /* T.L */) {
                dist_types[i] = 1 /* T.L */;
            }
            prev = type;
            if (type & 7 /* T.Strong */)
                prevStrong = type;
        }
    }
}
// Process brackets throughout a run sequence.
function processBracketPairs(line, rFrom, rTo, isolates, outerType) {
    let oppositeType = outerType == 1 /* T.L */ ? 2 /* T.R */ : 1 /* T.L */;
    for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {
        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
        // N0. Process bracket pairs in an isolating run sequence
        // sequentially in the logical order of the text positions of the
        // opening paired brackets using the logic given below. Within this
        // scope, bidirectional types EN and AN are treated as R.
        for (let i = from, ch, br, type; i < to; i++) {
            // Keeps [startIndex, type, strongSeen] triples for each open
            // bracket on BracketStack.
            if (br = Brackets[ch = line.charCodeAt(i)]) {
                if (br < 0) { // Closing bracket
                    for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
                        if (BracketStack[sJ + 1] == -br) {
                            let flags = BracketStack[sJ + 2];
                            let type = (flags & 2 /* Bracketed.EmbedInside */) ? outerType :
                                !(flags & 4 /* Bracketed.OppositeInside */) ? 0 :
                                    (flags & 1 /* Bracketed.OppositeBefore */) ? oppositeType : outerType;
                            if (type)
                                dist_types[i] = dist_types[BracketStack[sJ]] = type;
                            sI = sJ;
                            break;
                        }
                    }
                }
                else if (BracketStack.length == 189 /* Bracketed.MaxDepth */) {
                    break;
                }
                else {
                    BracketStack[sI++] = i;
                    BracketStack[sI++] = ch;
                    BracketStack[sI++] = context;
                }
            }
            else if ((type = dist_types[i]) == 2 /* T.R */ || type == 1 /* T.L */) {
                let embed = type == outerType;
                context = embed ? 0 : 1 /* Bracketed.OppositeBefore */;
                for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
                    let cur = BracketStack[sJ + 2];
                    if (cur & 2 /* Bracketed.EmbedInside */)
                        break;
                    if (embed) {
                        BracketStack[sJ + 2] |= 2 /* Bracketed.EmbedInside */;
                    }
                    else {
                        if (cur & 4 /* Bracketed.OppositeInside */)
                            break;
                        BracketStack[sJ + 2] |= 4 /* Bracketed.OppositeInside */;
                    }
                }
            }
        }
    }
}
function processNeutrals(rFrom, rTo, isolates, outerType) {
    for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {
        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
        // N1. A sequence of neutrals takes the direction of the
        // surrounding strong text if the text on both sides has the same
        // direction. European and Arabic numbers act as if they were R in
        // terms of their influence on neutrals. Start-of-level-run (sor)
        // and end-of-level-run (eor) are used at level run boundaries.
        // N2. Any remaining neutrals take the embedding direction.
        // (Left after this: L, R, EN+AN)
        for (let i = from; i < to;) {
            let type = dist_types[i];
            if (type == 256 /* T.NI */) {
                let end = i + 1;
                for (;;) {
                    if (end == to) {
                        if (iI == isolates.length)
                            break;
                        end = isolates[iI++].to;
                        to = iI < isolates.length ? isolates[iI].from : rTo;
                    }
                    else if (dist_types[end] == 256 /* T.NI */) {
                        end++;
                    }
                    else {
                        break;
                    }
                }
                let beforeL = prev == 1 /* T.L */;
                let afterL = (end < rTo ? dist_types[end] : outerType) == 1 /* T.L */;
                let replace = beforeL == afterL ? (beforeL ? 1 /* T.L */ : 2 /* T.R */) : outerType;
                for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i;) {
                    if (j == fromJ) {
                        j = isolates[--jI].from;
                        fromJ = jI ? isolates[jI - 1].to : rFrom;
                    }
                    dist_types[--j] = replace;
                }
                i = end;
            }
            else {
                prev = type;
                i++;
            }
        }
    }
}
// Find the contiguous ranges of character types in a given range, and
// emit spans for them. Flip the order of the spans as appropriate
// based on the level, and call through to compute the spans for
// isolates at the proper point.
function emitSpans(line, from, to, level, baseLevel, isolates, order) {
    let ourType = level % 2 ? 2 /* T.R */ : 1 /* T.L */;
    if ((level % 2) == (baseLevel % 2)) { // Same dir as base direction, don't flip
        for (let iCh = from, iI = 0; iCh < to;) {
            // Scan a section of characters in direction ourType, unless
            // there's another type of char right after iCh, in which case
            // we scan a section of other characters (which, if ourType ==
            // T.L, may contain both T.R and T.AN chars).
            let sameDir = true, isNum = false;
            if (iI == isolates.length || iCh < isolates[iI].from) {
                let next = dist_types[iCh];
                if (next != ourType) {
                    sameDir = false;
                    isNum = next == 16 /* T.AN */;
                }
            }
            // Holds an array of isolates to pass to a recursive call if we
            // must recurse (to distinguish T.AN inside an RTL section in
            // LTR text), null if we can emit directly
            let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;
            let localLevel = sameDir ? level : level + 1;
            let iScan = iCh;
            run: for (;;) {
                if (iI < isolates.length && iScan == isolates[iI].from) {
                    if (isNum)
                        break run;
                    let iso = isolates[iI];
                    // Scan ahead to verify that there is another char in this dir after the isolate(s)
                    if (!sameDir)
                        for (let upto = iso.to, jI = iI + 1;;) {
                            if (upto == to)
                                break run;
                            if (jI < isolates.length && isolates[jI].from == upto)
                                upto = isolates[jI++].to;
                            else if (dist_types[upto] == ourType)
                                break run;
                            else
                                break;
                        }
                    iI++;
                    if (recurse) {
                        recurse.push(iso);
                    }
                    else {
                        if (iso.from > iCh)
                            order.push(new BidiSpan(iCh, iso.from, localLevel));
                        let dirSwap = (iso.direction == LTR) != !(localLevel % 2);
                        computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
                        iCh = iso.to;
                    }
                    iScan = iso.to;
                }
                else if (iScan == to || (sameDir ? dist_types[iScan] != ourType : dist_types[iScan] == ourType)) {
                    break;
                }
                else {
                    iScan++;
                }
            }
            if (recurse)
                emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order);
            else if (iCh < iScan)
                order.push(new BidiSpan(iCh, iScan, localLevel));
            iCh = iScan;
        }
    }
    else {
        // Iterate in reverse to flip the span order. Same code again, but
        // going from the back of the section to the front
        for (let iCh = to, iI = isolates.length; iCh > from;) {
            let sameDir = true, isNum = false;
            if (!iI || iCh > isolates[iI - 1].to) {
                let next = dist_types[iCh - 1];
                if (next != ourType) {
                    sameDir = false;
                    isNum = next == 16 /* T.AN */;
                }
            }
            let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;
            let localLevel = sameDir ? level : level + 1;
            let iScan = iCh;
            run: for (;;) {
                if (iI && iScan == isolates[iI - 1].to) {
                    if (isNum)
                        break run;
                    let iso = isolates[--iI];
                    // Scan ahead to verify that there is another char in this dir after the isolate(s)
                    if (!sameDir)
                        for (let upto = iso.from, jI = iI;;) {
                            if (upto == from)
                                break run;
                            if (jI && isolates[jI - 1].to == upto)
                                upto = isolates[--jI].from;
                            else if (dist_types[upto - 1] == ourType)
                                break run;
                            else
                                break;
                        }
                    if (recurse) {
                        recurse.push(iso);
                    }
                    else {
                        if (iso.to < iCh)
                            order.push(new BidiSpan(iso.to, iCh, localLevel));
                        let dirSwap = (iso.direction == LTR) != !(localLevel % 2);
                        computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
                        iCh = iso.from;
                    }
                    iScan = iso.from;
                }
                else if (iScan == from || (sameDir ? dist_types[iScan - 1] != ourType : dist_types[iScan - 1] == ourType)) {
                    break;
                }
                else {
                    iScan--;
                }
            }
            if (recurse)
                emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order);
            else if (iScan < iCh)
                order.push(new BidiSpan(iScan, iCh, localLevel));
            iCh = iScan;
        }
    }
}
function computeSectionOrder(line, level, baseLevel, isolates, from, to, order) {
    let outerType = (level % 2 ? 2 /* T.R */ : 1 /* T.L */);
    computeCharTypes(line, from, to, isolates, outerType);
    processBracketPairs(line, from, to, isolates, outerType);
    processNeutrals(from, to, isolates, outerType);
    emitSpans(line, from, to, level, baseLevel, isolates, order);
}
function computeOrder(line, direction, isolates) {
    if (!line)
        return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)];
    if (direction == LTR && !isolates.length && !BidiRE.test(line))
        return trivialOrder(line.length);
    if (isolates.length)
        while (line.length > dist_types.length)
            dist_types[dist_types.length] = 256 /* T.NI */; // Make sure types array has no gaps
    let order = [], level = direction == LTR ? 0 : 1;
    computeSectionOrder(line, level, level, isolates, 0, line.length, order);
    return order;
}
function trivialOrder(length) {
    return [new BidiSpan(0, length, 0)];
}
let movedOver = "";
// This implementation moves strictly visually, without concern for a
// traversal visiting every logical position in the string. It will
// still do so for simple input, but situations like multiple isolates
// with the same level next to each other, or text going against the
// main dir at the end of the line, will make some positions
// unreachable with this motion. Each visible cursor position will
// correspond to the lower-level bidi span that touches it.
//
// The alternative would be to solve an order globally for a given
// line, making sure that it includes every position, but that would
// require associating non-canonical (higher bidi span level)
// positions with a given visual position, which is likely to confuse
// people. (And would generally be a lot more complicated.)
function moveVisually(line, order, dir, start, forward) {
    var _a;
    let startIndex = start.head - line.from;
    let spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc);
    let span = order[spanI], spanEnd = span.side(forward, dir);
    // End of span
    if (startIndex == spanEnd) {
        let nextI = spanI += forward ? 1 : -1;
        if (nextI < 0 || nextI >= order.length)
            return null;
        span = order[spanI = nextI];
        startIndex = span.side(!forward, dir);
        spanEnd = span.side(forward, dir);
    }
    let nextIndex = dist_findClusterBreak(line.text, startIndex, span.forward(forward, dir));
    if (nextIndex < span.from || nextIndex > span.to)
        nextIndex = spanEnd;
    movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
    let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
    if (nextSpan && nextIndex == spanEnd && nextSpan.level + (forward ? 0 : 1) < span.level)
        return dist_EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, nextSpan.forward(forward, dir) ? 1 : -1, nextSpan.level);
    return dist_EditorSelection.cursor(nextIndex + line.from, span.forward(forward, dir) ? -1 : 1, span.level);
}
function autoDirection(text, from, to) {
    for (let i = from; i < to; i++) {
        let type = charType(text.charCodeAt(i));
        if (type == 1 /* T.L */)
            return LTR;
        if (type == 2 /* T.R */ || type == 4 /* T.AL */)
            return RTL;
    }
    return LTR;
}

const clickAddsSelectionRange = /*@__PURE__*/Facet.define();
const dragMovesSelection$1 = /*@__PURE__*/Facet.define();
const mouseSelectionStyle = /*@__PURE__*/Facet.define();
const exceptionSink = /*@__PURE__*/Facet.define();
const updateListener = /*@__PURE__*/Facet.define();
const inputHandler = /*@__PURE__*/Facet.define();
const focusChangeEffect = /*@__PURE__*/Facet.define();
const clipboardInputFilter = /*@__PURE__*/Facet.define();
const clipboardOutputFilter = /*@__PURE__*/Facet.define();
const perLineTextDirection = /*@__PURE__*/Facet.define({
    combine: values => values.some(x => x)
});
const nativeSelectionHidden = /*@__PURE__*/Facet.define({
    combine: values => values.some(x => x)
});
const scrollHandler = /*@__PURE__*/Facet.define();
class ScrollTarget {
    constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5, 
    // This data structure is abused to also store precise scroll
    // snapshots, instead of a `scrollIntoView` request. When this
    // flag is `true`, `range` points at a position in the reference
    // line, `yMargin` holds the difference between the top of that
    // line and the top of the editor, and `xMargin` holds the
    // editor's `scrollLeft`.
    isSnapshot = false) {
        this.range = range;
        this.y = y;
        this.x = x;
        this.yMargin = yMargin;
        this.xMargin = xMargin;
        this.isSnapshot = isSnapshot;
    }
    map(changes) {
        return changes.empty ? this :
            new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
    }
    clip(state) {
        return this.range.to <= state.doc.length ? this :
            new ScrollTarget(dist_EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
    }
}
const scrollIntoView = /*@__PURE__*/dist_StateEffect.define({ map: (t, ch) => t.map(ch) });
const setEditContextFormatting = /*@__PURE__*/dist_StateEffect.define();
/**
Log or report an unhandled exception in client code. Should
probably only be used by extension code that allows client code to
provide functions, and calls those functions in a context where an
exception can't be propagated to calling code in a reasonable way
(for example when in an event handler).

Either calls a handler registered with
[`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink),
`window.onerror`, if defined, or `console.error` (in which case
it'll pass `context`, when given, as first argument).
*/
function logException(state, exception, context) {
    let handler = state.facet(exceptionSink);
    if (handler.length)
        handler[0](exception);
    else if (window.onerror && window.onerror(String(exception), context, undefined, undefined, exception)) ;
    else if (context)
        console.error(context + ":", exception);
    else
        console.error(exception);
}
const editable = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : true });
let nextPluginID = 0;
const viewPlugin = /*@__PURE__*/Facet.define({
    combine(plugins) {
        return plugins.filter((p, i) => {
            for (let j = 0; j < i; j++)
                if (plugins[j].plugin == p.plugin)
                    return false;
            return true;
        });
    }
});
/**
View plugins associate stateful values with a view. They can
influence the way the content is drawn, and are notified of things
that happen in the view. They optionally take an argument, in
which case you need to call [`of`](https://codemirror.net/6/docs/ref/#view.ViewPlugin.of) to create
an extension for the plugin. When the argument type is undefined,
you can use the plugin instance as an extension directly.
*/
class dist_ViewPlugin {
    constructor(
    /**
    @internal
    */
    id, 
    /**
    @internal
    */
    create, 
    /**
    @internal
    */
    domEventHandlers, 
    /**
    @internal
    */
    domEventObservers, buildExtensions) {
        this.id = id;
        this.create = create;
        this.domEventHandlers = domEventHandlers;
        this.domEventObservers = domEventObservers;
        this.baseExtensions = buildExtensions(this);
        this.extension = this.baseExtensions.concat(viewPlugin.of({ plugin: this, arg: undefined }));
    }
    /**
    Create an extension for this plugin with the given argument.
    */
    of(arg) {
        return this.baseExtensions.concat(viewPlugin.of({ plugin: this, arg }));
    }
    /**
    Define a plugin from a constructor function that creates the
    plugin's value, given an editor view.
    */
    static define(create, spec) {
        const { eventHandlers, eventObservers, provide, decorations: deco } = spec || {};
        return new dist_ViewPlugin(nextPluginID++, create, eventHandlers, eventObservers, plugin => {
            let ext = [];
            if (deco)
                ext.push(decorations.of(view => {
                    let pluginInst = view.plugin(plugin);
                    return pluginInst ? deco(pluginInst) : dist_Decoration.none;
                }));
            if (provide)
                ext.push(provide(plugin));
            return ext;
        });
    }
    /**
    Create a plugin for a class whose constructor takes a single
    editor view as argument.
    */
    static fromClass(cls, spec) {
        return dist_ViewPlugin.define((view, arg) => new cls(view, arg), spec);
    }
}
class PluginInstance {
    constructor(spec) {
        this.spec = spec;
        // When starting an update, all plugins have this field set to the
        // update object, indicating they need to be updated. When finished
        // updating, it is set to `null`. Retrieving a plugin that needs to
        // be updated with `view.plugin` forces an eager update.
        this.mustUpdate = null;
        // This is null when the plugin is initially created, but
        // initialized on the first update.
        this.value = null;
    }
    get plugin() { return this.spec && this.spec.plugin; }
    update(view) {
        if (!this.value) {
            if (this.spec) {
                try {
                    this.value = this.spec.plugin.create(view, this.spec.arg);
                }
                catch (e) {
                    logException(view.state, e, "CodeMirror plugin crashed");
                    this.deactivate();
                }
            }
        }
        else if (this.mustUpdate) {
            let update = this.mustUpdate;
            this.mustUpdate = null;
            if (this.value.update) {
                try {
                    this.value.update(update);
                }
                catch (e) {
                    logException(update.state, e, "CodeMirror plugin crashed");
                    if (this.value.destroy)
                        try {
                            this.value.destroy();
                        }
                        catch (_) { }
                    this.deactivate();
                }
            }
        }
        return this;
    }
    destroy(view) {
        var _a;
        if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) {
            try {
                this.value.destroy();
            }
            catch (e) {
                logException(view.state, e, "CodeMirror plugin crashed");
            }
        }
    }
    deactivate() {
        this.spec = this.value = null;
    }
}
const editorAttributes = /*@__PURE__*/Facet.define();
const contentAttributes = /*@__PURE__*/Facet.define();
// Provide decorations
const decorations = /*@__PURE__*/Facet.define();
const blockWrappers = /*@__PURE__*/Facet.define();
const outerDecorations = /*@__PURE__*/Facet.define();
const atomicRanges = /*@__PURE__*/Facet.define();
const bidiIsolatedRanges = /*@__PURE__*/Facet.define();
function getIsolatedRanges(view, line) {
    let isolates = view.state.facet(bidiIsolatedRanges);
    if (!isolates.length)
        return isolates;
    let sets = isolates.map(i => i instanceof Function ? i(view) : i);
    let result = [];
    dist_RangeSet.spans(sets, line.from, line.to, {
        point() { },
        span(fromDoc, toDoc, active, open) {
            let from = fromDoc - line.from, to = toDoc - line.from;
            let level = result;
            for (let i = active.length - 1; i >= 0; i--, open--) {
                let direction = active[i].spec.bidiIsolate, update;
                if (direction == null)
                    direction = autoDirection(line.text, from, to);
                if (open > 0 && level.length &&
                    (update = level[level.length - 1]).to == from && update.direction == direction) {
                    update.to = to;
                    level = update.inner;
                }
                else {
                    let add = { from, to, direction, inner: [] };
                    level.push(add);
                    level = add.inner;
                }
            }
        }
    });
    return result;
}
const scrollMargins = /*@__PURE__*/Facet.define();
function getScrollMargins(view) {
    let left = 0, right = 0, top = 0, bottom = 0;
    for (let source of view.state.facet(scrollMargins)) {
        let m = source(view);
        if (m) {
            if (m.left != null)
                left = Math.max(left, m.left);
            if (m.right != null)
                right = Math.max(right, m.right);
            if (m.top != null)
                top = Math.max(top, m.top);
            if (m.bottom != null)
                bottom = Math.max(bottom, m.bottom);
        }
    }
    return { left, right, top, bottom };
}
const styleModule = /*@__PURE__*/Facet.define();
class ChangedRange {
    constructor(fromA, toA, fromB, toB) {
        this.fromA = fromA;
        this.toA = toA;
        this.fromB = fromB;
        this.toB = toB;
    }
    join(other) {
        return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB));
    }
    addToSet(set) {
        let i = set.length, me = this;
        for (; i > 0; i--) {
            let range = set[i - 1];
            if (range.fromA > me.toA)
                continue;
            if (range.toA < me.fromA)
                break;
            me = me.join(range);
            set.splice(i - 1, 1);
        }
        set.splice(i, 0, me);
        return set;
    }
    // Extend a set to cover all the content in `ranges`, which is a
    // flat array with each pair of numbers representing fromB/toB
    // positions. These pairs are generated in unchanged ranges, so the
    // offset between doc A and doc B is the same for their start and
    // end points.
    static extendWithRanges(diff, ranges) {
        if (ranges.length == 0)
            return diff;
        let result = [];
        for (let dI = 0, rI = 0, off = 0;;) {
            let nextD = dI < diff.length ? diff[dI].fromB : 1e9;
            let nextR = rI < ranges.length ? ranges[rI] : 1e9;
            let fromB = Math.min(nextD, nextR);
            if (fromB == 1e9)
                break;
            let fromA = fromB + off, toB = fromB, toA = fromA;
            for (;;) {
                if (rI < ranges.length && ranges[rI] <= toB) {
                    let end = ranges[rI + 1];
                    rI += 2;
                    toB = Math.max(toB, end);
                    for (let i = dI; i < diff.length && diff[i].fromB <= toB; i++)
                        off = diff[i].toA - diff[i].toB;
                    toA = Math.max(toA, end + off);
                }
                else if (dI < diff.length && diff[dI].fromB <= toB) {
                    let next = diff[dI++];
                    toB = Math.max(toB, next.toB);
                    toA = Math.max(toA, next.toA);
                    off = next.toA - next.toB;
                }
                else {
                    break;
                }
            }
            result.push(new ChangedRange(fromA, toA, fromB, toB));
        }
        return result;
    }
}
/**
View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this
class, which describe what happened, whenever the view is updated.
*/
class ViewUpdate {
    constructor(
    /**
    The editor view that the update is associated with.
    */
    view, 
    /**
    The new editor state.
    */
    state, 
    /**
    The transactions involved in the update. May be empty.
    */
    transactions) {
        this.view = view;
        this.state = state;
        this.transactions = transactions;
        /**
        @internal
        */
        this.flags = 0;
        this.startState = view.state;
        this.changes = ChangeSet.empty(this.startState.doc.length);
        for (let tr of transactions)
            this.changes = this.changes.compose(tr.changes);
        let changedRanges = [];
        this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));
        this.changedRanges = changedRanges;
    }
    /**
    @internal
    */
    static create(view, state, transactions) {
        return new ViewUpdate(view, state, transactions);
    }
    /**
    Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or
    [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this
    update.
    */
    get viewportChanged() {
        return (this.flags & 4 /* UpdateFlag.Viewport */) > 0;
    }
    /**
    Returns true when
    [`viewportChanged`](https://codemirror.net/6/docs/ref/#view.ViewUpdate.viewportChanged) is true
    and the viewport change is not just the result of mapping it in
    response to document changes.
    */
    get viewportMoved() {
        return (this.flags & 8 /* UpdateFlag.ViewportMoved */) > 0;
    }
    /**
    Indicates whether the height of a block element in the editor
    changed in this update.
    */
    get heightChanged() {
        return (this.flags & 2 /* UpdateFlag.Height */) > 0;
    }
    /**
    Returns true when the document was modified or the size of the
    editor, or elements within the editor, changed.
    */
    get geometryChanged() {
        return this.docChanged || (this.flags & (16 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */)) > 0;
    }
    /**
    True when this update indicates a focus change.
    */
    get focusChanged() {
        return (this.flags & 1 /* UpdateFlag.Focus */) > 0;
    }
    /**
    Whether the document changed in this update.
    */
    get docChanged() {
        return !this.changes.empty;
    }
    /**
    Whether the selection was explicitly set in this update.
    */
    get selectionSet() {
        return this.transactions.some(tr => tr.selection);
    }
    /**
    @internal
    */
    get empty() { return this.flags == 0 && this.transactions.length == 0; }
}

const noChildren = [];
class Tile {
    constructor(dom, length, flags = 0) {
        this.dom = dom;
        this.length = length;
        this.flags = flags;
        this.parent = null;
        dom.cmTile = this;
    }
    get breakAfter() { return (this.flags & 1 /* TileFlag.BreakAfter */); }
    get children() { return noChildren; }
    isWidget() { return false; }
    get isHidden() { return false; }
    isComposite() { return false; }
    isLine() { return false; }
    isText() { return false; }
    isBlock() { return false; }
    get domAttrs() { return null; }
    sync(track) {
        this.flags |= 2 /* TileFlag.Synced */;
        if (this.flags & 4 /* TileFlag.AttrsDirty */) {
            this.flags &= ~4 /* TileFlag.AttrsDirty */;
            let attrs = this.domAttrs;
            if (attrs)
                setAttrs(this.dom, attrs);
        }
    }
    toString() {
        return this.constructor.name + (this.children.length ? `(${this.children})` : "") + (this.breakAfter ? "#" : "");
    }
    destroy() { this.parent = null; }
    setDOM(dom) {
        this.dom = dom;
        dom.cmTile = this;
    }
    get posAtStart() {
        return this.parent ? this.parent.posBefore(this) : 0;
    }
    get posAtEnd() {
        return this.posAtStart + this.length;
    }
    posBefore(tile, start = this.posAtStart) {
        let pos = start;
        for (let child of this.children) {
            if (child == tile)
                return pos;
            pos += child.length + child.breakAfter;
        }
        throw new RangeError("Invalid child in posBefore");
    }
    posAfter(tile) {
        return this.posBefore(tile) + tile.length;
    }
    covers(side) { return true; }
    coordsIn(pos, side) { return null; }
    domPosFor(off, side) {
        let index = domIndex(this.dom);
        let after = this.length ? off > 0 : side > 0;
        return new DOMPos(this.parent.dom, index + (after ? 1 : 0), off == 0 || off == this.length);
    }
    markDirty(attrs) {
        this.flags &= ~2 /* TileFlag.Synced */;
        if (attrs)
            this.flags |= 4 /* TileFlag.AttrsDirty */;
        if (this.parent && (this.parent.flags & 2 /* TileFlag.Synced */))
            this.parent.markDirty(false);
    }
    get overrideDOMText() { return null; }
    get root() {
        for (let t = this; t; t = t.parent)
            if (t instanceof DocTile)
                return t;
        return null;
    }
    static get(dom) {
        return dom.cmTile;
    }
}
class CompositeTile extends Tile {
    constructor(dom) {
        super(dom, 0);
        this._children = [];
    }
    isComposite() { return true; }
    get children() { return this._children; }
    get lastChild() { return this.children.length ? this.children[this.children.length - 1] : null; }
    append(child) {
        this.children.push(child);
        child.parent = this;
    }
    sync(track) {
        if (this.flags & 2 /* TileFlag.Synced */)
            return;
        super.sync(track);
        let parent = this.dom, prev = null, next;
        let tracking = (track === null || track === void 0 ? void 0 : track.node) == parent ? track : null;
        let length = 0;
        for (let child of this.children) {
            child.sync(track);
            length += child.length + child.breakAfter;
            next = prev ? prev.nextSibling : parent.firstChild;
            if (tracking && next != child.dom)
                tracking.written = true;
            if (child.dom.parentNode == parent) {
                while (next && next != child.dom)
                    next = rm$1(next);
            }
            else {
                parent.insertBefore(child.dom, next);
            }
            prev = child.dom;
        }
        next = prev ? prev.nextSibling : parent.firstChild;
        if (tracking && next)
            tracking.written = true;
        while (next)
            next = rm$1(next);
        this.length = length;
    }
}
// Remove a DOM node and return its next sibling.
function rm$1(dom) {
    let next = dom.nextSibling;
    dom.parentNode.removeChild(dom);
    return next;
}
// The top-level tile. Its dom property equals view.contentDOM.
class DocTile extends CompositeTile {
    constructor(view, dom) {
        super(dom);
        this.view = view;
    }
    owns(tile) {
        for (; tile; tile = tile.parent)
            if (tile == this)
                return true;
        return false;
    }
    isBlock() { return true; }
    nearest(dom) {
        for (;;) {
            if (!dom)
                return null;
            let tile = Tile.get(dom);
            if (tile && this.owns(tile))
                return tile;
            dom = dom.parentNode;
        }
    }
    blockTiles(f) {
        for (let stack = [], cur = this, i = 0, pos = 0;;) {
            if (i == cur.children.length) {
                if (!stack.length)
                    return;
                cur = cur.parent;
                if (cur.breakAfter)
                    pos++;
                i = stack.pop();
            }
            else {
                let next = cur.children[i++];
                if (next instanceof BlockWrapperTile) {
                    stack.push(i);
                    cur = next;
                    i = 0;
                }
                else {
                    let end = pos + next.length;
                    let result = f(next, pos);
                    if (result !== undefined)
                        return result;
                    pos = end + next.breakAfter;
                }
            }
        }
    }
    // Find the block at the given position. If side < -1, make sure to
    // stay before block widgets at that position, if side > 1, after
    // such widgets (used for selection drawing, which needs to be able
    // to get coordinates for positions that aren't valid cursor positions).
    resolveBlock(pos, side) {
        let before, beforeOff = -1, after, afterOff = -1;
        this.blockTiles((tile, off) => {
            let end = off + tile.length;
            if (pos >= off && pos <= end) {
                if (tile.isWidget() && side >= -1 && side <= 1) {
                    if (tile.flags & 32 /* TileFlag.After */)
                        return true;
                    if (tile.flags & 16 /* TileFlag.Before */)
                        before = undefined;
                }
                if ((off < pos || pos == end && (side < -1 ? tile.length : tile.covers(1))) &&
                    (!before || !tile.isWidget() && before.isWidget())) {
                    before = tile;
                    beforeOff = pos - off;
                }
                if ((end > pos || pos == off && (side > 1 ? tile.length : tile.covers(-1))) &&
                    (!after || !tile.isWidget() && after.isWidget())) {
                    after = tile;
                    afterOff = pos - off;
                }
            }
        });
        if (!before && !after)
            throw new Error("No tile at position " + pos);
        return before && side < 0 || !after ? { tile: before, offset: beforeOff } : { tile: after, offset: afterOff };
    }
}
class BlockWrapperTile extends CompositeTile {
    constructor(dom, wrapper) {
        super(dom);
        this.wrapper = wrapper;
    }
    isBlock() { return true; }
    covers(side) {
        if (!this.children.length)
            return false;
        return side < 0 ? this.children[0].covers(-1) : this.lastChild.covers(1);
    }
    get domAttrs() { return this.wrapper.attributes; }
    static of(wrapper, dom) {
        let tile = new BlockWrapperTile(dom || document.createElement(wrapper.tagName), wrapper);
        if (!dom)
            tile.flags |= 4 /* TileFlag.AttrsDirty */;
        return tile;
    }
}
class LineTile extends CompositeTile {
    constructor(dom, attrs) {
        super(dom);
        this.attrs = attrs;
    }
    isLine() { return true; }
    static start(attrs, dom, keepAttrs) {
        let line = new LineTile(dom || document.createElement("div"), attrs);
        if (!dom || !keepAttrs)
            line.flags |= 4 /* TileFlag.AttrsDirty */;
        return line;
    }
    get domAttrs() { return this.attrs; }
    // Find the tile associated with a given position in this line.
    resolveInline(pos, side, forCoords) {
        let before = null, beforeOff = -1, after = null, afterOff = -1;
        function scan(tile, pos) {
            for (let i = 0, off = 0; i < tile.children.length && off <= pos; i++) {
                let child = tile.children[i], end = off + child.length;
                if (end >= pos) {
                    if (child.isComposite()) {
                        scan(child, pos - off);
                    }
                    else if ((!after || after.isHidden && (side > 0 || forCoords && onSameLine(after, child))) &&
                        (end > pos || (child.flags & 32 /* TileFlag.After */))) {
                        after = child;
                        afterOff = pos - off;
                    }
                    else if (off < pos || (child.flags & 16 /* TileFlag.Before */) && !child.isHidden) {
                        before = child;
                        beforeOff = pos - off;
                    }
                }
                off = end;
            }
        }
        scan(this, pos);
        let target = ((side < 0 ? before : after) || before || after);
        return target ? { tile: target, offset: target == before ? beforeOff : afterOff } : null;
    }
    coordsIn(pos, side) {
        let found = this.resolveInline(pos, side, true);
        if (!found)
            return fallbackRect(this);
        return found.tile.coordsIn(Math.max(0, found.offset), side);
    }
    domIn(pos, side) {
        let found = this.resolveInline(pos, side);
        if (found) {
            let { tile, offset } = found;
            if (this.dom.contains(tile.dom)) {
                if (tile.isText())
                    return new DOMPos(tile.dom, Math.min(tile.dom.nodeValue.length, offset));
                return tile.domPosFor(offset, tile.flags & 16 /* TileFlag.Before */ ? 1 : tile.flags & 32 /* TileFlag.After */ ? -1 : side);
            }
            let parent = found.tile.parent, saw = false;
            for (let ch of parent.children) {
                if (saw)
                    return new DOMPos(ch.dom, 0);
                if (ch == found.tile) {
                    saw = true;
                }
            }
        }
        return new DOMPos(this.dom, 0);
    }
}
function fallbackRect(tile) {
    let last = tile.dom.lastChild;
    if (!last)
        return tile.dom.getBoundingClientRect();
    let rects = clientRectsFor(last);
    return rects[rects.length - 1] || null;
}
function onSameLine(a, b) {
    let posA = a.coordsIn(0, 1), posB = b.coordsIn(0, 1);
    return posA && posB && posB.top < posA.bottom;
}
class MarkTile extends CompositeTile {
    constructor(dom, mark) {
        super(dom);
        this.mark = mark;
    }
    get domAttrs() { return this.mark.attrs; }
    static of(mark, dom) {
        let tile = new MarkTile(dom || document.createElement(mark.tagName), mark);
        if (!dom)
            tile.flags |= 4 /* TileFlag.AttrsDirty */;
        return tile;
    }
}
class TextTile extends Tile {
    constructor(dom, text) {
        super(dom, text.length);
        this.text = text;
    }
    sync(track) {
        if (this.flags & 2 /* TileFlag.Synced */)
            return;
        super.sync(track);
        if (this.dom.nodeValue != this.text) {
            if (track && track.node == this.dom)
                track.written = true;
            this.dom.nodeValue = this.text;
        }
    }
    isText() { return true; }
    toString() { return JSON.stringify(this.text); }
    coordsIn(pos, side) {
        let length = this.dom.nodeValue.length;
        if (pos > length)
            pos = length;
        let from = pos, to = pos, flatten = 0;
        if (pos == 0 && side < 0 || pos == length && side >= 0) {
            if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges
                if (pos) {
                    from--;
                    flatten = 1;
                } // FIXME this is wrong in RTL text
                else if (to < length) {
                    to++;
                    flatten = -1;
                }
            }
        }
        else {
            if (side < 0)
                from--;
            else if (to < length)
                to++;
        }
        let rects = textRange(this.dom, from, to).getClientRects();
        if (!rects.length)
            return null;
        let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1];
        if (browser.safari && !flatten && rect.width == 0)
            rect = Array.prototype.find.call(rects, r => r.width) || rect;
        return flatten ? flattenRect(rect, flatten < 0) : rect || null;
    }
    static of(text, dom) {
        let tile = new TextTile(dom || document.createTextNode(text), text);
        if (!dom)
            tile.flags |= 2 /* TileFlag.Synced */;
        return tile;
    }
}
class WidgetTile extends Tile {
    constructor(dom, length, widget, flags) {
        super(dom, length, flags);
        this.widget = widget;
    }
    isWidget() { return true; }
    get isHidden() { return this.widget.isHidden; }
    covers(side) {
        if (this.flags & 48 /* TileFlag.PointWidget */)
            return false;
        return (this.flags & (side < 0 ? 64 /* TileFlag.IncStart */ : 128 /* TileFlag.IncEnd */)) > 0;
    }
    coordsIn(pos, side) { return this.coordsInWidget(pos, side, false); }
    coordsInWidget(pos, side, block) {
        let custom = this.widget.coordsAt(this.dom, pos, side);
        if (custom)
            return custom;
        if (block) {
            return flattenRect(this.dom.getBoundingClientRect(), this.length ? pos == 0 : side <= 0);
        }
        else {
            let rects = this.dom.getClientRects(), rect = null;
            if (!rects.length)
                return null;
            let fromBack = (this.flags & 16 /* TileFlag.Before */) ? true : (this.flags & 32 /* TileFlag.After */) ? false : pos > 0;
            for (let i = fromBack ? rects.length - 1 : 0;; i += (fromBack ? -1 : 1)) {
                rect = rects[i];
                if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom)
                    break;
            }
            return flattenRect(rect, !fromBack);
        }
    }
    get overrideDOMText() {
        if (!this.length)
            return dist_Text.empty;
        let { root } = this;
        if (!root)
            return dist_Text.empty;
        let start = this.posAtStart;
        return root.view.state.doc.slice(start, start + this.length);
    }
    destroy() {
        super.destroy();
        this.widget.destroy(this.dom);
    }
    static of(widget, view, length, flags, dom) {
        if (!dom) {
            dom = widget.toDOM(view);
            if (!widget.editable)
                dom.contentEditable = "false";
        }
        return new WidgetTile(dom, length, widget, flags);
    }
}
// These are drawn around uneditable widgets to avoid a number of
// browser bugs that show up when the cursor is directly next to
// uneditable inline content.
class WidgetBufferTile extends Tile {
    constructor(flags) {
        let img = document.createElement("img");
        img.className = "cm-widgetBuffer";
        img.setAttribute("aria-hidden", "true");
        super(img, 0, flags);
    }
    get isHidden() { return true; }
    get overrideDOMText() { return dist_Text.empty; }
    coordsIn(pos) { return this.dom.getBoundingClientRect(); }
}
// Represents a position in the tile tree.
class TilePointer {
    constructor(top) {
        this.index = 0;
        this.beforeBreak = false;
        this.parents = [];
        this.tile = top;
    }
    // Advance by the given distance. If side is -1, stop leaving or
    // entering tiles, or skipping zero-length tiles, once the distance
    // has been traversed. When side is 1, leave, enter, or skip
    // everything at the end position.
    advance(dist, side, walker) {
        let { tile, index, beforeBreak, parents } = this;
        while (dist || side > 0) {
            if (!tile.isComposite()) {
                if (index == tile.length) {
                    beforeBreak = !!tile.breakAfter;
                    ({ tile, index } = parents.pop());
                    index++;
                }
                else if (!dist) {
                    break;
                }
                else {
                    let take = Math.min(dist, tile.length - index);
                    if (walker)
                        walker.skip(tile, index, index + take);
                    dist -= take;
                    index += take;
                }
            }
            else if (beforeBreak) {
                if (!dist)
                    break;
                if (walker)
                    walker.break();
                dist--;
                beforeBreak = false;
            }
            else if (index == tile.children.length) {
                if (!dist && !parents.length)
                    break;
                if (walker)
                    walker.leave(tile);
                beforeBreak = !!tile.breakAfter;
                ({ tile, index } = parents.pop());
                index++;
            }
            else {
                let next = tile.children[index], brk = next.breakAfter;
                if ((side > 0 ? next.length <= dist : next.length < dist) &&
                    (!walker || walker.skip(next, 0, next.length) !== false || !next.isComposite)) {
                    beforeBreak = !!brk;
                    index++;
                    dist -= next.length;
                }
                else {
                    parents.push({ tile, index });
                    tile = next;
                    index = 0;
                    if (walker && next.isComposite())
                        walker.enter(next);
                }
            }
        }
        this.tile = tile;
        this.index = index;
        this.beforeBreak = beforeBreak;
        return this;
    }
    get root() { return (this.parents.length ? this.parents[0].tile : this.tile); }
}

// Used to track open block wrappers
class OpenWrapper {
    constructor(from, to, wrapper, rank) {
        this.from = from;
        this.to = to;
        this.wrapper = wrapper;
        this.rank = rank;
    }
}
// This class builds up a new document tile using input from either
// iteration over the old tree or iteration over the document +
// decorations. The add* methods emit elements into the tile
// structure. To avoid awkward synchronization issues, marks and block
// wrappers are treated as belonging to to their content, rather than
// opened/closed independently.
//
// All composite tiles that are touched by changes are rebuilt,
// reusing as much of the old tree (either whole nodes or just DOM
// elements) as possible. The new tree is built without the Synced
// flag, and then synced (during which DOM parent/child relations are
// fixed up, text nodes filled in, and attributes added) in a second
// phase.
class TileBuilder {
    constructor(cache, root, blockWrappers) {
        this.cache = cache;
        this.root = root;
        this.blockWrappers = blockWrappers;
        this.curLine = null;
        this.lastBlock = null;
        this.afterWidget = null;
        this.pos = 0;
        this.wrappers = [];
        this.wrapperPos = 0;
    }
    addText(text, marks, openStart, tile) {
        var _a;
        this.flushBuffer();
        let parent = this.ensureMarks(marks, openStart);
        let prev = parent.lastChild;
        if (prev && prev.isText() && !(prev.flags & 8 /* TileFlag.Composition */)) {
            this.cache.reused.set(prev, 2 /* Reused.DOM */);
            let tile = parent.children[parent.children.length - 1] = new TextTile(prev.dom, prev.text + text);
            tile.parent = parent;
        }
        else {
            parent.append(tile || TextTile.of(text, (_a = this.cache.find(TextTile)) === null || _a === void 0 ? void 0 : _a.dom));
        }
        this.pos += text.length;
        this.afterWidget = null;
    }
    addComposition(composition, context) {
        let line = this.curLine;
        if (line.dom != context.line.dom) {
            line.setDOM(this.cache.reused.has(context.line) ? freeNode(context.line.dom) : context.line.dom);
            this.cache.reused.set(context.line, 2 /* Reused.DOM */);
        }
        let head = line;
        for (let i = context.marks.length - 1; i >= 0; i--) {
            let mark = context.marks[i];
            let last = head.lastChild;
            if (last instanceof MarkTile && last.mark.eq(mark.mark)) {
                if (last.dom != mark.dom)
                    last.setDOM(freeNode(mark.dom));
                head = last;
            }
            else {
                if (this.cache.reused.get(mark)) {
                    let tile = Tile.get(mark.dom);
                    if (tile)
                        tile.setDOM(freeNode(mark.dom));
                }
                let nw = MarkTile.of(mark.mark, mark.dom);
                head.append(nw);
                head = nw;
            }
            this.cache.reused.set(mark, 2 /* Reused.DOM */);
        }
        let oldTile = Tile.get(composition.text);
        if (oldTile)
            this.cache.reused.set(oldTile, 2 /* Reused.DOM */);
        let text = new TextTile(composition.text, composition.text.nodeValue);
        text.flags |= 8 /* TileFlag.Composition */;
        head.append(text);
    }
    addInlineWidget(widget, marks, openStart) {
        // Adjacent same-side-facing non-replacing widgets don't need buffers between them
        let noSpace = this.afterWidget && (widget.flags & 48 /* TileFlag.PointWidget */) &&
            (this.afterWidget.flags & 48 /* TileFlag.PointWidget */) == (widget.flags & 48 /* TileFlag.PointWidget */);
        if (!noSpace)
            this.flushBuffer();
        let parent = this.ensureMarks(marks, openStart);
        if (!noSpace && !(widget.flags & 16 /* TileFlag.Before */))
            parent.append(this.getBuffer(1));
        parent.append(widget);
        this.pos += widget.length;
        this.afterWidget = widget;
    }
    addMark(tile, marks, openStart) {
        this.flushBuffer();
        let parent = this.ensureMarks(marks, openStart);
        parent.append(tile);
        this.pos += tile.length;
        this.afterWidget = null;
    }
    addBlockWidget(widget) {
        this.getBlockPos().append(widget);
        this.pos += widget.length;
        this.lastBlock = widget;
        this.endLine();
    }
    continueWidget(length) {
        let widget = this.afterWidget || this.lastBlock;
        widget.length += length;
        this.pos += length;
    }
    addLineStart(attrs, dom) {
        var _a;
        if (!attrs)
            attrs = lineBaseAttrs;
        let tile = LineTile.start(attrs, dom || ((_a = this.cache.find(LineTile)) === null || _a === void 0 ? void 0 : _a.dom), !!dom);
        this.getBlockPos().append(this.lastBlock = this.curLine = tile);
    }
    addLine(tile) {
        this.getBlockPos().append(tile);
        this.pos += tile.length;
        this.lastBlock = tile;
        this.endLine();
    }
    addBreak() {
        this.lastBlock.flags |= 1 /* TileFlag.BreakAfter */;
        this.endLine();
        this.pos++;
    }
    addLineStartIfNotCovered(attrs) {
        if (!this.blockPosCovered())
            this.addLineStart(attrs);
    }
    ensureLine(attrs) {
        if (!this.curLine)
            this.addLineStart(attrs);
    }
    ensureMarks(marks, openStart) {
        var _a;
        let parent = this.curLine;
        for (let i = marks.length - 1; i >= 0; i--) {
            let mark = marks[i], last;
            if (openStart > 0 && (last = parent.lastChild) && last instanceof MarkTile && last.mark.eq(mark)) {
                parent = last;
                openStart--;
            }
            else {
                let tile = MarkTile.of(mark, (_a = this.cache.find(MarkTile, m => m.mark.eq(mark))) === null || _a === void 0 ? void 0 : _a.dom);
                parent.append(tile);
                parent = tile;
                openStart = 0;
            }
        }
        return parent;
    }
    endLine() {
        if (this.curLine) {
            this.flushBuffer();
            let last = this.curLine.lastChild;
            if (!last || !hasContent(this.curLine, false) ||
                last.dom.nodeName != "BR" && last.isWidget() && !(browser.ios && hasContent(this.curLine, true)))
                this.curLine.append(this.cache.findWidget(BreakWidget, 0, 32 /* TileFlag.After */) ||
                    new WidgetTile(BreakWidget.toDOM(), 0, BreakWidget, 32 /* TileFlag.After */));
            this.curLine = this.afterWidget = null;
        }
    }
    updateBlockWrappers() {
        if (this.wrapperPos > this.pos + 10000 /* C.WrapperReset */) {
            this.blockWrappers.goto(this.pos);
            this.wrappers.length = 0;
        }
        for (let i = this.wrappers.length - 1; i >= 0; i--)
            if (this.wrappers[i].to < this.pos)
                this.wrappers.splice(i, 1);
        for (let cur = this.blockWrappers; cur.value && cur.from <= this.pos; cur.next())
            if (cur.to >= this.pos) {
                let wrap = new OpenWrapper(cur.from, cur.to, cur.value, cur.rank), i = this.wrappers.length;
                while (i > 0 && (this.wrappers[i - 1].rank - wrap.rank || this.wrappers[i - 1].to - wrap.to) < 0)
                    i--;
                this.wrappers.splice(i, 0, wrap);
            }
        this.wrapperPos = this.pos;
    }
    getBlockPos() {
        var _a;
        this.updateBlockWrappers();
        let parent = this.root;
        for (let wrap of this.wrappers) {
            let last = parent.lastChild;
            if (wrap.from < this.pos && last instanceof BlockWrapperTile && last.wrapper.eq(wrap.wrapper)) {
                parent = last;
            }
            else {
                let tile = BlockWrapperTile.of(wrap.wrapper, (_a = this.cache.find(BlockWrapperTile, t => t.wrapper.eq(wrap.wrapper))) === null || _a === void 0 ? void 0 : _a.dom);
                parent.append(tile);
                parent = tile;
            }
        }
        return parent;
    }
    blockPosCovered() {
        let last = this.lastBlock;
        return last != null && !last.breakAfter && (!last.isWidget() || (last.flags & (32 /* TileFlag.After */ | 128 /* TileFlag.IncEnd */)) > 0);
    }
    getBuffer(side) {
        let flags = 2 /* TileFlag.Synced */ | (side < 0 ? 16 /* TileFlag.Before */ : 32 /* TileFlag.After */);
        let found = this.cache.find(WidgetBufferTile, undefined, 1 /* Reused.Full */);
        if (found)
            found.flags = flags;
        return found || new WidgetBufferTile(flags);
    }
    flushBuffer() {
        if (this.afterWidget && !(this.afterWidget.flags & 32 /* TileFlag.After */)) {
            this.afterWidget.parent.append(this.getBuffer(-1));
            this.afterWidget = null;
        }
    }
}
// Helps getting efficient access to the document text.
class TextStream {
    constructor(doc) {
        this.skipCount = 0;
        this.text = "";
        this.textOff = 0;
        this.cursor = doc.iter();
    }
    skip(len) {
        // Advance the iterator past the replaced content
        if (this.textOff + len <= this.text.length) {
            this.textOff += len;
        }
        else {
            this.skipCount += len - (this.text.length - this.textOff);
            this.text = "";
            this.textOff = 0;
        }
    }
    next(maxLen) {
        if (this.textOff == this.text.length) {
            let { value, lineBreak, done } = this.cursor.next(this.skipCount);
            this.skipCount = 0;
            if (done)
                throw new Error("Ran out of text content when drawing inline views");
            this.text = value;
            let len = this.textOff = Math.min(maxLen, value.length);
            return lineBreak ? null : value.slice(0, len);
        }
        let end = Math.min(this.text.length, this.textOff + maxLen);
        let chars = this.text.slice(this.textOff, end);
        this.textOff = end;
        return chars;
    }
}
// Assign the tile classes bucket numbers for caching.
const buckets = [WidgetTile, LineTile, TextTile, MarkTile, WidgetBufferTile, BlockWrapperTile, DocTile];
for (let i = 0; i < buckets.length; i++)
    buckets[i].bucket = i;
// Leaf tiles and line tiles may be reused in their entirety. All
// others will get new tiles allocated, using the old DOM when
// possible.
class TileCache {
    constructor(view) {
        this.view = view;
        // Buckets are circular buffers, using `index` as the current
        // position.
        this.buckets = buckets.map(() => []);
        this.index = buckets.map(() => 0);
        this.reused = new Map;
    }
    // Put a tile in the cache.
    add(tile) {
        if (tile.demo)
            console.log("Add widget to cache");
        let i = tile.constructor.bucket, bucket = this.buckets[i];
        if (bucket.length < 6 /* C.Bucket */)
            bucket.push(tile);
        else
            bucket[this.index[i] = (this.index[i] + 1) % 6 /* C.Bucket */] = tile;
    }
    find(cls, test, type = 2 /* Reused.DOM */) {
        let i = cls.bucket;
        let bucket = this.buckets[i], off = this.index[i];
        for (let j = bucket.length - 1; j >= 0; j--) {
            // Look at the most recently added items first (last-in, first-out)
            let index = (j + off) % bucket.length, tile = bucket[index];
            if ((!test || test(tile)) && !this.reused.has(tile)) {
                bucket.splice(index, 1);
                if (index < off)
                    this.index[i]--;
                this.reused.set(tile, type);
                return tile;
            }
        }
        return null;
    }
    findWidget(widget, length, flags) {
        let widgets = this.buckets[0];
        if (widget.demo)
            console.log("looking for widget", widget, "in cache", widgets.slice());
        if (widgets.length)
            for (let i = 0, pass = 0;; i++) {
                if (i == widgets.length) {
                    if (pass)
                        return null;
                    pass = 1;
                    i = 0;
                }
                let tile = widgets[i];
                if (!this.reused.has(tile) &&
                    (pass == 0 ? tile.widget.compare(widget)
                        : tile.widget.constructor == widget.constructor && widget.updateDOM(tile.dom, this.view))) {
                    widgets.splice(i, 1);
                    if (i < this.index[0])
                        this.index[0]--;
                    if (tile.length == length && (tile.flags & (496 /* TileFlag.Widget */ | 1 /* TileFlag.BreakAfter */)) == flags) {
                        this.reused.set(tile, 1 /* Reused.Full */);
                        return tile;
                    }
                    else {
                        this.reused.set(tile, 2 /* Reused.DOM */);
                        return new WidgetTile(tile.dom, length, widget, (tile.flags & ~(496 /* TileFlag.Widget */ | 1 /* TileFlag.BreakAfter */)) | flags);
                    }
                }
            }
    }
    reuse(tile) {
        this.reused.set(tile, 1 /* Reused.Full */);
        return tile;
    }
    maybeReuse(tile, type = 2 /* Reused.DOM */) {
        if (this.reused.has(tile))
            return undefined;
        this.reused.set(tile, type);
        return tile.dom;
    }
    clear() {
        for (let i = 0; i < this.buckets.length; i++)
            this.buckets[i].length = this.index[i] = 0;
    }
}
// This class organizes a pass over the document, guided by the array
// of replaced ranges. For ranges that haven't changed, it iterates
// the old tree and copies its content into the new document. For
// changed ranges, it runs a decoration iterator to guide generation
// of content.
class TileUpdate {
    constructor(view, old, blockWrappers, decorations, disallowBlockEffectsFor) {
        this.view = view;
        this.decorations = decorations;
        this.disallowBlockEffectsFor = disallowBlockEffectsFor;
        this.openWidget = false;
        this.openMarks = 0;
        this.cache = new TileCache(view);
        this.text = new TextStream(view.state.doc);
        this.builder = new TileBuilder(this.cache, new DocTile(view, view.contentDOM), dist_RangeSet.iter(blockWrappers));
        this.cache.reused.set(old, 2 /* Reused.DOM */);
        this.old = new TilePointer(old);
        this.reuseWalker = {
            skip: (tile, from, to) => {
                this.cache.add(tile);
                if (tile.isComposite())
                    return false;
            },
            enter: tile => this.cache.add(tile),
            leave: () => { },
            break: () => { }
        };
    }
    run(changes, composition) {
        let compositionContext = composition && this.getCompositionContext(composition.text);
        for (let posA = 0, posB = 0, i = 0;;) {
            let next = i < changes.length ? changes[i++] : null;
            let skipA = next ? next.fromA : this.old.root.length;
            if (skipA > posA) {
                let len = skipA - posA;
                this.preserve(len, !i, !next);
                posA = skipA;
                posB += len;
            }
            if (!next)
                break;
            // Compositions need to be handled specially, forcing the
            // focused text node and its parent nodes to remain stable at
            // that point in the document.
            if (composition && next.fromA <= composition.range.fromA && next.toA >= composition.range.toA) {
                this.forward(next.fromA, composition.range.fromA);
                this.emit(posB, composition.range.fromB);
                this.cache.clear(); // Must not reuse DOM across composition
                this.builder.addComposition(composition, compositionContext);
                this.text.skip(composition.range.toB - composition.range.fromB);
                this.forward(composition.range.fromA, next.toA);
                this.emit(composition.range.toB, next.toB);
            }
            else {
                this.forward(next.fromA, next.toA);
                this.emit(posB, next.toB);
            }
            posB = next.toB;
            posA = next.toA;
        }
        if (this.builder.curLine)
            this.builder.endLine();
        return this.builder.root;
    }
    preserve(length, incStart, incEnd) {
        let activeMarks = getMarks(this.old), openMarks = this.openMarks;
        this.old.advance(length, incEnd ? 1 : -1, {
            skip: (tile, from, to) => {
                if (tile.isWidget()) {
                    if (this.openWidget) {
                        this.builder.continueWidget(to - from);
                    }
                    else {
                        let widget = to > 0 || from < tile.length
                            ? WidgetTile.of(tile.widget, this.view, to - from, tile.flags & 496 /* TileFlag.Widget */, this.cache.maybeReuse(tile))
                            : this.cache.reuse(tile);
                        if (widget.flags & 256 /* TileFlag.Block */) {
                            widget.flags &= ~1 /* TileFlag.BreakAfter */;
                            this.builder.addBlockWidget(widget);
                        }
                        else {
                            this.builder.ensureLine(null);
                            this.builder.addInlineWidget(widget, activeMarks, openMarks);
                            openMarks = activeMarks.length;
                        }
                    }
                }
                else if (tile.isText()) {
                    this.builder.ensureLine(null);
                    if (!from && to == tile.length) {
                        this.builder.addText(tile.text, activeMarks, openMarks, this.cache.reuse(tile));
                    }
                    else {
                        this.cache.add(tile);
                        this.builder.addText(tile.text.slice(from, to), activeMarks, openMarks);
                    }
                    openMarks = activeMarks.length;
                }
                else if (tile.isLine()) {
                    tile.flags &= ~1 /* TileFlag.BreakAfter */;
                    this.cache.reused.set(tile, 1 /* Reused.Full */);
                    this.builder.addLine(tile);
                }
                else if (tile instanceof WidgetBufferTile) {
                    this.cache.add(tile);
                }
                else if (tile instanceof MarkTile) {
                    this.builder.ensureLine(null);
                    this.builder.addMark(tile, activeMarks, openMarks);
                    this.cache.reused.set(tile, 1 /* Reused.Full */);
                    openMarks = activeMarks.length;
                }
                else {
                    return false;
                }
                this.openWidget = false;
            },
            enter: (tile) => {
                if (tile.isLine()) {
                    this.builder.addLineStart(tile.attrs, this.cache.maybeReuse(tile));
                }
                else {
                    this.cache.add(tile);
                    if (tile instanceof MarkTile)
                        activeMarks.unshift(tile.mark);
                }
                this.openWidget = false;
            },
            leave: (tile) => {
                if (tile.isLine()) {
                    if (activeMarks.length)
                        activeMarks.length = openMarks = 0;
                }
                else if (tile instanceof MarkTile) {
                    activeMarks.shift();
                    openMarks = Math.min(openMarks, activeMarks.length);
                }
            },
            break: () => {
                this.builder.addBreak();
                this.openWidget = false;
            },
        });
        this.text.skip(length);
    }
    emit(from, to) {
        let pendingLineAttrs = null;
        let b = this.builder, markCount = 0;
        let openEnd = dist_RangeSet.spans(this.decorations, from, to, {
            point: (from, to, deco, active, openStart, index) => {
                if (deco instanceof PointDecoration) {
                    if (this.disallowBlockEffectsFor[index]) {
                        if (deco.block)
                            throw new RangeError("Block decorations may not be specified via plugins");
                        if (to > this.view.state.doc.lineAt(from).to)
                            throw new RangeError("Decorations that replace line breaks may not be specified via plugins");
                    }
                    markCount = active.length;
                    if (openStart > active.length) {
                        b.continueWidget(to - from);
                    }
                    else {
                        let widget = deco.widget || (deco.block ? NullWidget.block : NullWidget.inline);
                        let flags = widgetFlags(deco);
                        let tile = this.cache.findWidget(widget, to - from, flags) || WidgetTile.of(widget, this.view, to - from, flags);
                        if (deco.block) {
                            if (deco.startSide > 0)
                                b.addLineStartIfNotCovered(pendingLineAttrs);
                            b.addBlockWidget(tile);
                        }
                        else {
                            b.ensureLine(pendingLineAttrs);
                            b.addInlineWidget(tile, active, openStart);
                        }
                    }
                    pendingLineAttrs = null;
                }
                else {
                    pendingLineAttrs = addLineDeco(pendingLineAttrs, deco);
                }
                if (to > from)
                    this.text.skip(to - from);
            },
            span: (from, to, active, openStart) => {
                for (let pos = from; pos < to;) {
                    let chars = this.text.next(Math.min(512 /* C.Chunk */, to - pos));
                    if (chars == null) { // Line break
                        b.addLineStartIfNotCovered(pendingLineAttrs);
                        b.addBreak();
                        pos++;
                    }
                    else {
                        b.ensureLine(pendingLineAttrs);
                        b.addText(chars, active, openStart);
                        pos += chars.length;
                    }
                    pendingLineAttrs = null;
                }
            }
        });
        b.addLineStartIfNotCovered(pendingLineAttrs);
        this.openWidget = openEnd > markCount;
        this.openMarks = openEnd;
    }
    forward(from, to) {
        if (to - from <= 10) {
            this.old.advance(to - from, 1, this.reuseWalker);
        }
        else {
            this.old.advance(5, -1, this.reuseWalker);
            this.old.advance(to - from - 10, -1);
            this.old.advance(5, 1, this.reuseWalker);
        }
    }
    getCompositionContext(text) {
        let marks = [], line = null;
        for (let parent = text.parentNode;; parent = parent.parentNode) {
            let tile = Tile.get(parent);
            if (parent == this.view.contentDOM)
                break;
            if (tile instanceof MarkTile)
                marks.push(tile);
            else if (tile === null || tile === void 0 ? void 0 : tile.isLine())
                line = tile;
            else if (parent.nodeName == "DIV" && !line && parent != this.view.contentDOM)
                line = new LineTile(parent, lineBaseAttrs);
            else
                marks.push(MarkTile.of(new MarkDecoration({ tagName: parent.nodeName.toLowerCase(), attributes: getAttrs(parent) }), parent));
        }
        return { line: line, marks };
    }
}
function hasContent(tile, requireText) {
    let scan = (tile) => {
        for (let ch of tile.children)
            if ((requireText ? ch.isText() : ch.length) || scan(ch))
                return true;
        return false;
    };
    return scan(tile);
}
function widgetFlags(deco) {
    let flags = deco.isReplace ? (deco.startSide < 0 ? 64 /* TileFlag.IncStart */ : 0) | (deco.endSide > 0 ? 128 /* TileFlag.IncEnd */ : 0)
        : (deco.startSide > 0 ? 32 /* TileFlag.After */ : 16 /* TileFlag.Before */);
    if (deco.block)
        flags |= 256 /* TileFlag.Block */;
    return flags;
}
const lineBaseAttrs = { class: "cm-line" };
function addLineDeco(value, deco) {
    let attrs = deco.spec.attributes, cls = deco.spec.class;
    if (!attrs && !cls)
        return value;
    if (!value)
        value = { class: "cm-line" };
    if (attrs)
        combineAttrs(attrs, value);
    if (cls)
        value.class += " " + cls;
    return value;
}
function getMarks(ptr) {
    let found = [];
    for (let i = ptr.parents.length; i > 1; i--) {
        let tile = i == ptr.parents.length ? ptr.tile : ptr.parents[i].tile;
        if (tile instanceof MarkTile)
            found.push(tile.mark);
    }
    return found;
}
function freeNode(node) {
    let tile = Tile.get(node);
    if (tile)
        tile.setDOM(node.cloneNode());
    return node;
}
class NullWidget extends WidgetType {
    constructor(tag) {
        super();
        this.tag = tag;
    }
    eq(other) { return other.tag == this.tag; }
    toDOM() { return document.createElement(this.tag); }
    updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; }
    get isHidden() { return true; }
}
NullWidget.inline = /*@__PURE__*/new NullWidget("span");
NullWidget.block = /*@__PURE__*/new NullWidget("div");
const BreakWidget = /*@__PURE__*/new class extends WidgetType {
    toDOM() { return document.createElement("br"); }
    get isHidden() { return true; }
    get editable() { return true; }
};

class DocView {
    constructor(view) {
        this.view = view;
        this.decorations = [];
        this.blockWrappers = [];
        this.dynamicDecorationMap = [false];
        this.domChanged = null;
        this.hasComposition = null;
        this.editContextFormatting = dist_Decoration.none;
        this.lastCompositionAfterCursor = false;
        // Track a minimum width for the editor. When measuring sizes in
        // measureVisibleLineHeights, this is updated to point at the width
        // of a given element and its extent in the document. When a change
        // happens in that range, these are reset. That way, once we've seen
        // a line/element of a given length, we keep the editor wide enough
        // to fit at least that element, until it is changed, at which point
        // we forget it again.
        this.minWidth = 0;
        this.minWidthFrom = 0;
        this.minWidthTo = 0;
        // Track whether the DOM selection was set in a lossy way, so that
        // we don't mess it up when reading it back it
        this.impreciseAnchor = null;
        this.impreciseHead = null;
        this.forceSelection = false;
        // Used by the resize observer to ignore resizes that we caused
        // ourselves
        this.lastUpdate = Date.now();
        this.updateDeco();
        this.tile = new DocTile(view, view.contentDOM);
        this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], null);
    }
    // Update the document view to a given state.
    update(update) {
        var _a;
        let changedRanges = update.changedRanges;
        if (this.minWidth > 0 && changedRanges.length) {
            if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) {
                this.minWidth = this.minWidthFrom = this.minWidthTo = 0;
            }
            else {
                this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);
                this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);
            }
        }
        this.updateEditContextFormatting(update);
        let readCompositionAt = -1;
        if (this.view.inputState.composing >= 0 && !this.view.observer.editContext) {
            if ((_a = this.domChanged) === null || _a === void 0 ? void 0 : _a.newSel)
                readCompositionAt = this.domChanged.newSel.head;
            else if (!touchesComposition(update.changes, this.hasComposition) && !update.selectionSet)
                readCompositionAt = update.state.selection.main.head;
        }
        let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update.changes, readCompositionAt) : null;
        this.domChanged = null;
        if (this.hasComposition) {
            let { from, to } = this.hasComposition;
            changedRanges = new ChangedRange(from, to, update.changes.mapPos(from, -1), update.changes.mapPos(to, 1))
                .addToSet(changedRanges.slice());
        }
        this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null;
        // When the DOM nodes around the selection are moved to another
        // parent, Chrome sometimes reports a different selection through
        // getSelection than the one that it actually shows to the user.
        // This forces a selection update when lines are joined to work
        // around that. Issue #54
        if ((browser.ie || browser.chrome) && !composition && update &&
            update.state.doc.lines != update.startState.doc.lines)
            this.forceSelection = true;
        let prevDeco = this.decorations, prevWrappers = this.blockWrappers;
        this.updateDeco();
        let decoDiff = findChangedDeco(prevDeco, this.decorations, update.changes);
        if (decoDiff.length)
            changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);
        let blockDiff = findChangedWrappers(prevWrappers, this.blockWrappers, update.changes);
        if (blockDiff.length)
            changedRanges = ChangedRange.extendWithRanges(changedRanges, blockDiff);
        if (composition && !changedRanges.some(r => r.fromA <= composition.range.fromA && r.toA >= composition.range.toA))
            changedRanges = composition.range.addToSet(changedRanges.slice());
        if ((this.tile.flags & 2 /* TileFlag.Synced */) && changedRanges.length == 0) {
            return false;
        }
        else {
            this.updateInner(changedRanges, composition);
            if (update.transactions.length)
                this.lastUpdate = Date.now();
            return true;
        }
    }
    // Used by update and the constructor do perform the actual DOM
    // update
    updateInner(changes, composition) {
        this.view.viewState.mustMeasureContent = true;
        let { observer } = this.view;
        observer.ignore(() => {
            if (composition || changes.length) {
                let oldTile = this.tile;
                let builder = new TileUpdate(this.view, oldTile, this.blockWrappers, this.decorations, this.dynamicDecorationMap);
                this.tile = builder.run(changes, composition);
                destroyDropped(oldTile, builder.cache.reused);
            }
            // Lock the height during redrawing, since Chrome sometimes
            // messes with the scroll position during DOM mutation (though
            // no relayout is triggered and I cannot imagine how it can
            // recompute the scroll position without a layout)
            this.tile.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + "px";
            this.tile.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : "";
            // Chrome will sometimes, when DOM mutations occur directly
            // around the selection, get confused and report a different
            // selection from the one it displays (issue #218). This tries
            // to detect that situation.
            let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined;
            this.tile.sync(track);
            if (track && (track.written || observer.selectionRange.focusNode != track.node || !this.tile.dom.contains(track.node)))
                this.forceSelection = true;
            this.tile.dom.style.height = "";
        });
        let gaps = [];
        if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length)
            for (let child of this.tile.children)
                if (child.isWidget() && child.widget instanceof BlockGapWidget)
                    gaps.push(child.dom);
        observer.updateGaps(gaps);
    }
    updateEditContextFormatting(update) {
        this.editContextFormatting = this.editContextFormatting.map(update.changes);
        for (let tr of update.transactions)
            for (let effect of tr.effects)
                if (effect.is(setEditContextFormatting)) {
                    this.editContextFormatting = effect.value;
                }
    }
    // Sync the DOM selection to this.state.selection
    updateSelection(mustRead = false, fromPointer = false) {
        if (mustRead || !this.view.observer.selectionRange.focusNode)
            this.view.observer.readSelectionRange();
        let { dom } = this.tile;
        let activeElt = this.view.root.activeElement, focused = activeElt == dom;
        let selectionNotFocus = !focused && !(this.view.state.facet(editable) || dom.tabIndex > -1) &&
            hasSelection(dom, this.view.observer.selectionRange) && !(activeElt && dom.contains(activeElt));
        if (!(focused || fromPointer || selectionNotFocus))
            return;
        let force = this.forceSelection;
        this.forceSelection = false;
        let main = this.view.state.selection.main, anchor, head;
        if (main.empty) {
            head = anchor = this.inlineDOMNearPos(main.anchor, main.assoc || 1);
        }
        else {
            head = this.inlineDOMNearPos(main.head, main.head == main.from ? 1 : -1);
            anchor = this.inlineDOMNearPos(main.anchor, main.anchor == main.from ? 1 : -1);
        }
        // Always reset on Firefox when next to an uneditable node to
        // avoid invisible cursor bugs (#111)
        if (browser.gecko && main.empty && !this.hasComposition && betweenUneditable(anchor)) {
            let dummy = document.createTextNode("");
            this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));
            anchor = head = new DOMPos(dummy, 0);
            force = true;
        }
        let domSel = this.view.observer.selectionRange;
        // If the selection is already here, or in an equivalent position, don't touch it
        if (force || !domSel.focusNode || (!isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) ||
            !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) && !this.suppressWidgetCursorChange(domSel, main)) {
            this.view.observer.ignore(() => {
                // Chrome Android will hide the virtual keyboard when tapping
                // inside an uneditable node, and not bring it back when we
                // move the cursor to its proper position. This tries to
                // restore the keyboard by cycling focus.
                if (browser.android && browser.chrome && dom.contains(domSel.focusNode) &&
                    inUneditable(domSel.focusNode, dom)) {
                    dom.blur();
                    dom.focus({ preventScroll: true });
                }
                let rawSel = getSelection(this.view.root);
                if (!rawSel) ;
                else if (main.empty) {
                    // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076
                    if (browser.gecko) {
                        let nextTo = nextToUneditable(anchor.node, anchor.offset);
                        if (nextTo && nextTo != (1 /* NextTo.Before */ | 2 /* NextTo.After */)) {
                            let text = (nextTo == 1 /* NextTo.Before */ ? textNodeBefore : textNodeAfter)(anchor.node, anchor.offset);
                            if (text)
                                anchor = new DOMPos(text.node, text.offset);
                        }
                    }
                    rawSel.collapse(anchor.node, anchor.offset);
                    if (main.bidiLevel != null && rawSel.caretBidiLevel !== undefined)
                        rawSel.caretBidiLevel = main.bidiLevel;
                }
                else if (rawSel.extend) {
                    // Selection.extend can be used to create an 'inverted' selection
                    // (one where the focus is before the anchor), but not all
                    // browsers support it yet.
                    rawSel.collapse(anchor.node, anchor.offset);
                    // Safari will ignore the call above when the editor is
                    // hidden, and then raise an error on the call to extend
                    // (#940).
                    try {
                        rawSel.extend(head.node, head.offset);
                    }
                    catch (_) { }
                }
                else {
                    // Primitive (IE) way
                    let range = document.createRange();
                    if (main.anchor > main.head)
                        [anchor, head] = [head, anchor];
                    range.setEnd(head.node, head.offset);
                    range.setStart(anchor.node, anchor.offset);
                    rawSel.removeAllRanges();
                    rawSel.addRange(range);
                }
                if (selectionNotFocus && this.view.root.activeElement == dom) {
                    dom.blur();
                    if (activeElt)
                        activeElt.focus();
                }
            });
            this.view.observer.setSelectionRange(anchor, head);
        }
        this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);
        this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);
    }
    // If a zero-length widget is inserted next to the cursor during
    // composition, avoid moving it across it and disrupting the
    // composition.
    suppressWidgetCursorChange(sel, cursor) {
        return this.hasComposition && cursor.empty &&
            isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) &&
            this.posFromDOM(sel.focusNode, sel.focusOffset) == cursor.head;
    }
    enforceCursorAssoc() {
        if (this.hasComposition)
            return;
        let { view } = this, cursor = view.state.selection.main;
        let sel = getSelection(view.root);
        let { anchorNode, anchorOffset } = view.observer.selectionRange;
        if (!sel || !cursor.empty || !cursor.assoc || !sel.modify)
            return;
        let line = this.lineAt(cursor.head, cursor.assoc);
        if (!line)
            return;
        let lineStart = line.posAtStart;
        if (cursor.head == lineStart || cursor.head == lineStart + line.length)
            return;
        let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1);
        if (!before || !after || before.bottom > after.top)
            return;
        let dom = this.domAtPos(cursor.head + cursor.assoc, cursor.assoc);
        sel.collapse(dom.node, dom.offset);
        sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary");
        // This can go wrong in corner cases like single-character lines,
        // so check and reset if necessary.
        view.observer.readSelectionRange();
        let newRange = view.observer.selectionRange;
        if (view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from)
            sel.collapse(anchorNode, anchorOffset);
    }
    posFromDOM(node, offset) {
        let tile = this.tile.nearest(node);
        if (!tile)
            return this.tile.dom.compareDocumentPosition(node) & 2 /* PRECEDING */ ? 0 : this.view.state.doc.length;
        let start = tile.posAtStart;
        if (tile.isComposite()) {
            let after;
            if (node == tile.dom) {
                after = tile.dom.childNodes[offset];
            }
            else {
                let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;
                for (;;) {
                    let parent = node.parentNode;
                    if (parent == tile.dom)
                        break;
                    if (bias == 0 && parent.firstChild != parent.lastChild) {
                        if (node == parent.firstChild)
                            bias = -1;
                        else
                            bias = 1;
                    }
                    node = parent;
                }
                if (bias < 0)
                    after = node;
                else
                    after = node.nextSibling;
            }
            if (after == tile.dom.firstChild)
                return start;
            while (after && !Tile.get(after))
                after = after.nextSibling;
            if (!after)
                return start + tile.length;
            for (let i = 0, pos = start;; i++) {
                let child = tile.children[i];
                if (child.dom == after)
                    return pos;
                pos += child.length + child.breakAfter;
            }
        }
        else if (tile.isText()) {
            return node == tile.dom ? start + offset : start + (offset ? tile.length : 0);
        }
        else {
            return start;
        }
    }
    domAtPos(pos, side) {
        let { tile, offset } = this.tile.resolveBlock(pos, side);
        if (tile.isWidget())
            return tile.domPosFor(pos, side);
        return tile.domIn(offset, side);
    }
    inlineDOMNearPos(pos, side) {
        let before, beforeOff = -1, beforeBad = false;
        let after, afterOff = -1, afterBad = false;
        this.tile.blockTiles((tile, off) => {
            if (tile.isWidget()) {
                if ((tile.flags & 32 /* TileFlag.After */) && off >= pos)
                    return true;
                if (tile.flags & 16 /* TileFlag.Before */)
                    beforeBad = true;
            }
            else {
                let end = off + tile.length;
                if (off <= pos) {
                    before = tile;
                    beforeOff = pos - off;
                    beforeBad = end < pos;
                }
                if (end >= pos && !after) {
                    after = tile;
                    afterOff = pos - off;
                    afterBad = off > pos;
                }
                if (off > pos && after)
                    return true;
            }
        });
        if (!before && !after)
            return this.domAtPos(pos, side);
        if (beforeBad && after)
            before = null;
        else if (afterBad && before)
            after = null;
        return before && side < 0 || !after ? before.domIn(beforeOff, side) : after.domIn(afterOff, side);
    }
    coordsAt(pos, side) {
        let { tile, offset } = this.tile.resolveBlock(pos, side);
        if (tile.isWidget()) {
            if (tile.widget instanceof BlockGapWidget)
                return null;
            return tile.coordsInWidget(offset, side, true);
        }
        return tile.coordsIn(offset, side);
    }
    lineAt(pos, side) {
        let { tile } = this.tile.resolveBlock(pos, side);
        return tile.isLine() ? tile : null;
    }
    coordsForChar(pos) {
        let { tile, offset } = this.tile.resolveBlock(pos, 1);
        if (!tile.isLine())
            return null;
        function scan(tile, offset) {
            if (tile.isComposite()) {
                for (let ch of tile.children) {
                    if (ch.length >= offset) {
                        let found = scan(ch, offset);
                        if (found)
                            return found;
                    }
                    offset -= ch.length;
                    if (offset < 0)
                        break;
                }
            }
            else if (tile.isText() && offset < tile.length) {
                let end = dist_findClusterBreak(tile.text, offset);
                if (end == offset)
                    return null;
                let rects = textRange(tile.dom, offset, end).getClientRects();
                for (let i = 0; i < rects.length; i++) {
                    let rect = rects[i];
                    if (i == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right)
                        return rect;
                }
            }
            return null;
        }
        return scan(tile, offset);
    }
    measureVisibleLineHeights(viewport) {
        let result = [], { from, to } = viewport;
        let contentWidth = this.view.contentDOM.clientWidth;
        let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;
        let widest = -1, ltr = this.view.textDirection == Direction.LTR;
        let spaceAbove = 0;
        let scan = (tile, pos, measureBounds) => {
            for (let i = 0; i < tile.children.length; i++) {
                if (pos > to)
                    break;
                let child = tile.children[i], end = pos + child.length;
                let childRect = child.dom.getBoundingClientRect(), { height } = childRect;
                if (measureBounds && !i)
                    spaceAbove += childRect.top - measureBounds.top;
                if (child instanceof BlockWrapperTile) {
                    if (end > from)
                        scan(child, pos, childRect);
                }
                else if (pos >= from) {
                    if (spaceAbove > 0)
                        result.push(-spaceAbove);
                    result.push(height + spaceAbove);
                    spaceAbove = 0;
                    if (isWider) {
                        let last = child.dom.lastChild;
                        let rects = last ? clientRectsFor(last) : [];
                        if (rects.length) {
                            let rect = rects[rects.length - 1];
                            let width = ltr ? rect.right - childRect.left : childRect.right - rect.left;
                            if (width > widest) {
                                widest = width;
                                this.minWidth = contentWidth;
                                this.minWidthFrom = pos;
                                this.minWidthTo = end;
                            }
                        }
                    }
                }
                if (measureBounds && i == tile.children.length - 1)
                    spaceAbove += measureBounds.bottom - childRect.bottom;
                pos = end + child.breakAfter;
            }
        };
        scan(this.tile, 0, null);
        return result;
    }
    textDirectionAt(pos) {
        let { tile } = this.tile.resolveBlock(pos, 1);
        return getComputedStyle(tile.dom).direction == "rtl" ? Direction.RTL : Direction.LTR;
    }
    measureTextSize() {
        let lineMeasure = this.tile.blockTiles(tile => {
            if (tile.isLine() && tile.children.length && tile.length <= 20) {
                let totalWidth = 0, textHeight;
                for (let child of tile.children) {
                    if (!child.isText() || /[^ -~]/.test(child.text))
                        return undefined;
                    let rects = clientRectsFor(child.dom);
                    if (rects.length != 1)
                        return undefined;
                    totalWidth += rects[0].width;
                    textHeight = rects[0].height;
                }
                if (totalWidth)
                    return {
                        lineHeight: tile.dom.getBoundingClientRect().height,
                        charWidth: totalWidth / tile.length,
                        textHeight
                    };
            }
        });
        if (lineMeasure)
            return lineMeasure;
        // If no workable line exists, force a layout of a measurable element
        let dummy = document.createElement("div"), lineHeight, charWidth, textHeight;
        dummy.className = "cm-line";
        dummy.style.width = "99999px";
        dummy.style.position = "absolute";
        dummy.textContent = "abc def ghi jkl mno pqr stu";
        this.view.observer.ignore(() => {
            this.tile.dom.appendChild(dummy);
            let rect = clientRectsFor(dummy.firstChild)[0];
            lineHeight = dummy.getBoundingClientRect().height;
            charWidth = rect && rect.width ? rect.width / 27 : 7;
            textHeight = rect && rect.height ? rect.height : lineHeight;
            dummy.remove();
        });
        return { lineHeight, charWidth, textHeight };
    }
    computeBlockGapDeco() {
        let deco = [], vs = this.view.viewState;
        for (let pos = 0, i = 0;; i++) {
            let next = i == vs.viewports.length ? null : vs.viewports[i];
            let end = next ? next.from - 1 : this.view.state.doc.length;
            if (end > pos) {
                let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY;
                deco.push(dist_Decoration.replace({
                    widget: new BlockGapWidget(height),
                    block: true,
                    inclusive: true,
                    isBlockGap: true,
                }).range(pos, end));
            }
            if (!next)
                break;
            pos = next.to + 1;
        }
        return dist_Decoration.set(deco);
    }
    updateDeco() {
        let i = 1;
        let allDeco = this.view.state.facet(decorations).map(d => {
            let dynamic = this.dynamicDecorationMap[i++] = typeof d == "function";
            return dynamic ? d(this.view) : d;
        });
        let dynamicOuter = false, outerDeco = this.view.state.facet(outerDecorations).map((d, i) => {
            let dynamic = typeof d == "function";
            if (dynamic)
                dynamicOuter = true;
            return dynamic ? d(this.view) : d;
        });
        if (outerDeco.length) {
            this.dynamicDecorationMap[i++] = dynamicOuter;
            allDeco.push(dist_RangeSet.join(outerDeco));
        }
        this.decorations = [
            this.editContextFormatting,
            ...allDeco,
            this.computeBlockGapDeco(),
            this.view.viewState.lineGapDeco
        ];
        while (i < this.decorations.length)
            this.dynamicDecorationMap[i++] = false;
        this.blockWrappers = this.view.state.facet(blockWrappers).map(v => typeof v == "function" ? v(this.view) : v);
    }
    scrollIntoView(target) {
        if (target.isSnapshot) {
            let ref = this.view.viewState.lineBlockAt(target.range.head);
            this.view.scrollDOM.scrollTop = ref.top - target.yMargin;
            this.view.scrollDOM.scrollLeft = target.xMargin;
            return;
        }
        for (let handler of this.view.state.facet(scrollHandler)) {
            try {
                if (handler(this.view, target.range, target))
                    return true;
            }
            catch (e) {
                logException(this.view.state, e, "scroll handler");
            }
        }
        let { range } = target;
        let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other;
        if (!rect)
            return;
        if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1)))
            rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top),
                right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) };
        let margins = getScrollMargins(this.view);
        let targetRect = {
            left: rect.left - margins.left, top: rect.top - margins.top,
            right: rect.right + margins.right, bottom: rect.bottom + margins.bottom
        };
        let { offsetWidth, offsetHeight } = this.view.scrollDOM;
        scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == Direction.LTR);
    }
    lineHasWidget(pos) {
        let scan = (child) => child.isWidget() || child.children.some(scan);
        return scan(this.tile.resolveBlock(pos, 1).tile);
    }
    destroy() {
        destroyDropped(this.tile);
    }
}
function destroyDropped(tile, reused) {
    let r = reused === null || reused === void 0 ? void 0 : reused.get(tile);
    if (r != 1 /* Reused.Full */) {
        if (r == null)
            tile.destroy();
        for (let ch of tile.children)
            destroyDropped(ch, reused);
    }
}
function betweenUneditable(pos) {
    return pos.node.nodeType == 1 && pos.node.firstChild &&
        (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") &&
        (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false");
}
function findCompositionNode(view, headPos) {
    let sel = view.observer.selectionRange;
    if (!sel.focusNode)
        return null;
    let textBefore = textNodeBefore(sel.focusNode, sel.focusOffset);
    let textAfter = textNodeAfter(sel.focusNode, sel.focusOffset);
    let textNode = textBefore || textAfter;
    if (textAfter && textBefore && textAfter.node != textBefore.node) {
        let tileAfter = Tile.get(textAfter.node);
        if (!tileAfter || tileAfter.isText() && tileAfter.text != textAfter.node.nodeValue) {
            textNode = textAfter;
        }
        else if (view.docView.lastCompositionAfterCursor) {
            let tileBefore = Tile.get(textBefore.node);
            if (!(!tileBefore || tileBefore.isText() && tileBefore.text != textBefore.node.nodeValue))
                textNode = textAfter;
        }
    }
    view.docView.lastCompositionAfterCursor = textNode != textBefore;
    if (!textNode)
        return null;
    let from = headPos - textNode.offset;
    return { from, to: from + textNode.node.nodeValue.length, node: textNode.node };
}
function findCompositionRange(view, changes, headPos) {
    let found = findCompositionNode(view, headPos);
    if (!found)
        return null;
    let { node: textNode, from, to } = found, text = textNode.nodeValue;
    // Don't try to preserve multi-line compositions
    if (/[\n\r]/.test(text))
        return null;
    if (view.state.doc.sliceString(found.from, found.to) != text)
        return null;
    let inv = changes.invertedDesc;
    return { range: new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to), text: textNode };
}
function nextToUneditable(node, offset) {
    if (node.nodeType != 1)
        return 0;
    return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 /* NextTo.Before */ : 0) |
        (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 /* NextTo.After */ : 0);
}
let DecorationComparator$1 = class DecorationComparator {
    constructor() {
        this.changes = [];
    }
    compareRange(from, to) { addRange(from, to, this.changes); }
    comparePoint(from, to) { addRange(from, to, this.changes); }
    boundChange(pos) { addRange(pos, pos, this.changes); }
};
function findChangedDeco(a, b, diff) {
    let comp = new DecorationComparator$1;
    dist_RangeSet.compare(a, b, diff, comp);
    return comp.changes;
}
class WrapperComparator {
    constructor() {
        this.changes = [];
    }
    compareRange(from, to) { addRange(from, to, this.changes); }
    comparePoint() { }
    boundChange(pos) { addRange(pos, pos, this.changes); }
}
function findChangedWrappers(a, b, diff) {
    let comp = new WrapperComparator;
    dist_RangeSet.compare(a, b, diff, comp);
    return comp.changes;
}
function inUneditable(node, inside) {
    for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) {
        if (cur.nodeType == 1 && cur.contentEditable == 'false') {
            return true;
        }
    }
    return false;
}
function touchesComposition(changes, composition) {
    let touched = false;
    if (composition)
        changes.iterChangedRanges((from, to) => {
            if (from < composition.to && to > composition.from)
                touched = true;
        });
    return touched;
}
class BlockGapWidget extends WidgetType {
    constructor(height) {
        super();
        this.height = height;
    }
    toDOM() {
        let elt = document.createElement("div");
        elt.className = "cm-gap";
        this.updateDOM(elt);
        return elt;
    }
    eq(other) { return other.height == this.height; }
    updateDOM(elt) {
        elt.style.height = this.height + "px";
        return true;
    }
    get editable() { return true; }
    get estimatedHeight() { return this.height; }
    ignoreEvent() { return false; }
}

function groupAt(state, pos, bias = 1) {
    let categorize = state.charCategorizer(pos);
    let line = state.doc.lineAt(pos), linePos = pos - line.from;
    if (line.length == 0)
        return dist_EditorSelection.cursor(pos);
    if (linePos == 0)
        bias = 1;
    else if (linePos == line.length)
        bias = -1;
    let from = linePos, to = linePos;
    if (bias < 0)
        from = dist_findClusterBreak(line.text, linePos, false);
    else
        to = dist_findClusterBreak(line.text, linePos);
    let cat = categorize(line.text.slice(from, to));
    while (from > 0) {
        let prev = dist_findClusterBreak(line.text, from, false);
        if (categorize(line.text.slice(prev, from)) != cat)
            break;
        from = prev;
    }
    while (to < line.length) {
        let next = dist_findClusterBreak(line.text, to);
        if (categorize(line.text.slice(to, next)) != cat)
            break;
        to = next;
    }
    return dist_EditorSelection.range(from + line.from, to + line.from);
}
function posAtCoordsImprecise(view, contentRect, block, x, y) {
    let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth);
    if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) {
        let textHeight = view.viewState.heightOracle.textHeight;
        let line = Math.floor((y - block.top - (view.defaultLineHeight - textHeight) * 0.5) / textHeight);
        into += line * view.viewState.heightOracle.lineLength;
    }
    let content = view.state.sliceDoc(block.from, block.to);
    return block.from + findColumn(content, into, view.state.tabSize);
}
function blockAt(view, pos, side) {
    let line = view.lineBlockAt(pos);
    if (Array.isArray(line.type)) {
        let best;
        for (let l of line.type) {
            if (l.from > pos)
                break;
            if (l.to < pos)
                continue;
            if (l.from < pos && l.to > pos)
                return l;
            if (!best || (l.type == BlockType.Text && (best.type != l.type || (side < 0 ? l.from < pos : l.to > pos))))
                best = l;
        }
        return best || line;
    }
    return line;
}
function moveToLineBoundary(view, start, forward, includeWrap) {
    let line = blockAt(view, start.head, start.assoc || -1);
    let coords = !includeWrap || line.type != BlockType.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null
        : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head);
    if (coords) {
        let editorRect = view.dom.getBoundingClientRect();
        let direction = view.textDirectionAt(line.from);
        let pos = view.posAtCoords({ x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,
            y: (coords.top + coords.bottom) / 2 });
        if (pos != null)
            return dist_EditorSelection.cursor(pos, forward ? -1 : 1);
    }
    return dist_EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1);
}
function moveByChar(view, start, forward, by) {
    let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line);
    let direction = view.textDirectionAt(line.from);
    for (let cur = start, check = null;;) {
        let next = moveVisually(line, spans, direction, cur, forward), char = movedOver;
        if (!next) {
            if (line.number == (forward ? view.state.doc.lines : 1))
                return cur;
            char = "\n";
            line = view.state.doc.line(line.number + (forward ? 1 : -1));
            spans = view.bidiSpans(line);
            next = view.visualLineSide(line, !forward);
        }
        if (!check) {
            if (!by)
                return next;
            check = by(char);
        }
        else if (!check(char)) {
            return cur;
        }
        cur = next;
    }
}
function byGroup(view, pos, start) {
    let categorize = view.state.charCategorizer(pos);
    let cat = categorize(start);
    return (next) => {
        let nextCat = categorize(next);
        if (cat == dist_CharCategory.Space)
            cat = nextCat;
        return cat == nextCat;
    };
}
function moveVertically(view, start, forward, distance) {
    let startPos = start.head, dir = forward ? 1 : -1;
    if (startPos == (forward ? view.state.doc.length : 0))
        return dist_EditorSelection.cursor(startPos, start.assoc);
    let goal = start.goalColumn, startY;
    let rect = view.contentDOM.getBoundingClientRect();
    let startCoords = view.coordsAtPos(startPos, start.assoc || -1), docTop = view.documentTop;
    if (startCoords) {
        if (goal == null)
            goal = startCoords.left - rect.left;
        startY = dir < 0 ? startCoords.top : startCoords.bottom;
    }
    else {
        let line = view.viewState.lineBlockAt(startPos);
        if (goal == null)
            goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from));
        startY = (dir < 0 ? line.top : line.bottom) + docTop;
    }
    let resolvedGoal = rect.left + goal;
    let dist = distance !== null && distance !== void 0 ? distance : (view.viewState.heightOracle.textHeight >> 1);
    for (let extra = 0;; extra += 10) {
        let curY = startY + (dist + extra) * dir;
        let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir);
        return dist_EditorSelection.cursor(pos.pos, pos.assoc, undefined, goal);
    }
}
function skipAtomicRanges(atoms, pos, bias) {
    for (;;) {
        let moved = 0;
        for (let set of atoms) {
            set.between(pos - 1, pos + 1, (from, to, value) => {
                if (pos > from && pos < to) {
                    let side = moved || bias || (pos - from < to - pos ? -1 : 1);
                    pos = side < 0 ? from : to;
                    moved = side;
                }
            });
        }
        if (!moved)
            return pos;
    }
}
function skipAtomsForSelection(atoms, sel) {
    let ranges = null;
    for (let i = 0; i < sel.ranges.length; i++) {
        let range = sel.ranges[i], updated = null;
        if (range.empty) {
            let pos = skipAtomicRanges(atoms, range.from, 0);
            if (pos != range.from)
                updated = dist_EditorSelection.cursor(pos, -1);
        }
        else {
            let from = skipAtomicRanges(atoms, range.from, -1);
            let to = skipAtomicRanges(atoms, range.to, 1);
            if (from != range.from || to != range.to)
                updated = dist_EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to);
        }
        if (updated) {
            if (!ranges)
                ranges = sel.ranges.slice();
            ranges[i] = updated;
        }
    }
    return ranges ? dist_EditorSelection.create(ranges, sel.mainIndex) : sel;
}
function skipAtoms(view, oldPos, pos) {
    let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map(f => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1);
    return newPos == pos.from ? pos : dist_EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);
}
class PosAssoc {
    constructor(pos, assoc) {
        this.pos = pos;
        this.assoc = assoc;
    }
}
function posAtCoords(view, coords, precise, scanY) {
    let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop;
    let { x, y } = coords, yOffset = y - docTop, block;
    // First find the block at the given Y position, if any. If scanY is
    // given (used for vertical cursor motion), try to skip widgets and
    // line padding.
    for (;;) {
        if (yOffset < 0)
            return new PosAssoc(0, 1);
        if (yOffset > view.viewState.docHeight)
            return new PosAssoc(view.state.doc.length, -1);
        block = view.elementAtHeight(yOffset);
        if (scanY == null)
            break;
        if (block.type == BlockType.Text) {
            // Check whether we aren't landing the top/bottom padding of the line
            let rect = view.docView.coordsAt(scanY < 0 ? block.from : block.to, scanY);
            if (rect && (scanY < 0 ? rect.top <= yOffset + docTop : rect.bottom >= yOffset + docTop))
                break;
        }
        let halfLine = view.viewState.heightOracle.textHeight / 2;
        yOffset = scanY > 0 ? block.bottom + halfLine : block.top - halfLine;
    }
    // If outside the viewport, return null if precise==true, an
    // estimate otherwise.
    if (view.viewport.from >= block.to || view.viewport.to <= block.from) {
        if (precise)
            return null;
        if (block.type == BlockType.Text) {
            let pos = posAtCoordsImprecise(view, content, block, x, y);
            return new PosAssoc(pos, pos == block.from ? 1 : -1);
        }
    }
    if (block.type != BlockType.Text)
        return yOffset < (block.top + block.bottom) / 2 ? new PosAssoc(block.from, 1) : new PosAssoc(block.to, -1);
    // Here we know we're in a line, so run the logic for inline layout
    let line = view.docView.lineAt(block.from, 2);
    if (!line || line.length != block.length)
        line = view.docView.lineAt(block.from, -2);
    return posAtCoordsInline(view, line, block.from, x, y);
}
// Scan through the rectangles for the content of a tile, finding the
// one closest to the given coordinates, prefering closeness in Y over
// closeness in X.
//
// If this is a text tile, go character-by-character. For line or mark
// tiles, check each non-point-widget child, and descend text or mark
// tiles with a recursive call.
//
// For non-wrapped, purely left-to-right text, this could use a binary
// search. But because this seems to be fast enough, for how often it
// is called, there's not currently a specialized implementation for
// that.
function posAtCoordsInline(view, tile, offset, x, y) {
    let closest = -1, closestRect = null;
    let dxClosest = 1e9, dyClosest = 1e9;
    let rowTop = y, rowBot = y;
    let checkRects = (rects, index) => {
        for (let i = 0; i < rects.length; i++) {
            let rect = rects[i];
            if (rect.top == rect.bottom)
                continue;
            let dx = rect.left > x ? rect.left - x : rect.right < x ? x - rect.right : 0;
            let dy = rect.top > y ? rect.top - y : rect.bottom < y ? y - rect.bottom : 0;
            if (rect.top <= rowBot && rect.bottom >= rowTop) {
                // Rectangle is in the current row
                rowTop = Math.min(rect.top, rowTop);
                rowBot = Math.max(rect.bottom, rowBot);
                dy = 0;
            }
            if (closest < 0 || (dy - dyClosest || dx - dxClosest) < 0) {
                if (closest >= 0 && dyClosest && dxClosest < dx &&
                    closestRect.top <= rowBot - 2 && closestRect.bottom >= rowTop + 2) {
                    // Retroactively set dy to 0 if the current match is in this row.
                    dyClosest = 0;
                }
                else {
                    closest = index;
                    dxClosest = dx;
                    dyClosest = dy;
                    closestRect = rect;
                }
            }
        }
    };
    if (tile.isText()) {
        for (let i = 0; i < tile.length;) {
            let next = dist_findClusterBreak(tile.text, i);
            checkRects(textRange(tile.dom, i, next).getClientRects(), i);
            if (!dxClosest && !dyClosest)
                break;
            i = next;
        }
        let after = (x > (closestRect.left + closestRect.right) / 2) == (dirAt(view, closest + offset) == Direction.LTR);
        return after ? new PosAssoc(offset + dist_findClusterBreak(tile.text, closest), -1) : new PosAssoc(offset + closest, 1);
    }
    else {
        if (!tile.length)
            return new PosAssoc(offset, 1);
        for (let i = 0; i < tile.children.length; i++) {
            let child = tile.children[i];
            if (child.flags & 48 /* TileFlag.PointWidget */)
                continue;
            let rects = (child.dom.nodeType == 1 ? child.dom : textRange(child.dom, 0, child.length)).getClientRects();
            checkRects(rects, i);
            if (!dxClosest && !dyClosest)
                break;
        }
        let inner = tile.children[closest], innerOff = tile.posBefore(inner, offset);
        if (inner.isComposite() || inner.isText())
            return posAtCoordsInline(view, inner, innerOff, Math.max(closestRect.left, Math.min(closestRect.right, x)), y);
        let after = (x > (closestRect.left + closestRect.right) / 2) == (dirAt(view, closest + offset) == Direction.LTR);
        return after ? new PosAssoc(innerOff + inner.length, -1) : new PosAssoc(innerOff, 1);
    }
}
function dirAt(view, pos) {
    let line = view.state.doc.lineAt(pos), spans = view.bidiSpans(line);
    return spans[BidiSpan.find(view.bidiSpans(line), pos - line.from, -1, 1)].dir;
}

const LineBreakPlaceholder = "\uffff";
class DOMReader {
    constructor(points, view) {
        this.points = points;
        this.view = view;
        this.text = "";
        this.lineSeparator = view.state.facet(dist_EditorState.lineSeparator);
    }
    append(text) {
        this.text += text;
    }
    lineBreak() {
        this.text += LineBreakPlaceholder;
    }
    readRange(start, end) {
        if (!start)
            return this;
        let parent = start.parentNode;
        for (let cur = start;;) {
            this.findPointBefore(parent, cur);
            let oldLen = this.text.length;
            this.readNode(cur);
            let tile = Tile.get(cur), next = cur.nextSibling;
            if (next == end) {
                if ((tile === null || tile === void 0 ? void 0 : tile.breakAfter) && !next && parent != this.view.contentDOM)
                    this.lineBreak();
                break;
            }
            let nextTile = Tile.get(next);
            if ((tile && nextTile ? tile.breakAfter :
                (tile ? tile.breakAfter : isBlockElement(cur)) ||
                    (isBlockElement(next) && (cur.nodeName != "BR" || (tile === null || tile === void 0 ? void 0 : tile.isWidget())) && this.text.length > oldLen)) &&
                !isEmptyToEnd(next, end))
                this.lineBreak();
            cur = next;
        }
        this.findPointBefore(parent, end);
        return this;
    }
    readTextNode(node) {
        let text = node.nodeValue;
        for (let point of this.points)
            if (point.node == node)
                point.pos = this.text.length + Math.min(point.offset, text.length);
        for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) {
            let nextBreak = -1, breakSize = 1, m;
            if (this.lineSeparator) {
                nextBreak = text.indexOf(this.lineSeparator, off);
                breakSize = this.lineSeparator.length;
            }
            else if (m = re.exec(text)) {
                nextBreak = m.index;
                breakSize = m[0].length;
            }
            this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak));
            if (nextBreak < 0)
                break;
            this.lineBreak();
            if (breakSize > 1)
                for (let point of this.points)
                    if (point.node == node && point.pos > this.text.length)
                        point.pos -= breakSize - 1;
            off = nextBreak + breakSize;
        }
    }
    readNode(node) {
        let tile = Tile.get(node);
        let fromView = tile && tile.overrideDOMText;
        if (fromView != null) {
            this.findPointInside(node, fromView.length);
            for (let i = fromView.iter(); !i.next().done;) {
                if (i.lineBreak)
                    this.lineBreak();
                else
                    this.append(i.value);
            }
        }
        else if (node.nodeType == 3) {
            this.readTextNode(node);
        }
        else if (node.nodeName == "BR") {
            if (node.nextSibling)
                this.lineBreak();
        }
        else if (node.nodeType == 1) {
            this.readRange(node.firstChild, null);
        }
    }
    findPointBefore(node, next) {
        for (let point of this.points)
            if (point.node == node && node.childNodes[point.offset] == next)
                point.pos = this.text.length;
    }
    findPointInside(node, length) {
        for (let point of this.points)
            if (node.nodeType == 3 ? point.node == node : node.contains(point.node))
                point.pos = this.text.length + (isAtEnd(node, point.node, point.offset) ? length : 0);
    }
}
function isAtEnd(parent, node, offset) {
    for (;;) {
        if (!node || offset < maxOffset(node))
            return false;
        if (node == parent)
            return true;
        offset = domIndex(node) + 1;
        node = node.parentNode;
    }
}
function isEmptyToEnd(node, end) {
    let widgets;
    for (;; node = node.nextSibling) {
        if (node == end || !node)
            break;
        let view = Tile.get(node);
        if (!(view === null || view === void 0 ? void 0 : view.isWidget()))
            return false;
        if (view)
            (widgets || (widgets = [])).push(view);
    }
    if (widgets)
        for (let w of widgets) {
            let override = w.overrideDOMText;
            if (override === null || override === void 0 ? void 0 : override.length)
                return false;
        }
    return true;
}
class DOMPoint {
    constructor(node, offset) {
        this.node = node;
        this.offset = offset;
        this.pos = -1;
    }
}

class DOMChange {
    constructor(view, start, end, typeOver) {
        this.typeOver = typeOver;
        this.bounds = null;
        this.text = "";
        this.domChanged = start > -1;
        let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
        if (view.state.readOnly && start > -1) {
            // Ignore changes when the editor is read-only
            this.newSel = null;
        }
        else if (start > -1 && (this.bounds = domBoundsAround(view.docView.tile, start, end, 0))) {
            let selPoints = iHead || iAnchor ? [] : selectionPoints(view);
            let reader = new DOMReader(selPoints, view);
            reader.readRange(this.bounds.startDOM, this.bounds.endDOM);
            this.text = reader.text;
            this.newSel = selectionFromPoints(selPoints, this.bounds.from);
        }
        else {
            let domSel = view.observer.selectionRange;
            let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset ||
                !contains(view.contentDOM, domSel.focusNode)
                ? view.state.selection.main.head
                : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
            let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset ||
                !contains(view.contentDOM, domSel.anchorNode)
                ? view.state.selection.main.anchor
                : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
            // iOS will refuse to select the block gaps when doing
            // select-all.
            // Chrome will put the selection *inside* them, confusing
            // posFromDOM
            let vp = view.viewport;
            if ((browser.ios || browser.chrome) && view.state.selection.main.empty && head != anchor &&
                (vp.from > 0 || vp.to < view.state.doc.length)) {
                let from = Math.min(head, anchor), to = Math.max(head, anchor);
                let offFrom = vp.from - from, offTo = vp.to - to;
                if ((offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length)) {
                    head = 0;
                    anchor = view.state.doc.length;
                }
            }
            if (view.inputState.composing > -1 && view.state.selection.ranges.length > 1)
                this.newSel = view.state.selection.replaceRange(dist_EditorSelection.range(anchor, head));
            else
                this.newSel = dist_EditorSelection.single(anchor, head);
        }
    }
}
function domBoundsAround(tile, from, to, offset) {
    if (tile.isComposite()) {
        let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;
        for (let i = 0, pos = offset, prevEnd = offset; i < tile.children.length; i++) {
            let child = tile.children[i], end = pos + child.length;
            if (pos < from && end > to)
                return domBoundsAround(child, from, to, pos);
            if (end >= from && fromI == -1) {
                fromI = i;
                fromStart = pos;
            }
            if (pos > to && child.dom.parentNode == tile.dom) {
                toI = i;
                toEnd = prevEnd;
                break;
            }
            prevEnd = end;
            pos = end + child.breakAfter;
        }
        return { from: fromStart, to: toEnd < 0 ? offset + tile.length : toEnd,
            startDOM: (fromI ? tile.children[fromI - 1].dom.nextSibling : null) || tile.dom.firstChild,
            endDOM: toI < tile.children.length && toI >= 0 ? tile.children[toI].dom : null };
    }
    else if (tile.isText()) {
        return { from: offset, to: offset + tile.length, startDOM: tile.dom, endDOM: tile.dom.nextSibling };
    }
    else {
        return null;
    }
}
function applyDOMChange(view, domChange) {
    let change;
    let { newSel } = domChange, sel = view.state.selection.main;
    let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;
    if (domChange.bounds) {
        let { from, to } = domChange.bounds;
        let preferredPos = sel.from, preferredSide = null;
        // Prefer anchoring to end when Backspace is pressed (or, on
        // Android, when something was deleted)
        if (lastKey === 8 || browser.android && domChange.text.length < to - from) {
            preferredPos = sel.to;
            preferredSide = "end";
        }
        let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);
        if (diff) {
            // Chrome inserts two newlines when pressing shift-enter at the
            // end of a line. DomChange drops one of those.
            if (browser.chrome && lastKey == 13 &&
                diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder)
                diff.toB--;
            change = { from: from + diff.from, to: from + diff.toA,
                insert: dist_Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) };
        }
    }
    else if (newSel && (!view.hasFocus && view.state.facet(editable) || newSel.main.eq(sel))) {
        newSel = null;
    }
    if (!change && !newSel)
        return false;
    if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) {
        // Heuristic to notice typing over a selected character
        change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) };
    }
    else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 &&
        /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off") {
        // Detect insert-period-on-double-space Mac and Android behavior,
        // and transform it into a regular space insert.
        if (newSel && change.insert.length == 2)
            newSel = dist_EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
        change = { from: change.from, to: change.to, insert: dist_Text.of([change.insert.toString().replace(".", " ")]) };
    }
    else if (change && change.from >= sel.from && change.to <= sel.to &&
        (change.from != sel.from || change.to != sel.to) &&
        (sel.to - sel.from) - (change.to - change.from) <= 4) {
        // If the change is inside the selection and covers most of it,
        // assume it is a selection replace (with identical characters at
        // the start/end not included in the diff)
        change = {
            from: sel.from, to: sel.to,
            insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))
        };
    }
    else if (view.state.doc.lineAt(sel.from).to < sel.to && view.docView.lineHasWidget(sel.to) &&
        view.inputState.insertingTextAt > Date.now() - 50) {
        // For a cross-line insertion, Chrome and Safari will crudely take
        // the text of the line after the selection, flattening any
        // widgets, and move it into the joined line. This tries to detect
        // such a situation, and replaces the change with a selection
        // replace of the text provided by the beforeinput event.
        change = {
            from: sel.from, to: sel.to,
            insert: view.state.toText(view.inputState.insertingText)
        };
    }
    else if (browser.chrome && change && change.from == change.to && change.from == sel.head &&
        change.insert.toString() == "\n " && view.lineWrapping) {
        // In Chrome, if you insert a space at the start of a wrapped
        // line, it will actually insert a newline and a space, causing a
        // bogus new line to be created in CodeMirror (#968)
        if (newSel)
            newSel = dist_EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
        change = { from: sel.from, to: sel.to, insert: dist_Text.of([" "]) };
    }
    if (change) {
        return applyDOMChangeInner(view, change, newSel, lastKey);
    }
    else if (newSel && !newSel.main.eq(sel)) {
        let scrollIntoView = false, userEvent = "select";
        if (view.inputState.lastSelectionTime > Date.now() - 50) {
            if (view.inputState.lastSelectionOrigin == "select")
                scrollIntoView = true;
            userEvent = view.inputState.lastSelectionOrigin;
            if (userEvent == "select.pointer")
                newSel = skipAtomsForSelection(view.state.facet(atomicRanges).map(f => f(view)), newSel);
        }
        view.dispatch({ selection: newSel, scrollIntoView, userEvent });
        return true;
    }
    else {
        return false;
    }
}
function applyDOMChangeInner(view, change, newSel, lastKey = -1) {
    if (browser.ios && view.inputState.flushIOSKey(change))
        return true;
    let sel = view.state.selection.main;
    // Android browsers don't fire reasonable key events for enter,
    // backspace, or delete. So this detects changes that look like
    // they're caused by those keys, and reinterprets them as key
    // events. (Some of these keys are also handled by beforeinput
    // events and the pendingAndroidKey mechanism, but that's not
    // reliable in all situations.)
    if (browser.android &&
        ((change.to == sel.to &&
            // GBoard will sometimes remove a space it just inserted
            // after a completion when you press enter
            (change.from == sel.from || change.from == sel.from - 1 && view.state.sliceDoc(change.from, sel.from) == " ") &&
            change.insert.length == 1 && change.insert.lines == 2 &&
            dispatchKey(view.contentDOM, "Enter", 13)) ||
            ((change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 ||
                lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) &&
                dispatchKey(view.contentDOM, "Backspace", 8)) ||
            (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 &&
                dispatchKey(view.contentDOM, "Delete", 46))))
        return true;
    let text = change.insert.toString();
    if (view.inputState.composing >= 0)
        view.inputState.composing++;
    let defaultTr;
    let defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel));
    if (!view.state.facet(inputHandler).some(h => h(view, change.from, change.to, text, defaultInsert)))
        view.dispatch(defaultInsert());
    return true;
}
function applyDefaultInsert(view, change, newSel) {
    let tr, startState = view.state, sel = startState.selection.main, inAtomic = -1;
    if (change.from == change.to && change.from < sel.from || change.from > sel.to) {
        let side = change.from < sel.from ? -1 : 1, pos = side < 0 ? sel.from : sel.to;
        let moved = skipAtomicRanges(startState.facet(atomicRanges).map(f => f(view)), pos, side);
        if (change.from == moved)
            inAtomic = moved;
    }
    if (inAtomic > -1) {
        tr = {
            changes: change,
            selection: dist_EditorSelection.cursor(change.from + change.insert.length, -1)
        };
    }
    else if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 &&
        (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) &&
        view.inputState.composing < 0) {
        let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "";
        let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : "";
        tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after));
    }
    else {
        let changes = startState.changes(change);
        let mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : undefined;
        // Try to apply a composition change to all cursors
        if (startState.selection.ranges.length > 1 && (view.inputState.composing >= 0 || view.inputState.compositionPendingChange) &&
            change.to <= sel.to + 10 && change.to >= sel.to - 10) {
            let replaced = view.state.sliceDoc(change.from, change.to);
            let compositionRange, composition = newSel && findCompositionNode(view, newSel.main.head);
            if (composition) {
                let dLen = change.insert.length - (change.to - change.from);
                compositionRange = { from: composition.from, to: composition.to - dLen };
            }
            else {
                compositionRange = view.state.doc.lineAt(sel.head);
            }
            let offset = sel.to - change.to;
            tr = startState.changeByRange(range => {
                if (range.from == sel.from && range.to == sel.to)
                    return { changes, range: mainSel || range.map(changes) };
                let to = range.to - offset, from = to - replaced.length;
                if (view.state.sliceDoc(from, to) != replaced ||
                    // Unfortunately, there's no way to make multiple
                    // changes in the same node work without aborting
                    // composition, so cursors in the composition range are
                    // ignored.
                    to >= compositionRange.from && from <= compositionRange.to)
                    return { range };
                let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to;
                return {
                    changes: rangeChanges,
                    range: !mainSel ? range.map(rangeChanges) :
                        dist_EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))
                };
            });
        }
        else {
            tr = {
                changes,
                selection: mainSel && startState.selection.replaceRange(mainSel)
            };
        }
    }
    let userEvent = "input.type";
    if (view.composing ||
        view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {
        view.inputState.compositionPendingChange = false;
        userEvent += ".compose";
        if (view.inputState.compositionFirstChange) {
            userEvent += ".start";
            view.inputState.compositionFirstChange = false;
        }
    }
    return startState.update(tr, { userEvent, scrollIntoView: true });
}
function findDiff(a, b, preferredPos, preferredSide) {
    let minLen = Math.min(a.length, b.length);
    let from = 0;
    while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from))
        from++;
    if (from == minLen && a.length == b.length)
        return null;
    let toA = a.length, toB = b.length;
    while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) {
        toA--;
        toB--;
    }
    if (preferredSide == "end") {
        let adjust = Math.max(0, from - Math.min(toA, toB));
        preferredPos -= toA + adjust - from;
    }
    if (toA < from && a.length < b.length) {
        let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;
        from -= move;
        toB = from + (toB - toA);
        toA = from;
    }
    else if (toB < from) {
        let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;
        from -= move;
        toA = from + (toA - toB);
        toB = from;
    }
    return { from, toA, toB };
}
function selectionPoints(view) {
    let result = [];
    if (view.root.activeElement != view.contentDOM)
        return result;
    let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange;
    if (anchorNode) {
        result.push(new DOMPoint(anchorNode, anchorOffset));
        if (focusNode != anchorNode || focusOffset != anchorOffset)
            result.push(new DOMPoint(focusNode, focusOffset));
    }
    return result;
}
function selectionFromPoints(points, base) {
    if (points.length == 0)
        return null;
    let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor;
    return anchor > -1 && head > -1 ? dist_EditorSelection.single(anchor + base, head + base) : null;
}

class InputState {
    setSelectionOrigin(origin) {
        this.lastSelectionOrigin = origin;
        this.lastSelectionTime = Date.now();
    }
    constructor(view) {
        this.view = view;
        this.lastKeyCode = 0;
        this.lastKeyTime = 0;
        this.lastTouchTime = 0;
        this.lastFocusTime = 0;
        this.lastScrollTop = 0;
        this.lastScrollLeft = 0;
        // On iOS, some keys need to have their default behavior happen
        // (after which we retroactively handle them and reset the DOM) to
        // avoid messing up the virtual keyboard state.
        this.pendingIOSKey = undefined;
        /**
        When enabled (>-1), tab presses are not given to key handlers,
        leaving the browser's default behavior. If >0, the mode expires
        at that timestamp, and any other keypress clears it.
        Esc enables temporary tab focus mode for two seconds when not
        otherwise handled.
        */
        this.tabFocusMode = -1;
        this.lastSelectionOrigin = null;
        this.lastSelectionTime = 0;
        this.lastContextMenu = 0;
        this.scrollHandlers = [];
        this.handlers = Object.create(null);
        // -1 means not in a composition. Otherwise, this counts the number
        // of changes made during the composition. The count is used to
        // avoid treating the start state of the composition, before any
        // changes have been made, as part of the composition.
        this.composing = -1;
        // Tracks whether the next change should be marked as starting the
        // composition (null means no composition, true means next is the
        // first, false means first has already been marked for this
        // composition)
        this.compositionFirstChange = null;
        // End time of the previous composition
        this.compositionEndedAt = 0;
        // Used in a kludge to detect when an Enter keypress should be
        // considered part of the composition on Safari, which fires events
        // in the wrong order
        this.compositionPendingKey = false;
        // Used to categorize changes as part of a composition, even when
        // the mutation events fire shortly after the compositionend event
        this.compositionPendingChange = false;
        // Set by beforeinput, used in DOM change reader
        this.insertingText = "";
        this.insertingTextAt = 0;
        this.mouseSelection = null;
        // When a drag from the editor is active, this points at the range
        // being dragged.
        this.draggedContent = null;
        this.handleEvent = this.handleEvent.bind(this);
        this.notifiedFocused = view.hasFocus;
        // On Safari adding an input event handler somehow prevents an
        // issue where the composition vanishes when you press enter.
        if (browser.safari)
            view.contentDOM.addEventListener("input", () => null);
        if (browser.gecko)
            firefoxCopyCutHack(view.contentDOM.ownerDocument);
    }
    handleEvent(event) {
        if (!eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event))
            return;
        if (event.type == "keydown" && this.keydown(event))
            return;
        if (this.view.updateState != 0 /* UpdateState.Idle */)
            Promise.resolve().then(() => this.runHandlers(event.type, event));
        else
            this.runHandlers(event.type, event);
    }
    runHandlers(type, event) {
        let handlers = this.handlers[type];
        if (handlers) {
            for (let observer of handlers.observers)
                observer(this.view, event);
            for (let handler of handlers.handlers) {
                if (event.defaultPrevented)
                    break;
                if (handler(this.view, event)) {
                    event.preventDefault();
                    break;
                }
            }
        }
    }
    ensureHandlers(plugins) {
        let handlers = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM;
        for (let type in handlers)
            if (type != "scroll") {
                let passive = !handlers[type].handlers.length;
                let exists = prev[type];
                if (exists && passive != !exists.handlers.length) {
                    dom.removeEventListener(type, this.handleEvent);
                    exists = null;
                }
                if (!exists)
                    dom.addEventListener(type, this.handleEvent, { passive });
            }
        for (let type in prev)
            if (type != "scroll" && !handlers[type])
                dom.removeEventListener(type, this.handleEvent);
        this.handlers = handlers;
    }
    keydown(event) {
        // Must always run, even if a custom handler handled the event
        this.lastKeyCode = event.keyCode;
        this.lastKeyTime = Date.now();
        if (event.keyCode == 9 && this.tabFocusMode > -1 && (!this.tabFocusMode || Date.now() <= this.tabFocusMode))
            return true;
        if (this.tabFocusMode > 0 && event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0)
            this.tabFocusMode = -1;
        // Chrome for Android usually doesn't fire proper key events, but
        // occasionally does, usually surrounded by a bunch of complicated
        // composition changes. When an enter or backspace key event is
        // seen, hold off on handling DOM events for a bit, and then
        // dispatch it.
        if (browser.android && browser.chrome && !event.synthetic &&
            (event.keyCode == 13 || event.keyCode == 8)) {
            this.view.observer.delayAndroidKey(event.key, event.keyCode);
            return true;
        }
        // Preventing the default behavior of Enter on iOS makes the
        // virtual keyboard get stuck in the wrong (lowercase)
        // state. So we let it go through, and then, in
        // applyDOMChange, notify key handlers of it and reset to
        // the state they produce.
        let pending;
        if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey &&
            ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey ||
                EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {
            this.pendingIOSKey = pending || event;
            setTimeout(() => this.flushIOSKey(), 250);
            return true;
        }
        if (event.keyCode != 229)
            this.view.observer.forceFlush();
        return false;
    }
    flushIOSKey(change) {
        let key = this.pendingIOSKey;
        if (!key)
            return false;
        // This looks like an autocorrection before Enter
        if (key.key == "Enter" && change && change.from < change.to && /^\S+$/.test(change.insert.toString()))
            return false;
        this.pendingIOSKey = undefined;
        return dispatchKey(this.view.contentDOM, key.key, key.keyCode, key instanceof KeyboardEvent ? key : undefined);
    }
    ignoreDuringComposition(event) {
        if (!/^key/.test(event.type) || event.synthetic)
            return false;
        if (this.composing > 0)
            return true;
        // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.
        // On some input method editors (IMEs), the Enter key is used to
        // confirm character selection. On Safari, when Enter is pressed,
        // compositionend and keydown events are sometimes emitted in the
        // wrong order. The key event should still be ignored, even when
        // it happens after the compositionend event.
        if (browser.safari && !browser.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {
            this.compositionPendingKey = false;
            return true;
        }
        return false;
    }
    startMouseSelection(mouseSelection) {
        if (this.mouseSelection)
            this.mouseSelection.destroy();
        this.mouseSelection = mouseSelection;
    }
    update(update) {
        this.view.observer.update(update);
        if (this.mouseSelection)
            this.mouseSelection.update(update);
        if (this.draggedContent && update.docChanged)
            this.draggedContent = this.draggedContent.map(update.changes);
        if (update.transactions.length)
            this.lastKeyCode = this.lastSelectionTime = 0;
    }
    destroy() {
        if (this.mouseSelection)
            this.mouseSelection.destroy();
    }
}
function bindHandler(plugin, handler) {
    return (view, event) => {
        try {
            return handler.call(plugin, event, view);
        }
        catch (e) {
            logException(view.state, e);
        }
    };
}
function computeHandlers(plugins) {
    let result = Object.create(null);
    function record(type) {
        return result[type] || (result[type] = { observers: [], handlers: [] });
    }
    for (let plugin of plugins) {
        let spec = plugin.spec, handlers = spec && spec.plugin.domEventHandlers, observers = spec && spec.plugin.domEventObservers;
        if (handlers)
            for (let type in handlers) {
                let f = handlers[type];
                if (f)
                    record(type).handlers.push(bindHandler(plugin.value, f));
            }
        if (observers)
            for (let type in observers) {
                let f = observers[type];
                if (f)
                    record(type).observers.push(bindHandler(plugin.value, f));
            }
    }
    for (let type in handlers)
        record(type).handlers.push(handlers[type]);
    for (let type in observers)
        record(type).observers.push(observers[type]);
    return result;
}
const PendingKeys = [
    { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" },
    { key: "Enter", keyCode: 13, inputType: "insertParagraph" },
    { key: "Enter", keyCode: 13, inputType: "insertLineBreak" },
    { key: "Delete", keyCode: 46, inputType: "deleteContentForward" }
];
const EmacsyPendingKeys = "dthko";
// Key codes for modifier keys
const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];
const dragScrollMargin = 6;
function dragScrollSpeed(dist) {
    return Math.max(0, dist) * 0.7 + 8;
}
function dist(a, b) {
    return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY));
}
class MouseSelection {
    constructor(view, startEvent, style, mustSelect) {
        this.view = view;
        this.startEvent = startEvent;
        this.style = style;
        this.mustSelect = mustSelect;
        this.scrollSpeed = { x: 0, y: 0 };
        this.scrolling = -1;
        this.lastEvent = startEvent;
        this.scrollParents = scrollableParents(view.contentDOM);
        this.atoms = view.state.facet(atomicRanges).map(f => f(view));
        let doc = view.contentDOM.ownerDocument;
        doc.addEventListener("mousemove", this.move = this.move.bind(this));
        doc.addEventListener("mouseup", this.up = this.up.bind(this));
        this.extend = startEvent.shiftKey;
        this.multiple = view.state.facet(dist_EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent);
        this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false;
    }
    start(event) {
        // When clicking outside of the selection, immediately apply the
        // effect of starting the selection
        if (this.dragging === false)
            this.select(event);
    }
    move(event) {
        if (event.buttons == 0)
            return this.destroy();
        if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10)
            return;
        this.select(this.lastEvent = event);
        let sx = 0, sy = 0;
        let left = 0, top = 0, right = this.view.win.innerWidth, bottom = this.view.win.innerHeight;
        if (this.scrollParents.x)
            ({ left, right } = this.scrollParents.x.getBoundingClientRect());
        if (this.scrollParents.y)
            ({ top, bottom } = this.scrollParents.y.getBoundingClientRect());
        let margins = getScrollMargins(this.view);
        if (event.clientX - margins.left <= left + dragScrollMargin)
            sx = -dragScrollSpeed(left - event.clientX);
        else if (event.clientX + margins.right >= right - dragScrollMargin)
            sx = dragScrollSpeed(event.clientX - right);
        if (event.clientY - margins.top <= top + dragScrollMargin)
            sy = -dragScrollSpeed(top - event.clientY);
        else if (event.clientY + margins.bottom >= bottom - dragScrollMargin)
            sy = dragScrollSpeed(event.clientY - bottom);
        this.setScrollSpeed(sx, sy);
    }
    up(event) {
        if (this.dragging == null)
            this.select(this.lastEvent);
        if (!this.dragging)
            event.preventDefault();
        this.destroy();
    }
    destroy() {
        this.setScrollSpeed(0, 0);
        let doc = this.view.contentDOM.ownerDocument;
        doc.removeEventListener("mousemove", this.move);
        doc.removeEventListener("mouseup", this.up);
        this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null;
    }
    setScrollSpeed(sx, sy) {
        this.scrollSpeed = { x: sx, y: sy };
        if (sx || sy) {
            if (this.scrolling < 0)
                this.scrolling = setInterval(() => this.scroll(), 50);
        }
        else if (this.scrolling > -1) {
            clearInterval(this.scrolling);
            this.scrolling = -1;
        }
    }
    scroll() {
        let { x, y } = this.scrollSpeed;
        if (x && this.scrollParents.x) {
            this.scrollParents.x.scrollLeft += x;
            x = 0;
        }
        if (y && this.scrollParents.y) {
            this.scrollParents.y.scrollTop += y;
            y = 0;
        }
        if (x || y)
            this.view.win.scrollBy(x, y);
        if (this.dragging === false)
            this.select(this.lastEvent);
    }
    select(event) {
        let { view } = this, selection = skipAtomsForSelection(this.atoms, this.style.get(event, this.extend, this.multiple));
        if (this.mustSelect || !selection.eq(view.state.selection, this.dragging === false))
            this.view.dispatch({
                selection,
                userEvent: "select.pointer"
            });
        this.mustSelect = false;
    }
    update(update) {
        if (update.transactions.some(tr => tr.isUserEvent("input.type")))
            this.destroy();
        else if (this.style.update(update))
            setTimeout(() => this.select(this.lastEvent), 20);
    }
}
function addsSelectionRange(view, event) {
    let facet = view.state.facet(clickAddsSelectionRange);
    return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey;
}
function dragMovesSelection(view, event) {
    let facet = view.state.facet(dragMovesSelection$1);
    return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey;
}
function isInPrimarySelection(view, event) {
    let { main } = view.state.selection;
    if (main.empty)
        return false;
    // On boundary clicks, check whether the coordinates are inside the
    // selection's client rectangles
    let sel = getSelection(view.root);
    if (!sel || sel.rangeCount == 0)
        return true;
    let rects = sel.getRangeAt(0).getClientRects();
    for (let i = 0; i < rects.length; i++) {
        let rect = rects[i];
        if (rect.left <= event.clientX && rect.right >= event.clientX &&
            rect.top <= event.clientY && rect.bottom >= event.clientY)
            return true;
    }
    return false;
}
function eventBelongsToEditor(view, event) {
    if (!event.bubbles)
        return true;
    if (event.defaultPrevented)
        return false;
    for (let node = event.target, tile; node != view.contentDOM; node = node.parentNode)
        if (!node || node.nodeType == 11 ||
            ((tile = Tile.get(node)) && tile.isWidget() && !tile.isHidden && tile.widget.ignoreEvent(event)))
            return false;
    return true;
}
const handlers = /*@__PURE__*/Object.create(null);
const observers = /*@__PURE__*/Object.create(null);
// This is very crude, but unfortunately both these browsers _pretend_
// that they have a clipboard API—all the objects and methods are
// there, they just don't work, and they are hard to test.
const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) ||
    (browser.ios && browser.webkit_version < 604);
function capturePaste(view) {
    let parent = view.dom.parentNode;
    if (!parent)
        return;
    let target = parent.appendChild(document.createElement("textarea"));
    target.style.cssText = "position: fixed; left: -10000px; top: 10px";
    target.focus();
    setTimeout(() => {
        view.focus();
        target.remove();
        doPaste(view, target.value);
    }, 50);
}
function textFilter(state, facet, text) {
    for (let filter of state.facet(facet))
        text = filter(text, state);
    return text;
}
function doPaste(view, input) {
    input = textFilter(view.state, clipboardInputFilter, input);
    let { state } = view, changes, i = 1, text = state.toText(input);
    let byLine = text.lines == state.selection.ranges.length;
    let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString();
    if (linewise) {
        let lastLine = -1;
        changes = state.changeByRange(range => {
            let line = state.doc.lineAt(range.from);
            if (line.from == lastLine)
                return { range };
            lastLine = line.from;
            let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak);
            return { changes: { from: line.from, insert },
                range: dist_EditorSelection.cursor(range.from + insert.length) };
        });
    }
    else if (byLine) {
        changes = state.changeByRange(range => {
            let line = text.line(i++);
            return { changes: { from: range.from, to: range.to, insert: line.text },
                range: dist_EditorSelection.cursor(range.from + line.length) };
        });
    }
    else {
        changes = state.replaceSelection(text);
    }
    view.dispatch(changes, {
        userEvent: "input.paste",
        scrollIntoView: true
    });
}
observers.scroll = view => {
    view.inputState.lastScrollTop = view.scrollDOM.scrollTop;
    view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;
};
handlers.keydown = (view, event) => {
    view.inputState.setSelectionOrigin("select");
    if (event.keyCode == 27 && view.inputState.tabFocusMode != 0)
        view.inputState.tabFocusMode = Date.now() + 2000;
    return false;
};
observers.touchstart = (view, e) => {
    view.inputState.lastTouchTime = Date.now();
    view.inputState.setSelectionOrigin("select.pointer");
};
observers.touchmove = view => {
    view.inputState.setSelectionOrigin("select.pointer");
};
handlers.mousedown = (view, event) => {
    view.observer.flush();
    if (view.inputState.lastTouchTime > Date.now() - 2000)
        return false; // Ignore touch interaction
    let style = null;
    for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
        style = makeStyle(view, event);
        if (style)
            break;
    }
    if (!style && event.button == 0)
        style = basicMouseSelection(view, event);
    if (style) {
        let mustFocus = !view.hasFocus;
        view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus));
        if (mustFocus)
            view.observer.ignore(() => {
                focusPreventScroll(view.contentDOM);
                let active = view.root.activeElement;
                if (active && !active.contains(view.contentDOM))
                    active.blur();
            });
        let mouseSel = view.inputState.mouseSelection;
        if (mouseSel) {
            mouseSel.start(event);
            return mouseSel.dragging === false;
        }
    }
    else {
        view.inputState.setSelectionOrigin("select.pointer");
    }
    return false;
};
function rangeForClick(view, pos, bias, type) {
    if (type == 1) { // Single click
        return dist_EditorSelection.cursor(pos, bias);
    }
    else if (type == 2) { // Double click
        return groupAt(view.state, pos, bias);
    }
    else { // Triple click
        let visual = view.docView.lineAt(pos, bias), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);
        let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to;
        if (to < view.state.doc.length && to == line.to)
            to++;
        return dist_EditorSelection.range(from, to);
    }
}
const BadMouseDetail = browser.ie && browser.ie_version <= 11;
let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0;
function getClickType(event) {
    if (!BadMouseDetail)
        return event.detail;
    let last = lastMouseDown, lastTime = lastMouseDownTime;
    lastMouseDown = event;
    lastMouseDownTime = Date.now();
    return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 &&
        Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1;
}
function basicMouseSelection(view, event) {
    let start = view.posAndSideAtCoords({ x: event.clientX, y: event.clientY }, false), type = getClickType(event);
    let startSel = view.state.selection;
    return {
        update(update) {
            if (update.docChanged) {
                start.pos = update.changes.mapPos(start.pos);
                startSel = startSel.map(update.changes);
            }
        },
        get(event, extend, multiple) {
            let cur = view.posAndSideAtCoords({ x: event.clientX, y: event.clientY }, false), removed;
            let range = rangeForClick(view, cur.pos, cur.assoc, type);
            if (start.pos != cur.pos && !extend) {
                let startRange = rangeForClick(view, start.pos, start.assoc, type);
                let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to);
                range = from < range.from ? dist_EditorSelection.range(from, to) : dist_EditorSelection.range(to, from);
            }
            if (extend)
                return startSel.replaceRange(startSel.main.extend(range.from, range.to));
            else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur.pos)))
                return removed;
            else if (multiple)
                return startSel.addRange(range);
            else
                return dist_EditorSelection.create([range]);
        }
    };
}
function removeRangeAround(sel, pos) {
    for (let i = 0; i < sel.ranges.length; i++) {
        let { from, to } = sel.ranges[i];
        if (from <= pos && to >= pos)
            return dist_EditorSelection.create(sel.ranges.slice(0, i).concat(sel.ranges.slice(i + 1)), sel.mainIndex == i ? 0 : sel.mainIndex - (sel.mainIndex > i ? 1 : 0));
    }
    return null;
}
handlers.dragstart = (view, event) => {
    let { selection: { main: range } } = view.state;
    if (event.target.draggable) {
        let tile = view.docView.tile.nearest(event.target);
        if (tile && tile.isWidget()) {
            let from = tile.posAtStart, to = from + tile.length;
            if (from >= range.to || to <= range.from)
                range = dist_EditorSelection.range(from, to);
        }
    }
    let { inputState } = view;
    if (inputState.mouseSelection)
        inputState.mouseSelection.dragging = true;
    inputState.draggedContent = range;
    if (event.dataTransfer) {
        event.dataTransfer.setData("Text", textFilter(view.state, clipboardOutputFilter, view.state.sliceDoc(range.from, range.to)));
        event.dataTransfer.effectAllowed = "copyMove";
    }
    return false;
};
handlers.dragend = view => {
    view.inputState.draggedContent = null;
    return false;
};
function dropText(view, event, text, direct) {
    text = textFilter(view.state, clipboardInputFilter, text);
    if (!text)
        return;
    let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
    let { draggedContent } = view.inputState;
    let del = direct && draggedContent && dragMovesSelection(view, event)
        ? { from: draggedContent.from, to: draggedContent.to } : null;
    let ins = { from: dropPos, insert: text };
    let changes = view.state.changes(del ? [del, ins] : ins);
    view.focus();
    view.dispatch({
        changes,
        selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) },
        userEvent: del ? "move.drop" : "input.drop"
    });
    view.inputState.draggedContent = null;
}
handlers.drop = (view, event) => {
    if (!event.dataTransfer)
        return false;
    if (view.state.readOnly)
        return true;
    let files = event.dataTransfer.files;
    if (files && files.length) { // For a file drop, read the file's text.
        let text = Array(files.length), read = 0;
        let finishFile = () => {
            if (++read == files.length)
                dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false);
        };
        for (let i = 0; i < files.length; i++) {
            let reader = new FileReader;
            reader.onerror = finishFile;
            reader.onload = () => {
                if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result))
                    text[i] = reader.result;
                finishFile();
            };
            reader.readAsText(files[i]);
        }
        return true;
    }
    else {
        let text = event.dataTransfer.getData("Text");
        if (text) {
            dropText(view, event, text, true);
            return true;
        }
    }
    return false;
};
handlers.paste = (view, event) => {
    if (view.state.readOnly)
        return true;
    view.observer.flush();
    let data = brokenClipboardAPI ? null : event.clipboardData;
    if (data) {
        doPaste(view, data.getData("text/plain") || data.getData("text/uri-list"));
        return true;
    }
    else {
        capturePaste(view);
        return false;
    }
};
function captureCopy(view, text) {
    // The extra wrapper is somehow necessary on IE/Edge to prevent the
    // content from being mangled when it is put onto the clipboard
    let parent = view.dom.parentNode;
    if (!parent)
        return;
    let target = parent.appendChild(document.createElement("textarea"));
    target.style.cssText = "position: fixed; left: -10000px; top: 10px";
    target.value = text;
    target.focus();
    target.selectionEnd = text.length;
    target.selectionStart = 0;
    setTimeout(() => {
        target.remove();
        view.focus();
    }, 50);
}
function copiedRange(state) {
    let content = [], ranges = [], linewise = false;
    for (let range of state.selection.ranges)
        if (!range.empty) {
            content.push(state.sliceDoc(range.from, range.to));
            ranges.push(range);
        }
    if (!content.length) {
        // Nothing selected, do a line-wise copy
        let upto = -1;
        for (let { from } of state.selection.ranges) {
            let line = state.doc.lineAt(from);
            if (line.number > upto) {
                content.push(line.text);
                ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) });
            }
            upto = line.number;
        }
        linewise = true;
    }
    return { text: textFilter(state, clipboardOutputFilter, content.join(state.lineBreak)), ranges, linewise };
}
let lastLinewiseCopy = null;
handlers.copy = handlers.cut = (view, event) => {
    let { text, ranges, linewise } = copiedRange(view.state);
    if (!text && !linewise)
        return false;
    lastLinewiseCopy = linewise ? text : null;
    if (event.type == "cut" && !view.state.readOnly)
        view.dispatch({
            changes: ranges,
            scrollIntoView: true,
            userEvent: "delete.cut"
        });
    let data = brokenClipboardAPI ? null : event.clipboardData;
    if (data) {
        data.clearData();
        data.setData("text/plain", text);
        return true;
    }
    else {
        captureCopy(view, text);
        return false;
    }
};
const isFocusChange = /*@__PURE__*/Annotation.define();
function focusChangeTransaction(state, focus) {
    let effects = [];
    for (let getEffect of state.facet(focusChangeEffect)) {
        let effect = getEffect(state, focus);
        if (effect)
            effects.push(effect);
    }
    return effects.length ? state.update({ effects, annotations: isFocusChange.of(true) }) : null;
}
function updateForFocusChange(view) {
    setTimeout(() => {
        let focus = view.hasFocus;
        if (focus != view.inputState.notifiedFocused) {
            let tr = focusChangeTransaction(view.state, focus);
            if (tr)
                view.dispatch(tr);
            else
                view.update([]);
        }
    }, 10);
}
observers.focus = view => {
    view.inputState.lastFocusTime = Date.now();
    // When focusing reset the scroll position, move it back to where it was
    if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {
        view.scrollDOM.scrollTop = view.inputState.lastScrollTop;
        view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;
    }
    updateForFocusChange(view);
};
observers.blur = view => {
    view.observer.clearSelectionRange();
    updateForFocusChange(view);
};
observers.compositionstart = observers.compositionupdate = view => {
    if (view.observer.editContext)
        return; // Composition handled by edit context
    if (view.inputState.compositionFirstChange == null)
        view.inputState.compositionFirstChange = true;
    if (view.inputState.composing < 0) {
        // FIXME possibly set a timeout to clear it again on Android
        view.inputState.composing = 0;
    }
};
observers.compositionend = view => {
    if (view.observer.editContext)
        return; // Composition handled by edit context
    view.inputState.composing = -1;
    view.inputState.compositionEndedAt = Date.now();
    view.inputState.compositionPendingKey = true;
    view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;
    view.inputState.compositionFirstChange = null;
    if (browser.chrome && browser.android) {
        // Delay flushing for a bit on Android because it'll often fire a
        // bunch of contradictory changes in a row at end of compositon
        view.observer.flushSoon();
    }
    else if (view.inputState.compositionPendingChange) {
        // If we found pending records, schedule a flush.
        Promise.resolve().then(() => view.observer.flush());
    }
    else {
        // Otherwise, make sure that, if no changes come in soon, the
        // composition view is cleared.
        setTimeout(() => {
            if (view.inputState.composing < 0 && view.docView.hasComposition)
                view.update([]);
        }, 50);
    }
};
observers.contextmenu = view => {
    view.inputState.lastContextMenu = Date.now();
};
handlers.beforeinput = (view, event) => {
    var _a, _b;
    if (event.inputType == "insertText" || event.inputType == "insertCompositionText") {
        view.inputState.insertingText = event.data;
        view.inputState.insertingTextAt = Date.now();
    }
    // In EditContext mode, we must handle insertReplacementText events
    // directly, to make spell checking corrections work
    if (event.inputType == "insertReplacementText" && view.observer.editContext) {
        let text = (_a = event.dataTransfer) === null || _a === void 0 ? void 0 : _a.getData("text/plain"), ranges = event.getTargetRanges();
        if (text && ranges.length) {
            let r = ranges[0];
            let from = view.posAtDOM(r.startContainer, r.startOffset), to = view.posAtDOM(r.endContainer, r.endOffset);
            applyDOMChangeInner(view, { from, to, insert: view.state.toText(text) }, null);
            return true;
        }
    }
    // Because Chrome Android doesn't fire useful key events, use
    // beforeinput to detect backspace (and possibly enter and delete,
    // but those usually don't even seem to fire beforeinput events at
    // the moment) and fake a key event for it.
    //
    // (preventDefault on beforeinput, though supported in the spec,
    // seems to do nothing at all on Chrome).
    let pending;
    if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) {
        view.observer.delayAndroidKey(pending.key, pending.keyCode);
        if (pending.key == "Backspace" || pending.key == "Delete") {
            let startViewHeight = ((_b = window.visualViewport) === null || _b === void 0 ? void 0 : _b.height) || 0;
            setTimeout(() => {
                var _a;
                // Backspacing near uneditable nodes on Chrome Android sometimes
                // closes the virtual keyboard. This tries to crudely detect
                // that and refocus to get it back.
                if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) {
                    view.contentDOM.blur();
                    view.focus();
                }
            }, 100);
        }
    }
    if (browser.ios && event.inputType == "deleteContentForward") {
        // For some reason, DOM changes (and beforeinput) happen _before_
        // the key event for ctrl-d on iOS when using an external
        // keyboard.
        view.observer.flushSoon();
    }
    // Safari will occasionally forget to fire compositionend at the end of a dead-key composition
    if (browser.safari && event.inputType == "insertText" && view.inputState.composing >= 0) {
        setTimeout(() => observers.compositionend(view, event), 20);
    }
    return false;
};
const appliedFirefoxHack = /*@__PURE__*/new Set;
// In Firefox, when cut/copy handlers are added to the document, that
// somehow avoids a bug where those events aren't fired when the
// selection is empty. See https://github.com/codemirror/dev/issues/1082
// and https://bugzilla.mozilla.org/show_bug.cgi?id=995961
function firefoxCopyCutHack(doc) {
    if (!appliedFirefoxHack.has(doc)) {
        appliedFirefoxHack.add(doc);
        doc.addEventListener("copy", () => { });
        doc.addEventListener("cut", () => { });
    }
}

const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"];
// Used to track, during updateHeight, if any actual heights changed
let heightChangeFlag = false;
function clearHeightChangeFlag() { heightChangeFlag = false; }
class HeightOracle {
    constructor(lineWrapping) {
        this.lineWrapping = lineWrapping;
        this.doc = dist_Text.empty;
        this.heightSamples = {};
        this.lineHeight = 14; // The height of an entire line (line-height)
        this.charWidth = 7;
        this.textHeight = 14; // The height of the actual font (font-size)
        this.lineLength = 30;
    }
    heightForGap(from, to) {
        let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;
        if (this.lineWrapping)
            lines += Math.max(0, Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength));
        return this.lineHeight * lines;
    }
    heightForLine(length) {
        if (!this.lineWrapping)
            return this.lineHeight;
        let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / Math.max(1, this.lineLength - 5)));
        return lines * this.lineHeight;
    }
    setDoc(doc) { this.doc = doc; return this; }
    mustRefreshForWrapping(whiteSpace) {
        return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping;
    }
    mustRefreshForHeights(lineHeights) {
        let newHeight = false;
        for (let i = 0; i < lineHeights.length; i++) {
            let h = lineHeights[i];
            if (h < 0) {
                i++;
            }
            else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels
                newHeight = true;
                this.heightSamples[Math.floor(h * 10)] = true;
            }
        }
        return newHeight;
    }
    refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {
        let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;
        let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping;
        this.lineWrapping = lineWrapping;
        this.lineHeight = lineHeight;
        this.charWidth = charWidth;
        this.textHeight = textHeight;
        this.lineLength = lineLength;
        if (changed) {
            this.heightSamples = {};
            for (let i = 0; i < knownHeights.length; i++) {
                let h = knownHeights[i];
                if (h < 0)
                    i++;
                else
                    this.heightSamples[Math.floor(h * 10)] = true;
            }
        }
        return changed;
    }
}
// This object is used by `updateHeight` to make DOM measurements
// arrive at the right nodes. The `heights` array is a sequence of
// block heights, starting from position `from`.
class MeasuredHeights {
    constructor(from, heights) {
        this.from = from;
        this.heights = heights;
        this.index = 0;
    }
    get more() { return this.index < this.heights.length; }
}
/**
Record used to represent information about a block-level element
in the editor view.
*/
class BlockInfo {
    /**
    @internal
    */
    constructor(
    /**
    The start of the element in the document.
    */
    from, 
    /**
    The length of the element.
    */
    length, 
    /**
    The top position of the element (relative to the top of the
    document).
    */
    top, 
    /**
    Its height.
    */
    height, 
    /**
    @internal Weird packed field that holds an array of children
    for composite blocks, a decoration for block widgets, and a
    number indicating the amount of widget-created line breaks for
    text blocks.
    */
    _content) {
        this.from = from;
        this.length = length;
        this.top = top;
        this.height = height;
        this._content = _content;
    }
    /**
    The type of element this is. When querying lines, this may be
    an array of all the blocks that make up the line.
    */
    get type() {
        return typeof this._content == "number" ? BlockType.Text :
            Array.isArray(this._content) ? this._content : this._content.type;
    }
    /**
    The end of the element as a document position.
    */
    get to() { return this.from + this.length; }
    /**
    The bottom position of the element.
    */
    get bottom() { return this.top + this.height; }
    /**
    If this is a widget block, this will return the widget
    associated with it.
    */
    get widget() {
        return this._content instanceof PointDecoration ? this._content.widget : null;
    }
    /**
    If this is a textblock, this holds the number of line breaks
    that appear in widgets inside the block.
    */
    get widgetLineBreaks() {
        return typeof this._content == "number" ? this._content : 0;
    }
    /**
    @internal
    */
    join(other) {
        let content = (Array.isArray(this._content) ? this._content : [this])
            .concat(Array.isArray(other._content) ? other._content : [other]);
        return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content);
    }
}
var QueryType = /*@__PURE__*/(function (QueryType) {
    QueryType[QueryType["ByPos"] = 0] = "ByPos";
    QueryType[QueryType["ByHeight"] = 1] = "ByHeight";
    QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight";
return QueryType})(QueryType || (QueryType = {}));
const Epsilon = 1e-3;
class HeightMap {
    constructor(length, // The number of characters covered
    height, // Height of this part of the document
    flags = 2 /* Flag.Outdated */) {
        this.length = length;
        this.height = height;
        this.flags = flags;
    }
    get outdated() { return (this.flags & 2 /* Flag.Outdated */) > 0; }
    set outdated(value) { this.flags = (value ? 2 /* Flag.Outdated */ : 0) | (this.flags & ~2 /* Flag.Outdated */); }
    setHeight(height) {
        if (this.height != height) {
            if (Math.abs(this.height - height) > Epsilon)
                heightChangeFlag = true;
            this.height = height;
        }
    }
    // Base case is to replace a leaf node, which simply builds a tree
    // from the new nodes and returns that (HeightMapBranch and
    // HeightMapGap override this to actually use from/to)
    replace(_from, _to, nodes) {
        return HeightMap.of(nodes);
    }
    // Again, these are base cases, and are overridden for branch and gap nodes.
    decomposeLeft(_to, result) { result.push(this); }
    decomposeRight(_from, result) { result.push(this); }
    applyChanges(decorations, oldDoc, oracle, changes) {
        let me = this, doc = oracle.doc;
        for (let i = changes.length - 1; i >= 0; i--) {
            let { fromA, toA, fromB, toB } = changes[i];
            let start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);
            let end = start.to >= toA ? start : me.lineAt(toA, QueryType.ByPosNoHeight, oracle, 0, 0);
            toB += end.to - toA;
            toA = end.to;
            while (i > 0 && start.from <= changes[i - 1].toA) {
                fromA = changes[i - 1].fromA;
                fromB = changes[i - 1].fromB;
                i--;
                if (fromA < start.from)
                    start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle, 0, 0);
            }
            fromB += start.from - fromA;
            fromA = start.from;
            let nodes = NodeBuilder.build(oracle.setDoc(doc), decorations, fromB, toB);
            me = replace(me, me.replace(fromA, toA, nodes));
        }
        return me.updateHeight(oracle, 0);
    }
    static empty() { return new HeightMapText(0, 0, 0); }
    // nodes uses null values to indicate the position of line breaks.
    // There are never line breaks at the start or end of the array, or
    // two line breaks next to each other, and the array isn't allowed
    // to be empty (same restrictions as return value from the builder).
    static of(nodes) {
        if (nodes.length == 1)
            return nodes[0];
        let i = 0, j = nodes.length, before = 0, after = 0;
        for (;;) {
            if (i == j) {
                if (before > after * 2) {
                    let split = nodes[i - 1];
                    if (split.break)
                        nodes.splice(--i, 1, split.left, null, split.right);
                    else
                        nodes.splice(--i, 1, split.left, split.right);
                    j += 1 + split.break;
                    before -= split.size;
                }
                else if (after > before * 2) {
                    let split = nodes[j];
                    if (split.break)
                        nodes.splice(j, 1, split.left, null, split.right);
                    else
                        nodes.splice(j, 1, split.left, split.right);
                    j += 2 + split.break;
                    after -= split.size;
                }
                else {
                    break;
                }
            }
            else if (before < after) {
                let next = nodes[i++];
                if (next)
                    before += next.size;
            }
            else {
                let next = nodes[--j];
                if (next)
                    after += next.size;
            }
        }
        let brk = 0;
        if (nodes[i - 1] == null) {
            brk = 1;
            i--;
        }
        else if (nodes[i] == null) {
            brk = 1;
            j++;
        }
        return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j)));
    }
}
function replace(old, val) {
    if (old == val)
        return old;
    if (old.constructor != val.constructor)
        heightChangeFlag = true;
    return val;
}
HeightMap.prototype.size = 1;
const SpaceDeco = /*@__PURE__*/dist_Decoration.replace({});
class HeightMapBlock extends HeightMap {
    constructor(length, height, deco) {
        super(length, height);
        this.deco = deco;
        this.spaceAbove = 0;
    }
    mainBlock(top, offset) {
        return new BlockInfo(offset, this.length, top + this.spaceAbove, this.height - this.spaceAbove, this.deco || 0);
    }
    blockAt(height, _oracle, top, offset) {
        return this.spaceAbove && height < top + this.spaceAbove ? new BlockInfo(offset, 0, top, this.spaceAbove, SpaceDeco)
            : this.mainBlock(top, offset);
    }
    lineAt(_value, _type, oracle, top, offset) {
        let main = this.mainBlock(top, offset);
        return this.spaceAbove ? this.blockAt(0, oracle, top, offset).join(main) : main;
    }
    forEachLine(from, to, oracle, top, offset, f) {
        if (from <= offset + this.length && to >= offset)
            f(this.lineAt(0, QueryType.ByPos, oracle, top, offset));
    }
    setMeasuredHeight(measured) {
        let next = measured.heights[measured.index++];
        if (next < 0) {
            this.spaceAbove = -next;
            next = measured.heights[measured.index++];
        }
        else {
            this.spaceAbove = 0;
        }
        this.setHeight(next);
    }
    updateHeight(oracle, offset = 0, _force = false, measured) {
        if (measured && measured.from <= offset && measured.more)
            this.setMeasuredHeight(measured);
        this.outdated = false;
        return this;
    }
    toString() { return `block(${this.length})`; }
}
class HeightMapText extends HeightMapBlock {
    constructor(length, height, above) {
        super(length, height, null);
        this.collapsed = 0; // Amount of collapsed content in the line
        this.widgetHeight = 0; // Maximum inline widget height
        this.breaks = 0; // Number of widget-introduced line breaks on the line
        this.spaceAbove = above;
    }
    mainBlock(top, offset) {
        return new BlockInfo(offset, this.length, top + this.spaceAbove, this.height - this.spaceAbove, this.breaks);
    }
    replace(_from, _to, nodes) {
        let node = nodes[0];
        if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* Flag.SingleLine */)) &&
            Math.abs(this.length - node.length) < 10) {
            if (node instanceof HeightMapGap)
                node = new HeightMapText(node.length, this.height, this.spaceAbove);
            else
                node.height = this.height;
            if (!this.outdated)
                node.outdated = false;
            return node;
        }
        else {
            return HeightMap.of(nodes);
        }
    }
    updateHeight(oracle, offset = 0, force = false, measured) {
        if (measured && measured.from <= offset && measured.more) {
            this.setMeasuredHeight(measured);
        }
        else if (force || this.outdated) {
            this.spaceAbove = 0;
            this.setHeight(Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) +
                this.breaks * oracle.lineHeight);
        }
        this.outdated = false;
        return this;
    }
    toString() {
        return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`;
    }
}
class HeightMapGap extends HeightMap {
    constructor(length) { super(length, 0); }
    heightMetrics(oracle, offset) {
        let firstLine = oracle.doc.lineAt(offset).number, lastLine = oracle.doc.lineAt(offset + this.length).number;
        let lines = lastLine - firstLine + 1;
        let perLine, perChar = 0;
        if (oracle.lineWrapping) {
            let totalPerLine = Math.min(this.height, oracle.lineHeight * lines);
            perLine = totalPerLine / lines;
            if (this.length > lines + 1)
                perChar = (this.height - totalPerLine) / (this.length - lines - 1);
        }
        else {
            perLine = this.height / lines;
        }
        return { firstLine, lastLine, perLine, perChar };
    }
    blockAt(height, oracle, top, offset) {
        let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset);
        if (oracle.lineWrapping) {
            let guess = offset + (height < oracle.lineHeight ? 0
                : Math.round(Math.max(0, Math.min(1, (height - top) / this.height)) * this.length));
            let line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar;
            let lineTop = Math.max(top, height - lineHeight / 2);
            return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0);
        }
        else {
            let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / perLine)));
            let { from, length } = oracle.doc.line(firstLine + line);
            return new BlockInfo(from, length, top + perLine * line, perLine, 0);
        }
    }
    lineAt(value, type, oracle, top, offset) {
        if (type == QueryType.ByHeight)
            return this.blockAt(value, oracle, top, offset);
        if (type == QueryType.ByPosNoHeight) {
            let { from, to } = oracle.doc.lineAt(value);
            return new BlockInfo(from, to - from, 0, 0, 0);
        }
        let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
        let line = oracle.doc.lineAt(value), lineHeight = perLine + line.length * perChar;
        let linesAbove = line.number - firstLine;
        let lineTop = top + perLine * linesAbove + perChar * (line.from - offset - linesAbove);
        return new BlockInfo(line.from, line.length, Math.max(top, Math.min(lineTop, top + this.height - lineHeight)), lineHeight, 0);
    }
    forEachLine(from, to, oracle, top, offset, f) {
        from = Math.max(from, offset);
        to = Math.min(to, offset + this.length);
        let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
        for (let pos = from, lineTop = top; pos <= to;) {
            let line = oracle.doc.lineAt(pos);
            if (pos == from) {
                let linesAbove = line.number - firstLine;
                lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);
            }
            let lineHeight = perLine + perChar * line.length;
            f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0));
            lineTop += lineHeight;
            pos = line.to + 1;
        }
    }
    replace(from, to, nodes) {
        let after = this.length - to;
        if (after > 0) {
            let last = nodes[nodes.length - 1];
            if (last instanceof HeightMapGap)
                nodes[nodes.length - 1] = new HeightMapGap(last.length + after);
            else
                nodes.push(null, new HeightMapGap(after - 1));
        }
        if (from > 0) {
            let first = nodes[0];
            if (first instanceof HeightMapGap)
                nodes[0] = new HeightMapGap(from + first.length);
            else
                nodes.unshift(new HeightMapGap(from - 1), null);
        }
        return HeightMap.of(nodes);
    }
    decomposeLeft(to, result) {
        result.push(new HeightMapGap(to - 1), null);
    }
    decomposeRight(from, result) {
        result.push(null, new HeightMapGap(this.length - from - 1));
    }
    updateHeight(oracle, offset = 0, force = false, measured) {
        let end = offset + this.length;
        if (measured && measured.from <= offset + this.length && measured.more) {
            // Fill in part of this gap with measured lines. We know there
            // can't be widgets or collapsed ranges in those lines, because
            // they would already have been added to the heightmap (gaps
            // only contain plain text).
            let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1;
            if (measured.from > offset)
                nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));
            while (pos <= end && measured.more) {
                let len = oracle.doc.lineAt(pos).length;
                if (nodes.length)
                    nodes.push(null);
                let height = measured.heights[measured.index++], above = 0;
                if (height < 0) {
                    above = -height;
                    height = measured.heights[measured.index++];
                }
                if (singleHeight == -1)
                    singleHeight = height;
                else if (Math.abs(height - singleHeight) >= Epsilon)
                    singleHeight = -2;
                let line = new HeightMapText(len, height, above);
                line.outdated = false;
                nodes.push(line);
                pos += len + 1;
            }
            if (pos <= end)
                nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos));
            let result = HeightMap.of(nodes);
            if (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon ||
                Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon)
                heightChangeFlag = true;
            return replace(this, result);
        }
        else if (force || this.outdated) {
            this.setHeight(oracle.heightForGap(offset, offset + this.length));
            this.outdated = false;
        }
        return this;
    }
    toString() { return `gap(${this.length})`; }
}
class HeightMapBranch extends HeightMap {
    constructor(left, brk, right) {
        super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Flag.Outdated */ : 0));
        this.left = left;
        this.right = right;
        this.size = left.size + right.size;
    }
    get break() { return this.flags & 1 /* Flag.Break */; }
    blockAt(height, oracle, top, offset) {
        let mid = top + this.left.height;
        return height < mid ? this.left.blockAt(height, oracle, top, offset)
            : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);
    }
    lineAt(value, type, oracle, top, offset) {
        let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;
        let left = type == QueryType.ByHeight ? value < rightTop : value < rightOffset;
        let base = left ? this.left.lineAt(value, type, oracle, top, offset)
            : this.right.lineAt(value, type, oracle, rightTop, rightOffset);
        if (this.break || (left ? base.to < rightOffset : base.from > rightOffset))
            return base;
        let subQuery = type == QueryType.ByPosNoHeight ? QueryType.ByPosNoHeight : QueryType.ByPos;
        if (left)
            return base.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));
        else
            return this.left.lineAt(rightOffset, subQuery, oracle, top, offset).join(base);
    }
    forEachLine(from, to, oracle, top, offset, f) {
        let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;
        if (this.break) {
            if (from < rightOffset)
                this.left.forEachLine(from, to, oracle, top, offset, f);
            if (to >= rightOffset)
                this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f);
        }
        else {
            let mid = this.lineAt(rightOffset, QueryType.ByPos, oracle, top, offset);
            if (from < mid.from)
                this.left.forEachLine(from, mid.from - 1, oracle, top, offset, f);
            if (mid.to >= from && mid.from <= to)
                f(mid);
            if (to > mid.to)
                this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f);
        }
    }
    replace(from, to, nodes) {
        let rightStart = this.left.length + this.break;
        if (to < rightStart)
            return this.balanced(this.left.replace(from, to, nodes), this.right);
        if (from > this.left.length)
            return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));
        let result = [];
        if (from > 0)
            this.decomposeLeft(from, result);
        let left = result.length;
        for (let node of nodes)
            result.push(node);
        if (from > 0)
            mergeGaps(result, left - 1);
        if (to < this.length) {
            let right = result.length;
            this.decomposeRight(to, result);
            mergeGaps(result, right);
        }
        return HeightMap.of(result);
    }
    decomposeLeft(to, result) {
        let left = this.left.length;
        if (to <= left)
            return this.left.decomposeLeft(to, result);
        result.push(this.left);
        if (this.break) {
            left++;
            if (to >= left)
                result.push(null);
        }
        if (to > left)
            this.right.decomposeLeft(to - left, result);
    }
    decomposeRight(from, result) {
        let left = this.left.length, right = left + this.break;
        if (from >= right)
            return this.right.decomposeRight(from - right, result);
        if (from < left)
            this.left.decomposeRight(from, result);
        if (this.break && from < right)
            result.push(null);
        result.push(this.right);
    }
    balanced(left, right) {
        if (left.size > 2 * right.size || right.size > 2 * left.size)
            return HeightMap.of(this.break ? [left, null, right] : [left, right]);
        this.left = replace(this.left, left);
        this.right = replace(this.right, right);
        this.setHeight(left.height + right.height);
        this.outdated = left.outdated || right.outdated;
        this.size = left.size + right.size;
        this.length = left.length + this.break + right.length;
        return this;
    }
    updateHeight(oracle, offset = 0, force = false, measured) {
        let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null;
        if (measured && measured.from <= offset + left.length && measured.more)
            rebalance = left = left.updateHeight(oracle, offset, force, measured);
        else
            left.updateHeight(oracle, offset, force);
        if (measured && measured.from <= rightStart + right.length && measured.more)
            rebalance = right = right.updateHeight(oracle, rightStart, force, measured);
        else
            right.updateHeight(oracle, rightStart, force);
        if (rebalance)
            return this.balanced(left, right);
        this.height = this.left.height + this.right.height;
        this.outdated = false;
        return this;
    }
    toString() { return this.left + (this.break ? " " : "-") + this.right; }
}
function mergeGaps(nodes, around) {
    let before, after;
    if (nodes[around] == null &&
        (before = nodes[around - 1]) instanceof HeightMapGap &&
        (after = nodes[around + 1]) instanceof HeightMapGap)
        nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length));
}
const relevantWidgetHeight = 5;
class NodeBuilder {
    constructor(pos, oracle) {
        this.pos = pos;
        this.oracle = oracle;
        this.nodes = [];
        this.lineStart = -1;
        this.lineEnd = -1;
        this.covering = null;
        this.writtenTo = pos;
    }
    get isCovered() {
        return this.covering && this.nodes[this.nodes.length - 1] == this.covering;
    }
    span(_from, to) {
        if (this.lineStart > -1) {
            let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1];
            if (last instanceof HeightMapText)
                last.length += end - this.pos;
            else if (end > this.pos || !this.isCovered)
                this.nodes.push(new HeightMapText(end - this.pos, -1, 0));
            this.writtenTo = end;
            if (to > end) {
                this.nodes.push(null);
                this.writtenTo++;
                this.lineStart = -1;
            }
        }
        this.pos = to;
    }
    point(from, to, deco) {
        if (from < to || deco.heightRelevant) {
            let height = deco.widget ? deco.widget.estimatedHeight : 0;
            let breaks = deco.widget ? deco.widget.lineBreaks : 0;
            if (height < 0)
                height = this.oracle.lineHeight;
            let len = to - from;
            if (deco.block) {
                this.addBlock(new HeightMapBlock(len, height, deco));
            }
            else if (len || breaks || height >= relevantWidgetHeight) {
                this.addLineDeco(height, breaks, len);
            }
        }
        else if (to > from) {
            this.span(from, to);
        }
        if (this.lineEnd > -1 && this.lineEnd < this.pos)
            this.lineEnd = this.oracle.doc.lineAt(this.pos).to;
    }
    enterLine() {
        if (this.lineStart > -1)
            return;
        let { from, to } = this.oracle.doc.lineAt(this.pos);
        this.lineStart = from;
        this.lineEnd = to;
        if (this.writtenTo < from) {
            if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null)
                this.nodes.push(this.blankContent(this.writtenTo, from - 1));
            this.nodes.push(null);
        }
        if (this.pos > from)
            this.nodes.push(new HeightMapText(this.pos - from, -1, 0));
        this.writtenTo = this.pos;
    }
    blankContent(from, to) {
        let gap = new HeightMapGap(to - from);
        if (this.oracle.doc.lineAt(from).to == to)
            gap.flags |= 4 /* Flag.SingleLine */;
        return gap;
    }
    ensureLine() {
        this.enterLine();
        let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;
        if (last instanceof HeightMapText)
            return last;
        let line = new HeightMapText(0, -1, 0);
        this.nodes.push(line);
        return line;
    }
    addBlock(block) {
        this.enterLine();
        let deco = block.deco;
        if (deco && deco.startSide > 0 && !this.isCovered)
            this.ensureLine();
        this.nodes.push(block);
        this.writtenTo = this.pos = this.pos + block.length;
        if (deco && deco.endSide > 0)
            this.covering = block;
    }
    addLineDeco(height, breaks, length) {
        let line = this.ensureLine();
        line.length += length;
        line.collapsed += length;
        line.widgetHeight = Math.max(line.widgetHeight, height);
        line.breaks += breaks;
        this.writtenTo = this.pos = this.pos + length;
    }
    finish(from) {
        let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];
        if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered)
            this.nodes.push(new HeightMapText(0, -1, 0));
        else if (this.writtenTo < this.pos || last == null)
            this.nodes.push(this.blankContent(this.writtenTo, this.pos));
        let pos = from;
        for (let node of this.nodes) {
            if (node instanceof HeightMapText)
                node.updateHeight(this.oracle, pos);
            pos += node ? node.length : 1;
        }
        return this.nodes;
    }
    // Always called with a region that on both sides either stretches
    // to a line break or the end of the document.
    // The returned array uses null to indicate line breaks, but never
    // starts or ends in a line break, or has multiple line breaks next
    // to each other.
    static build(oracle, decorations, from, to) {
        let builder = new NodeBuilder(from, oracle);
        dist_RangeSet.spans(decorations, from, to, builder, 0);
        return builder.finish(from);
    }
}
function heightRelevantDecoChanges(a, b, diff) {
    let comp = new DecorationComparator;
    dist_RangeSet.compare(a, b, diff, comp, 0);
    return comp.changes;
}
class DecorationComparator {
    constructor() {
        this.changes = [];
    }
    compareRange() { }
    comparePoint(from, to, a, b) {
        if (from < to || a && a.heightRelevant || b && b.heightRelevant)
            addRange(from, to, this.changes, 5);
    }
}

function visiblePixelRange(dom, paddingTop) {
    let rect = dom.getBoundingClientRect();
    let doc = dom.ownerDocument, win = doc.defaultView || window;
    let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right);
    let top = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom);
    for (let parent = dom.parentNode; parent && parent != doc.body;) {
        if (parent.nodeType == 1) {
            let elt = parent;
            let style = window.getComputedStyle(elt);
            if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) &&
                style.overflow != "visible") {
                let parentRect = elt.getBoundingClientRect();
                left = Math.max(left, parentRect.left);
                right = Math.min(right, parentRect.right);
                top = Math.max(top, parentRect.top);
                bottom = Math.min(parent == dom.parentNode ? win.innerHeight : bottom, parentRect.bottom);
            }
            parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode;
        }
        else if (parent.nodeType == 11) { // Shadow root
            parent = parent.host;
        }
        else {
            break;
        }
    }
    return { left: left - rect.left, right: Math.max(left, right) - rect.left,
        top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) };
}
function inWindow(elt) {
    let rect = elt.getBoundingClientRect(), win = elt.ownerDocument.defaultView || window;
    return rect.left < win.innerWidth && rect.right > 0 &&
        rect.top < win.innerHeight && rect.bottom > 0;
}
function fullPixelRange(dom, paddingTop) {
    let rect = dom.getBoundingClientRect();
    return { left: 0, right: rect.right - rect.left,
        top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) };
}
// Line gaps are placeholder widgets used to hide pieces of overlong
// lines within the viewport, as a kludge to keep the editor
// responsive when a ridiculously long line is loaded into it.
class LineGap {
    constructor(from, to, size, displaySize) {
        this.from = from;
        this.to = to;
        this.size = size;
        this.displaySize = displaySize;
    }
    static same(a, b) {
        if (a.length != b.length)
            return false;
        for (let i = 0; i < a.length; i++) {
            let gA = a[i], gB = b[i];
            if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size)
                return false;
        }
        return true;
    }
    draw(viewState, wrapping) {
        return dist_Decoration.replace({
            widget: new LineGapWidget(this.displaySize * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping)
        }).range(this.from, this.to);
    }
}
class LineGapWidget extends WidgetType {
    constructor(size, vertical) {
        super();
        this.size = size;
        this.vertical = vertical;
    }
    eq(other) { return other.size == this.size && other.vertical == this.vertical; }
    toDOM() {
        let elt = document.createElement("div");
        if (this.vertical) {
            elt.style.height = this.size + "px";
        }
        else {
            elt.style.width = this.size + "px";
            elt.style.height = "2px";
            elt.style.display = "inline-block";
        }
        return elt;
    }
    get estimatedHeight() { return this.vertical ? this.size : -1; }
}
class ViewState {
    constructor(state) {
        this.state = state;
        // These are contentDOM-local coordinates
        this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 };
        this.inView = true;
        this.paddingTop = 0; // Padding above the document, scaled
        this.paddingBottom = 0; // Padding below the document, scaled
        this.contentDOMWidth = 0; // contentDOM.getBoundingClientRect().width
        this.contentDOMHeight = 0; // contentDOM.getBoundingClientRect().height
        this.editorHeight = 0; // scrollDOM.clientHeight, unscaled
        this.editorWidth = 0; // scrollDOM.clientWidth, unscaled
        this.scrollTop = 0; // Last seen scrollDOM.scrollTop, scaled
        this.scrolledToBottom = false;
        // The CSS-transformation scale of the editor (transformed size /
        // concrete size)
        this.scaleX = 1;
        this.scaleY = 1;
        // The vertical position (document-relative) to which to anchor the
        // scroll position. -1 means anchor to the end of the document.
        this.scrollAnchorPos = 0;
        // The height at the anchor position. Set by the DOM update phase.
        // -1 means no height available.
        this.scrollAnchorHeight = -1;
        // See VP.MaxDOMHeight
        this.scaler = IdScaler;
        this.scrollTarget = null;
        // Briefly set to true when printing, to disable viewport limiting
        this.printing = false;
        // Flag set when editor content was redrawn, so that the next
        // measure stage knows it must read DOM layout
        this.mustMeasureContent = true;
        this.defaultTextDirection = Direction.LTR;
        this.visibleRanges = [];
        // Cursor 'assoc' is only significant when the cursor is on a line
        // wrap point, where it must stick to the character that it is
        // associated with. Since browsers don't provide a reasonable
        // interface to set or query this, when a selection is set that
        // might cause this to be significant, this flag is set. The next
        // measure phase will check whether the cursor is on a line-wrapping
        // boundary and, if so, reset it to make sure it is positioned in
        // the right place.
        this.mustEnforceCursorAssoc = false;
        let guessWrapping = state.facet(contentAttributes).some(v => typeof v != "function" && v.class == "cm-lineWrapping");
        this.heightOracle = new HeightOracle(guessWrapping);
        this.stateDeco = staticDeco(state);
        this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, dist_Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);
        for (let i = 0; i < 2; i++) {
            this.viewport = this.getViewport(0, null);
            if (!this.updateForViewport())
                break;
        }
        this.updateViewportLines();
        this.lineGaps = this.ensureLineGaps([]);
        this.lineGapDeco = dist_Decoration.set(this.lineGaps.map(gap => gap.draw(this, false)));
        this.computeVisibleRanges();
    }
    updateForViewport() {
        let viewports = [this.viewport], { main } = this.state.selection;
        for (let i = 0; i <= 1; i++) {
            let pos = i ? main.head : main.anchor;
            if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) {
                let { from, to } = this.lineBlockAt(pos);
                viewports.push(new Viewport(from, to));
            }
        }
        this.viewports = viewports.sort((a, b) => a.from - b.from);
        return this.updateScaler();
    }
    updateScaler() {
        let scaler = this.scaler;
        this.scaler = this.heightMap.height <= 7000000 /* VP.MaxDOMHeight */ ? IdScaler :
            new BigScaler(this.heightOracle, this.heightMap, this.viewports);
        return scaler.eq(this.scaler) ? 0 : 2 /* UpdateFlag.Height */;
    }
    updateViewportLines() {
        this.viewportLines = [];
        this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(this.state.doc), 0, 0, block => {
            this.viewportLines.push(scaleBlock(block, this.scaler));
        });
    }
    update(update, scrollTarget = null) {
        this.state = update.state;
        let prevDeco = this.stateDeco;
        this.stateDeco = staticDeco(this.state);
        let contentChanges = update.changedRanges;
        let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length)));
        let prevHeight = this.heightMap.height;
        let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);
        clearHeightChangeFlag();
        this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
        if (this.heightMap.height != prevHeight || heightChangeFlag)
            update.flags |= 2 /* UpdateFlag.Height */;
        if (scrollAnchor) {
            this.scrollAnchorPos = update.changes.mapPos(scrollAnchor.from, -1);
            this.scrollAnchorHeight = scrollAnchor.top;
        }
        else {
            this.scrollAnchorPos = -1;
            this.scrollAnchorHeight = prevHeight;
        }
        let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport;
        if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) ||
            !this.viewportIsAppropriate(viewport))
            viewport = this.getViewport(0, scrollTarget);
        let viewportChange = viewport.from != this.viewport.from || viewport.to != this.viewport.to;
        this.viewport = viewport;
        update.flags |= this.updateForViewport();
        if (viewportChange || !update.changes.empty || (update.flags & 2 /* UpdateFlag.Height */))
            this.updateViewportLines();
        if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))
            this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes)));
        update.flags |= this.computeVisibleRanges(update.changes);
        if (scrollTarget)
            this.scrollTarget = scrollTarget;
        if (!this.mustEnforceCursorAssoc && (update.selectionSet || update.focusChanged) && update.view.lineWrapping &&
            update.state.selection.main.empty && update.state.selection.main.assoc &&
            !update.state.facet(nativeSelectionHidden))
            this.mustEnforceCursorAssoc = true;
    }
    measure(view) {
        let dom = view.contentDOM, style = window.getComputedStyle(dom);
        let oracle = this.heightOracle;
        let whiteSpace = style.whiteSpace;
        this.defaultTextDirection = style.direction == "rtl" ? Direction.RTL : Direction.LTR;
        let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace);
        let domRect = dom.getBoundingClientRect();
        let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;
        this.contentDOMHeight = domRect.height;
        this.mustMeasureContent = false;
        let result = 0, bias = 0;
        if (domRect.width && domRect.height) {
            let { scaleX, scaleY } = getScale(dom, domRect);
            if (scaleX > .005 && Math.abs(this.scaleX - scaleX) > .005 ||
                scaleY > .005 && Math.abs(this.scaleY - scaleY) > .005) {
                this.scaleX = scaleX;
                this.scaleY = scaleY;
                result |= 16 /* UpdateFlag.Geometry */;
                refresh = measureContent = true;
            }
        }
        // Vertical padding
        let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY;
        let paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY;
        if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {
            this.paddingTop = paddingTop;
            this.paddingBottom = paddingBottom;
            result |= 16 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */;
        }
        if (this.editorWidth != view.scrollDOM.clientWidth) {
            if (oracle.lineWrapping)
                measureContent = true;
            this.editorWidth = view.scrollDOM.clientWidth;
            result |= 16 /* UpdateFlag.Geometry */;
        }
        let scrollTop = view.scrollDOM.scrollTop * this.scaleY;
        if (this.scrollTop != scrollTop) {
            this.scrollAnchorHeight = -1;
            this.scrollTop = scrollTop;
        }
        this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);
        // Pixel viewport
        let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);
        let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
        this.pixelViewport = pixelViewport;
        let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;
        if (inView != this.inView) {
            this.inView = inView;
            if (inView)
                measureContent = true;
        }
        if (!this.inView && !this.scrollTarget && !inWindow(view.dom))
            return 0;
        let contentWidth = domRect.width;
        if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {
            this.contentDOMWidth = domRect.width;
            this.editorHeight = view.scrollDOM.clientHeight;
            result |= 16 /* UpdateFlag.Geometry */;
        }
        if (measureContent) {
            let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);
            if (oracle.mustRefreshForHeights(lineHeights))
                refresh = true;
            if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {
                let { lineHeight, charWidth, textHeight } = view.docView.measureTextSize();
                refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, Math.max(5, contentWidth / charWidth), lineHeights);
                if (refresh) {
                    view.docView.minWidth = 0;
                    result |= 16 /* UpdateFlag.Geometry */;
                }
            }
            if (dTop > 0 && dBottom > 0)
                bias = Math.max(dTop, dBottom);
            else if (dTop < 0 && dBottom < 0)
                bias = Math.min(dTop, dBottom);
            clearHeightChangeFlag();
            for (let vp of this.viewports) {
                let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);
                this.heightMap = (refresh ? HeightMap.empty().applyChanges(this.stateDeco, dist_Text.empty, this.heightOracle, [new ChangedRange(0, 0, 0, view.state.doc.length)]) : this.heightMap).updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights));
            }
            if (heightChangeFlag)
                result |= 2 /* UpdateFlag.Height */;
        }
        let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) ||
            this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from ||
                this.scrollTarget.range.head > this.viewport.to);
        if (viewportChange) {
            if (result & 2 /* UpdateFlag.Height */)
                result |= this.updateScaler();
            this.viewport = this.getViewport(bias, this.scrollTarget);
            result |= this.updateForViewport();
        }
        if ((result & 2 /* UpdateFlag.Height */) || viewportChange)
            this.updateViewportLines();
        if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))
            this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));
        result |= this.computeVisibleRanges();
        if (this.mustEnforceCursorAssoc) {
            this.mustEnforceCursorAssoc = false;
            // This is done in the read stage, because moving the selection
            // to a line end is going to trigger a layout anyway, so it
            // can't be a pure write. It should be rare that it does any
            // writing.
            view.docView.enforceCursorAssoc();
        }
        return result;
    }
    get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); }
    get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); }
    getViewport(bias, scrollTarget) {
        // This will divide VP.Margin between the top and the
        // bottom, depending on the bias (the change in viewport position
        // since the last update). It'll hold a number between 0 and 1
        let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* VP.Margin */ / 2));
        let map = this.heightMap, oracle = this.heightOracle;
        let { visibleTop, visibleBottom } = this;
        let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1000 /* VP.Margin */, QueryType.ByHeight, oracle, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1000 /* VP.Margin */, QueryType.ByHeight, oracle, 0, 0).to);
        // If scrollTarget is given, make sure the viewport includes that position
        if (scrollTarget) {
            let { head } = scrollTarget.range;
            if (head < viewport.from || head > viewport.to) {
                let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);
                let block = map.lineAt(head, QueryType.ByPos, oracle, 0, 0), topPos;
                if (scrollTarget.y == "center")
                    topPos = (block.top + block.bottom) / 2 - viewHeight / 2;
                else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from)
                    topPos = block.top;
                else
                    topPos = block.bottom - viewHeight;
                viewport = new Viewport(map.lineAt(topPos - 1000 /* VP.Margin */ / 2, QueryType.ByHeight, oracle, 0, 0).from, map.lineAt(topPos + viewHeight + 1000 /* VP.Margin */ / 2, QueryType.ByHeight, oracle, 0, 0).to);
            }
        }
        return viewport;
    }
    mapViewport(viewport, changes) {
        let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1);
        return new Viewport(this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0).from, this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0).to);
    }
    // Checks if a given viewport covers the visible part of the
    // document and not too much beyond that.
    viewportIsAppropriate({ from, to }, bias = 0) {
        if (!this.inView)
            return true;
        let { top } = this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0);
        let { bottom } = this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0);
        let { visibleTop, visibleBottom } = this;
        return (from == 0 || top <= visibleTop - Math.max(10 /* VP.MinCoverMargin */, Math.min(-bias, 250 /* VP.MaxCoverMargin */))) &&
            (to == this.state.doc.length ||
                bottom >= visibleBottom + Math.max(10 /* VP.MinCoverMargin */, Math.min(bias, 250 /* VP.MaxCoverMargin */))) &&
            (top > visibleTop - 2 * 1000 /* VP.Margin */ && bottom < visibleBottom + 2 * 1000 /* VP.Margin */);
    }
    mapLineGaps(gaps, changes) {
        if (!gaps.length || changes.empty)
            return gaps;
        let mapped = [];
        for (let gap of gaps)
            if (!changes.touchesRange(gap.from, gap.to))
                mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size, gap.displaySize));
        return mapped;
    }
    // Computes positions in the viewport where the start or end of a
    // line should be hidden, trying to reuse existing line gaps when
    // appropriate to avoid unneccesary redraws.
    // Uses crude character-counting for the positioning and sizing,
    // since actual DOM coordinates aren't always available and
    // predictable. Relies on generous margins (see LG.Margin) to hide
    // the artifacts this might produce from the user.
    ensureLineGaps(current, mayMeasure) {
        let wrapping = this.heightOracle.lineWrapping;
        let margin = wrapping ? 10000 /* LG.MarginWrap */ : 2000 /* LG.Margin */, halfMargin = margin >> 1, doubleMargin = margin << 1;
        // The non-wrapping logic won't work at all in predominantly right-to-left text.
        if (this.defaultTextDirection != Direction.LTR && !wrapping)
            return [];
        let gaps = [];
        let addGap = (from, to, line, structure) => {
            if (to - from < halfMargin)
                return;
            let sel = this.state.selection.main, avoid = [sel.from];
            if (!sel.empty)
                avoid.push(sel.to);
            for (let pos of avoid) {
                if (pos > from && pos < to) {
                    addGap(from, pos - 10 /* LG.SelectionMargin */, line, structure);
                    addGap(pos + 10 /* LG.SelectionMargin */, to, line, structure);
                    return;
                }
            }
            let gap = find(current, gap => gap.from >= line.from && gap.to <= line.to &&
                Math.abs(gap.from - from) < halfMargin && Math.abs(gap.to - to) < halfMargin &&
                !avoid.some(pos => gap.from < pos && gap.to > pos));
            if (!gap) {
                // When scrolling down, snap gap ends to line starts to avoid shifts in wrapping
                if (to < line.to && mayMeasure && wrapping &&
                    mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) {
                    let lineStart = mayMeasure.moveToLineBoundary(dist_EditorSelection.cursor(to), false, true).head;
                    if (lineStart > from)
                        to = lineStart;
                }
                let size = this.gapSize(line, from, to, structure);
                let displaySize = wrapping || size < 2000000 /* VP.MaxHorizGap */ ? size : 2000000 /* VP.MaxHorizGap */;
                gap = new LineGap(from, to, size, displaySize);
            }
            gaps.push(gap);
        };
        let checkLine = (line) => {
            if (line.length < doubleMargin || line.type != BlockType.Text)
                return;
            let structure = lineStructure(line.from, line.to, this.stateDeco);
            if (structure.total < doubleMargin)
                return;
            let target = this.scrollTarget ? this.scrollTarget.range.head : null;
            let viewFrom, viewTo;
            if (wrapping) {
                let marginHeight = (margin / this.heightOracle.lineLength) * this.heightOracle.lineHeight;
                let top, bot;
                if (target != null) {
                    let targetFrac = findFraction(structure, target);
                    let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;
                    top = targetFrac - spaceFrac;
                    bot = targetFrac + spaceFrac;
                }
                else {
                    top = (this.visibleTop - line.top - marginHeight) / line.height;
                    bot = (this.visibleBottom - line.top + marginHeight) / line.height;
                }
                viewFrom = findPosition(structure, top);
                viewTo = findPosition(structure, bot);
            }
            else {
                let totalWidth = structure.total * this.heightOracle.charWidth;
                let marginWidth = margin * this.heightOracle.charWidth;
                let horizOffset = 0;
                if (totalWidth > 2000000 /* VP.MaxHorizGap */)
                    for (let old of current) {
                        if (old.from >= line.from && old.from < line.to && old.size != old.displaySize &&
                            old.from * this.heightOracle.charWidth + horizOffset < this.pixelViewport.left)
                            horizOffset = old.size - old.displaySize;
                    }
                let pxLeft = this.pixelViewport.left + horizOffset, pxRight = this.pixelViewport.right + horizOffset;
                let left, right;
                if (target != null) {
                    let targetFrac = findFraction(structure, target);
                    let spaceFrac = ((pxRight - pxLeft) / 2 + marginWidth) / totalWidth;
                    left = targetFrac - spaceFrac;
                    right = targetFrac + spaceFrac;
                }
                else {
                    left = (pxLeft - marginWidth) / totalWidth;
                    right = (pxRight + marginWidth) / totalWidth;
                }
                viewFrom = findPosition(structure, left);
                viewTo = findPosition(structure, right);
            }
            if (viewFrom > line.from)
                addGap(line.from, viewFrom, line, structure);
            if (viewTo < line.to)
                addGap(viewTo, line.to, line, structure);
        };
        for (let line of this.viewportLines) {
            if (Array.isArray(line.type))
                line.type.forEach(checkLine);
            else
                checkLine(line);
        }
        return gaps;
    }
    gapSize(line, from, to, structure) {
        let fraction = findFraction(structure, to) - findFraction(structure, from);
        if (this.heightOracle.lineWrapping) {
            return line.height * fraction;
        }
        else {
            return structure.total * this.heightOracle.charWidth * fraction;
        }
    }
    updateLineGaps(gaps) {
        if (!LineGap.same(gaps, this.lineGaps)) {
            this.lineGaps = gaps;
            this.lineGapDeco = dist_Decoration.set(gaps.map(gap => gap.draw(this, this.heightOracle.lineWrapping)));
        }
    }
    computeVisibleRanges(changes) {
        let deco = this.stateDeco;
        if (this.lineGaps.length)
            deco = deco.concat(this.lineGapDeco);
        let ranges = [];
        dist_RangeSet.spans(deco, this.viewport.from, this.viewport.to, {
            span(from, to) { ranges.push({ from, to }); },
            point() { }
        }, 20);
        let changed = 0;
        if (ranges.length != this.visibleRanges.length) {
            changed = 8 /* UpdateFlag.ViewportMoved */ | 4 /* UpdateFlag.Viewport */;
        }
        else {
            for (let i = 0; i < ranges.length && !(changed & 8 /* UpdateFlag.ViewportMoved */); i++) {
                let old = this.visibleRanges[i], nw = ranges[i];
                if (old.from != nw.from || old.to != nw.to) {
                    changed |= 4 /* UpdateFlag.Viewport */;
                    if (!(changes && changes.mapPos(old.from, -1) == nw.from && changes.mapPos(old.to, 1) == nw.to))
                        changed |= 8 /* UpdateFlag.ViewportMoved */;
                }
            }
        }
        this.visibleRanges = ranges;
        return changed;
    }
    lineBlockAt(pos) {
        return (pos >= this.viewport.from && pos <= this.viewport.to &&
            this.viewportLines.find(b => b.from <= pos && b.to >= pos)) ||
            scaleBlock(this.heightMap.lineAt(pos, QueryType.ByPos, this.heightOracle, 0, 0), this.scaler);
    }
    lineBlockAtHeight(height) {
        return (height >= this.viewportLines[0].top && height <= this.viewportLines[this.viewportLines.length - 1].bottom &&
            this.viewportLines.find(l => l.top <= height && l.bottom >= height)) ||
            scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType.ByHeight, this.heightOracle, 0, 0), this.scaler);
    }
    scrollAnchorAt(scrollTop) {
        let block = this.lineBlockAtHeight(scrollTop + 8);
        return block.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block : this.viewportLines[0];
    }
    elementAtHeight(height) {
        return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler);
    }
    get docHeight() {
        return this.scaler.toDOM(this.heightMap.height);
    }
    get contentHeight() {
        return this.docHeight + this.paddingTop + this.paddingBottom;
    }
}
class Viewport {
    constructor(from, to) {
        this.from = from;
        this.to = to;
    }
}
function lineStructure(from, to, stateDeco) {
    let ranges = [], pos = from, total = 0;
    dist_RangeSet.spans(stateDeco, from, to, {
        span() { },
        point(from, to) {
            if (from > pos) {
                ranges.push({ from: pos, to: from });
                total += from - pos;
            }
            pos = to;
        }
    }, 20); // We're only interested in collapsed ranges of a significant size
    if (pos < to) {
        ranges.push({ from: pos, to });
        total += to - pos;
    }
    return { total, ranges };
}
function findPosition({ total, ranges }, ratio) {
    if (ratio <= 0)
        return ranges[0].from;
    if (ratio >= 1)
        return ranges[ranges.length - 1].to;
    let dist = Math.floor(total * ratio);
    for (let i = 0;; i++) {
        let { from, to } = ranges[i], size = to - from;
        if (dist <= size)
            return from + dist;
        dist -= size;
    }
}
function findFraction(structure, pos) {
    let counted = 0;
    for (let { from, to } of structure.ranges) {
        if (pos <= to) {
            counted += pos - from;
            break;
        }
        counted += to - from;
    }
    return counted / structure.total;
}
function find(array, f) {
    for (let val of array)
        if (f(val))
            return val;
    return undefined;
}
// Don't scale when the document height is within the range of what
// the DOM can handle.
const IdScaler = {
    toDOM(n) { return n; },
    fromDOM(n) { return n; },
    scale: 1,
    eq(other) { return other == this; }
};
function staticDeco(state) {
    let deco = state.facet(decorations).filter(d => typeof d != "function");
    let outer = state.facet(outerDecorations).filter(d => typeof d != "function");
    if (outer.length)
        deco.push(dist_RangeSet.join(outer));
    return deco;
}
// When the height is too big (> VP.MaxDOMHeight), scale down the
// regions outside the viewports so that the total height is
// VP.MaxDOMHeight.
class BigScaler {
    constructor(oracle, heightMap, viewports) {
        let vpHeight = 0, base = 0, domBase = 0;
        this.viewports = viewports.map(({ from, to }) => {
            let top = heightMap.lineAt(from, QueryType.ByPos, oracle, 0, 0).top;
            let bottom = heightMap.lineAt(to, QueryType.ByPos, oracle, 0, 0).bottom;
            vpHeight += bottom - top;
            return { from, to, top, bottom, domTop: 0, domBottom: 0 };
        });
        this.scale = (7000000 /* VP.MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight);
        for (let obj of this.viewports) {
            obj.domTop = domBase + (obj.top - base) * this.scale;
            domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);
            base = obj.bottom;
        }
    }
    toDOM(n) {
        for (let i = 0, base = 0, domBase = 0;; i++) {
            let vp = i < this.viewports.length ? this.viewports[i] : null;
            if (!vp || n < vp.top)
                return domBase + (n - base) * this.scale;
            if (n <= vp.bottom)
                return vp.domTop + (n - vp.top);
            base = vp.bottom;
            domBase = vp.domBottom;
        }
    }
    fromDOM(n) {
        for (let i = 0, base = 0, domBase = 0;; i++) {
            let vp = i < this.viewports.length ? this.viewports[i] : null;
            if (!vp || n < vp.domTop)
                return base + (n - domBase) / this.scale;
            if (n <= vp.domBottom)
                return vp.top + (n - vp.domTop);
            base = vp.bottom;
            domBase = vp.domBottom;
        }
    }
    eq(other) {
        if (!(other instanceof BigScaler))
            return false;
        return this.scale == other.scale && this.viewports.length == other.viewports.length &&
            this.viewports.every((vp, i) => vp.from == other.viewports[i].from && vp.to == other.viewports[i].to);
    }
}
function scaleBlock(block, scaler) {
    if (scaler.scale == 1)
        return block;
    let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom);
    return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block._content) ? block._content.map(b => scaleBlock(b, scaler)) : block._content);
}

const theme = /*@__PURE__*/Facet.define({ combine: strs => strs.join(" ") });
const darkTheme = /*@__PURE__*/Facet.define({ combine: values => values.indexOf(true) > -1 });
const baseThemeID = /*@__PURE__*/external_style_mod_namespaceObject.StyleModule.newName(), baseLightID = /*@__PURE__*/external_style_mod_namespaceObject.StyleModule.newName(), baseDarkID = /*@__PURE__*/external_style_mod_namespaceObject.StyleModule.newName();
const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID };
function buildTheme(main, spec, scopes) {
    return new external_style_mod_namespaceObject.StyleModule(spec, {
        finish(sel) {
            return /&/.test(sel) ? sel.replace(/&\w*/, m => {
                if (m == "&")
                    return main;
                if (!scopes || !scopes[m])
                    throw new RangeError(`Unsupported selector: ${m}`);
                return scopes[m];
            }) : main + " " + sel;
        }
    });
}
const baseTheme$1 = /*@__PURE__*/buildTheme("." + baseThemeID, {
    "&": {
        position: "relative !important",
        boxSizing: "border-box",
        "&.cm-focused": {
            // Provide a simple default outline to make sure a focused
            // editor is visually distinct. Can't leave the default behavior
            // because that will apply to the content element, which is
            // inside the scrollable container and doesn't include the
            // gutters. We also can't use an 'auto' outline, since those
            // are, for some reason, drawn behind the element content, which
            // will cause things like the active line background to cover
            // the outline (#297).
            outline: "1px dotted #212121"
        },
        display: "flex !important",
        flexDirection: "column"
    },
    ".cm-scroller": {
        display: "flex !important",
        alignItems: "flex-start !important",
        fontFamily: "monospace",
        lineHeight: 1.4,
        height: "100%",
        overflowX: "auto",
        position: "relative",
        zIndex: 0,
        overflowAnchor: "none",
    },
    ".cm-content": {
        margin: 0,
        flexGrow: 2,
        flexShrink: 0,
        display: "block",
        whiteSpace: "pre",
        wordWrap: "normal", // https://github.com/codemirror/dev/issues/456
        boxSizing: "border-box",
        minHeight: "100%",
        padding: "4px 0",
        outline: "none",
        "&[contenteditable=true]": {
            WebkitUserModify: "read-write-plaintext-only",
        }
    },
    ".cm-lineWrapping": {
        whiteSpace_fallback: "pre-wrap", // For IE
        whiteSpace: "break-spaces",
        wordBreak: "break-word", // For Safari, which doesn't support overflow-wrap: anywhere
        overflowWrap: "anywhere",
        flexShrink: 1
    },
    "&light .cm-content": { caretColor: "black" },
    "&dark .cm-content": { caretColor: "white" },
    ".cm-line": {
        display: "block",
        padding: "0 2px 0 6px"
    },
    ".cm-layer": {
        position: "absolute",
        left: 0,
        top: 0,
        contain: "size style",
        "& > *": {
            position: "absolute"
        }
    },
    "&light .cm-selectionBackground": {
        background: "#d9d9d9"
    },
    "&dark .cm-selectionBackground": {
        background: "#222"
    },
    "&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
        background: "#d7d4f0"
    },
    "&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
        background: "#233"
    },
    ".cm-cursorLayer": {
        pointerEvents: "none"
    },
    "&.cm-focused > .cm-scroller > .cm-cursorLayer": {
        animation: "steps(1) cm-blink 1.2s infinite"
    },
    // Two animations defined so that we can switch between them to
    // restart the animation without forcing another style
    // recomputation.
    "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
    "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
    ".cm-cursor, .cm-dropCursor": {
        borderLeft: "1.2px solid black",
        marginLeft: "-0.6px",
        pointerEvents: "none",
    },
    ".cm-cursor": {
        display: "none"
    },
    "&dark .cm-cursor": {
        borderLeftColor: "#ddd"
    },
    ".cm-dropCursor": {
        position: "absolute"
    },
    "&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor": {
        display: "block"
    },
    ".cm-iso": {
        unicodeBidi: "isolate"
    },
    ".cm-announced": {
        position: "fixed",
        top: "-10000px"
    },
    "@media print": {
        ".cm-announced": { display: "none" }
    },
    "&light .cm-activeLine": { backgroundColor: "#cceeff44" },
    "&dark .cm-activeLine": { backgroundColor: "#99eeff33" },
    "&light .cm-specialChar": { color: "red" },
    "&dark .cm-specialChar": { color: "#f78" },
    ".cm-gutters": {
        flexShrink: 0,
        display: "flex",
        height: "100%",
        boxSizing: "border-box",
        zIndex: 200,
    },
    ".cm-gutters-before": { insetInlineStart: 0 },
    ".cm-gutters-after": { insetInlineEnd: 0 },
    "&light .cm-gutters": {
        backgroundColor: "#f5f5f5",
        color: "#6c6c6c",
        border: "0px solid #ddd",
        "&.cm-gutters-before": { borderRightWidth: "1px" },
        "&.cm-gutters-after": { borderLeftWidth: "1px" },
    },
    "&dark .cm-gutters": {
        backgroundColor: "#333338",
        color: "#ccc"
    },
    ".cm-gutter": {
        display: "flex !important", // Necessary -- prevents margin collapsing
        flexDirection: "column",
        flexShrink: 0,
        boxSizing: "border-box",
        minHeight: "100%",
        overflow: "hidden"
    },
    ".cm-gutterElement": {
        boxSizing: "border-box"
    },
    ".cm-lineNumbers .cm-gutterElement": {
        padding: "0 3px 0 5px",
        minWidth: "20px",
        textAlign: "right",
        whiteSpace: "nowrap"
    },
    "&light .cm-activeLineGutter": {
        backgroundColor: "#e2f2ff"
    },
    "&dark .cm-activeLineGutter": {
        backgroundColor: "#222227"
    },
    ".cm-panels": {
        boxSizing: "border-box",
        position: "sticky",
        left: 0,
        right: 0,
        zIndex: 300
    },
    "&light .cm-panels": {
        backgroundColor: "#f5f5f5",
        color: "black"
    },
    "&light .cm-panels-top": {
        borderBottom: "1px solid #ddd"
    },
    "&light .cm-panels-bottom": {
        borderTop: "1px solid #ddd"
    },
    "&dark .cm-panels": {
        backgroundColor: "#333338",
        color: "white"
    },
    ".cm-dialog": {
        padding: "2px 19px 4px 6px",
        position: "relative",
        "& label": { fontSize: "80%" },
    },
    ".cm-dialog-close": {
        position: "absolute",
        top: "3px",
        right: "4px",
        backgroundColor: "inherit",
        border: "none",
        font: "inherit",
        fontSize: "14px",
        padding: "0"
    },
    ".cm-tab": {
        display: "inline-block",
        overflow: "hidden",
        verticalAlign: "bottom"
    },
    ".cm-widgetBuffer": {
        verticalAlign: "text-top",
        height: "1em",
        width: 0,
        display: "inline"
    },
    ".cm-placeholder": {
        color: "#888",
        display: "inline-block",
        verticalAlign: "top",
        userSelect: "none"
    },
    ".cm-highlightSpace": {
        backgroundImage: "radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",
        backgroundPosition: "center",
    },
    ".cm-highlightTab": {
        backgroundImage: `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,
        backgroundSize: "auto 100%",
        backgroundPosition: "right 90%",
        backgroundRepeat: "no-repeat"
    },
    ".cm-trailingSpace": {
        backgroundColor: "#ff332255"
    },
    ".cm-button": {
        verticalAlign: "middle",
        color: "inherit",
        fontSize: "70%",
        padding: ".2em 1em",
        borderRadius: "1px"
    },
    "&light .cm-button": {
        backgroundImage: "linear-gradient(#eff1f5, #d9d9df)",
        border: "1px solid #888",
        "&:active": {
            backgroundImage: "linear-gradient(#b4b4b4, #d0d3d6)"
        }
    },
    "&dark .cm-button": {
        backgroundImage: "linear-gradient(#393939, #111)",
        border: "1px solid #888",
        "&:active": {
            backgroundImage: "linear-gradient(#111, #333)"
        }
    },
    ".cm-textfield": {
        verticalAlign: "middle",
        color: "inherit",
        fontSize: "70%",
        border: "1px solid silver",
        padding: ".2em .5em"
    },
    "&light .cm-textfield": {
        backgroundColor: "white"
    },
    "&dark .cm-textfield": {
        border: "1px solid #555",
        backgroundColor: "inherit"
    }
}, lightDarkIDs);

const observeOptions = {
    childList: true,
    characterData: true,
    subtree: true,
    attributes: true,
    characterDataOldValue: true
};
// IE11 has very broken mutation observers, so we also listen to
// DOMCharacterDataModified there
const useCharData = browser.ie && browser.ie_version <= 11;
class DOMObserver {
    constructor(view) {
        this.view = view;
        this.active = false;
        this.editContext = null;
        // The known selection. Kept in our own object, as opposed to just
        // directly accessing the selection because:
        //  - Safari doesn't report the right selection in shadow DOM
        //  - Reading from the selection forces a DOM layout
        //  - This way, we can ignore selectionchange events if we have
        //    already seen the 'new' selection
        this.selectionRange = new DOMSelectionState;
        // Set when a selection change is detected, cleared on flush
        this.selectionChanged = false;
        this.delayedFlush = -1;
        this.resizeTimeout = -1;
        this.queue = [];
        this.delayedAndroidKey = null;
        this.flushingAndroidKey = -1;
        this.lastChange = 0;
        this.scrollTargets = [];
        this.intersection = null;
        this.resizeScroll = null;
        this.intersecting = false;
        this.gapIntersection = null;
        this.gaps = [];
        this.printQuery = null;
        // Timeout for scheduling check of the parents that need scroll handlers
        this.parentCheck = -1;
        this.dom = view.contentDOM;
        this.observer = new MutationObserver(mutations => {
            for (let mut of mutations)
                this.queue.push(mut);
            // IE11 will sometimes (on typing over a selection or
            // backspacing out a single character text node) call the
            // observer callback before actually updating the DOM.
            //
            // Unrelatedly, iOS Safari will, when ending a composition,
            // sometimes first clear it, deliver the mutations, and then
            // reinsert the finished text. CodeMirror's handling of the
            // deletion will prevent the reinsertion from happening,
            // breaking composition.
            if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) &&
                mutations.some(m => m.type == "childList" && m.removedNodes.length ||
                    m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length))
                this.flushSoon();
            else
                this.flush();
        });
        if (window.EditContext && browser.android && view.constructor.EDIT_CONTEXT !== false &&
            // Chrome <126 doesn't support inverted selections in edit context (#1392)
            !(browser.chrome && browser.chrome_version < 126)) {
            this.editContext = new EditContextManager(view);
            if (view.state.facet(editable))
                view.contentDOM.editContext = this.editContext.editContext;
        }
        if (useCharData)
            this.onCharData = (event) => {
                this.queue.push({ target: event.target,
                    type: "characterData",
                    oldValue: event.prevValue });
                this.flushSoon();
            };
        this.onSelectionChange = this.onSelectionChange.bind(this);
        this.onResize = this.onResize.bind(this);
        this.onPrint = this.onPrint.bind(this);
        this.onScroll = this.onScroll.bind(this);
        if (window.matchMedia)
            this.printQuery = window.matchMedia("print");
        if (typeof ResizeObserver == "function") {
            this.resizeScroll = new ResizeObserver(() => {
                var _a;
                if (((_a = this.view.docView) === null || _a === void 0 ? void 0 : _a.lastUpdate) < Date.now() - 75)
                    this.onResize();
            });
            this.resizeScroll.observe(view.scrollDOM);
        }
        this.addWindowListeners(this.win = view.win);
        this.start();
        if (typeof IntersectionObserver == "function") {
            this.intersection = new IntersectionObserver(entries => {
                if (this.parentCheck < 0)
                    this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000);
                if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) {
                    this.intersecting = !this.intersecting;
                    if (this.intersecting != this.view.inView)
                        this.onScrollChanged(document.createEvent("Event"));
                }
            }, { threshold: [0, .001] });
            this.intersection.observe(this.dom);
            this.gapIntersection = new IntersectionObserver(entries => {
                if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0)
                    this.onScrollChanged(document.createEvent("Event"));
            }, {});
        }
        this.listenForScroll();
        this.readSelectionRange();
    }
    onScrollChanged(e) {
        this.view.inputState.runHandlers("scroll", e);
        if (this.intersecting)
            this.view.measure();
    }
    onScroll(e) {
        if (this.intersecting)
            this.flush(false);
        if (this.editContext)
            this.view.requestMeasure(this.editContext.measureReq);
        this.onScrollChanged(e);
    }
    onResize() {
        if (this.resizeTimeout < 0)
            this.resizeTimeout = setTimeout(() => {
                this.resizeTimeout = -1;
                this.view.requestMeasure();
            }, 50);
    }
    onPrint(event) {
        if ((event.type == "change" || !event.type) && !event.matches)
            return;
        this.view.viewState.printing = true;
        this.view.measure();
        setTimeout(() => {
            this.view.viewState.printing = false;
            this.view.requestMeasure();
        }, 500);
    }
    updateGaps(gaps) {
        if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) {
            this.gapIntersection.disconnect();
            for (let gap of gaps)
                this.gapIntersection.observe(gap);
            this.gaps = gaps;
        }
    }
    onSelectionChange(event) {
        let wasChanged = this.selectionChanged;
        if (!this.readSelectionRange() || this.delayedAndroidKey)
            return;
        let { view } = this, sel = this.selectionRange;
        if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(this.dom, sel))
            return;
        let context = sel.anchorNode && view.docView.tile.nearest(sel.anchorNode);
        if (context && context.isWidget() && context.widget.ignoreEvent(event)) {
            if (!wasChanged)
                this.selectionChanged = false;
            return;
        }
        // Deletions on IE11 fire their events in the wrong order, giving
        // us a selection change event before the DOM changes are
        // reported.
        // Chrome Android has a similar issue when backspacing out a
        // selection (#645).
        if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty &&
            // (Selection.isCollapsed isn't reliable on IE)
            sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
            this.flushSoon();
        else
            this.flush(false);
    }
    readSelectionRange() {
        let { view } = this;
        // The Selection object is broken in shadow roots in Safari. See
        // https://github.com/codemirror/dev/issues/414
        let selection = getSelection(view.root);
        if (!selection)
            return false;
        let range = browser.safari && view.root.nodeType == 11 &&
            view.root.activeElement == this.dom &&
            safariSelectionRangeHack(this.view, selection) || selection;
        if (!range || this.selectionRange.eq(range))
            return false;
        let local = hasSelection(this.dom, range);
        // Detect the situation where the browser has, on focus, moved the
        // selection to the start of the content element. Reset it to the
        // position from the editor state.
        if (local && !this.selectionChanged &&
            view.inputState.lastFocusTime > Date.now() - 200 &&
            view.inputState.lastTouchTime < Date.now() - 300 &&
            atElementStart(this.dom, range)) {
            this.view.inputState.lastFocusTime = 0;
            view.docView.updateSelection();
            return false;
        }
        this.selectionRange.setRange(range);
        if (local)
            this.selectionChanged = true;
        return true;
    }
    setSelectionRange(anchor, head) {
        this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset);
        this.selectionChanged = false;
    }
    clearSelectionRange() {
        this.selectionRange.set(null, 0, null, 0);
    }
    listenForScroll() {
        this.parentCheck = -1;
        let i = 0, changed = null;
        for (let dom = this.dom; dom;) {
            if (dom.nodeType == 1) {
                if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom)
                    i++;
                else if (!changed)
                    changed = this.scrollTargets.slice(0, i);
                if (changed)
                    changed.push(dom);
                dom = dom.assignedSlot || dom.parentNode;
            }
            else if (dom.nodeType == 11) { // Shadow root
                dom = dom.host;
            }
            else {
                break;
            }
        }
        if (i < this.scrollTargets.length && !changed)
            changed = this.scrollTargets.slice(0, i);
        if (changed) {
            for (let dom of this.scrollTargets)
                dom.removeEventListener("scroll", this.onScroll);
            for (let dom of this.scrollTargets = changed)
                dom.addEventListener("scroll", this.onScroll);
        }
    }
    ignore(f) {
        if (!this.active)
            return f();
        try {
            this.stop();
            return f();
        }
        finally {
            this.start();
            this.clear();
        }
    }
    start() {
        if (this.active)
            return;
        this.observer.observe(this.dom, observeOptions);
        if (useCharData)
            this.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
        this.active = true;
    }
    stop() {
        if (!this.active)
            return;
        this.active = false;
        this.observer.disconnect();
        if (useCharData)
            this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
    }
    // Throw away any pending changes
    clear() {
        this.processRecords();
        this.queue.length = 0;
        this.selectionChanged = false;
    }
    // Chrome Android, especially in combination with GBoard, not only
    // doesn't reliably fire regular key events, but also often
    // surrounds the effect of enter or backspace with a bunch of
    // composition events that, when interrupted, cause text duplication
    // or other kinds of corruption. This hack makes the editor back off
    // from handling DOM changes for a moment when such a key is
    // detected (via beforeinput or keydown), and then tries to flush
    // them or, if that has no effect, dispatches the given key.
    delayAndroidKey(key, keyCode) {
        var _a;
        if (!this.delayedAndroidKey) {
            let flush = () => {
                let key = this.delayedAndroidKey;
                if (key) {
                    this.clearDelayedAndroidKey();
                    this.view.inputState.lastKeyCode = key.keyCode;
                    this.view.inputState.lastKeyTime = Date.now();
                    let flushed = this.flush();
                    if (!flushed && key.force)
                        dispatchKey(this.dom, key.key, key.keyCode);
                }
            };
            this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush);
        }
        // Since backspace beforeinput is sometimes signalled spuriously,
        // Enter always takes precedence.
        if (!this.delayedAndroidKey || key == "Enter")
            this.delayedAndroidKey = {
                key, keyCode,
                // Only run the key handler when no changes are detected if
                // this isn't coming right after another change, in which case
                // it is probably part of a weird chain of updates, and should
                // be ignored if it returns the DOM to its previous state.
                force: this.lastChange < Date.now() - 50 || !!((_a = this.delayedAndroidKey) === null || _a === void 0 ? void 0 : _a.force)
            };
    }
    clearDelayedAndroidKey() {
        this.win.cancelAnimationFrame(this.flushingAndroidKey);
        this.delayedAndroidKey = null;
        this.flushingAndroidKey = -1;
    }
    flushSoon() {
        if (this.delayedFlush < 0)
            this.delayedFlush = this.view.win.requestAnimationFrame(() => { this.delayedFlush = -1; this.flush(); });
    }
    forceFlush() {
        if (this.delayedFlush >= 0) {
            this.view.win.cancelAnimationFrame(this.delayedFlush);
            this.delayedFlush = -1;
        }
        this.flush();
    }
    pendingRecords() {
        for (let mut of this.observer.takeRecords())
            this.queue.push(mut);
        return this.queue;
    }
    processRecords() {
        let records = this.pendingRecords();
        if (records.length)
            this.queue = [];
        let from = -1, to = -1, typeOver = false;
        for (let record of records) {
            let range = this.readMutation(record);
            if (!range)
                continue;
            if (range.typeOver)
                typeOver = true;
            if (from == -1) {
                ({ from, to } = range);
            }
            else {
                from = Math.min(range.from, from);
                to = Math.max(range.to, to);
            }
        }
        return { from, to, typeOver };
    }
    readChange() {
        let { from, to, typeOver } = this.processRecords();
        let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange);
        if (from < 0 && !newSel)
            return null;
        if (from > -1)
            this.lastChange = Date.now();
        this.view.inputState.lastFocusTime = 0;
        this.selectionChanged = false;
        let change = new DOMChange(this.view, from, to, typeOver);
        this.view.docView.domChanged = { newSel: change.newSel ? change.newSel.main : null };
        return change;
    }
    // Apply pending changes, if any
    flush(readSelection = true) {
        // Completely hold off flushing when pending keys are set—the code
        // managing those will make sure processRecords is called and the
        // view is resynchronized after
        if (this.delayedFlush >= 0 || this.delayedAndroidKey)
            return false;
        if (readSelection)
            this.readSelectionRange();
        let domChange = this.readChange();
        if (!domChange) {
            this.view.requestMeasure();
            return false;
        }
        let startState = this.view.state;
        let handled = applyDOMChange(this.view, domChange);
        // The view wasn't updated but DOM/selection changes were seen. Reset the view.
        if (this.view.state == startState &&
            (domChange.domChanged || domChange.newSel && !domChange.newSel.main.eq(this.view.state.selection.main)))
            this.view.update([]);
        return handled;
    }
    readMutation(rec) {
        let tile = this.view.docView.tile.nearest(rec.target);
        if (!tile || tile.isWidget())
            return null;
        tile.markDirty(rec.type == "attributes");
        if (rec.type == "childList") {
            let childBefore = findChild(tile, rec.previousSibling || rec.target.previousSibling, -1);
            let childAfter = findChild(tile, rec.nextSibling || rec.target.nextSibling, 1);
            return { from: childBefore ? tile.posAfter(childBefore) : tile.posAtStart,
                to: childAfter ? tile.posBefore(childAfter) : tile.posAtEnd, typeOver: false };
        }
        else if (rec.type == "characterData") {
            return { from: tile.posAtStart, to: tile.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue };
        }
        else {
            return null;
        }
    }
    setWindow(win) {
        if (win != this.win) {
            this.removeWindowListeners(this.win);
            this.win = win;
            this.addWindowListeners(this.win);
        }
    }
    addWindowListeners(win) {
        win.addEventListener("resize", this.onResize);
        if (this.printQuery) {
            if (this.printQuery.addEventListener)
                this.printQuery.addEventListener("change", this.onPrint);
            else
                this.printQuery.addListener(this.onPrint);
        }
        else
            win.addEventListener("beforeprint", this.onPrint);
        win.addEventListener("scroll", this.onScroll);
        win.document.addEventListener("selectionchange", this.onSelectionChange);
    }
    removeWindowListeners(win) {
        win.removeEventListener("scroll", this.onScroll);
        win.removeEventListener("resize", this.onResize);
        if (this.printQuery) {
            if (this.printQuery.removeEventListener)
                this.printQuery.removeEventListener("change", this.onPrint);
            else
                this.printQuery.removeListener(this.onPrint);
        }
        else
            win.removeEventListener("beforeprint", this.onPrint);
        win.document.removeEventListener("selectionchange", this.onSelectionChange);
    }
    update(update) {
        if (this.editContext) {
            this.editContext.update(update);
            if (update.startState.facet(editable) != update.state.facet(editable))
                update.view.contentDOM.editContext = update.state.facet(editable) ? this.editContext.editContext : null;
        }
    }
    destroy() {
        var _a, _b, _c;
        this.stop();
        (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect();
        (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect();
        (_c = this.resizeScroll) === null || _c === void 0 ? void 0 : _c.disconnect();
        for (let dom of this.scrollTargets)
            dom.removeEventListener("scroll", this.onScroll);
        this.removeWindowListeners(this.win);
        clearTimeout(this.parentCheck);
        clearTimeout(this.resizeTimeout);
        this.win.cancelAnimationFrame(this.delayedFlush);
        this.win.cancelAnimationFrame(this.flushingAndroidKey);
        if (this.editContext) {
            this.view.contentDOM.editContext = null;
            this.editContext.destroy();
        }
    }
}
function findChild(tile, dom, dir) {
    while (dom) {
        let curTile = Tile.get(dom);
        if (curTile && curTile.parent == tile)
            return curTile;
        let parent = dom.parentNode;
        dom = parent != tile.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling;
    }
    return null;
}
function buildSelectionRangeFromRange(view, range) {
    let anchorNode = range.startContainer, anchorOffset = range.startOffset;
    let focusNode = range.endContainer, focusOffset = range.endOffset;
    let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor, 1);
    // Since such a range doesn't distinguish between anchor and head,
    // use a heuristic that flips it around if its end matches the
    // current anchor.
    if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset))
        [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
    return { anchorNode, anchorOffset, focusNode, focusOffset };
}
// Used to work around a Safari Selection/shadow DOM bug (#414)
function safariSelectionRangeHack(view, selection) {
    if (selection.getComposedRanges) {
        let range = selection.getComposedRanges(view.root)[0];
        if (range)
            return buildSelectionRangeFromRange(view, range);
    }
    let found = null;
    // Because Safari (at least in 2018-2021) doesn't provide regular
    // access to the selection inside a shadowroot, we have to perform a
    // ridiculous hack to get at it—using `execCommand` to trigger a
    // `beforeInput` event so that we can read the target range from the
    // event.
    function read(event) {
        event.preventDefault();
        event.stopImmediatePropagation();
        found = event.getTargetRanges()[0];
    }
    view.contentDOM.addEventListener("beforeinput", read, true);
    view.dom.ownerDocument.execCommand("indent");
    view.contentDOM.removeEventListener("beforeinput", read, true);
    return found ? buildSelectionRangeFromRange(view, found) : null;
}
class EditContextManager {
    constructor(view) {
        // The document window for which the text in the context is
        // maintained. For large documents, this may be smaller than the
        // editor document. This window always includes the selection head.
        this.from = 0;
        this.to = 0;
        // When applying a transaction, this is used to compare the change
        // made to the context content to the change in the transaction in
        // order to make the minimal changes to the context (since touching
        // that sometimes breaks series of multiple edits made for a single
        // user action on some Android keyboards)
        this.pendingContextChange = null;
        this.handlers = Object.create(null);
        // Kludge to work around the fact that EditContext does not respond
        // well to having its content updated during a composition (see #1472)
        this.composing = null;
        this.resetRange(view.state);
        let context = this.editContext = new window.EditContext({
            text: view.state.doc.sliceString(this.from, this.to),
            selectionStart: this.toContextPos(Math.max(this.from, Math.min(this.to, view.state.selection.main.anchor))),
            selectionEnd: this.toContextPos(view.state.selection.main.head)
        });
        this.handlers.textupdate = e => {
            let main = view.state.selection.main, { anchor, head } = main;
            let from = this.toEditorPos(e.updateRangeStart), to = this.toEditorPos(e.updateRangeEnd);
            if (view.inputState.composing >= 0 && !this.composing)
                this.composing = { contextBase: e.updateRangeStart, editorBase: from, drifted: false };
            let deletes = to - from > e.text.length;
            // If the window doesn't include the anchor, assume changes
            // adjacent to a side go up to the anchor.
            if (from == this.from && anchor < this.from)
                from = anchor;
            else if (to == this.to && anchor > this.to)
                to = anchor;
            let diff = findDiff(view.state.sliceDoc(from, to), e.text, (deletes ? main.from : main.to) - from, deletes ? "end" : null);
            // Edit contexts sometimes fire empty changes
            if (!diff) {
                let newSel = dist_EditorSelection.single(this.toEditorPos(e.selectionStart), this.toEditorPos(e.selectionEnd));
                if (!newSel.main.eq(main))
                    view.dispatch({ selection: newSel, userEvent: "select" });
                return;
            }
            let change = { from: diff.from + from, to: diff.toA + from,
                insert: dist_Text.of(e.text.slice(diff.from, diff.toB).split("\n")) };
            if ((browser.mac || browser.android) && change.from == head - 1 &&
                /^\. ?$/.test(e.text) && view.contentDOM.getAttribute("autocorrect") == "off")
                change = { from, to, insert: dist_Text.of([e.text.replace(".", " ")]) };
            this.pendingContextChange = change;
            if (!view.state.readOnly) {
                let newLen = this.to - this.from + (change.to - change.from + change.insert.length);
                applyDOMChangeInner(view, change, dist_EditorSelection.single(this.toEditorPos(e.selectionStart, newLen), this.toEditorPos(e.selectionEnd, newLen)));
            }
            // If the transaction didn't flush our change, revert it so
            // that the context is in sync with the editor state again.
            if (this.pendingContextChange) {
                this.revertPending(view.state);
                this.setSelection(view.state);
            }
            // Work around missed compositionend events. See https://discuss.codemirror.net/t/a/9514
            if (change.from < change.to && !change.insert.length && view.inputState.composing >= 0 &&
                !/[\\p{Alphabetic}\\p{Number}_]/.test(context.text.slice(Math.max(0, e.updateRangeStart - 1), Math.min(context.text.length, e.updateRangeStart + 1))))
                this.handlers.compositionend(e);
        };
        this.handlers.characterboundsupdate = e => {
            let rects = [], prev = null;
            for (let i = this.toEditorPos(e.rangeStart), end = this.toEditorPos(e.rangeEnd); i < end; i++) {
                let rect = view.coordsForChar(i);
                prev = (rect && new DOMRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top))
                    || prev || new DOMRect;
                rects.push(prev);
            }
            context.updateCharacterBounds(e.rangeStart, rects);
        };
        this.handlers.textformatupdate = e => {
            let deco = [];
            for (let format of e.getTextFormats()) {
                let lineStyle = format.underlineStyle, thickness = format.underlineThickness;
                if (!/none/i.test(lineStyle) && !/none/i.test(thickness)) {
                    let from = this.toEditorPos(format.rangeStart), to = this.toEditorPos(format.rangeEnd);
                    if (from < to) {
                        // These values changed from capitalized custom strings to lower-case CSS keywords in 2025
                        let style = `text-decoration: underline ${/^[a-z]/.test(lineStyle) ? lineStyle + " " : lineStyle == "Dashed" ? "dashed " : lineStyle == "Squiggle" ? "wavy " : ""}${/thin/i.test(thickness) ? 1 : 2}px`;
                        deco.push(dist_Decoration.mark({ attributes: { style } }).range(from, to));
                    }
                }
            }
            view.dispatch({ effects: setEditContextFormatting.of(dist_Decoration.set(deco)) });
        };
        this.handlers.compositionstart = () => {
            if (view.inputState.composing < 0) {
                view.inputState.composing = 0;
                view.inputState.compositionFirstChange = true;
            }
        };
        this.handlers.compositionend = () => {
            view.inputState.composing = -1;
            view.inputState.compositionFirstChange = null;
            if (this.composing) {
                let { drifted } = this.composing;
                this.composing = null;
                if (drifted)
                    this.reset(view.state);
            }
        };
        for (let event in this.handlers)
            context.addEventListener(event, this.handlers[event]);
        this.measureReq = { read: view => {
                this.editContext.updateControlBounds(view.contentDOM.getBoundingClientRect());
                let sel = getSelection(view.root);
                if (sel && sel.rangeCount)
                    this.editContext.updateSelectionBounds(sel.getRangeAt(0).getBoundingClientRect());
            } };
    }
    applyEdits(update) {
        let off = 0, abort = false, pending = this.pendingContextChange;
        update.changes.iterChanges((fromA, toA, _fromB, _toB, insert) => {
            if (abort)
                return;
            let dLen = insert.length - (toA - fromA);
            if (pending && toA >= pending.to) {
                if (pending.from == fromA && pending.to == toA && pending.insert.eq(insert)) {
                    pending = this.pendingContextChange = null; // Match
                    off += dLen;
                    this.to += dLen;
                    return;
                }
                else { // Mismatch, revert
                    pending = null;
                    this.revertPending(update.state);
                }
            }
            fromA += off;
            toA += off;
            if (toA <= this.from) { // Before the window
                this.from += dLen;
                this.to += dLen;
            }
            else if (fromA < this.to) { // Overlaps with window
                if (fromA < this.from || toA > this.to || (this.to - this.from) + insert.length > 30000 /* CxVp.MaxSize */) {
                    abort = true;
                    return;
                }
                this.editContext.updateText(this.toContextPos(fromA), this.toContextPos(toA), insert.toString());
                this.to += dLen;
            }
            off += dLen;
        });
        if (pending && !abort)
            this.revertPending(update.state);
        return !abort;
    }
    update(update) {
        let reverted = this.pendingContextChange, startSel = update.startState.selection.main;
        if (this.composing &&
            (this.composing.drifted ||
                (!update.changes.touchesRange(startSel.from, startSel.to) &&
                    update.transactions.some(tr => !tr.isUserEvent("input.type") && tr.changes.touchesRange(this.from, this.to))))) {
            this.composing.drifted = true;
            this.composing.editorBase = update.changes.mapPos(this.composing.editorBase);
        }
        else if (!this.applyEdits(update) || !this.rangeIsValid(update.state)) {
            this.pendingContextChange = null;
            this.reset(update.state);
        }
        else if (update.docChanged || update.selectionSet || reverted) {
            this.setSelection(update.state);
        }
        if (update.geometryChanged || update.docChanged || update.selectionSet)
            update.view.requestMeasure(this.measureReq);
    }
    resetRange(state) {
        let { head } = state.selection.main;
        this.from = Math.max(0, head - 10000 /* CxVp.Margin */);
        this.to = Math.min(state.doc.length, head + 10000 /* CxVp.Margin */);
    }
    reset(state) {
        this.resetRange(state);
        this.editContext.updateText(0, this.editContext.text.length, state.doc.sliceString(this.from, this.to));
        this.setSelection(state);
    }
    revertPending(state) {
        let pending = this.pendingContextChange;
        this.pendingContextChange = null;
        this.editContext.updateText(this.toContextPos(pending.from), this.toContextPos(pending.from + pending.insert.length), state.doc.sliceString(pending.from, pending.to));
    }
    setSelection(state) {
        let { main } = state.selection;
        let start = this.toContextPos(Math.max(this.from, Math.min(this.to, main.anchor)));
        let end = this.toContextPos(main.head);
        if (this.editContext.selectionStart != start || this.editContext.selectionEnd != end)
            this.editContext.updateSelection(start, end);
    }
    rangeIsValid(state) {
        let { head } = state.selection.main;
        return !(this.from > 0 && head - this.from < 500 /* CxVp.MinMargin */ ||
            this.to < state.doc.length && this.to - head < 500 /* CxVp.MinMargin */ ||
            this.to - this.from > 10000 /* CxVp.Margin */ * 3);
    }
    toEditorPos(contextPos, clipLen = this.to - this.from) {
        contextPos = Math.min(contextPos, clipLen);
        let c = this.composing;
        return c && c.drifted ? c.editorBase + (contextPos - c.contextBase) : contextPos + this.from;
    }
    toContextPos(editorPos) {
        let c = this.composing;
        return c && c.drifted ? c.contextBase + (editorPos - c.editorBase) : editorPos - this.from;
    }
    destroy() {
        for (let event in this.handlers)
            this.editContext.removeEventListener(event, this.handlers[event]);
    }
}

// The editor's update state machine looks something like this:
//
//     Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle
//                                         ↑      ↓
//                                         Updating (measure)
//
// The difference between 'Idle' and 'Idle (unchecked)' lies in
// whether a layout check has been scheduled. A regular update through
// the `update` method updates the DOM in a write-only fashion, and
// relies on a check (scheduled with `requestAnimationFrame`) to make
// sure everything is where it should be and the viewport covers the
// visible code. That check continues to measure and then optionally
// update until it reaches a coherent state.
/**
An editor view represents the editor's user interface. It holds
the editable DOM surface, and possibly other elements such as the
line number gutter. It handles events and dispatches state
transactions for editing actions.
*/
class dist_EditorView {
    /**
    The current editor state.
    */
    get state() { return this.viewState.state; }
    /**
    To be able to display large documents without consuming too much
    memory or overloading the browser, CodeMirror only draws the
    code that is visible (plus a margin around it) to the DOM. This
    property tells you the extent of the current drawn viewport, in
    document positions.
    */
    get viewport() { return this.viewState.viewport; }
    /**
    When there are, for example, large collapsed ranges in the
    viewport, its size can be a lot bigger than the actual visible
    content. Thus, if you are doing something like styling the
    content in the viewport, it is preferable to only do so for
    these ranges, which are the subset of the viewport that is
    actually drawn.
    */
    get visibleRanges() { return this.viewState.visibleRanges; }
    /**
    Returns false when the editor is entirely scrolled out of view
    or otherwise hidden.
    */
    get inView() { return this.viewState.inView; }
    /**
    Indicates whether the user is currently composing text via
    [IME](https://en.wikipedia.org/wiki/Input_method), and at least
    one change has been made in the current composition.
    */
    get composing() { return !!this.inputState && this.inputState.composing > 0; }
    /**
    Indicates whether the user is currently in composing state. Note
    that on some platforms, like Android, this will be the case a
    lot, since just putting the cursor on a word starts a
    composition there.
    */
    get compositionStarted() { return !!this.inputState && this.inputState.composing >= 0; }
    /**
    The document or shadow root that the view lives in.
    */
    get root() { return this._root; }
    /**
    @internal
    */
    get win() { return this.dom.ownerDocument.defaultView || window; }
    /**
    Construct a new view. You'll want to either provide a `parent`
    option, or put `view.dom` into your document after creating a
    view, so that the user can see the editor.
    */
    constructor(config = {}) {
        var _a;
        this.plugins = [];
        this.pluginMap = new Map;
        this.editorAttrs = {};
        this.contentAttrs = {};
        this.bidiCache = [];
        this.destroyed = false;
        /**
        @internal
        */
        this.updateState = 2 /* UpdateState.Updating */;
        /**
        @internal
        */
        this.measureScheduled = -1;
        /**
        @internal
        */
        this.measureRequests = [];
        this.contentDOM = document.createElement("div");
        this.scrollDOM = document.createElement("div");
        this.scrollDOM.tabIndex = -1;
        this.scrollDOM.className = "cm-scroller";
        this.scrollDOM.appendChild(this.contentDOM);
        this.announceDOM = document.createElement("div");
        this.announceDOM.className = "cm-announced";
        this.announceDOM.setAttribute("aria-live", "polite");
        this.dom = document.createElement("div");
        this.dom.appendChild(this.announceDOM);
        this.dom.appendChild(this.scrollDOM);
        if (config.parent)
            config.parent.appendChild(this.dom);
        let { dispatch } = config;
        this.dispatchTransactions = config.dispatchTransactions ||
            (dispatch && ((trs) => trs.forEach(tr => dispatch(tr, this)))) ||
            ((trs) => this.update(trs));
        this.dispatch = this.dispatch.bind(this);
        this._root = (config.root || getRoot(config.parent) || document);
        this.viewState = new ViewState(config.state || dist_EditorState.create(config));
        if (config.scrollTo && config.scrollTo.is(scrollIntoView))
            this.viewState.scrollTarget = config.scrollTo.value.clip(this.viewState.state);
        this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec));
        for (let plugin of this.plugins)
            plugin.update(this);
        this.observer = new DOMObserver(this);
        this.inputState = new InputState(this);
        this.inputState.ensureHandlers(this.plugins);
        this.docView = new DocView(this);
        this.mountStyles();
        this.updateAttrs();
        this.updateState = 0 /* UpdateState.Idle */;
        this.requestMeasure();
        if ((_a = document.fonts) === null || _a === void 0 ? void 0 : _a.ready)
            document.fonts.ready.then(() => this.requestMeasure());
    }
    dispatch(...input) {
        let trs = input.length == 1 && input[0] instanceof Transaction ? input
            : input.length == 1 && Array.isArray(input[0]) ? input[0]
                : [this.state.update(...input)];
        this.dispatchTransactions(trs, this);
    }
    /**
    Update the view for the given array of transactions. This will
    update the visible document and selection to match the state
    produced by the transactions, and notify view plugins of the
    change. You should usually call
    [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this
    as a primitive.
    */
    update(transactions) {
        if (this.updateState != 0 /* UpdateState.Idle */)
            throw new Error("Calls to EditorView.update are not allowed while an update is in progress");
        let redrawn = false, attrsChanged = false, update;
        let state = this.state;
        for (let tr of transactions) {
            if (tr.startState != state)
                throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
            state = tr.state;
        }
        if (this.destroyed) {
            this.viewState.state = state;
            return;
        }
        let focus = this.hasFocus, focusFlag = 0, dispatchFocus = null;
        if (transactions.some(tr => tr.annotation(isFocusChange))) {
            this.inputState.notifiedFocused = focus;
            // If a focus-change transaction is being dispatched, set this update flag.
            focusFlag = 1 /* UpdateFlag.Focus */;
        }
        else if (focus != this.inputState.notifiedFocused) {
            this.inputState.notifiedFocused = focus;
            // Schedule a separate focus transaction if necessary, otherwise
            // add a flag to this update
            dispatchFocus = focusChangeTransaction(state, focus);
            if (!dispatchFocus)
                focusFlag = 1 /* UpdateFlag.Focus */;
        }
        // If there was a pending DOM change, eagerly read it and try to
        // apply it after the given transactions.
        let pendingKey = this.observer.delayedAndroidKey, domChange = null;
        if (pendingKey) {
            this.observer.clearDelayedAndroidKey();
            domChange = this.observer.readChange();
            // Only try to apply DOM changes if the transactions didn't
            // change the doc or selection.
            if (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection))
                domChange = null;
        }
        else {
            this.observer.clear();
        }
        // When the phrases change, redraw the editor
        if (state.facet(dist_EditorState.phrases) != this.state.facet(dist_EditorState.phrases))
            return this.setState(state);
        update = ViewUpdate.create(this, state, transactions);
        update.flags |= focusFlag;
        let scrollTarget = this.viewState.scrollTarget;
        try {
            this.updateState = 2 /* UpdateState.Updating */;
            for (let tr of transactions) {
                if (scrollTarget)
                    scrollTarget = scrollTarget.map(tr.changes);
                if (tr.scrollIntoView) {
                    let { main } = tr.state.selection;
                    scrollTarget = new ScrollTarget(main.empty ? main : dist_EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));
                }
                for (let e of tr.effects)
                    if (e.is(scrollIntoView))
                        scrollTarget = e.value.clip(this.state);
            }
            this.viewState.update(update, scrollTarget);
            this.bidiCache = CachedOrder.update(this.bidiCache, update.changes);
            if (!update.empty) {
                this.updatePlugins(update);
                this.inputState.update(update);
            }
            redrawn = this.docView.update(update);
            if (this.state.facet(styleModule) != this.styleModules)
                this.mountStyles();
            attrsChanged = this.updateAttrs();
            this.showAnnouncements(transactions);
            this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer")));
        }
        finally {
            this.updateState = 0 /* UpdateState.Idle */;
        }
        if (update.startState.facet(theme) != update.state.facet(theme))
            this.viewState.mustMeasureContent = true;
        if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent)
            this.requestMeasure();
        if (redrawn)
            this.docViewUpdate();
        if (!update.empty)
            for (let listener of this.state.facet(updateListener)) {
                try {
                    listener(update);
                }
                catch (e) {
                    logException(this.state, e, "update listener");
                }
            }
        if (dispatchFocus || domChange)
            Promise.resolve().then(() => {
                if (dispatchFocus && this.state == dispatchFocus.startState)
                    this.dispatch(dispatchFocus);
                if (domChange) {
                    if (!applyDOMChange(this, domChange) && pendingKey.force)
                        dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode);
                }
            });
    }
    /**
    Reset the view to the given state. (This will cause the entire
    document to be redrawn and all view plugins to be reinitialized,
    so you should probably only use it when the new state isn't
    derived from the old state. Otherwise, use
    [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.)
    */
    setState(newState) {
        if (this.updateState != 0 /* UpdateState.Idle */)
            throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");
        if (this.destroyed) {
            this.viewState.state = newState;
            return;
        }
        this.updateState = 2 /* UpdateState.Updating */;
        let hadFocus = this.hasFocus;
        try {
            for (let plugin of this.plugins)
                plugin.destroy(this);
            this.viewState = new ViewState(newState);
            this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec));
            this.pluginMap.clear();
            for (let plugin of this.plugins)
                plugin.update(this);
            this.docView.destroy();
            this.docView = new DocView(this);
            this.inputState.ensureHandlers(this.plugins);
            this.mountStyles();
            this.updateAttrs();
            this.bidiCache = [];
        }
        finally {
            this.updateState = 0 /* UpdateState.Idle */;
        }
        if (hadFocus)
            this.focus();
        this.requestMeasure();
    }
    updatePlugins(update) {
        let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin);
        if (prevSpecs != specs) {
            let newPlugins = [];
            for (let spec of specs) {
                let found = prevSpecs.indexOf(spec);
                if (found < 0) {
                    newPlugins.push(new PluginInstance(spec));
                }
                else {
                    let plugin = this.plugins[found];
                    plugin.mustUpdate = update;
                    newPlugins.push(plugin);
                }
            }
            for (let plugin of this.plugins)
                if (plugin.mustUpdate != update)
                    plugin.destroy(this);
            this.plugins = newPlugins;
            this.pluginMap.clear();
        }
        else {
            for (let p of this.plugins)
                p.mustUpdate = update;
        }
        for (let i = 0; i < this.plugins.length; i++)
            this.plugins[i].update(this);
        if (prevSpecs != specs)
            this.inputState.ensureHandlers(this.plugins);
    }
    docViewUpdate() {
        for (let plugin of this.plugins) {
            let val = plugin.value;
            if (val && val.docViewUpdate) {
                try {
                    val.docViewUpdate(this);
                }
                catch (e) {
                    logException(this.state, e, "doc view update listener");
                }
            }
        }
    }
    /**
    @internal
    */
    measure(flush = true) {
        if (this.destroyed)
            return;
        if (this.measureScheduled > -1)
            this.win.cancelAnimationFrame(this.measureScheduled);
        if (this.observer.delayedAndroidKey) {
            this.measureScheduled = -1;
            this.requestMeasure();
            return;
        }
        this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame
        if (flush)
            this.observer.forceFlush();
        let updated = null;
        let sDOM = this.scrollDOM, scrollTop = sDOM.scrollTop * this.scaleY;
        let { scrollAnchorPos, scrollAnchorHeight } = this.viewState;
        if (Math.abs(scrollTop - this.viewState.scrollTop) > 1)
            scrollAnchorHeight = -1;
        this.viewState.scrollAnchorHeight = -1;
        try {
            for (let i = 0;; i++) {
                if (scrollAnchorHeight < 0) {
                    if (isScrolledToBottom(sDOM)) {
                        scrollAnchorPos = -1;
                        scrollAnchorHeight = this.viewState.heightMap.height;
                    }
                    else {
                        let block = this.viewState.scrollAnchorAt(scrollTop);
                        scrollAnchorPos = block.from;
                        scrollAnchorHeight = block.top;
                    }
                }
                this.updateState = 1 /* UpdateState.Measuring */;
                let changed = this.viewState.measure(this);
                if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null)
                    break;
                if (i > 5) {
                    console.warn(this.measureRequests.length
                        ? "Measure loop restarted more than 5 times"
                        : "Viewport failed to stabilize");
                    break;
                }
                let measuring = [];
                // Only run measure requests in this cycle when the viewport didn't change
                if (!(changed & 4 /* UpdateFlag.Viewport */))
                    [this.measureRequests, measuring] = [measuring, this.measureRequests];
                let measured = measuring.map(m => {
                    try {
                        return m.read(this);
                    }
                    catch (e) {
                        logException(this.state, e);
                        return BadMeasure;
                    }
                });
                let update = ViewUpdate.create(this, this.state, []), redrawn = false;
                update.flags |= changed;
                if (!updated)
                    updated = update;
                else
                    updated.flags |= changed;
                this.updateState = 2 /* UpdateState.Updating */;
                if (!update.empty) {
                    this.updatePlugins(update);
                    this.inputState.update(update);
                    this.updateAttrs();
                    redrawn = this.docView.update(update);
                    if (redrawn)
                        this.docViewUpdate();
                }
                for (let i = 0; i < measuring.length; i++)
                    if (measured[i] != BadMeasure) {
                        try {
                            let m = measuring[i];
                            if (m.write)
                                m.write(measured[i], this);
                        }
                        catch (e) {
                            logException(this.state, e);
                        }
                    }
                if (redrawn)
                    this.docView.updateSelection(true);
                if (!update.viewportChanged && this.measureRequests.length == 0) {
                    if (this.viewState.editorHeight) {
                        if (this.viewState.scrollTarget) {
                            this.docView.scrollIntoView(this.viewState.scrollTarget);
                            this.viewState.scrollTarget = null;
                            scrollAnchorHeight = -1;
                            continue;
                        }
                        else {
                            let newAnchorHeight = scrollAnchorPos < 0 ? this.viewState.heightMap.height :
                                this.viewState.lineBlockAt(scrollAnchorPos).top;
                            let diff = newAnchorHeight - scrollAnchorHeight;
                            if (diff > 1 || diff < -1) {
                                scrollTop = scrollTop + diff;
                                sDOM.scrollTop = scrollTop / this.scaleY;
                                scrollAnchorHeight = -1;
                                continue;
                            }
                        }
                    }
                    break;
                }
            }
        }
        finally {
            this.updateState = 0 /* UpdateState.Idle */;
            this.measureScheduled = -1;
        }
        if (updated && !updated.empty)
            for (let listener of this.state.facet(updateListener))
                listener(updated);
    }
    /**
    Get the CSS classes for the currently active editor themes.
    */
    get themeClasses() {
        return baseThemeID + " " +
            (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " +
            this.state.facet(theme);
    }
    updateAttrs() {
        let editorAttrs = attrsFromFacet(this, editorAttributes, {
            class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses
        });
        let contentAttrs = {
            spellcheck: "false",
            autocorrect: "off",
            autocapitalize: "off",
            writingsuggestions: "false",
            translate: "no",
            contenteditable: !this.state.facet(editable) ? "false" : "true",
            class: "cm-content",
            style: `${browser.tabSize}: ${this.state.tabSize}`,
            role: "textbox",
            "aria-multiline": "true"
        };
        if (this.state.readOnly)
            contentAttrs["aria-readonly"] = "true";
        attrsFromFacet(this, contentAttributes, contentAttrs);
        let changed = this.observer.ignore(() => {
            let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs);
            let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs);
            return changedContent || changedEditor;
        });
        this.editorAttrs = editorAttrs;
        this.contentAttrs = contentAttrs;
        return changed;
    }
    showAnnouncements(trs) {
        let first = true;
        for (let tr of trs)
            for (let effect of tr.effects)
                if (effect.is(dist_EditorView.announce)) {
                    if (first)
                        this.announceDOM.textContent = "";
                    first = false;
                    let div = this.announceDOM.appendChild(document.createElement("div"));
                    div.textContent = effect.value;
                }
    }
    mountStyles() {
        this.styleModules = this.state.facet(styleModule);
        let nonce = this.state.facet(dist_EditorView.cspNonce);
        external_style_mod_namespaceObject.StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1).reverse(), nonce ? { nonce } : undefined);
    }
    readMeasured() {
        if (this.updateState == 2 /* UpdateState.Updating */)
            throw new Error("Reading the editor layout isn't allowed during an update");
        if (this.updateState == 0 /* UpdateState.Idle */ && this.measureScheduled > -1)
            this.measure(false);
    }
    /**
    Schedule a layout measurement, optionally providing callbacks to
    do custom DOM measuring followed by a DOM write phase. Using
    this is preferable reading DOM layout directly from, for
    example, an event handler, because it'll make sure measuring and
    drawing done by other components is synchronized, avoiding
    unnecessary DOM layout computations.
    */
    requestMeasure(request) {
        if (this.measureScheduled < 0)
            this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());
        if (request) {
            if (this.measureRequests.indexOf(request) > -1)
                return;
            if (request.key != null)
                for (let i = 0; i < this.measureRequests.length; i++) {
                    if (this.measureRequests[i].key === request.key) {
                        this.measureRequests[i] = request;
                        return;
                    }
                }
            this.measureRequests.push(request);
        }
    }
    /**
    Get the value of a specific plugin, if present. Note that
    plugins that crash can be dropped from a view, so even when you
    know you registered a given plugin, it is recommended to check
    the return value of this method.
    */
    plugin(plugin) {
        let known = this.pluginMap.get(plugin);
        if (known === undefined || known && known.plugin != plugin)
            this.pluginMap.set(plugin, known = this.plugins.find(p => p.plugin == plugin) || null);
        return known && known.update(this).value;
    }
    /**
    The top position of the document, in screen coordinates. This
    may be negative when the editor is scrolled down. Points
    directly to the top of the first line, not above the padding.
    */
    get documentTop() {
        return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;
    }
    /**
    Reports the padding above and below the document.
    */
    get documentPadding() {
        return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom };
    }
    /**
    If the editor is transformed with CSS, this provides the scale
    along the X axis. Otherwise, it will just be 1. Note that
    transforms other than translation and scaling are not supported.
    */
    get scaleX() { return this.viewState.scaleX; }
    /**
    Provide the CSS transformed scale along the Y axis.
    */
    get scaleY() { return this.viewState.scaleY; }
    /**
    Find the text line or block widget at the given vertical
    position (which is interpreted as relative to the [top of the
    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)).
    */
    elementAtHeight(height) {
        this.readMeasured();
        return this.viewState.elementAtHeight(height);
    }
    /**
    Find the line block (see
    [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt)) at the given
    height, again interpreted relative to the [top of the
    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop).
    */
    lineBlockAtHeight(height) {
        this.readMeasured();
        return this.viewState.lineBlockAtHeight(height);
    }
    /**
    Get the extent and vertical position of all [line
    blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions
    are relative to the [top of the
    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop);
    */
    get viewportLineBlocks() {
        return this.viewState.viewportLines;
    }
    /**
    Find the line block around the given document position. A line
    block is a range delimited on both sides by either a
    non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line break, or the
    start/end of the document. It will usually just hold a line of
    text, but may be broken into multiple textblocks by block
    widgets.
    */
    lineBlockAt(pos) {
        return this.viewState.lineBlockAt(pos);
    }
    /**
    The editor's total content height.
    */
    get contentHeight() {
        return this.viewState.contentHeight;
    }
    /**
    Move a cursor position by [grapheme
    cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether
    the motion is away from the line start, or towards it. In
    bidirectional text, the line is traversed in visual order, using
    the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
    When the start position was the last one on the line, the
    returned position will be across the line break. If there is no
    further line, the original position is returned.
    
    By default, this method moves over a single cluster. The
    optional `by` argument can be used to move across more. It will
    be called with the first cluster as argument, and should return
    a predicate that determines, for each subsequent cluster,
    whether it should also be moved over.
    */
    moveByChar(start, forward, by) {
        return skipAtoms(this, start, moveByChar(this, start, forward, by));
    }
    /**
    Move a cursor position across the next group of either
    [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter
    non-whitespace characters.
    */
    moveByGroup(start, forward) {
        return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial)));
    }
    /**
    Get the cursor position visually at the start or end of a line.
    Note that this may differ from the _logical_ position at its
    start or end (which is simply at `line.from`/`line.to`) if text
    at the start or end goes against the line's base text direction.
    */
    visualLineSide(line, end) {
        let order = this.bidiSpans(line), dir = this.textDirectionAt(line.from);
        let span = order[end ? order.length - 1 : 0];
        return dist_EditorSelection.cursor(span.side(end, dir) + line.from, span.forward(!end, dir) ? 1 : -1);
    }
    /**
    Move to the next line boundary in the given direction. If
    `includeWrap` is true, line wrapping is on, and there is a
    further wrap point on the current line, the wrap point will be
    returned. Otherwise this function will return the start or end
    of the line.
    */
    moveToLineBoundary(start, forward, includeWrap = true) {
        return moveToLineBoundary(this, start, forward, includeWrap);
    }
    /**
    Move a cursor position vertically. When `distance` isn't given,
    it defaults to moving to the next line (including wrapped
    lines). Otherwise, `distance` should provide a positive distance
    in pixels.
    
    When `start` has a
    [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical
    motion will use that as a target horizontal position. Otherwise,
    the cursor's own horizontal position is used. The returned
    cursor will have its goal column set to whichever column was
    used.
    */
    moveVertically(start, forward, distance) {
        return skipAtoms(this, start, moveVertically(this, start, forward, distance));
    }
    /**
    Find the DOM parent node and offset (child offset if `node` is
    an element, character offset when it is a text node) at the
    given document position.
    
    Note that for positions that aren't currently in
    `visibleRanges`, the resulting DOM position isn't necessarily
    meaningful (it may just point before or after a placeholder
    element).
    */
    domAtPos(pos, side = 1) {
        return this.docView.domAtPos(pos, side);
    }
    /**
    Find the document position at the given DOM node. Can be useful
    for associating positions with DOM events. Will raise an error
    when `node` isn't part of the editor content.
    */
    posAtDOM(node, offset = 0) {
        return this.docView.posFromDOM(node, offset);
    }
    posAtCoords(coords, precise = true) {
        this.readMeasured();
        let found = posAtCoords(this, coords, precise);
        return found && found.pos;
    }
    posAndSideAtCoords(coords, precise = true) {
        this.readMeasured();
        return posAtCoords(this, coords, precise);
    }
    /**
    Get the screen coordinates at the given document position.
    `side` determines whether the coordinates are based on the
    element before (-1) or after (1) the position (if no element is
    available on the given side, the method will transparently use
    another strategy to get reasonable coordinates).
    */
    coordsAtPos(pos, side = 1) {
        this.readMeasured();
        let rect = this.docView.coordsAt(pos, side);
        if (!rect || rect.left == rect.right)
            return rect;
        let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line);
        let span = order[BidiSpan.find(order, pos - line.from, -1, side)];
        return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0));
    }
    /**
    Return the rectangle around a given character. If `pos` does not
    point in front of a character that is in the viewport and
    rendered (i.e. not replaced, not a line break), this will return
    null. For space characters that are a line wrap point, this will
    return the position before the line break.
    */
    coordsForChar(pos) {
        this.readMeasured();
        return this.docView.coordsForChar(pos);
    }
    /**
    The default width of a character in the editor. May not
    accurately reflect the width of all characters (given variable
    width fonts or styling of invididual ranges).
    */
    get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; }
    /**
    The default height of a line in the editor. May not be accurate
    for all lines.
    */
    get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; }
    /**
    The text direction
    ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)
    CSS property) of the editor's content element.
    */
    get textDirection() { return this.viewState.defaultTextDirection; }
    /**
    Find the text direction of the block at the given position, as
    assigned by CSS. If
    [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection)
    isn't enabled, or the given position is outside of the viewport,
    this will always return the same as
    [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that
    this may trigger a DOM layout.
    */
    textDirectionAt(pos) {
        let perLine = this.state.facet(perLineTextDirection);
        if (!perLine || pos < this.viewport.from || pos > this.viewport.to)
            return this.textDirection;
        this.readMeasured();
        return this.docView.textDirectionAt(pos);
    }
    /**
    Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping)
    (as determined by the
    [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)
    CSS property of its content element).
    */
    get lineWrapping() { return this.viewState.heightOracle.lineWrapping; }
    /**
    Returns the bidirectional text structure of the given line
    (which should be in the current document) as an array of span
    objects. The order of these spans matches the [text
    direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is
    left-to-right, the leftmost spans come first, otherwise the
    rightmost spans come first.
    */
    bidiSpans(line) {
        if (line.length > MaxBidiLine)
            return trivialOrder(line.length);
        let dir = this.textDirectionAt(line.from), isolates;
        for (let entry of this.bidiCache) {
            if (entry.from == line.from && entry.dir == dir &&
                (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line))))
                return entry.order;
        }
        if (!isolates)
            isolates = getIsolatedRanges(this, line);
        let order = computeOrder(line.text, dir, isolates);
        this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, true, order));
        return order;
    }
    /**
    Check whether the editor has focus.
    */
    get hasFocus() {
        var _a;
        // Safari return false for hasFocus when the context menu is open
        // or closing, which leads us to ignore selection changes from the
        // context menu because it looks like the editor isn't focused.
        // This kludges around that.
        return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) &&
            this.root.activeElement == this.contentDOM;
    }
    /**
    Put focus on the editor.
    */
    focus() {
        this.observer.ignore(() => {
            focusPreventScroll(this.contentDOM);
            this.docView.updateSelection();
        });
    }
    /**
    Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only
    necessary when moving the editor's existing DOM to a new window or shadow root.
    */
    setRoot(root) {
        if (this._root != root) {
            this._root = root;
            this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window);
            this.mountStyles();
        }
    }
    /**
    Clean up this editor view, removing its element from the
    document, unregistering event handlers, and notifying
    plugins. The view instance can no longer be used after
    calling this.
    */
    destroy() {
        if (this.root.activeElement == this.contentDOM)
            this.contentDOM.blur();
        for (let plugin of this.plugins)
            plugin.destroy(this);
        this.plugins = [];
        this.inputState.destroy();
        this.docView.destroy();
        this.dom.remove();
        this.observer.destroy();
        if (this.measureScheduled > -1)
            this.win.cancelAnimationFrame(this.measureScheduled);
        this.destroyed = true;
    }
    /**
    Returns an effect that can be
    [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to
    cause it to scroll the given position or range into view.
    */
    static scrollIntoView(pos, options = {}) {
        return scrollIntoView.of(new ScrollTarget(typeof pos == "number" ? dist_EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin));
    }
    /**
    Return an effect that resets the editor to its current (at the
    time this method was called) scroll position. Note that this
    only affects the editor's own scrollable element, not parents.
    See also
    [`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).
    
    The effect should be used with a document identical to the one
    it was created for. Failing to do so is not an error, but may
    not scroll to the expected position. You can
    [map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.
    */
    scrollSnapshot() {
        let { scrollTop, scrollLeft } = this.scrollDOM;
        let ref = this.viewState.scrollAnchorAt(scrollTop);
        return scrollIntoView.of(new ScrollTarget(dist_EditorSelection.cursor(ref.from), "start", "start", ref.top - scrollTop, scrollLeft, true));
    }
    /**
    Enable or disable tab-focus mode, which disables key bindings
    for Tab and Shift-Tab, letting the browser's default
    focus-changing behavior go through instead. This is useful to
    prevent trapping keyboard users in your editor.
    
    Without argument, this toggles the mode. With a boolean, it
    enables (true) or disables it (false). Given a number, it
    temporarily enables the mode until that number of milliseconds
    have passed or another non-Tab key is pressed.
    */
    setTabFocusMode(to) {
        if (to == null)
            this.inputState.tabFocusMode = this.inputState.tabFocusMode < 0 ? 0 : -1;
        else if (typeof to == "boolean")
            this.inputState.tabFocusMode = to ? 0 : -1;
        else if (this.inputState.tabFocusMode != 0)
            this.inputState.tabFocusMode = Date.now() + to;
    }
    /**
    Returns an extension that can be used to add DOM event handlers.
    The value should be an object mapping event names to handler
    functions. For any given event, such functions are ordered by
    extension precedence, and the first handler to return true will
    be assumed to have handled that event, and no other handlers or
    built-in behavior will be activated for it. These are registered
    on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except
    for `scroll` handlers, which will be called any time the
    editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of
    its parent nodes is scrolled.
    */
    static domEventHandlers(handlers) {
        return dist_ViewPlugin.define(() => ({}), { eventHandlers: handlers });
    }
    /**
    Create an extension that registers DOM event observers. Contrary
    to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),
    observers can't be prevented from running by a higher-precedence
    handler returning true. They also don't prevent other handlers
    and observers from running when they return true, and should not
    call `preventDefault`.
    */
    static domEventObservers(observers) {
        return dist_ViewPlugin.define(() => ({}), { eventObservers: observers });
    }
    /**
    Create a theme extension. The first argument can be a
    [`style-mod`](https://github.com/marijnh/style-mod#documentation)
    style spec providing the styles for the theme. These will be
    prefixed with a generated class for the style.
    
    Because the selectors will be prefixed with a scope class, rule
    that directly match the editor's [wrapper
    element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be
    added—need to be explicitly differentiated by adding an `&` to
    the selector for that element—for example
    `&.cm-focused`.
    
    When `dark` is set to true, the theme will be marked as dark,
    which will cause the `&dark` rules from [base
    themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to
    `&light` when a light theme is active).
    */
    static theme(spec, options) {
        let prefix = external_style_mod_namespaceObject.StyleModule.newName();
        let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))];
        if (options && options.dark)
            result.push(darkTheme.of(true));
        return result;
    }
    /**
    Create an extension that adds styles to the base theme. Like
    with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the
    place of the editor wrapper element when directly targeting
    that. You can also use `&dark` or `&light` instead to only
    target editors with a dark or light theme.
    */
    static baseTheme(spec) {
        return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs)));
    }
    /**
    Retrieve an editor view instance from the view's DOM
    representation.
    */
    static findFromDOM(dom) {
        var _a;
        let content = dom.querySelector(".cm-content");
        let tile = content && Tile.get(content) || Tile.get(dom);
        return ((_a = tile === null || tile === void 0 ? void 0 : tile.root) === null || _a === void 0 ? void 0 : _a.view) || null;
    }
}
/**
Facet to add a [style
module](https://github.com/marijnh/style-mod#documentation) to
an editor view. The view will ensure that the module is
mounted in its [document
root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root).
*/
dist_EditorView.styleModule = styleModule;
/**
An input handler can override the way changes to the editable
DOM content are handled. Handlers are passed the document
positions between which the change was found, and the new
content. When one returns true, no further input handlers are
called and the default behavior is prevented.

The `insert` argument can be used to get the default transaction
that would be applied for this input. This can be useful when
dispatching the custom behavior as a separate transaction.
*/
dist_EditorView.inputHandler = inputHandler;
/**
Functions provided in this facet will be used to transform text
pasted or dropped into the editor.
*/
dist_EditorView.clipboardInputFilter = clipboardInputFilter;
/**
Transform text copied or dragged from the editor.
*/
dist_EditorView.clipboardOutputFilter = clipboardOutputFilter;
/**
Scroll handlers can override how things are scrolled into view.
If they return `true`, no further handling happens for the
scrolling. If they return false, the default scroll behavior is
applied. Scroll handlers should never initiate editor updates.
*/
dist_EditorView.scrollHandler = scrollHandler;
/**
This facet can be used to provide functions that create effects
to be dispatched when the editor's focus state changes.
*/
dist_EditorView.focusChangeEffect = focusChangeEffect;
/**
By default, the editor assumes all its content has the same
[text direction](https://codemirror.net/6/docs/ref/#view.Direction). Configure this with a `true`
value to make it read the text direction of every (rendered)
line separately.
*/
dist_EditorView.perLineTextDirection = perLineTextDirection;
/**
Allows you to provide a function that should be called when the
library catches an exception from an extension (mostly from view
plugins, but may be used by other extensions to route exceptions
from user-code-provided callbacks). This is mostly useful for
debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException).
*/
dist_EditorView.exceptionSink = exceptionSink;
/**
A facet that can be used to register a function to be called
every time the view updates.
*/
dist_EditorView.updateListener = updateListener;
/**
Facet that controls whether the editor content DOM is editable.
When its highest-precedence value is `false`, the element will
not have its `contenteditable` attribute set. (Note that this
doesn't affect API calls that change the editor content, even
when those are bound to keys or buttons. See the
[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.)
*/
dist_EditorView.editable = editable;
/**
Allows you to influence the way mouse selection happens. The
functions in this facet will be called for a `mousedown` event
on the editor, and can return an object that overrides the way a
selection is computed from that mouse click or drag.
*/
dist_EditorView.mouseSelectionStyle = mouseSelectionStyle;
/**
Facet used to configure whether a given selection drag event
should move or copy the selection. The given predicate will be
called with the `mousedown` event, and can return `true` when
the drag should move the content.
*/
dist_EditorView.dragMovesSelection = dragMovesSelection$1;
/**
Facet used to configure whether a given selecting click adds a
new range to the existing selection or replaces it entirely. The
default behavior is to check `event.metaKey` on macOS, and
`event.ctrlKey` elsewhere.
*/
dist_EditorView.clickAddsSelectionRange = clickAddsSelectionRange;
/**
A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration)
are shown in the view. Decorations can be provided in two
ways—directly, or via a function that takes an editor view.

Only decoration sets provided directly are allowed to influence
the editor's vertical layout structure. The ones provided as
functions are called _after_ the new viewport has been computed,
and thus **must not** introduce block widgets or replacing
decorations that cover line breaks.

If you want decorated ranges to behave like atomic units for
cursor motion and deletion purposes, also provide the range set
containing the decorations to
[`EditorView.atomicRanges`](https://codemirror.net/6/docs/ref/#view.EditorView^atomicRanges).
*/
dist_EditorView.decorations = decorations;
/**
[Block wrappers](https://codemirror.net/6/docs/ref/#view.BlockWrapper) provide a way to add DOM
structure around editor lines and block widgets. Sets of
wrappers are provided in a similar way to decorations, and are
nested in a similar way when they overlap. A wrapper affects all
lines and block widgets that start inside its range.
*/
dist_EditorView.blockWrappers = blockWrappers;
/**
Facet that works much like
[`decorations`](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), but puts its
inputs at the very bottom of the precedence stack, meaning mark
decorations provided here will only be split by other, partially
overlapping `outerDecorations` ranges, and wrap around all
regular decorations. Use this for mark elements that should, as
much as possible, remain in one piece.
*/
dist_EditorView.outerDecorations = outerDecorations;
/**
Used to provide ranges that should be treated as atoms as far as
cursor motion is concerned. This causes methods like
[`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and
[`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the
commands built on top of them) to skip across such regions when
a selection endpoint would enter them. This does _not_ prevent
direct programmatic [selection
updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such
regions.
*/
dist_EditorView.atomicRanges = atomicRanges;
/**
When range decorations add a `unicode-bidi: isolate` style, they
should also include a
[`bidiIsolate`](https://codemirror.net/6/docs/ref/#view.MarkDecorationSpec.bidiIsolate) property
in their decoration spec, and be exposed through this facet, so
that the editor can compute the proper text order. (Other values
for `unicode-bidi`, except of course `normal`, are not
supported.)
*/
dist_EditorView.bidiIsolatedRanges = bidiIsolatedRanges;
/**
Facet that allows extensions to provide additional scroll
margins (space around the sides of the scrolling element that
should be considered invisible). This can be useful when the
plugin introduces elements that cover part of that element (for
example a horizontally fixed gutter).
*/
dist_EditorView.scrollMargins = scrollMargins;
/**
This facet records whether a dark theme is active. The extension
returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically
includes an instance of this when the `dark` option is set to
true.
*/
dist_EditorView.darkTheme = darkTheme;
/**
Provides a Content Security Policy nonce to use when creating
the style sheets for the editor. Holds the empty string when no
nonce has been provided.
*/
dist_EditorView.cspNonce = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : "" });
/**
Facet that provides additional DOM attributes for the editor's
editable DOM element.
*/
dist_EditorView.contentAttributes = contentAttributes;
/**
Facet that provides DOM attributes for the editor's outer
element.
*/
dist_EditorView.editorAttributes = editorAttributes;
/**
An extension that enables line wrapping in the editor (by
setting CSS `white-space` to `pre-wrap` in the content).
*/
dist_EditorView.lineWrapping = /*@__PURE__*/dist_EditorView.contentAttributes.of({ "class": "cm-lineWrapping" });
/**
State effect used to include screen reader announcements in a
transaction. These will be added to the DOM in a visually hidden
element with `aria-live="polite"` set, and should be used to
describe effects that are visually obvious but may not be
noticed by screen reader users (such as moving to the next
search match).
*/
dist_EditorView.announce = /*@__PURE__*/dist_StateEffect.define();
// Maximum line length for which we compute accurate bidi info
const MaxBidiLine = 4096;
const BadMeasure = {};
class CachedOrder {
    constructor(from, to, dir, isolates, fresh, order) {
        this.from = from;
        this.to = to;
        this.dir = dir;
        this.isolates = isolates;
        this.fresh = fresh;
        this.order = order;
    }
    static update(cache, changes) {
        if (changes.empty && !cache.some(c => c.fresh))
            return cache;
        let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR;
        for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) {
            let entry = cache[i];
            if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to))
                result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, false, entry.order));
        }
        return result;
    }
}
function attrsFromFacet(view, facet, base) {
    for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) {
        let source = sources[i], value = typeof source == "function" ? source(view) : source;
        if (value)
            combineAttrs(value, base);
    }
    return base;
}

const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key";
function normalizeKeyName(name, platform) {
    const parts = name.split(/-(?!$)/);
    let result = parts[parts.length - 1];
    if (result == "Space")
        result = " ";
    let alt, ctrl, shift, meta;
    for (let i = 0; i < parts.length - 1; ++i) {
        const mod = parts[i];
        if (/^(cmd|meta|m)$/i.test(mod))
            meta = true;
        else if (/^a(lt)?$/i.test(mod))
            alt = true;
        else if (/^(c|ctrl|control)$/i.test(mod))
            ctrl = true;
        else if (/^s(hift)?$/i.test(mod))
            shift = true;
        else if (/^mod$/i.test(mod)) {
            if (platform == "mac")
                meta = true;
            else
                ctrl = true;
        }
        else
            throw new Error("Unrecognized modifier name: " + mod);
    }
    if (alt)
        result = "Alt-" + result;
    if (ctrl)
        result = "Ctrl-" + result;
    if (meta)
        result = "Meta-" + result;
    if (shift)
        result = "Shift-" + result;
    return result;
}
function modifiers(name, event, shift) {
    if (event.altKey)
        name = "Alt-" + name;
    if (event.ctrlKey)
        name = "Ctrl-" + name;
    if (event.metaKey)
        name = "Meta-" + name;
    if (shift !== false && event.shiftKey)
        name = "Shift-" + name;
    return name;
}
const handleKeyEvents = /*@__PURE__*/Prec.default(/*@__PURE__*/dist_EditorView.domEventHandlers({
    keydown(event, view) {
        return runHandlers(getKeymap(view.state), event, view, "editor");
    }
}));
/**
Facet used for registering keymaps.

You can add multiple keymaps to an editor. Their priorities
determine their precedence (the ones specified early or with high
priority get checked first). When a handler has returned `true`
for a given key, no further handlers are called.
*/
const keymap = /*@__PURE__*/Facet.define({ enables: handleKeyEvents });
const Keymaps = /*@__PURE__*/new WeakMap();
// This is hidden behind an indirection, rather than directly computed
// by the facet, to keep internal types out of the facet's type.
function getKeymap(state) {
    let bindings = state.facet(keymap);
    let map = Keymaps.get(bindings);
    if (!map)
        Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), [])));
    return map;
}
/**
Run the key handlers registered for a given scope. The event
object should be a `"keydown"` event. Returns true if any of the
handlers handled it.
*/
function runScopeHandlers(view, event, scope) {
    return runHandlers(getKeymap(view.state), event, view, scope);
}
let storedPrefix = null;
const PrefixTimeout = 4000;
function buildKeymap(bindings, platform = currentPlatform) {
    let bound = Object.create(null);
    let isPrefix = Object.create(null);
    let checkPrefix = (name, is) => {
        let current = isPrefix[name];
        if (current == null)
            isPrefix[name] = is;
        else if (current != is)
            throw new Error("Key binding " + name + " is used both as a regular binding and as a multi-stroke prefix");
    };
    let add = (scope, key, command, preventDefault, stopPropagation) => {
        var _a, _b;
        let scopeObj = bound[scope] || (bound[scope] = Object.create(null));
        let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform));
        for (let i = 1; i < parts.length; i++) {
            let prefix = parts.slice(0, i).join(" ");
            checkPrefix(prefix, true);
            if (!scopeObj[prefix])
                scopeObj[prefix] = {
                    preventDefault: true,
                    stopPropagation: false,
                    run: [(view) => {
                            let ourObj = storedPrefix = { view, prefix, scope };
                            setTimeout(() => { if (storedPrefix == ourObj)
                                storedPrefix = null; }, PrefixTimeout);
                            return true;
                        }]
                };
        }
        let full = parts.join(" ");
        checkPrefix(full, false);
        let binding = scopeObj[full] || (scopeObj[full] = {
            preventDefault: false,
            stopPropagation: false,
            run: ((_b = (_a = scopeObj._any) === null || _a === void 0 ? void 0 : _a.run) === null || _b === void 0 ? void 0 : _b.slice()) || []
        });
        if (command)
            binding.run.push(command);
        if (preventDefault)
            binding.preventDefault = true;
        if (stopPropagation)
            binding.stopPropagation = true;
    };
    for (let b of bindings) {
        let scopes = b.scope ? b.scope.split(" ") : ["editor"];
        if (b.any)
            for (let scope of scopes) {
                let scopeObj = bound[scope] || (bound[scope] = Object.create(null));
                if (!scopeObj._any)
                    scopeObj._any = { preventDefault: false, stopPropagation: false, run: [] };
                let { any } = b;
                for (let key in scopeObj)
                    scopeObj[key].run.push(view => any(view, currentKeyEvent));
            }
        let name = b[platform] || b.key;
        if (!name)
            continue;
        for (let scope of scopes) {
            add(scope, name, b.run, b.preventDefault, b.stopPropagation);
            if (b.shift)
                add(scope, "Shift-" + name, b.shift, b.preventDefault, b.stopPropagation);
        }
    }
    return bound;
}
let currentKeyEvent = null;
function runHandlers(map, event, view, scope) {
    currentKeyEvent = event;
    let name = (0,external_w3c_keyname_namespaceObject.keyName)(event);
    let charCode = dist_codePointAt(name, 0), isChar = dist_codePointSize(charCode) == name.length && name != " ";
    let prefix = "", handled = false, prevented = false, stopPropagation = false;
    if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
        prefix = storedPrefix.prefix + " ";
        if (modifierCodes.indexOf(event.keyCode) < 0) {
            prevented = true;
            storedPrefix = null;
        }
    }
    let ran = new Set;
    let runFor = (binding) => {
        if (binding) {
            for (let cmd of binding.run)
                if (!ran.has(cmd)) {
                    ran.add(cmd);
                    if (cmd(view)) {
                        if (binding.stopPropagation)
                            stopPropagation = true;
                        return true;
                    }
                }
            if (binding.preventDefault) {
                if (binding.stopPropagation)
                    stopPropagation = true;
                prevented = true;
            }
        }
        return false;
    };
    let scopeObj = map[scope], baseName, shiftName;
    if (scopeObj) {
        if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) {
            handled = true;
        }
        else if (isChar && (event.altKey || event.metaKey || event.ctrlKey) &&
            // Ctrl-Alt may be used for AltGr on Windows
            !(browser.windows && event.ctrlKey && event.altKey) &&
            // Alt-combinations on macOS tend to be typed characters
            !(browser.mac && event.altKey && !(event.ctrlKey || event.metaKey)) &&
            (baseName = external_w3c_keyname_namespaceObject.base[event.keyCode]) && baseName != name) {
            if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) {
                handled = true;
            }
            else if (event.shiftKey && (shiftName = external_w3c_keyname_namespaceObject.shift[event.keyCode]) != name && shiftName != baseName &&
                runFor(scopeObj[prefix + modifiers(shiftName, event, false)])) {
                handled = true;
            }
        }
        else if (isChar && event.shiftKey &&
            runFor(scopeObj[prefix + modifiers(name, event, true)])) {
            handled = true;
        }
        if (!handled && runFor(scopeObj._any))
            handled = true;
    }
    if (prevented)
        handled = true;
    if (handled && stopPropagation)
        event.stopPropagation();
    currentKeyEvent = null;
    return handled;
}

/**
Implementation of [`LayerMarker`](https://codemirror.net/6/docs/ref/#view.LayerMarker) that creates
a rectangle at a given set of coordinates.
*/
class RectangleMarker {
    /**
    Create a marker with the given class and dimensions. If `width`
    is null, the DOM element will get no width style.
    */
    constructor(className, 
    /**
    The left position of the marker (in pixels, document-relative).
    */
    left, 
    /**
    The top position of the marker.
    */
    top, 
    /**
    The width of the marker, or null if it shouldn't get a width assigned.
    */
    width, 
    /**
    The height of the marker.
    */
    height) {
        this.className = className;
        this.left = left;
        this.top = top;
        this.width = width;
        this.height = height;
    }
    draw() {
        let elt = document.createElement("div");
        elt.className = this.className;
        this.adjust(elt);
        return elt;
    }
    update(elt, prev) {
        if (prev.className != this.className)
            return false;
        this.adjust(elt);
        return true;
    }
    adjust(elt) {
        elt.style.left = this.left + "px";
        elt.style.top = this.top + "px";
        if (this.width != null)
            elt.style.width = this.width + "px";
        elt.style.height = this.height + "px";
    }
    eq(p) {
        return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height &&
            this.className == p.className;
    }
    /**
    Create a set of rectangles for the given selection range,
    assigning them theclass`className`. Will create a single
    rectangle for empty ranges, and a set of selection-style
    rectangles covering the range's content (in a bidi-aware
    way) for non-empty ones.
    */
    static forRange(view, className, range) {
        if (range.empty) {
            let pos = view.coordsAtPos(range.head, range.assoc || 1);
            if (!pos)
                return [];
            let base = getBase(view);
            return [new RectangleMarker(className, pos.left - base.left, pos.top - base.top, null, pos.bottom - pos.top)];
        }
        else {
            return rectanglesForRange(view, className, range);
        }
    }
}
function getBase(view) {
    let rect = view.scrollDOM.getBoundingClientRect();
    let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX;
    return { left: left - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY };
}
function wrappedLine(view, pos, side, inside) {
    let coords = view.coordsAtPos(pos, side * 2);
    if (!coords)
        return inside;
    let editorRect = view.dom.getBoundingClientRect();
    let y = (coords.top + coords.bottom) / 2;
    let left = view.posAtCoords({ x: editorRect.left + 1, y });
    let right = view.posAtCoords({ x: editorRect.right - 1, y });
    if (left == null || right == null)
        return inside;
    return { from: Math.max(inside.from, Math.min(left, right)), to: Math.min(inside.to, Math.max(left, right)) };
}
function rectanglesForRange(view, className, range) {
    if (range.to <= view.viewport.from || range.from >= view.viewport.to)
        return [];
    let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to);
    let ltr = view.textDirection == Direction.LTR;
    let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view);
    let lineElt = content.querySelector(".cm-line"), lineStyle = lineElt && window.getComputedStyle(lineElt);
    let leftSide = contentRect.left +
        (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0);
    let rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0);
    let startBlock = blockAt(view, from, 1), endBlock = blockAt(view, to, -1);
    let visualStart = startBlock.type == BlockType.Text ? startBlock : null;
    let visualEnd = endBlock.type == BlockType.Text ? endBlock : null;
    if (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks))
        visualStart = wrappedLine(view, from, 1, visualStart);
    if (visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks))
        visualEnd = wrappedLine(view, to, -1, visualEnd);
    if (visualStart && visualEnd && visualStart.from == visualEnd.from && visualStart.to == visualEnd.to) {
        return pieces(drawForLine(range.from, range.to, visualStart));
    }
    else {
        let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false);
        let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true);
        let between = [];
        if ((visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) ||
            startBlock.widgetLineBreaks > 1 && top.bottom + view.defaultLineHeight / 2 < bottom.top)
            between.push(piece(leftSide, top.bottom, rightSide, bottom.top));
        else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == BlockType.Text)
            top.bottom = bottom.top = (top.bottom + bottom.top) / 2;
        return pieces(top).concat(between).concat(pieces(bottom));
    }
    function piece(left, top, right, bottom) {
        return new RectangleMarker(className, left - base.left, top - base.top, right - left, bottom - top);
    }
    function pieces({ top, bottom, horizontal }) {
        let pieces = [];
        for (let i = 0; i < horizontal.length; i += 2)
            pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom));
        return pieces;
    }
    // Gets passed from/to in line-local positions
    function drawForLine(from, to, line) {
        let top = 1e9, bottom = -1e9, horizontal = [];
        function addSpan(from, fromOpen, to, toOpen, dir) {
            // Passing 2/-2 is a kludge to force the view to return
            // coordinates on the proper side of block widgets, since
            // normalizing the side there, though appropriate for most
            // coordsAtPos queries, would break selection drawing.
            let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2));
            let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2));
            if (!fromCoords || !toCoords)
                return;
            top = Math.min(fromCoords.top, toCoords.top, top);
            bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom);
            if (dir == Direction.LTR)
                horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);
            else
                horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);
        }
        let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to;
        // Split the range by visible range and document line
        for (let r of view.visibleRanges)
            if (r.to > start && r.from < end) {
                for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) {
                    let docLine = view.state.doc.lineAt(pos);
                    for (let span of view.bidiSpans(docLine)) {
                        let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from;
                        if (spanFrom >= endPos)
                            break;
                        if (spanTo > pos)
                            addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir);
                    }
                    pos = docLine.to + 1;
                    if (pos >= endPos)
                        break;
                }
            }
        if (horizontal.length == 0)
            addSpan(start, from == null, end, to == null, view.textDirection);
        return { top, bottom, horizontal };
    }
    function drawForWidget(block, top) {
        let y = contentRect.top + (top ? block.top : block.bottom);
        return { top: y, bottom: y, horizontal: [] };
    }
}
function sameMarker(a, b) {
    return a.constructor == b.constructor && a.eq(b);
}
class LayerView {
    constructor(view, layer) {
        this.view = view;
        this.layer = layer;
        this.drawn = [];
        this.scaleX = 1;
        this.scaleY = 1;
        this.measureReq = { read: this.measure.bind(this), write: this.draw.bind(this) };
        this.dom = view.scrollDOM.appendChild(document.createElement("div"));
        this.dom.classList.add("cm-layer");
        if (layer.above)
            this.dom.classList.add("cm-layer-above");
        if (layer.class)
            this.dom.classList.add(layer.class);
        this.scale();
        this.dom.setAttribute("aria-hidden", "true");
        this.setOrder(view.state);
        view.requestMeasure(this.measureReq);
        if (layer.mount)
            layer.mount(this.dom, view);
    }
    update(update) {
        if (update.startState.facet(layerOrder) != update.state.facet(layerOrder))
            this.setOrder(update.state);
        if (this.layer.update(update, this.dom) || update.geometryChanged) {
            this.scale();
            update.view.requestMeasure(this.measureReq);
        }
    }
    docViewUpdate(view) {
        if (this.layer.updateOnDocViewUpdate !== false)
            view.requestMeasure(this.measureReq);
    }
    setOrder(state) {
        let pos = 0, order = state.facet(layerOrder);
        while (pos < order.length && order[pos] != this.layer)
            pos++;
        this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos);
    }
    measure() {
        return this.layer.markers(this.view);
    }
    scale() {
        let { scaleX, scaleY } = this.view;
        if (scaleX != this.scaleX || scaleY != this.scaleY) {
            this.scaleX = scaleX;
            this.scaleY = scaleY;
            this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`;
        }
    }
    draw(markers) {
        if (markers.length != this.drawn.length || markers.some((p, i) => !sameMarker(p, this.drawn[i]))) {
            let old = this.dom.firstChild, oldI = 0;
            for (let marker of markers) {
                if (marker.update && old && marker.constructor && this.drawn[oldI].constructor &&
                    marker.update(old, this.drawn[oldI])) {
                    old = old.nextSibling;
                    oldI++;
                }
                else {
                    this.dom.insertBefore(marker.draw(), old);
                }
            }
            while (old) {
                let next = old.nextSibling;
                old.remove();
                old = next;
            }
            this.drawn = markers;
            if (browser.safari && browser.safari_version >= 26) // Issue #1600, 1627
                this.dom.style.display = this.dom.firstChild ? "" : "none";
        }
    }
    destroy() {
        if (this.layer.destroy)
            this.layer.destroy(this.dom, this.view);
        this.dom.remove();
    }
}
const layerOrder = /*@__PURE__*/Facet.define();
/**
Define a layer.
*/
function dist_layer(config) {
    return [
        dist_ViewPlugin.define(v => new LayerView(v, config)),
        layerOrder.of(config)
    ];
}

const selectionConfig = /*@__PURE__*/Facet.define({
    combine(configs) {
        return combineConfig(configs, {
            cursorBlinkRate: 1200,
            drawRangeCursor: true
        }, {
            cursorBlinkRate: (a, b) => Math.min(a, b),
            drawRangeCursor: (a, b) => a || b
        });
    }
});
/**
Returns an extension that hides the browser's native selection and
cursor, replacing the selection with a background behind the text
(with the `cm-selectionBackground` class), and the
cursors with elements overlaid over the code (using
`cm-cursor-primary` and `cm-cursor-secondary`).

This allows the editor to display secondary selection ranges, and
tends to produce a type of selection more in line with that users
expect in a text editor (the native selection styling will often
leave gaps between lines and won't fill the horizontal space after
a line when the selection continues past it).

It does have a performance cost, in that it requires an extra DOM
layout cycle for many updates (the selection is drawn based on DOM
layout information that's only available after laying out the
content).
*/
function drawSelection(config = {}) {
    return [
        selectionConfig.of(config),
        cursorLayer,
        selectionLayer,
        hideNativeSelection,
        nativeSelectionHidden.of(true)
    ];
}
/**
Retrieve the [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) configuration
for this state. (Note that this will return a set of defaults even
if `drawSelection` isn't enabled.)
*/
function getDrawSelectionConfig(state) {
    return state.facet(selectionConfig);
}
function configChanged(update) {
    return update.startState.facet(selectionConfig) != update.state.facet(selectionConfig);
}
const cursorLayer = /*@__PURE__*/dist_layer({
    above: true,
    markers(view) {
        let { state } = view, conf = state.facet(selectionConfig);
        let cursors = [];
        for (let r of state.selection.ranges) {
            let prim = r == state.selection.main;
            if (r.empty || conf.drawRangeCursor) {
                let className = prim ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary";
                let cursor = r.empty ? r : dist_EditorSelection.cursor(r.head, r.head > r.anchor ? -1 : 1);
                for (let piece of RectangleMarker.forRange(view, className, cursor))
                    cursors.push(piece);
            }
        }
        return cursors;
    },
    update(update, dom) {
        if (update.transactions.some(tr => tr.selection))
            dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
        let confChange = configChanged(update);
        if (confChange)
            setBlinkRate(update.state, dom);
        return update.docChanged || update.selectionSet || confChange;
    },
    mount(dom, view) {
        setBlinkRate(view.state, dom);
    },
    class: "cm-cursorLayer"
});
function setBlinkRate(state, dom) {
    dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + "ms";
}
const selectionLayer = /*@__PURE__*/dist_layer({
    above: false,
    markers(view) {
        return view.state.selection.ranges.map(r => r.empty ? [] : RectangleMarker.forRange(view, "cm-selectionBackground", r))
            .reduce((a, b) => a.concat(b));
    },
    update(update, dom) {
        return update.docChanged || update.selectionSet || update.viewportChanged || configChanged(update);
    },
    class: "cm-selectionLayer"
});
const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/dist_EditorView.theme({
    ".cm-line": {
        "& ::selection, &::selection": { backgroundColor: "transparent !important" },
        caretColor: "transparent !important"
    },
    ".cm-content": {
        caretColor: "transparent !important",
        "& :focus": {
            caretColor: "initial !important",
            "&::selection, & ::selection": {
                backgroundColor: "Highlight !important"
            }
        }
    }
}));

const setDropCursorPos = /*@__PURE__*/dist_StateEffect.define({
    map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); }
});
const dropCursorPos = /*@__PURE__*/dist_StateField.define({
    create() { return null; },
    update(pos, tr) {
        if (pos != null)
            pos = tr.changes.mapPos(pos);
        return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos);
    }
});
const drawDropCursor = /*@__PURE__*/dist_ViewPlugin.fromClass(class {
    constructor(view) {
        this.view = view;
        this.cursor = null;
        this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) };
    }
    update(update) {
        var _a;
        let cursorPos = update.state.field(dropCursorPos);
        if (cursorPos == null) {
            if (this.cursor != null) {
                (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove();
                this.cursor = null;
            }
        }
        else {
            if (!this.cursor) {
                this.cursor = this.view.scrollDOM.appendChild(document.createElement("div"));
                this.cursor.className = "cm-dropCursor";
            }
            if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged)
                this.view.requestMeasure(this.measureReq);
        }
    }
    readPos() {
        let { view } = this;
        let pos = view.state.field(dropCursorPos);
        let rect = pos != null && view.coordsAtPos(pos);
        if (!rect)
            return null;
        let outer = view.scrollDOM.getBoundingClientRect();
        return {
            left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX,
            top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY,
            height: rect.bottom - rect.top
        };
    }
    drawCursor(pos) {
        if (this.cursor) {
            let { scaleX, scaleY } = this.view;
            if (pos) {
                this.cursor.style.left = pos.left / scaleX + "px";
                this.cursor.style.top = pos.top / scaleY + "px";
                this.cursor.style.height = pos.height / scaleY + "px";
            }
            else {
                this.cursor.style.left = "-100000px";
            }
        }
    }
    destroy() {
        if (this.cursor)
            this.cursor.remove();
    }
    setDropPos(pos) {
        if (this.view.state.field(dropCursorPos) != pos)
            this.view.dispatch({ effects: setDropCursorPos.of(pos) });
    }
}, {
    eventObservers: {
        dragover(event) {
            this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY }));
        },
        dragleave(event) {
            if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget))
                this.setDropPos(null);
        },
        dragend() {
            this.setDropPos(null);
        },
        drop() {
            this.setDropPos(null);
        }
    }
});
/**
Draws a cursor at the current drop position when something is
dragged over the editor.
*/
function dropCursor() {
    return [dropCursorPos, drawDropCursor];
}

function iterMatches(doc, re, from, to, f) {
    re.lastIndex = 0;
    for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) {
        if (!cursor.lineBreak)
            while (m = re.exec(cursor.value))
                f(pos + m.index, m);
    }
}
function matchRanges(view, maxLength) {
    let visible = view.visibleRanges;
    if (visible.length == 1 && visible[0].from == view.viewport.from &&
        visible[0].to == view.viewport.to)
        return visible;
    let result = [];
    for (let { from, to } of visible) {
        from = Math.max(view.state.doc.lineAt(from).from, from - maxLength);
        to = Math.min(view.state.doc.lineAt(to).to, to + maxLength);
        if (result.length && result[result.length - 1].to >= from)
            result[result.length - 1].to = to;
        else
            result.push({ from, to });
    }
    return result;
}
/**
Helper class used to make it easier to maintain decorations on
visible code that matches a given regular expression. To be used
in a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object
represent a matching configuration.
*/
class MatchDecorator {
    /**
    Create a decorator.
    */
    constructor(config) {
        const { regexp, decoration, decorate, boundary, maxLength = 1000 } = config;
        if (!regexp.global)
            throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");
        this.regexp = regexp;
        if (decorate) {
            this.addMatch = (match, view, from, add) => decorate(add, from, from + match[0].length, match, view);
        }
        else if (typeof decoration == "function") {
            this.addMatch = (match, view, from, add) => {
                let deco = decoration(match, view, from);
                if (deco)
                    add(from, from + match[0].length, deco);
            };
        }
        else if (decoration) {
            this.addMatch = (match, _view, from, add) => add(from, from + match[0].length, decoration);
        }
        else {
            throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");
        }
        this.boundary = boundary;
        this.maxLength = maxLength;
    }
    /**
    Compute the full set of decorations for matches in the given
    view's viewport. You'll want to call this when initializing your
    plugin.
    */
    createDeco(view) {
        let build = new RangeSetBuilder(), add = build.add.bind(build);
        for (let { from, to } of matchRanges(view, this.maxLength))
            iterMatches(view.state.doc, this.regexp, from, to, (from, m) => this.addMatch(m, view, from, add));
        return build.finish();
    }
    /**
    Update a set of decorations for a view update. `deco` _must_ be
    the set of decorations produced by _this_ `MatchDecorator` for
    the view state before the update.
    */
    updateDeco(update, deco) {
        let changeFrom = 1e9, changeTo = -1;
        if (update.docChanged)
            update.changes.iterChanges((_f, _t, from, to) => {
                if (to >= update.view.viewport.from && from <= update.view.viewport.to) {
                    changeFrom = Math.min(from, changeFrom);
                    changeTo = Math.max(to, changeTo);
                }
            });
        if (update.viewportMoved || changeTo - changeFrom > 1000)
            return this.createDeco(update.view);
        if (changeTo > -1)
            return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo);
        return deco;
    }
    updateRange(view, deco, updateFrom, updateTo) {
        for (let r of view.visibleRanges) {
            let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo);
            if (to >= from) {
                let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;
                let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to);
                if (this.boundary) {
                    for (; from > fromLine.from; from--)
                        if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) {
                            start = from;
                            break;
                        }
                    for (; to < toLine.to; to++)
                        if (this.boundary.test(toLine.text[to - toLine.from])) {
                            end = to;
                            break;
                        }
                }
                let ranges = [], m;
                let add = (from, to, deco) => ranges.push(deco.range(from, to));
                if (fromLine == toLine) {
                    this.regexp.lastIndex = start - fromLine.from;
                    while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from)
                        this.addMatch(m, view, m.index + fromLine.from, add);
                }
                else {
                    iterMatches(view.state.doc, this.regexp, start, end, (from, m) => this.addMatch(m, view, from, add));
                }
                deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges });
            }
        }
        return deco;
    }
}

const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g";
const Specials = /*@__PURE__*/new RegExp("[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]", UnicodeRegexpSupport);
const Names = {
    0: "null",
    7: "bell",
    8: "backspace",
    10: "newline",
    11: "vertical tab",
    13: "carriage return",
    27: "escape",
    8203: "zero width space",
    8204: "zero width non-joiner",
    8205: "zero width joiner",
    8206: "left-to-right mark",
    8207: "right-to-left mark",
    8232: "line separator",
    8237: "left-to-right override",
    8238: "right-to-left override",
    8294: "left-to-right isolate",
    8295: "right-to-left isolate",
    8297: "pop directional isolate",
    8233: "paragraph separator",
    65279: "zero width no-break space",
    65532: "object replacement"
};
let _supportsTabSize = null;
function supportsTabSize() {
    var _a;
    if (_supportsTabSize == null && typeof document != "undefined" && document.body) {
        let styles = document.body.style;
        _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null;
    }
    return _supportsTabSize || false;
}
const specialCharConfig = /*@__PURE__*/Facet.define({
    combine(configs) {
        let config = combineConfig(configs, {
            render: null,
            specialChars: Specials,
            addSpecialChars: null
        });
        if (config.replaceTabs = !supportsTabSize())
            config.specialChars = new RegExp("\t|" + config.specialChars.source, UnicodeRegexpSupport);
        if (config.addSpecialChars)
            config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport);
        return config;
    }
});
/**
Returns an extension that installs highlighting of special
characters.
*/
function highlightSpecialChars(
/**
Configuration options.
*/
config = {}) {
    return [specialCharConfig.of(config), specialCharPlugin()];
}
let _plugin = null;
function specialCharPlugin() {
    return _plugin || (_plugin = dist_ViewPlugin.fromClass(class {
        constructor(view) {
            this.view = view;
            this.decorations = dist_Decoration.none;
            this.decorationCache = Object.create(null);
            this.decorator = this.makeDecorator(view.state.facet(specialCharConfig));
            this.decorations = this.decorator.createDeco(view);
        }
        makeDecorator(conf) {
            return new MatchDecorator({
                regexp: conf.specialChars,
                decoration: (m, view, pos) => {
                    let { doc } = view.state;
                    let code = codePointAt(m[0], 0);
                    if (code == 9) {
                        let line = doc.lineAt(pos);
                        let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from);
                        return dist_Decoration.replace({
                            widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth / this.view.scaleX)
                        });
                    }
                    return this.decorationCache[code] ||
                        (this.decorationCache[code] = dist_Decoration.replace({ widget: new SpecialCharWidget(conf, code) }));
                },
                boundary: conf.replaceTabs ? undefined : /[^]/
            });
        }
        update(update) {
            let conf = update.state.facet(specialCharConfig);
            if (update.startState.facet(specialCharConfig) != conf) {
                this.decorator = this.makeDecorator(conf);
                this.decorations = this.decorator.createDeco(update.view);
            }
            else {
                this.decorations = this.decorator.updateDeco(update, this.decorations);
            }
        }
    }, {
        decorations: v => v.decorations
    }));
}
const DefaultPlaceholder = "\u2022";
// Assigns placeholder characters from the Control Pictures block to
// ASCII control characters
function placeholder$1(code) {
    if (code >= 32)
        return DefaultPlaceholder;
    if (code == 10)
        return "\u2424";
    return String.fromCharCode(9216 + code);
}
class SpecialCharWidget extends WidgetType {
    constructor(options, code) {
        super();
        this.options = options;
        this.code = code;
    }
    eq(other) { return other.code == this.code; }
    toDOM(view) {
        let ph = placeholder$1(this.code);
        let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16));
        let custom = this.options.render && this.options.render(this.code, desc, ph);
        if (custom)
            return custom;
        let span = document.createElement("span");
        span.textContent = ph;
        span.title = desc;
        span.setAttribute("aria-label", desc);
        span.className = "cm-specialChar";
        return span;
    }
    ignoreEvent() { return false; }
}
class TabWidget extends WidgetType {
    constructor(width) {
        super();
        this.width = width;
    }
    eq(other) { return other.width == this.width; }
    toDOM() {
        let span = document.createElement("span");
        span.textContent = "\t";
        span.className = "cm-tab";
        span.style.width = this.width + "px";
        return span;
    }
    ignoreEvent() { return false; }
}

const dist_plugin = /*@__PURE__*/(/* unused pure expression or super */ null && (dist_ViewPlugin.fromClass(class {
    constructor() {
        this.height = 1000;
        this.attrs = { style: "padding-bottom: 1000px" };
    }
    update(update) {
        let { view } = update;
        let height = view.viewState.editorHeight -
            view.defaultLineHeight - view.documentPadding.top - 0.5;
        if (height >= 0 && height != this.height) {
            this.height = height;
            this.attrs = { style: `padding-bottom: ${height}px` };
        }
    }
})));
/**
Returns an extension that makes sure the content has a bottom
margin equivalent to the height of the editor, minus one line
height, so that every line in the document can be scrolled to the
top of the editor.

This is only meaningful when the editor is scrollable, and should
not be enabled in editors that take the size of their content.
*/
function scrollPastEnd() {
    return [dist_plugin, contentAttributes.of(view => { var _a; return ((_a = view.plugin(dist_plugin)) === null || _a === void 0 ? void 0 : _a.attrs) || null; })];
}

/**
Mark lines that have a cursor on them with the `"cm-activeLine"`
DOM class.
*/
function highlightActiveLine() {
    return activeLineHighlighter;
}
const lineDeco = /*@__PURE__*/dist_Decoration.line({ class: "cm-activeLine" });
const activeLineHighlighter = /*@__PURE__*/dist_ViewPlugin.fromClass(class {
    constructor(view) {
        this.decorations = this.getDeco(view);
    }
    update(update) {
        if (update.docChanged || update.selectionSet)
            this.decorations = this.getDeco(update.view);
    }
    getDeco(view) {
        let lastLineStart = -1, deco = [];
        for (let r of view.state.selection.ranges) {
            let line = view.lineBlockAt(r.head);
            if (line.from > lastLineStart) {
                deco.push(lineDeco.range(line.from));
                lastLineStart = line.from;
            }
        }
        return dist_Decoration.set(deco);
    }
}, {
    decorations: v => v.decorations
});

class Placeholder extends WidgetType {
    constructor(content) {
        super();
        this.content = content;
    }
    toDOM(view) {
        let wrap = document.createElement("span");
        wrap.className = "cm-placeholder";
        wrap.style.pointerEvents = "none";
        wrap.appendChild(typeof this.content == "string" ? document.createTextNode(this.content) :
            typeof this.content == "function" ? this.content(view) :
                this.content.cloneNode(true));
        wrap.setAttribute("aria-hidden", "true");
        return wrap;
    }
    coordsAt(dom) {
        let rects = dom.firstChild ? clientRectsFor(dom.firstChild) : [];
        if (!rects.length)
            return null;
        let style = window.getComputedStyle(dom.parentNode);
        let rect = flattenRect(rects[0], style.direction != "rtl");
        let lineHeight = parseInt(style.lineHeight);
        if (rect.bottom - rect.top > lineHeight * 1.5)
            return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.top + lineHeight };
        return rect;
    }
    ignoreEvent() { return false; }
}
/**
Extension that enables a placeholder—a piece of example content
to show when the editor is empty.
*/
function dist_placeholder(content) {
    let plugin = dist_ViewPlugin.fromClass(class {
        constructor(view) {
            this.view = view;
            this.placeholder = content
                ? dist_Decoration.set([dist_Decoration.widget({ widget: new Placeholder(content), side: 1 }).range(0)])
                : dist_Decoration.none;
        }
        get decorations() { return this.view.state.doc.length ? dist_Decoration.none : this.placeholder; }
    }, { decorations: v => v.decorations });
    return typeof content == "string" ? [
        plugin, dist_EditorView.contentAttributes.of({ "aria-placeholder": content })
    ] : plugin;
}

// Don't compute precise column positions for line offsets above this
// (since it could get expensive). Assume offset==column for them.
const MaxOff = 2000;
function rectangleFor(state, a, b) {
    let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line);
    let ranges = [];
    if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) {
        let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off);
        for (let i = startLine; i <= endLine; i++) {
            let line = state.doc.line(i);
            if (line.length <= endOff)
                ranges.push(dist_EditorSelection.range(line.from + startOff, line.to + endOff));
        }
    }
    else {
        let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col);
        for (let i = startLine; i <= endLine; i++) {
            let line = state.doc.line(i);
            let start = findColumn(line.text, startCol, state.tabSize, true);
            if (start < 0) {
                ranges.push(dist_EditorSelection.cursor(line.to));
            }
            else {
                let end = findColumn(line.text, endCol, state.tabSize);
                ranges.push(dist_EditorSelection.range(line.from + start, line.from + end));
            }
        }
    }
    return ranges;
}
function absoluteColumn(view, x) {
    let ref = view.coordsAtPos(view.viewport.from);
    return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1;
}
function getPos(view, event) {
    let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
    let line = view.state.doc.lineAt(offset), off = offset - line.from;
    let col = off > MaxOff ? -1
        : off == line.length ? absoluteColumn(view, event.clientX)
            : dist_countColumn(line.text, view.state.tabSize, offset - line.from);
    return { line: line.number, col, off };
}
function rectangleSelectionStyle(view, event) {
    let start = getPos(view, event), startSel = view.state.selection;
    if (!start)
        return null;
    return {
        update(update) {
            if (update.docChanged) {
                let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from);
                let newLine = update.state.doc.lineAt(newStart);
                start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) };
                startSel = startSel.map(update.changes);
            }
        },
        get(event, _extend, multiple) {
            let cur = getPos(view, event);
            if (!cur)
                return startSel;
            let ranges = rectangleFor(view.state, start, cur);
            if (!ranges.length)
                return startSel;
            if (multiple)
                return dist_EditorSelection.create(ranges.concat(startSel.ranges));
            else
                return dist_EditorSelection.create(ranges);
        }
    };
}
/**
Create an extension that enables rectangular selections. By
default, it will react to left mouse drag with the Alt key held
down. When such a selection occurs, the text within the rectangle
that was dragged over will be selected, as one selection
[range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line.
*/
function rectangularSelection(options) {
    let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0);
    return dist_EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null);
}
const keys = {
    Alt: [18, e => !!e.altKey],
    Control: [17, e => !!e.ctrlKey],
    Shift: [16, e => !!e.shiftKey],
    Meta: [91, e => !!e.metaKey]
};
const showCrosshair = { style: "cursor: crosshair" };
/**
Returns an extension that turns the pointer cursor into a
crosshair when a given modifier key, defaulting to Alt, is held
down. Can serve as a visual hint that rectangular selection is
going to happen when paired with
[`rectangularSelection`](https://codemirror.net/6/docs/ref/#view.rectangularSelection).
*/
function crosshairCursor(options = {}) {
    let [code, getter] = keys[options.key || "Alt"];
    let plugin = dist_ViewPlugin.fromClass(class {
        constructor(view) {
            this.view = view;
            this.isDown = false;
        }
        set(isDown) {
            if (this.isDown != isDown) {
                this.isDown = isDown;
                this.view.update([]);
            }
        }
    }, {
        eventObservers: {
            keydown(e) {
                this.set(e.keyCode == code || getter(e));
            },
            keyup(e) {
                if (e.keyCode == code || !getter(e))
                    this.set(false);
            },
            mousemove(e) {
                this.set(getter(e));
            }
        }
    });
    return [
        plugin,
        dist_EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; })
    ];
}

const Outside = "-10000px";
class TooltipViewManager {
    constructor(view, facet, createTooltipView, removeTooltipView) {
        this.facet = facet;
        this.createTooltipView = createTooltipView;
        this.removeTooltipView = removeTooltipView;
        this.input = view.state.facet(facet);
        this.tooltips = this.input.filter(t => t);
        let prev = null;
        this.tooltipViews = this.tooltips.map(t => prev = createTooltipView(t, prev));
    }
    update(update, above) {
        var _a;
        let input = update.state.facet(this.facet);
        let tooltips = input.filter(x => x);
        if (input === this.input) {
            for (let t of this.tooltipViews)
                if (t.update)
                    t.update(update);
            return false;
        }
        let tooltipViews = [], newAbove = above ? [] : null;
        for (let i = 0; i < tooltips.length; i++) {
            let tip = tooltips[i], known = -1;
            if (!tip)
                continue;
            for (let i = 0; i < this.tooltips.length; i++) {
                let other = this.tooltips[i];
                if (other && other.create == tip.create)
                    known = i;
            }
            if (known < 0) {
                tooltipViews[i] = this.createTooltipView(tip, i ? tooltipViews[i - 1] : null);
                if (newAbove)
                    newAbove[i] = !!tip.above;
            }
            else {
                let tooltipView = tooltipViews[i] = this.tooltipViews[known];
                if (newAbove)
                    newAbove[i] = above[known];
                if (tooltipView.update)
                    tooltipView.update(update);
            }
        }
        for (let t of this.tooltipViews)
            if (tooltipViews.indexOf(t) < 0) {
                this.removeTooltipView(t);
                (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);
            }
        if (above) {
            newAbove.forEach((val, i) => above[i] = val);
            above.length = newAbove.length;
        }
        this.input = input;
        this.tooltips = tooltips;
        this.tooltipViews = tooltipViews;
        return true;
    }
}
/**
Creates an extension that configures tooltip behavior.
*/
function tooltips(config = {}) {
    return tooltipConfig.of(config);
}
function windowSpace(view) {
    let docElt = view.dom.ownerDocument.documentElement;
    return { top: 0, left: 0, bottom: docElt.clientHeight, right: docElt.clientWidth };
}
const tooltipConfig = /*@__PURE__*/Facet.define({
    combine: values => {
        var _a, _b, _c;
        return ({
            position: browser.ios ? "absolute" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || "fixed",
            parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null,
            tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace,
        });
    }
});
const knownHeight = /*@__PURE__*/new WeakMap();
const tooltipPlugin = /*@__PURE__*/dist_ViewPlugin.fromClass(class {
    constructor(view) {
        this.view = view;
        this.above = [];
        this.inView = true;
        this.madeAbsolute = false;
        this.lastTransaction = 0;
        this.measureTimeout = -1;
        let config = view.state.facet(tooltipConfig);
        this.position = config.position;
        this.parent = config.parent;
        this.classes = view.themeClasses;
        this.createContainer();
        this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this };
        this.resizeObserver = typeof ResizeObserver == "function" ? new ResizeObserver(() => this.measureSoon()) : null;
        this.manager = new TooltipViewManager(view, showTooltip, (t, p) => this.createTooltip(t, p), t => {
            if (this.resizeObserver)
                this.resizeObserver.unobserve(t.dom);
            t.dom.remove();
        });
        this.above = this.manager.tooltips.map(t => !!t.above);
        this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => {
            if (Date.now() > this.lastTransaction - 50 &&
                entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1)
                this.measureSoon();
        }, { threshold: [1] }) : null;
        this.observeIntersection();
        view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this));
        this.maybeMeasure();
    }
    createContainer() {
        if (this.parent) {
            this.container = document.createElement("div");
            this.container.style.position = "relative";
            this.container.className = this.view.themeClasses;
            this.parent.appendChild(this.container);
        }
        else {
            this.container = this.view.dom;
        }
    }
    observeIntersection() {
        if (this.intersectionObserver) {
            this.intersectionObserver.disconnect();
            for (let tooltip of this.manager.tooltipViews)
                this.intersectionObserver.observe(tooltip.dom);
        }
    }
    measureSoon() {
        if (this.measureTimeout < 0)
            this.measureTimeout = setTimeout(() => {
                this.measureTimeout = -1;
                this.maybeMeasure();
            }, 50);
    }
    update(update) {
        if (update.transactions.length)
            this.lastTransaction = Date.now();
        let updated = this.manager.update(update, this.above);
        if (updated)
            this.observeIntersection();
        let shouldMeasure = updated || update.geometryChanged;
        let newConfig = update.state.facet(tooltipConfig);
        if (newConfig.position != this.position && !this.madeAbsolute) {
            this.position = newConfig.position;
            for (let t of this.manager.tooltipViews)
                t.dom.style.position = this.position;
            shouldMeasure = true;
        }
        if (newConfig.parent != this.parent) {
            if (this.parent)
                this.container.remove();
            this.parent = newConfig.parent;
            this.createContainer();
            for (let t of this.manager.tooltipViews)
                this.container.appendChild(t.dom);
            shouldMeasure = true;
        }
        else if (this.parent && this.view.themeClasses != this.classes) {
            this.classes = this.container.className = this.view.themeClasses;
        }
        if (shouldMeasure)
            this.maybeMeasure();
    }
    createTooltip(tooltip, prev) {
        let tooltipView = tooltip.create(this.view);
        let before = prev ? prev.dom : null;
        tooltipView.dom.classList.add("cm-tooltip");
        if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) {
            let arrow = document.createElement("div");
            arrow.className = "cm-tooltip-arrow";
            tooltipView.dom.appendChild(arrow);
        }
        tooltipView.dom.style.position = this.position;
        tooltipView.dom.style.top = Outside;
        tooltipView.dom.style.left = "0px";
        this.container.insertBefore(tooltipView.dom, before);
        if (tooltipView.mount)
            tooltipView.mount(this.view);
        if (this.resizeObserver)
            this.resizeObserver.observe(tooltipView.dom);
        return tooltipView;
    }
    destroy() {
        var _a, _b, _c;
        this.view.win.removeEventListener("resize", this.measureSoon);
        for (let tooltipView of this.manager.tooltipViews) {
            tooltipView.dom.remove();
            (_a = tooltipView.destroy) === null || _a === void 0 ? void 0 : _a.call(tooltipView);
        }
        if (this.parent)
            this.container.remove();
        (_b = this.resizeObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
        (_c = this.intersectionObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
        clearTimeout(this.measureTimeout);
    }
    readMeasure() {
        let scaleX = 1, scaleY = 1, makeAbsolute = false;
        if (this.position == "fixed" && this.manager.tooltipViews.length) {
            let { dom } = this.manager.tooltipViews[0];
            if (browser.safari) {
                // Safari always sets offsetParent to null, even if a fixed
                // element is positioned relative to a transformed parent. So
                // we use this kludge to try and detect this.
                let rect = dom.getBoundingClientRect();
                makeAbsolute = Math.abs(rect.top + 10000) > 1 || Math.abs(rect.left) > 1;
            }
            else {
                // More conforming browsers will set offsetParent to the
                // transformed element.
                makeAbsolute = !!dom.offsetParent && dom.offsetParent != this.container.ownerDocument.body;
            }
        }
        if (makeAbsolute || this.position == "absolute") {
            if (this.parent) {
                let rect = this.parent.getBoundingClientRect();
                if (rect.width && rect.height) {
                    scaleX = rect.width / this.parent.offsetWidth;
                    scaleY = rect.height / this.parent.offsetHeight;
                }
            }
            else {
                ({ scaleX, scaleY } = this.view.viewState);
            }
        }
        let visible = this.view.scrollDOM.getBoundingClientRect(), margins = getScrollMargins(this.view);
        return {
            visible: {
                left: visible.left + margins.left, top: visible.top + margins.top,
                right: visible.right - margins.right, bottom: visible.bottom - margins.bottom
            },
            parent: this.parent ? this.container.getBoundingClientRect() : this.view.dom.getBoundingClientRect(),
            pos: this.manager.tooltips.map((t, i) => {
                let tv = this.manager.tooltipViews[i];
                return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos);
            }),
            size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()),
            space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view),
            scaleX, scaleY, makeAbsolute
        };
    }
    writeMeasure(measured) {
        var _a;
        if (measured.makeAbsolute) {
            this.madeAbsolute = true;
            this.position = "absolute";
            for (let t of this.manager.tooltipViews)
                t.dom.style.position = "absolute";
        }
        let { visible, space, scaleX, scaleY } = measured;
        let others = [];
        for (let i = 0; i < this.manager.tooltips.length; i++) {
            let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView;
            let pos = measured.pos[i], size = measured.size[i];
            // Hide tooltips that are outside of the editor.
            if (!pos || tooltip.clip !== false && (pos.bottom <= Math.max(visible.top, space.top) ||
                pos.top >= Math.min(visible.bottom, space.bottom) ||
                pos.right < Math.max(visible.left, space.left) - .1 ||
                pos.left > Math.min(visible.right, space.right) + .1)) {
                dom.style.top = Outside;
                continue;
            }
            let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null;
            let arrowHeight = arrow ? 7 /* Arrow.Size */ : 0;
            let width = size.right - size.left, height = (_a = knownHeight.get(tView)) !== null && _a !== void 0 ? _a : size.bottom - size.top;
            let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR;
            let left = size.width > space.right - space.left
                ? (ltr ? space.left : space.right - size.width)
                : ltr ? Math.max(space.left, Math.min(pos.left - (arrow ? 14 /* Arrow.Offset */ : 0) + offset.x, space.right - width))
                    : Math.min(Math.max(space.left, pos.left - width + (arrow ? 14 /* Arrow.Offset */ : 0) - offset.x), space.right - width);
            let above = this.above[i];
            if (!tooltip.strictSide && (above
                ? pos.top - height - arrowHeight - offset.y < space.top
                : pos.bottom + height + arrowHeight + offset.y > space.bottom) &&
                above == (space.bottom - pos.bottom > pos.top - space.top))
                above = this.above[i] = !above;
            let spaceVert = (above ? pos.top - space.top : space.bottom - pos.bottom) - arrowHeight;
            if (spaceVert < height && tView.resize !== false) {
                if (spaceVert < this.view.defaultLineHeight) {
                    dom.style.top = Outside;
                    continue;
                }
                knownHeight.set(tView, height);
                dom.style.height = (height = spaceVert) / scaleY + "px";
            }
            else if (dom.style.height) {
                dom.style.height = "";
            }
            let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y;
            let right = left + width;
            if (tView.overlap !== true)
                for (let r of others)
                    if (r.left < right && r.right > left && r.top < top + height && r.bottom > top)
                        top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2;
            if (this.position == "absolute") {
                dom.style.top = (top - measured.parent.top) / scaleY + "px";
                setLeftStyle(dom, (left - measured.parent.left) / scaleX);
            }
            else {
                dom.style.top = top / scaleY + "px";
                setLeftStyle(dom, left / scaleX);
            }
            if (arrow) {
                let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Arrow.Offset */ - 7 /* Arrow.Size */);
                arrow.style.left = arrowLeft / scaleX + "px";
            }
            if (tView.overlap !== true)
                others.push({ left, top, right, bottom: top + height });
            dom.classList.toggle("cm-tooltip-above", above);
            dom.classList.toggle("cm-tooltip-below", !above);
            if (tView.positioned)
                tView.positioned(measured.space);
        }
    }
    maybeMeasure() {
        if (this.manager.tooltips.length) {
            if (this.view.inView)
                this.view.requestMeasure(this.measureReq);
            if (this.inView != this.view.inView) {
                this.inView = this.view.inView;
                if (!this.inView)
                    for (let tv of this.manager.tooltipViews)
                        tv.dom.style.top = Outside;
            }
        }
    }
}, {
    eventObservers: {
        scroll() { this.maybeMeasure(); }
    }
});
function setLeftStyle(elt, value) {
    let current = parseInt(elt.style.left, 10);
    if (isNaN(current) || Math.abs(value - current) > 1)
        elt.style.left = value + "px";
}
const baseTheme = /*@__PURE__*/dist_EditorView.baseTheme({
    ".cm-tooltip": {
        zIndex: 500,
        boxSizing: "border-box"
    },
    "&light .cm-tooltip": {
        border: "1px solid #bbb",
        backgroundColor: "#f5f5f5"
    },
    "&light .cm-tooltip-section:not(:first-child)": {
        borderTop: "1px solid #bbb",
    },
    "&dark .cm-tooltip": {
        backgroundColor: "#333338",
        color: "white"
    },
    ".cm-tooltip-arrow": {
        height: `${7 /* Arrow.Size */}px`,
        width: `${7 /* Arrow.Size */ * 2}px`,
        position: "absolute",
        zIndex: -1,
        overflow: "hidden",
        "&:before, &:after": {
            content: "''",
            position: "absolute",
            width: 0,
            height: 0,
            borderLeft: `${7 /* Arrow.Size */}px solid transparent`,
            borderRight: `${7 /* Arrow.Size */}px solid transparent`,
        },
        ".cm-tooltip-above &": {
            bottom: `-${7 /* Arrow.Size */}px`,
            "&:before": {
                borderTop: `${7 /* Arrow.Size */}px solid #bbb`,
            },
            "&:after": {
                borderTop: `${7 /* Arrow.Size */}px solid #f5f5f5`,
                bottom: "1px"
            }
        },
        ".cm-tooltip-below &": {
            top: `-${7 /* Arrow.Size */}px`,
            "&:before": {
                borderBottom: `${7 /* Arrow.Size */}px solid #bbb`,
            },
            "&:after": {
                borderBottom: `${7 /* Arrow.Size */}px solid #f5f5f5`,
                top: "1px"
            }
        },
    },
    "&dark .cm-tooltip .cm-tooltip-arrow": {
        "&:before": {
            borderTopColor: "#333338",
            borderBottomColor: "#333338"
        },
        "&:after": {
            borderTopColor: "transparent",
            borderBottomColor: "transparent"
        }
    }
});
const noOffset = { x: 0, y: 0 };
/**
Facet to which an extension can add a value to show a tooltip.
*/
const showTooltip = /*@__PURE__*/Facet.define({
    enables: [tooltipPlugin, baseTheme]
});
const showHoverTooltip = /*@__PURE__*/Facet.define({
    combine: inputs => inputs.reduce((a, i) => a.concat(i), [])
});
class HoverTooltipHost {
    // Needs to be static so that host tooltip instances always match
    static create(view) {
        return new HoverTooltipHost(view);
    }
    constructor(view) {
        this.view = view;
        this.mounted = false;
        this.dom = document.createElement("div");
        this.dom.classList.add("cm-tooltip-hover");
        this.manager = new TooltipViewManager(view, showHoverTooltip, (t, p) => this.createHostedView(t, p), t => t.dom.remove());
    }
    createHostedView(tooltip, prev) {
        let hostedView = tooltip.create(this.view);
        hostedView.dom.classList.add("cm-tooltip-section");
        this.dom.insertBefore(hostedView.dom, prev ? prev.dom.nextSibling : this.dom.firstChild);
        if (this.mounted && hostedView.mount)
            hostedView.mount(this.view);
        return hostedView;
    }
    mount(view) {
        for (let hostedView of this.manager.tooltipViews) {
            if (hostedView.mount)
                hostedView.mount(view);
        }
        this.mounted = true;
    }
    positioned(space) {
        for (let hostedView of this.manager.tooltipViews) {
            if (hostedView.positioned)
                hostedView.positioned(space);
        }
    }
    update(update) {
        this.manager.update(update);
    }
    destroy() {
        var _a;
        for (let t of this.manager.tooltipViews)
            (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);
    }
    passProp(name) {
        let value = undefined;
        for (let view of this.manager.tooltipViews) {
            let given = view[name];
            if (given !== undefined) {
                if (value === undefined)
                    value = given;
                else if (value !== given)
                    return undefined;
            }
        }
        return value;
    }
    get offset() { return this.passProp("offset"); }
    get getCoords() { return this.passProp("getCoords"); }
    get overlap() { return this.passProp("overlap"); }
    get resize() { return this.passProp("resize"); }
}
const showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => {
    let tooltips = state.facet(showHoverTooltip);
    if (tooltips.length === 0)
        return null;
    return {
        pos: Math.min(...tooltips.map(t => t.pos)),
        end: Math.max(...tooltips.map(t => { var _a; return (_a = t.end) !== null && _a !== void 0 ? _a : t.pos; })),
        create: HoverTooltipHost.create,
        above: tooltips[0].above,
        arrow: tooltips.some(t => t.arrow),
    };
});
class HoverPlugin {
    constructor(view, source, field, setHover, hoverTime) {
        this.view = view;
        this.source = source;
        this.field = field;
        this.setHover = setHover;
        this.hoverTime = hoverTime;
        this.hoverTimeout = -1;
        this.restartTimeout = -1;
        this.pending = null;
        this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 };
        this.checkHover = this.checkHover.bind(this);
        view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this));
        view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this));
    }
    update() {
        if (this.pending) {
            this.pending = null;
            clearTimeout(this.restartTimeout);
            this.restartTimeout = setTimeout(() => this.startHover(), 20);
        }
    }
    get active() {
        return this.view.state.field(this.field);
    }
    checkHover() {
        this.hoverTimeout = -1;
        if (this.active.length)
            return;
        let hovered = Date.now() - this.lastMove.time;
        if (hovered < this.hoverTime)
            this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered);
        else
            this.startHover();
    }
    startHover() {
        clearTimeout(this.restartTimeout);
        let { view, lastMove } = this;
        let tile = view.docView.tile.nearest(lastMove.target);
        if (!tile)
            return;
        let pos, side = 1;
        if (tile.isWidget()) {
            pos = tile.posAtStart;
        }
        else {
            pos = view.posAtCoords(lastMove);
            if (pos == null)
                return;
            let posCoords = view.coordsAtPos(pos);
            if (!posCoords ||
                lastMove.y < posCoords.top || lastMove.y > posCoords.bottom ||
                lastMove.x < posCoords.left - view.defaultCharacterWidth ||
                lastMove.x > posCoords.right + view.defaultCharacterWidth)
                return;
            let bidi = view.bidiSpans(view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos);
            let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1;
            side = (lastMove.x < posCoords.left ? -rtl : rtl);
        }
        let open = this.source(view, pos, side);
        if (open === null || open === void 0 ? void 0 : open.then) {
            let pending = this.pending = { pos };
            open.then(result => {
                if (this.pending == pending) {
                    this.pending = null;
                    if (result && !(Array.isArray(result) && !result.length))
                        view.dispatch({ effects: this.setHover.of(Array.isArray(result) ? result : [result]) });
                }
            }, e => logException(view.state, e, "hover tooltip"));
        }
        else if (open && !(Array.isArray(open) && !open.length)) {
            view.dispatch({ effects: this.setHover.of(Array.isArray(open) ? open : [open]) });
        }
    }
    get tooltip() {
        let plugin = this.view.plugin(tooltipPlugin);
        let index = plugin ? plugin.manager.tooltips.findIndex(t => t.create == HoverTooltipHost.create) : -1;
        return index > -1 ? plugin.manager.tooltipViews[index] : null;
    }
    mousemove(event) {
        var _a, _b;
        this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() };
        if (this.hoverTimeout < 0)
            this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime);
        let { active, tooltip } = this;
        if (active.length && tooltip && !isInTooltip(tooltip.dom, event) || this.pending) {
            let { pos } = active[0] || this.pending, end = (_b = (_a = active[0]) === null || _a === void 0 ? void 0 : _a.end) !== null && _b !== void 0 ? _b : pos;
            if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos
                : !isOverRange(this.view, pos, end, event.clientX, event.clientY))) {
                this.view.dispatch({ effects: this.setHover.of([]) });
                this.pending = null;
            }
        }
    }
    mouseleave(event) {
        clearTimeout(this.hoverTimeout);
        this.hoverTimeout = -1;
        let { active } = this;
        if (active.length) {
            let { tooltip } = this;
            let inTooltip = tooltip && tooltip.dom.contains(event.relatedTarget);
            if (!inTooltip)
                this.view.dispatch({ effects: this.setHover.of([]) });
            else
                this.watchTooltipLeave(tooltip.dom);
        }
    }
    watchTooltipLeave(tooltip) {
        let watch = (event) => {
            tooltip.removeEventListener("mouseleave", watch);
            if (this.active.length && !this.view.dom.contains(event.relatedTarget))
                this.view.dispatch({ effects: this.setHover.of([]) });
        };
        tooltip.addEventListener("mouseleave", watch);
    }
    destroy() {
        clearTimeout(this.hoverTimeout);
        clearTimeout(this.restartTimeout);
        this.view.dom.removeEventListener("mouseleave", this.mouseleave);
        this.view.dom.removeEventListener("mousemove", this.mousemove);
    }
}
const tooltipMargin = 4;
function isInTooltip(tooltip, event) {
    let { left, right, top, bottom } = tooltip.getBoundingClientRect(), arrow;
    if (arrow = tooltip.querySelector(".cm-tooltip-arrow")) {
        let arrowRect = arrow.getBoundingClientRect();
        top = Math.min(arrowRect.top, top);
        bottom = Math.max(arrowRect.bottom, bottom);
    }
    return event.clientX >= left - tooltipMargin && event.clientX <= right + tooltipMargin &&
        event.clientY >= top - tooltipMargin && event.clientY <= bottom + tooltipMargin;
}
function isOverRange(view, from, to, x, y, margin) {
    let rect = view.scrollDOM.getBoundingClientRect();
    let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;
    if (rect.left > x || rect.right < x || rect.top > y || Math.min(rect.bottom, docBottom) < y)
        return false;
    let pos = view.posAtCoords({ x, y }, false);
    return pos >= from && pos <= to;
}
/**
Set up a hover tooltip, which shows up when the pointer hovers
over ranges of text. The callback is called when the mouse hovers
over the document text. It should, if there is a tooltip
associated with position `pos`, return the tooltip description
(either directly or in a promise). The `side` argument indicates
on which side of the position the pointer is—it will be -1 if the
pointer is before the position, 1 if after the position.

Note that all hover tooltips are hosted within a single tooltip
container element. This allows multiple tooltips over the same
range to be "merged" together without overlapping.

The return value is a valid [editor extension](https://codemirror.net/6/docs/ref/#state.Extension)
but also provides an `active` property holding a state field that
can be used to read the currently active tooltips produced by this
extension.
*/
function hoverTooltip(source, options = {}) {
    let setHover = StateEffect.define();
    let hoverState = StateField.define({
        create() { return []; },
        update(value, tr) {
            if (value.length) {
                if (options.hideOnChange && (tr.docChanged || tr.selection))
                    value = [];
                else if (options.hideOn)
                    value = value.filter(v => !options.hideOn(tr, v));
                if (tr.docChanged) {
                    let mapped = [];
                    for (let tooltip of value) {
                        let newPos = tr.changes.mapPos(tooltip.pos, -1, MapMode.TrackDel);
                        if (newPos != null) {
                            let copy = Object.assign(Object.create(null), tooltip);
                            copy.pos = newPos;
                            if (copy.end != null)
                                copy.end = tr.changes.mapPos(copy.end);
                            mapped.push(copy);
                        }
                    }
                    value = mapped;
                }
            }
            for (let effect of tr.effects) {
                if (effect.is(setHover))
                    value = effect.value;
                if (effect.is(closeHoverTooltipEffect))
                    value = [];
            }
            return value;
        },
        provide: f => showHoverTooltip.from(f)
    });
    return {
        active: hoverState,
        extension: [
            hoverState,
            dist_ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Hover.Time */)),
            showHoverTooltipHost
        ]
    };
}
/**
Get the active tooltip view for a given tooltip, if available.
*/
function getTooltip(view, tooltip) {
    let plugin = view.plugin(tooltipPlugin);
    if (!plugin)
        return null;
    let found = plugin.manager.tooltips.indexOf(tooltip);
    return found < 0 ? null : plugin.manager.tooltipViews[found];
}
/**
Returns true if any hover tooltips are currently active.
*/
function hasHoverTooltips(state) {
    return state.facet(showHoverTooltip).some(x => x);
}
const closeHoverTooltipEffect = /*@__PURE__*/(/* unused pure expression or super */ null && (StateEffect.define()));
/**
Transaction effect that closes all hover tooltips.
*/
const closeHoverTooltips = /*@__PURE__*/(/* unused pure expression or super */ null && (closeHoverTooltipEffect.of(null)));
/**
Tell the tooltip extension to recompute the position of the active
tooltips. This can be useful when something happens (such as a
re-positioning or CSS change affecting the editor) that could
invalidate the existing tooltip positions.
*/
function repositionTooltips(view) {
    let plugin = view.plugin(tooltipPlugin);
    if (plugin)
        plugin.maybeMeasure();
}

const panelConfig = /*@__PURE__*/Facet.define({
    combine(configs) {
        let topContainer, bottomContainer;
        for (let c of configs) {
            topContainer = topContainer || c.topContainer;
            bottomContainer = bottomContainer || c.bottomContainer;
        }
        return { topContainer, bottomContainer };
    }
});
/**
Configures the panel-managing extension.
*/
function panels(config) {
    return config ? [panelConfig.of(config)] : [];
}
/**
Get the active panel created by the given constructor, if any.
This can be useful when you need access to your panels' DOM
structure.
*/
function getPanel(view, panel) {
    let plugin = view.plugin(panelPlugin);
    let index = plugin ? plugin.specs.indexOf(panel) : -1;
    return index > -1 ? plugin.panels[index] : null;
}
const panelPlugin = /*@__PURE__*/dist_ViewPlugin.fromClass(class {
    constructor(view) {
        this.input = view.state.facet(showPanel);
        this.specs = this.input.filter(s => s);
        this.panels = this.specs.map(spec => spec(view));
        let conf = view.state.facet(panelConfig);
        this.top = new PanelGroup(view, true, conf.topContainer);
        this.bottom = new PanelGroup(view, false, conf.bottomContainer);
        this.top.sync(this.panels.filter(p => p.top));
        this.bottom.sync(this.panels.filter(p => !p.top));
        for (let p of this.panels) {
            p.dom.classList.add("cm-panel");
            if (p.mount)
                p.mount();
        }
    }
    update(update) {
        let conf = update.state.facet(panelConfig);
        if (this.top.container != conf.topContainer) {
            this.top.sync([]);
            this.top = new PanelGroup(update.view, true, conf.topContainer);
        }
        if (this.bottom.container != conf.bottomContainer) {
            this.bottom.sync([]);
            this.bottom = new PanelGroup(update.view, false, conf.bottomContainer);
        }
        this.top.syncClasses();
        this.bottom.syncClasses();
        let input = update.state.facet(showPanel);
        if (input != this.input) {
            let specs = input.filter(x => x);
            let panels = [], top = [], bottom = [], mount = [];
            for (let spec of specs) {
                let known = this.specs.indexOf(spec), panel;
                if (known < 0) {
                    panel = spec(update.view);
                    mount.push(panel);
                }
                else {
                    panel = this.panels[known];
                    if (panel.update)
                        panel.update(update);
                }
                panels.push(panel);
                (panel.top ? top : bottom).push(panel);
            }
            this.specs = specs;
            this.panels = panels;
            this.top.sync(top);
            this.bottom.sync(bottom);
            for (let p of mount) {
                p.dom.classList.add("cm-panel");
                if (p.mount)
                    p.mount();
            }
        }
        else {
            for (let p of this.panels)
                if (p.update)
                    p.update(update);
        }
    }
    destroy() {
        this.top.sync([]);
        this.bottom.sync([]);
    }
}, {
    provide: plugin => dist_EditorView.scrollMargins.of(view => {
        let value = view.plugin(plugin);
        return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() };
    })
});
class PanelGroup {
    constructor(view, top, container) {
        this.view = view;
        this.top = top;
        this.container = container;
        this.dom = undefined;
        this.classes = "";
        this.panels = [];
        this.syncClasses();
    }
    sync(panels) {
        for (let p of this.panels)
            if (p.destroy && panels.indexOf(p) < 0)
                p.destroy();
        this.panels = panels;
        this.syncDOM();
    }
    syncDOM() {
        if (this.panels.length == 0) {
            if (this.dom) {
                this.dom.remove();
                this.dom = undefined;
            }
            return;
        }
        if (!this.dom) {
            this.dom = document.createElement("div");
            this.dom.className = this.top ? "cm-panels cm-panels-top" : "cm-panels cm-panels-bottom";
            this.dom.style[this.top ? "top" : "bottom"] = "0";
            let parent = this.container || this.view.dom;
            parent.insertBefore(this.dom, this.top ? parent.firstChild : null);
        }
        let curDOM = this.dom.firstChild;
        for (let panel of this.panels) {
            if (panel.dom.parentNode == this.dom) {
                while (curDOM != panel.dom)
                    curDOM = rm(curDOM);
                curDOM = curDOM.nextSibling;
            }
            else {
                this.dom.insertBefore(panel.dom, curDOM);
            }
        }
        while (curDOM)
            curDOM = rm(curDOM);
    }
    scrollMargin() {
        return !this.dom || this.container ? 0
            : Math.max(0, this.top ?
                this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) :
                Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top);
    }
    syncClasses() {
        if (!this.container || this.classes == this.view.themeClasses)
            return;
        for (let cls of this.classes.split(" "))
            if (cls)
                this.container.classList.remove(cls);
        for (let cls of (this.classes = this.view.themeClasses).split(" "))
            if (cls)
                this.container.classList.add(cls);
    }
}
function rm(node) {
    let next = node.nextSibling;
    node.remove();
    return next;
}
/**
Opening a panel is done by providing a constructor function for
the panel through this facet. (The panel is closed again when its
constructor is no longer provided.) Values of `null` are ignored.
*/
const showPanel = /*@__PURE__*/Facet.define({
    enables: panelPlugin
});

/**
Show a panel above or below the editor to show the user a message
or prompt them for input. Returns an effect that can be dispatched
to close the dialog, and a promise that resolves when the dialog
is closed or a form inside of it is submitted.

You are encouraged, if your handling of the result of the promise
dispatches a transaction, to include the `close` effect in it. If
you don't, this function will automatically dispatch a separate
transaction right after.
*/
function showDialog(view, config) {
    let resolve;
    let promise = new Promise(r => resolve = r);
    let panelCtor = (view) => createDialog(view, config, resolve);
    if (view.state.field(dialogField, false)) {
        view.dispatch({ effects: openDialogEffect.of(panelCtor) });
    }
    else {
        view.dispatch({ effects: StateEffect.appendConfig.of(dialogField.init(() => [panelCtor])) });
    }
    let close = closeDialogEffect.of(panelCtor);
    return { close, result: promise.then(form => {
            let queue = view.win.queueMicrotask || ((f) => view.win.setTimeout(f, 10));
            queue(() => {
                if (view.state.field(dialogField).indexOf(panelCtor) > -1)
                    view.dispatch({ effects: close });
            });
            return form;
        }) };
}
/**
Find the [`Panel`](https://codemirror.net/6/docs/ref/#view.Panel) for an open dialog, using a class
name as identifier.
*/
function getDialog(view, className) {
    let dialogs = view.state.field(dialogField, false) || [];
    for (let open of dialogs) {
        let panel = getPanel(view, open);
        if (panel && panel.dom.classList.contains(className))
            return panel;
    }
    return null;
}
const dialogField = /*@__PURE__*/dist_StateField.define({
    create() { return []; },
    update(dialogs, tr) {
        for (let e of tr.effects) {
            if (e.is(openDialogEffect))
                dialogs = [e.value].concat(dialogs);
            else if (e.is(closeDialogEffect))
                dialogs = dialogs.filter(d => d != e.value);
        }
        return dialogs;
    },
    provide: f => showPanel.computeN([f], state => state.field(f))
});
const openDialogEffect = /*@__PURE__*/dist_StateEffect.define();
const closeDialogEffect = /*@__PURE__*/dist_StateEffect.define();
function createDialog(view, config, result) {
    let content = config.content ? config.content(view, () => done(null)) : null;
    if (!content) {
        content = elt("form");
        if (config.input) {
            let input = elt("input", config.input);
            if (/^(text|password|number|email|tel|url)$/.test(input.type))
                input.classList.add("cm-textfield");
            if (!input.name)
                input.name = "input";
            content.appendChild(elt("label", (config.label || "") + ": ", input));
        }
        else {
            content.appendChild(document.createTextNode(config.label || ""));
        }
        content.appendChild(document.createTextNode(" "));
        content.appendChild(elt("button", { class: "cm-button", type: "submit" }, config.submitLabel || "OK"));
    }
    let forms = content.nodeName == "FORM" ? [content] : content.querySelectorAll("form");
    for (let i = 0; i < forms.length; i++) {
        let form = forms[i];
        form.addEventListener("keydown", (event) => {
            if (event.keyCode == 27) { // Escape
                event.preventDefault();
                done(null);
            }
            else if (event.keyCode == 13) { // Enter
                event.preventDefault();
                done(form);
            }
        });
        form.addEventListener("submit", (event) => {
            event.preventDefault();
            done(form);
        });
    }
    let panel = elt("div", content, elt("button", {
        onclick: () => done(null),
        "aria-label": view.state.phrase("close"),
        class: "cm-dialog-close",
        type: "button"
    }, ["×"]));
    if (config.class)
        panel.className = config.class;
    panel.classList.add("cm-dialog");
    function done(form) {
        if (panel.contains(panel.ownerDocument.activeElement))
            view.focus();
        result(form);
    }
    return {
        dom: panel,
        top: config.top,
        mount: () => {
            if (config.focus) {
                let focus;
                if (typeof config.focus == "string")
                    focus = content.querySelector(config.focus);
                else
                    focus = content.querySelector("input") || content.querySelector("button");
                if (focus && "select" in focus)
                    focus.select();
                else if (focus && "focus" in focus)
                    focus.focus();
            }
        }
    };
}

/**
A gutter marker represents a bit of information attached to a line
in a specific gutter. Your own custom markers have to extend this
class.
*/
class GutterMarker extends RangeValue {
    /**
    @internal
    */
    compare(other) {
        return this == other || this.constructor == other.constructor && this.eq(other);
    }
    /**
    Compare this marker to another marker of the same type.
    */
    eq(other) { return false; }
    /**
    Called if the marker has a `toDOM` method and its representation
    was removed from a gutter.
    */
    destroy(dom) { }
}
GutterMarker.prototype.elementClass = "";
GutterMarker.prototype.toDOM = undefined;
GutterMarker.prototype.mapMode = dist_MapMode.TrackBefore;
GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1;
GutterMarker.prototype.point = true;
/**
Facet used to add a class to all gutter elements for a given line.
Markers given to this facet should _only_ define an
[`elementclass`](https://codemirror.net/6/docs/ref/#view.GutterMarker.elementClass), not a
[`toDOM`](https://codemirror.net/6/docs/ref/#view.GutterMarker.toDOM) (or the marker will appear
in all gutters for the line).
*/
const gutterLineClass = /*@__PURE__*/Facet.define();
/**
Facet used to add a class to all gutter elements next to a widget.
Should not provide widgets with a `toDOM` method.
*/
const gutterWidgetClass = /*@__PURE__*/Facet.define();
const defaults = {
    class: "",
    renderEmptyElements: false,
    elementStyle: "",
    markers: () => dist_RangeSet.empty,
    lineMarker: () => null,
    widgetMarker: () => null,
    lineMarkerChange: null,
    initialSpacer: null,
    updateSpacer: null,
    domEventHandlers: {},
    side: "before"
};
const activeGutters = /*@__PURE__*/Facet.define();
/**
Define an editor gutter. The order in which the gutters appear is
determined by their extension priority.
*/
function gutter(config) {
    return [gutters(), activeGutters.of({ ...defaults, ...config })];
}
const unfixGutters = /*@__PURE__*/Facet.define({
    combine: values => values.some(x => x)
});
/**
The gutter-drawing plugin is automatically enabled when you add a
gutter, but you can use this function to explicitly configure it.

Unless `fixed` is explicitly set to `false`, the gutters are
fixed, meaning they don't scroll along with the content
horizontally (except on Internet Explorer, which doesn't support
CSS [`position:
sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)).
*/
function gutters(config) {
    let result = [
        gutterView,
    ];
    if (config && config.fixed === false)
        result.push(unfixGutters.of(true));
    return result;
}
const gutterView = /*@__PURE__*/dist_ViewPlugin.fromClass(class {
    constructor(view) {
        this.view = view;
        this.domAfter = null;
        this.prevViewport = view.viewport;
        this.dom = document.createElement("div");
        this.dom.className = "cm-gutters cm-gutters-before";
        this.dom.setAttribute("aria-hidden", "true");
        this.dom.style.minHeight = (this.view.contentHeight / this.view.scaleY) + "px";
        this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf));
        this.fixed = !view.state.facet(unfixGutters);
        for (let gutter of this.gutters) {
            if (gutter.config.side == "after")
                this.getDOMAfter().appendChild(gutter.dom);
            else
                this.dom.appendChild(gutter.dom);
        }
        if (this.fixed) {
            // FIXME IE11 fallback, which doesn't support position: sticky,
            // by using position: relative + event handlers that realign the
            // gutter (or just force fixed=false on IE11?)
            this.dom.style.position = "sticky";
        }
        this.syncGutters(false);
        view.scrollDOM.insertBefore(this.dom, view.contentDOM);
    }
    getDOMAfter() {
        if (!this.domAfter) {
            this.domAfter = document.createElement("div");
            this.domAfter.className = "cm-gutters cm-gutters-after";
            this.domAfter.setAttribute("aria-hidden", "true");
            this.domAfter.style.minHeight = (this.view.contentHeight / this.view.scaleY) + "px";
            this.domAfter.style.position = this.fixed ? "sticky" : "";
            this.view.scrollDOM.appendChild(this.domAfter);
        }
        return this.domAfter;
    }
    update(update) {
        if (this.updateGutters(update)) {
            // Detach during sync when the viewport changed significantly
            // (such as during scrolling), since for large updates that is
            // faster.
            let vpA = this.prevViewport, vpB = update.view.viewport;
            let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from);
            this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8);
        }
        if (update.geometryChanged) {
            let min = (this.view.contentHeight / this.view.scaleY) + "px";
            this.dom.style.minHeight = min;
            if (this.domAfter)
                this.domAfter.style.minHeight = min;
        }
        if (this.view.state.facet(unfixGutters) != !this.fixed) {
            this.fixed = !this.fixed;
            this.dom.style.position = this.fixed ? "sticky" : "";
            if (this.domAfter)
                this.domAfter.style.position = this.fixed ? "sticky" : "";
        }
        this.prevViewport = update.view.viewport;
    }
    syncGutters(detach) {
        let after = this.dom.nextSibling;
        if (detach) {
            this.dom.remove();
            if (this.domAfter)
                this.domAfter.remove();
        }
        let lineClasses = dist_RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from);
        let classSet = [];
        let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top));
        for (let line of this.view.viewportLineBlocks) {
            if (classSet.length)
                classSet = [];
            if (Array.isArray(line.type)) {
                let first = true;
                for (let b of line.type) {
                    if (b.type == BlockType.Text && first) {
                        advanceCursor(lineClasses, classSet, b.from);
                        for (let cx of contexts)
                            cx.line(this.view, b, classSet);
                        first = false;
                    }
                    else if (b.widget) {
                        for (let cx of contexts)
                            cx.widget(this.view, b);
                    }
                }
            }
            else if (line.type == BlockType.Text) {
                advanceCursor(lineClasses, classSet, line.from);
                for (let cx of contexts)
                    cx.line(this.view, line, classSet);
            }
            else if (line.widget) {
                for (let cx of contexts)
                    cx.widget(this.view, line);
            }
        }
        for (let cx of contexts)
            cx.finish();
        if (detach) {
            this.view.scrollDOM.insertBefore(this.dom, after);
            if (this.domAfter)
                this.view.scrollDOM.appendChild(this.domAfter);
        }
    }
    updateGutters(update) {
        let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters);
        let change = update.docChanged || update.heightChanged || update.viewportChanged ||
            !dist_RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to);
        if (prev == cur) {
            for (let gutter of this.gutters)
                if (gutter.update(update))
                    change = true;
        }
        else {
            change = true;
            let gutters = [];
            for (let conf of cur) {
                let known = prev.indexOf(conf);
                if (known < 0) {
                    gutters.push(new SingleGutterView(this.view, conf));
                }
                else {
                    this.gutters[known].update(update);
                    gutters.push(this.gutters[known]);
                }
            }
            for (let g of this.gutters) {
                g.dom.remove();
                if (gutters.indexOf(g) < 0)
                    g.destroy();
            }
            for (let g of gutters) {
                if (g.config.side == "after")
                    this.getDOMAfter().appendChild(g.dom);
                else
                    this.dom.appendChild(g.dom);
            }
            this.gutters = gutters;
        }
        return change;
    }
    destroy() {
        for (let view of this.gutters)
            view.destroy();
        this.dom.remove();
        if (this.domAfter)
            this.domAfter.remove();
    }
}, {
    provide: plugin => dist_EditorView.scrollMargins.of(view => {
        let value = view.plugin(plugin);
        if (!value || value.gutters.length == 0 || !value.fixed)
            return null;
        let before = value.dom.offsetWidth * view.scaleX, after = value.domAfter ? value.domAfter.offsetWidth * view.scaleX : 0;
        return view.textDirection == Direction.LTR
            ? { left: before, right: after }
            : { right: before, left: after };
    })
});
function dist_asArray(val) { return (Array.isArray(val) ? val : [val]); }
function advanceCursor(cursor, collect, pos) {
    while (cursor.value && cursor.from <= pos) {
        if (cursor.from == pos)
            collect.push(cursor.value);
        cursor.next();
    }
}
class UpdateContext {
    constructor(gutter, viewport, height) {
        this.gutter = gutter;
        this.height = height;
        this.i = 0;
        this.cursor = dist_RangeSet.iter(gutter.markers, viewport.from);
    }
    addElement(view, block, markers) {
        let { gutter } = this, above = (block.top - this.height) / view.scaleY, height = block.height / view.scaleY;
        if (this.i == gutter.elements.length) {
            let newElt = new GutterElement(view, height, above, markers);
            gutter.elements.push(newElt);
            gutter.dom.appendChild(newElt.dom);
        }
        else {
            gutter.elements[this.i].update(view, height, above, markers);
        }
        this.height = block.bottom;
        this.i++;
    }
    line(view, line, extraMarkers) {
        let localMarkers = [];
        advanceCursor(this.cursor, localMarkers, line.from);
        if (extraMarkers.length)
            localMarkers = localMarkers.concat(extraMarkers);
        let forLine = this.gutter.config.lineMarker(view, line, localMarkers);
        if (forLine)
            localMarkers.unshift(forLine);
        let gutter = this.gutter;
        if (localMarkers.length == 0 && !gutter.config.renderEmptyElements)
            return;
        this.addElement(view, line, localMarkers);
    }
    widget(view, block) {
        let marker = this.gutter.config.widgetMarker(view, block.widget, block), markers = marker ? [marker] : null;
        for (let cls of view.state.facet(gutterWidgetClass)) {
            let marker = cls(view, block.widget, block);
            if (marker)
                (markers || (markers = [])).push(marker);
        }
        if (markers)
            this.addElement(view, block, markers);
    }
    finish() {
        let gutter = this.gutter;
        while (gutter.elements.length > this.i) {
            let last = gutter.elements.pop();
            gutter.dom.removeChild(last.dom);
            last.destroy();
        }
    }
}
class SingleGutterView {
    constructor(view, config) {
        this.view = view;
        this.config = config;
        this.elements = [];
        this.spacer = null;
        this.dom = document.createElement("div");
        this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : "");
        for (let prop in config.domEventHandlers) {
            this.dom.addEventListener(prop, (event) => {
                let target = event.target, y;
                if (target != this.dom && this.dom.contains(target)) {
                    while (target.parentNode != this.dom)
                        target = target.parentNode;
                    let rect = target.getBoundingClientRect();
                    y = (rect.top + rect.bottom) / 2;
                }
                else {
                    y = event.clientY;
                }
                let line = view.lineBlockAtHeight(y - view.documentTop);
                if (config.domEventHandlers[prop](view, line, event))
                    event.preventDefault();
            });
        }
        this.markers = dist_asArray(config.markers(view));
        if (config.initialSpacer) {
            this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]);
            this.dom.appendChild(this.spacer.dom);
            this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none";
        }
    }
    update(update) {
        let prevMarkers = this.markers;
        this.markers = dist_asArray(this.config.markers(update.view));
        if (this.spacer && this.config.updateSpacer) {
            let updated = this.config.updateSpacer(this.spacer.markers[0], update);
            if (updated != this.spacer.markers[0])
                this.spacer.update(update.view, 0, 0, [updated]);
        }
        let vp = update.view.viewport;
        return !dist_RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) ||
            (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false);
    }
    destroy() {
        for (let elt of this.elements)
            elt.destroy();
    }
}
class GutterElement {
    constructor(view, height, above, markers) {
        this.height = -1;
        this.above = 0;
        this.markers = [];
        this.dom = document.createElement("div");
        this.dom.className = "cm-gutterElement";
        this.update(view, height, above, markers);
    }
    update(view, height, above, markers) {
        if (this.height != height) {
            this.height = height;
            this.dom.style.height = height + "px";
        }
        if (this.above != above)
            this.dom.style.marginTop = (this.above = above) ? above + "px" : "";
        if (!sameMarkers(this.markers, markers))
            this.setMarkers(view, markers);
    }
    setMarkers(view, markers) {
        let cls = "cm-gutterElement", domPos = this.dom.firstChild;
        for (let iNew = 0, iOld = 0;;) {
            let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false;
            if (marker) {
                let c = marker.elementClass;
                if (c)
                    cls += " " + c;
                for (let i = iOld; i < this.markers.length; i++)
                    if (this.markers[i].compare(marker)) {
                        skipTo = i;
                        matched = true;
                        break;
                    }
            }
            else {
                skipTo = this.markers.length;
            }
            while (iOld < skipTo) {
                let next = this.markers[iOld++];
                if (next.toDOM) {
                    next.destroy(domPos);
                    let after = domPos.nextSibling;
                    domPos.remove();
                    domPos = after;
                }
            }
            if (!marker)
                break;
            if (marker.toDOM) {
                if (matched)
                    domPos = domPos.nextSibling;
                else
                    this.dom.insertBefore(marker.toDOM(view), domPos);
            }
            if (matched)
                iOld++;
        }
        this.dom.className = cls;
        this.markers = markers;
    }
    destroy() {
        this.setMarkers(null, []); // First argument not used unless creating markers
    }
}
function sameMarkers(a, b) {
    if (a.length != b.length)
        return false;
    for (let i = 0; i < a.length; i++)
        if (!a[i].compare(b[i]))
            return false;
    return true;
}
/**
Facet used to provide markers to the line number gutter.
*/
const lineNumberMarkers = /*@__PURE__*/Facet.define();
/**
Facet used to create markers in the line number gutter next to widgets.
*/
const lineNumberWidgetMarker = /*@__PURE__*/Facet.define();
const lineNumberConfig = /*@__PURE__*/Facet.define({
    combine(values) {
        return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, {
            domEventHandlers(a, b) {
                let result = Object.assign({}, a);
                for (let event in b) {
                    let exists = result[event], add = b[event];
                    result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add;
                }
                return result;
            }
        });
    }
});
class NumberMarker extends GutterMarker {
    constructor(number) {
        super();
        this.number = number;
    }
    eq(other) { return this.number == other.number; }
    toDOM() { return document.createTextNode(this.number); }
}
function formatNumber(view, number) {
    return view.state.facet(lineNumberConfig).formatNumber(number, view.state);
}
const lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({
    class: "cm-lineNumbers",
    renderEmptyElements: false,
    markers(view) { return view.state.facet(lineNumberMarkers); },
    lineMarker(view, line, others) {
        if (others.some(m => m.toDOM))
            return null;
        return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number));
    },
    widgetMarker: (view, widget, block) => {
        for (let m of view.state.facet(lineNumberWidgetMarker)) {
            let result = m(view, widget, block);
            if (result)
                return result;
        }
        return null;
    },
    lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig),
    initialSpacer(view) {
        return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines)));
    },
    updateSpacer(spacer, update) {
        let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines));
        return max == spacer.number ? spacer : new NumberMarker(max);
    },
    domEventHandlers: state.facet(lineNumberConfig).domEventHandlers,
    side: "before"
}));
/**
Create a line number gutter extension.
*/
function lineNumbers(config = {}) {
    return [
        lineNumberConfig.of(config),
        gutters(),
        lineNumberGutter
    ];
}
function maxLineNumber(lines) {
    let last = 9;
    while (last < lines)
        last = last * 10 + 9;
    return last;
}
const activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker {
    constructor() {
        super(...arguments);
        this.elementClass = "cm-activeLineGutter";
    }
};
const activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute(["selection"], state => {
    let marks = [], last = -1;
    for (let range of state.selection.ranges) {
        let linePos = state.doc.lineAt(range.head).from;
        if (linePos > last) {
            last = linePos;
            marks.push(activeLineGutterMarker.range(linePos));
        }
    }
    return dist_RangeSet.of(marks);
});
/**
Returns an extension that adds a `cm-activeLineGutter` class to
all gutter elements on the [active
line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine).
*/
function highlightActiveLineGutter() {
    return activeLineGutterHighlighter;
}

function matcher(decorator) {
    return dist_ViewPlugin.define(view => ({
        decorations: decorator.createDeco(view),
        update(u) {
            this.decorations = decorator.updateDeco(u, this.decorations);
        },
    }), {
        decorations: v => v.decorations
    });
}
const tabDeco = /*@__PURE__*/dist_Decoration.mark({ class: "cm-highlightTab" });
const spaceDeco = /*@__PURE__*/dist_Decoration.mark({ class: "cm-highlightSpace" });
const whitespaceHighlighter = /*@__PURE__*/matcher(/*@__PURE__*/new MatchDecorator({
    regexp: /\t| /g,
    decoration: match => match[0] == "\t" ? tabDeco : spaceDeco,
    boundary: /\S/,
}));
/**
Returns an extension that highlights whitespace, adding a
`cm-highlightSpace` class to stretches of spaces, and a
`cm-highlightTab` class to individual tab characters. By default,
the former are shown as faint dots, and the latter as arrows.
*/
function highlightWhitespace() {
    return whitespaceHighlighter;
}
const trailingHighlighter = /*@__PURE__*/matcher(/*@__PURE__*/new MatchDecorator({
    regexp: /\s+$/g,
    decoration: /*@__PURE__*/dist_Decoration.mark({ class: "cm-trailingSpace" })
}));
/**
Returns an extension that adds a `cm-trailingSpace` class to all
trailing whitespace.
*/
function highlightTrailingWhitespace() {
    return trailingHighlighter;
}

/**
@internal
*/
const __test = { HeightMap, HeightOracle, MeasuredHeights, QueryType, ChangedRange, computeOrder,
    moveVisually, clearHeightChangeFlag, getHeightChangeFlag: () => heightChangeFlag };



// EXTERNAL MODULE: ./src/editor/src/hooks/useDragHandler.ts
var useDragHandler = __webpack_require__(34676);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/toolbar/ToolbarGrip/index.ts + 2 modules
var ToolbarGrip = __webpack_require__(61211);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryButton.module.scss
var CodeHistoryButton_module = __webpack_require__(76010);
;// ../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryButton.module.scss

      
      
      
      
      
      
      
      
      

var CodeHistoryButton_module_options = {};

CodeHistoryButton_module_options.styleTagTransform = (styleTagTransform_default());
CodeHistoryButton_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      CodeHistoryButton_module_options.insert = insertBySelector_default().bind(null, "head");
    
CodeHistoryButton_module_options.domAPI = (styleDomAPI_default());
CodeHistoryButton_module_options.insertStyleElement = (insertStyleElement_default());

var CodeHistoryButton_module_update = injectStylesIntoStyleTag_default()(CodeHistoryButton_module/* default */.A, CodeHistoryButton_module_options);




       /* harmony default export */ const CodeHistory_CodeHistoryButton_module = (CodeHistoryButton_module/* default */.A && CodeHistoryButton_module/* default */.A.locals ? CodeHistoryButton_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/code-editor/utils/codeDiff.ts
/**
 * Code Diff Utilities
 *
 * Computes line-based diffs between code snippets for history visualization.
 * Uses a simplified Myers diff algorithm.
 *
 * @module code-editor/utils
 */
/**
 * Compute a diff between two code snippets
 */
function computeDiff(oldCode, newCode) {
    const oldLines = oldCode.split('\n');
    const newLines = newCode.split('\n');
    const diff = simpleDiff(oldLines, newLines);
    return {
        lines: diff,
        additions: diff.filter((l) => l.type === 'added').length,
        deletions: diff.filter((l) => l.type === 'removed').length,
        modifications: diff.filter((l) => l.type === 'modified').length
    };
}
/**
 * Get a human-readable summary of changes
 */
function getDiffSummary(diff) {
    const { additions, deletions, modifications } = diff;
    let description = '';
    const parts = [];
    if (additions > 0) {
        parts.push(`+${additions} line${additions === 1 ? '' : 's'}`);
    }
    if (deletions > 0) {
        parts.push(`-${deletions} line${deletions === 1 ? '' : 's'}`);
    }
    if (modifications > 0) {
        parts.push(`~${modifications} modified`);
    }
    if (parts.length === 0) {
        description = 'No changes';
    }
    else if (additions + deletions + modifications > 10) {
        description = 'Major refactor';
    }
    else if (modifications > additions && modifications > deletions) {
        description = 'Modified: ' + parts.join(', ');
    }
    else {
        description = 'Changed: ' + parts.join(', ');
    }
    return {
        additions,
        deletions,
        modifications,
        description
    };
}
/**
 * Simplified diff algorithm
 * Uses Longest Common Subsequence (LCS) approach
 */
function simpleDiff(oldLines, newLines) {
    const result = [];
    // Compute LCS matrix
    const lcs = computeLCS(oldLines, newLines);
    // Backtrack through LCS to build diff (builds in reverse)
    let i = oldLines.length;
    let j = newLines.length;
    while (i > 0 || j > 0) {
        if (i > 0 && j > 0 && oldLines[i - 1] === newLines[j - 1]) {
            // Lines are identical
            result.unshift({
                type: 'unchanged',
                lineNumber: 0, // Will assign later
                content: oldLines[i - 1]
            });
            i--;
            j--;
        }
        else if (j > 0 && (i === 0 || lcs[i][j - 1] >= lcs[i - 1][j])) {
            // Line added in new version
            result.unshift({
                type: 'added',
                lineNumber: 0, // Will assign later
                content: newLines[j - 1]
            });
            j--;
        }
        else if (i > 0 && (j === 0 || lcs[i][j - 1] < lcs[i - 1][j])) {
            // Line removed from old version
            result.unshift({
                type: 'removed',
                lineNumber: 0, // Will assign later
                content: oldLines[i - 1]
            });
            i--;
        }
    }
    // Post-process to detect modifications (adjacent add/remove pairs)
    const processed = detectModifications(result);
    // Assign sequential line numbers (ascending order)
    let lineNumber = 1;
    processed.forEach((line) => {
        line.lineNumber = lineNumber++;
    });
    return processed;
}
/**
 * Detect modified lines (pairs of removed + added lines)
 */
function detectModifications(lines) {
    const result = [];
    for (let i = 0; i < lines.length; i++) {
        const current = lines[i];
        const next = lines[i + 1];
        // Check if we have a removed line followed by an added line
        if (current.type === 'removed' && next && next.type === 'added') {
            // This is likely a modification
            const similarity = calculateSimilarity(current.content, next.content);
            // If lines are somewhat similar (>30% similar), treat as modification
            if (similarity > 0.3) {
                result.push({
                    type: 'modified',
                    lineNumber: current.lineNumber,
                    content: next.content,
                    oldContent: current.content,
                    newContent: next.content
                });
                i++; // Skip next line (we processed it)
                continue;
            }
        }
        result.push(current);
    }
    return result;
}
/**
 * Compute Longest Common Subsequence (LCS) matrix
 */
function computeLCS(a, b) {
    const m = a.length;
    const n = b.length;
    const lcs = Array(m + 1)
        .fill(null)
        .map(() => Array(n + 1).fill(0));
    for (let i = 1; i <= m; i++) {
        for (let j = 1; j <= n; j++) {
            if (a[i - 1] === b[j - 1]) {
                lcs[i][j] = lcs[i - 1][j - 1] + 1;
            }
            else {
                lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]);
            }
        }
    }
    return lcs;
}
/**
 * Calculate similarity between two strings (0 to 1)
 * Uses simple character overlap metric
 */
function calculateSimilarity(a, b) {
    if (a === b)
        return 1;
    if (a.length === 0 || b.length === 0)
        return 0;
    // Count matching characters (case insensitive, ignoring whitespace)
    const aNorm = a.toLowerCase().replace(/\s+/g, '');
    const bNorm = b.toLowerCase().replace(/\s+/g, '');
    const shorter = aNorm.length < bNorm.length ? aNorm : bNorm;
    const longer = aNorm.length >= bNorm.length ? aNorm : bNorm;
    let matches = 0;
    for (let i = 0; i < shorter.length; i++) {
        if (longer.includes(shorter[i])) {
            matches++;
        }
    }
    return matches / longer.length;
}
/**
 * Format diff for display - returns context-aware subset of lines
 * Shows changes with 3 lines of context before/after
 */
function getContextualDiff(diff, contextLines = 3) {
    const { lines } = diff;
    // Find all changed lines
    const changedIndices = lines
        .map((line, index) => (line.type !== 'unchanged' ? index : -1))
        .filter((index) => index !== -1);
    if (changedIndices.length === 0) {
        // No changes, return first few lines
        return lines.slice(0, Math.min(10, lines.length));
    }
    // Determine ranges to include (changes + context)
    const ranges = [];
    for (const index of changedIndices) {
        const start = Math.max(0, index - contextLines);
        const end = Math.min(lines.length - 1, index + contextLines);
        // Merge overlapping ranges
        if (ranges.length > 0) {
            const lastRange = ranges[ranges.length - 1];
            if (start <= lastRange[1] + 1) {
                lastRange[1] = Math.max(lastRange[1], end);
                continue;
            }
        }
        ranges.push([start, end]);
    }
    // Extract lines from ranges
    const result = [];
    for (let i = 0; i < ranges.length; i++) {
        const [start, end] = ranges[i];
        // Add separator if not first range
        if (i > 0 && start - ranges[i - 1][1] > 1) {
            result.push({
                type: 'unchanged',
                lineNumber: -1,
                content: '...'
            });
        }
        result.push(...lines.slice(start, end + 1));
    }
    return result;
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryDiffModal.module.scss
var CodeHistoryDiffModal_module = __webpack_require__(51794);
;// ../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryDiffModal.module.scss

      
      
      
      
      
      
      
      
      

var CodeHistoryDiffModal_module_options = {};

CodeHistoryDiffModal_module_options.styleTagTransform = (styleTagTransform_default());
CodeHistoryDiffModal_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      CodeHistoryDiffModal_module_options.insert = insertBySelector_default().bind(null, "head");
    
CodeHistoryDiffModal_module_options.domAPI = (styleDomAPI_default());
CodeHistoryDiffModal_module_options.insertStyleElement = (insertStyleElement_default());

var CodeHistoryDiffModal_module_update = injectStylesIntoStyleTag_default()(CodeHistoryDiffModal_module/* default */.A, CodeHistoryDiffModal_module_options);




       /* harmony default export */ const CodeHistory_CodeHistoryDiffModal_module = (CodeHistoryDiffModal_module/* default */.A && CodeHistoryDiffModal_module/* default */.A.locals ? CodeHistoryDiffModal_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryDiffModal.tsx
/**
 * CodeHistoryDiffModal Component
 *
 * Shows a side-by-side diff comparison between code versions.
 * This is the KILLER feature - beautiful visual diff with restore confirmation.
 *
 * @module code-editor/CodeHistory
 */



// Format timestamp
function formatTimestamp(timestamp) {
    const now = new Date();
    const then = new Date(timestamp);
    const diffMs = now.getTime() - then.getTime();
    const diffMin = Math.floor(diffMs / 1000 / 60);
    const diffHour = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHour / 24);
    if (diffMin < 60) {
        return `${diffMin} minute${diffMin === 1 ? '' : 's'} ago`;
    }
    else if (diffHour < 24) {
        return `${diffHour} hour${diffHour === 1 ? '' : 's'} ago`;
    }
    else if (diffDay === 1) {
        return 'yesterday';
    }
    else {
        return `${diffDay} days ago`;
    }
}
function CodeHistoryDiffModal({ oldCode, newCode, timestamp, onRestore, onClose }) {
    // Compute diff
    const diff = (0,external_react_.useMemo)(() => {
        const fullDiff = computeDiff(oldCode, newCode);
        const contextualLines = getContextualDiff(fullDiff, 3);
        return {
            full: fullDiff,
            lines: contextualLines
        };
    }, [oldCode, newCode]);
    // Split into old and new for side-by-side view
    const sideBySide = (0,external_react_.useMemo)(() => {
        const oldLines = [];
        const newLines = [];
        diff.lines.forEach((line) => {
            if (line.type === 'unchanged') {
                oldLines.push({ content: line.content, type: 'unchanged', lineNumber: line.lineNumber });
                newLines.push({ content: line.content, type: 'unchanged', lineNumber: line.lineNumber });
            }
            else if (line.type === 'removed') {
                oldLines.push({ content: line.content, type: 'removed', lineNumber: line.lineNumber });
                newLines.push({ content: '', type: 'empty', lineNumber: line.lineNumber });
            }
            else if (line.type === 'added') {
                oldLines.push({ content: '', type: 'empty', lineNumber: line.lineNumber });
                newLines.push({ content: line.content, type: 'added', lineNumber: line.lineNumber });
            }
            else if (line.type === 'modified') {
                oldLines.push({ content: line.oldContent || '', type: 'modified-old', lineNumber: line.lineNumber });
                newLines.push({ content: line.newContent || '', type: 'modified-new', lineNumber: line.lineNumber });
            }
        });
        return { oldLines, newLines };
    }, [diff.lines]);
    return (external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.Overlay, onClick: onClose },
        external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.Modal, onClick: (e) => e.stopPropagation() },
            external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.Header },
                external_react_default().createElement("h2", { className: CodeHistory_CodeHistoryDiffModal_module.Title },
                    "Restore code from ",
                    formatTimestamp(timestamp),
                    "?"),
                external_react_default().createElement("button", { onClick: onClose, className: CodeHistory_CodeHistoryDiffModal_module.CloseButton, type: "button", title: "Close" }, "\u00D7")),
            external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.DiffContainer },
                external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.DiffSide },
                    external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.DiffHeader },
                        external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.DiffLabel }, formatTimestamp(timestamp)),
                        external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.DiffInfo },
                            diff.full.deletions > 0 && external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.Deletions },
                                "-",
                                diff.full.deletions),
                            diff.full.modifications > 0 && external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.Modifications },
                                "~",
                                diff.full.modifications))),
                    external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.DiffCode }, sideBySide.oldLines.map((line, index) => (external_react_default().createElement("div", { key: index, className: `${CodeHistory_CodeHistoryDiffModal_module.DiffLine} ${line.type === 'removed'
                            ? CodeHistory_CodeHistoryDiffModal_module.DiffLineRemoved
                            : line.type === 'modified-old'
                                ? CodeHistory_CodeHistoryDiffModal_module.DiffLineModified
                                : line.type === 'empty'
                                    ? CodeHistory_CodeHistoryDiffModal_module.DiffLineEmpty
                                    : ''}` },
                        external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.LineNumber }, line.type !== 'empty' ? line.lineNumber : ''),
                        external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.LineContent }, line.content || ' ')))))),
                external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.DiffSeparator },
                    external_react_default().createElement("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none" },
                        external_react_default().createElement("path", { d: "M5 12h14M13 5l7 7-7 7", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }))),
                external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.DiffSide },
                    external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.DiffHeader },
                        external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.DiffLabel }, "Current"),
                        external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.DiffInfo },
                            diff.full.additions > 0 && external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.Additions },
                                "+",
                                diff.full.additions),
                            diff.full.modifications > 0 && external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.Modifications },
                                "~",
                                diff.full.modifications))),
                    external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.DiffCode }, sideBySide.newLines.map((line, index) => (external_react_default().createElement("div", { key: index, className: `${CodeHistory_CodeHistoryDiffModal_module.DiffLine} ${line.type === 'added'
                            ? CodeHistory_CodeHistoryDiffModal_module.DiffLineAdded
                            : line.type === 'modified-new'
                                ? CodeHistory_CodeHistoryDiffModal_module.DiffLineModified
                                : line.type === 'empty'
                                    ? CodeHistory_CodeHistoryDiffModal_module.DiffLineEmpty
                                    : ''}` },
                        external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.LineNumber }, line.type !== 'empty' ? line.lineNumber : ''),
                        external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDiffModal_module.LineContent }, line.content || ' '))))))),
            external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.Summary },
                diff.full.additions > 0 && external_react_default().createElement("span", null,
                    "\u2022 ",
                    diff.full.additions,
                    " line(s) will be removed"),
                diff.full.deletions > 0 && external_react_default().createElement("span", null,
                    "\u2022 ",
                    diff.full.deletions,
                    " line(s) will be added"),
                diff.full.modifications > 0 && external_react_default().createElement("span", null,
                    "\u2022 ",
                    diff.full.modifications,
                    " line(s) will change")),
            external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDiffModal_module.Footer },
                external_react_default().createElement("button", { onClick: onClose, className: CodeHistory_CodeHistoryDiffModal_module.CancelButton, type: "button" }, "Cancel"),
                external_react_default().createElement("button", { onClick: onRestore, className: CodeHistory_CodeHistoryDiffModal_module.RestoreButton, type: "button" }, "Restore Code")))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryDropdown.module.scss
var CodeHistoryDropdown_module = __webpack_require__(34741);
;// ../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryDropdown.module.scss

      
      
      
      
      
      
      
      
      

var CodeHistoryDropdown_module_options = {};

CodeHistoryDropdown_module_options.styleTagTransform = (styleTagTransform_default());
CodeHistoryDropdown_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      CodeHistoryDropdown_module_options.insert = insertBySelector_default().bind(null, "head");
    
CodeHistoryDropdown_module_options.domAPI = (styleDomAPI_default());
CodeHistoryDropdown_module_options.insertStyleElement = (insertStyleElement_default());

var CodeHistoryDropdown_module_update = injectStylesIntoStyleTag_default()(CodeHistoryDropdown_module/* default */.A, CodeHistoryDropdown_module_options);




       /* harmony default export */ const CodeHistory_CodeHistoryDropdown_module = (CodeHistoryDropdown_module/* default */.A && CodeHistoryDropdown_module/* default */.A.locals ? CodeHistoryDropdown_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryDropdown.tsx
/**
 * CodeHistoryDropdown Component
 *
 * Shows a list of code snapshots with preview and restore functionality.
 *
 * @module code-editor/CodeHistory
 */




// Format timestamp to human-readable format
function CodeHistoryDropdown_formatTimestamp(timestamp) {
    const now = new Date();
    const then = new Date(timestamp);
    const diffMs = now.getTime() - then.getTime();
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHour = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHour / 24);
    if (diffSec < 60) {
        return 'just now';
    }
    else if (diffMin < 60) {
        return `${diffMin} minute${diffMin === 1 ? '' : 's'} ago`;
    }
    else if (diffHour < 24) {
        return `${diffHour} hour${diffHour === 1 ? '' : 's'} ago`;
    }
    else if (diffDay === 1) {
        return 'yesterday at ' + then.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }
    else if (diffDay < 7) {
        return `${diffDay} days ago`;
    }
    else {
        return then.toLocaleDateString() + ' at ' + then.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }
}
function CodeHistoryDropdown({ nodeId, parameterName, currentCode, onRestore, onClose }) {
    const [selectedSnapshot, setSelectedSnapshot] = (0,external_react_.useState)(null);
    const [history, setHistory] = (0,external_react_.useState)([]);
    // Load history on mount
    external_react_default().useEffect(() => {
        // Dynamically import CodeHistoryManager to avoid circular dependencies
        // This allows noodl-core-ui to access noodl-editor functionality
        Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 37949))
            .then(({ CodeHistoryManager }) => {
            const historyData = CodeHistoryManager.instance.getHistory(nodeId, parameterName);
            setHistory(historyData);
        })
            .catch((error) => {
            console.warn('Could not load CodeHistoryManager:', error);
            setHistory([]);
        });
    }, [nodeId, parameterName]);
    // Compute diffs for all snapshots (newest first)
    const snapshotsWithDiffs = (0,external_react_.useMemo)(() => {
        return history
            .slice() // Don't mutate original
            .reverse() // Newest first
            .map((snapshot) => {
            const diff = computeDiff(snapshot.code, currentCode);
            const summary = getDiffSummary(diff);
            return {
                snapshot,
                diff,
                summary
            };
        });
    }, [history, currentCode]);
    if (history.length === 0) {
        return (external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDropdown_module.Root },
            external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDropdown_module.Header },
                external_react_default().createElement("h3", { className: CodeHistory_CodeHistoryDropdown_module.Title }, "Code History"),
                external_react_default().createElement("button", { onClick: onClose, className: CodeHistory_CodeHistoryDropdown_module.CloseButton, type: "button", title: "Close" }, "\u00D7")),
            external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDropdown_module.Empty },
                external_react_default().createElement("svg", { width: "48", height: "48", viewBox: "0 0 48 48", fill: "none", className: CodeHistory_CodeHistoryDropdown_module.EmptyIcon },
                    external_react_default().createElement("path", { d: "M24 42c9.941 0 18-8.059 18-18S33.941 6 24 6 6 14.059 6 24s8.059 18 18 18z", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }),
                    external_react_default().createElement("path", { d: "M24 14v12l6 6", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" })),
                external_react_default().createElement("p", { className: CodeHistory_CodeHistoryDropdown_module.EmptyText }, "No history yet"),
                external_react_default().createElement("p", { className: CodeHistory_CodeHistoryDropdown_module.EmptyHint }, "Code snapshots are saved automatically when you save changes."))));
    }
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDropdown_module.Root },
            external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDropdown_module.Header },
                external_react_default().createElement("h3", { className: CodeHistory_CodeHistoryDropdown_module.Title }, "Code History"),
                external_react_default().createElement("button", { onClick: onClose, className: CodeHistory_CodeHistoryDropdown_module.CloseButton, type: "button", title: "Close" }, "\u00D7")),
            external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDropdown_module.List }, snapshotsWithDiffs.map(({ snapshot, diff, summary }, index) => (external_react_default().createElement("div", { key: snapshot.timestamp, className: CodeHistory_CodeHistoryDropdown_module.Item },
                external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDropdown_module.ItemHeader },
                    external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDropdown_module.ItemIcon }, "\u2022"),
                    external_react_default().createElement("span", { className: CodeHistory_CodeHistoryDropdown_module.ItemTime }, CodeHistoryDropdown_formatTimestamp(snapshot.timestamp))),
                external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDropdown_module.ItemSummary }, summary.description),
                external_react_default().createElement("div", { className: CodeHistory_CodeHistoryDropdown_module.ItemActions },
                    external_react_default().createElement("button", { onClick: () => setSelectedSnapshot(snapshot), className: CodeHistory_CodeHistoryDropdown_module.PreviewButton, type: "button", title: "Preview changes" }, "Preview"))))))),
        selectedSnapshot && (external_react_default().createElement(CodeHistoryDiffModal, { oldCode: selectedSnapshot.code, newCode: currentCode, timestamp: selectedSnapshot.timestamp, onRestore: () => {
                onRestore(selectedSnapshot);
                setSelectedSnapshot(null);
            }, onClose: () => setSelectedSnapshot(null) }))));
}

;// ../noodl-core-ui/src/components/code-editor/CodeHistory/CodeHistoryButton.tsx
/**
 * CodeHistoryButton Component
 *
 * Displays a history button in the code editor toolbar.
 * Opens a dropdown showing code snapshots with diffs.
 *
 * @module code-editor/CodeHistory
 */



/**
 * History button with dropdown
 */
function CodeHistoryButton({ nodeId, parameterName, currentCode, onRestore }) {
    const [isOpen, setIsOpen] = (0,external_react_.useState)(false);
    const buttonRef = (0,external_react_.useRef)(null);
    const dropdownRef = (0,external_react_.useRef)(null);
    // Close dropdown when clicking outside
    (0,external_react_.useEffect)(() => {
        if (!isOpen)
            return;
        function handleClickOutside(event) {
            if (dropdownRef.current &&
                !dropdownRef.current.contains(event.target) &&
                buttonRef.current &&
                !buttonRef.current.contains(event.target)) {
                setIsOpen(false);
            }
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [isOpen]);
    return (external_react_default().createElement("div", { className: CodeHistory_CodeHistoryButton_module.Root },
        external_react_default().createElement("button", { ref: buttonRef, onClick: () => setIsOpen(!isOpen), className: CodeHistory_CodeHistoryButton_module.Button, title: "View code history", type: "button" },
            external_react_default().createElement("svg", { className: CodeHistory_CodeHistoryButton_module.Icon, width: "16", height: "16", viewBox: "0 0 16 16", fill: "none" },
                external_react_default().createElement("path", { d: "M8 14A6 6 0 1 0 8 2a6 6 0 0 0 0 12z", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }),
                external_react_default().createElement("path", { d: "M8 4v4l2 2", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" })),
            external_react_default().createElement("span", { className: CodeHistory_CodeHistoryButton_module.Label }, "History")),
        isOpen && (external_react_default().createElement("div", { ref: dropdownRef, className: CodeHistory_CodeHistoryButton_module.Dropdown },
            external_react_default().createElement(CodeHistoryDropdown, { nodeId: nodeId, parameterName: parameterName, currentCode: currentCode, onRestore: (snapshot) => {
                    onRestore(snapshot);
                    setIsOpen(false);
                }, onClose: () => setIsOpen(false) })))));
}

;// ../noodl-core-ui/src/components/code-editor/CodeHistory/index.ts
/**
 * Code History Components
 *
 * Exports code history components for use in code editors.
 *
 * @module code-editor/CodeHistory
 */




;// ../../node_modules/@lezer/common/dist/index.js
/**
The default maximum length of a `TreeBuffer` node.
*/
const DefaultBufferLength = 1024;
let nextPropID = 0;
class dist_Range {
    constructor(from, to) {
        this.from = from;
        this.to = to;
    }
}
/**
Each [node type](#common.NodeType) or [individual tree](#common.Tree)
can have metadata associated with it in props. Instances of this
class represent prop names.
*/
class NodeProp {
    /**
    Create a new node prop type.
    */
    constructor(config = {}) {
        this.id = nextPropID++;
        this.perNode = !!config.perNode;
        this.deserialize = config.deserialize || (() => {
            throw new Error("This node type doesn't define a deserialize function");
        });
        this.combine = config.combine || null;
    }
    /**
    This is meant to be used with
    [`NodeSet.extend`](#common.NodeSet.extend) or
    [`LRParser.configure`](#lr.ParserConfig.props) to compute
    prop values for each node type in the set. Takes a [match
    object](#common.NodeType^match) or function that returns undefined
    if the node type doesn't get this prop, and the prop's value if
    it does.
    */
    add(match) {
        if (this.perNode)
            throw new RangeError("Can't add per-node props to node types");
        if (typeof match != "function")
            match = dist_NodeType.match(match);
        return (type) => {
            let result = match(type);
            return result === undefined ? null : [this, result];
        };
    }
}
/**
Prop that is used to describe matching delimiters. For opening
delimiters, this holds an array of node names (written as a
space-separated string when declaring this prop in a grammar)
for the node types of closing delimiters that match it.
*/
NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") });
/**
The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
attached to closing delimiters, holding an array of node names
of types of matching opening delimiters.
*/
NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") });
/**
Used to assign node types to groups (for example, all node
types that represent an expression could be tagged with an
`"Expression"` group).
*/
NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") });
/**
Attached to nodes to indicate these should be
[displayed](https://codemirror.net/docs/ref/#language.syntaxTree)
in a bidirectional text isolate, so that direction-neutral
characters on their sides don't incorrectly get associated with
surrounding text. You'll generally want to set this for nodes
that contain arbitrary text, like strings and comments, and for
nodes that appear _inside_ arbitrary text, like HTML tags. When
not given a value, in a grammar declaration, defaults to
`"auto"`.
*/
NodeProp.isolate = new NodeProp({ deserialize: value => {
        if (value && value != "rtl" && value != "ltr" && value != "auto")
            throw new RangeError("Invalid value for isolate: " + value);
        return value || "auto";
    } });
/**
The hash of the [context](#lr.ContextTracker.constructor)
that the node was parsed in, if any. Used to limit reuse of
contextual nodes.
*/
NodeProp.contextHash = new NodeProp({ perNode: true });
/**
The distance beyond the end of the node that the tokenizer
looked ahead for any of the tokens inside the node. (The LR
parser only stores this when it is larger than 25, for
efficiency reasons.)
*/
NodeProp.lookAhead = new NodeProp({ perNode: true });
/**
This per-node prop is used to replace a given node, or part of a
node, with another tree. This is useful to include trees from
different languages in mixed-language parsers.
*/
NodeProp.mounted = new NodeProp({ perNode: true });
/**
A mounted tree, which can be [stored](#common.NodeProp^mounted) on
a tree node to indicate that parts of its content are
represented by another tree.
*/
class MountedTree {
    constructor(
    /**
    The inner tree.
    */
    tree, 
    /**
    If this is null, this tree replaces the entire node (it will
    be included in the regular iteration instead of its host
    node). If not, only the given ranges are considered to be
    covered by this tree. This is used for trees that are mixed in
    a way that isn't strictly hierarchical. Such mounted trees are
    only entered by [`resolveInner`](#common.Tree.resolveInner)
    and [`enter`](#common.SyntaxNode.enter).
    */
    overlay, 
    /**
    The parser used to create this subtree.
    */
    parser, 
    /**
    [Indicates](#common.IterMode.EnterBracketed) that the nested
    content is delineated with some kind
    of bracket token.
    */
    bracketed = false) {
        this.tree = tree;
        this.overlay = overlay;
        this.parser = parser;
        this.bracketed = bracketed;
    }
    /**
    @internal
    */
    static get(tree) {
        return tree && tree.props && tree.props[NodeProp.mounted.id];
    }
}
const noProps = Object.create(null);
/**
Each node in a syntax tree has a node type associated with it.
*/
class dist_NodeType {
    /**
    @internal
    */
    constructor(
    /**
    The name of the node type. Not necessarily unique, but if the
    grammar was written properly, different node types with the
    same name within a node set should play the same semantic
    role.
    */
    name, 
    /**
    @internal
    */
    props, 
    /**
    The id of this node in its set. Corresponds to the term ids
    used in the parser.
    */
    id, 
    /**
    @internal
    */
    flags = 0) {
        this.name = name;
        this.props = props;
        this.id = id;
        this.flags = flags;
    }
    /**
    Define a node type.
    */
    static define(spec) {
        let props = spec.props && spec.props.length ? Object.create(null) : noProps;
        let flags = (spec.top ? 1 /* NodeFlag.Top */ : 0) | (spec.skipped ? 2 /* NodeFlag.Skipped */ : 0) |
            (spec.error ? 4 /* NodeFlag.Error */ : 0) | (spec.name == null ? 8 /* NodeFlag.Anonymous */ : 0);
        let type = new dist_NodeType(spec.name || "", props, spec.id, flags);
        if (spec.props)
            for (let src of spec.props) {
                if (!Array.isArray(src))
                    src = src(type);
                if (src) {
                    if (src[0].perNode)
                        throw new RangeError("Can't store a per-node prop on a node type");
                    props[src[0].id] = src[1];
                }
            }
        return type;
    }
    /**
    Retrieves a node prop for this type. Will return `undefined` if
    the prop isn't present on this node.
    */
    prop(prop) { return this.props[prop.id]; }
    /**
    True when this is the top node of a grammar.
    */
    get isTop() { return (this.flags & 1 /* NodeFlag.Top */) > 0; }
    /**
    True when this node is produced by a skip rule.
    */
    get isSkipped() { return (this.flags & 2 /* NodeFlag.Skipped */) > 0; }
    /**
    Indicates whether this is an error node.
    */
    get isError() { return (this.flags & 4 /* NodeFlag.Error */) > 0; }
    /**
    When true, this node type doesn't correspond to a user-declared
    named node, for example because it is used to cache repetition.
    */
    get isAnonymous() { return (this.flags & 8 /* NodeFlag.Anonymous */) > 0; }
    /**
    Returns true when this node's name or one of its
    [groups](#common.NodeProp^group) matches the given string.
    */
    is(name) {
        if (typeof name == 'string') {
            if (this.name == name)
                return true;
            let group = this.prop(NodeProp.group);
            return group ? group.indexOf(name) > -1 : false;
        }
        return this.id == name;
    }
    /**
    Create a function from node types to arbitrary values by
    specifying an object whose property names are node or
    [group](#common.NodeProp^group) names. Often useful with
    [`NodeProp.add`](#common.NodeProp.add). You can put multiple
    names, separated by spaces, in a single property name to map
    multiple node names to a single value.
    */
    static match(map) {
        let direct = Object.create(null);
        for (let prop in map)
            for (let name of prop.split(" "))
                direct[name] = map[prop];
        return (node) => {
            for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
                let found = direct[i < 0 ? node.name : groups[i]];
                if (found)
                    return found;
            }
        };
    }
}
/**
An empty dummy node type to use when no actual type is available.
*/
dist_NodeType.none = new dist_NodeType("", Object.create(null), 0, 8 /* NodeFlag.Anonymous */);
/**
A node set holds a collection of node types. It is used to
compactly represent trees by storing their type ids, rather than a
full pointer to the type object, in a numeric array. Each parser
[has](#lr.LRParser.nodeSet) a node set, and [tree
buffers](#common.TreeBuffer) can only store collections of nodes
from the same set. A set can have a maximum of 2**16 (65536) node
types in it, so that the ids fit into 16-bit typed array slots.
*/
class NodeSet {
    /**
    Create a set with the given types. The `id` property of each
    type should correspond to its position within the array.
    */
    constructor(
    /**
    The node types in this set, by id.
    */
    types) {
        this.types = types;
        for (let i = 0; i < types.length; i++)
            if (types[i].id != i)
                throw new RangeError("Node type ids should correspond to array positions when creating a node set");
    }
    /**
    Create a copy of this set with some node properties added. The
    arguments to this method can be created with
    [`NodeProp.add`](#common.NodeProp.add).
    */
    extend(...props) {
        let newTypes = [];
        for (let type of this.types) {
            let newProps = null;
            for (let source of props) {
                let add = source(type);
                if (add) {
                    if (!newProps)
                        newProps = Object.assign({}, type.props);
                    let value = add[1], prop = add[0];
                    if (prop.combine && prop.id in newProps)
                        value = prop.combine(newProps[prop.id], value);
                    newProps[prop.id] = value;
                }
            }
            newTypes.push(newProps ? new dist_NodeType(type.name, newProps, type.id, type.flags) : type);
        }
        return new NodeSet(newTypes);
    }
}
const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap();
/**
Options that control iteration. Can be combined with the `|`
operator to enable multiple ones.
*/
var IterMode;
(function (IterMode) {
    /**
    When enabled, iteration will only visit [`Tree`](#common.Tree)
    objects, not nodes packed into
    [`TreeBuffer`](#common.TreeBuffer)s.
    */
    IterMode[IterMode["ExcludeBuffers"] = 1] = "ExcludeBuffers";
    /**
    Enable this to make iteration include anonymous nodes (such as
    the nodes that wrap repeated grammar constructs into a balanced
    tree).
    */
    IterMode[IterMode["IncludeAnonymous"] = 2] = "IncludeAnonymous";
    /**
    By default, regular [mounted](#common.NodeProp^mounted) nodes
    replace their base node in iteration. Enable this to ignore them
    instead.
    */
    IterMode[IterMode["IgnoreMounts"] = 4] = "IgnoreMounts";
    /**
    This option only applies in
    [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
    library to not enter mounted overlays if one covers the given
    position.
    */
    IterMode[IterMode["IgnoreOverlays"] = 8] = "IgnoreOverlays";
    /**
    When set, positions on the boundary of a mounted overlay tree
    that has its [`bracketed`](#common.NestedParse.bracketed) flag
    set will enter that tree regardless of side. Only supported in
    [`enter`](#common.SyntaxNode.enter), not in cursors.
    */
    IterMode[IterMode["EnterBracketed"] = 16] = "EnterBracketed";
})(IterMode || (IterMode = {}));
/**
A piece of syntax tree. There are two ways to approach these
trees: the way they are actually stored in memory, and the
convenient way.

Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
objects. By packing detail information into `TreeBuffer` leaf
nodes, the representation is made a lot more memory-efficient.

However, when you want to actually work with tree nodes, this
representation is very awkward, so most client code will want to
use the [`TreeCursor`](#common.TreeCursor) or
[`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
a view on some part of this data structure, and can be used to
move around to adjacent nodes.
*/
class Tree {
    /**
    Construct a new tree. See also [`Tree.build`](#common.Tree^build).
    */
    constructor(
    /**
    The type of the top node.
    */
    type, 
    /**
    This node's child nodes.
    */
    children, 
    /**
    The positions (offsets relative to the start of this tree) of
    the children.
    */
    positions, 
    /**
    The total length of this tree
    */
    length, 
    /**
    Per-node [node props](#common.NodeProp) to associate with this node.
    */
    props) {
        this.type = type;
        this.children = children;
        this.positions = positions;
        this.length = length;
        /**
        @internal
        */
        this.props = null;
        if (props && props.length) {
            this.props = Object.create(null);
            for (let [prop, value] of props)
                this.props[typeof prop == "number" ? prop : prop.id] = value;
        }
    }
    /**
    @internal
    */
    toString() {
        let mounted = MountedTree.get(this);
        if (mounted && !mounted.overlay)
            return mounted.tree.toString();
        let children = "";
        for (let ch of this.children) {
            let str = ch.toString();
            if (str) {
                if (children)
                    children += ",";
                children += str;
            }
        }
        return !this.type.name ? children :
            (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +
                (children.length ? "(" + children + ")" : "");
    }
    /**
    Get a [tree cursor](#common.TreeCursor) positioned at the top of
    the tree. Mode can be used to [control](#common.IterMode) which
    nodes the cursor visits.
    */
    cursor(mode = 0) {
        return new TreeCursor(this.topNode, mode);
    }
    /**
    Get a [tree cursor](#common.TreeCursor) pointing into this tree
    at the given position and side (see
    [`moveTo`](#common.TreeCursor.moveTo).
    */
    cursorAt(pos, side = 0, mode = 0) {
        let scope = CachedNode.get(this) || this.topNode;
        let cursor = new TreeCursor(scope);
        cursor.moveTo(pos, side);
        CachedNode.set(this, cursor._tree);
        return cursor;
    }
    /**
    Get a [syntax node](#common.SyntaxNode) object for the top of the
    tree.
    */
    get topNode() {
        return new TreeNode(this, 0, 0, null);
    }
    /**
    Get the [syntax node](#common.SyntaxNode) at the given position.
    If `side` is -1, this will move into nodes that end at the
    position. If 1, it'll move into nodes that start at the
    position. With 0, it'll only enter nodes that cover the position
    from both sides.
    
    Note that this will not enter
    [overlays](#common.MountedTree.overlay), and you often want
    [`resolveInner`](#common.Tree.resolveInner) instead.
    */
    resolve(pos, side = 0) {
        let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
        CachedNode.set(this, node);
        return node;
    }
    /**
    Like [`resolve`](#common.Tree.resolve), but will enter
    [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
    pointing into the innermost overlaid tree at the given position
    (with parent links going through all parent structure, including
    the host trees).
    */
    resolveInner(pos, side = 0) {
        let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
        CachedInnerNode.set(this, node);
        return node;
    }
    /**
    In some situations, it can be useful to iterate through all
    nodes around a position, including those in overlays that don't
    directly cover the position. This method gives you an iterator
    that will produce all nodes, from small to big, around the given
    position.
    */
    resolveStack(pos, side = 0) {
        return stackIterator(this, pos, side);
    }
    /**
    Iterate over the tree and its children, calling `enter` for any
    node that touches the `from`/`to` region (if given) before
    running over such a node's children, and `leave` (if given) when
    leaving the node. When `enter` returns `false`, that node will
    not have its children iterated over (or `leave` called).
    */
    iterate(spec) {
        let { enter, leave, from = 0, to = this.length } = spec;
        let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
        for (let c = this.cursor(mode | IterMode.IncludeAnonymous);;) {
            let entered = false;
            if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
                if (c.firstChild())
                    continue;
                entered = true;
            }
            for (;;) {
                if (entered && leave && (anon || !c.type.isAnonymous))
                    leave(c);
                if (c.nextSibling())
                    break;
                if (!c.parent())
                    return;
                entered = true;
            }
        }
    }
    /**
    Get the value of the given [node prop](#common.NodeProp) for this
    node. Works with both per-node and per-type props.
    */
    prop(prop) {
        return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;
    }
    /**
    Returns the node's [per-node props](#common.NodeProp.perNode) in a
    format that can be passed to the [`Tree`](#common.Tree)
    constructor.
    */
    get propValues() {
        let result = [];
        if (this.props)
            for (let id in this.props)
                result.push([+id, this.props[id]]);
        return result;
    }
    /**
    Balance the direct children of this tree, producing a copy of
    which may have children grouped into subtrees with type
    [`NodeType.none`](#common.NodeType^none).
    */
    balance(config = {}) {
        return this.children.length <= 8 /* Balance.BranchFactor */ ? this :
            balanceRange(dist_NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new Tree(dist_NodeType.none, children, positions, length)));
    }
    /**
    Build a tree from a postfix-ordered buffer of node information,
    or a cursor over such a buffer.
    */
    static build(data) { return buildTree(data); }
}
/**
The empty tree
*/
Tree.empty = new Tree(dist_NodeType.none, [], [], 0);
class FlatBufferCursor {
    constructor(buffer, index) {
        this.buffer = buffer;
        this.index = index;
    }
    get id() { return this.buffer[this.index - 4]; }
    get start() { return this.buffer[this.index - 3]; }
    get end() { return this.buffer[this.index - 2]; }
    get size() { return this.buffer[this.index - 1]; }
    get pos() { return this.index; }
    next() { this.index -= 4; }
    fork() { return new FlatBufferCursor(this.buffer, this.index); }
}
/**
Tree buffers contain (type, start, end, endIndex) quads for each
node. In such a buffer, nodes are stored in prefix order (parents
before children, with the endIndex of the parent indicating which
children belong to it).
*/
class TreeBuffer {
    /**
    Create a tree buffer.
    */
    constructor(
    /**
    The buffer's content.
    */
    buffer, 
    /**
    The total length of the group of nodes in the buffer.
    */
    length, 
    /**
    The node set used in this buffer.
    */
    set) {
        this.buffer = buffer;
        this.length = length;
        this.set = set;
    }
    /**
    @internal
    */
    get type() { return dist_NodeType.none; }
    /**
    @internal
    */
    toString() {
        let result = [];
        for (let index = 0; index < this.buffer.length;) {
            result.push(this.childString(index));
            index = this.buffer[index + 3];
        }
        return result.join(",");
    }
    /**
    @internal
    */
    childString(index) {
        let id = this.buffer[index], endIndex = this.buffer[index + 3];
        let type = this.set.types[id], result = type.name;
        if (/\W/.test(result) && !type.isError)
            result = JSON.stringify(result);
        index += 4;
        if (endIndex == index)
            return result;
        let children = [];
        while (index < endIndex) {
            children.push(this.childString(index));
            index = this.buffer[index + 3];
        }
        return result + "(" + children.join(",") + ")";
    }
    /**
    @internal
    */
    findChild(startIndex, endIndex, dir, pos, side) {
        let { buffer } = this, pick = -1;
        for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
            if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
                pick = i;
                if (dir > 0)
                    break;
            }
        }
        return pick;
    }
    /**
    @internal
    */
    slice(startI, endI, from) {
        let b = this.buffer;
        let copy = new Uint16Array(endI - startI), len = 0;
        for (let i = startI, j = 0; i < endI;) {
            copy[j++] = b[i++];
            copy[j++] = b[i++] - from;
            let to = copy[j++] = b[i++] - from;
            copy[j++] = b[i++] - startI;
            len = Math.max(len, to);
        }
        return new TreeBuffer(copy, len, this.set);
    }
}
function checkSide(side, pos, from, to) {
    switch (side) {
        case -2 /* Side.Before */: return from < pos;
        case -1 /* Side.AtOrBefore */: return to >= pos && from < pos;
        case 0 /* Side.Around */: return from < pos && to > pos;
        case 1 /* Side.AtOrAfter */: return from <= pos && to > pos;
        case 2 /* Side.After */: return to > pos;
        case 4 /* Side.DontCare */: return true;
    }
}
function resolveNode(node, pos, side, overlays) {
    var _a;
    // Move up to a node that actually holds the position, if possible
    while (node.from == node.to ||
        (side < 1 ? node.from >= pos : node.from > pos) ||
        (side > -1 ? node.to <= pos : node.to < pos)) {
        let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
        if (!parent)
            return node;
        node = parent;
    }
    let mode = overlays ? 0 : IterMode.IgnoreOverlays;
    // Must go up out of overlays when those do not overlap with pos
    if (overlays)
        for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
            if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
                node = parent;
        }
    for (;;) {
        let inner = node.enter(pos, side, mode);
        if (!inner)
            return node;
        node = inner;
    }
}
class BaseNode {
    cursor(mode = 0) { return new TreeCursor(this, mode); }
    getChild(type, before = null, after = null) {
        let r = getChildren(this, type, before, after);
        return r.length ? r[0] : null;
    }
    getChildren(type, before = null, after = null) {
        return getChildren(this, type, before, after);
    }
    resolve(pos, side = 0) {
        return resolveNode(this, pos, side, false);
    }
    resolveInner(pos, side = 0) {
        return resolveNode(this, pos, side, true);
    }
    matchContext(context) {
        return matchNodeContext(this.parent, context);
    }
    enterUnfinishedNodesBefore(pos) {
        let scan = this.childBefore(pos), node = this;
        while (scan) {
            let last = scan.lastChild;
            if (!last || last.to != scan.to)
                break;
            if (last.type.isError && last.from == last.to) {
                node = scan;
                scan = last.prevSibling;
            }
            else {
                scan = last;
            }
        }
        return node;
    }
    get node() { return this; }
    get next() { return this.parent; }
}
class TreeNode extends BaseNode {
    constructor(_tree, from, 
    // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
    index, _parent) {
        super();
        this._tree = _tree;
        this.from = from;
        this.index = index;
        this._parent = _parent;
    }
    get type() { return this._tree.type; }
    get name() { return this._tree.type.name; }
    get to() { return this.from + this._tree.length; }
    nextChild(i, dir, pos, side, mode = 0) {
        var _a;
        for (let parent = this;;) {
            for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
                let next = children[i], start = positions[i] + parent.from;
                if (!((mode & IterMode.EnterBracketed) && next instanceof Tree &&
                    ((_a = MountedTree.get(next)) === null || _a === void 0 ? void 0 : _a.overlay) === null && (start >= pos || start + next.length <= pos)) &&
                    !checkSide(side, pos, start, start + next.length))
                    continue;
                if (next instanceof TreeBuffer) {
                    if (mode & IterMode.ExcludeBuffers)
                        continue;
                    let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
                    if (index > -1)
                        return new BufferNode(new BufferContext(parent, next, i, start), null, index);
                }
                else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) {
                    let mounted;
                    if (!(mode & IterMode.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay)
                        return new TreeNode(mounted.tree, start, i, parent);
                    let inner = new TreeNode(next, start, i, parent);
                    return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner
                        : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side, mode);
                }
            }
            if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous)
                return null;
            if (parent.index >= 0)
                i = parent.index + dir;
            else
                i = dir < 0 ? -1 : parent._parent._tree.children.length;
            parent = parent._parent;
            if (!parent)
                return null;
        }
    }
    get firstChild() { return this.nextChild(0, 1, 0, 4 /* Side.DontCare */); }
    get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* Side.DontCare */); }
    childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* Side.After */); }
    childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Side.Before */); }
    prop(prop) { return this._tree.prop(prop); }
    enter(pos, side, mode = 0) {
        let mounted;
        if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {
            let rPos = pos - this.from, enterBracketed = (mode & IterMode.EnterBracketed) && mounted.bracketed;
            for (let { from, to } of mounted.overlay) {
                if ((side > 0 || enterBracketed ? from <= rPos : from < rPos) &&
                    (side < 0 || enterBracketed ? to >= rPos : to > rPos))
                    return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
            }
        }
        return this.nextChild(0, 1, pos, side, mode);
    }
    nextSignificantParent() {
        let val = this;
        while (val.type.isAnonymous && val._parent)
            val = val._parent;
        return val;
    }
    get parent() {
        return this._parent ? this._parent.nextSignificantParent() : null;
    }
    get nextSibling() {
        return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4 /* Side.DontCare */) : null;
    }
    get prevSibling() {
        return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* Side.DontCare */) : null;
    }
    get tree() { return this._tree; }
    toTree() { return this._tree; }
    /**
    @internal
    */
    toString() { return this._tree.toString(); }
}
function getChildren(node, type, before, after) {
    let cur = node.cursor(), result = [];
    if (!cur.firstChild())
        return result;
    if (before != null)
        for (let found = false; !found;) {
            found = cur.type.is(before);
            if (!cur.nextSibling())
                return result;
        }
    for (;;) {
        if (after != null && cur.type.is(after))
            return result;
        if (cur.type.is(type))
            result.push(cur.node);
        if (!cur.nextSibling())
            return after == null ? result : [];
    }
}
function matchNodeContext(node, context, i = context.length - 1) {
    for (let p = node; i >= 0; p = p.parent) {
        if (!p)
            return false;
        if (!p.type.isAnonymous) {
            if (context[i] && context[i] != p.name)
                return false;
            i--;
        }
    }
    return true;
}
class BufferContext {
    constructor(parent, buffer, index, start) {
        this.parent = parent;
        this.buffer = buffer;
        this.index = index;
        this.start = start;
    }
}
class BufferNode extends BaseNode {
    get name() { return this.type.name; }
    get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }
    get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }
    constructor(context, _parent, index) {
        super();
        this.context = context;
        this._parent = _parent;
        this.index = index;
        this.type = context.buffer.set.types[context.buffer.buffer[index]];
    }
    child(dir, pos, side) {
        let { buffer } = this.context;
        let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
        return index < 0 ? null : new BufferNode(this.context, this, index);
    }
    get firstChild() { return this.child(1, 0, 4 /* Side.DontCare */); }
    get lastChild() { return this.child(-1, 0, 4 /* Side.DontCare */); }
    childAfter(pos) { return this.child(1, pos, 2 /* Side.After */); }
    childBefore(pos) { return this.child(-1, pos, -2 /* Side.Before */); }
    prop(prop) { return this.type.prop(prop); }
    enter(pos, side, mode = 0) {
        if (mode & IterMode.ExcludeBuffers)
            return null;
        let { buffer } = this.context;
        let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
        return index < 0 ? null : new BufferNode(this.context, this, index);
    }
    get parent() {
        return this._parent || this.context.parent.nextSignificantParent();
    }
    externalSibling(dir) {
        return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* Side.DontCare */);
    }
    get nextSibling() {
        let { buffer } = this.context;
        let after = buffer.buffer[this.index + 3];
        if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
            return new BufferNode(this.context, this._parent, after);
        return this.externalSibling(1);
    }
    get prevSibling() {
        let { buffer } = this.context;
        let parentStart = this._parent ? this._parent.index + 4 : 0;
        if (this.index == parentStart)
            return this.externalSibling(-1);
        return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));
    }
    get tree() { return null; }
    toTree() {
        let children = [], positions = [];
        let { buffer } = this.context;
        let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
        if (endI > startI) {
            let from = buffer.buffer[this.index + 1];
            children.push(buffer.slice(startI, endI, from));
            positions.push(0);
        }
        return new Tree(this.type, children, positions, this.to - this.from);
    }
    /**
    @internal
    */
    toString() { return this.context.buffer.childString(this.index); }
}
function iterStack(heads) {
    if (!heads.length)
        return null;
    let pick = 0, picked = heads[0];
    for (let i = 1; i < heads.length; i++) {
        let node = heads[i];
        if (node.from > picked.from || node.to < picked.to) {
            picked = node;
            pick = i;
        }
    }
    let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent;
    let newHeads = heads.slice();
    if (next)
        newHeads[pick] = next;
    else
        newHeads.splice(pick, 1);
    return new StackIterator(newHeads, picked);
}
class StackIterator {
    constructor(heads, node) {
        this.heads = heads;
        this.node = node;
    }
    get next() { return iterStack(this.heads); }
}
function stackIterator(tree, pos, side) {
    let inner = tree.resolveInner(pos, side), layers = null;
    for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent) {
        if (scan.index < 0) { // This is an overlay root
            let parent = scan.parent;
            (layers || (layers = [inner])).push(parent.resolve(pos, side));
            scan = parent;
        }
        else {
            let mount = MountedTree.get(scan.tree);
            // Relevant overlay branching off
            if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) {
                let root = new TreeNode(mount.tree, mount.overlay[0].from + scan.from, -1, scan);
                (layers || (layers = [inner])).push(resolveNode(root, pos, side, false));
            }
        }
    }
    return layers ? iterStack(layers) : inner;
}
/**
A tree cursor object focuses on a given node in a syntax tree, and
allows you to move to adjacent nodes.
*/
class TreeCursor {
    /**
    Shorthand for `.type.name`.
    */
    get name() { return this.type.name; }
    /**
    @internal
    */
    constructor(node, mode = 0) {
        /**
        @internal
        */
        this.buffer = null;
        this.stack = [];
        /**
        @internal
        */
        this.index = 0;
        this.bufferNode = null;
        this.mode = mode & ~IterMode.EnterBracketed;
        if (node instanceof TreeNode) {
            this.yieldNode(node);
        }
        else {
            this._tree = node.context.parent;
            this.buffer = node.context;
            for (let n = node._parent; n; n = n._parent)
                this.stack.unshift(n.index);
            this.bufferNode = node;
            this.yieldBuf(node.index);
        }
    }
    yieldNode(node) {
        if (!node)
            return false;
        this._tree = node;
        this.type = node.type;
        this.from = node.from;
        this.to = node.to;
        return true;
    }
    yieldBuf(index, type) {
        this.index = index;
        let { start, buffer } = this.buffer;
        this.type = type || buffer.set.types[buffer.buffer[index]];
        this.from = start + buffer.buffer[index + 1];
        this.to = start + buffer.buffer[index + 2];
        return true;
    }
    /**
    @internal
    */
    yield(node) {
        if (!node)
            return false;
        if (node instanceof TreeNode) {
            this.buffer = null;
            return this.yieldNode(node);
        }
        this.buffer = node.context;
        return this.yieldBuf(node.index, node.type);
    }
    /**
    @internal
    */
    toString() {
        return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
    }
    /**
    @internal
    */
    enterChild(dir, pos, side) {
        if (!this.buffer)
            return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
        let { buffer } = this.buffer;
        let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
        if (index < 0)
            return false;
        this.stack.push(this.index);
        return this.yieldBuf(index);
    }
    /**
    Move the cursor to this node's first child. When this returns
    false, the node has no child, and the cursor has not been moved.
    */
    firstChild() { return this.enterChild(1, 0, 4 /* Side.DontCare */); }
    /**
    Move the cursor to this node's last child.
    */
    lastChild() { return this.enterChild(-1, 0, 4 /* Side.DontCare */); }
    /**
    Move the cursor to the first child that ends after `pos`.
    */
    childAfter(pos) { return this.enterChild(1, pos, 2 /* Side.After */); }
    /**
    Move to the last child that starts before `pos`.
    */
    childBefore(pos) { return this.enterChild(-1, pos, -2 /* Side.Before */); }
    /**
    Move the cursor to the child around `pos`. If side is -1 the
    child may end at that position, when 1 it may start there. This
    will also enter [overlaid](#common.MountedTree.overlay)
    [mounted](#common.NodeProp^mounted) trees unless `overlays` is
    set to false.
    */
    enter(pos, side, mode = this.mode) {
        if (!this.buffer)
            return this.yield(this._tree.enter(pos, side, mode));
        return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
    }
    /**
    Move to the node's parent node, if this isn't the top node.
    */
    parent() {
        if (!this.buffer)
            return this.yieldNode((this.mode & IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent);
        if (this.stack.length)
            return this.yieldBuf(this.stack.pop());
        let parent = (this.mode & IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
        this.buffer = null;
        return this.yieldNode(parent);
    }
    /**
    @internal
    */
    sibling(dir) {
        if (!this.buffer)
            return !this._tree._parent ? false
                : this.yield(this._tree.index < 0 ? null
                    : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode));
        let { buffer } = this.buffer, d = this.stack.length - 1;
        if (dir < 0) {
            let parentStart = d < 0 ? 0 : this.stack[d] + 4;
            if (this.index != parentStart)
                return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));
        }
        else {
            let after = buffer.buffer[this.index + 3];
            if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
                return this.yieldBuf(after);
        }
        return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode)) : false;
    }
    /**
    Move to this node's next sibling, if any.
    */
    nextSibling() { return this.sibling(1); }
    /**
    Move to this node's previous sibling, if any.
    */
    prevSibling() { return this.sibling(-1); }
    atLastNode(dir) {
        let index, parent, { buffer } = this;
        if (buffer) {
            if (dir > 0) {
                if (this.index < buffer.buffer.buffer.length)
                    return false;
            }
            else {
                for (let i = 0; i < this.index; i++)
                    if (buffer.buffer.buffer[i + 3] < this.index)
                        return false;
            }
            ({ index, parent } = buffer);
        }
        else {
            ({ index, _parent: parent } = this._tree);
        }
        for (; parent; { index, _parent: parent } = parent) {
            if (index > -1)
                for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
                    let child = parent._tree.children[i];
                    if ((this.mode & IterMode.IncludeAnonymous) ||
                        child instanceof TreeBuffer ||
                        !child.type.isAnonymous ||
                        hasChild(child))
                        return false;
                }
        }
        return true;
    }
    move(dir, enter) {
        if (enter && this.enterChild(dir, 0, 4 /* Side.DontCare */))
            return true;
        for (;;) {
            if (this.sibling(dir))
                return true;
            if (this.atLastNode(dir) || !this.parent())
                return false;
        }
    }
    /**
    Move to the next node in a
    [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
    traversal, going from a node to its first child or, if the
    current node is empty or `enter` is false, its next sibling or
    the next sibling of the first parent node that has one.
    */
    next(enter = true) { return this.move(1, enter); }
    /**
    Move to the next node in a last-to-first pre-order traversal. A
    node is followed by its last child or, if it has none, its
    previous sibling or the previous sibling of the first parent
    node that has one.
    */
    prev(enter = true) { return this.move(-1, enter); }
    /**
    Move the cursor to the innermost node that covers `pos`. If
    `side` is -1, it will enter nodes that end at `pos`. If it is 1,
    it will enter nodes that start at `pos`.
    */
    moveTo(pos, side = 0) {
        // Move up to a node that actually holds the position, if possible
        while (this.from == this.to ||
            (side < 1 ? this.from >= pos : this.from > pos) ||
            (side > -1 ? this.to <= pos : this.to < pos))
            if (!this.parent())
                break;
        // Then scan down into child nodes as far as possible
        while (this.enterChild(1, pos, side)) { }
        return this;
    }
    /**
    Get a [syntax node](#common.SyntaxNode) at the cursor's current
    position.
    */
    get node() {
        if (!this.buffer)
            return this._tree;
        let cache = this.bufferNode, result = null, depth = 0;
        if (cache && cache.context == this.buffer) {
            scan: for (let index = this.index, d = this.stack.length; d >= 0;) {
                for (let c = cache; c; c = c._parent)
                    if (c.index == index) {
                        if (index == this.index)
                            return c;
                        result = c;
                        depth = d + 1;
                        break scan;
                    }
                index = this.stack[--d];
            }
        }
        for (let i = depth; i < this.stack.length; i++)
            result = new BufferNode(this.buffer, result, this.stack[i]);
        return this.bufferNode = new BufferNode(this.buffer, result, this.index);
    }
    /**
    Get the [tree](#common.Tree) that represents the current node, if
    any. Will return null when the node is in a [tree
    buffer](#common.TreeBuffer).
    */
    get tree() {
        return this.buffer ? null : this._tree._tree;
    }
    /**
    Iterate over the current node and all its descendants, calling
    `enter` when entering a node and `leave`, if given, when leaving
    one. When `enter` returns `false`, any children of that node are
    skipped, and `leave` isn't called for it.
    */
    iterate(enter, leave) {
        for (let depth = 0;;) {
            let mustLeave = false;
            if (this.type.isAnonymous || enter(this) !== false) {
                if (this.firstChild()) {
                    depth++;
                    continue;
                }
                if (!this.type.isAnonymous)
                    mustLeave = true;
            }
            for (;;) {
                if (mustLeave && leave)
                    leave(this);
                mustLeave = this.type.isAnonymous;
                if (!depth)
                    return;
                if (this.nextSibling())
                    break;
                this.parent();
                depth--;
                mustLeave = true;
            }
        }
    }
    /**
    Test whether the current node matches a given context—a sequence
    of direct parent node names. Empty strings in the context array
    are treated as wildcards.
    */
    matchContext(context) {
        if (!this.buffer)
            return matchNodeContext(this.node.parent, context);
        let { buffer } = this.buffer, { types } = buffer.set;
        for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
            if (d < 0)
                return matchNodeContext(this._tree, context, i);
            let type = types[buffer.buffer[this.stack[d]]];
            if (!type.isAnonymous) {
                if (context[i] && context[i] != type.name)
                    return false;
                i--;
            }
        }
        return true;
    }
}
function hasChild(tree) {
    return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
}
function buildTree(data) {
    var _a;
    let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
    let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
    let types = nodeSet.types;
    let contextHash = 0, lookAhead = 0;
    function takeNode(parentStart, minPos, children, positions, inRepeat, depth) {
        let { id, start, end, size } = cursor;
        let lookAheadAtStart = lookAhead, contextAtStart = contextHash;
        if (size < 0) {
            cursor.next();
            if (size == -1 /* SpecialRecord.Reuse */) {
                let node = reused[id];
                children.push(node);
                positions.push(start - parentStart);
                return;
            }
            else if (size == -3 /* SpecialRecord.ContextChange */) { // Context change
                contextHash = id;
                return;
            }
            else if (size == -4 /* SpecialRecord.LookAhead */) {
                lookAhead = id;
                return;
            }
            else {
                throw new RangeError(`Unrecognized record size: ${size}`);
            }
        }
        let type = types[id], node, buffer;
        let startPos = start - parentStart;
        if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {
            // Small enough for a buffer, and no reused nodes inside
            let data = new Uint16Array(buffer.size - buffer.skip);
            let endPos = cursor.pos - buffer.size, index = data.length;
            while (cursor.pos > endPos)
                index = copyToBuffer(buffer.start, data, index);
            node = new TreeBuffer(data, end - buffer.start, nodeSet);
            startPos = buffer.start - parentStart;
        }
        else { // Make it a node
            let endPos = cursor.pos - size;
            cursor.next();
            let localChildren = [], localPositions = [];
            let localInRepeat = id >= minRepeatType ? id : -1;
            let lastGroup = 0, lastEnd = end;
            while (cursor.pos > endPos) {
                if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
                    if (cursor.end <= lastEnd - maxBufferLength) {
                        makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
                        lastGroup = localChildren.length;
                        lastEnd = cursor.end;
                    }
                    cursor.next();
                }
                else if (depth > 2500 /* CutOff.Depth */) {
                    takeFlatNode(start, endPos, localChildren, localPositions);
                }
                else {
                    takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth + 1);
                }
            }
            if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
                makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
            localChildren.reverse();
            localPositions.reverse();
            if (localInRepeat > -1 && lastGroup > 0) {
                let make = makeBalanced(type, contextAtStart);
                node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
            }
            else {
                node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end, contextAtStart);
            }
        }
        children.push(node);
        positions.push(startPos);
    }
    function takeFlatNode(parentStart, minPos, children, positions) {
        let nodes = []; // Temporary, inverted array of leaf nodes found, with absolute positions
        let nodeCount = 0, stopAt = -1;
        while (cursor.pos > minPos) {
            let { id, start, end, size } = cursor;
            if (size > 4) { // Not a leaf
                cursor.next();
            }
            else if (stopAt > -1 && start < stopAt) {
                break;
            }
            else {
                if (stopAt < 0)
                    stopAt = end - maxBufferLength;
                nodes.push(id, start, end);
                nodeCount++;
                cursor.next();
            }
        }
        if (nodeCount) {
            let buffer = new Uint16Array(nodeCount * 4);
            let start = nodes[nodes.length - 2];
            for (let i = nodes.length - 3, j = 0; i >= 0; i -= 3) {
                buffer[j++] = nodes[i];
                buffer[j++] = nodes[i + 1] - start;
                buffer[j++] = nodes[i + 2] - start;
                buffer[j++] = j;
            }
            children.push(new TreeBuffer(buffer, nodes[2] - start, nodeSet));
            positions.push(start - parentStart);
        }
    }
    function makeBalanced(type, contextHash) {
        return (children, positions, length) => {
            let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp;
            if (lastI >= 0 && (last = children[lastI]) instanceof Tree) {
                if (!lastI && last.type == type && last.length == length)
                    return last;
                if (lookAheadProp = last.prop(NodeProp.lookAhead))
                    lookAhead = positions[lastI] + last.length + lookAheadProp;
            }
            return makeTree(type, children, positions, length, lookAhead, contextHash);
        };
    }
    function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead, contextHash) {
        let localChildren = [], localPositions = [];
        while (children.length > i) {
            localChildren.push(children.pop());
            localPositions.push(positions.pop() + base - from);
        }
        children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to, contextHash));
        positions.push(from - base);
    }
    function makeTree(type, children, positions, length, lookAhead, contextHash, props) {
        if (contextHash) {
            let pair = [NodeProp.contextHash, contextHash];
            props = props ? [pair].concat(props) : [pair];
        }
        if (lookAhead > 25) {
            let pair = [NodeProp.lookAhead, lookAhead];
            props = props ? [pair].concat(props) : [pair];
        }
        return new Tree(type, children, positions, length, props);
    }
    function findBufferSize(maxSize, inRepeat) {
        // Scan through the buffer to find previous siblings that fit
        // together in a TreeBuffer, and don't contain any reused nodes
        // (which can't be stored in a buffer).
        // If `inRepeat` is > -1, ignore node boundaries of that type for
        // nesting, but make sure the end falls either at the start
        // (`maxSize`) or before such a node.
        let fork = cursor.fork();
        let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
        let result = { size: 0, start: 0, skip: 0 };
        scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {
            let nodeSize = fork.size;
            // Pretend nested repeat nodes of the same type don't exist
            if (fork.id == inRepeat && nodeSize >= 0) {
                // Except that we store the current state as a valid return
                // value.
                result.size = size;
                result.start = start;
                result.skip = skip;
                skip += 4;
                size += 4;
                fork.next();
                continue;
            }
            let startPos = fork.pos - nodeSize;
            if (nodeSize < 0 || startPos < minPos || fork.start < minStart)
                break;
            let localSkipped = fork.id >= minRepeatType ? 4 : 0;
            let nodeStart = fork.start;
            fork.next();
            while (fork.pos > startPos) {
                if (fork.size < 0) {
                    if (fork.size == -3 /* SpecialRecord.ContextChange */ || fork.size == -4 /* SpecialRecord.LookAhead */)
                        localSkipped += 4;
                    else
                        break scan;
                }
                else if (fork.id >= minRepeatType) {
                    localSkipped += 4;
                }
                fork.next();
            }
            start = nodeStart;
            size += nodeSize;
            skip += localSkipped;
        }
        if (inRepeat < 0 || size == maxSize) {
            result.size = size;
            result.start = start;
            result.skip = skip;
        }
        return result.size > 4 ? result : undefined;
    }
    function copyToBuffer(bufferStart, buffer, index) {
        let { id, start, end, size } = cursor;
        cursor.next();
        if (size >= 0 && id < minRepeatType) {
            let startIndex = index;
            if (size > 4) {
                let endPos = cursor.pos - (size - 4);
                while (cursor.pos > endPos)
                    index = copyToBuffer(bufferStart, buffer, index);
            }
            buffer[--index] = startIndex;
            buffer[--index] = end - bufferStart;
            buffer[--index] = start - bufferStart;
            buffer[--index] = id;
        }
        else if (size == -3 /* SpecialRecord.ContextChange */) {
            contextHash = id;
        }
        else if (size == -4 /* SpecialRecord.LookAhead */) {
            lookAhead = id;
        }
        return index;
    }
    let children = [], positions = [];
    while (cursor.pos > 0)
        takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1, 0);
    let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);
    return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
}
const nodeSizeCache = new WeakMap;
function nodeSize(balanceType, node) {
    if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
        return 1;
    let size = nodeSizeCache.get(node);
    if (size == null) {
        size = 1;
        for (let child of node.children) {
            if (child.type != balanceType || !(child instanceof Tree)) {
                size = 1;
                break;
            }
            size += nodeSize(balanceType, child);
        }
        nodeSizeCache.set(node, size);
    }
    return size;
}
function balanceRange(
// The type the balanced tree's inner nodes.
balanceType, 
// The direct children and their positions
children, positions, 
// The index range in children/positions to use
from, to, 
// The start position of the nodes, relative to their parent.
start, 
// Length of the outer node
length, 
// Function to build the top node of the balanced tree
mkTop, 
// Function to build internal nodes for the balanced tree
mkTree) {
    let total = 0;
    for (let i = from; i < to; i++)
        total += nodeSize(balanceType, children[i]);
    let maxChild = Math.ceil((total * 1.5) / 8 /* Balance.BranchFactor */);
    let localChildren = [], localPositions = [];
    function divide(children, positions, from, to, offset) {
        for (let i = from; i < to;) {
            let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]);
            i++;
            for (; i < to; i++) {
                let nextSize = nodeSize(balanceType, children[i]);
                if (groupSize + nextSize >= maxChild)
                    break;
                groupSize += nextSize;
            }
            if (i == groupFrom + 1) {
                if (groupSize > maxChild) {
                    let only = children[groupFrom]; // Only trees can have a size > 1
                    divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset);
                    continue;
                }
                localChildren.push(children[groupFrom]);
            }
            else {
                let length = positions[i - 1] + children[i - 1].length - groupStart;
                localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree));
            }
            localPositions.push(groupStart + offset - start);
        }
    }
    divide(children, positions, from, to, 0);
    return (mkTop || mkTree)(localChildren, localPositions, length);
}
/**
Provides a way to associate values with pieces of trees. As long
as that part of the tree is reused, the associated values can be
retrieved from an updated tree.
*/
class NodeWeakMap {
    constructor() {
        this.map = new WeakMap();
    }
    setBuffer(buffer, index, value) {
        let inner = this.map.get(buffer);
        if (!inner)
            this.map.set(buffer, inner = new Map);
        inner.set(index, value);
    }
    getBuffer(buffer, index) {
        let inner = this.map.get(buffer);
        return inner && inner.get(index);
    }
    /**
    Set the value for this syntax node.
    */
    set(node, value) {
        if (node instanceof BufferNode)
            this.setBuffer(node.context.buffer, node.index, value);
        else if (node instanceof TreeNode)
            this.map.set(node.tree, value);
    }
    /**
    Retrieve value for this syntax node, if it exists in the map.
    */
    get(node) {
        return node instanceof BufferNode ? this.getBuffer(node.context.buffer, node.index)
            : node instanceof TreeNode ? this.map.get(node.tree) : undefined;
    }
    /**
    Set the value for the node that a cursor currently points to.
    */
    cursorSet(cursor, value) {
        if (cursor.buffer)
            this.setBuffer(cursor.buffer.buffer, cursor.index, value);
        else
            this.map.set(cursor.tree, value);
    }
    /**
    Retrieve the value for the node that a cursor currently points
    to.
    */
    cursorGet(cursor) {
        return cursor.buffer ? this.getBuffer(cursor.buffer.buffer, cursor.index) : this.map.get(cursor.tree);
    }
}

/**
Tree fragments are used during [incremental
parsing](#common.Parser.startParse) to track parts of old trees
that can be reused in a new parse. An array of fragments is used
to track regions of an old tree whose nodes might be reused in new
parses. Use the static
[`applyChanges`](#common.TreeFragment^applyChanges) method to
update fragments for document changes.
*/
class TreeFragment {
    /**
    Construct a tree fragment. You'll usually want to use
    [`addTree`](#common.TreeFragment^addTree) and
    [`applyChanges`](#common.TreeFragment^applyChanges) instead of
    calling this directly.
    */
    constructor(
    /**
    The start of the unchanged range pointed to by this fragment.
    This refers to an offset in the _updated_ document (as opposed
    to the original tree).
    */
    from, 
    /**
    The end of the unchanged range.
    */
    to, 
    /**
    The tree that this fragment is based on.
    */
    tree, 
    /**
    The offset between the fragment's tree and the document that
    this fragment can be used against. Add this when going from
    document to tree positions, subtract it to go from tree to
    document positions.
    */
    offset, openStart = false, openEnd = false) {
        this.from = from;
        this.to = to;
        this.tree = tree;
        this.offset = offset;
        this.open = (openStart ? 1 /* Open.Start */ : 0) | (openEnd ? 2 /* Open.End */ : 0);
    }
    /**
    Whether the start of the fragment represents the start of a
    parse, or the end of a change. (In the second case, it may not
    be safe to reuse some nodes at the start, depending on the
    parsing algorithm.)
    */
    get openStart() { return (this.open & 1 /* Open.Start */) > 0; }
    /**
    Whether the end of the fragment represents the end of a
    full-document parse, or the start of a change.
    */
    get openEnd() { return (this.open & 2 /* Open.End */) > 0; }
    /**
    Create a set of fragments from a freshly parsed tree, or update
    an existing set of fragments by replacing the ones that overlap
    with a tree with content from the new tree. When `partial` is
    true, the parse is treated as incomplete, and the resulting
    fragment has [`openEnd`](#common.TreeFragment.openEnd) set to
    true.
    */
    static addTree(tree, fragments = [], partial = false) {
        let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];
        for (let f of fragments)
            if (f.to > tree.length)
                result.push(f);
        return result;
    }
    /**
    Apply a set of edits to an array of fragments, removing or
    splitting fragments as necessary to remove edited ranges, and
    adjusting offsets for fragments that moved.
    */
    static applyChanges(fragments, changes, minGap = 128) {
        if (!changes.length)
            return fragments;
        let result = [];
        let fI = 1, nextF = fragments.length ? fragments[0] : null;
        for (let cI = 0, pos = 0, off = 0;; cI++) {
            let nextC = cI < changes.length ? changes[cI] : null;
            let nextPos = nextC ? nextC.fromA : 1e9;
            if (nextPos - pos >= minGap)
                while (nextF && nextF.from < nextPos) {
                    let cut = nextF;
                    if (pos >= cut.from || nextPos <= cut.to || off) {
                        let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;
                        cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);
                    }
                    if (cut)
                        result.push(cut);
                    if (nextF.to > nextPos)
                        break;
                    nextF = fI < fragments.length ? fragments[fI++] : null;
                }
            if (!nextC)
                break;
            pos = nextC.toA;
            off = nextC.toA - nextC.toB;
        }
        return result;
    }
}
/**
A superclass that parsers should extend.
*/
class Parser {
    /**
    Start a parse, returning a [partial parse](#common.PartialParse)
    object. [`fragments`](#common.TreeFragment) can be passed in to
    make the parse incremental.
    
    By default, the entire input is parsed. You can pass `ranges`,
    which should be a sorted array of non-empty, non-overlapping
    ranges, to parse only those ranges. The tree returned in that
    case will start at `ranges[0].from`.
    */
    startParse(input, fragments, ranges) {
        if (typeof input == "string")
            input = new StringInput(input);
        ranges = !ranges ? [new dist_Range(0, input.length)] : ranges.length ? ranges.map(r => new dist_Range(r.from, r.to)) : [new dist_Range(0, 0)];
        return this.createParse(input, fragments || [], ranges);
    }
    /**
    Run a full parse, returning the resulting tree.
    */
    parse(input, fragments, ranges) {
        let parse = this.startParse(input, fragments, ranges);
        for (;;) {
            let done = parse.advance();
            if (done)
                return done;
        }
    }
}
class StringInput {
    constructor(string) {
        this.string = string;
    }
    get length() { return this.string.length; }
    chunk(from) { return this.string.slice(from); }
    get lineChunks() { return false; }
    read(from, to) { return this.string.slice(from, to); }
}

/**
Create a parse wrapper that, after the inner parse completes,
scans its tree for mixed language regions with the `nest`
function, runs the resulting [inner parses](#common.NestedParse),
and then [mounts](#common.NodeProp^mounted) their results onto the
tree.
*/
function parseMixed(nest) {
    return (parse, input, fragments, ranges) => new MixedParse(parse, nest, input, fragments, ranges);
}
class InnerParse {
    constructor(parser, parse, overlay, bracketed, target, from) {
        this.parser = parser;
        this.parse = parse;
        this.overlay = overlay;
        this.bracketed = bracketed;
        this.target = target;
        this.from = from;
    }
}
function checkRanges(ranges) {
    if (!ranges.length || ranges.some(r => r.from >= r.to))
        throw new RangeError("Invalid inner parse ranges given: " + JSON.stringify(ranges));
}
class ActiveOverlay {
    constructor(parser, predicate, mounts, index, start, bracketed, target, prev) {
        this.parser = parser;
        this.predicate = predicate;
        this.mounts = mounts;
        this.index = index;
        this.start = start;
        this.bracketed = bracketed;
        this.target = target;
        this.prev = prev;
        this.depth = 0;
        this.ranges = [];
    }
}
const stoppedInner = new NodeProp({ perNode: true });
class MixedParse {
    constructor(base, nest, input, fragments, ranges) {
        this.nest = nest;
        this.input = input;
        this.fragments = fragments;
        this.ranges = ranges;
        this.inner = [];
        this.innerDone = 0;
        this.baseTree = null;
        this.stoppedAt = null;
        this.baseParse = base;
    }
    advance() {
        if (this.baseParse) {
            let done = this.baseParse.advance();
            if (!done)
                return null;
            this.baseParse = null;
            this.baseTree = done;
            this.startInner();
            if (this.stoppedAt != null)
                for (let inner of this.inner)
                    inner.parse.stopAt(this.stoppedAt);
        }
        if (this.innerDone == this.inner.length) {
            let result = this.baseTree;
            if (this.stoppedAt != null)
                result = new Tree(result.type, result.children, result.positions, result.length, result.propValues.concat([[stoppedInner, this.stoppedAt]]));
            return result;
        }
        let inner = this.inner[this.innerDone], done = inner.parse.advance();
        if (done) {
            this.innerDone++;
            // This is a somewhat dodgy but super helpful hack where we
            // patch up nodes created by the inner parse (and thus
            // presumably not aliased anywhere else) to hold the information
            // about the inner parse.
            let props = Object.assign(Object.create(null), inner.target.props);
            props[NodeProp.mounted.id] = new MountedTree(done, inner.overlay, inner.parser, inner.bracketed);
            inner.target.props = props;
        }
        return null;
    }
    get parsedPos() {
        if (this.baseParse)
            return 0;
        let pos = this.input.length;
        for (let i = this.innerDone; i < this.inner.length; i++) {
            if (this.inner[i].from < pos)
                pos = Math.min(pos, this.inner[i].parse.parsedPos);
        }
        return pos;
    }
    stopAt(pos) {
        this.stoppedAt = pos;
        if (this.baseParse)
            this.baseParse.stopAt(pos);
        else
            for (let i = this.innerDone; i < this.inner.length; i++)
                this.inner[i].parse.stopAt(pos);
    }
    startInner() {
        let fragmentCursor = new FragmentCursor(this.fragments);
        let overlay = null;
        let covered = null;
        let cursor = new TreeCursor(new TreeNode(this.baseTree, this.ranges[0].from, 0, null), IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
        scan: for (let nest, isCovered;;) {
            let enter = true, range;
            if (this.stoppedAt != null && cursor.from >= this.stoppedAt) {
                enter = false;
            }
            else if (fragmentCursor.hasNode(cursor)) {
                if (overlay) {
                    let match = overlay.mounts.find(m => m.frag.from <= cursor.from && m.frag.to >= cursor.to && m.mount.overlay);
                    if (match)
                        for (let r of match.mount.overlay) {
                            let from = r.from + match.pos, to = r.to + match.pos;
                            if (from >= cursor.from && to <= cursor.to && !overlay.ranges.some(r => r.from < to && r.to > from))
                                overlay.ranges.push({ from, to });
                        }
                }
                enter = false;
            }
            else if (covered && (isCovered = checkCover(covered.ranges, cursor.from, cursor.to))) {
                enter = isCovered != 2 /* Cover.Full */;
            }
            else if (!cursor.type.isAnonymous && (nest = this.nest(cursor, this.input)) &&
                (cursor.from < cursor.to || !nest.overlay)) {
                if (!cursor.tree) {
                    materialize(cursor);
                    // materialize create one more level of nesting
                    // we need to add depth to active overlay for going backwards
                    if (overlay)
                        overlay.depth++;
                    if (covered)
                        covered.depth++;
                }
                let oldMounts = fragmentCursor.findMounts(cursor.from, nest.parser);
                if (typeof nest.overlay == "function") {
                    overlay = new ActiveOverlay(nest.parser, nest.overlay, oldMounts, this.inner.length, cursor.from, !!nest.bracketed, cursor.tree, overlay);
                }
                else {
                    let ranges = punchRanges(this.ranges, nest.overlay ||
                        (cursor.from < cursor.to ? [new dist_Range(cursor.from, cursor.to)] : []));
                    if (ranges.length)
                        checkRanges(ranges);
                    if (ranges.length || !nest.overlay)
                        this.inner.push(new InnerParse(nest.parser, ranges.length ? nest.parser.startParse(this.input, enterFragments(oldMounts, ranges), ranges)
                            : nest.parser.startParse(""), nest.overlay ? nest.overlay.map(r => new dist_Range(r.from - cursor.from, r.to - cursor.from)) : null, !!nest.bracketed, cursor.tree, ranges.length ? ranges[0].from : cursor.from));
                    if (!nest.overlay)
                        enter = false;
                    else if (ranges.length)
                        covered = { ranges, depth: 0, prev: covered };
                }
            }
            else if (overlay && (range = overlay.predicate(cursor))) {
                if (range === true)
                    range = new dist_Range(cursor.from, cursor.to);
                if (range.from < range.to) {
                    let last = overlay.ranges.length - 1;
                    if (last >= 0 && overlay.ranges[last].to == range.from)
                        overlay.ranges[last] = { from: overlay.ranges[last].from, to: range.to };
                    else
                        overlay.ranges.push(range);
                }
            }
            if (enter && cursor.firstChild()) {
                if (overlay)
                    overlay.depth++;
                if (covered)
                    covered.depth++;
            }
            else {
                for (;;) {
                    if (cursor.nextSibling())
                        break;
                    if (!cursor.parent())
                        break scan;
                    if (overlay && !--overlay.depth) {
                        let ranges = punchRanges(this.ranges, overlay.ranges);
                        if (ranges.length) {
                            checkRanges(ranges);
                            this.inner.splice(overlay.index, 0, new InnerParse(overlay.parser, overlay.parser.startParse(this.input, enterFragments(overlay.mounts, ranges), ranges), overlay.ranges.map(r => new dist_Range(r.from - overlay.start, r.to - overlay.start)), overlay.bracketed, overlay.target, ranges[0].from));
                        }
                        overlay = overlay.prev;
                    }
                    if (covered && !--covered.depth)
                        covered = covered.prev;
                }
            }
        }
    }
}
function checkCover(covered, from, to) {
    for (let range of covered) {
        if (range.from >= to)
            break;
        if (range.to > from)
            return range.from <= from && range.to >= to ? 2 /* Cover.Full */ : 1 /* Cover.Partial */;
    }
    return 0 /* Cover.None */;
}
// Take a piece of buffer and convert it into a stand-alone
// TreeBuffer.
function sliceBuf(buf, startI, endI, nodes, positions, off) {
    if (startI < endI) {
        let from = buf.buffer[startI + 1];
        nodes.push(buf.slice(startI, endI, from));
        positions.push(from - off);
    }
}
// This function takes a node that's in a buffer, and converts it, and
// its parent buffer nodes, into a Tree. This is again acting on the
// assumption that the trees and buffers have been constructed by the
// parse that was ran via the mix parser, and thus aren't shared with
// any other code, making violations of the immutability safe.
function materialize(cursor) {
    let { node } = cursor, stack = [];
    let buffer = node.context.buffer;
    // Scan up to the nearest tree
    do {
        stack.push(cursor.index);
        cursor.parent();
    } while (!cursor.tree);
    // Find the index of the buffer in that tree
    let base = cursor.tree, i = base.children.indexOf(buffer);
    let buf = base.children[i], b = buf.buffer, newStack = [i];
    // Split a level in the buffer, putting the nodes before and after
    // the child that contains `node` into new buffers.
    function split(startI, endI, type, innerOffset, length, stackPos) {
        let targetI = stack[stackPos];
        let children = [], positions = [];
        sliceBuf(buf, startI, targetI, children, positions, innerOffset);
        let from = b[targetI + 1], to = b[targetI + 2];
        newStack.push(children.length);
        let child = stackPos
            ? split(targetI + 4, b[targetI + 3], buf.set.types[b[targetI]], from, to - from, stackPos - 1)
            : node.toTree();
        children.push(child);
        positions.push(from - innerOffset);
        sliceBuf(buf, b[targetI + 3], endI, children, positions, innerOffset);
        return new Tree(type, children, positions, length);
    }
    base.children[i] = split(0, b.length, dist_NodeType.none, 0, buf.length, stack.length - 1);
    // Move the cursor back to the target node
    for (let index of newStack) {
        let tree = cursor.tree.children[index], pos = cursor.tree.positions[index];
        cursor.yield(new TreeNode(tree, pos + cursor.from, index, cursor._tree));
    }
}
class StructureCursor {
    constructor(root, offset) {
        this.offset = offset;
        this.done = false;
        this.cursor = root.cursor(IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
    }
    // Move to the first node (in pre-order) that starts at or after `pos`.
    moveTo(pos) {
        let { cursor } = this, p = pos - this.offset;
        while (!this.done && cursor.from < p) {
            if (cursor.to >= pos && cursor.enter(p, 1, IterMode.IgnoreOverlays | IterMode.ExcludeBuffers)) ;
            else if (!cursor.next(false))
                this.done = true;
        }
    }
    hasNode(cursor) {
        this.moveTo(cursor.from);
        if (!this.done && this.cursor.from + this.offset == cursor.from && this.cursor.tree) {
            for (let tree = this.cursor.tree;;) {
                if (tree == cursor.tree)
                    return true;
                if (tree.children.length && tree.positions[0] == 0 && tree.children[0] instanceof Tree)
                    tree = tree.children[0];
                else
                    break;
            }
        }
        return false;
    }
}
class FragmentCursor {
    constructor(fragments) {
        var _a;
        this.fragments = fragments;
        this.curTo = 0;
        this.fragI = 0;
        if (fragments.length) {
            let first = this.curFrag = fragments[0];
            this.curTo = (_a = first.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : first.to;
            this.inner = new StructureCursor(first.tree, -first.offset);
        }
        else {
            this.curFrag = this.inner = null;
        }
    }
    hasNode(node) {
        while (this.curFrag && node.from >= this.curTo)
            this.nextFrag();
        return this.curFrag && this.curFrag.from <= node.from && this.curTo >= node.to && this.inner.hasNode(node);
    }
    nextFrag() {
        var _a;
        this.fragI++;
        if (this.fragI == this.fragments.length) {
            this.curFrag = this.inner = null;
        }
        else {
            let frag = this.curFrag = this.fragments[this.fragI];
            this.curTo = (_a = frag.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : frag.to;
            this.inner = new StructureCursor(frag.tree, -frag.offset);
        }
    }
    findMounts(pos, parser) {
        var _a;
        let result = [];
        if (this.inner) {
            this.inner.cursor.moveTo(pos, 1);
            for (let pos = this.inner.cursor.node; pos; pos = pos.parent) {
                let mount = (_a = pos.tree) === null || _a === void 0 ? void 0 : _a.prop(NodeProp.mounted);
                if (mount && mount.parser == parser) {
                    for (let i = this.fragI; i < this.fragments.length; i++) {
                        let frag = this.fragments[i];
                        if (frag.from >= pos.to)
                            break;
                        if (frag.tree == this.curFrag.tree)
                            result.push({
                                frag,
                                pos: pos.from - frag.offset,
                                mount
                            });
                    }
                }
            }
        }
        return result;
    }
}
function punchRanges(outer, ranges) {
    let copy = null, current = ranges;
    for (let i = 1, j = 0; i < outer.length; i++) {
        let gapFrom = outer[i - 1].to, gapTo = outer[i].from;
        for (; j < current.length; j++) {
            let r = current[j];
            if (r.from >= gapTo)
                break;
            if (r.to <= gapFrom)
                continue;
            if (!copy)
                current = copy = ranges.slice();
            if (r.from < gapFrom) {
                copy[j] = new dist_Range(r.from, gapFrom);
                if (r.to > gapTo)
                    copy.splice(j + 1, 0, new dist_Range(gapTo, r.to));
            }
            else if (r.to > gapTo) {
                copy[j--] = new dist_Range(gapTo, r.to);
            }
            else {
                copy.splice(j--, 1);
            }
        }
    }
    return current;
}
function findCoverChanges(a, b, from, to) {
    let iA = 0, iB = 0, inA = false, inB = false, pos = -1e9;
    let result = [];
    for (;;) {
        let nextA = iA == a.length ? 1e9 : inA ? a[iA].to : a[iA].from;
        let nextB = iB == b.length ? 1e9 : inB ? b[iB].to : b[iB].from;
        if (inA != inB) {
            let start = Math.max(pos, from), end = Math.min(nextA, nextB, to);
            if (start < end)
                result.push(new dist_Range(start, end));
        }
        pos = Math.min(nextA, nextB);
        if (pos == 1e9)
            break;
        if (nextA == pos) {
            if (!inA)
                inA = true;
            else {
                inA = false;
                iA++;
            }
        }
        if (nextB == pos) {
            if (!inB)
                inB = true;
            else {
                inB = false;
                iB++;
            }
        }
    }
    return result;
}
// Given a number of fragments for the outer tree, and a set of ranges
// to parse, find fragments for inner trees mounted around those
// ranges, if any.
function enterFragments(mounts, ranges) {
    let result = [];
    for (let { pos, mount, frag } of mounts) {
        let startPos = pos + (mount.overlay ? mount.overlay[0].from : 0), endPos = startPos + mount.tree.length;
        let from = Math.max(frag.from, startPos), to = Math.min(frag.to, endPos);
        if (mount.overlay) {
            let overlay = mount.overlay.map(r => new dist_Range(r.from + pos, r.to + pos));
            let changes = findCoverChanges(ranges, overlay, from, to);
            for (let i = 0, pos = from;; i++) {
                let last = i == changes.length, end = last ? to : changes[i].from;
                if (end > pos)
                    result.push(new TreeFragment(pos, end, mount.tree, -startPos, frag.from >= pos || frag.openStart, frag.to <= end || frag.openEnd));
                if (last)
                    break;
                pos = changes[i].to;
            }
        }
        else {
            result.push(new TreeFragment(from, to, mount.tree, -startPos, frag.from >= startPos || frag.openStart, frag.to <= endPos || frag.openEnd));
        }
    }
    return result;
}



;// ../../node_modules/@lezer/highlight/dist/index.js


let nextTagID = 0;
/**
Highlighting tags are markers that denote a highlighting category.
They are [associated](#highlight.styleTags) with parts of a syntax
tree by a language mode, and then mapped to an actual CSS style by
a [highlighter](#highlight.Highlighter).

Because syntax tree node types and highlight styles have to be
able to talk the same language, CodeMirror uses a mostly _closed_
[vocabulary](#highlight.tags) of syntax tags (as opposed to
traditional open string-based systems, which make it hard for
highlighting themes to cover all the tokens produced by the
various languages).

It _is_ possible to [define](#highlight.Tag^define) your own
highlighting tags for system-internal use (where you control both
the language package and the highlighter), but such tags will not
be picked up by regular highlighters (though you can derive them
from standard tags to allow highlighters to fall back to those).
*/
class Tag {
    /**
    @internal
    */
    constructor(
    /**
    The optional name of the base tag @internal
    */
    name, 
    /**
    The set of this tag and all its parent tags, starting with
    this one itself and sorted in order of decreasing specificity.
    */
    set, 
    /**
    The base unmodified tag that this one is based on, if it's
    modified @internal
    */
    base, 
    /**
    The modifiers applied to this.base @internal
    */
    modified) {
        this.name = name;
        this.set = set;
        this.base = base;
        this.modified = modified;
        /**
        @internal
        */
        this.id = nextTagID++;
    }
    toString() {
        let { name } = this;
        for (let mod of this.modified)
            if (mod.name)
                name = `${mod.name}(${name})`;
        return name;
    }
    static define(nameOrParent, parent) {
        let name = typeof nameOrParent == "string" ? nameOrParent : "?";
        if (nameOrParent instanceof Tag)
            parent = nameOrParent;
        if (parent === null || parent === void 0 ? void 0 : parent.base)
            throw new Error("Can not derive from a modified tag");
        let tag = new Tag(name, [], null, []);
        tag.set.push(tag);
        if (parent)
            for (let t of parent.set)
                tag.set.push(t);
        return tag;
    }
    /**
    Define a tag _modifier_, which is a function that, given a tag,
    will return a tag that is a subtag of the original. Applying the
    same modifier to a twice tag will return the same value (`m1(t1)
    == m1(t1)`) and applying multiple modifiers will, regardless or
    order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
    
    When multiple modifiers are applied to a given base tag, each
    smaller set of modifiers is registered as a parent, so that for
    example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
    `m1(m3(t1)`, and so on.
    */
    static defineModifier(name) {
        let mod = new Modifier(name);
        return (tag) => {
            if (tag.modified.indexOf(mod) > -1)
                return tag;
            return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
        };
    }
}
let nextModifierID = 0;
class Modifier {
    constructor(name) {
        this.name = name;
        this.instances = [];
        this.id = nextModifierID++;
    }
    static get(base, mods) {
        if (!mods.length)
            return base;
        let exists = mods[0].instances.find(t => t.base == base && dist_sameArray(mods, t.modified));
        if (exists)
            return exists;
        let set = [], tag = new Tag(base.name, set, base, mods);
        for (let m of mods)
            m.instances.push(tag);
        let configs = powerSet(mods);
        for (let parent of base.set)
            if (!parent.modified.length)
                for (let config of configs)
                    set.push(Modifier.get(parent, config));
        return tag;
    }
}
function dist_sameArray(a, b) {
    return a.length == b.length && a.every((x, i) => x == b[i]);
}
function powerSet(array) {
    let sets = [[]];
    for (let i = 0; i < array.length; i++) {
        for (let j = 0, e = sets.length; j < e; j++) {
            sets.push(sets[j].concat(array[i]));
        }
    }
    return sets.sort((a, b) => b.length - a.length);
}
/**
This function is used to add a set of tags to a language syntax
via [`NodeSet.extend`](#common.NodeSet.extend) or
[`LRParser.configure`](#lr.LRParser.configure).

The argument object maps node selectors to [highlighting
tags](#highlight.Tag) or arrays of tags.

Node selectors may hold one or more (space-separated) node paths.
Such a path can be a [node name](#common.NodeType.name), or
multiple node names (or `*` wildcards) separated by slash
characters, as in `"Block/Declaration/VariableName"`. Such a path
matches the final node but only if its direct parent nodes are the
other nodes mentioned. A `*` in such a path matches any parent,
but only a single level—wildcards that match multiple parents
aren't supported, both for efficiency reasons and because Lezer
trees make it rather hard to reason about what they would match.)

A path can be ended with `/...` to indicate that the tag assigned
to the node should also apply to all child nodes, even if they
match their own style (by default, only the innermost style is
used).

When a path ends in `!`, as in `Attribute!`, no further matching
happens for the node's child nodes, and the entire node gets the
given style.

In this notation, node names that contain `/`, `!`, `*`, or `...`
must be quoted as JSON strings.

For example:

```javascript
parser.configure({props: [
  styleTags({
    // Style Number and BigNumber nodes
    "Number BigNumber": tags.number,
    // Style Escape nodes whose parent is String
    "String/Escape": tags.escape,
    // Style anything inside Attributes nodes
    "Attributes!": tags.meta,
    // Add a style to all content inside Italic nodes
    "Italic/...": tags.emphasis,
    // Style InvalidString nodes as both `string` and `invalid`
    "InvalidString": [tags.string, tags.invalid],
    // Style the node named "/" as punctuation
    '"/"': tags.punctuation
  })
]})
```
*/
function styleTags(spec) {
    let byName = Object.create(null);
    for (let prop in spec) {
        let tags = spec[prop];
        if (!Array.isArray(tags))
            tags = [tags];
        for (let part of prop.split(" "))
            if (part) {
                let pieces = [], mode = 2 /* Mode.Normal */, rest = part;
                for (let pos = 0;;) {
                    if (rest == "..." && pos > 0 && pos + 3 == part.length) {
                        mode = 1 /* Mode.Inherit */;
                        break;
                    }
                    let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
                    if (!m)
                        throw new RangeError("Invalid path: " + part);
                    pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]);
                    pos += m[0].length;
                    if (pos == part.length)
                        break;
                    let next = part[pos++];
                    if (pos == part.length && next == "!") {
                        mode = 0 /* Mode.Opaque */;
                        break;
                    }
                    if (next != "/")
                        throw new RangeError("Invalid path: " + part);
                    rest = part.slice(pos);
                }
                let last = pieces.length - 1, inner = pieces[last];
                if (!inner)
                    throw new RangeError("Invalid path: " + part);
                let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null);
                byName[inner] = rule.sort(byName[inner]);
            }
    }
    return ruleNodeProp.add(byName);
}
const ruleNodeProp = new NodeProp({
    combine(a, b) {
        let cur, root, take;
        while (a || b) {
            if (!a || b && a.depth >= b.depth) {
                take = b;
                b = b.next;
            }
            else {
                take = a;
                a = a.next;
            }
            if (cur && cur.mode == take.mode && !take.context && !cur.context)
                continue;
            let copy = new Rule(take.tags, take.mode, take.context);
            if (cur)
                cur.next = copy;
            else
                root = copy;
            cur = copy;
        }
        return root;
    }
});
class Rule {
    constructor(tags, mode, context, next) {
        this.tags = tags;
        this.mode = mode;
        this.context = context;
        this.next = next;
    }
    get opaque() { return this.mode == 0 /* Mode.Opaque */; }
    get inherit() { return this.mode == 1 /* Mode.Inherit */; }
    sort(other) {
        if (!other || other.depth < this.depth) {
            this.next = other;
            return this;
        }
        other.next = this.sort(other.next);
        return other;
    }
    get depth() { return this.context ? this.context.length : 0; }
}
Rule.empty = new Rule([], 2 /* Mode.Normal */, null);
/**
Define a [highlighter](#highlight.Highlighter) from an array of
tag/class pairs. Classes associated with more specific tags will
take precedence.
*/
function tagHighlighter(tags, options) {
    let map = Object.create(null);
    for (let style of tags) {
        if (!Array.isArray(style.tag))
            map[style.tag.id] = style.class;
        else
            for (let tag of style.tag)
                map[tag.id] = style.class;
    }
    let { scope, all = null } = options || {};
    return {
        style: (tags) => {
            let cls = all;
            for (let tag of tags) {
                for (let sub of tag.set) {
                    let tagClass = map[sub.id];
                    if (tagClass) {
                        cls = cls ? cls + " " + tagClass : tagClass;
                        break;
                    }
                }
            }
            return cls;
        },
        scope
    };
}
function highlightTags(highlighters, tags) {
    let result = null;
    for (let highlighter of highlighters) {
        let value = highlighter.style(tags);
        if (value)
            result = result ? result + " " + value : value;
    }
    return result;
}
/**
Highlight the given [tree](#common.Tree) with the given
[highlighter](#highlight.Highlighter). Often, the higher-level
[`highlightCode`](#highlight.highlightCode) function is easier to
use.
*/
function highlightTree(tree, highlighter, 
/**
Assign styling to a region of the text. Will be called, in order
of position, for any ranges where more than zero classes apply.
`classes` is a space separated string of CSS classes.
*/
putStyle, 
/**
The start of the range to highlight.
*/
from = 0, 
/**
The end of the range.
*/
to = tree.length) {
    let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
    builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
    builder.flush(to);
}
/**
Highlight the given tree with the given highlighter, calling
`putText` for every piece of text, either with a set of classes or
with the empty string when unstyled, and `putBreak` for every line
break.
*/
function highlightCode(code, tree, highlighter, putText, putBreak, from = 0, to = code.length) {
    let pos = from;
    function writeTo(p, classes) {
        if (p <= pos)
            return;
        for (let text = code.slice(pos, p), i = 0;;) {
            let nextBreak = text.indexOf("\n", i);
            let upto = nextBreak < 0 ? text.length : nextBreak;
            if (upto > i)
                putText(text.slice(i, upto), classes);
            if (nextBreak < 0)
                break;
            putBreak();
            i = nextBreak + 1;
        }
        pos = p;
    }
    highlightTree(tree, highlighter, (from, to, classes) => {
        writeTo(from, "");
        writeTo(to, classes);
    }, from, to);
    writeTo(to, "");
}
class HighlightBuilder {
    constructor(at, highlighters, span) {
        this.at = at;
        this.highlighters = highlighters;
        this.span = span;
        this.class = "";
    }
    startSpan(at, cls) {
        if (cls != this.class) {
            this.flush(at);
            if (at > this.at)
                this.at = at;
            this.class = cls;
        }
    }
    flush(to) {
        if (to > this.at && this.class)
            this.span(this.at, to, this.class);
    }
    highlightRange(cursor, from, to, inheritedClass, highlighters) {
        let { type, from: start, to: end } = cursor;
        if (start >= to || end <= from)
            return;
        if (type.isTop)
            highlighters = this.highlighters.filter(h => !h.scope || h.scope(type));
        let cls = inheritedClass;
        let rule = getStyleTags(cursor) || Rule.empty;
        let tagCls = highlightTags(highlighters, rule.tags);
        if (tagCls) {
            if (cls)
                cls += " ";
            cls += tagCls;
            if (rule.mode == 1 /* Mode.Inherit */)
                inheritedClass += (inheritedClass ? " " : "") + tagCls;
        }
        this.startSpan(Math.max(from, start), cls);
        if (rule.opaque)
            return;
        let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted);
        if (mounted && mounted.overlay) {
            let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
            let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type));
            let hasChild = cursor.firstChild();
            for (let i = 0, pos = start;; i++) {
                let next = i < mounted.overlay.length ? mounted.overlay[i] : null;
                let nextPos = next ? next.from + start : end;
                let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos);
                if (rangeFrom < rangeTo && hasChild) {
                    while (cursor.from < rangeTo) {
                        this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters);
                        this.startSpan(Math.min(rangeTo, cursor.to), cls);
                        if (cursor.to >= nextPos || !cursor.nextSibling())
                            break;
                    }
                }
                if (!next || nextPos > to)
                    break;
                pos = next.to + start;
                if (pos > from) {
                    this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), "", innerHighlighters);
                    this.startSpan(Math.min(to, pos), cls);
                }
            }
            if (hasChild)
                cursor.parent();
        }
        else if (cursor.firstChild()) {
            if (mounted)
                inheritedClass = "";
            do {
                if (cursor.to <= from)
                    continue;
                if (cursor.from >= to)
                    break;
                this.highlightRange(cursor, from, to, inheritedClass, highlighters);
                this.startSpan(Math.min(to, cursor.to), cls);
            } while (cursor.nextSibling());
            cursor.parent();
        }
    }
}
/**
Match a syntax node's [highlight rules](#highlight.styleTags). If
there's a match, return its set of tags, and whether it is
opaque (uses a `!`) or applies to all child nodes (`/...`).
*/
function getStyleTags(node) {
    let rule = node.type.prop(ruleNodeProp);
    while (rule && rule.context && !node.matchContext(rule.context))
        rule = rule.next;
    return rule || null;
}
const t = Tag.define;
const comment = t(), dist_name = t(), typeName = t(dist_name), propertyName = t(dist_name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t();
/**
The default set of highlighting [tags](#highlight.Tag).

This collection is heavily biased towards programming languages,
and necessarily incomplete. A full ontology of syntactic
constructs would fill a stack of books, and be impractical to
write themes for. So try to make do with this set. If all else
fails, [open an
issue](https://github.com/codemirror/codemirror.next) to propose a
new tag, or [define](#highlight.Tag^define) a local custom tag for
your use case.

Note that it is not obligatory to always attach the most specific
tag possible to an element—if your grammar can't easily
distinguish a certain type of element (such as a local variable),
it is okay to style it as its more general variant (a variable).

For tags that extend some parent tag, the documentation links to
the parent.
*/
const tags = {
    /**
    A comment.
    */
    comment,
    /**
    A line [comment](#highlight.tags.comment).
    */
    lineComment: t(comment),
    /**
    A block [comment](#highlight.tags.comment).
    */
    blockComment: t(comment),
    /**
    A documentation [comment](#highlight.tags.comment).
    */
    docComment: t(comment),
    /**
    Any kind of identifier.
    */
    name: dist_name,
    /**
    The [name](#highlight.tags.name) of a variable.
    */
    variableName: t(dist_name),
    /**
    A type [name](#highlight.tags.name).
    */
    typeName: typeName,
    /**
    A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
    */
    tagName: t(typeName),
    /**
    A property or field [name](#highlight.tags.name).
    */
    propertyName: propertyName,
    /**
    An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
    */
    attributeName: t(propertyName),
    /**
    The [name](#highlight.tags.name) of a class.
    */
    className: t(dist_name),
    /**
    A label [name](#highlight.tags.name).
    */
    labelName: t(dist_name),
    /**
    A namespace [name](#highlight.tags.name).
    */
    namespace: t(dist_name),
    /**
    The [name](#highlight.tags.name) of a macro.
    */
    macroName: t(dist_name),
    /**
    A literal value.
    */
    literal,
    /**
    A string [literal](#highlight.tags.literal).
    */
    string,
    /**
    A documentation [string](#highlight.tags.string).
    */
    docString: t(string),
    /**
    A character literal (subtag of [string](#highlight.tags.string)).
    */
    character: t(string),
    /**
    An attribute value (subtag of [string](#highlight.tags.string)).
    */
    attributeValue: t(string),
    /**
    A number [literal](#highlight.tags.literal).
    */
    number,
    /**
    An integer [number](#highlight.tags.number) literal.
    */
    integer: t(number),
    /**
    A floating-point [number](#highlight.tags.number) literal.
    */
    float: t(number),
    /**
    A boolean [literal](#highlight.tags.literal).
    */
    bool: t(literal),
    /**
    Regular expression [literal](#highlight.tags.literal).
    */
    regexp: t(literal),
    /**
    An escape [literal](#highlight.tags.literal), for example a
    backslash escape in a string.
    */
    escape: t(literal),
    /**
    A color [literal](#highlight.tags.literal).
    */
    color: t(literal),
    /**
    A URL [literal](#highlight.tags.literal).
    */
    url: t(literal),
    /**
    A language keyword.
    */
    keyword,
    /**
    The [keyword](#highlight.tags.keyword) for the self or this
    object.
    */
    self: t(keyword),
    /**
    The [keyword](#highlight.tags.keyword) for null.
    */
    null: t(keyword),
    /**
    A [keyword](#highlight.tags.keyword) denoting some atomic value.
    */
    atom: t(keyword),
    /**
    A [keyword](#highlight.tags.keyword) that represents a unit.
    */
    unit: t(keyword),
    /**
    A modifier [keyword](#highlight.tags.keyword).
    */
    modifier: t(keyword),
    /**
    A [keyword](#highlight.tags.keyword) that acts as an operator.
    */
    operatorKeyword: t(keyword),
    /**
    A control-flow related [keyword](#highlight.tags.keyword).
    */
    controlKeyword: t(keyword),
    /**
    A [keyword](#highlight.tags.keyword) that defines something.
    */
    definitionKeyword: t(keyword),
    /**
    A [keyword](#highlight.tags.keyword) related to defining or
    interfacing with modules.
    */
    moduleKeyword: t(keyword),
    /**
    An operator.
    */
    operator,
    /**
    An [operator](#highlight.tags.operator) that dereferences something.
    */
    derefOperator: t(operator),
    /**
    Arithmetic-related [operator](#highlight.tags.operator).
    */
    arithmeticOperator: t(operator),
    /**
    Logical [operator](#highlight.tags.operator).
    */
    logicOperator: t(operator),
    /**
    Bit [operator](#highlight.tags.operator).
    */
    bitwiseOperator: t(operator),
    /**
    Comparison [operator](#highlight.tags.operator).
    */
    compareOperator: t(operator),
    /**
    [Operator](#highlight.tags.operator) that updates its operand.
    */
    updateOperator: t(operator),
    /**
    [Operator](#highlight.tags.operator) that defines something.
    */
    definitionOperator: t(operator),
    /**
    Type-related [operator](#highlight.tags.operator).
    */
    typeOperator: t(operator),
    /**
    Control-flow [operator](#highlight.tags.operator).
    */
    controlOperator: t(operator),
    /**
    Program or markup punctuation.
    */
    punctuation,
    /**
    [Punctuation](#highlight.tags.punctuation) that separates
    things.
    */
    separator: t(punctuation),
    /**
    Bracket-style [punctuation](#highlight.tags.punctuation).
    */
    bracket,
    /**
    Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
    tokens).
    */
    angleBracket: t(bracket),
    /**
    Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
    tokens).
    */
    squareBracket: t(bracket),
    /**
    Parentheses (usually `(` and `)` tokens). Subtag of
    [bracket](#highlight.tags.bracket).
    */
    paren: t(bracket),
    /**
    Braces (usually `{` and `}` tokens). Subtag of
    [bracket](#highlight.tags.bracket).
    */
    brace: t(bracket),
    /**
    Content, for example plain text in XML or markup documents.
    */
    content,
    /**
    [Content](#highlight.tags.content) that represents a heading.
    */
    heading,
    /**
    A level 1 [heading](#highlight.tags.heading).
    */
    heading1: t(heading),
    /**
    A level 2 [heading](#highlight.tags.heading).
    */
    heading2: t(heading),
    /**
    A level 3 [heading](#highlight.tags.heading).
    */
    heading3: t(heading),
    /**
    A level 4 [heading](#highlight.tags.heading).
    */
    heading4: t(heading),
    /**
    A level 5 [heading](#highlight.tags.heading).
    */
    heading5: t(heading),
    /**
    A level 6 [heading](#highlight.tags.heading).
    */
    heading6: t(heading),
    /**
    A prose [content](#highlight.tags.content) separator (such as a horizontal rule).
    */
    contentSeparator: t(content),
    /**
    [Content](#highlight.tags.content) that represents a list.
    */
    list: t(content),
    /**
    [Content](#highlight.tags.content) that represents a quote.
    */
    quote: t(content),
    /**
    [Content](#highlight.tags.content) that is emphasized.
    */
    emphasis: t(content),
    /**
    [Content](#highlight.tags.content) that is styled strong.
    */
    strong: t(content),
    /**
    [Content](#highlight.tags.content) that is part of a link.
    */
    link: t(content),
    /**
    [Content](#highlight.tags.content) that is styled as code or
    monospace.
    */
    monospace: t(content),
    /**
    [Content](#highlight.tags.content) that has a strike-through
    style.
    */
    strikethrough: t(content),
    /**
    Inserted text in a change-tracking format.
    */
    inserted: t(),
    /**
    Deleted text.
    */
    deleted: t(),
    /**
    Changed text.
    */
    changed: t(),
    /**
    An invalid or unsyntactic element.
    */
    invalid: t(),
    /**
    Metadata or meta-instruction.
    */
    meta,
    /**
    [Metadata](#highlight.tags.meta) that applies to the entire
    document.
    */
    documentMeta: t(meta),
    /**
    [Metadata](#highlight.tags.meta) that annotates or adds
    attributes to a given syntactic element.
    */
    annotation: t(meta),
    /**
    Processing instruction or preprocessor directive. Subtag of
    [meta](#highlight.tags.meta).
    */
    processingInstruction: t(meta),
    /**
    [Modifier](#highlight.Tag^defineModifier) that indicates that a
    given element is being defined. Expected to be used with the
    various [name](#highlight.tags.name) tags.
    */
    definition: Tag.defineModifier("definition"),
    /**
    [Modifier](#highlight.Tag^defineModifier) that indicates that
    something is constant. Mostly expected to be used with
    [variable names](#highlight.tags.variableName).
    */
    constant: Tag.defineModifier("constant"),
    /**
    [Modifier](#highlight.Tag^defineModifier) used to indicate that
    a [variable](#highlight.tags.variableName) or [property
    name](#highlight.tags.propertyName) is being called or defined
    as a function.
    */
    function: Tag.defineModifier("function"),
    /**
    [Modifier](#highlight.Tag^defineModifier) that can be applied to
    [names](#highlight.tags.name) to indicate that they belong to
    the language's standard environment.
    */
    standard: Tag.defineModifier("standard"),
    /**
    [Modifier](#highlight.Tag^defineModifier) that indicates a given
    [names](#highlight.tags.name) is local to some scope.
    */
    local: Tag.defineModifier("local"),
    /**
    A generic variant [modifier](#highlight.Tag^defineModifier) that
    can be used to tag language-specific alternative variants of
    some common tag. It is recommended for themes to define special
    forms of at least the [string](#highlight.tags.string) and
    [variable name](#highlight.tags.variableName) tags, since those
    come up a lot.
    */
    special: Tag.defineModifier("special")
};
for (let name in tags) {
    let val = tags[name];
    if (val instanceof Tag)
        val.name = name;
}
/**
This is a highlighter that adds stable, predictable classes to
tokens, for styling with external CSS.

The following tags are mapped to their name prefixed with `"tok-"`
(for example `"tok-comment"`):

* [`link`](#highlight.tags.link)
* [`heading`](#highlight.tags.heading)
* [`emphasis`](#highlight.tags.emphasis)
* [`strong`](#highlight.tags.strong)
* [`keyword`](#highlight.tags.keyword)
* [`atom`](#highlight.tags.atom)
* [`bool`](#highlight.tags.bool)
* [`url`](#highlight.tags.url)
* [`labelName`](#highlight.tags.labelName)
* [`inserted`](#highlight.tags.inserted)
* [`deleted`](#highlight.tags.deleted)
* [`literal`](#highlight.tags.literal)
* [`string`](#highlight.tags.string)
* [`number`](#highlight.tags.number)
* [`variableName`](#highlight.tags.variableName)
* [`typeName`](#highlight.tags.typeName)
* [`namespace`](#highlight.tags.namespace)
* [`className`](#highlight.tags.className)
* [`macroName`](#highlight.tags.macroName)
* [`propertyName`](#highlight.tags.propertyName)
* [`operator`](#highlight.tags.operator)
* [`comment`](#highlight.tags.comment)
* [`meta`](#highlight.tags.meta)
* [`punctuation`](#highlight.tags.punctuation)
* [`invalid`](#highlight.tags.invalid)

In addition, these mappings are provided:

* [`regexp`](#highlight.tags.regexp),
  [`escape`](#highlight.tags.escape), and
  [`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string)
  are mapped to `"tok-string2"`
* [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName)
  to `"tok-variableName2"`
* [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName)
  to `"tok-variableName tok-local"`
* [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName)
  to `"tok-variableName tok-definition"`
* [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName)
  to `"tok-propertyName tok-definition"`
*/
const classHighlighter = tagHighlighter([
    { tag: tags.link, class: "tok-link" },
    { tag: tags.heading, class: "tok-heading" },
    { tag: tags.emphasis, class: "tok-emphasis" },
    { tag: tags.strong, class: "tok-strong" },
    { tag: tags.keyword, class: "tok-keyword" },
    { tag: tags.atom, class: "tok-atom" },
    { tag: tags.bool, class: "tok-bool" },
    { tag: tags.url, class: "tok-url" },
    { tag: tags.labelName, class: "tok-labelName" },
    { tag: tags.inserted, class: "tok-inserted" },
    { tag: tags.deleted, class: "tok-deleted" },
    { tag: tags.literal, class: "tok-literal" },
    { tag: tags.string, class: "tok-string" },
    { tag: tags.number, class: "tok-number" },
    { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" },
    { tag: tags.variableName, class: "tok-variableName" },
    { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" },
    { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" },
    { tag: tags.special(tags.variableName), class: "tok-variableName2" },
    { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" },
    { tag: tags.typeName, class: "tok-typeName" },
    { tag: tags.namespace, class: "tok-namespace" },
    { tag: tags.className, class: "tok-className" },
    { tag: tags.macroName, class: "tok-macroName" },
    { tag: tags.propertyName, class: "tok-propertyName" },
    { tag: tags.operator, class: "tok-operator" },
    { tag: tags.comment, class: "tok-comment" },
    { tag: tags.meta, class: "tok-meta" },
    { tag: tags.invalid, class: "tok-invalid" },
    { tag: tags.punctuation, class: "tok-punctuation" }
]);



;// ../../node_modules/@codemirror/language/dist/index.js






var _a;
/**
Node prop stored in a parser's top syntax node to provide the
facet that stores language-specific data for that language.
*/
const languageDataProp = /*@__PURE__*/new NodeProp();
/**
Helper function to define a facet (to be added to the top syntax
node(s) for a language via
[`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be
used to associate language data with the language. You
probably only need this when subclassing
[`Language`](https://codemirror.net/6/docs/ref/#language.Language).
*/
function defineLanguageFacet(baseData) {
    return Facet.define({
        combine: baseData ? values => values.concat(baseData) : undefined
    });
}
/**
Syntax node prop used to register sublanguages. Should be added to
the top level node type for the language.
*/
const sublanguageProp = /*@__PURE__*/new NodeProp();
/**
A language object manages parsing and per-language
[metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is
managed as a [Lezer](https://lezer.codemirror.net) tree. The class
can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage)
subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or
via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass
for stream parsers.
*/
class Language {
    /**
    Construct a language object. If you need to invoke this
    directly, first define a data facet with
    [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
    configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
    to the language's outer syntax node.
    */
    constructor(
    /**
    The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet
    used for this language.
    */
    data, parser, extraExtensions = [], 
    /**
    A language name.
    */
    name = "") {
        this.data = data;
        this.name = name;
        // Kludge to define EditorState.tree as a debugging helper,
        // without the EditorState package actually knowing about
        // languages and lezer trees.
        if (!dist_EditorState.prototype.hasOwnProperty("tree"))
            Object.defineProperty(dist_EditorState.prototype, "tree", { get() { return dist_syntaxTree(this); } });
        this.parser = parser;
        this.extension = [
            language.of(this),
            dist_EditorState.languageData.of((state, pos, side) => {
                let top = topNodeAt(state, pos, side), data = top.type.prop(languageDataProp);
                if (!data)
                    return [];
                let base = state.facet(data), sub = top.type.prop(sublanguageProp);
                if (sub) {
                    let innerNode = top.resolve(pos - top.from, side);
                    for (let sublang of sub)
                        if (sublang.test(innerNode, state)) {
                            let data = state.facet(sublang.facet);
                            return sublang.type == "replace" ? data : data.concat(base);
                        }
                }
                return base;
            })
        ].concat(extraExtensions);
    }
    /**
    Query whether this language is active at the given position.
    */
    isActiveAt(state, pos, side = -1) {
        return topNodeAt(state, pos, side).type.prop(languageDataProp) == this.data;
    }
    /**
    Find the document regions that were parsed using this language.
    The returned regions will _include_ any nested languages rooted
    in this language, when those exist.
    */
    findRegions(state) {
        let lang = state.facet(language);
        if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)
            return [{ from: 0, to: state.doc.length }];
        if (!lang || !lang.allowsNesting)
            return [];
        let result = [];
        let explore = (tree, from) => {
            if (tree.prop(languageDataProp) == this.data) {
                result.push({ from, to: from + tree.length });
                return;
            }
            let mount = tree.prop(NodeProp.mounted);
            if (mount) {
                if (mount.tree.prop(languageDataProp) == this.data) {
                    if (mount.overlay)
                        for (let r of mount.overlay)
                            result.push({ from: r.from + from, to: r.to + from });
                    else
                        result.push({ from: from, to: from + tree.length });
                    return;
                }
                else if (mount.overlay) {
                    let size = result.length;
                    explore(mount.tree, mount.overlay[0].from + from);
                    if (result.length > size)
                        return;
                }
            }
            for (let i = 0; i < tree.children.length; i++) {
                let ch = tree.children[i];
                if (ch instanceof Tree)
                    explore(ch, tree.positions[i] + from);
            }
        };
        explore(dist_syntaxTree(state), 0);
        return result;
    }
    /**
    Indicates whether this language allows nested languages. The
    default implementation returns true.
    */
    get allowsNesting() { return true; }
}
/**
@internal
*/
Language.setState = /*@__PURE__*/dist_StateEffect.define();
function topNodeAt(state, pos, side) {
    let topLang = state.facet(language), tree = dist_syntaxTree(state).topNode;
    if (!topLang || topLang.allowsNesting) {
        for (let node = tree; node; node = node.enter(pos, side, IterMode.ExcludeBuffers | IterMode.EnterBracketed))
            if (node.type.isTop)
                tree = node;
    }
    return tree;
}
/**
A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer
[LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser)
parsers.
*/
class LRLanguage extends Language {
    constructor(data, parser, name) {
        super(data, parser, [], name);
        this.parser = parser;
    }
    /**
    Define a language from a parser.
    */
    static define(spec) {
        let data = defineLanguageFacet(spec.languageData);
        return new LRLanguage(data, spec.parser.configure({
            props: [languageDataProp.add(type => type.isTop ? data : undefined)]
        }), spec.name);
    }
    /**
    Create a new instance of this language with a reconfigured
    version of its parser and optionally a new name.
    */
    configure(options, name) {
        return new LRLanguage(this.data, this.parser.configure(options), name || this.name);
    }
    get allowsNesting() { return this.parser.hasWrappers(); }
}
/**
Get the syntax tree for a state, which is the current (possibly
incomplete) parse tree of the active
[language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no
language available.
*/
function dist_syntaxTree(state) {
    let field = state.field(Language.state, false);
    return field ? field.tree : Tree.empty;
}
/**
Try to get a parse tree that spans at least up to `upto`. The
method will do at most `timeout` milliseconds of work to parse
up to that point if the tree isn't already available.
*/
function ensureSyntaxTree(state, upto, timeout = 50) {
    var _a;
    let parse = (_a = state.field(Language.state, false)) === null || _a === void 0 ? void 0 : _a.context;
    if (!parse)
        return null;
    let oldVieport = parse.viewport;
    parse.updateViewport({ from: 0, to: upto });
    let result = parse.isDone(upto) || parse.work(timeout, upto) ? parse.tree : null;
    parse.updateViewport(oldVieport);
    return result;
}
/**
Queries whether there is a full syntax tree available up to the
given document position. If there isn't, the background parse
process _might_ still be working and update the tree further, but
there is no guarantee of that—the parser will [stop
working](https://codemirror.net/6/docs/ref/#language.syntaxParserRunning) when it has spent a
certain amount of time or has moved beyond the visible viewport.
Always returns false if no language has been enabled.
*/
function syntaxTreeAvailable(state, upto = state.doc.length) {
    var _a;
    return ((_a = state.field(Language.state, false)) === null || _a === void 0 ? void 0 : _a.context.isDone(upto)) || false;
}
/**
Move parsing forward, and update the editor state afterwards to
reflect the new tree. Will work for at most `timeout`
milliseconds. Returns true if the parser managed get to the given
position in that time.
*/
function forceParsing(view, upto = view.viewport.to, timeout = 100) {
    let success = ensureSyntaxTree(view.state, upto, timeout);
    if (success != dist_syntaxTree(view.state))
        view.dispatch({});
    return !!success;
}
/**
Tells you whether the language parser is planning to do more
parsing work (in a `requestIdleCallback` pseudo-thread) or has
stopped running, either because it parsed the entire document,
because it spent too much time and was cut off, or because there
is no language parser enabled.
*/
function syntaxParserRunning(view) {
    var _a;
    return ((_a = view.plugin(parseWorker)) === null || _a === void 0 ? void 0 : _a.isWorking()) || false;
}
/**
Lezer-style
[`Input`](https://lezer.codemirror.net/docs/ref#common.Input)
object for a [`Text`](https://codemirror.net/6/docs/ref/#state.Text) object.
*/
class DocInput {
    /**
    Create an input object for the given document.
    */
    constructor(doc) {
        this.doc = doc;
        this.cursorPos = 0;
        this.string = "";
        this.cursor = doc.iter();
    }
    get length() { return this.doc.length; }
    syncTo(pos) {
        this.string = this.cursor.next(pos - this.cursorPos).value;
        this.cursorPos = pos + this.string.length;
        return this.cursorPos - this.string.length;
    }
    chunk(pos) {
        this.syncTo(pos);
        return this.string;
    }
    get lineChunks() { return true; }
    read(from, to) {
        let stringStart = this.cursorPos - this.string.length;
        if (from < stringStart || to >= this.cursorPos)
            return this.doc.sliceString(from, to);
        else
            return this.string.slice(from - stringStart, to - stringStart);
    }
}
let currentContext = null;
/**
A parse context provided to parsers working on the editor content.
*/
class ParseContext {
    constructor(parser, 
    /**
    The current editor state.
    */
    state, 
    /**
    Tree fragments that can be reused by incremental re-parses.
    */
    fragments = [], 
    /**
    @internal
    */
    tree, 
    /**
    @internal
    */
    treeLen, 
    /**
    The current editor viewport (or some overapproximation
    thereof). Intended to be used for opportunistically avoiding
    work (in which case
    [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView)
    should be called to make sure the parser is restarted when the
    skipped region becomes visible).
    */
    viewport, 
    /**
    @internal
    */
    skipped, 
    /**
    This is where skipping parsers can register a promise that,
    when resolved, will schedule a new parse. It is cleared when
    the parse worker picks up the promise. @internal
    */
    scheduleOn) {
        this.parser = parser;
        this.state = state;
        this.fragments = fragments;
        this.tree = tree;
        this.treeLen = treeLen;
        this.viewport = viewport;
        this.skipped = skipped;
        this.scheduleOn = scheduleOn;
        this.parse = null;
        /**
        @internal
        */
        this.tempSkipped = [];
    }
    /**
    @internal
    */
    static create(parser, state, viewport) {
        return new ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null);
    }
    startParse() {
        return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
    }
    /**
    @internal
    */
    work(until, upto) {
        if (upto != null && upto >= this.state.doc.length)
            upto = undefined;
        if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
            this.takeTree();
            return true;
        }
        return this.withContext(() => {
            var _a;
            if (typeof until == "number") {
                let endTime = Date.now() + until;
                until = () => Date.now() > endTime;
            }
            if (!this.parse)
                this.parse = this.startParse();
            if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) &&
                upto < this.state.doc.length)
                this.parse.stopAt(upto);
            for (;;) {
                let done = this.parse.advance();
                if (done) {
                    this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));
                    this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length;
                    this.tree = done;
                    this.parse = null;
                    if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length))
                        this.parse = this.startParse();
                    else
                        return true;
                }
                if (until())
                    return false;
            }
        });
    }
    /**
    @internal
    */
    takeTree() {
        let pos, tree;
        if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {
            if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos)
                this.parse.stopAt(pos);
            this.withContext(() => { while (!(tree = this.parse.advance())) { } });
            this.treeLen = pos;
            this.tree = tree;
            this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));
            this.parse = null;
        }
    }
    withContext(f) {
        let prev = currentContext;
        currentContext = this;
        try {
            return f();
        }
        finally {
            currentContext = prev;
        }
    }
    withoutTempSkipped(fragments) {
        for (let r; r = this.tempSkipped.pop();)
            fragments = cutFragments(fragments, r.from, r.to);
        return fragments;
    }
    /**
    @internal
    */
    changes(changes, newState) {
        let { fragments, tree, treeLen, viewport, skipped } = this;
        this.takeTree();
        if (!changes.empty) {
            let ranges = [];
            changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB }));
            fragments = TreeFragment.applyChanges(fragments, ranges);
            tree = Tree.empty;
            treeLen = 0;
            viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) };
            if (this.skipped.length) {
                skipped = [];
                for (let r of this.skipped) {
                    let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1);
                    if (from < to)
                        skipped.push({ from, to });
                }
            }
        }
        return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);
    }
    /**
    @internal
    */
    updateViewport(viewport) {
        if (this.viewport.from == viewport.from && this.viewport.to == viewport.to)
            return false;
        this.viewport = viewport;
        let startLen = this.skipped.length;
        for (let i = 0; i < this.skipped.length; i++) {
            let { from, to } = this.skipped[i];
            if (from < viewport.to && to > viewport.from) {
                this.fragments = cutFragments(this.fragments, from, to);
                this.skipped.splice(i--, 1);
            }
        }
        if (this.skipped.length >= startLen)
            return false;
        this.reset();
        return true;
    }
    /**
    @internal
    */
    reset() {
        if (this.parse) {
            this.takeTree();
            this.parse = null;
        }
    }
    /**
    Notify the parse scheduler that the given region was skipped
    because it wasn't in view, and the parse should be restarted
    when it comes into view.
    */
    skipUntilInView(from, to) {
        this.skipped.push({ from, to });
    }
    /**
    Returns a parser intended to be used as placeholder when
    asynchronously loading a nested parser. It'll skip its input and
    mark it as not-really-parsed, so that the next update will parse
    it again.
    
    When `until` is given, a reparse will be scheduled when that
    promise resolves.
    */
    static getSkippingParser(until) {
        return new class extends Parser {
            createParse(input, fragments, ranges) {
                let from = ranges[0].from, to = ranges[ranges.length - 1].to;
                let parser = {
                    parsedPos: from,
                    advance() {
                        let cx = currentContext;
                        if (cx) {
                            for (let r of ranges)
                                cx.tempSkipped.push(r);
                            if (until)
                                cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
                        }
                        this.parsedPos = to;
                        return new Tree(dist_NodeType.none, [], [], to - from);
                    },
                    stoppedAt: null,
                    stopAt() { }
                };
                return parser;
            }
        };
    }
    /**
    @internal
    */
    isDone(upto) {
        upto = Math.min(upto, this.state.doc.length);
        let frags = this.fragments;
        return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;
    }
    /**
    Get the context for the current parse, or `null` if no editor
    parse is in progress.
    */
    static get() { return currentContext; }
}
function cutFragments(fragments, from, to) {
    return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]);
}
class LanguageState {
    constructor(
    // A mutable parse state that is used to preserve work done during
    // the lifetime of a state when moving to the next state.
    context) {
        this.context = context;
        this.tree = context.tree;
    }
    apply(tr) {
        if (!tr.docChanged && this.tree == this.context.tree)
            return this;
        let newCx = this.context.changes(tr.changes, tr.state);
        // If the previous parse wasn't done, go forward only up to its
        // end position or the end of the viewport, to avoid slowing down
        // state updates with parse work beyond the viewport.
        let upto = this.context.treeLen == tr.startState.doc.length ? undefined
            : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);
        if (!newCx.work(20 /* Work.Apply */, upto))
            newCx.takeTree();
        return new LanguageState(newCx);
    }
    static init(state) {
        let vpTo = Math.min(3000 /* Work.InitViewport */, state.doc.length);
        let parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo });
        if (!parseState.work(20 /* Work.Apply */, vpTo))
            parseState.takeTree();
        return new LanguageState(parseState);
    }
}
Language.state = /*@__PURE__*/dist_StateField.define({
    create: LanguageState.init,
    update(value, tr) {
        for (let e of tr.effects)
            if (e.is(Language.setState))
                return e.value;
        if (tr.startState.facet(language) != tr.state.facet(language))
            return LanguageState.init(tr.state);
        return value.apply(tr);
    }
});
let requestIdle = (callback) => {
    let timeout = setTimeout(() => callback(), 500 /* Work.MaxPause */);
    return () => clearTimeout(timeout);
};
if (typeof requestIdleCallback != "undefined")
    requestIdle = (callback) => {
        let idle = -1, timeout = setTimeout(() => {
            idle = requestIdleCallback(callback, { timeout: 500 /* Work.MaxPause */ - 100 /* Work.MinPause */ });
        }, 100 /* Work.MinPause */);
        return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle);
    };
const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending)
    ? () => navigator.scheduling.isInputPending() : null;
const parseWorker = /*@__PURE__*/dist_ViewPlugin.fromClass(class ParseWorker {
    constructor(view) {
        this.view = view;
        this.working = null;
        this.workScheduled = 0;
        // End of the current time chunk
        this.chunkEnd = -1;
        // Milliseconds of budget left for this chunk
        this.chunkBudget = -1;
        this.work = this.work.bind(this);
        this.scheduleWork();
    }
    update(update) {
        let cx = this.view.state.field(Language.state).context;
        if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen)
            this.scheduleWork();
        if (update.docChanged || update.selectionSet) {
            if (this.view.hasFocus)
                this.chunkBudget += 50 /* Work.ChangeBonus */;
            this.scheduleWork();
        }
        this.checkAsyncSchedule(cx);
    }
    scheduleWork() {
        if (this.working)
            return;
        let { state } = this.view, field = state.field(Language.state);
        if (field.tree != field.context.tree || !field.context.isDone(state.doc.length))
            this.working = requestIdle(this.work);
    }
    work(deadline) {
        this.working = null;
        let now = Date.now();
        if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk
            this.chunkEnd = now + 30000 /* Work.ChunkTime */;
            this.chunkBudget = 3000 /* Work.ChunkBudget */;
        }
        if (this.chunkBudget <= 0)
            return; // No more budget
        let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state);
        if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* Work.MaxParseAhead */))
            return;
        let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Work.Slice */, deadline && !isInputPending ? Math.max(25 /* Work.MinSlice */, deadline.timeRemaining() - 5) : 1e9);
        let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000;
        let done = field.context.work(() => {
            return isInputPending && isInputPending() || Date.now() > endTime;
        }, vpTo + (viewportFirst ? 0 : 100000 /* Work.MaxParseAhead */));
        this.chunkBudget -= Date.now() - now;
        if (done || this.chunkBudget <= 0) {
            field.context.takeTree();
            this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) });
        }
        if (this.chunkBudget > 0 && !(done && !viewportFirst))
            this.scheduleWork();
        this.checkAsyncSchedule(field.context);
    }
    checkAsyncSchedule(cx) {
        if (cx.scheduleOn) {
            this.workScheduled++;
            cx.scheduleOn
                .then(() => this.scheduleWork())
                .catch(err => logException(this.view.state, err))
                .then(() => this.workScheduled--);
            cx.scheduleOn = null;
        }
    }
    destroy() {
        if (this.working)
            this.working();
    }
    isWorking() {
        return !!(this.working || this.workScheduled > 0);
    }
}, {
    eventHandlers: { focus() { this.scheduleWork(); } }
});
/**
The facet used to associate a language with an editor state. Used
by `Language` object's `extension` property (so you don't need to
manually wrap your languages in this). Can be used to access the
current language on a state.
*/
const language = /*@__PURE__*/Facet.define({
    combine(languages) { return languages.length ? languages[0] : null; },
    enables: language => [
        Language.state,
        parseWorker,
        dist_EditorView.contentAttributes.compute([language], state => {
            let lang = state.facet(language);
            return lang && lang.name ? { "data-language": lang.name } : {};
        })
    ]
});
/**
This class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an
optional set of supporting extensions. Language packages are
encouraged to export a function that optionally takes a
configuration object and returns a `LanguageSupport` instance, as
the main way for client code to use the package.
*/
class LanguageSupport {
    /**
    Create a language support object.
    */
    constructor(
    /**
    The language object.
    */
    language, 
    /**
    An optional set of supporting extensions. When nesting a
    language in another language, the outer language is encouraged
    to include the supporting extensions for its inner languages
    in its own set of support extensions.
    */
    support = []) {
        this.language = language;
        this.support = support;
        this.extension = [language, support];
    }
}
/**
Language descriptions are used to store metadata about languages
and to dynamically load them. Their main role is finding the
appropriate language for a filename or dynamically loading nested
parsers.
*/
class LanguageDescription {
    constructor(
    /**
    The name of this language.
    */
    name, 
    /**
    Alternative names for the mode (lowercased, includes `this.name`).
    */
    alias, 
    /**
    File extensions associated with this language.
    */
    extensions, 
    /**
    Optional filename pattern that should be associated with this
    language.
    */
    filename, loadFunc, 
    /**
    If the language has been loaded, this will hold its value.
    */
    support = undefined) {
        this.name = name;
        this.alias = alias;
        this.extensions = extensions;
        this.filename = filename;
        this.loadFunc = loadFunc;
        this.support = support;
        this.loading = null;
    }
    /**
    Start loading the the language. Will return a promise that
    resolves to a [`LanguageSupport`](https://codemirror.net/6/docs/ref/#language.LanguageSupport)
    object when the language successfully loads.
    */
    load() {
        return this.loading || (this.loading = this.loadFunc().then(support => this.support = support, err => { this.loading = null; throw err; }));
    }
    /**
    Create a language description.
    */
    static of(spec) {
        let { load, support } = spec;
        if (!load) {
            if (!support)
                throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");
            load = () => Promise.resolve(support);
        }
        return new LanguageDescription(spec.name, (spec.alias || []).concat(spec.name).map(s => s.toLowerCase()), spec.extensions || [], spec.filename, load, support);
    }
    /**
    Look for a language in the given array of descriptions that
    matches the filename. Will first match
    [`filename`](https://codemirror.net/6/docs/ref/#language.LanguageDescription.filename) patterns,
    and then [extensions](https://codemirror.net/6/docs/ref/#language.LanguageDescription.extensions),
    and return the first language that matches.
    */
    static matchFilename(descs, filename) {
        for (let d of descs)
            if (d.filename && d.filename.test(filename))
                return d;
        let ext = /\.([^.]+)$/.exec(filename);
        if (ext)
            for (let d of descs)
                if (d.extensions.indexOf(ext[1]) > -1)
                    return d;
        return null;
    }
    /**
    Look for a language whose name or alias matches the the given
    name (case-insensitively). If `fuzzy` is true, and no direct
    matchs is found, this'll also search for a language whose name
    or alias occurs in the string (for names shorter than three
    characters, only when surrounded by non-word characters).
    */
    static matchLanguageName(descs, name, fuzzy = true) {
        name = name.toLowerCase();
        for (let d of descs)
            if (d.alias.some(a => a == name))
                return d;
        if (fuzzy)
            for (let d of descs)
                for (let a of d.alias) {
                    let found = name.indexOf(a);
                    if (found > -1 && (a.length > 2 || !/\w/.test(name[found - 1]) && !/\w/.test(name[found + a.length])))
                        return d;
                }
        return null;
    }
}

/**
Facet that defines a way to provide a function that computes the
appropriate indentation depth, as a column number (see
[`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)), at the start of a given
line. A return value of `null` indicates no indentation can be
determined, and the line should inherit the indentation of the one
above it. A return value of `undefined` defers to the next indent
service.
*/
const indentService = /*@__PURE__*/Facet.define();
/**
Facet for overriding the unit by which indentation happens. Should
be a string consisting entirely of the same whitespace character.
When not set, this defaults to 2 spaces.
*/
const indentUnit = /*@__PURE__*/Facet.define({
    combine: values => {
        if (!values.length)
            return "  ";
        let unit = values[0];
        if (!unit || /\S/.test(unit) || Array.from(unit).some(e => e != unit[0]))
            throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
        return unit;
    }
});
/**
Return the _column width_ of an indent unit in the state.
Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit)
facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that
contains tabs.
*/
function getIndentUnit(state) {
    let unit = state.facet(indentUnit);
    return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length;
}
/**
Create an indentation string that covers columns 0 to `cols`.
Will use tabs for as much of the columns as possible when the
[`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains
tabs.
*/
function indentString(state, cols) {
    let result = "", ts = state.tabSize, ch = state.facet(indentUnit)[0];
    if (ch == "\t") {
        while (cols >= ts) {
            result += "\t";
            cols -= ts;
        }
        ch = " ";
    }
    for (let i = 0; i < cols; i++)
        result += ch;
    return result;
}
/**
Get the indentation, as a column number, at the given position.
Will first consult any [indent services](https://codemirror.net/6/docs/ref/#language.indentService)
that are registered, and if none of those return an indentation,
this will check the syntax tree for the [indent node
prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) and use that if found. Returns a
number when an indentation could be determined, and null
otherwise.
*/
function getIndentation(context, pos) {
    if (context instanceof dist_EditorState)
        context = new IndentContext(context);
    for (let service of context.state.facet(indentService)) {
        let result = service(context, pos);
        if (result !== undefined)
            return result;
    }
    let tree = dist_syntaxTree(context.state);
    return tree.length >= pos ? syntaxIndentation(context, tree, pos) : null;
}
/**
Create a change set that auto-indents all lines touched by the
given document range.
*/
function indentRange(state, from, to) {
    let updated = Object.create(null);
    let context = new IndentContext(state, { overrideIndentation: start => { var _a; return (_a = updated[start]) !== null && _a !== void 0 ? _a : -1; } });
    let changes = [];
    for (let pos = from; pos <= to;) {
        let line = state.doc.lineAt(pos);
        pos = line.to + 1;
        let indent = getIndentation(context, line.from);
        if (indent == null)
            continue;
        if (!/\S/.test(line.text))
            indent = 0;
        let cur = /^\s*/.exec(line.text)[0];
        let norm = indentString(state, indent);
        if (cur != norm) {
            updated[line.from] = indent;
            changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
        }
    }
    return state.changes(changes);
}
/**
Indentation contexts are used when calling [indentation
services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities
useful in indentation logic, and can selectively override the
indentation reported for some lines.
*/
class IndentContext {
    /**
    Create an indent context.
    */
    constructor(
    /**
    The editor state.
    */
    state, 
    /**
    @internal
    */
    options = {}) {
        this.state = state;
        this.options = options;
        this.unit = getIndentUnit(state);
    }
    /**
    Get a description of the line at the given position, taking
    [simulated line
    breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
    into account. If there is such a break at `pos`, the `bias`
    argument determines whether the part of the line line before or
    after the break is used.
    */
    lineAt(pos, bias = 1) {
        let line = this.state.doc.lineAt(pos);
        let { simulateBreak, simulateDoubleBreak } = this.options;
        if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) {
            if (simulateDoubleBreak && simulateBreak == pos)
                return { text: "", from: pos };
            else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos)
                return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak };
            else
                return { text: line.text.slice(0, simulateBreak - line.from), from: line.from };
        }
        return line;
    }
    /**
    Get the text directly after `pos`, either the entire line
    or the next 100 characters, whichever is shorter.
    */
    textAfterPos(pos, bias = 1) {
        if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak)
            return "";
        let { text, from } = this.lineAt(pos, bias);
        return text.slice(pos - from, Math.min(text.length, pos + 100 - from));
    }
    /**
    Find the column for the given position.
    */
    column(pos, bias = 1) {
        let { text, from } = this.lineAt(pos, bias);
        let result = this.countColumn(text, pos - from);
        let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;
        if (override > -1)
            result += override - this.countColumn(text, text.search(/\S|$/));
        return result;
    }
    /**
    Find the column position (taking tabs into account) of the given
    position in the given string.
    */
    countColumn(line, pos = line.length) {
        return dist_countColumn(line, this.state.tabSize, pos);
    }
    /**
    Find the indentation column of the line at the given point.
    */
    lineIndent(pos, bias = 1) {
        let { text, from } = this.lineAt(pos, bias);
        let override = this.options.overrideIndentation;
        if (override) {
            let overriden = override(from);
            if (overriden > -1)
                return overriden;
        }
        return this.countColumn(text, text.search(/\S|$/));
    }
    /**
    Returns the [simulated line
    break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
    for this context, if any.
    */
    get simulatedBreak() {
        return this.options.simulateBreak || null;
    }
}
/**
A syntax tree node prop used to associate indentation strategies
with node types. Such a strategy is a function from an indentation
context to a column number (see also
[`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)) or null, where null
indicates that no definitive indentation can be determined.
*/
const indentNodeProp = /*@__PURE__*/new NodeProp();
// Compute the indentation for a given position from the syntax tree.
function syntaxIndentation(cx, ast, pos) {
    let stack = ast.resolveStack(pos);
    let inner = ast.resolveInner(pos, -1).resolve(pos, 0).enterUnfinishedNodesBefore(pos);
    if (inner != stack.node) {
        let add = [];
        for (let cur = inner; cur && !(cur.from < stack.node.from || cur.to > stack.node.to ||
            cur.from == stack.node.from && cur.type == stack.node.type); cur = cur.parent)
            add.push(cur);
        for (let i = add.length - 1; i >= 0; i--)
            stack = { node: add[i], next: stack };
    }
    return indentFor(stack, cx, pos);
}
function indentFor(stack, cx, pos) {
    for (let cur = stack; cur; cur = cur.next) {
        let strategy = indentStrategy(cur.node);
        if (strategy)
            return strategy(TreeIndentContext.create(cx, pos, cur));
    }
    return 0;
}
function ignoreClosed(cx) {
    return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak;
}
function indentStrategy(tree) {
    let strategy = tree.type.prop(indentNodeProp);
    if (strategy)
        return strategy;
    let first = tree.firstChild, close;
    if (first && (close = first.type.prop(NodeProp.closedBy))) {
        let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1;
        return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined);
    }
    return tree.parent == null ? topIndent : null;
}
function topIndent() { return 0; }
/**
Objects of this type provide context information and helper
methods to indentation functions registered on syntax nodes.
*/
class TreeIndentContext extends IndentContext {
    constructor(base, 
    /**
    The position at which indentation is being computed.
    */
    pos, 
    /**
    @internal
    */
    context) {
        super(base.state, base.options);
        this.base = base;
        this.pos = pos;
        this.context = context;
    }
    /**
    The syntax tree node to which the indentation strategy
    applies.
    */
    get node() { return this.context.node; }
    /**
    @internal
    */
    static create(base, pos, context) {
        return new TreeIndentContext(base, pos, context);
    }
    /**
    Get the text directly after `this.pos`, either the entire line
    or the next 100 characters, whichever is shorter.
    */
    get textAfter() {
        return this.textAfterPos(this.pos);
    }
    /**
    Get the indentation at the reference line for `this.node`, which
    is the line on which it starts, unless there is a node that is
    _not_ a parent of this node covering the start of that line. If
    so, the line at the start of that node is tried, again skipping
    on if it is covered by another such node.
    */
    get baseIndent() {
        return this.baseIndentFor(this.node);
    }
    /**
    Get the indentation for the reference line of the given node
    (see [`baseIndent`](https://codemirror.net/6/docs/ref/#language.TreeIndentContext.baseIndent)).
    */
    baseIndentFor(node) {
        let line = this.state.doc.lineAt(node.from);
        // Skip line starts that are covered by a sibling (or cousin, etc)
        for (;;) {
            let atBreak = node.resolve(line.from);
            while (atBreak.parent && atBreak.parent.from == atBreak.from)
                atBreak = atBreak.parent;
            if (isParent(atBreak, node))
                break;
            line = this.state.doc.lineAt(atBreak.from);
        }
        return this.lineIndent(line.from);
    }
    /**
    Continue looking for indentations in the node's parent nodes,
    and return the result of that.
    */
    continue() {
        return indentFor(this.context.next, this.base, this.pos);
    }
}
function isParent(parent, of) {
    for (let cur = of; cur; cur = cur.parent)
        if (parent == cur)
            return true;
    return false;
}
// Check whether a delimited node is aligned (meaning there are
// non-skipped nodes on the same line as the opening delimiter). And
// if so, return the opening token.
function bracketedAligned(context) {
    let tree = context.node;
    let openToken = tree.childAfter(tree.from), last = tree.lastChild;
    if (!openToken)
        return null;
    let sim = context.options.simulateBreak;
    let openLine = context.state.doc.lineAt(openToken.from);
    let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
    for (let pos = openToken.to;;) {
        let next = tree.childAfter(pos);
        if (!next || next == last)
            return null;
        if (!next.type.isSkipped) {
            if (next.from >= lineEnd)
                return null;
            let space = /^ */.exec(openLine.text.slice(openToken.to - openLine.from))[0].length;
            return { from: openToken.from, to: openToken.to + space };
        }
        pos = next.to;
    }
}
/**
An indentation strategy for delimited (usually bracketed) nodes.
Will, by default, indent one unit more than the parent's base
indent unless the line starts with a closing token. When `align`
is true and there are non-skipped nodes on the node's opening
line, the content of the node will be aligned with the end of the
opening node, like this:

    foo(bar,
        baz)
*/
function delimitedIndent({ closing, align = true, units = 1 }) {
    return (context) => delimitedStrategy(context, align, units, closing);
}
function delimitedStrategy(context, align, units, closing, closedAt) {
    let after = context.textAfter, space = after.match(/^\s*/)[0].length;
    let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space;
    let aligned = align ? bracketedAligned(context) : null;
    if (aligned)
        return closed ? context.column(aligned.from) : context.column(aligned.to);
    return context.baseIndent + (closed ? 0 : context.unit * units);
}
/**
An indentation strategy that aligns a node's content to its base
indentation.
*/
const flatIndent = (context) => context.baseIndent;
/**
Creates an indentation strategy that, by default, indents
continued lines one unit more than the node's base indentation.
You can provide `except` to prevent indentation of lines that
match a pattern (for example `/^else\b/` in `if`/`else`
constructs), and you can change the amount of units used with the
`units` option.
*/
function continuedIndent({ except, units = 1 } = {}) {
    return (context) => {
        let matchExcept = except && except.test(context.textAfter);
        return context.baseIndent + (matchExcept ? 0 : units * context.unit);
    };
}
const DontIndentBeyond = 200;
/**
Enables reindentation on input. When a language defines an
`indentOnInput` field in its [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular
expression, the line at the cursor will be reindented whenever new
text is typed and the input from the start of the line up to the
cursor matches that regexp.

To avoid unneccesary reindents, it is recommended to start the
regexp with `^` (usually followed by `\s*`), and end it with `$`.
For example, `/^\s*\}$/` will reindent when a closing brace is
added at the start of a line.
*/
function indentOnInput() {
    return EditorState.transactionFilter.of(tr => {
        if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete"))
            return tr;
        let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head);
        if (!rules.length)
            return tr;
        let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head);
        if (head > line.from + DontIndentBeyond)
            return tr;
        let lineStart = doc.sliceString(line.from, head);
        if (!rules.some(r => r.test(lineStart)))
            return tr;
        let { state } = tr, last = -1, changes = [];
        for (let { head } of state.selection.ranges) {
            let line = state.doc.lineAt(head);
            if (line.from == last)
                continue;
            last = line.from;
            let indent = getIndentation(state, line.from);
            if (indent == null)
                continue;
            let cur = /^\s*/.exec(line.text)[0];
            let norm = indentString(state, indent);
            if (cur != norm)
                changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
        }
        return changes.length ? [tr, { changes, sequential: true }] : tr;
    });
}

/**
A facet that registers a code folding service. When called with
the extent of a line, such a function should return a foldable
range that starts on that line (but continues beyond it), if one
can be found.
*/
const foldService = /*@__PURE__*/Facet.define();
/**
This node prop is used to associate folding information with
syntax node types. Given a syntax node, it should check whether
that tree is foldable and return the range that can be collapsed
when it is.
*/
const foldNodeProp = /*@__PURE__*/new NodeProp();
/**
[Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but
the first and the last child of a syntax node. Useful for nodes
that start and end with delimiters.
*/
function foldInside(node) {
    let first = node.firstChild, last = node.lastChild;
    return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null;
}
function syntaxFolding(state, start, end) {
    let tree = dist_syntaxTree(state);
    if (tree.length < end)
        return null;
    let stack = tree.resolveStack(end, 1);
    let found = null;
    for (let iter = stack; iter; iter = iter.next) {
        let cur = iter.node;
        if (cur.to <= end || cur.from > end)
            continue;
        if (found && cur.from < start)
            break;
        let prop = cur.type.prop(foldNodeProp);
        if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) {
            let value = prop(cur, state);
            if (value && value.from <= end && value.from >= start && value.to > end)
                found = value;
        }
    }
    return found;
}
function isUnfinished(node) {
    let ch = node.lastChild;
    return ch && ch.to == node.to && ch.type.isError;
}
/**
Check whether the given line is foldable. First asks any fold
services registered through
[`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return
a result, tries to query the [fold node
prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end
of the line.
*/
function foldable(state, lineStart, lineEnd) {
    for (let service of state.facet(foldService)) {
        let result = service(state, lineStart, lineEnd);
        if (result)
            return result;
    }
    return syntaxFolding(state, lineStart, lineEnd);
}
function mapRange(range, mapping) {
    let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1);
    return from >= to ? undefined : { from, to };
}
/**
State effect that can be attached to a transaction to fold the
given range. (You probably only need this in exceptional
circumstances—usually you'll just want to let
[`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold
gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.)
*/
const foldEffect = /*@__PURE__*/dist_StateEffect.define({ map: mapRange });
/**
State effect that unfolds the given range (if it was folded).
*/
const unfoldEffect = /*@__PURE__*/dist_StateEffect.define({ map: mapRange });
function selectedLines(view) {
    let lines = [];
    for (let { head } of view.state.selection.ranges) {
        if (lines.some(l => l.from <= head && l.to >= head))
            continue;
        lines.push(view.lineBlockAt(head));
    }
    return lines;
}
/**
The state field that stores the folded ranges (as a [decoration
set](https://codemirror.net/6/docs/ref/#view.DecorationSet)). Can be passed to
[`EditorState.toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) and
[`fromJSON`](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) to serialize the fold
state.
*/
const foldState = /*@__PURE__*/dist_StateField.define({
    create() {
        return dist_Decoration.none;
    },
    update(folded, tr) {
        if (tr.isUserEvent("delete"))
            tr.changes.iterChangedRanges((fromA, toA) => folded = clearTouchedFolds(folded, fromA, toA));
        folded = folded.map(tr.changes);
        for (let e of tr.effects) {
            if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) {
                let { preparePlaceholder } = tr.state.facet(foldConfig);
                let widget = !preparePlaceholder ? foldWidget :
                    dist_Decoration.replace({ widget: new PreparedFoldWidget(preparePlaceholder(tr.state, e.value)) });
                folded = folded.update({ add: [widget.range(e.value.from, e.value.to)] });
            }
            else if (e.is(unfoldEffect)) {
                folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to,
                    filterFrom: e.value.from, filterTo: e.value.to });
            }
        }
        // Clear folded ranges that cover the selection head
        if (tr.selection)
            folded = clearTouchedFolds(folded, tr.selection.main.head);
        return folded;
    },
    provide: f => dist_EditorView.decorations.from(f),
    toJSON(folded, state) {
        let ranges = [];
        folded.between(0, state.doc.length, (from, to) => { ranges.push(from, to); });
        return ranges;
    },
    fromJSON(value) {
        if (!Array.isArray(value) || value.length % 2)
            throw new RangeError("Invalid JSON for fold state");
        let ranges = [];
        for (let i = 0; i < value.length;) {
            let from = value[i++], to = value[i++];
            if (typeof from != "number" || typeof to != "number")
                throw new RangeError("Invalid JSON for fold state");
            ranges.push(foldWidget.range(from, to));
        }
        return dist_Decoration.set(ranges, true);
    }
});
function clearTouchedFolds(folded, from, to = from) {
    let touched = false;
    folded.between(from, to, (a, b) => { if (a < to && b > from)
        touched = true; });
    return !touched ? folded : folded.update({
        filterFrom: from,
        filterTo: to,
        filter: (a, b) => a >= to || b <= from
    });
}
/**
Get a [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) containing the folded ranges
in the given state.
*/
function foldedRanges(state) {
    return state.field(foldState, false) || RangeSet.empty;
}
function findFold(state, from, to) {
    var _a;
    let found = null;
    (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => {
        if (!found || found.from > from)
            found = { from, to };
    });
    return found;
}
function foldExists(folded, from, to) {
    let found = false;
    folded.between(from, from, (a, b) => { if (a == from && b == to)
        found = true; });
    return found;
}
function maybeEnable(state, other) {
    return state.field(foldState, false) ? other : other.concat(dist_StateEffect.appendConfig.of(codeFolding()));
}
/**
Fold the lines that are selected, if possible.
*/
const foldCode = view => {
    for (let line of selectedLines(view)) {
        let range = foldable(view.state, line.from, line.to);
        if (range) {
            view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) });
            return true;
        }
    }
    return false;
};
/**
Unfold folded ranges on selected lines.
*/
const unfoldCode = view => {
    if (!view.state.field(foldState, false))
        return false;
    let effects = [];
    for (let line of selectedLines(view)) {
        let folded = findFold(view.state, line.from, line.to);
        if (folded)
            effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
    }
    if (effects.length)
        view.dispatch({ effects });
    return effects.length > 0;
};
function announceFold(view, range, fold = true) {
    let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number;
    return dist_EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`);
}
/**
Fold all top-level foldable ranges. Note that, in most cases,
folding information will depend on the [syntax
tree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work
reliably when the document hasn't been fully parsed (either
because the editor state was only just initialized, or because the
document is so big that the parser decided not to parse it
entirely).
*/
const foldAll = view => {
    let { state } = view, effects = [];
    for (let pos = 0; pos < state.doc.length;) {
        let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to);
        if (range)
            effects.push(foldEffect.of(range));
        pos = (range ? view.lineBlockAt(range.to) : line).to + 1;
    }
    if (effects.length)
        view.dispatch({ effects: maybeEnable(view.state, effects) });
    return !!effects.length;
};
/**
Unfold all folded code.
*/
const unfoldAll = view => {
    let field = view.state.field(foldState, false);
    if (!field || !field.size)
        return false;
    let effects = [];
    field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
    view.dispatch({ effects });
    return true;
};
// Find the foldable region containing the given line, if one exists
function foldableContainer(view, lineBlock) {
    // Look backwards through line blocks until we find a foldable region that
    // intersects with the line
    for (let line = lineBlock;;) {
        let foldableRegion = foldable(view.state, line.from, line.to);
        if (foldableRegion && foldableRegion.to > lineBlock.from)
            return foldableRegion;
        if (!line.from)
            return null;
        line = view.lineBlockAt(line.from - 1);
    }
}
/**
Toggle folding at cursors. Unfolds if there is an existing fold
starting in that line, tries to find a foldable range around it
otherwise.
*/
const toggleFold = (view) => {
    let effects = [];
    for (let line of selectedLines(view)) {
        let folded = findFold(view.state, line.from, line.to);
        if (folded) {
            effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
        }
        else {
            let foldRange = foldableContainer(view, line);
            if (foldRange)
                effects.push(foldEffect.of(foldRange), announceFold(view, foldRange));
        }
    }
    if (effects.length > 0)
        view.dispatch({ effects: maybeEnable(view.state, effects) });
    return !!effects.length;
};
/**
Default fold-related key bindings.

 - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode).
 - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#language.unfoldCode).
 - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#language.foldAll).
 - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#language.unfoldAll).
*/
const foldKeymap = [
    { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode },
    { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode },
    { key: "Ctrl-Alt-[", run: foldAll },
    { key: "Ctrl-Alt-]", run: unfoldAll }
];
const defaultConfig = {
    placeholderDOM: null,
    preparePlaceholder: null,
    placeholderText: "…"
};
const foldConfig = /*@__PURE__*/Facet.define({
    combine(values) { return combineConfig(values, defaultConfig); }
});
/**
Create an extension that configures code folding.
*/
function codeFolding(config) {
    let result = [foldState, dist_baseTheme$1];
    if (config)
        result.push(foldConfig.of(config));
    return result;
}
function widgetToDOM(view, prepared) {
    let { state } = view, conf = state.facet(foldConfig);
    let onclick = (event) => {
        let line = view.lineBlockAt(view.posAtDOM(event.target));
        let folded = findFold(view.state, line.from, line.to);
        if (folded)
            view.dispatch({ effects: unfoldEffect.of(folded) });
        event.preventDefault();
    };
    if (conf.placeholderDOM)
        return conf.placeholderDOM(view, onclick, prepared);
    let element = document.createElement("span");
    element.textContent = conf.placeholderText;
    element.setAttribute("aria-label", state.phrase("folded code"));
    element.title = state.phrase("unfold");
    element.className = "cm-foldPlaceholder";
    element.onclick = onclick;
    return element;
}
const foldWidget = /*@__PURE__*/dist_Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType {
        toDOM(view) { return widgetToDOM(view, null); }
    } });
class PreparedFoldWidget extends WidgetType {
    constructor(value) {
        super();
        this.value = value;
    }
    eq(other) { return this.value == other.value; }
    toDOM(view) { return widgetToDOM(view, this.value); }
}
const foldGutterDefaults = {
    openText: "⌄",
    closedText: "›",
    markerDOM: null,
    domEventHandlers: {},
    foldingChanged: () => false
};
class FoldMarker extends GutterMarker {
    constructor(config, open) {
        super();
        this.config = config;
        this.open = open;
    }
    eq(other) { return this.config == other.config && this.open == other.open; }
    toDOM(view) {
        if (this.config.markerDOM)
            return this.config.markerDOM(this.open);
        let span = document.createElement("span");
        span.textContent = this.open ? this.config.openText : this.config.closedText;
        span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
        return span;
    }
}
/**
Create an extension that registers a fold gutter, which shows a
fold status indicator before foldable lines (which can be clicked
to fold or unfold the line).
*/
function foldGutter(config = {}) {
    let fullConfig = { ...foldGutterDefaults, ...config };
    let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);
    let markers = dist_ViewPlugin.fromClass(class {
        constructor(view) {
            this.from = view.viewport.from;
            this.markers = this.buildMarkers(view);
        }
        update(update) {
            if (update.docChanged || update.viewportChanged ||
                update.startState.facet(language) != update.state.facet(language) ||
                update.startState.field(foldState, false) != update.state.field(foldState, false) ||
                dist_syntaxTree(update.startState) != dist_syntaxTree(update.state) ||
                fullConfig.foldingChanged(update))
                this.markers = this.buildMarkers(update.view);
        }
        buildMarkers(view) {
            let builder = new RangeSetBuilder();
            for (let line of view.viewportLineBlocks) {
                let mark = findFold(view.state, line.from, line.to) ? canUnfold
                    : foldable(view.state, line.from, line.to) ? canFold : null;
                if (mark)
                    builder.add(line.from, line.from, mark);
            }
            return builder.finish();
        }
    });
    let { domEventHandlers } = fullConfig;
    return [
        markers,
        gutter({
            class: "cm-foldGutter",
            markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || dist_RangeSet.empty; },
            initialSpacer() {
                return new FoldMarker(fullConfig, false);
            },
            domEventHandlers: {
                ...domEventHandlers,
                click: (view, line, event) => {
                    if (domEventHandlers.click && domEventHandlers.click(view, line, event))
                        return true;
                    let folded = findFold(view.state, line.from, line.to);
                    if (folded) {
                        view.dispatch({ effects: unfoldEffect.of(folded) });
                        return true;
                    }
                    let range = foldable(view.state, line.from, line.to);
                    if (range) {
                        view.dispatch({ effects: foldEffect.of(range) });
                        return true;
                    }
                    return false;
                }
            }
        }),
        codeFolding()
    ];
}
const dist_baseTheme$1 = /*@__PURE__*/dist_EditorView.baseTheme({
    ".cm-foldPlaceholder": {
        backgroundColor: "#eee",
        border: "1px solid #ddd",
        color: "#888",
        borderRadius: ".2em",
        margin: "0 1px",
        padding: "0 1px",
        cursor: "pointer"
    },
    ".cm-foldGutter span": {
        padding: "0 1px",
        cursor: "pointer"
    }
});

/**
A highlight style associates CSS styles with highlighting
[tags](https://lezer.codemirror.net/docs/ref#highlight.Tag).
*/
class HighlightStyle {
    constructor(
    /**
    The tag styles used to create this highlight style.
    */
    specs, options) {
        this.specs = specs;
        let modSpec;
        function def(spec) {
            let cls = external_style_mod_namespaceObject.StyleModule.newName();
            (modSpec || (modSpec = Object.create(null)))["." + cls] = spec;
            return cls;
        }
        const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : undefined;
        const scopeOpt = options.scope;
        this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data
            : scopeOpt ? (type) => type == scopeOpt : undefined;
        this.style = tagHighlighter(specs.map(style => ({
            tag: style.tag,
            class: style.class || def(Object.assign({}, style, { tag: null }))
        })), {
            all,
        }).style;
        this.module = modSpec ? new external_style_mod_namespaceObject.StyleModule(modSpec) : null;
        this.themeType = options.themeType;
    }
    /**
    Create a highlighter style that associates the given styles to
    the given tags. The specs must be objects that hold a style tag
    or array of tags in their `tag` property, and either a single
    `class` property providing a static CSS class (for highlighter
    that rely on external styling), or a
    [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
    set of CSS properties (which define the styling for those tags).
    
    The CSS rules created for a highlighter will be emitted in the
    order of the spec's properties. That means that for elements that
    have multiple tags associated with them, styles defined further
    down in the list will have a higher CSS precedence than styles
    defined earlier.
    */
    static define(specs, options) {
        return new HighlightStyle(specs, options || {});
    }
}
const highlighterFacet = /*@__PURE__*/Facet.define();
const fallbackHighlighter = /*@__PURE__*/Facet.define({
    combine(values) { return values.length ? [values[0]] : null; }
});
function getHighlighters(state) {
    let main = state.facet(highlighterFacet);
    return main.length ? main : state.facet(fallbackHighlighter);
}
/**
Wrap a highlighter in an editor extension that uses it to apply
syntax highlighting to the editor content.

When multiple (non-fallback) styles are provided, the styling
applied is the union of the classes they emit.
*/
function syntaxHighlighting(highlighter, options) {
    let ext = [treeHighlighter], themeType;
    if (highlighter instanceof HighlightStyle) {
        if (highlighter.module)
            ext.push(dist_EditorView.styleModule.of(highlighter.module));
        themeType = highlighter.themeType;
    }
    if (options === null || options === void 0 ? void 0 : options.fallback)
        ext.push(fallbackHighlighter.of(highlighter));
    else if (themeType)
        ext.push(highlighterFacet.computeN([dist_EditorView.darkTheme], state => {
            return state.facet(dist_EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
        }));
    else
        ext.push(highlighterFacet.of(highlighter));
    return ext;
}
/**
Returns the CSS classes (if any) that the highlighters active in
the state would assign to the given style
[tags](https://lezer.codemirror.net/docs/ref#highlight.Tag) and
(optional) language
[scope](https://codemirror.net/6/docs/ref/#language.HighlightStyle^define^options.scope).
*/
function highlightingFor(state, tags, scope) {
    let highlighters = getHighlighters(state);
    let result = null;
    if (highlighters)
        for (let highlighter of highlighters) {
            if (!highlighter.scope || scope && highlighter.scope(scope)) {
                let cls = highlighter.style(tags);
                if (cls)
                    result = result ? result + " " + cls : cls;
            }
        }
    return result;
}
class TreeHighlighter {
    constructor(view) {
        this.markCache = Object.create(null);
        this.tree = dist_syntaxTree(view.state);
        this.decorations = this.buildDeco(view, getHighlighters(view.state));
        this.decoratedTo = view.viewport.to;
    }
    update(update) {
        let tree = dist_syntaxTree(update.state), highlighters = getHighlighters(update.state);
        let styleChange = highlighters != getHighlighters(update.startState);
        let { viewport } = update.view, decoratedToMapped = update.changes.mapPos(this.decoratedTo, 1);
        if (tree.length < viewport.to && !styleChange && tree.type == this.tree.type && decoratedToMapped >= viewport.to) {
            this.decorations = this.decorations.map(update.changes);
            this.decoratedTo = decoratedToMapped;
        }
        else if (tree != this.tree || update.viewportChanged || styleChange) {
            this.tree = tree;
            this.decorations = this.buildDeco(update.view, highlighters);
            this.decoratedTo = viewport.to;
        }
    }
    buildDeco(view, highlighters) {
        if (!highlighters || !this.tree.length)
            return dist_Decoration.none;
        let builder = new RangeSetBuilder();
        for (let { from, to } of view.visibleRanges) {
            highlightTree(this.tree, highlighters, (from, to, style) => {
                builder.add(from, to, this.markCache[style] || (this.markCache[style] = dist_Decoration.mark({ class: style })));
            }, from, to);
        }
        return builder.finish();
    }
}
const treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/dist_ViewPlugin.fromClass(TreeHighlighter, {
    decorations: v => v.decorations
}));
/**
A default highlight style (works well with light themes).
*/
const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([
    { tag: tags.meta,
        color: "#404740" },
    { tag: tags.link,
        textDecoration: "underline" },
    { tag: tags.heading,
        textDecoration: "underline",
        fontWeight: "bold" },
    { tag: tags.emphasis,
        fontStyle: "italic" },
    { tag: tags.strong,
        fontWeight: "bold" },
    { tag: tags.strikethrough,
        textDecoration: "line-through" },
    { tag: tags.keyword,
        color: "#708" },
    { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
        color: "#219" },
    { tag: [tags.literal, tags.inserted],
        color: "#164" },
    { tag: [tags.string, tags.deleted],
        color: "#a11" },
    { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)],
        color: "#e40" },
    { tag: /*@__PURE__*/tags.definition(tags.variableName),
        color: "#00f" },
    { tag: /*@__PURE__*/tags.local(tags.variableName),
        color: "#30a" },
    { tag: [tags.typeName, tags.namespace],
        color: "#085" },
    { tag: tags.className,
        color: "#167" },
    { tag: [/*@__PURE__*/tags.special(tags.variableName), tags.macroName],
        color: "#256" },
    { tag: /*@__PURE__*/tags.definition(tags.propertyName),
        color: "#00c" },
    { tag: tags.comment,
        color: "#940" },
    { tag: tags.invalid,
        color: "#f00" }
]);

const dist_baseTheme = /*@__PURE__*/dist_EditorView.baseTheme({
    "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" },
    "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" }
});
const DefaultScanDist = 10000, DefaultBrackets = "()[]{}";
const bracketMatchingConfig = /*@__PURE__*/Facet.define({
    combine(configs) {
        return combineConfig(configs, {
            afterCursor: true,
            brackets: DefaultBrackets,
            maxScanDistance: DefaultScanDist,
            renderMatch: defaultRenderMatch
        });
    }
});
const matchingMark = /*@__PURE__*/dist_Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /*@__PURE__*/dist_Decoration.mark({ class: "cm-nonmatchingBracket" });
function defaultRenderMatch(match) {
    let decorations = [];
    let mark = match.matched ? matchingMark : nonmatchingMark;
    decorations.push(mark.range(match.start.from, match.start.to));
    if (match.end)
        decorations.push(mark.range(match.end.from, match.end.to));
    return decorations;
}
const bracketMatchingState = /*@__PURE__*/dist_StateField.define({
    create() { return dist_Decoration.none; },
    update(deco, tr) {
        if (!tr.docChanged && !tr.selection)
            return deco;
        let decorations = [];
        let config = tr.state.facet(bracketMatchingConfig);
        for (let range of tr.state.selection.ranges) {
            if (!range.empty)
                continue;
            let match = matchBrackets(tr.state, range.head, -1, config)
                || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config))
                || (config.afterCursor &&
                    (matchBrackets(tr.state, range.head, 1, config) ||
                        (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config))));
            if (match)
                decorations = decorations.concat(config.renderMatch(match, tr.state));
        }
        return dist_Decoration.set(decorations, true);
    },
    provide: f => dist_EditorView.decorations.from(f)
});
const bracketMatchingUnique = [
    bracketMatchingState,
    dist_baseTheme
];
/**
Create an extension that enables bracket matching. Whenever the
cursor is next to a bracket, that bracket and the one it matches
are highlighted. Or, when no matching bracket is found, another
highlighting style is used to indicate this.
*/
function bracketMatching(config = {}) {
    return [bracketMatchingConfig.of(config), bracketMatchingUnique];
}
/**
When larger syntax nodes, such as HTML tags, are marked as
opening/closing, it can be a bit messy to treat the whole node as
a matchable bracket. This node prop allows you to define, for such
a node, a ‘handle’—the part of the node that is highlighted, and
that the cursor must be on to activate highlighting in the first
place.
*/
const bracketMatchingHandle = /*@__PURE__*/new NodeProp();
function matchingNodes(node, dir, brackets) {
    let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
    if (byProp)
        return byProp;
    if (node.name.length == 1) {
        let index = brackets.indexOf(node.name);
        if (index > -1 && index % 2 == (dir < 0 ? 1 : 0))
            return [brackets[index + dir]];
    }
    return null;
}
function findHandle(node) {
    let hasHandle = node.type.prop(bracketMatchingHandle);
    return hasHandle ? hasHandle(node.node) : node;
}
/**
Find the matching bracket for the token at `pos`, scanning
direction `dir`. Only the `brackets` and `maxScanDistance`
properties are used from `config`, if given. Returns null if no
bracket was found at `pos`, or a match result otherwise.
*/
function matchBrackets(state, pos, dir, config = {}) {
    let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets;
    let tree = dist_syntaxTree(state), node = tree.resolveInner(pos, dir);
    for (let cur = node; cur; cur = cur.parent) {
        let matches = matchingNodes(cur.type, dir, brackets);
        if (matches && cur.from < cur.to) {
            let handle = findHandle(cur);
            if (handle && (dir > 0 ? pos >= handle.from && pos < handle.to : pos > handle.from && pos <= handle.to))
                return matchMarkedBrackets(state, pos, dir, cur, handle, matches, brackets);
        }
    }
    return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);
}
function matchMarkedBrackets(_state, _pos, dir, token, handle, matching, brackets) {
    let parent = token.parent, firstToken = { from: handle.from, to: handle.to };
    let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor();
    if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to)))
        do {
            if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) {
                if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) {
                    let endHandle = findHandle(cursor);
                    return { start: firstToken, end: endHandle ? { from: endHandle.from, to: endHandle.to } : undefined, matched: true };
                }
                else if (matchingNodes(cursor.type, dir, brackets)) {
                    depth++;
                }
                else if (matchingNodes(cursor.type, -dir, brackets)) {
                    if (depth == 0) {
                        let endHandle = findHandle(cursor);
                        return {
                            start: firstToken,
                            end: endHandle && endHandle.from < endHandle.to ? { from: endHandle.from, to: endHandle.to } : undefined,
                            matched: false
                        };
                    }
                    depth--;
                }
            }
        } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
    return { start: firstToken, matched: false };
}
function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) {
    let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1);
    let bracket = brackets.indexOf(startCh);
    if (bracket < 0 || (bracket % 2 == 0) != (dir > 0))
        return null;
    let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos };
    let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0;
    for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) {
        let text = iter.value;
        if (dir < 0)
            distance += text.length;
        let basePos = pos + distance * dir;
        for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) {
            let found = brackets.indexOf(text[pos]);
            if (found < 0 || tree.resolveInner(basePos + pos, 1).type != tokenType)
                continue;
            if ((found % 2 == 0) == (dir > 0)) {
                depth++;
            }
            else if (depth == 1) { // Closing
                return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) };
            }
            else {
                depth--;
            }
        }
        if (dir > 0)
            distance += text.length;
    }
    return iter.done ? { start: startToken, matched: false } : null;
}

// Counts the column offset in a string, taking tabs into account.
// Used mostly to find indentation.
function countCol(string, end, tabSize, startIndex = 0, startValue = 0) {
    if (end == null) {
        end = string.search(/[^\s\u00a0]/);
        if (end == -1)
            end = string.length;
    }
    let n = startValue;
    for (let i = startIndex; i < end; i++) {
        if (string.charCodeAt(i) == 9)
            n += tabSize - (n % tabSize);
        else
            n++;
    }
    return n;
}
/**
Encapsulates a single line of input. Given to stream syntax code,
which uses it to tokenize the content.
*/
class StringStream {
    /**
    Create a stream.
    */
    constructor(
    /**
    The line.
    */
    string, tabSize, 
    /**
    The current indent unit size.
    */
    indentUnit, overrideIndent) {
        this.string = string;
        this.tabSize = tabSize;
        this.indentUnit = indentUnit;
        this.overrideIndent = overrideIndent;
        /**
        The current position on the line.
        */
        this.pos = 0;
        /**
        The start position of the current token.
        */
        this.start = 0;
        this.lastColumnPos = 0;
        this.lastColumnValue = 0;
    }
    /**
    True if we are at the end of the line.
    */
    eol() { return this.pos >= this.string.length; }
    /**
    True if we are at the start of the line.
    */
    sol() { return this.pos == 0; }
    /**
    Get the next code unit after the current position, or undefined
    if we're at the end of the line.
    */
    peek() { return this.string.charAt(this.pos) || undefined; }
    /**
    Read the next code unit and advance `this.pos`.
    */
    next() {
        if (this.pos < this.string.length)
            return this.string.charAt(this.pos++);
    }
    /**
    Match the next character against the given string, regular
    expression, or predicate. Consume and return it if it matches.
    */
    eat(match) {
        let ch = this.string.charAt(this.pos);
        let ok;
        if (typeof match == "string")
            ok = ch == match;
        else
            ok = ch && (match instanceof RegExp ? match.test(ch) : match(ch));
        if (ok) {
            ++this.pos;
            return ch;
        }
    }
    /**
    Continue matching characters that match the given string,
    regular expression, or predicate function. Return true if any
    characters were consumed.
    */
    eatWhile(match) {
        let start = this.pos;
        while (this.eat(match)) { }
        return this.pos > start;
    }
    /**
    Consume whitespace ahead of `this.pos`. Return true if any was
    found.
    */
    eatSpace() {
        let start = this.pos;
        while (/[\s\u00a0]/.test(this.string.charAt(this.pos)))
            ++this.pos;
        return this.pos > start;
    }
    /**
    Move to the end of the line.
    */
    skipToEnd() { this.pos = this.string.length; }
    /**
    Move to directly before the given character, if found on the
    current line.
    */
    skipTo(ch) {
        let found = this.string.indexOf(ch, this.pos);
        if (found > -1) {
            this.pos = found;
            return true;
        }
    }
    /**
    Move back `n` characters.
    */
    backUp(n) { this.pos -= n; }
    /**
    Get the column position at `this.pos`.
    */
    column() {
        if (this.lastColumnPos < this.start) {
            this.lastColumnValue = countCol(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
            this.lastColumnPos = this.start;
        }
        return this.lastColumnValue;
    }
    /**
    Get the indentation column of the current line.
    */
    indentation() {
        var _a;
        return (_a = this.overrideIndent) !== null && _a !== void 0 ? _a : countCol(this.string, null, this.tabSize);
    }
    /**
    Match the input against the given string or regular expression
    (which should start with a `^`). Return true or the regexp match
    if it matches.
    
    Unless `consume` is set to `false`, this will move `this.pos`
    past the matched text.
    
    When matching a string `caseInsensitive` can be set to true to
    make the match case-insensitive.
    */
    match(pattern, consume, caseInsensitive) {
        if (typeof pattern == "string") {
            let cased = (str) => caseInsensitive ? str.toLowerCase() : str;
            let substr = this.string.substr(this.pos, pattern.length);
            if (cased(substr) == cased(pattern)) {
                if (consume !== false)
                    this.pos += pattern.length;
                return true;
            }
            else
                return null;
        }
        else {
            let match = this.string.slice(this.pos).match(pattern);
            if (match && match.index > 0)
                return null;
            if (match && consume !== false)
                this.pos += match[0].length;
            return match;
        }
    }
    /**
    Get the current token.
    */
    current() { return this.string.slice(this.start, this.pos); }
}

function fullParser(spec) {
    return {
        name: spec.name || "",
        token: spec.token,
        blankLine: spec.blankLine || (() => { }),
        startState: spec.startState || (() => true),
        copyState: spec.copyState || defaultCopyState,
        indent: spec.indent || (() => null),
        languageData: spec.languageData || {},
        tokenTable: spec.tokenTable || noTokens,
        mergeTokens: spec.mergeTokens !== false
    };
}
function defaultCopyState(state) {
    if (typeof state != "object")
        return state;
    let newState = {};
    for (let prop in state) {
        let val = state[prop];
        newState[prop] = (val instanceof Array ? val.slice() : val);
    }
    return newState;
}
const IndentedFrom = /*@__PURE__*/new WeakMap();
/**
A [language](https://codemirror.net/6/docs/ref/#language.Language) class based on a CodeMirror
5-style [streaming parser](https://codemirror.net/6/docs/ref/#language.StreamParser).
*/
class StreamLanguage extends Language {
    constructor(parser) {
        let data = defineLanguageFacet(parser.languageData);
        let p = fullParser(parser), self;
        let impl = new class extends Parser {
            createParse(input, fragments, ranges) {
                return new Parse(self, input, fragments, ranges);
            }
        };
        super(data, impl, [], parser.name);
        this.topNode = docID(data, this);
        self = this;
        this.streamParser = p;
        this.stateAfter = new NodeProp({ perNode: true });
        this.tokenTable = parser.tokenTable ? new TokenTable(p.tokenTable) : defaultTokenTable;
    }
    /**
    Define a stream language.
    */
    static define(spec) { return new StreamLanguage(spec); }
    /**
    @internal
    */
    getIndent(cx) {
        let from = undefined;
        let { overrideIndentation } = cx.options;
        if (overrideIndentation) {
            from = IndentedFrom.get(cx.state);
            if (from != null && from < cx.pos - 1e4)
                from = undefined;
        }
        let start = findState(this, cx.node.tree, cx.node.from, cx.node.from, from !== null && from !== void 0 ? from : cx.pos), statePos, state;
        if (start) {
            state = start.state;
            statePos = start.pos + 1;
        }
        else {
            state = this.streamParser.startState(cx.unit);
            statePos = cx.node.from;
        }
        if (cx.pos - statePos > 10000 /* C.MaxIndentScanDist */)
            return null;
        while (statePos < cx.pos) {
            let line = cx.state.doc.lineAt(statePos), end = Math.min(cx.pos, line.to);
            if (line.length) {
                let indentation = overrideIndentation ? overrideIndentation(line.from) : -1;
                let stream = new StringStream(line.text, cx.state.tabSize, cx.unit, indentation < 0 ? undefined : indentation);
                while (stream.pos < end - line.from)
                    readToken(this.streamParser.token, stream, state);
            }
            else {
                this.streamParser.blankLine(state, cx.unit);
            }
            if (end == cx.pos)
                break;
            statePos = line.to + 1;
        }
        let line = cx.lineAt(cx.pos);
        if (overrideIndentation && from == null)
            IndentedFrom.set(cx.state, line.from);
        return this.streamParser.indent(state, /^\s*(.*)/.exec(line.text)[1], cx);
    }
    get allowsNesting() { return false; }
}
function findState(lang, tree, off, startPos, before) {
    let state = off >= startPos && off + tree.length <= before && tree.prop(lang.stateAfter);
    if (state)
        return { state: lang.streamParser.copyState(state), pos: off + tree.length };
    for (let i = tree.children.length - 1; i >= 0; i--) {
        let child = tree.children[i], pos = off + tree.positions[i];
        let found = child instanceof Tree && pos < before && findState(lang, child, pos, startPos, before);
        if (found)
            return found;
    }
    return null;
}
function cutTree(lang, tree, from, to, inside) {
    if (inside && from <= 0 && to >= tree.length)
        return tree;
    if (!inside && from == 0 && tree.type == lang.topNode)
        inside = true;
    for (let i = tree.children.length - 1; i >= 0; i--) {
        let pos = tree.positions[i], child = tree.children[i], inner;
        if (pos < to && child instanceof Tree) {
            if (!(inner = cutTree(lang, child, from - pos, to - pos, inside)))
                break;
            return !inside ? inner
                : new Tree(tree.type, tree.children.slice(0, i).concat(inner), tree.positions.slice(0, i + 1), pos + inner.length);
        }
    }
    return null;
}
function findStartInFragments(lang, fragments, startPos, endPos, editorState) {
    for (let f of fragments) {
        let from = f.from + (f.openStart ? 25 : 0), to = f.to - (f.openEnd ? 25 : 0);
        let found = from <= startPos && to > startPos && findState(lang, f.tree, 0 - f.offset, startPos, to), tree;
        if (found && found.pos <= endPos && (tree = cutTree(lang, f.tree, startPos + f.offset, found.pos + f.offset, false)))
            return { state: found.state, tree };
    }
    return { state: lang.streamParser.startState(editorState ? getIndentUnit(editorState) : 4), tree: Tree.empty };
}
class Parse {
    constructor(lang, input, fragments, ranges) {
        this.lang = lang;
        this.input = input;
        this.fragments = fragments;
        this.ranges = ranges;
        this.stoppedAt = null;
        this.chunks = [];
        this.chunkPos = [];
        this.chunk = [];
        this.chunkReused = undefined;
        this.rangeIndex = 0;
        this.to = ranges[ranges.length - 1].to;
        let context = ParseContext.get(), from = ranges[0].from;
        let { state, tree } = findStartInFragments(lang, fragments, from, this.to, context === null || context === void 0 ? void 0 : context.state);
        this.state = state;
        this.parsedPos = this.chunkStart = from + tree.length;
        for (let i = 0; i < tree.children.length; i++) {
            this.chunks.push(tree.children[i]);
            this.chunkPos.push(tree.positions[i]);
        }
        if (context && this.parsedPos < context.viewport.from - 100000 /* C.MaxDistanceBeforeViewport */ &&
            ranges.some(r => r.from <= context.viewport.from && r.to >= context.viewport.from)) {
            this.state = this.lang.streamParser.startState(getIndentUnit(context.state));
            context.skipUntilInView(this.parsedPos, context.viewport.from);
            this.parsedPos = context.viewport.from;
        }
        this.moveRangeIndex();
    }
    advance() {
        let context = ParseContext.get();
        let parseEnd = this.stoppedAt == null ? this.to : Math.min(this.to, this.stoppedAt);
        let end = Math.min(parseEnd, this.chunkStart + 512 /* C.ChunkSize */);
        if (context)
            end = Math.min(end, context.viewport.to);
        while (this.parsedPos < end)
            this.parseLine(context);
        if (this.chunkStart < this.parsedPos)
            this.finishChunk();
        if (this.parsedPos >= parseEnd)
            return this.finish();
        if (context && this.parsedPos >= context.viewport.to) {
            context.skipUntilInView(this.parsedPos, parseEnd);
            return this.finish();
        }
        return null;
    }
    stopAt(pos) {
        this.stoppedAt = pos;
    }
    lineAfter(pos) {
        let chunk = this.input.chunk(pos);
        if (!this.input.lineChunks) {
            let eol = chunk.indexOf("\n");
            if (eol > -1)
                chunk = chunk.slice(0, eol);
        }
        else if (chunk == "\n") {
            chunk = "";
        }
        return pos + chunk.length <= this.to ? chunk : chunk.slice(0, this.to - pos);
    }
    nextLine() {
        let from = this.parsedPos, line = this.lineAfter(from), end = from + line.length;
        for (let index = this.rangeIndex;;) {
            let rangeEnd = this.ranges[index].to;
            if (rangeEnd >= end)
                break;
            line = line.slice(0, rangeEnd - (end - line.length));
            index++;
            if (index == this.ranges.length)
                break;
            let rangeStart = this.ranges[index].from;
            let after = this.lineAfter(rangeStart);
            line += after;
            end = rangeStart + after.length;
        }
        return { line, end };
    }
    skipGapsTo(pos, offset, side) {
        for (;;) {
            let end = this.ranges[this.rangeIndex].to, offPos = pos + offset;
            if (side > 0 ? end > offPos : end >= offPos)
                break;
            let start = this.ranges[++this.rangeIndex].from;
            offset += start - end;
        }
        return offset;
    }
    moveRangeIndex() {
        while (this.ranges[this.rangeIndex].to < this.parsedPos)
            this.rangeIndex++;
    }
    emitToken(id, from, to, offset) {
        let size = 4;
        if (this.ranges.length > 1) {
            offset = this.skipGapsTo(from, offset, 1);
            from += offset;
            let len0 = this.chunk.length;
            offset = this.skipGapsTo(to, offset, -1);
            to += offset;
            size += this.chunk.length - len0;
        }
        let last = this.chunk.length - 4;
        if (this.lang.streamParser.mergeTokens && size == 4 && last >= 0 &&
            this.chunk[last] == id && this.chunk[last + 2] == from)
            this.chunk[last + 2] = to;
        else
            this.chunk.push(id, from, to, size);
        return offset;
    }
    parseLine(context) {
        let { line, end } = this.nextLine(), offset = 0, { streamParser } = this.lang;
        let stream = new StringStream(line, context ? context.state.tabSize : 4, context ? getIndentUnit(context.state) : 2);
        if (stream.eol()) {
            streamParser.blankLine(this.state, stream.indentUnit);
        }
        else {
            while (!stream.eol()) {
                let token = readToken(streamParser.token, stream, this.state);
                if (token)
                    offset = this.emitToken(this.lang.tokenTable.resolve(token), this.parsedPos + stream.start, this.parsedPos + stream.pos, offset);
                if (stream.start > 10000 /* C.MaxLineLength */)
                    break;
            }
        }
        this.parsedPos = end;
        this.moveRangeIndex();
        if (this.parsedPos < this.to)
            this.parsedPos++;
    }
    finishChunk() {
        let tree = Tree.build({
            buffer: this.chunk,
            start: this.chunkStart,
            length: this.parsedPos - this.chunkStart,
            nodeSet,
            topID: 0,
            maxBufferLength: 512 /* C.ChunkSize */,
            reused: this.chunkReused
        });
        tree = new Tree(tree.type, tree.children, tree.positions, tree.length, [[this.lang.stateAfter, this.lang.streamParser.copyState(this.state)]]);
        this.chunks.push(tree);
        this.chunkPos.push(this.chunkStart - this.ranges[0].from);
        this.chunk = [];
        this.chunkReused = undefined;
        this.chunkStart = this.parsedPos;
    }
    finish() {
        return new Tree(this.lang.topNode, this.chunks, this.chunkPos, this.parsedPos - this.ranges[0].from).balance();
    }
}
function readToken(token, stream, state) {
    stream.start = stream.pos;
    for (let i = 0; i < 10; i++) {
        let result = token(stream, state);
        if (stream.pos > stream.start)
            return result;
    }
    throw new Error("Stream parser failed to advance stream.");
}
const noTokens = /*@__PURE__*/Object.create(null);
const typeArray = [dist_NodeType.none];
const nodeSet = /*@__PURE__*/new NodeSet(typeArray);
const warned = [];
// Cache of node types by name and tags
const byTag = /*@__PURE__*/Object.create(null);
const defaultTable = /*@__PURE__*/Object.create(null);
for (let [legacyName, name] of [
    ["variable", "variableName"],
    ["variable-2", "variableName.special"],
    ["string-2", "string.special"],
    ["def", "variableName.definition"],
    ["tag", "tagName"],
    ["attribute", "attributeName"],
    ["type", "typeName"],
    ["builtin", "variableName.standard"],
    ["qualifier", "modifier"],
    ["error", "invalid"],
    ["header", "heading"],
    ["property", "propertyName"]
])
    defaultTable[legacyName] = /*@__PURE__*/createTokenType(noTokens, name);
class TokenTable {
    constructor(extra) {
        this.extra = extra;
        this.table = Object.assign(Object.create(null), defaultTable);
    }
    resolve(tag) {
        return !tag ? 0 : this.table[tag] || (this.table[tag] = createTokenType(this.extra, tag));
    }
}
const defaultTokenTable = /*@__PURE__*/new TokenTable(noTokens);
function warnForPart(part, msg) {
    if (warned.indexOf(part) > -1)
        return;
    warned.push(part);
    console.warn(msg);
}
function createTokenType(extra, tagStr) {
    let tags$1 = [];
    for (let name of tagStr.split(" ")) {
        let found = [];
        for (let part of name.split(".")) {
            let value = (extra[part] || tags[part]);
            if (!value) {
                warnForPart(part, `Unknown highlighting tag ${part}`);
            }
            else if (typeof value == "function") {
                if (!found.length)
                    warnForPart(part, `Modifier ${part} used at start of tag`);
                else
                    found = found.map(value);
            }
            else {
                if (found.length)
                    warnForPart(part, `Tag ${part} used as modifier`);
                else
                    found = Array.isArray(value) ? value : [value];
            }
        }
        for (let tag of found)
            tags$1.push(tag);
    }
    if (!tags$1.length)
        return 0;
    let name = tagStr.replace(/ /g, "_"), key = name + " " + tags$1.map(t => t.id);
    let known = byTag[key];
    if (known)
        return known.id;
    let type = byTag[key] = dist_NodeType.define({
        id: typeArray.length,
        name,
        props: [styleTags({ [name]: tags$1 })]
    });
    typeArray.push(type);
    return type.id;
}
function docID(data, lang) {
    let type = dist_NodeType.define({ id: typeArray.length, name: "Document", props: [
            languageDataProp.add(() => data),
            indentNodeProp.add(() => cx => lang.getIndent(cx))
        ], top: true });
    typeArray.push(type);
    return type;
}

function buildForLine(line) {
    return line.length <= 4096 && /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/.test(line);
}
function textHasRTL(text) {
    for (let i = text.iter(); !i.next().done;)
        if (buildForLine(i.value))
            return true;
    return false;
}
function changeAddsRTL(change) {
    let added = false;
    change.iterChanges((fA, tA, fB, tB, ins) => {
        if (!added && textHasRTL(ins))
            added = true;
    });
    return added;
}
const alwaysIsolate = /*@__PURE__*/Facet.define({ combine: values => values.some(x => x) });
/**
Make sure nodes
[marked](https://lezer.codemirror.net/docs/ref/#common.NodeProp^isolate)
as isolating for bidirectional text are rendered in a way that
isolates them from the surrounding text.
*/
function bidiIsolates(options = {}) {
    let extensions = [isolateMarks];
    if (options.alwaysIsolate)
        extensions.push(alwaysIsolate.of(true));
    return extensions;
}
const isolateMarks = /*@__PURE__*/dist_ViewPlugin.fromClass(class {
    constructor(view) {
        this.always = view.state.facet(alwaysIsolate) ||
            view.textDirection != Direction.LTR ||
            view.state.facet(dist_EditorView.perLineTextDirection);
        this.hasRTL = !this.always && textHasRTL(view.state.doc);
        this.tree = dist_syntaxTree(view.state);
        this.decorations = this.always || this.hasRTL ? buildDeco(view, this.tree, this.always) : dist_Decoration.none;
    }
    update(update) {
        let always = update.state.facet(alwaysIsolate) ||
            update.view.textDirection != Direction.LTR ||
            update.state.facet(dist_EditorView.perLineTextDirection);
        if (!always && !this.hasRTL && changeAddsRTL(update.changes))
            this.hasRTL = true;
        if (!always && !this.hasRTL)
            return;
        let tree = dist_syntaxTree(update.state);
        if (always != this.always || tree != this.tree || update.docChanged || update.viewportChanged) {
            this.tree = tree;
            this.always = always;
            this.decorations = buildDeco(update.view, tree, always);
        }
    }
}, {
    provide: plugin => {
        function access(view) {
            var _a, _b;
            return (_b = (_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.decorations) !== null && _b !== void 0 ? _b : dist_Decoration.none;
        }
        return [dist_EditorView.outerDecorations.of(access),
            Prec.lowest(dist_EditorView.bidiIsolatedRanges.of(access))];
    }
});
function buildDeco(view, tree, always) {
    let deco = new RangeSetBuilder();
    let ranges = view.visibleRanges;
    if (!always)
        ranges = clipRTLLines(ranges, view.state.doc);
    for (let { from, to } of ranges) {
        tree.iterate({
            enter: node => {
                let iso = node.type.prop(NodeProp.isolate);
                if (iso)
                    deco.add(node.from, node.to, marks[iso]);
            },
            from, to
        });
    }
    return deco.finish();
}
function clipRTLLines(ranges, doc) {
    let cur = doc.iter(), pos = 0, result = [], last = null;
    for (let { from, to } of ranges) {
        if (last && last.to > from) {
            from = last.to;
            if (from >= to)
                continue;
        }
        if (pos + cur.value.length < from) {
            cur.next(from - (pos + cur.value.length));
            pos = from;
        }
        for (;;) {
            let start = pos, end = pos + cur.value.length;
            if (!cur.lineBreak && buildForLine(cur.value)) {
                if (last && last.to > start - 10)
                    last.to = Math.min(to, end);
                else
                    result.push(last = { from: start, to: Math.min(to, end) });
            }
            if (end >= to)
                break;
            pos = end;
            cur.next();
        }
    }
    return result;
}
const marks = {
    rtl: /*@__PURE__*/dist_Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "rtl" }, bidiIsolate: Direction.RTL }),
    ltr: /*@__PURE__*/dist_Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "ltr" }, bidiIsolate: Direction.LTR }),
    auto: /*@__PURE__*/dist_Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "auto" }, bidiIsolate: null })
};



;// ../../node_modules/@codemirror/autocomplete/dist/index.js




/**
An instance of this is passed to completion source functions.
*/
class CompletionContext {
    /**
    Create a new completion context. (Mostly useful for testing
    completion sources—in the editor, the extension will create
    these for you.)
    */
    constructor(
    /**
    The editor state that the completion happens in.
    */
    state, 
    /**
    The position at which the completion is happening.
    */
    pos, 
    /**
    Indicates whether completion was activated explicitly, or
    implicitly by typing. The usual way to respond to this is to
    only return completions when either there is part of a
    completable entity before the cursor, or `explicit` is true.
    */
    explicit, 
    /**
    The editor view. May be undefined if the context was created
    in a situation where there is no such view available, such as
    in synchronous updates via
    [`CompletionResult.update`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.update)
    or when called by test code.
    */
    view) {
        this.state = state;
        this.pos = pos;
        this.explicit = explicit;
        this.view = view;
        /**
        @internal
        */
        this.abortListeners = [];
        /**
        @internal
        */
        this.abortOnDocChange = false;
    }
    /**
    Get the extent, content, and (if there is a token) type of the
    token before `this.pos`.
    */
    tokenBefore(types) {
        let token = dist_syntaxTree(this.state).resolveInner(this.pos, -1);
        while (token && types.indexOf(token.name) < 0)
            token = token.parent;
        return token ? { from: token.from, to: this.pos,
            text: this.state.sliceDoc(token.from, this.pos),
            type: token.type } : null;
    }
    /**
    Get the match of the given expression directly before the
    cursor.
    */
    matchBefore(expr) {
        let line = this.state.doc.lineAt(this.pos);
        let start = Math.max(line.from, this.pos - 250);
        let str = line.text.slice(start - line.from, this.pos - line.from);
        let found = str.search(ensureAnchor(expr, false));
        return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) };
    }
    /**
    Yields true when the query has been aborted. Can be useful in
    asynchronous queries to avoid doing work that will be ignored.
    */
    get aborted() { return this.abortListeners == null; }
    /**
    Allows you to register abort handlers, which will be called when
    the query is
    [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
    
    By default, running queries will not be aborted for regular
    typing or backspacing, on the assumption that they are likely to
    return a result with a
    [`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor) field that
    allows the result to be used after all. Passing `onDocChange:
    true` will cause this query to be aborted for any document
    change.
    */
    addEventListener(type, listener, options) {
        if (type == "abort" && this.abortListeners) {
            this.abortListeners.push(listener);
            if (options && options.onDocChange)
                this.abortOnDocChange = true;
        }
    }
}
function toSet(chars) {
    let flat = Object.keys(chars).join("");
    let words = /\w/.test(flat);
    if (words)
        flat = flat.replace(/\w/g, "");
    return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
}
function prefixMatch(options) {
    let first = Object.create(null), rest = Object.create(null);
    for (let { label } of options) {
        first[label[0]] = true;
        for (let i = 1; i < label.length; i++)
            rest[label[i]] = true;
    }
    let source = toSet(first) + toSet(rest) + "*$";
    return [new RegExp("^" + source), new RegExp(source)];
}
/**
Given a a fixed array of options, return an autocompleter that
completes them.
*/
function completeFromList(list) {
    let options = list.map(o => typeof o == "string" ? { label: o } : o);
    let [validFor, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options);
    return (context) => {
        let token = context.matchBefore(match);
        return token || context.explicit ? { from: token ? token.from : context.pos, options, validFor } : null;
    };
}
/**
Wrap the given completion source so that it will only fire when the
cursor is in a syntax node with one of the given names.
*/
function ifIn(nodes, source) {
    return (context) => {
        for (let pos = syntaxTree(context.state).resolveInner(context.pos, -1); pos; pos = pos.parent) {
            if (nodes.indexOf(pos.name) > -1)
                return source(context);
            if (pos.type.isTop)
                break;
        }
        return null;
    };
}
/**
Wrap the given completion source so that it will not fire when the
cursor is in a syntax node with one of the given names.
*/
function ifNotIn(nodes, source) {
    return (context) => {
        for (let pos = dist_syntaxTree(context.state).resolveInner(context.pos, -1); pos; pos = pos.parent) {
            if (nodes.indexOf(pos.name) > -1)
                return null;
            if (pos.type.isTop)
                break;
        }
        return source(context);
    };
}
class Option {
    constructor(completion, source, match, score) {
        this.completion = completion;
        this.source = source;
        this.match = match;
        this.score = score;
    }
}
function cur(state) { return state.selection.main.from; }
// Make sure the given regexp has a $ at its end and, if `start` is
// true, a ^ at its start.
function ensureAnchor(expr, start) {
    var _a;
    let { source } = expr;
    let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$";
    if (!addStart && !addEnd)
        return expr;
    return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? "i" : ""));
}
/**
This annotation is added to transactions that are produced by
picking a completion.
*/
const pickedCompletion = /*@__PURE__*/Annotation.define();
/**
Helper function that returns a transaction spec which inserts a
completion's text in the main selection range, and any other
selection range that has the same text in front of it.
*/
function insertCompletionText(state, text, from, to) {
    let { main } = state.selection, fromOff = from - main.from, toOff = to - main.from;
    return {
        ...state.changeByRange(range => {
            if (range != main && from != to &&
                state.sliceDoc(range.from + fromOff, range.from + toOff) != state.sliceDoc(from, to))
                return { range };
            let lines = state.toText(text);
            return {
                changes: { from: range.from + fromOff, to: to == main.from ? range.to : range.from + toOff, insert: lines },
                range: dist_EditorSelection.cursor(range.from + fromOff + lines.length)
            };
        }),
        scrollIntoView: true,
        userEvent: "input.complete"
    };
}
const SourceCache = /*@__PURE__*/new WeakMap();
function asSource(source) {
    if (!Array.isArray(source))
        return source;
    let known = SourceCache.get(source);
    if (!known)
        SourceCache.set(source, known = completeFromList(source));
    return known;
}
const startCompletionEffect = /*@__PURE__*/dist_StateEffect.define();
const closeCompletionEffect = /*@__PURE__*/dist_StateEffect.define();

// A pattern matcher for fuzzy completion matching. Create an instance
// once for a pattern, and then use that to match any number of
// completions.
class FuzzyMatcher {
    constructor(pattern) {
        this.pattern = pattern;
        this.chars = [];
        this.folded = [];
        // Buffers reused by calls to `match` to track matched character
        // positions.
        this.any = [];
        this.precise = [];
        this.byWord = [];
        this.score = 0;
        this.matched = [];
        for (let p = 0; p < pattern.length;) {
            let char = dist_codePointAt(pattern, p), size = dist_codePointSize(char);
            this.chars.push(char);
            let part = pattern.slice(p, p + size), upper = part.toUpperCase();
            this.folded.push(dist_codePointAt(upper == part ? part.toLowerCase() : upper, 0));
            p += size;
        }
        this.astral = pattern.length != this.chars.length;
    }
    ret(score, matched) {
        this.score = score;
        this.matched = matched;
        return this;
    }
    // Matches a given word (completion) against the pattern (input).
    // Will return a boolean indicating whether there was a match and,
    // on success, set `this.score` to the score, `this.matched` to an
    // array of `from, to` pairs indicating the matched parts of `word`.
    //
    // The score is a number that is more negative the worse the match
    // is. See `Penalty` above.
    match(word) {
        if (this.pattern.length == 0)
            return this.ret(-100 /* Penalty.NotFull */, []);
        if (word.length < this.pattern.length)
            return null;
        let { chars, folded, any, precise, byWord } = this;
        // For single-character queries, only match when they occur right
        // at the start
        if (chars.length == 1) {
            let first = dist_codePointAt(word, 0), firstSize = dist_codePointSize(first);
            let score = firstSize == word.length ? 0 : -100 /* Penalty.NotFull */;
            if (first == chars[0]) ;
            else if (first == folded[0])
                score += -200 /* Penalty.CaseFold */;
            else
                return null;
            return this.ret(score, [0, firstSize]);
        }
        let direct = word.indexOf(this.pattern);
        if (direct == 0)
            return this.ret(word.length == this.pattern.length ? 0 : -100 /* Penalty.NotFull */, [0, this.pattern.length]);
        let len = chars.length, anyTo = 0;
        if (direct < 0) {
            for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {
                let next = dist_codePointAt(word, i);
                if (next == chars[anyTo] || next == folded[anyTo])
                    any[anyTo++] = i;
                i += dist_codePointSize(next);
            }
            // No match, exit immediately
            if (anyTo < len)
                return null;
        }
        // This tracks the extent of the precise (non-folded, not
        // necessarily adjacent) match
        let preciseTo = 0;
        // Tracks whether there is a match that hits only characters that
        // appear to be starting words. `byWordFolded` is set to true when
        // a case folded character is encountered in such a match
        let byWordTo = 0, byWordFolded = false;
        // If we've found a partial adjacent match, these track its state
        let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;
        let hasLower = /[a-z]/.test(word), wordAdjacent = true;
        // Go over the option's text, scanning for the various kinds of matches
        for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* Tp.NonWord */; i < e && byWordTo < len;) {
            let next = dist_codePointAt(word, i);
            if (direct < 0) {
                if (preciseTo < len && next == chars[preciseTo])
                    precise[preciseTo++] = i;
                if (adjacentTo < len) {
                    if (next == chars[adjacentTo] || next == folded[adjacentTo]) {
                        if (adjacentTo == 0)
                            adjacentStart = i;
                        adjacentEnd = i + 1;
                        adjacentTo++;
                    }
                    else {
                        adjacentTo = 0;
                    }
                }
            }
            let ch, type = next < 0xff
                ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Tp.Lower */ : next >= 65 && next <= 90 ? 1 /* Tp.Upper */ : 0 /* Tp.NonWord */)
                : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Tp.Upper */ : ch != ch.toUpperCase() ? 2 /* Tp.Lower */ : 0 /* Tp.NonWord */);
            if (!i || type == 1 /* Tp.Upper */ && hasLower || prevType == 0 /* Tp.NonWord */ && type != 0 /* Tp.NonWord */) {
                if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true)))
                    byWord[byWordTo++] = i;
                else if (byWord.length)
                    wordAdjacent = false;
            }
            prevType = type;
            i += dist_codePointSize(next);
        }
        if (byWordTo == len && byWord[0] == 0 && wordAdjacent)
            return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0), byWord, word);
        if (adjacentTo == len && adjacentStart == 0)
            return this.ret(-200 /* Penalty.CaseFold */ - word.length + (adjacentEnd == word.length ? 0 : -100 /* Penalty.NotFull */), [0, adjacentEnd]);
        if (direct > -1)
            return this.ret(-700 /* Penalty.NotStart */ - word.length, [direct, direct + this.pattern.length]);
        if (adjacentTo == len)
            return this.ret(-200 /* Penalty.CaseFold */ + -700 /* Penalty.NotStart */ - word.length, [adjacentStart, adjacentEnd]);
        if (byWordTo == len)
            return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0) + -700 /* Penalty.NotStart */ +
                (wordAdjacent ? 0 : -1100 /* Penalty.Gap */), byWord, word);
        return chars.length == 2 ? null
            : this.result((any[0] ? -700 /* Penalty.NotStart */ : 0) + -200 /* Penalty.CaseFold */ + -1100 /* Penalty.Gap */, any, word);
    }
    result(score, positions, word) {
        let result = [], i = 0;
        for (let pos of positions) {
            let to = pos + (this.astral ? dist_codePointSize(dist_codePointAt(word, pos)) : 1);
            if (i && result[i - 1] == pos)
                result[i - 1] = to;
            else {
                result[i++] = pos;
                result[i++] = to;
            }
        }
        return this.ret(score - word.length, result);
    }
}
class StrictMatcher {
    constructor(pattern) {
        this.pattern = pattern;
        this.matched = [];
        this.score = 0;
        this.folded = pattern.toLowerCase();
    }
    match(word) {
        if (word.length < this.pattern.length)
            return null;
        let start = word.slice(0, this.pattern.length);
        let match = start == this.pattern ? 0 : start.toLowerCase() == this.folded ? -200 /* Penalty.CaseFold */ : null;
        if (match == null)
            return null;
        this.matched = [0, start.length];
        this.score = match + (word.length == this.pattern.length ? 0 : -100 /* Penalty.NotFull */);
        return this;
    }
}

const completionConfig = /*@__PURE__*/Facet.define({
    combine(configs) {
        return combineConfig(configs, {
            activateOnTyping: true,
            activateOnCompletion: () => false,
            activateOnTypingDelay: 100,
            selectOnOpen: true,
            override: null,
            closeOnBlur: true,
            maxRenderedOptions: 100,
            defaultKeymap: true,
            tooltipClass: () => "",
            optionClass: () => "",
            aboveCursor: false,
            icons: true,
            addToOptions: [],
            positionInfo: defaultPositionInfo,
            filterStrict: false,
            compareCompletions: (a, b) => (a.sortText || a.label).localeCompare(b.sortText || b.label),
            interactionDelay: 75,
            updateSyncTime: 100
        }, {
            defaultKeymap: (a, b) => a && b,
            closeOnBlur: (a, b) => a && b,
            icons: (a, b) => a && b,
            tooltipClass: (a, b) => c => joinClass(a(c), b(c)),
            optionClass: (a, b) => c => joinClass(a(c), b(c)),
            addToOptions: (a, b) => a.concat(b),
            filterStrict: (a, b) => a || b,
        });
    }
});
function joinClass(a, b) {
    return a ? b ? a + " " + b : a : b;
}
function defaultPositionInfo(view, list, option, info, space, tooltip) {
    let rtl = view.textDirection == Direction.RTL, left = rtl, narrow = false;
    let side = "top", offset, maxWidth;
    let spaceLeft = list.left - space.left, spaceRight = space.right - list.right;
    let infoWidth = info.right - info.left, infoHeight = info.bottom - info.top;
    if (left && spaceLeft < Math.min(infoWidth, spaceRight))
        left = false;
    else if (!left && spaceRight < Math.min(infoWidth, spaceLeft))
        left = true;
    if (infoWidth <= (left ? spaceLeft : spaceRight)) {
        offset = Math.max(space.top, Math.min(option.top, space.bottom - infoHeight)) - list.top;
        maxWidth = Math.min(400 /* Info.Width */, left ? spaceLeft : spaceRight);
    }
    else {
        narrow = true;
        maxWidth = Math.min(400 /* Info.Width */, (rtl ? list.right : space.right - list.left) - 30 /* Info.Margin */);
        let spaceBelow = space.bottom - list.bottom;
        if (spaceBelow >= infoHeight || spaceBelow > list.top) { // Below the completion
            offset = option.bottom - list.top;
        }
        else { // Above it
            side = "bottom";
            offset = list.bottom - option.top;
        }
    }
    let scaleY = (list.bottom - list.top) / tooltip.offsetHeight;
    let scaleX = (list.right - list.left) / tooltip.offsetWidth;
    return {
        style: `${side}: ${offset / scaleY}px; max-width: ${maxWidth / scaleX}px`,
        class: "cm-completionInfo-" + (narrow ? (rtl ? "left-narrow" : "right-narrow") : left ? "left" : "right")
    };
}

function optionContent(config) {
    let content = config.addToOptions.slice();
    if (config.icons)
        content.push({
            render(completion) {
                let icon = document.createElement("div");
                icon.classList.add("cm-completionIcon");
                if (completion.type)
                    icon.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls));
                icon.setAttribute("aria-hidden", "true");
                return icon;
            },
            position: 20
        });
    content.push({
        render(completion, _s, _v, match) {
            let labelElt = document.createElement("span");
            labelElt.className = "cm-completionLabel";
            let label = completion.displayLabel || completion.label, off = 0;
            for (let j = 0; j < match.length;) {
                let from = match[j++], to = match[j++];
                if (from > off)
                    labelElt.appendChild(document.createTextNode(label.slice(off, from)));
                let span = labelElt.appendChild(document.createElement("span"));
                span.appendChild(document.createTextNode(label.slice(from, to)));
                span.className = "cm-completionMatchedText";
                off = to;
            }
            if (off < label.length)
                labelElt.appendChild(document.createTextNode(label.slice(off)));
            return labelElt;
        },
        position: 50
    }, {
        render(completion) {
            if (!completion.detail)
                return null;
            let detailElt = document.createElement("span");
            detailElt.className = "cm-completionDetail";
            detailElt.textContent = completion.detail;
            return detailElt;
        },
        position: 80
    });
    return content.sort((a, b) => a.position - b.position).map(a => a.render);
}
function rangeAroundSelected(total, selected, max) {
    if (total <= max)
        return { from: 0, to: total };
    if (selected < 0)
        selected = 0;
    if (selected <= (total >> 1)) {
        let off = Math.floor(selected / max);
        return { from: off * max, to: (off + 1) * max };
    }
    let off = Math.floor((total - selected) / max);
    return { from: total - (off + 1) * max, to: total - off * max };
}
class CompletionTooltip {
    constructor(view, stateField, applyCompletion) {
        this.view = view;
        this.stateField = stateField;
        this.applyCompletion = applyCompletion;
        this.info = null;
        this.infoDestroy = null;
        this.placeInfoReq = {
            read: () => this.measureInfo(),
            write: (pos) => this.placeInfo(pos),
            key: this
        };
        this.space = null;
        this.currentClass = "";
        let cState = view.state.field(stateField);
        let { options, selected } = cState.open;
        let config = view.state.facet(completionConfig);
        this.optionContent = optionContent(config);
        this.optionClass = config.optionClass;
        this.tooltipClass = config.tooltipClass;
        this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions);
        this.dom = document.createElement("div");
        this.dom.className = "cm-tooltip-autocomplete";
        this.updateTooltipClass(view.state);
        this.dom.addEventListener("mousedown", (e) => {
            let { options } = view.state.field(stateField).open;
            for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) {
                if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) {
                    this.applyCompletion(view, options[+match[1]]);
                    e.preventDefault();
                    return;
                }
            }
        });
        this.dom.addEventListener("focusout", (e) => {
            let state = view.state.field(this.stateField, false);
            if (state && state.tooltip && view.state.facet(completionConfig).closeOnBlur &&
                e.relatedTarget != view.contentDOM)
                view.dispatch({ effects: closeCompletionEffect.of(null) });
        });
        this.showOptions(options, cState.id);
    }
    mount() { this.updateSel(); }
    showOptions(options, id) {
        if (this.list)
            this.list.remove();
        this.list = this.dom.appendChild(this.createListBox(options, id, this.range));
        this.list.addEventListener("scroll", () => {
            if (this.info)
                this.view.requestMeasure(this.placeInfoReq);
        });
    }
    update(update) {
        var _a;
        let cState = update.state.field(this.stateField);
        let prevState = update.startState.field(this.stateField);
        this.updateTooltipClass(update.state);
        if (cState != prevState) {
            let { options, selected, disabled } = cState.open;
            if (!prevState.open || prevState.open.options != options) {
                this.range = rangeAroundSelected(options.length, selected, update.state.facet(completionConfig).maxRenderedOptions);
                this.showOptions(options, cState.id);
            }
            this.updateSel();
            if (disabled != ((_a = prevState.open) === null || _a === void 0 ? void 0 : _a.disabled))
                this.dom.classList.toggle("cm-tooltip-autocomplete-disabled", !!disabled);
        }
    }
    updateTooltipClass(state) {
        let cls = this.tooltipClass(state);
        if (cls != this.currentClass) {
            for (let c of this.currentClass.split(" "))
                if (c)
                    this.dom.classList.remove(c);
            for (let c of cls.split(" "))
                if (c)
                    this.dom.classList.add(c);
            this.currentClass = cls;
        }
    }
    positioned(space) {
        this.space = space;
        if (this.info)
            this.view.requestMeasure(this.placeInfoReq);
    }
    updateSel() {
        let cState = this.view.state.field(this.stateField), open = cState.open;
        if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) {
            this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions);
            this.showOptions(open.options, cState.id);
        }
        let newSel = this.updateSelectedOption(open.selected);
        if (newSel) {
            this.destroyInfo();
            let { completion } = open.options[open.selected];
            let { info } = completion;
            if (!info)
                return;
            let infoResult = typeof info === "string" ? document.createTextNode(info) : info(completion);
            if (!infoResult)
                return;
            if ("then" in infoResult) {
                infoResult.then(obj => {
                    if (obj && this.view.state.field(this.stateField, false) == cState)
                        this.addInfoPane(obj, completion);
                }).catch(e => logException(this.view.state, e, "completion info"));
            }
            else {
                this.addInfoPane(infoResult, completion);
                newSel.setAttribute("aria-describedby", this.info.id);
            }
        }
    }
    addInfoPane(content, completion) {
        this.destroyInfo();
        let wrap = this.info = document.createElement("div");
        wrap.className = "cm-tooltip cm-completionInfo";
        wrap.id = "cm-completionInfo-" + Math.floor(Math.random() * 0xffff).toString(16);
        if (content.nodeType != null) {
            wrap.appendChild(content);
            this.infoDestroy = null;
        }
        else {
            let { dom, destroy } = content;
            wrap.appendChild(dom);
            this.infoDestroy = destroy || null;
        }
        this.dom.appendChild(wrap);
        this.view.requestMeasure(this.placeInfoReq);
    }
    updateSelectedOption(selected) {
        let set = null;
        for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) {
            if (opt.nodeName != "LI" || !opt.id) {
                i--; // A section header
            }
            else if (i == selected) {
                if (!opt.hasAttribute("aria-selected")) {
                    opt.setAttribute("aria-selected", "true");
                    set = opt;
                }
            }
            else {
                if (opt.hasAttribute("aria-selected")) {
                    opt.removeAttribute("aria-selected");
                    opt.removeAttribute("aria-describedby");
                }
            }
        }
        if (set)
            dist_scrollIntoView(this.list, set);
        return set;
    }
    measureInfo() {
        let sel = this.dom.querySelector("[aria-selected]");
        if (!sel || !this.info)
            return null;
        let listRect = this.dom.getBoundingClientRect();
        let infoRect = this.info.getBoundingClientRect();
        let selRect = sel.getBoundingClientRect();
        let space = this.space;
        if (!space) {
            let docElt = this.dom.ownerDocument.documentElement;
            space = { left: 0, top: 0, right: docElt.clientWidth, bottom: docElt.clientHeight };
        }
        if (selRect.top > Math.min(space.bottom, listRect.bottom) - 10 ||
            selRect.bottom < Math.max(space.top, listRect.top) + 10)
            return null;
        return this.view.state.facet(completionConfig).positionInfo(this.view, listRect, selRect, infoRect, space, this.dom);
    }
    placeInfo(pos) {
        if (this.info) {
            if (pos) {
                if (pos.style)
                    this.info.style.cssText = pos.style;
                this.info.className = "cm-tooltip cm-completionInfo " + (pos.class || "");
            }
            else {
                this.info.style.cssText = "top: -1e6px";
            }
        }
    }
    createListBox(options, id, range) {
        const ul = document.createElement("ul");
        ul.id = id;
        ul.setAttribute("role", "listbox");
        ul.setAttribute("aria-expanded", "true");
        ul.setAttribute("aria-label", this.view.state.phrase("Completions"));
        ul.addEventListener("mousedown", e => {
            // Prevent focus change when clicking the scrollbar
            if (e.target == ul)
                e.preventDefault();
        });
        let curSection = null;
        for (let i = range.from; i < range.to; i++) {
            let { completion, match } = options[i], { section } = completion;
            if (section) {
                let name = typeof section == "string" ? section : section.name;
                if (name != curSection && (i > range.from || range.from == 0)) {
                    curSection = name;
                    if (typeof section != "string" && section.header) {
                        ul.appendChild(section.header(section));
                    }
                    else {
                        let header = ul.appendChild(document.createElement("completion-section"));
                        header.textContent = name;
                    }
                }
            }
            const li = ul.appendChild(document.createElement("li"));
            li.id = id + "-" + i;
            li.setAttribute("role", "option");
            let cls = this.optionClass(completion);
            if (cls)
                li.className = cls;
            for (let source of this.optionContent) {
                let node = source(completion, this.view.state, this.view, match);
                if (node)
                    li.appendChild(node);
            }
        }
        if (range.from)
            ul.classList.add("cm-completionListIncompleteTop");
        if (range.to < options.length)
            ul.classList.add("cm-completionListIncompleteBottom");
        return ul;
    }
    destroyInfo() {
        if (this.info) {
            if (this.infoDestroy)
                this.infoDestroy();
            this.info.remove();
            this.info = null;
        }
    }
    destroy() {
        this.destroyInfo();
    }
}
function completionTooltip(stateField, applyCompletion) {
    return (view) => new CompletionTooltip(view, stateField, applyCompletion);
}
function dist_scrollIntoView(container, element) {
    let parent = container.getBoundingClientRect();
    let self = element.getBoundingClientRect();
    let scaleY = parent.height / container.offsetHeight;
    if (self.top < parent.top)
        container.scrollTop -= (parent.top - self.top) / scaleY;
    else if (self.bottom > parent.bottom)
        container.scrollTop += (self.bottom - parent.bottom) / scaleY;
}

// Used to pick a preferred option when two options with the same
// label occur in the result.
function score(option) {
    return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) +
        (option.type ? 1 : 0);
}
function sortOptions(active, state) {
    let options = [];
    let sections = null, dynamicSectionScore = null;
    let addOption = (option) => {
        options.push(option);
        let { section } = option.completion;
        if (section) {
            if (!sections)
                sections = [];
            let name = typeof section == "string" ? section : section.name;
            if (!sections.some(s => s.name == name))
                sections.push(typeof section == "string" ? { name } : section);
        }
    };
    let conf = state.facet(completionConfig);
    for (let a of active)
        if (a.hasResult()) {
            let getMatch = a.result.getMatch;
            if (a.result.filter === false) {
                for (let option of a.result.options) {
                    addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options.length));
                }
            }
            else {
                let pattern = state.sliceDoc(a.from, a.to), match;
                let matcher = conf.filterStrict ? new StrictMatcher(pattern) : new FuzzyMatcher(pattern);
                for (let option of a.result.options)
                    if (match = matcher.match(option.label)) {
                        let matched = !option.displayLabel ? match.matched : getMatch ? getMatch(option, match.matched) : [];
                        let score = match.score + (option.boost || 0);
                        addOption(new Option(option, a.source, matched, score));
                        if (typeof option.section == "object" && option.section.rank === "dynamic") {
                            let { name } = option.section;
                            if (!dynamicSectionScore)
                                dynamicSectionScore = Object.create(null);
                            dynamicSectionScore[name] = Math.max(score, dynamicSectionScore[name] || -1e9);
                        }
                    }
            }
        }
    if (sections) {
        let sectionOrder = Object.create(null), pos = 0;
        let cmp = (a, b) => {
            return (a.rank === "dynamic" && b.rank === "dynamic" ? dynamicSectionScore[b.name] - dynamicSectionScore[a.name] : 0) ||
                (typeof a.rank == "number" ? a.rank : 1e9) - (typeof b.rank == "number" ? b.rank : 1e9) ||
                (a.name < b.name ? -1 : 1);
        };
        for (let s of sections.sort(cmp)) {
            pos -= 1e5;
            sectionOrder[s.name] = pos;
        }
        for (let option of options) {
            let { section } = option.completion;
            if (section)
                option.score += sectionOrder[typeof section == "string" ? section : section.name];
        }
    }
    let result = [], prev = null;
    let compare = conf.compareCompletions;
    for (let opt of options.sort((a, b) => (b.score - a.score) || compare(a.completion, b.completion))) {
        let cur = opt.completion;
        if (!prev || prev.label != cur.label || prev.detail != cur.detail ||
            (prev.type != null && cur.type != null && prev.type != cur.type) ||
            prev.apply != cur.apply || prev.boost != cur.boost)
            result.push(opt);
        else if (score(opt.completion) > score(prev))
            result[result.length - 1] = opt;
        prev = opt.completion;
    }
    return result;
}
class CompletionDialog {
    constructor(options, attrs, tooltip, timestamp, selected, disabled) {
        this.options = options;
        this.attrs = attrs;
        this.tooltip = tooltip;
        this.timestamp = timestamp;
        this.selected = selected;
        this.disabled = disabled;
    }
    setSelected(selected, id) {
        return selected == this.selected || selected >= this.options.length ? this
            : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected, this.disabled);
    }
    static build(active, state, id, prev, conf, didSetActive) {
        if (prev && !didSetActive && active.some(s => s.isPending))
            return prev.setDisabled();
        let options = sortOptions(active, state);
        if (!options.length)
            return prev && active.some(a => a.isPending) ? prev.setDisabled() : null;
        let selected = state.facet(completionConfig).selectOnOpen ? 0 : -1;
        if (prev && prev.selected != selected && prev.selected != -1) {
            let selectedValue = prev.options[prev.selected].completion;
            for (let i = 0; i < options.length; i++)
                if (options[i].completion == selectedValue) {
                    selected = i;
                    break;
                }
        }
        return new CompletionDialog(options, makeAttrs(id, selected), {
            pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),
            create: createTooltip,
            above: conf.aboveCursor,
        }, prev ? prev.timestamp : Date.now(), selected, false);
    }
    map(changes) {
        return new CompletionDialog(this.options, this.attrs, { ...this.tooltip, pos: changes.mapPos(this.tooltip.pos) }, this.timestamp, this.selected, this.disabled);
    }
    setDisabled() {
        return new CompletionDialog(this.options, this.attrs, this.tooltip, this.timestamp, this.selected, true);
    }
}
class CompletionState {
    constructor(active, id, open) {
        this.active = active;
        this.id = id;
        this.open = open;
    }
    static start() {
        return new CompletionState(dist_none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
    }
    update(tr) {
        let { state } = tr, conf = state.facet(completionConfig);
        let sources = conf.override ||
            state.languageDataAt("autocomplete", cur(state)).map(asSource);
        let active = sources.map(source => {
            let value = this.active.find(s => s.source == source) ||
                new ActiveSource(source, this.active.some(a => a.state != 0 /* State.Inactive */) ? 1 /* State.Pending */ : 0 /* State.Inactive */);
            return value.update(tr, conf);
        });
        if (active.length == this.active.length && active.every((a, i) => a == this.active[i]))
            active = this.active;
        let open = this.open, didSet = tr.effects.some(e => e.is(setActiveEffect));
        if (open && tr.docChanged)
            open = open.map(tr.changes);
        if (tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) ||
            !sameResults(active, this.active) || didSet)
            open = CompletionDialog.build(active, state, this.id, open, conf, didSet);
        else if (open && open.disabled && !active.some(a => a.isPending))
            open = null;
        if (!open && active.every(a => !a.isPending) && active.some(a => a.hasResult()))
            active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* State.Inactive */) : a);
        for (let effect of tr.effects)
            if (effect.is(setSelectedEffect))
                open = open && open.setSelected(effect.value, this.id);
        return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open);
    }
    get tooltip() { return this.open ? this.open.tooltip : null; }
    get attrs() { return this.open ? this.open.attrs : this.active.length ? baseAttrs : dist_noAttrs; }
}
function sameResults(a, b) {
    if (a == b)
        return true;
    for (let iA = 0, iB = 0;;) {
        while (iA < a.length && !a[iA].hasResult())
            iA++;
        while (iB < b.length && !b[iB].hasResult())
            iB++;
        let endA = iA == a.length, endB = iB == b.length;
        if (endA || endB)
            return endA == endB;
        if (a[iA++].result != b[iB++].result)
            return false;
    }
}
const baseAttrs = {
    "aria-autocomplete": "list"
};
const dist_noAttrs = {};
function makeAttrs(id, selected) {
    let result = {
        "aria-autocomplete": "list",
        "aria-haspopup": "listbox",
        "aria-controls": id
    };
    if (selected > -1)
        result["aria-activedescendant"] = id + "-" + selected;
    return result;
}
const dist_none = [];
function getUpdateType(tr, conf) {
    if (tr.isUserEvent("input.complete")) {
        let completion = tr.annotation(pickedCompletion);
        if (completion && conf.activateOnCompletion(completion))
            return 4 /* UpdateType.Activate */ | 8 /* UpdateType.Reset */;
    }
    let typing = tr.isUserEvent("input.type");
    return typing && conf.activateOnTyping ? 4 /* UpdateType.Activate */ | 1 /* UpdateType.Typing */
        : typing ? 1 /* UpdateType.Typing */
            : tr.isUserEvent("delete.backward") ? 2 /* UpdateType.Backspacing */
                : tr.selection ? 8 /* UpdateType.Reset */
                    : tr.docChanged ? 16 /* UpdateType.ResetIfTouching */ : 0 /* UpdateType.None */;
}
class ActiveSource {
    constructor(source, state, explicit = false) {
        this.source = source;
        this.state = state;
        this.explicit = explicit;
    }
    hasResult() { return false; }
    get isPending() { return this.state == 1 /* State.Pending */; }
    update(tr, conf) {
        let type = getUpdateType(tr, conf), value = this;
        if ((type & 8 /* UpdateType.Reset */) || (type & 16 /* UpdateType.ResetIfTouching */) && this.touches(tr))
            value = new ActiveSource(value.source, 0 /* State.Inactive */);
        if ((type & 4 /* UpdateType.Activate */) && value.state == 0 /* State.Inactive */)
            value = new ActiveSource(this.source, 1 /* State.Pending */);
        value = value.updateFor(tr, type);
        for (let effect of tr.effects) {
            if (effect.is(startCompletionEffect))
                value = new ActiveSource(value.source, 1 /* State.Pending */, effect.value);
            else if (effect.is(closeCompletionEffect))
                value = new ActiveSource(value.source, 0 /* State.Inactive */);
            else if (effect.is(setActiveEffect))
                for (let active of effect.value)
                    if (active.source == value.source)
                        value = active;
        }
        return value;
    }
    updateFor(tr, type) { return this.map(tr.changes); }
    map(changes) { return this; }
    touches(tr) {
        return tr.changes.touchesRange(cur(tr.state));
    }
}
class ActiveResult extends ActiveSource {
    constructor(source, explicit, limit, result, from, to) {
        super(source, 3 /* State.Result */, explicit);
        this.limit = limit;
        this.result = result;
        this.from = from;
        this.to = to;
    }
    hasResult() { return true; }
    updateFor(tr, type) {
        var _a;
        if (!(type & 3 /* UpdateType.SimpleInteraction */))
            return this.map(tr.changes);
        let result = this.result;
        if (result.map && !tr.changes.empty)
            result = result.map(result, tr.changes);
        let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1);
        let pos = cur(tr.state);
        if (pos > to || !result ||
            (type & 2 /* UpdateType.Backspacing */) && (cur(tr.startState) == this.from || pos < this.limit))
            return new ActiveSource(this.source, type & 4 /* UpdateType.Activate */ ? 1 /* State.Pending */ : 0 /* State.Inactive */);
        let limit = tr.changes.mapPos(this.limit);
        if (checkValid(result.validFor, tr.state, from, to))
            return new ActiveResult(this.source, this.explicit, limit, result, from, to);
        if (result.update &&
            (result = result.update(result, from, to, new CompletionContext(tr.state, pos, false))))
            return new ActiveResult(this.source, this.explicit, limit, result, result.from, (_a = result.to) !== null && _a !== void 0 ? _a : cur(tr.state));
        return new ActiveSource(this.source, 1 /* State.Pending */, this.explicit);
    }
    map(mapping) {
        if (mapping.empty)
            return this;
        let result = this.result.map ? this.result.map(this.result, mapping) : this.result;
        if (!result)
            return new ActiveSource(this.source, 0 /* State.Inactive */);
        return new ActiveResult(this.source, this.explicit, mapping.mapPos(this.limit), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1));
    }
    touches(tr) {
        return tr.changes.touchesRange(this.from, this.to);
    }
}
function checkValid(validFor, state, from, to) {
    if (!validFor)
        return false;
    let text = state.sliceDoc(from, to);
    return typeof validFor == "function" ? validFor(text, from, to, state) : ensureAnchor(validFor, true).test(text);
}
const setActiveEffect = /*@__PURE__*/dist_StateEffect.define({
    map(sources, mapping) { return sources.map(s => s.map(mapping)); }
});
const setSelectedEffect = /*@__PURE__*/dist_StateEffect.define();
const completionState = /*@__PURE__*/dist_StateField.define({
    create() { return CompletionState.start(); },
    update(value, tr) { return value.update(tr); },
    provide: f => [
        showTooltip.from(f, val => val.tooltip),
        dist_EditorView.contentAttributes.from(f, state => state.attrs)
    ]
});
function applyCompletion(view, option) {
    const apply = option.completion.apply || option.completion.label;
    let result = view.state.field(completionState).active.find(a => a.source == option.source);
    if (!(result instanceof ActiveResult))
        return false;
    if (typeof apply == "string")
        view.dispatch({
            ...insertCompletionText(view.state, apply, result.from, result.to),
            annotations: pickedCompletion.of(option.completion)
        });
    else
        apply(view, option.completion, result.from, result.to);
    return true;
}
const createTooltip = /*@__PURE__*/completionTooltip(completionState, applyCompletion);

/**
Returns a command that moves the completion selection forward or
backward by the given amount.
*/
function moveCompletionSelection(forward, by = "option") {
    return (view) => {
        let cState = view.state.field(completionState, false);
        if (!cState || !cState.open || cState.open.disabled ||
            Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
            return false;
        let step = 1, tooltip;
        if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip)))
            step = Math.max(2, Math.floor(tooltip.dom.offsetHeight /
                tooltip.dom.querySelector("li").offsetHeight) - 1);
        let { length } = cState.open.options;
        let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1;
        if (selected < 0)
            selected = by == "page" ? 0 : length - 1;
        else if (selected >= length)
            selected = by == "page" ? length - 1 : 0;
        view.dispatch({ effects: setSelectedEffect.of(selected) });
        return true;
    };
}
/**
Accept the current completion.
*/
const acceptCompletion = (view) => {
    let cState = view.state.field(completionState, false);
    if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || cState.open.disabled ||
        Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
        return false;
    return applyCompletion(view, cState.open.options[cState.open.selected]);
};
/**
Explicitly start autocompletion.
*/
const startCompletion = (view) => {
    let cState = view.state.field(completionState, false);
    if (!cState)
        return false;
    view.dispatch({ effects: startCompletionEffect.of(true) });
    return true;
};
/**
Close the currently active completion.
*/
const closeCompletion = (view) => {
    let cState = view.state.field(completionState, false);
    if (!cState || !cState.active.some(a => a.state != 0 /* State.Inactive */))
        return false;
    view.dispatch({ effects: closeCompletionEffect.of(null) });
    return true;
};
class RunningQuery {
    constructor(active, context) {
        this.active = active;
        this.context = context;
        this.time = Date.now();
        this.updates = [];
        // Note that 'undefined' means 'not done yet', whereas 'null' means
        // 'query returned null'.
        this.done = undefined;
    }
}
const MaxUpdateCount = 50, MinAbortTime = 1000;
const completionPlugin = /*@__PURE__*/dist_ViewPlugin.fromClass(class {
    constructor(view) {
        this.view = view;
        this.debounceUpdate = -1;
        this.running = [];
        this.debounceAccept = -1;
        this.pendingStart = false;
        this.composing = 0 /* CompositionState.None */;
        for (let active of view.state.field(completionState).active)
            if (active.isPending)
                this.startQuery(active);
    }
    update(update) {
        let cState = update.state.field(completionState);
        let conf = update.state.facet(completionConfig);
        if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState)
            return;
        let doesReset = update.transactions.some(tr => {
            let type = getUpdateType(tr, conf);
            return (type & 8 /* UpdateType.Reset */) || (tr.selection || tr.docChanged) && !(type & 3 /* UpdateType.SimpleInteraction */);
        });
        for (let i = 0; i < this.running.length; i++) {
            let query = this.running[i];
            if (doesReset ||
                query.context.abortOnDocChange && update.docChanged ||
                query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) {
                for (let handler of query.context.abortListeners) {
                    try {
                        handler();
                    }
                    catch (e) {
                        logException(this.view.state, e);
                    }
                }
                query.context.abortListeners = null;
                this.running.splice(i--, 1);
            }
            else {
                query.updates.push(...update.transactions);
            }
        }
        if (this.debounceUpdate > -1)
            clearTimeout(this.debounceUpdate);
        if (update.transactions.some(tr => tr.effects.some(e => e.is(startCompletionEffect))))
            this.pendingStart = true;
        let delay = this.pendingStart ? 50 : conf.activateOnTypingDelay;
        this.debounceUpdate = cState.active.some(a => a.isPending && !this.running.some(q => q.active.source == a.source))
            ? setTimeout(() => this.startUpdate(), delay) : -1;
        if (this.composing != 0 /* CompositionState.None */)
            for (let tr of update.transactions) {
                if (tr.isUserEvent("input.type"))
                    this.composing = 2 /* CompositionState.Changed */;
                else if (this.composing == 2 /* CompositionState.Changed */ && tr.selection)
                    this.composing = 3 /* CompositionState.ChangedAndMoved */;
            }
    }
    startUpdate() {
        this.debounceUpdate = -1;
        this.pendingStart = false;
        let { state } = this.view, cState = state.field(completionState);
        for (let active of cState.active) {
            if (active.isPending && !this.running.some(r => r.active.source == active.source))
                this.startQuery(active);
        }
        if (this.running.length && cState.open && cState.open.disabled)
            this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
    }
    startQuery(active) {
        let { state } = this.view, pos = cur(state);
        let context = new CompletionContext(state, pos, active.explicit, this.view);
        let pending = new RunningQuery(active, context);
        this.running.push(pending);
        Promise.resolve(active.source(context)).then(result => {
            if (!pending.context.aborted) {
                pending.done = result || null;
                this.scheduleAccept();
            }
        }, err => {
            this.view.dispatch({ effects: closeCompletionEffect.of(null) });
            logException(this.view.state, err);
        });
    }
    scheduleAccept() {
        if (this.running.every(q => q.done !== undefined))
            this.accept();
        else if (this.debounceAccept < 0)
            this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
    }
    // For each finished query in this.running, try to create a result
    // or, if appropriate, restart the query.
    accept() {
        var _a;
        if (this.debounceAccept > -1)
            clearTimeout(this.debounceAccept);
        this.debounceAccept = -1;
        let updated = [];
        let conf = this.view.state.facet(completionConfig), cState = this.view.state.field(completionState);
        for (let i = 0; i < this.running.length; i++) {
            let query = this.running[i];
            if (query.done === undefined)
                continue;
            this.running.splice(i--, 1);
            if (query.done) {
                let pos = cur(query.updates.length ? query.updates[0].startState : this.view.state);
                let limit = Math.min(pos, query.done.from + (query.active.explicit ? 0 : 1));
                let active = new ActiveResult(query.active.source, query.active.explicit, limit, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : pos);
                // Replay the transactions that happened since the start of
                // the request and see if that preserves the result
                for (let tr of query.updates)
                    active = active.update(tr, conf);
                if (active.hasResult()) {
                    updated.push(active);
                    continue;
                }
            }
            let current = cState.active.find(a => a.source == query.active.source);
            if (current && current.isPending) {
                if (query.done == null) {
                    // Explicitly failed. Should clear the pending status if it
                    // hasn't been re-set in the meantime.
                    let active = new ActiveSource(query.active.source, 0 /* State.Inactive */);
                    for (let tr of query.updates)
                        active = active.update(tr, conf);
                    if (!active.isPending)
                        updated.push(active);
                }
                else {
                    // Cleared by subsequent transactions. Restart.
                    this.startQuery(current);
                }
            }
        }
        if (updated.length || cState.open && cState.open.disabled)
            this.view.dispatch({ effects: setActiveEffect.of(updated) });
    }
}, {
    eventHandlers: {
        blur(event) {
            let state = this.view.state.field(completionState, false);
            if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) {
                let dialog = state.open && getTooltip(this.view, state.open.tooltip);
                if (!dialog || !dialog.dom.contains(event.relatedTarget))
                    setTimeout(() => this.view.dispatch({ effects: closeCompletionEffect.of(null) }), 10);
            }
        },
        compositionstart() {
            this.composing = 1 /* CompositionState.Started */;
        },
        compositionend() {
            if (this.composing == 3 /* CompositionState.ChangedAndMoved */) {
                // Safari fires compositionend events synchronously, possibly
                // from inside an update, so dispatch asynchronously to avoid reentrancy
                setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20);
            }
            this.composing = 0 /* CompositionState.None */;
        }
    }
});
const windows = typeof navigator == "object" && /*@__PURE__*//Win/.test(navigator.platform);
const commitCharacters = /*@__PURE__*/Prec.highest(/*@__PURE__*/dist_EditorView.domEventHandlers({
    keydown(event, view) {
        let field = view.state.field(completionState, false);
        if (!field || !field.open || field.open.disabled || field.open.selected < 0 ||
            event.key.length > 1 || event.ctrlKey && !(windows && event.altKey) || event.metaKey)
            return false;
        let option = field.open.options[field.open.selected];
        let result = field.active.find(a => a.source == option.source);
        let commitChars = option.completion.commitCharacters || result.result.commitCharacters;
        if (commitChars && commitChars.indexOf(event.key) > -1)
            applyCompletion(view, option);
        return false;
    }
}));

const autocomplete_dist_baseTheme = /*@__PURE__*/dist_EditorView.baseTheme({
    ".cm-tooltip.cm-tooltip-autocomplete": {
        "& > ul": {
            fontFamily: "monospace",
            whiteSpace: "nowrap",
            overflow: "hidden auto",
            maxWidth_fallback: "700px",
            maxWidth: "min(700px, 95vw)",
            minWidth: "250px",
            maxHeight: "10em",
            height: "100%",
            listStyle: "none",
            margin: 0,
            padding: 0,
            "& > li, & > completion-section": {
                padding: "1px 3px",
                lineHeight: 1.2
            },
            "& > li": {
                overflowX: "hidden",
                textOverflow: "ellipsis",
                cursor: "pointer"
            },
            "& > completion-section": {
                display: "list-item",
                borderBottom: "1px solid silver",
                paddingLeft: "0.5em",
                opacity: 0.7
            }
        }
    },
    "&light .cm-tooltip-autocomplete ul li[aria-selected]": {
        background: "#17c",
        color: "white",
    },
    "&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
        background: "#777",
    },
    "&dark .cm-tooltip-autocomplete ul li[aria-selected]": {
        background: "#347",
        color: "white",
    },
    "&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
        background: "#444",
    },
    ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": {
        content: '"···"',
        opacity: 0.5,
        display: "block",
        textAlign: "center"
    },
    ".cm-tooltip.cm-completionInfo": {
        position: "absolute",
        padding: "3px 9px",
        width: "max-content",
        maxWidth: `${400 /* Info.Width */}px`,
        boxSizing: "border-box",
        whiteSpace: "pre-line"
    },
    ".cm-completionInfo.cm-completionInfo-left": { right: "100%" },
    ".cm-completionInfo.cm-completionInfo-right": { left: "100%" },
    ".cm-completionInfo.cm-completionInfo-left-narrow": { right: `${30 /* Info.Margin */}px` },
    ".cm-completionInfo.cm-completionInfo-right-narrow": { left: `${30 /* Info.Margin */}px` },
    "&light .cm-snippetField": { backgroundColor: "#00000022" },
    "&dark .cm-snippetField": { backgroundColor: "#ffffff22" },
    ".cm-snippetFieldPosition": {
        verticalAlign: "text-top",
        width: 0,
        height: "1.15em",
        display: "inline-block",
        margin: "0 -0.7px -.7em",
        borderLeft: "1.4px dotted #888"
    },
    ".cm-completionMatchedText": {
        textDecoration: "underline"
    },
    ".cm-completionDetail": {
        marginLeft: "0.5em",
        fontStyle: "italic"
    },
    ".cm-completionIcon": {
        fontSize: "90%",
        width: ".8em",
        display: "inline-block",
        textAlign: "center",
        paddingRight: ".6em",
        opacity: "0.6",
        boxSizing: "content-box"
    },
    ".cm-completionIcon-function, .cm-completionIcon-method": {
        "&:after": { content: "'ƒ'" }
    },
    ".cm-completionIcon-class": {
        "&:after": { content: "'○'" }
    },
    ".cm-completionIcon-interface": {
        "&:after": { content: "'◌'" }
    },
    ".cm-completionIcon-variable": {
        "&:after": { content: "'𝑥'" }
    },
    ".cm-completionIcon-constant": {
        "&:after": { content: "'𝐶'" }
    },
    ".cm-completionIcon-type": {
        "&:after": { content: "'𝑡'" }
    },
    ".cm-completionIcon-enum": {
        "&:after": { content: "'∪'" }
    },
    ".cm-completionIcon-property": {
        "&:after": { content: "'□'" }
    },
    ".cm-completionIcon-keyword": {
        "&:after": { content: "'🔑\uFE0E'" } // Disable emoji rendering
    },
    ".cm-completionIcon-namespace": {
        "&:after": { content: "'▢'" }
    },
    ".cm-completionIcon-text": {
        "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" }
    }
});

class FieldPos {
    constructor(field, line, from, to) {
        this.field = field;
        this.line = line;
        this.from = from;
        this.to = to;
    }
}
class FieldRange {
    constructor(field, from, to) {
        this.field = field;
        this.from = from;
        this.to = to;
    }
    map(changes) {
        let from = changes.mapPos(this.from, -1, dist_MapMode.TrackDel);
        let to = changes.mapPos(this.to, 1, dist_MapMode.TrackDel);
        return from == null || to == null ? null : new FieldRange(this.field, from, to);
    }
}
class Snippet {
    constructor(lines, fieldPositions) {
        this.lines = lines;
        this.fieldPositions = fieldPositions;
    }
    instantiate(state, pos) {
        let text = [], lineStart = [pos];
        let lineObj = state.doc.lineAt(pos), baseIndent = /^\s*/.exec(lineObj.text)[0];
        for (let line of this.lines) {
            if (text.length) {
                let indent = baseIndent, tabs = /^\t*/.exec(line)[0].length;
                for (let i = 0; i < tabs; i++)
                    indent += state.facet(indentUnit);
                lineStart.push(pos + indent.length - tabs);
                line = indent + line.slice(tabs);
            }
            text.push(line);
            pos += line.length + 1;
        }
        let ranges = this.fieldPositions.map(pos => new FieldRange(pos.field, lineStart[pos.line] + pos.from, lineStart[pos.line] + pos.to));
        return { text, ranges };
    }
    static parse(template) {
        let fields = [];
        let lines = [], positions = [], m;
        for (let line of template.split(/\r\n?|\n/)) {
            while (m = /[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(line)) {
                let seq = m[1] ? +m[1] : null, rawName = m[2] || m[3] || "", found = -1;
                let name = rawName.replace(/\\[{}]/g, m => m[1]);
                for (let i = 0; i < fields.length; i++) {
                    if (seq != null ? fields[i].seq == seq : name ? fields[i].name == name : false)
                        found = i;
                }
                if (found < 0) {
                    let i = 0;
                    while (i < fields.length && (seq == null || (fields[i].seq != null && fields[i].seq < seq)))
                        i++;
                    fields.splice(i, 0, { seq, name });
                    found = i;
                    for (let pos of positions)
                        if (pos.field >= found)
                            pos.field++;
                }
                for (let pos of positions)
                    if (pos.line == lines.length && pos.from > m.index) {
                        let snip = m[2] ? 3 + (m[1] || "").length : 2;
                        pos.from -= snip;
                        pos.to -= snip;
                    }
                positions.push(new FieldPos(found, lines.length, m.index, m.index + name.length));
                line = line.slice(0, m.index) + rawName + line.slice(m.index + m[0].length);
            }
            line = line.replace(/\\([{}])/g, (_, brace, index) => {
                for (let pos of positions)
                    if (pos.line == lines.length && pos.from > index) {
                        pos.from--;
                        pos.to--;
                    }
                return brace;
            });
            lines.push(line);
        }
        return new Snippet(lines, positions);
    }
}
let fieldMarker = /*@__PURE__*/dist_Decoration.widget({ widget: /*@__PURE__*/new class extends WidgetType {
        toDOM() {
            let span = document.createElement("span");
            span.className = "cm-snippetFieldPosition";
            return span;
        }
        ignoreEvent() { return false; }
    } });
let fieldRange = /*@__PURE__*/dist_Decoration.mark({ class: "cm-snippetField" });
class ActiveSnippet {
    constructor(ranges, active) {
        this.ranges = ranges;
        this.active = active;
        this.deco = dist_Decoration.set(ranges.map(r => (r.from == r.to ? fieldMarker : fieldRange).range(r.from, r.to)), true);
    }
    map(changes) {
        let ranges = [];
        for (let r of this.ranges) {
            let mapped = r.map(changes);
            if (!mapped)
                return null;
            ranges.push(mapped);
        }
        return new ActiveSnippet(ranges, this.active);
    }
    selectionInsideField(sel) {
        return sel.ranges.every(range => this.ranges.some(r => r.field == this.active && r.from <= range.from && r.to >= range.to));
    }
}
const setActive = /*@__PURE__*/dist_StateEffect.define({
    map(value, changes) { return value && value.map(changes); }
});
const moveToField = /*@__PURE__*/dist_StateEffect.define();
const snippetState = /*@__PURE__*/dist_StateField.define({
    create() { return null; },
    update(value, tr) {
        for (let effect of tr.effects) {
            if (effect.is(setActive))
                return effect.value;
            if (effect.is(moveToField) && value)
                return new ActiveSnippet(value.ranges, effect.value);
        }
        if (value && tr.docChanged)
            value = value.map(tr.changes);
        if (value && tr.selection && !value.selectionInsideField(tr.selection))
            value = null;
        return value;
    },
    provide: f => dist_EditorView.decorations.from(f, val => val ? val.deco : dist_Decoration.none)
});
function fieldSelection(ranges, field) {
    return dist_EditorSelection.create(ranges.filter(r => r.field == field).map(r => dist_EditorSelection.range(r.from, r.to)));
}
/**
Convert a snippet template to a function that can
[apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written
using syntax like this:

    "for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"

Each `${}` placeholder (you may also use `#{}`) indicates a field
that the user can fill in. Its name, if any, will be the default
content for the field.

When the snippet is activated by calling the returned function,
the code is inserted at the given position. Newlines in the
template are indented by the indentation of the start line, plus
one [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after
the newline.

On activation, (all instances of) the first field are selected.
The user can move between fields with Tab and Shift-Tab as long as
the fields are active. Moving to the last field or moving the
cursor out of the current field deactivates the fields.

The order of fields defaults to textual order, but you can add
numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
a custom order.

To include a literal `{` or `}` in your template, put a backslash
in front of it. This will be removed and the brace will not be
interpreted as indicating a placeholder.
*/
function snippet(template) {
    let snippet = Snippet.parse(template);
    return (editor, completion, from, to) => {
        let { text, ranges } = snippet.instantiate(editor.state, from);
        let { main } = editor.state.selection;
        let spec = {
            changes: { from, to: to == main.from ? main.to : to, insert: dist_Text.of(text) },
            scrollIntoView: true,
            annotations: completion ? [pickedCompletion.of(completion), Transaction.userEvent.of("input.complete")] : undefined
        };
        if (ranges.length)
            spec.selection = fieldSelection(ranges, 0);
        if (ranges.some(r => r.field > 0)) {
            let active = new ActiveSnippet(ranges, 0);
            let effects = spec.effects = [setActive.of(active)];
            if (editor.state.field(snippetState, false) === undefined)
                effects.push(dist_StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, autocomplete_dist_baseTheme]));
        }
        editor.dispatch(editor.state.update(spec));
    };
}
function moveField(dir) {
    return ({ state, dispatch }) => {
        let active = state.field(snippetState, false);
        if (!active || dir < 0 && active.active == 0)
            return false;
        let next = active.active + dir, last = dir > 0 && !active.ranges.some(r => r.field == next + dir);
        dispatch(state.update({
            selection: fieldSelection(active.ranges, next),
            effects: setActive.of(last ? null : new ActiveSnippet(active.ranges, next)),
            scrollIntoView: true
        }));
        return true;
    };
}
/**
A command that clears the active snippet, if any.
*/
const clearSnippet = ({ state, dispatch }) => {
    let active = state.field(snippetState, false);
    if (!active)
        return false;
    dispatch(state.update({ effects: setActive.of(null) }));
    return true;
};
/**
Move to the next snippet field, if available.
*/
const nextSnippetField = /*@__PURE__*/moveField(1);
/**
Move to the previous snippet field, if available.
*/
const prevSnippetField = /*@__PURE__*/moveField(-1);
/**
Check if there is an active snippet with a next field for
`nextSnippetField` to move to.
*/
function hasNextSnippetField(state) {
    let active = state.field(snippetState, false);
    return !!(active && active.ranges.some(r => r.field == active.active + 1));
}
/**
Returns true if there is an active snippet and a previous field
for `prevSnippetField` to move to.
*/
function hasPrevSnippetField(state) {
    let active = state.field(snippetState, false);
    return !!(active && active.active > 0);
}
const defaultSnippetKeymap = [
    { key: "Tab", run: nextSnippetField, shift: prevSnippetField },
    { key: "Escape", run: clearSnippet }
];
/**
A facet that can be used to configure the key bindings used by
snippets. The default binds Tab to
[`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to
[`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape
to [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).
*/
const snippetKeymap = /*@__PURE__*/Facet.define({
    combine(maps) { return maps.length ? maps[0] : defaultSnippetKeymap; }
});
const addSnippetKeymap = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.compute([snippetKeymap], state => state.facet(snippetKeymap)));
/**
Create a completion from a snippet. Returns an object with the
properties from `completion`, plus an `apply` function that
applies the snippet.
*/
function snippetCompletion(template, completion) {
    return { ...completion, apply: snippet(template) };
}
const snippetPointerHandler = /*@__PURE__*/dist_EditorView.domEventHandlers({
    mousedown(event, view) {
        let active = view.state.field(snippetState, false), pos;
        if (!active || (pos = view.posAtCoords({ x: event.clientX, y: event.clientY })) == null)
            return false;
        let match = active.ranges.find(r => r.from <= pos && r.to >= pos);
        if (!match || match.field == active.active)
            return false;
        view.dispatch({
            selection: fieldSelection(active.ranges, match.field),
            effects: setActive.of(active.ranges.some(r => r.field > match.field)
                ? new ActiveSnippet(active.ranges, match.field) : null),
            scrollIntoView: true
        });
        return true;
    }
});

function wordRE(wordChars) {
    let escaped = wordChars.replace(/[\]\-\\]/g, "\\$&");
    try {
        return new RegExp(`[\\p{Alphabetic}\\p{Number}_${escaped}]+`, "ug");
    }
    catch (_a) {
        return new RegExp(`[\w${escaped}]`, "g");
    }
}
function mapRE(re, f) {
    return new RegExp(f(re.source), re.unicode ? "u" : "");
}
const wordCaches = /*@__PURE__*/(/* unused pure expression or super */ null && (Object.create(null)));
function wordCache(wordChars) {
    return wordCaches[wordChars] || (wordCaches[wordChars] = new WeakMap);
}
function storeWords(doc, wordRE, result, seen, ignoreAt) {
    for (let lines = doc.iterLines(), pos = 0; !lines.next().done;) {
        let { value } = lines, m;
        wordRE.lastIndex = 0;
        while (m = wordRE.exec(value)) {
            if (!seen[m[0]] && pos + m.index != ignoreAt) {
                result.push({ type: "text", label: m[0] });
                seen[m[0]] = true;
                if (result.length >= 2000 /* C.MaxList */)
                    return;
            }
        }
        pos += value.length + 1;
    }
}
function collectWords(doc, cache, wordRE, to, ignoreAt) {
    let big = doc.length >= 1000 /* C.MinCacheLen */;
    let cached = big && cache.get(doc);
    if (cached)
        return cached;
    let result = [], seen = Object.create(null);
    if (doc.children) {
        let pos = 0;
        for (let ch of doc.children) {
            if (ch.length >= 1000 /* C.MinCacheLen */) {
                for (let c of collectWords(ch, cache, wordRE, to - pos, ignoreAt - pos)) {
                    if (!seen[c.label]) {
                        seen[c.label] = true;
                        result.push(c);
                    }
                }
            }
            else {
                storeWords(ch, wordRE, result, seen, ignoreAt - pos);
            }
            pos += ch.length + 1;
        }
    }
    else {
        storeWords(doc, wordRE, result, seen, ignoreAt);
    }
    if (big && result.length < 2000 /* C.MaxList */)
        cache.set(doc, result);
    return result;
}
/**
A completion source that will scan the document for words (using a
[character categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer)), and
return those as completions.
*/
const completeAnyWord = context => {
    let wordChars = context.state.languageDataAt("wordChars", context.pos).join("");
    let re = wordRE(wordChars);
    let token = context.matchBefore(mapRE(re, s => s + "$"));
    if (!token && !context.explicit)
        return null;
    let from = token ? token.from : context.pos;
    let options = collectWords(context.state.doc, wordCache(wordChars), re, 50000 /* C.Range */, from);
    return { from, options, validFor: mapRE(re, s => "^" + s) };
};

const dist_defaults = {
    brackets: ["(", "[", "{", "'", '"'],
    before: ")]}:;>",
    stringPrefixes: []
};
const closeBracketEffect = /*@__PURE__*/dist_StateEffect.define({
    map(value, mapping) {
        let mapped = mapping.mapPos(value, -1, dist_MapMode.TrackAfter);
        return mapped == null ? undefined : mapped;
    }
});
const closedBracket = /*@__PURE__*/new class extends RangeValue {
};
closedBracket.startSide = 1;
closedBracket.endSide = -1;
const bracketState = /*@__PURE__*/dist_StateField.define({
    create() { return dist_RangeSet.empty; },
    update(value, tr) {
        value = value.map(tr.changes);
        if (tr.selection) {
            let line = tr.state.doc.lineAt(tr.selection.main.head);
            value = value.update({ filter: from => from >= line.from && from <= line.to });
        }
        for (let effect of tr.effects)
            if (effect.is(closeBracketEffect))
                value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] });
        return value;
    }
});
/**
Extension to enable bracket-closing behavior. When a closeable
bracket is typed, its closing bracket is immediately inserted
after the cursor. When closing a bracket directly in front of a
closing bracket inserted by the extension, the cursor moves over
that bracket.
*/
function closeBrackets() {
    return [dist_inputHandler, bracketState];
}
const definedClosing = "()[]{}<>«»»«［］｛｝";
function closing(ch) {
    for (let i = 0; i < definedClosing.length; i += 2)
        if (definedClosing.charCodeAt(i) == ch)
            return definedClosing.charAt(i + 1);
    return fromCodePoint(ch < 128 ? ch : ch + 1);
}
function dist_config(state, pos) {
    return state.languageDataAt("closeBrackets", pos)[0] || dist_defaults;
}
const android = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent);
const dist_inputHandler = /*@__PURE__*/(/* unused pure expression or super */ null && (EditorView.inputHandler.of((view, from, to, insert) => {
    if ((android ? view.composing : view.compositionStarted) || view.state.readOnly)
        return false;
    let sel = view.state.selection.main;
    if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 ||
        from != sel.from || to != sel.to)
        return false;
    let tr = insertBracket(view.state, insert);
    if (!tr)
        return false;
    view.dispatch(tr);
    return true;
})));
/**
Command that implements deleting a pair of matching brackets when
the cursor is between them.
*/
const deleteBracketPair = ({ state, dispatch }) => {
    if (state.readOnly)
        return false;
    let conf = dist_config(state, state.selection.main.head);
    let tokens = conf.brackets || dist_defaults.brackets;
    let dont = null, changes = state.changeByRange(range => {
        if (range.empty) {
            let before = prevChar(state.doc, range.head);
            for (let token of tokens) {
                if (token == before && nextChar(state.doc, range.head) == closing(dist_codePointAt(token, 0)))
                    return { changes: { from: range.head - token.length, to: range.head + token.length },
                        range: dist_EditorSelection.cursor(range.head - token.length) };
            }
        }
        return { range: dont = range };
    });
    if (!dont)
        dispatch(state.update(changes, { scrollIntoView: true, userEvent: "delete.backward" }));
    return !dont;
};
/**
Close-brackets related key bindings. Binds Backspace to
[`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).
*/
const closeBracketsKeymap = [
    { key: "Backspace", run: deleteBracketPair }
];
/**
Implements the extension's behavior on text insertion. If the
given string counts as a bracket in the language around the
selection, and replacing the selection with it requires custom
behavior (inserting a closing version or skipping past a
previously-closed bracket), this function returns a transaction
representing that custom behavior. (You only need this if you want
to programmatically insert brackets—the
[`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will
take care of running this for user input.)
*/
function insertBracket(state, bracket) {
    let conf = dist_config(state, state.selection.main.head);
    let tokens = conf.brackets || dist_defaults.brackets;
    for (let tok of tokens) {
        let closed = closing(codePointAt(tok, 0));
        if (bracket == tok)
            return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf)
                : handleOpen(state, tok, closed, conf.before || dist_defaults.before);
        if (bracket == closed && closedBracketAt(state, state.selection.main.from))
            return handleClose(state, tok, closed);
    }
    return null;
}
function closedBracketAt(state, pos) {
    let found = false;
    state.field(bracketState).between(0, state.doc.length, from => {
        if (from == pos)
            found = true;
    });
    return found;
}
function nextChar(doc, pos) {
    let next = doc.sliceString(pos, pos + 2);
    return next.slice(0, dist_codePointSize(dist_codePointAt(next, 0)));
}
function prevChar(doc, pos) {
    let prev = doc.sliceString(pos - 2, pos);
    return dist_codePointSize(dist_codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
}
function handleOpen(state, open, close, closeBefore) {
    let dont = null, changes = state.changeByRange(range => {
        if (!range.empty)
            return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }],
                effects: closeBracketEffect.of(range.to + open.length),
                range: EditorSelection.range(range.anchor + open.length, range.head + open.length) };
        let next = nextChar(state.doc, range.head);
        if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1)
            return { changes: { insert: open + close, from: range.head },
                effects: closeBracketEffect.of(range.head + open.length),
                range: EditorSelection.cursor(range.head + open.length) };
        return { range: dont = range };
    });
    return dont ? null : state.update(changes, {
        scrollIntoView: true,
        userEvent: "input.type"
    });
}
function handleClose(state, _open, close) {
    let dont = null, changes = state.changeByRange(range => {
        if (range.empty && nextChar(state.doc, range.head) == close)
            return { changes: { from: range.head, to: range.head + close.length, insert: close },
                range: EditorSelection.cursor(range.head + close.length) };
        return dont = { range };
    });
    return dont ? null : state.update(changes, {
        scrollIntoView: true,
        userEvent: "input.type"
    });
}
// Handles cases where the open and close token are the same, and
// possibly triple quotes (as in `"""abc"""`-style quoting).
function handleSame(state, token, allowTriple, config) {
    let stringPrefixes = config.stringPrefixes || dist_defaults.stringPrefixes;
    let dont = null, changes = state.changeByRange(range => {
        if (!range.empty)
            return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }],
                effects: closeBracketEffect.of(range.to + token.length),
                range: EditorSelection.range(range.anchor + token.length, range.head + token.length) };
        let pos = range.head, next = nextChar(state.doc, pos), start;
        if (next == token) {
            if (nodeStart(state, pos)) {
                return { changes: { insert: token + token, from: pos },
                    effects: closeBracketEffect.of(pos + token.length),
                    range: EditorSelection.cursor(pos + token.length) };
            }
            else if (closedBracketAt(state, pos)) {
                let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token;
                let content = isTriple ? token + token + token : token;
                return { changes: { from: pos, to: pos + content.length, insert: content },
                    range: EditorSelection.cursor(pos + content.length) };
            }
        }
        else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token &&
            (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 &&
            nodeStart(state, start)) {
            return { changes: { insert: token + token + token + token, from: pos },
                effects: closeBracketEffect.of(pos + token.length),
                range: EditorSelection.cursor(pos + token.length) };
        }
        else if (state.charCategorizer(pos)(next) != CharCategory.Word) {
            if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes))
                return { changes: { insert: token + token, from: pos },
                    effects: closeBracketEffect.of(pos + token.length),
                    range: EditorSelection.cursor(pos + token.length) };
        }
        return { range: dont = range };
    });
    return dont ? null : state.update(changes, {
        scrollIntoView: true,
        userEvent: "input.type"
    });
}
function nodeStart(state, pos) {
    let tree = syntaxTree(state).resolveInner(pos + 1);
    return tree.parent && tree.from == pos;
}
function probablyInString(state, pos, quoteToken, prefixes) {
    let node = syntaxTree(state).resolveInner(pos, -1);
    let maxPrefix = prefixes.reduce((m, p) => Math.max(m, p.length), 0);
    for (let i = 0; i < 5; i++) {
        let start = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix));
        let quotePos = start.indexOf(quoteToken);
        if (!quotePos || quotePos > -1 && prefixes.indexOf(start.slice(0, quotePos)) > -1) {
            let first = node.firstChild;
            while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) {
                if (state.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken)
                    return false;
                first = first.firstChild;
            }
            return true;
        }
        let parent = node.to == pos && node.parent;
        if (!parent)
            break;
        node = parent;
    }
    return false;
}
function canStartStringAt(state, pos, prefixes) {
    let charCat = state.charCategorizer(pos);
    if (charCat(state.sliceDoc(pos - 1, pos)) != CharCategory.Word)
        return pos;
    for (let prefix of prefixes) {
        let start = pos - prefix.length;
        if (state.sliceDoc(start, pos) == prefix && charCat(state.sliceDoc(start - 1, start)) != CharCategory.Word)
            return start;
    }
    return -1;
}

/**
Returns an extension that enables autocompletion.
*/
function autocompletion(config = {}) {
    return [
        commitCharacters,
        completionState,
        completionConfig.of(config),
        completionPlugin,
        completionKeymapExt,
        autocomplete_dist_baseTheme
    ];
}
/**
Basic keybindings for autocompletion.

 - Ctrl-Space (and Alt-\` or Alt-i on macOS): [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
 - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
 - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
 - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
 - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
 - PageUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false, "page")`
 - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
*/
const completionKeymap = [
    { key: "Ctrl-Space", run: startCompletion },
    { mac: "Alt-`", run: startCompletion },
    { mac: "Alt-i", run: startCompletion },
    { key: "Escape", run: closeCompletion },
    { key: "ArrowDown", run: /*@__PURE__*/moveCompletionSelection(true) },
    { key: "ArrowUp", run: /*@__PURE__*/moveCompletionSelection(false) },
    { key: "PageDown", run: /*@__PURE__*/moveCompletionSelection(true, "page") },
    { key: "PageUp", run: /*@__PURE__*/moveCompletionSelection(false, "page") },
    { key: "Enter", run: acceptCompletion }
];
const completionKeymapExt = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));
/**
Get the current completion status. When completions are available,
this will return `"active"`. When completions are pending (in the
process of being queried), this returns `"pending"`. Otherwise, it
returns `null`.
*/
function completionStatus(state) {
    let cState = state.field(completionState, false);
    return cState && cState.active.some(a => a.isPending) ? "pending"
        : cState && cState.active.some(a => a.state != 0 /* State.Inactive */) ? "active" : null;
}
const completionArrayCache = /*@__PURE__*/new WeakMap;
/**
Returns the available completions as an array.
*/
function currentCompletions(state) {
    var _a;
    let open = (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.open;
    if (!open || open.disabled)
        return [];
    let completions = completionArrayCache.get(open.options);
    if (!completions)
        completionArrayCache.set(open.options, completions = open.options.map(o => o.completion));
    return completions;
}
/**
Return the currently selected completion, if any.
*/
function selectedCompletion(state) {
    var _a;
    let open = (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.open;
    return open && !open.disabled && open.selected >= 0 ? open.options[open.selected].completion : null;
}
/**
Returns the currently selected position in the active completion
list, or null if no completions are active.
*/
function selectedCompletionIndex(state) {
    var _a;
    let open = (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.open;
    return open && !open.disabled && open.selected >= 0 ? open.selected : null;
}
/**
Create an effect that can be attached to a transaction to change
the currently selected completion.
*/
function setSelectedCompletion(index) {
    return setSelectedEffect.of(index);
}



;// ../../node_modules/@codemirror/commands/dist/index.js





/**
Comment or uncomment the current selection. Will use line comments
if available, otherwise falling back to block comments.
*/
const toggleComment = target => {
    let { state } = target, line = state.doc.lineAt(state.selection.main.from), config = getConfig(target.state, line.from);
    return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : false;
};
function command(f, option) {
    return ({ state, dispatch }) => {
        if (state.readOnly)
            return false;
        let tr = f(option, state);
        if (!tr)
            return false;
        dispatch(state.update(tr));
        return true;
    };
}
/**
Comment or uncomment the current selection using line comments.
The line comment syntax is taken from the
[`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).
*/
const toggleLineComment = /*@__PURE__*/command(changeLineComment, 0 /* CommentOption.Toggle */);
/**
Comment the current selection using line comments.
*/
const lineComment = /*@__PURE__*/(/* unused pure expression or super */ null && (command(changeLineComment, 1 /* CommentOption.Comment */)));
/**
Uncomment the current selection using line comments.
*/
const lineUncomment = /*@__PURE__*/(/* unused pure expression or super */ null && (command(changeLineComment, 2 /* CommentOption.Uncomment */)));
/**
Comment or uncomment the current selection using block comments.
The block comment syntax is taken from the
[`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).
*/
const toggleBlockComment = /*@__PURE__*/command(changeBlockComment, 0 /* CommentOption.Toggle */);
/**
Comment the current selection using block comments.
*/
const blockComment = /*@__PURE__*/(/* unused pure expression or super */ null && (command(changeBlockComment, 1 /* CommentOption.Comment */)));
/**
Uncomment the current selection using block comments.
*/
const blockUncomment = /*@__PURE__*/(/* unused pure expression or super */ null && (command(changeBlockComment, 2 /* CommentOption.Uncomment */)));
/**
Comment or uncomment the lines around the current selection using
block comments.
*/
const toggleBlockCommentByLine = /*@__PURE__*/command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0 /* CommentOption.Toggle */);
function getConfig(state, pos) {
    let data = state.languageDataAt("commentTokens", pos, 1);
    return data.length ? data[0] : {};
}
const SearchMargin = 50;
/**
Determines if the given range is block-commented in the given
state.
*/
function findBlockComment(state, { open, close }, from, to) {
    let textBefore = state.sliceDoc(from - SearchMargin, from);
    let textAfter = state.sliceDoc(to, to + SearchMargin);
    let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length;
    let beforeOff = textBefore.length - spaceBefore;
    if (textBefore.slice(beforeOff - open.length, beforeOff) == open &&
        textAfter.slice(spaceAfter, spaceAfter + close.length) == close) {
        return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 },
            close: { pos: to + spaceAfter, margin: spaceAfter && 1 } };
    }
    let startText, endText;
    if (to - from <= 2 * SearchMargin) {
        startText = endText = state.sliceDoc(from, to);
    }
    else {
        startText = state.sliceDoc(from, from + SearchMargin);
        endText = state.sliceDoc(to - SearchMargin, to);
    }
    let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length;
    let endOff = endText.length - endSpace - close.length;
    if (startText.slice(startSpace, startSpace + open.length) == open &&
        endText.slice(endOff, endOff + close.length) == close) {
        return { open: { pos: from + startSpace + open.length,
                margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 },
            close: { pos: to - endSpace - close.length,
                margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } };
    }
    return null;
}
function selectedLineRanges(state) {
    let ranges = [];
    for (let r of state.selection.ranges) {
        let fromLine = state.doc.lineAt(r.from);
        let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to);
        if (toLine.from > fromLine.from && toLine.from == r.to)
            toLine = r.to == fromLine.to + 1 ? fromLine : state.doc.lineAt(r.to - 1);
        let last = ranges.length - 1;
        if (last >= 0 && ranges[last].to > fromLine.from)
            ranges[last].to = toLine.to;
        else
            ranges.push({ from: fromLine.from + /^\s*/.exec(fromLine.text)[0].length, to: toLine.to });
    }
    return ranges;
}
// Performs toggle, comment and uncomment of block comments in
// languages that support them.
function changeBlockComment(option, state, ranges = state.selection.ranges) {
    let tokens = ranges.map(r => getConfig(state, r.from).block);
    if (!tokens.every(c => c))
        return null;
    let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to));
    if (option != 2 /* CommentOption.Uncomment */ && !comments.every(c => c)) {
        return { changes: state.changes(ranges.map((range, i) => {
                if (comments[i])
                    return [];
                return [{ from: range.from, insert: tokens[i].open + " " }, { from: range.to, insert: " " + tokens[i].close }];
            })) };
    }
    else if (option != 1 /* CommentOption.Comment */ && comments.some(c => c)) {
        let changes = [];
        for (let i = 0, comment; i < comments.length; i++)
            if (comment = comments[i]) {
                let token = tokens[i], { open, close } = comment;
                changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length });
            }
        return { changes };
    }
    return null;
}
// Performs toggle, comment and uncomment of line comments.
function changeLineComment(option, state, ranges = state.selection.ranges) {
    let lines = [];
    let prevLine = -1;
    for (let { from, to } of ranges) {
        let startI = lines.length, minIndent = 1e9;
        let token = getConfig(state, from).line;
        if (!token)
            continue;
        for (let pos = from; pos <= to;) {
            let line = state.doc.lineAt(pos);
            if (line.from > prevLine && (from == to || to > line.from)) {
                prevLine = line.from;
                let indent = /^\s*/.exec(line.text)[0].length;
                let empty = indent == line.length;
                let comment = line.text.slice(indent, indent + token.length) == token ? indent : -1;
                if (indent < line.text.length && indent < minIndent)
                    minIndent = indent;
                lines.push({ line, comment, token, indent, empty, single: false });
            }
            pos = line.to + 1;
        }
        if (minIndent < 1e9)
            for (let i = startI; i < lines.length; i++)
                if (lines[i].indent < lines[i].line.text.length)
                    lines[i].indent = minIndent;
        if (lines.length == startI + 1)
            lines[startI].single = true;
    }
    if (option != 2 /* CommentOption.Uncomment */ && lines.some(l => l.comment < 0 && (!l.empty || l.single))) {
        let changes = [];
        for (let { line, token, indent, empty, single } of lines)
            if (single || !empty)
                changes.push({ from: line.from + indent, insert: token + " " });
        let changeSet = state.changes(changes);
        return { changes: changeSet, selection: state.selection.map(changeSet, 1) };
    }
    else if (option != 1 /* CommentOption.Comment */ && lines.some(l => l.comment >= 0)) {
        let changes = [];
        for (let { line, comment, token } of lines)
            if (comment >= 0) {
                let from = line.from + comment, to = from + token.length;
                if (line.text[to - line.from] == " ")
                    to++;
                changes.push({ from, to });
            }
        return { changes };
    }
    return null;
}

const fromHistory = /*@__PURE__*/Annotation.define();
/**
Transaction annotation that will prevent that transaction from
being combined with other transactions in the undo history. Given
`"before"`, it'll prevent merging with previous transactions. With
`"after"`, subsequent transactions won't be combined with this
one. With `"full"`, the transaction is isolated on both sides.
*/
const isolateHistory = /*@__PURE__*/Annotation.define();
/**
This facet provides a way to register functions that, given a
transaction, provide a set of effects that the history should
store when inverting the transaction. This can be used to
integrate some kinds of effects in the history, so that they can
be undone (and redone again).
*/
const invertedEffects = /*@__PURE__*/Facet.define();
const historyConfig = /*@__PURE__*/Facet.define({
    combine(configs) {
        return combineConfig(configs, {
            minDepth: 100,
            newGroupDelay: 500,
            joinToEvent: (_t, isAdjacent) => isAdjacent,
        }, {
            minDepth: Math.max,
            newGroupDelay: Math.min,
            joinToEvent: (a, b) => (tr, adj) => a(tr, adj) || b(tr, adj)
        });
    }
});
const historyField_ = /*@__PURE__*/dist_StateField.define({
    create() {
        return HistoryState.empty;
    },
    update(state, tr) {
        let config = tr.state.facet(historyConfig);
        let fromHist = tr.annotation(fromHistory);
        if (fromHist) {
            let item = HistEvent.fromTransaction(tr, fromHist.selection), from = fromHist.side;
            let other = from == 0 /* BranchName.Done */ ? state.undone : state.done;
            if (item)
                other = updateBranch(other, other.length, config.minDepth, item);
            else
                other = addSelection(other, tr.startState.selection);
            return new HistoryState(from == 0 /* BranchName.Done */ ? fromHist.rest : other, from == 0 /* BranchName.Done */ ? other : fromHist.rest);
        }
        let isolate = tr.annotation(isolateHistory);
        if (isolate == "full" || isolate == "before")
            state = state.isolate();
        if (tr.annotation(Transaction.addToHistory) === false)
            return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state;
        let event = HistEvent.fromTransaction(tr);
        let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent);
        if (event)
            state = state.addChanges(event, time, userEvent, config, tr);
        else if (tr.selection)
            state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay);
        if (isolate == "full" || isolate == "after")
            state = state.isolate();
        return state;
    },
    toJSON(value) {
        return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) };
    },
    fromJSON(json) {
        return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON));
    }
});
/**
Create a history extension with the given configuration.
*/
function dist_history(config = {}) {
    return [
        historyField_,
        historyConfig.of(config),
        dist_EditorView.domEventHandlers({
            beforeinput(e, view) {
                let command = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null;
                if (!command)
                    return false;
                e.preventDefault();
                return command(view);
            }
        })
    ];
}
/**
The state field used to store the history data. Should probably
only be used when you want to
[serialize](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) or
[deserialize](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) state objects in a way
that preserves history.
*/
const historyField = (/* unused pure expression or super */ null && (historyField_));
function cmd(side, selection) {
    return function ({ state, dispatch }) {
        if (!selection && state.readOnly)
            return false;
        let historyState = state.field(historyField_, false);
        if (!historyState)
            return false;
        let tr = historyState.pop(side, state, selection);
        if (!tr)
            return false;
        dispatch(tr);
        return true;
    };
}
/**
Undo a single group of history events. Returns false if no group
was available.
*/
const undo = /*@__PURE__*/cmd(0 /* BranchName.Done */, false);
/**
Redo a group of history events. Returns false if no group was
available.
*/
const redo = /*@__PURE__*/cmd(1 /* BranchName.Undone */, false);
/**
Undo a change or selection change.
*/
const undoSelection = /*@__PURE__*/cmd(0 /* BranchName.Done */, true);
/**
Redo a change or selection change.
*/
const redoSelection = /*@__PURE__*/cmd(1 /* BranchName.Undone */, true);
function depth(side) {
    return function (state) {
        let histState = state.field(historyField_, false);
        if (!histState)
            return 0;
        let branch = side == 0 /* BranchName.Done */ ? histState.done : histState.undone;
        return branch.length - (branch.length && !branch[0].changes ? 1 : 0);
    };
}
/**
The amount of undoable change events available in a given state.
*/
const undoDepth = /*@__PURE__*/(/* unused pure expression or super */ null && (depth(0 /* BranchName.Done */)));
/**
The amount of redoable change events available in a given state.
*/
const redoDepth = /*@__PURE__*/(/* unused pure expression or super */ null && (depth(1 /* BranchName.Undone */)));
// History events store groups of changes or effects that need to be
// undone/redone together.
class HistEvent {
    constructor(
    // The changes in this event. Normal events hold at least one
    // change or effect. But it may be necessary to store selection
    // events before the first change, in which case a special type of
    // instance is created which doesn't hold any changes, with
    // changes == startSelection == undefined
    changes, 
    // The effects associated with this event
    effects, 
    // Accumulated mapping (from addToHistory==false) that should be
    // applied to events below this one.
    mapped, 
    // The selection before this event
    startSelection, 
    // Stores selection changes after this event, to be used for
    // selection undo/redo.
    selectionsAfter) {
        this.changes = changes;
        this.effects = effects;
        this.mapped = mapped;
        this.startSelection = startSelection;
        this.selectionsAfter = selectionsAfter;
    }
    setSelAfter(after) {
        return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after);
    }
    toJSON() {
        var _a, _b, _c;
        return {
            changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(),
            mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(),
            startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(),
            selectionsAfter: this.selectionsAfter.map(s => s.toJSON())
        };
    }
    static fromJSON(json) {
        return new HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && dist_EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(dist_EditorSelection.fromJSON));
    }
    // This does not check `addToHistory` and such, it assumes the
    // transaction needs to be converted to an item. Returns null when
    // there are no changes or effects in the transaction.
    static fromTransaction(tr, selection) {
        let effects = commands_dist_none;
        for (let invert of tr.startState.facet(invertedEffects)) {
            let result = invert(tr);
            if (result.length)
                effects = effects.concat(result);
        }
        if (!effects.length && tr.changes.empty)
            return null;
        return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, selection || tr.startState.selection, commands_dist_none);
    }
    static selection(selections) {
        return new HistEvent(undefined, commands_dist_none, undefined, undefined, selections);
    }
}
function updateBranch(branch, to, maxLen, newEvent) {
    let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
    let newBranch = branch.slice(start, to);
    newBranch.push(newEvent);
    return newBranch;
}
function isAdjacent(a, b) {
    let ranges = [], isAdjacent = false;
    a.iterChangedRanges((f, t) => ranges.push(f, t));
    b.iterChangedRanges((_f, _t, f, t) => {
        for (let i = 0; i < ranges.length;) {
            let from = ranges[i++], to = ranges[i++];
            if (t >= from && f <= to)
                isAdjacent = true;
        }
    });
    return isAdjacent;
}
function eqSelectionShape(a, b) {
    return a.ranges.length == b.ranges.length &&
        a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0;
}
function conc(a, b) {
    return !a.length ? b : !b.length ? a : a.concat(b);
}
const commands_dist_none = [];
const MaxSelectionsPerEvent = 200;
function addSelection(branch, selection) {
    if (!branch.length) {
        return [HistEvent.selection([selection])];
    }
    else {
        let lastEvent = branch[branch.length - 1];
        let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
        if (sels.length && sels[sels.length - 1].eq(selection))
            return branch;
        sels.push(selection);
        return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels));
    }
}
// Assumes the top item has one or more selectionAfter values
function popSelection(branch) {
    let last = branch[branch.length - 1];
    let newBranch = branch.slice();
    newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));
    return newBranch;
}
// Add a mapping to the top event in the given branch. If this maps
// away all the changes and effects in that item, drop it and
// propagate the mapping to the next item.
function addMappingToBranch(branch, mapping) {
    if (!branch.length)
        return branch;
    let length = branch.length, selections = commands_dist_none;
    while (length) {
        let event = mapEvent(branch[length - 1], mapping, selections);
        if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping
            let result = branch.slice(0, length);
            result[length - 1] = event;
            return result;
        }
        else { // Drop this event, since there's no changes or effects left
            mapping = event.mapped;
            length--;
            selections = event.selectionsAfter;
        }
    }
    return selections.length ? [HistEvent.selection(selections)] : commands_dist_none;
}
function mapEvent(event, mapping, extraSelections) {
    let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : commands_dist_none, extraSelections);
    // Change-less events don't store mappings (they are always the last event in a branch)
    if (!event.changes)
        return HistEvent.selection(selections);
    let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true);
    let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before;
    return new HistEvent(mappedChanges, dist_StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections);
}
const joinableUserEvent = /^(input\.type|delete)($|\.)/;
class HistoryState {
    constructor(done, undone, prevTime = 0, prevUserEvent = undefined) {
        this.done = done;
        this.undone = undone;
        this.prevTime = prevTime;
        this.prevUserEvent = prevUserEvent;
    }
    isolate() {
        return this.prevTime ? new HistoryState(this.done, this.undone) : this;
    }
    addChanges(event, time, userEvent, config, tr) {
        let done = this.done, lastEvent = done[done.length - 1];
        if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes &&
            (!userEvent || joinableUserEvent.test(userEvent)) &&
            ((!lastEvent.selectionsAfter.length &&
                time - this.prevTime < config.newGroupDelay &&
                config.joinToEvent(tr, isAdjacent(lastEvent.changes, event.changes))) ||
                // For compose (but not compose.start) events, always join with previous event
                userEvent == "input.type.compose")) {
            done = updateBranch(done, done.length - 1, config.minDepth, new HistEvent(event.changes.compose(lastEvent.changes), conc(dist_StateEffect.mapEffects(event.effects, lastEvent.changes), lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, commands_dist_none));
        }
        else {
            done = updateBranch(done, done.length, config.minDepth, event);
        }
        return new HistoryState(done, commands_dist_none, time, userEvent);
    }
    addSelection(selection, time, userEvent, newGroupDelay) {
        let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : commands_dist_none;
        if (last.length > 0 &&
            time - this.prevTime < newGroupDelay &&
            userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) &&
            eqSelectionShape(last[last.length - 1], selection))
            return this;
        return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent);
    }
    addMapping(mapping) {
        return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
    }
    pop(side, state, onlySelection) {
        let branch = side == 0 /* BranchName.Done */ ? this.done : this.undone;
        if (branch.length == 0)
            return null;
        let event = branch[branch.length - 1], selection = event.selectionsAfter[0] || state.selection;
        if (onlySelection && event.selectionsAfter.length) {
            return state.update({
                selection: event.selectionsAfter[event.selectionsAfter.length - 1],
                annotations: fromHistory.of({ side, rest: popSelection(branch), selection }),
                userEvent: side == 0 /* BranchName.Done */ ? "select.undo" : "select.redo",
                scrollIntoView: true
            });
        }
        else if (!event.changes) {
            return null;
        }
        else {
            let rest = branch.length == 1 ? commands_dist_none : branch.slice(0, branch.length - 1);
            if (event.mapped)
                rest = addMappingToBranch(rest, event.mapped);
            return state.update({
                changes: event.changes,
                selection: event.startSelection,
                effects: event.effects,
                annotations: fromHistory.of({ side, rest, selection }),
                filter: false,
                userEvent: side == 0 /* BranchName.Done */ ? "undo" : "redo",
                scrollIntoView: true
            });
        }
    }
}
HistoryState.empty = /*@__PURE__*/new HistoryState(commands_dist_none, commands_dist_none);
/**
Default key bindings for the undo history.

- Mod-z: [`undo`](https://codemirror.net/6/docs/ref/#commands.undo).
- Mod-y (Mod-Shift-z on macOS) + Ctrl-Shift-z on Linux: [`redo`](https://codemirror.net/6/docs/ref/#commands.redo).
- Mod-u: [`undoSelection`](https://codemirror.net/6/docs/ref/#commands.undoSelection).
- Alt-u (Mod-Shift-u on macOS): [`redoSelection`](https://codemirror.net/6/docs/ref/#commands.redoSelection).
*/
const historyKeymap = [
    { key: "Mod-z", run: undo, preventDefault: true },
    { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true },
    { linux: "Ctrl-Shift-z", run: redo, preventDefault: true },
    { key: "Mod-u", run: undoSelection, preventDefault: true },
    { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true }
];

function updateSel(sel, by) {
    return dist_EditorSelection.create(sel.ranges.map(by), sel.mainIndex);
}
function setSel(state, selection) {
    return state.update({ selection, scrollIntoView: true, userEvent: "select" });
}
function moveSel({ state, dispatch }, how) {
    let selection = updateSel(state.selection, how);
    if (selection.eq(state.selection, true))
        return false;
    dispatch(setSel(state, selection));
    return true;
}
function rangeEnd(range, forward) {
    return dist_EditorSelection.cursor(forward ? range.to : range.from);
}
function cursorByChar(view, forward) {
    return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward));
}
function ltrAtCursor(view) {
    return view.textDirectionAt(view.state.selection.main.head) == Direction.LTR;
}
/**
Move the selection one character to the left (which is backward in
left-to-right text, forward in right-to-left text).
*/
const cursorCharLeft = view => cursorByChar(view, !ltrAtCursor(view));
/**
Move the selection one character to the right.
*/
const cursorCharRight = view => cursorByChar(view, ltrAtCursor(view));
/**
Move the selection one character forward.
*/
const cursorCharForward = view => cursorByChar(view, true);
/**
Move the selection one character backward.
*/
const cursorCharBackward = view => cursorByChar(view, false);
function byCharLogical(state, range, forward) {
    let pos = range.head, line = state.doc.lineAt(pos);
    if (pos == (forward ? line.to : line.from))
        pos = forward ? Math.min(state.doc.length, line.to + 1) : Math.max(0, line.from - 1);
    else
        pos = line.from + findClusterBreak(line.text, pos - line.from, forward);
    return EditorSelection.cursor(pos, forward ? -1 : 1);
}
function moveByCharLogical(target, forward) {
    return moveSel(target, range => range.empty ? byCharLogical(target.state, range, forward) : rangeEnd(range, forward));
}
/**
Move the selection one character forward, in logical
(non-text-direction-aware) string index order.
*/
const cursorCharForwardLogical = target => moveByCharLogical(target, true);
/**
Move the selection one character backward, in logical string index
order.
*/
const cursorCharBackwardLogical = target => moveByCharLogical(target, false);
function cursorByGroup(view, forward) {
    return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward));
}
/**
Move the selection to the left across one group of word or
non-word (but also non-space) characters.
*/
const cursorGroupLeft = view => cursorByGroup(view, !ltrAtCursor(view));
/**
Move the selection one group to the right.
*/
const cursorGroupRight = view => cursorByGroup(view, ltrAtCursor(view));
/**
Move the selection one group forward.
*/
const cursorGroupForward = view => cursorByGroup(view, true);
/**
Move the selection one group backward.
*/
const cursorGroupBackward = view => cursorByGroup(view, false);
function toGroupStart(view, pos, start) {
    let categorize = view.state.charCategorizer(pos);
    let cat = categorize(start), initial = cat != CharCategory.Space;
    return (next) => {
        let nextCat = categorize(next);
        if (nextCat != CharCategory.Space)
            return initial && nextCat == cat;
        initial = false;
        return true;
    };
}
/**
Move the cursor one group forward in the default Windows style,
where it moves to the start of the next group.
*/
const cursorGroupForwardWin = view => {
    return moveSel(view, range => range.empty
        ? view.moveByChar(range, true, start => toGroupStart(view, range.head, start))
        : rangeEnd(range, true));
};
const segmenter = typeof Intl != "undefined" && Intl.Segmenter ?
    /*@__PURE__*/new (Intl.Segmenter)(undefined, { granularity: "word" }) : null;
function moveBySubword(view, range, forward) {
    let categorize = view.state.charCategorizer(range.from);
    let cat = CharCategory.Space, pos = range.from, steps = 0;
    let done = false, sawUpper = false, sawLower = false;
    let step = (next) => {
        if (done)
            return false;
        pos += forward ? next.length : -next.length;
        let nextCat = categorize(next), ahead;
        if (nextCat == CharCategory.Word && next.charCodeAt(0) < 128 && /[\W_]/.test(next))
            nextCat = -1; // Treat word punctuation specially
        if (cat == CharCategory.Space)
            cat = nextCat;
        if (cat != nextCat)
            return false;
        if (cat == CharCategory.Word) {
            if (next.toLowerCase() == next) {
                if (!forward && sawUpper)
                    return false;
                sawLower = true;
            }
            else if (sawLower) {
                if (forward)
                    return false;
                done = true;
            }
            else {
                if (sawUpper && forward && categorize(ahead = view.state.sliceDoc(pos, pos + 1)) == CharCategory.Word &&
                    ahead.toLowerCase() == ahead)
                    return false;
                sawUpper = true;
            }
        }
        steps++;
        return true;
    };
    let end = view.moveByChar(range, forward, start => {
        step(start);
        return step;
    });
    if (segmenter && cat == CharCategory.Word && end.from == range.from + steps * (forward ? 1 : -1)) {
        let from = Math.min(range.head, end.head), to = Math.max(range.head, end.head);
        let skipped = view.state.sliceDoc(from, to);
        if (skipped.length > 1 && /[\u4E00-\uffff]/.test(skipped)) {
            let segments = Array.from(segmenter.segment(skipped));
            if (segments.length > 1) {
                if (forward)
                    return EditorSelection.cursor(range.head + segments[1].index, -1);
                return EditorSelection.cursor(end.head + segments[segments.length - 1].index, 1);
            }
        }
    }
    return end;
}
function cursorBySubword(view, forward) {
    return moveSel(view, range => range.empty ? moveBySubword(view, range, forward) : rangeEnd(range, forward));
}
/**
Move the selection one group or camel-case subword forward.
*/
const cursorSubwordForward = view => cursorBySubword(view, true);
/**
Move the selection one group or camel-case subword backward.
*/
const cursorSubwordBackward = view => cursorBySubword(view, false);
function interestingNode(state, node, bracketProp) {
    if (node.type.prop(bracketProp))
        return true;
    let len = node.to - node.from;
    return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild;
}
function moveBySyntax(state, start, forward) {
    let pos = dist_syntaxTree(state).resolveInner(start.head);
    let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;
    // Scan forward through child nodes to see if there's an interesting
    // node ahead.
    for (let at = start.head;;) {
        let next = forward ? pos.childAfter(at) : pos.childBefore(at);
        if (!next)
            break;
        if (interestingNode(state, next, bracketProp))
            pos = next;
        else
            at = forward ? next.to : next.from;
    }
    let bracket = pos.type.prop(bracketProp), match, newPos;
    if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched)
        newPos = forward ? match.end.to : match.end.from;
    else
        newPos = forward ? pos.to : pos.from;
    return dist_EditorSelection.cursor(newPos, forward ? -1 : 1);
}
/**
Move the cursor over the next syntactic element to the left.
*/
const cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view)));
/**
Move the cursor over the next syntactic element to the right.
*/
const cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view)));
function cursorByLine(view, forward) {
    return moveSel(view, range => {
        if (!range.empty)
            return rangeEnd(range, forward);
        let moved = view.moveVertically(range, forward);
        return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward);
    });
}
/**
Move the selection one line up.
*/
const cursorLineUp = view => cursorByLine(view, false);
/**
Move the selection one line down.
*/
const cursorLineDown = view => cursorByLine(view, true);
function pageInfo(view) {
    let selfScroll = view.scrollDOM.clientHeight < view.scrollDOM.scrollHeight - 2;
    let marginTop = 0, marginBottom = 0, height;
    if (selfScroll) {
        for (let source of view.state.facet(dist_EditorView.scrollMargins)) {
            let margins = source(view);
            if (margins === null || margins === void 0 ? void 0 : margins.top)
                marginTop = Math.max(margins === null || margins === void 0 ? void 0 : margins.top, marginTop);
            if (margins === null || margins === void 0 ? void 0 : margins.bottom)
                marginBottom = Math.max(margins === null || margins === void 0 ? void 0 : margins.bottom, marginBottom);
        }
        height = view.scrollDOM.clientHeight - marginTop - marginBottom;
    }
    else {
        height = (view.dom.ownerDocument.defaultView || window).innerHeight;
    }
    return { marginTop, marginBottom, selfScroll,
        height: Math.max(view.defaultLineHeight, height - 5) };
}
function cursorByPage(view, forward) {
    let page = pageInfo(view);
    let { state } = view, selection = updateSel(state.selection, range => {
        return range.empty ? view.moveVertically(range, forward, page.height)
            : rangeEnd(range, forward);
    });
    if (selection.eq(state.selection))
        return false;
    let effect;
    if (page.selfScroll) {
        let startPos = view.coordsAtPos(state.selection.main.head);
        let scrollRect = view.scrollDOM.getBoundingClientRect();
        let scrollTop = scrollRect.top + page.marginTop, scrollBottom = scrollRect.bottom - page.marginBottom;
        if (startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom)
            effect = dist_EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollTop });
    }
    view.dispatch(setSel(state, selection), { effects: effect });
    return true;
}
/**
Move the selection one page up.
*/
const cursorPageUp = view => cursorByPage(view, false);
/**
Move the selection one page down.
*/
const cursorPageDown = view => cursorByPage(view, true);
function moveByLineBoundary(view, start, forward) {
    let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward);
    if (moved.head == start.head && moved.head != (forward ? line.to : line.from))
        moved = view.moveToLineBoundary(start, forward, false);
    if (!forward && moved.head == line.from && line.length) {
        let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length;
        if (space && start.head != line.from + space)
            moved = dist_EditorSelection.cursor(line.from + space);
    }
    return moved;
}
/**
Move the selection to the next line wrap point, or to the end of
the line if there isn't one left on this line.
*/
const cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true));
/**
Move the selection to previous line wrap point, or failing that to
the start of the line. If the line is indented, and the cursor
isn't already at the end of the indentation, this will move to the
end of the indentation instead of the start of the line.
*/
const cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false));
/**
Move the selection one line wrap point to the left.
*/
const cursorLineBoundaryLeft = view => moveSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view)));
/**
Move the selection one line wrap point to the right.
*/
const cursorLineBoundaryRight = view => moveSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view)));
/**
Move the selection to the start of the line.
*/
const cursorLineStart = view => moveSel(view, range => dist_EditorSelection.cursor(view.lineBlockAt(range.head).from, 1));
/**
Move the selection to the end of the line.
*/
const cursorLineEnd = view => moveSel(view, range => dist_EditorSelection.cursor(view.lineBlockAt(range.head).to, -1));
function toMatchingBracket(state, dispatch, extend) {
    let found = false, selection = updateSel(state.selection, range => {
        let matching = matchBrackets(state, range.head, -1)
            || matchBrackets(state, range.head, 1)
            || (range.head > 0 && matchBrackets(state, range.head - 1, 1))
            || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1));
        if (!matching || !matching.end)
            return range;
        found = true;
        let head = matching.start.from == range.head ? matching.end.to : matching.end.from;
        return extend ? dist_EditorSelection.range(range.anchor, head) : dist_EditorSelection.cursor(head);
    });
    if (!found)
        return false;
    dispatch(setSel(state, selection));
    return true;
}
/**
Move the selection to the bracket matching the one it is currently
on, if any.
*/
const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false);
/**
Extend the selection to the bracket matching the one the selection
head is currently on, if any.
*/
const selectMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, true);
function extendSel(target, how) {
    let selection = updateSel(target.state.selection, range => {
        let head = how(range);
        return dist_EditorSelection.range(range.anchor, head.head, head.goalColumn, head.bidiLevel || undefined);
    });
    if (selection.eq(target.state.selection))
        return false;
    target.dispatch(setSel(target.state, selection));
    return true;
}
function selectByChar(view, forward) {
    return extendSel(view, range => view.moveByChar(range, forward));
}
/**
Move the selection head one character to the left, while leaving
the anchor in place.
*/
const selectCharLeft = view => selectByChar(view, !ltrAtCursor(view));
/**
Move the selection head one character to the right.
*/
const selectCharRight = view => selectByChar(view, ltrAtCursor(view));
/**
Move the selection head one character forward.
*/
const selectCharForward = view => selectByChar(view, true);
/**
Move the selection head one character backward.
*/
const selectCharBackward = view => selectByChar(view, false);
/**
Move the selection head one character forward by logical
(non-direction aware) string index order.
*/
const selectCharForwardLogical = target => extendSel(target, range => byCharLogical(target.state, range, true));
/**
Move the selection head one character backward by logical string
index order.
*/
const selectCharBackwardLogical = target => extendSel(target, range => byCharLogical(target.state, range, false));
function selectByGroup(view, forward) {
    return extendSel(view, range => view.moveByGroup(range, forward));
}
/**
Move the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to
the left.
*/
const selectGroupLeft = view => selectByGroup(view, !ltrAtCursor(view));
/**
Move the selection head one group to the right.
*/
const selectGroupRight = view => selectByGroup(view, ltrAtCursor(view));
/**
Move the selection head one group forward.
*/
const selectGroupForward = view => selectByGroup(view, true);
/**
Move the selection head one group backward.
*/
const selectGroupBackward = view => selectByGroup(view, false);
/**
Move the selection head one group forward in the default Windows
style, skipping to the start of the next group.
*/
const selectGroupForwardWin = view => {
    return extendSel(view, range => view.moveByChar(range, true, start => toGroupStart(view, range.head, start)));
};
function selectBySubword(view, forward) {
    return extendSel(view, range => moveBySubword(view, range, forward));
}
/**
Move the selection head one group or camel-case subword forward.
*/
const selectSubwordForward = view => selectBySubword(view, true);
/**
Move the selection head one group or subword backward.
*/
const selectSubwordBackward = view => selectBySubword(view, false);
/**
Move the selection head over the next syntactic element to the left.
*/
const selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view)));
/**
Move the selection head over the next syntactic element to the right.
*/
const selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view)));
function selectByLine(view, forward) {
    return extendSel(view, range => view.moveVertically(range, forward));
}
/**
Move the selection head one line up.
*/
const selectLineUp = view => selectByLine(view, false);
/**
Move the selection head one line down.
*/
const selectLineDown = view => selectByLine(view, true);
function selectByPage(view, forward) {
    return extendSel(view, range => view.moveVertically(range, forward, pageInfo(view).height));
}
/**
Move the selection head one page up.
*/
const selectPageUp = view => selectByPage(view, false);
/**
Move the selection head one page down.
*/
const selectPageDown = view => selectByPage(view, true);
/**
Move the selection head to the next line boundary.
*/
const selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true));
/**
Move the selection head to the previous line boundary.
*/
const selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false));
/**
Move the selection head one line boundary to the left.
*/
const selectLineBoundaryLeft = view => extendSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view)));
/**
Move the selection head one line boundary to the right.
*/
const selectLineBoundaryRight = view => extendSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view)));
/**
Move the selection head to the start of the line.
*/
const selectLineStart = view => extendSel(view, range => dist_EditorSelection.cursor(view.lineBlockAt(range.head).from));
/**
Move the selection head to the end of the line.
*/
const selectLineEnd = view => extendSel(view, range => dist_EditorSelection.cursor(view.lineBlockAt(range.head).to));
/**
Move the selection to the start of the document.
*/
const cursorDocStart = ({ state, dispatch }) => {
    dispatch(setSel(state, { anchor: 0 }));
    return true;
};
/**
Move the selection to the end of the document.
*/
const cursorDocEnd = ({ state, dispatch }) => {
    dispatch(setSel(state, { anchor: state.doc.length }));
    return true;
};
/**
Move the selection head to the start of the document.
*/
const selectDocStart = ({ state, dispatch }) => {
    dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 }));
    return true;
};
/**
Move the selection head to the end of the document.
*/
const selectDocEnd = ({ state, dispatch }) => {
    dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length }));
    return true;
};
/**
Select the entire document.
*/
const selectAll = ({ state, dispatch }) => {
    dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" }));
    return true;
};
/**
Expand the selection to cover entire lines.
*/
const selectLine = ({ state, dispatch }) => {
    let ranges = selectedLineBlocks(state).map(({ from, to }) => dist_EditorSelection.range(from, Math.min(to + 1, state.doc.length)));
    dispatch(state.update({ selection: dist_EditorSelection.create(ranges), userEvent: "select" }));
    return true;
};
/**
Select the next syntactic construct that is larger than the
selection. Note that this will only work insofar as the language
[provider](https://codemirror.net/6/docs/ref/#language.language) you use builds up a full
syntax tree.
*/
const selectParentSyntax = ({ state, dispatch }) => {
    let selection = updateSel(state.selection, range => {
        let tree = dist_syntaxTree(state), stack = tree.resolveStack(range.from, 1);
        if (range.empty) {
            let stackBefore = tree.resolveStack(range.from, -1);
            if (stackBefore.node.from >= stack.node.from && stackBefore.node.to <= stack.node.to)
                stack = stackBefore;
        }
        for (let cur = stack; cur; cur = cur.next) {
            let { node } = cur;
            if (((node.from < range.from && node.to >= range.to) ||
                (node.to > range.to && node.from <= range.from)) &&
                cur.next)
                return dist_EditorSelection.range(node.to, node.from);
        }
        return range;
    });
    if (selection.eq(state.selection))
        return false;
    dispatch(setSel(state, selection));
    return true;
};
function addCursorVertically(view, forward) {
    let { state } = view, sel = state.selection, ranges = state.selection.ranges.slice();
    for (let range of state.selection.ranges) {
        let line = state.doc.lineAt(range.head);
        if (forward ? line.to < view.state.doc.length : line.from > 0)
            for (let cur = range;;) {
                let next = view.moveVertically(cur, forward);
                if (next.head < line.from || next.head > line.to) {
                    if (!ranges.some(r => r.head == next.head))
                        ranges.push(next);
                    break;
                }
                else if (next.head == cur.head) {
                    break;
                }
                else {
                    cur = next;
                }
            }
    }
    if (ranges.length == sel.ranges.length)
        return false;
    view.dispatch(setSel(state, dist_EditorSelection.create(ranges, ranges.length - 1)));
    return true;
}
/**
Expand the selection by adding a cursor above the heads of
currently selected ranges.
*/
const addCursorAbove = view => addCursorVertically(view, false);
/**
Expand the selection by adding a cursor below the heads of
currently selected ranges.
*/
const addCursorBelow = view => addCursorVertically(view, true);
/**
Simplify the current selection. When multiple ranges are selected,
reduce it to its main range. Otherwise, if the selection is
non-empty, convert it to a cursor selection.
*/
const simplifySelection = ({ state, dispatch }) => {
    let cur = state.selection, selection = null;
    if (cur.ranges.length > 1)
        selection = dist_EditorSelection.create([cur.main]);
    else if (!cur.main.empty)
        selection = dist_EditorSelection.create([dist_EditorSelection.cursor(cur.main.head)]);
    if (!selection)
        return false;
    dispatch(setSel(state, selection));
    return true;
};
function deleteBy(target, by) {
    if (target.state.readOnly)
        return false;
    let event = "delete.selection", { state } = target;
    let changes = state.changeByRange(range => {
        let { from, to } = range;
        if (from == to) {
            let towards = by(range);
            if (towards < from) {
                event = "delete.backward";
                towards = skipAtomic(target, towards, false);
            }
            else if (towards > from) {
                event = "delete.forward";
                towards = skipAtomic(target, towards, true);
            }
            from = Math.min(from, towards);
            to = Math.max(to, towards);
        }
        else {
            from = skipAtomic(target, from, false);
            to = skipAtomic(target, to, true);
        }
        return from == to ? { range } : { changes: { from, to }, range: dist_EditorSelection.cursor(from, from < range.head ? -1 : 1) };
    });
    if (changes.changes.empty)
        return false;
    target.dispatch(state.update(changes, {
        scrollIntoView: true,
        userEvent: event,
        effects: event == "delete.selection" ? dist_EditorView.announce.of(state.phrase("Selection deleted")) : undefined
    }));
    return true;
}
function skipAtomic(target, pos, forward) {
    if (target instanceof dist_EditorView)
        for (let ranges of target.state.facet(dist_EditorView.atomicRanges).map(f => f(target)))
            ranges.between(pos, pos, (from, to) => {
                if (from < pos && to > pos)
                    pos = forward ? to : from;
            });
    return pos;
}
const deleteByChar = (target, forward, byIndentUnit) => deleteBy(target, range => {
    let pos = range.from, { state } = target, line = state.doc.lineAt(pos), before, targetPos;
    if (byIndentUnit && !forward && pos > line.from && pos < line.from + 200 &&
        !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) {
        if (before[before.length - 1] == "\t")
            return pos - 1;
        let col = dist_countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state);
        for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++)
            pos--;
        targetPos = pos;
    }
    else {
        targetPos = dist_findClusterBreak(line.text, pos - line.from, forward, forward) + line.from;
        if (targetPos == pos && line.number != (forward ? state.doc.lines : 1))
            targetPos += forward ? 1 : -1;
        else if (!forward && /[\ufe00-\ufe0f]/.test(line.text.slice(targetPos - line.from, pos - line.from)))
            targetPos = dist_findClusterBreak(line.text, targetPos - line.from, false, false) + line.from;
    }
    return targetPos;
});
/**
Delete the selection, or, for cursor selections, the character or
indentation unit before the cursor.
*/
const deleteCharBackward = view => deleteByChar(view, false, true);
/**
Delete the selection or the character before the cursor. Does not
implement any extended behavior like deleting whole indentation
units in one go.
*/
const deleteCharBackwardStrict = view => deleteByChar(view, false, false);
/**
Delete the selection or the character after the cursor.
*/
const deleteCharForward = view => deleteByChar(view, true, false);
const deleteByGroup = (target, forward) => deleteBy(target, range => {
    let pos = range.head, { state } = target, line = state.doc.lineAt(pos);
    let categorize = state.charCategorizer(pos);
    for (let cat = null;;) {
        if (pos == (forward ? line.to : line.from)) {
            if (pos == range.head && line.number != (forward ? state.doc.lines : 1))
                pos += forward ? 1 : -1;
            break;
        }
        let next = dist_findClusterBreak(line.text, pos - line.from, forward) + line.from;
        let nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from);
        let nextCat = categorize(nextChar);
        if (cat != null && nextCat != cat)
            break;
        if (nextChar != " " || pos != range.head)
            cat = nextCat;
        pos = next;
    }
    return pos;
});
/**
Delete the selection or backward until the end of the next
[group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of
whitespace when they consist of a single space.
*/
const deleteGroupBackward = target => deleteByGroup(target, false);
/**
Delete the selection or forward until the end of the next group.
*/
const deleteGroupForward = target => deleteByGroup(target, true);
/**
Variant of [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward)
that uses the Windows convention of also deleting the whitespace
after a word.
*/
const deleteGroupForwardWin = view => deleteBy(view, range => view.moveByChar(range, true, start => toGroupStart(view, range.head, start)).head);
/**
Delete the selection, or, if it is a cursor selection, delete to
the end of the line. If the cursor is directly at the end of the
line, delete the line break after it.
*/
const deleteToLineEnd = view => deleteBy(view, range => {
    let lineEnd = view.lineBlockAt(range.head).to;
    return range.head < lineEnd ? lineEnd : Math.min(view.state.doc.length, range.head + 1);
});
/**
Delete the selection, or, if it is a cursor selection, delete to
the start of the line. If the cursor is directly at the start of the
line, delete the line break before it.
*/
const deleteToLineStart = view => deleteBy(view, range => {
    let lineStart = view.lineBlockAt(range.head).from;
    return range.head > lineStart ? lineStart : Math.max(0, range.head - 1);
});
/**
Delete the selection, or, if it is a cursor selection, delete to
the start of the line or the next line wrap before the cursor.
*/
const deleteLineBoundaryBackward = view => deleteBy(view, range => {
    let lineStart = view.moveToLineBoundary(range, false).head;
    return range.head > lineStart ? lineStart : Math.max(0, range.head - 1);
});
/**
Delete the selection, or, if it is a cursor selection, delete to
the end of the line or the next line wrap after the cursor.
*/
const deleteLineBoundaryForward = view => deleteBy(view, range => {
    let lineStart = view.moveToLineBoundary(range, true).head;
    return range.head < lineStart ? lineStart : Math.min(view.state.doc.length, range.head + 1);
});
/**
Delete all whitespace directly before a line end from the
document.
*/
const deleteTrailingWhitespace = ({ state, dispatch }) => {
    if (state.readOnly)
        return false;
    let changes = [];
    for (let pos = 0, prev = "", iter = state.doc.iter();;) {
        iter.next();
        if (iter.lineBreak || iter.done) {
            let trailing = prev.search(/\s+$/);
            if (trailing > -1)
                changes.push({ from: pos - (prev.length - trailing), to: pos });
            if (iter.done)
                break;
            prev = "";
        }
        else {
            prev = iter.value;
        }
        pos += iter.value.length;
    }
    if (!changes.length)
        return false;
    dispatch(state.update({ changes, userEvent: "delete" }));
    return true;
};
/**
Replace each selection range with a line break, leaving the cursor
on the line before the break.
*/
const splitLine = ({ state, dispatch }) => {
    if (state.readOnly)
        return false;
    let changes = state.changeByRange(range => {
        return { changes: { from: range.from, to: range.to, insert: dist_Text.of(["", ""]) },
            range: dist_EditorSelection.cursor(range.from) };
    });
    dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
    return true;
};
/**
Flip the characters before and after the cursor(s).
*/
const transposeChars = ({ state, dispatch }) => {
    if (state.readOnly)
        return false;
    let changes = state.changeByRange(range => {
        if (!range.empty || range.from == 0 || range.from == state.doc.length)
            return { range };
        let pos = range.from, line = state.doc.lineAt(pos);
        let from = pos == line.from ? pos - 1 : dist_findClusterBreak(line.text, pos - line.from, false) + line.from;
        let to = pos == line.to ? pos + 1 : dist_findClusterBreak(line.text, pos - line.from, true) + line.from;
        return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) },
            range: dist_EditorSelection.cursor(to) };
    });
    if (changes.changes.empty)
        return false;
    dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" }));
    return true;
};
function selectedLineBlocks(state) {
    let blocks = [], upto = -1;
    for (let range of state.selection.ranges) {
        let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to);
        if (!range.empty && range.to == endLine.from)
            endLine = state.doc.lineAt(range.to - 1);
        if (upto >= startLine.number) {
            let prev = blocks[blocks.length - 1];
            prev.to = endLine.to;
            prev.ranges.push(range);
        }
        else {
            blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] });
        }
        upto = endLine.number + 1;
    }
    return blocks;
}
function moveLine(state, dispatch, forward) {
    if (state.readOnly)
        return false;
    let changes = [], ranges = [];
    for (let block of selectedLineBlocks(state)) {
        if (forward ? block.to == state.doc.length : block.from == 0)
            continue;
        let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1);
        let size = nextLine.length + 1;
        if (forward) {
            changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak });
            for (let r of block.ranges)
                ranges.push(dist_EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size)));
        }
        else {
            changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text });
            for (let r of block.ranges)
                ranges.push(dist_EditorSelection.range(r.anchor - size, r.head - size));
        }
    }
    if (!changes.length)
        return false;
    dispatch(state.update({
        changes,
        scrollIntoView: true,
        selection: dist_EditorSelection.create(ranges, state.selection.mainIndex),
        userEvent: "move.line"
    }));
    return true;
}
/**
Move the selected lines up one line.
*/
const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false);
/**
Move the selected lines down one line.
*/
const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true);
function copyLine(state, dispatch, forward) {
    if (state.readOnly)
        return false;
    let changes = [];
    for (let block of selectedLineBlocks(state)) {
        if (forward)
            changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak });
        else
            changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) });
    }
    let changeSet = state.changes(changes);
    dispatch(state.update({
        changes: changeSet,
        selection: state.selection.map(changeSet, forward ? 1 : -1),
        scrollIntoView: true,
        userEvent: "input.copyline"
    }));
    return true;
}
/**
Create a copy of the selected lines. Keep the selection in the top copy.
*/
const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false);
/**
Create a copy of the selected lines. Keep the selection in the bottom copy.
*/
const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true);
/**
Delete selected lines.
*/
const deleteLine = view => {
    if (view.state.readOnly)
        return false;
    let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => {
        if (from > 0)
            from--;
        else if (to < state.doc.length)
            to++;
        return { from, to };
    }));
    let selection = updateSel(state.selection, range => {
        let dist = undefined;
        if (view.lineWrapping) {
            let block = view.lineBlockAt(range.head), pos = view.coordsAtPos(range.head, range.assoc || 1);
            if (pos)
                dist = (block.bottom + view.documentTop) - pos.bottom + view.defaultLineHeight / 2;
        }
        return view.moveVertically(range, true, dist);
    }).map(changes);
    view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" });
    return true;
};
/**
Replace the selection with a newline.
*/
const insertNewline = ({ state, dispatch }) => {
    dispatch(state.update(state.replaceSelection(state.lineBreak), { scrollIntoView: true, userEvent: "input" }));
    return true;
};
/**
Replace the selection with a newline and the same amount of
indentation as the line above.
*/
const insertNewlineKeepIndent = ({ state, dispatch }) => {
    dispatch(state.update(state.changeByRange(range => {
        let indent = /^\s*/.exec(state.doc.lineAt(range.from).text)[0];
        return {
            changes: { from: range.from, to: range.to, insert: state.lineBreak + indent },
            range: EditorSelection.cursor(range.from + indent.length + 1)
        };
    }), { scrollIntoView: true, userEvent: "input" }));
    return true;
};
function isBetweenBrackets(state, pos) {
    if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1)))
        return { from: pos, to: pos };
    let context = dist_syntaxTree(state).resolveInner(pos);
    let before = context.childBefore(pos), after = context.childAfter(pos), closedBy;
    if (before && after && before.to <= pos && after.from >= pos &&
        (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 &&
        state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from &&
        !/\S/.test(state.sliceDoc(before.to, after.from)))
        return { from: before.to, to: after.from };
    return null;
}
/**
Replace the selection with a newline and indent the newly created
line(s). If the current line consists only of whitespace, this
will also delete that whitespace. When the cursor is between
matching brackets, an additional newline will be inserted after
the cursor.
*/
const insertNewlineAndIndent = /*@__PURE__*/newlineAndIndent(false);
/**
Create a blank, indented line below the current line.
*/
const insertBlankLine = /*@__PURE__*/newlineAndIndent(true);
function newlineAndIndent(atEof) {
    return ({ state, dispatch }) => {
        if (state.readOnly)
            return false;
        let changes = state.changeByRange(range => {
            let { from, to } = range, line = state.doc.lineAt(from);
            let explode = !atEof && from == to && isBetweenBrackets(state, from);
            if (atEof)
                from = to = (to <= line.to ? line : state.doc.lineAt(to)).to;
            let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode });
            let indent = getIndentation(cx, from);
            if (indent == null)
                indent = dist_countColumn(/^\s*/.exec(state.doc.lineAt(from).text)[0], state.tabSize);
            while (to < line.to && /\s/.test(line.text[to - line.from]))
                to++;
            if (explode)
                ({ from, to } = explode);
            else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from)))
                from = line.from;
            let insert = ["", indentString(state, indent)];
            if (explode)
                insert.push(indentString(state, cx.lineIndent(line.from, -1)));
            return { changes: { from, to, insert: dist_Text.of(insert) },
                range: dist_EditorSelection.cursor(from + 1 + insert[1].length) };
        });
        dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
        return true;
    };
}
function changeBySelectedLine(state, f) {
    let atLine = -1;
    return state.changeByRange(range => {
        let changes = [];
        for (let pos = range.from; pos <= range.to;) {
            let line = state.doc.lineAt(pos);
            if (line.number > atLine && (range.empty || range.to > line.from)) {
                f(line, changes, range);
                atLine = line.number;
            }
            pos = line.to + 1;
        }
        let changeSet = state.changes(changes);
        return { changes,
            range: dist_EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) };
    });
}
/**
Auto-indent the selected lines. This uses the [indentation service
facet](https://codemirror.net/6/docs/ref/#language.indentService) as source for auto-indent
information.
*/
const indentSelection = ({ state, dispatch }) => {
    if (state.readOnly)
        return false;
    let updated = Object.create(null);
    let context = new IndentContext(state, { overrideIndentation: start => {
            let found = updated[start];
            return found == null ? -1 : found;
        } });
    let changes = changeBySelectedLine(state, (line, changes, range) => {
        let indent = getIndentation(context, line.from);
        if (indent == null)
            return;
        if (!/\S/.test(line.text))
            indent = 0;
        let cur = /^\s*/.exec(line.text)[0];
        let norm = indentString(state, indent);
        if (cur != norm || range.from < line.from + cur.length) {
            updated[line.from] = indent;
            changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
        }
    });
    if (!changes.changes.empty)
        dispatch(state.update(changes, { userEvent: "indent" }));
    return true;
};
/**
Add a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected
lines.
*/
const indentMore = ({ state, dispatch }) => {
    if (state.readOnly)
        return false;
    dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
        changes.push({ from: line.from, insert: state.facet(indentUnit) });
    }), { userEvent: "input.indent" }));
    return true;
};
/**
Remove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all
selected lines.
*/
const indentLess = ({ state, dispatch }) => {
    if (state.readOnly)
        return false;
    dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
        let space = /^\s*/.exec(line.text)[0];
        if (!space)
            return;
        let col = dist_countColumn(space, state.tabSize), keep = 0;
        let insert = indentString(state, Math.max(0, col - getIndentUnit(state)));
        while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep))
            keep++;
        changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) });
    }), { userEvent: "delete.dedent" }));
    return true;
};
/**
Enables or disables
[tab-focus mode](https://codemirror.net/6/docs/ref/#view.EditorView.setTabFocusMode). While on, this
prevents the editor's key bindings from capturing Tab or
Shift-Tab, making it possible for the user to move focus out of
the editor with the keyboard.
*/
const toggleTabFocusMode = view => {
    view.setTabFocusMode();
    return true;
};
/**
Temporarily enables [tab-focus
mode](https://codemirror.net/6/docs/ref/#view.EditorView.setTabFocusMode) for two seconds or until
another key is pressed.
*/
const temporarilySetTabFocusMode = view => {
    view.setTabFocusMode(2000);
    return true;
};
/**
Insert a tab character at the cursor or, if something is selected,
use [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) to indent the entire
selection.
*/
const insertTab = ({ state, dispatch }) => {
    if (state.selection.ranges.some(r => !r.empty))
        return indentMore({ state, dispatch });
    dispatch(state.update(state.replaceSelection("\t"), { scrollIntoView: true, userEvent: "input" }));
    return true;
};
/**
Array of key bindings containing the Emacs-style bindings that are
available on macOS by default.

 - Ctrl-b: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift)
 - Ctrl-f: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift)
 - Ctrl-p: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift)
 - Ctrl-n: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift)
 - Ctrl-a: [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift)
 - Ctrl-e: [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift)
 - Ctrl-d: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward)
 - Ctrl-h: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward)
 - Ctrl-k: [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd)
 - Ctrl-Alt-h: [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward)
 - Ctrl-o: [`splitLine`](https://codemirror.net/6/docs/ref/#commands.splitLine)
 - Ctrl-t: [`transposeChars`](https://codemirror.net/6/docs/ref/#commands.transposeChars)
 - Ctrl-v: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown)
 - Alt-v: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp)
*/
const emacsStyleKeymap = [
    { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
    { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight },
    { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp },
    { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown },
    { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart },
    { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd },
    { key: "Ctrl-d", run: deleteCharForward },
    { key: "Ctrl-h", run: deleteCharBackward },
    { key: "Ctrl-k", run: deleteToLineEnd },
    { key: "Ctrl-Alt-h", run: deleteGroupBackward },
    { key: "Ctrl-o", run: splitLine },
    { key: "Ctrl-t", run: transposeChars },
    { key: "Ctrl-v", run: cursorPageDown },
];
/**
An array of key bindings closely sticking to platform-standard or
widely used bindings. (This includes the bindings from
[`emacsStyleKeymap`](https://codemirror.net/6/docs/ref/#commands.emacsStyleKeymap), with their `key`
property changed to `mac`.)

 - ArrowLeft: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift)
 - ArrowRight: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift)
 - Ctrl-ArrowLeft (Alt-ArrowLeft on macOS): [`cursorGroupLeft`](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) ([`selectGroupLeft`](https://codemirror.net/6/docs/ref/#commands.selectGroupLeft) with Shift)
 - Ctrl-ArrowRight (Alt-ArrowRight on macOS): [`cursorGroupRight`](https://codemirror.net/6/docs/ref/#commands.cursorGroupRight) ([`selectGroupRight`](https://codemirror.net/6/docs/ref/#commands.selectGroupRight) with Shift)
 - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift)
 - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift)
 - ArrowUp: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift)
 - ArrowDown: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift)
 - Cmd-ArrowUp (on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift)
 - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift)
 - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift)
 - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift)
 - PageUp: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift)
 - PageDown: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift)
 - Home: [`cursorLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryBackward) with Shift)
 - End: [`cursorLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryForward) with Shift)
 - Ctrl-Home (Cmd-Home on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift)
 - Ctrl-End (Cmd-Home on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift)
 - Enter and Shift-Enter: [`insertNewlineAndIndent`](https://codemirror.net/6/docs/ref/#commands.insertNewlineAndIndent)
 - Ctrl-a (Cmd-a on macOS): [`selectAll`](https://codemirror.net/6/docs/ref/#commands.selectAll)
 - Backspace: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward)
 - Delete: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward)
 - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward)
 - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward)
 - Cmd-Backspace (macOS): [`deleteLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.deleteLineBoundaryBackward).
 - Cmd-Delete (macOS): [`deleteLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.deleteLineBoundaryForward).
*/
const standardKeymap = /*@__PURE__*/[
    { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
    { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: true },
    { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: true },
    { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true },
    { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: true },
    { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: true },
    { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true },
    { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart },
    { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp },
    { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true },
    { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd },
    { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown },
    { key: "PageUp", run: cursorPageUp, shift: selectPageUp },
    { key: "PageDown", run: cursorPageDown, shift: selectPageDown },
    { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: true },
    { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart },
    { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: true },
    { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd },
    { key: "Enter", run: insertNewlineAndIndent, shift: insertNewlineAndIndent },
    { key: "Mod-a", run: selectAll },
    { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward, preventDefault: true },
    { key: "Delete", run: deleteCharForward, preventDefault: true },
    { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward, preventDefault: true },
    { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward, preventDefault: true },
    { mac: "Mod-Backspace", run: deleteLineBoundaryBackward, preventDefault: true },
    { mac: "Mod-Delete", run: deleteLineBoundaryForward, preventDefault: true }
].concat(/*@__PURE__*/emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift })));
/**
The default keymap. Includes all bindings from
[`standardKeymap`](https://codemirror.net/6/docs/ref/#commands.standardKeymap) plus the following:

- Alt-ArrowLeft (Ctrl-ArrowLeft on macOS): [`cursorSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxLeft) ([`selectSyntaxLeft`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxLeft) with Shift)
- Alt-ArrowRight (Ctrl-ArrowRight on macOS): [`cursorSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.cursorSyntaxRight) ([`selectSyntaxRight`](https://codemirror.net/6/docs/ref/#commands.selectSyntaxRight) with Shift)
- Alt-ArrowUp: [`moveLineUp`](https://codemirror.net/6/docs/ref/#commands.moveLineUp)
- Alt-ArrowDown: [`moveLineDown`](https://codemirror.net/6/docs/ref/#commands.moveLineDown)
- Shift-Alt-ArrowUp: [`copyLineUp`](https://codemirror.net/6/docs/ref/#commands.copyLineUp)
- Shift-Alt-ArrowDown: [`copyLineDown`](https://codemirror.net/6/docs/ref/#commands.copyLineDown)
- Ctrl-Alt-ArrowUp (Cmd-Alt-ArrowUp on macOS): [`addCursorAbove`](https://codemirror.net/6/docs/ref/#commands.addCursorAbove).
- Ctrl-Alt-ArrowDown (Cmd-Alt-ArrowDown on macOS): [`addCursorBelow`](https://codemirror.net/6/docs/ref/#commands.addCursorBelow).
- Escape: [`simplifySelection`](https://codemirror.net/6/docs/ref/#commands.simplifySelection)
- Ctrl-Enter (Cmd-Enter on macOS): [`insertBlankLine`](https://codemirror.net/6/docs/ref/#commands.insertBlankLine)
- Alt-l (Ctrl-l on macOS): [`selectLine`](https://codemirror.net/6/docs/ref/#commands.selectLine)
- Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](https://codemirror.net/6/docs/ref/#commands.selectParentSyntax)
- Ctrl-[ (Cmd-[ on macOS): [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess)
- Ctrl-] (Cmd-] on macOS): [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore)
- Ctrl-Alt-\\ (Cmd-Alt-\\ on macOS): [`indentSelection`](https://codemirror.net/6/docs/ref/#commands.indentSelection)
- Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](https://codemirror.net/6/docs/ref/#commands.deleteLine)
- Shift-Ctrl-\\ (Shift-Cmd-\\ on macOS): [`cursorMatchingBracket`](https://codemirror.net/6/docs/ref/#commands.cursorMatchingBracket)
- Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](https://codemirror.net/6/docs/ref/#commands.toggleComment).
- Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#commands.toggleBlockComment).
- Ctrl-m (Alt-Shift-m on macOS): [`toggleTabFocusMode`](https://codemirror.net/6/docs/ref/#commands.toggleTabFocusMode).
*/
const defaultKeymap = /*@__PURE__*/[
    { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft },
    { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight },
    { key: "Alt-ArrowUp", run: moveLineUp },
    { key: "Shift-Alt-ArrowUp", run: copyLineUp },
    { key: "Alt-ArrowDown", run: moveLineDown },
    { key: "Shift-Alt-ArrowDown", run: copyLineDown },
    { key: "Mod-Alt-ArrowUp", run: addCursorAbove },
    { key: "Mod-Alt-ArrowDown", run: addCursorBelow },
    { key: "Escape", run: simplifySelection },
    { key: "Mod-Enter", run: insertBlankLine },
    { key: "Alt-l", mac: "Ctrl-l", run: selectLine },
    { key: "Mod-i", run: selectParentSyntax, preventDefault: true },
    { key: "Mod-[", run: indentLess },
    { key: "Mod-]", run: indentMore },
    { key: "Mod-Alt-\\", run: indentSelection },
    { key: "Shift-Mod-k", run: deleteLine },
    { key: "Shift-Mod-\\", run: cursorMatchingBracket },
    { key: "Mod-/", run: toggleComment },
    { key: "Alt-A", run: toggleBlockComment },
    { key: "Ctrl-m", mac: "Shift-Alt-m", run: toggleTabFocusMode },
].concat(standardKeymap);
/**
A binding that binds Tab to [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) and
Shift-Tab to [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess).
Please see the [Tab example](../../examples/tab/) before using
this.
*/
const indentWithTab = { key: "Tab", run: indentMore, shift: indentLess };



;// ../../node_modules/@lezer/lr/dist/index.js


/**
A parse stack. These are used internally by the parser to track
parsing progress. They also provide some properties and methods
that external code such as a tokenizer can use to get information
about the parse state.
*/
class dist_Stack {
    /**
    @internal
    */
    constructor(
    /**
    The parse that this stack is part of @internal
    */
    p, 
    /**
    Holds state, input pos, buffer index triplets for all but the
    top state @internal
    */
    stack, 
    /**
    The current parse state @internal
    */
    state, 
    // The position at which the next reduce should take place. This
    // can be less than `this.pos` when skipped expressions have been
    // added to the stack (which should be moved outside of the next
    // reduction)
    /**
    @internal
    */
    reducePos, 
    /**
    The input position up to which this stack has parsed.
    */
    pos, 
    /**
    The dynamic score of the stack, including dynamic precedence
    and error-recovery penalties
    @internal
    */
    score, 
    // The output buffer. Holds (type, start, end, size) quads
    // representing nodes created by the parser, where `size` is
    // amount of buffer array entries covered by this node.
    /**
    @internal
    */
    buffer, 
    // The base offset of the buffer. When stacks are split, the split
    // instance shared the buffer history with its parent up to
    // `bufferBase`, which is the absolute offset (including the
    // offset of previous splits) into the buffer at which this stack
    // starts writing.
    /**
    @internal
    */
    bufferBase, 
    /**
    @internal
    */
    curContext, 
    /**
    @internal
    */
    lookAhead = 0, 
    // A parent stack from which this was split off, if any. This is
    // set up so that it always points to a stack that has some
    // additional buffer content, never to a stack with an equal
    // `bufferBase`.
    /**
    @internal
    */
    parent) {
        this.p = p;
        this.stack = stack;
        this.state = state;
        this.reducePos = reducePos;
        this.pos = pos;
        this.score = score;
        this.buffer = buffer;
        this.bufferBase = bufferBase;
        this.curContext = curContext;
        this.lookAhead = lookAhead;
        this.parent = parent;
    }
    /**
    @internal
    */
    toString() {
        return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
    }
    // Start an empty stack
    /**
    @internal
    */
    static start(p, state, pos = 0) {
        let cx = p.parser.context;
        return new dist_Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);
    }
    /**
    The stack's current [context](#lr.ContextTracker) value, if
    any. Its type will depend on the context tracker's type
    parameter, or it will be `null` if there is no context
    tracker.
    */
    get context() { return this.curContext ? this.curContext.context : null; }
    // Push a state onto the stack, tracking its start position as well
    // as the buffer base at that point.
    /**
    @internal
    */
    pushState(state, start) {
        this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
        this.state = state;
    }
    // Apply a reduce action
    /**
    @internal
    */
    reduce(action) {
        var _a;
        let depth = action >> 19 /* Action.ReduceDepthShift */, type = action & 65535 /* Action.ValueMask */;
        let { parser } = this.p;
        let lookaheadRecord = this.reducePos < this.pos - 25 /* Lookahead.Margin */ && this.setLookAhead(this.pos);
        let dPrec = parser.dynamicPrecedence(type);
        if (dPrec)
            this.score += dPrec;
        if (depth == 0) {
            this.pushState(parser.getGoto(this.state, type, true), this.reducePos);
            // Zero-depth reductions are a special case—they add stuff to
            // the stack without popping anything off.
            if (type < parser.minRepeatTerm)
                this.storeNode(type, this.reducePos, this.reducePos, lookaheadRecord ? 8 : 4, true);
            this.reduceContext(type, this.reducePos);
            return;
        }
        // Find the base index into `this.stack`, content after which will
        // be dropped. Note that with `StayFlag` reductions we need to
        // consume two extra frames (the dummy parent node for the skipped
        // expression and the state that we'll be staying in, which should
        // be moved to `this.state`).
        let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* Action.StayFlag */ ? 6 : 0);
        let start = base ? this.stack[base - 2] : this.p.ranges[0].from, size = this.reducePos - start;
        // This is a kludge to try and detect overly deep left-associative
        // trees, which will not increase the parse stack depth and thus
        // won't be caught by the regular stack-depth limit check.
        if (size >= 2000 /* Recover.MinBigReduction */ && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {
            if (start == this.p.lastBigReductionStart) {
                this.p.bigReductionCount++;
                this.p.lastBigReductionSize = size;
            }
            else if (this.p.lastBigReductionSize < size) {
                this.p.bigReductionCount = 1;
                this.p.lastBigReductionStart = start;
                this.p.lastBigReductionSize = size;
            }
        }
        let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;
        // Store normal terms or `R -> R R` repeat reductions
        if (type < parser.minRepeatTerm || (action & 131072 /* Action.RepeatFlag */)) {
            let pos = parser.stateFlag(this.state, 1 /* StateFlag.Skipped */) ? this.pos : this.reducePos;
            this.storeNode(type, start, pos, count + 4, true);
        }
        if (action & 262144 /* Action.StayFlag */) {
            this.state = this.stack[base];
        }
        else {
            let baseStateID = this.stack[base - 3];
            this.state = parser.getGoto(baseStateID, type, true);
        }
        while (this.stack.length > base)
            this.stack.pop();
        this.reduceContext(type, start);
    }
    // Shift a value into the buffer
    /**
    @internal
    */
    storeNode(term, start, end, size = 4, mustSink = false) {
        if (term == 0 /* Term.Err */ &&
            (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
            // Try to omit/merge adjacent error nodes
            let cur = this, top = this.buffer.length;
            if (top == 0 && cur.parent) {
                top = cur.bufferBase - cur.parent.bufferBase;
                cur = cur.parent;
            }
            if (top > 0 && cur.buffer[top - 4] == 0 /* Term.Err */ && cur.buffer[top - 1] > -1) {
                if (start == end)
                    return;
                if (cur.buffer[top - 2] >= start) {
                    cur.buffer[top - 2] = end;
                    return;
                }
            }
        }
        if (!mustSink || this.pos == end) { // Simple case, just append
            this.buffer.push(term, start, end, size);
        }
        else { // There may be skipped nodes that have to be moved forward
            let index = this.buffer.length;
            if (index > 0 && (this.buffer[index - 4] != 0 /* Term.Err */ || this.buffer[index - 1] < 0)) {
                let mustMove = false;
                for (let scan = index; scan > 0 && this.buffer[scan - 2] > end; scan -= 4) {
                    if (this.buffer[scan - 1] >= 0) {
                        mustMove = true;
                        break;
                    }
                }
                if (mustMove)
                    while (index > 0 && this.buffer[index - 2] > end) {
                        // Move this record forward
                        this.buffer[index] = this.buffer[index - 4];
                        this.buffer[index + 1] = this.buffer[index - 3];
                        this.buffer[index + 2] = this.buffer[index - 2];
                        this.buffer[index + 3] = this.buffer[index - 1];
                        index -= 4;
                        if (size > 4)
                            size -= 4;
                    }
            }
            this.buffer[index] = term;
            this.buffer[index + 1] = start;
            this.buffer[index + 2] = end;
            this.buffer[index + 3] = size;
        }
    }
    // Apply a shift action
    /**
    @internal
    */
    shift(action, type, start, end) {
        if (action & 131072 /* Action.GotoFlag */) {
            this.pushState(action & 65535 /* Action.ValueMask */, this.pos);
        }
        else if ((action & 262144 /* Action.StayFlag */) == 0) { // Regular shift
            let nextState = action, { parser } = this.p;
            this.pos = end;
            // Skipped or zero-length non-tree tokens don't move reducePos
            if (!parser.stateFlag(nextState, 1 /* StateFlag.Skipped */) && (end > start || type <= parser.maxNode))
                this.reducePos = end;
            this.pushState(nextState, Math.min(start, this.reducePos));
            this.shiftContext(type, start);
            if (type <= parser.maxNode)
                this.buffer.push(type, start, end, 4);
        }
        else { // Shift-and-stay, which means this is a skipped token
            this.pos = end;
            this.shiftContext(type, start);
            if (type <= this.p.parser.maxNode)
                this.buffer.push(type, start, end, 4);
        }
    }
    // Apply an action
    /**
    @internal
    */
    apply(action, next, nextStart, nextEnd) {
        if (action & 65536 /* Action.ReduceFlag */)
            this.reduce(action);
        else
            this.shift(action, next, nextStart, nextEnd);
    }
    // Add a prebuilt (reused) node into the buffer.
    /**
    @internal
    */
    useNode(value, next) {
        let index = this.p.reused.length - 1;
        if (index < 0 || this.p.reused[index] != value) {
            this.p.reused.push(value);
            index++;
        }
        let start = this.pos;
        this.reducePos = this.pos = start + value.length;
        this.pushState(next, start);
        this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */);
        if (this.curContext)
            this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
    }
    // Split the stack. Due to the buffer sharing and the fact
    // that `this.stack` tends to stay quite shallow, this isn't very
    // expensive.
    /**
    @internal
    */
    split() {
        let parent = this;
        let off = parent.buffer.length;
        // Because the top of the buffer (after this.pos) may be mutated
        // to reorder reductions and skipped tokens, and shared buffers
        // should be immutable, this copies any outstanding skipped tokens
        // to the new buffer, and puts the base pointer before them.
        while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
            off -= 4;
        let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;
        // Make sure parent points to an actual parent with content, if there is such a parent.
        while (parent && base == parent.bufferBase)
            parent = parent.parent;
        return new dist_Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);
    }
    // Try to recover from an error by 'deleting' (ignoring) one token.
    /**
    @internal
    */
    recoverByDelete(next, nextEnd) {
        let isNode = next <= this.p.parser.maxNode;
        if (isNode)
            this.storeNode(next, this.pos, nextEnd, 4);
        this.storeNode(0 /* Term.Err */, this.pos, nextEnd, isNode ? 8 : 4);
        this.pos = this.reducePos = nextEnd;
        this.score -= 190 /* Recover.Delete */;
    }
    /**
    Check if the given term would be able to be shifted (optionally
    after some reductions) on this stack. This can be useful for
    external tokenizers that want to make sure they only provide a
    given token when it applies.
    */
    canShift(term) {
        for (let sim = new SimulatedStack(this);;) {
            let action = this.p.parser.stateSlot(sim.state, 4 /* ParseState.DefaultReduce */) || this.p.parser.hasAction(sim.state, term);
            if (action == 0)
                return false;
            if ((action & 65536 /* Action.ReduceFlag */) == 0)
                return true;
            sim.reduce(action);
        }
    }
    // Apply up to Recover.MaxNext recovery actions that conceptually
    // inserts some missing token or rule.
    /**
    @internal
    */
    recoverByInsert(next) {
        if (this.stack.length >= 300 /* Recover.MaxInsertStackDepth */)
            return [];
        let nextStates = this.p.parser.nextStates(this.state);
        if (nextStates.length > 4 /* Recover.MaxNext */ << 1 || this.stack.length >= 120 /* Recover.DampenInsertStackDepth */) {
            let best = [];
            for (let i = 0, s; i < nextStates.length; i += 2) {
                if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))
                    best.push(nextStates[i], s);
            }
            if (this.stack.length < 120 /* Recover.DampenInsertStackDepth */)
                for (let i = 0; best.length < 4 /* Recover.MaxNext */ << 1 && i < nextStates.length; i += 2) {
                    let s = nextStates[i + 1];
                    if (!best.some((v, i) => (i & 1) && v == s))
                        best.push(nextStates[i], s);
                }
            nextStates = best;
        }
        let result = [];
        for (let i = 0; i < nextStates.length && result.length < 4 /* Recover.MaxNext */; i += 2) {
            let s = nextStates[i + 1];
            if (s == this.state)
                continue;
            let stack = this.split();
            stack.pushState(s, this.pos);
            stack.storeNode(0 /* Term.Err */, stack.pos, stack.pos, 4, true);
            stack.shiftContext(nextStates[i], this.pos);
            stack.reducePos = this.pos;
            stack.score -= 200 /* Recover.Insert */;
            result.push(stack);
        }
        return result;
    }
    // Force a reduce, if possible. Return false if that can't
    // be done.
    /**
    @internal
    */
    forceReduce() {
        let { parser } = this.p;
        let reduce = parser.stateSlot(this.state, 5 /* ParseState.ForcedReduce */);
        if ((reduce & 65536 /* Action.ReduceFlag */) == 0)
            return false;
        if (!parser.validAction(this.state, reduce)) {
            let depth = reduce >> 19 /* Action.ReduceDepthShift */, term = reduce & 65535 /* Action.ValueMask */;
            let target = this.stack.length - depth * 3;
            if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) {
                let backup = this.findForcedReduction();
                if (backup == null)
                    return false;
                reduce = backup;
            }
            this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
            this.score -= 100 /* Recover.Reduce */;
        }
        this.reducePos = this.pos;
        this.reduce(reduce);
        return true;
    }
    /**
    Try to scan through the automaton to find some kind of reduction
    that can be applied. Used when the regular ForcedReduce field
    isn't a valid action. @internal
    */
    findForcedReduction() {
        let { parser } = this.p, seen = [];
        let explore = (state, depth) => {
            if (seen.includes(state))
                return;
            seen.push(state);
            return parser.allActions(state, (action) => {
                if (action & (262144 /* Action.StayFlag */ | 131072 /* Action.GotoFlag */)) ;
                else if (action & 65536 /* Action.ReduceFlag */) {
                    let rDepth = (action >> 19 /* Action.ReduceDepthShift */) - depth;
                    if (rDepth > 1) {
                        let term = action & 65535 /* Action.ValueMask */, target = this.stack.length - rDepth * 3;
                        if (target >= 0 && parser.getGoto(this.stack[target], term, false) >= 0)
                            return (rDepth << 19 /* Action.ReduceDepthShift */) | 65536 /* Action.ReduceFlag */ | term;
                    }
                }
                else {
                    let found = explore(action, depth + 1);
                    if (found != null)
                        return found;
                }
            });
        };
        return explore(this.state, 0);
    }
    /**
    @internal
    */
    forceAll() {
        while (!this.p.parser.stateFlag(this.state, 2 /* StateFlag.Accepting */)) {
            if (!this.forceReduce()) {
                this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
                break;
            }
        }
        return this;
    }
    /**
    Check whether this state has no further actions (assumed to be a direct descendant of the
    top state, since any other states must be able to continue
    somehow). @internal
    */
    get deadEnd() {
        if (this.stack.length != 3)
            return false;
        let { parser } = this.p;
        return parser.data[parser.stateSlot(this.state, 1 /* ParseState.Actions */)] == 65535 /* Seq.End */ &&
            !parser.stateSlot(this.state, 4 /* ParseState.DefaultReduce */);
    }
    /**
    Restart the stack (put it back in its start state). Only safe
    when this.stack.length == 3 (state is directly below the top
    state). @internal
    */
    restart() {
        this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
        this.state = this.stack[0];
        this.stack.length = 0;
    }
    /**
    @internal
    */
    sameState(other) {
        if (this.state != other.state || this.stack.length != other.stack.length)
            return false;
        for (let i = 0; i < this.stack.length; i += 3)
            if (this.stack[i] != other.stack[i])
                return false;
        return true;
    }
    /**
    Get the parser used by this stack.
    */
    get parser() { return this.p.parser; }
    /**
    Test whether a given dialect (by numeric ID, as exported from
    the terms file) is enabled.
    */
    dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; }
    shiftContext(term, start) {
        if (this.curContext)
            this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
    }
    reduceContext(term, start) {
        if (this.curContext)
            this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
    }
    /**
    @internal
    */
    emitContext() {
        let last = this.buffer.length - 1;
        if (last < 0 || this.buffer[last] != -3)
            this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);
    }
    /**
    @internal
    */
    emitLookAhead() {
        let last = this.buffer.length - 1;
        if (last < 0 || this.buffer[last] != -4)
            this.buffer.push(this.lookAhead, this.pos, this.pos, -4);
    }
    updateContext(context) {
        if (context != this.curContext.context) {
            let newCx = new StackContext(this.curContext.tracker, context);
            if (newCx.hash != this.curContext.hash)
                this.emitContext();
            this.curContext = newCx;
        }
    }
    /**
    @internal
    */
    setLookAhead(lookAhead) {
        if (lookAhead <= this.lookAhead)
            return false;
        this.emitLookAhead();
        this.lookAhead = lookAhead;
        return true;
    }
    /**
    @internal
    */
    close() {
        if (this.curContext && this.curContext.tracker.strict)
            this.emitContext();
        if (this.lookAhead > 0)
            this.emitLookAhead();
    }
}
class StackContext {
    constructor(tracker, context) {
        this.tracker = tracker;
        this.context = context;
        this.hash = tracker.strict ? tracker.hash(context) : 0;
    }
}
// Used to cheaply run some reductions to scan ahead without mutating
// an entire stack
class SimulatedStack {
    constructor(start) {
        this.start = start;
        this.state = start.state;
        this.stack = start.stack;
        this.base = this.stack.length;
    }
    reduce(action) {
        let term = action & 65535 /* Action.ValueMask */, depth = action >> 19 /* Action.ReduceDepthShift */;
        if (depth == 0) {
            if (this.stack == this.start.stack)
                this.stack = this.stack.slice();
            this.stack.push(this.state, 0, 0);
            this.base += 3;
        }
        else {
            this.base -= (depth - 1) * 3;
        }
        let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
        this.state = goto;
    }
}
// This is given to `Tree.build` to build a buffer, and encapsulates
// the parent-stack-walking necessary to read the nodes.
class StackBufferCursor {
    constructor(stack, pos, index) {
        this.stack = stack;
        this.pos = pos;
        this.index = index;
        this.buffer = stack.buffer;
        if (this.index == 0)
            this.maybeNext();
    }
    static create(stack, pos = stack.bufferBase + stack.buffer.length) {
        return new StackBufferCursor(stack, pos, pos - stack.bufferBase);
    }
    maybeNext() {
        let next = this.stack.parent;
        if (next != null) {
            this.index = this.stack.bufferBase - next.bufferBase;
            this.stack = next;
            this.buffer = next.buffer;
        }
    }
    get id() { return this.buffer[this.index - 4]; }
    get start() { return this.buffer[this.index - 3]; }
    get end() { return this.buffer[this.index - 2]; }
    get size() { return this.buffer[this.index - 1]; }
    next() {
        this.index -= 4;
        this.pos -= 4;
        if (this.index == 0)
            this.maybeNext();
    }
    fork() {
        return new StackBufferCursor(this.stack, this.pos, this.index);
    }
}

// See lezer-generator/src/encode.ts for comments about the encoding
// used here
function decodeArray(input, Type = Uint16Array) {
    if (typeof input != "string")
        return input;
    let array = null;
    for (let pos = 0, out = 0; pos < input.length;) {
        let value = 0;
        for (;;) {
            let next = input.charCodeAt(pos++), stop = false;
            if (next == 126 /* Encode.BigValCode */) {
                value = 65535 /* Encode.BigVal */;
                break;
            }
            if (next >= 92 /* Encode.Gap2 */)
                next--;
            if (next >= 34 /* Encode.Gap1 */)
                next--;
            let digit = next - 32 /* Encode.Start */;
            if (digit >= 46 /* Encode.Base */) {
                digit -= 46 /* Encode.Base */;
                stop = true;
            }
            value += digit;
            if (stop)
                break;
            value *= 46 /* Encode.Base */;
        }
        if (array)
            array[out++] = value;
        else
            array = new Type(value);
    }
    return array;
}

class CachedToken {
    constructor() {
        this.start = -1;
        this.value = -1;
        this.end = -1;
        this.extended = -1;
        this.lookAhead = 0;
        this.mask = 0;
        this.context = 0;
    }
}
const nullToken = new CachedToken;
/**
[Tokenizers](#lr.ExternalTokenizer) interact with the input
through this interface. It presents the input as a stream of
characters, tracking lookahead and hiding the complexity of
[ranges](#common.Parser.parse^ranges) from tokenizer code.
*/
class InputStream {
    /**
    @internal
    */
    constructor(
    /**
    @internal
    */
    input, 
    /**
    @internal
    */
    ranges) {
        this.input = input;
        this.ranges = ranges;
        /**
        @internal
        */
        this.chunk = "";
        /**
        @internal
        */
        this.chunkOff = 0;
        /**
        Backup chunk
        */
        this.chunk2 = "";
        this.chunk2Pos = 0;
        /**
        The character code of the next code unit in the input, or -1
        when the stream is at the end of the input.
        */
        this.next = -1;
        /**
        @internal
        */
        this.token = nullToken;
        this.rangeIndex = 0;
        this.pos = this.chunkPos = ranges[0].from;
        this.range = ranges[0];
        this.end = ranges[ranges.length - 1].to;
        this.readNext();
    }
    /**
    @internal
    */
    resolveOffset(offset, assoc) {
        let range = this.range, index = this.rangeIndex;
        let pos = this.pos + offset;
        while (pos < range.from) {
            if (!index)
                return null;
            let next = this.ranges[--index];
            pos -= range.from - next.to;
            range = next;
        }
        while (assoc < 0 ? pos > range.to : pos >= range.to) {
            if (index == this.ranges.length - 1)
                return null;
            let next = this.ranges[++index];
            pos += next.from - range.to;
            range = next;
        }
        return pos;
    }
    /**
    @internal
    */
    clipPos(pos) {
        if (pos >= this.range.from && pos < this.range.to)
            return pos;
        for (let range of this.ranges)
            if (range.to > pos)
                return Math.max(pos, range.from);
        return this.end;
    }
    /**
    Look at a code unit near the stream position. `.peek(0)` equals
    `.next`, `.peek(-1)` gives you the previous character, and so
    on.
    
    Note that looking around during tokenizing creates dependencies
    on potentially far-away content, which may reduce the
    effectiveness incremental parsing—when looking forward—or even
    cause invalid reparses when looking backward more than 25 code
    units, since the library does not track lookbehind.
    */
    peek(offset) {
        let idx = this.chunkOff + offset, pos, result;
        if (idx >= 0 && idx < this.chunk.length) {
            pos = this.pos + offset;
            result = this.chunk.charCodeAt(idx);
        }
        else {
            let resolved = this.resolveOffset(offset, 1);
            if (resolved == null)
                return -1;
            pos = resolved;
            if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
                result = this.chunk2.charCodeAt(pos - this.chunk2Pos);
            }
            else {
                let i = this.rangeIndex, range = this.range;
                while (range.to <= pos)
                    range = this.ranges[++i];
                this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
                if (pos + this.chunk2.length > range.to)
                    this.chunk2 = this.chunk2.slice(0, range.to - pos);
                result = this.chunk2.charCodeAt(0);
            }
        }
        if (pos >= this.token.lookAhead)
            this.token.lookAhead = pos + 1;
        return result;
    }
    /**
    Accept a token. By default, the end of the token is set to the
    current stream position, but you can pass an offset (relative to
    the stream position) to change that.
    */
    acceptToken(token, endOffset = 0) {
        let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
        if (end == null || end < this.token.start)
            throw new RangeError("Token end out of bounds");
        this.token.value = token;
        this.token.end = end;
    }
    /**
    Accept a token ending at a specific given position.
    */
    acceptTokenTo(token, endPos) {
        this.token.value = token;
        this.token.end = endPos;
    }
    getChunk() {
        if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
            let { chunk, chunkPos } = this;
            this.chunk = this.chunk2;
            this.chunkPos = this.chunk2Pos;
            this.chunk2 = chunk;
            this.chunk2Pos = chunkPos;
            this.chunkOff = this.pos - this.chunkPos;
        }
        else {
            this.chunk2 = this.chunk;
            this.chunk2Pos = this.chunkPos;
            let nextChunk = this.input.chunk(this.pos);
            let end = this.pos + nextChunk.length;
            this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
            this.chunkPos = this.pos;
            this.chunkOff = 0;
        }
    }
    readNext() {
        if (this.chunkOff >= this.chunk.length) {
            this.getChunk();
            if (this.chunkOff == this.chunk.length)
                return this.next = -1;
        }
        return this.next = this.chunk.charCodeAt(this.chunkOff);
    }
    /**
    Move the stream forward N (defaults to 1) code units. Returns
    the new value of [`next`](#lr.InputStream.next).
    */
    advance(n = 1) {
        this.chunkOff += n;
        while (this.pos + n >= this.range.to) {
            if (this.rangeIndex == this.ranges.length - 1)
                return this.setDone();
            n -= this.range.to - this.pos;
            this.range = this.ranges[++this.rangeIndex];
            this.pos = this.range.from;
        }
        this.pos += n;
        if (this.pos >= this.token.lookAhead)
            this.token.lookAhead = this.pos + 1;
        return this.readNext();
    }
    setDone() {
        this.pos = this.chunkPos = this.end;
        this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
        this.chunk = "";
        return this.next = -1;
    }
    /**
    @internal
    */
    reset(pos, token) {
        if (token) {
            this.token = token;
            token.start = pos;
            token.lookAhead = pos + 1;
            token.value = token.extended = -1;
        }
        else {
            this.token = nullToken;
        }
        if (this.pos != pos) {
            this.pos = pos;
            if (pos == this.end) {
                this.setDone();
                return this;
            }
            while (pos < this.range.from)
                this.range = this.ranges[--this.rangeIndex];
            while (pos >= this.range.to)
                this.range = this.ranges[++this.rangeIndex];
            if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
                this.chunkOff = pos - this.chunkPos;
            }
            else {
                this.chunk = "";
                this.chunkOff = 0;
            }
            this.readNext();
        }
        return this;
    }
    /**
    @internal
    */
    read(from, to) {
        if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
            return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
        if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
            return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
        if (from >= this.range.from && to <= this.range.to)
            return this.input.read(from, to);
        let result = "";
        for (let r of this.ranges) {
            if (r.from >= to)
                break;
            if (r.to > from)
                result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));
        }
        return result;
    }
}
/**
@internal
*/
class TokenGroup {
    constructor(data, id) {
        this.data = data;
        this.id = id;
    }
    token(input, stack) {
        let { parser } = stack.p;
        dist_readToken(this.data, input, stack, this.id, parser.data, parser.tokenPrecTable);
    }
}
TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
/**
@hide
*/
class LocalTokenGroup {
    constructor(data, precTable, elseToken) {
        this.precTable = precTable;
        this.elseToken = elseToken;
        this.data = typeof data == "string" ? decodeArray(data) : data;
    }
    token(input, stack) {
        let start = input.pos, skipped = 0;
        for (;;) {
            let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
            dist_readToken(this.data, input, stack, 0, this.data, this.precTable);
            if (input.token.value > -1)
                break;
            if (this.elseToken == null)
                return;
            if (!atEof)
                skipped++;
            if (nextPos == null)
                break;
            input.reset(nextPos, input.token);
        }
        if (skipped) {
            input.reset(start, input.token);
            input.acceptToken(this.elseToken, skipped);
        }
    }
}
LocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
/**
`@external tokens` declarations in the grammar should resolve to
an instance of this class.
*/
class ExternalTokenizer {
    /**
    Create a tokenizer. The first argument is the function that,
    given an input stream, scans for the types of tokens it
    recognizes at the stream's position, and calls
    [`acceptToken`](#lr.InputStream.acceptToken) when it finds
    one.
    */
    constructor(
    /**
    @internal
    */
    token, options = {}) {
        this.token = token;
        this.contextual = !!options.contextual;
        this.fallback = !!options.fallback;
        this.extend = !!options.extend;
    }
}
// Tokenizer data is stored a big uint16 array containing, for each
// state:
//
//  - A group bitmask, indicating what token groups are reachable from
//    this state, so that paths that can only lead to tokens not in
//    any of the current groups can be cut off early.
//
//  - The position of the end of the state's sequence of accepting
//    tokens
//
//  - The number of outgoing edges for the state
//
//  - The accepting tokens, as (token id, group mask) pairs
//
//  - The outgoing edges, as (start character, end character, state
//    index) triples, with end character being exclusive
//
// This function interprets that data, running through a stream as
// long as new states with the a matching group mask can be reached,
// and updating `input.token` when it matches a token.
function dist_readToken(data, input, stack, group, precTable, precOffset) {
    let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
    scan: for (;;) {
        if ((groupMask & data[state]) == 0)
            break;
        let accEnd = data[state + 1];
        // Check whether this state can lead to a token in the current group
        // Accept tokens in this state, possibly overwriting
        // lower-precedence / shorter tokens
        for (let i = state + 3; i < accEnd; i += 2)
            if ((data[i + 1] & groupMask) > 0) {
                let term = data[i];
                if (dialect.allows(term) &&
                    (input.token.value == -1 || input.token.value == term ||
                        overrides(term, input.token.value, precTable, precOffset))) {
                    input.acceptToken(term);
                    break;
                }
            }
        let next = input.next, low = 0, high = data[state + 2];
        // Special case for EOF
        if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 /* Seq.End */) {
            state = data[accEnd + high * 3 - 1];
            continue scan;
        }
        // Do a binary search on the state's edges
        for (; low < high;) {
            let mid = (low + high) >> 1;
            let index = accEnd + mid + (mid << 1);
            let from = data[index], to = data[index + 1] || 0x10000;
            if (next < from)
                high = mid;
            else if (next >= to)
                low = mid + 1;
            else {
                state = data[index + 2];
                input.advance();
                continue scan;
            }
        }
        break;
    }
}
function findOffset(data, start, term) {
    for (let i = start, next; (next = data[i]) != 65535 /* Seq.End */; i++)
        if (next == term)
            return i - start;
    return -1;
}
function overrides(token, prev, tableData, tableOffset) {
    let iPrev = findOffset(tableData, tableOffset, prev);
    return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
}

// Environment variable used to control console output
const verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG);
let stackIDs = null;
function cutAt(tree, pos, side) {
    let cursor = tree.cursor(IterMode.IncludeAnonymous);
    cursor.moveTo(pos);
    for (;;) {
        if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
            for (;;) {
                if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)
                    return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Lookahead.Margin */))
                        : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Lookahead.Margin */));
                if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
                    break;
                if (!cursor.parent())
                    return side < 0 ? 0 : tree.length;
            }
    }
}
class dist_FragmentCursor {
    constructor(fragments, nodeSet) {
        this.fragments = fragments;
        this.nodeSet = nodeSet;
        this.i = 0;
        this.fragment = null;
        this.safeFrom = -1;
        this.safeTo = -1;
        this.trees = [];
        this.start = [];
        this.index = [];
        this.nextFragment();
    }
    nextFragment() {
        let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
        if (fr) {
            this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
            this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
            while (this.trees.length) {
                this.trees.pop();
                this.start.pop();
                this.index.pop();
            }
            this.trees.push(fr.tree);
            this.start.push(-fr.offset);
            this.index.push(0);
            this.nextStart = this.safeFrom;
        }
        else {
            this.nextStart = 1e9;
        }
    }
    // `pos` must be >= any previously given `pos` for this cursor
    nodeAt(pos) {
        if (pos < this.nextStart)
            return null;
        while (this.fragment && this.safeTo <= pos)
            this.nextFragment();
        if (!this.fragment)
            return null;
        for (;;) {
            let last = this.trees.length - 1;
            if (last < 0) { // End of tree
                this.nextFragment();
                return null;
            }
            let top = this.trees[last], index = this.index[last];
            if (index == top.children.length) {
                this.trees.pop();
                this.start.pop();
                this.index.pop();
                continue;
            }
            let next = top.children[index];
            let start = this.start[last] + top.positions[index];
            if (start > pos) {
                this.nextStart = start;
                return null;
            }
            if (next instanceof Tree) {
                if (start == pos) {
                    if (start < this.safeFrom)
                        return null;
                    let end = start + next.length;
                    if (end <= this.safeTo) {
                        let lookAhead = next.prop(NodeProp.lookAhead);
                        if (!lookAhead || end + lookAhead < this.fragment.to)
                            return next;
                    }
                }
                this.index[last]++;
                if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node
                    this.trees.push(next);
                    this.start.push(start);
                    this.index.push(0);
                }
            }
            else {
                this.index[last]++;
                this.nextStart = start + next.length;
            }
        }
    }
}
class TokenCache {
    constructor(parser, stream) {
        this.stream = stream;
        this.tokens = [];
        this.mainToken = null;
        this.actions = [];
        this.tokens = parser.tokenizers.map(_ => new CachedToken);
    }
    getActions(stack) {
        let actionIndex = 0;
        let main = null;
        let { parser } = stack.p, { tokenizers } = parser;
        let mask = parser.stateSlot(stack.state, 3 /* ParseState.TokenizerMask */);
        let context = stack.curContext ? stack.curContext.hash : 0;
        let lookAhead = 0;
        for (let i = 0; i < tokenizers.length; i++) {
            if (((1 << i) & mask) == 0)
                continue;
            let tokenizer = tokenizers[i], token = this.tokens[i];
            if (main && !tokenizer.fallback)
                continue;
            if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
                this.updateCachedToken(token, tokenizer, stack);
                token.mask = mask;
                token.context = context;
            }
            if (token.lookAhead > token.end + 25 /* Lookahead.Margin */)
                lookAhead = Math.max(token.lookAhead, lookAhead);
            if (token.value != 0 /* Term.Err */) {
                let startIndex = actionIndex;
                if (token.extended > -1)
                    actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
                actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
                if (!tokenizer.extend) {
                    main = token;
                    if (actionIndex > startIndex)
                        break;
                }
            }
        }
        while (this.actions.length > actionIndex)
            this.actions.pop();
        if (lookAhead)
            stack.setLookAhead(lookAhead);
        if (!main && stack.pos == this.stream.end) {
            main = new CachedToken;
            main.value = stack.p.parser.eofTerm;
            main.start = main.end = stack.pos;
            actionIndex = this.addActions(stack, main.value, main.end, actionIndex);
        }
        this.mainToken = main;
        return this.actions;
    }
    getMainToken(stack) {
        if (this.mainToken)
            return this.mainToken;
        let main = new CachedToken, { pos, p } = stack;
        main.start = pos;
        main.end = Math.min(pos + 1, p.stream.end);
        main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Term.Err */;
        return main;
    }
    updateCachedToken(token, tokenizer, stack) {
        let start = this.stream.clipPos(stack.pos);
        tokenizer.token(this.stream.reset(start, token), stack);
        if (token.value > -1) {
            let { parser } = stack.p;
            for (let i = 0; i < parser.specialized.length; i++)
                if (parser.specialized[i] == token.value) {
                    let result = parser.specializers[i](this.stream.read(token.start, token.end), stack);
                    if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {
                        if ((result & 1) == 0 /* Specialize.Specialize */)
                            token.value = result >> 1;
                        else
                            token.extended = result >> 1;
                        break;
                    }
                }
        }
        else {
            token.value = 0 /* Term.Err */;
            token.end = this.stream.clipPos(start + 1);
        }
    }
    putAction(action, token, end, index) {
        // Don't add duplicate actions
        for (let i = 0; i < index; i += 3)
            if (this.actions[i] == action)
                return index;
        this.actions[index++] = action;
        this.actions[index++] = token;
        this.actions[index++] = end;
        return index;
    }
    addActions(stack, token, end, index) {
        let { state } = stack, { parser } = stack.p, { data } = parser;
        for (let set = 0; set < 2; set++) {
            for (let i = parser.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */);; i += 3) {
                if (data[i] == 65535 /* Seq.End */) {
                    if (data[i + 1] == 1 /* Seq.Next */) {
                        i = pair(data, i + 2);
                    }
                    else {
                        if (index == 0 && data[i + 1] == 2 /* Seq.Other */)
                            index = this.putAction(pair(data, i + 2), token, end, index);
                        break;
                    }
                }
                if (data[i] == token)
                    index = this.putAction(pair(data, i + 1), token, end, index);
            }
        }
        return index;
    }
}
class dist_Parse {
    constructor(parser, input, fragments, ranges) {
        this.parser = parser;
        this.input = input;
        this.ranges = ranges;
        this.recovering = 0;
        this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
        this.minStackPos = 0;
        this.reused = [];
        this.stoppedAt = null;
        this.lastBigReductionStart = -1;
        this.lastBigReductionSize = 0;
        this.bigReductionCount = 0;
        this.stream = new InputStream(input, ranges);
        this.tokens = new TokenCache(parser, this.stream);
        this.topTerm = parser.top[1];
        let { from } = ranges[0];
        this.stacks = [dist_Stack.start(this, parser.top[0], from)];
        this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4
            ? new dist_FragmentCursor(fragments, parser.nodeSet) : null;
    }
    get parsedPos() {
        return this.minStackPos;
    }
    // Move the parser forward. This will process all parse stacks at
    // `this.pos` and try to advance them to a further position. If no
    // stack for such a position is found, it'll start error-recovery.
    //
    // When the parse is finished, this will return a syntax tree. When
    // not, it returns `null`.
    advance() {
        let stacks = this.stacks, pos = this.minStackPos;
        // This will hold stacks beyond `pos`.
        let newStacks = this.stacks = [];
        let stopped, stoppedTokens;
        // If a large amount of reductions happened with the same start
        // position, force the stack out of that production in order to
        // avoid creating a tree too deep to recurse through.
        // (This is an ugly kludge, because unfortunately there is no
        // straightforward, cheap way to check for this happening, due to
        // the history of reductions only being available in an
        // expensive-to-access format in the stack buffers.)
        if (this.bigReductionCount > 300 /* Rec.MaxLeftAssociativeReductionCount */ && stacks.length == 1) {
            let [s] = stacks;
            while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) { }
            this.bigReductionCount = this.lastBigReductionSize = 0;
        }
        // Keep advancing any stacks at `pos` until they either move
        // forward or can't be advanced. Gather stacks that can't be
        // advanced further in `stopped`.
        for (let i = 0; i < stacks.length; i++) {
            let stack = stacks[i];
            for (;;) {
                this.tokens.mainToken = null;
                if (stack.pos > pos) {
                    newStacks.push(stack);
                }
                else if (this.advanceStack(stack, newStacks, stacks)) {
                    continue;
                }
                else {
                    if (!stopped) {
                        stopped = [];
                        stoppedTokens = [];
                    }
                    stopped.push(stack);
                    let tok = this.tokens.getMainToken(stack);
                    stoppedTokens.push(tok.value, tok.end);
                }
                break;
            }
        }
        if (!newStacks.length) {
            let finished = stopped && findFinished(stopped);
            if (finished) {
                if (verbose)
                    console.log("Finish with " + this.stackID(finished));
                return this.stackToTree(finished);
            }
            if (this.parser.strict) {
                if (verbose && stopped)
                    console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
                throw new SyntaxError("No parse at " + pos);
            }
            if (!this.recovering)
                this.recovering = 5 /* Rec.Distance */;
        }
        if (this.recovering && stopped) {
            let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0]
                : this.runRecovery(stopped, stoppedTokens, newStacks);
            if (finished) {
                if (verbose)
                    console.log("Force-finish " + this.stackID(finished));
                return this.stackToTree(finished.forceAll());
            }
        }
        if (this.recovering) {
            let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* Rec.MaxRemainingPerStep */;
            if (newStacks.length > maxRemaining) {
                newStacks.sort((a, b) => b.score - a.score);
                while (newStacks.length > maxRemaining)
                    newStacks.pop();
            }
            if (newStacks.some(s => s.reducePos > pos))
                this.recovering--;
        }
        else if (newStacks.length > 1) {
            // Prune stacks that are in the same state, or that have been
            // running without splitting for a while, to avoid getting stuck
            // with multiple successful stacks running endlessly on.
            outer: for (let i = 0; i < newStacks.length - 1; i++) {
                let stack = newStacks[i];
                for (let j = i + 1; j < newStacks.length; j++) {
                    let other = newStacks[j];
                    if (stack.sameState(other) ||
                        stack.buffer.length > 500 /* Rec.MinBufferLengthPrune */ && other.buffer.length > 500 /* Rec.MinBufferLengthPrune */) {
                        if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) {
                            newStacks.splice(j--, 1);
                        }
                        else {
                            newStacks.splice(i--, 1);
                            continue outer;
                        }
                    }
                }
            }
            if (newStacks.length > 12 /* Rec.MaxStackCount */) {
                newStacks.sort((a, b) => b.score - a.score);
                newStacks.splice(12 /* Rec.MaxStackCount */, newStacks.length - 12 /* Rec.MaxStackCount */);
            }
        }
        this.minStackPos = newStacks[0].pos;
        for (let i = 1; i < newStacks.length; i++)
            if (newStacks[i].pos < this.minStackPos)
                this.minStackPos = newStacks[i].pos;
        return null;
    }
    stopAt(pos) {
        if (this.stoppedAt != null && this.stoppedAt < pos)
            throw new RangeError("Can't move stoppedAt forward");
        this.stoppedAt = pos;
    }
    // Returns an updated version of the given stack, or null if the
    // stack can't advance normally. When `split` and `stacks` are
    // given, stacks split off by ambiguous operations will be pushed to
    // `split`, or added to `stacks` if they move `pos` forward.
    advanceStack(stack, stacks, split) {
        let start = stack.pos, { parser } = this;
        let base = verbose ? this.stackID(stack) + " -> " : "";
        if (this.stoppedAt != null && start > this.stoppedAt)
            return stack.forceReduce() ? stack : null;
        if (this.fragments) {
            let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;
            for (let cached = this.fragments.nodeAt(start); cached;) {
                let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1;
                if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
                    stack.useNode(cached, match);
                    if (verbose)
                        console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`);
                    return true;
                }
                if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
                    break;
                let inner = cached.children[0];
                if (inner instanceof Tree && cached.positions[0] == 0)
                    cached = inner;
                else
                    break;
            }
        }
        let defaultReduce = parser.stateSlot(stack.state, 4 /* ParseState.DefaultReduce */);
        if (defaultReduce > 0) {
            stack.reduce(defaultReduce);
            if (verbose)
                console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* Action.ValueMask */)})`);
            return true;
        }
        if (stack.stack.length >= 8400 /* Rec.CutDepth */) {
            while (stack.stack.length > 6000 /* Rec.CutTo */ && stack.forceReduce()) { }
        }
        let actions = this.tokens.getActions(stack);
        for (let i = 0; i < actions.length;) {
            let action = actions[i++], term = actions[i++], end = actions[i++];
            let last = i == actions.length || !split;
            let localStack = last ? stack : stack.split();
            let main = this.tokens.mainToken;
            localStack.apply(action, term, main ? main.start : localStack.pos, end);
            if (verbose)
                console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* Action.ReduceFlag */) == 0 ? "shift"
                    : `reduce of ${parser.getName(action & 65535 /* Action.ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
            if (last)
                return true;
            else if (localStack.pos > start)
                stacks.push(localStack);
            else
                split.push(localStack);
        }
        return false;
    }
    // Advance a given stack forward as far as it will go. Returns the
    // (possibly updated) stack if it got stuck, or null if it moved
    // forward and was given to `pushStackDedup`.
    advanceFully(stack, newStacks) {
        let pos = stack.pos;
        for (;;) {
            if (!this.advanceStack(stack, null, null))
                return false;
            if (stack.pos > pos) {
                pushStackDedup(stack, newStacks);
                return true;
            }
        }
    }
    runRecovery(stacks, tokens, newStacks) {
        let finished = null, restarted = false;
        for (let i = 0; i < stacks.length; i++) {
            let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
            let base = verbose ? this.stackID(stack) + " -> " : "";
            if (stack.deadEnd) {
                if (restarted)
                    continue;
                restarted = true;
                stack.restart();
                if (verbose)
                    console.log(base + this.stackID(stack) + " (restarted)");
                let done = this.advanceFully(stack, newStacks);
                if (done)
                    continue;
            }
            let force = stack.split(), forceBase = base;
            for (let j = 0; j < 10 /* Rec.ForceReduceLimit */ && force.forceReduce(); j++) {
                if (verbose)
                    console.log(forceBase + this.stackID(force) + " (via force-reduce)");
                let done = this.advanceFully(force, newStacks);
                if (done)
                    break;
                if (verbose)
                    forceBase = this.stackID(force) + " -> ";
            }
            for (let insert of stack.recoverByInsert(token)) {
                if (verbose)
                    console.log(base + this.stackID(insert) + " (via recover-insert)");
                this.advanceFully(insert, newStacks);
            }
            if (this.stream.end > stack.pos) {
                if (tokenEnd == stack.pos) {
                    tokenEnd++;
                    token = 0 /* Term.Err */;
                }
                stack.recoverByDelete(token, tokenEnd);
                if (verbose)
                    console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
                pushStackDedup(stack, newStacks);
            }
            else if (!finished || finished.score < force.score) {
                finished = force;
            }
        }
        return finished;
    }
    // Convert the stack's buffer to a syntax tree.
    stackToTree(stack) {
        stack.close();
        return Tree.build({ buffer: StackBufferCursor.create(stack),
            nodeSet: this.parser.nodeSet,
            topID: this.topTerm,
            maxBufferLength: this.parser.bufferLength,
            reused: this.reused,
            start: this.ranges[0].from,
            length: stack.pos - this.ranges[0].from,
            minRepeatType: this.parser.minRepeatTerm });
    }
    stackID(stack) {
        let id = (stackIDs || (stackIDs = new WeakMap)).get(stack);
        if (!id)
            stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
        return id + stack;
    }
}
function pushStackDedup(stack, newStacks) {
    for (let i = 0; i < newStacks.length; i++) {
        let other = newStacks[i];
        if (other.pos == stack.pos && other.sameState(stack)) {
            if (newStacks[i].score < stack.score)
                newStacks[i] = stack;
            return;
        }
    }
    newStacks.push(stack);
}
class Dialect {
    constructor(source, flags, disabled) {
        this.source = source;
        this.flags = flags;
        this.disabled = disabled;
    }
    allows(term) { return !this.disabled || this.disabled[term] == 0; }
}
const id = x => x;
/**
Context trackers are used to track stateful context (such as
indentation in the Python grammar, or parent elements in the XML
grammar) needed by external tokenizers. You declare them in a
grammar file as `@context exportName from "module"`.

Context values should be immutable, and can be updated (replaced)
on shift or reduce actions.

The export used in a `@context` declaration should be of this
type.
*/
class ContextTracker {
    /**
    Define a context tracker.
    */
    constructor(spec) {
        this.start = spec.start;
        this.shift = spec.shift || id;
        this.reduce = spec.reduce || id;
        this.reuse = spec.reuse || id;
        this.hash = spec.hash || (() => 0);
        this.strict = spec.strict !== false;
    }
}
/**
Holds the parse tables for a given grammar, as generated by
`lezer-generator`, and provides [methods](#common.Parser) to parse
content with.
*/
class LRParser extends Parser {
    /**
    @internal
    */
    constructor(spec) {
        super();
        /**
        @internal
        */
        this.wrappers = [];
        if (spec.version != 14 /* File.Version */)
            throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14 /* File.Version */})`);
        let nodeNames = spec.nodeNames.split(" ");
        this.minRepeatTerm = nodeNames.length;
        for (let i = 0; i < spec.repeatNodeCount; i++)
            nodeNames.push("");
        let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]);
        let nodeProps = [];
        for (let i = 0; i < nodeNames.length; i++)
            nodeProps.push([]);
        function setProp(nodeID, prop, value) {
            nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
        }
        if (spec.nodeProps)
            for (let propSpec of spec.nodeProps) {
                let prop = propSpec[0];
                if (typeof prop == "string")
                    prop = NodeProp[prop];
                for (let i = 1; i < propSpec.length;) {
                    let next = propSpec[i++];
                    if (next >= 0) {
                        setProp(next, prop, propSpec[i++]);
                    }
                    else {
                        let value = propSpec[i + -next];
                        for (let j = -next; j > 0; j--)
                            setProp(propSpec[i++], prop, value);
                        i++;
                    }
                }
            }
        this.nodeSet = new NodeSet(nodeNames.map((name, i) => dist_NodeType.define({
            name: i >= this.minRepeatTerm ? undefined : name,
            id: i,
            props: nodeProps[i],
            top: topTerms.indexOf(i) > -1,
            error: i == 0,
            skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
        })));
        if (spec.propSources)
            this.nodeSet = this.nodeSet.extend(...spec.propSources);
        this.strict = false;
        this.bufferLength = DefaultBufferLength;
        let tokenArray = decodeArray(spec.tokenData);
        this.context = spec.context;
        this.specializerSpecs = spec.specialized || [];
        this.specialized = new Uint16Array(this.specializerSpecs.length);
        for (let i = 0; i < this.specializerSpecs.length; i++)
            this.specialized[i] = this.specializerSpecs[i].term;
        this.specializers = this.specializerSpecs.map(getSpecializer);
        this.states = decodeArray(spec.states, Uint32Array);
        this.data = decodeArray(spec.stateData);
        this.goto = decodeArray(spec.goto);
        this.maxTerm = spec.maxTerm;
        this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
        this.topRules = spec.topRules;
        this.dialects = spec.dialects || {};
        this.dynamicPrecedences = spec.dynamicPrecedences || null;
        this.tokenPrecTable = spec.tokenPrec;
        this.termNames = spec.termNames || null;
        this.maxNode = this.nodeSet.types.length - 1;
        this.dialect = this.parseDialect();
        this.top = this.topRules[Object.keys(this.topRules)[0]];
    }
    createParse(input, fragments, ranges) {
        let parse = new dist_Parse(this, input, fragments, ranges);
        for (let w of this.wrappers)
            parse = w(parse, input, fragments, ranges);
        return parse;
    }
    /**
    Get a goto table entry @internal
    */
    getGoto(state, term, loose = false) {
        let table = this.goto;
        if (term >= table[0])
            return -1;
        for (let pos = table[term + 1];;) {
            let groupTag = table[pos++], last = groupTag & 1;
            let target = table[pos++];
            if (last && loose)
                return target;
            for (let end = pos + (groupTag >> 1); pos < end; pos++)
                if (table[pos] == state)
                    return target;
            if (last)
                return -1;
        }
    }
    /**
    Check if this state has an action for a given terminal @internal
    */
    hasAction(state, terminal) {
        let data = this.data;
        for (let set = 0; set < 2; set++) {
            for (let i = this.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */), next;; i += 3) {
                if ((next = data[i]) == 65535 /* Seq.End */) {
                    if (data[i + 1] == 1 /* Seq.Next */)
                        next = data[i = pair(data, i + 2)];
                    else if (data[i + 1] == 2 /* Seq.Other */)
                        return pair(data, i + 2);
                    else
                        break;
                }
                if (next == terminal || next == 0 /* Term.Err */)
                    return pair(data, i + 1);
            }
        }
        return 0;
    }
    /**
    @internal
    */
    stateSlot(state, slot) {
        return this.states[(state * 6 /* ParseState.Size */) + slot];
    }
    /**
    @internal
    */
    stateFlag(state, flag) {
        return (this.stateSlot(state, 0 /* ParseState.Flags */) & flag) > 0;
    }
    /**
    @internal
    */
    validAction(state, action) {
        return !!this.allActions(state, a => a == action ? true : null);
    }
    /**
    @internal
    */
    allActions(state, action) {
        let deflt = this.stateSlot(state, 4 /* ParseState.DefaultReduce */);
        let result = deflt ? action(deflt) : undefined;
        for (let i = this.stateSlot(state, 1 /* ParseState.Actions */); result == null; i += 3) {
            if (this.data[i] == 65535 /* Seq.End */) {
                if (this.data[i + 1] == 1 /* Seq.Next */)
                    i = pair(this.data, i + 2);
                else
                    break;
            }
            result = action(pair(this.data, i + 1));
        }
        return result;
    }
    /**
    Get the states that can follow this one through shift actions or
    goto jumps. @internal
    */
    nextStates(state) {
        let result = [];
        for (let i = this.stateSlot(state, 1 /* ParseState.Actions */);; i += 3) {
            if (this.data[i] == 65535 /* Seq.End */) {
                if (this.data[i + 1] == 1 /* Seq.Next */)
                    i = pair(this.data, i + 2);
                else
                    break;
            }
            if ((this.data[i + 2] & (65536 /* Action.ReduceFlag */ >> 16)) == 0) {
                let value = this.data[i + 1];
                if (!result.some((v, i) => (i & 1) && v == value))
                    result.push(this.data[i], value);
            }
        }
        return result;
    }
    /**
    Configure the parser. Returns a new parser instance that has the
    given settings modified. Settings not provided in `config` are
    kept from the original parser.
    */
    configure(config) {
        // Hideous reflection-based kludge to make it easy to create a
        // slightly modified copy of a parser.
        let copy = Object.assign(Object.create(LRParser.prototype), this);
        if (config.props)
            copy.nodeSet = this.nodeSet.extend(...config.props);
        if (config.top) {
            let info = this.topRules[config.top];
            if (!info)
                throw new RangeError(`Invalid top rule name ${config.top}`);
            copy.top = info;
        }
        if (config.tokenizers)
            copy.tokenizers = this.tokenizers.map(t => {
                let found = config.tokenizers.find(r => r.from == t);
                return found ? found.to : t;
            });
        if (config.specializers) {
            copy.specializers = this.specializers.slice();
            copy.specializerSpecs = this.specializerSpecs.map((s, i) => {
                let found = config.specializers.find(r => r.from == s.external);
                if (!found)
                    return s;
                let spec = Object.assign(Object.assign({}, s), { external: found.to });
                copy.specializers[i] = getSpecializer(spec);
                return spec;
            });
        }
        if (config.contextTracker)
            copy.context = config.contextTracker;
        if (config.dialect)
            copy.dialect = this.parseDialect(config.dialect);
        if (config.strict != null)
            copy.strict = config.strict;
        if (config.wrap)
            copy.wrappers = copy.wrappers.concat(config.wrap);
        if (config.bufferLength != null)
            copy.bufferLength = config.bufferLength;
        return copy;
    }
    /**
    Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
    are registered for this parser.
    */
    hasWrappers() {
        return this.wrappers.length > 0;
    }
    /**
    Returns the name associated with a given term. This will only
    work for all terms when the parser was generated with the
    `--names` option. By default, only the names of tagged terms are
    stored.
    */
    getName(term) {
        return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
    }
    /**
    The eof term id is always allocated directly after the node
    types. @internal
    */
    get eofTerm() { return this.maxNode + 1; }
    /**
    The type of top node produced by the parser.
    */
    get topNode() { return this.nodeSet.types[this.top[1]]; }
    /**
    @internal
    */
    dynamicPrecedence(term) {
        let prec = this.dynamicPrecedences;
        return prec == null ? 0 : prec[term] || 0;
    }
    /**
    @internal
    */
    parseDialect(dialect) {
        let values = Object.keys(this.dialects), flags = values.map(() => false);
        if (dialect)
            for (let part of dialect.split(" ")) {
                let id = values.indexOf(part);
                if (id >= 0)
                    flags[id] = true;
            }
        let disabled = null;
        for (let i = 0; i < values.length; i++)
            if (!flags[i]) {
                for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* Seq.End */;)
                    (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
            }
        return new Dialect(dialect, flags, disabled);
    }
    /**
    Used by the output of the parser generator. Not available to
    user code. @hide
    */
    static deserialize(spec) {
        return new LRParser(spec);
    }
}
function pair(data, off) { return data[off] | (data[off + 1] << 16); }
function findFinished(stacks) {
    let best = null;
    for (let stack of stacks) {
        let stopped = stack.p.stoppedAt;
        if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) &&
            stack.p.parser.stateFlag(stack.state, 2 /* StateFlag.Accepting */) &&
            (!best || best.score < stack.score))
            best = stack;
    }
    return best;
}
function getSpecializer(spec) {
    if (spec.external) {
        let mask = spec.extend ? 1 /* Specialize.Extend */ : 0 /* Specialize.Specialize */;
        return (value, stack) => (spec.external(value, stack) << 1) | mask;
    }
    return spec.get;
}



;// ../../node_modules/@lezer/javascript/dist/index.js



// This file was generated by lezer-generator. You probably shouldn't edit it.
const noSemi = 316,
  noSemiType = 317,
  incdec = 1,
  incdecPrefix = 2,
  questionDot = 3,
  JSXStartTag = 4,
  insertSemi = 318,
  spaces = 320,
  newline = 321,
  LineComment = 5,
  BlockComment = 6,
  Dialect_jsx = 0;

/* Hand-written tokenizers for JavaScript tokens that can't be
   expressed by lezer's built-in tokenizer. */

const space = [9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200,
               8201, 8202, 8232, 8233, 8239, 8287, 12288];

const braceR = 125, semicolon = 59, slash = 47, star = 42, plus = 43, minus = 45, lt = 60, comma = 44,
      question = 63, dot = 46, bracketL = 91;

const trackNewline = new ContextTracker({
  start: false,
  shift(context, term) {
    return term == LineComment || term == BlockComment || term == spaces ? context : term == newline
  },
  strict: false
});

const insertSemicolon = new ExternalTokenizer((input, stack) => {
  let {next} = input;
  if (next == braceR || next == -1 || stack.context)
    input.acceptToken(insertSemi);
}, {contextual: true, fallback: true});

const noSemicolon = new ExternalTokenizer((input, stack) => {
  let {next} = input, after;
  if (space.indexOf(next) > -1) return
  if (next == slash && ((after = input.peek(1)) == slash || after == star)) return
  if (next != braceR && next != semicolon && next != -1 && !stack.context)
    input.acceptToken(noSemi);
}, {contextual: true});

const noSemicolonType = new ExternalTokenizer((input, stack) => {
  if (input.next == bracketL && !stack.context) input.acceptToken(noSemiType);
}, {contextual: true});

const operatorToken = new ExternalTokenizer((input, stack) => {
  let {next} = input;
  if (next == plus || next == minus) {
    input.advance();
    if (next == input.next) {
      input.advance();
      let mayPostfix = !stack.context && stack.canShift(incdec);
      input.acceptToken(mayPostfix ? incdec : incdecPrefix);
    }
  } else if (next == question && input.peek(1) == dot) {
    input.advance(); input.advance();
    if (input.next < 48 || input.next > 57) // No digit after
      input.acceptToken(questionDot);
  }
}, {contextual: true});

function identifierChar(ch, start) {
  return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch == 95 || ch >= 192 ||
    !start && ch >= 48 && ch <= 57
}

const jsx = new ExternalTokenizer((input, stack) => {
  if (input.next != lt || !stack.dialectEnabled(Dialect_jsx)) return
  input.advance();
  if (input.next == slash) return
  // Scan for an identifier followed by a comma or 'extends', don't
  // treat this as a start tag if present.
  let back = 0;
  while (space.indexOf(input.next) > -1) { input.advance(); back++; }
  if (identifierChar(input.next, true)) {
    input.advance();
    back++;
    while (identifierChar(input.next, false)) { input.advance(); back++; }
    while (space.indexOf(input.next) > -1) { input.advance(); back++; }
    if (input.next == comma) return
    for (let i = 0;; i++) {
      if (i == 7) {
        if (!identifierChar(input.next, true)) return
        break
      }
      if (input.next != "extends".charCodeAt(i)) break
      input.advance();
      back++;
    }
  }
  input.acceptToken(JSXStartTag, -back);
});

const jsHighlight = styleTags({
  "get set async static": tags.modifier,
  "for while do if else switch try catch finally return throw break continue default case defer": tags.controlKeyword,
  "in of await yield void typeof delete instanceof as satisfies": tags.operatorKeyword,
  "let var const using function class extends": tags.definitionKeyword,
  "import export from": tags.moduleKeyword,
  "with debugger new": tags.keyword,
  TemplateString: tags.special(tags.string),
  super: tags.atom,
  BooleanLiteral: tags.bool,
  this: tags.self,
  null: tags.null,
  Star: tags.modifier,
  VariableName: tags.variableName,
  "CallExpression/VariableName TaggedTemplateExpression/VariableName": tags.function(tags.variableName),
  VariableDefinition: tags.definition(tags.variableName),
  Label: tags.labelName,
  PropertyName: tags.propertyName,
  PrivatePropertyName: tags.special(tags.propertyName),
  "CallExpression/MemberExpression/PropertyName": tags.function(tags.propertyName),
  "FunctionDeclaration/VariableDefinition": tags.function(tags.definition(tags.variableName)),
  "ClassDeclaration/VariableDefinition": tags.definition(tags.className),
  "NewExpression/VariableName": tags.className,
  PropertyDefinition: tags.definition(tags.propertyName),
  PrivatePropertyDefinition: tags.definition(tags.special(tags.propertyName)),
  UpdateOp: tags.updateOperator,
  "LineComment Hashbang": tags.lineComment,
  BlockComment: tags.blockComment,
  Number: tags.number,
  String: tags.string,
  Escape: tags.escape,
  ArithOp: tags.arithmeticOperator,
  LogicOp: tags.logicOperator,
  BitOp: tags.bitwiseOperator,
  CompareOp: tags.compareOperator,
  RegExp: tags.regexp,
  Equals: tags.definitionOperator,
  Arrow: tags.function(tags.punctuation),
  ": Spread": tags.punctuation,
  "( )": tags.paren,
  "[ ]": tags.squareBracket,
  "{ }": tags.brace,
  "InterpolationStart InterpolationEnd": tags.special(tags.brace),
  ".": tags.derefOperator,
  ", ;": tags.separator,
  "@": tags.meta,

  TypeName: tags.typeName,
  TypeDefinition: tags.definition(tags.typeName),
  "type enum interface implements namespace module declare": tags.definitionKeyword,
  "abstract global Privacy readonly override": tags.modifier,
  "is keyof unique infer asserts": tags.operatorKeyword,

  JSXAttributeValue: tags.attributeValue,
  JSXText: tags.content,
  "JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag": tags.angleBracket,
  "JSXIdentifier JSXNameSpacedName": tags.tagName,
  "JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName": tags.attributeName,
  "JSXBuiltin/JSXIdentifier": tags.standard(tags.tagName)
});

// This file was generated by lezer-generator. You probably shouldn't edit it.
const spec_identifier = {__proto__:null,export:20, as:25, from:33, default:36, async:41, function:42, in:52, out:55, const:56, extends:60, this:64, true:72, false:72, null:84, void:88, typeof:92, super:108, new:142, delete:154, yield:163, await:167, class:172, public:235, private:235, protected:235, readonly:237, instanceof:256, satisfies:259, import:292, keyof:349, unique:353, infer:359, asserts:395, is:397, abstract:417, implements:419, type:421, let:424, var:426, using:429, interface:435, enum:439, namespace:445, module:447, declare:451, global:455, defer:471, for:476, of:485, while:488, with:492, do:496, if:500, else:502, switch:506, case:512, try:518, catch:522, finally:526, return:530, throw:534, break:538, continue:542, debugger:546};
const spec_word = {__proto__:null,async:129, get:131, set:133, declare:195, public:197, private:197, protected:197, static:199, abstract:201, override:203, readonly:209, accessor:211, new:401};
const spec_LessThan = {__proto__:null,"<":193};
const parser = LRParser.deserialize({
  version: 14,
  states: "$F|Q%TQlOOO%[QlOOO'_QpOOP(lO`OOO*zQ!0MxO'#CiO+RO#tO'#CjO+aO&jO'#CjO+oO#@ItO'#DaO.QQlO'#DgO.bQlO'#DrO%[QlO'#DzO0fQlO'#ESOOQ!0Lf'#E['#E[O1PQ`O'#EXOOQO'#Ep'#EpOOQO'#Il'#IlO1XQ`O'#GsO1dQ`O'#EoO1iQ`O'#EoO3hQ!0MxO'#JrO6[Q!0MxO'#JsO6uQ`O'#F]O6zQ,UO'#FtOOQ!0Lf'#Ff'#FfO7VO7dO'#FfO9XQMhO'#F|O9`Q`O'#F{OOQ!0Lf'#Js'#JsOOQ!0Lb'#Jr'#JrO9eQ`O'#GwOOQ['#K_'#K_O9pQ`O'#IYO9uQ!0LrO'#IZOOQ['#J`'#J`OOQ['#I_'#I_Q`QlOOQ`QlOOO9}Q!L^O'#DvO:UQlO'#EOO:]QlO'#EQO9kQ`O'#GsO:dQMhO'#CoO:rQ`O'#EnO:}Q`O'#EyO;hQMhO'#FeO;xQ`O'#GsOOQO'#K`'#K`O;}Q`O'#K`O<]Q`O'#G{O<]Q`O'#G|O<]Q`O'#HOO9kQ`O'#HRO=SQ`O'#HUO>kQ`O'#CeO>{Q`O'#HcO?TQ`O'#HiO?TQ`O'#HkO`QlO'#HmO?TQ`O'#HoO?TQ`O'#HrO?YQ`O'#HxO?_Q!0LsO'#IOO%[QlO'#IQO?jQ!0LsO'#ISO?uQ!0LsO'#IUO9uQ!0LrO'#IWO@QQ!0MxO'#CiOASQpO'#DlQOQ`OOO%[QlO'#EQOAjQ`O'#ETO:dQMhO'#EnOAuQ`O'#EnOBQQ!bO'#FeOOQ['#Cg'#CgOOQ!0Lb'#Dq'#DqOOQ!0Lb'#Jv'#JvO%[QlO'#JvOOQO'#Jy'#JyOOQO'#Ih'#IhOCQQpO'#EgOOQ!0Lb'#Ef'#EfOOQ!0Lb'#J}'#J}OC|Q!0MSO'#EgODWQpO'#EWOOQO'#Jx'#JxODlQpO'#JyOEyQpO'#EWODWQpO'#EgPFWO&2DjO'#CbPOOO)CD})CD}OOOO'#I`'#I`OFcO#tO,59UOOQ!0Lh,59U,59UOOOO'#Ia'#IaOFqO&jO,59UOGPQ!L^O'#DcOOOO'#Ic'#IcOGWO#@ItO,59{OOQ!0Lf,59{,59{OGfQlO'#IdOGyQ`O'#JtOIxQ!fO'#JtO+}QlO'#JtOJPQ`O,5:ROJgQ`O'#EpOJtQ`O'#KTOKPQ`O'#KSOKPQ`O'#KSOKXQ`O,5;^OK^Q`O'#KROOQ!0Ln,5:^,5:^OKeQlO,5:^OMcQ!0MxO,5:fONSQ`O,5:nONmQ!0LrO'#KQONtQ`O'#KPO9eQ`O'#KPO! YQ`O'#KPO! bQ`O,5;]O! gQ`O'#KPO!#lQ!fO'#JsOOQ!0Lh'#Ci'#CiO%[QlO'#ESO!$[Q!fO,5:sOOQS'#Jz'#JzOOQO-E<j-E<jO9kQ`O,5=_O!$rQ`O,5=_O!$wQlO,5;ZO!&zQMhO'#EkO!(eQ`O,5;ZO!(jQlO'#DyO!(tQpO,5;dO!(|QpO,5;dO%[QlO,5;dOOQ['#FT'#FTOOQ['#FV'#FVO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eO%[QlO,5;eOOQ['#FZ'#FZO!)[QlO,5;tOOQ!0Lf,5;y,5;yOOQ!0Lf,5;z,5;zOOQ!0Lf,5;|,5;|O%[QlO'#IpO!+_Q!0LrO,5<iO%[QlO,5;eO!&zQMhO,5;eO!+|QMhO,5;eO!-nQMhO'#E^O%[QlO,5;wOOQ!0Lf,5;{,5;{O!-uQ,UO'#FjO!.rQ,UO'#KXO!.^Q,UO'#KXO!.yQ,UO'#KXOOQO'#KX'#KXO!/_Q,UO,5<SOOOW,5<`,5<`O!/pQlO'#FvOOOW'#Io'#IoO7VO7dO,5<QO!/wQ,UO'#FxOOQ!0Lf,5<Q,5<QO!0hQ$IUO'#CyOOQ!0Lh'#C}'#C}O!0{O#@ItO'#DRO!1iQMjO,5<eO!1pQ`O,5<hO!3YQ(CWO'#GXO!3jQ`O'#GYO!3oQ`O'#GYO!5_Q(CWO'#G^O!6dQpO'#GbOOQO'#Gn'#GnO!,TQMhO'#GmOOQO'#Gp'#GpO!,TQMhO'#GoO!7VQ$IUO'#JlOOQ!0Lh'#Jl'#JlO!7aQ`O'#JkO!7oQ`O'#JjO!7wQ`O'#CuOOQ!0Lh'#C{'#C{O!8YQ`O'#C}OOQ!0Lh'#DV'#DVOOQ!0Lh'#DX'#DXO!8_Q`O,5<eO1SQ`O'#DZO!,TQMhO'#GPO!,TQMhO'#GRO!8gQ`O'#GTO!8lQ`O'#GUO!3oQ`O'#G[O!,TQMhO'#GaO<]Q`O'#JkO!8qQ`O'#EqO!9`Q`O,5<gOOQ!0Lb'#Cr'#CrO!9hQ`O'#ErO!:bQpO'#EsOOQ!0Lb'#KR'#KRO!:iQ!0LrO'#KaO9uQ!0LrO,5=cO`QlO,5>tOOQ['#Jh'#JhOOQ[,5>u,5>uOOQ[-E<]-E<]O!<hQ!0MxO,5:bO!:]QpO,5:`O!?RQ!0MxO,5:jO%[QlO,5:jO!AiQ!0MxO,5:lOOQO,5@z,5@zO!BYQMhO,5=_O!BhQ!0LrO'#JiO9`Q`O'#JiO!ByQ!0LrO,59ZO!CUQpO,59ZO!C^QMhO,59ZO:dQMhO,59ZO!CiQ`O,5;ZO!CqQ`O'#HbO!DVQ`O'#KdO%[QlO,5;}O!:]QpO,5<PO!D_Q`O,5=zO!DdQ`O,5=zO!DiQ`O,5=zO!DwQ`O,5=zO9uQ!0LrO,5=zO<]Q`O,5=jOOQO'#Cy'#CyO!EOQpO,5=gO!EWQMhO,5=hO!EcQ`O,5=jO!EhQ!bO,5=mO!EpQ`O'#K`O?YQ`O'#HWO9kQ`O'#HYO!EuQ`O'#HYO:dQMhO'#H[O!EzQ`O'#H[OOQ[,5=p,5=pO!FPQ`O'#H]O!FbQ`O'#CoO!FgQ`O,59PO!FqQ`O,59PO!HvQlO,59POOQ[,59P,59PO!IWQ!0LrO,59PO%[QlO,59PO!KcQlO'#HeOOQ['#Hf'#HfOOQ['#Hg'#HgO`QlO,5=}O!KyQ`O,5=}O`QlO,5>TO`QlO,5>VO!LOQ`O,5>XO`QlO,5>ZO!LTQ`O,5>^O!LYQlO,5>dOOQ[,5>j,5>jO%[QlO,5>jO9uQ!0LrO,5>lOOQ[,5>n,5>nO#!dQ`O,5>nOOQ[,5>p,5>pO#!dQ`O,5>pOOQ[,5>r,5>rO##QQpO'#D_O%[QlO'#JvO##sQpO'#JvO##}QpO'#DmO#$`QpO'#DmO#&qQlO'#DmO#&xQ`O'#JuO#'QQ`O,5:WO#'VQ`O'#EtO#'eQ`O'#KUO#'mQ`O,5;_O#'rQpO'#DmO#(PQpO'#EVOOQ!0Lf,5:o,5:oO%[QlO,5:oO#(WQ`O,5:oO?YQ`O,5;YO!CUQpO,5;YO!C^QMhO,5;YO:dQMhO,5;YO#(`Q`O,5@bO#(eQ07dO,5:sOOQO-E<f-E<fO#)kQ!0MSO,5;RODWQpO,5:rO#)uQpO,5:rODWQpO,5;RO!ByQ!0LrO,5:rOOQ!0Lb'#Ej'#EjOOQO,5;R,5;RO%[QlO,5;RO#*SQ!0LrO,5;RO#*_Q!0LrO,5;RO!CUQpO,5:rOOQO,5;X,5;XO#*mQ!0LrO,5;RPOOO'#I^'#I^P#+RO&2DjO,58|POOO,58|,58|OOOO-E<^-E<^OOQ!0Lh1G.p1G.pOOOO-E<_-E<_OOOO,59},59}O#+^Q!bO,59}OOOO-E<a-E<aOOQ!0Lf1G/g1G/gO#+cQ!fO,5?OO+}QlO,5?OOOQO,5?U,5?UO#+mQlO'#IdOOQO-E<b-E<bO#+zQ`O,5@`O#,SQ!fO,5@`O#,ZQ`O,5@nOOQ!0Lf1G/m1G/mO%[QlO,5@oO#,cQ`O'#IjOOQO-E<h-E<hO#,ZQ`O,5@nOOQ!0Lb1G0x1G0xOOQ!0Ln1G/x1G/xOOQ!0Ln1G0Y1G0YO%[QlO,5@lO#,wQ!0LrO,5@lO#-YQ!0LrO,5@lO#-aQ`O,5@kO9eQ`O,5@kO#-iQ`O,5@kO#-wQ`O'#ImO#-aQ`O,5@kOOQ!0Lb1G0w1G0wO!(tQpO,5:uO!)PQpO,5:uOOQS,5:w,5:wO#.iQdO,5:wO#.qQMhO1G2yO9kQ`O1G2yOOQ!0Lf1G0u1G0uO#/PQ!0MxO1G0uO#0UQ!0MvO,5;VOOQ!0Lh'#GW'#GWO#0rQ!0MzO'#JlO!$wQlO1G0uO#2}Q!fO'#JwO%[QlO'#JwO#3XQ`O,5:eOOQ!0Lh'#D_'#D_OOQ!0Lf1G1O1G1OO%[QlO1G1OOOQ!0Lf1G1f1G1fO#3^Q`O1G1OO#5rQ!0MxO1G1PO#5yQ!0MxO1G1PO#8aQ!0MxO1G1PO#8hQ!0MxO1G1PO#;OQ!0MxO1G1PO#=fQ!0MxO1G1PO#=mQ!0MxO1G1PO#=tQ!0MxO1G1PO#@[Q!0MxO1G1PO#@cQ!0MxO1G1PO#BpQ?MtO'#CiO#DkQ?MtO1G1`O#DrQ?MtO'#JsO#EVQ!0MxO,5?[OOQ!0Lb-E<n-E<nO#GdQ!0MxO1G1PO#HaQ!0MzO1G1POOQ!0Lf1G1P1G1PO#IdQMjO'#J|O#InQ`O,5:xO#IsQ!0MxO1G1cO#JgQ,UO,5<WO#JoQ,UO,5<XO#JwQ,UO'#FoO#K`Q`O'#FnOOQO'#KY'#KYOOQO'#In'#InO#KeQ,UO1G1nOOQ!0Lf1G1n1G1nOOOW1G1y1G1yO#KvQ?MtO'#JrO#LQQ`O,5<bO!)[QlO,5<bOOOW-E<m-E<mOOQ!0Lf1G1l1G1lO#LVQpO'#KXOOQ!0Lf,5<d,5<dO#L_QpO,5<dO#LdQMhO'#DTOOOO'#Ib'#IbO#LkO#@ItO,59mOOQ!0Lh,59m,59mO%[QlO1G2PO!8lQ`O'#IrO#LvQ`O,5<zOOQ!0Lh,5<w,5<wO!,TQMhO'#IuO#MdQMjO,5=XO!,TQMhO'#IwO#NVQMjO,5=ZO!&zQMhO,5=]OOQO1G2S1G2SO#NaQ!dO'#CrO#NtQ(CWO'#ErO$ |QpO'#GbO$!dQ!dO,5<sO$!kQ`O'#K[O9eQ`O'#K[O$!yQ`O,5<uO$#aQ!dO'#C{O!,TQMhO,5<tO$#kQ`O'#GZO$$PQ`O,5<tO$$UQ!dO'#GWO$$cQ!dO'#K]O$$mQ`O'#K]O!&zQMhO'#K]O$$rQ`O,5<xO$$wQlO'#JvO$%RQpO'#GcO#$`QpO'#GcO$%dQ`O'#GgO!3oQ`O'#GkO$%iQ!0LrO'#ItO$%tQpO,5<|OOQ!0Lp,5<|,5<|O$%{QpO'#GcO$&YQpO'#GdO$&kQpO'#GdO$&pQMjO,5=XO$'QQMjO,5=ZOOQ!0Lh,5=^,5=^O!,TQMhO,5@VO!,TQMhO,5@VO$'bQ`O'#IyO$'vQ`O,5@UO$(OQ`O,59aOOQ!0Lh,59i,59iO$(TQ`O,5@VO$)TQ$IYO,59uOOQ!0Lh'#Jp'#JpO$)vQMjO,5<kO$*iQMjO,5<mO@zQ`O,5<oOOQ!0Lh,5<p,5<pO$*sQ`O,5<vO$*xQMjO,5<{O$+YQ`O'#KPO!$wQlO1G2RO$+_Q`O1G2RO9eQ`O'#KSO9eQ`O'#EtO%[QlO'#EtO9eQ`O'#I{O$+dQ!0LrO,5@{OOQ[1G2}1G2}OOQ[1G4`1G4`OOQ!0Lf1G/|1G/|OOQ!0Lf1G/z1G/zO$-fQ!0MxO1G0UOOQ[1G2y1G2yO!&zQMhO1G2yO%[QlO1G2yO#.tQ`O1G2yO$/jQMhO'#EkOOQ!0Lb,5@T,5@TO$/wQ!0LrO,5@TOOQ[1G.u1G.uO!ByQ!0LrO1G.uO!CUQpO1G.uO!C^QMhO1G.uO$0YQ`O1G0uO$0_Q`O'#CiO$0jQ`O'#KeO$0rQ`O,5=|O$0wQ`O'#KeO$0|Q`O'#KeO$1[Q`O'#JRO$1jQ`O,5AOO$1rQ!fO1G1iOOQ!0Lf1G1k1G1kO9kQ`O1G3fO@zQ`O1G3fO$1yQ`O1G3fO$2OQ`O1G3fO!DiQ`O1G3fO9uQ!0LrO1G3fOOQ[1G3f1G3fO!EcQ`O1G3UO!&zQMhO1G3RO$2TQ`O1G3ROOQ[1G3S1G3SO!&zQMhO1G3SO$2YQ`O1G3SO$2bQpO'#HQOOQ[1G3U1G3UO!6_QpO'#I}O!EhQ!bO1G3XOOQ[1G3X1G3XOOQ[,5=r,5=rO$2jQMhO,5=tO9kQ`O,5=tO$%dQ`O,5=vO9`Q`O,5=vO!CUQpO,5=vO!C^QMhO,5=vO:dQMhO,5=vO$2xQ`O'#KcO$3TQ`O,5=wOOQ[1G.k1G.kO$3YQ!0LrO1G.kO@zQ`O1G.kO$3eQ`O1G.kO9uQ!0LrO1G.kO$5mQ!fO,5AQO$5zQ`O,5AQO9eQ`O,5AQO$6VQlO,5>PO$6^Q`O,5>POOQ[1G3i1G3iO`QlO1G3iOOQ[1G3o1G3oOOQ[1G3q1G3qO?TQ`O1G3sO$6cQlO1G3uO$:gQlO'#HtOOQ[1G3x1G3xO$:tQ`O'#HzO?YQ`O'#H|OOQ[1G4O1G4OO$:|QlO1G4OO9uQ!0LrO1G4UOOQ[1G4W1G4WOOQ!0Lb'#G_'#G_O9uQ!0LrO1G4YO9uQ!0LrO1G4[O$?TQ`O,5@bO!)[QlO,5;`O9eQ`O,5;`O?YQ`O,5:XO!)[QlO,5:XO!CUQpO,5:XO$?YQ?MtO,5:XOOQO,5;`,5;`O$?dQpO'#IeO$?zQ`O,5@aOOQ!0Lf1G/r1G/rO$@SQpO'#IkO$@^Q`O,5@pOOQ!0Lb1G0y1G0yO#$`QpO,5:XOOQO'#Ig'#IgO$@fQpO,5:qOOQ!0Ln,5:q,5:qO#(ZQ`O1G0ZOOQ!0Lf1G0Z1G0ZO%[QlO1G0ZOOQ!0Lf1G0t1G0tO?YQ`O1G0tO!CUQpO1G0tO!C^QMhO1G0tOOQ!0Lb1G5|1G5|O!ByQ!0LrO1G0^OOQO1G0m1G0mO%[QlO1G0mO$@mQ!0LrO1G0mO$@xQ!0LrO1G0mO!CUQpO1G0^ODWQpO1G0^O$AWQ!0LrO1G0mOOQO1G0^1G0^O$AlQ!0MxO1G0mPOOO-E<[-E<[POOO1G.h1G.hOOOO1G/i1G/iO$AvQ!bO,5<iO$BOQ!fO1G4jOOQO1G4p1G4pO%[QlO,5?OO$BYQ`O1G5zO$BbQ`O1G6YO$BjQ!fO1G6ZO9eQ`O,5?UO$BtQ!0MxO1G6WO%[QlO1G6WO$CUQ!0LrO1G6WO$CgQ`O1G6VO$CgQ`O1G6VO9eQ`O1G6VO$CoQ`O,5?XO9eQ`O,5?XOOQO,5?X,5?XO$DTQ`O,5?XO$+YQ`O,5?XOOQO-E<k-E<kOOQS1G0a1G0aOOQS1G0c1G0cO#.lQ`O1G0cOOQ[7+(e7+(eO!&zQMhO7+(eO%[QlO7+(eO$DcQ`O7+(eO$DnQMhO7+(eO$D|Q!0MzO,5=XO$GXQ!0MzO,5=ZO$IdQ!0MzO,5=XO$KuQ!0MzO,5=ZO$NWQ!0MzO,59uO%!]Q!0MzO,5<kO%$hQ!0MzO,5<mO%&sQ!0MzO,5<{OOQ!0Lf7+&a7+&aO%)UQ!0MxO7+&aO%)xQlO'#IfO%*VQ`O,5@cO%*_Q!fO,5@cOOQ!0Lf1G0P1G0PO%*iQ`O7+&jOOQ!0Lf7+&j7+&jO%*nQ?MtO,5:fO%[QlO7+&zO%*xQ?MtO,5:bO%+VQ?MtO,5:jO%+aQ?MtO,5:lO%+kQMhO'#IiO%+uQ`O,5@hOOQ!0Lh1G0d1G0dOOQO1G1r1G1rOOQO1G1s1G1sO%+}Q!jO,5<ZO!)[QlO,5<YOOQO-E<l-E<lOOQ!0Lf7+'Y7+'YOOOW7+'e7+'eOOOW1G1|1G1|O%,YQ`O1G1|OOQ!0Lf1G2O1G2OOOOO,59o,59oO%,_Q!dO,59oOOOO-E<`-E<`OOQ!0Lh1G/X1G/XO%,fQ!0MxO7+'kOOQ!0Lh,5?^,5?^O%-YQMhO1G2fP%-aQ`O'#IrPOQ!0Lh-E<p-E<pO%-}QMjO,5?aOOQ!0Lh-E<s-E<sO%.pQMjO,5?cOOQ!0Lh-E<u-E<uO%.zQ!dO1G2wO%/RQ!dO'#CrO%/iQMhO'#KSO$$wQlO'#JvOOQ!0Lh1G2_1G2_O%/sQ`O'#IqO%0[Q`O,5@vO%0[Q`O,5@vO%0dQ`O,5@vO%0oQ`O,5@vOOQO1G2a1G2aO%0}QMjO1G2`O$+YQ`O'#K[O!,TQMhO1G2`O%1_Q(CWO'#IsO%1lQ`O,5@wO!&zQMhO,5@wO%1tQ!dO,5@wOOQ!0Lh1G2d1G2dO%4UQ!fO'#CiO%4`Q`O,5=POOQ!0Lb,5<},5<}O%4hQpO,5<}OOQ!0Lb,5=O,5=OOCwQ`O,5<}O%4sQpO,5<}OOQ!0Lb,5=R,5=RO$+YQ`O,5=VOOQO,5?`,5?`OOQO-E<r-E<rOOQ!0Lp1G2h1G2hO#$`QpO,5<}O$$wQlO,5=PO%5RQ`O,5=OO%5^QpO,5=OO!,TQMhO'#IuO%6WQMjO1G2sO!,TQMhO'#IwO%6yQMjO1G2uO%7TQMjO1G5qO%7_QMjO1G5qOOQO,5?e,5?eOOQO-E<w-E<wOOQO1G.{1G.{O!,TQMhO1G5qO!,TQMhO1G5qO!:]QpO,59wO%[QlO,59wOOQ!0Lh,5<j,5<jO%7lQ`O1G2ZO!,TQMhO1G2bO%7qQ!0MxO7+'mOOQ!0Lf7+'m7+'mO!$wQlO7+'mO%8eQ`O,5;`OOQ!0Lb,5?g,5?gOOQ!0Lb-E<y-E<yO%8jQ!dO'#K^O#(ZQ`O7+(eO4UQ!fO7+(eO$DfQ`O7+(eO%8tQ!0MvO'#CiO%9XQ!0MvO,5=SO%9lQ`O,5=SO%9tQ`O,5=SOOQ!0Lb1G5o1G5oOOQ[7+$a7+$aO!ByQ!0LrO7+$aO!CUQpO7+$aO!$wQlO7+&aO%9yQ`O'#JQO%:bQ`O,5APOOQO1G3h1G3hO9kQ`O,5APO%:bQ`O,5APO%:jQ`O,5APOOQO,5?m,5?mOOQO-E=P-E=POOQ!0Lf7+'T7+'TO%:oQ`O7+)QO9uQ!0LrO7+)QO9kQ`O7+)QO@zQ`O7+)QO%:tQ`O7+)QOOQ[7+)Q7+)QOOQ[7+(p7+(pO%:yQ!0MvO7+(mO!&zQMhO7+(mO!E^Q`O7+(nOOQ[7+(n7+(nO!&zQMhO7+(nO%;TQ`O'#KbO%;`Q`O,5=lOOQO,5?i,5?iOOQO-E<{-E<{OOQ[7+(s7+(sO%<rQpO'#HZOOQ[1G3`1G3`O!&zQMhO1G3`O%[QlO1G3`O%<yQ`O1G3`O%=UQMhO1G3`O9uQ!0LrO1G3bO$%dQ`O1G3bO9`Q`O1G3bO!CUQpO1G3bO!C^QMhO1G3bO%=dQ`O'#JPO%=xQ`O,5@}O%>QQpO,5@}OOQ!0Lb1G3c1G3cOOQ[7+$V7+$VO@zQ`O7+$VO9uQ!0LrO7+$VO%>]Q`O7+$VO%[QlO1G6lO%[QlO1G6mO%>bQ!0LrO1G6lO%>lQlO1G3kO%>sQ`O1G3kO%>xQlO1G3kOOQ[7+)T7+)TO9uQ!0LrO7+)_O`QlO7+)aOOQ['#Kh'#KhOOQ['#JS'#JSO%?PQlO,5>`OOQ[,5>`,5>`O%[QlO'#HuO%?^Q`O'#HwOOQ[,5>f,5>fO9eQ`O,5>fOOQ[,5>h,5>hOOQ[7+)j7+)jOOQ[7+)p7+)pOOQ[7+)t7+)tOOQ[7+)v7+)vO%?cQpO1G5|O%?}Q?MtO1G0zO%@XQ`O1G0zOOQO1G/s1G/sO%@dQ?MtO1G/sO?YQ`O1G/sO!)[QlO'#DmOOQO,5?P,5?POOQO-E<c-E<cOOQO,5?V,5?VOOQO-E<i-E<iO!CUQpO1G/sOOQO-E<e-E<eOOQ!0Ln1G0]1G0]OOQ!0Lf7+%u7+%uO#(ZQ`O7+%uOOQ!0Lf7+&`7+&`O?YQ`O7+&`O!CUQpO7+&`OOQO7+%x7+%xO$AlQ!0MxO7+&XOOQO7+&X7+&XO%[QlO7+&XO%@nQ!0LrO7+&XO!ByQ!0LrO7+%xO!CUQpO7+%xO%@yQ!0LrO7+&XO%AXQ!0MxO7++rO%[QlO7++rO%AiQ`O7++qO%AiQ`O7++qOOQO1G4s1G4sO9eQ`O1G4sO%AqQ`O1G4sOOQS7+%}7+%}O#(ZQ`O<<LPO4UQ!fO<<LPO%BPQ`O<<LPOOQ[<<LP<<LPO!&zQMhO<<LPO%[QlO<<LPO%BXQ`O<<LPO%BdQ!0MzO,5?aO%DoQ!0MzO,5?cO%FzQ!0MzO1G2`O%I]Q!0MzO1G2sO%KhQ!0MzO1G2uO%MsQ!fO,5?QO%[QlO,5?QOOQO-E<d-E<dO%M}Q`O1G5}OOQ!0Lf<<JU<<JUO%NVQ?MtO1G0uO&!^Q?MtO1G1PO&!eQ?MtO1G1PO&$fQ?MtO1G1PO&$mQ?MtO1G1PO&&nQ?MtO1G1PO&(oQ?MtO1G1PO&(vQ?MtO1G1PO&(}Q?MtO1G1PO&+OQ?MtO1G1PO&+VQ?MtO1G1PO&+^Q!0MxO<<JfO&-UQ?MtO1G1PO&.RQ?MvO1G1PO&/UQ?MvO'#JlO&1[Q?MtO1G1cO&1iQ?MtO1G0UO&1sQMjO,5?TOOQO-E<g-E<gO!)[QlO'#FqOOQO'#KZ'#KZOOQO1G1u1G1uO&1}Q`O1G1tO&2SQ?MtO,5?[OOOW7+'h7+'hOOOO1G/Z1G/ZO&2^Q!dO1G4xOOQ!0Lh7+(Q7+(QP!&zQMhO,5?^O!,TQMhO7+(cO&2eQ`O,5?]O9eQ`O,5?]O$+YQ`O,5?]OOQO-E<o-E<oO&2sQ`O1G6bO&2sQ`O1G6bO&2{Q`O1G6bO&3WQMjO7+'zO&3hQ!dO,5?_O&3rQ`O,5?_O!&zQMhO,5?_OOQO-E<q-E<qO&3wQ!dO1G6cO&4RQ`O1G6cO&4ZQ`O1G2kO!&zQMhO1G2kOOQ!0Lb1G2i1G2iOOQ!0Lb1G2j1G2jO%4hQpO1G2iO!CUQpO1G2iOCwQ`O1G2iOOQ!0Lb1G2q1G2qO&4`QpO1G2iO&4nQ`O1G2kO$+YQ`O1G2jOCwQ`O1G2jO$$wQlO1G2kO&4vQ`O1G2jO&5jQMjO,5?aOOQ!0Lh-E<t-E<tO&6]QMjO,5?cOOQ!0Lh-E<v-E<vO!,TQMhO7++]O&6gQMjO7++]O&6qQMjO7++]OOQ!0Lh1G/c1G/cO&7OQ`O1G/cOOQ!0Lh7+'u7+'uO&7TQMjO7+'|O&7eQ!0MxO<<KXOOQ!0Lf<<KX<<KXO&8XQ`O1G0zO!&zQMhO'#IzO&8^Q`O,5@xO&:`Q!fO<<LPO!&zQMhO1G2nO&:gQ!0LrO1G2nOOQ[<<G{<<G{O!ByQ!0LrO<<G{O&:xQ!0MxO<<I{OOQ!0Lf<<I{<<I{OOQO,5?l,5?lO&;lQ`O,5?lO&;qQ`O,5?lOOQO-E=O-E=OO&<PQ`O1G6kO&<PQ`O1G6kO9kQ`O1G6kO@zQ`O<<LlOOQ[<<Ll<<LlO&<XQ`O<<LlO9uQ!0LrO<<LlO9kQ`O<<LlOOQ[<<LX<<LXO%:yQ!0MvO<<LXOOQ[<<LY<<LYO!E^Q`O<<LYO&<^QpO'#I|O&<iQ`O,5@|O!)[QlO,5@|OOQ[1G3W1G3WOOQO'#JO'#JOO9uQ!0LrO'#JOO&<qQpO,5=uOOQ[,5=u,5=uO&<xQpO'#EgO&=PQpO'#GeO&=UQ`O7+(zO&=ZQ`O7+(zOOQ[7+(z7+(zO!&zQMhO7+(zO%[QlO7+(zO&=cQ`O7+(zOOQ[7+(|7+(|O9uQ!0LrO7+(|O$%dQ`O7+(|O9`Q`O7+(|O!CUQpO7+(|O&=nQ`O,5?kOOQO-E<}-E<}OOQO'#H^'#H^O&=yQ`O1G6iO9uQ!0LrO<<GqOOQ[<<Gq<<GqO@zQ`O<<GqO&>RQ`O7+,WO&>WQ`O7+,XO%[QlO7+,WO%[QlO7+,XOOQ[7+)V7+)VO&>]Q`O7+)VO&>bQlO7+)VO&>iQ`O7+)VOOQ[<<Ly<<LyOOQ[<<L{<<L{OOQ[-E=Q-E=QOOQ[1G3z1G3zO&>nQ`O,5>aOOQ[,5>c,5>cO&>sQ`O1G4QO9eQ`O7+&fO!)[QlO7+&fOOQO7+%_7+%_O&>xQ?MtO1G6ZO?YQ`O7+%_OOQ!0Lf<<Ia<<IaOOQ!0Lf<<Iz<<IzO?YQ`O<<IzOOQO<<Is<<IsO$AlQ!0MxO<<IsO%[QlO<<IsOOQO<<Id<<IdO!ByQ!0LrO<<IdO&?SQ!0LrO<<IsO&?_Q!0MxO<= ^O&?oQ`O<= ]OOQO7+*_7+*_O9eQ`O7+*_OOQ[ANAkANAkO&?wQ!fOANAkO!&zQMhOANAkO#(ZQ`OANAkO4UQ!fOANAkO&@OQ`OANAkO%[QlOANAkO&@WQ!0MzO7+'zO&BiQ!0MzO,5?aO&DtQ!0MzO,5?cO&GPQ!0MzO7+'|O&IbQ!fO1G4lO&IlQ?MtO7+&aO&KpQ?MvO,5=XO&MwQ?MvO,5=ZO&NXQ?MvO,5=XO&NiQ?MvO,5=ZO&NyQ?MvO,59uO'#PQ?MvO,5<kO'%SQ?MvO,5<mO''hQ?MvO,5<{O')^Q?MtO7+'kO')kQ?MtO7+'mO')xQ`O,5<]OOQO7+'`7+'`OOQ!0Lh7+*d7+*dO')}QMjO<<K}OOQO1G4w1G4wO'*UQ`O1G4wO'*aQ`O1G4wO'*oQ`O7++|O'*oQ`O7++|O!&zQMhO1G4yO'*wQ!dO1G4yO'+RQ`O7++}O'+ZQ`O7+(VO'+fQ!dO7+(VOOQ!0Lb7+(T7+(TOOQ!0Lb7+(U7+(UO!CUQpO7+(TOCwQ`O7+(TO'+pQ`O7+(VO!&zQMhO7+(VO$+YQ`O7+(UO'+uQ`O7+(VOCwQ`O7+(UO'+}QMjO<<NwO!,TQMhO<<NwOOQ!0Lh7+$}7+$}O',XQ!dO,5?fOOQO-E<x-E<xO',cQ!0MvO7+(YO!&zQMhO7+(YOOQ[AN=gAN=gO9kQ`O1G5WOOQO1G5W1G5WO',sQ`O1G5WO',xQ`O7+,VO',xQ`O7+,VO9uQ!0LrOANBWO@zQ`OANBWOOQ[ANBWANBWO'-QQ`OANBWOOQ[ANAsANAsOOQ[ANAtANAtO'-VQ`O,5?hOOQO-E<z-E<zO'-bQ?MtO1G6hOOQO,5?j,5?jOOQO-E<|-E<|OOQ[1G3a1G3aO'-lQ`O,5=POOQ[<<Lf<<LfO!&zQMhO<<LfO&=UQ`O<<LfO'-qQ`O<<LfO%[QlO<<LfOOQ[<<Lh<<LhO9uQ!0LrO<<LhO$%dQ`O<<LhO9`Q`O<<LhO'-yQpO1G5VO'.UQ`O7+,TOOQ[AN=]AN=]O9uQ!0LrOAN=]OOQ[<= r<= rOOQ[<= s<= sO'.^Q`O<= rO'.cQ`O<= sOOQ[<<Lq<<LqO'.hQ`O<<LqO'.mQlO<<LqOOQ[1G3{1G3{O?YQ`O7+)lO'.tQ`O<<JQO'/PQ?MtO<<JQOOQO<<Hy<<HyOOQ!0LfAN?fAN?fOOQOAN?_AN?_O$AlQ!0MxOAN?_OOQOAN?OAN?OO%[QlOAN?_OOQO<<My<<MyOOQ[G27VG27VO!&zQMhOG27VO#(ZQ`OG27VO'/ZQ!fOG27VO4UQ!fOG27VO'/bQ`OG27VO'/jQ?MtO<<JfO'/wQ?MvO1G2`O'1mQ?MvO,5?aO'3pQ?MvO,5?cO'5sQ?MvO1G2sO'7vQ?MvO1G2uO'9yQ?MtO<<KXO':WQ?MtO<<I{OOQO1G1w1G1wO!,TQMhOANAiOOQO7+*c7+*cO':eQ`O7+*cO':pQ`O<= hO':xQ!dO7+*eOOQ!0Lb<<Kq<<KqO$+YQ`O<<KqOCwQ`O<<KqO';SQ`O<<KqO!&zQMhO<<KqOOQ!0Lb<<Ko<<KoO!CUQpO<<KoO';_Q!dO<<KqOOQ!0Lb<<Kp<<KpO';iQ`O<<KqO!&zQMhO<<KqO$+YQ`O<<KpO';nQMjOANDcO';xQ!0MvO<<KtOOQO7+*r7+*rO9kQ`O7+*rO'<YQ`O<= qOOQ[G27rG27rO9uQ!0LrOG27rO@zQ`OG27rO!)[QlO1G5SO'<bQ`O7+,SO'<jQ`O1G2kO&=UQ`OANBQOOQ[ANBQANBQO!&zQMhOANBQO'<oQ`OANBQOOQ[ANBSANBSO9uQ!0LrOANBSO$%dQ`OANBSOOQO'#H_'#H_OOQO7+*q7+*qOOQ[G22wG22wOOQ[ANE^ANE^OOQ[ANE_ANE_OOQ[ANB]ANB]O'<wQ`OANB]OOQ[<<MW<<MWO!)[QlOAN?lOOQOG24yG24yO$AlQ!0MxOG24yO#(ZQ`OLD,qOOQ[LD,qLD,qO!&zQMhOLD,qO'<|Q!fOLD,qO'=TQ?MvO7+'zO'>yQ?MvO,5?aO'@|Q?MvO,5?cO'CPQ?MvO7+'|O'DuQMjOG27TOOQO<<M}<<M}OOQ!0LbANA]ANA]O$+YQ`OANA]OCwQ`OANA]O'EVQ!dOANA]OOQ!0LbANAZANAZO'E^Q`OANA]O!&zQMhOANA]O'EiQ!dOANA]OOQ!0LbANA[ANA[OOQO<<N^<<N^OOQ[LD-^LD-^O9uQ!0LrOLD-^O'EsQ?MtO7+*nOOQO'#Gf'#GfOOQ[G27lG27lO&=UQ`OG27lO!&zQMhOG27lOOQ[G27nG27nO9uQ!0LrOG27nOOQ[G27wG27wO'E}Q?MtOG25WOOQOLD*eLD*eOOQ[!$(!]!$(!]O#(ZQ`O!$(!]O!&zQMhO!$(!]O'FXQ!0MzOG27TOOQ!0LbG26wG26wO$+YQ`OG26wO'HjQ`OG26wOCwQ`OG26wO'HuQ!dOG26wO!&zQMhOG26wOOQ[!$(!x!$(!xOOQ[LD-WLD-WO&=UQ`OLD-WOOQ[LD-YLD-YOOQ[!)9Ew!)9EwO#(ZQ`O!)9EwOOQ!0LbLD,cLD,cO$+YQ`OLD,cOCwQ`OLD,cO'H|Q`OLD,cO'IXQ!dOLD,cOOQ[!$(!r!$(!rOOQ[!.K;c!.K;cO'I`Q?MvOG27TOOQ!0Lb!$( }!$( }O$+YQ`O!$( }OCwQ`O!$( }O'KUQ`O!$( }OOQ!0Lb!)9Ei!)9EiO$+YQ`O!)9EiOCwQ`O!)9EiOOQ!0Lb!.K;T!.K;TO$+YQ`O!.K;TOOQ!0Lb!4/0o!4/0oO!)[QlO'#DzO1PQ`O'#EXO'KaQ!fO'#JrO'KhQ!L^O'#DvO'KoQlO'#EOO'KvQ!fO'#CiO'N^Q!fO'#CiO!)[QlO'#EQO'NnQlO,5;ZO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO,5;eO!)[QlO'#IpO(!qQ`O,5<iO!)[QlO,5;eO(!yQMhO,5;eO($dQMhO,5;eO!)[QlO,5;wO!&zQMhO'#GmO(!yQMhO'#GmO!&zQMhO'#GoO(!yQMhO'#GoO1SQ`O'#DZO1SQ`O'#DZO!&zQMhO'#GPO(!yQMhO'#GPO!&zQMhO'#GRO(!yQMhO'#GRO!&zQMhO'#GaO(!yQMhO'#GaO!)[QlO,5:jO($kQpO'#D_O($uQpO'#JvO!)[QlO,5@oO'NnQlO1G0uO(%PQ?MtO'#CiO!)[QlO1G2PO!&zQMhO'#IuO(!yQMhO'#IuO!&zQMhO'#IwO(!yQMhO'#IwO(%ZQ!dO'#CrO!&zQMhO,5<tO(!yQMhO,5<tO'NnQlO1G2RO!)[QlO7+&zO!&zQMhO1G2`O(!yQMhO1G2`O!&zQMhO'#IuO(!yQMhO'#IuO!&zQMhO'#IwO(!yQMhO'#IwO!&zQMhO1G2bO(!yQMhO1G2bO'NnQlO7+'mO'NnQlO7+&aO!&zQMhOANAiO(!yQMhOANAiO(%nQ`O'#EoO(%sQ`O'#EoO(%{Q`O'#F]O(&QQ`O'#EyO(&VQ`O'#KTO(&bQ`O'#KRO(&mQ`O,5;ZO(&rQMjO,5<eO(&yQ`O'#GYO('OQ`O'#GYO('TQ`O,5<eO(']Q`O,5<gO('eQ`O,5;ZO('mQ?MtO1G1`O('tQ`O,5<tO('yQ`O,5<tO((OQ`O,5<vO((TQ`O,5<vO((YQ`O1G2RO((_Q`O1G0uO((dQMjO<<K}O((kQMjO<<K}O((rQMhO'#F|O9`Q`O'#F{OAuQ`O'#EnO!)[QlO,5;tO!3oQ`O'#GYO!3oQ`O'#GYO!3oQ`O'#G[O!3oQ`O'#G[O!,TQMhO7+(cO!,TQMhO7+(cO%.zQ!dO1G2wO%.zQ!dO1G2wO!&zQMhO,5=]O!&zQMhO,5=]",
  stateData: "()x~O'|OS'}OSTOS(ORQ~OPYOQYOSfOY!VOaqOdzOeyOl!POpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_XO!iuO!lZO!oYO!pYO!qYO!svO!uwO!xxO!|]O$W|O$niO%h}O%j!QO%l!OO%m!OO%n!OO%q!RO%s!SO%v!TO%w!TO%y!UO&W!WO&^!XO&`!YO&b!ZO&d![O&g!]O&m!^O&s!_O&u!`O&w!aO&y!bO&{!cO(TSO(VTO(YUO(aVO(o[O~OWtO~P`OPYOQYOSfOd!jOe!iOpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_!eO!iuO!lZO!oYO!pYO!qYO!svO!u!gO!x!hO$W!kO$niO(T!dO(VTO(YUO(aVO(o[O~Oa!wOs!nO!S!oO!b!yO!c!vO!d!vO!|<VO#T!pO#U!pO#V!xO#W!pO#X!pO#[!zO#]!zO(U!lO(VTO(YUO(e!mO(o!sO~O(O!{O~OP]XR]X[]Xa]Xj]Xr]X!Q]X!S]X!]]X!l]X!p]X#R]X#S]X#`]X#kfX#n]X#o]X#p]X#q]X#r]X#s]X#t]X#u]X#v]X#x]X#z]X#{]X$Q]X'z]X(a]X(r]X(y]X(z]X~O!g%RX~P(qO_!}O(V#PO(W!}O(X#PO~O_#QO(X#PO(Y#PO(Z#QO~Ox#SO!U#TO(b#TO(c#VO~OPYOQYOSfOd!jOe!iOpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_!eO!iuO!lZO!oYO!pYO!qYO!svO!u!gO!x!hO$W!kO$niO(T<ZO(VTO(YUO(aVO(o[O~O![#ZO!]#WO!Y(hP!Y(vP~P+}O!^#cO~P`OPYOQYOSfOd!jOe!iOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_!eO!iuO!lZO!oYO!pYO!qYO!svO!u!gO!x!hO$W!kO$niO(VTO(YUO(aVO(o[O~Op#mO![#iO!|]O#i#lO#j#iO(T<[O!k(sP~P.iO!l#oO(T#nO~O!x#sO!|]O%h#tO~O#k#uO~O!g#vO#k#uO~OP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!]$_O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO#x$UO#z$WO#{$XO(aVO(r$YO(y#|O(z#}O~Oa(fX'z(fX'w(fX!k(fX!Y(fX!_(fX%i(fX!g(fX~P1qO#S$dO#`$eO$Q$eOP(gXR(gX[(gXj(gXr(gX!Q(gX!S(gX!](gX!l(gX!p(gX#R(gX#n(gX#o(gX#p(gX#q(gX#r(gX#s(gX#t(gX#u(gX#v(gX#x(gX#z(gX#{(gX(a(gX(r(gX(y(gX(z(gX!_(gX%i(gX~Oa(gX'z(gX'w(gX!Y(gX!k(gXv(gX!g(gX~P4UO#`$eO~O$]$hO$_$gO$f$mO~OSfO!_$nO$i$oO$k$qO~Oh%VOj%dOk%dOp%WOr%XOs$tOt$tOz%YO|%ZO!O%]O!S${O!_$|O!i%bO!l$xO#j%cO$W%`O$t%^O$v%_O$y%aO(T$sO(VTO(YUO(a$uO(y$}O(z%POg(^P~Ol%[O~P7eO!l%eO~O!S%hO!_%iO(T%gO~O!g%mO~Oa%nO'z%nO~O!Q%rO~P%[O(U!lO~P%[O%n%vO~P%[Oh%VO!l%eO(T%gO(U!lO~Oe%}O!l%eO(T%gO~Oj$RO~O!_&PO(T%gO(U!lO(VTO(YUO`)WP~O!Q&SO!l&RO%j&VO&T&WO~P;SO!x#sO~O%s&YO!S)SX!_)SX(T)SX~O(T&ZO~Ol!PO!u&`O%j!QO%l!OO%m!OO%n!OO%q!RO%s!SO%v!TO%w!TO~Od&eOe&dO!x&bO%h&cO%{&aO~P<bOd&hOeyOl!PO!_&gO!u&`O!xxO!|]O%h}O%l!OO%m!OO%n!OO%q!RO%s!SO%v!TO%w!TO%y!UO~Ob&kO#`&nO%j&iO(U!lO~P=gO!l&oO!u&sO~O!l#oO~O!_XO~Oa%nO'x&{O'z%nO~Oa%nO'x'OO'z%nO~Oa%nO'x'QO'z%nO~O'w]X!Y]Xv]X!k]X&[]X!_]X%i]X!g]X~P(qO!b'_O!c'WO!d'WO(U!lO(VTO(YUO~Os'UO!S'TO!['XO(e'SO!^(iP!^(xP~P@nOn'bO!_'`O(T%gO~Oe'gO!l%eO(T%gO~O!Q&SO!l&RO~Os!nO!S!oO!|<VO#T!pO#U!pO#W!pO#X!pO(U!lO(VTO(YUO(e!mO(o!sO~O!b'mO!c'lO!d'lO#V!pO#['nO#]'nO~PBYOa%nOh%VO!g#vO!l%eO'z%nO(r'pO~O!p'tO#`'rO~PChOs!nO!S!oO(VTO(YUO(e!mO(o!sO~O!_XOs(mX!S(mX!b(mX!c(mX!d(mX!|(mX#T(mX#U(mX#V(mX#W(mX#X(mX#[(mX#](mX(U(mX(V(mX(Y(mX(e(mX(o(mX~O!c'lO!d'lO(U!lO~PDWO(P'xO(Q'xO(R'zO~O_!}O(V'|O(W!}O(X'|O~O_#QO(X'|O(Y'|O(Z#QO~Ov(OO~P%[Ox#SO!U#TO(b#TO(c(RO~O![(TO!Y'WX!Y'^X!]'WX!]'^X~P+}O!](VO!Y(hX~OP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!](VO!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO#x$UO#z$WO#{$XO(aVO(r$YO(y#|O(z#}O~O!Y(hX~PHRO!Y([O~O!Y(uX!](uX!g(uX!k(uX(r(uX~O#`(uX#k#dX!^(uX~PJUO#`(]O!Y(wX!](wX~O!](^O!Y(vX~O!Y(aO~O#`$eO~PJUO!^(bO~P`OR#zO!Q#yO!S#{O!l#xO(aVOP!na[!naj!nar!na!]!na!p!na#R!na#n!na#o!na#p!na#q!na#r!na#s!na#t!na#u!na#v!na#x!na#z!na#{!na(r!na(y!na(z!na~Oa!na'z!na'w!na!Y!na!k!nav!na!_!na%i!na!g!na~PKlO!k(cO~O!g#vO#`(dO(r'pO!](tXa(tX'z(tX~O!k(tX~PNXO!S%hO!_%iO!|]O#i(iO#j(hO(T%gO~O!](jO!k(sX~O!k(lO~O!S%hO!_%iO#j(hO(T%gO~OP(gXR(gX[(gXj(gXr(gX!Q(gX!S(gX!](gX!l(gX!p(gX#R(gX#n(gX#o(gX#p(gX#q(gX#r(gX#s(gX#t(gX#u(gX#v(gX#x(gX#z(gX#{(gX(a(gX(r(gX(y(gX(z(gX~O!g#vO!k(gX~P! uOR(nO!Q(mO!l#xO#S$dO!|!{a!S!{a~O!x!{a%h!{a!_!{a#i!{a#j!{a(T!{a~P!#vO!x(rO~OPYOQYOSfOd!jOe!iOpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_XO!iuO!lZO!oYO!pYO!qYO!svO!u!gO!x!hO$W!kO$niO(T!dO(VTO(YUO(aVO(o[O~Oh%VOp%WOr%XOs$tOt$tOz%YO|%ZO!O<sO!S${O!_$|O!i>VO!l$xO#j<yO$W%`O$t<uO$v<wO$y%aO(T(vO(VTO(YUO(a$uO(y$}O(z%PO~O#k(xO~O![(zO!k(kP~P%[O(e(|O(o[O~O!S)OO!l#xO(e(|O(o[O~OP<UOQ<UOSfOd>ROe!iOpkOr<UOskOtkOzkO|<UO!O<UO!SWO!WkO!XkO!_!eO!i<XO!lZO!o<UO!p<UO!q<UO!s<YO!u<]O!x!hO$W!kO$n>PO(T)]O(VTO(YUO(aVO(o[O~O!]$_Oa$qa'z$qa'w$qa!k$qa!Y$qa!_$qa%i$qa!g$qa~Ol)dO~P!&zOh%VOp%WOr%XOs$tOt$tOz%YO|%ZO!O%]O!S${O!_$|O!i%bO!l$xO#j%cO$W%`O$t%^O$v%_O$y%aO(T(vO(VTO(YUO(a$uO(y$}O(z%PO~Og(pP~P!,TO!Q)iO!g)hO!_$^X$Z$^X$]$^X$_$^X$f$^X~O!g)hO!_({X$Z({X$]({X$_({X$f({X~O!Q)iO~P!.^O!Q)iO!_({X$Z({X$]({X$_({X$f({X~O!_)kO$Z)oO$])jO$_)jO$f)pO~O![)sO~P!)[O$]$hO$_$gO$f)wO~On$zX!Q$zX#S$zX'y$zX(y$zX(z$zX~OgmXg$zXnmX!]mX#`mX~P!0SOx)yO(b)zO(c)|O~On*VO!Q*OO'y*PO(y$}O(z%PO~Og)}O~P!1WOg*WO~Oh%VOr%XOs$tOt$tOz%YO|%ZO!O<sO!S*YO!_*ZO!i>VO!l$xO#j<yO$W%`O$t<uO$v<wO$y%aO(VTO(YUO(a$uO(y$}O(z%PO~Op*`O![*^O(T*XO!k)OP~P!1uO#k*aO~O!l*bO~Oh%VOp%WOr%XOs$tOt$tOz%YO|%ZO!O<sO!S${O!_$|O!i>VO!l$xO#j<yO$W%`O$t<uO$v<wO$y%aO(T*dO(VTO(YUO(a$uO(y$}O(z%PO~O![*gO!Y)PP~P!3tOr*sOs!nO!S*iO!b*qO!c*kO!d*kO!l*bO#[*rO%`*mO(U!lO(VTO(YUO(e!mO~O!^*pO~P!5iO#S$dOn(`X!Q(`X'y(`X(y(`X(z(`X!](`X#`(`X~Og(`X$O(`X~P!6kOn*xO#`*wOg(_X!](_X~O!]*yOg(^X~Oj%dOk%dOl%dO(T&ZOg(^P~Os*|O~Og)}O(T&ZO~O!l+SO~O(T(vO~Op+WO!S%hO![#iO!_%iO!|]O#i#lO#j#iO(T%gO!k(sP~O!g#vO#k+XO~O!S%hO![+ZO!](^O!_%iO(T%gO!Y(vP~Os'[O!S+]O![+[O(VTO(YUO(e(|O~O!^(xP~P!9|O!]+^Oa)TX'z)TX~OP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO#x$UO#z$WO#{$XO(aVO(r$YO(y#|O(z#}O~Oa!ja!]!ja'z!ja'w!ja!Y!ja!k!jav!ja!_!ja%i!ja!g!ja~P!:tOR#zO!Q#yO!S#{O!l#xO(aVOP!ra[!raj!rar!ra!]!ra!p!ra#R!ra#n!ra#o!ra#p!ra#q!ra#r!ra#s!ra#t!ra#u!ra#v!ra#x!ra#z!ra#{!ra(r!ra(y!ra(z!ra~Oa!ra'z!ra'w!ra!Y!ra!k!rav!ra!_!ra%i!ra!g!ra~P!=[OR#zO!Q#yO!S#{O!l#xO(aVOP!ta[!taj!tar!ta!]!ta!p!ta#R!ta#n!ta#o!ta#p!ta#q!ta#r!ta#s!ta#t!ta#u!ta#v!ta#x!ta#z!ta#{!ta(r!ta(y!ta(z!ta~Oa!ta'z!ta'w!ta!Y!ta!k!tav!ta!_!ta%i!ta!g!ta~P!?rOh%VOn+gO!_'`O%i+fO~O!g+iOa(]X!_(]X'z(]X!](]X~Oa%nO!_XO'z%nO~Oh%VO!l%eO~Oh%VO!l%eO(T%gO~O!g#vO#k(xO~Ob+tO%j+uO(T+qO(VTO(YUO!^)XP~O!]+vO`)WX~O[+zO~O`+{O~O!_&PO(T%gO(U!lO`)WP~O%j,OO~P;SOh%VO#`,SO~Oh%VOn,VO!_$|O~O!_,XO~O!Q,ZO!_XO~O%n%vO~O!x,`O~Oe,eO~Ob,fO(T#nO(VTO(YUO!^)VP~Oe%}O~O%j!QO(T&ZO~P=gO[,kO`,jO~OPYOQYOSfOdzOeyOpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!iuO!lZO!oYO!pYO!qYO!svO!xxO!|]O$niO%h}O(VTO(YUO(aVO(o[O~O!_!eO!u!gO$W!kO(T!dO~P!FyO`,jOa%nO'z%nO~OPYOQYOSfOd!jOe!iOpkOrYOskOtkOzkO|YO!OYO!SWO!WkO!XkO!_!eO!iuO!lZO!oYO!pYO!qYO!svO!x!hO$W!kO$niO(T!dO(VTO(YUO(aVO(o[O~Oa,pOl!OO!uwO%l!OO%m!OO%n!OO~P!IcO!l&oO~O&^,vO~O!_,xO~O&o,zO&q,{OP&laQ&laS&laY&laa&lad&lae&lal&lap&lar&las&lat&laz&la|&la!O&la!S&la!W&la!X&la!_&la!i&la!l&la!o&la!p&la!q&la!s&la!u&la!x&la!|&la$W&la$n&la%h&la%j&la%l&la%m&la%n&la%q&la%s&la%v&la%w&la%y&la&W&la&^&la&`&la&b&la&d&la&g&la&m&la&s&la&u&la&w&la&y&la&{&la'w&la(T&la(V&la(Y&la(a&la(o&la!^&la&e&lab&la&j&la~O(T-QO~Oh!eX!]!RX!^!RX!g!RX!g!eX!l!eX#`!RX~O!]!eX!^!eX~P#!iO!g-VO#`-UOh(jX!]#hX!^#hX!g(jX!l(jX~O!](jX!^(jX~P##[Oh%VO!g-XO!l%eO!]!aX!^!aX~Os!nO!S!oO(VTO(YUO(e!mO~OP<UOQ<UOSfOd>ROe!iOpkOr<UOskOtkOzkO|<UO!O<UO!SWO!WkO!XkO!_!eO!i<XO!lZO!o<UO!p<UO!q<UO!s<YO!u<]O!x!hO$W!kO$n>PO(VTO(YUO(aVO(o[O~O(T=QO~P#$qO!]-]O!^(iX~O!^-_O~O!g-VO#`-UO!]#hX!^#hX~O!]-`O!^(xX~O!^-bO~O!c-cO!d-cO(U!lO~P#$`O!^-fO~P'_On-iO!_'`O~O!Y-nO~Os!{a!b!{a!c!{a!d!{a#T!{a#U!{a#V!{a#W!{a#X!{a#[!{a#]!{a(U!{a(V!{a(Y!{a(e!{a(o!{a~P!#vO!p-sO#`-qO~PChO!c-uO!d-uO(U!lO~PDWOa%nO#`-qO'z%nO~Oa%nO!g#vO#`-qO'z%nO~Oa%nO!g#vO!p-sO#`-qO'z%nO(r'pO~O(P'xO(Q'xO(R-zO~Ov-{O~O!Y'Wa!]'Wa~P!:tO![.PO!Y'WX!]'WX~P%[O!](VO!Y(ha~O!Y(ha~PHRO!](^O!Y(va~O!S%hO![.TO!_%iO(T%gO!Y'^X!]'^X~O#`.VO!](ta!k(taa(ta'z(ta~O!g#vO~P#,wO!](jO!k(sa~O!S%hO!_%iO#j.ZO(T%gO~Op.`O!S%hO![.]O!_%iO!|]O#i._O#j.]O(T%gO!]'aX!k'aX~OR.dO!l#xO~Oh%VOn.gO!_'`O%i.fO~Oa#ci!]#ci'z#ci'w#ci!Y#ci!k#civ#ci!_#ci%i#ci!g#ci~P!:tOn>]O!Q*OO'y*PO(y$}O(z%PO~O#k#_aa#_a#`#_a'z#_a!]#_a!k#_a!_#_a!Y#_a~P#/sO#k(`XP(`XR(`X[(`Xa(`Xj(`Xr(`X!S(`X!l(`X!p(`X#R(`X#n(`X#o(`X#p(`X#q(`X#r(`X#s(`X#t(`X#u(`X#v(`X#x(`X#z(`X#{(`X'z(`X(a(`X(r(`X!k(`X!Y(`X'w(`Xv(`X!_(`X%i(`X!g(`X~P!6kO!].tO!k(kX~P!:tO!k.wO~O!Y.yO~OP$[OR#zO!Q#yO!S#{O!l#xO!p$[O(aVO[#mia#mij#mir#mi!]#mi#R#mi#o#mi#p#mi#q#mi#r#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#n#mi~P#3cO#n$OO~P#3cOP$[OR#zOr$aO!Q#yO!S#{O!l#xO!p$[O#n$OO#o$PO#p$PO#q$PO(aVO[#mia#mij#mi!]#mi#R#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#r#mi~P#6QO#r$QO~P#6QOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO(aVOa#mi!]#mi#x#mi#z#mi#{#mi'z#mi(r#mi(y#mi(z#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#v#mi~P#8oOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO(aVO(z#}Oa#mi!]#mi#z#mi#{#mi'z#mi(r#mi(y#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#x$UO~P#;VO#x#mi~P#;VO#v$SO~P#8oOP$[OR#zO[$cOj$ROr$aO!Q#yO!S#{O!l#xO!p$[O#R$RO#n$OO#o$PO#p$PO#q$PO#r$QO#s$RO#t$RO#u$bO#v$SO#x$UO(aVO(y#|O(z#}Oa#mi!]#mi#{#mi'z#mi(r#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~O#z#mi~P#={O#z$WO~P#={OP]XR]X[]Xj]Xr]X!Q]X!S]X!l]X!p]X#R]X#S]X#`]X#kfX#n]X#o]X#p]X#q]X#r]X#s]X#t]X#u]X#v]X#x]X#z]X#{]X$Q]X(a]X(r]X(y]X(z]X!]]X!^]X~O$O]X~P#@jOP$[OR#zO[<mOj<bOr<kO!Q#yO!S#{O!l#xO!p$[O#R<bO#n<_O#o<`O#p<`O#q<`O#r<aO#s<bO#t<bO#u<lO#v<cO#x<eO#z<gO#{<hO(aVO(r$YO(y#|O(z#}O~O$O.{O~P#BwO#S$dO#`<nO$Q<nO$O(gX!^(gX~P! uOa'da!]'da'z'da'w'da!k'da!Y'dav'da!_'da%i'da!g'da~P!:tO[#mia#mij#mir#mi!]#mi#R#mi#r#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi'z#mi(r#mi'w#mi!Y#mi!k#miv#mi!_#mi%i#mi!g#mi~OP$[OR#zO!Q#yO!S#{O!l#xO!p$[O#n$OO#o$PO#p$PO#q$PO(aVO(y#mi(z#mi~P#EyOn>]O!Q*OO'y*PO(y$}O(z%POP#miR#mi!S#mi!l#mi!p#mi#n#mi#o#mi#p#mi#q#mi(a#mi~P#EyO!]/POg(pX~P!1WOg/RO~Oa$Pi!]$Pi'z$Pi'w$Pi!Y$Pi!k$Piv$Pi!_$Pi%i$Pi!g$Pi~P!:tO$]/SO$_/SO~O$]/TO$_/TO~O!g)hO#`/UO!_$cX$Z$cX$]$cX$_$cX$f$cX~O![/VO~O!_)kO$Z/XO$])jO$_)jO$f/YO~O!]<iO!^(fX~P#BwO!^/ZO~O!g)hO$f({X~O$f/]O~Ov/^O~P!&zOx)yO(b)zO(c/aO~O!S/dO~O(y$}On%aa!Q%aa'y%aa(z%aa!]%aa#`%aa~Og%aa$O%aa~P#L{O(z%POn%ca!Q%ca'y%ca(y%ca!]%ca#`%ca~Og%ca$O%ca~P#MnO!]fX!gfX!kfX!k$zX(rfX~P!0SOp%WO![/mO!](^O(T/lO!Y(vP!Y)PP~P!1uOr*sO!b*qO!c*kO!d*kO!l*bO#[*rO%`*mO(U!lO(VTO(YUO~Os<}O!S/nO![+[O!^*pO(e<|O!^(xP~P$ [O!k/oO~P#/sO!]/pO!g#vO(r'pO!k)OX~O!k/uO~OnoX!QoX'yoX(yoX(zoX~O!g#vO!koX~P$#OOp/wO!S%hO![*^O!_%iO(T%gO!k)OP~O#k/xO~O!Y$zX!]$zX!g%RX~P!0SO!]/yO!Y)PX~P#/sO!g/{O~O!Y/}O~OpkO(T0OO~P.iOh%VOr0TO!g#vO!l%eO(r'pO~O!g+iO~Oa%nO!]0XO'z%nO~O!^0ZO~P!5iO!c0[O!d0[O(U!lO~P#$`Os!nO!S0]O(VTO(YUO(e!mO~O#[0_O~Og%aa!]%aa#`%aa$O%aa~P!1WOg%ca!]%ca#`%ca$O%ca~P!1WOj%dOk%dOl%dO(T&ZOg'mX!]'mX~O!]*yOg(^a~Og0hO~On0jO#`0iOg(_a!](_a~OR0kO!Q0kO!S0lO#S$dOn}a'y}a(y}a(z}a!]}a#`}a~Og}a$O}a~P$(cO!Q*OO'y*POn$sa(y$sa(z$sa!]$sa#`$sa~Og$sa$O$sa~P$)_O!Q*OO'y*POn$ua(y$ua(z$ua!]$ua#`$ua~Og$ua$O$ua~P$*QO#k0oO~Og%Ta!]%Ta#`%Ta$O%Ta~P!1WO!g#vO~O#k0rO~O!]+^Oa)Ta'z)Ta~OR#zO!Q#yO!S#{O!l#xO(aVOP!ri[!rij!rir!ri!]!ri!p!ri#R!ri#n!ri#o!ri#p!ri#q!ri#r!ri#s!ri#t!ri#u!ri#v!ri#x!ri#z!ri#{!ri(r!ri(y!ri(z!ri~Oa!ri'z!ri'w!ri!Y!ri!k!riv!ri!_!ri%i!ri!g!ri~P$+oOh%VOr%XOs$tOt$tOz%YO|%ZO!O<sO!S${O!_$|O!i>VO!l$xO#j<yO$W%`O$t<uO$v<wO$y%aO(VTO(YUO(a$uO(y$}O(z%PO~Op0{O%]0|O(T0zO~P$.VO!g+iOa(]a!_(]a'z(]a!](]a~O#k1SO~O[]X!]fX!^fX~O!]1TO!^)XX~O!^1VO~O[1WO~Ob1YO(T+qO(VTO(YUO~O!_&PO(T%gO`'uX!]'uX~O!]+vO`)Wa~O!k1]O~P!:tO[1`O~O`1aO~O#`1fO~On1iO!_$|O~O(e(|O!^)UP~Oh%VOn1rO!_1oO%i1qO~O[1|O!]1zO!^)VX~O!^1}O~O`2POa%nO'z%nO~O(T#nO(VTO(YUO~O#S$dO#`$eO$Q$eOP(gXR(gX[(gXr(gX!Q(gX!S(gX!](gX!l(gX!p(gX#R(gX#n(gX#o(gX#p(gX#q(gX#r(gX#s(gX#t(gX#u(gX#v(gX#x(gX#z(gX#{(gX(a(gX(r(gX(y(gX(z(gX~Oj2SO&[2TOa(gX~P$3pOj2SO#`$eO&[2TO~Oa2VO~P%[Oa2XO~O&e2[OP&ciQ&ciS&ciY&cia&cid&cie&cil&cip&cir&cis&cit&ciz&ci|&ci!O&ci!S&ci!W&ci!X&ci!_&ci!i&ci!l&ci!o&ci!p&ci!q&ci!s&ci!u&ci!x&ci!|&ci$W&ci$n&ci%h&ci%j&ci%l&ci%m&ci%n&ci%q&ci%s&ci%v&ci%w&ci%y&ci&W&ci&^&ci&`&ci&b&ci&d&ci&g&ci&m&ci&s&ci&u&ci&w&ci&y&ci&{&ci'w&ci(T&ci(V&ci(Y&ci(a&ci(o&ci!^&cib&ci&j&ci~Ob2bO!^2`O&j2aO~P`O!_XO!l2dO~O&q,{OP&liQ&liS&liY&lia&lid&lie&lil&lip&lir&lis&lit&liz&li|&li!O&li!S&li!W&li!X&li!_&li!i&li!l&li!o&li!p&li!q&li!s&li!u&li!x&li!|&li$W&li$n&li%h&li%j&li%l&li%m&li%n&li%q&li%s&li%v&li%w&li%y&li&W&li&^&li&`&li&b&li&d&li&g&li&m&li&s&li&u&li&w&li&y&li&{&li'w&li(T&li(V&li(Y&li(a&li(o&li!^&li&e&lib&li&j&li~O!Y2jO~O!]!aa!^!aa~P#BwOs!nO!S!oO![2pO(e!mO!]'XX!^'XX~P@nO!]-]O!^(ia~O!]'_X!^'_X~P!9|O!]-`O!^(xa~O!^2wO~P'_Oa%nO#`3QO'z%nO~Oa%nO!g#vO#`3QO'z%nO~Oa%nO!g#vO!p3UO#`3QO'z%nO(r'pO~Oa%nO'z%nO~P!:tO!]$_Ov$qa~O!Y'Wi!]'Wi~P!:tO!](VO!Y(hi~O!](^O!Y(vi~O!Y(wi!](wi~P!:tO!](ti!k(tia(ti'z(ti~P!:tO#`3WO!](ti!k(tia(ti'z(ti~O!](jO!k(si~O!S%hO!_%iO!|]O#i3]O#j3[O(T%gO~O!S%hO!_%iO#j3[O(T%gO~On3dO!_'`O%i3cO~Oh%VOn3dO!_'`O%i3cO~O#k%aaP%aaR%aa[%aaa%aaj%aar%aa!S%aa!l%aa!p%aa#R%aa#n%aa#o%aa#p%aa#q%aa#r%aa#s%aa#t%aa#u%aa#v%aa#x%aa#z%aa#{%aa'z%aa(a%aa(r%aa!k%aa!Y%aa'w%aav%aa!_%aa%i%aa!g%aa~P#L{O#k%caP%caR%ca[%caa%caj%car%ca!S%ca!l%ca!p%ca#R%ca#n%ca#o%ca#p%ca#q%ca#r%ca#s%ca#t%ca#u%ca#v%ca#x%ca#z%ca#{%ca'z%ca(a%ca(r%ca!k%ca!Y%ca'w%cav%ca!_%ca%i%ca!g%ca~P#MnO#k%aaP%aaR%aa[%aaa%aaj%aar%aa!S%aa!]%aa!l%aa!p%aa#R%aa#n%aa#o%aa#p%aa#q%aa#r%aa#s%aa#t%aa#u%aa#v%aa#x%aa#z%aa#{%aa'z%aa(a%aa(r%aa!k%aa!Y%aa'w%aa#`%aav%aa!_%aa%i%aa!g%aa~P#/sO#k%caP%caR%ca[%caa%caj%car%ca!S%ca!]%ca!l%ca!p%ca#R%ca#n%ca#o%ca#p%ca#q%ca#r%ca#s%ca#t%ca#u%ca#v%ca#x%ca#z%ca#{%ca'z%ca(a%ca(r%ca!k%ca!Y%ca'w%ca#`%cav%ca!_%ca%i%ca!g%ca~P#/sO#k}aP}a[}aa}aj}ar}a!l}a!p}a#R}a#n}a#o}a#p}a#q}a#r}a#s}a#t}a#u}a#v}a#x}a#z}a#{}a'z}a(a}a(r}a!k}a!Y}a'w}av}a!_}a%i}a!g}a~P$(cO#k$saP$saR$sa[$saa$saj$sar$sa!S$sa!l$sa!p$sa#R$sa#n$sa#o$sa#p$sa#q$sa#r$sa#s$sa#t$sa#u$sa#v$sa#x$sa#z$sa#{$sa'z$sa(a$sa(r$sa!k$sa!Y$sa'w$sav$sa!_$sa%i$sa!g$sa~P$)_O#k$uaP$uaR$ua[$uaa$uaj$uar$ua!S$ua!l$ua!p$ua#R$ua#n$ua#o$ua#p$ua#q$ua#r$ua#s$ua#t$ua#u$ua#v$ua#x$ua#z$ua#{$ua'z$ua(a$ua(r$ua!k$ua!Y$ua'w$uav$ua!_$ua%i$ua!g$ua~P$*QO#k%TaP%TaR%Ta[%Taa%Taj%Tar%Ta!S%Ta!]%Ta!l%Ta!p%Ta#R%Ta#n%Ta#o%Ta#p%Ta#q%Ta#r%Ta#s%Ta#t%Ta#u%Ta#v%Ta#x%Ta#z%Ta#{%Ta'z%Ta(a%Ta(r%Ta!k%Ta!Y%Ta'w%Ta#`%Tav%Ta!_%Ta%i%Ta!g%Ta~P#/sOa#cq!]#cq'z#cq'w#cq!Y#cq!k#cqv#cq!_#cq%i#cq!g#cq~P!:tO![3lO!]'YX!k'YX~P%[O!].tO!k(ka~O!].tO!k(ka~P!:tO!Y3oO~O$O!na!^!na~PKlO$O!ja!]!ja!^!ja~P#BwO$O!ra!^!ra~P!=[O$O!ta!^!ta~P!?rOg']X!]']X~P!,TO!]/POg(pa~OSfO!_4TO$d4UO~O!^4YO~Ov4ZO~P#/sOa$mq!]$mq'z$mq'w$mq!Y$mq!k$mqv$mq!_$mq%i$mq!g$mq~P!:tO!Y4]O~P!&zO!S4^O~O!Q*OO'y*PO(z%POn'ia(y'ia!]'ia#`'ia~Og'ia$O'ia~P%-fO!Q*OO'y*POn'ka(y'ka(z'ka!]'ka#`'ka~Og'ka$O'ka~P%.XO(r$YO~P#/sO!YfX!Y$zX!]fX!]$zX!g%RX#`fX~P!0SOp%WO(T=WO~P!1uOp4bO!S%hO![4aO!_%iO(T%gO!]'eX!k'eX~O!]/pO!k)Oa~O!]/pO!g#vO!k)Oa~O!]/pO!g#vO(r'pO!k)Oa~Og$|i!]$|i#`$|i$O$|i~P!1WO![4jO!Y'gX!]'gX~P!3tO!]/yO!Y)Pa~O!]/yO!Y)Pa~P#/sOP]XR]X[]Xj]Xr]X!Q]X!S]X!Y]X!]]X!l]X!p]X#R]X#S]X#`]X#kfX#n]X#o]X#p]X#q]X#r]X#s]X#t]X#u]X#v]X#x]X#z]X#{]X$Q]X(a]X(r]X(y]X(z]X~Oj%YX!g%YX~P%2OOj4oO!g#vO~Oh%VO!g#vO!l%eO~Oh%VOr4tO!l%eO(r'pO~Or4yO!g#vO(r'pO~Os!nO!S4zO(VTO(YUO(e!mO~O(y$}On%ai!Q%ai'y%ai(z%ai!]%ai#`%ai~Og%ai$O%ai~P%5oO(z%POn%ci!Q%ci'y%ci(y%ci!]%ci#`%ci~Og%ci$O%ci~P%6bOg(_i!](_i~P!1WO#`5QOg(_i!](_i~P!1WO!k5VO~Oa$oq!]$oq'z$oq'w$oq!Y$oq!k$oqv$oq!_$oq%i$oq!g$oq~P!:tO!Y5ZO~O!]5[O!_)QX~P#/sOa$zX!_$zX%^]X'z$zX!]$zX~P!0SO%^5_OaoX!_oX'zoX!]oX~P$#OOp5`O(T#nO~O%^5_O~Ob5fO%j5gO(T+qO(VTO(YUO!]'tX!^'tX~O!]1TO!^)Xa~O[5kO~O`5lO~O[5pO~Oa%nO'z%nO~P#/sO!]5uO#`5wO!^)UX~O!^5xO~Or6OOs!nO!S*iO!b!yO!c!vO!d!vO!|<VO#T!pO#U!pO#V!pO#W!pO#X!pO#[5}O#]!zO(U!lO(VTO(YUO(e!mO(o!sO~O!^5|O~P%;eOn6TO!_1oO%i6SO~Oh%VOn6TO!_1oO%i6SO~Ob6[O(T#nO(VTO(YUO!]'sX!^'sX~O!]1zO!^)Va~O(VTO(YUO(e6^O~O`6bO~Oj6eO&[6fO~PNXO!k6gO~P%[Oa6iO~Oa6iO~P%[Ob2bO!^6nO&j2aO~P`O!g6pO~O!g6rOh(ji!](ji!^(ji!g(ji!l(jir(ji(r(ji~O!]#hi!^#hi~P#BwO#`6sO!]#hi!^#hi~O!]!ai!^!ai~P#BwOa%nO#`6|O'z%nO~Oa%nO!g#vO#`6|O'z%nO~O!](tq!k(tqa(tq'z(tq~P!:tO!](jO!k(sq~O!S%hO!_%iO#j7TO(T%gO~O!_'`O%i7WO~On7[O!_'`O%i7WO~O#k'iaP'iaR'ia['iaa'iaj'iar'ia!S'ia!l'ia!p'ia#R'ia#n'ia#o'ia#p'ia#q'ia#r'ia#s'ia#t'ia#u'ia#v'ia#x'ia#z'ia#{'ia'z'ia(a'ia(r'ia!k'ia!Y'ia'w'iav'ia!_'ia%i'ia!g'ia~P%-fO#k'kaP'kaR'ka['kaa'kaj'kar'ka!S'ka!l'ka!p'ka#R'ka#n'ka#o'ka#p'ka#q'ka#r'ka#s'ka#t'ka#u'ka#v'ka#x'ka#z'ka#{'ka'z'ka(a'ka(r'ka!k'ka!Y'ka'w'kav'ka!_'ka%i'ka!g'ka~P%.XO#k$|iP$|iR$|i[$|ia$|ij$|ir$|i!S$|i!]$|i!l$|i!p$|i#R$|i#n$|i#o$|i#p$|i#q$|i#r$|i#s$|i#t$|i#u$|i#v$|i#x$|i#z$|i#{$|i'z$|i(a$|i(r$|i!k$|i!Y$|i'w$|i#`$|iv$|i!_$|i%i$|i!g$|i~P#/sO#k%aiP%aiR%ai[%aia%aij%air%ai!S%ai!l%ai!p%ai#R%ai#n%ai#o%ai#p%ai#q%ai#r%ai#s%ai#t%ai#u%ai#v%ai#x%ai#z%ai#{%ai'z%ai(a%ai(r%ai!k%ai!Y%ai'w%aiv%ai!_%ai%i%ai!g%ai~P%5oO#k%ciP%ciR%ci[%cia%cij%cir%ci!S%ci!l%ci!p%ci#R%ci#n%ci#o%ci#p%ci#q%ci#r%ci#s%ci#t%ci#u%ci#v%ci#x%ci#z%ci#{%ci'z%ci(a%ci(r%ci!k%ci!Y%ci'w%civ%ci!_%ci%i%ci!g%ci~P%6bO!]'Ya!k'Ya~P!:tO!].tO!k(ki~O$O#ci!]#ci!^#ci~P#BwOP$[OR#zO!Q#yO!S#{O!l#xO!p$[O(aVO[#mij#mir#mi#R#mi#o#mi#p#mi#q#mi#r#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi$O#mi(r#mi(y#mi(z#mi!]#mi!^#mi~O#n#mi~P%NdO#n<_O~P%NdOP$[OR#zOr<kO!Q#yO!S#{O!l#xO!p$[O#n<_O#o<`O#p<`O#q<`O(aVO[#mij#mi#R#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi$O#mi(r#mi(y#mi(z#mi!]#mi!^#mi~O#r#mi~P&!lO#r<aO~P&!lOP$[OR#zO[<mOj<bOr<kO!Q#yO!S#{O!l#xO!p$[O#R<bO#n<_O#o<`O#p<`O#q<`O#r<aO#s<bO#t<bO#u<lO(aVO#x#mi#z#mi#{#mi$O#mi(r#mi(y#mi(z#mi!]#mi!^#mi~O#v#mi~P&$tOP$[OR#zO[<mOj<bOr<kO!Q#yO!S#{O!l#xO!p$[O#R<bO#n<_O#o<`O#p<`O#q<`O#r<aO#s<bO#t<bO#u<lO#v<cO(aVO(z#}O#z#mi#{#mi$O#mi(r#mi(y#mi!]#mi!^#mi~O#x<eO~P&&uO#x#mi~P&&uO#v<cO~P&$tOP$[OR#zO[<mOj<bOr<kO!Q#yO!S#{O!l#xO!p$[O#R<bO#n<_O#o<`O#p<`O#q<`O#r<aO#s<bO#t<bO#u<lO#v<cO#x<eO(aVO(y#|O(z#}O#{#mi$O#mi(r#mi!]#mi!^#mi~O#z#mi~P&)UO#z<gO~P&)UOa#|y!]#|y'z#|y'w#|y!Y#|y!k#|yv#|y!_#|y%i#|y!g#|y~P!:tO[#mij#mir#mi#R#mi#r#mi#s#mi#t#mi#u#mi#v#mi#x#mi#z#mi#{#mi$O#mi(r#mi!]#mi!^#mi~OP$[OR#zO!Q#yO!S#{O!l#xO!p$[O#n<_O#o<`O#p<`O#q<`O(aVO(y#mi(z#mi~P&,QOn>^O!Q*OO'y*PO(y$}O(z%POP#miR#mi!S#mi!l#mi!p#mi#n#mi#o#mi#p#mi#q#mi(a#mi~P&,QO#S$dOP(`XR(`X[(`Xj(`Xn(`Xr(`X!Q(`X!S(`X!l(`X!p(`X#R(`X#n(`X#o(`X#p(`X#q(`X#r(`X#s(`X#t(`X#u(`X#v(`X#x(`X#z(`X#{(`X$O(`X'y(`X(a(`X(r(`X(y(`X(z(`X!](`X!^(`X~O$O$Pi!]$Pi!^$Pi~P#BwO$O!ri!^!ri~P$+oOg']a!]']a~P!1WO!^7nO~O!]'da!^'da~P#BwO!Y7oO~P#/sO!g#vO(r'pO!]'ea!k'ea~O!]/pO!k)Oi~O!]/pO!g#vO!k)Oi~Og$|q!]$|q#`$|q$O$|q~P!1WO!Y'ga!]'ga~P#/sO!g7vO~O!]/yO!Y)Pi~P#/sO!]/yO!Y)Pi~O!Y7yO~Oh%VOr8OO!l%eO(r'pO~Oj8QO!g#vO~Or8TO!g#vO(r'pO~O!Q*OO'y*PO(z%POn'ja(y'ja!]'ja#`'ja~Og'ja$O'ja~P&5RO!Q*OO'y*POn'la(y'la(z'la!]'la#`'la~Og'la$O'la~P&5tOg(_q!](_q~P!1WO#`8VOg(_q!](_q~P!1WO!Y8WO~Og%Oq!]%Oq#`%Oq$O%Oq~P!1WOa$oy!]$oy'z$oy'w$oy!Y$oy!k$oyv$oy!_$oy%i$oy!g$oy~P!:tO!g6rO~O!]5[O!_)Qa~O!_'`OP$TaR$Ta[$Taj$Tar$Ta!Q$Ta!S$Ta!]$Ta!l$Ta!p$Ta#R$Ta#n$Ta#o$Ta#p$Ta#q$Ta#r$Ta#s$Ta#t$Ta#u$Ta#v$Ta#x$Ta#z$Ta#{$Ta(a$Ta(r$Ta(y$Ta(z$Ta~O%i7WO~P&8fO%^8[Oa%[i!_%[i'z%[i!]%[i~Oa#cy!]#cy'z#cy'w#cy!Y#cy!k#cyv#cy!_#cy%i#cy!g#cy~P!:tO[8^O~Ob8`O(T+qO(VTO(YUO~O!]1TO!^)Xi~O`8dO~O(e(|O!]'pX!^'pX~O!]5uO!^)Ua~O!^8nO~P%;eO(o!sO~P$&YO#[8oO~O!_1oO~O!_1oO%i8qO~On8tO!_1oO%i8qO~O[8yO!]'sa!^'sa~O!]1zO!^)Vi~O!k8}O~O!k9OO~O!k9RO~O!k9RO~P%[Oa9TO~O!g9UO~O!k9VO~O!](wi!^(wi~P#BwOa%nO#`9_O'z%nO~O!](ty!k(tya(ty'z(ty~P!:tO!](jO!k(sy~O%i9bO~P&8fO!_'`O%i9bO~O#k$|qP$|qR$|q[$|qa$|qj$|qr$|q!S$|q!]$|q!l$|q!p$|q#R$|q#n$|q#o$|q#p$|q#q$|q#r$|q#s$|q#t$|q#u$|q#v$|q#x$|q#z$|q#{$|q'z$|q(a$|q(r$|q!k$|q!Y$|q'w$|q#`$|qv$|q!_$|q%i$|q!g$|q~P#/sO#k'jaP'jaR'ja['jaa'jaj'jar'ja!S'ja!l'ja!p'ja#R'ja#n'ja#o'ja#p'ja#q'ja#r'ja#s'ja#t'ja#u'ja#v'ja#x'ja#z'ja#{'ja'z'ja(a'ja(r'ja!k'ja!Y'ja'w'jav'ja!_'ja%i'ja!g'ja~P&5RO#k'laP'laR'la['laa'laj'lar'la!S'la!l'la!p'la#R'la#n'la#o'la#p'la#q'la#r'la#s'la#t'la#u'la#v'la#x'la#z'la#{'la'z'la(a'la(r'la!k'la!Y'la'w'lav'la!_'la%i'la!g'la~P&5tO#k%OqP%OqR%Oq[%Oqa%Oqj%Oqr%Oq!S%Oq!]%Oq!l%Oq!p%Oq#R%Oq#n%Oq#o%Oq#p%Oq#q%Oq#r%Oq#s%Oq#t%Oq#u%Oq#v%Oq#x%Oq#z%Oq#{%Oq'z%Oq(a%Oq(r%Oq!k%Oq!Y%Oq'w%Oq#`%Oqv%Oq!_%Oq%i%Oq!g%Oq~P#/sO!]'Yi!k'Yi~P!:tO$O#cq!]#cq!^#cq~P#BwO(y$}OP%aaR%aa[%aaj%aar%aa!S%aa!l%aa!p%aa#R%aa#n%aa#o%aa#p%aa#q%aa#r%aa#s%aa#t%aa#u%aa#v%aa#x%aa#z%aa#{%aa$O%aa(a%aa(r%aa!]%aa!^%aa~On%aa!Q%aa'y%aa(z%aa~P&IyO(z%POP%caR%ca[%caj%car%ca!S%ca!l%ca!p%ca#R%ca#n%ca#o%ca#p%ca#q%ca#r%ca#s%ca#t%ca#u%ca#v%ca#x%ca#z%ca#{%ca$O%ca(a%ca(r%ca!]%ca!^%ca~On%ca!Q%ca'y%ca(y%ca~P&LQOn>^O!Q*OO'y*PO(z%PO~P&IyOn>^O!Q*OO'y*PO(y$}O~P&LQOR0kO!Q0kO!S0lO#S$dOP}a[}aj}an}ar}a!l}a!p}a#R}a#n}a#o}a#p}a#q}a#r}a#s}a#t}a#u}a#v}a#x}a#z}a#{}a$O}a'y}a(a}a(r}a(y}a(z}a!]}a!^}a~O!Q*OO'y*POP$saR$sa[$saj$san$sar$sa!S$sa!l$sa!p$sa#R$sa#n$sa#o$sa#p$sa#q$sa#r$sa#s$sa#t$sa#u$sa#v$sa#x$sa#z$sa#{$sa$O$sa(a$sa(r$sa(y$sa(z$sa!]$sa!^$sa~O!Q*OO'y*POP$uaR$ua[$uaj$uan$uar$ua!S$ua!l$ua!p$ua#R$ua#n$ua#o$ua#p$ua#q$ua#r$ua#s$ua#t$ua#u$ua#v$ua#x$ua#z$ua#{$ua$O$ua(a$ua(r$ua(y$ua(z$ua!]$ua!^$ua~On>^O!Q*OO'y*PO(y$}O(z%PO~OP%TaR%Ta[%Taj%Tar%Ta!S%Ta!l%Ta!p%Ta#R%Ta#n%Ta#o%Ta#p%Ta#q%Ta#r%Ta#s%Ta#t%Ta#u%Ta#v%Ta#x%Ta#z%Ta#{%Ta$O%Ta(a%Ta(r%Ta!]%Ta!^%Ta~P''VO$O$mq!]$mq!^$mq~P#BwO$O$oq!]$oq!^$oq~P#BwO!^9oO~O$O9pO~P!1WO!g#vO!]'ei!k'ei~O!g#vO(r'pO!]'ei!k'ei~O!]/pO!k)Oq~O!Y'gi!]'gi~P#/sO!]/yO!Y)Pq~Or9wO!g#vO(r'pO~O[9yO!Y9xO~P#/sO!Y9xO~Oj:PO!g#vO~Og(_y!](_y~P!1WO!]'na!_'na~P#/sOa%[q!_%[q'z%[q!]%[q~P#/sO[:UO~O!]1TO!^)Xq~O`:YO~O#`:ZO!]'pa!^'pa~O!]5uO!^)Ui~P#BwO!S:]O~O!_1oO%i:`O~O(VTO(YUO(e:eO~O!]1zO!^)Vq~O!k:hO~O!k:iO~O!k:jO~O!k:jO~P%[O#`:mO!]#hy!^#hy~O!]#hy!^#hy~P#BwO%i:rO~P&8fO!_'`O%i:rO~O$O#|y!]#|y!^#|y~P#BwOP$|iR$|i[$|ij$|ir$|i!S$|i!l$|i!p$|i#R$|i#n$|i#o$|i#p$|i#q$|i#r$|i#s$|i#t$|i#u$|i#v$|i#x$|i#z$|i#{$|i$O$|i(a$|i(r$|i!]$|i!^$|i~P''VO!Q*OO'y*PO(z%POP'iaR'ia['iaj'ian'iar'ia!S'ia!l'ia!p'ia#R'ia#n'ia#o'ia#p'ia#q'ia#r'ia#s'ia#t'ia#u'ia#v'ia#x'ia#z'ia#{'ia$O'ia(a'ia(r'ia(y'ia!]'ia!^'ia~O!Q*OO'y*POP'kaR'ka['kaj'kan'kar'ka!S'ka!l'ka!p'ka#R'ka#n'ka#o'ka#p'ka#q'ka#r'ka#s'ka#t'ka#u'ka#v'ka#x'ka#z'ka#{'ka$O'ka(a'ka(r'ka(y'ka(z'ka!]'ka!^'ka~O(y$}OP%aiR%ai[%aij%ain%air%ai!Q%ai!S%ai!l%ai!p%ai#R%ai#n%ai#o%ai#p%ai#q%ai#r%ai#s%ai#t%ai#u%ai#v%ai#x%ai#z%ai#{%ai$O%ai'y%ai(a%ai(r%ai(z%ai!]%ai!^%ai~O(z%POP%ciR%ci[%cij%cin%cir%ci!Q%ci!S%ci!l%ci!p%ci#R%ci#n%ci#o%ci#p%ci#q%ci#r%ci#s%ci#t%ci#u%ci#v%ci#x%ci#z%ci#{%ci$O%ci'y%ci(a%ci(r%ci(y%ci!]%ci!^%ci~O$O$oy!]$oy!^$oy~P#BwO$O#cy!]#cy!^#cy~P#BwO!g#vO!]'eq!k'eq~O!]/pO!k)Oy~O!Y'gq!]'gq~P#/sOr:|O!g#vO(r'pO~O[;QO!Y;PO~P#/sO!Y;PO~Og(_!R!](_!R~P!1WOa%[y!_%[y'z%[y!]%[y~P#/sO!]1TO!^)Xy~O!]5uO!^)Uq~O(T;XO~O!_1oO%i;[O~O!k;_O~O%i;dO~P&8fOP$|qR$|q[$|qj$|qr$|q!S$|q!l$|q!p$|q#R$|q#n$|q#o$|q#p$|q#q$|q#r$|q#s$|q#t$|q#u$|q#v$|q#x$|q#z$|q#{$|q$O$|q(a$|q(r$|q!]$|q!^$|q~P''VO!Q*OO'y*PO(z%POP'jaR'ja['jaj'jan'jar'ja!S'ja!l'ja!p'ja#R'ja#n'ja#o'ja#p'ja#q'ja#r'ja#s'ja#t'ja#u'ja#v'ja#x'ja#z'ja#{'ja$O'ja(a'ja(r'ja(y'ja!]'ja!^'ja~O!Q*OO'y*POP'laR'la['laj'lan'lar'la!S'la!l'la!p'la#R'la#n'la#o'la#p'la#q'la#r'la#s'la#t'la#u'la#v'la#x'la#z'la#{'la$O'la(a'la(r'la(y'la(z'la!]'la!^'la~OP%OqR%Oq[%Oqj%Oqr%Oq!S%Oq!l%Oq!p%Oq#R%Oq#n%Oq#o%Oq#p%Oq#q%Oq#r%Oq#s%Oq#t%Oq#u%Oq#v%Oq#x%Oq#z%Oq#{%Oq$O%Oq(a%Oq(r%Oq!]%Oq!^%Oq~P''VOg%e!Z!]%e!Z#`%e!Z$O%e!Z~P!1WO!Y;hO~P#/sOr;iO!g#vO(r'pO~O[;kO!Y;hO~P#/sO!]'pq!^'pq~P#BwO!]#h!Z!^#h!Z~P#BwO#k%e!ZP%e!ZR%e!Z[%e!Za%e!Zj%e!Zr%e!Z!S%e!Z!]%e!Z!l%e!Z!p%e!Z#R%e!Z#n%e!Z#o%e!Z#p%e!Z#q%e!Z#r%e!Z#s%e!Z#t%e!Z#u%e!Z#v%e!Z#x%e!Z#z%e!Z#{%e!Z'z%e!Z(a%e!Z(r%e!Z!k%e!Z!Y%e!Z'w%e!Z#`%e!Zv%e!Z!_%e!Z%i%e!Z!g%e!Z~P#/sOr;tO!g#vO(r'pO~O!Y;uO~P#/sOr;|O!g#vO(r'pO~O!Y;}O~P#/sOP%e!ZR%e!Z[%e!Zj%e!Zr%e!Z!S%e!Z!l%e!Z!p%e!Z#R%e!Z#n%e!Z#o%e!Z#p%e!Z#q%e!Z#r%e!Z#s%e!Z#t%e!Z#u%e!Z#v%e!Z#x%e!Z#z%e!Z#{%e!Z$O%e!Z(a%e!Z(r%e!Z!]%e!Z!^%e!Z~P''VOr<QO!g#vO(r'pO~Ov(fX~P1qO!Q%rO~P!)[O(U!lO~P!)[O!YfX!]fX#`fX~P%2OOP]XR]X[]Xj]Xr]X!Q]X!S]X!]]X!]fX!l]X!p]X#R]X#S]X#`]X#`fX#kfX#n]X#o]X#p]X#q]X#r]X#s]X#t]X#u]X#v]X#x]X#z]X#{]X$Q]X(a]X(r]X(y]X(z]X~O!gfX!k]X!kfX(rfX~P'LTOP<UOQ<UOSfOd>ROe!iOpkOr<UOskOtkOzkO|<UO!O<UO!SWO!WkO!XkO!_XO!i<XO!lZO!o<UO!p<UO!q<UO!s<YO!u<]O!x!hO$W!kO$n>PO(T)]O(VTO(YUO(aVO(o[O~O!]<iO!^$qa~Oh%VOp%WOr%XOs$tOt$tOz%YO|%ZO!O<tO!S${O!_$|O!i>WO!l$xO#j<zO$W%`O$t<vO$v<xO$y%aO(T(vO(VTO(YUO(a$uO(y$}O(z%PO~Ol)dO~P(!yOr!eX(r!eX~P#!iOr(jX(r(jX~P##[O!^]X!^fX~P'LTO!YfX!Y$zX!]fX!]$zX#`fX~P!0SO#k<^O~O!g#vO#k<^O~O#`<nO~Oj<bO~O#`=OO!](wX!^(wX~O#`<nO!](uX!^(uX~O#k=PO~Og=RO~P!1WO#k=XO~O#k=YO~Og=RO(T&ZO~O!g#vO#k=ZO~O!g#vO#k=PO~O$O=[O~P#BwO#k=]O~O#k=^O~O#k=cO~O#k=dO~O#k=eO~O#k=fO~O$O=gO~P!1WO$O=hO~P!1WOl=sO~P7eOk#S#T#U#W#X#[#i#j#u$n$t$v$y%]%^%h%i%j%q%s%v%w%y%{~(OT#o!X'|(U#ps#n#qr!Q'}$]'}(T$_(e~",
  goto: "$9Y)]PPPPPP)^PP)aP)rP+W/]PPPP6mPP7TPP=QPPP@tPA^PA^PPPA^PCfPA^PA^PA^PCjPCoPD^PIWPPPI[PPPPI[L_PPPLeMVPI[PI[PP! eI[PPPI[PI[P!#lI[P!'S!(X!(bP!)U!)Y!)U!,gPPPPPPP!-W!(XPP!-h!/YP!2iI[I[!2n!5z!:h!:h!>gPPP!>oI[PPPPPPPPP!BOP!C]PPI[!DnPI[PI[I[I[I[I[PI[!FQP!I[P!LbP!Lf!Lp!Lt!LtP!IXP!Lx!LxP#!OP#!SI[PI[#!Y#%_CjA^PA^PA^A^P#&lA^A^#)OA^#+vA^#.SA^A^#.r#1W#1W#1]#1f#1W#1qPP#1WPA^#2ZA^#6YA^A^6mPPP#:_PPP#:x#:xP#:xP#;`#:xPP#;fP#;]P#;]#;y#;]#<e#<k#<n)aP#<q)aP#<z#<z#<zP)aP)aP)aP)aPP)aP#=Q#=TP#=T)aP#=XP#=[P)aP)aP)aP)aP)aP)a)aPP#=b#=h#=s#=y#>P#>V#>]#>k#>q#>{#?R#?]#?c#?s#?y#@k#@}#AT#AZ#Ai#BO#Cs#DR#DY#Et#FS#Gt#HS#HY#H`#Hf#Hp#Hv#H|#IW#Ij#IpPPPPPPPPPPP#IvPPPPPPP#Jk#Mx$ b$ i$ qPPP$']P$'f$*_$0x$0{$1O$1}$2Q$2X$2aP$2g$2jP$3W$3[$4S$5b$5g$5}PP$6S$6Y$6^$6a$6e$6i$7e$7|$8e$8i$8l$8o$8y$8|$9Q$9UR!|RoqOXst!Z#d%m&r&t&u&w,s,x2[2_Y!vQ'`-e1o5{Q%tvQ%|yQ&T|Q&j!VS'W!e-]Q'f!iS'l!r!yU*k$|*Z*oQ+o%}S+|&V&WQ,d&dQ-c'_Q-m'gQ-u'mQ0[*qQ1b,OQ1y,eR<{<Y%SdOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+],p,s,x-i-q.P.V.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3l4z6T6e6f6i6|8t9T9_S#q]<V!r)_$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SU+P%]<s<tQ+t&PQ,f&gQ,m&oQ0x+gQ0}+iQ1Y+uQ2R,kQ3`.gQ5`0|Q5f1TQ6[1zQ7Y3dQ8`5gR9e7['QkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>S!S!nQ!r!v!y!z$|'W'_'`'l'm'n*k*o*q*r-]-c-e-u0[0_1o5{5}%[$ti#v$b$c$d$x${%O%Q%^%_%c)y*R*T*V*Y*a*g*w*x+f+i,S,V.f/P/d/m/x/y/{0`0b0i0j0o1f1i1q3c4^4_4j4o5Q5[5_6S7W7v8Q8V8[8q9b9p9y:P:`:r;Q;[;d;k<l<m<o<p<q<r<u<v<w<x<y<z=S=T=U=V=X=Y=]=^=_=`=a=b=c=d=g=h>P>X>Y>]>^Q&X|Q'U!eS'[%i-`Q+t&PQ,P&WQ,f&gQ0n+SQ1Y+uQ1_+{Q2Q,jQ2R,kQ5f1TQ5o1aQ6[1zQ6_1|Q6`2PQ8`5gQ8c5lQ8|6bQ:X8dQ:f8yQ;V:YR<}*ZrnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_R,h&k&z^OPXYstuvwz!Z!`!g!j!o#S#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'b'r(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>R>S[#]WZ#W#Z'X(T!b%jm#h#i#l$x%e%h(^(h(i(j*Y*^*b+Z+[+^,o-V.T.Z.[.]._/m/p2d3[3]4a6r7TQ%wxQ%{yW&Q|&V&W,OQ&_!TQ'c!hQ'e!iQ(q#sS+n%|%}Q+r&PQ,_&bQ,c&dS-l'f'gQ.i(rQ1R+oQ1X+uQ1Z+vQ1^+zQ1t,`S1x,d,eQ2|-mQ5e1TQ5i1WQ5n1`Q6Z1yQ8_5gQ8b5kQ8f5pQ:T8^R;T:U!U$zi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y!^%yy!i!u%{%|%}'V'e'f'g'k'u*j+n+o-Y-l-m-t0R0U1R2u2|3T4r4s4v7}9{Q+h%wQ,T&[Q,W&]Q,b&dQ.h(qQ1s,_U1w,c,d,eQ3e.iQ6U1tS6Y1x1yQ8x6Z#f>T#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^o>U<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=hW%Ti%V*y>PS&[!Q&iQ&]!RQ&^!SU*}%[%d=sR,R&Y%]%Si#v$b$c$d$x${%O%Q%^%_%c)y*R*T*V*Y*a*g*w*x+f+i,S,V.f/P/d/m/x/y/{0`0b0i0j0o1f1i1q3c4^4_4j4o5Q5[5_6S7W7v8Q8V8[8q9b9p9y:P:`:r;Q;[;d;k<l<m<o<p<q<r<u<v<w<x<y<z=S=T=U=V=X=Y=]=^=_=`=a=b=c=d=g=h>P>X>Y>]>^T)z$u){V+P%]<s<tW'[!e%i*Z-`S(}#y#zQ+c%rQ+y&SS.b(m(nQ1j,XQ5T0kR8i5u'QkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>S$i$^c#Y#e%q%s%u(S(Y(t(y)R)S)T)U)V)W)X)Y)Z)[)^)`)b)g)q+d+x-Z-x-}.S.U.s.v.z.|.}/O/b0p2k2n3O3V3k3p3q3r3s3t3u3v3w3x3y3z3{3|4P4Q4X5X5c6u6{7Q7a7b7k7l8k9X9]9g9m9n:o;W;`<W=vT#TV#U'RkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SQ'Y!eR2q-]!W!nQ!e!r!v!y!z$|'W'_'`'l'm'n*Z*k*o*q*r-]-c-e-u0[0_1o5{5}R1l,ZnqOXst!Z#d%m&r&t&u&w,s,x2[2_Q&y!^Q'v!xS(s#u<^Q+l%zQ,]&_Q,^&aQ-j'dQ-w'oS.r(x=PS0q+X=ZQ1P+mQ1n,[Q2c,zQ2e,{Q2m-WQ2z-kQ2}-oS5Y0r=eQ5a1QS5d1S=fQ6t2oQ6x2{Q6}3SQ8]5bQ9Y6vQ9Z6yQ9^7OR:l9V$d$]c#Y#e%s%u(S(Y(t(y)R)S)T)U)V)W)X)Y)Z)[)^)`)b)g)q+d+x-Z-x-}.S.U.s.v.z.}/O/b0p2k2n3O3V3k3p3q3r3s3t3u3v3w3x3y3z3{3|4P4Q4X5X5c6u6{7Q7a7b7k7l8k9X9]9g9m9n:o;W;`<W=vS(o#p'iQ)P#zS+b%q.|S.c(n(pR3^.d'QkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SS#q]<VQ&t!XQ&u!YQ&w![Q&x!]R2Z,vQ'a!hQ+e%wQ-h'cS.e(q+hQ2x-gW3b.h.i0w0yQ6w2yW7U3_3a3e5^U9a7V7X7ZU:q9c9d9fS;b:p:sQ;p;cR;x;qU!wQ'`-eT5y1o5{!Q_OXZ`st!V!Z#d#h%e%m&i&k&r&t&u&w(j,s,x.[2[2_]!pQ!r'`-e1o5{T#q]<V%^{OPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_S(}#y#zS.b(m(n!s=l$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SU$fd)_,mS(p#p'iU*v%R(w4OU0m+O.n7gQ5^0xQ7V3`Q9d7YR:s9em!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}Q't!uS(f#g2US-s'k'wQ/s*]Q0R*jQ3U-vQ4f/tQ4r0TQ4s0UQ4x0^Q7r4`S7}4t4vS8R4y4{Q9r7sQ9v7yQ9{8OQ:Q8TS:{9w9xS;g:|;PS;s;h;iS;{;t;uS<P;|;}R<S<QQ#wbQ's!uS(e#g2US(g#m+WQ+Y%fQ+j%xQ+p&OU-r'k't'wQ.W(fU/r*]*`/wQ0S*jQ0V*lQ1O+kQ1u,aS3R-s-vQ3Z.`S4e/s/tQ4n0PS4q0R0^Q4u0WQ6W1vQ7P3US7q4`4bQ7u4fU7|4r4x4{Q8P4wQ8v6XS9q7r7sQ9u7yQ9}8RQ:O8SQ:c8wQ:y9rS:z9v9xQ;S:QQ;^:dS;f:{;PS;r;g;hS;z;s;uS<O;{;}Q<R<PQ<T<SQ=o=jQ={=tR=|=uV!wQ'`-e%^aOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_S#wz!j!r=i$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SR=o>R%^bOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_Q%fj!^%xy!i!u%{%|%}'V'e'f'g'k'u*j+n+o-Y-l-m-t0R0U1R2u2|3T4r4s4v7}9{S&Oz!jQ+k%yQ,a&dW1v,b,c,d,eU6X1w1x1yS8w6Y6ZQ:d8x!r=j$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SQ=t>QR=u>R%QeOPXYstuvw!Z!`!g!o#S#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&r&t&u&w&{'T'b'r(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_Y#bWZ#W#Z(T!b%jm#h#i#l$x%e%h(^(h(i(j*Y*^*b+Z+[+^,o-V.T.Z.[.]._/m/p2d3[3]4a6r7TQ,n&o!p=k$Z$n)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SR=n'XU']!e%i*ZR2s-`%SdOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+],p,s,x-i-q.P.V.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3l4z6T6e6f6i6|8t9T9_!r)_$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SQ,m&oQ0x+gQ3`.gQ7Y3dR9e7[!b$Tc#Y%q(S(Y(t(y)Z)[)`)g+x-x-}.S.U.s.v/b0p3O3V3k3{5X5c6{7Q7a9]:o<W!P<d)^)q-Z.|2k2n3p3y3z4P4X6u7b7k7l8k9X9g9m9n;W;`=v!f$Vc#Y%q(S(Y(t(y)W)X)Z)[)`)g+x-x-}.S.U.s.v/b0p3O3V3k3{5X5c6{7Q7a9]:o<W!T<f)^)q-Z.|2k2n3p3v3w3y3z4P4X6u7b7k7l8k9X9g9m9n;W;`=v!^$Zc#Y%q(S(Y(t(y)`)g+x-x-}.S.U.s.v/b0p3O3V3k3{5X5c6{7Q7a9]:o<WQ4_/kz>S)^)q-Z.|2k2n3p4P4X6u7b7k7l8k9X9g9m9n;W;`=vQ>X>ZR>Y>['QkOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>SS$oh$pR4U/U'XgOPWXYZhstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n$p%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/U/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>ST$kf$qQ$ifS)j$l)nR)v$qT$jf$qT)l$l)n'XhOPWXYZhstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$Z$_$a$e$n$p%m%t&R&k&n&o&r&t&u&w&{'T'X'b'r(T(V(](d(x(z)O)s)}*i+X+]+g,p,s,x-U-X-i-q.P.V.g.t.{/U/V/n0]0l0r1S1r2S2T2V2X2[2_2a2p3Q3W3d3l4T4z5w6T6e6f6i6s6|7[8t9T9_:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>ST$oh$pQ$rhR)u$p%^jOPWXYZstuvw!Z!`!g!o#S#W#Z#d#o#u#x#{$O$P$Q$R$S$T$U$V$W$X$_$a$e%m%t&R&k&n&o&r&t&u&w&{'T'b'r(T(V(](d(x(z)O)}*i+X+]+g,p,s,x-i-q.P.V.g.t.{/n0]0l0r1S1r2S2T2V2X2[2_2a3Q3W3d3l4z6T6e6f6i6|7[8t9T9_!s>Q$Z$n'X)s-U-X/V2p4T5w6s:Z:m<U<X<Y<]<^<_<`<a<b<c<d<e<f<g<h<i<k<n<{=O=P=R=Z=[=e=f>S#glOPXZst!Z!`!o#S#d#o#{$n%m&k&n&o&r&t&u&w&{'T'b)O)s*i+]+g,p,s,x-i.g/V/n0]0l1r2S2T2V2X2[2_2a3d4T4z6T6e6f6i7[8t9T!U%Ri$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y#f(w#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^Q+T%aQ/c*Oo4O<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=h!U$yi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>YQ*c$zU*l$|*Z*oQ+U%bQ0W*m#f=q#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^n=r<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=hQ=w>TQ=x>UQ=y>VR=z>W!U%Ri$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y#f(w#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^o4O<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=hnoOXst!Z#d%m&r&t&u&w,s,x2[2_S*f${*YQ-R'OQ-S'QR4i/y%[%Si#v$b$c$d$x${%O%Q%^%_%c)y*R*T*V*Y*a*g*w*x+f+i,S,V.f/P/d/m/x/y/{0`0b0i0j0o1f1i1q3c4^4_4j4o5Q5[5_6S7W7v8Q8V8[8q9b9p9y:P:`:r;Q;[;d;k<l<m<o<p<q<r<u<v<w<x<y<z=S=T=U=V=X=Y=]=^=_=`=a=b=c=d=g=h>P>X>Y>]>^Q,U&]Q1h,WQ5s1gR8h5tV*n$|*Z*oU*n$|*Z*oT5z1o5{S0P*i/nQ4w0]T8S4z:]Q+j%xQ0V*lQ1O+kQ1u,aQ6W1vQ8v6XQ:c8wR;^:d!U%Oi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Yx*R$v)e*S*u+V/v0d0e4R4g5R5S5W7p8U:R:x=p=}>OS0`*t0a#f<o#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^n<p<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=h!d=S(u)c*[*e.j.m.q/_/k/|0v1e3h4[4h4l5r7]7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[`=T3}7c7f7j9h:t:w;yS=_.l3iT=`7e9k!U%Qi$d%O%Q%^%_%c*R*T*a*w*x/P/x0`0b0i0j0o4_5Q8V9p>P>X>Y|*T$v)e*U*t+V/g/v0d0e4R4g4|5R5S5W7p8U:R:x=p=}>OS0b*u0c#f<q#v$b$c$x${)y*V*Y*g+f+i,S,V.f/d/m/y/{1f1i1q3c4^4j4o5[5_6S7W7v8Q8[8q9b9y:P:`:r;Q;[;d;k<o<q<u<w<y=S=U=X=]=_=a=c=g>]>^n<r<l<m<p<r<v<x<z=T=V=Y=^=`=b=d=h!h=U(u)c*[*e.k.l.q/_/k/|0v1e3f3h4[4h4l5r7]7^7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[d=V3}7d7e7j9h9i:t:u:w;yS=a.m3jT=b7f9lrnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_Q&f!UR,p&ornOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_R&f!UQ,Y&^R1d,RsnOXst!V!Z#d%m&i&r&t&u&w,s,x2[2_Q1p,_S6R1s1tU8p6P6Q6US:_8r8sS;Y:^:aQ;m;ZR;w;nQ&m!VR,i&iR6_1|R:f8yW&Q|&V&W,OR1Z+vQ&r!WR,s&sR,y&xT2],x2_R,}&yQ,|&yR2f,}Q'y!{R-y'ySsOtQ#dXT%ps#dQ#OTR'{#OQ#RUR'}#RQ){$uR/`){Q#UVR(Q#UQ#XWU(W#X(X.QQ(X#YR.Q(YQ-^'YR2r-^Q.u(yS3m.u3nR3n.vQ-e'`R2v-eY!rQ'`-e1o5{R'j!rQ/Q)eR4S/QU#_W%h*YU(_#_(`.RQ(`#`R.R(ZQ-a']R2t-at`OXst!V!Z#d%m&i&k&r&t&u&w,s,x2[2_S#hZ%eU#r`#h.[R.[(jQ(k#jQ.X(gW.a(k.X3X7RQ3X.YR7R3YQ)n$lR/W)nQ$phR)t$pQ$`cU)a$`-|<jQ-|<WR<j)qQ/q*]W4c/q4d7t9sU4d/r/s/tS7t4e4fR9s7u$e*Q$v(u)c)e*[*e*t*u+Q+R+V.l.m.o.p.q/_/g/i/k/v/|0d0e0v1e3f3g3h3}4R4[4g4h4l4|5O5R5S5W5r7]7^7_7`7e7f7h7i7j7p7w7z8U8X8Z9h9i9j9t9|:R:S:t:u:v:w:x:};R;e;j;v;y=p=}>O>Z>[Q/z*eU4k/z4m7xQ4m/|R7x4lS*o$|*ZR0Y*ox*S$v)e*t*u+V/v0d0e4R4g5R5S5W7p8U:R:x=p=}>O!d.j(u)c*[*e.l.m.q/_/k/|0v1e3h4[4h4l5r7]7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[U/h*S.j7ca7c3}7e7f7j9h:t:w;yQ0a*tQ3i.lU4}0a3i9kR9k7e|*U$v)e*t*u+V/g/v0d0e4R4g4|5R5S5W7p8U:R:x=p=}>O!h.k(u)c*[*e.l.m.q/_/k/|0v1e3f3h4[4h4l5r7]7^7`7w7z8X8Z9t9|:S:};R;e;j;v>Z>[U/j*U.k7de7d3}7e7f7j9h9i:t:u:w;yQ0c*uQ3j.mU5P0c3j9lR9l7fQ*z%UR0g*zQ5]0vR8Y5]Q+_%kR0u+_Q5v1jS8j5v:[R:[8kQ,[&_R1m,[Q5{1oR8m5{Q1{,fS6]1{8zR8z6_Q1U+rW5h1U5j8a:VQ5j1XQ8a5iR:V8bQ+w&QR1[+wQ2_,xR6m2_YrOXst#dQ&v!ZQ+a%mQ,r&rQ,t&tQ,u&uQ,w&wQ2Y,sS2],x2_R6l2[Q%opQ&z!_Q&}!aQ'P!bQ'R!cQ'q!uQ+`%lQ+l%zQ,Q&XQ,h&mQ-P&|W-p'k's't'wQ-w'oQ0X*nQ1P+mQ1c,PS2O,i,lQ2g-OQ2h-RQ2i-SQ2}-oW3P-r-s-v-xQ5a1QQ5m1_Q5q1eQ6V1uQ6a2QQ6k2ZU6z3O3R3UQ6}3SQ8]5bQ8e5oQ8g5rQ8l5zQ8u6WQ8{6`S9[6{7PQ9^7OQ:W8cQ:b8vQ:g8|Q:n9]Q;U:XQ;]:cQ;a:oQ;l;VR;o;^Q%zyQ'd!iQ'o!uU+m%{%|%}Q-W'VU-k'e'f'gS-o'k'uQ0Q*jS1Q+n+oQ2o-YS2{-l-mQ3S-tS4p0R0UQ5b1RQ6v2uQ6y2|Q7O3TU7{4r4s4vQ9z7}R;O9{S$wi>PR*{%VU%Ui%V>PR0f*yQ$viS(u#v+iS)c$b$cQ)e$dQ*[$xS*e${*YQ*t%OQ*u%QQ+Q%^Q+R%_Q+V%cQ.l<oQ.m<qQ.o<uQ.p<wQ.q<yQ/_)yQ/g*RQ/i*TQ/k*VQ/v*aS/|*g/mQ0d*wQ0e*xl0v+f,V.f1i1q3c6S7W8q9b:`:r;[;dQ1e,SQ3f=SQ3g=UQ3h=XS3}<l<mQ4R/PS4[/d4^Q4g/xQ4h/yQ4l/{Q4|0`Q5O0bQ5R0iQ5S0jQ5W0oQ5r1fQ7]=]Q7^=_Q7_=aQ7`=cQ7e<pQ7f<rQ7h<vQ7i<xQ7j<zQ7p4_Q7w4jQ7z4oQ8U5QQ8X5[Q8Z5_Q9h=YQ9i=TQ9j=VQ9t7vQ9|8QQ:R8VQ:S8[Q:t=^Q:u=`Q:v=bQ:w=dQ:x9pQ:}9yQ;R:PQ;e=gQ;j;QQ;v;kQ;y=hQ=p>PQ=}>XQ>O>YQ>Z>]R>[>^Q+O%]Q.n<sR7g<tnpOXst!Z#d%m&r&t&u&w,s,x2[2_Q!fPS#fZ#oQ&|!`W'h!o*i0]4zQ(P#SQ)Q#{Q)r$nS,l&k&nQ,q&oQ-O&{S-T'T/nQ-g'bQ.x)OQ/[)sQ0s+]Q0y+gQ2W,pQ2y-iQ3a.gQ4W/VQ5U0lQ6Q1rQ6c2SQ6d2TQ6h2VQ6j2XQ6o2aQ7Z3dQ7m4TQ8s6TQ9P6eQ9Q6fQ9S6iQ9f7[Q:a8tR:k9T#[cOPXZst!Z!`!o#d#o#{%m&k&n&o&r&t&u&w&{'T'b)O*i+]+g,p,s,x-i.g/n0]0l1r2S2T2V2X2[2_2a3d4z6T6e6f6i7[8t9TQ#YWQ#eYQ%quQ%svS%uw!gS(S#W(VQ(Y#ZQ(t#uQ(y#xQ)R$OQ)S$PQ)T$QQ)U$RQ)V$SQ)W$TQ)X$UQ)Y$VQ)Z$WQ)[$XQ)^$ZQ)`$_Q)b$aQ)g$eW)q$n)s/V4TQ+d%tQ+x&RS-Z'X2pQ-x'rS-}(T.PQ.S(]Q.U(dQ.s(xQ.v(zQ.z<UQ.|<XQ.}<YQ/O<]Q/b)}Q0p+XQ2k-UQ2n-XQ3O-qQ3V.VQ3k.tQ3p<^Q3q<_Q3r<`Q3s<aQ3t<bQ3u<cQ3v<dQ3w<eQ3x<fQ3y<gQ3z<hQ3{.{Q3|<kQ4P<nQ4Q<{Q4X<iQ5X0rQ5c1SQ6u=OQ6{3QQ7Q3WQ7a3lQ7b=PQ7k=RQ7l=ZQ8k5wQ9X6sQ9]6|Q9g=[Q9m=eQ9n=fQ:o9_Q;W:ZQ;`:mQ<W#SR=v>SR#[WR'Z!el!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}S'V!e-]U*j$|*Z*oS-Y'W'_S0U*k*qQ0^*rQ2u-cQ4v0[R4{0_R({#xQ!fQT-d'`-e]!qQ!r'`-e1o5{Q#p]R'i<VR)f$dY!uQ'`-e1o5{Q'k!rS'u!v!yS'w!z5}S-t'l'mQ-v'nR3T-uT#kZ%eS#jZ%eS%km,oU(g#h#i#lS.Y(h(iQ.^(jQ0t+^Q3Y.ZU3Z.[.]._S7S3[3]R9`7Td#^W#W#Z%h(T(^*Y+Z.T/mr#gZm#h#i#l%e(h(i(j+^.Z.[.]._3[3]7TS*]$x*bQ/t*^Q2U,oQ2l-VQ4`/pQ6q2dQ7s4aQ9W6rT=m'X+[V#aW%h*YU#`W%h*YS(U#W(^U(Z#Z+Z/mS-['X+[T.O(T.TV'^!e%i*ZQ$lfR)x$qT)m$l)nR4V/UT*_$x*bT*h${*YQ0w+fQ1g,VQ3_.fQ5t1iQ6P1qQ7X3cQ8r6SQ9c7WQ:^8qQ:p9bQ;Z:`Q;c:rQ;n;[R;q;dnqOXst!Z#d%m&r&t&u&w,s,x2[2_Q&l!VR,h&itmOXst!U!V!Z#d%m&i&r&t&u&w,s,x2[2_R,o&oT%lm,oR1k,XR,g&gQ&U|S+}&V&WR1^,OR+s&PT&p!W&sT&q!W&sT2^,x2_",
  nodeNames: "⚠ ArithOp ArithOp ?. JSXStartTag LineComment BlockComment Script Hashbang ExportDeclaration export Star as VariableName String Escape from ; default FunctionDeclaration async function VariableDefinition > < TypeParamList in out const TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewTarget new NewExpression ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression TypeArgList CompareOp < declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression InstantiationExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast < ArrowFunction TypeParamList SequenceExpression InstantiationExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate asserts is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration defer ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",
  maxTerm: 380,
  context: trackNewline,
  nodeProps: [
    ["isolate", -8,5,6,14,37,39,51,53,55,""],
    ["group", -26,9,17,19,68,207,211,215,216,218,221,224,234,237,243,245,247,249,252,258,264,266,268,270,272,274,275,"Statement",-34,13,14,32,35,36,42,51,54,55,57,62,70,72,76,80,82,84,85,110,111,120,121,136,139,141,142,143,144,145,147,148,167,169,171,"Expression",-23,31,33,37,41,43,45,173,175,177,178,180,181,182,184,185,186,188,189,190,201,203,205,206,"Type",-3,88,103,109,"ClassItem"],
    ["openedBy", 23,"<",38,"InterpolationStart",56,"[",60,"{",73,"(",160,"JSXStartCloseTag"],
    ["closedBy", -2,24,168,">",40,"InterpolationEnd",50,"]",61,"}",74,")",165,"JSXEndTag"]
  ],
  propSources: [jsHighlight],
  skippedNodes: [0,5,6,278],
  repeatNodeCount: 37,
  tokenData: "$Fq07[R!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tuEruvJSvwLkwx! Yxy!'iyz!(sz{!)}{|!,q|}!.O}!O!,q!O!P!/Y!P!Q!9j!Q!R#:O!R![#<_![!]#I_!]!^#Jk!^!_#Ku!_!`$![!`!a$$v!a!b$*T!b!c$,r!c!}Er!}#O$-|#O#P$/W#P#Q$4o#Q#R$5y#R#SEr#S#T$7W#T#o$8b#o#p$<r#p#q$=h#q#r$>x#r#s$@U#s$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$I|Er$I|$I}$Dk$I}$JO$Dk$JO$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr(n%d_$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&j&hT$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c&j&zP;=`<%l&c'|'U]$i&j(Z!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!b(SU(Z!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!b(iP;=`<%l'}'|(oP;=`<%l&}'[(y]$i&j(WpOY(rYZ&cZr(rrs&cs!^(r!^!_)r!_#O(r#O#P&c#P#o(r#o#p)r#p;'S(r;'S;=`*a<%lO(rp)wU(WpOY)rZr)rs#O)r#P;'S)r;'S;=`*Z<%lO)rp*^P;=`<%l)r'[*dP;=`<%l(r#S*nX(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g#S+^P;=`<%l*g(n+dP;=`<%l%Z07[+rq$i&j(Wp(Z!b'|0/lOX%ZXY+gYZ&cZ[+g[p%Zpq+gqr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p$f%Z$f$g+g$g#BY%Z#BY#BZ+g#BZ$IS%Z$IS$I_+g$I_$JT%Z$JT$JU+g$JU$KV%Z$KV$KW+g$KW&FU%Z&FU&FV+g&FV;'S%Z;'S;=`+a<%l?HT%Z?HT?HU+g?HUO%Z07[.ST(X#S$i&j'}0/lO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c07[.n_$i&j(Wp(Z!b'}0/lOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z)3p/x`$i&j!p),Q(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`0z!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW1V`#v(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`2X!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW2d_#v(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'At3l_(V':f$i&j(Z!bOY4kYZ5qZr4krs7nsw4kwx5qx!^4k!^!_8p!_#O4k#O#P5q#P#o4k#o#p8p#p;'S4k;'S;=`:X<%lO4k(^4r_$i&j(Z!bOY4kYZ5qZr4krs7nsw4kwx5qx!^4k!^!_8p!_#O4k#O#P5q#P#o4k#o#p8p#p;'S4k;'S;=`:X<%lO4k&z5vX$i&jOr5qrs6cs!^5q!^!_6y!_#o5q#o#p6y#p;'S5q;'S;=`7h<%lO5q&z6jT$d`$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c`6|TOr6yrs7]s;'S6y;'S;=`7b<%lO6y`7bO$d``7eP;=`<%l6y&z7kP;=`<%l5q(^7w]$d`$i&j(Z!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!r8uZ(Z!bOY8pYZ6yZr8prs9hsw8pwx6yx#O8p#O#P6y#P;'S8p;'S;=`:R<%lO8p!r9oU$d`(Z!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!r:UP;=`<%l8p(^:[P;=`<%l4k%9[:hh$i&j(Wp(Z!bOY%ZYZ&cZq%Zqr<Srs&}st%ZtuCruw%Zwx(rx!^%Z!^!_*g!_!c%Z!c!}Cr!}#O%Z#O#P&c#P#R%Z#R#SCr#S#T%Z#T#oCr#o#p*g#p$g%Z$g;'SCr;'S;=`El<%lOCr(r<__WS$i&j(Wp(Z!bOY<SYZ&cZr<Srs=^sw<Swx@nx!^<S!^!_Bm!_#O<S#O#P>`#P#o<S#o#pBm#p;'S<S;'S;=`Cl<%lO<S(Q=g]WS$i&j(Z!bOY=^YZ&cZw=^wx>`x!^=^!^!_?q!_#O=^#O#P>`#P#o=^#o#p?q#p;'S=^;'S;=`@h<%lO=^&n>gXWS$i&jOY>`YZ&cZ!^>`!^!_?S!_#o>`#o#p?S#p;'S>`;'S;=`?k<%lO>`S?XSWSOY?SZ;'S?S;'S;=`?e<%lO?SS?hP;=`<%l?S&n?nP;=`<%l>`!f?xWWS(Z!bOY?qZw?qwx?Sx#O?q#O#P?S#P;'S?q;'S;=`@b<%lO?q!f@eP;=`<%l?q(Q@kP;=`<%l=^'`@w]WS$i&j(WpOY@nYZ&cZr@nrs>`s!^@n!^!_Ap!_#O@n#O#P>`#P#o@n#o#pAp#p;'S@n;'S;=`Bg<%lO@ntAwWWS(WpOYApZrAprs?Ss#OAp#O#P?S#P;'SAp;'S;=`Ba<%lOAptBdP;=`<%lAp'`BjP;=`<%l@n#WBvYWS(Wp(Z!bOYBmZrBmrs?qswBmwxApx#OBm#O#P?S#P;'SBm;'S;=`Cf<%lOBm#WCiP;=`<%lBm(rCoP;=`<%l<S%9[C}i$i&j(o%1l(Wp(Z!bOY%ZYZ&cZr%Zrs&}st%ZtuCruw%Zwx(rx!Q%Z!Q![Cr![!^%Z!^!_*g!_!c%Z!c!}Cr!}#O%Z#O#P&c#P#R%Z#R#SCr#S#T%Z#T#oCr#o#p*g#p$g%Z$g;'SCr;'S;=`El<%lOCr%9[EoP;=`<%lCr07[FRk$i&j(Wp(Z!b$]#t(T,2j(e$I[OY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr+dHRk$i&j(Wp(Z!b$]#tOY%ZYZ&cZr%Zrs&}st%ZtuGvuw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Gv![!^%Z!^!_*g!_!c%Z!c!}Gv!}#O%Z#O#P&c#P#R%Z#R#SGv#S#T%Z#T#oGv#o#p*g#p$g%Z$g;'SGv;'S;=`Iv<%lOGv+dIyP;=`<%lGv07[JPP;=`<%lEr(KWJ_`$i&j(Wp(Z!b#p(ChOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KWKl_$i&j$Q(Ch(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z,#xLva(z+JY$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sv%ZvwM{wx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KWNW`$i&j#z(Ch(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'At! c_(Y';W$i&j(WpOY!!bYZ!#hZr!!brs!#hsw!!bwx!$xx!^!!b!^!_!%z!_#O!!b#O#P!#h#P#o!!b#o#p!%z#p;'S!!b;'S;=`!'c<%lO!!b'l!!i_$i&j(WpOY!!bYZ!#hZr!!brs!#hsw!!bwx!$xx!^!!b!^!_!%z!_#O!!b#O#P!#h#P#o!!b#o#p!%z#p;'S!!b;'S;=`!'c<%lO!!b&z!#mX$i&jOw!#hwx6cx!^!#h!^!_!$Y!_#o!#h#o#p!$Y#p;'S!#h;'S;=`!$r<%lO!#h`!$]TOw!$Ywx7]x;'S!$Y;'S;=`!$l<%lO!$Y`!$oP;=`<%l!$Y&z!$uP;=`<%l!#h'l!%R]$d`$i&j(WpOY(rYZ&cZr(rrs&cs!^(r!^!_)r!_#O(r#O#P&c#P#o(r#o#p)r#p;'S(r;'S;=`*a<%lO(r!Q!&PZ(WpOY!%zYZ!$YZr!%zrs!$Ysw!%zwx!&rx#O!%z#O#P!$Y#P;'S!%z;'S;=`!']<%lO!%z!Q!&yU$d`(WpOY)rZr)rs#O)r#P;'S)r;'S;=`*Z<%lO)r!Q!'`P;=`<%l!%z'l!'fP;=`<%l!!b/5|!'t_!l/.^$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z#&U!)O_!k!Lf$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z-!n!*[b$i&j(Wp(Z!b(U%&f#q(ChOY%ZYZ&cZr%Zrs&}sw%Zwx(rxz%Zz{!+d{!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW!+o`$i&j(Wp(Z!b#n(ChOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z+;x!,|`$i&j(Wp(Z!br+4YOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z,$U!.Z_!]+Jf$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z07[!/ec$i&j(Wp(Z!b!Q.2^OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!0p!P!Q%Z!Q![!3Y![!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z#%|!0ya$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!2O!P!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z#%|!2Z_![!L^$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad!3eg$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![!3Y![!^%Z!^!_*g!_!g%Z!g!h!4|!h#O%Z#O#P&c#P#R%Z#R#S!3Y#S#X%Z#X#Y!4|#Y#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad!5Vg$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx{%Z{|!6n|}%Z}!O!6n!O!Q%Z!Q![!8S![!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S!8S#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad!6wc$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![!8S![!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S!8S#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad!8_c$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![!8S![!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S!8S#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z07[!9uf$i&j(Wp(Z!b#o(ChOY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Lcxz!;Zz{#-}{!P!;Z!P!Q#/d!Q!^!;Z!^!_#(i!_!`#7S!`!a#8i!a!}!;Z!}#O#,f#O#P!Dy#P#o!;Z#o#p#(i#p;'S!;Z;'S;=`#-w<%lO!;Z?O!;fb$i&j(Wp(Z!b!X7`OY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Lcx!P!;Z!P!Q#&`!Q!^!;Z!^!_#(i!_!}!;Z!}#O#,f#O#P!Dy#P#o!;Z#o#p#(i#p;'S!;Z;'S;=`#-w<%lO!;Z>^!<w`$i&j(Z!b!X7`OY!<nYZ&cZw!<nwx!=yx!P!<n!P!Q!Eq!Q!^!<n!^!_!Gr!_!}!<n!}#O!KS#O#P!Dy#P#o!<n#o#p!Gr#p;'S!<n;'S;=`!L]<%lO!<n<z!>Q^$i&j!X7`OY!=yYZ&cZ!P!=y!P!Q!>|!Q!^!=y!^!_!@c!_!}!=y!}#O!CW#O#P!Dy#P#o!=y#o#p!@c#p;'S!=y;'S;=`!Ek<%lO!=y<z!?Td$i&j!X7`O!^&c!_#W&c#W#X!>|#X#Z&c#Z#[!>|#[#]&c#]#^!>|#^#a&c#a#b!>|#b#g&c#g#h!>|#h#i&c#i#j!>|#j#k!>|#k#m&c#m#n!>|#n#o&c#p;'S&c;'S;=`&w<%lO&c7`!@hX!X7`OY!@cZ!P!@c!P!Q!AT!Q!}!@c!}#O!Ar#O#P!Bq#P;'S!@c;'S;=`!CQ<%lO!@c7`!AYW!X7`#W#X!AT#Z#[!AT#]#^!AT#a#b!AT#g#h!AT#i#j!AT#j#k!AT#m#n!AT7`!AuVOY!ArZ#O!Ar#O#P!B[#P#Q!@c#Q;'S!Ar;'S;=`!Bk<%lO!Ar7`!B_SOY!ArZ;'S!Ar;'S;=`!Bk<%lO!Ar7`!BnP;=`<%l!Ar7`!BtSOY!@cZ;'S!@c;'S;=`!CQ<%lO!@c7`!CTP;=`<%l!@c<z!C][$i&jOY!CWYZ&cZ!^!CW!^!_!Ar!_#O!CW#O#P!DR#P#Q!=y#Q#o!CW#o#p!Ar#p;'S!CW;'S;=`!Ds<%lO!CW<z!DWX$i&jOY!CWYZ&cZ!^!CW!^!_!Ar!_#o!CW#o#p!Ar#p;'S!CW;'S;=`!Ds<%lO!CW<z!DvP;=`<%l!CW<z!EOX$i&jOY!=yYZ&cZ!^!=y!^!_!@c!_#o!=y#o#p!@c#p;'S!=y;'S;=`!Ek<%lO!=y<z!EnP;=`<%l!=y>^!Ezl$i&j(Z!b!X7`OY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#W&}#W#X!Eq#X#Z&}#Z#[!Eq#[#]&}#]#^!Eq#^#a&}#a#b!Eq#b#g&}#g#h!Eq#h#i&}#i#j!Eq#j#k!Eq#k#m&}#m#n!Eq#n#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}8r!GyZ(Z!b!X7`OY!GrZw!Grwx!@cx!P!Gr!P!Q!Hl!Q!}!Gr!}#O!JU#O#P!Bq#P;'S!Gr;'S;=`!J|<%lO!Gr8r!Hse(Z!b!X7`OY'}Zw'}x#O'}#P#W'}#W#X!Hl#X#Z'}#Z#[!Hl#[#]'}#]#^!Hl#^#a'}#a#b!Hl#b#g'}#g#h!Hl#h#i'}#i#j!Hl#j#k!Hl#k#m'}#m#n!Hl#n;'S'};'S;=`(f<%lO'}8r!JZX(Z!bOY!JUZw!JUwx!Arx#O!JU#O#P!B[#P#Q!Gr#Q;'S!JU;'S;=`!Jv<%lO!JU8r!JyP;=`<%l!JU8r!KPP;=`<%l!Gr>^!KZ^$i&j(Z!bOY!KSYZ&cZw!KSwx!CWx!^!KS!^!_!JU!_#O!KS#O#P!DR#P#Q!<n#Q#o!KS#o#p!JU#p;'S!KS;'S;=`!LV<%lO!KS>^!LYP;=`<%l!KS>^!L`P;=`<%l!<n=l!Ll`$i&j(Wp!X7`OY!LcYZ&cZr!Lcrs!=ys!P!Lc!P!Q!Mn!Q!^!Lc!^!_# o!_!}!Lc!}#O#%P#O#P!Dy#P#o!Lc#o#p# o#p;'S!Lc;'S;=`#&Y<%lO!Lc=l!Mwl$i&j(Wp!X7`OY(rYZ&cZr(rrs&cs!^(r!^!_)r!_#O(r#O#P&c#P#W(r#W#X!Mn#X#Z(r#Z#[!Mn#[#](r#]#^!Mn#^#a(r#a#b!Mn#b#g(r#g#h!Mn#h#i(r#i#j!Mn#j#k!Mn#k#m(r#m#n!Mn#n#o(r#o#p)r#p;'S(r;'S;=`*a<%lO(r8Q# vZ(Wp!X7`OY# oZr# ors!@cs!P# o!P!Q#!i!Q!}# o!}#O#$R#O#P!Bq#P;'S# o;'S;=`#$y<%lO# o8Q#!pe(Wp!X7`OY)rZr)rs#O)r#P#W)r#W#X#!i#X#Z)r#Z#[#!i#[#])r#]#^#!i#^#a)r#a#b#!i#b#g)r#g#h#!i#h#i)r#i#j#!i#j#k#!i#k#m)r#m#n#!i#n;'S)r;'S;=`*Z<%lO)r8Q#$WX(WpOY#$RZr#$Rrs!Ars#O#$R#O#P!B[#P#Q# o#Q;'S#$R;'S;=`#$s<%lO#$R8Q#$vP;=`<%l#$R8Q#$|P;=`<%l# o=l#%W^$i&j(WpOY#%PYZ&cZr#%Prs!CWs!^#%P!^!_#$R!_#O#%P#O#P!DR#P#Q!Lc#Q#o#%P#o#p#$R#p;'S#%P;'S;=`#&S<%lO#%P=l#&VP;=`<%l#%P=l#&]P;=`<%l!Lc?O#&kn$i&j(Wp(Z!b!X7`OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#W%Z#W#X#&`#X#Z%Z#Z#[#&`#[#]%Z#]#^#&`#^#a%Z#a#b#&`#b#g%Z#g#h#&`#h#i%Z#i#j#&`#j#k#&`#k#m%Z#m#n#&`#n#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z9d#(r](Wp(Z!b!X7`OY#(iZr#(irs!Grsw#(iwx# ox!P#(i!P!Q#)k!Q!}#(i!}#O#+`#O#P!Bq#P;'S#(i;'S;=`#,`<%lO#(i9d#)th(Wp(Z!b!X7`OY*gZr*grs'}sw*gwx)rx#O*g#P#W*g#W#X#)k#X#Z*g#Z#[#)k#[#]*g#]#^#)k#^#a*g#a#b#)k#b#g*g#g#h#)k#h#i*g#i#j#)k#j#k#)k#k#m*g#m#n#)k#n;'S*g;'S;=`+Z<%lO*g9d#+gZ(Wp(Z!bOY#+`Zr#+`rs!JUsw#+`wx#$Rx#O#+`#O#P!B[#P#Q#(i#Q;'S#+`;'S;=`#,Y<%lO#+`9d#,]P;=`<%l#+`9d#,cP;=`<%l#(i?O#,o`$i&j(Wp(Z!bOY#,fYZ&cZr#,frs!KSsw#,fwx#%Px!^#,f!^!_#+`!_#O#,f#O#P!DR#P#Q!;Z#Q#o#,f#o#p#+`#p;'S#,f;'S;=`#-q<%lO#,f?O#-tP;=`<%l#,f?O#-zP;=`<%l!;Z07[#.[b$i&j(Wp(Z!b(O0/l!X7`OY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Lcx!P!;Z!P!Q#&`!Q!^!;Z!^!_#(i!_!}!;Z!}#O#,f#O#P!Dy#P#o!;Z#o#p#(i#p;'S!;Z;'S;=`#-w<%lO!;Z07[#/o_$i&j(Wp(Z!bT0/lOY#/dYZ&cZr#/drs#0nsw#/dwx#4Ox!^#/d!^!_#5}!_#O#/d#O#P#1p#P#o#/d#o#p#5}#p;'S#/d;'S;=`#6|<%lO#/d06j#0w]$i&j(Z!bT0/lOY#0nYZ&cZw#0nwx#1px!^#0n!^!_#3R!_#O#0n#O#P#1p#P#o#0n#o#p#3R#p;'S#0n;'S;=`#3x<%lO#0n05W#1wX$i&jT0/lOY#1pYZ&cZ!^#1p!^!_#2d!_#o#1p#o#p#2d#p;'S#1p;'S;=`#2{<%lO#1p0/l#2iST0/lOY#2dZ;'S#2d;'S;=`#2u<%lO#2d0/l#2xP;=`<%l#2d05W#3OP;=`<%l#1p01O#3YW(Z!bT0/lOY#3RZw#3Rwx#2dx#O#3R#O#P#2d#P;'S#3R;'S;=`#3r<%lO#3R01O#3uP;=`<%l#3R06j#3{P;=`<%l#0n05x#4X]$i&j(WpT0/lOY#4OYZ&cZr#4Ors#1ps!^#4O!^!_#5Q!_#O#4O#O#P#1p#P#o#4O#o#p#5Q#p;'S#4O;'S;=`#5w<%lO#4O00^#5XW(WpT0/lOY#5QZr#5Qrs#2ds#O#5Q#O#P#2d#P;'S#5Q;'S;=`#5q<%lO#5Q00^#5tP;=`<%l#5Q05x#5zP;=`<%l#4O01p#6WY(Wp(Z!bT0/lOY#5}Zr#5}rs#3Rsw#5}wx#5Qx#O#5}#O#P#2d#P;'S#5};'S;=`#6v<%lO#5}01p#6yP;=`<%l#5}07[#7PP;=`<%l#/d)3h#7ab$i&j$Q(Ch(Wp(Z!b!X7`OY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Lcx!P!;Z!P!Q#&`!Q!^!;Z!^!_#(i!_!}!;Z!}#O#,f#O#P!Dy#P#o!;Z#o#p#(i#p;'S!;Z;'S;=`#-w<%lO!;ZAt#8vb$Z#t$i&j(Wp(Z!b!X7`OY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Lcx!P!;Z!P!Q#&`!Q!^!;Z!^!_#(i!_!}!;Z!}#O#,f#O#P!Dy#P#o!;Z#o#p#(i#p;'S!;Z;'S;=`#-w<%lO!;Z'Ad#:Zp$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!3Y!P!Q%Z!Q![#<_![!^%Z!^!_*g!_!g%Z!g!h!4|!h#O%Z#O#P&c#P#R%Z#R#S#<_#S#U%Z#U#V#?i#V#X%Z#X#Y!4|#Y#b%Z#b#c#>_#c#d#Bq#d#l%Z#l#m#Es#m#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#<jk$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!3Y!P!Q%Z!Q![#<_![!^%Z!^!_*g!_!g%Z!g!h!4|!h#O%Z#O#P&c#P#R%Z#R#S#<_#S#X%Z#X#Y!4|#Y#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#>j_$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#?rd$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#AQ!R!S#AQ!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#AQ#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#A]f$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#AQ!R!S#AQ!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#AQ#S#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Bzc$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!Y#DV!Y!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#DV#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Dbe$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!Y#DV!Y!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#DV#S#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#E|g$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![#Ge![!^%Z!^!_*g!_!c%Z!c!i#Ge!i#O%Z#O#P&c#P#R%Z#R#S#Ge#S#T%Z#T#Z#Ge#Z#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'Ad#Gpi$i&j(Wp(Z!bs'9tOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![#Ge![!^%Z!^!_*g!_!c%Z!c!i#Ge!i#O%Z#O#P&c#P#R%Z#R#S#Ge#S#T%Z#T#Z#Ge#Z#b%Z#b#c#>_#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z*)x#Il_!g$b$i&j$O)Lv(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z)[#Jv_al$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z04f#LS^h#)`#R-<U(Wp(Z!b$n7`OY*gZr*grs'}sw*gwx)rx!P*g!P!Q#MO!Q!^*g!^!_#Mt!_!`$ f!`#O*g#P;'S*g;'S;=`+Z<%lO*g(n#MXX$k&j(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g(El#M}Z#r(Ch(Wp(Z!bOY*gZr*grs'}sw*gwx)rx!_*g!_!`#Np!`#O*g#P;'S*g;'S;=`+Z<%lO*g(El#NyX$Q(Ch(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g(El$ oX#s(Ch(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g*)x$!ga#`*!Y$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`0z!`!a$#l!a#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(K[$#w_#k(Cl$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z*)x$%Vag!*r#s(Ch$f#|$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`$&[!`!a$'f!a#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW$&g_#s(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW$'qa#r(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`!a$(v!a#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW$)R`#r(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(Kd$*`a(r(Ct$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!a%Z!a!b$+e!b#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW$+p`$i&j#{(Ch(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#`$,}_!|$Ip$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z04f$.X_!S0,v$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(n$/]Z$i&jO!^$0O!^!_$0f!_#i$0O#i#j$0k#j#l$0O#l#m$2^#m#o$0O#o#p$0f#p;'S$0O;'S;=`$4i<%lO$0O(n$0VT_#S$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c#S$0kO_#S(n$0p[$i&jO!Q&c!Q![$1f![!^&c!_!c&c!c!i$1f!i#T&c#T#Z$1f#Z#o&c#o#p$3|#p;'S&c;'S;=`&w<%lO&c(n$1kZ$i&jO!Q&c!Q![$2^![!^&c!_!c&c!c!i$2^!i#T&c#T#Z$2^#Z#o&c#p;'S&c;'S;=`&w<%lO&c(n$2cZ$i&jO!Q&c!Q![$3U![!^&c!_!c&c!c!i$3U!i#T&c#T#Z$3U#Z#o&c#p;'S&c;'S;=`&w<%lO&c(n$3ZZ$i&jO!Q&c!Q![$0O![!^&c!_!c&c!c!i$0O!i#T&c#T#Z$0O#Z#o&c#p;'S&c;'S;=`&w<%lO&c#S$4PR!Q![$4Y!c!i$4Y#T#Z$4Y#S$4]S!Q![$4Y!c!i$4Y#T#Z$4Y#q#r$0f(n$4lP;=`<%l$0O#1[$4z_!Y#)l$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(KW$6U`#x(Ch$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z+;p$7c_$i&j(Wp(Z!b(a+4QOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z07[$8qk$i&j(Wp(Z!b(T,2j$_#t(e$I[OY%ZYZ&cZr%Zrs&}st%Ztu$8buw%Zwx(rx}%Z}!O$:f!O!Q%Z!Q![$8b![!^%Z!^!_*g!_!c%Z!c!}$8b!}#O%Z#O#P&c#P#R%Z#R#S$8b#S#T%Z#T#o$8b#o#p*g#p$g%Z$g;'S$8b;'S;=`$<l<%lO$8b+d$:qk$i&j(Wp(Z!b$_#tOY%ZYZ&cZr%Zrs&}st%Ztu$:fuw%Zwx(rx}%Z}!O$:f!O!Q%Z!Q![$:f![!^%Z!^!_*g!_!c%Z!c!}$:f!}#O%Z#O#P&c#P#R%Z#R#S$:f#S#T%Z#T#o$:f#o#p*g#p$g%Z$g;'S$:f;'S;=`$<f<%lO$:f+d$<iP;=`<%l$:f07[$<oP;=`<%l$8b#Jf$<{X!_#Hb(Wp(Z!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g,#x$=sa(y+JY$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p#q$+e#q;'S%Z;'S;=`+a<%lO%Z)>v$?V_!^(CdvBr$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z?O$@a_!q7`$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z07[$Aq|$i&j(Wp(Z!b'|0/l$]#t(T,2j(e$I[OX%ZXY+gYZ&cZ[+g[p%Zpq+gqr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr07[$D|k$i&j(Wp(Z!b'}0/l$]#t(T,2j(e$I[OY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr",
  tokenizers: [noSemicolon, noSemicolonType, operatorToken, jsx, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, insertSemicolon, new LocalTokenGroup("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOx~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!U~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(c~~", 141, 340), new LocalTokenGroup("j~RQYZXz{^~^O(Q~~aP!P!Qd~iO(R~~", 25, 323)],
  topRules: {"Script":[0,7],"SingleExpression":[1,276],"SingleClassItem":[2,277]},
  dialects: {jsx: 0, ts: 15175},
  dynamicPrecedences: {"80":1,"82":1,"94":1,"169":1,"199":1},
  specialized: [{term: 327, get: (value) => spec_identifier[value] || -1},{term: 343, get: (value) => spec_word[value] || -1},{term: 95, get: (value) => spec_LessThan[value] || -1}],
  tokenPrec: 15201
});



;// ../../node_modules/@codemirror/lang-javascript/dist/index.js







/**
A collection of JavaScript-related
[snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
*/
const snippets = [
    /*@__PURE__*/snippetCompletion("function ${name}(${params}) {\n\t${}\n}", {
        label: "function",
        detail: "definition",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n\t${}\n}", {
        label: "for",
        detail: "loop",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("for (let ${name} of ${collection}) {\n\t${}\n}", {
        label: "for",
        detail: "of loop",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("do {\n\t${}\n} while (${})", {
        label: "do",
        detail: "loop",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("while (${}) {\n\t${}\n}", {
        label: "while",
        detail: "loop",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("try {\n\t${}\n} catch (${error}) {\n\t${}\n}", {
        label: "try",
        detail: "/ catch block",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("if (${}) {\n\t${}\n}", {
        label: "if",
        detail: "block",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("if (${}) {\n\t${}\n} else {\n\t${}\n}", {
        label: "if",
        detail: "/ else block",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("class ${name} {\n\tconstructor(${params}) {\n\t\t${}\n\t}\n}", {
        label: "class",
        detail: "definition",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("import {${names}} from \"${module}\"\n${}", {
        label: "import",
        detail: "named",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("import ${name} from \"${module}\"\n${}", {
        label: "import",
        detail: "default",
        type: "keyword"
    })
];
/**
A collection of snippet completions for TypeScript. Includes the
JavaScript [snippets](https://codemirror.net/6/docs/ref/#lang-javascript.snippets).
*/
const typescriptSnippets = /*@__PURE__*/snippets.concat([
    /*@__PURE__*/snippetCompletion("interface ${name} {\n\t${}\n}", {
        label: "interface",
        detail: "definition",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("type ${name} = ${type}", {
        label: "type",
        detail: "definition",
        type: "keyword"
    }),
    /*@__PURE__*/snippetCompletion("enum ${name} {\n\t${}\n}", {
        label: "enum",
        detail: "definition",
        type: "keyword"
    })
]);

const cache = /*@__PURE__*/new NodeWeakMap();
const ScopeNodes = /*@__PURE__*/new Set([
    "Script", "Block",
    "FunctionExpression", "FunctionDeclaration", "ArrowFunction", "MethodDeclaration",
    "ForStatement"
]);
function defID(type) {
    return (node, def) => {
        let id = node.node.getChild("VariableDefinition");
        if (id)
            def(id, type);
        return true;
    };
}
const functionContext = ["FunctionDeclaration"];
const gatherCompletions = {
    FunctionDeclaration: /*@__PURE__*/defID("function"),
    ClassDeclaration: /*@__PURE__*/defID("class"),
    ClassExpression: () => true,
    EnumDeclaration: /*@__PURE__*/defID("constant"),
    TypeAliasDeclaration: /*@__PURE__*/defID("type"),
    NamespaceDeclaration: /*@__PURE__*/defID("namespace"),
    VariableDefinition(node, def) { if (!node.matchContext(functionContext))
        def(node, "variable"); },
    TypeDefinition(node, def) { def(node, "type"); },
    __proto__: null
};
function getScope(doc, node) {
    let cached = cache.get(node);
    if (cached)
        return cached;
    let completions = [], top = true;
    function def(node, type) {
        let name = doc.sliceString(node.from, node.to);
        completions.push({ label: name, type });
    }
    node.cursor(IterMode.IncludeAnonymous).iterate(node => {
        if (top) {
            top = false;
        }
        else if (node.name) {
            let gather = gatherCompletions[node.name];
            if (gather && gather(node, def) || ScopeNodes.has(node.name))
                return false;
        }
        else if (node.to - node.from > 8192) {
            // Allow caching for bigger internal nodes
            for (let c of getScope(doc, node.node))
                completions.push(c);
            return false;
        }
    });
    cache.set(node, completions);
    return completions;
}
const Identifier = /^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/;
const dontComplete = [
    "TemplateString", "String", "RegExp",
    "LineComment", "BlockComment",
    "VariableDefinition", "TypeDefinition", "Label",
    "PropertyDefinition", "PropertyName",
    "PrivatePropertyDefinition", "PrivatePropertyName",
    "JSXText", "JSXAttributeValue", "JSXOpenTag", "JSXCloseTag", "JSXSelfClosingTag",
    ".", "?."
];
/**
Completion source that looks up locally defined names in
JavaScript code.
*/
function localCompletionSource(context) {
    let inner = dist_syntaxTree(context.state).resolveInner(context.pos, -1);
    if (dontComplete.indexOf(inner.name) > -1)
        return null;
    let isWord = inner.name == "VariableName" ||
        inner.to - inner.from < 20 && Identifier.test(context.state.sliceDoc(inner.from, inner.to));
    if (!isWord && !context.explicit)
        return null;
    let options = [];
    for (let pos = inner; pos; pos = pos.parent) {
        if (ScopeNodes.has(pos.name))
            options = options.concat(getScope(context.state.doc, pos));
    }
    return {
        options,
        from: isWord ? inner.from : context.pos,
        validFor: Identifier
    };
}
function pathFor(read, member, name) {
    var _a;
    let path = [];
    for (;;) {
        let obj = member.firstChild, prop;
        if ((obj === null || obj === void 0 ? void 0 : obj.name) == "VariableName") {
            path.push(read(obj));
            return { path: path.reverse(), name };
        }
        else if ((obj === null || obj === void 0 ? void 0 : obj.name) == "MemberExpression" && ((_a = (prop = obj.lastChild)) === null || _a === void 0 ? void 0 : _a.name) == "PropertyName") {
            path.push(read(prop));
            member = obj;
        }
        else {
            return null;
        }
    }
}
/**
Helper function for defining JavaScript completion sources. It
returns the completable name and object path for a completion
context, or null if no name/property completion should happen at
that position. For example, when completing after `a.b.c` it will
return `{path: ["a", "b"], name: "c"}`. When completing after `x`
it will return `{path: [], name: "x"}`. When not in a property or
name, it will return null if `context.explicit` is false, and
`{path: [], name: ""}` otherwise.
*/
function completionPath(context) {
    let read = (node) => context.state.doc.sliceString(node.from, node.to);
    let inner = syntaxTree(context.state).resolveInner(context.pos, -1);
    if (inner.name == "PropertyName") {
        return pathFor(read, inner.parent, read(inner));
    }
    else if ((inner.name == "." || inner.name == "?.") && inner.parent.name == "MemberExpression") {
        return pathFor(read, inner.parent, "");
    }
    else if (dontComplete.indexOf(inner.name) > -1) {
        return null;
    }
    else if (inner.name == "VariableName" || inner.to - inner.from < 20 && Identifier.test(read(inner))) {
        return { path: [], name: read(inner) };
    }
    else if (inner.name == "MemberExpression") {
        return pathFor(read, inner, "");
    }
    else {
        return context.explicit ? { path: [], name: "" } : null;
    }
}
function enumeratePropertyCompletions(obj, top) {
    let options = [], seen = new Set;
    for (let depth = 0;; depth++) {
        for (let name of (Object.getOwnPropertyNames || Object.keys)(obj)) {
            if (!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(name) || seen.has(name))
                continue;
            seen.add(name);
            let value;
            try {
                value = obj[name];
            }
            catch (_) {
                continue;
            }
            options.push({
                label: name,
                type: typeof value == "function" ? (/^[A-Z]/.test(name) ? "class" : top ? "function" : "method")
                    : top ? "variable" : "property",
                boost: -depth
            });
        }
        let next = Object.getPrototypeOf(obj);
        if (!next)
            return options;
        obj = next;
    }
}
/**
Defines a [completion source](https://codemirror.net/6/docs/ref/#autocomplete.CompletionSource) that
completes from the given scope object (for example `globalThis`).
Will enter properties of the object when completing properties on
a directly-named path.
*/
function scopeCompletionSource(scope) {
    let cache = new Map;
    return (context) => {
        let path = completionPath(context);
        if (!path)
            return null;
        let target = scope;
        for (let step of path.path) {
            target = target[step];
            if (!target)
                return null;
        }
        let options = cache.get(target);
        if (!options)
            cache.set(target, options = enumeratePropertyCompletions(target, !path.path.length));
        return {
            from: context.pos - path.name.length,
            options,
            validFor: Identifier
        };
    };
}

/**
A language provider based on the [Lezer JavaScript
parser](https://github.com/lezer-parser/javascript), extended with
highlighting and indentation information.
*/
const javascriptLanguage = /*@__PURE__*/LRLanguage.define({
    name: "javascript",
    parser: /*@__PURE__*/parser.configure({
        props: [
            /*@__PURE__*/indentNodeProp.add({
                IfStatement: /*@__PURE__*/continuedIndent({ except: /^\s*({|else\b)/ }),
                TryStatement: /*@__PURE__*/continuedIndent({ except: /^\s*({|catch\b|finally\b)/ }),
                LabeledStatement: flatIndent,
                SwitchBody: context => {
                    let after = context.textAfter, closed = /^\s*\}/.test(after), isCase = /^\s*(case|default)\b/.test(after);
                    return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit;
                },
                Block: /*@__PURE__*/delimitedIndent({ closing: "}" }),
                ArrowFunction: cx => cx.baseIndent + cx.unit,
                "TemplateString BlockComment": () => null,
                "Statement Property": /*@__PURE__*/continuedIndent({ except: /^\s*{/ }),
                JSXElement(context) {
                    let closed = /^\s*<\//.test(context.textAfter);
                    return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);
                },
                JSXEscape(context) {
                    let closed = /\s*\}/.test(context.textAfter);
                    return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);
                },
                "JSXOpenTag JSXSelfClosingTag"(context) {
                    return context.column(context.node.from) + context.unit;
                }
            }),
            /*@__PURE__*/foldNodeProp.add({
                "Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType": foldInside,
                BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }
            })
        ]
    }),
    languageData: {
        closeBrackets: { brackets: ["(", "[", "{", "'", '"', "`"] },
        commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
        indentOnInput: /^\s*(?:case |default:|\{|\}|<\/)$/,
        wordChars: "$"
    }
});
const jsxSublanguage = {
    test: node => /^JSX/.test(node.name),
    facet: /*@__PURE__*/defineLanguageFacet({ commentTokens: { block: { open: "{/*", close: "*/}" } } })
};
/**
A language provider for TypeScript.
*/
const typescriptLanguage = /*@__PURE__*/javascriptLanguage.configure({ dialect: "ts" }, "typescript");
/**
Language provider for JSX.
*/
const jsxLanguage = /*@__PURE__*/javascriptLanguage.configure({
    dialect: "jsx",
    props: [/*@__PURE__*/sublanguageProp.add(n => n.isTop ? [jsxSublanguage] : undefined)]
});
/**
Language provider for JSX + TypeScript.
*/
const tsxLanguage = /*@__PURE__*/javascriptLanguage.configure({
    dialect: "jsx ts",
    props: [/*@__PURE__*/sublanguageProp.add(n => n.isTop ? [jsxSublanguage] : undefined)]
}, "typescript");
let kwCompletion = (name) => ({ label: name, type: "keyword" });
const keywords = /*@__PURE__*/"break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(kwCompletion);
const typescriptKeywords = /*@__PURE__*/keywords.concat(/*@__PURE__*/["declare", "implements", "private", "protected", "public"].map(kwCompletion));
/**
JavaScript support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-javascript.snippets)
and local variable completion.
*/
function javascript(config = {}) {
    let lang = config.jsx ? (config.typescript ? tsxLanguage : jsxLanguage)
        : config.typescript ? typescriptLanguage : javascriptLanguage;
    let completions = config.typescript ? typescriptSnippets.concat(typescriptKeywords) : snippets.concat(keywords);
    return new LanguageSupport(lang, [
        javascriptLanguage.data.of({
            autocomplete: ifNotIn(dontComplete, completeFromList(completions))
        }),
        javascriptLanguage.data.of({
            autocomplete: localCompletionSource
        }),
        config.jsx ? autoCloseTags : [],
    ]);
}
function findOpenTag(node) {
    for (;;) {
        if (node.name == "JSXOpenTag" || node.name == "JSXSelfClosingTag" || node.name == "JSXFragmentTag")
            return node;
        if (node.name == "JSXEscape" || !node.parent)
            return null;
        node = node.parent;
    }
}
function elementName(doc, tree, max = doc.length) {
    for (let ch = tree === null || tree === void 0 ? void 0 : tree.firstChild; ch; ch = ch.nextSibling) {
        if (ch.name == "JSXIdentifier" || ch.name == "JSXBuiltin" || ch.name == "JSXNamespacedName" ||
            ch.name == "JSXMemberExpression")
            return doc.sliceString(ch.from, Math.min(ch.to, max));
    }
    return "";
}
const dist_android = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent);
/**
Extension that will automatically insert JSX close tags when a `>` or
`/` is typed.
*/
const autoCloseTags = /*@__PURE__*/dist_EditorView.inputHandler.of((view, from, to, text, defaultInsert) => {
    if ((dist_android ? view.composing : view.compositionStarted) || view.state.readOnly ||
        from != to || (text != ">" && text != "/") ||
        !javascriptLanguage.isActiveAt(view.state, from, -1))
        return false;
    let base = defaultInsert(), { state } = base;
    let closeTags = state.changeByRange(range => {
        var _a;
        let { head } = range, around = dist_syntaxTree(state).resolveInner(head - 1, -1), name;
        if (around.name == "JSXStartTag")
            around = around.parent;
        if (state.doc.sliceString(head - 1, head) != text || around.name == "JSXAttributeValue" && around.to > head) ;
        else if (text == ">" && around.name == "JSXFragmentTag") {
            return { range, changes: { from: head, insert: `</>` } };
        }
        else if (text == "/" && around.name == "JSXStartCloseTag") {
            let empty = around.parent, base = empty.parent;
            if (base && empty.from == head - 2 &&
                ((name = elementName(state.doc, base.firstChild, head)) || ((_a = base.firstChild) === null || _a === void 0 ? void 0 : _a.name) == "JSXFragmentTag")) {
                let insert = `${name}>`;
                return { range: dist_EditorSelection.cursor(head + insert.length, -1), changes: { from: head, insert } };
            }
        }
        else if (text == ">") {
            let openTag = findOpenTag(around);
            if (openTag && openTag.name == "JSXOpenTag" &&
                !/^\/?>|^<\//.test(state.doc.sliceString(head, head + 2)) &&
                (name = elementName(state.doc, openTag, head)))
                return { range, changes: { from: head, insert: `</${name}>` } };
        }
        return { range };
    });
    if (closeTags.changes.empty)
        return false;
    view.dispatch([
        base,
        state.update(closeTags, { userEvent: "input.complete", scrollIntoView: true })
    ]);
    return true;
});

/**
Connects an [ESLint](https://eslint.org/) linter to CodeMirror's
[lint](https://codemirror.net/6/docs/ref/#lint) integration. `eslint` should be an instance of the
[`Linter`](https://eslint.org/docs/developer-guide/nodejs-api#linter)
class, and `config` an optional ESLint configuration. The return
value of this function can be passed to [`linter`](https://codemirror.net/6/docs/ref/#lint.linter)
to create a JavaScript linting extension.

Note that ESLint targets node, and is tricky to run in the
browser. The
[eslint-linter-browserify](https://github.com/UziTech/eslint-linter-browserify)
package may help with that (see
[example](https://github.com/UziTech/eslint-linter-browserify/blob/master/example/script.js)).
*/
function esLint(eslint, config) {
    if (!config) {
        config = {
            parserOptions: { ecmaVersion: 2019, sourceType: "module" },
            env: { browser: true, node: true, es6: true, es2015: true, es2017: true, es2020: true },
            rules: {}
        };
        eslint.getRules().forEach((desc, name) => {
            var _a;
            if ((_a = desc.meta.docs) === null || _a === void 0 ? void 0 : _a.recommended)
                config.rules[name] = 2;
        });
    }
    return (view) => {
        let { state } = view, found = [];
        for (let { from, to } of javascriptLanguage.findRegions(state)) {
            let fromLine = state.doc.lineAt(from), offset = { line: fromLine.number - 1, col: from - fromLine.from, pos: from };
            for (let d of eslint.verify(state.sliceDoc(from, to), config))
                found.push(translateDiagnostic(d, state.doc, offset));
        }
        return found;
    };
}
function mapPos(line, col, doc, offset) {
    return doc.line(line + offset.line).from + col + (line == 1 ? offset.col - 1 : -1);
}
function translateDiagnostic(input, doc, offset) {
    let start = mapPos(input.line, input.column, doc, offset);
    let result = {
        from: start,
        to: input.endLine != null && input.endColumn != 1 ? mapPos(input.endLine, input.endColumn, doc, offset) : start,
        message: input.message,
        source: input.ruleId ? "eslint:" + input.ruleId : "eslint",
        severity: input.severity == 1 ? "warning" : "error",
    };
    if (input.fix) {
        let { range, text } = input.fix, from = range[0] + offset.pos - start, to = range[1] + offset.pos - start;
        result.actions = [{
                name: "fix",
                apply(view, start) {
                    view.dispatch({ changes: { from: start + from, to: start + to, insert: text }, scrollIntoView: true });
                }
            }];
    }
    return result;
}



;// ../../node_modules/@codemirror/search/dist/index.js




const basicNormalize = typeof String.prototype.normalize == "function"
    ? x => x.normalize("NFKD") : x => x;
/**
A search cursor provides an iterator over text matches in a
document.
*/
class SearchCursor {
    /**
    Create a text cursor. The query is the search string, `from` to
    `to` provides the region to search.
    
    When `normalize` is given, it will be called, on both the query
    string and the content it is matched against, before comparing.
    You can, for example, create a case-insensitive search by
    passing `s => s.toLowerCase()`.
    
    Text is always normalized with
    [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize)
    (when supported).
    */
    constructor(text, query, from = 0, to = text.length, normalize, test) {
        this.test = test;
        /**
        The current match (only holds a meaningful value after
        [`next`](https://codemirror.net/6/docs/ref/#search.SearchCursor.next) has been called and when
        `done` is false).
        */
        this.value = { from: 0, to: 0 };
        /**
        Whether the end of the iterated region has been reached.
        */
        this.done = false;
        this.matches = [];
        this.buffer = "";
        this.bufferPos = 0;
        this.iter = text.iterRange(from, to);
        this.bufferStart = from;
        this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize;
        this.query = this.normalize(query);
    }
    peek() {
        if (this.bufferPos == this.buffer.length) {
            this.bufferStart += this.buffer.length;
            this.iter.next();
            if (this.iter.done)
                return -1;
            this.bufferPos = 0;
            this.buffer = this.iter.value;
        }
        return dist_codePointAt(this.buffer, this.bufferPos);
    }
    /**
    Look for the next match. Updates the iterator's
    [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and
    [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called
    at least once before using the cursor.
    */
    next() {
        while (this.matches.length)
            this.matches.pop();
        return this.nextOverlapping();
    }
    /**
    The `next` method will ignore matches that partially overlap a
    previous match. This method behaves like `next`, but includes
    such matches.
    */
    nextOverlapping() {
        for (;;) {
            let next = this.peek();
            if (next < 0) {
                this.done = true;
                return this;
            }
            let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos;
            this.bufferPos += dist_codePointSize(next);
            let norm = this.normalize(str);
            if (norm.length)
                for (let i = 0, pos = start;; i++) {
                    let code = norm.charCodeAt(i);
                    let match = this.match(code, pos, this.bufferPos + this.bufferStart);
                    if (i == norm.length - 1) {
                        if (match) {
                            this.value = match;
                            return this;
                        }
                        break;
                    }
                    if (pos == start && i < str.length && str.charCodeAt(i) == code)
                        pos++;
                }
        }
    }
    match(code, pos, end) {
        let match = null;
        for (let i = 0; i < this.matches.length; i += 2) {
            let index = this.matches[i], keep = false;
            if (this.query.charCodeAt(index) == code) {
                if (index == this.query.length - 1) {
                    match = { from: this.matches[i + 1], to: end };
                }
                else {
                    this.matches[i]++;
                    keep = true;
                }
            }
            if (!keep) {
                this.matches.splice(i, 2);
                i -= 2;
            }
        }
        if (this.query.charCodeAt(0) == code) {
            if (this.query.length == 1)
                match = { from: pos, to: end };
            else
                this.matches.push(1, pos);
        }
        if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferStart))
            match = null;
        return match;
    }
}
if (typeof Symbol != "undefined")
    SearchCursor.prototype[Symbol.iterator] = function () { return this; };

const empty = { from: -1, to: -1, match: /*@__PURE__*//.*/.exec("") };
const baseFlags = "gm" + (/x/.unicode == null ? "" : "u");
/**
This class is similar to [`SearchCursor`](https://codemirror.net/6/docs/ref/#search.SearchCursor)
but searches for a regular expression pattern instead of a plain
string.
*/
class RegExpCursor {
    /**
    Create a cursor that will search the given range in the given
    document. `query` should be the raw pattern (as you'd pass it to
    `new RegExp`).
    */
    constructor(text, query, options, from = 0, to = text.length) {
        this.text = text;
        this.to = to;
        this.curLine = "";
        /**
        Set to `true` when the cursor has reached the end of the search
        range.
        */
        this.done = false;
        /**
        Will contain an object with the extent of the match and the
        match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next)
        sucessfully finds a match.
        */
        this.value = empty;
        if (/\\[sWDnr]|\n|\r|\[\^/.test(query))
            return new MultilineRegExpCursor(text, query, options, from, to);
        this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : ""));
        this.test = options === null || options === void 0 ? void 0 : options.test;
        this.iter = text.iter();
        let startLine = text.lineAt(from);
        this.curLineStart = startLine.from;
        this.matchPos = toCharEnd(text, from);
        this.getLine(this.curLineStart);
    }
    getLine(skip) {
        this.iter.next(skip);
        if (this.iter.lineBreak) {
            this.curLine = "";
        }
        else {
            this.curLine = this.iter.value;
            if (this.curLineStart + this.curLine.length > this.to)
                this.curLine = this.curLine.slice(0, this.to - this.curLineStart);
            this.iter.next();
        }
    }
    nextLine() {
        this.curLineStart = this.curLineStart + this.curLine.length + 1;
        if (this.curLineStart > this.to)
            this.curLine = "";
        else
            this.getLine(0);
    }
    /**
    Move to the next match, if there is one.
    */
    next() {
        for (let off = this.matchPos - this.curLineStart;;) {
            this.re.lastIndex = off;
            let match = this.matchPos <= this.to && this.re.exec(this.curLine);
            if (match) {
                let from = this.curLineStart + match.index, to = from + match[0].length;
                this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
                if (from == this.curLineStart + this.curLine.length)
                    this.nextLine();
                if ((from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) {
                    this.value = { from, to, match };
                    return this;
                }
                off = this.matchPos - this.curLineStart;
            }
            else if (this.curLineStart + this.curLine.length < this.to) {
                this.nextLine();
                off = 0;
            }
            else {
                this.done = true;
                return this;
            }
        }
    }
}
const flattened = /*@__PURE__*/new WeakMap();
// Reusable (partially) flattened document strings
class FlattenedDoc {
    constructor(from, text) {
        this.from = from;
        this.text = text;
    }
    get to() { return this.from + this.text.length; }
    static get(doc, from, to) {
        let cached = flattened.get(doc);
        if (!cached || cached.from >= to || cached.to <= from) {
            let flat = new FlattenedDoc(from, doc.sliceString(from, to));
            flattened.set(doc, flat);
            return flat;
        }
        if (cached.from == from && cached.to == to)
            return cached;
        let { text, from: cachedFrom } = cached;
        if (cachedFrom > from) {
            text = doc.sliceString(from, cachedFrom) + text;
            cachedFrom = from;
        }
        if (cached.to < to)
            text += doc.sliceString(cached.to, to);
        flattened.set(doc, new FlattenedDoc(cachedFrom, text));
        return new FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom));
    }
}
class MultilineRegExpCursor {
    constructor(text, query, options, from, to) {
        this.text = text;
        this.to = to;
        this.done = false;
        this.value = empty;
        this.matchPos = toCharEnd(text, from);
        this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : ""));
        this.test = options === null || options === void 0 ? void 0 : options.test;
        this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5000 /* Chunk.Base */));
    }
    chunkEnd(pos) {
        return pos >= this.to ? this.to : this.text.lineAt(pos).to;
    }
    next() {
        for (;;) {
            let off = this.re.lastIndex = this.matchPos - this.flat.from;
            let match = this.re.exec(this.flat.text);
            // Skip empty matches directly after the last match
            if (match && !match[0] && match.index == off) {
                this.re.lastIndex = off + 1;
                match = this.re.exec(this.flat.text);
            }
            if (match) {
                let from = this.flat.from + match.index, to = from + match[0].length;
                // If a match goes almost to the end of a noncomplete chunk, try
                // again, since it'll likely be able to match more
                if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) &&
                    (!this.test || this.test(from, to, match))) {
                    this.value = { from, to, match };
                    this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
                    return this;
                }
            }
            if (this.flat.to == this.to) {
                this.done = true;
                return this;
            }
            // Grow the flattened doc
            this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2));
        }
    }
}
if (typeof Symbol != "undefined") {
    RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] =
        function () { return this; };
}
function validRegExp(source) {
    try {
        new RegExp(source, baseFlags);
        return true;
    }
    catch (_a) {
        return false;
    }
}
function toCharEnd(text, pos) {
    if (pos >= text.length)
        return pos;
    let line = text.lineAt(pos), next;
    while (pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 0xDC00 && next < 0xE000)
        pos++;
    return pos;
}

function createLineDialog(view) {
    let line = String(view.state.doc.lineAt(view.state.selection.main.head).number);
    let input = external_crelt_namespaceObject("input", { class: "cm-textfield", name: "line", value: line });
    let dom = external_crelt_namespaceObject("form", {
        class: "cm-gotoLine",
        onkeydown: (event) => {
            if (event.keyCode == 27) { // Escape
                event.preventDefault();
                view.dispatch({ effects: dialogEffect.of(false) });
                view.focus();
            }
            else if (event.keyCode == 13) { // Enter
                event.preventDefault();
                go();
            }
        },
        onsubmit: (event) => {
            event.preventDefault();
            go();
        }
    }, external_crelt_namespaceObject("label", view.state.phrase("Go to line"), ": ", input), " ", external_crelt_namespaceObject("button", { class: "cm-button", type: "submit" }, view.state.phrase("go")), external_crelt_namespaceObject("button", {
        name: "close",
        onclick: () => {
            view.dispatch({ effects: dialogEffect.of(false) });
            view.focus();
        },
        "aria-label": view.state.phrase("close"),
        type: "button"
    }, ["×"]));
    function go() {
        let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);
        if (!match)
            return;
        let { state } = view, startLine = state.doc.lineAt(state.selection.main.head);
        let [, sign, ln, cl, percent] = match;
        let col = cl ? +cl.slice(1) : 0;
        let line = ln ? +ln : startLine.number;
        if (ln && percent) {
            let pc = line / 100;
            if (sign)
                pc = pc * (sign == "-" ? -1 : 1) + (startLine.number / state.doc.lines);
            line = Math.round(state.doc.lines * pc);
        }
        else if (ln && sign) {
            line = line * (sign == "-" ? -1 : 1) + startLine.number;
        }
        let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line)));
        let selection = dist_EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length)));
        view.dispatch({
            effects: [dialogEffect.of(false), dist_EditorView.scrollIntoView(selection.from, { y: 'center' })],
            selection,
        });
        view.focus();
    }
    return { dom };
}
const dialogEffect = /*@__PURE__*/dist_StateEffect.define();
const dist_dialogField = /*@__PURE__*/dist_StateField.define({
    create() { return true; },
    update(value, tr) {
        for (let e of tr.effects)
            if (e.is(dialogEffect))
                value = e.value;
        return value;
    },
    provide: f => showPanel.from(f, val => val ? createLineDialog : null)
});
/**
Command that shows a dialog asking the user for a line number, and
when a valid position is provided, moves the cursor to that line.

Supports line numbers, relative line offsets prefixed with `+` or
`-`, document percentages suffixed with `%`, and an optional
column position by adding `:` and a second number after the line
number.
*/
const gotoLine = view => {
    let panel = getPanel(view, createLineDialog);
    if (!panel) {
        let effects = [dialogEffect.of(true)];
        if (view.state.field(dist_dialogField, false) == null)
            effects.push(dist_StateEffect.appendConfig.of([dist_dialogField, search_dist_baseTheme$1]));
        view.dispatch({ effects });
        panel = getPanel(view, createLineDialog);
    }
    if (panel)
        panel.dom.querySelector("input").select();
    return true;
};
const search_dist_baseTheme$1 = /*@__PURE__*/dist_EditorView.baseTheme({
    ".cm-panel.cm-gotoLine": {
        padding: "2px 6px 4px",
        position: "relative",
        "& label": { fontSize: "80%" },
        "& [name=close]": {
            position: "absolute",
            top: "0", bottom: "0",
            right: "4px",
            backgroundColor: "inherit",
            border: "none",
            font: "inherit",
            padding: "0"
        }
    }
});

const defaultHighlightOptions = {
    highlightWordAroundCursor: false,
    minSelectionLength: 1,
    maxMatches: 100,
    wholeWords: false
};
const highlightConfig = /*@__PURE__*/Facet.define({
    combine(options) {
        return combineConfig(options, defaultHighlightOptions, {
            highlightWordAroundCursor: (a, b) => a || b,
            minSelectionLength: Math.min,
            maxMatches: Math.min
        });
    }
});
/**
This extension highlights text that matches the selection. It uses
the `"cm-selectionMatch"` class for the highlighting. When
`highlightWordAroundCursor` is enabled, the word at the cursor
itself will be highlighted with `"cm-selectionMatch-main"`.
*/
function highlightSelectionMatches(options) {
    let ext = [defaultTheme, matchHighlighter];
    if (options)
        ext.push(highlightConfig.of(options));
    return ext;
}
const matchDeco = /*@__PURE__*/dist_Decoration.mark({ class: "cm-selectionMatch" });
const mainMatchDeco = /*@__PURE__*/dist_Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" });
// Whether the characters directly outside the given positions are non-word characters
function insideWordBoundaries(check, state, from, to) {
    return (from == 0 || check(state.sliceDoc(from - 1, from)) != dist_CharCategory.Word) &&
        (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != dist_CharCategory.Word);
}
// Whether the characters directly at the given positions are word characters
function insideWord(check, state, from, to) {
    return check(state.sliceDoc(from, from + 1)) == dist_CharCategory.Word
        && check(state.sliceDoc(to - 1, to)) == dist_CharCategory.Word;
}
const matchHighlighter = /*@__PURE__*/dist_ViewPlugin.fromClass(class {
    constructor(view) {
        this.decorations = this.getDeco(view);
    }
    update(update) {
        if (update.selectionSet || update.docChanged || update.viewportChanged)
            this.decorations = this.getDeco(update.view);
    }
    getDeco(view) {
        let conf = view.state.facet(highlightConfig);
        let { state } = view, sel = state.selection;
        if (sel.ranges.length > 1)
            return dist_Decoration.none;
        let range = sel.main, query, check = null;
        if (range.empty) {
            if (!conf.highlightWordAroundCursor)
                return dist_Decoration.none;
            let word = state.wordAt(range.head);
            if (!word)
                return dist_Decoration.none;
            check = state.charCategorizer(range.head);
            query = state.sliceDoc(word.from, word.to);
        }
        else {
            let len = range.to - range.from;
            if (len < conf.minSelectionLength || len > 200)
                return dist_Decoration.none;
            if (conf.wholeWords) {
                query = state.sliceDoc(range.from, range.to); // TODO: allow and include leading/trailing space?
                check = state.charCategorizer(range.head);
                if (!(insideWordBoundaries(check, state, range.from, range.to) &&
                    insideWord(check, state, range.from, range.to)))
                    return dist_Decoration.none;
            }
            else {
                query = state.sliceDoc(range.from, range.to);
                if (!query)
                    return dist_Decoration.none;
            }
        }
        let deco = [];
        for (let part of view.visibleRanges) {
            let cursor = new SearchCursor(state.doc, query, part.from, part.to);
            while (!cursor.next().done) {
                let { from, to } = cursor.value;
                if (!check || insideWordBoundaries(check, state, from, to)) {
                    if (range.empty && from <= range.from && to >= range.to)
                        deco.push(mainMatchDeco.range(from, to));
                    else if (from >= range.to || to <= range.from)
                        deco.push(matchDeco.range(from, to));
                    if (deco.length > conf.maxMatches)
                        return dist_Decoration.none;
                }
            }
        }
        return dist_Decoration.set(deco);
    }
}, {
    decorations: v => v.decorations
});
const defaultTheme = /*@__PURE__*/dist_EditorView.baseTheme({
    ".cm-selectionMatch": { backgroundColor: "#99ff7780" },
    ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" }
});
// Select the words around the cursors.
const selectWord = ({ state, dispatch }) => {
    let { selection } = state;
    let newSel = dist_EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || dist_EditorSelection.cursor(range.head)), selection.mainIndex);
    if (newSel.eq(selection))
        return false;
    dispatch(state.update({ selection: newSel }));
    return true;
};
// Find next occurrence of query relative to last cursor. Wrap around
// the document if there are no more matches.
function findNextOccurrence(state, query) {
    let { main, ranges } = state.selection;
    let word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to;
    for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to);;) {
        cursor.next();
        if (cursor.done) {
            if (cycled)
                return null;
            cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1));
            cycled = true;
        }
        else {
            if (cycled && ranges.some(r => r.from == cursor.value.from))
                continue;
            if (fullWord) {
                let word = state.wordAt(cursor.value.from);
                if (!word || word.from != cursor.value.from || word.to != cursor.value.to)
                    continue;
            }
            return cursor.value;
        }
    }
}
/**
Select next occurrence of the current selection. Expand selection
to the surrounding word when the selection is empty.
*/
const selectNextOccurrence = ({ state, dispatch }) => {
    let { ranges } = state.selection;
    if (ranges.some(sel => sel.from === sel.to))
        return selectWord({ state, dispatch });
    let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to);
    if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText))
        return false;
    let range = findNextOccurrence(state, searchedText);
    if (!range)
        return false;
    dispatch(state.update({
        selection: state.selection.addRange(dist_EditorSelection.range(range.from, range.to), false),
        effects: dist_EditorView.scrollIntoView(range.to)
    }));
    return true;
};

const searchConfigFacet = /*@__PURE__*/Facet.define({
    combine(configs) {
        return combineConfig(configs, {
            top: false,
            caseSensitive: false,
            literal: false,
            regexp: false,
            wholeWord: false,
            createPanel: view => new SearchPanel(view),
            scrollToMatch: range => dist_EditorView.scrollIntoView(range)
        });
    }
});
/**
Add search state to the editor configuration, and optionally
configure the search extension.
([`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) will automatically
enable this if it isn't already on).
*/
function search(config) {
    return config ? [searchConfigFacet.of(config), searchExtensions] : searchExtensions;
}
/**
A search query. Part of the editor's search state.
*/
class SearchQuery {
    /**
    Create a query object.
    */
    constructor(config) {
        this.search = config.search;
        this.caseSensitive = !!config.caseSensitive;
        this.literal = !!config.literal;
        this.regexp = !!config.regexp;
        this.replace = config.replace || "";
        this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
        this.unquoted = this.unquote(this.search);
        this.wholeWord = !!config.wholeWord;
    }
    /**
    @internal
    */
    unquote(text) {
        return this.literal ? text :
            text.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "\t" : "\\");
    }
    /**
    Compare this query to another query.
    */
    eq(other) {
        return this.search == other.search && this.replace == other.replace &&
            this.caseSensitive == other.caseSensitive && this.regexp == other.regexp &&
            this.wholeWord == other.wholeWord;
    }
    /**
    @internal
    */
    create() {
        return this.regexp ? new RegExpQuery(this) : new StringQuery(this);
    }
    /**
    Get a search cursor for this query, searching through the given
    range in the given state.
    */
    getCursor(state, from = 0, to) {
        let st = state.doc ? state : dist_EditorState.create({ doc: state });
        if (to == null)
            to = st.doc.length;
        return this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to);
    }
}
class dist_QueryType {
    constructor(spec) {
        this.spec = spec;
    }
}
function stringCursor(spec, state, from, to) {
    return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined);
}
function stringWordTest(doc, categorizer) {
    return (from, to, buf, bufPos) => {
        if (bufPos > from || bufPos + buf.length < to) {
            bufPos = Math.max(0, from - 2);
            buf = doc.sliceString(bufPos, Math.min(doc.length, to + 2));
        }
        return (categorizer(charBefore(buf, from - bufPos)) != dist_CharCategory.Word ||
            categorizer(charAfter(buf, from - bufPos)) != dist_CharCategory.Word) &&
            (categorizer(charAfter(buf, to - bufPos)) != dist_CharCategory.Word ||
                categorizer(charBefore(buf, to - bufPos)) != dist_CharCategory.Word);
    };
}
class StringQuery extends dist_QueryType {
    constructor(spec) {
        super(spec);
    }
    nextMatch(state, curFrom, curTo) {
        let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping();
        if (cursor.done) {
            let end = Math.min(state.doc.length, curFrom + this.spec.unquoted.length);
            cursor = stringCursor(this.spec, state, 0, end).nextOverlapping();
        }
        return cursor.done || cursor.value.from == curFrom && cursor.value.to == curTo ? null : cursor.value;
    }
    // Searching in reverse is, rather than implementing an inverted search
    // cursor, done by scanning chunk after chunk forward.
    prevMatchInRange(state, from, to) {
        for (let pos = to;;) {
            let start = Math.max(from, pos - 10000 /* FindPrev.ChunkSize */ - this.spec.unquoted.length);
            let cursor = stringCursor(this.spec, state, start, pos), range = null;
            while (!cursor.nextOverlapping().done)
                range = cursor.value;
            if (range)
                return range;
            if (start == from)
                return null;
            pos -= 10000 /* FindPrev.ChunkSize */;
        }
    }
    prevMatch(state, curFrom, curTo) {
        let found = this.prevMatchInRange(state, 0, curFrom);
        if (!found)
            found = this.prevMatchInRange(state, Math.max(0, curTo - this.spec.unquoted.length), state.doc.length);
        return found && (found.from != curFrom || found.to != curTo) ? found : null;
    }
    getReplacement(_result) { return this.spec.unquote(this.spec.replace); }
    matchAll(state, limit) {
        let cursor = stringCursor(this.spec, state, 0, state.doc.length), ranges = [];
        while (!cursor.next().done) {
            if (ranges.length >= limit)
                return null;
            ranges.push(cursor.value);
        }
        return ranges;
    }
    highlight(state, from, to, add) {
        let cursor = stringCursor(this.spec, state, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length));
        while (!cursor.next().done)
            add(cursor.value.from, cursor.value.to);
    }
}
function regexpCursor(spec, state, from, to) {
    return new RegExpCursor(state.doc, spec.search, {
        ignoreCase: !spec.caseSensitive,
        test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined
    }, from, to);
}
function charBefore(str, index) {
    return str.slice(dist_findClusterBreak(str, index, false), index);
}
function charAfter(str, index) {
    return str.slice(index, dist_findClusterBreak(str, index));
}
function regexpWordTest(categorizer) {
    return (_from, _to, match) => !match[0].length ||
        (categorizer(charBefore(match.input, match.index)) != dist_CharCategory.Word ||
            categorizer(charAfter(match.input, match.index)) != dist_CharCategory.Word) &&
            (categorizer(charAfter(match.input, match.index + match[0].length)) != dist_CharCategory.Word ||
                categorizer(charBefore(match.input, match.index + match[0].length)) != dist_CharCategory.Word);
}
class RegExpQuery extends dist_QueryType {
    nextMatch(state, curFrom, curTo) {
        let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next();
        if (cursor.done)
            cursor = regexpCursor(this.spec, state, 0, curFrom).next();
        return cursor.done ? null : cursor.value;
    }
    prevMatchInRange(state, from, to) {
        for (let size = 1;; size++) {
            let start = Math.max(from, to - size * 10000 /* FindPrev.ChunkSize */);
            let cursor = regexpCursor(this.spec, state, start, to), range = null;
            while (!cursor.next().done)
                range = cursor.value;
            if (range && (start == from || range.from > start + 10))
                return range;
            if (start == from)
                return null;
        }
    }
    prevMatch(state, curFrom, curTo) {
        return this.prevMatchInRange(state, 0, curFrom) ||
            this.prevMatchInRange(state, curTo, state.doc.length);
    }
    getReplacement(result) {
        return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m, i) => {
            if (i == "&")
                return result.match[0];
            if (i == "$")
                return "$";
            for (let l = i.length; l > 0; l--) {
                let n = +i.slice(0, l);
                if (n > 0 && n < result.match.length)
                    return result.match[n] + i.slice(l);
            }
            return m;
        });
    }
    matchAll(state, limit) {
        let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = [];
        while (!cursor.next().done) {
            if (ranges.length >= limit)
                return null;
            ranges.push(cursor.value);
        }
        return ranges;
    }
    highlight(state, from, to, add) {
        let cursor = regexpCursor(this.spec, state, Math.max(0, from - 250 /* RegExp.HighlightMargin */), Math.min(to + 250 /* RegExp.HighlightMargin */, state.doc.length));
        while (!cursor.next().done)
            add(cursor.value.from, cursor.value.to);
    }
}
/**
A state effect that updates the current search query. Note that
this only has an effect if the search state has been initialized
(by including [`search`](https://codemirror.net/6/docs/ref/#search.search) in your configuration or
by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) at least
once).
*/
const setSearchQuery = /*@__PURE__*/dist_StateEffect.define();
const togglePanel = /*@__PURE__*/dist_StateEffect.define();
const searchState = /*@__PURE__*/dist_StateField.define({
    create(state) {
        return new SearchState(defaultQuery(state).create(), null);
    },
    update(value, tr) {
        for (let effect of tr.effects) {
            if (effect.is(setSearchQuery))
                value = new SearchState(effect.value.create(), value.panel);
            else if (effect.is(togglePanel))
                value = new SearchState(value.query, effect.value ? createSearchPanel : null);
        }
        return value;
    },
    provide: f => showPanel.from(f, val => val.panel)
});
/**
Get the current search query from an editor state.
*/
function getSearchQuery(state) {
    let curState = state.field(searchState, false);
    return curState ? curState.query.spec : defaultQuery(state);
}
/**
Query whether the search panel is open in the given editor state.
*/
function searchPanelOpen(state) {
    var _a;
    return ((_a = state.field(searchState, false)) === null || _a === void 0 ? void 0 : _a.panel) != null;
}
class SearchState {
    constructor(query, panel) {
        this.query = query;
        this.panel = panel;
    }
}
const matchMark = /*@__PURE__*/dist_Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = /*@__PURE__*/dist_Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" });
const searchHighlighter = /*@__PURE__*/dist_ViewPlugin.fromClass(class {
    constructor(view) {
        this.view = view;
        this.decorations = this.highlight(view.state.field(searchState));
    }
    update(update) {
        let state = update.state.field(searchState);
        if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged)
            this.decorations = this.highlight(state);
    }
    highlight({ query, panel }) {
        if (!panel || !query.spec.valid)
            return dist_Decoration.none;
        let { view } = this;
        let builder = new RangeSetBuilder();
        for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) {
            let { from, to } = ranges[i];
            while (i < l - 1 && to > ranges[i + 1].from - 2 * 250 /* RegExp.HighlightMargin */)
                to = ranges[++i].to;
            query.highlight(view.state, from, to, (from, to) => {
                let selected = view.state.selection.ranges.some(r => r.from == from && r.to == to);
                builder.add(from, to, selected ? selectedMatchMark : matchMark);
            });
        }
        return builder.finish();
    }
}, {
    decorations: v => v.decorations
});
function searchCommand(f) {
    return view => {
        let state = view.state.field(searchState, false);
        return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view);
    };
}
/**
Open the search panel if it isn't already open, and move the
selection to the first match after the current main selection.
Will wrap around to the start of the document when it reaches the
end.
*/
const findNext = /*@__PURE__*/searchCommand((view, { query }) => {
    let { to } = view.state.selection.main;
    let next = query.nextMatch(view.state, to, to);
    if (!next)
        return false;
    let selection = dist_EditorSelection.single(next.from, next.to);
    let config = view.state.facet(searchConfigFacet);
    view.dispatch({
        selection,
        effects: [announceMatch(view, next), config.scrollToMatch(selection.main, view)],
        userEvent: "select.search"
    });
    selectSearchInput(view);
    return true;
});
/**
Move the selection to the previous instance of the search query,
before the current main selection. Will wrap past the start
of the document to start searching at the end again.
*/
const findPrevious = /*@__PURE__*/searchCommand((view, { query }) => {
    let { state } = view, { from } = state.selection.main;
    let prev = query.prevMatch(state, from, from);
    if (!prev)
        return false;
    let selection = dist_EditorSelection.single(prev.from, prev.to);
    let config = view.state.facet(searchConfigFacet);
    view.dispatch({
        selection,
        effects: [announceMatch(view, prev), config.scrollToMatch(selection.main, view)],
        userEvent: "select.search"
    });
    selectSearchInput(view);
    return true;
});
/**
Select all instances of the search query.
*/
const selectMatches = /*@__PURE__*/searchCommand((view, { query }) => {
    let ranges = query.matchAll(view.state, 1000);
    if (!ranges || !ranges.length)
        return false;
    view.dispatch({
        selection: dist_EditorSelection.create(ranges.map(r => dist_EditorSelection.range(r.from, r.to))),
        userEvent: "select.search.matches"
    });
    return true;
});
/**
Select all instances of the currently selected text.
*/
const selectSelectionMatches = ({ state, dispatch }) => {
    let sel = state.selection;
    if (sel.ranges.length > 1 || sel.main.empty)
        return false;
    let { from, to } = sel.main;
    let ranges = [], main = 0;
    for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) {
        if (ranges.length > 1000)
            return false;
        if (cur.value.from == from)
            main = ranges.length;
        ranges.push(dist_EditorSelection.range(cur.value.from, cur.value.to));
    }
    dispatch(state.update({
        selection: dist_EditorSelection.create(ranges, main),
        userEvent: "select.search.matches"
    }));
    return true;
};
/**
Replace the current match of the search query.
*/
const replaceNext = /*@__PURE__*/searchCommand((view, { query }) => {
    let { state } = view, { from, to } = state.selection.main;
    if (state.readOnly)
        return false;
    let match = query.nextMatch(state, from, from);
    if (!match)
        return false;
    let next = match;
    let changes = [], selection, replacement;
    let effects = [];
    if (next.from == from && next.to == to) {
        replacement = state.toText(query.getReplacement(next));
        changes.push({ from: next.from, to: next.to, insert: replacement });
        next = query.nextMatch(state, next.from, next.to);
        effects.push(dist_EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from).number) + "."));
    }
    let changeSet = view.state.changes(changes);
    if (next) {
        selection = dist_EditorSelection.single(next.from, next.to).map(changeSet);
        effects.push(announceMatch(view, next));
        effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main, view));
    }
    view.dispatch({
        changes: changeSet,
        selection,
        effects,
        userEvent: "input.replace"
    });
    return true;
});
/**
Replace all instances of the search query with the given
replacement.
*/
const replaceAll = /*@__PURE__*/searchCommand((view, { query }) => {
    if (view.state.readOnly)
        return false;
    let changes = query.matchAll(view.state, 1e9).map(match => {
        let { from, to } = match;
        return { from, to, insert: query.getReplacement(match) };
    });
    if (!changes.length)
        return false;
    let announceText = view.state.phrase("replaced $ matches", changes.length) + ".";
    view.dispatch({
        changes,
        effects: dist_EditorView.announce.of(announceText),
        userEvent: "input.replace.all"
    });
    return true;
});
function createSearchPanel(view) {
    return view.state.facet(searchConfigFacet).createPanel(view);
}
function defaultQuery(state, fallback) {
    var _a, _b, _c, _d, _e;
    let sel = state.selection.main;
    let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to);
    if (fallback && !selText)
        return fallback;
    let config = state.facet(searchConfigFacet);
    return new SearchQuery({
        search: ((_a = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _a !== void 0 ? _a : config.literal) ? selText : selText.replace(/\n/g, "\\n"),
        caseSensitive: (_b = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _b !== void 0 ? _b : config.caseSensitive,
        literal: (_c = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _c !== void 0 ? _c : config.literal,
        regexp: (_d = fallback === null || fallback === void 0 ? void 0 : fallback.regexp) !== null && _d !== void 0 ? _d : config.regexp,
        wholeWord: (_e = fallback === null || fallback === void 0 ? void 0 : fallback.wholeWord) !== null && _e !== void 0 ? _e : config.wholeWord
    });
}
function getSearchInput(view) {
    let panel = getPanel(view, createSearchPanel);
    return panel && panel.dom.querySelector("[main-field]");
}
function selectSearchInput(view) {
    let input = getSearchInput(view);
    if (input && input == view.root.activeElement)
        input.select();
}
/**
Make sure the search panel is open and focused.
*/
const openSearchPanel = view => {
    let state = view.state.field(searchState, false);
    if (state && state.panel) {
        let searchInput = getSearchInput(view);
        if (searchInput && searchInput != view.root.activeElement) {
            let query = defaultQuery(view.state, state.query.spec);
            if (query.valid)
                view.dispatch({ effects: setSearchQuery.of(query) });
            searchInput.focus();
            searchInput.select();
        }
    }
    else {
        view.dispatch({ effects: [
                togglePanel.of(true),
                state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : dist_StateEffect.appendConfig.of(searchExtensions)
            ] });
    }
    return true;
};
/**
Close the search panel.
*/
const closeSearchPanel = view => {
    let state = view.state.field(searchState, false);
    if (!state || !state.panel)
        return false;
    let panel = getPanel(view, createSearchPanel);
    if (panel && panel.dom.contains(view.root.activeElement))
        view.focus();
    view.dispatch({ effects: togglePanel.of(false) });
    return true;
};
/**
Default search-related key bindings.

 - Mod-f: [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel)
 - F3, Mod-g: [`findNext`](https://codemirror.net/6/docs/ref/#search.findNext)
 - Shift-F3, Shift-Mod-g: [`findPrevious`](https://codemirror.net/6/docs/ref/#search.findPrevious)
 - Mod-Alt-g: [`gotoLine`](https://codemirror.net/6/docs/ref/#search.gotoLine)
 - Mod-d: [`selectNextOccurrence`](https://codemirror.net/6/docs/ref/#search.selectNextOccurrence)
*/
const searchKeymap = [
    { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" },
    { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
    { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
    { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" },
    { key: "Mod-Shift-l", run: selectSelectionMatches },
    { key: "Mod-Alt-g", run: gotoLine },
    { key: "Mod-d", run: selectNextOccurrence, preventDefault: true },
];
class SearchPanel {
    constructor(view) {
        this.view = view;
        let query = this.query = view.state.field(searchState).query.spec;
        this.commit = this.commit.bind(this);
        this.searchField = external_crelt_namespaceObject("input", {
            value: query.search,
            placeholder: phrase(view, "Find"),
            "aria-label": phrase(view, "Find"),
            class: "cm-textfield",
            name: "search",
            form: "",
            "main-field": "true",
            onchange: this.commit,
            onkeyup: this.commit
        });
        this.replaceField = external_crelt_namespaceObject("input", {
            value: query.replace,
            placeholder: phrase(view, "Replace"),
            "aria-label": phrase(view, "Replace"),
            class: "cm-textfield",
            name: "replace",
            form: "",
            onchange: this.commit,
            onkeyup: this.commit
        });
        this.caseField = external_crelt_namespaceObject("input", {
            type: "checkbox",
            name: "case",
            form: "",
            checked: query.caseSensitive,
            onchange: this.commit
        });
        this.reField = external_crelt_namespaceObject("input", {
            type: "checkbox",
            name: "re",
            form: "",
            checked: query.regexp,
            onchange: this.commit
        });
        this.wordField = external_crelt_namespaceObject("input", {
            type: "checkbox",
            name: "word",
            form: "",
            checked: query.wholeWord,
            onchange: this.commit
        });
        function button(name, onclick, content) {
            return external_crelt_namespaceObject("button", { class: "cm-button", name, onclick, type: "button" }, content);
        }
        this.dom = external_crelt_namespaceObject("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [
            this.searchField,
            button("next", () => findNext(view), [phrase(view, "next")]),
            button("prev", () => findPrevious(view), [phrase(view, "previous")]),
            button("select", () => selectMatches(view), [phrase(view, "all")]),
            external_crelt_namespaceObject("label", null, [this.caseField, phrase(view, "match case")]),
            external_crelt_namespaceObject("label", null, [this.reField, phrase(view, "regexp")]),
            external_crelt_namespaceObject("label", null, [this.wordField, phrase(view, "by word")]),
            ...view.state.readOnly ? [] : [
                external_crelt_namespaceObject("br"),
                this.replaceField,
                button("replace", () => replaceNext(view), [phrase(view, "replace")]),
                button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")])
            ],
            external_crelt_namespaceObject("button", {
                name: "close",
                onclick: () => closeSearchPanel(view),
                "aria-label": phrase(view, "close"),
                type: "button"
            }, ["×"])
        ]);
    }
    commit() {
        let query = new SearchQuery({
            search: this.searchField.value,
            caseSensitive: this.caseField.checked,
            regexp: this.reField.checked,
            wholeWord: this.wordField.checked,
            replace: this.replaceField.value,
        });
        if (!query.eq(this.query)) {
            this.query = query;
            this.view.dispatch({ effects: setSearchQuery.of(query) });
        }
    }
    keydown(e) {
        if (runScopeHandlers(this.view, e, "search-panel")) {
            e.preventDefault();
        }
        else if (e.keyCode == 13 && e.target == this.searchField) {
            e.preventDefault();
            (e.shiftKey ? findPrevious : findNext)(this.view);
        }
        else if (e.keyCode == 13 && e.target == this.replaceField) {
            e.preventDefault();
            replaceNext(this.view);
        }
    }
    update(update) {
        for (let tr of update.transactions)
            for (let effect of tr.effects) {
                if (effect.is(setSearchQuery) && !effect.value.eq(this.query))
                    this.setQuery(effect.value);
            }
    }
    setQuery(query) {
        this.query = query;
        this.searchField.value = query.search;
        this.replaceField.value = query.replace;
        this.caseField.checked = query.caseSensitive;
        this.reField.checked = query.regexp;
        this.wordField.checked = query.wholeWord;
    }
    mount() {
        this.searchField.select();
    }
    get pos() { return 80; }
    get top() { return this.view.state.facet(searchConfigFacet).top; }
}
function phrase(view, phrase) { return view.state.phrase(phrase); }
const AnnounceMargin = 30;
const Break = /[\s\.,:;?!]/;
function announceMatch(view, { from, to }) {
    let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to;
    let start = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin);
    let text = view.state.sliceDoc(start, end);
    if (start != line.from) {
        for (let i = 0; i < AnnounceMargin; i++)
            if (!Break.test(text[i + 1]) && Break.test(text[i])) {
                text = text.slice(i);
                break;
            }
    }
    if (end != lineEnd) {
        for (let i = text.length - 1; i > text.length - AnnounceMargin; i--)
            if (!Break.test(text[i - 1]) && Break.test(text[i])) {
                text = text.slice(0, i);
                break;
            }
    }
    return dist_EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`);
}
const search_dist_baseTheme = /*@__PURE__*/dist_EditorView.baseTheme({
    ".cm-panel.cm-search": {
        padding: "2px 6px 4px",
        position: "relative",
        "& [name=close]": {
            position: "absolute",
            top: "0",
            right: "4px",
            backgroundColor: "inherit",
            border: "none",
            font: "inherit",
            padding: 0,
            margin: 0
        },
        "& input, & button, & label": {
            margin: ".2em .6em .2em 0"
        },
        "& input[type=checkbox]": {
            marginRight: ".2em"
        },
        "& label": {
            fontSize: "80%",
            whiteSpace: "pre"
        }
    },
    "&light .cm-searchMatch": { backgroundColor: "#ffff0054" },
    "&dark .cm-searchMatch": { backgroundColor: "#00ffff8a" },
    "&light .cm-searchMatch-selected": { backgroundColor: "#ff6a0054" },
    "&dark .cm-searchMatch-selected": { backgroundColor: "#ff00ff8a" }
});
const searchExtensions = [
    searchState,
    /*@__PURE__*/Prec.low(searchHighlighter),
    search_dist_baseTheme
];



;// ../noodl-core-ui/src/components/code-editor/codemirror-theme.ts
/**
 * CodeMirror Theme for OpenNoodl
 *
 * Custom theme matching OpenNoodl design tokens and VSCode Dark+ colors.
 * Provides syntax highlighting, UI colors, and visual feedback.
 *
 * @module code-editor
 */



/**
 * Create the OpenNoodl editor theme
 */
function createOpenNoodlTheme() {
    // Editor theme (UI elements)
    const editorTheme = dist_EditorView.theme({
        // Main editor
        '&': {
            backgroundColor: 'var(--theme-color-bg-2)',
            color: 'var(--theme-color-fg-default)',
            fontSize: '13px',
            fontFamily: "var(--theme-font-mono, 'Monaco', 'Menlo', 'Courier New', monospace)",
            lineHeight: '1.6'
        },
        // Content area
        '.cm-content': {
            caretColor: 'var(--theme-color-fg-default)',
            padding: '16px 0'
        },
        // Cursor
        '.cm-cursor, .cm-dropCursor': {
            borderLeftColor: 'var(--theme-color-fg-default)',
            borderLeftWidth: '2px'
        },
        // Selection
        '&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection': {
            backgroundColor: 'rgba(86, 156, 214, 0.3)'
        },
        // Active line
        '.cm-activeLine': {
            backgroundColor: 'rgba(255, 255, 255, 0.05)'
        },
        // Line numbers gutter
        '.cm-gutters': {
            backgroundColor: 'var(--theme-color-bg-3)',
            color: 'var(--theme-color-fg-muted)',
            border: 'none',
            borderRight: '1px solid var(--theme-color-border-default)',
            minWidth: '35px'
        },
        '.cm-gutter': {
            minWidth: '35px'
        },
        '.cm-lineNumbers': {
            minWidth: '35px'
        },
        '.cm-lineNumbers .cm-gutterElement': {
            padding: '0 8px 0 6px',
            textAlign: 'right',
            minWidth: '35px'
        },
        // Active line number
        '.cm-activeLineGutter': {
            backgroundColor: 'rgba(255, 255, 255, 0.05)',
            color: 'var(--theme-color-fg-default)'
        },
        // Fold gutter
        '.cm-foldGutter': {
            width: '20px',
            padding: '0 4px'
        },
        '.cm-foldGutter .cm-gutterElement': {
            textAlign: 'center',
            cursor: 'pointer'
        },
        '.cm-foldPlaceholder': {
            backgroundColor: 'rgba(255, 255, 255, 0.1)',
            border: '1px solid rgba(255, 255, 255, 0.2)',
            color: 'var(--theme-color-fg-muted)',
            borderRadius: '3px',
            padding: '0 6px',
            margin: '0 4px'
        },
        // Search panel
        '.cm-panel': {
            backgroundColor: 'var(--theme-color-bg-3)',
            border: '1px solid var(--theme-color-border-default)',
            borderRadius: '4px',
            padding: '8px'
        },
        '.cm-panel.cm-search': {
            padding: '8px 12px'
        },
        '.cm-searchMatch': {
            backgroundColor: 'rgba(255, 215, 0, 0.3)',
            outline: '1px solid rgba(255, 215, 0, 0.5)'
        },
        '.cm-searchMatch-selected': {
            backgroundColor: 'rgba(255, 165, 0, 0.4)',
            outline: '1px solid rgba(255, 165, 0, 0.7)'
        },
        // Highlight selection matches
        '.cm-selectionMatch': {
            backgroundColor: 'rgba(255, 255, 255, 0.1)',
            outline: '1px solid rgba(255, 255, 255, 0.2)'
        },
        // Matching brackets
        '.cm-matchingBracket': {
            backgroundColor: 'rgba(255, 255, 255, 0.15)',
            outline: '1px solid rgba(255, 255, 255, 0.3)',
            borderRadius: '2px'
        },
        '.cm-nonmatchingBracket': {
            backgroundColor: 'rgba(255, 0, 0, 0.2)',
            outline: '1px solid rgba(255, 0, 0, 0.4)'
        },
        // Autocomplete panel
        '.cm-tooltip-autocomplete': {
            backgroundColor: 'var(--theme-color-bg-3)',
            border: '1px solid var(--theme-color-border-default)',
            borderRadius: '6px',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.3)',
            overflow: 'hidden',
            fontFamily: "var(--theme-font-mono, 'Monaco', 'Menlo', 'Courier New', monospace)",
            fontSize: '13px'
        },
        '.cm-tooltip-autocomplete ul': {
            maxHeight: '300px',
            overflowY: 'auto'
        },
        '.cm-tooltip-autocomplete ul li': {
            padding: '6px 12px',
            color: 'var(--theme-color-fg-default)',
            cursor: 'pointer'
        },
        '.cm-tooltip-autocomplete ul li[aria-selected]': {
            backgroundColor: 'var(--theme-color-primary)',
            color: 'white'
        },
        '.cm-completionIcon': {
            width: '1em',
            marginRight: '8px',
            fontSize: '14px',
            lineHeight: '1'
        },
        // Lint markers (errors/warnings)
        '.cm-lintRange-error': {
            backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='6' height='3'%3E%3Cpath d='m0 3 l3 -3 l3 3' stroke='%23ef4444' fill='none' stroke-width='.7'/%3E%3C/svg%3E\")",
            backgroundRepeat: 'repeat-x',
            backgroundPosition: 'left bottom',
            paddingBottom: '3px'
        },
        '.cm-lintRange-warning': {
            backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='6' height='3'%3E%3Cpath d='m0 3 l3 -3 l3 3' stroke='%23f59e0b' fill='none' stroke-width='.7'/%3E%3C/svg%3E\")",
            backgroundRepeat: 'repeat-x',
            backgroundPosition: 'left bottom',
            paddingBottom: '3px'
        },
        '.cm-lint-marker-error': {
            content: '●',
            color: '#ef4444'
        },
        '.cm-lint-marker-warning': {
            content: '●',
            color: '#f59e0b'
        },
        // Hover tooltips
        '.cm-tooltip': {
            backgroundColor: 'var(--theme-color-bg-4)',
            border: '1px solid var(--theme-color-border-default)',
            borderRadius: '4px',
            padding: '6px 10px',
            color: 'var(--theme-color-fg-default)',
            fontSize: '12px',
            maxWidth: '400px',
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.2)'
        },
        '.cm-tooltip-lint': {
            fontFamily: "var(--theme-font-mono, 'Monaco', 'Menlo', 'Courier New', monospace)"
        },
        // Placeholder
        '.cm-placeholder': {
            color: 'var(--theme-color-fg-muted)',
            opacity: 0.6
        },
        // Indent guides (will be added via custom extension)
        '.cm-indent-guide': {
            position: 'absolute',
            top: '0',
            bottom: '0',
            width: '1px',
            backgroundColor: 'rgba(255, 255, 255, 0.1)'
        },
        // Scroller
        '.cm-scroller': {
            overflow: 'auto',
            fontFamily: "var(--theme-font-mono, 'Monaco', 'Menlo', 'Courier New', monospace)"
        },
        // Focused state
        '&.cm-focused': {
            outline: 'none'
        }
    }, { dark: true });
    // Syntax highlighting theme (token colors)
    const syntaxTheme = HighlightStyle.define([
        // Keywords (if, for, function, return, etc.)
        { tag: tags.keyword, color: '#569cd6', fontWeight: 'bold' },
        // Control keywords (if, else, switch, case)
        { tag: tags.controlKeyword, color: '#c586c0', fontWeight: 'bold' },
        // Definition keywords (function, class, const, let, var)
        { tag: tags.definitionKeyword, color: '#569cd6', fontWeight: 'bold' },
        // Module keywords (import, export)
        { tag: tags.moduleKeyword, color: '#c586c0', fontWeight: 'bold' },
        // Operator keywords (typeof, instanceof, new, delete)
        { tag: tags.operatorKeyword, color: '#569cd6', fontWeight: 'bold' },
        // Comments
        { tag: tags.comment, color: '#6a9955', fontStyle: 'italic' },
        { tag: tags.lineComment, color: '#6a9955', fontStyle: 'italic' },
        { tag: tags.blockComment, color: '#6a9955', fontStyle: 'italic' },
        // Strings
        { tag: tags.string, color: '#ce9178' },
        { tag: tags.special(tags.string), color: '#d16969' },
        // Numbers
        { tag: tags.number, color: '#b5cea8' },
        { tag: tags.integer, color: '#b5cea8' },
        { tag: tags.float, color: '#b5cea8' },
        // Booleans
        { tag: tags.bool, color: '#569cd6', fontWeight: 'bold' },
        // Null/Undefined
        { tag: tags.null, color: '#569cd6', fontWeight: 'bold' },
        // Variables
        { tag: tags.variableName, color: '#9cdcfe' },
        { tag: tags.local(tags.variableName), color: '#9cdcfe' },
        { tag: tags.definition(tags.variableName), color: '#9cdcfe' },
        // Functions
        { tag: tags.function(tags.variableName), color: '#dcdcaa' },
        { tag: tags.function(tags.propertyName), color: '#dcdcaa' },
        // Properties
        { tag: tags.propertyName, color: '#9cdcfe' },
        { tag: tags.special(tags.propertyName), color: '#4fc1ff' },
        // Operators
        { tag: tags.operator, color: '#d4d4d4' },
        { tag: tags.arithmeticOperator, color: '#d4d4d4' },
        { tag: tags.logicOperator, color: '#d4d4d4' },
        { tag: tags.compareOperator, color: '#d4d4d4' },
        // Punctuation
        { tag: tags.punctuation, color: '#d4d4d4' },
        { tag: tags.separator, color: '#d4d4d4' },
        { tag: tags.paren, color: '#ffd700' }, // Gold for ()
        { tag: tags.bracket, color: '#87ceeb' }, // Sky blue for []
        { tag: tags.brace, color: '#98fb98' }, // Pale green for {}
        { tag: tags.squareBracket, color: '#87ceeb' },
        { tag: tags.angleBracket, color: '#dda0dd' },
        // Types (for TypeScript/JSDoc)
        { tag: tags.typeName, color: '#4ec9b0' },
        { tag: tags.className, color: '#4ec9b0' },
        { tag: tags.namespace, color: '#4ec9b0' },
        // Special identifiers (self keyword)
        { tag: tags.self, color: '#569cd6', fontWeight: 'bold' },
        // Regular expressions
        { tag: tags.regexp, color: '#d16969' },
        // Invalid/Error
        { tag: tags.invalid, color: '#f44747', textDecoration: 'underline' },
        // Meta
        { tag: tags.meta, color: '#808080' },
        // Escape sequences
        { tag: tags.escape, color: '#d7ba7d' },
        // Labels
        { tag: tags.labelName, color: '#c8c8c8' }
    ]);
    return [editorTheme, syntaxHighlighting(syntaxTheme)];
}

;// ../noodl-core-ui/src/components/code-editor/noodl-completions.ts
/**
 * Noodl-Specific Autocomplete
 *
 * Provides intelligent code completion for Noodl's global API:
 * - Noodl.Variables, Noodl.Objects, Noodl.Arrays
 * - Inputs, Outputs, State, Props (node context)
 * - Math helpers (min, max, cos, sin, etc.)
 *
 * @module code-editor
 */
/**
 * Noodl API structure completions
 */
const noodlCompletions = [
    // Noodl global API
    { label: 'Noodl.Variables', type: 'property', info: 'Access global variables' },
    { label: 'Noodl.Objects', type: 'property', info: 'Access objects from model scope' },
    { label: 'Noodl.Arrays', type: 'property', info: 'Access arrays from model scope' },
    // Shorthand versions
    { label: 'Variables', type: 'property', info: 'Shorthand for Noodl.Variables' },
    { label: 'Objects', type: 'property', info: 'Shorthand for Noodl.Objects' },
    { label: 'Arrays', type: 'property', info: 'Shorthand for Noodl.Arrays' },
    // Node context (for Expression/Function nodes)
    { label: 'Inputs', type: 'property', info: 'Access node input values' },
    { label: 'Outputs', type: 'property', info: 'Set node output values' },
    { label: 'State', type: 'property', info: 'Access component state' },
    { label: 'Props', type: 'property', info: 'Access component props' },
    // Math helpers
    { label: 'min', type: 'function', info: 'Math.min - Return smallest value' },
    { label: 'max', type: 'function', info: 'Math.max - Return largest value' },
    { label: 'cos', type: 'function', info: 'Math.cos - Cosine function' },
    { label: 'sin', type: 'function', info: 'Math.sin - Sine function' },
    { label: 'tan', type: 'function', info: 'Math.tan - Tangent function' },
    { label: 'sqrt', type: 'function', info: 'Math.sqrt - Square root' },
    { label: 'pi', type: 'constant', info: 'Math.PI - The pi constant (3.14159...)' },
    { label: 'round', type: 'function', info: 'Math.round - Round to nearest integer' },
    { label: 'floor', type: 'function', info: 'Math.floor - Round down' },
    { label: 'ceil', type: 'function', info: 'Math.ceil - Round up' },
    { label: 'abs', type: 'function', info: 'Math.abs - Absolute value' },
    { label: 'random', type: 'function', info: 'Math.random - Random number 0-1' },
    { label: 'pow', type: 'function', info: 'Math.pow - Power function' },
    { label: 'log', type: 'function', info: 'Math.log - Natural logarithm' },
    { label: 'exp', type: 'function', info: 'Math.exp - e to the power of x' }
];
/**
 * Get the word before the cursor
 */
function wordBefore(context) {
    const word = context.matchBefore(/\w*/);
    if (!word)
        return null;
    if (word.from === word.to && !context.explicit)
        return null;
    return word;
}
/**
 * Get completions for after "Noodl."
 */
function getNoodlPropertyCompletions() {
    return {
        from: 0, // Will be set by caller
        options: [
            { label: 'Variables', type: 'property', info: 'Access global variables' },
            { label: 'Objects', type: 'property', info: 'Access objects from model scope' },
            { label: 'Arrays', type: 'property', info: 'Access arrays from model scope' }
        ]
    };
}
/**
 * Main Noodl completion source
 */
function noodlCompletionSource(context) {
    const word = wordBefore(context);
    if (!word)
        return null;
    // Check if we're after "Noodl."
    const textBefore = context.state.doc.sliceString(Math.max(0, word.from - 6), word.from);
    if (textBefore.endsWith('Noodl.')) {
        const result = getNoodlPropertyCompletions();
        result.from = word.from;
        return result;
    }
    // Check if we're typing "Noodl" itself
    if (word.text.toLowerCase().startsWith('nood')) {
        return {
            from: word.from,
            options: [{ label: 'Noodl', type: 'namespace', info: 'Noodl global namespace' }]
        };
    }
    // General completions (always available)
    const filtered = noodlCompletions.filter((c) => c.label.toLowerCase().startsWith(word.text.toLowerCase()));
    if (filtered.length === 0)
        return null;
    return {
        from: word.from,
        options: filtered
    };
}

;// ../noodl-core-ui/src/components/code-editor/codemirror-extensions.ts
/**
 * CodeMirror Extensions Configuration
 *
 * Configures all CodeMirror extensions and features including:
 * - Language support (JavaScript)
 * - Autocompletion
 * - Search/replace
 * - Code folding
 * - Linting
 * - Custom keybindings
 * - Bracket colorization
 * - Indent guides
 * - And more...
 *
 * @module code-editor
 */











/**
 * Indent guides extension
 * Draws vertical lines to show indentation levels
 */
function indentGuides() {
    const indentGuideDeco = Decoration.line({
        attributes: { class: 'cm-indent-guide' }
    });
    return ViewPlugin.fromClass(class {
        constructor(view) {
            this.decorations = this.buildDecorations(view);
        }
        update(update) {
            if (update.docChanged || update.viewportChanged) {
                this.decorations = this.buildDecorations(update.view);
            }
        }
        buildDecorations(view) {
            const decorations = [];
            const tabSize = view.state.tabSize;
            for (const { from, to } of view.visibleRanges) {
                for (let pos = from; pos <= to;) {
                    const line = view.state.doc.lineAt(pos);
                    const text = line.text;
                    // Count leading spaces/tabs
                    let indent = 0;
                    for (let i = 0; i < text.length; i++) {
                        if (text[i] === ' ')
                            indent++;
                        else if (text[i] === '\t')
                            indent += tabSize;
                        else
                            break;
                    }
                    // Add decoration if line has indentation
                    if (indent > 0) {
                        decorations.push(indentGuideDeco.range(line.from));
                    }
                    pos = line.to + 1;
                }
            }
            return Decoration.set(decorations);
        }
    }, {
        decorations: (v) => v.decorations
    });
}
/**
 * Custom Enter key handler for better brace/bracket handling
 */
function handleEnterKey(view) {
    var _a;
    const { state } = view;
    const { selection } = state;
    // Only handle if single cursor
    if (selection.ranges.length !== 1) {
        return false;
    }
    const range = selection.main;
    if (!range.empty) {
        return false; // Has selection, use default behavior
    }
    const pos = range.from;
    const line = state.doc.lineAt(pos);
    const before = state.sliceDoc(line.from, pos);
    // Check if cursor is between matching brackets/braces
    const beforeChar = state.sliceDoc(Math.max(0, pos - 1), pos);
    const afterChar = state.sliceDoc(pos, Math.min(state.doc.length, pos + 1));
    const matchingPairs = {
        '{': '}',
        '[': ']',
        '(': ')'
    };
    // If between matching pair (e.g., {|})
    if (matchingPairs[beforeChar] === afterChar) {
        // Calculate indentation
        const indent = ((_a = before.match(/^\s*/)) === null || _a === void 0 ? void 0 : _a[0]) || '';
        const indentSize = state.tabSize;
        const newIndent = indent + ' '.repeat(indentSize);
        // Insert newline with indentation, then another newline with original indentation
        view.dispatch({
            changes: {
                from: pos,
                to: pos,
                insert: '\n' + newIndent + '\n' + indent
            },
            selection: { anchor: pos + 1 + newIndent.length }
        });
        return true; // Handled
    }
    // Default behavior
    return false;
}
/**
 * Move line up command (Alt+↑)
 */
function codemirror_extensions_moveLineUp(view) {
    const { state } = view;
    const changes = state.changeByRange((range) => {
        const line = state.doc.lineAt(range.from);
        if (line.number === 1)
            return { range }; // Can't move first line up
        const prevLine = state.doc.line(line.number - 1);
        const lineText = state.doc.sliceString(line.from, line.to);
        const prevLineText = state.doc.sliceString(prevLine.from, prevLine.to);
        return {
            changes: [
                { from: prevLine.from, to: prevLine.to, insert: lineText },
                { from: line.from, to: line.to, insert: prevLineText }
            ],
            range: dist_EditorSelection.range(prevLine.from, prevLine.from + lineText.length)
        };
    });
    view.dispatch(changes);
    return true;
}
/**
 * Move line down command (Alt+↓)
 */
function codemirror_extensions_moveLineDown(view) {
    const { state } = view;
    const changes = state.changeByRange((range) => {
        const line = state.doc.lineAt(range.from);
        if (line.number === state.doc.lines)
            return { range }; // Can't move last line down
        const nextLine = state.doc.line(line.number + 1);
        const lineText = state.doc.sliceString(line.from, line.to);
        const nextLineText = state.doc.sliceString(nextLine.from, nextLine.to);
        return {
            changes: [
                { from: line.from, to: line.to, insert: nextLineText },
                { from: nextLine.from, to: nextLine.to, insert: lineText }
            ],
            range: dist_EditorSelection.range(nextLine.from, nextLine.from + lineText.length)
        };
    });
    view.dispatch(changes);
    return true;
}
/**
 * Create custom keybindings
 */
function customKeybindings(options) {
    return keymap.of([
        // Custom Enter key handler (before default keymap)
        {
            key: 'Enter',
            run: handleEnterKey
        },
        // Standard keymaps
        // REMOVED: closeBracketsKeymap (was intercepting closing brackets)
        ...defaultKeymap,
        ...searchKeymap,
        ...historyKeymap,
        ...foldKeymap,
        ...completionKeymap,
        // Tab key for indentation (not focus change)
        indentWithTab,
        // Comment toggle (Cmd+/)
        {
            key: 'Mod-/',
            run: toggleComment
        },
        // Move lines up/down (Alt+↑/↓)
        {
            key: 'Alt-ArrowUp',
            run: codemirror_extensions_moveLineUp
        },
        {
            key: 'Alt-ArrowDown',
            run: codemirror_extensions_moveLineDown
        },
        // Save (Cmd+S)
        ...(options.onSave
            ? [
                {
                    key: 'Mod-s',
                    preventDefault: true,
                    run: (view) => {
                        var _a;
                        (_a = options.onSave) === null || _a === void 0 ? void 0 : _a.call(options, view.state.doc.toString());
                        return true;
                    }
                }
            ]
            : []),
        // Undo/Redo (ensure they work)
        {
            key: 'Mod-z',
            run: undo
        },
        {
            key: 'Mod-Shift-z',
            run: redo
        },
        {
            key: 'Mod-y',
            mac: 'Mod-Shift-z',
            run: redo
        }
    ]);
}
/**
 * Create a linter from our validation function
 */
function createLinter(validationType) {
    return linter((view) => {
        const code = view.state.doc.toString();
        const validation = validateJavaScript(code, validationType);
        if (validation.valid) {
            return [];
        }
        const diagnostics = [];
        // Calculate position from line/column
        let from = 0;
        let to = code.length;
        if (validation.line !== undefined) {
            const lines = code.split('\n');
            const lineIndex = validation.line - 1;
            if (lineIndex >= 0 && lineIndex < lines.length) {
                // Calculate character position of the line
                from = lines.slice(0, lineIndex).reduce((sum, line) => sum + line.length + 1, 0);
                if (validation.column !== undefined) {
                    from += validation.column;
                    to = from + 1; // Highlight just one character
                }
                else {
                    to = from + lines[lineIndex].length;
                }
            }
        }
        diagnostics.push({
            from: Math.max(0, from),
            to: Math.min(code.length, to),
            severity: 'error',
            message: validation.error || 'Syntax error'
        });
        return diagnostics;
    });
}
/**
 * Create all CodeMirror extensions
 */
function createExtensions(options = {}) {
    const { validationType = 'expression', placeholder = '// Enter your JavaScript code here', readOnly = false, onChange, tabSize = 2 } = options;
    // Adding extensions back one by one to find the culprit
    const extensions = [
        // 1. Language support
        javascript(),
        // 2. Theme
        createOpenNoodlTheme(),
        // 3. Custom keybindings with Enter handler
        customKeybindings(options),
        // 4. Essential UI
        lineNumbers(),
        dist_history(),
        // 5. Visual enhancements (Group 1 - SAFE ✅)
        highlightActiveLineGutter(),
        highlightActiveLine(),
        drawSelection(),
        dropCursor(),
        rectangularSelection(),
        // 6. Bracket & selection features (Group 2 - SAFE ✅)
        bracketMatching(),
        highlightSelectionMatches(),
        dist_placeholder(placeholder),
        dist_EditorView.lineWrapping,
        // 7. Complex features (tested safe)
        foldGutter({
            openText: '▼',
            closedText: '▶'
        }),
        autocompletion({
            activateOnTyping: true,
            maxRenderedOptions: 10,
            defaultKeymap: true,
            override: [noodlCompletionSource]
        }),
        // 8. Tab size
        dist_EditorState.tabSize.of(tabSize),
        // 9. Read-only mode
        dist_EditorView.editable.of(!readOnly),
        dist_EditorState.readOnly.of(readOnly),
        // 10. onChange handler
        ...(onChange
            ? [
                dist_EditorView.updateListener.of((update) => {
                    if (update.docChanged) {
                        onChange(update.state.doc.toString());
                    }
                })
            ]
            : [])
        // ALL EXTENSIONS NOW ENABLED (except closeBrackets/indentOnInput)
        // closeBrackets() - PERMANENTLY DISABLED (conflicted with custom Enter handler)
        // closeBracketsKeymap - PERMANENTLY REMOVED (intercepted closing brackets)
        // indentOnInput() - PERMANENTLY DISABLED (not needed with our custom handler)
    ];
    return extensions;
}
/**
 * Helper to create a basic CodeMirror state
 */
function createEditorState(initialValue, extensions) {
    return dist_EditorState.create({
        doc: initialValue,
        extensions
    });
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/code-editor/JavaScriptEditor.module.scss
var JavaScriptEditor_module = __webpack_require__(51171);
;// ../noodl-core-ui/src/components/code-editor/JavaScriptEditor.module.scss

      
      
      
      
      
      
      
      
      

var JavaScriptEditor_module_options = {};

JavaScriptEditor_module_options.styleTagTransform = (styleTagTransform_default());
JavaScriptEditor_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      JavaScriptEditor_module_options.insert = insertBySelector_default().bind(null, "head");
    
JavaScriptEditor_module_options.domAPI = (styleDomAPI_default());
JavaScriptEditor_module_options.insertStyleElement = (insertStyleElement_default());

var JavaScriptEditor_module_update = injectStylesIntoStyleTag_default()(JavaScriptEditor_module/* default */.A, JavaScriptEditor_module_options);




       /* harmony default export */ const code_editor_JavaScriptEditor_module = (JavaScriptEditor_module/* default */.A && JavaScriptEditor_module/* default */.A.locals ? JavaScriptEditor_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/code-editor/utils/jsFormatter.ts
/**
 * JavaScript Formatting Utilities
 *
 * Simple indentation and formatting for JavaScript code.
 * Not a full formatter, just basic readability improvements.
 *
 * @module code-editor/utils
 */
/**
 * Format JavaScript code with basic indentation
 *
 * This is a simple formatter that:
 * - Adds indentation after opening braces
 * - Removes indentation after closing braces
 * - Adds newlines for readability
 *
 * Not perfect, but good enough for small code snippets.
 */
function formatJavaScript(code) {
    if (!code || code.trim() === '') {
        return code;
    }
    let formatted = '';
    let indentLevel = 0;
    const indentSize = 2; // 2 spaces per indent
    let inString = false;
    let stringChar = '';
    // Remove existing whitespace for consistent formatting
    const trimmed = code.trim();
    for (let i = 0; i < trimmed.length; i++) {
        const char = trimmed[i];
        const prevChar = i > 0 ? trimmed[i - 1] : '';
        const nextChar = i < trimmed.length - 1 ? trimmed[i + 1] : '';
        // Track string state to avoid formatting inside strings
        if ((char === '"' || char === "'" || char === '`') && prevChar !== '\\') {
            if (!inString) {
                inString = true;
                stringChar = char;
            }
            else if (char === stringChar) {
                inString = false;
                stringChar = '';
            }
        }
        // Don't format inside strings
        if (inString) {
            formatted += char;
            continue;
        }
        // Handle opening brace
        if (char === '{') {
            formatted += char;
            indentLevel++;
            if (nextChar !== '}') {
                formatted += '\n' + ' '.repeat(indentLevel * indentSize);
            }
            continue;
        }
        // Handle closing brace
        if (char === '}') {
            indentLevel = Math.max(0, indentLevel - 1);
            // Add newline before closing brace if there's content before it
            if (prevChar !== '{' && prevChar !== '\n') {
                formatted += '\n' + ' '.repeat(indentLevel * indentSize);
            }
            formatted += char;
            continue;
        }
        // Handle semicolon (add newline after)
        if (char === ';') {
            formatted += char;
            if (nextChar && nextChar !== '\n' && nextChar !== '}') {
                formatted += '\n' + ' '.repeat(indentLevel * indentSize);
            }
            continue;
        }
        // Skip multiple consecutive spaces/newlines
        if ((char === ' ' || char === '\n') && (prevChar === ' ' || prevChar === '\n')) {
            continue;
        }
        // Replace newlines with properly indented newlines
        if (char === '\n') {
            formatted += '\n' + ' '.repeat(indentLevel * indentSize);
            continue;
        }
        formatted += char;
    }
    return formatted.trim();
}

;// ../noodl-core-ui/src/components/code-editor/utils/jsValidator.ts
/**
 * JavaScript Validation Utilities
 *
 * Validates JavaScript code using the Function constructor.
 * This catches syntax errors without needing a full parser.
 *
 * @module code-editor/utils
 */
/**
 * Extract line and column from error message
 */
function parseErrorLocation(error) {
    const message = error.message;
    // Try to extract line number from various error formats
    const lineMatch = message.match(/line (\d+)/i);
    const posMatch = message.match(/position (\d+)/i);
    return {
        line: lineMatch ? parseInt(lineMatch[1], 10) : undefined,
        column: posMatch ? parseInt(posMatch[1], 10) : undefined
    };
}
/**
 * Get helpful suggestion based on error message
 */
function getSuggestion(error) {
    const message = error.message.toLowerCase();
    if (message.includes('unexpected token') || message.includes('unexpected identifier')) {
        return 'Check for missing or extra brackets, parentheses, or quotes';
    }
    if (message.includes('unexpected end of input')) {
        return 'You may be missing a closing bracket or parenthesis';
    }
    if (message.includes('unexpected string') || message.includes("unexpected ','")) {
        return 'Check for missing operators or commas between values';
    }
    if (message.includes('missing') && message.includes('after')) {
        return 'Check the syntax around the indicated position';
    }
    return undefined;
}
/**
 * Validate JavaScript expression
 * Wraps code in `return ()` to validate as expression
 */
function validateExpression(code) {
    if (!code || code.trim() === '') {
        return { valid: true };
    }
    try {
        // Try to create a function that returns the expression
        // This validates that it's a valid JavaScript expression
        new Function(`return (${code});`);
        return { valid: true };
    }
    catch (error) {
        const location = parseErrorLocation(error);
        return {
            valid: false,
            error: error.message,
            suggestion: getSuggestion(error),
            ...location
        };
    }
}
/**
 * Validate JavaScript function body
 * Creates a function with the code as body
 */
function validateFunction(code) {
    if (!code || code.trim() === '') {
        return { valid: true };
    }
    try {
        // Create a function with the code as body
        new Function(code);
        return { valid: true };
    }
    catch (error) {
        const location = parseErrorLocation(error);
        return {
            valid: false,
            error: error.message,
            suggestion: getSuggestion(error),
            ...location
        };
    }
}
/**
 * Validate JavaScript script
 * Same as function validation for our purposes
 */
function validateScript(code) {
    return validateFunction(code);
}
/**
 * Main validation function
 * Validates JavaScript code based on validation type
 */
function jsValidator_validateJavaScript(code, validationType = 'expression') {
    switch (validationType) {
        case 'expression':
            return validateExpression(code);
        case 'function':
            return validateFunction(code);
        case 'script':
            return validateScript(code);
        default:
            return { valid: false, error: 'Unknown validation type' };
    }
}

;// ../noodl-core-ui/src/components/code-editor/JavaScriptEditor.tsx
/**
 * JavaScriptEditor Component
 *
 * A feature-rich JavaScript code editor powered by CodeMirror 6.
 * Includes syntax highlighting, autocompletion, linting, and all IDE features.
 *
 * @module code-editor
 */









/**
 * Main JavaScriptEditor Component
 */
function JavaScriptEditor({ value, onChange, onSave, onClose, validationType = 'expression', disabled = false, height, width, placeholder = '// Enter your JavaScript code here', nodeId, parameterName }) {
    var _a;
    const rootRef = (0,external_react_.useRef)(null);
    const editorContainerRef = (0,external_react_.useRef)(null);
    const editorViewRef = (0,external_react_.useRef)(null);
    // Generation counter approach to prevent race conditions
    // Replaces the unreliable isInternalChangeRef + setTimeout pattern
    const changeGenerationRef = (0,external_react_.useRef)(0);
    const lastSyncedGenerationRef = (0,external_react_.useRef)(0);
    // Only store validation state (needed for display outside editor)
    // Don't store localValue - CodeMirror is the single source of truth
    const [validation, setValidation] = (0,external_react_.useState)(jsValidator_validateJavaScript(value || '', validationType));
    // Resize support - convert width/height to numbers
    const initialWidth = typeof width === 'number' ? width : typeof width === 'string' ? parseInt(width, 10) : 800;
    const initialHeight = typeof height === 'number' ? height : typeof height === 'string' ? parseInt(height, 10) : 500;
    const [size, setSize] = (0,external_react_.useState)({
        width: initialWidth,
        height: initialHeight
    });
    const { startDrag } = (0,useDragHandler/* useDragHandler */.k)({
        root: rootRef,
        minHeight: 200,
        minWidth: 400,
        onDrag(contentWidth, contentHeight) {
            setSize({
                width: contentWidth,
                height: contentHeight
            });
        },
        onEndDrag() {
            var _a;
            (_a = editorViewRef.current) === null || _a === void 0 ? void 0 : _a.focus();
        }
    });
    // Handle text changes from CodeMirror
    const handleChange = (0,external_react_.useCallback)((newValue) => {
        // Increment generation counter for every internal change
        // This prevents race conditions with external value syncing
        changeGenerationRef.current++;
        // Validate the new code
        const result = jsValidator_validateJavaScript(newValue, validationType);
        setValidation(result);
        // Propagate changes to parent
        if (onChange) {
            onChange(newValue);
        }
        // No setTimeout needed - generation counter handles sync safely
    }, [onChange, validationType]);
    // Handle format button
    const handleFormat = (0,external_react_.useCallback)(() => {
        if (!editorViewRef.current)
            return;
        try {
            const currentCode = editorViewRef.current.state.doc.toString();
            const formatted = formatJavaScript(currentCode);
            // Increment generation counter for programmatic changes
            changeGenerationRef.current++;
            // Update CodeMirror with formatted code
            editorViewRef.current.dispatch({
                changes: {
                    from: 0,
                    to: editorViewRef.current.state.doc.length,
                    insert: formatted
                }
            });
            if (onChange) {
                onChange(formatted);
            }
            // No setTimeout needed
        }
        catch (error) {
            console.error('Format error:', error);
        }
    }, [onChange]);
    // Initialize CodeMirror editor
    (0,external_react_.useEffect)(() => {
        if (!editorContainerRef.current)
            return;
        // Create extensions
        const extensions = createExtensions({
            validationType,
            placeholder,
            readOnly: disabled,
            onChange: handleChange,
            onSave,
            tabSize: 2
        });
        // Create editor state
        const state = createEditorState(value || '', extensions);
        // Create editor view
        const view = new dist_EditorView({
            state,
            parent: editorContainerRef.current
        });
        editorViewRef.current = view;
        // Cleanup on unmount
        return () => {
            view.destroy();
            editorViewRef.current = null;
        };
        // Only run on mount - we handle updates separately
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    // Update editor when external value changes (but NOT from internal typing)
    (0,external_react_.useEffect)(() => {
        if (!editorViewRef.current)
            return;
        // Skip if internal changes have happened since last sync
        // This prevents race conditions from auto-complete, fold, etc.
        if (changeGenerationRef.current > lastSyncedGenerationRef.current) {
            return;
        }
        const currentValue = editorViewRef.current.state.doc.toString();
        // Only update if value actually changed from external source
        if (currentValue !== value) {
            // Update synced generation to current
            lastSyncedGenerationRef.current = changeGenerationRef.current;
            // Preserve cursor position during external update
            const currentSelection = editorViewRef.current.state.selection;
            editorViewRef.current.dispatch({
                changes: {
                    from: 0,
                    to: editorViewRef.current.state.doc.length,
                    insert: value || ''
                },
                // Try to preserve selection if it's still valid
                selection: currentSelection.ranges[0].to <= (value || '').length ? currentSelection : undefined
            });
            setValidation(jsValidator_validateJavaScript(value || '', validationType));
        }
    }, [value, validationType]);
    // Update read-only state
    (0,external_react_.useEffect)(() => {
        if (!editorViewRef.current)
            return;
        editorViewRef.current.dispatch({
            effects: [
            // Note: This requires reconfiguring the editor
            // For now, we handle it on initial mount
            ]
        });
    }, [disabled]);
    // Get validation mode label
    const getModeLabel = () => {
        switch (validationType) {
            case 'expression':
                return 'Expression';
            case 'function':
                return 'Function';
            case 'script':
                return 'Script';
            default:
                return 'JavaScript';
        }
    };
    return (external_react_default().createElement("div", { ref: rootRef, className: code_editor_JavaScriptEditor_module['Root'], style: {
            width: size.width,
            height: size.height,
            minWidth: 400,
            minHeight: 200
        } },
        external_react_default().createElement("div", { className: code_editor_JavaScriptEditor_module['Toolbar'] },
            external_react_default().createElement("div", { className: code_editor_JavaScriptEditor_module['ToolbarLeft'] },
                external_react_default().createElement("span", { className: code_editor_JavaScriptEditor_module['ModeLabel'] }, getModeLabel()),
                validation.valid ? (external_react_default().createElement("span", { className: code_editor_JavaScriptEditor_module['StatusValid'] }, "\u2713 Valid")) : (external_react_default().createElement("span", { className: code_editor_JavaScriptEditor_module['StatusInvalid'] }, "\u2717 Error"))),
            external_react_default().createElement("div", { className: code_editor_JavaScriptEditor_module['ToolbarRight'] },
                nodeId && parameterName && (external_react_default().createElement(CodeHistoryButton, { nodeId: nodeId, parameterName: parameterName, currentCode: ((_a = editorViewRef.current) === null || _a === void 0 ? void 0 : _a.state.doc.toString()) || value || '', onRestore: (snapshot) => {
                        if (!editorViewRef.current)
                            return;
                        // Increment generation counter for restore operation
                        changeGenerationRef.current++;
                        // Restore code from snapshot
                        editorViewRef.current.dispatch({
                            changes: {
                                from: 0,
                                to: editorViewRef.current.state.doc.length,
                                insert: snapshot.code
                            }
                        });
                        if (onChange) {
                            onChange(snapshot.code);
                        }
                        // No setTimeout needed
                        // Don't auto-save - let user manually save if they want to keep the restored version
                        // This prevents creating duplicate snapshots
                    } })),
                external_react_default().createElement("button", { onClick: handleFormat, disabled: disabled, className: code_editor_JavaScriptEditor_module['FormatButton'], title: "Format code", type: "button" }, "Format"),
                onSave && (external_react_default().createElement("button", { onClick: () => {
                        var _a;
                        const currentCode = ((_a = editorViewRef.current) === null || _a === void 0 ? void 0 : _a.state.doc.toString()) || '';
                        onSave(currentCode);
                    }, disabled: disabled, className: code_editor_JavaScriptEditor_module['SaveButton'], title: "Save (Ctrl+S)", type: "button" }, "Save")),
                onClose && (external_react_default().createElement("button", { onClick: () => {
                        var _a;
                        // Save before closing if onSave is available
                        if (onSave) {
                            const currentCode = ((_a = editorViewRef.current) === null || _a === void 0 ? void 0 : _a.state.doc.toString()) || '';
                            onSave(currentCode);
                        }
                        onClose();
                    }, className: code_editor_JavaScriptEditor_module['CloseButton'], title: "Save and Close (Escape)", type: "button" }, "Close")))),
        external_react_default().createElement("div", { ref: editorContainerRef, className: code_editor_JavaScriptEditor_module['EditorContainer'] }),
        !validation.valid && (external_react_default().createElement("div", { className: code_editor_JavaScriptEditor_module['ErrorPanel'] },
            external_react_default().createElement("div", { className: code_editor_JavaScriptEditor_module['ErrorHeader'] },
                external_react_default().createElement("span", { className: code_editor_JavaScriptEditor_module['ErrorIcon'] }, "\u26A0\uFE0F"),
                external_react_default().createElement("span", { className: code_editor_JavaScriptEditor_module['ErrorTitle'] }, "Syntax Error")),
            external_react_default().createElement("div", { className: code_editor_JavaScriptEditor_module['ErrorMessage'] }, validation.error),
            validation.suggestion && (external_react_default().createElement("div", { className: code_editor_JavaScriptEditor_module['ErrorSuggestion'] },
                external_react_default().createElement("strong", null, "\uD83D\uDCA1 Suggestion:"),
                " ",
                validation.suggestion)),
            validation.line !== undefined && (external_react_default().createElement("div", { className: code_editor_JavaScriptEditor_module['ErrorLocation'] },
                "Line ",
                validation.line,
                validation.column !== undefined && `, Column ${validation.column}`)))),
        external_react_default().createElement("div", { className: code_editor_JavaScriptEditor_module['Footer'] },
            external_react_default().createElement("div", { className: code_editor_JavaScriptEditor_module['FooterLeft'] }),
            external_react_default().createElement("div", { className: code_editor_JavaScriptEditor_module['FooterRight'] },
                external_react_default().createElement(ToolbarGrip/* ToolbarGrip */.M, { onMouseDown: startDrag })))));
}

;// ../noodl-core-ui/src/components/code-editor/index.ts
/**
 * JavaScriptEditor Component
 *
 * A feature-rich JavaScript code editor powered by CodeMirror 6.
 * Includes syntax highlighting, autocompletion, linting, code folding,
 * and all modern IDE features for Expression, Function, and Script nodes.
 *
 * @module code-editor
 */




;// ./src/editor/src/views/panels/propertyeditor/TypeView.js




class TypeView extends (view_default()) {
  constructor() {
    super();
  }

  dispose() {
    EventDispatcher.EventDispatcher.instance.off(this);
  }

  render() {
    var _this = this;

    //check if we have a "parentPorts". If it does, it means the default value is derived
    //from a style, and we need to update when the style updates
    if (this.parent.model && this.parent.model.model) {
      EventDispatcher.EventDispatcher.instance.off(this); //safeguard agains multiple renders
      const port = this.parent.model.model.getPort(this.name);
      if (port.type.parentPort) {
        EventDispatcher.EventDispatcher.instance.on(
          'ProjectModel.metadataChanged',
          ({ key }) => {
            //only need to update if we're at the default value
            if (key === 'styles' && this.isDefault) {
              this.resetToDefault();
            }
          },
          this
        );
      }
    }

    var el = this.el.find('.property-input-connected');
    el.on('mouseenter', function () {
      popuplayer_default().instance.showTooltip({
        x: $(this).offset().left + $(this).outerWidth(),
        y: $(this).offset().top + $(this).outerHeight() / 2,
        position: 'right',
        content: 'This port is connected and the specified value is likely overwritten.'
      });
    }).on('mouseleave', function () {
      popuplayer_default().instance.hideTooltip();
    });

    this.$('input')
      .on('focus', function () {
        $(this).addClass('property-input-focused');
      })
      .on('blur', function () {
        $(this).removeClass('property-input-focused');
      });

    var toolTipTimeout;
    this.$('.property-changed-dot')
      .on('click', function () {
        clearTimeout(toolTipTimeout);
        _this.parent.model.setParameter(_this.name, undefined, {
          undo: true,
          label: 'reset parameter'
        });
        _this.isDefault = true;
        _this.resetToDefault();
      })
      .on('mouseenter', function () {
        var _el = this;
        toolTipTimeout = setTimeout(function () {
          popuplayer_default().instance.showTooltip({
            x: $(_el).offset().left + $(_el).outerWidth(),
            y: $(_el).offset().top + $(_el).outerHeight() / 2,
            position: 'right',
            content: 'Reset to default'
          });
        }, 1000);
      })
      .on('mouseleave', function () {
        popuplayer_default().instance.hideTooltip();
      });
  }

  getCurrentValue(name) {
    var _name = name === undefined ? this.name : name;

    if (this.parent.model.hasParameter && !this.parent.model.hasParameter(_name)) {
      // Happens for dynamic port sometimes
      return '';
    }

    return {
      value: this.parent.model.getParameter(_name),
      isDefault: this.parent.model.parameters[_name] === undefined
    };
  }

  resetToDefault() {
    this.$('input').val(this.getCurrentValue().value);
  }
}

;// ./src/editor/src/views/panels/propertyeditor/utils.ts
function getEditType(p) {
    var _a;
    return ((_a = p.type) === null || _a === void 0 ? void 0 : _a.editAsType) ? p.type.editAsType : p.type;
}

;// ./src/editor/src/reactcomponents/tooltip.tsx


/*
    TODO to reach parity with the popups in PopupLayer:
        - support arrows from more directions
        - align arrow with center of content
        - tooltips that expand and shows more content
        - optimization: don't render all the tooltip HTML if it's not showing (currently just hidden with opacity)
*/
function useShowThenHideWithTimeout(shouldShow) {
    const [isShowing, setIsShowing] = (0,external_react_.useState)(false);
    (0,external_react_.useEffect)(() => {
        if (!shouldShow) {
            setIsShowing(false);
            return;
        }
        const timeoutId = setTimeout(() => setIsShowing(true), 500);
        return () => clearTimeout(timeoutId);
    }, [shouldShow]);
    return isShowing;
}
function tooltip_Tooltip({ enabled, children, text }) {
    if (enabled === false) {
        return children;
    }
    const [isHovering, setIsHovering] = (0,external_react_.useState)(false);
    const show = useShowThenHideWithTimeout(isHovering);
    return (external_react_default().createElement("div", { style: { position: 'relative' } },
        external_react_default().createElement("div", { className: "popup-layer-tooltip", style: { opacity: show ? 1 : 0, top: 'calc(100% + 5px)', whiteSpace: 'nowrap' } },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud }, text)),
        external_react_default().createElement("div", { onMouseEnter: () => setIsHovering(true), onMouseLeave: () => setIsHovering(false) }, children)));
}

;// ./src/editor/src/views/panels/propertyeditor/CodeEditor/Property.tsx


function Property({ isPrimary, displayName, tooltip, isDefault, onClick }) {
    return (external_react_default().createElement("div", { "data-template": "codeeditor", "data-primary": isPrimary, style: { height: '35px', position: 'relative' } },
        external_react_default().createElement(tooltip_Tooltip, { enabled: !!tooltip, text: tooltip },
            external_react_default().createElement("label", { className: "property-label" }, displayName)),
        external_react_default().createElement("div", { className: "property-value" },
            external_react_default().createElement("button", { type: "button", style: { width: '100%', height: '100%' }, className: "property-codeeditor-button", onClick: onClick, "data-identifier": displayName }, "Edit")),
        !isDefault && (
        /* position="right" */
        external_react_default().createElement(tooltip_Tooltip, { text: "Cannot reset code" },
            external_react_default().createElement("span", { className: "property-changed-dot-noreset" })))));
}

;// ./src/editor/src/views/panels/propertyeditor/CodeEditor/CodeEditorType.ts










// hot-reload
const CodeEditor = (__webpack_require__(67736)/* .CodeEditor */ .B);
/**
 * Collect more information for where the error occurred.
 */
function parseStackTrace(stack) {
    const stackTraceLines = stack.split('\n');
    if (stackTraceLines.length <= 1)
        return null;
    const result = stackTraceLines[1].match(/<anonymous>:(\d+):(\d+)\)/);
    if (!result)
        return {};
    if (result.length < 3)
        return {};
    return {
        lineNumber: Number(result[1]),
        columnNumber: Number(result[2])
    };
}
// HACK: This is a very ugly solution to keep track of the position, for this
//       purpose I think it is an alright trade off with how the current system
//       is built, since we only care about the position during the currently
//       active editor instance.
//
// Ideally CodeEditorType should be more merged in to the React component and
// control everything from in there.
class CodeEditorViewStateCache {
    constructor() {
        this._cache = {};
    }
    save(nodeId, viewState) {
        this._cache[nodeId] = viewState;
    }
    get(nodeId) {
        return this._cache[nodeId];
    }
}
CodeEditorViewStateCache.instance = new CodeEditorViewStateCache();
class CodeEditorType extends TypeView {
    constructor() {
        super(...arguments);
        this.propertyRoot = null;
        this.popoutRoot = null;
    }
    static fromPort(args) {
        var _a, _b, _c;
        const view = new CodeEditorType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.parent = parent;
        view.value = parent.model.getParameter(p.name);
        view.default = p.default;
        view.tooltip = p.tooltip;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        // Try multiple locations for readOnly flag
        view.readOnly = p.readOnly || ((_a = p.type) === null || _a === void 0 ? void 0 : _a.readOnly) || ((_b = getEditType(p)) === null || _b === void 0 ? void 0 : _b.readOnly) || false;
        // HACK: Like most of Property panel,
        //       since the property panel can have many code editors
        //       we want to open the one most likely to be the
        //       primary one when dubble clicking a node.
        view.isPrimary = !!((_c = view.type) === null || _c === void 0 ? void 0 : _c.codeeditor);
        return view;
    }
    dispose() {
        var _a;
        (_a = this.model) === null || _a === void 0 ? void 0 : _a.dispose();
        this.model = null;
        // Unmount popout root
        if (this.popoutRoot) {
            this.popoutRoot.unmount();
            this.popoutRoot = null;
        }
        warningsmodel/* WarningsModel */.l.instance.off(this);
    }
    render() {
        this.el = this.bindView($(`<div></div>`), this);
        super.render();
        const self = this;
        const propertyProps = {
            isPrimary: this.isPrimary,
            displayName: this.displayName || 'Script',
            tooltip: this.tooltip,
            isDefault: this.isDefault,
            onClick(event) {
                self.onLaunchClicked(self, event.currentTarget, event);
            }
        };
        this.propertyDiv = document.createElement('div');
        this.propertyRoot = (0,client.createRoot)(this.propertyDiv);
        this.propertyRoot.render(external_react_default().createElement(Property, propertyProps));
        return this.propertyDiv;
    }
    updateWarnings() {
        const _this = this;
        if (!this.model) {
            return;
        }
        const markers = [];
        const decorations = [];
        try {
            warningsmodel/* WarningsModel */.l.instance.forEachWarning(function (_w, _ref, _key, warning) {
                if (!warning.ref.node)
                    return; // Only for node warnings
                if (!_this.parent.model.model)
                    return; // Head code doesn't have a model
                // Check if the warning is for this node and property
                const isThisNode = warning.ref.node.id === _this.parent.model.model.id;
                const isThisProp = warning.ref.node.typename === _this.parent.model.model.typename;
                const isForMe = isThisNode && isThisProp;
                if (!isForMe)
                    return;
                // Check if the warning has a stack trace
                if (!warning.warning.stack)
                    return;
                const { columnNumber, lineNumber } = parseStackTrace(warning.warning.stack);
                const length = warning.warning.message.split(' ')[0].length;
                // NOTE: This is becuase when the method is called, we pass in 3 arguments.
                //  await func.apply(this._internal._this, [inputs, outputs, JavascriptNodeParser.getComponentScopeForNode(this)]);
                const lineNumberOffset = -3;
                markers.push({
                    severity: editor_api.MarkerSeverity.Error,
                    startLineNumber: lineNumber + lineNumberOffset,
                    startColumn: columnNumber,
                    endLineNumber: lineNumber + lineNumberOffset,
                    endColumn: columnNumber + length,
                    message: 'Runtime: ' + warning.warning.message
                });
            });
        }
        catch (error) {
            // Lets just catch any errors here
            // Doing so will not prevent the code editor from opening
            console.error(error);
        }
        // Decorations are on the sidebar
        // decorations.push({
        //   ownerId: 999,
        //   id: 'test-999',
        //   range: new monaco.Range(lineNumber - 2, columnNumber, lineNumber - 2, columnNumber + 1),
        //   options: {
        //     isWholeLine: true,
        //     // linesDecorationsClassName: 'code-editor__line__error',
        //     inlineClassName: 'code-editor__inline__error',
        //     hoverMessage: { value: 'Runtime: ' + warning.warning.message },
        //   }
        // });
        editor_api.editor.setModelMarkers(this.model.model, 'editor', markers);
        this.model.model.deltaDecorations([], decorations);
    }
    /** HTML Binding */
    onLaunchClicked(scope, el, evt) {
        var _a, _b, _c, _d, _e;
        const _this = this;
        const nodeId = (_b = (_a = _this.parent.model) === null || _a === void 0 ? void 0 : _a.model) === null || _b === void 0 ? void 0 : _b.id;
        this.propertyName = scope.name;
        this.parent.hidePopout();
        // Always use new JavaScriptEditor for JavaScript/TypeScript
        const isJavaScriptEditor = this.type.codeeditor === 'javascript' || this.type.codeeditor === 'typescript';
        // Only set up Monaco warnings for Monaco-based editors
        if (!isJavaScriptEditor) {
            warningsmodel/* WarningsModel */.l.instance.off(this);
            warningsmodel/* WarningsModel */.l.instance.on('warningsChanged', function () {
                _this.updateWarnings();
            }, this);
        }
        function save() {
            // For JavaScriptEditor, use this.value (already updated in onChange)
            // For Monaco editor, get value from model
            let source = isJavaScriptEditor ? _this.value : _this.model.getValue();
            if (source === '')
                source = undefined;
            // Save snapshot to history (before updating)
            if (source && nodeId) {
                CodeHistoryManager.CodeHistoryManager.instance.saveSnapshot(nodeId, scope.name, source);
            }
            _this.value = source;
            _this.parent.setParameter(scope.name, source !== _this.default ? source : undefined);
            _this.isDefault = source === undefined;
        }
        const node = this.parent.model.model;
        // Only create Monaco model for Monaco-based editors
        if (!isJavaScriptEditor) {
            this.model = createModel({
                type: this.type.name || this.type,
                value: this.value,
                codeeditor: (_c = this.type.codeeditor) === null || _c === void 0 ? void 0 : _c.toLowerCase()
            }, node);
        }
        const props = {
            nodeId,
            model: this.model,
            // NOTE(auto-saving): Add debounce to enable auto saving
            // onSave: debounce(save, 500)
            onSave: save,
            outEditor: (editor) => {
                this.editor = editor;
                // Allow the editor to be rendered
                setImmediate(() => {
                    const viewState = CodeEditorViewStateCache.instance.get(nodeId);
                    if (viewState) {
                        editor.restoreViewState(viewState);
                    }
                });
            }
        };
        if (localStorage['codeeditor_size_percentage']) {
            try {
                const json = JSON.parse(localStorage['codeeditor_size_percentage']);
                const b = document.body.getBoundingClientRect();
                const width = Math.min(Math.max(b.width * json.width, 400), b.width - 300);
                const height = Math.min(Math.max(b.height * json.height, 400), b.height - 300);
                props.initialSize = {
                    x: width,
                    y: height
                };
            }
            catch (error) { }
        }
        else {
            // Default size: Make it wider (60% of viewport width, 70% of height)
            const b = document.body.getBoundingClientRect();
            props.initialSize = {
                x: Math.min(b.width * 0.6, b.width - 200), // 60% width, but leave some margin
                y: Math.min(b.height * 0.7, b.height - 200) // 70% height
            };
        }
        this.popoutDiv = document.createElement('div');
        this.popoutRoot = (0,client.createRoot)(this.popoutDiv);
        // Determine which editor to use
        if (isJavaScriptEditor) {
            // Determine validation type based on editor type
            let validationType = 'function';
            if (this.type.codeeditor === 'javascript') {
                // Could be expression or function - check type name for hints
                const typeName = (this.type.name || '').toLowerCase();
                if (typeName.includes('expression')) {
                    validationType = 'expression';
                }
                else if (typeName.includes('script')) {
                    validationType = 'script';
                }
                else {
                    validationType = 'function';
                }
            }
            else if (this.type.codeeditor === 'typescript') {
                validationType = 'script';
            }
            // Create close handler to trigger popout close
            const closeHandler = () => {
                _this.parent.hidePopout();
            };
            // Render JavaScriptEditor with proper sizing and history support
            // For read-only fields, don't pass nodeId/parameterName (no history tracking)
            this.popoutRoot.render(external_react_default().createElement(JavaScriptEditor, {
                value: this.value || '',
                onChange: (newValue) => {
                    this.value = newValue;
                    // Don't update Monaco model - JavaScriptEditor is independent
                    // The old code triggered Monaco validation which caused errors
                },
                onSave: () => {
                    save();
                },
                onClose: closeHandler,
                validationType,
                disabled: this.readOnly, // Enable read-only mode if port is marked readOnly
                width: ((_d = props.initialSize) === null || _d === void 0 ? void 0 : _d.x) || 800,
                height: ((_e = props.initialSize) === null || _e === void 0 ? void 0 : _e.y) || 500,
                // Only add history tracking for editable fields
                nodeId: this.readOnly ? undefined : nodeId,
                parameterName: this.readOnly ? undefined : scope.name
            }));
        }
        else {
            // Use existing Monaco CodeEditor
            this.popoutRoot.render(external_react_default().createElement(CodeEditor, props));
        }
        const popoutDiv = this.popoutDiv;
        this.parent.showPopout({
            content: { el: [this.popoutDiv] },
            attachTo: $(el),
            position: 'right',
            disableDynamicPositioning: true,
            onClose: function () {
                // ---
                // Save the document
                save();
                if (_this.editor) {
                    const viewState = _this.editor.saveViewState();
                    CodeEditorViewStateCache.instance.save(nodeId, viewState);
                }
                // ---
                // Save the window size
                const a = popoutDiv.getBoundingClientRect();
                const b = document.body.getBoundingClientRect();
                localStorage['codeeditor_size_percentage'] = JSON.stringify({
                    width: a.width / b.width,
                    height: a.height / b.height
                });
                // ---
                // Dispose
                _this.dispose();
            }
        });
        // Only update warnings for Monaco-based editors
        if (!isJavaScriptEditor) {
            this.updateWarnings();
        }
        evt.stopPropagation();
    }
}

;// ./src/editor/src/views/panels/propertyeditor/CodeEditor/index.ts


;// ./src/shared/ReactView.ts



class ReactView extends (view_default()) {
    constructor(props) {
        super();
        this.root = null;
        this.props = props;
    }
    set owner(owner) {
        this.props.owner = owner;
        this.render();
    }
    render() {
        if (!this.el) {
            this.el = $(document.createElement('div'));
            this.el.css({
                width: '100%',
                height: '100%'
            });
        }
        if (!this.root) {
            this.root = (0,client.createRoot)(this.el[0]);
        }
        this.root.render(external_react_default().createElement(this.renderReact.bind(this), this.props));
        return this.el;
    }
    dispose() {
        if (this.root) {
            this.root.unmount();
            this.root = null;
        }
    }
}

;// ./src/editor/src/views/PopupLayer/PopupMenu.tsx



class PopupMenu extends ReactView {
    constructor(props) {
        super(props);
    }
    renderReact({ items, owner }) {
        return (external_react_default().createElement("div", { className: "popup-layer-popup-menu" }, items.map((item, index) => {
            if (item.type === 'divider') {
                return external_react_default().createElement("div", { key: index, className: "popup-layer-popup-menu-divider" });
            }
            function onClick(evt) {
                owner && owner.hidePopup();
                item.onClick && item.onClick();
                evt.stopPropagation();
                evt.preventDefault();
            }
            return (external_react_default().createElement(ListItem, { key: index, onClick: onClick, icon: item.icon, text: item.label, variant: ListItemVariant.DefaultContrast }));
        })));
    }
}

;// ./src/editor/src/views/PopupLayer/index.ts


;// ./src/editor/src/views/panels/propertyeditor/Pages/Pages.tsx










// Styles
__webpack_require__(24004);
function CreateNewPage(props) {
    const [isCreating, setIsCreating] = (0,external_react_.useState)(false);
    const inputRef = (0,external_react_.useRef)(null);
    const onCreateNewPage = () => {
        const name = inputRef.current.value;
        if (!name)
            return;
        props.onCreateNewPage(name);
    };
    if (isCreating) {
        return (external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement("div", { className: "variants-header" },
                external_react_default().createElement("span", null, "New page name")),
            external_react_default().createElement("div", { className: "variants-input-container" },
                external_react_default().createElement("input", { autoFocus: true, className: "variants-input", ref: inputRef, onKeyUp: (e) => e.key === 'Enter' && onCreateNewPage() }),
                external_react_default().createElement("button", { className: "variants-button primary", onClick: onCreateNewPage }, "Create"))));
    }
    else {
        return (external_react_default().createElement("div", { className: "variants-header variants-add-header" },
            external_react_default().createElement("span", null, "Create new page"),
            external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Plus, size: common_Icon/* IconSize */.lK.Small, UNSAFE_className: "add-button", variant: inputs_IconButton/* IconButtonVariant */.nl.OpaqueOnHover, onClick: () => setIsCreating(true) })));
    }
}
function PageItem(props) {
    return (external_react_default().createElement("div", { className: "variants-pick-variant-item is-page", onClick: props.onSelectClicked },
        external_react_default().createElement("div", { className: "variants-pick-variant-inner" },
            external_react_default().createElement("div", { className: "router-pages-icon", style: { margin: '0px', marginLeft: '7px' } }),
            external_react_default().createElement("div", { className: "variant-item-name", style: { marginRight: '7px' } }, props.name))));
}
function AddNewPagePopup(props) {
    return (external_react_default().createElement("div", { style: { width: '230px', height: '400px', display: 'flex', flexDirection: 'column' } },
        external_react_default().createElement("div", { style: { overflow: 'hidden auto', flexGrow: 1 } },
            external_react_default().createElement(CreateNewPage, { onCreateNewPage: props.onCreateNewPage }),
            props.pages.map((p) => (external_react_default().createElement(PageItem, { name: p.title || p.component, key: p.title || p.component, onSelectClicked: () => props.onPageSelected(p) }))))));
}
function BigPageItem(props) {
    const popupAnchor = (0,external_react_.useRef)(null);
    const p = props.page;
    return (external_react_default().createElement("div", { style: { display: 'flex' } },
        external_react_default().createElement("div", { className: "router-pages-page", onClick: props.onPageClicked },
            external_react_default().createElement("div", { style: { display: 'flex' } },
                external_react_default().createElement("div", { className: 'router-pages-icon' + (props.isStartPage ? ' start-page' : '') })),
            external_react_default().createElement("div", { style: { flexGrow: 1 } },
                external_react_default().createElement("div", { className: "router-pages-component" }, p.title || p.component),
                external_react_default().createElement("div", { className: "router-pages-path" }, p.path)),
            external_react_default().createElement("div", { style: { display: 'flex' } },
                external_react_default().createElement("div", { className: "router-pages-actions-icon", ref: popupAnchor, onClick: (evt) => props.onPageActionsClicked(popupAnchor.current, evt) },
                    external_react_default().createElement("i", { className: "fa fa-ellipsis-h" }))))));
}
class Pages extends (external_react_default()).Component {
    constructor(props) {
        super(props);
        // @ts-expect-error
        this.value = this.props.value || {};
        // @ts-expect-error
        const pages = RouterAdapter/* RouterAdapter */.F.getPageInfoForComponents(this.value.routes || []);
        this.state = {
            pages: pages
        };
    }
    componentDidMount() { }
    componentWillUnmount() { }
    onPageClicked(p) {
        // @ts-expect-error
        this.props.onPageClicked && this.props.onPageClicked(p);
    }
    removePage(p) {
        // @ts-expect-error
        if (this.value === undefined || this.value.routes === undefined)
            return;
        // @ts-expect-error
        const idx = this.value.routes.indexOf(p.component);
        if (idx !== -1) {
            // @ts-expect-error
            this.value.routes.splice(idx, 1);
            // @ts-expect-error
            if (this.value.startPage === p.component)
                this.value.startPage = undefined;
            this.setState({
                // @ts-expect-error
                pages: RouterAdapter/* RouterAdapter */.F.getPageInfoForComponents(this.value.routes)
            });
            // @ts-expect-error
            this.props.onChange && this.props.onChange(this.value);
        }
    }
    setAsStartPage(p) {
        // @ts-expect-error
        this.value.startPage = p.component;
        this.setState({});
        // @ts-expect-error
        this.props.onChange && this.props.onChange(this.value);
    }
    onAddNewPageClicked() {
        // Get page components
        // Filter out pages already in the router
        const pages = RouterAdapter/* RouterAdapter */.F.getPageComponents().filter(
        // @ts-expect-error
        (p) => this.value.routes == undefined || this.value.routes.indexOf(p) === -1);
        const props = {
            pages: RouterAdapter/* RouterAdapter */.F.getPageInfoForComponents(pages),
            onCreateNewPage: (name) => {
                if (name === undefined || name === '') {
                    ToastLayer.ToastLayer.showError('Component name cannot be empty');
                    return;
                }
                // Place component in current folder
                const c = NodeGraphContext.NodeGraphContextTmp.nodeGraph.getActiveComponent();
                const nameParts = c.fullName.split('/');
                nameParts.pop();
                const fullName = nameParts.join('/') + '/' + name;
                if (projectmodel.ProjectModel.instance.getComponentWithName(fullName)) {
                    ToastLayer.ToastLayer.showError('A component with that name already exists');
                    return;
                }
                // Create the component
                const pageComponent = RouterAdapter/* RouterAdapter */.F.createPageComponent(fullName);
                projectmodel.ProjectModel.instance.addComponent(pageComponent, { undo: true, label: 'page created' });
                // @ts-expect-error
                if (this.value.routes === undefined)
                    this.value.routes = [];
                // @ts-expect-error
                this.value.routes.push(fullName);
                this.setState({
                    // @ts-expect-error
                    pages: RouterAdapter/* RouterAdapter */.F.getPageInfoForComponents(this.value.routes)
                });
                // @ts-expect-error
                this.props.onChange && this.props.onChange(this.value);
                popuplayer_default().instance.hidePopup();
            },
            onPageSelected: (page) => {
                // @ts-expect-error
                if (this.value.routes === undefined)
                    this.value.routes = [];
                // @ts-expect-error
                this.value.routes.push(page.component);
                this.setState({
                    // @ts-expect-error
                    pages: RouterAdapter/* RouterAdapter */.F.getPageInfoForComponents(this.value.routes)
                });
                // @ts-expect-error
                this.props.onChange && this.props.onChange(this.value);
                popuplayer_default().instance.hidePopup();
            }
        };
        const div = document.createElement('div');
        const root = (0,client.createRoot)(div);
        root.render(external_react_default().createElement(AddNewPagePopup, props));
        popuplayer_default().instance.showPopup({
            content: { el: $(div) },
            // @ts-expect-error - Legacy class component without proper typing
            attachTo: $(this.popupAnchor),
            position: 'right',
            onClose: function () {
                root.unmount();
            }
        });
    }
    onPageActionsClicked(page, popupAnchor, evt) {
        const menu = new PopupMenu({
            items: [
                {
                    icon: common_Icon/* IconName */.$M.Home,
                    label: 'Make start page',
                    onClick: () => {
                        this.setAsStartPage(page);
                    }
                },
                {
                    icon: common_Icon/* IconName */.$M.Trash,
                    label: 'Remove page',
                    onClick: () => {
                        this.removePage(page);
                    }
                }
            ]
        });
        menu.render();
        popuplayer_default().instance.showPopup({
            content: menu,
            attachTo: $(popupAnchor),
            position: 'bottom',
            onOpen: function () {
                //   el.removeClass('sidebar-panel-item-show-on-hover');
            },
            onClose: function () {
                //   el.addClass('sidebar-panel-item-show-on-hover');
            }
        });
        evt.stopPropagation();
    }
    render() {
        return (external_react_default().createElement("div", { style: { display: 'flex', flexDirection: 'column' } },
            // @ts-expect-error
            this.state.pages !== undefined
                ? // @ts-expect-error
                    this.state.pages.map((p) => (external_react_default().createElement(BigPageItem
                    // @ts-expect-error
                    , { 
                        // @ts-expect-error
                        isStartPage: p.component === this.value.startPage, page: p, key: p.component || p.title, onPageClicked: this.onPageClicked.bind(this, p), onPageActionsClicked: this.onPageActionsClicked.bind(this, p) })))
                : null,
            external_react_default().createElement("div", { className: "sidebar-fullwidth-button", onClick: (e) => {
                    e.stopPropagation();
                    this.onAddNewPageClicked();
                }, 
                // @ts-expect-error
                ref: (el) => (this.popupAnchor = el) },
                external_react_default().createElement("i", { className: "fa fa-plus", style: { marginRight: '5px' } }),
                "Add new page")));
    }
}

;// ./src/editor/src/views/panels/propertyeditor/Pages/PagesType.tsx







class PagesType extends TypeView {
    constructor() {
        super(...arguments);
        this.root = null;
    }
    static fromPort(args) {
        const view = new PagesType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.default = p.default;
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        const props = {
            value: this.value,
            router: this.parent.model.getParameter('name'),
            onChange: (value) => {
                const undoArgs = { undo: true, label: 'page settings', oldValue: this.value };
                this.value = value;
                this.parent.model.setParameter(this.name, value, undoArgs);
                this.isDefault = false;
            },
            onPageClicked: (page) => {
                const component = projectmodel.ProjectModel.instance.getComponentWithName(page.component);
                if (component === undefined)
                    return;
                NodeGraphContext.NodeGraphContextTmp.switchToComponent(component, { pushHistory: true });
            }
        };
        const div = document.createElement('div');
        this.root = (0,client.createRoot)(div);
        this.root.render(external_react_default().createElement(Pages, props));
        this.el = $(div);
        return this.el;
    }
    dispose() {
        if (this.root) {
            this.root.unmount();
            this.root = null;
        }
        TypeView.prototype.dispose.call(this);
    }
}

;// ./src/editor/src/views/panels/propertyeditor/Pages/index.ts


// EXTERNAL MODULE: ./src/editor/src/templates/propertyeditor/aligntools.html
var aligntools = __webpack_require__(70666);
var aligntools_default = /*#__PURE__*/__webpack_require__.n(aligntools);
;// ./src/editor/src/views/panels/propertyeditor/DataTypes/AlignTools/aligntools.js




var AlignTools = function (args) {
  view_default().call(this);

  this.parent = args.parent;
  this.onUpdate = args.onUpdate;

  this.defaults = args.defaults;
  this.values = args.values;
  this.tooltip = args.tooltip;

  this.isDefault = this.checkIsDefault();

  this.bindModels();
};
AlignTools.prototype = Object.create((view_default()).prototype);

AlignTools.prototype.bindModels = function () {
  this.isVertical = this.parent.model.parameters.flexDirection !== 'row';

  this.parent.model.on('parametersChanged', (args) => {
    this.isVertical = this.parent.model.parameters.flexDirection !== 'row';
  });
};

AlignTools.prototype.dispose = function () {
  this.parent.model.off(this);
};

AlignTools.prototype.render = function () {
  var _this = this;

  // Component inputs will have output ports, and vice versa
  this.el = this.bindView($((aligntools_default())), this);

  var toolTipTimeout;
  this.$('.align-icon').on('click', function () {
    var _el = this;
    clearTimeout(toolTipTimeout);

    var comp = $(_el).attr('data-comp');
    var value = $(_el).attr('data-value');

    if (_this.values[comp] === value) {
      //un-set this value if it's clicked twice
      _this.values[comp] = undefined;
    } else {
      _this.values[comp] = value;
    }

    _this.updateState();
    _this.onUpdate(comp, _this.values[comp]);
  });

  var changedToolTipTimeout;
  this.$('.property-changed-dot')
    .on('click', function () {
      clearTimeout(changedToolTipTimeout);
      Object.keys(_this.defaults).forEach((comp) => {
        if (_this.values[comp] !== undefined) {
          _this.values[comp] = undefined;
          _this.onUpdate(comp, undefined);
        }
      });
      _this.updateState();
    })
    .on('mouseenter', function () {
      var _el = this;
      changedToolTipTimeout = setTimeout(function () {
        popuplayer_default().instance.showTooltip({
          x: $(_el).offset().left + $(_el).outerWidth(),
          y: $(_el).offset().top + $(_el).outerHeight() / 2,
          position: 'right',
          content: 'Reset to default'
        });
      }, 1000);
    })
    .on('mouseleave', function () {
      popuplayer_default().instance.hideTooltip();
    });

  this.updateState();
};

AlignTools.prototype.checkIsDefault = function () {
  return (
    this.values['horizontal'] === undefined &&
    this.values['vertical'] === undefined &&
    this.values['justify'] === undefined &&
    this.values['align-items'] === undefined &&
    this.values['justify-content'] === undefined
  );
};

AlignTools.prototype.updateState = function () {
  var _this = this;

  this.isDefault = this.checkIsDefault();

  const comps = Object.keys(this.values);
  this.$('.align-icon').each(function () {
    var _el = this;
    var comp = $(_el).attr('data-comp');
    var value = $(_el).attr('data-value');

    $(_el).removeClass('sel').removeClass('def');
    if (_this.values[comp] !== undefined) {
      if (_this.values[comp] === value) $(_el).addClass('sel');
    } else if (_this.defaults[comp] !== undefined) {
      if (_this.defaults[comp] === value) $(_el).addClass('def');
    } else if (comps.includes(comp) === false) {
      //this icon is not part of this port, hide it
      $(_el).hide();
    }
  });
};

/* harmony default export */ const AlignTools_aligntools = (AlignTools);

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/AlignTools/AlignToolsType.ts


class AlignToolsType extends TypeView {
    constructor() {
        super();
        this.defaults = {};
        this.values = {};
        this.ports = {};
    }
    static fromPort(args) {
        const p = args.port;
        const parent = args.parent;
        let toolTypeId = 'aligntools-' + p.group;
        if (p.type.alignComp === 'justify-content' ||
            p.type.alignComp === 'align-items' ||
            p.type.alignComp === 'align-content') {
            toolTypeId += '-' + p.type.alignComp;
        }
        if (!parent._toolsType[toolTypeId]) {
            const view = (parent._toolsType[toolTypeId] = new AlignToolsType());
            view.parent = parent;
            view.group = p.group;
            view.addComponentPort(p);
            return view;
        }
        else {
            parent._toolsType[toolTypeId].addComponentPort(p);
        }
    }
    render() {
        const _this = this;
        this.alignToolsView = new AlignTools_aligntools({
            values: this.values,
            defaults: this.defaults,
            parent: this.parent,
            onUpdate: function (comp, value, opts) {
                const undoArgs = {
                    undo: true,
                    label: 'alignment changed',
                    oldValue: opts ? opts.oldValue : undefined
                };
                _this.parent.model.setParameter(_this.ports[comp].name, value, undoArgs);
            }
        });
        this.alignToolsView.render();
        this.el = this.alignToolsView.el;
        return this.el;
    }
    dispose() {
        TypeView.prototype.dispose.call(this);
        this.alignToolsView.dispose();
    }
    addComponentPort(p) {
        const comp = p.type.alignComp;
        this.ports[comp] = p;
        const value = this.parent.model.parameters[p.name];
        this.values[comp] = value;
        this.defaults[comp] = p.default;
    }
}

// EXTERNAL MODULE: ./src/editor/src/models/ExpressionParameter.ts
var ExpressionParameter = __webpack_require__(52034);
// EXTERNAL MODULE: ./src/editor/src/utils/ParameterValueResolver.ts
var ParameterValueResolver = __webpack_require__(87934);
// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelInput/index.ts + 21 modules
var PropertyPanelInput = __webpack_require__(83431);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/propertyeditor/ExpressionEditorModal/ExpressionEditorModal.module.scss
var ExpressionEditorModal_module = __webpack_require__(23438);
;// ./src/editor/src/views/panels/propertyeditor/ExpressionEditorModal/ExpressionEditorModal.module.scss

      
      
      
      
      
      
      
      
      

var ExpressionEditorModal_module_options = {};

ExpressionEditorModal_module_options.styleTagTransform = (styleTagTransform_default());
ExpressionEditorModal_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ExpressionEditorModal_module_options.insert = insertBySelector_default().bind(null, "head");
    
ExpressionEditorModal_module_options.domAPI = (styleDomAPI_default());
ExpressionEditorModal_module_options.insertStyleElement = (insertStyleElement_default());

var ExpressionEditorModal_module_update = injectStylesIntoStyleTag_default()(ExpressionEditorModal_module/* default */.A, ExpressionEditorModal_module_options);




       /* harmony default export */ const ExpressionEditorModal_ExpressionEditorModal_module = (ExpressionEditorModal_module/* default */.A && ExpressionEditorModal_module/* default */.A.locals ? ExpressionEditorModal_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/propertyeditor/ExpressionEditorModal/ExpressionEditorModal.tsx
/**
 * ExpressionEditorModal
 *
 * A modal dialog for editing expressions in a full-featured code editor.
 * Uses the new CodeMirror-based JavaScriptEditor component.
 */






/**
 * Modal for editing expressions in a larger code editor
 */
function ExpressionEditorModal({ isOpen, propertyName, expression, onApply, onClose }) {
    const [localExpression, setLocalExpression] = (0,external_react_.useState)(expression);
    // Reset local expression when modal opens with new value
    (0,external_react_.useEffect)(() => {
        if (isOpen) {
            setLocalExpression(expression);
        }
    }, [isOpen, expression]);
    // Handle keyboard shortcuts
    const handleKeyDown = (0,external_react_.useCallback)((e) => {
        if (!isOpen)
            return;
        if (e.key === 'Escape') {
            onClose();
        }
    }, [isOpen, onClose]);
    (0,external_react_.useEffect)(() => {
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [handleKeyDown]);
    const handleApply = (0,external_react_.useCallback)(() => {
        onApply(localExpression);
        onClose();
    }, [localExpression, onApply, onClose]);
    const handleCancel = (0,external_react_.useCallback)(() => {
        onClose();
    }, [onClose]);
    // Handle Ctrl+Enter to apply
    const handleSave = (0,external_react_.useCallback)((code) => {
        onApply(code);
        onClose();
    }, [onApply, onClose]);
    if (!isOpen)
        return null;
    // Render into portal to escape any z-index issues
    return external_react_dom_default().createPortal(external_react_default().createElement("div", { className: ExpressionEditorModal_ExpressionEditorModal_module['Overlay'], onClick: handleCancel },
        external_react_default().createElement("div", { className: ExpressionEditorModal_ExpressionEditorModal_module['Modal'], onClick: (e) => e.stopPropagation() },
            external_react_default().createElement("div", { className: ExpressionEditorModal_ExpressionEditorModal_module['Header'] },
                external_react_default().createElement("span", { className: ExpressionEditorModal_ExpressionEditorModal_module['Title'] },
                    "Edit Expression: ",
                    propertyName)),
            external_react_default().createElement("div", { className: ExpressionEditorModal_ExpressionEditorModal_module['Body'] },
                external_react_default().createElement("div", { className: ExpressionEditorModal_ExpressionEditorModal_module['HelpText'] },
                    external_react_default().createElement(typography_Text/* Text */.EY, null,
                        "Available: ",
                        external_react_default().createElement("code", null, "Noodl.Variables.x"),
                        ", ",
                        external_react_default().createElement("code", null, "Noodl.Objects.id.prop"),
                        ",",
                        ' ',
                        external_react_default().createElement("code", null, "Noodl.Arrays.id"),
                        ", and Math functions like ",
                        external_react_default().createElement("code", null, "min()"),
                        ", ",
                        external_react_default().createElement("code", null, "max()"),
                        ",",
                        ' ',
                        external_react_default().createElement("code", null, "round()"))),
                external_react_default().createElement("div", { className: ExpressionEditorModal_ExpressionEditorModal_module['EditorWrapper'] },
                    external_react_default().createElement(JavaScriptEditor, { value: localExpression, onChange: setLocalExpression, onSave: handleSave, validationType: "expression", height: 300, width: "100%", placeholder: "// Enter your expression here, e.g. Noodl.Variables.count * 2" }))),
            external_react_default().createElement("div", { className: ExpressionEditorModal_ExpressionEditorModal_module['Footer'] },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Ghost, onClick: handleCancel }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Apply", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Cta, onClick: handleApply })))), document.body);
}

;// ./src/editor/src/views/panels/propertyeditor/ExpressionEditorModal/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/PropertyPanelInputWithExpressionModal.tsx
/**
 * PropertyPanelInputWithExpressionModal
 *
 * Wraps PropertyPanelInput with ExpressionEditorModal state management.
 * Used by BasicType.ts to provide expression modal support.
 */



function PropertyPanelInputWithExpressionModal({ propertyName, label, expression = '', expressionMode, onExpressionChange, ...props }) {
    const [isModalOpen, setIsModalOpen] = (0,external_react_.useState)(false);
    const handleExpand = (0,external_react_.useCallback)(() => {
        setIsModalOpen(true);
    }, []);
    const handleModalClose = (0,external_react_.useCallback)(() => {
        setIsModalOpen(false);
    }, []);
    const handleModalApply = (0,external_react_.useCallback)((newExpression) => {
        if (onExpressionChange) {
            onExpressionChange(newExpression);
        }
    }, [onExpressionChange]);
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(PropertyPanelInput/* PropertyPanelInput */.mR, { label: label, expression: expression, expressionMode: expressionMode, onExpressionChange: onExpressionChange, onExpressionExpand: handleExpand, ...props }),
        external_react_default().createElement(ExpressionEditorModal, { isOpen: isModalOpen, propertyName: propertyName || label, expression: expression, onApply: handleModalApply, onClose: handleModalClose })));
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/BasicType.ts









function firstType(type) {
    return nodelibrary/* NodeLibrary */.m.nameForPortType(type);
}
function mapTypeToInputType(type) {
    switch (type) {
        case 'number':
            return PropertyPanelInput/* PropertyPanelInputType */.A2.Number;
        case 'string':
        default:
            return PropertyPanelInput/* PropertyPanelInputType */.A2.Text;
    }
}
class BasicType extends TypeView {
    constructor() {
        super(...arguments);
        this.root = null;
    }
    static fromPort(args) {
        const view = new BasicType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.tooltip = p.tooltip;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        // Create container for React component
        const div = document.createElement('div');
        div.style.width = '100%';
        if (!this.root) {
            this.root = (0,client.createRoot)(div);
        }
        this.renderReact();
        this.el = div;
        return this.el;
    }
    renderReact() {
        if (!this.root)
            return;
        const paramValue = this.parent.model.getParameter(this.name);
        const isExprMode = (0,ExpressionParameter/* isExpressionParameter */.UC)(paramValue);
        // Get display value - MUST be a primitive, never an object
        // Use ParameterValueResolver to defensively handle any value type,
        // including expression objects that might slip through during state transitions
        const rawValue = isExprMode ? paramValue.fallback : paramValue;
        const displayValue = ParameterValueResolver/* ParameterValueResolver */.L.toString(rawValue);
        const props = {
            label: this.displayName,
            value: displayValue,
            inputType: mapTypeToInputType(firstType(this.type)),
            properties: undefined, // No special properties needed for basic types
            isChanged: !this.isDefault,
            isConnected: this.isConnected,
            onChange: (value) => {
                // Handle standard value change
                if (firstType(this.type) === 'number') {
                    const numValue = parseFloat(String(value));
                    this.parent.setParameter(this.name, isNaN(numValue) ? undefined : numValue, {
                        undo: true,
                        label: `change ${this.displayName}`
                    });
                }
                else {
                    this.parent.setParameter(this.name, value, {
                        undo: true,
                        label: `change ${this.displayName}`
                    });
                }
                this.isDefault = false;
            },
            // Expression support
            supportsExpression: true,
            expressionMode: isExprMode ? 'expression' : 'fixed',
            expression: isExprMode ? paramValue.expression : '',
            onExpressionModeChange: (mode) => {
                const currentParam = this.parent.model.getParameter(this.name);
                if (mode === 'expression') {
                    // Convert to expression parameter
                    const currentValue = (0,ExpressionParameter/* isExpressionParameter */.UC)(currentParam) ? currentParam.fallback : currentParam;
                    const exprParam = (0,ExpressionParameter/* createExpressionParameter */.KV)(String(currentValue || ''), currentValue, 1);
                    this.parent.setParameter(this.name, exprParam, {
                        undo: true,
                        label: `enable expression for ${this.displayName}`
                    });
                }
                else {
                    // Convert back to fixed value
                    const fixedValue = (0,ExpressionParameter/* isExpressionParameter */.UC)(currentParam) ? currentParam.fallback : currentParam;
                    this.parent.setParameter(this.name, fixedValue, {
                        undo: true,
                        label: `disable expression for ${this.displayName}`
                    });
                }
                this.isDefault = false;
                // Re-render to update UI
                setTimeout(() => this.renderReact(), 0);
            },
            onExpressionChange: (expression) => {
                const currentParam = this.parent.model.getParameter(this.name);
                if ((0,ExpressionParameter/* isExpressionParameter */.UC)(currentParam)) {
                    // Update the expression
                    this.parent.setParameter(this.name, {
                        ...currentParam,
                        expression
                    }, {
                        undo: true,
                        label: `change ${this.displayName} expression`
                    });
                }
                this.isDefault = false;
                // Re-render to update UI and sync modal with inline input
                setTimeout(() => this.renderReact(), 0);
            }
        };
        this.root.render(external_react_default().createElement(PropertyPanelInputWithExpressionModal, props));
    }
    dispose() {
        if (this.root) {
            this.root.unmount();
            this.root = null;
        }
        super.dispose();
    }
    // Legacy method kept for compatibility
    onPropertyChanged(scope, el) {
        if (firstType(scope.type) === 'number') {
            const value = parseFloat(el.val());
            this.parent.setParameter(scope.name, isNaN(value) ? undefined : value);
        }
        else {
            this.parent.setParameter(scope.name, el.val());
        }
        const current = this.getCurrentValue();
        el.val(current.value);
        this.isDefault = current.isDefault;
        el.blur();
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/BooleanType.ts


class BooleanType extends TypeView {
    static fromPort(args) {
        const view = new BooleanType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.tooltip = p.tooltip;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        this.el = this.bindView(this.parent.cloneTemplate('boolean'), this);
        TypeView.prototype.render.call(this);
        return this.el;
    }
    onBoxClicked(scope, el) {
        this.value = !this.value;
        this.parent.setParameter(this.name, this.value);
        const current = this.getCurrentValue();
        this.isDefault = current.isDefault;
    }
    resetToDefault() {
        this.value = this.getCurrentValue().value;
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/ByobFilterBuilder.module.scss
var ByobFilterBuilder_module = __webpack_require__(80953);
;// ./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/ByobFilterBuilder.module.scss

      
      
      
      
      
      
      
      
      

var ByobFilterBuilder_module_options = {};

ByobFilterBuilder_module_options.styleTagTransform = (styleTagTransform_default());
ByobFilterBuilder_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ByobFilterBuilder_module_options.insert = insertBySelector_default().bind(null, "head");
    
ByobFilterBuilder_module_options.domAPI = (styleDomAPI_default());
ByobFilterBuilder_module_options.insertStyleElement = (insertStyleElement_default());

var ByobFilterBuilder_module_update = injectStylesIntoStyleTag_default()(ByobFilterBuilder_module/* default */.A, ByobFilterBuilder_module_options);




       /* harmony default export */ const ByobFilterBuilder_ByobFilterBuilder_module = (ByobFilterBuilder_module/* default */.A && ByobFilterBuilder_module/* default */.A.locals ? ByobFilterBuilder_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/types.ts
/**
 * BYOB Filter Builder Types
 *
 * Data models for the visual filter builder that generates
 * Directus-compatible filter JSON.
 */
/**
 * Type guard to check if item is a group
 */
function types_isFilterGroup(item) {
    return 'type' in item && (item.type === 'and' || item.type === 'or');
}
/**
 * Create an empty filter group
 */
function createEmptyFilterGroup() {
    return {
        id: types_generateId(),
        type: 'and',
        conditions: []
    };
}
/**
 * Create an empty filter condition
 */
function createEmptyCondition() {
    return {
        id: types_generateId(),
        field: '',
        operator: '_eq',
        value: ''
    };
}
/**
 * Generate a unique ID
 */
function types_generateId() {
    return Math.random().toString(36).substring(2, 11);
}
/**
 * Count total conditions and groups in a filter
 */
function countFilterItems(group) {
    if (!group) {
        return { conditions: 0, groups: 0 };
    }
    let conditions = 0;
    let groups = 0;
    function countRecursive(item) {
        if (types_isFilterGroup(item)) {
            groups++;
            item.conditions.forEach(countRecursive);
        }
        else {
            // Only count conditions that have a field selected
            if (item.field) {
                conditions++;
            }
        }
    }
    // Count the root group
    group.conditions.forEach(countRecursive);
    return { conditions, groups };
}
/**
 * Generate a human-readable summary of the filter
 */
function getFilterSummary(group) {
    if (!group) {
        return 'No filter';
    }
    const { conditions, groups } = countFilterItems(group);
    if (conditions === 0 && groups === 0) {
        return 'No filter';
    }
    const parts = [];
    if (conditions > 0) {
        parts.push(`${conditions} condition${conditions !== 1 ? 's' : ''}`);
    }
    if (groups > 0) {
        parts.push(`${groups} group${groups !== 1 ? 's' : ''}`);
    }
    return parts.join(', ');
}

;// ./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/DragContext.tsx
/**
 * Drag Context for Filter Builder
 *
 * Provides drag & drop state management for moving groups between parents.
 */


const DragContext = (0,external_react_.createContext)({
    dragState: { draggedItem: null, sourceGroupId: null },
    setDraggedItem: () => { },
    moveItem: () => { },
    rootFilter: null,
    setRootFilter: () => { },
    onFilterChange: null
});
function useDragContext() {
    return (0,external_react_.useContext)(DragContext);
}
function DragProvider({ children, rootFilter, onFilterChange }) {
    const [dragState, setDragState] = (0,external_react_.useState)({
        draggedItem: null,
        sourceGroupId: null
    });
    const setDraggedItem = (0,external_react_.useCallback)((item, sourceGroupId) => {
        setDragState({ draggedItem: item, sourceGroupId });
    }, []);
    /**
     * Find a group by ID in the filter tree
     */
    const findGroupById = (0,external_react_.useCallback)((id, group) => {
        if (!group)
            return null;
        if (group.id === id)
            return group;
        for (const item of group.conditions) {
            if (types_isFilterGroup(item)) {
                const found = findGroupById(id, item);
                if (found)
                    return found;
            }
        }
        return null;
    }, []);
    /**
     * Remove an item from a group by ID (returns new filter)
     */
    const removeItemFromTree = (0,external_react_.useCallback)((filter, itemId) => {
        return {
            ...filter,
            conditions: filter.conditions
                .filter((item) => item.id !== itemId)
                .map((item) => {
                if (types_isFilterGroup(item)) {
                    return removeItemFromTree(item, itemId);
                }
                return item;
            })
        };
    }, []);
    /**
     * Add an item to a group by ID (returns new filter)
     */
    const addItemToGroup = (0,external_react_.useCallback)((filter, targetGroupId, item) => {
        if (filter.id === targetGroupId) {
            return {
                ...filter,
                conditions: [...filter.conditions, item]
            };
        }
        return {
            ...filter,
            conditions: filter.conditions.map((cond) => {
                if (types_isFilterGroup(cond)) {
                    return addItemToGroup(cond, targetGroupId, item);
                }
                return cond;
            })
        };
    }, []);
    /**
     * Check if targetId is a descendant of sourceId (prevent circular nesting)
     */
    const isDescendant = (0,external_react_.useCallback)((sourceGroup, targetId) => {
        for (const item of sourceGroup.conditions) {
            if (item.id === targetId)
                return true;
            if (types_isFilterGroup(item) && isDescendant(item, targetId))
                return true;
        }
        return false;
    }, []);
    /**
     * Move the dragged item to a target group
     */
    const moveItem = (0,external_react_.useCallback)((targetGroupId) => {
        if (!dragState.draggedItem || !rootFilter || !onFilterChange)
            return;
        // Can't drop on itself
        if (dragState.draggedItem.id === targetGroupId)
            return;
        // Can't drop on the same parent
        if (dragState.sourceGroupId === targetGroupId)
            return;
        // If dragging a group, can't drop into a descendant (circular nesting)
        if (types_isFilterGroup(dragState.draggedItem)) {
            if (isDescendant(dragState.draggedItem, targetGroupId)) {
                console.warn('[DragContext] Cannot drop a group into its own descendant');
                return;
            }
        }
        // Perform the move
        let newFilter = removeItemFromTree(rootFilter, dragState.draggedItem.id);
        newFilter = addItemToGroup(newFilter, targetGroupId, dragState.draggedItem);
        onFilterChange(newFilter);
        setDragState({ draggedItem: null, sourceGroupId: null });
    }, [dragState, rootFilter, onFilterChange, removeItemFromTree, addItemToGroup, isDescendant]);
    const contextValue = {
        dragState,
        setDraggedItem,
        moveItem,
        rootFilter,
        setRootFilter: () => { }, // Not used directly
        onFilterChange
    };
    return external_react_default().createElement(DragContext.Provider, { value: contextValue }, children);
}

;// ../noodl-core-ui/src/components/popups/ConfirmationDialog/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/operators.ts
/**
 * BYOB Filter Operators
 *
 * Defines available operators for each field type with human-readable labels.
 */
/**
 * All available operators with their definitions
 */
const ALL_OPERATORS = {
    // Equality
    _eq: { value: '_eq', label: 'equals', description: 'Exact match', valueCount: 1 },
    _neq: { value: '_neq', label: 'does not equal', description: 'Not equal', valueCount: 1 },
    // Comparison
    _gt: { value: '_gt', label: 'greater than', description: 'Greater than', valueCount: 1 },
    _gte: { value: '_gte', label: 'greater than or equal', description: 'Greater than or equal', valueCount: 1 },
    _lt: { value: '_lt', label: 'less than', description: 'Less than', valueCount: 1 },
    _lte: { value: '_lte', label: 'less than or equal', description: 'Less than or equal', valueCount: 1 },
    // String
    _contains: { value: '_contains', label: 'contains', description: 'Contains substring', valueCount: 1 },
    _ncontains: { value: '_ncontains', label: 'does not contain', description: 'Does not contain', valueCount: 1 },
    _icontains: {
        value: '_icontains',
        label: 'contains (case-insensitive)',
        description: 'Contains (case-insensitive)',
        valueCount: 1
    },
    _starts_with: { value: '_starts_with', label: 'starts with', description: 'Starts with', valueCount: 1 },
    _nstarts_with: {
        value: '_nstarts_with',
        label: 'does not start with',
        description: 'Does not start with',
        valueCount: 1
    },
    _istarts_with: {
        value: '_istarts_with',
        label: 'starts with (case-insensitive)',
        description: 'Starts with (case-insensitive)',
        valueCount: 1
    },
    _ends_with: { value: '_ends_with', label: 'ends with', description: 'Ends with', valueCount: 1 },
    _nends_with: { value: '_nends_with', label: 'does not end with', description: 'Does not end with', valueCount: 1 },
    _iends_with: {
        value: '_iends_with',
        label: 'ends with (case-insensitive)',
        description: 'Ends with (case-insensitive)',
        valueCount: 1
    },
    // Array/In
    _in: { value: '_in', label: 'is one of', description: 'Value is in list', valueCount: 1 },
    _nin: { value: '_nin', label: 'is not one of', description: 'Value is not in list', valueCount: 1 },
    // Null
    _null: { value: '_null', label: 'is null', description: 'Is null', valueCount: 0 },
    _nnull: { value: '_nnull', label: 'is not null', description: 'Is not null', valueCount: 0 },
    // Between
    _between: { value: '_between', label: 'is between', description: 'Between two values', valueCount: 2 },
    _nbetween: { value: '_nbetween', label: 'is not between', description: 'Not between two values', valueCount: 2 },
    // Empty
    _empty: { value: '_empty', label: 'is empty', description: 'Is empty string or array', valueCount: 0 },
    _nempty: { value: '_nempty', label: 'is not empty', description: 'Is not empty', valueCount: 0 },
    // Regex
    _regex: { value: '_regex', label: 'matches regex', description: 'Matches regular expression', valueCount: 1 }
};
/**
 * Operators available for each field type
 */
const OPERATORS_BY_TYPE = {
    // String types - full text operators
    string: [
        '_eq',
        '_neq',
        '_contains',
        '_ncontains',
        '_icontains',
        '_starts_with',
        '_nstarts_with',
        '_istarts_with',
        '_ends_with',
        '_nends_with',
        '_iends_with',
        '_in',
        '_nin',
        '_null',
        '_nnull',
        '_empty',
        '_nempty',
        '_regex'
    ],
    text: [
        '_eq',
        '_neq',
        '_contains',
        '_ncontains',
        '_icontains',
        '_starts_with',
        '_nstarts_with',
        '_ends_with',
        '_nends_with',
        '_null',
        '_nnull',
        '_empty',
        '_nempty',
        '_regex'
    ],
    // Numeric types - comparison operators
    integer: ['_eq', '_neq', '_gt', '_gte', '_lt', '_lte', '_in', '_nin', '_between', '_nbetween', '_null', '_nnull'],
    float: ['_eq', '_neq', '_gt', '_gte', '_lt', '_lte', '_in', '_nin', '_between', '_nbetween', '_null', '_nnull'],
    decimal: ['_eq', '_neq', '_gt', '_gte', '_lt', '_lte', '_in', '_nin', '_between', '_nbetween', '_null', '_nnull'],
    // Boolean - simple equality
    boolean: ['_eq', '_neq', '_null', '_nnull'],
    // Date/Time types - comparison and between
    date: ['_eq', '_neq', '_gt', '_gte', '_lt', '_lte', '_between', '_nbetween', '_null', '_nnull'],
    datetime: ['_eq', '_neq', '_gt', '_gte', '_lt', '_lte', '_between', '_nbetween', '_null', '_nnull'],
    time: ['_eq', '_neq', '_gt', '_gte', '_lt', '_lte', '_between', '_nbetween', '_null', '_nnull'],
    timestamp: ['_eq', '_neq', '_gt', '_gte', '_lt', '_lte', '_between', '_nbetween', '_null', '_nnull'],
    // UUID - equality and null
    uuid: ['_eq', '_neq', '_in', '_nin', '_null', '_nnull'],
    // JSON - limited operators
    json: ['_null', '_nnull', '_empty', '_nempty'],
    // CSV - limited operators
    csv: ['_contains', '_ncontains', '_null', '_nnull', '_empty', '_nempty'],
    // Hash - equality only
    hash: ['_eq', '_neq', '_null', '_nnull'],
    // Alias - depends on target, default to string-like
    alias: ['_eq', '_neq', '_null', '_nnull'],
    // Unknown - basic operators
    unknown: ['_eq', '_neq', '_null', '_nnull']
};
/**
 * Get available operators for a field type
 */
function getOperatorsForType(type) {
    const operatorKeys = OPERATORS_BY_TYPE[type] || OPERATORS_BY_TYPE.unknown;
    return operatorKeys.map((key) => ALL_OPERATORS[key]);
}
/**
 * Get operator definition by value
 */
function getOperatorDefinition(operator) {
    return ALL_OPERATORS[operator] || ALL_OPERATORS._eq;
}
/**
 * Get a friendly display label for an operator
 */
function getOperatorLabel(operator) {
    var _a;
    return ((_a = ALL_OPERATORS[operator]) === null || _a === void 0 ? void 0 : _a.label) || operator;
}
/**
 * Check if operator requires a value input
 */
function operatorNeedsValue(operator) {
    const def = ALL_OPERATORS[operator];
    return def ? def.valueCount > 0 : true;
}
/**
 * Check if operator requires two values (between)
 */
function operatorNeedsTwoValues(operator) {
    const def = ALL_OPERATORS[operator];
    return def ? def.valueCount === 2 : false;
}

;// ./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/FilterCondition.tsx
/**
 * FilterCondition Component
 *
 * A single filter condition row: Field | Operator | Value
 * Supports drag & drop to move conditions between groups.
 */









function FilterCondition({ condition, fields, onChange, onDelete, parentGroupId }) {
    var _a, _b;
    const { dragState, setDraggedItem } = useDragContext();
    const [isDragging, setIsDragging] = (0,external_react_.useState)(false);
    // Is this condition being dragged?
    const isBeingDragged = ((_a = dragState.draggedItem) === null || _a === void 0 ? void 0 : _a.id) === condition.id;
    // Drag handlers
    const handleDragStart = (0,external_react_.useCallback)((e) => {
        e.stopPropagation();
        setDraggedItem(condition, parentGroupId || null);
        setIsDragging(true);
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/plain', condition.id);
    }, [condition, parentGroupId, setDraggedItem]);
    const handleDragEnd = (0,external_react_.useCallback)((e) => {
        e.stopPropagation();
        setDraggedItem(null, null);
        setIsDragging(false);
    }, [setDraggedItem]);
    // Get the selected field's type
    const selectedField = (0,external_react_.useMemo)(() => {
        return fields.find((f) => f.name === condition.field);
    }, [fields, condition.field]);
    const fieldType = (selectedField === null || selectedField === void 0 ? void 0 : selectedField.type) || 'string';
    // Get available operators for this field type
    const availableOperators = (0,external_react_.useMemo)(() => {
        return getOperatorsForType(fieldType);
    }, [fieldType]);
    // Handle field change
    const handleFieldChange = (0,external_react_.useCallback)((value) => {
        const newField = fields.find((f) => f.name === value);
        const newType = (newField === null || newField === void 0 ? void 0 : newField.type) || 'string';
        // Reset operator if not valid for new type
        const newOperators = getOperatorsForType(newType);
        const isOperatorValid = newOperators.some((op) => op.value === condition.operator);
        onChange({
            ...condition,
            field: value,
            operator: isOperatorValid ? condition.operator : '_eq',
            value: '' // Reset value when field changes
        });
    }, [condition, fields, onChange]);
    // Handle operator change
    const handleOperatorChange = (0,external_react_.useCallback)((value) => {
        const newOperator = value;
        const needsValue = operatorNeedsValue(newOperator);
        const needsTwoValues = operatorNeedsTwoValues(newOperator);
        let newValue = condition.value;
        // Reset value based on operator requirements
        if (!needsValue) {
            newValue = null;
        }
        else if (needsTwoValues && !Array.isArray(condition.value)) {
            newValue = ['', ''];
        }
        else if (!needsTwoValues && Array.isArray(condition.value)) {
            newValue = '';
        }
        onChange({
            ...condition,
            operator: newOperator,
            value: newValue
        });
    }, [condition, onChange]);
    // Handle value change
    const handleValueChange = (0,external_react_.useCallback)((value) => {
        onChange({
            ...condition,
            value: value
        });
    }, [condition, onChange]);
    // Handle between value changes
    const handleBetweenValueChange = (0,external_react_.useCallback)((index, value) => {
        const currentValue = Array.isArray(condition.value) ? condition.value : ['', ''];
        const newValue = [...currentValue];
        newValue[index] = value;
        onChange({
            ...condition,
            value: newValue
        });
    }, [condition, onChange]);
    const needsValue = operatorNeedsValue(condition.operator);
    const needsTwoValues = operatorNeedsTwoValues(condition.operator);
    // Field options for dropdown
    const fieldOptions = (0,external_react_.useMemo)(() => {
        return [
            { label: '(Select field)', value: '' },
            ...fields.map((f) => ({
                label: f.displayName || f.name,
                value: f.name
            }))
        ];
    }, [fields]);
    // Operator options for dropdown
    const operatorOptions = (0,external_react_.useMemo)(() => {
        return availableOperators.map((op) => ({
            label: op.label,
            value: op.value
        }));
    }, [availableOperators]);
    // Build class names
    const conditionClassName = [ByobFilterBuilder_ByobFilterBuilder_module.FilterCondition, isBeingDragged || isDragging ? ByobFilterBuilder_ByobFilterBuilder_module.FilterConditionDragging : '']
        .filter(Boolean)
        .join(' ');
    return (external_react_default().createElement(Box/* Box */.a, { hasXSpacing: 1, hasYSpacing: 1, UNSAFE_className: conditionClassName },
        external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterConditionFields },
            external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterConditionDragHandle, draggable: true, onDragStart: handleDragStart, onDragEnd: handleDragEnd, title: "Drag to move into another group" },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Grip, size: common_Icon/* IconSize */.lK.Small })),
            external_react_default().createElement(Select, { value: condition.field, options: fieldOptions, onChange: handleFieldChange, colorTheme: SelectColorTheme.Dark, UNSAFE_className: ByobFilterBuilder_ByobFilterBuilder_module.FilterConditionField }),
            external_react_default().createElement(Select, { value: condition.operator, options: operatorOptions, onChange: handleOperatorChange, colorTheme: SelectColorTheme.Dark, UNSAFE_className: ByobFilterBuilder_ByobFilterBuilder_module.FilterConditionOperator }),
            needsValue && !needsTwoValues && (external_react_default().createElement(TextInput, { value: String((_b = condition.value) !== null && _b !== void 0 ? _b : ''), onChange: (e) => handleValueChange(e.target.value), placeholder: "Value", UNSAFE_className: ByobFilterBuilder_ByobFilterBuilder_module.FilterConditionValue })),
            needsTwoValues && (external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement(TextInput, { value: String(Array.isArray(condition.value) ? condition.value[0] : ''), onChange: (e) => handleBetweenValueChange(0, e.target.value), placeholder: "From", UNSAFE_className: ByobFilterBuilder_ByobFilterBuilder_module.FilterConditionValueSmall }),
                external_react_default().createElement("span", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterConditionBetweenLabel }, "and"),
                external_react_default().createElement(TextInput, { value: String(Array.isArray(condition.value) ? condition.value[1] : ''), onChange: (e) => handleBetweenValueChange(1, e.target.value), placeholder: "To", UNSAFE_className: ByobFilterBuilder_ByobFilterBuilder_module.FilterConditionValueSmall }))),
            external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Trash, size: common_Icon/* IconSize */.lK.Small, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: onDelete, UNSAFE_className: ByobFilterBuilder_ByobFilterBuilder_module.FilterConditionDelete }))));
}

;// ./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/FilterGroup.tsx
/**
 * FilterGroup Component
 *
 * A recursive AND/OR group container for filter conditions.
 * Supports unlimited nesting of groups via drag & drop.
 */










function FilterGroup({ group, fields, onChange, onDelete, isRoot = false, depth = 0, parentGroupId }) {
    var _a;
    const { dragState, setDraggedItem, moveItem } = useDragContext();
    const [isDragOver, setIsDragOver] = (0,external_react_.useState)(false);
    // Delete confirmation state
    const [pendingDeleteIndex, setPendingDeleteIndex] = (0,external_react_.useState)(null);
    const [showDeleteConfirm, setShowDeleteConfirm] = (0,external_react_.useState)(false);
    // Is this group being dragged?
    const isDragging = ((_a = dragState.draggedItem) === null || _a === void 0 ? void 0 : _a.id) === group.id;
    // Can this group accept a drop?
    const canAcceptDrop = dragState.draggedItem !== null && dragState.draggedItem.id !== group.id && dragState.sourceGroupId !== group.id;
    // Toggle between AND/OR
    const handleToggleCombinator = (0,external_react_.useCallback)(() => {
        const newType = group.type === 'and' ? 'or' : 'and';
        onChange({
            ...group,
            type: newType
        });
    }, [group, onChange]);
    // Add a new condition
    const handleAddCondition = (0,external_react_.useCallback)(() => {
        const newCondition = createEmptyCondition();
        onChange({
            ...group,
            conditions: [...group.conditions, newCondition]
        });
    }, [group, onChange]);
    // Add a nested group
    const handleAddGroup = (0,external_react_.useCallback)(() => {
        const newGroup = {
            id: types_generateId(),
            type: group.type === 'and' ? 'or' : 'and', // Opposite type for variety
            conditions: []
        };
        onChange({
            ...group,
            conditions: [...group.conditions, newGroup]
        });
    }, [group, onChange]);
    // Update a condition
    const handleConditionChange = (0,external_react_.useCallback)((index, updatedItem) => {
        const newConditions = [...group.conditions];
        newConditions[index] = updatedItem;
        onChange({
            ...group,
            conditions: newConditions
        });
    }, [group, onChange]);
    // Helper to count total items in a group (recursively)
    const countGroupItems = (0,external_react_.useCallback)((g) => {
        let count = g.conditions.length;
        for (const item of g.conditions) {
            if (types_isFilterGroup(item)) {
                count += countGroupItems(item);
            }
        }
        return count;
    }, []);
    // Delete a condition - checks if it's a group with children and shows confirmation
    const handleRequestDelete = (0,external_react_.useCallback)((index) => {
        const item = group.conditions[index];
        // If it's a group with children, show confirmation
        if (types_isFilterGroup(item) && item.conditions.length > 0) {
            setPendingDeleteIndex(index);
            setShowDeleteConfirm(true);
        }
        else {
            // Delete directly (single condition or empty group)
            const newConditions = group.conditions.filter((_, i) => i !== index);
            onChange({
                ...group,
                conditions: newConditions
            });
        }
    }, [group, onChange]);
    // Confirm deletion of a group with children
    const handleConfirmDelete = (0,external_react_.useCallback)(() => {
        if (pendingDeleteIndex !== null) {
            const newConditions = group.conditions.filter((_, i) => i !== pendingDeleteIndex);
            onChange({
                ...group,
                conditions: newConditions
            });
        }
        setPendingDeleteIndex(null);
        setShowDeleteConfirm(false);
    }, [group, onChange, pendingDeleteIndex]);
    // Cancel deletion
    const handleCancelDelete = (0,external_react_.useCallback)(() => {
        setPendingDeleteIndex(null);
        setShowDeleteConfirm(false);
    }, []);
    // Get info about pending delete item for the confirmation message
    const getPendingDeleteInfo = (0,external_react_.useCallback)(() => {
        if (pendingDeleteIndex === null)
            return { count: 0 };
        const item = group.conditions[pendingDeleteIndex];
        if (types_isFilterGroup(item)) {
            return { count: countGroupItems(item) };
        }
        return { count: 0 };
    }, [pendingDeleteIndex, group.conditions, countGroupItems]);
    // Drag handlers
    const handleDragStart = (0,external_react_.useCallback)((e) => {
        e.stopPropagation();
        setDraggedItem(group, parentGroupId || null);
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/plain', group.id);
    }, [group, parentGroupId, setDraggedItem]);
    const handleDragEnd = (0,external_react_.useCallback)((e) => {
        e.stopPropagation();
        setDraggedItem(null, null);
        setIsDragOver(false);
    }, [setDraggedItem]);
    const handleDragOver = (0,external_react_.useCallback)((e) => {
        e.preventDefault();
        e.stopPropagation();
        if (canAcceptDrop) {
            e.dataTransfer.dropEffect = 'move';
            setIsDragOver(true);
        }
    }, [canAcceptDrop]);
    const handleDragLeave = (0,external_react_.useCallback)((e) => {
        e.stopPropagation();
        setIsDragOver(false);
    }, []);
    const handleDrop = (0,external_react_.useCallback)((e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(false);
        if (canAcceptDrop) {
            moveItem(group.id);
        }
    }, [canAcceptDrop, group.id, moveItem]);
    const hasConditions = group.conditions.length > 0;
    // Build class names
    const groupClassName = [
        ByobFilterBuilder_ByobFilterBuilder_module.FilterGroup,
        isRoot ? ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupRoot : '',
        isDragging ? ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupDragging : '',
        isDragOver && canAcceptDrop ? ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupDragOver : ''
    ]
        .filter(Boolean)
        .join(' ');
    const deleteInfo = getPendingDeleteInfo();
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement("div", { className: groupClassName, "data-depth": depth, onDragOver: handleDragOver, onDragLeave: handleDragLeave, onDrop: handleDrop },
            external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupHeader },
                external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupHeaderLeft },
                    !isRoot && (external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupDragHandle, draggable: true, onDragStart: handleDragStart, onDragEnd: handleDragEnd, title: "Drag to move into another group" },
                        external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Grip, size: common_Icon/* IconSize */.lK.Small }))),
                    external_react_default().createElement("button", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupCombinator, onClick: handleToggleCombinator, type: "button" }, group.type.toUpperCase())),
                !isRoot && onDelete && (external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Close, size: common_Icon/* IconSize */.lK.Small, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: onDelete, UNSAFE_className: ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupDelete }))),
            isDragOver && canAcceptDrop && (external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupDropIndicator }, "Drop here to nest inside this group")),
            external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupConditions },
                group.conditions.map((item, index) => (external_react_default().createElement((external_react_default()).Fragment, { key: item.id },
                    index > 0 && external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupCombinatorLabel }, group.type.toUpperCase()),
                    types_isFilterGroup(item) ? (
                    // Nested group
                    external_react_default().createElement(FilterGroup, { group: item, fields: fields, onChange: (updated) => handleConditionChange(index, updated), onDelete: () => handleRequestDelete(index), depth: depth + 1, parentGroupId: group.id })) : (
                    // Single condition
                    external_react_default().createElement(FilterCondition, { condition: item, fields: fields, onChange: (updated) => handleConditionChange(index, updated), onDelete: () => handleRequestDelete(index), parentGroupId: group.id }))))),
                !hasConditions && (external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupEmpty }, "No conditions. Add a filter rule to get started."))),
            external_react_default().createElement(Box/* Box */.a, { hasXSpacing: 1, hasYSpacing: 1 },
                external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterGroupActions },
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Add Condition", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, onClick: handleAddCondition }),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Add Group", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, onClick: handleAddGroup })))),
        external_react_default().createElement(ConfirmationDialog, { isVisible: showDeleteConfirm, title: "Delete Group?", message: `This group contains ${deleteInfo.count} item${deleteInfo.count !== 1 ? 's' : ''} (conditions and/or nested groups). Deleting this group will also delete all items inside it. This action cannot be undone.`, confirmButtonLabel: "Delete Group", cancelButtonLabel: "Cancel", isDangerousAction: true, onConfirm: handleConfirmDelete, onCancel: handleCancelDelete })));
}

;// ./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/ByobFilterBuilder.tsx
/**
 * BYOB Filter Builder
 *
 * Main component for building Directus-compatible filters visually.
 * Includes JSON preview and the ability to edit JSON directly.
 */









/**
 * Convert filter to JSON string for display/editing (internal format)
 * This preserves IDs and structure so edits can be saved correctly
 */
function filterToJsonString(filter, pretty = true) {
    if (!filter)
        return '';
    return JSON.stringify(filter, null, pretty ? 2 : 0);
}
/**
 * Parse JSON string to filter model (internal format)
 * Validates the structure has the required fields
 */
function jsonStringToFilter(json) {
    try {
        const parsed = JSON.parse(json);
        // Validate it has the required structure
        if (parsed && typeof parsed === 'object' && 'id' in parsed && 'type' in parsed && 'conditions' in parsed) {
            if ((parsed.type === 'and' || parsed.type === 'or') && Array.isArray(parsed.conditions)) {
                // Recursively validate conditions
                if (validateFilterGroup(parsed)) {
                    return parsed;
                }
            }
        }
        return null;
    }
    catch {
        return null;
    }
}
/**
 * Validate a filter group structure recursively
 */
function validateFilterGroup(group) {
    if (!group || typeof group !== 'object')
        return false;
    const g = group;
    if (!g.id || !g.type || !Array.isArray(g.conditions))
        return false;
    if (g.type !== 'and' && g.type !== 'or')
        return false;
    // Validate each condition
    for (const item of g.conditions) {
        if (!item || typeof item !== 'object')
            return false;
        const i = item;
        if (!i.id)
            return false;
        // Is it a group?
        if ('conditions' in i) {
            if (!validateFilterGroup(i))
                return false;
        }
        else {
            // It's a condition - must have field and operator
            if (!('field' in i) || !('operator' in i))
                return false;
        }
    }
    return true;
}
const ByobFilterBuilder = (0,external_react_.forwardRef)(function ByobFilterBuilder({ value, schema, onChange }, ref) {
    // Initialize filter state
    const [filter, setFilter] = (0,external_react_.useState)(() => {
        return value || createEmptyFilterGroup();
    });
    // Show/hide JSON preview
    const [showJson, setShowJson] = (0,external_react_.useState)(false);
    // JSON editing mode
    const [jsonEditMode, setJsonEditMode] = (0,external_react_.useState)(false);
    const [jsonText, setJsonText] = (0,external_react_.useState)('');
    const [jsonError, setJsonError] = (0,external_react_.useState)(null);
    // Expose imperative methods via ref
    (0,external_react_.useImperativeHandle)(ref, () => ({
        saveJsonIfEditing: () => {
            if (jsonEditMode) {
                try {
                    const parsed = jsonStringToFilter(jsonText);
                    if (parsed) {
                        setFilter(parsed);
                        onChange(parsed);
                        setJsonEditMode(false);
                        setJsonError(null);
                        return parsed;
                    }
                }
                catch {
                    // Invalid JSON - return null
                }
            }
            return null;
        }
    }), [jsonEditMode, jsonText, onChange]);
    // Sync external value changes
    (0,external_react_.useEffect)(() => {
        if (value) {
            setFilter(value);
        }
    }, [value]);
    // Update JSON text when filter changes
    (0,external_react_.useEffect)(() => {
        if (!jsonEditMode) {
            setJsonText(filterToJsonString(filter));
        }
    }, [filter, jsonEditMode]);
    // Handle filter changes from visual builder
    const handleFilterChange = (0,external_react_.useCallback)((newFilter) => {
        setFilter(newFilter);
        onChange(newFilter);
    }, [onChange]);
    // Toggle JSON preview
    const handleToggleJson = (0,external_react_.useCallback)(() => {
        setShowJson((prev) => !prev);
        setJsonEditMode(false);
        setJsonError(null);
    }, []);
    // Enter JSON edit mode
    const handleEditJson = (0,external_react_.useCallback)(() => {
        setJsonEditMode(true);
        setJsonText(filterToJsonString(filter));
        setJsonError(null);
    }, [filter]);
    // Save JSON edits
    const handleSaveJson = (0,external_react_.useCallback)(() => {
        try {
            const parsed = jsonStringToFilter(jsonText);
            if (parsed) {
                setFilter(parsed);
                onChange(parsed);
                setJsonEditMode(false);
                setJsonError(null);
            }
            else {
                setJsonError('Invalid filter JSON structure');
            }
        }
        catch (e) {
            setJsonError('Invalid JSON syntax');
        }
    }, [jsonText, onChange]);
    // Cancel JSON edits
    const handleCancelJson = (0,external_react_.useCallback)(() => {
        setJsonEditMode(false);
        setJsonText(filterToJsonString(filter));
        setJsonError(null);
    }, [filter]);
    // Copy JSON to clipboard
    const handleCopyJson = (0,external_react_.useCallback)(() => {
        const json = filterToJsonString(filter);
        navigator.clipboard.writeText(json).catch(console.error);
    }, [filter]);
    // Get fields from schema
    const fields = (schema === null || schema === void 0 ? void 0 : schema.fields) || [];
    return (external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.ByobFilterBuilder },
        external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.ByobFilterBuilderHeader },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.DefaultContrast }, "Filter Conditions"),
            external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.ByobFilterBuilderActions },
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Code, size: common_Icon/* IconSize */.lK.Small, variant: showJson ? inputs_IconButton/* IconButtonVariant */.nl.Default : inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: handleToggleJson }))),
        external_react_default().createElement(DragProvider, { rootFilter: filter, onFilterChange: handleFilterChange },
            external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.ByobFilterBuilderContent },
                external_react_default().createElement(FilterGroup, { group: filter, fields: fields, onChange: handleFilterChange, isRoot: true }))),
        showJson && (external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.ByobFilterBuilderJson },
            external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.ByobFilterBuilderJsonHeader },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "Filter JSON (editable)"),
                external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.ByobFilterBuilderJsonActions }, !jsonEditMode ? (external_react_default().createElement((external_react_default()).Fragment, null,
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Copy, size: common_Icon/* IconSize */.lK.Small, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: handleCopyJson }),
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Pencil, size: common_Icon/* IconSize */.lK.Small, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: handleEditJson }))) : (external_react_default().createElement((external_react_default()).Fragment, null,
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Check, size: common_Icon/* IconSize */.lK.Small, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: handleSaveJson }),
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Close, size: common_Icon/* IconSize */.lK.Small, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: handleCancelJson }))))),
            jsonError && (external_react_default().createElement(Box/* Box */.a, { hasXSpacing: 2, hasYSpacing: 1 },
                external_react_default().createElement("span", { className: ByobFilterBuilder_ByobFilterBuilder_module.ByobFilterBuilderJsonError }, jsonError))),
            jsonEditMode ? (external_react_default().createElement("textarea", { className: ByobFilterBuilder_ByobFilterBuilder_module.ByobFilterBuilderJsonEditor, value: jsonText, onChange: (e) => setJsonText(e.target.value), spellCheck: false })) : (external_react_default().createElement("pre", { className: ByobFilterBuilder_ByobFilterBuilder_module.ByobFilterBuilderJsonPreview }, jsonText || '(empty filter)'))))));
});
// Export for module
/* harmony default export */ const ByobFilterBuilder_ByobFilterBuilder = ((/* unused pure expression or super */ null && (ByobFilterBuilder)));

;// ./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/FilterBuilderModal.tsx
/**
 * Filter Builder Modal
 *
 * Modal dialog wrapper for the Visual Filter Builder.
 * Keeps the property panel clean by showing the full builder in a modal.
 */






function FilterBuilderModal({ isVisible, value, schema, onSave, onClose }) {
    // Ref to access filter builder imperatively (for saving pending JSON edits)
    const filterBuilderRef = (0,external_react_.useRef)(null);
    // Local state for editing - only save when "Save" is clicked
    const [localFilter, setLocalFilter] = (0,external_react_.useState)(() => {
        return value || createEmptyFilterGroup();
    });
    // Reset local state when modal opens with new value
    (0,external_react_.useEffect)(() => {
        if (isVisible) {
            setLocalFilter(value || createEmptyFilterGroup());
        }
    }, [isVisible, value]);
    const handleFilterChange = (0,external_react_.useCallback)((newFilter) => {
        setLocalFilter(newFilter);
    }, []);
    const handleSave = (0,external_react_.useCallback)(() => {
        var _a;
        // First, save any pending JSON edits from the raw editor
        // This returns the updated filter if JSON was being edited, null otherwise
        const updatedFromJson = (_a = filterBuilderRef.current) === null || _a === void 0 ? void 0 : _a.saveJsonIfEditing();
        // Use the JSON-edited filter if available, otherwise use localFilter
        onSave(updatedFromJson || localFilter);
        onClose();
    }, [localFilter, onSave, onClose]);
    const handleCancel = (0,external_react_.useCallback)(() => {
        // Discard changes
        onClose();
    }, [onClose]);
    const footerContent = (external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true, UNSAFE_style: { justifyContent: 'flex-end', width: '100%' } },
        external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: handleCancel }),
        external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Save Filter", onClick: handleSave })));
    return (external_react_default().createElement(Modal, { isVisible: isVisible, onClose: handleCancel, title: "Edit Filter", subtitle: (schema === null || schema === void 0 ? void 0 : schema.name) ? `Collection: ${schema.displayName || schema.name}` : undefined, footerSlot: footerContent, hasFooterDivider: true, UNSAFE_style: { width: '700px', maxHeight: '80vh' } },
        external_react_default().createElement("div", { style: { minHeight: '300px', maxHeight: '60vh', overflow: 'auto' } },
            external_react_default().createElement(ByobFilterBuilder, { ref: filterBuilderRef, value: localFilter, schema: schema, onChange: handleFilterChange }))));
}

;// ./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/FilterBuilderButton.tsx
/**
 * Filter Builder Button
 *
 * Compact button for the property panel that shows a summary
 * and opens the full Filter Builder in a modal.
 */







function FilterBuilderButton({ value, schema, onChange }) {
    const [isModalOpen, setIsModalOpen] = (0,external_react_.useState)(false);
    const summary = getFilterSummary(value);
    const hasFilter = summary !== 'No filter';
    const handleOpenModal = (0,external_react_.useCallback)(() => {
        setIsModalOpen(true);
    }, []);
    const handleCloseModal = (0,external_react_.useCallback)(() => {
        setIsModalOpen(false);
    }, []);
    const handleSave = (0,external_react_.useCallback)((filter) => {
        onChange(filter);
    }, [onChange]);
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterBuilderButton, onClick: handleOpenModal },
            external_react_default().createElement("div", { className: ByobFilterBuilder_ByobFilterBuilder_module.FilterBuilderButtonContent },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Search, size: common_Icon/* IconSize */.lK.Small, UNSAFE_style: { opacity: hasFilter ? 1 : 0.5 } }),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: hasFilter ? typography_Text/* TextType */.M2.DefaultContrast : typography_Text/* TextType */.M2.Shy }, summary)),
            external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Pencil, size: common_Icon/* IconSize */.lK.Small, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, onClick: (e) => {
                    e.stopPropagation();
                    handleOpenModal();
                } })),
        external_react_default().createElement(FilterBuilderModal, { isVisible: isModalOpen, value: value, schema: schema, onSave: handleSave, onClose: handleCloseModal })));
}

;// ./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/index.ts
/**
 * BYOB Filter Builder Module
 *
 * Visual filter builder for Directus-compatible queries
 */






// Utilities

// Converter

// Operators


;// ./src/editor/src/views/panels/propertyeditor/components/ByobFilterBuilder/converter.ts
/**
 * BYOB Filter Converter
 *
 * Converts between our internal filter model and Directus filter JSON format.
 */

/**
 * Convert internal filter model to Directus filter JSON
 *
 * Input (our model):
 * {
 *   type: 'and',
 *   conditions: [
 *     { field: 'status', operator: '_eq', value: 'published' },
 *     { field: 'author.name', operator: '_contains', value: 'John' }
 *   ]
 * }
 *
 * Output (Directus format):
 * {
 *   "_and": [
 *     { "status": { "_eq": "published" } },
 *     { "author": { "name": { "_contains": "John" } } }
 *   ]
 * }
 */
function toDirectusFilter(filter) {
    if (!filter)
        return null;
    // Skip empty groups
    if (filter.conditions.length === 0)
        return null;
    // If only one condition and it's not a group, return it directly (no wrapping _and/_or)
    if (filter.conditions.length === 1 && !isFilterGroup(filter.conditions[0])) {
        return convertCondition(filter.conditions[0]);
    }
    const key = `_${filter.type}`; // _and or _or
    const conditions = filter.conditions.map((item) => convertItem(item)).filter((c) => c !== null);
    if (conditions.length === 0)
        return null;
    if (conditions.length === 1)
        return conditions[0];
    return { [key]: conditions };
}
/**
 * Convert a single filter item (condition or group)
 */
function convertItem(item) {
    if (isFilterGroup(item)) {
        return toDirectusFilter(item);
    }
    else {
        return convertCondition(item);
    }
}
/**
 * Convert a single condition to Directus format
 *
 * Handles nested fields like "author.name" by building nested objects
 */
function convertCondition(condition) {
    const { field, operator, value } = condition;
    // Skip conditions without a field
    if (!field)
        return null;
    // Build the operator/value pair
    // For null checks, value is not used
    const operatorValue = operator === '_null' || operator === '_nnull' || operator === '_empty' || operator === '_nempty' ? true : value;
    // Handle nested fields like "author.name"
    const parts = field.split('.');
    // Build from inside out: { "_eq": "value" }
    let result = { [operator]: operatorValue };
    // Wrap in nested objects for each field part
    for (let i = parts.length - 1; i >= 0; i--) {
        result = { [parts[i]]: result };
    }
    return result;
}
/**
 * Parse Directus filter JSON back to our internal model
 *
 * This allows loading existing filters for editing
 */
function fromDirectusFilter(filter) {
    if (!filter || typeof filter !== 'object')
        return null;
    const keys = Object.keys(filter);
    if (keys.length === 0)
        return null;
    // Check if this is a group (_and or _or)
    if (keys.length === 1 && (keys[0] === '_and' || keys[0] === '_or')) {
        const type = keys[0] === '_and' ? 'and' : 'or';
        const conditions = filter[keys[0]];
        if (!Array.isArray(conditions))
            return null;
        return {
            id: converter_generateId(),
            type,
            conditions: conditions.map((c) => parseFilterItem(c)).filter((c) => c !== null)
        };
    }
    // Single condition - wrap in an AND group
    const condition = parseCondition(filter);
    if (!condition)
        return null;
    return {
        id: converter_generateId(),
        type: 'and',
        conditions: [condition]
    };
}
/**
 * Parse a single filter item from Directus format
 */
function parseFilterItem(item) {
    if (!item || typeof item !== 'object')
        return null;
    const keys = Object.keys(item);
    if (keys.length === 0)
        return null;
    // Check if this is a nested group
    if (keys.length === 1 && (keys[0] === '_and' || keys[0] === '_or')) {
        const type = keys[0] === '_and' ? 'and' : 'or';
        const conditions = item[keys[0]];
        if (!Array.isArray(conditions))
            return null;
        return {
            id: converter_generateId(),
            type,
            conditions: conditions.map((c) => parseFilterItem(c)).filter((c) => c !== null)
        };
    }
    // Otherwise it's a condition
    return parseCondition(item);
}
/**
 * Parse a condition from Directus format
 *
 * Input: { "status": { "_eq": "published" } }
 * Output: { field: "status", operator: "_eq", value: "published" }
 *
 * Input: { "author": { "name": { "_contains": "John" } } }
 * Output: { field: "author.name", operator: "_contains", value: "John" }
 */
function parseCondition(obj, path = []) {
    const keys = Object.keys(obj);
    if (keys.length !== 1)
        return null;
    const key = keys[0];
    const value = obj[key];
    // Check if this key is an operator
    if (key.startsWith('_') && !['_and', '_or'].includes(key)) {
        // This is the operator level
        return {
            id: converter_generateId(),
            field: path.join('.'),
            operator: key,
            value: value
        };
    }
    // Otherwise, this is a field name - recurse deeper
    if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
        return parseCondition(value, [...path, key]);
    }
    return null;
}
/**
 * Generate unique ID
 */
function converter_generateId() {
    return Math.random().toString(36).substring(2, 11);
}
/**
 * Stringify filter to JSON for display
 */
function converter_filterToJsonString(filter, pretty = true) {
    const directusFilter = toDirectusFilter(filter);
    if (!directusFilter)
        return '';
    return JSON.stringify(directusFilter, null, pretty ? 2 : 0);
}
/**
 * Parse JSON string to filter model
 */
function converter_jsonStringToFilter(json) {
    try {
        const parsed = JSON.parse(json);
        return fromDirectusFilter(parsed);
    }
    catch {
        return null;
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/ByobFilterType.ts
/**
 * BYOB Filter Type
 *
 * Property editor type for the BYOB Visual Filter Builder.
 * Renders a button in the property panel that opens a modal with the full builder.
 */






class ByobFilterType extends TypeView {
    constructor() {
        super(...arguments);
        this.root = null;
    }
    static fromPort(args) {
        const view = new ByobFilterType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.default = p.default;
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        const div = document.createElement('div');
        // Parse value from JSON string - extracted so it can be called on render and re-render
        const parseValue = () => {
            if (this.value) {
                try {
                    const parsed = JSON.parse(this.value);
                    // Check if it's already our visual builder format (has 'conditions' array)
                    if (parsed.conditions) {
                        return parsed;
                    }
                    else {
                        // It's a legacy Directus format, convert it
                        return fromDirectusFilter(parsed);
                    }
                }
                catch (e) {
                    console.warn('[ByobFilterType] Failed to parse existing filter:', e);
                }
            }
            return null;
        };
        // Render the button component
        const renderButton = (filterValue) => {
            var _a;
            // Get schema from port type (populated by node's updatePorts)
            const schema = ((_a = this.type) === null || _a === void 0 ? void 0 : _a.schema) || null;
            const props = {
                value: filterValue,
                schema: schema,
                onChange: (filter) => {
                    // Store the full visual builder format (with conditions array, IDs, etc.)
                    // The runtime will convert to Directus format at fetch time
                    const jsonString = JSON.stringify(filter);
                    console.log('[ByobFilterType] Saving filter:', jsonString);
                    const undoArgs = { undo: true, label: 'filter changed', oldValue: this.value };
                    this.value = jsonString;
                    this.parent.model.setParameter(this.name, jsonString, undoArgs);
                    this.isDefault = false;
                    // Re-render the button with the new value so UI updates immediately
                    renderButton(filter);
                }
            };
            if (!this.root) {
                this.root = (0,client.createRoot)(div);
            }
            this.root.render(external_react_default().createElement(FilterBuilderButton, props));
        };
        renderButton(parseValue());
        this.el = $(div);
        return this.el;
    }
}

// EXTERNAL MODULE: ./src/editor/src/views/panels/propertyeditor/DataTypes/ColorPicker/colorpicker.js + 1 modules
var colorpicker = __webpack_require__(45330);
// EXTERNAL MODULE: ./src/editor/src/views/TextStylePicker/utils.js
var TextStylePicker_utils = __webpack_require__(48032);
var utils_default = /*#__PURE__*/__webpack_require__.n(TextStylePicker_utils);
;// ./src/editor/src/views/panels/propertyeditor/DataTypes/ColorPicker/colorstylepicker.jsx









__webpack_require__(46055);
function getProjectColors(colorStyles) {
  const colorsNames = new Set();
  const components = projectmodel.ProjectModel.instance.getComponents();
  components.forEach(c => {
    c.graph.forEachNode(node => {
      const colorPorts = node.getPorts('input').filter(p => p.type === 'color');
      const values = colorPorts.map(port => node.getParameter(port.name));
      values.filter(name => name).forEach(name => {
        colorsNames.add(name);
      });
    });
  });
  let colors = Array.from(colorsNames);
  colors = colors.filter(c => !colorStyles.find(s => s.name === c)); //remove all color styles from the list, so we only get the #HEX colors
  colors.sort();
  return colors;
}
function ColorStylePicker(props) {
  const [stylesModel, setStylesModel] = (0,external_react_.useState)(null);
  const [colorStyles, setColorsStyles] = (0,external_react_.useState)([]);
  const [projectColors, setProjectColors] = (0,external_react_.useState)([]);
  const [styleToEdit, setStyleToEdit] = (0,external_react_.useState)(null);
  const [popupAnchor, setPopupAnchor] = (0,external_react_.useState)(null);

  //the color style picker is rendered in a popup/poput, and that system uses the height of the content to decide how big
  //the popup should be. And it needs that information directly on render.
  //this means we need to get all styles etc synchronously with the first render, which useLayoutEffect solves
  (0,external_react_.useLayoutEffect)(() => {
    const stylesModel = new StylesModel();
    setStylesModel(stylesModel);
    const styles = stylesModel.getStyles('colors');
    setColorsStyles(styles);
    setProjectColors(getProjectColors(styles));
    stylesModel.on('stylesChanged', args => {
      if (args.type === 'colors') {
        const styles = stylesModel.getStyles('colors');
        setColorsStyles(styles);
      }
    });
    return () => {
      stylesModel.dispose();
    };
  }, []);
  let filteredStyles = colorStyles;
  let filteredProjectColors = projectColors;
  const filterString = props.filter ? props.filter.toLowerCase() : undefined;
  if (filterString) {
    filteredStyles = colorStyles.filter(style => style.name.toLowerCase().includes(filterString));
    filteredProjectColors = projectColors.filter(color => color.toLowerCase().includes(filterString));
  }
  const onItemSelected = name => props.onItemSelected(name);
  const onDelete = name => {
    const {
      nodeCount,
      variantCount
    } = utils_default().getStyleUsage('color', name);
    if (nodeCount > 0 || variantCount > 0) {
      let message = `Are you sure you want to delete <strong>${name}</strong>?<br>This color style is used by `;
      if (nodeCount) {
        message += `${nodeCount} ${nodeCount === 1 ? 'node' : 'nodes'}`;
      }
      if (variantCount) {
        if (nodeCount) {
          message += ' and ';
        }
        message += `${variantCount} ${variantCount === 1 ? 'variant' : 'variants'}`;
      }
      popuplayer_default().instance.showConfirmModal({
        title: 'CONFIRM DELETE COLOR STYLE',
        message: message,
        confirmLabel: 'Yes, delete',
        onConfirm: () => {
          stylesModel.deleteStyle('colors', name, {
            undo: true,
            label: 'delete color style'
          });
        }
      });
    } else {
      stylesModel.deleteStyle('colors', name, {
        undo: true,
        label: 'delete color style'
      });
    }
  };
  const onChangeName = (name, newName) => {
    stylesModel.changeStyleName('colors', name, newName, {
      undo: true,
      label: 'change color style name'
    });
  };
  const onEditValue = (style, popupAnchor) => {
    setStyleToEdit(style);
    setPopupAnchor(popupAnchor);
  };
  (0,external_react_.useEffect)(() => {
    if (!styleToEdit) return;
    const colorPicker = new colorpicker/* default */.A();
    colorPicker.render();
    colorPicker.setColor(styleToEdit.style);
    colorPicker.setColorChangedListener((color, commitChange) => {
      if (commitChange) {
        stylesModel.setStyle('colors', styleToEdit.name, color, {
          undo: true,
          label: 'change color style'
        });
      }
    });
    const popout = popuplayer_default().instance.showPopout({
      content: colorPicker,
      attachTo: $(popupAnchor),
      position: 'right'
    });
    return () => {
      popuplayer_default().instance.hidePopout(popout);
    };
  }, [styleToEdit, popupAnchor]);
  return /*#__PURE__*/external_react_default().createElement("div", {
    style: {
      width: '230px',
      overflow: 'hidden',
      display: 'flex',
      flexDirection: 'column'
    }
  }, /*#__PURE__*/external_react_default().createElement("div", {
    style: {
      overflow: 'hidden auto',
      flexGrow: 1,
      maxHeight: '600px'
    }
  }, /*#__PURE__*/external_react_default().createElement(CreateNewStyle, {
    color: props.inputValue,
    stylesModel: stylesModel,
    onColorStyleCreated: onItemSelected
  }), filteredStyles.map(style => /*#__PURE__*/external_react_default().createElement(ColorStyleItem, {
    key: style.name,
    style: style,
    onSelect: onItemSelected,
    onChangeName: onChangeName,
    onEditValue: onEditValue,
    onDelete: onDelete,
    onEditingName: () => setStyleToEdit(null),
    currentSelectedColor: props.inputValue
  })), /*#__PURE__*/external_react_default().createElement(ProjectColorsList, {
    colors: filteredProjectColors,
    onSelect: onItemSelected,
    currentSelectedColor: props.inputValue
  })));
}
function ProjectColorsList(props) {
  if (props.colors.length === 0) {
    return null;
  }
  return /*#__PURE__*/external_react_default().createElement((external_react_default()).Fragment, null, /*#__PURE__*/external_react_default().createElement("div", {
    className: "variants-header"
  }, /*#__PURE__*/external_react_default().createElement("span", null, "Colors in project")), props.colors.map(color => /*#__PURE__*/external_react_default().createElement(ColorItem, {
    key: color,
    color: color,
    onSelect: props.onSelect,
    currentSelectedColor: props.currentSelectedColor
  })));
}
function useScrollToIfSelected(ref, colorName, selectedColorName) {
  (0,external_react_.useEffect)(() => {
    if (!ref.current || !colorName || !selectedColorName) return;
    if (colorName !== selectedColorName) return;
    ref.current.scrollIntoView({
      behavior: 'smooth',
      block: 'center'
    });
  }, [ref.current, colorName]);
}
function ColorStyleItem(props) {
  const [isEditing, setIsEditing] = (0,external_react_.useState)(false);
  const ref = (0,external_react_.useRef)(null);
  const [styleName, setStyleName] = (0,external_react_.useState)(props.style.name);
  const isSelectedColor = props.style.name === props.currentSelectedColor;
  useScrollToIfSelected(ref, props.style.name, props.currentSelectedColor);
  const onSelectClicked = e => {
    props.onSelect(props.style.name);
    e.stopPropagation();
  };
  const onEditClicked = e => {
    props.onEditingName();
    setIsEditing(true);
    setStyleName(props.style.name);
    e.stopPropagation();
  };
  const onDeleteClicked = e => {
    props.onDelete(props.style.name);
    e.stopPropagation();
  };
  const onColorClicked = e => {
    e.stopPropagation();
    e.preventDefault();
    e.nativeEvent.stopPropagation();
    props.onEditValue(props.style, ref.current);
  };
  const onInputKeyUp = e => {
    if (e.key === 'Enter') {
      const newName = e.target.value;
      if (newName && props.style.name !== newName) {
        props.onChangeName(props.style.name, newName);
      }
      setIsEditing(false);
    }
  };
  if (isEditing) {
    return /*#__PURE__*/external_react_default().createElement("div", {
      className: "variants-pick-variant-item"
    }, /*#__PURE__*/external_react_default().createElement("input", {
      className: "variants-input",
      type: "text",
      autoFocus: true,
      onChange: e => setStyleName(e.target.value),
      onKeyUp: onInputKeyUp,
      value: styleName,
      onBlur: () => setIsEditing(false)
    }), /*#__PURE__*/external_react_default().createElement("div", {
      className: "color-thumbnail"
    }, /*#__PURE__*/external_react_default().createElement("div", {
      className: "color-thumbnail-content",
      style: {
        backgroundColor: props.style.style
      }
    })));
  }
  return /*#__PURE__*/external_react_default().createElement("div", {
    className: "variants-pick-variant-item",
    onClick: onSelectClicked,
    ref: ref,
    style: {
      backgroundColor: isSelectedColor ? 'var(--hover-bg-color)' : null
    }
  }, /*#__PURE__*/external_react_default().createElement("div", {
    className: "variant-item-name"
  }, props.style.name), /*#__PURE__*/external_react_default().createElement("div", {
    className: "variants-item-icon",
    onClick: onEditClicked
  }, /*#__PURE__*/external_react_default().createElement("i", {
    className: "fa fa-edit"
  })), /*#__PURE__*/external_react_default().createElement("div", {
    className: "variants-item-icon",
    onClick: onDeleteClicked
  }, /*#__PURE__*/external_react_default().createElement("i", {
    className: "fa fa-trash"
  })), /*#__PURE__*/external_react_default().createElement("div", {
    className: "color-thumbnail",
    onClick: onColorClicked
  }, /*#__PURE__*/external_react_default().createElement("div", {
    className: "color-thumbnail-content",
    style: {
      backgroundColor: props.style.style
    }
  })));
}
function ColorItem(props) {
  const ref = (0,external_react_.useRef)();
  const onSelectClicked = e => {
    props.onSelect(props.color);
    e.stopPropagation();
  };
  useScrollToIfSelected(ref, props.color, props.currentSelectedColor);
  return /*#__PURE__*/external_react_default().createElement("div", {
    className: "variants-pick-variant-item",
    onClick: onSelectClicked,
    ref: ref,
    style: {
      backgroundColor: props.currentSelectedColor === props.color ? 'var(--hover-bg-color)' : null
    }
  }, /*#__PURE__*/external_react_default().createElement("div", {
    className: "variant-item-name"
  }, props.color), /*#__PURE__*/external_react_default().createElement("div", {
    className: "color-thumbnail"
  }, /*#__PURE__*/external_react_default().createElement("div", {
    className: "color-thumbnail-content",
    style: {
      backgroundColor: props.color
    }
  })));
}
function CreateNewStyle(props) {
  const [isCreating, setIsCreating] = (0,external_react_.useState)(false);
  const inputRef = (0,external_react_.useRef)(null);
  const color = projectmodel.ProjectModel.instance.resolveColor(props.color);
  const onCreateNewColorStyle = () => {
    const name = inputRef.current.value;
    if (!name) return;
    if (props.stylesModel.styleExists('colors', name)) {
      ToastLayer.ToastLayer.showError('Style already exists');
    } else {
      props.stylesModel.setStyle('colors', name, color, {
        undo: true,
        label: `create new color style: ${name}`
      });
      props.onColorStyleCreated(name);
      setIsCreating(false);
      ToastLayer.ToastLayer.showSuccess(`Created color style ${name}`);
    }
  };
  if (isCreating) {
    return /*#__PURE__*/external_react_default().createElement((external_react_default()).Fragment, null, /*#__PURE__*/external_react_default().createElement("div", {
      className: "variants-header"
    }, /*#__PURE__*/external_react_default().createElement("span", null, "New color style name")), /*#__PURE__*/external_react_default().createElement("div", null, /*#__PURE__*/external_react_default().createElement("div", {
      className: "variants-input-container"
    }, /*#__PURE__*/external_react_default().createElement("input", {
      autoFocus: true,
      className: "variants-input",
      ref: inputRef,
      onKeyUp: e => e.key === 'Enter' && onCreateNewColorStyle(),
      style: {
        marginRight: 0
      }
    }), /*#__PURE__*/external_react_default().createElement("div", {
      className: "color-thumbnail",
      style: {
        height: 27,
        width: 27
      }
    }, /*#__PURE__*/external_react_default().createElement("div", {
      className: "color-thumbnail-content",
      style: {
        backgroundColor: color
      }
    }))), /*#__PURE__*/external_react_default().createElement("div", {
      style: {
        padding: '0 8px 8px',
        display: 'flex',
        alignItems: 'center'
      }
    }, /*#__PURE__*/external_react_default().createElement("button", {
      className: "variants-button primary",
      onClick: onCreateNewColorStyle,
      style: {
        width: '100%'
      }
    }, "Create"))));
  } else {
    return /*#__PURE__*/external_react_default().createElement("div", {
      className: "variants-header variants-add-header"
    }, /*#__PURE__*/external_react_default().createElement("span", null, "Create new color style"), /*#__PURE__*/external_react_default().createElement(inputs_IconButton/* IconButton */.K0, {
      icon: common_Icon/* IconName */.$M.Plus,
      size: common_Icon/* IconSize */.lK.Small,
      UNSAFE_className: "add-button",
      variant: inputs_IconButton/* IconButtonVariant */.nl.OpaqueOnHover,
      onClick: () => setIsCreating(true)
    }));
  }
}
/* harmony default export */ const colorstylepicker = (ColorStylePicker);
;// ./src/editor/src/views/panels/propertyeditor/DataTypes/ColorPicker/ColorType.ts








//Note: this entire property can be re-created by events such as todo
//so the color picker can be left open, but now need a new callback to set
//values on the new property.
let colorPicker;
//The property panel might rerender, and recreate all the PropertyEditors, while the Color Picker is open.
//When this happens, the color picker need new callbacks to update the new DOM elements that are attached to the new view
//this function handles that and is called whenever a PropertyEditor.ColorType is re-rendered when the color picker is active
function bindColorPickerToView(view) {
    const initialColor = view.getCurrentValue();
    colorPicker.setColor(projectmodel.ProjectModel.instance.resolveColor(initialColor.value));
    colorPicker.setColorChangedListener((color, commit) => {
        //commit is true when the value should be added to the undo queue
        view.parent.setParameterEx(view.name, color, initialColor.value, !commit);
        view.updateCurrentValue();
    });
    colorPicker._propertyName = view.name;
}
class ColorType extends TypeView {
    static fromPort(args) {
        const view = new ColorType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    dispose() {
        TypeView.prototype.dispose.call(this);
        EventDispatcher.EventDispatcher.instance.off(this);
        if (colorPicker) {
            colorPicker.dispose();
            colorPicker = null;
        }
    }
    onLaunchClicked(scope, el, evt) {
        this.propertyName = scope.name;
        if (!colorPicker) {
            colorPicker = new colorpicker/* default */.A();
            colorPicker.render();
        }
        bindColorPickerToView(this);
        this.parent.showPopout({
            content: colorPicker,
            attachTo: el,
            position: 'right',
            onClose: () => {
                colorPicker && colorPicker.dispose();
                colorPicker = null;
            }
        });
        evt.stopPropagation();
    }
    render() {
        this.el = this.bindView(this.parent.cloneTemplate('color'), this);
        TypeView.prototype.render.call(this);
        this.updateCurrentValue();
        if (colorPicker && colorPicker._propertyName === this.name) {
            bindColorPickerToView(this);
        }
        let colorStylePickerDiv;
        let colorStylePickerRoot = null;
        const props = {};
        EventDispatcher.EventDispatcher.instance.on('Model.stylesChanged', (event) => {
            if (event.args.type === 'colors') {
                this.updateCurrentValue();
            }
        }, this);
        this.$('input').on('focus', (e) => {
            e.stopPropagation();
        });
        this.$('input').on('click', (e) => {
            // @ts-expect-error - Dynamic props assignment for legacy component
            delete props.filter; //delete filter in case the user opens/closes multiple times
            // @ts-expect-error - Dynamic props assignment for legacy component
            props.onItemSelected = (name) => {
                this.parent.setParameter(this.name, name);
                this.updateCurrentValue();
                this.parent.hidePopout();
            };
            const current = this.getCurrentValue();
            // @ts-expect-error - Dynamic props assignment for legacy component
            props.inputValue = current.value;
            colorStylePickerDiv = document.createElement('div');
            colorStylePickerRoot = (0,client.createRoot)(colorStylePickerDiv);
            colorStylePickerRoot.render(external_react_default().createElement(colorstylepicker, props));
            this.parent.showPopout({
                content: { el: $(colorStylePickerDiv) },
                attachTo: this.el,
                position: 'right',
                onClose: () => {
                    if (colorStylePickerRoot) {
                        colorStylePickerRoot.unmount();
                        colorStylePickerRoot = null;
                        colorStylePickerDiv = undefined;
                    }
                }
            });
            e.stopPropagation(); // Stop propagation, otherwise the popup will close
        });
        this.$('input').on('keyup', (e) => {
            if (!colorStylePickerRoot) {
                return;
            }
            if (e.key === 'Enter') {
                this.parent.hidePopout();
            }
            else {
                // @ts-expect-error - Dynamic props assignment for legacy component
                props.filter = e.target.value;
                colorStylePickerRoot.render(external_react_default().createElement(colorstylepicker, props));
            }
        });
        return this.el;
    }
    updateCurrentValue() {
        const current = this.getCurrentValue();
        let stringColor = current.value;
        if (stringColor && stringColor[0] === '#') {
            //only display the RGB part of a color in the input field
            //so if the colors has a #RRGGBBAA format, strip away the alpha
            const hasAlpha = stringColor.length === 9;
            stringColor = hasAlpha ? stringColor.slice(0, 7) : stringColor;
            stringColor = stringColor.toUpperCase();
        }
        this.$('#stringInput').val(stringColor);
        this.$('.color-thumbnail-content').css({
            'background-color': projectmodel.ProjectModel.instance.resolveColor(current.value)
        });
        this.isDefault = current.isDefault;
    }
    onStringInputChanged(scope, el) {
        let value = this.$('#stringInput').val().trim();
        if (value === '')
            value = undefined;
        const isHex = value !== undefined && /[0-9A-F]{6}$/i.test(value);
        if (isHex === true && value[0] !== '#') {
            value = '#' + value;
        }
        this.parent.setParameter(this.name, value);
        this.updateCurrentValue();
    }
    resetToDefault() {
        this.updateCurrentValue();
    }
}

// EXTERNAL MODULE: ./src/editor/src/models/nodelibrary/ComponentIcon.ts
var ComponentIcon = __webpack_require__(56937);
;// ./src/editor/src/views/panels/propertyeditor/componentpicker.ts









class ComponentPicker {
    constructor(args) {
        this.root = null;
        this.onItemSelected = args.onItemSelected;
        this.componentsToShow = args.components;
        this.ignoreSheetName = !!args.ignoreSheetName;
    }
    parseItems(components) {
        const parsedItems = [];
        // Parse all that match filter
        for (const component of components) {
            if (this.pathFilter === undefined ||
                this.pathFilter === '' ||
                component.fullName.toLowerCase().indexOf(this.pathFilter) !== -1) {
                const componentFolder = component.name.substring(0, component.name.length - component.localName.length);
                let folder = componentFolder !== '/' ? componentFolder : undefined;
                const iconType = (0,ComponentIcon/* getComponentIconType */.N)(component);
                if (folder) {
                    folder = folder.replace('/#__cloud__', '');
                }
                if (folder === '/') {
                    folder = undefined;
                }
                let icon;
                if (iconType === ComponentIcon/* ComponentIconType */.J.CloudFunction) {
                    icon = common_Icon/* IconName */.$M.CloudFunction;
                }
                else if (iconType === ComponentIcon/* ComponentIconType */.J.Page) {
                    icon = common_Icon/* IconName */.$M.File;
                }
                else {
                    icon = common_Icon/* IconName */.$M.Component;
                }
                parsedItems.push({
                    icon,
                    label: component.localName,
                    endSlot: folder,
                    fullPath: component.name,
                    key: component.id || component.name
                });
            }
        }
        parsedItems.sort((a, b) => {
            return a.fullPath > b.fullPath ? -1 : 1;
        });
        return insertDividerBetweenAllItems(parsedItems);
    }
    setFilter(filter) {
        this.pathFilter = filter.toLowerCase();
        this.renderReact();
    }
    setValue(item) {
        if (this.ignoreSheetName) {
            const withoutSheetName = item.fullPath.split('/').slice(2).join('/');
            this.onItemSelected(withoutSheetName);
        }
        else {
            this.onItemSelected(item.fullPath);
        }
    }
    getAllComponents() {
        const rootComponent = projectmodel.ProjectModel.instance.getRootComponent();
        const allComponents = projectmodel.ProjectModel.instance
            .getComponents()
            //dont include pages or the root component
            .filter((c) => c !== rootComponent && (0,ComponentIcon/* getComponentIconType */.N)(c) !== ComponentIcon/* ComponentIconType */.J.Page);
        const isShowingFrontend = NodeGraphContext.NodeGraphContextTmp.active === 'frontend';
        const components = allComponents.filter((c) => {
            const isCloud = (0,NodeGraph/* isComponentModel_CloudRuntime */.dk)(c);
            if (isShowingFrontend) {
                return !isCloud;
            }
            else {
                //don't allow references to cloud functions, only cloud components
                return isCloud && (0,ComponentIcon/* getComponentIconType */.N)(c) !== ComponentIcon/* ComponentIconType */.J.CloudFunction;
            }
        });
        return components;
    }
    getComponentModelsFromNames(names) {
        return names.map((name) => projectmodel.ProjectModel.instance.getComponentWithName(name)).filter((c) => !!c);
    }
    renderReact() {
        const components = this.componentsToShow
            ? this.getComponentModelsFromNames(this.componentsToShow)
            : this.getAllComponents();
        const items = this.parseItems(components);
        const menuItems = items.length
            ? items.map((item) => (item === 'divider' ? 'divider' : { ...item, onClick: () => this.setValue(item) }))
            : [
                {
                    label: 'No matching components'
                }
            ];
        const props = {
            isVisible: true,
            onClose: () => this.dispose(),
            // mapping out onclick here as the fullPath gets overwritten
            // with the last one up in the parseItems() function
            items: menuItems,
            title: 'Choose component',
            triggerRef: { current: this.reactMount },
            renderDirection: 1,
            width: MenuDialog.MenuDialogWidth.Medium
        };
        if (!this.root) {
            this.root = (0,client.createRoot)(this.reactMount);
        }
        this.root.render(external_react_default().createElement(MenuDialog.MenuDialog, props));
    }
    render(target) {
        this.reactMount = target;
        this.renderReact();
    }
    dispose() {
        if (this.root) {
            this.root.unmount();
            this.root = null;
        }
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/ComponentType.ts




function ComponentType_firstType(type) {
    return nodelibrary/* NodeLibrary */.m.nameForPortType(type);
}
class ComponentType extends TypeView {
    static fromPort(args) {
        const view = new ComponentType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        const _this = this;
        this.el = this.bindView(this.parent.cloneTemplate(ComponentType_firstType(this.type)), this);
        TypeView.prototype.render.call(this);
        let componentPicker;
        this.$('input')
            .on('focus', function (e) {
            e.stopPropagation();
        })
            .on('click', function (e) {
            componentPicker = new ComponentPicker({
                components: _this.type.components,
                ignoreSheetName: _this.type.ignoreSheetName,
                onItemSelected: function (name) {
                    _this.$('input').val(name);
                    _this.$('input').trigger('change');
                    _this.parent.hidePopout();
                }
            });
            componentPicker.render(e.target);
            e.stopPropagation(); // Most stop propagation here otherwise the popup will close
        })
            .on('keyup', function (e) {
            componentPicker && componentPicker.setFilter($(this).val());
        });
        return this.el;
    }
    onPropertyChanged(scope, el) {
        this.parent.setParameter(scope.name, el.val() === '' ? undefined : el.val());
        // Update current value and if it is default or not
        const current = this.getCurrentValue();
        el.val(current.value);
        this.isDefault = current.isDefault;
        el.blur();
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/CurveEditor/CurveType.ts




class CurveType extends TypeView {
    static fromPort(args) {
        const view = new CurveType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.default = p.default;
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        this.el = this.bindView(this.parent.cloneTemplate('curve'), this);
        TypeView.prototype.render.call(this);
        return this.el;
    }
    onEditClicked(scope, el, evt) {
        const _this = this;
        this.propertyName = scope.name;
        this.parent.hidePopout();
        const props = {
            value: this.value,
            default: this.default || { curve: [0.0, 0.0, 0.58, 1.0], dur: 300, delay: 0 },
            onUpdate: function (curve, drag) {
                const undoArgs = { undo: true, label: 'curve changed', oldValue: _this.value };
                if (!drag)
                    _this.value = curve;
                _this.parent.model.setParameter(scope.name, curve, drag ? undefined : undoArgs);
                _this.isDefault = false;
            }
        };
        const div = document.createElement('div');
        const root = (0,client.createRoot)(div);
        root.render(external_react_default().createElement(__webpack_require__(3191), props));
        const curveEditorView = {
            el: $(div)
        };
        this.parent.showPopout({
            content: curveEditorView,
            attachTo: el,
            position: 'right'
        });
        evt.stopPropagation();
    }
    resetToDefault() {
        this.value = undefined;
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/Dimension.ts


function parseNumberWithUnit(stringValue, permittedUnits) {
    let value = parseFloat(stringValue);
    if (isNaN(value)) {
        value = undefined;
    }
    let unit;
    permittedUnits.some((u) => {
        if (stringValue.endsWith(u)) {
            unit = u;
            return true;
        }
        return false;
    });
    return {
        value,
        unit
    };
}
class Dimension extends TypeView {
    static fromPort(args) {
        const view = new Dimension();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.tooltip = p.tooltip;
        view.numberWithUnits = parent.model.getParameter(p.name);
        view.isFixed = view.numberWithUnits ? view.numberWithUnits.isFixed : false;
        view.isPercent = view.unit === '%';
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    // @ts-expect-error
    get value() {
        return typeof this.numberWithUnits === 'object' ? this.numberWithUnits.value : this.numberWithUnits;
    }
    get unit() {
        return typeof this.numberWithUnits === 'object' ? this.numberWithUnits.unit : this.type.defaultUnit;
    }
    render() {
        const _this = this;
        this.el = this.bindView(this.parent.cloneTemplate('dimension'), this);
        TypeView.prototype.render.call(this);
        // Render units dropdown
        this.$('.property-input-dropdown').html('');
        const units = this.type.units;
        for (const i in units) {
            this.$('.property-input-dropdown').append(this.bindView($('<div class="property-number-unit-enum" data-click="onUnitChanged" data-value="' +
                units[i] +
                '">' +
                units[i] +
                '</div>')));
        }
        this.$('.property-input-dropdown').on('mousedown', function (event) {
            event.preventDefault(); // make sure drop down doesn't blur input until after "onPropertyChanged" has been triggered
        });
        this.$('.property-number-units').on('blur', function () {
            _this.$('.property-input-dropdown').hide();
        });
        return this.el;
    }
    onDropDownClicked(scope, el) {
        const showShould = !this.$('.property-input-dropdown').is(':visible');
        this.parent.$('.property-input-dropdown').hide();
        if (showShould) {
            this.$('.property-number-units')[0].focus();
            this.$('.property-input-dropdown').show();
        }
        // Hide show the padding so drop downs can be scrolled to if at the bottom of the prop editor
        this.parent.$('.property-drop-down-padding').hide();
        showShould && this.parent.$('.property-drop-down-padding').show();
        this.parent.notifyListeners('panelResized');
    }
    updateValue() {
        const v = parseNumberWithUnit(this.$('input').val(), this.type.units);
        const value = v.value;
        const unit = v.unit ? v.unit : this.$('[data-text=unit]').text();
        // If the input is not a valid value, then set undefined
        if (value !== undefined) {
            const u = unit ? unit : this.type.defaultUnit;
            this.parent.setParameter(this.name, { value, unit: u, isFixed: this.isFixed });
        }
        else
            this.parent.setParameter(this.name, undefined);
        // Update current value and if it is default or not
        const current = this.getCurrentValue();
        this.numberWithUnits = current.value;
        this.$('input').val(this.value);
        this.$('[data-text=unit]').text(this.unit);
        this.isDefault = current.isDefault;
        this.isPercent = this.unit === '%';
    }
    resetToDefault() {
        this.isPercent = this.type.defaultUnit === '%';
        this.isFixed = false;
        this.$('input').val(this.getCurrentValue().value);
        this.$('[data-text=unit]').text(this.type.defaultUnit);
    }
    onUnitChanged(scope, el) {
        const unit = el.attr('data-value');
        this.$('[data-text=unit]').text(unit);
        this.updateValue();
    }
    onBoxClicked(scope, el) {
        this.isFixed = !this.isFixed;
        this.updateValue();
    }
    onPropertyChanged(scope, el) {
        this.updateValue();
        el.blur();
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/EnumType.ts



class EnumType extends TypeView {
    static fromPort(args) {
        const view = new EnumType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.tooltip = p.tooltip;
        view.value = view.labelForValue(parent.model.getParameter(p.name));
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    labelForValue(value) {
        if (value === undefined)
            return '';
        const e = (0,external_underscore_.find)(this.type.enums, function (e) {
            return e === value || e.value === value;
        });
        if (e === undefined)
            return;
        return e.label ? e.label : e;
    }
    render() {
        const _this = this;
        this.el = this.bindView(this.parent.cloneTemplate('enum'), this);
        TypeView.prototype.render.call(this);
        this.$('.property-input-dropdown').html('');
        const enums = this.type.enums;
        for (const i in enums) {
            const value = typeof enums[i] === 'object' ? enums[i].value : enums[i];
            const label = typeof enums[i] === 'object' ? enums[i].label : enums[i];
            this.$('.property-input-dropdown').append(this.bindView($('<div class="property-input-enum" data-click="onPropertyChanged" data-value="' + value + '"></div>').text(label)));
        }
        this.$('.property-input-dropdown').on('mousedown', function (event) {
            event.preventDefault(); // make sure drop down doesn't blur input until after "onPropertyChanged" has been triggered
        });
        this.$('input').on('blur', function () {
            _this.$('.property-input-dropdown').hide();
        });
        return this.el;
    }
    onDropDownClicked(scope, el) {
        // Close other dropdowns
        const showShould = !this.$('.property-input-dropdown').is(':visible');
        this.parent.$('.property-input-dropdown').hide();
        showShould && this.$('.property-input-dropdown').show();
        // Hide show the padding so drop downs can be scrolled to if at the bottom of the prop editor
        this.parent.$('.property-drop-down-padding').hide();
        showShould && this.parent.$('.property-drop-down-padding').show();
        this.parent.notifyListeners('panelResized');
    }
    onPropertyChanged(scope, el) {
        this.parent.setParameter(this.name, el.attr('data-value'));
        // Update current value
        const current = this.getCurrentValue();
        this.$('input').val(this.labelForValue(current.value));
        this.isDefault = current.isDefault;
    }
    resetToDefault() {
        const current = this.getCurrentValue();
        this.$('input').val(this.labelForValue(current.value));
    }
}

// EXTERNAL MODULE: ./src/editor/src/templates/propertyeditor/filepicker.html
var filepicker = __webpack_require__(10310);
var filepicker_default = /*#__PURE__*/__webpack_require__.n(filepicker);
;// ./src/editor/src/views/panels/propertyeditor/DataTypes/FilePicker/filepicker.js







var FilePicker = function (args) {
  view_default().call(this);

  this.items = [];
  this.onItemSelected = args.onItemSelected;
  this.fileTypes = args.fileTypes;
};
FilePicker.prototype = Object.create((view_default()).prototype);

FilePicker.prototype.resize = function (layout) {
  this.el.css({
    position: 'absolute',
    left: layout.x + 'px',
    top: layout.y + 'px',
    width: layout.width + 'px',
    height: layout.height + 'px'
  });
};

FilePicker.prototype.renderItems = function () {
  var _this = this;

  if (!this.el) return;

  this.$('.items').html('');

  this.items.sort(function (a, b) {
    if (a.folder === '/' && b.folder !== '/') return -1;
    if (b.folder === '/' && a.folder !== '/') return 1;
    return a.fullPath < b.fullPath ? -1 : 1;
  });

  function append(item) {
    _this.$('.items').append(item.el);
    item.el.on('click', function () {
      _this.itemClicked(item);
    });
  }

  // Render all that match filter
  var folder;
  for (var i in this.items) {
    var item = this.items[i];

    if (item.folder !== folder) {
      folder = item.folder;
      if (folder !== '/') this.$('.items').append('<div class="content-picker-group-label">' + folder + '</div>');
    }

    if (
      this.pathFilter === undefined ||
      this.pathFilter === '' ||
      item.fullPath.toLowerCase().indexOf(this.pathFilter) !== -1
    ) {
      append(item);
    }
  }
};

FilePicker.prototype.setFilter = function (filter) {
  this.pathFilter = filter.toLowerCase();
  this.renderItems();
};

FilePicker.prototype.render = function () {
  var _this = this;

  var el = this.bindView($((filepicker_default())), this);
  if (this.el) this.el.append(el);
  else this.el = el;

  // Render image objects
  projectmodel.ProjectModel.instance.listFilesInProjectDirectory(function (files) {
    external_underscore_default().each(files, function (fileEntry) {
      var pathInProjectFolder = fileEntry.fullPath.substring(
        projectmodel.ProjectModel.instance._retainedProjectDirectory.length + 1
      );
      var el = _this.bindView(_this.cloneTemplate('item'), { name: fileEntry.name, fullPath: pathInProjectFolder });

      // Extract folder for image
      var folder = pathInProjectFolder.split('/');
      if (folder.length === 1) folder = '/';
      else folder = folder.splice(0, folder.length - 1).join('/');

      _this.items.push({
        el: el,
        name: fileEntry.name,
        fullPath: pathInProjectFolder,
        folder: folder
      });
    });
    _this.renderItems();
  }, _this.fileTypes);

  return this.el;
};

FilePicker.prototype.itemClicked = function (scope) {
  this.onItemSelected && this.onItemSelected(scope.fullPath);
};

/* harmony default export */ const FilePicker_filepicker = (FilePicker);

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/FilePicker/SourceCodeType.ts




function SourceCodeType_firstType(type) {
    return nodelibrary/* NodeLibrary */.m.nameForPortType(type);
}
class SourceCodeType extends TypeView {
    static fromPort(args) {
        const view = new SourceCodeType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        const _this = this;
        this.el = this.bindView(this.parent.cloneTemplate(SourceCodeType_firstType(this.type)), this);
        TypeView.prototype.render.call(this);
        let filePicker;
        this.$('input')
            .on('focus', function (e) {
            e.stopPropagation();
        })
            .on('click', function (e) {
            filePicker = new FilePicker_filepicker({
                onItemSelected: function (name) {
                    _this.$('input').val(name);
                    _this.$('input').trigger('change');
                    _this.parent.hidePopout();
                },
                fileTypes: ['js']
            });
            filePicker.render();
            const el = $(this);
            _this.parent.showPopout({
                content: filePicker,
                attachTo: el,
                position: 'right'
            });
            e.stopPropagation(); // Most stop propagation here otherwise the popup will close
        })
            .on('keyup', function (e) {
            filePicker && filePicker.setFilter($(this).val());
        });
        return this.el;
    }
    onPropertyChanged(scope, el) {
        this.parent.setParameter(scope.name, el.val() === '' ? undefined : el.val());
        // Update current value and if it is default or not
        const current = this.getCurrentValue();
        el.val(current.value);
        this.isDefault = current.isDefault;
        el.blur();
    }
}

// EXTERNAL MODULE: ./src/editor/src/views/panels/propertyeditor/fontpicker.js
var fontpicker = __webpack_require__(63544);
;// ./src/editor/src/views/panels/propertyeditor/DataTypes/FontType.ts




function FontType_firstType(type) {
    return nodelibrary/* NodeLibrary */.m.nameForPortType(type);
}
class FontType extends TypeView {
    static fromPort(args) {
        const view = new FontType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        this.el = this.bindView(this.parent.cloneTemplate(FontType_firstType(this.type)), this);
        TypeView.prototype.render.call(this);
        let fontPicker;
        this.$('input')
            .on('focus', (e) => {
            e.stopPropagation();
        })
            .on('click', (e) => {
            fontPicker = new fontpicker/* default */.A({
                onItemSelected: (name) => {
                    this.$('input').val(name);
                    this.$('input').trigger('change');
                    this.parent.hidePopout();
                }
            });
            fontPicker.render();
            this.parent.showPopout({
                content: fontPicker,
                attachTo: this.el,
                position: 'right'
            });
            e.stopPropagation(); // Most stop propagation here otherwise the popup will close
        })
            .on('keyup', (e) => {
            fontPicker && fontPicker.setFilter(e.target.value);
        });
        return this.el;
    }
    onPropertyChanged(scope, el) {
        this.parent.setParameter(scope.name, el.val() === '' ? undefined : el.val());
        // Update current value and if it is default or not
        const current = this.getCurrentValue();
        el.val(current.value);
        this.isDefault = current.isDefault;
        el.blur();
    }
}

;// ./src/editor/src/views/panels/propertyeditor/iconpicker.jsx





// Styles
__webpack_require__(78447);
class IconPicker extends (external_react_default()).Component {
  constructor(props) {
    super(props);
    this.value = props.value || props.default;
    this.default = props.default;
    this.state = {
      iconSets: []
    };
  }
  componentDidMount() {
    // Look for icon modules
    IconPicker.LoadIconSets(iconSets => {
      this.setState({
        iconSets: iconSets
      });
    });
  }
  componentWillUnmount() {}
  onIconClicked(iconSet, icon) {
    this.props.onIconSelected && this.props.onIconSelected({
      codeAsClass: iconSet.codeAsClass,
      class: iconSet.iconClass,
      code: icon
    });
  }
  renderIconSet(set) {
    return /*#__PURE__*/external_react_default().createElement("div", {
      style: {
        display: 'flex',
        flexWrap: 'wrap',
        overflow: 'hidden',
        paddingLeft: '12px',
        paddingTop: '12px',
        paddingBottom: '12px'
      }
    }, set.icons.filter(icon => this.state.filter === undefined || icon.indexOf(this.state.filter) !== -1).map(icon => {
      let className = set.iconClass;
      let content = icon;
      if (set.codeAsClass) {
        className = [set.iconClass, icon].join(' ');
        content = undefined;
      }
      return /*#__PURE__*/external_react_default().createElement("span", {
        className: "iconpicker-icon",
        onClick: e => this.onIconClicked(set, icon)
      }, /*#__PURE__*/external_react_default().createElement(tooltip_Tooltip, {
        text: icon
      }, /*#__PURE__*/external_react_default().createElement("span", {
        className: className,
        style: {
          fontSize: '20px'
        }
      }, content)));
    }), /*#__PURE__*/external_react_default().createElement("div", {
      style: {
        width: '100%',
        height: '32px'
      }
    }));
  }
  renderIconSets() {
    return /*#__PURE__*/external_react_default().createElement("div", {
      style: {
        overflowY: 'overlay'
      }
    }, this.state.iconSets.map(set => /*#__PURE__*/external_react_default().createElement("div", {
      style: {
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
        flex: 1
      }
    }, /*#__PURE__*/external_react_default().createElement("div", {
      className: "iconpicker-iconset-header",
      style: {
        marginTop: '2px',
        marginBottom: '2px'
      }
    }, /*#__PURE__*/external_react_default().createElement("span", {
      className: "iconpicker-label"
    }, set.name, " ")), /*#__PURE__*/external_react_default().createElement("div", null, this.renderIconSet(set)))));
  }
  onSearchChanged(ev) {
    this.setState({
      filter: ev.target.value.toLowerCase()
    });
  }
  render() {
    return /*#__PURE__*/external_react_default().createElement("div", {
      className: "iconpicker-bg",
      style: {
        width: '470px',
        height: '370px',
        margin: '0px',
        padding: '0px',
        overflow: 'hidden',
        display: 'flex',
        flexDirection: 'column'
      }
    }, /*#__PURE__*/external_react_default().createElement("div", {
      className: "iconpicker-header"
    }, /*#__PURE__*/external_react_default().createElement("span", {
      className: "iconpicker-label"
    }, "Icon picker")), /*#__PURE__*/external_react_default().createElement("div", {
      className: "iconpicker-search-header",
      style: {
        display: 'flex',
        paddingRight: '5px',
        paddingTop: '5px',
        paddingBottom: '3px'
      }
    }, /*#__PURE__*/external_react_default().createElement("div", {
      style: {
        flexGrow: 0,
        width: '35px',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
      }
    }, /*#__PURE__*/external_react_default().createElement("i", {
      style: {
        verticalAlign: 'middle',
        margin: '0 auto'
      },
      className: "fa fa-search search-icon"
    })), /*#__PURE__*/external_react_default().createElement("input", {
      className: "iconpicker-search-input",
      style: {
        width: '100%',
        height: '26px'
      },
      onChange: this.onSearchChanged.bind(this)
    })), this.renderIconSets());
  }
}
IconPicker.LoadIconSets = function (cb) {
  projectmodel.ProjectModel.instance.listModules(modules => {
    var iconSets = [];
    modules.forEach(m => {
      if (m.manifest !== undefined && m.manifest.type == 'iconset') {
        // Install font module if not already installed
        var exists = document.querySelector('#ndl-iconset-styles-0-' + m.name);
        if (!exists) {
          if (m.manifest.browser && m.manifest.browser.stylesheets) {
            m.manifest.browser.stylesheets.forEach((sheet, idx) => {
              if (typeof sheet === 'string') {
                const stylesheet = document.createElement('link');
                stylesheet.id = 'ndl-iconset-styles-' + idx + '-' + m.name;
                if (sheet.startsWith('http')) {
                  stylesheet.href = sheet;
                } else {
                  stylesheet.href = src.filesystem.join(projectmodel.ProjectModel.instance._retainedProjectDirectory, sheet);
                }
                stylesheet.rel = 'stylesheet';
                document.head.appendChild(stylesheet);
              }
            });
          }
        }
        iconSets.push({
          name: m.manifest.name,
          icons: m.manifest.icons,
          iconClass: m.manifest.iconClass,
          codeAsClass: m.manifest.codeAsClass || false
        });
      }
    });
    cb(iconSets);
  });
};
/* harmony default export */ const iconpicker = (IconPicker);
;// ./src/editor/src/views/panels/propertyeditor/DataTypes/IconType.ts






function IconType_firstType(type) {
    return nodelibrary/* NodeLibrary */.m.nameForPortType(type);
}
class IconType extends TypeView {
    static fromPort(args) {
        const view = new IconType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        this.el = this.bindView(this.parent.cloneTemplate(IconType_firstType(this.type)), this);
        TypeView.prototype.render.call(this);
        if (this.value) {
            if (this.value.codeAsClass) {
                this.$('#iconThumbnail').attr('class', [this.value.class, this.value.code].join(' ')).text('');
            }
            else {
                this.$('#iconThumbnail').attr('class', this.value.class).text(this.value.code);
            }
        }
        iconpicker.LoadIconSets((iconsSets) => {
            // Just make sure all styles and fonts are loaded
        });
        // var iconPicker;
        /* this.$('input').on('focus', function (e) {
          e.stopPropagation();
        })
          .on('click', function (e) {
      
          })
          .on('keyup', function (e) {
          //  iconPicker && iconPicker.setFilter($(this).val());
          })*/
        return this.el;
    }
    onLaunchClicked(scope, el, evt) {
        // Show Icon picker
        const props = {
            value: this.value,
            onIconSelected: (icon) => {
                if (icon.codeAsClass) {
                    this.$('#iconThumbnail').attr('class', [icon.class, icon.code].join(' ')).text('');
                }
                else {
                    this.$('#iconThumbnail').attr('class', icon.class).text(icon.code);
                }
                this.parent.setParameter(scope.name, { class: icon.class, code: icon.code, codeAsClass: icon.codeAsClass });
                this.isDefault = false;
                this.parent.hidePopout();
            }
        };
        const div = document.createElement('div');
        const root = (0,client.createRoot)(div);
        root.render(external_react_default().createElement(iconpicker, props));
        this.parent.showPopout({
            content: {
                el: $(div)
            },
            attachTo: el,
            position: 'right'
        });
        evt.stopPropagation(); // Most stop propagation here otherwise the popup will close
    }
    // @ts-expect-error
    resetToDefault(scope, el) {
        this.$('#iconThumbnail').attr('class', '').text('');
    }
}
/*PropertyEditor.IconType.prototype.onPropertyChanged = function (scope, el) {
  this.parent.setParameter(scope.name, el.val() === '' ? undefined : el.val());

  // Update current value and if it is default or not
  var current = this.getCurrentValue();
  el.val(current.value);
  this.isDefault = current.isDefault;

  el.blur();
}*/

// EXTERNAL MODULE: ./src/editor/src/templates/propertyeditor/identifierpicker.html
var identifierpicker = __webpack_require__(93447);
var identifierpicker_default = /*#__PURE__*/__webpack_require__.n(identifierpicker);
;// ./src/editor/src/views/panels/propertyeditor/identifierpicker.js







var IdentifierPicker = function (args) {
  view_default().call(this);

  this.items = [];
  this.title = args.title;
  this.identifierType = args.identifierType;
  this.onItemSelected = args.onItemSelected;
};
IdentifierPicker.prototype = Object.create((view_default()).prototype);

IdentifierPicker.prototype.resize = function (layout) {
  this.el.css({
    position: 'absolute',
    left: layout.x + 'px',
    top: layout.y + 'px',
    width: layout.width + 'px',
    height: layout.height + 'px'
  });
};

IdentifierPicker.prototype.renderItems = function (appendTo) {
  var _this = this;

  if (!this.el) return;

  var appendTo = this.$('.identifierItems');
  appendTo.html('');

  this.items.sort(function (a, b) {
    return a.name > b.name ? -1 : 1;
  });

  function append(item) {
    appendTo.append(item.el);
    item.el.on('click', function () {
      _this.itemClicked(item);
    });
  }

  // Render all that match filter
  var folder;
  var inNewFolder = true;
  for (var i in this.items) {
    var item = this.items[i];

    if (
      this.pathFilter === undefined ||
      this.pathFilter === '' ||
      item.name.toLowerCase().indexOf(this.pathFilter) !== -1
    ) {
      append(item);
    }
  }
};

IdentifierPicker.prototype.setFilter = function (filter) {
  this.pathFilter = filter.toLowerCase();
  this.renderItems();
};

IdentifierPicker.prototype.render = function () {
  var _this = this;

  var el = this.bindView($((identifierpicker_default())), this);
  if (this.el) this.el.append(el);
  else this.el = el;

  var identifiers = {};
  projectmodel.ProjectModel.instance.forEachComponent(function (c) {
    c.forEachNode(function (n) {
      external_underscore_default().each(n.getPorts(), function (p) {
        if (typeof p.type === 'object' && p.type.name === 'string' && p.type.identifierOf === _this.identifierType) {
          var _id = n.parameters[p.name];
          if (_id !== undefined) identifiers[_id] = true;
        }
      });
    });
  });

  Object.keys(identifiers).forEach(function (_id) {
    var el = _this.bindView(_this.cloneTemplate('item'), { name: _id });
    _this.items.push({
      el: el,
      name: _id
    });
  });

  this.renderItems();

  return this.el;
};

IdentifierPicker.prototype.itemClicked = function (scope) {
  this.onItemSelected && this.onItemSelected(scope.name);
};

/* harmony default export */ const propertyeditor_identifierpicker = (IdentifierPicker);

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/IdentifierType.ts



class IdentifierType extends TypeView {
    static fromPort(args) {
        const view = new IdentifierType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.identifierType = p.type.identifierOf;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        const _this = this;
        this.el = this.bindView(this.parent.cloneTemplate('identifier'), this);
        TypeView.prototype.render.call(this);
        let identifierPicker;
        this.$('input')
            .on('focus', function (e) {
            e.stopPropagation();
        })
            .on('click', function (e) {
            identifierPicker = new propertyeditor_identifierpicker({
                title: _this.type.identifierDisplayName || 'Identifiers',
                identifierType: _this.identifierType,
                onItemSelected: function (name) {
                    _this.$('input').val(name);
                    _this.$('input').trigger('change');
                    _this.parent.hidePopout();
                }
            });
            identifierPicker.render();
            const el = $(this);
            _this.parent.showPopout({
                content: identifierPicker,
                attachTo: el,
                position: 'right'
            });
            e.stopPropagation(); // Most stop propagation here otherwise the popup will close
        })
            .on('keyup', function (e) {
            identifierPicker && identifierPicker.setFilter($(this).val());
        });
        return this.el;
    }
    onPropertyChanged(scope, el) {
        this.parent.setParameter(scope.name, el.val() === '' ? undefined : el.val());
        // Update current value and if it is default or not
        const current = this.getCurrentValue();
        el.val(current.value);
        this.isDefault = current.isDefault;
        el.blur();
    }
}

// EXTERNAL MODULE: ./src/editor/src/utils/thumbnailcache.js
var thumbnailcache = __webpack_require__(96397);
var thumbnailcache_default = /*#__PURE__*/__webpack_require__.n(thumbnailcache);
// EXTERNAL MODULE: ./src/editor/src/templates/propertyeditor/imagepicker.html
var imagepicker = __webpack_require__(30999);
var imagepicker_default = /*#__PURE__*/__webpack_require__.n(imagepicker);
;// ./src/editor/src/views/panels/propertyeditor/imagepicker.js








var ImagePicker = function (args) {
  view_default().call(this);

  this.items = [];
  this.onItemSelected = args.onItemSelected;
};
ImagePicker.prototype = Object.create((view_default()).prototype);

ImagePicker.prototype.resize = function (layout) {
  this.el.css({
    position: 'absolute',
    left: layout.x + 'px',
    top: layout.y + 'px',
    width: layout.width + 'px',
    height: layout.height + 'px'
  });
};

ImagePicker.prototype.renderItems = function () {
  var _this = this;

  if (!this.el) return;

  this.$('.imageItems').html('');

  this.items.sort(function (a, b) {
    if (a.folder === '/' && b.folder !== '/') return -1;
    if (b.folder === '/' && a.folder !== '/') return 1;
    return a.fullPath < b.fullPath ? -1 : 1;
  });

  function append(item) {
    _this.$('.imageItems').append(item.el);
    item.el.on('click', function () {
      _this.itemClicked(item);
    });
  }

  // Render all that match filter
  var folder;
  for (var i in this.items) {
    var item = this.items[i];

    if (item.folder !== folder) {
      folder = item.folder;
      if (folder !== '/') this.$('.imageItems').append('<div class="content-picker-group-label">' + folder + '</div>');
    }

    if (
      this.pathFilter === undefined ||
      this.pathFilter === '' ||
      item.fullPath.toLowerCase().indexOf(this.pathFilter) !== -1
    ) {
      append(item);
    }
  }
};

ImagePicker.prototype.setFilter = function (filter) {
  this.pathFilter = filter.toLowerCase();
  this.renderItems();
};

ImagePicker.prototype.render = function () {
  var _this = this;

  var el = this.bindView($((imagepicker_default())), this);
  if (this.el) this.el.append(el);
  else this.el = el;

  // Render image objects
  projectmodel.ProjectModel.instance.listFilesInProjectDirectory(
    function (files) {
      var filesLeft = 0;
      function fileCompleted() {
        if (--filesLeft === 0) _this.renderItems();
      }

      external_underscore_default().each(files, function (fileEntry) {
        filesLeft++;
        thumbnailcache_default().instance.getThumbnailForFile(fileEntry, function (thumbnail) {
          var pathInProjectFolder = fileEntry.fullPath.substring(
            projectmodel.ProjectModel.instance._retainedProjectDirectory.length + 1
          );
          var el = _this.bindView(_this.cloneTemplate('item'), {
            thumbnail: thumbnail ? thumbnail.dataUrl : undefined,
            name: fileEntry.name,
            fullPath: pathInProjectFolder
          });

          // Extract folder for image
          var folder = pathInProjectFolder.split('/');
          if (folder.length === 1) folder = '/';
          else folder = folder.splice(0, folder.length - 1).join('/');

          _this.items.push({
            el: el,
            name: fileEntry.name,
            fullPath: pathInProjectFolder,
            folder: folder,
            originalSize: thumbnail ? thumbnail.originalSize : undefined
          });
          fileCompleted();
        });
      });
    },
    ['png', 'jpeg', 'jpg', 'svg', 'gif', 'webp']
  );

  return this.el;
};

ImagePicker.prototype.itemClicked = function (scope) {
  this.onItemSelected && this.onItemSelected(scope.fullPath);
};

/* harmony default export */ const propertyeditor_imagepicker = (ImagePicker);

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/ImageType.ts




function ImageType_firstType(type) {
    return nodelibrary/* NodeLibrary */.m.nameForPortType(type);
}
class ImageType extends TypeView {
    static fromPort(args) {
        const view = new ImageType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        const _this = this;
        this.el = this.bindView(this.parent.cloneTemplate(ImageType_firstType(this.type)), this);
        TypeView.prototype.render.call(this);
        let imagePicker;
        this.$('input')
            .on('focus', function (e) {
            e.stopPropagation();
        })
            .on('click', function (e) {
            imagePicker = new propertyeditor_imagepicker({
                onItemSelected: function (name) {
                    _this.$('input').val(name);
                    _this.$('input').trigger('change');
                    _this.parent.hidePopout();
                    // _this.$('input').blur();
                }
            });
            //imagePicker.setFilter($(this).val());
            imagePicker.render();
            const el = $(this);
            _this.parent.showPopout({
                content: imagePicker,
                attachTo: el,
                position: 'right'
            });
            e.stopPropagation(); // Most stop propagation here otherwise the popup will close
        })
            .on('keyup', function (e) {
            imagePicker && imagePicker.setFilter($(this).val());
        });
        return this.el;
    }
    onPropertyChanged(scope, el) {
        this.parent.setParameter(scope.name, el.val() === '' ? undefined : el.val());
        // Update current value and if it is default or not
        const current = this.getCurrentValue();
        el.val(current.value);
        this.isDefault = current.isDefault;
        el.blur();
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/LogicBuilderHiddenType.ts


/**
 * Hidden editor type for internal Logic Builder parameters
 * Renders nothing - used for parameters that need to be stored
 * but should not appear in the property panel
 */
class LogicBuilderHiddenType extends TypeView {
    static fromPort(args) {
        const view = new LogicBuilderHiddenType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = null; // No group
        view.tooltip = p.tooltip;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        // Render an empty, invisible element
        // This is necessary because the property panel expects something to be returned
        // but we want it to take up no space
        this.el = $('<div style="display: none;"></div>');
        return this.el;
    }
    dispose() {
        // Nothing to clean up
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/propertyeditor/GeneratedCodeModal/GeneratedCodeModal.module.scss
var GeneratedCodeModal_module = __webpack_require__(36370);
;// ./src/editor/src/views/panels/propertyeditor/GeneratedCodeModal/GeneratedCodeModal.module.scss

      
      
      
      
      
      
      
      
      

var GeneratedCodeModal_module_options = {};

GeneratedCodeModal_module_options.styleTagTransform = (styleTagTransform_default());
GeneratedCodeModal_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      GeneratedCodeModal_module_options.insert = insertBySelector_default().bind(null, "head");
    
GeneratedCodeModal_module_options.domAPI = (styleDomAPI_default());
GeneratedCodeModal_module_options.insertStyleElement = (insertStyleElement_default());

var GeneratedCodeModal_module_update = injectStylesIntoStyleTag_default()(GeneratedCodeModal_module/* default */.A, GeneratedCodeModal_module_options);




       /* harmony default export */ const GeneratedCodeModal_GeneratedCodeModal_module = (GeneratedCodeModal_module/* default */.A && GeneratedCodeModal_module/* default */.A.locals ? GeneratedCodeModal_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/propertyeditor/GeneratedCodeModal/GeneratedCodeModal.tsx
/**
 * GeneratedCodeModal
 *
 * A read-only modal for viewing generated code from Logic Builder.
 * Uses the CodeMirror-based JavaScriptEditor in read-only mode.
 */






/**
 * Read-only modal for viewing generated JavaScript code
 */
function GeneratedCodeModal({ isOpen, nodeName, code, onClose }) {
    const codeRef = (0,external_react_.useRef)(code);
    // Keep code ref updated
    (0,external_react_.useEffect)(() => {
        codeRef.current = code;
    }, [code]);
    // Handle keyboard shortcuts
    const handleKeyDown = (0,external_react_.useCallback)((e) => {
        if (!isOpen)
            return;
        if (e.key === 'Escape') {
            onClose();
        }
    }, [isOpen, onClose]);
    (0,external_react_.useEffect)(() => {
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [handleKeyDown]);
    // Handle copy to clipboard
    const handleCopy = (0,external_react_.useCallback)(() => {
        if (codeRef.current) {
            navigator.clipboard.writeText(codeRef.current).then(() => {
                console.log('[GeneratedCodeModal] Code copied to clipboard');
            }, (err) => {
                console.error('[GeneratedCodeModal] Failed to copy code:', err);
            });
        }
    }, []);
    if (!isOpen)
        return null;
    const displayCode = code || '// No code generated yet.\n// Add some blocks in the Logic Builder and close the editor.';
    // Render into portal to escape any z-index issues
    return external_react_dom_default().createPortal(external_react_default().createElement("div", { className: GeneratedCodeModal_GeneratedCodeModal_module['Overlay'], onClick: onClose },
        external_react_default().createElement("div", { className: GeneratedCodeModal_GeneratedCodeModal_module['Modal'], onClick: (e) => e.stopPropagation() },
            external_react_default().createElement("div", { className: GeneratedCodeModal_GeneratedCodeModal_module['Header'] },
                external_react_default().createElement("span", { className: GeneratedCodeModal_GeneratedCodeModal_module['Title'] },
                    "Generated Code: ",
                    nodeName),
                external_react_default().createElement("span", { className: GeneratedCodeModal_GeneratedCodeModal_module['ReadOnlyBadge'] }, "Read-Only")),
            external_react_default().createElement("div", { className: GeneratedCodeModal_GeneratedCodeModal_module['InfoBar'] },
                external_react_default().createElement("span", { className: GeneratedCodeModal_GeneratedCodeModal_module['InfoText'] }, "This is the JavaScript generated from your logic blocks. You can copy it but not edit it directly.")),
            external_react_default().createElement("div", { className: GeneratedCodeModal_GeneratedCodeModal_module['Body'] },
                external_react_default().createElement("div", { className: GeneratedCodeModal_GeneratedCodeModal_module['EditorWrapper'] },
                    external_react_default().createElement(JavaScriptEditor, { value: displayCode, onChange: () => { }, validationType: "script", height: 400, width: 700, disabled: true }))),
            external_react_default().createElement("div", { className: GeneratedCodeModal_GeneratedCodeModal_module['Footer'] },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Copy Code", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, icon: common_Icon/* IconName */.$M.Copy, onClick: handleCopy, isDisabled: !code }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Close", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Cta, onClick: onClose })))), document.body);
}

;// ./src/editor/src/views/panels/propertyeditor/GeneratedCodeModal/index.ts


;// ./src/editor/src/views/panels/propertyeditor/DataTypes/LogicBuilderWorkspaceType.ts






/**
 * Custom editor for Logic Builder workspace parameter
 * Shows an "Edit Blocks" button that opens the Blockly editor in a tab
 * And a "View Generated Code" button to show the compiled JavaScript
 */
class LogicBuilderWorkspaceType extends TypeView {
    constructor() {
        super(...arguments);
        this.modalContainer = null;
        this.modalRoot = null;
        this.isModalOpen = false;
    }
    static fromPort(args) {
        const view = new LogicBuilderWorkspaceType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = null; // Hide group label
        view.tooltip = p.tooltip;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        // Hide empty group labels
        const hideEmptyGroupsCSS = `
      <style>
        /* Hide empty group labels */
        .property-editor-group-name:empty {
          display: none !important;
        }
      </style>
    `;
        // Create a simple container with two buttons
        const html = hideEmptyGroupsCSS +
            `
      <div class="property-basic-container logic-builder-workspace-editor" style="display: flex; flex-direction: column; gap: 8px;">
        <button class="edit-blocks-button" 
                style="
                  padding: 8px 16px;
                  background: var(--theme-color-primary);
                  color: white;
                  border: none;
                  border-radius: 4px;
                  cursor: pointer;
                  font-size: 13px;
                  font-weight: 500;
                  transition: background-color 0.2s;
                "
                onmouseover="this.style.backgroundColor='var(--theme-color-primary-hover)'"
                onmouseout="this.style.backgroundColor='var(--theme-color-primary)'">
          Edit Logic Blocks
        </button>
        <button class="view-code-button" 
                style="
                  padding: 8px 16px;
                  background: var(--theme-color-bg-3);
                  color: var(--theme-color-fg-default);
                  border: 1px solid var(--theme-color-border-default);
                  border-radius: 4px;
                  cursor: pointer;
                  font-size: 13px;
                  font-weight: 500;
                  transition: background-color 0.2s;
                "
                onmouseover="this.style.backgroundColor='var(--theme-color-bg-4)'"
                onmouseout="this.style.backgroundColor='var(--theme-color-bg-3)'">
          View Generated Code
        </button>
      </div>
    `;
        this.el = this.bindView($(html), this);
        // Get references to buttons
        this.editButton = this.el.find('.edit-blocks-button');
        this.viewCodeButton = this.el.find('.view-code-button');
        // Handle button clicks
        this.editButton.on('click', () => {
            this.onEditBlocksClicked();
        });
        this.viewCodeButton.on('click', () => {
            this.onViewCodeClicked();
        });
        // Call parent render for common functionality (tooltips, etc.)
        TypeView.prototype.render.call(this);
        // Show/hide the "changed" dot based on whether value is default
        this.updateChangedDot();
        return this.el;
    }
    onEditBlocksClicked() {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
        // ModelProxy wraps the actual node model in a .model property
        const nodeId = (_c = (_b = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.model) === null || _b === void 0 ? void 0 : _b.model) === null || _c === void 0 ? void 0 : _c.id;
        const nodeName = ((_f = (_e = (_d = this.parent) === null || _d === void 0 ? void 0 : _d.model) === null || _e === void 0 ? void 0 : _e.model) === null || _f === void 0 ? void 0 : _f.label) || ((_j = (_h = (_g = this.parent) === null || _g === void 0 ? void 0 : _g.model) === null || _h === void 0 ? void 0 : _h.type) === null || _j === void 0 ? void 0 : _j.displayName) || 'Logic Builder';
        const workspace = ((_l = (_k = this.parent) === null || _k === void 0 ? void 0 : _k.model) === null || _l === void 0 ? void 0 : _l.getParameter('workspace')) || '';
        console.log('[LogicBuilderWorkspaceType] Opening Logic Builder tab for node:', nodeId);
        // Emit event to open Logic Builder tab
        EventDispatcher.EventDispatcher.instance.emit('LogicBuilder.OpenTab', {
            nodeId,
            nodeName,
            workspace
        });
    }
    onViewCodeClicked() {
        var _a, _b, _c, _d, _e, _f, _g, _h;
        const nodeName = ((_c = (_b = (_a = this.parent) === null || _a === void 0 ? void 0 : _a.model) === null || _b === void 0 ? void 0 : _b.model) === null || _c === void 0 ? void 0 : _c.label) || ((_f = (_e = (_d = this.parent) === null || _d === void 0 ? void 0 : _d.model) === null || _e === void 0 ? void 0 : _e.type) === null || _f === void 0 ? void 0 : _f.displayName) || 'Logic Builder';
        const generatedCode = ((_h = (_g = this.parent) === null || _g === void 0 ? void 0 : _g.model) === null || _h === void 0 ? void 0 : _h.getParameter('generatedCode')) || '';
        console.log('[LogicBuilderWorkspaceType] Opening generated code modal for node:', nodeName);
        this.showModal(nodeName, generatedCode);
    }
    showModal(nodeName, code) {
        // Create modal container if it doesn't exist
        if (!this.modalContainer) {
            this.modalContainer = document.createElement('div');
            this.modalContainer.id = 'generated-code-modal-container';
            document.body.appendChild(this.modalContainer);
            this.modalRoot = (0,client.createRoot)(this.modalContainer);
        }
        this.isModalOpen = true;
        this.renderModal(nodeName, code);
    }
    hideModal() {
        this.isModalOpen = false;
        this.renderModal('', '');
    }
    renderModal(nodeName, code) {
        if (!this.modalRoot)
            return;
        this.modalRoot.render(external_react_default().createElement(GeneratedCodeModal, {
            isOpen: this.isModalOpen,
            nodeName: nodeName,
            code: code,
            onClose: () => this.hideModal()
        }));
    }
    updateChangedDot() {
        const dot = this.el.find('.property-changed-dot');
        if (this.isDefault) {
            dot.hide();
        }
        else {
            dot.show();
        }
    }
    resetToDefault() {
        // Reset workspace to empty
        this.parent.model.setParameter(this.name, undefined, {
            undo: true,
            label: 'reset workspace'
        });
        this.isDefault = true;
        this.updateChangedDot();
    }
    dispose() {
        // Clean up modal when view is disposed
        if (this.modalRoot) {
            this.modalRoot.unmount();
            this.modalRoot = null;
        }
        if (this.modalContainer && this.modalContainer.parentNode) {
            this.modalContainer.parentNode.removeChild(this.modalContainer);
            this.modalContainer = null;
        }
    }
}

// EXTERNAL MODULE: ./src/editor/src/templates/propertyeditor/marginpaddingview.html
var marginpaddingview = __webpack_require__(35646);
var marginpaddingview_default = /*#__PURE__*/__webpack_require__.n(marginpaddingview);
;// ./src/editor/src/views/panels/propertyeditor/marginpaddingview.js




var MarginPaddingView = function (args) {
  view_default().call(this);

  this.onUpdate = args.onUpdate;

  this.defaults = args.defaults;
  this.values = args.values;

  this.isDefault = args.isDefault;
};
MarginPaddingView.prototype = Object.create((view_default()).prototype);

MarginPaddingView.prototype.render = function () {
  var _this = this;

  // Component inputs will have output ports, and vice versa
  this.el = this.bindView($((marginpaddingview_default())), this);

  // Render units dropdown
  this.$('.property-input-dropdown').html('');
  var units = ['px', '%'];
  for (var i in units) {
    this.$('.property-input-dropdown').append(
      this.bindView(
        $(
          '<div class="property-number-unit-enum" data-click="onUnitChanged" data-value="' +
            units[i] +
            '">' +
            units[i] +
            '</div>'
        )
      )
    );
  }

  this.$('.property-input-dropdown').on('mousedown', function (event) {
    event.preventDefault(); // make sure drop down doesn't blur input until after "onPropertyChanged" has been triggered
  });

  this.$('.property-number-units').on('blur', function () {
    _this.$('.property-input-dropdown').hide();
  });

  this.$('input')
    .on('click', function (evt) {
      evt.stopPropagation();
    })
    .on('keyup', function (evt) {
      if (evt.keyCode === 13) {
        _this.$('#editbox').hide();
        _this.editInProgress = undefined;
      }
    });

  var dragComp, dragX, dragY, dragStartValue;
  this.$('.drag-handle').on('mousedown', function (e) {
    dragComp = $(this).attr('data-comp');
    dragX = e.pageX;
    dragY = e.pageY;
    var v = _this.values[dragComp] || _this.defaults[dragComp];
    dragStartValue = { value: v.value || 0, unit: v.unit };
  });

  this._onMouseMove = (e) => {
    if (dragComp) {
      var dx = e.pageX - dragX,
        dy = dragY - e.pageY;

      var v = Math.round(dragStartValue.value + (dx + dy) * 0.33);
      this.values[dragComp] = { value: v, unit: dragStartValue.unit };

      this.isDefault = false;
      this.onUpdate && this.onUpdate(dragComp, this.values[dragComp], { drag: true });

      this.updateValues();
    }
  };

  this._onMouseUp = (e) => {
    if (dragComp) {
      this.onUpdate && this.onUpdate(dragComp, this.values[dragComp], { oldValue: dragStartValue });
      dragComp = undefined;
      e.stopPropagation();
    }
  };

  document.addEventListener('mousemove', this._onMouseMove);
  document.addEventListener('mouseup', this._onMouseUp);

  var changedToolTipTimeout;
  this.$('.property-changed-dot')
    .on('click', function () {
      clearTimeout(changedToolTipTimeout);
      Object.keys(_this.defaults).forEach((comp) => {
        if (_this.values[comp] !== undefined) {
          _this.values[comp] = undefined;
          _this.onUpdate(comp, undefined);
        }
      });
      _this.updateValues();
      _this.isDefault = true;
    })
    .on('mouseenter', function () {
      var _el = this;
      changedToolTipTimeout = setTimeout(function () {
        popuplayer_default().instance.showTooltip({
          x: $(_el).offset().left + $(_el).outerWidth(),
          y: $(_el).offset().top + $(_el).outerHeight() / 2,
          position: 'right',
          content: 'Reset to default'
        });
      }, 1000);
    })
    .on('mouseleave', function () {
      popuplayer_default().instance.hideTooltip();
    });

  this.updateValues();

  return this.el;
};

MarginPaddingView.prototype.dispose = function () {
  document.removeEventListener('mousemove', this._onMouseMove);
  document.removeEventListener('mouseup', this._onMouseUp);
};

MarginPaddingView.prototype.onDropDownClicked = function (scope, el, evt) {
  var showShould = !this.$('.property-input-dropdown').is(':visible');
  if (showShould) {
    this.$('.property-number-units')[0].focus();
    this.$('.property-input-dropdown').show();
  }

  evt.stopPropagation();
};

MarginPaddingView.prototype.onUnitChanged = function (scope, el, evt) {
  var unit = el.attr('data-value');
  this.$('[data-text=unit]').text(unit);

  this.$('.property-input-dropdown').hide();

  this.updateValues();

  evt.stopPropagation();
};

MarginPaddingView.prototype.onPropertyChanged = function (scope, el) {
  this.updateValues();

  this.editInProgress = undefined;
};

MarginPaddingView.prototype.updateValues = function () {
  // Extract values from edit
  if (this.editInProgress) {
    var _value = parseFloat(this.$('input').val());
    var value = isNaN(_value) ? undefined : _value;
    var unit = this.$('[data-text=unit]').text();

    if (value !== undefined) {
      this.values[this.editInProgress] = {
        value: value,
        unit: unit
      };
    } else {
      this.values[this.editInProgress] = undefined;
    }

    this.isDefault = false;
    this.onUpdate && this.onUpdate(this.editInProgress, this.values[this.editInProgress]);
  }

  for (var key in this.defaults) {
    var v = this.values[key] || this.defaults[key];
    var _el = this.$('[data-comp=' + key + ']');

    const value = v.value === undefined ? '-' : v.value;
    _el.text(value + ' ' + v.unit);

    _el.removeClass('changed');
    if (this.values[key] !== undefined) _el.addClass('changed');
  }
};

MarginPaddingView.prototype.onLabelClicked = function (scope, el) {
  this.$('#editbox').show();

  var editBoxWidth = 110;
  var editBoxHeight = 35;

  var containerWidth = this.el.outerWidth();

  var x = $(el).offset().left + $(el).outerWidth() / 2 - this.el.offset().left - editBoxWidth / 2;
  var y = $(el).offset().top + $(el).outerHeight() / 2 - this.el.offset().top - editBoxHeight / 2;

  if (x + editBoxWidth + 2 > containerWidth) x = containerWidth - editBoxWidth - 2;
  if (x < 0) x = 2;

  this.$('#editbox-editor').css({
    top: y + 'px',
    left: x + 'px',
    width: editBoxWidth + 'px',
    height: editBoxHeight + 'px'
  });

  var comp = el.attr('data-comp');
  this.editInProgress = comp;

  var v = this.values[comp] || this.defaults[comp];
  if (this.values[comp]) this.$('input').val(this.values[comp].value);
  else {
    this.$('input').val('');
    this.$('input').attr('placeholder', this.defaults[comp].value);
  }
  this.$('input').focus();
  this.$('[data-text=unit]').text(v.unit);
};

MarginPaddingView.prototype.onHideEditBoxClicked = function (scope, el) {
  this.$('#editbox').hide();
  this.editInProgress = undefined;
};

/* harmony default export */ const propertyeditor_marginpaddingview = (MarginPaddingView);

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/MarginPaddingType.ts


class MarginPaddingType extends TypeView {
    constructor() {
        super();
        this.defaults = {};
        this.values = {};
        this.ports = {};
    }
    static fromPort(args) {
        const p = args.port;
        const parent = args.parent;
        const toolTypeId = 'marginsandpadding-' + p.group;
        if (!parent._toolsType[toolTypeId]) {
            const view = (parent._toolsType[toolTypeId] = new MarginPaddingType());
            view.parent = parent;
            view.group = p.group;
            view.isDefault = true;
            view.addComponentPort(p);
            return view;
        }
        else {
            parent._toolsType[toolTypeId].addComponentPort(p);
        }
    }
    render() {
        const _this = this;
        this.marginPaddingView = new propertyeditor_marginpaddingview({
            values: this.values,
            defaults: this.defaults,
            isDefault: this.isDefault,
            onUpdate: (comp, value, opts) => {
                const undoArgs = {
                    undo: true,
                    label: 'margin or padding changed',
                    oldValue: opts ? opts.oldValue : undefined
                };
                this.parent.model.setParameter(this.ports[comp].name, value, opts && opts.drag ? undefined : undoArgs);
                // Update the default value in case we are resetting
                const defaultValue = this.parent.model.getParameter(this.ports[comp].name);
                if (typeof defaultValue === 'object') {
                    this.defaults[comp] = defaultValue;
                }
                else {
                    this.defaults[comp] = { value: defaultValue, unit: this.ports[comp].type.defaultUnit };
                }
            }
        });
        this.marginPaddingView.render();
        this.el = this.marginPaddingView.el;
        return this.el;
    }
    dispose() {
        TypeView.prototype.dispose.call(this);
        this.marginPaddingView && this.marginPaddingView.dispose();
    }
    addComponentPort(p) {
        const comp = p.type.marginPaddingComp;
        this.ports[comp] = p;
        let value = this.parent.model.parameters[p.name];
        if (typeof value === 'number')
            value = { value: value, unit: p.type.defaultUnit };
        this.values[comp] = value;
        this.isDefault = this.isDefault && this.parent.model.parameters[p.name] === undefined;
        const defaultValue = this.parent.model.getParameter(p.name);
        if (typeof defaultValue === 'object') {
            this.defaults[comp] = defaultValue;
        }
        else {
            this.defaults[comp] = { value: defaultValue, unit: p.type.defaultUnit };
        }
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/NumberWithUnits.ts


function NumberWithUnits_parseNumberWithUnit(stringValue, permittedUnits) {
    let value = parseFloat(stringValue);
    if (isNaN(value)) {
        value = undefined;
    }
    let unit;
    permittedUnits.some((u) => {
        if (stringValue.endsWith(u)) {
            unit = u;
            return true;
        }
        return false;
    });
    return {
        value,
        unit
    };
}
class NumberWithUnits extends TypeView {
    static fromPort(args) {
        const view = new NumberWithUnits();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.tooltip = p.tooltip;
        view.numberWithUnits = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    // @ts-expect-error
    get value() {
        return typeof this.numberWithUnits === 'object' ? this.numberWithUnits.value : this.numberWithUnits;
    }
    get unit() {
        return typeof this.numberWithUnits === 'object' ? this.numberWithUnits.unit : this.type.defaultUnit;
    }
    render() {
        const _this = this;
        this.el = this.bindView(this.parent.cloneTemplate('number-units'), this);
        TypeView.prototype.render.call(this);
        // Render units dropdown
        this.$('.property-input-dropdown').html('');
        const units = this.type.units;
        for (const i in units) {
            this.$('.property-input-dropdown').append(this.bindView($('<div class="property-number-unit-enum" data-click="onUnitChanged" data-value="' +
                units[i] +
                '">' +
                units[i] +
                '</div>')));
        }
        this.$('.property-input-dropdown').on('mousedown', function (event) {
            event.preventDefault(); // make sure drop down doesn't blur input until after "onPropertyChanged" has been triggered
        });
        this.$('.property-number-units').on('blur', function () {
            _this.$('.property-input-dropdown').hide();
        });
        return this.el;
    }
    onDropDownClicked(scope, el) {
        const showShould = !this.$('.property-input-dropdown').is(':visible');
        this.parent.$('.property-input-dropdown').hide();
        if (showShould) {
            this.$('.property-number-units')[0].focus();
            this.$('.property-input-dropdown').show();
        }
        // Hide show the padding so drop downs can be scrolled to if at the bottom of the prop editor
        this.parent.$('.property-drop-down-padding').hide();
        showShould && this.parent.$('.property-drop-down-padding').show();
        this.parent.notifyListeners('panelResized');
    }
    updateValue() {
        const v = NumberWithUnits_parseNumberWithUnit(this.$('input').val(), this.type.units);
        const value = v.value;
        const unit = v.unit ? v.unit : this.$('[data-text=unit]').text();
        // If the input is not a valid value, then set undefined
        if (value !== undefined)
            this.parent.setParameter(this.name, {
                value: value,
                unit: unit ? unit : this.type.defaultUnit
            });
        else
            this.parent.setParameter(this.name, undefined);
        // Update current value and if it is default or not
        const current = this.getCurrentValue();
        this.numberWithUnits = current.value;
        this.$('input').val(this.value);
        this.$('[data-text=unit]').text(this.unit);
        this.isDefault = current.isDefault;
    }
    resetToDefault() {
        const current = this.getCurrentValue();
        this.numberWithUnits = current.value;
        this.$('input').val(this.value);
        this.$('[data-text=unit]').text(this.unit);
    }
    onUnitChanged(scope, el) {
        const unit = el.attr('data-value');
        this.$('[data-text=unit]').text(unit);
        this.updateValue();
    }
    onPropertyChanged(scope, el) {
        this.updateValue();
        el.blur();
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/PopoutGroup.ts


class PopoutGroup extends (view_default()) {
    constructor(args) {
        super();
        this.group = args.group;
        this.popoutGroup = args.popoutGroup;
        this.label = args.label;
        this.parent = args.parent;
    }
    render() {
        this.el = this.bindView(this.parent.cloneTemplate('popout-group'), this);
        return this.el;
    }
    onPopoutClicked(scope, el, evt) {
        this.view = new Ports({
            model: this.parent.model,
            popout: this.popoutGroup
        });
        this.view.render();
        this.view.el.css({ width: '300px', overflowY: 'auto' });
        this.parent.showPopout({
            content: this.view,
            attachTo: el,
            position: 'right',
            onClose: () => {
                this.view && this.view.dispose();
            }
        });
        evt.stopPropagation();
    }
    dispose() {
        this.view && this.view.dispose();
    }
}

// EXTERNAL MODULE: ./src/editor/src/templates/propertyeditor/proplist.html
var proplist = __webpack_require__(46583);
var proplist_default = /*#__PURE__*/__webpack_require__.n(proplist);
;// ./src/editor/src/views/panels/propertyeditor/proplist.js





// Styles
__webpack_require__(48541);

class PropList extends (view_default()) {
  constructor(args) {
    super();

    this.parent = args.parent;
    this.list = args.list || [];
    this.type = args.type;
    this.plug = args.plug;
    this.title = args.title;
    this.group = args.group;
    this.isDefault = args.isDefault;
    this.onUpdate = args.onUpdate;
    this.childViews = args.childViews;
  }

  render() {
    // Component inputs will have output ports, and vice versa
    this.el = this.bindView($((proplist_default())), this);

    this.renderItems();

    this.parent && this.parent.append(this.el);

    return this.el;
  }

  listUpdated() {
    if (this.onUpdate) {
      var updated = this.onUpdate(this.list);
      if (updated) {
        this.list = updated.value || [];
        this.isDefault = updated.isDefault;
      }
    }
    this.renderItems();
  }

  renderItems() {
    this.$('.items').html('');

    this.itemForRef = {};
    for (var i in this.list) {
      var p = this.list[i];

      var compEl = this.bindView(this.cloneTemplate('item'), {
        id: p.id,
        name: p.label,
        index: i,
        isDefault: this.isDefault
      });

      this.childViews.forEach((view) => {
        // Insert child views
        if (view.port.parentItemId === p.id) compEl.find('.props').append(view.el);
      });
      this._makeDraggable(compEl, { label: p.label, item: p });
      this._makeDroppable(compEl, p);
      this.$('.items').append(compEl);
    }
  }

  _dropOnItem(args) {
    var sourceIdx = this.list.indexOf(args.source);
    this.list.splice(sourceIdx, 1); // Remove source

    var targetIdx = this.list.indexOf(args.target);
    this.list.splice(args.below ? targetIdx + 1 : targetIdx, 0, args.source);
    this.listUpdated();
  }

  _makeDraggable(el, args) {
    var _this = this;
    var mouseDownOnItem = false;

    el.find('.drag-handle').on('mousedown', function (e) {
      mouseDownOnItem = true;
    });
    el.find('.drag-handle').on('mouseup', function (e) {
      mouseDownOnItem = false;
    });
    el.find('.drag-handle').on('mousemove', function (e) {
      if (mouseDownOnItem) {
        popuplayer_default().instance.startDragging({
          label: args.label,
          item: args.item
        });
        mouseDownOnItem = false;
      }
    });
  }

  _makeDroppable(el, item) {
    el.on('mousemove', function (e) {
      if (popuplayer_default().instance.isDragging()) {
        var dragItem = (popuplayer_default()).instance.dragItem;

        if (dragItem.item === item) {
          // Can't drop on yourself
          popuplayer_default().instance.indicateDropType('none');
        } else {
          var rect = el[0].getBoundingClientRect();
          var h = el.outerHeight();
          if (e.clientY - rect.top > h / 2) {
            el.find('.drop-above-indicator').first().hide();
            el.find('.drop-below-indicator').first().show();
          } else {
            el.find('.drop-above-indicator').first().show();
            el.find('.drop-below-indicator').first().hide();
          }
          popuplayer_default().instance.indicateDropType('move');
        }
      }
    });
    el.on('mouseout', function (e) {
      el.find('.drop-above-indicator').first().hide();
      el.find('.drop-below-indicator').first().hide();
      popuplayer_default().instance.indicateDropType('none');
    });
    el.on('mouseup', (e) => {
      var dragItem = (popuplayer_default()).instance.dragItem;

      if (dragItem && dragItem.item !== item) {
        var rect = el[0].getBoundingClientRect();
        var h = el.outerHeight();

        this._dropOnItem({
          target: item,
          source: dragItem.item,
          below: e.clientY - rect.top > h / 2
        });

        popuplayer_default().instance.dragCompleted();
      }
    });
  }

  onAddPortClicked(scope, el, evt) {
    var _this = this;

    if (this.type.autoName !== undefined) {
      var result = _this.performAdd(this.type.autoName, true);
      if (!result.success) {
        ToastLayer.ToastLayer.showError(result.message);
      }
      evt.stopPropagation();
      return;
    }

    var popup = new (popuplayer_default()).StringInputPopup({
      label: 'New entry',
      okLabel: 'Add',
      cancelLabel: 'Cancel',
      onOk: function (name) {
        var result = _this.performAdd(name);
        if (!result.success) {
          ToastLayer.ToastLayer.showError(result.message);
        }
      }
    });
    popup.render();

    popuplayer_default().instance.showPopup({
      content: popup,
      attachTo: el,
      position: 'top'
    });

    evt.stopPropagation();
  }

  _guid() {
    while (true) {
      var uid = ('0000' + ((Math.random() * Math.pow(36, 4)) | 0).toString(36)).slice(-4);
      if (this.list.find((item) => item.id === uid) === undefined) {
        return uid;
      }
    }
  }

  performAdd(name, _makeUnique) {
    if (_makeUnique) {
      // Find a unique name by adding index at the end
      let idx = 2,
        uniqueName = name + ' ' + 1;
      while (this.list.find((item) => item.label === uniqueName) !== undefined) {
        uniqueName = name + ' ' + idx;
        idx++;
      }
      name = uniqueName;
    }

    if (name === '') {
      return { success: false, message: 'Entry name cannot be empty' };
    } else if (this.list.find((item) => item.label === name) !== undefined) {
      return { success: false, message: 'Cannot create an entry with the same name as an existing one.' };
    } else {
      this.list.push({
        id: this._guid(),
        label: name
      });
      this.listUpdated();

      return { success: true };
    }
  }

  performRename(args) {
    if (args.newName === '') {
      return { success: false, message: 'Entry name cannot be empty' };
    } else if (this.list.find((item) => item.label === args.newName) !== undefined) {
      // Show alert that component cannot have same name as an
      // existing component
      return { success: false, message: 'Entry with that name already exists.' };
    } else {
      var item = this.list.find((item) => item.label === args.oldName);
      item.label = args.newName;
      this.listUpdated();

      return { success: true };
    }
  }

  onRenameClicked(scope, el, evt) {
    var _this = this;

    var header = el.parents('.header');
    header.find('.show-on-edit').show();
    header.find('.hide-on-edit').hide();

    function rename() {
      var newName = input.val();
      if (newName !== scope.name) {
        var result = _this.performRename({
          newName: newName,
          oldName: scope.name
        });

        if (!result.success) {
          ToastLayer.ToastLayer.showError(result.message);
        }
      }

      header.find('.show-on-edit').hide();
      header.find('.hide-on-edit').show();
      input.off('blur').off('keypress'); // Make sure rename doesn't get called twice
    }

    var input = header.find('input');
    input
      .focus()
      .off('blur')
      .on('blur', function () {
        rename();
      })
      .off('keypress')
      .on('keypress', function (e) {
        if (e.which == 13) rename();
      });

    evt.stopPropagation();
  }

  performDelete(itemId) {
    var item = this.list.find((i) => i.id === itemId);
    if (item === undefined) return;
    var idx = this.list.indexOf(item);
    if (idx !== -1) this.list.splice(idx, 1);
    this.listUpdated();

    return { success: true };
  }

  onDeleteClicked(scope, el, evt) {
    var result = this.performDelete(scope.id);

    if (!result.success) {
      ToastLayer.ToastLayer.showError(result.message);
    }

    evt.stopPropagation();
  }
}

/* harmony default export */ const propertyeditor_proplist = (PropList);

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/PropListType.ts



class PropListType extends TypeView {
    constructor() {
        super();
        this.childViews = [];
    }
    static fromPort(args) {
        const view = new PropListType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        if (parent.model.parameters[p.name] === '')
            parent.model.parameters[p.name] = undefined;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        // view.isConnected = parent.model.isPortConnected(p.name,'target');
        // view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        const _this = this;
        this.listView = new propertyeditor_proplist({
            title: this.displayName,
            list: this.value,
            isDefault: _this.parent.model.parameters[_this.name] === undefined,
            childViews: this.childViews,
            type: this.type,
            onUpdate: function (newValue) {
                if (newValue === '')
                    newValue = undefined;
                _this.parent.setParameter(_this.name, newValue);
                _this.parent.notifyListeners('panelResized');
                return {
                    value: _this.parent.model.getParameter(_this.name),
                    isDefault: _this.parent.model.parameters[_this.name] === undefined
                };
            }
        });
        this.listView.render();
        this.el = this.listView.el;
        return this.el;
    }
    addChildTypeView(child) {
        this.childViews.push(child);
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryRulePopup/QueryRulePopup.tsx

function QueryRulePopup({ title, children, onDeleteClicked }) {
    return (external_react_default().createElement("div", { className: "queryeditor-popup" },
        external_react_default().createElement("div", { className: "queryeditor-header" }, title),
        external_react_default().createElement("div", { className: "queryeditor-content" },
            external_react_default().createElement("div", { className: "queryeditor-rule" }, children),
            external_react_default().createElement("div", { className: "queryeditor-trash-icon", onClick: onDeleteClicked }))));
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryRulePopup/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/RuleDropdown/RuleDropdown.tsx

function RuleDropdown({ label, value, dropdownItems, onItemSelected }) {
    const [showDropdown, setShowDropdown] = (0,external_react_.useState)(false);
    return (external_react_default().createElement("div", { className: "queryeditor-component hoverable", onClick: () => setShowDropdown(!showDropdown) },
        external_react_default().createElement("div", { className: "queryeditor-property-inner" },
            external_react_default().createElement("div", { className: "queryeditor-property-label" }, label),
            value),
        external_react_default().createElement("i", { className: "queryeditor-caret-icon fa fa-caret-down" }),
        showDropdown ? (external_react_default().createElement("div", { className: "queryeditor-dropdown" }, dropdownItems.map((p) => (external_react_default().createElement("div", { key: p, className: "queryeditor-dropdown-item", onClick: (e) => {
                onItemSelected(p);
                setShowDropdown(false);
                e.stopPropagation();
            } }, p))))) : null));
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/RuleDropdown/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/RuleInput/RuleInput.tsx

function RuleInput({ label, value, onChange }) {
    const [inputValue, setInputValue] = (0,external_react_.useState)('');
    (0,external_react_.useEffect)(() => {
        setInputValue(value || '');
    }, [value]);
    return (external_react_default().createElement("div", { className: "queryeditor-component" },
        external_react_default().createElement("div", { className: "queryeditor-property-inner" },
            external_react_default().createElement("div", { className: "queryeditor-property-label" }, label),
            external_react_default().createElement("input", { className: "queryeditor-value-input", value: inputValue, onChange: (e) => {
                    onChange(e.target.value);
                    setInputValue(e.target.value);
                } }))));
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/RuleInput/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/utils.ts



function openPopup(args) {
    let root = null;
    const onChange = () => {
        args.onChange && args.onChange();
        renderPopup();
    };
    const onDelete = () => {
        args.onDelete && args.onDelete();
        popuplayer_default().instance.hidePopouts();
    };
    const renderPopup = () => {
        const props = {
            ...args.props,
            onChange,
            onDelete
        };
        if (!root) {
            root = (0,client.createRoot)(div);
        }
        root.render(external_react_default().createElement(args.reactComponent, props));
    };
    const div = document.createElement('div');
    div.style.display = 'flex';
    renderPopup();
    popuplayer_default().instance.showPopout({
        content: { el: $(div) },
        attachTo: $(args.attachTo),
        position: 'right',
        onClose() {
            if (root) {
                root.unmount();
                root = null;
            }
        }
    });
}
const _supportedTypes = {
    Boolean: true,
    String: true,
    Number: true,
    Date: true,
    Pointer: true
};
const _operationsForType = {
    Boolean: ['equal to', 'not equal to', 'exist', 'not exist'],
    String: ['equal to', 'not equal to', 'exist', 'not exist', 'contain'],
    Number: [
        'less than',
        'less than or equal to',
        'greater than',
        'greater than or equal to',
        'equal to',
        'not equal to',
        'exist',
        'not exist'
    ],
    Date: [
        'less than',
        'less than or equal to',
        'greater than',
        'greater than or equal to',
        'equal to',
        'not equal to',
        'exist',
        'not exist'
    ]
};
function _propertiesFromSchema(schema) {
    const properties = Object.keys(schema.properties).filter((p) => {
        const propertySchema = schema.properties[p];
        return _supportedTypes[propertySchema.type];
    });
    if (schema.relations !== undefined)
        properties.push('related to');
    return properties;
}
function _initializeRuleForProperty(rule, property, schema) {
    if (property !== 'related to') {
        rule.property = property;
        rule.operator = rule.value = rule.value = undefined;
        const propertySchema = schema.properties[property];
        if (propertySchema.type === 'Pointer') {
            rule.input = 'MyRecordId';
            rule.operator = 'points to';
        }
        delete rule.relatedTo;
        delete rule.relationProperty;
    }
    else {
        rule.property = undefined;
        rule.operator = 'related to';
        rule.value = undefined;
        rule.input = 'MyRelationRecordId';
        rule.relatedTo = undefined;
        rule.relationProperty = undefined;
    }
}
function _formatValue(value, schema) {
    if (schema.type === 'Number') {
        return parseFloat(value);
    }
    else if (schema.type === 'Boolean') {
        return !!value;
    }
    return value;
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryPointerRuleEditPopup/QueryPointerRuleEditPopup.tsx






function QueryPointerRuleEditPopup(props) {
    function onPropItemClicked(property) {
        _initializeRuleForProperty(props.query, property, props.schema);
        props.onChange && props.onChange();
    }
    function onInputItemChanged(value) {
        props.query.input = value;
        props.onChange && props.onChange();
    }
    function onDeleteClicked() {
        popuplayer_default().instance.hidePopouts();
        props.onDeleteClicked && props.onDeleteClicked();
    }
    const q = props.query;
    const properties = _propertiesFromSchema(props.schema);
    return (external_react_default().createElement(QueryRulePopup, { title: "Edit filter rule", onDeleteClicked: onDeleteClicked },
        external_react_default().createElement(RuleDropdown, { label: "PROPERTY", value: q.property, dropdownItems: properties, onItemSelected: (p) => onPropItemClicked(p) }),
        external_react_default().createElement(RuleInput, { label: "INPUT", value: q.input, onChange: (value) => onInputItemChanged(value) })));
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryPointerRuleEditPopup/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryRelationRuleEditPopup/QueryRelationRuleEditPopup.tsx





function QueryRelationRuleEditPopup(props) {
    function onPropItemClicked(property) {
        const q = props.query;
        _initializeRuleForProperty(q, property, props.schema);
        props.onChange && props.onChange();
    }
    function onInputItemChanged(value) {
        props.query.input = value;
        props.onChange && props.onChange();
    }
    function onRelationClassItemClicked(value) {
        props.query.relatedTo = value;
        props.onChange && props.onChange();
    }
    function onRelationPropItemClicked(value) {
        props.query.relationProperty = value;
        props.onChange && props.onChange();
    }
    const q = props.query;
    const properties = _propertiesFromSchema(props.schema);
    const relationClasses = Object.keys(props.schema.relations);
    const relationProps = q.relatedTo ? props.schema.relations[q.relatedTo].map((r) => r.property) : [];
    return (external_react_default().createElement(QueryRulePopup, { title: "Edit filter rule", onDeleteClicked: props.onDeleteClicked },
        external_react_default().createElement(RuleDropdown, { label: "PROPERTY", value: q.operator, dropdownItems: properties, onItemSelected: onPropItemClicked }),
        external_react_default().createElement(RuleDropdown, { label: "RELATED TO CLASS", value: q.relatedTo, dropdownItems: relationClasses, onItemSelected: onRelationClassItemClicked }),
        q.relatedTo !== undefined ? (external_react_default().createElement(RuleDropdown, { label: "RELATION PROPERTY", value: q.relationProperty, dropdownItems: relationProps, onItemSelected: onRelationPropItemClicked })) : null,
        q.relatedTo !== undefined && q.relationProperty !== undefined ? (external_react_default().createElement(RuleInput, { label: "INPUT", value: q.input, onChange: onInputItemChanged })) : null));
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryRelationRuleEditPopup/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/RuleValueOrInputLabel/RuleValueOrInputLabel.tsx

function RuleValueOrInputLabel({ onClick, isValue }) {
    return (external_react_default().createElement("div", { onClick: (e) => {
            onClick();
            e.stopPropagation();
        } },
        external_react_default().createElement("span", { className: isValue ? 'queryeditor-strong' : '' }, "VALUE"),
        ' | ',
        external_react_default().createElement("span", { className: !isValue ? 'queryeditor-strong' : '' }, "INPUT")));
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/RuleValueOrInputLabel/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryRuleEditPopup/QueryRuleEditPopup.tsx






class QueryRuleEditPopup extends (external_react_default()).Component {
    onPropItemClicked(property) {
        const q = this.props.query;
        _initializeRuleForProperty(q, property, this.props.schema);
        this.props.onChange && this.props.onChange();
    }
    onOpItemClicked(op) {
        this.props.query.operator = op;
        this.props.onChange && this.props.onChange();
    }
    onValueChanged(value) {
        const q = this.props.query;
        this.props.query.value = _formatValue(value, this.props.schema.properties[q.property]);
        this.props.onChange && this.props.onChange();
    }
    onInputNameChanged(value) {
        this.props.query.input = value;
        this.props.onChange && this.props.onChange();
    }
    onSourceClicked() {
        const q = this.props.query;
        //toggle between a value and an input
        q.input = q.input ? undefined : 'MyInput';
        this.props.onChange && this.props.onChange();
    }
    renderInputValue() {
        const q = this.props.query;
        const propertySchema = this.props.schema.properties[q.property];
        const isBool = propertySchema.type === 'Boolean';
        if (isBool) {
            return (external_react_default().createElement(RuleDropdown, { label: external_react_default().createElement(RuleValueOrInputLabel, { onClick: () => this.onSourceClicked(), isValue: true }), value: q.value !== undefined ? (q.value === true ? 'True' : 'False') : null, dropdownItems: ['True', 'False'], onItemSelected: (p) => this.onValueChanged(p === 'True') }));
        }
        else {
            return (external_react_default().createElement(RuleInput, { label: external_react_default().createElement(RuleValueOrInputLabel, { onClick: () => this.onSourceClicked(), isValue: true }), value: q.value, onChange: (value) => this.onValueChanged(value) }));
        }
    }
    renderInputConnection() {
        return (external_react_default().createElement(RuleInput, { label: external_react_default().createElement(RuleValueOrInputLabel, { onClick: () => this.onSourceClicked(), isValue: false }), value: this.props.query.input, onChange: (value) => this.onInputNameChanged(value) }));
    }
    render() {
        const q = this.props.query;
        const properties = _propertiesFromSchema(this.props.schema);
        let operations;
        if (q.property) {
            const propertySchema = this.props.schema.properties[q.property];
            operations = _operationsForType[propertySchema.type];
        }
        const showValue = q.property !== undefined && q.operator !== undefined && q.operator !== 'exist' && q.operator !== 'not exist';
        return (external_react_default().createElement(QueryRulePopup, { title: "Edit filter rule", onDeleteClicked: this.props.onDeleteClicked },
            external_react_default().createElement(RuleDropdown, { label: "PROPERTY", value: q.property, dropdownItems: properties, onItemSelected: (p) => this.onPropItemClicked(p) }),
            q.property !== undefined ? (external_react_default().createElement(RuleDropdown, { label: "CONDITION", value: q.operator, dropdownItems: operations, onItemSelected: (p) => this.onOpItemClicked(p) })) : null,
            showValue ? (q.input === undefined ? this.renderInputValue() : this.renderInputConnection()) : null));
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryRuleEditPopup/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryEditPopup/QueryEditPopup.tsx




function QueryEditPopup(props) {
    const q = props.query;
    const propertySchema = props.schema.properties[q.property];
    // Relation rules
    if (q.operator === 'related to') {
        return (external_react_default().createElement(QueryRelationRuleEditPopup, { onDeleteClicked: props.onDelete, query: q, schema: props.schema, onChange: props.onChange }));
    }
    else if (propertySchema !== undefined && propertySchema.type === 'Pointer') {
        // Pointer rules
        return (external_react_default().createElement(QueryPointerRuleEditPopup, { onDeleteClicked: props.onDelete, query: q, schema: props.schema, onChange: props.onChange }));
    }
    else {
        // Property rules
        return (external_react_default().createElement(QueryRuleEditPopup, { onDeleteClicked: props.onDelete, query: q, schema: props.schema, onChange: props.onChange }));
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryEditPopup/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryPointerRule/QueryPointerRule.tsx



function QueryPointerRule(props) {
    const popupAnchor = (0,external_react_.useRef)(null);
    function openEditPopup(e) {
        e.stopPropagation();
        openPopup({
            reactComponent: QueryEditPopup,
            props: {
                query: props.query,
                schema: props.schema
            },
            attachTo: popupAnchor.current,
            onChange: props.onChange,
            onDelete: props.onDelete
        });
    }
    const q = props.query;
    return (external_react_default().createElement("div", { className: "queryeditor-text-rule", onClick: openEditPopup, ref: popupAnchor },
        external_react_default().createElement("span", { className: "queryeditor-span" },
            "where the property",
            q.property !== undefined ? (external_react_default().createElement("span", null,
                external_react_default().createElement("span", { className: "queryeditor-span-strong" }, q.property),
                "is pointing to a record with id that matches the input",
                q.input !== undefined ? (external_react_default().createElement("span", null,
                    external_react_default().createElement("span", { className: "queryeditor-span-strong" }, '' + q.input))) : null)) : null)));
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryPointerRule/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryRelationRule/QueryRelationRule.tsx



function QueryRelationRule(props) {
    const popupAnchor = (0,external_react_.useRef)(null);
    function openEditPopup(e) {
        e.stopPropagation();
        openPopup({
            reactComponent: QueryEditPopup,
            props: {
                query: props.query,
                schema: props.schema
            },
            attachTo: popupAnchor.current,
            onChange: props.onChange,
            onDelete: props.onDelete
        });
    }
    const q = props.query;
    return (external_react_default().createElement("div", { className: "queryeditor-text-rule", onClick: openEditPopup, ref: popupAnchor },
        external_react_default().createElement("span", { className: "queryeditor-span" },
            "that is related to another record with class",
            q.relatedTo !== undefined ? (external_react_default().createElement("span", null,
                external_react_default().createElement("span", { className: "queryeditor-span-strong" }, q.relatedTo),
                "via the relation property",
                q.relationProperty !== undefined ? (external_react_default().createElement("span", null,
                    external_react_default().createElement("span", { className: "queryeditor-span-strong" }, q.relationProperty),
                    "with id that matches the input",
                    q.input !== undefined ? (external_react_default().createElement("span", null,
                        external_react_default().createElement("span", { className: "queryeditor-span-strong" }, '' + q.input))) : null)) : null)) : null)));
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryRelationRule/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryRule/QueryRule.tsx



function QueryRule(props) {
    const popupAnchor = (0,external_react_.useRef)(null);
    function openEditPopup(e) {
        e.stopPropagation();
        openPopup({
            reactComponent: QueryEditPopup,
            props: {
                query: props.query,
                schema: props.schema
            },
            onChange: props.onChange,
            onDelete: props.onDelete,
            attachTo: popupAnchor.current
        });
    }
    const q = props.query;
    return (external_react_default().createElement("div", { className: "queryeditor-text-rule", onClick: openEditPopup, ref: popupAnchor },
        external_react_default().createElement("span", { className: "queryeditor-span" },
            "where the property",
            q.property !== undefined ? (external_react_default().createElement("span", null,
                external_react_default().createElement("span", { className: "queryeditor-span-strong" }, q.property),
                q.operator !== undefined && q.operator !== 'exist' && q.operator !== 'not exist' ? (external_react_default().createElement("span", null,
                    q.operator === 'contain' ? 'does' : 'is',
                    external_react_default().createElement("span", { className: "queryeditor-span-strong" }, q.operator),
                    q.value !== undefined && q.input === undefined ? (external_react_default().createElement("span", null,
                        "the value",
                        external_react_default().createElement("span", { className: "queryeditor-span-strong" }, '' + q.value))) : null,
                    q.input !== undefined ? (external_react_default().createElement("span", null,
                        "the input",
                        external_react_default().createElement("span", { className: "queryeditor-span-strong" }, '' + q.input))) : null)) : null,
                q.operator !== undefined && (q.operator === 'exist' || q.operator === 'not exist') ? (external_react_default().createElement("span", null,
                    "does",
                    external_react_default().createElement("span", { className: "queryeditor-span-strong" }, q.operator))) : null)) : null)));
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryRule/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryGroup/QueryGroup.tsx






class QueryGroup extends (external_react_default()).Component {
    renderQueryRule(r) {
        const propertySchema = this.props.schema.properties[r.property];
        // Relation rules
        if (r.operator === 'related to')
            return (external_react_default().createElement(QueryRelationRule, { onDelete: () => this.onDelete(r), query: r, schema: this.props.schema, onChange: () => this.onChildChange() }));
        // Pointer rules
        else if (propertySchema !== undefined && propertySchema.type === 'Pointer')
            return (external_react_default().createElement(QueryPointerRule, { onDelete: () => this.onDelete(r), query: r, schema: this.props.schema, onChange: () => this.onChildChange() }));
        // Property rules
        else
            return (external_react_default().createElement(QueryRule, { onDelete: () => this.onDelete(r), query: r, schema: this.props.schema, onChange: () => this.onChildChange() }));
    }
    renderChildren() {
        const q = this.props.query;
        return q.rules.map((r, idx) => (external_react_default().createElement("div", { key: idx /* TODO: Invalid key */ },
            r.combinator !== undefined ? (external_react_default().createElement(QueryGroup, { onDeleteClicked: () => this.onDelete(r), query: r, schema: this.props.schema, onChange: () => this.onChildChange() })) : (this.renderQueryRule(r)),
            idx !== q.rules.length - 1 ? external_react_default().createElement("div", { className: "queryeditor-combinator-label" }, q.combinator) : null)));
    }
    onDelete(rule) {
        const q = this.props.query;
        if (this.props.isTopLevel && q.rules.length === 1)
            return; // Don't delete last group on top level
        const idx = q.rules.indexOf(rule);
        if (idx !== -1)
            q.rules.splice(idx, 1);
        this.props.onChange && this.props.onChange();
        if (q.rules.length === 0)
            this.props.onDeleteClicked && this.props.onDeleteClicked();
        this.forceUpdate();
    }
    onChildChange() {
        this.props.onChange && this.props.onChange();
        this.forceUpdate();
    }
    onAddGroupClicked() {
        this.props.query.rules.push({
            combinator: 'and',
            rules: []
        });
        this.props.onChange && this.props.onChange();
        this.forceUpdate();
    }
    openEditPopupForRule(q, anchor) {
        openPopup({
            reactComponent: QueryEditPopup,
            props: {
                query: q,
                schema: this.props.schema
            },
            onChange: () => this.onChildChange(),
            onDelete: () => this.onDelete(q),
            attachTo: anchor
        });
    }
    onAddRuleClicked() {
        const rule = {};
        this.props.query.rules.push(rule);
        this.props.onChange && this.props.onChange();
        // This is a trick to automatically open the edit popup for the created rule
        setTimeout(() => {
            if (this.childContainer && this.childContainer.lastElementChild) {
                this.openEditPopupForRule(rule, this.childContainer.lastElementChild);
            }
        }, 100);
    }
    _isLastChildGroupsEmpty() {
        const q = this.props.query;
        const lastRule = q.rules[q.rules.length - 1];
        return lastRule.rules === undefined || lastRule.rules.length === 0;
    }
    render() {
        const q = this.props.query;
        return (external_react_default().createElement("div", { className: 'queryeditor-group' + (this.props.isTopLevel ? ' toplevel' : ''), style: { position: 'relative' } },
            external_react_default().createElement("div", { className: "queryeditor-group-children", ref: (el) => { this.childContainer = el; } }, this.renderChildren()),
            external_react_default().createElement("div", { className: "queryeditor-group-row" },
                !this.props.isTopLevel && q.rules.length === 0 ? (external_react_default().createElement("div", { className: "queryeditor-add-filter-group-inner", onClick: () => this.onAddRuleClicked() },
                    external_react_default().createElement("i", { className: "fa fa-plus", style: { marginRight: '10px' } }),
                    "Add filter rule")) : null,
                !this.props.isTopLevel && q.rules.length > 0 ? (external_react_default().createElement("div", { className: "queryeditor-add-rule", style: { marginTop: q.rules.length > 0 ? '5px' : '0px' }, onClick: () => this.onAddRuleClicked() },
                    external_react_default().createElement("div", { className: "queryeditor-add-button" }, "AND"))) : null,
                this.props.isTopLevel && !this._isLastChildGroupsEmpty() ? (external_react_default().createElement("div", { className: "queryeditor-add-group", style: { marginTop: '5px' }, onClick: () => this.onAddGroupClicked() },
                    external_react_default().createElement("div", { className: "queryeditor-add-button" }, "OR"))) : null)));
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QueryFilterEditor/QueryFilterEditor.tsx


function QueryFilterEditor(props) {
    let filter;
    if (props.filter !== undefined) {
        //we're going to modify nested parameters, so clone the object
        filter = JSON.parse(JSON.stringify(props.filter));
    }
    else {
        filter = { combinator: 'or', rules: [{ combinator: 'and', rules: [] }] };
    }
    return external_react_default().createElement(QueryGroup, { query: filter, schema: props.schema, isTopLevel: true, onChange: () => props.onChange(filter) });
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QuerySortingRuleEditPopup/QuerySortingRuleEditPopup.tsx



function QuerySortingRuleEditPopup(props) {
    function onPropItemClicked(property) {
        props.rule.property = property;
        props.onChange && props.onChange();
    }
    function onOrderItemClicked(order) {
        props.rule.order = order;
        props.onChange && props.onChange();
    }
    const r = props.rule;
    const properties = Object.keys(props.schema.properties);
    return (external_react_default().createElement(QueryRulePopup, { title: "Edit sorting rule", onDeleteClicked: props.onDelete },
        external_react_default().createElement(RuleDropdown, { label: "PROPERTY", dropdownItems: properties, value: r.property, onItemSelected: onPropItemClicked }),
        r.property !== undefined ? (external_react_default().createElement(RuleDropdown, { label: "ORDER", dropdownItems: ['ascending', 'descending'], value: r.order, onItemSelected: onOrderItemClicked })) : null));
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QuerySortingRuleEditPopup/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QuerySortingRule/QuerySortingRule.tsx



function QuerySortingRule(props) {
    const popupAnchor = (0,external_react_.useRef)(null);
    function openEditPopup(e) {
        e.stopPropagation();
        openPopup({
            reactComponent: QuerySortingRuleEditPopup,
            props: {
                rule: props.rule,
                schema: props.schema
            },
            attachTo: popupAnchor.current,
            onChange: props.onChange,
            onDelete: props.onDelete
        });
    }
    const r = props.rule;
    return (external_react_default().createElement("div", { className: "queryeditor-text-rule", onClick: openEditPopup, ref: popupAnchor },
        external_react_default().createElement("span", { className: "queryeditor-span" },
            "by the property",
            r.property !== undefined ? (external_react_default().createElement("span", null,
                external_react_default().createElement("span", { className: "queryeditor-span-strong" }, r.property),
                r.order !== undefined ? (external_react_default().createElement("span", null,
                    "in",
                    external_react_default().createElement("span", { className: "queryeditor-span-strong" }, r.order),
                    "order")) : null)) : null)));
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QuerySortingRule/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/QuerySortingEditor/QuerySortingEditor.tsx




class QuerySortingEditor extends (external_react_default()).Component {
    constructor(props) {
        super(props);
        if (props.sorting !== undefined)
            this.sorting = JSON.parse(JSON.stringify(props.sorting));
    }
    onChange() {
        this.props.onChange(this.sorting);
        this.forceUpdate();
    }
    onDelete(s) {
        const idx = this.sorting.indexOf(s);
        if (idx !== -1) {
            this.sorting.splice(idx, 1);
            if (this.sorting.length === 0)
                this.sorting = undefined;
            this.onChange();
        }
    }
    onAddRuleClicked() {
        if (this.sorting === undefined)
            this.sorting = [];
        const rule = {};
        this.sorting.push(rule);
        this.onChange();
        // This is a trick to automatically open the edit popup for the created rule
        setTimeout(() => {
            if (this.childContainer && this.childContainer.lastElementChild) {
                this.openEditPopupForRule(rule, this.childContainer.lastElementChild);
            }
        }, 100);
    }
    openEditPopupForRule(r, anchor) {
        openPopup({
            reactComponent: QuerySortingRuleEditPopup,
            props: {
                rule: r,
                schema: this.props.schema
            },
            onChange: () => this.onChange(),
            onDelete: () => this.onDelete(r),
            attachTo: anchor
        });
    }
    render() {
        return (external_react_default().createElement("div", null,
            this.sorting === undefined ? (external_react_default().createElement("div", { className: "queryeditor-add-filter-group" },
                external_react_default().createElement("div", { className: "queryeditor-add-filter-group-inner", onClick: () => this.onAddRuleClicked() },
                    external_react_default().createElement("i", { className: "fa fa-plus", style: { marginRight: '10px' } }),
                    "Add sorting rule"))) : null,
            this.sorting !== undefined ? (external_react_default().createElement("div", null,
                external_react_default().createElement("div", { className: "queryeditor-sorting-rules" },
                    external_react_default().createElement("div", { ref: (el) => { this.childContainer = el; } }, this.sorting.map((s, idx) => (external_react_default().createElement("div", { key: idx /* TODO: Invalid key */ },
                        external_react_default().createElement(QuerySortingRule, { rule: s, schema: this.props.schema, onChange: () => this.onChange(), onDelete: () => this.onDelete(s) }),
                        idx !== this.sorting.length - 1 ? external_react_default().createElement("div", { className: "queryeditor-combinator-label" }, "then") : null)))),
                    external_react_default().createElement("div", { className: "queryeditor-add-rule", style: { marginTop: this.sorting.length > 0 ? '5px' : '0px' }, onClick: () => this.onAddRuleClicked() },
                        external_react_default().createElement("div", { className: "queryeditor-add-button" }, "THEN"))))) : null));
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/QueryEditor/index.ts


__webpack_require__(41987);
/* harmony default export */ const QueryEditor = ({
    Filter: QueryFilterEditor,
    Sorting: QuerySortingEditor
});

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/QueryFilterType.ts





class QueryFilterType extends TypeView {
    constructor() {
        super(...arguments);
        this.root = null;
    }
    static fromPort(args) {
        const view = new QueryFilterType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.default = p.default;
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        const onChange = (filter) => {
            const undoArgs = { undo: true, label: 'query changed', oldValue: this.value };
            this.value = filter;
            this.parent.model.setParameter(this.name, filter, undoArgs);
            this.isDefault = false;
        };
        const div = document.createElement('div');
        const renderFilters = () => {
            const props = {
                filter: this.value,
                schema: this.type.schema,
                onChange
            };
            if (!this.root) {
                this.root = (0,client.createRoot)(div);
            }
            this.root.render(external_react_default().createElement(QueryEditor.Filter, props));
        };
        renderFilters();
        this.el = $(div);
        return this.el;
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/QuerySortingType.ts





class QuerySortingType extends TypeView {
    constructor() {
        super(...arguments);
        this.root = null;
    }
    static fromPort(args) {
        const view = new QuerySortingType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.default = p.default;
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        const onChange = (sorting) => {
            const undoArgs = { undo: true, label: 'query changed', oldValue: this.value };
            this.value = sorting;
            this.parent.model.setParameter(this.name, sorting, undoArgs);
            this.isDefault = false;
        };
        const div = document.createElement('div');
        const renderSorting = () => {
            const props = {
                sorting: this.value,
                schema: this.type.schema,
                onChange
            };
            if (!this.root) {
                this.root = (0,client.createRoot)(div);
            }
            this.root.render(external_react_default().createElement(QueryEditor.Sorting, props));
        };
        renderSorting();
        this.el = $(div);
        return this.el;
    }
}

// EXTERNAL MODULE: ./src/editor/src/templates/propertyeditor/resizingview.html
var resizingview = __webpack_require__(26768);
var resizingview_default = /*#__PURE__*/__webpack_require__.n(resizingview);
;// ./src/editor/src/views/panels/propertyeditor/resizingview.js



const resizingview_keys = ['pinLeft', 'pinRight', 'pinTop', 'pinBottom', 'pinHCenter', 'pinVCenter', 'sizeWidth', 'sizeHeight'];

var ResizingView = function (args) {
  view_default().call(this);

  const values = args.values || {};
  const defaults = args.defaults || {};

  this.values = {};
  resizingview_keys.forEach((key) => (this.values[key] = values[key] === undefined ? !!defaults[key] : values[key]));

  this.defaultWidth = defaults.width || { value: 100, unit: '%' };
  this.values.width = values.width;

  this.defaultHeight = defaults.height || { value: 100, unit: '%' };
  this.values.height = values.height;

  this.onUpdate = args.onUpdate;

  this.isDefault = args.values === undefined;

  this.widthUnits = args.widthUnits || ['%', 'px'];
  this.heightUnits = args.heightUnits || ['%', 'px'];
};
ResizingView.prototype = Object.create((view_default()).prototype);

ResizingView.prototype.render = function () {
  // Component inputs will have output ports, and vice versa
  this.el = this.bindView($((resizingview_default())), this);

  this.wInput = new ResizingView.DimInput({
    parent: this,
    label: 'W',
    default: this.defaultWidth,
    value: this.values.width,
    units: this.widthUnits,
    isDefault: this.isDefault,
    onUpdate: (value) => {
      this.values.width = value;
      this.updateValues();
    }
  });
  this.$('.dims').append(this.wInput.render());

  this.hInput = new ResizingView.DimInput({
    parent: this,
    label: 'H',
    default: this.defaultHeight,
    value: this.values.height,
    units: this.heightUnits,
    isDefault: this.isDefault,
    onUpdate: (value) => {
      this.values.height = value;
      this.updateValues();
    }
  });
  this.$('.dims').append(this.hInput.render());

  this.constrainValues();
  this.updateView();

  return this.el;
};

ResizingView.prototype.updateView = function () {
  var _values = {};
  resizingview_keys.forEach((key) => {
    if (!this.modes[key]) _values[key] = 'disabled';
    else _values[key] = this.values[key] ? 'sel' : undefined;
  });
  this._values = _values;

  resizingview_keys.forEach((key) => {
    this.$('[data-pin=' + key + ']')
      .removeClass('sel')
      .removeClass('disabled');
    if (this._values[key]) this.$('[data-pin=' + key + ']').addClass(this._values[key]);
  });
};

ResizingView.prototype.updateValues = function () {
  var values = {};
  resizingview_keys.forEach((key) => {
    values[key] = this._values[key] === 'sel';
  });

  values.width = this.values.width || this.defaultWidth;
  values.height = this.values.height || this.defaultHeight;

  this.hInput.isDefault = this.wInput.isDefault = false;

  this.onUpdate(values, { oldValue: this.values });
};

ResizingView.prototype.constrainValues = function () {
  var values = this.values;
  var modes = (this.modes = {
    pinLeft: true,
    pinRight: true,
    pinTop: true,
    pinBottom: true,
    pinHCenter: true,
    pinVCenter: true,
    sizeHeight: true,
    sizeWidth: true
  });

  //if(!values.pinRight && !values.pinLeft && !values.pinHCenter) values.pinLeft = true;

  if (values.pinLeft || values.pinRight) modes.pinHCenter = false;
  if (values.pinLeft && values.pinRight) modes.sizeWidth = false;
  else if (values.pinHCenter) {
    modes.pinRight = false;
    modes.pinLeft = false;
  } else if (values.pinLeft && values.sizeWidth) modes.pinRight = false;
  else if (values.pinRight && values.sizeWidth) modes.pinLeft = false;

  //if(!values.pinTop && !values.pinBottom && !values.pinVCenter) values.pinTop = true;

  if (values.pinTop || values.pinBottom) modes.pinVCenter = false;
  if (values.pinTop && values.pinBottom) modes.sizeHeight = false;
  else if (values.pinVCenter) {
    modes.pinTop = false;
    modes.pinBottom = false;
  } else if (values.pinTop && values.sizeHeight) modes.pinBottom = false;
  else if (values.pinBottom && values.sizeHeight) modes.pinTop = false;

  this.wInput.setVisible(modes.sizeWidth && values.sizeWidth);

  this.hInput.setVisible(modes.sizeHeight && values.sizeHeight);
};

ResizingView.prototype.onPinClicked = function (scope, el, evt) {
  var pin = el.attr('data-pin');

  if (this._values[pin] === 'disabled') return;

  this.values[pin] = !this.values[pin];

  this.constrainValues();
  this.updateView();

  this.updateValues();
};

ResizingView.DimInput = function (args) {
  view_default().call(this);

  this.el = args.el;
  this.default = args.default;
  this.value = args.value !== undefined ? args.value.value : this.default.value;
  this.unit = args.value !== undefined ? args.value.unit : this.default.unit;
  this.parent = args.parent;
  this.label = args.label;
  this.isDefault = args.isDefault;
  this.units = args.units;

  this.onUpdate = args.onUpdate;
};
ResizingView.DimInput.prototype = Object.create((view_default()).prototype);

ResizingView.DimInput.prototype.render = function () {
  this.el = this.bindView(this.parent.cloneTemplate('dim-input'), this);

  // Render units dropdown
  this.$('.property-input-dropdown').html('');
  var units = this.units;
  for (var i in units) {
    this.$('.property-input-dropdown').append(
      this.bindView(
        $(
          '<div class="property-number-unit-enum" data-click="onUnitChanged" data-value="' +
            units[i] +
            '">' +
            units[i] +
            '</div>'
        )
      )
    );
  }

  this.$('input')
    .on('focus', function () {
      $(this).addClass('property-input-focused');
    })
    .on('blur', function () {
      $(this).removeClass('property-input-focused');
    });

  return this.el;
};

ResizingView.DimInput.prototype.setVisible = function (visible) {
  if (visible) this.el.show();
  else this.el.hide();
};

ResizingView.DimInput.prototype.onDropDownClicked = function (scope, el, evt) {
  var showShould = !this.$('.property-input-dropdown').is(':visible');
  if (showShould) {
    this.$('.property-number-units')[0].focus();
    this.$('.property-input-dropdown').show();
  }

  evt.stopPropagation();
};

ResizingView.DimInput.prototype.updateValue = function () {
  var _value = parseFloat(this.$('input').val());
  var value = isNaN(_value) ? undefined : _value;

  var unit = this.$('[data-text=unit]').text();

  // If the input is not a valid value, then set undefined
  if (value !== undefined) {
    this.onUpdate({ value: value, unit: unit });
    this.isDefault = false;
  } else {
    this.onUpdate(undefined);
    this.value = this.default.value;
    this.$('input').val(this.value);
    this.unit = this.default.unit;
    this.$('[data-text=unit]').text(this.unit);
  }
};

ResizingView.DimInput.prototype.onUnitChanged = function (scope, el, evt) {
  var unit = el.attr('data-value');
  this.$('[data-text=unit]').text(unit);

  this.$('.property-input-dropdown').hide();

  this.updateValue();

  evt.stopPropagation();
};

ResizingView.DimInput.prototype.onPropertyChanged = function (scope, el) {
  this.updateValue();

  el.blur();
};

/*
MarginPaddingView.prototype.updateValues = function() {
  // Extract values from edit
  if(this.editInProgress) {
    var _value = parseFloat(this.$('input').val());
    var value = isNaN(_value)?undefined:_value;
    var unit = this.$('[data-text=unit]').text();

    if(value !== undefined) {
      this.values[this.editInProgress] = {
        value:value,
        unit:unit
      }
    }
    else {
      this.values[this.editInProgress] = undefined;
    }

    this.onUpdate&&this.onUpdate(this.editInProgress,this.values[this.editInProgress]);
  }

  for(var key in this.defaults) {
    var v = this.values[key] || this.defaults[key];
    this.$('[data-comp=' + key + ']').text(v.value + ' ' + v.unit);
  }
}

MarginPaddingView.prototype.onLabelClicked = function(scope,el) {
  this.$('#editbox').show();

  var editBoxWidth = 110;
  var editBoxHeight = 35;

  var containerWidth = this.el.outerWidth();

  var x = $(el).offset().left + $(el).outerWidth()/2 - this.el.offset().left - editBoxWidth/2;
  var y = $(el).offset().top + $(el).outerHeight()/2 - this.el.offset().top - editBoxHeight/2;

  if(x+editBoxWidth+2 > containerWidth) x = containerWidth - editBoxWidth - 2;
  if(x < 0) x = 2;

  this.$('#editbox-editor').css({
    top:y + 'px',
    left:x + 'px',
    width:editBoxWidth + 'px',
    height:editBoxHeight + 'px',
  });

  var comp = el.attr('data-comp');
  this.editInProgress = comp;

  var v = this.values[comp] || this.defaults[comp];
  if(this.values[comp]) this.$('input').val(this.values[comp].value);
  else {
    this.$('input').val('');
    this.$('input').attr('placeholder',this.defaults[comp].value);
  }
  this.$('input').focus();
  this.$('[data-text=unit]').text(v.unit);
}

MarginPaddingView.prototype.onHideEditBoxClicked = function(scope,el) {
  this.$('#editbox').hide();
  this.editInProgress = undefined;

}*/

/* harmony default export */ const propertyeditor_resizingview = (ResizingView);

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/ResizingType.ts



class ResizingType extends TypeView {
    static fromPort(args) {
        const view = new ResizingType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.parent = parent;
        view.values = parent.model.parameters[p.name];
        view.resizingView = new propertyeditor_resizingview({
            modes: p.type.modes,
            values: view.values,
            defaults: p.default || p.type.defaults,
            widthUnits: p.type.widthUnits || p.type.units,
            heightUnits: p.type.heightUnits || p.type.units,
            onUpdate: function (value, opts) {
                const undoArgs = {
                    undo: true,
                    label: 'resizing changed',
                    oldValue: opts ? opts.oldValue : undefined
                };
                parent.model.setParameter(p.name, value, undoArgs);
            }
        });
        return view;
    }
    render() {
        this.el = this.resizingView.render();
        return this.el;
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/SizeModeType.ts


class SizeModeType extends TypeView {
    static fromPort(args) {
        const view = new SizeModeType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.tooltip = p.tooltip || {};
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        const _this = this;
        this.el = this.bindView(this.parent.cloneTemplate('sizemode'), this);
        TypeView.prototype.render.call(this);
        this.$('.size-icon').on('click', function () {
            const _el = this;
            const value = $(_el).attr('data-value');
            _this.parent.setParameter(_this.name, value);
            _this.value = value;
            _this.isDefault = false;
            _this.updateState();
        });
        this.updateState();
        return this.el;
    }
    updateState() {
        const _this = this;
        this.$('.size-icon').each(function () {
            const _el = this;
            const value = $(_el).attr('data-value');
            $(_el).removeClass('sel').removeClass('def');
            if (_this.value === value) {
                if (!_this.isDefault)
                    $(_el).addClass('sel');
                else
                    $(_el).addClass('def');
            }
        });
    }
    resetToDefault() {
        this.value = this.parent.model.getParameter(this.name);
        this.updateState();
    }
}

// EXTERNAL MODULE: ./src/editor/src/templates/propertyeditor/stringlist.html
var stringlist = __webpack_require__(68415);
var stringlist_default = /*#__PURE__*/__webpack_require__.n(stringlist);
;// ./src/editor/src/views/panels/propertyeditor/DataTypes/StringList/stringlist.js





// Helper to normalize list input - handles both string and array formats
function normalizeList(value) {
  if (value === undefined || value === null || value === '') {
    return [];
  }
  if (Array.isArray(value)) {
    // Already an array (legacy proplist data) - extract labels if objects
    return value.map((item) => (typeof item === 'object' && item.label ? item.label : String(item)));
  }
  if (typeof value === 'string') {
    return value.split(',').filter(Boolean);
  }
  return [];
}

var StringList = function (args) {
  view_default().call(this);

  this.parent = args.parent;
  this.list = normalizeList(args.list);
  this.type = args.type;
  this.plug = args.plug;
  this.title = args.title;
  this.group = args.group;
  this.isDefault = args.isDefault;
  this.onUpdate = args.onUpdate;
};
StringList.prototype = Object.create((view_default()).prototype);

StringList.prototype.render = function () {
  // Component inputs will have output ports, and vice versa
  this.el = this.bindView($((stringlist_default())), this);

  this.renderItems();

  this.parent && this.parent.append(this.el);

  return this.el;
};

StringList.prototype.listUpdated = function () {
  if (this.onUpdate) {
    var updated = this.onUpdate(this.list.join(','));
    if (updated) {
      this.list = normalizeList(updated.value);
      this.isDefault = updated.isDefault;
    }
  }
  this.renderItems();
};

StringList.prototype.renderItems = function () {
  this.$('.items').html('');

  for (var i in this.list) {
    var p = this.list[i];

    var compEl = this.bindView(this.cloneTemplate('item'), { name: p, index: i, isDefault: this.isDefault });
    this.$('.items').append(compEl);
  }
};

StringList.prototype.onAddPortClicked = function (scope, el, evt) {
  var _this = this;

  var popup = new (popuplayer_default()).StringInputPopup({
    label: 'New entry',
    okLabel: 'Add',
    cancelLabel: 'Cancel',
    onOk: function (name) {
      var result = _this.performAdd(name);
      if (!result.success) {
        ToastLayer.ToastLayer.showError(result.message);
      }
    }
  });
  popup.render();

  popuplayer_default().instance.showPopup({
    content: popup,
    attachTo: el,
    position: 'top'
  });

  evt.stopPropagation();
};

StringList.prototype.performAdd = function (name) {
  if (name === '') {
    return { success: false, message: 'Entry name cannot be empty' };
  } else if (this.list.indexOf(name) !== -1) {
    return { success: false, message: 'Cannot create an entry with the same name as an existing one.' };
  } else {
    this.list.push(name);
    this.listUpdated();

    return { success: true };
  }
};

StringList.prototype.performRename = function (args) {
  if (args.newName === '') {
    return { success: false, message: 'Entry name cannot be empty' };
  } else if (this.list.indexOf(args.newName) !== -1) {
    // Show alert that component cannot have same name as an
    // existing component
    return { success: false, message: 'Entry with that name already exists.' };
  } else {
    var idx = this.list.indexOf(args.oldName);
    this.list[idx] = args.newName;
    this.listUpdated();

    return { success: true };
  }
};

StringList.prototype.onRenameClicked = function (scope, el, evt) {
  var _this = this;

  var parent = el.parents('.component-ports-item');
  parent.find('.show-on-edit').show();
  parent.find('.hide-on-edit').hide();

  function rename() {
    var newName = input.val();
    if (newName !== scope.name) {
      var result = _this.performRename({ newName: newName, oldName: scope.name });

      if (!result.success) {
        ToastLayer.ToastLayer.showError(result.message);
      }
    }

    parent.find('.show-on-edit').hide();
    parent.find('.hide-on-edit').show();
    input.off('blur').off('keypress'); // Make sure rename doesn't get called twice
  }

  var input = parent.find('input');
  input
    .focus()
    .off('blur')
    .on('blur', function () {
      rename();
    })
    .off('keypress')
    .on('keypress', function (e) {
      if (e.which == 13) rename();
    });

  evt.stopPropagation();
};

StringList.prototype.performDelete = function (item) {
  var idx = this.list.indexOf(item);
  if (idx !== -1) this.list.splice(idx, 1);
  this.listUpdated();

  return { success: true };
};

StringList.prototype.onDeleteClicked = function (scope, el, evt) {
  var result = this.performDelete(scope.name);

  if (!result.success) {
    ToastLayer.ToastLayer.showError(result.message);
  }

  evt.stopPropagation();
};

/* harmony default export */ const StringList_stringlist = (StringList);

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/StringList/StringListType.ts



class StringListType extends TypeView {
    static fromPort(args) {
        const view = new StringListType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        if (parent.model.parameters[p.name] === '')
            parent.model.parameters[p.name] = undefined;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        // view.isConnected = parent.model.isPortConnected(p.name,'target');
        // view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        const _this = this;
        this.listView = new StringList_stringlist({
            title: this.displayName,
            list: this.value,
            isDefault: _this.parent.model.parameters[_this.name] === undefined,
            onUpdate: function (newValue) {
                if (newValue === '')
                    newValue = undefined;
                _this.parent.setParameter(_this.name, newValue);
                _this.parent.notifyListeners('panelResized');
                return {
                    value: _this.parent.model.getParameter(_this.name),
                    isDefault: _this.parent.model.parameters[_this.name] === undefined
                };
            }
        });
        this.listView.render();
        this.el = this.listView.el;
        return this.el;
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/TabGroup.ts

class TabGroup extends (view_default()) {
    constructor(args) {
        super();
        this.group = args.group;
        this.tabGroup = args.tabGroup;
        this.parent = args.parent;
        this.views = [];
        this.tabs = [];
    }
    render() {
        this.el = this.bindView(this.parent.cloneTemplate('tab-group'), this);
        this.tabs.forEach((tab, idx) => {
            const _el = this.bindView(this.parent.cloneTemplate('tab-group-tab'), { tab: tab });
            _el.find('.property-tab-icon').addClass(tab);
            _el.attr('data-tab', tab);
            this.$('.tabs').append(_el);
        });
        const selectedTab = this.parent._selectedTabForGroup[this.tabGroup] || this.tabs[0];
        this.$('.property-tab').removeClass('selected');
        this.$('[data-tab=' + selectedTab + ']').addClass('selected');
        this.views.forEach((v) => {
            v.render();
            this.$('.properties').append(v.el);
            if (v.port.tab.tab !== selectedTab)
                v.el.hide();
        });
        return this.el;
    }
    onTabClicked(scope, el, evt) {
        const selectedTab = (this.parent._selectedTabForGroup[this.tabGroup] = scope.tab);
        this.views.forEach((v) => {
            if (v.port.tab.tab !== selectedTab)
                v.el.hide();
            else
                v.el.show();
        });
        this.$('.property-tab').removeClass('selected');
        this.$('[data-tab=' + selectedTab + ']').addClass('selected');
    }
    addView(view) {
        this.views.push(view);
        if (this.tabs.indexOf(view.port.tab.tab) === -1)
            this.tabs.push(view.port.tab.tab);
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/TextAreaType.ts


class TextAreaType extends TypeView {
    static fromPort(args) {
        const view = new TextAreaType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    render() {
        this.el = this.bindView(this.parent.cloneTemplate('textarea'), this);
        TypeView.prototype.render.call(this);
        this.$('textarea').autosize();
        return this.el;
    }
    onPropertyChanged(scope, el) {
        const value = el.val();
        this.parent.setParameter(scope.name, value);
        // Update current value
        const current = this.getCurrentValue();
        el.val(current.value);
        this.isDefault = current.isDefault;
    }
    resetToDefault() {
        this.$('textarea').val(this.getCurrentValue().value);
    }
}

// EXTERNAL MODULE: ./src/editor/src/utils/fontloader.js
var fontloader = __webpack_require__(67033);
var fontloader_default = /*#__PURE__*/__webpack_require__.n(fontloader);
// EXTERNAL MODULE: ./src/editor/src/views/TextStylePicker/TextStylePopup.jsx
var TextStylePopup = __webpack_require__(89330);
var TextStylePopup_default = /*#__PURE__*/__webpack_require__.n(TextStylePopup);
;// ./src/editor/src/views/TextStylePicker/TextStylePicker.jsx










__webpack_require__(46055);
__webpack_require__(4102);
function TextStylePicker(props) {
  const [stylesModel, setStylesModel] = (0,external_react_.useState)(null);
  const [textStyles, setTextStyles] = (0,external_react_.useState)([]);
  const [styleToEdit, setStyleToEdit] = (0,external_react_.useState)(null);
  const [popupAnchor, setPopupAnchor] = (0,external_react_.useState)(null);
  (0,external_react_.useLayoutEffect)(() => {
    const stylesModel = new StylesModel();
    setStylesModel(stylesModel);
    setTextStyles(stylesModel.getStyles('text'));
    stylesModel.on('stylesChanged', args => {
      if (args.type === 'text') {
        setTextStyles(stylesModel.getStyles('text'));
      }
    });
    return () => {
      stylesModel.dispose();
    };
  }, []);
  (0,external_react_.useEffect)(() => {
    if (!styleToEdit || !popupAnchor) return;
    const div = document.createElement('div');
    const root = (0,client.createRoot)(div);
    root.render(/*#__PURE__*/external_react_default().createElement((TextStylePopup_default()), {
      style: styleToEdit,
      stylesModel: stylesModel
    }));
    const popout = popuplayer_default().instance.showPopout({
      content: {
        el: $(div)
      },
      attachTo: $(popupAnchor),
      position: 'right',
      onClose: () => {
        root.unmount();
      }
    });
    return () => {
      popuplayer_default().instance.hidePopout(popout);
    };
  }, [styleToEdit, popupAnchor, stylesModel]);
  let filteredStyles = textStyles;
  const filterString = props.filter ? props.filter.toLowerCase() : undefined;
  if (filterString) {
    filteredStyles = textStyles.filter(style => style.name.toLowerCase().includes(filterString));
  }
  filteredStyles.sort((a, b) => {
    if (!a.style || !a.style.fontSize || !b.style || !b.style.fontSize) return 0;
    return a.style.fontSize - b.style.fontSize;
  });
  const onDelete = name => {
    const {
      nodeCount,
      variantCount
    } = utils_default().getStyleUsage('textStyle', name);
    if (nodeCount > 0 || variantCount > 0) {
      let message = `Are you sure you want to delete <strong>${name}</strong>?<br>This text style is used by `;
      if (nodeCount) {
        message += `${nodeCount} ${nodeCount === 1 ? 'node' : 'nodes'}`;
      }
      if (variantCount) {
        if (nodeCount) {
          message += ' and ';
        }
        message += `${variantCount} ${variantCount === 1 ? 'variant' : 'variants'}`;
      }
      popuplayer_default().instance.showConfirmModal({
        title: 'CONFIRM DELETE TEXT STYLE',
        message: message,
        confirmLabel: 'Yes, delete',
        onConfirm: () => {
          stylesModel.deleteStyle('text', name, {
            undo: true,
            label: 'delete text style'
          });
        }
      });
    } else {
      stylesModel.deleteStyle('text', name, {
        undo: true,
        label: 'delete text style'
      });
    }
  };
  const onChangeName = (name, newName) => {
    stylesModel.changeStyleName('text', name, newName, {
      undo: true,
      label: 'change text style name'
    });
  };
  const onCreateStyle = name => {
    //check if there's an existing style we should base the new style on
    const styleToCopyFrom = props.selectedStyle && textStyles.find(t => t.name === props.selectedStyle);
    const newStyle = {};
    if (styleToCopyFrom) {
      Object.assign(newStyle, styleToCopyFrom.style);
    }

    //and copy the properties from the node
    for (const prop in props.newStyleProps) {
      newStyle[prop] = props.newStyleProps[prop];
    }
    props.createNewStyle(name, newStyle);
  };
  const onEdit = (style, popupAnchor) => {
    setStyleToEdit(style);
    setPopupAnchor(popupAnchor);
  };
  return /*#__PURE__*/external_react_default().createElement("div", {
    style: {
      width: '270px',
      maxHeight: '400px',
      display: 'flex',
      flexDirection: 'column',
      fontSize: '16px'
    }
  }, /*#__PURE__*/external_react_default().createElement("div", {
    style: {
      overflow: 'hidden auto',
      flexGrow: 1
    }
  }, /*#__PURE__*/external_react_default().createElement(TextStylePicker_CreateNewStyle, {
    stylesModel: stylesModel,
    onCreateStyle: onCreateStyle
  }), filteredStyles.map(style => /*#__PURE__*/external_react_default().createElement(TextStyleItem, {
    key: style.name,
    style: style,
    onSelect: props.onItemSelected,
    onChangeName: onChangeName,
    onDelete: onDelete,
    onEdit: popupAnchor => onEdit(style, popupAnchor),
    onEditingName: () => setStyleToEdit(null)
  }))));
}
function TextStyleItem(props) {
  const [isEditing, setIsEditing] = (0,external_react_.useState)(false);
  const [styleName, setStyleName] = (0,external_react_.useState)(props.style.name);
  const popupAnchorRef = (0,external_react_.useRef)(null);
  const onSelectClicked = e => {
    props.onSelect(props.style.name);
    e.stopPropagation();
  };
  const onDeleteClicked = e => {
    props.onDelete(props.style.name);
    e.stopPropagation();
  };
  const onEditStyleClicked = e => {
    props.onEdit(popupAnchorRef.current);
    e.stopPropagation();
  };
  const onEditClicked = e => {
    props.onEditingName();
    setIsEditing(true);
    setStyleName(props.style.name);
    e.stopPropagation();
  };
  const onInputKeyUp = e => {
    if (e.key === 'Enter') {
      const newName = e.target.value;
      if (newName && props.style.name !== newName) {
        props.onChangeName(props.style.name, newName);
      }
      setIsEditing(false);
    }
  };
  const fontStyle = props.style.style || {};

  //style object is in the following format: {fontSize: 12, unit: 'px', ...}
  //lets convert it to CSS
  const propertiesToIgnore = ['fontSize', 'lineHeight'];
  const css = {};
  for (const prop in fontStyle) {
    if (!propertiesToIgnore.includes(prop)) {
      const value = fontStyle[prop];
      css[prop] = typeof value === 'object' ? value.value + value.unit : value;
    }
  }
  if (fontStyle.fontFamily && fontStyle.fontFamily.indexOf('.') !== -1) {
    const fontPath = fontStyle.fontFamily;
    const paths = fontPath.split('/');
    const fileName = paths[paths.length - 1];
    const nameWithoutExtension = fileName.split('.')[0];
    const nameWithoutExtensionAndSpaces = nameWithoutExtension.replace(/\s/g, '');
    fontloader_default().instance.loadFont(nameWithoutExtensionAndSpaces, fontPath);
    css.fontFamily = nameWithoutExtensionAndSpaces;
  }

  //if the text style color is too dark, add a light gray plate behind it
  if (css.color && colorToLuminance(css.color) < 0.5) {
    css.backgroundColor = '#ccc';
    css.padding = '0 4px';
  }
  if (isEditing) {
    return /*#__PURE__*/external_react_default().createElement("div", {
      className: "variants-pick-variant-item"
    }, /*#__PURE__*/external_react_default().createElement("input", {
      className: "variants-input",
      type: "text",
      autoFocus: true,
      onChange: e => setStyleName(e.target.value),
      onKeyUp: onInputKeyUp,
      value: styleName,
      onBlur: () => setIsEditing(false)
    }));
  }
  return /*#__PURE__*/external_react_default().createElement("div", {
    className: "variants-pick-variant-item",
    onClick: onSelectClicked
  }, /*#__PURE__*/external_react_default().createElement("div", {
    className: "variant-item-name"
  }, /*#__PURE__*/external_react_default().createElement("span", {
    style: css
  }, props.style.name)), /*#__PURE__*/external_react_default().createElement("div", {
    className: "variants-item-icon",
    onClick: onEditClicked
  }, /*#__PURE__*/external_react_default().createElement("i", {
    className: "fa fa-edit"
  })), /*#__PURE__*/external_react_default().createElement("div", {
    className: "variants-item-icon",
    onClick: onDeleteClicked
  }, /*#__PURE__*/external_react_default().createElement("i", {
    className: "fa fa-trash"
  })), /*#__PURE__*/external_react_default().createElement("div", {
    className: "textstyles-edit-style",
    onClick: onEditStyleClicked,
    ref: popupAnchorRef
  }));
}
function colorToLuminance(color) {
  const rgba = colorToRGBA(color);
  return 0.299 * rgba[0] + 0.587 * rgba[1] + 0.114 * rgba[2];
}
function colorToRGBA(color) {
  if (color === 'transparent' || !color) {
    return [0, 0, 0, 0];
  }
  if (color[0] !== '#') color = '#' + color;
  const numComponents = (color.length - 1) / 2;
  const result = [0, 0, 0, 1];
  for (let i = 0; i < numComponents; ++i) {
    const index = 1 + i * 2;
    result[i] = parseInt(color.substring(index, index + 2), 16) / 255;
  }
  return result;
}
function TextStylePicker_CreateNewStyle(props) {
  const [isCreating, setIsCreating] = (0,external_react_.useState)(false);
  const inputRef = (0,external_react_.useRef)(null);
  const onCreateNewStyle = () => {
    const name = inputRef.current.value;
    if (!name) return;
    if (props.stylesModel.styleExists('text', name)) {
      ToastLayer.ToastLayer.showError('Style already exists');
    } else {
      props.onCreateStyle(name);
      setIsCreating(false);
    }
  };
  if (isCreating) {
    return /*#__PURE__*/external_react_default().createElement((external_react_default()).Fragment, null, /*#__PURE__*/external_react_default().createElement("div", {
      className: "variants-header"
    }, /*#__PURE__*/external_react_default().createElement("span", null, "New text style name")), /*#__PURE__*/external_react_default().createElement("div", {
      className: "variants-input-container"
    }, /*#__PURE__*/external_react_default().createElement("input", {
      autoFocus: true,
      className: "variants-input",
      ref: inputRef,
      onKeyUp: e => e.key === 'Enter' && onCreateNewStyle()
    }), /*#__PURE__*/external_react_default().createElement("button", {
      className: "variants-button primary",
      onClick: onCreateNewStyle
    }, "Create")));
  } else {
    return /*#__PURE__*/external_react_default().createElement("div", {
      onClick: () => setIsCreating(true),
      className: "variants-header variants-add-header"
    }, /*#__PURE__*/external_react_default().createElement("span", null, "Create new text style"), /*#__PURE__*/external_react_default().createElement(inputs_IconButton/* IconButton */.K0, {
      icon: common_Icon/* IconName */.$M.Plus,
      size: common_Icon/* IconSize */.lK.Small,
      UNSAFE_className: "add-button",
      variant: inputs_IconButton/* IconButtonVariant */.nl.OpaqueOnHover,
      onClick: () => setIsCreating(true)
    }));
  }
}
/* harmony default export */ const TextStylePicker_TextStylePicker = (TextStylePicker);
;// ./src/editor/src/views/panels/propertyeditor/DataTypes/TextStyleType.ts









function TextStyleType_firstType(type) {
    return nodelibrary/* NodeLibrary */.m.nameForPortType(type);
}
class TextStyleType extends TypeView {
    static fromPort(args) {
        const view = new TextStyleType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.value = parent.model.getParameter(p.name);
        view.parent = parent;
        view.isConnected = parent.model.isPortConnected(p.name, 'target');
        view.isDefault = parent.model.parameters[p.name] === undefined;
        return view;
    }
    dispose() {
        TypeView.prototype.dispose.call(this);
        EventDispatcher.EventDispatcher.instance.off(this);
    }
    render() {
        this.el = this.bindView(this.parent.cloneTemplate(TextStyleType_firstType(this.type)), this);
        TypeView.prototype.render.call(this);
        EventDispatcher.EventDispatcher.instance.on('Model.stylesChanged', (event) => {
            if (event.args.type === 'text') {
                this.resetToDefault();
            }
        }, this);
        let textStylePickerDiv;
        let textStylePickerRoot = null;
        const props = {};
        this.$('input').on('focus', (e) => {
            e.stopPropagation();
        });
        this.$('input').on('click', (e) => {
            // @ts-expect-error
            delete props.filter; //delete filter in case the user opens/closes multiple times
            const newStyleProps = {};
            if (this.port.type.childPorts) {
                const prefix = this.port.type.childPortPrefix;
                for (const childPort of this.port.type.childPorts) {
                    const value = this.parent.model.getParameter(prefix + childPort);
                    if (value !== undefined) {
                        newStyleProps[childPort] = value;
                    }
                }
            }
            // @ts-expect-error
            props.newStyleProps = newStyleProps;
            // @ts-expect-error
            props.selectedStyle = this.getCurrentValue().value;
            // @ts-expect-error
            props.onItemSelected = (name) => {
                this.$('input').val(name);
                this.$('input').trigger('change');
                this.parent.hidePopout();
            };
            // @ts-expect-error
            props.createNewStyle = (styleName, newStyle) => {
                this.parent.hidePopout();
                //reset the values that are now moved to the text style
                const prevValue = this.parent.model.parameters[this.name];
                const portValuesToReset = {};
                if (this.port.type.childPorts) {
                    const prefix = this.port.type.childPortPrefix;
                    for (const childPort of this.port.type.childPorts) {
                        const value = this.parent.model.parameters[prefix + childPort];
                        if (value !== undefined) {
                            portValuesToReset[prefix + childPort] = value;
                        }
                    }
                }
                const portsToReset = Object.keys(portValuesToReset);
                // @ts-expect-error
                undo_queue_model/* UndoQueue */.g.instance.pushAndDo({
                    label: `create new text style: ${styleName}`,
                    do: () => {
                        const stylesModel = new StylesModel();
                        stylesModel.setStyle('text', styleName, newStyle);
                        stylesModel.dispose();
                        //Set the new text style
                        this.parent.model.setParameter(this.name, styleName === '' ? undefined : styleName, { undo: false });
                        if (portsToReset.length) {
                            for (const portName of portsToReset) {
                                this.parent.model.setParameter(portName, undefined, { undo: false });
                            }
                            //the ports have changed values so we need to re-render the ports
                            //this will reset any bound popouts, which causes some minor UX issues
                            this.parent._portsHash = undefined;
                            this.parent.renderGroups();
                        }
                        this._valueUpdated();
                    },
                    undo: () => {
                        const stylesModel = new StylesModel();
                        stylesModel.deleteStyle('text', styleName);
                        stylesModel.dispose();
                        this.parent.model.setParameter(this.name, prevValue === '' ? undefined : prevValue, { undo: false });
                        if (portsToReset.length) {
                            for (const portName of portsToReset) {
                                this.parent.model.setParameter(portName, portValuesToReset[portName], { undo: false });
                            }
                            //the ports have changed values so we need to re-render the ports
                            //this will reset any bound popouts, which causes some minor UX issues
                            this.parent._portsHash = undefined;
                            this.parent.renderGroups();
                        }
                        this._valueUpdated();
                    }
                });
            };
            // @ts-expect-error - Dynamic props assignment for legacy component
            props.inputValue = this.$('input').val();
            textStylePickerDiv = document.createElement('div');
            textStylePickerRoot = (0,client.createRoot)(textStylePickerDiv);
            textStylePickerRoot.render(external_react_default().createElement(TextStylePicker_TextStylePicker, props));
            this.parent.showPopout({
                content: { el: $(textStylePickerDiv) },
                attachTo: this.el,
                position: 'right',
                onClose: () => {
                    if (textStylePickerRoot) {
                        textStylePickerRoot.unmount();
                        textStylePickerRoot = null;
                        textStylePickerDiv = undefined;
                    }
                }
            });
            e.stopPropagation(); // Stop propagation, otherwise the popup will close
        });
        this.$('input').on('keyup', (e) => {
            if (!textStylePickerRoot) {
                return;
            }
            if (e.key === 'Enter') {
                this.parent.hidePopout();
            }
            else {
                // @ts-expect-error - Dynamic props assignment for legacy component
                props.filter = e.target.value;
                textStylePickerRoot.render(external_react_default().createElement(TextStylePicker_TextStylePicker, props));
            }
        });
        return this.el;
    }
    _valueUpdated() {
        const el = this.$('input');
        // Update current value and if it is default or not
        const current = this.getCurrentValue();
        el.val(current.value);
        this.isDefault = current.isDefault;
        //and update the child ports since their default values have changed
        if (this.parent.views && this.port.type.childPorts) {
            const prefix = this.port.type.childPortPrefix;
            for (const childPort of this.port.type.childPorts) {
                const portName = prefix + childPort;
                for (const portView of this.parent.views) {
                    if (portView.isDefault && portView.port && portView.port.name === portName) {
                        //resetToDefault actually doesn't reset, it just updates the value in the DOM to the current value from the model
                        portView.resetToDefault && portView.resetToDefault();
                    }
                }
            }
        }
    }
    onPropertyChanged(scope, el) {
        this.parent.setParameter(scope.name, el.val() === '' ? undefined : el.val());
        el.blur();
        this._valueUpdated();
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/VariableType.ts





function inferType(value) {
    if (typeof value === 'string') {
        if ((value[0] === '#' && value.length === 7) || value.length === 4)
            return 'Co';
        if (value.startsWith('rgb(') || value.startsWith('rgba('))
            return 'Co';
        return 'Ab';
    }
    else if (typeof value === 'boolean') {
        return 'Bo';
    }
    else if (typeof value === 'number') {
        return '12';
    }
    return '12';
}
class VariableType extends TypeView {
    static fromPort(args) {
        const view = new VariableType();
        const p = args.port;
        const parent = args.parent;
        view.port = p;
        view.displayName = p.displayName ? p.displayName : p.name;
        view.name = p.name;
        view.type = getEditType(p);
        view.group = p.group;
        view.parent = parent;
        const param = parent.model.parameters[p.name];
        view.isDefault = false;
        view.propertyType = inferType(param);
        return view;
    }
    render() {
        const _this = this;
        this.el = this.bindView(this.parent.cloneTemplate('variable-type'), this);
        TypeView.prototype.render.call(this);
        // Render types dropdown
        this.$('.property-input-dropdown').html('');
        const types = this.type.types;
        for (const i in types) {
            this.$('.property-input-dropdown').append(this.bindView($('<div class="property-number-unit-enum" data-click="onTypeChanged" data-value="' +
                types[i] +
                '">' +
                types[i] +
                '</div>')));
        }
        this.$('.property-input-dropdown').on('mousedown', function (event) {
            event.preventDefault(); // make sure drop down doesn't blur input until after "onPropertyChanged" has been triggered
        });
        this.$('.property-number-units').on('blur', function () {
            _this.$('.property-input-dropdown').hide();
        });
        this.renderTypeView();
        return this.el;
    }
    renderTypeView() {
        this.$('.property-view').html('');
        const port = {
            displayName: this.port.displayName,
            name: this.port.name
        };
        if (this.propertyType === '12') {
            // @ts-expect-error
            port.type = 'number';
            this.typeView = BasicType.fromPort({ port: port, parent: this.parent });
        }
        else if (this.propertyType === 'Ab') {
            // @ts-expect-error
            port.type = 'string';
            this.typeView = BasicType.fromPort({ port: port, parent: this.parent });
        }
        else if (this.propertyType === 'Co') {
            // @ts-expect-error
            port.type = 'color';
            this.typeView = ColorType.fromPort({ port: port, parent: this.parent });
        }
        else if (this.propertyType === 'Bo') {
            // @ts-expect-error
            port.type = 'boolean';
            this.typeView = BooleanType.fromPort({ port: port, parent: this.parent });
        }
        this.$('.property-view').html(this.typeView.render());
    }
    onTypeDropDownClicked(scope, el) {
        const showShould = !this.$('.property-input-dropdown').is(':visible');
        this.parent.$('.property-input-dropdown').hide();
        if (showShould) {
            this.$('.property-number-units')[0].focus();
            this.$('.property-input-dropdown').show();
        }
        // Hide show the padding so drop downs can be scrolled to if at the bottom of the prop editor
        this.parent.$('.property-drop-down-padding').hide();
        showShould && this.parent.$('.property-drop-down-padding').show();
        this.parent.notifyListeners('panelResized');
    }
    onTypeChanged(scope, el) {
        const type = el.attr('data-value');
        this.$('[data-text=propertyType]').text(type);
        this.parent.setParameter(this.name, undefined);
        this.propertyType = type;
        this.renderTypeView();
    }
}

;// ./src/editor/src/views/panels/propertyeditor/DataTypes/Ports.ts




































// eslint-disable-next-line @typescript-eslint/no-var-requires
const PropertyEditorPortsTemplate = __webpack_require__(5376);
const groupExpansions = {};
class Ports extends (view_default()) {
    constructor(args) {
        super();
        this.model = args.model;
        this.popout = args.popout;
        this._selectedTabForGroup = {};
        this.bindModel(this.model);
    }
    showPopout(popout) {
        if (this.activePopout) {
            this.hidePopout();
        }
        const _onClose = popout.onClose;
        popout.onClose = () => {
            this.activePopout = null;
            _onClose && _onClose();
        };
        this.activePopout = popuplayer_default().instance.showPopout(popout);
    }
    hidePopout() {
        popuplayer_default().instance.hidePopout(this.activePopout);
    }
    bindModel(model) {
        model.on([
            'instancePortsChanged',
            'portAdded',
            'portRemoved',
            'portRenamed',
            'connectionRemoved',
            'variantChanged',
            'variantUpdated'
        ], () => {
            this.renderGroups();
        }, this);
        model.on(['modelParameterUndo', 'modelParameterRedo'], () => {
            this._portsHash = undefined;
            this.renderGroups();
        }, this);
        model.owner &&
            model.owner.on(['connectionAdded', 'connectionRemoved'], () => {
                this.renderGroups();
            }, this);
    }
    dispose() {
        this.model && this.model.off(this);
        // @ts-expect-error
        this.model && this.model.owner && this.model.owner.off(this);
        EventDispatcher.EventDispatcher.instance.off(this);
        this.views.forEach((v) => v.dispose && v.dispose());
        this.hidePopout();
    }
    renderParams(views, appendTo) {
        for (const j in views) {
            const v = views[j];
            v.childViews && v.childViews.forEach((v) => v.render()); // Render any child views first
            appendTo.append(v.render());
        }
    }
    onGroupClicked(group) {
        // group.isExpanded = !group.isExpanded;
        // groupExpansions[group.name] = group.isExpanded;
    }
    renderGroups() {
        const _this = this;
        const inputData = {
            ports: this._getPorts(),
            variant: this.model.variantName
        };
        const _portsHash = JSON.stringify(inputData);
        if (_portsHash === this._portsHash)
            // No change in ports, no need to re-render
            return;
        this._portsHash = _portsHash;
        //remember the scrolling so a re-render doesn't reset the scroll position
        let scrollTop = 0;
        if (this.el[0].parentElement) {
            scrollTop = this.el[0].parentElement.parentElement.scrollTop;
        }
        //this will reset any scrolling that might've occurred
        //let's set it back later when the the ports have rendered
        this.el.html('');
        const groups = this.getViewGroupsFromPorts();
        if (groups.length === 1 && groups[0].name === 'Other') {
            // If only one group then don't render group sections
            this.renderParams(groups[0].views, this.el);
        }
        else {
            // Render prop groups
            for (const i in groups) {
                const g = groups[i];
                if (groupExpansions.hasOwnProperty(g.name)) {
                    g.isExpanded = groupExpansions[g.name];
                }
                const groupEl = this.bindView(this.cloneTemplate('group'), g);
                this.el.append(groupEl);
                this.renderParams(g.views, groupEl.find('.properties'));
            }
        }
        //and now the rendering is done. In case any scrolling was done, set the scrolling again
        if (scrollTop) {
            this.el[0].parentElement.parentElement.scrollTop = scrollTop;
        }
        this.$('input')
            .on('focus', function () {
            // Some element in the prop editor has gained focus
            // move to front
            _this.el.css({ 'z-index': '1000' });
        })
            .on('blur', function () {
            // Move back when blurred (wait 500ms)
            setTimeout(function () {
                _this.el.css({ 'z-index': '' });
            }, 500);
        });
    }
    render() {
        this._portsHash = undefined; // Clear cache
        this.el = this.bindView($(PropertyEditorPortsTemplate), this);
        this.renderGroups();
    }
    setParameterEx(name, newvalue, oldvalue, skipundo) {
        this.model.setParameter(name, newvalue, {
            undo: !skipundo,
            oldValue: oldvalue,
            label: 'edit parameter'
        });
    }
    setParameter(name, newvalue) {
        this.model.setParameter(name, newvalue, { undo: true, label: 'edit parameter' });
    }
    viewClassForPort(p) {
        const type = getEditType(p);
        // Check for custom editorType
        if (typeof type === 'object' && type.editorType === 'logic-builder-workspace') {
            return LogicBuilderWorkspaceType;
        }
        // Hidden type for internal Logic Builder parameters (renders nothing)
        if (typeof type === 'object' && type.editorType === 'logic-builder-hidden') {
            return LogicBuilderHiddenType;
        }
        // Align tools types
        function isOfAlignToolsType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'enum' && typeof type === 'object' && type.alignComp !== undefined;
        }
        // Size mode types
        function isOfSizeModeType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'enum' && typeof type === 'object' && type.sizeComp === 'mode';
        }
        // Enum types
        function isOfEnumType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'enum' && typeof type === 'object' && type.enums;
        }
        // Color types
        function isOfColorType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'color';
        }
        // Boolean types
        function isOfBooleanType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'boolean';
        }
        // Basic types
        function isOfBasicType() {
            const name = nodelibrary/* NodeLibrary */.m.nameForPortType(type);
            return name === 'string' || name === 'number';
        }
        // Is of text area type
        function isOfTextAreaType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'string' && typeof type === 'object' && type.multiline;
        }
        // Is of code editor type
        function isOfCodeEditorType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'string' && typeof type === 'object' && type.codeeditor;
        }
        function isOfArrayType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'array';
        }
        // Image ref type
        function isOfImageType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'image';
        }
        // Icon ref type
        function isOfIconType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'icon';
        }
        // Font ref type
        function isOfFontType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'font';
        }
        // Text style type
        function isOfTextStyleType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'textStyle';
        }
        // Component reference type
        function isOfComponentType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'component';
        }
        // Number with units
        function isOfNumberWithUnitsType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'number' && type.units !== undefined;
        }
        // Dimension type (number, unit dropdown and special boolean for fixed dimension)
        function isOfDimensionType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'dimension';
        }
        // Is source code file
        function isOfSourceCodeFileType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'source';
        }
        // Is string list type
        function isOfStringListType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'stringlist';
        }
        // Is margin padding type
        function isOfMarginPaddingType() {
            //  return NodeLibrary.nameForPortType(type) === 'margins' || NodeLibrary.nameForPortType(type) === 'padding';
            return type && type.marginPaddingComp !== undefined;
        }
        // Is of resizing type
        function isOfResizingType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'resizing';
        }
        // Is of variable type
        function isOfVariableType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'variable';
        }
        // Is of identifier
        function isOfIdentifierType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'string' && typeof type === 'object' && type.identifierOf;
        }
        // Is of curve
        function isOfCurveType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'curve';
        }
        // Is of query
        function isOfQueryFilterType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'query-filter';
        }
        function isOfQuerySortingType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'query-sorting';
        }
        function isOfByobFilterType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'byob-filter';
        }
        // Is of pages type
        function isOfPagesType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'pages';
        }
        // Is of proplist
        function isOfPropListType() {
            return nodelibrary/* NodeLibrary */.m.nameForPortType(type) === 'proplist';
        }
        if (isOfAlignToolsType())
            return AlignToolsType;
        else if (isOfSizeModeType())
            return SizeModeType;
        else if (isOfEnumType())
            return EnumType;
        else if (isOfColorType())
            return ColorType;
        else if (isOfBooleanType())
            return BooleanType;
        else if (isOfTextAreaType())
            return TextAreaType;
        else if (isOfCodeEditorType())
            return CodeEditorType;
        else if (isOfArrayType())
            return CodeEditorType;
        else if (isOfMarginPaddingType())
            return MarginPaddingType;
        else if (isOfNumberWithUnitsType())
            return NumberWithUnits;
        else if (isOfDimensionType())
            return Dimension;
        else if (isOfIdentifierType())
            return IdentifierType;
        else if (isOfBasicType())
            return BasicType;
        else if (isOfImageType())
            return ImageType;
        else if (isOfIconType())
            return IconType;
        else if (isOfFontType())
            return FontType;
        else if (isOfTextStyleType())
            return TextStyleType;
        else if (isOfComponentType())
            return ComponentType;
        else if (isOfSourceCodeFileType())
            return SourceCodeType;
        else if (isOfStringListType())
            return StringListType;
        else if (isOfResizingType())
            return ResizingType;
        else if (isOfVariableType())
            return VariableType;
        else if (isOfCurveType())
            return CurveType;
        else if (isOfQueryFilterType())
            return QueryFilterType;
        else if (isOfQuerySortingType())
            return QuerySortingType;
        else if (isOfByobFilterType())
            return ByobFilterType;
        else if (isOfPagesType())
            return PagesType;
        else if (isOfPropListType())
            return PropListType;
    }
    _getPorts() {
        let ports = this.model.getPorts('input');
        // Is type editable
        function isOfEditableType(p) {
            return !(typeof p.type === 'object' && p.type.allowConnectionsOnly);
        }
        // Remote not editable and ports that don't have an associated view
        ports = ports.filter((p) => isOfEditableType(p) && this.viewClassForPort(p) !== undefined);
        // If this is a popout remote all ports not beloning to this popout
        if (this.popout !== undefined)
            ports = ports.filter((p) => !(p.popout === undefined || p.popout.group !== this.popout));
        return ports;
    }
    getViewGroupsFromPorts() {
        const ports = this._getPorts();
        // Loop over all ports and create views
        this._toolsType = {};
        const _viewForPort = {};
        const _tabViews = {};
        const _popoutViews = {};
        this.views = [];
        let v;
        for (const i in ports) {
            const p = ports[i];
            if (p.popout !== undefined && this.popout === undefined) {
                // This port belongs to a popout
                if (_popoutViews[p.popout.group] === undefined) {
                    _popoutViews[p.popout.group] = new PopoutGroup({
                        group: p.popout.parentGroup || p.group,
                        popoutGroup: p.popout.group,
                        label: p.popout.label,
                        parent: this
                    });
                    this.views.push(_popoutViews[p.popout.group]);
                    _viewForPort[p.name] = v;
                }
                continue;
            }
            const viewClass = this.viewClassForPort(p);
            if (viewClass !== undefined) {
                v = viewClass.fromPort({ port: p, parent: this });
                if (v !== undefined) {
                    this.views.push(v);
                    _viewForPort[p.name] = v;
                }
            }
        }
        // Group property views
        const groups = (this.groups = []);
        function addToGroup(view) {
            const name = view.group ? view.group : 'Other';
            for (const i in groups) {
                const g = groups[i];
                if (g.name === name) {
                    g.views.push(view);
                    return;
                }
            }
            groups.push({ name: name, views: [view], isExpanded: true });
        }
        for (const i in this.views) {
            v = this.views[i];
            if (v.port !== undefined && v.port.parent !== undefined) {
                // This view port is a child to a parent port
                // add it to that view
                const parentV = _viewForPort[v.port.parent];
                parentV && parentV.addChildTypeView && parentV.addChildTypeView(v);
            }
            else if (v.port !== undefined && v.port.tab !== undefined) {
                // This port belongs to a tab group
                const group = v.port.tab.group;
                if (_tabViews[group] === undefined) {
                    _tabViews[group] = new TabGroup({
                        group: v.group,
                        tabGroup: group,
                        parent: this
                    });
                    addToGroup(_tabViews[group]);
                }
                _tabViews[group].addView(v);
            }
            else
                addToGroup(v);
        }
        return this.groups;
    }
}

;// ./src/editor/src/views/panels/ProjectSettingsPanel/ProjectSettingsModel.ts





class ProjectSettingsModel extends (model_default()) {
    constructor() {
        super();
        this.project = projectmodel.ProjectModel.instance;
        this.loadSettings();
        const _this = this;
        nodelibrary/* NodeLibrary */.m.instance.on('libraryUpdated', function () {
            _this.loadSettings();
            _this.notifyListeners('settingsChanged');
        }, this);
        this.bindProjectModel();
        EventDispatcher.EventDispatcher.instance.on('ProjectModel.instanceHasChanged', (args) => {
            args.oldInstance && args.oldInstance.off(this);
            if (projectmodel.ProjectModel.instance === undefined)
                return;
            _this.project = projectmodel.ProjectModel.instance;
            _this.bindProjectModel();
            _this.loadSettings();
            _this.notifyListeners('settingsChanged');
        }, this);
    }
    dispose() {
        nodelibrary/* NodeLibrary */.m.instance.off(this);
        EventDispatcher.EventDispatcher.instance.off(this);
        this.project && this.project.off(this);
    }
    bindProjectModel() {
        const _this = this;
        this.project.on('settingsChanged', function () {
            _this.loadSettings();
            _this.notifyListeners('settingsChanged');
        }, this);
    }
    loadSettings() {
        this._ports = undefined;
        // NOTE: We are getting the ports here!
        this.type = nodelibrary/* NodeLibrary */.m.instance.getProjectSettingsPorts();
        this.parameters = JSON.parse(JSON.stringify(this.project.getSettings()));
        //this.parameters.name = this.project.name; // Name of project
    }
    unbind() {
        nodelibrary/* NodeLibrary */.m.instance.off(this);
    }
    getParameter(name) {
        return this.parameters[name] !== undefined ? this.parameters[name] : this.getPort(name).default;
    }
    getPort(name) {
        const ports = this.getPorts();
        return (0,external_underscore_.find)(ports, function (p) {
            return p.name === name;
        });
    }
    getPorts() {
        if (this._ports)
            return this._ports;
        // Project name
        let ports = [
        /* {
          type:'string',
          name:'name',
          displayName:'Name',
          group:'General',
        }*/
        ];
        // Static ports
        ports = ports.concat(this.type.ports || []);
        // Dynamic ports
        //var dynamicports = NodeLibrary.instance.getDynamicPortsForNode(this);
        //if(dynamicports) ports = ports.concat(dynamicports);
        this._ports = ports;
        return ports;
    }
    setParameter(name, value) {
        /* if(name === 'name') {
          // Project name changed
          this.project.rename(value);
        }*/
        this.parameters[name] = value;
        // Push to project settings right away
        const settings = JSON.parse(JSON.stringify(this.parameters));
        //delete settings.name; // Remove the project name from settings
        this.project.setSettings(settings);
        this._ports = undefined;
        this.notifyListeners('settingsChanged');
    }
    isEmpty() {
        return this.getPorts().length === 0;
    }
    isPortConnected() {
        return false;
    }
}

// EXTERNAL MODULE: ../noodl-core-ui/src/components/property-panel/PropertyPanelCheckbox/index.ts + 2 modules
var PropertyPanelCheckbox = __webpack_require__(37837);
;// ./src/editor/src/views/panels/ProjectSettingsPanel/sections/DeploySection.tsx









function DeploySection() {
    const [enabledDeployDate, setEnabledDeployDate] = (0,external_react_.useState)(!!projectmodel.ProjectModel.instance.settings['deployEnvDate']);
    const [enabledGitStats, setEnabledGitStats] = (0,external_react_.useState)(!!projectmodel.ProjectModel.instance.settings['deployEnvGitStats']);
    const [baseUrl, setBaseUrl] = (0,external_react_.useState)(projectmodel.ProjectModel.instance.settings['baseUrl']);
    function handleBaseUrl(value) {
        setBaseUrl(value);
        projectmodel.ProjectModel.instance.setSetting('baseUrl', value);
    }
    function handleEnableDeployDate(value) {
        setEnabledDeployDate(value);
        projectmodel.ProjectModel.instance.setSetting('deployEnvDate', value);
    }
    function handleEnableGitStats(value) {
        setEnabledGitStats(value);
        projectmodel.ProjectModel.instance.setSetting('deployEnvGitStats', value);
    }
    return (external_react_default().createElement(CollapsableSection/* CollapsableSection */.M, { title: "Experimental features - Deploy Settings", hasGutter: true, hasVisibleOverflow: true, isClosed: true },
        external_react_default().createElement(ExperimentalFlag, { variant: ExperimentalFlagVariant.NoPadding, text: "All these settings are temporary and will be moved to another place in a future version." }),
        external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
            external_react_default().createElement(typography_Text/* Text */.EY, null, "The Base Url.")),
        external_react_default().createElement(PropertyPanelInput/* PropertyPanelRow */.eh, { label: "Custom Base Url" },
            external_react_default().createElement(PropertyPanelTextInput/* PropertyPanelTextInput */.$, { value: baseUrl, onChange: handleBaseUrl })),
        external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
            external_react_default().createElement(typography_Text/* Text */.EY, null, "Noodl.Env.BaseUrl: Get the current base url.")),
        external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true, hasTopSpacing: true },
            external_react_default().createElement(typography_Text/* Text */.EY, null, "Include some extra variables in Noodl.Env:")),
        external_react_default().createElement(PropertyPanelInput/* PropertyPanelRow */.eh, { label: "Deploy Date" },
            external_react_default().createElement(PropertyPanelCheckbox/* PropertyPanelCheckbox */.d, { value: enabledDeployDate, onChange: handleEnableDeployDate })),
        external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
            external_react_default().createElement(typography_Text/* Text */.EY, null, "Noodl.Env.DeployedAt: The deploy date time in UTC format.")),
        external_react_default().createElement(PropertyPanelInput/* PropertyPanelRow */.eh, { label: "Git Stats" },
            external_react_default().createElement(PropertyPanelCheckbox/* PropertyPanelCheckbox */.d, { value: enabledGitStats, onChange: handleEnableGitStats })),
        external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
            external_react_default().createElement(typography_Text/* Text */.EY, null, "Noodl.Env.GitBranch: The current git branch."),
            external_react_default().createElement(typography_Text/* Text */.EY, null, "Noodl.Env.GitSha: The current git commit sha."))));
}

;// ./src/editor/src/views/panels/ProjectSettingsPanel/sections/SitemapSection.tsx





function SitemapSection() {
    const [enabled, setEnabled] = (0,external_react_.useState)(!!projectmodel.ProjectModel.instance.settings['sitemap.enabled']);
    function handleEnable(value) {
        setEnabled(value);
        projectmodel.ProjectModel.instance.setSetting('sitemap.enabled', value);
    }
    // function handlePreviewSitemap() {
    //   // TODO: Show sitemap
    // }
    return (external_react_default().createElement(CollapsableSection/* CollapsableSection */.M, { title: "Experimental features - Sitemap", hasGutter: true, hasVisibleOverflow: true, hasTopDivider: true, isClosed: true },
        external_react_default().createElement(PropertyPanelInput/* PropertyPanelRow */.eh, { label: "Enable" },
            external_react_default().createElement(PropertyPanelCheckbox/* PropertyPanelCheckbox */.d, { value: enabled, onChange: handleEnable }))));
}

;// ./src/editor/src/views/panels/ProjectSettingsPanel/ProjectSettingsPanel.tsx













// eslint-disable-next-line no-empty-pattern
function ProjectSettingsPanel({}) {
    const [propertyView, setPropertyView] = (0,external_react_.useState)(null);
    const [renderIndex, triggerRerender] = useTriggerRerenderState();
    function onOpenProjectFolderClicked() {
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        const shell = (__webpack_require__(52391).shell);
        shell.showItemInFolder(external_path_default().normalize(projectmodel.ProjectModel.instance._retainedProjectDirectory + '/project.json'));
    }
    (0,external_react_.useEffect)(() => {
        const settingsModel = new ProjectSettingsModel();
        const view = new Ports({
            model: settingsModel
        });
        view.render();
        setPropertyView(view);
        settingsModel.on('settingsChanged', () => {
            triggerRerender();
        });
        return function () {
            settingsModel.dispose();
        };
    }, []);
    return (external_react_default().createElement(BasePanel, { title: "Project Settings", hasContentScroll: true },
        external_react_default().createElement(Section/* Section */.w, { hasGutter: true, hasVisibleOverflow: true },
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { icon: common_Icon/* IconName */.$M.FolderOpen, size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, label: "Open project folder", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, onClick: onOpenProjectFolderClicked, isGrowing: true })),
        external_react_default().createElement(Frame, { instance: propertyView, refresh: renderIndex }),
        external_react_default().createElement(SitemapSection, null),
        external_react_default().createElement(DeploySection, null)));
}

// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/AiAssistantModel.ts + 11 modules
var AiAssistantModel = __webpack_require__(77510);
// EXTERNAL MODULE: ./src/editor/src/models/AiAssistant/ChatHistory.ts
var ChatHistory = __webpack_require__(75928);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/ai/AiChatBox/AiChatBox.module.scss
var AiChatBox_module = __webpack_require__(19817);
;// ../noodl-core-ui/src/components/ai/AiChatBox/AiChatBox.module.scss

      
      
      
      
      
      
      
      
      

var AiChatBox_module_options = {};

AiChatBox_module_options.styleTagTransform = (styleTagTransform_default());
AiChatBox_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      AiChatBox_module_options.insert = insertBySelector_default().bind(null, "head");
    
AiChatBox_module_options.domAPI = (styleDomAPI_default());
AiChatBox_module_options.insertStyleElement = (insertStyleElement_default());

var AiChatBox_module_update = injectStylesIntoStyleTag_default()(AiChatBox_module/* default */.A, AiChatBox_module_options);




       /* harmony default export */ const AiChatBox_AiChatBox_module = (AiChatBox_module/* default */.A && AiChatBox_module/* default */.A.locals ? AiChatBox_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/ai/AiChatBox/AiChatBox.tsx







function AiChatBox({ children, footer }) {
    const scrollableRef = (0,external_react_.useRef)(null);
    const scrollBottomRef = (0,external_react_.useRef)(null);
    const [isTracking, setIsTracking] = (0,external_react_.useState)(true);
    const isTrackingRef = (0,external_react_.useRef)(true);
    const lastScrollTop = (0,external_react_.useRef)(0);
    const isJumpingToPresent = (0,external_react_.useRef)(false);
    const onResize = (0,external_react_.useCallback)(() => {
        if (isTrackingRef.current && scrollBottomRef.current) {
            scrollBottomRef.current.scrollIntoView({ behavior: 'auto' });
        }
    }, []);
    (0,external_react_.useEffect)(() => {
        if (!scrollableRef.current)
            return;
        function handleScroll() {
            const elem = scrollableRef.current;
            if (!isJumpingToPresent.current) {
                // Remove decimals from scrollTop to make it pixel perfect
                elem.scrollTop = Math.round(elem.scrollTop);
            }
            // scrollTop can be half a pixel off, so you will never hit the bottom.
            const isAtBottom = elem.scrollTop + elem.clientHeight + 1 >= elem.scrollHeight;
            setIsTracking(isAtBottom);
            isTrackingRef.current = isAtBottom;
            lastScrollTop.current = scrollableRef.current.scrollTop;
            if (isAtBottom && isJumpingToPresent.current) {
                isJumpingToPresent.current = false;
            }
        }
        const scrollable = scrollableRef.current;
        scrollable.addEventListener('scroll', handleScroll);
        const observer = new ResizeObserver(onResize);
        observer.observe(scrollableRef.current);
        return () => {
            observer.disconnect();
            scrollable.removeEventListener('scroll', handleScroll);
        };
    }, [onResize, scrollableRef]);
    (0,external_react_.useEffect)(() => {
        // Scroll to the bottom at the start
        if (scrollBottomRef.current) {
            scrollBottomRef.current.scrollIntoView({ behavior: 'auto' });
        }
    }, []);
    (0,external_react_.useEffect)(() => {
        if (scrollableRef.current && !isTracking) {
            scrollableRef.current.scrollTop = lastScrollTop.current;
        }
    }, [children, isTracking]);
    function handleScrollToBottom() {
        if (scrollBottomRef.current) {
            isJumpingToPresent.current = true;
            scrollBottomRef.current.scrollIntoView({ behavior: 'smooth' });
        }
    }
    if (isTracking && scrollBottomRef.current) {
        requestAnimationFrame(() => {
            if (scrollBottomRef.current) {
                scrollBottomRef.current.scrollIntoView({ behavior: 'auto' });
            }
        });
    }
    return (external_react_default().createElement(Stack/* VStack */.Tk, { UNSAFE_style: { height: '100%', width: '100%' } },
        external_react_default().createElement("div", { className: AiChatBox_AiChatBox_module['ScrollContainer'] },
            external_react_default().createElement("div", { className: AiChatBox_AiChatBox_module['ScrollArea'], ref: scrollableRef },
                children,
                external_react_default().createElement("span", { ref: scrollBottomRef })),
            !isTracking && (external_react_default().createElement("div", { className: AiChatBox_AiChatBox_module['JumpToPresentContainer'] },
                external_react_default().createElement("div", { className: external_classnames_default()(AiChatBox_AiChatBox_module['JumpToPresent'], AiChatBox_AiChatBox_module['is-past']), onClick: handleScrollToBottom },
                    external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: 1 },
                        external_react_default().createElement(typography_Text/* Text */.EY, null, "Jump To Present"),
                        external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.ArrowDown, size: common_Icon/* IconSize */.lK.Tiny })))))),
        Boolean(footer) && (external_react_default().createElement(Section/* Section */.w, { hasGutter: true, hasTopDivider: true, hasVisibleOverflow: true }, footer))));
}

;// ../noodl-core-ui/src/components/ai/AiChatBox/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/ai/AiChatboxError/AiChatboxError.module.scss
var AiChatboxError_module = __webpack_require__(58973);
;// ../noodl-core-ui/src/components/ai/AiChatboxError/AiChatboxError.module.scss

      
      
      
      
      
      
      
      
      

var AiChatboxError_module_options = {};

AiChatboxError_module_options.styleTagTransform = (styleTagTransform_default());
AiChatboxError_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      AiChatboxError_module_options.insert = insertBySelector_default().bind(null, "head");
    
AiChatboxError_module_options.domAPI = (styleDomAPI_default());
AiChatboxError_module_options.insertStyleElement = (insertStyleElement_default());

var AiChatboxError_module_update = injectStylesIntoStyleTag_default()(AiChatboxError_module/* default */.A, AiChatboxError_module_options);




       /* harmony default export */ const AiChatboxError_AiChatboxError_module = (AiChatboxError_module/* default */.A && AiChatboxError_module/* default */.A.locals ? AiChatboxError_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/ai/AiChatboxError/AiChatboxError.tsx




function AiChatboxError({ title = 'Aw, Snap!', content }) {
    return (external_react_default().createElement("div", { className: AiChatboxError_AiChatboxError_module['Root'] },
        external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Big, hasBottomSpacing: true }, title),
        external_react_default().createElement(typography_Text/* Text */.EY, { style: { textAlign: 'center' } }, content)));
}

;// ../noodl-core-ui/src/components/ai/AiChatboxError/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/ai/AiIconAnimated/AiIconAnimated.module.scss
var AiIconAnimated_module = __webpack_require__(27183);
;// ../noodl-core-ui/src/components/ai/AiIconAnimated/AiIconAnimated.module.scss

      
      
      
      
      
      
      
      
      

var AiIconAnimated_module_options = {};

AiIconAnimated_module_options.styleTagTransform = (styleTagTransform_default());
AiIconAnimated_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      AiIconAnimated_module_options.insert = insertBySelector_default().bind(null, "head");
    
AiIconAnimated_module_options.domAPI = (styleDomAPI_default());
AiIconAnimated_module_options.insertStyleElement = (insertStyleElement_default());

var AiIconAnimated_module_update = injectStylesIntoStyleTag_default()(AiIconAnimated_module/* default */.A, AiIconAnimated_module_options);




       /* harmony default export */ const AiIconAnimated_AiIconAnimated_module = (AiIconAnimated_module/* default */.A && AiIconAnimated_module/* default */.A.locals ? AiIconAnimated_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/ai/AiIconAnimated/AiIconAnimated.tsx



function AiIconAnimated({ isListening, isDimmed, UNSAFE_className, UNSAFE_style }) {
    return (external_react_default().createElement("div", { className: external_classnames_default()(AiIconAnimated_AiIconAnimated_module.Root, isListening && AiIconAnimated_AiIconAnimated_module.__isListening, isDimmed && AiIconAnimated_AiIconAnimated_module.__isDimmed, UNSAFE_className), style: UNSAFE_style },
        external_react_default().createElement("div", { className: AiIconAnimated_AiIconAnimated_module.HeroLogoWrapper },
            external_react_default().createElement("div", { className: AiIconAnimated_AiIconAnimated_module.HeroLogo },
                external_react_default().createElement("span", null, "Ai"),
                external_react_default().createElement("div", { className: AiIconAnimated_AiIconAnimated_module.LogoIdleCircleContainer },
                    external_react_default().createElement("div", { className: AiIconAnimated_AiIconAnimated_module.LogoIdleCircleInner },
                        external_react_default().createElement("div", { className: AiIconAnimated_AiIconAnimated_module.LogoIdleCircle }))),
                external_react_default().createElement("div", { className: AiIconAnimated_AiIconAnimated_module.LogoLoader },
                    external_react_default().createElement("div", { className: AiIconAnimated_AiIconAnimated_module.LogoLoaderInner },
                        external_react_default().createElement("div", { className: AiIconAnimated_AiIconAnimated_module.Circle1 },
                            external_react_default().createElement("span", { className: AiIconAnimated_AiIconAnimated_module.SpinningBalls })),
                        external_react_default().createElement("div", { className: AiIconAnimated_AiIconAnimated_module.Circle2 },
                            external_react_default().createElement("span", { className: AiIconAnimated_AiIconAnimated_module.SpinningBalls }))))))));
}

;// ../noodl-core-ui/src/components/ai/AiIconAnimated/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/ai/AiChatLoader/AiChatLoader.module.scss
var AiChatLoader_module = __webpack_require__(21613);
;// ../noodl-core-ui/src/components/ai/AiChatLoader/AiChatLoader.module.scss

      
      
      
      
      
      
      
      
      

var AiChatLoader_module_options = {};

AiChatLoader_module_options.styleTagTransform = (styleTagTransform_default());
AiChatLoader_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      AiChatLoader_module_options.insert = insertBySelector_default().bind(null, "head");
    
AiChatLoader_module_options.domAPI = (styleDomAPI_default());
AiChatLoader_module_options.insertStyleElement = (insertStyleElement_default());

var AiChatLoader_module_update = injectStylesIntoStyleTag_default()(AiChatLoader_module/* default */.A, AiChatLoader_module_options);




       /* harmony default export */ const AiChatLoader_AiChatLoader_module = (AiChatLoader_module/* default */.A && AiChatLoader_module/* default */.A.locals ? AiChatLoader_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/ai/AiChatLoader/AiChatLoader.tsx






function AiChatLoader({ text = 'Thinking...' }) {
    return (external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasYSpacing: 1, UNSAFE_className: AiChatLoader_AiChatLoader_module['Root'] },
        external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { minHeight: '18px' } },
            external_react_default().createElement(AiIconAnimated, { isListening: true, UNSAFE_style: { marginLeft: '-13px', marginRight: '5px' } }),
            external_react_default().createElement("div", { style: { display: 'flex', alignItems: 'center' } },
                external_react_default().createElement(typography_Text/* Text */.EY, null, text)))));
}

;// ../noodl-core-ui/src/components/ai/AiChatLoader/index.ts


;// ../noodl-core-ui/src/components/ai/AiIcon/AiIcon.tsx

function AiIcon({ UNSAFE_className, UNSAFE_style }) {
    const gradientId = 'd2d05813-26d2-4c03-812e-75f68a94b149';
    const gradientUrl = `url(#${gradientId})`;
    return (external_react_default().createElement("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", className: UNSAFE_className, style: UNSAFE_style },
        external_react_default().createElement("path", { d: "M10.9512 3.22576C11.5593 3.22576 12.0522 2.72751 12.0522 2.11288C12.0522 1.49825 11.5593 1 10.9512 1C10.3432 1 9.85022 1.49825 9.85022 2.11288C9.85022 2.72751 10.3432 3.22576 10.9512 3.22576Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M6.68969 4.40009C7.22049 4.40009 7.65079 3.96515 7.65079 3.42863C7.65079 2.8921 7.22049 2.45716 6.68969 2.45716C6.15889 2.45716 5.72859 2.8921 5.72859 3.42863C5.72859 3.96515 6.15889 4.40009 6.68969 4.40009Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M3.82576 6.73112C4.26115 6.73112 4.61411 6.37436 4.61411 5.93428C4.61411 5.49419 4.26115 5.13743 3.82576 5.13743C3.39037 5.13743 3.03742 5.49419 3.03742 5.93428C3.03742 6.37436 3.39037 6.73112 3.82576 6.73112Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M2.11012 9.34882C2.44573 9.34882 2.7178 9.07382 2.7178 8.73459C2.7178 8.39535 2.44573 8.12035 2.11012 8.12035C1.77451 8.12035 1.50244 8.39535 1.50244 8.73459C1.50244 9.07382 1.77451 9.34882 2.11012 9.34882Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M1.46048 12.4432C1.71479 12.4432 1.92095 12.2348 1.92095 11.9778C1.92095 11.7207 1.71479 11.5123 1.46048 11.5123C1.20616 11.5123 1 11.7207 1 11.9778C1 12.2348 1.20616 12.4432 1.46048 12.4432Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M1.78458 15.2657C1.96431 15.2657 2.11001 15.1185 2.11001 14.9368C2.11001 14.7551 1.96431 14.6079 1.78458 14.6079C1.60485 14.6079 1.45914 14.7551 1.45914 14.9368C1.45914 15.1185 1.60485 15.2657 1.78458 15.2657Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M13.0506 23C13.6587 23 14.1516 22.5017 14.1516 21.8871C14.1516 21.2725 13.6587 20.7742 13.0506 20.7742C12.4426 20.7742 11.9496 21.2725 11.9496 21.8871C11.9496 22.5017 12.4426 23 13.0506 23Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M17.3074 21.5417C17.8382 21.5417 18.2685 21.1067 18.2685 20.5702C18.2685 20.0337 17.8382 19.5988 17.3074 19.5988C16.7766 19.5988 16.3463 20.0337 16.3463 20.5702C16.3463 21.1067 16.7766 21.5417 17.3074 21.5417Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M20.1722 18.8626C20.6076 18.8626 20.9605 18.5058 20.9605 18.0657C20.9605 17.6256 20.6076 17.2689 20.1722 17.2689C19.7368 17.2689 19.3839 17.6256 19.3839 18.0657C19.3839 18.5058 19.7368 18.8626 20.1722 18.8626Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M21.8873 15.8798C22.2229 15.8798 22.4949 15.6048 22.4949 15.2656C22.4949 14.9264 22.2229 14.6514 21.8873 14.6514C21.5516 14.6514 21.2796 14.9264 21.2796 15.2656C21.2796 15.6048 21.5516 15.8798 21.8873 15.8798Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M22.5395 12.4879C22.7938 12.4879 23 12.2795 23 12.0224C23 11.7654 22.7938 11.557 22.5395 11.557C22.2852 11.557 22.079 11.7654 22.079 12.0224C22.079 12.2795 22.2852 12.4879 22.5395 12.4879Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M22.2142 9.39194C22.3939 9.39194 22.5396 9.24467 22.5396 9.06299C22.5396 8.88132 22.3939 8.73405 22.2142 8.73405C22.0344 8.73405 21.8887 8.88132 21.8887 9.06299C21.8887 9.24467 22.0344 9.39194 22.2142 9.39194Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M21.1878 6.79557C21.2847 6.79557 21.3633 6.71613 21.3633 6.61815C21.3633 6.52016 21.2847 6.44073 21.1878 6.44073C21.0908 6.44073 21.0123 6.52016 21.0123 6.61815C21.0123 6.71613 21.0908 6.79557 21.1878 6.79557Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M2.81427 17.6774C2.91122 17.6774 2.98981 17.5979 2.98981 17.5C2.98981 17.402 2.91122 17.3225 2.81427 17.3225C2.71732 17.3225 2.63873 17.402 2.63873 17.5C2.63873 17.5979 2.71732 17.6774 2.81427 17.6774Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M11.9629 14.689C11.9522 14.6574 11.9227 14.6361 11.8896 14.6361H8.30035C8.26724 14.6361 8.2378 14.6574 8.22707 14.689L7.6507 16.3907C7.63998 16.4223 7.61053 16.4436 7.57742 16.4436H5.78604C5.73253 16.4436 5.69514 16.3901 5.71306 16.3391L8.99863 6.99596C9.0096 6.96475 9.03883 6.94389 9.07161 6.94389H11.1317C11.1644 6.94389 11.1937 6.96475 11.2046 6.99596L14.4902 16.3391C14.5081 16.3901 14.4707 16.4436 14.4172 16.4436H12.6125C12.5794 16.4436 12.55 16.4223 12.5393 16.3907L11.9629 14.689ZM11.3308 13.114C11.384 13.114 11.4213 13.0611 11.4041 13.0103L10.1683 9.36187C10.1444 9.2913 10.0456 9.2913 10.0217 9.36187L8.78585 13.0103C8.76865 13.0611 8.806 13.114 8.85913 13.114H11.3308Z", fill: gradientUrl }),
        external_react_default().createElement("path", { d: "M17.5615 6.95748C17.6043 6.95748 17.6389 6.99253 17.6389 7.03576V16.3653C17.6389 16.4086 17.6043 16.4436 17.5615 16.4436H15.8531C15.8103 16.4436 15.7756 16.4086 15.7756 16.3653V7.03576C15.7756 6.99253 15.8103 6.95748 15.8531 6.95748H17.5615Z", fill: gradientUrl }),
        external_react_default().createElement("defs", null,
            external_react_default().createElement("linearGradient", { id: gradientId, x1: "11.6737", y1: "6.94385", x2: "11.6737", y2: "16.4436", gradientUnits: "userSpaceOnUse" },
                external_react_default().createElement("stop", { stopColor: "#B4B2FC" }),
                external_react_default().createElement("stop", { offset: "1", stopColor: "#A0EAEE" })))));
}

;// ../noodl-core-ui/src/components/ai/AiIcon/index.ts


// EXTERNAL MODULE: external "remarkable"
var external_remarkable_ = __webpack_require__(31890);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/common/Markdown/Markdown.module.scss
var Markdown_module = __webpack_require__(68336);
;// ../noodl-core-ui/src/components/common/Markdown/Markdown.module.scss

      
      
      
      
      
      
      
      
      

var Markdown_module_options = {};

Markdown_module_options.styleTagTransform = (styleTagTransform_default());
Markdown_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      Markdown_module_options.insert = insertBySelector_default().bind(null, "head");
    
Markdown_module_options.domAPI = (styleDomAPI_default());
Markdown_module_options.insertStyleElement = (insertStyleElement_default());

var Markdown_module_update = injectStylesIntoStyleTag_default()(Markdown_module/* default */.A, Markdown_module_options);




       /* harmony default export */ const Markdown_Markdown_module = (Markdown_module/* default */.A && Markdown_module/* default */.A.locals ? Markdown_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/common/Markdown/Markdown.tsx




function Markdown({ content, UNSAFE_className, UNSAFE_style }) {
    const __html = (0,external_react_.useMemo)(() => {
        const md = new external_remarkable_.Remarkable({
            html: true,
            breaks: true
        });
        return md.render(content);
    }, [content]);
    return (external_react_default().createElement("div", { className: external_classnames_default()([Markdown_Markdown_module['Root'], UNSAFE_className]), style: UNSAFE_style, dangerouslySetInnerHTML: { __html } }));
}

;// ../noodl-core-ui/src/components/common/Markdown/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/ai/AiChatMessage/AiChatMessage.module.scss
var AiChatMessage_module = __webpack_require__(96061);
;// ../noodl-core-ui/src/components/ai/AiChatMessage/AiChatMessage.module.scss

      
      
      
      
      
      
      
      
      

var AiChatMessage_module_options = {};

AiChatMessage_module_options.styleTagTransform = (styleTagTransform_default());
AiChatMessage_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      AiChatMessage_module_options.insert = insertBySelector_default().bind(null, "head");
    
AiChatMessage_module_options.domAPI = (styleDomAPI_default());
AiChatMessage_module_options.insertStyleElement = (insertStyleElement_default());

var AiChatMessage_module_update = injectStylesIntoStyleTag_default()(AiChatMessage_module/* default */.A, AiChatMessage_module_options);




       /* harmony default export */ const AiChatMessage_AiChatMessage_module = (AiChatMessage_module/* default */.A && AiChatMessage_module/* default */.A.locals ? AiChatMessage_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/ai/AiChatMessage/AiChatMessage.tsx







function AiChatMessage({ user, content, affix }) {
    return (external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasYSpacing: true, UNSAFE_className: AiChatMessage_AiChatMessage_module['Root'] },
        external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { height: 'auto', minHeight: '18px' } },
            Boolean(user) && (external_react_default().createElement(Box/* Box */.a, { hasRightSpacing: true },
                external_react_default().createElement("div", { style: { position: 'relative', width: '18px' } },
                    user.role === 'user' && (external_react_default().createElement(UserBadge, { size: UserBadgeSize.Tiny, name: user.name, email: user.name, id: user.name })),
                    user.role === 'assistant' && (external_react_default().createElement(AiIcon, { UNSAFE_style: {
                            position: 'absolute',
                            left: '-3px',
                            top: '-2px'
                        } }))))),
            external_react_default().createElement(Markdown, { content: content, UNSAFE_style: { marginTop: '2px', userSelect: 'text' } })),
        Boolean(affix) && external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true }, affix)));
}

;// ../noodl-core-ui/src/components/ai/AiChatMessage/index.ts


// EXTERNAL MODULE: ../noodl-core-ui/src/components/layout/Center/index.ts + 2 modules
var Center = __webpack_require__(92394);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/ai/AiChatSuggestion/AiChatSuggestion.module.scss
var AiChatSuggestion_module = __webpack_require__(22619);
;// ../noodl-core-ui/src/components/ai/AiChatSuggestion/AiChatSuggestion.module.scss

      
      
      
      
      
      
      
      
      

var AiChatSuggestion_module_options = {};

AiChatSuggestion_module_options.styleTagTransform = (styleTagTransform_default());
AiChatSuggestion_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      AiChatSuggestion_module_options.insert = insertBySelector_default().bind(null, "head");
    
AiChatSuggestion_module_options.domAPI = (styleDomAPI_default());
AiChatSuggestion_module_options.insertStyleElement = (insertStyleElement_default());

var AiChatSuggestion_module_update = injectStylesIntoStyleTag_default()(AiChatSuggestion_module/* default */.A, AiChatSuggestion_module_options);




       /* harmony default export */ const AiChatSuggestion_AiChatSuggestion_module = (AiChatSuggestion_module/* default */.A && AiChatSuggestion_module/* default */.A.locals ? AiChatSuggestion_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/ai/AiChatSuggestion/AiChatSuggestion.tsx







function AiChatSuggestion({ text, isLoading, onClick }) {
    const [mounted, setMounted] = (0,external_react_.useState)(false);
    (0,external_react_.useEffect)(() => {
        setMounted(true);
    }, []);
    return (external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasYSpacing: 1 },
        external_react_default().createElement("div", { className: external_classnames_default()([AiChatSuggestion_AiChatSuggestion_module['Root'], mounted ? AiChatSuggestion_AiChatSuggestion_module['Mounted'] : AiChatSuggestion_AiChatSuggestion_module['Mounting']]), onClick: onClick }, isLoading ? (external_react_default().createElement(Center/* Center */.o, null,
            external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null))) : (external_react_default().createElement(typography_Text/* Text */.EY, null,
            "\u201C",
            text,
            "\u201D")))));
}

;// ../noodl-core-ui/src/components/ai/AiChatSuggestion/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/TextArea/TextArea.module.scss
var TextArea_module = __webpack_require__(21834);
;// ../noodl-core-ui/src/components/inputs/TextArea/TextArea.module.scss

      
      
      
      
      
      
      
      
      

var TextArea_module_options = {};

TextArea_module_options.styleTagTransform = (styleTagTransform_default());
TextArea_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      TextArea_module_options.insert = insertBySelector_default().bind(null, "head");
    
TextArea_module_options.domAPI = (styleDomAPI_default());
TextArea_module_options.insertStyleElement = (insertStyleElement_default());

var TextArea_module_update = injectStylesIntoStyleTag_default()(TextArea_module/* default */.A, TextArea_module_options);




       /* harmony default export */ const TextArea_TextArea_module = (TextArea_module/* default */.A && TextArea_module/* default */.A.locals ? TextArea_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/TextArea/TextArea.tsx







function TextArea({ value, placeholder, label, minLength, maxLength, notification, isDisabled, hasBottomSpacing, isResizeDisabled, isAutoFocus, onChange, onMouseEnter, onMouseLeave, onFocus, onBlur, onEnter, UNSAFE_className, UNSAFE_style }) {
    const [newNotification, _updateNotification] = useNotificationFeedbackDisplay(notification);
    const isEmpty = !(typeof value === 'string' && value.length > 0);
    return (external_react_default().createElement("div", { className: external_classnames_default()(TextArea_TextArea_module['Root'], hasBottomSpacing && TextArea_TextArea_module['has-bottom-spacing']) },
        label && external_react_default().createElement(InputLabelSection, { label: label }),
        external_react_default().createElement("div", { className: external_classnames_default()(TextArea_TextArea_module['InputArea'], isDisabled && TextArea_TextArea_module['is-disabled'], (newNotification === null || newNotification === void 0 ? void 0 : newNotification.message) && TextArea_TextArea_module['has-message']), onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave },
            external_react_default().createElement("textarea", { className: external_classnames_default()(TextArea_TextArea_module['Input'], isResizeDisabled && TextArea_TextArea_module['is-resize-disabled'], onChange && isEmpty && TextArea_TextArea_module['is-empty'], UNSAFE_className), style: UNSAFE_style, minLength: minLength, maxLength: maxLength, disabled: isDisabled, placeholder: placeholder, onChange: onChange, onFocus: onFocus, onBlur: onBlur, onKeyDown: (ev) => {
                    if (onEnter && ev.shiftKey && ev.key === 'Enter') {
                        onEnter();
                        ev.preventDefault();
                    }
                }, value: value, autoFocus: isAutoFocus }),
            newNotification && external_react_default().createElement(NotificationFeedbackDisplay, { notification: newNotification })),
        (newNotification === null || newNotification === void 0 ? void 0 : newNotification.message) && (external_react_default().createElement(typography_Text/* Text */.EY, { className: TextArea_TextArea_module['NotificationMessage'], textType: newNotification.type }, newNotification.message))));
}

;// ../noodl-core-ui/src/components/inputs/TextArea/index.ts


// EXTERNAL MODULE: ./src/editor/src/views/panels/propertyeditor/CodeEditor/CodeEditor.tsx + 6 modules
var CodeEditor_CodeEditor = __webpack_require__(67736);
;// ./src/editor/src/views/panels/propertyeditor/components/AiChat/AiChat.tsx


























function AiChat({ model, onUpdated }) {
    const [context, setContext] = (0,external_react_.useState)(null);
    const [error, setError] = (0,external_react_.useState)(null);
    const [group] = (0,external_react_.useState)({});
    (0,external_react_.useEffect)(() => {
        AiAssistantModel/* AiAssistantModel */.g.instance
            .createContext(model)
            .then((context) => {
            setContext(context);
        })
            .catch((error) => {
            setError(error);
        });
    }, []);
    (0,external_react_.useEffect)(() => {
        if (!context)
            return;
        context.chatHistory.on(ChatHistory/* ChatHistoryEvent */.Pw.ActivitiesChanged, () => {
            onUpdated();
        }, group);
        return () => {
            context.chatHistory.off(group);
        };
    }, [context]);
    if (error) {
        return (external_react_default().createElement(AiChatboxError, { content: "Cannot find the chat history for this node. Could it be that the chat history is missing in Version Control? :(" }));
    }
    if (!context) {
        return (external_react_default().createElement("div", { style: {
                height: '100%',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                flexDirection: 'column'
            } },
            external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
                external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null)),
            external_react_default().createElement(Label/* Label */.JU, null, "Loading Chat History...")));
    }
    return external_react_default().createElement(AiNodeChat, { context: context, onUpdated: onUpdated });
}
// TODO: clean up the typings across all AI fetures
function aiNodeTypeToPopupItemType(type) {
    switch (type) {
        case 'pink':
            return PopupItemType.Custom;
        case 'green':
            return PopupItemType.Data;
        case 'blue':
            return PopupItemType.Visual;
        default:
            return PopupItemType.Custom;
    }
}
function AiNodeChat({ context, onUpdated }) {
    (0,useModel/* useModernModel */.e)(context.chatHistory);
    const [message, setMessage] = (0,external_react_.useState)('');
    const canSend = context.chatHistory.activities.length === 0;
    function sendMessage(message) {
        tracker.tracker.track('AI Chat Message', {
            prompt: message,
            templateId: context.template.id,
            templateName: context.template.name,
            messages: context.chatHistory.messages.map((x) => ({
                content: x.content,
                type: x.type
            }))
        });
        context.chatHistory.add({
            content: message,
            metadata: {
                user: LocalUserIdentity.getUserInfo()
            }
        });
        const id = new Date().getTime().toString();
        AiAssistantModel/* AiAssistantModel */.g.instance.addActivity({
            id,
            type: aiNodeTypeToPopupItemType(context.template.type),
            title: context.template.name,
            prompt: message,
            node: context.node,
            graph: context.node.owner.owner
        });
        AiAssistantModel/* AiAssistantModel */.g.instance
            .send(context)
            .then(() => {
            console.log('done');
        })
            .catch((error) => {
            console.error(error);
        })
            .finally(() => {
            AiAssistantModel/* AiAssistantModel */.g.instance.removeActivity(id);
            onUpdated();
        });
    }
    function handleSubmit() {
        if (!(message && canSend))
            return;
        sendMessage(message);
        setMessage('');
    }
    // You should not be able to reactivly update this while having this panel open
    // So it will always re-render when opening the panel, and we get the latest version.
    const version = AiAssistantStore/* OpenAiStore */.q.getVersion();
    const prettyVersion = AiAssistantStore/* OpenAiStore */.q.getPrettyVersion();
    const activities = context.chatHistory.activities;
    const suggestions = context.chatHistory.suggestions;
    return (external_react_default().createElement(AiChatBox, { footer: version === 'disabled' ? (external_react_default().createElement(Center/* Center */.o, null,
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "Noodl AI is currently disabled."))) : (external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement(TextArea, { value: message, onChange: (e) => setMessage(e.target.value), placeholder: "Describe the task you want the function node to do", hasBottomSpacing: true, isResizeDisabled: true, onEnter: handleSubmit, UNSAFE_style: { minHeight: '72px', fontSize: '12px' } }),
            external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: 1 },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Send Message", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, isGrowing: true, isDisabled: !canSend, onClick: handleSubmit })))) },
        external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasYSpacing: true },
            external_react_default().createElement(Stack/* VStack */.Tk, null,
                external_react_default().createElement(Center/* Center */.o, null,
                    external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Shy, hasBottomSpacing: !!prettyVersion }, context.template.name)),
                prettyVersion && (external_react_default().createElement(Center/* Center */.o, null,
                    external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Shy, size: Label/* LabelSize */.IV.Small },
                        "(",
                        prettyVersion,
                        ")"))))),
        context.chatHistory.messages.map((message, index) => (external_react_default().createElement(AiMessage, { key: message.snowflakeId, context: context, message: message, index: index, onUpdated: onUpdated }))),
        activities.some((x) => x.id === 'code-generation') && external_react_default().createElement(AiChatLoader, null),
        activities.length === 0 && suggestions.length > 0 && (external_react_default().createElement(Box/* Box */.a, { hasYSpacing: 2, UNSAFE_style: { borderTop: '1px solid var(--theme-color-bg-1)' } }, suggestions.map((x) => (external_react_default().createElement(AiChatSuggestion, { key: x.id, text: x.text, onClick: () => {
                sendMessage(x.text);
            } })))))));
}
function AiMessage({ context, message, index, onUpdated }) {
    const isLast = context.chatHistory.messages.length - 1 === index;
    const isFunctionNode = context.template.nodeName === 'JavaScriptFunction';
    const showAffix = isLast && context.chatHistory.activities.length === 0 && isFunctionNode;
    const username = (0,external_react_.useMemo)(() => {
        var _a, _b;
        return ((_b = (_a = message.metadata) === null || _a === void 0 ? void 0 : _a.user) === null || _b === void 0 ? void 0 : _b.name) || LocalUserIdentity.getUserInfo().name;
    }, [message]);
    return (external_react_default().createElement(AiChatMessage, { key: message.snowflakeId, user: message.type === 'assistant'
            ? {
                role: 'assistant'
            }
            : {
                role: 'user',
                // TODO: Save the sender with the message
                name: username
            }, content: message.content, affix: showAffix && external_react_default().createElement(AiMessageFunctionNodeAffix, { context: context, onUpdated: onUpdated }) }));
}
function AiMessageFunctionNodeAffix({ context, onUpdated }) {
    const rootRef = (0,external_react_.useRef)(null);
    const editorRef = (0,external_react_.useRef)(null);
    (0,external_react_.useEffect)(() => {
        return () => {
            if (!editorRef.current)
                return;
            editorRef.current.model.dispose();
            editorRef.current = null;
        };
    }, []);
    function showEditor() {
        if (editorRef.current !== null) {
            editorRef.current.model.dispose();
            editorRef.current = null;
        }
        const model = createModel({
            // NOTE: Hardcoded for the Function node
            type: 'string',
            value: context.node.getParameter('functionScript'),
            codeeditor: 'javascript'
        }, context.node);
        function save() {
            const newValue = model.getValue();
            context.node.setParameter('functionScript', newValue);
            // Refresh Property Panel
            onUpdated && onUpdated();
        }
        const props = {
            nodeId: context.node.id,
            model: model,
            onSave: save
        };
        const popoutDiv = document.createElement('div');
        const root = (0,client.createRoot)(popoutDiv);
        root.render(external_react_default().createElement(CodeEditor_CodeEditor/* CodeEditor */.B, props));
        const popout = popuplayer_default().instance.showPopout({
            content: { el: [popoutDiv] },
            attachTo: $(rootRef.current),
            position: 'right',
            onClose: function () {
                save();
            }
        });
        editorRef.current = {
            model,
            popoutDiv,
            popout
        };
    }
    return (external_react_default().createElement("div", { ref: rootRef },
        external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, icon: common_Icon/* IconName */.$M.ImportSlanted, label: "Open code editor", testId: "ai-code-editor", isGrowing: true, onClick: (ev) => {
                ev.stopPropagation();
                showEditor();
            } })));
}

;// ./src/editor/src/views/panels/propertyeditor/components/AiChat/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/NodeLabel/NodeLabel.tsx












function NodeLabel({ model, showHelp = true }) {
    const labelInputRef = (0,external_react_.useRef)(null);
    const [isEditingLabel, setIsEditingLabel] = (0,external_react_.useState)(false);
    // Defensive: convert label to string (handles expression parameter objects)
    const [label, setLabel] = (0,external_react_.useState)(ParameterValueResolver/* ParameterValueResolver */.L.toString(model.label));
    // Listen for label changes on the model
    (0,external_react_.useEffect)(() => {
        model.on('labelChanged', () => {
            // Defensive: convert label to string (handles expression parameter objects)
            setLabel(ParameterValueResolver/* ParameterValueResolver */.L.toString(model.label));
        }, this);
        return function () {
            model.off(this);
        };
    }, []);
    function onOpenDocs() {
        if (!model.type.docs)
            return;
        // Update no version tag with version tag (and potentially switch to local docs)
        const docsUrl = model.type.docs.replace('https://docs.noodl.net', (0,editor_getDocsEndpoint/* default */.A)());
        tracker.tracker.track('Open Node Docs Clicked', { url: docsUrl });
        src.platform.openExternal(docsUrl);
    }
    function onEditLabel() {
        setIsEditingLabel(true);
        requestAnimationFrame(() => {
            labelInputRef.current.focus();
            labelInputRef.current.select();
        });
    }
    function onSaveLabel() {
        NodeGraphNodeRename(model, label);
        setIsEditingLabel(false);
        setLabel(model.label);
        // Unselect text
        window.getSelection().removeAllRanges();
    }
    useKeyboardCommands(() => [
        {
            handler: () => onOpenDocs(),
            keybinding: Keybindings.PROPERTY_PANEL_OPEN_DOCS.hash
        },
        {
            handler: () => {
                if (!isEditingLabel) {
                    onEditLabel();
                }
            },
            keybinding: Keybindings.PROPERTY_PANEL_EDIT_LABEL.hash
        }
    ]);
    return (external_react_default().createElement("div", { className: "property-editor-label-and-buttons property-header-bar", style: { flex: '0 0' } },
        external_react_default().createElement("div", { style: { flexGrow: 1, overflow: 'hidden' }, onDoubleClick: (e) => {
                // Stop propagation to prevent canvas double-click handler from triggering
                e.stopPropagation();
                if (!isEditingLabel) {
                    onEditLabel();
                }
            } },
            external_react_default().createElement(TextInput, { onRefChange: (ref) => (labelInputRef.current = ref.current), value: label, isDisabled: !isEditingLabel, UNSAFE_textStyle: { color: 'var(--theme-color-fg-highlight)' }, variant: TextInputVariant.Transparent, onChange: (e) => setLabel(e.target.value), onBlur: () => onSaveLabel(), onEnter: () => onSaveLabel() })),
        !isEditingLabel && (external_react_default().createElement("div", { className: "sidebar-panel-edit-bar hide-on-edit property-panel-header-edit-bar" },
            showHelp && Boolean(model.type.docs) && (external_react_default().createElement("div", { style: { width: '35px', height: '35px', display: 'flex', justifyContent: 'center', alignItems: 'center' } },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Open Node Docs", fineType: Keybindings.PROPERTY_PANEL_OPEN_DOCS.label },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Question, size: common_Icon/* IconSize */.lK.Tiny, variant: inputs_IconButton/* IconButtonVariant */.nl.OpaqueOnHover, onClick: () => onOpenDocs() })))),
            external_react_default().createElement("div", { style: { width: '35px', height: '35px', display: 'flex', justifyContent: 'center', alignItems: 'center' } },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Edit the node label", fineType: Keybindings.PROPERTY_PANEL_EDIT_LABEL.label },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Pencil, size: common_Icon/* IconSize */.lK.Tiny, variant: inputs_IconButton/* IconButtonVariant */.nl.OpaqueOnHover, onClick: () => onEditLabel() }))),
            external_react_default().createElement("div", { style: { width: '35px', height: '35px', display: 'flex', justifyContent: 'center', alignItems: 'center' } },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "Delete the node", fineType: Keybindings.PROPERTY_PANEL_DELETE.label },
                    external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Trash, size: common_Icon/* IconSize */.lK.Tiny, variant: inputs_IconButton/* IconButtonVariant */.nl.OpaqueOnHover, onClick: () => {
                            NodeGraphNodeDelete(model);
                        } })))))));
}

;// ./src/editor/src/views/panels/propertyeditor/components/NodeLabel/index.ts


;// ./src/editor/src/views/panels/propertyeditor/components/VariantStates/PickVariantItem.tsx

class PickVariantItem extends (external_react_default()).Component {
    constructor(props) {
        super(props);
        this.state = {
            editMode: false,
            newVariantName: props.variant.name
        };
    }
    onRenameVariantClicked(e) {
        this.setState({
            editMode: true
        });
        e.stopPropagation();
    }
    onRenameVariant(e) {
        if (e.key === 'Enter') {
            this.props.onRenameVariant(this.state.newVariantName);
            this.setState({
                editMode: false
            });
        }
    }
    render() {
        if (this.state.editMode) {
            return (external_react_default().createElement("div", { className: "variants-pick-variant-item" },
                external_react_default().createElement("input", { className: "variants-input", value: this.state.newVariantName, autoFocus: true, onChange: (e) => this.setState({ newVariantName: e.target.value }), onKeyUp: (e) => this.onRenameVariant(e) })));
        }
        return (external_react_default().createElement("div", { className: "variants-pick-variant-item", onClick: (e) => {
                this.props.onPickVariant();
                e.stopPropagation();
            } },
            external_react_default().createElement("div", { className: "variant-item-name" }, this.props.variant.name),
            external_react_default().createElement("div", { className: "variants-item-icon", onClick: (e) => {
                    this.onRenameVariantClicked(e);
                    e.stopPropagation();
                } },
                external_react_default().createElement("i", { className: "fa fa-edit" })),
            external_react_default().createElement("div", { className: "variants-item-icon", onClick: (e) => {
                    this.props.onDeleteVariant();
                    e.stopPropagation();
                } },
                external_react_default().createElement("i", { className: "fa fa-trash" }))));
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/VariantStates/PickVariantPopup.tsx




class PickVariantPopup extends (external_react_default()).Component {
    constructor(props) {
        super(props);
        this.model = props.model;
        this.state = {
            variants: projectmodel.ProjectModel.instance.findVariantsForNodeType(this.model.type),
            showCreateNewVariant: props.showCreateNewVariant
        };
    }
    componentDidMount() {
        projectmodel.ProjectModel.instance.on(['variantDeleted', 'variantCreated', 'variantRenamed'], () => {
            this.setState({
                variants: projectmodel.ProjectModel.instance.findVariantsForNodeType(this.model.type)
            });
        }, this);
    }
    componentWillUnmount() {
        projectmodel.ProjectModel.instance.off(this);
    }
    onPickVariant(variant) {
        this.model.setVariant(variant, { undo: true });
        this.props.hidePopout();
    }
    onDeleteVariant(variant) {
        if (projectmodel.ProjectModel.instance.isVariantUsed(variant)) {
            ToastLayer.ToastLayer.showError('Cannot delete variant that is in use');
            return;
        }
        projectmodel.ProjectModel.instance.deleteVariant(variant, { undo: true });
    }
    onRenameVariant(variant, name) {
        if (name === undefined || name.length === 0) {
            ToastLayer.ToastLayer.showError('Must provide name for variant');
            return;
        }
        if (projectmodel.ProjectModel.instance.findVariant(name, this.model.type)) {
            // Variant with name already exists for this node
            ToastLayer.ToastLayer.showError('Variant with the name already exists');
            return;
        }
        projectmodel.ProjectModel.instance.renameVariant(variant, name, { undo: true });
        ToastLayer.ToastLayer.showSuccess('Variant renamed');
    }
    performAddVariant(name) {
        if (name === undefined || name.length === 0) {
            ToastLayer.ToastLayer.showError('Must provide name for variant');
            return;
        }
        if (projectmodel.ProjectModel.instance.findVariant(name, this.model.type)) {
            // Variant with name already exists for this node
            ToastLayer.ToastLayer.showError('Variant with the name already exists');
            return;
        }
        this.model.createNewVariant(name, { undo: true });
        ToastLayer.ToastLayer.showSuccess('Variant created');
        this.props.hidePopout();
    }
    onKeyUp(e) {
        if (e.key === 'Enter') {
            this.performAddVariant(e.target.value);
        }
    }
    onCreateNewVariantClicked() {
        this.setState({
            showCreateNewVariant: true
        });
    }
    renderVariants() {
        return this.state.variants.map((v) => (external_react_default().createElement(PickVariantItem, { key: v.typename + v.name, variant: v, onRenameVariant: this.onRenameVariant.bind(this, v), onDeleteVariant: this.onDeleteVariant.bind(this, v), onPickVariant: this.onPickVariant.bind(this, v) })));
    }
    render() {
        let header;
        if (this.state.showCreateNewVariant) {
            //note about autoFocus on the input. It doesn't work, probably because this component is mounted on a non-react component, so maybe it creates
            //the input before the component is mounted to the DOM. A ref callback with a short timeout solves it.
            header = (external_react_default().createElement("div", { style: { display: 'flex', flexDirection: 'column', width: '100%', position: 'relative' } },
                external_react_default().createElement("div", { className: "variants-header" },
                    external_react_default().createElement("span", null, "New variant name")),
                external_react_default().createElement("div", { className: "variants-input-container" },
                    external_react_default().createElement("input", { className: "variants-input", ref: (ref) => { if (ref)
                            setTimeout(() => ref.focus(), 10); }, autoFocus: true, onKeyUp: this.onKeyUp.bind(this), onChange: (e) => (this.newVariantName = e.target.value) }),
                    external_react_default().createElement("button", { className: "variants-button primary", onClick: (e) => this.performAddVariant(this.newVariantName) }, "Create"))));
        }
        else {
            header = (external_react_default().createElement("div", { onClick: this.onCreateNewVariantClicked.bind(this), className: "variants-header variants-add-header" },
                external_react_default().createElement("div", null, "Create new variant"),
                external_react_default().createElement("i", { className: "fa fa-plus" })));
        }
        const hasVariant = this.model.variant && this.model.variant.name !== undefined;
        return (external_react_default().createElement("div", { style: { width: '230px', display: 'flex', flexDirection: 'column' } },
            header,
            hasVariant ? (external_react_default().createElement("div", { className: "variants-pick-variant-item", onClick: (e) => {
                    const v = projectmodel.ProjectModel.instance.findVariant(undefined, this.model.type);
                    this.onPickVariant(v);
                    e.stopPropagation();
                } },
                external_react_default().createElement("div", { className: "variants-add-icon", style: { marginLeft: '10px', opacity: 1 } },
                    external_react_default().createElement("i", { className: "fa fa-close" })),
                external_react_default().createElement("div", { className: "variant-item-name", style: { paddingLeft: '0px' } }, "Remove variant from node"))) : null,
            external_react_default().createElement("div", { style: { overflowY: 'auto' } }, this.renderVariants())));
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/VariantStates/variantseditor.tsx






// Styles
__webpack_require__(46055);
class VariantsEditor extends (external_react_default()).Component {
    constructor(props) {
        super(props);
        this.popupRoot = null;
        this.model = props.model;
        this.state = {
            variant: this.model.variant
            //   canUpdateVariant:_hasParameterChanges(this.model)
        };
    }
    componentDidMount() {
        /*   this.model.on(['variantUpdated','variantChanged','parametersChanged','stateTransitionsChanged','defaultStateTransitionChanged'],() => {
                this.setState({
                    variant:this.model.variant,
                    canUpdateVariant:_hasParameterChanges(this.model)
                })
            },this)*/
        this.model.on(['variantChanged'], () => {
            this.setState({
                variant: this.model.variant
            });
        }, this);
        projectmodel.ProjectModel.instance.on(['variantRenamed'], (args) => {
            if (args.variant === this.model.variant)
                this.setState({
                    variant: this.model.variant
                });
        }, this);
    }
    componentWillUnmount() {
        this.model.off(this);
        projectmodel.ProjectModel.instance.off(this);
        if (this.popout) {
            popuplayer_default().instance.hidePopout(this.popout);
        }
    }
    render() {
        let content;
        if (this.state.variant === undefined || this.state.variant.name === undefined) {
            //No variant
            content = (external_react_default().createElement("div", { className: "variants-section" },
                external_react_default().createElement("div", { className: "variants-name-section", onClick: this.onPickVariant.bind(this) },
                    external_react_default().createElement("label", null, "Add style variant"),
                    external_react_default().createElement("div", { className: "variants-add-icon" },
                        external_react_default().createElement("i", { className: "fa fa-plus", style: { color: 'white' } })))));
        }
        else if (this.state.variant !== undefined && this.state.variant.name !== undefined && !this.state.editMode) {
            //Variant
            content = (external_react_default().createElement("div", { className: "variants-section" },
                external_react_default().createElement("div", { className: "variants-name-section", onClick: this.onPickVariant.bind(this) },
                    external_react_default().createElement("label", null, this.state.variant.name),
                    external_react_default().createElement("div", { className: "variants-pick-icon" })),
                external_react_default().createElement("button", { className: "variants-button", style: { marginLeft: '10px', width: '78px' }, onClick: this.onEditVariant.bind(this) }, "Edit variant")));
        }
        else if (this.state.variant !== undefined && this.state.variant.name !== undefined && this.state.editMode) {
            //Edit variant
            content = (external_react_default().createElement("div", { style: { width: '100%' } },
                external_react_default().createElement("div", { className: "variants-edit-mode-header" }, "Edit variant"),
                external_react_default().createElement("div", { className: "variants-section" },
                    external_react_default().createElement("label", null, this.state.variant.name),
                    external_react_default().createElement("button", { className: "variants-button teal", style: { marginLeft: 'auto', width: '78px' }, onClick: this.onDoneEditingVariant.bind(this) }, "Close"))));
        }
        return (external_react_default().createElement("div", { className: "variants-editor", ref: (el) => { this.popupAnchor = el; } }, content));
    }
    performAddVariant(name) {
        if (projectmodel.ProjectModel.instance.findVariant(name, this.model.type)) {
            // Variant with name already exists for this node
            ToastLayer.ToastLayer.showError('Variant with the name already exists');
            return;
        }
        this.model.createNewVariant(name, { undo: true });
        ToastLayer.ToastLayer.showSuccess('Variant created');
    }
    onUpdateVariant(evt) {
        this.model.updateVariant({ undo: true });
        ToastLayer.ToastLayer.showSuccess('Variant updated');
        evt.stopPropagation();
    }
    onEditVariant(evt) {
        this.props.onEditVariant && this.props.onEditVariant();
        this.setState({
            editMode: true
        });
        evt.stopPropagation();
    }
    onDoneEditingVariant(evt) {
        this.props.onDoneEditingVariant && this.props.onDoneEditingVariant();
        this.setState({
            editMode: false
        });
        evt.stopPropagation();
    }
    onPickVariant(evt) {
        const div = document.createElement('div');
        const variants = projectmodel.ProjectModel.instance.findVariantsForNodeType(this.model.type);
        const props = {
            showCreateNewVariant: variants.length === 0 || (variants.length === 1 && variants[0].name === undefined),
            model: this.model,
            hidePopout: () => {
                popuplayer_default().instance.hidePopout(this.popout);
            }
        };
        this.popupRoot = (0,client.createRoot)(div);
        this.popupRoot.render(external_react_default().createElement(PickVariantPopup, props));
        this.popout = popuplayer_default().instance.showPopout({
            content: { el: $(div) },
            attachTo: $(this.popupAnchor),
            position: 'right',
            onClose: () => {
                if (this.popupRoot) {
                    this.popupRoot.unmount();
                    this.popupRoot = null;
                }
                this.popout = undefined;
            }
        });
        evt.stopPropagation();
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/VariantStates/index.ts


// EXTERNAL MODULE: ./src/editor/src/views/panels/propertyeditor/DataTypes/CurveEditor/curveeditor.jsx
var curveeditor = __webpack_require__(3191);
var curveeditor_default = /*#__PURE__*/__webpack_require__.n(curveeditor);
;// ./src/editor/src/views/panels/propertyeditor/DataTypes/CurveEditor/index.ts




;// ./src/editor/src/views/panels/propertyeditor/components/VisualStates/DefaultVisualStateTransition.tsx

class DefaultVisualStateTransition extends (external_react_default()).Component {
    constructor(props) {
        super(props);
    }
    onResetClicked() {
        this.props.model.setDefaultStateTransition(undefined, { undo: true, label: 'default transition reset' });
    }
    onToggleEnabled() {
        const transition = this.props.model.getDefaultStateTransition();
        const hasTransition = transition !== undefined && transition.curve !== undefined;
        if (hasTransition) {
            // Force disable a transition
            this.props.model.setDefaultStateTransition({}, { undo: true, label: 'disable default transition' });
        }
        else {
            // Force enable a transition
            this.props.model.setDefaultStateTransition({ curve: [0.0, 0.0, 0.58, 1.0], dur: 300, delay: 0 }, { undo: true, label: 'enable default transition' });
        }
    }
    render() {
        const isDefault = !this.props.model.hasDefaultStateTransition();
        const transition = this.props.model.getDefaultStateTransition();
        const hasTransition = transition !== undefined && transition.curve !== undefined;
        return (external_react_default().createElement("div", { className: 'visual-state-default-transition' + (isDefault ? ' default' : '') + (this.props.selected ? ' selected' : ''), style: { display: 'flex', alignItems: 'center' }, onClick: (e) => this.props.onClick && this.props.onClick() },
            external_react_default().createElement("div", { className: "label" },
                external_react_default().createElement("span", { style: { flexGrow: 1 } }, "All properties"),
                external_react_default().createElement("div", { className: 'visual-state-transition-curve-button' + (hasTransition ? ' enabled' : ''), onClick: this.onToggleEnabled.bind(this) }, hasTransition ? 'Disable' : 'Enable')),
            external_react_default().createElement("span", { className: "visual-state-transition-changed-dot", style: { visibility: !isDefault ? 'visible' : 'hidden' }, onClick: this.onResetClicked.bind(this) })));
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/VisualStates/VisualStateTransition.tsx

class VisualStateTransition extends (external_react_default()).Component {
    constructor(props) {
        super(props);
    }
    onResetClicked() {
        // Reset to default
        this.props.model.setStateTransition(this.props.transition.name, undefined, {
            undo: true,
            label: 'reset state transition'
        });
    }
    onToggleEnabled() {
        const _transition = this.props.model.getStateTransition(this.props.transition.name);
        const hasTransition = _transition !== undefined && _transition.curve !== undefined;
        if (hasTransition) {
            // Force disable a transition
            this.props.model.setStateTransition(this.props.transition.name, {}, { undo: true, label: 'disable state transition' });
        }
        else {
            // Force enable a transition
            this.props.model.setStateTransition(this.props.transition.name, { curve: [0.0, 0.0, 0.58, 1.0], dur: 300, delay: 0 }, { undo: true, label: 'enable state transition' });
        }
    }
    render() {
        const isDefault = !this.props.model.hasStateTransition(this.props.transition.name);
        const _transition = this.props.model.getStateTransition(this.props.transition.name);
        const hasTransition = _transition !== undefined && _transition.curve !== undefined;
        return (external_react_default().createElement("div", { className: 'visual-state-default-transition' + (isDefault ? ' default' : '') + (this.props.selected ? ' selected' : ''), style: { display: 'flex', alignItems: 'center' }, onClick: (e) => this.props.onClick && this.props.onClick() },
            external_react_default().createElement("div", { className: "label" },
                external_react_default().createElement("span", { style: { marginRight: '10px', flexGrow: 1 } }, this.props.transition.displayName),
                external_react_default().createElement("div", { className: 'visual-state-transition-curve-button' + (hasTransition ? ' enabled' : ''), onClick: this.onToggleEnabled.bind(this) }, hasTransition ? 'Disable' : 'Enable')),
            external_react_default().createElement("span", { className: "visual-state-transition-changed-dot", style: { visibility: !isDefault ? 'visible' : 'hidden' }, onClick: this.onResetClicked.bind(this) })));
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/VisualStates/TransitionEditor.tsx




class TransitionEditor extends (external_react_default()).Component {
    constructor(props) {
        super(props);
        this.state = {
            transitions: props.model.getPossibleTransitionsForState(props.visualState.name)
        };
    }
    componentDidMount() {
        this.props.model.on(['stateTransitionChanged', 'defaultStateTransitionChanged'], () => {
            let curve;
            if (this.state.editingTransition === undefined) {
                curve = this.props.model.getDefaultStateTransition();
            }
            this.setState({
                curve: curve,
                defaultCurve: curve || { curve: [0.0, 0.0, 0.58, 1.0], dur: 300, delay: 0 },
                transitions: this.props.model.getPossibleTransitionsForState(this.props.visualState.name)
            });
        }, this);
        if (this.props.visualState.name === 'neutral') {
            this.onDefaultStateTransitionClicked(); // Select default transition
        }
        else {
            this.onStateTransitionClicked(this.state.transitions[0]); // Select first transition
        }
    }
    componentWillUnmount() {
        this.props.model.off(this);
    }
    onDefaultStateTransitionClicked() {
        const transition = this.props.model.getDefaultStateTransition();
        this.setState({
            showCurveEditor: transition !== undefined && transition.curve !== undefined,
            curve: transition,
            defaultCurve: transition || { curve: [0.0, 0.0, 0.58, 1.0], dur: 300, delay: 0 },
            selectedTransition: undefined
        });
    }
    onStateTransitionClicked(transition) {
        const _transition = this.props.model.getStateTransition(transition.name);
        this.setState({
            showCurveEditor: _transition !== undefined && _transition.curve !== undefined,
            curve: _transition,
            defaultCurve: _transition || { curve: [0.0, 0.0, 0.58, 1.0], dur: 300, delay: 0 },
            selectedTransition: transition
        });
    }
    onCurveUpdated(curve, drag) {
        if (this.state.selectedTransition === undefined) {
            const undoArgs = { undo: true, label: 'default transition changed' };
            this.props.model.setDefaultStateTransition(curve, drag ? undefined : undoArgs);
        }
        else {
            const undoArgs = { undo: true, label: 'default transition changed' };
            this.props.model.setStateTransition(this.state.selectedTransition.name, curve, drag ? undefined : undoArgs);
        }
    }
    renderTransitionProperties() {
        // Sort into groups
        const groups = {};
        this.state.transitions.forEach((t) => {
            if (!groups[t.group])
                groups[t.group] = [];
            groups[t.group].push(t);
        });
        return (external_react_default().createElement("div", { style: { padding: '8px' } },
            external_react_default().createElement(DefaultVisualStateTransition, { model: this.props.model, selected: this.state.selectedTransition === undefined && this.state.showCurveEditor, onClick: this.onDefaultStateTransitionClicked.bind(this) }),
            Object.keys(groups)
                .sort()
                .map((group) => (
            // eslint-disable-next-line react/jsx-key
            external_react_default().createElement("div", null,
                external_react_default().createElement("div", { className: "visual-states-group-header" }, group),
                groups[group].map((transition) => (
                // eslint-disable-next-line react/jsx-key
                external_react_default().createElement(VisualStateTransition, { model: this.props.model, selected: this.state.selectedTransition === transition && this.state.showCurveEditor, transition: transition, onClick: this.onStateTransitionClicked.bind(this, transition) }))))))));
    }
    render() {
        return (external_react_default().createElement("div", { className: "visual-states-transition-popup" },
            external_react_default().createElement("div", { className: "visual-states-transitions-header" },
                "Transitions to ",
                this.props.visualState.label),
            external_react_default().createElement("div", { style: { display: 'flex' } },
                external_react_default().createElement("div", { style: { width: '330px', height: '100%', position: 'relative' } }, this.renderTransitionProperties()),
                this.state.showCurveEditor ? (external_react_default().createElement("div", { style: { width: '270px', height: '100%', position: 'relative' } },
                    external_react_default().createElement((curveeditor_default()), { value: this.state.curve, default: this.state.defaultCurve, onUpdate: this.onCurveUpdated.bind(this) }))) : null)));
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/VisualStates/visualstates.tsx



// Styles
__webpack_require__(88612);
class VisualStates extends (external_react_default()).Component {
    constructor(props) {
        super(props);
        this.popupRoot = null;
        const states = props.model.getVisualStates();
        this.state = {
            visualStates: states,
            selectedVisualState: states[0],
            visualStateTransitions: props.model.getPossibleTransitionsForState(states[0].name)
        };
        props.model.on(['parametersChanged'], () => {
            this.setState({
                visualStateTransitions: props.model.getPossibleTransitionsForState(this.state.selectedVisualState.name)
            });
        });
    }
    onVisualStateClicked(state) {
        this.props.onVisualStateChanged(state);
        this.setState({
            selectedVisualState: state,
            visualStateTransitions: this.props.model.getPossibleTransitionsForState(state.name)
        });
    }
    onToggleTransitionsClicked() {
        this.setState({
            showTransitions: !this.state.showTransitions
        });
    }
    renderVisualStates() {
        return this.state.visualStates.map((state) => (
        // eslint-disable-next-line react/jsx-key
        external_react_default().createElement("div", { className: "property-editor-visual-state-item", onClick: this.onVisualStateClicked.bind(this, state) },
            external_react_default().createElement("div", { className: 'property-editor-visual-state-item-label ' + (this.state.selectedVisualState === state ? 'selected' : '') }, state.label))));
    }
    onCurrentStateClicked() {
        this.setState({
            showStatesSelector: !this.state.showStatesSelector
        });
    }
    onTransitionsClicked(evt) {
        const div = document.createElement('div');
        const props = {
            model: this.props.model,
            visualState: this.state.selectedVisualState
        };
        this.popupRoot = (0,client.createRoot)(div);
        this.popupRoot.render(external_react_default().createElement(TransitionEditor, props));
        this.props.portsView.showPopout({
            arrowColor: '#444444',
            content: { el: $(div) },
            attachTo: $(this.popupAnchor),
            position: 'right',
            onClose: () => {
                if (this.popupRoot) {
                    this.popupRoot.unmount();
                    this.popupRoot = null;
                }
            }
        });
        evt.stopPropagation();
    }
    render() {
        return (external_react_default().createElement("div", { className: "variants-section property-editor-visual-states", style: { position: 'relative', display: 'flex', alignItems: 'center' }, ref: (el) => { this.popupAnchor = el; } },
            external_react_default().createElement("div", { className: "variants-name-section", onClick: this.onCurrentStateClicked.bind(this) },
                external_react_default().createElement("label", null,
                    this.state.selectedVisualState.label,
                    " state"),
                external_react_default().createElement("div", { className: "variants-pick-icon" }),
                this.state.showStatesSelector ? (external_react_default().createElement("div", { className: "visual-states-popup", style: { position: 'absolute', zIndex: '10', top: '20px', right: '70px' } }, this.renderVisualStates())) : null),
            this.state.visualStateTransitions.length > 0 ? (external_react_default().createElement("div", { className: "variants-button", onClick: this.onTransitionsClicked.bind(this) }, "Transitions")) : null));
    }
}

;// ./src/editor/src/views/panels/propertyeditor/components/VisualStates/index.ts


;// ./src/editor/src/views/panels/propertyeditor/models/modelProxy.ts


/**
 * The model proxy is used to simulate different models for different interaction states / default values etc
 */
class ModelProxy {
    get parameters() {
        return new Proxy(this.model.parameters, {
            get: (_target, prop) => {
                const source = this.editMode === 'variant' ? this.model.variant : this.model;
                if (this.visualState === undefined || this.visualState === 'neutral')
                    return source.parameters[prop];
                else
                    return source.stateParameters !== undefined && source.stateParameters[this.visualState] !== undefined
                        ? source.stateParameters[this.visualState][prop]
                        : undefined;
            }
        });
    }
    get type() {
        return this.model.type;
    }
    get variantName() {
        return this.model.variantName;
    }
    constructor(args) {
        this.model = args.model;
        this.visualState = 'neutral';
    }
    setVisualState(state) {
        this.visualState = state;
    }
    setEditMode(mode) {
        this.editMode = mode;
    }
    getParameter(name) {
        const source = this.editMode === 'variant' ? this.model.variant : this.model;
        return source.getParameter(name, { state: this.visualState });
    }
    setParameter(name, value, args = {}) {
        const _oldPorts = this.getPorts();
        // @ts-expect-error
        args.state = this.visualState;
        const target = this.editMode === 'variant' ? this.model.variant : this.model;
        // Set the parameter for the specific interaction state
        target.setParameter(name, value, args);
        // Check if the ports have changed for this specific interaction state
        if (!(0,external_underscore_.isEqual)(_oldPorts, this.getPorts()))
            this.model.notifyListeners('instancePortsChanged');
    }
    isPortConnected(name) {
        if ((this.editMode !== 'variant' && this.visualState === undefined) || this.visualState === 'neutral') {
            return this.model.isPortConnected(name);
        }
        else
            return false;
    }
    on(event, handler, group) {
        return this.model.on(event, handler, group);
    }
    off(group) {
        return this.model.off(group);
    }
    getPorts(filter) {
        const source = this.editMode === 'variant' ? this.model.variant : this.model;
        let ports = [].concat(source.getPorts(filter));
        // Apply ports condition filter
        const portFilter = nodelibrary/* NodeLibrary */.m.instance.applyPortConditionsFilterForNode(this);
        portFilter.forEach((portname) => {
            const idx = ports.findIndex((p) => p.name === portname);
            if (idx !== -1)
                ports.splice(idx, 1);
        });
        // Apply filter for allowVisualStates
        if (this.visualState !== undefined && this.visualState !== 'neutral') {
            ports = ports.filter((p) => !!p.allowVisualStates);
        }
        return ports;
    }
    getVisualStates() {
        return this.model.type.visualStates;
    }
    getPossibleTransitionsForState(state) {
        const source = this.editMode === 'variant' ? this.model.variant : this.model;
        return source.getPossibleTransitionsForState(state);
    }
    getStateTransition(property) {
        const source = this.editMode === 'variant' ? this.model.variant : this.model;
        return source.getStateTransition(this.visualState, property);
    }
    setStateTransition(property, curve, args) {
        const target = this.editMode === 'variant' ? this.model.variant : this.model;
        target.setStateTransition(this.visualState, property, curve, args);
    }
    getDefaultStateTransition() {
        const source = this.editMode === 'variant' ? this.model.variant : this.model;
        return source.getDefaultStateTransition(this.visualState);
    }
    setDefaultStateTransition(curve, args) {
        const target = this.editMode === 'variant' ? this.model.variant : this.model;
        target.setDefaultStateTransition(this.visualState, curve, args);
    }
    hasDefaultStateTransition() {
        const source = this.editMode === 'variant' ? this.model.variant : this.model;
        return (source.defaultStateTransitions !== undefined && source.defaultStateTransitions[this.visualState] !== undefined);
    }
    hasStateTransition(parameterName) {
        const source = this.editMode === 'variant' ? this.model.variant : this.model;
        return (source.stateTransitions !== undefined &&
            source.stateTransitions[this.visualState] !== undefined &&
            source.stateTransitions[this.visualState][parameterName] !== undefined);
    }
}

;// ./src/editor/src/views/panels/propertyeditor/propertyeditor.ts











// eslint-disable-next-line @typescript-eslint/no-var-requires
const PropertyEditorTemplate = __webpack_require__(37762);
// Styles
__webpack_require__(41554);
class PropertyEditor extends (view_default()) {
    constructor(args) {
        super();
        this.variantsRoot = null;
        this.visualStatesRoot = null;
        this.parent = args.parent;
        this.model = args.model;
        this.modelProxy = new ModelProxy({ model: this.model });
        //this.isRoot = ProjectModel.instance.getRootNode() === this.model;
        this.allowAsRoot = this.model.type.allowAsExportRoot;
    }
    dispose() {
        this.portsView.dispose();
    }
    scheduleRenderPortsView() {
        if (this.renderPortsViewScheduled)
            return;
        const _this = this;
        this.renderPortsViewScheduled = true;
        setTimeout(function () {
            _this.renderPortsViewScheduled = false;
            _this.renderPortsView();
        }, 0);
    }
    renderPortsView() {
        this.portsView.render();
        this.$('.groups').html(this.portsView.el);
    }
    renderVariantsEditor() {
        if (this.model.type.useVariants) {
            const props = {
                model: this.model,
                onEditVariant: () => {
                    // Hide top panel when editing variant
                    this.$('.property-editor-label-and-buttons').hide();
                    this.modelProxy.setEditMode('variant');
                    this.scheduleRenderPortsView();
                    this.$('.sidebar-property-editor').addClass('variants-sidepanel-edit-mode');
                },
                onDoneEditingVariant: () => {
                    this.$('.property-editor-label-and-buttons').show();
                    this.modelProxy.setEditMode('node');
                    this.scheduleRenderPortsView();
                    this.$('.sidebar-property-editor').removeClass('variants-sidepanel-edit-mode');
                }
            };
            const container = this.$('.variants')[0];
            if (!this.variantsRoot) {
                this.variantsRoot = (0,client.createRoot)(container);
            }
            this.variantsRoot.render(external_react_default().createElement(VariantsEditor, props));
        }
    }
    renderVisualStates() {
        if (this.model.type.visualStates !== undefined) {
            const props = {
                model: this.modelProxy,
                onVisualStateChanged: this.onVisualStateChanged.bind(this),
                portsView: this.portsView
            };
            const container = this.$('.visual-states')[0];
            if (!this.visualStatesRoot) {
                this.visualStatesRoot = (0,client.createRoot)(container);
            }
            this.visualStatesRoot.render(external_react_default().createElement(VisualStates, props));
        }
    }
    onVisualStateChanged(state) {
        this.modelProxy.setVisualState(state.name);
        // Interaction state changed, schedule
        this.scheduleRenderPortsView();
    }
    render() {
        this.el = this.bindView($(PropertyEditorTemplate), this);
        this.portsView = new Ports({
            model: this.modelProxy
        });
        this.renderPortsView();
        this.renderVariantsEditor();
        this.renderVisualStates();
        this.parent && this.parent.append(this.el);
        return this.el;
    }
    performDelete() {
        if (!this.model.canBeDeleted()) {
            ToastLayer.ToastLayer.showError('This node cannot be deleted');
            return;
        }
        const graph = this.model.owner;
        const undo = new undo_queue_model/* UndoActionGroup */.C({ label: 'delete node' });
        graph.removeNode(this.model, { undo: undo });
        undo_queue_model/* UndoQueue */.g.instance.push(undo);
    }
    _tryPropertyPanelInputInteraction(inputIdentifier) {
        const input = document.querySelector(`div[data-panel-id="PropertyEditor"] [data-identifier="${inputIdentifier}"]`);
        if (input) {
            setTimeout(() => {
                switch (input === null || input === void 0 ? void 0 : input.nodeName) {
                    case 'BUTTON': {
                        input.click();
                        // if the button click opens a code editor we want to focus that
                        const codeEditor = document.querySelector('.monaco-editor .inputarea') || undefined;
                        if (codeEditor) {
                            codeEditor.focus();
                        }
                        break;
                    }
                    case 'INPUT': {
                        if (input.dataset.type === 'color') {
                            input.click();
                        }
                        else {
                            input.focus();
                        }
                        break;
                    }
                    default: {
                        input.focus();
                    }
                }
                input.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }, 1);
        }
    }
    doubleClick(node) {
        var _a;
        if ((_a = node.metadata) === null || _a === void 0 ? void 0 : _a.AiAssistant) {
            const aiButton = document.querySelector('button[data-test="ai-code-editor"]');
            if (aiButton) {
                setTimeout(() => {
                    aiButton.click();
                    $('.monaco-editor .inputarea')[0].focus();
                }, 1);
            }
        }
        else if (node.type.name === 'CloudFunction2') {
            const functionName = '/#__cloud__/' + node.parameters.function;
            const component = projectmodel.ProjectModel.instance.getComponentWithName(functionName);
            if (component) {
                NodeGraphContext.NodeGraphContextTmp.switchToComponent(component, { pushHistory: true });
            }
            else {
                ToastLayer.ToastLayer.showError('Could not find Cloud Function in project.');
            }
        }
        else if (node.type.nodeDoubleClickAction) {
            if (Array.isArray(node.type.nodeDoubleClickAction)) {
                node.type.nodeDoubleClickAction.forEach((action) => {
                    this._tryPropertyPanelInputInteraction(action.focusPort);
                });
            }
            else {
                this._tryPropertyPanelInputInteraction(node.type.nodeDoubleClickAction.focusPort);
            }
        }
    }
}

;// ./src/editor/src/views/panels/propertyeditor/index.tsx











function NodeGraphNodeRename(model, newname) {
    model.setLabel(newname, { undo: true, label: 'change label' });
}
function NodeGraphNodeDelete(model) {
    if (!model.canBeDeleted()) {
        ToastLayer.ToastLayer.showError('This node cannot be deleted');
        return;
    }
    const graph = model.owner;
    const undo = new undo_queue_model/* UndoActionGroup */.C({ label: 'delete node' });
    graph.removeNode(model, { undo: undo });
    undo_queue_model/* UndoQueue */.g.instance.push(undo);
}
function propertyeditor_PropertyEditor(props) {
    var _a, _b;
    const [group] = (0,external_react_.useState)({});
    const [instance, setInstance] = (0,external_react_.useState)(null);
    (0,external_react_.useEffect)(() => {
        const instance = new PropertyEditor(props);
        instance.render();
        setInstance(instance);
        models_sidebar/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.receivedCommand, (panelId, command, args) => {
            var _a, _b, _c;
            if (panelId !== 'PropertyEditor')
                return;
            // Disable double click for AI Nodes
            // For now lets allow Function nodes (JavaScriptFunction)
            const aiAssistant = (_b = (_a = props.model) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.AiAssistant;
            if (aiAssistant && ((_c = props.model) === null || _c === void 0 ? void 0 : _c.typename) !== 'JavaScriptFunction')
                return;
            switch (command) {
                case 'doubleClick': {
                    instance.doubleClick(args.model);
                    break;
                }
            }
        }, group);
        return function () {
            models_sidebar/* SidebarModel */.s.instance.off(group);
        };
    }, [props.model]); // FIX: Update when model changes!
    const aiAssistant = (_b = (_a = props.model) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.AiAssistant;
    if (aiAssistant) {
        return external_react_default().createElement(AiPropertyEditor, { ...props, instance: instance });
    }
    return (external_react_default().createElement("div", { style: { position: 'relative', height: '100%', width: '100%', display: 'flex', flexDirection: 'column' } },
        Boolean(props.model) && external_react_default().createElement(NodeLabel, { ...props }),
        external_react_default().createElement(ScrollArea, null,
            external_react_default().createElement(Frame, { instance: instance, isContentSize: true, UNSAFE_style: { flex: 1 } }))));
}
function AiPropertyEditor(props) {
    return (external_react_default().createElement("div", { style: { position: 'relative', height: '100%', width: '100%', display: 'flex', flexDirection: 'column' } },
        external_react_default().createElement(NodeLabel, { ...props, showHelp: false }),
        external_react_default().createElement(Tabs/* Tabs */.t, { variant: Tabs/* TabsVariant */._.Sidebar, tabs: [
                {
                    label: 'AI Chat',
                    content: (external_react_default().createElement(AiChat, { model: props.model, onUpdated: () => {
                            // Update the property panel values
                            props.instance.render();
                        } }))
                },
                {
                    label: 'Properties',
                    content: (external_react_default().createElement(ScrollArea, null,
                        external_react_default().createElement(Frame, { instance: props.instance, isContentSize: true, UNSAFE_style: { flex: 1 } })))
                }
            ] })));
}

;// ./src/editor/src/hooks/useDebounceState.ts

function useDebounceState(value, delay) {
    const [debouncedValue, setDebouncedValue] = (0,external_react_.useState)(value);
    (0,external_react_.useEffect)(() => {
        const handler = setTimeout(() => {
            setDebouncedValue(value);
        }, delay);
        return () => {
            clearTimeout(handler);
        };
    }, [value, delay]);
    return debouncedValue;
}

;// ./src/editor/src/utils/universal-search.js
const { ProjectModel } = __webpack_require__(6203);

function matchStrings(string1, string2) {
  return string1.toLowerCase().indexOf(string2.toLowerCase()) !== -1;
}

function searchInNodeRecursive(node, searchTerms, component) {
  var results = [];
  var matchLabel = null;
  var i = 0;

  if (node._label !== undefined && matchStrings(node._label, searchTerms)) {
    matchLabel = node.label;
  } else if (matchStrings(node.id, searchTerms)) {
    matchLabel = node.id;
  } else if (matchStrings(node.type.displayName || node.type.name, searchTerms)) {
    matchLabel = node.label;
  } else {
    let parameterNames = Object.keys(node.parameters);
    for (const parameterNameIndex in parameterNames) {
      const parameterName = parameterNames[parameterNameIndex];

      if (
        typeof node.parameters[parameterName] === 'string' &&
        matchStrings(node.parameters[parameterName], searchTerms)
      ) {
        let displayLabel = parameterName;
        let connectionPort = node.type.ports?.find((port) => port.name === parameterName);
        if (connectionPort) {
          displayLabel = connectionPort.displayName;
        }

        if (node.type.name === 'Javascript2' && parameterName === 'code') {
          matchLabel = 'In the code';
        } else if (node.type.name === 'Expression' && parameterName === 'expression') {
          matchLabel = 'In the expression';
        } else if (node.type.name === 'For Each' && parameterName === 'templateScript') {
          matchLabel = 'In the template script';
        } else if (node.type.name === 'REST' && parameterName === 'code') {
          matchLabel = 'In the script';
        } else if (node.type.name === 'Model' && parameterName === 'properties') {
          matchLabel = displayLabel;
        } else if (node.type.name === 'States' && parameterName === 'states') {
          matchLabel = displayLabel;
        } else {
          matchLabel = displayLabel + ': ' + node.parameters[parameterName];
        }

        break;
      }
    }

    if (matchLabel === null) {
      var ports = node.dynamicports;
      for (i = 0; i < ports.length; ++i) {
        var port = ports[i];
        if (matchStrings(port.name, searchTerms)) {
          matchLabel = node.label + ' : ' + port.name;
          break;
        }
      }
    }

    if (matchLabel === null) {
      var ports = node.ports;
      for (i = 0; i < ports.length; ++i) {
        var port = ports[i];
        if (matchStrings(port.name, searchTerms)) {
          matchLabel = node.label + ' : ' + port.name;
          break;
        }
      }
    }
  }

  if (matchLabel !== null) {
    results.push({
      componentTarget: component,
      nodeTarget: node,
      type: node.type.displayName || node.type.name,
      userLabel: node._label,
      label: matchLabel
    });
  }

  for (i = 0; i < node.children.length; ++i) {
    var child = node.children[i];
    var childResults = searchInNodeRecursive(child, searchTerms, component);
    results = results.concat(childResults);
  }

  return results;
}

function searchInComponent(component, searchTerms) {
  var results = [];
  if (matchStrings(component.displayName, searchTerms)) {
    results.push({
      componentTarget: component,
      type: 'Component',
      label: component.displayName
    });
  }

  for (var i = 0; i < component.graph.roots.length; ++i) {
    var node = component.graph.roots[i];
    var nodeResults = searchInNodeRecursive(node, searchTerms, component);
    results = results.concat(nodeResults);
  }

  if (component.graph.commentsModel.comments) {
    for (var i = 0; i < component.graph.commentsModel.comments.length; ++i) {
      const comment = component.graph.commentsModel.comments[i];
      if (matchStrings(comment.text, searchTerms)) {
        results.push({
          componentTarget: component,
          type: 'Comment',
          label: comment.text
        });
      }
    }
  }

  if (results.length > 0) {
    return {
      componentName: component.displayName,
      componentId: component.id,
      results: results
    };
  } else {
    return null;
  }
}

function performSearch(searchTerms) {
  var results = [];
  var root = ProjectModel.instance.getRootNode();
  if (root === undefined) return;

  var components = ProjectModel.instance.components;

  for (var i = 0; i < components.length; ++i) {
    var component = components[i];

    var componentResults = searchInComponent(component, searchTerms);
    if (componentResults !== null) {
      //limit the label length (it can search in markdown, css, etc)
      for (const result of componentResults.results) {
        if (result.label?.length > 100) {
          result.label = result.label.substring(0, 100) + '...';
        }
      }

      results.push(componentResults);
    }
  }

  return results;
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/search-panel/search-panel.module.scss
var search_panel_module = __webpack_require__(83171);
;// ./src/editor/src/views/panels/search-panel/search-panel.module.scss

      
      
      
      
      
      
      
      
      

var search_panel_module_options = {};

search_panel_module_options.styleTagTransform = (styleTagTransform_default());
search_panel_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      search_panel_module_options.insert = insertBySelector_default().bind(null, "head");
    
search_panel_module_options.domAPI = (styleDomAPI_default());
search_panel_module_options.insertStyleElement = (insertStyleElement_default());

var search_panel_module_update = injectStylesIntoStyleTag_default()(search_panel_module/* default */.A, search_panel_module_options);




       /* harmony default export */ const search_panel_search_panel_module = (search_panel_module/* default */.A && search_panel_module/* default */.A.locals ? search_panel_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/search-panel/search-panel.tsx















function search_panel_SearchPanel() {
    const [searchTerm, setSearchTerm] = (0,external_react_.useState)('');
    const [searchResults, setSearchResults] = (0,external_react_.useState)([]);
    const inputRef = (0,external_react_.useRef)(null);
    // TODO: Not same context
    // const { lastActiveComponentId, switchToComponent } = useNodeGraphContext();
    useOnPanelActive(() => {
        inputRef.current.focus();
        inputRef.current.select();
    }, 'search');
    useSidePanelKeyboardCommands(() => [
        {
            weight: 2,
            handler: () => {
                inputRef.current.focus();
                inputRef.current.select();
            },
            keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.KEY_F
        }
    ], 'search');
    const debouncedSearchTerm = useDebounceState(searchTerm, 300);
    (0,external_react_.useEffect)(() => {
        if (debouncedSearchTerm.length === 0) {
            setSearchResults([]);
        }
        else {
            setSearchResults(performSearch(debouncedSearchTerm));
        }
    }, [debouncedSearchTerm]);
    function onSearchItemClicked(searchResult) {
        if (searchResult.type === 'Component') {
            NodeGraphContext.NodeGraphContextTmp.switchToComponent(searchResult.componentTarget, {
                breadcrumbs: false,
                pushHistory: true
            });
        }
        else {
            NodeGraphContext.NodeGraphContextTmp.switchToComponent(searchResult.componentTarget, {
                breadcrumbs: false,
                node: searchResult.nodeTarget,
                pushHistory: true
            });
        }
    }
    return (external_react_default().createElement(BasePanel, { title: "Search" },
        external_react_default().createElement("div", { className: search_panel_search_panel_module.SearchInput },
            external_react_default().createElement(Section/* Section */.w, { hasGutter: true },
                external_react_default().createElement(SearchInput/* SearchInput */.D, { placeholder: "Search nodes and properties", onChange: (text) => setSearchTerm(text), UNSAFE_style: { height: 34 }, value: searchTerm, inputRef: inputRef }))),
        external_react_default().createElement("div", { className: search_panel_search_panel_module.SearchResults },
            searchResults.map((component) => (external_react_default().createElement(Section/* Section */.w, { title: `${component.componentName} (${component.results.length} result${component.results.length > 1 ? 's' : ''})`, key: component.componentId, variant: Section/* SectionVariant */.$.Panel }, component.results.map((result, index) => (external_react_default().createElement("div", { className: external_classnames_default()(search_panel_search_panel_module.SearchResultItem
                // lastActiveComponentId === result.componentTarget.id && css['is-active']
                ), key: index, onClick: () => onSearchItemClicked(result) },
                external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Proud }, result.userLabel ? result.type + ' - ' + result.userLabel : result.type),
                external_react_default().createElement(typography_Text/* Text */.EY, null, result.label))))))),
            searchResults.length === 0 && debouncedSearchTerm.length > 0 && (external_react_default().createElement(Container, { hasXSpacing: true, hasYSpacing: true },
                external_react_default().createElement(typography_Text/* Text */.EY, null, "No results found"))))));
}

// EXTERNAL MODULE: ./src/editor/src/utils/triggerChain/index.ts + 2 modules
var triggerChain = __webpack_require__(41954);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/ChainStats.module.scss
var ChainStats_module = __webpack_require__(25352);
;// ./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/ChainStats.module.scss

      
      
      
      
      
      
      
      
      

var ChainStats_module_options = {};

ChainStats_module_options.styleTagTransform = (styleTagTransform_default());
ChainStats_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ChainStats_module_options.insert = insertBySelector_default().bind(null, "head");
    
ChainStats_module_options.domAPI = (styleDomAPI_default());
ChainStats_module_options.insertStyleElement = (insertStyleElement_default());

var ChainStats_module_update = injectStylesIntoStyleTag_default()(ChainStats_module/* default */.A, ChainStats_module_options);




       /* harmony default export */ const components_ChainStats_module = (ChainStats_module/* default */.A && ChainStats_module/* default */.A.locals ? ChainStats_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/ChainStats.tsx
/**
 * ChainStats Component
 *
 * Displays statistics about the trigger chain.
 * Shows event counts, component breakdown, and timing info.
 */






function ChainStats({ events, isRecording }) {
    // Build chain and calculate stats
    const stats = (0,external_react_.useMemo)(() => {
        if (events.length === 0)
            return null;
        const chain = (0,triggerChain/* buildChainFromEvents */.rp)(events);
        return (0,triggerChain/* calculateStatistics */.G_)(chain);
    }, [events]);
    const handleComponentClick = (0,external_react_.useCallback)((componentName) => {
        var _a;
        // Don't navigate while recording
        if (isRecording)
            return;
        // Find and navigate to the component
        const component = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(componentName);
        if (component && NodeGraphContext.NodeGraphContextTmp.switchToComponent) {
            NodeGraphContext.NodeGraphContextTmp.switchToComponent(component, { pushHistory: true });
        }
    }, [isRecording]);
    if (!stats) {
        return null;
    }
    return (external_react_default().createElement("div", { className: components_ChainStats_module['ChainStats'] },
        external_react_default().createElement("h4", { className: components_ChainStats_module['StatsTitle'] },
            external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Setting }),
            "Chain Statistics"),
        external_react_default().createElement("div", { className: components_ChainStats_module['StatGroup'] },
            external_react_default().createElement("div", { className: components_ChainStats_module['StatItem'] },
                external_react_default().createElement("span", { className: components_ChainStats_module['StatLabel'] }, "Total Events"),
                external_react_default().createElement("span", { className: components_ChainStats_module['StatValue'] }, stats.totalEvents))),
        external_react_default().createElement("div", { className: components_ChainStats_module['StatGroup'] },
            external_react_default().createElement("h5", { className: components_ChainStats_module['GroupTitle'] }, "Events by Type"),
            Array.from(stats.eventsByType.entries()).map(([type, count]) => (external_react_default().createElement("div", { key: type, className: components_ChainStats_module['StatItem'] },
                external_react_default().createElement("span", { className: components_ChainStats_module['StatLabel'] }, type),
                external_react_default().createElement("span", { className: components_ChainStats_module['StatValue'] }, count))))),
        external_react_default().createElement("div", { className: components_ChainStats_module['StatGroup'] },
            external_react_default().createElement("h5", { className: components_ChainStats_module['GroupTitle'] }, "Events by Component"),
            Array.from(stats.eventsByComponent.entries()).map(([component, count]) => (external_react_default().createElement("div", { key: component, className: components_ChainStats_module['StatItem'] },
                external_react_default().createElement("span", { className: components_ChainStats_module['StatLabel'] }, component),
                external_react_default().createElement("span", { className: components_ChainStats_module['StatValue'] }, count))))),
        external_react_default().createElement("div", { className: components_ChainStats_module['StatGroup'] },
            external_react_default().createElement("h5", { className: components_ChainStats_module['GroupTitle'] }, "Timing"),
            external_react_default().createElement("div", { className: components_ChainStats_module['StatItem'] },
                external_react_default().createElement("span", { className: components_ChainStats_module['StatLabel'] }, "Average Gap"),
                external_react_default().createElement("span", { className: components_ChainStats_module['StatValue'] },
                    stats.averageEventGap.toFixed(2),
                    "ms")),
            external_react_default().createElement("div", { className: components_ChainStats_module['StatItem'] },
                external_react_default().createElement("span", { className: components_ChainStats_module['StatLabel'] }, "Longest Gap"),
                external_react_default().createElement("span", { className: components_ChainStats_module['StatValue'] },
                    stats.longestGap.toFixed(2),
                    "ms"))),
        external_react_default().createElement("div", { className: components_ChainStats_module['StatGroup'] },
            external_react_default().createElement("h5", { className: components_ChainStats_module['GroupTitle'] }, "Components Involved"),
            external_react_default().createElement("div", { className: components_ChainStats_module['ComponentList'] }, stats.componentsInvolved.map((component) => (external_react_default().createElement("div", { key: component, className: components_ChainStats_module['ComponentChip'], onClick: () => handleComponentClick(component), style: { cursor: isRecording ? 'default' : 'pointer' } },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Component }),
                external_react_default().createElement("span", null, component))))))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/ChainTimeline.module.scss
var ChainTimeline_module = __webpack_require__(51178);
;// ./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/ChainTimeline.module.scss

      
      
      
      
      
      
      
      
      

var ChainTimeline_module_options = {};

ChainTimeline_module_options.styleTagTransform = (styleTagTransform_default());
ChainTimeline_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ChainTimeline_module_options.insert = insertBySelector_default().bind(null, "head");
    
ChainTimeline_module_options.domAPI = (styleDomAPI_default());
ChainTimeline_module_options.insertStyleElement = (insertStyleElement_default());

var ChainTimeline_module_update = injectStylesIntoStyleTag_default()(ChainTimeline_module/* default */.A, ChainTimeline_module_options);




       /* harmony default export */ const components_ChainTimeline_module = (ChainTimeline_module/* default */.A && ChainTimeline_module/* default */.A.locals ? ChainTimeline_module/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/EventStep.module.scss
var EventStep_module = __webpack_require__(53482);
;// ./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/EventStep.module.scss

      
      
      
      
      
      
      
      
      

var EventStep_module_options = {};

EventStep_module_options.styleTagTransform = (styleTagTransform_default());
EventStep_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      EventStep_module_options.insert = insertBySelector_default().bind(null, "head");
    
EventStep_module_options.domAPI = (styleDomAPI_default());
EventStep_module_options.insertStyleElement = (insertStyleElement_default());

var EventStep_module_update = injectStylesIntoStyleTag_default()(EventStep_module/* default */.A, EventStep_module_options);




       /* harmony default export */ const components_EventStep_module = (EventStep_module/* default */.A && EventStep_module/* default */.A.locals ? EventStep_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/EventStep.tsx
/**
 * EventStep Component
 *
 * Displays a single event in the trigger chain timeline.
 * Shows node info, timing, and event type.
 */





/**
 * Get icon for event type
 */
function getEventTypeIcon(type) {
    switch (type) {
        case 'signal':
            return common_Icon/* IconName */.$M.Play;
        case 'value-change':
            return common_Icon/* IconName */.$M.Setting;
        case 'component-enter':
            return common_Icon/* IconName */.$M.Component;
        case 'component-exit':
            return common_Icon/* IconName */.$M.Component;
        case 'api-call':
            return common_Icon/* IconName */.$M.CloudData;
        case 'api-response':
            return common_Icon/* IconName */.$M.CloudData;
        case 'navigation':
            return common_Icon/* IconName */.$M.Navigate;
        case 'error':
            return common_Icon/* IconName */.$M.Close;
        default:
            return common_Icon/* IconName */.$M.Play;
    }
}
/**
 * Format duration in milliseconds to readable string
 */
function formatDuration(ms) {
    if (ms < 1)
        return '<1ms';
    if (ms < 1000)
        return `${Math.round(ms)}ms`;
    return `${(ms / 1000).toFixed(2)}s`;
}
function EventStep({ event, timeSinceStart, timeSincePrevious, isRecording }) {
    const icon = getEventTypeIcon(event.type);
    const handleClick = (0,external_react_.useCallback)(() => {
        var _a;
        // Don't navigate while recording
        if (isRecording)
            return;
        // Find the component
        const component = (_a = projectmodel.ProjectModel.instance) === null || _a === void 0 ? void 0 : _a.getComponentWithName(event.componentName);
        if (!component || !NodeGraphContext.NodeGraphContextTmp.switchToComponent)
            return;
        // Find the node if we have a nodeId
        let nodeToSelect;
        if (event.nodeId && component.graph) {
            nodeToSelect = component.graph.findNodeWithId(event.nodeId);
        }
        // Navigate to component and select the node (if found)
        NodeGraphContext.NodeGraphContextTmp.switchToComponent(component, {
            node: nodeToSelect,
            pushHistory: true
        });
    }, [event.componentName, event.nodeId, isRecording]);
    return (external_react_default().createElement("div", { className: components_EventStep_module['EventStep'] },
        external_react_default().createElement("div", { className: components_EventStep_module['TimelineConnector'] },
            external_react_default().createElement("div", { className: components_EventStep_module['TimelineDot'] }),
            external_react_default().createElement("div", { className: components_EventStep_module['TimelineLine'] })),
        external_react_default().createElement("div", { className: components_EventStep_module['EventCard'], onClick: handleClick, style: { cursor: isRecording ? 'default' : 'pointer' } },
            external_react_default().createElement("div", { className: components_EventStep_module['EventHeader'] },
                external_react_default().createElement("div", { className: components_EventStep_module['EventIcon'] },
                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: icon })),
                external_react_default().createElement("div", { className: components_EventStep_module['EventMeta'] },
                    external_react_default().createElement("div", { className: components_EventStep_module['NodeInfo'] },
                        external_react_default().createElement("span", { className: components_EventStep_module['NodeType'] }, event.nodeType),
                        event.nodeLabel && external_react_default().createElement("span", { className: components_EventStep_module['NodeLabel'] }, event.nodeLabel)),
                    external_react_default().createElement("div", { className: components_EventStep_module['ComponentInfo'] },
                        external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Component }),
                        external_react_default().createElement("span", null, event.componentName))),
                external_react_default().createElement("div", { className: components_EventStep_module['EventType'] },
                    external_react_default().createElement("span", { className: components_EventStep_module[`type-${event.type}`] }, event.type))),
            external_react_default().createElement("div", { className: components_EventStep_module['EventTiming'] },
                external_react_default().createElement("div", { className: components_EventStep_module['TimingItem'] },
                    external_react_default().createElement("span", { className: components_EventStep_module['TimingLabel'] }, "Since Start:"),
                    external_react_default().createElement("span", { className: components_EventStep_module['TimingValue'] }, formatDuration(timeSinceStart))),
                timeSincePrevious > 0 && (external_react_default().createElement("div", { className: components_EventStep_module['TimingItem'] },
                    external_react_default().createElement("span", { className: components_EventStep_module['TimingLabel'] }, "Delta:"),
                    external_react_default().createElement("span", { className: components_EventStep_module['TimingValue'] },
                        "+",
                        formatDuration(timeSincePrevious))))),
            event.port && (external_react_default().createElement("div", { className: components_EventStep_module['EventPort'] },
                external_react_default().createElement("span", { className: components_EventStep_module['PortLabel'] }, "Port:"),
                external_react_default().createElement("span", { className: components_EventStep_module['PortName'] }, event.port))),
            event.data !== undefined && (external_react_default().createElement("div", { className: components_EventStep_module['EventData'] },
                external_react_default().createElement("span", { className: components_EventStep_module['DataLabel'] }, "Data:"),
                external_react_default().createElement("code", { className: components_EventStep_module['DataValue'] }, typeof event.data === 'object' ? JSON.stringify(event.data, null, 2) : String(event.data)))),
            event.error && (external_react_default().createElement("div", { className: components_EventStep_module['EventError'] },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Close }),
                external_react_default().createElement("span", null, event.error.message))))));
}

;// ./src/editor/src/views/panels/TriggerChainDebuggerPanel/components/ChainTimeline.tsx
/**
 * ChainTimeline Component
 *
 * Displays a timeline visualization of trigger chain events.
 * Builds chains from raw events using buildChainFromEvents().
 */




function ChainTimeline({ events, isRecording }) {
    // Build the trigger chain from raw events
    const chain = (0,external_react_.useMemo)(() => {
        if (events.length === 0)
            return null;
        return (0,triggerChain/* buildChainFromEvents */.rp)(events);
    }, [events]);
    // Calculate timing for each event
    const timing = (0,external_react_.useMemo)(() => {
        if (!chain)
            return [];
        return (0,triggerChain/* calculateTiming */.pI)(chain);
    }, [chain]);
    if (!chain || events.length === 0) {
        return (external_react_default().createElement("div", { className: components_ChainTimeline_module['ChainTimeline'] },
            external_react_default().createElement("div", { className: components_ChainTimeline_module['EmptyTimeline'] },
                external_react_default().createElement("p", null, "No events to display"))));
    }
    return (external_react_default().createElement("div", { className: components_ChainTimeline_module['ChainTimeline'] },
        external_react_default().createElement("div", { className: components_ChainTimeline_module['ChainHeader'] },
            external_react_default().createElement("div", { className: components_ChainTimeline_module['ChainInfo'] },
                external_react_default().createElement("h3", null, chain.name),
                external_react_default().createElement("div", { className: components_ChainTimeline_module['ChainMeta'] },
                    external_react_default().createElement("span", null,
                        chain.eventCount,
                        " events"),
                    external_react_default().createElement("span", null, "\u2022"),
                    external_react_default().createElement("span", null,
                        chain.duration.toFixed(2),
                        "ms")))),
        external_react_default().createElement("div", { className: components_ChainTimeline_module['TimelineList'] }, chain.events.map((event) => {
            const eventTiming = timing.find((t) => t.eventId === event.id);
            return (external_react_default().createElement(EventStep, { key: event.id, event: event, timeSinceStart: (eventTiming === null || eventTiming === void 0 ? void 0 : eventTiming.sinceStart) || 0, timeSincePrevious: (eventTiming === null || eventTiming === void 0 ? void 0 : eventTiming.sincePrevious) || 0, isRecording: isRecording }));
        }))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/TriggerChainDebuggerPanel/TriggerChainDebuggerPanel.module.scss
var TriggerChainDebuggerPanel_module = __webpack_require__(83623);
;// ./src/editor/src/views/panels/TriggerChainDebuggerPanel/TriggerChainDebuggerPanel.module.scss

      
      
      
      
      
      
      
      
      

var TriggerChainDebuggerPanel_module_options = {};

TriggerChainDebuggerPanel_module_options.styleTagTransform = (styleTagTransform_default());
TriggerChainDebuggerPanel_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      TriggerChainDebuggerPanel_module_options.insert = insertBySelector_default().bind(null, "head");
    
TriggerChainDebuggerPanel_module_options.domAPI = (styleDomAPI_default());
TriggerChainDebuggerPanel_module_options.insertStyleElement = (insertStyleElement_default());

var TriggerChainDebuggerPanel_module_update = injectStylesIntoStyleTag_default()(TriggerChainDebuggerPanel_module/* default */.A, TriggerChainDebuggerPanel_module_options);




       /* harmony default export */ const TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module = (TriggerChainDebuggerPanel_module/* default */.A && TriggerChainDebuggerPanel_module/* default */.A.locals ? TriggerChainDebuggerPanel_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/panels/TriggerChainDebuggerPanel/TriggerChainDebuggerPanel.tsx
/**
 * Trigger Chain Debugger Panel
 *
 * Records and visualizes event trigger chains in the runtime preview.
 * Shows a timeline of events, their relationships, and component boundaries.
 */







function TriggerChainDebuggerPanel() {
    const [isRecording, setIsRecording] = (0,external_react_.useState)(false);
    const [eventCount, setEventCount] = (0,external_react_.useState)(0);
    const [liveEvents, setLiveEvents] = (0,external_react_.useState)(triggerChain/* triggerChainRecorder */.qF.getEvents());
    const handleStartRecording = (0,external_react_.useCallback)(() => {
        triggerChain/* triggerChainRecorder */.qF.startRecording();
        setIsRecording(true);
        setEventCount(0);
        setLiveEvents([]);
    }, []);
    const handleStopRecording = (0,external_react_.useCallback)(() => {
        triggerChain/* triggerChainRecorder */.qF.stopRecording();
        setIsRecording(false);
        const state = triggerChain/* triggerChainRecorder */.qF.getState();
        setEventCount(state.events.length);
    }, []);
    const handleClear = (0,external_react_.useCallback)(() => {
        triggerChain/* triggerChainRecorder */.qF.reset();
        setEventCount(0);
    }, []);
    const hasEvents = eventCount > 0;
    // Poll for events while recording (live updates)
    (0,external_react_.useEffect)(() => {
        if (!isRecording)
            return;
        const interval = setInterval(() => {
            const events = triggerChain/* triggerChainRecorder */.qF.getEvents();
            setEventCount(events.length);
            setLiveEvents(events);
        }, 100); // Poll every 100ms
        return () => clearInterval(interval);
    }, [isRecording]);
    return (external_react_default().createElement("div", { className: TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module['TriggerChainDebuggerPanel'] },
        external_react_default().createElement("div", { className: TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module['Header'] },
            external_react_default().createElement("div", { className: TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module['Title'] },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CloudData }),
                external_react_default().createElement("h2", null, "Trigger Chain Debugger")),
            isRecording && (external_react_default().createElement("div", { className: TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module['RecordingIndicator'] },
                external_react_default().createElement("span", { className: TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module['RecordingDot'] }),
                external_react_default().createElement("span", null, "Recording...")))),
        external_react_default().createElement("div", { className: TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module['Controls'] },
            !isRecording ? (external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Start Recording", onClick: handleStartRecording, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Cta, icon: common_Icon/* IconName */.$M.Play })) : (external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Stop Recording", onClick: handleStopRecording, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Danger, icon: common_Icon/* IconName */.$M.Close })),
            hasEvents && !isRecording && (external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Clear", onClick: handleClear, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, icon: common_Icon/* IconName */.$M.Trash })),
            hasEvents && (external_react_default().createElement("div", { className: TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module['EventCount'] },
                external_react_default().createElement("span", null,
                    eventCount,
                    " events captured")))),
        external_react_default().createElement("div", { className: TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module['Content'] },
            !hasEvents && !isRecording && (external_react_default().createElement("div", { className: TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module['EmptyState'] },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CloudData }),
                external_react_default().createElement("h3", null, "No Events Recorded"),
                external_react_default().createElement("p", null, "Click \"Start Recording\" then interact with your preview to capture event chains"))),
            isRecording && !hasEvents && (external_react_default().createElement("div", { className: TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module['RecordingState'] },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CloudData }),
                external_react_default().createElement("h3", null, "Recording Active"),
                external_react_default().createElement("p", null, "Interact with your preview to capture events..."))),
            hasEvents && (external_react_default().createElement("div", { className: TriggerChainDebuggerPanel_TriggerChainDebuggerPanel_module['TimelineContainer'] },
                external_react_default().createElement(ChainStats, { events: liveEvents, isRecording: isRecording }),
                external_react_default().createElement(ChainTimeline, { events: liveEvents, isRecording: isRecording }))))));
}

;// ./src/editor/src/views/panels/TriggerChainDebuggerPanel/index.ts
/**
 * Trigger Chain Debugger Panel
 *
 * Panel for recording and visualizing event trigger chains in the runtime.
 *
 * @module TriggerChainDebuggerPanel
 */


;// ./src/editor/src/views/panels/UndoQueuePanel/UndoQueuePanel.tsx







function UndoQueuePanel({}) {
    const undoQueue = (0,useModel/* useModel */.f)(undo_queue_model/* UndoQueue */.g.instance, ['undoHistoryChanged', 'undo', 'redo']);
    const historyLocation = undoQueue.getHistoryLocation();
    const history = [...undoQueue.getHistory()].reverse();
    return (external_react_default().createElement(BasePanel, { title: "History" },
        external_react_default().createElement(ExperimentalFlag, null),
        external_react_default().createElement(Container, { hasXSpacing: true, hasYSpacing: true, direction: ContainerDirection.Vertical }, history.map((item, index) => (external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { key: index, label: item.label, isGrowing: true, hasBottomSpacing: true }))))));
}

;// ./src/editor/src/views/panels/VersionControlPanel/index.ts
const VersionControlPanel_ID = 'versioncontrol';

;// ./src/editor/src/views/panels/useIsActivePanel.ts


function useIsActivePanel(panelId) {
    const [isActivePanel, setActivePanel] = (0,external_react_.useState)(sidebarmodel/* SidebarModel */.s.instance.getCurrent().id === panelId);
    (0,external_react_.useEffect)(() => {
        const eventRef = {};
        sidebarmodel/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.activeChanged, () => {
            setActivePanel(sidebarmodel/* SidebarModel */.s.instance.getCurrent().id === panelId);
        }, eventRef);
        return () => {
            sidebarmodel/* SidebarModel */.s.instance.off(eventRef);
        };
    }, []);
    return isActivePanel;
}

// EXTERNAL MODULE: ../noodl-git/src/core/logs.ts
var logs = __webpack_require__(41176);
// EXTERNAL MODULE: ../noodl-git/src/core/merge.ts + 1 modules
var core_merge = __webpack_require__(73622);
// EXTERNAL MODULE: ../noodl-git/src/core/reset.ts
var core_reset = __webpack_require__(33532);
// EXTERNAL MODULE: ../noodl-git/src/core/models/status.ts
var models_status = __webpack_require__(45226);
// EXTERNAL MODULE: ./src/editor/src/models/ProjectPatches/applypatches.js
var applypatches = __webpack_require__(26732);
// EXTERNAL MODULE: ./src/editor/src/utils/projectmerger.nodeequals.js
var projectmerger_nodeequals = __webpack_require__(42533);
;// ./src/editor/src/utils/projectmerger.diff.ts

const { isDeepStrictEqual } = __webpack_require__(28354);
const _ = __webpack_require__(42551);
function createEmptyArrayDiff() {
    return {
        deleted: [],
        created: [],
        changed: [],
        unchanged: [],
    };
}
function diff(_base, _current, keyFunc, diffFunc) {
    const created = [], deleted = [], changed = [], unchanged = [];
    // Lookups based on key
    const base = {}, current = {};
    for (var i in _base)
        base[keyFunc(_base[i])] = _base[i];
    for (var i in _current)
        current[keyFunc(_current[i])] = _current[i];
    const names = {};
    for (var key in base)
        names[key] = true;
    for (var key in current)
        names[key] = true;
    for (var key in names) {
        if (base[key] === undefined && current[key] !== undefined) {
            // Component created
            created.push(current[key]);
        }
        else if (base[key] !== undefined && current[key] === undefined) {
            // Component deleted
            deleted.push(base[key]);
        }
        else {
            var changes = diffFunc(base[key], current[key]);
            if (changes !== undefined) {
                // Component has changes
                changed.push(changes);
            }
            else {
                unchanged.push(current[key]);
            }
        }
    }
    return {
        deleted: deleted,
        created: created,
        changed: changed,
        unchanged: unchanged
    };
}
function diffConnections(base, current) {
    function key(c) {
        return c.fromId + ':' + c.fromProperty + '-' + c.toId + ':' + c.toProperty;
    }
    function diffFunc(b, c) {
        return;
    }
    var d = diff(base, current, key, diffFunc);
    d.deleted.forEach((c) => {
        c.annotation = 'Deleted';
    });
    d.created.forEach((c) => {
        c.annotation = 'Created';
    });
    const changes = d.deleted.concat(d.unchanged.concat(d.created));
    return {
        connections: changes,
        hasModifications: d.deleted.length + d.created.length > 0
    };
}
function diffNodes(base, current) {
    // Flatten node heirarchy (store parent reference)
    function collectNodes(nodes, parent, list) {
        if (!nodes)
            return;
        if (!list)
            list = [];
        for (var i = 0; i < nodes.length; i++) {
            var n = nodes[i];
            if (parent)
                n._parent = parent.id;
            n._sort = i;
            list.push(n);
            collectNodes(n.children, n, list);
            delete n.children; // Remove children, creating a flattened list
        }
        return list;
    }
    var baseFlattened = collectNodes(base);
    var currentFlattened = collectNodes(current);
    // Merge all nodes
    function key(o) {
        return o.id;
    }
    function diffNode(base, current) {
        if ((0,projectmerger_nodeequals.nodesSoftEqual)(base, current))
            return;
        // No change
        else {
            current.diffData = { parent: base };
            return current;
        }
    }
    var d = diff(baseFlattened, currentFlattened, key, diffNode);
    d.deleted.forEach((n) => {
        n.annotation = 'Deleted';
    });
    d.created.forEach((n) => {
        n.annotation = 'Created';
    });
    d.changed.forEach((n) => {
        n.annotation = 'Changed';
    });
    var res = d.unchanged.concat(d.changed.concat(d.deleted.concat(d.created)));
    // Recreate the hierarchy
    function collectChildren(node) {
        var id = node.id;
        var children = [];
        for (var i in res) {
            if (res[i]._parent === id)
                children.push(res[i]);
        }
        children.sort(function (a, b) {
            return a._sort > b._sort ? 1 : -1;
        });
        return children.length > 0 ? children : undefined;
    }
    for (var i in res) {
        var n = res[i];
        n.children = collectChildren(n);
    }
    // Delete temporary keys and store all roots
    var roots = [];
    for (var i in res) {
        if (!res[i]._parent)
            roots.push(res[i]);
        delete res[i]._parent;
        delete res[i]._sort;
    }
    return {
        roots,
        hasModifications: d.changed.length + d.deleted.length + d.created.length > 0
    };
}
function diffComments(base, current) {
    function diffComment(base, current) {
        const propsToOmit = ['x', 'y', 'width', 'height'];
        if (_.isEqual(_.omit(base, propsToOmit), _.omit(current, propsToOmit)))
            return;
        // No change
        else {
            current.diffData = { parent: base };
            return current;
        }
    }
    var d = diff(base, current, (c) => c.id, diffComment);
    d.deleted.forEach((n) => {
        n.annotation = 'deleted';
    });
    d.created.forEach((n) => {
        n.annotation = 'created';
    });
    d.changed.forEach((n) => {
        n.annotation = 'changed';
    });
    return {
        comments: d.unchanged.concat(d.changed.concat(d.deleted.concat(d.created))),
        hasModifications: d.changed.length + d.deleted.length + d.created.length > 0
    };
}
function diffComponent(base, current) {
    const changes = {
        graph: {
            connections: []
        }
    };
    const connDiff = diffConnections(base.graph.connections, current.graph.connections);
    const rootDiff = diffNodes(base.graph.roots, current.graph.roots);
    const commentDiff = diffComments(base.graph.comments, current.graph.comments);
    // First find delete and created connections
    changes.graph.connections = connDiff.connections;
    // Find deleted, created and changed nodes
    changes.graph.roots = rootDiff.roots;
    changes.graph.comments = commentDiff.comments;
    changes.name = current.name;
    changes.id = current.id;
    changes.metadata = current.metadata;
    return connDiff.hasModifications || rootDiff.hasModifications || commentDiff.hasModifications ? changes : undefined;
}
function diffComponents(baseComponents, currentComponents) {
    function key(o) {
        return o.id || o.name;
    }
    return diff(baseComponents, currentComponents, key, diffComponent);
}
function diffVariant(base, current) {
    if (!_.isEqual(base, current))
        return { name: current.name, typename: current.typename };
}
function diffVariants(baseVariants = [], currentVariants = []) {
    function key(v) {
        return v.typename + ':' + (v.name || '$default');
    }
    return diff(baseVariants, currentVariants, key, diffVariant);
}
//diff two Objects and return diff as {name, value} for each prop
function diffPlainObject(base, current, propsToIgnore) {
    const created = [];
    const deleted = [];
    const changed = [];
    const unchanged = [];
    const props = new Set(Object.keys(base)
        .concat(Object.keys(current))
        .filter((prop) => !propsToIgnore || propsToIgnore.includes(prop) === false));
    for (const key of props) {
        const keyValue = { name: key, value: current[key] };
        if (base[key] === undefined && current[key] !== undefined) {
            created.push(keyValue);
        }
        else if (base[key] !== undefined && current[key] === undefined) {
            deleted.push({ ...keyValue, oldValue: base[key] });
        }
        else {
            const isEqual = isDeepStrictEqual(current[key], base[key]);
            if (!isEqual) {
                changed.push({ ...keyValue, oldValue: base[key] });
            }
            else {
                unchanged.push(keyValue);
            }
        }
    }
    return {
        deleted: deleted,
        created: created,
        changed: changed,
        unchanged: unchanged
    };
}
function diffProject(base, current) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    //objects will be modified, so make a copy
    base = JSON.parse(JSON.stringify(base));
    current = JSON.parse(JSON.stringify(current));
    return {
        components: diffComponents(base.components, current.components),
        variants: diffVariants(base.variants, current.variants),
        settings: diffPlainObject(base.settings || {}, current.settings || {}),
        styles: {
            colors: diffPlainObject(((_b = (_a = base.metadata) === null || _a === void 0 ? void 0 : _a.styles) === null || _b === void 0 ? void 0 : _b.colors) || {}, ((_d = (_c = current.metadata) === null || _c === void 0 ? void 0 : _c.styles) === null || _d === void 0 ? void 0 : _d.colors) || {}),
            text: diffPlainObject(((_f = (_e = base.metadata) === null || _e === void 0 ? void 0 : _e.styles) === null || _f === void 0 ? void 0 : _f.text) || {}, ((_h = (_g = current.metadata) === null || _g === void 0 ? void 0 : _g.styles) === null || _h === void 0 ? void 0 : _h.text) || {})
        },
        cloudservices: diffPlainObject({ cloudservice: (_j = base.metadata) === null || _j === void 0 ? void 0 : _j.cloudservices }, { cloudservice: (_k = current.metadata) === null || _k === void 0 ? void 0 : _k.cloudservices }, ['instanceId'])
    };
}

;// ./src/editor/src/views/panels/VersionControlPanel/context/DiffUtils.ts








function getChangedComponents(components) {
    const items = components.changed
        .map((c) => ({ status: models_status/* FileStatusKind */.Jb.Modified, component: c }))
        .concat(components.created.map((c) => ({ status: models_status/* FileStatusKind */.Jb.New, component: c })))
        .concat(components.deleted.map((c) => ({ status: models_status/* FileStatusKind */.Jb.Deleted, component: c })));
    items.sort((a, b) => {
        if (a.component.name < b.component.name)
            return -1;
        return a.component.name > b.component.name ? 1 : 0;
    });
    return items;
}
function getChangedObjectProperties(properties) {
    const items = properties.changed
        .map((property) => ({ status: models_status/* FileStatusKind */.Jb.Modified, property }))
        .concat(properties.created.map((property) => ({ status: models_status/* FileStatusKind */.Jb.New, property })))
        .concat(properties.deleted.map((property) => ({ status: models_status/* FileStatusKind */.Jb.Deleted, property })));
    items.sort((a, b) => {
        if (a.property.name < b.property.name)
            return -1;
        return a.property.name > b.property.name ? 1 : 0;
    });
    return items;
}
function getFileStatusIconProps(status) {
    switch (status) {
        case models_status/* FileStatusKind */.Jb.Copied:
        case models_status/* FileStatusKind */.Jb.Untracked:
        case models_status/* FileStatusKind */.Jb.New:
            return {
                icon: common_Icon/* IconName */.$M.Plus,
                iconVariant: FeedbackType/* FeedbackType */.M.Success
            };
        case models_status/* FileStatusKind */.Jb.Renamed:
        case models_status/* FileStatusKind */.Jb.Conflicted:
        case models_status/* FileStatusKind */.Jb.Modified:
            return {
                icon: common_Icon/* IconName */.$M.DotsThreeHorizontal,
                iconVariant: FeedbackType/* FeedbackType */.M.Notice
            };
        case models_status/* FileStatusKind */.Jb.Deleted:
            return {
                icon: common_Icon/* IconName */.$M.Minus,
                iconVariant: FeedbackType/* FeedbackType */.M.Danger
            };
    }
}
function getProjectFilePath(repositoryPath, projectPath) {
    const relativePath = external_path_default().relative(repositoryPath, projectPath);
    const projectFilePath = external_path_default().join(relativePath, 'project.json').replaceAll('\\', '/');
    return projectFilePath;
}
async function doLocalDiff(repositoryPath, projectPath, headCommitId) {
    const projectFilePath = getProjectFilePath(repositoryPath, projectPath);
    try {
        const baseCommit = await (0,logs/* getCommit */.kO)(projectPath, headCommitId);
        const baseProjectJson = await baseCommit.getFileAsString(projectFilePath);
        const baseProject = JSON.parse(baseProjectJson);
        (0,applypatches.applyPatches)(baseProject);
        const diff = diffProject(baseProject, projectmodel.ProjectModel.instance.toJSON());
        return {
            ...diff,
            baseProject,
            commitShaDiffedTo: headCommitId
        };
    }
    catch (error) {
        if (error.toString().includes('exists on disk, but not in')) {
            console.warn('project.json does not exist in this commit.');
        }
        // Return empty state
        return {
            baseProject: {},
            commitShaDiffedTo: headCommitId,
            components: createEmptyArrayDiff(),
            variants: createEmptyArrayDiff(),
            settings: createEmptyArrayDiff(),
            styles: {
                colors: createEmptyArrayDiff(),
                text: createEmptyArrayDiff()
            },
            cloudservices: createEmptyArrayDiff()
        };
    }
}

// EXTERNAL MODULE: ../noodl-git/src/core/stash.ts
var core_stash = __webpack_require__(55654);
// EXTERNAL MODULE: ../noodl-git/src/core/status.ts + 5 modules
var core_status = __webpack_require__(99918);
;// ./src/editor/src/views/panels/VersionControlPanel/context/fetch.context.ts






function useVersionControlFetch({ git }) {
    // UI
    const [gitStatus, setGitStatus] = (0,external_react_.useState)({ kind: 'default' });
    const [lastFetchTime, setLastFetchTime] = (0,external_react_.useState)(undefined);
    // Data
    const [currentBranch, setCurrentBranch] = (0,external_react_.useState)(undefined);
    const [currentCommitSha, setCurrentCommitSha] = (0,external_react_.useState)(undefined);
    const [remoteCommitSha, setRemoteCommitSha] = (0,external_react_.useState)(undefined);
    const [workingDirectoryStatus, setWorkingDirectoryStatus] = (0,external_react_.useState)(null);
    const [branches, setBranches] = (0,external_react_.useState)(undefined);
    const [stashes, setStashes] = (0,external_react_.useState)([]);
    // Data helpers
    const [localCommitCount, setLocalCommitCount] = (0,external_react_.useState)(undefined);
    const [remoteCommitCount, setRemoteCommitCount] = (0,external_react_.useState)(undefined);
    const fetchLocal = (0,external_react_.useCallback)(async () => {
        const { workingDirectoryStatus, headSha, remoteHeadSha, branchName, branches, stashes } = await src.PromiseUtils.allObjects({
            workingDirectoryStatus: (0,core_status/* getStatus */.B)(git.repositoryPath),
            headSha: git.getHeadCommitId(),
            remoteHeadSha: git.getRemoteHeadCommitId(),
            branchName: git.getCurrentBranchName(),
            branches: (0,noodl_git_src/* getBranches */.p9)(git.repositoryPath),
            stashes: (0,core_stash/* getStashes */.At)(git.repositoryPath)
        });
        if (remoteHeadSha) {
            const aheadBehind = await git.aheadBehind(headSha, remoteHeadSha);
            setLocalCommitCount(aheadBehind.ahead);
            setRemoteCommitCount(aheadBehind.behind);
        }
        else {
            setLocalCommitCount(0);
            setRemoteCommitCount(0);
        }
        setWorkingDirectoryStatus(workingDirectoryStatus);
        setCurrentCommitSha(headSha);
        setRemoteCommitSha(remoteHeadSha);
        setCurrentBranch(branches.find((x) => x.name === branchName));
        setBranches(branches);
        setStashes(stashes.entries);
    }, []);
    const fetchRemote = (0,external_react_.useCallback)(async () => {
        async function perform() {
            await git.fetch({
                onProgress: (value) => {
                    setGitStatus({
                        kind: 'fetch',
                        progress: value.value
                    });
                }
            });
            setLastFetchTime(Date.now());
            await fetchLocal();
        }
        // Fetch remote changes
        setGitStatus({
            kind: 'fetch',
            progress: undefined
        });
        let success = false;
        let lastError = '';
        try {
            await perform();
            success = true;
        }
        catch (e) {
            if (e instanceof noodl_git_src/* GitActionError */.v7) {
                switch (e.code) {
                    case noodl_git_src/* GitActionErrorCode */.I7.LocalRepository:
                        setGitStatus({
                            kind: 'push-repository'
                        });
                        return;
                    case noodl_git_src/* GitActionErrorCode */.I7.AuthorizationFailed:
                        setGitStatus({
                            kind: 'set-authorization'
                        });
                        return;
                }
            }
            lastError = e.message;
            console.log(e.message);
        }
        if (!success) {
            // Check if the user is offline
            if (!window.navigator.onLine) {
                setGitStatus({
                    kind: 'error',
                    message: 'Please try again, it looks like you are offline.'
                });
            }
            else {
                setGitStatus({
                    kind: 'error-fetch',
                    message: lastError !== null && lastError !== void 0 ? lastError : 'Please try again'
                });
                if (lastError) {
                    ToastLayer.ToastLayer.showError(lastError);
                }
            }
            console.log(`Git fetch failed`);
        }
        else {
            setGitStatus((previous) => {
                if (previous.kind !== 'fetch') {
                    return previous;
                }
                return {
                    kind: 'default'
                };
            });
        }
    }, [fetchLocal]);
    const createStashMessage = (0,external_react_.useCallback)(() => {
        // NOTE: Using ":" here will create a marker and message.
        return `Stash from ${currentBranch.nameWithoutRemote} branch at #${currentCommitSha.slice(0, 7)}`;
    }, [currentBranch, currentCommitSha]);
    return {
        gitStatus,
        setGitStatus,
        lastFetchTime,
        currentBranch,
        currentCommitSha,
        remoteCommitSha,
        workingDirectoryStatus,
        branches,
        stashes,
        localCommitCount,
        remoteCommitCount,
        fetchLocal,
        fetchRemote,
        createStashMessage
    };
}

;// ./src/editor/src/views/panels/VersionControlPanel/context/index.tsx




const VersionControlContext = (0,external_react_.createContext)({
    git: null,
    repositoryPath: null,
    activeTabId: null,
    setActiveTabId: null,
    selectedCommit: null,
    setSelectedCommit: null,
    isPerformingAction: null,
    setIsPerformingAction: null,
    branchStatus: null,
    setBranchStatus: null,
    updateLocalDiff: null,
    localDiff: null,
    localFiles: null,
    localChangesCount: null,
    fetch: null
});
function getNumChanges(changes) {
    if (!changes)
        return 0;
    return changes.changed.length + changes.created.length + changes.deleted.length;
}
function VersionControlProvider({ git, children }) {
    var _a;
    // UI
    const [branchStatus, setBranchStatus] = (0,external_react_.useState)(null);
    const [activeTabId, setActiveTabId] = (0,external_react_.useState)('changes');
    const [selectedCommit, setSelectedCommit] = (0,external_react_.useState)(undefined);
    const [isPerformingAction, setIsPerformingAction] = (0,external_react_.useState)(false);
    const [localDiff, setLocalDiff] = (0,external_react_.useState)(null);
    const fetch = useVersionControlFetch({ git });
    const localFiles = (((_a = fetch.workingDirectoryStatus) === null || _a === void 0 ? void 0 : _a.files) || []).filter((f) => f.path !== 'project.json');
    const localChangesCount = getNumChanges(localDiff === null || localDiff === void 0 ? void 0 : localDiff.components) +
        localFiles.length +
        getNumChanges(localDiff === null || localDiff === void 0 ? void 0 : localDiff.settings) +
        getNumChanges(localDiff === null || localDiff === void 0 ? void 0 : localDiff.styles.colors) +
        getNumChanges(localDiff === null || localDiff === void 0 ? void 0 : localDiff.styles.text) +
        getNumChanges(localDiff === null || localDiff === void 0 ? void 0 : localDiff.cloudservices);
    const updateLocalDiff = (0,external_react_.useCallback)(() => {
        setLocalDiff(null); //reset old diff to show loaders again
        (async () => {
            const currentCommitSha = await git.getHeadCommitId();
            if (currentCommitSha) {
                const projectPath = projectmodel.ProjectModel.instance._retainedProjectDirectory;
                const diff = await doLocalDiff(git.repositoryPath, projectPath, currentCommitSha);
                setLocalDiff(diff);
            }
        })();
    }, []);
    //refresh diff if the current commit is changed, but only if we already have a diff
    (0,external_react_.useEffect)(() => {
        if ((localDiff === null || localDiff === void 0 ? void 0 : localDiff.commitShaDiffedTo) && (localDiff === null || localDiff === void 0 ? void 0 : localDiff.commitShaDiffedTo) !== fetch.currentCommitSha) {
            updateLocalDiff();
        }
    }, [localDiff === null || localDiff === void 0 ? void 0 : localDiff.commitShaDiffedTo, fetch.currentCommitSha]);
    (0,external_react_.useEffect)(() => {
        var _a;
        // User have to push before we can do anything
        if (fetch.gitStatus.kind === 'push-repository') {
            return;
        }
        if (fetch.remoteCommitCount > 0) {
            fetch.setGitStatus({
                kind: 'pull'
            });
        }
        else if (((_a = fetch.currentBranch) === null || _a === void 0 ? void 0 : _a.isLocal) || fetch.localCommitCount > 0) {
            fetch.setGitStatus({
                kind: 'push'
            });
        }
        else {
            fetch.setGitStatus({
                kind: 'default'
            });
        }
    }, [fetch.remoteCommitCount, fetch.localCommitCount, fetch.currentBranch]);
    // Do the first status check
    (0,external_react_.useEffect)(() => {
        // Fetch the current info first then we do a fetch call
        fetch.fetchRemote();
    }, []);
    const repositoryPath = git.repositoryPath;
    return (external_react_default().createElement(VersionControlContext.Provider, { value: {
            git,
            repositoryPath,
            activeTabId,
            setActiveTabId,
            selectedCommit,
            setSelectedCommit,
            isPerformingAction,
            setIsPerformingAction,
            branchStatus,
            setBranchStatus,
            localDiff: localDiff,
            localFiles,
            localChangesCount,
            updateLocalDiff,
            fetch
        } }, children));
}
function useVersionControlContext() {
    const context = (0,external_react_.useContext)(VersionControlContext);
    if (context === undefined) {
        throw new Error('useVersionControlContext must be a child of VersionControlProvider');
    }
    return context;
}

// EXTERNAL MODULE: ../noodl-git/src/core/diff-tree.ts
var diff_tree = __webpack_require__(78285);
// EXTERNAL MODULE: ../noodl-git/src/core/rev-list.ts
var rev_list = __webpack_require__(65079);
;// external "isbinaryfile"
const external_isbinaryfile_namespaceObject = require("isbinaryfile");
// EXTERNAL MODULE: ../noodl-git/src/core/show.ts
var show = __webpack_require__(35742);
;// ./src/editor/src/views/documents/ComponentDiffDocument/ImageDiffDialog.tsx




function ImageDiffDialog({ diff, onClose }) {
    return (external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { background: BaseDialog/* DialogBackground */.$j.Secondary, isVisible: diff !== null, hasBackdrop: true, onClose: onClose, UNSAFE_style: { width: '80vw' } },
        external_react_default().createElement(Container, { isFill: true, direction: ContainerDirection.Horizontal },
            Boolean(diff.original) && (external_react_default().createElement("div", { style: { width: '50%', padding: '8px' } },
                external_react_default().createElement("div", { style: { textAlign: 'center', paddingBottom: '8px' } },
                    external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Big }, "Previous")),
                external_react_default().createElement("img", { src: diff.original.dataSource, style: { width: '100%' } }))),
            external_react_default().createElement("div", { style: { width: '50%', padding: '8px' } },
                external_react_default().createElement("div", { style: { textAlign: 'center', paddingBottom: '8px' } },
                    external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Big }, "Current")),
                external_react_default().createElement("img", { src: diff.modified.dataSource, style: { width: '100%' } })))));
}

;// ./src/editor/src/views/panels/VersionControlPanel/hooks/useShowComponentDiffDocument.ts




function useShowComponentDiffDocument({ component, title, onDocumentClosed }) {
    (0,external_react_.useEffect)(() => {
        if (!component) {
            //if component is set to null after we have navigated to a diff, close the document
            if (AppRegistry.instance.CurrentDocumentId === ComponentDiffDocumentProvider.ID) {
                AppRegistry.instance.openDocument(EditorDocumentProvider.ID);
            }
            return;
        }
        AppRegistry.instance.openDocument(ComponentDiffDocumentProvider.ID, { component, title });
        const eventGroup = {};
        //If diff document is closed we want to deselect active component
        AppRegistry.instance.on('documentChanged', () => {
            if (AppRegistry.instance.CurrentDocumentId !== ComponentDiffDocumentProvider.ID) {
                onDocumentClosed();
            }
        }, eventGroup);
        return () => {
            AppRegistry.instance.off(eventGroup);
        };
    }, [component]);
    //close diff document when view unmounts
    (0,external_react_.useEffect)(() => {
        return () => {
            if (AppRegistry.instance.CurrentDocumentId === ComponentDiffDocumentProvider.ID) {
                AppRegistry.instance.openDocument(EditorDocumentProvider.ID);
            }
        };
    }, []);
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/DiffList.tsx






















function DiffList({ diff, fileChanges, componentDiffTitle, actions, commit }) {
    var _a;
    const { repositoryPath, fetch } = useVersionControlContext();
    const { currentCommitSha } = fetch;
    const [activeComponent, setActiveComponent] = (0,external_react_.useState)(null);
    const [codeDiff, setCodeDiff] = (0,external_react_.useState)(null);
    const [imageDiff, setImageDiff] = (0,external_react_.useState)(null);
    const components = (diff === null || diff === void 0 ? void 0 : diff.components) ? getChangedComponents(diff.components) : [];
    const files = ((_a = (fileChanges || [])) === null || _a === void 0 ? void 0 : _a.filter((f) => !f.path.endsWith('project.json'))) || [];
    const settings = (diff === null || diff === void 0 ? void 0 : diff.settings) ? getChangedObjectProperties(diff.settings) : [];
    const colorStyles = (diff === null || diff === void 0 ? void 0 : diff.styles.colors) ? getChangedObjectProperties(diff.styles.colors) : [];
    const textStyles = (diff === null || diff === void 0 ? void 0 : diff.styles.text) ? getChangedObjectProperties(diff.styles.text) : [];
    const cloudservices = (diff === null || diff === void 0 ? void 0 : diff.cloudservices) ? getChangedObjectProperties(diff.cloudservices) : [];
    const cloudKey = '/#__cloud__';
    const frontendComponents = components.filter((x) => !x.component.name.startsWith(cloudKey));
    const backendComponents = components.filter((x) => x.component.name.startsWith(cloudKey));
    (0,external_react_.useEffect)(() => {
        //make sure the active component exists in the diff. This can be false if a component is reset
        if (activeComponent && !components.find((c) => c.component.name === activeComponent.fullName)) {
            setActiveComponent(null);
        }
    }, [components, activeComponent]);
    useShowComponentDiffDocument({
        component: activeComponent,
        title: componentDiffTitle,
        onDocumentClosed: () => setActiveComponent(null)
    });
    function onComponentClicked(change) {
        if (componentId(activeComponent) === componentId(change.component)) {
            setActiveComponent(null);
            return;
        }
        //ComponentModel.fromJSON will trigger lots of global Model.* events, causing the project to save, which triggers the diff
        //Fix this by stopping the project from saving
        projectmodel.ProjectModel.setSaveOnModelChange(false);
        const componentModel = componentmodel/* ComponentModel */.j.fromJSON(change.component);
        projectmodel.ProjectModel.setSaveOnModelChange(true);
        setActiveComponent(componentModel);
    }
    const numChanges = components.length + files.length + settings.length + colorStyles.length + textStyles.length;
    return (external_react_default().createElement(ConditionalContainer, { doRenderWhen: diff !== null, loaderVisibilityDelayMs: 0, UNSAFE_root_style: { width: '100%' } },
        external_react_default().createElement(CodeDiffDialog, { onClose: () => setCodeDiff(null), diff: codeDiff }),
        Boolean(imageDiff) && external_react_default().createElement(ImageDiffDialog, { onClose: () => setImageDiff(null), diff: imageDiff }),
        numChanges == 0 && (external_react_default().createElement(Section/* Section */.w, { hasGutter: true, variant: Section/* SectionVariant */.$.PanelShy },
            external_react_default().createElement(Label/* Label */.JU, null, "No changes"))),
        external_react_default().createElement(Stack/* VStack */.Tk, null,
            Boolean((frontendComponents === null || frontendComponents === void 0 ? void 0 : frontendComponents.length) > 0) && (external_react_default().createElement(Section/* Section */.w, { title: "Changed Components", variant: Section/* SectionVariant */.$.PanelShy, hasBottomSpacing: true, hasVisibleOverflow: true }, frontendComponents.map((change) => (external_react_default().createElement(ListItem, { key: 'component_' + componentId(change.component), text: change.component.name, variant: componentId(activeComponent) === componentId(change.component)
                    ? ListItemVariant.Active
                    : ListItemVariant.Default, ...getFileStatusIconProps(change.status), ...getActionProps(actions === null || actions === void 0 ? void 0 : actions.component, change), onClick: () => onComponentClicked(change) }))))),
            Boolean((backendComponents === null || backendComponents === void 0 ? void 0 : backendComponents.length) > 0) && (external_react_default().createElement(Section/* Section */.w, { title: "Changed Cloud Components", variant: Section/* SectionVariant */.$.PanelShy, hasBottomSpacing: true, hasVisibleOverflow: true }, backendComponents.map((change) => (external_react_default().createElement(ListItem, { key: 'cloud_component_' + componentId(change.component), text: change.component.name.substring(cloudKey.length), variant: componentId(activeComponent) === componentId(change.component)
                    ? ListItemVariant.Active
                    : ListItemVariant.Default, ...getFileStatusIconProps(change.status), ...getActionProps(actions === null || actions === void 0 ? void 0 : actions.component, change), onClick: () => onComponentClicked(change) }))))),
            Boolean((files === null || files === void 0 ? void 0 : files.length) > 0) && (external_react_default().createElement(Section/* Section */.w, { title: "Changed Files", variant: Section/* SectionVariant */.$.PanelShy, hasBottomSpacing: true, hasVisibleOverflow: true }, files.map((change) => (external_react_default().createElement(ListItem, { key: 'file_' + change.id, text: change.path, onClick: async () => {
                    const diff = await getFileDiff(repositoryPath, change, currentCommitSha, commit);
                    switch (diff.kind) {
                        case diff_data/* DiffType */.s.Text:
                            setCodeDiff(diff);
                            break;
                        case diff_data/* DiffType */.s.Image:
                            setImageDiff(diff);
                            break;
                    }
                }, ...getFileStatusIconProps(change.status.kind), ...getActionProps(actions === null || actions === void 0 ? void 0 : actions.file, change) }))))),
            Boolean(settings.length > 0) && (external_react_default().createElement(Section/* Section */.w, { title: "Changed Settings", variant: Section/* SectionVariant */.$.PanelShy, hasBottomSpacing: true, hasVisibleOverflow: true }, settings.map((change) => {
                return (external_react_default().createElement(ListItem, { key: 'setting_' + change.property.name, text: getSettingDisplayName(change.property.name), onClick: () => {
                        setCodeDiff({
                            kind: diff_data/* DiffType */.s.Text,
                            original: change.property.oldValue,
                            modified: change.property.value
                        });
                    }, ...getFileStatusIconProps(change.status), ...getActionProps(actions === null || actions === void 0 ? void 0 : actions.setting, change) }));
            }))),
            Boolean(colorStyles.length > 0) && (external_react_default().createElement(Section/* Section */.w, { title: "Changed Color Styles", variant: Section/* SectionVariant */.$.PanelShy, hasBottomSpacing: true, hasVisibleOverflow: true }, colorStyles.map((change) => {
                return (external_react_default().createElement(ListItem, { key: 'style_color_' + change.property.name, text: change.property.name, onClick: () => {
                        setCodeDiff({
                            kind: diff_data/* DiffType */.s.Text,
                            original: change.property.oldValue,
                            modified: change.property.value
                        });
                    }, ...getFileStatusIconProps(change.status), ...getActionProps(actions === null || actions === void 0 ? void 0 : actions.colorStyle, change) }));
            }))),
            Boolean(textStyles.length > 0) && (external_react_default().createElement(Section/* Section */.w, { title: "Changed Text Styles", variant: Section/* SectionVariant */.$.PanelShy, hasBottomSpacing: true, hasVisibleOverflow: true }, textStyles.map((change) => {
                return (external_react_default().createElement(ListItem, { key: 'style_text_' + change.property.name, text: change.property.name, onClick: () => {
                        setCodeDiff({
                            kind: diff_data/* DiffType */.s.Text,
                            original: change.property.oldValue,
                            modified: change.property.value
                        });
                    }, ...getFileStatusIconProps(change.status), ...getActionProps(actions === null || actions === void 0 ? void 0 : actions.textStyle, change) }));
            }))),
            Boolean(cloudservices.length > 0) && (external_react_default().createElement(Section/* Section */.w, { title: "Other", variant: Section/* SectionVariant */.$.PanelShy, hasBottomSpacing: true, hasVisibleOverflow: true },
                external_react_default().createElement(ListItem, { text: "Active editor cloud service", onClick: () => {
                        setCodeDiff({
                            kind: diff_data/* DiffType */.s.Text,
                            original: cloudservices[0].property.oldValue,
                            modified: cloudservices[0].property.value
                        });
                    }, ...getFileStatusIconProps(cloudservices[0].status), ...getActionProps(actions === null || actions === void 0 ? void 0 : actions.cloudservice, cloudservices[0]) }))))));
}
function getSettingDisplayName(portName) {
    const ports = nodelibrary/* NodeLibrary */.m.instance.getProjectSettingsPorts();
    const allPorts = (ports.ports || []).concat(ports.dynamicports || []);
    const p = allPorts.find((p) => p.name === portName);
    return ((p === null || p === void 0 ? void 0 : p.group) || 'Other') + ': ' + ((p === null || p === void 0 ? void 0 : p.displayName) || portName);
}
//sometimes components don't have IDs
function componentId(component) {
    return (component === null || component === void 0 ? void 0 : component.id) || (component === null || component === void 0 ? void 0 : component.name);
}
function getActionProps(action, change) {
    return {
        isShowingAffixOnHover: !!action,
        affix: Boolean(action) && (external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { variant: inputs_IconButton/* IconButtonVariant */.nl.SemiTransparent, size: common_Icon/* IconSize */.lK.Small, icon: action.icon, onClick: (e) => {
                action.onClick(change);
                e.stopPropagation();
            } }))
    };
}
async function getFileDiff(repositoryPath, change, currentCommitSha, commit) {
    if (change.status.kind === models_status/* FileStatusKind */.Jb.Modified) {
        if (commit) {
            // compare against parent commit
            if (commit.parentSHAs[0]) {
                return await diff_fromSHA(repositoryPath, change, commit.parentSHAs[0], commit.sha);
            }
        }
        else {
            // compare against working dir content
            const fullPath = external_node_path_default().join(projectmodel.ProjectModel.instance._retainedProjectDirectory, change.path);
            const { current, previous } = await src.PromiseUtils.allObjects({
                current: src.filesystem.readBinaryFile(fullPath),
                previous: (0,show/* getBlobBinaryContents */.B)(repositoryPath, currentCommitSha, change.path)
            });
            return await diff_fromBuffers(change, previous, current);
        }
    }
    else if (change.status.kind === models_status/* FileStatusKind */.Jb.New && commit) {
        const current = await (0,show/* getBlobBinaryContents */.B)(repositoryPath, commit.sha, change.path);
        return await diff_fromBuffers(change, null, current);
    }
    else if (change.status.kind === models_status/* FileStatusKind */.Jb.Untracked) {
        const fullPath = external_node_path_default().join(projectmodel.ProjectModel.instance._retainedProjectDirectory, change.path);
        const current = await src.filesystem.readBinaryFile(fullPath);
        return await diff_fromBuffers(change, null, current);
    }
    else if (change.status.kind === models_status/* FileStatusKind */.Jb.Deleted) {
        // if this is a local change we're reading from the latest commit.
        // if this is a commit we're diffing we need to read from its parent
        const sha = commit ? commit.parentSHAs[0] : currentCommitSha;
        const current = await (0,show/* getBlobBinaryContents */.B)(repositoryPath, sha, change.path);
        return await diff_fromBuffers(change, null, current);
    }
    return {
        kind: diff_data/* DiffType */.s.Unrenderable
    };
}
async function diff_fromSHA(repositoryPath, change, previousSHA, currentSHA) {
    const { current, previous } = await src.PromiseUtils.allObjects({
        current: (0,show/* getBlobBinaryContents */.B)(repositoryPath, currentSHA, change.path),
        previous: (0,show/* getBlobBinaryContents */.B)(repositoryPath, previousSHA, change.path)
    });
    return await diff_fromBuffers(change, previous, current);
}
async function diff_fromBuffers(change, previous, current) {
    const { currentIsBinary, previousIsBinary } = await src.PromiseUtils.allObjects({
        currentIsBinary: (0,external_isbinaryfile_namespaceObject.isBinaryFile)(current),
        previousIsBinary: previous ? (0,external_isbinaryfile_namespaceObject.isBinaryFile)(previous) : Promise.resolve(undefined)
    });
    const isBinary = currentIsBinary && (previousIsBinary || !previous);
    if (isBinary && (0,models_status/* isFileImage */.Av)(change)) {
        return {
            kind: diff_data/* DiffType */.s.Image,
            original: previous ? diff_data/* Image */._.fromBinary(change, previous) : undefined,
            modified: diff_data/* Image */._.fromBinary(change, current)
        };
    }
    if (!isBinary) {
        return {
            kind: diff_data/* DiffType */.s.Text,
            original: previous ? previous.toString('utf-8') : undefined,
            modified: current.toString('utf-8')
        };
    }
    return {
        kind: diff_data/* DiffType */.s.Binary
    };
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/CommitChangesDiff.tsx












function CommitChangesDiff(props) {
    const [diff, setDiff] = (0,external_react_.useState)(null);
    const [commitFiles, setCommitFiles] = (0,external_react_.useState)(null);
    const { commit } = props;
    const { repositoryPath } = useVersionControlContext();
    (0,external_react_.useEffect)(() => {
        //This component might re-render with a new diff, so reset diff to show loading indicator again
        setDiff(null);
        setCommitFiles(null);
        if (!commit || (props.kind === 'merge' && !props.refToDiffTo)) {
            return;
        }
        async function doDiff() {
            if (props.kind === 'parent') {
                const { diff, files } = await getParentDiff(repositoryPath, props.commit);
                setDiff(diff);
                setCommitFiles(files);
            }
            else if (props.kind === 'merge') {
                const { diff, files } = await getMergeDiff(repositoryPath, props.commit, props.refToDiffTo);
                setDiff(diff);
                setCommitFiles(files);
            }
        }
        doDiff();
    }, [commit, props.kind]);
    if (!commit) {
        return null;
    }
    return (external_react_default().createElement(DiffList, { diff: diff, fileChanges: commitFiles, commit: commit, componentDiffTitle: `Changes made in #${commit.shortSha} by ${commit.author.name}` }));
}
async function getParentDiff(repositoryPath, commit) {
    const parentSHA = commit.parentSHAs[0];
    if (!parentSHA) {
        //this only happens for the first commit
        const thisProject = await getProjectFile(commit);
        return {
            diff: diffProject({ components: [] }, thisProject),
            files: await commit.getFiles()
        };
    }
    const [currentCommit, otherCommit] = await Promise.all([
        (0,logs/* getCommit */.kO)(repositoryPath, commit.sha),
        (0,logs/* getCommit */.kO)(repositoryPath, parentSHA)
    ]);
    const [currentProject, otherProject] = await Promise.all([
        getProjectFile(currentCommit),
        getProjectFile(otherCommit)
    ]);
    return {
        diff: diffProject(otherProject, currentProject),
        files: await (0,diff_tree/* getCommitFiles */.R)(repositoryPath, commit.sha)
    };
}
async function getMergeDiff(repositoryPath, commit, refToDiffTo) {
    const mergeBaseSHA = await (0,core_merge/* getMergeBase */.sT)(repositoryPath, commit.sha, refToDiffTo);
    const [currentCommit, otherCommit, mergeBaseCommit] = await Promise.all([
        (0,logs/* getCommit */.kO)(repositoryPath, commit.sha),
        (0,logs/* getCommit */.kO)(repositoryPath, refToDiffTo),
        (0,logs/* getCommit */.kO)(repositoryPath, mergeBaseSHA)
    ]);
    const [currentProject, otherProject, ancestorProject] = await Promise.all([
        getProjectFile(currentCommit),
        getProjectFile(otherCommit),
        getProjectFile(mergeBaseCommit)
    ]);
    const result = (0,projectmerger.mergeProject)(ancestorProject, JSON.parse(JSON.stringify(currentProject)), otherProject);
    return {
        diff: diffProject(currentProject, result),
        files: await (0,diff_tree/* getCommitFiles */.R)(repositoryPath, (0,rev_list/* revRange */.zg)(commit.sha, refToDiffTo))
    };
}
async function getProjectFile(commit) {
    const projectFilePath = getProjectFilePath(commit.repositoryDir, projectmodel.ProjectModel.instance._retainedProjectDirectory);
    const projectContentRaw = await commit.getFileAsString(projectFilePath);
    const projectContent = JSON.parse(projectContentRaw);
    (0,applypatches.applyPatches)(projectContent);
    return projectContent;
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/BranchMerge.tsx
















function BranchMerge() {
    return (external_react_default().createElement(ScrollArea, null,
        external_react_default().createElement(Stack/* VStack */.Tk, null,
            external_react_default().createElement(BranchMergeChanges, null))));
}
function BranchMergeChanges() {
    const [commitMessage, setCommitMessage] = (0,external_react_.useState)('');
    const { repositoryPath, fetch, branchStatus, localChangesCount, setBranchStatus } = useVersionControlContext();
    const { currentBranch, fetchLocal } = fetch;
    const [ourCommit, setOurCommit] = (0,external_react_.useState)(null);
    const [HasLocalChangesDialog, showHasLocalChangesDialog] = useConfirmationDialog({
        isCancelButtonHidden: true,
        title: 'Merge',
        message: "Can't merge to a branch with local changes. Commit or stash your changes before merging.",
        confirmButtonLabel: 'OK'
    });
    (0,external_react_.useEffect)(() => {
        (async () => {
            const ourCommit = await (0,logs/* getCommit */.kO)(repositoryPath, fetch.currentCommitSha);
            setOurCommit(ourCommit);
        })();
    }, [fetch.currentCommitSha]);
    function onMergeBranches() {
        if (localChangesCount > 0) {
            showHasLocalChangesDialog();
            return;
        }
        async function doMerge() {
            var _a, _b;
            const activityId = 'branch-merge';
            ToastLayer.ToastLayer.showActivity(`Merging ${currentBranch.name} with ${branchStatus.to.nameWithoutRemote}`, activityId);
            try {
                //localChangesCount is zero but we might have some minor metadata changes, reset them before merging
                projectmodel.ProjectModel.setSaveOnModelChange(false);
                await (0,core_reset/* reset */.c)(repositoryPath, 0 /* GitResetMode.Hard */, 'HEAD');
                await (0,core_merge/* merge */.h1)(repositoryPath, branchStatus.to.nameWithoutRemote, {
                    message: commitMessage,
                    strategy: 'recursive',
                    strategyOption: 'ours'
                });
                setBranchStatus(null);
                EventDispatcher.EventDispatcher.instance.notifyListeners('projectChangedOnDisk');
                await fetchLocal();
            }
            catch (e) {
                ToastLayer.ToastLayer.showError(e.message || ((_b = (_a = e.result) === null || _a === void 0 ? void 0 : _a.output) === null || _b === void 0 ? void 0 : _b.toString()));
            }
            ToastLayer.ToastLayer.hideActivity(activityId);
            projectmodel.ProjectModel.setSaveOnModelChange(true);
        }
        doMerge();
    }
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(HasLocalChangesDialog, null),
        external_react_default().createElement(Container, { direction: ContainerDirection.Vertical, hasXSpacing: true, hasYSpacing: true },
            external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, "Please write a merge message."),
            external_react_default().createElement(TextArea, { value: commitMessage, onChange: (ev) => setCommitMessage(ev.target.value), placeholder: "Describe changes", hasBottomSpacing: true }),
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Merge branches", onClick: onMergeBranches })),
        external_react_default().createElement(CommitChangesDiff, { commit: ourCommit, kind: "merge", refToDiffTo: branchStatus.to.tip.sha })));
}

// EXTERNAL MODULE: ../noodl-git/src/core/checkout.ts
var checkout = __webpack_require__(36479);
// EXTERNAL MODULE: ../noodl-git/src/core/models/branch.ts + 1 modules
var models_branch = __webpack_require__(16279);
;// ./src/editor/src/utils/copyValueToClipboard.ts

/**
 * Simple copy to clipboard with ToastLayer support.
 *
 * @param param0
 * @returns
 */
function copyValueToClipboard({ value, successMessage, onSuccess, onError }) {
    return new Promise((resolve, reject) => {
        let valueToCopy = value;
        if (typeof value !== 'string') {
            valueToCopy = value.toString();
        }
        navigator.clipboard.writeText(valueToCopy).then(function () {
            ToastLayer.ToastLayer.showSuccess(successMessage || 'Copying to clipboard was successful!');
            onSuccess && onSuccess();
            resolve();
        }, function (err) {
            ToastLayer.ToastLayer.showError('Could not copy text to clipboard!');
            onError && onError(err);
            reject();
        });
    });
}

;// ../noodl-core-ui/src/components/layout/ListItemMenu/ListItemMenu.tsx




/**
 * Component building on top of **ListItem** to make it
 * easier to use **ContextMenu** as affix.
 *
 * When there are no **menuItems** it will fallback to show the **menuIcon**.
 */
function ListItemMenu(args) {
    const [isOpen, setIsOpen] = (0,external_react_.useState)(false);
    let isShowingAffixOnHover = !isOpen;
    if (typeof args.alwaysShowAffixIcon === 'boolean' && args.alwaysShowAffixIcon) {
        isShowingAffixOnHover = false;
    }
    return (external_react_default().createElement(ListItem, { ...args, isHover: isOpen, isShowingAffixOnHover: isShowingAffixOnHover, onClick: (ev) => !isOpen && args.onClick && args.onClick(ev), affix: args.isDisabled ? null : args.menuItems.length === 0 ? (external_react_default().createElement(common_Icon/* Icon */.In, { icon: args.menuIcon })) : (external_react_default().createElement(ContextMenu/* ContextMenu */.t, { onOpen: () => setIsOpen(true), onClose: () => setIsOpen(false), menuItems: args.menuItems || [] })) }));
}

;// ../noodl-core-ui/src/components/layout/ListItemMenu/index.ts


;// ./src/editor/src/views/panels/VersionControlPanel/constants.ts
// All of this will be moved to providers later.
const PROTECTED_BRANCHES = ['main'];

;// ./src/editor/src/views/panels/VersionControlPanel/components/BranchList.tsx
























function BranchList({ onBranchCheckout, onBranchCreated }) {
    const { repositoryPath, fetch, localChangesCount } = useVersionControlContext();
    const { branches, currentBranch } = fetch;
    const [otherBranches, setOtherBranches] = (0,external_react_.useState)([]);
    const [HaveLocalChangesDialog, showHaveLocalChangesDialog] = useConfirmationDialog({
        title: 'Switch branch',
        message: 'You have local changes. Please commit your changes or stash them before you switch branches.',
        confirmButtonLabel: 'OK',
        isCancelButtonHidden: true
    });
    (0,external_react_.useEffect)(() => {
        if (!branches) {
            return;
        }
        setOtherBranches(branches.filter((x) => x.name !== (currentBranch === null || currentBranch === void 0 ? void 0 : currentBranch.name)));
    }, [branches, currentBranch]);
    async function onBranchClick(branch) {
        if (localChangesCount > 0) {
            showHaveLocalChangesDialog();
            return;
        }
        onBranchCheckout();
        projectmodel.ProjectModel.setSaveOnModelChange(false);
        try {
            //localChangesCount is zero but we might have some minor metadata changes, reset them before switching branch
            await (0,core_reset/* reset */.c)(repositoryPath, 0 /* GitResetMode.Hard */, 'HEAD');
            await (0,checkout/* checkoutBranch */.n)(repositoryPath, branch, {
                force: false,
                commitish: undefined
            });
            EventDispatcher.EventDispatcher.instance.notifyListeners('projectChangedOnDisk');
            ToastLayer.ToastLayer.showSuccess(`Checked out ${branch.nameWithoutRemote} branch.`);
            await fetch.fetchLocal();
        }
        catch (error) {
            console.error(error);
            ToastLayer.ToastLayer.showError('Failed to checkout branch. Error: ' + error.toString());
        }
        projectmodel.ProjectModel.setSaveOnModelChange(true);
    }
    return (external_react_default().createElement(Section/* Section */.w, { title: "Other branches", actions: external_react_default().createElement(CreateBranchButton, { onBranchCreated: onBranchCreated }), hasBottomSpacing: true, UNSAFE_style: { backgroundColor: 'var(--theme-color-bg-3)' } },
        external_react_default().createElement(HaveLocalChangesDialog, null),
        otherBranches.length === 0 ? (external_react_default().createElement(Box/* Box */.a, { hasLeftSpacing: true },
            external_react_default().createElement(Label/* Label */.JU, { hasTopSpacing: true, hasBottomSpacing: true, variant: typography_Text/* TextType */.M2.Secondary }, "No other branches"))) : (otherBranches.map((x) => external_react_default().createElement(BranchListItem, { key: x.name, branch: x, onClick: () => onBranchClick(x) })))));
}
function BranchListItem({ branch, onClick }) {
    var _a;
    const { repositoryPath, fetch, setBranchStatus } = useVersionControlContext();
    const [DeleteDialog, conformDelete] = useConfirmationDialog({
        title: 'Confirm Delete branch',
        message: `Are you sure you want to delete ${branch.nameWithoutRemote} branch? This action cannot be undone.`,
        confirmButtonLabel: 'Yes, delete'
    });
    function onDelete() {
        conformDelete()
            .then(async () => {
            // TODO: Add a different confirmation dialog for deleting branch.
            //       Looking at GitHub Desktop, they have a checkbox for deleting remote branch.
            //       In case you want to keep the branch around, but not locally.
            try {
                // Delete the local branch
                if (branch.type === models_branch/* BranchType */.Rk.Local) {
                    await (0,noodl_git_src/* deleteLocalBranch */.PR)(repositoryPath, branch);
                }
                // Delete the remote branch
                if (branch.upstream) {
                    await (0,noodl_git_src/* deleteRemoteBranch */.SE)(repositoryPath, branch);
                }
                ToastLayer.ToastLayer.showSuccess(`Successfully deleted ${branch.nameWithoutRemote} branch.`);
            }
            catch (error) {
                if (error instanceof noodl_git_src/* GitActionError */.v7) {
                    ToastLayer.ToastLayer.showError(error.message);
                }
                else {
                    console.error(error);
                    ToastLayer.ToastLayer.showError('Failed to delete branch. Error: ' + error);
                }
            }
            // Fetch all the changes
            if (branch.upstream) {
                await fetch.fetchRemote();
            }
            else {
                await fetch.fetchLocal();
            }
        })
            .catch(() => {
            // Cancelled
        });
    }
    let menuItems = [];
    if (branch.type !== models_branch/* BranchType */.Rk.Remote) {
        menuItems = [
            {
                label: 'Copy branch name',
                onClick: () => copyValueToClipboard({
                    value: branch.nameWithoutRemote
                })
            },
            'divider',
            {
                label: `Merge into ${(_a = fetch.currentBranch) === null || _a === void 0 ? void 0 : _a.nameWithoutRemote}...`,
                onClick: () => setBranchStatus({
                    kind: 'merge',
                    to: branch
                })
            }
        ];
        // Add delete to branches that can be deleted
        if (!PROTECTED_BRANCHES.includes(branch.nameWithoutRemote)) {
            menuItems.push('divider');
            menuItems.push({
                label: 'Delete',
                onClick: onDelete
            });
        }
    }
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(DeleteDialog, null),
        external_react_default().createElement(ListItemMenu, { text: branch.nameWithoutRemote, variant: branch.type === models_branch/* BranchType */.Rk.Remote ? ListItemVariant.HighlightedShy : ListItemVariant.Highlighted, icon: common_Icon/* IconName */.$M.StructureCircle, gutter: 3, menuIcon: common_Icon/* IconName */.$M.ImportDown, menuItems: menuItems, onClick: () => onClick(branch) }, Boolean(branch.isLocal) && (external_react_default().createElement(Box/* Box */.a, { hasLeftSpacing: 1 },
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, size: typography_Text/* TextSize */.$C.Small, isSpan: true }, "(local only)"))))));
}
function CreateBranchButton({ onBranchCreated }) {
    var _a;
    const { git, fetch } = useVersionControlContext();
    const addButtonRef = (0,external_react_.useRef)(null);
    const [open, setOpen] = (0,external_react_.useState)(false);
    const [branchName, setBranchName] = (0,external_react_.useState)('');
    async function onCreate() {
        try {
            // Create the new branch
            // TODO: Setup expect error for git, status: 128. Invalid characters.
            await git.createAndCheckoutBranch(branchName);
            ToastLayer.ToastLayer.showSuccess(`Created and checked out branch ${branchName}`);
            onBranchCreated();
        }
        catch (error) {
            if (error instanceof noodl_git_src/* GitActionError */.v7) {
                ToastLayer.ToastLayer.showError(error.message);
            }
            else {
                console.error(error);
                ToastLayer.ToastLayer.showError('Failed to create branch. Error: ' + error);
            }
        }
        // Close the panel
        setOpen(false);
        setBranchName('');
        // Tell git to fetch the new local status
        fetch.fetchLocal();
    }
    function onCancel() {
        setBranchName('');
        setOpen(false);
    }
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement("div", { ref: addButtonRef },
            external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { size: common_Icon/* IconSize */.lK.Small, icon: common_Icon/* IconName */.$M.Plus, onClick: () => setOpen(true) })),
        external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { isVisible: open, triggerRef: addButtonRef, hasArrow: true, isLockingScroll: true, onClose: () => setOpen(false), UNSAFE_style: { width: '350px' } },
            external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasYSpacing: true },
                external_react_default().createElement(TextInput, { label: "Name", value: branchName, onChange: (ev) => setBranchName(ev.target.value.replace(/ /g, '-')), hasBottomSpacing: true, isAutoFocus: true }),
                external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
                    external_react_default().createElement(typography_Text/* Text */.EY, null,
                        "Create a new branch based on the current",
                        ' ',
                        external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud, isSpan: true }, (_a = fetch.currentBranch) === null || _a === void 0 ? void 0 : _a.nameWithoutRemote),
                        ' ',
                        "branch.")),
                external_react_default().createElement(Stack/* HStack */.zt, null,
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Create branch", isGrowing: true, hasRightSpacing: true, onClick: onCreate }),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, isGrowing: true, onClick: onCancel }))))));
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/BranchStatusButton.tsx









function BranchStatusButton() {
    const { branchStatus, setBranchStatus, fetch } = useVersionControlContext();
    const { currentBranch } = fetch;
    const [isBranchesOpen, setIsBranchesOpen] = (0,external_react_.useState)(false);
    (0,external_react_.useEffect)(() => {
        if ((branchStatus === null || branchStatus === void 0 ? void 0 : branchStatus.kind) === 'merge') {
            setIsBranchesOpen(false);
        }
    }, [branchStatus === null || branchStatus === void 0 ? void 0 : branchStatus.kind]);
    const props = (function () {
        if (!currentBranch) {
            return {
                icon: common_Icon/* IconName */.$M.StructureCircle,
                variant: ActionButtonVariant.BackgroundAction,
                prefixText: 'Active branch',
                label: '',
                isDisabled: true
            };
        }
        if (!branchStatus || typeof branchStatus === 'string') {
            return {
                icon: common_Icon/* IconName */.$M.StructureCircle,
                prefixText: 'Active branch',
                label: currentBranch === null || currentBranch === void 0 ? void 0 : currentBranch.name,
                affixIcon: isBranchesOpen ? common_Icon/* IconName */.$M.CaretUp : common_Icon/* IconName */.$M.CaretDown
            };
        }
        switch (branchStatus.kind) {
            case 'merge': {
                return {
                    icon: common_Icon/* IconName */.$M.ArrowLeft,
                    variant: ActionButtonVariant.Proud,
                    prefixText: 'Merging',
                    label: (external_react_default().createElement(Container, null,
                        external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud }, currentBranch.name),
                        external_react_default().createElement(Box/* Box */.a, { hasXSpacing: 1 },
                            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Default }, "with")),
                        external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud }, branchStatus.to.nameWithoutRemote)))
                };
            }
        }
    })();
    function onClick() {
        if (props.isDisabled)
            return;
        setBranchStatus(null);
        setIsBranchesOpen(!isBranchesOpen);
    }
    return (external_react_default().createElement("div", { style: { position: 'relative' } },
        external_react_default().createElement(ActionButton, { ...props, variant: isBranchesOpen ? ActionButtonVariant.Proud : props.variant || ActionButtonVariant.Default, onClick: onClick }),
        external_react_default().createElement("div", { style: {
                position: 'absolute',
                width: '100%',
                zIndex: 1,
                boxShadow: '0 10px 10px 0px var(--theme-color-bg-1-transparent-2)',
                maxHeight: '50vh',
                overflow: 'hidden overlay'
            } },
            external_react_default().createElement(Collapsible/* Collapsible */.N, { isCollapsed: !isBranchesOpen, transitionMs: 200 },
                external_react_default().createElement(BranchList, { onBranchCheckout: () => setIsBranchesOpen(false), onBranchCreated: () => setIsBranchesOpen(false) })))));
}

// EXTERNAL MODULE: ./src/editor/src/store/GitStore.ts + 1 modules
var GitStore = __webpack_require__(72316);
// EXTERNAL MODULE: ../noodl-git/src/core/trampoline/trampoline-askpass-handler.ts
var trampoline_askpass_handler = __webpack_require__(58848);
;// ./src/editor/src/views/panels/VersionControlPanel/components/GitProviderPopout/sections/CredentialsSection.tsx








function CredentialsSection({ provider, username, password, onUserNameChanged, onPasswordChanged }) {
    const passwordLabel = provider === 'github' ? 'Personal Access Token' : 'Password';
    const showUsername = provider !== 'github';
    const [hidePassword, setHidePassword] = (0,external_react_.useState)(true);
    // OAuth state management using GitHubOAuthService
    const [isAuthenticated, setIsAuthenticated] = (0,external_react_.useState)(false);
    const [authenticatedUsername, setAuthenticatedUsername] = (0,external_react_.useState)(null);
    const [isConnecting, setIsConnecting] = (0,external_react_.useState)(false);
    const [progressMessage, setProgressMessage] = (0,external_react_.useState)('');
    const [error, setError] = (0,external_react_.useState)(null);
    const oauthService = GitHubOAuthService/* GitHubOAuthService */.W.instance;
    // Initialize OAuth service on mount
    (0,external_react_.useEffect)(() => {
        if (provider === 'github') {
            console.log('🔧 [CredentialsSection] Initializing GitHubOAuthService...');
            oauthService.initialize().then(() => {
                setIsAuthenticated(oauthService.isAuthenticated());
                const user = oauthService.getCurrentUser();
                setAuthenticatedUsername((user === null || user === void 0 ? void 0 : user.login) || null);
                console.log('🔧 [CredentialsSection] Auth state:', oauthService.isAuthenticated(), user === null || user === void 0 ? void 0 : user.login);
            });
        }
    }, [provider, oauthService]);
    // Listen for auth state changes
    (0,useEventListener/* useEventListener */.M)(oauthService, 'auth-state-changed', (event) => {
        console.log('🔔 [CredentialsSection] Auth state changed:', event.authenticated);
        setIsAuthenticated(event.authenticated);
        if (event.authenticated) {
            const user = oauthService.getCurrentUser();
            setAuthenticatedUsername((user === null || user === void 0 ? void 0 : user.login) || null);
        }
        else {
            setAuthenticatedUsername(null);
        }
    });
    const handleConnect = async () => {
        console.log('🔘 [CredentialsSection] handleConnect called - button clicked!');
        setIsConnecting(true);
        setError(null);
        setProgressMessage('Opening GitHub in your browser...');
        try {
            console.log('🔐 [CredentialsSection] Calling GitHubOAuthService.initiateOAuth...');
            await oauthService.initiateOAuth();
            console.log('✅ [CredentialsSection] OAuth flow initiated');
            // State will be updated via event listener when auth completes
            setProgressMessage('Waiting for authorization...');
        }
        catch (err) {
            console.error('❌ [CredentialsSection] OAuth flow error:', err);
            setError(err instanceof Error ? err.message : 'Authentication failed');
            setProgressMessage('');
            setIsConnecting(false);
        }
    };
    // Listen for auth success to clear connecting state
    (0,useEventListener/* useEventListener */.M)(oauthService, 'oauth-success', () => {
        setIsConnecting(false);
        setProgressMessage('');
    });
    (0,useEventListener/* useEventListener */.M)(oauthService, 'oauth-error', (event) => {
        setIsConnecting(false);
        setError(event.error);
        setProgressMessage('');
    });
    const handleDisconnect = async () => {
        await oauthService.disconnect();
        setError(null);
    };
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        provider === 'github' && (external_react_default().createElement(Section/* Section */.w, { title: "GitHub Account (Recommended)", variant: Section/* SectionVariant */.$.InModal, hasGutter: true }, isAuthenticated ? (
        // Connected state
        external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true },
                "\u2713 Connected as ",
                external_react_default().createElement("strong", null, authenticatedUsername)),
            external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, "Your GitHub account is connected and will be used for all Git operations."),
            external_react_default().createElement(TextButton, { label: "Disconnect GitHub Account", onClick: handleDisconnect }))) : (
        // Not connected state
        external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, "Connect your GitHub account for the best experience. This enables advanced features and is more secure than Personal Access Tokens."),
            isConnecting && progressMessage && external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, progressMessage),
            error && external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, error),
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: isConnecting ? 'Connecting...' : 'Connect GitHub Account', onClick: handleConnect, isDisabled: isConnecting }))))),
        external_react_default().createElement(Section/* Section */.w, { title: provider === 'github' ? 'Or use Personal Access Token' : getTitle(provider), variant: Section/* SectionVariant */.$.InModal, hasGutter: true },
            showUsername && (external_react_default().createElement(TextInput, { hasBottomSpacing: true, label: "Username", value: username, variant: TextInputVariant.InModal, onChange: (ev) => onUserNameChanged(ev.target.value) })),
            external_react_default().createElement(TextInput, { hasBottomSpacing: true, label: passwordLabel, type: hidePassword ? 'password' : 'text', value: password, variant: TextInputVariant.InModal, onChange: (ev) => onPasswordChanged(ev.target.value), onFocus: () => setHidePassword(false), onBlur: () => setHidePassword(true) }),
            external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, "The credentials are saved encrypted locally per project."),
            provider === 'github' && !(password === null || password === void 0 ? void 0 : password.length) && (external_react_default().createElement("a", { href: "https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens", target: "_blank", rel: "noreferrer" }, "How to create a personal access token")))));
}
function getTitle(provider) {
    if (provider === 'github') {
        return 'GitHub Credentials';
    }
    return 'Git Credentials';
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/GitProviderPopout/sections/GitConfigSection.tsx




function GitConfigSection({ gitConfigName, onUserNameChanged, gitConfigEmail, onUserEmailChanged }) {
    return (external_react_default().createElement(Section/* Section */.w, { title: "Git Config Settings", variant: Section/* SectionVariant */.$.InModal, hasGutter: true },
        external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, "These are used as metadata for commits to help your collaborators understand who did a commit."),
        external_react_default().createElement(TextInput, { label: "Name", value: gitConfigName, variant: TextInputVariant.InModal, hasBottomSpacing: true, onChange: (ev) => onUserNameChanged(ev.target.value) }),
        external_react_default().createElement(TextInput, { label: "Email", value: gitConfigEmail, variant: TextInputVariant.InModal, onChange: (ev) => onUserEmailChanged(ev.target.value) })));
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/GitProviderPopout/sections/OriginSection.tsx







function OriginSection({ provider, origin, onOriginChanged }) {
    return (external_react_default().createElement(Section/* Section */.w, { title: "Git Origin", variant: Section/* SectionVariant */.$.InModal, hasGutter: true },
        external_react_default().createElement(TextInput, { hasBottomSpacing: true, label: "Git Origin", value: origin, variant: TextInputVariant.InModal, onChange: (ev) => onOriginChanged(ev.target.value) }),
        provider === 'noodl' && (external_react_default().createElement(Container, { hasBottomSpacing: true, UNSAFE_style: { alignItems: 'center', gap: '8px' } },
            external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.WarningTriangle, size: common_Icon/* IconSize */.lK.Default, variant: FeedbackType/* FeedbackType */.M.Danger, UNSAFE_style: { flexShrink: 0 } }),
            external_react_default().createElement(typography_Text/* Text */.EY, null, "This project has a git origin set to a deprecated Noodl git hosting service. Please update to a different origin, such as GitHub.")))));
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/GitProviderPopout/GitProviderPopout.tsx












function GitProviderPopout({ git }) {
    const [loading, setLoading] = (0,external_react_.useState)(true);
    const [username, setUsername] = (0,external_react_.useState)('');
    const [password, setPassword] = (0,external_react_.useState)('');
    const [gitConfigName, setGitConfigName] = (0,external_react_.useState)('');
    const [gitConfigEmail, setGitConfigEmail] = (0,external_react_.useState)('');
    const [gitOrigin, setGitOrigin] = (0,external_react_.useState)(git.OriginUrl);
    //load start values
    (0,external_react_.useEffect)(() => {
        async function getGitConfig() {
            const [config, name, email] = await Promise.all([
                GitStore/* GitStore */.W.get(git.Provider, projectmodel.ProjectModel.instance.id),
                git.getConfigValue('user.name'),
                git.getConfigValue('user.email')
            ]);
            setUsername(config === null || config === void 0 ? void 0 : config.username);
            setPassword(config === null || config === void 0 ? void 0 : config.password);
            setGitConfigName(name);
            setGitConfigEmail(email);
            setLoading(false);
        }
        getGitConfig();
    }, []);
    const provider = git.getProviderForRemote(gitOrigin);
    (0,external_react_.useEffect)(() => {
        async function getGitProviderConfig() {
            if (!provider)
                return;
            setLoading(true);
            const config = await GitStore/* GitStore */.W.get(provider, projectmodel.ProjectModel.instance.id);
            setUsername(config === null || config === void 0 ? void 0 : config.username);
            setPassword(config === null || config === void 0 ? void 0 : config.password);
            setLoading(false);
        }
        getGitProviderConfig();
    }, [provider]);
    const hasRemote = provider !== 'none' && provider !== 'noodl'; //the deprecated noodl remote is not a valid remote anymore
    function onSubmit() {
        async function updateGitConfig() {
            if ((await git.getConfigValue('user.name')) !== gitConfigName) {
                git.setConfigValue('user.name', gitConfigName);
            }
            if ((await git.getConfigValue('user.email')) !== gitConfigEmail) {
                git.setConfigValue('user.email', gitConfigEmail);
            }
            if (git.OriginUrl !== gitOrigin) {
                git.setRemoteURL(gitOrigin);
            }
        }
        async function updateGitStore() {
            try {
                const config = { password };
                if (provider !== 'github') {
                    config.username = username;
                }
                await GitStore/* GitStore */.W.set(provider, projectmodel.ProjectModel.instance.id, config);
                (0,trampoline_askpass_handler/* clearCredentialsCache */.id)();
            }
            catch (e) {
                console.log(e);
            }
        }
        setLoading(true);
        Promise.all([updateGitConfig(), updateGitStore()]).finally(() => {
            popuplayer_default().instance.hidePopouts();
        });
    }
    return (external_react_default().createElement(Stack/* VStack */.Tk, { UNSAFE_style: { width: '400px' } },
        external_react_default().createElement(OriginSection, { provider: provider, origin: gitOrigin, onOriginChanged: setGitOrigin }),
        external_react_default().createElement(ConditionalContainer, { doRenderWhen: !loading },
            hasRemote && (external_react_default().createElement(CredentialsSection, { provider: provider, username: username, onUserNameChanged: setUsername, password: password, onPasswordChanged: setPassword })),
            external_react_default().createElement(GitConfigSection, { gitConfigName: gitConfigName, onUserNameChanged: setGitConfigName, gitConfigEmail: gitConfigEmail, onUserEmailChanged: setGitConfigEmail }),
            external_react_default().createElement(Section/* Section */.w, { variant: Section/* SectionVariant */.$.InModal, hasGutter: true },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Save", onClick: onSubmit })))));
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/GitStatusButton.tsx











function GitStatusButton({ openGitSettingsPopout }) {
    const { git, repositoryPath, localChangesCount, fetch } = useVersionControlContext();
    const [StashBeforePullDialog, showStashBeforePullDialog] = useConfirmationDialog({
        message: 'You have local changes. Do you want to pull and merge your local changes?',
        confirmButtonLabel: 'Yes'
    });
    const { gitStatus, setGitStatus, currentBranch, lastFetchTime, localCommitCount, remoteCommitCount, fetchRemote, fetchLocal } = fetch;
    const [lastUpdate, setLastUpdate] = (0,external_react_.useState)(undefined);
    (0,external_react_.useEffect)(() => {
        if (lastFetchTime) {
            const date = new Date(lastFetchTime);
            const text = date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
            setLastUpdate(text);
        }
    }, [lastFetchTime]);
    function lastUpdateText() {
        return lastUpdate ? `Last updated ${lastUpdate}` : 'Fetching...';
    }
    const props = (function () {
        switch (gitStatus.kind) {
            case 'default':
                return {
                    icon: common_Icon/* IconName */.$M.Refresh,
                    label: 'Up to date',
                    affixText: lastUpdateText()
                };
            case 'error':
                return {
                    icon: common_Icon/* IconName */.$M.Refresh,
                    label: 'Failed',
                    affixText: gitStatus.message
                };
            case 'error-fetch':
                return {
                    icon: common_Icon/* IconName */.$M.Refresh,
                    label: 'Failed to update',
                    affixText: gitStatus.message
                };
            case 'fetch': {
                if (typeof gitStatus.progress === 'number') {
                    return {
                        icon: common_Icon/* IconName */.$M.ArrowDown,
                        isDisabled: true,
                        variant: ActionButtonVariant.Background,
                        label: 'Receiving Updates...',
                        affixText: `${Math.ceil(gitStatus.progress * 100)}%`
                    };
                }
                else {
                    return {
                        icon: common_Icon/* IconName */.$M.Refresh,
                        isDisabled: true,
                        variant: ActionButtonVariant.Background,
                        label: 'Checking for updates...',
                        affixText: lastUpdateText()
                    };
                }
            }
            case 'pull': {
                if (typeof gitStatus.progress === 'number') {
                    return {
                        icon: common_Icon/* IconName */.$M.ArrowDown,
                        isDisabled: true,
                        variant: ActionButtonVariant.BackgroundAction,
                        label: 'Pull in progress...',
                        affixText: `${gitStatus.message}: ${Math.ceil(gitStatus.progress * 100)}%`
                    };
                }
                else {
                    return {
                        icon: common_Icon/* IconName */.$M.ArrowDown,
                        variant: ActionButtonVariant.CallToAction,
                        label: remoteCommitCount === 1 ? `Pull 1 remote commit` : `Pull ${remoteCommitCount} remote commits`,
                        affixText: lastUpdateText()
                    };
                }
            }
            case 'push-repository': {
                return {
                    icon: common_Icon/* IconName */.$M.Setting,
                    variant: ActionButtonVariant.Background,
                    label: 'No remote set',
                    affixText: 'To push changes set a git remote'
                };
            }
            case 'push': {
                if (typeof gitStatus.progress === 'number') {
                    return {
                        icon: common_Icon/* IconName */.$M.ArrowUp,
                        isDisabled: true,
                        variant: ActionButtonVariant.BackgroundAction,
                        label: 'Push in progress...',
                        affixText: `${Math.ceil(gitStatus.progress * 100)}%`
                    };
                }
                else {
                    // Generic text to fit all edge cases
                    let label = 'Push local changes';
                    if (localCommitCount > 0) {
                        // Pluralize the text
                        label = localCommitCount === 1 ? `Push 1 local commit` : `Push ${localCommitCount} local commits`;
                    }
                    else if (currentBranch === null || currentBranch === void 0 ? void 0 : currentBranch.isLocal) {
                        // There are no local commits and the branch is only local.
                        label = `Push ${currentBranch.nameWithoutRemote} branch`;
                    }
                    return {
                        icon: common_Icon/* IconName */.$M.ArrowUp,
                        variant: ActionButtonVariant.CallToAction,
                        label,
                        affixText: lastUpdateText()
                    };
                }
            }
            case 'set-authorization': {
                if (git.Provider === 'noodl') {
                    return {
                        icon: common_Icon/* IconName */.$M.WarningTriangle,
                        variant: ActionButtonVariant.CallToAction,
                        label: 'Migration required',
                        affixText: 'Noodl git hosting is deprecated'
                    };
                }
                return {
                    icon: common_Icon/* IconName */.$M.Setting,
                    variant: ActionButtonVariant.CallToAction,
                    label: 'Update credentials',
                    affixText: 'Invalid credentials'
                };
            }
        }
    })();
    async function onAction() {
        switch (gitStatus.kind) {
            case 'default':
            case 'fetch':
            case 'error-fetch':
                return fetchRemote();
            case 'pull':
                setGitStatus({
                    kind: 'pull',
                    progress: 0
                });
                try {
                    let autoStash = undefined;
                    const autoStashMessge = 'Noodl autostash on pull';
                    if (localChangesCount === 0) {
                        await git.resetToHead();
                    }
                    else {
                        try {
                            await showStashBeforePullDialog();
                        }
                        catch (_) {
                            //user canceled
                            await fetchLocal();
                            return;
                        }
                        projectmodel.ProjectModel.setSaveOnModelChange(false);
                        autoStash = await (0,core_stash/* createStashEntry */.OT)(repositoryPath, autoStashMessge);
                    }
                    const remote = await (0,noodl_git_src/* getRemote */.Bo)(repositoryPath);
                    projectmodel.ProjectModel.setSaveOnModelChange(false);
                    await (0,noodl_git_src/* pull */.a$)(repositoryPath, remote, currentBranch, (progress) => {
                        setGitStatus({
                            kind: 'pull',
                            progress: progress.value,
                            message: progress.title || progress.description
                        });
                    });
                    if (await git.isRebaseInProgress()) {
                        await git.tryHandleRebaseState();
                        await fetchLocal();
                    }
                    if (autoStash) {
                        try {
                            await (0,core_stash/* popStashEntry */.$S)(repositoryPath, autoStash.name);
                        }
                        catch (err) {
                            //
                            // Here be dragons. Thou art forewarned
                            //
                            if (err.toString().includes('could not restore untracked files from stash')) {
                                const stashBranchName = `!!Noodl-AutoStash-${autoStash.branchName}`;
                                // Having some minor changes to project.json
                                await git.resetToHead();
                                // Create a new branch from the stash
                                // this will also checkout the branch
                                await (0,core_stash/* popStashEntryToBranch */.yT)(repositoryPath, autoStash.name, stashBranchName);
                                // Merge our working branch into the stash branch
                                await git._merge({
                                    theirsBranchName: currentBranch.name,
                                    oursBranchName: stashBranchName,
                                    isSquash: false,
                                    message: undefined,
                                    allowFastForward: false
                                });
                                const changes = await git.status();
                                if (changes.length > 0) {
                                    await git.commit('Merge stash');
                                }
                                // TODO: Should we make sure there are no issues?
                                // Checkout the working branch
                                await git.checkoutBranch(currentBranch.nameWithoutRemote);
                                // Squash merge our stash branch into the working branch without making any commits.
                                await (0,core_merge/* merge */.h1)(repositoryPath, stashBranchName, {
                                    strategy: 'recursive',
                                    strategyOption: 'theirs',
                                    isSquash: true,
                                    squashNoCommit: true,
                                    message: undefined,
                                    noFastForward: true
                                });
                                // Delete the stash branch
                                await git.deleteBranch(stashBranchName);
                                // And what should be left on the working branch is our stash, that we love so much!
                            }
                            else {
                                // We failed to pop the stash, this shouldn't happen, but we just log the error and return false.
                                throw err;
                            }
                        }
                    }
                    EventDispatcher.EventDispatcher.instance.notifyListeners('projectChangedOnDisk');
                }
                catch (error) {
                    if (error instanceof noodl_git_src/* GitActionError */.v7) {
                        if (error.code === noodl_git_src/* GitActionErrorCode */.I7.AuthorizationFailed) {
                            setGitStatus({
                                kind: 'set-authorization'
                            });
                        }
                        else {
                            ToastLayer.ToastLayer.showError(error.message);
                        }
                    }
                    else {
                        console.error(error);
                        ToastLayer.ToastLayer.showError('Failed to pull. Error: ' + error);
                    }
                }
                projectmodel.ProjectModel.setSaveOnModelChange(true);
                await fetchLocal();
                break;
            case 'push':
                setGitStatus({
                    kind: 'push',
                    progress: 0
                });
                try {
                    await (0,noodl_git_src/* push */.VC)({
                        baseDir: repositoryPath,
                        currentBranch,
                        onProgress: (progress) => {
                            setGitStatus({
                                kind: 'push',
                                message: progress.title,
                                progress: progress.value
                            });
                        }
                    });
                }
                catch (error) {
                    if (error instanceof noodl_git_src/* GitActionError */.v7 && error.code === noodl_git_src/* GitActionErrorCode */.I7.AuthorizationFailed) {
                        setGitStatus({
                            kind: 'set-authorization'
                        });
                    }
                    else {
                        ToastLayer.ToastLayer.showError('Failed to push. ' + error);
                        // If the error is a rejected push, we need to fetch again to get the latest state where we can pull and rebase
                        if (error === null || error === void 0 ? void 0 : error.toString().includes('rejected')) {
                            await fetchRemote();
                        }
                    }
                    return;
                }
                await fetchRemote();
                break;
            case 'push-repository':
            case 'set-authorization':
                openGitSettingsPopout();
                break;
        }
    }
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(StashBeforePullDialog, null),
        external_react_default().createElement(ActionButton, { ...props, onClick: onAction })));
}

// EXTERNAL MODULE: ../noodl-git/src/core/models/snapshot.ts + 1 modules
var snapshot = __webpack_require__(60629);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/version-control/GitHistoryItem/GitHistoryItem.module.scss
var GitHistoryItem_module = __webpack_require__(49449);
;// ../noodl-core-ui/src/components/version-control/GitHistoryItem/GitHistoryItem.module.scss

      
      
      
      
      
      
      
      
      

var GitHistoryItem_module_options = {};

GitHistoryItem_module_options.styleTagTransform = (styleTagTransform_default());
GitHistoryItem_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      GitHistoryItem_module_options.insert = insertBySelector_default().bind(null, "head");
    
GitHistoryItem_module_options.domAPI = (styleDomAPI_default());
GitHistoryItem_module_options.insertStyleElement = (insertStyleElement_default());

var GitHistoryItem_module_update = injectStylesIntoStyleTag_default()(GitHistoryItem_module/* default */.A, GitHistoryItem_module_options);




       /* harmony default export */ const GitHistoryItem_GitHistoryItem_module = (GitHistoryItem_module/* default */.A && GitHistoryItem_module/* default */.A.locals ? GitHistoryItem_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/version-control/GitHistoryItem/GitHistoryItem.tsx





var BranchColor;
(function (BranchColor) {
    BranchColor["Remote"] = "remote";
    BranchColor["Remote_Ahead"] = "remote_ahead";
    BranchColor["Local"] = "local";
})(BranchColor || (BranchColor = {}));
function BranchVizItem({ branches }) {
    const [svgHeight, setSvgHeight] = (0,external_react_.useState)(0);
    const svgRef = (0,external_react_.useRef)(null);
    (0,external_react_.useEffect)(() => {
        //some SVG parameters only work with absolute pixel positions, so track the height of the parent so we can
        //make the SVG graphic responsive
        const resizeObserver = new ResizeObserver((entries) => {
            setSvgHeight(entries[0].borderBoxSize[0].blockSize + 1); //add one pixel so we render over the list item divider
        });
        resizeObserver.observe(svgRef.current.parentNode);
        return () => {
            resizeObserver.disconnect();
        };
    }, []);
    //set height synchronously to avoid first frame flicker
    (0,external_react_.useLayoutEffect)(() => {
        setSvgHeight(svgRef.current.parentNode.getBoundingClientRect().height);
    }, []);
    const cy = svgHeight / 2;
    const leftPadding = 18; //enough room to render the largest circle without clipping
    const curveRadius = 8;
    return (external_react_default().createElement("svg", { ref: svgRef, strokeWidth: "2", xmlns: "http://www.w3.org/2000/svg" }, branches.map((b, i) => {
        const x = b.x + leftPadding;
        return (external_react_default().createElement((external_react_default()).Fragment, { key: i },
            external_react_default().createElement("g", { className: external_classnames_default()(GitHistoryItem_GitHistoryItem_module['Branch'], GitHistoryItem_GitHistoryItem_module[`is-variant-${b.color}`]) },
                b.top && (external_react_default().createElement("line", { className: external_classnames_default()(GitHistoryItem_GitHistoryItem_module['BranchTop'], GitHistoryItem_GitHistoryItem_module[`is-variant-${b.topColor}`]), x1: x, x2: x, y1: 0, y2: cy })),
                b.bottom && external_react_default().createElement("line", { x1: x, x2: x, y1: cy, y2: svgHeight }),
                Boolean(b.branchPoints) &&
                    b.branchPoints.map((bp, i) => (external_react_default().createElement("path", { key: i, stroke: bp.color, fill: "none", d: `M${x} ${cy} L${bp.x + leftPadding - curveRadius} ${cy} Q${bp.x + leftPadding} ${cy} ${bp.x + leftPadding} ${cy - curveRadius} L${bp.x + leftPadding} 0` }))),
                b.isHead && external_react_default().createElement("circle", { className: GitHistoryItem_GitHistoryItem_module['Head'], cx: x, cy: cy, r: "14", opacity: "0.3" }),
                b.circle && (external_react_default().createElement("circle", { className: external_classnames_default()([GitHistoryItem_GitHistoryItem_module['Circle'], b.isHead && GitHistoryItem_GitHistoryItem_module['is-head']]), cx: x, cy: cy, r: "7" })))));
    })));
}
function GitHistoryItem({ branches, hasAction, onClick, isSelected, children, UNSAFE_className, UNSAFE_style }) {
    const isFirstCommit = branches === null || branches === void 0 ? void 0 : branches.every((x) => !x.bottom);
    return (external_react_default().createElement("div", { className: external_classnames_default()([
            GitHistoryItem_GitHistoryItem_module['Root'],
            Boolean(hasAction) && GitHistoryItem_GitHistoryItem_module['can-selected'],
            isSelected && GitHistoryItem_GitHistoryItem_module['is-selected'],
            isFirstCommit && GitHistoryItem_GitHistoryItem_module['is-first-commit'],
            UNSAFE_className
        ]), style: UNSAFE_style, onClick: onClick },
        external_react_default().createElement("div", { className: external_classnames_default()([GitHistoryItem_GitHistoryItem_module['Item']]) },
            external_react_default().createElement(BranchVizItem, { branches: branches })),
        external_react_default().createElement(Stack/* VStack */.Tk, null,
            external_react_default().createElement(Box/* Box */.a, { hasYSpacing: 3 }, children))));
}

;// ../noodl-core-ui/src/components/version-control/GitHistoryItem/index.ts


;// ./src/editor/src/views/panels/VersionControlPanel/hooks/usecollaborators.ts

function useCollaborators() {
    const [collaborators, setCollaborators] = (0,external_react_.useState)(null);
    //TODO: fetch from git (all commiters)
    return collaborators;
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/HistoryCommitDiff.tsx











function HistoryCommitDiff({ commit }) {
    const { repositoryPath, localChangesCount, fetch } = useVersionControlContext();
    const [HaveLocalChangesDialog, showHaveLocalChangesDialog] = useConfirmationDialog({
        isCancelButtonHidden: true,
        title: 'Reset to commit',
        message: "Can't reset to this commit when you have local changes. Commit or stash your changes before applying.",
        confirmButtonLabel: 'OK'
    });
    const [HaveLocalCommitsDialog, showHaveLocalCommitsDialog] = useConfirmationDialog({
        title: 'Reset to commit',
        message: 'You have local commits that might be deleted by this operation. Are you sure you want to contine?',
        confirmButtonLabel: 'Yes, reset'
    });
    async function performResetToCommit() {
        projectmodel.ProjectModel.setSaveOnModelChange(false);
        await (0,core_reset/* reset */.c)(repositoryPath, 0 /* GitResetMode.Hard */, commit.sha);
        EventDispatcher.EventDispatcher.instance.notifyListeners('projectChangedOnDisk');
        await fetch.fetchLocal();
        ToastLayer.ToastLayer.showSuccess('Resetted to commit #' + commit.shortSha);
    }
    function resetToCommit() {
        if (localChangesCount > 0) {
            showHaveLocalChangesDialog();
        }
        else if (fetch.localCommitCount > 0) {
            showHaveLocalCommitsDialog().then(performResetToCommit);
        }
        else {
            performResetToCommit();
        }
    }
    return (external_react_default().createElement(Section/* Section */.w, { title: `Commit changes (#${commit.shortSha})`, variant: Section/* SectionVariant */.$.Panel, UNSAFE_style: { flex: '1' }, actions: external_react_default().createElement(ContextMenu/* ContextMenu */.t, { menuItems: [
                {
                    label: 'Reset to this commit',
                    onClick: resetToCommit
                },
                'divider',
                {
                    label: 'Copy SHA',
                    onClick: () => copyValueToClipboard({
                        value: commit.sha
                    })
                }
            ] }) },
        external_react_default().createElement(HaveLocalChangesDialog, null),
        external_react_default().createElement(HaveLocalCommitsDialog, null),
        external_react_default().createElement(CommitChangesDiff, { commit: commit, kind: "parent" })));
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/HistoryCommitItem.tsx







function CommitListItem({ item, onCommitSelected, selectedCommit }) {
    var _a, _b;
    function onClick(e) {
        // item.shortSha is the easiest way to check if this is a remote commit atm
        if (!!item.commit.shortSha) {
            if (selectedCommit && item.commit.sha === selectedCommit) {
                onCommitSelected(null);
            }
            else {
                onCommitSelected(item.commit.sha);
                setTimeout(() => {
                    e.target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'center'
                    });
                }, 100);
            }
        }
    }
    const collaborator = item.collaborator || (item.commit.author ? { id: 'invalid-id', ...item.commit.author } : null);
    const date = (_b = (_a = item.commit.author) === null || _a === void 0 ? void 0 : _a.date) === null || _b === void 0 ? void 0 : _b.toLocaleString(undefined, {
        weekday: 'short',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(GitHistoryItem, { branches: item.branches, isSelected: item.commit.sha === selectedCommit, hasAction: !!item.commit.shortSha, onClick: onClick },
            Boolean(item.commit.summary) && (external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: 2, hasTopSpacing: !collaborator, hasRightSpacing: 4 },
                external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Default }, item.commit.summary))),
            Boolean(collaborator) && (external_react_default().createElement(Box/* Box */.a, { UNSAFE_style: { display: 'flex', alignItems: 'center', userSelect: 'none' } },
                external_react_default().createElement(Tooltip/* Tooltip */.m, { content: collaborator.name || collaborator.email },
                    external_react_default().createElement(UserBadge, { email: collaborator.email, id: collaborator.id, name: collaborator.name, size: UserBadgeSize.Small })),
                external_react_default().createElement(Stack/* VStack */.Tk, null,
                    Boolean(item.commit.shortSha) && (external_react_default().createElement(Box/* Box */.a, { hasLeftSpacing: 2 },
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Medium, textType: typography_Text/* TextType */.M2.Proud },
                            "#",
                            item.commit.shortSha))),
                    external_react_default().createElement(Box/* Box */.a, { hasLeftSpacing: 2 },
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Medium }, date))))),
            Boolean(item.commit.tags.length) && (external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: 2, UNSAFE_style: { display: 'flex' } }, item.commit.tags.map((tag) => (external_react_default().createElement("div", { style: {
                    borderRadius: 4,
                    backgroundColor: 'var(--theme-color-secondary)',
                    color: 'var(--theme-color-on-secondary)',
                    padding: '4px 8px'
                } }, tag))))))));
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/History.tsx











function History() {
    const { repositoryPath, git, localChangesCount, selectedCommit, setSelectedCommit, fetch } = useVersionControlContext();
    const { currentBranch, currentCommitSha } = fetch;
    const collaborators = useCollaborators();
    const history = (0,external_react_.useMemo)(() => new noodl_git_src/* CommitHistory */.gf(repositoryPath, currentBranch), [repositoryPath, currentBranch]);
    const [commits, setCommits] = (0,external_react_.useState)([]);
    const [selectedCommitData, setSelectedCommitData] = (0,external_react_.useState)(null);
    (0,external_react_.useEffect)(() => {
        (async () => {
            if (selectedCommit) {
                const commit = await git.getCommitFromId(selectedCommit);
                setSelectedCommitData(commit);
            }
            else {
                setSelectedCommitData(null);
            }
        })();
    }, [selectedCommit]);
    const items = (0,external_react_.useMemo)(() => createBranchAndItemList(currentCommitSha, commits, collaborators, !!localChangesCount), [currentCommitSha, collaborators, commits, localChangesCount]);
    const isLoading = (0,external_react_.useRef)(false);
    const fetchData = async () => {
        if (!currentBranch) {
            return;
        }
        if (isLoading.current)
            return;
        isLoading.current = true;
        // TODO: Handle error
        const newCommits = await history.fetch(100);
        setCommits(newCommits);
        isLoading.current = false;
    };
    (0,external_react_.useEffect)(() => {
        fetchData();
    }, [history]);
    const remoteAheadCommits = items.filter((c) => c.commit.isRemoteAhead);
    const otherCommits = items.filter((c) => !c.commit.isRemoteAhead);
    return (external_react_default().createElement(Stack/* VStack */.Tk, { UNSAFE_style: { height: '100%' } },
        external_react_default().createElement(ScrollArea, null,
            external_react_default().createElement(Stack/* VStack */.Tk, { UNSAFE_style: { flex: '1', minHeight: '81px' } },
                Boolean(remoteAheadCommits.length) && (external_react_default().createElement(Section/* Section */.w, { title: "Remote Commits" }, remoteAheadCommits.map((x) => (external_react_default().createElement(CommitListItem, { item: x, key: x.commit.sha, onCommitSelected: setSelectedCommit, selectedCommit: selectedCommit }))))),
                Boolean(otherCommits.length) && (external_react_default().createElement(Section/* Section */.w, { title: "Commits" }, otherCommits.map((x) => (external_react_default().createElement(CommitListItem, { item: x, key: x.commit.sha, onCommitSelected: setSelectedCommit, selectedCommit: selectedCommit }))))))),
        Boolean(selectedCommitData) && external_react_default().createElement(HistoryCommitDiff, { commit: selectedCommitData })));
}
function createBranchAndItemList(headCommitId, commits, collaborators, hasLocalChanges) {
    if (commits.length === 0)
        return [];
    //Two "branches":;
    const remoteCommits = commits.filter((c) => !c.isLocalAhead); //stuff that's on the remote
    const localCommits = commits.filter((c) => c.isLocalAhead); //local commits that haven't been pushed
    //if we have local uncommited changes, visualize it as a special list item on the local branch
    if (hasLocalChanges) {
        localCommits.unshift(new noodl_git_src/* CommitHistoryEntry */.s9(new snapshot/* Commit */.gn(null, 'local changes', undefined, 'Local changes', undefined, undefined, undefined, [], []), false, false));
    }
    function mapItem(commit, branches) {
        const collaborator = collaborators === null || collaborators === void 0 ? void 0 : collaborators.find((c) => { var _a; return c.email === ((_a = commit.author) === null || _a === void 0 ? void 0 : _a.email); });
        return {
            commit,
            collaborator,
            branches
        };
    }
    let itemData = [];
    if (localCommits.length && remoteCommits.length) {
        const spacing = 28;
        //we have two branches
        //the local changes are "branched" from the first remote commit that is not ahead
        let localStartIndex = remoteCommits.findIndex((c) => !c.isRemoteAhead);
        if (localStartIndex === -1) {
            // there is no local commit, so local changes are "branched" from the latest pulled remote commit
            localStartIndex = 0;
        }
        //add all remote commits that are ahead
        for (let i = 0; i < localStartIndex; i++) {
            const c = remoteCommits[i];
            itemData.push(mapItem(c, [
                {
                    x: 0,
                    top: i > 0,
                    bottom: c.parentSHAs.length > 0,
                    color: BranchColor.Remote_Ahead,
                    circle: true,
                    isHead: false
                }
            ]));
        }
        //time for local commits
        const hasRemoteBranch = localStartIndex > 0;
        for (let i = 0; i < localCommits.length; i++) {
            const c = localCommits[i];
            const branches = [];
            if (hasRemoteBranch) {
                branches.push({
                    x: 0,
                    top: true,
                    bottom: true,
                    color: BranchColor.Remote_Ahead,
                    circle: false,
                    isHead: false
                });
            }
            branches.push({
                x: spacing,
                top: i > 0,
                bottom: i < localCommits.length,
                color: BranchColor.Local,
                circle: true,
                isHead: i === 0
            });
            itemData.push(mapItem(c, branches));
        }
        //commits after local changes
        for (let i = localStartIndex; i < remoteCommits.length; i++) {
            const c = remoteCommits[i];
            const branches = [
                {
                    x: 0,
                    top: i > localStartIndex || localStartIndex > 0,
                    topColor: i === localStartIndex ? BranchColor.Remote_Ahead : BranchColor.Remote,
                    bottom: c.parentSHAs.length > 0,
                    color: c.isRemoteAhead ? BranchColor.Remote_Ahead : BranchColor.Remote,
                    circle: true,
                    isHead: false
                }
            ];
            if (i === localStartIndex) {
                branches[0].branchPoints = [{ x: spacing, color: 'var(--branch-color-local)' }];
            }
            itemData.push(mapItem(c, branches));
        }
    }
    else if (localCommits.length) {
        itemData = localCommits.map((c, i) => {
            return mapItem(c, [
                {
                    x: 0,
                    top: i > 0,
                    bottom: c.parentSHAs.length > 0 || c.sha === 'local changes',
                    color: BranchColor.Local,
                    circle: true,
                    isHead: c.sha === headCommitId && !hasLocalChanges
                }
            ]);
        });
    }
    else if (remoteCommits.length) {
        itemData = remoteCommits.map((c, i) => {
            return mapItem(c, [
                {
                    x: 0,
                    top: i > 0,
                    bottom: c.parentSHAs.length > 0,
                    color: c.isRemoteAhead ? BranchColor.Remote_Ahead : BranchColor.Remote,
                    circle: true,
                    isHead: c.sha === headCommitId
                }
            ]);
        });
    }
    return itemData;
}

;// ./src/editor/src/views/panels/VersionControlPanel/helper.ts









function resetComponent(baseProjectJson, componentName) {
    const activityId = 'resetting-component';
    ToastLayer.ToastLayer.showActivity('Resetting component', activityId);
    //get previous version of component
    const baseCompJson = baseProjectJson.components.find((c) => c.name === componentName);
    const currentComponent = projectmodel.ProjectModel.instance.getComponentWithName(componentName);
    if (currentComponent && baseCompJson) {
        const isReplacingRootComponent = projectmodel.ProjectModel.instance.getRootComponent() === currentComponent;
        //we're resetting to a previous version of the same component
        //Do this by just replacing the graph, so we don't trigger ComponentRemoved and other events
        //that might affect Page Routers and have other unwanted side effects
        const graph = nodegraphmodel/* NodeGraphModel */.W2.fromJSON(baseCompJson.graph);
        currentComponent.bindGraph(graph);
        currentComponent.graph.evaluateHealth(); //update warnings
        if (isReplacingRootComponent) {
            //previous version of the component might have a different root node
            projectmodel.ProjectModel.instance.setRootComponent(currentComponent);
        }
        //reload viewers so they get a new export
        EventDispatcher.EventDispatcher.instance.emit('viewer-refresh');
    }
    else if (currentComponent) {
        //there is no old version, so this is a new component, delete it
        projectmodel.ProjectModel.instance.removeComponent(currentComponent);
    }
    else if (baseCompJson) {
        //the current version has been deleted, so add it back
        projectmodel.ProjectModel.instance.addComponent(componentmodel/* ComponentModel */.j.fromJSON(baseCompJson));
    }
    ToastLayer.ToastLayer.hideActivity(activityId);
    ToastLayer.ToastLayer.showSuccess('Component reset');
}
async function resetFile(project, change, respositoryPath, currentCommitSha) {
    const activityId = 'resetting-file';
    ToastLayer.ToastLayer.showActivity('Resetting file', activityId);
    const fullPath = external_node_path_default().join(project._retainedProjectDirectory, change.path);
    try {
        if (change.status.kind === models_status/* FileStatusKind */.Jb.Untracked) {
            await src.filesystem.removeFile(fullPath);
        }
        else if (change.status.kind === models_status/* FileStatusKind */.Jb.Modified || change.status.kind === models_status/* FileStatusKind */.Jb.Deleted) {
            const fileContent = await (0,show/* getBlobContents */.w)(respositoryPath, currentCommitSha, change.path);
            if (!fileContent) {
                throw "Couldn't get previous version of the file";
            }
            await src.filesystem.writeFile(fullPath, fileContent);
        }
        else {
            throw `No support for resetting file status ${change.status.kind} yet`;
        }
        ToastLayer.ToastLayer.hideActivity(activityId);
        ToastLayer.ToastLayer.showSuccess('File reset');
    }
    catch (e) {
        ToastLayer.ToastLayer.hideActivity(activityId);
        ToastLayer.ToastLayer.showError('Failed to delete file. ' + e.toString());
    }
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/LocalChangesDiff.tsx








function LocalChangesDiff() {
    const { fetch, localDiff, localFiles, repositoryPath } = useVersionControlContext();
    const [ResetSingleDialog, confirmSingleReset] = useSimpleConfirmationDialog({
        title: 'Confirm Reset Component',
        confirmButtonLabel: 'Yes, reset',
        isDangerousAction: true
    });
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(ResetSingleDialog, null),
        external_react_default().createElement(DiffList, { componentDiffTitle: `Showing uncommited changes`, diff: localDiff, fileChanges: localFiles, actions: {
                component: {
                    icon: common_Icon/* IconName */.$M.Reset,
                    onClick: (change) => {
                        confirmSingleReset(`Are you sure you want to reset your changes to: <b>${change.component.name}</b>`)
                            .then(() => {
                            resetComponent(localDiff.baseProject, change.component.name);
                            fetch.fetchLocal();
                        })
                            .catch(() => { });
                    }
                },
                file: {
                    icon: common_Icon/* IconName */.$M.Reset,
                    onClick: (change) => {
                        confirmSingleReset(`Are you sure you want to reset your changes to: <b>${change.path}</b>`)
                            .then(async () => {
                            await resetFile(projectmodel.ProjectModel.instance, change, repositoryPath, fetch.currentCommitSha);
                            fetch.fetchLocal();
                        })
                            .catch(() => { });
                    }
                },
                setting: {
                    icon: common_Icon/* IconName */.$M.Reset,
                    onClick: (change) => {
                        confirmSingleReset(`Are you sure you want to reset your changes to: <b>${getSettingDisplayName(change.property.name)}</b>`)
                            .then(() => {
                            projectmodel.ProjectModel.instance.setSetting(change.property.name, change.property.oldValue);
                        })
                            .catch(() => { });
                    }
                },
                textStyle: {
                    icon: common_Icon/* IconName */.$M.Reset,
                    onClick: (change) => {
                        confirmSingleReset(`Are you sure you want to reset your changes to: <b>${change.property.name}</b>`)
                            .then(() => updateStyle('text', change))
                            .catch(() => { });
                    }
                },
                colorStyle: {
                    icon: common_Icon/* IconName */.$M.Reset,
                    onClick: (change) => {
                        confirmSingleReset(`Are you sure you want to reset your changes to: <b>${change.property.name}</b>`)
                            .then(() => updateStyle('colors', change))
                            .catch(() => { });
                    }
                },
                cloudservice: {
                    icon: common_Icon/* IconName */.$M.Reset,
                    onClick: (change) => {
                        confirmSingleReset(`Are you sure you want to reset your changes to the active cloud services?`)
                            .then(() => {
                            const cloudservices = change.property.oldValue || {
                                instanceId: undefined,
                                endpoint: undefined,
                                appId: undefined
                            };
                            projectmodel.ProjectModel.instance.setMetaData('cloudservices', cloudservices);
                            projectmodel.ProjectModel.instance.notifyListeners('cloudServicesChanged');
                        })
                            .catch(() => { });
                    }
                }
            } })));
}
function updateStyle(styleType, change) {
    const stylesModel = new StylesModel();
    console.log(styleType, change);
    if (!change.property.oldValue) {
        stylesModel.deleteStyle(styleType, change.property.name);
    }
    else {
        stylesModel.setStyle(styleType, change.property.name, change.property.oldValue);
    }
    stylesModel.dispose();
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/panels/VersionControlPanel/components/GitStashCard/GitStashCard.module.scss
var GitStashCard_module = __webpack_require__(36560);
;// ./src/editor/src/views/panels/VersionControlPanel/components/GitStashCard/GitStashCard.module.scss

      
      
      
      
      
      
      
      
      

var GitStashCard_module_options = {};

GitStashCard_module_options.styleTagTransform = (styleTagTransform_default());
GitStashCard_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      GitStashCard_module_options.insert = insertBySelector_default().bind(null, "head");
    
GitStashCard_module_options.domAPI = (styleDomAPI_default());
GitStashCard_module_options.insertStyleElement = (insertStyleElement_default());

var GitStashCard_module_update = injectStylesIntoStyleTag_default()(GitStashCard_module/* default */.A, GitStashCard_module_options);




       /* harmony default export */ const GitStashCard_GitStashCard_module = (GitStashCard_module/* default */.A && GitStashCard_module/* default */.A.locals ? GitStashCard_module/* default */.A.locals : undefined);

;// ./src/editor/src/utils/dateUtils.ts
function getMonthNameFromNumber(number) {
    switch (number) {
        case 0:
            return 'January';
        case 1:
            return 'February';
        case 2:
            return 'March';
        case 3:
            return 'April';
        case 4:
            return 'May';
        case 5:
            return 'June';
        case 6:
            return 'July';
        case 7:
            return 'August';
        case 8:
            return 'September';
        case 9:
            return 'October';
        case 10:
            return 'November';
        case 11:
            return 'December';
        default:
            return null;
    }
}
function isSameDay(dateA, dateB) {
    return (dateA.getFullYear() === dateB.getFullYear() &&
        dateA.getMonth() === dateB.getMonth() &&
        dateA.getDate() === dateB.getDate());
}
function addLeadingZero(number) {
    if (number > -1 && number < 10)
        return '0' + number;
    return number;
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/StashChangesDiff.tsx






function StashChangesDiff({ stash }) {
    const [diff, setDiff] = (0,external_react_.useState)(null);
    const [commitFiles, setCommitFiles] = (0,external_react_.useState)(null);
    const { repositoryPath, fetch } = useVersionControlContext();
    (0,external_react_.useEffect)(() => {
        //This component might re-render with a new diff, so reset diff to show loading indicator again
        setDiff(null);
        setCommitFiles(null);
        if (!fetch.currentCommitSha) {
            return;
        }
        async function doDiff() {
            async function getProjectFile(snapshot) {
                const projectContent = JSON.parse(await snapshot.getFileAsString('project.json'));
                (0,applypatches.applyPatches)(projectContent);
                return projectContent;
            }
            const commit = await (0,logs/* getCommit */.kO)(repositoryPath, fetch.currentCommitSha);
            const files = await stash.getFiles();
            setCommitFiles(files);
            const [thisProject, otherProject] = await Promise.all([getProjectFile(commit), getProjectFile(stash)]);
            const diff = diffProject(otherProject, thisProject);
            setDiff(diff);
        }
        doDiff();
    }, [stash]);
    return (external_react_default().createElement(DiffList, { diff: diff, fileChanges: commitFiles, componentDiffTitle: `Changes made in stash #${stash.sha.slice(0, 7)} by ${stash.author.name}` }));
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/GitStashCard/GitStashCard.tsx













function GitStashCard({ stash, onDeleteClick, onApplyClick }) {
    const { git } = useVersionControlContext();
    const rootRef = (0,external_react_.useRef)(null);
    const [isDrawerOpen, setIsDrawerOpen] = (0,external_react_.useState)(false);
    const [commit, setCommit] = (0,external_react_.useState)(null);
    let isDrawerCollapsed = !isDrawerOpen;
    (0,external_react_.useEffect)(() => {
        var _a;
        if (!(rootRef === null || rootRef === void 0 ? void 0 : rootRef.current))
            return;
        (_a = rootRef.current) === null || _a === void 0 ? void 0 : _a.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }, [rootRef === null || rootRef === void 0 ? void 0 : rootRef.current]);
    (0,external_react_.useEffect)(() => {
        const getCommit = async () => {
            setCommit(await git.getCommitFromId(stash.sha));
        };
        if (!isDrawerCollapsed && !commit) {
            getCommit();
        }
    }, [stash.sha, isDrawerCollapsed, commit]);
    const date = stash.author.date;
    const dateString = isSameDay(date, new Date())
        ? `today at ${addLeadingZero(date.getHours())}:${addLeadingZero(date.getMinutes())}`
        : `${date.getDate()} ${getMonthNameFromNumber(date.getMonth())} ${date.getFullYear()}`;
    return (external_react_default().createElement("div", { ref: rootRef, className: external_classnames_default()([GitStashCard_GitStashCard_module['Root'], !isDrawerCollapsed && GitStashCard_GitStashCard_module['is-open']]) },
        external_react_default().createElement("div", { className: external_classnames_default()(GitStashCard_GitStashCard_module['Inner']), onClick: () => setIsDrawerOpen(!isDrawerOpen) },
            external_react_default().createElement(Stack/* VStack */.Tk, { UNSAFE_style: { flexGrow: 1 } },
                external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { justifyContent: 'space-between' } },
                    external_react_default().createElement(Stack/* HStack */.zt, null,
                        external_react_default().createElement(common_Icon/* Icon */.In, { size: common_Icon/* IconSize */.lK.Tiny, icon: common_Icon/* IconName */.$M.StructureCircle }),
                        external_react_default().createElement(typography_Text/* Text */.EY, null, stash.branchName)),
                    external_react_default().createElement(typography_Text/* Text */.EY, null, dateString))),
            external_react_default().createElement("div", { className: GitStashCard_GitStashCard_module['ToggleContainer'] },
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.CaretDown, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, state: isDrawerOpen ? inputs_IconButton/* IconButtonState */.Df.Rotated : null }))),
        external_react_default().createElement(Collapsible/* Collapsible */.N, { isCollapsed: isDrawerCollapsed },
            external_react_default().createElement("div", { className: external_classnames_default()(GitStashCard_GitStashCard_module['Drawer']) },
                Boolean(commit) && external_react_default().createElement(StashChangesDiff, { stash: stash }),
                external_react_default().createElement(Section/* Section */.w, { hasGutter: true, hasVisibleOverflow: true },
                    external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, stash.message),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, label: "Apply stash", hasBottomSpacing: true, isGrowing: true, onClick: onApplyClick }),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.MutedOnLowBg, label: "Delete stash", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, isGrowing: true, onClick: onDeleteClick }))))));
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/GitStashCard/index.ts


;// ./src/editor/src/views/panels/VersionControlPanel/components/Stashes.tsx










function Stashes() {
    const { fetch, repositoryPath, localChangesCount } = useVersionControlContext();
    const stashes = fetch.stashes;
    const [ApplyStashDialog, confirmApplyStash] = useConfirmationDialog({
        title: 'Confirm Stash',
        message: 'Do you want to apply this stash?',
        confirmButtonLabel: 'Yes, apply',
        isDangerousAction: true
    });
    const [DeleteStashDialog, confirmDeleteStash] = useConfirmationDialog({
        title: 'Confirm Stash',
        message: 'Do you want to delete this stash?',
        confirmButtonLabel: 'Yes, delete',
        isDangerousAction: true
    });
    const [CantCreateStashDialog, showCantCreateStashDialog] = useConfirmationDialog({
        isCancelButtonHidden: true,
        title: "Can't do that yet",
        message: "Can't apply stash with local changes. Commit your changes before applying.",
        confirmButtonLabel: 'OK',
        isDangerousAction: true
    });
    async function applyStash(stash) {
        if (localChangesCount > 0) {
            showCantCreateStashDialog();
            return;
        }
        confirmApplyStash()
            .then(async () => {
            projectmodel.ProjectModel.setSaveOnModelChange(false);
            //localChangesCount is zero but we might have some minor metadata changes, reset them before applying stash
            await (0,core_reset/* reset */.c)(repositoryPath, 0 /* GitResetMode.Hard */, 'HEAD');
            try {
                await (0,core_stash/* popStashEntry */.$S)(repositoryPath, stash.name);
                EventDispatcher.EventDispatcher.instance.notifyListeners('projectChangedOnDisk'); //note: automatically enables project saving again when the project has been reloaded
                await fetch.fetchLocal();
                ToastLayer.ToastLayer.showSuccess('Stash applied');
            }
            catch (e) {
                ToastLayer.ToastLayer.showError(e.toString());
            }
            projectmodel.ProjectModel.setSaveOnModelChange(true);
        })
            .catch((_) => { });
    }
    async function deleteStash(stash) {
        confirmDeleteStash()
            .then(async () => {
            try {
                await (0,core_stash/* dropStashEntry */.DE)(repositoryPath, stash.name);
                fetch.fetchLocal();
                ToastLayer.ToastLayer.showSuccess('Stash deleted');
            }
            catch (e) {
                ToastLayer.ToastLayer.showError(e.toString());
            }
        })
            .catch((_) => {
            /* user canceled */
        });
    }
    if (stashes.length === 0) {
        return null;
    }
    return (external_react_default().createElement(Section/* Section */.w, { title: "Stashes", variant: Section/* SectionVariant */.$.Panel, UNSAFE_style: { flexGrow: 1 } },
        external_react_default().createElement(CantCreateStashDialog, null),
        external_react_default().createElement(ApplyStashDialog, null),
        external_react_default().createElement(DeleteStashDialog, null),
        stashes.map((stash) => (external_react_default().createElement(GitStashCard, { key: stash.sha, stash: stash, onApplyClick: () => applyStash(stash), onDeleteClick: () => deleteStash(stash) })))));
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/LocalChanges.tsx


















function LocalChanges({ hasConflictsInProject }) {
    const { git, repositoryPath, setActiveTabId, setSelectedCommit, setIsPerformingAction, localChangesCount, localDiff, fetch } = useVersionControlContext();
    const { gitStatus, branches, currentBranch, fetchLocal } = fetch;
    const canInteract = gitStatus.kind !== 'fetch';
    const hasChanges = localChangesCount > 0;
    const [commitMessage, setCommitMessage] = (0,external_react_.useState)('');
    const [ResetDialog, confirmReset] = useConfirmationDialog({
        title: 'Confirm Reset',
        message: 'Are you sure you want to reset all your local changes? This action can not be undone.',
        confirmButtonLabel: 'Yes, reset',
        isDangerousAction: true
    });
    const [StashDialog, showStashDialog] = useConfirmationDialog({
        title: 'Confirm Stash',
        message: 'Do you want to stash your local changes?',
        confirmButtonLabel: 'Yes, stash'
    });
    const canCommit = canInteract && hasChanges;
    async function onCommit() {
        setIsPerformingAction(true);
        ToastLayer.ToastLayer.showActivity('Commiting local changes', 'performing-action');
        try {
            // Create the commit
            const commitSha = await git.commit(commitMessage);
            setCommitMessage('');
            // Update local status
            await fetchLocal();
            // Select the history tab
            setActiveTabId('history');
            // Select the new commit
            if (commitSha) {
                setSelectedCommit(commitSha);
            }
        }
        catch (error) {
            if (error instanceof noodl_git_src/* GitActionError */.v7) {
                ToastLayer.ToastLayer.showError(error.message);
            }
            else {
                console.error(error);
                ToastLayer.ToastLayer.showError('Failed to commit. Error: ' + error);
            }
        }
        ToastLayer.ToastLayer.hideActivity('performing-action');
        setIsPerformingAction(false);
    }
    function onResetAllChanges() {
        confirmReset().then(async () => {
            setIsPerformingAction(true);
            ToastLayer.ToastLayer.showActivity('Resetting local changes', 'performing-action');
            try {
                projectmodel.ProjectModel.setSaveOnModelChange(false);
                // TODO: remoteHasBranch ?
                const remoteHasBranch = branches.some((b) => b.name === (currentBranch === null || currentBranch === void 0 ? void 0 : currentBranch.name) && !!b.remoteName);
                if (remoteHasBranch) {
                    await git.resetToMergeBase();
                }
                else {
                    await git.resetToHead();
                }
                // TODO: Require delay?
                await fetchLocal();
                //note: the projectChangedOnDisk listener will enable ProjectModel.setSaveOnModelChange when it's done
                EventDispatcher.EventDispatcher.instance.notifyListeners('projectChangedOnDisk');
                ToastLayer.ToastLayer.showSuccess('Reset done');
            }
            catch (e) {
                projectmodel.ProjectModel.setSaveOnModelChange(true);
                if (e instanceof noodl_git_src/* GitActionError */.v7) {
                    ToastLayer.ToastLayer.showError(e.message);
                }
                else {
                    ToastLayer.ToastLayer.showError('Reset failed. ' + e.toString());
                }
            }
            ToastLayer.ToastLayer.hideActivity('performing-action');
            setIsPerformingAction(false);
        });
    }
    function onStashLocalChanges() {
        showStashDialog()
            .then(async () => {
            projectmodel.ProjectModel.setSaveOnModelChange(false);
            const stashMessage = fetch.createStashMessage();
            await (0,core_stash/* createStashEntry */.OT)(repositoryPath, stashMessage);
            EventDispatcher.EventDispatcher.instance.notifyListeners('projectChangedOnDisk'); //note: automatically enables project saving again when the project has been reloaded
            await fetch.fetchLocal();
        })
            .catch((_) => { });
    }
    return (external_react_default().createElement(Container, { direction: ContainerDirection.Vertical, UNSAFE_style: { height: '100%' } },
        external_react_default().createElement(ResetDialog, null),
        external_react_default().createElement(StashDialog, null),
        external_react_default().createElement(Container, { direction: ContainerDirection.Vertical, hasXSpacing: true, hasYSpacing: true },
            !hasConflictsInProject && (external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement(Label/* Label */.JU, { hasBottomSpacing: true }, "Please write a commit message"),
                external_react_default().createElement(TextArea, { value: commitMessage, onChange: (ev) => setCommitMessage(ev.target.value), placeholder: "Describe your changes", hasBottomSpacing: true }))),
            external_react_default().createElement(Stack/* HStack */.zt, null,
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Commit local changes", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, isDisabled: !canCommit || hasConflictsInProject, isGrowing: true, hasRightSpacing: true, onClick: onCommit }),
                external_react_default().createElement(ContextMenu/* ContextMenu */.t, { size: common_Icon/* IconSize */.lK.Large, menuItems: [
                        {
                            label: 'Stash local changes',
                            onClick: onStashLocalChanges,
                            icon: common_Icon/* IconName */.$M.Stash,
                            isDisabled: !hasChanges || hasConflictsInProject
                        },
                        'divider',
                        {
                            label: 'Delete local changes',
                            onClick: onResetAllChanges,
                            isDangerous: true,
                            icon: common_Icon/* IconName */.$M.Trash,
                            isDisabled: !hasChanges
                        }
                    ] }))),
        external_react_default().createElement(ScrollArea, { UNSAFE_style: { width: '100%', minHeight: 81 } }, hasChanges || !localDiff ? (external_react_default().createElement(LocalChangesDiff, null)) : (external_react_default().createElement(Container, { direction: ContainerDirection.Vertical, hasXSpacing: true, hasYSpacing: true },
            external_react_default().createElement(Label/* Label */.JU, null, "You have no local changes")))),
        external_react_default().createElement(Stashes, null)));
}

;// ./src/editor/src/views/panels/VersionControlPanel/components/MergeConflicts.tsx









function MergeConflicts() {
    return (external_react_default().createElement(Stack/* VStack */.Tk, null,
        external_react_default().createElement(Section/* Section */.w, { hasVisibleOverflow: true, hasGutter: true },
            external_react_default().createElement(Container, null,
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.WarningTriangle, size: common_Icon/* IconSize */.lK.Small }),
                external_react_default().createElement(Box/* Box */.a, null,
                    external_react_default().createElement(Label/* Label */.JU, { hasLeftSpacing: true, variant: typography_Text/* TextType */.M2.Shy }, "Warning"),
                    external_react_default().createElement(Label/* Label */.JU, { hasLeftSpacing: true }, "Merge conflict")))),
        external_react_default().createElement(Section/* Section */.w, { hasVisibleOverflow: true, hasGutter: true },
            external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, "You and your collaborators have made changes to the same nodes and you need to resolve them"),
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Open warnings", isGrowing: true, size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, onClick: () => {
                    document.getElementById('editortopbar-warning-button').click();
                } }))));
}

;// ./src/editor/src/views/panels/VersionControlPanel/VersionControlPanel.tsx
































var VersionControlPanel_ViewState;
(function (ViewState) {
    ViewState[ViewState["Default"] = 0] = "Default";
    ViewState[ViewState["Branches"] = 1] = "Branches";
    ViewState[ViewState["BranchMerge"] = 2] = "BranchMerge";
})(VersionControlPanel_ViewState || (VersionControlPanel_ViewState = {}));
function convertGitRemoteUrlToRepoUrl(gitRemoteUrl) {
    // Remove the .git extension if present
    gitRemoteUrl = gitRemoteUrl.replace(/\.git$/, '');
    // Extract the repository name and owner from the URL
    const regex = /^(?:https?:\/\/)?github\.com\/([^/]+)\/([^/]+)$/;
    const match = gitRemoteUrl.match(regex);
    if (match) {
        const owner = match[1];
        const repo = match[2];
        // Construct the GitHub repository URL
        const repoUrl = `https://github.com/${owner}/${repo}`;
        return repoUrl;
    }
    else {
        throw new Error('Invalid GitHub Git remote URL');
    }
}
function BaseVersionControlPanel() {
    const { git, activeTabId, setActiveTabId, localChangesCount, branchStatus, fetch, updateLocalDiff } = useVersionControlContext();
    const historyCount = fetch.localCommitCount + fetch.remoteCommitCount;
    const isActivePanel = useIsActivePanel(VersionControlPanel_ID);
    const shouldUpdateDiff = (0,external_react_.useRef)(true);
    const settingsButtonRef = (0,external_react_.useRef)(null);
    (0,external_react_.useEffect)(() => {
        const eventGroup = {};
        if (!isActivePanel) {
            //if we're switching to another panel make sure we close any open diff documents
            if (AppRegistry.instance.CurrentDocumentId === ComponentDiffDocumentProvider.ID) {
                AppRegistry.instance.openDocument(EditorDocumentProvider.ID);
            }
            //check if project is saved while we're inactive, and if so, diff next time we're active
            EventDispatcher.EventDispatcher.instance.on(['ProjectModel.projectSavedToDisk', 'ProjectModel.instanceHasChanged'], () => {
                shouldUpdateDiff.current = true;
            }, eventGroup);
        }
        else {
            //we're now the active panel, fetch local changes and update diff if needed
            fetch.fetchLocal().then(() => {
                if (shouldUpdateDiff.current === true) {
                    shouldUpdateDiff.current = false;
                    updateLocalDiff();
                }
            });
            //if project is saved and we're active, update the diff
            EventDispatcher.EventDispatcher.instance.on(['ProjectModel.projectSavedToDisk', 'ProjectModel.instanceHasChanged'], () => {
                updateLocalDiff();
            }, eventGroup);
        }
        return () => {
            EventDispatcher.EventDispatcher.instance.off(eventGroup);
        };
    }, [isActivePanel]);
    const hasConflictsInProject = useHasConflictsInProject();
    // NOTE: The keep alive stuff here is a little confusing,
    //       but are designed in a way to be performant.
    let viewState = VersionControlPanel_ViewState.Default;
    if (branchStatus) {
        switch (branchStatus.kind) {
            case 'merge':
                viewState = VersionControlPanel_ViewState.BranchMerge;
                break;
        }
    }
    function openGitSettingsPopout() {
        const popoutDiv = document.createElement('div');
        const root = (0,client.createRoot)(popoutDiv);
        root.render(external_react_default().createElement(GitProviderPopout, { git }));
        //the timeout is needed to solve a bug when the popout us opened from the git status button
        //it causes timing issues between native events and react where the popout is instantly closed
        setTimeout(() => {
            popuplayer_default().instance.showPopout({
                content: { el: [popoutDiv] },
                attachTo: $(settingsButtonRef.current),
                position: 'right',
                disableDynamicPositioning: true,
                onClose: () => {
                    root.unmount();
                    fetch.fetchRemote();
                }
            });
        }, 1);
    }
    return (external_react_default().createElement(BasePanel, { isFill: true, title: "Version Control", headerSlot: external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: 1 },
            git.Provider === 'github' && (external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.ExternalLink, size: common_Icon/* IconSize */.lK.Small, variant: inputs_IconButton/* IconButtonVariant */.nl.OpaqueOnHover, onClick: () => {
                    const githubLink = convertGitRemoteUrlToRepoUrl(git.OriginUrl);
                    src.platform.openExternal(githubLink);
                    // TODO: Toast
                } })),
            git.Provider && (external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { ref: settingsButtonRef, icon: common_Icon/* IconName */.$M.Setting, size: common_Icon/* IconSize */.lK.Small, variant: inputs_IconButton/* IconButtonVariant */.nl.OpaqueOnHover, onClick: (ev) => {
                    ev.stopPropagation();
                    openGitSettingsPopout();
                } }))) },
        external_react_default().createElement(Container, { direction: ContainerDirection.Vertical, UNSAFE_style: { height: '100%', isolation: 'isolate' } },
            hasConflictsInProject ? (external_react_default().createElement(MergeConflicts, null)) : (external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement(GitStatusButton, { openGitSettingsPopout: openGitSettingsPopout }),
                external_react_default().createElement(BranchStatusButton, null),
                viewState === VersionControlPanel_ViewState.BranchMerge && external_react_default().createElement(BranchMerge, null))),
            viewState !== VersionControlPanel_ViewState.BranchMerge && (external_react_default().createElement(Tabs/* Tabs */.t, { variant: Tabs/* TabsVariant */._.Sidebar, keepTabsAlive: true, activeTab: activeTabId, onChange: (activeTab) => setActiveTabId(activeTab), tabs: [
                    {
                        id: 'changes',
                        label: localChangesCount ? `Local Changes (${localChangesCount})` : 'Local Changes',
                        content: external_react_default().createElement(LocalChanges, { hasConflictsInProject: hasConflictsInProject })
                    },
                    {
                        id: 'history',
                        label: historyCount > 0 ? `History (${historyCount})` : 'History',
                        content: external_react_default().createElement(History, null)
                    }
                ] })))));
}
function VersionControlPanel() {
    const [git, setGit] = (0,external_react_.useState)(null);
    const [state, setState] = (0,external_react_.useState)('loading');
    async function createGit() {
        const gitClient = new noodl_git_src/* Git */.TU(projectmerger.mergeProject);
        await gitClient.openRepository(projectmodel.ProjectModel.instance._retainedProjectDirectory);
        setGit(gitClient);
    }
    (0,external_react_.useEffect)(() => {
        LocalProjectsModel/* LocalProjectsModel */.h.instance
            .isGitProject(projectmodel.ProjectModel.instance)
            .then(async (isGitProject) => {
            if (isGitProject) {
                await createGit();
                setState('loaded');
            }
            else {
                setState('not-git');
            }
        });
    }, []);
    async function setupGit() {
        const gitClient = new noodl_git_src/* Git */.TU(projectmerger.mergeProject);
        await gitClient.initNewRepo(projectmodel.ProjectModel.instance._retainedProjectDirectory);
        await gitClient.commit('Initial commit');
        setGit(gitClient);
    }
    if (git === null && state === 'not-git') {
        return (external_react_default().createElement(BasePanel, { isFill: true, title: "Version Control" },
            external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasYSpacing: true },
                external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, "This project is missing a git setup."),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Initialize Version Control (git)", isGrowing: true, onClick: setupGit }))));
    }
    // TODO: Loading state? Should be really quick though
    if (git === null) {
        return null;
    }
    return (external_react_default().createElement(VersionControlProvider, { git: git },
        external_react_default().createElement(BaseVersionControlPanel, null)));
}
function useHasConflictsInProject() {
    const [hasConflicts, setHasConflicts] = (0,external_react_.useState)(false);
    // Listen for changes to conflicts
    (0,external_react_.useEffect)(() => {
        const checkForWarnings = () => {
            setHasConflicts(warningsmodel/* WarningsModel */.l.instance.getTotalNumberOfWarningsMatching((_key, _ref, warning) => warning.warning.type === 'conflict' || warning.warning.type === 'conflict-source-code') > 0);
        };
        const eventGroup = {};
        warningsmodel/* WarningsModel */.l.instance.on('warningsChanged', checkForWarnings, eventGroup);
        checkForWarnings();
        return () => {
            warningsmodel/* WarningsModel */.l.instance.off(eventGroup);
        };
    }, []);
    return hasConflicts;
}

;// ./src/editor/src/router.setup.ts

























// import { TopologyMapPanel } from './views/panels/TopologyMapPanel'; // Disabled - shelved feature




function installSidePanel({ isLesson }) {
    const appRegistry = AppRegistry.instance;
    models_sidebar/* SidebarModel */.s.instance.register({
        transient: true,
        id: 'PropertyEditor',
        name: 'Properties',
        // @ts-expect-error
        panel: propertyeditor_PropertyEditor
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        transient: true,
        id: 'PortEditor',
        name: 'Ports',
        panel: ComponentPortsComponent
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        id: 'components',
        name: 'Components',
        order: 1,
        icon: common_Icon/* IconName */.$M.Components,
        onOpen: () => {
            if (appRegistry.CurrentDocumentId !== EditorDocumentProvider.ID) {
                appRegistry.openDocument(EditorDocumentProvider.ID);
            }
        },
        panelProps: {
            // This is a temporary solution so we can keep the state of open folder etc
            options: {
                showSheetList: true,
                hideSheets: ['__cloud__']
            }
        },
        panel: componentspanel_ComponentsPanel
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        id: 'search',
        name: 'Search',
        fineType: new Keybinding(KeyCode.KeyMod.CtrlCmd, KeyCode.KeyCode.KEY_F).label,
        order: 2,
        icon: common_Icon/* IconName */.$M.Search,
        panel: search_panel_SearchPanel
    });
    // Topology Map Panel - Disabled (shelved for future development)
    // See: dev-docs/tasks/phase-4-canvas-visualisation-views/VIEW-001-topology-map/SHELVED.md
    // SidebarModel.instance.register({
    //   experimental: true,
    //   id: 'topology',
    //   name: 'Topology',
    //   order: 3,
    //   icon: IconName.StructureCircle,
    //   panel: TopologyMapPanel
    // });
    models_sidebar/* SidebarModel */.s.instance.register({
        experimental: true,
        id: 'component-xray',
        name: 'Component X-Ray',
        description: 'Shows comprehensive information about the active component: usage, interface, structure, and dependencies.',
        order: 4,
        icon: common_Icon/* IconName */.$M.SearchGrid,
        panel: ComponentXRayPanel
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        experimental: true,
        id: 'data-lineage',
        name: 'Data Lineage',
        description: 'Traces where data values come from (upstream sources) and where they go to (downstream destinations), crossing component boundaries.',
        order: 4.5,
        icon: common_Icon/* IconName */.$M.Link,
        panel: DataLineagePanel
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        id: VersionControlPanel_ID,
        name: 'Version control',
        order: 5,
        icon: common_Icon/* IconName */.$M.StructureCircle,
        panel: VersionControlPanel
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        id: 'github',
        name: 'GitHub',
        order: 5.5,
        icon: common_Icon/* IconName */.$M.Link,
        panel: GitHubPanel
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        id: 'cloudservice',
        name: 'Cloud Services',
        isDisabled: isLesson === true,
        order: 6,
        icon: common_Icon/* IconName */.$M.CloudData,
        panel: CloudServicePanel
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        id: 'cloud-functions',
        name: 'Cloud Functions',
        isDisabled: isLesson === true,
        order: 7,
        icon: common_Icon/* IconName */.$M.CloudFunction,
        panel: CloudFunctionsPanel
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        id: 'backend-services',
        name: 'Backend Services',
        isDisabled: isLesson === true,
        order: 8,
        icon: common_Icon/* IconName */.$M.RestApi,
        panel: BackendServicesPanel
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        id: 'app-setup',
        name: 'App Setup',
        isDisabled: isLesson === true,
        order: 8.5,
        icon: common_Icon/* IconName */.$M.Sliders,
        panel: AppSetupPanel
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        id: 'settings',
        name: 'Project settings',
        order: 9,
        icon: common_Icon/* IconName */.$M.Setting,
        panel: ProjectSettingsPanel
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        experimental: true,
        id: 'trigger-chain-debugger',
        name: 'Trigger Chain Debugger',
        description: 'Records and visualizes chains of events triggered from user interactions in the preview.',
        order: 10,
        icon: common_Icon/* IconName */.$M.Play,
        panel: TriggerChainDebuggerPanel
    });
    if ((config_default()).devMode) {
        models_sidebar/* SidebarModel */.s.instance.register({
            experimental: true,
            id: 'file-explorer',
            name: 'File Explorer',
            order: 19,
            icon: common_Icon/* IconName */.$M.FolderOpen,
            panel: FileExplorerPanel
        });
        models_sidebar/* SidebarModel */.s.instance.register({
            experimental: true,
            id: 'design-tokens',
            name: 'Design Tokens',
            order: 20,
            icon: common_Icon/* IconName */.$M.Palette,
            panel: DesignTokenPanel
        });
        models_sidebar/* SidebarModel */.s.instance.register({
            experimental: true,
            id: 'undo-queue',
            name: 'Undo Queue',
            order: 21,
            icon: common_Icon/* IconName */.$M.Reset,
            panel: UndoQueuePanel
        });
    }
    models_sidebar/* SidebarModel */.s.instance.register({
        experimental: true,
        id: NodeReferencesPanel_ID,
        name: 'Node References',
        description: 'Node References Panel is showing how many times each core node and component is used.',
        order: 23,
        icon: common_Icon/* IconName */.$M.Component,
        panel: NodeReferencesPanel
    });
    models_sidebar/* SidebarModel */.s.instance.register({
        id: 'editor-settings',
        name: 'Editor settings',
        order: 1,
        placement: 'bottom',
        icon: common_Icon/* IconName */.$M.SlidersHorizontal,
        panel: EditorSettingsPanel
    });
}
function installDocuments() {
    const appRegistry = AppRegistry.instance;
    // Register EditorDocumentProvider
    appRegistry.registerDocumentProvider(EditorDocumentProvider.ID, new EditorDocumentProvider());
    appRegistry.openDocument(EditorDocumentProvider.ID);
    appRegistry.registerDocumentProvider(ComponentDiffDocumentProvider.ID, new ComponentDiffDocumentProvider());
    if (false) // removed by dead control flow
{}
}

// EXTERNAL MODULE: ./src/editor/src/views/importpopup.js
var importpopup = __webpack_require__(52501);
var importpopup_default = /*#__PURE__*/__webpack_require__.n(importpopup);
// EXTERNAL MODULE: ./src/editor/src/views/lessons/lessonevalconditions.js
var lessonevalconditions = __webpack_require__(79624);
var lessonevalconditions_default = /*#__PURE__*/__webpack_require__.n(lessonevalconditions);
// EXTERNAL MODULE: ./src/editor/src/views/lessons/LessonLayerView.jsx
var LessonLayerView = __webpack_require__(88575);
var LessonLayerView_default = /*#__PURE__*/__webpack_require__.n(LessonLayerView);
;// ./src/editor/src/views/lessonlayer2.ts









class LessonLayer {
    constructor() {
        this.root = null;
        this.keyboardCommands = [
            {
                handler: () => this.reload(),
                keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyMod.Shift | KeyCode.KeyCode.KEY_R
            },
            {
                handler: () => this.restart(),
                keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyMod.Shift | KeyCode.KeyCode.KEY_T
            },
            {
                handler: () => this.model.next(),
                keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyMod.Shift | KeyCode.KeyCode.KEY_N
            }
        ];
        keyboardhandler["default"].instance.registerCommands(this.keyboardCommands);
    }
    startLesson(model) {
        if (this.model) {
            this.dispose();
        }
        this.model = model;
        this.model.on('instructionsChanged', () => {
            this.refresh();
        }, this);
        this.model.on('instructionsFetched', () => {
            this.loadSteps();
            this.refresh();
        }, this);
        EventDispatcher.EventDispatcher.instance.on('activeComponentChanged', () => {
            this.refresh();
        }, this);
        EventDispatcher.EventDispatcher.instance.on('viewer-navigated', () => {
            this.refresh();
        }, this);
        model.start();
        // When the model changes refresh the lesson popup
        EventDispatcher.EventDispatcher.instance.on('Model.*', () => {
            clearTimeout(this.refreshTimeout);
            this.refreshTimeout = setTimeout(() => {
                this.refresh();
            }, 1);
        }, this);
        return this._render();
    }
    _renderReact() {
        const props = {
            steps: this.steps,
            currentStepIndex: this.model.index,
            onMoveToNextStep: () => {
                this.model.next();
            }
        };
        if (!this.root) {
            this.root = (0,client.createRoot)(this.div);
        }
        this.root.render(external_react_default().createElement((LessonLayerView_default()), props));
    }
    _render() {
        if (this.root) {
            this.root.unmount();
            this.root = null;
        }
        this.div = document.createElement('div');
        this.div.className = 'lessonlayerview';
        this._renderReact();
        this.el = $(this.div);
        return this.el;
    }
    refresh() {
        if (!this.steps) {
            //still waiting for the model to fetch the steps
            return;
        }
        // if (this.nextButton.parentElement) {
        //   this.nextButton.parentElement.removeChild(this.nextButton);
        // }
        this.steps.forEach((step, stepIndex) => {
            if (stepIndex < this.model.index) {
                step.isComplete = true;
                const nextButton = step.popupContent.querySelector('.popup-button-container');
                if (nextButton)
                    nextButton.parentElement.removeChild(nextButton);
                step.hasNextButton = false;
            }
            else if (stepIndex === this.model.index) {
                if (step.conditions && step.conditions.length) {
                    try {
                        step.isComplete = lessonevalconditions_default()(step.conditions);
                    }
                    catch (e) {
                        console.error('error in lesson condition', step.conditions, e.message);
                        step.error = `Step ${stepIndex}: ${e.message}. Invalid condition: ${JSON.stringify(step.conditions)}.`;
                    }
                }
                else {
                    step.isComplete = false;
                    //add the next or done button if this isn't an popup only step, since they already have one added
                    if (step.itemContent && step.popupContent) {
                        // if (stepIndex < this.steps.length - 1) {
                        //   step.popupContent.appendChild(this.nextButton);
                        //   step.hasNextButton = true;
                        // }
                    }
                }
            }
            else {
                step.isComplete = false;
            }
        });
        const currentStep = this.steps[this.model.index];
        if (currentStep && currentStep.conditions && currentStep.isComplete) {
            //jump to the next step if all conditions are completed.
            //This will tigger the "instrcuctionsChanged" event on the model wich re-renders the lessons
            this.model.next();
        }
        else {
            this.div && this._renderReact();
        }
    }
    _onNextClick() {
        popuplayer_default().instance.hideModal();
        popuplayer_default().instance.hidePopouts(true);
        this.model.next();
    }
    loadSteps() {
        const steps = this.model.lessons.map((instructionsHTML, stepIndex) => {
            const stepElement = document.createElement('div');
            stepElement.innerHTML = instructionsHTML;
            const itemContent = stepElement.querySelector('div[data-template="item"]');
            const popupContent = stepElement.querySelector('div[data-template="popup"]');
            //look for buttons in the lesson that can trigger special actions
            const buttons = stepElement.querySelectorAll('[data-click]');
            for (const button of Array.from(buttons)) {
                const clickAction = button.getAttribute('data-click');
                if (clickAction === 'exitEditor') {
                    button.parentElement.removeChild(button);
                }
            }
            const step = {
                hasNextButton: false
            };
            if (itemContent) {
                this._loadImages(itemContent);
                this._loadVideos(itemContent);
                let conditions = stepElement.firstElementChild.getAttribute('data-conditions');
                if (conditions) {
                    try {
                        conditions = JSON.parse(conditions);
                    }
                    catch (e) {
                        console.error('error in lesson condition', conditions, e.message);
                        step.error = `Step ${stepIndex}: Invalid condition: ${conditions}. ${e.message}`;
                    }
                }
                step.conditions = conditions && conditions.length ? conditions : undefined;
                if (itemContent.style.width) {
                    step.width = itemContent.style.width;
                    itemContent.style.width = '';
                }
                step.itemContent = itemContent;
                const actions = stepElement.firstElementChild.getAttribute('data-actions');
                if (actions) {
                    try {
                        step.actions = JSON.parse(actions);
                    }
                    catch (e) {
                        console.error('error in lesson actions', actions, e.message);
                        step.error = `Step ${stepIndex}: Invalid actions: ${actions}. ${e.message}`;
                    }
                }
            }
            if (popupContent) {
                // New rendering for 2.8.1 and above is a hot mess
                // It works though. Feel free to hit me in the head
                // if you are ever forced to work on this code.
                //
                // xoxo, Kotte
                const root = popupContent.cloneNode();
                root.innerHTML = '';
                const mediaContainer = document.createElement('div');
                mediaContainer.classList.add('popup-media');
                root.appendChild(mediaContainer);
                const mediaRenderContainer = root.querySelector('.popup-media');
                this._loadImages(popupContent, mediaRenderContainer);
                this._loadVideos(popupContent, mediaRenderContainer);
                const legacyStyleTag = popupContent.querySelector('style');
                if (legacyStyleTag)
                    popupContent.removeChild(legacyStyleTag);
                const contentWrapper = document.createElement('div');
                contentWrapper.classList.add('popup-content-wrapper');
                const contentContainer = document.createElement('div');
                contentContainer.classList.add('popup-content');
                contentContainer.innerHTML = popupContent.innerHTML;
                popupContent.innerHTML = '';
                const shouldButtonRender = !step.conditions;
                const isLastStep = this.model.lessons.length - 1 === stepIndex;
                // empty content containers still take up space
                if (shouldButtonRender || contentContainer.innerHTML.trim().length) {
                    contentWrapper.prepend(contentContainer);
                    root.prepend(contentWrapper);
                }
                if (shouldButtonRender) {
                    //this is a step with only a popup. Add a next button.
                    const buttonContainer = root.querySelector('.popup-content-wrapper');
                    const buttonToAppend = !isLastStep
                        ? createPopupButton('NEXT', () => {
                            this._onNextClick();
                        })
                        : createPopupButton('EXIT LESSON', () => {
                            App.instance.exitProject();
                        });
                    buttonContainer.appendChild(buttonToAppend);
                    step.hasNextButton = !isLastStep;
                }
                step.popupContent = root;
            }
            return step;
        });
        this.steps = steps.filter((step) => step.itemContent || step.popupContent); //remove any steps with incorrect HTML
    }
    reload() {
        dataurls = {}; // Reload images, reset cache
        this.model.start();
    }
    restart() {
        this.model.index = 0;
        this.model.start();
    }
    dispose() {
        clearTimeout(this.refreshTimeout);
        keyboardhandler["default"].instance.deregisterCommands(this.keyboardCommands);
        this.model.off(this);
        EventDispatcher.EventDispatcher.instance.off(this);
        if (this.root) {
            this.root.unmount();
            this.root = null;
        }
    }
    resize() { }
    _loadImages(el, renderContainer = undefined) {
        const _this = this;
        // Iterate over all images and load the src as a dataurl
        $(el)
            .find('img')
            .each(function () {
            const _el = $(this);
            const url = _el.attr('src');
            loadSrcAsset(_el, _this.model.baseURL + url, 'image/*', renderContainer);
        });
    }
    _loadVideos(el, renderContainer = undefined) {
        const _this = this;
        // Iterate over all images and load the src as a dataurl
        $(el)
            .find('video')
            .each(function () {
            const _el = $(this);
            const url = _el.attr('src');
            //having autoplay here will make the video run in the background, which can cause performance issues, so remove it if it's there
            _el.removeAttr('autoplay');
            //_el.attr('autoplay', '');
            _el.attr('loop', '');
            _el.attr('muted', '');
            loadSrcAsset(_el, _this.model.baseURL + url, 'video/*', renderContainer);
        });
    }
}
//download the asset and show a load indicator while fetching it
let dataurls = {};
function loadSrcAsset(el, url, acceptType, renderContainer) {
    el.addClass('unselectable');
    const _hash = url;
    if (dataurls[_hash]) {
        // This image has been loaded
        el.attr('src', dataurls[_hash]);
        if (renderContainer) {
            renderContainer.append(el[0]);
        }
    }
    else {
        // Request image and show spinner
        el.attr('src', '');
        const spinner = $('<div class="spinner lesson-spinner"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>');
        if (renderContainer) {
            el.replaceWith('');
            renderContainer.appendChild(spinner[0]);
        }
        else {
            el.replaceWith(spinner);
        }
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.setRequestHeader('Accept', acceptType);
        xhr.responseType = 'blob';
        xhr.onload = function (e) {
            const dataurl = window.URL.createObjectURL(this.response);
            dataurls[_hash] = dataurl;
            el.attr('src', dataurl);
            if (renderContainer) {
                const spinners = Array.from(renderContainer.querySelectorAll('.lesson-spinner'));
                spinners.forEach((spinner) => {
                    renderContainer.removeChild(spinner);
                });
                renderContainer.append(el[0]);
            }
            else {
                spinner.replaceWith(el);
            }
        };
        xhr.send();
    }
}
function createPopupButton(label, onClick) {
    const div = document.createElement('div');
    div.style.display = 'flex';
    div.style.justifyContent = 'flex-end';
    div.classList.add('popup-button-container');
    const button = document.createElement('button');
    button.className = 'lesson-next-button';
    button.innerText = label;
    button.onclick = onClick;
    div.appendChild(button);
    return div;
}

// EXTERNAL MODULE: ./src/editor/src/views/NodePicker/NodePicker.hooks.ts + 4 modules
var NodePicker_hooks = __webpack_require__(38943);
;// external "process"
const external_process_namespaceObject = require("process");
;// ../noodl-core-ui/src/components/app/SideNavigation/SideNavigation.context.tsx

const SideNavigationContext = (0,external_react_.createContext)({
    isShowingTooltips: null,
    setIsShowingTooltips: null
});
function SideNavigationContextProvider({ children }) {
    const [isShowingTooltips, setIsShowingTooltips] = (0,external_react_.useState)(false);
    return (external_react_default().createElement(SideNavigationContext.Provider, { value: {
            isShowingTooltips,
            setIsShowingTooltips
        } }, children));
}
function useSideNavigationContext() {
    const context = (0,external_react_.useContext)(SideNavigationContext);
    if (context === undefined) {
        throw new Error('useSideNavigationContext must be a child of SideNavigationContextProvider');
    }
    return context;
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/app/SideNavigation/SideNavigation.module.scss
var SideNavigation_module = __webpack_require__(98096);
;// ../noodl-core-ui/src/components/app/SideNavigation/SideNavigation.module.scss

      
      
      
      
      
      
      
      
      

var SideNavigation_module_options = {};

SideNavigation_module_options.styleTagTransform = (styleTagTransform_default());
SideNavigation_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      SideNavigation_module_options.insert = insertBySelector_default().bind(null, "head");
    
SideNavigation_module_options.domAPI = (styleDomAPI_default());
SideNavigation_module_options.insertStyleElement = (insertStyleElement_default());

var SideNavigation_module_update = injectStylesIntoStyleTag_default()(SideNavigation_module/* default */.A, SideNavigation_module_options);




       /* harmony default export */ const SideNavigation_SideNavigation_module = (SideNavigation_module/* default */.A && SideNavigation_module/* default */.A.locals ? SideNavigation_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/app/SideNavigation/SideNavigation.tsx









function SideNavigationButton({ isActive, icon, label, fineType, notification, isDisabled, testId, onClick, menuItems }) {
    const context = useSideNavigationContext();
    const iconRef = (0,external_react_.useRef)(null);
    const hasMenu = Boolean(menuItems);
    const [isMenuVisible, setIsMenuVisible] = (0,external_react_.useState)(false);
    // NOTE: Commented out extending sidebar labels in case we want to bring them back at some point
    return (external_react_default().createElement("div", { className: SideNavigation_SideNavigation_module['SideNavigationButton'], onClick: () => {
            !isDisabled && onClick && onClick();
            //context.setIsShowingTooltips(false);
        }, "data-test": testId },
        hasMenu && (external_react_default().createElement(MenuDialog.MenuDialog, { items: menuItems, onClose: () => setIsMenuVisible(false), triggerRef: iconRef, isVisible: isMenuVisible })),
        external_react_default().createElement("div", { className: SideNavigation_SideNavigation_module['IconButtonContainer'], ref: iconRef, onClick: () => hasMenu && setIsMenuVisible(true) },
            external_react_default().createElement(Tooltip/* Tooltip */.m, { content: label, fineType: fineType, renderDirection: BaseDialog/* DialogRenderDirection */.K1.Horizontal, showAfterMs: 300 },
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent, state: isActive ? inputs_IconButton/* IconButtonState */.Df.Active : inputs_IconButton/* IconButtonState */.Df.Default, icon: icon, isDisabled: isDisabled })),
            notification && (external_react_default().createElement("div", { className: SideNavigation_SideNavigation_module['NotificationBadge'] }, notification.count > 99 ? '99+' : notification.count)))));
}
function SideNavigation({ toolbar, panel, onExitClick, isExpanded = false }) {
    return (external_react_default().createElement(SideNavigationContextProvider, null,
        external_react_default().createElement("div", { className: external_classnames_default()(SideNavigation_SideNavigation_module['Root'], isExpanded && SideNavigation_SideNavigation_module['Root--expanded']) },
            external_react_default().createElement("div", { className: SideNavigation_SideNavigation_module['Panel'] }, panel),
            external_react_default().createElement("div", { className: SideNavigation_SideNavigation_module['Toolbar'] },
                external_react_default().createElement("div", { className: SideNavigation_SideNavigation_module['Logo'] },
                    external_react_default().createElement(SideNavigationButton, { icon: common_Icon/* IconName */.$M.Logo, label: "Exit project", menuItems: [{ label: 'Exit project', isDangerous: true, onClick: onExitClick }] })),
                toolbar))));
}

;// ../noodl-core-ui/src/components/app/SideNavigation/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/SidePanel/SidePanel.model.scss
var SidePanel_model = __webpack_require__(8636);
;// ./src/editor/src/views/SidePanel/SidePanel.model.scss

      
      
      
      
      
      
      
      
      

var SidePanel_model_options = {};

SidePanel_model_options.styleTagTransform = (styleTagTransform_default());
SidePanel_model_options.setAttributes = (setAttributesWithoutAttributes_default());

      SidePanel_model_options.insert = insertBySelector_default().bind(null, "head");
    
SidePanel_model_options.domAPI = (styleDomAPI_default());
SidePanel_model_options.insertStyleElement = (insertStyleElement_default());

var SidePanel_model_update = injectStylesIntoStyleTag_default()(SidePanel_model/* default */.A, SidePanel_model_options);




       /* harmony default export */ const SidePanel_SidePanel_model = (SidePanel_model/* default */.A && SidePanel_model/* default */.A.locals ? SidePanel_model/* default */.A.locals : undefined);

;// ./src/editor/src/views/SidePanel/SidePanel.tsx










function SidePanel() {
    const [group] = (0,external_react_.useState)({});
    const sidebar = (0,useModel/* useModernModel */.e)(models_sidebar/* SidebarModel */.s.instance, [sidebarmodel/* SidebarModelEvent */.q.itemsChanged]);
    // Get all the visible toolbar icons
    const items = sidebar.getVisibleItems();
    // All the panel data
    const [activeId, setActiveId] = (0,external_react_.useState)(null);
    const [panels, setPanels] = (0,external_react_.useState)({});
    (0,external_react_.useEffect)(() => {
        // ---
        // Add the first panel
        const currentPanelId = models_sidebar/* SidebarModel */.s.instance.ActiveId;
        setPanels((prev) => {
            const component = models_sidebar/* SidebarModel */.s.instance.getPanelComponent(currentPanelId);
            if (component) {
                return {
                    ...prev,
                    [currentPanelId]: external_react_default().createElement(component)
                };
            }
            return prev;
        });
        setActiveId(currentPanelId);
        // ---
        // Listen to when a new panel is opened, also add them if they dont exist.
        models_sidebar/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.activeChanged, (panelId) => {
            const panel = models_sidebar/* SidebarModel */.s.instance.getPanel(panelId);
            // if transient, then always create it again
            if (panel.transient || !panels[panelId]) {
                setPanels((prev) => {
                    // TODO: Clean up this inside SidebarModel, createElement can be done here instead
                    const component = models_sidebar/* SidebarModel */.s.instance.getPanelComponent(panelId);
                    if (component) {
                        return {
                            ...prev,
                            [panelId]: external_react_default().createElement(component)
                        };
                    }
                    return prev;
                });
            }
            setActiveId(panelId);
        }, group);
        // ---
        // Listen for node selection changes to force PropertyEditor recreation
        // This ensures the panel updates when switching between different nodes
        models_sidebar/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.nodeSelected, () => {
            const panelId = 'PropertyEditor';
            setPanels((prev) => {
                const component = models_sidebar/* SidebarModel */.s.instance.getPanelComponent(panelId);
                if (component) {
                    // Force recreation with new node props - MUST return new object for React to detect change
                    return {
                        ...prev,
                        [panelId]: external_react_default().createElement(component)
                    };
                }
                return prev;
            });
        }, group);
        // ---
        // Support Hot reload on all panels
        models_sidebar/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.HotReload, () => {
            (0,external_process_namespaceObject.nextTick)(() => {
                console.log('[hot-reload] Side Panel');
                const currentPanelId = models_sidebar/* SidebarModel */.s.instance.ActiveId;
                const component = models_sidebar/* SidebarModel */.s.instance.getPanelComponent(currentPanelId);
                setPanels({
                    [currentPanelId]: external_react_default().createElement(component)
                });
                setActiveId(currentPanelId);
            });
        });
        return function () {
            models_sidebar/* SidebarModel */.s.instance.off(group);
        };
    }, []);
    function onItemClick(item) {
        sidebar.switch(item.id);
        item.onClick && item.onClick();
    }
    // Check if topology panel is active for expanded view
    const isExpanded = activeId === 'topology';
    return (external_react_default().createElement(SideNavigation, { isExpanded: isExpanded, onExitClick: () => App.instance.exitProject(), toolbar: external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement(Container, { direction: ContainerDirection.Vertical, UNSAFE_style: { flex: '1' } }, items
                .filter((x) => !x.placement || x.placement === 'top')
                .map((item) => (external_react_default().createElement(SideNavigationButton, { key: item.id, isActive: item.id === activeId, icon: item.icon, onClick: () => onItemClick(item), label: item.name, fineType: item.fineType, isDisabled: item.isDisabled, testId: item.id + '-panel' })))),
            external_react_default().createElement(Container, { direction: ContainerDirection.Vertical }, items
                .filter((x) => x.placement === 'bottom')
                .map((item) => (external_react_default().createElement(SideNavigationButton, { key: item.id, isActive: item.id === activeId, icon: item.icon, onClick: () => onItemClick(item), label: item.name, testId: item.id + '-panel' }))))), panel: external_react_default().createElement("div", { style: { height: '100%' } }, Object.entries(panels).map(([id, panel]) => (external_react_default().createElement("div", { key: id, "data-panel-id": id, className: SidePanel_SidePanel_model['PanelItem'], style: {
                display: id === activeId ? 'block' : 'none'
            } },
            external_react_default().createElement(ErrorBoundary, { showTryAgain: true, onTryAgain: () => {
                    // Recreate all the panels, hopefully it will work again
                    setPanels({});
                    (0,external_process_namespaceObject.nextTick)(() => {
                        const currentPanelId = models_sidebar/* SidebarModel */.s.instance.ActiveId;
                        const component = models_sidebar/* SidebarModel */.s.instance.getPanelComponent(currentPanelId);
                        setPanels({
                            [currentPanelId]: external_react_default().createElement(component)
                        });
                        setActiveId(currentPanelId);
                    });
                } }, panel))))) }));
}

;// ./src/editor/src/views/SidePanel/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/app/TitleBar/TitleBar.module.scss
var TitleBar_module = __webpack_require__(10268);
;// ../noodl-core-ui/src/components/app/TitleBar/TitleBar.module.scss

      
      
      
      
      
      
      
      
      

var TitleBar_module_options = {};

TitleBar_module_options.styleTagTransform = (styleTagTransform_default());
TitleBar_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      TitleBar_module_options.insert = insertBySelector_default().bind(null, "head");
    
TitleBar_module_options.domAPI = (styleDomAPI_default());
TitleBar_module_options.insertStyleElement = (insertStyleElement_default());

var TitleBar_module_update = injectStylesIntoStyleTag_default()(TitleBar_module/* default */.A, TitleBar_module_options);




       /* harmony default export */ const TitleBar_TitleBar_module = (TitleBar_module/* default */.A && TitleBar_module/* default */.A.locals ? TitleBar_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/app/TitleBar/TitleBar.tsx





var TitleBarVariant;
(function (TitleBarVariant) {
    TitleBarVariant["Default"] = "default";
    TitleBarVariant["Shallow"] = "shallow";
})(TitleBarVariant || (TitleBarVariant = {}));
var TitleBarState;
(function (TitleBarState) {
    TitleBarState["Default"] = "default";
    TitleBarState["UpdateAvailable"] = "version-available";
    TitleBarState["Updated"] = "version-updated";
})(TitleBarState || (TitleBarState = {}));
function TitleBar({ title, version, state = TitleBarState.Default, variant = TitleBarVariant.Default, onNewVersionAvailableClicked, onNewUpdateAvailableClicked, isWindows, onMinimizeClicked, onMaximizeClicked, onCloseClicked }) {
    return (external_react_default().createElement("div", { className: external_classnames_default()([TitleBar_TitleBar_module['Root'], TitleBar_TitleBar_module[`is-variant-${variant}`]]) },
        external_react_default().createElement("div", { className: external_classnames_default()([TitleBar_TitleBar_module['Title']]) }, title),
        Boolean(variant === TitleBarVariant.Default) && (external_react_default().createElement((external_react_default()).Fragment, null,
            state === TitleBarState.UpdateAvailable && (external_react_default().createElement(TextButton, { label: `New version available`, onClick: onNewVersionAvailableClicked, size: TextButtonSize.Small, variant: FeedbackType/* FeedbackType */.M.Notice, 
                //@ts-ignore
                UNSAFE_style: { WebkitAppRegion: 'no-drag' }, hasLeftSpacing: true, hasRightSpacing: true })),
            state === TitleBarState.Updated && (external_react_default().createElement(TextButton, { label: "New update downloaded", onClick: onNewUpdateAvailableClicked, size: TextButtonSize.Small, variant: FeedbackType/* FeedbackType */.M.Notice, 
                //@ts-ignore
                UNSAFE_style: { WebkitAppRegion: 'no-drag' }, hasLeftSpacing: true, hasRightSpacing: true })),
            Boolean(version) && external_react_default().createElement("div", { className: external_classnames_default()(TitleBar_TitleBar_module['Version']) }, version))),
        Boolean(isWindows) && (external_react_default().createElement("div", { className: external_classnames_default()(TitleBar_TitleBar_module['OSWindows']) },
            Boolean(variant === TitleBarVariant.Default) && (external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement("div", { className: external_classnames_default()([TitleBar_TitleBar_module['OSWindowsIcon'], TitleBar_TitleBar_module['OSWindowsIcon__Minimize']]), onClick: onMinimizeClicked }),
                external_react_default().createElement("div", { className: external_classnames_default()([TitleBar_TitleBar_module['OSWindowsIcon'], TitleBar_TitleBar_module['OSWindowsIcon__Maximize']]), onClick: onMaximizeClicked }))),
            external_react_default().createElement("div", { className: external_classnames_default()([TitleBar_TitleBar_module['OSWindowsIcon'], TitleBar_TitleBar_module['OSWindowsIcon__Close']]), onClick: onCloseClicked })))));
}

;// ../noodl-core-ui/src/components/app/TitleBar/index.ts


;// ./src/editor/src/views/windows/BaseWindow/BaseWindow.tsx








var BaseWindowVariant;
(function (BaseWindowVariant) {
    BaseWindowVariant["Default"] = "default";
    BaseWindowVariant["Shallow"] = "shallow";
})(BaseWindowVariant || (BaseWindowVariant = {}));
function BaseWindow({ title = projectmodel.ProjectModel.instance.name, variant = BaseWindowVariant.Default, children }) {
    const [newVersionAvailable, setNewVersionAvailable] = (0,external_react_.useState)(undefined);
    const [AutoUpdateDialog, autoUpdateConfirmation] = useConfirmationDialog({
        title: 'New auto update available',
        message: 'A new version has been downloaded. Restart the application to apply the updates.',
        confirmButtonLabel: 'Restart',
        cancelButtonLabel: 'Later'
    });
    (0,external_react_.useEffect)(() => {
        const func = () => setNewVersionAvailable(true);
        external_electron_.ipcRenderer.on('showAutoUpdatePopup', func);
        return function () {
            external_electron_.ipcRenderer.off('showAutoUpdatePopup', func);
        };
    }, []);
    function onNewVersionAvailableClicked() {
        autoUpdateConfirmation()
            .then(() => {
            external_electron_.ipcRenderer.send('autoUpdatePopupClosed', true);
        })
            .catch(() => {
            external_electron_.ipcRenderer.send('autoUpdatePopupClosed', false);
        });
    }
    return (external_react_default().createElement("div", { style: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 } },
        external_react_default().createElement(AutoUpdateDialog, null),
        external_react_default().createElement(Stack/* VStack */.Tk, { UNSAFE_style: { height: '100%' } },
            external_react_default().createElement(TitleBar, { title: title, variant: variant === BaseWindowVariant.Shallow ? TitleBarVariant.Shallow : TitleBarVariant.Default, version: src.platform.getVersionWithTag(), state: newVersionAvailable ? TitleBarState.UpdateAvailable : TitleBarState.Default, isWindows: ['win32', 'linux'].includes(process.platform), onMinimizeClicked: () => App.instance.minimize(), onMaximizeClicked: () => App.instance.maximize(), onCloseClicked: () => App.instance.close(), onNewVersionAvailableClicked: onNewVersionAvailableClicked }),
            children)));
}

;// ./src/editor/src/views/windows/BaseWindow/index.ts


;// ./src/editor/src/constants/LocalStorageKey.ts
const LocalStorageKey = {
    lastSeenChangelogDate: 'lastSeenChangelogDate',
    hasNewEditorVersionAvailable: 'hasNewEditorVersionAvailable',
    devModeSignInUsername: 'devModeSignInUsername'
};

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/NewsModal/NewsModal.module.scss
var NewsModal_module = __webpack_require__(55155);
;// ./src/editor/src/views/NewsModal/NewsModal.module.scss

      
      
      
      
      
      
      
      
      

var NewsModal_module_options = {};

NewsModal_module_options.styleTagTransform = (styleTagTransform_default());
NewsModal_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      NewsModal_module_options.insert = insertBySelector_default().bind(null, "head");
    
NewsModal_module_options.domAPI = (styleDomAPI_default());
NewsModal_module_options.insertStyleElement = (insertStyleElement_default());

var NewsModal_module_update = injectStylesIntoStyleTag_default()(NewsModal_module/* default */.A, NewsModal_module_options);




       /* harmony default export */ const NewsModal_NewsModal_module = (NewsModal_module/* default */.A && NewsModal_module/* default */.A.locals ? NewsModal_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/NewsModal/NewsModal.tsx









function NewsModal({ content, onFinished }) {
    const [isVisible, setIsVisible] = (0,external_react_.useState)(undefined);
    const [activeSlide, setActiveSlide] = (0,external_react_.useState)(0);
    const host = (0,editor_getDocsEndpoint/* default */.A)();
    const version = src.platform.getVersion();
    const parsedContent = (0,external_react_.useMemo)(() => {
        const parseContainer = document.createElement('div');
        parseContainer.innerHTML = content;
        const images = Array.from(parseContainer.querySelectorAll('img'));
        images.forEach((image) => {
            const src = image.getAttribute('src');
            image.src = host + src;
            image.removeAttribute('width');
            image.removeAttribute('height');
        });
        const slides = Array.from(parseContainer.querySelectorAll('section'));
        if (images.length) {
            const loadTrigger = document.createElement('img');
            loadTrigger.onload = () => setIsVisible(true);
            loadTrigger.src = images[0].src;
        }
        else {
            setIsVisible(true);
        }
        if (slides.length)
            return slides.map((slide) => slide.innerHTML);
        return [parseContainer.innerHTML];
    }, [content]);
    const isOnLastSlide = activeSlide >= parsedContent.length - 1;
    const nextButton = isOnLastSlide
        ? {
            label: 'Got it',
            onClick: () => {
                setIsVisible(false);
                onFinished();
            }
        }
        : {
            label: 'Next',
            onClick: () => setActiveSlide((val) => val + 1)
        };
    if (typeof isVisible === 'undefined')
        return null;
    return (external_react_default().createElement(BaseDialog/* BaseDialog */.mY, { isVisible: isVisible, hasBackdrop: true, onClose: () => setIsVisible(false), UNSAFE_className: NewsModal_NewsModal_module['Background'] },
        external_react_default().createElement("div", { className: NewsModal_NewsModal_module['Root'] },
            external_react_default().createElement("div", { className: NewsModal_NewsModal_module['Header'] },
                external_react_default().createElement(typography_Text/* Text */.EY, null,
                    "New updates in ",
                    version)),
            external_react_default().createElement("div", { className: NewsModal_NewsModal_module['Inner'] },
                parsedContent.map((slide, i) => (external_react_default().createElement(Collapsible/* Collapsible */.N, { key: i, isCollapsed: i !== activeSlide },
                    external_react_default().createElement(HtmlRenderer/* HtmlRenderer */.j, { html: slide })))),
                external_react_default().createElement("div", { className: NewsModal_NewsModal_module['Nav'] },
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: nextButton.label, onClick: () => nextButton.onClick(), UNSAFE_className: NewsModal_NewsModal_module['Button'] }))))));
}

;// ./src/editor/src/views/NewsModal/index.ts


;// ./src/editor/src/whats-new.ts







/**
 * Display latest whats-new-post if the user hasn't seen one after it was last published
 * @returns
 */
async function whatsnewRender() {
    const newEditorVersionAvailable = JSON.parse(localStorage.getItem(LocalStorageKey.hasNewEditorVersionAvailable));
    // if user runs an older version the changelog will be irrelevant
    if (newEditorVersionAvailable)
        return;
    const latestChangelogPost = await fetch(`${(0,editor_getDocsEndpoint/* default */.A)()}/whats-new/feed.json`)
        .then((data) => data.json())
        .then((json) => json.items[0]);
    const lastSeenChangelogDate = new Date(JSON.parse(localStorage.getItem(LocalStorageKey.lastSeenChangelogDate))).getTime();
    const latestChangelogDate = new Date(latestChangelogPost.date_modified).getTime();
    if (lastSeenChangelogDate >= latestChangelogDate)
        return;
    external_electron_.ipcRenderer.send('viewer-hide');
    const modalContainer = document.createElement('div');
    modalContainer.classList.add('popup-layer-react-modal');
    popuplayer_default().instance.el.find('.popup-layer-modal').before(modalContainer);
    // Create root once and properly unmount when finished
    const modalRoot = (0,client.createRoot)(modalContainer);
    modalRoot.render(external_react_default().createElement(NewsModal, {
        content: latestChangelogPost.content_html,
        onFinished: () => {
            external_electron_.ipcRenderer.send('viewer-show');
            // Properly cleanup React root and DOM element
            modalRoot.unmount();
            modalContainer.remove();
        }
    }));
    localStorage.setItem(LocalStorageKey.lastSeenChangelogDate, latestChangelogDate.toString());
}

;// ./src/editor/src/pages/EditorPage/useSetupSettings.ts





function useSetupSettings() {
    (0,external_react_.useEffect)(() => {
        const eventGroup = {};
        // Set the active side panel
        const projectEditorSettings = editorsettings/* EditorSettings */.H.instance.get(projectmodel.ProjectModel.instance.id) || {};
        const savedPanelId = projectEditorSettings['editor-sidebar-panel'];
        const panelExists = savedPanelId && models_sidebar/* SidebarModel */.s.instance.getItems().find((p) => p.id === savedPanelId);
        const panelId = panelExists ? savedPanelId : 'components';
        models_sidebar/* SidebarModel */.s.instance.switch(panelId);
        // Save changes to side panel
        models_sidebar/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.activeChanged, () => {
            if (!projectmodel.ProjectModel.instance)
                return;
            const currentPanel = models_sidebar/* SidebarModel */.s.instance.getCurrent();
            if (!currentPanel.transient) {
                editorsettings/* EditorSettings */.H.instance.setMerge(projectmodel.ProjectModel.instance.id, { 'editor-sidebar-panel': currentPanel.id });
            }
        }, eventGroup);
        return () => {
            models_sidebar/* SidebarModel */.s.instance.off(eventGroup);
        };
    }, []);
}

;// ./src/editor/src/pages/EditorPage/EditorPage.tsx









































// eslint-disable-next-line @typescript-eslint/no-var-requires
const ImportOverwritePopupTemplate = __webpack_require__(94047);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const ImportPopupTemplate = __webpack_require__(72498);
if (false) // removed by dead control flow
{}
function setupSidePanels() {
    const isLesson = projectmodel.ProjectModel.instance.isLesson();
    installSidePanel({ isLesson });
}
function EditorPage({ route }) {
    const [isLoading, setIsLoading] = (0,external_react_.useState)(true);
    const appRegistry = (0,useModel/* useModel */.f)(AppRegistry.instance, ['documentChanged']);
    const Document = appRegistry.getActiveDocument();
    const [lesson, setLesson] = (0,external_react_.useState)(null);
    const [frameDividerSize, setFrameDividerSize] = (0,external_react_.useState)(undefined);
    // Handle sidebar expansion for topology panel
    (0,external_react_.useEffect)(() => {
        const eventGroup = {};
        const updateSidebarSize = () => {
            const activeId = models_sidebar/* SidebarModel */.s.instance.ActiveId;
            const isTopology = activeId === 'topology';
            if (isTopology) {
                // Calculate 55vw in pixels to match SideNavigation expansion
                const expandedSize = Math.floor(window.innerWidth * 0.55);
                setFrameDividerSize(expandedSize);
            }
            else {
                // Use default size
                setFrameDividerSize(380);
            }
        };
        // Listen to sidebar changes
        models_sidebar/* SidebarModel */.s.instance.on(sidebarmodel/* SidebarModelEvent */.q.activeChanged, updateSidebarSize, eventGroup);
        // Also listen to window resize to recalculate 55vw
        window.addEventListener('resize', updateSidebarSize);
        // Run once on mount
        updateSidebarSize();
        return () => {
            models_sidebar/* SidebarModel */.s.instance.off(eventGroup);
            window.removeEventListener('resize', updateSidebarSize);
        };
    }, []);
    (0,external_react_.useEffect)(() => {
        // Display latest whats-new-post if the user hasn't seen one after it was last published
        whatsnewRender();
        (0,NodePicker_hooks/* NodePickerClearNews */.dF)();
        schemahandler/* default */.A.instance = new schemahandler/* default */.A();
        if (!projectmodel.ProjectModel.instance.isLesson()) {
            CloudServices.CloudService.instance.prefetch();
        }
        setupSidePanels();
        installDocuments();
        const eventGroup = {};
        // Docs layer
        //DocsLayer.instance.render();
        //$('body').append(DocsLayer.instance.el);
        //broadcast new project name over udp to noodl-shells on the same network
        external_electron_.ipcRenderer.send('project-opened', projectmodel.ProjectModel.instance.name);
        // Listen to exit editor
        App.instance.off(this).on('exitEditor', () => {
            route.router.route({ to: 'projects' });
            //close viewer window and broadcast that no project is open
            external_electron_.ipcRenderer.send('project-closed');
        }, this);
        // Listen to project changed on disk, reload editor
        EventDispatcher.EventDispatcher.instance.on('projectChangedOnDisk', () => reloadProjectFromDisk(), eventGroup);
        EventDispatcher.EventDispatcher.instance.on('importFromUrl', (url) => importFromUrl(url), eventGroup);
        EventDispatcher.EventDispatcher.instance.on('ProjectModel.saveFailedRetryScheduled', () => {
            ToastLayer.ToastLayer.showError('Failed to save project, retrying...', 3000);
        }, eventGroup);
        setIsLoading(false);
        return function () {
            EventDispatcher.EventDispatcher.instance.off(eventGroup);
            if (schemahandler/* default */.A.instance) {
                schemahandler/* default */.A.instance.dispose();
                schemahandler/* default */.A.instance = null;
            }
            //stop parse dashboard if it's running
            parsedashboardserver.instance.stop();
            // Reset the cloud services token, since the tokens are per project.
            CloudServices.CloudService.instance.reset();
            models_sidebar/* SidebarModel */.s.instance.reset();
            undo_queue_model/* UndoQueue */.g.instance.clear();
        };
    }, []);
    useKeyboardCommands(() => [
        {
            handler: () => models_sidebar/* SidebarModel */.s.instance.switch('search'),
            keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.KEY_F
        },
        {
            handler: () => EventDispatcher.EventDispatcher.instance.emit('viewer-open-devtools'),
            keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.KEY_D
        },
        {
            handler: () => external_electron_.ipcRenderer.send('cloud-runtime-open-devtools'),
            keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyMod.Shift | KeyCode.KeyCode.KEY_R
        },
        {
            handler: () => EventDispatcher.EventDispatcher.instance.emit('viewer-refresh'),
            keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.KEY_R
        },
        {
            // Refresh viewer and node library
            handler: () => {
                NodeLibraryImporter/* NodeLibraryImporter */.K.instance.clear();
                EventDispatcher.EventDispatcher.instance.emit('viewer-refresh');
                external_electron_.ipcRenderer.send('cloud-runtime-refresh');
                ToastLayer.ToastLayer.showInteraction('Refresh Node Library and viewers');
            },
            keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyMod.Shift | KeyCode.KeyCode.KEY_X
        },
        {
            handler: () => exportProjectComponents(),
            keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyMod.Shift | KeyCode.KeyCode.KEY_E
        },
        {
            handler: async () => {
                const environment = await CloudServices.CloudService.instance.getActiveEnvironment(projectmodel.ProjectModel.instance);
                if (environment) {
                    parsedashboardserver.instance.openInWindow(environment);
                }
            },
            keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyMod.Shift | KeyCode.KeyCode.KEY_P
        },
        {
            handler: async () => {
                const environment = await CloudServices.CloudService.instance.getActiveEnvironment(projectmodel.ProjectModel.instance);
                if (environment) {
                    parsedashboardserver.instance.openInBrowser(environment);
                }
            },
            keybinding: KeyCode.KeyMod.CtrlCmd | KeyCode.KeyCode.KEY_P
        }
    ]);
    useSetupSettings();
    // Attach lesson
    (0,external_react_.useEffect)(() => {
        if (!projectmodel.ProjectModel.instance.isLesson())
            return;
        const lessonLayer = new LessonLayer();
        const projectModel = projectmodel.ProjectModel.instance;
        const element = lessonLayer.startLesson(projectModel.getLessonModel());
        setLesson({ el: element });
        return () => {
            lessonLayer.dispose();
        };
    }, []);
    return (external_react_default().createElement(NodeGraphContext.NodeGraphContextProvider, null,
        external_react_default().createElement(ProjectDesignTokenContextProvider, null,
            external_react_default().createElement(BaseWindow, null, isLoading ? (external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null)) : (external_react_default().createElement((external_react_default()).Fragment, null,
                external_react_default().createElement(FrameDivider, { first: external_react_default().createElement(SidePanel, null), second: external_react_default().createElement(ErrorBoundary, null, Boolean(Document) && external_react_default().createElement(Document, null)), sizeMin: 200, size: frameDividerSize, horizontal: true, onSizeChanged: setFrameDividerSize }),
                Boolean(lesson) && external_react_default().createElement(Frame, { instance: lesson, isContentSize: true, isFitWidth: true })))))));
}
function importFromUrl(url) {
    const activityId = 'import-from-url';
    popuplayer_default().instance.hidePopup();
    ToastLayer.ToastLayer.showActivity('Importing from url', activityId);
    const tmp = src.platform.getUserDataPath() + '/tmp/' + (0,utils.guid)();
    filesystem_default().instance.makeDirectory(tmp, function (r) {
        if (r.result !== 'success') {
            ToastLayer.ToastLayer.hideActivity(activityId);
            ToastLayer.ToastLayer.showError('Import failed');
            return;
        }
        (0,projectmodel_editor.unzipIntoDirectory)(url, tmp, function (r) {
            ToastLayer.ToastLayer.hideActivity(activityId);
            if (r.result !== 'success') {
                ToastLayer.ToastLayer.showError("Couldn't load project from URL");
                return;
            }
            const validator = new (projectvalidator_default())();
            validator.validateProjectDirectory(tmp);
            if (validator.hasErrors()) {
                ToastLayer.ToastLayer.showError('This is not a valid Noodl project');
                return;
            }
            _importProject(tmp);
        }, { skipLoad: true, noAuth: true });
    });
}
function _importProject(dirEntry) {
    const activityId = 'import-project';
    ToastLayer.ToastLayer.showActivity('Importing...', activityId);
    let selectedImports = {};
    projectimporter_default().instance.listComponentsAndDependencies(dirEntry, function (imports) {
        if (!imports) {
            ToastLayer.ToastLayer.hideActivity(activityId);
            ToastLayer.ToastLayer.showError('Could not load import project');
            return;
        }
        // Pre check all imports
        if (imports.components)
            imports.components.forEach((i) => {
                i.import = true;
            });
        if (imports.resources)
            imports.resources.forEach((r) => {
                r.import = true;
            });
        // Show popup and allow the user to choose which components to import
        var chooseImportsPopup = new (importpopup_default())({
            template: ImportPopupTemplate,
            imports: imports,
            onOk: function () {
                // User have made choice of what to import, check if there are any collisions
                selectedImports = chooseImportsPopup.getSelectedImports();
                projectimporter_default().instance.checkForCollisions(selectedImports, function (collisions) {
                    ToastLayer.ToastLayer.hideActivity(activityId);
                    if (collisions === undefined) {
                        // No collisions
                        popuplayer_default().instance.hideAllModalsAndPopups();
                        doImport(selectedImports);
                    }
                    else {
                        // There is a collision for import, promt user if we should overwrite
                        const overwritePopup = new (importpopup_default())({
                            template: ImportOverwritePopupTemplate,
                            imports: collisions,
                            onOk: function () {
                                popuplayer_default().instance.hideAllModalsAndPopups();
                                doImport(selectedImports);
                            },
                            onCancel: function () {
                                popuplayer_default().instance.hideAllModalsAndPopups();
                            }
                        });
                        overwritePopup.render();
                        overwritePopup.el.css('width', '500px'); // Make it a little bit wider as a modal
                        popuplayer_default().instance.showModal({
                            content: overwritePopup
                        });
                    }
                });
            },
            onCancel: function () {
                popuplayer_default().instance.hideModal();
            }
        });
        chooseImportsPopup.render();
        chooseImportsPopup.el.css('width', '500px'); // Make it a little bit wider as a modal
        ToastLayer.ToastLayer.hideActivity(activityId);
        popuplayer_default().instance.showModal({
            content: chooseImportsPopup
        });
    });
    function doImport(imports) {
        ToastLayer.ToastLayer.showActivity('Importing...', activityId);
        ViewerConnection/* ViewerConnection */.t.instance.setWatchModelChangesEnabled(false);
        projectimporter_default().instance.import(dirEntry, imports, function (r) {
            ViewerConnection/* ViewerConnection */.t.instance.setWatchModelChangesEnabled(true);
            ToastLayer.ToastLayer.hideActivity(activityId);
            if (r.result !== 'success') {
                ToastLayer.ToastLayer.showError(r.message);
                return;
            }
            ToastLayer.ToastLayer.showSuccess('Import successful');
            // Reload the viewer
            EventDispatcher.EventDispatcher.instance.emit('ProjectModel.importComplete');
            EventDispatcher.EventDispatcher.instance.emit('viewer-refresh');
        });
    }
}
function reloadProjectFromDisk() {
    const hasActiveProject = projectmodel.ProjectModel.instance && projectmodel.ProjectModel.instance._retainedProjectDirectory;
    if (!hasActiveProject) {
        return;
    }
    ViewerConnection/* ViewerConnection */.t.instance.setWatchModelChangesEnabled(false);
    projectmodel.ProjectModel.setSaveOnModelChange(false);
    projectmodel.ProjectModel.instance.dispose(); // Unload current project
    (0,projectmodel_editor.projectFromDirectory)(projectmodel.ProjectModel.instance._retainedProjectDirectory, (reloaded) => {
        ViewerConnection/* ViewerConnection */.t.instance.setWatchModelChangesEnabled(true);
        if (reloaded) {
            reloaded.id = projectmodel.ProjectModel.instance.id;
            projectmodel.ProjectModel.instance = reloaded;
            // Make sure the correct projects model tracks changes
            LocalProjectsModel/* LocalProjectsModel */.h.instance.bindProject(reloaded);
            projectmodel.ProjectModel.setSaveOnModelChange(true);
        }
    });
}

;// ./src/editor/src/pages/EditorPage/index.ts


// EXTERNAL MODULE: ../noodl-git/src/core/clone.ts
var clone = __webpack_require__(29902);
// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/preview/launcher/Launcher/components/CreateProjectModal/CreateProjectModal.module.scss
var CreateProjectModal_module = __webpack_require__(90939);
;// ../noodl-core-ui/src/preview/launcher/Launcher/components/CreateProjectModal/CreateProjectModal.module.scss

      
      
      
      
      
      
      
      
      

var CreateProjectModal_module_options = {};

CreateProjectModal_module_options.styleTagTransform = (styleTagTransform_default());
CreateProjectModal_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      CreateProjectModal_module_options.insert = insertBySelector_default().bind(null, "head");
    
CreateProjectModal_module_options.domAPI = (styleDomAPI_default());
CreateProjectModal_module_options.insertStyleElement = (insertStyleElement_default());

var CreateProjectModal_module_update = injectStylesIntoStyleTag_default()(CreateProjectModal_module/* default */.A, CreateProjectModal_module_options);




       /* harmony default export */ const CreateProjectModal_CreateProjectModal_module = (CreateProjectModal_module/* default */.A && CreateProjectModal_module/* default */.A.locals ? CreateProjectModal_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/CreateProjectModal/CreateProjectModal.tsx





function CreateProjectModal({ isVisible, onClose, onConfirm, onChooseLocation }) {
    const [projectName, setProjectName] = (0,external_react_.useState)('');
    const [location, setLocation] = (0,external_react_.useState)('');
    const [isChoosingLocation, setIsChoosingLocation] = (0,external_react_.useState)(false);
    // Reset state when modal opens
    (0,external_react_.useEffect)(() => {
        if (isVisible) {
            setProjectName('');
            setLocation('');
        }
    }, [isVisible]);
    const handleChooseLocation = async () => {
        if (!onChooseLocation)
            return;
        setIsChoosingLocation(true);
        try {
            const chosen = await onChooseLocation();
            if (chosen) {
                setLocation(chosen);
            }
        }
        finally {
            setIsChoosingLocation(false);
        }
    };
    const handleCreate = () => {
        if (!projectName.trim() || !location)
            return;
        onConfirm(projectName.trim(), location);
    };
    const isValid = projectName.trim().length > 0 && location.length > 0;
    if (!isVisible)
        return null;
    return (external_react_default().createElement("div", { className: CreateProjectModal_CreateProjectModal_module['Backdrop'], onClick: onClose },
        external_react_default().createElement("div", { className: CreateProjectModal_CreateProjectModal_module['Modal'], onClick: (e) => e.stopPropagation() },
            external_react_default().createElement("div", { className: CreateProjectModal_CreateProjectModal_module['Header'] },
                external_react_default().createElement("h3", { className: CreateProjectModal_CreateProjectModal_module['Title'] }, "Create New Project")),
            external_react_default().createElement("div", { className: CreateProjectModal_CreateProjectModal_module['Content'] },
                external_react_default().createElement("div", { className: CreateProjectModal_CreateProjectModal_module['Field'] },
                    external_react_default().createElement(Label/* Label */.JU, null, "Project Name"),
                    external_react_default().createElement(TextInput, { value: projectName, onChange: (e) => setProjectName(e.target.value), placeholder: "My New Project", isAutoFocus: true, UNSAFE_style: { marginTop: 'var(--spacing-2)' } })),
                external_react_default().createElement("div", { className: CreateProjectModal_CreateProjectModal_module['Field'] },
                    external_react_default().createElement(Label/* Label */.JU, null, "Location"),
                    external_react_default().createElement("div", { className: CreateProjectModal_CreateProjectModal_module['LocationRow'] },
                        external_react_default().createElement(TextInput, { value: location, onChange: (e) => setLocation(e.target.value), placeholder: "Choose folder...", isReadonly: true, UNSAFE_style: { flex: 1 } }),
                        external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Choose...", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: handleChooseLocation, isDisabled: isChoosingLocation, UNSAFE_style: { marginLeft: 'var(--spacing-2)' } }))),
                projectName && location && (external_react_default().createElement("div", { className: CreateProjectModal_CreateProjectModal_module['PathPreview'] },
                    external_react_default().createElement("span", { className: CreateProjectModal_CreateProjectModal_module['PathText'] },
                        "Full path: ",
                        location,
                        "/",
                        projectName,
                        "/")))),
            external_react_default().createElement("div", { className: CreateProjectModal_CreateProjectModal_module['Footer'] },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Default, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onClose, UNSAFE_style: { marginRight: 'var(--spacing-2)' } }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Create", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Default, onClick: handleCreate, isDisabled: !isValid })))));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/CreateProjectModal/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/common/Card/Card.module.scss
var Card_module = __webpack_require__(82470);
;// ../noodl-core-ui/src/components/common/Card/Card.module.scss

      
      
      
      
      
      
      
      
      

var Card_module_options = {};

Card_module_options.styleTagTransform = (styleTagTransform_default());
Card_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      Card_module_options.insert = insertBySelector_default().bind(null, "head");
    
Card_module_options.domAPI = (styleDomAPI_default());
Card_module_options.insertStyleElement = (insertStyleElement_default());

var Card_module_update = injectStylesIntoStyleTag_default()(Card_module/* default */.A, Card_module_options);




       /* harmony default export */ const Card_Card_module = (Card_module/* default */.A && Card_module/* default */.A.locals ? Card_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/common/Card/Card.tsx



var CardPadding;
(function (CardPadding) {
    CardPadding["Small"] = "is-padding-small";
    CardPadding["Default"] = "is-padding-default";
    CardPadding["Large"] = "is-padding-large";
})(CardPadding || (CardPadding = {}));
var CardBackground;
(function (CardBackground) {
    CardBackground["Bg1"] = "is-bg-1";
    CardBackground["Bg2"] = "is-bg-2";
    CardBackground["Bg3"] = "is-bg-3";
    CardBackground["Bg4"] = "is-bg-4";
})(CardBackground || (CardBackground = {}));
function Card({ children, padding = CardPadding.Default, background = CardBackground.Bg3, hoverBackground, onClick, UNSAFE_className, UNSAFE_style }) {
    return (external_react_default().createElement("div", { style: UNSAFE_style, className: external_classnames_default()(Card_Card_module.Root, Card_Card_module[padding], Card_Card_module[background], Card_Card_module[`${hoverBackground}-on-hover`], (Boolean(hoverBackground) || Boolean(onClick)) && Card_Card_module['has-hover-state'], UNSAFE_className), onClick: onClick }, children));
}

;// ../noodl-core-ui/src/components/common/Card/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/user/UserBadgeList/UserBadgeList.module.scss
var UserBadgeList_module = __webpack_require__(71594);
;// ../noodl-core-ui/src/components/user/UserBadgeList/UserBadgeList.module.scss

      
      
      
      
      
      
      
      
      

var UserBadgeList_module_options = {};

UserBadgeList_module_options.styleTagTransform = (styleTagTransform_default());
UserBadgeList_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      UserBadgeList_module_options.insert = insertBySelector_default().bind(null, "head");
    
UserBadgeList_module_options.domAPI = (styleDomAPI_default());
UserBadgeList_module_options.insertStyleElement = (insertStyleElement_default());

var UserBadgeList_module_update = injectStylesIntoStyleTag_default()(UserBadgeList_module/* default */.A, UserBadgeList_module_options);




       /* harmony default export */ const UserBadgeList_UserBadgeList_module = (UserBadgeList_module/* default */.A && UserBadgeList_module/* default */.A.locals ? UserBadgeList_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/user/UserBadgeList/UserBadgeList.tsx






function UserBadgeList({ badges, size, maxVisible }) {
    const itemsToRender = Boolean(maxVisible) ? badges.slice(0, maxVisible) : badges;
    const hiddenItems = Boolean(maxVisible) ? badges.slice(maxVisible) : [];
    const hiddenPeople = hiddenItems.map((badge) => badge.name).join(', ');
    const restItemsAmount = Boolean(maxVisible) ? badges.length - maxVisible : 0;
    return (external_react_default().createElement("div", { className: UserBadgeList_UserBadgeList_module['Root'] },
        itemsToRender.map((badge, i) => (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: badge.name, fineType: badge.email, key: badge.id },
            external_react_default().createElement(UserBadge, { email: badge.email, name: badge.name, id: badge.id, size: size, UNSAFE_style: { marginLeft: i > 0 ? '-6px' : null, border: '1px solid var(--theme-color-bg-2)' } })))),
        restItemsAmount > 0 && (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: hiddenPeople },
            external_react_default().createElement(Label/* Label */.JU, { hasLeftSpacing: true, variant: typography_Text/* TextType */.M2.Shy },
                "+ ",
                restItemsAmount,
                " more")))));
}

;// ../noodl-core-ui/src/components/user/UserBadgeList/index.ts


;// ../noodl-core-ui/src/preview/launcher/Launcher/LauncherContext.tsx
/**
 * LauncherContext - State management for the launcher dashboard
 *
 * Provides global state for active tab navigation and other launcher-wide concerns.
 *
 * @module noodl-core-ui/preview/launcher
 */

const LauncherContext = (0,external_react_.createContext)(null);
function LauncherProvider({ children, value }) {
    return external_react_default().createElement(LauncherContext.Provider, { value: value }, children);
}
/**
 * Hook to access launcher context
 * @throws Error if used outside of LauncherProvider
 */
function useLauncherContext() {
    const context = (0,external_react_.useContext)(LauncherContext);
    if (!context) {
        throw new Error('useLauncherContext must be used within a LauncherProvider');
    }
    return context;
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/hooks/useProjectOrganization.ts
/**
 * useProjectOrganization
 *
 * React hook for managing project organization (folders and tags).
 * Interfaces with ProjectOrganizationService from noodl-editor.
 */


/**
 * Hook to manage project organization through folders and tags.
 *
 * Uses the real ProjectOrganizationService when available (in production),
 * falls back to localStorage service for Storybook compatibility.
 */
function useProjectOrganization() {
    const { projectOrganizationService } = useLauncherContext();
    const [folders, setFolders] = (0,external_react_.useState)([]);
    const [tags, setTags] = (0,external_react_.useState)([]);
    const [, setUpdateTrigger] = (0,external_react_.useState)(0);
    // Use real service if available, otherwise fall back to localStorage
    const service = (0,external_react_.useMemo)(() => {
        if (projectOrganizationService) {
            console.log('✅ Using real ProjectOrganizationService');
            return projectOrganizationService;
        }
        console.warn('⚠️ ProjectOrganizationService not available, using localStorage fallback');
        return createLocalStorageService();
    }, [projectOrganizationService]);
    // Subscribe to service events and load initial data
    (0,external_react_.useEffect)(() => {
        // Initial load
        setFolders(service.getFolders());
        setTags(service.getTags());
        // Subscribe to changes
        const handleDataChange = () => {
            setFolders(service.getFolders());
            setTags(service.getTags());
            setUpdateTrigger((prev) => prev + 1);
        };
        service.on('dataChanged', handleDataChange);
        // Cleanup
        return () => {
            service.off('dataChanged', handleDataChange);
        };
    }, [service]);
    return {
        // Data
        folders,
        tags,
        // Folder operations
        createFolder: (name, parentId) => service.createFolder(name, parentId),
        renameFolder: (id, name) => service.renameFolder(id, name),
        deleteFolder: (id) => service.deleteFolder(id),
        getProjectCountInFolder: (folderId) => service.getProjectCountInFolder(folderId),
        // Tag operations
        createTag: (name, color) => service.createTag(name, color),
        renameTag: (id, name) => service.renameTag(id, name),
        changeTagColor: (id, color) => service.changeTagColor(id, color),
        deleteTag: (id) => service.deleteTag(id),
        // Project organization
        moveProjectToFolder: (projectPath, folderId) => service.moveProjectToFolder(projectPath, folderId),
        addTagToProject: (projectPath, tagId) => service.addTagToProject(projectPath, tagId),
        removeTagFromProject: (projectPath, tagId) => service.removeTagFromProject(projectPath, tagId),
        getProjectMeta: (projectPath) => service.getProjectMeta(projectPath),
        getProjectsInFolder: (folderId) => service.getProjectsInFolder(folderId),
        getProjectsWithTag: (tagId) => service.getProjectsWithTag(tagId)
    };
}
// ============================================================================
// Minimal localStorage-based service for noodl-core-ui
// This allows the hook to work in Storybook and standalone contexts
// ============================================================================
class EventEmitter {
    constructor() {
        this.listeners = new Map();
    }
    on(event, callback) {
        if (!this.listeners.has(event)) {
            this.listeners.set(event, []);
        }
        this.listeners.get(event).push(callback);
    }
    off(event, callback) {
        if (!callback) {
            this.listeners.delete(event);
            return;
        }
        const callbacks = this.listeners.get(event);
        if (callbacks) {
            const index = callbacks.indexOf(callback);
            if (index > -1) {
                callbacks.splice(index, 1);
            }
        }
    }
    emit(event, data) {
        const callbacks = this.listeners.get(event);
        if (callbacks) {
            callbacks.forEach((callback) => callback(data));
        }
    }
}
function createLocalStorageService() {
    const emitter = new EventEmitter();
    const storageKey = 'projectOrganization';
    const loadData = () => {
        try {
            const stored = localStorage.getItem(storageKey);
            if (stored) {
                return JSON.parse(stored);
            }
        }
        catch (error) {
            console.error('[useProjectOrganization] Failed to load data:', error);
        }
        return {
            version: 1,
            folders: [],
            tags: [],
            projectMeta: {}
        };
    };
    let data = loadData();
    const saveData = () => {
        try {
            localStorage.setItem(storageKey, JSON.stringify(data));
            emitter.emit('dataChanged', data);
        }
        catch (error) {
            console.error('[useProjectOrganization] Failed to save data:', error);
        }
    };
    const generateId = (prefix) => {
        return `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    };
    const TAG_COLORS = [
        '#EF4444',
        '#F97316',
        '#EAB308',
        '#22C55E',
        '#06B6D4',
        '#3B82F6',
        '#8B5CF6',
        '#EC4899',
        '#6B7280'
    ];
    const getNextTagColor = () => {
        const usedColors = data.tags.map((t) => t.color);
        const availableColors = TAG_COLORS.filter((c) => !usedColors.includes(c));
        return availableColors.length > 0 ? availableColors[0] : TAG_COLORS[0];
    };
    return {
        // Event methods
        on: emitter.on.bind(emitter),
        off: emitter.off.bind(emitter),
        emit: emitter.emit.bind(emitter),
        // Data methods
        getFolders: () => [...data.folders].sort((a, b) => a.order - b.order),
        getTags: () => [...data.tags],
        createFolder: (name, parentId) => {
            const folder = {
                id: generateId('folder'),
                name,
                parentId: parentId || null,
                order: data.folders.length,
                createdAt: new Date().toISOString()
            };
            data.folders.push(folder);
            saveData();
            return folder;
        },
        renameFolder: (id, name) => {
            const folder = data.folders.find((f) => f.id === id);
            if (folder) {
                folder.name = name;
                saveData();
            }
        },
        deleteFolder: (id) => {
            data.folders = data.folders.filter((f) => f.id !== id && f.parentId !== id);
            Object.keys(data.projectMeta).forEach((projectPath) => {
                if (data.projectMeta[projectPath].folderId === id) {
                    data.projectMeta[projectPath].folderId = null;
                }
            });
            saveData();
        },
        getProjectCountInFolder: (folderId) => {
            return Object.values(data.projectMeta).filter((meta) => meta.folderId === folderId).length;
        },
        createTag: (name, color) => {
            const tag = {
                id: generateId('tag'),
                name,
                color: color || getNextTagColor(),
                createdAt: new Date().toISOString()
            };
            data.tags.push(tag);
            saveData();
            return tag;
        },
        renameTag: (id, name) => {
            const tag = data.tags.find((t) => t.id === id);
            if (tag) {
                tag.name = name;
                saveData();
            }
        },
        changeTagColor: (id, color) => {
            const tag = data.tags.find((t) => t.id === id);
            if (tag) {
                tag.color = color;
                saveData();
            }
        },
        deleteTag: (id) => {
            data.tags = data.tags.filter((t) => t.id !== id);
            Object.keys(data.projectMeta).forEach((projectPath) => {
                data.projectMeta[projectPath].tagIds = data.projectMeta[projectPath].tagIds.filter((tagId) => tagId !== id);
            });
            saveData();
        },
        moveProjectToFolder: (projectPath, folderId) => {
            if (!data.projectMeta[projectPath]) {
                data.projectMeta[projectPath] = { folderId: null, tagIds: [] };
            }
            data.projectMeta[projectPath].folderId = folderId;
            saveData();
        },
        addTagToProject: (projectPath, tagId) => {
            if (!data.projectMeta[projectPath]) {
                data.projectMeta[projectPath] = { folderId: null, tagIds: [] };
            }
            const meta = data.projectMeta[projectPath];
            if (!meta.tagIds.includes(tagId)) {
                meta.tagIds.push(tagId);
                saveData();
            }
        },
        removeTagFromProject: (projectPath, tagId) => {
            const meta = data.projectMeta[projectPath];
            if (meta) {
                meta.tagIds = meta.tagIds.filter((id) => id !== tagId);
                saveData();
            }
        },
        getProjectMeta: (projectPath) => {
            return data.projectMeta[projectPath] || null;
        },
        getProjectsInFolder: (folderId) => {
            return Object.keys(data.projectMeta).filter((projectPath) => data.projectMeta[projectPath].folderId === folderId);
        },
        getProjectsWithTag: (tagId) => {
            return Object.keys(data.projectMeta).filter((projectPath) => data.projectMeta[projectPath].tagIds.includes(tagId));
        }
    };
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/preview/launcher/Launcher/components/TagPill/TagPill.module.scss
var TagPill_module = __webpack_require__(31957);
;// ../noodl-core-ui/src/preview/launcher/Launcher/components/TagPill/TagPill.module.scss

      
      
      
      
      
      
      
      
      

var TagPill_module_options = {};

TagPill_module_options.styleTagTransform = (styleTagTransform_default());
TagPill_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      TagPill_module_options.insert = insertBySelector_default().bind(null, "head");
    
TagPill_module_options.domAPI = (styleDomAPI_default());
TagPill_module_options.insertStyleElement = (insertStyleElement_default());

var TagPill_module_update = injectStylesIntoStyleTag_default()(TagPill_module/* default */.A, TagPill_module_options);




       /* harmony default export */ const TagPill_TagPill_module = (TagPill_module/* default */.A && TagPill_module/* default */.A.locals ? TagPill_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/TagPill/TagPill.tsx
/**
 * TagPill Component
 *
 * Displays a tag as a small colored pill/badge.
 * Used to show project tags in cards and lists.
 */




var TagPillSize;
(function (TagPillSize) {
    TagPillSize["Small"] = "small";
    TagPillSize["Medium"] = "medium";
})(TagPillSize || (TagPillSize = {}));
/**
 * TagPill - Displays a tag as a colored pill badge
 *
 * @example
 * ```tsx
 * <TagPill
 *   tag={{ id: '1', name: 'Frontend', color: '#3B82F6' }}
 *   size={TagPillSize.Small}
 * />
 * ```
 */
function TagPill({ tag, size = TagPillSize.Medium, removable = false, onRemove, onClick, className }) {
    const handleRemoveClick = (e) => {
        e.stopPropagation();
        onRemove === null || onRemove === void 0 ? void 0 : onRemove();
    };
    const handlePillClick = (e) => {
        if (onClick) {
            e.stopPropagation();
            onClick();
        }
    };
    return (external_react_default().createElement("div", { className: `${TagPill_TagPill_module.Root} ${TagPill_TagPill_module[`Size-${size}`]} ${onClick ? TagPill_TagPill_module.Clickable : ''} ${className || ''}`, style: { backgroundColor: tag.color }, onClick: handlePillClick, role: onClick ? 'button' : undefined, tabIndex: onClick ? 0 : undefined },
        external_react_default().createElement(Label/* Label */.JU, { size: size === TagPillSize.Small ? Label/* LabelSize */.IV.Small : Label/* LabelSize */.IV.Default, UNSAFE_className: TagPill_TagPill_module.Label }, tag.name),
        removable && (external_react_default().createElement("button", { className: TagPill_TagPill_module.RemoveButton, onClick: handleRemoveClick, "aria-label": `Remove ${tag.name} tag`, type: "button" },
            external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Close, size: size === TagPillSize.Small ? common_Icon/* IconSize */.lK.Tiny : common_Icon/* IconSize */.lK.Small })))));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/TagPill/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherProjectCard/LauncherProjectCard.module.scss
var LauncherProjectCard_module = __webpack_require__(86373);
;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherProjectCard/LauncherProjectCard.module.scss

      
      
      
      
      
      
      
      
      

var LauncherProjectCard_module_options = {};

LauncherProjectCard_module_options.styleTagTransform = (styleTagTransform_default());
LauncherProjectCard_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      LauncherProjectCard_module_options.insert = insertBySelector_default().bind(null, "head");
    
LauncherProjectCard_module_options.domAPI = (styleDomAPI_default());
LauncherProjectCard_module_options.insertStyleElement = (insertStyleElement_default());

var LauncherProjectCard_module_update = injectStylesIntoStyleTag_default()(LauncherProjectCard_module/* default */.A, LauncherProjectCard_module_options);




       /* harmony default export */ const LauncherProjectCard_LauncherProjectCard_module = (LauncherProjectCard_module/* default */.A && LauncherProjectCard_module/* default */.A.locals ? LauncherProjectCard_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherProjectCard/LauncherProjectCard.tsx



















// FIXME: Use the timeSince function from the editor package when this is moved there
function timeSince(date) {
    const date_unix = typeof date === 'number' ? date : date.getTime();
    var seconds = Math.floor((new Date().getTime() - date_unix) / 1000);
    var interval = Math.floor(seconds / 31536000);
    if (interval > 1) {
        return interval + ' years';
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
        return interval + ' months';
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
        return interval + ' days';
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
        return interval + ' hours';
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
        return interval + ' minutes';
    }
    return Math.floor(seconds) + ' seconds';
}
var CloudSyncType;
(function (CloudSyncType) {
    CloudSyncType["None"] = "Local";
    CloudSyncType["Git"] = "Git";
})(CloudSyncType || (CloudSyncType = {}));
function LauncherProjectCard({ id, title, cloudSyncMeta, localPath, lastOpened, pullAmount, pushAmount, uncommittedChangesAmount, imageSrc, contextMenuItems, contributors, onClick, runtimeInfo, onMigrateProject, onOpenReadOnly }) {
    const { tags, getProjectMeta } = useProjectOrganization();
    const [showLegacyDetails, setShowLegacyDetails] = (0,external_react_.useState)(false);
    // Get project tags
    const projectMeta = getProjectMeta(localPath);
    const projectTags = projectMeta ? tags.filter((tag) => projectMeta.tagIds.includes(tag.id)) : [];
    // Determine if this is a legacy project
    const isLegacy = (runtimeInfo === null || runtimeInfo === void 0 ? void 0 : runtimeInfo.version) === 'react17';
    const isDetecting = runtimeInfo === undefined;
    return (external_react_default().createElement(Card, { background: CardBackground.Bg2, hoverBackground: CardBackground.Bg3, onClick: isLegacy
            ? () => {
                // Auto-expand details when user clicks legacy project
                setShowLegacyDetails(true);
            }
            : onClick, UNSAFE_className: isLegacy ? LauncherProjectCard_LauncherProjectCard_module.LegacyCard : undefined },
        external_react_default().createElement(Stack/* Stack */.BJ, { direction: "row" },
            external_react_default().createElement("div", { className: LauncherProjectCard_LauncherProjectCard_module.Image, style: { backgroundImage: `url(${imageSrc})` } }),
            external_react_default().createElement("div", { className: LauncherProjectCard_LauncherProjectCard_module.Details },
                external_react_default().createElement(Columns, { layoutString: "1 1 1", hasXGap: 4 },
                    external_react_default().createElement("div", null,
                        external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: 2, UNSAFE_style: { alignItems: 'center' } },
                            external_react_default().createElement(Title/* Title */.hE, { hasBottomSpacing: true, size: Title/* TitleSize */.uM.Medium }, title),
                            isLegacy && (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: "This project uses React 17 and needs migration" },
                                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.WarningCircle, variant: FeedbackType/* FeedbackType */.M.Danger, size: common_Icon/* IconSize */.lK.Default })))),
                        projectTags.length > 0 && (external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: 2, UNSAFE_style: { marginBottom: 'var(--spacing-2)', flexWrap: 'wrap' } }, projectTags.map((tag) => (external_react_default().createElement(TagPill, { key: tag.id, tag: tag, size: TagPillSize.Small }))))),
                        external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Shy },
                            "Last opened ",
                            timeSince(new Date(lastOpened)),
                            " ago")),
                    external_react_default().createElement("div", null,
                        cloudSyncMeta.type === CloudSyncType.None && (external_react_default().createElement("div", null,
                            external_react_default().createElement(Label/* Label */.JU, { hasBottomSpacing: true }, "None"),
                            external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { alignItems: 'center' }, hasSpacing: 1 },
                                external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.WarningCircle, variant: typography_Text/* TextType */.M2.Shy, size: common_Icon/* IconSize */.lK.Tiny }),
                                external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Shy }, "Project is only local")))),
                        cloudSyncMeta.type === CloudSyncType.Git && (external_react_default().createElement("div", { className: LauncherProjectCard_LauncherProjectCard_module.TypeDisplay },
                            external_react_default().createElement(TextButton, { label: "Open Git repo", size: TextButtonSize.Small, icon: common_Icon/* IconName */.$M.ExternalLink, onClick: (e) => {
                                    e.stopPropagation();
                                    alert('FIXME: Link to repo?');
                                } }))),
                        external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: 4, UNSAFE_style: { paddingLeft: 4 } },
                            Boolean(pullAmount) && (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: `${pullAmount} unpulled commits`, showAfterMs: 200, UNSAFE_className: LauncherProjectCard_LauncherProjectCard_module.VersionControlTooltip },
                                external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { alignItems: 'center' } },
                                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CloudDownload, variant: FeedbackType/* FeedbackType */.M.Notice, size: common_Icon/* IconSize */.lK.Tiny }),
                                    external_react_default().createElement(Label/* Label */.JU, { hasLeftSpacing: Label/* LabelSpacingSize */.Zt.Small, variant: FeedbackType/* FeedbackType */.M.Notice }, String(pullAmount))))),
                            Boolean(pushAmount) && (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: `${pushAmount} unpushed local commits`, showAfterMs: 200, UNSAFE_className: LauncherProjectCard_LauncherProjectCard_module.VersionControlTooltip },
                                external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { alignItems: 'center' } },
                                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CloudUpload, variant: FeedbackType/* FeedbackType */.M.Danger, size: common_Icon/* IconSize */.lK.Tiny }),
                                    external_react_default().createElement(Label/* Label */.JU, { hasLeftSpacing: Label/* LabelSpacingSize */.Zt.Small, variant: FeedbackType/* FeedbackType */.M.Danger }, String(pushAmount))))),
                            Boolean(uncommittedChangesAmount) && (external_react_default().createElement(Tooltip/* Tooltip */.m, { content: `${uncommittedChangesAmount} uncommitted changes`, showAfterMs: 200, UNSAFE_className: LauncherProjectCard_LauncherProjectCard_module.VersionControlTooltip },
                                external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { alignItems: 'center' } },
                                    external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.WarningCircle, variant: FeedbackType/* FeedbackType */.M.Danger, size: common_Icon/* IconSize */.lK.Tiny, UNSAFE_className: LauncherProjectCard_LauncherProjectCard_module.VersionControlTooltip }),
                                    external_react_default().createElement(Label/* Label */.JU, { hasLeftSpacing: Label/* LabelSpacingSize */.Zt.Small, variant: FeedbackType/* FeedbackType */.M.Danger }, String(uncommittedChangesAmount))))))),
                    external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { justifyContent: 'space-between', alignItems: 'center' }, hasSpacing: 4 },
                        external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { alignItems: 'center' }, hasSpacing: 2 },
                            external_react_default().createElement(UserBadgeList, { badges: contributors || [{ name: 'Tore Knudsen', email: 'tore@noodl.net', id: 'Tore' }], size: UserBadgeSize.Medium, maxVisible: 4 }),
                            !Boolean(contributors) && external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Shy }, "(Only you)")),
                        Boolean(contextMenuItems) && (external_react_default().createElement("div", null,
                            external_react_default().createElement(ContextMenu/* ContextMenu */.t, { renderDirection: BaseDialog/* DialogRenderDirection */.K1.Below, menuItems: contextMenuItems }))))),
                isLegacy && (external_react_default().createElement("div", { className: LauncherProjectCard_LauncherProjectCard_module.LegacyBanner },
                    external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: 2, UNSAFE_style: { alignItems: 'center', flex: 1 } },
                        external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.WarningCircle, variant: FeedbackType/* FeedbackType */.M.Danger, size: common_Icon/* IconSize */.lK.Small }),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, "React 17 (Legacy Runtime)")),
                    external_react_default().createElement(TextButton, { label: showLegacyDetails ? 'Less' : 'Options', size: TextButtonSize.Small, onClick: (e) => {
                            e.stopPropagation();
                            setShowLegacyDetails(!showLegacyDetails);
                        } }))),
                isLegacy && showLegacyDetails && (external_react_default().createElement("div", { className: LauncherProjectCard_LauncherProjectCard_module.LegacyDetails },
                    external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Shy, size: Label/* LabelSize */.IV.Default }, "This project needs migration to work with OpenNoodl 1.2+. Your original project will remain untouched."),
                    external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: 2, UNSAFE_style: { marginTop: 'var(--spacing-3)' } },
                        external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Migrate Project", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, onClick: (e) => {
                                e.stopPropagation();
                                onMigrateProject === null || onMigrateProject === void 0 ? void 0 : onMigrateProject();
                            } }),
                        external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "View Read-Only", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: (e) => {
                                e.stopPropagation();
                                onOpenReadOnly === null || onOpenReadOnly === void 0 ? void 0 : onOpenReadOnly();
                            } }),
                        external_react_default().createElement(TextButton, { label: "Learn More", size: TextButtonSize.Small, icon: common_Icon/* IconName */.$M.ExternalLink, onClick: (e) => {
                                e.stopPropagation();
                                // TODO: Open documentation
                                window.open('https://docs.opennoodl.com/migration', '_blank');
                            } }))))))));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherProjectCard/index.ts


;// ../noodl-core-ui/src/preview/launcher/Launcher/hooks/useGitHubRepos.ts
/**
 * useGitHubRepos Hook
 *
 * Fetches and manages GitHub repositories for the authenticated user,
 * including personal repos and organization repos.
 * Detects Noodl projects by checking for project.json or nodegx.project.json.
 *
 * @module noodl-core-ui/preview/launcher/Launcher/hooks
 */

/**
 * Hook to fetch GitHub repositories and detect Noodl projects
 *
 * @param client - GitHub client instance
 * @param isAuthenticated - Whether user is authenticated with GitHub
 */
function useGitHubRepos(client, isAuthenticated) {
    const [personalRepos, setPersonalRepos] = (0,external_react_.useState)([]);
    const [organizations, setOrganizations] = (0,external_react_.useState)([]);
    const [isLoading, setIsLoading] = (0,external_react_.useState)(false);
    const [error, setError] = (0,external_react_.useState)(null);
    // Track ongoing Noodl checks to avoid duplicates
    const noodlCheckQueue = (0,external_react_.useRef)(new Map());
    /**
     * Check if a repo is a Noodl project (with deduplication)
     */
    const checkIfNoodlProject = (0,external_react_.useCallback)(async (owner, repo) => {
        if (!client)
            return false;
        const key = `${owner}/${repo}`;
        // Return existing promise if already checking
        if (noodlCheckQueue.current.has(key)) {
            return noodlCheckQueue.current.get(key);
        }
        // Start new check
        const checkPromise = client.isNoodlProject(owner, repo);
        noodlCheckQueue.current.set(key, checkPromise);
        try {
            const result = await checkPromise;
            return result;
        }
        finally {
            noodlCheckQueue.current.delete(key);
        }
    }, [client]);
    /**
     * Map GitHubRepo to NoodlGitHubRepo
     */
    const mapRepo = (0,external_react_.useCallback)((repo, source) => {
        return {
            ...repo,
            isNoodlProject: null,
            isCheckingNoodl: false,
            source
        };
    }, []);
    /**
     * Check Noodl status for a batch of repos (rate-limit friendly)
     */
    const checkNoodlStatusForRepos = (0,external_react_.useCallback)(async (repos, updateFn) => {
        console.log('🔍 [checkNoodlStatusForRepos] Starting check for', repos.length, 'repos');
        // Check repos sequentially to avoid rate limits
        for (const repo of repos) {
            if (repo.isNoodlProject !== null)
                continue; // Already checked
            try {
                const isNoodl = await checkIfNoodlProject(repo.owner.login, repo.name);
                console.log('🔍 [checkNoodlStatusForRepos]', repo.full_name, '- isNoodl:', isNoodl);
                updateFn(repo.id, isNoodl);
                // Small delay between checks to be rate-limit friendly
                await new Promise((resolve) => setTimeout(resolve, 100));
            }
            catch (err) {
                // On error, mark as not a Noodl project
                console.error('❌ [checkNoodlStatusForRepos] Error checking', repo.full_name, err);
                updateFn(repo.id, false);
            }
        }
        console.log('✅ [checkNoodlStatusForRepos] Finished checking repos');
    }, [checkIfNoodlProject]);
    /**
     * Fetch all repos (personal + org)
     */
    const fetchRepos = (0,external_react_.useCallback)(async () => {
        var _a, _b;
        console.log('🔍 [useGitHubRepos] fetchRepos called', {
            hasClient: !!client,
            isAuthenticated
        });
        if (!client || !isAuthenticated) {
            console.log('🔍 [useGitHubRepos] Skipping fetch - not authenticated or no client');
            setPersonalRepos([]);
            setOrganizations([]);
            setError(null);
            return;
        }
        setIsLoading(true);
        setError(null);
        try {
            console.log('🔍 [useGitHubRepos] Fetching personal repos and orgs...');
            // Fetch personal repos and orgs in parallel
            const [reposResponse, orgsResponse] = await Promise.all([
                client.listRepositories({ per_page: 100, sort: 'updated' }),
                client.listOrganizations()
            ]);
            console.log('🔍 [useGitHubRepos] API responses:', {
                personalRepoCount: ((_a = reposResponse === null || reposResponse === void 0 ? void 0 : reposResponse.data) === null || _a === void 0 ? void 0 : _a.length) || 0,
                orgCount: ((_b = orgsResponse === null || orgsResponse === void 0 ? void 0 : orgsResponse.data) === null || _b === void 0 ? void 0 : _b.length) || 0
            });
            // Map personal repos
            const mappedPersonalRepos = reposResponse.data.map((r) => mapRepo(r, 'personal'));
            setPersonalRepos(mappedPersonalRepos);
            // Initialize orgs (repos will be loaded on-demand or in parallel)
            const mappedOrgs = orgsResponse.data.map((org) => ({
                ...org,
                repos: [],
                isLoading: true,
                error: null
            }));
            setOrganizations(mappedOrgs);
            // Fetch org repos in parallel
            const orgRepoPromises = orgsResponse.data.map(async (org) => {
                try {
                    const orgRepos = await client.listOrganizationRepositories(org.login, { per_page: 100 });
                    return {
                        orgLogin: org.login,
                        repos: orgRepos.data.map((r) => mapRepo(r, org.login)),
                        error: null
                    };
                }
                catch (err) {
                    return {
                        orgLogin: org.login,
                        repos: [],
                        error: err instanceof Error ? err.message : 'Failed to load repos'
                    };
                }
            });
            const orgResults = await Promise.all(orgRepoPromises);
            // Update orgs with their repos
            setOrganizations((prev) => prev.map((org) => {
                const result = orgResults.find((r) => r.orgLogin === org.login);
                if (result) {
                    return {
                        ...org,
                        repos: result.repos,
                        isLoading: false,
                        error: result.error
                    };
                }
                return { ...org, isLoading: false };
            }));
            // Start checking Noodl status for personal repos
            const updatePersonalRepo = (repoId, isNoodl) => {
                setPersonalRepos((prev) => prev.map((r) => (r.id === repoId ? { ...r, isNoodlProject: isNoodl, isCheckingNoodl: false } : r)));
            };
            // Check personal repos
            checkNoodlStatusForRepos(mappedPersonalRepos, updatePersonalRepo);
            // Check org repos
            for (const result of orgResults) {
                const updateOrgRepo = (repoId, isNoodl) => {
                    setOrganizations((prev) => prev.map((org) => {
                        if (org.login === result.orgLogin) {
                            return {
                                ...org,
                                repos: org.repos.map((r) => r.id === repoId ? { ...r, isNoodlProject: isNoodl, isCheckingNoodl: false } : r)
                            };
                        }
                        return org;
                    }));
                };
                checkNoodlStatusForRepos(result.repos, updateOrgRepo);
            }
        }
        catch (err) {
            setError(err instanceof Error ? err.message : 'Failed to fetch repositories');
        }
        finally {
            setIsLoading(false);
        }
    }, [client, isAuthenticated, mapRepo, checkNoodlStatusForRepos]);
    // Fetch on mount and when auth changes
    (0,external_react_.useEffect)(() => {
        fetchRepos();
    }, [fetchRepos]);
    // Compute derived values
    const allRepos = [...personalRepos, ...organizations.flatMap((org) => org.repos)];
    const noodlProjects = allRepos.filter((repo) => repo.isNoodlProject === true);
    return {
        noodlProjects,
        allRepos,
        organizations,
        personalRepos,
        isLoading,
        error,
        refresh: fetchRepos,
        checkIfNoodlProject
    };
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/layout/TabBar/TabBar.module.scss
var TabBar_module = __webpack_require__(31303);
;// ../noodl-core-ui/src/components/layout/TabBar/TabBar.module.scss

      
      
      
      
      
      
      
      
      

var TabBar_module_options = {};

TabBar_module_options.styleTagTransform = (styleTagTransform_default());
TabBar_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      TabBar_module_options.insert = insertBySelector_default().bind(null, "head");
    
TabBar_module_options.domAPI = (styleDomAPI_default());
TabBar_module_options.insertStyleElement = (insertStyleElement_default());

var TabBar_module_update = injectStylesIntoStyleTag_default()(TabBar_module/* default */.A, TabBar_module_options);




       /* harmony default export */ const TabBar_TabBar_module = (TabBar_module/* default */.A && TabBar_module/* default */.A.locals ? TabBar_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/layout/TabBar/TabBar.tsx
/**
 * TabBar - Modern horizontal tab navigation component
 *
 * A clean, accessible tab bar for switching between views.
 * Supports keyboard navigation, icons, and state persistence.
 *
 * @module noodl-core-ui/components/layout
 */




function TabBar({ items, activeItemId, onChange, size = 'medium', UNSAFE_className, UNSAFE_style }) {
    const tabRefs = (0,external_react_.useRef)({});
    /**
     * Handle keyboard navigation
     */
    const handleKeyDown = (event, currentIndex) => {
        var _a;
        const enabledItems = items.filter((item) => !item.disabled);
        const currentEnabledIndex = enabledItems.findIndex((item) => item.id === items[currentIndex].id);
        let newIndex = currentEnabledIndex;
        switch (event.key) {
            case 'ArrowLeft':
                event.preventDefault();
                newIndex = currentEnabledIndex > 0 ? currentEnabledIndex - 1 : enabledItems.length - 1;
                break;
            case 'ArrowRight':
                event.preventDefault();
                newIndex = currentEnabledIndex < enabledItems.length - 1 ? currentEnabledIndex + 1 : 0;
                break;
            case 'Home':
                event.preventDefault();
                newIndex = 0;
                break;
            case 'End':
                event.preventDefault();
                newIndex = enabledItems.length - 1;
                break;
            default:
                return;
        }
        const newItem = enabledItems[newIndex];
        if (newItem) {
            onChange(newItem.id);
            (_a = tabRefs.current[newItem.id]) === null || _a === void 0 ? void 0 : _a.focus();
        }
    };
    return (external_react_default().createElement("div", { className: external_classnames_default()(TabBar_TabBar_module['Root'], TabBar_TabBar_module[`is-size-${size}`], UNSAFE_className), style: UNSAFE_style, role: "tablist", "aria-label": "Main navigation" }, items.map((item, index) => {
        const isActive = item.id === activeItemId;
        const isDisabled = item.disabled;
        return (external_react_default().createElement("button", { key: item.id, ref: (el) => {
                tabRefs.current[item.id] = el;
            }, className: external_classnames_default()(TabBar_TabBar_module['Tab'], {
                [TabBar_TabBar_module['is-active']]: isActive,
                [TabBar_TabBar_module['is-disabled']]: isDisabled
            }), onClick: () => !isDisabled && onChange(item.id), onKeyDown: (e) => handleKeyDown(e, index), disabled: isDisabled, role: "tab", "aria-selected": isActive, "aria-disabled": isDisabled, tabIndex: isActive ? 0 : -1, "data-test": item.testId },
            item.icon && (external_react_default().createElement("span", { className: TabBar_TabBar_module['Tab-icon'] },
                external_react_default().createElement(common_Icon/* Icon */.In, { icon: item.icon }))),
            external_react_default().createElement("span", { className: TabBar_TabBar_module['Tab-label'] }, item.label)));
    })));
}

;// ../noodl-core-ui/src/components/layout/TabBar/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/inputs/ExternalLink/ExternalLink.module.scss
var ExternalLink_module = __webpack_require__(64808);
;// ../noodl-core-ui/src/components/inputs/ExternalLink/ExternalLink.module.scss

      
      
      
      
      
      
      
      
      

var ExternalLink_module_options = {};

ExternalLink_module_options.styleTagTransform = (styleTagTransform_default());
ExternalLink_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ExternalLink_module_options.insert = insertBySelector_default().bind(null, "head");
    
ExternalLink_module_options.domAPI = (styleDomAPI_default());
ExternalLink_module_options.insertStyleElement = (insertStyleElement_default());

var ExternalLink_module_update = injectStylesIntoStyleTag_default()(ExternalLink_module/* default */.A, ExternalLink_module_options);




       /* harmony default export */ const ExternalLink_ExternalLink_module = (ExternalLink_module/* default */.A && ExternalLink_module/* default */.A.locals ? ExternalLink_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/inputs/ExternalLink/ExternalLink.tsx






function ExternalLink({ children, href, testId, UNSAFE_className, UNSAFE_style }) {
    const parsedHref = (0,useParsedHref/* default */.A)(href);
    function handleClick() {
        src.platform.openExternal(parsedHref);
    }
    return (external_react_default().createElement("a", { className: external_classnames_default()(ExternalLink_ExternalLink_module['Root'], UNSAFE_className), onClick: handleClick, target: "_blank", "data-test": testId, style: UNSAFE_style },
        children,
        external_react_default().createElement(common_Icon/* Icon */.In, { UNSAFE_className: ExternalLink_ExternalLink_module['Icon'], icon: common_Icon/* IconName */.$M.ExternalLink, size: common_Icon/* IconSize */.lK.Tiny })));
}

;// ../noodl-core-ui/src/components/inputs/ExternalLink/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherFooter/LauncherFooter.module.scss
var LauncherFooter_module = __webpack_require__(32917);
;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherFooter/LauncherFooter.module.scss

      
      
      
      
      
      
      
      
      

var LauncherFooter_module_options = {};

LauncherFooter_module_options.styleTagTransform = (styleTagTransform_default());
LauncherFooter_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      LauncherFooter_module_options.insert = insertBySelector_default().bind(null, "head");
    
LauncherFooter_module_options.domAPI = (styleDomAPI_default());
LauncherFooter_module_options.insertStyleElement = (insertStyleElement_default());

var LauncherFooter_module_update = injectStylesIntoStyleTag_default()(LauncherFooter_module/* default */.A, LauncherFooter_module_options);




       /* harmony default export */ const LauncherFooter_LauncherFooter_module = (LauncherFooter_module/* default */.A && LauncherFooter_module/* default */.A.locals ? LauncherFooter_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherFooter/LauncherFooter.tsx
/**
 * LauncherFooter - Bottom footer for the launcher dashboard
 *
 * Contains resource links (Documentation, YouTube, Discord)
 *
 * @module noodl-core-ui/preview/launcher
 */




function LauncherFooter({}) {
    return (external_react_default().createElement("div", { className: LauncherFooter_LauncherFooter_module['Root'] },
        external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_className: LauncherFooter_LauncherFooter_module['Content'], hasSpacing: true },
            external_react_default().createElement("span", { className: LauncherFooter_LauncherFooter_module['Label'] }, "Resources:"),
            external_react_default().createElement(ExternalLink, { href: "https://docs.noodl.net" }, "Documentation"),
            external_react_default().createElement(ExternalLink, { href: "https://youtube.com/@noodlapp" }, "YouTube"),
            external_react_default().createElement(ExternalLink, { href: "https://discord.gg/noodl" }, "Discord"))));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherFooter/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/components/common/Logo/Logo.module.scss
var Logo_module = __webpack_require__(19448);
;// ../noodl-core-ui/src/components/common/Logo/Logo.module.scss

      
      
      
      
      
      
      
      
      

var Logo_module_options = {};

Logo_module_options.styleTagTransform = (styleTagTransform_default());
Logo_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      Logo_module_options.insert = insertBySelector_default().bind(null, "head");
    
Logo_module_options.domAPI = (styleDomAPI_default());
Logo_module_options.insertStyleElement = (insertStyleElement_default());

var Logo_module_update = injectStylesIntoStyleTag_default()(Logo_module/* default */.A, Logo_module_options);




       /* harmony default export */ const Logo_Logo_module = (Logo_module/* default */.A && Logo_module/* default */.A.locals ? Logo_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/components/common/Logo/Logo.tsx



var LogoVariant;
(function (LogoVariant) {
    LogoVariant["Default"] = "default";
    LogoVariant["Inverted"] = "inverted";
    LogoVariant["Grayscale"] = "grayscale";
})(LogoVariant || (LogoVariant = {}));
var LogoSize;
(function (LogoSize) {
    LogoSize["Small"] = "small";
    LogoSize["Medium"] = "medium";
    LogoSize["Large"] = "large";
})(LogoSize || (LogoSize = {}));
function Logo({ variant = LogoVariant.Default, size = LogoSize.Medium, onClick, UNSAFE_className, UNSAFE_style }) {
    function VariantIcon(props) {
        switch (variant) {
            default:
            case LogoVariant.Default:
                return external_react_default().createElement(DefaultIcon, null);
            case LogoVariant.Inverted:
                return external_react_default().createElement(InvertedIcon, null);
            case LogoVariant.Grayscale:
                return external_react_default().createElement(GrayscaleIcon, null);
        }
    }
    return (external_react_default().createElement("div", { className: external_classnames_default()([
            Logo_Logo_module['Root'],
            Logo_Logo_module[`is-variant-${variant}`],
            Logo_Logo_module[`is-size-${size}`],
            UNSAFE_className
        ]), onClick: onClick, style: UNSAFE_style },
        external_react_default().createElement(VariantIcon, null)));
}
const DefaultIcon = external_react_default().memo(function () {
    return (external_react_default().createElement("svg", { version: "1.0", xmlns: "http://www.w3.org/2000/svg", width: "60px", height: "60px", viewBox: "0 0 512 512", preserveAspectRatio: "xMidYMid meet" },
        external_react_default().createElement("metadata", null, "Created by potrace 1.10, written by Peter Selinger 2001-2011"),
        external_react_default().createElement("g", { transform: "scale(0.16, -0.16) translate(0, -3200)", fill: "#ffffff", stroke: "none" },
            external_react_default().createElement("path", { d: "M1345 3084 c-122 -18 -294 -61 -305 -76 -3 -4 -39 -21 -79 -38 -140\n-57 -290 -156 -436 -286 -173 -155 -350 -399 -422 -583 -114 -292 -133 -639\n-51 -961 21 -86 90 -254 139 -344 444 -805 1454 -1042 2175 -511 316 233 531\n574 606 962 34 176 32 438 -4 614 -43 205 -134 416 -247 565 -71 95 -338 356\n-421 411 -264 175 -467 241 -765 248 -88 2 -173 1 -190 -1z m304 -207 c108\n-67 238 -259 320 -472 17 -43 29 -80 28 -82 -2 -1 -39 -9 -82 -18 -43 -8 -86\n-17 -96 -20 -14 -5 -20 2 -29 36 -25 93 -99 169 -189 196 -151 44 -312 -39\n-358 -184 -14 -44 -20 -52 -37 -48 -12 2 -54 10 -94 16 -41 7 -76 18 -78 24\n-14 35 121 310 209 427 124 165 268 209 406 125z m-539 -52 c0 -3 -23 -40 -52\n-82 -55 -82 -124 -224 -153 -313 -23 -73 -21 -70 -58 -58 -55 18 -234 105\n-241 116 -8 14 58 79 158 153 94 71 179 122 266 160 67 29 80 33 80 24z m913\n-40 c109 -54 243 -148 335 -235 l66 -62 -59 -31 c-73 -37 -194 -87 -209 -87\n-6 0 -24 35 -40 78 -40 108 -110 247 -154 307 -70 93 -68 94 61 30z m-1458\n-449 c43 -25 112 -57 154 -72 42 -15 87 -31 100 -36 17 -6 21 -13 16 -26 -14\n-35 -53 -200 -65 -274 l-12 -76 -52 5 c-85 9 -158 -18 -221 -81 -34 -34 -58\n-68 -66 -95 -15 -50 -24 -53 -139 -49 l-85 3 3 55 c5 90 66 310 116 412 37 77\n160 278 170 278 1 0 38 -20 81 -44z m1020 10 c54 -35 74 -128 39 -181 -36 -55\n-120 -72 -179 -35 -37 23 -57 63 -57 115 0 97 114 155 197 101z m992 -42 c61\n-85 148 -266 176 -364 31 -107 61 -275 53 -295 -4 -12 -24 -15 -95 -15 l-90 0\n-31 64 c-51 107 -130 158 -249 162 l-75 3 -18 108 c-16 93 -37 190 -53 243 -4\n12 16 22 78 43 45 16 118 48 162 71 44 24 85 42 90 41 6 -1 29 -28 52 -61z\nm-1479 -149 c46 -8 96 -15 111 -15 21 0 31 -10 53 -50 30 -53 95 -108 140\n-117 39 -8 50 -25 46 -74 -3 -40 -5 -43 -45 -56 -63 -21 -138 -93 -161 -156\nl-20 -52 -122 0 -122 0 -12 37 c-7 20 -27 56 -44 79 -20 26 -30 50 -27 63 51\n235 78 353 82 359 3 5 12 6 20 3 9 -4 54 -13 101 -21z m965 -32 c14 -51 46\n-209 60 -298 4 -23 -2 -38 -29 -68 -18 -22 -39 -58 -47 -81 l-14 -41 -111 -3\n-112 -3 -24 55 c-29 66 -92 129 -152 152 l-44 17 0 53 0 53 53 24 c58 27 119\n84 137 128 9 21 19 29 39 29 14 1 67 9 116 19 50 10 95 19 101 20 6 0 19 -25\n27 -56z m-1313 -438 c75 -39 92 -148 32 -207 -79 -80 -222 -21 -222 92 0 93\n107 158 190 115z m821 0 c65 -34 91 -135 48 -189 -61 -78 -165 -73 -220 10\n-37 56 -13 134 53 174 40 24 79 25 119 5z m842 -24 c87 -86 27 -221 -98 -221\n-42 0 -52 4 -81 35 -57 61 -55 132 4 188 33 31 55 37 107 31 26 -3 50 -15 68\n-33z m-1992 -216 c60 -115 150 -169 271 -164 l62 3 18 -120 c10 -65 29 -163\n42 -217 21 -89 22 -99 7 -104 -61 -21 -208 -88 -257 -117 -32 -20 -62 -36 -66\n-36 -12 0 -115 163 -161 255 -51 104 -80 185 -108 303 -22 91 -40 232 -32 245\n2 4 48 6 101 5 l97 -3 26 -50z m808 24 c6 -17 27 -53 47 -80 28 -38 52 -57\n105 -82 l69 -32 0 -51 0 -51 -65 -32 c-72 -36 -128 -98 -145 -161 -10 -36 -11\n-37 -82 -49 -40 -7 -96 -19 -125 -26 -47 -12 -53 -11 -57 4 -13 45 -58 266\n-70 344 l-13 87 33 48 c19 26 34 50 34 54 0 4 4 18 10 32 9 26 10 26 129 26\nl119 0 11 -31z m811 -1 c7 -18 28 -54 47 -81 18 -26 33 -59 33 -75 0 -43 -28\n-218 -51 -319 -22 -101 -23 -101 -89 -84 -19 5 -67 15 -106 21 l-72 11 -16 44\nc-30 77 -69 121 -141 155 -70 33 -71 36 -59 112 5 28 12 38 31 43 63 15 128\n77 172 163 l21 42 109 0 109 0 12 -32z m770 -5 c0 -121 -66 -377 -136 -530\n-26 -58 -110 -203 -139 -241 -1 -1 -49 22 -106 52 -57 30 -134 67 -171 81 -38\n15 -68 30 -68 34 0 3 7 29 16 56 15 52 54 290 54 338 0 27 1 27 63 27 35 0 84\n7 110 16 64 22 135 87 163 151 l24 53 95 0 95 0 0 -37z m-1246 -467 c50 -21\n76 -60 76 -116 0 -138 -185 -180 -244 -55 -31 65 -10 124 59 166 36 23 64 24\n109 5z m-314 -247 c32 -61 99 -123 155 -142 147 -50 292 4 371 139 14 24 29\n44 32 44 4 0 46 -7 95 -17 55 -10 87 -21 87 -29 0 -48 -105 -278 -171 -375\n-88 -130 -170 -186 -286 -196 -128 -10 -228 50 -323 195 -68 103 -180 338\n-180 378 0 7 32 18 78 27 119 22 119 22 142 -24z m-341 -121 c34 -86 103 -226\n150 -307 30 -51 31 -52 9 -46 -42 13 -206 96 -270 137 -72 46 -198 147 -198\n158 0 12 268 145 276 137 1 -1 16 -37 33 -79z m1469 -30 c17 -11 32 -25 32\n-32 0 -18 -175 -156 -261 -206 -71 -42 -209 -103 -216 -96 -2 2 13 27 33 57\n48 72 99 173 141 284 19 49 37 93 39 97 5 7 177 -70 232 -104z" }))));
});
const InvertedIcon = external_react_default().memo(function () {
    return (external_react_default().createElement("svg", { version: "1.0", xmlns: "http://www.w3.org/2000/svg", width: "60px", height: "60px", viewBox: "0 0 512 512", preserveAspectRatio: "xMidYMid meet" },
        external_react_default().createElement("metadata", null, "Created by potrace 1.10, written by Peter Selinger 2001-2011"),
        external_react_default().createElement("g", { transform: "scale(0.16, -0.16) translate(0, -3200)", fill: "#ffffff", stroke: "none" },
            external_react_default().createElement("path", { d: "M1345 3084 c-122 -18 -294 -61 -305 -76 -3 -4 -39 -21 -79 -38 -140\n-57 -290 -156 -436 -286 -173 -155 -350 -399 -422 -583 -114 -292 -133 -639\n-51 -961 21 -86 90 -254 139 -344 444 -805 1454 -1042 2175 -511 316 233 531\n574 606 962 34 176 32 438 -4 614 -43 205 -134 416 -247 565 -71 95 -338 356\n-421 411 -264 175 -467 241 -765 248 -88 2 -173 1 -190 -1z m304 -207 c108\n-67 238 -259 320 -472 17 -43 29 -80 28 -82 -2 -1 -39 -9 -82 -18 -43 -8 -86\n-17 -96 -20 -14 -5 -20 2 -29 36 -25 93 -99 169 -189 196 -151 44 -312 -39\n-358 -184 -14 -44 -20 -52 -37 -48 -12 2 -54 10 -94 16 -41 7 -76 18 -78 24\n-14 35 121 310 209 427 124 165 268 209 406 125z m-539 -52 c0 -3 -23 -40 -52\n-82 -55 -82 -124 -224 -153 -313 -23 -73 -21 -70 -58 -58 -55 18 -234 105\n-241 116 -8 14 58 79 158 153 94 71 179 122 266 160 67 29 80 33 80 24z m913\n-40 c109 -54 243 -148 335 -235 l66 -62 -59 -31 c-73 -37 -194 -87 -209 -87\n-6 0 -24 35 -40 78 -40 108 -110 247 -154 307 -70 93 -68 94 61 30z m-1458\n-449 c43 -25 112 -57 154 -72 42 -15 87 -31 100 -36 17 -6 21 -13 16 -26 -14\n-35 -53 -200 -65 -274 l-12 -76 -52 5 c-85 9 -158 -18 -221 -81 -34 -34 -58\n-68 -66 -95 -15 -50 -24 -53 -139 -49 l-85 3 3 55 c5 90 66 310 116 412 37 77\n160 278 170 278 1 0 38 -20 81 -44z m1020 10 c54 -35 74 -128 39 -181 -36 -55\n-120 -72 -179 -35 -37 23 -57 63 -57 115 0 97 114 155 197 101z m992 -42 c61\n-85 148 -266 176 -364 31 -107 61 -275 53 -295 -4 -12 -24 -15 -95 -15 l-90 0\n-31 64 c-51 107 -130 158 -249 162 l-75 3 -18 108 c-16 93 -37 190 -53 243 -4\n12 16 22 78 43 45 16 118 48 162 71 44 24 85 42 90 41 6 -1 29 -28 52 -61z\nm-1479 -149 c46 -8 96 -15 111 -15 21 0 31 -10 53 -50 30 -53 95 -108 140\n-117 39 -8 50 -25 46 -74 -3 -40 -5 -43 -45 -56 -63 -21 -138 -93 -161 -156\nl-20 -52 -122 0 -122 0 -12 37 c-7 20 -27 56 -44 79 -20 26 -30 50 -27 63 51\n235 78 353 82 359 3 5 12 6 20 3 9 -4 54 -13 101 -21z m965 -32 c14 -51 46\n-209 60 -298 4 -23 -2 -38 -29 -68 -18 -22 -39 -58 -47 -81 l-14 -41 -111 -3\n-112 -3 -24 55 c-29 66 -92 129 -152 152 l-44 17 0 53 0 53 53 24 c58 27 119\n84 137 128 9 21 19 29 39 29 14 1 67 9 116 19 50 10 95 19 101 20 6 0 19 -25\n27 -56z m-1313 -438 c75 -39 92 -148 32 -207 -79 -80 -222 -21 -222 92 0 93\n107 158 190 115z m821 0 c65 -34 91 -135 48 -189 -61 -78 -165 -73 -220 10\n-37 56 -13 134 53 174 40 24 79 25 119 5z m842 -24 c87 -86 27 -221 -98 -221\n-42 0 -52 4 -81 35 -57 61 -55 132 4 188 33 31 55 37 107 31 26 -3 50 -15 68\n-33z m-1992 -216 c60 -115 150 -169 271 -164 l62 3 18 -120 c10 -65 29 -163\n42 -217 21 -89 22 -99 7 -104 -61 -21 -208 -88 -257 -117 -32 -20 -62 -36 -66\n-36 -12 0 -115 163 -161 255 -51 104 -80 185 -108 303 -22 91 -40 232 -32 245\n2 4 48 6 101 5 l97 -3 26 -50z m808 24 c6 -17 27 -53 47 -80 28 -38 52 -57\n105 -82 l69 -32 0 -51 0 -51 -65 -32 c-72 -36 -128 -98 -145 -161 -10 -36 -11\n-37 -82 -49 -40 -7 -96 -19 -125 -26 -47 -12 -53 -11 -57 4 -13 45 -58 266\n-70 344 l-13 87 33 48 c19 26 34 50 34 54 0 4 4 18 10 32 9 26 10 26 129 26\nl119 0 11 -31z m811 -1 c7 -18 28 -54 47 -81 18 -26 33 -59 33 -75 0 -43 -28\n-218 -51 -319 -22 -101 -23 -101 -89 -84 -19 5 -67 15 -106 21 l-72 11 -16 44\nc-30 77 -69 121 -141 155 -70 33 -71 36 -59 112 5 28 12 38 31 43 63 15 128\n77 172 163 l21 42 109 0 109 0 12 -32z m770 -5 c0 -121 -66 -377 -136 -530\n-26 -58 -110 -203 -139 -241 -1 -1 -49 22 -106 52 -57 30 -134 67 -171 81 -38\n15 -68 30 -68 34 0 3 7 29 16 56 15 52 54 290 54 338 0 27 1 27 63 27 35 0 84\n7 110 16 64 22 135 87 163 151 l24 53 95 0 95 0 0 -37z m-1246 -467 c50 -21\n76 -60 76 -116 0 -138 -185 -180 -244 -55 -31 65 -10 124 59 166 36 23 64 24\n109 5z m-314 -247 c32 -61 99 -123 155 -142 147 -50 292 4 371 139 14 24 29\n44 32 44 4 0 46 -7 95 -17 55 -10 87 -21 87 -29 0 -48 -105 -278 -171 -375\n-88 -130 -170 -186 -286 -196 -128 -10 -228 50 -323 195 -68 103 -180 338\n-180 378 0 7 32 18 78 27 119 22 119 22 142 -24z m-341 -121 c34 -86 103 -226\n150 -307 30 -51 31 -52 9 -46 -42 13 -206 96 -270 137 -72 46 -198 147 -198\n158 0 12 268 145 276 137 1 -1 16 -37 33 -79z m1469 -30 c17 -11 32 -25 32\n-32 0 -18 -175 -156 -261 -206 -71 -42 -209 -103 -216 -96 -2 2 13 27 33 57\n48 72 99 173 141 284 19 49 37 93 39 97 5 7 177 -70 232 -104z" }))));
});
const GrayscaleIcon = external_react_default().memo(function () {
    return (external_react_default().createElement("svg", { version: "1.0", xmlns: "http://www.w3.org/2000/svg", width: "60px", height: "60px", viewBox: "0 0 512 512", preserveAspectRatio: "xMidYMid meet" },
        external_react_default().createElement("metadata", null, "Created by potrace 1.10, written by Peter Selinger 2001-2011"),
        external_react_default().createElement("g", { transform: "scale(0.16, -0.16) translate(0, -3200)", fill: "#ffffff", stroke: "none" },
            external_react_default().createElement("path", { d: "M1345 3084 c-122 -18 -294 -61 -305 -76 -3 -4 -39 -21 -79 -38 -140\n-57 -290 -156 -436 -286 -173 -155 -350 -399 -422 -583 -114 -292 -133 -639\n-51 -961 21 -86 90 -254 139 -344 444 -805 1454 -1042 2175 -511 316 233 531\n574 606 962 34 176 32 438 -4 614 -43 205 -134 416 -247 565 -71 95 -338 356\n-421 411 -264 175 -467 241 -765 248 -88 2 -173 1 -190 -1z m304 -207 c108\n-67 238 -259 320 -472 17 -43 29 -80 28 -82 -2 -1 -39 -9 -82 -18 -43 -8 -86\n-17 -96 -20 -14 -5 -20 2 -29 36 -25 93 -99 169 -189 196 -151 44 -312 -39\n-358 -184 -14 -44 -20 -52 -37 -48 -12 2 -54 10 -94 16 -41 7 -76 18 -78 24\n-14 35 121 310 209 427 124 165 268 209 406 125z m-539 -52 c0 -3 -23 -40 -52\n-82 -55 -82 -124 -224 -153 -313 -23 -73 -21 -70 -58 -58 -55 18 -234 105\n-241 116 -8 14 58 79 158 153 94 71 179 122 266 160 67 29 80 33 80 24z m913\n-40 c109 -54 243 -148 335 -235 l66 -62 -59 -31 c-73 -37 -194 -87 -209 -87\n-6 0 -24 35 -40 78 -40 108 -110 247 -154 307 -70 93 -68 94 61 30z m-1458\n-449 c43 -25 112 -57 154 -72 42 -15 87 -31 100 -36 17 -6 21 -13 16 -26 -14\n-35 -53 -200 -65 -274 l-12 -76 -52 5 c-85 9 -158 -18 -221 -81 -34 -34 -58\n-68 -66 -95 -15 -50 -24 -53 -139 -49 l-85 3 3 55 c5 90 66 310 116 412 37 77\n160 278 170 278 1 0 38 -20 81 -44z m1020 10 c54 -35 74 -128 39 -181 -36 -55\n-120 -72 -179 -35 -37 23 -57 63 -57 115 0 97 114 155 197 101z m992 -42 c61\n-85 148 -266 176 -364 31 -107 61 -275 53 -295 -4 -12 -24 -15 -95 -15 l-90 0\n-31 64 c-51 107 -130 158 -249 162 l-75 3 -18 108 c-16 93 -37 190 -53 243 -4\n12 16 22 78 43 45 16 118 48 162 71 44 24 85 42 90 41 6 -1 29 -28 52 -61z\nm-1479 -149 c46 -8 96 -15 111 -15 21 0 31 -10 53 -50 30 -53 95 -108 140\n-117 39 -8 50 -25 46 -74 -3 -40 -5 -43 -45 -56 -63 -21 -138 -93 -161 -156\nl-20 -52 -122 0 -122 0 -12 37 c-7 20 -27 56 -44 79 -20 26 -30 50 -27 63 51\n235 78 353 82 359 3 5 12 6 20 3 9 -4 54 -13 101 -21z m965 -32 c14 -51 46\n-209 60 -298 4 -23 -2 -38 -29 -68 -18 -22 -39 -58 -47 -81 l-14 -41 -111 -3\n-112 -3 -24 55 c-29 66 -92 129 -152 152 l-44 17 0 53 0 53 53 24 c58 27 119\n84 137 128 9 21 19 29 39 29 14 1 67 9 116 19 50 10 95 19 101 20 6 0 19 -25\n27 -56z m-1313 -438 c75 -39 92 -148 32 -207 -79 -80 -222 -21 -222 92 0 93\n107 158 190 115z m821 0 c65 -34 91 -135 48 -189 -61 -78 -165 -73 -220 10\n-37 56 -13 134 53 174 40 24 79 25 119 5z m842 -24 c87 -86 27 -221 -98 -221\n-42 0 -52 4 -81 35 -57 61 -55 132 4 188 33 31 55 37 107 31 26 -3 50 -15 68\n-33z m-1992 -216 c60 -115 150 -169 271 -164 l62 3 18 -120 c10 -65 29 -163\n42 -217 21 -89 22 -99 7 -104 -61 -21 -208 -88 -257 -117 -32 -20 -62 -36 -66\n-36 -12 0 -115 163 -161 255 -51 104 -80 185 -108 303 -22 91 -40 232 -32 245\n2 4 48 6 101 5 l97 -3 26 -50z m808 24 c6 -17 27 -53 47 -80 28 -38 52 -57\n105 -82 l69 -32 0 -51 0 -51 -65 -32 c-72 -36 -128 -98 -145 -161 -10 -36 -11\n-37 -82 -49 -40 -7 -96 -19 -125 -26 -47 -12 -53 -11 -57 4 -13 45 -58 266\n-70 344 l-13 87 33 48 c19 26 34 50 34 54 0 4 4 18 10 32 9 26 10 26 129 26\nl119 0 11 -31z m811 -1 c7 -18 28 -54 47 -81 18 -26 33 -59 33 -75 0 -43 -28\n-218 -51 -319 -22 -101 -23 -101 -89 -84 -19 5 -67 15 -106 21 l-72 11 -16 44\nc-30 77 -69 121 -141 155 -70 33 -71 36 -59 112 5 28 12 38 31 43 63 15 128\n77 172 163 l21 42 109 0 109 0 12 -32z m770 -5 c0 -121 -66 -377 -136 -530\n-26 -58 -110 -203 -139 -241 -1 -1 -49 22 -106 52 -57 30 -134 67 -171 81 -38\n15 -68 30 -68 34 0 3 7 29 16 56 15 52 54 290 54 338 0 27 1 27 63 27 35 0 84\n7 110 16 64 22 135 87 163 151 l24 53 95 0 95 0 0 -37z m-1246 -467 c50 -21\n76 -60 76 -116 0 -138 -185 -180 -244 -55 -31 65 -10 124 59 166 36 23 64 24\n109 5z m-314 -247 c32 -61 99 -123 155 -142 147 -50 292 4 371 139 14 24 29\n44 32 44 4 0 46 -7 95 -17 55 -10 87 -21 87 -29 0 -48 -105 -278 -171 -375\n-88 -130 -170 -186 -286 -196 -128 -10 -228 50 -323 195 -68 103 -180 338\n-180 378 0 7 32 18 78 27 119 22 119 22 142 -24z m-341 -121 c34 -86 103 -226\n150 -307 30 -51 31 -52 9 -46 -42 13 -206 96 -270 137 -72 46 -198 147 -198\n158 0 12 268 145 276 137 1 -1 16 -37 33 -79z m1469 -30 c17 -11 32 -25 32\n-32 0 -18 -175 -156 -261 -206 -71 -42 -209 -103 -216 -96 -2 2 13 27 33 57\n48 72 99 173 141 284 19 49 37 93 39 97 5 7 177 -70 232 -104z" }))));
});

;// ../noodl-core-ui/src/components/common/Logo/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/preview/launcher/Launcher/components/GitHubConnectButton/GitHubConnectButton.module.scss
var GitHubConnectButton_module = __webpack_require__(82045);
;// ../noodl-core-ui/src/preview/launcher/Launcher/components/GitHubConnectButton/GitHubConnectButton.module.scss

      
      
      
      
      
      
      
      
      

var GitHubConnectButton_module_options = {};

GitHubConnectButton_module_options.styleTagTransform = (styleTagTransform_default());
GitHubConnectButton_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      GitHubConnectButton_module_options.insert = insertBySelector_default().bind(null, "head");
    
GitHubConnectButton_module_options.domAPI = (styleDomAPI_default());
GitHubConnectButton_module_options.insertStyleElement = (insertStyleElement_default());

var GitHubConnectButton_module_update = injectStylesIntoStyleTag_default()(GitHubConnectButton_module/* default */.A, GitHubConnectButton_module_options);




       /* harmony default export */ const GitHubConnectButton_GitHubConnectButton_module = (GitHubConnectButton_module/* default */.A && GitHubConnectButton_module/* default */.A.locals ? GitHubConnectButton_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/GitHubConnectButton/GitHubConnectButton.tsx
/**
 * GitHubConnectButton
 *
 * Button component for initiating GitHub OAuth flow
 */



function GitHubConnectButton({ onConnect, isConnecting = false }) {
    return (external_react_default().createElement("div", { className: GitHubConnectButton_GitHubConnectButton_module.Root },
        external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: isConnecting ? 'Connecting...' : 'Connect with GitHub', onClick: onConnect, isDisabled: isConnecting }),
        external_react_default().createElement("p", { className: GitHubConnectButton_GitHubConnectButton_module.Description }, "Connect to access your repositories and enable version control features.")));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/GitHubConnectButton/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherHeader/LauncherHeader.module.scss
var LauncherHeader_module = __webpack_require__(45625);
;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherHeader/LauncherHeader.module.scss

      
      
      
      
      
      
      
      
      

var LauncherHeader_module_options = {};

LauncherHeader_module_options.styleTagTransform = (styleTagTransform_default());
LauncherHeader_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      LauncherHeader_module_options.insert = insertBySelector_default().bind(null, "head");
    
LauncherHeader_module_options.domAPI = (styleDomAPI_default());
LauncherHeader_module_options.insertStyleElement = (insertStyleElement_default());

var LauncherHeader_module_update = injectStylesIntoStyleTag_default()(LauncherHeader_module/* default */.A, LauncherHeader_module_options);




       /* harmony default export */ const LauncherHeader_LauncherHeader_module = (LauncherHeader_module/* default */.A && LauncherHeader_module/* default */.A.locals ? LauncherHeader_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherHeader/LauncherHeader.tsx
/**
 * LauncherHeader - Top header for the launcher dashboard
 *
 * Contains logo, version info, and utility actions
 *
 * @module noodl-core-ui/preview/launcher
 */












const VERSION_NUMBER = '2.9.3';
function LauncherHeader({}) {
    const { useMockData, setUseMockData, hasRealProjects, githubIsAuthenticated, githubIsConnecting, onGitHubConnect } = useLauncherContext();
    const handleToggleDataSource = () => {
        setUseMockData(!useMockData);
        console.info(`Data source switched to: ${!useMockData ? 'Mock' : 'Real'}`);
    };
    return (external_react_default().createElement("div", { className: LauncherHeader_LauncherHeader_module['Root'] },
        external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_className: LauncherHeader_LauncherHeader_module['Content'] },
            external_react_default().createElement(Logo, null),
            external_react_default().createElement("div", { className: LauncherHeader_LauncherHeader_module['VersionInfo'] },
                external_react_default().createElement(Title/* Title */.hE, { variant: Title/* TitleVariant */.Is.Highlighted, size: Title/* TitleSize */.uM.Large },
                    "Noodl ",
                    VERSION_NUMBER)),
            external_react_default().createElement("div", { className: LauncherHeader_LauncherHeader_module['Actions'] },
                !githubIsAuthenticated && onGitHubConnect && (external_react_default().createElement(GitHubConnectButton, { onConnect: onGitHubConnect, isConnecting: githubIsConnecting })),
                hasRealProjects && (external_react_default().createElement("div", { className: LauncherHeader_LauncherHeader_module['DataSourceToggle'] },
                    external_react_default().createElement(TextButton, { label: useMockData ? 'Mock Data' : 'Real Data', icon: useMockData ? common_Icon/* IconName */.$M.CloudData : common_Icon/* IconName */.$M.Check, variant: useMockData ? typography_Text/* TextType */.M2.Shy : typography_Text/* TextType */.M2.Proud, size: TextButtonSize.Small, onClick: handleToggleDataSource, testId: "data-source-toggle" }))),
                external_react_default().createElement(ContextMenu/* ContextMenu */.t, { menuItems: [{ label: 'Check for updates', onClick: () => alert('FIXME: check updates') }], renderDirection: BaseDialog/* DialogRenderDirection */.K1.Horizontal })))));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherHeader/index.ts


;// ../noodl-core-ui/src/preview/launcher/Launcher/hooks/usePersistentTab.ts
/**
 * usePersistentTab - Hook for persisting active tab state
 *
 * Saves and restores the active tab choice across application restarts
 * using localStorage.
 *
 * @module noodl-core-ui/preview/launcher
 */

const STORAGE_KEY = 'noodl-launcher-active-tab';
/**
 * Hook that manages tab state with localStorage persistence
 *
 * @param defaultTab - The default tab if no stored value exists
 * @returns Tuple of [activeTab, setActiveTab]
 *
 * @example
 * ```tsx
 * const [activeTab, setActiveTab] = usePersistentTab('projects');
 * ```
 */
function usePersistentTab(defaultTab) {
    // Initialize state from localStorage or default
    const [activeTab, setActiveTab] = (0,external_react_.useState)(() => {
        try {
            const stored = localStorage.getItem(STORAGE_KEY);
            if (stored && isValidPageId(stored)) {
                return stored;
            }
        }
        catch (error) {
            console.warn('Failed to load active tab from localStorage:', error);
        }
        return defaultTab;
    });
    // Save to localStorage whenever tab changes
    (0,external_react_.useEffect)(() => {
        try {
            localStorage.setItem(STORAGE_KEY, activeTab);
        }
        catch (error) {
            console.warn('Failed to save active tab to localStorage:', error);
        }
    }, [activeTab]);
    return [activeTab, setActiveTab];
}
/**
 * Type guard to validate stored values
 */
function isValidPageId(value) {
    return value === 'projects' || value === 'learn' || value === 'templates';
}
/**
 * Utility to manually clear stored tab preference
 * Useful for testing or reset functionality
 */
function clearStoredTab() {
    try {
        localStorage.removeItem(STORAGE_KEY);
    }
    catch (error) {
        console.warn('Failed to clear stored tab:', error);
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherPage/LauncherPage.module.scss
var LauncherPage_module = __webpack_require__(19421);
;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherPage/LauncherPage.module.scss

      
      
      
      
      
      
      
      
      

var LauncherPage_module_options = {};

LauncherPage_module_options.styleTagTransform = (styleTagTransform_default());
LauncherPage_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      LauncherPage_module_options.insert = insertBySelector_default().bind(null, "head");
    
LauncherPage_module_options.domAPI = (styleDomAPI_default());
LauncherPage_module_options.insertStyleElement = (insertStyleElement_default());

var LauncherPage_module_update = injectStylesIntoStyleTag_default()(LauncherPage_module/* default */.A, LauncherPage_module_options);




       /* harmony default export */ const LauncherPage_LauncherPage_module = (LauncherPage_module/* default */.A && LauncherPage_module/* default */.A.locals ? LauncherPage_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherPage/LauncherPage.tsx





function LauncherPage({ title, children, headerSlot }) {
    return (external_react_default().createElement("div", { className: LauncherPage_LauncherPage_module['Root'] },
        external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: 14 },
            external_react_default().createElement(Stack/* HStack */.zt, { UNSAFE_style: { justifyContent: 'space-between' } },
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Large, variant: Title/* TitleVariant */.Is.Highlighted }, title),
                external_react_default().createElement("div", null, headerSlot))),
        children));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherPage/index.ts


;// ../noodl-core-ui/src/preview/launcher/Launcher/views/GitHubRepos.tsx
/**
 * GitHubRepos View
 *
 * Browse and clone Noodl projects from GitHub repositories.
 * Only shows repos that contain project.json or nodegx.project.json.
 *
 * @module noodl-core-ui/preview/launcher/Launcher/views
 */









function GitHubRepoCard({ repo, onClone, isCloning }) {
    const updatedAt = new Date(repo.updated_at).toLocaleDateString();
    return (external_react_default().createElement("div", { style: {
            display: 'flex',
            alignItems: 'center',
            gap: 'var(--spacing-4)',
            padding: 'var(--spacing-3) var(--spacing-4)',
            backgroundColor: 'var(--theme-color-bg-3)',
            borderRadius: 'var(--radius-default)',
            border: '1px solid var(--theme-color-border-default)'
        } },
        external_react_default().createElement("img", { src: repo.owner.avatar_url, alt: repo.owner.login, style: {
                width: 40,
                height: 40,
                borderRadius: 'var(--radius-default)'
            } }),
        external_react_default().createElement("div", { style: { flex: 1, minWidth: 0 } },
            external_react_default().createElement("div", { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
                external_react_default().createElement("span", { style: { fontWeight: 600, color: 'var(--theme-color-fg-default)' } }, repo.name),
                repo.private && (external_react_default().createElement("span", { style: {
                        fontSize: '10px',
                        padding: '2px 6px',
                        backgroundColor: 'var(--theme-color-secondary-highlight)',
                        borderRadius: 'var(--radius-small)',
                        color: 'var(--theme-color-fg-default)'
                    } }, "Private")),
                repo.isNoodlProject && (external_react_default().createElement("span", { style: {
                        fontSize: '10px',
                        padding: '2px 6px',
                        backgroundColor: 'var(--theme-color-primary)',
                        borderRadius: 'var(--radius-small)',
                        color: 'white'
                    } }, "Noodl Project"))),
            external_react_default().createElement("div", { style: { fontSize: '12px', color: 'var(--theme-color-fg-default-shy)' } },
                repo.full_name,
                " \u2022 Updated ",
                updatedAt),
            repo.description && (external_react_default().createElement("div", { style: {
                    fontSize: '12px',
                    color: 'var(--theme-color-fg-default-shy)',
                    marginTop: '4px',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                } }, repo.description))),
        external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: isCloning ? 'Cloning...' : 'Clone', size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, isDisabled: isCloning || repo.isCheckingNoodl, onClick: () => onClone(repo) })));
}
/**
 * Section header for organization
 */
function OrgSection({ org, children }) {
    const [isExpanded, setIsExpanded] = (0,external_react_.useState)(true);
    const noodlProjectCount = org.repos.filter((r) => r.isNoodlProject === true).length;
    return (external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: 4 },
        external_react_default().createElement("button", { onClick: () => setIsExpanded(!isExpanded), style: {
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                width: '100%',
                padding: '8px 12px',
                backgroundColor: 'transparent',
                border: 'none',
                cursor: 'pointer',
                color: 'var(--theme-color-fg-default)'
            } },
            external_react_default().createElement("img", { src: org.avatar_url, alt: org.login, style: { width: 24, height: 24, borderRadius: '4px' } }),
            external_react_default().createElement("span", { style: { fontWeight: 600, flex: 1, textAlign: 'left' } }, org.login),
            external_react_default().createElement("span", { style: { fontSize: '12px', color: 'var(--theme-color-fg-default-shy)' } },
                noodlProjectCount,
                " ",
                noodlProjectCount === 1 ? 'project' : 'projects'),
            external_react_default().createElement(common_Icon/* Icon */.In, { icon: isExpanded ? common_Icon/* IconName */.$M.CaretDown : common_Icon/* IconName */.$M.CaretRight })),
        isExpanded && external_react_default().createElement("div", { style: { paddingLeft: '16px' } }, children)));
}
/**
 * Empty state when no Noodl projects found
 */
function EmptyState() {
    return (external_react_default().createElement("div", { style: {
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '64px',
            textAlign: 'center'
        } },
        external_react_default().createElement("div", { style: { fontSize: '48px' } },
            external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.FolderOpen })),
        external_react_default().createElement("h3", { style: { fontSize: '18px', fontWeight: 600, color: 'var(--theme-color-fg-default)', marginTop: '16px' } }, "No Noodl Projects Found"),
        external_react_default().createElement("p", { style: {
                color: 'var(--theme-color-fg-default-shy)',
                marginTop: '8px',
                maxWidth: '400px',
                lineHeight: 1.5
            } }, "No repositories with project.json were found in your GitHub account. Noodl projects contain a project.json file in the root directory.")));
}
/**
 * Connect GitHub prompt when not authenticated
 */
function ConnectGitHubPrompt({ onConnect }) {
    return (external_react_default().createElement("div", { style: {
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '64px',
            textAlign: 'center'
        } },
        external_react_default().createElement("div", { style: { fontSize: '48px' } },
            external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.CloudFunction })),
        external_react_default().createElement("h3", { style: { fontSize: '18px', fontWeight: 600, color: 'var(--theme-color-fg-default)', marginTop: '16px' } }, "Connect GitHub"),
        external_react_default().createElement("p", { style: {
                color: 'var(--theme-color-fg-default-shy)',
                marginTop: '8px',
                maxWidth: '400px',
                lineHeight: 1.5
            } }, "Connect your GitHub account to browse and clone your Noodl projects."),
        external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: 4 },
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Connect GitHub", onClick: onConnect }))));
}
/**
 * Loading spinner
 */
function LoadingState() {
    return (external_react_default().createElement("div", { style: {
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '64px',
            gap: '12px'
        } },
        external_react_default().createElement("div", { style: {
                width: 24,
                height: 24,
                border: '2px solid var(--theme-color-border-default)',
                borderTopColor: 'var(--theme-color-primary)',
                borderRadius: '50%',
                animation: 'spin 1s linear infinite'
            } }),
        external_react_default().createElement("span", { style: { color: 'var(--theme-color-fg-default-shy)' } }, "Loading repositories...")));
}
function GitHubRepos({}) {
    const { githubIsAuthenticated, onGitHubConnect, githubRepos, onCloneRepo } = useLauncherContext();
    const [searchTerm, setSearchTerm] = (0,external_react_.useState)('');
    const [cloningRepoId, setCloningRepoId] = (0,external_react_.useState)(null);
    // Get repos from context
    const { noodlProjects, allRepos, organizations, isLoading, error, refresh } = githubRepos || {
        noodlProjects: [],
        allRepos: [],
        organizations: [],
        personalRepos: [],
        isLoading: false,
        error: null,
        refresh: async () => { }
    };
    // Count how many repos are still being checked
    const checkingCount = allRepos.filter((r) => r.isNoodlProject === null).length;
    const isChecking = checkingCount > 0;
    // Only show Noodl projects
    const reposToShow = noodlProjects;
    // Filter by search term
    const filteredRepos = (0,external_react_.useMemo)(() => {
        if (!searchTerm)
            return reposToShow;
        const term = searchTerm.toLowerCase();
        return reposToShow.filter((repo) => {
            var _a;
            return repo.name.toLowerCase().includes(term) ||
                repo.full_name.toLowerCase().includes(term) ||
                ((_a = repo.description) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(term));
        });
    }, [reposToShow, searchTerm]);
    // Group by source (personal vs org)
    const personalFilteredRepos = filteredRepos.filter((r) => r.source === 'personal');
    const orgFilteredRepos = filteredRepos.filter((r) => r.source !== 'personal');
    // Group org projects by org
    const projectsByOrg = (0,external_react_.useMemo)(() => {
        const grouped = new Map();
        for (const repo of orgFilteredRepos) {
            const existing = grouped.get(repo.source) || [];
            grouped.set(repo.source, [...existing, repo]);
        }
        return grouped;
    }, [orgFilteredRepos]);
    const handleClone = async (repo) => {
        if (!onCloneRepo)
            return;
        setCloningRepoId(repo.id);
        try {
            await onCloneRepo(repo);
        }
        finally {
            setCloningRepoId(null);
        }
    };
    // Not authenticated
    if (!githubIsAuthenticated) {
        return (external_react_default().createElement(LauncherPage, { title: "GitHub" },
            external_react_default().createElement(ConnectGitHubPrompt, { onConnect: () => onGitHubConnect === null || onGitHubConnect === void 0 ? void 0 : onGitHubConnect() })));
    }
    return (external_react_default().createElement(LauncherPage, { title: "GitHub Projects", headerSlot: external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Refresh", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: refresh, isDisabled: isLoading })) },
        external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: 4 },
            external_react_default().createElement(TextInput, { variant: TextInputVariant.InModal, value: searchTerm, onChange: (e) => setSearchTerm(e.target.value), placeholder: "Search Noodl projects..." })),
        error && (external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: 4 },
            external_react_default().createElement("div", { style: {
                    padding: '12px',
                    backgroundColor: 'var(--theme-color-danger-10)',
                    borderRadius: 'var(--radius-default)',
                    color: 'var(--theme-color-danger)'
                } }, error))),
        isLoading && external_react_default().createElement(LoadingState, null),
        !isLoading && isChecking && (external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: 4 },
            external_react_default().createElement("div", { style: {
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px',
                    padding: '8px 12px',
                    backgroundColor: 'var(--theme-color-bg-2)',
                    borderRadius: 'var(--radius-default)',
                    fontSize: '12px',
                    color: 'var(--theme-color-fg-default-shy)'
                } },
                external_react_default().createElement("div", { style: {
                        width: 12,
                        height: 12,
                        border: '2px solid var(--theme-color-border-default)',
                        borderTopColor: 'var(--theme-color-primary)',
                        borderRadius: '50%',
                        animation: 'spin 1s linear infinite'
                    } }),
                "Scanning ",
                checkingCount,
                " repositories for project.json..."))),
        !isLoading && !isChecking && filteredRepos.length === 0 && external_react_default().createElement(EmptyState, null),
        !isLoading && filteredRepos.length > 0 && (external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: true },
            personalFilteredRepos.length > 0 && (external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: 4 },
                external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Default },
                    "Personal Repositories (",
                    personalFilteredRepos.length,
                    ")"),
                external_react_default().createElement("div", { style: { marginTop: '8px', display: 'flex', flexDirection: 'column', gap: '8px' } }, personalFilteredRepos.map((repo) => (external_react_default().createElement(GitHubRepoCard, { key: repo.id, repo: repo, onClone: handleClone, isCloning: cloningRepoId === repo.id })))))),
            Array.from(projectsByOrg.entries()).map(([orgLogin, repos]) => {
                const org = organizations.find((o) => o.login === orgLogin);
                if (!org)
                    return null;
                return (external_react_default().createElement(OrgSection, { key: orgLogin, org: org },
                    external_react_default().createElement("div", { style: { display: 'flex', flexDirection: 'column', gap: '8px' } }, repos.map((repo) => (external_react_default().createElement(GitHubRepoCard, { key: repo.id, repo: repo, onClone: handleClone, isCloning: cloningRepoId === repo.id }))))));
            })))));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/views/LearningCenter.tsx


function LearningCenter({}) {
    return external_react_default().createElement(LauncherPage, { title: "Learning Center" });
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/preview/launcher/Launcher/components/FolderTreeItem/FolderTreeItem.module.scss
var FolderTreeItem_module = __webpack_require__(96293);
;// ../noodl-core-ui/src/preview/launcher/Launcher/components/FolderTreeItem/FolderTreeItem.module.scss

      
      
      
      
      
      
      
      
      

var FolderTreeItem_module_options = {};

FolderTreeItem_module_options.styleTagTransform = (styleTagTransform_default());
FolderTreeItem_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      FolderTreeItem_module_options.insert = insertBySelector_default().bind(null, "head");
    
FolderTreeItem_module_options.domAPI = (styleDomAPI_default());
FolderTreeItem_module_options.insertStyleElement = (insertStyleElement_default());

var FolderTreeItem_module_update = injectStylesIntoStyleTag_default()(FolderTreeItem_module/* default */.A, FolderTreeItem_module_options);




       /* harmony default export */ const FolderTreeItem_FolderTreeItem_module = (FolderTreeItem_module/* default */.A && FolderTreeItem_module/* default */.A.locals ? FolderTreeItem_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/FolderTreeItem/FolderTreeItem.tsx
/**
 * FolderTreeItem - Individual folder row in the folder tree
 *
 * Displays a folder with icon, name, project count badge, and context menu.
 * Supports nested folders with expand/collapse chevron.
 *
 * @module noodl-core-ui/preview/launcher
 */







/**
 * FolderTreeItem displays a single folder in the tree with:
 * - Folder icon (open/closed based on expansion)
 * - Folder name
 * - Project count badge
 * - Context menu for rename/delete
 * - Expand/collapse chevron for nested folders
 */
function FolderTreeItem({ folder, projectCount, isSelected = false, hasChildren = false, isExpanded = false, level = 0, onClick, onToggleExpand, onRename, onDelete }) {
    const [isHovered, setIsHovered] = (0,external_react_.useState)(false);
    const handleChevronClick = (e) => {
        e.stopPropagation();
        onToggleExpand === null || onToggleExpand === void 0 ? void 0 : onToggleExpand();
    };
    const contextMenuItems = [
        {
            label: 'Rename folder',
            icon: common_Icon/* IconName */.$M.PencilLine,
            onClick: () => onRename === null || onRename === void 0 ? void 0 : onRename()
        },
        'divider',
        {
            label: 'Delete folder',
            icon: common_Icon/* IconName */.$M.Trash,
            onClick: () => onDelete === null || onDelete === void 0 ? void 0 : onDelete(),
            isDangerous: true
        }
    ];
    const paddingLeft = 8 + level * 16; // Base padding + indent per level
    return (external_react_default().createElement("div", { className: external_classnames_default()(FolderTreeItem_FolderTreeItem_module['Root'], {
            [FolderTreeItem_FolderTreeItem_module['Root--selected']]: isSelected,
            [FolderTreeItem_FolderTreeItem_module['Root--hasChildren']]: hasChildren
        }), style: { paddingLeft: `${paddingLeft}px` }, onClick: onClick, onMouseEnter: () => setIsHovered(true), onMouseLeave: () => setIsHovered(false) },
        hasChildren && (external_react_default().createElement("button", { className: FolderTreeItem_FolderTreeItem_module['Chevron'], onClick: handleChevronClick, "aria-label": isExpanded ? 'Collapse folder' : 'Expand folder' },
            external_react_default().createElement(common_Icon/* Icon */.In, { icon: isExpanded ? common_Icon/* IconName */.$M.CaretDown : common_Icon/* IconName */.$M.CaretRight, size: common_Icon/* IconSize */.lK.Small, UNSAFE_className: FolderTreeItem_FolderTreeItem_module['ChevronIcon'] }))),
        external_react_default().createElement("div", { className: FolderTreeItem_FolderTreeItem_module['FolderIcon'] },
            external_react_default().createElement(common_Icon/* Icon */.In, { icon: isExpanded ? common_Icon/* IconName */.$M.FolderOpen : common_Icon/* IconName */.$M.FolderClosed, size: common_Icon/* IconSize */.lK.Default, UNSAFE_className: FolderTreeItem_FolderTreeItem_module['Icon'] })),
        external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Default, variant: isSelected ? typography_Text/* TextType */.M2.Default : typography_Text/* TextType */.M2.Shy, UNSAFE_className: FolderTreeItem_FolderTreeItem_module['FolderName'] }, folder.name),
        projectCount > 0 && (external_react_default().createElement("span", { className: FolderTreeItem_FolderTreeItem_module['Badge'] },
            external_react_default().createElement(Label/* Label */.JU, { size: Label/* LabelSize */.IV.Small, variant: typography_Text/* TextType */.M2.Shy }, String(projectCount)))),
        isHovered && (external_react_default().createElement("div", { className: FolderTreeItem_FolderTreeItem_module['ContextMenuTrigger'], onClick: (e) => e.stopPropagation() },
            external_react_default().createElement(ContextMenu/* ContextMenu */.t, { menuItems: contextMenuItems })))));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/FolderTreeItem/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/preview/launcher/Launcher/components/FolderTree/FolderTree.module.scss
var FolderTree_module = __webpack_require__(70567);
;// ../noodl-core-ui/src/preview/launcher/Launcher/components/FolderTree/FolderTree.module.scss

      
      
      
      
      
      
      
      
      

var FolderTree_module_options = {};

FolderTree_module_options.styleTagTransform = (styleTagTransform_default());
FolderTree_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      FolderTree_module_options.insert = insertBySelector_default().bind(null, "head");
    
FolderTree_module_options.domAPI = (styleDomAPI_default());
FolderTree_module_options.insertStyleElement = (insertStyleElement_default());

var FolderTree_module_update = injectStylesIntoStyleTag_default()(FolderTree_module/* default */.A, FolderTree_module_options);




       /* harmony default export */ const FolderTree_FolderTree_module = (FolderTree_module/* default */.A && FolderTree_module/* default */.A.locals ? FolderTree_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/FolderTree/FolderTree.tsx
/**
 * FolderTree - Project organization folder tree
 *
 * Displays virtual folders (All Projects, Uncategorized) and user-created folders
 * with expand/collapse functionality and folder management actions.
 *
 * @module noodl-core-ui/preview/launcher
 */





/**
 * FolderTree displays the project organization structure:
 * - Virtual folders ("All Projects", "Uncategorized")
 * - User-created folders with expand/collapse
 * - "+ New Folder" button
 */
function FolderTree({ selectedFolderId, onFolderSelect, totalProjectCount, uncategorizedProjectCount }) {
    const { folders, createFolder, renameFolder, deleteFolder, getProjectCountInFolder } = useProjectOrganization();
    // Track expanded folders (folder IDs that are expanded)
    const [expandedFolderIds, setExpandedFolderIds] = (0,external_react_.useState)(new Set());
    // Track folder being renamed
    const [renamingFolderId, setRenamingFolderId] = (0,external_react_.useState)(null);
    const [renameValue, setRenameValue] = (0,external_react_.useState)('');
    // Track new folder creation
    const [isCreatingFolder, setIsCreatingFolder] = (0,external_react_.useState)(false);
    const [newFolderName, setNewFolderName] = (0,external_react_.useState)('');
    // Track folder deletion confirmation
    const [deletingFolder, setDeletingFolder] = (0,external_react_.useState)(null);
    const toggleExpand = (folderId) => {
        setExpandedFolderIds((prev) => {
            const next = new Set(prev);
            if (next.has(folderId)) {
                next.delete(folderId);
            }
            else {
                next.add(folderId);
            }
            return next;
        });
    };
    const handleCreateFolder = () => {
        setIsCreatingFolder(true);
        setNewFolderName('');
    };
    const handleCreateFolderSubmit = () => {
        if (newFolderName.trim()) {
            createFolder(newFolderName.trim());
        }
        setIsCreatingFolder(false);
        setNewFolderName('');
    };
    const handleCreateFolderCancel = () => {
        setIsCreatingFolder(false);
        setNewFolderName('');
    };
    const handleRenameFolder = (folder) => {
        setRenamingFolderId(folder.id);
        setRenameValue(folder.name);
    };
    const handleRenameSubmit = (folderId) => {
        if (renameValue.trim()) {
            renameFolder(folderId, renameValue.trim());
        }
        setRenamingFolderId(null);
        setRenameValue('');
    };
    const handleRenameCancel = () => {
        setRenamingFolderId(null);
        setRenameValue('');
    };
    const handleDeleteFolder = (folder) => {
        setDeletingFolder(folder);
    };
    const handleDeleteFolderConfirm = () => {
        if (deletingFolder) {
            deleteFolder(deletingFolder.id);
            // If deleted folder was selected, reset to "All Projects"
            if (selectedFolderId === deletingFolder.id) {
                onFolderSelect(null);
            }
            setDeletingFolder(null);
        }
    };
    const handleDeleteFolderCancel = () => {
        setDeletingFolder(null);
    };
    // Organize folders into root and nested
    const rootFolders = folders.filter((f) => f.parentId === null);
    const getFolderChildren = (parentId) => {
        return folders.filter((f) => f.parentId === parentId);
    };
    return (external_react_default().createElement("div", { className: FolderTree_FolderTree_module['Root'] },
        external_react_default().createElement("div", { className: FolderTree_FolderTree_module['VirtualFolders'] },
            external_react_default().createElement(FolderTreeItem, { folder: { id: 'all', name: 'All Projects', parentId: null, order: 0, createdAt: '' }, projectCount: totalProjectCount, isSelected: selectedFolderId === null, onClick: () => onFolderSelect(null) }),
            external_react_default().createElement(FolderTreeItem, { folder: {
                    id: 'uncategorized',
                    name: 'Uncategorized',
                    parentId: null,
                    order: 1,
                    createdAt: ''
                }, projectCount: uncategorizedProjectCount, isSelected: selectedFolderId === 'uncategorized', onClick: () => onFolderSelect('uncategorized') })),
        rootFolders.length > 0 && external_react_default().createElement("div", { className: FolderTree_FolderTree_module['Divider'] }),
        external_react_default().createElement("div", { className: FolderTree_FolderTree_module['UserFolders'] }, rootFolders.map((folder) => {
            const children = getFolderChildren(folder.id);
            const isExpanded = expandedFolderIds.has(folder.id);
            const projectCount = getProjectCountInFolder(folder.id);
            return (external_react_default().createElement("div", { key: folder.id },
                renamingFolderId === folder.id ? (external_react_default().createElement("div", { className: FolderTree_FolderTree_module['RenameInput'] },
                    external_react_default().createElement("input", { type: "text", value: renameValue, onChange: (e) => setRenameValue(e.target.value), onKeyDown: (e) => {
                            if (e.key === 'Enter') {
                                handleRenameSubmit(folder.id);
                            }
                            else if (e.key === 'Escape') {
                                handleRenameCancel();
                            }
                        }, onBlur: () => handleRenameSubmit(folder.id), autoFocus: true, className: FolderTree_FolderTree_module['RenameInputField'] }))) : (external_react_default().createElement(FolderTreeItem, { folder: folder, projectCount: projectCount, isSelected: selectedFolderId === folder.id, hasChildren: children.length > 0, isExpanded: isExpanded, onClick: () => onFolderSelect(folder.id), onToggleExpand: () => toggleExpand(folder.id), onRename: () => handleRenameFolder(folder), onDelete: () => handleDeleteFolder(folder) })),
                isExpanded &&
                    children.map((childFolder) => {
                        const childProjectCount = getProjectCountInFolder(childFolder.id);
                        return (external_react_default().createElement(FolderTreeItem, { key: childFolder.id, folder: childFolder, projectCount: childProjectCount, isSelected: selectedFolderId === childFolder.id, level: 1, onClick: () => onFolderSelect(childFolder.id), onRename: () => handleRenameFolder(childFolder), onDelete: () => handleDeleteFolder(childFolder) }));
                    })));
        })),
        isCreatingFolder ? (external_react_default().createElement("div", { className: FolderTree_FolderTree_module['CreateFolderInput'] },
            external_react_default().createElement("input", { type: "text", value: newFolderName, onChange: (e) => setNewFolderName(e.target.value), onKeyDown: (e) => {
                    if (e.key === 'Enter') {
                        handleCreateFolderSubmit();
                    }
                    else if (e.key === 'Escape') {
                        handleCreateFolderCancel();
                    }
                }, onBlur: handleCreateFolderSubmit, placeholder: "Folder name...", autoFocus: true, className: FolderTree_FolderTree_module['CreateFolderInputField'] }))) : (external_react_default().createElement("button", { className: FolderTree_FolderTree_module['NewFolderButton'], onClick: handleCreateFolder },
            external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Plus, size: common_Icon/* IconSize */.lK.Small, UNSAFE_className: FolderTree_FolderTree_module['NewFolderIcon'] }),
            external_react_default().createElement("span", { className: FolderTree_FolderTree_module['NewFolderLabel'] }, "New Folder"))),
        deletingFolder && (external_react_default().createElement("div", { className: FolderTree_FolderTree_module['DeleteConfirmation'] },
            external_react_default().createElement("div", { className: FolderTree_FolderTree_module['DeleteConfirmationBackdrop'], onClick: handleDeleteFolderCancel }),
            external_react_default().createElement("div", { className: FolderTree_FolderTree_module['DeleteConfirmationDialog'] },
                external_react_default().createElement("div", { className: FolderTree_FolderTree_module['DeleteConfirmationTitle'] }, "Delete Folder"),
                external_react_default().createElement("div", { className: FolderTree_FolderTree_module['DeleteConfirmationMessage'] }, getProjectCountInFolder(deletingFolder.id) > 0
                    ? `Delete "${deletingFolder.name}"? ${getProjectCountInFolder(deletingFolder.id)} project(s) will be moved to Uncategorized.`
                    : `Delete "${deletingFolder.name}"?`),
                external_react_default().createElement("div", { className: FolderTree_FolderTree_module['DeleteConfirmationButtons'] },
                    external_react_default().createElement("button", { className: FolderTree_FolderTree_module['DeleteConfirmationCancelButton'], onClick: handleDeleteFolderCancel }, "Cancel"),
                    external_react_default().createElement("button", { className: FolderTree_FolderTree_module['DeleteConfirmationDeleteButton'], onClick: handleDeleteFolderConfirm }, "Delete")))))));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/FolderTree/index.ts


;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherSearchBar/LauncherSearchBar.tsx







function useLauncherSearchBar({ filterDropdownItems, allItems, propertyNameToFilter }) {
    const [searchTerm, setSearchTerm] = (0,external_react_.useState)('');
    const [filterValue, setFilterValue] = (0,external_react_.useState)(filterDropdownItems[0].value);
    function createFilterFunction(propertyName, value) {
        return (item) => {
            let propertyChain = propertyName.split('.');
            let currentValue = item;
            for (let prop of propertyChain) {
                if (currentValue.hasOwnProperty(prop)) {
                    currentValue = currentValue[prop];
                }
                else {
                    return false; // Property not found, filter it out
                }
            }
            return currentValue === value;
        };
    }
    const filteredItems = filterValue !== 'all' ? allItems.filter(createFilterFunction(propertyNameToFilter, filterValue)) : allItems;
    const searchedItems = Boolean(searchTerm)
        ? filteredItems.filter((project) => project.title.toLowerCase().includes(searchTerm.toLowerCase()))
        : filteredItems;
    return {
        items: searchedItems,
        filterValue,
        setFilterValue,
        searchTerm,
        setSearchTerm
    };
}
function LauncherSearchBar({ searchTerm, setSearchTerm, filterDropdownItems, setFilterValue, filterValue }) {
    return (external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
        external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true, UNSAFE_style: { paddingBottom: 4, borderBottom: '1px solid var(--theme-color-bg-3)' } },
            external_react_default().createElement(TextInput, { slotBeforeInput: external_react_default().createElement(common_Icon/* Icon */.In, { icon: common_Icon/* IconName */.$M.Search, variant: typography_Text/* TextType */.M2.Shy }), value: searchTerm, onChange: (e) => setSearchTerm(e.currentTarget.value), variant: TextInputVariant.Transparent }),
            external_react_default().createElement("div", { style: { width: 220 } },
                external_react_default().createElement(Select, { options: filterDropdownItems, onChange: setFilterValue, value: filterValue, colorTheme: SelectColorTheme.Transparent })))));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/LauncherSearchBar/index.ts


;// ../noodl-core-ui/src/preview/launcher/Launcher/components/ProjectSettingsModal/ProjectSettingsModal.tsx















function ProjectSettingsModal({ isVisible, projectData, onClose }) {
    const [newProjectName, setNewProjectName] = (0,external_react_.useState)(projectData === null || projectData === void 0 ? void 0 : projectData.title);
    const [gitUrl, setGitUrl] = (0,external_react_.useState)('');
    const [SaveDialog, confirmSaveProjectData] = useConfirmationDialog({
        title: 'Please confirm',
        message: 'Are you sure you want to update the project settings?'
    });
    const [RemoveDialog, confirmRemoveWorkspaceProject] = useConfirmationDialog({
        title: 'Please confirm',
        message: 'Are you sure you want to remove the project?',
        isDangerousAction: true
    });
    if (!projectData)
        return null;
    function onPersistUpdatedData() {
        confirmSaveProjectData()
            .then(() => {
            alert('FIXME: take all new values and persist them');
        })
            .catch(() => console.log('Save cancelled'));
    }
    function onPushToExternalGitRepo() {
        alert('FIXME: Push to an external Git repo');
    }
    function onUnsyncProjectFromGit() {
        alert('FIXME: Reset .git folder in project');
    }
    function onRemoveProject() {
        confirmRemoveWorkspaceProject()
            .then(() => {
            alert('FIXME: Remove project');
        })
            .catch(() => {
            console.log('Project removal cancelled');
        });
    }
    return (external_react_default().createElement(Modal, { isVisible: isVisible, onClose: onClose, title: "Project settings", subtitle: projectData.title, footerSlot: external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true, UNSAFE_style: { width: '100%' } },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true, UNSAFE_style: { justifyContent: 'space-between', alignItems: 'center' } },
                external_react_default().createElement(TextButton, { label: "Remove project", icon: common_Icon/* IconName */.$M.Trash, variant: FeedbackType/* FeedbackType */.M.Danger, onClick: onRemoveProject }),
                external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", onClick: onClose, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted }),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Save changes", onClick: onPersistUpdatedData })))) },
        external_react_default().createElement(SaveDialog, null),
        external_react_default().createElement(RemoveDialog, null),
        external_react_default().createElement(Columns, { hasXGap: true },
            external_react_default().createElement(TextInput, { value: newProjectName, onChange: (e) => setNewProjectName(e.currentTarget.value), variant: TextInputVariant.InModal, label: "Project name" }),
            external_react_default().createElement(TextInput, { value: projectData.localPath, variant: TextInputVariant.InModal, label: "Project folder path", isReadonly: true, isCopyable: true })),
        projectData.cloudSyncMeta.type === CloudSyncType.None && (external_react_default().createElement((external_react_default()).Fragment, null,
            external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
                external_react_default().createElement(Card, { background: CardBackground.Bg2 },
                    external_react_default().createElement(Title/* Title */.hE, { hasBottomSpacing: true }, "This project is local only."),
                    external_react_default().createElement(typography_Text/* Text */.EY, null, "Please create a Git repository in your preferred Git provider, and push the repository to enable collaboration and version control for this project."),
                    external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                        external_react_default().createElement(TextInput, { value: gitUrl, onChange: (e) => setGitUrl(e.currentTarget.value), label: "Git repo URL", UNSAFE_style: { paddingTop: 16 } }),
                        external_react_default().createElement("div", { style: { alignSelf: 'flex-end' } },
                            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Push project to Git", onClick: () => onPushToExternalGitRepo() }))))))),
        projectData.cloudSyncMeta.type === CloudSyncType.Git && (external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
            external_react_default().createElement(Card, { background: CardBackground.Bg2 },
                external_react_default().createElement(Title/* Title */.hE, { hasBottomSpacing: true }, "Project is synced to a Git repo"),
                external_react_default().createElement(typography_Text/* Text */.EY, { hasBottomSpacing: true }, "Versioning and branching can be managed inside of the Noodl editor. User access has to be managed with your Git provider."),
                external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                    external_react_default().createElement(TextInput, { value: projectData.cloudSyncMeta.source, label: "Current Git repository URL", isReadonly: true, isCopyable: true }),
                    external_react_default().createElement("div", { style: { alignSelf: 'flex-end' } },
                        external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Unsync project instance from Git", onClick: () => onUnsyncProjectFromGit(), variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Danger }))))))));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/components/ProjectSettingsModal/index.ts


;// ../noodl-core-ui/src/preview/launcher/Launcher/views/Projects.tsx















function Projects({}) {
    const { projects: allProjects, selectedFolderId, setSelectedFolderId, onCreateProject, onOpenProject, onLaunchProject, onOpenProjectFolder, onDeleteProject, onMigrateProject, onOpenReadOnly } = useLauncherContext();
    const { getProjectMeta, getProjectsInFolder, folders, moveProjectToFolder } = useProjectOrganization();
    const [selectedProjectId, setSelectedProjectId] = (0,external_react_.useState)(null);
    const [movingProject, setMovingProject] = (0,external_react_.useState)(null);
    // Filter projects based on selected folder
    const filteredByFolder = (0,external_react_.useMemo)(() => {
        if (selectedFolderId === null) {
            // "All Projects" - show everything
            return allProjects;
        }
        else if (selectedFolderId === 'uncategorized') {
            // "Uncategorized" - show projects without a folder
            return allProjects.filter((project) => {
                const meta = getProjectMeta(project.localPath);
                return !meta || meta.folderId === null;
            });
        }
        else {
            // Specific folder - show projects in that folder
            const projectPathsInFolder = getProjectsInFolder(selectedFolderId);
            return allProjects.filter((project) => projectPathsInFolder.includes(project.localPath));
        }
    }, [allProjects, selectedFolderId, getProjectMeta, getProjectsInFolder]);
    // Calculate counts for folder tree
    const uncategorizedCount = (0,external_react_.useMemo)(() => {
        return allProjects.filter((project) => {
            const meta = getProjectMeta(project.localPath);
            return !meta || meta.folderId === null;
        }).length;
    }, [allProjects, getProjectMeta]);
    const uniqueTypes = [...new Set(filteredByFolder.map((item) => item.cloudSyncMeta.type))];
    const visibleTypesDropdownItems = [
        { label: 'All projects', value: 'all' },
        ...uniqueTypes.map((type) => ({ label: `Only ${type.toLowerCase()} projects`, value: type }))
    ];
    const { items: projects, filterValue, setFilterValue, searchTerm, setSearchTerm } = useLauncherSearchBar({
        allItems: filteredByFolder,
        filterDropdownItems: visibleTypesDropdownItems,
        propertyNameToFilter: 'cloudSyncMeta.type'
    });
    function onOpenProjectSettings(projectDataId) {
        setSelectedProjectId(projectDataId);
    }
    function onCloseProjectSettings() {
        setSelectedProjectId(null);
    }
    function onMoveToFolder(project) {
        setMovingProject(project);
    }
    function onCloseFolderPicker() {
        setMovingProject(null);
    }
    function handleMoveToFolder(folderId) {
        if (movingProject) {
            moveProjectToFolder(movingProject.localPath, folderId);
            setMovingProject(null);
        }
    }
    function onImportProjectClick() {
        onOpenProject === null || onOpenProject === void 0 ? void 0 : onOpenProject();
    }
    function onNewProjectClick() {
        onCreateProject === null || onCreateProject === void 0 ? void 0 : onCreateProject();
    }
    return (external_react_default().createElement("div", { style: { display: 'flex', height: '100%', overflow: 'hidden' } },
        external_react_default().createElement("div", { style: { width: '240px', borderRight: '1px solid var(--theme-color-border-default)', flexShrink: 0 } },
            external_react_default().createElement(FolderTree, { selectedFolderId: selectedFolderId, onFolderSelect: setSelectedFolderId, totalProjectCount: allProjects.length, uncategorizedProjectCount: uncategorizedCount })),
        external_react_default().createElement("div", { style: { flex: 1, overflow: 'auto' } },
            external_react_default().createElement(LauncherPage, { title: "Recent Projects", headerSlot: external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Open project", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onImportProjectClick }),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Create new project", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, onClick: onNewProjectClick })) },
                external_react_default().createElement(ProjectSettingsModal, { isVisible: selectedProjectId !== null, onClose: onCloseProjectSettings, projectData: projects.find((project) => project.id === selectedProjectId) }),
                external_react_default().createElement(LauncherSearchBar, { searchTerm: searchTerm, setSearchTerm: setSearchTerm, filterValue: filterValue, setFilterValue: setFilterValue, filterDropdownItems: visibleTypesDropdownItems }),
                external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: 4 },
                    external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: 4 },
                        external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                            external_react_default().createElement("div", { style: { width: 100 } }),
                            external_react_default().createElement("div", { style: { width: '100%' } },
                                external_react_default().createElement(Columns, { layoutString: '1 1 1' },
                                    external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Shy, size: Label/* LabelSize */.IV.Small }, "Name"),
                                    external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Shy, size: Label/* LabelSize */.IV.Small }, "Version control"),
                                    external_react_default().createElement(Label/* Label */.JU, { variant: typography_Text/* TextType */.M2.Shy, size: Label/* LabelSize */.IV.Small }, "Contributors"))))),
                    external_react_default().createElement(Columns, { layoutString: "1", hasXGap: true, hasYGap: true }, projects.map((project) => (external_react_default().createElement(LauncherProjectCard, { key: project.id, ...project, onClick: () => onLaunchProject === null || onLaunchProject === void 0 ? void 0 : onLaunchProject(project.id), onMigrateProject: () => onMigrateProject === null || onMigrateProject === void 0 ? void 0 : onMigrateProject(project.id), onOpenReadOnly: () => onOpenReadOnly === null || onOpenReadOnly === void 0 ? void 0 : onOpenReadOnly(project.id), contextMenuItems: [
                            {
                                label: 'Launch project',
                                onClick: () => onLaunchProject === null || onLaunchProject === void 0 ? void 0 : onLaunchProject(project.id)
                            },
                            {
                                label: 'Open project folder',
                                onClick: () => onOpenProjectFolder === null || onOpenProjectFolder === void 0 ? void 0 : onOpenProjectFolder(project.id)
                            },
                            {
                                label: 'Move to folder...',
                                onClick: () => onMoveToFolder(project)
                            },
                            {
                                label: 'Open project settings',
                                onClick: () => onOpenProjectSettings(project.id)
                            },
                            'divider',
                            {
                                label: 'Delete project',
                                onClick: () => onDeleteProject === null || onDeleteProject === void 0 ? void 0 : onDeleteProject(project.id),
                                icon: common_Icon/* IconName */.$M.Trash,
                                isDangerous: true
                            }
                        ] }))))),
                movingProject && (external_react_default().createElement("div", { style: {
                        position: 'fixed',
                        top: 0,
                        left: 0,
                        right: 0,
                        bottom: 0,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        zIndex: 1000
                    } },
                    external_react_default().createElement("div", { style: {
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            backgroundColor: 'rgba(0, 0, 0, 0.5)'
                        }, onClick: onCloseFolderPicker }),
                    external_react_default().createElement("div", { style: {
                            position: 'relative',
                            backgroundColor: 'var(--theme-color-bg-2)',
                            border: '1px solid var(--theme-color-border-default)',
                            borderRadius: 'var(--radius-lg)',
                            padding: 'var(--spacing-6)',
                            minWidth: '400px',
                            maxWidth: '500px',
                            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)',
                            zIndex: 1001
                        } },
                        external_react_default().createElement("h3", { style: {
                                fontSize: '20px',
                                fontWeight: 600,
                                color: 'var(--theme-color-fg-default)',
                                margin: '0 0 var(--spacing-3) 0',
                                lineHeight: 1.3
                            } },
                            "Move \"",
                            movingProject.title,
                            "\" to folder"),
                        external_react_default().createElement("div", { style: {
                                marginBottom: 'var(--spacing-6)',
                                maxHeight: '300px',
                                overflowY: 'auto'
                            } },
                            external_react_default().createElement("button", { onClick: () => handleMoveToFolder(null), style: {
                                    width: '100%',
                                    textAlign: 'left',
                                    padding: 'var(--spacing-2) var(--spacing-3)',
                                    marginBottom: 'var(--spacing-1)',
                                    backgroundColor: 'var(--theme-color-bg-3)',
                                    border: '1px solid var(--theme-color-border-default)',
                                    borderRadius: 'var(--radius-default)',
                                    color: 'var(--theme-color-fg-default)',
                                    cursor: 'pointer',
                                    transition: 'all 0.15s ease'
                                }, onMouseEnter: (e) => {
                                    e.currentTarget.style.backgroundColor = 'var(--theme-color-bg-4)';
                                }, onMouseLeave: (e) => {
                                    e.currentTarget.style.backgroundColor = 'var(--theme-color-bg-3)';
                                } }, "Uncategorized"),
                            folders.map((folder) => (external_react_default().createElement("button", { key: folder.id, onClick: () => handleMoveToFolder(folder.id), style: {
                                    width: '100%',
                                    textAlign: 'left',
                                    padding: 'var(--spacing-2) var(--spacing-3)',
                                    marginBottom: 'var(--spacing-1)',
                                    backgroundColor: 'var(--theme-color-bg-3)',
                                    border: '1px solid var(--theme-color-border-default)',
                                    borderRadius: 'var(--radius-default)',
                                    color: 'var(--theme-color-fg-default)',
                                    cursor: 'pointer',
                                    transition: 'all 0.15s ease'
                                }, onMouseEnter: (e) => {
                                    e.currentTarget.style.backgroundColor = 'var(--theme-color-bg-4)';
                                }, onMouseLeave: (e) => {
                                    e.currentTarget.style.backgroundColor = 'var(--theme-color-bg-3)';
                                } }, folder.name)))),
                        external_react_default().createElement("div", { style: { display: 'flex', justifyContent: 'flex-end' } },
                            external_react_default().createElement("button", { onClick: onCloseFolderPicker, style: {
                                    padding: 'var(--spacing-2) var(--spacing-4)',
                                    backgroundColor: 'var(--theme-color-bg-3)',
                                    border: '1px solid var(--theme-color-border-default)',
                                    borderRadius: 'var(--radius-default)',
                                    color: 'var(--theme-color-fg-default)',
                                    cursor: 'pointer',
                                    transition: 'all 0.15s ease'
                                }, onMouseEnter: (e) => {
                                    e.currentTarget.style.backgroundColor = 'var(--theme-color-bg-4)';
                                }, onMouseLeave: (e) => {
                                    e.currentTarget.style.backgroundColor = 'var(--theme-color-bg-3)';
                                } }, "Cancel")))))))));
}

;// ../noodl-core-ui/src/preview/launcher/Launcher/views/Templates.tsx
/**
 * Templates View - Project template browser
 *
 * Displays available project templates for quick starts
 *
 * @module noodl-core-ui/preview/launcher
 */



function Templates({}) {
    return (external_react_default().createElement(Box/* Box */.a, { hasXSpacing: true, hasYSpacing: true },
        external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
            external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Large }, "Templates")),
        external_react_default().createElement("div", { style: { color: 'var(--theme-color-fg-default-shy)' } }, "Project templates will be displayed here. This feature is coming soon!")));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!../noodl-core-ui/src/preview/launcher/Launcher/Launcher.module.scss
var Launcher_module = __webpack_require__(65601);
;// ../noodl-core-ui/src/preview/launcher/Launcher/Launcher.module.scss

      
      
      
      
      
      
      
      
      

var Launcher_module_options = {};

Launcher_module_options.styleTagTransform = (styleTagTransform_default());
Launcher_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      Launcher_module_options.insert = insertBySelector_default().bind(null, "head");
    
Launcher_module_options.domAPI = (styleDomAPI_default());
Launcher_module_options.insertStyleElement = (insertStyleElement_default());

var Launcher_module_update = injectStylesIntoStyleTag_default()(Launcher_module/* default */.A, Launcher_module_options);




       /* harmony default export */ const Launcher_Launcher_module = (Launcher_module/* default */.A && Launcher_module/* default */.A.locals ? Launcher_module/* default */.A.locals : undefined);

;// ../noodl-core-ui/src/preview/launcher/Launcher/Launcher.tsx
/**
 * Launcher - Main dashboard for OpenNoodl
 *
 * Modern, clean tabbed interface for managing projects, learning resources,
 * and project templates.
 *
 * @module noodl-core-ui/preview/launcher
 */













// Tab configuration (GitHub tab added dynamically based on auth state)
const LAUNCHER_TABS = [
    {
        id: 'projects',
        label: 'Projects',
        icon: common_Icon/* IconName */.$M.FolderOpen
    },
    {
        id: 'github',
        label: 'GitHub',
        icon: common_Icon/* IconName */.$M.CloudFunction
    },
    {
        id: 'learn',
        label: 'Learn',
        icon: common_Icon/* IconName */.$M.Rocket
    },
    {
        id: 'templates',
        label: 'Templates',
        icon: common_Icon/* IconName */.$M.Components
    }
];
// FIXME: make the mock data real
const MOCK_PROJECTS = [
    {
        id: '1',
        title: 'My first project',
        imageSrc: 'http://placekitten.com/g/200/300',
        localPath: '/User/Desktop/dev/my-first-project',
        lastOpened: '2023-10-26T12:22:13.462Z',
        cloudSyncMeta: {
            type: CloudSyncType.None,
            source: undefined
        },
        uncommittedChangesAmount: undefined,
        pullAmount: undefined,
        pushAmount: undefined
    },
    {
        id: '2',
        title: 'External git project with push but no pull',
        imageSrc: 'http://placekitten.com/g/400/800',
        localPath: '/User/Desktop/dev/area-51-employee-portal/top-secret-version',
        lastOpened: '2023-10-23T12:42:13.462Z',
        cloudSyncMeta: {
            type: CloudSyncType.Git,
            source: 'https://TESTHUB.com/org/testcompany/my-repo-project'
        },
        uncommittedChangesAmount: undefined,
        pullAmount: undefined,
        pushAmount: 666,
        contributors: [
            { email: 'tore@noodl.net', name: 'Tore Knudsen', id: 'Tore' },
            { email: 'eric@noodl.net', name: 'Eric Tuvesson', id: 'Eric' }
        ]
    },
    {
        id: '3',
        title: 'External git project with local changes',
        imageSrc: 'http://placekitten.com/g/500/500',
        localPath: '/User/Desktop/projects/my-git-repo',
        lastOpened: '2023-08-26T12:42:13.462Z',
        cloudSyncMeta: {
            type: CloudSyncType.Git,
            source: 'https://TESTHUB.com/org/testcompany/my-repo-project'
        },
        uncommittedChangesAmount: 4,
        pullAmount: undefined,
        pushAmount: undefined,
        contributors: [
            { email: 'tore@noodl.net', name: 'Tore Knudsen', id: 'Tore' },
            { email: 'eric@noodl.net', name: 'Eric Tuvesson', id: 'Eric' },
            { email: 'michael@noodl.net', name: 'Michael Cartner', id: 'Michael' },
            { email: 'mikael@noodl.net', name: 'Mikael Tellhed', id: 'Mikael' },
            { email: 'anders@noodl.net', name: 'Anders Larsson', id: 'Anders' },
            { email: 'johan@noodl.net', name: 'Johan Olsson', id: 'Johan' },
            { email: 'victor@noodl.net', name: 'Victor Permild', id: 'Victor' },
            { email: 'kotte@noodl.net', name: 'Kotte Aistre', id: 'Kotte' }
        ]
    },
    {
        id: '4',
        title: 'Git project with all notifications',
        imageSrc: 'http://placekitten.com/g/100/100',
        localPath: '/User/Desktop/projects/forgotten-project',
        lastOpened: '2023-06-26T12:42:13.462Z',
        cloudSyncMeta: {
            type: CloudSyncType.Git
        },
        uncommittedChangesAmount: 10,
        pullAmount: 10,
        pushAmount: 4,
        contributors: [
            { email: 'tore@noodl.net', name: 'Tore Knudsen', id: 'Tore' },
            { email: 'eric@noodl.net', name: 'Eric Tuvesson', id: 'Eric' },
            { email: 'michael@noodl.net', name: 'Michael Cartner', id: 'Michael' },
            { email: 'victor@noodl.net', name: 'Victor Permild', id: 'Victor' }
        ]
    }
];
/**
 * Parse deep link URL to extract initial tab
 * Supports formats like: noodl://dashboard/learn, noodl://dashboard/templates
 */
function parseDeepLink() {
    try {
        const url = new URL(window.location.href);
        const pathParts = url.pathname.split('/');
        const tabPart = pathParts[pathParts.length - 1];
        if (tabPart === 'projects' || tabPart === 'learn' || tabPart === 'templates') {
            return tabPart;
        }
    }
    catch (error) {
        // Ignore parsing errors
    }
    return null;
}
function Launcher({ initialTab, projects, onCreateProject, onOpenProject, onLaunchProject, onOpenProjectFolder, onDeleteProject, onMigrateProject, onOpenReadOnly, projectOrganizationService, githubUser, githubIsAuthenticated, githubIsConnecting, onGitHubConnect, onGitHubDisconnect, githubRepos, onCloneRepo }) {
    // Determine initial tab: props > deep link > persisted > default
    const deepLinkTab = parseDeepLink();
    const defaultTab = initialTab || deepLinkTab || 'projects';
    const [activePageId, setActivePageId] = usePersistentTab(defaultTab);
    // Mock data toggle state with localStorage persistence
    const [useMockData, setUseMockData] = (0,external_react_.useState)(() => {
        // Default to mock if no projects provided, otherwise check localStorage
        if (!projects)
            return true;
        try {
            const stored = localStorage.getItem('launcher:useMockData');
            return stored === 'true';
        }
        catch {
            return false; // Default to real data if provided
        }
    });
    // Folder selection state with localStorage persistence
    const [selectedFolderId, setSelectedFolderId] = (0,external_react_.useState)(() => {
        try {
            const stored = localStorage.getItem('launcher:selectedFolderId');
            return stored === 'null' ? null : stored;
        }
        catch {
            return null; // Default to "All Projects"
        }
    });
    // Persist mock data toggle
    (0,external_react_.useEffect)(() => {
        if (projects) {
            try {
                localStorage.setItem('launcher:useMockData', String(useMockData));
            }
            catch (error) {
                console.warn('Failed to persist mock data preference:', error);
            }
        }
    }, [useMockData, projects]);
    // Persist folder selection
    (0,external_react_.useEffect)(() => {
        try {
            localStorage.setItem('launcher:selectedFolderId', selectedFolderId === null ? 'null' : selectedFolderId);
        }
        catch (error) {
            console.warn('Failed to persist folder selection:', error);
        }
    }, [selectedFolderId]);
    // Determine which projects to use and if toggle should be available
    const hasRealProjects = Boolean(projects && projects.length > 0);
    const activeProjects = useMockData ? MOCK_PROJECTS : projects || MOCK_PROJECTS;
    // Update URL when tab changes (for deep linking support)
    (0,external_react_.useEffect)(() => {
        try {
            const url = new URL(window.location.href);
            url.pathname = `/dashboard/${activePageId}`;
            window.history.replaceState({}, '', url.toString());
        }
        catch (error) {
            // Ignore URL update errors
        }
    }, [activePageId]);
    const handleTabChange = (tabId) => {
        setActivePageId(tabId);
        console.info(`Navigated to tab: ${tabId}`);
    };
    // Render active view
    const renderActiveView = () => {
        switch (activePageId) {
            case 'projects':
                return external_react_default().createElement(Projects, null);
            case 'github':
                return external_react_default().createElement(GitHubRepos, null);
            case 'learn':
                return external_react_default().createElement(LearningCenter, null);
            case 'templates':
                return external_react_default().createElement(Templates, null);
            default:
                return external_react_default().createElement(Projects, null);
        }
    };
    return (external_react_default().createElement(LauncherProvider, { value: {
            activePageId,
            setActivePageId,
            useMockData,
            setUseMockData,
            projects: activeProjects,
            hasRealProjects,
            selectedFolderId,
            setSelectedFolderId,
            projectOrganizationService,
            onCreateProject,
            onOpenProject,
            onLaunchProject,
            onOpenProjectFolder,
            onDeleteProject,
            onMigrateProject,
            onOpenReadOnly,
            githubUser,
            githubIsAuthenticated,
            githubIsConnecting,
            onGitHubConnect,
            onGitHubDisconnect,
            githubRepos,
            onCloneRepo
        } },
        external_react_default().createElement("div", { className: Launcher_Launcher_module['Root'] },
            external_react_default().createElement(LauncherHeader, null),
            external_react_default().createElement(TabBar, { items: LAUNCHER_TABS, activeItemId: activePageId, onChange: handleTabChange, size: "large" }),
            external_react_default().createElement("div", { className: Launcher_Launcher_module['ContentArea'] }, renderActiveView()),
            external_react_default().createElement(LauncherFooter, null))));
}

// EXTERNAL MODULE: ./src/editor/src/models/migration/ProjectScanner.ts
var ProjectScanner = __webpack_require__(89911);
;// ./src/editor/src/services/ProjectOrganizationService.ts
/**
 * ProjectOrganizationService
 *
 * Manages project organization through folders and tags.
 * Data is stored client-side in electron-store and keyed by project path.
 */


// Tag color palette
const TAG_COLORS = [
    '#EF4444', // Red
    '#F97316', // Orange
    '#EAB308', // Yellow
    '#22C55E', // Green
    '#06B6D4', // Cyan
    '#3B82F6', // Blue
    '#8B5CF6', // Purple
    '#EC4899', // Pink
    '#6B7280' // Gray
];
// ============================================================================
// Service
// ============================================================================
class ProjectOrganizationService extends EventDispatcher.EventDispatcher {
    constructor() {
        super();
        // Initialize electron-store
        this.store = new (external_electron_store_default())({
            name: 'project_organization',
            defaults: {
                version: 1,
                folders: [],
                tags: [],
                projectMeta: {}
            }
        });
        this.data = this.loadData();
    }
    static get instance() {
        if (!ProjectOrganizationService._instance) {
            ProjectOrganizationService._instance = new ProjectOrganizationService();
        }
        return ProjectOrganizationService._instance;
    }
    // ============================================================================
    // Storage
    // ============================================================================
    loadData() {
        try {
            return this.store.store; // Get all data from store
        }
        catch (error) {
            console.error('[ProjectOrganizationService] Failed to load data:', error);
            return {
                version: 1,
                folders: [],
                tags: [],
                projectMeta: {}
            };
        }
    }
    saveData() {
        try {
            this.store.store = this.data; // Save all data to store
            this.notifyListeners('dataChanged', this.data);
        }
        catch (error) {
            console.error('[ProjectOrganizationService] Failed to save data:', error);
        }
    }
    // ============================================================================
    // Folder Operations
    // ============================================================================
    createFolder(name, parentId) {
        const folder = {
            id: this.generateId('folder'),
            name,
            parentId: parentId || null,
            order: this.data.folders.length,
            createdAt: new Date().toISOString()
        };
        this.data.folders.push(folder);
        this.saveData();
        this.notifyListeners('folderCreated', folder);
        return folder;
    }
    renameFolder(id, name) {
        const folder = this.data.folders.find((f) => f.id === id);
        if (!folder) {
            console.warn('[ProjectOrganizationService] Folder not found:', id);
            return;
        }
        folder.name = name;
        this.saveData();
        this.notifyListeners('folderRenamed', { id, name });
    }
    deleteFolder(id) {
        // Remove folder
        this.data.folders = this.data.folders.filter((f) => f.id !== id);
        // Remove child folders
        this.data.folders = this.data.folders.filter((f) => f.parentId !== id);
        // Move projects in deleted folder to uncategorized
        Object.keys(this.data.projectMeta).forEach((projectPath) => {
            if (this.data.projectMeta[projectPath].folderId === id) {
                this.data.projectMeta[projectPath].folderId = null;
            }
        });
        this.saveData();
        this.notifyListeners('folderDeleted', id);
    }
    reorderFolder(id, newOrder) {
        const folder = this.data.folders.find((f) => f.id === id);
        if (!folder)
            return;
        folder.order = newOrder;
        this.saveData();
        this.notifyListeners('folderReordered', { id, order: newOrder });
    }
    getFolders() {
        return [...this.data.folders].sort((a, b) => a.order - b.order);
    }
    getFolder(id) {
        return this.data.folders.find((f) => f.id === id);
    }
    // ============================================================================
    // Tag Operations
    // ============================================================================
    createTag(name, color) {
        const tag = {
            id: this.generateId('tag'),
            name,
            color: color || this.getNextTagColor(),
            createdAt: new Date().toISOString()
        };
        this.data.tags.push(tag);
        this.saveData();
        this.notifyListeners('tagCreated', tag);
        return tag;
    }
    renameTag(id, name) {
        const tag = this.data.tags.find((t) => t.id === id);
        if (!tag) {
            console.warn('[ProjectOrganizationService] Tag not found:', id);
            return;
        }
        tag.name = name;
        this.saveData();
        this.notifyListeners('tagRenamed', { id, name });
    }
    changeTagColor(id, color) {
        const tag = this.data.tags.find((t) => t.id === id);
        if (!tag)
            return;
        tag.color = color;
        this.saveData();
        this.notifyListeners('tagColorChanged', { id, color });
    }
    deleteTag(id) {
        // Remove tag
        this.data.tags = this.data.tags.filter((t) => t.id !== id);
        // Remove tag from all projects
        Object.keys(this.data.projectMeta).forEach((projectPath) => {
            const meta = this.data.projectMeta[projectPath];
            meta.tagIds = meta.tagIds.filter((tagId) => tagId !== id);
        });
        this.saveData();
        this.notifyListeners('tagDeleted', id);
    }
    getTags() {
        return [...this.data.tags];
    }
    getTag(id) {
        return this.data.tags.find((t) => t.id === id);
    }
    getNextTagColor() {
        const usedColors = this.data.tags.map((t) => t.color);
        const availableColors = TAG_COLORS.filter((c) => !usedColors.includes(c));
        return availableColors.length > 0 ? availableColors[0] : TAG_COLORS[0];
    }
    // ============================================================================
    // Project Organization
    // ============================================================================
    moveProjectToFolder(projectPath, folderId) {
        if (!this.data.projectMeta[projectPath]) {
            this.data.projectMeta[projectPath] = {
                folderId: null,
                tagIds: []
            };
        }
        this.data.projectMeta[projectPath].folderId = folderId;
        this.saveData();
        this.notifyListeners('projectMoved', { projectPath, folderId });
    }
    addTagToProject(projectPath, tagId) {
        if (!this.data.projectMeta[projectPath]) {
            this.data.projectMeta[projectPath] = {
                folderId: null,
                tagIds: []
            };
        }
        const meta = this.data.projectMeta[projectPath];
        if (!meta.tagIds.includes(tagId)) {
            meta.tagIds.push(tagId);
            this.saveData();
            this.notifyListeners('projectTagAdded', { projectPath, tagId });
        }
    }
    removeTagFromProject(projectPath, tagId) {
        const meta = this.data.projectMeta[projectPath];
        if (!meta)
            return;
        meta.tagIds = meta.tagIds.filter((id) => id !== tagId);
        this.saveData();
        this.notifyListeners('projectTagRemoved', { projectPath, tagId });
    }
    getProjectMeta(projectPath) {
        return this.data.projectMeta[projectPath] || null;
    }
    // ============================================================================
    // Queries
    // ============================================================================
    getProjectsInFolder(folderId) {
        return Object.keys(this.data.projectMeta).filter((projectPath) => {
            const meta = this.data.projectMeta[projectPath];
            return meta.folderId === folderId;
        });
    }
    getProjectsWithTag(tagId) {
        return Object.keys(this.data.projectMeta).filter((projectPath) => {
            const meta = this.data.projectMeta[projectPath];
            return meta.tagIds.includes(tagId);
        });
    }
    getProjectCountInFolder(folderId) {
        return this.getProjectsInFolder(folderId).length;
    }
    // ============================================================================
    // Utilities
    // ============================================================================
    generateId(prefix) {
        return `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    }
    // For debugging
    exportData() {
        return JSON.parse(JSON.stringify(this.data));
    }
    importData(data) {
        this.data = data;
        this.saveData();
    }
    clearAll() {
        this.data = {
            version: 1,
            folders: [],
            tags: [],
            projectMeta: {}
        };
        this.saveData();
        this.notifyListeners('dataCleared', null);
    }
}

;// ./src/editor/src/models/migration/MigrationSession.ts
/**
 * MigrationSession
 *
 * State machine for managing the React 19 migration process.
 * Handles step transitions, progress tracking, and session persistence.
 *
 * @module noodl-editor/models/migration
 * @since 1.2.0
 */



// =============================================================================
// Constants
// =============================================================================
/**
 * Default AI budget configuration
 */
const DEFAULT_AI_BUDGET = {
    maxPerSession: 5.0, // $5 max per migration session
    spent: 0,
    pauseIncrement: 1.0, // Pause and confirm every $1
    showEstimates: true
};
/**
 * Default AI preferences
 */
const DEFAULT_AI_PREFERENCES = {
    preferFunctional: true,
    preserveComments: true,
    verboseOutput: false
};
// =============================================================================
// MigrationSessionManager
// =============================================================================
/**
 * Manages the migration session state machine.
 * Extends EventDispatcher for reactive updates to UI.
 */
class MigrationSessionManager extends EventDispatcher.EventDispatcher {
    constructor() {
        super(...arguments);
        this.session = null;
        this.orchestrator = null; // AIMigrationOrchestrator instance
    }
    /**
     * Creates a new migration session for a project
     */
    async createSession(sourcePath, projectName) {
        // Generate unique session ID
        const sessionId = `migration-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
        // Detect runtime version
        const versionInfo = await (0,ProjectScanner/* detectRuntimeVersion */.Cb)(sourcePath);
        // Only allow migration of React 17 projects
        if (versionInfo.version !== 'react17' && versionInfo.version !== 'unknown') {
            throw new Error(`Project is already using ${versionInfo.version}. Migration not needed.`);
        }
        // Create session
        this.session = {
            id: sessionId,
            step: 'confirm',
            source: {
                path: sourcePath,
                name: projectName,
                runtimeVersion: 'react17'
            },
            target: {
                path: '', // Will be set when user confirms
                copied: false
            }
        };
        this.notifyListeners('sessionCreated', { session: this.session });
        return this.session;
    }
    /**
     * Gets the current session
     */
    getSession() {
        return this.session;
    }
    /**
     * Gets the current step
     */
    getCurrentStep() {
        var _a, _b;
        return (_b = (_a = this.session) === null || _a === void 0 ? void 0 : _a.step) !== null && _b !== void 0 ? _b : null;
    }
    /**
     * Validates if a step transition is allowed
     */
    canTransitionTo(from, to) {
        var _a, _b;
        const allowedTransitions = {
            confirm: ['scanning'],
            scanning: ['report', 'failed'],
            report: ['configureAi', 'migrating'], // Can skip AI config if no AI needed
            configureAi: ['migrating', 'report'], // Can go back to report (cancel)
            migrating: ['complete', 'failed'],
            complete: [], // Terminal state
            failed: ['confirm'] // Can retry from beginning
        };
        return (_b = (_a = allowedTransitions[from]) === null || _a === void 0 ? void 0 : _a.includes(to)) !== null && _b !== void 0 ? _b : false;
    }
    /**
     * Transitions to a new step
     */
    async transitionTo(step) {
        if (!this.session) {
            throw new Error('No active migration session');
        }
        const currentStep = this.session.step;
        if (!this.canTransitionTo(currentStep, step)) {
            throw new Error(`Invalid transition from "${currentStep}" to "${step}"`);
        }
        const previousStep = this.session.step;
        this.session.step = step;
        this.notifyListeners('stepChanged', {
            session: this.session,
            previousStep,
            newStep: step
        });
    }
    /**
     * Sets the target path for the migrated project copy
     */
    setTargetPath(targetPath) {
        if (!this.session) {
            throw new Error('No active migration session');
        }
        this.session.target.path = targetPath;
        this.notifyListeners('targetPathSet', {
            session: this.session,
            targetPath
        });
    }
    /**
     * Starts scanning the project for migration needs
     */
    async startScanning() {
        if (!this.session) {
            throw new Error('No active migration session');
        }
        await this.transitionTo('scanning');
        try {
            const scan = await (0,ProjectScanner/* scanProjectForMigration */.OA)(this.session.source.path, (progress, currentItem, stats) => {
                this.notifyListeners('scanProgress', {
                    session: this.session,
                    progress,
                    currentItem,
                    stats
                });
            });
            this.session.scan = scan;
            await this.transitionTo('report');
            this.notifyListeners('scanComplete', {
                session: this.session,
                scan
            });
            return scan;
        }
        catch (error) {
            await this.transitionTo('failed');
            throw error;
        }
    }
    /**
     * Configures AI settings for the migration
     */
    configureAI(config) {
        var _a, _b, _c;
        if (!this.session) {
            throw new Error('No active migration session');
        }
        this.session.ai = {
            enabled: (_a = config.enabled) !== null && _a !== void 0 ? _a : false,
            apiKey: config.apiKey,
            budget: (_b = config.budget) !== null && _b !== void 0 ? _b : DEFAULT_AI_BUDGET,
            preferences: (_c = config.preferences) !== null && _c !== void 0 ? _c : DEFAULT_AI_PREFERENCES
        };
        this.notifyListeners('aiConfigured', {
            session: this.session,
            ai: this.session.ai
        });
    }
    /**
     * Starts the migration process
     */
    async startMigration() {
        var _a, _b, _c, _d, _e;
        if (!this.session) {
            throw new Error('No active migration session');
        }
        if (!this.session.scan) {
            throw new Error('Project must be scanned before migration');
        }
        await this.transitionTo('migrating');
        const startTime = Date.now();
        // Initialize progress
        this.session.progress = {
            phase: 'copying',
            current: 0,
            total: this.getTotalMigrationSteps(),
            log: []
        };
        try {
            // Phase 1: Copy project
            await this.executeCopyPhase();
            // Phase 2: Automatic migrations
            await this.executeAutomaticPhase();
            // Phase 3: AI-assisted migrations (if enabled)
            if ((_a = this.session.ai) === null || _a === void 0 ? void 0 : _a.enabled) {
                await this.executeAIAssistedPhase();
            }
            // Phase 4: Finalize
            await this.executeFinalizePhase();
            // Calculate result
            const result = {
                success: true,
                migrated: this.getSuccessfulMigrationCount(),
                needsReview: this.getNeedsReviewCount(),
                failed: this.getFailedCount(),
                totalCost: (_c = (_b = this.session.ai) === null || _b === void 0 ? void 0 : _b.budget.spent) !== null && _c !== void 0 ? _c : 0,
                duration: Date.now() - startTime
            };
            this.session.result = result;
            await this.transitionTo('complete');
            this.notifyListeners('migrationComplete', {
                session: this.session,
                result
            });
            return result;
        }
        catch (error) {
            const result = {
                success: false,
                migrated: this.getSuccessfulMigrationCount(),
                needsReview: this.getNeedsReviewCount(),
                failed: this.getFailedCount() + 1,
                totalCost: (_e = (_d = this.session.ai) === null || _d === void 0 ? void 0 : _d.budget.spent) !== null && _e !== void 0 ? _e : 0,
                duration: Date.now() - startTime
            };
            this.session.result = result;
            await this.transitionTo('failed');
            this.notifyListeners('migrationFailed', {
                session: this.session,
                error,
                result
            });
            throw error;
        }
    }
    /**
     * Adds a log entry to the migration progress
     */
    addLogEntry(entry) {
        var _a;
        if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.progress))
            return;
        const logEntry = {
            ...entry,
            timestamp: new Date().toISOString()
        };
        this.session.progress.log.push(logEntry);
        this.notifyListeners('logEntry', {
            session: this.session,
            entry: logEntry
        });
    }
    /**
     * Updates migration progress
     */
    updateProgress(updates) {
        var _a;
        if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.progress))
            return;
        Object.assign(this.session.progress, updates);
        this.notifyListeners('progressUpdated', {
            session: this.session,
            progress: this.session.progress
        });
    }
    /**
     * Cancels the current migration session
     */
    cancelSession() {
        if (!this.session)
            return;
        // Abort orchestrator if running
        if (this.orchestrator) {
            this.orchestrator.abort();
            this.orchestrator = null;
        }
        const session = this.session;
        this.session = null;
        this.notifyListeners('sessionCancelled', { session });
    }
    /**
     * Resets a failed session to retry
     */
    async resetForRetry() {
        if (!this.session) {
            throw new Error('No active migration session');
        }
        if (this.session.step !== 'failed') {
            throw new Error('Can only reset failed sessions');
        }
        await this.transitionTo('confirm');
        // Clear progress and result
        this.session.progress = undefined;
        this.session.result = undefined;
        this.session.target.copied = false;
        this.notifyListeners('sessionReset', { session: this.session });
    }
    // ===========================================================================
    // Private Migration Phase Methods
    // ===========================================================================
    getTotalMigrationSteps() {
        var _a;
        if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.scan))
            return 0;
        const { categories } = this.session.scan;
        return (1 + // Copy phase
            categories.automatic.length +
            categories.simpleFixes.length +
            categories.needsReview.length +
            1 // Finalize phase
        );
    }
    getSuccessfulMigrationCount() {
        var _a, _b, _c;
        // Count from log entries
        return (_c = (_b = (_a = this.session) === null || _a === void 0 ? void 0 : _a.progress) === null || _b === void 0 ? void 0 : _b.log.filter((l) => l.level === 'success').length) !== null && _c !== void 0 ? _c : 0;
    }
    getNeedsReviewCount() {
        var _a, _b, _c;
        return (_c = (_b = (_a = this.session) === null || _a === void 0 ? void 0 : _a.scan) === null || _b === void 0 ? void 0 : _b.categories.needsReview.length) !== null && _c !== void 0 ? _c : 0;
    }
    getFailedCount() {
        var _a, _b, _c;
        return (_c = (_b = (_a = this.session) === null || _a === void 0 ? void 0 : _a.progress) === null || _b === void 0 ? void 0 : _b.log.filter((l) => l.level === 'error').length) !== null && _c !== void 0 ? _c : 0;
    }
    async executeCopyPhase() {
        if (!this.session)
            return;
        const sourcePath = this.session.source.path;
        const targetPath = this.session.target.path;
        this.updateProgress({ phase: 'copying', current: 0 });
        this.addLogEntry({
            level: 'info',
            message: `Copying project from ${sourcePath} to ${targetPath}...`
        });
        try {
            // Check if target already exists
            const targetExists = await src.filesystem.exists(targetPath);
            if (targetExists) {
                throw new Error(`Target directory already exists: ${targetPath}`);
            }
            // Create target directory
            await src.filesystem.makeDirectory(targetPath);
            // Copy all files recursively
            await this.copyDirectoryRecursive(sourcePath, targetPath);
            this.session.target.copied = true;
            this.addLogEntry({
                level: 'success',
                message: 'Project copied successfully'
            });
            this.updateProgress({ current: 1 });
        }
        catch (error) {
            this.addLogEntry({
                level: 'error',
                message: `Failed to copy project: ${error instanceof Error ? error.message : 'Unknown error'}`
            });
            throw error;
        }
    }
    /**
     * Recursively copies a directory and its contents
     * Uses copyFile to preserve binary files (fonts, images, etc.)
     */
    async copyDirectoryRecursive(sourcePath, targetPath) {
        const entries = await src.filesystem.listDirectory(sourcePath);
        for (const entry of entries) {
            const sourceItemPath = entry.fullPath;
            const targetItemPath = `${targetPath}/${entry.name}`;
            if (entry.isDirectory) {
                // Skip node_modules and .git folders
                if (entry.name === 'node_modules' || entry.name === '.git') {
                    continue;
                }
                // Create directory and recurse
                await src.filesystem.makeDirectory(targetItemPath);
                await this.copyDirectoryRecursive(sourceItemPath, targetItemPath);
            }
            else {
                // Copy file using copyFile to preserve binary files correctly
                await src.filesystem.copyFile(sourceItemPath, targetItemPath);
            }
        }
    }
    async executeAutomaticPhase() {
        var _a;
        if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.scan))
            return;
        this.updateProgress({ phase: 'automatic' });
        this.addLogEntry({
            level: 'info',
            message: 'Applying automatic migrations...'
        });
        const { automatic, simpleFixes } = this.session.scan.categories;
        const allAutomatic = [...automatic, ...simpleFixes];
        for (let i = 0; i < allAutomatic.length; i++) {
            const component = allAutomatic[i];
            this.updateProgress({
                current: 1 + i,
                currentComponent: component.name
            });
            // TODO: Implement actual automatic fixes
            await this.simulateDelay(100);
            this.addLogEntry({
                level: 'success',
                component: component.name,
                message: `Migrated automatically`
            });
        }
    }
    async executeAIAssistedPhase() {
        var _a, _b, _c;
        if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.scan) || !((_b = this.session.ai) === null || _b === void 0 ? void 0 : _b.enabled) || !this.session.ai.apiKey)
            return;
        this.updateProgress({ phase: 'ai-assisted' });
        this.addLogEntry({
            level: 'info',
            message: 'Starting AI-assisted migration with Claude...'
        });
        const { needsReview } = this.session.scan.categories;
        // Dynamic import to avoid loading unless needed
        const { AIMigrationOrchestrator } = await Promise.all(/* import() */[__webpack_require__.e(773), __webpack_require__.e(605)]).then(__webpack_require__.bind(__webpack_require__, 61605));
        // Create orchestrator with budget pause callback
        const orchestrator = new AIMigrationOrchestrator(this.session.ai.apiKey, {
            maxPerSession: this.session.ai.budget.maxPerSession,
            pauseIncrement: this.session.ai.budget.pauseIncrement
        }, {
            maxRetries: 3,
            minConfidence: 0.7,
            verifyMigration: true
        }, async (budgetState) => {
            // Emit budget pause event
            return new Promise((resolve) => {
                this.notifyListeners('budget-pause-required', {
                    session: this.session,
                    budgetState,
                    resolve
                });
            });
        });
        // Track orchestrator for abort capability
        this.orchestrator = orchestrator;
        try {
            for (let i = 0; i < needsReview.length; i++) {
                const component = needsReview[i];
                this.updateProgress({
                    current: this.getAutomaticComponentCount() + i + 1,
                    currentComponent: component.name
                });
                this.addLogEntry({
                    level: 'info',
                    component: component.name,
                    message: 'Starting AI migration...'
                });
                // Read source code
                const sourcePath = `${this.session.source.path}/${component.path}`;
                let sourceCode;
                try {
                    sourceCode = await src.filesystem.readFile(sourcePath);
                }
                catch (error) {
                    this.addLogEntry({
                        level: 'error',
                        component: component.name,
                        message: `Failed to read source file: ${error instanceof Error ? error.message : 'Unknown error'}`
                    });
                    continue;
                }
                // Migrate with AI
                const result = await orchestrator.migrateComponent(component, sourceCode, this.session.ai.preferences, (update) => {
                    // Progress callback
                    this.addLogEntry({
                        level: 'info',
                        component: component.name,
                        message: update.message
                    });
                }, async (request) => {
                    // Decision callback
                    return new Promise((resolve) => {
                        this.notifyListeners('ai-decision-required', {
                            session: this.session,
                            request,
                            resolve
                        });
                    });
                });
                // Update budget
                if ((_c = this.session.ai) === null || _c === void 0 ? void 0 : _c.budget) {
                    this.session.ai.budget.spent += result.totalCost;
                }
                // Handle result
                if (result.status === 'success' && result.migratedCode) {
                    // Write migrated code to target
                    const targetPath = `${this.session.target.path}/${component.path}`;
                    try {
                        await src.filesystem.writeFile(targetPath, result.migratedCode);
                        this.addLogEntry({
                            level: 'success',
                            component: component.name,
                            message: `Migrated successfully (${result.attempts} attempts)`,
                            cost: result.totalCost
                        });
                    }
                    catch (error) {
                        this.addLogEntry({
                            level: 'error',
                            component: component.name,
                            message: `Failed to write migrated file: ${error instanceof Error ? error.message : 'Unknown error'}`
                        });
                    }
                }
                else if (result.status === 'partial' && result.migratedCode) {
                    // Write partial migration
                    const targetPath = `${this.session.target.path}/${component.path}`;
                    try {
                        await src.filesystem.writeFile(targetPath, result.migratedCode);
                        this.addLogEntry({
                            level: 'warning',
                            component: component.name,
                            message: 'Partial migration - manual review required',
                            cost: result.totalCost
                        });
                    }
                    catch (error) {
                        this.addLogEntry({
                            level: 'error',
                            component: component.name,
                            message: `Failed to write partial migration: ${error instanceof Error ? error.message : 'Unknown error'}`
                        });
                    }
                }
                else if (result.status === 'failed') {
                    this.addLogEntry({
                        level: 'error',
                        component: component.name,
                        message: result.error || 'Migration failed',
                        details: result.aiSuggestion,
                        cost: result.totalCost
                    });
                }
                else if (result.status === 'skipped') {
                    this.addLogEntry({
                        level: 'warning',
                        component: component.name,
                        message: result.warnings[0] || 'Component skipped',
                        cost: result.totalCost
                    });
                }
            }
            this.addLogEntry({
                level: 'success',
                message: `AI migration complete. Total spent: $${this.session.ai.budget.spent.toFixed(2)}`
            });
        }
        catch (error) {
            this.addLogEntry({
                level: 'error',
                message: `AI migration error: ${error instanceof Error ? error.message : 'Unknown error'}`
            });
            throw error;
        }
        finally {
            this.orchestrator = null;
        }
    }
    getAutomaticComponentCount() {
        var _a;
        if (!((_a = this.session) === null || _a === void 0 ? void 0 : _a.scan))
            return 0;
        const { automatic, simpleFixes } = this.session.scan.categories;
        return automatic.length + simpleFixes.length;
    }
    async executeFinalizePhase() {
        var _a, _b;
        if (!this.session)
            return;
        this.updateProgress({ phase: 'finalizing' });
        this.addLogEntry({
            level: 'info',
            message: 'Finalizing migration...'
        });
        try {
            // Update project.json with migration metadata
            const targetProjectJsonPath = `${this.session.target.path}/project.json`;
            // Read existing project.json
            const projectJson = (await src.filesystem.readJson(targetProjectJsonPath));
            // Add React 19 markers
            projectJson.runtimeVersion = 'react19';
            projectJson.migratedFrom = {
                version: 'react17',
                date: new Date().toISOString(),
                originalPath: this.session.source.path,
                aiAssisted: (_b = (_a = this.session.ai) === null || _a === void 0 ? void 0 : _a.enabled) !== null && _b !== void 0 ? _b : false
            };
            // Write updated project.json back
            await src.filesystem.writeFile(targetProjectJsonPath, JSON.stringify(projectJson, null, 2));
            this.addLogEntry({
                level: 'success',
                message: 'Project marked as React 19'
            });
        }
        catch (error) {
            this.addLogEntry({
                level: 'warning',
                message: `Could not update project.json metadata: ${error instanceof Error ? error.message : 'Unknown error'}`
            });
            // Don't throw - this is not a critical failure
        }
        this.addLogEntry({
            level: 'success',
            message: 'Migration finalized'
        });
        this.updateProgress({
            current: this.getTotalMigrationSteps()
        });
    }
    simulateDelay(ms) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }
}
// =============================================================================
// Singleton Export
// =============================================================================
/**
 * Global migration session manager instance
 */
const migrationSessionManager = new MigrationSessionManager();
// =============================================================================
// Helper Functions
// =============================================================================
/**
 * Checks if a project needs migration
 */
async function checkProjectNeedsMigration(projectPath) {
    const versionInfo = await detectRuntimeVersion(projectPath);
    return {
        needsMigration: versionInfo.version === 'react17' || versionInfo.version === 'unknown',
        versionInfo
    };
}
/**
 * Gets a human-readable step label
 */
function getStepLabel(step) {
    const labels = {
        confirm: 'Confirm Migration',
        scanning: 'Scanning Project',
        report: 'Migration Report',
        configureAi: 'Configure AI Assistance',
        migrating: 'Migrating',
        complete: 'Migration Complete',
        failed: 'Migration Failed'
    };
    return labels[step];
}
/**
 * Gets the step number for progress display (1-indexed)
 */
function getStepNumber(step) {
    const order = ['confirm', 'scanning', 'report', 'configureAi', 'migrating', 'complete'];
    const index = order.indexOf(step);
    return index >= 0 ? index + 1 : 0;
}
/**
 * Gets total number of steps for progress display
 */
function getTotalSteps(includeAi) {
    return includeAi ? 6 : 5;
}

;// ./src/editor/src/utils/migration/keyStorage.ts
/**
 * API Key Storage with Encryption
 *
 * Securely stores Anthropic API keys using Electron's safeStorage API
 * for OS-level encryption, with electron-store as a fallback.
 *
 * @module migration/keyStorage
 */

// safeStorage is available on remote in Electron
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { safeStorage } = __webpack_require__(52391);
const keyStorage_store = new (external_electron_store_default())({
    name: 'ai-config',
    encryptionKey: 'opennoodl-migration' // Additional layer
});
/**
 * Save an API key with OS-level encryption
 */
async function saveApiKey(apiKey) {
    // Use Electron's safeStorage for OS-level encryption
    if (safeStorage.isEncryptionAvailable()) {
        const encrypted = safeStorage.encryptString(apiKey);
        keyStorage_store.set('anthropic.apiKey', encrypted.toString('base64'));
    }
    else {
        // Fallback to electron-store encryption
        keyStorage_store.set('anthropic.apiKey', apiKey);
    }
}
/**
 * Retrieve the stored API key
 */
async function getApiKey() {
    const stored = keyStorage_store.get('anthropic.apiKey');
    if (!stored)
        return null;
    if (safeStorage.isEncryptionAvailable()) {
        try {
            const buffer = Buffer.from(stored, 'base64');
            return safeStorage.decryptString(buffer);
        }
        catch {
            return null;
        }
    }
    return stored;
}
/**
 * Clear the stored API key
 */
async function clearApiKey() {
    keyStorage_store.delete('anthropic.apiKey');
}
/**
 * Test an Anthropic API key by making a minimal API call
 */
async function testAnthropicKey(apiKey) {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const Anthropic = __webpack_require__(63065);
    const client = new Anthropic({
        apiKey,
        dangerouslyAllowBrowser: true // Safe in Electron - code runs locally, not in public browser
    });
    try {
        // Make a minimal API call to verify the key
        await client.messages.create({
            model: 'claude-sonnet-4-20250514',
            max_tokens: 10,
            messages: [{ role: 'user', content: 'Hi' }]
        });
        return true;
    }
    catch (error) {
        const err = error;
        if (err.status === 401) {
            throw new Error('Invalid API key');
        }
        if (err.status === 403) {
            throw new Error('API key does not have required permissions');
        }
        throw new Error(`API error: ${err.message || 'Unknown error'}`);
    }
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/migration/AIConfigPanel.module.scss
var AIConfigPanel_module = __webpack_require__(62733);
;// ./src/editor/src/views/migration/AIConfigPanel.module.scss

      
      
      
      
      
      
      
      
      

var AIConfigPanel_module_options = {};

AIConfigPanel_module_options.styleTagTransform = (styleTagTransform_default());
AIConfigPanel_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      AIConfigPanel_module_options.insert = insertBySelector_default().bind(null, "head");
    
AIConfigPanel_module_options.domAPI = (styleDomAPI_default());
AIConfigPanel_module_options.insertStyleElement = (insertStyleElement_default());

var AIConfigPanel_module_update = injectStylesIntoStyleTag_default()(AIConfigPanel_module/* default */.A, AIConfigPanel_module_options);




       /* harmony default export */ const migration_AIConfigPanel_module = (AIConfigPanel_module/* default */.A && AIConfigPanel_module/* default */.A.locals ? AIConfigPanel_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/migration/AIConfigPanel.tsx
/**
 * AI Configuration Panel
 *
 * First-time setup UI for configuring Anthropic API key,
 * budget controls, and migration preferences.
 */






function AIConfigPanel({ existingConfig, onSave, onCancel }) {
    var _a, _b;
    const [apiKey, setApiKey] = (0,external_react_.useState)((existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.apiKey) || '');
    const [maxBudget, setMaxBudget] = (0,external_react_.useState)((existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.budget.maxPerSession) || 5);
    const [pauseIncrement, setPauseIncrement] = (0,external_react_.useState)((existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.budget.pauseIncrement) || 1);
    const [showEstimates, setShowEstimates] = (0,external_react_.useState)((_a = existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.budget.showEstimates) !== null && _a !== void 0 ? _a : true);
    const [preferFunctional, setPreferFunctional] = (0,external_react_.useState)((_b = existingConfig === null || existingConfig === void 0 ? void 0 : existingConfig.preferences.preferFunctional) !== null && _b !== void 0 ? _b : true);
    const [validating, setValidating] = (0,external_react_.useState)(false);
    const [validationError, setValidationError] = (0,external_react_.useState)(null);
    const [validationSuccess, setValidationSuccess] = (0,external_react_.useState)(false);
    const validateApiKey = async () => {
        setValidating(true);
        setValidationError(null);
        setValidationSuccess(false);
        try {
            await testAnthropicKey(apiKey);
            setValidationSuccess(true);
            return true;
        }
        catch (error) {
            const err = error;
            setValidationError(err.message || 'Validation failed');
            return false;
        }
        finally {
            setValidating(false);
        }
    };
    const handleSave = async () => {
        if (await validateApiKey()) {
            onSave({
                apiKey,
                enabled: true, // Enable AI when config is saved
                budget: {
                    maxPerSession: maxBudget,
                    pauseIncrement,
                    showEstimates
                },
                preferences: {
                    preferFunctional,
                    preserveComments: true,
                    verboseOutput: true
                }
            });
        }
    };
    return (external_react_default().createElement("div", { className: migration_AIConfigPanel_module['AIConfigPanel'] },
        external_react_default().createElement("div", { className: migration_AIConfigPanel_module['Header'] },
            external_react_default().createElement("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none" },
                external_react_default().createElement("path", { d: "M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5z", fill: "currentColor", opacity: "0.2" }),
                external_react_default().createElement("path", { d: "M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5zm0 2.18l8 3.64v9.18c0 4.52-3.13 8.78-7 9.82-3.87-1.04-7-5.3-7-9.82V7.82l6-2.64z", fill: "currentColor" }),
                external_react_default().createElement("path", { d: "M10.5 13.5l-2-2-1.5 1.5 3.5 3.5 6-6-1.5-1.5-4.5 4.5z", fill: "currentColor" })),
            external_react_default().createElement("div", { className: migration_AIConfigPanel_module['HeaderText'] },
                external_react_default().createElement("h3", null, "Configure AI Migration Assistant"),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "OpenNoodl uses Claude (by Anthropic) to intelligently migrate complex code patterns."))),
        external_react_default().createElement("section", { className: migration_AIConfigPanel_module['Section'] },
            external_react_default().createElement("h4", null, "Anthropic API Key"),
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy },
                "You'll need an API key from Anthropic.",
                ' ',
                external_react_default().createElement("a", { href: "https://console.anthropic.com", target: "_blank", rel: "noopener noreferrer" }, "Get one here \u2192")),
            external_react_default().createElement("div", { className: migration_AIConfigPanel_module['InputGroup'] },
                external_react_default().createElement(TextInput, { type: "password", placeholder: "sk-ant-api03-...", value: apiKey, onChange: (e) => setApiKey(e.target.value) }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, label: validating ? 'Validating...' : 'Validate', onClick: validateApiKey, isDisabled: !apiKey || validating })),
            validationSuccess && (external_react_default().createElement("div", { className: migration_AIConfigPanel_module['ValidationSuccess'] },
                external_react_default().createElement("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "currentColor" },
                    external_react_default().createElement("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" })),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "API key validated successfully!"))),
            validationError && (external_react_default().createElement("div", { className: migration_AIConfigPanel_module['ValidationError'] },
                external_react_default().createElement("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "currentColor" },
                    external_react_default().createElement("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z" })),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, validationError))),
            external_react_default().createElement("div", { className: migration_AIConfigPanel_module['SecurityNote'] },
                external_react_default().createElement("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "currentColor" },
                    external_react_default().createElement("path", { d: "M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z" })),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "Your API key is stored locally and encrypted. It's never sent to OpenNoodl servers - all API calls go directly to Anthropic."))),
        external_react_default().createElement("section", { className: migration_AIConfigPanel_module['Section'] },
            external_react_default().createElement("h4", null, "Budget Controls"),
            external_react_default().createElement("div", { className: migration_AIConfigPanel_module['Field'] },
                external_react_default().createElement("label", null, "Maximum spend per migration session"),
                external_react_default().createElement("div", { className: migration_AIConfigPanel_module['BudgetRow'] },
                    external_react_default().createElement("span", null, "$"),
                    external_react_default().createElement("input", { type: "number", min: 1, max: 100, step: 1, value: maxBudget, onChange: (e) => setMaxBudget(Number(e.target.value)), className: migration_AIConfigPanel_module['BudgetInput'] })),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "Typical migration: $0.10 - $2.00")),
            external_react_default().createElement("div", { className: migration_AIConfigPanel_module['Field'] },
                external_react_default().createElement("label", { className: migration_AIConfigPanel_module['Checkbox'] },
                    external_react_default().createElement("input", { type: "checkbox", checked: pauseIncrement > 0, onChange: (e) => setPauseIncrement(e.target.checked ? 1 : 0) }),
                    external_react_default().createElement("span", null,
                        "Pause and ask before each $",
                        pauseIncrement,
                        " increment"))),
            external_react_default().createElement("div", { className: migration_AIConfigPanel_module['Field'] },
                external_react_default().createElement("label", { className: migration_AIConfigPanel_module['Checkbox'] },
                    external_react_default().createElement("input", { type: "checkbox", checked: showEstimates, onChange: (e) => setShowEstimates(e.target.checked) }),
                    external_react_default().createElement("span", null, "Show cost estimate before each component")))),
        external_react_default().createElement("section", { className: migration_AIConfigPanel_module['Section'] },
            external_react_default().createElement("h4", null, "Migration Preferences"),
            external_react_default().createElement("div", { className: migration_AIConfigPanel_module['Field'] },
                external_react_default().createElement("label", { className: migration_AIConfigPanel_module['Checkbox'] },
                    external_react_default().createElement("input", { type: "checkbox", checked: preferFunctional, onChange: (e) => setPreferFunctional(e.target.checked) }),
                    external_react_default().createElement("span", null, "Prefer converting to functional components with hooks")),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, "When possible, Claude will convert class components to modern functional components"))),
        external_react_default().createElement("div", { className: migration_AIConfigPanel_module['Actions'] },
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, label: "Cancel", onClick: onCancel }),
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Cta, label: "Save & Continue", onClick: handleSave, isDisabled: !apiKey || validating }))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/migration/components/WizardProgress.module.scss
var WizardProgress_module = __webpack_require__(36172);
;// ./src/editor/src/views/migration/components/WizardProgress.module.scss

      
      
      
      
      
      
      
      
      

var WizardProgress_module_options = {};

WizardProgress_module_options.styleTagTransform = (styleTagTransform_default());
WizardProgress_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      WizardProgress_module_options.insert = insertBySelector_default().bind(null, "head");
    
WizardProgress_module_options.domAPI = (styleDomAPI_default());
WizardProgress_module_options.insertStyleElement = (insertStyleElement_default());

var WizardProgress_module_update = injectStylesIntoStyleTag_default()(WizardProgress_module/* default */.A, WizardProgress_module_options);




       /* harmony default export */ const components_WizardProgress_module = (WizardProgress_module/* default */.A && WizardProgress_module/* default */.A.locals ? WizardProgress_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/migration/components/WizardProgress.tsx
/**
 * WizardProgress
 *
 * A visual progress indicator showing the current step in the migration wizard.
 *
 * @module noodl-editor/views/migration/components
 * @since 1.2.0
 */



function WizardProgress({ currentStep, totalSteps, stepLabels }) {
    return (external_react_default().createElement("div", { className: components_WizardProgress_module['Root'] },
        external_react_default().createElement("div", { className: components_WizardProgress_module['Steps'] }, stepLabels.map((label, index) => {
            const stepNumber = index + 1;
            const isActive = stepNumber === currentStep;
            const isCompleted = stepNumber < currentStep;
            return (external_react_default().createElement("div", { key: label, className: external_classnames_default()(components_WizardProgress_module['Step'], isActive && components_WizardProgress_module['is-active'], isCompleted && components_WizardProgress_module['is-completed']) },
                external_react_default().createElement("div", { className: components_WizardProgress_module['StepIndicator'] }, isCompleted ? (external_react_default().createElement("svg", { viewBox: "0 0 16 16", className: components_WizardProgress_module['CheckIcon'] },
                    external_react_default().createElement("path", { d: "M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z", fill: "currentColor" }))) : (external_react_default().createElement("span", null, stepNumber))),
                external_react_default().createElement("span", { className: components_WizardProgress_module['StepLabel'] }, label),
                index < stepLabels.length - 1 && (external_react_default().createElement("div", { className: external_classnames_default()(components_WizardProgress_module['StepConnector'], isCompleted && components_WizardProgress_module['is-completed']) }))));
        })),
        external_react_default().createElement("div", { className: components_WizardProgress_module['ProgressBar'] },
            external_react_default().createElement("div", { className: components_WizardProgress_module['ProgressFill'], style: { width: `${((currentStep - 1) / (totalSteps - 1)) * 100}%` } }))));
}
/* harmony default export */ const components_WizardProgress = ((/* unused pure expression or super */ null && (WizardProgress)));

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/migration/MigrationWizard.module.scss
var MigrationWizard_module = __webpack_require__(80222);
;// ./src/editor/src/views/migration/MigrationWizard.module.scss

      
      
      
      
      
      
      
      
      

var MigrationWizard_module_options = {};

MigrationWizard_module_options.styleTagTransform = (styleTagTransform_default());
MigrationWizard_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      MigrationWizard_module_options.insert = insertBySelector_default().bind(null, "head");
    
MigrationWizard_module_options.domAPI = (styleDomAPI_default());
MigrationWizard_module_options.insertStyleElement = (insertStyleElement_default());

var MigrationWizard_module_update = injectStylesIntoStyleTag_default()(MigrationWizard_module/* default */.A, MigrationWizard_module_options);




       /* harmony default export */ const migration_MigrationWizard_module = (MigrationWizard_module/* default */.A && MigrationWizard_module/* default */.A.locals ? MigrationWizard_module/* default */.A.locals : undefined);

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/migration/steps/CompleteStep.module.scss
var CompleteStep_module = __webpack_require__(28286);
;// ./src/editor/src/views/migration/steps/CompleteStep.module.scss

      
      
      
      
      
      
      
      
      

var CompleteStep_module_options = {};

CompleteStep_module_options.styleTagTransform = (styleTagTransform_default());
CompleteStep_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      CompleteStep_module_options.insert = insertBySelector_default().bind(null, "head");
    
CompleteStep_module_options.domAPI = (styleDomAPI_default());
CompleteStep_module_options.insertStyleElement = (insertStyleElement_default());

var CompleteStep_module_update = injectStylesIntoStyleTag_default()(CompleteStep_module/* default */.A, CompleteStep_module_options);




       /* harmony default export */ const steps_CompleteStep_module = (CompleteStep_module/* default */.A && CompleteStep_module/* default */.A.locals ? CompleteStep_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/migration/steps/CompleteStep.tsx
/**
 * CompleteStep
 *
 * Step 5 of the migration wizard: Shows final summary.
 *
 * @module noodl-editor/views/migration/steps
 * @since 1.2.0
 */






function CompleteStep_formatDuration(ms) {
    const seconds = Math.floor(ms / 1000);
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    if (minutes > 0) {
        return `${minutes}m ${remainingSeconds}s`;
    }
    return `${seconds}s`;
}
function CompleteStep({ result, sourcePath, targetPath, onOpenProject }) {
    const hasIssues = result.needsReview > 0;
    return (external_react_default().createElement("div", { className: steps_CompleteStep_module['Root'] },
        external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: true },
            external_react_default().createElement("div", { className: steps_CompleteStep_module['Header'] },
                hasIssues ? external_react_default().createElement(CheckWarningIcon, null) : external_react_default().createElement(CheckCircleIcon, null),
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Medium }, hasIssues ? 'Migration Complete (With Notes)' : 'Migration Complete!')),
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Secondary }, "Your project has been migrated to React 19. The original project remains untouched."),
            external_react_default().createElement("div", { className: steps_CompleteStep_module['Stats'] },
                external_react_default().createElement(StatCard, { icon: external_react_default().createElement(CheckIcon, null), value: result.migrated, label: "Migrated", variant: "success" }),
                result.needsReview > 0 && (external_react_default().createElement(StatCard, { icon: external_react_default().createElement(WarningIcon, null), value: result.needsReview, label: "Needs Review", variant: "warning" })),
                result.failed > 0 && (external_react_default().createElement(StatCard, { icon: external_react_default().createElement(ErrorIcon, null), value: result.failed, label: "Failed", variant: "error" }))),
            external_react_default().createElement("div", { className: steps_CompleteStep_module['MetaInfo'] },
                external_react_default().createElement("div", { className: steps_CompleteStep_module['MetaItem'] },
                    external_react_default().createElement(ClockIcon, null),
                    external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small },
                        "Time: ",
                        CompleteStep_formatDuration(result.duration))),
                result.totalCost > 0 && (external_react_default().createElement("div", { className: steps_CompleteStep_module['MetaItem'] },
                    external_react_default().createElement(RobotIcon, null),
                    external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small },
                        "AI cost: $",
                        result.totalCost.toFixed(2))))),
            external_react_default().createElement("div", { className: steps_CompleteStep_module['Paths'] },
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Small }, "Project Locations"),
                external_react_default().createElement("div", { className: steps_CompleteStep_module['PathItem'] },
                    external_react_default().createElement(LockIcon, null),
                    external_react_default().createElement("div", { className: steps_CompleteStep_module['PathContent'] },
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, textType: typography_Text/* TextType */.M2.Shy }, "Original (untouched)"),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, sourcePath))),
                external_react_default().createElement("div", { className: steps_CompleteStep_module['PathItem'] },
                    external_react_default().createElement(CompleteStep_FolderIcon, null),
                    external_react_default().createElement("div", { className: steps_CompleteStep_module['PathContent'] },
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, textType: typography_Text/* TextType */.M2.Shy }, "Migrated copy"),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, targetPath)))),
            external_react_default().createElement("div", { className: steps_CompleteStep_module['NextSteps'] },
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Small }, "What's Next?"),
                external_react_default().createElement("ol", { className: steps_CompleteStep_module['StepsList'] },
                    result.needsReview > 0 && (external_react_default().createElement("li", null,
                        external_react_default().createElement(WarningIcon, null),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, "Components marked with \u26A0\uFE0F have notes in the component panel - click to see migration details"))),
                    external_react_default().createElement("li", null,
                        external_react_default().createElement(CheckIcon, null),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, "Test your app thoroughly before deploying")),
                    external_react_default().createElement("li", null,
                        external_react_default().createElement(TrashIcon, null),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, "Once confirmed working, you can archive or delete the original folder"))))),
        external_react_default().createElement("div", { className: steps_CompleteStep_module['Actions'] },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Open Migrated Project", onClick: onOpenProject })))));
}
function StatCard({ icon, value, label, variant }) {
    return (external_react_default().createElement("div", { className: `${steps_CompleteStep_module['StatCard']} ${steps_CompleteStep_module[`is-${variant}`]}` },
        external_react_default().createElement("div", { className: steps_CompleteStep_module['StatCardIcon'] }, icon),
        external_react_default().createElement("div", { className: steps_CompleteStep_module['StatCardValue'] }, value),
        external_react_default().createElement("div", { className: steps_CompleteStep_module['StatCardLabel'] }, label)));
}
// =============================================================================
// Icons
// =============================================================================
function CheckCircleIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 32, height: 32 },
        external_react_default().createElement("path", { d: "M8 16A8 8 0 108 0a8 8 0 000 16zm3.78-9.72a.75.75 0 00-1.06-1.06L6.75 9.19 5.28 7.72a.75.75 0 00-1.06 1.06l2 2a.75.75 0 001.06 0l4.5-4.5z", fill: "currentColor" })));
}
function CheckWarningIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 32, height: 32 },
        external_react_default().createElement("path", { d: "M8 16A8 8 0 108 0a8 8 0 000 16zm3.78-9.72a.75.75 0 00-1.06-1.06L6.75 9.19 5.28 7.72a.75.75 0 00-1.06 1.06l2 2a.75.75 0 001.06 0l4.5-4.5z", fill: "currentColor" })));
}
function CheckIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z", fill: "currentColor" })));
}
function WarningIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M8.863 1.035c-.39-.678-1.336-.678-1.726 0L.187 12.78c-.403.7.096 1.57.863 1.57h13.9c.767 0 1.266-.87.863-1.57L8.863 1.035zM8 5a.75.75 0 01.75.75v2.5a.75.75 0 11-1.5 0v-2.5A.75.75 0 018 5zm0 7a1 1 0 100-2 1 1 0 000 2z", fill: "currentColor" })));
}
function ErrorIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z", fill: "currentColor" })));
}
function ClockIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M8 0a8 8 0 108 8A8 8 0 008 0zm0 14.5A6.5 6.5 0 1114.5 8 6.5 6.5 0 018 14.5zM8 3.5a.75.75 0 01.75.75V8h2.5a.75.75 0 110 1.5H8a.75.75 0 01-.75-.75V4.25A.75.75 0 018 3.5z", fill: "currentColor" })));
}
function RobotIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M8 0a1 1 0 011 1v1.5h2A2.5 2.5 0 0113.5 5v6a2.5 2.5 0 01-2.5 2.5h-6A2.5 2.5 0 012.5 11V5A2.5 2.5 0 015 2.5h2V1a1 1 0 011-1zM5 4a1 1 0 00-1 1v6a1 1 0 001 1h6a1 1 0 001-1V5a1 1 0 00-1-1H5zm1.5 2a1 1 0 110 2 1 1 0 010-2zm3 0a1 1 0 110 2 1 1 0 010-2zM6 8.5a.5.5 0 000 1h4a.5.5 0 000-1H6z", fill: "currentColor" })));
}
function LockIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M4 6V4a4 4 0 118 0v2h1a1 1 0 011 1v7a1 1 0 01-1 1H3a1 1 0 01-1-1V7a1 1 0 011-1h1zm2 0h4V4a2 2 0 10-4 0v2zm3 4a1 1 0 10-2 0v2a1 1 0 102 0v-2z", fill: "currentColor" })));
}
function CompleteStep_FolderIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M1.75 2A1.75 1.75 0 000 3.75v8.5C0 13.216.784 14 1.75 14h12.5A1.75 1.75 0 0016 12.25v-6.5A1.75 1.75 0 0014.25 4H7.5a.25.25 0 01-.2-.1l-.9-1.2a1.75 1.75 0 00-1.4-.7h-3.25z", fill: "currentColor" })));
}
function TrashIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M6.5 1.75a.25.25 0 01.25-.25h2.5a.25.25 0 01.25.25V3h-3V1.75zm4.5 0V3h2.25a.75.75 0 010 1.5H2.75a.75.75 0 010-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75zM4.496 6.675a.75.75 0 10-1.492.15l.66 6.6A1.75 1.75 0 005.405 15h5.19c.9 0 1.652-.681 1.741-1.576l.66-6.6a.75.75 0 00-1.492-.149l-.66 6.6a.25.25 0 01-.249.225h-5.19a.25.25 0 01-.249-.225l-.66-6.6z", fill: "currentColor" })));
}
/* harmony default export */ const steps_CompleteStep = ((/* unused pure expression or super */ null && (CompleteStep)));

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/migration/steps/ConfirmStep.module.scss
var ConfirmStep_module = __webpack_require__(93837);
;// ./src/editor/src/views/migration/steps/ConfirmStep.module.scss

      
      
      
      
      
      
      
      
      

var ConfirmStep_module_options = {};

ConfirmStep_module_options.styleTagTransform = (styleTagTransform_default());
ConfirmStep_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ConfirmStep_module_options.insert = insertBySelector_default().bind(null, "head");
    
ConfirmStep_module_options.domAPI = (styleDomAPI_default());
ConfirmStep_module_options.insertStyleElement = (insertStyleElement_default());

var ConfirmStep_module_update = injectStylesIntoStyleTag_default()(ConfirmStep_module/* default */.A, ConfirmStep_module_options);




       /* harmony default export */ const steps_ConfirmStep_module = (ConfirmStep_module/* default */.A && ConfirmStep_module/* default */.A.locals ? ConfirmStep_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/migration/steps/ConfirmStep.tsx
/**
 * ConfirmStep
 *
 * Step 1 of the migration wizard: Confirm source and target paths.
 *
 * @module noodl-editor/views/migration/steps
 * @since 1.2.0
 */










function ConfirmStep({ sourcePath, projectName, targetPath, onUpdateTargetPath, onNext, onCancel, loading = false }) {
    const [targetExists, setTargetExists] = (0,external_react_.useState)(false);
    const [checkingPath, setCheckingPath] = (0,external_react_.useState)(false);
    // Check if target path exists
    const checkTargetPath = (0,external_react_.useCallback)(async (path) => {
        if (!path) {
            setTargetExists(false);
            return;
        }
        setCheckingPath(true);
        try {
            const exists = await src.filesystem.exists(path);
            setTargetExists(exists);
        }
        catch {
            setTargetExists(false);
        }
        finally {
            setCheckingPath(false);
        }
    }, []);
    (0,external_react_.useEffect)(() => {
        checkTargetPath(targetPath);
    }, [targetPath, checkTargetPath]);
    const handleTargetChange = (0,external_react_.useCallback)((e) => {
        onUpdateTargetPath(e.target.value);
    }, [onUpdateTargetPath]);
    const handleUseUniqueName = (0,external_react_.useCallback)(() => {
        const timestamp = Date.now();
        const uniquePath = `${sourcePath}-react19-${timestamp}`;
        onUpdateTargetPath(uniquePath);
    }, [sourcePath, onUpdateTargetPath]);
    const canProceed = targetPath && !targetExists && !loading && !checkingPath;
    return (external_react_default().createElement("div", { className: steps_ConfirmStep_module['Root'] },
        external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: true },
            external_react_default().createElement(Box/* Box */.a, { hasBottomSpacing: true },
                external_react_default().createElement(typography_Text/* Text */.EY, null, "We'll create a safe copy of your project before making any changes. Your original project will remain untouched.")),
            external_react_default().createElement("div", { className: steps_ConfirmStep_module['PathSection'] },
                external_react_default().createElement("div", { className: steps_ConfirmStep_module['PathHeader'] },
                    external_react_default().createElement("svg", { viewBox: "0 0 16 16", className: steps_ConfirmStep_module['LockIcon'], width: 16, height: 16 },
                        external_react_default().createElement("path", { d: "M4 6V4a4 4 0 118 0v2h1a1 1 0 011 1v7a1 1 0 01-1 1H3a1 1 0 01-1-1V7a1 1 0 011-1h1zm2 0h4V4a2 2 0 10-4 0v2zm3 4a1 1 0 10-2 0v2a1 1 0 102 0v-2z", fill: "currentColor" })),
                    external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Small }, "Original Project (will not be modified)")),
                external_react_default().createElement("div", { className: steps_ConfirmStep_module['PathDisplay'] },
                    external_react_default().createElement(typography_Text/* Text */.EY, { className: steps_ConfirmStep_module['PathText'] }, sourcePath),
                    external_react_default().createElement(typography_Text/* Text */.EY, { className: steps_ConfirmStep_module['ProjectName'] }, projectName))),
            external_react_default().createElement("div", { className: steps_ConfirmStep_module['Arrow'] },
                external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 20, height: 20 },
                    external_react_default().createElement("path", { d: "M8 2a.75.75 0 01.75.75v8.69l2.22-2.22a.75.75 0 111.06 1.06l-3.5 3.5a.75.75 0 01-1.06 0l-3.5-3.5a.75.75 0 111.06-1.06l2.22 2.22V2.75A.75.75 0 018 2z", fill: "currentColor" })),
                external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, "Creates copy")),
            external_react_default().createElement("div", { className: steps_ConfirmStep_module['PathSection'] },
                external_react_default().createElement("div", { className: steps_ConfirmStep_module['PathHeader'] },
                    external_react_default().createElement("svg", { viewBox: "0 0 16 16", className: steps_ConfirmStep_module['FolderIcon'], width: 16, height: 16 },
                        external_react_default().createElement("path", { d: "M1.75 2A1.75 1.75 0 000 3.75v8.5C0 13.216.784 14 1.75 14h12.5A1.75 1.75 0 0016 12.25v-6.5A1.75 1.75 0 0014.25 4H7.5a.25.25 0 01-.2-.1l-.9-1.2a1.75 1.75 0 00-1.4-.7h-3.25z", fill: "currentColor" })),
                    external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Small }, "Migrated Copy Location")),
                external_react_default().createElement(TextInput, { value: targetPath, onChange: handleTargetChange, UNSAFE_className: steps_ConfirmStep_module['PathInput'] }),
                targetExists && (external_react_default().createElement("div", { className: steps_ConfirmStep_module['PathError'] },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: FeedbackType/* FeedbackType */.M.Danger }, "A folder already exists at this location."),
                    external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Use Different Name", size: inputs_PrimaryButton/* PrimaryButtonSize */._S.Small, variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: handleUseUniqueName })))),
            external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
                external_react_default().createElement("div", { className: steps_ConfirmStep_module['InfoBox'] },
                    external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Small }, "What happens next:"),
                    external_react_default().createElement("ol", { className: steps_ConfirmStep_module['StepsList'] },
                        external_react_default().createElement("li", null, "Your project will be copied to the new location"),
                        external_react_default().createElement("li", null, "We'll scan for compatibility issues"),
                        external_react_default().createElement("li", null, "You'll see a report of what needs to change"),
                        external_react_default().createElement("li", null, "Automatic fixes will be applied"))))),
        external_react_default().createElement("div", { className: steps_ConfirmStep_module['Actions'] },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onCancel, isDisabled: loading }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: loading ? 'Starting...' : 'Start Migration', onClick: onNext, isDisabled: !canProceed })))));
}
/* harmony default export */ const steps_ConfirmStep = ((/* unused pure expression or super */ null && (ConfirmStep)));

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/migration/steps/FailedStep.module.scss
var FailedStep_module = __webpack_require__(22744);
;// ./src/editor/src/views/migration/steps/FailedStep.module.scss

      
      
      
      
      
      
      
      
      

var FailedStep_module_options = {};

FailedStep_module_options.styleTagTransform = (styleTagTransform_default());
FailedStep_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      FailedStep_module_options.insert = insertBySelector_default().bind(null, "head");
    
FailedStep_module_options.domAPI = (styleDomAPI_default());
FailedStep_module_options.insertStyleElement = (insertStyleElement_default());

var FailedStep_module_update = injectStylesIntoStyleTag_default()(FailedStep_module/* default */.A, FailedStep_module_options);




       /* harmony default export */ const steps_FailedStep_module = (FailedStep_module/* default */.A && FailedStep_module/* default */.A.locals ? FailedStep_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/migration/steps/FailedStep.tsx
/**
 * FailedStep
 *
 * Step shown when migration fails. Allows user to retry or cancel.
 *
 * @module noodl-editor/views/migration/steps
 * @since 1.2.0
 */






function FailedStep({ error, onRetry, onCancel }) {
    const errorMessage = (error === null || error === void 0 ? void 0 : error.message) || 'An unknown error occurred during migration.';
    const isNetworkError = errorMessage.toLowerCase().includes('network') ||
        errorMessage.toLowerCase().includes('timeout');
    const isPermissionError = errorMessage.toLowerCase().includes('permission') ||
        errorMessage.toLowerCase().includes('access');
    return (external_react_default().createElement("div", { className: steps_FailedStep_module['Root'] },
        external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: true },
            external_react_default().createElement("div", { className: steps_FailedStep_module['Header'] },
                external_react_default().createElement(ErrorCircleIcon, null),
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Medium }, "Migration Failed")),
            external_react_default().createElement(typography_Text/* Text */.EY, { className: steps_FailedStep_module['DescriptionText'] }, "Something went wrong during the migration process. Your original project is safe and unchanged."),
            external_react_default().createElement("div", { className: steps_FailedStep_module['ErrorBox'] },
                external_react_default().createElement("div", { className: steps_FailedStep_module['ErrorHeader'] },
                    external_react_default().createElement(FailedStep_ErrorIcon, null),
                    external_react_default().createElement(typography_Text/* Text */.EY, { className: steps_FailedStep_module['ErrorText'] }, "Error Details")),
                external_react_default().createElement("div", { className: steps_FailedStep_module['ErrorMessage'] },
                    external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, errorMessage))),
            external_react_default().createElement("div", { className: steps_FailedStep_module['Suggestions'] },
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Small }, "What you can try:"),
                external_react_default().createElement("ul", { className: steps_FailedStep_module['SuggestionList'] },
                    isNetworkError && (external_react_default().createElement("li", null,
                        external_react_default().createElement(WifiIcon, null),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, "Check your internet connection and try again"))),
                    isPermissionError && (external_react_default().createElement("li", null,
                        external_react_default().createElement(FailedStep_LockIcon, null),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, "Make sure you have write access to the target directory"))),
                    external_react_default().createElement("li", null,
                        external_react_default().createElement(FailedStep_RefreshIcon, null),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, "Click \"Try Again\" to restart the migration")),
                    external_react_default().createElement("li", null,
                        external_react_default().createElement(FailedStep_FolderIcon, null),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, "Try choosing a different target directory")),
                    external_react_default().createElement("li", null,
                        external_react_default().createElement(HelpIcon, null),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small },
                            "If the problem persists, check the",
                            ' ',
                            external_react_default().createElement("a", { href: "https://github.com/The-Low-Code-Foundation/OpenNoodl/issues", target: "_blank", rel: "noopener noreferrer", className: steps_FailedStep_module['Link'] }, "GitHub Issues"))))),
            external_react_default().createElement("div", { className: steps_FailedStep_module['SafetyNotice'] },
                external_react_default().createElement(ShieldIcon, null),
                external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, className: steps_FailedStep_module['SafetyText'] }, "Your original project remains untouched. Any partial migration files have been cleaned up."))),
        external_react_default().createElement("div", { className: steps_FailedStep_module['Actions'] },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onCancel }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Try Again", onClick: onRetry })))));
}
// =============================================================================
// Icons
// =============================================================================
function ErrorCircleIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 32, height: 32, className: steps_FailedStep_module['ErrorCircleIcon'] },
        external_react_default().createElement("path", { d: "M8 16A8 8 0 108 0a8 8 0 000 16zm0-11.5a.75.75 0 01.75.75v3.5a.75.75 0 11-1.5 0v-3.5A.75.75 0 018 4.5zm0 8a1 1 0 100-2 1 1 0 000 2z", fill: "currentColor" })));
}
function FailedStep_ErrorIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z", fill: "currentColor" })));
}
function WifiIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M8 12a1.5 1.5 0 100 3 1.5 1.5 0 000-3zM1.332 5.084a.75.75 0 10.97 1.142 9.5 9.5 0 0113.396 0 .75.75 0 00.97-1.142 11 11 0 00-15.336 0zm2.91 2.908a.75.75 0 10.97 1.142 5.5 5.5 0 017.576 0 .75.75 0 00.97-1.142 7 7 0 00-9.516 0z", fill: "currentColor" })));
}
function FailedStep_LockIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M4 6V4a4 4 0 118 0v2h1a1 1 0 011 1v7a1 1 0 01-1 1H3a1 1 0 01-1-1V7a1 1 0 011-1h1zm2 0h4V4a2 2 0 10-4 0v2zm3 4a1 1 0 10-2 0v2a1 1 0 102 0v-2z", fill: "currentColor" })));
}
function FailedStep_RefreshIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M8 3a5 5 0 00-4.546 2.914.5.5 0 01-.908-.414A6 6 0 0113.944 5H12.5a.5.5 0 010-1h3a.5.5 0 01.5.5v3a.5.5 0 11-1 0V6.057A5.956 5.956 0 018 3zM0 8a.5.5 0 01.5-.5h1a.5.5 0 010 1H.5A.5.5 0 010 8zm1.5 2.5a.5.5 0 01.5.5v1.443A5.956 5.956 0 008 13a5 5 0 004.546-2.914.5.5 0 01.908.414A6 6 0 012.056 11H3.5a.5.5 0 010 1h-3a.5.5 0 01-.5-.5v-3a.5.5 0 01.5-.5z", fill: "currentColor" })));
}
function FailedStep_FolderIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M1.75 2A1.75 1.75 0 000 3.75v8.5C0 13.216.784 14 1.75 14h12.5A1.75 1.75 0 0016 12.25v-6.5A1.75 1.75 0 0014.25 4H7.5a.25.25 0 01-.2-.1l-.9-1.2a1.75 1.75 0 00-1.4-.7h-3.25z", fill: "currentColor" })));
}
function HelpIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M8 0a8 8 0 108 8A8 8 0 008 0zm0 14.5A6.5 6.5 0 1114.5 8 6.5 6.5 0 018 14.5zm0-10.25a2.25 2.25 0 00-2.25 2.25.75.75 0 001.5 0 .75.75 0 111.5 0c0 .52-.3.866-.658 1.075-.368.216-.842.425-.842 1.175a.75.75 0 001.5 0c0-.15.099-.282.282-.394.187-.114.486-.291.727-.524A2.25 2.25 0 008 4.25zM8 13a1 1 0 100-2 1 1 0 000 2z", fill: "currentColor" })));
}
function ShieldIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M7.467.133a1.75 1.75 0 011.066 0l5.25 1.68A1.75 1.75 0 0115 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.7 1.7 0 01-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 011.217-1.667l5.25-1.68zm.61 1.429a.25.25 0 00-.153 0l-5.25 1.68a.25.25 0 00-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.2.2 0 00.154 0c2.245-.956 3.582-2.103 4.366-3.298C13.225 9.666 13.5 8.358 13.5 7V3.48a.25.25 0 00-.174-.238l-5.25-1.68zM11.28 6.28a.75.75 0 00-1.06-1.06L7.25 8.19 5.78 6.72a.75.75 0 00-1.06 1.06l2 2a.75.75 0 001.06 0l3.5-3.5z", fill: "currentColor" })));
}
/* harmony default export */ const steps_FailedStep = ((/* unused pure expression or super */ null && (FailedStep)));

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/migration/BudgetApprovalDialog.module.scss
var BudgetApprovalDialog_module = __webpack_require__(24039);
;// ./src/editor/src/views/migration/BudgetApprovalDialog.module.scss

      
      
      
      
      
      
      
      
      

var BudgetApprovalDialog_module_options = {};

BudgetApprovalDialog_module_options.styleTagTransform = (styleTagTransform_default());
BudgetApprovalDialog_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      BudgetApprovalDialog_module_options.insert = insertBySelector_default().bind(null, "head");
    
BudgetApprovalDialog_module_options.domAPI = (styleDomAPI_default());
BudgetApprovalDialog_module_options.insertStyleElement = (insertStyleElement_default());

var BudgetApprovalDialog_module_update = injectStylesIntoStyleTag_default()(BudgetApprovalDialog_module/* default */.A, BudgetApprovalDialog_module_options);




       /* harmony default export */ const migration_BudgetApprovalDialog_module = (BudgetApprovalDialog_module/* default */.A && BudgetApprovalDialog_module/* default */.A.locals ? BudgetApprovalDialog_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/migration/BudgetApprovalDialog.tsx
/**
 * Budget Approval Dialog
 *
 * Pause-and-approve dialog shown when reaching spending increments
 * during AI-assisted migration.
 */




function BudgetApprovalDialog({ state, onApprove, onDeny }) {
    const progressPercent = (state.spent / state.maxPerSession) * 100;
    const pendingPercent = (state.pauseIncrement / state.maxPerSession) * 100;
    return (external_react_default().createElement("div", { className: migration_BudgetApprovalDialog_module['BudgetApprovalDialog'] },
        external_react_default().createElement("div", { className: migration_BudgetApprovalDialog_module['Icon'] },
            external_react_default().createElement("svg", { width: "32", height: "32", viewBox: "0 0 24 24", fill: "currentColor" },
                external_react_default().createElement("path", { d: "M21 18v1c0 1.1-.9 2-2 2H5c-1.11 0-2-.9-2-2V5c0-1.1.89-2 2-2h14c1.1 0 2 .9 2 2v1h-9c-1.11 0-2 .9-2 2v8c0 1.1.89 2 2 2h9zm-9-2h10V8H12v8zm4-2.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" }))),
        external_react_default().createElement("div", { className: migration_BudgetApprovalDialog_module['Content'] },
            external_react_default().createElement("h3", null, "Budget Check"),
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Secondary },
                "You've spent ",
                external_react_default().createElement("strong", null,
                    "$",
                    state.spent.toFixed(2)),
                " of your",
                ' ',
                external_react_default().createElement("strong", null,
                    "$",
                    state.maxPerSession.toFixed(2)),
                " budget."),
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Secondary },
                "Continue with another ",
                external_react_default().createElement("strong", null,
                    "$",
                    state.pauseIncrement.toFixed(2)),
                " allowance?"),
            external_react_default().createElement("div", { className: migration_BudgetApprovalDialog_module['BudgetBar'] },
                external_react_default().createElement("div", { className: migration_BudgetApprovalDialog_module['BudgetBar__Track'] },
                    external_react_default().createElement("div", { className: migration_BudgetApprovalDialog_module['BudgetBar__Spent'], style: { width: `${progressPercent}%` } }),
                    external_react_default().createElement("div", { className: migration_BudgetApprovalDialog_module['BudgetBar__Pending'], style: {
                            left: `${progressPercent}%`,
                            width: `${pendingPercent}%`
                        } }))),
            external_react_default().createElement("div", { className: migration_BudgetApprovalDialog_module['BudgetLabels'] },
                external_react_default().createElement("span", null, "$0"),
                external_react_default().createElement("span", { className: migration_BudgetApprovalDialog_module['Current'] },
                    "$",
                    state.spent.toFixed(2)),
                external_react_default().createElement("span", null,
                    "$",
                    state.maxPerSession.toFixed(2)))),
        external_react_default().createElement("div", { className: migration_BudgetApprovalDialog_module['Actions'] },
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, label: "Stop Here", onClick: onDeny }),
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Cta, label: `Continue (+$${state.pauseIncrement.toFixed(2)})`, onClick: onApprove }))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/migration/DecisionDialog.module.scss
var DecisionDialog_module = __webpack_require__(89587);
;// ./src/editor/src/views/migration/DecisionDialog.module.scss

      
      
      
      
      
      
      
      
      

var DecisionDialog_module_options = {};

DecisionDialog_module_options.styleTagTransform = (styleTagTransform_default());
DecisionDialog_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      DecisionDialog_module_options.insert = insertBySelector_default().bind(null, "head");
    
DecisionDialog_module_options.domAPI = (styleDomAPI_default());
DecisionDialog_module_options.insertStyleElement = (insertStyleElement_default());

var DecisionDialog_module_update = injectStylesIntoStyleTag_default()(DecisionDialog_module/* default */.A, DecisionDialog_module_options);




       /* harmony default export */ const migration_DecisionDialog_module = (DecisionDialog_module/* default */.A && DecisionDialog_module/* default */.A.locals ? DecisionDialog_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/migration/DecisionDialog.tsx
/**
 * Decision Dialog
 *
 * Dialog shown when AI migration fails after max retries.
 * Allows user to choose how to proceed with the component.
 */




function DecisionDialog({ request, onDecision }) {
    const [showingHelp, setShowingHelp] = (0,external_react_.useState)(false);
    const handleGetHelp = () => {
        setShowingHelp(true);
    };
    const handleBack = () => {
        setShowingHelp(false);
    };
    if (showingHelp) {
        return (external_react_default().createElement("div", { className: migration_DecisionDialog_module['DecisionDialog'] },
            external_react_default().createElement("div", { className: migration_DecisionDialog_module['Icon'], "data-type": "help" },
                external_react_default().createElement("svg", { width: "32", height: "32", viewBox: "0 0 24 24", fill: "currentColor" },
                    external_react_default().createElement("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z" }))),
            external_react_default().createElement("div", { className: migration_DecisionDialog_module['Content'] },
                external_react_default().createElement("h3", null, "AI Migration Suggestions"),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Secondary },
                    "The AI couldn't automatically migrate ",
                    external_react_default().createElement("strong", null, request.componentName),
                    " after ",
                    request.attempts,
                    ' ',
                    "attempts. Here's what to look for:"),
                external_react_default().createElement("div", { className: migration_DecisionDialog_module['HelpContent'] },
                    external_react_default().createElement("div", { className: migration_DecisionDialog_module['HelpSection'] },
                        external_react_default().createElement("h4", null, "Common Issues"),
                        external_react_default().createElement("ul", null,
                            external_react_default().createElement("li", null,
                                external_react_default().createElement("strong", null, "Legacy Lifecycle Methods:"),
                                " Replace componentWillMount, componentWillReceiveProps, componentWillUpdate with modern alternatives"),
                            external_react_default().createElement("li", null,
                                external_react_default().createElement("strong", null, "String Refs:"),
                                " Convert ref=\"myRef\" to ref=",
                                '{',
                                " (el) => this.myRef = el ",
                                '}'),
                            external_react_default().createElement("li", null,
                                external_react_default().createElement("strong", null, "findDOMNode:"),
                                " Use ref callbacks to access DOM nodes directly"),
                            external_react_default().createElement("li", null,
                                external_react_default().createElement("strong", null, "Legacy Context:"),
                                " Migrate to modern Context API (createContext/useContext)"))),
                    request.attemptHistory.length > 0 && (external_react_default().createElement("div", { className: migration_DecisionDialog_module['HelpSection'] },
                        external_react_default().createElement("h4", null, "What the AI Tried"),
                        request.attemptHistory.map((attempt, index) => (external_react_default().createElement("div", { key: index, className: migration_DecisionDialog_module['AttemptSummary'] },
                            external_react_default().createElement("strong", null,
                                "Attempt ",
                                index + 1,
                                ":"),
                            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy }, attempt.error)))))),
                    external_react_default().createElement("div", { className: migration_DecisionDialog_module['HelpSection'] },
                        external_react_default().createElement("h4", null, "Recommended Actions"),
                        external_react_default().createElement("ol", null,
                            external_react_default().createElement("li", null, "Open the component in the code editor"),
                            external_react_default().createElement("li", null, "Check the console for specific error messages"),
                            external_react_default().createElement("li", null, "Refer to the React 19 upgrade guide"),
                            external_react_default().createElement("li", null, "Make changes incrementally and test after each change"))))),
            external_react_default().createElement("div", { className: migration_DecisionDialog_module['Actions'] },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, label: "Back", onClick: handleBack }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Cta, label: "Mark for Manual Review", onClick: () => onDecision('skip') }))));
    }
    return (external_react_default().createElement("div", { className: migration_DecisionDialog_module['DecisionDialog'] },
        external_react_default().createElement("div", { className: migration_DecisionDialog_module['Icon'], "data-type": "warning" },
            external_react_default().createElement("svg", { width: "32", height: "32", viewBox: "0 0 24 24", fill: "currentColor" },
                external_react_default().createElement("path", { d: "M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z" }))),
        external_react_default().createElement("div", { className: migration_DecisionDialog_module['Content'] },
            external_react_default().createElement("h3", null, "Migration Needs Your Help"),
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Secondary },
                "The AI couldn't automatically migrate ",
                external_react_default().createElement("strong", null, request.componentName),
                " after ",
                request.attempts,
                ' ',
                "attempts."),
            external_react_default().createElement("div", { className: migration_DecisionDialog_module['CostInfo'] },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy },
                    "Spent so far: ",
                    external_react_default().createElement("strong", null,
                        "$",
                        request.costSpent.toFixed(2)),
                    request.retryCost > 0 && (external_react_default().createElement((external_react_default()).Fragment, null,
                        ' ',
                        "\u00B7 Retry cost: ",
                        external_react_default().createElement("strong", null,
                            "$",
                            request.retryCost.toFixed(2)))))),
            external_react_default().createElement("div", { className: migration_DecisionDialog_module['AttemptHistory'] },
                external_react_default().createElement("h4", null, "Previous Attempts"),
                external_react_default().createElement("div", { className: migration_DecisionDialog_module['Attempts'] }, request.attemptHistory.map((attempt, index) => (external_react_default().createElement("div", { key: index, className: migration_DecisionDialog_module['Attempt'] },
                    external_react_default().createElement("div", { className: migration_DecisionDialog_module['Attempt__Header'] },
                        external_react_default().createElement("span", { className: migration_DecisionDialog_module['Attempt__Number'] },
                            "Attempt ",
                            index + 1),
                        external_react_default().createElement("span", { className: migration_DecisionDialog_module['Attempt__Cost'] },
                            "$",
                            attempt.cost.toFixed(3))),
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, className: migration_DecisionDialog_module['Attempt__Error'] }, attempt.error)))))),
            external_react_default().createElement("div", { className: migration_DecisionDialog_module['Options'] },
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Secondary }, "What would you like to do?"))),
        external_react_default().createElement("div", { className: migration_DecisionDialog_module['Actions'] },
            external_react_default().createElement("div", { className: migration_DecisionDialog_module['Actions__Row'] },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, label: "Try Again", onClick: () => onDecision('retry') }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, label: "Skip for Now", onClick: () => onDecision('skip') })),
            external_react_default().createElement("div", { className: migration_DecisionDialog_module['Actions__Row'] },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Ghost, label: "Get Help", onClick: handleGetHelp }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Danger, label: "Accept Last Attempt", onClick: () => onDecision('manual') })))));
}

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/migration/steps/MigratingStep.module.scss
var MigratingStep_module = __webpack_require__(70903);
;// ./src/editor/src/views/migration/steps/MigratingStep.module.scss

      
      
      
      
      
      
      
      
      

var MigratingStep_module_options = {};

MigratingStep_module_options.styleTagTransform = (styleTagTransform_default());
MigratingStep_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      MigratingStep_module_options.insert = insertBySelector_default().bind(null, "head");
    
MigratingStep_module_options.domAPI = (styleDomAPI_default());
MigratingStep_module_options.insertStyleElement = (insertStyleElement_default());

var MigratingStep_module_update = injectStylesIntoStyleTag_default()(MigratingStep_module/* default */.A, MigratingStep_module_options);




       /* harmony default export */ const steps_MigratingStep_module = (MigratingStep_module/* default */.A && MigratingStep_module/* default */.A.locals ? MigratingStep_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/migration/steps/MigratingStep.tsx
/**
 * MigratingStep
 *
 * Step 4 of the migration wizard: Shows real-time migration progress with AI.
 * Displays budget tracking, component progress, and AI decision panels.
 *
 * @module noodl-editor/views/migration/steps
 * @since 1.2.0
 */









function MigratingStep({ progress, useAi, budget, awaitingDecision, onAiDecision, onPause, budgetApprovalRequest, onBudgetApproval, decisionRequest, onDecision }) {
    const progressPercent = Math.round((progress.current / progress.total) * 100);
    const budgetPercent = budget ? (budget.spent / budget.maxPerSession) * 100 : 0;
    return (external_react_default().createElement("div", { className: steps_MigratingStep_module['Root'] },
        external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: true },
            external_react_default().createElement("div", { className: steps_MigratingStep_module['Header'] },
                external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null),
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Medium }, useAi ? 'AI Migration in Progress' : 'Migrating Project...')),
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Secondary },
                "Phase: ",
                getPhaseLabel(progress.phase)),
            useAi && budget && (external_react_default().createElement("div", { className: steps_MigratingStep_module['BudgetSection'] },
                external_react_default().createElement("div", { className: steps_MigratingStep_module['BudgetHeader'] },
                    external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, textType: typography_Text/* TextType */.M2.Proud }, "AI Budget"),
                    external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small },
                        "$",
                        budget.spent.toFixed(2),
                        " / $",
                        budget.maxPerSession.toFixed(2))),
                external_react_default().createElement("div", { className: steps_MigratingStep_module['BudgetBar'] },
                    external_react_default().createElement("div", { className: `${steps_MigratingStep_module['BudgetFill']} ${budgetPercent > 80 ? steps_MigratingStep_module['is-warning'] : ''}`, style: { width: `${Math.min(budgetPercent, 100)}%` } })))),
            external_react_default().createElement("div", { className: steps_MigratingStep_module['ProgressSection'] },
                external_react_default().createElement("div", { className: steps_MigratingStep_module['ProgressBar'] },
                    external_react_default().createElement("div", { className: steps_MigratingStep_module['ProgressFill'], style: { width: `${progressPercent}%` } })),
                external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, textType: typography_Text/* TextType */.M2.Shy },
                    progress.current,
                    " / ",
                    progress.total,
                    " components")),
            progress.currentComponent && !awaitingDecision && (external_react_default().createElement("div", { className: steps_MigratingStep_module['CurrentComponent'] },
                external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null),
                external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, progress.currentComponent))),
            progress.log && progress.log.length > 0 && (external_react_default().createElement("div", { className: steps_MigratingStep_module['LogSection'] },
                external_react_default().createElement("div", { className: steps_MigratingStep_module['LogEntries'] }, progress.log.slice(-6).map((entry, index) => (external_react_default().createElement("div", { key: index, className: `${steps_MigratingStep_module['LogEntry']} ${steps_MigratingStep_module[`is-${entry.level}`]}` },
                    external_react_default().createElement(LogIcon, { level: entry.level }),
                    external_react_default().createElement("div", { className: steps_MigratingStep_module['LogContent'] },
                        entry.component && (external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, textType: typography_Text/* TextType */.M2.Proud, isSpan: true },
                            entry.component,
                            ":",
                            ' ')),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, isSpan: true }, entry.message)),
                    entry.cost !== undefined && (external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, textType: typography_Text/* TextType */.M2.Shy },
                        "$",
                        entry.cost.toFixed(2))))))))),
            awaitingDecision && onAiDecision && external_react_default().createElement(AiDecisionPanel, { request: awaitingDecision, onDecision: onAiDecision }),
            budgetApprovalRequest && onBudgetApproval && (external_react_default().createElement("div", { className: steps_MigratingStep_module['DialogOverlay'] },
                external_react_default().createElement(BudgetApprovalDialog, { state: budgetApprovalRequest, onApprove: () => onBudgetApproval(true), onDeny: () => onBudgetApproval(false) }))),
            decisionRequest && onDecision && (external_react_default().createElement("div", { className: steps_MigratingStep_module['DialogOverlay'] },
                external_react_default().createElement(DecisionDialog, { request: decisionRequest, onDecision: onDecision })))),
        external_react_default().createElement("div", { className: steps_MigratingStep_module['Actions'] },
            external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Pause Migration", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onPause, isDisabled: !!awaitingDecision }))));
}
function AiDecisionPanel({ request, onDecision }) {
    return (external_react_default().createElement("div", { className: steps_MigratingStep_module['DecisionPanel'] },
        external_react_default().createElement("div", { className: steps_MigratingStep_module['DecisionHeader'] },
            external_react_default().createElement(ToolIcon, null),
            external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Small },
                request.componentName,
                " - Needs Your Input")),
        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small },
            "Claude attempted ",
            request.attempts,
            " migrations but the component still has issues. Here's what happened:"),
        external_react_default().createElement("div", { className: steps_MigratingStep_module['AttemptHistory'] }, request.attemptHistory.map((attempt, i) => (external_react_default().createElement("div", { key: i, className: steps_MigratingStep_module['AttemptEntry'] },
            external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, textType: typography_Text/* TextType */.M2.Proud, isSpan: true },
                "Attempt ",
                i + 1,
                ":"),
            ' ',
            external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, isSpan: true }, attempt.description))))),
        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, textType: typography_Text/* TextType */.M2.Shy },
            "Cost so far: $",
            request.costSpent.toFixed(2)),
        external_react_default().createElement("div", { className: steps_MigratingStep_module['DecisionOptions'] },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: `Try Again (~$${request.retryCost.toFixed(2)})`, onClick: () => onDecision({ componentId: request.componentId, action: 'retry' }) }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Skip Component", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: () => onDecision({ componentId: request.componentId, action: 'skip' }) }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Get Suggestions (~$0.02)", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: () => onDecision({ componentId: request.componentId, action: 'getHelp' }) })))));
}
// =============================================================================
// Helper Functions & Icons
// =============================================================================
function getPhaseLabel(phase) {
    const labels = {
        copying: 'Copying files',
        automatic: 'Applying automatic fixes',
        'ai-assisted': 'AI-assisted migration',
        finalizing: 'Finalizing'
    };
    return labels[phase || ''] || 'Starting';
}
function LogIcon({ level }) {
    const icons = {
        info: (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 12, height: 12 },
            external_react_default().createElement("path", { d: "M8 16A8 8 0 108 0a8 8 0 000 16zm.93-9.412l-1 4.705c-.07.34.029.533.304.533.194 0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287h.001zm-.043-3.33a.86.86 0 110 1.72.86.86 0 010-1.72z", fill: "currentColor" }))),
        success: (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 12, height: 12 },
            external_react_default().createElement("path", { d: "M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z", fill: "currentColor" }))),
        warning: (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 12, height: 12 },
            external_react_default().createElement("path", { d: "M8.863 1.035c-.39-.678-1.336-.678-1.726 0L.187 12.78c-.403.7.096 1.57.863 1.57h13.9c.767 0 1.266-.87.863-1.57L8.863 1.035zM8 5a.75.75 0 01.75.75v2.5a.75.75 0 11-1.5 0v-2.5A.75.75 0 018 5zm0 7a1 1 0 100-2 1 1 0 000 2z", fill: "currentColor" }))),
        error: (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 12, height: 12 },
            external_react_default().createElement("path", { d: "M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z", fill: "currentColor" })))
    };
    return icons[level] || icons.info;
}
function ToolIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 20, height: 20 },
        external_react_default().createElement("path", { d: "M5.433 2.304A4.492 4.492 0 003.5 6c0 1.598.832 3.002 2.09 3.802.518.328.929.923.902 1.64l-.086 2.27a.75.75 0 01-.75.72h-1.3a.75.75 0 01-.75-.72l-.086-2.27c-.027-.717.384-1.312.902-1.64A4.495 4.495 0 003.5 6a5.99 5.99 0 012.433-4.864.75.75 0 011.134.64v3.046l.5.865.5-.865V1.776a.75.75 0 011.134-.64A5.99 5.99 0 0111.5 6a4.495 4.495 0 01-.922 3.802c-.518.328-.929.923-.902 1.64l.086 2.27a.75.75 0 01-.75.72h-1.3a.75.75 0 01-.75-.72l-.086-2.27c-.027-.717.384-1.312.902-1.64A4.495 4.495 0 007.5 6c0-.54-.185-1.061-.433-1.548", fill: "currentColor" })));
}
/* harmony default export */ const steps_MigratingStep = ((/* unused pure expression or super */ null && (MigratingStep)));

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/migration/steps/ReportStep.module.scss
var ReportStep_module = __webpack_require__(54597);
;// ./src/editor/src/views/migration/steps/ReportStep.module.scss

      
      
      
      
      
      
      
      
      

var ReportStep_module_options = {};

ReportStep_module_options.styleTagTransform = (styleTagTransform_default());
ReportStep_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ReportStep_module_options.insert = insertBySelector_default().bind(null, "head");
    
ReportStep_module_options.domAPI = (styleDomAPI_default());
ReportStep_module_options.insertStyleElement = (insertStyleElement_default());

var ReportStep_module_update = injectStylesIntoStyleTag_default()(ReportStep_module/* default */.A, ReportStep_module_options);




       /* harmony default export */ const steps_ReportStep_module = (ReportStep_module/* default */.A && ReportStep_module/* default */.A.locals ? ReportStep_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/migration/steps/ReportStep.tsx
/**
 * ReportStep
 *
 * Step 3 of the migration wizard: Shows scan results by category.
 *
 * @module noodl-editor/views/migration/steps
 * @since 1.2.0
 */







function ReportStep({ scan, onConfigureAi, onMigrateWithoutAi, onMigrateWithAi, onCancel, aiEnabled = false }) {
    const [expandedCategory, setExpandedCategory] = (0,external_react_.useState)(null);
    const { automatic, simpleFixes, needsReview } = scan.categories;
    const totalIssues = simpleFixes.length + needsReview.length;
    const allAutomatic = totalIssues === 0;
    // Calculate estimated cost (placeholder - AI not yet implemented)
    const estimatedCost = needsReview.length * 0.05 + simpleFixes.length * 0.02;
    return (external_react_default().createElement("div", { className: steps_ReportStep_module['Root'] },
        external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: true },
            external_react_default().createElement(typography_Text/* Text */.EY, null,
                "Analyzed ",
                scan.totalComponents,
                " components and ",
                scan.totalNodes,
                " nodes.",
                scan.customJsFiles > 0 && ` Found ${scan.customJsFiles} custom JavaScript files.`),
            external_react_default().createElement("div", { className: steps_ReportStep_module['SummaryStats'] },
                external_react_default().createElement(ReportStep_StatCard, { icon: external_react_default().createElement(ReportStep_CheckCircleIcon, null), value: automatic.length, label: "Automatic", variant: "success" }),
                external_react_default().createElement(ReportStep_StatCard, { icon: external_react_default().createElement(ZapIcon, null), value: simpleFixes.length, label: "Simple Fixes", variant: "info" }),
                external_react_default().createElement(ReportStep_StatCard, { icon: external_react_default().createElement(ReportStep_ToolIcon, null), value: needsReview.length, label: "Needs Review", variant: "warning" })),
            external_react_default().createElement("div", { className: steps_ReportStep_module['Categories'] },
                external_react_default().createElement(CategorySection, { title: "Automatic", description: "These components will migrate without any changes", icon: external_react_default().createElement(ReportStep_CheckCircleIcon, null), items: automatic, variant: "success", expanded: expandedCategory === 'automatic', onToggle: () => setExpandedCategory(expandedCategory === 'automatic' ? null : 'automatic') }),
                simpleFixes.length > 0 && (external_react_default().createElement(CategorySection, { title: "Simple Fixes", description: "Minor syntax updates needed", icon: external_react_default().createElement(ZapIcon, null), items: simpleFixes, variant: "info", expanded: expandedCategory === 'simpleFixes', onToggle: () => setExpandedCategory(expandedCategory === 'simpleFixes' ? null : 'simpleFixes'), showIssueDetails: true })),
                needsReview.length > 0 && (external_react_default().createElement(CategorySection, { title: "Needs Review", description: "May require manual adjustment after migration", icon: external_react_default().createElement(ReportStep_ToolIcon, null), items: needsReview, variant: "warning", expanded: expandedCategory === 'needsReview', onToggle: () => setExpandedCategory(expandedCategory === 'needsReview' ? null : 'needsReview'), showIssueDetails: true }))),
            !allAutomatic && (external_react_default().createElement("div", { className: steps_ReportStep_module['AiPrompt'] },
                external_react_default().createElement("div", { className: steps_ReportStep_module['AiPromptIcon'] },
                    external_react_default().createElement(ReportStep_RobotIcon, null)),
                external_react_default().createElement("div", { className: steps_ReportStep_module['AiPromptContent'] },
                    external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Small }, "AI-Assisted Migration Available"),
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Secondary, size: typography_Text/* TextSize */.$C.Small },
                        "Claude can help automatically fix the ",
                        totalIssues,
                        " components that need code changes. Estimated cost: ~$",
                        estimatedCost.toFixed(2))),
                !aiEnabled && (external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Configure AI", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onConfigureAi }))))),
        external_react_default().createElement("div", { className: steps_ReportStep_module['Actions'] },
            external_react_default().createElement(Stack/* HStack */.zt, { hasSpacing: true },
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Cancel", variant: inputs_PrimaryButton/* PrimaryButtonVariant */.Mw.Muted, onClick: onCancel }),
                external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: allAutomatic ? 'Migrate Project' : 'Migrate (Auto Only)', onClick: onMigrateWithoutAi }),
                !allAutomatic && aiEnabled && external_react_default().createElement(inputs_PrimaryButton/* PrimaryButton */.jn, { label: "Migrate with AI", onClick: onMigrateWithAi })))));
}
function ReportStep_StatCard({ icon, value, label, variant }) {
    return (external_react_default().createElement("div", { className: `${steps_ReportStep_module['StatCard']} ${steps_ReportStep_module[`is-${variant}`]}` },
        external_react_default().createElement("div", { className: steps_ReportStep_module['StatCardIcon'] }, icon),
        external_react_default().createElement("div", { className: steps_ReportStep_module['StatCardValue'] }, value),
        external_react_default().createElement("div", { className: steps_ReportStep_module['StatCardLabel'] }, label)));
}
function CategorySection({ title, description, icon, items, variant, expanded, onToggle, showIssueDetails = false }) {
    if (items.length === 0)
        return null;
    return (external_react_default().createElement("div", { className: `${steps_ReportStep_module['CategorySection']} ${steps_ReportStep_module[`is-${variant}`]}` },
        external_react_default().createElement("button", { className: steps_ReportStep_module['CategoryHeader'], onClick: onToggle },
            external_react_default().createElement("div", { className: steps_ReportStep_module['CategoryHeaderLeft'] },
                icon,
                external_react_default().createElement("div", null,
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Proud },
                        title,
                        " (",
                        items.length,
                        ")"),
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Secondary, size: typography_Text/* TextSize */.$C.Small }, description))),
            external_react_default().createElement(ChevronIcon, { direction: expanded ? 'up' : 'down' })),
        external_react_default().createElement(Collapsible/* Collapsible */.N, { isCollapsed: !expanded },
            external_react_default().createElement("div", { className: steps_ReportStep_module['CategoryItems'] }, items.map((item) => (external_react_default().createElement("div", { key: item.id, className: steps_ReportStep_module['CategoryItem'] },
                external_react_default().createElement(ReportStep_ComponentIcon, null),
                external_react_default().createElement("div", { className: steps_ReportStep_module['CategoryItemInfo'] },
                    external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, item.name),
                    showIssueDetails && item.issues.length > 0 && (external_react_default().createElement("ul", { className: steps_ReportStep_module['IssuesList'] }, item.issues.map((issue) => (external_react_default().createElement("li", { key: issue.id },
                        external_react_default().createElement("code", null, issue.type),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, isSpan: true, textType: typography_Text/* TextType */.M2.Secondary },
                            ' ',
                            issue.description))))))),
                item.estimatedCost !== undefined && (external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, textType: typography_Text/* TextType */.M2.Shy },
                    "~$",
                    item.estimatedCost.toFixed(2))))))))));
}
// =============================================================================
// Icons
// =============================================================================
function ReportStep_CheckCircleIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 16, height: 16 },
        external_react_default().createElement("path", { d: "M8 16A8 8 0 108 0a8 8 0 000 16zm3.78-9.72a.75.75 0 00-1.06-1.06L6.75 9.19 5.28 7.72a.75.75 0 00-1.06 1.06l2 2a.75.75 0 001.06 0l4.5-4.5z", fill: "currentColor" })));
}
function ZapIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 16, height: 16 },
        external_react_default().createElement("path", { d: "M9.504.43a.75.75 0 01.397.696L9.223 5h4.027a.75.75 0 01.577 1.22l-5.25 6.25a.75.75 0 01-1.327-.55l.678-4.42H3.902a.75.75 0 01-.577-1.22l5.25-6.25a.75.75 0 01.93-.18z", fill: "currentColor" })));
}
function ReportStep_ToolIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 16, height: 16 },
        external_react_default().createElement("path", { d: "M5.433 2.304A4.492 4.492 0 003.5 6c0 1.598.832 3.002 2.09 3.802.518.328.929.923.902 1.64l-.086 2.27a.75.75 0 01-.75.72h-1.3a.75.75 0 01-.75-.72l-.086-2.27c-.027-.717.384-1.312.902-1.64A4.495 4.495 0 003.5 6a5.99 5.99 0 012.433-4.864.75.75 0 011.134.64v3.046l.5.865.5-.865V1.776a.75.75 0 011.134-.64A5.99 5.99 0 0111.5 6a4.495 4.495 0 01-.922 3.802c-.518.328-.929.923-.902 1.64l.086 2.27a.75.75 0 01-.75.72h-1.3a.75.75 0 01-.75-.72l-.086-2.27c-.027-.717.384-1.312.902-1.64A4.495 4.495 0 007.5 6c0-.54-.185-1.061-.433-1.548", fill: "currentColor" })));
}
function ReportStep_RobotIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 24, height: 24 },
        external_react_default().createElement("path", { d: "M8 0a1 1 0 011 1v1.5h2A2.5 2.5 0 0113.5 5v6a2.5 2.5 0 01-2.5 2.5h-6A2.5 2.5 0 012.5 11V5A2.5 2.5 0 015 2.5h2V1a1 1 0 011-1zM5 4a1 1 0 00-1 1v6a1 1 0 001 1h6a1 1 0 001-1V5a1 1 0 00-1-1H5zm1.5 2a1 1 0 110 2 1 1 0 010-2zm3 0a1 1 0 110 2 1 1 0 010-2zM6 8.5a.5.5 0 000 1h4a.5.5 0 000-1H6z", fill: "currentColor" })));
}
function ReportStep_ComponentIcon() {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
        external_react_default().createElement("path", { d: "M8.186 1.113a.5.5 0 00-.372 0L1.814 3.5l-.372.149v8.702l.372.149 6 2.387a.5.5 0 00.372 0l6-2.387.372-.149V3.649l-.372-.149-6-2.387zM8 2.123l4.586 1.828L8 5.778 3.414 3.95 8 2.123zm-5.5 2.89l5 1.992v6.372l-5-1.992V5.013zm6.5 8.364V7.005l5-1.992v6.372l-5 1.992z", fill: "currentColor" })));
}
function ChevronIcon({ direction }) {
    return (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 16, height: 16, style: { transform: direction === 'up' ? 'rotate(180deg)' : undefined } },
        external_react_default().createElement("path", { d: "M12.78 6.22a.75.75 0 010 1.06l-4.25 4.25a.75.75 0 01-1.06 0L3.22 7.28a.75.75 0 011.06-1.06L8 9.94l3.72-3.72a.75.75 0 011.06 0z", fill: "currentColor" })));
}
/* harmony default export */ const steps_ReportStep = ((/* unused pure expression or super */ null && (ReportStep)));

// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/migration/steps/ScanningStep.module.scss
var ScanningStep_module = __webpack_require__(74986);
;// ./src/editor/src/views/migration/steps/ScanningStep.module.scss

      
      
      
      
      
      
      
      
      

var ScanningStep_module_options = {};

ScanningStep_module_options.styleTagTransform = (styleTagTransform_default());
ScanningStep_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      ScanningStep_module_options.insert = insertBySelector_default().bind(null, "head");
    
ScanningStep_module_options.domAPI = (styleDomAPI_default());
ScanningStep_module_options.insertStyleElement = (insertStyleElement_default());

var ScanningStep_module_update = injectStylesIntoStyleTag_default()(ScanningStep_module/* default */.A, ScanningStep_module_options);




       /* harmony default export */ const steps_ScanningStep_module = (ScanningStep_module/* default */.A && ScanningStep_module/* default */.A.locals ? ScanningStep_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/migration/steps/ScanningStep.tsx
/**
 * ScanningStep
 *
 * Step 2 of the migration wizard: Shows progress while copying and scanning.
 * Also used during the migration phase (step 4).
 *
 * @module noodl-editor/views/migration/steps
 * @since 1.2.0
 */







function ScanningStep({ sourcePath: _sourcePath, targetPath: _targetPath, isMigrating = false, progress }) {
    // sourcePath and targetPath are available for future use (e.g., displaying paths)
    void _sourcePath;
    void _targetPath;
    const title = isMigrating ? 'Migrating Project...' : 'Analyzing Project...';
    const subtitle = isMigrating
        ? `Phase: ${ScanningStep_getPhaseLabel(progress === null || progress === void 0 ? void 0 : progress.phase)}`
        : 'Creating a safe copy before making any changes';
    const progressPercent = progress
        ? Math.round((progress.current / progress.total) * 100)
        : 0;
    return (external_react_default().createElement("div", { className: steps_ScanningStep_module['Root'] },
        external_react_default().createElement(Stack/* VStack */.Tk, { hasSpacing: true },
            external_react_default().createElement("div", { className: steps_ScanningStep_module['Header'] },
                external_react_default().createElement(ActivityIndicator/* ActivityIndicator */.$$, null),
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Medium }, title)),
            external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Secondary }, subtitle),
            external_react_default().createElement("div", { className: steps_ScanningStep_module['ProgressSection'] },
                external_react_default().createElement("div", { className: steps_ScanningStep_module['ProgressBar'] },
                    external_react_default().createElement("div", { className: steps_ScanningStep_module['ProgressFill'], style: { width: `${progressPercent}%` } })),
                progress && (external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, textType: typography_Text/* TextType */.M2.Shy },
                    progress.current,
                    " / ",
                    progress.total,
                    " components"))),
            (progress === null || progress === void 0 ? void 0 : progress.currentComponent) && (external_react_default().createElement("div", { className: steps_ScanningStep_module['CurrentItem'] },
                external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14 },
                    external_react_default().createElement("path", { d: "M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z", fill: "currentColor" })),
                external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small }, progress.currentComponent))),
            (progress === null || progress === void 0 ? void 0 : progress.log) && progress.log.length > 0 && (external_react_default().createElement("div", { className: steps_ScanningStep_module['LogSection'] },
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Small }, "Activity Log"),
                external_react_default().createElement("div", { className: steps_ScanningStep_module['LogEntries'] }, progress.log.slice(-5).map((entry, index) => (external_react_default().createElement("div", { key: index, className: `${steps_ScanningStep_module['LogEntry']} ${steps_ScanningStep_module[`is-${entry.level}`]}` },
                    external_react_default().createElement(ScanningStep_LogIcon, { level: entry.level }),
                    external_react_default().createElement("div", { className: steps_ScanningStep_module['LogContent'] },
                        entry.component && (external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, textType: typography_Text/* TextType */.M2.Proud, isSpan: true },
                            entry.component,
                            ":",
                            ' ')),
                        external_react_default().createElement(typography_Text/* Text */.EY, { size: typography_Text/* TextSize */.$C.Small, isSpan: true }, entry.message)))))))),
            external_react_default().createElement(Box/* Box */.a, { hasTopSpacing: true },
                external_react_default().createElement("div", { className: steps_ScanningStep_module['InfoBox'] },
                    external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Shy, size: typography_Text/* TextSize */.$C.Small }, isMigrating
                        ? 'Please wait while we migrate your project. This may take a few minutes for larger projects.'
                        : 'Scanning components for React 17 patterns that need updating...'))))));
}
// Helper Components
function ScanningStep_LogIcon({ level }) {
    const icons = {
        info: (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 12, height: 12 },
            external_react_default().createElement("path", { d: "M8 16A8 8 0 108 0a8 8 0 000 16zm.93-9.412l-1 4.705c-.07.34.029.533.304.533.194 0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287h.001zm-.043-3.33a.86.86 0 110 1.72.86.86 0 010-1.72z", fill: "currentColor" }))),
        success: (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 12, height: 12 },
            external_react_default().createElement("path", { d: "M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z", fill: "currentColor" }))),
        warning: (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 12, height: 12 },
            external_react_default().createElement("path", { d: "M8.863 1.035c-.39-.678-1.336-.678-1.726 0L.187 12.78c-.403.7.096 1.57.863 1.57h13.9c.767 0 1.266-.87.863-1.57L8.863 1.035zM8 5a.75.75 0 01.75.75v2.5a.75.75 0 11-1.5 0v-2.5A.75.75 0 018 5zm0 7a1 1 0 100-2 1 1 0 000 2z", fill: "currentColor" }))),
        error: (external_react_default().createElement("svg", { viewBox: "0 0 16 16", width: 12, height: 12 },
            external_react_default().createElement("path", { d: "M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z", fill: "currentColor" })))
    };
    return icons[level] || icons.info;
}
function ScanningStep_getPhaseLabel(phase) {
    const labels = {
        copying: 'Copying files',
        automatic: 'Applying automatic fixes',
        'ai-assisted': 'AI-assisted migration',
        finalizing: 'Finalizing'
    };
    return labels[phase || ''] || 'Starting';
}
/* harmony default export */ const steps_ScanningStep = ((/* unused pure expression or super */ null && (ScanningStep)));

;// ./src/editor/src/views/migration/MigrationWizard.tsx
/**
 * MigrationWizard
 *
 * Main container component for the React 19 migration wizard.
 * Manages step navigation and integrates with MigrationSessionManager.
 *
 * @module noodl-editor/views/migration
 * @since 1.2.0
 */
















// =============================================================================
// Reducer
// =============================================================================
function wizardReducer(state, action) {
    var _a;
    switch (action.type) {
        case 'SET_SESSION':
            return {
                ...state,
                session: action.session
            };
        case 'SET_TARGET_PATH':
            if (!state.session)
                return state;
            return {
                ...state,
                session: {
                    ...state.session,
                    target: { ...state.session.target, path: action.path }
                }
            };
        case 'START_SCAN':
            if (!state.session)
                return state;
            return {
                ...state,
                session: { ...state.session, step: 'scanning' },
                loading: true
            };
        case 'SCAN_COMPLETE':
            if (!state.session)
                return state;
            return {
                ...state,
                session: {
                    ...state.session,
                    step: 'report',
                    scan: action.scan
                },
                loading: false
            };
        case 'CONFIGURE_AI':
            if (!state.session)
                return state;
            return {
                ...state,
                session: { ...state.session, step: 'configureAi' }
            };
        case 'AI_CONFIGURED':
            if (!state.session)
                return state;
            return {
                ...state,
                session: { ...state.session, step: 'report' }
            };
        case 'BACK_TO_REPORT':
            if (!state.session)
                return state;
            return {
                ...state,
                session: { ...state.session, step: 'report' }
            };
        case 'AI_DECISION':
            // Handle AI decision - just continue migration
            return state;
        case 'ERROR':
            if (!state.session)
                return state;
            return {
                ...state,
                session: { ...state.session, step: 'failed' },
                loading: false,
                error: action.error
            };
        case 'START_MIGRATE':
            if (!state.session)
                return state;
            return {
                ...state,
                session: {
                    ...state.session,
                    step: 'migrating',
                    ai: action.useAi ? state.session.ai : undefined
                },
                loading: true
            };
        case 'MIGRATION_PROGRESS':
            if (!((_a = state.session) === null || _a === void 0 ? void 0 : _a.progress))
                return state;
            return {
                ...state,
                session: {
                    ...state.session,
                    progress: {
                        ...state.session.progress,
                        current: action.progress,
                        currentComponent: action.currentComponent
                    }
                }
            };
        case 'COMPLETE':
            if (!state.session)
                return state;
            return {
                ...state,
                session: {
                    ...state.session,
                    step: 'complete',
                    result: action.result
                },
                loading: false
            };
        case 'RETRY':
            if (!state.session)
                return state;
            return {
                ...state,
                session: {
                    ...state.session,
                    step: 'confirm',
                    scan: undefined,
                    progress: undefined,
                    result: undefined
                },
                loading: false,
                error: null
            };
        default:
            return state;
    }
}
// =============================================================================
// Component
// =============================================================================
function MigrationWizard({ sourcePath, projectName, onComplete, onCancel }) {
    // Initialize session on mount
    const [state, dispatch] = (0,external_react_.useReducer)(wizardReducer, {
        session: null,
        loading: false,
        error: null
    });
    const [isInitialized, setIsInitialized] = (0,external_react_.useState)(false);
    const [budgetApprovalRequest, setBudgetApprovalRequest] = (0,external_react_.useState)(null);
    const [decisionRequest, setDecisionRequest] = (0,external_react_.useState)(null);
    const [budgetApprovalResolve, setBudgetApprovalResolve] = (0,external_react_.useState)(null);
    const [decisionResolve, setDecisionResolve] = (0,external_react_.useState)(null);
    // Create session on mount
    (0,external_react_.useEffect)(() => {
        async function initSession() {
            try {
                // Create session in manager (stores it internally)
                await migrationSessionManager.createSession(sourcePath, projectName);
                // Set default target path
                const defaultTargetPath = `${sourcePath}-react19`;
                migrationSessionManager.setTargetPath(defaultTargetPath);
                // Update session with new target path
                const updatedSession = migrationSessionManager.getSession();
                if (updatedSession) {
                    // Initialize reducer state with the session
                    dispatch({ type: 'SET_SESSION', session: updatedSession });
                }
                setIsInitialized(true);
            }
            catch (error) {
                console.error('Failed to create migration session:', error);
                dispatch({ type: 'ERROR', error: error });
            }
        }
        initSession();
        // Cleanup on unmount
        return () => {
            migrationSessionManager.cancelSession();
        };
    }, [sourcePath, projectName]);
    // Sync local state with session manager
    (0,external_react_.useEffect)(() => {
        if (!isInitialized)
            return;
        const currentSession = migrationSessionManager.getSession();
        if (currentSession) {
            // Initialize local state from session manager
            dispatch({ type: 'SET_TARGET_PATH', path: currentSession.target.path });
        }
    }, [isInitialized]);
    // ==========================================================================
    // Handlers
    // ==========================================================================
    const handleUpdateTargetPath = (0,external_react_.useCallback)((path) => {
        migrationSessionManager.setTargetPath(path);
        dispatch({ type: 'SET_TARGET_PATH', path });
    }, []);
    const handleStartScan = (0,external_react_.useCallback)(async () => {
        dispatch({ type: 'START_SCAN' });
        try {
            const scan = await migrationSessionManager.startScanning();
            dispatch({ type: 'SCAN_COMPLETE', scan });
        }
        catch (error) {
            dispatch({ type: 'ERROR', error: error });
        }
    }, []);
    const handleStartMigration = (0,external_react_.useCallback)(async (useAi) => {
        dispatch({ type: 'START_MIGRATE', useAi });
        try {
            const result = await migrationSessionManager.startMigration();
            dispatch({ type: 'COMPLETE', result });
        }
        catch (error) {
            dispatch({ type: 'ERROR', error: error });
        }
    }, []);
    const handleRetry = (0,external_react_.useCallback)(async () => {
        try {
            await migrationSessionManager.resetForRetry();
            dispatch({ type: 'RETRY' });
        }
        catch (error) {
            console.error('Failed to reset session:', error);
        }
    }, []);
    const handleOpenProject = (0,external_react_.useCallback)(() => {
        const currentSession = migrationSessionManager.getSession();
        if (currentSession === null || currentSession === void 0 ? void 0 : currentSession.target.path) {
            onComplete(currentSession.target.path);
        }
    }, [onComplete]);
    const handleConfigureAi = (0,external_react_.useCallback)(async () => {
        try {
            await migrationSessionManager.transitionTo('configureAi');
            dispatch({ type: 'CONFIGURE_AI' });
        }
        catch (error) {
            console.error('Failed to transition to AI config:', error);
            dispatch({ type: 'ERROR', error: error });
        }
    }, []);
    const handleAiConfigured = (0,external_react_.useCallback)(async (config) => {
        try {
            // Transform AIConfig to match MigrationSessionManager expectations
            const aiConfig = {
                ...config,
                budget: {
                    ...config.budget,
                    spent: 0 // Initialize spent to 0 for new config
                }
            };
            migrationSessionManager.configureAI(aiConfig);
            await migrationSessionManager.transitionTo('report');
            dispatch({ type: 'AI_CONFIGURED' });
        }
        catch (error) {
            console.error('Failed to configure AI:', error);
            dispatch({ type: 'ERROR', error: error });
        }
    }, []);
    const handleBackToReport = (0,external_react_.useCallback)(async () => {
        try {
            await migrationSessionManager.transitionTo('report');
            dispatch({ type: 'BACK_TO_REPORT' });
        }
        catch (error) {
            console.error('Failed to go back to report:', error);
            dispatch({ type: 'ERROR', error: error });
        }
    }, []);
    const handleAiDecision = (0,external_react_.useCallback)((decision) => {
        // For now, just continue - full AI orchestration will be wired in Phase 3
        console.log('AI decision:', decision);
        dispatch({ type: 'AI_DECISION', decision });
    }, []);
    const handlePauseMigration = (0,external_react_.useCallback)(() => {
        // Pause migration - will be implemented when orchestrator is wired up
        console.log('Pause migration requested');
    }, []);
    const handleBudgetApproval = (0,external_react_.useCallback)((approved) => {
        if (budgetApprovalResolve) {
            budgetApprovalResolve(approved);
            setBudgetApprovalResolve(null);
        }
        setBudgetApprovalRequest(null);
    }, [budgetApprovalResolve]);
    const handleDecision = (0,external_react_.useCallback)((action) => {
        if (decisionResolve) {
            decisionResolve(action);
            setDecisionResolve(null);
        }
        setDecisionRequest(null);
    }, [decisionResolve]);
    // Callback for orchestrator to request budget approval
    const requestBudgetApproval = (0,external_react_.useCallback)((state) => {
        return new Promise((resolve) => {
            setBudgetApprovalRequest(state);
            setBudgetApprovalResolve(() => resolve);
        });
    }, []);
    // Callback for orchestrator to request decision
    const requestDecision = (0,external_react_.useCallback)((request) => {
        return new Promise((resolve) => {
            setDecisionRequest(request);
            setDecisionResolve(() => resolve);
        });
    }, []);
    // ==========================================================================
    // Render
    // ==========================================================================
    // Get current session from manager (source of truth)
    const session = migrationSessionManager.getSession();
    if (!session) {
        return null; // Session not initialized yet
    }
    const currentStep = session.step;
    const stepIndex = getStepNumber(currentStep);
    const totalSteps = getTotalSteps(false); // No AI for now
    const renderStep = () => {
        var _a, _b;
        switch (currentStep) {
            case 'confirm':
                return (external_react_default().createElement(ConfirmStep, { sourcePath: sourcePath, projectName: projectName, targetPath: session.target.path, onUpdateTargetPath: handleUpdateTargetPath, onNext: handleStartScan, onCancel: onCancel, loading: state.loading }));
            case 'scanning':
                return external_react_default().createElement(ScanningStep, { sourcePath: sourcePath, targetPath: session.target.path });
            case 'configureAi':
                return (external_react_default().createElement(AIConfigPanel, { existingConfig: session.ai
                        ? {
                            apiKey: session.ai.apiKey || '',
                            enabled: session.ai.enabled,
                            budget: session.ai.budget,
                            preferences: session.ai.preferences
                        }
                        : undefined, onSave: handleAiConfigured, onCancel: handleBackToReport }));
            case 'report':
                return (external_react_default().createElement(ReportStep, { scan: session.scan, onConfigureAi: handleConfigureAi, onMigrateWithoutAi: () => handleStartMigration(false), onMigrateWithAi: () => handleStartMigration(true), onCancel: onCancel, aiEnabled: ((_a = session.ai) === null || _a === void 0 ? void 0 : _a.enabled) || false }));
            case 'migrating':
                return (external_react_default().createElement(MigratingStep, { progress: session.progress || { phase: 'copying', current: 0, total: 0, log: [] }, useAi: !!session.ai, budget: (_b = session.ai) === null || _b === void 0 ? void 0 : _b.budget, onAiDecision: handleAiDecision, onPause: handlePauseMigration, budgetApprovalRequest: budgetApprovalRequest, onBudgetApproval: handleBudgetApproval, decisionRequest: decisionRequest, onDecision: handleDecision }));
            case 'complete':
                return (external_react_default().createElement(CompleteStep, { result: session.result, sourcePath: sourcePath, targetPath: session.target.path, onOpenProject: handleOpenProject }));
            case 'failed':
                return external_react_default().createElement(FailedStep, { error: state.error, onRetry: handleRetry, onCancel: onCancel });
            default:
                return null;
        }
    };
    return (external_react_default().createElement(BaseDialog/* CoreBaseDialog */.V9, { isVisible: true, hasBackdrop: true, onClose: onCancel },
        external_react_default().createElement("div", { className: migration_MigrationWizard_module['WizardContainer'] },
            external_react_default().createElement("div", { className: migration_MigrationWizard_module['CloseButton'] },
                external_react_default().createElement(inputs_IconButton/* IconButton */.K0, { icon: common_Icon/* IconName */.$M.Close, onClick: onCancel, variant: inputs_IconButton/* IconButtonVariant */.nl.Transparent })),
            external_react_default().createElement("div", { className: migration_MigrationWizard_module['WizardHeader'] },
                external_react_default().createElement(Title/* Title */.hE, { size: Title/* TitleSize */.uM.Large, variant: Title/* TitleVariant */.Is.Highlighted }, "Migrate Project to React 19"),
                external_react_default().createElement(typography_Text/* Text */.EY, { textType: typography_Text/* TextType */.M2.Secondary }, getStepLabel(currentStep))),
            external_react_default().createElement("div", { className: migration_MigrationWizard_module['WizardContent'] },
                external_react_default().createElement(WizardProgress, { currentStep: stepIndex, totalSteps: totalSteps, stepLabels: ['Confirm', 'Scan', 'Report', 'Migrate', 'Complete'] }),
                external_react_default().createElement("div", { className: migration_MigrationWizard_module['StepContainer'] }, renderStep())))));
}
/* harmony default export */ const migration_MigrationWizard = ((/* unused pure expression or super */ null && (MigrationWizard)));

;// ./src/editor/src/pages/ProjectsPage/ProjectsPage.tsx
/**
 * ProjectsPage - Entry point for the launcher dashboard
 *
 * This page displays the new React-based Launcher component
 * with horizontal tab navigation.
 */

















/**
 * Map LocalProjectsModel ProjectItemWithRuntime to LauncherProjectData format
 */
function mapProjectToLauncherData(project) {
    return {
        id: project.id,
        title: project.name || 'Untitled',
        localPath: project.retainedProjectDirectory,
        lastOpened: new Date(project.latestAccessed).toISOString(),
        imageSrc: project.thumbURI || 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg"%3E%3C/svg%3E',
        cloudSyncMeta: {
            type: CloudSyncType.None // TODO: Detect git repos in future
        },
        // Include runtime info for legacy detection
        runtimeInfo: project.runtimeInfo
        // Git-related fields will be populated in future tasks
    };
}
function ProjectsPage(props) {
    // Real projects from LocalProjectsModel
    const [realProjects, setRealProjects] = (0,external_react_.useState)([]);
    // Create project modal state
    const [isCreateModalVisible, setIsCreateModalVisible] = (0,external_react_.useState)(false);
    // GitHub OAuth state
    const [githubIsAuthenticated, setGithubIsAuthenticated] = (0,external_react_.useState)(false);
    const [githubIsConnecting, setGithubIsConnecting] = (0,external_react_.useState)(false);
    const [githubUser, setGithubUser] = (0,external_react_.useState)(null);
    const oauthService = GitHubOAuthService/* GitHubOAuthService */.W.instance;
    // Initialize GitHub OAuth state on mount
    (0,external_react_.useEffect)(() => {
        console.log('🔧 [ProjectsPage] Initializing GitHub OAuth...');
        oauthService.initialize().then(() => {
            const isAuth = oauthService.isAuthenticated();
            const user = oauthService.getCurrentUser();
            console.log('🔧 [ProjectsPage] GitHub auth state:', isAuth, user === null || user === void 0 ? void 0 : user.login);
            setGithubIsAuthenticated(isAuth);
            setGithubUser(user);
        });
    }, [oauthService]);
    // Listen for GitHub auth state changes
    (0,useEventListener/* useEventListener */.M)(oauthService, 'auth-state-changed', (event) => {
        console.log('🔔 [ProjectsPage] GitHub auth state changed:', event.authenticated);
        setGithubIsAuthenticated(event.authenticated);
        if (event.authenticated) {
            setGithubUser(oauthService.getCurrentUser());
        }
        else {
            setGithubUser(null);
        }
    });
    // Listen for OAuth success
    (0,useEventListener/* useEventListener */.M)(oauthService, 'oauth-success', () => {
        setGithubIsConnecting(false);
    });
    (0,useEventListener/* useEventListener */.M)(oauthService, 'oauth-error', () => {
        setGithubIsConnecting(false);
        ToastLayer.ToastLayer.showError('GitHub authentication failed');
    });
    // GitHub OAuth handlers
    const handleGitHubConnect = (0,external_react_.useCallback)(async () => {
        console.log('🔘 [ProjectsPage] handleGitHubConnect called');
        setGithubIsConnecting(true);
        try {
            await oauthService.initiateOAuth();
            console.log('✅ [ProjectsPage] OAuth initiated');
        }
        catch (error) {
            console.error('❌ [ProjectsPage] OAuth error:', error);
            setGithubIsConnecting(false);
            ToastLayer.ToastLayer.showError('Failed to connect GitHub');
        }
    }, [oauthService]);
    const handleGitHubDisconnect = (0,external_react_.useCallback)(async () => {
        console.log('🔘 [ProjectsPage] handleGitHubDisconnect called');
        await oauthService.disconnect();
        ToastLayer.ToastLayer.showSuccess('GitHub account disconnected');
    }, [oauthService]);
    // Create GitHubClient adapter for useGitHubRepos hook
    const githubClient = (0,external_react_.useMemo)(() => {
        if (!githubIsAuthenticated)
            return null;
        const client = GitHubClient.instance;
        return {
            listRepositories: async (options) => {
                const result = await client.listRepositories(options);
                return result;
            },
            listOrganizations: async () => {
                const result = await client.listOrganizations();
                return result;
            },
            listOrganizationRepositories: async (org, options) => {
                const result = await client.listOrganizationRepositories(org, options);
                return result;
            },
            isNoodlProject: async (owner, repo) => {
                return client.isNoodlProject(owner, repo);
            }
        };
    }, [githubIsAuthenticated]);
    // Use the GitHub repos hook
    const githubRepos = useGitHubRepos(githubClient, githubIsAuthenticated);
    /**
     * Handle cloning a GitHub repository
     * Follows the same legacy detection flow as handleOpenProject
     */
    const handleCloneRepo = (0,external_react_.useCallback)(async (repo) => {
        console.log('🔵 [handleCloneRepo] Starting clone for:', repo.full_name);
        // Ask user where to clone
        try {
            const targetDir = await src.filesystem.openDialog({
                allowCreateDirectory: true
            });
            if (!targetDir) {
                console.log('🔵 [handleCloneRepo] User cancelled');
                return;
            }
            // Create path with repo name
            const clonePath = src.filesystem.join(targetDir, repo.name);
            // Check if directory already exists
            if (await src.filesystem.exists(clonePath)) {
                ToastLayer.ToastLayer.showError(`A folder named "${repo.name}" already exists at that location`);
                return;
            }
            const activityId = 'cloning-repo';
            ToastLayer.ToastLayer.showActivity(`Cloning ${repo.name}...`, activityId);
            // Get clone URL (prefer HTTPS with token for authenticated access)
            const token = await oauthService.getToken();
            const cloneUrl = repo.html_url.replace('https://', `https://x-access-token:${token}@`) + '.git';
            await (0,clone/* clone */.o)(cloneUrl, clonePath, {
                singleBranch: false,
                defaultBranch: repo.default_branch
            });
            ToastLayer.ToastLayer.hideActivity(activityId);
            ToastLayer.ToastLayer.showSuccess(`Cloned "${repo.name}" successfully!`);
            tracker.tracker.track('GitHub Repository Cloned', {
                repoName: repo.name,
                isPrivate: repo.private
            });
            // Now detect runtime and follow the same flow as handleOpenProject
            const runtimeActivityId = 'checking-compatibility';
            ToastLayer.ToastLayer.showActivity('Checking project compatibility...', runtimeActivityId);
            try {
                const runtimeInfo = await (0,ProjectScanner/* detectRuntimeVersion */.Cb)(clonePath);
                ToastLayer.ToastLayer.hideActivity(runtimeActivityId);
                console.log('🔵 [handleCloneRepo] Runtime detected:', runtimeInfo);
                // If legacy or unknown, show warning dialog
                if (runtimeInfo.version === 'react17' || runtimeInfo.version === 'unknown') {
                    const projectName = repo.name;
                    // Show legacy project warning dialog
                    const userChoice = await new Promise((resolve) => {
                        const confirmed = confirm(`⚠️  Legacy Project Detected\n\n` +
                            `This project "${projectName}" was created with an earlier version of Noodl (React 17).\n\n` +
                            `OpenNoodl uses React 19, which requires migrating your project to ensure compatibility.\n\n` +
                            `What would you like to do?\n\n` +
                            `OK - Migrate Project (Recommended)\n` +
                            `Cancel - View options`);
                        if (confirmed) {
                            resolve('migrate');
                        }
                        else {
                            // Show second dialog for Read-Only or Cancel
                            const openReadOnly = confirm(`Would you like to open this project in Read-Only mode?\n\n` +
                                `You can inspect the project safely without making changes.\n\n` +
                                `OK - Open Read-Only\n` +
                                `Cancel - Return to launcher`);
                            if (openReadOnly) {
                                resolve('readonly');
                            }
                            else {
                                resolve('cancel');
                            }
                        }
                    });
                    console.log('🔵 [handleCloneRepo] User choice:', userChoice);
                    if (userChoice === 'cancel') {
                        // Add to projects list but don't open
                        await LocalProjectsModel/* LocalProjectsModel */.h.instance.openProjectFromFolder(clonePath);
                        await LocalProjectsModel/* LocalProjectsModel */.h.instance.fetch();
                        LocalProjectsModel/* LocalProjectsModel */.h.instance.detectAllProjectRuntimes();
                        ToastLayer.ToastLayer.showSuccess(`Project "${repo.name}" added to your projects.`);
                        return;
                    }
                    if (userChoice === 'migrate') {
                        // Launch migration wizard
                        tracker.tracker.track('Legacy Project Migration Started from Clone', { projectName });
                        DialogLayerModel.instance.showDialog((close) => external_react_default().createElement(MigrationWizard, {
                            sourcePath: clonePath,
                            projectName,
                            onComplete: async (targetPath) => {
                                close();
                                const migrateActivityId = 'opening-migrated';
                                ToastLayer.ToastLayer.showActivity('Opening migrated project', migrateActivityId);
                                try {
                                    const migratedProject = await LocalProjectsModel/* LocalProjectsModel */.h.instance.openProjectFromFolder(targetPath);
                                    if (!migratedProject.name) {
                                        migratedProject.name = projectName + ' (React 19)';
                                    }
                                    await LocalProjectsModel/* LocalProjectsModel */.h.instance.fetch();
                                    await LocalProjectsModel/* LocalProjectsModel */.h.instance.detectProjectRuntime(targetPath);
                                    LocalProjectsModel/* LocalProjectsModel */.h.instance.detectAllProjectRuntimes();
                                    const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
                                    const projectEntry = projects.find((p) => p.id === migratedProject.id);
                                    if (projectEntry) {
                                        const loaded = await LocalProjectsModel/* LocalProjectsModel */.h.instance.loadProject(projectEntry);
                                        ToastLayer.ToastLayer.hideActivity(migrateActivityId);
                                        if (loaded) {
                                            ToastLayer.ToastLayer.showSuccess('Project migrated and opened successfully!');
                                            props.route.router.route({ to: 'editor', project: loaded });
                                        }
                                    }
                                }
                                catch (error) {
                                    ToastLayer.ToastLayer.hideActivity(migrateActivityId);
                                    ToastLayer.ToastLayer.showError('Could not open migrated project');
                                    console.error(error);
                                }
                            },
                            onCancel: () => {
                                close();
                            }
                        }), {
                            onClose: () => {
                                LocalProjectsModel/* LocalProjectsModel */.h.instance.fetch();
                            }
                        });
                        return;
                    }
                    // Read-only mode
                    tracker.tracker.track('Legacy Project Opened Read-Only from Clone', { projectName });
                    const readOnlyActivityId = 'opening-project-readonly';
                    ToastLayer.ToastLayer.showActivity('Opening project in read-only mode', readOnlyActivityId);
                    const readOnlyProject = await LocalProjectsModel/* LocalProjectsModel */.h.instance.openProjectFromFolder(clonePath);
                    if (!readOnlyProject) {
                        ToastLayer.ToastLayer.hideActivity(readOnlyActivityId);
                        ToastLayer.ToastLayer.showError('Could not open project');
                        return;
                    }
                    if (!readOnlyProject.name) {
                        readOnlyProject.name = repo.name;
                    }
                    const readOnlyProjects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
                    const readOnlyProjectEntry = readOnlyProjects.find((p) => p.id === readOnlyProject.id);
                    if (!readOnlyProjectEntry) {
                        ToastLayer.ToastLayer.hideActivity(readOnlyActivityId);
                        ToastLayer.ToastLayer.showError('Could not find project in recent list');
                        return;
                    }
                    const loadedReadOnly = await LocalProjectsModel/* LocalProjectsModel */.h.instance.loadProject(readOnlyProjectEntry);
                    ToastLayer.ToastLayer.hideActivity(readOnlyActivityId);
                    if (!loadedReadOnly) {
                        ToastLayer.ToastLayer.showError('Could not load project');
                        return;
                    }
                    ToastLayer.ToastLayer.showError('⚠️  READ-ONLY MODE - No changes will be saved to this legacy project');
                    props.route.router.route({ to: 'editor', project: loadedReadOnly, readOnly: true });
                    return;
                }
            }
            catch (error) {
                ToastLayer.ToastLayer.hideActivity(runtimeActivityId);
                console.error('Failed to detect runtime:', error);
                // Continue with normal flow if detection fails
            }
            // Modern project - add to list and ask to open
            const project = await LocalProjectsModel/* LocalProjectsModel */.h.instance.openProjectFromFolder(clonePath);
            if (project) {
                if (!project.name) {
                    project.name = repo.name;
                }
                await LocalProjectsModel/* LocalProjectsModel */.h.instance.fetch();
                LocalProjectsModel/* LocalProjectsModel */.h.instance.detectAllProjectRuntimes();
                const shouldOpen = confirm(`Project "${repo.name}" cloned successfully!\n\nWould you like to open it now?`);
                if (shouldOpen) {
                    const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
                    const projectEntry = projects.find((p) => p.id === project.id);
                    if (projectEntry) {
                        const loaded = await LocalProjectsModel/* LocalProjectsModel */.h.instance.loadProject(projectEntry);
                        if (loaded) {
                            props.route.router.route({ to: 'editor', project: loaded });
                        }
                    }
                }
            }
        }
        catch (error) {
            ToastLayer.ToastLayer.hideActivity('cloning-repo');
            console.error('Failed to clone repository:', error);
            ToastLayer.ToastLayer.showError(`Failed to clone repository: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
    }, [oauthService, props.route]);
    // Initialize and fetch projects on mount
    (0,external_react_.useEffect)(() => {
        // Switch main window size to editor size
        external_electron_.ipcRenderer.send('main-window-resize', { size: 'editor', center: true });
        // Load projects with runtime detection
        const loadProjects = async () => {
            await LocalProjectsModel/* LocalProjectsModel */.h.instance.fetch();
            // Trigger background runtime detection for all projects
            LocalProjectsModel/* LocalProjectsModel */.h.instance.detectAllProjectRuntimes();
            // Get projects (detection runs in background, will update via events)
            const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjectsWithRuntime();
            console.log('🔵 Projects loaded, triggering runtime detection for:', projects.length);
            setRealProjects(projects.map(mapProjectToLauncherData));
        };
        loadProjects();
    }, []);
    // Subscribe to project list changes
    (0,useEventListener/* useEventListener */.M)(LocalProjectsModel/* LocalProjectsModel */.h.instance, 'myProjectsChanged', () => {
        console.log('🔔 Projects list changed, updating dashboard with runtime detection');
        const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjectsWithRuntime();
        setRealProjects(projects.map(mapProjectToLauncherData));
    });
    // Subscribe to runtime detection completion to update UI
    (0,useEventListener/* useEventListener */.M)(LocalProjectsModel/* LocalProjectsModel */.h.instance, 'runtimeDetectionComplete', (projectPath, runtimeInfo) => {
        console.log('🎯 Runtime detection complete for:', projectPath, runtimeInfo);
        const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjectsWithRuntime();
        setRealProjects(projects.map(mapProjectToLauncherData));
    });
    const handleCreateProject = (0,external_react_.useCallback)(() => {
        setIsCreateModalVisible(true);
    }, []);
    const handleChooseLocation = (0,external_react_.useCallback)(async () => {
        try {
            const direntry = await src.filesystem.openDialog({
                allowCreateDirectory: true
            });
            return direntry || null;
        }
        catch (error) {
            console.error('Failed to choose location:', error);
            return null;
        }
    }, []);
    const handleCreateProjectConfirm = (0,external_react_.useCallback)(async (name, location) => {
        setIsCreateModalVisible(false);
        try {
            const path = src.filesystem.makeUniquePath(src.filesystem.join(location, name));
            const activityId = 'creating-project';
            ToastLayer.ToastLayer.showActivity('Creating new project', activityId);
            LocalProjectsModel/* LocalProjectsModel */.h.instance.newProject((project) => {
                ToastLayer.ToastLayer.hideActivity(activityId);
                if (!project) {
                    ToastLayer.ToastLayer.showError('Could not create project');
                    return;
                }
                // Navigate to editor with the newly created project
                props.route.router.route({ to: 'editor', project });
            }, { name, path, projectTemplate: '' });
        }
        catch (error) {
            console.error('Failed to create project:', error);
            ToastLayer.ToastLayer.showError('Failed to create project');
        }
    }, [props.route]);
    const handleCreateModalClose = (0,external_react_.useCallback)(() => {
        setIsCreateModalVisible(false);
    }, []);
    const handleOpenProject = (0,external_react_.useCallback)(async () => {
        console.log('🔵 [handleOpenProject] Starting...');
        try {
            console.log('🔵 [handleOpenProject] Opening file dialog...');
            const direntry = await src.filesystem.openDialog({
                allowCreateDirectory: false
            });
            console.log('🔵 [handleOpenProject] Selected folder:', direntry);
            if (!direntry) {
                console.log('🔵 [handleOpenProject] User cancelled');
                return;
            }
            // Check if this project is already in the list
            const existingProjects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
            const isExisting = existingProjects.some((p) => p.retainedProjectDirectory === direntry);
            // If project is new, check for legacy runtime before opening
            if (!isExisting) {
                console.log('🔵 [handleOpenProject] New project detected, checking runtime...');
                const activityId = 'checking-compatibility';
                ToastLayer.ToastLayer.showActivity('Checking project compatibility...', activityId);
                try {
                    const runtimeInfo = await (0,ProjectScanner/* detectRuntimeVersion */.Cb)(direntry);
                    ToastLayer.ToastLayer.hideActivity(activityId);
                    console.log('🔵 [handleOpenProject] Runtime detected:', runtimeInfo);
                    // If legacy or unknown, show warning dialog
                    if (runtimeInfo.version === 'react17' || runtimeInfo.version === 'unknown') {
                        const projectName = src.filesystem.basename(direntry);
                        // Show legacy project warning dialog
                        const userChoice = await new Promise((resolve) => {
                            const confirmed = confirm(`⚠️  Legacy Project Detected\n\n` +
                                `This project "${projectName}" was created with an earlier version of Noodl (React 17).\n\n` +
                                `OpenNoodl uses React 19, which requires migrating your project to ensure compatibility.\n\n` +
                                `What would you like to do?\n\n` +
                                `OK - Migrate Project (Recommended)\n` +
                                `Cancel - View options`);
                            if (confirmed) {
                                resolve('migrate');
                            }
                            else {
                                // Show second dialog for Read-Only or Cancel
                                const openReadOnly = confirm(`Would you like to open this project in Read-Only mode?\n\n` +
                                    `You can inspect the project safely without making changes.\n\n` +
                                    `OK - Open Read-Only\n` +
                                    `Cancel - Return to launcher`);
                                if (openReadOnly) {
                                    resolve('readonly');
                                }
                                else {
                                    resolve('cancel');
                                }
                            }
                        });
                        console.log('🔵 [handleOpenProject] User choice:', userChoice);
                        if (userChoice === 'cancel') {
                            console.log('🔵 [handleOpenProject] User cancelled');
                            return;
                        }
                        if (userChoice === 'migrate') {
                            // Launch migration wizard
                            tracker.tracker.track('Legacy Project Migration Started from Open', {
                                projectName
                            });
                            DialogLayerModel.instance.showDialog((close) => external_react_default().createElement(MigrationWizard, {
                                sourcePath: direntry,
                                projectName,
                                onComplete: async (targetPath) => {
                                    close();
                                    const migrateActivityId = 'opening-migrated';
                                    ToastLayer.ToastLayer.showActivity('Opening migrated project', migrateActivityId);
                                    try {
                                        // Add migrated project and open it
                                        const migratedProject = await LocalProjectsModel/* LocalProjectsModel */.h.instance.openProjectFromFolder(targetPath);
                                        if (!migratedProject.name) {
                                            migratedProject.name = projectName + ' (React 19)';
                                        }
                                        // Refresh and detect runtimes
                                        await LocalProjectsModel/* LocalProjectsModel */.h.instance.fetch();
                                        await LocalProjectsModel/* LocalProjectsModel */.h.instance.detectProjectRuntime(targetPath);
                                        LocalProjectsModel/* LocalProjectsModel */.h.instance.detectAllProjectRuntimes();
                                        const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
                                        const projectEntry = projects.find((p) => p.id === migratedProject.id);
                                        if (projectEntry) {
                                            const loaded = await LocalProjectsModel/* LocalProjectsModel */.h.instance.loadProject(projectEntry);
                                            ToastLayer.ToastLayer.hideActivity(migrateActivityId);
                                            if (loaded) {
                                                ToastLayer.ToastLayer.showSuccess('Project migrated and opened successfully!');
                                                props.route.router.route({ to: 'editor', project: loaded });
                                            }
                                        }
                                    }
                                    catch (error) {
                                        ToastLayer.ToastLayer.hideActivity(migrateActivityId);
                                        ToastLayer.ToastLayer.showError('Could not open migrated project');
                                        console.error(error);
                                    }
                                },
                                onCancel: () => {
                                    close();
                                }
                            }), {
                                onClose: () => {
                                    LocalProjectsModel/* LocalProjectsModel */.h.instance.fetch();
                                }
                            });
                            return;
                        }
                        // If read-only, continue to open normally (will add to list with legacy badge)
                        tracker.tracker.track('Legacy Project Opened Read-Only from Open', {
                            projectName
                        });
                        // CRITICAL: Open the project in read-only mode
                        const readOnlyActivityId = 'opening-project-readonly';
                        ToastLayer.ToastLayer.showActivity('Opening project in read-only mode', readOnlyActivityId);
                        const readOnlyProject = await LocalProjectsModel/* LocalProjectsModel */.h.instance.openProjectFromFolder(direntry);
                        if (!readOnlyProject) {
                            ToastLayer.ToastLayer.hideActivity(readOnlyActivityId);
                            ToastLayer.ToastLayer.showError('Could not open project');
                            return;
                        }
                        if (!readOnlyProject.name) {
                            readOnlyProject.name = src.filesystem.basename(direntry);
                        }
                        const readOnlyProjects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
                        const readOnlyProjectEntry = readOnlyProjects.find((p) => p.id === readOnlyProject.id);
                        if (!readOnlyProjectEntry) {
                            ToastLayer.ToastLayer.hideActivity(readOnlyActivityId);
                            ToastLayer.ToastLayer.showError('Could not find project in recent list');
                            return;
                        }
                        const loadedReadOnly = await LocalProjectsModel/* LocalProjectsModel */.h.instance.loadProject(readOnlyProjectEntry);
                        ToastLayer.ToastLayer.hideActivity(readOnlyActivityId);
                        if (!loadedReadOnly) {
                            ToastLayer.ToastLayer.showError('Could not load project');
                            return;
                        }
                        // Show persistent warning toast (stays forever with Infinity default)
                        ToastLayer.ToastLayer.showError('⚠️  READ-ONLY MODE - No changes will be saved to this legacy project');
                        // Route to editor with read-only flag
                        props.route.router.route({ to: 'editor', project: loadedReadOnly, readOnly: true });
                        return; // Exit early - don't continue to normal flow
                    }
                }
                catch (error) {
                    ToastLayer.ToastLayer.hideActivity(activityId);
                    console.error('Failed to detect runtime:', error);
                    // Continue opening anyway if detection fails
                }
            }
            // Proceed with normal opening flow (non-legacy or legacy with migrate choice)
            const activityId = 'opening-project';
            ToastLayer.ToastLayer.showActivity('Opening project', activityId);
            const project = await LocalProjectsModel/* LocalProjectsModel */.h.instance.openProjectFromFolder(direntry);
            if (!project) {
                ToastLayer.ToastLayer.hideActivity(activityId);
                ToastLayer.ToastLayer.showError('Could not open project');
                return;
            }
            if (!project.name) {
                project.name = src.filesystem.basename(direntry);
            }
            const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
            const projectEntry = projects.find((p) => p.id === project.id);
            if (!projectEntry) {
                ToastLayer.ToastLayer.hideActivity(activityId);
                ToastLayer.ToastLayer.showError('Could not find project in recent list');
                console.error('Project was added but not found in list:', project.id);
                return;
            }
            const loaded = await LocalProjectsModel/* LocalProjectsModel */.h.instance.loadProject(projectEntry);
            ToastLayer.ToastLayer.hideActivity(activityId);
            if (!loaded) {
                ToastLayer.ToastLayer.showError('Could not load project');
            }
            else {
                props.route.router.route({ to: 'editor', project: loaded });
            }
        }
        catch (error) {
            ToastLayer.ToastLayer.hideActivity('opening-project');
            console.error('Failed to open project:', error);
            ToastLayer.ToastLayer.showError('Could not open project');
        }
    }, [props.route]);
    const handleLaunchProject = (0,external_react_.useCallback)(async (projectId) => {
        const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
        const project = projects.find((p) => p.id === projectId);
        if (!project)
            return;
        const activityId = 'launching-project';
        ToastLayer.ToastLayer.showActivity('Opening project', activityId);
        try {
            const loaded = await LocalProjectsModel/* LocalProjectsModel */.h.instance.loadProject(project);
            ToastLayer.ToastLayer.hideActivity(activityId);
            if (!loaded) {
                ToastLayer.ToastLayer.showError('Could not load project');
            }
            else {
                // Navigate to editor with the loaded project
                props.route.router.route({ to: 'editor', project: loaded });
            }
        }
        catch (error) {
            ToastLayer.ToastLayer.hideActivity(activityId);
            console.error('Failed to launch project:', error);
            ToastLayer.ToastLayer.showError('Could not load project');
        }
    }, [props.route]);
    const handleOpenProjectFolder = (0,external_react_.useCallback)(async (projectId) => {
        const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
        const project = projects.find((p) => p.id === projectId);
        if (!project || !project.retainedProjectDirectory) {
            ToastLayer.ToastLayer.showError('Project folder not found');
            return;
        }
        try {
            external_electron_.shell.showItemInFolder(project.retainedProjectDirectory);
        }
        catch (error) {
            console.error('Failed to open project folder:', error);
            ToastLayer.ToastLayer.showError('Could not open project folder');
        }
    }, []);
    const handleDeleteProject = (0,external_react_.useCallback)((projectId) => {
        const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
        const project = projects.find((p) => p.id === projectId);
        if (!project)
            return;
        // Confirm deletion
        if (confirm(`Remove project "${project.name}" from the list?\n\nNote: The project folder will remain on disk and can be opened again later.`)) {
            LocalProjectsModel/* LocalProjectsModel */.h.instance.removeProject(projectId);
            ToastLayer.ToastLayer.showSuccess('Project removed from list');
        }
    }, []);
    /**
     * Handle "Migrate Project" button click - opens the migration wizard
     */
    const handleMigrateProject = (0,external_react_.useCallback)((projectId) => {
        const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
        const project = projects.find((p) => p.id === projectId);
        if (!project || !project.retainedProjectDirectory) {
            ToastLayer.ToastLayer.showError('Cannot migrate project: path not found');
            return;
        }
        const projectPath = project.retainedProjectDirectory;
        // Show the migration wizard as a dialog
        DialogLayerModel.instance.showDialog((close) => external_react_default().createElement(MigrationWizard, {
            sourcePath: projectPath,
            projectName: project.name,
            onComplete: async (targetPath) => {
                close();
                // Clear runtime cache for the source project
                LocalProjectsModel/* LocalProjectsModel */.h.instance.clearRuntimeCache(projectPath);
                // Show activity indicator
                const activityId = 'adding-migrated-project';
                ToastLayer.ToastLayer.showActivity('Adding migrated project to list', activityId);
                try {
                    // Add the migrated project to the projects list
                    const migratedProject = await LocalProjectsModel/* LocalProjectsModel */.h.instance.openProjectFromFolder(targetPath);
                    if (!migratedProject.name) {
                        migratedProject.name = project.name + ' (React 19)';
                    }
                    // Refresh the projects list to show both projects
                    await LocalProjectsModel/* LocalProjectsModel */.h.instance.fetch();
                    // Trigger runtime detection for both projects to update UI immediately
                    await LocalProjectsModel/* LocalProjectsModel */.h.instance.detectProjectRuntime(projectPath);
                    await LocalProjectsModel/* LocalProjectsModel */.h.instance.detectProjectRuntime(targetPath);
                    // Force a full re-detection to update the UI with correct runtime info
                    LocalProjectsModel/* LocalProjectsModel */.h.instance.detectAllProjectRuntimes();
                    ToastLayer.ToastLayer.hideActivity(activityId);
                    // Ask user if they want to archive the original
                    const shouldArchive = confirm(`Migration successful!\n\n` +
                        `Would you like to move the original project to a "Legacy Projects" folder?\n\n` +
                        `The original will be preserved but organized separately. You can access it anytime from the Legacy Projects category.`);
                    if (shouldArchive) {
                        // Get or create "Legacy Projects" folder
                        let legacyFolder = ProjectOrganizationService.instance
                            .getFolders()
                            .find((f) => f.name === 'Legacy Projects');
                        if (!legacyFolder) {
                            legacyFolder = ProjectOrganizationService.instance.createFolder('Legacy Projects');
                        }
                        // Move original project to Legacy folder
                        ProjectOrganizationService.instance.moveProjectToFolder(projectPath, legacyFolder.id);
                        ToastLayer.ToastLayer.showSuccess(`"${migratedProject.name}" is ready! Original moved to Legacy Projects folder.`);
                        tracker.tracker.track('Legacy Project Archived', {
                            projectName: project.name
                        });
                    }
                    else {
                        ToastLayer.ToastLayer.showSuccess(`"${migratedProject.name}" is now in your projects list!`);
                    }
                    // Stay in launcher - user can now see both projects and choose which to open
                    tracker.tracker.track('Migration Completed', {
                        projectName: project.name,
                        archivedOriginal: shouldArchive
                    });
                }
                catch (error) {
                    ToastLayer.ToastLayer.hideActivity(activityId);
                    ToastLayer.ToastLayer.showError('Project migrated but could not be added to list. Try opening it manually.');
                    console.error('Failed to add migrated project:', error);
                    // Refresh project list anyway
                    LocalProjectsModel/* LocalProjectsModel */.h.instance.fetch();
                }
            },
            onCancel: () => {
                close();
            }
        }), {
            onClose: () => {
                // Refresh project list when dialog closes
                LocalProjectsModel/* LocalProjectsModel */.h.instance.fetch();
            }
        });
        tracker.tracker.track('Migration Wizard Opened', {
            projectName: project.name
        });
    }, [props.route]);
    /**
     * Handle "Open Read-Only" button click - opens legacy project without migration
     */
    const handleOpenReadOnly = (0,external_react_.useCallback)(async (projectId) => {
        const projects = LocalProjectsModel/* LocalProjectsModel */.h.instance.getProjects();
        const project = projects.find((p) => p.id === projectId);
        if (!project)
            return;
        const activityId = 'opening-project-readonly';
        ToastLayer.ToastLayer.showActivity('Opening project in read-only mode', activityId);
        try {
            const loaded = await LocalProjectsModel/* LocalProjectsModel */.h.instance.loadProject(project);
            ToastLayer.ToastLayer.hideActivity(activityId);
            if (!loaded) {
                ToastLayer.ToastLayer.showError("Couldn't load project.");
                return;
            }
            tracker.tracker.track('Legacy Project Opened Read-Only', {
                projectName: project.name
            });
            // Show persistent warning about read-only mode (stays forever with Infinity default)
            ToastLayer.ToastLayer.showError('⚠️  READ-ONLY MODE - No changes will be saved to this legacy project');
            // Open the project in read-only mode
            props.route.router.route({ to: 'editor', project: loaded, readOnly: true });
        }
        catch (error) {
            ToastLayer.ToastLayer.hideActivity(activityId);
            ToastLayer.ToastLayer.showError('Could not open project');
            console.error('Failed to open legacy project:', error);
        }
    }, [props.route]);
    return (external_react_default().createElement((external_react_default()).Fragment, null,
        external_react_default().createElement(Launcher, { projects: realProjects, onCreateProject: handleCreateProject, onOpenProject: handleOpenProject, onLaunchProject: handleLaunchProject, onOpenProjectFolder: handleOpenProjectFolder, onDeleteProject: handleDeleteProject, onMigrateProject: handleMigrateProject, onOpenReadOnly: handleOpenReadOnly, projectOrganizationService: ProjectOrganizationService.instance, githubUser: githubUser, githubIsAuthenticated: githubIsAuthenticated, githubIsConnecting: githubIsConnecting, onGitHubConnect: handleGitHubConnect, onGitHubDisconnect: handleGitHubDisconnect, githubRepos: githubRepos, onCloneRepo: handleCloneRepo }),
        external_react_default().createElement(CreateProjectModal, { isVisible: isCreateModalVisible, onClose: handleCreateModalClose, onConfirm: handleCreateProjectConfirm, onChooseLocation: handleChooseLocation })));
}

;// ./src/editor/src/pages/ProjectsPage/index.ts


// EXTERNAL MODULE: ../../node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[4].use[1]!../../node_modules/sass-loader/dist/cjs.js!./src/editor/src/views/DialogLayer/DialogLayerContainer.module.scss
var DialogLayerContainer_module = __webpack_require__(2680);
;// ./src/editor/src/views/DialogLayer/DialogLayerContainer.module.scss

      
      
      
      
      
      
      
      
      

var DialogLayerContainer_module_options = {};

DialogLayerContainer_module_options.styleTagTransform = (styleTagTransform_default());
DialogLayerContainer_module_options.setAttributes = (setAttributesWithoutAttributes_default());

      DialogLayerContainer_module_options.insert = insertBySelector_default().bind(null, "head");
    
DialogLayerContainer_module_options.domAPI = (styleDomAPI_default());
DialogLayerContainer_module_options.insertStyleElement = (insertStyleElement_default());

var DialogLayerContainer_module_update = injectStylesIntoStyleTag_default()(DialogLayerContainer_module/* default */.A, DialogLayerContainer_module_options);




       /* harmony default export */ const DialogLayer_DialogLayerContainer_module = (DialogLayerContainer_module/* default */.A && DialogLayerContainer_module/* default */.A.locals ? DialogLayerContainer_module/* default */.A.locals : undefined);

;// ./src/editor/src/views/DialogLayer/DialogLayerContainer.tsx




function DialogLayerContainer() {
    const { dialogs } = (0,useModel/* useModernModel */.e)(DialogLayerModel.instance);
    return (external_react_default().createElement("div", { className: DialogLayer_DialogLayerContainer_module['Root'], style: { pointerEvents: dialogs.length ? 'auto' : 'none' } }, dialogs.map(({ id, slot: Component }) => (external_react_default().createElement(Component, { key: id })))));
}
/*
<ConfirmDialog
  title="Your Free Trial  Expries in 7 Days"
  text="Thank you for trying our platform! Your 30-day free trial will expire in 7 days. After that you won’t have access to paid features. Please consider upgrading to a paid plan."
  confirmText="Manage plan"
/>
*/

;// ./src/editor/src/views/DialogLayer/index.ts


;// ./src/editor/src/router.tsx
















// Store roots globally for HMR reuse
let toastLayerRoot = null;
let dialogLayerRoot = null;
function createToastLayer() {
    const toastLayer = document.createElement('div');
    toastLayer.classList.add('toast-layer');
    $('body').append(toastLayer);
    toastLayerRoot = (0,client.createRoot)(toastLayer);
    toastLayerRoot.render(external_react_default().createElement(ToastLayerContainer));
    if (false) // removed by dead control flow
{}
}
function createDialogLayer() {
    // ---
    // Add support for the BaseDialog, since that is using React Portals this have
    // to be added to the DOM now!
    const dialogLayerPortalTarget = document.createElement('div');
    dialogLayerPortalTarget.classList.add('dialog-layer-portal-target');
    $('body').append(dialogLayerPortalTarget);
    // ---
    // Add the Dialog Layer
    const dialogLayer = document.createElement('div');
    dialogLayer.classList.add('dialog-layer');
    $('body').append(dialogLayer);
    dialogLayerRoot = (0,client.createRoot)(dialogLayer);
    dialogLayerRoot.render(external_react_default().createElement(DialogLayerContainer));
    if (false) // removed by dead control flow
{}
}
class Router extends (external_react_default()).Component {
    constructor(props) {
        super(props);
        //start at projects page
        this.state = {
            routeName: 'projects',
            route: ProjectsPage,
            routeArgs: { route: new AppRoute(this) }
        };
        console.log(`
  _   _                    _  _
 | \\ | |                  | || |
 |  \\| |  ___    ___    __| || |
 | . \` | / _ \\  / _ \\  / _\` || |
 | |\\  || (_) || (_) || (_| || |
 |_| \\_| \\___/  \\___/  \\__,_||_|

      version: ${src.platform.getFullVersion() || src.platform.getVersion()}

`);
        // Initialise models
        lessontemplatesmodel_default().instance.fetch();
        EventDispatcher.EventDispatcher.instance.on('viewer-refresh', () => {
            external_electron_.ipcRenderer.send('viewer-refresh');
        }, null);
        (popuplayer_default()).instance = new (popuplayer_default())();
        $('body').append(popuplayer_default().instance.render());
        createDialogLayer();
        createToastLayer();
        //close the viewer. Viewer is normally closed at this point, but can be open if we refresh the editor from the dev tools
        external_electron_.ipcRenderer.send('viewer-attach', {});
        if (false) // removed by dead control flow
{}
    }
    route(args) {
        if (!args)
            return;
        // console.log(`route, from: ${this._route}, to: ${args.to}`);
        if (this._route == args.to) {
            return;
        }
        this._route = args.to;
        // TODO: Store route specific data
        const route = new AppRoute(this);
        //Set the global singleton here (and only here) to load the active project for this route
        if (projectmodel.ProjectModel.instance && projectmodel.ProjectModel.instance !== args.project) {
            //new or no project, dispose old one
            projectmodel.ProjectModel.instance.dispose();
            AiAssistant/* AiAssistantModel */.g.instance.resetContexts();
            // HACK: Allow all react components to unmount un unregister the effectsbefore we delete the ProjectModel.
            setTimeout(() => {
                projectmodel.ProjectModel.instance = undefined;
            }, 0);
        }
        if (args.project && projectmodel.ProjectModel.instance !== args.project) {
            //set new project
            projectmodel.ProjectModel.instance = args.project;
            // Set read-only mode if specified (for legacy projects)
            if (args.readOnly !== undefined) {
                args.project._isReadOnly = args.readOnly;
            }
        }
        // Routes
        if (args.to === 'editor') {
            this.setState({
                route: EditorPage,
                routeArgs: { route, readOnly: args.readOnly }
            });
        }
        else if (args.to === 'projects') {
            this.setState({
                route: ProjectsPage,
                routeArgs: { route, from: args.from }
            });
        }
    }
    render() {
        const Route = this.state.route;
        return external_react_default().createElement((external_react_default()).Fragment, null, Route ? external_react_default().createElement(Route, { ...this.state.routeArgs }) : null);
    }
}

;// ./src/editor/index.ts








//Design tokens for later
// import '../../../noodl-core-ui/src/styles/custom-properties/animations.css';
// import '../../../noodl-core-ui/src/styles/custom-properties/fonts.css';
// import '../../../noodl-core-ui/src/styles/custom-properties/colors.css';





// Build canary: Verify fresh code is loading
console.log('🔥🔥 BUILD TIMESTAMP:', new Date().toISOString());
external_electron_.ipcRenderer.on('open-noodl-uri', async (event, uri) => {
    if (uri.startsWith('noodl:import/http')) {
        console.log('import: ', uri);
        EventDispatcher.EventDispatcher.instance.emit('importFromUrl', uri.substring('noodl:import/'.length));
    }
});
external_electron_.ipcRenderer.on('import-projectmetadata', (event, data) => {
    projectmodel.ProjectModel.instance.mergeMetadata(data);
});
function setupViewerIpc() {
    external_electron_.ipcRenderer.on('viewer-refreshed', () => {
        EventDispatcher.EventDispatcher.instance.emit('viewer-refreshed');
    });
    external_electron_.ipcRenderer.on('viewer-closed', () => {
        EventDispatcher.EventDispatcher.instance.emit('viewer-closed');
    });
}
window.addEventListener('DOMContentLoaded', () => {
    // Register node adapters
    __webpack_require__(97478);
    // Disable context menu
    $('body').on('contextmenu', function () {
        return false;
    });
    external_electron_.ipcRenderer.on('showAutoUpdatePopup', () => {
        //@ts-expect-error
        window._hasNewAutoUpdateAvailable = true;
    });
    setupViewerIpc();
    external_electron_.ipcRenderer.on('window-focused', () => {
        EventDispatcher.EventDispatcher.instance.notifyListeners('window-focused');
    });
    document.addEventListener('mousedown', () => {
        renderer.getCurrentWindow().focus();
    });
    // Activity detector
    let lastActiveTime = +new Date();
    document.addEventListener('mousedown', function (evt) {
        const now = +new Date();
        if (now > lastActiveTime + 10 * 60 * 1000) {
            // Wake up after 10 minutes of inactivity
            EventDispatcher.EventDispatcher.instance.notifyListeners('wakeup');
        }
        lastActiveTime = now;
    });
    EventDispatcher.EventDispatcher.instance.on('ProjectModel.instanceWillChange', () => {
        //@ts-expect-error
        window.NodeLibraryData = undefined;
        nodelibrary/* NodeLibrary */.m.instance.reload();
    }, null);
    // Create the main element
    const rootElement = document.getElementById('root');
    (0,client.createRoot)(rootElement).render(external_react_default().createElement(Router, { uri: renderer.process.env.noodlURI }));
});

})();

module.exports = __webpack_exports__;
/******/ })()
;
//# sourceMappingURL=index.bundle.js.map